repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
darth-llamah/a510_almoststock | sound/soc/omap/mcpdm.c | 379 | 10874 | /*
* mcpdm.c -- McPDM interface driver
*
* Author: Jorge Eduardo Candelaria <x0107209@ti.com>
* Copyright (C) 2009 - Texas Instruments, 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.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/wait.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/irq.h>
#include "mcpdm.h"
static struct omap_mcpdm *mcpdm;
static inline void omap_mcpdm_write(u16 reg, u32 val)
{
__raw_writel(val, mcpdm->io_base + reg);
}
static inline int omap_mcpdm_read(u16 reg)
{
return __raw_readl(mcpdm->io_base + reg);
}
static void omap_mcpdm_reg_dump(void)
{
dev_dbg(mcpdm->dev, "***********************\n");
dev_dbg(mcpdm->dev, "IRQSTATUS_RAW: 0x%04x\n",
omap_mcpdm_read(MCPDM_IRQSTATUS_RAW));
dev_dbg(mcpdm->dev, "IRQSTATUS: 0x%04x\n",
omap_mcpdm_read(MCPDM_IRQSTATUS));
dev_dbg(mcpdm->dev, "IRQENABLE_SET: 0x%04x\n",
omap_mcpdm_read(MCPDM_IRQENABLE_SET));
dev_dbg(mcpdm->dev, "IRQENABLE_CLR: 0x%04x\n",
omap_mcpdm_read(MCPDM_IRQENABLE_CLR));
dev_dbg(mcpdm->dev, "IRQWAKE_EN: 0x%04x\n",
omap_mcpdm_read(MCPDM_IRQWAKE_EN));
dev_dbg(mcpdm->dev, "DMAENABLE_SET: 0x%04x\n",
omap_mcpdm_read(MCPDM_DMAENABLE_SET));
dev_dbg(mcpdm->dev, "DMAENABLE_CLR: 0x%04x\n",
omap_mcpdm_read(MCPDM_DMAENABLE_CLR));
dev_dbg(mcpdm->dev, "DMAWAKEEN: 0x%04x\n",
omap_mcpdm_read(MCPDM_DMAWAKEEN));
dev_dbg(mcpdm->dev, "CTRL: 0x%04x\n",
omap_mcpdm_read(MCPDM_CTRL));
dev_dbg(mcpdm->dev, "DN_DATA: 0x%04x\n",
omap_mcpdm_read(MCPDM_DN_DATA));
dev_dbg(mcpdm->dev, "UP_DATA: 0x%04x\n",
omap_mcpdm_read(MCPDM_UP_DATA));
dev_dbg(mcpdm->dev, "FIFO_CTRL_DN: 0x%04x\n",
omap_mcpdm_read(MCPDM_FIFO_CTRL_DN));
dev_dbg(mcpdm->dev, "FIFO_CTRL_UP: 0x%04x\n",
omap_mcpdm_read(MCPDM_FIFO_CTRL_UP));
dev_dbg(mcpdm->dev, "DN_OFFSET: 0x%04x\n",
omap_mcpdm_read(MCPDM_DN_OFFSET));
dev_dbg(mcpdm->dev, "***********************\n");
}
/*
* Takes the McPDM module in and out of reset state.
* Uplink and downlink can be reset individually.
*/
static void omap_mcpdm_reset_capture(int reset)
{
int ctrl = omap_mcpdm_read(MCPDM_CTRL);
if (reset)
ctrl |= SW_UP_RST;
else
ctrl &= ~SW_UP_RST;
omap_mcpdm_write(MCPDM_CTRL, ctrl);
}
static void omap_mcpdm_reset_playback(int reset)
{
int ctrl = omap_mcpdm_read(MCPDM_CTRL);
if (reset)
ctrl |= SW_DN_RST;
else
ctrl &= ~SW_DN_RST;
omap_mcpdm_write(MCPDM_CTRL, ctrl);
}
/*
* Enables the transfer through the PDM interface to/from the Phoenix
* codec by enabling the corresponding UP or DN channels.
*/
void omap_mcpdm_start(int stream)
{
int ctrl = omap_mcpdm_read(MCPDM_CTRL);
if (stream)
ctrl |= mcpdm->up_channels;
else
ctrl |= mcpdm->dn_channels;
omap_mcpdm_write(MCPDM_CTRL, ctrl);
}
/*
* Disables the transfer through the PDM interface to/from the Phoenix
* codec by disabling the corresponding UP or DN channels.
*/
void omap_mcpdm_stop(int stream)
{
int ctrl = omap_mcpdm_read(MCPDM_CTRL);
if (stream)
ctrl &= ~mcpdm->up_channels;
else
ctrl &= ~mcpdm->dn_channels;
omap_mcpdm_write(MCPDM_CTRL, ctrl);
}
/*
* Configures McPDM uplink for audio recording.
* This function should be called before omap_mcpdm_start.
*/
int omap_mcpdm_capture_open(struct omap_mcpdm_link *uplink)
{
int irq_mask = 0;
int ctrl;
if (!uplink)
return -EINVAL;
mcpdm->uplink = uplink;
/* Enable irq request generation */
irq_mask |= uplink->irq_mask & MCPDM_UPLINK_IRQ_MASK;
omap_mcpdm_write(MCPDM_IRQENABLE_SET, irq_mask);
/* Configure uplink threshold */
if (uplink->threshold > UP_THRES_MAX)
uplink->threshold = UP_THRES_MAX;
omap_mcpdm_write(MCPDM_FIFO_CTRL_UP, uplink->threshold);
/* Configure DMA controller */
omap_mcpdm_write(MCPDM_DMAENABLE_SET, DMA_UP_ENABLE);
/* Set pdm out format */
ctrl = omap_mcpdm_read(MCPDM_CTRL);
ctrl &= ~PDMOUTFORMAT;
ctrl |= uplink->format & PDMOUTFORMAT;
/* Uplink channels */
mcpdm->up_channels = uplink->channels & (PDM_UP_MASK | PDM_STATUS_MASK);
omap_mcpdm_write(MCPDM_CTRL, ctrl);
return 0;
}
/*
* Configures McPDM downlink for audio playback.
* This function should be called before omap_mcpdm_start.
*/
int omap_mcpdm_playback_open(struct omap_mcpdm_link *downlink)
{
int irq_mask = 0;
int ctrl;
if (!downlink)
return -EINVAL;
mcpdm->downlink = downlink;
/* Enable irq request generation */
irq_mask |= downlink->irq_mask & MCPDM_DOWNLINK_IRQ_MASK;
omap_mcpdm_write(MCPDM_IRQENABLE_SET, irq_mask);
/* Configure uplink threshold */
if (downlink->threshold > DN_THRES_MAX)
downlink->threshold = DN_THRES_MAX;
omap_mcpdm_write(MCPDM_FIFO_CTRL_DN, downlink->threshold);
/* Enable DMA request generation */
omap_mcpdm_write(MCPDM_DMAENABLE_SET, DMA_DN_ENABLE);
/* Set pdm out format */
ctrl = omap_mcpdm_read(MCPDM_CTRL);
ctrl &= ~PDMOUTFORMAT;
ctrl |= downlink->format & PDMOUTFORMAT;
/* Downlink channels */
mcpdm->dn_channels = downlink->channels & (PDM_DN_MASK | PDM_CMD_MASK);
omap_mcpdm_write(MCPDM_CTRL, ctrl);
return 0;
}
/*
* Cleans McPDM uplink configuration.
* This function should be called when the stream is closed.
*/
int omap_mcpdm_capture_close(struct omap_mcpdm_link *uplink)
{
int irq_mask = 0;
if (!uplink)
return -EINVAL;
/* Disable irq request generation */
irq_mask |= uplink->irq_mask & MCPDM_UPLINK_IRQ_MASK;
omap_mcpdm_write(MCPDM_IRQENABLE_CLR, irq_mask);
/* Disable DMA request generation */
omap_mcpdm_write(MCPDM_DMAENABLE_CLR, DMA_UP_ENABLE);
/* Clear Downlink channels */
mcpdm->up_channels = 0;
mcpdm->uplink = NULL;
return 0;
}
/*
* Cleans McPDM downlink configuration.
* This function should be called when the stream is closed.
*/
int omap_mcpdm_playback_close(struct omap_mcpdm_link *downlink)
{
int irq_mask = 0;
if (!downlink)
return -EINVAL;
/* Disable irq request generation */
irq_mask |= downlink->irq_mask & MCPDM_DOWNLINK_IRQ_MASK;
omap_mcpdm_write(MCPDM_IRQENABLE_CLR, irq_mask);
/* Disable DMA request generation */
omap_mcpdm_write(MCPDM_DMAENABLE_CLR, DMA_DN_ENABLE);
/* clear Downlink channels */
mcpdm->dn_channels = 0;
mcpdm->downlink = NULL;
return 0;
}
static irqreturn_t omap_mcpdm_irq_handler(int irq, void *dev_id)
{
struct omap_mcpdm *mcpdm_irq = dev_id;
int irq_status;
irq_status = omap_mcpdm_read(MCPDM_IRQSTATUS);
/* Acknowledge irq event */
omap_mcpdm_write(MCPDM_IRQSTATUS, irq_status);
if (irq & MCPDM_DN_IRQ_FULL) {
dev_err(mcpdm_irq->dev, "DN FIFO error %x\n", irq_status);
omap_mcpdm_reset_playback(1);
omap_mcpdm_playback_open(mcpdm_irq->downlink);
omap_mcpdm_reset_playback(0);
}
if (irq & MCPDM_DN_IRQ_EMPTY) {
dev_err(mcpdm_irq->dev, "DN FIFO error %x\n", irq_status);
omap_mcpdm_reset_playback(1);
omap_mcpdm_playback_open(mcpdm_irq->downlink);
omap_mcpdm_reset_playback(0);
}
if (irq & MCPDM_DN_IRQ) {
dev_dbg(mcpdm_irq->dev, "DN write request\n");
}
if (irq & MCPDM_UP_IRQ_FULL) {
dev_err(mcpdm_irq->dev, "UP FIFO error %x\n", irq_status);
omap_mcpdm_reset_capture(1);
omap_mcpdm_capture_open(mcpdm_irq->uplink);
omap_mcpdm_reset_capture(0);
}
if (irq & MCPDM_UP_IRQ_EMPTY) {
dev_err(mcpdm_irq->dev, "UP FIFO error %x\n", irq_status);
omap_mcpdm_reset_capture(1);
omap_mcpdm_capture_open(mcpdm_irq->uplink);
omap_mcpdm_reset_capture(0);
}
if (irq & MCPDM_UP_IRQ) {
dev_dbg(mcpdm_irq->dev, "UP write request\n");
}
return IRQ_HANDLED;
}
int omap_mcpdm_request(void)
{
int ret;
clk_enable(mcpdm->clk);
spin_lock(&mcpdm->lock);
if (!mcpdm->free) {
dev_err(mcpdm->dev, "McPDM interface is in use\n");
spin_unlock(&mcpdm->lock);
ret = -EBUSY;
goto err;
}
mcpdm->free = 0;
spin_unlock(&mcpdm->lock);
/* Disable lines while request is ongoing */
omap_mcpdm_write(MCPDM_CTRL, 0x00);
ret = request_irq(mcpdm->irq, omap_mcpdm_irq_handler,
0, "McPDM", (void *)mcpdm);
if (ret) {
dev_err(mcpdm->dev, "Request for McPDM IRQ failed\n");
goto err;
}
return 0;
err:
clk_disable(mcpdm->clk);
return ret;
}
void omap_mcpdm_free(void)
{
spin_lock(&mcpdm->lock);
if (mcpdm->free) {
dev_err(mcpdm->dev, "McPDM interface is already free\n");
spin_unlock(&mcpdm->lock);
return;
}
mcpdm->free = 1;
spin_unlock(&mcpdm->lock);
clk_disable(mcpdm->clk);
free_irq(mcpdm->irq, (void *)mcpdm);
}
/* Enable/disable DC offset cancelation for the analog
* headset path (PDM channels 1 and 2).
*/
int omap_mcpdm_set_offset(int offset1, int offset2)
{
int offset;
if ((offset1 > DN_OFST_MAX) || (offset2 > DN_OFST_MAX))
return -EINVAL;
offset = (offset1 << DN_OFST_RX1) | (offset2 << DN_OFST_RX2);
/* offset cancellation for channel 1 */
if (offset1)
offset |= DN_OFST_RX1_EN;
else
offset &= ~DN_OFST_RX1_EN;
/* offset cancellation for channel 2 */
if (offset2)
offset |= DN_OFST_RX2_EN;
else
offset &= ~DN_OFST_RX2_EN;
omap_mcpdm_write(MCPDM_DN_OFFSET, offset);
return 0;
}
int __devinit omap_mcpdm_probe(struct platform_device *pdev)
{
struct resource *res;
int ret = 0;
mcpdm = kzalloc(sizeof(struct omap_mcpdm), GFP_KERNEL);
if (!mcpdm) {
ret = -ENOMEM;
goto exit;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res == NULL) {
dev_err(&pdev->dev, "no resource\n");
goto err_resource;
}
spin_lock_init(&mcpdm->lock);
mcpdm->free = 1;
mcpdm->io_base = ioremap(res->start, resource_size(res));
if (!mcpdm->io_base) {
ret = -ENOMEM;
goto err_resource;
}
mcpdm->irq = platform_get_irq(pdev, 0);
mcpdm->clk = clk_get(&pdev->dev, "pdm_ck");
if (IS_ERR(mcpdm->clk)) {
ret = PTR_ERR(mcpdm->clk);
dev_err(&pdev->dev, "unable to get pdm_ck: %d\n", ret);
goto err_clk;
}
mcpdm->dev = &pdev->dev;
platform_set_drvdata(pdev, mcpdm);
return 0;
err_clk:
iounmap(mcpdm->io_base);
err_resource:
kfree(mcpdm);
exit:
return ret;
}
int omap_mcpdm_remove(struct platform_device *pdev)
{
struct omap_mcpdm *mcpdm_ptr = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
clk_put(mcpdm_ptr->clk);
iounmap(mcpdm_ptr->io_base);
mcpdm_ptr->clk = NULL;
mcpdm_ptr->free = 0;
mcpdm_ptr->dev = NULL;
kfree(mcpdm_ptr);
return 0;
}
| gpl-2.0 |
DJSteve/StreakKernel | sound/oss/sb_mixer.c | 891 | 19704 | /*
* sound/oss/sb_mixer.c
*
* The low level mixer driver for the Sound Blaster compatible cards.
*/
/*
* Copyright (C) by Hannu Savolainen 1993-1997
*
* OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
* Version 2 (June 1991). See the "COPYING" file distributed with this software
* for more info.
*
*
* Thomas Sailer : ioctl code reworked (vmalloc/vfree removed)
* Rolf Fokkens (Dec 20 1998) : Moved ESS stuff into sb_ess.[ch]
* Stanislav Voronyi <stas@esc.kharkov.com> : Support for AWE 3DSE device (Jun 7 1999)
*/
#include "sound_config.h"
#define __SB_MIXER_C__
#include "sb.h"
#include "sb_mixer.h"
#include "sb_ess.h"
#define SBPRO_RECORDING_DEVICES (SOUND_MASK_LINE | SOUND_MASK_MIC | SOUND_MASK_CD)
/* Same as SB Pro, unless I find otherwise */
#define SGNXPRO_RECORDING_DEVICES SBPRO_RECORDING_DEVICES
#define SBPRO_MIXER_DEVICES (SOUND_MASK_SYNTH | SOUND_MASK_PCM | SOUND_MASK_LINE | SOUND_MASK_MIC | \
SOUND_MASK_CD | SOUND_MASK_VOLUME)
/* SG NX Pro has treble and bass settings on the mixer. The 'speaker'
* channel is the COVOX/DisneySoundSource emulation volume control
* on the mixer. It does NOT control speaker volume. Should have own
* mask eventually?
*/
#define SGNXPRO_MIXER_DEVICES (SBPRO_MIXER_DEVICES|SOUND_MASK_BASS| \
SOUND_MASK_TREBLE|SOUND_MASK_SPEAKER )
#define SB16_RECORDING_DEVICES (SOUND_MASK_SYNTH | SOUND_MASK_LINE | SOUND_MASK_MIC | \
SOUND_MASK_CD)
#define SB16_OUTFILTER_DEVICES (SOUND_MASK_LINE | SOUND_MASK_MIC | \
SOUND_MASK_CD)
#define SB16_MIXER_DEVICES (SOUND_MASK_SYNTH | SOUND_MASK_PCM | SOUND_MASK_SPEAKER | SOUND_MASK_LINE | SOUND_MASK_MIC | \
SOUND_MASK_CD | \
SOUND_MASK_IGAIN | SOUND_MASK_OGAIN | \
SOUND_MASK_VOLUME | SOUND_MASK_BASS | SOUND_MASK_TREBLE | \
SOUND_MASK_IMIX)
/* These are the only devices that are working at the moment. Others could
* be added once they are identified and a method is found to control them.
*/
#define ALS007_MIXER_DEVICES (SOUND_MASK_SYNTH | SOUND_MASK_LINE | \
SOUND_MASK_PCM | SOUND_MASK_MIC | \
SOUND_MASK_CD | \
SOUND_MASK_VOLUME)
static mixer_tab sbpro_mix = {
MIX_ENT(SOUND_MIXER_VOLUME, 0x22, 7, 4, 0x22, 3, 4),
MIX_ENT(SOUND_MIXER_BASS, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_TREBLE, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_SYNTH, 0x26, 7, 4, 0x26, 3, 4),
MIX_ENT(SOUND_MIXER_PCM, 0x04, 7, 4, 0x04, 3, 4),
MIX_ENT(SOUND_MIXER_SPEAKER, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE, 0x2e, 7, 4, 0x2e, 3, 4),
MIX_ENT(SOUND_MIXER_MIC, 0x0a, 2, 3, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_CD, 0x28, 7, 4, 0x28, 3, 4),
MIX_ENT(SOUND_MIXER_IMIX, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_ALTPCM, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_RECLEV, 0x00, 0, 0, 0x00, 0, 0)
};
static mixer_tab sb16_mix = {
MIX_ENT(SOUND_MIXER_VOLUME, 0x30, 7, 5, 0x31, 7, 5),
MIX_ENT(SOUND_MIXER_BASS, 0x46, 7, 4, 0x47, 7, 4),
MIX_ENT(SOUND_MIXER_TREBLE, 0x44, 7, 4, 0x45, 7, 4),
MIX_ENT(SOUND_MIXER_SYNTH, 0x34, 7, 5, 0x35, 7, 5),
MIX_ENT(SOUND_MIXER_PCM, 0x32, 7, 5, 0x33, 7, 5),
MIX_ENT(SOUND_MIXER_SPEAKER, 0x3b, 7, 2, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE, 0x38, 7, 5, 0x39, 7, 5),
MIX_ENT(SOUND_MIXER_MIC, 0x3a, 7, 5, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_CD, 0x36, 7, 5, 0x37, 7, 5),
MIX_ENT(SOUND_MIXER_IMIX, 0x3c, 0, 1, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_ALTPCM, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_RECLEV, 0x3f, 7, 2, 0x40, 7, 2), /* Obsolete. Use IGAIN */
MIX_ENT(SOUND_MIXER_IGAIN, 0x3f, 7, 2, 0x40, 7, 2),
MIX_ENT(SOUND_MIXER_OGAIN, 0x41, 7, 2, 0x42, 7, 2)
};
static mixer_tab als007_mix =
{
MIX_ENT(SOUND_MIXER_VOLUME, 0x62, 7, 4, 0x62, 3, 4),
MIX_ENT(SOUND_MIXER_BASS, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_TREBLE, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_SYNTH, 0x66, 7, 4, 0x66, 3, 4),
MIX_ENT(SOUND_MIXER_PCM, 0x64, 7, 4, 0x64, 3, 4),
MIX_ENT(SOUND_MIXER_SPEAKER, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_LINE, 0x6e, 7, 4, 0x6e, 3, 4),
MIX_ENT(SOUND_MIXER_MIC, 0x6a, 2, 3, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_CD, 0x68, 7, 4, 0x68, 3, 4),
MIX_ENT(SOUND_MIXER_IMIX, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_ALTPCM, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_RECLEV, 0x00, 0, 0, 0x00, 0, 0), /* Obsolete. Use IGAIN */
MIX_ENT(SOUND_MIXER_IGAIN, 0x00, 0, 0, 0x00, 0, 0),
MIX_ENT(SOUND_MIXER_OGAIN, 0x00, 0, 0, 0x00, 0, 0)
};
/* SM_GAMES Master volume is lower and PCM & FM volumes
higher than with SB Pro. This improves the
sound quality */
static int smg_default_levels[32] =
{
0x2020, /* Master Volume */
0x4b4b, /* Bass */
0x4b4b, /* Treble */
0x6464, /* FM */
0x6464, /* PCM */
0x4b4b, /* PC Speaker */
0x4b4b, /* Ext Line */
0x0000, /* Mic */
0x4b4b, /* CD */
0x4b4b, /* Recording monitor */
0x4b4b, /* SB PCM */
0x4b4b, /* Recording level */
0x4b4b, /* Input gain */
0x4b4b, /* Output gain */
0x4040, /* Line1 */
0x4040, /* Line2 */
0x1515 /* Line3 */
};
static int sb_default_levels[32] =
{
0x5a5a, /* Master Volume */
0x4b4b, /* Bass */
0x4b4b, /* Treble */
0x4b4b, /* FM */
0x4b4b, /* PCM */
0x4b4b, /* PC Speaker */
0x4b4b, /* Ext Line */
0x1010, /* Mic */
0x4b4b, /* CD */
0x0000, /* Recording monitor */
0x4b4b, /* SB PCM */
0x4b4b, /* Recording level */
0x4b4b, /* Input gain */
0x4b4b, /* Output gain */
0x4040, /* Line1 */
0x4040, /* Line2 */
0x1515 /* Line3 */
};
static unsigned char sb16_recmasks_L[SOUND_MIXER_NRDEVICES] =
{
0x00, /* SOUND_MIXER_VOLUME */
0x00, /* SOUND_MIXER_BASS */
0x00, /* SOUND_MIXER_TREBLE */
0x40, /* SOUND_MIXER_SYNTH */
0x00, /* SOUND_MIXER_PCM */
0x00, /* SOUND_MIXER_SPEAKER */
0x10, /* SOUND_MIXER_LINE */
0x01, /* SOUND_MIXER_MIC */
0x04, /* SOUND_MIXER_CD */
0x00, /* SOUND_MIXER_IMIX */
0x00, /* SOUND_MIXER_ALTPCM */
0x00, /* SOUND_MIXER_RECLEV */
0x00, /* SOUND_MIXER_IGAIN */
0x00 /* SOUND_MIXER_OGAIN */
};
static unsigned char sb16_recmasks_R[SOUND_MIXER_NRDEVICES] =
{
0x00, /* SOUND_MIXER_VOLUME */
0x00, /* SOUND_MIXER_BASS */
0x00, /* SOUND_MIXER_TREBLE */
0x20, /* SOUND_MIXER_SYNTH */
0x00, /* SOUND_MIXER_PCM */
0x00, /* SOUND_MIXER_SPEAKER */
0x08, /* SOUND_MIXER_LINE */
0x01, /* SOUND_MIXER_MIC */
0x02, /* SOUND_MIXER_CD */
0x00, /* SOUND_MIXER_IMIX */
0x00, /* SOUND_MIXER_ALTPCM */
0x00, /* SOUND_MIXER_RECLEV */
0x00, /* SOUND_MIXER_IGAIN */
0x00 /* SOUND_MIXER_OGAIN */
};
static char smw_mix_regs[] = /* Left mixer registers */
{
0x0b, /* SOUND_MIXER_VOLUME */
0x0d, /* SOUND_MIXER_BASS */
0x0d, /* SOUND_MIXER_TREBLE */
0x05, /* SOUND_MIXER_SYNTH */
0x09, /* SOUND_MIXER_PCM */
0x00, /* SOUND_MIXER_SPEAKER */
0x03, /* SOUND_MIXER_LINE */
0x01, /* SOUND_MIXER_MIC */
0x07, /* SOUND_MIXER_CD */
0x00, /* SOUND_MIXER_IMIX */
0x00, /* SOUND_MIXER_ALTPCM */
0x00, /* SOUND_MIXER_RECLEV */
0x00, /* SOUND_MIXER_IGAIN */
0x00, /* SOUND_MIXER_OGAIN */
0x00, /* SOUND_MIXER_LINE1 */
0x00, /* SOUND_MIXER_LINE2 */
0x00 /* SOUND_MIXER_LINE3 */
};
static int sbmixnum = 1;
static void sb_mixer_reset(sb_devc * devc);
void sb_mixer_set_stereo(sb_devc * devc, int mode)
{
sb_chgmixer(devc, OUT_FILTER, STEREO_DAC, (mode ? STEREO_DAC : MONO_DAC));
}
static int detect_mixer(sb_devc * devc)
{
/* Just trust the mixer is there */
return 1;
}
static void change_bits(sb_devc * devc, unsigned char *regval, int dev, int chn, int newval)
{
unsigned char mask;
int shift;
mask = (1 << (*devc->iomap)[dev][chn].nbits) - 1;
newval = (int) ((newval * mask) + 50) / 100; /* Scale */
shift = (*devc->iomap)[dev][chn].bitoffs - (*devc->iomap)[dev][LEFT_CHN].nbits + 1;
*regval &= ~(mask << shift); /* Mask out previous value */
*regval |= (newval & mask) << shift; /* Set the new value */
}
static int sb_mixer_get(sb_devc * devc, int dev)
{
if (!((1 << dev) & devc->supported_devices))
return -EINVAL;
return devc->levels[dev];
}
void smw_mixer_init(sb_devc * devc)
{
int i;
sb_setmixer(devc, 0x00, 0x18); /* Mute unused (Telephone) line */
sb_setmixer(devc, 0x10, 0x38); /* Config register 2 */
devc->supported_devices = 0;
for (i = 0; i < sizeof(smw_mix_regs); i++)
if (smw_mix_regs[i] != 0)
devc->supported_devices |= (1 << i);
devc->supported_rec_devices = devc->supported_devices &
~(SOUND_MASK_BASS | SOUND_MASK_TREBLE | SOUND_MASK_PCM | SOUND_MASK_VOLUME);
sb_mixer_reset(devc);
}
int sb_common_mixer_set(sb_devc * devc, int dev, int left, int right)
{
int regoffs;
unsigned char val;
if ((dev < 0) || (dev >= devc->iomap_sz))
return -EINVAL;
regoffs = (*devc->iomap)[dev][LEFT_CHN].regno;
if (regoffs == 0)
return -EINVAL;
val = sb_getmixer(devc, regoffs);
change_bits(devc, &val, dev, LEFT_CHN, left);
if ((*devc->iomap)[dev][RIGHT_CHN].regno != regoffs) /*
* Change register
*/
{
sb_setmixer(devc, regoffs, val); /*
* Save the old one
*/
regoffs = (*devc->iomap)[dev][RIGHT_CHN].regno;
if (regoffs == 0)
return left | (left << 8); /*
* Just left channel present
*/
val = sb_getmixer(devc, regoffs); /*
* Read the new one
*/
}
change_bits(devc, &val, dev, RIGHT_CHN, right);
sb_setmixer(devc, regoffs, val);
return left | (right << 8);
}
static int smw_mixer_set(sb_devc * devc, int dev, int left, int right)
{
int reg, val;
switch (dev)
{
case SOUND_MIXER_VOLUME:
sb_setmixer(devc, 0x0b, 96 - (96 * left / 100)); /* 96=mute, 0=max */
sb_setmixer(devc, 0x0c, 96 - (96 * right / 100));
break;
case SOUND_MIXER_BASS:
case SOUND_MIXER_TREBLE:
devc->levels[dev] = left | (right << 8);
/* Set left bass and treble values */
val = ((devc->levels[SOUND_MIXER_TREBLE] & 0xff) * 16 / (unsigned) 100) << 4;
val |= ((devc->levels[SOUND_MIXER_BASS] & 0xff) * 16 / (unsigned) 100) & 0x0f;
sb_setmixer(devc, 0x0d, val);
/* Set right bass and treble values */
val = (((devc->levels[SOUND_MIXER_TREBLE] >> 8) & 0xff) * 16 / (unsigned) 100) << 4;
val |= (((devc->levels[SOUND_MIXER_BASS] >> 8) & 0xff) * 16 / (unsigned) 100) & 0x0f;
sb_setmixer(devc, 0x0e, val);
break;
default:
/* bounds check */
if (dev < 0 || dev >= ARRAY_SIZE(smw_mix_regs))
return -EINVAL;
reg = smw_mix_regs[dev];
if (reg == 0)
return -EINVAL;
sb_setmixer(devc, reg, (24 - (24 * left / 100)) | 0x20); /* 24=mute, 0=max */
sb_setmixer(devc, reg + 1, (24 - (24 * right / 100)) | 0x40);
}
devc->levels[dev] = left | (right << 8);
return left | (right << 8);
}
static int sb_mixer_set(sb_devc * devc, int dev, int value)
{
int left = value & 0x000000ff;
int right = (value & 0x0000ff00) >> 8;
int retval;
if (left > 100)
left = 100;
if (right > 100)
right = 100;
if ((dev < 0) || (dev > 31))
return -EINVAL;
if (!(devc->supported_devices & (1 << dev))) /*
* Not supported
*/
return -EINVAL;
/* Differentiate depending on the chipsets */
switch (devc->model) {
case MDL_SMW:
retval = smw_mixer_set(devc, dev, left, right);
break;
case MDL_ESS:
retval = ess_mixer_set(devc, dev, left, right);
break;
default:
retval = sb_common_mixer_set(devc, dev, left, right);
}
if (retval >= 0) devc->levels[dev] = retval;
return retval;
}
/*
* set_recsrc doesn't apply to ES188x
*/
static void set_recsrc(sb_devc * devc, int src)
{
sb_setmixer(devc, RECORD_SRC, (sb_getmixer(devc, RECORD_SRC) & ~7) | (src & 0x7));
}
static int set_recmask(sb_devc * devc, int mask)
{
int devmask, i;
unsigned char regimageL, regimageR;
devmask = mask & devc->supported_rec_devices;
switch (devc->model)
{
case MDL_SBPRO:
case MDL_ESS:
case MDL_JAZZ:
case MDL_SMW:
if (devc->model == MDL_ESS && ess_set_recmask (devc, &devmask)) {
break;
};
if (devmask != SOUND_MASK_MIC &&
devmask != SOUND_MASK_LINE &&
devmask != SOUND_MASK_CD)
{
/*
* More than one device selected. Drop the
* previous selection
*/
devmask &= ~devc->recmask;
}
if (devmask != SOUND_MASK_MIC &&
devmask != SOUND_MASK_LINE &&
devmask != SOUND_MASK_CD)
{
/*
* More than one device selected. Default to
* mic
*/
devmask = SOUND_MASK_MIC;
}
if (devmask ^ devc->recmask) /*
* Input source changed
*/
{
switch (devmask)
{
case SOUND_MASK_MIC:
set_recsrc(devc, SRC__MIC);
break;
case SOUND_MASK_LINE:
set_recsrc(devc, SRC__LINE);
break;
case SOUND_MASK_CD:
set_recsrc(devc, SRC__CD);
break;
default:
set_recsrc(devc, SRC__MIC);
}
}
break;
case MDL_SB16:
if (!devmask)
devmask = SOUND_MASK_MIC;
if (devc->submodel == SUBMDL_ALS007)
{
switch (devmask)
{
case SOUND_MASK_LINE:
sb_setmixer(devc, ALS007_RECORD_SRC, ALS007_LINE);
break;
case SOUND_MASK_CD:
sb_setmixer(devc, ALS007_RECORD_SRC, ALS007_CD);
break;
case SOUND_MASK_SYNTH:
sb_setmixer(devc, ALS007_RECORD_SRC, ALS007_SYNTH);
break;
default: /* Also takes care of SOUND_MASK_MIC case */
sb_setmixer(devc, ALS007_RECORD_SRC, ALS007_MIC);
break;
}
}
else
{
regimageL = regimageR = 0;
for (i = 0; i < SOUND_MIXER_NRDEVICES; i++)
{
if ((1 << i) & devmask)
{
regimageL |= sb16_recmasks_L[i];
regimageR |= sb16_recmasks_R[i];
}
sb_setmixer (devc, SB16_IMASK_L, regimageL);
sb_setmixer (devc, SB16_IMASK_R, regimageR);
}
}
break;
}
devc->recmask = devmask;
return devc->recmask;
}
static int set_outmask(sb_devc * devc, int mask)
{
int devmask, i;
unsigned char regimage;
devmask = mask & devc->supported_out_devices;
switch (devc->model)
{
case MDL_SB16:
if (devc->submodel == SUBMDL_ALS007)
break;
else
{
regimage = 0;
for (i = 0; i < SOUND_MIXER_NRDEVICES; i++)
{
if ((1 << i) & devmask)
{
regimage |= (sb16_recmasks_L[i] | sb16_recmasks_R[i]);
}
sb_setmixer (devc, SB16_OMASK, regimage);
}
}
break;
default:
break;
}
devc->outmask = devmask;
return devc->outmask;
}
static int sb_mixer_ioctl(int dev, unsigned int cmd, void __user *arg)
{
sb_devc *devc = mixer_devs[dev]->devc;
int val, ret;
int __user *p = arg;
/*
* Use ioctl(fd, SOUND_MIXER_AGC, &mode) to turn AGC off (0) or on (1).
* Use ioctl(fd, SOUND_MIXER_3DSE, &mode) to turn 3DSE off (0) or on (1)
* or mode==2 put 3DSE state to mode.
*/
if (devc->model == MDL_SB16) {
if (cmd == SOUND_MIXER_AGC)
{
if (get_user(val, p))
return -EFAULT;
sb_setmixer(devc, 0x43, (~val) & 0x01);
return 0;
}
if (cmd == SOUND_MIXER_3DSE)
{
/* I put here 15, but I don't know the exact version.
At least my 4.13 havn't 3DSE, 4.16 has it. */
if (devc->minor < 15)
return -EINVAL;
if (get_user(val, p))
return -EFAULT;
if (val == 0 || val == 1)
sb_chgmixer(devc, AWE_3DSE, 0x01, val);
else if (val == 2)
{
ret = sb_getmixer(devc, AWE_3DSE)&0x01;
return put_user(ret, p);
}
else
return -EINVAL;
return 0;
}
}
if (((cmd >> 8) & 0xff) == 'M')
{
if (_SIOC_DIR(cmd) & _SIOC_WRITE)
{
if (get_user(val, p))
return -EFAULT;
switch (cmd & 0xff)
{
case SOUND_MIXER_RECSRC:
ret = set_recmask(devc, val);
break;
case SOUND_MIXER_OUTSRC:
ret = set_outmask(devc, val);
break;
default:
ret = sb_mixer_set(devc, cmd & 0xff, val);
}
}
else switch (cmd & 0xff)
{
case SOUND_MIXER_RECSRC:
ret = devc->recmask;
break;
case SOUND_MIXER_OUTSRC:
ret = devc->outmask;
break;
case SOUND_MIXER_DEVMASK:
ret = devc->supported_devices;
break;
case SOUND_MIXER_STEREODEVS:
ret = devc->supported_devices;
/* The ESS seems to have stereo mic controls */
if (devc->model == MDL_ESS)
ret &= ~(SOUND_MASK_SPEAKER|SOUND_MASK_IMIX);
else if (devc->model != MDL_JAZZ && devc->model != MDL_SMW)
ret &= ~(SOUND_MASK_MIC | SOUND_MASK_SPEAKER | SOUND_MASK_IMIX);
break;
case SOUND_MIXER_RECMASK:
ret = devc->supported_rec_devices;
break;
case SOUND_MIXER_OUTMASK:
ret = devc->supported_out_devices;
break;
case SOUND_MIXER_CAPS:
ret = devc->mixer_caps;
break;
default:
ret = sb_mixer_get(devc, cmd & 0xff);
break;
}
return put_user(ret, p);
} else
return -EINVAL;
}
static struct mixer_operations sb_mixer_operations =
{
.owner = THIS_MODULE,
.id = "SB",
.name = "Sound Blaster",
.ioctl = sb_mixer_ioctl
};
static struct mixer_operations als007_mixer_operations =
{
.owner = THIS_MODULE,
.id = "ALS007",
.name = "Avance ALS-007",
.ioctl = sb_mixer_ioctl
};
static void sb_mixer_reset(sb_devc * devc)
{
char name[32];
int i;
sprintf(name, "SB_%d", devc->sbmixnum);
if (devc->sbmo.sm_games)
devc->levels = load_mixer_volumes(name, smg_default_levels, 1);
else
devc->levels = load_mixer_volumes(name, sb_default_levels, 1);
for (i = 0; i < SOUND_MIXER_NRDEVICES; i++)
sb_mixer_set(devc, i, devc->levels[i]);
if (devc->model != MDL_ESS || !ess_mixer_reset (devc)) {
set_recmask(devc, SOUND_MASK_MIC);
};
}
int sb_mixer_init(sb_devc * devc, struct module *owner)
{
int mixer_type = 0;
int m;
devc->sbmixnum = sbmixnum++;
devc->levels = NULL;
sb_setmixer(devc, 0x00, 0); /* Reset mixer */
if (!(mixer_type = detect_mixer(devc)))
return 0; /* No mixer. Why? */
switch (devc->model)
{
case MDL_ESSPCI:
case MDL_YMPCI:
case MDL_SBPRO:
case MDL_AZTECH:
case MDL_JAZZ:
devc->mixer_caps = SOUND_CAP_EXCL_INPUT;
devc->supported_devices = SBPRO_MIXER_DEVICES;
devc->supported_rec_devices = SBPRO_RECORDING_DEVICES;
devc->iomap = &sbpro_mix;
devc->iomap_sz = ARRAY_SIZE(sbpro_mix);
break;
case MDL_ESS:
ess_mixer_init (devc);
break;
case MDL_SMW:
devc->mixer_caps = SOUND_CAP_EXCL_INPUT;
devc->supported_devices = 0;
devc->supported_rec_devices = 0;
devc->iomap = &sbpro_mix;
devc->iomap_sz = ARRAY_SIZE(sbpro_mix);
smw_mixer_init(devc);
break;
case MDL_SB16:
devc->mixer_caps = 0;
devc->supported_rec_devices = SB16_RECORDING_DEVICES;
devc->supported_out_devices = SB16_OUTFILTER_DEVICES;
if (devc->submodel != SUBMDL_ALS007)
{
devc->supported_devices = SB16_MIXER_DEVICES;
devc->iomap = &sb16_mix;
devc->iomap_sz = ARRAY_SIZE(sb16_mix);
}
else
{
devc->supported_devices = ALS007_MIXER_DEVICES;
devc->iomap = &als007_mix;
devc->iomap_sz = ARRAY_SIZE(als007_mix);
}
break;
default:
printk(KERN_WARNING "sb_mixer: Unsupported mixer type %d\n", devc->model);
return 0;
}
m = sound_alloc_mixerdev();
if (m == -1)
return 0;
mixer_devs[m] = kmalloc(sizeof(struct mixer_operations), GFP_KERNEL);
if (mixer_devs[m] == NULL)
{
printk(KERN_ERR "sb_mixer: Can't allocate memory\n");
sound_unload_mixerdev(m);
return 0;
}
if (devc->submodel != SUBMDL_ALS007)
memcpy ((char *) mixer_devs[m], (char *) &sb_mixer_operations, sizeof (struct mixer_operations));
else
memcpy ((char *) mixer_devs[m], (char *) &als007_mixer_operations, sizeof (struct mixer_operations));
mixer_devs[m]->devc = devc;
if (owner)
mixer_devs[m]->owner = owner;
devc->my_mixerdev = m;
sb_mixer_reset(devc);
return 1;
}
void sb_mixer_unload(sb_devc *devc)
{
if (devc->my_mixerdev == -1)
return;
kfree(mixer_devs[devc->my_mixerdev]);
sound_unload_mixerdev(devc->my_mixerdev);
sbmixnum--;
}
| gpl-2.0 |
MrHyde03/android_kernel_samsung_espressovzw | drivers/staging/brcm80211/brcmsmac/bcmsrom.c | 2427 | 16292 | /*
* Copyright (c) 2010 Broadcom Corporation
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/etherdevice.h>
#include <bcmdefs.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <stdarg.h>
#include <bcmutils.h>
#include <hndsoc.h>
#include <sbchipc.h>
#include <bcmdevs.h>
#include <pcicfg.h>
#include <aiutils.h>
#include <bcmsrom.h>
#include <bcmsrom_tbl.h>
#include <bcmnvram.h>
#include <bcmotp.h>
#define SROM_OFFSET(sih) ((sih->ccrev > 31) ? \
(((sih->cccaps & CC_CAP_SROM) == 0) ? NULL : \
((u8 *)curmap + PCI_16KB0_CCREGS_OFFSET + CC_SROM_OTP)) : \
((u8 *)curmap + PCI_BAR0_SPROM_OFFSET))
#if defined(BCMDBG)
#define WRITE_ENABLE_DELAY 500 /* 500 ms after write enable/disable toggle */
#define WRITE_WORD_DELAY 20 /* 20 ms between each word write */
#endif
typedef struct varbuf {
char *base; /* pointer to buffer base */
char *buf; /* pointer to current position */
unsigned int size; /* current (residual) size in bytes */
} varbuf_t;
extern char *_vars;
extern uint _varsz;
static int initvars_srom_si(si_t *sih, void *curmap, char **vars, uint *count);
static void _initvars_srom_pci(u8 sromrev, u16 *srom, uint off, varbuf_t *b);
static int initvars_srom_pci(si_t *sih, void *curmap, char **vars, uint *count);
static int initvars_flash_si(si_t *sih, char **vars, uint *count);
static int sprom_read_pci(si_t *sih, u16 *sprom,
uint wordoff, u16 *buf, uint nwords, bool check_crc);
#if defined(BCMNVRAMR)
static int otp_read_pci(si_t *sih, u16 *buf, uint bufsz);
#endif
static u16 srom_cc_cmd(si_t *sih, void *ccregs, u32 cmd,
uint wordoff, u16 data);
static int initvars_table(char *start, char *end,
char **vars, uint *count);
static int initvars_flash(si_t *sih, char **vp,
uint len);
/* Initialization of varbuf structure */
static void varbuf_init(varbuf_t *b, char *buf, uint size)
{
b->size = size;
b->base = b->buf = buf;
}
/* append a null terminated var=value string */
static int varbuf_append(varbuf_t *b, const char *fmt, ...)
{
va_list ap;
int r;
size_t len;
char *s;
if (b->size < 2)
return 0;
va_start(ap, fmt);
r = vsnprintf(b->buf, b->size, fmt, ap);
va_end(ap);
/* C99 snprintf behavior returns r >= size on overflow,
* others return -1 on overflow.
* All return -1 on format error.
* We need to leave room for 2 null terminations, one for the current var
* string, and one for final null of the var table. So check that the
* strlen written, r, leaves room for 2 chars.
*/
if ((r == -1) || (r > (int)(b->size - 2))) {
b->size = 0;
return 0;
}
/* Remove any earlier occurrence of the same variable */
s = strchr(b->buf, '=');
if (s != NULL) {
len = (size_t) (s - b->buf);
for (s = b->base; s < b->buf;) {
if ((memcmp(s, b->buf, len) == 0) && s[len] == '=') {
len = strlen(s) + 1;
memmove(s, (s + len),
((b->buf + r + 1) - (s + len)));
b->buf -= len;
b->size += (unsigned int)len;
break;
}
while (*s++)
;
}
}
/* skip over this string's null termination */
r++;
b->size -= r;
b->buf += r;
return r;
}
/*
* Initialize local vars from the right source for this platform.
* Return 0 on success, nonzero on error.
*/
int srom_var_init(si_t *sih, uint bustype, void *curmap,
char **vars, uint *count)
{
uint len;
len = 0;
if (vars == NULL || count == NULL)
return 0;
*vars = NULL;
*count = 0;
switch (bustype) {
case SI_BUS:
case JTAG_BUS:
return initvars_srom_si(sih, curmap, vars, count);
case PCI_BUS:
if (curmap == NULL)
return -1;
return initvars_srom_pci(sih, curmap, vars, count);
default:
break;
}
return -1;
}
/* In chips with chipcommon rev 32 and later, the srom is in chipcommon,
* not in the bus cores.
*/
static u16
srom_cc_cmd(si_t *sih, void *ccregs, u32 cmd,
uint wordoff, u16 data)
{
chipcregs_t *cc = (chipcregs_t *) ccregs;
uint wait_cnt = 1000;
if ((cmd == SRC_OP_READ) || (cmd == SRC_OP_WRITE)) {
W_REG(&cc->sromaddress, wordoff * 2);
if (cmd == SRC_OP_WRITE)
W_REG(&cc->sromdata, data);
}
W_REG(&cc->sromcontrol, SRC_START | cmd);
while (wait_cnt--) {
if ((R_REG(&cc->sromcontrol) & SRC_BUSY) == 0)
break;
}
if (!wait_cnt) {
return 0xffff;
}
if (cmd == SRC_OP_READ)
return (u16) R_REG(&cc->sromdata);
else
return 0xffff;
}
static inline void ltoh16_buf(u16 *buf, unsigned int size)
{
for (size /= 2; size; size--)
*(buf + size) = le16_to_cpu(*(buf + size));
}
static inline void htol16_buf(u16 *buf, unsigned int size)
{
for (size /= 2; size; size--)
*(buf + size) = cpu_to_le16(*(buf + size));
}
/*
* Read in and validate sprom.
* Return 0 on success, nonzero on error.
*/
static int
sprom_read_pci(si_t *sih, u16 *sprom, uint wordoff,
u16 *buf, uint nwords, bool check_crc)
{
int err = 0;
uint i;
void *ccregs = NULL;
/* read the sprom */
for (i = 0; i < nwords; i++) {
if (sih->ccrev > 31 && ISSIM_ENAB(sih)) {
/* use indirect since direct is too slow on QT */
if ((sih->cccaps & CC_CAP_SROM) == 0)
return 1;
ccregs = (void *)((u8 *) sprom - CC_SROM_OTP);
buf[i] =
srom_cc_cmd(sih, ccregs, SRC_OP_READ,
wordoff + i, 0);
} else {
if (ISSIM_ENAB(sih))
buf[i] = R_REG(&sprom[wordoff + i]);
buf[i] = R_REG(&sprom[wordoff + i]);
}
}
/* bypass crc checking for simulation to allow srom hack */
if (ISSIM_ENAB(sih))
return err;
if (check_crc) {
if (buf[0] == 0xffff) {
/* The hardware thinks that an srom that starts with 0xffff
* is blank, regardless of the rest of the content, so declare
* it bad.
*/
return 1;
}
/* fixup the endianness so crc8 will pass */
htol16_buf(buf, nwords * 2);
if (bcm_crc8((u8 *) buf, nwords * 2, CRC8_INIT_VALUE) !=
CRC8_GOOD_VALUE) {
/* DBG only pci always read srom4 first, then srom8/9 */
err = 1;
}
/* now correct the endianness of the byte array */
ltoh16_buf(buf, nwords * 2);
}
return err;
}
#if defined(BCMNVRAMR)
static int otp_read_pci(si_t *sih, u16 *buf, uint bufsz)
{
u8 *otp;
uint sz = OTP_SZ_MAX / 2; /* size in words */
int err = 0;
otp = kzalloc(OTP_SZ_MAX, GFP_ATOMIC);
if (otp == NULL) {
return -EBADE;
}
err = otp_read_region(sih, OTP_HW_RGN, (u16 *) otp, &sz);
memcpy(buf, otp, bufsz);
kfree(otp);
/* Check CRC */
if (buf[0] == 0xffff) {
/* The hardware thinks that an srom that starts with 0xffff
* is blank, regardless of the rest of the content, so declare
* it bad.
*/
return 1;
}
/* fixup the endianness so crc8 will pass */
htol16_buf(buf, bufsz);
if (bcm_crc8((u8 *) buf, SROM4_WORDS * 2, CRC8_INIT_VALUE) !=
CRC8_GOOD_VALUE) {
err = 1;
}
/* now correct the endianness of the byte array */
ltoh16_buf(buf, bufsz);
return err;
}
#endif /* defined(BCMNVRAMR) */
/*
* Create variable table from memory.
* Return 0 on success, nonzero on error.
*/
static int initvars_table(char *start, char *end,
char **vars, uint *count)
{
int c = (int)(end - start);
/* do it only when there is more than just the null string */
if (c > 1) {
char *vp = kmalloc(c, GFP_ATOMIC);
if (!vp)
return -ENOMEM;
memcpy(vp, start, c);
*vars = vp;
*count = c;
} else {
*vars = NULL;
*count = 0;
}
return 0;
}
/*
* Find variables with <devpath> from flash. 'base' points to the beginning
* of the table upon enter and to the end of the table upon exit when success.
* Return 0 on success, nonzero on error.
*/
static int initvars_flash(si_t *sih, char **base, uint len)
{
char *vp = *base;
char *flash;
int err;
char *s;
uint l, dl, copy_len;
char devpath[SI_DEVPATH_BUFSZ];
/* allocate memory and read in flash */
flash = kmalloc(NVRAM_SPACE, GFP_ATOMIC);
if (!flash)
return -ENOMEM;
err = nvram_getall(flash, NVRAM_SPACE);
if (err)
goto exit;
ai_devpath(sih, devpath, sizeof(devpath));
/* grab vars with the <devpath> prefix in name */
dl = strlen(devpath);
for (s = flash; s && *s; s += l + 1) {
l = strlen(s);
/* skip non-matching variable */
if (strncmp(s, devpath, dl))
continue;
/* is there enough room to copy? */
copy_len = l - dl + 1;
if (len < copy_len) {
err = -EOVERFLOW;
goto exit;
}
/* no prefix, just the name=value */
strncpy(vp, &s[dl], copy_len);
vp += copy_len;
len -= copy_len;
}
/* add null string as terminator */
if (len < 1) {
err = -EOVERFLOW;
goto exit;
}
*vp++ = '\0';
*base = vp;
exit: kfree(flash);
return err;
}
/*
* Initialize nonvolatile variable table from flash.
* Return 0 on success, nonzero on error.
*/
static int initvars_flash_si(si_t *sih, char **vars, uint *count)
{
char *vp, *base;
int err;
base = vp = kmalloc(MAXSZ_NVRAM_VARS, GFP_ATOMIC);
if (!vp)
return -ENOMEM;
err = initvars_flash(sih, &vp, MAXSZ_NVRAM_VARS);
if (err == 0)
err = initvars_table(base, vp, vars, count);
kfree(base);
return err;
}
/* Parse SROM and create name=value pairs. 'srom' points to
* the SROM word array. 'off' specifies the offset of the
* first word 'srom' points to, which should be either 0 or
* SROM3_SWRG_OFF (full SROM or software region).
*/
static uint mask_shift(u16 mask)
{
uint i;
for (i = 0; i < (sizeof(mask) << 3); i++) {
if (mask & (1 << i))
return i;
}
return 0;
}
static uint mask_width(u16 mask)
{
int i;
for (i = (sizeof(mask) << 3) - 1; i >= 0; i--) {
if (mask & (1 << i))
return (uint) (i - mask_shift(mask) + 1);
}
return 0;
}
static void _initvars_srom_pci(u8 sromrev, u16 *srom, uint off, varbuf_t *b)
{
u16 w;
u32 val;
const sromvar_t *srv;
uint width;
uint flags;
u32 sr = (1 << sromrev);
varbuf_append(b, "sromrev=%d", sromrev);
for (srv = pci_sromvars; srv->name != NULL; srv++) {
const char *name;
if ((srv->revmask & sr) == 0)
continue;
if (srv->off < off)
continue;
flags = srv->flags;
name = srv->name;
/* This entry is for mfgc only. Don't generate param for it, */
if (flags & SRFL_NOVAR)
continue;
if (flags & SRFL_ETHADDR) {
u8 ea[ETH_ALEN];
ea[0] = (srom[srv->off - off] >> 8) & 0xff;
ea[1] = srom[srv->off - off] & 0xff;
ea[2] = (srom[srv->off + 1 - off] >> 8) & 0xff;
ea[3] = srom[srv->off + 1 - off] & 0xff;
ea[4] = (srom[srv->off + 2 - off] >> 8) & 0xff;
ea[5] = srom[srv->off + 2 - off] & 0xff;
varbuf_append(b, "%s=%pM", name, ea);
} else {
w = srom[srv->off - off];
val = (w & srv->mask) >> mask_shift(srv->mask);
width = mask_width(srv->mask);
while (srv->flags & SRFL_MORE) {
srv++;
if (srv->off == 0 || srv->off < off)
continue;
w = srom[srv->off - off];
val +=
((w & srv->mask) >> mask_shift(srv->
mask)) <<
width;
width += mask_width(srv->mask);
}
if ((flags & SRFL_NOFFS)
&& ((int)val == (1 << width) - 1))
continue;
if (flags & SRFL_CCODE) {
if (val == 0)
varbuf_append(b, "ccode=");
else
varbuf_append(b, "ccode=%c%c",
(val >> 8), (val & 0xff));
}
/* LED Powersave duty cycle has to be scaled:
*(oncount >> 24) (offcount >> 8)
*/
else if (flags & SRFL_LEDDC) {
u32 w32 = (((val >> 8) & 0xff) << 24) | /* oncount */
(((val & 0xff)) << 8); /* offcount */
varbuf_append(b, "leddc=%d", w32);
} else if (flags & SRFL_PRHEX)
varbuf_append(b, "%s=0x%x", name, val);
else if ((flags & SRFL_PRSIGN)
&& (val & (1 << (width - 1))))
varbuf_append(b, "%s=%d", name,
(int)(val | (~0 << width)));
else
varbuf_append(b, "%s=%u", name, val);
}
}
if (sromrev >= 4) {
/* Do per-path variables */
uint p, pb, psz;
if (sromrev >= 8) {
pb = SROM8_PATH0;
psz = SROM8_PATH1 - SROM8_PATH0;
} else {
pb = SROM4_PATH0;
psz = SROM4_PATH1 - SROM4_PATH0;
}
for (p = 0; p < MAX_PATH_SROM; p++) {
for (srv = perpath_pci_sromvars; srv->name != NULL;
srv++) {
if ((srv->revmask & sr) == 0)
continue;
if (pb + srv->off < off)
continue;
/* This entry is for mfgc only. Don't generate param for it, */
if (srv->flags & SRFL_NOVAR)
continue;
w = srom[pb + srv->off - off];
val = (w & srv->mask) >> mask_shift(srv->mask);
width = mask_width(srv->mask);
/* Cheating: no per-path var is more than 1 word */
if ((srv->flags & SRFL_NOFFS)
&& ((int)val == (1 << width) - 1))
continue;
if (srv->flags & SRFL_PRHEX)
varbuf_append(b, "%s%d=0x%x", srv->name,
p, val);
else
varbuf_append(b, "%s%d=%d", srv->name,
p, val);
}
pb += psz;
}
}
}
/*
* Initialize nonvolatile variable table from sprom.
* Return 0 on success, nonzero on error.
*/
static int initvars_srom_pci(si_t *sih, void *curmap, char **vars, uint *count)
{
u16 *srom, *sromwindow;
u8 sromrev = 0;
u32 sr;
varbuf_t b;
char *vp, *base = NULL;
bool flash = false;
int err = 0;
/*
* Apply CRC over SROM content regardless SROM is present or not,
* and use variable <devpath>sromrev's existence in flash to decide
* if we should return an error when CRC fails or read SROM variables
* from flash.
*/
srom = kmalloc(SROM_MAX, GFP_ATOMIC);
if (!srom)
return -2;
sromwindow = (u16 *) SROM_OFFSET(sih);
if (ai_is_sprom_available(sih)) {
err =
sprom_read_pci(sih, sromwindow, 0, srom, SROM_WORDS,
true);
if ((srom[SROM4_SIGN] == SROM4_SIGNATURE) ||
(((sih->buscoretype == PCIE_CORE_ID)
&& (sih->buscorerev >= 6))
|| ((sih->buscoretype == PCI_CORE_ID)
&& (sih->buscorerev >= 0xe)))) {
/* sromrev >= 4, read more */
err =
sprom_read_pci(sih, sromwindow, 0, srom,
SROM4_WORDS, true);
sromrev = srom[SROM4_CRCREV] & 0xff;
} else if (err == 0) {
/* srom is good and is rev < 4 */
/* top word of sprom contains version and crc8 */
sromrev = srom[SROM_CRCREV] & 0xff;
/* bcm4401 sroms misprogrammed */
if (sromrev == 0x10)
sromrev = 1;
}
}
#if defined(BCMNVRAMR)
/* Use OTP if SPROM not available */
else {
err = otp_read_pci(sih, srom, SROM_MAX);
if (err == 0)
/* OTP only contain SROM rev8/rev9 for now */
sromrev = srom[SROM4_CRCREV] & 0xff;
else
err = 1;
}
#else
else
err = 1;
#endif
/*
* We want internal/wltest driver to come up with default
* sromvars so we can program a blank SPROM/OTP.
*/
if (err) {
char *value;
u32 val;
val = 0;
value = ai_getdevpathvar(sih, "sromrev");
if (value) {
sromrev = (u8) simple_strtoul(value, NULL, 0);
flash = true;
goto varscont;
}
value = ai_getnvramflvar(sih, "sromrev");
if (value) {
err = 0;
goto errout;
}
{
err = -1;
goto errout;
}
}
varscont:
/* Bitmask for the sromrev */
sr = 1 << sromrev;
/* srom version check: Current valid versions: 1, 2, 3, 4, 5, 8, 9 */
if ((sr & 0x33e) == 0) {
err = -2;
goto errout;
}
base = vp = kmalloc(MAXSZ_NVRAM_VARS, GFP_ATOMIC);
if (!vp) {
err = -2;
goto errout;
}
/* read variables from flash */
if (flash) {
err = initvars_flash(sih, &vp, MAXSZ_NVRAM_VARS);
if (err)
goto errout;
goto varsdone;
}
varbuf_init(&b, base, MAXSZ_NVRAM_VARS);
/* parse SROM into name=value pairs. */
_initvars_srom_pci(sromrev, srom, 0, &b);
/* final nullbyte terminator */
vp = b.buf;
*vp++ = '\0';
varsdone:
err = initvars_table(base, vp, vars, count);
errout:
if (base)
kfree(base);
kfree(srom);
return err;
}
static int initvars_srom_si(si_t *sih, void *curmap, char **vars, uint *varsz)
{
/* Search flash nvram section for srom variables */
return initvars_flash_si(sih, vars, varsz);
}
| gpl-2.0 |
dreikk91/android_kernel_motorola_omap4-common | arch/arm/mach-omap1/board-htcherald.c | 2427 | 17645 | /*
* HTC Herald board configuration
* Copyright (C) 2009 Cory Maccarrone <darkstar6262@gmail.com>
* Copyright (C) 2009 Wing Linux
*
* Based on the board-htcwizard.c file from the linwizard project:
* Copyright (C) 2006 Unai Uribarri
* Copyright (C) 2008 linwizard.sourceforge.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <linux/gpio_keys.h>
#include <linux/i2c.h>
#include <linux/i2c-gpio.h>
#include <linux/htcpld.h>
#include <linux/leds.h>
#include <linux/spi/spi.h>
#include <linux/spi/ads7846.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <plat/omap7xx.h>
#include <plat/common.h>
#include <plat/board.h>
#include <plat/keypad.h>
#include <plat/usb.h>
#include <plat/mmc.h>
#include <mach/irqs.h>
#include <linux/delay.h>
/* LCD register definition */
#define OMAP_LCDC_CONTROL (0xfffec000 + 0x00)
#define OMAP_LCDC_STATUS (0xfffec000 + 0x10)
#define OMAP_DMA_LCD_CCR (0xfffee300 + 0xc2)
#define OMAP_DMA_LCD_CTRL (0xfffee300 + 0xc4)
#define OMAP_LCDC_CTRL_LCD_EN (1 << 0)
#define OMAP_LCDC_STAT_DONE (1 << 0)
/* GPIO definitions for the power button and keyboard slide switch */
#define HTCHERALD_GPIO_POWER 139
#define HTCHERALD_GPIO_SLIDE 174
#define HTCHERALD_GIRQ_BTNS 141
/* GPIO definitions for the touchscreen */
#define HTCHERALD_GPIO_TS 76
/* HTCPLD definitions */
/*
* CPLD Logic
*
* Chip 3 - 0x03
*
* Function 7 6 5 4 3 2 1 0
* ------------------------------------
* DPAD light x x x x x x x 1
* SoundDev x x x x 1 x x x
* Screen white 1 x x x x x x x
* MMC power on x x x x x 1 x x
* Happy times (n) 0 x x x x 1 x x
*
* Chip 4 - 0x04
*
* Function 7 6 5 4 3 2 1 0
* ------------------------------------
* Keyboard light x x x x x x x 1
* LCD Bright (4) x x x x x 1 1 x
* LCD Bright (3) x x x x x 0 1 x
* LCD Bright (2) x x x x x 1 0 x
* LCD Bright (1) x x x x x 0 0 x
* LCD Off x x x x 0 x x x
* LCD image (fb) 1 x x x x x x x
* LCD image (white) 0 x x x x x x x
* Caps lock LED x x 1 x x x x x
*
* Chip 5 - 0x05
*
* Function 7 6 5 4 3 2 1 0
* ------------------------------------
* Red (solid) x x x x x 1 x x
* Red (flash) x x x x x x 1 x
* Green (GSM flash) x x x x 1 x x x
* Green (GSM solid) x x x 1 x x x x
* Green (wifi flash) x x 1 x x x x x
* Blue (bt flash) x 1 x x x x x x
* DPAD Int Enable 1 x x x x x x 0
*
* (Combinations of the above can be made for different colors.)
* The direction pad interrupt enable must be set each time the
* interrupt is handled.
*
* Chip 6 - 0x06
*
* Function 7 6 5 4 3 2 1 0
* ------------------------------------
* Vibrator x x x x 1 x x x
* Alt LED x x x 1 x x x x
* Screen white 1 x x x x x x x
* Screen white x x 1 x x x x x
* Screen white x 0 x x x x x x
* Enable kbd dpad x x x x x x 0 x
* Happy Times 0 1 0 x x x 0 x
*/
/*
* HTCPLD GPIO lines start 16 after OMAP_MAX_GPIO_LINES to account
* for the 16 MPUIO lines.
*/
#define HTCPLD_GPIO_START_OFFSET (OMAP_MAX_GPIO_LINES + 16)
#define HTCPLD_IRQ(chip, offset) (OMAP_IRQ_END + 8 * (chip) + (offset))
#define HTCPLD_BASE(chip, offset) \
(HTCPLD_GPIO_START_OFFSET + 8 * (chip) + (offset))
#define HTCPLD_GPIO_LED_DPAD HTCPLD_BASE(0, 0)
#define HTCPLD_GPIO_LED_KBD HTCPLD_BASE(1, 0)
#define HTCPLD_GPIO_LED_CAPS HTCPLD_BASE(1, 5)
#define HTCPLD_GPIO_LED_RED_FLASH HTCPLD_BASE(2, 1)
#define HTCPLD_GPIO_LED_RED_SOLID HTCPLD_BASE(2, 2)
#define HTCPLD_GPIO_LED_GREEN_FLASH HTCPLD_BASE(2, 3)
#define HTCPLD_GPIO_LED_GREEN_SOLID HTCPLD_BASE(2, 4)
#define HTCPLD_GPIO_LED_WIFI HTCPLD_BASE(2, 5)
#define HTCPLD_GPIO_LED_BT HTCPLD_BASE(2, 6)
#define HTCPLD_GPIO_LED_VIBRATE HTCPLD_BASE(3, 3)
#define HTCPLD_GPIO_LED_ALT HTCPLD_BASE(3, 4)
#define HTCPLD_GPIO_RIGHT_KBD HTCPLD_BASE(6, 7)
#define HTCPLD_GPIO_UP_KBD HTCPLD_BASE(6, 6)
#define HTCPLD_GPIO_LEFT_KBD HTCPLD_BASE(6, 5)
#define HTCPLD_GPIO_DOWN_KBD HTCPLD_BASE(6, 4)
#define HTCPLD_GPIO_RIGHT_DPAD HTCPLD_BASE(7, 7)
#define HTCPLD_GPIO_UP_DPAD HTCPLD_BASE(7, 6)
#define HTCPLD_GPIO_LEFT_DPAD HTCPLD_BASE(7, 5)
#define HTCPLD_GPIO_DOWN_DPAD HTCPLD_BASE(7, 4)
#define HTCPLD_GPIO_ENTER_DPAD HTCPLD_BASE(7, 3)
/*
* The htcpld chip requires a gpio write to a specific line
* to re-enable interrupts after one has occurred.
*/
#define HTCPLD_GPIO_INT_RESET_HI HTCPLD_BASE(2, 7)
#define HTCPLD_GPIO_INT_RESET_LO HTCPLD_BASE(2, 0)
/* Chip 5 */
#define HTCPLD_IRQ_RIGHT_KBD HTCPLD_IRQ(0, 7)
#define HTCPLD_IRQ_UP_KBD HTCPLD_IRQ(0, 6)
#define HTCPLD_IRQ_LEFT_KBD HTCPLD_IRQ(0, 5)
#define HTCPLD_IRQ_DOWN_KBD HTCPLD_IRQ(0, 4)
/* Chip 6 */
#define HTCPLD_IRQ_RIGHT_DPAD HTCPLD_IRQ(1, 7)
#define HTCPLD_IRQ_UP_DPAD HTCPLD_IRQ(1, 6)
#define HTCPLD_IRQ_LEFT_DPAD HTCPLD_IRQ(1, 5)
#define HTCPLD_IRQ_DOWN_DPAD HTCPLD_IRQ(1, 4)
#define HTCPLD_IRQ_ENTER_DPAD HTCPLD_IRQ(1, 3)
/* Keyboard definition */
static const unsigned int htc_herald_keymap[] = {
KEY(0, 0, KEY_RECORD), /* Mail button */
KEY(1, 0, KEY_CAMERA), /* Camera */
KEY(2, 0, KEY_PHONE), /* Send key */
KEY(3, 0, KEY_VOLUMEUP), /* Volume up */
KEY(4, 0, KEY_F2), /* Right bar (landscape) */
KEY(5, 0, KEY_MAIL), /* Win key (portrait) */
KEY(6, 0, KEY_DIRECTORY), /* Right bar (protrait) */
KEY(0, 1, KEY_LEFTCTRL), /* Windows key */
KEY(1, 1, KEY_COMMA),
KEY(2, 1, KEY_M),
KEY(3, 1, KEY_K),
KEY(4, 1, KEY_SLASH), /* OK key */
KEY(5, 1, KEY_I),
KEY(6, 1, KEY_U),
KEY(0, 2, KEY_LEFTALT),
KEY(1, 2, KEY_TAB),
KEY(2, 2, KEY_N),
KEY(3, 2, KEY_J),
KEY(4, 2, KEY_ENTER),
KEY(5, 2, KEY_H),
KEY(6, 2, KEY_Y),
KEY(0, 3, KEY_SPACE),
KEY(1, 3, KEY_L),
KEY(2, 3, KEY_B),
KEY(3, 3, KEY_V),
KEY(4, 3, KEY_BACKSPACE),
KEY(5, 3, KEY_G),
KEY(6, 3, KEY_T),
KEY(0, 4, KEY_CAPSLOCK), /* Shift */
KEY(1, 4, KEY_C),
KEY(2, 4, KEY_F),
KEY(3, 4, KEY_R),
KEY(4, 4, KEY_O),
KEY(5, 4, KEY_E),
KEY(6, 4, KEY_D),
KEY(0, 5, KEY_X),
KEY(1, 5, KEY_Z),
KEY(2, 5, KEY_S),
KEY(3, 5, KEY_W),
KEY(4, 5, KEY_P),
KEY(5, 5, KEY_Q),
KEY(6, 5, KEY_A),
KEY(0, 6, KEY_CONNECT), /* Voice button */
KEY(2, 6, KEY_CANCEL), /* End key */
KEY(3, 6, KEY_VOLUMEDOWN), /* Volume down */
KEY(4, 6, KEY_F1), /* Left bar (landscape) */
KEY(5, 6, KEY_WWW), /* OK button (portrait) */
KEY(6, 6, KEY_CALENDAR), /* Left bar (portrait) */
};
static const struct matrix_keymap_data htc_herald_keymap_data = {
.keymap = htc_herald_keymap,
.keymap_size = ARRAY_SIZE(htc_herald_keymap),
};
static struct omap_kp_platform_data htcherald_kp_data = {
.rows = 7,
.cols = 7,
.delay = 20,
.rep = true,
.keymap_data = &htc_herald_keymap_data,
};
static struct resource kp_resources[] = {
[0] = {
.start = INT_7XX_MPUIO_KEYPAD,
.end = INT_7XX_MPUIO_KEYPAD,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device kp_device = {
.name = "omap-keypad",
.id = -1,
.dev = {
.platform_data = &htcherald_kp_data,
},
.num_resources = ARRAY_SIZE(kp_resources),
.resource = kp_resources,
};
/* GPIO buttons for keyboard slide and power button */
static struct gpio_keys_button herald_gpio_keys_table[] = {
{BTN_0, HTCHERALD_GPIO_POWER, 1, "POWER", EV_KEY, 1, 20},
{SW_LID, HTCHERALD_GPIO_SLIDE, 0, "SLIDE", EV_SW, 1, 20},
{KEY_LEFT, HTCPLD_GPIO_LEFT_KBD, 1, "LEFT", EV_KEY, 1, 20},
{KEY_RIGHT, HTCPLD_GPIO_RIGHT_KBD, 1, "RIGHT", EV_KEY, 1, 20},
{KEY_UP, HTCPLD_GPIO_UP_KBD, 1, "UP", EV_KEY, 1, 20},
{KEY_DOWN, HTCPLD_GPIO_DOWN_KBD, 1, "DOWN", EV_KEY, 1, 20},
{KEY_LEFT, HTCPLD_GPIO_LEFT_DPAD, 1, "DLEFT", EV_KEY, 1, 20},
{KEY_RIGHT, HTCPLD_GPIO_RIGHT_DPAD, 1, "DRIGHT", EV_KEY, 1, 20},
{KEY_UP, HTCPLD_GPIO_UP_DPAD, 1, "DUP", EV_KEY, 1, 20},
{KEY_DOWN, HTCPLD_GPIO_DOWN_DPAD, 1, "DDOWN", EV_KEY, 1, 20},
{KEY_ENTER, HTCPLD_GPIO_ENTER_DPAD, 1, "DENTER", EV_KEY, 1, 20},
};
static struct gpio_keys_platform_data herald_gpio_keys_data = {
.buttons = herald_gpio_keys_table,
.nbuttons = ARRAY_SIZE(herald_gpio_keys_table),
.rep = true,
};
static struct platform_device herald_gpiokeys_device = {
.name = "gpio-keys",
.id = -1,
.dev = {
.platform_data = &herald_gpio_keys_data,
},
};
/* LEDs for the Herald. These connect to the HTCPLD GPIO device. */
static struct gpio_led gpio_leds[] = {
{"dpad", NULL, HTCPLD_GPIO_LED_DPAD, 0, 0, LEDS_GPIO_DEFSTATE_OFF},
{"kbd", NULL, HTCPLD_GPIO_LED_KBD, 0, 0, LEDS_GPIO_DEFSTATE_OFF},
{"vibrate", NULL, HTCPLD_GPIO_LED_VIBRATE, 0, 0, LEDS_GPIO_DEFSTATE_OFF},
{"green_solid", NULL, HTCPLD_GPIO_LED_GREEN_SOLID, 0, 0, LEDS_GPIO_DEFSTATE_OFF},
{"green_flash", NULL, HTCPLD_GPIO_LED_GREEN_FLASH, 0, 0, LEDS_GPIO_DEFSTATE_OFF},
{"red_solid", "mmc0", HTCPLD_GPIO_LED_RED_SOLID, 0, 0, LEDS_GPIO_DEFSTATE_OFF},
{"red_flash", NULL, HTCPLD_GPIO_LED_RED_FLASH, 0, 0, LEDS_GPIO_DEFSTATE_OFF},
{"wifi", NULL, HTCPLD_GPIO_LED_WIFI, 0, 0, LEDS_GPIO_DEFSTATE_OFF},
{"bt", NULL, HTCPLD_GPIO_LED_BT, 0, 0, LEDS_GPIO_DEFSTATE_OFF},
{"caps", NULL, HTCPLD_GPIO_LED_CAPS, 0, 0, LEDS_GPIO_DEFSTATE_OFF},
{"alt", NULL, HTCPLD_GPIO_LED_ALT, 0, 0, LEDS_GPIO_DEFSTATE_OFF},
};
static struct gpio_led_platform_data gpio_leds_data = {
.leds = gpio_leds,
.num_leds = ARRAY_SIZE(gpio_leds),
};
static struct platform_device gpio_leds_device = {
.name = "leds-gpio",
.id = 0,
.dev = {
.platform_data = &gpio_leds_data,
},
};
/* HTC PLD chips */
static struct resource htcpld_resources[] = {
[0] = {
.start = OMAP_GPIO_IRQ(HTCHERALD_GIRQ_BTNS),
.end = OMAP_GPIO_IRQ(HTCHERALD_GIRQ_BTNS),
.flags = IORESOURCE_IRQ,
},
};
static struct htcpld_chip_platform_data htcpld_chips[] = {
[0] = {
.addr = 0x03,
.reset = 0x04,
.num_gpios = 8,
.gpio_out_base = HTCPLD_BASE(0, 0),
.gpio_in_base = HTCPLD_BASE(4, 0),
},
[1] = {
.addr = 0x04,
.reset = 0x8e,
.num_gpios = 8,
.gpio_out_base = HTCPLD_BASE(1, 0),
.gpio_in_base = HTCPLD_BASE(5, 0),
},
[2] = {
.addr = 0x05,
.reset = 0x80,
.num_gpios = 8,
.gpio_out_base = HTCPLD_BASE(2, 0),
.gpio_in_base = HTCPLD_BASE(6, 0),
.irq_base = HTCPLD_IRQ(0, 0),
.num_irqs = 8,
},
[3] = {
.addr = 0x06,
.reset = 0x40,
.num_gpios = 8,
.gpio_out_base = HTCPLD_BASE(3, 0),
.gpio_in_base = HTCPLD_BASE(7, 0),
.irq_base = HTCPLD_IRQ(1, 0),
.num_irqs = 8,
},
};
static struct htcpld_core_platform_data htcpld_pfdata = {
.int_reset_gpio_hi = HTCPLD_GPIO_INT_RESET_HI,
.int_reset_gpio_lo = HTCPLD_GPIO_INT_RESET_LO,
.i2c_adapter_id = 1,
.chip = htcpld_chips,
.num_chip = ARRAY_SIZE(htcpld_chips),
};
static struct platform_device htcpld_device = {
.name = "i2c-htcpld",
.id = -1,
.resource = htcpld_resources,
.num_resources = ARRAY_SIZE(htcpld_resources),
.dev = {
.platform_data = &htcpld_pfdata,
},
};
/* USB Device */
static struct omap_usb_config htcherald_usb_config __initdata = {
.otg = 0,
.register_host = 0,
.register_dev = 1,
.hmc_mode = 4,
.pins[0] = 2,
};
/* LCD Device resources */
static struct omap_lcd_config htcherald_lcd_config __initdata = {
.ctrl_name = "internal",
};
static struct omap_board_config_kernel htcherald_config[] __initdata = {
{ OMAP_TAG_LCD, &htcherald_lcd_config },
};
static struct platform_device lcd_device = {
.name = "lcd_htcherald",
.id = -1,
};
/* MMC Card */
#if defined(CONFIG_MMC_OMAP) || defined(CONFIG_MMC_OMAP_MODULE)
static struct omap_mmc_platform_data htc_mmc1_data = {
.nr_slots = 1,
.switch_slot = NULL,
.slots[0] = {
.ocr_mask = MMC_VDD_32_33 | MMC_VDD_33_34,
.name = "mmcblk",
.nomux = 1,
.wires = 4,
.switch_pin = -1,
},
};
static struct omap_mmc_platform_data *htc_mmc_data[1];
#endif
/* Platform devices for the Herald */
static struct platform_device *devices[] __initdata = {
&kp_device,
&lcd_device,
&htcpld_device,
&gpio_leds_device,
&herald_gpiokeys_device,
};
/*
* Touchscreen
*/
static const struct ads7846_platform_data htcherald_ts_platform_data = {
.model = 7846,
.keep_vref_on = 1,
.x_plate_ohms = 496,
.gpio_pendown = HTCHERALD_GPIO_TS,
.pressure_max = 10000,
.pressure_min = 5000,
.x_min = 528,
.x_max = 3760,
.y_min = 624,
.y_max = 3760,
};
static struct spi_board_info __initdata htcherald_spi_board_info[] = {
{
.modalias = "ads7846",
.platform_data = &htcherald_ts_platform_data,
.irq = OMAP_GPIO_IRQ(HTCHERALD_GPIO_TS),
.max_speed_hz = 2500000,
.bus_num = 2,
.chip_select = 1,
}
};
/*
* Init functions from here on
*/
static void __init htcherald_lcd_init(void)
{
u32 reg;
unsigned int tries = 200;
/* disable controller if active */
reg = omap_readl(OMAP_LCDC_CONTROL);
if (reg & OMAP_LCDC_CTRL_LCD_EN) {
reg &= ~OMAP_LCDC_CTRL_LCD_EN;
omap_writel(reg, OMAP_LCDC_CONTROL);
/* wait for end of frame */
while (!(omap_readl(OMAP_LCDC_STATUS) & OMAP_LCDC_STAT_DONE)) {
tries--;
if (!tries)
break;
}
if (!tries)
printk(KERN_WARNING "Timeout waiting for end of frame "
"-- LCD may not be available\n");
/* turn off DMA */
reg = omap_readw(OMAP_DMA_LCD_CCR);
reg &= ~(1 << 7);
omap_writew(reg, OMAP_DMA_LCD_CCR);
reg = omap_readw(OMAP_DMA_LCD_CTRL);
reg &= ~(1 << 8);
omap_writew(reg, OMAP_DMA_LCD_CTRL);
}
}
static void __init htcherald_map_io(void)
{
omap1_map_common_io();
/*
* The LCD panel must be disabled and DMA turned off here, as doing
* it later causes the LCD never to reinitialize.
*/
htcherald_lcd_init();
printk(KERN_INFO "htcherald_map_io done.\n");
}
static void __init htcherald_disable_watchdog(void)
{
/* Disable watchdog if running */
if (omap_readl(OMAP_WDT_TIMER_MODE) & 0x8000) {
/*
* disable a potentially running watchdog timer before
* it kills us.
*/
printk(KERN_WARNING "OMAP850 Watchdog seems to be activated, disabling it for now.\n");
omap_writel(0xF5, OMAP_WDT_TIMER_MODE);
omap_writel(0xA0, OMAP_WDT_TIMER_MODE);
}
}
#define HTCHERALD_GPIO_USB_EN1 33
#define HTCHERALD_GPIO_USB_EN2 73
#define HTCHERALD_GPIO_USB_DM 35
#define HTCHERALD_GPIO_USB_DP 36
static void __init htcherald_usb_enable(void)
{
unsigned int tries = 20;
unsigned int value = 0;
/* Request the GPIOs we need to control here */
if (gpio_request(HTCHERALD_GPIO_USB_EN1, "herald_usb") < 0)
goto err1;
if (gpio_request(HTCHERALD_GPIO_USB_EN2, "herald_usb") < 0)
goto err2;
if (gpio_request(HTCHERALD_GPIO_USB_DM, "herald_usb") < 0)
goto err3;
if (gpio_request(HTCHERALD_GPIO_USB_DP, "herald_usb") < 0)
goto err4;
/* force USB_EN GPIO to 0 */
do {
/* output low */
gpio_direction_output(HTCHERALD_GPIO_USB_EN1, 0);
} while ((value = gpio_get_value(HTCHERALD_GPIO_USB_EN1)) == 1 &&
--tries);
if (value == 1)
printk(KERN_WARNING "Unable to reset USB, trying to continue\n");
gpio_direction_output(HTCHERALD_GPIO_USB_EN2, 0); /* output low */
gpio_direction_input(HTCHERALD_GPIO_USB_DM); /* input */
gpio_direction_input(HTCHERALD_GPIO_USB_DP); /* input */
goto done;
err4:
gpio_free(HTCHERALD_GPIO_USB_DM);
err3:
gpio_free(HTCHERALD_GPIO_USB_EN2);
err2:
gpio_free(HTCHERALD_GPIO_USB_EN1);
err1:
printk(KERN_ERR "Unabled to request GPIO for USB\n");
done:
printk(KERN_INFO "USB setup complete.\n");
}
static void __init htcherald_init(void)
{
printk(KERN_INFO "HTC Herald init.\n");
/* Do board initialization before we register all the devices */
omap_board_config = htcherald_config;
omap_board_config_size = ARRAY_SIZE(htcherald_config);
platform_add_devices(devices, ARRAY_SIZE(devices));
htcherald_disable_watchdog();
htcherald_usb_enable();
omap1_usb_init(&htcherald_usb_config);
spi_register_board_info(htcherald_spi_board_info,
ARRAY_SIZE(htcherald_spi_board_info));
omap_register_i2c_bus(1, 100, NULL, 0);
#if defined(CONFIG_MMC_OMAP) || defined(CONFIG_MMC_OMAP_MODULE)
htc_mmc_data[0] = &htc_mmc1_data;
omap1_init_mmc(htc_mmc_data, 1);
#endif
}
static void __init htcherald_init_irq(void)
{
printk(KERN_INFO "htcherald_init_irq.\n");
omap1_init_common_hw();
omap_init_irq();
}
MACHINE_START(HERALD, "HTC Herald")
/* Maintainer: Cory Maccarrone <darkstar6262@gmail.com> */
/* Maintainer: wing-linux.sourceforge.net */
.boot_params = 0x10000100,
.map_io = htcherald_map_io,
.reserve = omap_reserve,
.init_irq = htcherald_init_irq,
.init_machine = htcherald_init,
.timer = &omap_timer,
MACHINE_END
| gpl-2.0 |
Ateeq72/weekly-kernel | drivers/media/video/omap3isp/ispcsi2.c | 2939 | 36997 | /*
* ispcsi2.c
*
* TI OMAP3 ISP - CSI2 module
*
* Copyright (C) 2010 Nokia Corporation
* Copyright (C) 2009 Texas Instruments, Inc.
*
* Contacts: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
* Sakari Ailus <sakari.ailus@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <linux/delay.h>
#include <media/v4l2-common.h>
#include <linux/v4l2-mediabus.h>
#include <linux/mm.h>
#include "isp.h"
#include "ispreg.h"
#include "ispcsi2.h"
/*
* csi2_if_enable - Enable CSI2 Receiver interface.
* @enable: enable flag
*
*/
static void csi2_if_enable(struct isp_device *isp,
struct isp_csi2_device *csi2, u8 enable)
{
struct isp_csi2_ctrl_cfg *currctrl = &csi2->ctrl;
isp_reg_clr_set(isp, csi2->regs1, ISPCSI2_CTRL, ISPCSI2_CTRL_IF_EN,
enable ? ISPCSI2_CTRL_IF_EN : 0);
currctrl->if_enable = enable;
}
/*
* csi2_recv_config - CSI2 receiver module configuration.
* @currctrl: isp_csi2_ctrl_cfg structure
*
*/
static void csi2_recv_config(struct isp_device *isp,
struct isp_csi2_device *csi2,
struct isp_csi2_ctrl_cfg *currctrl)
{
u32 reg;
reg = isp_reg_readl(isp, csi2->regs1, ISPCSI2_CTRL);
if (currctrl->frame_mode)
reg |= ISPCSI2_CTRL_FRAME;
else
reg &= ~ISPCSI2_CTRL_FRAME;
if (currctrl->vp_clk_enable)
reg |= ISPCSI2_CTRL_VP_CLK_EN;
else
reg &= ~ISPCSI2_CTRL_VP_CLK_EN;
if (currctrl->vp_only_enable)
reg |= ISPCSI2_CTRL_VP_ONLY_EN;
else
reg &= ~ISPCSI2_CTRL_VP_ONLY_EN;
reg &= ~ISPCSI2_CTRL_VP_OUT_CTRL_MASK;
reg |= currctrl->vp_out_ctrl << ISPCSI2_CTRL_VP_OUT_CTRL_SHIFT;
if (currctrl->ecc_enable)
reg |= ISPCSI2_CTRL_ECC_EN;
else
reg &= ~ISPCSI2_CTRL_ECC_EN;
isp_reg_writel(isp, reg, csi2->regs1, ISPCSI2_CTRL);
}
static const unsigned int csi2_input_fmts[] = {
V4L2_MBUS_FMT_SGRBG10_1X10,
V4L2_MBUS_FMT_SGRBG10_DPCM8_1X8,
V4L2_MBUS_FMT_SRGGB10_1X10,
V4L2_MBUS_FMT_SRGGB10_DPCM8_1X8,
V4L2_MBUS_FMT_SBGGR10_1X10,
V4L2_MBUS_FMT_SBGGR10_DPCM8_1X8,
V4L2_MBUS_FMT_SGBRG10_1X10,
V4L2_MBUS_FMT_SGBRG10_DPCM8_1X8,
};
/* To set the format on the CSI2 requires a mapping function that takes
* the following inputs:
* - 2 different formats (at this time)
* - 2 destinations (mem, vp+mem) (vp only handled separately)
* - 2 decompression options (on, off)
* - 2 isp revisions (certain format must be handled differently on OMAP3630)
* Output should be CSI2 frame format code
* Array indices as follows: [format][dest][decompr][is_3630]
* Not all combinations are valid. 0 means invalid.
*/
static const u16 __csi2_fmt_map[2][2][2][2] = {
/* RAW10 formats */
{
/* Output to memory */
{
/* No DPCM decompression */
{ CSI2_PIX_FMT_RAW10_EXP16, CSI2_PIX_FMT_RAW10_EXP16 },
/* DPCM decompression */
{ 0, 0 },
},
/* Output to both */
{
/* No DPCM decompression */
{ CSI2_PIX_FMT_RAW10_EXP16_VP,
CSI2_PIX_FMT_RAW10_EXP16_VP },
/* DPCM decompression */
{ 0, 0 },
},
},
/* RAW10 DPCM8 formats */
{
/* Output to memory */
{
/* No DPCM decompression */
{ CSI2_PIX_FMT_RAW8, CSI2_USERDEF_8BIT_DATA1 },
/* DPCM decompression */
{ CSI2_PIX_FMT_RAW8_DPCM10_EXP16,
CSI2_USERDEF_8BIT_DATA1_DPCM10 },
},
/* Output to both */
{
/* No DPCM decompression */
{ CSI2_PIX_FMT_RAW8_VP,
CSI2_PIX_FMT_RAW8_VP },
/* DPCM decompression */
{ CSI2_PIX_FMT_RAW8_DPCM10_VP,
CSI2_USERDEF_8BIT_DATA1_DPCM10_VP },
},
},
};
/*
* csi2_ctx_map_format - Map CSI2 sink media bus format to CSI2 format ID
* @csi2: ISP CSI2 device
*
* Returns CSI2 physical format id
*/
static u16 csi2_ctx_map_format(struct isp_csi2_device *csi2)
{
const struct v4l2_mbus_framefmt *fmt = &csi2->formats[CSI2_PAD_SINK];
int fmtidx, destidx, is_3630;
switch (fmt->code) {
case V4L2_MBUS_FMT_SGRBG10_1X10:
case V4L2_MBUS_FMT_SRGGB10_1X10:
case V4L2_MBUS_FMT_SBGGR10_1X10:
case V4L2_MBUS_FMT_SGBRG10_1X10:
fmtidx = 0;
break;
case V4L2_MBUS_FMT_SGRBG10_DPCM8_1X8:
case V4L2_MBUS_FMT_SRGGB10_DPCM8_1X8:
case V4L2_MBUS_FMT_SBGGR10_DPCM8_1X8:
case V4L2_MBUS_FMT_SGBRG10_DPCM8_1X8:
fmtidx = 1;
break;
default:
WARN(1, KERN_ERR "CSI2: pixel format %08x unsupported!\n",
fmt->code);
return 0;
}
if (!(csi2->output & CSI2_OUTPUT_CCDC) &&
!(csi2->output & CSI2_OUTPUT_MEMORY)) {
/* Neither output enabled is a valid combination */
return CSI2_PIX_FMT_OTHERS;
}
/* If we need to skip frames at the beginning of the stream disable the
* video port to avoid sending the skipped frames to the CCDC.
*/
destidx = csi2->frame_skip ? 0 : !!(csi2->output & CSI2_OUTPUT_CCDC);
is_3630 = csi2->isp->revision == ISP_REVISION_15_0;
return __csi2_fmt_map[fmtidx][destidx][csi2->dpcm_decompress][is_3630];
}
/*
* csi2_set_outaddr - Set memory address to save output image
* @csi2: Pointer to ISP CSI2a device.
* @addr: ISP MMU Mapped 32-bit memory address aligned on 32 byte boundary.
*
* Sets the memory address where the output will be saved.
*
* Returns 0 if successful, or -EINVAL if the address is not in the 32 byte
* boundary.
*/
static void csi2_set_outaddr(struct isp_csi2_device *csi2, u32 addr)
{
struct isp_device *isp = csi2->isp;
struct isp_csi2_ctx_cfg *ctx = &csi2->contexts[0];
ctx->ping_addr = addr;
ctx->pong_addr = addr;
isp_reg_writel(isp, ctx->ping_addr,
csi2->regs1, ISPCSI2_CTX_DAT_PING_ADDR(ctx->ctxnum));
isp_reg_writel(isp, ctx->pong_addr,
csi2->regs1, ISPCSI2_CTX_DAT_PONG_ADDR(ctx->ctxnum));
}
/*
* is_usr_def_mapping - Checks whether USER_DEF_MAPPING should
* be enabled by CSI2.
* @format_id: mapped format id
*
*/
static inline int is_usr_def_mapping(u32 format_id)
{
return (format_id & 0x40) ? 1 : 0;
}
/*
* csi2_ctx_enable - Enable specified CSI2 context
* @ctxnum: Context number, valid between 0 and 7 values.
* @enable: enable
*
*/
static void csi2_ctx_enable(struct isp_device *isp,
struct isp_csi2_device *csi2, u8 ctxnum, u8 enable)
{
struct isp_csi2_ctx_cfg *ctx = &csi2->contexts[ctxnum];
unsigned int skip = 0;
u32 reg;
reg = isp_reg_readl(isp, csi2->regs1, ISPCSI2_CTX_CTRL1(ctxnum));
if (enable) {
if (csi2->frame_skip)
skip = csi2->frame_skip;
else if (csi2->output & CSI2_OUTPUT_MEMORY)
skip = 1;
reg &= ~ISPCSI2_CTX_CTRL1_COUNT_MASK;
reg |= ISPCSI2_CTX_CTRL1_COUNT_UNLOCK
| (skip << ISPCSI2_CTX_CTRL1_COUNT_SHIFT)
| ISPCSI2_CTX_CTRL1_CTX_EN;
} else {
reg &= ~ISPCSI2_CTX_CTRL1_CTX_EN;
}
isp_reg_writel(isp, reg, csi2->regs1, ISPCSI2_CTX_CTRL1(ctxnum));
ctx->enabled = enable;
}
/*
* csi2_ctx_config - CSI2 context configuration.
* @ctx: context configuration
*
*/
static void csi2_ctx_config(struct isp_device *isp,
struct isp_csi2_device *csi2,
struct isp_csi2_ctx_cfg *ctx)
{
u32 reg;
/* Set up CSI2_CTx_CTRL1 */
reg = isp_reg_readl(isp, csi2->regs1, ISPCSI2_CTX_CTRL1(ctx->ctxnum));
if (ctx->eof_enabled)
reg |= ISPCSI2_CTX_CTRL1_EOF_EN;
else
reg &= ~ISPCSI2_CTX_CTRL1_EOF_EN;
if (ctx->eol_enabled)
reg |= ISPCSI2_CTX_CTRL1_EOL_EN;
else
reg &= ~ISPCSI2_CTX_CTRL1_EOL_EN;
if (ctx->checksum_enabled)
reg |= ISPCSI2_CTX_CTRL1_CS_EN;
else
reg &= ~ISPCSI2_CTX_CTRL1_CS_EN;
isp_reg_writel(isp, reg, csi2->regs1, ISPCSI2_CTX_CTRL1(ctx->ctxnum));
/* Set up CSI2_CTx_CTRL2 */
reg = isp_reg_readl(isp, csi2->regs1, ISPCSI2_CTX_CTRL2(ctx->ctxnum));
reg &= ~(ISPCSI2_CTX_CTRL2_VIRTUAL_ID_MASK);
reg |= ctx->virtual_id << ISPCSI2_CTX_CTRL2_VIRTUAL_ID_SHIFT;
reg &= ~(ISPCSI2_CTX_CTRL2_FORMAT_MASK);
reg |= ctx->format_id << ISPCSI2_CTX_CTRL2_FORMAT_SHIFT;
if (ctx->dpcm_decompress) {
if (ctx->dpcm_predictor)
reg |= ISPCSI2_CTX_CTRL2_DPCM_PRED;
else
reg &= ~ISPCSI2_CTX_CTRL2_DPCM_PRED;
}
if (is_usr_def_mapping(ctx->format_id)) {
reg &= ~ISPCSI2_CTX_CTRL2_USER_DEF_MAP_MASK;
reg |= 2 << ISPCSI2_CTX_CTRL2_USER_DEF_MAP_SHIFT;
}
isp_reg_writel(isp, reg, csi2->regs1, ISPCSI2_CTX_CTRL2(ctx->ctxnum));
/* Set up CSI2_CTx_CTRL3 */
reg = isp_reg_readl(isp, csi2->regs1, ISPCSI2_CTX_CTRL3(ctx->ctxnum));
reg &= ~(ISPCSI2_CTX_CTRL3_ALPHA_MASK);
reg |= (ctx->alpha << ISPCSI2_CTX_CTRL3_ALPHA_SHIFT);
isp_reg_writel(isp, reg, csi2->regs1, ISPCSI2_CTX_CTRL3(ctx->ctxnum));
/* Set up CSI2_CTx_DAT_OFST */
reg = isp_reg_readl(isp, csi2->regs1,
ISPCSI2_CTX_DAT_OFST(ctx->ctxnum));
reg &= ~ISPCSI2_CTX_DAT_OFST_OFST_MASK;
reg |= ctx->data_offset << ISPCSI2_CTX_DAT_OFST_OFST_SHIFT;
isp_reg_writel(isp, reg, csi2->regs1,
ISPCSI2_CTX_DAT_OFST(ctx->ctxnum));
isp_reg_writel(isp, ctx->ping_addr,
csi2->regs1, ISPCSI2_CTX_DAT_PING_ADDR(ctx->ctxnum));
isp_reg_writel(isp, ctx->pong_addr,
csi2->regs1, ISPCSI2_CTX_DAT_PONG_ADDR(ctx->ctxnum));
}
/*
* csi2_timing_config - CSI2 timing configuration.
* @timing: csi2_timing_cfg structure
*/
static void csi2_timing_config(struct isp_device *isp,
struct isp_csi2_device *csi2,
struct isp_csi2_timing_cfg *timing)
{
u32 reg;
reg = isp_reg_readl(isp, csi2->regs1, ISPCSI2_TIMING);
if (timing->force_rx_mode)
reg |= ISPCSI2_TIMING_FORCE_RX_MODE_IO(timing->ionum);
else
reg &= ~ISPCSI2_TIMING_FORCE_RX_MODE_IO(timing->ionum);
if (timing->stop_state_16x)
reg |= ISPCSI2_TIMING_STOP_STATE_X16_IO(timing->ionum);
else
reg &= ~ISPCSI2_TIMING_STOP_STATE_X16_IO(timing->ionum);
if (timing->stop_state_4x)
reg |= ISPCSI2_TIMING_STOP_STATE_X4_IO(timing->ionum);
else
reg &= ~ISPCSI2_TIMING_STOP_STATE_X4_IO(timing->ionum);
reg &= ~ISPCSI2_TIMING_STOP_STATE_COUNTER_IO_MASK(timing->ionum);
reg |= timing->stop_state_counter <<
ISPCSI2_TIMING_STOP_STATE_COUNTER_IO_SHIFT(timing->ionum);
isp_reg_writel(isp, reg, csi2->regs1, ISPCSI2_TIMING);
}
/*
* csi2_irq_ctx_set - Enables CSI2 Context IRQs.
* @enable: Enable/disable CSI2 Context interrupts
*/
static void csi2_irq_ctx_set(struct isp_device *isp,
struct isp_csi2_device *csi2, int enable)
{
u32 reg = ISPCSI2_CTX_IRQSTATUS_FE_IRQ;
int i;
if (csi2->use_fs_irq)
reg |= ISPCSI2_CTX_IRQSTATUS_FS_IRQ;
for (i = 0; i < 8; i++) {
isp_reg_writel(isp, reg, csi2->regs1,
ISPCSI2_CTX_IRQSTATUS(i));
if (enable)
isp_reg_set(isp, csi2->regs1, ISPCSI2_CTX_IRQENABLE(i),
reg);
else
isp_reg_clr(isp, csi2->regs1, ISPCSI2_CTX_IRQENABLE(i),
reg);
}
}
/*
* csi2_irq_complexio1_set - Enables CSI2 ComplexIO IRQs.
* @enable: Enable/disable CSI2 ComplexIO #1 interrupts
*/
static void csi2_irq_complexio1_set(struct isp_device *isp,
struct isp_csi2_device *csi2, int enable)
{
u32 reg;
reg = ISPCSI2_PHY_IRQENABLE_STATEALLULPMEXIT |
ISPCSI2_PHY_IRQENABLE_STATEALLULPMENTER |
ISPCSI2_PHY_IRQENABLE_STATEULPM5 |
ISPCSI2_PHY_IRQENABLE_ERRCONTROL5 |
ISPCSI2_PHY_IRQENABLE_ERRESC5 |
ISPCSI2_PHY_IRQENABLE_ERRSOTSYNCHS5 |
ISPCSI2_PHY_IRQENABLE_ERRSOTHS5 |
ISPCSI2_PHY_IRQENABLE_STATEULPM4 |
ISPCSI2_PHY_IRQENABLE_ERRCONTROL4 |
ISPCSI2_PHY_IRQENABLE_ERRESC4 |
ISPCSI2_PHY_IRQENABLE_ERRSOTSYNCHS4 |
ISPCSI2_PHY_IRQENABLE_ERRSOTHS4 |
ISPCSI2_PHY_IRQENABLE_STATEULPM3 |
ISPCSI2_PHY_IRQENABLE_ERRCONTROL3 |
ISPCSI2_PHY_IRQENABLE_ERRESC3 |
ISPCSI2_PHY_IRQENABLE_ERRSOTSYNCHS3 |
ISPCSI2_PHY_IRQENABLE_ERRSOTHS3 |
ISPCSI2_PHY_IRQENABLE_STATEULPM2 |
ISPCSI2_PHY_IRQENABLE_ERRCONTROL2 |
ISPCSI2_PHY_IRQENABLE_ERRESC2 |
ISPCSI2_PHY_IRQENABLE_ERRSOTSYNCHS2 |
ISPCSI2_PHY_IRQENABLE_ERRSOTHS2 |
ISPCSI2_PHY_IRQENABLE_STATEULPM1 |
ISPCSI2_PHY_IRQENABLE_ERRCONTROL1 |
ISPCSI2_PHY_IRQENABLE_ERRESC1 |
ISPCSI2_PHY_IRQENABLE_ERRSOTSYNCHS1 |
ISPCSI2_PHY_IRQENABLE_ERRSOTHS1;
isp_reg_writel(isp, reg, csi2->regs1, ISPCSI2_PHY_IRQSTATUS);
if (enable)
reg |= isp_reg_readl(isp, csi2->regs1, ISPCSI2_PHY_IRQENABLE);
else
reg = 0;
isp_reg_writel(isp, reg, csi2->regs1, ISPCSI2_PHY_IRQENABLE);
}
/*
* csi2_irq_status_set - Enables CSI2 Status IRQs.
* @enable: Enable/disable CSI2 Status interrupts
*/
static void csi2_irq_status_set(struct isp_device *isp,
struct isp_csi2_device *csi2, int enable)
{
u32 reg;
reg = ISPCSI2_IRQSTATUS_OCP_ERR_IRQ |
ISPCSI2_IRQSTATUS_SHORT_PACKET_IRQ |
ISPCSI2_IRQSTATUS_ECC_CORRECTION_IRQ |
ISPCSI2_IRQSTATUS_ECC_NO_CORRECTION_IRQ |
ISPCSI2_IRQSTATUS_COMPLEXIO2_ERR_IRQ |
ISPCSI2_IRQSTATUS_COMPLEXIO1_ERR_IRQ |
ISPCSI2_IRQSTATUS_FIFO_OVF_IRQ |
ISPCSI2_IRQSTATUS_CONTEXT(0);
isp_reg_writel(isp, reg, csi2->regs1, ISPCSI2_IRQSTATUS);
if (enable)
reg |= isp_reg_readl(isp, csi2->regs1, ISPCSI2_IRQENABLE);
else
reg = 0;
isp_reg_writel(isp, reg, csi2->regs1, ISPCSI2_IRQENABLE);
}
/*
* omap3isp_csi2_reset - Resets the CSI2 module.
*
* Must be called with the phy lock held.
*
* Returns 0 if successful, or -EBUSY if power command didn't respond.
*/
int omap3isp_csi2_reset(struct isp_csi2_device *csi2)
{
struct isp_device *isp = csi2->isp;
u8 soft_reset_retries = 0;
u32 reg;
int i;
if (!csi2->available)
return -ENODEV;
if (csi2->phy->phy_in_use)
return -EBUSY;
isp_reg_set(isp, csi2->regs1, ISPCSI2_SYSCONFIG,
ISPCSI2_SYSCONFIG_SOFT_RESET);
do {
reg = isp_reg_readl(isp, csi2->regs1, ISPCSI2_SYSSTATUS) &
ISPCSI2_SYSSTATUS_RESET_DONE;
if (reg == ISPCSI2_SYSSTATUS_RESET_DONE)
break;
soft_reset_retries++;
if (soft_reset_retries < 5)
udelay(100);
} while (soft_reset_retries < 5);
if (soft_reset_retries == 5) {
printk(KERN_ERR "CSI2: Soft reset try count exceeded!\n");
return -EBUSY;
}
if (isp->revision == ISP_REVISION_15_0)
isp_reg_set(isp, csi2->regs1, ISPCSI2_PHY_CFG,
ISPCSI2_PHY_CFG_RESET_CTRL);
i = 100;
do {
reg = isp_reg_readl(isp, csi2->phy->phy_regs, ISPCSIPHY_REG1)
& ISPCSIPHY_REG1_RESET_DONE_CTRLCLK;
if (reg == ISPCSIPHY_REG1_RESET_DONE_CTRLCLK)
break;
udelay(100);
} while (--i > 0);
if (i == 0) {
printk(KERN_ERR
"CSI2: Reset for CSI2_96M_FCLK domain Failed!\n");
return -EBUSY;
}
if (isp->autoidle)
isp_reg_clr_set(isp, csi2->regs1, ISPCSI2_SYSCONFIG,
ISPCSI2_SYSCONFIG_MSTANDBY_MODE_MASK |
ISPCSI2_SYSCONFIG_AUTO_IDLE,
ISPCSI2_SYSCONFIG_MSTANDBY_MODE_SMART |
((isp->revision == ISP_REVISION_15_0) ?
ISPCSI2_SYSCONFIG_AUTO_IDLE : 0));
else
isp_reg_clr_set(isp, csi2->regs1, ISPCSI2_SYSCONFIG,
ISPCSI2_SYSCONFIG_MSTANDBY_MODE_MASK |
ISPCSI2_SYSCONFIG_AUTO_IDLE,
ISPCSI2_SYSCONFIG_MSTANDBY_MODE_NO);
return 0;
}
static int csi2_configure(struct isp_csi2_device *csi2)
{
const struct isp_v4l2_subdevs_group *pdata;
struct isp_device *isp = csi2->isp;
struct isp_csi2_timing_cfg *timing = &csi2->timing[0];
struct v4l2_subdev *sensor;
struct media_pad *pad;
/*
* CSI2 fields that can be updated while the context has
* been enabled or the interface has been enabled are not
* updated dynamically currently. So we do not allow to
* reconfigure if either has been enabled
*/
if (csi2->contexts[0].enabled || csi2->ctrl.if_enable)
return -EBUSY;
pad = media_entity_remote_source(&csi2->pads[CSI2_PAD_SINK]);
sensor = media_entity_to_v4l2_subdev(pad->entity);
pdata = sensor->host_priv;
csi2->frame_skip = 0;
v4l2_subdev_call(sensor, sensor, g_skip_frames, &csi2->frame_skip);
csi2->ctrl.vp_out_ctrl = pdata->bus.csi2.vpclk_div;
csi2->ctrl.frame_mode = ISP_CSI2_FRAME_IMMEDIATE;
csi2->ctrl.ecc_enable = pdata->bus.csi2.crc;
timing->ionum = 1;
timing->force_rx_mode = 1;
timing->stop_state_16x = 1;
timing->stop_state_4x = 1;
timing->stop_state_counter = 0x1FF;
/*
* The CSI2 receiver can't do any format conversion except DPCM
* decompression, so every set_format call configures both pads
* and enables DPCM decompression as a special case:
*/
if (csi2->formats[CSI2_PAD_SINK].code !=
csi2->formats[CSI2_PAD_SOURCE].code)
csi2->dpcm_decompress = true;
else
csi2->dpcm_decompress = false;
csi2->contexts[0].format_id = csi2_ctx_map_format(csi2);
if (csi2->video_out.bpl_padding == 0)
csi2->contexts[0].data_offset = 0;
else
csi2->contexts[0].data_offset = csi2->video_out.bpl_value;
/*
* Enable end of frame and end of line signals generation for
* context 0. These signals are generated from CSI2 receiver to
* qualify the last pixel of a frame and the last pixel of a line.
* Without enabling the signals CSI2 receiver writes data to memory
* beyond buffer size and/or data line offset is not handled correctly.
*/
csi2->contexts[0].eof_enabled = 1;
csi2->contexts[0].eol_enabled = 1;
csi2_irq_complexio1_set(isp, csi2, 1);
csi2_irq_ctx_set(isp, csi2, 1);
csi2_irq_status_set(isp, csi2, 1);
/* Set configuration (timings, format and links) */
csi2_timing_config(isp, csi2, timing);
csi2_recv_config(isp, csi2, &csi2->ctrl);
csi2_ctx_config(isp, csi2, &csi2->contexts[0]);
return 0;
}
/*
* csi2_print_status - Prints CSI2 debug information.
*/
#define CSI2_PRINT_REGISTER(isp, regs, name)\
dev_dbg(isp->dev, "###CSI2 " #name "=0x%08x\n", \
isp_reg_readl(isp, regs, ISPCSI2_##name))
static void csi2_print_status(struct isp_csi2_device *csi2)
{
struct isp_device *isp = csi2->isp;
if (!csi2->available)
return;
dev_dbg(isp->dev, "-------------CSI2 Register dump-------------\n");
CSI2_PRINT_REGISTER(isp, csi2->regs1, SYSCONFIG);
CSI2_PRINT_REGISTER(isp, csi2->regs1, SYSSTATUS);
CSI2_PRINT_REGISTER(isp, csi2->regs1, IRQENABLE);
CSI2_PRINT_REGISTER(isp, csi2->regs1, IRQSTATUS);
CSI2_PRINT_REGISTER(isp, csi2->regs1, CTRL);
CSI2_PRINT_REGISTER(isp, csi2->regs1, DBG_H);
CSI2_PRINT_REGISTER(isp, csi2->regs1, GNQ);
CSI2_PRINT_REGISTER(isp, csi2->regs1, PHY_CFG);
CSI2_PRINT_REGISTER(isp, csi2->regs1, PHY_IRQSTATUS);
CSI2_PRINT_REGISTER(isp, csi2->regs1, SHORT_PACKET);
CSI2_PRINT_REGISTER(isp, csi2->regs1, PHY_IRQENABLE);
CSI2_PRINT_REGISTER(isp, csi2->regs1, DBG_P);
CSI2_PRINT_REGISTER(isp, csi2->regs1, TIMING);
CSI2_PRINT_REGISTER(isp, csi2->regs1, CTX_CTRL1(0));
CSI2_PRINT_REGISTER(isp, csi2->regs1, CTX_CTRL2(0));
CSI2_PRINT_REGISTER(isp, csi2->regs1, CTX_DAT_OFST(0));
CSI2_PRINT_REGISTER(isp, csi2->regs1, CTX_DAT_PING_ADDR(0));
CSI2_PRINT_REGISTER(isp, csi2->regs1, CTX_DAT_PONG_ADDR(0));
CSI2_PRINT_REGISTER(isp, csi2->regs1, CTX_IRQENABLE(0));
CSI2_PRINT_REGISTER(isp, csi2->regs1, CTX_IRQSTATUS(0));
CSI2_PRINT_REGISTER(isp, csi2->regs1, CTX_CTRL3(0));
dev_dbg(isp->dev, "--------------------------------------------\n");
}
/* -----------------------------------------------------------------------------
* Interrupt handling
*/
/*
* csi2_isr_buffer - Does buffer handling at end-of-frame
* when writing to memory.
*/
static void csi2_isr_buffer(struct isp_csi2_device *csi2)
{
struct isp_device *isp = csi2->isp;
struct isp_buffer *buffer;
csi2_ctx_enable(isp, csi2, 0, 0);
buffer = omap3isp_video_buffer_next(&csi2->video_out, 0);
/*
* Let video queue operation restart engine if there is an underrun
* condition.
*/
if (buffer == NULL)
return;
csi2_set_outaddr(csi2, buffer->isp_addr);
csi2_ctx_enable(isp, csi2, 0, 1);
}
static void csi2_isr_ctx(struct isp_csi2_device *csi2,
struct isp_csi2_ctx_cfg *ctx)
{
struct isp_device *isp = csi2->isp;
unsigned int n = ctx->ctxnum;
u32 status;
status = isp_reg_readl(isp, csi2->regs1, ISPCSI2_CTX_IRQSTATUS(n));
isp_reg_writel(isp, status, csi2->regs1, ISPCSI2_CTX_IRQSTATUS(n));
/* Propagate frame number */
if (status & ISPCSI2_CTX_IRQSTATUS_FS_IRQ) {
struct isp_pipeline *pipe =
to_isp_pipeline(&csi2->subdev.entity);
if (pipe->do_propagation)
atomic_inc(&pipe->frame_number);
}
if (!(status & ISPCSI2_CTX_IRQSTATUS_FE_IRQ))
return;
/* Skip interrupts until we reach the frame skip count. The CSI2 will be
* automatically disabled, as the frame skip count has been programmed
* in the CSI2_CTx_CTRL1::COUNT field, so reenable it.
*
* It would have been nice to rely on the FRAME_NUMBER interrupt instead
* but it turned out that the interrupt is only generated when the CSI2
* writes to memory (the CSI2_CTx_CTRL1::COUNT field is decreased
* correctly and reaches 0 when data is forwarded to the video port only
* but no interrupt arrives). Maybe a CSI2 hardware bug.
*/
if (csi2->frame_skip) {
csi2->frame_skip--;
if (csi2->frame_skip == 0) {
ctx->format_id = csi2_ctx_map_format(csi2);
csi2_ctx_config(isp, csi2, ctx);
csi2_ctx_enable(isp, csi2, n, 1);
}
return;
}
if (csi2->output & CSI2_OUTPUT_MEMORY)
csi2_isr_buffer(csi2);
}
/*
* omap3isp_csi2_isr - CSI2 interrupt handling.
*
* Return -EIO on Transmission error
*/
int omap3isp_csi2_isr(struct isp_csi2_device *csi2)
{
u32 csi2_irqstatus, cpxio1_irqstatus;
struct isp_device *isp = csi2->isp;
int retval = 0;
if (!csi2->available)
return -ENODEV;
csi2_irqstatus = isp_reg_readl(isp, csi2->regs1, ISPCSI2_IRQSTATUS);
isp_reg_writel(isp, csi2_irqstatus, csi2->regs1, ISPCSI2_IRQSTATUS);
/* Failure Cases */
if (csi2_irqstatus & ISPCSI2_IRQSTATUS_COMPLEXIO1_ERR_IRQ) {
cpxio1_irqstatus = isp_reg_readl(isp, csi2->regs1,
ISPCSI2_PHY_IRQSTATUS);
isp_reg_writel(isp, cpxio1_irqstatus,
csi2->regs1, ISPCSI2_PHY_IRQSTATUS);
dev_dbg(isp->dev, "CSI2: ComplexIO Error IRQ "
"%x\n", cpxio1_irqstatus);
retval = -EIO;
}
if (csi2_irqstatus & (ISPCSI2_IRQSTATUS_OCP_ERR_IRQ |
ISPCSI2_IRQSTATUS_SHORT_PACKET_IRQ |
ISPCSI2_IRQSTATUS_ECC_NO_CORRECTION_IRQ |
ISPCSI2_IRQSTATUS_COMPLEXIO2_ERR_IRQ |
ISPCSI2_IRQSTATUS_FIFO_OVF_IRQ)) {
dev_dbg(isp->dev, "CSI2 Err:"
" OCP:%d,"
" Short_pack:%d,"
" ECC:%d,"
" CPXIO2:%d,"
" FIFO_OVF:%d,"
"\n",
(csi2_irqstatus &
ISPCSI2_IRQSTATUS_OCP_ERR_IRQ) ? 1 : 0,
(csi2_irqstatus &
ISPCSI2_IRQSTATUS_SHORT_PACKET_IRQ) ? 1 : 0,
(csi2_irqstatus &
ISPCSI2_IRQSTATUS_ECC_NO_CORRECTION_IRQ) ? 1 : 0,
(csi2_irqstatus &
ISPCSI2_IRQSTATUS_COMPLEXIO2_ERR_IRQ) ? 1 : 0,
(csi2_irqstatus &
ISPCSI2_IRQSTATUS_FIFO_OVF_IRQ) ? 1 : 0);
retval = -EIO;
}
if (omap3isp_module_sync_is_stopping(&csi2->wait, &csi2->stopping))
return 0;
/* Successful cases */
if (csi2_irqstatus & ISPCSI2_IRQSTATUS_CONTEXT(0))
csi2_isr_ctx(csi2, &csi2->contexts[0]);
if (csi2_irqstatus & ISPCSI2_IRQSTATUS_ECC_CORRECTION_IRQ)
dev_dbg(isp->dev, "CSI2: ECC correction done\n");
return retval;
}
/* -----------------------------------------------------------------------------
* ISP video operations
*/
/*
* csi2_queue - Queues the first buffer when using memory output
* @video: The video node
* @buffer: buffer to queue
*/
static int csi2_queue(struct isp_video *video, struct isp_buffer *buffer)
{
struct isp_device *isp = video->isp;
struct isp_csi2_device *csi2 = &isp->isp_csi2a;
csi2_set_outaddr(csi2, buffer->isp_addr);
/*
* If streaming was enabled before there was a buffer queued
* or underrun happened in the ISR, the hardware was not enabled
* and DMA queue flag ISP_VIDEO_DMAQUEUE_UNDERRUN is still set.
* Enable it now.
*/
if (csi2->video_out.dmaqueue_flags & ISP_VIDEO_DMAQUEUE_UNDERRUN) {
/* Enable / disable context 0 and IRQs */
csi2_if_enable(isp, csi2, 1);
csi2_ctx_enable(isp, csi2, 0, 1);
isp_video_dmaqueue_flags_clr(&csi2->video_out);
}
return 0;
}
static const struct isp_video_operations csi2_ispvideo_ops = {
.queue = csi2_queue,
};
/* -----------------------------------------------------------------------------
* V4L2 subdev operations
*/
static struct v4l2_mbus_framefmt *
__csi2_get_format(struct isp_csi2_device *csi2, struct v4l2_subdev_fh *fh,
unsigned int pad, enum v4l2_subdev_format_whence which)
{
if (which == V4L2_SUBDEV_FORMAT_TRY)
return v4l2_subdev_get_try_format(fh, pad);
else
return &csi2->formats[pad];
}
static void
csi2_try_format(struct isp_csi2_device *csi2, struct v4l2_subdev_fh *fh,
unsigned int pad, struct v4l2_mbus_framefmt *fmt,
enum v4l2_subdev_format_whence which)
{
enum v4l2_mbus_pixelcode pixelcode;
struct v4l2_mbus_framefmt *format;
const struct isp_format_info *info;
unsigned int i;
switch (pad) {
case CSI2_PAD_SINK:
/* Clamp the width and height to valid range (1-8191). */
for (i = 0; i < ARRAY_SIZE(csi2_input_fmts); i++) {
if (fmt->code == csi2_input_fmts[i])
break;
}
/* If not found, use SGRBG10 as default */
if (i >= ARRAY_SIZE(csi2_input_fmts))
fmt->code = V4L2_MBUS_FMT_SGRBG10_1X10;
fmt->width = clamp_t(u32, fmt->width, 1, 8191);
fmt->height = clamp_t(u32, fmt->height, 1, 8191);
break;
case CSI2_PAD_SOURCE:
/* Source format same as sink format, except for DPCM
* compression.
*/
pixelcode = fmt->code;
format = __csi2_get_format(csi2, fh, CSI2_PAD_SINK, which);
memcpy(fmt, format, sizeof(*fmt));
/*
* Only Allow DPCM decompression, and check that the
* pattern is preserved
*/
info = omap3isp_video_format_info(fmt->code);
if (info->uncompressed == pixelcode)
fmt->code = pixelcode;
break;
}
/* RGB, non-interlaced */
fmt->colorspace = V4L2_COLORSPACE_SRGB;
fmt->field = V4L2_FIELD_NONE;
}
/*
* csi2_enum_mbus_code - Handle pixel format enumeration
* @sd : pointer to v4l2 subdev structure
* @fh : V4L2 subdev file handle
* @code : pointer to v4l2_subdev_mbus_code_enum structure
* return -EINVAL or zero on success
*/
static int csi2_enum_mbus_code(struct v4l2_subdev *sd,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_mbus_code_enum *code)
{
struct isp_csi2_device *csi2 = v4l2_get_subdevdata(sd);
struct v4l2_mbus_framefmt *format;
const struct isp_format_info *info;
if (code->pad == CSI2_PAD_SINK) {
if (code->index >= ARRAY_SIZE(csi2_input_fmts))
return -EINVAL;
code->code = csi2_input_fmts[code->index];
} else {
format = __csi2_get_format(csi2, fh, CSI2_PAD_SINK,
V4L2_SUBDEV_FORMAT_TRY);
switch (code->index) {
case 0:
/* Passthrough sink pad code */
code->code = format->code;
break;
case 1:
/* Uncompressed code */
info = omap3isp_video_format_info(format->code);
if (info->uncompressed == format->code)
return -EINVAL;
code->code = info->uncompressed;
break;
default:
return -EINVAL;
}
}
return 0;
}
static int csi2_enum_frame_size(struct v4l2_subdev *sd,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_frame_size_enum *fse)
{
struct isp_csi2_device *csi2 = v4l2_get_subdevdata(sd);
struct v4l2_mbus_framefmt format;
if (fse->index != 0)
return -EINVAL;
format.code = fse->code;
format.width = 1;
format.height = 1;
csi2_try_format(csi2, fh, fse->pad, &format, V4L2_SUBDEV_FORMAT_TRY);
fse->min_width = format.width;
fse->min_height = format.height;
if (format.code != fse->code)
return -EINVAL;
format.code = fse->code;
format.width = -1;
format.height = -1;
csi2_try_format(csi2, fh, fse->pad, &format, V4L2_SUBDEV_FORMAT_TRY);
fse->max_width = format.width;
fse->max_height = format.height;
return 0;
}
/*
* csi2_get_format - Handle get format by pads subdev method
* @sd : pointer to v4l2 subdev structure
* @fh : V4L2 subdev file handle
* @fmt: pointer to v4l2 subdev format structure
* return -EINVAL or zero on success
*/
static int csi2_get_format(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh,
struct v4l2_subdev_format *fmt)
{
struct isp_csi2_device *csi2 = v4l2_get_subdevdata(sd);
struct v4l2_mbus_framefmt *format;
format = __csi2_get_format(csi2, fh, fmt->pad, fmt->which);
if (format == NULL)
return -EINVAL;
fmt->format = *format;
return 0;
}
/*
* csi2_set_format - Handle set format by pads subdev method
* @sd : pointer to v4l2 subdev structure
* @fh : V4L2 subdev file handle
* @fmt: pointer to v4l2 subdev format structure
* return -EINVAL or zero on success
*/
static int csi2_set_format(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh,
struct v4l2_subdev_format *fmt)
{
struct isp_csi2_device *csi2 = v4l2_get_subdevdata(sd);
struct v4l2_mbus_framefmt *format;
format = __csi2_get_format(csi2, fh, fmt->pad, fmt->which);
if (format == NULL)
return -EINVAL;
csi2_try_format(csi2, fh, fmt->pad, &fmt->format, fmt->which);
*format = fmt->format;
/* Propagate the format from sink to source */
if (fmt->pad == CSI2_PAD_SINK) {
format = __csi2_get_format(csi2, fh, CSI2_PAD_SOURCE,
fmt->which);
*format = fmt->format;
csi2_try_format(csi2, fh, CSI2_PAD_SOURCE, format, fmt->which);
}
return 0;
}
/*
* csi2_init_formats - Initialize formats on all pads
* @sd: ISP CSI2 V4L2 subdevice
* @fh: V4L2 subdev file handle
*
* Initialize all pad formats with default values. If fh is not NULL, try
* formats are initialized on the file handle. Otherwise active formats are
* initialized on the device.
*/
static int csi2_init_formats(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh)
{
struct v4l2_subdev_format format;
memset(&format, 0, sizeof(format));
format.pad = CSI2_PAD_SINK;
format.which = fh ? V4L2_SUBDEV_FORMAT_TRY : V4L2_SUBDEV_FORMAT_ACTIVE;
format.format.code = V4L2_MBUS_FMT_SGRBG10_1X10;
format.format.width = 4096;
format.format.height = 4096;
csi2_set_format(sd, fh, &format);
return 0;
}
/*
* csi2_set_stream - Enable/Disable streaming on the CSI2 module
* @sd: ISP CSI2 V4L2 subdevice
* @enable: ISP pipeline stream state
*
* Return 0 on success or a negative error code otherwise.
*/
static int csi2_set_stream(struct v4l2_subdev *sd, int enable)
{
struct isp_csi2_device *csi2 = v4l2_get_subdevdata(sd);
struct isp_device *isp = csi2->isp;
struct isp_pipeline *pipe = to_isp_pipeline(&csi2->subdev.entity);
struct isp_video *video_out = &csi2->video_out;
switch (enable) {
case ISP_PIPELINE_STREAM_CONTINUOUS:
if (omap3isp_csiphy_acquire(csi2->phy) < 0)
return -ENODEV;
csi2->use_fs_irq = pipe->do_propagation;
if (csi2->output & CSI2_OUTPUT_MEMORY)
omap3isp_sbl_enable(isp, OMAP3_ISP_SBL_CSI2A_WRITE);
csi2_configure(csi2);
csi2_print_status(csi2);
/*
* When outputting to memory with no buffer available, let the
* buffer queue handler start the hardware. A DMA queue flag
* ISP_VIDEO_DMAQUEUE_QUEUED will be set as soon as there is
* a buffer available.
*/
if (csi2->output & CSI2_OUTPUT_MEMORY &&
!(video_out->dmaqueue_flags & ISP_VIDEO_DMAQUEUE_QUEUED))
break;
/* Enable context 0 and IRQs */
atomic_set(&csi2->stopping, 0);
csi2_ctx_enable(isp, csi2, 0, 1);
csi2_if_enable(isp, csi2, 1);
isp_video_dmaqueue_flags_clr(video_out);
break;
case ISP_PIPELINE_STREAM_STOPPED:
if (csi2->state == ISP_PIPELINE_STREAM_STOPPED)
return 0;
if (omap3isp_module_sync_idle(&sd->entity, &csi2->wait,
&csi2->stopping))
dev_dbg(isp->dev, "%s: module stop timeout.\n",
sd->name);
csi2_ctx_enable(isp, csi2, 0, 0);
csi2_if_enable(isp, csi2, 0);
csi2_irq_ctx_set(isp, csi2, 0);
omap3isp_csiphy_release(csi2->phy);
isp_video_dmaqueue_flags_clr(video_out);
omap3isp_sbl_disable(isp, OMAP3_ISP_SBL_CSI2A_WRITE);
break;
}
csi2->state = enable;
return 0;
}
/* subdev video operations */
static const struct v4l2_subdev_video_ops csi2_video_ops = {
.s_stream = csi2_set_stream,
};
/* subdev pad operations */
static const struct v4l2_subdev_pad_ops csi2_pad_ops = {
.enum_mbus_code = csi2_enum_mbus_code,
.enum_frame_size = csi2_enum_frame_size,
.get_fmt = csi2_get_format,
.set_fmt = csi2_set_format,
};
/* subdev operations */
static const struct v4l2_subdev_ops csi2_ops = {
.video = &csi2_video_ops,
.pad = &csi2_pad_ops,
};
/* subdev internal operations */
static const struct v4l2_subdev_internal_ops csi2_internal_ops = {
.open = csi2_init_formats,
};
/* -----------------------------------------------------------------------------
* Media entity operations
*/
/*
* csi2_link_setup - Setup CSI2 connections.
* @entity : Pointer to media entity structure
* @local : Pointer to local pad array
* @remote : Pointer to remote pad array
* @flags : Link flags
* return -EINVAL or zero on success
*/
static int csi2_link_setup(struct media_entity *entity,
const struct media_pad *local,
const struct media_pad *remote, u32 flags)
{
struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(entity);
struct isp_csi2_device *csi2 = v4l2_get_subdevdata(sd);
struct isp_csi2_ctrl_cfg *ctrl = &csi2->ctrl;
/*
* The ISP core doesn't support pipelines with multiple video outputs.
* Revisit this when it will be implemented, and return -EBUSY for now.
*/
switch (local->index | media_entity_type(remote->entity)) {
case CSI2_PAD_SOURCE | MEDIA_ENT_T_DEVNODE:
if (flags & MEDIA_LNK_FL_ENABLED) {
if (csi2->output & ~CSI2_OUTPUT_MEMORY)
return -EBUSY;
csi2->output |= CSI2_OUTPUT_MEMORY;
} else {
csi2->output &= ~CSI2_OUTPUT_MEMORY;
}
break;
case CSI2_PAD_SOURCE | MEDIA_ENT_T_V4L2_SUBDEV:
if (flags & MEDIA_LNK_FL_ENABLED) {
if (csi2->output & ~CSI2_OUTPUT_CCDC)
return -EBUSY;
csi2->output |= CSI2_OUTPUT_CCDC;
} else {
csi2->output &= ~CSI2_OUTPUT_CCDC;
}
break;
default:
/* Link from camera to CSI2 is fixed... */
return -EINVAL;
}
ctrl->vp_only_enable =
(csi2->output & CSI2_OUTPUT_MEMORY) ? false : true;
ctrl->vp_clk_enable = !!(csi2->output & CSI2_OUTPUT_CCDC);
return 0;
}
/* media operations */
static const struct media_entity_operations csi2_media_ops = {
.link_setup = csi2_link_setup,
};
/*
* csi2_init_entities - Initialize subdev and media entity.
* @csi2: Pointer to csi2 structure.
* return -ENOMEM or zero on success
*/
static int csi2_init_entities(struct isp_csi2_device *csi2)
{
struct v4l2_subdev *sd = &csi2->subdev;
struct media_pad *pads = csi2->pads;
struct media_entity *me = &sd->entity;
int ret;
v4l2_subdev_init(sd, &csi2_ops);
sd->internal_ops = &csi2_internal_ops;
strlcpy(sd->name, "OMAP3 ISP CSI2a", sizeof(sd->name));
sd->grp_id = 1 << 16; /* group ID for isp subdevs */
v4l2_set_subdevdata(sd, csi2);
sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
pads[CSI2_PAD_SOURCE].flags = MEDIA_PAD_FL_SOURCE;
pads[CSI2_PAD_SINK].flags = MEDIA_PAD_FL_SINK;
me->ops = &csi2_media_ops;
ret = media_entity_init(me, CSI2_PADS_NUM, pads, 0);
if (ret < 0)
return ret;
csi2_init_formats(sd, NULL);
/* Video device node */
csi2->video_out.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
csi2->video_out.ops = &csi2_ispvideo_ops;
csi2->video_out.bpl_alignment = 32;
csi2->video_out.bpl_zero_padding = 1;
csi2->video_out.bpl_max = 0x1ffe0;
csi2->video_out.isp = csi2->isp;
csi2->video_out.capture_mem = PAGE_ALIGN(4096 * 4096) * 3;
ret = omap3isp_video_init(&csi2->video_out, "CSI2a");
if (ret < 0)
return ret;
/* Connect the CSI2 subdev to the video node. */
ret = media_entity_create_link(&csi2->subdev.entity, CSI2_PAD_SOURCE,
&csi2->video_out.video.entity, 0, 0);
if (ret < 0)
return ret;
return 0;
}
void omap3isp_csi2_unregister_entities(struct isp_csi2_device *csi2)
{
media_entity_cleanup(&csi2->subdev.entity);
v4l2_device_unregister_subdev(&csi2->subdev);
omap3isp_video_unregister(&csi2->video_out);
}
int omap3isp_csi2_register_entities(struct isp_csi2_device *csi2,
struct v4l2_device *vdev)
{
int ret;
/* Register the subdev and video nodes. */
ret = v4l2_device_register_subdev(vdev, &csi2->subdev);
if (ret < 0)
goto error;
ret = omap3isp_video_register(&csi2->video_out, vdev);
if (ret < 0)
goto error;
return 0;
error:
omap3isp_csi2_unregister_entities(csi2);
return ret;
}
/* -----------------------------------------------------------------------------
* ISP CSI2 initialisation and cleanup
*/
/*
* omap3isp_csi2_cleanup - Routine for module driver cleanup
*/
void omap3isp_csi2_cleanup(struct isp_device *isp)
{
}
/*
* omap3isp_csi2_init - Routine for module driver init
*/
int omap3isp_csi2_init(struct isp_device *isp)
{
struct isp_csi2_device *csi2a = &isp->isp_csi2a;
struct isp_csi2_device *csi2c = &isp->isp_csi2c;
int ret;
csi2a->isp = isp;
csi2a->available = 1;
csi2a->regs1 = OMAP3_ISP_IOMEM_CSI2A_REGS1;
csi2a->regs2 = OMAP3_ISP_IOMEM_CSI2A_REGS2;
csi2a->phy = &isp->isp_csiphy2;
csi2a->state = ISP_PIPELINE_STREAM_STOPPED;
init_waitqueue_head(&csi2a->wait);
ret = csi2_init_entities(csi2a);
if (ret < 0)
goto fail;
if (isp->revision == ISP_REVISION_15_0) {
csi2c->isp = isp;
csi2c->available = 1;
csi2c->regs1 = OMAP3_ISP_IOMEM_CSI2C_REGS1;
csi2c->regs2 = OMAP3_ISP_IOMEM_CSI2C_REGS2;
csi2c->phy = &isp->isp_csiphy1;
csi2c->state = ISP_PIPELINE_STREAM_STOPPED;
init_waitqueue_head(&csi2c->wait);
}
return 0;
fail:
omap3isp_csi2_cleanup(isp);
return ret;
}
| gpl-2.0 |
Motorhead1991/samsung_kernel_comanche | drivers/infiniband/hw/ipath/ipath_fs.c | 3195 | 9173 | /*
* Copyright (c) 2006, 2007 QLogic Corporation. All rights reserved.
* Copyright (c) 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 <linux/module.h>
#include <linux/fs.h>
#include <linux/mount.h>
#include <linux/pagemap.h>
#include <linux/init.h>
#include <linux/namei.h>
#include <linux/slab.h>
#include "ipath_kernel.h"
#define IPATHFS_MAGIC 0x726a77
static struct super_block *ipath_super;
static int ipathfs_mknod(struct inode *dir, struct dentry *dentry,
int mode, const struct file_operations *fops,
void *data)
{
int error;
struct inode *inode = new_inode(dir->i_sb);
if (!inode) {
error = -EPERM;
goto bail;
}
inode->i_ino = get_next_ino();
inode->i_mode = mode;
inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
inode->i_private = data;
if ((mode & S_IFMT) == S_IFDIR) {
inode->i_op = &simple_dir_inode_operations;
inc_nlink(inode);
inc_nlink(dir);
}
inode->i_fop = fops;
d_instantiate(dentry, inode);
error = 0;
bail:
return error;
}
static int create_file(const char *name, mode_t mode,
struct dentry *parent, struct dentry **dentry,
const struct file_operations *fops, void *data)
{
int error;
*dentry = NULL;
mutex_lock(&parent->d_inode->i_mutex);
*dentry = lookup_one_len(name, parent, strlen(name));
if (!IS_ERR(*dentry))
error = ipathfs_mknod(parent->d_inode, *dentry,
mode, fops, data);
else
error = PTR_ERR(dentry);
mutex_unlock(&parent->d_inode->i_mutex);
return error;
}
static ssize_t atomic_stats_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
return simple_read_from_buffer(buf, count, ppos, &ipath_stats,
sizeof ipath_stats);
}
static const struct file_operations atomic_stats_ops = {
.read = atomic_stats_read,
.llseek = default_llseek,
};
static ssize_t atomic_counters_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct infinipath_counters counters;
struct ipath_devdata *dd;
dd = file->f_path.dentry->d_inode->i_private;
dd->ipath_f_read_counters(dd, &counters);
return simple_read_from_buffer(buf, count, ppos, &counters,
sizeof counters);
}
static const struct file_operations atomic_counters_ops = {
.read = atomic_counters_read,
.llseek = default_llseek,
};
static ssize_t flash_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct ipath_devdata *dd;
ssize_t ret;
loff_t pos;
char *tmp;
pos = *ppos;
if ( pos < 0) {
ret = -EINVAL;
goto bail;
}
if (pos >= sizeof(struct ipath_flash)) {
ret = 0;
goto bail;
}
if (count > sizeof(struct ipath_flash) - pos)
count = sizeof(struct ipath_flash) - pos;
tmp = kmalloc(count, GFP_KERNEL);
if (!tmp) {
ret = -ENOMEM;
goto bail;
}
dd = file->f_path.dentry->d_inode->i_private;
if (ipath_eeprom_read(dd, pos, tmp, count)) {
ipath_dev_err(dd, "failed to read from flash\n");
ret = -ENXIO;
goto bail_tmp;
}
if (copy_to_user(buf, tmp, count)) {
ret = -EFAULT;
goto bail_tmp;
}
*ppos = pos + count;
ret = count;
bail_tmp:
kfree(tmp);
bail:
return ret;
}
static ssize_t flash_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct ipath_devdata *dd;
ssize_t ret;
loff_t pos;
char *tmp;
pos = *ppos;
if (pos != 0) {
ret = -EINVAL;
goto bail;
}
if (count != sizeof(struct ipath_flash)) {
ret = -EINVAL;
goto bail;
}
tmp = kmalloc(count, GFP_KERNEL);
if (!tmp) {
ret = -ENOMEM;
goto bail;
}
if (copy_from_user(tmp, buf, count)) {
ret = -EFAULT;
goto bail_tmp;
}
dd = file->f_path.dentry->d_inode->i_private;
if (ipath_eeprom_write(dd, pos, tmp, count)) {
ret = -ENXIO;
ipath_dev_err(dd, "failed to write to flash\n");
goto bail_tmp;
}
*ppos = pos + count;
ret = count;
bail_tmp:
kfree(tmp);
bail:
return ret;
}
static const struct file_operations flash_ops = {
.read = flash_read,
.write = flash_write,
.llseek = default_llseek,
};
static int create_device_files(struct super_block *sb,
struct ipath_devdata *dd)
{
struct dentry *dir, *tmp;
char unit[10];
int ret;
snprintf(unit, sizeof unit, "%02d", dd->ipath_unit);
ret = create_file(unit, S_IFDIR|S_IRUGO|S_IXUGO, sb->s_root, &dir,
&simple_dir_operations, dd);
if (ret) {
printk(KERN_ERR "create_file(%s) failed: %d\n", unit, ret);
goto bail;
}
ret = create_file("atomic_counters", S_IFREG|S_IRUGO, dir, &tmp,
&atomic_counters_ops, dd);
if (ret) {
printk(KERN_ERR "create_file(%s/atomic_counters) "
"failed: %d\n", unit, ret);
goto bail;
}
ret = create_file("flash", S_IFREG|S_IWUSR|S_IRUGO, dir, &tmp,
&flash_ops, dd);
if (ret) {
printk(KERN_ERR "create_file(%s/flash) "
"failed: %d\n", unit, ret);
goto bail;
}
bail:
return ret;
}
static int remove_file(struct dentry *parent, char *name)
{
struct dentry *tmp;
int ret;
tmp = lookup_one_len(name, parent, strlen(name));
if (IS_ERR(tmp)) {
ret = PTR_ERR(tmp);
goto bail;
}
spin_lock(&tmp->d_lock);
if (!(d_unhashed(tmp) && tmp->d_inode)) {
dget_dlock(tmp);
__d_drop(tmp);
spin_unlock(&tmp->d_lock);
simple_unlink(parent->d_inode, tmp);
} else
spin_unlock(&tmp->d_lock);
ret = 0;
bail:
/*
* We don't expect clients to care about the return value, but
* it's there if they need it.
*/
return ret;
}
static int remove_device_files(struct super_block *sb,
struct ipath_devdata *dd)
{
struct dentry *dir, *root;
char unit[10];
int ret;
root = dget(sb->s_root);
mutex_lock(&root->d_inode->i_mutex);
snprintf(unit, sizeof unit, "%02d", dd->ipath_unit);
dir = lookup_one_len(unit, root, strlen(unit));
if (IS_ERR(dir)) {
ret = PTR_ERR(dir);
printk(KERN_ERR "Lookup of %s failed\n", unit);
goto bail;
}
remove_file(dir, "flash");
remove_file(dir, "atomic_counters");
d_delete(dir);
ret = simple_rmdir(root->d_inode, dir);
bail:
mutex_unlock(&root->d_inode->i_mutex);
dput(root);
return ret;
}
static int ipathfs_fill_super(struct super_block *sb, void *data,
int silent)
{
struct ipath_devdata *dd, *tmp;
unsigned long flags;
int ret;
static struct tree_descr files[] = {
[2] = {"atomic_stats", &atomic_stats_ops, S_IRUGO},
{""},
};
ret = simple_fill_super(sb, IPATHFS_MAGIC, files);
if (ret) {
printk(KERN_ERR "simple_fill_super failed: %d\n", ret);
goto bail;
}
spin_lock_irqsave(&ipath_devs_lock, flags);
list_for_each_entry_safe(dd, tmp, &ipath_dev_list, ipath_list) {
spin_unlock_irqrestore(&ipath_devs_lock, flags);
ret = create_device_files(sb, dd);
if (ret)
goto bail;
spin_lock_irqsave(&ipath_devs_lock, flags);
}
spin_unlock_irqrestore(&ipath_devs_lock, flags);
bail:
return ret;
}
static struct dentry *ipathfs_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
struct dentry *ret;
ret = mount_single(fs_type, flags, data, ipathfs_fill_super);
if (!IS_ERR(ret))
ipath_super = ret->d_sb;
return ret;
}
static void ipathfs_kill_super(struct super_block *s)
{
kill_litter_super(s);
ipath_super = NULL;
}
int ipathfs_add_device(struct ipath_devdata *dd)
{
int ret;
if (ipath_super == NULL) {
ret = 0;
goto bail;
}
ret = create_device_files(ipath_super, dd);
bail:
return ret;
}
int ipathfs_remove_device(struct ipath_devdata *dd)
{
int ret;
if (ipath_super == NULL) {
ret = 0;
goto bail;
}
ret = remove_device_files(ipath_super, dd);
bail:
return ret;
}
static struct file_system_type ipathfs_fs_type = {
.owner = THIS_MODULE,
.name = "ipathfs",
.mount = ipathfs_mount,
.kill_sb = ipathfs_kill_super,
};
int __init ipath_init_ipathfs(void)
{
return register_filesystem(&ipathfs_fs_type);
}
void __exit ipath_exit_ipathfs(void)
{
unregister_filesystem(&ipathfs_fs_type);
}
| gpl-2.0 |
holyangel/HTC_M8_GPE-4.4.3 | kernel/irq/pm.c | 3451 | 3119 | /*
* linux/kernel/irq/pm.c
*
* Copyright (C) 2009 Rafael J. Wysocki <rjw@sisk.pl>, Novell Inc.
*
* This file contains power management functions related to interrupts.
*/
#include <linux/irq.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/syscore_ops.h>
#include "internals.h"
/**
* suspend_device_irqs - disable all currently enabled interrupt lines
*
* During system-wide suspend or hibernation device drivers need to be prevented
* from receiving interrupts and this function is provided for this purpose.
* It marks all interrupt lines in use, except for the timer ones, as disabled
* and sets the IRQS_SUSPENDED flag for each of them.
*/
void suspend_device_irqs(void)
{
struct irq_desc *desc;
int irq;
for_each_irq_desc(irq, desc) {
unsigned long flags;
raw_spin_lock_irqsave(&desc->lock, flags);
__disable_irq(desc, irq, true);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
for_each_irq_desc(irq, desc)
if (desc->istate & IRQS_SUSPENDED)
synchronize_irq(irq);
}
EXPORT_SYMBOL_GPL(suspend_device_irqs);
static void resume_irqs(bool want_early)
{
struct irq_desc *desc;
int irq;
for_each_irq_desc_reverse(irq, desc) {
unsigned long flags;
bool is_early = desc->action &&
desc->action->flags & IRQF_EARLY_RESUME;
if (is_early != want_early)
continue;
raw_spin_lock_irqsave(&desc->lock, flags);
__enable_irq(desc, irq, true);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
/**
* irq_pm_syscore_ops - enable interrupt lines early
*
* Enable all interrupt lines with %IRQF_EARLY_RESUME set.
*/
static void irq_pm_syscore_resume(void)
{
resume_irqs(true);
}
static struct syscore_ops irq_pm_syscore_ops = {
.resume = irq_pm_syscore_resume,
};
static int __init irq_pm_init_ops(void)
{
register_syscore_ops(&irq_pm_syscore_ops);
return 0;
}
device_initcall(irq_pm_init_ops);
/**
* resume_device_irqs - enable interrupt lines disabled by suspend_device_irqs()
*
* Enable all non-%IRQF_EARLY_RESUME interrupt lines previously
* disabled by suspend_device_irqs() that have the IRQS_SUSPENDED flag
* set as well as those with %IRQF_FORCE_RESUME.
*/
void resume_device_irqs(void)
{
resume_irqs(false);
}
EXPORT_SYMBOL_GPL(resume_device_irqs);
/**
* check_wakeup_irqs - check if any wake-up interrupts are pending
*/
int check_wakeup_irqs(void)
{
struct irq_desc *desc;
int irq;
for_each_irq_desc(irq, desc) {
if (irqd_is_wakeup_set(&desc->irq_data)) {
if (desc->istate & IRQS_PENDING) {
pr_info("Wakeup IRQ %d %s pending, suspend aborted\n",
irq,
desc->action && desc->action->name ?
desc->action->name : "");
return -EBUSY;
}
continue;
}
/*
* Check the non wakeup interrupts whether they need
* to be masked before finally going into suspend
* state. That's for hardware which has no wakeup
* source configuration facility. The chip
* implementation indicates that with
* IRQCHIP_MASK_ON_SUSPEND.
*/
if (desc->istate & IRQS_SUSPENDED &&
irq_desc_get_chip(desc)->flags & IRQCHIP_MASK_ON_SUSPEND)
mask_irq(desc);
}
return 0;
}
| gpl-2.0 |
pitah81/android_kernel_elephone_p8000 | lib/decompress_unlzo.c | 3963 | 6970 | /*
* LZO decompressor for the Linux kernel. Code borrowed from the lzo
* implementation by Markus Franz Xaver Johannes Oberhumer.
*
* Linux kernel adaptation:
* Copyright (C) 2009
* Albin Tonnerre, Free Electrons <albin.tonnerre@free-electrons.com>
*
* Original code:
* Copyright (C) 1996-2005 Markus Franz Xaver Johannes Oberhumer
* All Rights Reserved.
*
* lzop and the LZO library are free software; you can redistribute them
* and/or modify them 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; see the file COPYING.
* If not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Markus F.X.J. Oberhumer
* <markus@oberhumer.com>
* http://www.oberhumer.com/opensource/lzop/
*/
#ifdef STATIC
#include "lzo/lzo1x_decompress_safe.c"
#else
#include <linux/decompress/unlzo.h>
#endif
#include <linux/types.h>
#include <linux/lzo.h>
#include <linux/decompress/mm.h>
#include <linux/compiler.h>
#include <asm/unaligned.h>
static const unsigned char lzop_magic[] = {
0x89, 0x4c, 0x5a, 0x4f, 0x00, 0x0d, 0x0a, 0x1a, 0x0a };
#define LZO_BLOCK_SIZE (256*1024l)
#define HEADER_HAS_FILTER 0x00000800L
#define HEADER_SIZE_MIN (9 + 7 + 4 + 8 + 1 + 4)
#define HEADER_SIZE_MAX (9 + 7 + 1 + 8 + 8 + 4 + 1 + 255 + 4)
STATIC inline int INIT parse_header(u8 *input, int *skip, int in_len)
{
int l;
u8 *parse = input;
u8 *end = input + in_len;
u8 level = 0;
u16 version;
/*
* Check that there's enough input to possibly have a valid header.
* Then it is possible to parse several fields until the minimum
* size may have been used.
*/
if (in_len < HEADER_SIZE_MIN)
return 0;
/* read magic: 9 first bits */
for (l = 0; l < 9; l++) {
if (*parse++ != lzop_magic[l])
return 0;
}
/* get version (2bytes), skip library version (2),
* 'need to be extracted' version (2) and
* method (1) */
version = get_unaligned_be16(parse);
parse += 7;
if (version >= 0x0940)
level = *parse++;
if (get_unaligned_be32(parse) & HEADER_HAS_FILTER)
parse += 8; /* flags + filter info */
else
parse += 4; /* flags */
/*
* At least mode, mtime_low, filename length, and checksum must
* be left to be parsed. If also mtime_high is present, it's OK
* because the next input buffer check is after reading the
* filename length.
*/
if (end - parse < 8 + 1 + 4)
return 0;
/* skip mode and mtime_low */
parse += 8;
if (version >= 0x0940)
parse += 4; /* skip mtime_high */
l = *parse++;
/* don't care about the file name, and skip checksum */
if (end - parse < l + 4)
return 0;
parse += l + 4;
*skip = parse - input;
return 1;
}
STATIC inline int INIT unlzo(u8 *input, int in_len,
int (*fill) (void *, unsigned int),
int (*flush) (void *, unsigned int),
u8 *output, int *posp,
void (*error) (char *x))
{
u8 r = 0;
int skip = 0;
u32 src_len, dst_len;
size_t tmp;
u8 *in_buf, *in_buf_save, *out_buf;
int ret = -1;
if (output) {
out_buf = output;
} else if (!flush) {
error("NULL output pointer and no flush function provided");
goto exit;
} else {
out_buf = malloc(LZO_BLOCK_SIZE);
if (!out_buf) {
error("Could not allocate output buffer");
goto exit;
}
}
if (input && fill) {
error("Both input pointer and fill function provided, don't know what to do");
goto exit_1;
} else if (input) {
in_buf = input;
} else if (!fill) {
error("NULL input pointer and missing fill function");
goto exit_1;
} else {
in_buf = malloc(lzo1x_worst_compress(LZO_BLOCK_SIZE));
if (!in_buf) {
error("Could not allocate input buffer");
goto exit_1;
}
}
in_buf_save = in_buf;
if (posp)
*posp = 0;
if (fill) {
/*
* Start from in_buf + HEADER_SIZE_MAX to make it possible
* to use memcpy() to copy the unused data to the beginning
* of the buffer. This way memmove() isn't needed which
* is missing from pre-boot environments of most archs.
*/
in_buf += HEADER_SIZE_MAX;
in_len = fill(in_buf, HEADER_SIZE_MAX);
}
if (!parse_header(in_buf, &skip, in_len)) {
error("invalid header");
goto exit_2;
}
in_buf += skip;
in_len -= skip;
if (fill) {
/* Move the unused data to the beginning of the buffer. */
memcpy(in_buf_save, in_buf, in_len);
in_buf = in_buf_save;
}
if (posp)
*posp = skip;
for (;;) {
/* read uncompressed block size */
if (fill && in_len < 4) {
skip = fill(in_buf + in_len, 4 - in_len);
if (skip > 0)
in_len += skip;
}
if (in_len < 4) {
error("file corrupted");
goto exit_2;
}
dst_len = get_unaligned_be32(in_buf);
in_buf += 4;
in_len -= 4;
/* exit if last block */
if (dst_len == 0) {
if (posp)
*posp += 4;
break;
}
if (dst_len > LZO_BLOCK_SIZE) {
error("dest len longer than block size");
goto exit_2;
}
/* read compressed block size, and skip block checksum info */
if (fill && in_len < 8) {
skip = fill(in_buf + in_len, 8 - in_len);
if (skip > 0)
in_len += skip;
}
if (in_len < 8) {
error("file corrupted");
goto exit_2;
}
src_len = get_unaligned_be32(in_buf);
in_buf += 8;
in_len -= 8;
if (src_len <= 0 || src_len > dst_len) {
error("file corrupted");
goto exit_2;
}
/* decompress */
if (fill && in_len < src_len) {
skip = fill(in_buf + in_len, src_len - in_len);
if (skip > 0)
in_len += skip;
}
if (in_len < src_len) {
error("file corrupted");
goto exit_2;
}
tmp = dst_len;
/* When the input data is not compressed at all,
* lzo1x_decompress_safe will fail, so call memcpy()
* instead */
if (unlikely(dst_len == src_len))
memcpy(out_buf, in_buf, src_len);
else {
r = lzo1x_decompress_safe((u8 *) in_buf, src_len,
out_buf, &tmp);
if (r != LZO_E_OK || dst_len != tmp) {
error("Compressed data violation");
goto exit_2;
}
}
if (flush && flush(out_buf, dst_len) != dst_len)
goto exit_2;
if (output)
out_buf += dst_len;
if (posp)
*posp += src_len + 12;
in_buf += src_len;
in_len -= src_len;
if (fill) {
/*
* If there happens to still be unused data left in
* in_buf, move it to the beginning of the buffer.
* Use a loop to avoid memmove() dependency.
*/
if (in_len > 0)
for (skip = 0; skip < in_len; ++skip)
in_buf_save[skip] = in_buf[skip];
in_buf = in_buf_save;
}
}
ret = 0;
exit_2:
if (!input)
free(in_buf_save);
exit_1:
if (!output)
free(out_buf);
exit:
return ret;
}
#define decompress unlzo
| gpl-2.0 |
touchpro/android_kernel_lge_msm8226 | drivers/usb/host/ohci-pci.c | 4219 | 10297 | /*
* OHCI HCD (Host Controller Driver) for USB.
*
* (C) Copyright 1999 Roman Weissgaerber <weissg@vienna.at>
* (C) Copyright 2000-2002 David Brownell <dbrownell@users.sourceforge.net>
*
* [ Initialisation is based on Linus' ]
* [ uhci code and gregs ohci fragments ]
* [ (C) Copyright 1999 Linus Torvalds ]
* [ (C) Copyright 1999 Gregory P. Smith]
*
* PCI Bus Glue
*
* This file is licenced under the GPL.
*/
#ifndef CONFIG_PCI
#error "This file is PCI bus glue. CONFIG_PCI must be defined."
#endif
#include <linux/pci.h>
#include <linux/io.h>
/*-------------------------------------------------------------------------*/
static int broken_suspend(struct usb_hcd *hcd)
{
device_init_wakeup(&hcd->self.root_hub->dev, 0);
return 0;
}
/* AMD 756, for most chips (early revs), corrupts register
* values on read ... so enable the vendor workaround.
*/
static int ohci_quirk_amd756(struct usb_hcd *hcd)
{
struct ohci_hcd *ohci = hcd_to_ohci (hcd);
ohci->flags = OHCI_QUIRK_AMD756;
ohci_dbg (ohci, "AMD756 erratum 4 workaround\n");
/* also erratum 10 (suspend/resume issues) */
return broken_suspend(hcd);
}
/* Apple's OHCI driver has a lot of bizarre workarounds
* for this chip. Evidently control and bulk lists
* can get confused. (B&W G3 models, and ...)
*/
static int ohci_quirk_opti(struct usb_hcd *hcd)
{
struct ohci_hcd *ohci = hcd_to_ohci (hcd);
ohci_dbg (ohci, "WARNING: OPTi workarounds unavailable\n");
return 0;
}
/* Check for NSC87560. We have to look at the bridge (fn1) to
* identify the USB (fn2). This quirk might apply to more or
* even all NSC stuff.
*/
static int ohci_quirk_ns(struct usb_hcd *hcd)
{
struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
struct pci_dev *b;
b = pci_get_slot (pdev->bus, PCI_DEVFN (PCI_SLOT (pdev->devfn), 1));
if (b && b->device == PCI_DEVICE_ID_NS_87560_LIO
&& b->vendor == PCI_VENDOR_ID_NS) {
struct ohci_hcd *ohci = hcd_to_ohci (hcd);
ohci->flags |= OHCI_QUIRK_SUPERIO;
ohci_dbg (ohci, "Using NSC SuperIO setup\n");
}
pci_dev_put(b);
return 0;
}
/* Check for Compaq's ZFMicro chipset, which needs short
* delays before control or bulk queues get re-activated
* in finish_unlinks()
*/
static int ohci_quirk_zfmicro(struct usb_hcd *hcd)
{
struct ohci_hcd *ohci = hcd_to_ohci (hcd);
ohci->flags |= OHCI_QUIRK_ZFMICRO;
ohci_dbg(ohci, "enabled Compaq ZFMicro chipset quirks\n");
return 0;
}
/* Check for Toshiba SCC OHCI which has big endian registers
* and little endian in memory data structures
*/
static int ohci_quirk_toshiba_scc(struct usb_hcd *hcd)
{
struct ohci_hcd *ohci = hcd_to_ohci (hcd);
/* That chip is only present in the southbridge of some
* cell based platforms which are supposed to select
* CONFIG_USB_OHCI_BIG_ENDIAN_MMIO. We verify here if
* that was the case though.
*/
#ifdef CONFIG_USB_OHCI_BIG_ENDIAN_MMIO
ohci->flags |= OHCI_QUIRK_BE_MMIO;
ohci_dbg (ohci, "enabled big endian Toshiba quirk\n");
return 0;
#else
ohci_err (ohci, "unsupported big endian Toshiba quirk\n");
return -ENXIO;
#endif
}
/* Check for NEC chip and apply quirk for allegedly lost interrupts.
*/
static void ohci_quirk_nec_worker(struct work_struct *work)
{
struct ohci_hcd *ohci = container_of(work, struct ohci_hcd, nec_work);
int status;
status = ohci_init(ohci);
if (status != 0) {
ohci_err(ohci, "Restarting NEC controller failed in %s, %d\n",
"ohci_init", status);
return;
}
status = ohci_restart(ohci);
if (status != 0)
ohci_err(ohci, "Restarting NEC controller failed in %s, %d\n",
"ohci_restart", status);
}
static int ohci_quirk_nec(struct usb_hcd *hcd)
{
struct ohci_hcd *ohci = hcd_to_ohci (hcd);
ohci->flags |= OHCI_QUIRK_NEC;
INIT_WORK(&ohci->nec_work, ohci_quirk_nec_worker);
ohci_dbg (ohci, "enabled NEC chipset lost interrupt quirk\n");
return 0;
}
static int ohci_quirk_amd700(struct usb_hcd *hcd)
{
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
struct pci_dev *amd_smbus_dev;
u8 rev;
if (usb_amd_find_chipset_info())
ohci->flags |= OHCI_QUIRK_AMD_PLL;
amd_smbus_dev = pci_get_device(PCI_VENDOR_ID_ATI,
PCI_DEVICE_ID_ATI_SBX00_SMBUS, NULL);
if (!amd_smbus_dev)
return 0;
rev = amd_smbus_dev->revision;
/* SB800 needs pre-fetch fix */
if ((rev >= 0x40) && (rev <= 0x4f)) {
ohci->flags |= OHCI_QUIRK_AMD_PREFETCH;
ohci_dbg(ohci, "enabled AMD prefetch quirk\n");
}
pci_dev_put(amd_smbus_dev);
amd_smbus_dev = NULL;
return 0;
}
static void sb800_prefetch(struct ohci_hcd *ohci, int on)
{
struct pci_dev *pdev;
u16 misc;
pdev = to_pci_dev(ohci_to_hcd(ohci)->self.controller);
pci_read_config_word(pdev, 0x50, &misc);
if (on == 0)
pci_write_config_word(pdev, 0x50, misc & 0xfcff);
else
pci_write_config_word(pdev, 0x50, misc | 0x0300);
}
/* List of quirks for OHCI */
static const struct pci_device_id ohci_pci_quirks[] = {
{
PCI_DEVICE(PCI_VENDOR_ID_AMD, 0x740c),
.driver_data = (unsigned long)ohci_quirk_amd756,
},
{
PCI_DEVICE(PCI_VENDOR_ID_OPTI, 0xc861),
.driver_data = (unsigned long)ohci_quirk_opti,
},
{
PCI_DEVICE(PCI_VENDOR_ID_NS, PCI_ANY_ID),
.driver_data = (unsigned long)ohci_quirk_ns,
},
{
PCI_DEVICE(PCI_VENDOR_ID_COMPAQ, 0xa0f8),
.driver_data = (unsigned long)ohci_quirk_zfmicro,
},
{
PCI_DEVICE(PCI_VENDOR_ID_TOSHIBA_2, 0x01b6),
.driver_data = (unsigned long)ohci_quirk_toshiba_scc,
},
{
PCI_DEVICE(PCI_VENDOR_ID_NEC, PCI_DEVICE_ID_NEC_USB),
.driver_data = (unsigned long)ohci_quirk_nec,
},
{
/* Toshiba portege 4000 */
.vendor = PCI_VENDOR_ID_AL,
.device = 0x5237,
.subvendor = PCI_VENDOR_ID_TOSHIBA,
.subdevice = 0x0004,
.driver_data = (unsigned long) broken_suspend,
},
{
PCI_DEVICE(PCI_VENDOR_ID_ITE, 0x8152),
.driver_data = (unsigned long) broken_suspend,
},
{
PCI_DEVICE(PCI_VENDOR_ID_ATI, 0x4397),
.driver_data = (unsigned long)ohci_quirk_amd700,
},
{
PCI_DEVICE(PCI_VENDOR_ID_ATI, 0x4398),
.driver_data = (unsigned long)ohci_quirk_amd700,
},
{
PCI_DEVICE(PCI_VENDOR_ID_ATI, 0x4399),
.driver_data = (unsigned long)ohci_quirk_amd700,
},
/* FIXME for some of the early AMD 760 southbridges, OHCI
* won't work at all. blacklist them.
*/
{},
};
static int ohci_pci_reset (struct usb_hcd *hcd)
{
struct ohci_hcd *ohci = hcd_to_ohci (hcd);
int ret = 0;
if (hcd->self.controller) {
struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
const struct pci_device_id *quirk_id;
quirk_id = pci_match_id(ohci_pci_quirks, pdev);
if (quirk_id != NULL) {
int (*quirk)(struct usb_hcd *ohci);
quirk = (void *)quirk_id->driver_data;
ret = quirk(hcd);
}
}
if (ret == 0) {
ohci_hcd_init (ohci);
return ohci_init (ohci);
}
return ret;
}
static int __devinit ohci_pci_start (struct usb_hcd *hcd)
{
struct ohci_hcd *ohci = hcd_to_ohci (hcd);
int ret;
#ifdef CONFIG_PM /* avoid warnings about unused pdev */
if (hcd->self.controller) {
struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
/* RWC may not be set for add-in PCI cards, since boot
* firmware probably ignored them. This transfers PCI
* PM wakeup capabilities.
*/
if (device_can_wakeup(&pdev->dev))
ohci->hc_control |= OHCI_CTRL_RWC;
}
#endif /* CONFIG_PM */
ret = ohci_run (ohci);
if (ret < 0) {
ohci_err (ohci, "can't start\n");
ohci_stop (hcd);
}
return ret;
}
#ifdef CONFIG_PM
static int ohci_pci_suspend(struct usb_hcd *hcd, bool do_wakeup)
{
struct ohci_hcd *ohci = hcd_to_ohci (hcd);
unsigned long flags;
int rc = 0;
/* Root hub was already suspended. Disable irq emission and
* mark HW unaccessible, bail out if RH has been resumed. Use
* the spinlock to properly synchronize with possible pending
* RH suspend or resume activity.
*/
spin_lock_irqsave (&ohci->lock, flags);
if (ohci->rh_state != OHCI_RH_SUSPENDED) {
rc = -EINVAL;
goto bail;
}
ohci_writel(ohci, OHCI_INTR_MIE, &ohci->regs->intrdisable);
(void)ohci_readl(ohci, &ohci->regs->intrdisable);
clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
bail:
spin_unlock_irqrestore (&ohci->lock, flags);
return rc;
}
static int ohci_pci_resume(struct usb_hcd *hcd, bool hibernated)
{
set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
/* Make sure resume from hibernation re-enumerates everything */
if (hibernated)
ohci_usb_reset(hcd_to_ohci(hcd));
ohci_finish_controller_resume(hcd);
return 0;
}
#endif /* CONFIG_PM */
/*-------------------------------------------------------------------------*/
static const struct hc_driver ohci_pci_hc_driver = {
.description = hcd_name,
.product_desc = "OHCI Host Controller",
.hcd_priv_size = sizeof(struct ohci_hcd),
/*
* generic hardware linkage
*/
.irq = ohci_irq,
.flags = HCD_MEMORY | HCD_USB11,
/*
* basic lifecycle operations
*/
.reset = ohci_pci_reset,
.start = ohci_pci_start,
.stop = ohci_stop,
.shutdown = ohci_shutdown,
#ifdef CONFIG_PM
.pci_suspend = ohci_pci_suspend,
.pci_resume = ohci_pci_resume,
#endif
/*
* managing i/o requests and associated device resources
*/
.urb_enqueue = ohci_urb_enqueue,
.urb_dequeue = ohci_urb_dequeue,
.endpoint_disable = ohci_endpoint_disable,
/*
* scheduling support
*/
.get_frame_number = ohci_get_frame,
/*
* root hub support
*/
.hub_status_data = ohci_hub_status_data,
.hub_control = ohci_hub_control,
#ifdef CONFIG_PM
.bus_suspend = ohci_bus_suspend,
.bus_resume = ohci_bus_resume,
#endif
.start_port_reset = ohci_start_port_reset,
};
/*-------------------------------------------------------------------------*/
static const struct pci_device_id pci_ids [] = { {
/* handle any USB OHCI controller */
PCI_DEVICE_CLASS(PCI_CLASS_SERIAL_USB_OHCI, ~0),
.driver_data = (unsigned long) &ohci_pci_hc_driver,
}, {
/* The device in the ConneXT I/O hub has no class reg */
PCI_VDEVICE(STMICRO, PCI_DEVICE_ID_STMICRO_USB_OHCI),
.driver_data = (unsigned long) &ohci_pci_hc_driver,
}, { /* end: all zeroes */ }
};
MODULE_DEVICE_TABLE (pci, pci_ids);
/* pci driver glue; this is a "new style" PCI driver module */
static struct pci_driver ohci_pci_driver = {
.name = (char *) hcd_name,
.id_table = pci_ids,
.probe = usb_hcd_pci_probe,
.remove = usb_hcd_pci_remove,
.shutdown = usb_hcd_pci_shutdown,
#ifdef CONFIG_PM_SLEEP
.driver = {
.pm = &usb_hcd_pci_pm_ops
},
#endif
};
| gpl-2.0 |
MoKee/android_kernel_huawei_msm8928 | arch/arm/mach-pxa/stargate2.c | 4731 | 24175 | /*
* linux/arch/arm/mach-pxa/stargate2.c
*
* Author: Ed C. Epp
* Created: Nov 05, 2002
* Copyright: Intel Corp.
*
* Modified 2009: Jonathan Cameron <jic23@cam.ac.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/device.h>
#include <linux/interrupt.h>
#include <linux/sched.h>
#include <linux/bitops.h>
#include <linux/fb.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/regulator/machine.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/plat-ram.h>
#include <linux/mtd/partitions.h>
#include <linux/i2c/pxa-i2c.h>
#include <linux/i2c/pcf857x.h>
#include <linux/i2c/at24.h>
#include <linux/smc91x.h>
#include <linux/gpio.h>
#include <linux/leds.h>
#include <asm/types.h>
#include <asm/setup.h>
#include <asm/memory.h>
#include <asm/mach-types.h>
#include <asm/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <asm/mach/flash.h>
#include <mach/pxa27x.h>
#include <mach/mmc.h>
#include <mach/udc.h>
#include <mach/pxa27x-udc.h>
#include <mach/smemc.h>
#include <linux/spi/spi.h>
#include <linux/spi/pxa2xx_spi.h>
#include <linux/mfd/da903x.h>
#include <linux/sht15.h>
#include "devices.h"
#include "generic.h"
#define STARGATE_NR_IRQS (IRQ_BOARD_START + 8)
/* Bluetooth */
#define SG2_BT_RESET 81
/* SD */
#define SG2_GPIO_nSD_DETECT 90
#define SG2_SD_POWER_ENABLE 89
static unsigned long sg2_im2_unified_pin_config[] __initdata = {
/* Device Identification for wakeup*/
GPIO102_GPIO,
/* DA9030 */
GPIO1_GPIO,
/* MMC */
GPIO32_MMC_CLK,
GPIO112_MMC_CMD,
GPIO92_MMC_DAT_0,
GPIO109_MMC_DAT_1,
GPIO110_MMC_DAT_2,
GPIO111_MMC_DAT_3,
/* 802.15.4 radio - driver out of mainline */
GPIO22_GPIO, /* CC_RSTN */
GPIO114_GPIO, /* CC_FIFO */
GPIO116_GPIO, /* CC_CCA */
GPIO0_GPIO, /* CC_FIFOP */
GPIO16_GPIO, /* CCSFD */
GPIO115_GPIO, /* Power enable */
/* I2C */
GPIO117_I2C_SCL,
GPIO118_I2C_SDA,
/* SSP 3 - 802.15.4 radio */
GPIO39_GPIO, /* Chip Select */
GPIO34_SSP3_SCLK,
GPIO35_SSP3_TXD,
GPIO41_SSP3_RXD,
/* SSP 2 to daughter boards */
GPIO11_SSP2_RXD,
GPIO38_SSP2_TXD,
GPIO36_SSP2_SCLK,
GPIO37_GPIO, /* chip select */
/* SSP 1 - to daughter boards */
GPIO24_GPIO, /* Chip Select */
GPIO23_SSP1_SCLK,
GPIO25_SSP1_TXD,
GPIO26_SSP1_RXD,
/* BTUART Basic Connector*/
GPIO42_BTUART_RXD,
GPIO43_BTUART_TXD,
GPIO44_BTUART_CTS,
GPIO45_BTUART_RTS,
/* STUART - IM2 via debug board not sure on SG2*/
GPIO46_STUART_RXD,
GPIO47_STUART_TXD,
/* Basic sensor board */
GPIO96_GPIO, /* accelerometer interrupt */
GPIO99_GPIO, /* ADC interrupt */
/* SHT15 */
GPIO100_GPIO,
GPIO98_GPIO,
/* Basic sensor board */
GPIO96_GPIO, /* accelerometer interrupt */
GPIO99_GPIO, /* ADC interrupt */
/* Connector pins specified as gpios */
GPIO94_GPIO, /* large basic connector pin 14 */
GPIO10_GPIO, /* large basic connector pin 23 */
};
static struct sht15_platform_data platform_data_sht15 = {
.gpio_data = 100,
.gpio_sck = 98,
};
static struct platform_device sht15 = {
.name = "sht15",
.id = -1,
.dev = {
.platform_data = &platform_data_sht15,
},
};
static struct regulator_consumer_supply stargate2_sensor_3_con[] = {
{
.dev_name = "sht15",
.supply = "vcc",
},
};
enum stargate2_ldos{
vcc_vref,
vcc_cc2420,
/* a mote connector? */
vcc_mica,
/* the CSR bluecore chip */
vcc_bt,
/* The two voltages available to sensor boards */
vcc_sensor_1_8,
vcc_sensor_3,
/* directly connected to the pxa27x */
vcc_sram_ext,
vcc_pxa_pll,
vcc_pxa_usim, /* Reference voltage for certain gpios */
vcc_pxa_mem,
vcc_pxa_flash,
vcc_pxa_core, /*Dc-Dc buck not yet supported */
vcc_lcd,
vcc_bb,
vcc_bbio, /*not sure!*/
vcc_io, /* cc2420 802.15.4 radio and pxa vcc_io ?*/
};
/* The values of the various regulator constraints are obviously dependent
* on exactly what is wired to each ldo. Unfortunately this information is
* not generally available. More information has been requested from Xbow.
*/
static struct regulator_init_data stargate2_ldo_init_data[] = {
[vcc_bbio] = {
.constraints = { /* board default 1.8V */
.name = "vcc_bbio",
.min_uV = 1800000,
.max_uV = 1800000,
},
},
[vcc_bb] = {
.constraints = { /* board default 2.8V */
.name = "vcc_bb",
.min_uV = 2700000,
.max_uV = 3000000,
},
},
[vcc_pxa_flash] = {
.constraints = {/* default is 1.8V */
.name = "vcc_pxa_flash",
.min_uV = 1800000,
.max_uV = 1800000,
},
},
[vcc_cc2420] = { /* also vcc_io */
.constraints = {
/* board default is 2.8V */
.name = "vcc_cc2420",
.min_uV = 2700000,
.max_uV = 3300000,
},
},
[vcc_vref] = { /* Reference for what? */
.constraints = { /* default 1.8V */
.name = "vcc_vref",
.min_uV = 1800000,
.max_uV = 1800000,
},
},
[vcc_sram_ext] = {
.constraints = { /* default 2.8V */
.name = "vcc_sram_ext",
.min_uV = 2800000,
.max_uV = 2800000,
},
},
[vcc_mica] = {
.constraints = { /* default 2.8V */
.name = "vcc_mica",
.min_uV = 2800000,
.max_uV = 2800000,
},
},
[vcc_bt] = {
.constraints = { /* default 2.8V */
.name = "vcc_bt",
.min_uV = 2800000,
.max_uV = 2800000,
},
},
[vcc_lcd] = {
.constraints = { /* default 2.8V */
.name = "vcc_lcd",
.min_uV = 2700000,
.max_uV = 3300000,
},
},
[vcc_io] = { /* Same or higher than everything
* bar vccbat and vccusb */
.constraints = { /* default 2.8V */
.name = "vcc_io",
.min_uV = 2692000,
.max_uV = 3300000,
},
},
[vcc_sensor_1_8] = {
.constraints = { /* default 1.8V */
.name = "vcc_sensor_1_8",
.min_uV = 1800000,
.max_uV = 1800000,
},
},
[vcc_sensor_3] = { /* curiously default 2.8V */
.constraints = {
.name = "vcc_sensor_3",
.min_uV = 2800000,
.max_uV = 3000000,
},
.num_consumer_supplies = ARRAY_SIZE(stargate2_sensor_3_con),
.consumer_supplies = stargate2_sensor_3_con,
},
[vcc_pxa_pll] = { /* 1.17V - 1.43V, default 1.3V*/
.constraints = {
.name = "vcc_pxa_pll",
.min_uV = 1170000,
.max_uV = 1430000,
},
},
[vcc_pxa_usim] = {
.constraints = { /* default 1.8V */
.name = "vcc_pxa_usim",
.min_uV = 1710000,
.max_uV = 2160000,
},
},
[vcc_pxa_mem] = {
.constraints = { /* default 1.8V */
.name = "vcc_pxa_mem",
.min_uV = 1800000,
.max_uV = 1800000,
},
},
};
static struct mtd_partition stargate2flash_partitions[] = {
{
.name = "Bootloader",
.size = 0x00040000,
.offset = 0,
.mask_flags = 0,
}, {
.name = "Kernel",
.size = 0x00200000,
.offset = 0x00040000,
.mask_flags = 0
}, {
.name = "Filesystem",
.size = 0x01DC0000,
.offset = 0x00240000,
.mask_flags = 0
},
};
static struct resource flash_resources = {
.start = PXA_CS0_PHYS,
.end = PXA_CS0_PHYS + SZ_32M - 1,
.flags = IORESOURCE_MEM,
};
static struct flash_platform_data stargate2_flash_data = {
.map_name = "cfi_probe",
.parts = stargate2flash_partitions,
.nr_parts = ARRAY_SIZE(stargate2flash_partitions),
.name = "PXA27xOnChipROM",
.width = 2,
};
static struct platform_device stargate2_flash_device = {
.name = "pxa2xx-flash",
.id = 0,
.dev = {
.platform_data = &stargate2_flash_data,
},
.resource = &flash_resources,
.num_resources = 1,
};
static struct pxa2xx_spi_master pxa_ssp_master_0_info = {
.num_chipselect = 1,
};
static struct pxa2xx_spi_master pxa_ssp_master_1_info = {
.num_chipselect = 1,
};
static struct pxa2xx_spi_master pxa_ssp_master_2_info = {
.num_chipselect = 1,
};
/* An upcoming kernel change will scrap SFRM usage so these
* drivers have been moved to use gpio's via cs_control */
static struct pxa2xx_spi_chip staccel_chip_info = {
.tx_threshold = 8,
.rx_threshold = 8,
.dma_burst_size = 8,
.timeout = 235,
.gpio_cs = 24,
};
static struct pxa2xx_spi_chip cc2420_info = {
.tx_threshold = 8,
.rx_threshold = 8,
.dma_burst_size = 8,
.timeout = 235,
.gpio_cs = 39,
};
static struct spi_board_info spi_board_info[] __initdata = {
{
.modalias = "lis3l02dq",
.max_speed_hz = 8000000,/* 8MHz max spi frequency at 3V */
.bus_num = 1,
.chip_select = 0,
.controller_data = &staccel_chip_info,
.irq = PXA_GPIO_TO_IRQ(96),
}, {
.modalias = "cc2420",
.max_speed_hz = 6500000,
.bus_num = 3,
.chip_select = 0,
.controller_data = &cc2420_info,
},
};
static void sg2_udc_command(int cmd)
{
switch (cmd) {
case PXA2XX_UDC_CMD_CONNECT:
UP2OCR |= UP2OCR_HXOE | UP2OCR_DPPUE | UP2OCR_DPPUBE;
break;
case PXA2XX_UDC_CMD_DISCONNECT:
UP2OCR &= ~(UP2OCR_HXOE | UP2OCR_DPPUE | UP2OCR_DPPUBE);
break;
}
}
static struct i2c_pxa_platform_data i2c_pwr_pdata = {
.fast_mode = 1,
};
static struct i2c_pxa_platform_data i2c_pdata = {
.fast_mode = 1,
};
static void __init imote2_stargate2_init(void)
{
pxa2xx_mfp_config(ARRAY_AND_SIZE(sg2_im2_unified_pin_config));
pxa_set_ffuart_info(NULL);
pxa_set_btuart_info(NULL);
pxa_set_stuart_info(NULL);
pxa2xx_set_spi_info(1, &pxa_ssp_master_0_info);
pxa2xx_set_spi_info(2, &pxa_ssp_master_1_info);
pxa2xx_set_spi_info(3, &pxa_ssp_master_2_info);
spi_register_board_info(spi_board_info, ARRAY_SIZE(spi_board_info));
pxa27x_set_i2c_power_info(&i2c_pwr_pdata);
pxa_set_i2c_info(&i2c_pdata);
}
#ifdef CONFIG_MACH_INTELMOTE2
/* As the the imote2 doesn't currently have a conventional SD slot
* there is no option to hotplug cards, making all this rather simple
*/
static int imote2_mci_get_ro(struct device *dev)
{
return 0;
}
/* Rather simple case as hotplugging not possible */
static struct pxamci_platform_data imote2_mci_platform_data = {
.ocr_mask = MMC_VDD_32_33 | MMC_VDD_33_34, /* default anyway */
.get_ro = imote2_mci_get_ro,
.gpio_card_detect = -1,
.gpio_card_ro = -1,
.gpio_power = -1,
};
static struct gpio_led imote2_led_pins[] = {
{
.name = "imote2:red",
.gpio = 103,
.active_low = 1,
}, {
.name = "imote2:green",
.gpio = 104,
.active_low = 1,
}, {
.name = "imote2:blue",
.gpio = 105,
.active_low = 1,
},
};
static struct gpio_led_platform_data imote2_led_data = {
.num_leds = ARRAY_SIZE(imote2_led_pins),
.leds = imote2_led_pins,
};
static struct platform_device imote2_leds = {
.name = "leds-gpio",
.id = -1,
.dev = {
.platform_data = &imote2_led_data,
},
};
static struct da903x_subdev_info imote2_da9030_subdevs[] = {
{
.name = "da903x-regulator",
.id = DA9030_ID_LDO2,
.platform_data = &stargate2_ldo_init_data[vcc_bbio],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO3,
.platform_data = &stargate2_ldo_init_data[vcc_bb],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO4,
.platform_data = &stargate2_ldo_init_data[vcc_pxa_flash],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO5,
.platform_data = &stargate2_ldo_init_data[vcc_cc2420],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO6,
.platform_data = &stargate2_ldo_init_data[vcc_vref],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO7,
.platform_data = &stargate2_ldo_init_data[vcc_sram_ext],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO8,
.platform_data = &stargate2_ldo_init_data[vcc_mica],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO9,
.platform_data = &stargate2_ldo_init_data[vcc_bt],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO10,
.platform_data = &stargate2_ldo_init_data[vcc_sensor_1_8],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO11,
.platform_data = &stargate2_ldo_init_data[vcc_sensor_3],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO12,
.platform_data = &stargate2_ldo_init_data[vcc_lcd],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO15,
.platform_data = &stargate2_ldo_init_data[vcc_pxa_pll],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO17,
.platform_data = &stargate2_ldo_init_data[vcc_pxa_usim],
}, {
.name = "da903x-regulator", /*pxa vcc i/o and cc2420 vcc i/o */
.id = DA9030_ID_LDO18,
.platform_data = &stargate2_ldo_init_data[vcc_io],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO19,
.platform_data = &stargate2_ldo_init_data[vcc_pxa_mem],
},
};
static struct da903x_platform_data imote2_da9030_pdata = {
.num_subdevs = ARRAY_SIZE(imote2_da9030_subdevs),
.subdevs = imote2_da9030_subdevs,
};
static struct i2c_board_info __initdata imote2_pwr_i2c_board_info[] = {
{
.type = "da9030",
.addr = 0x49,
.platform_data = &imote2_da9030_pdata,
.irq = PXA_GPIO_TO_IRQ(1),
},
};
static struct i2c_board_info __initdata imote2_i2c_board_info[] = {
{ /* UCAM sensor board */
.type = "max1239",
.addr = 0x35,
}, { /* ITS400 Sensor board only */
.type = "max1363",
.addr = 0x34,
/* Through a nand gate - Also beware, on V2 sensor board the
* pull up resistors are missing.
*/
.irq = PXA_GPIO_TO_IRQ(99),
}, { /* ITS400 Sensor board only */
.type = "tsl2561",
.addr = 0x49,
/* Through a nand gate - Also beware, on V2 sensor board the
* pull up resistors are missing.
*/
.irq = PXA_GPIO_TO_IRQ(99),
}, { /* ITS400 Sensor board only */
.type = "tmp175",
.addr = 0x4A,
.irq = PXA_GPIO_TO_IRQ(96),
}, { /* IMB400 Multimedia board */
.type = "wm8940",
.addr = 0x1A,
},
};
static unsigned long imote2_pin_config[] __initdata = {
/* Button */
GPIO91_GPIO,
/* LEDS */
GPIO103_GPIO, /* red led */
GPIO104_GPIO, /* green led */
GPIO105_GPIO, /* blue led */
};
static struct pxa2xx_udc_mach_info imote2_udc_info __initdata = {
.udc_command = sg2_udc_command,
};
static struct platform_device imote2_audio_device = {
.name = "imote2-audio",
.id = -1,
};
static struct platform_device *imote2_devices[] = {
&stargate2_flash_device,
&imote2_leds,
&sht15,
&imote2_audio_device,
};
static void __init imote2_init(void)
{
pxa2xx_mfp_config(ARRAY_AND_SIZE(imote2_pin_config));
imote2_stargate2_init();
platform_add_devices(imote2_devices, ARRAY_SIZE(imote2_devices));
i2c_register_board_info(0, imote2_i2c_board_info,
ARRAY_SIZE(imote2_i2c_board_info));
i2c_register_board_info(1, imote2_pwr_i2c_board_info,
ARRAY_SIZE(imote2_pwr_i2c_board_info));
pxa_set_mci_info(&imote2_mci_platform_data);
pxa_set_udc_info(&imote2_udc_info);
}
#endif
#ifdef CONFIG_MACH_STARGATE2
static unsigned long stargate2_pin_config[] __initdata = {
GPIO15_nCS_1, /* SRAM */
/* SMC91x */
GPIO80_nCS_4,
GPIO40_GPIO, /*cable detect?*/
/* Button */
GPIO91_GPIO | WAKEUP_ON_LEVEL_HIGH,
/* Compact Flash */
GPIO79_PSKTSEL,
GPIO48_nPOE,
GPIO49_nPWE,
GPIO50_nPIOR,
GPIO51_nPIOW,
GPIO85_nPCE_1,
GPIO54_nPCE_2,
GPIO55_nPREG,
GPIO56_nPWAIT,
GPIO57_nIOIS16,
GPIO120_GPIO, /* Buff ctrl */
GPIO108_GPIO, /* Power ctrl */
GPIO82_GPIO, /* Reset */
GPIO53_GPIO, /* SG2_S0_GPIO_DETECT */
/* MMC not shared with imote2 */
GPIO90_GPIO, /* nSD detect */
GPIO89_GPIO, /* SD_POWER_ENABLE */
/* Bluetooth */
GPIO81_GPIO, /* reset */
};
static struct resource smc91x_resources[] = {
[0] = {
.name = "smc91x-regs",
.start = (PXA_CS4_PHYS + 0x300),
.end = (PXA_CS4_PHYS + 0xfffff),
.flags = IORESOURCE_MEM,
},
[1] = {
.start = PXA_GPIO_TO_IRQ(40),
.end = PXA_GPIO_TO_IRQ(40),
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHEDGE,
}
};
static struct smc91x_platdata stargate2_smc91x_info = {
.flags = SMC91X_USE_8BIT | SMC91X_USE_16BIT | SMC91X_USE_32BIT
| SMC91X_NOWAIT | SMC91X_USE_DMA,
};
static struct platform_device smc91x_device = {
.name = "smc91x",
.id = -1,
.num_resources = ARRAY_SIZE(smc91x_resources),
.resource = smc91x_resources,
.dev = {
.platform_data = &stargate2_smc91x_info,
},
};
/*
* The card detect interrupt isn't debounced so we delay it by 250ms
* to give the card a chance to fully insert / eject.
*/
static int stargate2_mci_init(struct device *dev,
irq_handler_t stargate2_detect_int,
void *data)
{
int err;
err = gpio_request(SG2_SD_POWER_ENABLE, "SG2_sd_power_enable");
if (err) {
printk(KERN_ERR "Can't get the gpio for SD power control");
goto return_err;
}
gpio_direction_output(SG2_SD_POWER_ENABLE, 0);
err = gpio_request(SG2_GPIO_nSD_DETECT, "SG2_sd_detect");
if (err) {
printk(KERN_ERR "Can't get the sd detect gpio");
goto free_power_en;
}
gpio_direction_input(SG2_GPIO_nSD_DETECT);
err = request_irq(PXA_GPIO_TO_IRQ(SG2_GPIO_nSD_DETECT),
stargate2_detect_int,
IRQ_TYPE_EDGE_BOTH,
"MMC card detect",
data);
if (err) {
printk(KERN_ERR "can't request MMC card detect IRQ\n");
goto free_nsd_detect;
}
return 0;
free_nsd_detect:
gpio_free(SG2_GPIO_nSD_DETECT);
free_power_en:
gpio_free(SG2_SD_POWER_ENABLE);
return_err:
return err;
}
/**
* stargate2_mci_setpower() - set state of mmc power supply
*
* Very simple control. Either it is on or off and is controlled by
* a gpio pin */
static void stargate2_mci_setpower(struct device *dev, unsigned int vdd)
{
gpio_set_value(SG2_SD_POWER_ENABLE, !!vdd);
}
static void stargate2_mci_exit(struct device *dev, void *data)
{
free_irq(PXA_GPIO_TO_IRQ(SG2_GPIO_nSD_DETECT), data);
gpio_free(SG2_SD_POWER_ENABLE);
gpio_free(SG2_GPIO_nSD_DETECT);
}
static struct pxamci_platform_data stargate2_mci_platform_data = {
.detect_delay_ms = 250,
.ocr_mask = MMC_VDD_32_33 | MMC_VDD_33_34,
.init = stargate2_mci_init,
.setpower = stargate2_mci_setpower,
.exit = stargate2_mci_exit,
};
/*
* SRAM - The Stargate 2 has 32MB of SRAM.
*
* Here it is made available as an MTD. This will then
* typically have a cifs filesystem created on it to provide
* fast temporary storage.
*/
static struct resource sram_resources = {
.start = PXA_CS1_PHYS,
.end = PXA_CS1_PHYS + SZ_32M-1,
.flags = IORESOURCE_MEM,
};
static struct platdata_mtd_ram stargate2_sram_pdata = {
.mapname = "Stargate2 SRAM",
.bankwidth = 2,
};
static struct platform_device stargate2_sram = {
.name = "mtd-ram",
.id = 0,
.resource = &sram_resources,
.num_resources = 1,
.dev = {
.platform_data = &stargate2_sram_pdata,
},
};
static struct pcf857x_platform_data platform_data_pcf857x = {
.gpio_base = 128,
.n_latch = 0,
.setup = NULL,
.teardown = NULL,
.context = NULL,
};
static struct at24_platform_data pca9500_eeprom_pdata = {
.byte_len = 256,
.page_size = 4,
};
/**
* stargate2_reset_bluetooth() reset the bluecore to ensure consistent state
**/
static int stargate2_reset_bluetooth(void)
{
int err;
err = gpio_request(SG2_BT_RESET, "SG2_BT_RESET");
if (err) {
printk(KERN_ERR "Could not get gpio for bluetooth reset\n");
return err;
}
gpio_direction_output(SG2_BT_RESET, 1);
mdelay(5);
/* now reset it - 5 msec minimum */
gpio_set_value(SG2_BT_RESET, 0);
mdelay(10);
gpio_set_value(SG2_BT_RESET, 1);
gpio_free(SG2_BT_RESET);
return 0;
}
static struct led_info stargate2_leds[] = {
{
.name = "sg2:red",
.flags = DA9030_LED_RATE_ON,
}, {
.name = "sg2:blue",
.flags = DA9030_LED_RATE_ON,
}, {
.name = "sg2:green",
.flags = DA9030_LED_RATE_ON,
},
};
static struct da903x_subdev_info stargate2_da9030_subdevs[] = {
{
.name = "da903x-led",
.id = DA9030_ID_LED_2,
.platform_data = &stargate2_leds[0],
}, {
.name = "da903x-led",
.id = DA9030_ID_LED_3,
.platform_data = &stargate2_leds[2],
}, {
.name = "da903x-led",
.id = DA9030_ID_LED_4,
.platform_data = &stargate2_leds[1],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO2,
.platform_data = &stargate2_ldo_init_data[vcc_bbio],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO3,
.platform_data = &stargate2_ldo_init_data[vcc_bb],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO4,
.platform_data = &stargate2_ldo_init_data[vcc_pxa_flash],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO5,
.platform_data = &stargate2_ldo_init_data[vcc_cc2420],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO6,
.platform_data = &stargate2_ldo_init_data[vcc_vref],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO7,
.platform_data = &stargate2_ldo_init_data[vcc_sram_ext],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO8,
.platform_data = &stargate2_ldo_init_data[vcc_mica],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO9,
.platform_data = &stargate2_ldo_init_data[vcc_bt],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO10,
.platform_data = &stargate2_ldo_init_data[vcc_sensor_1_8],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO11,
.platform_data = &stargate2_ldo_init_data[vcc_sensor_3],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO12,
.platform_data = &stargate2_ldo_init_data[vcc_lcd],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO15,
.platform_data = &stargate2_ldo_init_data[vcc_pxa_pll],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO17,
.platform_data = &stargate2_ldo_init_data[vcc_pxa_usim],
}, {
.name = "da903x-regulator", /*pxa vcc i/o and cc2420 vcc i/o */
.id = DA9030_ID_LDO18,
.platform_data = &stargate2_ldo_init_data[vcc_io],
}, {
.name = "da903x-regulator",
.id = DA9030_ID_LDO19,
.platform_data = &stargate2_ldo_init_data[vcc_pxa_mem],
},
};
static struct da903x_platform_data stargate2_da9030_pdata = {
.num_subdevs = ARRAY_SIZE(stargate2_da9030_subdevs),
.subdevs = stargate2_da9030_subdevs,
};
static struct i2c_board_info __initdata stargate2_pwr_i2c_board_info[] = {
{
.type = "da9030",
.addr = 0x49,
.platform_data = &stargate2_da9030_pdata,
.irq = PXA_GPIO_TO_IRQ(1),
},
};
static struct i2c_board_info __initdata stargate2_i2c_board_info[] = {
/* Techically this a pca9500 - but it's compatible with the 8574
* for gpio expansion and the 24c02 for eeprom access.
*/
{
.type = "pcf8574",
.addr = 0x27,
.platform_data = &platform_data_pcf857x,
}, {
.type = "24c02",
.addr = 0x57,
.platform_data = &pca9500_eeprom_pdata,
}, {
.type = "max1238",
.addr = 0x35,
}, { /* ITS400 Sensor board only */
.type = "max1363",
.addr = 0x34,
/* Through a nand gate - Also beware, on V2 sensor board the
* pull up resistors are missing.
*/
.irq = PXA_GPIO_TO_IRQ(99),
}, { /* ITS400 Sensor board only */
.type = "tsl2561",
.addr = 0x49,
/* Through a nand gate - Also beware, on V2 sensor board the
* pull up resistors are missing.
*/
.irq = PXA_GPIO_TO_IRQ(99),
}, { /* ITS400 Sensor board only */
.type = "tmp175",
.addr = 0x4A,
.irq = PXA_GPIO_TO_IRQ(96),
},
};
/* Board doesn't support cable detection - so always lie and say
* something is there.
*/
static int sg2_udc_detect(void)
{
return 1;
}
static struct pxa2xx_udc_mach_info stargate2_udc_info __initdata = {
.udc_is_connected = sg2_udc_detect,
.udc_command = sg2_udc_command,
};
static struct platform_device *stargate2_devices[] = {
&stargate2_flash_device,
&stargate2_sram,
&smc91x_device,
&sht15,
};
static void __init stargate2_init(void)
{
/* This is probably a board specific hack as this must be set
prior to connecting the MFP stuff up. */
__raw_writel(__raw_readl(MECR) & ~MECR_NOS, MECR);
pxa2xx_mfp_config(ARRAY_AND_SIZE(stargate2_pin_config));
imote2_stargate2_init();
platform_add_devices(ARRAY_AND_SIZE(stargate2_devices));
i2c_register_board_info(0, ARRAY_AND_SIZE(stargate2_i2c_board_info));
i2c_register_board_info(1, stargate2_pwr_i2c_board_info,
ARRAY_SIZE(stargate2_pwr_i2c_board_info));
pxa_set_mci_info(&stargate2_mci_platform_data);
pxa_set_udc_info(&stargate2_udc_info);
stargate2_reset_bluetooth();
}
#endif
#ifdef CONFIG_MACH_INTELMOTE2
MACHINE_START(INTELMOTE2, "IMOTE 2")
.map_io = pxa27x_map_io,
.nr_irqs = PXA_NR_IRQS,
.init_irq = pxa27x_init_irq,
.handle_irq = pxa27x_handle_irq,
.timer = &pxa_timer,
.init_machine = imote2_init,
.atag_offset = 0x100,
.restart = pxa_restart,
MACHINE_END
#endif
#ifdef CONFIG_MACH_STARGATE2
MACHINE_START(STARGATE2, "Stargate 2")
.map_io = pxa27x_map_io,
.nr_irqs = STARGATE_NR_IRQS,
.init_irq = pxa27x_init_irq,
.handle_irq = pxa27x_handle_irq,
.timer = &pxa_timer,
.init_machine = stargate2_init,
.atag_offset = 0x100,
.restart = pxa_restart,
MACHINE_END
#endif
| gpl-2.0 |
jcadduono/nethunter_kernel_mako_flo | arch/arm/mach-omap1/board-h2.c | 4731 | 10753 | /*
* linux/arch/arm/mach-omap1/board-h2.c
*
* Board specific inits for OMAP-1610 H2
*
* Copyright (C) 2001 RidgeRun, Inc.
* Author: Greg Lonnon <glonnon@ridgerun.com>
*
* Copyright (C) 2002 MontaVista Software, Inc.
*
* Separated FPGA interrupts from innovator1510.c and cleaned up for 2.6
* Copyright (C) 2004 Nokia Corporation by Tony Lindrgen <tony@atomide.com>
*
* H2 specific changes and cleanup
* Copyright (C) 2004 Nokia Corporation by Imre Deak <imre.deak@nokia.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/gpio.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/input.h>
#include <linux/i2c/tps65010.h>
#include <linux/smc91x.h>
#include <linux/omapfb.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <plat/mux.h>
#include <plat/dma.h>
#include <plat/tc.h>
#include <plat/irda.h>
#include <plat/usb.h>
#include <plat/keypad.h>
#include <plat/flash.h>
#include <mach/hardware.h>
#include "common.h"
#include "board-h2.h"
/* At OMAP1610 Innovator the Ethernet is directly connected to CS1 */
#define OMAP1610_ETHR_START 0x04000300
static const unsigned int h2_keymap[] = {
KEY(0, 0, KEY_LEFT),
KEY(1, 0, KEY_RIGHT),
KEY(2, 0, KEY_3),
KEY(3, 0, KEY_F10),
KEY(4, 0, KEY_F5),
KEY(5, 0, KEY_9),
KEY(0, 1, KEY_DOWN),
KEY(1, 1, KEY_UP),
KEY(2, 1, KEY_2),
KEY(3, 1, KEY_F9),
KEY(4, 1, KEY_F7),
KEY(5, 1, KEY_0),
KEY(0, 2, KEY_ENTER),
KEY(1, 2, KEY_6),
KEY(2, 2, KEY_1),
KEY(3, 2, KEY_F2),
KEY(4, 2, KEY_F6),
KEY(5, 2, KEY_HOME),
KEY(0, 3, KEY_8),
KEY(1, 3, KEY_5),
KEY(2, 3, KEY_F12),
KEY(3, 3, KEY_F3),
KEY(4, 3, KEY_F8),
KEY(5, 3, KEY_END),
KEY(0, 4, KEY_7),
KEY(1, 4, KEY_4),
KEY(2, 4, KEY_F11),
KEY(3, 4, KEY_F1),
KEY(4, 4, KEY_F4),
KEY(5, 4, KEY_ESC),
KEY(0, 5, KEY_F13),
KEY(1, 5, KEY_F14),
KEY(2, 5, KEY_F15),
KEY(3, 5, KEY_F16),
KEY(4, 5, KEY_SLEEP),
};
static struct mtd_partition h2_nor_partitions[] = {
/* bootloader (U-Boot, etc) in first sector */
{
.name = "bootloader",
.offset = 0,
.size = SZ_128K,
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
/* bootloader params in the next sector */
{
.name = "params",
.offset = MTDPART_OFS_APPEND,
.size = SZ_128K,
.mask_flags = 0,
},
/* kernel */
{
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = SZ_2M,
.mask_flags = 0
},
/* file system */
{
.name = "filesystem",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
.mask_flags = 0
}
};
static struct physmap_flash_data h2_nor_data = {
.width = 2,
.set_vpp = omap1_set_vpp,
.parts = h2_nor_partitions,
.nr_parts = ARRAY_SIZE(h2_nor_partitions),
};
static struct resource h2_nor_resource = {
/* This is on CS3, wherever it's mapped */
.flags = IORESOURCE_MEM,
};
static struct platform_device h2_nor_device = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &h2_nor_data,
},
.num_resources = 1,
.resource = &h2_nor_resource,
};
static struct mtd_partition h2_nand_partitions[] = {
#if 0
/* REVISIT: enable these partitions if you make NAND BOOT
* work on your H2 (rev C or newer); published versions of
* x-load only support P2 and H3.
*/
{
.name = "xloader",
.offset = 0,
.size = 64 * 1024,
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
{
.name = "bootloader",
.offset = MTDPART_OFS_APPEND,
.size = 256 * 1024,
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
{
.name = "params",
.offset = MTDPART_OFS_APPEND,
.size = 192 * 1024,
},
{
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = 2 * SZ_1M,
},
#endif
{
.name = "filesystem",
.size = MTDPART_SIZ_FULL,
.offset = MTDPART_OFS_APPEND,
},
};
static void h2_nand_cmd_ctl(struct mtd_info *mtd, int cmd, unsigned int ctrl)
{
struct nand_chip *this = mtd->priv;
unsigned long mask;
if (cmd == NAND_CMD_NONE)
return;
mask = (ctrl & NAND_CLE) ? 0x02 : 0;
if (ctrl & NAND_ALE)
mask |= 0x04;
writeb(cmd, (unsigned long)this->IO_ADDR_W | mask);
}
#define H2_NAND_RB_GPIO_PIN 62
static int h2_nand_dev_ready(struct mtd_info *mtd)
{
return gpio_get_value(H2_NAND_RB_GPIO_PIN);
}
static const char *h2_part_probes[] = { "cmdlinepart", NULL };
static struct platform_nand_data h2_nand_platdata = {
.chip = {
.nr_chips = 1,
.chip_offset = 0,
.nr_partitions = ARRAY_SIZE(h2_nand_partitions),
.partitions = h2_nand_partitions,
.options = NAND_SAMSUNG_LP_OPTIONS,
.part_probe_types = h2_part_probes,
},
.ctrl = {
.cmd_ctrl = h2_nand_cmd_ctl,
.dev_ready = h2_nand_dev_ready,
},
};
static struct resource h2_nand_resource = {
.flags = IORESOURCE_MEM,
};
static struct platform_device h2_nand_device = {
.name = "gen_nand",
.id = 0,
.dev = {
.platform_data = &h2_nand_platdata,
},
.num_resources = 1,
.resource = &h2_nand_resource,
};
static struct smc91x_platdata h2_smc91x_info = {
.flags = SMC91X_USE_16BIT | SMC91X_NOWAIT,
.leda = RPC_LED_100_10,
.ledb = RPC_LED_TX_RX,
};
static struct resource h2_smc91x_resources[] = {
[0] = {
.start = OMAP1610_ETHR_START, /* Physical */
.end = OMAP1610_ETHR_START + 0xf,
.flags = IORESOURCE_MEM,
},
[1] = {
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_LOWEDGE,
},
};
static struct platform_device h2_smc91x_device = {
.name = "smc91x",
.id = 0,
.dev = {
.platform_data = &h2_smc91x_info,
},
.num_resources = ARRAY_SIZE(h2_smc91x_resources),
.resource = h2_smc91x_resources,
};
static struct resource h2_kp_resources[] = {
[0] = {
.start = INT_KEYBOARD,
.end = INT_KEYBOARD,
.flags = IORESOURCE_IRQ,
},
};
static const struct matrix_keymap_data h2_keymap_data = {
.keymap = h2_keymap,
.keymap_size = ARRAY_SIZE(h2_keymap),
};
static struct omap_kp_platform_data h2_kp_data = {
.rows = 8,
.cols = 8,
.keymap_data = &h2_keymap_data,
.rep = true,
.delay = 9,
.dbounce = true,
};
static struct platform_device h2_kp_device = {
.name = "omap-keypad",
.id = -1,
.dev = {
.platform_data = &h2_kp_data,
},
.num_resources = ARRAY_SIZE(h2_kp_resources),
.resource = h2_kp_resources,
};
#define H2_IRDA_FIRSEL_GPIO_PIN 17
static struct omap_irda_config h2_irda_data = {
.transceiver_cap = IR_SIRMODE | IR_MIRMODE | IR_FIRMODE,
.rx_channel = OMAP_DMA_UART3_RX,
.tx_channel = OMAP_DMA_UART3_TX,
.dest_start = UART3_THR,
.src_start = UART3_RHR,
.tx_trigger = 0,
.rx_trigger = 0,
};
static struct resource h2_irda_resources[] = {
[0] = {
.start = INT_UART3,
.end = INT_UART3,
.flags = IORESOURCE_IRQ,
},
};
static u64 irda_dmamask = 0xffffffff;
static struct platform_device h2_irda_device = {
.name = "omapirda",
.id = 0,
.dev = {
.platform_data = &h2_irda_data,
.dma_mask = &irda_dmamask,
},
.num_resources = ARRAY_SIZE(h2_irda_resources),
.resource = h2_irda_resources,
};
static struct platform_device *h2_devices[] __initdata = {
&h2_nor_device,
&h2_nand_device,
&h2_smc91x_device,
&h2_irda_device,
&h2_kp_device,
};
static void __init h2_init_smc91x(void)
{
if (gpio_request(0, "SMC91x irq") < 0) {
printk("Error requesting gpio 0 for smc91x irq\n");
return;
}
}
static int tps_setup(struct i2c_client *client, void *context)
{
tps65010_config_vregs1(TPS_LDO2_ENABLE | TPS_VLDO2_3_0V |
TPS_LDO1_ENABLE | TPS_VLDO1_3_0V);
return 0;
}
static struct tps65010_board tps_board = {
.base = H2_TPS_GPIO_BASE,
.outmask = 0x0f,
.setup = tps_setup,
};
static struct i2c_board_info __initdata h2_i2c_board_info[] = {
{
I2C_BOARD_INFO("tps65010", 0x48),
.platform_data = &tps_board,
}, {
I2C_BOARD_INFO("isp1301_omap", 0x2d),
},
};
static struct omap_usb_config h2_usb_config __initdata = {
/* usb1 has a Mini-AB port and external isp1301 transceiver */
.otg = 2,
#ifdef CONFIG_USB_GADGET_OMAP
.hmc_mode = 19, /* 0:host(off) 1:dev|otg 2:disabled */
/* .hmc_mode = 21,*/ /* 0:host(off) 1:dev(loopback) 2:host(loopback) */
#elif defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE)
/* needs OTG cable, or NONSTANDARD (B-to-MiniB) */
.hmc_mode = 20, /* 1:dev|otg(off) 1:host 2:disabled */
#endif
.pins[1] = 3,
};
static struct omap_lcd_config h2_lcd_config __initdata = {
.ctrl_name = "internal",
};
static void __init h2_init(void)
{
h2_init_smc91x();
/* Here we assume the NOR boot config: NOR on CS3 (possibly swapped
* to address 0 by a dip switch), NAND on CS2B. The NAND driver will
* notice whether a NAND chip is enabled at probe time.
*
* FIXME revC boards (and H3) support NAND-boot, with a dip switch to
* put NOR on CS2B and NAND (which on H2 may be 16bit) on CS3. Try
* detecting that in code here, to avoid probing every possible flash
* configuration...
*/
h2_nor_resource.end = h2_nor_resource.start = omap_cs3_phys();
h2_nor_resource.end += SZ_32M - 1;
h2_nand_resource.end = h2_nand_resource.start = OMAP_CS2B_PHYS;
h2_nand_resource.end += SZ_4K - 1;
if (gpio_request(H2_NAND_RB_GPIO_PIN, "NAND ready") < 0)
BUG();
gpio_direction_input(H2_NAND_RB_GPIO_PIN);
omap_cfg_reg(L3_1610_FLASH_CS2B_OE);
omap_cfg_reg(M8_1610_FLASH_CS2B_WE);
/* MMC: card detect and WP */
/* omap_cfg_reg(U19_ARMIO1); */ /* CD */
omap_cfg_reg(BALLOUT_V8_ARMIO3); /* WP */
/* Mux pins for keypad */
omap_cfg_reg(F18_1610_KBC0);
omap_cfg_reg(D20_1610_KBC1);
omap_cfg_reg(D19_1610_KBC2);
omap_cfg_reg(E18_1610_KBC3);
omap_cfg_reg(C21_1610_KBC4);
omap_cfg_reg(G18_1610_KBR0);
omap_cfg_reg(F19_1610_KBR1);
omap_cfg_reg(H14_1610_KBR2);
omap_cfg_reg(E20_1610_KBR3);
omap_cfg_reg(E19_1610_KBR4);
omap_cfg_reg(N19_1610_KBR5);
h2_smc91x_resources[1].start = gpio_to_irq(0);
h2_smc91x_resources[1].end = gpio_to_irq(0);
platform_add_devices(h2_devices, ARRAY_SIZE(h2_devices));
omap_serial_init();
h2_i2c_board_info[0].irq = gpio_to_irq(58);
h2_i2c_board_info[1].irq = gpio_to_irq(2);
omap_register_i2c_bus(1, 100, h2_i2c_board_info,
ARRAY_SIZE(h2_i2c_board_info));
omap1_usb_init(&h2_usb_config);
h2_mmc_init();
omapfb_set_lcd_config(&h2_lcd_config);
}
MACHINE_START(OMAP_H2, "TI-H2")
/* Maintainer: Imre Deak <imre.deak@nokia.com> */
.atag_offset = 0x100,
.map_io = omap16xx_map_io,
.init_early = omap1_init_early,
.reserve = omap_reserve,
.init_irq = omap1_init_irq,
.init_machine = h2_init,
.timer = &omap1_timer,
.restart = omap1_restart,
MACHINE_END
| gpl-2.0 |
TeamBliss-Devices/android_kernel_samsung_s3ve3g | arch/arm/mach-shmobile/intc-sh7372.c | 4731 | 23489 | /*
* sh7372 processor support - INTC hardware block
*
* Copyright (C) 2010 Magnus Damm
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/sh_intc.h>
#include <mach/intc.h>
#include <mach/irqs.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
enum {
UNUSED_INTCA = 0,
/* interrupt sources INTCA */
DIRC,
CRYPT_STD,
IIC1_ALI1, IIC1_TACKI1, IIC1_WAITI1, IIC1_DTEI1,
AP_ARM_IRQPMU, AP_ARM_COMMTX, AP_ARM_COMMRX,
MFI_MFIM, MFI_MFIS,
BBIF1, BBIF2,
USBHSDMAC0_USHDMI,
_3DG_SGX540,
CMT1_CMT10, CMT1_CMT11, CMT1_CMT12, CMT1_CMT13, CMT2, CMT3,
KEYSC_KEY,
SCIFA0, SCIFA1, SCIFA2, SCIFA3,
MSIOF2, MSIOF1,
SCIFA4, SCIFA5, SCIFB,
FLCTL_FLSTEI, FLCTL_FLTENDI, FLCTL_FLTREQ0I, FLCTL_FLTREQ1I,
SDHI0_SDHI0I0, SDHI0_SDHI0I1, SDHI0_SDHI0I2, SDHI0_SDHI0I3,
SDHI1_SDHI1I0, SDHI1_SDHI1I1, SDHI1_SDHI1I2,
IRREM,
IRDA,
TPU0,
TTI20,
DDM,
SDHI2_SDHI2I0, SDHI2_SDHI2I1, SDHI2_SDHI2I2, SDHI2_SDHI2I3,
RWDT0,
DMAC1_1_DEI0, DMAC1_1_DEI1, DMAC1_1_DEI2, DMAC1_1_DEI3,
DMAC1_2_DEI4, DMAC1_2_DEI5, DMAC1_2_DADERR,
DMAC2_1_DEI0, DMAC2_1_DEI1, DMAC2_1_DEI2, DMAC2_1_DEI3,
DMAC2_2_DEI4, DMAC2_2_DEI5, DMAC2_2_DADERR,
DMAC3_1_DEI0, DMAC3_1_DEI1, DMAC3_1_DEI2, DMAC3_1_DEI3,
DMAC3_2_DEI4, DMAC3_2_DEI5, DMAC3_2_DADERR,
SHWYSTAT_RT, SHWYSTAT_HS, SHWYSTAT_COM,
HDMI,
SPU2_SPU0, SPU2_SPU1,
FSI, FMSI,
MIPI_HSI,
IPMMU_IPMMUD,
CEC_1, CEC_2,
AP_ARM_CTIIRQ, AP_ARM_DMAEXTERRIRQ, AP_ARM_DMAIRQ, AP_ARM_DMASIRQ,
MFIS2,
CPORTR2S,
CMT14, CMT15,
MMC_MMC_ERR, MMC_MMC_NOR,
IIC4_ALI4, IIC4_TACKI4, IIC4_WAITI4, IIC4_DTEI4,
IIC3_ALI3, IIC3_TACKI3, IIC3_WAITI3, IIC3_DTEI3,
USB0_USB0I1, USB0_USB0I0,
USB1_USB1I1, USB1_USB1I0,
USBHSDMAC1_USHDMI,
/* interrupt groups INTCA */
DMAC1_1, DMAC1_2, DMAC2_1, DMAC2_2, DMAC3_1, DMAC3_2, SHWYSTAT,
AP_ARM1, AP_ARM2, SPU2, FLCTL, IIC1, SDHI0, SDHI1, SDHI2
};
static struct intc_vect intca_vectors[] __initdata = {
INTC_VECT(DIRC, 0x0560),
INTC_VECT(CRYPT_STD, 0x0700),
INTC_VECT(IIC1_ALI1, 0x0780), INTC_VECT(IIC1_TACKI1, 0x07a0),
INTC_VECT(IIC1_WAITI1, 0x07c0), INTC_VECT(IIC1_DTEI1, 0x07e0),
INTC_VECT(AP_ARM_IRQPMU, 0x0800), INTC_VECT(AP_ARM_COMMTX, 0x0840),
INTC_VECT(AP_ARM_COMMRX, 0x0860),
INTC_VECT(MFI_MFIM, 0x0900), INTC_VECT(MFI_MFIS, 0x0920),
INTC_VECT(BBIF1, 0x0940), INTC_VECT(BBIF2, 0x0960),
INTC_VECT(USBHSDMAC0_USHDMI, 0x0a00),
INTC_VECT(_3DG_SGX540, 0x0a60),
INTC_VECT(CMT1_CMT10, 0x0b00), INTC_VECT(CMT1_CMT11, 0x0b20),
INTC_VECT(CMT1_CMT12, 0x0b40), INTC_VECT(CMT1_CMT13, 0x0b60),
INTC_VECT(CMT2, 0x0b80), INTC_VECT(CMT3, 0x0ba0),
INTC_VECT(KEYSC_KEY, 0x0be0),
INTC_VECT(SCIFA0, 0x0c00), INTC_VECT(SCIFA1, 0x0c20),
INTC_VECT(SCIFA2, 0x0c40), INTC_VECT(SCIFA3, 0x0c60),
INTC_VECT(MSIOF2, 0x0c80), INTC_VECT(MSIOF1, 0x0d00),
INTC_VECT(SCIFA4, 0x0d20), INTC_VECT(SCIFA5, 0x0d40),
INTC_VECT(SCIFB, 0x0d60),
INTC_VECT(FLCTL_FLSTEI, 0x0d80), INTC_VECT(FLCTL_FLTENDI, 0x0da0),
INTC_VECT(FLCTL_FLTREQ0I, 0x0dc0), INTC_VECT(FLCTL_FLTREQ1I, 0x0de0),
INTC_VECT(SDHI0_SDHI0I0, 0x0e00), INTC_VECT(SDHI0_SDHI0I1, 0x0e20),
INTC_VECT(SDHI0_SDHI0I2, 0x0e40), INTC_VECT(SDHI0_SDHI0I3, 0x0e60),
INTC_VECT(SDHI1_SDHI1I0, 0x0e80), INTC_VECT(SDHI1_SDHI1I1, 0x0ea0),
INTC_VECT(SDHI1_SDHI1I2, 0x0ec0),
INTC_VECT(IRREM, 0x0f60),
INTC_VECT(IRDA, 0x0480),
INTC_VECT(TPU0, 0x04a0),
INTC_VECT(TTI20, 0x1100),
INTC_VECT(DDM, 0x1140),
INTC_VECT(SDHI2_SDHI2I0, 0x1200), INTC_VECT(SDHI2_SDHI2I1, 0x1220),
INTC_VECT(SDHI2_SDHI2I2, 0x1240), INTC_VECT(SDHI2_SDHI2I3, 0x1260),
INTC_VECT(RWDT0, 0x1280),
INTC_VECT(DMAC1_1_DEI0, 0x2000), INTC_VECT(DMAC1_1_DEI1, 0x2020),
INTC_VECT(DMAC1_1_DEI2, 0x2040), INTC_VECT(DMAC1_1_DEI3, 0x2060),
INTC_VECT(DMAC1_2_DEI4, 0x2080), INTC_VECT(DMAC1_2_DEI5, 0x20a0),
INTC_VECT(DMAC1_2_DADERR, 0x20c0),
INTC_VECT(DMAC2_1_DEI0, 0x2100), INTC_VECT(DMAC2_1_DEI1, 0x2120),
INTC_VECT(DMAC2_1_DEI2, 0x2140), INTC_VECT(DMAC2_1_DEI3, 0x2160),
INTC_VECT(DMAC2_2_DEI4, 0x2180), INTC_VECT(DMAC2_2_DEI5, 0x21a0),
INTC_VECT(DMAC2_2_DADERR, 0x21c0),
INTC_VECT(DMAC3_1_DEI0, 0x2200), INTC_VECT(DMAC3_1_DEI1, 0x2220),
INTC_VECT(DMAC3_1_DEI2, 0x2240), INTC_VECT(DMAC3_1_DEI3, 0x2260),
INTC_VECT(DMAC3_2_DEI4, 0x2280), INTC_VECT(DMAC3_2_DEI5, 0x22a0),
INTC_VECT(DMAC3_2_DADERR, 0x22c0),
INTC_VECT(SHWYSTAT_RT, 0x1300), INTC_VECT(SHWYSTAT_HS, 0x1320),
INTC_VECT(SHWYSTAT_COM, 0x1340),
INTC_VECT(HDMI, 0x17e0),
INTC_VECT(SPU2_SPU0, 0x1800), INTC_VECT(SPU2_SPU1, 0x1820),
INTC_VECT(FSI, 0x1840),
INTC_VECT(FMSI, 0x1860),
INTC_VECT(MIPI_HSI, 0x18e0),
INTC_VECT(IPMMU_IPMMUD, 0x1920),
INTC_VECT(CEC_1, 0x1940), INTC_VECT(CEC_2, 0x1960),
INTC_VECT(AP_ARM_CTIIRQ, 0x1980),
INTC_VECT(AP_ARM_DMAEXTERRIRQ, 0x19a0),
INTC_VECT(AP_ARM_DMAIRQ, 0x19c0),
INTC_VECT(AP_ARM_DMASIRQ, 0x19e0),
INTC_VECT(MFIS2, 0x1a00),
INTC_VECT(CPORTR2S, 0x1a20),
INTC_VECT(CMT14, 0x1a40), INTC_VECT(CMT15, 0x1a60),
INTC_VECT(MMC_MMC_ERR, 0x1ac0), INTC_VECT(MMC_MMC_NOR, 0x1ae0),
INTC_VECT(IIC4_ALI4, 0x1b00), INTC_VECT(IIC4_TACKI4, 0x1b20),
INTC_VECT(IIC4_WAITI4, 0x1b40), INTC_VECT(IIC4_DTEI4, 0x1b60),
INTC_VECT(IIC3_ALI3, 0x1b80), INTC_VECT(IIC3_TACKI3, 0x1ba0),
INTC_VECT(IIC3_WAITI3, 0x1bc0), INTC_VECT(IIC3_DTEI3, 0x1be0),
INTC_VECT(USB0_USB0I1, 0x1c80), INTC_VECT(USB0_USB0I0, 0x1ca0),
INTC_VECT(USB1_USB1I1, 0x1cc0), INTC_VECT(USB1_USB1I0, 0x1ce0),
INTC_VECT(USBHSDMAC1_USHDMI, 0x1d00),
};
static struct intc_group intca_groups[] __initdata = {
INTC_GROUP(DMAC1_1, DMAC1_1_DEI0,
DMAC1_1_DEI1, DMAC1_1_DEI2, DMAC1_1_DEI3),
INTC_GROUP(DMAC1_2, DMAC1_2_DEI4,
DMAC1_2_DEI5, DMAC1_2_DADERR),
INTC_GROUP(DMAC2_1, DMAC2_1_DEI0,
DMAC2_1_DEI1, DMAC2_1_DEI2, DMAC2_1_DEI3),
INTC_GROUP(DMAC2_2, DMAC2_2_DEI4,
DMAC2_2_DEI5, DMAC2_2_DADERR),
INTC_GROUP(DMAC3_1, DMAC3_1_DEI0,
DMAC3_1_DEI1, DMAC3_1_DEI2, DMAC3_1_DEI3),
INTC_GROUP(DMAC3_2, DMAC3_2_DEI4,
DMAC3_2_DEI5, DMAC3_2_DADERR),
INTC_GROUP(AP_ARM1, AP_ARM_IRQPMU, AP_ARM_COMMTX, AP_ARM_COMMRX),
INTC_GROUP(AP_ARM2, AP_ARM_CTIIRQ, AP_ARM_DMAEXTERRIRQ,
AP_ARM_DMAIRQ, AP_ARM_DMASIRQ),
INTC_GROUP(SPU2, SPU2_SPU0, SPU2_SPU1),
INTC_GROUP(FLCTL, FLCTL_FLSTEI, FLCTL_FLTENDI,
FLCTL_FLTREQ0I, FLCTL_FLTREQ1I),
INTC_GROUP(IIC1, IIC1_ALI1, IIC1_TACKI1, IIC1_WAITI1, IIC1_DTEI1),
INTC_GROUP(SDHI0, SDHI0_SDHI0I0, SDHI0_SDHI0I1,
SDHI0_SDHI0I2, SDHI0_SDHI0I3),
INTC_GROUP(SDHI1, SDHI1_SDHI1I0, SDHI1_SDHI1I1,
SDHI1_SDHI1I2),
INTC_GROUP(SDHI2, SDHI2_SDHI2I0, SDHI2_SDHI2I1,
SDHI2_SDHI2I2, SDHI2_SDHI2I3),
INTC_GROUP(SHWYSTAT, SHWYSTAT_RT, SHWYSTAT_HS, SHWYSTAT_COM),
};
static struct intc_mask_reg intca_mask_registers[] __initdata = {
{ 0xe6940080, 0xe69400c0, 8, /* IMR0A / IMCR0A */
{ DMAC2_1_DEI3, DMAC2_1_DEI2, DMAC2_1_DEI1, DMAC2_1_DEI0,
AP_ARM_IRQPMU, 0, AP_ARM_COMMTX, AP_ARM_COMMRX } },
{ 0xe6940084, 0xe69400c4, 8, /* IMR1A / IMCR1A */
{ 0, CRYPT_STD, DIRC, 0,
DMAC1_1_DEI3, DMAC1_1_DEI2, DMAC1_1_DEI1, DMAC1_1_DEI0 } },
{ 0xe6940088, 0xe69400c8, 8, /* IMR2A / IMCR2A */
{ 0, 0, 0, 0,
BBIF1, BBIF2, MFI_MFIS, MFI_MFIM } },
{ 0xe694008c, 0xe69400cc, 8, /* IMR3A / IMCR3A */
{ DMAC3_1_DEI3, DMAC3_1_DEI2, DMAC3_1_DEI1, DMAC3_1_DEI0,
DMAC3_2_DADERR, DMAC3_2_DEI5, DMAC3_2_DEI4, IRDA } },
{ 0xe6940090, 0xe69400d0, 8, /* IMR4A / IMCR4A */
{ DDM, 0, 0, 0,
0, 0, 0, 0 } },
{ 0xe6940094, 0xe69400d4, 8, /* IMR5A / IMCR5A */
{ KEYSC_KEY, DMAC1_2_DADERR, DMAC1_2_DEI5, DMAC1_2_DEI4,
SCIFA3, SCIFA2, SCIFA1, SCIFA0 } },
{ 0xe6940098, 0xe69400d8, 8, /* IMR6A / IMCR6A */
{ SCIFB, SCIFA5, SCIFA4, MSIOF1,
0, 0, MSIOF2, 0 } },
{ 0xe694009c, 0xe69400dc, 8, /* IMR7A / IMCR7A */
{ SDHI0_SDHI0I3, SDHI0_SDHI0I2, SDHI0_SDHI0I1, SDHI0_SDHI0I0,
FLCTL_FLTREQ1I, FLCTL_FLTREQ0I, FLCTL_FLTENDI, FLCTL_FLSTEI } },
{ 0xe69400a0, 0xe69400e0, 8, /* IMR8A / IMCR8A */
{ 0, SDHI1_SDHI1I2, SDHI1_SDHI1I1, SDHI1_SDHI1I0,
TTI20, USBHSDMAC0_USHDMI, 0, 0 } },
{ 0xe69400a4, 0xe69400e4, 8, /* IMR9A / IMCR9A */
{ CMT1_CMT13, CMT1_CMT12, CMT1_CMT11, CMT1_CMT10,
CMT2, 0, 0, _3DG_SGX540 } },
{ 0xe69400a8, 0xe69400e8, 8, /* IMR10A / IMCR10A */
{ 0, DMAC2_2_DADERR, DMAC2_2_DEI5, DMAC2_2_DEI4,
0, 0, 0, 0 } },
{ 0xe69400ac, 0xe69400ec, 8, /* IMR11A / IMCR11A */
{ IIC1_DTEI1, IIC1_WAITI1, IIC1_TACKI1, IIC1_ALI1,
0, 0, IRREM, 0 } },
{ 0xe69400b0, 0xe69400f0, 8, /* IMR12A / IMCR12A */
{ 0, 0, TPU0, 0,
0, 0, 0, 0 } },
{ 0xe69400b4, 0xe69400f4, 8, /* IMR13A / IMCR13A */
{ SDHI2_SDHI2I3, SDHI2_SDHI2I2, SDHI2_SDHI2I1, SDHI2_SDHI2I0,
0, CMT3, 0, RWDT0 } },
{ 0xe6950080, 0xe69500c0, 8, /* IMR0A3 / IMCR0A3 */
{ SHWYSTAT_RT, SHWYSTAT_HS, SHWYSTAT_COM, 0,
0, 0, 0, 0 } },
{ 0xe6950090, 0xe69500d0, 8, /* IMR4A3 / IMCR4A3 */
{ 0, 0, 0, 0,
0, 0, 0, HDMI } },
{ 0xe6950094, 0xe69500d4, 8, /* IMR5A3 / IMCR5A3 */
{ SPU2_SPU0, SPU2_SPU1, FSI, FMSI,
0, 0, 0, MIPI_HSI } },
{ 0xe6950098, 0xe69500d8, 8, /* IMR6A3 / IMCR6A3 */
{ 0, IPMMU_IPMMUD, CEC_1, CEC_2,
AP_ARM_CTIIRQ, AP_ARM_DMAEXTERRIRQ,
AP_ARM_DMAIRQ, AP_ARM_DMASIRQ } },
{ 0xe695009c, 0xe69500dc, 8, /* IMR7A3 / IMCR7A3 */
{ MFIS2, CPORTR2S, CMT14, CMT15,
0, 0, MMC_MMC_ERR, MMC_MMC_NOR } },
{ 0xe69500a0, 0xe69500e0, 8, /* IMR8A3 / IMCR8A3 */
{ IIC4_ALI4, IIC4_TACKI4, IIC4_WAITI4, IIC4_DTEI4,
IIC3_ALI3, IIC3_TACKI3, IIC3_WAITI3, IIC3_DTEI3 } },
{ 0xe69500a4, 0xe69500e4, 8, /* IMR9A3 / IMCR9A3 */
{ 0, 0, 0, 0,
USB0_USB0I1, USB0_USB0I0, USB1_USB1I1, USB1_USB1I0 } },
{ 0xe69500a8, 0xe69500e8, 8, /* IMR10A3 / IMCR10A3 */
{ USBHSDMAC1_USHDMI, 0, 0, 0,
0, 0, 0, 0 } },
};
static struct intc_prio_reg intca_prio_registers[] __initdata = {
{ 0xe6940000, 0, 16, 4, /* IPRAA */ { DMAC3_1, DMAC3_2, CMT2, 0 } },
{ 0xe6940004, 0, 16, 4, /* IPRBA */ { IRDA, 0, BBIF1, BBIF2 } },
{ 0xe6940008, 0, 16, 4, /* IPRCA */ { 0, CRYPT_STD,
CMT1_CMT11, AP_ARM1 } },
{ 0xe694000c, 0, 16, 4, /* IPRDA */ { 0, 0,
CMT1_CMT12, 0 } },
{ 0xe6940010, 0, 16, 4, /* IPREA */ { DMAC1_1, MFI_MFIS,
MFI_MFIM, 0 } },
{ 0xe6940014, 0, 16, 4, /* IPRFA */ { KEYSC_KEY, DMAC1_2,
_3DG_SGX540, CMT1_CMT10 } },
{ 0xe6940018, 0, 16, 4, /* IPRGA */ { SCIFA0, SCIFA1,
SCIFA2, SCIFA3 } },
{ 0xe694001c, 0, 16, 4, /* IPRGH */ { MSIOF2, USBHSDMAC0_USHDMI,
FLCTL, SDHI0 } },
{ 0xe6940020, 0, 16, 4, /* IPRIA */ { MSIOF1, SCIFA4,
0/* MSU */, IIC1 } },
{ 0xe6940024, 0, 16, 4, /* IPRJA */ { DMAC2_1, DMAC2_2,
0/* MSUG */, TTI20 } },
{ 0xe6940028, 0, 16, 4, /* IPRKA */ { 0, CMT1_CMT13, IRREM, SDHI1 } },
{ 0xe694002c, 0, 16, 4, /* IPRLA */ { TPU0, 0, 0, 0 } },
{ 0xe6940030, 0, 16, 4, /* IPRMA */ { 0, CMT3, 0, RWDT0 } },
{ 0xe6940034, 0, 16, 4, /* IPRNA */ { SCIFB, SCIFA5, 0, DDM } },
{ 0xe6940038, 0, 16, 4, /* IPROA */ { 0, 0, DIRC, SDHI2 } },
{ 0xe6950000, 0, 16, 4, /* IPRAA3 */ { SHWYSTAT, 0, 0, 0 } },
{ 0xe6950024, 0, 16, 4, /* IPRJA3 */ { 0, 0, 0, HDMI } },
{ 0xe6950028, 0, 16, 4, /* IPRKA3 */ { SPU2, 0, FSI, FMSI } },
{ 0xe695002c, 0, 16, 4, /* IPRLA3 */ { 0, 0, 0, MIPI_HSI } },
{ 0xe6950030, 0, 16, 4, /* IPRMA3 */ { IPMMU_IPMMUD, 0,
CEC_1, CEC_2 } },
{ 0xe6950034, 0, 16, 4, /* IPRNA3 */ { AP_ARM2, 0, 0, 0 } },
{ 0xe6950038, 0, 16, 4, /* IPROA3 */ { MFIS2, CPORTR2S,
CMT14, CMT15 } },
{ 0xe695003c, 0, 16, 4, /* IPRPA3 */ { 0, 0,
MMC_MMC_ERR, MMC_MMC_NOR } },
{ 0xe6950040, 0, 16, 4, /* IPRQA3 */ { IIC4_ALI4, IIC4_TACKI4,
IIC4_WAITI4, IIC4_DTEI4 } },
{ 0xe6950044, 0, 16, 4, /* IPRRA3 */ { IIC3_ALI3, IIC3_TACKI3,
IIC3_WAITI3, IIC3_DTEI3 } },
{ 0xe6950048, 0, 16, 4, /* IPRSA3 */ { 0/*ERI*/, 0/*RXI*/,
0/*TXI*/, 0/*TEI*/} },
{ 0xe695004c, 0, 16, 4, /* IPRTA3 */ { USB0_USB0I1, USB0_USB0I0,
USB1_USB1I1, USB1_USB1I0 } },
{ 0xe6950050, 0, 16, 4, /* IPRUA3 */ { USBHSDMAC1_USHDMI, 0, 0, 0 } },
};
static DECLARE_INTC_DESC(intca_desc, "sh7372-intca",
intca_vectors, intca_groups,
intca_mask_registers, intca_prio_registers,
NULL);
INTC_IRQ_PINS_32(intca_irq_pins, 0xe6900000,
INTC_VECT, "sh7372-intca-irq-pins");
enum {
UNUSED_INTCS = 0,
ENABLED_INTCS,
INTCS,
/* interrupt sources INTCS */
/* IRQ0S - IRQ31S */
VEU_VEU0, VEU_VEU1, VEU_VEU2, VEU_VEU3,
RTDMAC_1_DEI0, RTDMAC_1_DEI1, RTDMAC_1_DEI2, RTDMAC_1_DEI3,
CEU, BEU_BEU0, BEU_BEU1, BEU_BEU2,
/* MFI */
/* BBIF2 */
VPU,
TSIF1,
/* 3DG */
_2DDMAC,
IIC2_ALI2, IIC2_TACKI2, IIC2_WAITI2, IIC2_DTEI2,
IPMMU_IPMMUR, IPMMU_IPMMUR2,
RTDMAC_2_DEI4, RTDMAC_2_DEI5, RTDMAC_2_DADERR,
/* KEYSC */
/* TTI20 */
MSIOF,
IIC0_ALI0, IIC0_TACKI0, IIC0_WAITI0, IIC0_DTEI0,
TMU_TUNI0, TMU_TUNI1, TMU_TUNI2,
CMT0,
TSIF0,
/* CMT2 */
LMB,
CTI,
/* RWDT0 */
ICB,
JPU_JPEG,
LCDC,
LCRC,
RTDMAC2_1_DEI0, RTDMAC2_1_DEI1, RTDMAC2_1_DEI2, RTDMAC2_1_DEI3,
RTDMAC2_2_DEI4, RTDMAC2_2_DEI5, RTDMAC2_2_DADERR,
ISP,
LCDC1,
CSIRX,
DSITX_DSITX0,
DSITX_DSITX1,
/* SPU2 */
/* FSI */
/* FMSI */
/* HDMI */
TMU1_TUNI0, TMU1_TUNI1, TMU1_TUNI2,
CMT4,
DSITX1_DSITX1_0,
DSITX1_DSITX1_1,
MFIS2_INTCS, /* Priority always enabled using ENABLED_INTCS */
CPORTS2R,
/* CEC */
JPU6E,
/* interrupt groups INTCS */
RTDMAC_1, RTDMAC_2, VEU, BEU, IIC0, IPMMU, IIC2,
RTDMAC2_1, RTDMAC2_2, TMU1, DSITX,
};
static struct intc_vect intcs_vectors[] = {
/* IRQ0S - IRQ31S */
INTCS_VECT(VEU_VEU0, 0x700), INTCS_VECT(VEU_VEU1, 0x720),
INTCS_VECT(VEU_VEU2, 0x740), INTCS_VECT(VEU_VEU3, 0x760),
INTCS_VECT(RTDMAC_1_DEI0, 0x800), INTCS_VECT(RTDMAC_1_DEI1, 0x820),
INTCS_VECT(RTDMAC_1_DEI2, 0x840), INTCS_VECT(RTDMAC_1_DEI3, 0x860),
INTCS_VECT(CEU, 0x880), INTCS_VECT(BEU_BEU0, 0x8a0),
INTCS_VECT(BEU_BEU1, 0x8c0), INTCS_VECT(BEU_BEU2, 0x8e0),
/* MFI */
/* BBIF2 */
INTCS_VECT(VPU, 0x980),
INTCS_VECT(TSIF1, 0x9a0),
/* 3DG */
INTCS_VECT(_2DDMAC, 0xa00),
INTCS_VECT(IIC2_ALI2, 0xa80), INTCS_VECT(IIC2_TACKI2, 0xaa0),
INTCS_VECT(IIC2_WAITI2, 0xac0), INTCS_VECT(IIC2_DTEI2, 0xae0),
INTCS_VECT(IPMMU_IPMMUR, 0xb00), INTCS_VECT(IPMMU_IPMMUR2, 0xb20),
INTCS_VECT(RTDMAC_2_DEI4, 0xb80), INTCS_VECT(RTDMAC_2_DEI5, 0xba0),
INTCS_VECT(RTDMAC_2_DADERR, 0xbc0),
/* KEYSC */
/* TTI20 */
INTCS_VECT(MSIOF, 0x0d20),
INTCS_VECT(IIC0_ALI0, 0xe00), INTCS_VECT(IIC0_TACKI0, 0xe20),
INTCS_VECT(IIC0_WAITI0, 0xe40), INTCS_VECT(IIC0_DTEI0, 0xe60),
INTCS_VECT(TMU_TUNI0, 0xe80), INTCS_VECT(TMU_TUNI1, 0xea0),
INTCS_VECT(TMU_TUNI2, 0xec0),
INTCS_VECT(CMT0, 0xf00),
INTCS_VECT(TSIF0, 0xf20),
/* CMT2 */
INTCS_VECT(LMB, 0xf60),
INTCS_VECT(CTI, 0x400),
/* RWDT0 */
INTCS_VECT(ICB, 0x480),
INTCS_VECT(JPU_JPEG, 0x560),
INTCS_VECT(LCDC, 0x580),
INTCS_VECT(LCRC, 0x5a0),
INTCS_VECT(RTDMAC2_1_DEI0, 0x1300), INTCS_VECT(RTDMAC2_1_DEI1, 0x1320),
INTCS_VECT(RTDMAC2_1_DEI2, 0x1340), INTCS_VECT(RTDMAC2_1_DEI3, 0x1360),
INTCS_VECT(RTDMAC2_2_DEI4, 0x1380), INTCS_VECT(RTDMAC2_2_DEI5, 0x13a0),
INTCS_VECT(RTDMAC2_2_DADERR, 0x13c0),
INTCS_VECT(ISP, 0x1720),
INTCS_VECT(LCDC1, 0x1780),
INTCS_VECT(CSIRX, 0x17a0),
INTCS_VECT(DSITX_DSITX0, 0x17c0),
INTCS_VECT(DSITX_DSITX1, 0x17e0),
/* SPU2 */
/* FSI */
/* FMSI */
/* HDMI */
INTCS_VECT(TMU1_TUNI0, 0x1900), INTCS_VECT(TMU1_TUNI1, 0x1920),
INTCS_VECT(TMU1_TUNI2, 0x1940),
INTCS_VECT(CMT4, 0x1980),
INTCS_VECT(DSITX1_DSITX1_0, 0x19a0),
INTCS_VECT(DSITX1_DSITX1_1, 0x19c0),
INTCS_VECT(MFIS2_INTCS, 0x1a00),
INTCS_VECT(CPORTS2R, 0x1a20),
/* CEC */
INTCS_VECT(JPU6E, 0x1a80),
INTC_VECT(INTCS, 0xf80),
};
static struct intc_group intcs_groups[] __initdata = {
INTC_GROUP(RTDMAC_1, RTDMAC_1_DEI0, RTDMAC_1_DEI1,
RTDMAC_1_DEI2, RTDMAC_1_DEI3),
INTC_GROUP(RTDMAC_2, RTDMAC_2_DEI4, RTDMAC_2_DEI5, RTDMAC_2_DADERR),
INTC_GROUP(VEU, VEU_VEU0, VEU_VEU1, VEU_VEU2, VEU_VEU3),
INTC_GROUP(BEU, BEU_BEU0, BEU_BEU1, BEU_BEU2),
INTC_GROUP(IIC0, IIC0_ALI0, IIC0_TACKI0, IIC0_WAITI0, IIC0_DTEI0),
INTC_GROUP(IPMMU, IPMMU_IPMMUR, IPMMU_IPMMUR2),
INTC_GROUP(IIC2, IIC2_ALI2, IIC2_TACKI2, IIC2_WAITI2, IIC2_DTEI2),
INTC_GROUP(RTDMAC2_1, RTDMAC2_1_DEI0, RTDMAC2_1_DEI1,
RTDMAC2_1_DEI2, RTDMAC2_1_DEI3),
INTC_GROUP(RTDMAC2_2, RTDMAC2_2_DEI4,
RTDMAC2_2_DEI5, RTDMAC2_2_DADERR),
INTC_GROUP(TMU1, TMU1_TUNI2, TMU1_TUNI1, TMU1_TUNI0),
INTC_GROUP(DSITX, DSITX_DSITX0, DSITX_DSITX1),
};
static struct intc_mask_reg intcs_mask_registers[] = {
{ 0xffd20184, 0xffd201c4, 8, /* IMR1SA / IMCR1SA */
{ BEU_BEU2, BEU_BEU1, BEU_BEU0, CEU,
VEU_VEU3, VEU_VEU2, VEU_VEU1, VEU_VEU0 } },
{ 0xffd20188, 0xffd201c8, 8, /* IMR2SA / IMCR2SA */
{ 0, 0, 0, VPU,
0, 0, 0, 0 } },
{ 0xffd2018c, 0xffd201cc, 8, /* IMR3SA / IMCR3SA */
{ 0, 0, 0, _2DDMAC,
0, 0, 0, ICB } },
{ 0xffd20190, 0xffd201d0, 8, /* IMR4SA / IMCR4SA */
{ 0, 0, 0, CTI,
JPU_JPEG, 0, LCRC, LCDC } },
{ 0xffd20194, 0xffd201d4, 8, /* IMR5SA / IMCR5SA */
{ 0, RTDMAC_2_DADERR, RTDMAC_2_DEI5, RTDMAC_2_DEI4,
RTDMAC_1_DEI3, RTDMAC_1_DEI2, RTDMAC_1_DEI1, RTDMAC_1_DEI0 } },
{ 0xffd20198, 0xffd201d8, 8, /* IMR6SA / IMCR6SA */
{ 0, 0, MSIOF, 0,
0, 0, 0, 0 } },
{ 0xffd2019c, 0xffd201dc, 8, /* IMR7SA / IMCR7SA */
{ 0, TMU_TUNI2, TMU_TUNI1, TMU_TUNI0,
0, 0, 0, 0 } },
{ 0xffd201a4, 0xffd201e4, 8, /* IMR9SA / IMCR9SA */
{ 0, 0, 0, CMT0,
IIC2_DTEI2, IIC2_WAITI2, IIC2_TACKI2, IIC2_ALI2 } },
{ 0xffd201a8, 0xffd201e8, 8, /* IMR10SA / IMCR10SA */
{ 0, 0, IPMMU_IPMMUR2, IPMMU_IPMMUR,
0, 0, 0, 0 } },
{ 0xffd201ac, 0xffd201ec, 8, /* IMR11SA / IMCR11SA */
{ IIC0_DTEI0, IIC0_WAITI0, IIC0_TACKI0, IIC0_ALI0,
0, TSIF1, LMB, TSIF0 } },
{ 0xffd50180, 0xffd501c0, 8, /* IMR0SA3 / IMCR0SA3 */
{ 0, RTDMAC2_2_DADERR, RTDMAC2_2_DEI5, RTDMAC2_2_DEI4,
RTDMAC2_1_DEI3, RTDMAC2_1_DEI2, RTDMAC2_1_DEI1, RTDMAC2_1_DEI0 } },
{ 0xffd50190, 0xffd501d0, 8, /* IMR4SA3 / IMCR4SA3 */
{ 0, ISP, 0, 0,
LCDC1, CSIRX, DSITX_DSITX0, DSITX_DSITX1 } },
{ 0xffd50198, 0xffd501d8, 8, /* IMR6SA3 / IMCR6SA3 */
{ 0, TMU1_TUNI2, TMU1_TUNI1, TMU1_TUNI0,
CMT4, DSITX1_DSITX1_0, DSITX1_DSITX1_1, 0 } },
{ 0xffd5019c, 0xffd501dc, 8, /* IMR7SA3 / IMCR7SA3 */
{ MFIS2_INTCS, CPORTS2R, 0, 0,
JPU6E, 0, 0, 0 } },
{ 0xffd20104, 0, 16, /* INTAMASK */
{ 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, INTCS } },
};
/* Priority is needed for INTCA to receive the INTCS interrupt */
static struct intc_prio_reg intcs_prio_registers[] = {
{ 0xffd20000, 0, 16, 4, /* IPRAS */ { CTI, 0, _2DDMAC, ICB } },
{ 0xffd20004, 0, 16, 4, /* IPRBS */ { JPU_JPEG, LCDC, 0, LCRC } },
{ 0xffd20010, 0, 16, 4, /* IPRES */ { RTDMAC_1, CEU, 0, VPU } },
{ 0xffd20014, 0, 16, 4, /* IPRFS */ { 0, RTDMAC_2, 0, CMT0 } },
{ 0xffd20018, 0, 16, 4, /* IPRGS */ { TMU_TUNI0, TMU_TUNI1,
TMU_TUNI2, TSIF1 } },
{ 0xffd2001c, 0, 16, 4, /* IPRHS */ { 0, 0, VEU, BEU } },
{ 0xffd20020, 0, 16, 4, /* IPRIS */ { 0, MSIOF, TSIF0, IIC0 } },
{ 0xffd20028, 0, 16, 4, /* IPRKS */ { 0, 0, LMB, 0 } },
{ 0xffd2002c, 0, 16, 4, /* IPRLS */ { IPMMU, 0, 0, 0 } },
{ 0xffd20030, 0, 16, 4, /* IPRMS */ { IIC2, 0, 0, 0 } },
{ 0xffd50000, 0, 16, 4, /* IPRAS3 */ { RTDMAC2_1, 0, 0, 0 } },
{ 0xffd50004, 0, 16, 4, /* IPRBS3 */ { RTDMAC2_2, 0, 0, 0 } },
{ 0xffd50020, 0, 16, 4, /* IPRIS3 */ { 0, ISP, 0, 0 } },
{ 0xffd50024, 0, 16, 4, /* IPRJS3 */ { LCDC1, CSIRX, DSITX, 0 } },
{ 0xffd50030, 0, 16, 4, /* IPRMS3 */ { TMU1, 0, 0, 0 } },
{ 0xffd50034, 0, 16, 4, /* IPRNS3 */ { CMT4, DSITX1_DSITX1_0,
DSITX1_DSITX1_1, 0 } },
{ 0xffd50038, 0, 16, 4, /* IPROS3 */ { ENABLED_INTCS, CPORTS2R,
0, 0 } },
{ 0xffd5003c, 0, 16, 4, /* IPRPS3 */ { JPU6E, 0, 0, 0 } },
};
static struct resource intcs_resources[] __initdata = {
[0] = {
.start = 0xffd20000,
.end = 0xffd201ff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 0xffd50000,
.end = 0xffd501ff,
.flags = IORESOURCE_MEM,
}
};
static struct intc_desc intcs_desc __initdata = {
.name = "sh7372-intcs",
.force_enable = ENABLED_INTCS,
.skip_syscore_suspend = true,
.resource = intcs_resources,
.num_resources = ARRAY_SIZE(intcs_resources),
.hw = INTC_HW_DESC(intcs_vectors, intcs_groups, intcs_mask_registers,
intcs_prio_registers, NULL, NULL),
};
static void intcs_demux(unsigned int irq, struct irq_desc *desc)
{
void __iomem *reg = (void *)irq_get_handler_data(irq);
unsigned int evtcodeas = ioread32(reg);
generic_handle_irq(intcs_evt2irq(evtcodeas));
}
static void __iomem *intcs_ffd2;
static void __iomem *intcs_ffd5;
void __init sh7372_init_irq(void)
{
void __iomem *intevtsa;
intcs_ffd2 = ioremap_nocache(0xffd20000, PAGE_SIZE);
intevtsa = intcs_ffd2 + 0x100;
intcs_ffd5 = ioremap_nocache(0xffd50000, PAGE_SIZE);
register_intc_controller(&intca_desc);
register_intc_controller(&intca_irq_pins_desc);
register_intc_controller(&intcs_desc);
/* demux using INTEVTSA */
irq_set_handler_data(evt2irq(0xf80), (void *)intevtsa);
irq_set_chained_handler(evt2irq(0xf80), intcs_demux);
}
static unsigned short ffd2[0x200];
static unsigned short ffd5[0x100];
void sh7372_intcs_suspend(void)
{
int k;
for (k = 0x00; k <= 0x30; k += 4)
ffd2[k] = __raw_readw(intcs_ffd2 + k);
for (k = 0x80; k <= 0xb0; k += 4)
ffd2[k] = __raw_readb(intcs_ffd2 + k);
for (k = 0x180; k <= 0x188; k += 4)
ffd2[k] = __raw_readb(intcs_ffd2 + k);
for (k = 0x00; k <= 0x3c; k += 4)
ffd5[k] = __raw_readw(intcs_ffd5 + k);
for (k = 0x80; k <= 0x9c; k += 4)
ffd5[k] = __raw_readb(intcs_ffd5 + k);
}
void sh7372_intcs_resume(void)
{
int k;
for (k = 0x00; k <= 0x30; k += 4)
__raw_writew(ffd2[k], intcs_ffd2 + k);
for (k = 0x80; k <= 0xb0; k += 4)
__raw_writeb(ffd2[k], intcs_ffd2 + k);
for (k = 0x180; k <= 0x188; k += 4)
__raw_writeb(ffd2[k], intcs_ffd2 + k);
for (k = 0x00; k <= 0x3c; k += 4)
__raw_writew(ffd5[k], intcs_ffd5 + k);
for (k = 0x80; k <= 0x9c; k += 4)
__raw_writeb(ffd5[k], intcs_ffd5 + k);
}
static unsigned short e694[0x200];
static unsigned short e695[0x200];
void sh7372_intca_suspend(void)
{
int k;
for (k = 0x00; k <= 0x38; k += 4)
e694[k] = __raw_readw(0xe6940000 + k);
for (k = 0x80; k <= 0xb4; k += 4)
e694[k] = __raw_readb(0xe6940000 + k);
for (k = 0x180; k <= 0x1b4; k += 4)
e694[k] = __raw_readb(0xe6940000 + k);
for (k = 0x00; k <= 0x50; k += 4)
e695[k] = __raw_readw(0xe6950000 + k);
for (k = 0x80; k <= 0xa8; k += 4)
e695[k] = __raw_readb(0xe6950000 + k);
for (k = 0x180; k <= 0x1a8; k += 4)
e695[k] = __raw_readb(0xe6950000 + k);
}
void sh7372_intca_resume(void)
{
int k;
for (k = 0x00; k <= 0x38; k += 4)
__raw_writew(e694[k], 0xe6940000 + k);
for (k = 0x80; k <= 0xb4; k += 4)
__raw_writeb(e694[k], 0xe6940000 + k);
for (k = 0x180; k <= 0x1b4; k += 4)
__raw_writeb(e694[k], 0xe6940000 + k);
for (k = 0x00; k <= 0x50; k += 4)
__raw_writew(e695[k], 0xe6950000 + k);
for (k = 0x80; k <= 0xa8; k += 4)
__raw_writeb(e695[k], 0xe6950000 + k);
for (k = 0x180; k <= 0x1a8; k += 4)
__raw_writeb(e695[k], 0xe6950000 + k);
}
| gpl-2.0 |
ronasimi/android.googlesource.com-kernel-msm | drivers/net/ethernet/broadcom/sb1250-mac.c | 4987 | 66470 | /*
* Copyright (C) 2001,2002,2003,2004 Broadcom Corporation
* Copyright (c) 2006, 2007 Maciej W. Rozycki
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*
* This driver is designed for the Broadcom SiByte SOC built-in
* Ethernet controllers. Written by Mitch Lichtenberg at Broadcom Corp.
*
* Updated to the driver model and the PHY abstraction layer
* by Maciej W. Rozycki.
*/
#include <linux/bug.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/bitops.h>
#include <linux/err.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/phy.h>
#include <linux/platform_device.h>
#include <linux/prefetch.h>
#include <asm/cache.h>
#include <asm/io.h>
#include <asm/processor.h> /* Processor type for cache alignment. */
/* Operational parameters that usually are not changed. */
#define CONFIG_SBMAC_COALESCE
/* Time in jiffies before concluding the transmitter is hung. */
#define TX_TIMEOUT (2*HZ)
MODULE_AUTHOR("Mitch Lichtenberg (Broadcom Corp.)");
MODULE_DESCRIPTION("Broadcom SiByte SOC GB Ethernet driver");
/* A few user-configurable values which may be modified when a driver
module is loaded. */
/* 1 normal messages, 0 quiet .. 7 verbose. */
static int debug = 1;
module_param(debug, int, S_IRUGO);
MODULE_PARM_DESC(debug, "Debug messages");
#ifdef CONFIG_SBMAC_COALESCE
static int int_pktcnt_tx = 255;
module_param(int_pktcnt_tx, int, S_IRUGO);
MODULE_PARM_DESC(int_pktcnt_tx, "TX packet count");
static int int_timeout_tx = 255;
module_param(int_timeout_tx, int, S_IRUGO);
MODULE_PARM_DESC(int_timeout_tx, "TX timeout value");
static int int_pktcnt_rx = 64;
module_param(int_pktcnt_rx, int, S_IRUGO);
MODULE_PARM_DESC(int_pktcnt_rx, "RX packet count");
static int int_timeout_rx = 64;
module_param(int_timeout_rx, int, S_IRUGO);
MODULE_PARM_DESC(int_timeout_rx, "RX timeout value");
#endif
#include <asm/sibyte/board.h>
#include <asm/sibyte/sb1250.h>
#if defined(CONFIG_SIBYTE_BCM1x55) || defined(CONFIG_SIBYTE_BCM1x80)
#include <asm/sibyte/bcm1480_regs.h>
#include <asm/sibyte/bcm1480_int.h>
#define R_MAC_DMA_OODPKTLOST_RX R_MAC_DMA_OODPKTLOST
#elif defined(CONFIG_SIBYTE_SB1250) || defined(CONFIG_SIBYTE_BCM112X)
#include <asm/sibyte/sb1250_regs.h>
#include <asm/sibyte/sb1250_int.h>
#else
#error invalid SiByte MAC configuration
#endif
#include <asm/sibyte/sb1250_scd.h>
#include <asm/sibyte/sb1250_mac.h>
#include <asm/sibyte/sb1250_dma.h>
#if defined(CONFIG_SIBYTE_BCM1x55) || defined(CONFIG_SIBYTE_BCM1x80)
#define UNIT_INT(n) (K_BCM1480_INT_MAC_0 + ((n) * 2))
#elif defined(CONFIG_SIBYTE_SB1250) || defined(CONFIG_SIBYTE_BCM112X)
#define UNIT_INT(n) (K_INT_MAC_0 + (n))
#else
#error invalid SiByte MAC configuration
#endif
#ifdef K_INT_PHY
#define SBMAC_PHY_INT K_INT_PHY
#else
#define SBMAC_PHY_INT PHY_POLL
#endif
/**********************************************************************
* Simple types
********************************************************************* */
enum sbmac_speed {
sbmac_speed_none = 0,
sbmac_speed_10 = SPEED_10,
sbmac_speed_100 = SPEED_100,
sbmac_speed_1000 = SPEED_1000,
};
enum sbmac_duplex {
sbmac_duplex_none = -1,
sbmac_duplex_half = DUPLEX_HALF,
sbmac_duplex_full = DUPLEX_FULL,
};
enum sbmac_fc {
sbmac_fc_none,
sbmac_fc_disabled,
sbmac_fc_frame,
sbmac_fc_collision,
sbmac_fc_carrier,
};
enum sbmac_state {
sbmac_state_uninit,
sbmac_state_off,
sbmac_state_on,
sbmac_state_broken,
};
/**********************************************************************
* Macros
********************************************************************* */
#define SBDMA_NEXTBUF(d,f) ((((d)->f+1) == (d)->sbdma_dscrtable_end) ? \
(d)->sbdma_dscrtable : (d)->f+1)
#define NUMCACHEBLKS(x) (((x)+SMP_CACHE_BYTES-1)/SMP_CACHE_BYTES)
#define SBMAC_MAX_TXDESCR 256
#define SBMAC_MAX_RXDESCR 256
#define ENET_PACKET_SIZE 1518
/*#define ENET_PACKET_SIZE 9216 */
/**********************************************************************
* DMA Descriptor structure
********************************************************************* */
struct sbdmadscr {
uint64_t dscr_a;
uint64_t dscr_b;
};
/**********************************************************************
* DMA Controller structure
********************************************************************* */
struct sbmacdma {
/*
* This stuff is used to identify the channel and the registers
* associated with it.
*/
struct sbmac_softc *sbdma_eth; /* back pointer to associated
MAC */
int sbdma_channel; /* channel number */
int sbdma_txdir; /* direction (1=transmit) */
int sbdma_maxdescr; /* total # of descriptors
in ring */
#ifdef CONFIG_SBMAC_COALESCE
int sbdma_int_pktcnt;
/* # descriptors rx/tx
before interrupt */
int sbdma_int_timeout;
/* # usec rx/tx interrupt */
#endif
void __iomem *sbdma_config0; /* DMA config register 0 */
void __iomem *sbdma_config1; /* DMA config register 1 */
void __iomem *sbdma_dscrbase;
/* descriptor base address */
void __iomem *sbdma_dscrcnt; /* descriptor count register */
void __iomem *sbdma_curdscr; /* current descriptor
address */
void __iomem *sbdma_oodpktlost;
/* pkt drop (rx only) */
/*
* This stuff is for maintenance of the ring
*/
void *sbdma_dscrtable_unaligned;
struct sbdmadscr *sbdma_dscrtable;
/* base of descriptor table */
struct sbdmadscr *sbdma_dscrtable_end;
/* end of descriptor table */
struct sk_buff **sbdma_ctxtable;
/* context table, one
per descr */
dma_addr_t sbdma_dscrtable_phys;
/* and also the phys addr */
struct sbdmadscr *sbdma_addptr; /* next dscr for sw to add */
struct sbdmadscr *sbdma_remptr; /* next dscr for sw
to remove */
};
/**********************************************************************
* Ethernet softc structure
********************************************************************* */
struct sbmac_softc {
/*
* Linux-specific things
*/
struct net_device *sbm_dev; /* pointer to linux device */
struct napi_struct napi;
struct phy_device *phy_dev; /* the associated PHY device */
struct mii_bus *mii_bus; /* the MII bus */
int phy_irq[PHY_MAX_ADDR];
spinlock_t sbm_lock; /* spin lock */
int sbm_devflags; /* current device flags */
/*
* Controller-specific things
*/
void __iomem *sbm_base; /* MAC's base address */
enum sbmac_state sbm_state; /* current state */
void __iomem *sbm_macenable; /* MAC Enable Register */
void __iomem *sbm_maccfg; /* MAC Config Register */
void __iomem *sbm_fifocfg; /* FIFO Config Register */
void __iomem *sbm_framecfg; /* Frame Config Register */
void __iomem *sbm_rxfilter; /* Receive Filter Register */
void __iomem *sbm_isr; /* Interrupt Status Register */
void __iomem *sbm_imr; /* Interrupt Mask Register */
void __iomem *sbm_mdio; /* MDIO Register */
enum sbmac_speed sbm_speed; /* current speed */
enum sbmac_duplex sbm_duplex; /* current duplex */
enum sbmac_fc sbm_fc; /* cur. flow control setting */
int sbm_pause; /* current pause setting */
int sbm_link; /* current link state */
unsigned char sbm_hwaddr[ETH_ALEN];
struct sbmacdma sbm_txdma; /* only channel 0 for now */
struct sbmacdma sbm_rxdma;
int rx_hw_checksum;
int sbe_idx;
};
/**********************************************************************
* Externs
********************************************************************* */
/**********************************************************************
* Prototypes
********************************************************************* */
static void sbdma_initctx(struct sbmacdma *d, struct sbmac_softc *s, int chan,
int txrx, int maxdescr);
static void sbdma_channel_start(struct sbmacdma *d, int rxtx);
static int sbdma_add_rcvbuffer(struct sbmac_softc *sc, struct sbmacdma *d,
struct sk_buff *m);
static int sbdma_add_txbuffer(struct sbmacdma *d, struct sk_buff *m);
static void sbdma_emptyring(struct sbmacdma *d);
static void sbdma_fillring(struct sbmac_softc *sc, struct sbmacdma *d);
static int sbdma_rx_process(struct sbmac_softc *sc, struct sbmacdma *d,
int work_to_do, int poll);
static void sbdma_tx_process(struct sbmac_softc *sc, struct sbmacdma *d,
int poll);
static int sbmac_initctx(struct sbmac_softc *s);
static void sbmac_channel_start(struct sbmac_softc *s);
static void sbmac_channel_stop(struct sbmac_softc *s);
static enum sbmac_state sbmac_set_channel_state(struct sbmac_softc *,
enum sbmac_state);
static void sbmac_promiscuous_mode(struct sbmac_softc *sc, int onoff);
static uint64_t sbmac_addr2reg(unsigned char *ptr);
static irqreturn_t sbmac_intr(int irq, void *dev_instance);
static int sbmac_start_tx(struct sk_buff *skb, struct net_device *dev);
static void sbmac_setmulti(struct sbmac_softc *sc);
static int sbmac_init(struct platform_device *pldev, long long base);
static int sbmac_set_speed(struct sbmac_softc *s, enum sbmac_speed speed);
static int sbmac_set_duplex(struct sbmac_softc *s, enum sbmac_duplex duplex,
enum sbmac_fc fc);
static int sbmac_open(struct net_device *dev);
static void sbmac_tx_timeout (struct net_device *dev);
static void sbmac_set_rx_mode(struct net_device *dev);
static int sbmac_mii_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
static int sbmac_close(struct net_device *dev);
static int sbmac_poll(struct napi_struct *napi, int budget);
static void sbmac_mii_poll(struct net_device *dev);
static int sbmac_mii_probe(struct net_device *dev);
static void sbmac_mii_sync(void __iomem *sbm_mdio);
static void sbmac_mii_senddata(void __iomem *sbm_mdio, unsigned int data,
int bitcnt);
static int sbmac_mii_read(struct mii_bus *bus, int phyaddr, int regidx);
static int sbmac_mii_write(struct mii_bus *bus, int phyaddr, int regidx,
u16 val);
/**********************************************************************
* Globals
********************************************************************* */
static char sbmac_string[] = "sb1250-mac";
static char sbmac_mdio_string[] = "sb1250-mac-mdio";
/**********************************************************************
* MDIO constants
********************************************************************* */
#define MII_COMMAND_START 0x01
#define MII_COMMAND_READ 0x02
#define MII_COMMAND_WRITE 0x01
#define MII_COMMAND_ACK 0x02
#define M_MAC_MDIO_DIR_OUTPUT 0 /* for clarity */
#define ENABLE 1
#define DISABLE 0
/**********************************************************************
* SBMAC_MII_SYNC(sbm_mdio)
*
* Synchronize with the MII - send a pattern of bits to the MII
* that will guarantee that it is ready to accept a command.
*
* Input parameters:
* sbm_mdio - address of the MAC's MDIO register
*
* Return value:
* nothing
********************************************************************* */
static void sbmac_mii_sync(void __iomem *sbm_mdio)
{
int cnt;
uint64_t bits;
int mac_mdio_genc;
mac_mdio_genc = __raw_readq(sbm_mdio) & M_MAC_GENC;
bits = M_MAC_MDIO_DIR_OUTPUT | M_MAC_MDIO_OUT;
__raw_writeq(bits | mac_mdio_genc, sbm_mdio);
for (cnt = 0; cnt < 32; cnt++) {
__raw_writeq(bits | M_MAC_MDC | mac_mdio_genc, sbm_mdio);
__raw_writeq(bits | mac_mdio_genc, sbm_mdio);
}
}
/**********************************************************************
* SBMAC_MII_SENDDATA(sbm_mdio, data, bitcnt)
*
* Send some bits to the MII. The bits to be sent are right-
* justified in the 'data' parameter.
*
* Input parameters:
* sbm_mdio - address of the MAC's MDIO register
* data - data to send
* bitcnt - number of bits to send
********************************************************************* */
static void sbmac_mii_senddata(void __iomem *sbm_mdio, unsigned int data,
int bitcnt)
{
int i;
uint64_t bits;
unsigned int curmask;
int mac_mdio_genc;
mac_mdio_genc = __raw_readq(sbm_mdio) & M_MAC_GENC;
bits = M_MAC_MDIO_DIR_OUTPUT;
__raw_writeq(bits | mac_mdio_genc, sbm_mdio);
curmask = 1 << (bitcnt - 1);
for (i = 0; i < bitcnt; i++) {
if (data & curmask)
bits |= M_MAC_MDIO_OUT;
else bits &= ~M_MAC_MDIO_OUT;
__raw_writeq(bits | mac_mdio_genc, sbm_mdio);
__raw_writeq(bits | M_MAC_MDC | mac_mdio_genc, sbm_mdio);
__raw_writeq(bits | mac_mdio_genc, sbm_mdio);
curmask >>= 1;
}
}
/**********************************************************************
* SBMAC_MII_READ(bus, phyaddr, regidx)
* Read a PHY register.
*
* Input parameters:
* bus - MDIO bus handle
* phyaddr - PHY's address
* regnum - index of register to read
*
* Return value:
* value read, or 0xffff if an error occurred.
********************************************************************* */
static int sbmac_mii_read(struct mii_bus *bus, int phyaddr, int regidx)
{
struct sbmac_softc *sc = (struct sbmac_softc *)bus->priv;
void __iomem *sbm_mdio = sc->sbm_mdio;
int idx;
int error;
int regval;
int mac_mdio_genc;
/*
* Synchronize ourselves so that the PHY knows the next
* thing coming down is a command
*/
sbmac_mii_sync(sbm_mdio);
/*
* Send the data to the PHY. The sequence is
* a "start" command (2 bits)
* a "read" command (2 bits)
* the PHY addr (5 bits)
* the register index (5 bits)
*/
sbmac_mii_senddata(sbm_mdio, MII_COMMAND_START, 2);
sbmac_mii_senddata(sbm_mdio, MII_COMMAND_READ, 2);
sbmac_mii_senddata(sbm_mdio, phyaddr, 5);
sbmac_mii_senddata(sbm_mdio, regidx, 5);
mac_mdio_genc = __raw_readq(sbm_mdio) & M_MAC_GENC;
/*
* Switch the port around without a clock transition.
*/
__raw_writeq(M_MAC_MDIO_DIR_INPUT | mac_mdio_genc, sbm_mdio);
/*
* Send out a clock pulse to signal we want the status
*/
__raw_writeq(M_MAC_MDIO_DIR_INPUT | M_MAC_MDC | mac_mdio_genc,
sbm_mdio);
__raw_writeq(M_MAC_MDIO_DIR_INPUT | mac_mdio_genc, sbm_mdio);
/*
* If an error occurred, the PHY will signal '1' back
*/
error = __raw_readq(sbm_mdio) & M_MAC_MDIO_IN;
/*
* Issue an 'idle' clock pulse, but keep the direction
* the same.
*/
__raw_writeq(M_MAC_MDIO_DIR_INPUT | M_MAC_MDC | mac_mdio_genc,
sbm_mdio);
__raw_writeq(M_MAC_MDIO_DIR_INPUT | mac_mdio_genc, sbm_mdio);
regval = 0;
for (idx = 0; idx < 16; idx++) {
regval <<= 1;
if (error == 0) {
if (__raw_readq(sbm_mdio) & M_MAC_MDIO_IN)
regval |= 1;
}
__raw_writeq(M_MAC_MDIO_DIR_INPUT | M_MAC_MDC | mac_mdio_genc,
sbm_mdio);
__raw_writeq(M_MAC_MDIO_DIR_INPUT | mac_mdio_genc, sbm_mdio);
}
/* Switch back to output */
__raw_writeq(M_MAC_MDIO_DIR_OUTPUT | mac_mdio_genc, sbm_mdio);
if (error == 0)
return regval;
return 0xffff;
}
/**********************************************************************
* SBMAC_MII_WRITE(bus, phyaddr, regidx, regval)
*
* Write a value to a PHY register.
*
* Input parameters:
* bus - MDIO bus handle
* phyaddr - PHY to use
* regidx - register within the PHY
* regval - data to write to register
*
* Return value:
* 0 for success
********************************************************************* */
static int sbmac_mii_write(struct mii_bus *bus, int phyaddr, int regidx,
u16 regval)
{
struct sbmac_softc *sc = (struct sbmac_softc *)bus->priv;
void __iomem *sbm_mdio = sc->sbm_mdio;
int mac_mdio_genc;
sbmac_mii_sync(sbm_mdio);
sbmac_mii_senddata(sbm_mdio, MII_COMMAND_START, 2);
sbmac_mii_senddata(sbm_mdio, MII_COMMAND_WRITE, 2);
sbmac_mii_senddata(sbm_mdio, phyaddr, 5);
sbmac_mii_senddata(sbm_mdio, regidx, 5);
sbmac_mii_senddata(sbm_mdio, MII_COMMAND_ACK, 2);
sbmac_mii_senddata(sbm_mdio, regval, 16);
mac_mdio_genc = __raw_readq(sbm_mdio) & M_MAC_GENC;
__raw_writeq(M_MAC_MDIO_DIR_OUTPUT | mac_mdio_genc, sbm_mdio);
return 0;
}
/**********************************************************************
* SBDMA_INITCTX(d,s,chan,txrx,maxdescr)
*
* Initialize a DMA channel context. Since there are potentially
* eight DMA channels per MAC, it's nice to do this in a standard
* way.
*
* Input parameters:
* d - struct sbmacdma (DMA channel context)
* s - struct sbmac_softc (pointer to a MAC)
* chan - channel number (0..1 right now)
* txrx - Identifies DMA_TX or DMA_RX for channel direction
* maxdescr - number of descriptors
*
* Return value:
* nothing
********************************************************************* */
static void sbdma_initctx(struct sbmacdma *d, struct sbmac_softc *s, int chan,
int txrx, int maxdescr)
{
#ifdef CONFIG_SBMAC_COALESCE
int int_pktcnt, int_timeout;
#endif
/*
* Save away interesting stuff in the structure
*/
d->sbdma_eth = s;
d->sbdma_channel = chan;
d->sbdma_txdir = txrx;
#if 0
/* RMON clearing */
s->sbe_idx =(s->sbm_base - A_MAC_BASE_0)/MAC_SPACING;
#endif
__raw_writeq(0, s->sbm_base + R_MAC_RMON_TX_BYTES);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_COLLISIONS);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_LATE_COL);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_EX_COL);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_FCS_ERROR);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_TX_ABORT);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_TX_BAD);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_TX_GOOD);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_TX_RUNT);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_TX_OVERSIZE);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_RX_BYTES);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_RX_MCAST);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_RX_BCAST);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_RX_BAD);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_RX_GOOD);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_RX_RUNT);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_RX_OVERSIZE);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_RX_FCS_ERROR);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_RX_LENGTH_ERROR);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_RX_CODE_ERROR);
__raw_writeq(0, s->sbm_base + R_MAC_RMON_RX_ALIGN_ERROR);
/*
* initialize register pointers
*/
d->sbdma_config0 =
s->sbm_base + R_MAC_DMA_REGISTER(txrx,chan,R_MAC_DMA_CONFIG0);
d->sbdma_config1 =
s->sbm_base + R_MAC_DMA_REGISTER(txrx,chan,R_MAC_DMA_CONFIG1);
d->sbdma_dscrbase =
s->sbm_base + R_MAC_DMA_REGISTER(txrx,chan,R_MAC_DMA_DSCR_BASE);
d->sbdma_dscrcnt =
s->sbm_base + R_MAC_DMA_REGISTER(txrx,chan,R_MAC_DMA_DSCR_CNT);
d->sbdma_curdscr =
s->sbm_base + R_MAC_DMA_REGISTER(txrx,chan,R_MAC_DMA_CUR_DSCRADDR);
if (d->sbdma_txdir)
d->sbdma_oodpktlost = NULL;
else
d->sbdma_oodpktlost =
s->sbm_base + R_MAC_DMA_REGISTER(txrx,chan,R_MAC_DMA_OODPKTLOST_RX);
/*
* Allocate memory for the ring
*/
d->sbdma_maxdescr = maxdescr;
d->sbdma_dscrtable_unaligned = kcalloc(d->sbdma_maxdescr + 1,
sizeof(*d->sbdma_dscrtable),
GFP_KERNEL);
/*
* The descriptor table must be aligned to at least 16 bytes or the
* MAC will corrupt it.
*/
d->sbdma_dscrtable = (struct sbdmadscr *)
ALIGN((unsigned long)d->sbdma_dscrtable_unaligned,
sizeof(*d->sbdma_dscrtable));
d->sbdma_dscrtable_end = d->sbdma_dscrtable + d->sbdma_maxdescr;
d->sbdma_dscrtable_phys = virt_to_phys(d->sbdma_dscrtable);
/*
* And context table
*/
d->sbdma_ctxtable = kcalloc(d->sbdma_maxdescr,
sizeof(*d->sbdma_ctxtable), GFP_KERNEL);
#ifdef CONFIG_SBMAC_COALESCE
/*
* Setup Rx/Tx DMA coalescing defaults
*/
int_pktcnt = (txrx == DMA_TX) ? int_pktcnt_tx : int_pktcnt_rx;
if ( int_pktcnt ) {
d->sbdma_int_pktcnt = int_pktcnt;
} else {
d->sbdma_int_pktcnt = 1;
}
int_timeout = (txrx == DMA_TX) ? int_timeout_tx : int_timeout_rx;
if ( int_timeout ) {
d->sbdma_int_timeout = int_timeout;
} else {
d->sbdma_int_timeout = 0;
}
#endif
}
/**********************************************************************
* SBDMA_CHANNEL_START(d)
*
* Initialize the hardware registers for a DMA channel.
*
* Input parameters:
* d - DMA channel to init (context must be previously init'd
* rxtx - DMA_RX or DMA_TX depending on what type of channel
*
* Return value:
* nothing
********************************************************************* */
static void sbdma_channel_start(struct sbmacdma *d, int rxtx)
{
/*
* Turn on the DMA channel
*/
#ifdef CONFIG_SBMAC_COALESCE
__raw_writeq(V_DMA_INT_TIMEOUT(d->sbdma_int_timeout) |
0, d->sbdma_config1);
__raw_writeq(M_DMA_EOP_INT_EN |
V_DMA_RINGSZ(d->sbdma_maxdescr) |
V_DMA_INT_PKTCNT(d->sbdma_int_pktcnt) |
0, d->sbdma_config0);
#else
__raw_writeq(0, d->sbdma_config1);
__raw_writeq(V_DMA_RINGSZ(d->sbdma_maxdescr) |
0, d->sbdma_config0);
#endif
__raw_writeq(d->sbdma_dscrtable_phys, d->sbdma_dscrbase);
/*
* Initialize ring pointers
*/
d->sbdma_addptr = d->sbdma_dscrtable;
d->sbdma_remptr = d->sbdma_dscrtable;
}
/**********************************************************************
* SBDMA_CHANNEL_STOP(d)
*
* Initialize the hardware registers for a DMA channel.
*
* Input parameters:
* d - DMA channel to init (context must be previously init'd
*
* Return value:
* nothing
********************************************************************* */
static void sbdma_channel_stop(struct sbmacdma *d)
{
/*
* Turn off the DMA channel
*/
__raw_writeq(0, d->sbdma_config1);
__raw_writeq(0, d->sbdma_dscrbase);
__raw_writeq(0, d->sbdma_config0);
/*
* Zero ring pointers
*/
d->sbdma_addptr = NULL;
d->sbdma_remptr = NULL;
}
static inline void sbdma_align_skb(struct sk_buff *skb,
unsigned int power2, unsigned int offset)
{
unsigned char *addr = skb->data;
unsigned char *newaddr = PTR_ALIGN(addr, power2);
skb_reserve(skb, newaddr - addr + offset);
}
/**********************************************************************
* SBDMA_ADD_RCVBUFFER(d,sb)
*
* Add a buffer to the specified DMA channel. For receive channels,
* this queues a buffer for inbound packets.
*
* Input parameters:
* sc - softc structure
* d - DMA channel descriptor
* sb - sk_buff to add, or NULL if we should allocate one
*
* Return value:
* 0 if buffer could not be added (ring is full)
* 1 if buffer added successfully
********************************************************************* */
static int sbdma_add_rcvbuffer(struct sbmac_softc *sc, struct sbmacdma *d,
struct sk_buff *sb)
{
struct net_device *dev = sc->sbm_dev;
struct sbdmadscr *dsc;
struct sbdmadscr *nextdsc;
struct sk_buff *sb_new = NULL;
int pktsize = ENET_PACKET_SIZE;
/* get pointer to our current place in the ring */
dsc = d->sbdma_addptr;
nextdsc = SBDMA_NEXTBUF(d,sbdma_addptr);
/*
* figure out if the ring is full - if the next descriptor
* is the same as the one that we're going to remove from
* the ring, the ring is full
*/
if (nextdsc == d->sbdma_remptr) {
return -ENOSPC;
}
/*
* Allocate a sk_buff if we don't already have one.
* If we do have an sk_buff, reset it so that it's empty.
*
* Note: sk_buffs don't seem to be guaranteed to have any sort
* of alignment when they are allocated. Therefore, allocate enough
* extra space to make sure that:
*
* 1. the data does not start in the middle of a cache line.
* 2. The data does not end in the middle of a cache line
* 3. The buffer can be aligned such that the IP addresses are
* naturally aligned.
*
* Remember, the SOCs MAC writes whole cache lines at a time,
* without reading the old contents first. So, if the sk_buff's
* data portion starts in the middle of a cache line, the SOC
* DMA will trash the beginning (and ending) portions.
*/
if (sb == NULL) {
sb_new = netdev_alloc_skb(dev, ENET_PACKET_SIZE +
SMP_CACHE_BYTES * 2 +
NET_IP_ALIGN);
if (sb_new == NULL) {
pr_info("%s: sk_buff allocation failed\n",
d->sbdma_eth->sbm_dev->name);
return -ENOBUFS;
}
sbdma_align_skb(sb_new, SMP_CACHE_BYTES, NET_IP_ALIGN);
}
else {
sb_new = sb;
/*
* nothing special to reinit buffer, it's already aligned
* and sb->data already points to a good place.
*/
}
/*
* fill in the descriptor
*/
#ifdef CONFIG_SBMAC_COALESCE
/*
* Do not interrupt per DMA transfer.
*/
dsc->dscr_a = virt_to_phys(sb_new->data) |
V_DMA_DSCRA_A_SIZE(NUMCACHEBLKS(pktsize + NET_IP_ALIGN)) | 0;
#else
dsc->dscr_a = virt_to_phys(sb_new->data) |
V_DMA_DSCRA_A_SIZE(NUMCACHEBLKS(pktsize + NET_IP_ALIGN)) |
M_DMA_DSCRA_INTERRUPT;
#endif
/* receiving: no options */
dsc->dscr_b = 0;
/*
* fill in the context
*/
d->sbdma_ctxtable[dsc-d->sbdma_dscrtable] = sb_new;
/*
* point at next packet
*/
d->sbdma_addptr = nextdsc;
/*
* Give the buffer to the DMA engine.
*/
__raw_writeq(1, d->sbdma_dscrcnt);
return 0; /* we did it */
}
/**********************************************************************
* SBDMA_ADD_TXBUFFER(d,sb)
*
* Add a transmit buffer to the specified DMA channel, causing a
* transmit to start.
*
* Input parameters:
* d - DMA channel descriptor
* sb - sk_buff to add
*
* Return value:
* 0 transmit queued successfully
* otherwise error code
********************************************************************* */
static int sbdma_add_txbuffer(struct sbmacdma *d, struct sk_buff *sb)
{
struct sbdmadscr *dsc;
struct sbdmadscr *nextdsc;
uint64_t phys;
uint64_t ncb;
int length;
/* get pointer to our current place in the ring */
dsc = d->sbdma_addptr;
nextdsc = SBDMA_NEXTBUF(d,sbdma_addptr);
/*
* figure out if the ring is full - if the next descriptor
* is the same as the one that we're going to remove from
* the ring, the ring is full
*/
if (nextdsc == d->sbdma_remptr) {
return -ENOSPC;
}
/*
* Under Linux, it's not necessary to copy/coalesce buffers
* like it is on NetBSD. We think they're all contiguous,
* but that may not be true for GBE.
*/
length = sb->len;
/*
* fill in the descriptor. Note that the number of cache
* blocks in the descriptor is the number of blocks
* *spanned*, so we need to add in the offset (if any)
* while doing the calculation.
*/
phys = virt_to_phys(sb->data);
ncb = NUMCACHEBLKS(length+(phys & (SMP_CACHE_BYTES - 1)));
dsc->dscr_a = phys |
V_DMA_DSCRA_A_SIZE(ncb) |
#ifndef CONFIG_SBMAC_COALESCE
M_DMA_DSCRA_INTERRUPT |
#endif
M_DMA_ETHTX_SOP;
/* transmitting: set outbound options and length */
dsc->dscr_b = V_DMA_DSCRB_OPTIONS(K_DMA_ETHTX_APPENDCRC_APPENDPAD) |
V_DMA_DSCRB_PKT_SIZE(length);
/*
* fill in the context
*/
d->sbdma_ctxtable[dsc-d->sbdma_dscrtable] = sb;
/*
* point at next packet
*/
d->sbdma_addptr = nextdsc;
/*
* Give the buffer to the DMA engine.
*/
__raw_writeq(1, d->sbdma_dscrcnt);
return 0; /* we did it */
}
/**********************************************************************
* SBDMA_EMPTYRING(d)
*
* Free all allocated sk_buffs on the specified DMA channel;
*
* Input parameters:
* d - DMA channel
*
* Return value:
* nothing
********************************************************************* */
static void sbdma_emptyring(struct sbmacdma *d)
{
int idx;
struct sk_buff *sb;
for (idx = 0; idx < d->sbdma_maxdescr; idx++) {
sb = d->sbdma_ctxtable[idx];
if (sb) {
dev_kfree_skb(sb);
d->sbdma_ctxtable[idx] = NULL;
}
}
}
/**********************************************************************
* SBDMA_FILLRING(d)
*
* Fill the specified DMA channel (must be receive channel)
* with sk_buffs
*
* Input parameters:
* sc - softc structure
* d - DMA channel
*
* Return value:
* nothing
********************************************************************* */
static void sbdma_fillring(struct sbmac_softc *sc, struct sbmacdma *d)
{
int idx;
for (idx = 0; idx < SBMAC_MAX_RXDESCR - 1; idx++) {
if (sbdma_add_rcvbuffer(sc, d, NULL) != 0)
break;
}
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void sbmac_netpoll(struct net_device *netdev)
{
struct sbmac_softc *sc = netdev_priv(netdev);
int irq = sc->sbm_dev->irq;
__raw_writeq(0, sc->sbm_imr);
sbmac_intr(irq, netdev);
#ifdef CONFIG_SBMAC_COALESCE
__raw_writeq(((M_MAC_INT_EOP_COUNT | M_MAC_INT_EOP_TIMER) << S_MAC_TX_CH0) |
((M_MAC_INT_EOP_COUNT | M_MAC_INT_EOP_TIMER) << S_MAC_RX_CH0),
sc->sbm_imr);
#else
__raw_writeq((M_MAC_INT_CHANNEL << S_MAC_TX_CH0) |
(M_MAC_INT_CHANNEL << S_MAC_RX_CH0), sc->sbm_imr);
#endif
}
#endif
/**********************************************************************
* SBDMA_RX_PROCESS(sc,d,work_to_do,poll)
*
* Process "completed" receive buffers on the specified DMA channel.
*
* Input parameters:
* sc - softc structure
* d - DMA channel context
* work_to_do - no. of packets to process before enabling interrupt
* again (for NAPI)
* poll - 1: using polling (for NAPI)
*
* Return value:
* nothing
********************************************************************* */
static int sbdma_rx_process(struct sbmac_softc *sc, struct sbmacdma *d,
int work_to_do, int poll)
{
struct net_device *dev = sc->sbm_dev;
int curidx;
int hwidx;
struct sbdmadscr *dsc;
struct sk_buff *sb;
int len;
int work_done = 0;
int dropped = 0;
prefetch(d);
again:
/* Check if the HW dropped any frames */
dev->stats.rx_fifo_errors
+= __raw_readq(sc->sbm_rxdma.sbdma_oodpktlost) & 0xffff;
__raw_writeq(0, sc->sbm_rxdma.sbdma_oodpktlost);
while (work_to_do-- > 0) {
/*
* figure out where we are (as an index) and where
* the hardware is (also as an index)
*
* This could be done faster if (for example) the
* descriptor table was page-aligned and contiguous in
* both virtual and physical memory -- you could then
* just compare the low-order bits of the virtual address
* (sbdma_remptr) and the physical address (sbdma_curdscr CSR)
*/
dsc = d->sbdma_remptr;
curidx = dsc - d->sbdma_dscrtable;
prefetch(dsc);
prefetch(&d->sbdma_ctxtable[curidx]);
hwidx = ((__raw_readq(d->sbdma_curdscr) & M_DMA_CURDSCR_ADDR) -
d->sbdma_dscrtable_phys) /
sizeof(*d->sbdma_dscrtable);
/*
* If they're the same, that means we've processed all
* of the descriptors up to (but not including) the one that
* the hardware is working on right now.
*/
if (curidx == hwidx)
goto done;
/*
* Otherwise, get the packet's sk_buff ptr back
*/
sb = d->sbdma_ctxtable[curidx];
d->sbdma_ctxtable[curidx] = NULL;
len = (int)G_DMA_DSCRB_PKT_SIZE(dsc->dscr_b) - 4;
/*
* Check packet status. If good, process it.
* If not, silently drop it and put it back on the
* receive ring.
*/
if (likely (!(dsc->dscr_a & M_DMA_ETHRX_BAD))) {
/*
* Add a new buffer to replace the old one. If we fail
* to allocate a buffer, we're going to drop this
* packet and put it right back on the receive ring.
*/
if (unlikely(sbdma_add_rcvbuffer(sc, d, NULL) ==
-ENOBUFS)) {
dev->stats.rx_dropped++;
/* Re-add old buffer */
sbdma_add_rcvbuffer(sc, d, sb);
/* No point in continuing at the moment */
printk(KERN_ERR "dropped packet (1)\n");
d->sbdma_remptr = SBDMA_NEXTBUF(d,sbdma_remptr);
goto done;
} else {
/*
* Set length into the packet
*/
skb_put(sb,len);
/*
* Buffer has been replaced on the
* receive ring. Pass the buffer to
* the kernel
*/
sb->protocol = eth_type_trans(sb,d->sbdma_eth->sbm_dev);
/* Check hw IPv4/TCP checksum if supported */
if (sc->rx_hw_checksum == ENABLE) {
if (!((dsc->dscr_a) & M_DMA_ETHRX_BADIP4CS) &&
!((dsc->dscr_a) & M_DMA_ETHRX_BADTCPCS)) {
sb->ip_summed = CHECKSUM_UNNECESSARY;
/* don't need to set sb->csum */
} else {
skb_checksum_none_assert(sb);
}
}
prefetch(sb->data);
prefetch((const void *)(((char *)sb->data)+32));
if (poll)
dropped = netif_receive_skb(sb);
else
dropped = netif_rx(sb);
if (dropped == NET_RX_DROP) {
dev->stats.rx_dropped++;
d->sbdma_remptr = SBDMA_NEXTBUF(d,sbdma_remptr);
goto done;
}
else {
dev->stats.rx_bytes += len;
dev->stats.rx_packets++;
}
}
} else {
/*
* Packet was mangled somehow. Just drop it and
* put it back on the receive ring.
*/
dev->stats.rx_errors++;
sbdma_add_rcvbuffer(sc, d, sb);
}
/*
* .. and advance to the next buffer.
*/
d->sbdma_remptr = SBDMA_NEXTBUF(d,sbdma_remptr);
work_done++;
}
if (!poll) {
work_to_do = 32;
goto again; /* collect fifo drop statistics again */
}
done:
return work_done;
}
/**********************************************************************
* SBDMA_TX_PROCESS(sc,d)
*
* Process "completed" transmit buffers on the specified DMA channel.
* This is normally called within the interrupt service routine.
* Note that this isn't really ideal for priority channels, since
* it processes all of the packets on a given channel before
* returning.
*
* Input parameters:
* sc - softc structure
* d - DMA channel context
* poll - 1: using polling (for NAPI)
*
* Return value:
* nothing
********************************************************************* */
static void sbdma_tx_process(struct sbmac_softc *sc, struct sbmacdma *d,
int poll)
{
struct net_device *dev = sc->sbm_dev;
int curidx;
int hwidx;
struct sbdmadscr *dsc;
struct sk_buff *sb;
unsigned long flags;
int packets_handled = 0;
spin_lock_irqsave(&(sc->sbm_lock), flags);
if (d->sbdma_remptr == d->sbdma_addptr)
goto end_unlock;
hwidx = ((__raw_readq(d->sbdma_curdscr) & M_DMA_CURDSCR_ADDR) -
d->sbdma_dscrtable_phys) / sizeof(*d->sbdma_dscrtable);
for (;;) {
/*
* figure out where we are (as an index) and where
* the hardware is (also as an index)
*
* This could be done faster if (for example) the
* descriptor table was page-aligned and contiguous in
* both virtual and physical memory -- you could then
* just compare the low-order bits of the virtual address
* (sbdma_remptr) and the physical address (sbdma_curdscr CSR)
*/
curidx = d->sbdma_remptr - d->sbdma_dscrtable;
/*
* If they're the same, that means we've processed all
* of the descriptors up to (but not including) the one that
* the hardware is working on right now.
*/
if (curidx == hwidx)
break;
/*
* Otherwise, get the packet's sk_buff ptr back
*/
dsc = &(d->sbdma_dscrtable[curidx]);
sb = d->sbdma_ctxtable[curidx];
d->sbdma_ctxtable[curidx] = NULL;
/*
* Stats
*/
dev->stats.tx_bytes += sb->len;
dev->stats.tx_packets++;
/*
* for transmits, we just free buffers.
*/
dev_kfree_skb_irq(sb);
/*
* .. and advance to the next buffer.
*/
d->sbdma_remptr = SBDMA_NEXTBUF(d,sbdma_remptr);
packets_handled++;
}
/*
* Decide if we should wake up the protocol or not.
* Other drivers seem to do this when we reach a low
* watermark on the transmit queue.
*/
if (packets_handled)
netif_wake_queue(d->sbdma_eth->sbm_dev);
end_unlock:
spin_unlock_irqrestore(&(sc->sbm_lock), flags);
}
/**********************************************************************
* SBMAC_INITCTX(s)
*
* Initialize an Ethernet context structure - this is called
* once per MAC on the 1250. Memory is allocated here, so don't
* call it again from inside the ioctl routines that bring the
* interface up/down
*
* Input parameters:
* s - sbmac context structure
*
* Return value:
* 0
********************************************************************* */
static int sbmac_initctx(struct sbmac_softc *s)
{
/*
* figure out the addresses of some ports
*/
s->sbm_macenable = s->sbm_base + R_MAC_ENABLE;
s->sbm_maccfg = s->sbm_base + R_MAC_CFG;
s->sbm_fifocfg = s->sbm_base + R_MAC_THRSH_CFG;
s->sbm_framecfg = s->sbm_base + R_MAC_FRAMECFG;
s->sbm_rxfilter = s->sbm_base + R_MAC_ADFILTER_CFG;
s->sbm_isr = s->sbm_base + R_MAC_STATUS;
s->sbm_imr = s->sbm_base + R_MAC_INT_MASK;
s->sbm_mdio = s->sbm_base + R_MAC_MDIO;
/*
* Initialize the DMA channels. Right now, only one per MAC is used
* Note: Only do this _once_, as it allocates memory from the kernel!
*/
sbdma_initctx(&(s->sbm_txdma),s,0,DMA_TX,SBMAC_MAX_TXDESCR);
sbdma_initctx(&(s->sbm_rxdma),s,0,DMA_RX,SBMAC_MAX_RXDESCR);
/*
* initial state is OFF
*/
s->sbm_state = sbmac_state_off;
return 0;
}
static void sbdma_uninitctx(struct sbmacdma *d)
{
if (d->sbdma_dscrtable_unaligned) {
kfree(d->sbdma_dscrtable_unaligned);
d->sbdma_dscrtable_unaligned = d->sbdma_dscrtable = NULL;
}
if (d->sbdma_ctxtable) {
kfree(d->sbdma_ctxtable);
d->sbdma_ctxtable = NULL;
}
}
static void sbmac_uninitctx(struct sbmac_softc *sc)
{
sbdma_uninitctx(&(sc->sbm_txdma));
sbdma_uninitctx(&(sc->sbm_rxdma));
}
/**********************************************************************
* SBMAC_CHANNEL_START(s)
*
* Start packet processing on this MAC.
*
* Input parameters:
* s - sbmac structure
*
* Return value:
* nothing
********************************************************************* */
static void sbmac_channel_start(struct sbmac_softc *s)
{
uint64_t reg;
void __iomem *port;
uint64_t cfg,fifo,framecfg;
int idx, th_value;
/*
* Don't do this if running
*/
if (s->sbm_state == sbmac_state_on)
return;
/*
* Bring the controller out of reset, but leave it off.
*/
__raw_writeq(0, s->sbm_macenable);
/*
* Ignore all received packets
*/
__raw_writeq(0, s->sbm_rxfilter);
/*
* Calculate values for various control registers.
*/
cfg = M_MAC_RETRY_EN |
M_MAC_TX_HOLD_SOP_EN |
V_MAC_TX_PAUSE_CNT_16K |
M_MAC_AP_STAT_EN |
M_MAC_FAST_SYNC |
M_MAC_SS_EN |
0;
/*
* Be sure that RD_THRSH+WR_THRSH <= 32 for pass1 pars
* and make sure that RD_THRSH + WR_THRSH <=128 for pass2 and above
* Use a larger RD_THRSH for gigabit
*/
if (soc_type == K_SYS_SOC_TYPE_BCM1250 && periph_rev < 2)
th_value = 28;
else
th_value = 64;
fifo = V_MAC_TX_WR_THRSH(4) | /* Must be '4' or '8' */
((s->sbm_speed == sbmac_speed_1000)
? V_MAC_TX_RD_THRSH(th_value) : V_MAC_TX_RD_THRSH(4)) |
V_MAC_TX_RL_THRSH(4) |
V_MAC_RX_PL_THRSH(4) |
V_MAC_RX_RD_THRSH(4) | /* Must be '4' */
V_MAC_RX_RL_THRSH(8) |
0;
framecfg = V_MAC_MIN_FRAMESZ_DEFAULT |
V_MAC_MAX_FRAMESZ_DEFAULT |
V_MAC_BACKOFF_SEL(1);
/*
* Clear out the hash address map
*/
port = s->sbm_base + R_MAC_HASH_BASE;
for (idx = 0; idx < MAC_HASH_COUNT; idx++) {
__raw_writeq(0, port);
port += sizeof(uint64_t);
}
/*
* Clear out the exact-match table
*/
port = s->sbm_base + R_MAC_ADDR_BASE;
for (idx = 0; idx < MAC_ADDR_COUNT; idx++) {
__raw_writeq(0, port);
port += sizeof(uint64_t);
}
/*
* Clear out the DMA Channel mapping table registers
*/
port = s->sbm_base + R_MAC_CHUP0_BASE;
for (idx = 0; idx < MAC_CHMAP_COUNT; idx++) {
__raw_writeq(0, port);
port += sizeof(uint64_t);
}
port = s->sbm_base + R_MAC_CHLO0_BASE;
for (idx = 0; idx < MAC_CHMAP_COUNT; idx++) {
__raw_writeq(0, port);
port += sizeof(uint64_t);
}
/*
* Program the hardware address. It goes into the hardware-address
* register as well as the first filter register.
*/
reg = sbmac_addr2reg(s->sbm_hwaddr);
port = s->sbm_base + R_MAC_ADDR_BASE;
__raw_writeq(reg, port);
port = s->sbm_base + R_MAC_ETHERNET_ADDR;
#ifdef CONFIG_SB1_PASS_1_WORKAROUNDS
/*
* Pass1 SOCs do not receive packets addressed to the
* destination address in the R_MAC_ETHERNET_ADDR register.
* Set the value to zero.
*/
__raw_writeq(0, port);
#else
__raw_writeq(reg, port);
#endif
/*
* Set the receive filter for no packets, and write values
* to the various config registers
*/
__raw_writeq(0, s->sbm_rxfilter);
__raw_writeq(0, s->sbm_imr);
__raw_writeq(framecfg, s->sbm_framecfg);
__raw_writeq(fifo, s->sbm_fifocfg);
__raw_writeq(cfg, s->sbm_maccfg);
/*
* Initialize DMA channels (rings should be ok now)
*/
sbdma_channel_start(&(s->sbm_rxdma), DMA_RX);
sbdma_channel_start(&(s->sbm_txdma), DMA_TX);
/*
* Configure the speed, duplex, and flow control
*/
sbmac_set_speed(s,s->sbm_speed);
sbmac_set_duplex(s,s->sbm_duplex,s->sbm_fc);
/*
* Fill the receive ring
*/
sbdma_fillring(s, &(s->sbm_rxdma));
/*
* Turn on the rest of the bits in the enable register
*/
#if defined(CONFIG_SIBYTE_BCM1x55) || defined(CONFIG_SIBYTE_BCM1x80)
__raw_writeq(M_MAC_RXDMA_EN0 |
M_MAC_TXDMA_EN0, s->sbm_macenable);
#elif defined(CONFIG_SIBYTE_SB1250) || defined(CONFIG_SIBYTE_BCM112X)
__raw_writeq(M_MAC_RXDMA_EN0 |
M_MAC_TXDMA_EN0 |
M_MAC_RX_ENABLE |
M_MAC_TX_ENABLE, s->sbm_macenable);
#else
#error invalid SiByte MAC configuration
#endif
#ifdef CONFIG_SBMAC_COALESCE
__raw_writeq(((M_MAC_INT_EOP_COUNT | M_MAC_INT_EOP_TIMER) << S_MAC_TX_CH0) |
((M_MAC_INT_EOP_COUNT | M_MAC_INT_EOP_TIMER) << S_MAC_RX_CH0), s->sbm_imr);
#else
__raw_writeq((M_MAC_INT_CHANNEL << S_MAC_TX_CH0) |
(M_MAC_INT_CHANNEL << S_MAC_RX_CH0), s->sbm_imr);
#endif
/*
* Enable receiving unicasts and broadcasts
*/
__raw_writeq(M_MAC_UCAST_EN | M_MAC_BCAST_EN, s->sbm_rxfilter);
/*
* we're running now.
*/
s->sbm_state = sbmac_state_on;
/*
* Program multicast addresses
*/
sbmac_setmulti(s);
/*
* If channel was in promiscuous mode before, turn that on
*/
if (s->sbm_devflags & IFF_PROMISC) {
sbmac_promiscuous_mode(s,1);
}
}
/**********************************************************************
* SBMAC_CHANNEL_STOP(s)
*
* Stop packet processing on this MAC.
*
* Input parameters:
* s - sbmac structure
*
* Return value:
* nothing
********************************************************************* */
static void sbmac_channel_stop(struct sbmac_softc *s)
{
/* don't do this if already stopped */
if (s->sbm_state == sbmac_state_off)
return;
/* don't accept any packets, disable all interrupts */
__raw_writeq(0, s->sbm_rxfilter);
__raw_writeq(0, s->sbm_imr);
/* Turn off ticker */
/* XXX */
/* turn off receiver and transmitter */
__raw_writeq(0, s->sbm_macenable);
/* We're stopped now. */
s->sbm_state = sbmac_state_off;
/*
* Stop DMA channels (rings should be ok now)
*/
sbdma_channel_stop(&(s->sbm_rxdma));
sbdma_channel_stop(&(s->sbm_txdma));
/* Empty the receive and transmit rings */
sbdma_emptyring(&(s->sbm_rxdma));
sbdma_emptyring(&(s->sbm_txdma));
}
/**********************************************************************
* SBMAC_SET_CHANNEL_STATE(state)
*
* Set the channel's state ON or OFF
*
* Input parameters:
* state - new state
*
* Return value:
* old state
********************************************************************* */
static enum sbmac_state sbmac_set_channel_state(struct sbmac_softc *sc,
enum sbmac_state state)
{
enum sbmac_state oldstate = sc->sbm_state;
/*
* If same as previous state, return
*/
if (state == oldstate) {
return oldstate;
}
/*
* If new state is ON, turn channel on
*/
if (state == sbmac_state_on) {
sbmac_channel_start(sc);
}
else {
sbmac_channel_stop(sc);
}
/*
* Return previous state
*/
return oldstate;
}
/**********************************************************************
* SBMAC_PROMISCUOUS_MODE(sc,onoff)
*
* Turn on or off promiscuous mode
*
* Input parameters:
* sc - softc
* onoff - 1 to turn on, 0 to turn off
*
* Return value:
* nothing
********************************************************************* */
static void sbmac_promiscuous_mode(struct sbmac_softc *sc,int onoff)
{
uint64_t reg;
if (sc->sbm_state != sbmac_state_on)
return;
if (onoff) {
reg = __raw_readq(sc->sbm_rxfilter);
reg |= M_MAC_ALLPKT_EN;
__raw_writeq(reg, sc->sbm_rxfilter);
}
else {
reg = __raw_readq(sc->sbm_rxfilter);
reg &= ~M_MAC_ALLPKT_EN;
__raw_writeq(reg, sc->sbm_rxfilter);
}
}
/**********************************************************************
* SBMAC_SETIPHDR_OFFSET(sc,onoff)
*
* Set the iphdr offset as 15 assuming ethernet encapsulation
*
* Input parameters:
* sc - softc
*
* Return value:
* nothing
********************************************************************* */
static void sbmac_set_iphdr_offset(struct sbmac_softc *sc)
{
uint64_t reg;
/* Hard code the off set to 15 for now */
reg = __raw_readq(sc->sbm_rxfilter);
reg &= ~M_MAC_IPHDR_OFFSET | V_MAC_IPHDR_OFFSET(15);
__raw_writeq(reg, sc->sbm_rxfilter);
/* BCM1250 pass1 didn't have hardware checksum. Everything
later does. */
if (soc_type == K_SYS_SOC_TYPE_BCM1250 && periph_rev < 2) {
sc->rx_hw_checksum = DISABLE;
} else {
sc->rx_hw_checksum = ENABLE;
}
}
/**********************************************************************
* SBMAC_ADDR2REG(ptr)
*
* Convert six bytes into the 64-bit register value that
* we typically write into the SBMAC's address/mcast registers
*
* Input parameters:
* ptr - pointer to 6 bytes
*
* Return value:
* register value
********************************************************************* */
static uint64_t sbmac_addr2reg(unsigned char *ptr)
{
uint64_t reg = 0;
ptr += 6;
reg |= (uint64_t) *(--ptr);
reg <<= 8;
reg |= (uint64_t) *(--ptr);
reg <<= 8;
reg |= (uint64_t) *(--ptr);
reg <<= 8;
reg |= (uint64_t) *(--ptr);
reg <<= 8;
reg |= (uint64_t) *(--ptr);
reg <<= 8;
reg |= (uint64_t) *(--ptr);
return reg;
}
/**********************************************************************
* SBMAC_SET_SPEED(s,speed)
*
* Configure LAN speed for the specified MAC.
* Warning: must be called when MAC is off!
*
* Input parameters:
* s - sbmac structure
* speed - speed to set MAC to (see enum sbmac_speed)
*
* Return value:
* 1 if successful
* 0 indicates invalid parameters
********************************************************************* */
static int sbmac_set_speed(struct sbmac_softc *s, enum sbmac_speed speed)
{
uint64_t cfg;
uint64_t framecfg;
/*
* Save new current values
*/
s->sbm_speed = speed;
if (s->sbm_state == sbmac_state_on)
return 0; /* save for next restart */
/*
* Read current register values
*/
cfg = __raw_readq(s->sbm_maccfg);
framecfg = __raw_readq(s->sbm_framecfg);
/*
* Mask out the stuff we want to change
*/
cfg &= ~(M_MAC_BURST_EN | M_MAC_SPEED_SEL);
framecfg &= ~(M_MAC_IFG_RX | M_MAC_IFG_TX | M_MAC_IFG_THRSH |
M_MAC_SLOT_SIZE);
/*
* Now add in the new bits
*/
switch (speed) {
case sbmac_speed_10:
framecfg |= V_MAC_IFG_RX_10 |
V_MAC_IFG_TX_10 |
K_MAC_IFG_THRSH_10 |
V_MAC_SLOT_SIZE_10;
cfg |= V_MAC_SPEED_SEL_10MBPS;
break;
case sbmac_speed_100:
framecfg |= V_MAC_IFG_RX_100 |
V_MAC_IFG_TX_100 |
V_MAC_IFG_THRSH_100 |
V_MAC_SLOT_SIZE_100;
cfg |= V_MAC_SPEED_SEL_100MBPS ;
break;
case sbmac_speed_1000:
framecfg |= V_MAC_IFG_RX_1000 |
V_MAC_IFG_TX_1000 |
V_MAC_IFG_THRSH_1000 |
V_MAC_SLOT_SIZE_1000;
cfg |= V_MAC_SPEED_SEL_1000MBPS | M_MAC_BURST_EN;
break;
default:
return 0;
}
/*
* Send the bits back to the hardware
*/
__raw_writeq(framecfg, s->sbm_framecfg);
__raw_writeq(cfg, s->sbm_maccfg);
return 1;
}
/**********************************************************************
* SBMAC_SET_DUPLEX(s,duplex,fc)
*
* Set Ethernet duplex and flow control options for this MAC
* Warning: must be called when MAC is off!
*
* Input parameters:
* s - sbmac structure
* duplex - duplex setting (see enum sbmac_duplex)
* fc - flow control setting (see enum sbmac_fc)
*
* Return value:
* 1 if ok
* 0 if an invalid parameter combination was specified
********************************************************************* */
static int sbmac_set_duplex(struct sbmac_softc *s, enum sbmac_duplex duplex,
enum sbmac_fc fc)
{
uint64_t cfg;
/*
* Save new current values
*/
s->sbm_duplex = duplex;
s->sbm_fc = fc;
if (s->sbm_state == sbmac_state_on)
return 0; /* save for next restart */
/*
* Read current register values
*/
cfg = __raw_readq(s->sbm_maccfg);
/*
* Mask off the stuff we're about to change
*/
cfg &= ~(M_MAC_FC_SEL | M_MAC_FC_CMD | M_MAC_HDX_EN);
switch (duplex) {
case sbmac_duplex_half:
switch (fc) {
case sbmac_fc_disabled:
cfg |= M_MAC_HDX_EN | V_MAC_FC_CMD_DISABLED;
break;
case sbmac_fc_collision:
cfg |= M_MAC_HDX_EN | V_MAC_FC_CMD_ENABLED;
break;
case sbmac_fc_carrier:
cfg |= M_MAC_HDX_EN | V_MAC_FC_CMD_ENAB_FALSECARR;
break;
case sbmac_fc_frame: /* not valid in half duplex */
default: /* invalid selection */
return 0;
}
break;
case sbmac_duplex_full:
switch (fc) {
case sbmac_fc_disabled:
cfg |= V_MAC_FC_CMD_DISABLED;
break;
case sbmac_fc_frame:
cfg |= V_MAC_FC_CMD_ENABLED;
break;
case sbmac_fc_collision: /* not valid in full duplex */
case sbmac_fc_carrier: /* not valid in full duplex */
default:
return 0;
}
break;
default:
return 0;
}
/*
* Send the bits back to the hardware
*/
__raw_writeq(cfg, s->sbm_maccfg);
return 1;
}
/**********************************************************************
* SBMAC_INTR()
*
* Interrupt handler for MAC interrupts
*
* Input parameters:
* MAC structure
*
* Return value:
* nothing
********************************************************************* */
static irqreturn_t sbmac_intr(int irq,void *dev_instance)
{
struct net_device *dev = (struct net_device *) dev_instance;
struct sbmac_softc *sc = netdev_priv(dev);
uint64_t isr;
int handled = 0;
/*
* Read the ISR (this clears the bits in the real
* register, except for counter addr)
*/
isr = __raw_readq(sc->sbm_isr) & ~M_MAC_COUNTER_ADDR;
if (isr == 0)
return IRQ_RETVAL(0);
handled = 1;
/*
* Transmits on channel 0
*/
if (isr & (M_MAC_INT_CHANNEL << S_MAC_TX_CH0))
sbdma_tx_process(sc,&(sc->sbm_txdma), 0);
if (isr & (M_MAC_INT_CHANNEL << S_MAC_RX_CH0)) {
if (napi_schedule_prep(&sc->napi)) {
__raw_writeq(0, sc->sbm_imr);
__napi_schedule(&sc->napi);
/* Depend on the exit from poll to reenable intr */
}
else {
/* may leave some packets behind */
sbdma_rx_process(sc,&(sc->sbm_rxdma),
SBMAC_MAX_RXDESCR * 2, 0);
}
}
return IRQ_RETVAL(handled);
}
/**********************************************************************
* SBMAC_START_TX(skb,dev)
*
* Start output on the specified interface. Basically, we
* queue as many buffers as we can until the ring fills up, or
* we run off the end of the queue, whichever comes first.
*
* Input parameters:
*
*
* Return value:
* nothing
********************************************************************* */
static int sbmac_start_tx(struct sk_buff *skb, struct net_device *dev)
{
struct sbmac_softc *sc = netdev_priv(dev);
unsigned long flags;
/* lock eth irq */
spin_lock_irqsave(&sc->sbm_lock, flags);
/*
* Put the buffer on the transmit ring. If we
* don't have room, stop the queue.
*/
if (sbdma_add_txbuffer(&(sc->sbm_txdma),skb)) {
/* XXX save skb that we could not send */
netif_stop_queue(dev);
spin_unlock_irqrestore(&sc->sbm_lock, flags);
return NETDEV_TX_BUSY;
}
spin_unlock_irqrestore(&sc->sbm_lock, flags);
return NETDEV_TX_OK;
}
/**********************************************************************
* SBMAC_SETMULTI(sc)
*
* Reprogram the multicast table into the hardware, given
* the list of multicasts associated with the interface
* structure.
*
* Input parameters:
* sc - softc
*
* Return value:
* nothing
********************************************************************* */
static void sbmac_setmulti(struct sbmac_softc *sc)
{
uint64_t reg;
void __iomem *port;
int idx;
struct netdev_hw_addr *ha;
struct net_device *dev = sc->sbm_dev;
/*
* Clear out entire multicast table. We do this by nuking
* the entire hash table and all the direct matches except
* the first one, which is used for our station address
*/
for (idx = 1; idx < MAC_ADDR_COUNT; idx++) {
port = sc->sbm_base + R_MAC_ADDR_BASE+(idx*sizeof(uint64_t));
__raw_writeq(0, port);
}
for (idx = 0; idx < MAC_HASH_COUNT; idx++) {
port = sc->sbm_base + R_MAC_HASH_BASE+(idx*sizeof(uint64_t));
__raw_writeq(0, port);
}
/*
* Clear the filter to say we don't want any multicasts.
*/
reg = __raw_readq(sc->sbm_rxfilter);
reg &= ~(M_MAC_MCAST_INV | M_MAC_MCAST_EN);
__raw_writeq(reg, sc->sbm_rxfilter);
if (dev->flags & IFF_ALLMULTI) {
/*
* Enable ALL multicasts. Do this by inverting the
* multicast enable bit.
*/
reg = __raw_readq(sc->sbm_rxfilter);
reg |= (M_MAC_MCAST_INV | M_MAC_MCAST_EN);
__raw_writeq(reg, sc->sbm_rxfilter);
return;
}
/*
* Progam new multicast entries. For now, only use the
* perfect filter. In the future we'll need to use the
* hash filter if the perfect filter overflows
*/
/* XXX only using perfect filter for now, need to use hash
* XXX if the table overflows */
idx = 1; /* skip station address */
netdev_for_each_mc_addr(ha, dev) {
if (idx == MAC_ADDR_COUNT)
break;
reg = sbmac_addr2reg(ha->addr);
port = sc->sbm_base + R_MAC_ADDR_BASE+(idx * sizeof(uint64_t));
__raw_writeq(reg, port);
idx++;
}
/*
* Enable the "accept multicast bits" if we programmed at least one
* multicast.
*/
if (idx > 1) {
reg = __raw_readq(sc->sbm_rxfilter);
reg |= M_MAC_MCAST_EN;
__raw_writeq(reg, sc->sbm_rxfilter);
}
}
static int sb1250_change_mtu(struct net_device *_dev, int new_mtu)
{
if (new_mtu > ENET_PACKET_SIZE)
return -EINVAL;
_dev->mtu = new_mtu;
pr_info("changing the mtu to %d\n", new_mtu);
return 0;
}
static const struct net_device_ops sbmac_netdev_ops = {
.ndo_open = sbmac_open,
.ndo_stop = sbmac_close,
.ndo_start_xmit = sbmac_start_tx,
.ndo_set_rx_mode = sbmac_set_rx_mode,
.ndo_tx_timeout = sbmac_tx_timeout,
.ndo_do_ioctl = sbmac_mii_ioctl,
.ndo_change_mtu = sb1250_change_mtu,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = sbmac_netpoll,
#endif
};
/**********************************************************************
* SBMAC_INIT(dev)
*
* Attach routine - init hardware and hook ourselves into linux
*
* Input parameters:
* dev - net_device structure
*
* Return value:
* status
********************************************************************* */
static int sbmac_init(struct platform_device *pldev, long long base)
{
struct net_device *dev = dev_get_drvdata(&pldev->dev);
int idx = pldev->id;
struct sbmac_softc *sc = netdev_priv(dev);
unsigned char *eaddr;
uint64_t ea_reg;
int i;
int err;
sc->sbm_dev = dev;
sc->sbe_idx = idx;
eaddr = sc->sbm_hwaddr;
/*
* Read the ethernet address. The firmware left this programmed
* for us in the ethernet address register for each mac.
*/
ea_reg = __raw_readq(sc->sbm_base + R_MAC_ETHERNET_ADDR);
__raw_writeq(0, sc->sbm_base + R_MAC_ETHERNET_ADDR);
for (i = 0; i < 6; i++) {
eaddr[i] = (uint8_t) (ea_reg & 0xFF);
ea_reg >>= 8;
}
for (i = 0; i < 6; i++) {
dev->dev_addr[i] = eaddr[i];
}
/*
* Initialize context (get pointers to registers and stuff), then
* allocate the memory for the descriptor tables.
*/
sbmac_initctx(sc);
/*
* Set up Linux device callins
*/
spin_lock_init(&(sc->sbm_lock));
dev->netdev_ops = &sbmac_netdev_ops;
dev->watchdog_timeo = TX_TIMEOUT;
netif_napi_add(dev, &sc->napi, sbmac_poll, 16);
dev->irq = UNIT_INT(idx);
/* This is needed for PASS2 for Rx H/W checksum feature */
sbmac_set_iphdr_offset(sc);
sc->mii_bus = mdiobus_alloc();
if (sc->mii_bus == NULL) {
err = -ENOMEM;
goto uninit_ctx;
}
sc->mii_bus->name = sbmac_mdio_string;
snprintf(sc->mii_bus->id, MII_BUS_ID_SIZE, "%s-%x",
pldev->name, idx);
sc->mii_bus->priv = sc;
sc->mii_bus->read = sbmac_mii_read;
sc->mii_bus->write = sbmac_mii_write;
sc->mii_bus->irq = sc->phy_irq;
for (i = 0; i < PHY_MAX_ADDR; ++i)
sc->mii_bus->irq[i] = SBMAC_PHY_INT;
sc->mii_bus->parent = &pldev->dev;
/*
* Probe PHY address
*/
err = mdiobus_register(sc->mii_bus);
if (err) {
printk(KERN_ERR "%s: unable to register MDIO bus\n",
dev->name);
goto free_mdio;
}
dev_set_drvdata(&pldev->dev, sc->mii_bus);
err = register_netdev(dev);
if (err) {
printk(KERN_ERR "%s.%d: unable to register netdev\n",
sbmac_string, idx);
goto unreg_mdio;
}
pr_info("%s.%d: registered as %s\n", sbmac_string, idx, dev->name);
if (sc->rx_hw_checksum == ENABLE)
pr_info("%s: enabling TCP rcv checksum\n", dev->name);
/*
* Display Ethernet address (this is called during the config
* process so we need to finish off the config message that
* was being displayed)
*/
pr_info("%s: SiByte Ethernet at 0x%08Lx, address: %pM\n",
dev->name, base, eaddr);
return 0;
unreg_mdio:
mdiobus_unregister(sc->mii_bus);
dev_set_drvdata(&pldev->dev, NULL);
free_mdio:
mdiobus_free(sc->mii_bus);
uninit_ctx:
sbmac_uninitctx(sc);
return err;
}
static int sbmac_open(struct net_device *dev)
{
struct sbmac_softc *sc = netdev_priv(dev);
int err;
if (debug > 1)
pr_debug("%s: sbmac_open() irq %d.\n", dev->name, dev->irq);
/*
* map/route interrupt (clear status first, in case something
* weird is pending; we haven't initialized the mac registers
* yet)
*/
__raw_readq(sc->sbm_isr);
err = request_irq(dev->irq, sbmac_intr, IRQF_SHARED, dev->name, dev);
if (err) {
printk(KERN_ERR "%s: unable to get IRQ %d\n", dev->name,
dev->irq);
goto out_err;
}
sc->sbm_speed = sbmac_speed_none;
sc->sbm_duplex = sbmac_duplex_none;
sc->sbm_fc = sbmac_fc_none;
sc->sbm_pause = -1;
sc->sbm_link = 0;
/*
* Attach to the PHY
*/
err = sbmac_mii_probe(dev);
if (err)
goto out_unregister;
/*
* Turn on the channel
*/
sbmac_set_channel_state(sc,sbmac_state_on);
netif_start_queue(dev);
sbmac_set_rx_mode(dev);
phy_start(sc->phy_dev);
napi_enable(&sc->napi);
return 0;
out_unregister:
free_irq(dev->irq, dev);
out_err:
return err;
}
static int sbmac_mii_probe(struct net_device *dev)
{
struct sbmac_softc *sc = netdev_priv(dev);
struct phy_device *phy_dev;
int i;
for (i = 0; i < PHY_MAX_ADDR; i++) {
phy_dev = sc->mii_bus->phy_map[i];
if (phy_dev)
break;
}
if (!phy_dev) {
printk(KERN_ERR "%s: no PHY found\n", dev->name);
return -ENXIO;
}
phy_dev = phy_connect(dev, dev_name(&phy_dev->dev), &sbmac_mii_poll, 0,
PHY_INTERFACE_MODE_GMII);
if (IS_ERR(phy_dev)) {
printk(KERN_ERR "%s: could not attach to PHY\n", dev->name);
return PTR_ERR(phy_dev);
}
/* Remove any features not supported by the controller */
phy_dev->supported &= SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full |
SUPPORTED_1000baseT_Half |
SUPPORTED_1000baseT_Full |
SUPPORTED_Autoneg |
SUPPORTED_MII |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause;
phy_dev->advertising = phy_dev->supported;
pr_info("%s: attached PHY driver [%s] (mii_bus:phy_addr=%s, irq=%d)\n",
dev->name, phy_dev->drv->name,
dev_name(&phy_dev->dev), phy_dev->irq);
sc->phy_dev = phy_dev;
return 0;
}
static void sbmac_mii_poll(struct net_device *dev)
{
struct sbmac_softc *sc = netdev_priv(dev);
struct phy_device *phy_dev = sc->phy_dev;
unsigned long flags;
enum sbmac_fc fc;
int link_chg, speed_chg, duplex_chg, pause_chg, fc_chg;
link_chg = (sc->sbm_link != phy_dev->link);
speed_chg = (sc->sbm_speed != phy_dev->speed);
duplex_chg = (sc->sbm_duplex != phy_dev->duplex);
pause_chg = (sc->sbm_pause != phy_dev->pause);
if (!link_chg && !speed_chg && !duplex_chg && !pause_chg)
return; /* Hmmm... */
if (!phy_dev->link) {
if (link_chg) {
sc->sbm_link = phy_dev->link;
sc->sbm_speed = sbmac_speed_none;
sc->sbm_duplex = sbmac_duplex_none;
sc->sbm_fc = sbmac_fc_disabled;
sc->sbm_pause = -1;
pr_info("%s: link unavailable\n", dev->name);
}
return;
}
if (phy_dev->duplex == DUPLEX_FULL) {
if (phy_dev->pause)
fc = sbmac_fc_frame;
else
fc = sbmac_fc_disabled;
} else
fc = sbmac_fc_collision;
fc_chg = (sc->sbm_fc != fc);
pr_info("%s: link available: %dbase-%cD\n", dev->name, phy_dev->speed,
phy_dev->duplex == DUPLEX_FULL ? 'F' : 'H');
spin_lock_irqsave(&sc->sbm_lock, flags);
sc->sbm_speed = phy_dev->speed;
sc->sbm_duplex = phy_dev->duplex;
sc->sbm_fc = fc;
sc->sbm_pause = phy_dev->pause;
sc->sbm_link = phy_dev->link;
if ((speed_chg || duplex_chg || fc_chg) &&
sc->sbm_state != sbmac_state_off) {
/*
* something changed, restart the channel
*/
if (debug > 1)
pr_debug("%s: restarting channel "
"because PHY state changed\n", dev->name);
sbmac_channel_stop(sc);
sbmac_channel_start(sc);
}
spin_unlock_irqrestore(&sc->sbm_lock, flags);
}
static void sbmac_tx_timeout (struct net_device *dev)
{
struct sbmac_softc *sc = netdev_priv(dev);
unsigned long flags;
spin_lock_irqsave(&sc->sbm_lock, flags);
dev->trans_start = jiffies; /* prevent tx timeout */
dev->stats.tx_errors++;
spin_unlock_irqrestore(&sc->sbm_lock, flags);
printk (KERN_WARNING "%s: Transmit timed out\n",dev->name);
}
static void sbmac_set_rx_mode(struct net_device *dev)
{
unsigned long flags;
struct sbmac_softc *sc = netdev_priv(dev);
spin_lock_irqsave(&sc->sbm_lock, flags);
if ((dev->flags ^ sc->sbm_devflags) & IFF_PROMISC) {
/*
* Promiscuous changed.
*/
if (dev->flags & IFF_PROMISC) {
sbmac_promiscuous_mode(sc,1);
}
else {
sbmac_promiscuous_mode(sc,0);
}
}
spin_unlock_irqrestore(&sc->sbm_lock, flags);
/*
* Program the multicasts. Do this every time.
*/
sbmac_setmulti(sc);
}
static int sbmac_mii_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
struct sbmac_softc *sc = netdev_priv(dev);
if (!netif_running(dev) || !sc->phy_dev)
return -EINVAL;
return phy_mii_ioctl(sc->phy_dev, rq, cmd);
}
static int sbmac_close(struct net_device *dev)
{
struct sbmac_softc *sc = netdev_priv(dev);
napi_disable(&sc->napi);
phy_stop(sc->phy_dev);
sbmac_set_channel_state(sc, sbmac_state_off);
netif_stop_queue(dev);
if (debug > 1)
pr_debug("%s: Shutting down ethercard\n", dev->name);
phy_disconnect(sc->phy_dev);
sc->phy_dev = NULL;
free_irq(dev->irq, dev);
sbdma_emptyring(&(sc->sbm_txdma));
sbdma_emptyring(&(sc->sbm_rxdma));
return 0;
}
static int sbmac_poll(struct napi_struct *napi, int budget)
{
struct sbmac_softc *sc = container_of(napi, struct sbmac_softc, napi);
int work_done;
work_done = sbdma_rx_process(sc, &(sc->sbm_rxdma), budget, 1);
sbdma_tx_process(sc, &(sc->sbm_txdma), 1);
if (work_done < budget) {
napi_complete(napi);
#ifdef CONFIG_SBMAC_COALESCE
__raw_writeq(((M_MAC_INT_EOP_COUNT | M_MAC_INT_EOP_TIMER) << S_MAC_TX_CH0) |
((M_MAC_INT_EOP_COUNT | M_MAC_INT_EOP_TIMER) << S_MAC_RX_CH0),
sc->sbm_imr);
#else
__raw_writeq((M_MAC_INT_CHANNEL << S_MAC_TX_CH0) |
(M_MAC_INT_CHANNEL << S_MAC_RX_CH0), sc->sbm_imr);
#endif
}
return work_done;
}
static int __devinit sbmac_probe(struct platform_device *pldev)
{
struct net_device *dev;
struct sbmac_softc *sc;
void __iomem *sbm_base;
struct resource *res;
u64 sbmac_orig_hwaddr;
int err;
res = platform_get_resource(pldev, IORESOURCE_MEM, 0);
BUG_ON(!res);
sbm_base = ioremap_nocache(res->start, resource_size(res));
if (!sbm_base) {
printk(KERN_ERR "%s: unable to map device registers\n",
dev_name(&pldev->dev));
err = -ENOMEM;
goto out_out;
}
/*
* The R_MAC_ETHERNET_ADDR register will be set to some nonzero
* value for us by the firmware if we're going to use this MAC.
* If we find a zero, skip this MAC.
*/
sbmac_orig_hwaddr = __raw_readq(sbm_base + R_MAC_ETHERNET_ADDR);
pr_debug("%s: %sconfiguring MAC at 0x%08Lx\n", dev_name(&pldev->dev),
sbmac_orig_hwaddr ? "" : "not ", (long long)res->start);
if (sbmac_orig_hwaddr == 0) {
err = 0;
goto out_unmap;
}
/*
* Okay, cool. Initialize this MAC.
*/
dev = alloc_etherdev(sizeof(struct sbmac_softc));
if (!dev) {
err = -ENOMEM;
goto out_unmap;
}
dev_set_drvdata(&pldev->dev, dev);
SET_NETDEV_DEV(dev, &pldev->dev);
sc = netdev_priv(dev);
sc->sbm_base = sbm_base;
err = sbmac_init(pldev, res->start);
if (err)
goto out_kfree;
return 0;
out_kfree:
free_netdev(dev);
__raw_writeq(sbmac_orig_hwaddr, sbm_base + R_MAC_ETHERNET_ADDR);
out_unmap:
iounmap(sbm_base);
out_out:
return err;
}
static int __exit sbmac_remove(struct platform_device *pldev)
{
struct net_device *dev = dev_get_drvdata(&pldev->dev);
struct sbmac_softc *sc = netdev_priv(dev);
unregister_netdev(dev);
sbmac_uninitctx(sc);
mdiobus_unregister(sc->mii_bus);
mdiobus_free(sc->mii_bus);
iounmap(sc->sbm_base);
free_netdev(dev);
return 0;
}
static struct platform_driver sbmac_driver = {
.probe = sbmac_probe,
.remove = __exit_p(sbmac_remove),
.driver = {
.name = sbmac_string,
.owner = THIS_MODULE,
},
};
module_platform_driver(sbmac_driver);
| gpl-2.0 |
jrior001/android_kernel_samsung_d2 | drivers/pinctrl/pinctrl-mmp2.c | 4987 | 39622 | /*
* linux/drivers/pinctrl/pinmux-mmp2.c
*
* 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
* publishhed by the Free Software Foundation.
*
* Copyright (C) 2011, Marvell Technology Group Ltd.
*
* Author: Haojian Zhuang <haojian.zhuang@marvell.com>
*
*/
#include <linux/device.h>
#include <linux/module.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include "pinctrl-pxa3xx.h"
#define MMP2_DS_MASK 0x1800
#define MMP2_DS_SHIFT 11
#define MMP2_SLEEP_MASK 0x38
#define MMP2_SLEEP_SELECT (1 << 9)
#define MMP2_SLEEP_DATA (1 << 8)
#define MMP2_SLEEP_DIR (1 << 7)
#define MFPR_MMP2(a, r, f0, f1, f2, f3, f4, f5, f6, f7) \
{ \
.name = #a, \
.pin = a, \
.mfpr = r, \
.func = { \
MMP2_MUX_##f0, \
MMP2_MUX_##f1, \
MMP2_MUX_##f2, \
MMP2_MUX_##f3, \
MMP2_MUX_##f4, \
MMP2_MUX_##f5, \
MMP2_MUX_##f6, \
MMP2_MUX_##f7, \
}, \
}
#define GRP_MMP2(a, m, p) \
{ .name = a, .mux = MMP2_MUX_##m, .pins = p, .npins = ARRAY_SIZE(p), }
/* 174 pins */
enum mmp2_pin_list {
/* 0~168: GPIO0~GPIO168 */
TWSI4_SCL = 169,
TWSI4_SDA, /* 170 */
G_CLKREQ,
VCXO_REQ,
VCXO_OUT,
};
enum mmp2_mux {
/* PXA3xx_MUX_GPIO = 0 (predefined in pinctrl-pxa3xx.h) */
MMP2_MUX_GPIO = 0,
MMP2_MUX_G_CLKREQ,
MMP2_MUX_VCXO_REQ,
MMP2_MUX_VCXO_OUT,
MMP2_MUX_KP_MK,
MMP2_MUX_KP_DK,
MMP2_MUX_CCIC1,
MMP2_MUX_CCIC2,
MMP2_MUX_SPI,
MMP2_MUX_SSPA2,
MMP2_MUX_ROT,
MMP2_MUX_I2S,
MMP2_MUX_TB,
MMP2_MUX_CAM2,
MMP2_MUX_HDMI,
MMP2_MUX_TWSI2,
MMP2_MUX_TWSI3,
MMP2_MUX_TWSI4,
MMP2_MUX_TWSI5,
MMP2_MUX_TWSI6,
MMP2_MUX_UART1,
MMP2_MUX_UART2,
MMP2_MUX_UART3,
MMP2_MUX_UART4,
MMP2_MUX_SSP1_RX,
MMP2_MUX_SSP1_FRM,
MMP2_MUX_SSP1_TXRX,
MMP2_MUX_SSP2_RX,
MMP2_MUX_SSP2_FRM,
MMP2_MUX_SSP1,
MMP2_MUX_SSP2,
MMP2_MUX_SSP3,
MMP2_MUX_SSP4,
MMP2_MUX_MMC1,
MMP2_MUX_MMC2,
MMP2_MUX_MMC3,
MMP2_MUX_MMC4,
MMP2_MUX_ULPI,
MMP2_MUX_AC,
MMP2_MUX_CA,
MMP2_MUX_PWM,
MMP2_MUX_USIM,
MMP2_MUX_TIPU,
MMP2_MUX_PLL,
MMP2_MUX_NAND,
MMP2_MUX_FSIC,
MMP2_MUX_SLEEP_IND,
MMP2_MUX_EXT_DMA,
MMP2_MUX_ONE_WIRE,
MMP2_MUX_LCD,
MMP2_MUX_SMC,
MMP2_MUX_SMC_INT,
MMP2_MUX_MSP,
MMP2_MUX_G_CLKOUT,
MMP2_MUX_32K_CLKOUT,
MMP2_MUX_PRI_JTAG,
MMP2_MUX_AAS_JTAG,
MMP2_MUX_AAS_GPIO,
MMP2_MUX_AAS_SPI,
MMP2_MUX_AAS_TWSI,
MMP2_MUX_AAS_DEU_EX,
MMP2_MUX_NONE = 0xffff,
};
static struct pinctrl_pin_desc mmp2_pads[] = {
/*
* The name indicates function 0 of this pin.
* After reset, function 0 is the default function of pin.
*/
PINCTRL_PIN(GPIO0, "GPIO0"),
PINCTRL_PIN(GPIO1, "GPIO1"),
PINCTRL_PIN(GPIO2, "GPIO2"),
PINCTRL_PIN(GPIO3, "GPIO3"),
PINCTRL_PIN(GPIO4, "GPIO4"),
PINCTRL_PIN(GPIO5, "GPIO5"),
PINCTRL_PIN(GPIO6, "GPIO6"),
PINCTRL_PIN(GPIO7, "GPIO7"),
PINCTRL_PIN(GPIO8, "GPIO8"),
PINCTRL_PIN(GPIO9, "GPIO9"),
PINCTRL_PIN(GPIO10, "GPIO10"),
PINCTRL_PIN(GPIO11, "GPIO11"),
PINCTRL_PIN(GPIO12, "GPIO12"),
PINCTRL_PIN(GPIO13, "GPIO13"),
PINCTRL_PIN(GPIO14, "GPIO14"),
PINCTRL_PIN(GPIO15, "GPIO15"),
PINCTRL_PIN(GPIO16, "GPIO16"),
PINCTRL_PIN(GPIO17, "GPIO17"),
PINCTRL_PIN(GPIO18, "GPIO18"),
PINCTRL_PIN(GPIO19, "GPIO19"),
PINCTRL_PIN(GPIO20, "GPIO20"),
PINCTRL_PIN(GPIO21, "GPIO21"),
PINCTRL_PIN(GPIO22, "GPIO22"),
PINCTRL_PIN(GPIO23, "GPIO23"),
PINCTRL_PIN(GPIO24, "GPIO24"),
PINCTRL_PIN(GPIO25, "GPIO25"),
PINCTRL_PIN(GPIO26, "GPIO26"),
PINCTRL_PIN(GPIO27, "GPIO27"),
PINCTRL_PIN(GPIO28, "GPIO28"),
PINCTRL_PIN(GPIO29, "GPIO29"),
PINCTRL_PIN(GPIO30, "GPIO30"),
PINCTRL_PIN(GPIO31, "GPIO31"),
PINCTRL_PIN(GPIO32, "GPIO32"),
PINCTRL_PIN(GPIO33, "GPIO33"),
PINCTRL_PIN(GPIO34, "GPIO34"),
PINCTRL_PIN(GPIO35, "GPIO35"),
PINCTRL_PIN(GPIO36, "GPIO36"),
PINCTRL_PIN(GPIO37, "GPIO37"),
PINCTRL_PIN(GPIO38, "GPIO38"),
PINCTRL_PIN(GPIO39, "GPIO39"),
PINCTRL_PIN(GPIO40, "GPIO40"),
PINCTRL_PIN(GPIO41, "GPIO41"),
PINCTRL_PIN(GPIO42, "GPIO42"),
PINCTRL_PIN(GPIO43, "GPIO43"),
PINCTRL_PIN(GPIO44, "GPIO44"),
PINCTRL_PIN(GPIO45, "GPIO45"),
PINCTRL_PIN(GPIO46, "GPIO46"),
PINCTRL_PIN(GPIO47, "GPIO47"),
PINCTRL_PIN(GPIO48, "GPIO48"),
PINCTRL_PIN(GPIO49, "GPIO49"),
PINCTRL_PIN(GPIO50, "GPIO50"),
PINCTRL_PIN(GPIO51, "GPIO51"),
PINCTRL_PIN(GPIO52, "GPIO52"),
PINCTRL_PIN(GPIO53, "GPIO53"),
PINCTRL_PIN(GPIO54, "GPIO54"),
PINCTRL_PIN(GPIO55, "GPIO55"),
PINCTRL_PIN(GPIO56, "GPIO56"),
PINCTRL_PIN(GPIO57, "GPIO57"),
PINCTRL_PIN(GPIO58, "GPIO58"),
PINCTRL_PIN(GPIO59, "GPIO59"),
PINCTRL_PIN(GPIO60, "GPIO60"),
PINCTRL_PIN(GPIO61, "GPIO61"),
PINCTRL_PIN(GPIO62, "GPIO62"),
PINCTRL_PIN(GPIO63, "GPIO63"),
PINCTRL_PIN(GPIO64, "GPIO64"),
PINCTRL_PIN(GPIO65, "GPIO65"),
PINCTRL_PIN(GPIO66, "GPIO66"),
PINCTRL_PIN(GPIO67, "GPIO67"),
PINCTRL_PIN(GPIO68, "GPIO68"),
PINCTRL_PIN(GPIO69, "GPIO69"),
PINCTRL_PIN(GPIO70, "GPIO70"),
PINCTRL_PIN(GPIO71, "GPIO71"),
PINCTRL_PIN(GPIO72, "GPIO72"),
PINCTRL_PIN(GPIO73, "GPIO73"),
PINCTRL_PIN(GPIO74, "GPIO74"),
PINCTRL_PIN(GPIO75, "GPIO75"),
PINCTRL_PIN(GPIO76, "GPIO76"),
PINCTRL_PIN(GPIO77, "GPIO77"),
PINCTRL_PIN(GPIO78, "GPIO78"),
PINCTRL_PIN(GPIO79, "GPIO79"),
PINCTRL_PIN(GPIO80, "GPIO80"),
PINCTRL_PIN(GPIO81, "GPIO81"),
PINCTRL_PIN(GPIO82, "GPIO82"),
PINCTRL_PIN(GPIO83, "GPIO83"),
PINCTRL_PIN(GPIO84, "GPIO84"),
PINCTRL_PIN(GPIO85, "GPIO85"),
PINCTRL_PIN(GPIO86, "GPIO86"),
PINCTRL_PIN(GPIO87, "GPIO87"),
PINCTRL_PIN(GPIO88, "GPIO88"),
PINCTRL_PIN(GPIO89, "GPIO89"),
PINCTRL_PIN(GPIO90, "GPIO90"),
PINCTRL_PIN(GPIO91, "GPIO91"),
PINCTRL_PIN(GPIO92, "GPIO92"),
PINCTRL_PIN(GPIO93, "GPIO93"),
PINCTRL_PIN(GPIO94, "GPIO94"),
PINCTRL_PIN(GPIO95, "GPIO95"),
PINCTRL_PIN(GPIO96, "GPIO96"),
PINCTRL_PIN(GPIO97, "GPIO97"),
PINCTRL_PIN(GPIO98, "GPIO98"),
PINCTRL_PIN(GPIO99, "GPIO99"),
PINCTRL_PIN(GPIO100, "GPIO100"),
PINCTRL_PIN(GPIO101, "GPIO101"),
PINCTRL_PIN(GPIO102, "GPIO102"),
PINCTRL_PIN(GPIO103, "GPIO103"),
PINCTRL_PIN(GPIO104, "GPIO104"),
PINCTRL_PIN(GPIO105, "GPIO105"),
PINCTRL_PIN(GPIO106, "GPIO106"),
PINCTRL_PIN(GPIO107, "GPIO107"),
PINCTRL_PIN(GPIO108, "GPIO108"),
PINCTRL_PIN(GPIO109, "GPIO109"),
PINCTRL_PIN(GPIO110, "GPIO110"),
PINCTRL_PIN(GPIO111, "GPIO111"),
PINCTRL_PIN(GPIO112, "GPIO112"),
PINCTRL_PIN(GPIO113, "GPIO113"),
PINCTRL_PIN(GPIO114, "GPIO114"),
PINCTRL_PIN(GPIO115, "GPIO115"),
PINCTRL_PIN(GPIO116, "GPIO116"),
PINCTRL_PIN(GPIO117, "GPIO117"),
PINCTRL_PIN(GPIO118, "GPIO118"),
PINCTRL_PIN(GPIO119, "GPIO119"),
PINCTRL_PIN(GPIO120, "GPIO120"),
PINCTRL_PIN(GPIO121, "GPIO121"),
PINCTRL_PIN(GPIO122, "GPIO122"),
PINCTRL_PIN(GPIO123, "GPIO123"),
PINCTRL_PIN(GPIO124, "GPIO124"),
PINCTRL_PIN(GPIO125, "GPIO125"),
PINCTRL_PIN(GPIO126, "GPIO126"),
PINCTRL_PIN(GPIO127, "GPIO127"),
PINCTRL_PIN(GPIO128, "GPIO128"),
PINCTRL_PIN(GPIO129, "GPIO129"),
PINCTRL_PIN(GPIO130, "GPIO130"),
PINCTRL_PIN(GPIO131, "GPIO131"),
PINCTRL_PIN(GPIO132, "GPIO132"),
PINCTRL_PIN(GPIO133, "GPIO133"),
PINCTRL_PIN(GPIO134, "GPIO134"),
PINCTRL_PIN(GPIO135, "GPIO135"),
PINCTRL_PIN(GPIO136, "GPIO136"),
PINCTRL_PIN(GPIO137, "GPIO137"),
PINCTRL_PIN(GPIO138, "GPIO138"),
PINCTRL_PIN(GPIO139, "GPIO139"),
PINCTRL_PIN(GPIO140, "GPIO140"),
PINCTRL_PIN(GPIO141, "GPIO141"),
PINCTRL_PIN(GPIO142, "GPIO142"),
PINCTRL_PIN(GPIO143, "GPIO143"),
PINCTRL_PIN(GPIO144, "GPIO144"),
PINCTRL_PIN(GPIO145, "GPIO145"),
PINCTRL_PIN(GPIO146, "GPIO146"),
PINCTRL_PIN(GPIO147, "GPIO147"),
PINCTRL_PIN(GPIO148, "GPIO148"),
PINCTRL_PIN(GPIO149, "GPIO149"),
PINCTRL_PIN(GPIO150, "GPIO150"),
PINCTRL_PIN(GPIO151, "GPIO151"),
PINCTRL_PIN(GPIO152, "GPIO152"),
PINCTRL_PIN(GPIO153, "GPIO153"),
PINCTRL_PIN(GPIO154, "GPIO154"),
PINCTRL_PIN(GPIO155, "GPIO155"),
PINCTRL_PIN(GPIO156, "GPIO156"),
PINCTRL_PIN(GPIO157, "GPIO157"),
PINCTRL_PIN(GPIO158, "GPIO158"),
PINCTRL_PIN(GPIO159, "GPIO159"),
PINCTRL_PIN(GPIO160, "GPIO160"),
PINCTRL_PIN(GPIO161, "GPIO161"),
PINCTRL_PIN(GPIO162, "GPIO162"),
PINCTRL_PIN(GPIO163, "GPIO163"),
PINCTRL_PIN(GPIO164, "GPIO164"),
PINCTRL_PIN(GPIO165, "GPIO165"),
PINCTRL_PIN(GPIO166, "GPIO166"),
PINCTRL_PIN(GPIO167, "GPIO167"),
PINCTRL_PIN(GPIO168, "GPIO168"),
PINCTRL_PIN(TWSI4_SCL, "TWSI4_SCL"),
PINCTRL_PIN(TWSI4_SDA, "TWSI4_SDA"),
PINCTRL_PIN(G_CLKREQ, "G_CLKREQ"),
PINCTRL_PIN(VCXO_REQ, "VCXO_REQ"),
PINCTRL_PIN(VCXO_OUT, "VCXO_OUT"),
};
struct pxa3xx_mfp_pin mmp2_mfp[] = {
/* pin offs f0 f1 f2 f3 f4 f5 f6 f7 */
MFPR_MMP2(GPIO0, 0x054, GPIO, KP_MK, NONE, SPI, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO1, 0x058, GPIO, KP_MK, NONE, SPI, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO2, 0x05C, GPIO, KP_MK, NONE, SPI, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO3, 0x060, GPIO, KP_MK, NONE, SPI, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO4, 0x064, GPIO, KP_MK, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO5, 0x068, GPIO, KP_MK, NONE, SPI, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO6, 0x06C, GPIO, KP_MK, NONE, SPI, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO7, 0x070, GPIO, KP_MK, NONE, SPI, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO8, 0x074, GPIO, KP_MK, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO9, 0x078, GPIO, KP_MK, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO10, 0x07C, GPIO, KP_MK, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO11, 0x080, GPIO, KP_MK, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO12, 0x084, GPIO, KP_MK, NONE, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO13, 0x088, GPIO, KP_MK, NONE, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO14, 0x08C, GPIO, KP_MK, NONE, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO15, 0x090, GPIO, KP_MK, KP_DK, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO16, 0x094, GPIO, KP_DK, ROT, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO17, 0x098, GPIO, KP_DK, ROT, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO18, 0x09C, GPIO, KP_DK, ROT, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO19, 0x0A0, GPIO, KP_DK, ROT, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO20, 0x0A4, GPIO, KP_DK, TB, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO21, 0x0A8, GPIO, KP_DK, TB, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO22, 0x0AC, GPIO, KP_DK, TB, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO23, 0x0B0, GPIO, KP_DK, TB, CCIC1, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO24, 0x0B4, GPIO, I2S, VCXO_OUT, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO25, 0x0B8, GPIO, I2S, HDMI, SSPA2, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO26, 0x0BC, GPIO, I2S, HDMI, SSPA2, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO27, 0x0C0, GPIO, I2S, HDMI, SSPA2, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO28, 0x0C4, GPIO, I2S, NONE, SSPA2, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO29, 0x0C8, GPIO, UART1, KP_MK, NONE, NONE, NONE, AAS_SPI, NONE),
MFPR_MMP2(GPIO30, 0x0CC, GPIO, UART1, KP_MK, NONE, NONE, NONE, AAS_SPI, NONE),
MFPR_MMP2(GPIO31, 0x0D0, GPIO, UART1, KP_MK, NONE, NONE, NONE, AAS_SPI, NONE),
MFPR_MMP2(GPIO32, 0x0D4, GPIO, UART1, KP_MK, NONE, NONE, NONE, AAS_SPI, NONE),
MFPR_MMP2(GPIO33, 0x0D8, GPIO, SSPA2, I2S, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO34, 0x0DC, GPIO, SSPA2, I2S, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO35, 0x0E0, GPIO, SSPA2, I2S, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO36, 0x0E4, GPIO, SSPA2, I2S, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO37, 0x0E8, GPIO, MMC2, SSP1, TWSI2, UART2, UART3, AAS_SPI, AAS_TWSI),
MFPR_MMP2(GPIO38, 0x0EC, GPIO, MMC2, SSP1, TWSI2, UART2, UART3, AAS_SPI, AAS_TWSI),
MFPR_MMP2(GPIO39, 0x0F0, GPIO, MMC2, SSP1, TWSI2, UART2, UART3, AAS_SPI, AAS_TWSI),
MFPR_MMP2(GPIO40, 0x0F4, GPIO, MMC2, SSP1, TWSI2, UART2, UART3, AAS_SPI, AAS_TWSI),
MFPR_MMP2(GPIO41, 0x0F8, GPIO, MMC2, TWSI5, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO42, 0x0FC, GPIO, MMC2, TWSI5, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO43, 0x100, GPIO, TWSI2, UART4, SSP1, UART2, UART3, NONE, AAS_TWSI),
MFPR_MMP2(GPIO44, 0x104, GPIO, TWSI2, UART4, SSP1, UART2, UART3, NONE, AAS_TWSI),
MFPR_MMP2(GPIO45, 0x108, GPIO, UART1, UART4, SSP1, UART2, UART3, NONE, NONE),
MFPR_MMP2(GPIO46, 0x10C, GPIO, UART1, UART4, SSP1, UART2, UART3, NONE, NONE),
MFPR_MMP2(GPIO47, 0x110, GPIO, UART2, SSP2, TWSI6, CAM2, AAS_SPI, AAS_GPIO, NONE),
MFPR_MMP2(GPIO48, 0x114, GPIO, UART2, SSP2, TWSI6, CAM2, AAS_SPI, AAS_GPIO, NONE),
MFPR_MMP2(GPIO49, 0x118, GPIO, UART2, SSP2, PWM, CCIC2, AAS_SPI, NONE, NONE),
MFPR_MMP2(GPIO50, 0x11C, GPIO, UART2, SSP2, PWM, CCIC2, AAS_SPI, NONE, NONE),
MFPR_MMP2(GPIO51, 0x120, GPIO, UART3, ROT, AAS_GPIO, PWM, NONE, NONE, NONE),
MFPR_MMP2(GPIO52, 0x124, GPIO, UART3, ROT, AAS_GPIO, PWM, NONE, NONE, NONE),
MFPR_MMP2(GPIO53, 0x128, GPIO, UART3, TWSI2, VCXO_REQ, NONE, PWM, NONE, AAS_TWSI),
MFPR_MMP2(GPIO54, 0x12C, GPIO, UART3, TWSI2, VCXO_OUT, HDMI, PWM, NONE, AAS_TWSI),
MFPR_MMP2(GPIO55, 0x130, GPIO, SSP2, SSP1, UART2, ROT, TWSI2, SSP3, AAS_TWSI),
MFPR_MMP2(GPIO56, 0x134, GPIO, SSP2, SSP1, UART2, ROT, TWSI2, KP_DK, AAS_TWSI),
MFPR_MMP2(GPIO57, 0x138, GPIO, SSP2_RX, SSP1_TXRX, SSP2_FRM, SSP1_RX, VCXO_REQ, KP_DK, NONE),
MFPR_MMP2(GPIO58, 0x13C, GPIO, SSP2, SSP1_RX, SSP1_FRM, SSP1_TXRX, VCXO_REQ, KP_DK, NONE),
MFPR_MMP2(GPIO59, 0x280, GPIO, CCIC1, ULPI, MMC3, CCIC2, UART3, UART4, NONE),
MFPR_MMP2(GPIO60, 0x284, GPIO, CCIC1, ULPI, MMC3, CCIC2, UART3, UART4, NONE),
MFPR_MMP2(GPIO61, 0x288, GPIO, CCIC1, ULPI, MMC3, CCIC2, UART3, HDMI, NONE),
MFPR_MMP2(GPIO62, 0x28C, GPIO, CCIC1, ULPI, MMC3, CCIC2, UART3, NONE, NONE),
MFPR_MMP2(GPIO63, 0x290, GPIO, CCIC1, ULPI, MMC3, CCIC2, MSP, UART4, NONE),
MFPR_MMP2(GPIO64, 0x294, GPIO, CCIC1, ULPI, MMC3, CCIC2, MSP, UART4, NONE),
MFPR_MMP2(GPIO65, 0x298, GPIO, CCIC1, ULPI, MMC3, CCIC2, MSP, UART4, NONE),
MFPR_MMP2(GPIO66, 0x29C, GPIO, CCIC1, ULPI, MMC3, CCIC2, MSP, UART4, NONE),
MFPR_MMP2(GPIO67, 0x2A0, GPIO, CCIC1, ULPI, MMC3, CCIC2, MSP, NONE, NONE),
MFPR_MMP2(GPIO68, 0x2A4, GPIO, CCIC1, ULPI, MMC3, CCIC2, MSP, LCD, NONE),
MFPR_MMP2(GPIO69, 0x2A8, GPIO, CCIC1, ULPI, MMC3, CCIC2, NONE, LCD, NONE),
MFPR_MMP2(GPIO70, 0x2AC, GPIO, CCIC1, ULPI, MMC3, CCIC2, MSP, LCD, NONE),
MFPR_MMP2(GPIO71, 0x2B0, GPIO, TWSI3, NONE, PWM, NONE, NONE, LCD, AAS_TWSI),
MFPR_MMP2(GPIO72, 0x2B4, GPIO, TWSI3, HDMI, PWM, NONE, NONE, LCD, AAS_TWSI),
MFPR_MMP2(GPIO73, 0x2B8, GPIO, VCXO_REQ, 32K_CLKOUT, PWM, VCXO_OUT, NONE, LCD, NONE),
MFPR_MMP2(GPIO74, 0x170, GPIO, LCD, SMC, MMC4, SSP3, UART2, UART4, TIPU),
MFPR_MMP2(GPIO75, 0x174, GPIO, LCD, SMC, MMC4, SSP3, UART2, UART4, TIPU),
MFPR_MMP2(GPIO76, 0x178, GPIO, LCD, SMC, MMC4, SSP3, UART2, UART4, TIPU),
MFPR_MMP2(GPIO77, 0x17C, GPIO, LCD, SMC, MMC4, SSP3, UART2, UART4, TIPU),
MFPR_MMP2(GPIO78, 0x180, GPIO, LCD, HDMI, MMC4, NONE, SSP4, AAS_SPI, TIPU),
MFPR_MMP2(GPIO79, 0x184, GPIO, LCD, AAS_GPIO, MMC4, NONE, SSP4, AAS_SPI, TIPU),
MFPR_MMP2(GPIO80, 0x188, GPIO, LCD, AAS_GPIO, MMC4, NONE, SSP4, AAS_SPI, TIPU),
MFPR_MMP2(GPIO81, 0x18C, GPIO, LCD, AAS_GPIO, MMC4, NONE, SSP4, AAS_SPI, TIPU),
MFPR_MMP2(GPIO82, 0x190, GPIO, LCD, NONE, MMC4, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO83, 0x194, GPIO, LCD, NONE, MMC4, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO84, 0x198, GPIO, LCD, SMC, MMC2, NONE, TWSI5, AAS_TWSI, TIPU),
MFPR_MMP2(GPIO85, 0x19C, GPIO, LCD, SMC, MMC2, NONE, TWSI5, AAS_TWSI, TIPU),
MFPR_MMP2(GPIO86, 0x1A0, GPIO, LCD, SMC, MMC2, NONE, TWSI6, CCIC2, TIPU),
MFPR_MMP2(GPIO87, 0x1A4, GPIO, LCD, SMC, MMC2, NONE, TWSI6, CCIC2, TIPU),
MFPR_MMP2(GPIO88, 0x1A8, GPIO, LCD, AAS_GPIO, MMC2, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO89, 0x1AC, GPIO, LCD, AAS_GPIO, MMC2, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO90, 0x1B0, GPIO, LCD, AAS_GPIO, MMC2, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO91, 0x1B4, GPIO, LCD, AAS_GPIO, MMC2, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO92, 0x1B8, GPIO, LCD, AAS_GPIO, MMC2, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO93, 0x1BC, GPIO, LCD, AAS_GPIO, MMC2, NONE, NONE, CCIC2, TIPU),
MFPR_MMP2(GPIO94, 0x1C0, GPIO, LCD, AAS_GPIO, SPI, NONE, AAS_SPI, CCIC2, TIPU),
MFPR_MMP2(GPIO95, 0x1C4, GPIO, LCD, TWSI3, SPI, AAS_DEU_EX, AAS_SPI, CCIC2, TIPU),
MFPR_MMP2(GPIO96, 0x1C8, GPIO, LCD, TWSI3, SPI, AAS_DEU_EX, AAS_SPI, NONE, TIPU),
MFPR_MMP2(GPIO97, 0x1CC, GPIO, LCD, TWSI6, SPI, AAS_DEU_EX, AAS_SPI, NONE, TIPU),
MFPR_MMP2(GPIO98, 0x1D0, GPIO, LCD, TWSI6, SPI, ONE_WIRE, NONE, NONE, TIPU),
MFPR_MMP2(GPIO99, 0x1D4, GPIO, LCD, SMC, SPI, TWSI5, NONE, NONE, TIPU),
MFPR_MMP2(GPIO100, 0x1D8, GPIO, LCD, SMC, SPI, TWSI5, NONE, NONE, TIPU),
MFPR_MMP2(GPIO101, 0x1DC, GPIO, LCD, SMC, SPI, NONE, NONE, NONE, TIPU),
MFPR_MMP2(GPIO102, 0x000, USIM, GPIO, FSIC, KP_DK, LCD, NONE, NONE, NONE),
MFPR_MMP2(GPIO103, 0x004, USIM, GPIO, FSIC, KP_DK, LCD, NONE, NONE, NONE),
MFPR_MMP2(GPIO104, 0x1FC, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO105, 0x1F8, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO106, 0x1F4, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO107, 0x1F0, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO108, 0x21C, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO109, 0x218, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO110, 0x214, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO111, 0x200, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO112, 0x244, NAND, GPIO, MMC3, SMC, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO113, 0x25C, SMC, GPIO, EXT_DMA, MMC3, SMC, HDMI, NONE, NONE),
MFPR_MMP2(GPIO114, 0x164, G_CLKOUT, 32K_CLKOUT, HDMI, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO115, 0x260, GPIO, NONE, AC, UART4, UART3, SSP1, NONE, NONE),
MFPR_MMP2(GPIO116, 0x264, GPIO, NONE, AC, UART4, UART3, SSP1, NONE, NONE),
MFPR_MMP2(GPIO117, 0x268, GPIO, NONE, AC, UART4, UART3, SSP1, NONE, NONE),
MFPR_MMP2(GPIO118, 0x26C, GPIO, NONE, AC, UART4, UART3, SSP1, NONE, NONE),
MFPR_MMP2(GPIO119, 0x270, GPIO, NONE, CA, SSP3, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO120, 0x274, GPIO, NONE, CA, SSP3, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO121, 0x278, GPIO, NONE, CA, SSP3, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO122, 0x27C, GPIO, NONE, CA, SSP3, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO123, 0x148, GPIO, SLEEP_IND, ONE_WIRE, 32K_CLKOUT, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO124, 0x00C, GPIO, MMC1, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO125, 0x010, GPIO, MMC1, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO126, 0x014, GPIO, MMC1, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO127, 0x018, GPIO, NONE, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO128, 0x01C, GPIO, NONE, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO129, 0x020, GPIO, MMC1, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO130, 0x024, GPIO, MMC1, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO131, 0x028, GPIO, MMC1, NONE, MSP, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO132, 0x02C, GPIO, MMC1, PRI_JTAG, MSP, SSP3, AAS_JTAG, NONE, NONE),
MFPR_MMP2(GPIO133, 0x030, GPIO, MMC1, PRI_JTAG, MSP, SSP3, AAS_JTAG, NONE, NONE),
MFPR_MMP2(GPIO134, 0x034, GPIO, MMC1, PRI_JTAG, MSP, SSP3, AAS_JTAG, NONE, NONE),
MFPR_MMP2(GPIO135, 0x038, GPIO, NONE, LCD, MMC3, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO136, 0x03C, GPIO, MMC1, PRI_JTAG, MSP, SSP3, AAS_JTAG, NONE, NONE),
MFPR_MMP2(GPIO137, 0x040, GPIO, HDMI, LCD, MSP, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO138, 0x044, GPIO, NONE, LCD, MMC3, SMC, NONE, NONE, NONE),
MFPR_MMP2(GPIO139, 0x048, GPIO, MMC1, PRI_JTAG, MSP, NONE, AAS_JTAG, NONE, NONE),
MFPR_MMP2(GPIO140, 0x04C, GPIO, MMC1, LCD, NONE, NONE, UART2, UART1, NONE),
MFPR_MMP2(GPIO141, 0x050, GPIO, MMC1, LCD, NONE, NONE, UART2, UART1, NONE),
MFPR_MMP2(GPIO142, 0x008, USIM, GPIO, FSIC, KP_DK, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO143, 0x220, NAND, GPIO, SMC, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO144, 0x224, NAND, GPIO, SMC_INT, SMC, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO145, 0x228, SMC, GPIO, NONE, NONE, SMC, NONE, NONE, NONE),
MFPR_MMP2(GPIO146, 0x22C, SMC, GPIO, NONE, NONE, SMC, NONE, NONE, NONE),
MFPR_MMP2(GPIO147, 0x230, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO148, 0x234, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO149, 0x238, NAND, GPIO, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO150, 0x23C, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO151, 0x240, SMC, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO152, 0x248, SMC, GPIO, NONE, NONE, SMC, NONE, NONE, NONE),
MFPR_MMP2(GPIO153, 0x24C, SMC, GPIO, NONE, NONE, SMC, NONE, NONE, NONE),
MFPR_MMP2(GPIO154, 0x254, SMC_INT, GPIO, SMC, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO155, 0x258, EXT_DMA, GPIO, SMC, NONE, EXT_DMA, NONE, NONE, NONE),
MFPR_MMP2(GPIO156, 0x14C, PRI_JTAG, GPIO, PWM, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO157, 0x150, PRI_JTAG, GPIO, PWM, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO158, 0x154, PRI_JTAG, GPIO, PWM, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO159, 0x158, PRI_JTAG, GPIO, PWM, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO160, 0x250, NAND, GPIO, SMC, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO161, 0x210, NAND, GPIO, NONE, NONE, NAND, NONE, NONE, NONE),
MFPR_MMP2(GPIO162, 0x20C, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO163, 0x208, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO164, 0x204, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO165, 0x1EC, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO166, 0x1E8, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO167, 0x1E4, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(GPIO168, 0x1E0, NAND, GPIO, MMC3, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(TWSI4_SCL, 0x2BC, TWSI4, LCD, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(TWSI4_SDA, 0x2C0, TWSI4, LCD, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(G_CLKREQ, 0x160, G_CLKREQ, ONE_WIRE, NONE, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(VCXO_REQ, 0x168, VCXO_REQ, ONE_WIRE, PLL, NONE, NONE, NONE, NONE, NONE),
MFPR_MMP2(VCXO_OUT, 0x16C, VCXO_OUT, 32K_CLKOUT, NONE, NONE, NONE, NONE, NONE, NONE),
};
static const unsigned mmp2_uart1_pin1[] = {GPIO29, GPIO30, GPIO31, GPIO32};
static const unsigned mmp2_uart1_pin2[] = {GPIO45, GPIO46};
static const unsigned mmp2_uart1_pin3[] = {GPIO140, GPIO141};
static const unsigned mmp2_uart2_pin1[] = {GPIO37, GPIO38, GPIO39, GPIO40};
static const unsigned mmp2_uart2_pin2[] = {GPIO43, GPIO44, GPIO45, GPIO46};
static const unsigned mmp2_uart2_pin3[] = {GPIO47, GPIO48, GPIO49, GPIO50};
static const unsigned mmp2_uart2_pin4[] = {GPIO74, GPIO75, GPIO76, GPIO77};
static const unsigned mmp2_uart2_pin5[] = {GPIO55, GPIO56};
static const unsigned mmp2_uart2_pin6[] = {GPIO140, GPIO141};
static const unsigned mmp2_uart3_pin1[] = {GPIO37, GPIO38, GPIO39, GPIO40};
static const unsigned mmp2_uart3_pin2[] = {GPIO43, GPIO44, GPIO45, GPIO46};
static const unsigned mmp2_uart3_pin3[] = {GPIO51, GPIO52, GPIO53, GPIO54};
static const unsigned mmp2_uart3_pin4[] = {GPIO59, GPIO60, GPIO61, GPIO62};
static const unsigned mmp2_uart3_pin5[] = {GPIO115, GPIO116, GPIO117, GPIO118};
static const unsigned mmp2_uart3_pin6[] = {GPIO51, GPIO52};
static const unsigned mmp2_uart4_pin1[] = {GPIO43, GPIO44, GPIO45, GPIO46};
static const unsigned mmp2_uart4_pin2[] = {GPIO63, GPIO64, GPIO65, GPIO66};
static const unsigned mmp2_uart4_pin3[] = {GPIO74, GPIO75, GPIO76, GPIO77};
static const unsigned mmp2_uart4_pin4[] = {GPIO115, GPIO116, GPIO117, GPIO118};
static const unsigned mmp2_uart4_pin5[] = {GPIO59, GPIO60};
static const unsigned mmp2_kpdk_pin1[] = {GPIO16, GPIO17, GPIO18, GPIO19};
static const unsigned mmp2_kpdk_pin2[] = {GPIO16, GPIO17};
static const unsigned mmp2_twsi2_pin1[] = {GPIO37, GPIO38};
static const unsigned mmp2_twsi2_pin2[] = {GPIO39, GPIO40};
static const unsigned mmp2_twsi2_pin3[] = {GPIO43, GPIO44};
static const unsigned mmp2_twsi2_pin4[] = {GPIO53, GPIO54};
static const unsigned mmp2_twsi2_pin5[] = {GPIO55, GPIO56};
static const unsigned mmp2_twsi3_pin1[] = {GPIO71, GPIO72};
static const unsigned mmp2_twsi3_pin2[] = {GPIO95, GPIO96};
static const unsigned mmp2_twsi4_pin1[] = {TWSI4_SCL, TWSI4_SDA};
static const unsigned mmp2_twsi5_pin1[] = {GPIO41, GPIO42};
static const unsigned mmp2_twsi5_pin2[] = {GPIO84, GPIO85};
static const unsigned mmp2_twsi5_pin3[] = {GPIO99, GPIO100};
static const unsigned mmp2_twsi6_pin1[] = {GPIO47, GPIO48};
static const unsigned mmp2_twsi6_pin2[] = {GPIO86, GPIO87};
static const unsigned mmp2_twsi6_pin3[] = {GPIO97, GPIO98};
static const unsigned mmp2_ccic1_pin1[] = {GPIO12, GPIO13, GPIO14, GPIO15,
GPIO16, GPIO17, GPIO18, GPIO19, GPIO20, GPIO21, GPIO22, GPIO23};
static const unsigned mmp2_ccic1_pin2[] = {GPIO59, GPIO60, GPIO61, GPIO62,
GPIO63, GPIO64, GPIO65, GPIO66, GPIO67, GPIO68, GPIO69, GPIO70};
static const unsigned mmp2_ccic2_pin1[] = {GPIO59, GPIO60, GPIO61, GPIO62,
GPIO63, GPIO64, GPIO65, GPIO66, GPIO67, GPIO68, GPIO69, GPIO70};
static const unsigned mmp2_ccic2_pin2[] = {GPIO82, GPIO83, GPIO86, GPIO87,
GPIO88, GPIO89, GPIO90, GPIO91, GPIO92, GPIO93, GPIO94, GPIO95};
static const unsigned mmp2_ulpi_pin1[] = {GPIO59, GPIO60, GPIO61, GPIO62,
GPIO63, GPIO64, GPIO65, GPIO66, GPIO67, GPIO68, GPIO69, GPIO70};
static const unsigned mmp2_ro_pin1[] = {GPIO16, GPIO17};
static const unsigned mmp2_ro_pin2[] = {GPIO18, GPIO19};
static const unsigned mmp2_ro_pin3[] = {GPIO51, GPIO52};
static const unsigned mmp2_ro_pin4[] = {GPIO55, GPIO56};
static const unsigned mmp2_i2s_pin1[] = {GPIO24, GPIO25, GPIO26, GPIO27,
GPIO28};
static const unsigned mmp2_i2s_pin2[] = {GPIO33, GPIO34, GPIO35, GPIO36};
static const unsigned mmp2_ssp1_pin1[] = {GPIO37, GPIO38, GPIO39, GPIO40};
static const unsigned mmp2_ssp1_pin2[] = {GPIO43, GPIO44, GPIO45, GPIO46};
static const unsigned mmp2_ssp1_pin3[] = {GPIO115, GPIO116, GPIO117, GPIO118};
static const unsigned mmp2_ssp2_pin1[] = {GPIO47, GPIO48, GPIO49, GPIO50};
static const unsigned mmp2_ssp3_pin1[] = {GPIO119, GPIO120, GPIO121, GPIO122};
static const unsigned mmp2_ssp3_pin2[] = {GPIO132, GPIO133, GPIO133, GPIO136};
static const unsigned mmp2_sspa2_pin1[] = {GPIO25, GPIO26, GPIO27, GPIO28};
static const unsigned mmp2_sspa2_pin2[] = {GPIO33, GPIO34, GPIO35, GPIO36};
static const unsigned mmp2_mmc1_pin1[] = {GPIO131, GPIO132, GPIO133, GPIO134,
GPIO136, GPIO139, GPIO140, GPIO141};
static const unsigned mmp2_mmc2_pin1[] = {GPIO37, GPIO38, GPIO39, GPIO40,
GPIO41, GPIO42};
static const unsigned mmp2_mmc3_pin1[] = {GPIO111, GPIO112, GPIO151, GPIO162,
GPIO163, GPIO164, GPIO165, GPIO166, GPIO167, GPIO168};
static struct pxa3xx_pin_group mmp2_grps[] = {
GRP_MMP2("uart1 4p1", UART1, mmp2_uart1_pin1),
GRP_MMP2("uart1 2p2", UART1, mmp2_uart1_pin2),
GRP_MMP2("uart1 2p3", UART1, mmp2_uart1_pin3),
GRP_MMP2("uart2 4p1", UART2, mmp2_uart2_pin1),
GRP_MMP2("uart2 4p2", UART2, mmp2_uart2_pin2),
GRP_MMP2("uart2 4p3", UART2, mmp2_uart2_pin3),
GRP_MMP2("uart2 4p4", UART2, mmp2_uart2_pin4),
GRP_MMP2("uart2 2p5", UART2, mmp2_uart2_pin5),
GRP_MMP2("uart2 2p6", UART2, mmp2_uart2_pin6),
GRP_MMP2("uart3 4p1", UART3, mmp2_uart3_pin1),
GRP_MMP2("uart3 4p2", UART3, mmp2_uart3_pin2),
GRP_MMP2("uart3 4p3", UART3, mmp2_uart3_pin3),
GRP_MMP2("uart3 4p4", UART3, mmp2_uart3_pin4),
GRP_MMP2("uart3 4p5", UART3, mmp2_uart3_pin5),
GRP_MMP2("uart3 2p6", UART3, mmp2_uart3_pin6),
GRP_MMP2("uart4 4p1", UART4, mmp2_uart4_pin1),
GRP_MMP2("uart4 4p2", UART4, mmp2_uart4_pin2),
GRP_MMP2("uart4 4p3", UART4, mmp2_uart4_pin3),
GRP_MMP2("uart4 4p4", UART4, mmp2_uart4_pin4),
GRP_MMP2("uart4 2p5", UART4, mmp2_uart4_pin5),
GRP_MMP2("kpdk 4p1", KP_DK, mmp2_kpdk_pin1),
GRP_MMP2("kpdk 4p2", KP_DK, mmp2_kpdk_pin2),
GRP_MMP2("twsi2-1", TWSI2, mmp2_twsi2_pin1),
GRP_MMP2("twsi2-2", TWSI2, mmp2_twsi2_pin2),
GRP_MMP2("twsi2-3", TWSI2, mmp2_twsi2_pin3),
GRP_MMP2("twsi2-4", TWSI2, mmp2_twsi2_pin4),
GRP_MMP2("twsi2-5", TWSI2, mmp2_twsi2_pin5),
GRP_MMP2("twsi3-1", TWSI3, mmp2_twsi3_pin1),
GRP_MMP2("twsi3-2", TWSI3, mmp2_twsi3_pin2),
GRP_MMP2("twsi4", TWSI4, mmp2_twsi4_pin1),
GRP_MMP2("twsi5-1", TWSI5, mmp2_twsi5_pin1),
GRP_MMP2("twsi5-2", TWSI5, mmp2_twsi5_pin2),
GRP_MMP2("twsi5-3", TWSI5, mmp2_twsi5_pin3),
GRP_MMP2("twsi6-1", TWSI6, mmp2_twsi6_pin1),
GRP_MMP2("twsi6-2", TWSI6, mmp2_twsi6_pin2),
GRP_MMP2("twsi6-3", TWSI6, mmp2_twsi6_pin3),
GRP_MMP2("ccic1-1", CCIC1, mmp2_ccic1_pin1),
GRP_MMP2("ccic1-2", CCIC1, mmp2_ccic1_pin2),
GRP_MMP2("ccic2-1", CCIC2, mmp2_ccic2_pin1),
GRP_MMP2("ccic2-1", CCIC2, mmp2_ccic2_pin2),
GRP_MMP2("ulpi", ULPI, mmp2_ulpi_pin1),
GRP_MMP2("ro-1", ROT, mmp2_ro_pin1),
GRP_MMP2("ro-2", ROT, mmp2_ro_pin2),
GRP_MMP2("ro-3", ROT, mmp2_ro_pin3),
GRP_MMP2("ro-4", ROT, mmp2_ro_pin4),
GRP_MMP2("i2s 5p1", I2S, mmp2_i2s_pin1),
GRP_MMP2("i2s 4p2", I2S, mmp2_i2s_pin2),
GRP_MMP2("ssp1 4p1", SSP1, mmp2_ssp1_pin1),
GRP_MMP2("ssp1 4p2", SSP1, mmp2_ssp1_pin2),
GRP_MMP2("ssp1 4p3", SSP1, mmp2_ssp1_pin3),
GRP_MMP2("ssp2 4p1", SSP2, mmp2_ssp2_pin1),
GRP_MMP2("ssp3 4p1", SSP3, mmp2_ssp3_pin1),
GRP_MMP2("ssp3 4p2", SSP3, mmp2_ssp3_pin2),
GRP_MMP2("sspa2 4p1", SSPA2, mmp2_sspa2_pin1),
GRP_MMP2("sspa2 4p2", SSPA2, mmp2_sspa2_pin2),
GRP_MMP2("mmc1 8p1", MMC1, mmp2_mmc1_pin1),
GRP_MMP2("mmc2 6p1", MMC2, mmp2_mmc2_pin1),
GRP_MMP2("mmc3 10p1", MMC3, mmp2_mmc3_pin1),
};
static const char * const mmp2_uart1_grps[] = {"uart1 4p1", "uart1 2p2",
"uart1 2p3"};
static const char * const mmp2_uart2_grps[] = {"uart2 4p1", "uart2 4p2",
"uart2 4p3", "uart2 4p4", "uart2 4p5", "uart2 4p6"};
static const char * const mmp2_uart3_grps[] = {"uart3 4p1", "uart3 4p2",
"uart3 4p3", "uart3 4p4", "uart3 4p5", "uart3 2p6"};
static const char * const mmp2_uart4_grps[] = {"uart4 4p1", "uart4 4p2",
"uart4 4p3", "uart4 4p4", "uart4 2p5"};
static const char * const mmp2_kpdk_grps[] = {"kpdk 4p1", "kpdk 4p2"};
static const char * const mmp2_twsi2_grps[] = {"twsi2-1", "twsi2-2",
"twsi2-3", "twsi2-4", "twsi2-5"};
static const char * const mmp2_twsi3_grps[] = {"twsi3-1", "twsi3-2"};
static const char * const mmp2_twsi4_grps[] = {"twsi4"};
static const char * const mmp2_twsi5_grps[] = {"twsi5-1", "twsi5-2",
"twsi5-3"};
static const char * const mmp2_twsi6_grps[] = {"twsi6-1", "twsi6-2",
"twsi6-3"};
static const char * const mmp2_ccic1_grps[] = {"ccic1-1", "ccic1-2"};
static const char * const mmp2_ccic2_grps[] = {"ccic2-1", "ccic2-2"};
static const char * const mmp2_ulpi_grps[] = {"ulpi"};
static const char * const mmp2_ro_grps[] = {"ro-1", "ro-2", "ro-3", "ro-4"};
static const char * const mmp2_i2s_grps[] = {"i2s 5p1", "i2s 4p2"};
static const char * const mmp2_ssp1_grps[] = {"ssp1 4p1", "ssp1 4p2",
"ssp1 4p3"};
static const char * const mmp2_ssp2_grps[] = {"ssp2 4p1"};
static const char * const mmp2_ssp3_grps[] = {"ssp3 4p1", "ssp3 4p2"};
static const char * const mmp2_sspa2_grps[] = {"sspa2 4p1", "sspa2 4p2"};
static const char * const mmp2_mmc1_grps[] = {"mmc1 8p1"};
static const char * const mmp2_mmc2_grps[] = {"mmc2 6p1"};
static const char * const mmp2_mmc3_grps[] = {"mmc3 10p1"};
static struct pxa3xx_pmx_func mmp2_funcs[] = {
{"uart1", ARRAY_AND_SIZE(mmp2_uart1_grps)},
{"uart2", ARRAY_AND_SIZE(mmp2_uart2_grps)},
{"uart3", ARRAY_AND_SIZE(mmp2_uart3_grps)},
{"uart4", ARRAY_AND_SIZE(mmp2_uart4_grps)},
{"kpdk", ARRAY_AND_SIZE(mmp2_kpdk_grps)},
{"twsi2", ARRAY_AND_SIZE(mmp2_twsi2_grps)},
{"twsi3", ARRAY_AND_SIZE(mmp2_twsi3_grps)},
{"twsi4", ARRAY_AND_SIZE(mmp2_twsi4_grps)},
{"twsi5", ARRAY_AND_SIZE(mmp2_twsi5_grps)},
{"twsi6", ARRAY_AND_SIZE(mmp2_twsi6_grps)},
{"ccic1", ARRAY_AND_SIZE(mmp2_ccic1_grps)},
{"ccic2", ARRAY_AND_SIZE(mmp2_ccic2_grps)},
{"ulpi", ARRAY_AND_SIZE(mmp2_ulpi_grps)},
{"ro", ARRAY_AND_SIZE(mmp2_ro_grps)},
{"i2s", ARRAY_AND_SIZE(mmp2_i2s_grps)},
{"ssp1", ARRAY_AND_SIZE(mmp2_ssp1_grps)},
{"ssp2", ARRAY_AND_SIZE(mmp2_ssp2_grps)},
{"ssp3", ARRAY_AND_SIZE(mmp2_ssp3_grps)},
{"sspa2", ARRAY_AND_SIZE(mmp2_sspa2_grps)},
{"mmc1", ARRAY_AND_SIZE(mmp2_mmc1_grps)},
{"mmc2", ARRAY_AND_SIZE(mmp2_mmc2_grps)},
{"mmc3", ARRAY_AND_SIZE(mmp2_mmc3_grps)},
};
static struct pinctrl_desc mmp2_pctrl_desc = {
.name = "mmp2-pinctrl",
.owner = THIS_MODULE,
};
static struct pxa3xx_pinmux_info mmp2_info = {
.mfp = mmp2_mfp,
.num_mfp = ARRAY_SIZE(mmp2_mfp),
.grps = mmp2_grps,
.num_grps = ARRAY_SIZE(mmp2_grps),
.funcs = mmp2_funcs,
.num_funcs = ARRAY_SIZE(mmp2_funcs),
.num_gpio = 169,
.desc = &mmp2_pctrl_desc,
.pads = mmp2_pads,
.num_pads = ARRAY_SIZE(mmp2_pads),
.cputype = PINCTRL_MMP2,
.ds_mask = MMP2_DS_MASK,
.ds_shift = MMP2_DS_SHIFT,
};
static int __devinit mmp2_pinmux_probe(struct platform_device *pdev)
{
return pxa3xx_pinctrl_register(pdev, &mmp2_info);
}
static int __devexit mmp2_pinmux_remove(struct platform_device *pdev)
{
return pxa3xx_pinctrl_unregister(pdev);
}
static struct platform_driver mmp2_pinmux_driver = {
.driver = {
.name = "mmp2-pinmux",
.owner = THIS_MODULE,
},
.probe = mmp2_pinmux_probe,
.remove = __devexit_p(mmp2_pinmux_remove),
};
static int __init mmp2_pinmux_init(void)
{
return platform_driver_register(&mmp2_pinmux_driver);
}
core_initcall_sync(mmp2_pinmux_init);
static void __exit mmp2_pinmux_exit(void)
{
platform_driver_unregister(&mmp2_pinmux_driver);
}
module_exit(mmp2_pinmux_exit);
MODULE_AUTHOR("Haojian Zhuang <haojian.zhuang@marvell.com>");
MODULE_DESCRIPTION("PXA3xx pin control driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
NieNs/IM-A840S-kernel-1 | drivers/hid/hid-lg2ff.c | 7035 | 3176 | /*
* Force feedback support for Logitech RumblePad and Rumblepad 2
*
* Copyright (c) 2008 Anssi Hannula <anssi.hannula@gmail.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/input.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/hid.h>
#include "usbhid/usbhid.h"
#include "hid-lg.h"
struct lg2ff_device {
struct hid_report *report;
};
static int play_effect(struct input_dev *dev, void *data,
struct ff_effect *effect)
{
struct hid_device *hid = input_get_drvdata(dev);
struct lg2ff_device *lg2ff = data;
int weak, strong;
strong = effect->u.rumble.strong_magnitude;
weak = effect->u.rumble.weak_magnitude;
if (weak || strong) {
weak = weak * 0xff / 0xffff;
strong = strong * 0xff / 0xffff;
lg2ff->report->field[0]->value[0] = 0x51;
lg2ff->report->field[0]->value[2] = weak;
lg2ff->report->field[0]->value[4] = strong;
} else {
lg2ff->report->field[0]->value[0] = 0xf3;
lg2ff->report->field[0]->value[2] = 0x00;
lg2ff->report->field[0]->value[4] = 0x00;
}
usbhid_submit_report(hid, lg2ff->report, USB_DIR_OUT);
return 0;
}
int lg2ff_init(struct hid_device *hid)
{
struct lg2ff_device *lg2ff;
struct hid_report *report;
struct hid_input *hidinput = list_entry(hid->inputs.next,
struct hid_input, list);
struct list_head *report_list =
&hid->report_enum[HID_OUTPUT_REPORT].report_list;
struct input_dev *dev = hidinput->input;
int error;
if (list_empty(report_list)) {
hid_err(hid, "no output report found\n");
return -ENODEV;
}
report = list_entry(report_list->next, struct hid_report, list);
if (report->maxfield < 1) {
hid_err(hid, "output report is empty\n");
return -ENODEV;
}
if (report->field[0]->report_count < 7) {
hid_err(hid, "not enough values in the field\n");
return -ENODEV;
}
lg2ff = kmalloc(sizeof(struct lg2ff_device), GFP_KERNEL);
if (!lg2ff)
return -ENOMEM;
set_bit(FF_RUMBLE, dev->ffbit);
error = input_ff_create_memless(dev, lg2ff, play_effect);
if (error) {
kfree(lg2ff);
return error;
}
lg2ff->report = report;
report->field[0]->value[0] = 0xf3;
report->field[0]->value[1] = 0x00;
report->field[0]->value[2] = 0x00;
report->field[0]->value[3] = 0x00;
report->field[0]->value[4] = 0x00;
report->field[0]->value[5] = 0x00;
report->field[0]->value[6] = 0x00;
usbhid_submit_report(hid, report, USB_DIR_OUT);
hid_info(hid, "Force feedback for Logitech RumblePad/Rumblepad 2 by Anssi Hannula <anssi.hannula@gmail.com>\n");
return 0;
}
| gpl-2.0 |
Team-Exhibit/android_kernel_samsung_u8500 | drivers/ide/ide-probe.c | 10619 | 38318 | /*
* Copyright (C) 1994-1998 Linus Torvalds & authors (see below)
* Copyright (C) 2005, 2007 Bartlomiej Zolnierkiewicz
*/
/*
* Mostly written by Mark Lord <mlord@pobox.com>
* and Gadi Oxman <gadio@netvision.net.il>
* and Andre Hedrick <andre@linux-ide.org>
*
* See linux/MAINTAINERS for address of current maintainer.
*
* This is the IDE probe module, as evolved from hd.c and ide.c.
*
* -- increase WAIT_PIDENTIFY to avoid CD-ROM locking at boot
* by Andrea Arcangeli
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/major.h>
#include <linux/errno.h>
#include <linux/genhd.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/spinlock.h>
#include <linux/kmod.h>
#include <linux/pci.h>
#include <linux/scatterlist.h>
#include <asm/byteorder.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#include <asm/io.h>
/**
* generic_id - add a generic drive id
* @drive: drive to make an ID block for
*
* Add a fake id field to the drive we are passed. This allows
* use to skip a ton of NULL checks (which people always miss)
* and make drive properties unconditional outside of this file
*/
static void generic_id(ide_drive_t *drive)
{
u16 *id = drive->id;
id[ATA_ID_CUR_CYLS] = id[ATA_ID_CYLS] = drive->cyl;
id[ATA_ID_CUR_HEADS] = id[ATA_ID_HEADS] = drive->head;
id[ATA_ID_CUR_SECTORS] = id[ATA_ID_SECTORS] = drive->sect;
}
static void ide_disk_init_chs(ide_drive_t *drive)
{
u16 *id = drive->id;
/* Extract geometry if we did not already have one for the drive */
if (!drive->cyl || !drive->head || !drive->sect) {
drive->cyl = drive->bios_cyl = id[ATA_ID_CYLS];
drive->head = drive->bios_head = id[ATA_ID_HEADS];
drive->sect = drive->bios_sect = id[ATA_ID_SECTORS];
}
/* Handle logical geometry translation by the drive */
if (ata_id_current_chs_valid(id)) {
drive->cyl = id[ATA_ID_CUR_CYLS];
drive->head = id[ATA_ID_CUR_HEADS];
drive->sect = id[ATA_ID_CUR_SECTORS];
}
/* Use physical geometry if what we have still makes no sense */
if (drive->head > 16 && id[ATA_ID_HEADS] && id[ATA_ID_HEADS] <= 16) {
drive->cyl = id[ATA_ID_CYLS];
drive->head = id[ATA_ID_HEADS];
drive->sect = id[ATA_ID_SECTORS];
}
}
static void ide_disk_init_mult_count(ide_drive_t *drive)
{
u16 *id = drive->id;
u8 max_multsect = id[ATA_ID_MAX_MULTSECT] & 0xff;
if (max_multsect) {
if ((max_multsect / 2) > 1)
id[ATA_ID_MULTSECT] = max_multsect | 0x100;
else
id[ATA_ID_MULTSECT] &= ~0x1ff;
drive->mult_req = id[ATA_ID_MULTSECT] & 0xff;
if (drive->mult_req)
drive->special_flags |= IDE_SFLAG_SET_MULTMODE;
}
}
static void ide_classify_ata_dev(ide_drive_t *drive)
{
u16 *id = drive->id;
char *m = (char *)&id[ATA_ID_PROD];
int is_cfa = ata_id_is_cfa(id);
/* CF devices are *not* removable in Linux definition of the term */
if (is_cfa == 0 && (id[ATA_ID_CONFIG] & (1 << 7)))
drive->dev_flags |= IDE_DFLAG_REMOVABLE;
drive->media = ide_disk;
if (!ata_id_has_unload(drive->id))
drive->dev_flags |= IDE_DFLAG_NO_UNLOAD;
printk(KERN_INFO "%s: %s, %s DISK drive\n", drive->name, m,
is_cfa ? "CFA" : "ATA");
}
static void ide_classify_atapi_dev(ide_drive_t *drive)
{
u16 *id = drive->id;
char *m = (char *)&id[ATA_ID_PROD];
u8 type = (id[ATA_ID_CONFIG] >> 8) & 0x1f;
printk(KERN_INFO "%s: %s, ATAPI ", drive->name, m);
switch (type) {
case ide_floppy:
if (!strstr(m, "CD-ROM")) {
if (!strstr(m, "oppy") &&
!strstr(m, "poyp") &&
!strstr(m, "ZIP"))
printk(KERN_CONT "cdrom or floppy?, assuming ");
if (drive->media != ide_cdrom) {
printk(KERN_CONT "FLOPPY");
drive->dev_flags |= IDE_DFLAG_REMOVABLE;
break;
}
}
/* Early cdrom models used zero */
type = ide_cdrom;
case ide_cdrom:
drive->dev_flags |= IDE_DFLAG_REMOVABLE;
#ifdef CONFIG_PPC
/* kludge for Apple PowerBook internal zip */
if (!strstr(m, "CD-ROM") && strstr(m, "ZIP")) {
printk(KERN_CONT "FLOPPY");
type = ide_floppy;
break;
}
#endif
printk(KERN_CONT "CD/DVD-ROM");
break;
case ide_tape:
printk(KERN_CONT "TAPE");
break;
case ide_optical:
printk(KERN_CONT "OPTICAL");
drive->dev_flags |= IDE_DFLAG_REMOVABLE;
break;
default:
printk(KERN_CONT "UNKNOWN (type %d)", type);
break;
}
printk(KERN_CONT " drive\n");
drive->media = type;
/* an ATAPI device ignores DRDY */
drive->ready_stat = 0;
if (ata_id_cdb_intr(id))
drive->atapi_flags |= IDE_AFLAG_DRQ_INTERRUPT;
drive->dev_flags |= IDE_DFLAG_DOORLOCKING;
/* we don't do head unloading on ATAPI devices */
drive->dev_flags |= IDE_DFLAG_NO_UNLOAD;
}
/**
* do_identify - identify a drive
* @drive: drive to identify
* @cmd: command used
* @id: buffer for IDENTIFY data
*
* Called when we have issued a drive identify command to
* read and parse the results. This function is run with
* interrupts disabled.
*/
static void do_identify(ide_drive_t *drive, u8 cmd, u16 *id)
{
ide_hwif_t *hwif = drive->hwif;
char *m = (char *)&id[ATA_ID_PROD];
unsigned long flags;
int bswap = 1;
/* local CPU only; some systems need this */
local_irq_save(flags);
/* read 512 bytes of id info */
hwif->tp_ops->input_data(drive, NULL, id, SECTOR_SIZE);
local_irq_restore(flags);
drive->dev_flags |= IDE_DFLAG_ID_READ;
#ifdef DEBUG
printk(KERN_INFO "%s: dumping identify data\n", drive->name);
ide_dump_identify((u8 *)id);
#endif
ide_fix_driveid(id);
/*
* ATA_CMD_ID_ATA returns little-endian info,
* ATA_CMD_ID_ATAPI *usually* returns little-endian info.
*/
if (cmd == ATA_CMD_ID_ATAPI) {
if ((m[0] == 'N' && m[1] == 'E') || /* NEC */
(m[0] == 'F' && m[1] == 'X') || /* Mitsumi */
(m[0] == 'P' && m[1] == 'i')) /* Pioneer */
/* Vertos drives may still be weird */
bswap ^= 1;
}
ide_fixstring(m, ATA_ID_PROD_LEN, bswap);
ide_fixstring((char *)&id[ATA_ID_FW_REV], ATA_ID_FW_REV_LEN, bswap);
ide_fixstring((char *)&id[ATA_ID_SERNO], ATA_ID_SERNO_LEN, bswap);
/* we depend on this a lot! */
m[ATA_ID_PROD_LEN - 1] = '\0';
if (strstr(m, "E X A B Y T E N E S T"))
drive->dev_flags &= ~IDE_DFLAG_PRESENT;
else
drive->dev_flags |= IDE_DFLAG_PRESENT;
}
/**
* ide_dev_read_id - send ATA/ATAPI IDENTIFY command
* @drive: drive to identify
* @cmd: command to use
* @id: buffer for IDENTIFY data
* @irq_ctx: flag set when called from the IRQ context
*
* Sends an ATA(PI) IDENTIFY request to a drive and waits for a response.
*
* Returns: 0 device was identified
* 1 device timed-out (no response to identify request)
* 2 device aborted the command (refused to identify itself)
*/
int ide_dev_read_id(ide_drive_t *drive, u8 cmd, u16 *id, int irq_ctx)
{
ide_hwif_t *hwif = drive->hwif;
struct ide_io_ports *io_ports = &hwif->io_ports;
const struct ide_tp_ops *tp_ops = hwif->tp_ops;
int use_altstatus = 0, rc;
unsigned long timeout;
u8 s = 0, a = 0;
/*
* Disable device IRQ. Otherwise we'll get spurious interrupts
* during the identify phase that the IRQ handler isn't expecting.
*/
if (io_ports->ctl_addr)
tp_ops->write_devctl(hwif, ATA_NIEN | ATA_DEVCTL_OBS);
/* take a deep breath */
if (irq_ctx)
mdelay(50);
else
msleep(50);
if (io_ports->ctl_addr &&
(hwif->host_flags & IDE_HFLAG_BROKEN_ALTSTATUS) == 0) {
a = tp_ops->read_altstatus(hwif);
s = tp_ops->read_status(hwif);
if ((a ^ s) & ~ATA_IDX)
/* ancient Seagate drives, broken interfaces */
printk(KERN_INFO "%s: probing with STATUS(0x%02x) "
"instead of ALTSTATUS(0x%02x)\n",
drive->name, s, a);
else
/* use non-intrusive polling */
use_altstatus = 1;
}
/* set features register for atapi
* identify command to be sure of reply
*/
if (cmd == ATA_CMD_ID_ATAPI) {
struct ide_taskfile tf;
memset(&tf, 0, sizeof(tf));
/* disable DMA & overlap */
tp_ops->tf_load(drive, &tf, IDE_VALID_FEATURE);
}
/* ask drive for ID */
tp_ops->exec_command(hwif, cmd);
timeout = ((cmd == ATA_CMD_ID_ATA) ? WAIT_WORSTCASE : WAIT_PIDENTIFY) / 2;
/* wait for IRQ and ATA_DRQ */
if (irq_ctx) {
rc = __ide_wait_stat(drive, ATA_DRQ, BAD_R_STAT, timeout, &s);
if (rc)
return 1;
} else {
rc = ide_busy_sleep(drive, timeout, use_altstatus);
if (rc)
return 1;
msleep(50);
s = tp_ops->read_status(hwif);
}
if (OK_STAT(s, ATA_DRQ, BAD_R_STAT)) {
/* drive returned ID */
do_identify(drive, cmd, id);
/* drive responded with ID */
rc = 0;
/* clear drive IRQ */
(void)tp_ops->read_status(hwif);
} else {
/* drive refused ID */
rc = 2;
}
return rc;
}
int ide_busy_sleep(ide_drive_t *drive, unsigned long timeout, int altstatus)
{
ide_hwif_t *hwif = drive->hwif;
u8 stat;
timeout += jiffies;
do {
msleep(50); /* give drive a breather */
stat = altstatus ? hwif->tp_ops->read_altstatus(hwif)
: hwif->tp_ops->read_status(hwif);
if ((stat & ATA_BUSY) == 0)
return 0;
} while (time_before(jiffies, timeout));
printk(KERN_ERR "%s: timeout in %s\n", drive->name, __func__);
return 1; /* drive timed-out */
}
static u8 ide_read_device(ide_drive_t *drive)
{
struct ide_taskfile tf;
drive->hwif->tp_ops->tf_read(drive, &tf, IDE_VALID_DEVICE);
return tf.device;
}
/**
* do_probe - probe an IDE device
* @drive: drive to probe
* @cmd: command to use
*
* do_probe() has the difficult job of finding a drive if it exists,
* without getting hung up if it doesn't exist, without trampling on
* ethernet cards, and without leaving any IRQs dangling to haunt us later.
*
* If a drive is "known" to exist (from CMOS or kernel parameters),
* but does not respond right away, the probe will "hang in there"
* for the maximum wait time (about 30 seconds), otherwise it will
* exit much more quickly.
*
* Returns: 0 device was identified
* 1 device timed-out (no response to identify request)
* 2 device aborted the command (refused to identify itself)
* 3 bad status from device (possible for ATAPI drives)
* 4 probe was not attempted because failure was obvious
*/
static int do_probe (ide_drive_t *drive, u8 cmd)
{
ide_hwif_t *hwif = drive->hwif;
const struct ide_tp_ops *tp_ops = hwif->tp_ops;
u16 *id = drive->id;
int rc;
u8 present = !!(drive->dev_flags & IDE_DFLAG_PRESENT), stat;
/* avoid waiting for inappropriate probes */
if (present && drive->media != ide_disk && cmd == ATA_CMD_ID_ATA)
return 4;
#ifdef DEBUG
printk(KERN_INFO "probing for %s: present=%d, media=%d, probetype=%s\n",
drive->name, present, drive->media,
(cmd == ATA_CMD_ID_ATA) ? "ATA" : "ATAPI");
#endif
/* needed for some systems
* (e.g. crw9624 as drive0 with disk as slave)
*/
msleep(50);
tp_ops->dev_select(drive);
msleep(50);
if (ide_read_device(drive) != drive->select && present == 0) {
if (drive->dn & 1) {
/* exit with drive0 selected */
tp_ops->dev_select(hwif->devices[0]);
/* allow ATA_BUSY to assert & clear */
msleep(50);
}
/* no i/f present: mmm.. this should be a 4 -ml */
return 3;
}
stat = tp_ops->read_status(hwif);
if (OK_STAT(stat, ATA_DRDY, ATA_BUSY) ||
present || cmd == ATA_CMD_ID_ATAPI) {
rc = ide_dev_read_id(drive, cmd, id, 0);
if (rc)
/* failed: try again */
rc = ide_dev_read_id(drive, cmd, id, 0);
stat = tp_ops->read_status(hwif);
if (stat == (ATA_BUSY | ATA_DRDY))
return 4;
if (rc == 1 && cmd == ATA_CMD_ID_ATAPI) {
printk(KERN_ERR "%s: no response (status = 0x%02x), "
"resetting drive\n", drive->name, stat);
msleep(50);
tp_ops->dev_select(drive);
msleep(50);
tp_ops->exec_command(hwif, ATA_CMD_DEV_RESET);
(void)ide_busy_sleep(drive, WAIT_WORSTCASE, 0);
rc = ide_dev_read_id(drive, cmd, id, 0);
}
/* ensure drive IRQ is clear */
stat = tp_ops->read_status(hwif);
if (rc == 1)
printk(KERN_ERR "%s: no response (status = 0x%02x)\n",
drive->name, stat);
} else {
/* not present or maybe ATAPI */
rc = 3;
}
if (drive->dn & 1) {
/* exit with drive0 selected */
tp_ops->dev_select(hwif->devices[0]);
msleep(50);
/* ensure drive irq is clear */
(void)tp_ops->read_status(hwif);
}
return rc;
}
/**
* probe_for_drives - upper level drive probe
* @drive: drive to probe for
*
* probe_for_drive() tests for existence of a given drive using do_probe()
* and presents things to the user as needed.
*
* Returns: 0 no device was found
* 1 device was found
* (note: IDE_DFLAG_PRESENT might still be not set)
*/
static u8 probe_for_drive(ide_drive_t *drive)
{
char *m;
int rc;
u8 cmd;
drive->dev_flags &= ~IDE_DFLAG_ID_READ;
m = (char *)&drive->id[ATA_ID_PROD];
strcpy(m, "UNKNOWN");
/* skip probing? */
if ((drive->dev_flags & IDE_DFLAG_NOPROBE) == 0) {
/* if !(success||timed-out) */
cmd = ATA_CMD_ID_ATA;
rc = do_probe(drive, cmd);
if (rc >= 2) {
/* look for ATAPI device */
cmd = ATA_CMD_ID_ATAPI;
rc = do_probe(drive, cmd);
}
if ((drive->dev_flags & IDE_DFLAG_PRESENT) == 0)
return 0;
/* identification failed? */
if ((drive->dev_flags & IDE_DFLAG_ID_READ) == 0) {
if (drive->media == ide_disk) {
printk(KERN_INFO "%s: non-IDE drive, CHS=%d/%d/%d\n",
drive->name, drive->cyl,
drive->head, drive->sect);
} else if (drive->media == ide_cdrom) {
printk(KERN_INFO "%s: ATAPI cdrom (?)\n", drive->name);
} else {
/* nuke it */
printk(KERN_WARNING "%s: Unknown device on bus refused identification. Ignoring.\n", drive->name);
drive->dev_flags &= ~IDE_DFLAG_PRESENT;
}
} else {
if (cmd == ATA_CMD_ID_ATAPI)
ide_classify_atapi_dev(drive);
else
ide_classify_ata_dev(drive);
}
}
if ((drive->dev_flags & IDE_DFLAG_PRESENT) == 0)
return 0;
/* The drive wasn't being helpful. Add generic info only */
if ((drive->dev_flags & IDE_DFLAG_ID_READ) == 0) {
generic_id(drive);
return 1;
}
if (drive->media == ide_disk) {
ide_disk_init_chs(drive);
ide_disk_init_mult_count(drive);
}
return 1;
}
static void hwif_release_dev(struct device *dev)
{
ide_hwif_t *hwif = container_of(dev, ide_hwif_t, gendev);
complete(&hwif->gendev_rel_comp);
}
static int ide_register_port(ide_hwif_t *hwif)
{
int ret;
/* register with global device tree */
dev_set_name(&hwif->gendev, hwif->name);
dev_set_drvdata(&hwif->gendev, hwif);
if (hwif->gendev.parent == NULL)
hwif->gendev.parent = hwif->dev;
hwif->gendev.release = hwif_release_dev;
ret = device_register(&hwif->gendev);
if (ret < 0) {
printk(KERN_WARNING "IDE: %s: device_register error: %d\n",
__func__, ret);
goto out;
}
hwif->portdev = device_create(ide_port_class, &hwif->gendev,
MKDEV(0, 0), hwif, hwif->name);
if (IS_ERR(hwif->portdev)) {
ret = PTR_ERR(hwif->portdev);
device_unregister(&hwif->gendev);
}
out:
return ret;
}
/**
* ide_port_wait_ready - wait for port to become ready
* @hwif: IDE port
*
* This is needed on some PPCs and a bunch of BIOS-less embedded
* platforms. Typical cases are:
*
* - The firmware hard reset the disk before booting the kernel,
* the drive is still doing it's poweron-reset sequence, that
* can take up to 30 seconds.
*
* - The firmware does nothing (or no firmware), the device is
* still in POST state (same as above actually).
*
* - Some CD/DVD/Writer combo drives tend to drive the bus during
* their reset sequence even when they are non-selected slave
* devices, thus preventing discovery of the main HD.
*
* Doing this wait-for-non-busy should not harm any existing
* configuration and fix some issues like the above.
*
* BenH.
*
* Returns 0 on success, error code (< 0) otherwise.
*/
static int ide_port_wait_ready(ide_hwif_t *hwif)
{
const struct ide_tp_ops *tp_ops = hwif->tp_ops;
ide_drive_t *drive;
int i, rc;
printk(KERN_DEBUG "Probing IDE interface %s...\n", hwif->name);
/* Let HW settle down a bit from whatever init state we
* come from */
mdelay(2);
/* Wait for BSY bit to go away, spec timeout is 30 seconds,
* I know of at least one disk who takes 31 seconds, I use 35
* here to be safe
*/
rc = ide_wait_not_busy(hwif, 35000);
if (rc)
return rc;
/* Now make sure both master & slave are ready */
ide_port_for_each_dev(i, drive, hwif) {
/* Ignore disks that we will not probe for later. */
if ((drive->dev_flags & IDE_DFLAG_NOPROBE) == 0 ||
(drive->dev_flags & IDE_DFLAG_PRESENT)) {
tp_ops->dev_select(drive);
tp_ops->write_devctl(hwif, ATA_DEVCTL_OBS);
mdelay(2);
rc = ide_wait_not_busy(hwif, 35000);
if (rc)
goto out;
} else
printk(KERN_DEBUG "%s: ide_wait_not_busy() skipped\n",
drive->name);
}
out:
/* Exit function with master reselected (let's be sane) */
if (i)
tp_ops->dev_select(hwif->devices[0]);
return rc;
}
/**
* ide_undecoded_slave - look for bad CF adapters
* @dev1: slave device
*
* Analyse the drives on the interface and attempt to decide if we
* have the same drive viewed twice. This occurs with crap CF adapters
* and PCMCIA sometimes.
*/
void ide_undecoded_slave(ide_drive_t *dev1)
{
ide_drive_t *dev0 = dev1->hwif->devices[0];
if ((dev1->dn & 1) == 0 || (dev0->dev_flags & IDE_DFLAG_PRESENT) == 0)
return;
/* If the models don't match they are not the same product */
if (strcmp((char *)&dev0->id[ATA_ID_PROD],
(char *)&dev1->id[ATA_ID_PROD]))
return;
/* Serial numbers do not match */
if (strncmp((char *)&dev0->id[ATA_ID_SERNO],
(char *)&dev1->id[ATA_ID_SERNO], ATA_ID_SERNO_LEN))
return;
/* No serial number, thankfully very rare for CF */
if (*(char *)&dev0->id[ATA_ID_SERNO] == 0)
return;
/* Appears to be an IDE flash adapter with decode bugs */
printk(KERN_WARNING "ide-probe: ignoring undecoded slave\n");
dev1->dev_flags &= ~IDE_DFLAG_PRESENT;
}
EXPORT_SYMBOL_GPL(ide_undecoded_slave);
static int ide_probe_port(ide_hwif_t *hwif)
{
ide_drive_t *drive;
unsigned int irqd;
int i, rc = -ENODEV;
BUG_ON(hwif->present);
if ((hwif->devices[0]->dev_flags & IDE_DFLAG_NOPROBE) &&
(hwif->devices[1]->dev_flags & IDE_DFLAG_NOPROBE))
return -EACCES;
/*
* We must always disable IRQ, as probe_for_drive will assert IRQ, but
* we'll install our IRQ driver much later...
*/
irqd = hwif->irq;
if (irqd)
disable_irq(hwif->irq);
if (ide_port_wait_ready(hwif) == -EBUSY)
printk(KERN_DEBUG "%s: Wait for ready failed before probe !\n", hwif->name);
/*
* Second drive should only exist if first drive was found,
* but a lot of cdrom drives are configured as single slaves.
*/
ide_port_for_each_dev(i, drive, hwif) {
(void) probe_for_drive(drive);
if (drive->dev_flags & IDE_DFLAG_PRESENT)
rc = 0;
}
/*
* Use cached IRQ number. It might be (and is...) changed by probe
* code above
*/
if (irqd)
enable_irq(irqd);
return rc;
}
static void ide_port_tune_devices(ide_hwif_t *hwif)
{
const struct ide_port_ops *port_ops = hwif->port_ops;
ide_drive_t *drive;
int i;
ide_port_for_each_present_dev(i, drive, hwif) {
ide_check_nien_quirk_list(drive);
if (port_ops && port_ops->quirkproc)
port_ops->quirkproc(drive);
}
ide_port_for_each_present_dev(i, drive, hwif) {
ide_set_max_pio(drive);
drive->dev_flags |= IDE_DFLAG_NICE1;
if (hwif->dma_ops)
ide_set_dma(drive);
}
}
/*
* init request queue
*/
static int ide_init_queue(ide_drive_t *drive)
{
struct request_queue *q;
ide_hwif_t *hwif = drive->hwif;
int max_sectors = 256;
int max_sg_entries = PRD_ENTRIES;
/*
* Our default set up assumes the normal IDE case,
* that is 64K segmenting, standard PRD setup
* and LBA28. Some drivers then impose their own
* limits and LBA48 we could raise it but as yet
* do not.
*/
q = blk_init_queue_node(do_ide_request, NULL, hwif_to_node(hwif));
if (!q)
return 1;
q->queuedata = drive;
blk_queue_segment_boundary(q, 0xffff);
if (hwif->rqsize < max_sectors)
max_sectors = hwif->rqsize;
blk_queue_max_hw_sectors(q, max_sectors);
#ifdef CONFIG_PCI
/* When we have an IOMMU, we may have a problem where pci_map_sg()
* creates segments that don't completely match our boundary
* requirements and thus need to be broken up again. Because it
* doesn't align properly either, we may actually have to break up
* to more segments than what was we got in the first place, a max
* worst case is twice as many.
* This will be fixed once we teach pci_map_sg() about our boundary
* requirements, hopefully soon. *FIXME*
*/
if (!PCI_DMA_BUS_IS_PHYS)
max_sg_entries >>= 1;
#endif /* CONFIG_PCI */
blk_queue_max_segments(q, max_sg_entries);
/* assign drive queue */
drive->queue = q;
/* needs drive->queue to be set */
ide_toggle_bounce(drive, 1);
return 0;
}
static DEFINE_MUTEX(ide_cfg_mtx);
/*
* For any present drive:
* - allocate the block device queue
*/
static int ide_port_setup_devices(ide_hwif_t *hwif)
{
ide_drive_t *drive;
int i, j = 0;
mutex_lock(&ide_cfg_mtx);
ide_port_for_each_present_dev(i, drive, hwif) {
if (ide_init_queue(drive)) {
printk(KERN_ERR "ide: failed to init %s\n",
drive->name);
drive->dev_flags &= ~IDE_DFLAG_PRESENT;
continue;
}
j++;
}
mutex_unlock(&ide_cfg_mtx);
return j;
}
static void ide_host_enable_irqs(struct ide_host *host)
{
ide_hwif_t *hwif;
int i;
ide_host_for_each_port(i, hwif, host) {
if (hwif == NULL)
continue;
/* clear any pending IRQs */
hwif->tp_ops->read_status(hwif);
/* unmask IRQs */
if (hwif->io_ports.ctl_addr)
hwif->tp_ops->write_devctl(hwif, ATA_DEVCTL_OBS);
}
}
/*
* This routine sets up the IRQ for an IDE interface.
*/
static int init_irq (ide_hwif_t *hwif)
{
struct ide_io_ports *io_ports = &hwif->io_ports;
struct ide_host *host = hwif->host;
irq_handler_t irq_handler = host->irq_handler;
int sa = host->irq_flags;
if (irq_handler == NULL)
irq_handler = ide_intr;
if (request_irq(hwif->irq, irq_handler, sa, hwif->name, hwif))
goto out_up;
#if !defined(__mc68000__)
printk(KERN_INFO "%s at 0x%03lx-0x%03lx,0x%03lx on irq %d", hwif->name,
io_ports->data_addr, io_ports->status_addr,
io_ports->ctl_addr, hwif->irq);
#else
printk(KERN_INFO "%s at 0x%08lx on irq %d", hwif->name,
io_ports->data_addr, hwif->irq);
#endif /* __mc68000__ */
if (hwif->host->host_flags & IDE_HFLAG_SERIALIZE)
printk(KERN_CONT " (serialized)");
printk(KERN_CONT "\n");
return 0;
out_up:
return 1;
}
static int ata_lock(dev_t dev, void *data)
{
/* FIXME: we want to pin hwif down */
return 0;
}
static struct kobject *ata_probe(dev_t dev, int *part, void *data)
{
ide_hwif_t *hwif = data;
int unit = *part >> PARTN_BITS;
ide_drive_t *drive = hwif->devices[unit];
if ((drive->dev_flags & IDE_DFLAG_PRESENT) == 0)
return NULL;
if (drive->media == ide_disk)
request_module("ide-disk");
if (drive->media == ide_cdrom || drive->media == ide_optical)
request_module("ide-cd");
if (drive->media == ide_tape)
request_module("ide-tape");
if (drive->media == ide_floppy)
request_module("ide-floppy");
return NULL;
}
static struct kobject *exact_match(dev_t dev, int *part, void *data)
{
struct gendisk *p = data;
*part &= (1 << PARTN_BITS) - 1;
return &disk_to_dev(p)->kobj;
}
static int exact_lock(dev_t dev, void *data)
{
struct gendisk *p = data;
if (!get_disk(p))
return -1;
return 0;
}
void ide_register_region(struct gendisk *disk)
{
blk_register_region(MKDEV(disk->major, disk->first_minor),
disk->minors, NULL, exact_match, exact_lock, disk);
}
EXPORT_SYMBOL_GPL(ide_register_region);
void ide_unregister_region(struct gendisk *disk)
{
blk_unregister_region(MKDEV(disk->major, disk->first_minor),
disk->minors);
}
EXPORT_SYMBOL_GPL(ide_unregister_region);
void ide_init_disk(struct gendisk *disk, ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
unsigned int unit = drive->dn & 1;
disk->major = hwif->major;
disk->first_minor = unit << PARTN_BITS;
sprintf(disk->disk_name, "hd%c", 'a' + hwif->index * MAX_DRIVES + unit);
disk->queue = drive->queue;
}
EXPORT_SYMBOL_GPL(ide_init_disk);
static void drive_release_dev (struct device *dev)
{
ide_drive_t *drive = container_of(dev, ide_drive_t, gendev);
ide_proc_unregister_device(drive);
blk_cleanup_queue(drive->queue);
drive->queue = NULL;
drive->dev_flags &= ~IDE_DFLAG_PRESENT;
complete(&drive->gendev_rel_comp);
}
static int hwif_init(ide_hwif_t *hwif)
{
if (!hwif->irq) {
printk(KERN_ERR "%s: disabled, no IRQ\n", hwif->name);
return 0;
}
if (register_blkdev(hwif->major, hwif->name))
return 0;
if (!hwif->sg_max_nents)
hwif->sg_max_nents = PRD_ENTRIES;
hwif->sg_table = kmalloc(sizeof(struct scatterlist)*hwif->sg_max_nents,
GFP_KERNEL);
if (!hwif->sg_table) {
printk(KERN_ERR "%s: unable to allocate SG table.\n", hwif->name);
goto out;
}
sg_init_table(hwif->sg_table, hwif->sg_max_nents);
if (init_irq(hwif)) {
printk(KERN_ERR "%s: disabled, unable to get IRQ %d\n",
hwif->name, hwif->irq);
goto out;
}
blk_register_region(MKDEV(hwif->major, 0), MAX_DRIVES << PARTN_BITS,
THIS_MODULE, ata_probe, ata_lock, hwif);
return 1;
out:
unregister_blkdev(hwif->major, hwif->name);
return 0;
}
static void hwif_register_devices(ide_hwif_t *hwif)
{
ide_drive_t *drive;
unsigned int i;
ide_port_for_each_present_dev(i, drive, hwif) {
struct device *dev = &drive->gendev;
int ret;
dev_set_name(dev, "%u.%u", hwif->index, i);
dev_set_drvdata(dev, drive);
dev->parent = &hwif->gendev;
dev->bus = &ide_bus_type;
dev->release = drive_release_dev;
ret = device_register(dev);
if (ret < 0)
printk(KERN_WARNING "IDE: %s: device_register error: "
"%d\n", __func__, ret);
}
}
static void ide_port_init_devices(ide_hwif_t *hwif)
{
const struct ide_port_ops *port_ops = hwif->port_ops;
ide_drive_t *drive;
int i;
ide_port_for_each_dev(i, drive, hwif) {
drive->dn = i + hwif->channel * 2;
if (hwif->host_flags & IDE_HFLAG_IO_32BIT)
drive->io_32bit = 1;
if (hwif->host_flags & IDE_HFLAG_NO_IO_32BIT)
drive->dev_flags |= IDE_DFLAG_NO_IO_32BIT;
if (hwif->host_flags & IDE_HFLAG_UNMASK_IRQS)
drive->dev_flags |= IDE_DFLAG_UNMASK;
if (hwif->host_flags & IDE_HFLAG_NO_UNMASK_IRQS)
drive->dev_flags |= IDE_DFLAG_NO_UNMASK;
drive->pio_mode = XFER_PIO_0;
if (port_ops && port_ops->init_dev)
port_ops->init_dev(drive);
}
}
static void ide_init_port(ide_hwif_t *hwif, unsigned int port,
const struct ide_port_info *d)
{
hwif->channel = port;
hwif->chipset = d->chipset ? d->chipset : ide_pci;
if (d->init_iops)
d->init_iops(hwif);
/* ->host_flags may be set by ->init_iops (or even earlier...) */
hwif->host_flags |= d->host_flags;
hwif->pio_mask = d->pio_mask;
if (d->tp_ops)
hwif->tp_ops = d->tp_ops;
/* ->set_pio_mode for DTC2278 is currently limited to port 0 */
if ((hwif->host_flags & IDE_HFLAG_DTC2278) == 0 || hwif->channel == 0)
hwif->port_ops = d->port_ops;
hwif->swdma_mask = d->swdma_mask;
hwif->mwdma_mask = d->mwdma_mask;
hwif->ultra_mask = d->udma_mask;
if ((d->host_flags & IDE_HFLAG_NO_DMA) == 0) {
int rc;
hwif->dma_ops = d->dma_ops;
if (d->init_dma)
rc = d->init_dma(hwif, d);
else
rc = ide_hwif_setup_dma(hwif, d);
if (rc < 0) {
printk(KERN_INFO "%s: DMA disabled\n", hwif->name);
hwif->dma_ops = NULL;
hwif->dma_base = 0;
hwif->swdma_mask = 0;
hwif->mwdma_mask = 0;
hwif->ultra_mask = 0;
}
}
if ((d->host_flags & IDE_HFLAG_SERIALIZE) ||
((d->host_flags & IDE_HFLAG_SERIALIZE_DMA) && hwif->dma_base))
hwif->host->host_flags |= IDE_HFLAG_SERIALIZE;
if (d->max_sectors)
hwif->rqsize = d->max_sectors;
else {
if ((hwif->host_flags & IDE_HFLAG_NO_LBA48) ||
(hwif->host_flags & IDE_HFLAG_NO_LBA48_DMA))
hwif->rqsize = 256;
else
hwif->rqsize = 65536;
}
/* call chipset specific routine for each enabled port */
if (d->init_hwif)
d->init_hwif(hwif);
}
static void ide_port_cable_detect(ide_hwif_t *hwif)
{
const struct ide_port_ops *port_ops = hwif->port_ops;
if (port_ops && port_ops->cable_detect && (hwif->ultra_mask & 0x78)) {
if (hwif->cbl != ATA_CBL_PATA40_SHORT)
hwif->cbl = port_ops->cable_detect(hwif);
}
}
static const u8 ide_hwif_to_major[] =
{ IDE0_MAJOR, IDE1_MAJOR, IDE2_MAJOR, IDE3_MAJOR, IDE4_MAJOR,
IDE5_MAJOR, IDE6_MAJOR, IDE7_MAJOR, IDE8_MAJOR, IDE9_MAJOR };
static void ide_port_init_devices_data(ide_hwif_t *hwif)
{
ide_drive_t *drive;
int i;
ide_port_for_each_dev(i, drive, hwif) {
u8 j = (hwif->index * MAX_DRIVES) + i;
u16 *saved_id = drive->id;
memset(drive, 0, sizeof(*drive));
memset(saved_id, 0, SECTOR_SIZE);
drive->id = saved_id;
drive->media = ide_disk;
drive->select = (i << 4) | ATA_DEVICE_OBS;
drive->hwif = hwif;
drive->ready_stat = ATA_DRDY;
drive->bad_wstat = BAD_W_STAT;
drive->special_flags = IDE_SFLAG_RECALIBRATE |
IDE_SFLAG_SET_GEOMETRY;
drive->name[0] = 'h';
drive->name[1] = 'd';
drive->name[2] = 'a' + j;
drive->max_failures = IDE_DEFAULT_MAX_FAILURES;
INIT_LIST_HEAD(&drive->list);
init_completion(&drive->gendev_rel_comp);
}
}
static void ide_init_port_data(ide_hwif_t *hwif, unsigned int index)
{
/* fill in any non-zero initial values */
hwif->index = index;
hwif->major = ide_hwif_to_major[index];
hwif->name[0] = 'i';
hwif->name[1] = 'd';
hwif->name[2] = 'e';
hwif->name[3] = '0' + index;
spin_lock_init(&hwif->lock);
init_timer(&hwif->timer);
hwif->timer.function = &ide_timer_expiry;
hwif->timer.data = (unsigned long)hwif;
init_completion(&hwif->gendev_rel_comp);
hwif->tp_ops = &default_tp_ops;
ide_port_init_devices_data(hwif);
}
static void ide_init_port_hw(ide_hwif_t *hwif, struct ide_hw *hw)
{
memcpy(&hwif->io_ports, &hw->io_ports, sizeof(hwif->io_ports));
hwif->irq = hw->irq;
hwif->dev = hw->dev;
hwif->gendev.parent = hw->parent ? hw->parent : hw->dev;
hwif->config_data = hw->config;
}
static unsigned int ide_indexes;
/**
* ide_find_port_slot - find free port slot
* @d: IDE port info
*
* Return the new port slot index or -ENOENT if we are out of free slots.
*/
static int ide_find_port_slot(const struct ide_port_info *d)
{
int idx = -ENOENT;
u8 bootable = (d && (d->host_flags & IDE_HFLAG_NON_BOOTABLE)) ? 0 : 1;
u8 i = (d && (d->host_flags & IDE_HFLAG_QD_2ND_PORT)) ? 1 : 0;
/*
* Claim an unassigned slot.
*
* Give preference to claiming other slots before claiming ide0/ide1,
* just in case there's another interface yet-to-be-scanned
* which uses ports 0x1f0/0x170 (the ide0/ide1 defaults).
*
* Unless there is a bootable card that does not use the standard
* ports 0x1f0/0x170 (the ide0/ide1 defaults).
*/
mutex_lock(&ide_cfg_mtx);
if (bootable) {
if ((ide_indexes | i) != (1 << MAX_HWIFS) - 1)
idx = ffz(ide_indexes | i);
} else {
if ((ide_indexes | 3) != (1 << MAX_HWIFS) - 1)
idx = ffz(ide_indexes | 3);
else if ((ide_indexes & 3) != 3)
idx = ffz(ide_indexes);
}
if (idx >= 0)
ide_indexes |= (1 << idx);
mutex_unlock(&ide_cfg_mtx);
return idx;
}
static void ide_free_port_slot(int idx)
{
mutex_lock(&ide_cfg_mtx);
ide_indexes &= ~(1 << idx);
mutex_unlock(&ide_cfg_mtx);
}
static void ide_port_free_devices(ide_hwif_t *hwif)
{
ide_drive_t *drive;
int i;
ide_port_for_each_dev(i, drive, hwif) {
kfree(drive->id);
kfree(drive);
}
}
static int ide_port_alloc_devices(ide_hwif_t *hwif, int node)
{
int i;
for (i = 0; i < MAX_DRIVES; i++) {
ide_drive_t *drive;
drive = kzalloc_node(sizeof(*drive), GFP_KERNEL, node);
if (drive == NULL)
goto out_nomem;
/*
* In order to keep things simple we have an id
* block for all drives at all times. If the device
* is pre ATA or refuses ATA/ATAPI identify we
* will add faked data to this.
*
* Also note that 0 everywhere means "can't do X"
*/
drive->id = kzalloc_node(SECTOR_SIZE, GFP_KERNEL, node);
if (drive->id == NULL)
goto out_nomem;
hwif->devices[i] = drive;
}
return 0;
out_nomem:
ide_port_free_devices(hwif);
return -ENOMEM;
}
struct ide_host *ide_host_alloc(const struct ide_port_info *d,
struct ide_hw **hws, unsigned int n_ports)
{
struct ide_host *host;
struct device *dev = hws[0] ? hws[0]->dev : NULL;
int node = dev ? dev_to_node(dev) : -1;
int i;
host = kzalloc_node(sizeof(*host), GFP_KERNEL, node);
if (host == NULL)
return NULL;
for (i = 0; i < n_ports; i++) {
ide_hwif_t *hwif;
int idx;
if (hws[i] == NULL)
continue;
hwif = kzalloc_node(sizeof(*hwif), GFP_KERNEL, node);
if (hwif == NULL)
continue;
if (ide_port_alloc_devices(hwif, node) < 0) {
kfree(hwif);
continue;
}
idx = ide_find_port_slot(d);
if (idx < 0) {
printk(KERN_ERR "%s: no free slot for interface\n",
d ? d->name : "ide");
ide_port_free_devices(hwif);
kfree(hwif);
continue;
}
ide_init_port_data(hwif, idx);
hwif->host = host;
host->ports[i] = hwif;
host->n_ports++;
}
if (host->n_ports == 0) {
kfree(host);
return NULL;
}
host->dev[0] = dev;
if (d) {
host->init_chipset = d->init_chipset;
host->get_lock = d->get_lock;
host->release_lock = d->release_lock;
host->host_flags = d->host_flags;
host->irq_flags = d->irq_flags;
}
return host;
}
EXPORT_SYMBOL_GPL(ide_host_alloc);
static void ide_port_free(ide_hwif_t *hwif)
{
ide_port_free_devices(hwif);
ide_free_port_slot(hwif->index);
kfree(hwif);
}
static void ide_disable_port(ide_hwif_t *hwif)
{
struct ide_host *host = hwif->host;
int i;
printk(KERN_INFO "%s: disabling port\n", hwif->name);
for (i = 0; i < MAX_HOST_PORTS; i++) {
if (host->ports[i] == hwif) {
host->ports[i] = NULL;
host->n_ports--;
}
}
ide_port_free(hwif);
}
int ide_host_register(struct ide_host *host, const struct ide_port_info *d,
struct ide_hw **hws)
{
ide_hwif_t *hwif, *mate = NULL;
int i, j = 0;
ide_host_for_each_port(i, hwif, host) {
if (hwif == NULL) {
mate = NULL;
continue;
}
ide_init_port_hw(hwif, hws[i]);
ide_port_apply_params(hwif);
if ((i & 1) && mate) {
hwif->mate = mate;
mate->mate = hwif;
}
mate = (i & 1) ? NULL : hwif;
ide_init_port(hwif, i & 1, d);
ide_port_cable_detect(hwif);
hwif->port_flags |= IDE_PFLAG_PROBING;
ide_port_init_devices(hwif);
}
ide_host_for_each_port(i, hwif, host) {
if (hwif == NULL)
continue;
if (ide_probe_port(hwif) == 0)
hwif->present = 1;
hwif->port_flags &= ~IDE_PFLAG_PROBING;
if ((hwif->host_flags & IDE_HFLAG_4DRIVES) == 0 ||
hwif->mate == NULL || hwif->mate->present == 0) {
if (ide_register_port(hwif)) {
ide_disable_port(hwif);
continue;
}
}
if (hwif->present)
ide_port_tune_devices(hwif);
}
ide_host_enable_irqs(host);
ide_host_for_each_port(i, hwif, host) {
if (hwif == NULL)
continue;
if (hwif_init(hwif) == 0) {
printk(KERN_INFO "%s: failed to initialize IDE "
"interface\n", hwif->name);
device_unregister(&hwif->gendev);
ide_disable_port(hwif);
continue;
}
if (hwif->present)
if (ide_port_setup_devices(hwif) == 0) {
hwif->present = 0;
continue;
}
j++;
ide_acpi_init_port(hwif);
if (hwif->present)
ide_acpi_port_init_devices(hwif);
}
ide_host_for_each_port(i, hwif, host) {
if (hwif == NULL)
continue;
ide_sysfs_register_port(hwif);
ide_proc_register_port(hwif);
if (hwif->present) {
ide_proc_port_register_devices(hwif);
hwif_register_devices(hwif);
}
}
return j ? 0 : -1;
}
EXPORT_SYMBOL_GPL(ide_host_register);
int ide_host_add(const struct ide_port_info *d, struct ide_hw **hws,
unsigned int n_ports, struct ide_host **hostp)
{
struct ide_host *host;
int rc;
host = ide_host_alloc(d, hws, n_ports);
if (host == NULL)
return -ENOMEM;
rc = ide_host_register(host, d, hws);
if (rc) {
ide_host_free(host);
return rc;
}
if (hostp)
*hostp = host;
return 0;
}
EXPORT_SYMBOL_GPL(ide_host_add);
static void __ide_port_unregister_devices(ide_hwif_t *hwif)
{
ide_drive_t *drive;
int i;
ide_port_for_each_present_dev(i, drive, hwif) {
device_unregister(&drive->gendev);
wait_for_completion(&drive->gendev_rel_comp);
}
}
void ide_port_unregister_devices(ide_hwif_t *hwif)
{
mutex_lock(&ide_cfg_mtx);
__ide_port_unregister_devices(hwif);
hwif->present = 0;
ide_port_init_devices_data(hwif);
mutex_unlock(&ide_cfg_mtx);
}
EXPORT_SYMBOL_GPL(ide_port_unregister_devices);
/**
* ide_unregister - free an IDE interface
* @hwif: IDE interface
*
* Perform the final unregister of an IDE interface.
*
* Locking:
* The caller must not hold the IDE locks.
*
* It is up to the caller to be sure there is no pending I/O here,
* and that the interface will not be reopened (present/vanishing
* locking isn't yet done BTW).
*/
static void ide_unregister(ide_hwif_t *hwif)
{
BUG_ON(in_interrupt());
BUG_ON(irqs_disabled());
mutex_lock(&ide_cfg_mtx);
if (hwif->present) {
__ide_port_unregister_devices(hwif);
hwif->present = 0;
}
ide_proc_unregister_port(hwif);
free_irq(hwif->irq, hwif);
device_unregister(hwif->portdev);
device_unregister(&hwif->gendev);
wait_for_completion(&hwif->gendev_rel_comp);
/*
* Remove us from the kernel's knowledge
*/
blk_unregister_region(MKDEV(hwif->major, 0), MAX_DRIVES<<PARTN_BITS);
kfree(hwif->sg_table);
unregister_blkdev(hwif->major, hwif->name);
ide_release_dma_engine(hwif);
mutex_unlock(&ide_cfg_mtx);
}
void ide_host_free(struct ide_host *host)
{
ide_hwif_t *hwif;
int i;
ide_host_for_each_port(i, hwif, host) {
if (hwif)
ide_port_free(hwif);
}
kfree(host);
}
EXPORT_SYMBOL_GPL(ide_host_free);
void ide_host_remove(struct ide_host *host)
{
ide_hwif_t *hwif;
int i;
ide_host_for_each_port(i, hwif, host) {
if (hwif)
ide_unregister(hwif);
}
ide_host_free(host);
}
EXPORT_SYMBOL_GPL(ide_host_remove);
void ide_port_scan(ide_hwif_t *hwif)
{
int rc;
ide_port_apply_params(hwif);
ide_port_cable_detect(hwif);
hwif->port_flags |= IDE_PFLAG_PROBING;
ide_port_init_devices(hwif);
rc = ide_probe_port(hwif);
hwif->port_flags &= ~IDE_PFLAG_PROBING;
if (rc < 0)
return;
hwif->present = 1;
ide_port_tune_devices(hwif);
ide_port_setup_devices(hwif);
ide_acpi_port_init_devices(hwif);
hwif_register_devices(hwif);
ide_proc_port_register_devices(hwif);
}
EXPORT_SYMBOL_GPL(ide_port_scan);
| gpl-2.0 |
MpApQ/kernel_huawei | arch/tile/lib/delay.c | 12155 | 1184 | /*
* Copyright 2010 Tilera Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, 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, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for
* more details.
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/thread_info.h>
#include <asm/timex.h>
void __udelay(unsigned long usecs)
{
if (usecs > ULONG_MAX / 1000) {
WARN_ON_ONCE(usecs > ULONG_MAX / 1000);
usecs = ULONG_MAX / 1000;
}
__ndelay(usecs * 1000);
}
EXPORT_SYMBOL(__udelay);
void __ndelay(unsigned long nsecs)
{
cycles_t target = get_cycles();
target += ns2cycles(nsecs);
while (get_cycles() < target)
cpu_relax();
}
EXPORT_SYMBOL(__ndelay);
void __delay(unsigned long cycles)
{
cycles_t target = get_cycles() + cycles;
while (get_cycles() < target)
cpu_relax();
}
EXPORT_SYMBOL(__delay);
| gpl-2.0 |
holyangel/DesireEye | arch/powerpc/boot/mv64x60_i2c.c | 13947 | 5704 | /*
* Bootloader version of the i2c driver for the MV64x60.
*
* Author: Dale Farnsworth <dfarnsworth@mvista.com>
* Maintained by: Mark A. Greer <mgreer@mvista.com>
*
* 2003, 2007 (c) MontaVista, Software, Inc. This file is licensed under
* the terms of the GNU General Public License version 2. This program is
* licensed "as is" without any warranty of any kind, whether express or
* implied.
*/
#include <stdarg.h>
#include <stddef.h>
#include "types.h"
#include "elf.h"
#include "page.h"
#include "string.h"
#include "stdio.h"
#include "io.h"
#include "ops.h"
#include "mv64x60.h"
/* Register defines */
#define MV64x60_I2C_REG_SLAVE_ADDR 0x00
#define MV64x60_I2C_REG_DATA 0x04
#define MV64x60_I2C_REG_CONTROL 0x08
#define MV64x60_I2C_REG_STATUS 0x0c
#define MV64x60_I2C_REG_BAUD 0x0c
#define MV64x60_I2C_REG_EXT_SLAVE_ADDR 0x10
#define MV64x60_I2C_REG_SOFT_RESET 0x1c
#define MV64x60_I2C_CONTROL_ACK 0x04
#define MV64x60_I2C_CONTROL_IFLG 0x08
#define MV64x60_I2C_CONTROL_STOP 0x10
#define MV64x60_I2C_CONTROL_START 0x20
#define MV64x60_I2C_CONTROL_TWSIEN 0x40
#define MV64x60_I2C_CONTROL_INTEN 0x80
#define MV64x60_I2C_STATUS_BUS_ERR 0x00
#define MV64x60_I2C_STATUS_MAST_START 0x08
#define MV64x60_I2C_STATUS_MAST_REPEAT_START 0x10
#define MV64x60_I2C_STATUS_MAST_WR_ADDR_ACK 0x18
#define MV64x60_I2C_STATUS_MAST_WR_ADDR_NO_ACK 0x20
#define MV64x60_I2C_STATUS_MAST_WR_ACK 0x28
#define MV64x60_I2C_STATUS_MAST_WR_NO_ACK 0x30
#define MV64x60_I2C_STATUS_MAST_LOST_ARB 0x38
#define MV64x60_I2C_STATUS_MAST_RD_ADDR_ACK 0x40
#define MV64x60_I2C_STATUS_MAST_RD_ADDR_NO_ACK 0x48
#define MV64x60_I2C_STATUS_MAST_RD_DATA_ACK 0x50
#define MV64x60_I2C_STATUS_MAST_RD_DATA_NO_ACK 0x58
#define MV64x60_I2C_STATUS_MAST_WR_ADDR_2_ACK 0xd0
#define MV64x60_I2C_STATUS_MAST_WR_ADDR_2_NO_ACK 0xd8
#define MV64x60_I2C_STATUS_MAST_RD_ADDR_2_ACK 0xe0
#define MV64x60_I2C_STATUS_MAST_RD_ADDR_2_NO_ACK 0xe8
#define MV64x60_I2C_STATUS_NO_STATUS 0xf8
static u8 *ctlr_base;
static int mv64x60_i2c_wait_for_status(int wanted)
{
int i;
int status;
for (i=0; i<1000; i++) {
udelay(10);
status = in_le32((u32 *)(ctlr_base + MV64x60_I2C_REG_STATUS))
& 0xff;
if (status == wanted)
return status;
}
return -status;
}
static int mv64x60_i2c_control(int control, int status)
{
out_le32((u32 *)(ctlr_base + MV64x60_I2C_REG_CONTROL), control & 0xff);
return mv64x60_i2c_wait_for_status(status);
}
static int mv64x60_i2c_read_byte(int control, int status)
{
out_le32((u32 *)(ctlr_base + MV64x60_I2C_REG_CONTROL), control & 0xff);
if (mv64x60_i2c_wait_for_status(status) < 0)
return -1;
return in_le32((u32 *)(ctlr_base + MV64x60_I2C_REG_DATA)) & 0xff;
}
static int mv64x60_i2c_write_byte(int data, int control, int status)
{
out_le32((u32 *)(ctlr_base + MV64x60_I2C_REG_DATA), data & 0xff);
out_le32((u32 *)(ctlr_base + MV64x60_I2C_REG_CONTROL), control & 0xff);
return mv64x60_i2c_wait_for_status(status);
}
int mv64x60_i2c_read(u32 devaddr, u8 *buf, u32 offset, u32 offset_size,
u32 count)
{
int i;
int data;
int control;
int status;
if (ctlr_base == NULL)
return -1;
/* send reset */
out_le32((u32 *)(ctlr_base + MV64x60_I2C_REG_SOFT_RESET), 0);
out_le32((u32 *)(ctlr_base + MV64x60_I2C_REG_SLAVE_ADDR), 0);
out_le32((u32 *)(ctlr_base + MV64x60_I2C_REG_EXT_SLAVE_ADDR), 0);
out_le32((u32 *)(ctlr_base + MV64x60_I2C_REG_BAUD), (4 << 3) | 0x4);
if (mv64x60_i2c_control(MV64x60_I2C_CONTROL_TWSIEN,
MV64x60_I2C_STATUS_NO_STATUS) < 0)
return -1;
/* send start */
control = MV64x60_I2C_CONTROL_START | MV64x60_I2C_CONTROL_TWSIEN;
status = MV64x60_I2C_STATUS_MAST_START;
if (mv64x60_i2c_control(control, status) < 0)
return -1;
/* select device for writing */
data = devaddr & ~0x1;
control = MV64x60_I2C_CONTROL_TWSIEN;
status = MV64x60_I2C_STATUS_MAST_WR_ADDR_ACK;
if (mv64x60_i2c_write_byte(data, control, status) < 0)
return -1;
/* send offset of data */
control = MV64x60_I2C_CONTROL_TWSIEN;
status = MV64x60_I2C_STATUS_MAST_WR_ACK;
if (offset_size > 1) {
if (mv64x60_i2c_write_byte(offset >> 8, control, status) < 0)
return -1;
}
if (mv64x60_i2c_write_byte(offset, control, status) < 0)
return -1;
/* resend start */
control = MV64x60_I2C_CONTROL_START | MV64x60_I2C_CONTROL_TWSIEN;
status = MV64x60_I2C_STATUS_MAST_REPEAT_START;
if (mv64x60_i2c_control(control, status) < 0)
return -1;
/* select device for reading */
data = devaddr | 0x1;
control = MV64x60_I2C_CONTROL_TWSIEN;
status = MV64x60_I2C_STATUS_MAST_RD_ADDR_ACK;
if (mv64x60_i2c_write_byte(data, control, status) < 0)
return -1;
/* read all but last byte of data */
control = MV64x60_I2C_CONTROL_ACK | MV64x60_I2C_CONTROL_TWSIEN;
status = MV64x60_I2C_STATUS_MAST_RD_DATA_ACK;
for (i=1; i<count; i++) {
data = mv64x60_i2c_read_byte(control, status);
if (data < 0) {
printf("errors on iteration %d\n", i);
return -1;
}
*buf++ = data;
}
/* read last byte of data */
control = MV64x60_I2C_CONTROL_TWSIEN;
status = MV64x60_I2C_STATUS_MAST_RD_DATA_NO_ACK;
data = mv64x60_i2c_read_byte(control, status);
if (data < 0)
return -1;
*buf++ = data;
/* send stop */
control = MV64x60_I2C_CONTROL_STOP | MV64x60_I2C_CONTROL_TWSIEN;
status = MV64x60_I2C_STATUS_NO_STATUS;
if (mv64x60_i2c_control(control, status) < 0)
return -1;
return count;
}
int mv64x60_i2c_open(void)
{
u32 v;
void *devp;
devp = find_node_by_compatible(NULL, "marvell,mv64360-i2c");
if (devp == NULL)
goto err_out;
if (getprop(devp, "virtual-reg", &v, sizeof(v)) != sizeof(v))
goto err_out;
ctlr_base = (u8 *)v;
return 0;
err_out:
return -1;
}
void mv64x60_i2c_close(void)
{
ctlr_base = NULL;
}
| gpl-2.0 |
OliverG96/android_kernel_samsung_golden | arch/arm/mach-ux500/pm/context-db9540.c | 124 | 24285 | /*
* Copyright (C) STMicroelectronics 2009
* Copyright (C) ST-Ericsson SA 2010-2011
*
* License Terms: GNU General Public License v2
* Author: Sundar Iyer for ST-Ericsson
*
*/
#include <linux/io.h>
#include <mach/hardware.h>
#include <mach/context.h>
/*
* ST-Interconnect context
*/
/* priority, bw limiter register offsets */
#define NODE_HIBW1_ESRAM_IN_0_PRIORITY 0x00
#define NODE_HIBW1_ESRAM_IN_1_PRIORITY 0x04
#define NODE_HIBW1_ESRAM_IN_2_PRIORITY 0x08
#define NODE_HIBW1_ESRAM_IN_3_PRIORITY 0x0C
#define NODE_HIBW1_ESRAM_IN_0_ARB_1_LIMIT 0x30
#define NODE_HIBW1_ESRAM_IN_0_ARB_2_LIMIT 0x34
#define NODE_HIBW1_ESRAM_IN_0_ARB_3_LIMIT 0x38
#define NODE_HIBW1_ESRAM_IN_1_ARB_1_LIMIT 0x3C
#define NODE_HIBW1_ESRAM_IN_1_ARB_2_LIMIT 0x40
#define NODE_HIBW1_ESRAM_IN_1_ARB_3_LIMIT 0x44
#define NODE_HIBW1_ESRAM_IN_2_ARB_1_LIMIT 0x48
#define NODE_HIBW1_ESRAM_IN_2_ARB_2_LIMIT 0x4C
#define NODE_HIBW1_ESRAM_IN_2_ARB_3_LIMIT 0x50
#define NODE_HIBW1_ESRAM_IN_3_ARB_1_LIMIT 0x54
#define NODE_HIBW1_ESRAM_IN_3_ARB_2_LIMIT 0x58
#define NODE_HIBW1_ESRAM_IN_3_ARB_3_LIMIT 0x5C
#define NODE_HIBW1_DDR0_IN_0_PRIORITY 0x400
#define NODE_HIBW1_DDR0_IN_1_PRIORITY 0x404
#define NODE_HIBW1_DDR0_IN_2_PRIORITY 0x408
#define NODE_HIBW1_DDR0_IN_3_PRIORITY 0x40C
#define NODE_HIBW1_DDR0_IN_0_LIMIT 0x430
#define NODE_HIBW1_DDR0_IN_1_LIMIT 0x434
#define NODE_HIBW1_DDR0_IN_2_LIMIT 0x438
#define NODE_HIBW1_DDR0_IN_3_LIMIT 0x43C
#define NODE_HIBW1_DDR0_OUT_0_PRIORITY 0x440
#define NODE_HIBW2_ESRAM_IN_0_PRIORITY 0x800
#define NODE_HIBW2_ESRAM_IN_1_PRIORITY 0x804
#define NODE_HIBW2_ESRAM_IN_0_ARB_1_LIMIT 0x818
#define NODE_HIBW2_ESRAM_IN_0_ARB_2_LIMIT 0x81C
#define NODE_HIBW2_ESRAM_IN_0_ARB_3_LIMIT 0x820
#define NODE_HIBW2_ESRAM_IN_1_ARB_1_LIMIT 0x824
#define NODE_HIBW2_ESRAM_IN_1_ARB_2_LIMIT 0x828
#define NODE_HIBW2_ESRAM_IN_1_ARB_3_LIMIT 0x82C
#define NODE_HIBW2_DDR0_IN_0_PRIORITY 0xC00
#define NODE_HIBW2_DDR0_IN_1_PRIORITY 0xC04
#define NODE_HIBW2_DDR0_IN_0_LIMIT 0xC18
#define NODE_HIBW2_DDR0_IN_1_LIMIT 0xC1C
#define NODE_HIBW2_DDR0_OUT_0_PRIORITY 0xC20
/*
* Note the following addresses are presented in
* db8500 design spec v3.1 and v3.3, table 10.
* But their addresses are not the same as in the
* description. The addresses in the description
* of each registers are correct.
* NODE_HIBW2_DDR_IN_3_LIMIT is only present in v1.
*
* Faulty registers addresses in table 10:
* NODE_HIBW2_DDR_IN_2_LIMIT 0xC38
* NODE_HIBW2_DDR_IN_3_LIMIT 0xC3C
* NODE_HIBW2_DDR_OUT_0_PRIORITY 0xC40
*/
#define NODE_ESRAM0_IN_0_PRIORITY 0x1000
#define NODE_ESRAM0_IN_1_PRIORITY 0x1004
#define NODE_ESRAM0_IN_2_PRIORITY 0x1008
#define NODE_ESRAM0_IN_3_PRIORITY 0x100C
#define NODE_ESRAM0_IN_0_LIMIT 0x1030
#define NODE_ESRAM0_IN_1_LIMIT 0x1034
#define NODE_ESRAM0_IN_2_LIMIT 0x1038
#define NODE_ESRAM0_IN_3_LIMIT 0x103C
#define NODE_ESRAM0_OUT_0_PRIORITY 0x1040
/* common */
#define NODE_ESRAM1_2_IN_0_PRIORITY 0x1400
#define NODE_ESRAM1_2_IN_1_PRIORITY 0x1404
#define NODE_ESRAM1_2_IN_2_PRIORITY 0x1408
#define NODE_ESRAM1_2_IN_3_PRIORITY 0x140C
#define NODE_ESRAM1_2_IN_0_ARB_1_LIMIT 0x1430
#define NODE_ESRAM1_2_IN_0_ARB_2_LIMIT 0x1434
#define NODE_ESRAM1_2_IN_1_ARB_1_LIMIT 0x1438
#define NODE_ESRAM1_2_IN_1_ARB_2_LIMIT 0x143C
#define NODE_ESRAM1_2_IN_2_ARB_1_LIMIT 0x1440
#define NODE_ESRAM1_2_IN_2_ARB_2_LIMIT 0x1444
#define NODE_ESRAM1_2_IN_3_ARB_1_LIMIT 0x1448
#define NODE_ESRAM1_2_IN_3_ARB_2_LIMIT 0x144C
#define NODE_ESRAM3_4_IN_0_PRIORITY 0x1800
#define NODE_ESRAM3_4_IN_1_PRIORITY 0x1804
#define NODE_ESRAM3_4_IN_2_PRIORITY 0x1808
#define NODE_ESRAM3_4_IN_3_PRIORITY 0x180C
#define NODE_ESRAM3_4_IN_0_ARB_1_LIMIT 0x1830
#define NODE_ESRAM3_4_IN_0_ARB_2_LIMIT 0x1834
#define NODE_ESRAM3_4_IN_1_ARB_1_LIMIT 0x1838
#define NODE_ESRAM3_4_IN_1_ARB_2_LIMIT 0x183C
#define NODE_ESRAM3_4_IN_2_ARB_1_LIMIT 0x1840
#define NODE_ESRAM3_4_IN_2_ARB_2_LIMIT 0x1844
#define NODE_ESRAM3_4_IN_3_ARB_1_LIMIT 0x1848
#define NODE_ESRAM3_4_IN_3_ARB_2_LIMIT 0x184C
#define NODE_HIBW1_DDR1_IN_0_PRIORITY_REG 0x1C00
#define NODE_HIBW1_DDR1_IN_1_PRIORITY_REG 0x1C04
#define NODE_HIBW1_DDR1_IN_2_PRIORITY_REG 0x1C08
#define NODE_HIBW1_DDR1_IN_3_PRIORITY_REG 0x1C0C
#define NODE_HIBW1_DDR1_IN_0_LIMIT_REG 0x1C30
#define NODE_HIBW1_DDR1_IN_1_LIMIT_REG 0x1C34
#define NODE_HIBW1_DDR1_IN_2_LIMIT_REG 0x1C38
#define NODE_HIBW1_DDR1_IN_3_LIMIT_REG 0x1C3C
#define NODE_HIBW1_DDR1_OUT_0_PRIORITY_REG 0x1C40
#define NODE_HIBW2_DDR1_IN_0_PRIORITY_REG 0x2000
#define NODE_HIBW2_DDR1_IN_1_PRIORITY_REG 0x2004
#define NODE_HIBW2_DDR1_IN_0_LIMIT_REG 0x2018
#define NODE_HIBW2_DDR1_IN_1_LIMIT_REG 0x201C
#define NODE_HIBW2_DDR1_OUT_0_PRIORITY_REG 0x2020
#define NODE_DDR_AWQOS_DSP_DDR0_REG 0x340C
#define NODE_DDR_AWQOS_DSP_DDR1_REG 0x3400
#define NODE_DDR_ARQOS_DSP_DDR0_REG 0x3408
#define NODE_DDR_ARQOS_DSP_DDR1_REG 0x3404
#define NODE_DDR_AWQOS_ARM_DDR_REG 0x3410
#define NODE_DDR_ARQOS_ARM_DDR_REG 0x3414
#define NODE_SGA_AWQOS_DDR0_HIBW2_REG 0x3418
#define NODE_SGA_ARQOS_DDR0_HIBW2_REG 0x341C
#define NODE_SGA_AWQOS_SGA_HIBW2_REG 0x3420
#define NODE_SGA_ARQOS_SGA_HIBW2_REG 0x3424
static struct {
void __iomem *base;
u32 hibw1_esram_in_pri[4];
u32 hibw1_esram_in0_arb[3];
u32 hibw1_esram_in1_arb[3];
u32 hibw1_esram_in2_arb[3];
u32 hibw1_esram_in3_arb[3];
u32 hibw1_ddr0_in_prio[4];
u32 hibw1_ddr0_in_limit[4];
u32 hibw1_ddr0_out_prio;
u32 hibw1_ddr1_in_prio[4];
u32 hibw1_ddr1_in_limit[4];
u32 hibw1_ddr1_out_prio;
/* HiBw2 node registers */
u32 hibw2_esram_in_pri[2];
u32 hibw2_esram_in0_arblimit[3];
u32 hibw2_esram_in1_arblimit[3];
u32 hibw2_ddr0_in_prio[2];
u32 hibw2_ddr0_in_limit[2];
u32 hibw2_ddr0_out_prio;
u32 hibw2_ddr1_in_prio[2];
u32 hibw2_ddr1_in_limit[2];
u32 hibw2_ddr1_out_prio;
/* ESRAM node registers */
u32 esram0_in_prio[4];
u32 esram0_in_lim[4];
u32 esram0_out_prio;
u32 esram12_in_prio[4];
u32 esram12_in_arb_lim[8];
u32 esram34_in_prio[4];
u32 esram34_in_arb_lim[8];
u32 ddr_awqos_dsp_ddr0;
u32 ddr_awqos_dsp_ddr1;
u32 ddr_arqos_dsp_ddr0;
u32 ddr_arqos_dsp_ddr1;
u32 ddr_awqos_arm_ddr;
u32 ddr_arqos_arm_ddr;
u32 sga_awqos_ddr0_hibw2;
u32 sga_arqos_ddr0_hibw2;
u32 sga_awqos_sga_hibw2;
u32 sga_arqos_sga_hibw2;
} context_icn;
/**
* u8500_context_save_icn() - save ICN context
*
*/
void u9540_context_save_icn(void)
{
void __iomem *b = context_icn.base;
context_icn.hibw1_esram_in_pri[0] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_0_PRIORITY);
context_icn.hibw1_esram_in_pri[1] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_1_PRIORITY);
context_icn.hibw1_esram_in_pri[2] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_2_PRIORITY);
context_icn.hibw1_esram_in_pri[3] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_3_PRIORITY);
context_icn.hibw1_esram_in0_arb[0] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_0_ARB_1_LIMIT);
context_icn.hibw1_esram_in0_arb[1] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_0_ARB_2_LIMIT);
context_icn.hibw1_esram_in0_arb[2] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_0_ARB_3_LIMIT);
context_icn.hibw1_esram_in1_arb[0] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_1_ARB_1_LIMIT);
context_icn.hibw1_esram_in1_arb[1] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_1_ARB_2_LIMIT);
context_icn.hibw1_esram_in1_arb[2] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_1_ARB_3_LIMIT);
context_icn.hibw1_esram_in2_arb[0] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_2_ARB_1_LIMIT);
context_icn.hibw1_esram_in2_arb[1] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_2_ARB_2_LIMIT);
context_icn.hibw1_esram_in2_arb[2] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_2_ARB_3_LIMIT);
context_icn.hibw1_esram_in3_arb[0] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_3_ARB_1_LIMIT);
context_icn.hibw1_esram_in3_arb[1] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_3_ARB_2_LIMIT);
context_icn.hibw1_esram_in3_arb[2] =
readl_relaxed(b + NODE_HIBW1_ESRAM_IN_3_ARB_3_LIMIT);
context_icn.hibw1_ddr0_in_prio[0] =
readl_relaxed(b + NODE_HIBW1_DDR0_IN_0_PRIORITY);
context_icn.hibw1_ddr0_in_prio[1] =
readl_relaxed(b + NODE_HIBW1_DDR0_IN_1_PRIORITY);
context_icn.hibw1_ddr0_in_prio[2] =
readl_relaxed(b + NODE_HIBW1_DDR0_IN_2_PRIORITY);
context_icn.hibw1_ddr0_in_prio[3] =
readl_relaxed(b + NODE_HIBW1_DDR0_IN_3_PRIORITY);
context_icn.hibw1_ddr0_in_limit[0] =
readl_relaxed(b + NODE_HIBW1_DDR0_IN_0_LIMIT);
context_icn.hibw1_ddr0_in_limit[1] =
readl_relaxed(b + NODE_HIBW1_DDR0_IN_1_LIMIT);
context_icn.hibw1_ddr0_in_limit[2] =
readl_relaxed(b + NODE_HIBW1_DDR0_IN_2_LIMIT);
context_icn.hibw1_ddr0_in_limit[3] =
readl_relaxed(b + NODE_HIBW1_DDR0_IN_3_LIMIT);
context_icn.hibw1_ddr0_out_prio =
readl_relaxed(b + NODE_HIBW1_DDR0_OUT_0_PRIORITY);
context_icn.hibw1_ddr1_in_prio[0] =
readl_relaxed(b + NODE_HIBW1_DDR1_IN_0_PRIORITY_REG);
context_icn.hibw1_ddr1_in_prio[1] =
readl_relaxed(b + NODE_HIBW1_DDR1_IN_1_PRIORITY_REG);
context_icn.hibw1_ddr1_in_prio[2] =
readl_relaxed(b + NODE_HIBW1_DDR1_IN_2_PRIORITY_REG);
context_icn.hibw1_ddr1_in_prio[3] =
readl_relaxed(b + NODE_HIBW1_DDR1_IN_3_PRIORITY_REG);
context_icn.hibw1_ddr1_in_limit[0] =
readl_relaxed(b + NODE_HIBW1_DDR1_IN_0_LIMIT_REG);
context_icn.hibw1_ddr1_in_limit[1] =
readl_relaxed(b + NODE_HIBW1_DDR1_IN_1_LIMIT_REG);
context_icn.hibw1_ddr1_in_limit[2] =
readl_relaxed(b + NODE_HIBW1_DDR1_IN_2_LIMIT_REG);
context_icn.hibw1_ddr1_in_limit[3] =
readl_relaxed(b + NODE_HIBW1_DDR1_IN_3_LIMIT_REG);
context_icn.hibw1_ddr1_out_prio =
readl_relaxed(b + NODE_HIBW1_DDR1_OUT_0_PRIORITY_REG);
context_icn.hibw2_esram_in_pri[0] =
readl_relaxed(b + NODE_HIBW2_ESRAM_IN_0_PRIORITY);
context_icn.hibw2_esram_in_pri[1] =
readl_relaxed(b + NODE_HIBW2_ESRAM_IN_1_PRIORITY);
context_icn.hibw2_esram_in0_arblimit[0] =
readl_relaxed(b + NODE_HIBW2_ESRAM_IN_0_ARB_1_LIMIT);
context_icn.hibw2_esram_in0_arblimit[1] =
readl_relaxed(b + NODE_HIBW2_ESRAM_IN_0_ARB_2_LIMIT);
context_icn.hibw2_esram_in0_arblimit[2] =
readl_relaxed(b + NODE_HIBW2_ESRAM_IN_0_ARB_3_LIMIT);
context_icn.hibw2_esram_in1_arblimit[0] =
readl_relaxed(b + NODE_HIBW2_ESRAM_IN_1_ARB_1_LIMIT);
context_icn.hibw2_esram_in1_arblimit[1] =
readl_relaxed(b + NODE_HIBW2_ESRAM_IN_1_ARB_2_LIMIT);
context_icn.hibw2_esram_in1_arblimit[2] =
readl_relaxed(b + NODE_HIBW2_ESRAM_IN_1_ARB_3_LIMIT);
context_icn.hibw2_ddr0_in_prio[0] =
readl_relaxed(b + NODE_HIBW2_DDR0_IN_0_PRIORITY);
context_icn.hibw2_ddr0_in_prio[1] =
readl_relaxed(b + NODE_HIBW2_DDR0_IN_1_PRIORITY);
context_icn.hibw2_ddr0_in_limit[0] =
readl_relaxed(b + NODE_HIBW2_DDR0_IN_0_LIMIT);
context_icn.hibw2_ddr0_in_limit[1] =
readl_relaxed(b + NODE_HIBW2_DDR0_IN_1_LIMIT);
context_icn.hibw2_ddr0_out_prio =
readl_relaxed(b + NODE_HIBW2_DDR0_OUT_0_PRIORITY);
context_icn.hibw2_ddr1_in_prio[0] =
readl_relaxed(b + NODE_HIBW2_DDR1_IN_0_PRIORITY_REG);
context_icn.hibw2_ddr1_in_prio[1] =
readl_relaxed(b + NODE_HIBW2_DDR1_IN_1_PRIORITY_REG);
context_icn.hibw2_ddr1_in_limit[0] =
readl_relaxed(b + NODE_HIBW2_DDR1_IN_0_LIMIT_REG);
context_icn.hibw2_ddr1_in_limit[1] =
readl_relaxed(b + NODE_HIBW2_DDR1_IN_1_LIMIT_REG);
context_icn.hibw2_ddr1_out_prio =
readl_relaxed(b + NODE_HIBW2_DDR1_OUT_0_PRIORITY_REG);
context_icn.esram0_in_prio[0] =
readl_relaxed(b + NODE_ESRAM0_IN_0_PRIORITY);
context_icn.esram0_in_prio[1] =
readl_relaxed(b + NODE_ESRAM0_IN_1_PRIORITY);
context_icn.esram0_in_prio[2] =
readl_relaxed(b + NODE_ESRAM0_IN_2_PRIORITY);
context_icn.esram0_in_prio[3] =
readl_relaxed(b + NODE_ESRAM0_IN_3_PRIORITY);
context_icn.esram0_in_lim[0] =
readl_relaxed(b + NODE_ESRAM0_IN_0_LIMIT);
context_icn.esram0_in_lim[1] =
readl_relaxed(b + NODE_ESRAM0_IN_1_LIMIT);
context_icn.esram0_in_lim[2] =
readl_relaxed(b + NODE_ESRAM0_IN_2_LIMIT);
context_icn.esram0_in_lim[3] =
readl_relaxed(b + NODE_ESRAM0_IN_3_LIMIT);
context_icn.esram0_out_prio =
readl_relaxed(b + NODE_ESRAM0_OUT_0_PRIORITY);
context_icn.esram12_in_prio[0] =
readl_relaxed(b + NODE_ESRAM1_2_IN_0_PRIORITY);
context_icn.esram12_in_prio[1] =
readl_relaxed(b + NODE_ESRAM1_2_IN_1_PRIORITY);
context_icn.esram12_in_prio[2] =
readl_relaxed(b + NODE_ESRAM1_2_IN_2_PRIORITY);
context_icn.esram12_in_prio[3] =
readl_relaxed(b + NODE_ESRAM1_2_IN_3_PRIORITY);
context_icn.esram12_in_arb_lim[0] =
readl_relaxed(b + NODE_ESRAM1_2_IN_0_ARB_1_LIMIT);
context_icn.esram12_in_arb_lim[1] =
readl_relaxed(b + NODE_ESRAM1_2_IN_0_ARB_2_LIMIT);
context_icn.esram12_in_arb_lim[2] =
readl_relaxed(b + NODE_ESRAM1_2_IN_1_ARB_1_LIMIT);
context_icn.esram12_in_arb_lim[3] =
readl_relaxed(b + NODE_ESRAM1_2_IN_1_ARB_2_LIMIT);
context_icn.esram12_in_arb_lim[4] =
readl_relaxed(b + NODE_ESRAM1_2_IN_2_ARB_1_LIMIT);
context_icn.esram12_in_arb_lim[5] =
readl_relaxed(b + NODE_ESRAM1_2_IN_2_ARB_2_LIMIT);
context_icn.esram12_in_arb_lim[6] =
readl_relaxed(b + NODE_ESRAM1_2_IN_3_ARB_1_LIMIT);
context_icn.esram12_in_arb_lim[7] =
readl_relaxed(b + NODE_ESRAM1_2_IN_3_ARB_2_LIMIT);
context_icn.esram34_in_prio[0] =
readl_relaxed(b + NODE_ESRAM3_4_IN_0_PRIORITY);
context_icn.esram34_in_prio[1] =
readl_relaxed(b + NODE_ESRAM3_4_IN_1_PRIORITY);
context_icn.esram34_in_prio[2] =
readl_relaxed(b + NODE_ESRAM3_4_IN_2_PRIORITY);
context_icn.esram34_in_prio[3] =
readl_relaxed(b + NODE_ESRAM3_4_IN_3_PRIORITY);
context_icn.esram34_in_arb_lim[0] =
readl_relaxed(b + NODE_ESRAM3_4_IN_0_ARB_1_LIMIT);
context_icn.esram34_in_arb_lim[1] =
readl_relaxed(b + NODE_ESRAM3_4_IN_0_ARB_2_LIMIT);
context_icn.esram34_in_arb_lim[2] =
readl_relaxed(b + NODE_ESRAM3_4_IN_1_ARB_1_LIMIT);
context_icn.esram34_in_arb_lim[3] =
readl_relaxed(b + NODE_ESRAM3_4_IN_1_ARB_2_LIMIT);
context_icn.esram34_in_arb_lim[4] =
readl_relaxed(b + NODE_ESRAM3_4_IN_2_ARB_1_LIMIT);
context_icn.esram34_in_arb_lim[5] =
readl_relaxed(b + NODE_ESRAM3_4_IN_2_ARB_2_LIMIT);
context_icn.esram34_in_arb_lim[6] =
readl_relaxed(b + NODE_ESRAM3_4_IN_3_ARB_1_LIMIT);
context_icn.esram34_in_arb_lim[7] =
readl_relaxed(b + NODE_ESRAM3_4_IN_3_ARB_2_LIMIT);
context_icn.ddr_awqos_dsp_ddr0 =
readl_relaxed(b + NODE_DDR_AWQOS_DSP_DDR0_REG);
context_icn.ddr_awqos_dsp_ddr1 =
readl_relaxed(b + NODE_DDR_AWQOS_DSP_DDR1_REG);
context_icn.ddr_arqos_dsp_ddr0 =
readl_relaxed(b + NODE_DDR_ARQOS_DSP_DDR0_REG);
context_icn.ddr_arqos_dsp_ddr1 =
readl_relaxed(b + NODE_DDR_ARQOS_DSP_DDR1_REG);
context_icn.ddr_awqos_arm_ddr =
readl_relaxed(b + NODE_DDR_AWQOS_ARM_DDR_REG);
context_icn.ddr_arqos_arm_ddr =
readl_relaxed(b + NODE_DDR_ARQOS_ARM_DDR_REG);
context_icn.sga_awqos_ddr0_hibw2 =
readl_relaxed(b + NODE_SGA_AWQOS_DDR0_HIBW2_REG);
context_icn.sga_arqos_ddr0_hibw2 =
readl_relaxed(b + NODE_SGA_ARQOS_DDR0_HIBW2_REG);
context_icn.sga_awqos_sga_hibw2 =
readl_relaxed(b + NODE_SGA_AWQOS_SGA_HIBW2_REG);
context_icn.sga_arqos_sga_hibw2 =
readl_relaxed(b + NODE_SGA_ARQOS_SGA_HIBW2_REG);
}
/**
* u9540_context_restore_icn() - restore ICN context
*
*/
void u9540_context_restore_icn(void)
{
void __iomem *b = context_icn.base;
writel_relaxed(context_icn.hibw1_esram_in_pri[0],
b + NODE_HIBW1_ESRAM_IN_0_PRIORITY);
writel_relaxed(context_icn.hibw1_esram_in_pri[1],
b + NODE_HIBW1_ESRAM_IN_1_PRIORITY);
writel_relaxed(context_icn.hibw1_esram_in_pri[2],
b + NODE_HIBW1_ESRAM_IN_2_PRIORITY);
writel_relaxed(context_icn.hibw1_esram_in_pri[3],
b + NODE_HIBW1_ESRAM_IN_3_PRIORITY);
writel_relaxed(context_icn.hibw1_esram_in0_arb[0],
b + NODE_HIBW1_ESRAM_IN_0_ARB_1_LIMIT);
writel_relaxed(context_icn.hibw1_esram_in0_arb[1],
b + NODE_HIBW1_ESRAM_IN_0_ARB_2_LIMIT);
writel_relaxed(context_icn.hibw1_esram_in0_arb[2],
b + NODE_HIBW1_ESRAM_IN_0_ARB_3_LIMIT);
writel_relaxed(context_icn.hibw1_esram_in1_arb[0],
b + NODE_HIBW1_ESRAM_IN_1_ARB_1_LIMIT);
writel_relaxed(context_icn.hibw1_esram_in1_arb[1],
b + NODE_HIBW1_ESRAM_IN_1_ARB_2_LIMIT);
writel_relaxed(context_icn.hibw1_esram_in1_arb[2],
b + NODE_HIBW1_ESRAM_IN_1_ARB_3_LIMIT);
writel_relaxed(context_icn.hibw1_esram_in2_arb[0],
b + NODE_HIBW1_ESRAM_IN_2_ARB_1_LIMIT);
writel_relaxed(context_icn.hibw1_esram_in2_arb[1],
b + NODE_HIBW1_ESRAM_IN_2_ARB_2_LIMIT);
writel_relaxed(context_icn.hibw1_esram_in2_arb[2],
b + NODE_HIBW1_ESRAM_IN_2_ARB_3_LIMIT);
writel_relaxed(context_icn.hibw1_esram_in3_arb[0],
b + NODE_HIBW1_ESRAM_IN_3_ARB_1_LIMIT);
writel_relaxed(context_icn.hibw1_esram_in3_arb[1],
b + NODE_HIBW1_ESRAM_IN_3_ARB_2_LIMIT);
writel_relaxed(context_icn.hibw1_esram_in3_arb[2],
b + NODE_HIBW1_ESRAM_IN_3_ARB_3_LIMIT);
writel_relaxed(context_icn.hibw1_ddr0_in_prio[0],
b + NODE_HIBW1_DDR0_IN_0_PRIORITY);
writel_relaxed(context_icn.hibw1_ddr0_in_prio[1],
b + NODE_HIBW1_DDR0_IN_1_PRIORITY);
writel_relaxed(context_icn.hibw1_ddr0_in_prio[2],
b + NODE_HIBW1_DDR0_IN_2_PRIORITY);
writel_relaxed(context_icn.hibw1_ddr0_in_prio[3],
b + NODE_HIBW1_DDR0_IN_3_PRIORITY);
writel_relaxed(context_icn.hibw1_ddr0_in_limit[0],
b + NODE_HIBW1_DDR0_IN_0_LIMIT);
writel_relaxed(context_icn.hibw1_ddr0_in_limit[1],
b + NODE_HIBW1_DDR0_IN_1_LIMIT);
writel_relaxed(context_icn.hibw1_ddr0_in_limit[2],
b + NODE_HIBW1_DDR0_IN_2_LIMIT);
writel_relaxed(context_icn.hibw1_ddr0_in_limit[3],
b + NODE_HIBW1_DDR0_IN_3_LIMIT);
writel_relaxed(context_icn.hibw1_ddr0_out_prio,
b + NODE_HIBW1_DDR0_OUT_0_PRIORITY);
writel_relaxed(context_icn.hibw1_ddr1_in_prio[0],
b + NODE_HIBW1_DDR1_IN_0_PRIORITY_REG);
writel_relaxed(context_icn.hibw1_ddr1_in_prio[1],
b + NODE_HIBW1_DDR1_IN_1_PRIORITY_REG);
writel_relaxed(context_icn.hibw1_ddr1_in_prio[2],
b + NODE_HIBW1_DDR1_IN_2_PRIORITY_REG);
writel_relaxed(context_icn.hibw1_ddr1_in_prio[3],
b + NODE_HIBW1_DDR1_IN_3_PRIORITY_REG);
writel_relaxed(context_icn.hibw1_ddr1_in_limit[0],
b + NODE_HIBW1_DDR1_IN_0_LIMIT_REG);
writel_relaxed(context_icn.hibw1_ddr1_in_limit[1],
b + NODE_HIBW1_DDR1_IN_1_LIMIT_REG);
writel_relaxed(context_icn.hibw1_ddr1_in_limit[2],
b + NODE_HIBW1_DDR1_IN_2_LIMIT_REG);
writel_relaxed(context_icn.hibw1_ddr1_in_limit[3],
b + NODE_HIBW1_DDR1_IN_3_LIMIT_REG);
writel_relaxed(context_icn.hibw1_ddr1_out_prio,
b + NODE_HIBW1_DDR1_OUT_0_PRIORITY_REG);
writel_relaxed(context_icn.hibw2_esram_in_pri[0],
b + NODE_HIBW2_ESRAM_IN_0_PRIORITY);
writel_relaxed(context_icn.hibw2_esram_in_pri[1],
b + NODE_HIBW2_ESRAM_IN_1_PRIORITY);
writel_relaxed(context_icn.hibw2_esram_in0_arblimit[0],
b + NODE_HIBW2_ESRAM_IN_0_ARB_1_LIMIT);
writel_relaxed(context_icn.hibw2_esram_in0_arblimit[1],
b + NODE_HIBW2_ESRAM_IN_0_ARB_2_LIMIT);
writel_relaxed(context_icn.hibw2_esram_in0_arblimit[2],
b + NODE_HIBW2_ESRAM_IN_0_ARB_3_LIMIT);
writel_relaxed(context_icn.hibw2_esram_in1_arblimit[0],
b + NODE_HIBW2_ESRAM_IN_1_ARB_1_LIMIT);
writel_relaxed(context_icn.hibw2_esram_in1_arblimit[1],
b + NODE_HIBW2_ESRAM_IN_1_ARB_2_LIMIT);
writel_relaxed(context_icn.hibw2_esram_in1_arblimit[2],
b + NODE_HIBW2_ESRAM_IN_1_ARB_3_LIMIT);
writel_relaxed(context_icn.hibw2_ddr0_in_prio[0],
b + NODE_HIBW2_DDR0_IN_0_PRIORITY);
writel_relaxed(context_icn.hibw2_ddr0_in_prio[1],
b + NODE_HIBW2_DDR0_IN_1_PRIORITY);
writel_relaxed(context_icn.hibw2_ddr0_in_limit[0],
b + NODE_HIBW2_DDR0_IN_0_LIMIT);
writel_relaxed(context_icn.hibw2_ddr0_in_limit[1],
b + NODE_HIBW2_DDR0_IN_1_LIMIT);
writel_relaxed(context_icn.hibw2_ddr0_out_prio,
b + NODE_HIBW2_DDR0_OUT_0_PRIORITY);
writel_relaxed(context_icn.hibw2_ddr1_in_prio[0],
b + NODE_HIBW2_DDR1_IN_0_PRIORITY_REG);
writel_relaxed(context_icn.hibw2_ddr1_in_prio[1],
b + NODE_HIBW2_DDR1_IN_1_PRIORITY_REG);
writel_relaxed(context_icn.hibw2_ddr1_in_limit[0],
b + NODE_HIBW2_DDR1_IN_0_LIMIT_REG);
writel_relaxed(context_icn.hibw2_ddr1_in_limit[1],
b + NODE_HIBW2_DDR1_IN_1_LIMIT_REG);
writel_relaxed(context_icn.hibw2_ddr1_out_prio,
b + NODE_HIBW2_DDR1_OUT_0_PRIORITY_REG);
writel_relaxed(context_icn.esram0_in_prio[0],
b + NODE_ESRAM0_IN_0_PRIORITY);
writel_relaxed(context_icn.esram0_in_prio[1],
b + NODE_ESRAM0_IN_1_PRIORITY);
writel_relaxed(context_icn.esram0_in_prio[2],
b + NODE_ESRAM0_IN_2_PRIORITY);
writel_relaxed(context_icn.esram0_in_prio[3],
b + NODE_ESRAM0_IN_3_PRIORITY);
writel_relaxed(context_icn.esram0_in_lim[0],
b + NODE_ESRAM0_IN_0_LIMIT);
writel_relaxed(context_icn.esram0_in_lim[1],
b + NODE_ESRAM0_IN_1_LIMIT);
writel_relaxed(context_icn.esram0_in_lim[2],
b + NODE_ESRAM0_IN_2_LIMIT);
writel_relaxed(context_icn.esram0_in_lim[3],
b + NODE_ESRAM0_IN_3_LIMIT);
writel_relaxed(context_icn.esram0_out_prio,
b + NODE_ESRAM0_OUT_0_PRIORITY);
writel_relaxed(context_icn.esram12_in_prio[0],
b + NODE_ESRAM1_2_IN_0_PRIORITY);
writel_relaxed(context_icn.esram12_in_prio[1],
b + NODE_ESRAM1_2_IN_1_PRIORITY);
writel_relaxed(context_icn.esram12_in_prio[2],
b + NODE_ESRAM1_2_IN_2_PRIORITY);
writel_relaxed(context_icn.esram12_in_prio[3],
b + NODE_ESRAM1_2_IN_3_PRIORITY);
writel_relaxed(context_icn.esram12_in_arb_lim[0],
b + NODE_ESRAM1_2_IN_0_ARB_1_LIMIT);
writel_relaxed(context_icn.esram12_in_arb_lim[1],
b + NODE_ESRAM1_2_IN_0_ARB_2_LIMIT);
writel_relaxed(context_icn.esram12_in_arb_lim[2],
b + NODE_ESRAM1_2_IN_1_ARB_1_LIMIT);
writel_relaxed(context_icn.esram12_in_arb_lim[3],
b + NODE_ESRAM1_2_IN_1_ARB_2_LIMIT);
writel_relaxed(context_icn.esram12_in_arb_lim[4],
b + NODE_ESRAM1_2_IN_2_ARB_1_LIMIT);
writel_relaxed(context_icn.esram12_in_arb_lim[5],
b + NODE_ESRAM1_2_IN_2_ARB_2_LIMIT);
writel_relaxed(context_icn.esram12_in_arb_lim[6],
b + NODE_ESRAM1_2_IN_3_ARB_1_LIMIT);
writel_relaxed(context_icn.esram12_in_arb_lim[7],
b + NODE_ESRAM1_2_IN_3_ARB_2_LIMIT);
writel_relaxed(context_icn.esram34_in_prio[0],
b + NODE_ESRAM3_4_IN_0_PRIORITY);
writel_relaxed(context_icn.esram34_in_prio[1],
b + NODE_ESRAM3_4_IN_1_PRIORITY);
writel_relaxed(context_icn.esram34_in_prio[2],
b + NODE_ESRAM3_4_IN_2_PRIORITY);
writel_relaxed(context_icn.esram34_in_prio[3],
b + NODE_ESRAM3_4_IN_3_PRIORITY);
writel_relaxed(context_icn.esram34_in_arb_lim[0],
b + NODE_ESRAM3_4_IN_0_ARB_1_LIMIT);
writel_relaxed(context_icn.esram34_in_arb_lim[1],
b + NODE_ESRAM3_4_IN_0_ARB_2_LIMIT);
writel_relaxed(context_icn.esram34_in_arb_lim[2],
b + NODE_ESRAM3_4_IN_1_ARB_1_LIMIT);
writel_relaxed(context_icn.esram34_in_arb_lim[3],
b + NODE_ESRAM3_4_IN_1_ARB_2_LIMIT);
writel_relaxed(context_icn.esram34_in_arb_lim[4],
b + NODE_ESRAM3_4_IN_2_ARB_1_LIMIT);
writel_relaxed(context_icn.esram34_in_arb_lim[5],
b + NODE_ESRAM3_4_IN_2_ARB_2_LIMIT);
writel_relaxed(context_icn.esram34_in_arb_lim[6],
b + NODE_ESRAM3_4_IN_3_ARB_1_LIMIT);
writel_relaxed(context_icn.esram34_in_arb_lim[7],
b + NODE_ESRAM3_4_IN_3_ARB_2_LIMIT);
writel_relaxed(context_icn.ddr_awqos_dsp_ddr0,
b + NODE_DDR_AWQOS_DSP_DDR0_REG);
writel_relaxed(context_icn.ddr_awqos_dsp_ddr1,
b + NODE_DDR_AWQOS_DSP_DDR1_REG);
writel_relaxed(context_icn.ddr_arqos_dsp_ddr0,
b + NODE_DDR_ARQOS_DSP_DDR0_REG);
writel_relaxed(context_icn.ddr_arqos_dsp_ddr1,
b + NODE_DDR_ARQOS_DSP_DDR1_REG);
writel_relaxed(context_icn.ddr_awqos_arm_ddr,
b + NODE_DDR_AWQOS_ARM_DDR_REG);
writel_relaxed(context_icn.ddr_arqos_arm_ddr,
b + NODE_DDR_ARQOS_ARM_DDR_REG);
writel_relaxed(context_icn.sga_awqos_ddr0_hibw2,
b + NODE_SGA_AWQOS_DDR0_HIBW2_REG);
writel_relaxed(context_icn.sga_arqos_ddr0_hibw2,
b + NODE_SGA_ARQOS_DDR0_HIBW2_REG);
writel_relaxed(context_icn.sga_awqos_sga_hibw2,
b + NODE_SGA_AWQOS_SGA_HIBW2_REG);
writel_relaxed(context_icn.sga_arqos_sga_hibw2,
b + NODE_SGA_ARQOS_SGA_HIBW2_REG);
}
void u9540_context_init(void)
{
context_icn.base = ioremap(U8500_ICN_BASE, SZ_16K);
}
| gpl-2.0 |
kinsamanka/linux | drivers/mfd/mc13xxx-spi.c | 124 | 4959 | /*
* Copyright 2009-2010 Pengutronix
* Uwe Kleine-Koenig <u.kleine-koenig@pengutronix.de>
*
* loosely based on an earlier driver that has
* Copyright 2009 Pengutronix, Sascha Hauer <s.hauer@pengutronix.de>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/mutex.h>
#include <linux/interrupt.h>
#include <linux/mfd/core.h>
#include <linux/mfd/mc13xxx.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/of_gpio.h>
#include <linux/err.h>
#include <linux/spi/spi.h>
#include "mc13xxx.h"
static const struct spi_device_id mc13xxx_device_id[] = {
{
.name = "mc13783",
.driver_data = MC13XXX_ID_MC13783,
}, {
.name = "mc13892",
.driver_data = MC13XXX_ID_MC13892,
}, {
/* sentinel */
}
};
MODULE_DEVICE_TABLE(spi, mc13xxx_device_id);
static const struct of_device_id mc13xxx_dt_ids[] = {
{ .compatible = "fsl,mc13783", .data = (void *) MC13XXX_ID_MC13783, },
{ .compatible = "fsl,mc13892", .data = (void *) MC13XXX_ID_MC13892, },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, mc13xxx_dt_ids);
static struct regmap_config mc13xxx_regmap_spi_config = {
.reg_bits = 7,
.pad_bits = 1,
.val_bits = 24,
.write_flag_mask = 0x80,
.max_register = MC13XXX_NUMREGS,
.cache_type = REGCACHE_NONE,
.use_single_rw = 1,
};
static int mc13xxx_spi_read(void *context, const void *reg, size_t reg_size,
void *val, size_t val_size)
{
unsigned char w[4] = { *((unsigned char *) reg), 0, 0, 0};
unsigned char r[4];
unsigned char *p = val;
struct device *dev = context;
struct spi_device *spi = to_spi_device(dev);
struct spi_transfer t = {
.tx_buf = w,
.rx_buf = r,
.len = 4,
};
struct spi_message m;
int ret;
if (val_size != 3 || reg_size != 1)
return -ENOTSUPP;
spi_message_init(&m);
spi_message_add_tail(&t, &m);
ret = spi_sync(spi, &m);
memcpy(p, &r[1], 3);
return ret;
}
static int mc13xxx_spi_write(void *context, const void *data, size_t count)
{
struct device *dev = context;
struct spi_device *spi = to_spi_device(dev);
if (count != 4)
return -ENOTSUPP;
return spi_write(spi, data, count);
}
/*
* We cannot use regmap-spi generic bus implementation here.
* The MC13783 chip will get corrupted if CS signal is deasserted
* and on i.Mx31 SoC (the target SoC for MC13783 PMIC) the SPI controller
* has the following errata (DSPhl22960):
* "The CSPI negates SS when the FIFO becomes empty with
* SSCTL= 0. Software cannot guarantee that the FIFO will not
* drain because of higher priority interrupts and the
* non-realtime characteristics of the operating system. As a
* result, the SS will negate before all of the data has been
* transferred to/from the peripheral."
* We workaround this by accessing the SPI controller with a
* single transfert.
*/
static struct regmap_bus regmap_mc13xxx_bus = {
.write = mc13xxx_spi_write,
.read = mc13xxx_spi_read,
};
static int mc13xxx_spi_probe(struct spi_device *spi)
{
struct mc13xxx *mc13xxx;
struct mc13xxx_platform_data *pdata = dev_get_platdata(&spi->dev);
int ret;
mc13xxx = devm_kzalloc(&spi->dev, sizeof(*mc13xxx), GFP_KERNEL);
if (!mc13xxx)
return -ENOMEM;
dev_set_drvdata(&spi->dev, mc13xxx);
spi->mode = SPI_MODE_0 | SPI_CS_HIGH;
mc13xxx->dev = &spi->dev;
mutex_init(&mc13xxx->lock);
mc13xxx->regmap = devm_regmap_init(&spi->dev, ®map_mc13xxx_bus,
&spi->dev,
&mc13xxx_regmap_spi_config);
if (IS_ERR(mc13xxx->regmap)) {
ret = PTR_ERR(mc13xxx->regmap);
dev_err(mc13xxx->dev, "Failed to initialize register map: %d\n",
ret);
dev_set_drvdata(&spi->dev, NULL);
return ret;
}
ret = mc13xxx_common_init(mc13xxx, pdata, spi->irq);
if (ret) {
dev_set_drvdata(&spi->dev, NULL);
} else {
const struct spi_device_id *devid =
spi_get_device_id(spi);
if (!devid || devid->driver_data != mc13xxx->ictype)
dev_warn(mc13xxx->dev,
"device id doesn't match auto detection!\n");
}
return ret;
}
static int __devexit mc13xxx_spi_remove(struct spi_device *spi)
{
struct mc13xxx *mc13xxx = dev_get_drvdata(&spi->dev);
mc13xxx_common_cleanup(mc13xxx);
return 0;
}
static struct spi_driver mc13xxx_spi_driver = {
.id_table = mc13xxx_device_id,
.driver = {
.name = "mc13xxx",
.owner = THIS_MODULE,
.of_match_table = mc13xxx_dt_ids,
},
.probe = mc13xxx_spi_probe,
.remove = __devexit_p(mc13xxx_spi_remove),
};
static int __init mc13xxx_init(void)
{
return spi_register_driver(&mc13xxx_spi_driver);
}
subsys_initcall(mc13xxx_init);
static void __exit mc13xxx_exit(void)
{
spi_unregister_driver(&mc13xxx_spi_driver);
}
module_exit(mc13xxx_exit);
MODULE_DESCRIPTION("Core driver for Freescale MC13XXX PMIC");
MODULE_AUTHOR("Uwe Kleine-Koenig <u.kleine-koenig@pengutronix.de>");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
k5t4j5/kernel_htc_trinity | arch/arm/mvp/pvtcpkm/pvtcp_off_linux.c | 124 | 57370 | /*
* Linux 2.6.32 and later Kernel module for VMware MVP PVTCP Server
*
* Copyright (C) 2010-2013 VMware, Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; see the file COPYING. If not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#line 5
#include "pvtcp.h"
#if defined(CONFIG_NET_NS)
#include <linux/nsproxy.h>
#include <linux/un.h>
#endif
#include <net/ipv6.h>
#include <linux/kobject.h>
#include <linux/netfilter_ipv4.h>
#include <linux/netfilter_ipv6.h>
#include <linux/cred.h>
#define PVTCP_PVSOCK_ADDR 0x7fee0001
#define PVTCP_PVSOCK_NET 0x7fee0000
#define PVTCP_PVSOCK_MASK 0x000000ff
#define PVTCP_PVSOCK_NETMASK 0xffffff00
extern uid_t Mvpkm_vmwareUid;
extern gid_t Mvpkm_vmwareGid;
static struct cred _cred;
static struct file _file = {
.f_cred = &_cred,
};
extern CommOSAtomic PvtcpOutputAIOSection;
extern void PvtcpOffLargeDgramBufInit(void);
static const unsigned short portRangeBase = 7000;
static const unsigned int portRangeSize = 31;
static int hooksRegistered;
static inline int PvtcpTestPortIndexBit(unsigned int addr,
unsigned int portIdx);
static inline unsigned int
PvsockNfHook(struct sk_buff *skb, int inet6)
{
uid_t uid;
unsigned int port;
struct socket *sock;
unsigned int addr = inet6 ?
ntohl(ipv6_hdr(skb)->daddr.s6_addr32[3]) :
ntohl(ip_hdr(skb)->daddr);
if (likely((addr ^ PVTCP_PVSOCK_NET) & ~PVTCP_PVSOCK_MASK)) {
return NF_ACCEPT;
}
sock = skb->sk->sk_socket;
if (unlikely(!sock)) {
return NF_ACCEPT;
}
uid = (sock->file ? sock->file->f_cred->uid : 0);
if (uid == 0 || (sock->type != SOCK_STREAM && sock->type != SOCK_DGRAM)) {
return NF_ACCEPT;
}
if (likely(uid == Mvpkm_vmwareUid)) {
if (sock->type == SOCK_DGRAM) {
port = ntohs(udp_hdr(skb)->dest) - portRangeBase;
if ((port < portRangeSize) &&
PvtcpTestPortIndexBit(htonl(addr), port)) {
return NF_ACCEPT;
}
return NF_DROP;
}
return NF_ACCEPT;
}
return NF_DROP;
}
static unsigned int
Inet4NfHook(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return PvsockNfHook(skb, 0);
}
static unsigned int
Inet6NfHook(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
if (!ipv6_addr_v4mapped(&ipv6_hdr(skb)->daddr)) {
return NF_ACCEPT;
}
return PvsockNfHook(skb, 1);
}
static struct nf_hook_ops netfilterHooks[] = {
{
.hook = Inet4NfHook,
.owner = THIS_MODULE,
.pf = PF_INET,
.hooknum = NF_INET_LOCAL_OUT,
.priority = NF_IP_PRI_SECURITY
},
{
.hook = Inet6NfHook,
.owner = THIS_MODULE,
.pf = PF_INET6,
.hooknum = NF_INET_LOCAL_OUT,
.priority = NF_IP6_PRI_SECURITY
}
};
#if !defined(CONFIG_SYSFS)
#error "The pvTCP offload module requires sysfs!"
#endif
typedef struct PvtcpStateKObj {
struct kobject kobj;
CommTranspInitArgs transpArgs;
unsigned int pvsockAddr;
int useNS;
int haveNS;
} PvtcpStateKObj;
typedef struct PvtcpStateKObjAttr {
struct attribute attr;
ssize_t (*show)(PvtcpStateKObj *stateKObj, char *buf);
ssize_t (*store)(PvtcpStateKObj *stateKObj, const char *buf, size_t count);
} PvtcpStateKObjAttr;
static void
StateKObjRelease(struct kobject *kobj)
{
kfree(container_of(kobj, PvtcpStateKObj, kobj));
}
/**
* @brief Sysfs show function for all pvtcp attributes.
* @param kobj (embedded) state kobject.
* @param attr pvtcp attribute to show.
* @param buf output buffer.
* @return number of bytes written or negative error code.
*/
static ssize_t
StateKObjShow(struct kobject *kobj,
struct attribute *attr,
char *buf)
{
PvtcpStateKObjAttr *stateAttr = container_of(attr, PvtcpStateKObjAttr, attr);
PvtcpStateKObj *stateKObj = container_of(kobj, PvtcpStateKObj, kobj);
if (stateAttr->show) {
return stateAttr->show(stateKObj, buf);
}
return -EIO;
}
static ssize_t
StateKObjStore(struct kobject *kobj,
struct attribute *attr,
const char *buf,
size_t count)
{
PvtcpStateKObjAttr *stateAttr = container_of(attr, PvtcpStateKObjAttr, attr);
PvtcpStateKObj *stateKObj = container_of(kobj, PvtcpStateKObj, kobj);
if (stateAttr->store) {
return stateAttr->store(stateKObj, buf, count);
}
return -EIO;
}
static const struct sysfs_ops StateKObjSysfsOps = {
.show = StateKObjShow,
.store = StateKObjStore
};
/**
* @brief Show function for the comm_info pvtcp attribute.
* @param stateKObj state kobject.
* @param buf output buffer.
* @return number of bytes written or negative error code.
*/
static ssize_t
StateKObjCommInfoShow(PvtcpStateKObj *stateKObj,
char *buf)
{
unsigned int typeHash;
typeHash = CommTransp_GetType(pvtcpVersions[stateKObj->transpArgs.type]);
return snprintf(buf, PAGE_SIZE, "ID=%u,%u\nCAPACITY=%u\nTYPE=0x%0x\n",
stateKObj->transpArgs.id.d32[0],
stateKObj->transpArgs.id.d32[1],
stateKObj->transpArgs.capacity,
typeHash);
}
/**
* @brief Show function for the pvsock_addr pvtcp attribute.
* @param stateKObj state kobject.
* @param buf output buffer.
* @return number of bytes written or negative error code.
*/
static ssize_t
StateKObjPvsockAddrShow(PvtcpStateKObj *stateKObj,
char *buf)
{
union {
unsigned int raw;
unsigned char bytes[4];
} addr;
addr.raw = stateKObj->pvsockAddr;
return snprintf(buf, PAGE_SIZE, "%u.%u.%u.%u\n",
(unsigned int)addr.bytes[0], (unsigned int)addr.bytes[1],
(unsigned int)addr.bytes[2], (unsigned int)addr.bytes[3]);
}
/**
* @brief Show function for the use_ns pvtcp attribute.
* @param stateKObj state kobject.
* @param buf output buffer.
* @return number of bytes written or negative error code.
*/
static ssize_t
StateKObjUseNSShow(PvtcpStateKObj *stateKObj,
char *buf)
{
return snprintf(buf, PAGE_SIZE, "%d\n", stateKObj->useNS);
}
static ssize_t
StateKObjUseNSStore(PvtcpStateKObj *stateKObj,
const char *buf,
size_t count)
{
int rc = -EINVAL;
if (stateKObj->haveNS && (sscanf(buf, "%d", &stateKObj->useNS) == 1)) {
stateKObj->useNS = !!stateKObj->useNS;
rc = count;
}
return rc;
}
static PvtcpStateKObjAttr stateKObjCommInfoAttr =
__ATTR(comm_info, 0444, StateKObjCommInfoShow, NULL);
static PvtcpStateKObjAttr stateKObjPvsockAddrAttr =
__ATTR(pvsock_addr, 0444, StateKObjPvsockAddrShow, NULL);
static PvtcpStateKObjAttr stateKObjUseNSAttr =
__ATTR(use_ns, 0644, StateKObjUseNSShow, StateKObjUseNSStore);
static struct attribute *stateKObjDefaultAttrs[] = {
&stateKObjCommInfoAttr.attr,
&stateKObjPvsockAddrAttr.attr,
&stateKObjUseNSAttr.attr,
NULL
};
static struct kobj_type stateKType = {
.sysfs_ops = &StateKObjSysfsOps,
.release = StateKObjRelease,
.default_attrs = stateKObjDefaultAttrs
};
static int Init(void *args);
static void Exit(void);
COMM_OS_MOD_INIT(Init, Exit);
static CommOSMutex globalLock;
static char perCpuBuf[NR_CPUS][PVTCP_SOCK_BUF_SIZE];
#define PVTCP_OFF_MAX_LB_ADDRS 255
static unsigned int loopbackAddrs[PVTCP_OFF_MAX_LB_ADDRS] = {
0xffffffff,
0x7fffffff
};
static const unsigned int loopbackReserved = 0x00000001 << 31;
#define PvtcpTestLoopbackBit(entry, mask) \
((entry) & (mask))
#define PvtcpSetLoopbackBit(entry, mask) \
((entry) |= (mask))
#define PvtcpResetLoopbackBit(entry, mask) \
((entry) &= ~(mask))
static inline int
PvtcpTestPortIndexBit(unsigned int addr,
unsigned int portIdx)
{
return PvtcpTestLoopbackBit(loopbackAddrs[*((unsigned char *)&addr + 3)],
BIT(portIdx));
}
static inline void
PvtcpSetPortIndexBit(unsigned int addr,
unsigned int portIdx)
{
PvtcpSetLoopbackBit(loopbackAddrs[*((unsigned char *)&addr + 3)],
BIT(portIdx));
}
static inline void
PvtcpResetPortIndexBit(unsigned int addr,
unsigned int portIdx)
{
PvtcpResetLoopbackBit(loopbackAddrs[*((unsigned char *)&addr + 3)],
BIT(portIdx));
}
unsigned int pvtcpLoopbackOffAddr;
unsigned long long pvtcpOffDgramAllocations;
extern void asmDestructorShim(struct sock *);
static void
SockReleaseWrapper(struct socket *sock)
{
sock->file = NULL;
sock_release(sock);
}
static unsigned int
GetLoopbackAddr(void)
{
static unsigned char addrTempl[4] = { 127, 238, 0, 0 };
unsigned int rc = -1U;
unsigned int idx;
struct socket *sock;
CommOS_MutexLock(&globalLock);
for (idx = 1; idx < PVTCP_OFF_MAX_LB_ADDRS; idx++) {
if (!PvtcpTestLoopbackBit(loopbackAddrs[idx], loopbackReserved)) {
addrTempl[3] = (unsigned char)idx;
memcpy(&rc, addrTempl, sizeof(rc));
if (!sock_create_kern(AF_INET, SOCK_DGRAM, 0, &sock)) {
int err;
struct sockaddr_in sin = {
.sin_family = AF_INET,
.sin_addr = { .s_addr = rc }
};
struct ifreq ifr = {
.ifr_flags = IFF_UP
};
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "lo:%u", idx);
memcpy(&ifr.ifr_addr, &sin, sizeof(ifr.ifr_addr));
err = kernel_sock_ioctl(sock, SIOCSIFADDR, (unsigned long)&ifr);
sock_release(sock);
if (err) {
CommOS_Log(("%s: Could not set loopback address (ioctl)!\n",
__func__));
rc = -1U;
continue;
} else {
PvtcpSetLoopbackBit(loopbackAddrs[idx], loopbackReserved);
CommOS_Debug(("%s: Allocated loopback address [%u.%u.%u.%u].\n",
__func__,
addrTempl[0], addrTempl[1],
addrTempl[2], addrTempl[3]));
break;
}
} else {
CommOS_Log(("%s: Could not set loopback address (create)!\n",
__func__));
rc = -1U;
break;
}
}
}
if (idx == PVTCP_OFF_MAX_LB_ADDRS) {
CommOS_Log(("%s: loopback address range exceeded!\n", __func__));
}
CommOS_MutexUnlock(&globalLock);
return rc;
}
static void
PutLoopbackAddr(unsigned int uaddr)
{
const unsigned char addrTempl[3] = { 127, 238, 0 };
unsigned char addr[4];
unsigned int idx;
struct socket *sock;
memcpy(addr, &uaddr, sizeof(uaddr));
if (memcmp(addrTempl, addr, sizeof(addrTempl))) {
return;
}
idx = addr[3];
if ((idx == 0) || (idx >= PVTCP_OFF_MAX_LB_ADDRS)) {
return;
}
CommOS_MutexLock(&globalLock);
if (!PvtcpTestLoopbackBit(loopbackAddrs[idx], loopbackReserved)) {
CommOS_Debug(("%s: loopback entry [%u] already freed.\n",
__func__, idx));
goto out;
}
if (!sock_create_kern(AF_INET, SOCK_DGRAM, 0, &sock)) {
struct sockaddr_in sin = {
.sin_family = AF_INET,
.sin_addr = { .s_addr = uaddr }
};
struct ifreq ifr = {
.ifr_flags = 0
};
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "lo:%u", idx);
memcpy(&ifr.ifr_addr, &sin, sizeof(ifr.ifr_addr));
kernel_sock_ioctl(sock, SIOCSIFFLAGS, (unsigned long)&ifr);
sock_release(sock);
loopbackAddrs[idx] = 0;
CommOS_Debug(("%s: Deallocated loopback address [%u.%u.%u.%u].\n",
__func__, addr[0], addr[1], addr[2], addr[3]));
} else {
CommOS_Log(("%s: Could not delete loopback address!\n",
__func__));
}
out:
CommOS_MutexUnlock(&globalLock);
}
static void
GetNetNamespace(PvtcpState *state)
{
#if defined(CONFIG_NET_NS) && !defined(PVTCP_NET_NS_DISABLE)
CommTranspInitArgs args;
pid_t pidn;
struct pid *pid;
struct task_struct *tsk;
struct nsproxy *nsproxy;
struct net *ns;
struct socket *sock;
struct sockaddr_un addr __attribute__ ((aligned(4))) = {
.sun_family = AF_UNIX
};
struct timeval timeout = {
.tv_sec = 3000,
.tv_usec = 0
};
const int passcred = 1;
char buf[64];
struct kvec vec;
const char *sockname = "pvtcp-vpn";
const size_t socknamelen = strlen(sockname);
struct msghdr msg = {
.msg_name = (struct sockaddr *)&addr,
.msg_namelen = 1 + offsetof(struct sockaddr_un, sun_path) + socknamelen
};
if (!state) {
return;
}
args = CommSvc_GetTranspInitArgs(state->channel);
ns = NULL;
pidn = 0;
if (sock_create_kern(AF_UNIX, SOCK_DGRAM, 0, &sock)) {
CommOS_Debug(("%s: Can't create config socket!\n", __func__));
goto out;
}
if (kernel_setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
(char *)&timeout, sizeof(timeout))) {
sock_release(sock);
CommOS_Debug(("%s: Can't set timeout on config socket!\n", __func__));
goto out;
}
if (kernel_setsockopt(sock, SOL_SOCKET, SO_PASSCRED,
(char *)&passcred, sizeof(passcred))) {
sock_release(sock);
CommOS_Debug(("%s: Can't set passcred on config socket!\n",
__func__));
goto out;
}
memset(buf, 0, sizeof(buf));
snprintf(buf, sizeof(buf), "%u\n", args.id.d32[0]);
buf[sizeof(buf) - 1] = '\0';
vec.iov_base = buf;
vec.iov_len = strlen(buf);
addr.sun_path[0] = 0;
memcpy(addr.sun_path+1, sockname, socknamelen);
if (kernel_sendmsg(sock, &msg, &vec, 1, vec.iov_len) <= 0) {
sock_release(sock);
CommOS_Debug(("%s: Could not send config request for vm [%u]!\n",
__func__, args.id.d32[0]));
goto out;
}
memset(buf, 0, sizeof(buf));
vec.iov_base = buf;
vec.iov_len = sizeof(buf);
if (kernel_recvmsg(sock, &msg, &vec, 1, vec.iov_len, 0) <= 0) {
CommOS_Debug(("%s: Could not receive config reply for vm [%u]!\n",
__func__, args.id.d32[0]));
} else {
buf[sizeof(buf) - 1] = '\0';
sscanf(buf, "%d", &pidn);
}
sock_release(sock);
if (!pidn) {
goto out;
}
pid = find_get_pid(pidn);
if (pid) {
tsk = pid_task(pid, PIDTYPE_PID);
if (tsk) {
rcu_read_lock();
nsproxy = task_nsproxy(tsk);
if (nsproxy && nsproxy->net_ns) {
ns = maybe_get_net(nsproxy->net_ns);
}
rcu_read_unlock();
}
put_pid(pid);
}
out:
if (!ns) {
CommOS_Debug(("%s: Not using a namespace for vm [%u].\n",
__func__, args.id.d32[0]));
ns = &init_net;
} else {
CommOS_Debug(("%s: Found the net namespace for vm [%u].\n",
__func__, args.id.d32[0]));
}
#else
void *ns = NULL;
#endif
state->namespace = ns;
}
static void
PutNetNamespace(void *namespace)
{
#if defined(CONFIG_NET_NS) && !defined(PVTCP_NET_NS_DISABLE)
if (namespace && (namespace != &init_net)) {
put_net((struct net *)namespace);
}
#endif
}
static void *
StateAlloc(CommChannel channel)
{
extern struct kset *Mvpkm_FindVMNamedKSet(int, const char *);
PvtcpState *state = NULL;
PvtcpIf *loopbackNetif = NULL;
PvtcpStateKObj *stateKObj = NULL;
struct kset *kset = NULL;
int rc;
CommTranspInitArgs transpArgs;
transpArgs = CommSvc_GetTranspInitArgs(channel);
kset = Mvpkm_FindVMNamedKSet((int)transpArgs.id.d32[0], "devices");
if (!kset) {
CommOS_Debug(("%s: Could not find sysfs '.../vm/N/devices' kset!\n",
__func__));
goto error;
}
state = PvtcpStateAlloc(channel);
if (!state) {
CommOS_Debug(("%s: Could not allocate state!\n", __func__));
goto error;
}
stateKObj = kzalloc(sizeof(*stateKObj), GFP_KERNEL);
if (!stateKObj) {
CommOS_Debug(("%s: Could not allocate state kobject!\n", __func__));
goto error;
}
stateKObj->kobj.kset = kset;
rc = kobject_init_and_add(&stateKObj->kobj, &stateKType, NULL, "pvtcp");
if (rc) {
CommOS_Debug(("%s: Could not add state kobject to parent kset [%d]!\n",
__func__, rc));
goto error;
}
loopbackNetif = PvtcpStateFindIf(state, pvtcpIfLoopbackInet4);
BUG_ON(loopbackNetif == NULL);
loopbackNetif->conf.addr.in.s_addr = GetLoopbackAddr();
if (loopbackNetif->conf.addr.in.s_addr == -1U) {
CommOS_Log(("%s: Could not allocate loopback address!\n", __func__));
goto error;
}
GetNetNamespace(state);
stateKObj->transpArgs = transpArgs;
stateKObj->pvsockAddr = loopbackNetif->conf.addr.in.s_addr;
#if defined(CONFIG_NET_NS)
stateKObj->haveNS = (state->namespace != &init_net);
stateKObj->useNS = stateKObj->haveNS;
#endif
state->extra = stateKObj;
_cred.uid = _cred.suid = _cred.euid = _cred.fsuid = Mvpkm_vmwareUid;
_cred.gid = _cred.sgid = _cred.egid = _cred.fsgid = Mvpkm_vmwareGid;
out:
if (kset) {
kset_put(kset);
}
return state;
error:
if (stateKObj) {
kobject_del(&stateKObj->kobj);
kobject_put(&stateKObj->kobj);
}
if (loopbackNetif && (loopbackNetif->conf.addr.in.s_addr != -1U)) {
PutLoopbackAddr(loopbackNetif->conf.addr.in.s_addr);
}
if (state) {
PvtcpStateFree(state);
state = NULL;
}
goto out;
}
static void
StateFree(void *arg)
{
PvtcpState *state = arg;
PvtcpIf *loopbackNetif;
void *namespace;
if (!state) {
return;
}
if (state->extra) {
PvtcpStateKObj *stateKObj = state->extra;
kobject_del(&stateKObj->kobj);
kobject_put(&stateKObj->kobj);
}
namespace = state->namespace;
loopbackNetif = PvtcpStateFindIf(state, pvtcpIfLoopbackInet4);
BUG_ON(loopbackNetif == NULL);
PutLoopbackAddr(loopbackNetif->conf.addr.in.s_addr);
PvtcpStateFree(state);
PutNetNamespace(namespace);
}
void
PvtcpReleaseSocket(PvtcpSock *pvsk)
{
struct socket *sock = SkFromPvsk(pvsk)->sk_socket;
PvtcpHoldSock(pvsk);
SOCK_IN_LOCK(pvsk);
SOCK_OUT_LOCK(pvsk);
pvsk->peerSockSet = 0;
SockReleaseWrapper(sock);
SOCK_OUT_UNLOCK(pvsk);
SOCK_IN_UNLOCK(pvsk);
PvtcpPutSock(pvsk);
CommOS_Debug(("%s: [0x%p].\n", __func__, pvsk));
}
static inline int
TestLoopbackInet4(PvtcpSock *pvsk,
unsigned int addr)
{
if (!ipv4_is_loopback(addr)) {
return 0;
}
if (addr != htonl(PVTCP_PVSOCK_ADDR)) {
if (addr != htonl(INADDR_LOOPBACK)) {
return -EADDRNOTAVAIL;
}
if (PvtcpHasSockNamespace(pvsk)) {
return 0;
}
return 2;
}
return 1;
}
int
PvtcpTestAndBindLoopbackInet4(PvtcpSock *pvsk,
unsigned int *addr,
unsigned short port)
{
int rc;
struct sockaddr_in sin;
unsigned int morphedAddr;
int propagate = 0;
rc = TestLoopbackInet4(pvsk, *addr);
switch (rc) {
case 2:
propagate = 1;
case 1:
break;
case 0:
return 1;
default:
return rc;
}
if (pvsk->netif->conf.family == PVTCP_PF_LOOPBACK_INET4) {
morphedAddr = pvsk->netif->conf.addr.in.s_addr;
rc = 0;
goto out;
}
PvtcpSwitchSock(pvsk, PVTCP_SOCK_NAMESPACE_INITIAL);
PvtcpStateAddSocket(pvsk->channel, pvtcpIfLoopbackInet4, pvsk);
morphedAddr = pvsk->netif->conf.addr.in.s_addr;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = port;
sin.sin_addr.s_addr = morphedAddr;
rc = kernel_bind(SkFromPvsk(pvsk)->sk_socket,
(struct sockaddr *)&sin, sizeof(sin));
if (rc) {
PvtcpSwitchSock(pvsk, PVTCP_SOCK_NAMESPACE_CHANNEL);
PvtcpStateAddSocket(pvsk->channel, pvtcpIfUnbound, pvsk);
} else {
port = ntohs(port) - portRangeBase;
if ((SkFromPvsk(pvsk)->sk_socket->type == SOCK_DGRAM) &&
(port < portRangeSize)) {
CommOS_MutexLock(&globalLock);
PvtcpSetPortIndexBit(pvsk->netif->conf.addr.in.s_addr, port);
CommOS_MutexUnlock(&globalLock);
}
SkFromPvsk(pvsk)->sk_socket->file = NULL;
}
out:
if (propagate) {
*addr = morphedAddr;
}
return rc;
}
int
PvtcpTestAndBindLoopbackInet6(PvtcpSock *pvsk,
unsigned long long *addr0,
unsigned long long *addr1,
unsigned short port)
{
int rc;
struct sockaddr_in6 sin6;
union {
unsigned long long halves[2];
struct in6_addr in6;
} in6Addr = {
.halves = { *addr0, *addr1 }
};
int propagate = 0;
const int ipv6Only = 0;
if (ipv6_addr_loopback(&in6Addr.in6)) {
if (PvtcpHasSockNamespace(pvsk)) {
return 1;
}
PvskSetFlag(pvsk, PVTCP_OFF_PVSKF_IPV6_LOOP, 1);
ipv6_addr_set_v4mapped(htonl(INADDR_LOOPBACK), &in6Addr.in6);
}
if (!ipv6_addr_v4mapped(&in6Addr.in6)) {
return 1;
}
rc = TestLoopbackInet4(pvsk, in6Addr.in6.s6_addr32[3]);
switch (rc) {
case 2:
propagate = 1;
case 1:
break;
case 0:
return 1;
default:
return rc;
}
if (pvsk->netif->conf.family == PVTCP_PF_LOOPBACK_INET4) {
ipv6_addr_set_v4mapped(pvsk->netif->conf.addr.in.s_addr, &in6Addr.in6);
rc = 0;
goto out;
}
PvtcpSwitchSock(pvsk, PVTCP_SOCK_NAMESPACE_INITIAL);
PvtcpStateAddSocket(pvsk->channel, pvtcpIfLoopbackInet4, pvsk);
ipv6_addr_set_v4mapped(pvsk->netif->conf.addr.in.s_addr, &in6Addr.in6);
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
sin6.sin6_port = port;
sin6.sin6_addr = in6Addr.in6;
(void)kernel_setsockopt(SkFromPvsk(pvsk)->sk_socket, IPPROTO_IPV6,
IPV6_V6ONLY, (char *)&ipv6Only, sizeof(ipv6Only));
rc = kernel_bind(SkFromPvsk(pvsk)->sk_socket,
(struct sockaddr *)&sin6, sizeof(sin6));
if (rc) {
PvtcpSwitchSock(pvsk, PVTCP_SOCK_NAMESPACE_CHANNEL);
PvtcpStateAddSocket(pvsk->channel, pvtcpIfUnbound, pvsk);
} else {
port = ntohs(port) - portRangeBase;
if ((SkFromPvsk(pvsk)->sk_socket->type == SOCK_DGRAM) &&
(port < portRangeSize)) {
CommOS_MutexLock(&globalLock);
PvtcpSetPortIndexBit(pvsk->netif->conf.addr.in.s_addr, port);
CommOS_MutexUnlock(&globalLock);
}
SkFromPvsk(pvsk)->sk_socket->file = NULL;
}
out:
if (propagate) {
*addr0 = in6Addr.halves[0];
*addr1 = in6Addr.halves[1];
}
return rc;
}
void
PvtcpResetLoopbackInet4(PvtcpSock *pvsk,
unsigned int *addr)
{
if (!PvtcpHasSockNamespace(pvsk)) {
unsigned int addrOnHost = ntohl(*addr);
if ((addrOnHost & PVTCP_PVSOCK_NETMASK) == PVTCP_PVSOCK_NET &&
addrOnHost != PVTCP_PVSOCK_ADDR) {
*addr = htonl(INADDR_LOOPBACK);
}
}
}
void
PvtcpResetLoopbackInet6(PvtcpSock *pvsk,
struct in6_addr *in6)
{
if (!PvtcpHasSockNamespace(pvsk) && ipv6_addr_v4mapped(in6)) {
if (PvskTestFlag(pvsk, PVTCP_OFF_PVSKF_IPV6_LOOP)) {
static const struct in6_addr in6Loopback = IN6ADDR_LOOPBACK_INIT;
*in6 = in6Loopback;
} else {
PvtcpResetLoopbackInet4(pvsk, &in6->s6_addr32[3]);
}
}
}
static int
Init(void *args)
{
int rc = -1;
#if !defined(PVTCP_DISABLE_NETFILTER)
rc = nf_register_hooks(netfilterHooks, ARRAY_SIZE(netfilterHooks));
if (rc) {
CommOS_Log(("%s: Could not register netfilter hooks!\n", __func__));
goto out;
} else {
CommOS_Debug(("%s: Registered netfilter hooks.\n", __func__));
}
hooksRegistered = 1;
#else
CommOS_Log(("%s: Netfilter hooks disabled.\n", __func__));
#endif
CommOS_MutexInit(&globalLock);
CommOS_WriteAtomic(&PvtcpOutputAIOSection, 0);
PvtcpOffLargeDgramBufInit();
pvtcpImpl.owner = CommOS_ModuleSelf();
pvtcpImpl.stateCtor = StateAlloc;
pvtcpImpl.stateDtor = StateFree;
if (CommSvc_RegisterImpl(&pvtcpImpl) == 0) {
rc = 0;
pvtcpLoopbackOffAddr = GetLoopbackAddr();
if (pvtcpLoopbackOffAddr == -1U) {
CommOS_Log(("%s: Could not allocate offload loopback address!\n",
__func__));
rc = -1;
CommSvc_UnregisterImpl(&pvtcpImpl);
}
}
out:
if (rc) {
if (hooksRegistered) {
nf_unregister_hooks(netfilterHooks, ARRAY_SIZE(netfilterHooks));
}
}
return rc;
}
static void
Exit(void)
{
PutLoopbackAddr(pvtcpLoopbackOffAddr);
CommSvc_UnregisterImpl(&pvtcpImpl);
#if !defined(PVTCP_DISABLE_NETFILTER)
if (hooksRegistered) {
nf_unregister_hooks(netfilterHooks, ARRAY_SIZE(netfilterHooks));
CommOS_Debug(("%s: Netfilter hooks unregistered.\n", __func__));
}
#endif
CommOS_Log(("%s: Allocations of large datagrams: %llu.\n",
__func__, pvtcpOffDgramAllocations));
}
int
DestructCB(struct sock *sk)
{
PvtcpOffBuf *internalBuf;
PvtcpOffBuf *tmp;
PvtcpSock *pvsk = PvskFromSk(sk);
if (!pvsk ||
(SkFromPvsk(pvsk) != sk) ||
(pvsk->destruct == asmDestructorShim)) {
CommOS_Debug(("%s: pvsk / sk inconsistency. Ignored.\n", __func__));
return -1;
}
CommOS_ListForEachSafe(&pvsk->queue, internalBuf, tmp, link) {
CommOS_ListDel(&internalBuf->link);
PvtcpBufFree(PvtcpOffBufFromInternal(internalBuf));
}
if (pvsk->destruct) {
pvsk->destruct(sk);
}
if (pvsk->rpcReply) {
CommOS_Kfree(pvsk->rpcReply);
}
CommOS_Kfree(pvsk);
return 0;
}
static void
StateChangeCB(struct sock *sk)
{
PvtcpSock *pvsk = PvskFromSk(sk);
if (!pvsk ||
(SkFromPvsk(pvsk) != sk) ||
(pvsk->stateChange == StateChangeCB)) {
CommOS_Debug(("%s: pvsk / sk inconsistency. Ignored.\n", __func__));
return;
}
CommOS_Debug(("%s: [0x%p] sk_state [%u] sk_err [%d] sk_err_soft [%d].\n",
__func__, pvsk, sk->sk_state,
sk->sk_err, sk->sk_err_soft));
if (pvsk->stateChange) {
pvsk->stateChange(sk);
}
if (sk->sk_state == TCP_ESTABLISHED) {
PvskSetOpFlag(pvsk, PVTCP_OP_CONNECT);
}
PvtcpSchedSock(pvsk);
}
static void
ErrorReportCB(struct sock *sk)
{
PvtcpSock *pvsk = PvskFromSk(sk);
if (!pvsk ||
(SkFromPvsk(pvsk) != sk) ||
(pvsk->errorReport == ErrorReportCB)) {
CommOS_Debug(("%s: pvsk / sk inconsistency. Ignored\n", __func__));
return;
}
CommOS_Debug(("%s: [0x%p] sk_err [%d] sk_err_soft [%d].\n",
__func__, pvsk, sk->sk_err, sk->sk_err_soft));
if (pvsk->errorReport) {
pvsk->errorReport(sk);
}
pvsk->err = sk->sk_err;
PvtcpSchedSock(pvsk);
}
static void
DataReadyCB(struct sock *sk,
int bytes)
{
PvtcpSock *pvsk = PvskFromSk(sk);
if (!pvsk ||
(SkFromPvsk(pvsk) != sk) ||
(pvsk->dataReady == DataReadyCB)) {
CommOS_Debug(("%s: pvsk / sk inconsistency. Ignored.\n", __func__));
return;
}
if (pvsk->dataReady) {
pvsk->dataReady(sk, bytes);
}
if (sk->sk_state == TCP_LISTEN) {
CommOS_Debug(("%s: Listen socket ready to accept [0x%p].\n",
__func__, pvsk));
}
PvtcpSchedSock(pvsk);
}
static void
WriteSpaceCB(struct sock *sk)
{
PvtcpSock *pvsk = PvskFromSk(sk);
if (!pvsk ||
(SkFromPvsk(pvsk) != sk) ||
(pvsk->writeSpace == WriteSpaceCB)) {
CommOS_Debug(("%s: pvsk / sk inconsistency. Ignored.\n", __func__));
return;
}
if (pvsk->writeSpace) {
pvsk->writeSpace(sk);
}
PvtcpSchedSock(pvsk);
}
static int
SockAllocInit(struct socket *sock,
CommChannel channel,
unsigned long long peerSock,
PvtcpSock *parentPvsk)
{
struct sock *sk;
struct inode *inode;
PvtcpSock *pvsk;
int sndBuf = PVTCP_SOCK_RCVSIZE * 4;
if (!sock || !channel || !peerSock) {
return -EINVAL;
}
sk = sock->sk;
sk->sk_user_data = NULL;
pvsk = CommOS_Kmalloc(sizeof(*pvsk));
if (!pvsk) {
return -ENOMEM;
}
if (PvtcpOffSockInit(pvsk, channel)) {
CommOS_Kfree(pvsk);
return -ENOMEM;
}
sk->sk_socket->file = &_file;
inode = SOCK_INODE(sock);
inode->i_uid = _cred.fsuid;
inode->i_gid = _cred.fsgid;
pvsk->peerSock = peerSock;
pvsk->peerSockSet = 1;
pvsk->sk = sk;
if (PvtcpStateAddSocket(channel, pvtcpIfUnbound, pvsk) != 0) {
CommOS_Kfree(pvsk);
return -ENOMEM;
}
CommOS_ModuleGet(pvtcpImpl.owner);
if (!parentPvsk) {
pvsk->destruct = sk->sk_destruct;
sk->sk_destruct = asmDestructorShim;
pvsk->stateChange = sk->sk_state_change;
sk->sk_state_change = StateChangeCB;
pvsk->errorReport = sk->sk_error_report;
sk->sk_error_report = ErrorReportCB;
pvsk->dataReady = sk->sk_data_ready;
sk->sk_data_ready = DataReadyCB;
pvsk->writeSpace = sk->sk_write_space;
sk->sk_write_space = WriteSpaceCB;
} else {
pvsk->destruct = parentPvsk->destruct;
sk->sk_destruct = asmDestructorShim;
pvsk->stateChange = parentPvsk->stateChange;
sk->sk_state_change = StateChangeCB;
pvsk->errorReport = parentPvsk->errorReport;
sk->sk_error_report = ErrorReportCB;
pvsk->dataReady = parentPvsk->dataReady;
sk->sk_data_ready = DataReadyCB;
pvsk->writeSpace = parentPvsk->writeSpace;
sk->sk_write_space = WriteSpaceCB;
if (parentPvsk->netif->conf.family == PVTCP_PF_LOOPBACK_INET4) {
PvtcpSwitchSock(pvsk, PVTCP_SOCK_NAMESPACE_INITIAL);
PvtcpStateAddSocket(pvsk->channel, pvtcpIfLoopbackInet4, pvsk);
}
}
sk->sk_user_data = pvsk;
kernel_setsockopt(sock, SOL_SOCKET, SO_SNDBUFFORCE,
(void *)&sndBuf, sizeof(sndBuf));
return 0;
}
static PvtcpSock *
SockAllocErrInit(int err,
CommChannel channel,
unsigned long long peerSock)
{
PvtcpSock *pvsk;
if (!channel || !peerSock) {
return NULL;
}
pvsk = CommOS_Kmalloc(sizeof(*pvsk));
if (!pvsk) {
return NULL;
}
if (PvtcpOffSockInit(pvsk, channel)) {
CommOS_Kfree(pvsk);
return NULL;
}
pvsk->peerSock = peerSock;
pvsk->peerSockSet = 1;
pvsk->err = err;
pvsk->sk = NULL;
return pvsk;
}
void
PvtcpCreateOp(CommChannel channel,
void *upperLayerState,
CommPacket *packet,
struct kvec *vec,
unsigned int vecLen)
{
int rc;
struct socket *sock;
PvtcpSock *pvsk;
PvtcpState *state = (PvtcpState *)upperLayerState;
const int enable = 1;
PVTCP_UNLOCK_DISP_DISCARD_VEC();
#if defined(PVTCP_IPV6_DISABLE)
if (packet->data16 == AF_INET6) {
CommOS_Debug(("%s: AF_INET6 support is disabled.\n", __func__));
rc = -EAFNOSUPPORT;
} else
#endif
{
rc = sock_create_kern(packet->data16, packet->data32,
packet->data32ex, &sock);
}
if (!rc) {
rc = SockAllocInit(sock, channel, packet->data64, NULL);
if (rc) {
SockReleaseWrapper(sock);
goto fail;
}
kernel_setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
(void *)&enable, sizeof(enable));
pvsk = PvskFromSk(sock->sk);
if (state->extra &&
((PvtcpStateKObj *)(state->extra))->useNS) {
PvtcpSwitchSock(pvsk, PVTCP_SOCK_NAMESPACE_CHANNEL);
} else {
PvtcpSwitchSock(pvsk, PVTCP_SOCK_NAMESPACE_INITIAL);
}
PvtcpStateAddSocket(pvsk->channel, pvtcpIfUnbound, pvsk);
PvskSetOpFlag(pvsk, PVTCP_OP_CREATE);
} else {
CommOS_Debug(("%s: Error creating offload socket: %d\n",
__func__, rc));
pvsk = SockAllocErrInit(-rc, channel, packet->data64);
if (!pvsk) {
goto fail;
}
}
PvtcpSchedSock(pvsk);
return;
fail:
CommOS_Log(("%s: BOOG ** FAILED TO CREATE OFFLOAD SOCKET [%d] "
"_AND_ ERROR REPORTING SOCKET!\n"
" PV SIDE MAY BE LOCKED UP UNTIL CREATE RPC TIMES OUT!",
__func__, rc));
}
void
PvtcpReleaseOp(CommChannel channel,
void *upperLayerState,
CommPacket *packet,
struct kvec *vec,
unsigned int vecLen)
{
PvtcpSock *pvsk = PvtcpGetPvskOrReturn(packet->data64, upperLayerState);
struct sock *sk = SkFromPvsk(pvsk);
if ((sk->sk_socket->type == SOCK_DGRAM) &&
(pvsk->netif->conf.family == PVTCP_PF_LOOPBACK_INET4)) {
unsigned short port = 0;
if (sk->sk_family == AF_INET) {
struct sockaddr_in sin = { .sin_family = AF_INET };
int addrLen = sizeof(sin);
if (!kernel_getsockname(sk->sk_socket,
(struct sockaddr *)&sin, &addrLen)) {
port = sin.sin_port;
}
} else {
struct sockaddr_in6 sin = { .sin6_family = AF_INET6 };
int addrLen = sizeof(sin);
if (!kernel_getsockname(sk->sk_socket,
(struct sockaddr *)&sin, &addrLen)) {
port = sin.sin6_port;
}
}
port = ntohs(port) - portRangeBase;
if (port < portRangeSize) {
CommOS_MutexLock(&globalLock);
PvtcpResetPortIndexBit(pvsk->netif->conf.addr.in.s_addr, port);
CommOS_MutexUnlock(&globalLock);
}
}
PvtcpStateRemoveSocket(pvsk->channel, pvsk);
PvtcpHoldSock(pvsk);
SOCK_STATE_LOCK(pvsk);
pvsk->peerSockSet = 0;
SOCK_STATE_UNLOCK(pvsk);
PvskSetOpFlag(pvsk, PVTCP_OP_RELEASE);
PvtcpSchedSock(pvsk);
PvtcpPutSock(pvsk);
PVTCP_UNLOCK_DISP_DISCARD_VEC();
}
void
PvtcpBindOp(CommChannel channel,
void *upperLayerState,
CommPacket *packet,
struct kvec *vec,
unsigned int vecLen)
{
PvtcpSock *pvsk = PvtcpGetPvskOrReturn(packet->data64, upperLayerState);
struct sock *sk = SkFromPvsk(pvsk);
struct sockaddr *addr;
struct sockaddr_in sin;
struct sockaddr_in6 sin6;
int reuseAddr;
int addrLen;
int rc;
PvtcpHoldSock(pvsk);
PVTCP_UNLOCK_DISP_DISCARD_VEC();
reuseAddr = COMM_OPF_GET_VAL(packet->flags);
if ((reuseAddr == 1) || (reuseAddr == 2)) {
reuseAddr--;
kernel_setsockopt(sk->sk_socket, SOL_SOCKET, SO_REUSEADDR,
(void *)&reuseAddr, sizeof(reuseAddr));
}
if (sk->sk_family == AF_INET) {
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = packet->data16;
sin.sin_addr.s_addr = (unsigned int)packet->data64ex;
addr = (struct sockaddr *)&sin;
addrLen = sizeof(sin);
rc = PvtcpTestAndBindLoopbackInet4(pvsk, &sin.sin_addr.s_addr,
sin.sin_port);
if (rc <= 0) {
pvsk->err = -rc;
goto out;
}
} else {
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
sin6.sin6_port = packet->data16;
addr = (struct sockaddr *)&sin6;
addrLen = sizeof(sin6);
rc = PvtcpTestAndBindLoopbackInet6(pvsk, &packet->data64ex,
&packet->data64ex2, sin6.sin6_port);
if (rc <= 0) {
pvsk->err = -rc;
goto out;
}
PvtcpI6AddrUnpack(&sin6.sin6_addr.s6_addr32[0],
packet->data64ex, packet->data64ex2);
}
pvsk->err = -kernel_bind(sk->sk_socket, addr, addrLen);
out:
PvskSetOpFlag(pvsk, PVTCP_OP_BIND);
PvtcpSchedSock(pvsk);
PvtcpPutSock(pvsk);
}
void
PvtcpSetSockOptOp(CommChannel channel,
void *upperLayerState,
CommPacket *packet,
struct kvec *vec,
unsigned int vecLen)
{
PvtcpSock *pvsk = PvtcpGetPvskOrReturn(packet->data64, upperLayerState);
struct sock *sk = SkFromPvsk(pvsk);
struct socket *sock = sk->sk_socket;
unsigned int optlen = packet->len - sizeof(*packet);
PvtcpHoldSock(pvsk);
if ((vecLen != 1) || (vec[0].iov_len != optlen) || (optlen < sizeof(int))) {
pvsk->rpcStatus = -EINVAL;
goto out;
}
if (packet->data32 == SOL_TCP) {
int on;
switch (packet->data32ex) {
case TCP_NODELAY:
memcpy(&on, vec[0].iov_base, sizeof(on));
PvskSetFlag(pvsk, PVTCP_OFF_PVSKF_TCP_NODELAY, on);
pvsk->rpcStatus = 0;
goto out;
case TCP_CORK:
memcpy(&on, vec[0].iov_base, sizeof(on));
PvskSetFlag(pvsk, PVTCP_OFF_PVSKF_TCP_CORK, on);
pvsk->rpcStatus = 0;
goto out;
}
}
pvsk->rpcStatus = kernel_setsockopt(sock,
packet->data32,
packet->data32ex,
vec[0].iov_base,
optlen);
out:
PVTCP_UNLOCK_DISP_DISCARD_VEC();
PvskSetOpFlag(pvsk, PVTCP_OP_SETSOCKOPT);
PvtcpSchedSock(pvsk);
PvtcpPutSock(pvsk);
}
void
PvtcpGetSockOptOp(CommChannel channel,
void *upperLayerState,
CommPacket *packet,
struct kvec *vec,
unsigned int vecLen)
{
PvtcpSock *pvsk = PvtcpGetPvskOrReturn(packet->data64, upperLayerState);
struct sock *sk = SkFromPvsk(pvsk);
struct socket *sock = sk->sk_socket;
unsigned int optLen = (unsigned int)(packet->data64ex);
char *optBuf;
int rc = 0;
PvtcpHoldSock(pvsk);
if ((optLen < sizeof(int)) || (optLen > PVTCP_SOCK_SAFE_RCVSIZE)) {
pvsk->rpcStatus = -EINVAL;
goto out;
}
optBuf = CommOS_Kmalloc(optLen);
if (!optBuf) {
pvsk->rpcStatus = -EINVAL;
goto out;
}
if (packet->data32 == SOL_TCP) {
int on;
switch (packet->data32ex) {
case TCP_NODELAY:
on = PvskTestFlag(pvsk, PVTCP_OFF_PVSKF_TCP_NODELAY);
optLen = sizeof(on);
memcpy(optBuf, &on, optLen);
goto done;
case TCP_CORK:
on = PvskTestFlag(pvsk, PVTCP_OFF_PVSKF_TCP_CORK);
optLen = sizeof(on);
memcpy(optBuf, &on, optLen);
goto done;
}
}
rc = kernel_getsockopt(sock, packet->data32,
packet->data32ex, optBuf, &optLen);
done:
if (!rc) {
pvsk->rpcReply = optBuf;
CommOS_MemBarrier();
pvsk->rpcStatus = (int)optLen;
} else {
CommOS_Kfree(optBuf);
pvsk->rpcStatus = rc;
}
out:
PVTCP_UNLOCK_DISP_DISCARD_VEC();
PvskSetOpFlag(pvsk, PVTCP_OP_GETSOCKOPT);
PvtcpSchedSock(pvsk);
PvtcpPutSock(pvsk);
}
void
PvtcpIoctlOp(CommChannel channel,
void *state,
CommPacket *packet,
struct kvec *vec,
unsigned int vecLen)
{
PvtcpSock *pvsk = PvtcpGetPvskOrReturn(packet->data64, state);
struct sock *sk = SkFromPvsk(pvsk);
struct socket *sock = sk->sk_socket;
PvtcpHoldSock(pvsk);
(void)sock;
pvsk->rpcStatus = -ENOIOCTLCMD;
PVTCP_UNLOCK_DISP_DISCARD_VEC();
PvskSetOpFlag(pvsk, PVTCP_OP_IOCTL);
PvtcpSchedSock(pvsk);
PvtcpPutSock(pvsk);
}
void
PvtcpListenOp(CommChannel channel,
void *upperLayerState,
CommPacket *packet,
struct kvec *vec,
unsigned int vecLen)
{
PvtcpSock *pvsk = PvtcpGetPvskOrReturn(packet->data64, upperLayerState);
struct sock *sk = SkFromPvsk(pvsk);
int backlog = (int)packet->data32;
PvtcpHoldSock(pvsk);
PVTCP_UNLOCK_DISP_DISCARD_VEC();
pvsk->err = -kernel_listen(sk->sk_socket, backlog);
PvskSetOpFlag(pvsk, PVTCP_OP_LISTEN);
PvtcpSchedSock(pvsk);
PvtcpPutSock(pvsk);
}
void
PvtcpAcceptOp(CommChannel channel,
void *upperLayerState,
CommPacket *packet,
struct kvec *vec,
unsigned int vecLen)
{
int rc;
PvtcpSock *pvsk = PvtcpGetPvskOrReturn(packet->data64, upperLayerState);
struct sock *sk = SkFromPvsk(pvsk);
struct socket *newsock = NULL;
PvtcpHoldSock(pvsk);
PVTCP_UNLOCK_DISP_DISCARD_VEC();
rc = kernel_accept(sk->sk_socket, &newsock, O_NONBLOCK);
if (rc == 0) {
rc = SockAllocInit(newsock, channel, packet->data64ex, pvsk);
if (rc) {
SockReleaseWrapper(newsock);
}
}
if (rc == 0) {
struct sock *newsk = newsock->sk;
PvtcpSock *newpvsk = PvskFromSk(newsk);
newpvsk->state = (PvtcpState *)pvsk;
PvskSetOpFlag(newpvsk, PVTCP_OP_ACCEPT);
PvtcpSchedSock(newpvsk);
} else {
pvsk->err = -rc;
PvskSetOpFlag(pvsk, PVTCP_OP_ACCEPT);
PvtcpSchedSock(pvsk);
}
PvtcpPutSock(pvsk);
}
void
PvtcpConnectOp(CommChannel channel,
void *upperLayerState,
CommPacket *packet,
struct kvec *vec,
unsigned int vecLen)
{
PvtcpSock *pvsk = PvtcpGetPvskOrReturn(packet->data64, upperLayerState);
struct sock *sk = SkFromPvsk(pvsk);
struct sockaddr *addr;
struct sockaddr_in sin;
struct sockaddr_in6 sin6;
int addrLen;
int flags = 0;
int rc = 0;
int disconnect = 0;
PvtcpHoldSock(pvsk);
PVTCP_UNLOCK_DISP_DISCARD_VEC();
if (sk->sk_family == AF_INET) {
addr = (struct sockaddr *)&sin;
addrLen = sizeof(sin);
memset(&sin, 0, sizeof(sin));
sin.sin_port = packet->data16;
sin.sin_addr.s_addr = (unsigned int)packet->data64ex;
if (COMM_OPF_GET_VAL(packet->flags)) {
sin.sin_family = AF_UNSPEC;
disconnect = 1;
goto connect;
}
sin.sin_family = AF_INET;
PvtcpTestAndBindLoopbackInet4(pvsk, &sin.sin_addr.s_addr, 0);
} else {
addr = (struct sockaddr *)&sin6;
addrLen = sizeof(sin6);
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_port = packet->data16;
if (COMM_OPF_GET_VAL(packet->flags)) {
sin6.sin6_family = AF_UNSPEC;
PvtcpI6AddrUnpack(&sin6.sin6_addr.s6_addr32[0],
packet->data64ex, packet->data64ex2);
disconnect = 1;
goto connect;
}
sin6.sin6_family = AF_INET6;
PvtcpTestAndBindLoopbackInet6(pvsk, &packet->data64ex,
&packet->data64ex2, 0);
PvtcpI6AddrUnpack(&sin6.sin6_addr.s6_addr32[0],
packet->data64ex, packet->data64ex2);
}
connect:
rc = kernel_connect(sk->sk_socket, addr, addrLen, flags | O_NONBLOCK);
if (rc && (sk->sk_socket->type == SOCK_DGRAM)) {
pvsk->err = -rc;
}
PvskSetFlag(pvsk, PVTCP_OFF_PVSKF_DISCONNECT, disconnect);
PvskSetOpFlag(pvsk, PVTCP_OP_CONNECT);
PvtcpSchedSock(pvsk);
PvtcpPutSock(pvsk);
}
void
PvtcpShutdownOp(CommChannel channel,
void *upperLayerState,
CommPacket *packet,
struct kvec *vec,
unsigned int vecLen)
{
PvtcpSock *pvsk = PvtcpGetPvskOrReturn(packet->data64, upperLayerState);
int how = (int)packet->data32;
PvtcpHoldSock(pvsk);
if ((how == SHUT_RD) || (how == SHUT_RDWR)) {
kernel_sock_shutdown(SkFromPvsk(pvsk)->sk_socket, SHUT_RD);
PvskSetFlag(pvsk, PVTCP_OFF_PVSKF_SHUT_RD, 1);
}
if ((how == SHUT_WR) || (how == SHUT_RDWR)) {
PvskSetFlag(pvsk, PVTCP_OFF_PVSKF_SHUT_WR, 1);
}
PVTCP_UNLOCK_DISP_DISCARD_VEC();
PvtcpSchedSock(pvsk);
PvtcpPutSock(pvsk);
}
static inline void
ReleaseAIO(PvtcpSock *pvsk)
{
struct sock *sk = SkFromPvsk(pvsk);
struct socket *sock = sk->sk_socket;
CommPacket packet = {
.len = sizeof(packet),
.flags = 0,
.opCode = PVTCP_OP_RELEASE,
.data64 = pvsk->peerSock,
.data64ex = PvtcpGetHandle(pvsk)
};
unsigned long long timeout = COMM_MAX_TO;
SOCK_OUT_LOCK(pvsk);
CommSvc_Write(pvsk->channel, &packet, &timeout);
#if defined(PVTCP_FULL_DEBUG)
CommOS_Debug(("%s: Sent 'Release' [0x%p] -> 0x%0x] reply.\n",
__func__, pvsk, (unsigned)(pvsk->peerSock)));
#endif
SockReleaseWrapper(sock);
SOCK_OUT_UNLOCK(pvsk);
}
static inline void
CreateAIO(PvtcpSock *pvsk)
{
struct sock *sk;
struct socket *sock;
CommPacket packet = {
.len = sizeof(packet),
.flags = 0,
.opCode = PVTCP_OP_CREATE,
.data64 = pvsk->peerSock,
};
unsigned long long timeout = COMM_MAX_TO;
int rc;
sk = SkFromPvsk(pvsk);
if (!sk) {
return;
}
sock = sk->sk_socket;
packet.data64ex = PvtcpGetHandle(pvsk);
rc = CommSvc_Write(pvsk->channel, &packet, &timeout);
if (rc != packet.len) {
PvtcpStateRemoveSocket(pvsk->channel, pvsk);
SockReleaseWrapper(sock);
CommOS_Log(("%s: BOOG -- Couldn't send 'Create' reply [0x%p]!\n",
__func__, sk));
} else {
#if defined(PVTCP_FULL_DEBUG)
CommOS_Debug(("%s: Sent 'Create' [0x%p] reply [%d].\n",
__func__, pvsk, rc));
#endif
}
}
static inline void
BindAIO(PvtcpSock *pvsk)
{
struct sock *sk = SkFromPvsk(pvsk);
struct socket *sock = sk->sk_socket;
CommPacket packet = {
.len = sizeof(packet),
.flags = 0,
.opCode = PVTCP_OP_BIND,
.data64 = pvsk->peerSock
};
unsigned long long timeout = COMM_MAX_TO;
int rc;
if (pvsk->peerSockSet) {
if (sk->sk_family == AF_INET) {
struct sockaddr_in sin = { .sin_family = AF_INET };
int addrLen = sizeof(sin);
rc = kernel_getsockname(sock, (struct sockaddr *)&sin, &addrLen);
if (rc == 0) {
packet.data16 = sin.sin_port;
PvtcpResetLoopbackInet4(pvsk, &sin.sin_addr.s_addr);
packet.data64ex = (unsigned long long)sin.sin_addr.s_addr;
}
} else {
struct sockaddr_in6 sin = { .sin6_family = AF_INET6 };
int addrLen = sizeof(sin);
rc = kernel_getsockname(sock, (struct sockaddr *)&sin, &addrLen);
if (rc == 0) {
packet.data16 = sin.sin6_port;
PvtcpResetLoopbackInet6(pvsk, &sin.sin6_addr);
PvtcpI6AddrPack(&sin.sin6_addr.s6_addr32[0],
&packet.data64ex, &packet.data64ex2);
}
}
if (rc) {
COMM_OPF_SET_ERR(packet.flags);
packet.data32ex = (unsigned int)(-rc);
packet.opCode = PVTCP_OP_FLOW;
}
CommSvc_Write(pvsk->channel, &packet, &timeout);
#if defined(PVTCP_FULL_DEBUG)
CommOS_Debug(("%s: Sent 'Bind' [0x%p, %d] reply.\n",
__func__, pvsk, rc));
#endif
}
}
static inline void
SetSockOptAIO(PvtcpSock *pvsk)
{
CommPacket packet;
unsigned long long timeout;
packet.len = sizeof(packet);
packet.flags = 0;
packet.opCode = PVTCP_OP_SETSOCKOPT;
packet.data64 = pvsk->peerSock;
packet.data32 = (unsigned int)(pvsk->rpcStatus);
timeout = COMM_MAX_TO;
CommSvc_Write(pvsk->channel, &packet, &timeout);
pvsk->rpcStatus = 0;
}
static inline void
GetSockOptAIO(PvtcpSock *pvsk)
{
CommPacket packet = {
.len = sizeof(packet),
.opCode = PVTCP_OP_GETSOCKOPT,
.flags = 0
};
unsigned long long timeout = COMM_MAX_TO;
struct kvec vec[1];
struct kvec *inVec = vec;
unsigned int vecLen = 1;
unsigned int iovOffset = 0;
if (pvsk->rpcStatus > 0) {
packet.len = sizeof(packet) + pvsk->rpcStatus;
vec[0].iov_base = pvsk->rpcReply;
vec[0].iov_len = pvsk->rpcStatus;
} else {
vecLen = 0;
}
packet.data64 = pvsk->peerSock;
packet.data32 = pvsk->rpcStatus;
CommSvc_WriteVec(pvsk->channel, &packet, &inVec, &vecLen,
&timeout, &iovOffset, 1);
if (pvsk->rpcReply) {
CommOS_Kfree(pvsk->rpcReply);
pvsk->rpcReply = NULL;
}
pvsk->rpcStatus = 0;
}
static inline void
IoctlAIO(PvtcpSock *pvsk)
{
CommPacket packet = {
.len = sizeof(packet),
.opCode = PVTCP_OP_IOCTL,
.flags = 0
};
unsigned long long timeout = COMM_MAX_TO;
packet.data64 = pvsk->peerSock;
packet.data32 = pvsk->rpcStatus;
CommSvc_Write(pvsk->channel, &packet, &timeout);
pvsk->rpcStatus = 0;
}
static inline void
ListenAIO(PvtcpSock *pvsk)
{
struct sock *sk = SkFromPvsk(pvsk);
CommPacket packet = {
.len = sizeof(packet),
.flags = 0,
.opCode = PVTCP_OP_LISTEN,
.data64 = pvsk->peerSock
};
unsigned long long timeout = COMM_MAX_TO;
if (pvsk->peerSockSet) {
if (sk->sk_state != TCP_LISTEN) {
COMM_OPF_SET_ERR(packet.flags);
packet.data32ex = (unsigned int)pvsk->err;
packet.opCode = PVTCP_OP_FLOW;
}
CommSvc_Write(pvsk->channel, &packet, &timeout);
#if defined(PVTCP_FULL_DEBUG)
CommOS_Debug(("%s: Sent 'Listen' [0x%p] reply.\n", __func__, pvsk));
#endif
}
}
static inline void
AcceptAIO(PvtcpSock *pvsk)
{
struct sock *sk = SkFromPvsk(pvsk);
struct socket *sock = sk->sk_socket;
CommPacket packet = {
.len = sizeof(packet),
.flags = 0,
.opCode = PVTCP_OP_ACCEPT
};
unsigned long long timeout = COMM_MAX_TO;
const int enable = 1;
int rc;
if (pvsk->peerSockSet) {
unsigned long long payloadSocks[2] = { 0, 0 };
struct kvec payloadVec[] = {
{ .iov_base = &payloadSocks, .iov_len = sizeof(payloadSocks) }
};
struct kvec *payload = payloadVec;
unsigned int payloadLen = 1;
unsigned int iovOffset = 0;
packet.len = sizeof(packet) + sizeof(payloadSocks);
packet.data64 = ((PvtcpSock *)pvsk->state)->peerSock;
pvsk->state = CommSvc_GetState(pvsk->channel);
payloadSocks[0] = pvsk->peerSock;
payloadSocks[1] = PvtcpGetHandle(pvsk);
rc = 0;
if (sk->sk_family == AF_INET) {
struct sockaddr_in sin = { .sin_family = AF_INET };
int addrLen = sizeof(sin);
rc = kernel_getpeername(sock, (struct sockaddr *)&sin, &addrLen);
if (rc == 0) {
packet.data16 = sin.sin_port;
PvtcpResetLoopbackInet4(pvsk, &sin.sin_addr.s_addr);
packet.data64ex = (unsigned long long)sin.sin_addr.s_addr;
}
} else {
struct sockaddr_in6 sin = { .sin6_family = AF_INET6 };
int addrLen = sizeof(sin);
rc = kernel_getpeername(sock, (struct sockaddr *)&sin, &addrLen);
if (rc == 0) {
packet.data16 = sin.sin6_port;
PvtcpResetLoopbackInet6(pvsk, &sin.sin6_addr);
PvtcpI6AddrPack(&sin.sin6_addr.s6_addr32[0],
&packet.data64ex, &packet.data64ex2);
}
}
if (rc == 0) {
kernel_setsockopt(sock, SOL_TCP, TCP_NODELAY,
(void *)&enable, sizeof(enable));
kernel_setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE,
(void *)&enable, sizeof(enable));
kernel_setsockopt(sock, SOL_SOCKET, SO_OOBINLINE,
(void *)&enable, sizeof(enable));
} else {
PvtcpStateRemoveSocket(pvsk->channel, pvsk);
SockReleaseWrapper(sock);
COMM_OPF_SET_ERR(packet.flags);
packet.data32ex = (unsigned int)ECONNABORTED;
packet.len = sizeof(packet);
packet.opCode = PVTCP_OP_FLOW;
}
rc = CommSvc_WriteVec(pvsk->channel, &packet,
&payload, &payloadLen, &timeout, &iovOffset, 1);
if ((rc != packet.len) && !COMM_OPF_TEST_ERR(packet.flags)) {
PvtcpStateRemoveSocket(pvsk->channel, pvsk);
SockReleaseWrapper(sock);
}
#if defined(PVTCP_FULL_DEBUG)
CommOS_Debug(("%s: Sent 'Accept' [0x%p] reply.\n", __func__, pvsk));
#endif
}
}
static inline void
ConnectAIO(PvtcpSock *pvsk)
{
struct sock *sk = SkFromPvsk(pvsk);
struct socket *sock = sk->sk_socket;
CommPacket packet = {
.len = sizeof(packet),
.flags = 0,
.opCode = PVTCP_OP_CONNECT,
.data64 = pvsk->peerSock
};
unsigned long long timeout = COMM_MAX_TO;
const int enable = 1;
int rc;
if (!pvsk->peerSockSet ||
(!PvskTestFlag(pvsk, PVTCP_OFF_PVSKF_DISCONNECT) &&
(sk->sk_state != TCP_ESTABLISHED))) {
return;
}
if (PvskTestFlag(pvsk, PVTCP_OFF_PVSKF_DISCONNECT)) {
COMM_OPF_SET_VAL(packet.flags, 1);
PvskSetFlag(pvsk, PVTCP_OFF_PVSKF_DISCONNECT, 0);
} else if (sk->sk_state == TCP_ESTABLISHED) {
if (sk->sk_family == AF_INET) {
struct sockaddr_in sin = { .sin_family = AF_INET };
int addrLen = sizeof(sin);
rc = kernel_getsockname(sock, (struct sockaddr *)&sin, &addrLen);
if (rc == 0) {
packet.data16 = sin.sin_port;
PvtcpResetLoopbackInet4(pvsk, &sin.sin_addr.s_addr);
packet.data64ex = (unsigned long long)sin.sin_addr.s_addr;
}
} else {
struct sockaddr_in6 sin = { .sin6_family = AF_INET6 };
int addrLen = sizeof(sin);
rc = kernel_getsockname(sock, (struct sockaddr *)&sin, &addrLen);
if (rc == 0) {
packet.data16 = sin.sin6_port;
PvtcpResetLoopbackInet6(pvsk, &sin.sin6_addr);
PvtcpI6AddrPack(&sin.sin6_addr.s6_addr32[0],
&packet.data64ex, &packet.data64ex2);
}
}
if (rc == 0) {
kernel_setsockopt(sock, SOL_TCP, TCP_NODELAY,
(void *)&enable, sizeof(enable));
kernel_setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE,
(void *)&enable, sizeof(enable));
kernel_setsockopt(sock, SOL_SOCKET, SO_OOBINLINE,
(void *)&enable, sizeof(enable));
} else {
COMM_OPF_SET_ERR(packet.flags);
packet.data32ex = ECONNABORTED;
packet.opCode = PVTCP_OP_FLOW;
}
}
CommSvc_Write(pvsk->channel, &packet, &timeout);
#if defined(PVTCP_FULL_DEBUG)
CommOS_Debug(("%s: Sent 'Connect' [0x%p] reply.\n", __func__, pvsk));
#endif
}
void
PvtcpProcessAIO(CommOSWork *arg)
{
PvtcpSock *pvsk = container_of(arg, PvtcpSock, work);
struct sock *sk = SkFromPvsk(pvsk);
if (!SOCK_OUT_TRYLOCK(pvsk)) {
if (sk && sk->sk_socket) {
PvtcpOutputAIO(pvsk);
}
SOCK_OUT_UNLOCK(pvsk);
}
if (!SOCK_IN_TRYLOCK(pvsk)) {
if (sk && sk->sk_socket) {
int err;
err = PvtcpInputAIO(pvsk, perCpuBuf[smp_processor_id()]);
PvtcpFlowAIO(pvsk, err);
if (!pvsk->opFlags) {
goto doneInUnlock;
}
if (PvskTestOpFlag(pvsk, PVTCP_OP_RELEASE)) {
PvskResetOpFlag(pvsk, PVTCP_OP_RELEASE);
ReleaseAIO(pvsk);
goto doneInUnlock;
}
if (PvskTestOpFlag(pvsk, PVTCP_OP_CREATE)) {
PvskResetOpFlag(pvsk, PVTCP_OP_CREATE);
CreateAIO(pvsk);
}
if (PvskTestOpFlag(pvsk, PVTCP_OP_BIND)) {
PvskResetOpFlag(pvsk, PVTCP_OP_BIND);
BindAIO(pvsk);
}
if (PvskTestOpFlag(pvsk, PVTCP_OP_SETSOCKOPT)) {
PvskResetOpFlag(pvsk, PVTCP_OP_SETSOCKOPT);
SetSockOptAIO(pvsk);
}
if (PvskTestOpFlag(pvsk, PVTCP_OP_GETSOCKOPT)) {
PvskResetOpFlag(pvsk, PVTCP_OP_GETSOCKOPT);
GetSockOptAIO(pvsk);
}
if (PvskTestOpFlag(pvsk, PVTCP_OP_IOCTL)) {
PvskResetOpFlag(pvsk, PVTCP_OP_IOCTL);
IoctlAIO(pvsk);
}
if (PvskTestOpFlag(pvsk, PVTCP_OP_LISTEN)) {
PvskResetOpFlag(pvsk, PVTCP_OP_LISTEN);
ListenAIO(pvsk);
}
if (PvskTestOpFlag(pvsk, PVTCP_OP_ACCEPT)) {
PvskResetOpFlag(pvsk, PVTCP_OP_ACCEPT);
AcceptAIO(pvsk);
}
if (PvskTestOpFlag(pvsk, PVTCP_OP_CONNECT)) {
PvskResetOpFlag(pvsk, PVTCP_OP_CONNECT);
ConnectAIO(pvsk);
}
doneInUnlock:
SOCK_IN_UNLOCK(pvsk);
} else {
PvtcpFlowAIO(pvsk, -ENETDOWN);
}
} else {
if ((pvsk->peerSockSet || PvskTestOpFlag(pvsk, PVTCP_OP_RELEASE)) &&
sk && sk->sk_socket) {
PvtcpSchedSock(pvsk);
}
}
PvtcpPutSock(pvsk);
}
| gpl-2.0 |
x456/linux | net/sched/act_api.c | 380 | 24347 | /*
* net/sched/act_api.c Packet action API.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Author: Jamal Hadi Salim
*
*
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/kmod.h>
#include <linux/err.h>
#include <linux/module.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/sch_generic.h>
#include <net/act_api.h>
#include <net/netlink.h>
static void free_tcf(struct rcu_head *head)
{
struct tcf_common *p = container_of(head, struct tcf_common, tcfc_rcu);
free_percpu(p->cpu_bstats);
free_percpu(p->cpu_qstats);
kfree(p);
}
static void tcf_hash_destroy(struct tc_action *a)
{
struct tcf_common *p = a->priv;
struct tcf_hashinfo *hinfo = a->ops->hinfo;
spin_lock_bh(&hinfo->lock);
hlist_del(&p->tcfc_head);
spin_unlock_bh(&hinfo->lock);
gen_kill_estimator(&p->tcfc_bstats,
&p->tcfc_rate_est);
/*
* gen_estimator est_timer() might access p->tcfc_lock
* or bstats, wait a RCU grace period before freeing p
*/
call_rcu(&p->tcfc_rcu, free_tcf);
}
int __tcf_hash_release(struct tc_action *a, bool bind, bool strict)
{
struct tcf_common *p = a->priv;
int ret = 0;
if (p) {
if (bind)
p->tcfc_bindcnt--;
else if (strict && p->tcfc_bindcnt > 0)
return -EPERM;
p->tcfc_refcnt--;
if (p->tcfc_bindcnt <= 0 && p->tcfc_refcnt <= 0) {
if (a->ops->cleanup)
a->ops->cleanup(a, bind);
tcf_hash_destroy(a);
ret = 1;
}
}
return ret;
}
EXPORT_SYMBOL(__tcf_hash_release);
static int tcf_dump_walker(struct sk_buff *skb, struct netlink_callback *cb,
struct tc_action *a)
{
struct tcf_hashinfo *hinfo = a->ops->hinfo;
struct hlist_head *head;
struct tcf_common *p;
int err = 0, index = -1, i = 0, s_i = 0, n_i = 0;
struct nlattr *nest;
spin_lock_bh(&hinfo->lock);
s_i = cb->args[0];
for (i = 0; i < (hinfo->hmask + 1); i++) {
head = &hinfo->htab[tcf_hash(i, hinfo->hmask)];
hlist_for_each_entry_rcu(p, head, tcfc_head) {
index++;
if (index < s_i)
continue;
a->priv = p;
a->order = n_i;
nest = nla_nest_start(skb, a->order);
if (nest == NULL)
goto nla_put_failure;
err = tcf_action_dump_1(skb, a, 0, 0);
if (err < 0) {
index--;
nlmsg_trim(skb, nest);
goto done;
}
nla_nest_end(skb, nest);
n_i++;
if (n_i >= TCA_ACT_MAX_PRIO)
goto done;
}
}
done:
spin_unlock_bh(&hinfo->lock);
if (n_i)
cb->args[0] += n_i;
return n_i;
nla_put_failure:
nla_nest_cancel(skb, nest);
goto done;
}
static int tcf_del_walker(struct sk_buff *skb, struct tc_action *a)
{
struct tcf_hashinfo *hinfo = a->ops->hinfo;
struct hlist_head *head;
struct hlist_node *n;
struct tcf_common *p;
struct nlattr *nest;
int i = 0, n_i = 0;
int ret = -EINVAL;
nest = nla_nest_start(skb, a->order);
if (nest == NULL)
goto nla_put_failure;
if (nla_put_string(skb, TCA_KIND, a->ops->kind))
goto nla_put_failure;
for (i = 0; i < (hinfo->hmask + 1); i++) {
head = &hinfo->htab[tcf_hash(i, hinfo->hmask)];
hlist_for_each_entry_safe(p, n, head, tcfc_head) {
a->priv = p;
ret = __tcf_hash_release(a, false, true);
if (ret == ACT_P_DELETED) {
module_put(a->ops->owner);
n_i++;
} else if (ret < 0)
goto nla_put_failure;
}
}
if (nla_put_u32(skb, TCA_FCNT, n_i))
goto nla_put_failure;
nla_nest_end(skb, nest);
return n_i;
nla_put_failure:
nla_nest_cancel(skb, nest);
return ret;
}
static int tcf_generic_walker(struct sk_buff *skb, struct netlink_callback *cb,
int type, struct tc_action *a)
{
if (type == RTM_DELACTION) {
return tcf_del_walker(skb, a);
} else if (type == RTM_GETACTION) {
return tcf_dump_walker(skb, cb, a);
} else {
WARN(1, "tcf_generic_walker: unknown action %d\n", type);
return -EINVAL;
}
}
static struct tcf_common *tcf_hash_lookup(u32 index, struct tcf_hashinfo *hinfo)
{
struct tcf_common *p = NULL;
struct hlist_head *head;
spin_lock_bh(&hinfo->lock);
head = &hinfo->htab[tcf_hash(index, hinfo->hmask)];
hlist_for_each_entry_rcu(p, head, tcfc_head)
if (p->tcfc_index == index)
break;
spin_unlock_bh(&hinfo->lock);
return p;
}
u32 tcf_hash_new_index(struct tcf_hashinfo *hinfo)
{
u32 val = hinfo->index;
do {
if (++val == 0)
val = 1;
} while (tcf_hash_lookup(val, hinfo));
hinfo->index = val;
return val;
}
EXPORT_SYMBOL(tcf_hash_new_index);
int tcf_hash_search(struct tc_action *a, u32 index)
{
struct tcf_hashinfo *hinfo = a->ops->hinfo;
struct tcf_common *p = tcf_hash_lookup(index, hinfo);
if (p) {
a->priv = p;
return 1;
}
return 0;
}
EXPORT_SYMBOL(tcf_hash_search);
int tcf_hash_check(u32 index, struct tc_action *a, int bind)
{
struct tcf_hashinfo *hinfo = a->ops->hinfo;
struct tcf_common *p = NULL;
if (index && (p = tcf_hash_lookup(index, hinfo)) != NULL) {
if (bind)
p->tcfc_bindcnt++;
p->tcfc_refcnt++;
a->priv = p;
return 1;
}
return 0;
}
EXPORT_SYMBOL(tcf_hash_check);
void tcf_hash_cleanup(struct tc_action *a, struct nlattr *est)
{
struct tcf_common *pc = a->priv;
if (est)
gen_kill_estimator(&pc->tcfc_bstats,
&pc->tcfc_rate_est);
call_rcu(&pc->tcfc_rcu, free_tcf);
}
EXPORT_SYMBOL(tcf_hash_cleanup);
int tcf_hash_create(u32 index, struct nlattr *est, struct tc_action *a,
int size, int bind, bool cpustats)
{
struct tcf_hashinfo *hinfo = a->ops->hinfo;
struct tcf_common *p = kzalloc(size, GFP_KERNEL);
int err = -ENOMEM;
if (unlikely(!p))
return -ENOMEM;
p->tcfc_refcnt = 1;
if (bind)
p->tcfc_bindcnt = 1;
if (cpustats) {
p->cpu_bstats = netdev_alloc_pcpu_stats(struct gnet_stats_basic_cpu);
if (!p->cpu_bstats) {
err1:
kfree(p);
return err;
}
p->cpu_qstats = alloc_percpu(struct gnet_stats_queue);
if (!p->cpu_qstats) {
err2:
free_percpu(p->cpu_bstats);
goto err1;
}
}
spin_lock_init(&p->tcfc_lock);
INIT_HLIST_NODE(&p->tcfc_head);
p->tcfc_index = index ? index : tcf_hash_new_index(hinfo);
p->tcfc_tm.install = jiffies;
p->tcfc_tm.lastuse = jiffies;
if (est) {
err = gen_new_estimator(&p->tcfc_bstats, p->cpu_bstats,
&p->tcfc_rate_est,
&p->tcfc_lock, est);
if (err) {
free_percpu(p->cpu_qstats);
goto err2;
}
}
a->priv = (void *) p;
return 0;
}
EXPORT_SYMBOL(tcf_hash_create);
void tcf_hash_insert(struct tc_action *a)
{
struct tcf_common *p = a->priv;
struct tcf_hashinfo *hinfo = a->ops->hinfo;
unsigned int h = tcf_hash(p->tcfc_index, hinfo->hmask);
spin_lock_bh(&hinfo->lock);
hlist_add_head(&p->tcfc_head, &hinfo->htab[h]);
spin_unlock_bh(&hinfo->lock);
}
EXPORT_SYMBOL(tcf_hash_insert);
static LIST_HEAD(act_base);
static DEFINE_RWLOCK(act_mod_lock);
int tcf_register_action(struct tc_action_ops *act, unsigned int mask)
{
struct tc_action_ops *a;
int err;
/* Must supply act, dump and init */
if (!act->act || !act->dump || !act->init)
return -EINVAL;
/* Supply defaults */
if (!act->lookup)
act->lookup = tcf_hash_search;
if (!act->walk)
act->walk = tcf_generic_walker;
act->hinfo = kmalloc(sizeof(struct tcf_hashinfo), GFP_KERNEL);
if (!act->hinfo)
return -ENOMEM;
err = tcf_hashinfo_init(act->hinfo, mask);
if (err) {
kfree(act->hinfo);
return err;
}
write_lock(&act_mod_lock);
list_for_each_entry(a, &act_base, head) {
if (act->type == a->type || (strcmp(act->kind, a->kind) == 0)) {
write_unlock(&act_mod_lock);
tcf_hashinfo_destroy(act->hinfo);
kfree(act->hinfo);
return -EEXIST;
}
}
list_add_tail(&act->head, &act_base);
write_unlock(&act_mod_lock);
return 0;
}
EXPORT_SYMBOL(tcf_register_action);
int tcf_unregister_action(struct tc_action_ops *act)
{
struct tc_action_ops *a;
int err = -ENOENT;
write_lock(&act_mod_lock);
list_for_each_entry(a, &act_base, head) {
if (a == act) {
list_del(&act->head);
tcf_hashinfo_destroy(act->hinfo);
kfree(act->hinfo);
err = 0;
break;
}
}
write_unlock(&act_mod_lock);
return err;
}
EXPORT_SYMBOL(tcf_unregister_action);
/* lookup by name */
static struct tc_action_ops *tc_lookup_action_n(char *kind)
{
struct tc_action_ops *a, *res = NULL;
if (kind) {
read_lock(&act_mod_lock);
list_for_each_entry(a, &act_base, head) {
if (strcmp(kind, a->kind) == 0) {
if (try_module_get(a->owner))
res = a;
break;
}
}
read_unlock(&act_mod_lock);
}
return res;
}
/* lookup by nlattr */
static struct tc_action_ops *tc_lookup_action(struct nlattr *kind)
{
struct tc_action_ops *a, *res = NULL;
if (kind) {
read_lock(&act_mod_lock);
list_for_each_entry(a, &act_base, head) {
if (nla_strcmp(kind, a->kind) == 0) {
if (try_module_get(a->owner))
res = a;
break;
}
}
read_unlock(&act_mod_lock);
}
return res;
}
int tcf_action_exec(struct sk_buff *skb, const struct list_head *actions,
struct tcf_result *res)
{
const struct tc_action *a;
int ret = -1;
if (skb->tc_verd & TC_NCLS) {
skb->tc_verd = CLR_TC_NCLS(skb->tc_verd);
ret = TC_ACT_OK;
goto exec_done;
}
list_for_each_entry(a, actions, list) {
repeat:
ret = a->ops->act(skb, a, res);
if (ret == TC_ACT_REPEAT)
goto repeat; /* we need a ttl - JHS */
if (ret != TC_ACT_PIPE)
goto exec_done;
}
exec_done:
return ret;
}
EXPORT_SYMBOL(tcf_action_exec);
int tcf_action_destroy(struct list_head *actions, int bind)
{
struct tc_action *a, *tmp;
int ret = 0;
list_for_each_entry_safe(a, tmp, actions, list) {
ret = __tcf_hash_release(a, bind, true);
if (ret == ACT_P_DELETED)
module_put(a->ops->owner);
else if (ret < 0)
return ret;
list_del(&a->list);
kfree(a);
}
return ret;
}
int
tcf_action_dump_old(struct sk_buff *skb, struct tc_action *a, int bind, int ref)
{
return a->ops->dump(skb, a, bind, ref);
}
int
tcf_action_dump_1(struct sk_buff *skb, struct tc_action *a, int bind, int ref)
{
int err = -EINVAL;
unsigned char *b = skb_tail_pointer(skb);
struct nlattr *nest;
if (nla_put_string(skb, TCA_KIND, a->ops->kind))
goto nla_put_failure;
if (tcf_action_copy_stats(skb, a, 0))
goto nla_put_failure;
nest = nla_nest_start(skb, TCA_OPTIONS);
if (nest == NULL)
goto nla_put_failure;
err = tcf_action_dump_old(skb, a, bind, ref);
if (err > 0) {
nla_nest_end(skb, nest);
return err;
}
nla_put_failure:
nlmsg_trim(skb, b);
return -1;
}
EXPORT_SYMBOL(tcf_action_dump_1);
int
tcf_action_dump(struct sk_buff *skb, struct list_head *actions, int bind, int ref)
{
struct tc_action *a;
int err = -EINVAL;
struct nlattr *nest;
list_for_each_entry(a, actions, list) {
nest = nla_nest_start(skb, a->order);
if (nest == NULL)
goto nla_put_failure;
err = tcf_action_dump_1(skb, a, bind, ref);
if (err < 0)
goto errout;
nla_nest_end(skb, nest);
}
return 0;
nla_put_failure:
err = -EINVAL;
errout:
nla_nest_cancel(skb, nest);
return err;
}
struct tc_action *tcf_action_init_1(struct net *net, struct nlattr *nla,
struct nlattr *est, char *name, int ovr,
int bind)
{
struct tc_action *a;
struct tc_action_ops *a_o;
char act_name[IFNAMSIZ];
struct nlattr *tb[TCA_ACT_MAX + 1];
struct nlattr *kind;
int err;
if (name == NULL) {
err = nla_parse_nested(tb, TCA_ACT_MAX, nla, NULL);
if (err < 0)
goto err_out;
err = -EINVAL;
kind = tb[TCA_ACT_KIND];
if (kind == NULL)
goto err_out;
if (nla_strlcpy(act_name, kind, IFNAMSIZ) >= IFNAMSIZ)
goto err_out;
} else {
err = -EINVAL;
if (strlcpy(act_name, name, IFNAMSIZ) >= IFNAMSIZ)
goto err_out;
}
a_o = tc_lookup_action_n(act_name);
if (a_o == NULL) {
#ifdef CONFIG_MODULES
rtnl_unlock();
request_module("act_%s", act_name);
rtnl_lock();
a_o = tc_lookup_action_n(act_name);
/* We dropped the RTNL semaphore in order to
* perform the module load. So, even if we
* succeeded in loading the module we have to
* tell the caller to replay the request. We
* indicate this using -EAGAIN.
*/
if (a_o != NULL) {
err = -EAGAIN;
goto err_mod;
}
#endif
err = -ENOENT;
goto err_out;
}
err = -ENOMEM;
a = kzalloc(sizeof(*a), GFP_KERNEL);
if (a == NULL)
goto err_mod;
a->ops = a_o;
INIT_LIST_HEAD(&a->list);
/* backward compatibility for policer */
if (name == NULL)
err = a_o->init(net, tb[TCA_ACT_OPTIONS], est, a, ovr, bind);
else
err = a_o->init(net, nla, est, a, ovr, bind);
if (err < 0)
goto err_free;
/* module count goes up only when brand new policy is created
* if it exists and is only bound to in a_o->init() then
* ACT_P_CREATED is not returned (a zero is).
*/
if (err != ACT_P_CREATED)
module_put(a_o->owner);
return a;
err_free:
kfree(a);
err_mod:
module_put(a_o->owner);
err_out:
return ERR_PTR(err);
}
int tcf_action_init(struct net *net, struct nlattr *nla,
struct nlattr *est, char *name, int ovr,
int bind, struct list_head *actions)
{
struct nlattr *tb[TCA_ACT_MAX_PRIO + 1];
struct tc_action *act;
int err;
int i;
err = nla_parse_nested(tb, TCA_ACT_MAX_PRIO, nla, NULL);
if (err < 0)
return err;
for (i = 1; i <= TCA_ACT_MAX_PRIO && tb[i]; i++) {
act = tcf_action_init_1(net, tb[i], est, name, ovr, bind);
if (IS_ERR(act)) {
err = PTR_ERR(act);
goto err;
}
act->order = i;
list_add_tail(&act->list, actions);
}
return 0;
err:
tcf_action_destroy(actions, bind);
return err;
}
int tcf_action_copy_stats(struct sk_buff *skb, struct tc_action *a,
int compat_mode)
{
int err = 0;
struct gnet_dump d;
struct tcf_common *p = a->priv;
if (p == NULL)
goto errout;
/* compat_mode being true specifies a call that is supposed
* to add additional backward compatibility statistic TLVs.
*/
if (compat_mode) {
if (a->type == TCA_OLD_COMPAT)
err = gnet_stats_start_copy_compat(skb, 0,
TCA_STATS, TCA_XSTATS, &p->tcfc_lock, &d);
else
return 0;
} else
err = gnet_stats_start_copy(skb, TCA_ACT_STATS,
&p->tcfc_lock, &d);
if (err < 0)
goto errout;
if (gnet_stats_copy_basic(&d, p->cpu_bstats, &p->tcfc_bstats) < 0 ||
gnet_stats_copy_rate_est(&d, &p->tcfc_bstats,
&p->tcfc_rate_est) < 0 ||
gnet_stats_copy_queue(&d, p->cpu_qstats,
&p->tcfc_qstats,
p->tcfc_qstats.qlen) < 0)
goto errout;
if (gnet_stats_finish_copy(&d) < 0)
goto errout;
return 0;
errout:
return -1;
}
static int
tca_get_fill(struct sk_buff *skb, struct list_head *actions, u32 portid, u32 seq,
u16 flags, int event, int bind, int ref)
{
struct tcamsg *t;
struct nlmsghdr *nlh;
unsigned char *b = skb_tail_pointer(skb);
struct nlattr *nest;
nlh = nlmsg_put(skb, portid, seq, event, sizeof(*t), flags);
if (!nlh)
goto out_nlmsg_trim;
t = nlmsg_data(nlh);
t->tca_family = AF_UNSPEC;
t->tca__pad1 = 0;
t->tca__pad2 = 0;
nest = nla_nest_start(skb, TCA_ACT_TAB);
if (nest == NULL)
goto out_nlmsg_trim;
if (tcf_action_dump(skb, actions, bind, ref) < 0)
goto out_nlmsg_trim;
nla_nest_end(skb, nest);
nlh->nlmsg_len = skb_tail_pointer(skb) - b;
return skb->len;
out_nlmsg_trim:
nlmsg_trim(skb, b);
return -1;
}
static int
act_get_notify(struct net *net, u32 portid, struct nlmsghdr *n,
struct list_head *actions, int event)
{
struct sk_buff *skb;
skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb)
return -ENOBUFS;
if (tca_get_fill(skb, actions, portid, n->nlmsg_seq, 0, event, 0, 0) <= 0) {
kfree_skb(skb);
return -EINVAL;
}
return rtnl_unicast(skb, net, portid);
}
static struct tc_action *create_a(int i)
{
struct tc_action *act;
act = kzalloc(sizeof(*act), GFP_KERNEL);
if (act == NULL) {
pr_debug("create_a: failed to alloc!\n");
return NULL;
}
act->order = i;
INIT_LIST_HEAD(&act->list);
return act;
}
static struct tc_action *
tcf_action_get_1(struct nlattr *nla, struct nlmsghdr *n, u32 portid)
{
struct nlattr *tb[TCA_ACT_MAX + 1];
struct tc_action *a;
int index;
int err;
err = nla_parse_nested(tb, TCA_ACT_MAX, nla, NULL);
if (err < 0)
goto err_out;
err = -EINVAL;
if (tb[TCA_ACT_INDEX] == NULL ||
nla_len(tb[TCA_ACT_INDEX]) < sizeof(index))
goto err_out;
index = nla_get_u32(tb[TCA_ACT_INDEX]);
err = -ENOMEM;
a = create_a(0);
if (a == NULL)
goto err_out;
err = -EINVAL;
a->ops = tc_lookup_action(tb[TCA_ACT_KIND]);
if (a->ops == NULL) /* could happen in batch of actions */
goto err_free;
err = -ENOENT;
if (a->ops->lookup(a, index) == 0)
goto err_mod;
module_put(a->ops->owner);
return a;
err_mod:
module_put(a->ops->owner);
err_free:
kfree(a);
err_out:
return ERR_PTR(err);
}
static void cleanup_a(struct list_head *actions)
{
struct tc_action *a, *tmp;
list_for_each_entry_safe(a, tmp, actions, list) {
list_del(&a->list);
kfree(a);
}
}
static int tca_action_flush(struct net *net, struct nlattr *nla,
struct nlmsghdr *n, u32 portid)
{
struct sk_buff *skb;
unsigned char *b;
struct nlmsghdr *nlh;
struct tcamsg *t;
struct netlink_callback dcb;
struct nlattr *nest;
struct nlattr *tb[TCA_ACT_MAX + 1];
struct nlattr *kind;
struct tc_action a;
int err = -ENOMEM;
skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb) {
pr_debug("tca_action_flush: failed skb alloc\n");
return err;
}
b = skb_tail_pointer(skb);
err = nla_parse_nested(tb, TCA_ACT_MAX, nla, NULL);
if (err < 0)
goto err_out;
err = -EINVAL;
kind = tb[TCA_ACT_KIND];
memset(&a, 0, sizeof(struct tc_action));
INIT_LIST_HEAD(&a.list);
a.ops = tc_lookup_action(kind);
if (a.ops == NULL) /*some idjot trying to flush unknown action */
goto err_out;
nlh = nlmsg_put(skb, portid, n->nlmsg_seq, RTM_DELACTION, sizeof(*t), 0);
if (!nlh)
goto out_module_put;
t = nlmsg_data(nlh);
t->tca_family = AF_UNSPEC;
t->tca__pad1 = 0;
t->tca__pad2 = 0;
nest = nla_nest_start(skb, TCA_ACT_TAB);
if (nest == NULL)
goto out_module_put;
err = a.ops->walk(skb, &dcb, RTM_DELACTION, &a);
if (err < 0)
goto out_module_put;
if (err == 0)
goto noflush_out;
nla_nest_end(skb, nest);
nlh->nlmsg_len = skb_tail_pointer(skb) - b;
nlh->nlmsg_flags |= NLM_F_ROOT;
module_put(a.ops->owner);
err = rtnetlink_send(skb, net, portid, RTNLGRP_TC,
n->nlmsg_flags & NLM_F_ECHO);
if (err > 0)
return 0;
return err;
out_module_put:
module_put(a.ops->owner);
err_out:
noflush_out:
kfree_skb(skb);
return err;
}
static int
tcf_del_notify(struct net *net, struct nlmsghdr *n, struct list_head *actions,
u32 portid)
{
int ret;
struct sk_buff *skb;
skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb)
return -ENOBUFS;
if (tca_get_fill(skb, actions, portid, n->nlmsg_seq, 0, RTM_DELACTION,
0, 1) <= 0) {
kfree_skb(skb);
return -EINVAL;
}
/* now do the delete */
ret = tcf_action_destroy(actions, 0);
if (ret < 0) {
kfree_skb(skb);
return ret;
}
ret = rtnetlink_send(skb, net, portid, RTNLGRP_TC,
n->nlmsg_flags & NLM_F_ECHO);
if (ret > 0)
return 0;
return ret;
}
static int
tca_action_gd(struct net *net, struct nlattr *nla, struct nlmsghdr *n,
u32 portid, int event)
{
int i, ret;
struct nlattr *tb[TCA_ACT_MAX_PRIO + 1];
struct tc_action *act;
LIST_HEAD(actions);
ret = nla_parse_nested(tb, TCA_ACT_MAX_PRIO, nla, NULL);
if (ret < 0)
return ret;
if (event == RTM_DELACTION && n->nlmsg_flags & NLM_F_ROOT) {
if (tb[1] != NULL)
return tca_action_flush(net, tb[1], n, portid);
else
return -EINVAL;
}
for (i = 1; i <= TCA_ACT_MAX_PRIO && tb[i]; i++) {
act = tcf_action_get_1(tb[i], n, portid);
if (IS_ERR(act)) {
ret = PTR_ERR(act);
goto err;
}
act->order = i;
list_add_tail(&act->list, &actions);
}
if (event == RTM_GETACTION)
ret = act_get_notify(net, portid, n, &actions, event);
else { /* delete */
ret = tcf_del_notify(net, n, &actions, portid);
if (ret)
goto err;
return ret;
}
err:
cleanup_a(&actions);
return ret;
}
static int
tcf_add_notify(struct net *net, struct nlmsghdr *n, struct list_head *actions,
u32 portid)
{
struct sk_buff *skb;
int err = 0;
skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb)
return -ENOBUFS;
if (tca_get_fill(skb, actions, portid, n->nlmsg_seq, n->nlmsg_flags,
RTM_NEWACTION, 0, 0) <= 0) {
kfree_skb(skb);
return -EINVAL;
}
err = rtnetlink_send(skb, net, portid, RTNLGRP_TC,
n->nlmsg_flags & NLM_F_ECHO);
if (err > 0)
err = 0;
return err;
}
static int
tcf_action_add(struct net *net, struct nlattr *nla, struct nlmsghdr *n,
u32 portid, int ovr)
{
int ret = 0;
LIST_HEAD(actions);
ret = tcf_action_init(net, nla, NULL, NULL, ovr, 0, &actions);
if (ret)
goto done;
/* dump then free all the actions after update; inserted policy
* stays intact
*/
ret = tcf_add_notify(net, n, &actions, portid);
cleanup_a(&actions);
done:
return ret;
}
static int tc_ctl_action(struct sk_buff *skb, struct nlmsghdr *n)
{
struct net *net = sock_net(skb->sk);
struct nlattr *tca[TCA_ACT_MAX + 1];
u32 portid = skb ? NETLINK_CB(skb).portid : 0;
int ret = 0, ovr = 0;
if ((n->nlmsg_type != RTM_GETACTION) && !netlink_capable(skb, CAP_NET_ADMIN))
return -EPERM;
ret = nlmsg_parse(n, sizeof(struct tcamsg), tca, TCA_ACT_MAX, NULL);
if (ret < 0)
return ret;
if (tca[TCA_ACT_TAB] == NULL) {
pr_notice("tc_ctl_action: received NO action attribs\n");
return -EINVAL;
}
/* n->nlmsg_flags & NLM_F_CREATE */
switch (n->nlmsg_type) {
case RTM_NEWACTION:
/* we are going to assume all other flags
* imply create only if it doesn't exist
* Note that CREATE | EXCL implies that
* but since we want avoid ambiguity (eg when flags
* is zero) then just set this
*/
if (n->nlmsg_flags & NLM_F_REPLACE)
ovr = 1;
replay:
ret = tcf_action_add(net, tca[TCA_ACT_TAB], n, portid, ovr);
if (ret == -EAGAIN)
goto replay;
break;
case RTM_DELACTION:
ret = tca_action_gd(net, tca[TCA_ACT_TAB], n,
portid, RTM_DELACTION);
break;
case RTM_GETACTION:
ret = tca_action_gd(net, tca[TCA_ACT_TAB], n,
portid, RTM_GETACTION);
break;
default:
BUG();
}
return ret;
}
static struct nlattr *
find_dump_kind(const struct nlmsghdr *n)
{
struct nlattr *tb1, *tb2[TCA_ACT_MAX + 1];
struct nlattr *tb[TCA_ACT_MAX_PRIO + 1];
struct nlattr *nla[TCAA_MAX + 1];
struct nlattr *kind;
if (nlmsg_parse(n, sizeof(struct tcamsg), nla, TCAA_MAX, NULL) < 0)
return NULL;
tb1 = nla[TCA_ACT_TAB];
if (tb1 == NULL)
return NULL;
if (nla_parse(tb, TCA_ACT_MAX_PRIO, nla_data(tb1),
NLMSG_ALIGN(nla_len(tb1)), NULL) < 0)
return NULL;
if (tb[1] == NULL)
return NULL;
if (nla_parse(tb2, TCA_ACT_MAX, nla_data(tb[1]),
nla_len(tb[1]), NULL) < 0)
return NULL;
kind = tb2[TCA_ACT_KIND];
return kind;
}
static int
tc_dump_action(struct sk_buff *skb, struct netlink_callback *cb)
{
struct nlmsghdr *nlh;
unsigned char *b = skb_tail_pointer(skb);
struct nlattr *nest;
struct tc_action_ops *a_o;
struct tc_action a;
int ret = 0;
struct tcamsg *t = (struct tcamsg *) nlmsg_data(cb->nlh);
struct nlattr *kind = find_dump_kind(cb->nlh);
if (kind == NULL) {
pr_info("tc_dump_action: action bad kind\n");
return 0;
}
a_o = tc_lookup_action(kind);
if (a_o == NULL)
return 0;
memset(&a, 0, sizeof(struct tc_action));
a.ops = a_o;
nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
cb->nlh->nlmsg_type, sizeof(*t), 0);
if (!nlh)
goto out_module_put;
t = nlmsg_data(nlh);
t->tca_family = AF_UNSPEC;
t->tca__pad1 = 0;
t->tca__pad2 = 0;
nest = nla_nest_start(skb, TCA_ACT_TAB);
if (nest == NULL)
goto out_module_put;
ret = a_o->walk(skb, cb, RTM_GETACTION, &a);
if (ret < 0)
goto out_module_put;
if (ret > 0) {
nla_nest_end(skb, nest);
ret = skb->len;
} else
nla_nest_cancel(skb, nest);
nlh->nlmsg_len = skb_tail_pointer(skb) - b;
if (NETLINK_CB(cb->skb).portid && ret)
nlh->nlmsg_flags |= NLM_F_MULTI;
module_put(a_o->owner);
return skb->len;
out_module_put:
module_put(a_o->owner);
nlmsg_trim(skb, b);
return skb->len;
}
static int __init tc_action_init(void)
{
rtnl_register(PF_UNSPEC, RTM_NEWACTION, tc_ctl_action, NULL, NULL);
rtnl_register(PF_UNSPEC, RTM_DELACTION, tc_ctl_action, NULL, NULL);
rtnl_register(PF_UNSPEC, RTM_GETACTION, tc_ctl_action, tc_dump_action,
NULL);
return 0;
}
subsys_initcall(tc_action_init);
| gpl-2.0 |
jrfastab/hardware_maps | arch/arm64/kernel/cpu_ops.c | 380 | 2448 | /*
* CPU kernel entry/exit control
*
* Copyright (C) 2013 ARM Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/acpi.h>
#include <linux/errno.h>
#include <linux/of.h>
#include <linux/string.h>
#include <asm/acpi.h>
#include <asm/cpu_ops.h>
#include <asm/smp_plat.h>
extern const struct cpu_operations smp_spin_table_ops;
extern const struct cpu_operations cpu_psci_ops;
const struct cpu_operations *cpu_ops[NR_CPUS];
static const struct cpu_operations *supported_cpu_ops[] __initconst = {
&smp_spin_table_ops,
&cpu_psci_ops,
NULL,
};
static const struct cpu_operations * __init cpu_get_ops(const char *name)
{
const struct cpu_operations **ops = supported_cpu_ops;
while (*ops) {
if (!strcmp(name, (*ops)->name))
return *ops;
ops++;
}
return NULL;
}
static const char *__init cpu_read_enable_method(int cpu)
{
const char *enable_method;
if (acpi_disabled) {
struct device_node *dn = of_get_cpu_node(cpu, NULL);
if (!dn) {
if (!cpu)
pr_err("Failed to find device node for boot cpu\n");
return NULL;
}
enable_method = of_get_property(dn, "enable-method", NULL);
if (!enable_method) {
/*
* The boot CPU may not have an enable method (e.g.
* when spin-table is used for secondaries).
* Don't warn spuriously.
*/
if (cpu != 0)
pr_err("%s: missing enable-method property\n",
dn->full_name);
}
} else {
enable_method = acpi_get_enable_method(cpu);
if (!enable_method)
pr_err("Unsupported ACPI enable-method\n");
}
return enable_method;
}
/*
* Read a cpu's enable method and record it in cpu_ops.
*/
int __init cpu_read_ops(int cpu)
{
const char *enable_method = cpu_read_enable_method(cpu);
if (!enable_method)
return -ENODEV;
cpu_ops[cpu] = cpu_get_ops(enable_method);
if (!cpu_ops[cpu]) {
pr_warn("Unsupported enable-method: %s\n", enable_method);
return -EOPNOTSUPP;
}
return 0;
}
| gpl-2.0 |
namko/MID-Kernel-3.0 | kernel/compat.c | 1148 | 29617 | /*
* linux/kernel/compat.c
*
* Kernel compatibililty routines for e.g. 32 bit syscall support
* on 64 bit kernels.
*
* Copyright (C) 2002-2003 Stephen Rothwell, IBM Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/linkage.h>
#include <linux/compat.h>
#include <linux/errno.h>
#include <linux/time.h>
#include <linux/signal.h>
#include <linux/sched.h> /* for MAX_SCHEDULE_TIMEOUT */
#include <linux/syscalls.h>
#include <linux/unistd.h>
#include <linux/security.h>
#include <linux/timex.h>
#include <linux/migrate.h>
#include <linux/posix-timers.h>
#include <linux/times.h>
#include <linux/ptrace.h>
#include <linux/gfp.h>
#include <asm/uaccess.h>
/*
* Note that the native side is already converted to a timespec, because
* that's what we want anyway.
*/
static int compat_get_timeval(struct timespec *o,
struct compat_timeval __user *i)
{
long usec;
if (get_user(o->tv_sec, &i->tv_sec) ||
get_user(usec, &i->tv_usec))
return -EFAULT;
o->tv_nsec = usec * 1000;
return 0;
}
static int compat_put_timeval(struct compat_timeval __user *o,
struct timeval *i)
{
return (put_user(i->tv_sec, &o->tv_sec) ||
put_user(i->tv_usec, &o->tv_usec)) ? -EFAULT : 0;
}
static int compat_get_timex(struct timex *txc, struct compat_timex __user *utp)
{
memset(txc, 0, sizeof(struct timex));
if (!access_ok(VERIFY_READ, utp, sizeof(struct compat_timex)) ||
__get_user(txc->modes, &utp->modes) ||
__get_user(txc->offset, &utp->offset) ||
__get_user(txc->freq, &utp->freq) ||
__get_user(txc->maxerror, &utp->maxerror) ||
__get_user(txc->esterror, &utp->esterror) ||
__get_user(txc->status, &utp->status) ||
__get_user(txc->constant, &utp->constant) ||
__get_user(txc->precision, &utp->precision) ||
__get_user(txc->tolerance, &utp->tolerance) ||
__get_user(txc->time.tv_sec, &utp->time.tv_sec) ||
__get_user(txc->time.tv_usec, &utp->time.tv_usec) ||
__get_user(txc->tick, &utp->tick) ||
__get_user(txc->ppsfreq, &utp->ppsfreq) ||
__get_user(txc->jitter, &utp->jitter) ||
__get_user(txc->shift, &utp->shift) ||
__get_user(txc->stabil, &utp->stabil) ||
__get_user(txc->jitcnt, &utp->jitcnt) ||
__get_user(txc->calcnt, &utp->calcnt) ||
__get_user(txc->errcnt, &utp->errcnt) ||
__get_user(txc->stbcnt, &utp->stbcnt))
return -EFAULT;
return 0;
}
static int compat_put_timex(struct compat_timex __user *utp, struct timex *txc)
{
if (!access_ok(VERIFY_WRITE, utp, sizeof(struct compat_timex)) ||
__put_user(txc->modes, &utp->modes) ||
__put_user(txc->offset, &utp->offset) ||
__put_user(txc->freq, &utp->freq) ||
__put_user(txc->maxerror, &utp->maxerror) ||
__put_user(txc->esterror, &utp->esterror) ||
__put_user(txc->status, &utp->status) ||
__put_user(txc->constant, &utp->constant) ||
__put_user(txc->precision, &utp->precision) ||
__put_user(txc->tolerance, &utp->tolerance) ||
__put_user(txc->time.tv_sec, &utp->time.tv_sec) ||
__put_user(txc->time.tv_usec, &utp->time.tv_usec) ||
__put_user(txc->tick, &utp->tick) ||
__put_user(txc->ppsfreq, &utp->ppsfreq) ||
__put_user(txc->jitter, &utp->jitter) ||
__put_user(txc->shift, &utp->shift) ||
__put_user(txc->stabil, &utp->stabil) ||
__put_user(txc->jitcnt, &utp->jitcnt) ||
__put_user(txc->calcnt, &utp->calcnt) ||
__put_user(txc->errcnt, &utp->errcnt) ||
__put_user(txc->stbcnt, &utp->stbcnt) ||
__put_user(txc->tai, &utp->tai))
return -EFAULT;
return 0;
}
asmlinkage long compat_sys_gettimeofday(struct compat_timeval __user *tv,
struct timezone __user *tz)
{
if (tv) {
struct timeval ktv;
do_gettimeofday(&ktv);
if (compat_put_timeval(tv, &ktv))
return -EFAULT;
}
if (tz) {
if (copy_to_user(tz, &sys_tz, sizeof(sys_tz)))
return -EFAULT;
}
return 0;
}
asmlinkage long compat_sys_settimeofday(struct compat_timeval __user *tv,
struct timezone __user *tz)
{
struct timespec kts;
struct timezone ktz;
if (tv) {
if (compat_get_timeval(&kts, tv))
return -EFAULT;
}
if (tz) {
if (copy_from_user(&ktz, tz, sizeof(ktz)))
return -EFAULT;
}
return do_sys_settimeofday(tv ? &kts : NULL, tz ? &ktz : NULL);
}
int get_compat_timespec(struct timespec *ts, const struct compat_timespec __user *cts)
{
return (!access_ok(VERIFY_READ, cts, sizeof(*cts)) ||
__get_user(ts->tv_sec, &cts->tv_sec) ||
__get_user(ts->tv_nsec, &cts->tv_nsec)) ? -EFAULT : 0;
}
int put_compat_timespec(const struct timespec *ts, struct compat_timespec __user *cts)
{
return (!access_ok(VERIFY_WRITE, cts, sizeof(*cts)) ||
__put_user(ts->tv_sec, &cts->tv_sec) ||
__put_user(ts->tv_nsec, &cts->tv_nsec)) ? -EFAULT : 0;
}
static long compat_nanosleep_restart(struct restart_block *restart)
{
struct compat_timespec __user *rmtp;
struct timespec rmt;
mm_segment_t oldfs;
long ret;
restart->nanosleep.rmtp = (struct timespec __user *) &rmt;
oldfs = get_fs();
set_fs(KERNEL_DS);
ret = hrtimer_nanosleep_restart(restart);
set_fs(oldfs);
if (ret) {
rmtp = restart->nanosleep.compat_rmtp;
if (rmtp && put_compat_timespec(&rmt, rmtp))
return -EFAULT;
}
return ret;
}
asmlinkage long compat_sys_nanosleep(struct compat_timespec __user *rqtp,
struct compat_timespec __user *rmtp)
{
struct timespec tu, rmt;
mm_segment_t oldfs;
long ret;
if (get_compat_timespec(&tu, rqtp))
return -EFAULT;
if (!timespec_valid(&tu))
return -EINVAL;
oldfs = get_fs();
set_fs(KERNEL_DS);
ret = hrtimer_nanosleep(&tu,
rmtp ? (struct timespec __user *)&rmt : NULL,
HRTIMER_MODE_REL, CLOCK_MONOTONIC);
set_fs(oldfs);
if (ret) {
struct restart_block *restart
= ¤t_thread_info()->restart_block;
restart->fn = compat_nanosleep_restart;
restart->nanosleep.compat_rmtp = rmtp;
if (rmtp && put_compat_timespec(&rmt, rmtp))
return -EFAULT;
}
return ret;
}
static inline long get_compat_itimerval(struct itimerval *o,
struct compat_itimerval __user *i)
{
return (!access_ok(VERIFY_READ, i, sizeof(*i)) ||
(__get_user(o->it_interval.tv_sec, &i->it_interval.tv_sec) |
__get_user(o->it_interval.tv_usec, &i->it_interval.tv_usec) |
__get_user(o->it_value.tv_sec, &i->it_value.tv_sec) |
__get_user(o->it_value.tv_usec, &i->it_value.tv_usec)));
}
static inline long put_compat_itimerval(struct compat_itimerval __user *o,
struct itimerval *i)
{
return (!access_ok(VERIFY_WRITE, o, sizeof(*o)) ||
(__put_user(i->it_interval.tv_sec, &o->it_interval.tv_sec) |
__put_user(i->it_interval.tv_usec, &o->it_interval.tv_usec) |
__put_user(i->it_value.tv_sec, &o->it_value.tv_sec) |
__put_user(i->it_value.tv_usec, &o->it_value.tv_usec)));
}
asmlinkage long compat_sys_getitimer(int which,
struct compat_itimerval __user *it)
{
struct itimerval kit;
int error;
error = do_getitimer(which, &kit);
if (!error && put_compat_itimerval(it, &kit))
error = -EFAULT;
return error;
}
asmlinkage long compat_sys_setitimer(int which,
struct compat_itimerval __user *in,
struct compat_itimerval __user *out)
{
struct itimerval kin, kout;
int error;
if (in) {
if (get_compat_itimerval(&kin, in))
return -EFAULT;
} else
memset(&kin, 0, sizeof(kin));
error = do_setitimer(which, &kin, out ? &kout : NULL);
if (error || !out)
return error;
if (put_compat_itimerval(out, &kout))
return -EFAULT;
return 0;
}
static compat_clock_t clock_t_to_compat_clock_t(clock_t x)
{
return compat_jiffies_to_clock_t(clock_t_to_jiffies(x));
}
asmlinkage long compat_sys_times(struct compat_tms __user *tbuf)
{
if (tbuf) {
struct tms tms;
struct compat_tms tmp;
do_sys_times(&tms);
/* Convert our struct tms to the compat version. */
tmp.tms_utime = clock_t_to_compat_clock_t(tms.tms_utime);
tmp.tms_stime = clock_t_to_compat_clock_t(tms.tms_stime);
tmp.tms_cutime = clock_t_to_compat_clock_t(tms.tms_cutime);
tmp.tms_cstime = clock_t_to_compat_clock_t(tms.tms_cstime);
if (copy_to_user(tbuf, &tmp, sizeof(tmp)))
return -EFAULT;
}
force_successful_syscall_return();
return compat_jiffies_to_clock_t(jiffies);
}
#ifdef __ARCH_WANT_SYS_SIGPENDING
/*
* Assumption: old_sigset_t and compat_old_sigset_t are both
* types that can be passed to put_user()/get_user().
*/
asmlinkage long compat_sys_sigpending(compat_old_sigset_t __user *set)
{
old_sigset_t s;
long ret;
mm_segment_t old_fs = get_fs();
set_fs(KERNEL_DS);
ret = sys_sigpending((old_sigset_t __user *) &s);
set_fs(old_fs);
if (ret == 0)
ret = put_user(s, set);
return ret;
}
#endif
#ifdef __ARCH_WANT_SYS_SIGPROCMASK
/*
* sys_sigprocmask SIG_SETMASK sets the first (compat) word of the
* blocked set of signals to the supplied signal set
*/
static inline void compat_sig_setmask(sigset_t *blocked, compat_sigset_word set)
{
memcpy(blocked->sig, &set, sizeof(set));
}
asmlinkage long compat_sys_sigprocmask(int how,
compat_old_sigset_t __user *nset,
compat_old_sigset_t __user *oset)
{
old_sigset_t old_set, new_set;
sigset_t new_blocked;
old_set = current->blocked.sig[0];
if (nset) {
if (get_user(new_set, nset))
return -EFAULT;
new_set &= ~(sigmask(SIGKILL) | sigmask(SIGSTOP));
new_blocked = current->blocked;
switch (how) {
case SIG_BLOCK:
sigaddsetmask(&new_blocked, new_set);
break;
case SIG_UNBLOCK:
sigdelsetmask(&new_blocked, new_set);
break;
case SIG_SETMASK:
compat_sig_setmask(&new_blocked, new_set);
break;
default:
return -EINVAL;
}
set_current_blocked(&new_blocked);
}
if (oset) {
if (put_user(old_set, oset))
return -EFAULT;
}
return 0;
}
#endif
asmlinkage long compat_sys_setrlimit(unsigned int resource,
struct compat_rlimit __user *rlim)
{
struct rlimit r;
if (!access_ok(VERIFY_READ, rlim, sizeof(*rlim)) ||
__get_user(r.rlim_cur, &rlim->rlim_cur) ||
__get_user(r.rlim_max, &rlim->rlim_max))
return -EFAULT;
if (r.rlim_cur == COMPAT_RLIM_INFINITY)
r.rlim_cur = RLIM_INFINITY;
if (r.rlim_max == COMPAT_RLIM_INFINITY)
r.rlim_max = RLIM_INFINITY;
return do_prlimit(current, resource, &r, NULL);
}
#ifdef COMPAT_RLIM_OLD_INFINITY
asmlinkage long compat_sys_old_getrlimit(unsigned int resource,
struct compat_rlimit __user *rlim)
{
struct rlimit r;
int ret;
mm_segment_t old_fs = get_fs();
set_fs(KERNEL_DS);
ret = sys_old_getrlimit(resource, &r);
set_fs(old_fs);
if (!ret) {
if (r.rlim_cur > COMPAT_RLIM_OLD_INFINITY)
r.rlim_cur = COMPAT_RLIM_INFINITY;
if (r.rlim_max > COMPAT_RLIM_OLD_INFINITY)
r.rlim_max = COMPAT_RLIM_INFINITY;
if (!access_ok(VERIFY_WRITE, rlim, sizeof(*rlim)) ||
__put_user(r.rlim_cur, &rlim->rlim_cur) ||
__put_user(r.rlim_max, &rlim->rlim_max))
return -EFAULT;
}
return ret;
}
#endif
asmlinkage long compat_sys_getrlimit(unsigned int resource,
struct compat_rlimit __user *rlim)
{
struct rlimit r;
int ret;
ret = do_prlimit(current, resource, NULL, &r);
if (!ret) {
if (r.rlim_cur > COMPAT_RLIM_INFINITY)
r.rlim_cur = COMPAT_RLIM_INFINITY;
if (r.rlim_max > COMPAT_RLIM_INFINITY)
r.rlim_max = COMPAT_RLIM_INFINITY;
if (!access_ok(VERIFY_WRITE, rlim, sizeof(*rlim)) ||
__put_user(r.rlim_cur, &rlim->rlim_cur) ||
__put_user(r.rlim_max, &rlim->rlim_max))
return -EFAULT;
}
return ret;
}
int put_compat_rusage(const struct rusage *r, struct compat_rusage __user *ru)
{
if (!access_ok(VERIFY_WRITE, ru, sizeof(*ru)) ||
__put_user(r->ru_utime.tv_sec, &ru->ru_utime.tv_sec) ||
__put_user(r->ru_utime.tv_usec, &ru->ru_utime.tv_usec) ||
__put_user(r->ru_stime.tv_sec, &ru->ru_stime.tv_sec) ||
__put_user(r->ru_stime.tv_usec, &ru->ru_stime.tv_usec) ||
__put_user(r->ru_maxrss, &ru->ru_maxrss) ||
__put_user(r->ru_ixrss, &ru->ru_ixrss) ||
__put_user(r->ru_idrss, &ru->ru_idrss) ||
__put_user(r->ru_isrss, &ru->ru_isrss) ||
__put_user(r->ru_minflt, &ru->ru_minflt) ||
__put_user(r->ru_majflt, &ru->ru_majflt) ||
__put_user(r->ru_nswap, &ru->ru_nswap) ||
__put_user(r->ru_inblock, &ru->ru_inblock) ||
__put_user(r->ru_oublock, &ru->ru_oublock) ||
__put_user(r->ru_msgsnd, &ru->ru_msgsnd) ||
__put_user(r->ru_msgrcv, &ru->ru_msgrcv) ||
__put_user(r->ru_nsignals, &ru->ru_nsignals) ||
__put_user(r->ru_nvcsw, &ru->ru_nvcsw) ||
__put_user(r->ru_nivcsw, &ru->ru_nivcsw))
return -EFAULT;
return 0;
}
asmlinkage long compat_sys_getrusage(int who, struct compat_rusage __user *ru)
{
struct rusage r;
int ret;
mm_segment_t old_fs = get_fs();
set_fs(KERNEL_DS);
ret = sys_getrusage(who, (struct rusage __user *) &r);
set_fs(old_fs);
if (ret)
return ret;
if (put_compat_rusage(&r, ru))
return -EFAULT;
return 0;
}
asmlinkage long
compat_sys_wait4(compat_pid_t pid, compat_uint_t __user *stat_addr, int options,
struct compat_rusage __user *ru)
{
if (!ru) {
return sys_wait4(pid, stat_addr, options, NULL);
} else {
struct rusage r;
int ret;
unsigned int status;
mm_segment_t old_fs = get_fs();
set_fs (KERNEL_DS);
ret = sys_wait4(pid,
(stat_addr ?
(unsigned int __user *) &status : NULL),
options, (struct rusage __user *) &r);
set_fs (old_fs);
if (ret > 0) {
if (put_compat_rusage(&r, ru))
return -EFAULT;
if (stat_addr && put_user(status, stat_addr))
return -EFAULT;
}
return ret;
}
}
asmlinkage long compat_sys_waitid(int which, compat_pid_t pid,
struct compat_siginfo __user *uinfo, int options,
struct compat_rusage __user *uru)
{
siginfo_t info;
struct rusage ru;
long ret;
mm_segment_t old_fs = get_fs();
memset(&info, 0, sizeof(info));
set_fs(KERNEL_DS);
ret = sys_waitid(which, pid, (siginfo_t __user *)&info, options,
uru ? (struct rusage __user *)&ru : NULL);
set_fs(old_fs);
if ((ret < 0) || (info.si_signo == 0))
return ret;
if (uru) {
ret = put_compat_rusage(&ru, uru);
if (ret)
return ret;
}
BUG_ON(info.si_code & __SI_MASK);
info.si_code |= __SI_CHLD;
return copy_siginfo_to_user32(uinfo, &info);
}
static int compat_get_user_cpu_mask(compat_ulong_t __user *user_mask_ptr,
unsigned len, struct cpumask *new_mask)
{
unsigned long *k;
if (len < cpumask_size())
memset(new_mask, 0, cpumask_size());
else if (len > cpumask_size())
len = cpumask_size();
k = cpumask_bits(new_mask);
return compat_get_bitmap(k, user_mask_ptr, len * 8);
}
asmlinkage long compat_sys_sched_setaffinity(compat_pid_t pid,
unsigned int len,
compat_ulong_t __user *user_mask_ptr)
{
cpumask_var_t new_mask;
int retval;
if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
return -ENOMEM;
retval = compat_get_user_cpu_mask(user_mask_ptr, len, new_mask);
if (retval)
goto out;
retval = sched_setaffinity(pid, new_mask);
out:
free_cpumask_var(new_mask);
return retval;
}
asmlinkage long compat_sys_sched_getaffinity(compat_pid_t pid, unsigned int len,
compat_ulong_t __user *user_mask_ptr)
{
int ret;
cpumask_var_t mask;
if ((len * BITS_PER_BYTE) < nr_cpu_ids)
return -EINVAL;
if (len & (sizeof(compat_ulong_t)-1))
return -EINVAL;
if (!alloc_cpumask_var(&mask, GFP_KERNEL))
return -ENOMEM;
ret = sched_getaffinity(pid, mask);
if (ret == 0) {
size_t retlen = min_t(size_t, len, cpumask_size());
if (compat_put_bitmap(user_mask_ptr, cpumask_bits(mask), retlen * 8))
ret = -EFAULT;
else
ret = retlen;
}
free_cpumask_var(mask);
return ret;
}
int get_compat_itimerspec(struct itimerspec *dst,
const struct compat_itimerspec __user *src)
{
if (get_compat_timespec(&dst->it_interval, &src->it_interval) ||
get_compat_timespec(&dst->it_value, &src->it_value))
return -EFAULT;
return 0;
}
int put_compat_itimerspec(struct compat_itimerspec __user *dst,
const struct itimerspec *src)
{
if (put_compat_timespec(&src->it_interval, &dst->it_interval) ||
put_compat_timespec(&src->it_value, &dst->it_value))
return -EFAULT;
return 0;
}
long compat_sys_timer_create(clockid_t which_clock,
struct compat_sigevent __user *timer_event_spec,
timer_t __user *created_timer_id)
{
struct sigevent __user *event = NULL;
if (timer_event_spec) {
struct sigevent kevent;
event = compat_alloc_user_space(sizeof(*event));
if (get_compat_sigevent(&kevent, timer_event_spec) ||
copy_to_user(event, &kevent, sizeof(*event)))
return -EFAULT;
}
return sys_timer_create(which_clock, event, created_timer_id);
}
long compat_sys_timer_settime(timer_t timer_id, int flags,
struct compat_itimerspec __user *new,
struct compat_itimerspec __user *old)
{
long err;
mm_segment_t oldfs;
struct itimerspec newts, oldts;
if (!new)
return -EINVAL;
if (get_compat_itimerspec(&newts, new))
return -EFAULT;
oldfs = get_fs();
set_fs(KERNEL_DS);
err = sys_timer_settime(timer_id, flags,
(struct itimerspec __user *) &newts,
(struct itimerspec __user *) &oldts);
set_fs(oldfs);
if (!err && old && put_compat_itimerspec(old, &oldts))
return -EFAULT;
return err;
}
long compat_sys_timer_gettime(timer_t timer_id,
struct compat_itimerspec __user *setting)
{
long err;
mm_segment_t oldfs;
struct itimerspec ts;
oldfs = get_fs();
set_fs(KERNEL_DS);
err = sys_timer_gettime(timer_id,
(struct itimerspec __user *) &ts);
set_fs(oldfs);
if (!err && put_compat_itimerspec(setting, &ts))
return -EFAULT;
return err;
}
long compat_sys_clock_settime(clockid_t which_clock,
struct compat_timespec __user *tp)
{
long err;
mm_segment_t oldfs;
struct timespec ts;
if (get_compat_timespec(&ts, tp))
return -EFAULT;
oldfs = get_fs();
set_fs(KERNEL_DS);
err = sys_clock_settime(which_clock,
(struct timespec __user *) &ts);
set_fs(oldfs);
return err;
}
long compat_sys_clock_gettime(clockid_t which_clock,
struct compat_timespec __user *tp)
{
long err;
mm_segment_t oldfs;
struct timespec ts;
oldfs = get_fs();
set_fs(KERNEL_DS);
err = sys_clock_gettime(which_clock,
(struct timespec __user *) &ts);
set_fs(oldfs);
if (!err && put_compat_timespec(&ts, tp))
return -EFAULT;
return err;
}
long compat_sys_clock_adjtime(clockid_t which_clock,
struct compat_timex __user *utp)
{
struct timex txc;
mm_segment_t oldfs;
int err, ret;
err = compat_get_timex(&txc, utp);
if (err)
return err;
oldfs = get_fs();
set_fs(KERNEL_DS);
ret = sys_clock_adjtime(which_clock, (struct timex __user *) &txc);
set_fs(oldfs);
err = compat_put_timex(utp, &txc);
if (err)
return err;
return ret;
}
long compat_sys_clock_getres(clockid_t which_clock,
struct compat_timespec __user *tp)
{
long err;
mm_segment_t oldfs;
struct timespec ts;
oldfs = get_fs();
set_fs(KERNEL_DS);
err = sys_clock_getres(which_clock,
(struct timespec __user *) &ts);
set_fs(oldfs);
if (!err && tp && put_compat_timespec(&ts, tp))
return -EFAULT;
return err;
}
static long compat_clock_nanosleep_restart(struct restart_block *restart)
{
long err;
mm_segment_t oldfs;
struct timespec tu;
struct compat_timespec *rmtp = restart->nanosleep.compat_rmtp;
restart->nanosleep.rmtp = (struct timespec __user *) &tu;
oldfs = get_fs();
set_fs(KERNEL_DS);
err = clock_nanosleep_restart(restart);
set_fs(oldfs);
if ((err == -ERESTART_RESTARTBLOCK) && rmtp &&
put_compat_timespec(&tu, rmtp))
return -EFAULT;
if (err == -ERESTART_RESTARTBLOCK) {
restart->fn = compat_clock_nanosleep_restart;
restart->nanosleep.compat_rmtp = rmtp;
}
return err;
}
long compat_sys_clock_nanosleep(clockid_t which_clock, int flags,
struct compat_timespec __user *rqtp,
struct compat_timespec __user *rmtp)
{
long err;
mm_segment_t oldfs;
struct timespec in, out;
struct restart_block *restart;
if (get_compat_timespec(&in, rqtp))
return -EFAULT;
oldfs = get_fs();
set_fs(KERNEL_DS);
err = sys_clock_nanosleep(which_clock, flags,
(struct timespec __user *) &in,
(struct timespec __user *) &out);
set_fs(oldfs);
if ((err == -ERESTART_RESTARTBLOCK) && rmtp &&
put_compat_timespec(&out, rmtp))
return -EFAULT;
if (err == -ERESTART_RESTARTBLOCK) {
restart = ¤t_thread_info()->restart_block;
restart->fn = compat_clock_nanosleep_restart;
restart->nanosleep.compat_rmtp = rmtp;
}
return err;
}
/*
* We currently only need the following fields from the sigevent
* structure: sigev_value, sigev_signo, sig_notify and (sometimes
* sigev_notify_thread_id). The others are handled in user mode.
* We also assume that copying sigev_value.sival_int is sufficient
* to keep all the bits of sigev_value.sival_ptr intact.
*/
int get_compat_sigevent(struct sigevent *event,
const struct compat_sigevent __user *u_event)
{
memset(event, 0, sizeof(*event));
return (!access_ok(VERIFY_READ, u_event, sizeof(*u_event)) ||
__get_user(event->sigev_value.sival_int,
&u_event->sigev_value.sival_int) ||
__get_user(event->sigev_signo, &u_event->sigev_signo) ||
__get_user(event->sigev_notify, &u_event->sigev_notify) ||
__get_user(event->sigev_notify_thread_id,
&u_event->sigev_notify_thread_id))
? -EFAULT : 0;
}
long compat_get_bitmap(unsigned long *mask, const compat_ulong_t __user *umask,
unsigned long bitmap_size)
{
int i, j;
unsigned long m;
compat_ulong_t um;
unsigned long nr_compat_longs;
/* align bitmap up to nearest compat_long_t boundary */
bitmap_size = ALIGN(bitmap_size, BITS_PER_COMPAT_LONG);
if (!access_ok(VERIFY_READ, umask, bitmap_size / 8))
return -EFAULT;
nr_compat_longs = BITS_TO_COMPAT_LONGS(bitmap_size);
for (i = 0; i < BITS_TO_LONGS(bitmap_size); i++) {
m = 0;
for (j = 0; j < sizeof(m)/sizeof(um); j++) {
/*
* We dont want to read past the end of the userspace
* bitmap. We must however ensure the end of the
* kernel bitmap is zeroed.
*/
if (nr_compat_longs-- > 0) {
if (__get_user(um, umask))
return -EFAULT;
} else {
um = 0;
}
umask++;
m |= (long)um << (j * BITS_PER_COMPAT_LONG);
}
*mask++ = m;
}
return 0;
}
long compat_put_bitmap(compat_ulong_t __user *umask, unsigned long *mask,
unsigned long bitmap_size)
{
int i, j;
unsigned long m;
compat_ulong_t um;
unsigned long nr_compat_longs;
/* align bitmap up to nearest compat_long_t boundary */
bitmap_size = ALIGN(bitmap_size, BITS_PER_COMPAT_LONG);
if (!access_ok(VERIFY_WRITE, umask, bitmap_size / 8))
return -EFAULT;
nr_compat_longs = BITS_TO_COMPAT_LONGS(bitmap_size);
for (i = 0; i < BITS_TO_LONGS(bitmap_size); i++) {
m = *mask++;
for (j = 0; j < sizeof(m)/sizeof(um); j++) {
um = m;
/*
* We dont want to write past the end of the userspace
* bitmap.
*/
if (nr_compat_longs-- > 0) {
if (__put_user(um, umask))
return -EFAULT;
}
umask++;
m >>= 4*sizeof(um);
m >>= 4*sizeof(um);
}
}
return 0;
}
void
sigset_from_compat (sigset_t *set, compat_sigset_t *compat)
{
switch (_NSIG_WORDS) {
case 4: set->sig[3] = compat->sig[6] | (((long)compat->sig[7]) << 32 );
case 3: set->sig[2] = compat->sig[4] | (((long)compat->sig[5]) << 32 );
case 2: set->sig[1] = compat->sig[2] | (((long)compat->sig[3]) << 32 );
case 1: set->sig[0] = compat->sig[0] | (((long)compat->sig[1]) << 32 );
}
}
asmlinkage long
compat_sys_rt_sigtimedwait (compat_sigset_t __user *uthese,
struct compat_siginfo __user *uinfo,
struct compat_timespec __user *uts, compat_size_t sigsetsize)
{
compat_sigset_t s32;
sigset_t s;
struct timespec t;
siginfo_t info;
long ret;
if (sigsetsize != sizeof(sigset_t))
return -EINVAL;
if (copy_from_user(&s32, uthese, sizeof(compat_sigset_t)))
return -EFAULT;
sigset_from_compat(&s, &s32);
if (uts) {
if (get_compat_timespec(&t, uts))
return -EFAULT;
}
ret = do_sigtimedwait(&s, &info, uts ? &t : NULL);
if (ret > 0 && uinfo) {
if (copy_siginfo_to_user32(uinfo, &info))
ret = -EFAULT;
}
return ret;
}
asmlinkage long
compat_sys_rt_tgsigqueueinfo(compat_pid_t tgid, compat_pid_t pid, int sig,
struct compat_siginfo __user *uinfo)
{
siginfo_t info;
if (copy_siginfo_from_user32(&info, uinfo))
return -EFAULT;
return do_rt_tgsigqueueinfo(tgid, pid, sig, &info);
}
#ifdef __ARCH_WANT_COMPAT_SYS_TIME
/* compat_time_t is a 32 bit "long" and needs to get converted. */
asmlinkage long compat_sys_time(compat_time_t __user * tloc)
{
compat_time_t i;
struct timeval tv;
do_gettimeofday(&tv);
i = tv.tv_sec;
if (tloc) {
if (put_user(i,tloc))
return -EFAULT;
}
force_successful_syscall_return();
return i;
}
asmlinkage long compat_sys_stime(compat_time_t __user *tptr)
{
struct timespec tv;
int err;
if (get_user(tv.tv_sec, tptr))
return -EFAULT;
tv.tv_nsec = 0;
err = security_settime(&tv, NULL);
if (err)
return err;
do_settimeofday(&tv);
return 0;
}
#endif /* __ARCH_WANT_COMPAT_SYS_TIME */
#ifdef __ARCH_WANT_COMPAT_SYS_RT_SIGSUSPEND
asmlinkage long compat_sys_rt_sigsuspend(compat_sigset_t __user *unewset, compat_size_t sigsetsize)
{
sigset_t newset;
compat_sigset_t newset32;
/* XXX: Don't preclude handling different sized sigset_t's. */
if (sigsetsize != sizeof(sigset_t))
return -EINVAL;
if (copy_from_user(&newset32, unewset, sizeof(compat_sigset_t)))
return -EFAULT;
sigset_from_compat(&newset, &newset32);
sigdelsetmask(&newset, sigmask(SIGKILL)|sigmask(SIGSTOP));
spin_lock_irq(¤t->sighand->siglock);
current->saved_sigmask = current->blocked;
current->blocked = newset;
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
current->state = TASK_INTERRUPTIBLE;
schedule();
set_restore_sigmask();
return -ERESTARTNOHAND;
}
#endif /* __ARCH_WANT_COMPAT_SYS_RT_SIGSUSPEND */
asmlinkage long compat_sys_adjtimex(struct compat_timex __user *utp)
{
struct timex txc;
int err, ret;
err = compat_get_timex(&txc, utp);
if (err)
return err;
ret = do_adjtimex(&txc);
err = compat_put_timex(utp, &txc);
if (err)
return err;
return ret;
}
#ifdef CONFIG_NUMA
asmlinkage long compat_sys_move_pages(pid_t pid, unsigned long nr_pages,
compat_uptr_t __user *pages32,
const int __user *nodes,
int __user *status,
int flags)
{
const void __user * __user *pages;
int i;
pages = compat_alloc_user_space(nr_pages * sizeof(void *));
for (i = 0; i < nr_pages; i++) {
compat_uptr_t p;
if (get_user(p, pages32 + i) ||
put_user(compat_ptr(p), pages + i))
return -EFAULT;
}
return sys_move_pages(pid, nr_pages, pages, nodes, status, flags);
}
asmlinkage long compat_sys_migrate_pages(compat_pid_t pid,
compat_ulong_t maxnode,
const compat_ulong_t __user *old_nodes,
const compat_ulong_t __user *new_nodes)
{
unsigned long __user *old = NULL;
unsigned long __user *new = NULL;
nodemask_t tmp_mask;
unsigned long nr_bits;
unsigned long size;
nr_bits = min_t(unsigned long, maxnode - 1, MAX_NUMNODES);
size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
if (old_nodes) {
if (compat_get_bitmap(nodes_addr(tmp_mask), old_nodes, nr_bits))
return -EFAULT;
old = compat_alloc_user_space(new_nodes ? size * 2 : size);
if (new_nodes)
new = old + size / sizeof(unsigned long);
if (copy_to_user(old, nodes_addr(tmp_mask), size))
return -EFAULT;
}
if (new_nodes) {
if (compat_get_bitmap(nodes_addr(tmp_mask), new_nodes, nr_bits))
return -EFAULT;
if (new == NULL)
new = compat_alloc_user_space(size);
if (copy_to_user(new, nodes_addr(tmp_mask), size))
return -EFAULT;
}
return sys_migrate_pages(pid, nr_bits + 1, old, new);
}
#endif
struct compat_sysinfo {
s32 uptime;
u32 loads[3];
u32 totalram;
u32 freeram;
u32 sharedram;
u32 bufferram;
u32 totalswap;
u32 freeswap;
u16 procs;
u16 pad;
u32 totalhigh;
u32 freehigh;
u32 mem_unit;
char _f[20-2*sizeof(u32)-sizeof(int)];
};
asmlinkage long
compat_sys_sysinfo(struct compat_sysinfo __user *info)
{
struct sysinfo s;
do_sysinfo(&s);
/* Check to see if any memory value is too large for 32-bit and scale
* down if needed
*/
if ((s.totalram >> 32) || (s.totalswap >> 32)) {
int bitcount = 0;
while (s.mem_unit < PAGE_SIZE) {
s.mem_unit <<= 1;
bitcount++;
}
s.totalram >>= bitcount;
s.freeram >>= bitcount;
s.sharedram >>= bitcount;
s.bufferram >>= bitcount;
s.totalswap >>= bitcount;
s.freeswap >>= bitcount;
s.totalhigh >>= bitcount;
s.freehigh >>= bitcount;
}
if (!access_ok(VERIFY_WRITE, info, sizeof(struct compat_sysinfo)) ||
__put_user (s.uptime, &info->uptime) ||
__put_user (s.loads[0], &info->loads[0]) ||
__put_user (s.loads[1], &info->loads[1]) ||
__put_user (s.loads[2], &info->loads[2]) ||
__put_user (s.totalram, &info->totalram) ||
__put_user (s.freeram, &info->freeram) ||
__put_user (s.sharedram, &info->sharedram) ||
__put_user (s.bufferram, &info->bufferram) ||
__put_user (s.totalswap, &info->totalswap) ||
__put_user (s.freeswap, &info->freeswap) ||
__put_user (s.procs, &info->procs) ||
__put_user (s.totalhigh, &info->totalhigh) ||
__put_user (s.freehigh, &info->freehigh) ||
__put_user (s.mem_unit, &info->mem_unit))
return -EFAULT;
return 0;
}
/*
* Allocate user-space memory for the duration of a single system call,
* in order to marshall parameters inside a compat thunk.
*/
void __user *compat_alloc_user_space(unsigned long len)
{
void __user *ptr;
/* If len would occupy more than half of the entire compat space... */
if (unlikely(len > (((compat_uptr_t)~0) >> 1)))
return NULL;
ptr = arch_compat_alloc_user_space(len);
if (unlikely(!access_ok(VERIFY_WRITE, ptr, len)))
return NULL;
return ptr;
}
EXPORT_SYMBOL_GPL(compat_alloc_user_space);
| gpl-2.0 |
Skin1980/bass | drivers/char/hw_random/msm_fips_selftest.c | 1916 | 8911 | /*
* Copyright (c) 2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/string.h>
#include "fips_drbg.h"
#include "ctr_drbg.h"
#include "msm_rng.h"
#include "msm_fips_selftest.h"
#define CTRAES128_ENTROPY_BYTES (16)
#define CTRAES128_NONCE_BYTES (8)
#define CTRAES128_MAX_OUTPUT_BYTES (64)
struct ctr_drbg_testcase_s {
char *name;
char *entropy_string;
char *nonce_string;
char *reseed_entropy_string;
char *expected_string;
};
static struct ctr_drbg_testcase_s t0 = {
.name = "use_pr_0",
.entropy_string = "\x8f\xb9\x57\x3a\x54\x62\x53\xcd"
"\xbf\x62\x15\xa1\x80\x5a\x41\x38",
.nonce_string = "\x7c\x2c\xe6\x54\x02\xbc\xa6\x83",
.reseed_entropy_string = "\xbc\x5a\xd8\x9a\xe1\x8c\x49\x1f"
"\x90\xa2\xae\x9e\x7e\x2c\xf9\x9d",
.expected_string = "\x07\x62\x82\xe8\x0e\x65\xd7\x70"
"\x1a\x35\xb3\x44\x63\x68\xb6\x16"
"\xf8\xd9\x62\x23\xb9\xb5\x11\x64"
"\x23\xa3\xa2\x32\xc7\x2c\xea\xbf"
"\x4a\xcc\xc4\x0a\xc6\x19\xd6\xaa"
"\x68\xae\xdb\x8b\x26\x70\xb8\x07"
"\xcc\xe9\x9f\xc2\x1b\x8f\xa5\x16"
"\xef\x75\xb6\x8f\xc0\x6c\x87\xc7",
};
static struct ctr_drbg_testcase_s t1 = {
.name = "use_pr_1",
.entropy_string = "\xa3\x56\xf3\x9a\xce\x48\x59\xb1"
"\xe1\x99\x49\x40\x22\x8e\xa4\xeb",
.nonce_string = "\xff\x33\xe9\x51\x39\xf7\x67\xf1",
.reseed_entropy_string = "\x66\x8f\x0f\xe2\xd8\xa9\xa9\x29"
"\x20\xfc\xb9\xf3\x55\xd6\xc3\x4c",
.expected_string = "\xa1\x06\x61\x65\x7b\x98\x0f\xac"
"\xce\x77\x91\xde\x7f\x6f\xe6\x1e"
"\x88\x15\xe5\xe2\x4c\xce\xb8\xa6"
"\x63\xf2\xe8\x2f\x5b\xfb\x16\x92"
"\x06\x2a\xf3\xa8\x59\x05\xe0\x5a"
"\x92\x9a\x07\x65\xc7\x41\x29\x3a"
"\x4b\x1d\x15\x3e\x02\x14\x7b\xdd"
"\x74\x5e\xbd\x70\x07\x4d\x6c\x08",
};
static struct ctr_drbg_testcase_s *testlist[] = {
&t0, &t1
};
static int allzeroP(void *p, size_t len)
{
size_t i;
for (i = 0; i < len; ++i)
if (((uint8_t *)p)[i] != 0)
return 0;
return 1;
}
/*
* basic test. return value is error count.
*/
int fips_ctraes128_df_known_answer_test(struct ctr_debg_test_inputs_s *tcase)
{
struct ctr_drbg_ctx_s ctx;
enum ctr_drbg_status_t rv;
if (tcase->observed_string_len > CTRAES128_MAX_OUTPUT_BYTES) {
pr_debug("known answer test output is bigger than 64!\n");
return 1;
}
memset(&ctx, 0, sizeof(ctx));
ctx.continuous_test_started = 1;
rv = ctr_drbg_instantiate(&ctx,
tcase->entropy_string,
8 * CTRAES128_ENTROPY_BYTES,
tcase->nonce_string,
8 * CTRAES128_NONCE_BYTES,
1<<19);
if (rv != CTR_DRBG_SUCCESS) {
pr_err("test instantiate failed with code %d\n", rv);
return 1;
}
rv = ctr_drbg_reseed(&ctx,
tcase->reseed_entropy_string,
8 * CTRAES128_ENTROPY_BYTES);
if (rv != CTR_DRBG_SUCCESS) {
pr_err("test reseed failed with code %d\n", rv);
return 1;
}
rv = ctr_drbg_generate(&ctx,
tcase->observed_string,
tcase->observed_string_len * 8);
if (rv != CTR_DRBG_SUCCESS) {
pr_err("test generate (2) failed with code %d\n", rv);
return 1;
}
rv = ctr_drbg_generate(&ctx,
tcase->observed_string,
tcase->observed_string_len * 8);
if (rv != CTR_DRBG_SUCCESS) {
pr_err("test generate (2) failed with code %d\n", rv);
return 1;
}
ctr_drbg_uninstantiate(&ctx);
if (!allzeroP(&ctx.seed, sizeof(ctx.seed))) {
pr_err("test Final failed to zeroize the context\n");
return 1;
}
pr_info("\n DRBG counter test done");
return 0;
}
static int fips_drbg_healthcheck_sanitytest(void)
{
struct ctr_drbg_ctx_s *p_ctx = NULL;
enum ctr_drbg_status_t rv = CTR_DRBG_SUCCESS;
char entropy_string[MSM_ENTROPY_BUFFER_SIZE];
char nonce[MSM_NONCE_BUFFER_SIZE];
char buffer[32];
pr_info("start DRBG health check sanity test.\n");
p_ctx = kzalloc(sizeof(struct ctr_drbg_ctx_s), GFP_KERNEL);
if (NULL == p_ctx) {
rv = CTR_DRBG_GENERAL_ERROR;
pr_err("p_ctx kzalloc fail\n");
goto outbuf;
}
/*
* test DRGB Instantiaion function error handling.
* Sends a NULL pointer as DTR-DRBG context.
*/
rv = ctr_drbg_instantiate(NULL,
entropy_string,
8 * CTRAES128_ENTROPY_BYTES,
nonce,
8 * CTRAES128_NONCE_BYTES,
1<<19);
if (CTR_DRBG_SUCCESS == rv) {
rv = CTR_DRBG_INVALID_ARG;
pr_err("failed to handle NULL pointer of CTR context\n");
goto outbuf;
}
/*
* test DRGB Instantiaion function error handling.
* Sends a NULL pointer as entropy input.
*/
rv = ctr_drbg_instantiate(p_ctx,
NULL,
8 * CTRAES128_ENTROPY_BYTES,
nonce,
8 * CTRAES128_NONCE_BYTES,
1<<19);
if (CTR_DRBG_SUCCESS == rv) {
rv = CTR_DRBG_INVALID_ARG;
pr_err("failed to handle NULL pointer of entropy string\n");
goto outbuf;
}
rv = ctr_drbg_instantiate(p_ctx,
entropy_string,
8 * CTRAES128_ENTROPY_BYTES,
NULL,
8 * CTRAES128_NONCE_BYTES,
1<<19);
if (CTR_DRBG_SUCCESS == rv) {
rv = CTR_DRBG_INVALID_ARG;
pr_err("failed to handle NULL pointer of nonce string\n");
goto outbuf;
}
/*
* test DRGB Instantiaion function error handling.
* Sends very long seed length.
*/
rv = ctr_drbg_instantiate(p_ctx,
entropy_string,
8 * CTRAES128_ENTROPY_BYTES,
nonce,
32 * CTRAES128_NONCE_BYTES,
1<<19);
if (CTR_DRBG_SUCCESS == rv) {
rv = CTR_DRBG_INVALID_ARG;
pr_err("failed to handle incorrect seed size\n");
goto outbuf;
}
rv = ctr_drbg_instantiate(p_ctx,
entropy_string,
8 * CTRAES128_ENTROPY_BYTES,
nonce,
8 * CTRAES128_NONCE_BYTES,
1<<19);
if (CTR_DRBG_SUCCESS != rv) {
pr_err("Instantiation failed to handle CTR-DRBG instance\n");
goto outbuf;
}
/*
* test DRGB generator function error handling.
* set output string as NULL.
*/
rv = ctr_drbg_generate(p_ctx, NULL, 256);
if (CTR_DRBG_SUCCESS == rv) {
pr_err("failed to handle incorrect buffer pointer\n");
rv = CTR_DRBG_INVALID_ARG;
goto outdrbg;
}
rv = ctr_drbg_generate(p_ctx, &buffer, 1 << 20);
if (CTR_DRBG_SUCCESS == rv) {
pr_err("failed to handle too long output length\n");
rv = CTR_DRBG_INVALID_ARG;
goto outdrbg;
}
rv = ctr_drbg_generate(p_ctx, &buffer, 177);
if (CTR_DRBG_SUCCESS == rv) {
pr_err("failed to handle incorrect output length\n");
rv = CTR_DRBG_INVALID_ARG;
goto outdrbg;
}
pr_info("DRBG health check sanity test passed.\n");
rv = CTR_DRBG_SUCCESS;
outdrbg:
ctr_drbg_uninstantiate(p_ctx);
outbuf:
if (p_ctx)
kzfree(p_ctx);
p_ctx = NULL;
memset(buffer, 0, 32);
memset(nonce, 0, MSM_NONCE_BUFFER_SIZE);
memset(entropy_string, 0, MSM_ENTROPY_BUFFER_SIZE);
return rv;
}
int fips_self_test(void)
{
struct ctr_debg_test_inputs_s cavs_input;
uint8_t entropy[CTRAES128_ENTROPY_BYTES];
uint8_t nonce[CTRAES128_NONCE_BYTES];
uint8_t reseed_entropy[CTRAES128_ENTROPY_BYTES];
uint8_t expected[CTRAES128_MAX_OUTPUT_BYTES];
uint8_t observed[CTRAES128_MAX_OUTPUT_BYTES];
unsigned int i;
int errors = 0;
int ret;
cavs_input.entropy_string = entropy;
cavs_input.nonce_string = nonce;
cavs_input.reseed_entropy_string = reseed_entropy;
cavs_input.observed_string = observed;
cavs_input.observed_string_len = CTRAES128_MAX_OUTPUT_BYTES;
ret = fips_drbg_healthcheck_sanitytest();
if (CTR_DRBG_SUCCESS != ret) {
pr_err("DRBG health check fail\n");
errors++;
return errors;
}
for (i = 0;
i < sizeof(testlist)/sizeof(struct ctr_drbg_testcase_s *);
++i) {
memcpy(entropy,
testlist[i]->entropy_string,
CTRAES128_ENTROPY_BYTES);
memcpy(nonce,
testlist[i]->nonce_string,
CTRAES128_NONCE_BYTES);
memcpy(reseed_entropy,
testlist[i]->reseed_entropy_string,
CTRAES128_ENTROPY_BYTES);
memcpy(expected,
testlist[i]->expected_string,
CTRAES128_MAX_OUTPUT_BYTES);
pr_debug("starting test %s\n", testlist[i]->name);
ret = fips_ctraes128_df_known_answer_test(&cavs_input);
pr_debug("completed test %s\n\n", testlist[i]->name);
if (0 != ret) {
pr_debug("got error from drbg known answer test!\n");
return 1;
}
if (memcmp(expected,
cavs_input.observed_string,
CTRAES128_MAX_OUTPUT_BYTES) != 0) {
errors++;
pr_info("%s: generate failed\n", testlist[i]->name);
return 1;
} else
pr_info("%s: generate PASSED!\n", testlist[i]->name);
}
if (errors == 0)
pr_debug("All tests passed\n");
else
pr_debug("%d tests failed\n", errors);
return errors;
}
| gpl-2.0 |
olefb/android_kernel_sony_msm8974 | sound/soc/msm/qdsp6v2/msm-dai-stub-v2.c | 2172 | 2894 | /* Copyright (c) 2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
static int msm_dai_stub_set_channel_map(struct snd_soc_dai *dai,
unsigned int tx_num, unsigned int *tx_slot,
unsigned int rx_num, unsigned int *rx_slot)
{
pr_debug("%s:\n", __func__);
return 0;
}
static struct snd_soc_dai_ops msm_dai_stub_ops = {
.set_channel_map = msm_dai_stub_set_channel_map,
};
static struct snd_soc_dai_driver msm_dai_stub_dai = {
.playback = {
.rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 |
SNDRV_PCM_RATE_16000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 2,
.rate_min = 8000,
.rate_max = 48000,
},
.capture = {
.rates = SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_8000 |
SNDRV_PCM_RATE_16000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 1,
.channels_max = 2,
.rate_min = 8000,
.rate_max = 48000,
},
.ops = &msm_dai_stub_ops,
};
static __devinit int msm_dai_stub_dev_probe(struct platform_device *pdev)
{
int rc = 0;
dev_dbg(&pdev->dev, "dev name %s\n", dev_name(&pdev->dev));
if (pdev->dev.of_node)
dev_set_name(&pdev->dev, "%s", "msm-dai-stub");
pr_debug("%s: dev name %s\n", __func__, dev_name(&pdev->dev));
rc = snd_soc_register_dai(&pdev->dev, &msm_dai_stub_dai);
return rc;
}
static __devexit int msm_dai_stub_dev_remove(struct platform_device *pdev)
{
pr_debug("%s:\n", __func__);
snd_soc_unregister_dai(&pdev->dev);
return 0;
}
static const struct of_device_id msm_dai_stub_dt_match[] = {
{.compatible = "qcom,msm-dai-stub"},
{}
};
MODULE_DEVICE_TABLE(of, msm_dai_stub_dt_match);
static struct platform_driver msm_dai_stub_driver = {
.probe = msm_dai_stub_dev_probe,
.remove = msm_dai_stub_dev_remove,
.driver = {
.name = "msm-dai-stub",
.owner = THIS_MODULE,
.of_match_table = msm_dai_stub_dt_match,
},
};
static int __init msm_dai_stub_init(void)
{
pr_debug("%s:\n", __func__);
return platform_driver_register(&msm_dai_stub_driver);
}
module_init(msm_dai_stub_init);
static void __exit msm_dai_stub_exit(void)
{
pr_debug("%s:\n", __func__);
platform_driver_unregister(&msm_dai_stub_driver);
}
module_exit(msm_dai_stub_exit);
/* Module information */
MODULE_DESCRIPTION("MSM Stub DSP DAI driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
dwander/eas-backports | drivers/pinctrl/sh-pfc/pfc-sh7786.c | 2172 | 27283 | /*
* SH7786 Pinmux
*
* Copyright (C) 2008, 2009 Renesas Solutions Corp.
* Kuninori Morimoto <morimoto.kuninori@renesas.com>
*
* Based on SH7785 pinmux
*
* Copyright (C) 2008 Magnus Damm
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <cpu/sh7786.h>
#include "sh_pfc.h"
enum {
PINMUX_RESERVED = 0,
PINMUX_DATA_BEGIN,
PA7_DATA, PA6_DATA, PA5_DATA, PA4_DATA,
PA3_DATA, PA2_DATA, PA1_DATA, PA0_DATA,
PB7_DATA, PB6_DATA, PB5_DATA, PB4_DATA,
PB3_DATA, PB2_DATA, PB1_DATA, PB0_DATA,
PC7_DATA, PC6_DATA, PC5_DATA, PC4_DATA,
PC3_DATA, PC2_DATA, PC1_DATA, PC0_DATA,
PD7_DATA, PD6_DATA, PD5_DATA, PD4_DATA,
PD3_DATA, PD2_DATA, PD1_DATA, PD0_DATA,
PE7_DATA, PE6_DATA,
PF7_DATA, PF6_DATA, PF5_DATA, PF4_DATA,
PF3_DATA, PF2_DATA, PF1_DATA, PF0_DATA,
PG7_DATA, PG6_DATA, PG5_DATA,
PH7_DATA, PH6_DATA, PH5_DATA, PH4_DATA,
PH3_DATA, PH2_DATA, PH1_DATA, PH0_DATA,
PJ7_DATA, PJ6_DATA, PJ5_DATA, PJ4_DATA,
PJ3_DATA, PJ2_DATA, PJ1_DATA,
PINMUX_DATA_END,
PINMUX_INPUT_BEGIN,
PA7_IN, PA6_IN, PA5_IN, PA4_IN,
PA3_IN, PA2_IN, PA1_IN, PA0_IN,
PB7_IN, PB6_IN, PB5_IN, PB4_IN,
PB3_IN, PB2_IN, PB1_IN, PB0_IN,
PC7_IN, PC6_IN, PC5_IN, PC4_IN,
PC3_IN, PC2_IN, PC1_IN, PC0_IN,
PD7_IN, PD6_IN, PD5_IN, PD4_IN,
PD3_IN, PD2_IN, PD1_IN, PD0_IN,
PE7_IN, PE6_IN,
PF7_IN, PF6_IN, PF5_IN, PF4_IN,
PF3_IN, PF2_IN, PF1_IN, PF0_IN,
PG7_IN, PG6_IN, PG5_IN,
PH7_IN, PH6_IN, PH5_IN, PH4_IN,
PH3_IN, PH2_IN, PH1_IN, PH0_IN,
PJ7_IN, PJ6_IN, PJ5_IN, PJ4_IN,
PJ3_IN, PJ2_IN, PJ1_IN,
PINMUX_INPUT_END,
PINMUX_INPUT_PULLUP_BEGIN,
PA7_IN_PU, PA6_IN_PU, PA5_IN_PU, PA4_IN_PU,
PA3_IN_PU, PA2_IN_PU, PA1_IN_PU, PA0_IN_PU,
PB7_IN_PU, PB6_IN_PU, PB5_IN_PU, PB4_IN_PU,
PB3_IN_PU, PB2_IN_PU, PB1_IN_PU, PB0_IN_PU,
PC7_IN_PU, PC6_IN_PU, PC5_IN_PU, PC4_IN_PU,
PC3_IN_PU, PC2_IN_PU, PC1_IN_PU, PC0_IN_PU,
PD7_IN_PU, PD6_IN_PU, PD5_IN_PU, PD4_IN_PU,
PD3_IN_PU, PD2_IN_PU, PD1_IN_PU, PD0_IN_PU,
PE7_IN_PU, PE6_IN_PU,
PF7_IN_PU, PF6_IN_PU, PF5_IN_PU, PF4_IN_PU,
PF3_IN_PU, PF2_IN_PU, PF1_IN_PU, PF0_IN_PU,
PG7_IN_PU, PG6_IN_PU, PG5_IN_PU,
PH7_IN_PU, PH6_IN_PU, PH5_IN_PU, PH4_IN_PU,
PH3_IN_PU, PH2_IN_PU, PH1_IN_PU, PH0_IN_PU,
PJ7_IN_PU, PJ6_IN_PU, PJ5_IN_PU, PJ4_IN_PU,
PJ3_IN_PU, PJ2_IN_PU, PJ1_IN_PU,
PINMUX_INPUT_PULLUP_END,
PINMUX_OUTPUT_BEGIN,
PA7_OUT, PA6_OUT, PA5_OUT, PA4_OUT,
PA3_OUT, PA2_OUT, PA1_OUT, PA0_OUT,
PB7_OUT, PB6_OUT, PB5_OUT, PB4_OUT,
PB3_OUT, PB2_OUT, PB1_OUT, PB0_OUT,
PC7_OUT, PC6_OUT, PC5_OUT, PC4_OUT,
PC3_OUT, PC2_OUT, PC1_OUT, PC0_OUT,
PD7_OUT, PD6_OUT, PD5_OUT, PD4_OUT,
PD3_OUT, PD2_OUT, PD1_OUT, PD0_OUT,
PE7_OUT, PE6_OUT,
PF7_OUT, PF6_OUT, PF5_OUT, PF4_OUT,
PF3_OUT, PF2_OUT, PF1_OUT, PF0_OUT,
PG7_OUT, PG6_OUT, PG5_OUT,
PH7_OUT, PH6_OUT, PH5_OUT, PH4_OUT,
PH3_OUT, PH2_OUT, PH1_OUT, PH0_OUT,
PJ7_OUT, PJ6_OUT, PJ5_OUT, PJ4_OUT,
PJ3_OUT, PJ2_OUT, PJ1_OUT,
PINMUX_OUTPUT_END,
PINMUX_FUNCTION_BEGIN,
PA7_FN, PA6_FN, PA5_FN, PA4_FN,
PA3_FN, PA2_FN, PA1_FN, PA0_FN,
PB7_FN, PB6_FN, PB5_FN, PB4_FN,
PB3_FN, PB2_FN, PB1_FN, PB0_FN,
PC7_FN, PC6_FN, PC5_FN, PC4_FN,
PC3_FN, PC2_FN, PC1_FN, PC0_FN,
PD7_FN, PD6_FN, PD5_FN, PD4_FN,
PD3_FN, PD2_FN, PD1_FN, PD0_FN,
PE7_FN, PE6_FN,
PF7_FN, PF6_FN, PF5_FN, PF4_FN,
PF3_FN, PF2_FN, PF1_FN, PF0_FN,
PG7_FN, PG6_FN, PG5_FN,
PH7_FN, PH6_FN, PH5_FN, PH4_FN,
PH3_FN, PH2_FN, PH1_FN, PH0_FN,
PJ7_FN, PJ6_FN, PJ5_FN, PJ4_FN,
PJ3_FN, PJ2_FN, PJ1_FN,
P1MSEL14_0, P1MSEL14_1,
P1MSEL13_0, P1MSEL13_1,
P1MSEL12_0, P1MSEL12_1,
P1MSEL11_0, P1MSEL11_1,
P1MSEL10_0, P1MSEL10_1,
P1MSEL9_0, P1MSEL9_1,
P1MSEL8_0, P1MSEL8_1,
P1MSEL7_0, P1MSEL7_1,
P1MSEL6_0, P1MSEL6_1,
P1MSEL5_0, P1MSEL5_1,
P1MSEL4_0, P1MSEL4_1,
P1MSEL3_0, P1MSEL3_1,
P1MSEL2_0, P1MSEL2_1,
P1MSEL1_0, P1MSEL1_1,
P1MSEL0_0, P1MSEL0_1,
P2MSEL15_0, P2MSEL15_1,
P2MSEL14_0, P2MSEL14_1,
P2MSEL13_0, P2MSEL13_1,
P2MSEL12_0, P2MSEL12_1,
P2MSEL11_0, P2MSEL11_1,
P2MSEL10_0, P2MSEL10_1,
P2MSEL9_0, P2MSEL9_1,
P2MSEL8_0, P2MSEL8_1,
P2MSEL7_0, P2MSEL7_1,
P2MSEL6_0, P2MSEL6_1,
P2MSEL5_0, P2MSEL5_1,
P2MSEL4_0, P2MSEL4_1,
P2MSEL3_0, P2MSEL3_1,
P2MSEL2_0, P2MSEL2_1,
P2MSEL1_0, P2MSEL1_1,
P2MSEL0_0, P2MSEL0_1,
PINMUX_FUNCTION_END,
PINMUX_MARK_BEGIN,
DCLKIN_MARK, DCLKOUT_MARK, ODDF_MARK,
VSYNC_MARK, HSYNC_MARK, CDE_MARK, DISP_MARK,
DR0_MARK, DR1_MARK, DR2_MARK, DR3_MARK, DR4_MARK, DR5_MARK,
DG0_MARK, DG1_MARK, DG2_MARK, DG3_MARK, DG4_MARK, DG5_MARK,
DB0_MARK, DB1_MARK, DB2_MARK, DB3_MARK, DB4_MARK, DB5_MARK,
ETH_MAGIC_MARK, ETH_LINK_MARK, ETH_TX_ER_MARK, ETH_TX_EN_MARK,
ETH_MDIO_MARK, ETH_RX_CLK_MARK, ETH_MDC_MARK, ETH_COL_MARK,
ETH_TX_CLK_MARK, ETH_CRS_MARK, ETH_RX_DV_MARK, ETH_RX_ER_MARK,
ETH_TXD3_MARK, ETH_TXD2_MARK, ETH_TXD1_MARK, ETH_TXD0_MARK,
ETH_RXD3_MARK, ETH_RXD2_MARK, ETH_RXD1_MARK, ETH_RXD0_MARK,
HSPI_CLK_MARK, HSPI_CS_MARK, HSPI_RX_MARK, HSPI_TX_MARK,
SCIF0_CTS_MARK, SCIF0_RTS_MARK,
SCIF0_SCK_MARK, SCIF0_RXD_MARK, SCIF0_TXD_MARK,
SCIF1_SCK_MARK, SCIF1_RXD_MARK, SCIF1_TXD_MARK,
SCIF3_SCK_MARK, SCIF3_RXD_MARK, SCIF3_TXD_MARK,
SCIF4_SCK_MARK, SCIF4_RXD_MARK, SCIF4_TXD_MARK,
SCIF5_SCK_MARK, SCIF5_RXD_MARK, SCIF5_TXD_MARK,
BREQ_MARK, IOIS16_MARK, CE2B_MARK, CE2A_MARK, BACK_MARK,
FALE_MARK, FRB_MARK, FSTATUS_MARK,
FSE_MARK, FCLE_MARK,
DACK0_MARK, DACK1_MARK, DACK2_MARK, DACK3_MARK,
DREQ0_MARK, DREQ1_MARK, DREQ2_MARK, DREQ3_MARK,
DRAK0_MARK, DRAK1_MARK, DRAK2_MARK, DRAK3_MARK,
USB_OVC1_MARK, USB_OVC0_MARK,
USB_PENC1_MARK, USB_PENC0_MARK,
HAC_RES_MARK,
HAC1_SDOUT_MARK, HAC1_SDIN_MARK, HAC1_SYNC_MARK, HAC1_BITCLK_MARK,
HAC0_SDOUT_MARK, HAC0_SDIN_MARK, HAC0_SYNC_MARK, HAC0_BITCLK_MARK,
SSI0_SDATA_MARK, SSI0_SCK_MARK, SSI0_WS_MARK, SSI0_CLK_MARK,
SSI1_SDATA_MARK, SSI1_SCK_MARK, SSI1_WS_MARK, SSI1_CLK_MARK,
SSI2_SDATA_MARK, SSI2_SCK_MARK, SSI2_WS_MARK,
SSI3_SDATA_MARK, SSI3_SCK_MARK, SSI3_WS_MARK,
SDIF1CMD_MARK, SDIF1CD_MARK, SDIF1WP_MARK, SDIF1CLK_MARK,
SDIF1D3_MARK, SDIF1D2_MARK, SDIF1D1_MARK, SDIF1D0_MARK,
SDIF0CMD_MARK, SDIF0CD_MARK, SDIF0WP_MARK, SDIF0CLK_MARK,
SDIF0D3_MARK, SDIF0D2_MARK, SDIF0D1_MARK, SDIF0D0_MARK,
TCLK_MARK,
IRL7_MARK, IRL6_MARK, IRL5_MARK, IRL4_MARK,
PINMUX_MARK_END,
};
static const pinmux_enum_t pinmux_data[] = {
/* PA GPIO */
PINMUX_DATA(PA7_DATA, PA7_IN, PA7_OUT, PA7_IN_PU),
PINMUX_DATA(PA6_DATA, PA6_IN, PA6_OUT, PA6_IN_PU),
PINMUX_DATA(PA5_DATA, PA5_IN, PA5_OUT, PA5_IN_PU),
PINMUX_DATA(PA4_DATA, PA4_IN, PA4_OUT, PA4_IN_PU),
PINMUX_DATA(PA3_DATA, PA3_IN, PA3_OUT, PA3_IN_PU),
PINMUX_DATA(PA2_DATA, PA2_IN, PA2_OUT, PA2_IN_PU),
PINMUX_DATA(PA1_DATA, PA1_IN, PA1_OUT, PA1_IN_PU),
PINMUX_DATA(PA0_DATA, PA0_IN, PA0_OUT, PA0_IN_PU),
/* PB GPIO */
PINMUX_DATA(PB7_DATA, PB7_IN, PB7_OUT, PB7_IN_PU),
PINMUX_DATA(PB6_DATA, PB6_IN, PB6_OUT, PB6_IN_PU),
PINMUX_DATA(PB5_DATA, PB5_IN, PB5_OUT, PB5_IN_PU),
PINMUX_DATA(PB4_DATA, PB4_IN, PB4_OUT, PB4_IN_PU),
PINMUX_DATA(PB3_DATA, PB3_IN, PB3_OUT, PB3_IN_PU),
PINMUX_DATA(PB2_DATA, PB2_IN, PB2_OUT, PB2_IN_PU),
PINMUX_DATA(PB1_DATA, PB1_IN, PB1_OUT, PB1_IN_PU),
PINMUX_DATA(PB0_DATA, PB0_IN, PB0_OUT, PB0_IN_PU),
/* PC GPIO */
PINMUX_DATA(PC7_DATA, PC7_IN, PC7_OUT, PC7_IN_PU),
PINMUX_DATA(PC6_DATA, PC6_IN, PC6_OUT, PC6_IN_PU),
PINMUX_DATA(PC5_DATA, PC5_IN, PC5_OUT, PC5_IN_PU),
PINMUX_DATA(PC4_DATA, PC4_IN, PC4_OUT, PC4_IN_PU),
PINMUX_DATA(PC3_DATA, PC3_IN, PC3_OUT, PC3_IN_PU),
PINMUX_DATA(PC2_DATA, PC2_IN, PC2_OUT, PC2_IN_PU),
PINMUX_DATA(PC1_DATA, PC1_IN, PC1_OUT, PC1_IN_PU),
PINMUX_DATA(PC0_DATA, PC0_IN, PC0_OUT, PC0_IN_PU),
/* PD GPIO */
PINMUX_DATA(PD7_DATA, PD7_IN, PD7_OUT, PD7_IN_PU),
PINMUX_DATA(PD6_DATA, PD6_IN, PD6_OUT, PD6_IN_PU),
PINMUX_DATA(PD5_DATA, PD5_IN, PD5_OUT, PD5_IN_PU),
PINMUX_DATA(PD4_DATA, PD4_IN, PD4_OUT, PD4_IN_PU),
PINMUX_DATA(PD3_DATA, PD3_IN, PD3_OUT, PD3_IN_PU),
PINMUX_DATA(PD2_DATA, PD2_IN, PD2_OUT, PD2_IN_PU),
PINMUX_DATA(PD1_DATA, PD1_IN, PD1_OUT, PD1_IN_PU),
PINMUX_DATA(PD0_DATA, PD0_IN, PD0_OUT, PD0_IN_PU),
/* PE GPIO */
PINMUX_DATA(PE7_DATA, PE7_IN, PE7_OUT, PE7_IN_PU),
PINMUX_DATA(PE6_DATA, PE6_IN, PE6_OUT, PE6_IN_PU),
/* PF GPIO */
PINMUX_DATA(PF7_DATA, PF7_IN, PF7_OUT, PF7_IN_PU),
PINMUX_DATA(PF6_DATA, PF6_IN, PF6_OUT, PF6_IN_PU),
PINMUX_DATA(PF5_DATA, PF5_IN, PF5_OUT, PF5_IN_PU),
PINMUX_DATA(PF4_DATA, PF4_IN, PF4_OUT, PF4_IN_PU),
PINMUX_DATA(PF3_DATA, PF3_IN, PF3_OUT, PF3_IN_PU),
PINMUX_DATA(PF2_DATA, PF2_IN, PF2_OUT, PF2_IN_PU),
PINMUX_DATA(PF1_DATA, PF1_IN, PF1_OUT, PF1_IN_PU),
PINMUX_DATA(PF0_DATA, PF0_IN, PF0_OUT, PF0_IN_PU),
/* PG GPIO */
PINMUX_DATA(PG7_DATA, PG7_IN, PG7_OUT, PG7_IN_PU),
PINMUX_DATA(PG6_DATA, PG6_IN, PG6_OUT, PG6_IN_PU),
PINMUX_DATA(PG5_DATA, PG5_IN, PG5_OUT, PG5_IN_PU),
/* PH GPIO */
PINMUX_DATA(PH7_DATA, PH7_IN, PH7_OUT, PH7_IN_PU),
PINMUX_DATA(PH6_DATA, PH6_IN, PH6_OUT, PH6_IN_PU),
PINMUX_DATA(PH5_DATA, PH5_IN, PH5_OUT, PH5_IN_PU),
PINMUX_DATA(PH4_DATA, PH4_IN, PH4_OUT, PH4_IN_PU),
PINMUX_DATA(PH3_DATA, PH3_IN, PH3_OUT, PH3_IN_PU),
PINMUX_DATA(PH2_DATA, PH2_IN, PH2_OUT, PH2_IN_PU),
PINMUX_DATA(PH1_DATA, PH1_IN, PH1_OUT, PH1_IN_PU),
PINMUX_DATA(PH0_DATA, PH0_IN, PH0_OUT, PH0_IN_PU),
/* PJ GPIO */
PINMUX_DATA(PJ7_DATA, PJ7_IN, PJ7_OUT, PJ7_IN_PU),
PINMUX_DATA(PJ6_DATA, PJ6_IN, PJ6_OUT, PJ6_IN_PU),
PINMUX_DATA(PJ5_DATA, PJ5_IN, PJ5_OUT, PJ5_IN_PU),
PINMUX_DATA(PJ4_DATA, PJ4_IN, PJ4_OUT, PJ4_IN_PU),
PINMUX_DATA(PJ3_DATA, PJ3_IN, PJ3_OUT, PJ3_IN_PU),
PINMUX_DATA(PJ2_DATA, PJ2_IN, PJ2_OUT, PJ2_IN_PU),
PINMUX_DATA(PJ1_DATA, PJ1_IN, PJ1_OUT, PJ1_IN_PU),
/* PA FN */
PINMUX_DATA(CDE_MARK, P1MSEL2_0, PA7_FN),
PINMUX_DATA(DISP_MARK, P1MSEL2_0, PA6_FN),
PINMUX_DATA(DR5_MARK, P1MSEL2_0, PA5_FN),
PINMUX_DATA(DR4_MARK, P1MSEL2_0, PA4_FN),
PINMUX_DATA(DR3_MARK, P1MSEL2_0, PA3_FN),
PINMUX_DATA(DR2_MARK, P1MSEL2_0, PA2_FN),
PINMUX_DATA(DR1_MARK, P1MSEL2_0, PA1_FN),
PINMUX_DATA(DR0_MARK, P1MSEL2_0, PA0_FN),
PINMUX_DATA(ETH_MAGIC_MARK, P1MSEL2_1, PA7_FN),
PINMUX_DATA(ETH_LINK_MARK, P1MSEL2_1, PA6_FN),
PINMUX_DATA(ETH_TX_ER_MARK, P1MSEL2_1, PA5_FN),
PINMUX_DATA(ETH_TX_EN_MARK, P1MSEL2_1, PA4_FN),
PINMUX_DATA(ETH_TXD3_MARK, P1MSEL2_1, PA3_FN),
PINMUX_DATA(ETH_TXD2_MARK, P1MSEL2_1, PA2_FN),
PINMUX_DATA(ETH_TXD1_MARK, P1MSEL2_1, PA1_FN),
PINMUX_DATA(ETH_TXD0_MARK, P1MSEL2_1, PA0_FN),
/* PB FN */
PINMUX_DATA(VSYNC_MARK, P1MSEL3_0, PB7_FN),
PINMUX_DATA(ODDF_MARK, P1MSEL3_0, PB6_FN),
PINMUX_DATA(DG5_MARK, P1MSEL2_0, PB5_FN),
PINMUX_DATA(DG4_MARK, P1MSEL2_0, PB4_FN),
PINMUX_DATA(DG3_MARK, P1MSEL2_0, PB3_FN),
PINMUX_DATA(DG2_MARK, P1MSEL2_0, PB2_FN),
PINMUX_DATA(DG1_MARK, P1MSEL2_0, PB1_FN),
PINMUX_DATA(DG0_MARK, P1MSEL2_0, PB0_FN),
PINMUX_DATA(HSPI_CLK_MARK, P1MSEL3_1, PB7_FN),
PINMUX_DATA(HSPI_CS_MARK, P1MSEL3_1, PB6_FN),
PINMUX_DATA(ETH_MDIO_MARK, P1MSEL2_1, PB5_FN),
PINMUX_DATA(ETH_RX_CLK_MARK, P1MSEL2_1, PB4_FN),
PINMUX_DATA(ETH_MDC_MARK, P1MSEL2_1, PB3_FN),
PINMUX_DATA(ETH_COL_MARK, P1MSEL2_1, PB2_FN),
PINMUX_DATA(ETH_TX_CLK_MARK, P1MSEL2_1, PB1_FN),
PINMUX_DATA(ETH_CRS_MARK, P1MSEL2_1, PB0_FN),
/* PC FN */
PINMUX_DATA(DCLKIN_MARK, P1MSEL3_0, PC7_FN),
PINMUX_DATA(HSYNC_MARK, P1MSEL3_0, PC6_FN),
PINMUX_DATA(DB5_MARK, P1MSEL2_0, PC5_FN),
PINMUX_DATA(DB4_MARK, P1MSEL2_0, PC4_FN),
PINMUX_DATA(DB3_MARK, P1MSEL2_0, PC3_FN),
PINMUX_DATA(DB2_MARK, P1MSEL2_0, PC2_FN),
PINMUX_DATA(DB1_MARK, P1MSEL2_0, PC1_FN),
PINMUX_DATA(DB0_MARK, P1MSEL2_0, PC0_FN),
PINMUX_DATA(HSPI_RX_MARK, P1MSEL3_1, PC7_FN),
PINMUX_DATA(HSPI_TX_MARK, P1MSEL3_1, PC6_FN),
PINMUX_DATA(ETH_RXD3_MARK, P1MSEL2_1, PC5_FN),
PINMUX_DATA(ETH_RXD2_MARK, P1MSEL2_1, PC4_FN),
PINMUX_DATA(ETH_RXD1_MARK, P1MSEL2_1, PC3_FN),
PINMUX_DATA(ETH_RXD0_MARK, P1MSEL2_1, PC2_FN),
PINMUX_DATA(ETH_RX_DV_MARK, P1MSEL2_1, PC1_FN),
PINMUX_DATA(ETH_RX_ER_MARK, P1MSEL2_1, PC0_FN),
/* PD FN */
PINMUX_DATA(DCLKOUT_MARK, PD7_FN),
PINMUX_DATA(SCIF1_SCK_MARK, PD6_FN),
PINMUX_DATA(SCIF1_RXD_MARK, PD5_FN),
PINMUX_DATA(SCIF1_TXD_MARK, PD4_FN),
PINMUX_DATA(DACK1_MARK, P1MSEL13_1, P1MSEL12_0, PD3_FN),
PINMUX_DATA(BACK_MARK, P1MSEL13_0, P1MSEL12_1, PD3_FN),
PINMUX_DATA(FALE_MARK, P1MSEL13_0, P1MSEL12_0, PD3_FN),
PINMUX_DATA(DACK0_MARK, P1MSEL14_1, PD2_FN),
PINMUX_DATA(FCLE_MARK, P1MSEL14_0, PD2_FN),
PINMUX_DATA(DREQ1_MARK, P1MSEL10_0, P1MSEL9_1, PD1_FN),
PINMUX_DATA(BREQ_MARK, P1MSEL10_1, P1MSEL9_0, PD1_FN),
PINMUX_DATA(USB_OVC1_MARK, P1MSEL10_0, P1MSEL9_0, PD1_FN),
PINMUX_DATA(DREQ0_MARK, P1MSEL11_1, PD0_FN),
PINMUX_DATA(USB_OVC0_MARK, P1MSEL11_0, PD0_FN),
/* PE FN */
PINMUX_DATA(USB_PENC1_MARK, PE7_FN),
PINMUX_DATA(USB_PENC0_MARK, PE6_FN),
/* PF FN */
PINMUX_DATA(HAC1_SDOUT_MARK, P2MSEL15_0, P2MSEL14_0, PF7_FN),
PINMUX_DATA(HAC1_SDIN_MARK, P2MSEL15_0, P2MSEL14_0, PF6_FN),
PINMUX_DATA(HAC1_SYNC_MARK, P2MSEL15_0, P2MSEL14_0, PF5_FN),
PINMUX_DATA(HAC1_BITCLK_MARK, P2MSEL15_0, P2MSEL14_0, PF4_FN),
PINMUX_DATA(HAC0_SDOUT_MARK, P2MSEL13_0, P2MSEL12_0, PF3_FN),
PINMUX_DATA(HAC0_SDIN_MARK, P2MSEL13_0, P2MSEL12_0, PF2_FN),
PINMUX_DATA(HAC0_SYNC_MARK, P2MSEL13_0, P2MSEL12_0, PF1_FN),
PINMUX_DATA(HAC0_BITCLK_MARK, P2MSEL13_0, P2MSEL12_0, PF0_FN),
PINMUX_DATA(SSI1_SDATA_MARK, P2MSEL15_0, P2MSEL14_1, PF7_FN),
PINMUX_DATA(SSI1_SCK_MARK, P2MSEL15_0, P2MSEL14_1, PF6_FN),
PINMUX_DATA(SSI1_WS_MARK, P2MSEL15_0, P2MSEL14_1, PF5_FN),
PINMUX_DATA(SSI1_CLK_MARK, P2MSEL15_0, P2MSEL14_1, PF4_FN),
PINMUX_DATA(SSI0_SDATA_MARK, P2MSEL13_0, P2MSEL12_1, PF3_FN),
PINMUX_DATA(SSI0_SCK_MARK, P2MSEL13_0, P2MSEL12_1, PF2_FN),
PINMUX_DATA(SSI0_WS_MARK, P2MSEL13_0, P2MSEL12_1, PF1_FN),
PINMUX_DATA(SSI0_CLK_MARK, P2MSEL13_0, P2MSEL12_1, PF0_FN),
PINMUX_DATA(SDIF1CMD_MARK, P2MSEL15_1, P2MSEL14_0, PF7_FN),
PINMUX_DATA(SDIF1CD_MARK, P2MSEL15_1, P2MSEL14_0, PF6_FN),
PINMUX_DATA(SDIF1WP_MARK, P2MSEL15_1, P2MSEL14_0, PF5_FN),
PINMUX_DATA(SDIF1CLK_MARK, P2MSEL15_1, P2MSEL14_0, PF4_FN),
PINMUX_DATA(SDIF1D3_MARK, P2MSEL13_1, P2MSEL12_0, PF3_FN),
PINMUX_DATA(SDIF1D2_MARK, P2MSEL13_1, P2MSEL12_0, PF2_FN),
PINMUX_DATA(SDIF1D1_MARK, P2MSEL13_1, P2MSEL12_0, PF1_FN),
PINMUX_DATA(SDIF1D0_MARK, P2MSEL13_1, P2MSEL12_0, PF0_FN),
/* PG FN */
PINMUX_DATA(SCIF3_SCK_MARK, P1MSEL8_0, PG7_FN),
PINMUX_DATA(SSI2_SDATA_MARK, P1MSEL8_1, PG7_FN),
PINMUX_DATA(SCIF3_RXD_MARK, P1MSEL7_0, P1MSEL6_0, PG6_FN),
PINMUX_DATA(SSI2_SCK_MARK, P1MSEL7_1, P1MSEL6_0, PG6_FN),
PINMUX_DATA(TCLK_MARK, P1MSEL7_0, P1MSEL6_1, PG6_FN),
PINMUX_DATA(SCIF3_TXD_MARK, P1MSEL5_0, P1MSEL4_0, PG5_FN),
PINMUX_DATA(SSI2_WS_MARK, P1MSEL5_1, P1MSEL4_0, PG5_FN),
PINMUX_DATA(HAC_RES_MARK, P1MSEL5_0, P1MSEL4_1, PG5_FN),
/* PH FN */
PINMUX_DATA(DACK3_MARK, P2MSEL4_0, PH7_FN),
PINMUX_DATA(SDIF0CMD_MARK, P2MSEL4_1, PH7_FN),
PINMUX_DATA(DACK2_MARK, P2MSEL4_0, PH6_FN),
PINMUX_DATA(SDIF0CD_MARK, P2MSEL4_1, PH6_FN),
PINMUX_DATA(DREQ3_MARK, P2MSEL4_0, PH5_FN),
PINMUX_DATA(SDIF0WP_MARK, P2MSEL4_1, PH5_FN),
PINMUX_DATA(DREQ2_MARK, P2MSEL3_0, P2MSEL2_1, PH4_FN),
PINMUX_DATA(SDIF0CLK_MARK, P2MSEL3_1, P2MSEL2_0, PH4_FN),
PINMUX_DATA(SCIF0_CTS_MARK, P2MSEL3_0, P2MSEL2_0, PH4_FN),
PINMUX_DATA(SDIF0D3_MARK, P2MSEL1_1, P2MSEL0_0, PH3_FN),
PINMUX_DATA(SCIF0_RTS_MARK, P2MSEL1_0, P2MSEL0_0, PH3_FN),
PINMUX_DATA(IRL7_MARK, P2MSEL1_0, P2MSEL0_1, PH3_FN),
PINMUX_DATA(SDIF0D2_MARK, P2MSEL1_1, P2MSEL0_0, PH2_FN),
PINMUX_DATA(SCIF0_SCK_MARK, P2MSEL1_0, P2MSEL0_0, PH2_FN),
PINMUX_DATA(IRL6_MARK, P2MSEL1_0, P2MSEL0_1, PH2_FN),
PINMUX_DATA(SDIF0D1_MARK, P2MSEL1_1, P2MSEL0_0, PH1_FN),
PINMUX_DATA(SCIF0_RXD_MARK, P2MSEL1_0, P2MSEL0_0, PH1_FN),
PINMUX_DATA(IRL5_MARK, P2MSEL1_0, P2MSEL0_1, PH1_FN),
PINMUX_DATA(SDIF0D0_MARK, P2MSEL1_1, P2MSEL0_0, PH0_FN),
PINMUX_DATA(SCIF0_TXD_MARK, P2MSEL1_0, P2MSEL0_0, PH0_FN),
PINMUX_DATA(IRL4_MARK, P2MSEL1_0, P2MSEL0_1, PH0_FN),
/* PJ FN */
PINMUX_DATA(SCIF5_SCK_MARK, P2MSEL11_1, PJ7_FN),
PINMUX_DATA(FRB_MARK, P2MSEL11_0, PJ7_FN),
PINMUX_DATA(SCIF5_RXD_MARK, P2MSEL10_0, PJ6_FN),
PINMUX_DATA(IOIS16_MARK, P2MSEL10_1, PJ6_FN),
PINMUX_DATA(SCIF5_TXD_MARK, P2MSEL10_0, PJ5_FN),
PINMUX_DATA(CE2B_MARK, P2MSEL10_1, PJ5_FN),
PINMUX_DATA(DRAK3_MARK, P2MSEL7_0, PJ4_FN),
PINMUX_DATA(CE2A_MARK, P2MSEL7_1, PJ4_FN),
PINMUX_DATA(SCIF4_SCK_MARK, P2MSEL9_0, P2MSEL8_0, PJ3_FN),
PINMUX_DATA(DRAK2_MARK, P2MSEL9_0, P2MSEL8_1, PJ3_FN),
PINMUX_DATA(SSI3_WS_MARK, P2MSEL9_1, P2MSEL8_0, PJ3_FN),
PINMUX_DATA(SCIF4_RXD_MARK, P2MSEL6_1, P2MSEL5_0, PJ2_FN),
PINMUX_DATA(DRAK1_MARK, P2MSEL6_0, P2MSEL5_1, PJ2_FN),
PINMUX_DATA(FSTATUS_MARK, P2MSEL6_0, P2MSEL5_0, PJ2_FN),
PINMUX_DATA(SSI3_SDATA_MARK, P2MSEL6_1, P2MSEL5_1, PJ2_FN),
PINMUX_DATA(SCIF4_TXD_MARK, P2MSEL6_1, P2MSEL5_0, PJ1_FN),
PINMUX_DATA(DRAK0_MARK, P2MSEL6_0, P2MSEL5_1, PJ1_FN),
PINMUX_DATA(FSE_MARK, P2MSEL6_0, P2MSEL5_0, PJ1_FN),
PINMUX_DATA(SSI3_SCK_MARK, P2MSEL6_1, P2MSEL5_1, PJ1_FN),
};
static struct sh_pfc_pin pinmux_pins[] = {
/* PA */
PINMUX_GPIO(GPIO_PA7, PA7_DATA),
PINMUX_GPIO(GPIO_PA6, PA6_DATA),
PINMUX_GPIO(GPIO_PA5, PA5_DATA),
PINMUX_GPIO(GPIO_PA4, PA4_DATA),
PINMUX_GPIO(GPIO_PA3, PA3_DATA),
PINMUX_GPIO(GPIO_PA2, PA2_DATA),
PINMUX_GPIO(GPIO_PA1, PA1_DATA),
PINMUX_GPIO(GPIO_PA0, PA0_DATA),
/* PB */
PINMUX_GPIO(GPIO_PB7, PB7_DATA),
PINMUX_GPIO(GPIO_PB6, PB6_DATA),
PINMUX_GPIO(GPIO_PB5, PB5_DATA),
PINMUX_GPIO(GPIO_PB4, PB4_DATA),
PINMUX_GPIO(GPIO_PB3, PB3_DATA),
PINMUX_GPIO(GPIO_PB2, PB2_DATA),
PINMUX_GPIO(GPIO_PB1, PB1_DATA),
PINMUX_GPIO(GPIO_PB0, PB0_DATA),
/* PC */
PINMUX_GPIO(GPIO_PC7, PC7_DATA),
PINMUX_GPIO(GPIO_PC6, PC6_DATA),
PINMUX_GPIO(GPIO_PC5, PC5_DATA),
PINMUX_GPIO(GPIO_PC4, PC4_DATA),
PINMUX_GPIO(GPIO_PC3, PC3_DATA),
PINMUX_GPIO(GPIO_PC2, PC2_DATA),
PINMUX_GPIO(GPIO_PC1, PC1_DATA),
PINMUX_GPIO(GPIO_PC0, PC0_DATA),
/* PD */
PINMUX_GPIO(GPIO_PD7, PD7_DATA),
PINMUX_GPIO(GPIO_PD6, PD6_DATA),
PINMUX_GPIO(GPIO_PD5, PD5_DATA),
PINMUX_GPIO(GPIO_PD4, PD4_DATA),
PINMUX_GPIO(GPIO_PD3, PD3_DATA),
PINMUX_GPIO(GPIO_PD2, PD2_DATA),
PINMUX_GPIO(GPIO_PD1, PD1_DATA),
PINMUX_GPIO(GPIO_PD0, PD0_DATA),
/* PE */
PINMUX_GPIO(GPIO_PE7, PE7_DATA),
PINMUX_GPIO(GPIO_PE6, PE6_DATA),
/* PF */
PINMUX_GPIO(GPIO_PF7, PF7_DATA),
PINMUX_GPIO(GPIO_PF6, PF6_DATA),
PINMUX_GPIO(GPIO_PF5, PF5_DATA),
PINMUX_GPIO(GPIO_PF4, PF4_DATA),
PINMUX_GPIO(GPIO_PF3, PF3_DATA),
PINMUX_GPIO(GPIO_PF2, PF2_DATA),
PINMUX_GPIO(GPIO_PF1, PF1_DATA),
PINMUX_GPIO(GPIO_PF0, PF0_DATA),
/* PG */
PINMUX_GPIO(GPIO_PG7, PG7_DATA),
PINMUX_GPIO(GPIO_PG6, PG6_DATA),
PINMUX_GPIO(GPIO_PG5, PG5_DATA),
/* PH */
PINMUX_GPIO(GPIO_PH7, PH7_DATA),
PINMUX_GPIO(GPIO_PH6, PH6_DATA),
PINMUX_GPIO(GPIO_PH5, PH5_DATA),
PINMUX_GPIO(GPIO_PH4, PH4_DATA),
PINMUX_GPIO(GPIO_PH3, PH3_DATA),
PINMUX_GPIO(GPIO_PH2, PH2_DATA),
PINMUX_GPIO(GPIO_PH1, PH1_DATA),
PINMUX_GPIO(GPIO_PH0, PH0_DATA),
/* PJ */
PINMUX_GPIO(GPIO_PJ7, PJ7_DATA),
PINMUX_GPIO(GPIO_PJ6, PJ6_DATA),
PINMUX_GPIO(GPIO_PJ5, PJ5_DATA),
PINMUX_GPIO(GPIO_PJ4, PJ4_DATA),
PINMUX_GPIO(GPIO_PJ3, PJ3_DATA),
PINMUX_GPIO(GPIO_PJ2, PJ2_DATA),
PINMUX_GPIO(GPIO_PJ1, PJ1_DATA),
};
#define PINMUX_FN_BASE ARRAY_SIZE(pinmux_pins)
static const struct pinmux_func pinmux_func_gpios[] = {
/* FN */
GPIO_FN(CDE),
GPIO_FN(ETH_MAGIC),
GPIO_FN(DISP),
GPIO_FN(ETH_LINK),
GPIO_FN(DR5),
GPIO_FN(ETH_TX_ER),
GPIO_FN(DR4),
GPIO_FN(ETH_TX_EN),
GPIO_FN(DR3),
GPIO_FN(ETH_TXD3),
GPIO_FN(DR2),
GPIO_FN(ETH_TXD2),
GPIO_FN(DR1),
GPIO_FN(ETH_TXD1),
GPIO_FN(DR0),
GPIO_FN(ETH_TXD0),
GPIO_FN(VSYNC),
GPIO_FN(HSPI_CLK),
GPIO_FN(ODDF),
GPIO_FN(HSPI_CS),
GPIO_FN(DG5),
GPIO_FN(ETH_MDIO),
GPIO_FN(DG4),
GPIO_FN(ETH_RX_CLK),
GPIO_FN(DG3),
GPIO_FN(ETH_MDC),
GPIO_FN(DG2),
GPIO_FN(ETH_COL),
GPIO_FN(DG1),
GPIO_FN(ETH_TX_CLK),
GPIO_FN(DG0),
GPIO_FN(ETH_CRS),
GPIO_FN(DCLKIN),
GPIO_FN(HSPI_RX),
GPIO_FN(HSYNC),
GPIO_FN(HSPI_TX),
GPIO_FN(DB5),
GPIO_FN(ETH_RXD3),
GPIO_FN(DB4),
GPIO_FN(ETH_RXD2),
GPIO_FN(DB3),
GPIO_FN(ETH_RXD1),
GPIO_FN(DB2),
GPIO_FN(ETH_RXD0),
GPIO_FN(DB1),
GPIO_FN(ETH_RX_DV),
GPIO_FN(DB0),
GPIO_FN(ETH_RX_ER),
GPIO_FN(DCLKOUT),
GPIO_FN(SCIF1_SCK),
GPIO_FN(SCIF1_RXD),
GPIO_FN(SCIF1_TXD),
GPIO_FN(DACK1),
GPIO_FN(BACK),
GPIO_FN(FALE),
GPIO_FN(DACK0),
GPIO_FN(FCLE),
GPIO_FN(DREQ1),
GPIO_FN(BREQ),
GPIO_FN(USB_OVC1),
GPIO_FN(DREQ0),
GPIO_FN(USB_OVC0),
GPIO_FN(USB_PENC1),
GPIO_FN(USB_PENC0),
GPIO_FN(HAC1_SDOUT),
GPIO_FN(SSI1_SDATA),
GPIO_FN(SDIF1CMD),
GPIO_FN(HAC1_SDIN),
GPIO_FN(SSI1_SCK),
GPIO_FN(SDIF1CD),
GPIO_FN(HAC1_SYNC),
GPIO_FN(SSI1_WS),
GPIO_FN(SDIF1WP),
GPIO_FN(HAC1_BITCLK),
GPIO_FN(SSI1_CLK),
GPIO_FN(SDIF1CLK),
GPIO_FN(HAC0_SDOUT),
GPIO_FN(SSI0_SDATA),
GPIO_FN(SDIF1D3),
GPIO_FN(HAC0_SDIN),
GPIO_FN(SSI0_SCK),
GPIO_FN(SDIF1D2),
GPIO_FN(HAC0_SYNC),
GPIO_FN(SSI0_WS),
GPIO_FN(SDIF1D1),
GPIO_FN(HAC0_BITCLK),
GPIO_FN(SSI0_CLK),
GPIO_FN(SDIF1D0),
GPIO_FN(SCIF3_SCK),
GPIO_FN(SSI2_SDATA),
GPIO_FN(SCIF3_RXD),
GPIO_FN(TCLK),
GPIO_FN(SSI2_SCK),
GPIO_FN(SCIF3_TXD),
GPIO_FN(HAC_RES),
GPIO_FN(SSI2_WS),
GPIO_FN(DACK3),
GPIO_FN(SDIF0CMD),
GPIO_FN(DACK2),
GPIO_FN(SDIF0CD),
GPIO_FN(DREQ3),
GPIO_FN(SDIF0WP),
GPIO_FN(SCIF0_CTS),
GPIO_FN(DREQ2),
GPIO_FN(SDIF0CLK),
GPIO_FN(SCIF0_RTS),
GPIO_FN(IRL7),
GPIO_FN(SDIF0D3),
GPIO_FN(SCIF0_SCK),
GPIO_FN(IRL6),
GPIO_FN(SDIF0D2),
GPIO_FN(SCIF0_RXD),
GPIO_FN(IRL5),
GPIO_FN(SDIF0D1),
GPIO_FN(SCIF0_TXD),
GPIO_FN(IRL4),
GPIO_FN(SDIF0D0),
GPIO_FN(SCIF5_SCK),
GPIO_FN(FRB),
GPIO_FN(SCIF5_RXD),
GPIO_FN(IOIS16),
GPIO_FN(SCIF5_TXD),
GPIO_FN(CE2B),
GPIO_FN(DRAK3),
GPIO_FN(CE2A),
GPIO_FN(SCIF4_SCK),
GPIO_FN(DRAK2),
GPIO_FN(SSI3_WS),
GPIO_FN(SCIF4_RXD),
GPIO_FN(DRAK1),
GPIO_FN(SSI3_SDATA),
GPIO_FN(FSTATUS),
GPIO_FN(SCIF4_TXD),
GPIO_FN(DRAK0),
GPIO_FN(SSI3_SCK),
GPIO_FN(FSE),
};
static const struct pinmux_cfg_reg pinmux_config_regs[] = {
{ PINMUX_CFG_REG("PACR", 0xffcc0000, 16, 2) {
PA7_FN, PA7_OUT, PA7_IN, PA7_IN_PU,
PA6_FN, PA6_OUT, PA6_IN, PA6_IN_PU,
PA5_FN, PA5_OUT, PA5_IN, PA5_IN_PU,
PA4_FN, PA4_OUT, PA4_IN, PA4_IN_PU,
PA3_FN, PA3_OUT, PA3_IN, PA3_IN_PU,
PA2_FN, PA2_OUT, PA2_IN, PA2_IN_PU,
PA1_FN, PA1_OUT, PA1_IN, PA1_IN_PU,
PA0_FN, PA0_OUT, PA0_IN, PA0_IN_PU }
},
{ PINMUX_CFG_REG("PBCR", 0xffcc0002, 16, 2) {
PB7_FN, PB7_OUT, PB7_IN, PB7_IN_PU,
PB6_FN, PB6_OUT, PB6_IN, PB6_IN_PU,
PB5_FN, PB5_OUT, PB5_IN, PB5_IN_PU,
PB4_FN, PB4_OUT, PB4_IN, PB4_IN_PU,
PB3_FN, PB3_OUT, PB3_IN, PB3_IN_PU,
PB2_FN, PB2_OUT, PB2_IN, PB2_IN_PU,
PB1_FN, PB1_OUT, PB1_IN, PB1_IN_PU,
PB0_FN, PB0_OUT, PB0_IN, PB0_IN_PU }
},
{ PINMUX_CFG_REG("PCCR", 0xffcc0004, 16, 2) {
PC7_FN, PC7_OUT, PC7_IN, PC7_IN_PU,
PC6_FN, PC6_OUT, PC6_IN, PC6_IN_PU,
PC5_FN, PC5_OUT, PC5_IN, PC5_IN_PU,
PC4_FN, PC4_OUT, PC4_IN, PC4_IN_PU,
PC3_FN, PC3_OUT, PC3_IN, PC3_IN_PU,
PC2_FN, PC2_OUT, PC2_IN, PC2_IN_PU,
PC1_FN, PC1_OUT, PC1_IN, PC1_IN_PU,
PC0_FN, PC0_OUT, PC0_IN, PC0_IN_PU }
},
{ PINMUX_CFG_REG("PDCR", 0xffcc0006, 16, 2) {
PD7_FN, PD7_OUT, PD7_IN, PD7_IN_PU,
PD6_FN, PD6_OUT, PD6_IN, PD6_IN_PU,
PD5_FN, PD5_OUT, PD5_IN, PD5_IN_PU,
PD4_FN, PD4_OUT, PD4_IN, PD4_IN_PU,
PD3_FN, PD3_OUT, PD3_IN, PD3_IN_PU,
PD2_FN, PD2_OUT, PD2_IN, PD2_IN_PU,
PD1_FN, PD1_OUT, PD1_IN, PD1_IN_PU,
PD0_FN, PD0_OUT, PD0_IN, PD0_IN_PU }
},
{ PINMUX_CFG_REG("PECR", 0xffcc0008, 16, 2) {
PE7_FN, PE7_OUT, PE7_IN, PE7_IN_PU,
PE6_FN, PE6_OUT, PE6_IN, PE6_IN_PU,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, }
},
{ PINMUX_CFG_REG("PFCR", 0xffcc000a, 16, 2) {
PF7_FN, PF7_OUT, PF7_IN, PF7_IN_PU,
PF6_FN, PF6_OUT, PF6_IN, PF6_IN_PU,
PF5_FN, PF5_OUT, PF5_IN, PF5_IN_PU,
PF4_FN, PF4_OUT, PF4_IN, PF4_IN_PU,
PF3_FN, PF3_OUT, PF3_IN, PF3_IN_PU,
PF2_FN, PF2_OUT, PF2_IN, PF2_IN_PU,
PF1_FN, PF1_OUT, PF1_IN, PF1_IN_PU,
PF0_FN, PF0_OUT, PF0_IN, PF0_IN_PU }
},
{ PINMUX_CFG_REG("PGCR", 0xffcc000c, 16, 2) {
PG7_FN, PG7_OUT, PG7_IN, PG7_IN_PU,
PG6_FN, PG6_OUT, PG6_IN, PG6_IN_PU,
PG5_FN, PG5_OUT, PG5_IN, PG5_IN_PU,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, }
},
{ PINMUX_CFG_REG("PHCR", 0xffcc000e, 16, 2) {
PH7_FN, PH7_OUT, PH7_IN, PH7_IN_PU,
PH6_FN, PH6_OUT, PH6_IN, PH6_IN_PU,
PH5_FN, PH5_OUT, PH5_IN, PH5_IN_PU,
PH4_FN, PH4_OUT, PH4_IN, PH4_IN_PU,
PH3_FN, PH3_OUT, PH3_IN, PH3_IN_PU,
PH2_FN, PH2_OUT, PH2_IN, PH2_IN_PU,
PH1_FN, PH1_OUT, PH1_IN, PH1_IN_PU,
PH0_FN, PH0_OUT, PH0_IN, PH0_IN_PU }
},
{ PINMUX_CFG_REG("PJCR", 0xffcc0010, 16, 2) {
PJ7_FN, PJ7_OUT, PJ7_IN, PJ7_IN_PU,
PJ6_FN, PJ6_OUT, PJ6_IN, PJ6_IN_PU,
PJ5_FN, PJ5_OUT, PJ5_IN, PJ5_IN_PU,
PJ4_FN, PJ4_OUT, PJ4_IN, PJ4_IN_PU,
PJ3_FN, PJ3_OUT, PJ3_IN, PJ3_IN_PU,
PJ2_FN, PJ2_OUT, PJ2_IN, PJ2_IN_PU,
PJ1_FN, PJ1_OUT, PJ1_IN, PJ1_IN_PU,
0, 0, 0, 0, }
},
{ PINMUX_CFG_REG("P1MSELR", 0xffcc0080, 16, 1) {
0, 0,
P1MSEL14_0, P1MSEL14_1,
P1MSEL13_0, P1MSEL13_1,
P1MSEL12_0, P1MSEL12_1,
P1MSEL11_0, P1MSEL11_1,
P1MSEL10_0, P1MSEL10_1,
P1MSEL9_0, P1MSEL9_1,
P1MSEL8_0, P1MSEL8_1,
P1MSEL7_0, P1MSEL7_1,
P1MSEL6_0, P1MSEL6_1,
P1MSEL5_0, P1MSEL5_1,
P1MSEL4_0, P1MSEL4_1,
P1MSEL3_0, P1MSEL3_1,
P1MSEL2_0, P1MSEL2_1,
P1MSEL1_0, P1MSEL1_1,
P1MSEL0_0, P1MSEL0_1 }
},
{ PINMUX_CFG_REG("P2MSELR", 0xffcc0082, 16, 1) {
P2MSEL15_0, P2MSEL15_1,
P2MSEL14_0, P2MSEL14_1,
P2MSEL13_0, P2MSEL13_1,
P2MSEL12_0, P2MSEL12_1,
P2MSEL11_0, P2MSEL11_1,
P2MSEL10_0, P2MSEL10_1,
P2MSEL9_0, P2MSEL9_1,
P2MSEL8_0, P2MSEL8_1,
P2MSEL7_0, P2MSEL7_1,
P2MSEL6_0, P2MSEL6_1,
P2MSEL5_0, P2MSEL5_1,
P2MSEL4_0, P2MSEL4_1,
P2MSEL3_0, P2MSEL3_1,
P2MSEL2_0, P2MSEL2_1,
P2MSEL1_0, P2MSEL1_1,
P2MSEL0_0, P2MSEL0_1 }
},
{}
};
static const struct pinmux_data_reg pinmux_data_regs[] = {
{ PINMUX_DATA_REG("PADR", 0xffcc0020, 8) {
PA7_DATA, PA6_DATA, PA5_DATA, PA4_DATA,
PA3_DATA, PA2_DATA, PA1_DATA, PA0_DATA }
},
{ PINMUX_DATA_REG("PBDR", 0xffcc0022, 8) {
PB7_DATA, PB6_DATA, PB5_DATA, PB4_DATA,
PB3_DATA, PB2_DATA, PB1_DATA, PB0_DATA }
},
{ PINMUX_DATA_REG("PCDR", 0xffcc0024, 8) {
PC7_DATA, PC6_DATA, PC5_DATA, PC4_DATA,
PC3_DATA, PC2_DATA, PC1_DATA, PC0_DATA }
},
{ PINMUX_DATA_REG("PDDR", 0xffcc0026, 8) {
PD7_DATA, PD6_DATA, PD5_DATA, PD4_DATA,
PD3_DATA, PD2_DATA, PD1_DATA, PD0_DATA }
},
{ PINMUX_DATA_REG("PEDR", 0xffcc0028, 8) {
PE7_DATA, PE6_DATA,
0, 0, 0, 0, 0, 0 }
},
{ PINMUX_DATA_REG("PFDR", 0xffcc002a, 8) {
PF7_DATA, PF6_DATA, PF5_DATA, PF4_DATA,
PF3_DATA, PF2_DATA, PF1_DATA, PF0_DATA }
},
{ PINMUX_DATA_REG("PGDR", 0xffcc002c, 8) {
PG7_DATA, PG6_DATA, PG5_DATA, 0,
0, 0, 0, 0 }
},
{ PINMUX_DATA_REG("PHDR", 0xffcc002e, 8) {
PH7_DATA, PH6_DATA, PH5_DATA, PH4_DATA,
PH3_DATA, PH2_DATA, PH1_DATA, PH0_DATA }
},
{ PINMUX_DATA_REG("PJDR", 0xffcc0030, 8) {
PJ7_DATA, PJ6_DATA, PJ5_DATA, PJ4_DATA,
PJ3_DATA, PJ2_DATA, PJ1_DATA, 0 }
},
{ },
};
const struct sh_pfc_soc_info sh7786_pinmux_info = {
.name = "sh7786_pfc",
.input = { PINMUX_INPUT_BEGIN, PINMUX_INPUT_END },
.input_pu = { PINMUX_INPUT_PULLUP_BEGIN, PINMUX_INPUT_PULLUP_END },
.output = { PINMUX_OUTPUT_BEGIN, PINMUX_OUTPUT_END },
.function = { PINMUX_FUNCTION_BEGIN, PINMUX_FUNCTION_END },
.pins = pinmux_pins,
.nr_pins = ARRAY_SIZE(pinmux_pins),
.func_gpios = pinmux_func_gpios,
.nr_func_gpios = ARRAY_SIZE(pinmux_func_gpios),
.cfg_regs = pinmux_config_regs,
.data_regs = pinmux_data_regs,
.gpio_data = pinmux_data,
.gpio_data_size = ARRAY_SIZE(pinmux_data),
};
| gpl-2.0 |
BlazeDevs/android_kernel_samsung_msm8660-common | arch/arm/mach-omap1/mcbsp.c | 2428 | 8241 | /*
* linux/arch/arm/mach-omap1/mcbsp.c
*
* Copyright (C) 2008 Instituto Nokia de Tecnologia
* Contact: Eduardo Valentin <eduardo.valentin@indt.org.br>
*
* 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.
*
* Multichannel mode not supported.
*/
#include <linux/ioport.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <mach/irqs.h>
#include <plat/dma.h>
#include <plat/mux.h>
#include <plat/cpu.h>
#include <plat/mcbsp.h>
#define DPS_RSTCT2_PER_EN (1 << 0)
#define DSP_RSTCT2_WD_PER_EN (1 << 1)
static int dsp_use;
static struct clk *api_clk;
static struct clk *dsp_clk;
static void omap1_mcbsp_request(unsigned int id)
{
/*
* On 1510, 1610 and 1710, McBSP1 and McBSP3
* are DSP public peripherals.
*/
if (id == OMAP_MCBSP1 || id == OMAP_MCBSP3) {
if (dsp_use++ == 0) {
api_clk = clk_get(NULL, "api_ck");
dsp_clk = clk_get(NULL, "dsp_ck");
if (!IS_ERR(api_clk) && !IS_ERR(dsp_clk)) {
clk_enable(api_clk);
clk_enable(dsp_clk);
/*
* DSP external peripheral reset
* FIXME: This should be moved to dsp code
*/
__raw_writew(__raw_readw(DSP_RSTCT2) | DPS_RSTCT2_PER_EN |
DSP_RSTCT2_WD_PER_EN, DSP_RSTCT2);
}
}
}
}
static void omap1_mcbsp_free(unsigned int id)
{
if (id == OMAP_MCBSP1 || id == OMAP_MCBSP3) {
if (--dsp_use == 0) {
if (!IS_ERR(api_clk)) {
clk_disable(api_clk);
clk_put(api_clk);
}
if (!IS_ERR(dsp_clk)) {
clk_disable(dsp_clk);
clk_put(dsp_clk);
}
}
}
}
static struct omap_mcbsp_ops omap1_mcbsp_ops = {
.request = omap1_mcbsp_request,
.free = omap1_mcbsp_free,
};
#if defined(CONFIG_ARCH_OMAP730) || defined(CONFIG_ARCH_OMAP850)
struct resource omap7xx_mcbsp_res[][6] = {
{
{
.start = OMAP7XX_MCBSP1_BASE,
.end = OMAP7XX_MCBSP1_BASE + SZ_256,
.flags = IORESOURCE_MEM,
},
{
.name = "rx",
.start = INT_7XX_McBSP1RX,
.flags = IORESOURCE_IRQ,
},
{
.name = "tx",
.start = INT_7XX_McBSP1TX,
.flags = IORESOURCE_IRQ,
},
{
.name = "rx",
.start = OMAP_DMA_MCBSP1_RX,
.flags = IORESOURCE_DMA,
},
{
.name = "tx",
.start = OMAP_DMA_MCBSP1_TX,
.flags = IORESOURCE_DMA,
},
},
{
{
.start = OMAP7XX_MCBSP2_BASE,
.end = OMAP7XX_MCBSP2_BASE + SZ_256,
.flags = IORESOURCE_MEM,
},
{
.name = "rx",
.start = INT_7XX_McBSP2RX,
.flags = IORESOURCE_IRQ,
},
{
.name = "tx",
.start = INT_7XX_McBSP2TX,
.flags = IORESOURCE_IRQ,
},
{
.name = "rx",
.start = OMAP_DMA_MCBSP3_RX,
.flags = IORESOURCE_DMA,
},
{
.name = "tx",
.start = OMAP_DMA_MCBSP3_TX,
.flags = IORESOURCE_DMA,
},
},
};
#define omap7xx_mcbsp_res_0 omap7xx_mcbsp_res[0]
static struct omap_mcbsp_platform_data omap7xx_mcbsp_pdata[] = {
{
.ops = &omap1_mcbsp_ops,
},
{
.ops = &omap1_mcbsp_ops,
},
};
#define OMAP7XX_MCBSP_RES_SZ ARRAY_SIZE(omap7xx_mcbsp_res[1])
#define OMAP7XX_MCBSP_COUNT ARRAY_SIZE(omap7xx_mcbsp_res)
#else
#define omap7xx_mcbsp_res_0 NULL
#define omap7xx_mcbsp_pdata NULL
#define OMAP7XX_MCBSP_RES_SZ 0
#define OMAP7XX_MCBSP_COUNT 0
#endif
#ifdef CONFIG_ARCH_OMAP15XX
struct resource omap15xx_mcbsp_res[][6] = {
{
{
.start = OMAP1510_MCBSP1_BASE,
.end = OMAP1510_MCBSP1_BASE + SZ_256,
.flags = IORESOURCE_MEM,
},
{
.name = "rx",
.start = INT_McBSP1RX,
.flags = IORESOURCE_IRQ,
},
{
.name = "tx",
.start = INT_McBSP1TX,
.flags = IORESOURCE_IRQ,
},
{
.name = "rx",
.start = OMAP_DMA_MCBSP1_RX,
.flags = IORESOURCE_DMA,
},
{
.name = "tx",
.start = OMAP_DMA_MCBSP1_TX,
.flags = IORESOURCE_DMA,
},
},
{
{
.start = OMAP1510_MCBSP2_BASE,
.end = OMAP1510_MCBSP2_BASE + SZ_256,
.flags = IORESOURCE_MEM,
},
{
.name = "rx",
.start = INT_1510_SPI_RX,
.flags = IORESOURCE_IRQ,
},
{
.name = "tx",
.start = INT_1510_SPI_TX,
.flags = IORESOURCE_IRQ,
},
{
.name = "rx",
.start = OMAP_DMA_MCBSP2_RX,
.flags = IORESOURCE_DMA,
},
{
.name = "tx",
.start = OMAP_DMA_MCBSP2_TX,
.flags = IORESOURCE_DMA,
},
},
{
{
.start = OMAP1510_MCBSP3_BASE,
.end = OMAP1510_MCBSP3_BASE + SZ_256,
.flags = IORESOURCE_MEM,
},
{
.name = "rx",
.start = INT_McBSP3RX,
.flags = IORESOURCE_IRQ,
},
{
.name = "tx",
.start = INT_McBSP3TX,
.flags = IORESOURCE_IRQ,
},
{
.name = "rx",
.start = OMAP_DMA_MCBSP3_RX,
.flags = IORESOURCE_DMA,
},
{
.name = "tx",
.start = OMAP_DMA_MCBSP3_TX,
.flags = IORESOURCE_DMA,
},
},
};
#define omap15xx_mcbsp_res_0 omap15xx_mcbsp_res[0]
static struct omap_mcbsp_platform_data omap15xx_mcbsp_pdata[] = {
{
.ops = &omap1_mcbsp_ops,
},
{
.ops = &omap1_mcbsp_ops,
},
{
.ops = &omap1_mcbsp_ops,
},
};
#define OMAP15XX_MCBSP_RES_SZ ARRAY_SIZE(omap15xx_mcbsp_res[1])
#define OMAP15XX_MCBSP_COUNT ARRAY_SIZE(omap15xx_mcbsp_res)
#else
#define omap15xx_mcbsp_res_0 NULL
#define omap15xx_mcbsp_pdata NULL
#define OMAP15XX_MCBSP_RES_SZ 0
#define OMAP15XX_MCBSP_COUNT 0
#endif
#ifdef CONFIG_ARCH_OMAP16XX
struct resource omap16xx_mcbsp_res[][6] = {
{
{
.start = OMAP1610_MCBSP1_BASE,
.end = OMAP1610_MCBSP1_BASE + SZ_256,
.flags = IORESOURCE_MEM,
},
{
.name = "rx",
.start = INT_McBSP1RX,
.flags = IORESOURCE_IRQ,
},
{
.name = "tx",
.start = INT_McBSP1TX,
.flags = IORESOURCE_IRQ,
},
{
.name = "rx",
.start = OMAP_DMA_MCBSP1_RX,
.flags = IORESOURCE_DMA,
},
{
.name = "tx",
.start = OMAP_DMA_MCBSP1_TX,
.flags = IORESOURCE_DMA,
},
},
{
{
.start = OMAP1610_MCBSP2_BASE,
.end = OMAP1610_MCBSP2_BASE + SZ_256,
.flags = IORESOURCE_MEM,
},
{
.name = "rx",
.start = INT_1610_McBSP2_RX,
.flags = IORESOURCE_IRQ,
},
{
.name = "tx",
.start = INT_1610_McBSP2_TX,
.flags = IORESOURCE_IRQ,
},
{
.name = "rx",
.start = OMAP_DMA_MCBSP2_RX,
.flags = IORESOURCE_DMA,
},
{
.name = "tx",
.start = OMAP_DMA_MCBSP2_TX,
.flags = IORESOURCE_DMA,
},
},
{
{
.start = OMAP1610_MCBSP3_BASE,
.end = OMAP1610_MCBSP3_BASE + SZ_256,
.flags = IORESOURCE_MEM,
},
{
.name = "rx",
.start = INT_McBSP3RX,
.flags = IORESOURCE_IRQ,
},
{
.name = "tx",
.start = INT_McBSP3TX,
.flags = IORESOURCE_IRQ,
},
{
.name = "rx",
.start = OMAP_DMA_MCBSP3_RX,
.flags = IORESOURCE_DMA,
},
{
.name = "tx",
.start = OMAP_DMA_MCBSP3_TX,
.flags = IORESOURCE_DMA,
},
},
};
#define omap16xx_mcbsp_res_0 omap16xx_mcbsp_res[0]
static struct omap_mcbsp_platform_data omap16xx_mcbsp_pdata[] = {
{
.ops = &omap1_mcbsp_ops,
},
{
.ops = &omap1_mcbsp_ops,
},
{
.ops = &omap1_mcbsp_ops,
},
};
#define OMAP16XX_MCBSP_RES_SZ ARRAY_SIZE(omap16xx_mcbsp_res[1])
#define OMAP16XX_MCBSP_COUNT ARRAY_SIZE(omap16xx_mcbsp_res)
#else
#define omap16xx_mcbsp_res_0 NULL
#define omap16xx_mcbsp_pdata NULL
#define OMAP16XX_MCBSP_RES_SZ 0
#define OMAP16XX_MCBSP_COUNT 0
#endif
static int __init omap1_mcbsp_init(void)
{
if (!cpu_class_is_omap1())
return -ENODEV;
if (cpu_is_omap7xx())
omap_mcbsp_count = OMAP7XX_MCBSP_COUNT;
else if (cpu_is_omap15xx())
omap_mcbsp_count = OMAP15XX_MCBSP_COUNT;
else if (cpu_is_omap16xx())
omap_mcbsp_count = OMAP16XX_MCBSP_COUNT;
mcbsp_ptr = kzalloc(omap_mcbsp_count * sizeof(struct omap_mcbsp *),
GFP_KERNEL);
if (!mcbsp_ptr)
return -ENOMEM;
if (cpu_is_omap7xx())
omap_mcbsp_register_board_cfg(omap7xx_mcbsp_res_0,
OMAP7XX_MCBSP_RES_SZ,
omap7xx_mcbsp_pdata,
OMAP7XX_MCBSP_COUNT);
if (cpu_is_omap15xx())
omap_mcbsp_register_board_cfg(omap15xx_mcbsp_res_0,
OMAP15XX_MCBSP_RES_SZ,
omap15xx_mcbsp_pdata,
OMAP15XX_MCBSP_COUNT);
if (cpu_is_omap16xx())
omap_mcbsp_register_board_cfg(omap16xx_mcbsp_res_0,
OMAP16XX_MCBSP_RES_SZ,
omap16xx_mcbsp_pdata,
OMAP16XX_MCBSP_COUNT);
return omap_mcbsp_init();
}
arch_initcall(omap1_mcbsp_init);
| gpl-2.0 |
vaginessa/Samsung_STE_Kernel | arch/arm/mach-omap1/board-palmte.c | 2428 | 6948 | /*
* linux/arch/arm/mach-omap1/board-palmte.c
*
* Modified from board-generic.c
*
* Support for the Palm Tungsten E PDA.
*
* Original version : Laurent Gonzalez
*
* Maintainers : http://palmtelinux.sf.net
* palmtelinux-developpers@lists.sf.net
*
* Copyright (c) 2006 Andrzej Zaborowski <balrog@zabor.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/input.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/interrupt.h>
#include <linux/apm-emulation.h>
#include <mach/hardware.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/gpio.h>
#include <plat/flash.h>
#include <plat/mux.h>
#include <plat/usb.h>
#include <plat/tc.h>
#include <plat/dma.h>
#include <plat/board.h>
#include <plat/irda.h>
#include <plat/keypad.h>
#include <plat/common.h>
#define PALMTE_USBDETECT_GPIO 0
#define PALMTE_USB_OR_DC_GPIO 1
#define PALMTE_TSC_GPIO 4
#define PALMTE_PINTDAV_GPIO 6
#define PALMTE_MMC_WP_GPIO 8
#define PALMTE_MMC_POWER_GPIO 9
#define PALMTE_HDQ_GPIO 11
#define PALMTE_HEADPHONES_GPIO 14
#define PALMTE_SPEAKER_GPIO 15
#define PALMTE_DC_GPIO OMAP_MPUIO(2)
#define PALMTE_MMC_SWITCH_GPIO OMAP_MPUIO(4)
#define PALMTE_MMC1_GPIO OMAP_MPUIO(6)
#define PALMTE_MMC2_GPIO OMAP_MPUIO(7)
#define PALMTE_MMC3_GPIO OMAP_MPUIO(11)
static void __init omap_palmte_init_irq(void)
{
omap1_init_common_hw();
omap_init_irq();
}
static const unsigned int palmte_keymap[] = {
KEY(0, 0, KEY_F1), /* Calendar */
KEY(1, 0, KEY_F2), /* Contacts */
KEY(2, 0, KEY_F3), /* Tasks List */
KEY(3, 0, KEY_F4), /* Note Pad */
KEY(4, 0, KEY_POWER),
KEY(0, 1, KEY_LEFT),
KEY(1, 1, KEY_DOWN),
KEY(2, 1, KEY_UP),
KEY(3, 1, KEY_RIGHT),
KEY(4, 1, KEY_ENTER),
};
static const struct matrix_keymap_data palmte_keymap_data = {
.keymap = palmte_keymap,
.keymap_size = ARRAY_SIZE(palmte_keymap),
};
static struct omap_kp_platform_data palmte_kp_data = {
.rows = 8,
.cols = 8,
.keymap_data = &palmte_keymap_data,
.rep = true,
.delay = 12,
};
static struct resource palmte_kp_resources[] = {
[0] = {
.start = INT_KEYBOARD,
.end = INT_KEYBOARD,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device palmte_kp_device = {
.name = "omap-keypad",
.id = -1,
.dev = {
.platform_data = &palmte_kp_data,
},
.num_resources = ARRAY_SIZE(palmte_kp_resources),
.resource = palmte_kp_resources,
};
static struct mtd_partition palmte_rom_partitions[] = {
/* PalmOS "Small ROM", contains the bootloader and the debugger */
{
.name = "smallrom",
.offset = 0,
.size = 0xa000,
.mask_flags = MTD_WRITEABLE,
},
/* PalmOS "Big ROM", a filesystem with all the OS code and data */
{
.name = "bigrom",
.offset = SZ_128K,
/*
* 0x5f0000 bytes big in the multi-language ("EFIGS") version,
* 0x7b0000 bytes in the English-only ("enUS") version.
*/
.size = 0x7b0000,
.mask_flags = MTD_WRITEABLE,
},
};
static struct physmap_flash_data palmte_rom_data = {
.width = 2,
.set_vpp = omap1_set_vpp,
.parts = palmte_rom_partitions,
.nr_parts = ARRAY_SIZE(palmte_rom_partitions),
};
static struct resource palmte_rom_resource = {
.start = OMAP_CS0_PHYS,
.end = OMAP_CS0_PHYS + SZ_8M - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device palmte_rom_device = {
.name = "physmap-flash",
.id = -1,
.dev = {
.platform_data = &palmte_rom_data,
},
.num_resources = 1,
.resource = &palmte_rom_resource,
};
static struct platform_device palmte_lcd_device = {
.name = "lcd_palmte",
.id = -1,
};
static struct omap_backlight_config palmte_backlight_config = {
.default_intensity = 0xa0,
};
static struct platform_device palmte_backlight_device = {
.name = "omap-bl",
.id = -1,
.dev = {
.platform_data = &palmte_backlight_config,
},
};
static struct omap_irda_config palmte_irda_config = {
.transceiver_cap = IR_SIRMODE,
.rx_channel = OMAP_DMA_UART3_RX,
.tx_channel = OMAP_DMA_UART3_TX,
.dest_start = UART3_THR,
.src_start = UART3_RHR,
.tx_trigger = 0,
.rx_trigger = 0,
};
static struct resource palmte_irda_resources[] = {
[0] = {
.start = INT_UART3,
.end = INT_UART3,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device palmte_irda_device = {
.name = "omapirda",
.id = -1,
.dev = {
.platform_data = &palmte_irda_config,
},
.num_resources = ARRAY_SIZE(palmte_irda_resources),
.resource = palmte_irda_resources,
};
static struct platform_device *palmte_devices[] __initdata = {
&palmte_rom_device,
&palmte_kp_device,
&palmte_lcd_device,
&palmte_backlight_device,
&palmte_irda_device,
};
static struct omap_usb_config palmte_usb_config __initdata = {
.register_dev = 1, /* Mini-B only receptacle */
.hmc_mode = 0,
.pins[0] = 2,
};
static struct omap_lcd_config palmte_lcd_config __initdata = {
.ctrl_name = "internal",
};
static struct omap_board_config_kernel palmte_config[] __initdata = {
{ OMAP_TAG_LCD, &palmte_lcd_config },
};
static struct spi_board_info palmte_spi_info[] __initdata = {
{
.modalias = "tsc2102",
.bus_num = 2, /* uWire (officially) */
.chip_select = 0, /* As opposed to 3 */
.irq = OMAP_GPIO_IRQ(PALMTE_PINTDAV_GPIO),
.max_speed_hz = 8000000,
},
};
static void __init palmte_misc_gpio_setup(void)
{
/* Set TSC2102 PINTDAV pin as input (used by TSC2102 driver) */
if (gpio_request(PALMTE_PINTDAV_GPIO, "TSC2102 PINTDAV") < 0) {
printk(KERN_ERR "Could not reserve PINTDAV GPIO!\n");
return;
}
gpio_direction_input(PALMTE_PINTDAV_GPIO);
/* Set USB-or-DC-IN pin as input (unused) */
if (gpio_request(PALMTE_USB_OR_DC_GPIO, "USB/DC-IN") < 0) {
printk(KERN_ERR "Could not reserve cable signal GPIO!\n");
return;
}
gpio_direction_input(PALMTE_USB_OR_DC_GPIO);
}
static void __init omap_palmte_init(void)
{
/* mux pins for uarts */
omap_cfg_reg(UART1_TX);
omap_cfg_reg(UART1_RTS);
omap_cfg_reg(UART2_TX);
omap_cfg_reg(UART2_RTS);
omap_cfg_reg(UART3_TX);
omap_cfg_reg(UART3_RX);
omap_board_config = palmte_config;
omap_board_config_size = ARRAY_SIZE(palmte_config);
platform_add_devices(palmte_devices, ARRAY_SIZE(palmte_devices));
spi_register_board_info(palmte_spi_info, ARRAY_SIZE(palmte_spi_info));
palmte_misc_gpio_setup();
omap_serial_init();
omap1_usb_init(&palmte_usb_config);
omap_register_i2c_bus(1, 100, NULL, 0);
}
static void __init omap_palmte_map_io(void)
{
omap1_map_common_io();
}
MACHINE_START(OMAP_PALMTE, "OMAP310 based Palm Tungsten E")
.boot_params = 0x10000100,
.map_io = omap_palmte_map_io,
.reserve = omap_reserve,
.init_irq = omap_palmte_init_irq,
.init_machine = omap_palmte_init,
.timer = &omap_timer,
MACHINE_END
| gpl-2.0 |
kenkit/AndromadusMod-New | drivers/staging/brcm80211/brcmfmac/dhd_cdc.c | 2428 | 11386 | /*
* Copyright (c) 2010 Broadcom Corporation
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <linux/types.h>
#include <linux/netdevice.h>
#include <bcmdefs.h>
#include <bcmutils.h>
#include <bcmcdc.h>
#include <dngl_stats.h>
#include <dhd.h>
#include <dhd_proto.h>
#include <dhd_bus.h>
#include <dhd_dbg.h>
#ifdef CUSTOMER_HW2
int wifi_get_mac_addr(unsigned char *buf);
#endif
extern int dhd_preinit_ioctls(dhd_pub_t *dhd);
/* Packet alignment for most efficient SDIO (can change based on platform) */
#ifndef DHD_SDALIGN
#define DHD_SDALIGN 32
#endif
#if !ISPOWEROF2(DHD_SDALIGN)
#error DHD_SDALIGN is not a power of 2!
#endif
#define RETRIES 2 /* # of retries to retrieve matching ioctl response */
#define BUS_HEADER_LEN (16+DHD_SDALIGN) /* Must be atleast SDPCM_RESERVE
* defined in dhd_sdio.c
* (amount of header tha might be added)
* plus any space that might be needed
* for alignment padding.
*/
#define ROUND_UP_MARGIN 2048 /* Biggest SDIO block size possible for
* round off at the end of buffer
*/
typedef struct dhd_prot {
u16 reqid;
u8 pending;
u32 lastcmd;
u8 bus_header[BUS_HEADER_LEN];
cdc_ioctl_t msg;
unsigned char buf[WLC_IOCTL_MAXLEN + ROUND_UP_MARGIN];
} dhd_prot_t;
static int dhdcdc_msg(dhd_pub_t *dhd)
{
dhd_prot_t *prot = dhd->prot;
int len = le32_to_cpu(prot->msg.len) + sizeof(cdc_ioctl_t);
DHD_TRACE(("%s: Enter\n", __func__));
/* NOTE : cdc->msg.len holds the desired length of the buffer to be
* returned. Only up to CDC_MAX_MSG_SIZE of this buffer area
* is actually sent to the dongle
*/
if (len > CDC_MAX_MSG_SIZE)
len = CDC_MAX_MSG_SIZE;
/* Send request */
return dhd_bus_txctl(dhd->bus, (unsigned char *)&prot->msg, len);
}
static int dhdcdc_cmplt(dhd_pub_t *dhd, u32 id, u32 len)
{
int ret;
dhd_prot_t *prot = dhd->prot;
DHD_TRACE(("%s: Enter\n", __func__));
do {
ret =
dhd_bus_rxctl(dhd->bus, (unsigned char *)&prot->msg,
len + sizeof(cdc_ioctl_t));
if (ret < 0)
break;
} while (CDC_IOC_ID(le32_to_cpu(prot->msg.flags)) != id);
return ret;
}
int
dhdcdc_query_ioctl(dhd_pub_t *dhd, int ifidx, uint cmd, void *buf, uint len)
{
dhd_prot_t *prot = dhd->prot;
cdc_ioctl_t *msg = &prot->msg;
void *info;
int ret = 0, retries = 0;
u32 id, flags = 0;
DHD_TRACE(("%s: Enter\n", __func__));
DHD_CTL(("%s: cmd %d len %d\n", __func__, cmd, len));
/* Respond "bcmerror" and "bcmerrorstr" with local cache */
if (cmd == WLC_GET_VAR && buf) {
if (!strcmp((char *)buf, "bcmerrorstr")) {
strncpy((char *)buf, "bcm_error",
BCME_STRLEN);
goto done;
} else if (!strcmp((char *)buf, "bcmerror")) {
*(int *)buf = dhd->dongle_error;
goto done;
}
}
memset(msg, 0, sizeof(cdc_ioctl_t));
msg->cmd = cpu_to_le32(cmd);
msg->len = cpu_to_le32(len);
msg->flags = (++prot->reqid << CDCF_IOC_ID_SHIFT);
CDC_SET_IF_IDX(msg, ifidx);
msg->flags = cpu_to_le32(msg->flags);
if (buf)
memcpy(prot->buf, buf, len);
ret = dhdcdc_msg(dhd);
if (ret < 0) {
DHD_ERROR(("dhdcdc_query_ioctl: dhdcdc_msg failed w/status "
"%d\n", ret));
goto done;
}
retry:
/* wait for interrupt and get first fragment */
ret = dhdcdc_cmplt(dhd, prot->reqid, len);
if (ret < 0)
goto done;
flags = le32_to_cpu(msg->flags);
id = (flags & CDCF_IOC_ID_MASK) >> CDCF_IOC_ID_SHIFT;
if ((id < prot->reqid) && (++retries < RETRIES))
goto retry;
if (id != prot->reqid) {
DHD_ERROR(("%s: %s: unexpected request id %d (expected %d)\n",
dhd_ifname(dhd, ifidx), __func__, id, prot->reqid));
ret = -EINVAL;
goto done;
}
/* Check info buffer */
info = (void *)&msg[1];
/* Copy info buffer */
if (buf) {
if (ret < (int)len)
len = ret;
memcpy(buf, info, len);
}
/* Check the ERROR flag */
if (flags & CDCF_IOC_ERROR) {
ret = le32_to_cpu(msg->status);
/* Cache error from dongle */
dhd->dongle_error = ret;
}
done:
return ret;
}
int dhdcdc_set_ioctl(dhd_pub_t *dhd, int ifidx, uint cmd, void *buf, uint len)
{
dhd_prot_t *prot = dhd->prot;
cdc_ioctl_t *msg = &prot->msg;
int ret = 0;
u32 flags, id;
DHD_TRACE(("%s: Enter\n", __func__));
DHD_CTL(("%s: cmd %d len %d\n", __func__, cmd, len));
memset(msg, 0, sizeof(cdc_ioctl_t));
msg->cmd = cpu_to_le32(cmd);
msg->len = cpu_to_le32(len);
msg->flags = (++prot->reqid << CDCF_IOC_ID_SHIFT) | CDCF_IOC_SET;
CDC_SET_IF_IDX(msg, ifidx);
msg->flags = cpu_to_le32(msg->flags);
if (buf)
memcpy(prot->buf, buf, len);
ret = dhdcdc_msg(dhd);
if (ret < 0)
goto done;
ret = dhdcdc_cmplt(dhd, prot->reqid, len);
if (ret < 0)
goto done;
flags = le32_to_cpu(msg->flags);
id = (flags & CDCF_IOC_ID_MASK) >> CDCF_IOC_ID_SHIFT;
if (id != prot->reqid) {
DHD_ERROR(("%s: %s: unexpected request id %d (expected %d)\n",
dhd_ifname(dhd, ifidx), __func__, id, prot->reqid));
ret = -EINVAL;
goto done;
}
/* Check the ERROR flag */
if (flags & CDCF_IOC_ERROR) {
ret = le32_to_cpu(msg->status);
/* Cache error from dongle */
dhd->dongle_error = ret;
}
done:
return ret;
}
extern int dhd_bus_interface(struct dhd_bus *bus, uint arg, void *arg2);
int
dhd_prot_ioctl(dhd_pub_t *dhd, int ifidx, wl_ioctl_t *ioc, void *buf, int len)
{
dhd_prot_t *prot = dhd->prot;
int ret = -1;
if (dhd->busstate == DHD_BUS_DOWN) {
DHD_ERROR(("%s : bus is down. we have nothing to do\n",
__func__));
return ret;
}
dhd_os_proto_block(dhd);
DHD_TRACE(("%s: Enter\n", __func__));
ASSERT(len <= WLC_IOCTL_MAXLEN);
if (len > WLC_IOCTL_MAXLEN)
goto done;
if (prot->pending == true) {
DHD_TRACE(("CDC packet is pending!!!! cmd=0x%x (%lu) "
"lastcmd=0x%x (%lu)\n",
ioc->cmd, (unsigned long)ioc->cmd, prot->lastcmd,
(unsigned long)prot->lastcmd));
if ((ioc->cmd == WLC_SET_VAR) || (ioc->cmd == WLC_GET_VAR))
DHD_TRACE(("iovar cmd=%s\n", (char *)buf));
goto done;
}
prot->pending = true;
prot->lastcmd = ioc->cmd;
if (ioc->set)
ret = dhdcdc_set_ioctl(dhd, ifidx, ioc->cmd, buf, len);
else {
ret = dhdcdc_query_ioctl(dhd, ifidx, ioc->cmd, buf, len);
if (ret > 0)
ioc->used = ret - sizeof(cdc_ioctl_t);
}
/* Too many programs assume ioctl() returns 0 on success */
if (ret >= 0)
ret = 0;
else {
cdc_ioctl_t *msg = &prot->msg;
/* len == needed when set/query fails from dongle */
ioc->needed = le32_to_cpu(msg->len);
}
/* Intercept the wme_dp ioctl here */
if ((!ret) && (ioc->cmd == WLC_SET_VAR) && (!strcmp(buf, "wme_dp"))) {
int slen, val = 0;
slen = strlen("wme_dp") + 1;
if (len >= (int)(slen + sizeof(int)))
memcpy(&val, (char *)buf + slen, sizeof(int));
dhd->wme_dp = (u8) le32_to_cpu(val);
}
prot->pending = false;
done:
dhd_os_proto_unblock(dhd);
return ret;
}
#define PKTSUMNEEDED(skb) \
(((struct sk_buff *)(skb))->ip_summed == CHECKSUM_PARTIAL)
#define PKTSETSUMGOOD(skb, x) \
(((struct sk_buff *)(skb))->ip_summed = \
((x) ? CHECKSUM_UNNECESSARY : CHECKSUM_NONE))
/* PKTSETSUMNEEDED and PKTSUMGOOD are not possible because
skb->ip_summed is overloaded */
int
dhd_prot_iovar_op(dhd_pub_t *dhdp, const char *name,
void *params, int plen, void *arg, int len, bool set)
{
return -ENOTSUPP;
}
void dhd_prot_dump(dhd_pub_t *dhdp, struct bcmstrbuf *strbuf)
{
bcm_bprintf(strbuf, "Protocol CDC: reqid %d\n", dhdp->prot->reqid);
}
void dhd_prot_hdrpush(dhd_pub_t *dhd, int ifidx, struct sk_buff *pktbuf)
{
#ifdef BDC
struct bdc_header *h;
#endif /* BDC */
DHD_TRACE(("%s: Enter\n", __func__));
#ifdef BDC
/* Push BDC header used to convey priority for buses that don't */
skb_push(pktbuf, BDC_HEADER_LEN);
h = (struct bdc_header *)(pktbuf->data);
h->flags = (BDC_PROTO_VER << BDC_FLAG_VER_SHIFT);
if (PKTSUMNEEDED(pktbuf))
h->flags |= BDC_FLAG_SUM_NEEDED;
h->priority = (pktbuf->priority & BDC_PRIORITY_MASK);
h->flags2 = 0;
h->rssi = 0;
#endif /* BDC */
BDC_SET_IF_IDX(h, ifidx);
}
int dhd_prot_hdrpull(dhd_pub_t *dhd, int *ifidx, struct sk_buff *pktbuf)
{
#ifdef BDC
struct bdc_header *h;
#endif
DHD_TRACE(("%s: Enter\n", __func__));
#ifdef BDC
/* Pop BDC header used to convey priority for buses that don't */
if (pktbuf->len < BDC_HEADER_LEN) {
DHD_ERROR(("%s: rx data too short (%d < %d)\n", __func__,
pktbuf->len, BDC_HEADER_LEN));
return -EBADE;
}
h = (struct bdc_header *)(pktbuf->data);
*ifidx = BDC_GET_IF_IDX(h);
if (*ifidx >= DHD_MAX_IFS) {
DHD_ERROR(("%s: rx data ifnum out of range (%d)\n",
__func__, *ifidx));
return -EBADE;
}
if (((h->flags & BDC_FLAG_VER_MASK) >> BDC_FLAG_VER_SHIFT) !=
BDC_PROTO_VER) {
DHD_ERROR(("%s: non-BDC packet received, flags 0x%x\n",
dhd_ifname(dhd, *ifidx), h->flags));
return -EBADE;
}
if (h->flags & BDC_FLAG_SUM_GOOD) {
DHD_INFO(("%s: BDC packet received with good rx-csum, "
"flags 0x%x\n",
dhd_ifname(dhd, *ifidx), h->flags));
PKTSETSUMGOOD(pktbuf, true);
}
pktbuf->priority = h->priority & BDC_PRIORITY_MASK;
skb_pull(pktbuf, BDC_HEADER_LEN);
#endif /* BDC */
return 0;
}
int dhd_prot_attach(dhd_pub_t *dhd)
{
dhd_prot_t *cdc;
cdc = kzalloc(sizeof(dhd_prot_t), GFP_ATOMIC);
if (!cdc) {
DHD_ERROR(("%s: kmalloc failed\n", __func__));
goto fail;
}
/* ensure that the msg buf directly follows the cdc msg struct */
if ((unsigned long)(&cdc->msg + 1) != (unsigned long)cdc->buf) {
DHD_ERROR(("dhd_prot_t is not correctly defined\n"));
goto fail;
}
dhd->prot = cdc;
#ifdef BDC
dhd->hdrlen += BDC_HEADER_LEN;
#endif
dhd->maxctl = WLC_IOCTL_MAXLEN + sizeof(cdc_ioctl_t) + ROUND_UP_MARGIN;
return 0;
fail:
kfree(cdc);
return -ENOMEM;
}
/* ~NOTE~ What if another thread is waiting on the semaphore? Holding it? */
void dhd_prot_detach(dhd_pub_t *dhd)
{
kfree(dhd->prot);
dhd->prot = NULL;
}
void dhd_prot_dstats(dhd_pub_t *dhd)
{
/* No stats from dongle added yet, copy bus stats */
dhd->dstats.tx_packets = dhd->tx_packets;
dhd->dstats.tx_errors = dhd->tx_errors;
dhd->dstats.rx_packets = dhd->rx_packets;
dhd->dstats.rx_errors = dhd->rx_errors;
dhd->dstats.rx_dropped = dhd->rx_dropped;
dhd->dstats.multicast = dhd->rx_multicast;
return;
}
int dhd_prot_init(dhd_pub_t *dhd)
{
int ret = 0;
char buf[128];
DHD_TRACE(("%s: Enter\n", __func__));
dhd_os_proto_block(dhd);
/* Get the device MAC address */
strcpy(buf, "cur_etheraddr");
ret = dhdcdc_query_ioctl(dhd, 0, WLC_GET_VAR, buf, sizeof(buf));
if (ret < 0) {
dhd_os_proto_unblock(dhd);
return ret;
}
memcpy(dhd->mac, buf, ETH_ALEN);
dhd_os_proto_unblock(dhd);
#ifdef EMBEDDED_PLATFORM
ret = dhd_preinit_ioctls(dhd);
#endif /* EMBEDDED_PLATFORM */
/* Always assumes wl for now */
dhd->iswl = true;
return ret;
}
void dhd_prot_stop(dhd_pub_t *dhd)
{
/* Nothing to do for CDC */
}
| gpl-2.0 |
playfulgod/kernel_lge_dory | drivers/gpu/drm/nouveau/dispnv04/cursor.c | 2684 | 2151 | #include <drm/drmP.h>
#include <drm/drm_mode.h>
#include "nouveau_drm.h"
#include "nouveau_reg.h"
#include "nouveau_crtc.h"
#include "hw.h"
static void
nv04_cursor_show(struct nouveau_crtc *nv_crtc, bool update)
{
nv_show_cursor(nv_crtc->base.dev, nv_crtc->index, true);
}
static void
nv04_cursor_hide(struct nouveau_crtc *nv_crtc, bool update)
{
nv_show_cursor(nv_crtc->base.dev, nv_crtc->index, false);
}
static void
nv04_cursor_set_pos(struct nouveau_crtc *nv_crtc, int x, int y)
{
nv_crtc->cursor_saved_x = x; nv_crtc->cursor_saved_y = y;
NVWriteRAMDAC(nv_crtc->base.dev, nv_crtc->index,
NV_PRAMDAC_CU_START_POS,
XLATE(y, 0, NV_PRAMDAC_CU_START_POS_Y) |
XLATE(x, 0, NV_PRAMDAC_CU_START_POS_X));
}
static void
crtc_wr_cio_state(struct drm_crtc *crtc, struct nv04_crtc_reg *crtcstate, int index)
{
NVWriteVgaCrtc(crtc->dev, nouveau_crtc(crtc)->index, index,
crtcstate->CRTC[index]);
}
static void
nv04_cursor_set_offset(struct nouveau_crtc *nv_crtc, uint32_t offset)
{
struct drm_device *dev = nv_crtc->base.dev;
struct nouveau_drm *drm = nouveau_drm(dev);
struct nv04_crtc_reg *regp = &nv04_display(dev)->mode_reg.crtc_reg[nv_crtc->index];
struct drm_crtc *crtc = &nv_crtc->base;
regp->CRTC[NV_CIO_CRE_HCUR_ADDR0_INDEX] =
MASK(NV_CIO_CRE_HCUR_ASI) |
XLATE(offset, 17, NV_CIO_CRE_HCUR_ADDR0_ADR);
regp->CRTC[NV_CIO_CRE_HCUR_ADDR1_INDEX] =
XLATE(offset, 11, NV_CIO_CRE_HCUR_ADDR1_ADR);
if (crtc->mode.flags & DRM_MODE_FLAG_DBLSCAN)
regp->CRTC[NV_CIO_CRE_HCUR_ADDR1_INDEX] |=
MASK(NV_CIO_CRE_HCUR_ADDR1_CUR_DBL);
regp->CRTC[NV_CIO_CRE_HCUR_ADDR2_INDEX] = offset >> 24;
crtc_wr_cio_state(crtc, regp, NV_CIO_CRE_HCUR_ADDR0_INDEX);
crtc_wr_cio_state(crtc, regp, NV_CIO_CRE_HCUR_ADDR1_INDEX);
crtc_wr_cio_state(crtc, regp, NV_CIO_CRE_HCUR_ADDR2_INDEX);
if (nv_device(drm->device)->card_type == NV_40)
nv_fix_nv40_hw_cursor(dev, nv_crtc->index);
}
int
nv04_cursor_init(struct nouveau_crtc *crtc)
{
crtc->cursor.set_offset = nv04_cursor_set_offset;
crtc->cursor.set_pos = nv04_cursor_set_pos;
crtc->cursor.hide = nv04_cursor_hide;
crtc->cursor.show = nv04_cursor_show;
return 0;
}
| gpl-2.0 |
codename13/android_kernel_ba2x_2.0 | drivers/pci/pcie/aer/aerdrv_core.c | 2684 | 21031 | /*
* drivers/pci/pcie/aer/aerdrv_core.c
*
* 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.
*
* This file implements the core part of PCI-Express AER. When an pci-express
* error is delivered, an error message will be collected and printed to
* console, then, an error recovery procedure will be executed by following
* the pci error recovery rules.
*
* Copyright (C) 2006 Intel Corp.
* Tom Long Nguyen (tom.l.nguyen@intel.com)
* Zhang Yanmin (yanmin.zhang@intel.com)
*
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/pm.h>
#include <linux/suspend.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include "aerdrv.h"
static int forceload;
static int nosourceid;
module_param(forceload, bool, 0);
module_param(nosourceid, bool, 0);
int pci_enable_pcie_error_reporting(struct pci_dev *dev)
{
u16 reg16 = 0;
int pos;
if (pcie_aer_get_firmware_first(dev))
return -EIO;
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR);
if (!pos)
return -EIO;
pos = pci_pcie_cap(dev);
if (!pos)
return -EIO;
pci_read_config_word(dev, pos + PCI_EXP_DEVCTL, ®16);
reg16 |= (PCI_EXP_DEVCTL_CERE |
PCI_EXP_DEVCTL_NFERE |
PCI_EXP_DEVCTL_FERE |
PCI_EXP_DEVCTL_URRE);
pci_write_config_word(dev, pos + PCI_EXP_DEVCTL, reg16);
return 0;
}
EXPORT_SYMBOL_GPL(pci_enable_pcie_error_reporting);
int pci_disable_pcie_error_reporting(struct pci_dev *dev)
{
u16 reg16 = 0;
int pos;
if (pcie_aer_get_firmware_first(dev))
return -EIO;
pos = pci_pcie_cap(dev);
if (!pos)
return -EIO;
pci_read_config_word(dev, pos + PCI_EXP_DEVCTL, ®16);
reg16 &= ~(PCI_EXP_DEVCTL_CERE |
PCI_EXP_DEVCTL_NFERE |
PCI_EXP_DEVCTL_FERE |
PCI_EXP_DEVCTL_URRE);
pci_write_config_word(dev, pos + PCI_EXP_DEVCTL, reg16);
return 0;
}
EXPORT_SYMBOL_GPL(pci_disable_pcie_error_reporting);
int pci_cleanup_aer_uncorrect_error_status(struct pci_dev *dev)
{
int pos;
u32 status;
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR);
if (!pos)
return -EIO;
pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, &status);
if (status)
pci_write_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, status);
return 0;
}
EXPORT_SYMBOL_GPL(pci_cleanup_aer_uncorrect_error_status);
/**
* add_error_device - list device to be handled
* @e_info: pointer to error info
* @dev: pointer to pci_dev to be added
*/
static int add_error_device(struct aer_err_info *e_info, struct pci_dev *dev)
{
if (e_info->error_dev_num < AER_MAX_MULTI_ERR_DEVICES) {
e_info->dev[e_info->error_dev_num] = dev;
e_info->error_dev_num++;
return 0;
}
return -ENOSPC;
}
#define PCI_BUS(x) (((x) >> 8) & 0xff)
/**
* is_error_source - check whether the device is source of reported error
* @dev: pointer to pci_dev to be checked
* @e_info: pointer to reported error info
*/
static bool is_error_source(struct pci_dev *dev, struct aer_err_info *e_info)
{
int pos;
u32 status, mask;
u16 reg16;
/*
* When bus id is equal to 0, it might be a bad id
* reported by root port.
*/
if (!nosourceid && (PCI_BUS(e_info->id) != 0)) {
/* Device ID match? */
if (e_info->id == ((dev->bus->number << 8) | dev->devfn))
return true;
/* Continue id comparing if there is no multiple error */
if (!e_info->multi_error_valid)
return false;
}
/*
* When either
* 1) nosourceid==y;
* 2) bus id is equal to 0. Some ports might lose the bus
* id of error source id;
* 3) There are multiple errors and prior id comparing fails;
* We check AER status registers to find possible reporter.
*/
if (atomic_read(&dev->enable_cnt) == 0)
return false;
pos = pci_pcie_cap(dev);
if (!pos)
return false;
/* Check if AER is enabled */
pci_read_config_word(dev, pos + PCI_EXP_DEVCTL, ®16);
if (!(reg16 & (
PCI_EXP_DEVCTL_CERE |
PCI_EXP_DEVCTL_NFERE |
PCI_EXP_DEVCTL_FERE |
PCI_EXP_DEVCTL_URRE)))
return false;
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR);
if (!pos)
return false;
/* Check if error is recorded */
if (e_info->severity == AER_CORRECTABLE) {
pci_read_config_dword(dev, pos + PCI_ERR_COR_STATUS, &status);
pci_read_config_dword(dev, pos + PCI_ERR_COR_MASK, &mask);
} else {
pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS, &status);
pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_MASK, &mask);
}
if (status & ~mask)
return true;
return false;
}
static int find_device_iter(struct pci_dev *dev, void *data)
{
struct aer_err_info *e_info = (struct aer_err_info *)data;
if (is_error_source(dev, e_info)) {
/* List this device */
if (add_error_device(e_info, dev)) {
/* We cannot handle more... Stop iteration */
/* TODO: Should print error message here? */
return 1;
}
/* If there is only a single error, stop iteration */
if (!e_info->multi_error_valid)
return 1;
}
return 0;
}
/**
* find_source_device - search through device hierarchy for source device
* @parent: pointer to Root Port pci_dev data structure
* @e_info: including detailed error information such like id
*
* Return true if found.
*
* Invoked by DPC when error is detected at the Root Port.
* Caller of this function must set id, severity, and multi_error_valid of
* struct aer_err_info pointed by @e_info properly. This function must fill
* e_info->error_dev_num and e_info->dev[], based on the given information.
*/
static bool find_source_device(struct pci_dev *parent,
struct aer_err_info *e_info)
{
struct pci_dev *dev = parent;
int result;
/* Must reset in this function */
e_info->error_dev_num = 0;
/* Is Root Port an agent that sends error message? */
result = find_device_iter(dev, e_info);
if (result)
return true;
pci_walk_bus(parent->subordinate, find_device_iter, e_info);
if (!e_info->error_dev_num) {
dev_printk(KERN_DEBUG, &parent->dev,
"can't find device of ID%04x\n",
e_info->id);
return false;
}
return true;
}
static int report_error_detected(struct pci_dev *dev, void *data)
{
pci_ers_result_t vote;
struct pci_error_handlers *err_handler;
struct aer_broadcast_data *result_data;
result_data = (struct aer_broadcast_data *) data;
dev->error_state = result_data->state;
if (!dev->driver ||
!dev->driver->err_handler ||
!dev->driver->err_handler->error_detected) {
if (result_data->state == pci_channel_io_frozen &&
!(dev->hdr_type & PCI_HEADER_TYPE_BRIDGE)) {
/*
* In case of fatal recovery, if one of down-
* stream device has no driver. We might be
* unable to recover because a later insmod
* of a driver for this device is unaware of
* its hw state.
*/
dev_printk(KERN_DEBUG, &dev->dev, "device has %s\n",
dev->driver ?
"no AER-aware driver" : "no driver");
}
return 0;
}
err_handler = dev->driver->err_handler;
vote = err_handler->error_detected(dev, result_data->state);
result_data->result = merge_result(result_data->result, vote);
return 0;
}
static int report_mmio_enabled(struct pci_dev *dev, void *data)
{
pci_ers_result_t vote;
struct pci_error_handlers *err_handler;
struct aer_broadcast_data *result_data;
result_data = (struct aer_broadcast_data *) data;
if (!dev->driver ||
!dev->driver->err_handler ||
!dev->driver->err_handler->mmio_enabled)
return 0;
err_handler = dev->driver->err_handler;
vote = err_handler->mmio_enabled(dev);
result_data->result = merge_result(result_data->result, vote);
return 0;
}
static int report_slot_reset(struct pci_dev *dev, void *data)
{
pci_ers_result_t vote;
struct pci_error_handlers *err_handler;
struct aer_broadcast_data *result_data;
result_data = (struct aer_broadcast_data *) data;
if (!dev->driver ||
!dev->driver->err_handler ||
!dev->driver->err_handler->slot_reset)
return 0;
err_handler = dev->driver->err_handler;
vote = err_handler->slot_reset(dev);
result_data->result = merge_result(result_data->result, vote);
return 0;
}
static int report_resume(struct pci_dev *dev, void *data)
{
struct pci_error_handlers *err_handler;
dev->error_state = pci_channel_io_normal;
if (!dev->driver ||
!dev->driver->err_handler ||
!dev->driver->err_handler->resume)
return 0;
err_handler = dev->driver->err_handler;
err_handler->resume(dev);
return 0;
}
/**
* broadcast_error_message - handle message broadcast to downstream drivers
* @dev: pointer to from where in a hierarchy message is broadcasted down
* @state: error state
* @error_mesg: message to print
* @cb: callback to be broadcasted
*
* Invoked during error recovery process. Once being invoked, the content
* of error severity will be broadcasted to all downstream drivers in a
* hierarchy in question.
*/
static pci_ers_result_t broadcast_error_message(struct pci_dev *dev,
enum pci_channel_state state,
char *error_mesg,
int (*cb)(struct pci_dev *, void *))
{
struct aer_broadcast_data result_data;
dev_printk(KERN_DEBUG, &dev->dev, "broadcast %s message\n", error_mesg);
result_data.state = state;
if (cb == report_error_detected)
result_data.result = PCI_ERS_RESULT_CAN_RECOVER;
else
result_data.result = PCI_ERS_RESULT_RECOVERED;
if (dev->hdr_type & PCI_HEADER_TYPE_BRIDGE) {
/*
* If the error is reported by a bridge, we think this error
* is related to the downstream link of the bridge, so we
* do error recovery on all subordinates of the bridge instead
* of the bridge and clear the error status of the bridge.
*/
if (cb == report_error_detected)
dev->error_state = state;
pci_walk_bus(dev->subordinate, cb, &result_data);
if (cb == report_resume) {
pci_cleanup_aer_uncorrect_error_status(dev);
dev->error_state = pci_channel_io_normal;
}
} else {
/*
* If the error is reported by an end point, we think this
* error is related to the upstream link of the end point.
*/
pci_walk_bus(dev->bus, cb, &result_data);
}
return result_data.result;
}
/**
* aer_do_secondary_bus_reset - perform secondary bus reset
* @dev: pointer to bridge's pci_dev data structure
*
* Invoked when performing link reset at Root Port or Downstream Port.
*/
void aer_do_secondary_bus_reset(struct pci_dev *dev)
{
u16 p2p_ctrl;
/* Assert Secondary Bus Reset */
pci_read_config_word(dev, PCI_BRIDGE_CONTROL, &p2p_ctrl);
p2p_ctrl |= PCI_BRIDGE_CTL_BUS_RESET;
pci_write_config_word(dev, PCI_BRIDGE_CONTROL, p2p_ctrl);
/*
* we should send hot reset message for 2ms to allow it time to
* propagate to all downstream ports
*/
msleep(2);
/* De-assert Secondary Bus Reset */
p2p_ctrl &= ~PCI_BRIDGE_CTL_BUS_RESET;
pci_write_config_word(dev, PCI_BRIDGE_CONTROL, p2p_ctrl);
/*
* System software must wait for at least 100ms from the end
* of a reset of one or more device before it is permitted
* to issue Configuration Requests to those devices.
*/
msleep(200);
}
/**
* default_downstream_reset_link - default reset function for Downstream Port
* @dev: pointer to downstream port's pci_dev data structure
*
* Invoked when performing link reset at Downstream Port w/ no aer driver.
*/
static pci_ers_result_t default_downstream_reset_link(struct pci_dev *dev)
{
aer_do_secondary_bus_reset(dev);
dev_printk(KERN_DEBUG, &dev->dev,
"Downstream Port link has been reset\n");
return PCI_ERS_RESULT_RECOVERED;
}
static int find_aer_service_iter(struct device *device, void *data)
{
struct pcie_port_service_driver *service_driver, **drv;
drv = (struct pcie_port_service_driver **) data;
if (device->bus == &pcie_port_bus_type && device->driver) {
service_driver = to_service_driver(device->driver);
if (service_driver->service == PCIE_PORT_SERVICE_AER) {
*drv = service_driver;
return 1;
}
}
return 0;
}
static struct pcie_port_service_driver *find_aer_service(struct pci_dev *dev)
{
struct pcie_port_service_driver *drv = NULL;
device_for_each_child(&dev->dev, &drv, find_aer_service_iter);
return drv;
}
static pci_ers_result_t reset_link(struct pcie_device *aerdev,
struct pci_dev *dev)
{
struct pci_dev *udev;
pci_ers_result_t status;
struct pcie_port_service_driver *driver;
if (dev->hdr_type & PCI_HEADER_TYPE_BRIDGE) {
/* Reset this port for all subordinates */
udev = dev;
} else {
/* Reset the upstream component (likely downstream port) */
udev = dev->bus->self;
}
/* Use the aer driver of the component firstly */
driver = find_aer_service(udev);
if (driver && driver->reset_link) {
status = driver->reset_link(udev);
} else if (udev->pcie_type == PCI_EXP_TYPE_DOWNSTREAM) {
status = default_downstream_reset_link(udev);
} else {
dev_printk(KERN_DEBUG, &dev->dev,
"no link-reset support at upstream device %s\n",
pci_name(udev));
return PCI_ERS_RESULT_DISCONNECT;
}
if (status != PCI_ERS_RESULT_RECOVERED) {
dev_printk(KERN_DEBUG, &dev->dev,
"link reset at upstream device %s failed\n",
pci_name(udev));
return PCI_ERS_RESULT_DISCONNECT;
}
return status;
}
/**
* do_recovery - handle nonfatal/fatal error recovery process
* @aerdev: pointer to a pcie_device data structure of root port
* @dev: pointer to a pci_dev data structure of agent detecting an error
* @severity: error severity type
*
* Invoked when an error is nonfatal/fatal. Once being invoked, broadcast
* error detected message to all downstream drivers within a hierarchy in
* question and return the returned code.
*/
static void do_recovery(struct pcie_device *aerdev, struct pci_dev *dev,
int severity)
{
pci_ers_result_t status, result = PCI_ERS_RESULT_RECOVERED;
enum pci_channel_state state;
if (severity == AER_FATAL)
state = pci_channel_io_frozen;
else
state = pci_channel_io_normal;
status = broadcast_error_message(dev,
state,
"error_detected",
report_error_detected);
if (severity == AER_FATAL) {
result = reset_link(aerdev, dev);
if (result != PCI_ERS_RESULT_RECOVERED)
goto failed;
}
if (status == PCI_ERS_RESULT_CAN_RECOVER)
status = broadcast_error_message(dev,
state,
"mmio_enabled",
report_mmio_enabled);
if (status == PCI_ERS_RESULT_NEED_RESET) {
/*
* TODO: Should call platform-specific
* functions to reset slot before calling
* drivers' slot_reset callbacks?
*/
status = broadcast_error_message(dev,
state,
"slot_reset",
report_slot_reset);
}
if (status != PCI_ERS_RESULT_RECOVERED)
goto failed;
broadcast_error_message(dev,
state,
"resume",
report_resume);
dev_printk(KERN_DEBUG, &dev->dev,
"AER driver successfully recovered\n");
return;
failed:
/* TODO: Should kernel panic here? */
dev_printk(KERN_DEBUG, &dev->dev,
"AER driver didn't recover\n");
}
/**
* handle_error_source - handle logging error into an event log
* @aerdev: pointer to pcie_device data structure of the root port
* @dev: pointer to pci_dev data structure of error source device
* @info: comprehensive error information
*
* Invoked when an error being detected by Root Port.
*/
static void handle_error_source(struct pcie_device *aerdev,
struct pci_dev *dev,
struct aer_err_info *info)
{
int pos;
if (info->severity == AER_CORRECTABLE) {
/*
* Correctable error does not need software intevention.
* No need to go through error recovery process.
*/
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR);
if (pos)
pci_write_config_dword(dev, pos + PCI_ERR_COR_STATUS,
info->status);
} else
do_recovery(aerdev, dev, info->severity);
}
/**
* get_device_error_info - read error status from dev and store it to info
* @dev: pointer to the device expected to have a error record
* @info: pointer to structure to store the error record
*
* Return 1 on success, 0 on error.
*
* Note that @info is reused among all error devices. Clear fields properly.
*/
static int get_device_error_info(struct pci_dev *dev, struct aer_err_info *info)
{
int pos, temp;
/* Must reset in this function */
info->status = 0;
info->tlp_header_valid = 0;
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR);
/* The device might not support AER */
if (!pos)
return 1;
if (info->severity == AER_CORRECTABLE) {
pci_read_config_dword(dev, pos + PCI_ERR_COR_STATUS,
&info->status);
pci_read_config_dword(dev, pos + PCI_ERR_COR_MASK,
&info->mask);
if (!(info->status & ~info->mask))
return 0;
} else if (dev->hdr_type & PCI_HEADER_TYPE_BRIDGE ||
info->severity == AER_NONFATAL) {
/* Link is still healthy for IO reads */
pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS,
&info->status);
pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_MASK,
&info->mask);
if (!(info->status & ~info->mask))
return 0;
/* Get First Error Pointer */
pci_read_config_dword(dev, pos + PCI_ERR_CAP, &temp);
info->first_error = PCI_ERR_CAP_FEP(temp);
if (info->status & AER_LOG_TLP_MASKS) {
info->tlp_header_valid = 1;
pci_read_config_dword(dev,
pos + PCI_ERR_HEADER_LOG, &info->tlp.dw0);
pci_read_config_dword(dev,
pos + PCI_ERR_HEADER_LOG + 4, &info->tlp.dw1);
pci_read_config_dword(dev,
pos + PCI_ERR_HEADER_LOG + 8, &info->tlp.dw2);
pci_read_config_dword(dev,
pos + PCI_ERR_HEADER_LOG + 12, &info->tlp.dw3);
}
}
return 1;
}
static inline void aer_process_err_devices(struct pcie_device *p_device,
struct aer_err_info *e_info)
{
int i;
/* Report all before handle them, not to lost records by reset etc. */
for (i = 0; i < e_info->error_dev_num && e_info->dev[i]; i++) {
if (get_device_error_info(e_info->dev[i], e_info))
aer_print_error(e_info->dev[i], e_info);
}
for (i = 0; i < e_info->error_dev_num && e_info->dev[i]; i++) {
if (get_device_error_info(e_info->dev[i], e_info))
handle_error_source(p_device, e_info->dev[i], e_info);
}
}
/**
* aer_isr_one_error - consume an error detected by root port
* @p_device: pointer to error root port service device
* @e_src: pointer to an error source
*/
static void aer_isr_one_error(struct pcie_device *p_device,
struct aer_err_source *e_src)
{
struct aer_err_info *e_info;
/* struct aer_err_info might be big, so we allocate it with slab */
e_info = kmalloc(sizeof(struct aer_err_info), GFP_KERNEL);
if (!e_info) {
dev_printk(KERN_DEBUG, &p_device->port->dev,
"Can't allocate mem when processing AER errors\n");
return;
}
/*
* There is a possibility that both correctable error and
* uncorrectable error being logged. Report correctable error first.
*/
if (e_src->status & PCI_ERR_ROOT_COR_RCV) {
e_info->id = ERR_COR_ID(e_src->id);
e_info->severity = AER_CORRECTABLE;
if (e_src->status & PCI_ERR_ROOT_MULTI_COR_RCV)
e_info->multi_error_valid = 1;
else
e_info->multi_error_valid = 0;
aer_print_port_info(p_device->port, e_info);
if (find_source_device(p_device->port, e_info))
aer_process_err_devices(p_device, e_info);
}
if (e_src->status & PCI_ERR_ROOT_UNCOR_RCV) {
e_info->id = ERR_UNCOR_ID(e_src->id);
if (e_src->status & PCI_ERR_ROOT_FATAL_RCV)
e_info->severity = AER_FATAL;
else
e_info->severity = AER_NONFATAL;
if (e_src->status & PCI_ERR_ROOT_MULTI_UNCOR_RCV)
e_info->multi_error_valid = 1;
else
e_info->multi_error_valid = 0;
aer_print_port_info(p_device->port, e_info);
if (find_source_device(p_device->port, e_info))
aer_process_err_devices(p_device, e_info);
}
kfree(e_info);
}
/**
* get_e_source - retrieve an error source
* @rpc: pointer to the root port which holds an error
* @e_src: pointer to store retrieved error source
*
* Return 1 if an error source is retrieved, otherwise 0.
*
* Invoked by DPC handler to consume an error.
*/
static int get_e_source(struct aer_rpc *rpc, struct aer_err_source *e_src)
{
unsigned long flags;
/* Lock access to Root error producer/consumer index */
spin_lock_irqsave(&rpc->e_lock, flags);
if (rpc->prod_idx == rpc->cons_idx) {
spin_unlock_irqrestore(&rpc->e_lock, flags);
return 0;
}
*e_src = rpc->e_sources[rpc->cons_idx];
rpc->cons_idx++;
if (rpc->cons_idx == AER_ERROR_SOURCES_MAX)
rpc->cons_idx = 0;
spin_unlock_irqrestore(&rpc->e_lock, flags);
return 1;
}
/**
* aer_isr - consume errors detected by root port
* @work: definition of this work item
*
* Invoked, as DPC, when root port records new detected error
*/
void aer_isr(struct work_struct *work)
{
struct aer_rpc *rpc = container_of(work, struct aer_rpc, dpc_handler);
struct pcie_device *p_device = rpc->rpd;
struct aer_err_source uninitialized_var(e_src);
mutex_lock(&rpc->rpc_mutex);
while (get_e_source(rpc, &e_src))
aer_isr_one_error(p_device, &e_src);
mutex_unlock(&rpc->rpc_mutex);
wake_up(&rpc->wait_release);
}
/**
* aer_init - provide AER initialization
* @dev: pointer to AER pcie device
*
* Invoked when AER service driver is loaded.
*/
int aer_init(struct pcie_device *dev)
{
if (forceload) {
dev_printk(KERN_DEBUG, &dev->device,
"aerdrv forceload requested.\n");
pcie_aer_force_firmware_first(dev->port, 0);
}
return 0;
}
| gpl-2.0 |
TeamOrion-Devices/kernel_asus_grouper | arch/arm/mach-omap2/cm2xxx_3xxx.c | 2940 | 17969 | /*
* OMAP2/3 CM module functions
*
* Copyright (C) 2009 Nokia Corporation
* Paul Walmsley
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/spinlock.h>
#include <linux/list.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/io.h>
#include <plat/common.h>
#include "cm.h"
#include "cm2xxx_3xxx.h"
#include "cm-regbits-24xx.h"
#include "cm-regbits-34xx.h"
/* CM_AUTOIDLE_PLL.AUTO_* bit values for DPLLs */
#define DPLL_AUTOIDLE_DISABLE 0x0
#define OMAP2XXX_DPLL_AUTOIDLE_LOW_POWER_STOP 0x3
/* CM_AUTOIDLE_PLL.AUTO_* bit values for APLLs (OMAP2xxx only) */
#define OMAP2XXX_APLL_AUTOIDLE_DISABLE 0x0
#define OMAP2XXX_APLL_AUTOIDLE_LOW_POWER_STOP 0x3
static const u8 cm_idlest_offs[] = {
CM_IDLEST1, CM_IDLEST2, OMAP2430_CM_IDLEST3
};
u32 omap2_cm_read_mod_reg(s16 module, u16 idx)
{
return __raw_readl(cm_base + module + idx);
}
void omap2_cm_write_mod_reg(u32 val, s16 module, u16 idx)
{
__raw_writel(val, cm_base + module + idx);
}
/* Read-modify-write a register in a CM module. Caller must lock */
u32 omap2_cm_rmw_mod_reg_bits(u32 mask, u32 bits, s16 module, s16 idx)
{
u32 v;
v = omap2_cm_read_mod_reg(module, idx);
v &= ~mask;
v |= bits;
omap2_cm_write_mod_reg(v, module, idx);
return v;
}
u32 omap2_cm_set_mod_reg_bits(u32 bits, s16 module, s16 idx)
{
return omap2_cm_rmw_mod_reg_bits(bits, bits, module, idx);
}
u32 omap2_cm_clear_mod_reg_bits(u32 bits, s16 module, s16 idx)
{
return omap2_cm_rmw_mod_reg_bits(bits, 0x0, module, idx);
}
/*
*
*/
static void _write_clktrctrl(u8 c, s16 module, u32 mask)
{
u32 v;
v = omap2_cm_read_mod_reg(module, OMAP2_CM_CLKSTCTRL);
v &= ~mask;
v |= c << __ffs(mask);
omap2_cm_write_mod_reg(v, module, OMAP2_CM_CLKSTCTRL);
}
bool omap2_cm_is_clkdm_in_hwsup(s16 module, u32 mask)
{
u32 v;
bool ret = 0;
BUG_ON(!cpu_is_omap24xx() && !cpu_is_omap34xx());
v = omap2_cm_read_mod_reg(module, OMAP2_CM_CLKSTCTRL);
v &= mask;
v >>= __ffs(mask);
if (cpu_is_omap24xx())
ret = (v == OMAP24XX_CLKSTCTRL_ENABLE_AUTO) ? 1 : 0;
else
ret = (v == OMAP34XX_CLKSTCTRL_ENABLE_AUTO) ? 1 : 0;
return ret;
}
void omap2xxx_cm_clkdm_enable_hwsup(s16 module, u32 mask)
{
_write_clktrctrl(OMAP24XX_CLKSTCTRL_ENABLE_AUTO, module, mask);
}
void omap2xxx_cm_clkdm_disable_hwsup(s16 module, u32 mask)
{
_write_clktrctrl(OMAP24XX_CLKSTCTRL_DISABLE_AUTO, module, mask);
}
void omap3xxx_cm_clkdm_enable_hwsup(s16 module, u32 mask)
{
_write_clktrctrl(OMAP34XX_CLKSTCTRL_ENABLE_AUTO, module, mask);
}
void omap3xxx_cm_clkdm_disable_hwsup(s16 module, u32 mask)
{
_write_clktrctrl(OMAP34XX_CLKSTCTRL_DISABLE_AUTO, module, mask);
}
void omap3xxx_cm_clkdm_force_sleep(s16 module, u32 mask)
{
_write_clktrctrl(OMAP34XX_CLKSTCTRL_FORCE_SLEEP, module, mask);
}
void omap3xxx_cm_clkdm_force_wakeup(s16 module, u32 mask)
{
_write_clktrctrl(OMAP34XX_CLKSTCTRL_FORCE_WAKEUP, module, mask);
}
/*
* DPLL autoidle control
*/
static void _omap2xxx_set_dpll_autoidle(u8 m)
{
u32 v;
v = omap2_cm_read_mod_reg(PLL_MOD, CM_AUTOIDLE);
v &= ~OMAP24XX_AUTO_DPLL_MASK;
v |= m << OMAP24XX_AUTO_DPLL_SHIFT;
omap2_cm_write_mod_reg(v, PLL_MOD, CM_AUTOIDLE);
}
void omap2xxx_cm_set_dpll_disable_autoidle(void)
{
_omap2xxx_set_dpll_autoidle(OMAP2XXX_DPLL_AUTOIDLE_LOW_POWER_STOP);
}
void omap2xxx_cm_set_dpll_auto_low_power_stop(void)
{
_omap2xxx_set_dpll_autoidle(DPLL_AUTOIDLE_DISABLE);
}
/*
* APLL autoidle control
*/
static void _omap2xxx_set_apll_autoidle(u8 m, u32 mask)
{
u32 v;
v = omap2_cm_read_mod_reg(PLL_MOD, CM_AUTOIDLE);
v &= ~mask;
v |= m << __ffs(mask);
omap2_cm_write_mod_reg(v, PLL_MOD, CM_AUTOIDLE);
}
void omap2xxx_cm_set_apll54_disable_autoidle(void)
{
_omap2xxx_set_apll_autoidle(OMAP2XXX_APLL_AUTOIDLE_LOW_POWER_STOP,
OMAP24XX_AUTO_54M_MASK);
}
void omap2xxx_cm_set_apll54_auto_low_power_stop(void)
{
_omap2xxx_set_apll_autoidle(OMAP2XXX_APLL_AUTOIDLE_DISABLE,
OMAP24XX_AUTO_54M_MASK);
}
void omap2xxx_cm_set_apll96_disable_autoidle(void)
{
_omap2xxx_set_apll_autoidle(OMAP2XXX_APLL_AUTOIDLE_LOW_POWER_STOP,
OMAP24XX_AUTO_96M_MASK);
}
void omap2xxx_cm_set_apll96_auto_low_power_stop(void)
{
_omap2xxx_set_apll_autoidle(OMAP2XXX_APLL_AUTOIDLE_DISABLE,
OMAP24XX_AUTO_96M_MASK);
}
/*
*
*/
/**
* omap2_cm_wait_idlest_ready - wait for a module to leave idle or standby
* @prcm_mod: PRCM module offset
* @idlest_id: CM_IDLESTx register ID (i.e., x = 1, 2, 3)
* @idlest_shift: shift of the bit in the CM_IDLEST* register to check
*
* XXX document
*/
int omap2_cm_wait_module_ready(s16 prcm_mod, u8 idlest_id, u8 idlest_shift)
{
int ena = 0, i = 0;
u8 cm_idlest_reg;
u32 mask;
if (!idlest_id || (idlest_id > ARRAY_SIZE(cm_idlest_offs)))
return -EINVAL;
cm_idlest_reg = cm_idlest_offs[idlest_id - 1];
mask = 1 << idlest_shift;
if (cpu_is_omap24xx())
ena = mask;
else if (cpu_is_omap34xx())
ena = 0;
else
BUG();
omap_test_timeout(((omap2_cm_read_mod_reg(prcm_mod, cm_idlest_reg) & mask) == ena),
MAX_MODULE_READY_TIME, i);
return (i < MAX_MODULE_READY_TIME) ? 0 : -EBUSY;
}
/*
* Context save/restore code - OMAP3 only
*/
#ifdef CONFIG_ARCH_OMAP3
struct omap3_cm_regs {
u32 iva2_cm_clksel1;
u32 iva2_cm_clksel2;
u32 cm_sysconfig;
u32 sgx_cm_clksel;
u32 dss_cm_clksel;
u32 cam_cm_clksel;
u32 per_cm_clksel;
u32 emu_cm_clksel;
u32 emu_cm_clkstctrl;
u32 pll_cm_autoidle;
u32 pll_cm_autoidle2;
u32 pll_cm_clksel4;
u32 pll_cm_clksel5;
u32 pll_cm_clken2;
u32 cm_polctrl;
u32 iva2_cm_fclken;
u32 iva2_cm_clken_pll;
u32 core_cm_fclken1;
u32 core_cm_fclken3;
u32 sgx_cm_fclken;
u32 wkup_cm_fclken;
u32 dss_cm_fclken;
u32 cam_cm_fclken;
u32 per_cm_fclken;
u32 usbhost_cm_fclken;
u32 core_cm_iclken1;
u32 core_cm_iclken2;
u32 core_cm_iclken3;
u32 sgx_cm_iclken;
u32 wkup_cm_iclken;
u32 dss_cm_iclken;
u32 cam_cm_iclken;
u32 per_cm_iclken;
u32 usbhost_cm_iclken;
u32 iva2_cm_autoidle2;
u32 mpu_cm_autoidle2;
u32 iva2_cm_clkstctrl;
u32 mpu_cm_clkstctrl;
u32 core_cm_clkstctrl;
u32 sgx_cm_clkstctrl;
u32 dss_cm_clkstctrl;
u32 cam_cm_clkstctrl;
u32 per_cm_clkstctrl;
u32 neon_cm_clkstctrl;
u32 usbhost_cm_clkstctrl;
u32 core_cm_autoidle1;
u32 core_cm_autoidle2;
u32 core_cm_autoidle3;
u32 wkup_cm_autoidle;
u32 dss_cm_autoidle;
u32 cam_cm_autoidle;
u32 per_cm_autoidle;
u32 usbhost_cm_autoidle;
u32 sgx_cm_sleepdep;
u32 dss_cm_sleepdep;
u32 cam_cm_sleepdep;
u32 per_cm_sleepdep;
u32 usbhost_cm_sleepdep;
u32 cm_clkout_ctrl;
};
static struct omap3_cm_regs cm_context;
void omap3_cm_save_context(void)
{
cm_context.iva2_cm_clksel1 =
omap2_cm_read_mod_reg(OMAP3430_IVA2_MOD, CM_CLKSEL1);
cm_context.iva2_cm_clksel2 =
omap2_cm_read_mod_reg(OMAP3430_IVA2_MOD, CM_CLKSEL2);
cm_context.cm_sysconfig = __raw_readl(OMAP3430_CM_SYSCONFIG);
cm_context.sgx_cm_clksel =
omap2_cm_read_mod_reg(OMAP3430ES2_SGX_MOD, CM_CLKSEL);
cm_context.dss_cm_clksel =
omap2_cm_read_mod_reg(OMAP3430_DSS_MOD, CM_CLKSEL);
cm_context.cam_cm_clksel =
omap2_cm_read_mod_reg(OMAP3430_CAM_MOD, CM_CLKSEL);
cm_context.per_cm_clksel =
omap2_cm_read_mod_reg(OMAP3430_PER_MOD, CM_CLKSEL);
cm_context.emu_cm_clksel =
omap2_cm_read_mod_reg(OMAP3430_EMU_MOD, CM_CLKSEL1);
cm_context.emu_cm_clkstctrl =
omap2_cm_read_mod_reg(OMAP3430_EMU_MOD, OMAP2_CM_CLKSTCTRL);
/*
* As per erratum i671, ROM code does not respect the PER DPLL
* programming scheme if CM_AUTOIDLE_PLL.AUTO_PERIPH_DPLL == 1.
* In this case, even though this register has been saved in
* scratchpad contents, we need to restore AUTO_PERIPH_DPLL
* by ourselves. So, we need to save it anyway.
*/
cm_context.pll_cm_autoidle =
omap2_cm_read_mod_reg(PLL_MOD, CM_AUTOIDLE);
cm_context.pll_cm_autoidle2 =
omap2_cm_read_mod_reg(PLL_MOD, CM_AUTOIDLE2);
cm_context.pll_cm_clksel4 =
omap2_cm_read_mod_reg(PLL_MOD, OMAP3430ES2_CM_CLKSEL4);
cm_context.pll_cm_clksel5 =
omap2_cm_read_mod_reg(PLL_MOD, OMAP3430ES2_CM_CLKSEL5);
cm_context.pll_cm_clken2 =
omap2_cm_read_mod_reg(PLL_MOD, OMAP3430ES2_CM_CLKEN2);
cm_context.cm_polctrl = __raw_readl(OMAP3430_CM_POLCTRL);
cm_context.iva2_cm_fclken =
omap2_cm_read_mod_reg(OMAP3430_IVA2_MOD, CM_FCLKEN);
cm_context.iva2_cm_clken_pll =
omap2_cm_read_mod_reg(OMAP3430_IVA2_MOD, OMAP3430_CM_CLKEN_PLL);
cm_context.core_cm_fclken1 =
omap2_cm_read_mod_reg(CORE_MOD, CM_FCLKEN1);
cm_context.core_cm_fclken3 =
omap2_cm_read_mod_reg(CORE_MOD, OMAP3430ES2_CM_FCLKEN3);
cm_context.sgx_cm_fclken =
omap2_cm_read_mod_reg(OMAP3430ES2_SGX_MOD, CM_FCLKEN);
cm_context.wkup_cm_fclken =
omap2_cm_read_mod_reg(WKUP_MOD, CM_FCLKEN);
cm_context.dss_cm_fclken =
omap2_cm_read_mod_reg(OMAP3430_DSS_MOD, CM_FCLKEN);
cm_context.cam_cm_fclken =
omap2_cm_read_mod_reg(OMAP3430_CAM_MOD, CM_FCLKEN);
cm_context.per_cm_fclken =
omap2_cm_read_mod_reg(OMAP3430_PER_MOD, CM_FCLKEN);
cm_context.usbhost_cm_fclken =
omap2_cm_read_mod_reg(OMAP3430ES2_USBHOST_MOD, CM_FCLKEN);
cm_context.core_cm_iclken1 =
omap2_cm_read_mod_reg(CORE_MOD, CM_ICLKEN1);
cm_context.core_cm_iclken2 =
omap2_cm_read_mod_reg(CORE_MOD, CM_ICLKEN2);
cm_context.core_cm_iclken3 =
omap2_cm_read_mod_reg(CORE_MOD, CM_ICLKEN3);
cm_context.sgx_cm_iclken =
omap2_cm_read_mod_reg(OMAP3430ES2_SGX_MOD, CM_ICLKEN);
cm_context.wkup_cm_iclken =
omap2_cm_read_mod_reg(WKUP_MOD, CM_ICLKEN);
cm_context.dss_cm_iclken =
omap2_cm_read_mod_reg(OMAP3430_DSS_MOD, CM_ICLKEN);
cm_context.cam_cm_iclken =
omap2_cm_read_mod_reg(OMAP3430_CAM_MOD, CM_ICLKEN);
cm_context.per_cm_iclken =
omap2_cm_read_mod_reg(OMAP3430_PER_MOD, CM_ICLKEN);
cm_context.usbhost_cm_iclken =
omap2_cm_read_mod_reg(OMAP3430ES2_USBHOST_MOD, CM_ICLKEN);
cm_context.iva2_cm_autoidle2 =
omap2_cm_read_mod_reg(OMAP3430_IVA2_MOD, CM_AUTOIDLE2);
cm_context.mpu_cm_autoidle2 =
omap2_cm_read_mod_reg(MPU_MOD, CM_AUTOIDLE2);
cm_context.iva2_cm_clkstctrl =
omap2_cm_read_mod_reg(OMAP3430_IVA2_MOD, OMAP2_CM_CLKSTCTRL);
cm_context.mpu_cm_clkstctrl =
omap2_cm_read_mod_reg(MPU_MOD, OMAP2_CM_CLKSTCTRL);
cm_context.core_cm_clkstctrl =
omap2_cm_read_mod_reg(CORE_MOD, OMAP2_CM_CLKSTCTRL);
cm_context.sgx_cm_clkstctrl =
omap2_cm_read_mod_reg(OMAP3430ES2_SGX_MOD, OMAP2_CM_CLKSTCTRL);
cm_context.dss_cm_clkstctrl =
omap2_cm_read_mod_reg(OMAP3430_DSS_MOD, OMAP2_CM_CLKSTCTRL);
cm_context.cam_cm_clkstctrl =
omap2_cm_read_mod_reg(OMAP3430_CAM_MOD, OMAP2_CM_CLKSTCTRL);
cm_context.per_cm_clkstctrl =
omap2_cm_read_mod_reg(OMAP3430_PER_MOD, OMAP2_CM_CLKSTCTRL);
cm_context.neon_cm_clkstctrl =
omap2_cm_read_mod_reg(OMAP3430_NEON_MOD, OMAP2_CM_CLKSTCTRL);
cm_context.usbhost_cm_clkstctrl =
omap2_cm_read_mod_reg(OMAP3430ES2_USBHOST_MOD,
OMAP2_CM_CLKSTCTRL);
cm_context.core_cm_autoidle1 =
omap2_cm_read_mod_reg(CORE_MOD, CM_AUTOIDLE1);
cm_context.core_cm_autoidle2 =
omap2_cm_read_mod_reg(CORE_MOD, CM_AUTOIDLE2);
cm_context.core_cm_autoidle3 =
omap2_cm_read_mod_reg(CORE_MOD, CM_AUTOIDLE3);
cm_context.wkup_cm_autoidle =
omap2_cm_read_mod_reg(WKUP_MOD, CM_AUTOIDLE);
cm_context.dss_cm_autoidle =
omap2_cm_read_mod_reg(OMAP3430_DSS_MOD, CM_AUTOIDLE);
cm_context.cam_cm_autoidle =
omap2_cm_read_mod_reg(OMAP3430_CAM_MOD, CM_AUTOIDLE);
cm_context.per_cm_autoidle =
omap2_cm_read_mod_reg(OMAP3430_PER_MOD, CM_AUTOIDLE);
cm_context.usbhost_cm_autoidle =
omap2_cm_read_mod_reg(OMAP3430ES2_USBHOST_MOD, CM_AUTOIDLE);
cm_context.sgx_cm_sleepdep =
omap2_cm_read_mod_reg(OMAP3430ES2_SGX_MOD,
OMAP3430_CM_SLEEPDEP);
cm_context.dss_cm_sleepdep =
omap2_cm_read_mod_reg(OMAP3430_DSS_MOD, OMAP3430_CM_SLEEPDEP);
cm_context.cam_cm_sleepdep =
omap2_cm_read_mod_reg(OMAP3430_CAM_MOD, OMAP3430_CM_SLEEPDEP);
cm_context.per_cm_sleepdep =
omap2_cm_read_mod_reg(OMAP3430_PER_MOD, OMAP3430_CM_SLEEPDEP);
cm_context.usbhost_cm_sleepdep =
omap2_cm_read_mod_reg(OMAP3430ES2_USBHOST_MOD,
OMAP3430_CM_SLEEPDEP);
cm_context.cm_clkout_ctrl =
omap2_cm_read_mod_reg(OMAP3430_CCR_MOD,
OMAP3_CM_CLKOUT_CTRL_OFFSET);
}
void omap3_cm_restore_context(void)
{
omap2_cm_write_mod_reg(cm_context.iva2_cm_clksel1, OMAP3430_IVA2_MOD,
CM_CLKSEL1);
omap2_cm_write_mod_reg(cm_context.iva2_cm_clksel2, OMAP3430_IVA2_MOD,
CM_CLKSEL2);
__raw_writel(cm_context.cm_sysconfig, OMAP3430_CM_SYSCONFIG);
omap2_cm_write_mod_reg(cm_context.sgx_cm_clksel, OMAP3430ES2_SGX_MOD,
CM_CLKSEL);
omap2_cm_write_mod_reg(cm_context.dss_cm_clksel, OMAP3430_DSS_MOD,
CM_CLKSEL);
omap2_cm_write_mod_reg(cm_context.cam_cm_clksel, OMAP3430_CAM_MOD,
CM_CLKSEL);
omap2_cm_write_mod_reg(cm_context.per_cm_clksel, OMAP3430_PER_MOD,
CM_CLKSEL);
omap2_cm_write_mod_reg(cm_context.emu_cm_clksel, OMAP3430_EMU_MOD,
CM_CLKSEL1);
omap2_cm_write_mod_reg(cm_context.emu_cm_clkstctrl, OMAP3430_EMU_MOD,
OMAP2_CM_CLKSTCTRL);
/*
* As per erratum i671, ROM code does not respect the PER DPLL
* programming scheme if CM_AUTOIDLE_PLL.AUTO_PERIPH_DPLL == 1.
* In this case, we need to restore AUTO_PERIPH_DPLL by ourselves.
*/
omap2_cm_write_mod_reg(cm_context.pll_cm_autoidle, PLL_MOD,
CM_AUTOIDLE);
omap2_cm_write_mod_reg(cm_context.pll_cm_autoidle2, PLL_MOD,
CM_AUTOIDLE2);
omap2_cm_write_mod_reg(cm_context.pll_cm_clksel4, PLL_MOD,
OMAP3430ES2_CM_CLKSEL4);
omap2_cm_write_mod_reg(cm_context.pll_cm_clksel5, PLL_MOD,
OMAP3430ES2_CM_CLKSEL5);
omap2_cm_write_mod_reg(cm_context.pll_cm_clken2, PLL_MOD,
OMAP3430ES2_CM_CLKEN2);
__raw_writel(cm_context.cm_polctrl, OMAP3430_CM_POLCTRL);
omap2_cm_write_mod_reg(cm_context.iva2_cm_fclken, OMAP3430_IVA2_MOD,
CM_FCLKEN);
omap2_cm_write_mod_reg(cm_context.iva2_cm_clken_pll, OMAP3430_IVA2_MOD,
OMAP3430_CM_CLKEN_PLL);
omap2_cm_write_mod_reg(cm_context.core_cm_fclken1, CORE_MOD,
CM_FCLKEN1);
omap2_cm_write_mod_reg(cm_context.core_cm_fclken3, CORE_MOD,
OMAP3430ES2_CM_FCLKEN3);
omap2_cm_write_mod_reg(cm_context.sgx_cm_fclken, OMAP3430ES2_SGX_MOD,
CM_FCLKEN);
omap2_cm_write_mod_reg(cm_context.wkup_cm_fclken, WKUP_MOD, CM_FCLKEN);
omap2_cm_write_mod_reg(cm_context.dss_cm_fclken, OMAP3430_DSS_MOD,
CM_FCLKEN);
omap2_cm_write_mod_reg(cm_context.cam_cm_fclken, OMAP3430_CAM_MOD,
CM_FCLKEN);
omap2_cm_write_mod_reg(cm_context.per_cm_fclken, OMAP3430_PER_MOD,
CM_FCLKEN);
omap2_cm_write_mod_reg(cm_context.usbhost_cm_fclken,
OMAP3430ES2_USBHOST_MOD, CM_FCLKEN);
omap2_cm_write_mod_reg(cm_context.core_cm_iclken1, CORE_MOD,
CM_ICLKEN1);
omap2_cm_write_mod_reg(cm_context.core_cm_iclken2, CORE_MOD,
CM_ICLKEN2);
omap2_cm_write_mod_reg(cm_context.core_cm_iclken3, CORE_MOD,
CM_ICLKEN3);
omap2_cm_write_mod_reg(cm_context.sgx_cm_iclken, OMAP3430ES2_SGX_MOD,
CM_ICLKEN);
omap2_cm_write_mod_reg(cm_context.wkup_cm_iclken, WKUP_MOD, CM_ICLKEN);
omap2_cm_write_mod_reg(cm_context.dss_cm_iclken, OMAP3430_DSS_MOD,
CM_ICLKEN);
omap2_cm_write_mod_reg(cm_context.cam_cm_iclken, OMAP3430_CAM_MOD,
CM_ICLKEN);
omap2_cm_write_mod_reg(cm_context.per_cm_iclken, OMAP3430_PER_MOD,
CM_ICLKEN);
omap2_cm_write_mod_reg(cm_context.usbhost_cm_iclken,
OMAP3430ES2_USBHOST_MOD, CM_ICLKEN);
omap2_cm_write_mod_reg(cm_context.iva2_cm_autoidle2, OMAP3430_IVA2_MOD,
CM_AUTOIDLE2);
omap2_cm_write_mod_reg(cm_context.mpu_cm_autoidle2, MPU_MOD,
CM_AUTOIDLE2);
omap2_cm_write_mod_reg(cm_context.iva2_cm_clkstctrl, OMAP3430_IVA2_MOD,
OMAP2_CM_CLKSTCTRL);
omap2_cm_write_mod_reg(cm_context.mpu_cm_clkstctrl, MPU_MOD,
OMAP2_CM_CLKSTCTRL);
omap2_cm_write_mod_reg(cm_context.core_cm_clkstctrl, CORE_MOD,
OMAP2_CM_CLKSTCTRL);
omap2_cm_write_mod_reg(cm_context.sgx_cm_clkstctrl, OMAP3430ES2_SGX_MOD,
OMAP2_CM_CLKSTCTRL);
omap2_cm_write_mod_reg(cm_context.dss_cm_clkstctrl, OMAP3430_DSS_MOD,
OMAP2_CM_CLKSTCTRL);
omap2_cm_write_mod_reg(cm_context.cam_cm_clkstctrl, OMAP3430_CAM_MOD,
OMAP2_CM_CLKSTCTRL);
omap2_cm_write_mod_reg(cm_context.per_cm_clkstctrl, OMAP3430_PER_MOD,
OMAP2_CM_CLKSTCTRL);
omap2_cm_write_mod_reg(cm_context.neon_cm_clkstctrl, OMAP3430_NEON_MOD,
OMAP2_CM_CLKSTCTRL);
omap2_cm_write_mod_reg(cm_context.usbhost_cm_clkstctrl,
OMAP3430ES2_USBHOST_MOD, OMAP2_CM_CLKSTCTRL);
omap2_cm_write_mod_reg(cm_context.core_cm_autoidle1, CORE_MOD,
CM_AUTOIDLE1);
omap2_cm_write_mod_reg(cm_context.core_cm_autoidle2, CORE_MOD,
CM_AUTOIDLE2);
omap2_cm_write_mod_reg(cm_context.core_cm_autoidle3, CORE_MOD,
CM_AUTOIDLE3);
omap2_cm_write_mod_reg(cm_context.wkup_cm_autoidle, WKUP_MOD,
CM_AUTOIDLE);
omap2_cm_write_mod_reg(cm_context.dss_cm_autoidle, OMAP3430_DSS_MOD,
CM_AUTOIDLE);
omap2_cm_write_mod_reg(cm_context.cam_cm_autoidle, OMAP3430_CAM_MOD,
CM_AUTOIDLE);
omap2_cm_write_mod_reg(cm_context.per_cm_autoidle, OMAP3430_PER_MOD,
CM_AUTOIDLE);
omap2_cm_write_mod_reg(cm_context.usbhost_cm_autoidle,
OMAP3430ES2_USBHOST_MOD, CM_AUTOIDLE);
omap2_cm_write_mod_reg(cm_context.sgx_cm_sleepdep, OMAP3430ES2_SGX_MOD,
OMAP3430_CM_SLEEPDEP);
omap2_cm_write_mod_reg(cm_context.dss_cm_sleepdep, OMAP3430_DSS_MOD,
OMAP3430_CM_SLEEPDEP);
omap2_cm_write_mod_reg(cm_context.cam_cm_sleepdep, OMAP3430_CAM_MOD,
OMAP3430_CM_SLEEPDEP);
omap2_cm_write_mod_reg(cm_context.per_cm_sleepdep, OMAP3430_PER_MOD,
OMAP3430_CM_SLEEPDEP);
omap2_cm_write_mod_reg(cm_context.usbhost_cm_sleepdep,
OMAP3430ES2_USBHOST_MOD, OMAP3430_CM_SLEEPDEP);
omap2_cm_write_mod_reg(cm_context.cm_clkout_ctrl, OMAP3430_CCR_MOD,
OMAP3_CM_CLKOUT_CTRL_OFFSET);
}
#endif
| gpl-2.0 |
EPDCenterSpain/bq-DC-v2 | drivers/video/omap/blizzard.c | 3196 | 43421 | /*
* Epson Blizzard LCD controller driver
*
* Copyright (C) 2004-2005 Nokia Corporation
* Authors: Juha Yrjola <juha.yrjola@nokia.com>
* Imre Deak <imre.deak@nokia.com>
* YUV support: Jussi Laako <jussi.laako@nokia.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/fb.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <plat/dma.h>
#include <plat/blizzard.h>
#include "omapfb.h"
#include "dispc.h"
#define MODULE_NAME "blizzard"
#define BLIZZARD_REV_CODE 0x00
#define BLIZZARD_CONFIG 0x02
#define BLIZZARD_PLL_DIV 0x04
#define BLIZZARD_PLL_LOCK_RANGE 0x06
#define BLIZZARD_PLL_CLOCK_SYNTH_0 0x08
#define BLIZZARD_PLL_CLOCK_SYNTH_1 0x0a
#define BLIZZARD_PLL_MODE 0x0c
#define BLIZZARD_CLK_SRC 0x0e
#define BLIZZARD_MEM_BANK0_ACTIVATE 0x10
#define BLIZZARD_MEM_BANK0_STATUS 0x14
#define BLIZZARD_PANEL_CONFIGURATION 0x28
#define BLIZZARD_HDISP 0x2a
#define BLIZZARD_HNDP 0x2c
#define BLIZZARD_VDISP0 0x2e
#define BLIZZARD_VDISP1 0x30
#define BLIZZARD_VNDP 0x32
#define BLIZZARD_HSW 0x34
#define BLIZZARD_VSW 0x38
#define BLIZZARD_DISPLAY_MODE 0x68
#define BLIZZARD_INPUT_WIN_X_START_0 0x6c
#define BLIZZARD_DATA_SOURCE_SELECT 0x8e
#define BLIZZARD_DISP_MEM_DATA_PORT 0x90
#define BLIZZARD_DISP_MEM_READ_ADDR0 0x92
#define BLIZZARD_POWER_SAVE 0xE6
#define BLIZZARD_NDISP_CTRL_STATUS 0xE8
/* Data source select */
/* For S1D13745 */
#define BLIZZARD_SRC_WRITE_LCD_BACKGROUND 0x00
#define BLIZZARD_SRC_WRITE_LCD_DESTRUCTIVE 0x01
#define BLIZZARD_SRC_WRITE_OVERLAY_ENABLE 0x04
#define BLIZZARD_SRC_DISABLE_OVERLAY 0x05
/* For S1D13744 */
#define BLIZZARD_SRC_WRITE_LCD 0x00
#define BLIZZARD_SRC_BLT_LCD 0x06
#define BLIZZARD_COLOR_RGB565 0x01
#define BLIZZARD_COLOR_YUV420 0x09
#define BLIZZARD_VERSION_S1D13745 0x01 /* Hailstorm */
#define BLIZZARD_VERSION_S1D13744 0x02 /* Blizzard */
#define BLIZZARD_AUTO_UPDATE_TIME (HZ / 20)
/* Reserve 4 request slots for requests in irq context */
#define REQ_POOL_SIZE 24
#define IRQ_REQ_POOL_SIZE 4
#define REQ_FROM_IRQ_POOL 0x01
#define REQ_COMPLETE 0
#define REQ_PENDING 1
struct blizzard_reg_list {
int start;
int end;
};
/* These need to be saved / restored separately from the rest. */
static const struct blizzard_reg_list blizzard_pll_regs[] = {
{
.start = 0x04, /* Don't save PLL ctrl (0x0C) */
.end = 0x0a,
},
{
.start = 0x0e, /* Clock configuration */
.end = 0x0e,
},
};
static const struct blizzard_reg_list blizzard_gen_regs[] = {
{
.start = 0x18, /* SDRAM control */
.end = 0x20,
},
{
.start = 0x28, /* LCD Panel configuration */
.end = 0x5a, /* HSSI interface, TV configuration */
},
};
static u8 blizzard_reg_cache[0x5a / 2];
struct update_param {
int plane;
int x, y, width, height;
int out_x, out_y;
int out_width, out_height;
int color_mode;
int bpp;
int flags;
};
struct blizzard_request {
struct list_head entry;
unsigned int flags;
int (*handler)(struct blizzard_request *req);
void (*complete)(void *data);
void *complete_data;
union {
struct update_param update;
struct completion *sync;
} par;
};
struct plane_info {
unsigned long offset;
int pos_x, pos_y;
int width, height;
int out_width, out_height;
int scr_width;
int color_mode;
int bpp;
};
struct blizzard_struct {
enum omapfb_update_mode update_mode;
enum omapfb_update_mode update_mode_before_suspend;
struct timer_list auto_update_timer;
int stop_auto_update;
struct omapfb_update_window auto_update_window;
int enabled_planes;
int vid_nonstd_color;
int vid_scaled;
int last_color_mode;
int zoom_on;
int zoom_area_gx1;
int zoom_area_gx2;
int zoom_area_gy1;
int zoom_area_gy2;
int screen_width;
int screen_height;
unsigned te_connected:1;
unsigned vsync_only:1;
struct plane_info plane[OMAPFB_PLANE_NUM];
struct blizzard_request req_pool[REQ_POOL_SIZE];
struct list_head pending_req_list;
struct list_head free_req_list;
struct semaphore req_sema;
spinlock_t req_lock;
unsigned long sys_ck_rate;
struct extif_timings reg_timings, lut_timings;
u32 max_transmit_size;
u32 extif_clk_period;
int extif_clk_div;
unsigned long pix_tx_time;
unsigned long line_upd_time;
struct omapfb_device *fbdev;
struct lcd_ctrl_extif *extif;
const struct lcd_ctrl *int_ctrl;
void (*power_up)(struct device *dev);
void (*power_down)(struct device *dev);
int version;
} blizzard;
struct lcd_ctrl blizzard_ctrl;
static u8 blizzard_read_reg(u8 reg)
{
u8 data;
blizzard.extif->set_bits_per_cycle(8);
blizzard.extif->write_command(®, 1);
blizzard.extif->read_data(&data, 1);
return data;
}
static void blizzard_write_reg(u8 reg, u8 val)
{
blizzard.extif->set_bits_per_cycle(8);
blizzard.extif->write_command(®, 1);
blizzard.extif->write_data(&val, 1);
}
static void blizzard_restart_sdram(void)
{
unsigned long tmo;
blizzard_write_reg(BLIZZARD_MEM_BANK0_ACTIVATE, 0);
udelay(50);
blizzard_write_reg(BLIZZARD_MEM_BANK0_ACTIVATE, 1);
tmo = jiffies + msecs_to_jiffies(200);
while (!(blizzard_read_reg(BLIZZARD_MEM_BANK0_STATUS) & 0x01)) {
if (time_after(jiffies, tmo)) {
dev_err(blizzard.fbdev->dev,
"s1d1374x: SDRAM not ready\n");
break;
}
msleep(1);
}
}
static void blizzard_stop_sdram(void)
{
blizzard_write_reg(BLIZZARD_MEM_BANK0_ACTIVATE, 0);
}
/* Wait until the last window was completely written into the controllers
* SDRAM and we can start transferring the next window.
*/
static void blizzard_wait_line_buffer(void)
{
unsigned long tmo = jiffies + msecs_to_jiffies(30);
while (blizzard_read_reg(BLIZZARD_NDISP_CTRL_STATUS) & (1 << 7)) {
if (time_after(jiffies, tmo)) {
if (printk_ratelimit())
dev_err(blizzard.fbdev->dev,
"s1d1374x: line buffer not ready\n");
break;
}
}
}
/* Wait until the YYC color space converter is idle. */
static void blizzard_wait_yyc(void)
{
unsigned long tmo = jiffies + msecs_to_jiffies(30);
while (blizzard_read_reg(BLIZZARD_NDISP_CTRL_STATUS) & (1 << 4)) {
if (time_after(jiffies, tmo)) {
if (printk_ratelimit())
dev_err(blizzard.fbdev->dev,
"s1d1374x: YYC not ready\n");
break;
}
}
}
static void disable_overlay(void)
{
blizzard_write_reg(BLIZZARD_DATA_SOURCE_SELECT,
BLIZZARD_SRC_DISABLE_OVERLAY);
}
static void set_window_regs(int x_start, int y_start, int x_end, int y_end,
int x_out_start, int y_out_start,
int x_out_end, int y_out_end, int color_mode,
int zoom_off, int flags)
{
u8 tmp[18];
u8 cmd;
x_end--;
y_end--;
tmp[0] = x_start;
tmp[1] = x_start >> 8;
tmp[2] = y_start;
tmp[3] = y_start >> 8;
tmp[4] = x_end;
tmp[5] = x_end >> 8;
tmp[6] = y_end;
tmp[7] = y_end >> 8;
x_out_end--;
y_out_end--;
tmp[8] = x_out_start;
tmp[9] = x_out_start >> 8;
tmp[10] = y_out_start;
tmp[11] = y_out_start >> 8;
tmp[12] = x_out_end;
tmp[13] = x_out_end >> 8;
tmp[14] = y_out_end;
tmp[15] = y_out_end >> 8;
tmp[16] = color_mode;
if (zoom_off && blizzard.version == BLIZZARD_VERSION_S1D13745)
tmp[17] = BLIZZARD_SRC_WRITE_LCD_BACKGROUND;
else if (flags & OMAPFB_FORMAT_FLAG_ENABLE_OVERLAY)
tmp[17] = BLIZZARD_SRC_WRITE_OVERLAY_ENABLE;
else
tmp[17] = blizzard.version == BLIZZARD_VERSION_S1D13744 ?
BLIZZARD_SRC_WRITE_LCD :
BLIZZARD_SRC_WRITE_LCD_DESTRUCTIVE;
blizzard.extif->set_bits_per_cycle(8);
cmd = BLIZZARD_INPUT_WIN_X_START_0;
blizzard.extif->write_command(&cmd, 1);
blizzard.extif->write_data(tmp, 18);
}
static void enable_tearsync(int y, int width, int height, int screen_height,
int out_height, int force_vsync)
{
u8 b;
b = blizzard_read_reg(BLIZZARD_NDISP_CTRL_STATUS);
b |= 1 << 3;
blizzard_write_reg(BLIZZARD_NDISP_CTRL_STATUS, b);
if (likely(blizzard.vsync_only || force_vsync)) {
blizzard.extif->enable_tearsync(1, 0);
return;
}
if (width * blizzard.pix_tx_time < blizzard.line_upd_time) {
blizzard.extif->enable_tearsync(1, 0);
return;
}
if ((width * blizzard.pix_tx_time / 1000) * height <
(y + out_height) * (blizzard.line_upd_time / 1000)) {
blizzard.extif->enable_tearsync(1, 0);
return;
}
blizzard.extif->enable_tearsync(1, y + 1);
}
static void disable_tearsync(void)
{
u8 b;
blizzard.extif->enable_tearsync(0, 0);
b = blizzard_read_reg(BLIZZARD_NDISP_CTRL_STATUS);
b &= ~(1 << 3);
blizzard_write_reg(BLIZZARD_NDISP_CTRL_STATUS, b);
b = blizzard_read_reg(BLIZZARD_NDISP_CTRL_STATUS);
}
static inline void set_extif_timings(const struct extif_timings *t);
static inline struct blizzard_request *alloc_req(void)
{
unsigned long flags;
struct blizzard_request *req;
int req_flags = 0;
if (!in_interrupt())
down(&blizzard.req_sema);
else
req_flags = REQ_FROM_IRQ_POOL;
spin_lock_irqsave(&blizzard.req_lock, flags);
BUG_ON(list_empty(&blizzard.free_req_list));
req = list_entry(blizzard.free_req_list.next,
struct blizzard_request, entry);
list_del(&req->entry);
spin_unlock_irqrestore(&blizzard.req_lock, flags);
INIT_LIST_HEAD(&req->entry);
req->flags = req_flags;
return req;
}
static inline void free_req(struct blizzard_request *req)
{
unsigned long flags;
spin_lock_irqsave(&blizzard.req_lock, flags);
list_move(&req->entry, &blizzard.free_req_list);
if (!(req->flags & REQ_FROM_IRQ_POOL))
up(&blizzard.req_sema);
spin_unlock_irqrestore(&blizzard.req_lock, flags);
}
static void process_pending_requests(void)
{
unsigned long flags;
spin_lock_irqsave(&blizzard.req_lock, flags);
while (!list_empty(&blizzard.pending_req_list)) {
struct blizzard_request *req;
void (*complete)(void *);
void *complete_data;
req = list_entry(blizzard.pending_req_list.next,
struct blizzard_request, entry);
spin_unlock_irqrestore(&blizzard.req_lock, flags);
if (req->handler(req) == REQ_PENDING)
return;
complete = req->complete;
complete_data = req->complete_data;
free_req(req);
if (complete)
complete(complete_data);
spin_lock_irqsave(&blizzard.req_lock, flags);
}
spin_unlock_irqrestore(&blizzard.req_lock, flags);
}
static void submit_req_list(struct list_head *head)
{
unsigned long flags;
int process = 1;
spin_lock_irqsave(&blizzard.req_lock, flags);
if (likely(!list_empty(&blizzard.pending_req_list)))
process = 0;
list_splice_init(head, blizzard.pending_req_list.prev);
spin_unlock_irqrestore(&blizzard.req_lock, flags);
if (process)
process_pending_requests();
}
static void request_complete(void *data)
{
struct blizzard_request *req = (struct blizzard_request *)data;
void (*complete)(void *);
void *complete_data;
complete = req->complete;
complete_data = req->complete_data;
free_req(req);
if (complete)
complete(complete_data);
process_pending_requests();
}
static int do_full_screen_update(struct blizzard_request *req)
{
int i;
int flags;
for (i = 0; i < 3; i++) {
struct plane_info *p = &blizzard.plane[i];
if (!(blizzard.enabled_planes & (1 << i))) {
blizzard.int_ctrl->enable_plane(i, 0);
continue;
}
dev_dbg(blizzard.fbdev->dev, "pw %d ph %d\n",
p->width, p->height);
blizzard.int_ctrl->setup_plane(i,
OMAPFB_CHANNEL_OUT_LCD, p->offset,
p->scr_width, p->pos_x, p->pos_y,
p->width, p->height,
p->color_mode);
blizzard.int_ctrl->enable_plane(i, 1);
}
dev_dbg(blizzard.fbdev->dev, "sw %d sh %d\n",
blizzard.screen_width, blizzard.screen_height);
blizzard_wait_line_buffer();
flags = req->par.update.flags;
if (flags & OMAPFB_FORMAT_FLAG_TEARSYNC)
enable_tearsync(0, blizzard.screen_width,
blizzard.screen_height,
blizzard.screen_height,
blizzard.screen_height,
flags & OMAPFB_FORMAT_FLAG_FORCE_VSYNC);
else
disable_tearsync();
set_window_regs(0, 0, blizzard.screen_width, blizzard.screen_height,
0, 0, blizzard.screen_width, blizzard.screen_height,
BLIZZARD_COLOR_RGB565, blizzard.zoom_on, flags);
blizzard.zoom_on = 0;
blizzard.extif->set_bits_per_cycle(16);
/* set_window_regs has left the register index at the right
* place, so no need to set it here.
*/
blizzard.extif->transfer_area(blizzard.screen_width,
blizzard.screen_height,
request_complete, req);
return REQ_PENDING;
}
static int check_1d_intersect(int a1, int a2, int b1, int b2)
{
if (a2 <= b1 || b2 <= a1)
return 0;
return 1;
}
/* Setup all planes with an overlapping area with the update window. */
static int do_partial_update(struct blizzard_request *req, int plane,
int x, int y, int w, int h,
int x_out, int y_out, int w_out, int h_out,
int wnd_color_mode, int bpp)
{
int i;
int gx1, gy1, gx2, gy2;
int gx1_out, gy1_out, gx2_out, gy2_out;
int color_mode;
int flags;
int zoom_off;
int have_zoom_for_this_update = 0;
/* Global coordinates, relative to pixel 0,0 of the LCD */
gx1 = x + blizzard.plane[plane].pos_x;
gy1 = y + blizzard.plane[plane].pos_y;
gx2 = gx1 + w;
gy2 = gy1 + h;
flags = req->par.update.flags;
if (flags & OMAPFB_FORMAT_FLAG_DOUBLE) {
gx1_out = gx1;
gy1_out = gy1;
gx2_out = gx1 + w * 2;
gy2_out = gy1 + h * 2;
} else {
gx1_out = x_out + blizzard.plane[plane].pos_x;
gy1_out = y_out + blizzard.plane[plane].pos_y;
gx2_out = gx1_out + w_out;
gy2_out = gy1_out + h_out;
}
for (i = 0; i < OMAPFB_PLANE_NUM; i++) {
struct plane_info *p = &blizzard.plane[i];
int px1, py1;
int px2, py2;
int pw, ph;
int pposx, pposy;
unsigned long offset;
if (!(blizzard.enabled_planes & (1 << i)) ||
(wnd_color_mode && i != plane)) {
blizzard.int_ctrl->enable_plane(i, 0);
continue;
}
/* Plane coordinates */
if (i == plane) {
/* Plane in which we are doing the update.
* Local coordinates are the one in the update
* request.
*/
px1 = x;
py1 = y;
px2 = x + w;
py2 = y + h;
pposx = 0;
pposy = 0;
} else {
/* Check if this plane has an overlapping part */
px1 = gx1 - p->pos_x;
py1 = gy1 - p->pos_y;
px2 = gx2 - p->pos_x;
py2 = gy2 - p->pos_y;
if (px1 >= p->width || py1 >= p->height ||
px2 <= 0 || py2 <= 0) {
blizzard.int_ctrl->enable_plane(i, 0);
continue;
}
/* Calculate the coordinates for the overlapping
* part in the plane's local coordinates.
*/
pposx = -px1;
pposy = -py1;
if (px1 < 0)
px1 = 0;
if (py1 < 0)
py1 = 0;
if (px2 > p->width)
px2 = p->width;
if (py2 > p->height)
py2 = p->height;
if (pposx < 0)
pposx = 0;
if (pposy < 0)
pposy = 0;
}
pw = px2 - px1;
ph = py2 - py1;
offset = p->offset + (p->scr_width * py1 + px1) * p->bpp / 8;
if (wnd_color_mode)
/* Window embedded in the plane with a differing
* color mode / bpp. Calculate the number of DMA
* transfer elements in terms of the plane's bpp.
*/
pw = (pw + 1) * bpp / p->bpp;
#ifdef VERBOSE
dev_dbg(blizzard.fbdev->dev,
"plane %d offset %#08lx pposx %d pposy %d "
"px1 %d py1 %d pw %d ph %d\n",
i, offset, pposx, pposy, px1, py1, pw, ph);
#endif
blizzard.int_ctrl->setup_plane(i,
OMAPFB_CHANNEL_OUT_LCD, offset,
p->scr_width,
pposx, pposy, pw, ph,
p->color_mode);
blizzard.int_ctrl->enable_plane(i, 1);
}
switch (wnd_color_mode) {
case OMAPFB_COLOR_YUV420:
color_mode = BLIZZARD_COLOR_YUV420;
/* Currently only the 16 bits/pixel cycle format is
* supported on the external interface. Adjust the number
* of transfer elements per line for 12bpp format.
*/
w = (w + 1) * 3 / 4;
break;
default:
color_mode = BLIZZARD_COLOR_RGB565;
break;
}
blizzard_wait_line_buffer();
if (blizzard.last_color_mode == BLIZZARD_COLOR_YUV420)
blizzard_wait_yyc();
blizzard.last_color_mode = color_mode;
if (flags & OMAPFB_FORMAT_FLAG_TEARSYNC)
enable_tearsync(gy1, w, h,
blizzard.screen_height,
h_out,
flags & OMAPFB_FORMAT_FLAG_FORCE_VSYNC);
else
disable_tearsync();
if ((gx2_out - gx1_out) != (gx2 - gx1) ||
(gy2_out - gy1_out) != (gy2 - gy1))
have_zoom_for_this_update = 1;
/* 'background' type of screen update (as opposed to 'destructive')
can be used to disable scaling if scaling is active */
zoom_off = blizzard.zoom_on && !have_zoom_for_this_update &&
(gx1_out == 0) && (gx2_out == blizzard.screen_width) &&
(gy1_out == 0) && (gy2_out == blizzard.screen_height) &&
(gx1 == 0) && (gy1 == 0);
if (blizzard.zoom_on && !have_zoom_for_this_update && !zoom_off &&
check_1d_intersect(blizzard.zoom_area_gx1, blizzard.zoom_area_gx2,
gx1_out, gx2_out) &&
check_1d_intersect(blizzard.zoom_area_gy1, blizzard.zoom_area_gy2,
gy1_out, gy2_out)) {
/* Previous screen update was using scaling, current update
* is not using it. Additionally, current screen update is
* going to overlap with the scaled area. Scaling needs to be
* disabled in order to avoid 'magnifying glass' effect.
* Dummy setup of background window can be used for this.
*/
set_window_regs(0, 0, blizzard.screen_width,
blizzard.screen_height,
0, 0, blizzard.screen_width,
blizzard.screen_height,
BLIZZARD_COLOR_RGB565, 1, flags);
blizzard.zoom_on = 0;
}
/* remember scaling settings if we have scaled update */
if (have_zoom_for_this_update) {
blizzard.zoom_on = 1;
blizzard.zoom_area_gx1 = gx1_out;
blizzard.zoom_area_gx2 = gx2_out;
blizzard.zoom_area_gy1 = gy1_out;
blizzard.zoom_area_gy2 = gy2_out;
}
set_window_regs(gx1, gy1, gx2, gy2, gx1_out, gy1_out, gx2_out, gy2_out,
color_mode, zoom_off, flags);
if (zoom_off)
blizzard.zoom_on = 0;
blizzard.extif->set_bits_per_cycle(16);
/* set_window_regs has left the register index at the right
* place, so no need to set it here.
*/
blizzard.extif->transfer_area(w, h, request_complete, req);
return REQ_PENDING;
}
static int send_frame_handler(struct blizzard_request *req)
{
struct update_param *par = &req->par.update;
int plane = par->plane;
#ifdef VERBOSE
dev_dbg(blizzard.fbdev->dev,
"send_frame: x %d y %d w %d h %d "
"x_out %d y_out %d w_out %d h_out %d "
"color_mode %04x flags %04x planes %01x\n",
par->x, par->y, par->width, par->height,
par->out_x, par->out_y, par->out_width, par->out_height,
par->color_mode, par->flags, blizzard.enabled_planes);
#endif
if (par->flags & OMAPFB_FORMAT_FLAG_DISABLE_OVERLAY)
disable_overlay();
if ((blizzard.enabled_planes & blizzard.vid_nonstd_color) ||
(blizzard.enabled_planes & blizzard.vid_scaled))
return do_full_screen_update(req);
return do_partial_update(req, plane, par->x, par->y,
par->width, par->height,
par->out_x, par->out_y,
par->out_width, par->out_height,
par->color_mode, par->bpp);
}
static void send_frame_complete(void *data)
{
}
#define ADD_PREQ(_x, _y, _w, _h, _x_out, _y_out, _w_out, _h_out) do { \
req = alloc_req(); \
req->handler = send_frame_handler; \
req->complete = send_frame_complete; \
req->par.update.plane = plane_idx; \
req->par.update.x = _x; \
req->par.update.y = _y; \
req->par.update.width = _w; \
req->par.update.height = _h; \
req->par.update.out_x = _x_out; \
req->par.update.out_y = _y_out; \
req->par.update.out_width = _w_out; \
req->par.update.out_height = _h_out; \
req->par.update.bpp = bpp; \
req->par.update.color_mode = color_mode;\
req->par.update.flags = flags; \
list_add_tail(&req->entry, req_head); \
} while(0)
static void create_req_list(int plane_idx,
struct omapfb_update_window *win,
struct list_head *req_head)
{
struct blizzard_request *req;
int x = win->x;
int y = win->y;
int width = win->width;
int height = win->height;
int x_out = win->out_x;
int y_out = win->out_y;
int width_out = win->out_width;
int height_out = win->out_height;
int color_mode;
int bpp;
int flags;
unsigned int ystart = y;
unsigned int yspan = height;
unsigned int ystart_out = y_out;
unsigned int yspan_out = height_out;
flags = win->format & ~OMAPFB_FORMAT_MASK;
color_mode = win->format & OMAPFB_FORMAT_MASK;
switch (color_mode) {
case OMAPFB_COLOR_YUV420:
/* Embedded window with different color mode */
bpp = 12;
/* X, Y, height must be aligned at 2, width at 4 pixels */
x &= ~1;
y &= ~1;
height = yspan = height & ~1;
width = width & ~3;
break;
default:
/* Same as the plane color mode */
bpp = blizzard.plane[plane_idx].bpp;
break;
}
if (width * height * bpp / 8 > blizzard.max_transmit_size) {
yspan = blizzard.max_transmit_size / (width * bpp / 8);
yspan_out = yspan * height_out / height;
ADD_PREQ(x, ystart, width, yspan, x_out, ystart_out,
width_out, yspan_out);
ystart += yspan;
ystart_out += yspan_out;
yspan = height - yspan;
yspan_out = height_out - yspan_out;
flags &= ~OMAPFB_FORMAT_FLAG_TEARSYNC;
}
ADD_PREQ(x, ystart, width, yspan, x_out, ystart_out,
width_out, yspan_out);
}
static void auto_update_complete(void *data)
{
if (!blizzard.stop_auto_update)
mod_timer(&blizzard.auto_update_timer,
jiffies + BLIZZARD_AUTO_UPDATE_TIME);
}
static void blizzard_update_window_auto(unsigned long arg)
{
LIST_HEAD(req_list);
struct blizzard_request *last;
struct omapfb_plane_struct *plane;
plane = blizzard.fbdev->fb_info[0]->par;
create_req_list(plane->idx,
&blizzard.auto_update_window, &req_list);
last = list_entry(req_list.prev, struct blizzard_request, entry);
last->complete = auto_update_complete;
last->complete_data = NULL;
submit_req_list(&req_list);
}
int blizzard_update_window_async(struct fb_info *fbi,
struct omapfb_update_window *win,
void (*complete_callback)(void *arg),
void *complete_callback_data)
{
LIST_HEAD(req_list);
struct blizzard_request *last;
struct omapfb_plane_struct *plane = fbi->par;
if (unlikely(blizzard.update_mode != OMAPFB_MANUAL_UPDATE))
return -EINVAL;
if (unlikely(!blizzard.te_connected &&
(win->format & OMAPFB_FORMAT_FLAG_TEARSYNC)))
return -EINVAL;
create_req_list(plane->idx, win, &req_list);
last = list_entry(req_list.prev, struct blizzard_request, entry);
last->complete = complete_callback;
last->complete_data = (void *)complete_callback_data;
submit_req_list(&req_list);
return 0;
}
EXPORT_SYMBOL(blizzard_update_window_async);
static int update_full_screen(void)
{
return blizzard_update_window_async(blizzard.fbdev->fb_info[0],
&blizzard.auto_update_window, NULL, NULL);
}
static int blizzard_setup_plane(int plane, int channel_out,
unsigned long offset, int screen_width,
int pos_x, int pos_y, int width, int height,
int color_mode)
{
struct plane_info *p;
#ifdef VERBOSE
dev_dbg(blizzard.fbdev->dev,
"plane %d ch_out %d offset %#08lx scr_width %d "
"pos_x %d pos_y %d width %d height %d color_mode %d\n",
plane, channel_out, offset, screen_width,
pos_x, pos_y, width, height, color_mode);
#endif
if ((unsigned)plane > OMAPFB_PLANE_NUM)
return -EINVAL;
p = &blizzard.plane[plane];
switch (color_mode) {
case OMAPFB_COLOR_YUV422:
case OMAPFB_COLOR_YUY422:
p->bpp = 16;
blizzard.vid_nonstd_color &= ~(1 << plane);
break;
case OMAPFB_COLOR_YUV420:
p->bpp = 12;
blizzard.vid_nonstd_color |= 1 << plane;
break;
case OMAPFB_COLOR_RGB565:
p->bpp = 16;
blizzard.vid_nonstd_color &= ~(1 << plane);
break;
default:
return -EINVAL;
}
p->offset = offset;
p->pos_x = pos_x;
p->pos_y = pos_y;
p->width = width;
p->height = height;
p->scr_width = screen_width;
if (!p->out_width)
p->out_width = width;
if (!p->out_height)
p->out_height = height;
p->color_mode = color_mode;
return 0;
}
static int blizzard_set_scale(int plane, int orig_w, int orig_h,
int out_w, int out_h)
{
struct plane_info *p = &blizzard.plane[plane];
int r;
dev_dbg(blizzard.fbdev->dev,
"plane %d orig_w %d orig_h %d out_w %d out_h %d\n",
plane, orig_w, orig_h, out_w, out_h);
if ((unsigned)plane > OMAPFB_PLANE_NUM)
return -ENODEV;
r = blizzard.int_ctrl->set_scale(plane, orig_w, orig_h, out_w, out_h);
if (r < 0)
return r;
p->width = orig_w;
p->height = orig_h;
p->out_width = out_w;
p->out_height = out_h;
if (orig_w == out_w && orig_h == out_h)
blizzard.vid_scaled &= ~(1 << plane);
else
blizzard.vid_scaled |= 1 << plane;
return 0;
}
static int blizzard_set_rotate(int angle)
{
u32 l;
l = blizzard_read_reg(BLIZZARD_PANEL_CONFIGURATION);
l &= ~0x03;
switch (angle) {
case 0:
l = l | 0x00;
break;
case 90:
l = l | 0x03;
break;
case 180:
l = l | 0x02;
break;
case 270:
l = l | 0x01;
break;
default:
return -EINVAL;
}
blizzard_write_reg(BLIZZARD_PANEL_CONFIGURATION, l);
return 0;
}
static int blizzard_enable_plane(int plane, int enable)
{
if (enable)
blizzard.enabled_planes |= 1 << plane;
else
blizzard.enabled_planes &= ~(1 << plane);
return 0;
}
static int sync_handler(struct blizzard_request *req)
{
complete(req->par.sync);
return REQ_COMPLETE;
}
static void blizzard_sync(void)
{
LIST_HEAD(req_list);
struct blizzard_request *req;
struct completion comp;
req = alloc_req();
req->handler = sync_handler;
req->complete = NULL;
init_completion(&comp);
req->par.sync = ∁
list_add(&req->entry, &req_list);
submit_req_list(&req_list);
wait_for_completion(&comp);
}
static void blizzard_bind_client(struct omapfb_notifier_block *nb)
{
if (blizzard.update_mode == OMAPFB_MANUAL_UPDATE) {
omapfb_notify_clients(blizzard.fbdev, OMAPFB_EVENT_READY);
}
}
static int blizzard_set_update_mode(enum omapfb_update_mode mode)
{
if (unlikely(mode != OMAPFB_MANUAL_UPDATE &&
mode != OMAPFB_AUTO_UPDATE &&
mode != OMAPFB_UPDATE_DISABLED))
return -EINVAL;
if (mode == blizzard.update_mode)
return 0;
dev_info(blizzard.fbdev->dev, "s1d1374x: setting update mode to %s\n",
mode == OMAPFB_UPDATE_DISABLED ? "disabled" :
(mode == OMAPFB_AUTO_UPDATE ? "auto" : "manual"));
switch (blizzard.update_mode) {
case OMAPFB_MANUAL_UPDATE:
omapfb_notify_clients(blizzard.fbdev, OMAPFB_EVENT_DISABLED);
break;
case OMAPFB_AUTO_UPDATE:
blizzard.stop_auto_update = 1;
del_timer_sync(&blizzard.auto_update_timer);
break;
case OMAPFB_UPDATE_DISABLED:
break;
}
blizzard.update_mode = mode;
blizzard_sync();
blizzard.stop_auto_update = 0;
switch (mode) {
case OMAPFB_MANUAL_UPDATE:
omapfb_notify_clients(blizzard.fbdev, OMAPFB_EVENT_READY);
break;
case OMAPFB_AUTO_UPDATE:
blizzard_update_window_auto(0);
break;
case OMAPFB_UPDATE_DISABLED:
break;
}
return 0;
}
static enum omapfb_update_mode blizzard_get_update_mode(void)
{
return blizzard.update_mode;
}
static inline void set_extif_timings(const struct extif_timings *t)
{
blizzard.extif->set_timings(t);
}
static inline unsigned long round_to_extif_ticks(unsigned long ps, int div)
{
int bus_tick = blizzard.extif_clk_period * div;
return (ps + bus_tick - 1) / bus_tick * bus_tick;
}
static int calc_reg_timing(unsigned long sysclk, int div)
{
struct extif_timings *t;
unsigned long systim;
/* CSOnTime 0, WEOnTime 2 ns, REOnTime 2 ns,
* AccessTime 2 ns + 12.2 ns (regs),
* WEOffTime = WEOnTime + 1 ns,
* REOffTime = REOnTime + 12 ns (regs),
* CSOffTime = REOffTime + 1 ns
* ReadCycle = 2ns + 2*SYSCLK (regs),
* WriteCycle = 2*SYSCLK + 2 ns,
* CSPulseWidth = 10 ns */
systim = 1000000000 / (sysclk / 1000);
dev_dbg(blizzard.fbdev->dev,
"Blizzard systim %lu ps extif_clk_period %u div %d\n",
systim, blizzard.extif_clk_period, div);
t = &blizzard.reg_timings;
memset(t, 0, sizeof(*t));
t->clk_div = div;
t->cs_on_time = 0;
t->we_on_time = round_to_extif_ticks(t->cs_on_time + 2000, div);
t->re_on_time = round_to_extif_ticks(t->cs_on_time + 2000, div);
t->access_time = round_to_extif_ticks(t->re_on_time + 12200, div);
t->we_off_time = round_to_extif_ticks(t->we_on_time + 1000, div);
t->re_off_time = round_to_extif_ticks(t->re_on_time + 13000, div);
t->cs_off_time = round_to_extif_ticks(t->re_off_time + 1000, div);
t->we_cycle_time = round_to_extif_ticks(2 * systim + 2000, div);
if (t->we_cycle_time < t->we_off_time)
t->we_cycle_time = t->we_off_time;
t->re_cycle_time = round_to_extif_ticks(2 * systim + 2000, div);
if (t->re_cycle_time < t->re_off_time)
t->re_cycle_time = t->re_off_time;
t->cs_pulse_width = 0;
dev_dbg(blizzard.fbdev->dev, "[reg]cson %d csoff %d reon %d reoff %d\n",
t->cs_on_time, t->cs_off_time, t->re_on_time, t->re_off_time);
dev_dbg(blizzard.fbdev->dev, "[reg]weon %d weoff %d recyc %d wecyc %d\n",
t->we_on_time, t->we_off_time, t->re_cycle_time,
t->we_cycle_time);
dev_dbg(blizzard.fbdev->dev, "[reg]rdaccess %d cspulse %d\n",
t->access_time, t->cs_pulse_width);
return blizzard.extif->convert_timings(t);
}
static int calc_lut_timing(unsigned long sysclk, int div)
{
struct extif_timings *t;
unsigned long systim;
/* CSOnTime 0, WEOnTime 2 ns, REOnTime 2 ns,
* AccessTime 2 ns + 4 * SYSCLK + 26 (lut),
* WEOffTime = WEOnTime + 1 ns,
* REOffTime = REOnTime + 4*SYSCLK + 26 ns (lut),
* CSOffTime = REOffTime + 1 ns
* ReadCycle = 2ns + 4*SYSCLK + 26 ns (lut),
* WriteCycle = 2*SYSCLK + 2 ns,
* CSPulseWidth = 10 ns */
systim = 1000000000 / (sysclk / 1000);
dev_dbg(blizzard.fbdev->dev,
"Blizzard systim %lu ps extif_clk_period %u div %d\n",
systim, blizzard.extif_clk_period, div);
t = &blizzard.lut_timings;
memset(t, 0, sizeof(*t));
t->clk_div = div;
t->cs_on_time = 0;
t->we_on_time = round_to_extif_ticks(t->cs_on_time + 2000, div);
t->re_on_time = round_to_extif_ticks(t->cs_on_time + 2000, div);
t->access_time = round_to_extif_ticks(t->re_on_time + 4 * systim +
26000, div);
t->we_off_time = round_to_extif_ticks(t->we_on_time + 1000, div);
t->re_off_time = round_to_extif_ticks(t->re_on_time + 4 * systim +
26000, div);
t->cs_off_time = round_to_extif_ticks(t->re_off_time + 1000, div);
t->we_cycle_time = round_to_extif_ticks(2 * systim + 2000, div);
if (t->we_cycle_time < t->we_off_time)
t->we_cycle_time = t->we_off_time;
t->re_cycle_time = round_to_extif_ticks(2000 + 4 * systim + 26000, div);
if (t->re_cycle_time < t->re_off_time)
t->re_cycle_time = t->re_off_time;
t->cs_pulse_width = 0;
dev_dbg(blizzard.fbdev->dev,
"[lut]cson %d csoff %d reon %d reoff %d\n",
t->cs_on_time, t->cs_off_time, t->re_on_time, t->re_off_time);
dev_dbg(blizzard.fbdev->dev,
"[lut]weon %d weoff %d recyc %d wecyc %d\n",
t->we_on_time, t->we_off_time, t->re_cycle_time,
t->we_cycle_time);
dev_dbg(blizzard.fbdev->dev, "[lut]rdaccess %d cspulse %d\n",
t->access_time, t->cs_pulse_width);
return blizzard.extif->convert_timings(t);
}
static int calc_extif_timings(unsigned long sysclk, int *extif_mem_div)
{
int max_clk_div;
int div;
blizzard.extif->get_clk_info(&blizzard.extif_clk_period, &max_clk_div);
for (div = 1; div <= max_clk_div; div++) {
if (calc_reg_timing(sysclk, div) == 0)
break;
}
if (div > max_clk_div) {
dev_dbg(blizzard.fbdev->dev, "reg timing failed\n");
goto err;
}
*extif_mem_div = div;
for (div = 1; div <= max_clk_div; div++) {
if (calc_lut_timing(sysclk, div) == 0)
break;
}
if (div > max_clk_div)
goto err;
blizzard.extif_clk_div = div;
return 0;
err:
dev_err(blizzard.fbdev->dev, "can't setup timings\n");
return -1;
}
static void calc_blizzard_clk_rates(unsigned long ext_clk,
unsigned long *sys_clk, unsigned long *pix_clk)
{
int pix_clk_src;
int sys_div = 0, sys_mul = 0;
int pix_div;
pix_clk_src = blizzard_read_reg(BLIZZARD_CLK_SRC);
pix_div = ((pix_clk_src >> 3) & 0x1f) + 1;
if ((pix_clk_src & (0x3 << 1)) == 0) {
/* Source is the PLL */
sys_div = (blizzard_read_reg(BLIZZARD_PLL_DIV) & 0x3f) + 1;
sys_mul = blizzard_read_reg(BLIZZARD_PLL_CLOCK_SYNTH_0);
sys_mul |= ((blizzard_read_reg(BLIZZARD_PLL_CLOCK_SYNTH_1)
& 0x0f) << 11);
*sys_clk = ext_clk * sys_mul / sys_div;
} else /* else source is ext clk, or oscillator */
*sys_clk = ext_clk;
*pix_clk = *sys_clk / pix_div; /* HZ */
dev_dbg(blizzard.fbdev->dev,
"ext_clk %ld pix_src %d pix_div %d sys_div %d sys_mul %d\n",
ext_clk, pix_clk_src & (0x3 << 1), pix_div, sys_div, sys_mul);
dev_dbg(blizzard.fbdev->dev, "sys_clk %ld pix_clk %ld\n",
*sys_clk, *pix_clk);
}
static int setup_tearsync(unsigned long pix_clk, int extif_div)
{
int hdisp, vdisp;
int hndp, vndp;
int hsw, vsw;
int hs, vs;
int hs_pol_inv, vs_pol_inv;
int use_hsvs, use_ndp;
u8 b;
hsw = blizzard_read_reg(BLIZZARD_HSW);
vsw = blizzard_read_reg(BLIZZARD_VSW);
hs_pol_inv = !(hsw & 0x80);
vs_pol_inv = !(vsw & 0x80);
hsw = hsw & 0x7f;
vsw = vsw & 0x3f;
hdisp = blizzard_read_reg(BLIZZARD_HDISP) * 8;
vdisp = blizzard_read_reg(BLIZZARD_VDISP0) +
((blizzard_read_reg(BLIZZARD_VDISP1) & 0x3) << 8);
hndp = blizzard_read_reg(BLIZZARD_HNDP) & 0x3f;
vndp = blizzard_read_reg(BLIZZARD_VNDP);
/* time to transfer one pixel (16bpp) in ps */
blizzard.pix_tx_time = blizzard.reg_timings.we_cycle_time;
if (blizzard.extif->get_max_tx_rate != NULL) {
/* The external interface might have a rate limitation,
* if so, we have to maximize our transfer rate.
*/
unsigned long min_tx_time;
unsigned long max_tx_rate = blizzard.extif->get_max_tx_rate();
dev_dbg(blizzard.fbdev->dev, "max_tx_rate %ld HZ\n",
max_tx_rate);
min_tx_time = 1000000000 / (max_tx_rate / 1000); /* ps */
if (blizzard.pix_tx_time < min_tx_time)
blizzard.pix_tx_time = min_tx_time;
}
/* time to update one line in ps */
blizzard.line_upd_time = (hdisp + hndp) * 1000000 / (pix_clk / 1000);
blizzard.line_upd_time *= 1000;
if (hdisp * blizzard.pix_tx_time > blizzard.line_upd_time)
/* transfer speed too low, we might have to use both
* HS and VS */
use_hsvs = 1;
else
/* decent transfer speed, we'll always use only VS */
use_hsvs = 0;
if (use_hsvs && (hs_pol_inv || vs_pol_inv)) {
/* HS or'ed with VS doesn't work, use the active high
* TE signal based on HNDP / VNDP */
use_ndp = 1;
hs_pol_inv = 0;
vs_pol_inv = 0;
hs = hndp;
vs = vndp;
} else {
/* Use HS or'ed with VS as a TE signal if both are needed
* or VNDP if only vsync is needed. */
use_ndp = 0;
hs = hsw;
vs = vsw;
if (!use_hsvs) {
hs_pol_inv = 0;
vs_pol_inv = 0;
}
}
hs = hs * 1000000 / (pix_clk / 1000); /* ps */
hs *= 1000;
vs = vs * (hdisp + hndp) * 1000000 / (pix_clk / 1000); /* ps */
vs *= 1000;
if (vs <= hs)
return -EDOM;
/* set VS to 120% of HS to minimize VS detection time */
vs = hs * 12 / 10;
/* minimize HS too */
if (hs > 10000)
hs = 10000;
b = blizzard_read_reg(BLIZZARD_NDISP_CTRL_STATUS);
b &= ~0x3;
b |= use_hsvs ? 1 : 0;
b |= (use_ndp && use_hsvs) ? 0 : 2;
blizzard_write_reg(BLIZZARD_NDISP_CTRL_STATUS, b);
blizzard.vsync_only = !use_hsvs;
dev_dbg(blizzard.fbdev->dev,
"pix_clk %ld HZ pix_tx_time %ld ps line_upd_time %ld ps\n",
pix_clk, blizzard.pix_tx_time, blizzard.line_upd_time);
dev_dbg(blizzard.fbdev->dev,
"hs %d ps vs %d ps mode %d vsync_only %d\n",
hs, vs, b & 0x3, !use_hsvs);
return blizzard.extif->setup_tearsync(1, hs, vs,
hs_pol_inv, vs_pol_inv,
extif_div);
}
static void blizzard_get_caps(int plane, struct omapfb_caps *caps)
{
blizzard.int_ctrl->get_caps(plane, caps);
caps->ctrl |= OMAPFB_CAPS_MANUAL_UPDATE |
OMAPFB_CAPS_WINDOW_PIXEL_DOUBLE |
OMAPFB_CAPS_WINDOW_SCALE |
OMAPFB_CAPS_WINDOW_OVERLAY |
OMAPFB_CAPS_WINDOW_ROTATE;
if (blizzard.te_connected)
caps->ctrl |= OMAPFB_CAPS_TEARSYNC;
caps->wnd_color |= (1 << OMAPFB_COLOR_RGB565) |
(1 << OMAPFB_COLOR_YUV420);
}
static void _save_regs(const struct blizzard_reg_list *list, int cnt)
{
int i;
for (i = 0; i < cnt; i++, list++) {
int reg;
for (reg = list->start; reg <= list->end; reg += 2)
blizzard_reg_cache[reg / 2] = blizzard_read_reg(reg);
}
}
static void _restore_regs(const struct blizzard_reg_list *list, int cnt)
{
int i;
for (i = 0; i < cnt; i++, list++) {
int reg;
for (reg = list->start; reg <= list->end; reg += 2)
blizzard_write_reg(reg, blizzard_reg_cache[reg / 2]);
}
}
static void blizzard_save_all_regs(void)
{
_save_regs(blizzard_pll_regs, ARRAY_SIZE(blizzard_pll_regs));
_save_regs(blizzard_gen_regs, ARRAY_SIZE(blizzard_gen_regs));
}
static void blizzard_restore_pll_regs(void)
{
_restore_regs(blizzard_pll_regs, ARRAY_SIZE(blizzard_pll_regs));
}
static void blizzard_restore_gen_regs(void)
{
_restore_regs(blizzard_gen_regs, ARRAY_SIZE(blizzard_gen_regs));
}
static void blizzard_suspend(void)
{
u32 l;
unsigned long tmo;
if (blizzard.last_color_mode) {
update_full_screen();
blizzard_sync();
}
blizzard.update_mode_before_suspend = blizzard.update_mode;
/* the following will disable clocks as well */
blizzard_set_update_mode(OMAPFB_UPDATE_DISABLED);
blizzard_save_all_regs();
blizzard_stop_sdram();
l = blizzard_read_reg(BLIZZARD_POWER_SAVE);
/* Standby, Sleep. We assume we use an external clock. */
l |= 0x03;
blizzard_write_reg(BLIZZARD_POWER_SAVE, l);
tmo = jiffies + msecs_to_jiffies(100);
while (!(blizzard_read_reg(BLIZZARD_PLL_MODE) & (1 << 1))) {
if (time_after(jiffies, tmo)) {
dev_err(blizzard.fbdev->dev,
"s1d1374x: sleep timeout, stopping PLL manually\n");
l = blizzard_read_reg(BLIZZARD_PLL_MODE);
l &= ~0x03;
/* Disable PLL, counter function */
l |= 0x2;
blizzard_write_reg(BLIZZARD_PLL_MODE, l);
break;
}
msleep(1);
}
if (blizzard.power_down != NULL)
blizzard.power_down(blizzard.fbdev->dev);
}
static void blizzard_resume(void)
{
u32 l;
if (blizzard.power_up != NULL)
blizzard.power_up(blizzard.fbdev->dev);
l = blizzard_read_reg(BLIZZARD_POWER_SAVE);
/* Standby, Sleep */
l &= ~0x03;
blizzard_write_reg(BLIZZARD_POWER_SAVE, l);
blizzard_restore_pll_regs();
l = blizzard_read_reg(BLIZZARD_PLL_MODE);
l &= ~0x03;
/* Enable PLL, counter function */
l |= 0x1;
blizzard_write_reg(BLIZZARD_PLL_MODE, l);
while (!(blizzard_read_reg(BLIZZARD_PLL_DIV) & (1 << 7)))
msleep(1);
blizzard_restart_sdram();
blizzard_restore_gen_regs();
/* Enable display */
blizzard_write_reg(BLIZZARD_DISPLAY_MODE, 0x01);
/* the following will enable clocks as necessary */
blizzard_set_update_mode(blizzard.update_mode_before_suspend);
/* Force a background update */
blizzard.zoom_on = 1;
update_full_screen();
blizzard_sync();
}
static int blizzard_init(struct omapfb_device *fbdev, int ext_mode,
struct omapfb_mem_desc *req_vram)
{
int r = 0, i;
u8 rev, conf;
unsigned long ext_clk;
int extif_div;
unsigned long sys_clk, pix_clk;
struct omapfb_platform_data *omapfb_conf;
struct blizzard_platform_data *ctrl_conf;
blizzard.fbdev = fbdev;
BUG_ON(!fbdev->ext_if || !fbdev->int_ctrl);
blizzard.fbdev = fbdev;
blizzard.extif = fbdev->ext_if;
blizzard.int_ctrl = fbdev->int_ctrl;
omapfb_conf = fbdev->dev->platform_data;
ctrl_conf = omapfb_conf->ctrl_platform_data;
if (ctrl_conf == NULL || ctrl_conf->get_clock_rate == NULL) {
dev_err(fbdev->dev, "s1d1374x: missing platform data\n");
r = -ENOENT;
goto err1;
}
blizzard.power_down = ctrl_conf->power_down;
blizzard.power_up = ctrl_conf->power_up;
spin_lock_init(&blizzard.req_lock);
if ((r = blizzard.int_ctrl->init(fbdev, 1, req_vram)) < 0)
goto err1;
if ((r = blizzard.extif->init(fbdev)) < 0)
goto err2;
blizzard_ctrl.set_color_key = blizzard.int_ctrl->set_color_key;
blizzard_ctrl.get_color_key = blizzard.int_ctrl->get_color_key;
blizzard_ctrl.setup_mem = blizzard.int_ctrl->setup_mem;
blizzard_ctrl.mmap = blizzard.int_ctrl->mmap;
ext_clk = ctrl_conf->get_clock_rate(fbdev->dev);
if ((r = calc_extif_timings(ext_clk, &extif_div)) < 0)
goto err3;
set_extif_timings(&blizzard.reg_timings);
if (blizzard.power_up != NULL)
blizzard.power_up(fbdev->dev);
calc_blizzard_clk_rates(ext_clk, &sys_clk, &pix_clk);
if ((r = calc_extif_timings(sys_clk, &extif_div)) < 0)
goto err3;
set_extif_timings(&blizzard.reg_timings);
if (!(blizzard_read_reg(BLIZZARD_PLL_DIV) & 0x80)) {
dev_err(fbdev->dev,
"controller not initialized by the bootloader\n");
r = -ENODEV;
goto err3;
}
if (ctrl_conf->te_connected) {
if ((r = setup_tearsync(pix_clk, extif_div)) < 0)
goto err3;
blizzard.te_connected = 1;
}
rev = blizzard_read_reg(BLIZZARD_REV_CODE);
conf = blizzard_read_reg(BLIZZARD_CONFIG);
switch (rev & 0xfc) {
case 0x9c:
blizzard.version = BLIZZARD_VERSION_S1D13744;
pr_info("omapfb: s1d13744 LCD controller rev %d "
"initialized (CNF pins %x)\n", rev & 0x03, conf & 0x07);
break;
case 0xa4:
blizzard.version = BLIZZARD_VERSION_S1D13745;
pr_info("omapfb: s1d13745 LCD controller rev %d "
"initialized (CNF pins %x)\n", rev & 0x03, conf & 0x07);
break;
default:
dev_err(fbdev->dev, "invalid s1d1374x revision %02x\n",
rev);
r = -ENODEV;
goto err3;
}
blizzard.max_transmit_size = blizzard.extif->max_transmit_size;
blizzard.update_mode = OMAPFB_UPDATE_DISABLED;
blizzard.auto_update_window.x = 0;
blizzard.auto_update_window.y = 0;
blizzard.auto_update_window.width = fbdev->panel->x_res;
blizzard.auto_update_window.height = fbdev->panel->y_res;
blizzard.auto_update_window.out_x = 0;
blizzard.auto_update_window.out_y = 0;
blizzard.auto_update_window.out_width = fbdev->panel->x_res;
blizzard.auto_update_window.out_height = fbdev->panel->y_res;
blizzard.auto_update_window.format = 0;
blizzard.screen_width = fbdev->panel->x_res;
blizzard.screen_height = fbdev->panel->y_res;
init_timer(&blizzard.auto_update_timer);
blizzard.auto_update_timer.function = blizzard_update_window_auto;
blizzard.auto_update_timer.data = 0;
INIT_LIST_HEAD(&blizzard.free_req_list);
INIT_LIST_HEAD(&blizzard.pending_req_list);
for (i = 0; i < ARRAY_SIZE(blizzard.req_pool); i++)
list_add(&blizzard.req_pool[i].entry, &blizzard.free_req_list);
BUG_ON(i <= IRQ_REQ_POOL_SIZE);
sema_init(&blizzard.req_sema, i - IRQ_REQ_POOL_SIZE);
return 0;
err3:
if (blizzard.power_down != NULL)
blizzard.power_down(fbdev->dev);
blizzard.extif->cleanup();
err2:
blizzard.int_ctrl->cleanup();
err1:
return r;
}
static void blizzard_cleanup(void)
{
blizzard_set_update_mode(OMAPFB_UPDATE_DISABLED);
blizzard.extif->cleanup();
blizzard.int_ctrl->cleanup();
if (blizzard.power_down != NULL)
blizzard.power_down(blizzard.fbdev->dev);
}
struct lcd_ctrl blizzard_ctrl = {
.name = "blizzard",
.init = blizzard_init,
.cleanup = blizzard_cleanup,
.bind_client = blizzard_bind_client,
.get_caps = blizzard_get_caps,
.set_update_mode = blizzard_set_update_mode,
.get_update_mode = blizzard_get_update_mode,
.setup_plane = blizzard_setup_plane,
.set_scale = blizzard_set_scale,
.enable_plane = blizzard_enable_plane,
.set_rotate = blizzard_set_rotate,
.update_window = blizzard_update_window_async,
.sync = blizzard_sync,
.suspend = blizzard_suspend,
.resume = blizzard_resume,
};
| gpl-2.0 |
CM10DNA/android_kernel_htc_dlx | drivers/target/target_core_rd.c | 3452 | 13903 | /*******************************************************************************
* Filename: target_core_rd.c
*
* This file contains the Storage Engine <-> Ramdisk transport
* specific functions.
*
* Copyright (c) 2003, 2004, 2005 PyX Technologies, Inc.
* Copyright (c) 2005, 2006, 2007 SBE, Inc.
* Copyright (c) 2007-2010 Rising Tide Systems
* Copyright (c) 2008-2010 Linux-iSCSI.org
*
* Nicholas A. Bellinger <nab@kernel.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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
******************************************************************************/
#include <linux/string.h>
#include <linux/parser.h>
#include <linux/timer.h>
#include <linux/blkdev.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <scsi/scsi.h>
#include <scsi/scsi_host.h>
#include <target/target_core_base.h>
#include <target/target_core_backend.h>
#include "target_core_rd.h"
static struct se_subsystem_api rd_mcp_template;
/* rd_attach_hba(): (Part of se_subsystem_api_t template)
*
*
*/
static int rd_attach_hba(struct se_hba *hba, u32 host_id)
{
struct rd_host *rd_host;
rd_host = kzalloc(sizeof(struct rd_host), GFP_KERNEL);
if (!rd_host) {
pr_err("Unable to allocate memory for struct rd_host\n");
return -ENOMEM;
}
rd_host->rd_host_id = host_id;
hba->hba_ptr = rd_host;
pr_debug("CORE_HBA[%d] - TCM Ramdisk HBA Driver %s on"
" Generic Target Core Stack %s\n", hba->hba_id,
RD_HBA_VERSION, TARGET_CORE_MOD_VERSION);
pr_debug("CORE_HBA[%d] - Attached Ramdisk HBA: %u to Generic"
" MaxSectors: %u\n", hba->hba_id,
rd_host->rd_host_id, RD_MAX_SECTORS);
return 0;
}
static void rd_detach_hba(struct se_hba *hba)
{
struct rd_host *rd_host = hba->hba_ptr;
pr_debug("CORE_HBA[%d] - Detached Ramdisk HBA: %u from"
" Generic Target Core\n", hba->hba_id, rd_host->rd_host_id);
kfree(rd_host);
hba->hba_ptr = NULL;
}
/* rd_release_device_space():
*
*
*/
static void rd_release_device_space(struct rd_dev *rd_dev)
{
u32 i, j, page_count = 0, sg_per_table;
struct rd_dev_sg_table *sg_table;
struct page *pg;
struct scatterlist *sg;
if (!rd_dev->sg_table_array || !rd_dev->sg_table_count)
return;
sg_table = rd_dev->sg_table_array;
for (i = 0; i < rd_dev->sg_table_count; i++) {
sg = sg_table[i].sg_table;
sg_per_table = sg_table[i].rd_sg_count;
for (j = 0; j < sg_per_table; j++) {
pg = sg_page(&sg[j]);
if (pg) {
__free_page(pg);
page_count++;
}
}
kfree(sg);
}
pr_debug("CORE_RD[%u] - Released device space for Ramdisk"
" Device ID: %u, pages %u in %u tables total bytes %lu\n",
rd_dev->rd_host->rd_host_id, rd_dev->rd_dev_id, page_count,
rd_dev->sg_table_count, (unsigned long)page_count * PAGE_SIZE);
kfree(sg_table);
rd_dev->sg_table_array = NULL;
rd_dev->sg_table_count = 0;
}
/* rd_build_device_space():
*
*
*/
static int rd_build_device_space(struct rd_dev *rd_dev)
{
u32 i = 0, j, page_offset = 0, sg_per_table, sg_tables, total_sg_needed;
u32 max_sg_per_table = (RD_MAX_ALLOCATION_SIZE /
sizeof(struct scatterlist));
struct rd_dev_sg_table *sg_table;
struct page *pg;
struct scatterlist *sg;
if (rd_dev->rd_page_count <= 0) {
pr_err("Illegal page count: %u for Ramdisk device\n",
rd_dev->rd_page_count);
return -EINVAL;
}
total_sg_needed = rd_dev->rd_page_count;
sg_tables = (total_sg_needed / max_sg_per_table) + 1;
sg_table = kzalloc(sg_tables * sizeof(struct rd_dev_sg_table), GFP_KERNEL);
if (!sg_table) {
pr_err("Unable to allocate memory for Ramdisk"
" scatterlist tables\n");
return -ENOMEM;
}
rd_dev->sg_table_array = sg_table;
rd_dev->sg_table_count = sg_tables;
while (total_sg_needed) {
sg_per_table = (total_sg_needed > max_sg_per_table) ?
max_sg_per_table : total_sg_needed;
sg = kzalloc(sg_per_table * sizeof(struct scatterlist),
GFP_KERNEL);
if (!sg) {
pr_err("Unable to allocate scatterlist array"
" for struct rd_dev\n");
return -ENOMEM;
}
sg_init_table(sg, sg_per_table);
sg_table[i].sg_table = sg;
sg_table[i].rd_sg_count = sg_per_table;
sg_table[i].page_start_offset = page_offset;
sg_table[i++].page_end_offset = (page_offset + sg_per_table)
- 1;
for (j = 0; j < sg_per_table; j++) {
pg = alloc_pages(GFP_KERNEL, 0);
if (!pg) {
pr_err("Unable to allocate scatterlist"
" pages for struct rd_dev_sg_table\n");
return -ENOMEM;
}
sg_assign_page(&sg[j], pg);
sg[j].length = PAGE_SIZE;
}
page_offset += sg_per_table;
total_sg_needed -= sg_per_table;
}
pr_debug("CORE_RD[%u] - Built Ramdisk Device ID: %u space of"
" %u pages in %u tables\n", rd_dev->rd_host->rd_host_id,
rd_dev->rd_dev_id, rd_dev->rd_page_count,
rd_dev->sg_table_count);
return 0;
}
static void *rd_allocate_virtdevice(
struct se_hba *hba,
const char *name,
int rd_direct)
{
struct rd_dev *rd_dev;
struct rd_host *rd_host = hba->hba_ptr;
rd_dev = kzalloc(sizeof(struct rd_dev), GFP_KERNEL);
if (!rd_dev) {
pr_err("Unable to allocate memory for struct rd_dev\n");
return NULL;
}
rd_dev->rd_host = rd_host;
rd_dev->rd_direct = rd_direct;
return rd_dev;
}
static void *rd_MEMCPY_allocate_virtdevice(struct se_hba *hba, const char *name)
{
return rd_allocate_virtdevice(hba, name, 0);
}
/* rd_create_virtdevice():
*
*
*/
static struct se_device *rd_create_virtdevice(
struct se_hba *hba,
struct se_subsystem_dev *se_dev,
void *p,
int rd_direct)
{
struct se_device *dev;
struct se_dev_limits dev_limits;
struct rd_dev *rd_dev = p;
struct rd_host *rd_host = hba->hba_ptr;
int dev_flags = 0, ret;
char prod[16], rev[4];
memset(&dev_limits, 0, sizeof(struct se_dev_limits));
ret = rd_build_device_space(rd_dev);
if (ret < 0)
goto fail;
snprintf(prod, 16, "RAMDISK-%s", (rd_dev->rd_direct) ? "DR" : "MCP");
snprintf(rev, 4, "%s", (rd_dev->rd_direct) ? RD_DR_VERSION :
RD_MCP_VERSION);
dev_limits.limits.logical_block_size = RD_BLOCKSIZE;
dev_limits.limits.max_hw_sectors = RD_MAX_SECTORS;
dev_limits.limits.max_sectors = RD_MAX_SECTORS;
dev_limits.hw_queue_depth = RD_MAX_DEVICE_QUEUE_DEPTH;
dev_limits.queue_depth = RD_DEVICE_QUEUE_DEPTH;
dev = transport_add_device_to_core_hba(hba,
&rd_mcp_template, se_dev, dev_flags, rd_dev,
&dev_limits, prod, rev);
if (!dev)
goto fail;
rd_dev->rd_dev_id = rd_host->rd_host_dev_id_count++;
rd_dev->rd_queue_depth = dev->queue_depth;
pr_debug("CORE_RD[%u] - Added TCM %s Ramdisk Device ID: %u of"
" %u pages in %u tables, %lu total bytes\n",
rd_host->rd_host_id, (!rd_dev->rd_direct) ? "MEMCPY" :
"DIRECT", rd_dev->rd_dev_id, rd_dev->rd_page_count,
rd_dev->sg_table_count,
(unsigned long)(rd_dev->rd_page_count * PAGE_SIZE));
return dev;
fail:
rd_release_device_space(rd_dev);
return ERR_PTR(ret);
}
static struct se_device *rd_MEMCPY_create_virtdevice(
struct se_hba *hba,
struct se_subsystem_dev *se_dev,
void *p)
{
return rd_create_virtdevice(hba, se_dev, p, 0);
}
/* rd_free_device(): (Part of se_subsystem_api_t template)
*
*
*/
static void rd_free_device(void *p)
{
struct rd_dev *rd_dev = p;
rd_release_device_space(rd_dev);
kfree(rd_dev);
}
static inline struct rd_request *RD_REQ(struct se_task *task)
{
return container_of(task, struct rd_request, rd_task);
}
static struct se_task *
rd_alloc_task(unsigned char *cdb)
{
struct rd_request *rd_req;
rd_req = kzalloc(sizeof(struct rd_request), GFP_KERNEL);
if (!rd_req) {
pr_err("Unable to allocate struct rd_request\n");
return NULL;
}
return &rd_req->rd_task;
}
/* rd_get_sg_table():
*
*
*/
static struct rd_dev_sg_table *rd_get_sg_table(struct rd_dev *rd_dev, u32 page)
{
u32 i;
struct rd_dev_sg_table *sg_table;
for (i = 0; i < rd_dev->sg_table_count; i++) {
sg_table = &rd_dev->sg_table_array[i];
if ((sg_table->page_start_offset <= page) &&
(sg_table->page_end_offset >= page))
return sg_table;
}
pr_err("Unable to locate struct rd_dev_sg_table for page: %u\n",
page);
return NULL;
}
static int rd_MEMCPY(struct rd_request *req, u32 read_rd)
{
struct se_task *task = &req->rd_task;
struct rd_dev *dev = req->rd_task.task_se_cmd->se_dev->dev_ptr;
struct rd_dev_sg_table *table;
struct scatterlist *rd_sg;
struct sg_mapping_iter m;
u32 rd_offset = req->rd_offset;
u32 src_len;
table = rd_get_sg_table(dev, req->rd_page);
if (!table)
return -EINVAL;
rd_sg = &table->sg_table[req->rd_page - table->page_start_offset];
pr_debug("RD[%u]: %s LBA: %llu, Size: %u Page: %u, Offset: %u\n",
dev->rd_dev_id, read_rd ? "Read" : "Write",
task->task_lba, req->rd_size, req->rd_page,
rd_offset);
src_len = PAGE_SIZE - rd_offset;
sg_miter_start(&m, task->task_sg, task->task_sg_nents,
read_rd ? SG_MITER_TO_SG : SG_MITER_FROM_SG);
while (req->rd_size) {
u32 len;
void *rd_addr;
sg_miter_next(&m);
len = min((u32)m.length, src_len);
m.consumed = len;
rd_addr = sg_virt(rd_sg) + rd_offset;
if (read_rd)
memcpy(m.addr, rd_addr, len);
else
memcpy(rd_addr, m.addr, len);
req->rd_size -= len;
if (!req->rd_size)
continue;
src_len -= len;
if (src_len) {
rd_offset += len;
continue;
}
/* rd page completed, next one please */
req->rd_page++;
rd_offset = 0;
src_len = PAGE_SIZE;
if (req->rd_page <= table->page_end_offset) {
rd_sg++;
continue;
}
table = rd_get_sg_table(dev, req->rd_page);
if (!table) {
sg_miter_stop(&m);
return -EINVAL;
}
/* since we increment, the first sg entry is correct */
rd_sg = table->sg_table;
}
sg_miter_stop(&m);
return 0;
}
/* rd_MEMCPY_do_task(): (Part of se_subsystem_api_t template)
*
*
*/
static int rd_MEMCPY_do_task(struct se_task *task)
{
struct se_device *dev = task->task_se_cmd->se_dev;
struct rd_request *req = RD_REQ(task);
u64 tmp;
int ret;
tmp = task->task_lba * dev->se_sub_dev->se_dev_attrib.block_size;
req->rd_offset = do_div(tmp, PAGE_SIZE);
req->rd_page = tmp;
req->rd_size = task->task_size;
ret = rd_MEMCPY(req, task->task_data_direction == DMA_FROM_DEVICE);
if (ret != 0)
return ret;
task->task_scsi_status = GOOD;
transport_complete_task(task, 1);
return 0;
}
/* rd_free_task(): (Part of se_subsystem_api_t template)
*
*
*/
static void rd_free_task(struct se_task *task)
{
kfree(RD_REQ(task));
}
enum {
Opt_rd_pages, Opt_err
};
static match_table_t tokens = {
{Opt_rd_pages, "rd_pages=%d"},
{Opt_err, NULL}
};
static ssize_t rd_set_configfs_dev_params(
struct se_hba *hba,
struct se_subsystem_dev *se_dev,
const char *page,
ssize_t count)
{
struct rd_dev *rd_dev = se_dev->se_dev_su_ptr;
char *orig, *ptr, *opts;
substring_t args[MAX_OPT_ARGS];
int ret = 0, arg, token;
opts = kstrdup(page, GFP_KERNEL);
if (!opts)
return -ENOMEM;
orig = opts;
while ((ptr = strsep(&opts, ",\n")) != NULL) {
if (!*ptr)
continue;
token = match_token(ptr, tokens, args);
switch (token) {
case Opt_rd_pages:
match_int(args, &arg);
rd_dev->rd_page_count = arg;
pr_debug("RAMDISK: Referencing Page"
" Count: %u\n", rd_dev->rd_page_count);
rd_dev->rd_flags |= RDF_HAS_PAGE_COUNT;
break;
default:
break;
}
}
kfree(orig);
return (!ret) ? count : ret;
}
static ssize_t rd_check_configfs_dev_params(struct se_hba *hba, struct se_subsystem_dev *se_dev)
{
struct rd_dev *rd_dev = se_dev->se_dev_su_ptr;
if (!(rd_dev->rd_flags & RDF_HAS_PAGE_COUNT)) {
pr_debug("Missing rd_pages= parameter\n");
return -EINVAL;
}
return 0;
}
static ssize_t rd_show_configfs_dev_params(
struct se_hba *hba,
struct se_subsystem_dev *se_dev,
char *b)
{
struct rd_dev *rd_dev = se_dev->se_dev_su_ptr;
ssize_t bl = sprintf(b, "TCM RamDisk ID: %u RamDisk Makeup: %s\n",
rd_dev->rd_dev_id, (rd_dev->rd_direct) ?
"rd_direct" : "rd_mcp");
bl += sprintf(b + bl, " PAGES/PAGE_SIZE: %u*%lu"
" SG_table_count: %u\n", rd_dev->rd_page_count,
PAGE_SIZE, rd_dev->sg_table_count);
return bl;
}
static u32 rd_get_device_rev(struct se_device *dev)
{
return SCSI_SPC_2; /* Returns SPC-3 in Initiator Data */
}
static u32 rd_get_device_type(struct se_device *dev)
{
return TYPE_DISK;
}
static sector_t rd_get_blocks(struct se_device *dev)
{
struct rd_dev *rd_dev = dev->dev_ptr;
unsigned long long blocks_long = ((rd_dev->rd_page_count * PAGE_SIZE) /
dev->se_sub_dev->se_dev_attrib.block_size) - 1;
return blocks_long;
}
static struct se_subsystem_api rd_mcp_template = {
.name = "rd_mcp",
.transport_type = TRANSPORT_PLUGIN_VHBA_VDEV,
.attach_hba = rd_attach_hba,
.detach_hba = rd_detach_hba,
.allocate_virtdevice = rd_MEMCPY_allocate_virtdevice,
.create_virtdevice = rd_MEMCPY_create_virtdevice,
.free_device = rd_free_device,
.alloc_task = rd_alloc_task,
.do_task = rd_MEMCPY_do_task,
.free_task = rd_free_task,
.check_configfs_dev_params = rd_check_configfs_dev_params,
.set_configfs_dev_params = rd_set_configfs_dev_params,
.show_configfs_dev_params = rd_show_configfs_dev_params,
.get_device_rev = rd_get_device_rev,
.get_device_type = rd_get_device_type,
.get_blocks = rd_get_blocks,
};
int __init rd_module_init(void)
{
int ret;
ret = transport_subsystem_register(&rd_mcp_template);
if (ret < 0) {
return ret;
}
return 0;
}
void rd_module_exit(void)
{
transport_subsystem_release(&rd_mcp_template);
}
| gpl-2.0 |
hzpeterchen/linux-usb | arch/x86/um/syscalls_64.c | 3708 | 2220 | /*
* Copyright (C) 2003 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Copyright 2003 PathScale, Inc.
*
* Licensed under the GPL
*/
#include <linux/sched.h>
#include <asm/prctl.h> /* XXX This should get the constants from libc */
#include <os.h>
long arch_prctl(struct task_struct *task, int code, unsigned long __user *addr)
{
unsigned long *ptr = addr, tmp;
long ret;
int pid = task->mm->context.id.u.pid;
/*
* With ARCH_SET_FS (and ARCH_SET_GS is treated similarly to
* be safe), we need to call arch_prctl on the host because
* setting %fs may result in something else happening (like a
* GDT or thread.fs being set instead). So, we let the host
* fiddle the registers and thread struct and restore the
* registers afterwards.
*
* So, the saved registers are stored to the process (this
* needed because a stub may have been the last thing to run),
* arch_prctl is run on the host, then the registers are read
* back.
*/
switch (code) {
case ARCH_SET_FS:
case ARCH_SET_GS:
ret = restore_registers(pid, ¤t->thread.regs.regs);
if (ret)
return ret;
break;
case ARCH_GET_FS:
case ARCH_GET_GS:
/*
* With these two, we read to a local pointer and
* put_user it to the userspace pointer that we were
* given. If addr isn't valid (because it hasn't been
* faulted in or is just bogus), we want put_user to
* fault it in (or return -EFAULT) instead of having
* the host return -EFAULT.
*/
ptr = &tmp;
}
ret = os_arch_prctl(pid, code, ptr);
if (ret)
return ret;
switch (code) {
case ARCH_SET_FS:
current->thread.arch.fs = (unsigned long) ptr;
ret = save_registers(pid, ¤t->thread.regs.regs);
break;
case ARCH_SET_GS:
ret = save_registers(pid, ¤t->thread.regs.regs);
break;
case ARCH_GET_FS:
ret = put_user(tmp, addr);
break;
case ARCH_GET_GS:
ret = put_user(tmp, addr);
break;
}
return ret;
}
long sys_arch_prctl(int code, unsigned long addr)
{
return arch_prctl(current, code, (unsigned long __user *) addr);
}
void arch_switch_to(struct task_struct *to)
{
if ((to->thread.arch.fs == 0) || (to->mm == NULL))
return;
arch_prctl(to, ARCH_SET_FS, (void __user *) to->thread.arch.fs);
}
| gpl-2.0 |
SaberMod/samsung_kernel_manta | drivers/gpu/drm/nouveau/nouveau_drv.c | 3708 | 14044 | /*
* Copyright 2005 Stephane Marchesin.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <linux/console.h>
#include <linux/module.h>
#include "drmP.h"
#include "drm.h"
#include "drm_crtc_helper.h"
#include "nouveau_drv.h"
#include "nouveau_hw.h"
#include "nouveau_fb.h"
#include "nouveau_fbcon.h"
#include "nouveau_pm.h"
#include "nv50_display.h"
#include "drm_pciids.h"
MODULE_PARM_DESC(agpmode, "AGP mode (0 to disable AGP)");
int nouveau_agpmode = -1;
module_param_named(agpmode, nouveau_agpmode, int, 0400);
MODULE_PARM_DESC(modeset, "Enable kernel modesetting");
int nouveau_modeset = -1;
module_param_named(modeset, nouveau_modeset, int, 0400);
MODULE_PARM_DESC(vbios, "Override default VBIOS location");
char *nouveau_vbios;
module_param_named(vbios, nouveau_vbios, charp, 0400);
MODULE_PARM_DESC(vram_pushbuf, "Force DMA push buffers to be in VRAM");
int nouveau_vram_pushbuf;
module_param_named(vram_pushbuf, nouveau_vram_pushbuf, int, 0400);
MODULE_PARM_DESC(vram_notify, "Force DMA notifiers to be in VRAM");
int nouveau_vram_notify = 0;
module_param_named(vram_notify, nouveau_vram_notify, int, 0400);
MODULE_PARM_DESC(vram_type, "Override detected VRAM type");
char *nouveau_vram_type;
module_param_named(vram_type, nouveau_vram_type, charp, 0400);
MODULE_PARM_DESC(duallink, "Allow dual-link TMDS (>=GeForce 8)");
int nouveau_duallink = 1;
module_param_named(duallink, nouveau_duallink, int, 0400);
MODULE_PARM_DESC(uscript_lvds, "LVDS output script table ID (>=GeForce 8)");
int nouveau_uscript_lvds = -1;
module_param_named(uscript_lvds, nouveau_uscript_lvds, int, 0400);
MODULE_PARM_DESC(uscript_tmds, "TMDS output script table ID (>=GeForce 8)");
int nouveau_uscript_tmds = -1;
module_param_named(uscript_tmds, nouveau_uscript_tmds, int, 0400);
MODULE_PARM_DESC(ignorelid, "Ignore ACPI lid status");
int nouveau_ignorelid = 0;
module_param_named(ignorelid, nouveau_ignorelid, int, 0400);
MODULE_PARM_DESC(noaccel, "Disable all acceleration");
int nouveau_noaccel = -1;
module_param_named(noaccel, nouveau_noaccel, int, 0400);
MODULE_PARM_DESC(nofbaccel, "Disable fbcon acceleration");
int nouveau_nofbaccel = 0;
module_param_named(nofbaccel, nouveau_nofbaccel, int, 0400);
MODULE_PARM_DESC(force_post, "Force POST");
int nouveau_force_post = 0;
module_param_named(force_post, nouveau_force_post, int, 0400);
MODULE_PARM_DESC(override_conntype, "Ignore DCB connector type");
int nouveau_override_conntype = 0;
module_param_named(override_conntype, nouveau_override_conntype, int, 0400);
MODULE_PARM_DESC(tv_disable, "Disable TV-out detection");
int nouveau_tv_disable = 0;
module_param_named(tv_disable, nouveau_tv_disable, int, 0400);
MODULE_PARM_DESC(tv_norm, "Default TV norm.\n"
"\t\tSupported: PAL, PAL-M, PAL-N, PAL-Nc, NTSC-M, NTSC-J,\n"
"\t\t\thd480i, hd480p, hd576i, hd576p, hd720p, hd1080i.\n"
"\t\tDefault: PAL\n"
"\t\t*NOTE* Ignored for cards with external TV encoders.");
char *nouveau_tv_norm;
module_param_named(tv_norm, nouveau_tv_norm, charp, 0400);
MODULE_PARM_DESC(reg_debug, "Register access debug bitmask:\n"
"\t\t0x1 mc, 0x2 video, 0x4 fb, 0x8 extdev,\n"
"\t\t0x10 crtc, 0x20 ramdac, 0x40 vgacrtc, 0x80 rmvio,\n"
"\t\t0x100 vgaattr, 0x200 EVO (G80+)");
int nouveau_reg_debug;
module_param_named(reg_debug, nouveau_reg_debug, int, 0600);
MODULE_PARM_DESC(perflvl, "Performance level (default: boot)");
char *nouveau_perflvl;
module_param_named(perflvl, nouveau_perflvl, charp, 0400);
MODULE_PARM_DESC(perflvl_wr, "Allow perflvl changes (warning: dangerous!)");
int nouveau_perflvl_wr;
module_param_named(perflvl_wr, nouveau_perflvl_wr, int, 0400);
MODULE_PARM_DESC(msi, "Enable MSI (default: off)");
int nouveau_msi;
module_param_named(msi, nouveau_msi, int, 0400);
MODULE_PARM_DESC(ctxfw, "Use external HUB/GPC ucode (fermi)");
int nouveau_ctxfw;
module_param_named(ctxfw, nouveau_ctxfw, int, 0400);
MODULE_PARM_DESC(mxmdcb, "Santise DCB table according to MXM-SIS");
int nouveau_mxmdcb = 1;
module_param_named(mxmdcb, nouveau_mxmdcb, int, 0400);
int nouveau_fbpercrtc;
#if 0
module_param_named(fbpercrtc, nouveau_fbpercrtc, int, 0400);
#endif
static struct pci_device_id pciidlist[] = {
{
PCI_DEVICE(PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID),
.class = PCI_BASE_CLASS_DISPLAY << 16,
.class_mask = 0xff << 16,
},
{
PCI_DEVICE(PCI_VENDOR_ID_NVIDIA_SGS, PCI_ANY_ID),
.class = PCI_BASE_CLASS_DISPLAY << 16,
.class_mask = 0xff << 16,
},
{}
};
MODULE_DEVICE_TABLE(pci, pciidlist);
static struct drm_driver driver;
static int __devinit
nouveau_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
return drm_get_pci_dev(pdev, ent, &driver);
}
static void
nouveau_pci_remove(struct pci_dev *pdev)
{
struct drm_device *dev = pci_get_drvdata(pdev);
drm_put_dev(dev);
}
int
nouveau_pci_suspend(struct pci_dev *pdev, pm_message_t pm_state)
{
struct drm_device *dev = pci_get_drvdata(pdev);
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_instmem_engine *pinstmem = &dev_priv->engine.instmem;
struct nouveau_fifo_engine *pfifo = &dev_priv->engine.fifo;
struct nouveau_channel *chan;
struct drm_crtc *crtc;
int ret, i, e;
if (pm_state.event == PM_EVENT_PRETHAW)
return 0;
if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
return 0;
NV_INFO(dev, "Disabling display...\n");
nouveau_display_fini(dev);
NV_INFO(dev, "Disabling fbcon...\n");
nouveau_fbcon_set_suspend(dev, 1);
NV_INFO(dev, "Unpinning framebuffer(s)...\n");
list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
struct nouveau_framebuffer *nouveau_fb;
nouveau_fb = nouveau_framebuffer(crtc->fb);
if (!nouveau_fb || !nouveau_fb->nvbo)
continue;
nouveau_bo_unpin(nouveau_fb->nvbo);
}
list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
nouveau_bo_unmap(nv_crtc->cursor.nvbo);
nouveau_bo_unpin(nv_crtc->cursor.nvbo);
}
NV_INFO(dev, "Evicting buffers...\n");
ttm_bo_evict_mm(&dev_priv->ttm.bdev, TTM_PL_VRAM);
NV_INFO(dev, "Idling channels...\n");
for (i = 0; i < pfifo->channels; i++) {
chan = dev_priv->channels.ptr[i];
if (chan && chan->pushbuf_bo)
nouveau_channel_idle(chan);
}
pfifo->reassign(dev, false);
pfifo->disable(dev);
pfifo->unload_context(dev);
for (e = NVOBJ_ENGINE_NR - 1; e >= 0; e--) {
if (!dev_priv->eng[e])
continue;
ret = dev_priv->eng[e]->fini(dev, e, true);
if (ret) {
NV_ERROR(dev, "... engine %d failed: %d\n", e, ret);
goto out_abort;
}
}
ret = pinstmem->suspend(dev);
if (ret) {
NV_ERROR(dev, "... failed: %d\n", ret);
goto out_abort;
}
NV_INFO(dev, "Suspending GPU objects...\n");
ret = nouveau_gpuobj_suspend(dev);
if (ret) {
NV_ERROR(dev, "... failed: %d\n", ret);
pinstmem->resume(dev);
goto out_abort;
}
NV_INFO(dev, "And we're gone!\n");
pci_save_state(pdev);
if (pm_state.event == PM_EVENT_SUSPEND) {
pci_disable_device(pdev);
pci_set_power_state(pdev, PCI_D3hot);
}
return 0;
out_abort:
NV_INFO(dev, "Re-enabling acceleration..\n");
for (e = e + 1; e < NVOBJ_ENGINE_NR; e++) {
if (dev_priv->eng[e])
dev_priv->eng[e]->init(dev, e);
}
pfifo->enable(dev);
pfifo->reassign(dev, true);
return ret;
}
int
nouveau_pci_resume(struct pci_dev *pdev)
{
struct drm_device *dev = pci_get_drvdata(pdev);
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_engine *engine = &dev_priv->engine;
struct drm_crtc *crtc;
int ret, i;
if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
return 0;
NV_INFO(dev, "We're back, enabling device...\n");
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
if (pci_enable_device(pdev))
return -1;
pci_set_master(dev->pdev);
/* Make sure the AGP controller is in a consistent state */
if (dev_priv->gart_info.type == NOUVEAU_GART_AGP)
nouveau_mem_reset_agp(dev);
/* Make the CRTCs accessible */
engine->display.early_init(dev);
NV_INFO(dev, "POSTing device...\n");
ret = nouveau_run_vbios_init(dev);
if (ret)
return ret;
if (dev_priv->gart_info.type == NOUVEAU_GART_AGP) {
ret = nouveau_mem_init_agp(dev);
if (ret) {
NV_ERROR(dev, "error reinitialising AGP: %d\n", ret);
return ret;
}
}
NV_INFO(dev, "Restoring GPU objects...\n");
nouveau_gpuobj_resume(dev);
NV_INFO(dev, "Reinitialising engines...\n");
engine->instmem.resume(dev);
engine->mc.init(dev);
engine->timer.init(dev);
engine->fb.init(dev);
for (i = 0; i < NVOBJ_ENGINE_NR; i++) {
if (dev_priv->eng[i])
dev_priv->eng[i]->init(dev, i);
}
engine->fifo.init(dev);
nouveau_irq_postinstall(dev);
/* Re-write SKIPS, they'll have been lost over the suspend */
if (nouveau_vram_pushbuf) {
struct nouveau_channel *chan;
int j;
for (i = 0; i < dev_priv->engine.fifo.channels; i++) {
chan = dev_priv->channels.ptr[i];
if (!chan || !chan->pushbuf_bo)
continue;
for (j = 0; j < NOUVEAU_DMA_SKIPS; j++)
nouveau_bo_wr32(chan->pushbuf_bo, i, 0);
}
}
nouveau_pm_resume(dev);
NV_INFO(dev, "Restoring mode...\n");
list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
struct nouveau_framebuffer *nouveau_fb;
nouveau_fb = nouveau_framebuffer(crtc->fb);
if (!nouveau_fb || !nouveau_fb->nvbo)
continue;
nouveau_bo_pin(nouveau_fb->nvbo, TTM_PL_FLAG_VRAM);
}
list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
ret = nouveau_bo_pin(nv_crtc->cursor.nvbo, TTM_PL_FLAG_VRAM);
if (!ret)
ret = nouveau_bo_map(nv_crtc->cursor.nvbo);
if (ret)
NV_ERROR(dev, "Could not pin/map cursor.\n");
}
nouveau_fbcon_set_suspend(dev, 0);
nouveau_fbcon_zfill_all(dev);
nouveau_display_init(dev);
/* Force CLUT to get re-loaded during modeset */
list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
nv_crtc->lut.depth = 0;
}
drm_helper_resume_force_mode(dev);
list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
u32 offset = nv_crtc->cursor.nvbo->bo.offset;
nv_crtc->cursor.set_offset(nv_crtc, offset);
nv_crtc->cursor.set_pos(nv_crtc, nv_crtc->cursor_saved_x,
nv_crtc->cursor_saved_y);
}
return 0;
}
static const struct file_operations nouveau_driver_fops = {
.owner = THIS_MODULE,
.open = drm_open,
.release = drm_release,
.unlocked_ioctl = drm_ioctl,
.mmap = nouveau_ttm_mmap,
.poll = drm_poll,
.fasync = drm_fasync,
.read = drm_read,
#if defined(CONFIG_COMPAT)
.compat_ioctl = nouveau_compat_ioctl,
#endif
.llseek = noop_llseek,
};
static struct drm_driver driver = {
.driver_features =
DRIVER_USE_AGP | DRIVER_PCI_DMA | DRIVER_SG |
DRIVER_HAVE_IRQ | DRIVER_IRQ_SHARED | DRIVER_GEM |
DRIVER_MODESET,
.load = nouveau_load,
.firstopen = nouveau_firstopen,
.lastclose = nouveau_lastclose,
.unload = nouveau_unload,
.open = nouveau_open,
.preclose = nouveau_preclose,
.postclose = nouveau_postclose,
#if defined(CONFIG_DRM_NOUVEAU_DEBUG)
.debugfs_init = nouveau_debugfs_init,
.debugfs_cleanup = nouveau_debugfs_takedown,
#endif
.irq_preinstall = nouveau_irq_preinstall,
.irq_postinstall = nouveau_irq_postinstall,
.irq_uninstall = nouveau_irq_uninstall,
.irq_handler = nouveau_irq_handler,
.get_vblank_counter = drm_vblank_count,
.enable_vblank = nouveau_vblank_enable,
.disable_vblank = nouveau_vblank_disable,
.reclaim_buffers = drm_core_reclaim_buffers,
.ioctls = nouveau_ioctls,
.fops = &nouveau_driver_fops,
.gem_init_object = nouveau_gem_object_new,
.gem_free_object = nouveau_gem_object_del,
.gem_open_object = nouveau_gem_object_open,
.gem_close_object = nouveau_gem_object_close,
.dumb_create = nouveau_display_dumb_create,
.dumb_map_offset = nouveau_display_dumb_map_offset,
.dumb_destroy = nouveau_display_dumb_destroy,
.name = DRIVER_NAME,
.desc = DRIVER_DESC,
#ifdef GIT_REVISION
.date = GIT_REVISION,
#else
.date = DRIVER_DATE,
#endif
.major = DRIVER_MAJOR,
.minor = DRIVER_MINOR,
.patchlevel = DRIVER_PATCHLEVEL,
};
static struct pci_driver nouveau_pci_driver = {
.name = DRIVER_NAME,
.id_table = pciidlist,
.probe = nouveau_pci_probe,
.remove = nouveau_pci_remove,
.suspend = nouveau_pci_suspend,
.resume = nouveau_pci_resume
};
static int __init nouveau_init(void)
{
driver.num_ioctls = nouveau_max_ioctl;
if (nouveau_modeset == -1) {
#ifdef CONFIG_VGA_CONSOLE
if (vgacon_text_force())
nouveau_modeset = 0;
else
#endif
nouveau_modeset = 1;
}
if (!nouveau_modeset)
return 0;
nouveau_register_dsm_handler();
return drm_pci_init(&driver, &nouveau_pci_driver);
}
static void __exit nouveau_exit(void)
{
if (!nouveau_modeset)
return;
drm_pci_exit(&driver, &nouveau_pci_driver);
nouveau_unregister_dsm_handler();
}
module_init(nouveau_init);
module_exit(nouveau_exit);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL and additional rights");
| gpl-2.0 |
aatjitra/OnePlus | fs/read_write.c | 3964 | 22942 | /*
* linux/fs/read_write.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
#include <linux/slab.h>
#include <linux/stat.h>
#include <linux/fcntl.h>
#include <linux/file.h>
#include <linux/uio.h>
#include <linux/fsnotify.h>
#include <linux/security.h>
#include <linux/export.h>
#include <linux/syscalls.h>
#include <linux/pagemap.h>
#include <linux/splice.h>
#include "read_write.h"
#include <asm/uaccess.h>
#include <asm/unistd.h>
const struct file_operations generic_ro_fops = {
.llseek = generic_file_llseek,
.read = do_sync_read,
.aio_read = generic_file_aio_read,
.mmap = generic_file_readonly_mmap,
.splice_read = generic_file_splice_read,
};
EXPORT_SYMBOL(generic_ro_fops);
static inline int unsigned_offsets(struct file *file)
{
return file->f_mode & FMODE_UNSIGNED_OFFSET;
}
static loff_t lseek_execute(struct file *file, struct inode *inode,
loff_t offset, loff_t maxsize)
{
if (offset < 0 && !unsigned_offsets(file))
return -EINVAL;
if (offset > maxsize)
return -EINVAL;
if (offset != file->f_pos) {
file->f_pos = offset;
file->f_version = 0;
}
return offset;
}
/**
* generic_file_llseek_size - generic llseek implementation for regular files
* @file: file structure to seek on
* @offset: file offset to seek to
* @origin: type of seek
* @size: max size of file system
*
* This is a variant of generic_file_llseek that allows passing in a custom
* file size.
*
* Synchronization:
* SEEK_SET and SEEK_END are unsynchronized (but atomic on 64bit platforms)
* SEEK_CUR is synchronized against other SEEK_CURs, but not read/writes.
* read/writes behave like SEEK_SET against seeks.
*/
loff_t
generic_file_llseek_size(struct file *file, loff_t offset, int origin,
loff_t maxsize)
{
struct inode *inode = file->f_mapping->host;
switch (origin) {
case SEEK_END:
offset += i_size_read(inode);
break;
case SEEK_CUR:
/*
* Here we special-case the lseek(fd, 0, SEEK_CUR)
* position-querying operation. Avoid rewriting the "same"
* f_pos value back to the file because a concurrent read(),
* write() or lseek() might have altered it
*/
if (offset == 0)
return file->f_pos;
/*
* f_lock protects against read/modify/write race with other
* SEEK_CURs. Note that parallel writes and reads behave
* like SEEK_SET.
*/
spin_lock(&file->f_lock);
offset = lseek_execute(file, inode, file->f_pos + offset,
maxsize);
spin_unlock(&file->f_lock);
return offset;
case SEEK_DATA:
/*
* In the generic case the entire file is data, so as long as
* offset isn't at the end of the file then the offset is data.
*/
if (offset >= i_size_read(inode))
return -ENXIO;
break;
case SEEK_HOLE:
/*
* There is a virtual hole at the end of the file, so as long as
* offset isn't i_size or larger, return i_size.
*/
if (offset >= i_size_read(inode))
return -ENXIO;
offset = i_size_read(inode);
break;
}
return lseek_execute(file, inode, offset, maxsize);
}
EXPORT_SYMBOL(generic_file_llseek_size);
/**
* generic_file_llseek - generic llseek implementation for regular files
* @file: file structure to seek on
* @offset: file offset to seek to
* @origin: type of seek
*
* This is a generic implemenation of ->llseek useable for all normal local
* filesystems. It just updates the file offset to the value specified by
* @offset and @origin under i_mutex.
*/
loff_t generic_file_llseek(struct file *file, loff_t offset, int origin)
{
struct inode *inode = file->f_mapping->host;
return generic_file_llseek_size(file, offset, origin,
inode->i_sb->s_maxbytes);
}
EXPORT_SYMBOL(generic_file_llseek);
/**
* noop_llseek - No Operation Performed llseek implementation
* @file: file structure to seek on
* @offset: file offset to seek to
* @origin: type of seek
*
* This is an implementation of ->llseek useable for the rare special case when
* userspace expects the seek to succeed but the (device) file is actually not
* able to perform the seek. In this case you use noop_llseek() instead of
* falling back to the default implementation of ->llseek.
*/
loff_t noop_llseek(struct file *file, loff_t offset, int origin)
{
return file->f_pos;
}
EXPORT_SYMBOL(noop_llseek);
loff_t no_llseek(struct file *file, loff_t offset, int origin)
{
return -ESPIPE;
}
EXPORT_SYMBOL(no_llseek);
loff_t default_llseek(struct file *file, loff_t offset, int origin)
{
struct inode *inode = file->f_path.dentry->d_inode;
loff_t retval;
mutex_lock(&inode->i_mutex);
switch (origin) {
case SEEK_END:
offset += i_size_read(inode);
break;
case SEEK_CUR:
if (offset == 0) {
retval = file->f_pos;
goto out;
}
offset += file->f_pos;
break;
case SEEK_DATA:
/*
* In the generic case the entire file is data, so as
* long as offset isn't at the end of the file then the
* offset is data.
*/
if (offset >= inode->i_size) {
retval = -ENXIO;
goto out;
}
break;
case SEEK_HOLE:
/*
* There is a virtual hole at the end of the file, so
* as long as offset isn't i_size or larger, return
* i_size.
*/
if (offset >= inode->i_size) {
retval = -ENXIO;
goto out;
}
offset = inode->i_size;
break;
}
retval = -EINVAL;
if (offset >= 0 || unsigned_offsets(file)) {
if (offset != file->f_pos) {
file->f_pos = offset;
file->f_version = 0;
}
retval = offset;
}
out:
mutex_unlock(&inode->i_mutex);
return retval;
}
EXPORT_SYMBOL(default_llseek);
loff_t vfs_llseek(struct file *file, loff_t offset, int origin)
{
loff_t (*fn)(struct file *, loff_t, int);
fn = no_llseek;
if (file->f_mode & FMODE_LSEEK) {
if (file->f_op && file->f_op->llseek)
fn = file->f_op->llseek;
}
return fn(file, offset, origin);
}
EXPORT_SYMBOL(vfs_llseek);
SYSCALL_DEFINE3(lseek, unsigned int, fd, off_t, offset, unsigned int, origin)
{
off_t retval;
struct file * file;
int fput_needed;
retval = -EBADF;
file = fget_light(fd, &fput_needed);
if (!file)
goto bad;
retval = -EINVAL;
if (origin <= SEEK_MAX) {
loff_t res = vfs_llseek(file, offset, origin);
retval = res;
if (res != (loff_t)retval)
retval = -EOVERFLOW; /* LFS: should only happen on 32 bit platforms */
}
fput_light(file, fput_needed);
bad:
return retval;
}
#ifdef __ARCH_WANT_SYS_LLSEEK
SYSCALL_DEFINE5(llseek, unsigned int, fd, unsigned long, offset_high,
unsigned long, offset_low, loff_t __user *, result,
unsigned int, origin)
{
int retval;
struct file * file;
loff_t offset;
int fput_needed;
retval = -EBADF;
file = fget_light(fd, &fput_needed);
if (!file)
goto bad;
retval = -EINVAL;
if (origin > SEEK_MAX)
goto out_putf;
offset = vfs_llseek(file, ((loff_t) offset_high << 32) | offset_low,
origin);
retval = (int)offset;
if (offset >= 0) {
retval = -EFAULT;
if (!copy_to_user(result, &offset, sizeof(offset)))
retval = 0;
}
out_putf:
fput_light(file, fput_needed);
bad:
return retval;
}
#endif
/*
* rw_verify_area doesn't like huge counts. We limit
* them to something that fits in "int" so that others
* won't have to do range checks all the time.
*/
int rw_verify_area(int read_write, struct file *file, loff_t *ppos, size_t count)
{
struct inode *inode;
loff_t pos;
int retval = -EINVAL;
inode = file->f_path.dentry->d_inode;
if (unlikely((ssize_t) count < 0))
return retval;
pos = *ppos;
if (unlikely(pos < 0)) {
if (!unsigned_offsets(file))
return retval;
if (count >= -pos) /* both values are in 0..LLONG_MAX */
return -EOVERFLOW;
} else if (unlikely((loff_t) (pos + count) < 0)) {
if (!unsigned_offsets(file))
return retval;
}
if (unlikely(inode->i_flock && mandatory_lock(inode))) {
retval = locks_mandatory_area(
read_write == READ ? FLOCK_VERIFY_READ : FLOCK_VERIFY_WRITE,
inode, file, pos, count);
if (retval < 0)
return retval;
}
retval = security_file_permission(file,
read_write == READ ? MAY_READ : MAY_WRITE);
if (retval)
return retval;
return count > MAX_RW_COUNT ? MAX_RW_COUNT : count;
}
static void wait_on_retry_sync_kiocb(struct kiocb *iocb)
{
set_current_state(TASK_UNINTERRUPTIBLE);
if (!kiocbIsKicked(iocb))
schedule();
else
kiocbClearKicked(iocb);
__set_current_state(TASK_RUNNING);
}
ssize_t do_sync_read(struct file *filp, char __user *buf, size_t len, loff_t *ppos)
{
struct iovec iov = { .iov_base = buf, .iov_len = len };
struct kiocb kiocb;
ssize_t ret;
init_sync_kiocb(&kiocb, filp);
kiocb.ki_pos = *ppos;
kiocb.ki_left = len;
kiocb.ki_nbytes = len;
for (;;) {
ret = filp->f_op->aio_read(&kiocb, &iov, 1, kiocb.ki_pos);
if (ret != -EIOCBRETRY)
break;
wait_on_retry_sync_kiocb(&kiocb);
}
if (-EIOCBQUEUED == ret)
ret = wait_on_sync_kiocb(&kiocb);
*ppos = kiocb.ki_pos;
return ret;
}
EXPORT_SYMBOL(do_sync_read);
ssize_t vfs_read(struct file *file, char __user *buf, size_t count, loff_t *pos)
{
ssize_t ret;
if (!(file->f_mode & FMODE_READ))
return -EBADF;
if (!file->f_op || (!file->f_op->read && !file->f_op->aio_read))
return -EINVAL;
if (unlikely(!access_ok(VERIFY_WRITE, buf, count)))
return -EFAULT;
ret = rw_verify_area(READ, file, pos, count);
if (ret >= 0) {
count = ret;
if (file->f_op->read)
ret = file->f_op->read(file, buf, count, pos);
else
ret = do_sync_read(file, buf, count, pos);
if (ret > 0) {
fsnotify_access(file);
add_rchar(current, ret);
}
inc_syscr(current);
}
return ret;
}
EXPORT_SYMBOL(vfs_read);
ssize_t do_sync_write(struct file *filp, const char __user *buf, size_t len, loff_t *ppos)
{
struct iovec iov = { .iov_base = (void __user *)buf, .iov_len = len };
struct kiocb kiocb;
ssize_t ret;
init_sync_kiocb(&kiocb, filp);
kiocb.ki_pos = *ppos;
kiocb.ki_left = len;
kiocb.ki_nbytes = len;
for (;;) {
ret = filp->f_op->aio_write(&kiocb, &iov, 1, kiocb.ki_pos);
if (ret != -EIOCBRETRY)
break;
wait_on_retry_sync_kiocb(&kiocb);
}
if (-EIOCBQUEUED == ret)
ret = wait_on_sync_kiocb(&kiocb);
*ppos = kiocb.ki_pos;
return ret;
}
EXPORT_SYMBOL(do_sync_write);
ssize_t vfs_write(struct file *file, const char __user *buf, size_t count, loff_t *pos)
{
ssize_t ret;
if (!(file->f_mode & FMODE_WRITE))
return -EBADF;
if (!file->f_op || (!file->f_op->write && !file->f_op->aio_write))
return -EINVAL;
if (unlikely(!access_ok(VERIFY_READ, buf, count)))
return -EFAULT;
ret = rw_verify_area(WRITE, file, pos, count);
if (ret >= 0) {
count = ret;
if (file->f_op->write)
ret = file->f_op->write(file, buf, count, pos);
else
ret = do_sync_write(file, buf, count, pos);
if (ret > 0) {
fsnotify_modify(file);
add_wchar(current, ret);
}
inc_syscw(current);
}
return ret;
}
EXPORT_SYMBOL(vfs_write);
static inline loff_t file_pos_read(struct file *file)
{
return file->f_pos;
}
static inline void file_pos_write(struct file *file, loff_t pos)
{
file->f_pos = pos;
}
SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count)
{
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
file = fget_light(fd, &fput_needed);
if (file) {
loff_t pos = file_pos_read(file);
ret = vfs_read(file, buf, count, &pos);
file_pos_write(file, pos);
fput_light(file, fput_needed);
}
return ret;
}
SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *, buf,
size_t, count)
{
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
file = fget_light(fd, &fput_needed);
if (file) {
loff_t pos = file_pos_read(file);
ret = vfs_write(file, buf, count, &pos);
file_pos_write(file, pos);
fput_light(file, fput_needed);
}
return ret;
}
SYSCALL_DEFINE(pread64)(unsigned int fd, char __user *buf,
size_t count, loff_t pos)
{
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
if (pos < 0)
return -EINVAL;
file = fget_light(fd, &fput_needed);
if (file) {
ret = -ESPIPE;
if (file->f_mode & FMODE_PREAD)
ret = vfs_read(file, buf, count, &pos);
fput_light(file, fput_needed);
}
return ret;
}
#ifdef CONFIG_HAVE_SYSCALL_WRAPPERS
asmlinkage long SyS_pread64(long fd, long buf, long count, loff_t pos)
{
return SYSC_pread64((unsigned int) fd, (char __user *) buf,
(size_t) count, pos);
}
SYSCALL_ALIAS(sys_pread64, SyS_pread64);
#endif
SYSCALL_DEFINE(pwrite64)(unsigned int fd, const char __user *buf,
size_t count, loff_t pos)
{
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
if (pos < 0)
return -EINVAL;
file = fget_light(fd, &fput_needed);
if (file) {
ret = -ESPIPE;
if (file->f_mode & FMODE_PWRITE)
ret = vfs_write(file, buf, count, &pos);
fput_light(file, fput_needed);
}
return ret;
}
#ifdef CONFIG_HAVE_SYSCALL_WRAPPERS
asmlinkage long SyS_pwrite64(long fd, long buf, long count, loff_t pos)
{
return SYSC_pwrite64((unsigned int) fd, (const char __user *) buf,
(size_t) count, pos);
}
SYSCALL_ALIAS(sys_pwrite64, SyS_pwrite64);
#endif
/*
* Reduce an iovec's length in-place. Return the resulting number of segments
*/
unsigned long iov_shorten(struct iovec *iov, unsigned long nr_segs, size_t to)
{
unsigned long seg = 0;
size_t len = 0;
while (seg < nr_segs) {
seg++;
if (len + iov->iov_len >= to) {
iov->iov_len = to - len;
break;
}
len += iov->iov_len;
iov++;
}
return seg;
}
EXPORT_SYMBOL(iov_shorten);
ssize_t do_sync_readv_writev(struct file *filp, const struct iovec *iov,
unsigned long nr_segs, size_t len, loff_t *ppos, iov_fn_t fn)
{
struct kiocb kiocb;
ssize_t ret;
init_sync_kiocb(&kiocb, filp);
kiocb.ki_pos = *ppos;
kiocb.ki_left = len;
kiocb.ki_nbytes = len;
for (;;) {
ret = fn(&kiocb, iov, nr_segs, kiocb.ki_pos);
if (ret != -EIOCBRETRY)
break;
wait_on_retry_sync_kiocb(&kiocb);
}
if (ret == -EIOCBQUEUED)
ret = wait_on_sync_kiocb(&kiocb);
*ppos = kiocb.ki_pos;
return ret;
}
/* Do it by hand, with file-ops */
ssize_t do_loop_readv_writev(struct file *filp, struct iovec *iov,
unsigned long nr_segs, loff_t *ppos, io_fn_t fn)
{
struct iovec *vector = iov;
ssize_t ret = 0;
while (nr_segs > 0) {
void __user *base;
size_t len;
ssize_t nr;
base = vector->iov_base;
len = vector->iov_len;
vector++;
nr_segs--;
nr = fn(filp, base, len, ppos);
if (nr < 0) {
if (!ret)
ret = nr;
break;
}
ret += nr;
if (nr != len)
break;
}
return ret;
}
/* A write operation does a read from user space and vice versa */
#define vrfy_dir(type) ((type) == READ ? VERIFY_WRITE : VERIFY_READ)
ssize_t rw_copy_check_uvector(int type, const struct iovec __user * uvector,
unsigned long nr_segs, unsigned long fast_segs,
struct iovec *fast_pointer,
struct iovec **ret_pointer,
int check_access)
{
unsigned long seg;
ssize_t ret;
struct iovec *iov = fast_pointer;
/*
* SuS says "The readv() function *may* fail if the iovcnt argument
* was less than or equal to 0, or greater than {IOV_MAX}. Linux has
* traditionally returned zero for zero segments, so...
*/
if (nr_segs == 0) {
ret = 0;
goto out;
}
/*
* First get the "struct iovec" from user memory and
* verify all the pointers
*/
if (nr_segs > UIO_MAXIOV) {
ret = -EINVAL;
goto out;
}
if (nr_segs > fast_segs) {
iov = kmalloc(nr_segs*sizeof(struct iovec), GFP_KERNEL);
if (iov == NULL) {
ret = -ENOMEM;
goto out;
}
}
if (copy_from_user(iov, uvector, nr_segs*sizeof(*uvector))) {
ret = -EFAULT;
goto out;
}
/*
* According to the Single Unix Specification we should return EINVAL
* if an element length is < 0 when cast to ssize_t or if the
* total length would overflow the ssize_t return value of the
* system call.
*
* Linux caps all read/write calls to MAX_RW_COUNT, and avoids the
* overflow case.
*/
ret = 0;
for (seg = 0; seg < nr_segs; seg++) {
void __user *buf = iov[seg].iov_base;
ssize_t len = (ssize_t)iov[seg].iov_len;
/* see if we we're about to use an invalid len or if
* it's about to overflow ssize_t */
if (len < 0) {
ret = -EINVAL;
goto out;
}
if (check_access
&& unlikely(!access_ok(vrfy_dir(type), buf, len))) {
ret = -EFAULT;
goto out;
}
if (len > MAX_RW_COUNT - ret) {
len = MAX_RW_COUNT - ret;
iov[seg].iov_len = len;
}
ret += len;
}
out:
*ret_pointer = iov;
return ret;
}
static ssize_t do_readv_writev(int type, struct file *file,
const struct iovec __user * uvector,
unsigned long nr_segs, loff_t *pos)
{
size_t tot_len;
struct iovec iovstack[UIO_FASTIOV];
struct iovec *iov = iovstack;
ssize_t ret;
io_fn_t fn;
iov_fn_t fnv;
if (!file->f_op) {
ret = -EINVAL;
goto out;
}
ret = rw_copy_check_uvector(type, uvector, nr_segs,
ARRAY_SIZE(iovstack), iovstack, &iov, 1);
if (ret <= 0)
goto out;
tot_len = ret;
ret = rw_verify_area(type, file, pos, tot_len);
if (ret < 0)
goto out;
fnv = NULL;
if (type == READ) {
fn = file->f_op->read;
fnv = file->f_op->aio_read;
} else {
fn = (io_fn_t)file->f_op->write;
fnv = file->f_op->aio_write;
}
if (fnv)
ret = do_sync_readv_writev(file, iov, nr_segs, tot_len,
pos, fnv);
else
ret = do_loop_readv_writev(file, iov, nr_segs, pos, fn);
out:
if (iov != iovstack)
kfree(iov);
if ((ret + (type == READ)) > 0) {
if (type == READ)
fsnotify_access(file);
else
fsnotify_modify(file);
}
return ret;
}
ssize_t vfs_readv(struct file *file, const struct iovec __user *vec,
unsigned long vlen, loff_t *pos)
{
if (!(file->f_mode & FMODE_READ))
return -EBADF;
if (!file->f_op || (!file->f_op->aio_read && !file->f_op->read))
return -EINVAL;
return do_readv_writev(READ, file, vec, vlen, pos);
}
EXPORT_SYMBOL(vfs_readv);
ssize_t vfs_writev(struct file *file, const struct iovec __user *vec,
unsigned long vlen, loff_t *pos)
{
if (!(file->f_mode & FMODE_WRITE))
return -EBADF;
if (!file->f_op || (!file->f_op->aio_write && !file->f_op->write))
return -EINVAL;
return do_readv_writev(WRITE, file, vec, vlen, pos);
}
EXPORT_SYMBOL(vfs_writev);
SYSCALL_DEFINE3(readv, unsigned long, fd, const struct iovec __user *, vec,
unsigned long, vlen)
{
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
file = fget_light(fd, &fput_needed);
if (file) {
loff_t pos = file_pos_read(file);
ret = vfs_readv(file, vec, vlen, &pos);
file_pos_write(file, pos);
fput_light(file, fput_needed);
}
if (ret > 0)
add_rchar(current, ret);
inc_syscr(current);
return ret;
}
SYSCALL_DEFINE3(writev, unsigned long, fd, const struct iovec __user *, vec,
unsigned long, vlen)
{
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
file = fget_light(fd, &fput_needed);
if (file) {
loff_t pos = file_pos_read(file);
ret = vfs_writev(file, vec, vlen, &pos);
file_pos_write(file, pos);
fput_light(file, fput_needed);
}
if (ret > 0)
add_wchar(current, ret);
inc_syscw(current);
return ret;
}
static inline loff_t pos_from_hilo(unsigned long high, unsigned long low)
{
#define HALF_LONG_BITS (BITS_PER_LONG / 2)
return (((loff_t)high << HALF_LONG_BITS) << HALF_LONG_BITS) | low;
}
SYSCALL_DEFINE5(preadv, unsigned long, fd, const struct iovec __user *, vec,
unsigned long, vlen, unsigned long, pos_l, unsigned long, pos_h)
{
loff_t pos = pos_from_hilo(pos_h, pos_l);
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
if (pos < 0)
return -EINVAL;
file = fget_light(fd, &fput_needed);
if (file) {
ret = -ESPIPE;
if (file->f_mode & FMODE_PREAD)
ret = vfs_readv(file, vec, vlen, &pos);
fput_light(file, fput_needed);
}
if (ret > 0)
add_rchar(current, ret);
inc_syscr(current);
return ret;
}
SYSCALL_DEFINE5(pwritev, unsigned long, fd, const struct iovec __user *, vec,
unsigned long, vlen, unsigned long, pos_l, unsigned long, pos_h)
{
loff_t pos = pos_from_hilo(pos_h, pos_l);
struct file *file;
ssize_t ret = -EBADF;
int fput_needed;
if (pos < 0)
return -EINVAL;
file = fget_light(fd, &fput_needed);
if (file) {
ret = -ESPIPE;
if (file->f_mode & FMODE_PWRITE)
ret = vfs_writev(file, vec, vlen, &pos);
fput_light(file, fput_needed);
}
if (ret > 0)
add_wchar(current, ret);
inc_syscw(current);
return ret;
}
static ssize_t do_sendfile(int out_fd, int in_fd, loff_t *ppos,
size_t count, loff_t max)
{
struct file * in_file, * out_file;
struct inode * in_inode, * out_inode;
loff_t pos;
ssize_t retval;
int fput_needed_in, fput_needed_out, fl;
/*
* Get input file, and verify that it is ok..
*/
retval = -EBADF;
in_file = fget_light(in_fd, &fput_needed_in);
if (!in_file)
goto out;
if (!(in_file->f_mode & FMODE_READ))
goto fput_in;
retval = -ESPIPE;
if (!ppos)
ppos = &in_file->f_pos;
else
if (!(in_file->f_mode & FMODE_PREAD))
goto fput_in;
retval = rw_verify_area(READ, in_file, ppos, count);
if (retval < 0)
goto fput_in;
count = retval;
/*
* Get output file, and verify that it is ok..
*/
retval = -EBADF;
out_file = fget_light(out_fd, &fput_needed_out);
if (!out_file)
goto fput_in;
if (!(out_file->f_mode & FMODE_WRITE))
goto fput_out;
retval = -EINVAL;
in_inode = in_file->f_path.dentry->d_inode;
out_inode = out_file->f_path.dentry->d_inode;
retval = rw_verify_area(WRITE, out_file, &out_file->f_pos, count);
if (retval < 0)
goto fput_out;
count = retval;
if (!max)
max = min(in_inode->i_sb->s_maxbytes, out_inode->i_sb->s_maxbytes);
pos = *ppos;
if (unlikely(pos + count > max)) {
retval = -EOVERFLOW;
if (pos >= max)
goto fput_out;
count = max - pos;
}
fl = 0;
#if 0
/*
* We need to debate whether we can enable this or not. The
* man page documents EAGAIN return for the output at least,
* and the application is arguably buggy if it doesn't expect
* EAGAIN on a non-blocking file descriptor.
*/
if (in_file->f_flags & O_NONBLOCK)
fl = SPLICE_F_NONBLOCK;
#endif
retval = do_splice_direct(in_file, ppos, out_file, count, fl);
if (retval > 0) {
add_rchar(current, retval);
add_wchar(current, retval);
}
inc_syscr(current);
inc_syscw(current);
if (*ppos > max)
retval = -EOVERFLOW;
fput_out:
fput_light(out_file, fput_needed_out);
fput_in:
fput_light(in_file, fput_needed_in);
out:
return retval;
}
SYSCALL_DEFINE4(sendfile, int, out_fd, int, in_fd, off_t __user *, offset, size_t, count)
{
loff_t pos;
off_t off;
ssize_t ret;
if (offset) {
if (unlikely(get_user(off, offset)))
return -EFAULT;
pos = off;
ret = do_sendfile(out_fd, in_fd, &pos, count, MAX_NON_LFS);
if (unlikely(put_user(pos, offset)))
return -EFAULT;
return ret;
}
return do_sendfile(out_fd, in_fd, NULL, count, 0);
}
SYSCALL_DEFINE4(sendfile64, int, out_fd, int, in_fd, loff_t __user *, offset, size_t, count)
{
loff_t pos;
ssize_t ret;
if (offset) {
if (unlikely(copy_from_user(&pos, offset, sizeof(loff_t))))
return -EFAULT;
ret = do_sendfile(out_fd, in_fd, &pos, count, 0);
if (unlikely(put_user(pos, offset)))
return -EFAULT;
return ret;
}
return do_sendfile(out_fd, in_fd, NULL, count, 0);
}
| gpl-2.0 |
nitrogen-os-devices/nitrogen_kernel_lge_hammerhead | arch/arm/mach-imx/mach-mx31moboard.c | 4732 | 16174 | /*
* Copyright (C) 2008 Valentin Longchamp, EPFL Mobots group
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/gfp.h>
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/moduleparam.h>
#include <linux/leds.h>
#include <linux/memory.h>
#include <linux/mtd/physmap.h>
#include <linux/mtd/partitions.h>
#include <linux/platform_device.h>
#include <linux/regulator/machine.h>
#include <linux/mfd/mc13783.h>
#include <linux/spi/spi.h>
#include <linux/types.h>
#include <linux/memblock.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/err.h>
#include <linux/input.h>
#include <linux/usb/otg.h>
#include <linux/usb/ulpi.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include <asm/mach/map.h>
#include <asm/memblock.h>
#include <mach/board-mx31moboard.h>
#include <mach/common.h>
#include <mach/hardware.h>
#include <mach/iomux-mx3.h>
#include <mach/ulpi.h>
#include "devices-imx31.h"
static unsigned int moboard_pins[] = {
/* UART0 */
MX31_PIN_TXD1__TXD1, MX31_PIN_RXD1__RXD1,
MX31_PIN_CTS1__GPIO2_7,
/* UART4 */
MX31_PIN_PC_RST__CTS5, MX31_PIN_PC_VS2__RTS5,
MX31_PIN_PC_BVD2__TXD5, MX31_PIN_PC_BVD1__RXD5,
/* I2C0 */
MX31_PIN_I2C_DAT__I2C1_SDA, MX31_PIN_I2C_CLK__I2C1_SCL,
/* I2C1 */
MX31_PIN_DCD_DTE1__I2C2_SDA, MX31_PIN_RI_DTE1__I2C2_SCL,
/* SDHC1 */
MX31_PIN_SD1_DATA3__SD1_DATA3, MX31_PIN_SD1_DATA2__SD1_DATA2,
MX31_PIN_SD1_DATA1__SD1_DATA1, MX31_PIN_SD1_DATA0__SD1_DATA0,
MX31_PIN_SD1_CLK__SD1_CLK, MX31_PIN_SD1_CMD__SD1_CMD,
MX31_PIN_ATA_CS0__GPIO3_26, MX31_PIN_ATA_CS1__GPIO3_27,
/* USB reset */
MX31_PIN_GPIO1_0__GPIO1_0,
/* USB OTG */
MX31_PIN_USBOTG_DATA0__USBOTG_DATA0,
MX31_PIN_USBOTG_DATA1__USBOTG_DATA1,
MX31_PIN_USBOTG_DATA2__USBOTG_DATA2,
MX31_PIN_USBOTG_DATA3__USBOTG_DATA3,
MX31_PIN_USBOTG_DATA4__USBOTG_DATA4,
MX31_PIN_USBOTG_DATA5__USBOTG_DATA5,
MX31_PIN_USBOTG_DATA6__USBOTG_DATA6,
MX31_PIN_USBOTG_DATA7__USBOTG_DATA7,
MX31_PIN_USBOTG_CLK__USBOTG_CLK, MX31_PIN_USBOTG_DIR__USBOTG_DIR,
MX31_PIN_USBOTG_NXT__USBOTG_NXT, MX31_PIN_USBOTG_STP__USBOTG_STP,
MX31_PIN_USB_OC__GPIO1_30,
/* USB H2 */
MX31_PIN_USBH2_DATA0__USBH2_DATA0,
MX31_PIN_USBH2_DATA1__USBH2_DATA1,
MX31_PIN_STXD3__USBH2_DATA2, MX31_PIN_SRXD3__USBH2_DATA3,
MX31_PIN_SCK3__USBH2_DATA4, MX31_PIN_SFS3__USBH2_DATA5,
MX31_PIN_STXD6__USBH2_DATA6, MX31_PIN_SRXD6__USBH2_DATA7,
MX31_PIN_USBH2_CLK__USBH2_CLK, MX31_PIN_USBH2_DIR__USBH2_DIR,
MX31_PIN_USBH2_NXT__USBH2_NXT, MX31_PIN_USBH2_STP__USBH2_STP,
MX31_PIN_SCK6__GPIO1_25,
/* LEDs */
MX31_PIN_SVEN0__GPIO2_0, MX31_PIN_STX0__GPIO2_1,
MX31_PIN_SRX0__GPIO2_2, MX31_PIN_SIMPD0__GPIO2_3,
/* SPI1 */
MX31_PIN_CSPI2_MOSI__MOSI, MX31_PIN_CSPI2_MISO__MISO,
MX31_PIN_CSPI2_SCLK__SCLK, MX31_PIN_CSPI2_SPI_RDY__SPI_RDY,
MX31_PIN_CSPI2_SS0__SS0, MX31_PIN_CSPI2_SS2__SS2,
/* Atlas IRQ */
MX31_PIN_GPIO1_3__GPIO1_3,
/* SPI2 */
MX31_PIN_CSPI3_MOSI__MOSI, MX31_PIN_CSPI3_MISO__MISO,
MX31_PIN_CSPI3_SCLK__SCLK, MX31_PIN_CSPI3_SPI_RDY__SPI_RDY,
MX31_PIN_CSPI2_SS1__CSPI3_SS1,
};
static struct physmap_flash_data mx31moboard_flash_data = {
.width = 2,
};
static struct resource mx31moboard_flash_resource = {
.start = 0xa0000000,
.end = 0xa1ffffff,
.flags = IORESOURCE_MEM,
};
static struct platform_device mx31moboard_flash = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &mx31moboard_flash_data,
},
.resource = &mx31moboard_flash_resource,
.num_resources = 1,
};
static int moboard_uart0_init(struct platform_device *pdev)
{
int ret = gpio_request(IOMUX_TO_GPIO(MX31_PIN_CTS1), "uart0-cts-hack");
if (ret)
return ret;
ret = gpio_direction_output(IOMUX_TO_GPIO(MX31_PIN_CTS1), 0);
if (ret)
gpio_free(IOMUX_TO_GPIO(MX31_PIN_CTS1));
return ret;
}
static void moboard_uart0_exit(struct platform_device *pdev)
{
gpio_free(IOMUX_TO_GPIO(MX31_PIN_CTS1));
}
static const struct imxuart_platform_data uart0_pdata __initconst = {
.init = moboard_uart0_init,
.exit = moboard_uart0_exit,
};
static const struct imxuart_platform_data uart4_pdata __initconst = {
.flags = IMXUART_HAVE_RTSCTS,
};
static const struct imxi2c_platform_data moboard_i2c0_data __initconst = {
.bitrate = 400000,
};
static const struct imxi2c_platform_data moboard_i2c1_data __initconst = {
.bitrate = 100000,
};
static int moboard_spi1_cs[] = {
MXC_SPI_CS(0),
MXC_SPI_CS(2),
};
static const struct spi_imx_master moboard_spi1_pdata __initconst = {
.chipselect = moboard_spi1_cs,
.num_chipselect = ARRAY_SIZE(moboard_spi1_cs),
};
static struct regulator_consumer_supply sdhc_consumers[] = {
{
.dev_name = "mxc-mmc.0",
.supply = "sdhc0_vcc",
},
{
.dev_name = "mxc-mmc.1",
.supply = "sdhc1_vcc",
},
};
static struct regulator_init_data sdhc_vreg_data = {
.constraints = {
.min_uV = 2700000,
.max_uV = 3000000,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE |
REGULATOR_CHANGE_MODE | REGULATOR_CHANGE_STATUS,
.valid_modes_mask = REGULATOR_MODE_NORMAL |
REGULATOR_MODE_FAST,
.always_on = 0,
.boot_on = 1,
},
.num_consumer_supplies = ARRAY_SIZE(sdhc_consumers),
.consumer_supplies = sdhc_consumers,
};
static struct regulator_consumer_supply cam_consumers[] = {
{
.dev_name = "mx3_camera.0",
.supply = "cam_vcc",
},
};
static struct regulator_init_data cam_vreg_data = {
.constraints = {
.min_uV = 2700000,
.max_uV = 3000000,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE |
REGULATOR_CHANGE_MODE | REGULATOR_CHANGE_STATUS,
.valid_modes_mask = REGULATOR_MODE_NORMAL |
REGULATOR_MODE_FAST,
.always_on = 0,
.boot_on = 1,
},
.num_consumer_supplies = ARRAY_SIZE(cam_consumers),
.consumer_supplies = cam_consumers,
};
static struct mc13xxx_regulator_init_data moboard_regulators[] = {
{
.id = MC13783_REG_VMMC1,
.init_data = &sdhc_vreg_data,
},
{
.id = MC13783_REG_VCAM,
.init_data = &cam_vreg_data,
},
};
static struct mc13xxx_led_platform_data moboard_led[] = {
{
.id = MC13783_LED_R1,
.name = "coreboard-led-4:red",
.max_current = 2,
},
{
.id = MC13783_LED_G1,
.name = "coreboard-led-4:green",
.max_current = 2,
},
{
.id = MC13783_LED_B1,
.name = "coreboard-led-4:blue",
.max_current = 2,
},
{
.id = MC13783_LED_R2,
.name = "coreboard-led-5:red",
.max_current = 3,
},
{
.id = MC13783_LED_G2,
.name = "coreboard-led-5:green",
.max_current = 3,
},
{
.id = MC13783_LED_B2,
.name = "coreboard-led-5:blue",
.max_current = 3,
},
};
static struct mc13xxx_leds_platform_data moboard_leds = {
.num_leds = ARRAY_SIZE(moboard_led),
.led = moboard_led,
.flags = MC13783_LED_SLEWLIMTC,
.abmode = MC13783_LED_AB_DISABLED,
.tc1_period = MC13783_LED_PERIOD_10MS,
.tc2_period = MC13783_LED_PERIOD_10MS,
};
static struct mc13xxx_buttons_platform_data moboard_buttons = {
.b1on_flags = MC13783_BUTTON_DBNC_750MS | MC13783_BUTTON_ENABLE |
MC13783_BUTTON_POL_INVERT,
.b1on_key = KEY_POWER,
};
static struct mc13xxx_platform_data moboard_pmic = {
.regulators = {
.regulators = moboard_regulators,
.num_regulators = ARRAY_SIZE(moboard_regulators),
},
.leds = &moboard_leds,
.buttons = &moboard_buttons,
.flags = MC13XXX_USE_RTC | MC13XXX_USE_ADC,
};
static struct spi_board_info moboard_spi_board_info[] __initdata = {
{
.modalias = "mc13783",
.irq = IOMUX_TO_IRQ(MX31_PIN_GPIO1_3),
.max_speed_hz = 300000,
.bus_num = 1,
.chip_select = 0,
.platform_data = &moboard_pmic,
.mode = SPI_CS_HIGH,
},
};
static int moboard_spi2_cs[] = {
MXC_SPI_CS(1),
};
static const struct spi_imx_master moboard_spi2_pdata __initconst = {
.chipselect = moboard_spi2_cs,
.num_chipselect = ARRAY_SIZE(moboard_spi2_cs),
};
#define SDHC1_CD IOMUX_TO_GPIO(MX31_PIN_ATA_CS0)
#define SDHC1_WP IOMUX_TO_GPIO(MX31_PIN_ATA_CS1)
static int moboard_sdhc1_get_ro(struct device *dev)
{
return !gpio_get_value(SDHC1_WP);
}
static int moboard_sdhc1_init(struct device *dev, irq_handler_t detect_irq,
void *data)
{
int ret;
ret = gpio_request(SDHC1_CD, "sdhc-detect");
if (ret)
return ret;
gpio_direction_input(SDHC1_CD);
ret = gpio_request(SDHC1_WP, "sdhc-wp");
if (ret)
goto err_gpio_free;
gpio_direction_input(SDHC1_WP);
ret = request_irq(gpio_to_irq(SDHC1_CD), detect_irq,
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
"sdhc1-card-detect", data);
if (ret)
goto err_gpio_free_2;
return 0;
err_gpio_free_2:
gpio_free(SDHC1_WP);
err_gpio_free:
gpio_free(SDHC1_CD);
return ret;
}
static void moboard_sdhc1_exit(struct device *dev, void *data)
{
free_irq(gpio_to_irq(SDHC1_CD), data);
gpio_free(SDHC1_WP);
gpio_free(SDHC1_CD);
}
static const struct imxmmc_platform_data sdhc1_pdata __initconst = {
.get_ro = moboard_sdhc1_get_ro,
.init = moboard_sdhc1_init,
.exit = moboard_sdhc1_exit,
};
/*
* this pin is dedicated for all mx31moboard systems, so we do it here
*/
#define USB_RESET_B IOMUX_TO_GPIO(MX31_PIN_GPIO1_0)
#define USB_PAD_CFG (PAD_CTL_DRV_MAX | PAD_CTL_SRE_FAST | PAD_CTL_HYS_CMOS | \
PAD_CTL_ODE_CMOS)
#define OTG_EN_B IOMUX_TO_GPIO(MX31_PIN_USB_OC)
#define USBH2_EN_B IOMUX_TO_GPIO(MX31_PIN_SCK6)
static void usb_xcvr_reset(void)
{
mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA0, USB_PAD_CFG | PAD_CTL_100K_PD);
mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA1, USB_PAD_CFG | PAD_CTL_100K_PD);
mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA2, USB_PAD_CFG | PAD_CTL_100K_PD);
mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA3, USB_PAD_CFG | PAD_CTL_100K_PD);
mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA4, USB_PAD_CFG | PAD_CTL_100K_PD);
mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA5, USB_PAD_CFG | PAD_CTL_100K_PD);
mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA6, USB_PAD_CFG | PAD_CTL_100K_PD);
mxc_iomux_set_pad(MX31_PIN_USBOTG_DATA7, USB_PAD_CFG | PAD_CTL_100K_PD);
mxc_iomux_set_pad(MX31_PIN_USBOTG_CLK, USB_PAD_CFG | PAD_CTL_100K_PU);
mxc_iomux_set_pad(MX31_PIN_USBOTG_DIR, USB_PAD_CFG | PAD_CTL_100K_PU);
mxc_iomux_set_pad(MX31_PIN_USBOTG_NXT, USB_PAD_CFG | PAD_CTL_100K_PU);
mxc_iomux_set_pad(MX31_PIN_USBOTG_STP, USB_PAD_CFG | PAD_CTL_100K_PU);
mxc_iomux_set_gpr(MUX_PGP_UH2, true);
mxc_iomux_set_pad(MX31_PIN_USBH2_CLK, USB_PAD_CFG | PAD_CTL_100K_PU);
mxc_iomux_set_pad(MX31_PIN_USBH2_DIR, USB_PAD_CFG | PAD_CTL_100K_PU);
mxc_iomux_set_pad(MX31_PIN_USBH2_NXT, USB_PAD_CFG | PAD_CTL_100K_PU);
mxc_iomux_set_pad(MX31_PIN_USBH2_STP, USB_PAD_CFG | PAD_CTL_100K_PU);
mxc_iomux_set_pad(MX31_PIN_USBH2_DATA0, USB_PAD_CFG | PAD_CTL_100K_PD);
mxc_iomux_set_pad(MX31_PIN_USBH2_DATA1, USB_PAD_CFG | PAD_CTL_100K_PD);
mxc_iomux_set_pad(MX31_PIN_SRXD6, USB_PAD_CFG | PAD_CTL_100K_PD);
mxc_iomux_set_pad(MX31_PIN_STXD6, USB_PAD_CFG | PAD_CTL_100K_PD);
mxc_iomux_set_pad(MX31_PIN_SFS3, USB_PAD_CFG | PAD_CTL_100K_PD);
mxc_iomux_set_pad(MX31_PIN_SCK3, USB_PAD_CFG | PAD_CTL_100K_PD);
mxc_iomux_set_pad(MX31_PIN_SRXD3, USB_PAD_CFG | PAD_CTL_100K_PD);
mxc_iomux_set_pad(MX31_PIN_STXD3, USB_PAD_CFG | PAD_CTL_100K_PD);
gpio_request(OTG_EN_B, "usb-udc-en");
gpio_direction_output(OTG_EN_B, 0);
gpio_request(USBH2_EN_B, "usbh2-en");
gpio_direction_output(USBH2_EN_B, 0);
gpio_request(USB_RESET_B, "usb-reset");
gpio_direction_output(USB_RESET_B, 0);
mdelay(1);
gpio_set_value(USB_RESET_B, 1);
mdelay(1);
}
static int moboard_usbh2_init_hw(struct platform_device *pdev)
{
return mx31_initialize_usb_hw(pdev->id, MXC_EHCI_POWER_PINS_ENABLED);
}
static struct mxc_usbh_platform_data usbh2_pdata __initdata = {
.init = moboard_usbh2_init_hw,
.portsc = MXC_EHCI_MODE_ULPI | MXC_EHCI_UTMI_8BIT,
};
static int __init moboard_usbh2_init(void)
{
struct platform_device *pdev;
usbh2_pdata.otg = imx_otg_ulpi_create(ULPI_OTG_DRVVBUS |
ULPI_OTG_DRVVBUS_EXT);
if (!usbh2_pdata.otg)
return -ENODEV;
pdev = imx31_add_mxc_ehci_hs(2, &usbh2_pdata);
if (IS_ERR(pdev))
return PTR_ERR(pdev);
return 0;
}
static const struct gpio_led mx31moboard_leds[] __initconst = {
{
.name = "coreboard-led-0:red:running",
.default_trigger = "heartbeat",
.gpio = IOMUX_TO_GPIO(MX31_PIN_SVEN0),
}, {
.name = "coreboard-led-1:red",
.gpio = IOMUX_TO_GPIO(MX31_PIN_STX0),
}, {
.name = "coreboard-led-2:red",
.gpio = IOMUX_TO_GPIO(MX31_PIN_SRX0),
}, {
.name = "coreboard-led-3:red",
.gpio = IOMUX_TO_GPIO(MX31_PIN_SIMPD0),
},
};
static const struct gpio_led_platform_data mx31moboard_led_pdata __initconst = {
.num_leds = ARRAY_SIZE(mx31moboard_leds),
.leds = mx31moboard_leds,
};
static const struct ipu_platform_data mx3_ipu_data __initconst = {
.irq_base = MXC_IPU_IRQ_START,
};
static struct platform_device *devices[] __initdata = {
&mx31moboard_flash,
};
static struct mx3_camera_pdata camera_pdata __initdata = {
.flags = MX3_CAMERA_DATAWIDTH_8 | MX3_CAMERA_DATAWIDTH_10,
.mclk_10khz = 4800,
};
static phys_addr_t mx3_camera_base __initdata;
#define MX3_CAMERA_BUF_SIZE SZ_4M
static int __init mx31moboard_init_cam(void)
{
int dma, ret = -ENOMEM;
struct platform_device *pdev;
imx31_add_ipu_core(&mx3_ipu_data);
pdev = imx31_alloc_mx3_camera(&camera_pdata);
if (IS_ERR(pdev))
return PTR_ERR(pdev);
dma = dma_declare_coherent_memory(&pdev->dev,
mx3_camera_base, mx3_camera_base,
MX3_CAMERA_BUF_SIZE,
DMA_MEMORY_MAP | DMA_MEMORY_EXCLUSIVE);
if (!(dma & DMA_MEMORY_MAP))
goto err;
ret = platform_device_add(pdev);
if (ret)
err:
platform_device_put(pdev);
return ret;
}
static void mx31moboard_poweroff(void)
{
struct clk *clk = clk_get_sys("imx2-wdt.0", NULL);
if (!IS_ERR(clk))
clk_prepare_enable(clk);
mxc_iomux_mode(MX31_PIN_WATCHDOG_RST__WATCHDOG_RST);
__raw_writew(1 << 6 | 1 << 2, MX31_IO_ADDRESS(MX31_WDOG_BASE_ADDR));
}
static int mx31moboard_baseboard;
core_param(mx31moboard_baseboard, mx31moboard_baseboard, int, 0444);
/*
* Board specific initialization.
*/
static void __init mx31moboard_init(void)
{
imx31_soc_init();
mxc_iomux_setup_multiple_pins(moboard_pins, ARRAY_SIZE(moboard_pins),
"moboard");
platform_add_devices(devices, ARRAY_SIZE(devices));
gpio_led_register_device(-1, &mx31moboard_led_pdata);
imx31_add_imx2_wdt(NULL);
imx31_add_imx_uart0(&uart0_pdata);
imx31_add_imx_uart4(&uart4_pdata);
imx31_add_imx_i2c0(&moboard_i2c0_data);
imx31_add_imx_i2c1(&moboard_i2c1_data);
imx31_add_spi_imx1(&moboard_spi1_pdata);
imx31_add_spi_imx2(&moboard_spi2_pdata);
gpio_request(IOMUX_TO_GPIO(MX31_PIN_GPIO1_3), "pmic-irq");
gpio_direction_input(IOMUX_TO_GPIO(MX31_PIN_GPIO1_3));
spi_register_board_info(moboard_spi_board_info,
ARRAY_SIZE(moboard_spi_board_info));
imx31_add_mxc_mmc(0, &sdhc1_pdata);
mx31moboard_init_cam();
usb_xcvr_reset();
moboard_usbh2_init();
pm_power_off = mx31moboard_poweroff;
switch (mx31moboard_baseboard) {
case MX31NOBOARD:
break;
case MX31DEVBOARD:
mx31moboard_devboard_init();
break;
case MX31MARXBOT:
mx31moboard_marxbot_init();
break;
case MX31SMARTBOT:
case MX31EYEBOT:
mx31moboard_smartbot_init(mx31moboard_baseboard);
break;
default:
printk(KERN_ERR "Illegal mx31moboard_baseboard type %d\n",
mx31moboard_baseboard);
}
}
static void __init mx31moboard_timer_init(void)
{
mx31_clocks_init(26000000);
}
struct sys_timer mx31moboard_timer = {
.init = mx31moboard_timer_init,
};
static void __init mx31moboard_reserve(void)
{
/* reserve 4 MiB for mx3-camera */
mx3_camera_base = arm_memblock_steal(MX3_CAMERA_BUF_SIZE,
MX3_CAMERA_BUF_SIZE);
}
MACHINE_START(MX31MOBOARD, "EPFL Mobots mx31moboard")
/* Maintainer: Philippe Retornaz, EPFL Mobots group */
.atag_offset = 0x100,
.reserve = mx31moboard_reserve,
.map_io = mx31_map_io,
.init_early = imx31_init_early,
.init_irq = mx31_init_irq,
.handle_irq = imx31_handle_irq,
.timer = &mx31moboard_timer,
.init_machine = mx31moboard_init,
.restart = mxc_restart,
MACHINE_END
| gpl-2.0 |
knych/linux-sunxi | drivers/rtc/rtc-nuc900.c | 4988 | 8231 | /*
* Copyright (c) 2008-2009 Nuvoton technology corporation.
*
* Wan ZongShun <mcuos.com@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation;version 2 of the License.
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/rtc.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/bcd.h>
/* RTC Control Registers */
#define REG_RTC_INIR 0x00
#define REG_RTC_AER 0x04
#define REG_RTC_FCR 0x08
#define REG_RTC_TLR 0x0C
#define REG_RTC_CLR 0x10
#define REG_RTC_TSSR 0x14
#define REG_RTC_DWR 0x18
#define REG_RTC_TAR 0x1C
#define REG_RTC_CAR 0x20
#define REG_RTC_LIR 0x24
#define REG_RTC_RIER 0x28
#define REG_RTC_RIIR 0x2C
#define REG_RTC_TTR 0x30
#define RTCSET 0x01
#define AERRWENB 0x10000
#define INIRRESET 0xa5eb1357
#define AERPOWERON 0xA965
#define AERPOWEROFF 0x0000
#define LEAPYEAR 0x0001
#define TICKENB 0x80
#define TICKINTENB 0x0002
#define ALARMINTENB 0x0001
#define MODE24 0x0001
struct nuc900_rtc {
int irq_num;
void __iomem *rtc_reg;
struct rtc_device *rtcdev;
};
struct nuc900_bcd_time {
int bcd_sec;
int bcd_min;
int bcd_hour;
int bcd_mday;
int bcd_mon;
int bcd_year;
};
static irqreturn_t nuc900_rtc_interrupt(int irq, void *_rtc)
{
struct nuc900_rtc *rtc = _rtc;
unsigned long events = 0, rtc_irq;
rtc_irq = __raw_readl(rtc->rtc_reg + REG_RTC_RIIR);
if (rtc_irq & ALARMINTENB) {
rtc_irq &= ~ALARMINTENB;
__raw_writel(rtc_irq, rtc->rtc_reg + REG_RTC_RIIR);
events |= RTC_AF | RTC_IRQF;
}
if (rtc_irq & TICKINTENB) {
rtc_irq &= ~TICKINTENB;
__raw_writel(rtc_irq, rtc->rtc_reg + REG_RTC_RIIR);
events |= RTC_UF | RTC_IRQF;
}
rtc_update_irq(rtc->rtcdev, 1, events);
return IRQ_HANDLED;
}
static int *check_rtc_access_enable(struct nuc900_rtc *nuc900_rtc)
{
unsigned int timeout = 0x1000;
__raw_writel(INIRRESET, nuc900_rtc->rtc_reg + REG_RTC_INIR);
mdelay(10);
__raw_writel(AERPOWERON, nuc900_rtc->rtc_reg + REG_RTC_AER);
while (!(__raw_readl(nuc900_rtc->rtc_reg + REG_RTC_AER) & AERRWENB)
&& timeout--)
mdelay(1);
if (!timeout)
return ERR_PTR(-EPERM);
return 0;
}
static int nuc900_rtc_bcd2bin(unsigned int timereg,
unsigned int calreg, struct rtc_time *tm)
{
tm->tm_mday = bcd2bin(calreg >> 0);
tm->tm_mon = bcd2bin(calreg >> 8);
tm->tm_year = bcd2bin(calreg >> 16) + 100;
tm->tm_sec = bcd2bin(timereg >> 0);
tm->tm_min = bcd2bin(timereg >> 8);
tm->tm_hour = bcd2bin(timereg >> 16);
return rtc_valid_tm(tm);
}
static void nuc900_rtc_bin2bcd(struct device *dev, struct rtc_time *settm,
struct nuc900_bcd_time *gettm)
{
gettm->bcd_mday = bin2bcd(settm->tm_mday) << 0;
gettm->bcd_mon = bin2bcd(settm->tm_mon) << 8;
if (settm->tm_year < 100) {
dev_warn(dev, "The year will be between 1970-1999, right?\n");
gettm->bcd_year = bin2bcd(settm->tm_year) << 16;
} else {
gettm->bcd_year = bin2bcd(settm->tm_year - 100) << 16;
}
gettm->bcd_sec = bin2bcd(settm->tm_sec) << 0;
gettm->bcd_min = bin2bcd(settm->tm_min) << 8;
gettm->bcd_hour = bin2bcd(settm->tm_hour) << 16;
}
static int nuc900_alarm_irq_enable(struct device *dev, unsigned int enabled)
{
struct nuc900_rtc *rtc = dev_get_drvdata(dev);
if (enabled)
__raw_writel(__raw_readl(rtc->rtc_reg + REG_RTC_RIER)|
(ALARMINTENB), rtc->rtc_reg + REG_RTC_RIER);
else
__raw_writel(__raw_readl(rtc->rtc_reg + REG_RTC_RIER)&
(~ALARMINTENB), rtc->rtc_reg + REG_RTC_RIER);
return 0;
}
static int nuc900_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
struct nuc900_rtc *rtc = dev_get_drvdata(dev);
unsigned int timeval, clrval;
timeval = __raw_readl(rtc->rtc_reg + REG_RTC_TLR);
clrval = __raw_readl(rtc->rtc_reg + REG_RTC_CLR);
return nuc900_rtc_bcd2bin(timeval, clrval, tm);
}
static int nuc900_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
struct nuc900_rtc *rtc = dev_get_drvdata(dev);
struct nuc900_bcd_time gettm;
unsigned long val;
int *err;
nuc900_rtc_bin2bcd(dev, tm, &gettm);
err = check_rtc_access_enable(rtc);
if (IS_ERR(err))
return PTR_ERR(err);
val = gettm.bcd_mday | gettm.bcd_mon | gettm.bcd_year;
__raw_writel(val, rtc->rtc_reg + REG_RTC_CLR);
val = gettm.bcd_sec | gettm.bcd_min | gettm.bcd_hour;
__raw_writel(val, rtc->rtc_reg + REG_RTC_TLR);
return 0;
}
static int nuc900_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct nuc900_rtc *rtc = dev_get_drvdata(dev);
unsigned int timeval, carval;
timeval = __raw_readl(rtc->rtc_reg + REG_RTC_TAR);
carval = __raw_readl(rtc->rtc_reg + REG_RTC_CAR);
return nuc900_rtc_bcd2bin(timeval, carval, &alrm->time);
}
static int nuc900_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct nuc900_rtc *rtc = dev_get_drvdata(dev);
struct nuc900_bcd_time tm;
unsigned long val;
int *err;
nuc900_rtc_bin2bcd(dev, &alrm->time, &tm);
err = check_rtc_access_enable(rtc);
if (IS_ERR(err))
return PTR_ERR(err);
val = tm.bcd_mday | tm.bcd_mon | tm.bcd_year;
__raw_writel(val, rtc->rtc_reg + REG_RTC_CAR);
val = tm.bcd_sec | tm.bcd_min | tm.bcd_hour;
__raw_writel(val, rtc->rtc_reg + REG_RTC_TAR);
return 0;
}
static struct rtc_class_ops nuc900_rtc_ops = {
.read_time = nuc900_rtc_read_time,
.set_time = nuc900_rtc_set_time,
.read_alarm = nuc900_rtc_read_alarm,
.set_alarm = nuc900_rtc_set_alarm,
.alarm_irq_enable = nuc900_alarm_irq_enable,
};
static int __devinit nuc900_rtc_probe(struct platform_device *pdev)
{
struct resource *res;
struct nuc900_rtc *nuc900_rtc;
int err = 0;
nuc900_rtc = kzalloc(sizeof(struct nuc900_rtc), GFP_KERNEL);
if (!nuc900_rtc) {
dev_err(&pdev->dev, "kzalloc nuc900_rtc failed\n");
return -ENOMEM;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "platform_get_resource failed\n");
err = -ENXIO;
goto fail1;
}
if (!request_mem_region(res->start, resource_size(res),
pdev->name)) {
dev_err(&pdev->dev, "request_mem_region failed\n");
err = -EBUSY;
goto fail1;
}
nuc900_rtc->rtc_reg = ioremap(res->start, resource_size(res));
if (!nuc900_rtc->rtc_reg) {
dev_err(&pdev->dev, "ioremap rtc_reg failed\n");
err = -ENOMEM;
goto fail2;
}
platform_set_drvdata(pdev, nuc900_rtc);
nuc900_rtc->rtcdev = rtc_device_register(pdev->name, &pdev->dev,
&nuc900_rtc_ops, THIS_MODULE);
if (IS_ERR(nuc900_rtc->rtcdev)) {
dev_err(&pdev->dev, "rtc device register failed\n");
err = PTR_ERR(nuc900_rtc->rtcdev);
goto fail3;
}
__raw_writel(__raw_readl(nuc900_rtc->rtc_reg + REG_RTC_TSSR) | MODE24,
nuc900_rtc->rtc_reg + REG_RTC_TSSR);
nuc900_rtc->irq_num = platform_get_irq(pdev, 0);
if (request_irq(nuc900_rtc->irq_num, nuc900_rtc_interrupt,
0, "nuc900rtc", nuc900_rtc)) {
dev_err(&pdev->dev, "NUC900 RTC request irq failed\n");
err = -EBUSY;
goto fail4;
}
return 0;
fail4: rtc_device_unregister(nuc900_rtc->rtcdev);
fail3: iounmap(nuc900_rtc->rtc_reg);
fail2: release_mem_region(res->start, resource_size(res));
fail1: kfree(nuc900_rtc);
return err;
}
static int __devexit nuc900_rtc_remove(struct platform_device *pdev)
{
struct nuc900_rtc *nuc900_rtc = platform_get_drvdata(pdev);
struct resource *res;
free_irq(nuc900_rtc->irq_num, nuc900_rtc);
rtc_device_unregister(nuc900_rtc->rtcdev);
iounmap(nuc900_rtc->rtc_reg);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(res->start, resource_size(res));
kfree(nuc900_rtc);
platform_set_drvdata(pdev, NULL);
return 0;
}
static struct platform_driver nuc900_rtc_driver = {
.remove = __devexit_p(nuc900_rtc_remove),
.driver = {
.name = "nuc900-rtc",
.owner = THIS_MODULE,
},
};
static int __init nuc900_rtc_init(void)
{
return platform_driver_probe(&nuc900_rtc_driver, nuc900_rtc_probe);
}
static void __exit nuc900_rtc_exit(void)
{
platform_driver_unregister(&nuc900_rtc_driver);
}
module_init(nuc900_rtc_init);
module_exit(nuc900_rtc_exit);
MODULE_AUTHOR("Wan ZongShun <mcuos.com@gmail.com>");
MODULE_DESCRIPTION("nuc910/nuc920 RTC driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:nuc900-rtc");
| gpl-2.0 |
tudorsirb/android_kernel_lge_jagnm | drivers/net/ethernet/ibm/emac/zmii.c | 4988 | 7626 | /*
* drivers/net/ethernet/ibm/emac/zmii.c
*
* Driver for PowerPC 4xx on-chip ethernet controller, ZMII bridge support.
*
* Copyright 2007 Benjamin Herrenschmidt, IBM Corp.
* <benh@kernel.crashing.org>
*
* Based on the arch/ppc version of the driver:
*
* Copyright (c) 2004, 2005 Zultys Technologies.
* Eugene Surovegin <eugene.surovegin@zultys.com> or <ebs@ebshome.net>
*
* Based on original work by
* Armin Kuster <akuster@mvista.com>
* Copyright 2001 MontaVista Softare Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/ethtool.h>
#include <asm/io.h>
#include "emac.h"
#include "core.h"
/* ZMIIx_FER */
#define ZMII_FER_MDI(idx) (0x80000000 >> ((idx) * 4))
#define ZMII_FER_MDI_ALL (ZMII_FER_MDI(0) | ZMII_FER_MDI(1) | \
ZMII_FER_MDI(2) | ZMII_FER_MDI(3))
#define ZMII_FER_SMII(idx) (0x40000000 >> ((idx) * 4))
#define ZMII_FER_RMII(idx) (0x20000000 >> ((idx) * 4))
#define ZMII_FER_MII(idx) (0x10000000 >> ((idx) * 4))
/* ZMIIx_SSR */
#define ZMII_SSR_SCI(idx) (0x40000000 >> ((idx) * 4))
#define ZMII_SSR_FSS(idx) (0x20000000 >> ((idx) * 4))
#define ZMII_SSR_SP(idx) (0x10000000 >> ((idx) * 4))
/* ZMII only supports MII, RMII and SMII
* we also support autodetection for backward compatibility
*/
static inline int zmii_valid_mode(int mode)
{
return mode == PHY_MODE_MII ||
mode == PHY_MODE_RMII ||
mode == PHY_MODE_SMII ||
mode == PHY_MODE_NA;
}
static inline const char *zmii_mode_name(int mode)
{
switch (mode) {
case PHY_MODE_MII:
return "MII";
case PHY_MODE_RMII:
return "RMII";
case PHY_MODE_SMII:
return "SMII";
default:
BUG();
}
}
static inline u32 zmii_mode_mask(int mode, int input)
{
switch (mode) {
case PHY_MODE_MII:
return ZMII_FER_MII(input);
case PHY_MODE_RMII:
return ZMII_FER_RMII(input);
case PHY_MODE_SMII:
return ZMII_FER_SMII(input);
default:
return 0;
}
}
int __devinit zmii_attach(struct platform_device *ofdev, int input, int *mode)
{
struct zmii_instance *dev = dev_get_drvdata(&ofdev->dev);
struct zmii_regs __iomem *p = dev->base;
ZMII_DBG(dev, "init(%d, %d)" NL, input, *mode);
if (!zmii_valid_mode(*mode)) {
/* Probably an EMAC connected to RGMII,
* but it still may need ZMII for MDIO so
* we don't fail here.
*/
dev->users++;
return 0;
}
mutex_lock(&dev->lock);
/* Autodetect ZMII mode if not specified.
* This is only for backward compatibility with the old driver.
* Please, always specify PHY mode in your board port to avoid
* any surprises.
*/
if (dev->mode == PHY_MODE_NA) {
if (*mode == PHY_MODE_NA) {
u32 r = dev->fer_save;
ZMII_DBG(dev, "autodetecting mode, FER = 0x%08x" NL, r);
if (r & (ZMII_FER_MII(0) | ZMII_FER_MII(1)))
dev->mode = PHY_MODE_MII;
else if (r & (ZMII_FER_RMII(0) | ZMII_FER_RMII(1)))
dev->mode = PHY_MODE_RMII;
else
dev->mode = PHY_MODE_SMII;
} else
dev->mode = *mode;
printk(KERN_NOTICE "%s: bridge in %s mode\n",
ofdev->dev.of_node->full_name,
zmii_mode_name(dev->mode));
} else {
/* All inputs must use the same mode */
if (*mode != PHY_MODE_NA && *mode != dev->mode) {
printk(KERN_ERR
"%s: invalid mode %d specified for input %d\n",
ofdev->dev.of_node->full_name, *mode, input);
mutex_unlock(&dev->lock);
return -EINVAL;
}
}
/* Report back correct PHY mode,
* it may be used during PHY initialization.
*/
*mode = dev->mode;
/* Enable this input */
out_be32(&p->fer, in_be32(&p->fer) | zmii_mode_mask(dev->mode, input));
++dev->users;
mutex_unlock(&dev->lock);
return 0;
}
void zmii_get_mdio(struct platform_device *ofdev, int input)
{
struct zmii_instance *dev = dev_get_drvdata(&ofdev->dev);
u32 fer;
ZMII_DBG2(dev, "get_mdio(%d)" NL, input);
mutex_lock(&dev->lock);
fer = in_be32(&dev->base->fer) & ~ZMII_FER_MDI_ALL;
out_be32(&dev->base->fer, fer | ZMII_FER_MDI(input));
}
void zmii_put_mdio(struct platform_device *ofdev, int input)
{
struct zmii_instance *dev = dev_get_drvdata(&ofdev->dev);
ZMII_DBG2(dev, "put_mdio(%d)" NL, input);
mutex_unlock(&dev->lock);
}
void zmii_set_speed(struct platform_device *ofdev, int input, int speed)
{
struct zmii_instance *dev = dev_get_drvdata(&ofdev->dev);
u32 ssr;
mutex_lock(&dev->lock);
ssr = in_be32(&dev->base->ssr);
ZMII_DBG(dev, "speed(%d, %d)" NL, input, speed);
if (speed == SPEED_100)
ssr |= ZMII_SSR_SP(input);
else
ssr &= ~ZMII_SSR_SP(input);
out_be32(&dev->base->ssr, ssr);
mutex_unlock(&dev->lock);
}
void zmii_detach(struct platform_device *ofdev, int input)
{
struct zmii_instance *dev = dev_get_drvdata(&ofdev->dev);
BUG_ON(!dev || dev->users == 0);
mutex_lock(&dev->lock);
ZMII_DBG(dev, "detach(%d)" NL, input);
/* Disable this input */
out_be32(&dev->base->fer,
in_be32(&dev->base->fer) & ~zmii_mode_mask(dev->mode, input));
--dev->users;
mutex_unlock(&dev->lock);
}
int zmii_get_regs_len(struct platform_device *ofdev)
{
return sizeof(struct emac_ethtool_regs_subhdr) +
sizeof(struct zmii_regs);
}
void *zmii_dump_regs(struct platform_device *ofdev, void *buf)
{
struct zmii_instance *dev = dev_get_drvdata(&ofdev->dev);
struct emac_ethtool_regs_subhdr *hdr = buf;
struct zmii_regs *regs = (struct zmii_regs *)(hdr + 1);
hdr->version = 0;
hdr->index = 0; /* for now, are there chips with more than one
* zmii ? if yes, then we'll add a cell_index
* like we do for emac
*/
memcpy_fromio(regs, dev->base, sizeof(struct zmii_regs));
return regs + 1;
}
static int __devinit zmii_probe(struct platform_device *ofdev)
{
struct device_node *np = ofdev->dev.of_node;
struct zmii_instance *dev;
struct resource regs;
int rc;
rc = -ENOMEM;
dev = kzalloc(sizeof(struct zmii_instance), GFP_KERNEL);
if (dev == NULL)
goto err_gone;
mutex_init(&dev->lock);
dev->ofdev = ofdev;
dev->mode = PHY_MODE_NA;
rc = -ENXIO;
if (of_address_to_resource(np, 0, ®s)) {
printk(KERN_ERR "%s: Can't get registers address\n",
np->full_name);
goto err_free;
}
rc = -ENOMEM;
dev->base = (struct zmii_regs __iomem *)ioremap(regs.start,
sizeof(struct zmii_regs));
if (dev->base == NULL) {
printk(KERN_ERR "%s: Can't map device registers!\n",
np->full_name);
goto err_free;
}
/* We may need FER value for autodetection later */
dev->fer_save = in_be32(&dev->base->fer);
/* Disable all inputs by default */
out_be32(&dev->base->fer, 0);
printk(KERN_INFO
"ZMII %s initialized\n", ofdev->dev.of_node->full_name);
wmb();
dev_set_drvdata(&ofdev->dev, dev);
return 0;
err_free:
kfree(dev);
err_gone:
return rc;
}
static int __devexit zmii_remove(struct platform_device *ofdev)
{
struct zmii_instance *dev = dev_get_drvdata(&ofdev->dev);
dev_set_drvdata(&ofdev->dev, NULL);
WARN_ON(dev->users != 0);
iounmap(dev->base);
kfree(dev);
return 0;
}
static struct of_device_id zmii_match[] =
{
{
.compatible = "ibm,zmii",
},
/* For backward compat with old DT */
{
.type = "emac-zmii",
},
{},
};
static struct platform_driver zmii_driver = {
.driver = {
.name = "emac-zmii",
.owner = THIS_MODULE,
.of_match_table = zmii_match,
},
.probe = zmii_probe,
.remove = zmii_remove,
};
int __init zmii_init(void)
{
return platform_driver_register(&zmii_driver);
}
void zmii_exit(void)
{
platform_driver_unregister(&zmii_driver);
}
| gpl-2.0 |
Cheshkin/sprout_cm11_mt6589_kernel | drivers/net/ethernet/ibm/emac/tah.c | 4988 | 4062 | /*
* drivers/net/ethernet/ibm/emac/tah.c
*
* Driver for PowerPC 4xx on-chip ethernet controller, TAH support.
*
* Copyright 2007 Benjamin Herrenschmidt, IBM Corp.
* <benh@kernel.crashing.org>
*
* Based on the arch/ppc version of the driver:
*
* Copyright 2004 MontaVista Software, Inc.
* Matt Porter <mporter@kernel.crashing.org>
*
* Copyright (c) 2005 Eugene Surovegin <ebs@ebshome.net>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <asm/io.h>
#include "emac.h"
#include "core.h"
int __devinit tah_attach(struct platform_device *ofdev, int channel)
{
struct tah_instance *dev = dev_get_drvdata(&ofdev->dev);
mutex_lock(&dev->lock);
/* Reset has been done at probe() time... nothing else to do for now */
++dev->users;
mutex_unlock(&dev->lock);
return 0;
}
void tah_detach(struct platform_device *ofdev, int channel)
{
struct tah_instance *dev = dev_get_drvdata(&ofdev->dev);
mutex_lock(&dev->lock);
--dev->users;
mutex_unlock(&dev->lock);
}
void tah_reset(struct platform_device *ofdev)
{
struct tah_instance *dev = dev_get_drvdata(&ofdev->dev);
struct tah_regs __iomem *p = dev->base;
int n;
/* Reset TAH */
out_be32(&p->mr, TAH_MR_SR);
n = 100;
while ((in_be32(&p->mr) & TAH_MR_SR) && n)
--n;
if (unlikely(!n))
printk(KERN_ERR "%s: reset timeout\n",
ofdev->dev.of_node->full_name);
/* 10KB TAH TX FIFO accommodates the max MTU of 9000 */
out_be32(&p->mr,
TAH_MR_CVR | TAH_MR_ST_768 | TAH_MR_TFS_10KB | TAH_MR_DTFP |
TAH_MR_DIG);
}
int tah_get_regs_len(struct platform_device *ofdev)
{
return sizeof(struct emac_ethtool_regs_subhdr) +
sizeof(struct tah_regs);
}
void *tah_dump_regs(struct platform_device *ofdev, void *buf)
{
struct tah_instance *dev = dev_get_drvdata(&ofdev->dev);
struct emac_ethtool_regs_subhdr *hdr = buf;
struct tah_regs *regs = (struct tah_regs *)(hdr + 1);
hdr->version = 0;
hdr->index = 0; /* for now, are there chips with more than one
* zmii ? if yes, then we'll add a cell_index
* like we do for emac
*/
memcpy_fromio(regs, dev->base, sizeof(struct tah_regs));
return regs + 1;
}
static int __devinit tah_probe(struct platform_device *ofdev)
{
struct device_node *np = ofdev->dev.of_node;
struct tah_instance *dev;
struct resource regs;
int rc;
rc = -ENOMEM;
dev = kzalloc(sizeof(struct tah_instance), GFP_KERNEL);
if (dev == NULL)
goto err_gone;
mutex_init(&dev->lock);
dev->ofdev = ofdev;
rc = -ENXIO;
if (of_address_to_resource(np, 0, ®s)) {
printk(KERN_ERR "%s: Can't get registers address\n",
np->full_name);
goto err_free;
}
rc = -ENOMEM;
dev->base = (struct tah_regs __iomem *)ioremap(regs.start,
sizeof(struct tah_regs));
if (dev->base == NULL) {
printk(KERN_ERR "%s: Can't map device registers!\n",
np->full_name);
goto err_free;
}
dev_set_drvdata(&ofdev->dev, dev);
/* Initialize TAH and enable IPv4 checksum verification, no TSO yet */
tah_reset(ofdev);
printk(KERN_INFO
"TAH %s initialized\n", ofdev->dev.of_node->full_name);
wmb();
return 0;
err_free:
kfree(dev);
err_gone:
return rc;
}
static int __devexit tah_remove(struct platform_device *ofdev)
{
struct tah_instance *dev = dev_get_drvdata(&ofdev->dev);
dev_set_drvdata(&ofdev->dev, NULL);
WARN_ON(dev->users != 0);
iounmap(dev->base);
kfree(dev);
return 0;
}
static struct of_device_id tah_match[] =
{
{
.compatible = "ibm,tah",
},
/* For backward compat with old DT */
{
.type = "tah",
},
{},
};
static struct platform_driver tah_driver = {
.driver = {
.name = "emac-tah",
.owner = THIS_MODULE,
.of_match_table = tah_match,
},
.probe = tah_probe,
.remove = tah_remove,
};
int __init tah_init(void)
{
return platform_driver_register(&tah_driver);
}
void tah_exit(void)
{
platform_driver_unregister(&tah_driver);
}
| gpl-2.0 |
zcop/android_kernel_lge_d1lsk | drivers/gpu/drm/nouveau/nouveau_volt.c | 5500 | 6245 | /*
* 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_pm.h"
#include "nouveau_gpio.h"
static const enum dcb_gpio_tag vidtag[] = { 0x04, 0x05, 0x06, 0x1a, 0x73 };
static int nr_vidtag = sizeof(vidtag) / sizeof(vidtag[0]);
int
nouveau_voltage_gpio_get(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_pm_voltage *volt = &dev_priv->engine.pm.voltage;
u8 vid = 0;
int i;
for (i = 0; i < nr_vidtag; i++) {
if (!(volt->vid_mask & (1 << i)))
continue;
vid |= nouveau_gpio_func_get(dev, vidtag[i]) << i;
}
return nouveau_volt_lvl_lookup(dev, vid);
}
int
nouveau_voltage_gpio_set(struct drm_device *dev, int voltage)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_pm_voltage *volt = &dev_priv->engine.pm.voltage;
int vid, i;
vid = nouveau_volt_vid_lookup(dev, voltage);
if (vid < 0)
return vid;
for (i = 0; i < nr_vidtag; i++) {
if (!(volt->vid_mask & (1 << i)))
continue;
nouveau_gpio_func_set(dev, vidtag[i], !!(vid & (1 << i)));
}
return 0;
}
int
nouveau_volt_vid_lookup(struct drm_device *dev, int voltage)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_pm_voltage *volt = &dev_priv->engine.pm.voltage;
int i;
for (i = 0; i < volt->nr_level; i++) {
if (volt->level[i].voltage == voltage)
return volt->level[i].vid;
}
return -ENOENT;
}
int
nouveau_volt_lvl_lookup(struct drm_device *dev, int vid)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_pm_voltage *volt = &dev_priv->engine.pm.voltage;
int i;
for (i = 0; i < volt->nr_level; i++) {
if (volt->level[i].vid == vid)
return volt->level[i].voltage;
}
return -ENOENT;
}
void
nouveau_volt_init(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_pm_engine *pm = &dev_priv->engine.pm;
struct nouveau_pm_voltage *voltage = &pm->voltage;
struct nvbios *bios = &dev_priv->vbios;
struct bit_entry P;
u8 *volt = NULL, *entry;
int i, headerlen, recordlen, entries, vidmask, vidshift;
if (bios->type == NVBIOS_BIT) {
if (bit_table(dev, 'P', &P))
return;
if (P.version == 1)
volt = ROMPTR(dev, P.data[16]);
else
if (P.version == 2)
volt = ROMPTR(dev, P.data[12]);
else {
NV_WARN(dev, "unknown volt for BIT P %d\n", P.version);
}
} else {
if (bios->data[bios->offset + 6] < 0x27) {
NV_DEBUG(dev, "BMP version too old for voltage\n");
return;
}
volt = ROMPTR(dev, bios->data[bios->offset + 0x98]);
}
if (!volt) {
NV_DEBUG(dev, "voltage table pointer invalid\n");
return;
}
switch (volt[0]) {
case 0x10:
case 0x11:
case 0x12:
headerlen = 5;
recordlen = volt[1];
entries = volt[2];
vidshift = 0;
vidmask = volt[4];
break;
case 0x20:
headerlen = volt[1];
recordlen = volt[3];
entries = volt[2];
vidshift = 0; /* could be vidshift like 0x30? */
vidmask = volt[5];
break;
case 0x30:
headerlen = volt[1];
recordlen = volt[2];
entries = volt[3];
vidmask = volt[4];
/* no longer certain what volt[5] is, if it's related to
* the vid shift then it's definitely not a function of
* how many bits are set.
*
* after looking at a number of nva3+ vbios images, they
* all seem likely to have a static shift of 2.. lets
* go with that for now until proven otherwise.
*/
vidshift = 2;
break;
case 0x40:
headerlen = volt[1];
recordlen = volt[2];
entries = volt[3]; /* not a clue what the entries are for.. */
vidmask = volt[11]; /* guess.. */
vidshift = 0;
break;
default:
NV_WARN(dev, "voltage table 0x%02x unknown\n", volt[0]);
return;
}
/* validate vid mask */
voltage->vid_mask = vidmask;
if (!voltage->vid_mask)
return;
i = 0;
while (vidmask) {
if (i > nr_vidtag) {
NV_DEBUG(dev, "vid bit %d unknown\n", i);
return;
}
if (!nouveau_gpio_func_valid(dev, vidtag[i])) {
NV_DEBUG(dev, "vid bit %d has no gpio tag\n", i);
return;
}
vidmask >>= 1;
i++;
}
/* parse vbios entries into common format */
voltage->version = volt[0];
if (voltage->version < 0x40) {
voltage->nr_level = entries;
voltage->level =
kcalloc(entries, sizeof(*voltage->level), GFP_KERNEL);
if (!voltage->level)
return;
entry = volt + headerlen;
for (i = 0; i < entries; i++, entry += recordlen) {
voltage->level[i].voltage = entry[0] * 10000;
voltage->level[i].vid = entry[1] >> vidshift;
}
} else {
u32 volt_uv = ROM32(volt[4]);
s16 step_uv = ROM16(volt[8]);
u8 vid;
voltage->nr_level = voltage->vid_mask + 1;
voltage->level = kcalloc(voltage->nr_level,
sizeof(*voltage->level), GFP_KERNEL);
if (!voltage->level)
return;
for (vid = 0; vid <= voltage->vid_mask; vid++) {
voltage->level[vid].voltage = volt_uv;
voltage->level[vid].vid = vid;
volt_uv += step_uv;
}
}
voltage->supported = true;
}
void
nouveau_volt_fini(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_pm_voltage *volt = &dev_priv->engine.pm.voltage;
kfree(volt->level);
}
| gpl-2.0 |
TheNameIsNigel/kernel_common | drivers/isdn/hardware/eicon/os_4bri.c | 9596 | 28951 | /* $Id: os_4bri.c,v 1.28.4.4 2005/02/11 19:40:25 armin Exp $ */
#include "platform.h"
#include "debuglib.h"
#include "cardtype.h"
#include "pc.h"
#include "pr_pc.h"
#include "di_defs.h"
#include "dsp_defs.h"
#include "di.h"
#include "io.h"
#include "xdi_msg.h"
#include "xdi_adapter.h"
#include "os_4bri.h"
#include "diva_pci.h"
#include "mi_pc.h"
#include "dsrv4bri.h"
#include "helpers.h"
static void *diva_xdiLoadFileFile = NULL;
static dword diva_xdiLoadFileLength = 0;
/*
** IMPORTS
*/
extern void prepare_qBri_functions(PISDN_ADAPTER IoAdapter);
extern void prepare_qBri2_functions(PISDN_ADAPTER IoAdapter);
extern void diva_xdi_display_adapter_features(int card);
extern void diva_add_slave_adapter(diva_os_xdi_adapter_t *a);
extern int qBri_FPGA_download(PISDN_ADAPTER IoAdapter);
extern void start_qBri_hardware(PISDN_ADAPTER IoAdapter);
extern int diva_card_read_xlog(diva_os_xdi_adapter_t *a);
/*
** LOCALS
*/
static unsigned long _4bri_bar_length[4] = {
0x100,
0x100, /* I/O */
MQ_MEMORY_SIZE,
0x2000
};
static unsigned long _4bri_v2_bar_length[4] = {
0x100,
0x100, /* I/O */
MQ2_MEMORY_SIZE,
0x10000
};
static unsigned long _4bri_v2_bri_bar_length[4] = {
0x100,
0x100, /* I/O */
BRI2_MEMORY_SIZE,
0x10000
};
static int diva_4bri_cleanup_adapter(diva_os_xdi_adapter_t *a);
static int _4bri_get_serial_number(diva_os_xdi_adapter_t *a);
static int diva_4bri_cmd_card_proc(struct _diva_os_xdi_adapter *a,
diva_xdi_um_cfg_cmd_t *cmd,
int length);
static int diva_4bri_cleanup_slave_adapters(diva_os_xdi_adapter_t *a);
static int diva_4bri_write_fpga_image(diva_os_xdi_adapter_t *a,
byte *data, dword length);
static int diva_4bri_reset_adapter(PISDN_ADAPTER IoAdapter);
static int diva_4bri_write_sdram_block(PISDN_ADAPTER IoAdapter,
dword address,
const byte *data,
dword length, dword limit);
static int diva_4bri_start_adapter(PISDN_ADAPTER IoAdapter,
dword start_address, dword features);
static int check_qBri_interrupt(PISDN_ADAPTER IoAdapter);
static int diva_4bri_stop_adapter(diva_os_xdi_adapter_t *a);
static int _4bri_is_rev_2_card(int card_ordinal)
{
switch (card_ordinal) {
case CARDTYPE_DIVASRV_Q_8M_V2_PCI:
case CARDTYPE_DIVASRV_VOICE_Q_8M_V2_PCI:
case CARDTYPE_DIVASRV_B_2M_V2_PCI:
case CARDTYPE_DIVASRV_B_2F_PCI:
case CARDTYPE_DIVASRV_VOICE_B_2M_V2_PCI:
return (1);
}
return (0);
}
static int _4bri_is_rev_2_bri_card(int card_ordinal)
{
switch (card_ordinal) {
case CARDTYPE_DIVASRV_B_2M_V2_PCI:
case CARDTYPE_DIVASRV_B_2F_PCI:
case CARDTYPE_DIVASRV_VOICE_B_2M_V2_PCI:
return (1);
}
return (0);
}
static void diva_4bri_set_addresses(diva_os_xdi_adapter_t *a)
{
dword offset = a->resources.pci.qoffset;
dword c_offset = offset * a->xdi_adapter.ControllerNumber;
a->resources.pci.mem_type_id[MEM_TYPE_RAM] = 2;
a->resources.pci.mem_type_id[MEM_TYPE_ADDRESS] = 2;
a->resources.pci.mem_type_id[MEM_TYPE_CONTROL] = 2;
a->resources.pci.mem_type_id[MEM_TYPE_RESET] = 0;
a->resources.pci.mem_type_id[MEM_TYPE_CTLREG] = 3;
a->resources.pci.mem_type_id[MEM_TYPE_PROM] = 0;
/*
Set up hardware related pointers
*/
a->xdi_adapter.Address = a->resources.pci.addr[2]; /* BAR2 SDRAM */
a->xdi_adapter.Address += c_offset;
a->xdi_adapter.Control = a->resources.pci.addr[2]; /* BAR2 SDRAM */
a->xdi_adapter.ram = a->resources.pci.addr[2]; /* BAR2 SDRAM */
a->xdi_adapter.ram += c_offset + (offset - MQ_SHARED_RAM_SIZE);
a->xdi_adapter.reset = a->resources.pci.addr[0]; /* BAR0 CONFIG */
/*
ctlReg contains the register address for the MIPS CPU reset control
*/
a->xdi_adapter.ctlReg = a->resources.pci.addr[3]; /* BAR3 CNTRL */
/*
prom contains the register address for FPGA and EEPROM programming
*/
a->xdi_adapter.prom = &a->xdi_adapter.reset[0x6E];
}
/*
** BAR0 - MEM - 0x100 - CONFIG MEM
** BAR1 - I/O - 0x100 - UNUSED
** BAR2 - MEM - MQ_MEMORY_SIZE (MQ2_MEMORY_SIZE on Rev.2) - SDRAM
** BAR3 - MEM - 0x2000 (0x10000 on Rev.2) - CNTRL
**
** Called by master adapter, that will initialize and add slave adapters
*/
int diva_4bri_init_card(diva_os_xdi_adapter_t *a)
{
int bar, i;
byte __iomem *p;
PADAPTER_LIST_ENTRY quadro_list;
diva_os_xdi_adapter_t *diva_current;
diva_os_xdi_adapter_t *adapter_list[4];
PISDN_ADAPTER Slave;
unsigned long bar_length[ARRAY_SIZE(_4bri_bar_length)];
int v2 = _4bri_is_rev_2_card(a->CardOrdinal);
int tasks = _4bri_is_rev_2_bri_card(a->CardOrdinal) ? 1 : MQ_INSTANCE_COUNT;
int factor = (tasks == 1) ? 1 : 2;
if (v2) {
if (_4bri_is_rev_2_bri_card(a->CardOrdinal)) {
memcpy(bar_length, _4bri_v2_bri_bar_length,
sizeof(bar_length));
} else {
memcpy(bar_length, _4bri_v2_bar_length,
sizeof(bar_length));
}
} else {
memcpy(bar_length, _4bri_bar_length, sizeof(bar_length));
}
DBG_TRC(("SDRAM_LENGTH=%08x, tasks=%d, factor=%d",
bar_length[2], tasks, factor))
/*
Get Serial Number
The serial number of 4BRI is accessible in accordance with PCI spec
via command register located in configuration space, also we do not
have to map any BAR before we can access it
*/
if (!_4bri_get_serial_number(a)) {
DBG_ERR(("A: 4BRI can't get Serial Number"))
diva_4bri_cleanup_adapter(a);
return (-1);
}
/*
Set properties
*/
a->xdi_adapter.Properties = CardProperties[a->CardOrdinal];
DBG_LOG(("Load %s, SN:%ld, bus:%02x, func:%02x",
a->xdi_adapter.Properties.Name,
a->xdi_adapter.serialNo,
a->resources.pci.bus, a->resources.pci.func))
/*
First initialization step: get and check hardware resoures.
Do not map resources and do not access card at this step
*/
for (bar = 0; bar < 4; bar++) {
a->resources.pci.bar[bar] =
divasa_get_pci_bar(a->resources.pci.bus,
a->resources.pci.func, bar,
a->resources.pci.hdev);
if (!a->resources.pci.bar[bar]
|| (a->resources.pci.bar[bar] == 0xFFFFFFF0)) {
DBG_ERR(
("A: invalid bar[%d]=%08x", bar,
a->resources.pci.bar[bar]))
return (-1);
}
}
a->resources.pci.irq =
(byte) divasa_get_pci_irq(a->resources.pci.bus,
a->resources.pci.func,
a->resources.pci.hdev);
if (!a->resources.pci.irq) {
DBG_ERR(("A: invalid irq"));
return (-1);
}
a->xdi_adapter.sdram_bar = a->resources.pci.bar[2];
/*
Map all MEMORY BAR's
*/
for (bar = 0; bar < 4; bar++) {
if (bar != 1) { /* ignore I/O */
a->resources.pci.addr[bar] =
divasa_remap_pci_bar(a, bar, a->resources.pci.bar[bar],
bar_length[bar]);
if (!a->resources.pci.addr[bar]) {
DBG_ERR(("A: 4BRI: can't map bar[%d]", bar))
diva_4bri_cleanup_adapter(a);
return (-1);
}
}
}
/*
Register I/O port
*/
sprintf(&a->port_name[0], "DIVA 4BRI %ld", (long) a->xdi_adapter.serialNo);
if (diva_os_register_io_port(a, 1, a->resources.pci.bar[1],
bar_length[1], &a->port_name[0], 1)) {
DBG_ERR(("A: 4BRI: can't register bar[1]"))
diva_4bri_cleanup_adapter(a);
return (-1);
}
a->resources.pci.addr[1] =
(void *) (unsigned long) a->resources.pci.bar[1];
/*
Set cleanup pointer for base adapter only, so slave adapter
will be unable to get cleanup
*/
a->interface.cleanup_adapter_proc = diva_4bri_cleanup_adapter;
/*
Create slave adapters
*/
if (tasks > 1) {
if (!(a->slave_adapters[0] =
(diva_os_xdi_adapter_t *) diva_os_malloc(0, sizeof(*a))))
{
diva_4bri_cleanup_adapter(a);
return (-1);
}
if (!(a->slave_adapters[1] =
(diva_os_xdi_adapter_t *) diva_os_malloc(0, sizeof(*a))))
{
diva_os_free(0, a->slave_adapters[0]);
a->slave_adapters[0] = NULL;
diva_4bri_cleanup_adapter(a);
return (-1);
}
if (!(a->slave_adapters[2] =
(diva_os_xdi_adapter_t *) diva_os_malloc(0, sizeof(*a))))
{
diva_os_free(0, a->slave_adapters[0]);
diva_os_free(0, a->slave_adapters[1]);
a->slave_adapters[0] = NULL;
a->slave_adapters[1] = NULL;
diva_4bri_cleanup_adapter(a);
return (-1);
}
memset(a->slave_adapters[0], 0x00, sizeof(*a));
memset(a->slave_adapters[1], 0x00, sizeof(*a));
memset(a->slave_adapters[2], 0x00, sizeof(*a));
}
adapter_list[0] = a;
adapter_list[1] = a->slave_adapters[0];
adapter_list[2] = a->slave_adapters[1];
adapter_list[3] = a->slave_adapters[2];
/*
Allocate slave list
*/
quadro_list =
(PADAPTER_LIST_ENTRY) diva_os_malloc(0, sizeof(*quadro_list));
if (!(a->slave_list = quadro_list)) {
for (i = 0; i < (tasks - 1); i++) {
diva_os_free(0, a->slave_adapters[i]);
a->slave_adapters[i] = NULL;
}
diva_4bri_cleanup_adapter(a);
return (-1);
}
memset(quadro_list, 0x00, sizeof(*quadro_list));
/*
Set interfaces
*/
a->xdi_adapter.QuadroList = quadro_list;
for (i = 0; i < tasks; i++) {
adapter_list[i]->xdi_adapter.ControllerNumber = i;
adapter_list[i]->xdi_adapter.tasks = tasks;
quadro_list->QuadroAdapter[i] =
&adapter_list[i]->xdi_adapter;
}
for (i = 0; i < tasks; i++) {
diva_current = adapter_list[i];
diva_current->dsp_mask = 0x00000003;
diva_current->xdi_adapter.a.io =
&diva_current->xdi_adapter;
diva_current->xdi_adapter.DIRequest = request;
diva_current->interface.cmd_proc = diva_4bri_cmd_card_proc;
diva_current->xdi_adapter.Properties =
CardProperties[a->CardOrdinal];
diva_current->CardOrdinal = a->CardOrdinal;
diva_current->xdi_adapter.Channels =
CardProperties[a->CardOrdinal].Channels;
diva_current->xdi_adapter.e_max =
CardProperties[a->CardOrdinal].E_info;
diva_current->xdi_adapter.e_tbl =
diva_os_malloc(0,
diva_current->xdi_adapter.e_max *
sizeof(E_INFO));
if (!diva_current->xdi_adapter.e_tbl) {
diva_4bri_cleanup_slave_adapters(a);
diva_4bri_cleanup_adapter(a);
for (i = 1; i < (tasks - 1); i++) {
diva_os_free(0, adapter_list[i]);
}
return (-1);
}
memset(diva_current->xdi_adapter.e_tbl, 0x00,
diva_current->xdi_adapter.e_max * sizeof(E_INFO));
if (diva_os_initialize_spin_lock(&diva_current->xdi_adapter.isr_spin_lock, "isr")) {
diva_4bri_cleanup_slave_adapters(a);
diva_4bri_cleanup_adapter(a);
for (i = 1; i < (tasks - 1); i++) {
diva_os_free(0, adapter_list[i]);
}
return (-1);
}
if (diva_os_initialize_spin_lock(&diva_current->xdi_adapter.data_spin_lock, "data")) {
diva_4bri_cleanup_slave_adapters(a);
diva_4bri_cleanup_adapter(a);
for (i = 1; i < (tasks - 1); i++) {
diva_os_free(0, adapter_list[i]);
}
return (-1);
}
strcpy(diva_current->xdi_adapter.req_soft_isr. dpc_thread_name, "kdivas4brid");
if (diva_os_initialize_soft_isr(&diva_current->xdi_adapter.req_soft_isr, DIDpcRoutine,
&diva_current->xdi_adapter)) {
diva_4bri_cleanup_slave_adapters(a);
diva_4bri_cleanup_adapter(a);
for (i = 1; i < (tasks - 1); i++) {
diva_os_free(0, adapter_list[i]);
}
return (-1);
}
/*
Do not initialize second DPC - only one thread will be created
*/
diva_current->xdi_adapter.isr_soft_isr.object =
diva_current->xdi_adapter.req_soft_isr.object;
}
if (v2) {
prepare_qBri2_functions(&a->xdi_adapter);
} else {
prepare_qBri_functions(&a->xdi_adapter);
}
for (i = 0; i < tasks; i++) {
diva_current = adapter_list[i];
if (i)
memcpy(&diva_current->resources, &a->resources, sizeof(divas_card_resources_t));
diva_current->resources.pci.qoffset = (a->xdi_adapter.MemorySize >> factor);
}
/*
Set up hardware related pointers
*/
a->xdi_adapter.cfg = (void *) (unsigned long) a->resources.pci.bar[0]; /* BAR0 CONFIG */
a->xdi_adapter.port = (void *) (unsigned long) a->resources.pci.bar[1]; /* BAR1 */
a->xdi_adapter.ctlReg = (void *) (unsigned long) a->resources.pci.bar[3]; /* BAR3 CNTRL */
for (i = 0; i < tasks; i++) {
diva_current = adapter_list[i];
diva_4bri_set_addresses(diva_current);
Slave = a->xdi_adapter.QuadroList->QuadroAdapter[i];
Slave->MultiMaster = &a->xdi_adapter;
Slave->sdram_bar = a->xdi_adapter.sdram_bar;
if (i) {
Slave->serialNo = ((dword) (Slave->ControllerNumber << 24)) |
a->xdi_adapter.serialNo;
Slave->cardType = a->xdi_adapter.cardType;
}
}
/*
reset contains the base address for the PLX 9054 register set
*/
p = DIVA_OS_MEM_ATTACH_RESET(&a->xdi_adapter);
WRITE_BYTE(&p[PLX9054_INTCSR], 0x00); /* disable PCI interrupts */
DIVA_OS_MEM_DETACH_RESET(&a->xdi_adapter, p);
/*
Set IRQ handler
*/
a->xdi_adapter.irq_info.irq_nr = a->resources.pci.irq;
sprintf(a->xdi_adapter.irq_info.irq_name, "DIVA 4BRI %ld",
(long) a->xdi_adapter.serialNo);
if (diva_os_register_irq(a, a->xdi_adapter.irq_info.irq_nr,
a->xdi_adapter.irq_info.irq_name)) {
diva_4bri_cleanup_slave_adapters(a);
diva_4bri_cleanup_adapter(a);
for (i = 1; i < (tasks - 1); i++) {
diva_os_free(0, adapter_list[i]);
}
return (-1);
}
a->xdi_adapter.irq_info.registered = 1;
/*
Add three slave adapters
*/
if (tasks > 1) {
diva_add_slave_adapter(adapter_list[1]);
diva_add_slave_adapter(adapter_list[2]);
diva_add_slave_adapter(adapter_list[3]);
}
diva_log_info("%s IRQ:%d SerNo:%d", a->xdi_adapter.Properties.Name,
a->resources.pci.irq, a->xdi_adapter.serialNo);
return (0);
}
/*
** Cleanup function will be called for master adapter only
** this is guaranteed by design: cleanup callback is set
** by master adapter only
*/
static int diva_4bri_cleanup_adapter(diva_os_xdi_adapter_t *a)
{
int bar;
/*
Stop adapter if running
*/
if (a->xdi_adapter.Initialized) {
diva_4bri_stop_adapter(a);
}
/*
Remove IRQ handler
*/
if (a->xdi_adapter.irq_info.registered) {
diva_os_remove_irq(a, a->xdi_adapter.irq_info.irq_nr);
}
a->xdi_adapter.irq_info.registered = 0;
/*
Free DPC's and spin locks on all adapters
*/
diva_4bri_cleanup_slave_adapters(a);
/*
Unmap all BARS
*/
for (bar = 0; bar < 4; bar++) {
if (bar != 1) {
if (a->resources.pci.bar[bar]
&& a->resources.pci.addr[bar]) {
divasa_unmap_pci_bar(a->resources.pci.addr[bar]);
a->resources.pci.bar[bar] = 0;
a->resources.pci.addr[bar] = NULL;
}
}
}
/*
Unregister I/O
*/
if (a->resources.pci.bar[1] && a->resources.pci.addr[1]) {
diva_os_register_io_port(a, 0, a->resources.pci.bar[1],
_4bri_is_rev_2_card(a->
CardOrdinal) ?
_4bri_v2_bar_length[1] :
_4bri_bar_length[1],
&a->port_name[0], 1);
a->resources.pci.bar[1] = 0;
a->resources.pci.addr[1] = NULL;
}
if (a->slave_list) {
diva_os_free(0, a->slave_list);
a->slave_list = NULL;
}
return (0);
}
static int _4bri_get_serial_number(diva_os_xdi_adapter_t *a)
{
dword data[64];
dword serNo;
word addr, status, i, j;
byte Bus, Slot;
void *hdev;
Bus = a->resources.pci.bus;
Slot = a->resources.pci.func;
hdev = a->resources.pci.hdev;
for (i = 0; i < 64; ++i) {
addr = i * 4;
for (j = 0; j < 5; ++j) {
PCIwrite(Bus, Slot, 0x4E, &addr, sizeof(addr),
hdev);
diva_os_wait(1);
PCIread(Bus, Slot, 0x4E, &status, sizeof(status),
hdev);
if (status & 0x8000)
break;
}
if (j >= 5) {
DBG_ERR(("EEPROM[%d] read failed (0x%x)", i * 4, addr))
return (0);
}
PCIread(Bus, Slot, 0x50, &data[i], sizeof(data[i]), hdev);
}
DBG_BLK(((char *) &data[0], sizeof(data)))
serNo = data[32];
if (serNo == 0 || serNo == 0xffffffff)
serNo = data[63];
if (!serNo) {
DBG_LOG(("W: Serial Number == 0, create one serial number"));
serNo = a->resources.pci.bar[1] & 0xffff0000;
serNo |= a->resources.pci.bus << 8;
serNo |= a->resources.pci.func;
}
a->xdi_adapter.serialNo = serNo;
DBG_REG(("Serial No. : %ld", a->xdi_adapter.serialNo))
return (serNo);
}
/*
** Release resources of slave adapters
*/
static int diva_4bri_cleanup_slave_adapters(diva_os_xdi_adapter_t *a)
{
diva_os_xdi_adapter_t *adapter_list[4];
diva_os_xdi_adapter_t *diva_current;
int i;
adapter_list[0] = a;
adapter_list[1] = a->slave_adapters[0];
adapter_list[2] = a->slave_adapters[1];
adapter_list[3] = a->slave_adapters[2];
for (i = 0; i < a->xdi_adapter.tasks; i++) {
diva_current = adapter_list[i];
if (diva_current) {
diva_os_destroy_spin_lock(&diva_current->
xdi_adapter.
isr_spin_lock, "unload");
diva_os_destroy_spin_lock(&diva_current->
xdi_adapter.
data_spin_lock,
"unload");
diva_os_cancel_soft_isr(&diva_current->xdi_adapter.
req_soft_isr);
diva_os_cancel_soft_isr(&diva_current->xdi_adapter.
isr_soft_isr);
diva_os_remove_soft_isr(&diva_current->xdi_adapter.
req_soft_isr);
diva_current->xdi_adapter.isr_soft_isr.object = NULL;
if (diva_current->xdi_adapter.e_tbl) {
diva_os_free(0,
diva_current->xdi_adapter.
e_tbl);
}
diva_current->xdi_adapter.e_tbl = NULL;
diva_current->xdi_adapter.e_max = 0;
diva_current->xdi_adapter.e_count = 0;
}
}
return (0);
}
static int
diva_4bri_cmd_card_proc(struct _diva_os_xdi_adapter *a,
diva_xdi_um_cfg_cmd_t *cmd, int length)
{
int ret = -1;
if (cmd->adapter != a->controller) {
DBG_ERR(("A: 4bri_cmd, invalid controller=%d != %d",
cmd->adapter, a->controller))
return (-1);
}
switch (cmd->command) {
case DIVA_XDI_UM_CMD_GET_CARD_ORDINAL:
a->xdi_mbox.data_length = sizeof(dword);
a->xdi_mbox.data =
diva_os_malloc(0, a->xdi_mbox.data_length);
if (a->xdi_mbox.data) {
*(dword *) a->xdi_mbox.data =
(dword) a->CardOrdinal;
a->xdi_mbox.status = DIVA_XDI_MBOX_BUSY;
ret = 0;
}
break;
case DIVA_XDI_UM_CMD_GET_SERIAL_NR:
a->xdi_mbox.data_length = sizeof(dword);
a->xdi_mbox.data =
diva_os_malloc(0, a->xdi_mbox.data_length);
if (a->xdi_mbox.data) {
*(dword *) a->xdi_mbox.data =
(dword) a->xdi_adapter.serialNo;
a->xdi_mbox.status = DIVA_XDI_MBOX_BUSY;
ret = 0;
}
break;
case DIVA_XDI_UM_CMD_GET_PCI_HW_CONFIG:
if (!a->xdi_adapter.ControllerNumber) {
/*
Only master adapter can access hardware config
*/
a->xdi_mbox.data_length = sizeof(dword) * 9;
a->xdi_mbox.data =
diva_os_malloc(0, a->xdi_mbox.data_length);
if (a->xdi_mbox.data) {
int i;
dword *data = (dword *) a->xdi_mbox.data;
for (i = 0; i < 8; i++) {
*data++ = a->resources.pci.bar[i];
}
*data++ = (dword) a->resources.pci.irq;
a->xdi_mbox.status = DIVA_XDI_MBOX_BUSY;
ret = 0;
}
}
break;
case DIVA_XDI_UM_CMD_GET_CARD_STATE:
if (!a->xdi_adapter.ControllerNumber) {
a->xdi_mbox.data_length = sizeof(dword);
a->xdi_mbox.data =
diva_os_malloc(0, a->xdi_mbox.data_length);
if (a->xdi_mbox.data) {
dword *data = (dword *) a->xdi_mbox.data;
if (!a->xdi_adapter.ram
|| !a->xdi_adapter.reset
|| !a->xdi_adapter.cfg) {
*data = 3;
} else if (a->xdi_adapter.trapped) {
*data = 2;
} else if (a->xdi_adapter.Initialized) {
*data = 1;
} else {
*data = 0;
}
a->xdi_mbox.status = DIVA_XDI_MBOX_BUSY;
ret = 0;
}
}
break;
case DIVA_XDI_UM_CMD_WRITE_FPGA:
if (!a->xdi_adapter.ControllerNumber) {
ret =
diva_4bri_write_fpga_image(a,
(byte *)&cmd[1],
cmd->command_data.
write_fpga.
image_length);
}
break;
case DIVA_XDI_UM_CMD_RESET_ADAPTER:
if (!a->xdi_adapter.ControllerNumber) {
ret = diva_4bri_reset_adapter(&a->xdi_adapter);
}
break;
case DIVA_XDI_UM_CMD_WRITE_SDRAM_BLOCK:
if (!a->xdi_adapter.ControllerNumber) {
ret = diva_4bri_write_sdram_block(&a->xdi_adapter,
cmd->
command_data.
write_sdram.
offset,
(byte *) &
cmd[1],
cmd->
command_data.
write_sdram.
length,
a->xdi_adapter.
MemorySize);
}
break;
case DIVA_XDI_UM_CMD_START_ADAPTER:
if (!a->xdi_adapter.ControllerNumber) {
ret = diva_4bri_start_adapter(&a->xdi_adapter,
cmd->command_data.
start.offset,
cmd->command_data.
start.features);
}
break;
case DIVA_XDI_UM_CMD_SET_PROTOCOL_FEATURES:
if (!a->xdi_adapter.ControllerNumber) {
a->xdi_adapter.features =
cmd->command_data.features.features;
a->xdi_adapter.a.protocol_capabilities =
a->xdi_adapter.features;
DBG_TRC(("Set raw protocol features (%08x)",
a->xdi_adapter.features))
ret = 0;
}
break;
case DIVA_XDI_UM_CMD_STOP_ADAPTER:
if (!a->xdi_adapter.ControllerNumber) {
ret = diva_4bri_stop_adapter(a);
}
break;
case DIVA_XDI_UM_CMD_READ_XLOG_ENTRY:
ret = diva_card_read_xlog(a);
break;
case DIVA_XDI_UM_CMD_READ_SDRAM:
if (!a->xdi_adapter.ControllerNumber
&& a->xdi_adapter.Address) {
if (
(a->xdi_mbox.data_length =
cmd->command_data.read_sdram.length)) {
if (
(a->xdi_mbox.data_length +
cmd->command_data.read_sdram.offset) <
a->xdi_adapter.MemorySize) {
a->xdi_mbox.data =
diva_os_malloc(0,
a->xdi_mbox.
data_length);
if (a->xdi_mbox.data) {
byte __iomem *p = DIVA_OS_MEM_ATTACH_ADDRESS(&a->xdi_adapter);
byte __iomem *src = p;
byte *dst = a->xdi_mbox.data;
dword len = a->xdi_mbox.data_length;
src += cmd->command_data.read_sdram.offset;
while (len--) {
*dst++ = READ_BYTE(src++);
}
DIVA_OS_MEM_DETACH_ADDRESS(&a->xdi_adapter, p);
a->xdi_mbox.status = DIVA_XDI_MBOX_BUSY;
ret = 0;
}
}
}
}
break;
default:
DBG_ERR(("A: A(%d) invalid cmd=%d", a->controller,
cmd->command))
}
return (ret);
}
void *xdiLoadFile(char *FileName, dword *FileLength,
unsigned long lim)
{
void *ret = diva_xdiLoadFileFile;
if (FileLength) {
*FileLength = diva_xdiLoadFileLength;
}
diva_xdiLoadFileFile = NULL;
diva_xdiLoadFileLength = 0;
return (ret);
}
void diva_os_set_qBri_functions(PISDN_ADAPTER IoAdapter)
{
}
void diva_os_set_qBri2_functions(PISDN_ADAPTER IoAdapter)
{
}
static int
diva_4bri_write_fpga_image(diva_os_xdi_adapter_t *a, byte *data,
dword length)
{
int ret;
diva_xdiLoadFileFile = data;
diva_xdiLoadFileLength = length;
ret = qBri_FPGA_download(&a->xdi_adapter);
diva_xdiLoadFileFile = NULL;
diva_xdiLoadFileLength = 0;
return (ret ? 0 : -1);
}
static int diva_4bri_reset_adapter(PISDN_ADAPTER IoAdapter)
{
PISDN_ADAPTER Slave;
int i;
if (!IoAdapter->Address || !IoAdapter->reset) {
return (-1);
}
if (IoAdapter->Initialized) {
DBG_ERR(("A: A(%d) can't reset 4BRI adapter - please stop first",
IoAdapter->ANum))
return (-1);
}
/*
Forget all entities on all adapters
*/
for (i = 0; ((i < IoAdapter->tasks) && IoAdapter->QuadroList); i++) {
Slave = IoAdapter->QuadroList->QuadroAdapter[i];
Slave->e_count = 0;
if (Slave->e_tbl) {
memset(Slave->e_tbl, 0x00,
Slave->e_max * sizeof(E_INFO));
}
Slave->head = 0;
Slave->tail = 0;
Slave->assign = 0;
Slave->trapped = 0;
memset(&Slave->a.IdTable[0], 0x00,
sizeof(Slave->a.IdTable));
memset(&Slave->a.IdTypeTable[0], 0x00,
sizeof(Slave->a.IdTypeTable));
memset(&Slave->a.FlowControlIdTable[0], 0x00,
sizeof(Slave->a.FlowControlIdTable));
memset(&Slave->a.FlowControlSkipTable[0], 0x00,
sizeof(Slave->a.FlowControlSkipTable));
memset(&Slave->a.misc_flags_table[0], 0x00,
sizeof(Slave->a.misc_flags_table));
memset(&Slave->a.rx_stream[0], 0x00,
sizeof(Slave->a.rx_stream));
memset(&Slave->a.tx_stream[0], 0x00,
sizeof(Slave->a.tx_stream));
memset(&Slave->a.tx_pos[0], 0x00, sizeof(Slave->a.tx_pos));
memset(&Slave->a.rx_pos[0], 0x00, sizeof(Slave->a.rx_pos));
}
return (0);
}
static int
diva_4bri_write_sdram_block(PISDN_ADAPTER IoAdapter,
dword address,
const byte *data, dword length, dword limit)
{
byte __iomem *p = DIVA_OS_MEM_ATTACH_ADDRESS(IoAdapter);
byte __iomem *mem = p;
if (((address + length) >= limit) || !mem) {
DIVA_OS_MEM_DETACH_ADDRESS(IoAdapter, p);
DBG_ERR(("A: A(%d) write 4BRI address=0x%08lx",
IoAdapter->ANum, address + length))
return (-1);
}
mem += address;
while (length--) {
WRITE_BYTE(mem++, *data++);
}
DIVA_OS_MEM_DETACH_ADDRESS(IoAdapter, p);
return (0);
}
static int
diva_4bri_start_adapter(PISDN_ADAPTER IoAdapter,
dword start_address, dword features)
{
volatile word __iomem *signature;
int started = 0;
int i;
byte __iomem *p;
/*
start adapter
*/
start_qBri_hardware(IoAdapter);
p = DIVA_OS_MEM_ATTACH_RAM(IoAdapter);
/*
wait for signature in shared memory (max. 3 seconds)
*/
signature = (volatile word __iomem *) (&p[0x1E]);
for (i = 0; i < 300; ++i) {
diva_os_wait(10);
if (READ_WORD(&signature[0]) == 0x4447) {
DBG_TRC(("Protocol startup time %d.%02d seconds",
(i / 100), (i % 100)))
started = 1;
break;
}
}
for (i = 1; i < IoAdapter->tasks; i++) {
IoAdapter->QuadroList->QuadroAdapter[i]->features =
IoAdapter->features;
IoAdapter->QuadroList->QuadroAdapter[i]->a.
protocol_capabilities = IoAdapter->features;
}
if (!started) {
DBG_FTL(("%s: Adapter selftest failed, signature=%04x",
IoAdapter->Properties.Name,
READ_WORD(&signature[0])))
DIVA_OS_MEM_DETACH_RAM(IoAdapter, p);
(*(IoAdapter->trapFnc)) (IoAdapter);
IoAdapter->stop(IoAdapter);
return (-1);
}
DIVA_OS_MEM_DETACH_RAM(IoAdapter, p);
for (i = 0; i < IoAdapter->tasks; i++) {
IoAdapter->QuadroList->QuadroAdapter[i]->Initialized = 1;
IoAdapter->QuadroList->QuadroAdapter[i]->IrqCount = 0;
}
if (check_qBri_interrupt(IoAdapter)) {
DBG_ERR(("A: A(%d) interrupt test failed",
IoAdapter->ANum))
for (i = 0; i < IoAdapter->tasks; i++) {
IoAdapter->QuadroList->QuadroAdapter[i]->Initialized = 0;
}
IoAdapter->stop(IoAdapter);
return (-1);
}
IoAdapter->Properties.Features = (word) features;
diva_xdi_display_adapter_features(IoAdapter->ANum);
for (i = 0; i < IoAdapter->tasks; i++) {
DBG_LOG(("A(%d) %s adapter successfully started",
IoAdapter->QuadroList->QuadroAdapter[i]->ANum,
(IoAdapter->tasks == 1) ? "BRI 2.0" : "4BRI"))
diva_xdi_didd_register_adapter(IoAdapter->QuadroList->QuadroAdapter[i]->ANum);
IoAdapter->QuadroList->QuadroAdapter[i]->Properties.Features = (word) features;
}
return (0);
}
static int check_qBri_interrupt(PISDN_ADAPTER IoAdapter)
{
#ifdef SUPPORT_INTERRUPT_TEST_ON_4BRI
int i;
ADAPTER *a = &IoAdapter->a;
byte __iomem *p;
IoAdapter->IrqCount = 0;
if (IoAdapter->ControllerNumber > 0)
return (-1);
p = DIVA_OS_MEM_ATTACH_RESET(IoAdapter);
WRITE_BYTE(&p[PLX9054_INTCSR], PLX9054_INT_ENABLE);
DIVA_OS_MEM_DETACH_RESET(IoAdapter, p);
/*
interrupt test
*/
a->ReadyInt = 1;
a->ram_out(a, &PR_RAM->ReadyInt, 1);
for (i = 100; !IoAdapter->IrqCount && (i-- > 0); diva_os_wait(10));
return ((IoAdapter->IrqCount > 0) ? 0 : -1);
#else
dword volatile __iomem *qBriIrq;
byte __iomem *p;
/*
Reset on-board interrupt register
*/
IoAdapter->IrqCount = 0;
p = DIVA_OS_MEM_ATTACH_CTLREG(IoAdapter);
qBriIrq = (dword volatile __iomem *) (&p[_4bri_is_rev_2_card
(IoAdapter->
cardType) ? (MQ2_BREG_IRQ_TEST)
: (MQ_BREG_IRQ_TEST)]);
WRITE_DWORD(qBriIrq, MQ_IRQ_REQ_OFF);
DIVA_OS_MEM_DETACH_CTLREG(IoAdapter, p);
p = DIVA_OS_MEM_ATTACH_RESET(IoAdapter);
WRITE_BYTE(&p[PLX9054_INTCSR], PLX9054_INT_ENABLE);
DIVA_OS_MEM_DETACH_RESET(IoAdapter, p);
diva_os_wait(100);
return (0);
#endif /* SUPPORT_INTERRUPT_TEST_ON_4BRI */
}
static void diva_4bri_clear_interrupts(diva_os_xdi_adapter_t *a)
{
PISDN_ADAPTER IoAdapter = &a->xdi_adapter;
/*
clear any pending interrupt
*/
IoAdapter->disIrq(IoAdapter);
IoAdapter->tst_irq(&IoAdapter->a);
IoAdapter->clr_irq(&IoAdapter->a);
IoAdapter->tst_irq(&IoAdapter->a);
/*
kill pending dpcs
*/
diva_os_cancel_soft_isr(&IoAdapter->req_soft_isr);
diva_os_cancel_soft_isr(&IoAdapter->isr_soft_isr);
}
static int diva_4bri_stop_adapter(diva_os_xdi_adapter_t *a)
{
PISDN_ADAPTER IoAdapter = &a->xdi_adapter;
int i;
if (!IoAdapter->ram) {
return (-1);
}
if (!IoAdapter->Initialized) {
DBG_ERR(("A: A(%d) can't stop PRI adapter - not running",
IoAdapter->ANum))
return (-1); /* nothing to stop */
}
for (i = 0; i < IoAdapter->tasks; i++) {
IoAdapter->QuadroList->QuadroAdapter[i]->Initialized = 0;
}
/*
Disconnect Adapters from DIDD
*/
for (i = 0; i < IoAdapter->tasks; i++) {
diva_xdi_didd_remove_adapter(IoAdapter->QuadroList->QuadroAdapter[i]->ANum);
}
i = 100;
/*
Stop interrupts
*/
a->clear_interrupts_proc = diva_4bri_clear_interrupts;
IoAdapter->a.ReadyInt = 1;
IoAdapter->a.ram_inc(&IoAdapter->a, &PR_RAM->ReadyInt);
do {
diva_os_sleep(10);
} while (i-- && a->clear_interrupts_proc);
if (a->clear_interrupts_proc) {
diva_4bri_clear_interrupts(a);
a->clear_interrupts_proc = NULL;
DBG_ERR(("A: A(%d) no final interrupt from 4BRI adapter",
IoAdapter->ANum))
}
IoAdapter->a.ReadyInt = 0;
/*
Stop and reset adapter
*/
IoAdapter->stop(IoAdapter);
return (0);
}
| gpl-2.0 |
djvoleur/kernel_samsung_exynos7420 | drivers/misc/sim_slot.c | 125 | 3718 | /*
* Copyright (c) 2010-2011 Samsung Electronics Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/of_platform.h>
#include <linux/of_gpio.h>
#include <linux/of.h>
#include <linux/i2c-gpio.h>
#include <asm/gpio.h>
/* GPIO STATUS */
#define SS_VALUE 0 /* Low = Single Sim */
#define DS_VALUE 1 /* High = Dual Sim */
static unsigned int gpio_number = -1;
enum { NO_SIM = 0, SINGLE_SIM, DUAL_SIM, TRIPLE_SIM };
static int check_simslot_count(struct seq_file *m, void *v)
{
int retval, support_number_of_simslot;
printk("\n SIM_SLOT_PIN : %d\n", gpio_number); //temp log for checking GPIO Setting correctly applyed or not
retval = gpio_request(gpio_number,"SIM_SLOT_PIN");
if (retval) {
pr_err("%s:Failed to reqeust GPIO, code = %d.\n",
__func__, retval);
support_number_of_simslot = retval;
}
else
{
retval = gpio_direction_input(gpio_number);
if (retval){
pr_err("%s:Failed to set direction of GPIO, code = %d.\n",
__func__, retval);
support_number_of_simslot = retval;
}
else
{
retval = gpio_get_value(gpio_number);
/* This codes are implemented assumption that count of GPIO about simslot is only one on H/W schematic
You may change this codes if count of GPIO about simslot has change */
switch(retval)
{
case SS_VALUE:
support_number_of_simslot = SINGLE_SIM;
break;
case DS_VALUE:
support_number_of_simslot = DUAL_SIM;
break;
default :
support_number_of_simslot = -1;
break;
}
}
gpio_free(gpio_number);
}
if(support_number_of_simslot < 0)
{
pr_err("******* Make a forced kernel panic because can't check simslot count******\n");
panic("kernel panic");
}
printk("%s: Number of simslot: %u\n", __func__, support_number_of_simslot);
seq_printf(m, "%u\n", support_number_of_simslot);
return 0;
}
static int check_simslot_count_open(struct inode *inode, struct file *file)
{
return single_open(file, check_simslot_count, NULL);
}
static const struct file_operations check_simslot_count_fops = {
.open = check_simslot_count_open,
.read = seq_read,
.llseek = seq_lseek,
.release= single_release,
};
static int simslot_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
gpio_number = of_get_gpio(dev->of_node, 0);
if (gpio_number < 0) {
dev_err(dev, "failed to get proper gpio number\n");
return -EINVAL;
}
if (!proc_create("simslot_count",0,NULL,&check_simslot_count_fops))
{
pr_err("***** Make a forced kernel panic because can't make a simslot_count file node ******\n");
panic("kernel panic");
return -ENOMEM;
}
return 0;
}
#if defined(CONFIG_OF)
static struct of_device_id simslot_dt_ids[] = {
{ .compatible = "simslot_count" },
{ },
};
MODULE_DEVICE_TABLE(of, simslot_dt_ids);
#endif /* CONFIG_OF */
static struct platform_driver simslot_device_driver = {
.probe = simslot_probe,
.driver = {
.name = "simslot_count",
.owner = THIS_MODULE,
#if defined(CONFIG_OF)
.of_match_table = simslot_dt_ids,
#endif /* CONFIG_OF */
}
};
static int __init simslot_count_init(void)
{
printk("%s start\n", __func__);
return platform_driver_register(&simslot_device_driver);
}
static void __exit simslot_count_exit(void)
{
printk("%s start\n", __func__);
platform_driver_unregister(&simslot_device_driver);
}
late_initcall(simslot_count_init);
module_exit(simslot_count_exit)
| gpl-2.0 |
sdemario/BlueZ | tools/hcisecfilter.c | 125 | 6005 | /*
*
* BlueZ - Bluetooth protocol stack for Linux
*
* Copyright (C) 2002-2003 Maxim Krasnyansky <maxk@qualcomm.com>
* Copyright (C) 2002-2010 Marcel Holtmann <marcel@holtmann.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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
int main(void)
{
uint32_t type_mask;
uint32_t event_mask[2];
uint32_t ocf_mask[4];
/* Packet types */
memset(&type_mask, 0, sizeof(type_mask));
hci_set_bit(HCI_EVENT_PKT, &type_mask);
printf("Type mask: { 0x%02x }\n", type_mask);
/* Events */
memset(event_mask, 0, sizeof(event_mask));
hci_set_bit(EVT_INQUIRY_COMPLETE, event_mask);
hci_set_bit(EVT_INQUIRY_RESULT, event_mask);
hci_set_bit(EVT_CONN_COMPLETE, event_mask);
hci_set_bit(EVT_CONN_REQUEST, event_mask);
hci_set_bit(EVT_DISCONN_COMPLETE, event_mask);
hci_set_bit(EVT_AUTH_COMPLETE, event_mask);
hci_set_bit(EVT_REMOTE_NAME_REQ_COMPLETE, event_mask);
hci_set_bit(EVT_ENCRYPT_CHANGE, event_mask);
hci_set_bit(EVT_READ_REMOTE_FEATURES_COMPLETE, event_mask);
hci_set_bit(EVT_READ_REMOTE_VERSION_COMPLETE, event_mask);
hci_set_bit(EVT_CMD_COMPLETE, event_mask);
hci_set_bit(EVT_CMD_STATUS, event_mask);
hci_set_bit(EVT_READ_CLOCK_OFFSET_COMPLETE, event_mask);
hci_set_bit(EVT_INQUIRY_RESULT_WITH_RSSI, event_mask);
hci_set_bit(EVT_READ_REMOTE_EXT_FEATURES_COMPLETE, event_mask);
hci_set_bit(EVT_SYNC_CONN_COMPLETE, event_mask);
hci_set_bit(EVT_SYNC_CONN_CHANGED, event_mask);
hci_set_bit(EVT_EXTENDED_INQUIRY_RESULT, event_mask);
printf("Event mask: { 0x%08x, 0x%08x }\n",
event_mask[0], event_mask[1]);
/* OGF_LINK_CTL */
memset(ocf_mask, 0, sizeof(ocf_mask));
hci_set_bit(OCF_INQUIRY, ocf_mask);
hci_set_bit(OCF_INQUIRY_CANCEL, ocf_mask);
hci_set_bit(OCF_REMOTE_NAME_REQ, ocf_mask);
hci_set_bit(OCF_REMOTE_NAME_REQ_CANCEL, ocf_mask);
hci_set_bit(OCF_READ_REMOTE_FEATURES, ocf_mask);
hci_set_bit(OCF_READ_REMOTE_EXT_FEATURES, ocf_mask);
hci_set_bit(OCF_READ_REMOTE_VERSION, ocf_mask);
hci_set_bit(OCF_READ_CLOCK_OFFSET, ocf_mask);
hci_set_bit(OCF_READ_LMP_HANDLE, ocf_mask);
printf("OGF_LINK_CTL: { 0x%08x, 0x%08x, 0x%08x, 0x%02x }\n",
ocf_mask[0], ocf_mask[1], ocf_mask[2], ocf_mask[3]);
/* OGF_LINK_POLICY */
memset(ocf_mask, 0, sizeof(ocf_mask));
hci_set_bit(OCF_ROLE_DISCOVERY, ocf_mask);
hci_set_bit(OCF_READ_LINK_POLICY, ocf_mask);
hci_set_bit(OCF_READ_DEFAULT_LINK_POLICY, ocf_mask);
printf("OGF_LINK_POLICY: { 0x%08x, 0x%08x, 0x%08x, 0x%02x }\n",
ocf_mask[0], ocf_mask[1], ocf_mask[2], ocf_mask[3]);
/* OGF_HOST_CTL */
memset(ocf_mask, 0, sizeof(ocf_mask));
hci_set_bit(OCF_READ_PIN_TYPE, ocf_mask);
hci_set_bit(OCF_READ_LOCAL_NAME, ocf_mask);
hci_set_bit(OCF_READ_CONN_ACCEPT_TIMEOUT, ocf_mask);
hci_set_bit(OCF_READ_PAGE_TIMEOUT, ocf_mask);
hci_set_bit(OCF_READ_SCAN_ENABLE, ocf_mask);
hci_set_bit(OCF_READ_PAGE_ACTIVITY, ocf_mask);
hci_set_bit(OCF_READ_INQ_ACTIVITY, ocf_mask);
hci_set_bit(OCF_READ_AUTH_ENABLE, ocf_mask);
hci_set_bit(OCF_READ_ENCRYPT_MODE, ocf_mask);
hci_set_bit(OCF_READ_CLASS_OF_DEV, ocf_mask);
hci_set_bit(OCF_READ_VOICE_SETTING, ocf_mask);
hci_set_bit(OCF_READ_AUTOMATIC_FLUSH_TIMEOUT, ocf_mask);
hci_set_bit(OCF_READ_NUM_BROADCAST_RETRANS, ocf_mask);
hci_set_bit(OCF_READ_HOLD_MODE_ACTIVITY, ocf_mask);
hci_set_bit(OCF_READ_TRANSMIT_POWER_LEVEL, ocf_mask);
hci_set_bit(OCF_READ_LINK_SUPERVISION_TIMEOUT, ocf_mask);
hci_set_bit(OCF_READ_NUM_SUPPORTED_IAC, ocf_mask);
hci_set_bit(OCF_READ_CURRENT_IAC_LAP, ocf_mask);
hci_set_bit(OCF_READ_PAGE_SCAN_PERIOD_MODE, ocf_mask);
hci_set_bit(OCF_READ_PAGE_SCAN_MODE, ocf_mask);
hci_set_bit(OCF_READ_INQUIRY_SCAN_TYPE, ocf_mask);
hci_set_bit(OCF_READ_INQUIRY_MODE, ocf_mask);
hci_set_bit(OCF_READ_PAGE_SCAN_TYPE, ocf_mask);
hci_set_bit(OCF_READ_AFH_MODE, ocf_mask);
hci_set_bit(OCF_READ_EXT_INQUIRY_RESPONSE, ocf_mask);
hci_set_bit(OCF_READ_SIMPLE_PAIRING_MODE, ocf_mask);
hci_set_bit(OCF_READ_INQ_RESPONSE_TX_POWER_LEVEL, ocf_mask);
hci_set_bit(OCF_READ_DEFAULT_ERROR_DATA_REPORTING, ocf_mask);
printf("OGF_HOST_CTL: { 0x%08x, 0x%08x, 0x%08x, 0x%02x }\n",
ocf_mask[0], ocf_mask[1], ocf_mask[2], ocf_mask[3]);
/* OGF_INFO_PARAM */
memset(ocf_mask, 0, sizeof(ocf_mask));
hci_set_bit(OCF_READ_LOCAL_VERSION, ocf_mask);
hci_set_bit(OCF_READ_LOCAL_COMMANDS, ocf_mask);
hci_set_bit(OCF_READ_LOCAL_FEATURES, ocf_mask);
hci_set_bit(OCF_READ_LOCAL_EXT_FEATURES, ocf_mask);
hci_set_bit(OCF_READ_BUFFER_SIZE, ocf_mask);
hci_set_bit(OCF_READ_COUNTRY_CODE, ocf_mask);
hci_set_bit(OCF_READ_BD_ADDR, ocf_mask);
printf("OGF_INFO_PARAM: { 0x%08x, 0x%08x, 0x%08x, 0x%02x }\n",
ocf_mask[0], ocf_mask[1], ocf_mask[2], ocf_mask[3]);
/* OGF_STATUS_PARAM */
memset(ocf_mask, 0, sizeof(ocf_mask));
hci_set_bit(OCF_READ_FAILED_CONTACT_COUNTER, ocf_mask);
hci_set_bit(OCF_READ_LINK_QUALITY, ocf_mask);
hci_set_bit(OCF_READ_RSSI, ocf_mask);
hci_set_bit(OCF_READ_AFH_MAP, ocf_mask);
hci_set_bit(OCF_READ_CLOCK, ocf_mask);
printf("OGF_STATUS_PARAM: { 0x%08x, 0x%08x, 0x%08x, 0x%02x }\n",
ocf_mask[0], ocf_mask[1], ocf_mask[2], ocf_mask[3]);
return 0;
}
| gpl-2.0 |
hausdorff/linux | drivers/pci/pcie/pme.c | 381 | 11193 | /*
* PCIe Native PME support
*
* Copyright (C) 2007 - 2009 Intel Corp
* Copyright (C) 2007 - 2009 Shaohua Li <shaohua.li@intel.com>
* Copyright (C) 2009 Rafael J. Wysocki <rjw@sisk.pl>, Novell Inc.
*
* This file is subject to the terms and conditions of the GNU General Public
* License V2. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <linux/pcieport_if.h>
#include <linux/pm_runtime.h>
#include "../pci.h"
#include "portdrv.h"
/*
* If this switch is set, MSI will not be used for PCIe PME signaling. This
* causes the PCIe port driver to use INTx interrupts only, but it turns out
* that using MSI for PCIe PME signaling doesn't play well with PCIe PME-based
* wake-up from system sleep states.
*/
bool pcie_pme_msi_disabled;
static int __init pcie_pme_setup(char *str)
{
if (!strncmp(str, "nomsi", 5))
pcie_pme_msi_disabled = true;
return 1;
}
__setup("pcie_pme=", pcie_pme_setup);
struct pcie_pme_service_data {
spinlock_t lock;
struct pcie_device *srv;
struct work_struct work;
bool noirq; /* Don't enable the PME interrupt used by this service. */
};
/**
* pcie_pme_interrupt_enable - Enable/disable PCIe PME interrupt generation.
* @dev: PCIe root port or event collector.
* @enable: Enable or disable the interrupt.
*/
void pcie_pme_interrupt_enable(struct pci_dev *dev, bool enable)
{
if (enable)
pcie_capability_set_word(dev, PCI_EXP_RTCTL,
PCI_EXP_RTCTL_PMEIE);
else
pcie_capability_clear_word(dev, PCI_EXP_RTCTL,
PCI_EXP_RTCTL_PMEIE);
}
/**
* pcie_pme_walk_bus - Scan a PCI bus for devices asserting PME#.
* @bus: PCI bus to scan.
*
* Scan given PCI bus and all buses under it for devices asserting PME#.
*/
static bool pcie_pme_walk_bus(struct pci_bus *bus)
{
struct pci_dev *dev;
bool ret = false;
list_for_each_entry(dev, &bus->devices, bus_list) {
/* Skip PCIe devices in case we started from a root port. */
if (!pci_is_pcie(dev) && pci_check_pme_status(dev)) {
if (dev->pme_poll)
dev->pme_poll = false;
pci_wakeup_event(dev);
pm_request_resume(&dev->dev);
ret = true;
}
if (dev->subordinate && pcie_pme_walk_bus(dev->subordinate))
ret = true;
}
return ret;
}
/**
* pcie_pme_from_pci_bridge - Check if PCIe-PCI bridge generated a PME.
* @bus: Secondary bus of the bridge.
* @devfn: Device/function number to check.
*
* PME from PCI devices under a PCIe-PCI bridge may be converted to an in-band
* PCIe PME message. In such that case the bridge should use the Requester ID
* of device/function number 0 on its secondary bus.
*/
static bool pcie_pme_from_pci_bridge(struct pci_bus *bus, u8 devfn)
{
struct pci_dev *dev;
bool found = false;
if (devfn)
return false;
dev = pci_dev_get(bus->self);
if (!dev)
return false;
if (pci_is_pcie(dev) && pci_pcie_type(dev) == PCI_EXP_TYPE_PCI_BRIDGE) {
down_read(&pci_bus_sem);
if (pcie_pme_walk_bus(bus))
found = true;
up_read(&pci_bus_sem);
}
pci_dev_put(dev);
return found;
}
/**
* pcie_pme_handle_request - Find device that generated PME and handle it.
* @port: Root port or event collector that generated the PME interrupt.
* @req_id: PCIe Requester ID of the device that generated the PME.
*/
static void pcie_pme_handle_request(struct pci_dev *port, u16 req_id)
{
u8 busnr = req_id >> 8, devfn = req_id & 0xff;
struct pci_bus *bus;
struct pci_dev *dev;
bool found = false;
/* First, check if the PME is from the root port itself. */
if (port->devfn == devfn && port->bus->number == busnr) {
if (port->pme_poll)
port->pme_poll = false;
if (pci_check_pme_status(port)) {
pm_request_resume(&port->dev);
found = true;
} else {
/*
* Apparently, the root port generated the PME on behalf
* of a non-PCIe device downstream. If this is done by
* a root port, the Requester ID field in its status
* register may contain either the root port's, or the
* source device's information (PCI Express Base
* Specification, Rev. 2.0, Section 6.1.9).
*/
down_read(&pci_bus_sem);
found = pcie_pme_walk_bus(port->subordinate);
up_read(&pci_bus_sem);
}
goto out;
}
/* Second, find the bus the source device is on. */
bus = pci_find_bus(pci_domain_nr(port->bus), busnr);
if (!bus)
goto out;
/* Next, check if the PME is from a PCIe-PCI bridge. */
found = pcie_pme_from_pci_bridge(bus, devfn);
if (found)
goto out;
/* Finally, try to find the PME source on the bus. */
down_read(&pci_bus_sem);
list_for_each_entry(dev, &bus->devices, bus_list) {
pci_dev_get(dev);
if (dev->devfn == devfn) {
found = true;
break;
}
pci_dev_put(dev);
}
up_read(&pci_bus_sem);
if (found) {
/* The device is there, but we have to check its PME status. */
found = pci_check_pme_status(dev);
if (found) {
if (dev->pme_poll)
dev->pme_poll = false;
pci_wakeup_event(dev);
pm_request_resume(&dev->dev);
}
pci_dev_put(dev);
} else if (devfn) {
/*
* The device is not there, but we can still try to recover by
* assuming that the PME was reported by a PCIe-PCI bridge that
* used devfn different from zero.
*/
dev_dbg(&port->dev, "PME interrupt generated for "
"non-existent device %02x:%02x.%d\n",
busnr, PCI_SLOT(devfn), PCI_FUNC(devfn));
found = pcie_pme_from_pci_bridge(bus, 0);
}
out:
if (!found)
dev_dbg(&port->dev, "Spurious native PME interrupt!\n");
}
/**
* pcie_pme_work_fn - Work handler for PCIe PME interrupt.
* @work: Work structure giving access to service data.
*/
static void pcie_pme_work_fn(struct work_struct *work)
{
struct pcie_pme_service_data *data =
container_of(work, struct pcie_pme_service_data, work);
struct pci_dev *port = data->srv->port;
u32 rtsta;
spin_lock_irq(&data->lock);
for (;;) {
if (data->noirq)
break;
pcie_capability_read_dword(port, PCI_EXP_RTSTA, &rtsta);
if (rtsta & PCI_EXP_RTSTA_PME) {
/*
* Clear PME status of the port. If there are other
* pending PMEs, the status will be set again.
*/
pcie_clear_root_pme_status(port);
spin_unlock_irq(&data->lock);
pcie_pme_handle_request(port, rtsta & 0xffff);
spin_lock_irq(&data->lock);
continue;
}
/* No need to loop if there are no more PMEs pending. */
if (!(rtsta & PCI_EXP_RTSTA_PENDING))
break;
spin_unlock_irq(&data->lock);
cpu_relax();
spin_lock_irq(&data->lock);
}
if (!data->noirq)
pcie_pme_interrupt_enable(port, true);
spin_unlock_irq(&data->lock);
}
/**
* pcie_pme_irq - Interrupt handler for PCIe root port PME interrupt.
* @irq: Interrupt vector.
* @context: Interrupt context pointer.
*/
static irqreturn_t pcie_pme_irq(int irq, void *context)
{
struct pci_dev *port;
struct pcie_pme_service_data *data;
u32 rtsta;
unsigned long flags;
port = ((struct pcie_device *)context)->port;
data = get_service_data((struct pcie_device *)context);
spin_lock_irqsave(&data->lock, flags);
pcie_capability_read_dword(port, PCI_EXP_RTSTA, &rtsta);
if (!(rtsta & PCI_EXP_RTSTA_PME)) {
spin_unlock_irqrestore(&data->lock, flags);
return IRQ_NONE;
}
pcie_pme_interrupt_enable(port, false);
spin_unlock_irqrestore(&data->lock, flags);
/* We don't use pm_wq, because it's freezable. */
schedule_work(&data->work);
return IRQ_HANDLED;
}
/**
* pcie_pme_set_native - Set the PME interrupt flag for given device.
* @dev: PCI device to handle.
* @ign: Ignored.
*/
static int pcie_pme_set_native(struct pci_dev *dev, void *ign)
{
dev_info(&dev->dev, "Signaling PME through PCIe PME interrupt\n");
device_set_run_wake(&dev->dev, true);
dev->pme_interrupt = true;
return 0;
}
/**
* pcie_pme_mark_devices - Set the PME interrupt flag for devices below a port.
* @port: PCIe root port or event collector to handle.
*
* For each device below given root port, including the port itself (or for each
* root complex integrated endpoint if @port is a root complex event collector)
* set the flag indicating that it can signal run-time wake-up events via PCIe
* PME interrupts.
*/
static void pcie_pme_mark_devices(struct pci_dev *port)
{
pcie_pme_set_native(port, NULL);
if (port->subordinate) {
pci_walk_bus(port->subordinate, pcie_pme_set_native, NULL);
} else {
struct pci_bus *bus = port->bus;
struct pci_dev *dev;
/* Check if this is a root port event collector. */
if (pci_pcie_type(port) != PCI_EXP_TYPE_RC_EC || !bus)
return;
down_read(&pci_bus_sem);
list_for_each_entry(dev, &bus->devices, bus_list)
if (pci_is_pcie(dev)
&& pci_pcie_type(dev) == PCI_EXP_TYPE_RC_END)
pcie_pme_set_native(dev, NULL);
up_read(&pci_bus_sem);
}
}
/**
* pcie_pme_probe - Initialize PCIe PME service for given root port.
* @srv: PCIe service to initialize.
*/
static int pcie_pme_probe(struct pcie_device *srv)
{
struct pci_dev *port;
struct pcie_pme_service_data *data;
int ret;
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (!data)
return -ENOMEM;
spin_lock_init(&data->lock);
INIT_WORK(&data->work, pcie_pme_work_fn);
data->srv = srv;
set_service_data(srv, data);
port = srv->port;
pcie_pme_interrupt_enable(port, false);
pcie_clear_root_pme_status(port);
ret = request_irq(srv->irq, pcie_pme_irq, IRQF_SHARED, "PCIe PME", srv);
if (ret) {
kfree(data);
} else {
pcie_pme_mark_devices(port);
pcie_pme_interrupt_enable(port, true);
}
return ret;
}
/**
* pcie_pme_suspend - Suspend PCIe PME service device.
* @srv: PCIe service device to suspend.
*/
static int pcie_pme_suspend(struct pcie_device *srv)
{
struct pcie_pme_service_data *data = get_service_data(srv);
struct pci_dev *port = srv->port;
spin_lock_irq(&data->lock);
pcie_pme_interrupt_enable(port, false);
pcie_clear_root_pme_status(port);
data->noirq = true;
spin_unlock_irq(&data->lock);
synchronize_irq(srv->irq);
return 0;
}
/**
* pcie_pme_resume - Resume PCIe PME service device.
* @srv - PCIe service device to resume.
*/
static int pcie_pme_resume(struct pcie_device *srv)
{
struct pcie_pme_service_data *data = get_service_data(srv);
struct pci_dev *port = srv->port;
spin_lock_irq(&data->lock);
data->noirq = false;
pcie_clear_root_pme_status(port);
pcie_pme_interrupt_enable(port, true);
spin_unlock_irq(&data->lock);
return 0;
}
/**
* pcie_pme_remove - Prepare PCIe PME service device for removal.
* @srv - PCIe service device to remove.
*/
static void pcie_pme_remove(struct pcie_device *srv)
{
pcie_pme_suspend(srv);
free_irq(srv->irq, srv);
kfree(get_service_data(srv));
}
static struct pcie_port_service_driver pcie_pme_driver = {
.name = "pcie_pme",
.port_type = PCI_EXP_TYPE_ROOT_PORT,
.service = PCIE_PORT_SERVICE_PME,
.probe = pcie_pme_probe,
.suspend = pcie_pme_suspend,
.resume = pcie_pme_resume,
.remove = pcie_pme_remove,
};
/**
* pcie_pme_service_init - Register the PCIe PME service driver.
*/
static int __init pcie_pme_service_init(void)
{
return pcie_port_service_register(&pcie_pme_driver);
}
module_init(pcie_pme_service_init);
| gpl-2.0 |
DerArtem/android_kernel_dell_streak7 | arch/sparc/kernel/process_32.c | 381 | 19087 | /* linux/arch/sparc/kernel/process.c
*
* Copyright (C) 1995, 2008 David S. Miller (davem@davemloft.net)
* Copyright (C) 1996 Eddie C. Dost (ecd@skynet.be)
*/
/*
* This file handles the architecture-dependent parts of process handling..
*/
#include <stdarg.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/stddef.h>
#include <linux/ptrace.h>
#include <linux/user.h>
#include <linux/smp.h>
#include <linux/reboot.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <asm/auxio.h>
#include <asm/oplib.h>
#include <asm/uaccess.h>
#include <asm/system.h>
#include <asm/page.h>
#include <asm/pgalloc.h>
#include <asm/pgtable.h>
#include <asm/delay.h>
#include <asm/processor.h>
#include <asm/psr.h>
#include <asm/elf.h>
#include <asm/prom.h>
#include <asm/unistd.h>
/*
* Power management idle function
* Set in pm platform drivers (apc.c and pmc.c)
*/
void (*pm_idle)(void);
EXPORT_SYMBOL(pm_idle);
/*
* Power-off handler instantiation for pm.h compliance
* This is done via auxio, but could be used as a fallback
* handler when auxio is not present-- unused for now...
*/
void (*pm_power_off)(void) = machine_power_off;
EXPORT_SYMBOL(pm_power_off);
/*
* sysctl - toggle power-off restriction for serial console
* systems in machine_power_off()
*/
int scons_pwroff = 1;
extern void fpsave(unsigned long *, unsigned long *, void *, unsigned long *);
struct task_struct *last_task_used_math = NULL;
struct thread_info *current_set[NR_CPUS];
#ifndef CONFIG_SMP
#define SUN4C_FAULT_HIGH 100
/*
* the idle loop on a Sparc... ;)
*/
void cpu_idle(void)
{
/* endless idle loop with no priority at all */
for (;;) {
if (ARCH_SUN4C) {
static int count = HZ;
static unsigned long last_jiffies;
static unsigned long last_faults;
static unsigned long fps;
unsigned long now;
unsigned long faults;
extern unsigned long sun4c_kernel_faults;
extern void sun4c_grow_kernel_ring(void);
local_irq_disable();
now = jiffies;
count -= (now - last_jiffies);
last_jiffies = now;
if (count < 0) {
count += HZ;
faults = sun4c_kernel_faults;
fps = (fps + (faults - last_faults)) >> 1;
last_faults = faults;
#if 0
printk("kernel faults / second = %ld\n", fps);
#endif
if (fps >= SUN4C_FAULT_HIGH) {
sun4c_grow_kernel_ring();
}
}
local_irq_enable();
}
if (pm_idle) {
while (!need_resched())
(*pm_idle)();
} else {
while (!need_resched())
cpu_relax();
}
preempt_enable_no_resched();
schedule();
preempt_disable();
check_pgt_cache();
}
}
#else
/* This is being executed in task 0 'user space'. */
void cpu_idle(void)
{
set_thread_flag(TIF_POLLING_NRFLAG);
/* endless idle loop with no priority at all */
while(1) {
while (!need_resched())
cpu_relax();
preempt_enable_no_resched();
schedule();
preempt_disable();
check_pgt_cache();
}
}
#endif
/* XXX cli/sti -> local_irq_xxx here, check this works once SMP is fixed. */
void machine_halt(void)
{
local_irq_enable();
mdelay(8);
local_irq_disable();
prom_halt();
panic("Halt failed!");
}
void machine_restart(char * cmd)
{
char *p;
local_irq_enable();
mdelay(8);
local_irq_disable();
p = strchr (reboot_command, '\n');
if (p) *p = 0;
if (cmd)
prom_reboot(cmd);
if (*reboot_command)
prom_reboot(reboot_command);
prom_feval ("reset");
panic("Reboot failed!");
}
void machine_power_off(void)
{
if (auxio_power_register &&
(strcmp(of_console_device->type, "serial") || scons_pwroff))
*auxio_power_register |= AUXIO_POWER_OFF;
machine_halt();
}
#if 0
static DEFINE_SPINLOCK(sparc_backtrace_lock);
void __show_backtrace(unsigned long fp)
{
struct reg_window32 *rw;
unsigned long flags;
int cpu = smp_processor_id();
spin_lock_irqsave(&sparc_backtrace_lock, flags);
rw = (struct reg_window32 *)fp;
while(rw && (((unsigned long) rw) >= PAGE_OFFSET) &&
!(((unsigned long) rw) & 0x7)) {
printk("CPU[%d]: ARGS[%08lx,%08lx,%08lx,%08lx,%08lx,%08lx] "
"FP[%08lx] CALLER[%08lx]: ", cpu,
rw->ins[0], rw->ins[1], rw->ins[2], rw->ins[3],
rw->ins[4], rw->ins[5],
rw->ins[6],
rw->ins[7]);
printk("%pS\n", (void *) rw->ins[7]);
rw = (struct reg_window32 *) rw->ins[6];
}
spin_unlock_irqrestore(&sparc_backtrace_lock, flags);
}
#define __SAVE __asm__ __volatile__("save %sp, -0x40, %sp\n\t")
#define __RESTORE __asm__ __volatile__("restore %g0, %g0, %g0\n\t")
#define __GET_FP(fp) __asm__ __volatile__("mov %%i6, %0" : "=r" (fp))
void show_backtrace(void)
{
unsigned long fp;
__SAVE; __SAVE; __SAVE; __SAVE;
__SAVE; __SAVE; __SAVE; __SAVE;
__RESTORE; __RESTORE; __RESTORE; __RESTORE;
__RESTORE; __RESTORE; __RESTORE; __RESTORE;
__GET_FP(fp);
__show_backtrace(fp);
}
#ifdef CONFIG_SMP
void smp_show_backtrace_all_cpus(void)
{
xc0((smpfunc_t) show_backtrace);
show_backtrace();
}
#endif
void show_stackframe(struct sparc_stackf *sf)
{
unsigned long size;
unsigned long *stk;
int i;
printk("l0: %08lx l1: %08lx l2: %08lx l3: %08lx "
"l4: %08lx l5: %08lx l6: %08lx l7: %08lx\n",
sf->locals[0], sf->locals[1], sf->locals[2], sf->locals[3],
sf->locals[4], sf->locals[5], sf->locals[6], sf->locals[7]);
printk("i0: %08lx i1: %08lx i2: %08lx i3: %08lx "
"i4: %08lx i5: %08lx fp: %08lx i7: %08lx\n",
sf->ins[0], sf->ins[1], sf->ins[2], sf->ins[3],
sf->ins[4], sf->ins[5], (unsigned long)sf->fp, sf->callers_pc);
printk("sp: %08lx x0: %08lx x1: %08lx x2: %08lx "
"x3: %08lx x4: %08lx x5: %08lx xx: %08lx\n",
(unsigned long)sf->structptr, sf->xargs[0], sf->xargs[1],
sf->xargs[2], sf->xargs[3], sf->xargs[4], sf->xargs[5],
sf->xxargs[0]);
size = ((unsigned long)sf->fp) - ((unsigned long)sf);
size -= STACKFRAME_SZ;
stk = (unsigned long *)((unsigned long)sf + STACKFRAME_SZ);
i = 0;
do {
printk("s%d: %08lx\n", i++, *stk++);
} while ((size -= sizeof(unsigned long)));
}
#endif
void show_regs(struct pt_regs *r)
{
struct reg_window32 *rw = (struct reg_window32 *) r->u_regs[14];
printk("PSR: %08lx PC: %08lx NPC: %08lx Y: %08lx %s\n",
r->psr, r->pc, r->npc, r->y, print_tainted());
printk("PC: <%pS>\n", (void *) r->pc);
printk("%%G: %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
r->u_regs[0], r->u_regs[1], r->u_regs[2], r->u_regs[3],
r->u_regs[4], r->u_regs[5], r->u_regs[6], r->u_regs[7]);
printk("%%O: %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
r->u_regs[8], r->u_regs[9], r->u_regs[10], r->u_regs[11],
r->u_regs[12], r->u_regs[13], r->u_regs[14], r->u_regs[15]);
printk("RPC: <%pS>\n", (void *) r->u_regs[15]);
printk("%%L: %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
rw->locals[0], rw->locals[1], rw->locals[2], rw->locals[3],
rw->locals[4], rw->locals[5], rw->locals[6], rw->locals[7]);
printk("%%I: %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
rw->ins[0], rw->ins[1], rw->ins[2], rw->ins[3],
rw->ins[4], rw->ins[5], rw->ins[6], rw->ins[7]);
}
/*
* The show_stack is an external API which we do not use ourselves.
* The oops is printed in die_if_kernel.
*/
void show_stack(struct task_struct *tsk, unsigned long *_ksp)
{
unsigned long pc, fp;
unsigned long task_base;
struct reg_window32 *rw;
int count = 0;
if (tsk != NULL)
task_base = (unsigned long) task_stack_page(tsk);
else
task_base = (unsigned long) current_thread_info();
fp = (unsigned long) _ksp;
do {
/* Bogus frame pointer? */
if (fp < (task_base + sizeof(struct thread_info)) ||
fp >= (task_base + (PAGE_SIZE << 1)))
break;
rw = (struct reg_window32 *) fp;
pc = rw->ins[7];
printk("[%08lx : ", pc);
printk("%pS ] ", (void *) pc);
fp = rw->ins[6];
} while (++count < 16);
printk("\n");
}
void dump_stack(void)
{
unsigned long *ksp;
__asm__ __volatile__("mov %%fp, %0"
: "=r" (ksp));
show_stack(current, ksp);
}
EXPORT_SYMBOL(dump_stack);
/*
* Note: sparc64 has a pretty intricated thread_saved_pc, check it out.
*/
unsigned long thread_saved_pc(struct task_struct *tsk)
{
return task_thread_info(tsk)->kpc;
}
/*
* Free current thread data structures etc..
*/
void exit_thread(void)
{
#ifndef CONFIG_SMP
if(last_task_used_math == current) {
#else
if (test_thread_flag(TIF_USEDFPU)) {
#endif
/* Keep process from leaving FPU in a bogon state. */
put_psr(get_psr() | PSR_EF);
fpsave(¤t->thread.float_regs[0], ¤t->thread.fsr,
¤t->thread.fpqueue[0], ¤t->thread.fpqdepth);
#ifndef CONFIG_SMP
last_task_used_math = NULL;
#else
clear_thread_flag(TIF_USEDFPU);
#endif
}
}
void flush_thread(void)
{
current_thread_info()->w_saved = 0;
#ifndef CONFIG_SMP
if(last_task_used_math == current) {
#else
if (test_thread_flag(TIF_USEDFPU)) {
#endif
/* Clean the fpu. */
put_psr(get_psr() | PSR_EF);
fpsave(¤t->thread.float_regs[0], ¤t->thread.fsr,
¤t->thread.fpqueue[0], ¤t->thread.fpqdepth);
#ifndef CONFIG_SMP
last_task_used_math = NULL;
#else
clear_thread_flag(TIF_USEDFPU);
#endif
}
/* Now, this task is no longer a kernel thread. */
current->thread.current_ds = USER_DS;
if (current->thread.flags & SPARC_FLAG_KTHREAD) {
current->thread.flags &= ~SPARC_FLAG_KTHREAD;
/* We must fixup kregs as well. */
/* XXX This was not fixed for ti for a while, worked. Unused? */
current->thread.kregs = (struct pt_regs *)
(task_stack_page(current) + (THREAD_SIZE - TRACEREG_SZ));
}
}
static inline struct sparc_stackf __user *
clone_stackframe(struct sparc_stackf __user *dst,
struct sparc_stackf __user *src)
{
unsigned long size, fp;
struct sparc_stackf *tmp;
struct sparc_stackf __user *sp;
if (get_user(tmp, &src->fp))
return NULL;
fp = (unsigned long) tmp;
size = (fp - ((unsigned long) src));
fp = (unsigned long) dst;
sp = (struct sparc_stackf __user *)(fp - size);
/* do_fork() grabs the parent semaphore, we must release it
* temporarily so we can build the child clone stack frame
* without deadlocking.
*/
if (__copy_user(sp, src, size))
sp = NULL;
else if (put_user(fp, &sp->fp))
sp = NULL;
return sp;
}
asmlinkage int sparc_do_fork(unsigned long clone_flags,
unsigned long stack_start,
struct pt_regs *regs,
unsigned long stack_size)
{
unsigned long parent_tid_ptr, child_tid_ptr;
unsigned long orig_i1 = regs->u_regs[UREG_I1];
long ret;
parent_tid_ptr = regs->u_regs[UREG_I2];
child_tid_ptr = regs->u_regs[UREG_I4];
ret = do_fork(clone_flags, stack_start,
regs, stack_size,
(int __user *) parent_tid_ptr,
(int __user *) child_tid_ptr);
/* If we get an error and potentially restart the system
* call, we're screwed because copy_thread() clobbered
* the parent's %o1. So detect that case and restore it
* here.
*/
if ((unsigned long)ret >= -ERESTART_RESTARTBLOCK)
regs->u_regs[UREG_I1] = orig_i1;
return ret;
}
/* Copy a Sparc thread. The fork() return value conventions
* under SunOS are nothing short of bletcherous:
* Parent --> %o0 == childs pid, %o1 == 0
* Child --> %o0 == parents pid, %o1 == 1
*
* NOTE: We have a separate fork kpsr/kwim because
* the parent could change these values between
* sys_fork invocation and when we reach here
* if the parent should sleep while trying to
* allocate the task_struct and kernel stack in
* do_fork().
* XXX See comment above sys_vfork in sparc64. todo.
*/
extern void ret_from_fork(void);
int copy_thread(unsigned long clone_flags, unsigned long sp,
unsigned long unused,
struct task_struct *p, struct pt_regs *regs)
{
struct thread_info *ti = task_thread_info(p);
struct pt_regs *childregs;
char *new_stack;
#ifndef CONFIG_SMP
if(last_task_used_math == current) {
#else
if (test_thread_flag(TIF_USEDFPU)) {
#endif
put_psr(get_psr() | PSR_EF);
fpsave(&p->thread.float_regs[0], &p->thread.fsr,
&p->thread.fpqueue[0], &p->thread.fpqdepth);
#ifdef CONFIG_SMP
clear_thread_flag(TIF_USEDFPU);
#endif
}
/*
* p->thread_info new_stack childregs
* ! ! ! {if(PSR_PS) }
* V V (stk.fr.) V (pt_regs) { (stk.fr.) }
* +----- - - - - - ------+===========+============={+==========}+
*/
new_stack = task_stack_page(p) + THREAD_SIZE;
if (regs->psr & PSR_PS)
new_stack -= STACKFRAME_SZ;
new_stack -= STACKFRAME_SZ + TRACEREG_SZ;
memcpy(new_stack, (char *)regs - STACKFRAME_SZ, STACKFRAME_SZ + TRACEREG_SZ);
childregs = (struct pt_regs *) (new_stack + STACKFRAME_SZ);
/*
* A new process must start with interrupts closed in 2.5,
* because this is how Mingo's scheduler works (see schedule_tail
* and finish_arch_switch). If we do not do it, a timer interrupt hits
* before we unlock, attempts to re-take the rq->lock, and then we die.
* Thus, kpsr|=PSR_PIL.
*/
ti->ksp = (unsigned long) new_stack;
ti->kpc = (((unsigned long) ret_from_fork) - 0x8);
ti->kpsr = current->thread.fork_kpsr | PSR_PIL;
ti->kwim = current->thread.fork_kwim;
if(regs->psr & PSR_PS) {
extern struct pt_regs fake_swapper_regs;
p->thread.kregs = &fake_swapper_regs;
new_stack += STACKFRAME_SZ + TRACEREG_SZ;
childregs->u_regs[UREG_FP] = (unsigned long) new_stack;
p->thread.flags |= SPARC_FLAG_KTHREAD;
p->thread.current_ds = KERNEL_DS;
memcpy(new_stack, (void *)regs->u_regs[UREG_FP], STACKFRAME_SZ);
childregs->u_regs[UREG_G6] = (unsigned long) ti;
} else {
p->thread.kregs = childregs;
childregs->u_regs[UREG_FP] = sp;
p->thread.flags &= ~SPARC_FLAG_KTHREAD;
p->thread.current_ds = USER_DS;
if (sp != regs->u_regs[UREG_FP]) {
struct sparc_stackf __user *childstack;
struct sparc_stackf __user *parentstack;
/*
* This is a clone() call with supplied user stack.
* Set some valid stack frames to give to the child.
*/
childstack = (struct sparc_stackf __user *)
(sp & ~0xfUL);
parentstack = (struct sparc_stackf __user *)
regs->u_regs[UREG_FP];
#if 0
printk("clone: parent stack:\n");
show_stackframe(parentstack);
#endif
childstack = clone_stackframe(childstack, parentstack);
if (!childstack)
return -EFAULT;
#if 0
printk("clone: child stack:\n");
show_stackframe(childstack);
#endif
childregs->u_regs[UREG_FP] = (unsigned long)childstack;
}
}
#ifdef CONFIG_SMP
/* FPU must be disabled on SMP. */
childregs->psr &= ~PSR_EF;
#endif
/* Set the return value for the child. */
childregs->u_regs[UREG_I0] = current->pid;
childregs->u_regs[UREG_I1] = 1;
/* Set the return value for the parent. */
regs->u_regs[UREG_I1] = 0;
if (clone_flags & CLONE_SETTLS)
childregs->u_regs[UREG_G7] = regs->u_regs[UREG_I3];
return 0;
}
/*
* fill in the fpu structure for a core dump.
*/
int dump_fpu (struct pt_regs * regs, elf_fpregset_t * fpregs)
{
if (used_math()) {
memset(fpregs, 0, sizeof(*fpregs));
fpregs->pr_q_entrysize = 8;
return 1;
}
#ifdef CONFIG_SMP
if (test_thread_flag(TIF_USEDFPU)) {
put_psr(get_psr() | PSR_EF);
fpsave(¤t->thread.float_regs[0], ¤t->thread.fsr,
¤t->thread.fpqueue[0], ¤t->thread.fpqdepth);
if (regs != NULL) {
regs->psr &= ~(PSR_EF);
clear_thread_flag(TIF_USEDFPU);
}
}
#else
if (current == last_task_used_math) {
put_psr(get_psr() | PSR_EF);
fpsave(¤t->thread.float_regs[0], ¤t->thread.fsr,
¤t->thread.fpqueue[0], ¤t->thread.fpqdepth);
if (regs != NULL) {
regs->psr &= ~(PSR_EF);
last_task_used_math = NULL;
}
}
#endif
memcpy(&fpregs->pr_fr.pr_regs[0],
¤t->thread.float_regs[0],
(sizeof(unsigned long) * 32));
fpregs->pr_fsr = current->thread.fsr;
fpregs->pr_qcnt = current->thread.fpqdepth;
fpregs->pr_q_entrysize = 8;
fpregs->pr_en = 1;
if(fpregs->pr_qcnt != 0) {
memcpy(&fpregs->pr_q[0],
¤t->thread.fpqueue[0],
sizeof(struct fpq) * fpregs->pr_qcnt);
}
/* Zero out the rest. */
memset(&fpregs->pr_q[fpregs->pr_qcnt], 0,
sizeof(struct fpq) * (32 - fpregs->pr_qcnt));
return 1;
}
/*
* sparc_execve() executes a new program after the asm stub has set
* things up for us. This should basically do what I want it to.
*/
asmlinkage int sparc_execve(struct pt_regs *regs)
{
int error, base = 0;
char *filename;
/* Check for indirect call. */
if(regs->u_regs[UREG_G1] == 0)
base = 1;
filename = getname((char __user *)regs->u_regs[base + UREG_I0]);
error = PTR_ERR(filename);
if(IS_ERR(filename))
goto out;
error = do_execve(filename,
(const char __user *const __user *)
regs->u_regs[base + UREG_I1],
(const char __user *const __user *)
regs->u_regs[base + UREG_I2],
regs);
putname(filename);
out:
return error;
}
/*
* This is the mechanism for creating a new kernel thread.
*
* NOTE! Only a kernel-only process(ie the swapper or direct descendants
* who haven't done an "execve()") should use this: it will work within
* a system call from a "real" process, but the process memory space will
* not be freed until both the parent and the child have exited.
*/
pid_t kernel_thread(int (*fn)(void *), void * arg, unsigned long flags)
{
long retval;
__asm__ __volatile__("mov %4, %%g2\n\t" /* Set aside fn ptr... */
"mov %5, %%g3\n\t" /* and arg. */
"mov %1, %%g1\n\t"
"mov %2, %%o0\n\t" /* Clone flags. */
"mov 0, %%o1\n\t" /* usp arg == 0 */
"t 0x10\n\t" /* Linux/Sparc clone(). */
"cmp %%o1, 0\n\t"
"be 1f\n\t" /* The parent, just return. */
" nop\n\t" /* Delay slot. */
"jmpl %%g2, %%o7\n\t" /* Call the function. */
" mov %%g3, %%o0\n\t" /* Get back the arg in delay. */
"mov %3, %%g1\n\t"
"t 0x10\n\t" /* Linux/Sparc exit(). */
/* Notreached by child. */
"1: mov %%o0, %0\n\t" :
"=r" (retval) :
"i" (__NR_clone), "r" (flags | CLONE_VM | CLONE_UNTRACED),
"i" (__NR_exit), "r" (fn), "r" (arg) :
"g1", "g2", "g3", "o0", "o1", "memory", "cc");
return retval;
}
EXPORT_SYMBOL(kernel_thread);
unsigned long get_wchan(struct task_struct *task)
{
unsigned long pc, fp, bias = 0;
unsigned long task_base = (unsigned long) task;
unsigned long ret = 0;
struct reg_window32 *rw;
int count = 0;
if (!task || task == current ||
task->state == TASK_RUNNING)
goto out;
fp = task_thread_info(task)->ksp + bias;
do {
/* Bogus frame pointer? */
if (fp < (task_base + sizeof(struct thread_info)) ||
fp >= (task_base + (2 * PAGE_SIZE)))
break;
rw = (struct reg_window32 *) fp;
pc = rw->ins[7];
if (!in_sched_functions(pc)) {
ret = pc;
goto out;
}
fp = rw->ins[6] + bias;
} while (++count < 16);
out:
return ret;
}
| gpl-2.0 |
AmeriCanAndroid/kernel-android-msm-2.6.35 | net/netfilter/ipvs/ip_vs_sync.c | 893 | 24358 | /*
* IPVS An implementation of the IP virtual server support for the
* LINUX operating system. IPVS is now implemented as a module
* over the NetFilter framework. IPVS can be used to build a
* high-performance and highly available server based on a
* cluster of servers.
*
* Authors: Wensong Zhang <wensong@linuxvirtualserver.org>
*
* ip_vs_sync: sync connection info from master load balancer to backups
* through multicast
*
* Changes:
* Alexandre Cassen : Added master & backup support at a time.
* Alexandre Cassen : Added SyncID support for incoming sync
* messages filtering.
* Justin Ossevoort : Fix endian problem on sync message size.
*/
#define KMSG_COMPONENT "IPVS"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/inetdevice.h>
#include <linux/net.h>
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/skbuff.h>
#include <linux/in.h>
#include <linux/igmp.h> /* for ip_mc_join_group */
#include <linux/udp.h>
#include <linux/err.h>
#include <linux/kthread.h>
#include <linux/wait.h>
#include <linux/kernel.h>
#include <net/ip.h>
#include <net/sock.h>
#include <net/ip_vs.h>
#define IP_VS_SYNC_GROUP 0xe0000051 /* multicast addr - 224.0.0.81 */
#define IP_VS_SYNC_PORT 8848 /* multicast port */
/*
* IPVS sync connection entry
*/
struct ip_vs_sync_conn {
__u8 reserved;
/* Protocol, addresses and port numbers */
__u8 protocol; /* Which protocol (TCP/UDP) */
__be16 cport;
__be16 vport;
__be16 dport;
__be32 caddr; /* client address */
__be32 vaddr; /* virtual address */
__be32 daddr; /* destination address */
/* Flags and state transition */
__be16 flags; /* status flags */
__be16 state; /* state info */
/* The sequence options start here */
};
struct ip_vs_sync_conn_options {
struct ip_vs_seq in_seq; /* incoming seq. struct */
struct ip_vs_seq out_seq; /* outgoing seq. struct */
};
struct ip_vs_sync_thread_data {
struct socket *sock;
char *buf;
};
#define SIMPLE_CONN_SIZE (sizeof(struct ip_vs_sync_conn))
#define FULL_CONN_SIZE \
(sizeof(struct ip_vs_sync_conn) + sizeof(struct ip_vs_sync_conn_options))
/*
The master mulitcasts messages to the backup load balancers in the
following format.
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Count Conns | SyncID | Size |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
| IPVS Sync Connection (1) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| . |
| . |
| . |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
| IPVS Sync Connection (n) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
#define SYNC_MESG_HEADER_LEN 4
#define MAX_CONNS_PER_SYNCBUFF 255 /* nr_conns in ip_vs_sync_mesg is 8 bit */
struct ip_vs_sync_mesg {
__u8 nr_conns;
__u8 syncid;
__u16 size;
/* ip_vs_sync_conn entries start here */
};
/* the maximum length of sync (sending/receiving) message */
static int sync_send_mesg_maxlen;
static int sync_recv_mesg_maxlen;
struct ip_vs_sync_buff {
struct list_head list;
unsigned long firstuse;
/* pointers for the message data */
struct ip_vs_sync_mesg *mesg;
unsigned char *head;
unsigned char *end;
};
/* the sync_buff list head and the lock */
static LIST_HEAD(ip_vs_sync_queue);
static DEFINE_SPINLOCK(ip_vs_sync_lock);
/* current sync_buff for accepting new conn entries */
static struct ip_vs_sync_buff *curr_sb = NULL;
static DEFINE_SPINLOCK(curr_sb_lock);
/* ipvs sync daemon state */
volatile int ip_vs_sync_state = IP_VS_STATE_NONE;
volatile int ip_vs_master_syncid = 0;
volatile int ip_vs_backup_syncid = 0;
/* multicast interface name */
char ip_vs_master_mcast_ifn[IP_VS_IFNAME_MAXLEN];
char ip_vs_backup_mcast_ifn[IP_VS_IFNAME_MAXLEN];
/* sync daemon tasks */
static struct task_struct *sync_master_thread;
static struct task_struct *sync_backup_thread;
/* multicast addr */
static struct sockaddr_in mcast_addr = {
.sin_family = AF_INET,
.sin_port = cpu_to_be16(IP_VS_SYNC_PORT),
.sin_addr.s_addr = cpu_to_be32(IP_VS_SYNC_GROUP),
};
static inline struct ip_vs_sync_buff *sb_dequeue(void)
{
struct ip_vs_sync_buff *sb;
spin_lock_bh(&ip_vs_sync_lock);
if (list_empty(&ip_vs_sync_queue)) {
sb = NULL;
} else {
sb = list_entry(ip_vs_sync_queue.next,
struct ip_vs_sync_buff,
list);
list_del(&sb->list);
}
spin_unlock_bh(&ip_vs_sync_lock);
return sb;
}
static inline struct ip_vs_sync_buff * ip_vs_sync_buff_create(void)
{
struct ip_vs_sync_buff *sb;
if (!(sb=kmalloc(sizeof(struct ip_vs_sync_buff), GFP_ATOMIC)))
return NULL;
if (!(sb->mesg=kmalloc(sync_send_mesg_maxlen, GFP_ATOMIC))) {
kfree(sb);
return NULL;
}
sb->mesg->nr_conns = 0;
sb->mesg->syncid = ip_vs_master_syncid;
sb->mesg->size = 4;
sb->head = (unsigned char *)sb->mesg + 4;
sb->end = (unsigned char *)sb->mesg + sync_send_mesg_maxlen;
sb->firstuse = jiffies;
return sb;
}
static inline void ip_vs_sync_buff_release(struct ip_vs_sync_buff *sb)
{
kfree(sb->mesg);
kfree(sb);
}
static inline void sb_queue_tail(struct ip_vs_sync_buff *sb)
{
spin_lock(&ip_vs_sync_lock);
if (ip_vs_sync_state & IP_VS_STATE_MASTER)
list_add_tail(&sb->list, &ip_vs_sync_queue);
else
ip_vs_sync_buff_release(sb);
spin_unlock(&ip_vs_sync_lock);
}
/*
* Get the current sync buffer if it has been created for more
* than the specified time or the specified time is zero.
*/
static inline struct ip_vs_sync_buff *
get_curr_sync_buff(unsigned long time)
{
struct ip_vs_sync_buff *sb;
spin_lock_bh(&curr_sb_lock);
if (curr_sb && (time == 0 ||
time_before(jiffies - curr_sb->firstuse, time))) {
sb = curr_sb;
curr_sb = NULL;
} else
sb = NULL;
spin_unlock_bh(&curr_sb_lock);
return sb;
}
/*
* Add an ip_vs_conn information into the current sync_buff.
* Called by ip_vs_in.
*/
void ip_vs_sync_conn(struct ip_vs_conn *cp)
{
struct ip_vs_sync_mesg *m;
struct ip_vs_sync_conn *s;
int len;
spin_lock(&curr_sb_lock);
if (!curr_sb) {
if (!(curr_sb=ip_vs_sync_buff_create())) {
spin_unlock(&curr_sb_lock);
pr_err("ip_vs_sync_buff_create failed.\n");
return;
}
}
len = (cp->flags & IP_VS_CONN_F_SEQ_MASK) ? FULL_CONN_SIZE :
SIMPLE_CONN_SIZE;
m = curr_sb->mesg;
s = (struct ip_vs_sync_conn *)curr_sb->head;
/* copy members */
s->protocol = cp->protocol;
s->cport = cp->cport;
s->vport = cp->vport;
s->dport = cp->dport;
s->caddr = cp->caddr.ip;
s->vaddr = cp->vaddr.ip;
s->daddr = cp->daddr.ip;
s->flags = htons(cp->flags & ~IP_VS_CONN_F_HASHED);
s->state = htons(cp->state);
if (cp->flags & IP_VS_CONN_F_SEQ_MASK) {
struct ip_vs_sync_conn_options *opt =
(struct ip_vs_sync_conn_options *)&s[1];
memcpy(opt, &cp->in_seq, sizeof(*opt));
}
m->nr_conns++;
m->size += len;
curr_sb->head += len;
/* check if there is a space for next one */
if (curr_sb->head+FULL_CONN_SIZE > curr_sb->end) {
sb_queue_tail(curr_sb);
curr_sb = NULL;
}
spin_unlock(&curr_sb_lock);
/* synchronize its controller if it has */
if (cp->control)
ip_vs_sync_conn(cp->control);
}
/*
* Process received multicast message and create the corresponding
* ip_vs_conn entries.
*/
static void ip_vs_process_message(const char *buffer, const size_t buflen)
{
struct ip_vs_sync_mesg *m = (struct ip_vs_sync_mesg *)buffer;
struct ip_vs_sync_conn *s;
struct ip_vs_sync_conn_options *opt;
struct ip_vs_conn *cp;
struct ip_vs_protocol *pp;
struct ip_vs_dest *dest;
char *p;
int i;
if (buflen < sizeof(struct ip_vs_sync_mesg)) {
IP_VS_ERR_RL("sync message header too short\n");
return;
}
/* Convert size back to host byte order */
m->size = ntohs(m->size);
if (buflen != m->size) {
IP_VS_ERR_RL("bogus sync message size\n");
return;
}
/* SyncID sanity check */
if (ip_vs_backup_syncid != 0 && m->syncid != ip_vs_backup_syncid) {
IP_VS_DBG(7, "Ignoring incoming msg with syncid = %d\n",
m->syncid);
return;
}
p = (char *)buffer + sizeof(struct ip_vs_sync_mesg);
for (i=0; i<m->nr_conns; i++) {
unsigned flags, state;
if (p + SIMPLE_CONN_SIZE > buffer+buflen) {
IP_VS_ERR_RL("bogus conn in sync message\n");
return;
}
s = (struct ip_vs_sync_conn *) p;
flags = ntohs(s->flags) | IP_VS_CONN_F_SYNC;
flags &= ~IP_VS_CONN_F_HASHED;
if (flags & IP_VS_CONN_F_SEQ_MASK) {
opt = (struct ip_vs_sync_conn_options *)&s[1];
p += FULL_CONN_SIZE;
if (p > buffer+buflen) {
IP_VS_ERR_RL("bogus conn options in sync message\n");
return;
}
} else {
opt = NULL;
p += SIMPLE_CONN_SIZE;
}
state = ntohs(s->state);
if (!(flags & IP_VS_CONN_F_TEMPLATE)) {
pp = ip_vs_proto_get(s->protocol);
if (!pp) {
IP_VS_ERR_RL("Unsupported protocol %u in sync msg\n",
s->protocol);
continue;
}
if (state >= pp->num_states) {
IP_VS_DBG(2, "Invalid %s state %u in sync msg\n",
pp->name, state);
continue;
}
} else {
/* protocol in templates is not used for state/timeout */
pp = NULL;
if (state > 0) {
IP_VS_DBG(2, "Invalid template state %u in sync msg\n",
state);
state = 0;
}
}
if (!(flags & IP_VS_CONN_F_TEMPLATE))
cp = ip_vs_conn_in_get(AF_INET, s->protocol,
(union nf_inet_addr *)&s->caddr,
s->cport,
(union nf_inet_addr *)&s->vaddr,
s->vport);
else
cp = ip_vs_ct_in_get(AF_INET, s->protocol,
(union nf_inet_addr *)&s->caddr,
s->cport,
(union nf_inet_addr *)&s->vaddr,
s->vport);
if (!cp) {
/*
* Find the appropriate destination for the connection.
* If it is not found the connection will remain unbound
* but still handled.
*/
dest = ip_vs_find_dest(AF_INET,
(union nf_inet_addr *)&s->daddr,
s->dport,
(union nf_inet_addr *)&s->vaddr,
s->vport,
s->protocol);
/* Set the approprite ativity flag */
if (s->protocol == IPPROTO_TCP) {
if (state != IP_VS_TCP_S_ESTABLISHED)
flags |= IP_VS_CONN_F_INACTIVE;
else
flags &= ~IP_VS_CONN_F_INACTIVE;
} else if (s->protocol == IPPROTO_SCTP) {
if (state != IP_VS_SCTP_S_ESTABLISHED)
flags |= IP_VS_CONN_F_INACTIVE;
else
flags &= ~IP_VS_CONN_F_INACTIVE;
}
cp = ip_vs_conn_new(AF_INET, s->protocol,
(union nf_inet_addr *)&s->caddr,
s->cport,
(union nf_inet_addr *)&s->vaddr,
s->vport,
(union nf_inet_addr *)&s->daddr,
s->dport,
flags, dest);
if (dest)
atomic_dec(&dest->refcnt);
if (!cp) {
pr_err("ip_vs_conn_new failed\n");
return;
}
} else if (!cp->dest) {
dest = ip_vs_try_bind_dest(cp);
if (dest)
atomic_dec(&dest->refcnt);
} else if ((cp->dest) && (cp->protocol == IPPROTO_TCP) &&
(cp->state != state)) {
/* update active/inactive flag for the connection */
dest = cp->dest;
if (!(cp->flags & IP_VS_CONN_F_INACTIVE) &&
(state != IP_VS_TCP_S_ESTABLISHED)) {
atomic_dec(&dest->activeconns);
atomic_inc(&dest->inactconns);
cp->flags |= IP_VS_CONN_F_INACTIVE;
} else if ((cp->flags & IP_VS_CONN_F_INACTIVE) &&
(state == IP_VS_TCP_S_ESTABLISHED)) {
atomic_inc(&dest->activeconns);
atomic_dec(&dest->inactconns);
cp->flags &= ~IP_VS_CONN_F_INACTIVE;
}
} else if ((cp->dest) && (cp->protocol == IPPROTO_SCTP) &&
(cp->state != state)) {
dest = cp->dest;
if (!(cp->flags & IP_VS_CONN_F_INACTIVE) &&
(state != IP_VS_SCTP_S_ESTABLISHED)) {
atomic_dec(&dest->activeconns);
atomic_inc(&dest->inactconns);
cp->flags &= ~IP_VS_CONN_F_INACTIVE;
}
}
if (opt)
memcpy(&cp->in_seq, opt, sizeof(*opt));
atomic_set(&cp->in_pkts, sysctl_ip_vs_sync_threshold[0]);
cp->state = state;
cp->old_state = cp->state;
/*
* We can not recover the right timeout for templates
* in all cases, we can not find the right fwmark
* virtual service. If needed, we can do it for
* non-fwmark persistent services.
*/
if (!(flags & IP_VS_CONN_F_TEMPLATE) && pp->timeout_table)
cp->timeout = pp->timeout_table[state];
else
cp->timeout = (3*60*HZ);
ip_vs_conn_put(cp);
}
}
/*
* Setup loopback of outgoing multicasts on a sending socket
*/
static void set_mcast_loop(struct sock *sk, u_char loop)
{
struct inet_sock *inet = inet_sk(sk);
/* setsockopt(sock, SOL_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); */
lock_sock(sk);
inet->mc_loop = loop ? 1 : 0;
release_sock(sk);
}
/*
* Specify TTL for outgoing multicasts on a sending socket
*/
static void set_mcast_ttl(struct sock *sk, u_char ttl)
{
struct inet_sock *inet = inet_sk(sk);
/* setsockopt(sock, SOL_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); */
lock_sock(sk);
inet->mc_ttl = ttl;
release_sock(sk);
}
/*
* Specifiy default interface for outgoing multicasts
*/
static int set_mcast_if(struct sock *sk, char *ifname)
{
struct net_device *dev;
struct inet_sock *inet = inet_sk(sk);
if ((dev = __dev_get_by_name(&init_net, ifname)) == NULL)
return -ENODEV;
if (sk->sk_bound_dev_if && dev->ifindex != sk->sk_bound_dev_if)
return -EINVAL;
lock_sock(sk);
inet->mc_index = dev->ifindex;
/* inet->mc_addr = 0; */
release_sock(sk);
return 0;
}
/*
* Set the maximum length of sync message according to the
* specified interface's MTU.
*/
static int set_sync_mesg_maxlen(int sync_state)
{
struct net_device *dev;
int num;
if (sync_state == IP_VS_STATE_MASTER) {
if ((dev = __dev_get_by_name(&init_net, ip_vs_master_mcast_ifn)) == NULL)
return -ENODEV;
num = (dev->mtu - sizeof(struct iphdr) -
sizeof(struct udphdr) -
SYNC_MESG_HEADER_LEN - 20) / SIMPLE_CONN_SIZE;
sync_send_mesg_maxlen = SYNC_MESG_HEADER_LEN +
SIMPLE_CONN_SIZE * min(num, MAX_CONNS_PER_SYNCBUFF);
IP_VS_DBG(7, "setting the maximum length of sync sending "
"message %d.\n", sync_send_mesg_maxlen);
} else if (sync_state == IP_VS_STATE_BACKUP) {
if ((dev = __dev_get_by_name(&init_net, ip_vs_backup_mcast_ifn)) == NULL)
return -ENODEV;
sync_recv_mesg_maxlen = dev->mtu -
sizeof(struct iphdr) - sizeof(struct udphdr);
IP_VS_DBG(7, "setting the maximum length of sync receiving "
"message %d.\n", sync_recv_mesg_maxlen);
}
return 0;
}
/*
* Join a multicast group.
* the group is specified by a class D multicast address 224.0.0.0/8
* in the in_addr structure passed in as a parameter.
*/
static int
join_mcast_group(struct sock *sk, struct in_addr *addr, char *ifname)
{
struct ip_mreqn mreq;
struct net_device *dev;
int ret;
memset(&mreq, 0, sizeof(mreq));
memcpy(&mreq.imr_multiaddr, addr, sizeof(struct in_addr));
if ((dev = __dev_get_by_name(&init_net, ifname)) == NULL)
return -ENODEV;
if (sk->sk_bound_dev_if && dev->ifindex != sk->sk_bound_dev_if)
return -EINVAL;
mreq.imr_ifindex = dev->ifindex;
lock_sock(sk);
ret = ip_mc_join_group(sk, &mreq);
release_sock(sk);
return ret;
}
static int bind_mcastif_addr(struct socket *sock, char *ifname)
{
struct net_device *dev;
__be32 addr;
struct sockaddr_in sin;
if ((dev = __dev_get_by_name(&init_net, ifname)) == NULL)
return -ENODEV;
addr = inet_select_addr(dev, 0, RT_SCOPE_UNIVERSE);
if (!addr)
pr_err("You probably need to specify IP address on "
"multicast interface.\n");
IP_VS_DBG(7, "binding socket with (%s) %pI4\n",
ifname, &addr);
/* Now bind the socket with the address of multicast interface */
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = addr;
sin.sin_port = 0;
return sock->ops->bind(sock, (struct sockaddr*)&sin, sizeof(sin));
}
/*
* Set up sending multicast socket over UDP
*/
static struct socket * make_send_sock(void)
{
struct socket *sock;
int result;
/* First create a socket */
result = sock_create_kern(PF_INET, SOCK_DGRAM, IPPROTO_UDP, &sock);
if (result < 0) {
pr_err("Error during creation of socket; terminating\n");
return ERR_PTR(result);
}
result = set_mcast_if(sock->sk, ip_vs_master_mcast_ifn);
if (result < 0) {
pr_err("Error setting outbound mcast interface\n");
goto error;
}
set_mcast_loop(sock->sk, 0);
set_mcast_ttl(sock->sk, 1);
result = bind_mcastif_addr(sock, ip_vs_master_mcast_ifn);
if (result < 0) {
pr_err("Error binding address of the mcast interface\n");
goto error;
}
result = sock->ops->connect(sock, (struct sockaddr *) &mcast_addr,
sizeof(struct sockaddr), 0);
if (result < 0) {
pr_err("Error connecting to the multicast addr\n");
goto error;
}
return sock;
error:
sock_release(sock);
return ERR_PTR(result);
}
/*
* Set up receiving multicast socket over UDP
*/
static struct socket * make_receive_sock(void)
{
struct socket *sock;
int result;
/* First create a socket */
result = sock_create_kern(PF_INET, SOCK_DGRAM, IPPROTO_UDP, &sock);
if (result < 0) {
pr_err("Error during creation of socket; terminating\n");
return ERR_PTR(result);
}
/* it is equivalent to the REUSEADDR option in user-space */
sock->sk->sk_reuse = 1;
result = sock->ops->bind(sock, (struct sockaddr *) &mcast_addr,
sizeof(struct sockaddr));
if (result < 0) {
pr_err("Error binding to the multicast addr\n");
goto error;
}
/* join the multicast group */
result = join_mcast_group(sock->sk,
(struct in_addr *) &mcast_addr.sin_addr,
ip_vs_backup_mcast_ifn);
if (result < 0) {
pr_err("Error joining to the multicast group\n");
goto error;
}
return sock;
error:
sock_release(sock);
return ERR_PTR(result);
}
static int
ip_vs_send_async(struct socket *sock, const char *buffer, const size_t length)
{
struct msghdr msg = {.msg_flags = MSG_DONTWAIT|MSG_NOSIGNAL};
struct kvec iov;
int len;
EnterFunction(7);
iov.iov_base = (void *)buffer;
iov.iov_len = length;
len = kernel_sendmsg(sock, &msg, &iov, 1, (size_t)(length));
LeaveFunction(7);
return len;
}
static void
ip_vs_send_sync_msg(struct socket *sock, struct ip_vs_sync_mesg *msg)
{
int msize;
msize = msg->size;
/* Put size in network byte order */
msg->size = htons(msg->size);
if (ip_vs_send_async(sock, (char *)msg, msize) != msize)
pr_err("ip_vs_send_async error\n");
}
static int
ip_vs_receive(struct socket *sock, char *buffer, const size_t buflen)
{
struct msghdr msg = {NULL,};
struct kvec iov;
int len;
EnterFunction(7);
/* Receive a packet */
iov.iov_base = buffer;
iov.iov_len = (size_t)buflen;
len = kernel_recvmsg(sock, &msg, &iov, 1, buflen, 0);
if (len < 0)
return -1;
LeaveFunction(7);
return len;
}
static int sync_thread_master(void *data)
{
struct ip_vs_sync_thread_data *tinfo = data;
struct ip_vs_sync_buff *sb;
pr_info("sync thread started: state = MASTER, mcast_ifn = %s, "
"syncid = %d\n",
ip_vs_master_mcast_ifn, ip_vs_master_syncid);
while (!kthread_should_stop()) {
while ((sb = sb_dequeue())) {
ip_vs_send_sync_msg(tinfo->sock, sb->mesg);
ip_vs_sync_buff_release(sb);
}
/* check if entries stay in curr_sb for 2 seconds */
sb = get_curr_sync_buff(2 * HZ);
if (sb) {
ip_vs_send_sync_msg(tinfo->sock, sb->mesg);
ip_vs_sync_buff_release(sb);
}
schedule_timeout_interruptible(HZ);
}
/* clean up the sync_buff queue */
while ((sb=sb_dequeue())) {
ip_vs_sync_buff_release(sb);
}
/* clean up the current sync_buff */
if ((sb = get_curr_sync_buff(0))) {
ip_vs_sync_buff_release(sb);
}
/* release the sending multicast socket */
sock_release(tinfo->sock);
kfree(tinfo);
return 0;
}
static int sync_thread_backup(void *data)
{
struct ip_vs_sync_thread_data *tinfo = data;
int len;
pr_info("sync thread started: state = BACKUP, mcast_ifn = %s, "
"syncid = %d\n",
ip_vs_backup_mcast_ifn, ip_vs_backup_syncid);
while (!kthread_should_stop()) {
wait_event_interruptible(*sk_sleep(tinfo->sock->sk),
!skb_queue_empty(&tinfo->sock->sk->sk_receive_queue)
|| kthread_should_stop());
/* do we have data now? */
while (!skb_queue_empty(&(tinfo->sock->sk->sk_receive_queue))) {
len = ip_vs_receive(tinfo->sock, tinfo->buf,
sync_recv_mesg_maxlen);
if (len <= 0) {
pr_err("receiving message error\n");
break;
}
/* disable bottom half, because it accesses the data
shared by softirq while getting/creating conns */
local_bh_disable();
ip_vs_process_message(tinfo->buf, len);
local_bh_enable();
}
}
/* release the sending multicast socket */
sock_release(tinfo->sock);
kfree(tinfo->buf);
kfree(tinfo);
return 0;
}
int start_sync_thread(int state, char *mcast_ifn, __u8 syncid)
{
struct ip_vs_sync_thread_data *tinfo;
struct task_struct **realtask, *task;
struct socket *sock;
char *name, *buf = NULL;
int (*threadfn)(void *data);
int result = -ENOMEM;
IP_VS_DBG(7, "%s(): pid %d\n", __func__, task_pid_nr(current));
IP_VS_DBG(7, "Each ip_vs_sync_conn entry needs %Zd bytes\n",
sizeof(struct ip_vs_sync_conn));
if (state == IP_VS_STATE_MASTER) {
if (sync_master_thread)
return -EEXIST;
strlcpy(ip_vs_master_mcast_ifn, mcast_ifn,
sizeof(ip_vs_master_mcast_ifn));
ip_vs_master_syncid = syncid;
realtask = &sync_master_thread;
name = "ipvs_syncmaster";
threadfn = sync_thread_master;
sock = make_send_sock();
} else if (state == IP_VS_STATE_BACKUP) {
if (sync_backup_thread)
return -EEXIST;
strlcpy(ip_vs_backup_mcast_ifn, mcast_ifn,
sizeof(ip_vs_backup_mcast_ifn));
ip_vs_backup_syncid = syncid;
realtask = &sync_backup_thread;
name = "ipvs_syncbackup";
threadfn = sync_thread_backup;
sock = make_receive_sock();
} else {
return -EINVAL;
}
if (IS_ERR(sock)) {
result = PTR_ERR(sock);
goto out;
}
set_sync_mesg_maxlen(state);
if (state == IP_VS_STATE_BACKUP) {
buf = kmalloc(sync_recv_mesg_maxlen, GFP_KERNEL);
if (!buf)
goto outsocket;
}
tinfo = kmalloc(sizeof(*tinfo), GFP_KERNEL);
if (!tinfo)
goto outbuf;
tinfo->sock = sock;
tinfo->buf = buf;
task = kthread_run(threadfn, tinfo, name);
if (IS_ERR(task)) {
result = PTR_ERR(task);
goto outtinfo;
}
/* mark as active */
*realtask = task;
ip_vs_sync_state |= state;
/* increase the module use count */
ip_vs_use_count_inc();
return 0;
outtinfo:
kfree(tinfo);
outbuf:
kfree(buf);
outsocket:
sock_release(sock);
out:
return result;
}
int stop_sync_thread(int state)
{
IP_VS_DBG(7, "%s(): pid %d\n", __func__, task_pid_nr(current));
if (state == IP_VS_STATE_MASTER) {
if (!sync_master_thread)
return -ESRCH;
pr_info("stopping master sync thread %d ...\n",
task_pid_nr(sync_master_thread));
/*
* The lock synchronizes with sb_queue_tail(), so that we don't
* add sync buffers to the queue, when we are already in
* progress of stopping the master sync daemon.
*/
spin_lock_bh(&ip_vs_sync_lock);
ip_vs_sync_state &= ~IP_VS_STATE_MASTER;
spin_unlock_bh(&ip_vs_sync_lock);
kthread_stop(sync_master_thread);
sync_master_thread = NULL;
} else if (state == IP_VS_STATE_BACKUP) {
if (!sync_backup_thread)
return -ESRCH;
pr_info("stopping backup sync thread %d ...\n",
task_pid_nr(sync_backup_thread));
ip_vs_sync_state &= ~IP_VS_STATE_BACKUP;
kthread_stop(sync_backup_thread);
sync_backup_thread = NULL;
} else {
return -EINVAL;
}
/* decrease the module use count */
ip_vs_use_count_dec();
return 0;
}
| gpl-2.0 |
ZdrowyGosciu/kernel_g900f | arch/arm/mach-msm/qdsp6v2/audio_amrwb.c | 1917 | 4403 | /* amrwb audio output device
*
* Copyright (C) 2008 Google, Inc.
* Copyright (C) 2008 HTC Corporation
* Copyright (c) 2011-2014, The Linux Foundation. All rights reserved.
*
* 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 "audio_utils_aio.h"
#ifdef CONFIG_DEBUG_FS
static const struct file_operations audio_amrwb_debug_fops = {
.read = audio_aio_debug_read,
.open = audio_aio_debug_open,
};
#endif
static long audio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct q6audio_aio *audio = file->private_data;
int rc = 0;
switch (cmd) {
case AUDIO_START: {
pr_debug("%s[%p]: AUDIO_START session_id[%d]\n", __func__,
audio, audio->ac->session);
if (audio->feedback == NON_TUNNEL_MODE) {
/* Configure PCM output block */
rc = q6asm_enc_cfg_blk_pcm(audio->ac,
audio->pcm_cfg.sample_rate,
audio->pcm_cfg.channel_count);
if (rc < 0) {
pr_err("pcm output block config failed\n");
break;
}
}
rc = audio_aio_enable(audio);
audio->eos_rsp = 0;
audio->eos_flag = 0;
if (!rc) {
audio->enabled = 1;
} else {
audio->enabled = 0;
pr_err("Audio Start procedure failed rc=%d\n", rc);
break;
}
pr_debug("%s: AUDIO_START sessionid[%d]enable[%d]\n", __func__,
audio->ac->session,
audio->enabled);
if (audio->stopped == 1)
audio->stopped = 0;
break;
}
default:
pr_debug("%s[%p]: Calling utils ioctl\n", __func__, audio);
rc = audio->codec_ioctl(file, cmd, arg);
}
return rc;
}
static int audio_open(struct inode *inode, struct file *file)
{
struct q6audio_aio *audio = NULL;
int rc = 0;
#ifdef CONFIG_DEBUG_FS
/* 4 bytes represents decoder number, 1 byte for terminate string */
char name[sizeof "msm_amrwb_" + 5];
#endif
audio = kzalloc(sizeof(struct q6audio_aio), GFP_KERNEL);
if (audio == NULL) {
pr_err("Could not allocate memory for aac decode driver\n");
return -ENOMEM;
}
audio->pcm_cfg.buffer_size = PCM_BUFSZ_MIN;
audio->ac = q6asm_audio_client_alloc((app_cb) q6_audio_cb,
(void *)audio);
if (!audio->ac) {
pr_err("Could not allocate memory for audio client\n");
kfree(audio);
return -ENOMEM;
}
rc = audio_aio_open(audio, file);
if (rc < 0) {
pr_err("%s: audio_aio_open rc=%d\n",
__func__, rc);
goto fail;
}
/* open in T/NT mode */
if ((file->f_mode & FMODE_WRITE) && (file->f_mode & FMODE_READ)) {
rc = q6asm_open_read_write(audio->ac, FORMAT_LINEAR_PCM,
FORMAT_AMRWB);
if (rc < 0) {
pr_err("NT mode Open failed rc=%d\n", rc);
rc = -ENODEV;
goto fail;
}
audio->feedback = NON_TUNNEL_MODE;
audio->buf_cfg.frames_per_buf = 0x01;
audio->buf_cfg.meta_info_enable = 0x01;
} else if ((file->f_mode & FMODE_WRITE) &&
!(file->f_mode & FMODE_READ)) {
rc = q6asm_open_write(audio->ac, FORMAT_AMRWB);
if (rc < 0) {
pr_err("T mode Open failed rc=%d\n", rc);
rc = -ENODEV;
goto fail;
}
audio->feedback = TUNNEL_MODE;
audio->buf_cfg.meta_info_enable = 0x00;
} else {
pr_err("Not supported mode\n");
rc = -EACCES;
goto fail;
}
#ifdef CONFIG_DEBUG_FS
snprintf(name, sizeof name, "msm_amrwb_%04x", audio->ac->session);
audio->dentry = debugfs_create_file(name, S_IFREG | S_IRUGO,
NULL, (void *)audio,
&audio_amrwb_debug_fops);
if (IS_ERR(audio->dentry))
pr_debug("debugfs_create_file failed\n");
#endif
pr_info("%s: AMRWB dec success mode[%d]session[%d]\n", __func__,
audio->feedback,
audio->ac->session);
return 0;
fail:
q6asm_audio_client_free(audio->ac);
kfree(audio);
return rc;
}
static const struct file_operations audio_amrwb_fops = {
.owner = THIS_MODULE,
.open = audio_open,
.release = audio_aio_release,
.unlocked_ioctl = audio_ioctl,
.fsync = audio_aio_fsync,
};
struct miscdevice audio_amrwb_misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = "msm_amrwb",
.fops = &audio_amrwb_fops,
};
static int __init audio_amrwb_init(void)
{
return misc_register(&audio_amrwb_misc);
}
device_initcall(audio_amrwb_init);
| gpl-2.0 |
Rlasalle15/android_kernel_moto_shamu | drivers/net/ethernet/8390/ax88796.c | 2173 | 24372 | /* drivers/net/ethernet/8390/ax88796.c
*
* Copyright 2005,2007 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
*
* Asix AX88796 10/100 Ethernet controller support
* Based on ne.c, by Donald Becker, et-al.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/isapnp.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/timer.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/mdio-bitbang.h>
#include <linux/phy.h>
#include <linux/eeprom_93cx6.h>
#include <linux/slab.h>
#include <net/ax88796.h>
/* Rename the lib8390.c functions to show that they are in this driver */
#define __ei_open ax_ei_open
#define __ei_close ax_ei_close
#define __ei_poll ax_ei_poll
#define __ei_start_xmit ax_ei_start_xmit
#define __ei_tx_timeout ax_ei_tx_timeout
#define __ei_get_stats ax_ei_get_stats
#define __ei_set_multicast_list ax_ei_set_multicast_list
#define __ei_interrupt ax_ei_interrupt
#define ____alloc_ei_netdev ax__alloc_ei_netdev
#define __NS8390_init ax_NS8390_init
/* force unsigned long back to 'void __iomem *' */
#define ax_convert_addr(_a) ((void __force __iomem *)(_a))
#define ei_inb(_a) readb(ax_convert_addr(_a))
#define ei_outb(_v, _a) writeb(_v, ax_convert_addr(_a))
#define ei_inb_p(_a) ei_inb(_a)
#define ei_outb_p(_v, _a) ei_outb(_v, _a)
/* define EI_SHIFT() to take into account our register offsets */
#define EI_SHIFT(x) (ei_local->reg_offset[(x)])
/* Ensure we have our RCR base value */
#define AX88796_PLATFORM
static unsigned char version[] = "ax88796.c: Copyright 2005,2007 Simtec Electronics\n";
#include "lib8390.c"
#define DRV_NAME "ax88796"
#define DRV_VERSION "1.00"
/* from ne.c */
#define NE_CMD EI_SHIFT(0x00)
#define NE_RESET EI_SHIFT(0x1f)
#define NE_DATAPORT EI_SHIFT(0x10)
#define NE1SM_START_PG 0x20 /* First page of TX buffer */
#define NE1SM_STOP_PG 0x40 /* Last page +1 of RX ring */
#define NESM_START_PG 0x40 /* First page of TX buffer */
#define NESM_STOP_PG 0x80 /* Last page +1 of RX ring */
#define AX_GPOC_PPDSET BIT(6)
/* device private data */
struct ax_device {
struct mii_bus *mii_bus;
struct mdiobb_ctrl bb_ctrl;
struct phy_device *phy_dev;
void __iomem *addr_memr;
u8 reg_memr;
int link;
int speed;
int duplex;
void __iomem *map2;
const struct ax_plat_data *plat;
unsigned char running;
unsigned char resume_open;
unsigned int irqflags;
u32 reg_offsets[0x20];
};
static inline struct ax_device *to_ax_dev(struct net_device *dev)
{
struct ei_device *ei_local = netdev_priv(dev);
return (struct ax_device *)(ei_local + 1);
}
/*
* ax_initial_check
*
* do an initial probe for the card to check whether it exists
* and is functional
*/
static int ax_initial_check(struct net_device *dev)
{
struct ei_device *ei_local = netdev_priv(dev);
void __iomem *ioaddr = ei_local->mem;
int reg0;
int regd;
reg0 = ei_inb(ioaddr);
if (reg0 == 0xFF)
return -ENODEV;
ei_outb(E8390_NODMA + E8390_PAGE1 + E8390_STOP, ioaddr + E8390_CMD);
regd = ei_inb(ioaddr + 0x0d);
ei_outb(0xff, ioaddr + 0x0d);
ei_outb(E8390_NODMA + E8390_PAGE0, ioaddr + E8390_CMD);
ei_inb(ioaddr + EN0_COUNTER0); /* Clear the counter by reading. */
if (ei_inb(ioaddr + EN0_COUNTER0) != 0) {
ei_outb(reg0, ioaddr);
ei_outb(regd, ioaddr + 0x0d); /* Restore the old values. */
return -ENODEV;
}
return 0;
}
/*
* Hard reset the card. This used to pause for the same period that a
* 8390 reset command required, but that shouldn't be necessary.
*/
static void ax_reset_8390(struct net_device *dev)
{
struct ei_device *ei_local = netdev_priv(dev);
unsigned long reset_start_time = jiffies;
void __iomem *addr = (void __iomem *)dev->base_addr;
if (ei_debug > 1)
netdev_dbg(dev, "resetting the 8390 t=%ld\n", jiffies);
ei_outb(ei_inb(addr + NE_RESET), addr + NE_RESET);
ei_local->txing = 0;
ei_local->dmaing = 0;
/* This check _should_not_ be necessary, omit eventually. */
while ((ei_inb(addr + EN0_ISR) & ENISR_RESET) == 0) {
if (jiffies - reset_start_time > 2 * HZ / 100) {
netdev_warn(dev, "%s: did not complete.\n", __func__);
break;
}
}
ei_outb(ENISR_RESET, addr + EN0_ISR); /* Ack intr. */
}
static void ax_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr,
int ring_page)
{
struct ei_device *ei_local = netdev_priv(dev);
void __iomem *nic_base = ei_local->mem;
/* This *shouldn't* happen. If it does, it's the last thing you'll see */
if (ei_local->dmaing) {
netdev_err(dev, "DMAing conflict in %s "
"[DMAstat:%d][irqlock:%d].\n",
__func__,
ei_local->dmaing, ei_local->irqlock);
return;
}
ei_local->dmaing |= 0x01;
ei_outb(E8390_NODMA + E8390_PAGE0 + E8390_START, nic_base + NE_CMD);
ei_outb(sizeof(struct e8390_pkt_hdr), nic_base + EN0_RCNTLO);
ei_outb(0, nic_base + EN0_RCNTHI);
ei_outb(0, nic_base + EN0_RSARLO); /* On page boundary */
ei_outb(ring_page, nic_base + EN0_RSARHI);
ei_outb(E8390_RREAD+E8390_START, nic_base + NE_CMD);
if (ei_local->word16)
ioread16_rep(nic_base + NE_DATAPORT, hdr,
sizeof(struct e8390_pkt_hdr) >> 1);
else
ioread8_rep(nic_base + NE_DATAPORT, hdr,
sizeof(struct e8390_pkt_hdr));
ei_outb(ENISR_RDC, nic_base + EN0_ISR); /* Ack intr. */
ei_local->dmaing &= ~0x01;
le16_to_cpus(&hdr->count);
}
/*
* Block input and output, similar to the Crynwr packet driver. If
* you are porting to a new ethercard, look at the packet driver
* source for hints. The NEx000 doesn't share the on-board packet
* memory -- you have to put the packet out through the "remote DMA"
* dataport using ei_outb.
*/
static void ax_block_input(struct net_device *dev, int count,
struct sk_buff *skb, int ring_offset)
{
struct ei_device *ei_local = netdev_priv(dev);
void __iomem *nic_base = ei_local->mem;
char *buf = skb->data;
if (ei_local->dmaing) {
netdev_err(dev,
"DMAing conflict in %s "
"[DMAstat:%d][irqlock:%d].\n",
__func__,
ei_local->dmaing, ei_local->irqlock);
return;
}
ei_local->dmaing |= 0x01;
ei_outb(E8390_NODMA+E8390_PAGE0+E8390_START, nic_base + NE_CMD);
ei_outb(count & 0xff, nic_base + EN0_RCNTLO);
ei_outb(count >> 8, nic_base + EN0_RCNTHI);
ei_outb(ring_offset & 0xff, nic_base + EN0_RSARLO);
ei_outb(ring_offset >> 8, nic_base + EN0_RSARHI);
ei_outb(E8390_RREAD+E8390_START, nic_base + NE_CMD);
if (ei_local->word16) {
ioread16_rep(nic_base + NE_DATAPORT, buf, count >> 1);
if (count & 0x01)
buf[count-1] = ei_inb(nic_base + NE_DATAPORT);
} else {
ioread8_rep(nic_base + NE_DATAPORT, buf, count);
}
ei_local->dmaing &= ~1;
}
static void ax_block_output(struct net_device *dev, int count,
const unsigned char *buf, const int start_page)
{
struct ei_device *ei_local = netdev_priv(dev);
void __iomem *nic_base = ei_local->mem;
unsigned long dma_start;
/*
* Round the count up for word writes. Do we need to do this?
* What effect will an odd byte count have on the 8390? I
* should check someday.
*/
if (ei_local->word16 && (count & 0x01))
count++;
/* This *shouldn't* happen. If it does, it's the last thing you'll see */
if (ei_local->dmaing) {
netdev_err(dev, "DMAing conflict in %s."
"[DMAstat:%d][irqlock:%d]\n",
__func__,
ei_local->dmaing, ei_local->irqlock);
return;
}
ei_local->dmaing |= 0x01;
/* We should already be in page 0, but to be safe... */
ei_outb(E8390_PAGE0+E8390_START+E8390_NODMA, nic_base + NE_CMD);
ei_outb(ENISR_RDC, nic_base + EN0_ISR);
/* Now the normal output. */
ei_outb(count & 0xff, nic_base + EN0_RCNTLO);
ei_outb(count >> 8, nic_base + EN0_RCNTHI);
ei_outb(0x00, nic_base + EN0_RSARLO);
ei_outb(start_page, nic_base + EN0_RSARHI);
ei_outb(E8390_RWRITE+E8390_START, nic_base + NE_CMD);
if (ei_local->word16)
iowrite16_rep(nic_base + NE_DATAPORT, buf, count >> 1);
else
iowrite8_rep(nic_base + NE_DATAPORT, buf, count);
dma_start = jiffies;
while ((ei_inb(nic_base + EN0_ISR) & ENISR_RDC) == 0) {
if (jiffies - dma_start > 2 * HZ / 100) { /* 20ms */
netdev_warn(dev, "timeout waiting for Tx RDC.\n");
ax_reset_8390(dev);
ax_NS8390_init(dev, 1);
break;
}
}
ei_outb(ENISR_RDC, nic_base + EN0_ISR); /* Ack intr. */
ei_local->dmaing &= ~0x01;
}
/* definitions for accessing MII/EEPROM interface */
#define AX_MEMR EI_SHIFT(0x14)
#define AX_MEMR_MDC BIT(0)
#define AX_MEMR_MDIR BIT(1)
#define AX_MEMR_MDI BIT(2)
#define AX_MEMR_MDO BIT(3)
#define AX_MEMR_EECS BIT(4)
#define AX_MEMR_EEI BIT(5)
#define AX_MEMR_EEO BIT(6)
#define AX_MEMR_EECLK BIT(7)
static void ax_handle_link_change(struct net_device *dev)
{
struct ax_device *ax = to_ax_dev(dev);
struct phy_device *phy_dev = ax->phy_dev;
int status_change = 0;
if (phy_dev->link && ((ax->speed != phy_dev->speed) ||
(ax->duplex != phy_dev->duplex))) {
ax->speed = phy_dev->speed;
ax->duplex = phy_dev->duplex;
status_change = 1;
}
if (phy_dev->link != ax->link) {
if (!phy_dev->link) {
ax->speed = 0;
ax->duplex = -1;
}
ax->link = phy_dev->link;
status_change = 1;
}
if (status_change)
phy_print_status(phy_dev);
}
static int ax_mii_probe(struct net_device *dev)
{
struct ax_device *ax = to_ax_dev(dev);
struct phy_device *phy_dev = NULL;
int ret;
/* find the first phy */
phy_dev = phy_find_first(ax->mii_bus);
if (!phy_dev) {
netdev_err(dev, "no PHY found\n");
return -ENODEV;
}
ret = phy_connect_direct(dev, phy_dev, ax_handle_link_change,
PHY_INTERFACE_MODE_MII);
if (ret) {
netdev_err(dev, "Could not attach to PHY\n");
return ret;
}
/* mask with MAC supported features */
phy_dev->supported &= PHY_BASIC_FEATURES;
phy_dev->advertising = phy_dev->supported;
ax->phy_dev = phy_dev;
netdev_info(dev, "PHY driver [%s] (mii_bus:phy_addr=%s, irq=%d)\n",
phy_dev->drv->name, dev_name(&phy_dev->dev), phy_dev->irq);
return 0;
}
static void ax_phy_switch(struct net_device *dev, int on)
{
struct ei_device *ei_local = netdev_priv(dev);
struct ax_device *ax = to_ax_dev(dev);
u8 reg_gpoc = ax->plat->gpoc_val;
if (!!on)
reg_gpoc &= ~AX_GPOC_PPDSET;
else
reg_gpoc |= AX_GPOC_PPDSET;
ei_outb(reg_gpoc, ei_local->mem + EI_SHIFT(0x17));
}
static int ax_open(struct net_device *dev)
{
struct ax_device *ax = to_ax_dev(dev);
int ret;
netdev_dbg(dev, "open\n");
ret = request_irq(dev->irq, ax_ei_interrupt, ax->irqflags,
dev->name, dev);
if (ret)
goto failed_request_irq;
/* turn the phy on (if turned off) */
ax_phy_switch(dev, 1);
ret = ax_mii_probe(dev);
if (ret)
goto failed_mii_probe;
phy_start(ax->phy_dev);
ret = ax_ei_open(dev);
if (ret)
goto failed_ax_ei_open;
ax->running = 1;
return 0;
failed_ax_ei_open:
phy_disconnect(ax->phy_dev);
failed_mii_probe:
ax_phy_switch(dev, 0);
free_irq(dev->irq, dev);
failed_request_irq:
return ret;
}
static int ax_close(struct net_device *dev)
{
struct ax_device *ax = to_ax_dev(dev);
netdev_dbg(dev, "close\n");
ax->running = 0;
wmb();
ax_ei_close(dev);
/* turn the phy off */
ax_phy_switch(dev, 0);
phy_disconnect(ax->phy_dev);
free_irq(dev->irq, dev);
return 0;
}
static int ax_ioctl(struct net_device *dev, struct ifreq *req, int cmd)
{
struct ax_device *ax = to_ax_dev(dev);
struct phy_device *phy_dev = ax->phy_dev;
if (!netif_running(dev))
return -EINVAL;
if (!phy_dev)
return -ENODEV;
return phy_mii_ioctl(phy_dev, req, cmd);
}
/* ethtool ops */
static void ax_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct platform_device *pdev = to_platform_device(dev->dev.parent);
strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_VERSION, sizeof(info->version));
strlcpy(info->bus_info, pdev->name, sizeof(info->bus_info));
}
static int ax_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct ax_device *ax = to_ax_dev(dev);
struct phy_device *phy_dev = ax->phy_dev;
if (!phy_dev)
return -ENODEV;
return phy_ethtool_gset(phy_dev, cmd);
}
static int ax_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct ax_device *ax = to_ax_dev(dev);
struct phy_device *phy_dev = ax->phy_dev;
if (!phy_dev)
return -ENODEV;
return phy_ethtool_sset(phy_dev, cmd);
}
static const struct ethtool_ops ax_ethtool_ops = {
.get_drvinfo = ax_get_drvinfo,
.get_settings = ax_get_settings,
.set_settings = ax_set_settings,
.get_link = ethtool_op_get_link,
.get_ts_info = ethtool_op_get_ts_info,
};
#ifdef CONFIG_AX88796_93CX6
static void ax_eeprom_register_read(struct eeprom_93cx6 *eeprom)
{
struct ei_device *ei_local = eeprom->data;
u8 reg = ei_inb(ei_local->mem + AX_MEMR);
eeprom->reg_data_in = reg & AX_MEMR_EEI;
eeprom->reg_data_out = reg & AX_MEMR_EEO; /* Input pin */
eeprom->reg_data_clock = reg & AX_MEMR_EECLK;
eeprom->reg_chip_select = reg & AX_MEMR_EECS;
}
static void ax_eeprom_register_write(struct eeprom_93cx6 *eeprom)
{
struct ei_device *ei_local = eeprom->data;
u8 reg = ei_inb(ei_local->mem + AX_MEMR);
reg &= ~(AX_MEMR_EEI | AX_MEMR_EECLK | AX_MEMR_EECS);
if (eeprom->reg_data_in)
reg |= AX_MEMR_EEI;
if (eeprom->reg_data_clock)
reg |= AX_MEMR_EECLK;
if (eeprom->reg_chip_select)
reg |= AX_MEMR_EECS;
ei_outb(reg, ei_local->mem + AX_MEMR);
udelay(10);
}
#endif
static const struct net_device_ops ax_netdev_ops = {
.ndo_open = ax_open,
.ndo_stop = ax_close,
.ndo_do_ioctl = ax_ioctl,
.ndo_start_xmit = ax_ei_start_xmit,
.ndo_tx_timeout = ax_ei_tx_timeout,
.ndo_get_stats = ax_ei_get_stats,
.ndo_set_rx_mode = ax_ei_set_multicast_list,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
.ndo_change_mtu = eth_change_mtu,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = ax_ei_poll,
#endif
};
static void ax_bb_mdc(struct mdiobb_ctrl *ctrl, int level)
{
struct ax_device *ax = container_of(ctrl, struct ax_device, bb_ctrl);
if (level)
ax->reg_memr |= AX_MEMR_MDC;
else
ax->reg_memr &= ~AX_MEMR_MDC;
ei_outb(ax->reg_memr, ax->addr_memr);
}
static void ax_bb_dir(struct mdiobb_ctrl *ctrl, int output)
{
struct ax_device *ax = container_of(ctrl, struct ax_device, bb_ctrl);
if (output)
ax->reg_memr &= ~AX_MEMR_MDIR;
else
ax->reg_memr |= AX_MEMR_MDIR;
ei_outb(ax->reg_memr, ax->addr_memr);
}
static void ax_bb_set_data(struct mdiobb_ctrl *ctrl, int value)
{
struct ax_device *ax = container_of(ctrl, struct ax_device, bb_ctrl);
if (value)
ax->reg_memr |= AX_MEMR_MDO;
else
ax->reg_memr &= ~AX_MEMR_MDO;
ei_outb(ax->reg_memr, ax->addr_memr);
}
static int ax_bb_get_data(struct mdiobb_ctrl *ctrl)
{
struct ax_device *ax = container_of(ctrl, struct ax_device, bb_ctrl);
int reg_memr = ei_inb(ax->addr_memr);
return reg_memr & AX_MEMR_MDI ? 1 : 0;
}
static struct mdiobb_ops bb_ops = {
.owner = THIS_MODULE,
.set_mdc = ax_bb_mdc,
.set_mdio_dir = ax_bb_dir,
.set_mdio_data = ax_bb_set_data,
.get_mdio_data = ax_bb_get_data,
};
/* setup code */
static int ax_mii_init(struct net_device *dev)
{
struct platform_device *pdev = to_platform_device(dev->dev.parent);
struct ei_device *ei_local = netdev_priv(dev);
struct ax_device *ax = to_ax_dev(dev);
int err, i;
ax->bb_ctrl.ops = &bb_ops;
ax->addr_memr = ei_local->mem + AX_MEMR;
ax->mii_bus = alloc_mdio_bitbang(&ax->bb_ctrl);
if (!ax->mii_bus) {
err = -ENOMEM;
goto out;
}
ax->mii_bus->name = "ax88796_mii_bus";
ax->mii_bus->parent = dev->dev.parent;
snprintf(ax->mii_bus->id, MII_BUS_ID_SIZE, "%s-%x",
pdev->name, pdev->id);
ax->mii_bus->irq = kmalloc(sizeof(int) * PHY_MAX_ADDR, GFP_KERNEL);
if (!ax->mii_bus->irq) {
err = -ENOMEM;
goto out_free_mdio_bitbang;
}
for (i = 0; i < PHY_MAX_ADDR; i++)
ax->mii_bus->irq[i] = PHY_POLL;
err = mdiobus_register(ax->mii_bus);
if (err)
goto out_free_irq;
return 0;
out_free_irq:
kfree(ax->mii_bus->irq);
out_free_mdio_bitbang:
free_mdio_bitbang(ax->mii_bus);
out:
return err;
}
static void ax_initial_setup(struct net_device *dev, struct ei_device *ei_local)
{
void __iomem *ioaddr = ei_local->mem;
struct ax_device *ax = to_ax_dev(dev);
/* Select page 0 */
ei_outb(E8390_NODMA + E8390_PAGE0 + E8390_STOP, ioaddr + E8390_CMD);
/* set to byte access */
ei_outb(ax->plat->dcr_val & ~1, ioaddr + EN0_DCFG);
ei_outb(ax->plat->gpoc_val, ioaddr + EI_SHIFT(0x17));
}
/*
* ax_init_dev
*
* initialise the specified device, taking care to note the MAC
* address it may already have (if configured), ensure
* the device is ready to be used by lib8390.c and registerd with
* the network layer.
*/
static int ax_init_dev(struct net_device *dev)
{
struct ei_device *ei_local = netdev_priv(dev);
struct ax_device *ax = to_ax_dev(dev);
void __iomem *ioaddr = ei_local->mem;
unsigned int start_page;
unsigned int stop_page;
int ret;
int i;
ret = ax_initial_check(dev);
if (ret)
goto err_out;
/* setup goes here */
ax_initial_setup(dev, ei_local);
/* read the mac from the card prom if we need it */
if (ax->plat->flags & AXFLG_HAS_EEPROM) {
unsigned char SA_prom[32];
for (i = 0; i < sizeof(SA_prom); i += 2) {
SA_prom[i] = ei_inb(ioaddr + NE_DATAPORT);
SA_prom[i + 1] = ei_inb(ioaddr + NE_DATAPORT);
}
if (ax->plat->wordlength == 2)
for (i = 0; i < 16; i++)
SA_prom[i] = SA_prom[i+i];
memcpy(dev->dev_addr, SA_prom, 6);
}
#ifdef CONFIG_AX88796_93CX6
if (ax->plat->flags & AXFLG_HAS_93CX6) {
unsigned char mac_addr[6];
struct eeprom_93cx6 eeprom;
eeprom.data = ei_local;
eeprom.register_read = ax_eeprom_register_read;
eeprom.register_write = ax_eeprom_register_write;
eeprom.width = PCI_EEPROM_WIDTH_93C56;
eeprom_93cx6_multiread(&eeprom, 0,
(__le16 __force *)mac_addr,
sizeof(mac_addr) >> 1);
memcpy(dev->dev_addr, mac_addr, 6);
}
#endif
if (ax->plat->wordlength == 2) {
/* We must set the 8390 for word mode. */
ei_outb(ax->plat->dcr_val, ei_local->mem + EN0_DCFG);
start_page = NESM_START_PG;
stop_page = NESM_STOP_PG;
} else {
start_page = NE1SM_START_PG;
stop_page = NE1SM_STOP_PG;
}
/* load the mac-address from the device */
if (ax->plat->flags & AXFLG_MAC_FROMDEV) {
ei_outb(E8390_NODMA + E8390_PAGE1 + E8390_STOP,
ei_local->mem + E8390_CMD); /* 0x61 */
for (i = 0; i < ETH_ALEN; i++)
dev->dev_addr[i] =
ei_inb(ioaddr + EN1_PHYS_SHIFT(i));
}
if ((ax->plat->flags & AXFLG_MAC_FROMPLATFORM) &&
ax->plat->mac_addr)
memcpy(dev->dev_addr, ax->plat->mac_addr, ETH_ALEN);
ax_reset_8390(dev);
ei_local->name = "AX88796";
ei_local->tx_start_page = start_page;
ei_local->stop_page = stop_page;
ei_local->word16 = (ax->plat->wordlength == 2);
ei_local->rx_start_page = start_page + TX_PAGES;
#ifdef PACKETBUF_MEMSIZE
/* Allow the packet buffer size to be overridden by know-it-alls. */
ei_local->stop_page = ei_local->tx_start_page + PACKETBUF_MEMSIZE;
#endif
ei_local->reset_8390 = &ax_reset_8390;
ei_local->block_input = &ax_block_input;
ei_local->block_output = &ax_block_output;
ei_local->get_8390_hdr = &ax_get_8390_hdr;
ei_local->priv = 0;
dev->netdev_ops = &ax_netdev_ops;
dev->ethtool_ops = &ax_ethtool_ops;
ret = ax_mii_init(dev);
if (ret)
goto out_irq;
ax_NS8390_init(dev, 0);
ret = register_netdev(dev);
if (ret)
goto out_irq;
netdev_info(dev, "%dbit, irq %d, %lx, MAC: %pM\n",
ei_local->word16 ? 16 : 8, dev->irq, dev->base_addr,
dev->dev_addr);
return 0;
out_irq:
/* cleanup irq */
free_irq(dev->irq, dev);
err_out:
return ret;
}
static int ax_remove(struct platform_device *pdev)
{
struct net_device *dev = platform_get_drvdata(pdev);
struct ei_device *ei_local = netdev_priv(dev);
struct ax_device *ax = to_ax_dev(dev);
struct resource *mem;
unregister_netdev(dev);
free_irq(dev->irq, dev);
iounmap(ei_local->mem);
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(mem->start, resource_size(mem));
if (ax->map2) {
iounmap(ax->map2);
mem = platform_get_resource(pdev, IORESOURCE_MEM, 1);
release_mem_region(mem->start, resource_size(mem));
}
free_netdev(dev);
return 0;
}
/*
* ax_probe
*
* This is the entry point when the platform device system uses to
* notify us of a new device to attach to. Allocate memory, find the
* resources and information passed, and map the necessary registers.
*/
static int ax_probe(struct platform_device *pdev)
{
struct net_device *dev;
struct ei_device *ei_local;
struct ax_device *ax;
struct resource *irq, *mem, *mem2;
unsigned long mem_size, mem2_size = 0;
int ret = 0;
dev = ax__alloc_ei_netdev(sizeof(struct ax_device));
if (dev == NULL)
return -ENOMEM;
/* ok, let's setup our device */
SET_NETDEV_DEV(dev, &pdev->dev);
ei_local = netdev_priv(dev);
ax = to_ax_dev(dev);
ax->plat = pdev->dev.platform_data;
platform_set_drvdata(pdev, dev);
ei_local->rxcr_base = ax->plat->rcr_val;
/* find the platform resources */
irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!irq) {
dev_err(&pdev->dev, "no IRQ specified\n");
ret = -ENXIO;
goto exit_mem;
}
dev->irq = irq->start;
ax->irqflags = irq->flags & IRQF_TRIGGER_MASK;
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem) {
dev_err(&pdev->dev, "no MEM specified\n");
ret = -ENXIO;
goto exit_mem;
}
mem_size = resource_size(mem);
/*
* setup the register offsets from either the platform data or
* by using the size of the resource provided
*/
if (ax->plat->reg_offsets)
ei_local->reg_offset = ax->plat->reg_offsets;
else {
ei_local->reg_offset = ax->reg_offsets;
for (ret = 0; ret < 0x18; ret++)
ax->reg_offsets[ret] = (mem_size / 0x18) * ret;
}
if (!request_mem_region(mem->start, mem_size, pdev->name)) {
dev_err(&pdev->dev, "cannot reserve registers\n");
ret = -ENXIO;
goto exit_mem;
}
ei_local->mem = ioremap(mem->start, mem_size);
dev->base_addr = (unsigned long)ei_local->mem;
if (ei_local->mem == NULL) {
dev_err(&pdev->dev, "Cannot ioremap area %pR\n", mem);
ret = -ENXIO;
goto exit_req;
}
/* look for reset area */
mem2 = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!mem2) {
if (!ax->plat->reg_offsets) {
for (ret = 0; ret < 0x20; ret++)
ax->reg_offsets[ret] = (mem_size / 0x20) * ret;
}
} else {
mem2_size = resource_size(mem2);
if (!request_mem_region(mem2->start, mem2_size, pdev->name)) {
dev_err(&pdev->dev, "cannot reserve registers\n");
ret = -ENXIO;
goto exit_mem1;
}
ax->map2 = ioremap(mem2->start, mem2_size);
if (!ax->map2) {
dev_err(&pdev->dev, "cannot map reset register\n");
ret = -ENXIO;
goto exit_mem2;
}
ei_local->reg_offset[0x1f] = ax->map2 - ei_local->mem;
}
/* got resources, now initialise and register device */
ret = ax_init_dev(dev);
if (!ret)
return 0;
if (!ax->map2)
goto exit_mem1;
iounmap(ax->map2);
exit_mem2:
release_mem_region(mem2->start, mem2_size);
exit_mem1:
iounmap(ei_local->mem);
exit_req:
release_mem_region(mem->start, mem_size);
exit_mem:
free_netdev(dev);
return ret;
}
/* suspend and resume */
#ifdef CONFIG_PM
static int ax_suspend(struct platform_device *dev, pm_message_t state)
{
struct net_device *ndev = platform_get_drvdata(dev);
struct ax_device *ax = to_ax_dev(ndev);
ax->resume_open = ax->running;
netif_device_detach(ndev);
ax_close(ndev);
return 0;
}
static int ax_resume(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct ax_device *ax = to_ax_dev(ndev);
ax_initial_setup(ndev, netdev_priv(ndev));
ax_NS8390_init(ndev, ax->resume_open);
netif_device_attach(ndev);
if (ax->resume_open)
ax_open(ndev);
return 0;
}
#else
#define ax_suspend NULL
#define ax_resume NULL
#endif
static struct platform_driver axdrv = {
.driver = {
.name = "ax88796",
.owner = THIS_MODULE,
},
.probe = ax_probe,
.remove = ax_remove,
.suspend = ax_suspend,
.resume = ax_resume,
};
module_platform_driver(axdrv);
MODULE_DESCRIPTION("AX88796 10/100 Ethernet platform driver");
MODULE_AUTHOR("Ben Dooks, <ben@simtec.co.uk>");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:ax88796");
| gpl-2.0 |
Ezekeel/android-3.0 | arch/arm/mach-s5p64x0/dev-spi.c | 2685 | 4833 | /* linux/arch/arm/mach-s5p64x0/dev-spi.c
*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* Copyright (C) 2010 Samsung Electronics Co. Ltd.
* Jaswinder Singh <jassi.brar@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/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/gpio.h>
#include <mach/dma.h>
#include <mach/map.h>
#include <mach/irqs.h>
#include <mach/regs-clock.h>
#include <mach/spi-clocks.h>
#include <plat/s3c64xx-spi.h>
#include <plat/gpio-cfg.h>
static char *s5p64x0_spi_src_clks[] = {
[S5P64X0_SPI_SRCCLK_PCLK] = "pclk",
[S5P64X0_SPI_SRCCLK_SCLK] = "sclk_spi",
};
/* SPI Controller platform_devices */
/* Since we emulate multi-cs capability, we do not touch the CS.
* The emulated CS is toggled by board specific mechanism, as it can
* be either some immediate GPIO or some signal out of some other
* chip in between ... or some yet another way.
* We simply do not assume anything about CS.
*/
static int s5p6440_spi_cfg_gpio(struct platform_device *pdev)
{
unsigned int base;
switch (pdev->id) {
case 0:
base = S5P6440_GPC(0);
break;
case 1:
base = S5P6440_GPC(4);
break;
default:
dev_err(&pdev->dev, "Invalid SPI Controller number!");
return -EINVAL;
}
s3c_gpio_cfgall_range(base, 3,
S3C_GPIO_SFN(2), S3C_GPIO_PULL_UP);
return 0;
}
static int s5p6450_spi_cfg_gpio(struct platform_device *pdev)
{
unsigned int base;
switch (pdev->id) {
case 0:
base = S5P6450_GPC(0);
break;
case 1:
base = S5P6450_GPC(4);
break;
default:
dev_err(&pdev->dev, "Invalid SPI Controller number!");
return -EINVAL;
}
s3c_gpio_cfgall_range(base, 3,
S3C_GPIO_SFN(2), S3C_GPIO_PULL_UP);
return 0;
}
static struct resource s5p64x0_spi0_resource[] = {
[0] = {
.start = S5P64X0_PA_SPI0,
.end = S5P64X0_PA_SPI0 + 0x100 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = DMACH_SPI0_TX,
.end = DMACH_SPI0_TX,
.flags = IORESOURCE_DMA,
},
[2] = {
.start = DMACH_SPI0_RX,
.end = DMACH_SPI0_RX,
.flags = IORESOURCE_DMA,
},
[3] = {
.start = IRQ_SPI0,
.end = IRQ_SPI0,
.flags = IORESOURCE_IRQ,
},
};
static struct s3c64xx_spi_info s5p6440_spi0_pdata = {
.cfg_gpio = s5p6440_spi_cfg_gpio,
.fifo_lvl_mask = 0x1ff,
.rx_lvl_offset = 15,
.tx_st_done = 25,
};
static struct s3c64xx_spi_info s5p6450_spi0_pdata = {
.cfg_gpio = s5p6450_spi_cfg_gpio,
.fifo_lvl_mask = 0x1ff,
.rx_lvl_offset = 15,
.tx_st_done = 25,
};
static u64 spi_dmamask = DMA_BIT_MASK(32);
struct platform_device s5p64x0_device_spi0 = {
.name = "s3c64xx-spi",
.id = 0,
.num_resources = ARRAY_SIZE(s5p64x0_spi0_resource),
.resource = s5p64x0_spi0_resource,
.dev = {
.dma_mask = &spi_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
static struct resource s5p64x0_spi1_resource[] = {
[0] = {
.start = S5P64X0_PA_SPI1,
.end = S5P64X0_PA_SPI1 + 0x100 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = DMACH_SPI1_TX,
.end = DMACH_SPI1_TX,
.flags = IORESOURCE_DMA,
},
[2] = {
.start = DMACH_SPI1_RX,
.end = DMACH_SPI1_RX,
.flags = IORESOURCE_DMA,
},
[3] = {
.start = IRQ_SPI1,
.end = IRQ_SPI1,
.flags = IORESOURCE_IRQ,
},
};
static struct s3c64xx_spi_info s5p6440_spi1_pdata = {
.cfg_gpio = s5p6440_spi_cfg_gpio,
.fifo_lvl_mask = 0x7f,
.rx_lvl_offset = 15,
.tx_st_done = 25,
};
static struct s3c64xx_spi_info s5p6450_spi1_pdata = {
.cfg_gpio = s5p6450_spi_cfg_gpio,
.fifo_lvl_mask = 0x7f,
.rx_lvl_offset = 15,
.tx_st_done = 25,
};
struct platform_device s5p64x0_device_spi1 = {
.name = "s3c64xx-spi",
.id = 1,
.num_resources = ARRAY_SIZE(s5p64x0_spi1_resource),
.resource = s5p64x0_spi1_resource,
.dev = {
.dma_mask = &spi_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
void __init s5p64x0_spi_set_info(int cntrlr, int src_clk_nr, int num_cs)
{
unsigned int id;
struct s3c64xx_spi_info *pd;
id = __raw_readl(S5P64X0_SYS_ID) & 0xFF000;
/* Reject invalid configuration */
if (!num_cs || src_clk_nr < 0
|| src_clk_nr > S5P64X0_SPI_SRCCLK_SCLK) {
printk(KERN_ERR "%s: Invalid SPI configuration\n", __func__);
return;
}
switch (cntrlr) {
case 0:
if (id == 0x50000)
pd = &s5p6450_spi0_pdata;
else
pd = &s5p6440_spi0_pdata;
s5p64x0_device_spi0.dev.platform_data = pd;
break;
case 1:
if (id == 0x50000)
pd = &s5p6450_spi1_pdata;
else
pd = &s5p6440_spi1_pdata;
s5p64x0_device_spi1.dev.platform_data = pd;
break;
default:
printk(KERN_ERR "%s: Invalid SPI controller(%d)\n",
__func__, cntrlr);
return;
}
pd->num_cs = num_cs;
pd->src_clk_nr = src_clk_nr;
pd->src_clk_name = s5p64x0_spi_src_clks[src_clk_nr];
}
| gpl-2.0 |
jiangyanfeng/android_kernel_huawei_G300 | drivers/hwmon/max6642.c | 2941 | 10020 | /*
* Driver for +/-1 degree C, SMBus-Compatible Remote/Local Temperature Sensor
* with Overtemperature Alarm
*
* Copyright (C) 2011 AppearTV AS
*
* Derived from:
*
* Based on the max1619 driver.
* Copyright (C) 2003-2004 Alexey Fisher <fishor@mail.ru>
* Jean Delvare <khali@linux-fr.org>
*
* The MAX6642 is a sensor chip made by Maxim.
* It reports up to two temperatures (its own plus up to
* one external one). Complete datasheet can be
* obtained from Maxim's website at:
* http://datasheets.maxim-ic.com/en/ds/MAX6642.pdf
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/sysfs.h>
static const unsigned short normal_i2c[] = {
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, I2C_CLIENT_END };
/*
* The MAX6642 registers
*/
#define MAX6642_REG_R_MAN_ID 0xFE
#define MAX6642_REG_R_CONFIG 0x03
#define MAX6642_REG_W_CONFIG 0x09
#define MAX6642_REG_R_STATUS 0x02
#define MAX6642_REG_R_LOCAL_TEMP 0x00
#define MAX6642_REG_R_LOCAL_TEMPL 0x11
#define MAX6642_REG_R_LOCAL_HIGH 0x05
#define MAX6642_REG_W_LOCAL_HIGH 0x0B
#define MAX6642_REG_R_REMOTE_TEMP 0x01
#define MAX6642_REG_R_REMOTE_TEMPL 0x10
#define MAX6642_REG_R_REMOTE_HIGH 0x07
#define MAX6642_REG_W_REMOTE_HIGH 0x0D
/*
* Conversions
*/
static int temp_from_reg10(int val)
{
return val * 250;
}
static int temp_from_reg(int val)
{
return val * 1000;
}
static int temp_to_reg(int val)
{
return val / 1000;
}
/*
* Client data (each client gets its own)
*/
struct max6642_data {
struct device *hwmon_dev;
struct mutex update_lock;
bool valid; /* zero until following fields are valid */
unsigned long last_updated; /* in jiffies */
/* registers values */
u16 temp_input[2]; /* local/remote */
u16 temp_high[2]; /* local/remote */
u8 alarms;
};
/*
* Real code
*/
static void max6642_init_client(struct i2c_client *client)
{
u8 config;
struct max6642_data *data = i2c_get_clientdata(client);
/*
* Start the conversions.
*/
config = i2c_smbus_read_byte_data(client, MAX6642_REG_R_CONFIG);
if (config & 0x40)
i2c_smbus_write_byte_data(client, MAX6642_REG_W_CONFIG,
config & 0xBF); /* run */
data->temp_high[0] = i2c_smbus_read_byte_data(client,
MAX6642_REG_R_LOCAL_HIGH);
data->temp_high[1] = i2c_smbus_read_byte_data(client,
MAX6642_REG_R_REMOTE_HIGH);
}
/* Return 0 if detection is successful, -ENODEV otherwise */
static int max6642_detect(struct i2c_client *client,
struct i2c_board_info *info)
{
struct i2c_adapter *adapter = client->adapter;
u8 reg_config, reg_status, man_id;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
/* identification */
man_id = i2c_smbus_read_byte_data(client, MAX6642_REG_R_MAN_ID);
if (man_id != 0x4D)
return -ENODEV;
/* sanity check */
if (i2c_smbus_read_byte_data(client, 0x04) != 0x4D
|| i2c_smbus_read_byte_data(client, 0x06) != 0x4D
|| i2c_smbus_read_byte_data(client, 0xff) != 0x4D)
return -ENODEV;
/*
* We read the config and status register, the 4 lower bits in the
* config register should be zero and bit 5, 3, 1 and 0 should be
* zero in the status register.
*/
reg_config = i2c_smbus_read_byte_data(client, MAX6642_REG_R_CONFIG);
if ((reg_config & 0x0f) != 0x00)
return -ENODEV;
/* in between, another round of sanity checks */
if (i2c_smbus_read_byte_data(client, 0x04) != reg_config
|| i2c_smbus_read_byte_data(client, 0x06) != reg_config
|| i2c_smbus_read_byte_data(client, 0xff) != reg_config)
return -ENODEV;
reg_status = i2c_smbus_read_byte_data(client, MAX6642_REG_R_STATUS);
if ((reg_status & 0x2b) != 0x00)
return -ENODEV;
strlcpy(info->type, "max6642", I2C_NAME_SIZE);
return 0;
}
static struct max6642_data *max6642_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct max6642_data *data = i2c_get_clientdata(client);
u16 val, tmp;
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ) || !data->valid) {
dev_dbg(&client->dev, "Updating max6642 data.\n");
val = i2c_smbus_read_byte_data(client,
MAX6642_REG_R_LOCAL_TEMPL);
tmp = (val >> 6) & 3;
val = i2c_smbus_read_byte_data(client,
MAX6642_REG_R_LOCAL_TEMP);
val = (val << 2) | tmp;
data->temp_input[0] = val;
val = i2c_smbus_read_byte_data(client,
MAX6642_REG_R_REMOTE_TEMPL);
tmp = (val >> 6) & 3;
val = i2c_smbus_read_byte_data(client,
MAX6642_REG_R_REMOTE_TEMP);
val = (val << 2) | tmp;
data->temp_input[1] = val;
data->alarms = i2c_smbus_read_byte_data(client,
MAX6642_REG_R_STATUS);
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
/*
* Sysfs stuff
*/
static ssize_t show_temp_max10(struct device *dev,
struct device_attribute *dev_attr, char *buf)
{
struct max6642_data *data = max6642_update_device(dev);
struct sensor_device_attribute *attr = to_sensor_dev_attr(dev_attr);
return sprintf(buf, "%d\n",
temp_from_reg10(data->temp_input[attr->index]));
}
static ssize_t show_temp_max(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct max6642_data *data = max6642_update_device(dev);
struct sensor_device_attribute_2 *attr2 = to_sensor_dev_attr_2(attr);
return sprintf(buf, "%d\n", temp_from_reg(data->temp_high[attr2->nr]));
}
static ssize_t set_temp_max(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
unsigned long val;
int err;
struct i2c_client *client = to_i2c_client(dev);
struct max6642_data *data = i2c_get_clientdata(client);
struct sensor_device_attribute_2 *attr2 = to_sensor_dev_attr_2(attr);
err = strict_strtoul(buf, 10, &val);
if (err < 0)
return err;
mutex_lock(&data->update_lock);
data->temp_high[attr2->nr] = SENSORS_LIMIT(temp_to_reg(val), 0, 255);
i2c_smbus_write_byte_data(client, attr2->index,
data->temp_high[attr2->nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_alarm(struct device *dev, struct device_attribute *attr,
char *buf)
{
int bitnr = to_sensor_dev_attr(attr)->index;
struct max6642_data *data = max6642_update_device(dev);
return sprintf(buf, "%d\n", (data->alarms >> bitnr) & 1);
}
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_temp_max10, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_input, S_IRUGO, show_temp_max10, NULL, 1);
static SENSOR_DEVICE_ATTR_2(temp1_max, S_IWUSR | S_IRUGO, show_temp_max,
set_temp_max, 0, MAX6642_REG_W_LOCAL_HIGH);
static SENSOR_DEVICE_ATTR_2(temp2_max, S_IWUSR | S_IRUGO, show_temp_max,
set_temp_max, 1, MAX6642_REG_W_REMOTE_HIGH);
static SENSOR_DEVICE_ATTR(temp2_fault, S_IRUGO, show_alarm, NULL, 2);
static SENSOR_DEVICE_ATTR(temp1_max_alarm, S_IRUGO, show_alarm, NULL, 6);
static SENSOR_DEVICE_ATTR(temp2_max_alarm, S_IRUGO, show_alarm, NULL, 4);
static struct attribute *max6642_attributes[] = {
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp2_input.dev_attr.attr,
&sensor_dev_attr_temp1_max.dev_attr.attr,
&sensor_dev_attr_temp2_max.dev_attr.attr,
&sensor_dev_attr_temp2_fault.dev_attr.attr,
&sensor_dev_attr_temp1_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_max_alarm.dev_attr.attr,
NULL
};
static const struct attribute_group max6642_group = {
.attrs = max6642_attributes,
};
static int max6642_probe(struct i2c_client *new_client,
const struct i2c_device_id *id)
{
struct max6642_data *data;
int err;
data = kzalloc(sizeof(struct max6642_data), GFP_KERNEL);
if (!data) {
err = -ENOMEM;
goto exit;
}
i2c_set_clientdata(new_client, data);
mutex_init(&data->update_lock);
/* Initialize the MAX6642 chip */
max6642_init_client(new_client);
/* Register sysfs hooks */
err = sysfs_create_group(&new_client->dev.kobj, &max6642_group);
if (err)
goto exit_free;
data->hwmon_dev = hwmon_device_register(&new_client->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto exit_remove_files;
}
return 0;
exit_remove_files:
sysfs_remove_group(&new_client->dev.kobj, &max6642_group);
exit_free:
kfree(data);
exit:
return err;
}
static int max6642_remove(struct i2c_client *client)
{
struct max6642_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&client->dev.kobj, &max6642_group);
kfree(data);
return 0;
}
/*
* Driver data (common to all clients)
*/
static const struct i2c_device_id max6642_id[] = {
{ "max6642", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, max6642_id);
static struct i2c_driver max6642_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "max6642",
},
.probe = max6642_probe,
.remove = max6642_remove,
.id_table = max6642_id,
.detect = max6642_detect,
.address_list = normal_i2c,
};
static int __init max6642_init(void)
{
return i2c_add_driver(&max6642_driver);
}
static void __exit max6642_exit(void)
{
i2c_del_driver(&max6642_driver);
}
MODULE_AUTHOR("Per Dalen <per.dalen@appeartv.com>");
MODULE_DESCRIPTION("MAX6642 sensor driver");
MODULE_LICENSE("GPL");
module_init(max6642_init);
module_exit(max6642_exit);
| gpl-2.0 |
NoelMacwan/SXDNickiKernels | drivers/net/wireless/rtlwifi/ps.c | 3965 | 16513 | /******************************************************************************
*
* 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 <linux/export.h>
#include "wifi.h"
#include "base.h"
#include "ps.h"
bool rtl_ps_enable_nic(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
/*<1> reset trx ring */
if (rtlhal->interface == INTF_PCI)
rtlpriv->intf_ops->reset_trx_ring(hw);
if (is_hal_stop(rtlhal))
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"Driver is already down!\n");
/*<2> Enable Adapter */
if (rtlpriv->cfg->ops->hw_init(hw))
return 1;
RT_CLEAR_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_HALT_NIC);
/*<3> Enable Interrupt */
rtlpriv->cfg->ops->enable_interrupt(hw);
/*<enable timer> */
rtl_watch_dog_timer_callback((unsigned long)hw);
return true;
}
EXPORT_SYMBOL(rtl_ps_enable_nic);
bool rtl_ps_disable_nic(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
/*<1> Stop all timer */
rtl_deinit_deferred_work(hw);
/*<2> Disable Interrupt */
rtlpriv->cfg->ops->disable_interrupt(hw);
tasklet_kill(&rtlpriv->works.irq_tasklet);
/*<3> Disable Adapter */
rtlpriv->cfg->ops->hw_disable(hw);
return true;
}
EXPORT_SYMBOL(rtl_ps_disable_nic);
bool rtl_ps_set_rf_state(struct ieee80211_hw *hw,
enum rf_pwrstate state_toset,
u32 changesource)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
bool actionallowed = false;
switch (state_toset) {
case ERFON:
ppsc->rfoff_reason &= (~changesource);
if ((changesource == RF_CHANGE_BY_HW) &&
(ppsc->hwradiooff)) {
ppsc->hwradiooff = false;
}
if (!ppsc->rfoff_reason) {
ppsc->rfoff_reason = 0;
actionallowed = true;
}
break;
case ERFOFF:
if ((changesource == RF_CHANGE_BY_HW) && !ppsc->hwradiooff) {
ppsc->hwradiooff = true;
}
ppsc->rfoff_reason |= changesource;
actionallowed = true;
break;
case ERFSLEEP:
ppsc->rfoff_reason |= changesource;
actionallowed = true;
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
}
if (actionallowed)
rtlpriv->cfg->ops->set_rf_power_state(hw, state_toset);
return actionallowed;
}
EXPORT_SYMBOL(rtl_ps_set_rf_state);
static void _rtl_ps_inactive_ps(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
ppsc->swrf_processing = true;
if (ppsc->inactive_pwrstate == ERFON &&
rtlhal->interface == INTF_PCI) {
if ((ppsc->reg_rfps_level & RT_RF_OFF_LEVL_ASPM) &&
RT_IN_PS_LEVEL(ppsc, RT_PS_LEVEL_ASPM) &&
rtlhal->interface == INTF_PCI) {
rtlpriv->intf_ops->disable_aspm(hw);
RT_CLEAR_PS_LEVEL(ppsc, RT_PS_LEVEL_ASPM);
}
}
rtl_ps_set_rf_state(hw, ppsc->inactive_pwrstate, RF_CHANGE_BY_IPS);
if (ppsc->inactive_pwrstate == ERFOFF &&
rtlhal->interface == INTF_PCI) {
if (ppsc->reg_rfps_level & RT_RF_OFF_LEVL_ASPM &&
!RT_IN_PS_LEVEL(ppsc, RT_PS_LEVEL_ASPM)) {
rtlpriv->intf_ops->enable_aspm(hw);
RT_SET_PS_LEVEL(ppsc, RT_PS_LEVEL_ASPM);
}
}
ppsc->swrf_processing = false;
}
void rtl_ips_nic_off_wq_callback(void *data)
{
struct rtl_works *rtlworks =
container_of_dwork_rtl(data, struct rtl_works, ips_nic_off_wq);
struct ieee80211_hw *hw = rtlworks->hw;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
enum rf_pwrstate rtstate;
if (mac->opmode != NL80211_IFTYPE_STATION) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"not station return\n");
return;
}
if (mac->link_state > MAC80211_NOLINK)
return;
if (is_hal_stop(rtlhal))
return;
if (rtlpriv->sec.being_setkey)
return;
if (ppsc->inactiveps) {
rtstate = ppsc->rfpwr_state;
/*
*Do not enter IPS in the following conditions:
*(1) RF is already OFF or Sleep
*(2) swrf_processing (indicates the IPS is still under going)
*(3) Connectted (only disconnected can trigger IPS)
*(4) IBSS (send Beacon)
*(5) AP mode (send Beacon)
*(6) monitor mode (rcv packet)
*/
if (rtstate == ERFON &&
!ppsc->swrf_processing &&
(mac->link_state == MAC80211_NOLINK) &&
!mac->act_scanning) {
RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE,
"IPSEnter(): Turn off RF\n");
ppsc->inactive_pwrstate = ERFOFF;
ppsc->in_powersavemode = true;
/*rtl_pci_reset_trx_ring(hw); */
_rtl_ps_inactive_ps(hw);
}
}
}
void rtl_ips_nic_off(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
/*
*because when link with ap, mac80211 will ask us
*to disable nic quickly after scan before linking,
*this will cause link failed, so we delay 100ms here
*/
queue_delayed_work(rtlpriv->works.rtl_wq,
&rtlpriv->works.ips_nic_off_wq, MSECS(100));
}
void rtl_ips_nic_on(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
enum rf_pwrstate rtstate;
unsigned long flags;
if (mac->opmode != NL80211_IFTYPE_STATION)
return;
spin_lock_irqsave(&rtlpriv->locks.ips_lock, flags);
if (ppsc->inactiveps) {
rtstate = ppsc->rfpwr_state;
if (rtstate != ERFON &&
!ppsc->swrf_processing &&
ppsc->rfoff_reason <= RF_CHANGE_BY_IPS) {
ppsc->inactive_pwrstate = ERFON;
ppsc->in_powersavemode = false;
_rtl_ps_inactive_ps(hw);
}
}
spin_unlock_irqrestore(&rtlpriv->locks.ips_lock, flags);
}
/*for FW LPS*/
/*
*Determine if we can set Fw into PS mode
*in current condition.Return TRUE if it
*can enter PS mode.
*/
static bool rtl_get_fwlps_doze(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
u32 ps_timediff;
ps_timediff = jiffies_to_msecs(jiffies -
ppsc->last_delaylps_stamp_jiffies);
if (ps_timediff < 2000) {
RT_TRACE(rtlpriv, COMP_POWER, DBG_LOUD,
"Delay enter Fw LPS for DHCP, ARP, or EAPOL exchanging state\n");
return false;
}
if (mac->link_state != MAC80211_LINKED)
return false;
if (mac->opmode == NL80211_IFTYPE_ADHOC)
return false;
return true;
}
/* Change current and default preamble mode.*/
static void rtl_lps_set_psmode(struct ieee80211_hw *hw, u8 rt_psmode)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
u8 rpwm_val, fw_pwrmode;
if (mac->opmode == NL80211_IFTYPE_ADHOC)
return;
if (mac->link_state != MAC80211_LINKED)
return;
if (ppsc->dot11_psmode == rt_psmode)
return;
/* Update power save mode configured. */
ppsc->dot11_psmode = rt_psmode;
/*
*<FW control LPS>
*1. Enter PS mode
* Set RPWM to Fw to turn RF off and send H2C fw_pwrmode
* cmd to set Fw into PS mode.
*2. Leave PS mode
* Send H2C fw_pwrmode cmd to Fw to set Fw into Active
* mode and set RPWM to turn RF on.
*/
if ((ppsc->fwctrl_lps) && ppsc->report_linked) {
bool fw_current_inps;
if (ppsc->dot11_psmode == EACTIVE) {
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"FW LPS leave ps_mode:%x\n",
FW_PS_ACTIVE_MODE);
rpwm_val = 0x0C; /* RF on */
fw_pwrmode = FW_PS_ACTIVE_MODE;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_SET_RPWM,
(u8 *) (&rpwm_val));
rtlpriv->cfg->ops->set_hw_reg(hw,
HW_VAR_H2C_FW_PWRMODE,
(u8 *) (&fw_pwrmode));
fw_current_inps = false;
rtlpriv->cfg->ops->set_hw_reg(hw,
HW_VAR_FW_PSMODE_STATUS,
(u8 *) (&fw_current_inps));
} else {
if (rtl_get_fwlps_doze(hw)) {
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"FW LPS enter ps_mode:%x\n",
ppsc->fwctrl_psmode);
rpwm_val = 0x02; /* RF off */
fw_current_inps = true;
rtlpriv->cfg->ops->set_hw_reg(hw,
HW_VAR_FW_PSMODE_STATUS,
(u8 *) (&fw_current_inps));
rtlpriv->cfg->ops->set_hw_reg(hw,
HW_VAR_H2C_FW_PWRMODE,
(u8 *) (&ppsc->fwctrl_psmode));
rtlpriv->cfg->ops->set_hw_reg(hw,
HW_VAR_SET_RPWM,
(u8 *) (&rpwm_val));
} else {
/* Reset the power save related parameters. */
ppsc->dot11_psmode = EACTIVE;
}
}
}
}
/*Enter the leisure power save mode.*/
void rtl_lps_enter(struct ieee80211_hw *hw)
{
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct rtl_priv *rtlpriv = rtl_priv(hw);
if (!ppsc->fwctrl_lps)
return;
if (rtlpriv->sec.being_setkey)
return;
if (rtlpriv->link_info.busytraffic)
return;
/*sleep after linked 10s, to let DHCP and 4-way handshake ok enough!! */
if (mac->cnt_after_linked < 5)
return;
if (mac->opmode == NL80211_IFTYPE_ADHOC)
return;
if (mac->link_state != MAC80211_LINKED)
return;
mutex_lock(&rtlpriv->locks.ps_mutex);
/* Idle for a while if we connect to AP a while ago. */
if (mac->cnt_after_linked >= 2) {
if (ppsc->dot11_psmode == EACTIVE) {
RT_TRACE(rtlpriv, COMP_POWER, DBG_LOUD,
"Enter 802.11 power save mode...\n");
rtl_lps_set_psmode(hw, EAUTOPS);
}
}
mutex_unlock(&rtlpriv->locks.ps_mutex);
}
/*Leave the leisure power save mode.*/
void rtl_lps_leave(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
mutex_lock(&rtlpriv->locks.ps_mutex);
if (ppsc->fwctrl_lps) {
if (ppsc->dot11_psmode != EACTIVE) {
/*FIX ME */
rtlpriv->cfg->ops->enable_interrupt(hw);
if (ppsc->reg_rfps_level & RT_RF_LPS_LEVEL_ASPM &&
RT_IN_PS_LEVEL(ppsc, RT_PS_LEVEL_ASPM) &&
rtlhal->interface == INTF_PCI) {
rtlpriv->intf_ops->disable_aspm(hw);
RT_CLEAR_PS_LEVEL(ppsc, RT_PS_LEVEL_ASPM);
}
RT_TRACE(rtlpriv, COMP_POWER, DBG_LOUD,
"Busy Traffic,Leave 802.11 power save..\n");
rtl_lps_set_psmode(hw, EACTIVE);
}
}
mutex_unlock(&rtlpriv->locks.ps_mutex);
}
/* For sw LPS*/
void rtl_swlps_beacon(struct ieee80211_hw *hw, void *data, unsigned int len)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct ieee80211_hdr *hdr = (void *) data;
struct ieee80211_tim_ie *tim_ie;
u8 *tim;
u8 tim_len;
bool u_buffed;
bool m_buffed;
if (mac->opmode != NL80211_IFTYPE_STATION)
return;
if (!rtlpriv->psc.swctrl_lps)
return;
if (rtlpriv->mac80211.link_state != MAC80211_LINKED)
return;
if (!rtlpriv->psc.sw_ps_enabled)
return;
if (rtlpriv->psc.fwctrl_lps)
return;
if (likely(!(hw->conf.flags & IEEE80211_CONF_PS)))
return;
/* check if this really is a beacon */
if (!ieee80211_is_beacon(hdr->frame_control))
return;
/* min. beacon length + FCS_LEN */
if (len <= 40 + FCS_LEN)
return;
/* and only beacons from the associated BSSID, please */
if (compare_ether_addr(hdr->addr3, rtlpriv->mac80211.bssid))
return;
rtlpriv->psc.last_beacon = jiffies;
tim = rtl_find_ie(data, len - FCS_LEN, WLAN_EID_TIM);
if (!tim)
return;
if (tim[1] < sizeof(*tim_ie))
return;
tim_len = tim[1];
tim_ie = (struct ieee80211_tim_ie *) &tim[2];
if (!WARN_ON_ONCE(!hw->conf.ps_dtim_period))
rtlpriv->psc.dtim_counter = tim_ie->dtim_count;
/* Check whenever the PHY can be turned off again. */
/* 1. What about buffered unicast traffic for our AID? */
u_buffed = ieee80211_check_tim(tim_ie, tim_len,
rtlpriv->mac80211.assoc_id);
/* 2. Maybe the AP wants to send multicast/broadcast data? */
m_buffed = tim_ie->bitmap_ctrl & 0x01;
rtlpriv->psc.multi_buffered = m_buffed;
/* unicast will process by mac80211 through
* set ~IEEE80211_CONF_PS, So we just check
* multicast frames here */
if (!m_buffed) {
/* back to low-power land. and delay is
* prevent null power save frame tx fail */
queue_delayed_work(rtlpriv->works.rtl_wq,
&rtlpriv->works.ps_work, MSECS(5));
} else {
RT_TRACE(rtlpriv, COMP_POWER, DBG_DMESG,
"u_bufferd: %x, m_buffered: %x\n", u_buffed, m_buffed);
}
}
void rtl_swlps_rf_awake(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
if (!rtlpriv->psc.swctrl_lps)
return;
if (mac->link_state != MAC80211_LINKED)
return;
if (ppsc->reg_rfps_level & RT_RF_LPS_LEVEL_ASPM &&
RT_IN_PS_LEVEL(ppsc, RT_PS_LEVEL_ASPM)) {
rtlpriv->intf_ops->disable_aspm(hw);
RT_CLEAR_PS_LEVEL(ppsc, RT_PS_LEVEL_ASPM);
}
mutex_lock(&rtlpriv->locks.ps_mutex);
rtl_ps_set_rf_state(hw, ERFON, RF_CHANGE_BY_PS);
mutex_unlock(&rtlpriv->locks.ps_mutex);
}
void rtl_swlps_rfon_wq_callback(void *data)
{
struct rtl_works *rtlworks =
container_of_dwork_rtl(data, struct rtl_works, ps_rfon_wq);
struct ieee80211_hw *hw = rtlworks->hw;
rtl_swlps_rf_awake(hw);
}
void rtl_swlps_rf_sleep(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
u8 sleep_intv;
if (!rtlpriv->psc.sw_ps_enabled)
return;
if ((rtlpriv->sec.being_setkey) ||
(mac->opmode == NL80211_IFTYPE_ADHOC))
return;
/*sleep after linked 10s, to let DHCP and 4-way handshake ok enough!! */
if ((mac->link_state != MAC80211_LINKED) || (mac->cnt_after_linked < 5))
return;
if (rtlpriv->link_info.busytraffic)
return;
mutex_lock(&rtlpriv->locks.ps_mutex);
rtl_ps_set_rf_state(hw, ERFSLEEP, RF_CHANGE_BY_PS);
mutex_unlock(&rtlpriv->locks.ps_mutex);
if (ppsc->reg_rfps_level & RT_RF_OFF_LEVL_ASPM &&
!RT_IN_PS_LEVEL(ppsc, RT_PS_LEVEL_ASPM)) {
rtlpriv->intf_ops->enable_aspm(hw);
RT_SET_PS_LEVEL(ppsc, RT_PS_LEVEL_ASPM);
}
/* here is power save alg, when this beacon is DTIM
* we will set sleep time to dtim_period * n;
* when this beacon is not DTIM, we will set sleep
* time to sleep_intv = rtlpriv->psc.dtim_counter or
* MAX_SW_LPS_SLEEP_INTV(default set to 5) */
if (rtlpriv->psc.dtim_counter == 0) {
if (hw->conf.ps_dtim_period == 1)
sleep_intv = hw->conf.ps_dtim_period * 2;
else
sleep_intv = hw->conf.ps_dtim_period;
} else {
sleep_intv = rtlpriv->psc.dtim_counter;
}
if (sleep_intv > MAX_SW_LPS_SLEEP_INTV)
sleep_intv = MAX_SW_LPS_SLEEP_INTV;
/* this print should always be dtim_conter = 0 &
* sleep = dtim_period, that meaons, we should
* awake before every dtim */
RT_TRACE(rtlpriv, COMP_POWER, DBG_DMESG,
"dtim_counter:%x will sleep :%d beacon_intv\n",
rtlpriv->psc.dtim_counter, sleep_intv);
/* we tested that 40ms is enough for sw & hw sw delay */
queue_delayed_work(rtlpriv->works.rtl_wq, &rtlpriv->works.ps_rfon_wq,
MSECS(sleep_intv * mac->vif->bss_conf.beacon_int - 40));
}
void rtl_swlps_wq_callback(void *data)
{
struct rtl_works *rtlworks = container_of_dwork_rtl(data,
struct rtl_works,
ps_work);
struct ieee80211_hw *hw = rtlworks->hw;
struct rtl_priv *rtlpriv = rtl_priv(hw);
bool ps = false;
ps = (hw->conf.flags & IEEE80211_CONF_PS);
/* we can sleep after ps null send ok */
if (rtlpriv->psc.state_inap) {
rtl_swlps_rf_sleep(hw);
if (rtlpriv->psc.state && !ps) {
rtlpriv->psc.sleep_ms = jiffies_to_msecs(jiffies -
rtlpriv->psc.last_action);
}
if (ps)
rtlpriv->psc.last_slept = jiffies;
rtlpriv->psc.last_action = jiffies;
rtlpriv->psc.state = ps;
}
}
| gpl-2.0 |
HSAFoundation/HSA-Drivers-Linux-AMD | src/kernel/arch/sh/boards/mach-dreamcast/irq.c | 4733 | 4412 | /*
* arch/sh/boards/dreamcast/irq.c
*
* Holly IRQ support for the Sega Dreamcast.
*
* Copyright (c) 2001, 2002 M. R. Brown <mrbrown@0xd6.org>
*
* This file is part of the LinuxDC project (www.linuxdc.org)
* Released under the terms of the GNU GPL v2.0
*/
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/export.h>
#include <linux/err.h>
#include <mach/sysasic.h>
/*
* Dreamcast System ASIC Hardware Events -
*
* The Dreamcast's System ASIC (a.k.a. Holly) is responsible for receiving
* hardware events from system peripherals and triggering an SH7750 IRQ.
* Hardware events can trigger IRQs 13, 11, or 9 depending on which bits are
* set in the Event Mask Registers (EMRs). When a hardware event is
* triggered, its corresponding bit in the Event Status Registers (ESRs)
* is set, and that bit should be rewritten to the ESR to acknowledge that
* event.
*
* There are three 32-bit ESRs located at 0xa05f6900 - 0xa05f6908. Event
* types can be found in arch/sh/include/mach-dreamcast/mach/sysasic.h.
* There are three groups of EMRs that parallel the ESRs. Each EMR group
* corresponds to an IRQ, so 0xa05f6910 - 0xa05f6918 triggers IRQ 13,
* 0xa05f6920 - 0xa05f6928 triggers IRQ 11, and 0xa05f6930 - 0xa05f6938
* triggers IRQ 9.
*
* In the kernel, these events are mapped to virtual IRQs so that drivers can
* respond to them as they would a normal interrupt. In order to keep this
* mapping simple, the events are mapped as:
*
* 6900/6910 - Events 0-31, IRQ 13
* 6904/6924 - Events 32-63, IRQ 11
* 6908/6938 - Events 64-95, IRQ 9
*
*/
#define ESR_BASE 0x005f6900 /* Base event status register */
#define EMR_BASE 0x005f6910 /* Base event mask register */
/*
* Helps us determine the EMR group that this event belongs to: 0 = 0x6910,
* 1 = 0x6920, 2 = 0x6930; also determine the event offset.
*/
#define LEVEL(event) (((event) - HW_EVENT_IRQ_BASE) / 32)
/* Return the hardware event's bit position within the EMR/ESR */
#define EVENT_BIT(event) (((event) - HW_EVENT_IRQ_BASE) & 31)
/*
* For each of these *_irq routines, the IRQ passed in is the virtual IRQ
* (logically mapped to the corresponding bit for the hardware event).
*/
/* Disable the hardware event by masking its bit in its EMR */
static inline void disable_systemasic_irq(struct irq_data *data)
{
unsigned int irq = data->irq;
__u32 emr = EMR_BASE + (LEVEL(irq) << 4) + (LEVEL(irq) << 2);
__u32 mask;
mask = inl(emr);
mask &= ~(1 << EVENT_BIT(irq));
outl(mask, emr);
}
/* Enable the hardware event by setting its bit in its EMR */
static inline void enable_systemasic_irq(struct irq_data *data)
{
unsigned int irq = data->irq;
__u32 emr = EMR_BASE + (LEVEL(irq) << 4) + (LEVEL(irq) << 2);
__u32 mask;
mask = inl(emr);
mask |= (1 << EVENT_BIT(irq));
outl(mask, emr);
}
/* Acknowledge a hardware event by writing its bit back to its ESR */
static void mask_ack_systemasic_irq(struct irq_data *data)
{
unsigned int irq = data->irq;
__u32 esr = ESR_BASE + (LEVEL(irq) << 2);
disable_systemasic_irq(data);
outl((1 << EVENT_BIT(irq)), esr);
}
struct irq_chip systemasic_int = {
.name = "System ASIC",
.irq_mask = disable_systemasic_irq,
.irq_mask_ack = mask_ack_systemasic_irq,
.irq_unmask = enable_systemasic_irq,
};
/*
* Map the hardware event indicated by the processor IRQ to a virtual IRQ.
*/
int systemasic_irq_demux(int irq)
{
__u32 emr, esr, status, level;
__u32 j, bit;
switch (irq) {
case 13:
level = 0;
break;
case 11:
level = 1;
break;
case 9:
level = 2;
break;
default:
return irq;
}
emr = EMR_BASE + (level << 4) + (level << 2);
esr = ESR_BASE + (level << 2);
/* Mask the ESR to filter any spurious, unwanted interrupts */
status = inl(esr);
status &= inl(emr);
/* Now scan and find the first set bit as the event to map */
for (bit = 1, j = 0; j < 32; bit <<= 1, j++) {
if (status & bit) {
irq = HW_EVENT_IRQ_BASE + j + (level << 5);
return irq;
}
}
/* Not reached */
return irq;
}
void systemasic_irq_init(void)
{
int irq_base, i;
irq_base = irq_alloc_descs(HW_EVENT_IRQ_BASE, HW_EVENT_IRQ_BASE,
HW_EVENT_IRQ_MAX - HW_EVENT_IRQ_BASE, -1);
if (IS_ERR_VALUE(irq_base)) {
pr_err("%s: failed hooking irqs\n", __func__);
return;
}
for (i = HW_EVENT_IRQ_BASE; i < HW_EVENT_IRQ_MAX; i++)
irq_set_chip_and_handler(i, &systemasic_int, handle_level_irq);
}
| gpl-2.0 |
drod2169/KernelSanders-OMAP | drivers/parisc/lba_pci.c | 4733 | 47704 | /*
**
** PCI Lower Bus Adapter (LBA) manager
**
** (c) Copyright 1999,2000 Grant Grundler
** (c) Copyright 1999,2000 Hewlett-Packard Company
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
**
** This module primarily provides access to PCI bus (config/IOport
** spaces) on platforms with an SBA/LBA chipset. A/B/C/J/L/N-class
** with 4 digit model numbers - eg C3000 (and A400...sigh).
**
** LBA driver isn't as simple as the Dino driver because:
** (a) this chip has substantial bug fixes between revisions
** (Only one Dino bug has a software workaround :^( )
** (b) has more options which we don't (yet) support (DMA hints, OLARD)
** (c) IRQ support lives in the I/O SAPIC driver (not with PCI driver)
** (d) play nicely with both PAT and "Legacy" PA-RISC firmware (PDC).
** (dino only deals with "Legacy" PDC)
**
** LBA driver passes the I/O SAPIC HPA to the I/O SAPIC driver.
** (I/O SAPIC is integratd in the LBA chip).
**
** FIXME: Add support to SBA and LBA drivers for DMA hint sets
** FIXME: Add support for PCI card hot-plug (OLARD).
*/
#include <linux/delay.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/init.h> /* for __init and __devinit */
#include <linux/pci.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <asm/byteorder.h>
#include <asm/pdc.h>
#include <asm/pdcpat.h>
#include <asm/page.h>
#include <asm/system.h>
#include <asm/ropes.h>
#include <asm/hardware.h> /* for register_parisc_driver() stuff */
#include <asm/parisc-device.h>
#include <asm/io.h> /* read/write stuff */
#undef DEBUG_LBA /* general stuff */
#undef DEBUG_LBA_PORT /* debug I/O Port access */
#undef DEBUG_LBA_CFG /* debug Config Space Access (ie PCI Bus walk) */
#undef DEBUG_LBA_PAT /* debug PCI Resource Mgt code - PDC PAT only */
#undef FBB_SUPPORT /* Fast Back-Back xfers - NOT READY YET */
#ifdef DEBUG_LBA
#define DBG(x...) printk(x)
#else
#define DBG(x...)
#endif
#ifdef DEBUG_LBA_PORT
#define DBG_PORT(x...) printk(x)
#else
#define DBG_PORT(x...)
#endif
#ifdef DEBUG_LBA_CFG
#define DBG_CFG(x...) printk(x)
#else
#define DBG_CFG(x...)
#endif
#ifdef DEBUG_LBA_PAT
#define DBG_PAT(x...) printk(x)
#else
#define DBG_PAT(x...)
#endif
/*
** Config accessor functions only pass in the 8-bit bus number and not
** the 8-bit "PCI Segment" number. Each LBA will be assigned a PCI bus
** number based on what firmware wrote into the scratch register.
**
** The "secondary" bus number is set to this before calling
** pci_register_ops(). If any PPB's are present, the scan will
** discover them and update the "secondary" and "subordinate"
** fields in the pci_bus structure.
**
** Changes in the configuration *may* result in a different
** bus number for each LBA depending on what firmware does.
*/
#define MODULE_NAME "LBA"
/* non-postable I/O port space, densely packed */
#define LBA_PORT_BASE (PCI_F_EXTEND | 0xfee00000UL)
static void __iomem *astro_iop_base __read_mostly;
static u32 lba_t32;
/* lba flags */
#define LBA_FLAG_SKIP_PROBE 0x10
#define LBA_SKIP_PROBE(d) ((d)->flags & LBA_FLAG_SKIP_PROBE)
/* Looks nice and keeps the compiler happy */
#define LBA_DEV(d) ((struct lba_device *) (d))
/*
** Only allow 8 subsidiary busses per LBA
** Problem is the PCI bus numbering is globally shared.
*/
#define LBA_MAX_NUM_BUSES 8
/************************************
* LBA register read and write support
*
* BE WARNED: register writes are posted.
* (ie follow writes which must reach HW with a read)
*/
#define READ_U8(addr) __raw_readb(addr)
#define READ_U16(addr) __raw_readw(addr)
#define READ_U32(addr) __raw_readl(addr)
#define WRITE_U8(value, addr) __raw_writeb(value, addr)
#define WRITE_U16(value, addr) __raw_writew(value, addr)
#define WRITE_U32(value, addr) __raw_writel(value, addr)
#define READ_REG8(addr) readb(addr)
#define READ_REG16(addr) readw(addr)
#define READ_REG32(addr) readl(addr)
#define READ_REG64(addr) readq(addr)
#define WRITE_REG8(value, addr) writeb(value, addr)
#define WRITE_REG16(value, addr) writew(value, addr)
#define WRITE_REG32(value, addr) writel(value, addr)
#define LBA_CFG_TOK(bus,dfn) ((u32) ((bus)<<16 | (dfn)<<8))
#define LBA_CFG_BUS(tok) ((u8) ((tok)>>16))
#define LBA_CFG_DEV(tok) ((u8) ((tok)>>11) & 0x1f)
#define LBA_CFG_FUNC(tok) ((u8) ((tok)>>8 ) & 0x7)
/*
** Extract LBA (Rope) number from HPA
** REVISIT: 16 ropes for Stretch/Ike?
*/
#define ROPES_PER_IOC 8
#define LBA_NUM(x) ((((unsigned long) x) >> 13) & (ROPES_PER_IOC-1))
static void
lba_dump_res(struct resource *r, int d)
{
int i;
if (NULL == r)
return;
printk(KERN_DEBUG "(%p)", r->parent);
for (i = d; i ; --i) printk(" ");
printk(KERN_DEBUG "%p [%lx,%lx]/%lx\n", r,
(long)r->start, (long)r->end, r->flags);
lba_dump_res(r->child, d+2);
lba_dump_res(r->sibling, d);
}
/*
** LBA rev 2.0, 2.1, 2.2, and 3.0 bus walks require a complex
** workaround for cfg cycles:
** -- preserve LBA state
** -- prevent any DMA from occurring
** -- turn on smart mode
** -- probe with config writes before doing config reads
** -- check ERROR_STATUS
** -- clear ERROR_STATUS
** -- restore LBA state
**
** The workaround is only used for device discovery.
*/
static int lba_device_present(u8 bus, u8 dfn, struct lba_device *d)
{
u8 first_bus = d->hba.hba_bus->secondary;
u8 last_sub_bus = d->hba.hba_bus->subordinate;
if ((bus < first_bus) ||
(bus > last_sub_bus) ||
((bus - first_bus) >= LBA_MAX_NUM_BUSES)) {
return 0;
}
return 1;
}
#define LBA_CFG_SETUP(d, tok) { \
/* Save contents of error config register. */ \
error_config = READ_REG32(d->hba.base_addr + LBA_ERROR_CONFIG); \
\
/* Save contents of status control register. */ \
status_control = READ_REG32(d->hba.base_addr + LBA_STAT_CTL); \
\
/* For LBA rev 2.0, 2.1, 2.2, and 3.0, we must disable DMA \
** arbitration for full bus walks. \
*/ \
/* Save contents of arb mask register. */ \
arb_mask = READ_REG32(d->hba.base_addr + LBA_ARB_MASK); \
\
/* \
* Turn off all device arbitration bits (i.e. everything \
* except arbitration enable bit). \
*/ \
WRITE_REG32(0x1, d->hba.base_addr + LBA_ARB_MASK); \
\
/* \
* Set the smart mode bit so that master aborts don't cause \
* LBA to go into PCI fatal mode (required). \
*/ \
WRITE_REG32(error_config | LBA_SMART_MODE, d->hba.base_addr + LBA_ERROR_CONFIG); \
}
#define LBA_CFG_PROBE(d, tok) { \
/* \
* Setup Vendor ID write and read back the address register \
* to make sure that LBA is the bus master. \
*/ \
WRITE_REG32(tok | PCI_VENDOR_ID, (d)->hba.base_addr + LBA_PCI_CFG_ADDR);\
/* \
* Read address register to ensure that LBA is the bus master, \
* which implies that DMA traffic has stopped when DMA arb is off. \
*/ \
lba_t32 = READ_REG32((d)->hba.base_addr + LBA_PCI_CFG_ADDR); \
/* \
* Generate a cfg write cycle (will have no affect on \
* Vendor ID register since read-only). \
*/ \
WRITE_REG32(~0, (d)->hba.base_addr + LBA_PCI_CFG_DATA); \
/* \
* Make sure write has completed before proceeding further, \
* i.e. before setting clear enable. \
*/ \
lba_t32 = READ_REG32((d)->hba.base_addr + LBA_PCI_CFG_ADDR); \
}
/*
* HPREVISIT:
* -- Can't tell if config cycle got the error.
*
* OV bit is broken until rev 4.0, so can't use OV bit and
* LBA_ERROR_LOG_ADDR to tell if error belongs to config cycle.
*
* As of rev 4.0, no longer need the error check.
*
* -- Even if we could tell, we still want to return -1
* for **ANY** error (not just master abort).
*
* -- Only clear non-fatal errors (we don't want to bring
* LBA out of pci-fatal mode).
*
* Actually, there is still a race in which
* we could be clearing a fatal error. We will
* live with this during our initial bus walk
* until rev 4.0 (no driver activity during
* initial bus walk). The initial bus walk
* has race conditions concerning the use of
* smart mode as well.
*/
#define LBA_MASTER_ABORT_ERROR 0xc
#define LBA_FATAL_ERROR 0x10
#define LBA_CFG_MASTER_ABORT_CHECK(d, base, tok, error) { \
u32 error_status = 0; \
/* \
* Set clear enable (CE) bit. Unset by HW when new \
* errors are logged -- LBA HW ERS section 14.3.3). \
*/ \
WRITE_REG32(status_control | CLEAR_ERRLOG_ENABLE, base + LBA_STAT_CTL); \
error_status = READ_REG32(base + LBA_ERROR_STATUS); \
if ((error_status & 0x1f) != 0) { \
/* \
* Fail the config read request. \
*/ \
error = 1; \
if ((error_status & LBA_FATAL_ERROR) == 0) { \
/* \
* Clear error status (if fatal bit not set) by setting \
* clear error log bit (CL). \
*/ \
WRITE_REG32(status_control | CLEAR_ERRLOG, base + LBA_STAT_CTL); \
} \
} \
}
#define LBA_CFG_TR4_ADDR_SETUP(d, addr) \
WRITE_REG32(((addr) & ~3), (d)->hba.base_addr + LBA_PCI_CFG_ADDR);
#define LBA_CFG_ADDR_SETUP(d, addr) { \
WRITE_REG32(((addr) & ~3), (d)->hba.base_addr + LBA_PCI_CFG_ADDR); \
/* \
* Read address register to ensure that LBA is the bus master, \
* which implies that DMA traffic has stopped when DMA arb is off. \
*/ \
lba_t32 = READ_REG32((d)->hba.base_addr + LBA_PCI_CFG_ADDR); \
}
#define LBA_CFG_RESTORE(d, base) { \
/* \
* Restore status control register (turn off clear enable). \
*/ \
WRITE_REG32(status_control, base + LBA_STAT_CTL); \
/* \
* Restore error config register (turn off smart mode). \
*/ \
WRITE_REG32(error_config, base + LBA_ERROR_CONFIG); \
/* \
* Restore arb mask register (reenables DMA arbitration). \
*/ \
WRITE_REG32(arb_mask, base + LBA_ARB_MASK); \
}
static unsigned int
lba_rd_cfg(struct lba_device *d, u32 tok, u8 reg, u32 size)
{
u32 data = ~0U;
int error = 0;
u32 arb_mask = 0; /* used by LBA_CFG_SETUP/RESTORE */
u32 error_config = 0; /* used by LBA_CFG_SETUP/RESTORE */
u32 status_control = 0; /* used by LBA_CFG_SETUP/RESTORE */
LBA_CFG_SETUP(d, tok);
LBA_CFG_PROBE(d, tok);
LBA_CFG_MASTER_ABORT_CHECK(d, d->hba.base_addr, tok, error);
if (!error) {
void __iomem *data_reg = d->hba.base_addr + LBA_PCI_CFG_DATA;
LBA_CFG_ADDR_SETUP(d, tok | reg);
switch (size) {
case 1: data = (u32) READ_REG8(data_reg + (reg & 3)); break;
case 2: data = (u32) READ_REG16(data_reg+ (reg & 2)); break;
case 4: data = READ_REG32(data_reg); break;
}
}
LBA_CFG_RESTORE(d, d->hba.base_addr);
return(data);
}
static int elroy_cfg_read(struct pci_bus *bus, unsigned int devfn, int pos, int size, u32 *data)
{
struct lba_device *d = LBA_DEV(parisc_walk_tree(bus->bridge));
u32 local_bus = (bus->parent == NULL) ? 0 : bus->secondary;
u32 tok = LBA_CFG_TOK(local_bus, devfn);
void __iomem *data_reg = d->hba.base_addr + LBA_PCI_CFG_DATA;
if ((pos > 255) || (devfn > 255))
return -EINVAL;
/* FIXME: B2K/C3600 workaround is always use old method... */
/* if (!LBA_SKIP_PROBE(d)) */ {
/* original - Generate config cycle on broken elroy
with risk we will miss PCI bus errors. */
*data = lba_rd_cfg(d, tok, pos, size);
DBG_CFG("%s(%x+%2x) -> 0x%x (a)\n", __func__, tok, pos, *data);
return 0;
}
if (LBA_SKIP_PROBE(d) && !lba_device_present(bus->secondary, devfn, d)) {
DBG_CFG("%s(%x+%2x) -> -1 (b)\n", __func__, tok, pos);
/* either don't want to look or know device isn't present. */
*data = ~0U;
return(0);
}
/* Basic Algorithm
** Should only get here on fully working LBA rev.
** This is how simple the code should have been.
*/
LBA_CFG_ADDR_SETUP(d, tok | pos);
switch(size) {
case 1: *data = READ_REG8 (data_reg + (pos & 3)); break;
case 2: *data = READ_REG16(data_reg + (pos & 2)); break;
case 4: *data = READ_REG32(data_reg); break;
}
DBG_CFG("%s(%x+%2x) -> 0x%x (c)\n", __func__, tok, pos, *data);
return 0;
}
static void
lba_wr_cfg(struct lba_device *d, u32 tok, u8 reg, u32 data, u32 size)
{
int error = 0;
u32 arb_mask = 0;
u32 error_config = 0;
u32 status_control = 0;
void __iomem *data_reg = d->hba.base_addr + LBA_PCI_CFG_DATA;
LBA_CFG_SETUP(d, tok);
LBA_CFG_ADDR_SETUP(d, tok | reg);
switch (size) {
case 1: WRITE_REG8 (data, data_reg + (reg & 3)); break;
case 2: WRITE_REG16(data, data_reg + (reg & 2)); break;
case 4: WRITE_REG32(data, data_reg); break;
}
LBA_CFG_MASTER_ABORT_CHECK(d, d->hba.base_addr, tok, error);
LBA_CFG_RESTORE(d, d->hba.base_addr);
}
/*
* LBA 4.0 config write code implements non-postable semantics
* by doing a read of CONFIG ADDR after the write.
*/
static int elroy_cfg_write(struct pci_bus *bus, unsigned int devfn, int pos, int size, u32 data)
{
struct lba_device *d = LBA_DEV(parisc_walk_tree(bus->bridge));
u32 local_bus = (bus->parent == NULL) ? 0 : bus->secondary;
u32 tok = LBA_CFG_TOK(local_bus,devfn);
if ((pos > 255) || (devfn > 255))
return -EINVAL;
if (!LBA_SKIP_PROBE(d)) {
/* Original Workaround */
lba_wr_cfg(d, tok, pos, (u32) data, size);
DBG_CFG("%s(%x+%2x) = 0x%x (a)\n", __func__, tok, pos,data);
return 0;
}
if (LBA_SKIP_PROBE(d) && (!lba_device_present(bus->secondary, devfn, d))) {
DBG_CFG("%s(%x+%2x) = 0x%x (b)\n", __func__, tok, pos,data);
return 1; /* New Workaround */
}
DBG_CFG("%s(%x+%2x) = 0x%x (c)\n", __func__, tok, pos, data);
/* Basic Algorithm */
LBA_CFG_ADDR_SETUP(d, tok | pos);
switch(size) {
case 1: WRITE_REG8 (data, d->hba.base_addr + LBA_PCI_CFG_DATA + (pos & 3));
break;
case 2: WRITE_REG16(data, d->hba.base_addr + LBA_PCI_CFG_DATA + (pos & 2));
break;
case 4: WRITE_REG32(data, d->hba.base_addr + LBA_PCI_CFG_DATA);
break;
}
/* flush posted write */
lba_t32 = READ_REG32(d->hba.base_addr + LBA_PCI_CFG_ADDR);
return 0;
}
static struct pci_ops elroy_cfg_ops = {
.read = elroy_cfg_read,
.write = elroy_cfg_write,
};
/*
* The mercury_cfg_ops are slightly misnamed; they're also used for Elroy
* TR4.0 as no additional bugs were found in this areea between Elroy and
* Mercury
*/
static int mercury_cfg_read(struct pci_bus *bus, unsigned int devfn, int pos, int size, u32 *data)
{
struct lba_device *d = LBA_DEV(parisc_walk_tree(bus->bridge));
u32 local_bus = (bus->parent == NULL) ? 0 : bus->secondary;
u32 tok = LBA_CFG_TOK(local_bus, devfn);
void __iomem *data_reg = d->hba.base_addr + LBA_PCI_CFG_DATA;
if ((pos > 255) || (devfn > 255))
return -EINVAL;
LBA_CFG_TR4_ADDR_SETUP(d, tok | pos);
switch(size) {
case 1:
*data = READ_REG8(data_reg + (pos & 3));
break;
case 2:
*data = READ_REG16(data_reg + (pos & 2));
break;
case 4:
*data = READ_REG32(data_reg); break;
break;
}
DBG_CFG("mercury_cfg_read(%x+%2x) -> 0x%x\n", tok, pos, *data);
return 0;
}
/*
* LBA 4.0 config write code implements non-postable semantics
* by doing a read of CONFIG ADDR after the write.
*/
static int mercury_cfg_write(struct pci_bus *bus, unsigned int devfn, int pos, int size, u32 data)
{
struct lba_device *d = LBA_DEV(parisc_walk_tree(bus->bridge));
void __iomem *data_reg = d->hba.base_addr + LBA_PCI_CFG_DATA;
u32 local_bus = (bus->parent == NULL) ? 0 : bus->secondary;
u32 tok = LBA_CFG_TOK(local_bus,devfn);
if ((pos > 255) || (devfn > 255))
return -EINVAL;
DBG_CFG("%s(%x+%2x) <- 0x%x (c)\n", __func__, tok, pos, data);
LBA_CFG_TR4_ADDR_SETUP(d, tok | pos);
switch(size) {
case 1:
WRITE_REG8 (data, data_reg + (pos & 3));
break;
case 2:
WRITE_REG16(data, data_reg + (pos & 2));
break;
case 4:
WRITE_REG32(data, data_reg);
break;
}
/* flush posted write */
lba_t32 = READ_U32(d->hba.base_addr + LBA_PCI_CFG_ADDR);
return 0;
}
static struct pci_ops mercury_cfg_ops = {
.read = mercury_cfg_read,
.write = mercury_cfg_write,
};
static void
lba_bios_init(void)
{
DBG(MODULE_NAME ": lba_bios_init\n");
}
#ifdef CONFIG_64BIT
/*
* truncate_pat_collision: Deal with overlaps or outright collisions
* between PAT PDC reported ranges.
*
* Broken PA8800 firmware will report lmmio range that
* overlaps with CPU HPA. Just truncate the lmmio range.
*
* BEWARE: conflicts with this lmmio range may be an
* elmmio range which is pointing down another rope.
*
* FIXME: only deals with one collision per range...theoretically we
* could have several. Supporting more than one collision will get messy.
*/
static unsigned long
truncate_pat_collision(struct resource *root, struct resource *new)
{
unsigned long start = new->start;
unsigned long end = new->end;
struct resource *tmp = root->child;
if (end <= start || start < root->start || !tmp)
return 0;
/* find first overlap */
while (tmp && tmp->end < start)
tmp = tmp->sibling;
/* no entries overlap */
if (!tmp) return 0;
/* found one that starts behind the new one
** Don't need to do anything.
*/
if (tmp->start >= end) return 0;
if (tmp->start <= start) {
/* "front" of new one overlaps */
new->start = tmp->end + 1;
if (tmp->end >= end) {
/* AACCKK! totally overlaps! drop this range. */
return 1;
}
}
if (tmp->end < end ) {
/* "end" of new one overlaps */
new->end = tmp->start - 1;
}
printk(KERN_WARNING "LBA: Truncating lmmio_space [%lx/%lx] "
"to [%lx,%lx]\n",
start, end,
(long)new->start, (long)new->end );
return 0; /* truncation successful */
}
#else
#define truncate_pat_collision(r,n) (0)
#endif
/*
** The algorithm is generic code.
** But it needs to access local data structures to get the IRQ base.
** Could make this a "pci_fixup_irq(bus, region)" but not sure
** it's worth it.
**
** Called by do_pci_scan_bus() immediately after each PCI bus is walked.
** Resources aren't allocated until recursive buswalk below HBA is completed.
*/
static void
lba_fixup_bus(struct pci_bus *bus)
{
struct list_head *ln;
#ifdef FBB_SUPPORT
u16 status;
#endif
struct lba_device *ldev = LBA_DEV(parisc_walk_tree(bus->bridge));
int lba_portbase = HBA_PORT_BASE(ldev->hba.hba_num);
DBG("lba_fixup_bus(0x%p) bus %d platform_data 0x%p\n",
bus, bus->secondary, bus->bridge->platform_data);
/*
** Properly Setup MMIO resources for this bus.
** pci_alloc_primary_bus() mangles this.
*/
if (bus->parent) {
int i;
/* PCI-PCI Bridge */
pci_read_bridge_bases(bus);
for (i = PCI_BRIDGE_RESOURCES; i < PCI_NUM_RESOURCES; i++) {
pci_claim_resource(bus->self, i);
}
} else {
/* Host-PCI Bridge */
int err, i;
DBG("lba_fixup_bus() %s [%lx/%lx]/%lx\n",
ldev->hba.io_space.name,
ldev->hba.io_space.start, ldev->hba.io_space.end,
ldev->hba.io_space.flags);
DBG("lba_fixup_bus() %s [%lx/%lx]/%lx\n",
ldev->hba.lmmio_space.name,
ldev->hba.lmmio_space.start, ldev->hba.lmmio_space.end,
ldev->hba.lmmio_space.flags);
err = request_resource(&ioport_resource, &(ldev->hba.io_space));
if (err < 0) {
lba_dump_res(&ioport_resource, 2);
BUG();
}
/* advertize Host bridge resources to PCI bus */
bus->resource[0] = &(ldev->hba.io_space);
i = 1;
if (ldev->hba.elmmio_space.start) {
err = request_resource(&iomem_resource,
&(ldev->hba.elmmio_space));
if (err < 0) {
printk("FAILED: lba_fixup_bus() request for "
"elmmio_space [%lx/%lx]\n",
(long)ldev->hba.elmmio_space.start,
(long)ldev->hba.elmmio_space.end);
/* lba_dump_res(&iomem_resource, 2); */
/* BUG(); */
} else
bus->resource[i++] = &(ldev->hba.elmmio_space);
}
/* Overlaps with elmmio can (and should) fail here.
* We will prune (or ignore) the distributed range.
*
* FIXME: SBA code should register all elmmio ranges first.
* that would take care of elmmio ranges routed
* to a different rope (already discovered) from
* getting registered *after* LBA code has already
* registered it's distributed lmmio range.
*/
if (truncate_pat_collision(&iomem_resource,
&(ldev->hba.lmmio_space))) {
printk(KERN_WARNING "LBA: lmmio_space [%lx/%lx] duplicate!\n",
(long)ldev->hba.lmmio_space.start,
(long)ldev->hba.lmmio_space.end);
} else {
err = request_resource(&iomem_resource, &(ldev->hba.lmmio_space));
if (err < 0) {
printk(KERN_ERR "FAILED: lba_fixup_bus() request for "
"lmmio_space [%lx/%lx]\n",
(long)ldev->hba.lmmio_space.start,
(long)ldev->hba.lmmio_space.end);
} else
bus->resource[i++] = &(ldev->hba.lmmio_space);
}
#ifdef CONFIG_64BIT
/* GMMIO is distributed range. Every LBA/Rope gets part it. */
if (ldev->hba.gmmio_space.flags) {
err = request_resource(&iomem_resource, &(ldev->hba.gmmio_space));
if (err < 0) {
printk("FAILED: lba_fixup_bus() request for "
"gmmio_space [%lx/%lx]\n",
(long)ldev->hba.gmmio_space.start,
(long)ldev->hba.gmmio_space.end);
lba_dump_res(&iomem_resource, 2);
BUG();
}
bus->resource[i++] = &(ldev->hba.gmmio_space);
}
#endif
}
list_for_each(ln, &bus->devices) {
int i;
struct pci_dev *dev = pci_dev_b(ln);
DBG("lba_fixup_bus() %s\n", pci_name(dev));
/* Virtualize Device/Bridge Resources. */
for (i = 0; i < PCI_BRIDGE_RESOURCES; i++) {
struct resource *res = &dev->resource[i];
/* If resource not allocated - skip it */
if (!res->start)
continue;
if (res->flags & IORESOURCE_IO) {
DBG("lba_fixup_bus() I/O Ports [%lx/%lx] -> ",
res->start, res->end);
res->start |= lba_portbase;
res->end |= lba_portbase;
DBG("[%lx/%lx]\n", res->start, res->end);
} else if (res->flags & IORESOURCE_MEM) {
/*
** Convert PCI (IO_VIEW) addresses to
** processor (PA_VIEW) addresses
*/
DBG("lba_fixup_bus() MMIO [%lx/%lx] -> ",
res->start, res->end);
res->start = PCI_HOST_ADDR(HBA_DATA(ldev), res->start);
res->end = PCI_HOST_ADDR(HBA_DATA(ldev), res->end);
DBG("[%lx/%lx]\n", res->start, res->end);
} else {
DBG("lba_fixup_bus() WTF? 0x%lx [%lx/%lx] XXX",
res->flags, res->start, res->end);
}
/*
** FIXME: this will result in whinging for devices
** that share expansion ROMs (think quad tulip), but
** isn't harmful.
*/
pci_claim_resource(dev, i);
}
#ifdef FBB_SUPPORT
/*
** If one device does not support FBB transfers,
** No one on the bus can be allowed to use them.
*/
(void) pci_read_config_word(dev, PCI_STATUS, &status);
bus->bridge_ctl &= ~(status & PCI_STATUS_FAST_BACK);
#endif
/*
** P2PB's have no IRQs. ignore them.
*/
if ((dev->class >> 8) == PCI_CLASS_BRIDGE_PCI)
continue;
/* Adjust INTERRUPT_LINE for this dev */
iosapic_fixup_irq(ldev->iosapic_obj, dev);
}
#ifdef FBB_SUPPORT
/* FIXME/REVISIT - finish figuring out to set FBB on both
** pci_setup_bridge() clobbers PCI_BRIDGE_CONTROL.
** Can't fixup here anyway....garr...
*/
if (fbb_enable) {
if (bus->parent) {
u8 control;
/* enable on PPB */
(void) pci_read_config_byte(bus->self, PCI_BRIDGE_CONTROL, &control);
(void) pci_write_config_byte(bus->self, PCI_BRIDGE_CONTROL, control | PCI_STATUS_FAST_BACK);
} else {
/* enable on LBA */
}
fbb_enable = PCI_COMMAND_FAST_BACK;
}
/* Lastly enable FBB/PERR/SERR on all devices too */
list_for_each(ln, &bus->devices) {
(void) pci_read_config_word(dev, PCI_COMMAND, &status);
status |= PCI_COMMAND_PARITY | PCI_COMMAND_SERR | fbb_enable;
(void) pci_write_config_word(dev, PCI_COMMAND, status);
}
#endif
}
static struct pci_bios_ops lba_bios_ops = {
.init = lba_bios_init,
.fixup_bus = lba_fixup_bus,
};
/*******************************************************
**
** LBA Sprockets "I/O Port" Space Accessor Functions
**
** This set of accessor functions is intended for use with
** "legacy firmware" (ie Sprockets on Allegro/Forte boxes).
**
** Many PCI devices don't require use of I/O port space (eg Tulip,
** NCR720) since they export the same registers to both MMIO and
** I/O port space. In general I/O port space is slower than
** MMIO since drivers are designed so PIO writes can be posted.
**
********************************************************/
#define LBA_PORT_IN(size, mask) \
static u##size lba_astro_in##size (struct pci_hba_data *d, u16 addr) \
{ \
u##size t; \
t = READ_REG##size(astro_iop_base + addr); \
DBG_PORT(" 0x%x\n", t); \
return (t); \
}
LBA_PORT_IN( 8, 3)
LBA_PORT_IN(16, 2)
LBA_PORT_IN(32, 0)
/*
** BUG X4107: Ordering broken - DMA RD return can bypass PIO WR
**
** Fixed in Elroy 2.2. The READ_U32(..., LBA_FUNC_ID) below is
** guarantee non-postable completion semantics - not avoid X4107.
** The READ_U32 only guarantees the write data gets to elroy but
** out to the PCI bus. We can't read stuff from I/O port space
** since we don't know what has side-effects. Attempting to read
** from configuration space would be suicidal given the number of
** bugs in that elroy functionality.
**
** Description:
** DMA read results can improperly pass PIO writes (X4107). The
** result of this bug is that if a processor modifies a location in
** memory after having issued PIO writes, the PIO writes are not
** guaranteed to be completed before a PCI device is allowed to see
** the modified data in a DMA read.
**
** Note that IKE bug X3719 in TR1 IKEs will result in the same
** symptom.
**
** Workaround:
** The workaround for this bug is to always follow a PIO write with
** a PIO read to the same bus before starting DMA on that PCI bus.
**
*/
#define LBA_PORT_OUT(size, mask) \
static void lba_astro_out##size (struct pci_hba_data *d, u16 addr, u##size val) \
{ \
DBG_PORT("%s(0x%p, 0x%x, 0x%x)\n", __func__, d, addr, val); \
WRITE_REG##size(val, astro_iop_base + addr); \
if (LBA_DEV(d)->hw_rev < 3) \
lba_t32 = READ_U32(d->base_addr + LBA_FUNC_ID); \
}
LBA_PORT_OUT( 8, 3)
LBA_PORT_OUT(16, 2)
LBA_PORT_OUT(32, 0)
static struct pci_port_ops lba_astro_port_ops = {
.inb = lba_astro_in8,
.inw = lba_astro_in16,
.inl = lba_astro_in32,
.outb = lba_astro_out8,
.outw = lba_astro_out16,
.outl = lba_astro_out32
};
#ifdef CONFIG_64BIT
#define PIOP_TO_GMMIO(lba, addr) \
((lba)->iop_base + (((addr)&0xFFFC)<<10) + ((addr)&3))
/*******************************************************
**
** LBA PAT "I/O Port" Space Accessor Functions
**
** This set of accessor functions is intended for use with
** "PAT PDC" firmware (ie Prelude/Rhapsody/Piranha boxes).
**
** This uses the PIOP space located in the first 64MB of GMMIO.
** Each rope gets a full 64*KB* (ie 4 bytes per page) this way.
** bits 1:0 stay the same. bits 15:2 become 25:12.
** Then add the base and we can generate an I/O Port cycle.
********************************************************/
#undef LBA_PORT_IN
#define LBA_PORT_IN(size, mask) \
static u##size lba_pat_in##size (struct pci_hba_data *l, u16 addr) \
{ \
u##size t; \
DBG_PORT("%s(0x%p, 0x%x) ->", __func__, l, addr); \
t = READ_REG##size(PIOP_TO_GMMIO(LBA_DEV(l), addr)); \
DBG_PORT(" 0x%x\n", t); \
return (t); \
}
LBA_PORT_IN( 8, 3)
LBA_PORT_IN(16, 2)
LBA_PORT_IN(32, 0)
#undef LBA_PORT_OUT
#define LBA_PORT_OUT(size, mask) \
static void lba_pat_out##size (struct pci_hba_data *l, u16 addr, u##size val) \
{ \
void __iomem *where = PIOP_TO_GMMIO(LBA_DEV(l), addr); \
DBG_PORT("%s(0x%p, 0x%x, 0x%x)\n", __func__, l, addr, val); \
WRITE_REG##size(val, where); \
/* flush the I/O down to the elroy at least */ \
lba_t32 = READ_U32(l->base_addr + LBA_FUNC_ID); \
}
LBA_PORT_OUT( 8, 3)
LBA_PORT_OUT(16, 2)
LBA_PORT_OUT(32, 0)
static struct pci_port_ops lba_pat_port_ops = {
.inb = lba_pat_in8,
.inw = lba_pat_in16,
.inl = lba_pat_in32,
.outb = lba_pat_out8,
.outw = lba_pat_out16,
.outl = lba_pat_out32
};
/*
** make range information from PDC available to PCI subsystem.
** We make the PDC call here in order to get the PCI bus range
** numbers. The rest will get forwarded in pcibios_fixup_bus().
** We don't have a struct pci_bus assigned to us yet.
*/
static void
lba_pat_resources(struct parisc_device *pa_dev, struct lba_device *lba_dev)
{
unsigned long bytecnt;
long io_count;
long status; /* PDC return status */
long pa_count;
pdc_pat_cell_mod_maddr_block_t *pa_pdc_cell; /* PA_VIEW */
pdc_pat_cell_mod_maddr_block_t *io_pdc_cell; /* IO_VIEW */
int i;
pa_pdc_cell = kzalloc(sizeof(pdc_pat_cell_mod_maddr_block_t), GFP_KERNEL);
if (!pa_pdc_cell)
return;
io_pdc_cell = kzalloc(sizeof(pdc_pat_cell_mod_maddr_block_t), GFP_KERNEL);
if (!io_pdc_cell) {
kfree(pa_pdc_cell);
return;
}
/* return cell module (IO view) */
status = pdc_pat_cell_module(&bytecnt, pa_dev->pcell_loc, pa_dev->mod_index,
PA_VIEW, pa_pdc_cell);
pa_count = pa_pdc_cell->mod[1];
status |= pdc_pat_cell_module(&bytecnt, pa_dev->pcell_loc, pa_dev->mod_index,
IO_VIEW, io_pdc_cell);
io_count = io_pdc_cell->mod[1];
/* We've already done this once for device discovery...*/
if (status != PDC_OK) {
panic("pdc_pat_cell_module() call failed for LBA!\n");
}
if (PAT_GET_ENTITY(pa_pdc_cell->mod_info) != PAT_ENTITY_LBA) {
panic("pdc_pat_cell_module() entity returned != PAT_ENTITY_LBA!\n");
}
/*
** Inspect the resources PAT tells us about
*/
for (i = 0; i < pa_count; i++) {
struct {
unsigned long type;
unsigned long start;
unsigned long end; /* aka finish */
} *p, *io;
struct resource *r;
p = (void *) &(pa_pdc_cell->mod[2+i*3]);
io = (void *) &(io_pdc_cell->mod[2+i*3]);
/* Convert the PAT range data to PCI "struct resource" */
switch(p->type & 0xff) {
case PAT_PBNUM:
lba_dev->hba.bus_num.start = p->start;
lba_dev->hba.bus_num.end = p->end;
break;
case PAT_LMMIO:
/* used to fix up pre-initialized MEM BARs */
if (!lba_dev->hba.lmmio_space.start) {
sprintf(lba_dev->hba.lmmio_name,
"PCI%02x LMMIO",
(int)lba_dev->hba.bus_num.start);
lba_dev->hba.lmmio_space_offset = p->start -
io->start;
r = &lba_dev->hba.lmmio_space;
r->name = lba_dev->hba.lmmio_name;
} else if (!lba_dev->hba.elmmio_space.start) {
sprintf(lba_dev->hba.elmmio_name,
"PCI%02x ELMMIO",
(int)lba_dev->hba.bus_num.start);
r = &lba_dev->hba.elmmio_space;
r->name = lba_dev->hba.elmmio_name;
} else {
printk(KERN_WARNING MODULE_NAME
" only supports 2 LMMIO resources!\n");
break;
}
r->start = p->start;
r->end = p->end;
r->flags = IORESOURCE_MEM;
r->parent = r->sibling = r->child = NULL;
break;
case PAT_GMMIO:
/* MMIO space > 4GB phys addr; for 64-bit BAR */
sprintf(lba_dev->hba.gmmio_name, "PCI%02x GMMIO",
(int)lba_dev->hba.bus_num.start);
r = &lba_dev->hba.gmmio_space;
r->name = lba_dev->hba.gmmio_name;
r->start = p->start;
r->end = p->end;
r->flags = IORESOURCE_MEM;
r->parent = r->sibling = r->child = NULL;
break;
case PAT_NPIOP:
printk(KERN_WARNING MODULE_NAME
" range[%d] : ignoring NPIOP (0x%lx)\n",
i, p->start);
break;
case PAT_PIOP:
/*
** Postable I/O port space is per PCI host adapter.
** base of 64MB PIOP region
*/
lba_dev->iop_base = ioremap_nocache(p->start, 64 * 1024 * 1024);
sprintf(lba_dev->hba.io_name, "PCI%02x Ports",
(int)lba_dev->hba.bus_num.start);
r = &lba_dev->hba.io_space;
r->name = lba_dev->hba.io_name;
r->start = HBA_PORT_BASE(lba_dev->hba.hba_num);
r->end = r->start + HBA_PORT_SPACE_SIZE - 1;
r->flags = IORESOURCE_IO;
r->parent = r->sibling = r->child = NULL;
break;
default:
printk(KERN_WARNING MODULE_NAME
" range[%d] : unknown pat range type (0x%lx)\n",
i, p->type & 0xff);
break;
}
}
kfree(pa_pdc_cell);
kfree(io_pdc_cell);
}
#else
/* keep compiler from complaining about missing declarations */
#define lba_pat_port_ops lba_astro_port_ops
#define lba_pat_resources(pa_dev, lba_dev)
#endif /* CONFIG_64BIT */
extern void sba_distributed_lmmio(struct parisc_device *, struct resource *);
extern void sba_directed_lmmio(struct parisc_device *, struct resource *);
static void
lba_legacy_resources(struct parisc_device *pa_dev, struct lba_device *lba_dev)
{
struct resource *r;
int lba_num;
lba_dev->hba.lmmio_space_offset = PCI_F_EXTEND;
/*
** With "legacy" firmware, the lowest byte of FW_SCRATCH
** represents bus->secondary and the second byte represents
** bus->subsidiary (i.e. highest PPB programmed by firmware).
** PCI bus walk *should* end up with the same result.
** FIXME: But we don't have sanity checks in PCI or LBA.
*/
lba_num = READ_REG32(lba_dev->hba.base_addr + LBA_FW_SCRATCH);
r = &(lba_dev->hba.bus_num);
r->name = "LBA PCI Busses";
r->start = lba_num & 0xff;
r->end = (lba_num>>8) & 0xff;
/* Set up local PCI Bus resources - we don't need them for
** Legacy boxes but it's nice to see in /proc/iomem.
*/
r = &(lba_dev->hba.lmmio_space);
sprintf(lba_dev->hba.lmmio_name, "PCI%02x LMMIO",
(int)lba_dev->hba.bus_num.start);
r->name = lba_dev->hba.lmmio_name;
#if 1
/* We want the CPU -> IO routing of addresses.
* The SBA BASE/MASK registers control CPU -> IO routing.
* Ask SBA what is routed to this rope/LBA.
*/
sba_distributed_lmmio(pa_dev, r);
#else
/*
* The LBA BASE/MASK registers control IO -> System routing.
*
* The following code works but doesn't get us what we want.
* Well, only because firmware (v5.0) on C3000 doesn't program
* the LBA BASE/MASE registers to be the exact inverse of
* the corresponding SBA registers. Other Astro/Pluto
* based platform firmware may do it right.
*
* Should someone want to mess with MSI, they may need to
* reprogram LBA BASE/MASK registers. Thus preserve the code
* below until MSI is known to work on C3000/A500/N4000/RP3440.
*
* Using the code below, /proc/iomem shows:
* ...
* f0000000-f0ffffff : PCI00 LMMIO
* f05d0000-f05d0000 : lcd_data
* f05d0008-f05d0008 : lcd_cmd
* f1000000-f1ffffff : PCI01 LMMIO
* f4000000-f4ffffff : PCI02 LMMIO
* f4000000-f4001fff : sym53c8xx
* f4002000-f4003fff : sym53c8xx
* f4004000-f40043ff : sym53c8xx
* f4005000-f40053ff : sym53c8xx
* f4007000-f4007fff : ohci_hcd
* f4008000-f40083ff : tulip
* f6000000-f6ffffff : PCI03 LMMIO
* f8000000-fbffffff : PCI00 ELMMIO
* fa100000-fa4fffff : stifb mmio
* fb000000-fb1fffff : stifb fb
*
* But everything listed under PCI02 actually lives under PCI00.
* This is clearly wrong.
*
* Asking SBA how things are routed tells the correct story:
* LMMIO_BASE/MASK/ROUTE f4000001 fc000000 00000000
* DIR0_BASE/MASK/ROUTE fa000001 fe000000 00000006
* DIR1_BASE/MASK/ROUTE f9000001 ff000000 00000004
* DIR2_BASE/MASK/ROUTE f0000000 fc000000 00000000
* DIR3_BASE/MASK/ROUTE f0000000 fc000000 00000000
*
* Which looks like this in /proc/iomem:
* f4000000-f47fffff : PCI00 LMMIO
* f4000000-f4001fff : sym53c8xx
* ...[deteled core devices - same as above]...
* f4008000-f40083ff : tulip
* f4800000-f4ffffff : PCI01 LMMIO
* f6000000-f67fffff : PCI02 LMMIO
* f7000000-f77fffff : PCI03 LMMIO
* f9000000-f9ffffff : PCI02 ELMMIO
* fa000000-fbffffff : PCI03 ELMMIO
* fa100000-fa4fffff : stifb mmio
* fb000000-fb1fffff : stifb fb
*
* ie all Built-in core are under now correctly under PCI00.
* The "PCI02 ELMMIO" directed range is for:
* +-[02]---03.0 3Dfx Interactive, Inc. Voodoo 2
*
* All is well now.
*/
r->start = READ_REG32(lba_dev->hba.base_addr + LBA_LMMIO_BASE);
if (r->start & 1) {
unsigned long rsize;
r->flags = IORESOURCE_MEM;
/* mmio_mask also clears Enable bit */
r->start &= mmio_mask;
r->start = PCI_HOST_ADDR(HBA_DATA(lba_dev), r->start);
rsize = ~ READ_REG32(lba_dev->hba.base_addr + LBA_LMMIO_MASK);
/*
** Each rope only gets part of the distributed range.
** Adjust "window" for this rope.
*/
rsize /= ROPES_PER_IOC;
r->start += (rsize + 1) * LBA_NUM(pa_dev->hpa.start);
r->end = r->start + rsize;
} else {
r->end = r->start = 0; /* Not enabled. */
}
#endif
/*
** "Directed" ranges are used when the "distributed range" isn't
** sufficient for all devices below a given LBA. Typically devices
** like graphics cards or X25 may need a directed range when the
** bus has multiple slots (ie multiple devices) or the device
** needs more than the typical 4 or 8MB a distributed range offers.
**
** The main reason for ignoring it now frigging complications.
** Directed ranges may overlap (and have precedence) over
** distributed ranges. Or a distributed range assigned to a unused
** rope may be used by a directed range on a different rope.
** Support for graphics devices may require fixing this
** since they may be assigned a directed range which overlaps
** an existing (but unused portion of) distributed range.
*/
r = &(lba_dev->hba.elmmio_space);
sprintf(lba_dev->hba.elmmio_name, "PCI%02x ELMMIO",
(int)lba_dev->hba.bus_num.start);
r->name = lba_dev->hba.elmmio_name;
#if 1
/* See comment which precedes call to sba_directed_lmmio() */
sba_directed_lmmio(pa_dev, r);
#else
r->start = READ_REG32(lba_dev->hba.base_addr + LBA_ELMMIO_BASE);
if (r->start & 1) {
unsigned long rsize;
r->flags = IORESOURCE_MEM;
/* mmio_mask also clears Enable bit */
r->start &= mmio_mask;
r->start = PCI_HOST_ADDR(HBA_DATA(lba_dev), r->start);
rsize = READ_REG32(lba_dev->hba.base_addr + LBA_ELMMIO_MASK);
r->end = r->start + ~rsize;
}
#endif
r = &(lba_dev->hba.io_space);
sprintf(lba_dev->hba.io_name, "PCI%02x Ports",
(int)lba_dev->hba.bus_num.start);
r->name = lba_dev->hba.io_name;
r->flags = IORESOURCE_IO;
r->start = READ_REG32(lba_dev->hba.base_addr + LBA_IOS_BASE) & ~1L;
r->end = r->start + (READ_REG32(lba_dev->hba.base_addr + LBA_IOS_MASK) ^ (HBA_PORT_SPACE_SIZE - 1));
/* Virtualize the I/O Port space ranges */
lba_num = HBA_PORT_BASE(lba_dev->hba.hba_num);
r->start |= lba_num;
r->end |= lba_num;
}
/**************************************************************************
**
** LBA initialization code (HW and SW)
**
** o identify LBA chip itself
** o initialize LBA chip modes (HardFail)
** o FIXME: initialize DMA hints for reasonable defaults
** o enable configuration functions
** o call pci_register_ops() to discover devs (fixup/fixup_bus get invoked)
**
**************************************************************************/
static int __init
lba_hw_init(struct lba_device *d)
{
u32 stat;
u32 bus_reset; /* PDC_PAT_BUG */
#if 0
printk(KERN_DEBUG "LBA %lx STAT_CTL %Lx ERROR_CFG %Lx STATUS %Lx DMA_CTL %Lx\n",
d->hba.base_addr,
READ_REG64(d->hba.base_addr + LBA_STAT_CTL),
READ_REG64(d->hba.base_addr + LBA_ERROR_CONFIG),
READ_REG64(d->hba.base_addr + LBA_ERROR_STATUS),
READ_REG64(d->hba.base_addr + LBA_DMA_CTL) );
printk(KERN_DEBUG " ARB mask %Lx pri %Lx mode %Lx mtlt %Lx\n",
READ_REG64(d->hba.base_addr + LBA_ARB_MASK),
READ_REG64(d->hba.base_addr + LBA_ARB_PRI),
READ_REG64(d->hba.base_addr + LBA_ARB_MODE),
READ_REG64(d->hba.base_addr + LBA_ARB_MTLT) );
printk(KERN_DEBUG " HINT cfg 0x%Lx\n",
READ_REG64(d->hba.base_addr + LBA_HINT_CFG));
printk(KERN_DEBUG " HINT reg ");
{ int i;
for (i=LBA_HINT_BASE; i< (14*8 + LBA_HINT_BASE); i+=8)
printk(" %Lx", READ_REG64(d->hba.base_addr + i));
}
printk("\n");
#endif /* DEBUG_LBA_PAT */
#ifdef CONFIG_64BIT
/*
* FIXME add support for PDC_PAT_IO "Get slot status" - OLAR support
* Only N-Class and up can really make use of Get slot status.
* maybe L-class too but I've never played with it there.
*/
#endif
/* PDC_PAT_BUG: exhibited in rev 40.48 on L2000 */
bus_reset = READ_REG32(d->hba.base_addr + LBA_STAT_CTL + 4) & 1;
if (bus_reset) {
printk(KERN_DEBUG "NOTICE: PCI bus reset still asserted! (clearing)\n");
}
stat = READ_REG32(d->hba.base_addr + LBA_ERROR_CONFIG);
if (stat & LBA_SMART_MODE) {
printk(KERN_DEBUG "NOTICE: LBA in SMART mode! (cleared)\n");
stat &= ~LBA_SMART_MODE;
WRITE_REG32(stat, d->hba.base_addr + LBA_ERROR_CONFIG);
}
/* Set HF mode as the default (vs. -1 mode). */
stat = READ_REG32(d->hba.base_addr + LBA_STAT_CTL);
WRITE_REG32(stat | HF_ENABLE, d->hba.base_addr + LBA_STAT_CTL);
/*
** Writing a zero to STAT_CTL.rf (bit 0) will clear reset signal
** if it's not already set. If we just cleared the PCI Bus Reset
** signal, wait a bit for the PCI devices to recover and setup.
*/
if (bus_reset)
mdelay(pci_post_reset_delay);
if (0 == READ_REG32(d->hba.base_addr + LBA_ARB_MASK)) {
/*
** PDC_PAT_BUG: PDC rev 40.48 on L2000.
** B2000/C3600/J6000 also have this problem?
**
** Elroys with hot pluggable slots don't get configured
** correctly if the slot is empty. ARB_MASK is set to 0
** and we can't master transactions on the bus if it's
** not at least one. 0x3 enables elroy and first slot.
*/
printk(KERN_DEBUG "NOTICE: Enabling PCI Arbitration\n");
WRITE_REG32(0x3, d->hba.base_addr + LBA_ARB_MASK);
}
/*
** FIXME: Hint registers are programmed with default hint
** values by firmware. Hints should be sane even if we
** can't reprogram them the way drivers want.
*/
return 0;
}
/*
* Unfortunately, when firmware numbers busses, it doesn't take into account
* Cardbus bridges. So we have to renumber the busses to suit ourselves.
* Elroy/Mercury don't actually know what bus number they're attached to;
* we use bus 0 to indicate the directly attached bus and any other bus
* number will be taken care of by the PCI-PCI bridge.
*/
static unsigned int lba_next_bus = 0;
/*
* Determine if lba should claim this chip (return 0) or not (return 1).
* If so, initialize the chip and tell other partners in crime they
* have work to do.
*/
static int __init
lba_driver_probe(struct parisc_device *dev)
{
struct lba_device *lba_dev;
struct pci_bus *lba_bus;
struct pci_ops *cfg_ops;
u32 func_class;
void *tmp_obj;
char *version;
void __iomem *addr = ioremap_nocache(dev->hpa.start, 4096);
/* Read HW Rev First */
func_class = READ_REG32(addr + LBA_FCLASS);
if (IS_ELROY(dev)) {
func_class &= 0xf;
switch (func_class) {
case 0: version = "TR1.0"; break;
case 1: version = "TR2.0"; break;
case 2: version = "TR2.1"; break;
case 3: version = "TR2.2"; break;
case 4: version = "TR3.0"; break;
case 5: version = "TR4.0"; break;
default: version = "TR4+";
}
printk(KERN_INFO "Elroy version %s (0x%x) found at 0x%lx\n",
version, func_class & 0xf, (long)dev->hpa.start);
if (func_class < 2) {
printk(KERN_WARNING "Can't support LBA older than "
"TR2.1 - continuing under adversity.\n");
}
#if 0
/* Elroy TR4.0 should work with simple algorithm.
But it doesn't. Still missing something. *sigh*
*/
if (func_class > 4) {
cfg_ops = &mercury_cfg_ops;
} else
#endif
{
cfg_ops = &elroy_cfg_ops;
}
} else if (IS_MERCURY(dev) || IS_QUICKSILVER(dev)) {
int major, minor;
func_class &= 0xff;
major = func_class >> 4, minor = func_class & 0xf;
/* We could use one printk for both Elroy and Mercury,
* but for the mask for func_class.
*/
printk(KERN_INFO "%s version TR%d.%d (0x%x) found at 0x%lx\n",
IS_MERCURY(dev) ? "Mercury" : "Quicksilver", major,
minor, func_class, (long)dev->hpa.start);
cfg_ops = &mercury_cfg_ops;
} else {
printk(KERN_ERR "Unknown LBA found at 0x%lx\n",
(long)dev->hpa.start);
return -ENODEV;
}
/* Tell I/O SAPIC driver we have a IRQ handler/region. */
tmp_obj = iosapic_register(dev->hpa.start + LBA_IOSAPIC_BASE);
/* NOTE: PCI devices (e.g. 103c:1005 graphics card) which don't
** have an IRT entry will get NULL back from iosapic code.
*/
lba_dev = kzalloc(sizeof(struct lba_device), GFP_KERNEL);
if (!lba_dev) {
printk(KERN_ERR "lba_init_chip - couldn't alloc lba_device\n");
return(1);
}
/* ---------- First : initialize data we already have --------- */
lba_dev->hw_rev = func_class;
lba_dev->hba.base_addr = addr;
lba_dev->hba.dev = dev;
lba_dev->iosapic_obj = tmp_obj; /* save interrupt handle */
lba_dev->hba.iommu = sba_get_iommu(dev); /* get iommu data */
parisc_set_drvdata(dev, lba_dev);
/* ------------ Second : initialize common stuff ---------- */
pci_bios = &lba_bios_ops;
pcibios_register_hba(HBA_DATA(lba_dev));
spin_lock_init(&lba_dev->lba_lock);
if (lba_hw_init(lba_dev))
return(1);
/* ---------- Third : setup I/O Port and MMIO resources --------- */
if (is_pdc_pat()) {
/* PDC PAT firmware uses PIOP region of GMMIO space. */
pci_port = &lba_pat_port_ops;
/* Go ask PDC PAT what resources this LBA has */
lba_pat_resources(dev, lba_dev);
} else {
if (!astro_iop_base) {
/* Sprockets PDC uses NPIOP region */
astro_iop_base = ioremap_nocache(LBA_PORT_BASE, 64 * 1024);
pci_port = &lba_astro_port_ops;
}
/* Poke the chip a bit for /proc output */
lba_legacy_resources(dev, lba_dev);
}
if (lba_dev->hba.bus_num.start < lba_next_bus)
lba_dev->hba.bus_num.start = lba_next_bus;
dev->dev.platform_data = lba_dev;
lba_bus = lba_dev->hba.hba_bus =
pci_scan_bus_parented(&dev->dev, lba_dev->hba.bus_num.start,
cfg_ops, NULL);
/* This is in lieu of calling pci_assign_unassigned_resources() */
if (is_pdc_pat()) {
/* assign resources to un-initialized devices */
DBG_PAT("LBA pci_bus_size_bridges()\n");
pci_bus_size_bridges(lba_bus);
DBG_PAT("LBA pci_bus_assign_resources()\n");
pci_bus_assign_resources(lba_bus);
#ifdef DEBUG_LBA_PAT
DBG_PAT("\nLBA PIOP resource tree\n");
lba_dump_res(&lba_dev->hba.io_space, 2);
DBG_PAT("\nLBA LMMIO resource tree\n");
lba_dump_res(&lba_dev->hba.lmmio_space, 2);
#endif
}
pci_enable_bridges(lba_bus);
/*
** Once PCI register ops has walked the bus, access to config
** space is restricted. Avoids master aborts on config cycles.
** Early LBA revs go fatal on *any* master abort.
*/
if (cfg_ops == &elroy_cfg_ops) {
lba_dev->flags |= LBA_FLAG_SKIP_PROBE;
}
if (lba_bus) {
lba_next_bus = lba_bus->subordinate + 1;
pci_bus_add_devices(lba_bus);
}
/* Whew! Finally done! Tell services we got this one covered. */
return 0;
}
static struct parisc_device_id lba_tbl[] = {
{ HPHW_BRIDGE, HVERSION_REV_ANY_ID, ELROY_HVERS, 0xa },
{ HPHW_BRIDGE, HVERSION_REV_ANY_ID, MERCURY_HVERS, 0xa },
{ HPHW_BRIDGE, HVERSION_REV_ANY_ID, QUICKSILVER_HVERS, 0xa },
{ 0, }
};
static struct parisc_driver lba_driver = {
.name = MODULE_NAME,
.id_table = lba_tbl,
.probe = lba_driver_probe,
};
/*
** One time initialization to let the world know the LBA was found.
** Must be called exactly once before pci_init().
*/
void __init lba_init(void)
{
register_parisc_driver(&lba_driver);
}
/*
** Initialize the IBASE/IMASK registers for LBA (Elroy).
** Only called from sba_iommu.c in order to route ranges (MMIO vs DMA).
** sba_iommu is responsible for locking (none needed at init time).
*/
void lba_set_iregs(struct parisc_device *lba, u32 ibase, u32 imask)
{
void __iomem * base_addr = ioremap_nocache(lba->hpa.start, 4096);
imask <<= 2; /* adjust for hints - 2 more bits */
/* Make sure we aren't trying to set bits that aren't writeable. */
WARN_ON((ibase & 0x001fffff) != 0);
WARN_ON((imask & 0x001fffff) != 0);
DBG("%s() ibase 0x%x imask 0x%x\n", __func__, ibase, imask);
WRITE_REG32( imask, base_addr + LBA_IMASK);
WRITE_REG32( ibase, base_addr + LBA_IBASE);
iounmap(base_addr);
}
| gpl-2.0 |
percy-g2/android_kernel_motorola_msm8610 | drivers/power/wm97xx_battery.c | 4989 | 7306 | /*
* linux/drivers/power/wm97xx_battery.c
*
* Battery measurement code for WM97xx
*
* based on tosa_battery.c
*
* Copyright (C) 2008 Marek Vasut <marek.vasut@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/wm97xx.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/gpio.h>
#include <linux/irq.h>
#include <linux/slab.h>
static struct work_struct bat_work;
static DEFINE_MUTEX(work_lock);
static int bat_status = POWER_SUPPLY_STATUS_UNKNOWN;
static enum power_supply_property *prop;
static unsigned long wm97xx_read_bat(struct power_supply *bat_ps)
{
struct wm97xx_pdata *wmdata = bat_ps->dev->parent->platform_data;
struct wm97xx_batt_pdata *pdata = wmdata->batt_pdata;
return wm97xx_read_aux_adc(dev_get_drvdata(bat_ps->dev->parent),
pdata->batt_aux) * pdata->batt_mult /
pdata->batt_div;
}
static unsigned long wm97xx_read_temp(struct power_supply *bat_ps)
{
struct wm97xx_pdata *wmdata = bat_ps->dev->parent->platform_data;
struct wm97xx_batt_pdata *pdata = wmdata->batt_pdata;
return wm97xx_read_aux_adc(dev_get_drvdata(bat_ps->dev->parent),
pdata->temp_aux) * pdata->temp_mult /
pdata->temp_div;
}
static int wm97xx_bat_get_property(struct power_supply *bat_ps,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct wm97xx_pdata *wmdata = bat_ps->dev->parent->platform_data;
struct wm97xx_batt_pdata *pdata = wmdata->batt_pdata;
switch (psp) {
case POWER_SUPPLY_PROP_STATUS:
val->intval = bat_status;
break;
case POWER_SUPPLY_PROP_TECHNOLOGY:
val->intval = pdata->batt_tech;
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
if (pdata->batt_aux >= 0)
val->intval = wm97xx_read_bat(bat_ps);
else
return -EINVAL;
break;
case POWER_SUPPLY_PROP_TEMP:
if (pdata->temp_aux >= 0)
val->intval = wm97xx_read_temp(bat_ps);
else
return -EINVAL;
break;
case POWER_SUPPLY_PROP_VOLTAGE_MAX:
if (pdata->max_voltage >= 0)
val->intval = pdata->max_voltage;
else
return -EINVAL;
break;
case POWER_SUPPLY_PROP_VOLTAGE_MIN:
if (pdata->min_voltage >= 0)
val->intval = pdata->min_voltage;
else
return -EINVAL;
break;
case POWER_SUPPLY_PROP_PRESENT:
val->intval = 1;
break;
default:
return -EINVAL;
}
return 0;
}
static void wm97xx_bat_external_power_changed(struct power_supply *bat_ps)
{
schedule_work(&bat_work);
}
static void wm97xx_bat_update(struct power_supply *bat_ps)
{
int old_status = bat_status;
struct wm97xx_pdata *wmdata = bat_ps->dev->parent->platform_data;
struct wm97xx_batt_pdata *pdata = wmdata->batt_pdata;
mutex_lock(&work_lock);
bat_status = (pdata->charge_gpio >= 0) ?
(gpio_get_value(pdata->charge_gpio) ?
POWER_SUPPLY_STATUS_DISCHARGING :
POWER_SUPPLY_STATUS_CHARGING) :
POWER_SUPPLY_STATUS_UNKNOWN;
if (old_status != bat_status) {
pr_debug("%s: %i -> %i\n", bat_ps->name, old_status,
bat_status);
power_supply_changed(bat_ps);
}
mutex_unlock(&work_lock);
}
static struct power_supply bat_ps = {
.type = POWER_SUPPLY_TYPE_BATTERY,
.get_property = wm97xx_bat_get_property,
.external_power_changed = wm97xx_bat_external_power_changed,
.use_for_apm = 1,
};
static void wm97xx_bat_work(struct work_struct *work)
{
wm97xx_bat_update(&bat_ps);
}
static irqreturn_t wm97xx_chrg_irq(int irq, void *data)
{
schedule_work(&bat_work);
return IRQ_HANDLED;
}
#ifdef CONFIG_PM
static int wm97xx_bat_suspend(struct device *dev)
{
flush_work_sync(&bat_work);
return 0;
}
static int wm97xx_bat_resume(struct device *dev)
{
schedule_work(&bat_work);
return 0;
}
static const struct dev_pm_ops wm97xx_bat_pm_ops = {
.suspend = wm97xx_bat_suspend,
.resume = wm97xx_bat_resume,
};
#endif
static int __devinit wm97xx_bat_probe(struct platform_device *dev)
{
int ret = 0;
int props = 1; /* POWER_SUPPLY_PROP_PRESENT */
int i = 0;
struct wm97xx_pdata *wmdata = dev->dev.platform_data;
struct wm97xx_batt_pdata *pdata;
if (!wmdata) {
dev_err(&dev->dev, "No platform data supplied\n");
return -EINVAL;
}
pdata = wmdata->batt_pdata;
if (dev->id != -1)
return -EINVAL;
if (!pdata) {
dev_err(&dev->dev, "No platform_data supplied\n");
return -EINVAL;
}
if (gpio_is_valid(pdata->charge_gpio)) {
ret = gpio_request(pdata->charge_gpio, "BATT CHRG");
if (ret)
goto err;
ret = gpio_direction_input(pdata->charge_gpio);
if (ret)
goto err2;
ret = request_irq(gpio_to_irq(pdata->charge_gpio),
wm97xx_chrg_irq, 0,
"AC Detect", dev);
if (ret)
goto err2;
props++; /* POWER_SUPPLY_PROP_STATUS */
}
if (pdata->batt_tech >= 0)
props++; /* POWER_SUPPLY_PROP_TECHNOLOGY */
if (pdata->temp_aux >= 0)
props++; /* POWER_SUPPLY_PROP_TEMP */
if (pdata->batt_aux >= 0)
props++; /* POWER_SUPPLY_PROP_VOLTAGE_NOW */
if (pdata->max_voltage >= 0)
props++; /* POWER_SUPPLY_PROP_VOLTAGE_MAX */
if (pdata->min_voltage >= 0)
props++; /* POWER_SUPPLY_PROP_VOLTAGE_MIN */
prop = kzalloc(props * sizeof(*prop), GFP_KERNEL);
if (!prop)
goto err3;
prop[i++] = POWER_SUPPLY_PROP_PRESENT;
if (pdata->charge_gpio >= 0)
prop[i++] = POWER_SUPPLY_PROP_STATUS;
if (pdata->batt_tech >= 0)
prop[i++] = POWER_SUPPLY_PROP_TECHNOLOGY;
if (pdata->temp_aux >= 0)
prop[i++] = POWER_SUPPLY_PROP_TEMP;
if (pdata->batt_aux >= 0)
prop[i++] = POWER_SUPPLY_PROP_VOLTAGE_NOW;
if (pdata->max_voltage >= 0)
prop[i++] = POWER_SUPPLY_PROP_VOLTAGE_MAX;
if (pdata->min_voltage >= 0)
prop[i++] = POWER_SUPPLY_PROP_VOLTAGE_MIN;
INIT_WORK(&bat_work, wm97xx_bat_work);
if (!pdata->batt_name) {
dev_info(&dev->dev, "Please consider setting proper battery "
"name in platform definition file, falling "
"back to name \"wm97xx-batt\"\n");
bat_ps.name = "wm97xx-batt";
} else
bat_ps.name = pdata->batt_name;
bat_ps.properties = prop;
bat_ps.num_properties = props;
ret = power_supply_register(&dev->dev, &bat_ps);
if (!ret)
schedule_work(&bat_work);
else
goto err4;
return 0;
err4:
kfree(prop);
err3:
if (gpio_is_valid(pdata->charge_gpio))
free_irq(gpio_to_irq(pdata->charge_gpio), dev);
err2:
if (gpio_is_valid(pdata->charge_gpio))
gpio_free(pdata->charge_gpio);
err:
return ret;
}
static int __devexit wm97xx_bat_remove(struct platform_device *dev)
{
struct wm97xx_pdata *wmdata = dev->dev.platform_data;
struct wm97xx_batt_pdata *pdata = wmdata->batt_pdata;
if (pdata && gpio_is_valid(pdata->charge_gpio)) {
free_irq(gpio_to_irq(pdata->charge_gpio), dev);
gpio_free(pdata->charge_gpio);
}
cancel_work_sync(&bat_work);
power_supply_unregister(&bat_ps);
kfree(prop);
return 0;
}
static struct platform_driver wm97xx_bat_driver = {
.driver = {
.name = "wm97xx-battery",
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &wm97xx_bat_pm_ops,
#endif
},
.probe = wm97xx_bat_probe,
.remove = __devexit_p(wm97xx_bat_remove),
};
module_platform_driver(wm97xx_bat_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Marek Vasut <marek.vasut@gmail.com>");
MODULE_DESCRIPTION("WM97xx battery driver");
| gpl-2.0 |
flar2/m7-GPE | drivers/gpio/gpio-pca953x.c | 4989 | 17365 | /*
* PCA953x 4/8/16 bit I/O ports
*
* Copyright (C) 2005 Ben Gardner <bgardner@wabtec.com>
* Copyright (C) 2007 Marvell International Ltd.
*
* Derived from drivers/i2c/chips/pca9539.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; version 2 of the License.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/i2c.h>
#include <linux/i2c/pca953x.h>
#include <linux/slab.h>
#ifdef CONFIG_OF_GPIO
#include <linux/of_platform.h>
#endif
#define PCA953X_INPUT 0
#define PCA953X_OUTPUT 1
#define PCA953X_INVERT 2
#define PCA953X_DIRECTION 3
#define PCA957X_IN 0
#define PCA957X_INVRT 1
#define PCA957X_BKEN 2
#define PCA957X_PUPD 3
#define PCA957X_CFG 4
#define PCA957X_OUT 5
#define PCA957X_MSK 6
#define PCA957X_INTS 7
#define PCA_GPIO_MASK 0x00FF
#define PCA_INT 0x0100
#define PCA953X_TYPE 0x1000
#define PCA957X_TYPE 0x2000
static const struct i2c_device_id pca953x_id[] = {
{ "pca9534", 8 | PCA953X_TYPE | PCA_INT, },
{ "pca9535", 16 | PCA953X_TYPE | PCA_INT, },
{ "pca9536", 4 | PCA953X_TYPE, },
{ "pca9537", 4 | PCA953X_TYPE | PCA_INT, },
{ "pca9538", 8 | PCA953X_TYPE | PCA_INT, },
{ "pca9539", 16 | PCA953X_TYPE | PCA_INT, },
{ "pca9554", 8 | PCA953X_TYPE | PCA_INT, },
{ "pca9555", 16 | PCA953X_TYPE | PCA_INT, },
{ "pca9556", 8 | PCA953X_TYPE, },
{ "pca9557", 8 | PCA953X_TYPE, },
{ "pca9574", 8 | PCA957X_TYPE | PCA_INT, },
{ "pca9575", 16 | PCA957X_TYPE | PCA_INT, },
{ "max7310", 8 | PCA953X_TYPE, },
{ "max7312", 16 | PCA953X_TYPE | PCA_INT, },
{ "max7313", 16 | PCA953X_TYPE | PCA_INT, },
{ "max7315", 8 | PCA953X_TYPE | PCA_INT, },
{ "pca6107", 8 | PCA953X_TYPE | PCA_INT, },
{ "tca6408", 8 | PCA953X_TYPE | PCA_INT, },
{ "tca6416", 16 | PCA953X_TYPE | PCA_INT, },
/* NYET: { "tca6424", 24, }, */
{ }
};
MODULE_DEVICE_TABLE(i2c, pca953x_id);
struct pca953x_chip {
unsigned gpio_start;
uint16_t reg_output;
uint16_t reg_direction;
struct mutex i2c_lock;
#ifdef CONFIG_GPIO_PCA953X_IRQ
struct mutex irq_lock;
uint16_t irq_mask;
uint16_t irq_stat;
uint16_t irq_trig_raise;
uint16_t irq_trig_fall;
int irq_base;
#endif
struct i2c_client *client;
struct gpio_chip gpio_chip;
const char *const *names;
int chip_type;
};
static int pca953x_write_reg(struct pca953x_chip *chip, int reg, uint16_t val)
{
int ret = 0;
if (chip->gpio_chip.ngpio <= 8)
ret = i2c_smbus_write_byte_data(chip->client, reg, val);
else {
switch (chip->chip_type) {
case PCA953X_TYPE:
ret = i2c_smbus_write_word_data(chip->client,
reg << 1, val);
break;
case PCA957X_TYPE:
ret = i2c_smbus_write_byte_data(chip->client, reg << 1,
val & 0xff);
if (ret < 0)
break;
ret = i2c_smbus_write_byte_data(chip->client,
(reg << 1) + 1,
(val & 0xff00) >> 8);
break;
}
}
if (ret < 0) {
dev_err(&chip->client->dev, "failed writing register\n");
return ret;
}
return 0;
}
static int pca953x_read_reg(struct pca953x_chip *chip, int reg, uint16_t *val)
{
int ret;
if (chip->gpio_chip.ngpio <= 8)
ret = i2c_smbus_read_byte_data(chip->client, reg);
else
ret = i2c_smbus_read_word_data(chip->client, reg << 1);
if (ret < 0) {
dev_err(&chip->client->dev, "failed reading register\n");
return ret;
}
*val = (uint16_t)ret;
return 0;
}
static int pca953x_gpio_direction_input(struct gpio_chip *gc, unsigned off)
{
struct pca953x_chip *chip;
uint16_t reg_val;
int ret, offset = 0;
chip = container_of(gc, struct pca953x_chip, gpio_chip);
mutex_lock(&chip->i2c_lock);
reg_val = chip->reg_direction | (1u << off);
switch (chip->chip_type) {
case PCA953X_TYPE:
offset = PCA953X_DIRECTION;
break;
case PCA957X_TYPE:
offset = PCA957X_CFG;
break;
}
ret = pca953x_write_reg(chip, offset, reg_val);
if (ret)
goto exit;
chip->reg_direction = reg_val;
ret = 0;
exit:
mutex_unlock(&chip->i2c_lock);
return ret;
}
static int pca953x_gpio_direction_output(struct gpio_chip *gc,
unsigned off, int val)
{
struct pca953x_chip *chip;
uint16_t reg_val;
int ret, offset = 0;
chip = container_of(gc, struct pca953x_chip, gpio_chip);
mutex_lock(&chip->i2c_lock);
/* set output level */
if (val)
reg_val = chip->reg_output | (1u << off);
else
reg_val = chip->reg_output & ~(1u << off);
switch (chip->chip_type) {
case PCA953X_TYPE:
offset = PCA953X_OUTPUT;
break;
case PCA957X_TYPE:
offset = PCA957X_OUT;
break;
}
ret = pca953x_write_reg(chip, offset, reg_val);
if (ret)
goto exit;
chip->reg_output = reg_val;
/* then direction */
reg_val = chip->reg_direction & ~(1u << off);
switch (chip->chip_type) {
case PCA953X_TYPE:
offset = PCA953X_DIRECTION;
break;
case PCA957X_TYPE:
offset = PCA957X_CFG;
break;
}
ret = pca953x_write_reg(chip, offset, reg_val);
if (ret)
goto exit;
chip->reg_direction = reg_val;
ret = 0;
exit:
mutex_unlock(&chip->i2c_lock);
return ret;
}
static int pca953x_gpio_get_value(struct gpio_chip *gc, unsigned off)
{
struct pca953x_chip *chip;
uint16_t reg_val;
int ret, offset = 0;
chip = container_of(gc, struct pca953x_chip, gpio_chip);
mutex_lock(&chip->i2c_lock);
switch (chip->chip_type) {
case PCA953X_TYPE:
offset = PCA953X_INPUT;
break;
case PCA957X_TYPE:
offset = PCA957X_IN;
break;
}
ret = pca953x_read_reg(chip, offset, ®_val);
mutex_unlock(&chip->i2c_lock);
if (ret < 0) {
/* NOTE: diagnostic already emitted; that's all we should
* do unless gpio_*_value_cansleep() calls become different
* from their nonsleeping siblings (and report faults).
*/
return 0;
}
return (reg_val & (1u << off)) ? 1 : 0;
}
static void pca953x_gpio_set_value(struct gpio_chip *gc, unsigned off, int val)
{
struct pca953x_chip *chip;
uint16_t reg_val;
int ret, offset = 0;
chip = container_of(gc, struct pca953x_chip, gpio_chip);
mutex_lock(&chip->i2c_lock);
if (val)
reg_val = chip->reg_output | (1u << off);
else
reg_val = chip->reg_output & ~(1u << off);
switch (chip->chip_type) {
case PCA953X_TYPE:
offset = PCA953X_OUTPUT;
break;
case PCA957X_TYPE:
offset = PCA957X_OUT;
break;
}
ret = pca953x_write_reg(chip, offset, reg_val);
if (ret)
goto exit;
chip->reg_output = reg_val;
exit:
mutex_unlock(&chip->i2c_lock);
}
static void pca953x_setup_gpio(struct pca953x_chip *chip, int gpios)
{
struct gpio_chip *gc;
gc = &chip->gpio_chip;
gc->direction_input = pca953x_gpio_direction_input;
gc->direction_output = pca953x_gpio_direction_output;
gc->get = pca953x_gpio_get_value;
gc->set = pca953x_gpio_set_value;
gc->can_sleep = 1;
gc->base = chip->gpio_start;
gc->ngpio = gpios;
gc->label = chip->client->name;
gc->dev = &chip->client->dev;
gc->owner = THIS_MODULE;
gc->names = chip->names;
}
#ifdef CONFIG_GPIO_PCA953X_IRQ
static int pca953x_gpio_to_irq(struct gpio_chip *gc, unsigned off)
{
struct pca953x_chip *chip;
chip = container_of(gc, struct pca953x_chip, gpio_chip);
return chip->irq_base + off;
}
static void pca953x_irq_mask(struct irq_data *d)
{
struct pca953x_chip *chip = irq_data_get_irq_chip_data(d);
chip->irq_mask &= ~(1 << (d->irq - chip->irq_base));
}
static void pca953x_irq_unmask(struct irq_data *d)
{
struct pca953x_chip *chip = irq_data_get_irq_chip_data(d);
chip->irq_mask |= 1 << (d->irq - chip->irq_base);
}
static void pca953x_irq_bus_lock(struct irq_data *d)
{
struct pca953x_chip *chip = irq_data_get_irq_chip_data(d);
mutex_lock(&chip->irq_lock);
}
static void pca953x_irq_bus_sync_unlock(struct irq_data *d)
{
struct pca953x_chip *chip = irq_data_get_irq_chip_data(d);
uint16_t new_irqs;
uint16_t level;
/* Look for any newly setup interrupt */
new_irqs = chip->irq_trig_fall | chip->irq_trig_raise;
new_irqs &= ~chip->reg_direction;
while (new_irqs) {
level = __ffs(new_irqs);
pca953x_gpio_direction_input(&chip->gpio_chip, level);
new_irqs &= ~(1 << level);
}
mutex_unlock(&chip->irq_lock);
}
static int pca953x_irq_set_type(struct irq_data *d, unsigned int type)
{
struct pca953x_chip *chip = irq_data_get_irq_chip_data(d);
uint16_t level = d->irq - chip->irq_base;
uint16_t mask = 1 << level;
if (!(type & IRQ_TYPE_EDGE_BOTH)) {
dev_err(&chip->client->dev, "irq %d: unsupported type %d\n",
d->irq, type);
return -EINVAL;
}
if (type & IRQ_TYPE_EDGE_FALLING)
chip->irq_trig_fall |= mask;
else
chip->irq_trig_fall &= ~mask;
if (type & IRQ_TYPE_EDGE_RISING)
chip->irq_trig_raise |= mask;
else
chip->irq_trig_raise &= ~mask;
return 0;
}
static struct irq_chip pca953x_irq_chip = {
.name = "pca953x",
.irq_mask = pca953x_irq_mask,
.irq_unmask = pca953x_irq_unmask,
.irq_bus_lock = pca953x_irq_bus_lock,
.irq_bus_sync_unlock = pca953x_irq_bus_sync_unlock,
.irq_set_type = pca953x_irq_set_type,
};
static uint16_t pca953x_irq_pending(struct pca953x_chip *chip)
{
uint16_t cur_stat;
uint16_t old_stat;
uint16_t pending;
uint16_t trigger;
int ret, offset = 0;
switch (chip->chip_type) {
case PCA953X_TYPE:
offset = PCA953X_INPUT;
break;
case PCA957X_TYPE:
offset = PCA957X_IN;
break;
}
ret = pca953x_read_reg(chip, offset, &cur_stat);
if (ret)
return 0;
/* Remove output pins from the equation */
cur_stat &= chip->reg_direction;
old_stat = chip->irq_stat;
trigger = (cur_stat ^ old_stat) & chip->irq_mask;
if (!trigger)
return 0;
chip->irq_stat = cur_stat;
pending = (old_stat & chip->irq_trig_fall) |
(cur_stat & chip->irq_trig_raise);
pending &= trigger;
return pending;
}
static irqreturn_t pca953x_irq_handler(int irq, void *devid)
{
struct pca953x_chip *chip = devid;
uint16_t pending;
uint16_t level;
pending = pca953x_irq_pending(chip);
if (!pending)
return IRQ_HANDLED;
do {
level = __ffs(pending);
handle_nested_irq(level + chip->irq_base);
pending &= ~(1 << level);
} while (pending);
return IRQ_HANDLED;
}
static int pca953x_irq_setup(struct pca953x_chip *chip,
const struct i2c_device_id *id,
int irq_base)
{
struct i2c_client *client = chip->client;
int ret, offset = 0;
if (irq_base != -1
&& (id->driver_data & PCA_INT)) {
int lvl;
switch (chip->chip_type) {
case PCA953X_TYPE:
offset = PCA953X_INPUT;
break;
case PCA957X_TYPE:
offset = PCA957X_IN;
break;
}
ret = pca953x_read_reg(chip, offset, &chip->irq_stat);
if (ret)
goto out_failed;
/*
* There is no way to know which GPIO line generated the
* interrupt. We have to rely on the previous read for
* this purpose.
*/
chip->irq_stat &= chip->reg_direction;
mutex_init(&chip->irq_lock);
chip->irq_base = irq_alloc_descs(-1, irq_base, chip->gpio_chip.ngpio, -1);
if (chip->irq_base < 0)
goto out_failed;
for (lvl = 0; lvl < chip->gpio_chip.ngpio; lvl++) {
int irq = lvl + chip->irq_base;
irq_clear_status_flags(irq, IRQ_NOREQUEST);
irq_set_chip_data(irq, chip);
irq_set_chip(irq, &pca953x_irq_chip);
irq_set_nested_thread(irq, true);
#ifdef CONFIG_ARM
set_irq_flags(irq, IRQF_VALID);
#else
irq_set_noprobe(irq);
#endif
}
ret = request_threaded_irq(client->irq,
NULL,
pca953x_irq_handler,
IRQF_TRIGGER_LOW | IRQF_ONESHOT,
dev_name(&client->dev), chip);
if (ret) {
dev_err(&client->dev, "failed to request irq %d\n",
client->irq);
goto out_failed;
}
chip->gpio_chip.to_irq = pca953x_gpio_to_irq;
}
return 0;
out_failed:
chip->irq_base = -1;
return ret;
}
static void pca953x_irq_teardown(struct pca953x_chip *chip)
{
if (chip->irq_base != -1) {
irq_free_descs(chip->irq_base, chip->gpio_chip.ngpio);
free_irq(chip->client->irq, chip);
}
}
#else /* CONFIG_GPIO_PCA953X_IRQ */
static int pca953x_irq_setup(struct pca953x_chip *chip,
const struct i2c_device_id *id,
int irq_base)
{
struct i2c_client *client = chip->client;
if (irq_base != -1 && (id->driver_data & PCA_INT))
dev_warn(&client->dev, "interrupt support not compiled in\n");
return 0;
}
static void pca953x_irq_teardown(struct pca953x_chip *chip)
{
}
#endif
/*
* Handlers for alternative sources of platform_data
*/
#ifdef CONFIG_OF_GPIO
/*
* Translate OpenFirmware node properties into platform_data
* WARNING: This is DEPRECATED and will be removed eventually!
*/
static void
pca953x_get_alt_pdata(struct i2c_client *client, int *gpio_base, int *invert)
{
struct device_node *node;
const __be32 *val;
int size;
node = client->dev.of_node;
if (node == NULL)
return;
*gpio_base = -1;
val = of_get_property(node, "linux,gpio-base", &size);
WARN(val, "%s: device-tree property 'linux,gpio-base' is deprecated!", __func__);
if (val) {
if (size != sizeof(*val))
dev_warn(&client->dev, "%s: wrong linux,gpio-base\n",
node->full_name);
else
*gpio_base = be32_to_cpup(val);
}
val = of_get_property(node, "polarity", NULL);
WARN(val, "%s: device-tree property 'polarity' is deprecated!", __func__);
if (val)
*invert = *val;
}
#else
static void
pca953x_get_alt_pdata(struct i2c_client *client, int *gpio_base, int *invert)
{
*gpio_base = -1;
}
#endif
static int __devinit device_pca953x_init(struct pca953x_chip *chip, int invert)
{
int ret;
ret = pca953x_read_reg(chip, PCA953X_OUTPUT, &chip->reg_output);
if (ret)
goto out;
ret = pca953x_read_reg(chip, PCA953X_DIRECTION,
&chip->reg_direction);
if (ret)
goto out;
/* set platform specific polarity inversion */
ret = pca953x_write_reg(chip, PCA953X_INVERT, invert);
out:
return ret;
}
static int __devinit device_pca957x_init(struct pca953x_chip *chip, int invert)
{
int ret;
uint16_t val = 0;
/* Let every port in proper state, that could save power */
pca953x_write_reg(chip, PCA957X_PUPD, 0x0);
pca953x_write_reg(chip, PCA957X_CFG, 0xffff);
pca953x_write_reg(chip, PCA957X_OUT, 0x0);
ret = pca953x_read_reg(chip, PCA957X_IN, &val);
if (ret)
goto out;
ret = pca953x_read_reg(chip, PCA957X_OUT, &chip->reg_output);
if (ret)
goto out;
ret = pca953x_read_reg(chip, PCA957X_CFG, &chip->reg_direction);
if (ret)
goto out;
/* set platform specific polarity inversion */
pca953x_write_reg(chip, PCA957X_INVRT, invert);
/* To enable register 6, 7 to controll pull up and pull down */
pca953x_write_reg(chip, PCA957X_BKEN, 0x202);
return 0;
out:
return ret;
}
static int __devinit pca953x_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct pca953x_platform_data *pdata;
struct pca953x_chip *chip;
int irq_base=0, invert=0;
int ret;
chip = kzalloc(sizeof(struct pca953x_chip), GFP_KERNEL);
if (chip == NULL)
return -ENOMEM;
pdata = client->dev.platform_data;
if (pdata) {
irq_base = pdata->irq_base;
chip->gpio_start = pdata->gpio_base;
invert = pdata->invert;
chip->names = pdata->names;
} else {
pca953x_get_alt_pdata(client, &chip->gpio_start, &invert);
#ifdef CONFIG_OF_GPIO
/* If I2C node has no interrupts property, disable GPIO interrupts */
if (of_find_property(client->dev.of_node, "interrupts", NULL) == NULL)
irq_base = -1;
#endif
}
chip->client = client;
chip->chip_type = id->driver_data & (PCA953X_TYPE | PCA957X_TYPE);
mutex_init(&chip->i2c_lock);
/* initialize cached registers from their original values.
* we can't share this chip with another i2c master.
*/
pca953x_setup_gpio(chip, id->driver_data & PCA_GPIO_MASK);
if (chip->chip_type == PCA953X_TYPE)
ret = device_pca953x_init(chip, invert);
else
ret = device_pca957x_init(chip, invert);
if (ret)
goto out_failed;
ret = pca953x_irq_setup(chip, id, irq_base);
if (ret)
goto out_failed;
ret = gpiochip_add(&chip->gpio_chip);
if (ret)
goto out_failed_irq;
if (pdata && pdata->setup) {
ret = pdata->setup(client, chip->gpio_chip.base,
chip->gpio_chip.ngpio, pdata->context);
if (ret < 0)
dev_warn(&client->dev, "setup failed, %d\n", ret);
}
i2c_set_clientdata(client, chip);
return 0;
out_failed_irq:
pca953x_irq_teardown(chip);
out_failed:
kfree(chip);
return ret;
}
static int pca953x_remove(struct i2c_client *client)
{
struct pca953x_platform_data *pdata = client->dev.platform_data;
struct pca953x_chip *chip = i2c_get_clientdata(client);
int ret = 0;
if (pdata && pdata->teardown) {
ret = pdata->teardown(client, chip->gpio_chip.base,
chip->gpio_chip.ngpio, pdata->context);
if (ret < 0) {
dev_err(&client->dev, "%s failed, %d\n",
"teardown", ret);
return ret;
}
}
ret = gpiochip_remove(&chip->gpio_chip);
if (ret) {
dev_err(&client->dev, "%s failed, %d\n",
"gpiochip_remove()", ret);
return ret;
}
pca953x_irq_teardown(chip);
kfree(chip);
return 0;
}
static struct i2c_driver pca953x_driver = {
.driver = {
.name = "pca953x",
},
.probe = pca953x_probe,
.remove = pca953x_remove,
.id_table = pca953x_id,
};
static int __init pca953x_init(void)
{
return i2c_add_driver(&pca953x_driver);
}
/* register after i2c postcore initcall and before
* subsys initcalls that may rely on these GPIOs
*/
subsys_initcall(pca953x_init);
static void __exit pca953x_exit(void)
{
i2c_del_driver(&pca953x_driver);
}
module_exit(pca953x_exit);
MODULE_AUTHOR("eric miao <eric.miao@marvell.com>");
MODULE_DESCRIPTION("GPIO expander driver for PCA953x");
MODULE_LICENSE("GPL");
| gpl-2.0 |
gherkaul/kernel_lge_fx3 | arch/mips/kernel/ftrace.c | 5245 | 8673 | /*
* Code for replacing ftrace calls with jumps.
*
* Copyright (C) 2007-2008 Steven Rostedt <srostedt@redhat.com>
* Copyright (C) 2009, 2010 DSLab, Lanzhou University, China
* Author: Wu Zhangjin <wuzhangjin@gmail.com>
*
* Thanks goes to Steven Rostedt for writing the original x86 version.
*/
#include <linux/uaccess.h>
#include <linux/init.h>
#include <linux/ftrace.h>
#include <asm/asm.h>
#include <asm/asm-offsets.h>
#include <asm/cacheflush.h>
#include <asm/uasm.h>
#include <asm-generic/sections.h>
#if defined(KBUILD_MCOUNT_RA_ADDRESS) && defined(CONFIG_32BIT)
#define MCOUNT_OFFSET_INSNS 5
#else
#define MCOUNT_OFFSET_INSNS 4
#endif
/*
* Check if the address is in kernel space
*
* Clone core_kernel_text() from kernel/extable.c, but doesn't call
* init_kernel_text() for Ftrace doesn't trace functions in init sections.
*/
static inline int in_kernel_space(unsigned long ip)
{
if (ip >= (unsigned long)_stext &&
ip <= (unsigned long)_etext)
return 1;
return 0;
}
#ifdef CONFIG_DYNAMIC_FTRACE
#define JAL 0x0c000000 /* jump & link: ip --> ra, jump to target */
#define ADDR_MASK 0x03ffffff /* op_code|addr : 31...26|25 ....0 */
#define JUMP_RANGE_MASK ((1UL << 28) - 1)
#define INSN_NOP 0x00000000 /* nop */
#define INSN_JAL(addr) \
((unsigned int)(JAL | (((addr) >> 2) & ADDR_MASK)))
static unsigned int insn_jal_ftrace_caller __read_mostly;
static unsigned int insn_lui_v1_hi16_mcount __read_mostly;
static unsigned int insn_j_ftrace_graph_caller __maybe_unused __read_mostly;
static inline void ftrace_dyn_arch_init_insns(void)
{
u32 *buf;
unsigned int v1;
/* lui v1, hi16_mcount */
v1 = 3;
buf = (u32 *)&insn_lui_v1_hi16_mcount;
UASM_i_LA_mostly(&buf, v1, MCOUNT_ADDR);
/* jal (ftrace_caller + 8), jump over the first two instruction */
buf = (u32 *)&insn_jal_ftrace_caller;
uasm_i_jal(&buf, (FTRACE_ADDR + 8) & JUMP_RANGE_MASK);
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
/* j ftrace_graph_caller */
buf = (u32 *)&insn_j_ftrace_graph_caller;
uasm_i_j(&buf, (unsigned long)ftrace_graph_caller & JUMP_RANGE_MASK);
#endif
}
static int ftrace_modify_code(unsigned long ip, unsigned int new_code)
{
int faulted;
/* *(unsigned int *)ip = new_code; */
safe_store_code(new_code, ip, faulted);
if (unlikely(faulted))
return -EFAULT;
flush_icache_range(ip, ip + 8);
return 0;
}
/*
* The details about the calling site of mcount on MIPS
*
* 1. For kernel:
*
* move at, ra
* jal _mcount --> nop
*
* 2. For modules:
*
* 2.1 For KBUILD_MCOUNT_RA_ADDRESS and CONFIG_32BIT
*
* lui v1, hi_16bit_of_mcount --> b 1f (0x10000005)
* addiu v1, v1, low_16bit_of_mcount
* move at, ra
* move $12, ra_address
* jalr v1
* sub sp, sp, 8
* 1: offset = 5 instructions
* 2.2 For the Other situations
*
* lui v1, hi_16bit_of_mcount --> b 1f (0x10000004)
* addiu v1, v1, low_16bit_of_mcount
* move at, ra
* jalr v1
* nop | move $12, ra_address | sub sp, sp, 8
* 1: offset = 4 instructions
*/
#define INSN_B_1F (0x10000000 | MCOUNT_OFFSET_INSNS)
int ftrace_make_nop(struct module *mod,
struct dyn_ftrace *rec, unsigned long addr)
{
unsigned int new;
unsigned long ip = rec->ip;
/*
* If ip is in kernel space, no long call, otherwise, long call is
* needed.
*/
new = in_kernel_space(ip) ? INSN_NOP : INSN_B_1F;
return ftrace_modify_code(ip, new);
}
int ftrace_make_call(struct dyn_ftrace *rec, unsigned long addr)
{
unsigned int new;
unsigned long ip = rec->ip;
new = in_kernel_space(ip) ? insn_jal_ftrace_caller :
insn_lui_v1_hi16_mcount;
return ftrace_modify_code(ip, new);
}
#define FTRACE_CALL_IP ((unsigned long)(&ftrace_call))
int ftrace_update_ftrace_func(ftrace_func_t func)
{
unsigned int new;
new = INSN_JAL((unsigned long)func);
return ftrace_modify_code(FTRACE_CALL_IP, new);
}
int __init ftrace_dyn_arch_init(void *data)
{
/* Encode the instructions when booting */
ftrace_dyn_arch_init_insns();
/* Remove "b ftrace_stub" to ensure ftrace_caller() is executed */
ftrace_modify_code(MCOUNT_ADDR, INSN_NOP);
/* The return code is retured via data */
*(unsigned long *)data = 0;
return 0;
}
#endif /* CONFIG_DYNAMIC_FTRACE */
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
#ifdef CONFIG_DYNAMIC_FTRACE
extern void ftrace_graph_call(void);
#define FTRACE_GRAPH_CALL_IP ((unsigned long)(&ftrace_graph_call))
int ftrace_enable_ftrace_graph_caller(void)
{
return ftrace_modify_code(FTRACE_GRAPH_CALL_IP,
insn_j_ftrace_graph_caller);
}
int ftrace_disable_ftrace_graph_caller(void)
{
return ftrace_modify_code(FTRACE_GRAPH_CALL_IP, INSN_NOP);
}
#endif /* CONFIG_DYNAMIC_FTRACE */
#ifndef KBUILD_MCOUNT_RA_ADDRESS
#define S_RA_SP (0xafbf << 16) /* s{d,w} ra, offset(sp) */
#define S_R_SP (0xafb0 << 16) /* s{d,w} R, offset(sp) */
#define OFFSET_MASK 0xffff /* stack offset range: 0 ~ PT_SIZE */
unsigned long ftrace_get_parent_ra_addr(unsigned long self_ra, unsigned long
old_parent_ra, unsigned long parent_ra_addr, unsigned long fp)
{
unsigned long sp, ip, tmp;
unsigned int code;
int faulted;
/*
* For module, move the ip from the return address after the
* instruction "lui v1, hi_16bit_of_mcount"(offset is 24), but for
* kernel, move after the instruction "move ra, at"(offset is 16)
*/
ip = self_ra - (in_kernel_space(self_ra) ? 16 : 24);
/*
* search the text until finding the non-store instruction or "s{d,w}
* ra, offset(sp)" instruction
*/
do {
/* get the code at "ip": code = *(unsigned int *)ip; */
safe_load_code(code, ip, faulted);
if (unlikely(faulted))
return 0;
/*
* If we hit the non-store instruction before finding where the
* ra is stored, then this is a leaf function and it does not
* store the ra on the stack
*/
if ((code & S_R_SP) != S_R_SP)
return parent_ra_addr;
/* Move to the next instruction */
ip -= 4;
} while ((code & S_RA_SP) != S_RA_SP);
sp = fp + (code & OFFSET_MASK);
/* tmp = *(unsigned long *)sp; */
safe_load_stack(tmp, sp, faulted);
if (unlikely(faulted))
return 0;
if (tmp == old_parent_ra)
return sp;
return 0;
}
#endif /* !KBUILD_MCOUNT_RA_ADDRESS */
/*
* Hook the return address and push it in the stack of return addrs
* in current thread info.
*/
void prepare_ftrace_return(unsigned long *parent_ra_addr, unsigned long self_ra,
unsigned long fp)
{
unsigned long old_parent_ra;
struct ftrace_graph_ent trace;
unsigned long return_hooker = (unsigned long)
&return_to_handler;
int faulted, insns;
if (unlikely(atomic_read(¤t->tracing_graph_pause)))
return;
/*
* "parent_ra_addr" is the stack address saved the return address of
* the caller of _mcount.
*
* if the gcc < 4.5, a leaf function does not save the return address
* in the stack address, so, we "emulate" one in _mcount's stack space,
* and hijack it directly, but for a non-leaf function, it save the
* return address to the its own stack space, we can not hijack it
* directly, but need to find the real stack address,
* ftrace_get_parent_addr() does it!
*
* if gcc>= 4.5, with the new -mmcount-ra-address option, for a
* non-leaf function, the location of the return address will be saved
* to $12 for us, and for a leaf function, only put a zero into $12. we
* do it in ftrace_graph_caller of mcount.S.
*/
/* old_parent_ra = *parent_ra_addr; */
safe_load_stack(old_parent_ra, parent_ra_addr, faulted);
if (unlikely(faulted))
goto out;
#ifndef KBUILD_MCOUNT_RA_ADDRESS
parent_ra_addr = (unsigned long *)ftrace_get_parent_ra_addr(self_ra,
old_parent_ra, (unsigned long)parent_ra_addr, fp);
/*
* If fails when getting the stack address of the non-leaf function's
* ra, stop function graph tracer and return
*/
if (parent_ra_addr == 0)
goto out;
#endif
/* *parent_ra_addr = return_hooker; */
safe_store_stack(return_hooker, parent_ra_addr, faulted);
if (unlikely(faulted))
goto out;
if (ftrace_push_return_trace(old_parent_ra, self_ra, &trace.depth, fp)
== -EBUSY) {
*parent_ra_addr = old_parent_ra;
return;
}
/*
* Get the recorded ip of the current mcount calling site in the
* __mcount_loc section, which will be used to filter the function
* entries configured through the tracing/set_graph_function interface.
*/
insns = in_kernel_space(self_ra) ? 2 : MCOUNT_OFFSET_INSNS + 1;
trace.func = self_ra - (MCOUNT_INSN_SIZE * insns);
/* Only trace if the calling function expects to */
if (!ftrace_graph_entry(&trace)) {
current->curr_ret_stack--;
*parent_ra_addr = old_parent_ra;
}
return;
out:
ftrace_graph_stop();
WARN_ON(1);
}
#endif /* CONFIG_FUNCTION_GRAPH_TRACER */
| gpl-2.0 |
mifl/android_kernel_pantech_ef65s | arch/mips/kernel/ftrace.c | 5245 | 8673 | /*
* Code for replacing ftrace calls with jumps.
*
* Copyright (C) 2007-2008 Steven Rostedt <srostedt@redhat.com>
* Copyright (C) 2009, 2010 DSLab, Lanzhou University, China
* Author: Wu Zhangjin <wuzhangjin@gmail.com>
*
* Thanks goes to Steven Rostedt for writing the original x86 version.
*/
#include <linux/uaccess.h>
#include <linux/init.h>
#include <linux/ftrace.h>
#include <asm/asm.h>
#include <asm/asm-offsets.h>
#include <asm/cacheflush.h>
#include <asm/uasm.h>
#include <asm-generic/sections.h>
#if defined(KBUILD_MCOUNT_RA_ADDRESS) && defined(CONFIG_32BIT)
#define MCOUNT_OFFSET_INSNS 5
#else
#define MCOUNT_OFFSET_INSNS 4
#endif
/*
* Check if the address is in kernel space
*
* Clone core_kernel_text() from kernel/extable.c, but doesn't call
* init_kernel_text() for Ftrace doesn't trace functions in init sections.
*/
static inline int in_kernel_space(unsigned long ip)
{
if (ip >= (unsigned long)_stext &&
ip <= (unsigned long)_etext)
return 1;
return 0;
}
#ifdef CONFIG_DYNAMIC_FTRACE
#define JAL 0x0c000000 /* jump & link: ip --> ra, jump to target */
#define ADDR_MASK 0x03ffffff /* op_code|addr : 31...26|25 ....0 */
#define JUMP_RANGE_MASK ((1UL << 28) - 1)
#define INSN_NOP 0x00000000 /* nop */
#define INSN_JAL(addr) \
((unsigned int)(JAL | (((addr) >> 2) & ADDR_MASK)))
static unsigned int insn_jal_ftrace_caller __read_mostly;
static unsigned int insn_lui_v1_hi16_mcount __read_mostly;
static unsigned int insn_j_ftrace_graph_caller __maybe_unused __read_mostly;
static inline void ftrace_dyn_arch_init_insns(void)
{
u32 *buf;
unsigned int v1;
/* lui v1, hi16_mcount */
v1 = 3;
buf = (u32 *)&insn_lui_v1_hi16_mcount;
UASM_i_LA_mostly(&buf, v1, MCOUNT_ADDR);
/* jal (ftrace_caller + 8), jump over the first two instruction */
buf = (u32 *)&insn_jal_ftrace_caller;
uasm_i_jal(&buf, (FTRACE_ADDR + 8) & JUMP_RANGE_MASK);
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
/* j ftrace_graph_caller */
buf = (u32 *)&insn_j_ftrace_graph_caller;
uasm_i_j(&buf, (unsigned long)ftrace_graph_caller & JUMP_RANGE_MASK);
#endif
}
static int ftrace_modify_code(unsigned long ip, unsigned int new_code)
{
int faulted;
/* *(unsigned int *)ip = new_code; */
safe_store_code(new_code, ip, faulted);
if (unlikely(faulted))
return -EFAULT;
flush_icache_range(ip, ip + 8);
return 0;
}
/*
* The details about the calling site of mcount on MIPS
*
* 1. For kernel:
*
* move at, ra
* jal _mcount --> nop
*
* 2. For modules:
*
* 2.1 For KBUILD_MCOUNT_RA_ADDRESS and CONFIG_32BIT
*
* lui v1, hi_16bit_of_mcount --> b 1f (0x10000005)
* addiu v1, v1, low_16bit_of_mcount
* move at, ra
* move $12, ra_address
* jalr v1
* sub sp, sp, 8
* 1: offset = 5 instructions
* 2.2 For the Other situations
*
* lui v1, hi_16bit_of_mcount --> b 1f (0x10000004)
* addiu v1, v1, low_16bit_of_mcount
* move at, ra
* jalr v1
* nop | move $12, ra_address | sub sp, sp, 8
* 1: offset = 4 instructions
*/
#define INSN_B_1F (0x10000000 | MCOUNT_OFFSET_INSNS)
int ftrace_make_nop(struct module *mod,
struct dyn_ftrace *rec, unsigned long addr)
{
unsigned int new;
unsigned long ip = rec->ip;
/*
* If ip is in kernel space, no long call, otherwise, long call is
* needed.
*/
new = in_kernel_space(ip) ? INSN_NOP : INSN_B_1F;
return ftrace_modify_code(ip, new);
}
int ftrace_make_call(struct dyn_ftrace *rec, unsigned long addr)
{
unsigned int new;
unsigned long ip = rec->ip;
new = in_kernel_space(ip) ? insn_jal_ftrace_caller :
insn_lui_v1_hi16_mcount;
return ftrace_modify_code(ip, new);
}
#define FTRACE_CALL_IP ((unsigned long)(&ftrace_call))
int ftrace_update_ftrace_func(ftrace_func_t func)
{
unsigned int new;
new = INSN_JAL((unsigned long)func);
return ftrace_modify_code(FTRACE_CALL_IP, new);
}
int __init ftrace_dyn_arch_init(void *data)
{
/* Encode the instructions when booting */
ftrace_dyn_arch_init_insns();
/* Remove "b ftrace_stub" to ensure ftrace_caller() is executed */
ftrace_modify_code(MCOUNT_ADDR, INSN_NOP);
/* The return code is retured via data */
*(unsigned long *)data = 0;
return 0;
}
#endif /* CONFIG_DYNAMIC_FTRACE */
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
#ifdef CONFIG_DYNAMIC_FTRACE
extern void ftrace_graph_call(void);
#define FTRACE_GRAPH_CALL_IP ((unsigned long)(&ftrace_graph_call))
int ftrace_enable_ftrace_graph_caller(void)
{
return ftrace_modify_code(FTRACE_GRAPH_CALL_IP,
insn_j_ftrace_graph_caller);
}
int ftrace_disable_ftrace_graph_caller(void)
{
return ftrace_modify_code(FTRACE_GRAPH_CALL_IP, INSN_NOP);
}
#endif /* CONFIG_DYNAMIC_FTRACE */
#ifndef KBUILD_MCOUNT_RA_ADDRESS
#define S_RA_SP (0xafbf << 16) /* s{d,w} ra, offset(sp) */
#define S_R_SP (0xafb0 << 16) /* s{d,w} R, offset(sp) */
#define OFFSET_MASK 0xffff /* stack offset range: 0 ~ PT_SIZE */
unsigned long ftrace_get_parent_ra_addr(unsigned long self_ra, unsigned long
old_parent_ra, unsigned long parent_ra_addr, unsigned long fp)
{
unsigned long sp, ip, tmp;
unsigned int code;
int faulted;
/*
* For module, move the ip from the return address after the
* instruction "lui v1, hi_16bit_of_mcount"(offset is 24), but for
* kernel, move after the instruction "move ra, at"(offset is 16)
*/
ip = self_ra - (in_kernel_space(self_ra) ? 16 : 24);
/*
* search the text until finding the non-store instruction or "s{d,w}
* ra, offset(sp)" instruction
*/
do {
/* get the code at "ip": code = *(unsigned int *)ip; */
safe_load_code(code, ip, faulted);
if (unlikely(faulted))
return 0;
/*
* If we hit the non-store instruction before finding where the
* ra is stored, then this is a leaf function and it does not
* store the ra on the stack
*/
if ((code & S_R_SP) != S_R_SP)
return parent_ra_addr;
/* Move to the next instruction */
ip -= 4;
} while ((code & S_RA_SP) != S_RA_SP);
sp = fp + (code & OFFSET_MASK);
/* tmp = *(unsigned long *)sp; */
safe_load_stack(tmp, sp, faulted);
if (unlikely(faulted))
return 0;
if (tmp == old_parent_ra)
return sp;
return 0;
}
#endif /* !KBUILD_MCOUNT_RA_ADDRESS */
/*
* Hook the return address and push it in the stack of return addrs
* in current thread info.
*/
void prepare_ftrace_return(unsigned long *parent_ra_addr, unsigned long self_ra,
unsigned long fp)
{
unsigned long old_parent_ra;
struct ftrace_graph_ent trace;
unsigned long return_hooker = (unsigned long)
&return_to_handler;
int faulted, insns;
if (unlikely(atomic_read(¤t->tracing_graph_pause)))
return;
/*
* "parent_ra_addr" is the stack address saved the return address of
* the caller of _mcount.
*
* if the gcc < 4.5, a leaf function does not save the return address
* in the stack address, so, we "emulate" one in _mcount's stack space,
* and hijack it directly, but for a non-leaf function, it save the
* return address to the its own stack space, we can not hijack it
* directly, but need to find the real stack address,
* ftrace_get_parent_addr() does it!
*
* if gcc>= 4.5, with the new -mmcount-ra-address option, for a
* non-leaf function, the location of the return address will be saved
* to $12 for us, and for a leaf function, only put a zero into $12. we
* do it in ftrace_graph_caller of mcount.S.
*/
/* old_parent_ra = *parent_ra_addr; */
safe_load_stack(old_parent_ra, parent_ra_addr, faulted);
if (unlikely(faulted))
goto out;
#ifndef KBUILD_MCOUNT_RA_ADDRESS
parent_ra_addr = (unsigned long *)ftrace_get_parent_ra_addr(self_ra,
old_parent_ra, (unsigned long)parent_ra_addr, fp);
/*
* If fails when getting the stack address of the non-leaf function's
* ra, stop function graph tracer and return
*/
if (parent_ra_addr == 0)
goto out;
#endif
/* *parent_ra_addr = return_hooker; */
safe_store_stack(return_hooker, parent_ra_addr, faulted);
if (unlikely(faulted))
goto out;
if (ftrace_push_return_trace(old_parent_ra, self_ra, &trace.depth, fp)
== -EBUSY) {
*parent_ra_addr = old_parent_ra;
return;
}
/*
* Get the recorded ip of the current mcount calling site in the
* __mcount_loc section, which will be used to filter the function
* entries configured through the tracing/set_graph_function interface.
*/
insns = in_kernel_space(self_ra) ? 2 : MCOUNT_OFFSET_INSNS + 1;
trace.func = self_ra - (MCOUNT_INSN_SIZE * insns);
/* Only trace if the calling function expects to */
if (!ftrace_graph_entry(&trace)) {
current->curr_ret_stack--;
*parent_ra_addr = old_parent_ra;
}
return;
out:
ftrace_graph_stop();
WARN_ON(1);
}
#endif /* CONFIG_FUNCTION_GRAPH_TRACER */
| gpl-2.0 |
Drgravy/g3stock | drivers/mfd/max8997-irq.c | 5501 | 10821 | /*
* max8997-irq.c - Interrupt controller support for MAX8997
*
* Copyright (C) 2011 Samsung Electronics Co.Ltd
* MyungJoo Ham <myungjoo.ham@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* This driver is based on max8998-irq.c
*/
#include <linux/err.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/mfd/max8997.h>
#include <linux/mfd/max8997-private.h>
static const u8 max8997_mask_reg[] = {
[PMIC_INT1] = MAX8997_REG_INT1MSK,
[PMIC_INT2] = MAX8997_REG_INT2MSK,
[PMIC_INT3] = MAX8997_REG_INT3MSK,
[PMIC_INT4] = MAX8997_REG_INT4MSK,
[FUEL_GAUGE] = MAX8997_REG_INVALID,
[MUIC_INT1] = MAX8997_MUIC_REG_INTMASK1,
[MUIC_INT2] = MAX8997_MUIC_REG_INTMASK2,
[MUIC_INT3] = MAX8997_MUIC_REG_INTMASK3,
[GPIO_LOW] = MAX8997_REG_INVALID,
[GPIO_HI] = MAX8997_REG_INVALID,
[FLASH_STATUS] = MAX8997_REG_INVALID,
};
static struct i2c_client *get_i2c(struct max8997_dev *max8997,
enum max8997_irq_source src)
{
switch (src) {
case PMIC_INT1 ... PMIC_INT4:
return max8997->i2c;
case FUEL_GAUGE:
return NULL;
case MUIC_INT1 ... MUIC_INT3:
return max8997->muic;
case GPIO_LOW ... GPIO_HI:
return max8997->i2c;
case FLASH_STATUS:
return max8997->i2c;
default:
return ERR_PTR(-EINVAL);
}
}
struct max8997_irq_data {
int mask;
enum max8997_irq_source group;
};
#define DECLARE_IRQ(idx, _group, _mask) \
[(idx)] = { .group = (_group), .mask = (_mask) }
static const struct max8997_irq_data max8997_irqs[] = {
DECLARE_IRQ(MAX8997_PMICIRQ_PWRONR, PMIC_INT1, 1 << 0),
DECLARE_IRQ(MAX8997_PMICIRQ_PWRONF, PMIC_INT1, 1 << 1),
DECLARE_IRQ(MAX8997_PMICIRQ_PWRON1SEC, PMIC_INT1, 1 << 3),
DECLARE_IRQ(MAX8997_PMICIRQ_JIGONR, PMIC_INT1, 1 << 4),
DECLARE_IRQ(MAX8997_PMICIRQ_JIGONF, PMIC_INT1, 1 << 5),
DECLARE_IRQ(MAX8997_PMICIRQ_LOWBAT2, PMIC_INT1, 1 << 6),
DECLARE_IRQ(MAX8997_PMICIRQ_LOWBAT1, PMIC_INT1, 1 << 7),
DECLARE_IRQ(MAX8997_PMICIRQ_JIGR, PMIC_INT2, 1 << 0),
DECLARE_IRQ(MAX8997_PMICIRQ_JIGF, PMIC_INT2, 1 << 1),
DECLARE_IRQ(MAX8997_PMICIRQ_MR, PMIC_INT2, 1 << 2),
DECLARE_IRQ(MAX8997_PMICIRQ_DVS1OK, PMIC_INT2, 1 << 3),
DECLARE_IRQ(MAX8997_PMICIRQ_DVS2OK, PMIC_INT2, 1 << 4),
DECLARE_IRQ(MAX8997_PMICIRQ_DVS3OK, PMIC_INT2, 1 << 5),
DECLARE_IRQ(MAX8997_PMICIRQ_DVS4OK, PMIC_INT2, 1 << 6),
DECLARE_IRQ(MAX8997_PMICIRQ_CHGINS, PMIC_INT3, 1 << 0),
DECLARE_IRQ(MAX8997_PMICIRQ_CHGRM, PMIC_INT3, 1 << 1),
DECLARE_IRQ(MAX8997_PMICIRQ_DCINOVP, PMIC_INT3, 1 << 2),
DECLARE_IRQ(MAX8997_PMICIRQ_TOPOFFR, PMIC_INT3, 1 << 3),
DECLARE_IRQ(MAX8997_PMICIRQ_CHGRSTF, PMIC_INT3, 1 << 5),
DECLARE_IRQ(MAX8997_PMICIRQ_MBCHGTMEXPD, PMIC_INT3, 1 << 7),
DECLARE_IRQ(MAX8997_PMICIRQ_RTC60S, PMIC_INT4, 1 << 0),
DECLARE_IRQ(MAX8997_PMICIRQ_RTCA1, PMIC_INT4, 1 << 1),
DECLARE_IRQ(MAX8997_PMICIRQ_RTCA2, PMIC_INT4, 1 << 2),
DECLARE_IRQ(MAX8997_PMICIRQ_SMPL_INT, PMIC_INT4, 1 << 3),
DECLARE_IRQ(MAX8997_PMICIRQ_RTC1S, PMIC_INT4, 1 << 4),
DECLARE_IRQ(MAX8997_PMICIRQ_WTSR, PMIC_INT4, 1 << 5),
DECLARE_IRQ(MAX8997_MUICIRQ_ADCError, MUIC_INT1, 1 << 2),
DECLARE_IRQ(MAX8997_MUICIRQ_ADCLow, MUIC_INT1, 1 << 1),
DECLARE_IRQ(MAX8997_MUICIRQ_ADC, MUIC_INT1, 1 << 0),
DECLARE_IRQ(MAX8997_MUICIRQ_VBVolt, MUIC_INT2, 1 << 4),
DECLARE_IRQ(MAX8997_MUICIRQ_DBChg, MUIC_INT2, 1 << 3),
DECLARE_IRQ(MAX8997_MUICIRQ_DCDTmr, MUIC_INT2, 1 << 2),
DECLARE_IRQ(MAX8997_MUICIRQ_ChgDetRun, MUIC_INT2, 1 << 1),
DECLARE_IRQ(MAX8997_MUICIRQ_ChgTyp, MUIC_INT2, 1 << 0),
DECLARE_IRQ(MAX8997_MUICIRQ_OVP, MUIC_INT3, 1 << 2),
};
static void max8997_irq_lock(struct irq_data *data)
{
struct max8997_dev *max8997 = irq_get_chip_data(data->irq);
mutex_lock(&max8997->irqlock);
}
static void max8997_irq_sync_unlock(struct irq_data *data)
{
struct max8997_dev *max8997 = irq_get_chip_data(data->irq);
int i;
for (i = 0; i < MAX8997_IRQ_GROUP_NR; i++) {
u8 mask_reg = max8997_mask_reg[i];
struct i2c_client *i2c = get_i2c(max8997, i);
if (mask_reg == MAX8997_REG_INVALID ||
IS_ERR_OR_NULL(i2c))
continue;
max8997->irq_masks_cache[i] = max8997->irq_masks_cur[i];
max8997_write_reg(i2c, max8997_mask_reg[i],
max8997->irq_masks_cur[i]);
}
mutex_unlock(&max8997->irqlock);
}
static const inline struct max8997_irq_data *
irq_to_max8997_irq(struct max8997_dev *max8997, int irq)
{
return &max8997_irqs[irq - max8997->irq_base];
}
static void max8997_irq_mask(struct irq_data *data)
{
struct max8997_dev *max8997 = irq_get_chip_data(data->irq);
const struct max8997_irq_data *irq_data = irq_to_max8997_irq(max8997,
data->irq);
max8997->irq_masks_cur[irq_data->group] |= irq_data->mask;
}
static void max8997_irq_unmask(struct irq_data *data)
{
struct max8997_dev *max8997 = irq_get_chip_data(data->irq);
const struct max8997_irq_data *irq_data = irq_to_max8997_irq(max8997,
data->irq);
max8997->irq_masks_cur[irq_data->group] &= ~irq_data->mask;
}
static struct irq_chip max8997_irq_chip = {
.name = "max8997",
.irq_bus_lock = max8997_irq_lock,
.irq_bus_sync_unlock = max8997_irq_sync_unlock,
.irq_mask = max8997_irq_mask,
.irq_unmask = max8997_irq_unmask,
};
#define MAX8997_IRQSRC_PMIC (1 << 1)
#define MAX8997_IRQSRC_FUELGAUGE (1 << 2)
#define MAX8997_IRQSRC_MUIC (1 << 3)
#define MAX8997_IRQSRC_GPIO (1 << 4)
#define MAX8997_IRQSRC_FLASH (1 << 5)
static irqreturn_t max8997_irq_thread(int irq, void *data)
{
struct max8997_dev *max8997 = data;
u8 irq_reg[MAX8997_IRQ_GROUP_NR] = {};
u8 irq_src;
int ret;
int i;
ret = max8997_read_reg(max8997->i2c, MAX8997_REG_INTSRC, &irq_src);
if (ret < 0) {
dev_err(max8997->dev, "Failed to read interrupt source: %d\n",
ret);
return IRQ_NONE;
}
if (irq_src & MAX8997_IRQSRC_PMIC) {
/* PMIC INT1 ~ INT4 */
max8997_bulk_read(max8997->i2c, MAX8997_REG_INT1, 4,
&irq_reg[PMIC_INT1]);
}
if (irq_src & MAX8997_IRQSRC_FUELGAUGE) {
/*
* TODO: FUEL GAUGE
*
* This is to be supported by Max17042 driver. When
* an interrupt incurs here, it should be relayed to a
* Max17042 device that is connected (probably by
* platform-data). However, we do not have interrupt
* handling in Max17042 driver currently. The Max17042 IRQ
* driver should be ready to be used as a stand-alone device and
* a Max8997-dependent device. Because it is not ready in
* Max17042-side and it is not too critical in operating
* Max8997, we do not implement this in initial releases.
*/
irq_reg[FUEL_GAUGE] = 0;
}
if (irq_src & MAX8997_IRQSRC_MUIC) {
/* MUIC INT1 ~ INT3 */
max8997_bulk_read(max8997->muic, MAX8997_MUIC_REG_INT1, 3,
&irq_reg[MUIC_INT1]);
}
if (irq_src & MAX8997_IRQSRC_GPIO) {
/* GPIO Interrupt */
u8 gpio_info[MAX8997_NUM_GPIO];
irq_reg[GPIO_LOW] = 0;
irq_reg[GPIO_HI] = 0;
max8997_bulk_read(max8997->i2c, MAX8997_REG_GPIOCNTL1,
MAX8997_NUM_GPIO, gpio_info);
for (i = 0; i < MAX8997_NUM_GPIO; i++) {
bool interrupt = false;
switch (gpio_info[i] & MAX8997_GPIO_INT_MASK) {
case MAX8997_GPIO_INT_BOTH:
if (max8997->gpio_status[i] != gpio_info[i])
interrupt = true;
break;
case MAX8997_GPIO_INT_RISE:
if ((max8997->gpio_status[i] != gpio_info[i]) &&
(gpio_info[i] & MAX8997_GPIO_DATA_MASK))
interrupt = true;
break;
case MAX8997_GPIO_INT_FALL:
if ((max8997->gpio_status[i] != gpio_info[i]) &&
!(gpio_info[i] & MAX8997_GPIO_DATA_MASK))
interrupt = true;
break;
default:
break;
}
if (interrupt) {
if (i < 8)
irq_reg[GPIO_LOW] |= (1 << i);
else
irq_reg[GPIO_HI] |= (1 << (i - 8));
}
}
}
if (irq_src & MAX8997_IRQSRC_FLASH) {
/* Flash Status Interrupt */
ret = max8997_read_reg(max8997->i2c, MAX8997_REG_FLASHSTATUS,
&irq_reg[FLASH_STATUS]);
}
/* Apply masking */
for (i = 0; i < MAX8997_IRQ_GROUP_NR; i++)
irq_reg[i] &= ~max8997->irq_masks_cur[i];
/* Report */
for (i = 0; i < MAX8997_IRQ_NR; i++) {
if (irq_reg[max8997_irqs[i].group] & max8997_irqs[i].mask)
handle_nested_irq(max8997->irq_base + i);
}
return IRQ_HANDLED;
}
int max8997_irq_resume(struct max8997_dev *max8997)
{
if (max8997->irq && max8997->irq_base)
max8997_irq_thread(max8997->irq_base, max8997);
return 0;
}
int max8997_irq_init(struct max8997_dev *max8997)
{
int i;
int cur_irq;
int ret;
u8 val;
if (!max8997->irq) {
dev_warn(max8997->dev, "No interrupt specified.\n");
max8997->irq_base = 0;
return 0;
}
if (!max8997->irq_base) {
dev_err(max8997->dev, "No interrupt base specified.\n");
return 0;
}
mutex_init(&max8997->irqlock);
/* Mask individual interrupt sources */
for (i = 0; i < MAX8997_IRQ_GROUP_NR; i++) {
struct i2c_client *i2c;
max8997->irq_masks_cur[i] = 0xff;
max8997->irq_masks_cache[i] = 0xff;
i2c = get_i2c(max8997, i);
if (IS_ERR_OR_NULL(i2c))
continue;
if (max8997_mask_reg[i] == MAX8997_REG_INVALID)
continue;
max8997_write_reg(i2c, max8997_mask_reg[i], 0xff);
}
for (i = 0; i < MAX8997_NUM_GPIO; i++) {
max8997->gpio_status[i] = (max8997_read_reg(max8997->i2c,
MAX8997_REG_GPIOCNTL1 + i,
&val)
& MAX8997_GPIO_DATA_MASK) ?
true : false;
}
/* Register with genirq */
for (i = 0; i < MAX8997_IRQ_NR; i++) {
cur_irq = i + max8997->irq_base;
irq_set_chip_data(cur_irq, max8997);
irq_set_chip_and_handler(cur_irq, &max8997_irq_chip,
handle_edge_irq);
irq_set_nested_thread(cur_irq, 1);
#ifdef CONFIG_ARM
set_irq_flags(cur_irq, IRQF_VALID);
#else
irq_set_noprobe(cur_irq);
#endif
}
ret = request_threaded_irq(max8997->irq, NULL, max8997_irq_thread,
IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
"max8997-irq", max8997);
if (ret) {
dev_err(max8997->dev, "Failed to request IRQ %d: %d\n",
max8997->irq, ret);
return ret;
}
if (!max8997->ono)
return 0;
ret = request_threaded_irq(max8997->ono, NULL, max8997_irq_thread,
IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING |
IRQF_ONESHOT, "max8997-ono", max8997);
if (ret)
dev_err(max8997->dev, "Failed to request ono-IRQ %d: %d\n",
max8997->ono, ret);
return 0;
}
void max8997_irq_exit(struct max8997_dev *max8997)
{
if (max8997->ono)
free_irq(max8997->ono, max8997);
if (max8997->irq)
free_irq(max8997->irq, max8997);
}
| gpl-2.0 |
spezi77/hellspawn-N4 | drivers/ide/ide-gd.c | 8317 | 11060 | #include <linux/module.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/genhd.h>
#include <linux/mutex.h>
#include <linux/ide.h>
#include <linux/hdreg.h>
#include <linux/dmi.h>
#include <linux/slab.h>
#if !defined(CONFIG_DEBUG_BLOCK_EXT_DEVT)
#define IDE_DISK_MINORS (1 << PARTN_BITS)
#else
#define IDE_DISK_MINORS 0
#endif
#include "ide-disk.h"
#include "ide-floppy.h"
#define IDE_GD_VERSION "1.18"
/* module parameters */
static DEFINE_MUTEX(ide_gd_mutex);
static unsigned long debug_mask;
module_param(debug_mask, ulong, 0644);
static DEFINE_MUTEX(ide_disk_ref_mutex);
static void ide_disk_release(struct device *);
static struct ide_disk_obj *ide_disk_get(struct gendisk *disk)
{
struct ide_disk_obj *idkp = NULL;
mutex_lock(&ide_disk_ref_mutex);
idkp = ide_drv_g(disk, ide_disk_obj);
if (idkp) {
if (ide_device_get(idkp->drive))
idkp = NULL;
else
get_device(&idkp->dev);
}
mutex_unlock(&ide_disk_ref_mutex);
return idkp;
}
static void ide_disk_put(struct ide_disk_obj *idkp)
{
ide_drive_t *drive = idkp->drive;
mutex_lock(&ide_disk_ref_mutex);
put_device(&idkp->dev);
ide_device_put(drive);
mutex_unlock(&ide_disk_ref_mutex);
}
sector_t ide_gd_capacity(ide_drive_t *drive)
{
return drive->capacity64;
}
static int ide_gd_probe(ide_drive_t *);
static void ide_gd_remove(ide_drive_t *drive)
{
struct ide_disk_obj *idkp = drive->driver_data;
struct gendisk *g = idkp->disk;
ide_proc_unregister_driver(drive, idkp->driver);
device_del(&idkp->dev);
del_gendisk(g);
drive->disk_ops->flush(drive);
mutex_lock(&ide_disk_ref_mutex);
put_device(&idkp->dev);
mutex_unlock(&ide_disk_ref_mutex);
}
static void ide_disk_release(struct device *dev)
{
struct ide_disk_obj *idkp = to_ide_drv(dev, ide_disk_obj);
ide_drive_t *drive = idkp->drive;
struct gendisk *g = idkp->disk;
drive->disk_ops = NULL;
drive->driver_data = NULL;
g->private_data = NULL;
put_disk(g);
kfree(idkp);
}
/*
* On HPA drives the capacity needs to be
* reinitialized on resume otherwise the disk
* can not be used and a hard reset is required
*/
static void ide_gd_resume(ide_drive_t *drive)
{
if (ata_id_hpa_enabled(drive->id))
(void)drive->disk_ops->get_capacity(drive);
}
static const struct dmi_system_id ide_coldreboot_table[] = {
{
/* Acer TravelMate 66x cuts power during reboot */
.ident = "Acer TravelMate 660",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Acer"),
DMI_MATCH(DMI_PRODUCT_NAME, "TravelMate 660"),
},
},
{ } /* terminate list */
};
static void ide_gd_shutdown(ide_drive_t *drive)
{
#ifdef CONFIG_ALPHA
/* On Alpha, halt(8) doesn't actually turn the machine off,
it puts you into the sort of firmware monitor. Typically,
it's used to boot another kernel image, so it's not much
different from reboot(8). Therefore, we don't need to
spin down the disk in this case, especially since Alpha
firmware doesn't handle disks in standby mode properly.
On the other hand, it's reasonably safe to turn the power
off when the shutdown process reaches the firmware prompt,
as the firmware initialization takes rather long time -
at least 10 seconds, which should be sufficient for
the disk to expire its write cache. */
if (system_state != SYSTEM_POWER_OFF) {
#else
if (system_state == SYSTEM_RESTART &&
!dmi_check_system(ide_coldreboot_table)) {
#endif
drive->disk_ops->flush(drive);
return;
}
printk(KERN_INFO "Shutdown: %s\n", drive->name);
drive->gendev.bus->suspend(&drive->gendev, PMSG_SUSPEND);
}
#ifdef CONFIG_IDE_PROC_FS
static ide_proc_entry_t *ide_disk_proc_entries(ide_drive_t *drive)
{
return (drive->media == ide_disk) ? ide_disk_proc : ide_floppy_proc;
}
static const struct ide_proc_devset *ide_disk_proc_devsets(ide_drive_t *drive)
{
return (drive->media == ide_disk) ? ide_disk_settings
: ide_floppy_settings;
}
#endif
static ide_startstop_t ide_gd_do_request(ide_drive_t *drive,
struct request *rq, sector_t sector)
{
return drive->disk_ops->do_request(drive, rq, sector);
}
static struct ide_driver ide_gd_driver = {
.gen_driver = {
.owner = THIS_MODULE,
.name = "ide-gd",
.bus = &ide_bus_type,
},
.probe = ide_gd_probe,
.remove = ide_gd_remove,
.resume = ide_gd_resume,
.shutdown = ide_gd_shutdown,
.version = IDE_GD_VERSION,
.do_request = ide_gd_do_request,
#ifdef CONFIG_IDE_PROC_FS
.proc_entries = ide_disk_proc_entries,
.proc_devsets = ide_disk_proc_devsets,
#endif
};
static int ide_gd_open(struct block_device *bdev, fmode_t mode)
{
struct gendisk *disk = bdev->bd_disk;
struct ide_disk_obj *idkp;
ide_drive_t *drive;
int ret = 0;
idkp = ide_disk_get(disk);
if (idkp == NULL)
return -ENXIO;
drive = idkp->drive;
ide_debug_log(IDE_DBG_FUNC, "enter");
idkp->openers++;
if ((drive->dev_flags & IDE_DFLAG_REMOVABLE) && idkp->openers == 1) {
drive->dev_flags &= ~IDE_DFLAG_FORMAT_IN_PROGRESS;
/* Just in case */
ret = drive->disk_ops->init_media(drive, disk);
/*
* Allow O_NDELAY to open a drive without a disk, or with an
* unreadable disk, so that we can get the format capacity
* of the drive or begin the format - Sam
*/
if (ret && (mode & FMODE_NDELAY) == 0) {
ret = -EIO;
goto out_put_idkp;
}
if ((drive->dev_flags & IDE_DFLAG_WP) && (mode & FMODE_WRITE)) {
ret = -EROFS;
goto out_put_idkp;
}
/*
* Ignore the return code from door_lock,
* since the open() has already succeeded,
* and the door_lock is irrelevant at this point.
*/
drive->disk_ops->set_doorlock(drive, disk, 1);
drive->dev_flags |= IDE_DFLAG_MEDIA_CHANGED;
check_disk_change(bdev);
} else if (drive->dev_flags & IDE_DFLAG_FORMAT_IN_PROGRESS) {
ret = -EBUSY;
goto out_put_idkp;
}
return 0;
out_put_idkp:
idkp->openers--;
ide_disk_put(idkp);
return ret;
}
static int ide_gd_unlocked_open(struct block_device *bdev, fmode_t mode)
{
int ret;
mutex_lock(&ide_gd_mutex);
ret = ide_gd_open(bdev, mode);
mutex_unlock(&ide_gd_mutex);
return ret;
}
static int ide_gd_release(struct gendisk *disk, fmode_t mode)
{
struct ide_disk_obj *idkp = ide_drv_g(disk, ide_disk_obj);
ide_drive_t *drive = idkp->drive;
ide_debug_log(IDE_DBG_FUNC, "enter");
mutex_lock(&ide_gd_mutex);
if (idkp->openers == 1)
drive->disk_ops->flush(drive);
if ((drive->dev_flags & IDE_DFLAG_REMOVABLE) && idkp->openers == 1) {
drive->disk_ops->set_doorlock(drive, disk, 0);
drive->dev_flags &= ~IDE_DFLAG_FORMAT_IN_PROGRESS;
}
idkp->openers--;
ide_disk_put(idkp);
mutex_unlock(&ide_gd_mutex);
return 0;
}
static int ide_gd_getgeo(struct block_device *bdev, struct hd_geometry *geo)
{
struct ide_disk_obj *idkp = ide_drv_g(bdev->bd_disk, ide_disk_obj);
ide_drive_t *drive = idkp->drive;
geo->heads = drive->bios_head;
geo->sectors = drive->bios_sect;
geo->cylinders = (u16)drive->bios_cyl; /* truncate */
return 0;
}
static unsigned int ide_gd_check_events(struct gendisk *disk,
unsigned int clearing)
{
struct ide_disk_obj *idkp = ide_drv_g(disk, ide_disk_obj);
ide_drive_t *drive = idkp->drive;
bool ret;
/* do not scan partitions twice if this is a removable device */
if (drive->dev_flags & IDE_DFLAG_ATTACH) {
drive->dev_flags &= ~IDE_DFLAG_ATTACH;
return 0;
}
/*
* The following is used to force revalidation on the first open on
* removeable devices, and never gets reported to userland as
* genhd->events is 0. This is intended as removeable ide disk
* can't really detect MEDIA_CHANGE events.
*/
ret = drive->dev_flags & IDE_DFLAG_MEDIA_CHANGED;
drive->dev_flags &= ~IDE_DFLAG_MEDIA_CHANGED;
return ret ? DISK_EVENT_MEDIA_CHANGE : 0;
}
static void ide_gd_unlock_native_capacity(struct gendisk *disk)
{
struct ide_disk_obj *idkp = ide_drv_g(disk, ide_disk_obj);
ide_drive_t *drive = idkp->drive;
const struct ide_disk_ops *disk_ops = drive->disk_ops;
if (disk_ops->unlock_native_capacity)
disk_ops->unlock_native_capacity(drive);
}
static int ide_gd_revalidate_disk(struct gendisk *disk)
{
struct ide_disk_obj *idkp = ide_drv_g(disk, ide_disk_obj);
ide_drive_t *drive = idkp->drive;
if (ide_gd_check_events(disk, 0))
drive->disk_ops->get_capacity(drive);
set_capacity(disk, ide_gd_capacity(drive));
return 0;
}
static int ide_gd_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
struct ide_disk_obj *idkp = ide_drv_g(bdev->bd_disk, ide_disk_obj);
ide_drive_t *drive = idkp->drive;
return drive->disk_ops->ioctl(drive, bdev, mode, cmd, arg);
}
static const struct block_device_operations ide_gd_ops = {
.owner = THIS_MODULE,
.open = ide_gd_unlocked_open,
.release = ide_gd_release,
.ioctl = ide_gd_ioctl,
.getgeo = ide_gd_getgeo,
.check_events = ide_gd_check_events,
.unlock_native_capacity = ide_gd_unlock_native_capacity,
.revalidate_disk = ide_gd_revalidate_disk
};
static int ide_gd_probe(ide_drive_t *drive)
{
const struct ide_disk_ops *disk_ops = NULL;
struct ide_disk_obj *idkp;
struct gendisk *g;
/* strstr("foo", "") is non-NULL */
if (!strstr("ide-gd", drive->driver_req))
goto failed;
#ifdef CONFIG_IDE_GD_ATA
if (drive->media == ide_disk)
disk_ops = &ide_ata_disk_ops;
#endif
#ifdef CONFIG_IDE_GD_ATAPI
if (drive->media == ide_floppy)
disk_ops = &ide_atapi_disk_ops;
#endif
if (disk_ops == NULL)
goto failed;
if (disk_ops->check(drive, DRV_NAME) == 0) {
printk(KERN_ERR PFX "%s: not supported by this driver\n",
drive->name);
goto failed;
}
idkp = kzalloc(sizeof(*idkp), GFP_KERNEL);
if (!idkp) {
printk(KERN_ERR PFX "%s: can't allocate a disk structure\n",
drive->name);
goto failed;
}
g = alloc_disk_node(IDE_DISK_MINORS, hwif_to_node(drive->hwif));
if (!g)
goto out_free_idkp;
ide_init_disk(g, drive);
idkp->dev.parent = &drive->gendev;
idkp->dev.release = ide_disk_release;
dev_set_name(&idkp->dev, dev_name(&drive->gendev));
if (device_register(&idkp->dev))
goto out_free_disk;
idkp->drive = drive;
idkp->driver = &ide_gd_driver;
idkp->disk = g;
g->private_data = &idkp->driver;
drive->driver_data = idkp;
drive->debug_mask = debug_mask;
drive->disk_ops = disk_ops;
disk_ops->setup(drive);
set_capacity(g, ide_gd_capacity(drive));
g->minors = IDE_DISK_MINORS;
g->driverfs_dev = &drive->gendev;
g->flags |= GENHD_FL_EXT_DEVT;
if (drive->dev_flags & IDE_DFLAG_REMOVABLE)
g->flags = GENHD_FL_REMOVABLE;
g->fops = &ide_gd_ops;
add_disk(g);
return 0;
out_free_disk:
put_disk(g);
out_free_idkp:
kfree(idkp);
failed:
return -ENODEV;
}
static int __init ide_gd_init(void)
{
printk(KERN_INFO DRV_NAME " driver " IDE_GD_VERSION "\n");
return driver_register(&ide_gd_driver.gen_driver);
}
static void __exit ide_gd_exit(void)
{
driver_unregister(&ide_gd_driver.gen_driver);
}
MODULE_ALIAS("ide:*m-disk*");
MODULE_ALIAS("ide-disk");
MODULE_ALIAS("ide:*m-floppy*");
MODULE_ALIAS("ide-floppy");
module_init(ide_gd_init);
module_exit(ide_gd_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("generic ATA/ATAPI disk driver");
| gpl-2.0 |
werty100/android_kernel_boxer8_ouya | drivers/input/serio/hp_sdc_mlc.c | 12925 | 9419 | /*
* Access to HP-HIL MLC through HP System Device Controller.
*
* Copyright (c) 2001 Brian S. Julin
* 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. The name of the author may not 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").
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
*
* References:
* HP-HIL Technical Reference Manual. Hewlett Packard Product No. 45918A
* System Device Controller Microprocessor Firmware Theory of Operation
* for Part Number 1820-4784 Revision B. Dwg No. A-1820-4784-2
*
*/
#include <linux/hil_mlc.h>
#include <linux/hp_sdc.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/semaphore.h>
#define PREFIX "HP SDC MLC: "
static hil_mlc hp_sdc_mlc;
MODULE_AUTHOR("Brian S. Julin <bri@calyx.com>");
MODULE_DESCRIPTION("Glue for onboard HIL MLC in HP-PARISC machines");
MODULE_LICENSE("Dual BSD/GPL");
static struct hp_sdc_mlc_priv_s {
int emtestmode;
hp_sdc_transaction trans;
u8 tseq[16];
int got5x;
} hp_sdc_mlc_priv;
/************************* Interrupt context ******************************/
static void hp_sdc_mlc_isr (int irq, void *dev_id,
uint8_t status, uint8_t data)
{
int idx;
hil_mlc *mlc = &hp_sdc_mlc;
write_lock(&mlc->lock);
if (mlc->icount < 0) {
printk(KERN_WARNING PREFIX "HIL Overflow!\n");
up(&mlc->isem);
goto out;
}
idx = 15 - mlc->icount;
if ((status & HP_SDC_STATUS_IRQMASK) == HP_SDC_STATUS_HILDATA) {
mlc->ipacket[idx] |= data | HIL_ERR_INT;
mlc->icount--;
if (hp_sdc_mlc_priv.got5x || !idx)
goto check;
if ((mlc->ipacket[idx - 1] & HIL_PKT_ADDR_MASK) !=
(mlc->ipacket[idx] & HIL_PKT_ADDR_MASK)) {
mlc->ipacket[idx] &= ~HIL_PKT_ADDR_MASK;
mlc->ipacket[idx] |= (mlc->ipacket[idx - 1]
& HIL_PKT_ADDR_MASK);
}
goto check;
}
/* We know status is 5X */
if (data & HP_SDC_HIL_ISERR)
goto err;
mlc->ipacket[idx] =
(data & HP_SDC_HIL_R1MASK) << HIL_PKT_ADDR_SHIFT;
hp_sdc_mlc_priv.got5x = 1;
goto out;
check:
hp_sdc_mlc_priv.got5x = 0;
if (mlc->imatch == 0)
goto done;
if ((mlc->imatch == (HIL_ERR_INT | HIL_PKT_CMD | HIL_CMD_POL))
&& (mlc->ipacket[idx] == (mlc->imatch | idx)))
goto done;
if (mlc->ipacket[idx] == mlc->imatch)
goto done;
goto out;
err:
printk(KERN_DEBUG PREFIX "err code %x\n", data);
switch (data) {
case HP_SDC_HIL_RC_DONE:
printk(KERN_WARNING PREFIX "Bastard SDC reconfigured loop!\n");
break;
case HP_SDC_HIL_ERR:
mlc->ipacket[idx] |= HIL_ERR_INT | HIL_ERR_PERR |
HIL_ERR_FERR | HIL_ERR_FOF;
break;
case HP_SDC_HIL_TO:
mlc->ipacket[idx] |= HIL_ERR_INT | HIL_ERR_LERR;
break;
case HP_SDC_HIL_RC:
printk(KERN_WARNING PREFIX "Bastard SDC decided to reconfigure loop!\n");
break;
default:
printk(KERN_WARNING PREFIX "Unknown HIL Error status (%x)!\n", data);
break;
}
/* No more data will be coming due to an error. */
done:
tasklet_schedule(mlc->tasklet);
up(&mlc->isem);
out:
write_unlock(&mlc->lock);
}
/******************** Tasklet or userspace context functions ****************/
static int hp_sdc_mlc_in(hil_mlc *mlc, suseconds_t timeout)
{
struct hp_sdc_mlc_priv_s *priv;
int rc = 2;
priv = mlc->priv;
/* Try to down the semaphore */
if (down_trylock(&mlc->isem)) {
struct timeval tv;
if (priv->emtestmode) {
mlc->ipacket[0] =
HIL_ERR_INT | (mlc->opacket &
(HIL_PKT_CMD |
HIL_PKT_ADDR_MASK |
HIL_PKT_DATA_MASK));
mlc->icount = 14;
/* printk(KERN_DEBUG PREFIX ">[%x]\n", mlc->ipacket[0]); */
goto wasup;
}
do_gettimeofday(&tv);
tv.tv_usec += USEC_PER_SEC * (tv.tv_sec - mlc->instart.tv_sec);
if (tv.tv_usec - mlc->instart.tv_usec > mlc->intimeout) {
/* printk("!%i %i",
tv.tv_usec - mlc->instart.tv_usec,
mlc->intimeout);
*/
rc = 1;
up(&mlc->isem);
}
goto done;
}
wasup:
up(&mlc->isem);
rc = 0;
done:
return rc;
}
static int hp_sdc_mlc_cts(hil_mlc *mlc)
{
struct hp_sdc_mlc_priv_s *priv;
priv = mlc->priv;
/* Try to down the semaphores -- they should be up. */
BUG_ON(down_trylock(&mlc->isem));
BUG_ON(down_trylock(&mlc->osem));
up(&mlc->isem);
up(&mlc->osem);
if (down_trylock(&mlc->csem)) {
if (priv->trans.act.semaphore != &mlc->csem)
goto poll;
else
goto busy;
}
if (!(priv->tseq[4] & HP_SDC_USE_LOOP))
goto done;
poll:
priv->trans.act.semaphore = &mlc->csem;
priv->trans.actidx = 0;
priv->trans.idx = 1;
priv->trans.endidx = 5;
priv->tseq[0] =
HP_SDC_ACT_POSTCMD | HP_SDC_ACT_DATAIN | HP_SDC_ACT_SEMAPHORE;
priv->tseq[1] = HP_SDC_CMD_READ_USE;
priv->tseq[2] = 1;
priv->tseq[3] = 0;
priv->tseq[4] = 0;
__hp_sdc_enqueue_transaction(&priv->trans);
busy:
return 1;
done:
priv->trans.act.semaphore = &mlc->osem;
up(&mlc->csem);
return 0;
}
static void hp_sdc_mlc_out(hil_mlc *mlc)
{
struct hp_sdc_mlc_priv_s *priv;
priv = mlc->priv;
/* Try to down the semaphore -- it should be up. */
BUG_ON(down_trylock(&mlc->osem));
if (mlc->opacket & HIL_DO_ALTER_CTRL)
goto do_control;
do_data:
if (priv->emtestmode) {
up(&mlc->osem);
return;
}
/* Shouldn't be sending commands when loop may be busy */
BUG_ON(down_trylock(&mlc->csem));
up(&mlc->csem);
priv->trans.actidx = 0;
priv->trans.idx = 1;
priv->trans.act.semaphore = &mlc->osem;
priv->trans.endidx = 6;
priv->tseq[0] =
HP_SDC_ACT_DATAREG | HP_SDC_ACT_POSTCMD | HP_SDC_ACT_SEMAPHORE;
priv->tseq[1] = 0x7;
priv->tseq[2] =
(mlc->opacket &
(HIL_PKT_ADDR_MASK | HIL_PKT_CMD))
>> HIL_PKT_ADDR_SHIFT;
priv->tseq[3] =
(mlc->opacket & HIL_PKT_DATA_MASK)
>> HIL_PKT_DATA_SHIFT;
priv->tseq[4] = 0; /* No timeout */
if (priv->tseq[3] == HIL_CMD_DHR)
priv->tseq[4] = 1;
priv->tseq[5] = HP_SDC_CMD_DO_HIL;
goto enqueue;
do_control:
priv->emtestmode = mlc->opacket & HIL_CTRL_TEST;
/* we cannot emulate this, it should not be used. */
BUG_ON((mlc->opacket & (HIL_CTRL_APE | HIL_CTRL_IPF)) == HIL_CTRL_APE);
if ((mlc->opacket & HIL_CTRL_ONLY) == HIL_CTRL_ONLY)
goto control_only;
/* Should not send command/data after engaging APE */
BUG_ON(mlc->opacket & HIL_CTRL_APE);
/* Disengaging APE this way would not be valid either since
* the loop must be allowed to idle.
*
* So, it works out that we really never actually send control
* and data when using SDC, we just send the data.
*/
goto do_data;
control_only:
priv->trans.actidx = 0;
priv->trans.idx = 1;
priv->trans.act.semaphore = &mlc->osem;
priv->trans.endidx = 4;
priv->tseq[0] =
HP_SDC_ACT_PRECMD | HP_SDC_ACT_DATAOUT | HP_SDC_ACT_SEMAPHORE;
priv->tseq[1] = HP_SDC_CMD_SET_LPC;
priv->tseq[2] = 1;
/* priv->tseq[3] = (mlc->ddc + 1) | HP_SDC_LPS_ACSUCC; */
priv->tseq[3] = 0;
if (mlc->opacket & HIL_CTRL_APE) {
priv->tseq[3] |= HP_SDC_LPC_APE_IPF;
BUG_ON(down_trylock(&mlc->csem));
}
enqueue:
hp_sdc_enqueue_transaction(&priv->trans);
}
static int __init hp_sdc_mlc_init(void)
{
hil_mlc *mlc = &hp_sdc_mlc;
int err;
#ifdef __mc68000__
if (!MACH_IS_HP300)
return -ENODEV;
#endif
printk(KERN_INFO PREFIX "Registering the System Domain Controller's HIL MLC.\n");
hp_sdc_mlc_priv.emtestmode = 0;
hp_sdc_mlc_priv.trans.seq = hp_sdc_mlc_priv.tseq;
hp_sdc_mlc_priv.trans.act.semaphore = &mlc->osem;
hp_sdc_mlc_priv.got5x = 0;
mlc->cts = &hp_sdc_mlc_cts;
mlc->in = &hp_sdc_mlc_in;
mlc->out = &hp_sdc_mlc_out;
mlc->priv = &hp_sdc_mlc_priv;
err = hil_mlc_register(mlc);
if (err) {
printk(KERN_WARNING PREFIX "Failed to register MLC structure with hil_mlc\n");
return err;
}
if (hp_sdc_request_hil_irq(&hp_sdc_mlc_isr)) {
printk(KERN_WARNING PREFIX "Request for raw HIL ISR hook denied\n");
if (hil_mlc_unregister(mlc))
printk(KERN_ERR PREFIX "Failed to unregister MLC structure with hil_mlc.\n"
"This is bad. Could cause an oops.\n");
return -EBUSY;
}
return 0;
}
static void __exit hp_sdc_mlc_exit(void)
{
hil_mlc *mlc = &hp_sdc_mlc;
if (hp_sdc_release_hil_irq(&hp_sdc_mlc_isr))
printk(KERN_ERR PREFIX "Failed to release the raw HIL ISR hook.\n"
"This is bad. Could cause an oops.\n");
if (hil_mlc_unregister(mlc))
printk(KERN_ERR PREFIX "Failed to unregister MLC structure with hil_mlc.\n"
"This is bad. Could cause an oops.\n");
}
module_init(hp_sdc_mlc_init);
module_exit(hp_sdc_mlc_exit);
| gpl-2.0 |
zhaoleidd/btrfs | drivers/staging/iio/meter/ade7758_ring.c | 126 | 4549 | /*
* ADE7758 Poly Phase Multifunction Energy Metering IC driver
*
* Copyright 2010-2011 Analog Devices Inc.
*
* Licensed under the GPL-2.
*/
#include <linux/export.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <asm/unaligned.h>
#include <linux/iio/iio.h>
#include <linux/iio/kfifo_buf.h>
#include <linux/iio/trigger_consumer.h>
#include "ade7758.h"
/**
* ade7758_spi_read_burst() - read data registers
* @indio_dev: the IIO device
**/
static int ade7758_spi_read_burst(struct iio_dev *indio_dev)
{
struct ade7758_state *st = iio_priv(indio_dev);
int ret;
ret = spi_sync(st->us, &st->ring_msg);
if (ret)
dev_err(&st->us->dev, "problem when reading WFORM value\n");
return ret;
}
static int ade7758_write_waveform_type(struct device *dev, unsigned type)
{
int ret;
u8 reg;
ret = ade7758_spi_read_reg_8(dev,
ADE7758_WAVMODE,
®);
if (ret)
goto out;
reg &= ~0x1F;
reg |= type & 0x1F;
ret = ade7758_spi_write_reg_8(dev,
ADE7758_WAVMODE,
reg);
out:
return ret;
}
/* Whilst this makes a lot of calls to iio_sw_ring functions - it is too device
* specific to be rolled into the core.
*/
static irqreturn_t ade7758_trigger_handler(int irq, void *p)
{
struct iio_poll_func *pf = p;
struct iio_dev *indio_dev = pf->indio_dev;
struct ade7758_state *st = iio_priv(indio_dev);
s64 dat64[2];
u32 *dat32 = (u32 *)dat64;
if (!bitmap_empty(indio_dev->active_scan_mask, indio_dev->masklength))
if (ade7758_spi_read_burst(indio_dev) >= 0)
*dat32 = get_unaligned_be32(&st->rx_buf[5]) & 0xFFFFFF;
iio_push_to_buffers_with_timestamp(indio_dev, dat64, pf->timestamp);
iio_trigger_notify_done(indio_dev->trig);
return IRQ_HANDLED;
}
/**
* ade7758_ring_preenable() setup the parameters of the ring before enabling
*
* The complex nature of the setting of the number of bytes per datum is due
* to this driver currently ensuring that the timestamp is stored at an 8
* byte boundary.
**/
static int ade7758_ring_preenable(struct iio_dev *indio_dev)
{
unsigned channel;
if (bitmap_empty(indio_dev->active_scan_mask, indio_dev->masklength))
return -EINVAL;
channel = find_first_bit(indio_dev->active_scan_mask,
indio_dev->masklength);
ade7758_write_waveform_type(&indio_dev->dev,
indio_dev->channels[channel].address);
return 0;
}
static const struct iio_buffer_setup_ops ade7758_ring_setup_ops = {
.preenable = &ade7758_ring_preenable,
.postenable = &iio_triggered_buffer_postenable,
.predisable = &iio_triggered_buffer_predisable,
.validate_scan_mask = &iio_validate_scan_mask_onehot,
};
void ade7758_unconfigure_ring(struct iio_dev *indio_dev)
{
iio_dealloc_pollfunc(indio_dev->pollfunc);
iio_kfifo_free(indio_dev->buffer);
}
int ade7758_configure_ring(struct iio_dev *indio_dev)
{
struct ade7758_state *st = iio_priv(indio_dev);
struct iio_buffer *buffer;
int ret = 0;
buffer = iio_kfifo_allocate();
if (!buffer) {
ret = -ENOMEM;
return ret;
}
iio_device_attach_buffer(indio_dev, buffer);
indio_dev->setup_ops = &ade7758_ring_setup_ops;
indio_dev->pollfunc = iio_alloc_pollfunc(&iio_pollfunc_store_time,
&ade7758_trigger_handler,
0,
indio_dev,
"ade7759_consumer%d",
indio_dev->id);
if (indio_dev->pollfunc == NULL) {
ret = -ENOMEM;
goto error_iio_kfifo_free;
}
indio_dev->modes |= INDIO_BUFFER_TRIGGERED;
st->tx_buf[0] = ADE7758_READ_REG(ADE7758_RSTATUS);
st->tx_buf[1] = 0;
st->tx_buf[2] = 0;
st->tx_buf[3] = 0;
st->tx_buf[4] = ADE7758_READ_REG(ADE7758_WFORM);
st->tx_buf[5] = 0;
st->tx_buf[6] = 0;
st->tx_buf[7] = 0;
/* build spi ring message */
st->ring_xfer[0].tx_buf = &st->tx_buf[0];
st->ring_xfer[0].len = 1;
st->ring_xfer[0].bits_per_word = 8;
st->ring_xfer[0].delay_usecs = 4;
st->ring_xfer[1].rx_buf = &st->rx_buf[1];
st->ring_xfer[1].len = 3;
st->ring_xfer[1].bits_per_word = 8;
st->ring_xfer[1].cs_change = 1;
st->ring_xfer[2].tx_buf = &st->tx_buf[4];
st->ring_xfer[2].len = 1;
st->ring_xfer[2].bits_per_word = 8;
st->ring_xfer[2].delay_usecs = 1;
st->ring_xfer[3].rx_buf = &st->rx_buf[5];
st->ring_xfer[3].len = 3;
st->ring_xfer[3].bits_per_word = 8;
spi_message_init(&st->ring_msg);
spi_message_add_tail(&st->ring_xfer[0], &st->ring_msg);
spi_message_add_tail(&st->ring_xfer[1], &st->ring_msg);
spi_message_add_tail(&st->ring_xfer[2], &st->ring_msg);
spi_message_add_tail(&st->ring_xfer[3], &st->ring_msg);
return 0;
error_iio_kfifo_free:
iio_kfifo_free(indio_dev->buffer);
return ret;
}
| gpl-2.0 |
liulijun1/linux-3.6 | drivers/staging/bcm/InterfaceIdleMode.c | 126 | 9635 | #include "headers.h"
/*
Function: InterfaceIdleModeWakeup
Description: This is the hardware specific Function for waking up HW device from Idle mode.
A software abort pattern is written to the device to wake it and necessary power state
transitions from host are performed here.
Input parameters: IN struct bcm_mini_adapter *Adapter - Miniport Adapter Context
Return: BCM_STATUS_SUCCESS - If Wakeup of the HW Interface was successful.
Other - If an error occurred.
*/
/*
Function: InterfaceIdleModeRespond
Description: This is the hardware specific Function for responding to Idle mode request from target.
Necessary power state transitions from host for idle mode or other device specific
initializations are performed here.
Input parameters: IN struct bcm_mini_adapter * Adapter - Miniport Adapter Context
Return: BCM_STATUS_SUCCESS - If Idle mode response related HW configuration was successful.
Other - If an error occurred.
*/
/*
"dmem bfc02f00 100" tells how many time device went in Idle mode.
this value will be at address bfc02fa4.just before value d0ea1dle.
Set time value by writing at bfc02f98 7d0
checking the Ack timer expire on kannon by running command
d qcslog .. if it shows e means host has not send response to f/w with in 200 ms. Response should be
send to f/w with in 200 ms after the Idle/Shutdown req issued
*/
int InterfaceIdleModeRespond(struct bcm_mini_adapter *Adapter, unsigned int* puiBuffer)
{
int status = STATUS_SUCCESS;
unsigned int uiRegRead = 0;
int bytes;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL,"SubType of Message :0x%X", ntohl(*puiBuffer));
if(ntohl(*puiBuffer) == GO_TO_IDLE_MODE_PAYLOAD)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL," Got GO_TO_IDLE_MODE_PAYLOAD(210) Msg Subtype");
if(ntohl(*(puiBuffer+1)) == 0 )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL,"Got IDLE MODE WAKE UP Response From F/W");
status = wrmalt (Adapter,SW_ABORT_IDLEMODE_LOC, &uiRegRead, sizeof(uiRegRead));
if(status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "wrm failed while clearing Idle Mode Reg");
return status;
}
if(Adapter->ulPowerSaveMode == DEVICE_POWERSAVE_MODE_AS_MANUAL_CLOCK_GATING)
{
uiRegRead = 0x00000000 ;
status = wrmalt (Adapter,DEBUG_INTERRUPT_GENERATOR_REGISTOR, &uiRegRead, sizeof(uiRegRead));
if(status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "wrm failed while clearing Idle Mode Reg");
return status;
}
}
//Below Register should not br read in case of Manual and Protocol Idle mode.
else if(Adapter->ulPowerSaveMode != DEVICE_POWERSAVE_MODE_AS_PROTOCOL_IDLE_MODE)
{
//clear on read Register
bytes = rdmalt(Adapter, DEVICE_INT_OUT_EP_REG0, &uiRegRead, sizeof(uiRegRead));
if (bytes < 0) {
status = bytes;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "rdm failed while clearing H/W Abort Reg0");
return status;
}
//clear on read Register
bytes = rdmalt(Adapter, DEVICE_INT_OUT_EP_REG1, &uiRegRead, sizeof(uiRegRead));
if (bytes < 0) {
status = bytes;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "rdm failed while clearing H/W Abort Reg1");
return status;
}
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL, "Device Up from Idle Mode");
// Set Idle Mode Flag to False and Clear IdleMode reg.
Adapter->IdleMode = FALSE;
Adapter->bTriedToWakeUpFromlowPowerMode = FALSE;
wake_up(&Adapter->lowpower_mode_wait_queue);
}
else
{
if(TRUE == Adapter->IdleMode)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL,"Device is already in Idle mode....");
return status ;
}
uiRegRead = 0;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL, "Got Req from F/W to go in IDLE mode \n");
if (Adapter->chip_id== BCS220_2 ||
Adapter->chip_id == BCS220_2BC ||
Adapter->chip_id== BCS250_BC ||
Adapter->chip_id== BCS220_3)
{
bytes = rdmalt(Adapter, HPM_CONFIG_MSW, &uiRegRead, sizeof(uiRegRead));
if (bytes < 0) {
status = bytes;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL, "rdm failed while Reading HPM_CONFIG_LDO145 Reg 0\n");
return status;
}
uiRegRead |= (1<<17);
status = wrmalt (Adapter,HPM_CONFIG_MSW, &uiRegRead, sizeof(uiRegRead));
if(status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "wrm failed while clearing Idle Mode Reg\n");
return status;
}
}
SendIdleModeResponse(Adapter);
}
}
else if(ntohl(*puiBuffer) == IDLE_MODE_SF_UPDATE_MSG)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL, "OverRiding Service Flow Params");
OverrideServiceFlowParams(Adapter,puiBuffer);
}
return status;
}
static int InterfaceAbortIdlemode(struct bcm_mini_adapter *Adapter, unsigned int Pattern)
{
int status = STATUS_SUCCESS;
unsigned int value;
unsigned int chip_id ;
unsigned long timeout = 0 ,itr = 0;
int lenwritten = 0;
unsigned char aucAbortPattern[8]={0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
PS_INTERFACE_ADAPTER psInterfaceAdapter = Adapter->pvInterfaceAdapter;
//Abort Bus suspend if its already suspended
if((TRUE == psInterfaceAdapter->bSuspended) && (TRUE == Adapter->bDoSuspend))
{
status = usb_autopm_get_interface(psInterfaceAdapter->interface);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL,"Bus got wakeup..Aborting Idle mode... status:%d \n",status);
}
if((Adapter->ulPowerSaveMode == DEVICE_POWERSAVE_MODE_AS_MANUAL_CLOCK_GATING)
||
(Adapter->ulPowerSaveMode == DEVICE_POWERSAVE_MODE_AS_PROTOCOL_IDLE_MODE))
{
//write the SW abort pattern.
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL, "Writing pattern<%d> to SW_ABORT_IDLEMODE_LOC\n", Pattern);
status = wrmalt(Adapter,SW_ABORT_IDLEMODE_LOC, &Pattern, sizeof(Pattern));
if(status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL,"WRM to Register SW_ABORT_IDLEMODE_LOC failed..");
return status;
}
}
if(Adapter->ulPowerSaveMode == DEVICE_POWERSAVE_MODE_AS_MANUAL_CLOCK_GATING)
{
value = 0x80000000;
status = wrmalt(Adapter,DEBUG_INTERRUPT_GENERATOR_REGISTOR, &value, sizeof(value));
if(status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL,"WRM to DEBUG_INTERRUPT_GENERATOR_REGISTOR Register failed");
return status;
}
}
else if(Adapter->ulPowerSaveMode != DEVICE_POWERSAVE_MODE_AS_PROTOCOL_IDLE_MODE)
{
/*
* Get a Interrupt Out URB and send 8 Bytes Down
* To be Done in Thread Context.
* Not using Asynchronous Mechanism.
*/
status = usb_interrupt_msg (psInterfaceAdapter->udev,
usb_sndintpipe(psInterfaceAdapter->udev,
psInterfaceAdapter->sIntrOut.int_out_endpointAddr),
aucAbortPattern,
8,
&lenwritten,
5000);
if(status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL, "Sending Abort pattern down fails with status:%d..\n",status);
return status;
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL, "NOB Sent down :%d", lenwritten);
}
//mdelay(25);
timeout= jiffies + msecs_to_jiffies(50) ;
while( timeout > jiffies )
{
itr++ ;
rdmalt(Adapter, CHIP_ID_REG, &chip_id, sizeof(UINT));
if(0xbece3200==(chip_id&~(0xF0)))
{
chip_id = chip_id&~(0xF0);
}
if(chip_id == Adapter->chip_id)
break;
}
if(timeout < jiffies )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL,"Not able to read chip-id even after 25 msec");
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL,"Number of completed iteration to read chip-id :%lu", itr);
}
status = wrmalt(Adapter,SW_ABORT_IDLEMODE_LOC, &Pattern, sizeof(status));
if(status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"WRM to Register SW_ABORT_IDLEMODE_LOC failed..");
return status;
}
}
return status;
}
int InterfaceIdleModeWakeup(struct bcm_mini_adapter *Adapter)
{
ULONG Status = 0;
if(Adapter->bTriedToWakeUpFromlowPowerMode)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL, "Wake up already attempted.. ignoring\n");
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, IDLE_MODE, DBG_LVL_ALL,"Writing Low Power Mode Abort pattern to the Device\n");
Adapter->bTriedToWakeUpFromlowPowerMode = TRUE;
InterfaceAbortIdlemode(Adapter, Adapter->usIdleModePattern);
}
return Status;
}
void InterfaceHandleShutdownModeWakeup(struct bcm_mini_adapter *Adapter)
{
unsigned int uiRegVal = 0;
INT Status = 0;
int bytes;
if(Adapter->ulPowerSaveMode == DEVICE_POWERSAVE_MODE_AS_MANUAL_CLOCK_GATING)
{
// clear idlemode interrupt.
uiRegVal = 0;
Status =wrmalt(Adapter,DEBUG_INTERRUPT_GENERATOR_REGISTOR, &uiRegVal, sizeof(uiRegVal));
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"WRM to DEBUG_INTERRUPT_GENERATOR_REGISTOR Failed with err :%d", Status);
return;
}
}
else
{
//clear Interrupt EP registers.
bytes = rdmalt(Adapter,DEVICE_INT_OUT_EP_REG0, &uiRegVal, sizeof(uiRegVal));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"RDM of DEVICE_INT_OUT_EP_REG0 failed with Err :%d", Status);
return;
}
bytes = rdmalt(Adapter,DEVICE_INT_OUT_EP_REG1, &uiRegVal, sizeof(uiRegVal));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"RDM of DEVICE_INT_OUT_EP_REG1 failed with Err :%d", Status);
return;
}
}
}
| gpl-2.0 |
LokiWuh/android_kernel_asus_grouper | net/xfrm/xfrm_user.c | 382 | 70654 | /* xfrm_user.c: User interface to configure xfrm engine.
*
* Copyright (C) 2002 David S. Miller (davem@redhat.com)
*
* Changes:
* Mitsuru KANDA @USAGI
* Kazunori MIYAZAWA @USAGI
* Kunihiro Ishiguro <kunihiro@ipinfusion.com>
* IPv6 support
*
*/
#include <linux/crypto.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/socket.h>
#include <linux/string.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/pfkeyv2.h>
#include <linux/ipsec.h>
#include <linux/init.h>
#include <linux/security.h>
#include <net/sock.h>
#include <net/xfrm.h>
#include <net/netlink.h>
#include <net/ah.h>
#include <asm/uaccess.h>
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
#include <linux/in6.h>
#endif
static inline int aead_len(struct xfrm_algo_aead *alg)
{
return sizeof(*alg) + ((alg->alg_key_len + 7) / 8);
}
static int verify_one_alg(struct nlattr **attrs, enum xfrm_attr_type_t type)
{
struct nlattr *rt = attrs[type];
struct xfrm_algo *algp;
if (!rt)
return 0;
algp = nla_data(rt);
if (nla_len(rt) < xfrm_alg_len(algp))
return -EINVAL;
switch (type) {
case XFRMA_ALG_AUTH:
case XFRMA_ALG_CRYPT:
case XFRMA_ALG_COMP:
break;
default:
return -EINVAL;
}
algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0';
return 0;
}
static int verify_auth_trunc(struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_ALG_AUTH_TRUNC];
struct xfrm_algo_auth *algp;
if (!rt)
return 0;
algp = nla_data(rt);
if (nla_len(rt) < xfrm_alg_auth_len(algp))
return -EINVAL;
algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0';
return 0;
}
static int verify_aead(struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_ALG_AEAD];
struct xfrm_algo_aead *algp;
if (!rt)
return 0;
algp = nla_data(rt);
if (nla_len(rt) < aead_len(algp))
return -EINVAL;
algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0';
return 0;
}
static void verify_one_addr(struct nlattr **attrs, enum xfrm_attr_type_t type,
xfrm_address_t **addrp)
{
struct nlattr *rt = attrs[type];
if (rt && addrp)
*addrp = nla_data(rt);
}
static inline int verify_sec_ctx_len(struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_user_sec_ctx *uctx;
if (!rt)
return 0;
uctx = nla_data(rt);
if (uctx->len != (sizeof(struct xfrm_user_sec_ctx) + uctx->ctx_len))
return -EINVAL;
return 0;
}
static inline int verify_replay(struct xfrm_usersa_info *p,
struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_REPLAY_ESN_VAL];
if ((p->flags & XFRM_STATE_ESN) && !rt)
return -EINVAL;
if (!rt)
return 0;
if (p->id.proto != IPPROTO_ESP)
return -EINVAL;
if (p->replay_window != 0)
return -EINVAL;
return 0;
}
static int verify_newsa_info(struct xfrm_usersa_info *p,
struct nlattr **attrs)
{
int err;
err = -EINVAL;
switch (p->family) {
case AF_INET:
break;
case AF_INET6:
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
break;
#else
err = -EAFNOSUPPORT;
goto out;
#endif
default:
goto out;
}
err = -EINVAL;
switch (p->id.proto) {
case IPPROTO_AH:
if ((!attrs[XFRMA_ALG_AUTH] &&
!attrs[XFRMA_ALG_AUTH_TRUNC]) ||
attrs[XFRMA_ALG_AEAD] ||
attrs[XFRMA_ALG_CRYPT] ||
attrs[XFRMA_ALG_COMP] ||
attrs[XFRMA_TFCPAD])
goto out;
break;
case IPPROTO_ESP:
if (attrs[XFRMA_ALG_COMP])
goto out;
if (!attrs[XFRMA_ALG_AUTH] &&
!attrs[XFRMA_ALG_AUTH_TRUNC] &&
!attrs[XFRMA_ALG_CRYPT] &&
!attrs[XFRMA_ALG_AEAD])
goto out;
if ((attrs[XFRMA_ALG_AUTH] ||
attrs[XFRMA_ALG_AUTH_TRUNC] ||
attrs[XFRMA_ALG_CRYPT]) &&
attrs[XFRMA_ALG_AEAD])
goto out;
if (attrs[XFRMA_TFCPAD] &&
p->mode != XFRM_MODE_TUNNEL)
goto out;
break;
case IPPROTO_COMP:
if (!attrs[XFRMA_ALG_COMP] ||
attrs[XFRMA_ALG_AEAD] ||
attrs[XFRMA_ALG_AUTH] ||
attrs[XFRMA_ALG_AUTH_TRUNC] ||
attrs[XFRMA_ALG_CRYPT] ||
attrs[XFRMA_TFCPAD])
goto out;
break;
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
case IPPROTO_DSTOPTS:
case IPPROTO_ROUTING:
if (attrs[XFRMA_ALG_COMP] ||
attrs[XFRMA_ALG_AUTH] ||
attrs[XFRMA_ALG_AUTH_TRUNC] ||
attrs[XFRMA_ALG_AEAD] ||
attrs[XFRMA_ALG_CRYPT] ||
attrs[XFRMA_ENCAP] ||
attrs[XFRMA_SEC_CTX] ||
attrs[XFRMA_TFCPAD] ||
!attrs[XFRMA_COADDR])
goto out;
break;
#endif
default:
goto out;
}
if ((err = verify_aead(attrs)))
goto out;
if ((err = verify_auth_trunc(attrs)))
goto out;
if ((err = verify_one_alg(attrs, XFRMA_ALG_AUTH)))
goto out;
if ((err = verify_one_alg(attrs, XFRMA_ALG_CRYPT)))
goto out;
if ((err = verify_one_alg(attrs, XFRMA_ALG_COMP)))
goto out;
if ((err = verify_sec_ctx_len(attrs)))
goto out;
if ((err = verify_replay(p, attrs)))
goto out;
err = -EINVAL;
switch (p->mode) {
case XFRM_MODE_TRANSPORT:
case XFRM_MODE_TUNNEL:
case XFRM_MODE_ROUTEOPTIMIZATION:
case XFRM_MODE_BEET:
break;
default:
goto out;
}
err = 0;
out:
return err;
}
static int attach_one_algo(struct xfrm_algo **algpp, u8 *props,
struct xfrm_algo_desc *(*get_byname)(const char *, int),
struct nlattr *rta)
{
struct xfrm_algo *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, xfrm_alg_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
*algpp = p;
return 0;
}
static int attach_auth(struct xfrm_algo_auth **algpp, u8 *props,
struct nlattr *rta)
{
struct xfrm_algo *ualg;
struct xfrm_algo_auth *p;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = xfrm_aalg_get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmalloc(sizeof(*p) + (ualg->alg_key_len + 7) / 8, GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
p->alg_key_len = ualg->alg_key_len;
p->alg_trunc_len = algo->uinfo.auth.icv_truncbits;
memcpy(p->alg_key, ualg->alg_key, (ualg->alg_key_len + 7) / 8);
*algpp = p;
return 0;
}
static int attach_auth_trunc(struct xfrm_algo_auth **algpp, u8 *props,
struct nlattr *rta)
{
struct xfrm_algo_auth *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = xfrm_aalg_get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
if ((ualg->alg_trunc_len / 8) > MAX_AH_AUTH_LEN ||
ualg->alg_trunc_len > algo->uinfo.auth.icv_fullbits)
return -EINVAL;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, xfrm_alg_auth_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
if (!p->alg_trunc_len)
p->alg_trunc_len = algo->uinfo.auth.icv_truncbits;
*algpp = p;
return 0;
}
static int attach_aead(struct xfrm_algo_aead **algpp, u8 *props,
struct nlattr *rta)
{
struct xfrm_algo_aead *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = xfrm_aead_get_byname(ualg->alg_name, ualg->alg_icv_len, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, aead_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
*algpp = p;
return 0;
}
static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn,
struct nlattr *rp)
{
struct xfrm_replay_state_esn *up;
if (!replay_esn || !rp)
return 0;
up = nla_data(rp);
if (xfrm_replay_state_esn_len(replay_esn) !=
xfrm_replay_state_esn_len(up))
return -EINVAL;
return 0;
}
static int xfrm_alloc_replay_state_esn(struct xfrm_replay_state_esn **replay_esn,
struct xfrm_replay_state_esn **preplay_esn,
struct nlattr *rta)
{
struct xfrm_replay_state_esn *p, *pp, *up;
if (!rta)
return 0;
up = nla_data(rta);
p = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL);
if (!p)
return -ENOMEM;
pp = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL);
if (!pp) {
kfree(p);
return -ENOMEM;
}
*replay_esn = p;
*preplay_esn = pp;
return 0;
}
static inline int xfrm_user_sec_ctx_size(struct xfrm_sec_ctx *xfrm_ctx)
{
int len = 0;
if (xfrm_ctx) {
len += sizeof(struct xfrm_user_sec_ctx);
len += xfrm_ctx->ctx_len;
}
return len;
}
static void copy_from_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
{
memcpy(&x->id, &p->id, sizeof(x->id));
memcpy(&x->sel, &p->sel, sizeof(x->sel));
memcpy(&x->lft, &p->lft, sizeof(x->lft));
x->props.mode = p->mode;
x->props.replay_window = p->replay_window;
x->props.reqid = p->reqid;
x->props.family = p->family;
memcpy(&x->props.saddr, &p->saddr, sizeof(x->props.saddr));
x->props.flags = p->flags;
if (!x->sel.family && !(p->flags & XFRM_STATE_AF_UNSPEC))
x->sel.family = p->family;
}
/*
* someday when pfkey also has support, we could have the code
* somehow made shareable and move it to xfrm_state.c - JHS
*
*/
static void xfrm_update_ae_params(struct xfrm_state *x, struct nlattr **attrs)
{
struct nlattr *rp = attrs[XFRMA_REPLAY_VAL];
struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL];
struct nlattr *lt = attrs[XFRMA_LTIME_VAL];
struct nlattr *et = attrs[XFRMA_ETIMER_THRESH];
struct nlattr *rt = attrs[XFRMA_REPLAY_THRESH];
if (re) {
struct xfrm_replay_state_esn *replay_esn;
replay_esn = nla_data(re);
memcpy(x->replay_esn, replay_esn,
xfrm_replay_state_esn_len(replay_esn));
memcpy(x->preplay_esn, replay_esn,
xfrm_replay_state_esn_len(replay_esn));
}
if (rp) {
struct xfrm_replay_state *replay;
replay = nla_data(rp);
memcpy(&x->replay, replay, sizeof(*replay));
memcpy(&x->preplay, replay, sizeof(*replay));
}
if (lt) {
struct xfrm_lifetime_cur *ltime;
ltime = nla_data(lt);
x->curlft.bytes = ltime->bytes;
x->curlft.packets = ltime->packets;
x->curlft.add_time = ltime->add_time;
x->curlft.use_time = ltime->use_time;
}
if (et)
x->replay_maxage = nla_get_u32(et);
if (rt)
x->replay_maxdiff = nla_get_u32(rt);
}
static struct xfrm_state *xfrm_state_construct(struct net *net,
struct xfrm_usersa_info *p,
struct nlattr **attrs,
int *errp)
{
struct xfrm_state *x = xfrm_state_alloc(net);
int err = -ENOMEM;
if (!x)
goto error_no_put;
copy_from_user_state(x, p);
if ((err = attach_aead(&x->aead, &x->props.ealgo,
attrs[XFRMA_ALG_AEAD])))
goto error;
if ((err = attach_auth_trunc(&x->aalg, &x->props.aalgo,
attrs[XFRMA_ALG_AUTH_TRUNC])))
goto error;
if (!x->props.aalgo) {
if ((err = attach_auth(&x->aalg, &x->props.aalgo,
attrs[XFRMA_ALG_AUTH])))
goto error;
}
if ((err = attach_one_algo(&x->ealg, &x->props.ealgo,
xfrm_ealg_get_byname,
attrs[XFRMA_ALG_CRYPT])))
goto error;
if ((err = attach_one_algo(&x->calg, &x->props.calgo,
xfrm_calg_get_byname,
attrs[XFRMA_ALG_COMP])))
goto error;
if (attrs[XFRMA_ENCAP]) {
x->encap = kmemdup(nla_data(attrs[XFRMA_ENCAP]),
sizeof(*x->encap), GFP_KERNEL);
if (x->encap == NULL)
goto error;
}
if (attrs[XFRMA_TFCPAD])
x->tfcpad = nla_get_u32(attrs[XFRMA_TFCPAD]);
if (attrs[XFRMA_COADDR]) {
x->coaddr = kmemdup(nla_data(attrs[XFRMA_COADDR]),
sizeof(*x->coaddr), GFP_KERNEL);
if (x->coaddr == NULL)
goto error;
}
xfrm_mark_get(attrs, &x->mark);
err = __xfrm_init_state(x, false);
if (err)
goto error;
if (attrs[XFRMA_SEC_CTX] &&
security_xfrm_state_alloc(x, nla_data(attrs[XFRMA_SEC_CTX])))
goto error;
if ((err = xfrm_alloc_replay_state_esn(&x->replay_esn, &x->preplay_esn,
attrs[XFRMA_REPLAY_ESN_VAL])))
goto error;
x->km.seq = p->seq;
x->replay_maxdiff = net->xfrm.sysctl_aevent_rseqth;
/* sysctl_xfrm_aevent_etime is in 100ms units */
x->replay_maxage = (net->xfrm.sysctl_aevent_etime*HZ)/XFRM_AE_ETH_M;
if ((err = xfrm_init_replay(x)))
goto error;
/* override default values from above */
xfrm_update_ae_params(x, attrs);
return x;
error:
x->km.state = XFRM_STATE_DEAD;
xfrm_state_put(x);
error_no_put:
*errp = err;
return NULL;
}
static int xfrm_add_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_usersa_info *p = nlmsg_data(nlh);
struct xfrm_state *x;
int err;
struct km_event c;
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
err = verify_newsa_info(p, attrs);
if (err)
return err;
x = xfrm_state_construct(net, p, attrs, &err);
if (!x)
return err;
xfrm_state_hold(x);
if (nlh->nlmsg_type == XFRM_MSG_NEWSA)
err = xfrm_state_add(x);
else
err = xfrm_state_update(x);
security_task_getsecid(current, &sid);
xfrm_audit_state_add(x, err ? 0 : 1, loginuid, sessionid, sid);
if (err < 0) {
x->km.state = XFRM_STATE_DEAD;
__xfrm_state_put(x);
goto out;
}
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.event = nlh->nlmsg_type;
km_state_notify(x, &c);
out:
xfrm_state_put(x);
return err;
}
static struct xfrm_state *xfrm_user_state_lookup(struct net *net,
struct xfrm_usersa_id *p,
struct nlattr **attrs,
int *errp)
{
struct xfrm_state *x = NULL;
struct xfrm_mark m;
int err;
u32 mark = xfrm_mark_get(attrs, &m);
if (xfrm_id_proto_match(p->proto, IPSEC_PROTO_ANY)) {
err = -ESRCH;
x = xfrm_state_lookup(net, mark, &p->daddr, p->spi, p->proto, p->family);
} else {
xfrm_address_t *saddr = NULL;
verify_one_addr(attrs, XFRMA_SRCADDR, &saddr);
if (!saddr) {
err = -EINVAL;
goto out;
}
err = -ESRCH;
x = xfrm_state_lookup_byaddr(net, mark,
&p->daddr, saddr,
p->proto, p->family);
}
out:
if (!x && errp)
*errp = err;
return x;
}
static int xfrm_del_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
int err = -ESRCH;
struct km_event c;
struct xfrm_usersa_id *p = nlmsg_data(nlh);
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
x = xfrm_user_state_lookup(net, p, attrs, &err);
if (x == NULL)
return err;
if ((err = security_xfrm_state_delete(x)) != 0)
goto out;
if (xfrm_state_kern(x)) {
err = -EPERM;
goto out;
}
err = xfrm_state_delete(x);
if (err < 0)
goto out;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.event = nlh->nlmsg_type;
km_state_notify(x, &c);
out:
security_task_getsecid(current, &sid);
xfrm_audit_state_delete(x, err ? 0 : 1, loginuid, sessionid, sid);
xfrm_state_put(x);
return err;
}
static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
{
memcpy(&p->id, &x->id, sizeof(p->id));
memcpy(&p->sel, &x->sel, sizeof(p->sel));
memcpy(&p->lft, &x->lft, sizeof(p->lft));
memcpy(&p->curlft, &x->curlft, sizeof(p->curlft));
memcpy(&p->stats, &x->stats, sizeof(p->stats));
memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr));
p->mode = x->props.mode;
p->replay_window = x->props.replay_window;
p->reqid = x->props.reqid;
p->family = x->props.family;
p->flags = x->props.flags;
p->seq = x->km.seq;
}
struct xfrm_dump_info {
struct sk_buff *in_skb;
struct sk_buff *out_skb;
u32 nlmsg_seq;
u16 nlmsg_flags;
};
static int copy_sec_ctx(struct xfrm_sec_ctx *s, struct sk_buff *skb)
{
struct xfrm_user_sec_ctx *uctx;
struct nlattr *attr;
int ctx_size = sizeof(*uctx) + s->ctx_len;
attr = nla_reserve(skb, XFRMA_SEC_CTX, ctx_size);
if (attr == NULL)
return -EMSGSIZE;
uctx = nla_data(attr);
uctx->exttype = XFRMA_SEC_CTX;
uctx->len = ctx_size;
uctx->ctx_doi = s->ctx_doi;
uctx->ctx_alg = s->ctx_alg;
uctx->ctx_len = s->ctx_len;
memcpy(uctx + 1, s->ctx_str, s->ctx_len);
return 0;
}
static int copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb)
{
struct xfrm_algo *algo;
struct nlattr *nla;
nla = nla_reserve(skb, XFRMA_ALG_AUTH,
sizeof(*algo) + (auth->alg_key_len + 7) / 8);
if (!nla)
return -EMSGSIZE;
algo = nla_data(nla);
strcpy(algo->alg_name, auth->alg_name);
memcpy(algo->alg_key, auth->alg_key, (auth->alg_key_len + 7) / 8);
algo->alg_key_len = auth->alg_key_len;
return 0;
}
/* Don't change this without updating xfrm_sa_len! */
static int copy_to_user_state_extra(struct xfrm_state *x,
struct xfrm_usersa_info *p,
struct sk_buff *skb)
{
copy_to_user_state(x, p);
if (x->coaddr)
NLA_PUT(skb, XFRMA_COADDR, sizeof(*x->coaddr), x->coaddr);
if (x->lastused)
NLA_PUT_U64(skb, XFRMA_LASTUSED, x->lastused);
if (x->aead)
NLA_PUT(skb, XFRMA_ALG_AEAD, aead_len(x->aead), x->aead);
if (x->aalg) {
if (copy_to_user_auth(x->aalg, skb))
goto nla_put_failure;
NLA_PUT(skb, XFRMA_ALG_AUTH_TRUNC,
xfrm_alg_auth_len(x->aalg), x->aalg);
}
if (x->ealg)
NLA_PUT(skb, XFRMA_ALG_CRYPT, xfrm_alg_len(x->ealg), x->ealg);
if (x->calg)
NLA_PUT(skb, XFRMA_ALG_COMP, sizeof(*(x->calg)), x->calg);
if (x->encap)
NLA_PUT(skb, XFRMA_ENCAP, sizeof(*x->encap), x->encap);
if (x->tfcpad)
NLA_PUT_U32(skb, XFRMA_TFCPAD, x->tfcpad);
if (xfrm_mark_put(skb, &x->mark))
goto nla_put_failure;
if (x->replay_esn)
NLA_PUT(skb, XFRMA_REPLAY_ESN_VAL,
xfrm_replay_state_esn_len(x->replay_esn), x->replay_esn);
if (x->security && copy_sec_ctx(x->security, skb) < 0)
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
static int dump_one_state(struct xfrm_state *x, int count, void *ptr)
{
struct xfrm_dump_info *sp = ptr;
struct sk_buff *in_skb = sp->in_skb;
struct sk_buff *skb = sp->out_skb;
struct xfrm_usersa_info *p;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq,
XFRM_MSG_NEWSA, sizeof(*p), sp->nlmsg_flags);
if (nlh == NULL)
return -EMSGSIZE;
p = nlmsg_data(nlh);
err = copy_to_user_state_extra(x, p, skb);
if (err)
goto nla_put_failure;
nlmsg_end(skb, nlh);
return 0;
nla_put_failure:
nlmsg_cancel(skb, nlh);
return err;
}
static int xfrm_dump_sa_done(struct netlink_callback *cb)
{
struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1];
xfrm_state_walk_done(walk);
return 0;
}
static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1];
struct xfrm_dump_info info;
BUILD_BUG_ON(sizeof(struct xfrm_state_walk) >
sizeof(cb->args) - sizeof(cb->args[0]));
info.in_skb = cb->skb;
info.out_skb = skb;
info.nlmsg_seq = cb->nlh->nlmsg_seq;
info.nlmsg_flags = NLM_F_MULTI;
if (!cb->args[0]) {
cb->args[0] = 1;
xfrm_state_walk_init(walk, 0);
}
(void) xfrm_state_walk(net, walk, dump_one_state, &info);
return skb->len;
}
static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb,
struct xfrm_state *x, u32 seq)
{
struct xfrm_dump_info info;
struct sk_buff *skb;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!skb)
return ERR_PTR(-ENOMEM);
info.in_skb = in_skb;
info.out_skb = skb;
info.nlmsg_seq = seq;
info.nlmsg_flags = 0;
if (dump_one_state(x, 0, &info)) {
kfree_skb(skb);
return NULL;
}
return skb;
}
static inline size_t xfrm_spdinfo_msgsize(void)
{
return NLMSG_ALIGN(4)
+ nla_total_size(sizeof(struct xfrmu_spdinfo))
+ nla_total_size(sizeof(struct xfrmu_spdhinfo));
}
static int build_spdinfo(struct sk_buff *skb, struct net *net,
u32 pid, u32 seq, u32 flags)
{
struct xfrmk_spdinfo si;
struct xfrmu_spdinfo spc;
struct xfrmu_spdhinfo sph;
struct nlmsghdr *nlh;
u32 *f;
nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSPDINFO, sizeof(u32), 0);
if (nlh == NULL) /* shouldn't really happen ... */
return -EMSGSIZE;
f = nlmsg_data(nlh);
*f = flags;
xfrm_spd_getinfo(net, &si);
spc.incnt = si.incnt;
spc.outcnt = si.outcnt;
spc.fwdcnt = si.fwdcnt;
spc.inscnt = si.inscnt;
spc.outscnt = si.outscnt;
spc.fwdscnt = si.fwdscnt;
sph.spdhcnt = si.spdhcnt;
sph.spdhmcnt = si.spdhmcnt;
NLA_PUT(skb, XFRMA_SPD_INFO, sizeof(spc), &spc);
NLA_PUT(skb, XFRMA_SPD_HINFO, sizeof(sph), &sph);
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static int xfrm_get_spdinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct sk_buff *r_skb;
u32 *flags = nlmsg_data(nlh);
u32 spid = NETLINK_CB(skb).pid;
u32 seq = nlh->nlmsg_seq;
r_skb = nlmsg_new(xfrm_spdinfo_msgsize(), GFP_ATOMIC);
if (r_skb == NULL)
return -ENOMEM;
if (build_spdinfo(r_skb, net, spid, seq, *flags) < 0)
BUG();
return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid);
}
static inline size_t xfrm_sadinfo_msgsize(void)
{
return NLMSG_ALIGN(4)
+ nla_total_size(sizeof(struct xfrmu_sadhinfo))
+ nla_total_size(4); /* XFRMA_SAD_CNT */
}
static int build_sadinfo(struct sk_buff *skb, struct net *net,
u32 pid, u32 seq, u32 flags)
{
struct xfrmk_sadinfo si;
struct xfrmu_sadhinfo sh;
struct nlmsghdr *nlh;
u32 *f;
nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSADINFO, sizeof(u32), 0);
if (nlh == NULL) /* shouldn't really happen ... */
return -EMSGSIZE;
f = nlmsg_data(nlh);
*f = flags;
xfrm_sad_getinfo(net, &si);
sh.sadhmcnt = si.sadhmcnt;
sh.sadhcnt = si.sadhcnt;
NLA_PUT_U32(skb, XFRMA_SAD_CNT, si.sadcnt);
NLA_PUT(skb, XFRMA_SAD_HINFO, sizeof(sh), &sh);
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static int xfrm_get_sadinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct sk_buff *r_skb;
u32 *flags = nlmsg_data(nlh);
u32 spid = NETLINK_CB(skb).pid;
u32 seq = nlh->nlmsg_seq;
r_skb = nlmsg_new(xfrm_sadinfo_msgsize(), GFP_ATOMIC);
if (r_skb == NULL)
return -ENOMEM;
if (build_sadinfo(r_skb, net, spid, seq, *flags) < 0)
BUG();
return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid);
}
static int xfrm_get_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_usersa_id *p = nlmsg_data(nlh);
struct xfrm_state *x;
struct sk_buff *resp_skb;
int err = -ESRCH;
x = xfrm_user_state_lookup(net, p, attrs, &err);
if (x == NULL)
goto out_noput;
resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq);
if (IS_ERR(resp_skb)) {
err = PTR_ERR(resp_skb);
} else {
err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid);
}
xfrm_state_put(x);
out_noput:
return err;
}
static int verify_userspi_info(struct xfrm_userspi_info *p)
{
switch (p->info.id.proto) {
case IPPROTO_AH:
case IPPROTO_ESP:
break;
case IPPROTO_COMP:
/* IPCOMP spi is 16-bits. */
if (p->max >= 0x10000)
return -EINVAL;
break;
default:
return -EINVAL;
}
if (p->min > p->max)
return -EINVAL;
return 0;
}
static int xfrm_alloc_userspi(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
struct xfrm_userspi_info *p;
struct sk_buff *resp_skb;
xfrm_address_t *daddr;
int family;
int err;
u32 mark;
struct xfrm_mark m;
p = nlmsg_data(nlh);
err = verify_userspi_info(p);
if (err)
goto out_noput;
family = p->info.family;
daddr = &p->info.id.daddr;
x = NULL;
mark = xfrm_mark_get(attrs, &m);
if (p->info.seq) {
x = xfrm_find_acq_byseq(net, mark, p->info.seq);
if (x && xfrm_addr_cmp(&x->id.daddr, daddr, family)) {
xfrm_state_put(x);
x = NULL;
}
}
if (!x)
x = xfrm_find_acq(net, &m, p->info.mode, p->info.reqid,
p->info.id.proto, daddr,
&p->info.saddr, 1,
family);
err = -ENOENT;
if (x == NULL)
goto out_noput;
err = xfrm_alloc_spi(x, p->min, p->max);
if (err)
goto out;
resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq);
if (IS_ERR(resp_skb)) {
err = PTR_ERR(resp_skb);
goto out;
}
err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid);
out:
xfrm_state_put(x);
out_noput:
return err;
}
static int verify_policy_dir(u8 dir)
{
switch (dir) {
case XFRM_POLICY_IN:
case XFRM_POLICY_OUT:
case XFRM_POLICY_FWD:
break;
default:
return -EINVAL;
}
return 0;
}
static int verify_policy_type(u8 type)
{
switch (type) {
case XFRM_POLICY_TYPE_MAIN:
#ifdef CONFIG_XFRM_SUB_POLICY
case XFRM_POLICY_TYPE_SUB:
#endif
break;
default:
return -EINVAL;
}
return 0;
}
static int verify_newpolicy_info(struct xfrm_userpolicy_info *p)
{
switch (p->share) {
case XFRM_SHARE_ANY:
case XFRM_SHARE_SESSION:
case XFRM_SHARE_USER:
case XFRM_SHARE_UNIQUE:
break;
default:
return -EINVAL;
}
switch (p->action) {
case XFRM_POLICY_ALLOW:
case XFRM_POLICY_BLOCK:
break;
default:
return -EINVAL;
}
switch (p->sel.family) {
case AF_INET:
break;
case AF_INET6:
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
break;
#else
return -EAFNOSUPPORT;
#endif
default:
return -EINVAL;
}
return verify_policy_dir(p->dir);
}
static int copy_from_user_sec_ctx(struct xfrm_policy *pol, struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_user_sec_ctx *uctx;
if (!rt)
return 0;
uctx = nla_data(rt);
return security_xfrm_policy_alloc(&pol->security, uctx);
}
static void copy_templates(struct xfrm_policy *xp, struct xfrm_user_tmpl *ut,
int nr)
{
int i;
xp->xfrm_nr = nr;
for (i = 0; i < nr; i++, ut++) {
struct xfrm_tmpl *t = &xp->xfrm_vec[i];
memcpy(&t->id, &ut->id, sizeof(struct xfrm_id));
memcpy(&t->saddr, &ut->saddr,
sizeof(xfrm_address_t));
t->reqid = ut->reqid;
t->mode = ut->mode;
t->share = ut->share;
t->optional = ut->optional;
t->aalgos = ut->aalgos;
t->ealgos = ut->ealgos;
t->calgos = ut->calgos;
/* If all masks are ~0, then we allow all algorithms. */
t->allalgs = !~(t->aalgos & t->ealgos & t->calgos);
t->encap_family = ut->family;
}
}
static int validate_tmpl(int nr, struct xfrm_user_tmpl *ut, u16 family)
{
int i;
if (nr > XFRM_MAX_DEPTH)
return -EINVAL;
for (i = 0; i < nr; i++) {
/* We never validated the ut->family value, so many
* applications simply leave it at zero. The check was
* never made and ut->family was ignored because all
* templates could be assumed to have the same family as
* the policy itself. Now that we will have ipv4-in-ipv6
* and ipv6-in-ipv4 tunnels, this is no longer true.
*/
if (!ut[i].family)
ut[i].family = family;
switch (ut[i].family) {
case AF_INET:
break;
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
case AF_INET6:
break;
#endif
default:
return -EINVAL;
}
}
return 0;
}
static int copy_from_user_tmpl(struct xfrm_policy *pol, struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_TMPL];
if (!rt) {
pol->xfrm_nr = 0;
} else {
struct xfrm_user_tmpl *utmpl = nla_data(rt);
int nr = nla_len(rt) / sizeof(*utmpl);
int err;
err = validate_tmpl(nr, utmpl, pol->family);
if (err)
return err;
copy_templates(pol, utmpl, nr);
}
return 0;
}
static int copy_from_user_policy_type(u8 *tp, struct nlattr **attrs)
{
struct nlattr *rt = attrs[XFRMA_POLICY_TYPE];
struct xfrm_userpolicy_type *upt;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err;
if (rt) {
upt = nla_data(rt);
type = upt->type;
}
err = verify_policy_type(type);
if (err)
return err;
*tp = type;
return 0;
}
static void copy_from_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p)
{
xp->priority = p->priority;
xp->index = p->index;
memcpy(&xp->selector, &p->sel, sizeof(xp->selector));
memcpy(&xp->lft, &p->lft, sizeof(xp->lft));
xp->action = p->action;
xp->flags = p->flags;
xp->family = p->sel.family;
/* XXX xp->share = p->share; */
}
static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir)
{
memcpy(&p->sel, &xp->selector, sizeof(p->sel));
memcpy(&p->lft, &xp->lft, sizeof(p->lft));
memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft));
p->priority = xp->priority;
p->index = xp->index;
p->sel.family = xp->family;
p->dir = dir;
p->action = xp->action;
p->flags = xp->flags;
p->share = XFRM_SHARE_ANY; /* XXX xp->share */
}
static struct xfrm_policy *xfrm_policy_construct(struct net *net, struct xfrm_userpolicy_info *p, struct nlattr **attrs, int *errp)
{
struct xfrm_policy *xp = xfrm_policy_alloc(net, GFP_KERNEL);
int err;
if (!xp) {
*errp = -ENOMEM;
return NULL;
}
copy_from_user_policy(xp, p);
err = copy_from_user_policy_type(&xp->type, attrs);
if (err)
goto error;
if (!(err = copy_from_user_tmpl(xp, attrs)))
err = copy_from_user_sec_ctx(xp, attrs);
if (err)
goto error;
xfrm_mark_get(attrs, &xp->mark);
return xp;
error:
*errp = err;
xp->walk.dead = 1;
xfrm_policy_destroy(xp);
return NULL;
}
static int xfrm_add_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_userpolicy_info *p = nlmsg_data(nlh);
struct xfrm_policy *xp;
struct km_event c;
int err;
int excl;
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
err = verify_newpolicy_info(p);
if (err)
return err;
err = verify_sec_ctx_len(attrs);
if (err)
return err;
xp = xfrm_policy_construct(net, p, attrs, &err);
if (!xp)
return err;
/* shouldn't excl be based on nlh flags??
* Aha! this is anti-netlink really i.e more pfkey derived
* in netlink excl is a flag and you wouldnt need
* a type XFRM_MSG_UPDPOLICY - JHS */
excl = nlh->nlmsg_type == XFRM_MSG_NEWPOLICY;
err = xfrm_policy_insert(p->dir, xp, excl);
security_task_getsecid(current, &sid);
xfrm_audit_policy_add(xp, err ? 0 : 1, loginuid, sessionid, sid);
if (err) {
security_xfrm_policy_free(xp->security);
kfree(xp);
return err;
}
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
km_policy_notify(xp, p->dir, &c);
xfrm_pol_put(xp);
return 0;
}
static int copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb)
{
struct xfrm_user_tmpl vec[XFRM_MAX_DEPTH];
int i;
if (xp->xfrm_nr == 0)
return 0;
for (i = 0; i < xp->xfrm_nr; i++) {
struct xfrm_user_tmpl *up = &vec[i];
struct xfrm_tmpl *kp = &xp->xfrm_vec[i];
memcpy(&up->id, &kp->id, sizeof(up->id));
up->family = kp->encap_family;
memcpy(&up->saddr, &kp->saddr, sizeof(up->saddr));
up->reqid = kp->reqid;
up->mode = kp->mode;
up->share = kp->share;
up->optional = kp->optional;
up->aalgos = kp->aalgos;
up->ealgos = kp->ealgos;
up->calgos = kp->calgos;
}
return nla_put(skb, XFRMA_TMPL,
sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr, vec);
}
static inline int copy_to_user_state_sec_ctx(struct xfrm_state *x, struct sk_buff *skb)
{
if (x->security) {
return copy_sec_ctx(x->security, skb);
}
return 0;
}
static inline int copy_to_user_sec_ctx(struct xfrm_policy *xp, struct sk_buff *skb)
{
if (xp->security) {
return copy_sec_ctx(xp->security, skb);
}
return 0;
}
static inline size_t userpolicy_type_attrsize(void)
{
#ifdef CONFIG_XFRM_SUB_POLICY
return nla_total_size(sizeof(struct xfrm_userpolicy_type));
#else
return 0;
#endif
}
#ifdef CONFIG_XFRM_SUB_POLICY
static int copy_to_user_policy_type(u8 type, struct sk_buff *skb)
{
struct xfrm_userpolicy_type upt = {
.type = type,
};
return nla_put(skb, XFRMA_POLICY_TYPE, sizeof(upt), &upt);
}
#else
static inline int copy_to_user_policy_type(u8 type, struct sk_buff *skb)
{
return 0;
}
#endif
static int dump_one_policy(struct xfrm_policy *xp, int dir, int count, void *ptr)
{
struct xfrm_dump_info *sp = ptr;
struct xfrm_userpolicy_info *p;
struct sk_buff *in_skb = sp->in_skb;
struct sk_buff *skb = sp->out_skb;
struct nlmsghdr *nlh;
nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq,
XFRM_MSG_NEWPOLICY, sizeof(*p), sp->nlmsg_flags);
if (nlh == NULL)
return -EMSGSIZE;
p = nlmsg_data(nlh);
copy_to_user_policy(xp, p, dir);
if (copy_to_user_tmpl(xp, skb) < 0)
goto nlmsg_failure;
if (copy_to_user_sec_ctx(xp, skb))
goto nlmsg_failure;
if (copy_to_user_policy_type(xp->type, skb) < 0)
goto nlmsg_failure;
if (xfrm_mark_put(skb, &xp->mark))
goto nla_put_failure;
nlmsg_end(skb, nlh);
return 0;
nla_put_failure:
nlmsg_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static int xfrm_dump_policy_done(struct netlink_callback *cb)
{
struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1];
xfrm_policy_walk_done(walk);
return 0;
}
static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1];
struct xfrm_dump_info info;
BUILD_BUG_ON(sizeof(struct xfrm_policy_walk) >
sizeof(cb->args) - sizeof(cb->args[0]));
info.in_skb = cb->skb;
info.out_skb = skb;
info.nlmsg_seq = cb->nlh->nlmsg_seq;
info.nlmsg_flags = NLM_F_MULTI;
if (!cb->args[0]) {
cb->args[0] = 1;
xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY);
}
(void) xfrm_policy_walk(net, walk, dump_one_policy, &info);
return skb->len;
}
static struct sk_buff *xfrm_policy_netlink(struct sk_buff *in_skb,
struct xfrm_policy *xp,
int dir, u32 seq)
{
struct xfrm_dump_info info;
struct sk_buff *skb;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!skb)
return ERR_PTR(-ENOMEM);
info.in_skb = in_skb;
info.out_skb = skb;
info.nlmsg_seq = seq;
info.nlmsg_flags = 0;
if (dump_one_policy(xp, dir, 0, &info) < 0) {
kfree_skb(skb);
return NULL;
}
return skb;
}
static int xfrm_get_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy *xp;
struct xfrm_userpolicy_id *p;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err;
struct km_event c;
int delete;
struct xfrm_mark m;
u32 mark = xfrm_mark_get(attrs, &m);
p = nlmsg_data(nlh);
delete = nlh->nlmsg_type == XFRM_MSG_DELPOLICY;
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
err = verify_policy_dir(p->dir);
if (err)
return err;
if (p->index)
xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, delete, &err);
else {
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_sec_ctx *ctx;
err = verify_sec_ctx_len(attrs);
if (err)
return err;
ctx = NULL;
if (rt) {
struct xfrm_user_sec_ctx *uctx = nla_data(rt);
err = security_xfrm_policy_alloc(&ctx, uctx);
if (err)
return err;
}
xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir, &p->sel,
ctx, delete, &err);
security_xfrm_policy_free(ctx);
}
if (xp == NULL)
return -ENOENT;
if (!delete) {
struct sk_buff *resp_skb;
resp_skb = xfrm_policy_netlink(skb, xp, p->dir, nlh->nlmsg_seq);
if (IS_ERR(resp_skb)) {
err = PTR_ERR(resp_skb);
} else {
err = nlmsg_unicast(net->xfrm.nlsk, resp_skb,
NETLINK_CB(skb).pid);
}
} else {
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
security_task_getsecid(current, &sid);
xfrm_audit_policy_delete(xp, err ? 0 : 1, loginuid, sessionid,
sid);
if (err != 0)
goto out;
c.data.byid = p->index;
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
km_policy_notify(xp, p->dir, &c);
}
out:
xfrm_pol_put(xp);
return err;
}
static int xfrm_flush_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct km_event c;
struct xfrm_usersa_flush *p = nlmsg_data(nlh);
struct xfrm_audit audit_info;
int err;
audit_info.loginuid = audit_get_loginuid(current);
audit_info.sessionid = audit_get_sessionid(current);
security_task_getsecid(current, &audit_info.secid);
err = xfrm_state_flush(net, p->proto, &audit_info);
if (err) {
if (err == -ESRCH) /* empty table */
return 0;
return err;
}
c.data.proto = p->proto;
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.net = net;
km_state_notify(NULL, &c);
return 0;
}
static inline size_t xfrm_aevent_msgsize(struct xfrm_state *x)
{
size_t replay_size = x->replay_esn ?
xfrm_replay_state_esn_len(x->replay_esn) :
sizeof(struct xfrm_replay_state);
return NLMSG_ALIGN(sizeof(struct xfrm_aevent_id))
+ nla_total_size(replay_size)
+ nla_total_size(sizeof(struct xfrm_lifetime_cur))
+ nla_total_size(sizeof(struct xfrm_mark))
+ nla_total_size(4) /* XFRM_AE_RTHR */
+ nla_total_size(4); /* XFRM_AE_ETHR */
}
static int build_aevent(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c)
{
struct xfrm_aevent_id *id;
struct nlmsghdr *nlh;
nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_NEWAE, sizeof(*id), 0);
if (nlh == NULL)
return -EMSGSIZE;
id = nlmsg_data(nlh);
memcpy(&id->sa_id.daddr, &x->id.daddr,sizeof(x->id.daddr));
id->sa_id.spi = x->id.spi;
id->sa_id.family = x->props.family;
id->sa_id.proto = x->id.proto;
memcpy(&id->saddr, &x->props.saddr,sizeof(x->props.saddr));
id->reqid = x->props.reqid;
id->flags = c->data.aevent;
if (x->replay_esn)
NLA_PUT(skb, XFRMA_REPLAY_ESN_VAL,
xfrm_replay_state_esn_len(x->replay_esn),
x->replay_esn);
else
NLA_PUT(skb, XFRMA_REPLAY_VAL, sizeof(x->replay), &x->replay);
NLA_PUT(skb, XFRMA_LTIME_VAL, sizeof(x->curlft), &x->curlft);
if (id->flags & XFRM_AE_RTHR)
NLA_PUT_U32(skb, XFRMA_REPLAY_THRESH, x->replay_maxdiff);
if (id->flags & XFRM_AE_ETHR)
NLA_PUT_U32(skb, XFRMA_ETIMER_THRESH,
x->replay_maxage * 10 / HZ);
if (xfrm_mark_put(skb, &x->mark))
goto nla_put_failure;
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static int xfrm_get_ae(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
struct sk_buff *r_skb;
int err;
struct km_event c;
u32 mark;
struct xfrm_mark m;
struct xfrm_aevent_id *p = nlmsg_data(nlh);
struct xfrm_usersa_id *id = &p->sa_id;
mark = xfrm_mark_get(attrs, &m);
x = xfrm_state_lookup(net, mark, &id->daddr, id->spi, id->proto, id->family);
if (x == NULL)
return -ESRCH;
r_skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC);
if (r_skb == NULL) {
xfrm_state_put(x);
return -ENOMEM;
}
/*
* XXX: is this lock really needed - none of the other
* gets lock (the concern is things getting updated
* while we are still reading) - jhs
*/
spin_lock_bh(&x->lock);
c.data.aevent = p->flags;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
if (build_aevent(r_skb, x, &c) < 0)
BUG();
err = nlmsg_unicast(net->xfrm.nlsk, r_skb, NETLINK_CB(skb).pid);
spin_unlock_bh(&x->lock);
xfrm_state_put(x);
return err;
}
static int xfrm_new_ae(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
struct km_event c;
int err = - EINVAL;
u32 mark = 0;
struct xfrm_mark m;
struct xfrm_aevent_id *p = nlmsg_data(nlh);
struct nlattr *rp = attrs[XFRMA_REPLAY_VAL];
struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL];
struct nlattr *lt = attrs[XFRMA_LTIME_VAL];
if (!lt && !rp && !re)
return err;
/* pedantic mode - thou shalt sayeth replaceth */
if (!(nlh->nlmsg_flags&NLM_F_REPLACE))
return err;
mark = xfrm_mark_get(attrs, &m);
x = xfrm_state_lookup(net, mark, &p->sa_id.daddr, p->sa_id.spi, p->sa_id.proto, p->sa_id.family);
if (x == NULL)
return -ESRCH;
if (x->km.state != XFRM_STATE_VALID)
goto out;
err = xfrm_replay_verify_len(x->replay_esn, rp);
if (err)
goto out;
spin_lock_bh(&x->lock);
xfrm_update_ae_params(x, attrs);
spin_unlock_bh(&x->lock);
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.data.aevent = XFRM_AE_CU;
km_state_notify(x, &c);
err = 0;
out:
xfrm_state_put(x);
return err;
}
static int xfrm_flush_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct km_event c;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err;
struct xfrm_audit audit_info;
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
audit_info.loginuid = audit_get_loginuid(current);
audit_info.sessionid = audit_get_sessionid(current);
security_task_getsecid(current, &audit_info.secid);
err = xfrm_policy_flush(net, type, &audit_info);
if (err) {
if (err == -ESRCH) /* empty table */
return 0;
return err;
}
c.data.type = type;
c.event = nlh->nlmsg_type;
c.seq = nlh->nlmsg_seq;
c.pid = nlh->nlmsg_pid;
c.net = net;
km_policy_notify(NULL, 0, &c);
return 0;
}
static int xfrm_add_pol_expire(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy *xp;
struct xfrm_user_polexpire *up = nlmsg_data(nlh);
struct xfrm_userpolicy_info *p = &up->pol;
u8 type = XFRM_POLICY_TYPE_MAIN;
int err = -ENOENT;
struct xfrm_mark m;
u32 mark = xfrm_mark_get(attrs, &m);
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
err = verify_policy_dir(p->dir);
if (err)
return err;
if (p->index)
xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, 0, &err);
else {
struct nlattr *rt = attrs[XFRMA_SEC_CTX];
struct xfrm_sec_ctx *ctx;
err = verify_sec_ctx_len(attrs);
if (err)
return err;
ctx = NULL;
if (rt) {
struct xfrm_user_sec_ctx *uctx = nla_data(rt);
err = security_xfrm_policy_alloc(&ctx, uctx);
if (err)
return err;
}
xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir,
&p->sel, ctx, 0, &err);
security_xfrm_policy_free(ctx);
}
if (xp == NULL)
return -ENOENT;
if (unlikely(xp->walk.dead))
goto out;
err = 0;
if (up->hard) {
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
security_task_getsecid(current, &sid);
xfrm_policy_delete(xp, p->dir);
xfrm_audit_policy_delete(xp, 1, loginuid, sessionid, sid);
} else {
// reset the timers here?
WARN(1, "Dont know what to do with soft policy expire\n");
}
km_policy_expired(xp, p->dir, up->hard, current->pid);
out:
xfrm_pol_put(xp);
return err;
}
static int xfrm_add_sa_expire(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_state *x;
int err;
struct xfrm_user_expire *ue = nlmsg_data(nlh);
struct xfrm_usersa_info *p = &ue->state;
struct xfrm_mark m;
u32 mark = xfrm_mark_get(attrs, &m);
x = xfrm_state_lookup(net, mark, &p->id.daddr, p->id.spi, p->id.proto, p->family);
err = -ENOENT;
if (x == NULL)
return err;
spin_lock_bh(&x->lock);
err = -EINVAL;
if (x->km.state != XFRM_STATE_VALID)
goto out;
km_state_expired(x, ue->hard, current->pid);
if (ue->hard) {
uid_t loginuid = audit_get_loginuid(current);
u32 sessionid = audit_get_sessionid(current);
u32 sid;
security_task_getsecid(current, &sid);
__xfrm_state_delete(x);
xfrm_audit_state_delete(x, 1, loginuid, sessionid, sid);
}
err = 0;
out:
spin_unlock_bh(&x->lock);
xfrm_state_put(x);
return err;
}
static int xfrm_add_acquire(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy *xp;
struct xfrm_user_tmpl *ut;
int i;
struct nlattr *rt = attrs[XFRMA_TMPL];
struct xfrm_mark mark;
struct xfrm_user_acquire *ua = nlmsg_data(nlh);
struct xfrm_state *x = xfrm_state_alloc(net);
int err = -ENOMEM;
if (!x)
goto nomem;
xfrm_mark_get(attrs, &mark);
err = verify_newpolicy_info(&ua->policy);
if (err)
goto bad_policy;
/* build an XP */
xp = xfrm_policy_construct(net, &ua->policy, attrs, &err);
if (!xp)
goto free_state;
memcpy(&x->id, &ua->id, sizeof(ua->id));
memcpy(&x->props.saddr, &ua->saddr, sizeof(ua->saddr));
memcpy(&x->sel, &ua->sel, sizeof(ua->sel));
xp->mark.m = x->mark.m = mark.m;
xp->mark.v = x->mark.v = mark.v;
ut = nla_data(rt);
/* extract the templates and for each call km_key */
for (i = 0; i < xp->xfrm_nr; i++, ut++) {
struct xfrm_tmpl *t = &xp->xfrm_vec[i];
memcpy(&x->id, &t->id, sizeof(x->id));
x->props.mode = t->mode;
x->props.reqid = t->reqid;
x->props.family = ut->family;
t->aalgos = ua->aalgos;
t->ealgos = ua->ealgos;
t->calgos = ua->calgos;
err = km_query(x, t, xp);
}
kfree(x);
kfree(xp);
return 0;
bad_policy:
WARN(1, "BAD policy passed\n");
free_state:
kfree(x);
nomem:
return err;
}
#ifdef CONFIG_XFRM_MIGRATE
static int copy_from_user_migrate(struct xfrm_migrate *ma,
struct xfrm_kmaddress *k,
struct nlattr **attrs, int *num)
{
struct nlattr *rt = attrs[XFRMA_MIGRATE];
struct xfrm_user_migrate *um;
int i, num_migrate;
if (k != NULL) {
struct xfrm_user_kmaddress *uk;
uk = nla_data(attrs[XFRMA_KMADDRESS]);
memcpy(&k->local, &uk->local, sizeof(k->local));
memcpy(&k->remote, &uk->remote, sizeof(k->remote));
k->family = uk->family;
k->reserved = uk->reserved;
}
um = nla_data(rt);
num_migrate = nla_len(rt) / sizeof(*um);
if (num_migrate <= 0 || num_migrate > XFRM_MAX_DEPTH)
return -EINVAL;
for (i = 0; i < num_migrate; i++, um++, ma++) {
memcpy(&ma->old_daddr, &um->old_daddr, sizeof(ma->old_daddr));
memcpy(&ma->old_saddr, &um->old_saddr, sizeof(ma->old_saddr));
memcpy(&ma->new_daddr, &um->new_daddr, sizeof(ma->new_daddr));
memcpy(&ma->new_saddr, &um->new_saddr, sizeof(ma->new_saddr));
ma->proto = um->proto;
ma->mode = um->mode;
ma->reqid = um->reqid;
ma->old_family = um->old_family;
ma->new_family = um->new_family;
}
*num = i;
return 0;
}
static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
struct xfrm_userpolicy_id *pi = nlmsg_data(nlh);
struct xfrm_migrate m[XFRM_MAX_DEPTH];
struct xfrm_kmaddress km, *kmp;
u8 type;
int err;
int n = 0;
if (attrs[XFRMA_MIGRATE] == NULL)
return -EINVAL;
kmp = attrs[XFRMA_KMADDRESS] ? &km : NULL;
err = copy_from_user_policy_type(&type, attrs);
if (err)
return err;
err = copy_from_user_migrate((struct xfrm_migrate *)m, kmp, attrs, &n);
if (err)
return err;
if (!n)
return 0;
xfrm_migrate(&pi->sel, pi->dir, type, m, n, kmp);
return 0;
}
#else
static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
return -ENOPROTOOPT;
}
#endif
#ifdef CONFIG_XFRM_MIGRATE
static int copy_to_user_migrate(const struct xfrm_migrate *m, struct sk_buff *skb)
{
struct xfrm_user_migrate um;
memset(&um, 0, sizeof(um));
um.proto = m->proto;
um.mode = m->mode;
um.reqid = m->reqid;
um.old_family = m->old_family;
memcpy(&um.old_daddr, &m->old_daddr, sizeof(um.old_daddr));
memcpy(&um.old_saddr, &m->old_saddr, sizeof(um.old_saddr));
um.new_family = m->new_family;
memcpy(&um.new_daddr, &m->new_daddr, sizeof(um.new_daddr));
memcpy(&um.new_saddr, &m->new_saddr, sizeof(um.new_saddr));
return nla_put(skb, XFRMA_MIGRATE, sizeof(um), &um);
}
static int copy_to_user_kmaddress(const struct xfrm_kmaddress *k, struct sk_buff *skb)
{
struct xfrm_user_kmaddress uk;
memset(&uk, 0, sizeof(uk));
uk.family = k->family;
uk.reserved = k->reserved;
memcpy(&uk.local, &k->local, sizeof(uk.local));
memcpy(&uk.remote, &k->remote, sizeof(uk.remote));
return nla_put(skb, XFRMA_KMADDRESS, sizeof(uk), &uk);
}
static inline size_t xfrm_migrate_msgsize(int num_migrate, int with_kma)
{
return NLMSG_ALIGN(sizeof(struct xfrm_userpolicy_id))
+ (with_kma ? nla_total_size(sizeof(struct xfrm_kmaddress)) : 0)
+ nla_total_size(sizeof(struct xfrm_user_migrate) * num_migrate)
+ userpolicy_type_attrsize();
}
static int build_migrate(struct sk_buff *skb, const struct xfrm_migrate *m,
int num_migrate, const struct xfrm_kmaddress *k,
const struct xfrm_selector *sel, u8 dir, u8 type)
{
const struct xfrm_migrate *mp;
struct xfrm_userpolicy_id *pol_id;
struct nlmsghdr *nlh;
int i;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MIGRATE, sizeof(*pol_id), 0);
if (nlh == NULL)
return -EMSGSIZE;
pol_id = nlmsg_data(nlh);
/* copy data from selector, dir, and type to the pol_id */
memset(pol_id, 0, sizeof(*pol_id));
memcpy(&pol_id->sel, sel, sizeof(pol_id->sel));
pol_id->dir = dir;
if (k != NULL && (copy_to_user_kmaddress(k, skb) < 0))
goto nlmsg_failure;
if (copy_to_user_policy_type(type, skb) < 0)
goto nlmsg_failure;
for (i = 0, mp = m ; i < num_migrate; i++, mp++) {
if (copy_to_user_migrate(mp, skb) < 0)
goto nlmsg_failure;
}
return nlmsg_end(skb, nlh);
nlmsg_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
const struct xfrm_migrate *m, int num_migrate,
const struct xfrm_kmaddress *k)
{
struct net *net = &init_net;
struct sk_buff *skb;
skb = nlmsg_new(xfrm_migrate_msgsize(num_migrate, !!k), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
/* build migrate */
if (build_migrate(skb, m, num_migrate, k, sel, dir, type) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MIGRATE, GFP_ATOMIC);
}
#else
static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
const struct xfrm_migrate *m, int num_migrate,
const struct xfrm_kmaddress *k)
{
return -ENOPROTOOPT;
}
#endif
#define XMSGSIZE(type) sizeof(struct type)
static const int xfrm_msg_min[XFRM_NR_MSGTYPES] = {
[XFRM_MSG_NEWSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info),
[XFRM_MSG_DELSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id),
[XFRM_MSG_GETSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id),
[XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info),
[XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
[XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
[XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userspi_info),
[XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_acquire),
[XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_expire),
[XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info),
[XFRM_MSG_UPDSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info),
[XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_polexpire),
[XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_flush),
[XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = 0,
[XFRM_MSG_NEWAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id),
[XFRM_MSG_GETAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id),
[XFRM_MSG_REPORT - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_report),
[XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
[XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = sizeof(u32),
[XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = sizeof(u32),
};
#undef XMSGSIZE
static const struct nla_policy xfrma_policy[XFRMA_MAX+1] = {
[XFRMA_SA] = { .len = sizeof(struct xfrm_usersa_info)},
[XFRMA_POLICY] = { .len = sizeof(struct xfrm_userpolicy_info)},
[XFRMA_LASTUSED] = { .type = NLA_U64},
[XFRMA_ALG_AUTH_TRUNC] = { .len = sizeof(struct xfrm_algo_auth)},
[XFRMA_ALG_AEAD] = { .len = sizeof(struct xfrm_algo_aead) },
[XFRMA_ALG_AUTH] = { .len = sizeof(struct xfrm_algo) },
[XFRMA_ALG_CRYPT] = { .len = sizeof(struct xfrm_algo) },
[XFRMA_ALG_COMP] = { .len = sizeof(struct xfrm_algo) },
[XFRMA_ENCAP] = { .len = sizeof(struct xfrm_encap_tmpl) },
[XFRMA_TMPL] = { .len = sizeof(struct xfrm_user_tmpl) },
[XFRMA_SEC_CTX] = { .len = sizeof(struct xfrm_sec_ctx) },
[XFRMA_LTIME_VAL] = { .len = sizeof(struct xfrm_lifetime_cur) },
[XFRMA_REPLAY_VAL] = { .len = sizeof(struct xfrm_replay_state) },
[XFRMA_REPLAY_THRESH] = { .type = NLA_U32 },
[XFRMA_ETIMER_THRESH] = { .type = NLA_U32 },
[XFRMA_SRCADDR] = { .len = sizeof(xfrm_address_t) },
[XFRMA_COADDR] = { .len = sizeof(xfrm_address_t) },
[XFRMA_POLICY_TYPE] = { .len = sizeof(struct xfrm_userpolicy_type)},
[XFRMA_MIGRATE] = { .len = sizeof(struct xfrm_user_migrate) },
[XFRMA_KMADDRESS] = { .len = sizeof(struct xfrm_user_kmaddress) },
[XFRMA_MARK] = { .len = sizeof(struct xfrm_mark) },
[XFRMA_TFCPAD] = { .type = NLA_U32 },
[XFRMA_REPLAY_ESN_VAL] = { .len = sizeof(struct xfrm_replay_state_esn) },
};
static struct xfrm_link {
int (*doit)(struct sk_buff *, struct nlmsghdr *, struct nlattr **);
int (*dump)(struct sk_buff *, struct netlink_callback *);
int (*done)(struct netlink_callback *);
} xfrm_dispatch[XFRM_NR_MSGTYPES] = {
[XFRM_MSG_NEWSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa },
[XFRM_MSG_DELSA - XFRM_MSG_BASE] = { .doit = xfrm_del_sa },
[XFRM_MSG_GETSA - XFRM_MSG_BASE] = { .doit = xfrm_get_sa,
.dump = xfrm_dump_sa,
.done = xfrm_dump_sa_done },
[XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy },
[XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy },
[XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy,
.dump = xfrm_dump_policy,
.done = xfrm_dump_policy_done },
[XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = { .doit = xfrm_alloc_userspi },
[XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_acquire },
[XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_sa_expire },
[XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy },
[XFRM_MSG_UPDSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa },
[XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_pol_expire},
[XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = { .doit = xfrm_flush_sa },
[XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_flush_policy },
[XFRM_MSG_NEWAE - XFRM_MSG_BASE] = { .doit = xfrm_new_ae },
[XFRM_MSG_GETAE - XFRM_MSG_BASE] = { .doit = xfrm_get_ae },
[XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = { .doit = xfrm_do_migrate },
[XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_sadinfo },
[XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_spdinfo },
};
static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct net *net = sock_net(skb->sk);
struct nlattr *attrs[XFRMA_MAX+1];
struct xfrm_link *link;
int type, err;
type = nlh->nlmsg_type;
if (type > XFRM_MSG_MAX)
return -EINVAL;
type -= XFRM_MSG_BASE;
link = &xfrm_dispatch[type];
/* All operations require privileges, even GET */
if (security_netlink_recv(skb, CAP_NET_ADMIN))
return -EPERM;
if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) ||
type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) &&
(nlh->nlmsg_flags & NLM_F_DUMP)) {
if (link->dump == NULL)
return -EINVAL;
return netlink_dump_start(net->xfrm.nlsk, skb, nlh,
link->dump, link->done, 0);
}
err = nlmsg_parse(nlh, xfrm_msg_min[type], attrs, XFRMA_MAX,
xfrma_policy);
if (err < 0)
return err;
if (link->doit == NULL)
return -EINVAL;
return link->doit(skb, nlh, attrs);
}
static void xfrm_netlink_rcv(struct sk_buff *skb)
{
mutex_lock(&xfrm_cfg_mutex);
netlink_rcv_skb(skb, &xfrm_user_rcv_msg);
mutex_unlock(&xfrm_cfg_mutex);
}
static inline size_t xfrm_expire_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_expire))
+ nla_total_size(sizeof(struct xfrm_mark));
}
static int build_expire(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c)
{
struct xfrm_user_expire *ue;
struct nlmsghdr *nlh;
nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_EXPIRE, sizeof(*ue), 0);
if (nlh == NULL)
return -EMSGSIZE;
ue = nlmsg_data(nlh);
copy_to_user_state(x, &ue->state);
ue->hard = (c->data.hard != 0) ? 1 : 0;
if (xfrm_mark_put(skb, &x->mark))
goto nla_put_failure;
return nlmsg_end(skb, nlh);
nla_put_failure:
return -EMSGSIZE;
}
static int xfrm_exp_state_notify(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_expire_msgsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_expire(skb, x, c) < 0) {
kfree_skb(skb);
return -EMSGSIZE;
}
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC);
}
static int xfrm_aevent_state_notify(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_aevent(skb, x, c) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_AEVENTS, GFP_ATOMIC);
}
static int xfrm_notify_sa_flush(const struct km_event *c)
{
struct net *net = c->net;
struct xfrm_usersa_flush *p;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int len = NLMSG_ALIGN(sizeof(struct xfrm_usersa_flush));
skb = nlmsg_new(len, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHSA, sizeof(*p), 0);
if (nlh == NULL) {
kfree_skb(skb);
return -EMSGSIZE;
}
p = nlmsg_data(nlh);
p->proto = c->data.proto;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC);
}
static inline size_t xfrm_sa_len(struct xfrm_state *x)
{
size_t l = 0;
if (x->aead)
l += nla_total_size(aead_len(x->aead));
if (x->aalg) {
l += nla_total_size(sizeof(struct xfrm_algo) +
(x->aalg->alg_key_len + 7) / 8);
l += nla_total_size(xfrm_alg_auth_len(x->aalg));
}
if (x->ealg)
l += nla_total_size(xfrm_alg_len(x->ealg));
if (x->calg)
l += nla_total_size(sizeof(*x->calg));
if (x->encap)
l += nla_total_size(sizeof(*x->encap));
if (x->tfcpad)
l += nla_total_size(sizeof(x->tfcpad));
if (x->replay_esn)
l += nla_total_size(xfrm_replay_state_esn_len(x->replay_esn));
if (x->security)
l += nla_total_size(sizeof(struct xfrm_user_sec_ctx) +
x->security->ctx_len);
if (x->coaddr)
l += nla_total_size(sizeof(*x->coaddr));
/* Must count x->lastused as it may become non-zero behind our back. */
l += nla_total_size(sizeof(u64));
return l;
}
static int xfrm_notify_sa(struct xfrm_state *x, const struct km_event *c)
{
struct net *net = xs_net(x);
struct xfrm_usersa_info *p;
struct xfrm_usersa_id *id;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int len = xfrm_sa_len(x);
int headlen;
headlen = sizeof(*p);
if (c->event == XFRM_MSG_DELSA) {
len += nla_total_size(headlen);
headlen = sizeof(*id);
len += nla_total_size(sizeof(struct xfrm_mark));
}
len += NLMSG_ALIGN(headlen);
skb = nlmsg_new(len, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0);
if (nlh == NULL)
goto nla_put_failure;
p = nlmsg_data(nlh);
if (c->event == XFRM_MSG_DELSA) {
struct nlattr *attr;
id = nlmsg_data(nlh);
memcpy(&id->daddr, &x->id.daddr, sizeof(id->daddr));
id->spi = x->id.spi;
id->family = x->props.family;
id->proto = x->id.proto;
attr = nla_reserve(skb, XFRMA_SA, sizeof(*p));
if (attr == NULL)
goto nla_put_failure;
p = nla_data(attr);
}
if (copy_to_user_state_extra(x, p, skb))
goto nla_put_failure;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC);
nla_put_failure:
/* Somebody screwed up with xfrm_sa_len! */
WARN_ON(1);
kfree_skb(skb);
return -1;
}
static int xfrm_send_state_notify(struct xfrm_state *x, const struct km_event *c)
{
switch (c->event) {
case XFRM_MSG_EXPIRE:
return xfrm_exp_state_notify(x, c);
case XFRM_MSG_NEWAE:
return xfrm_aevent_state_notify(x, c);
case XFRM_MSG_DELSA:
case XFRM_MSG_UPDSA:
case XFRM_MSG_NEWSA:
return xfrm_notify_sa(x, c);
case XFRM_MSG_FLUSHSA:
return xfrm_notify_sa_flush(c);
default:
printk(KERN_NOTICE "xfrm_user: Unknown SA event %d\n",
c->event);
break;
}
return 0;
}
static inline size_t xfrm_acquire_msgsize(struct xfrm_state *x,
struct xfrm_policy *xp)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_acquire))
+ nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr)
+ nla_total_size(sizeof(struct xfrm_mark))
+ nla_total_size(xfrm_user_sec_ctx_size(x->security))
+ userpolicy_type_attrsize();
}
static int build_acquire(struct sk_buff *skb, struct xfrm_state *x,
struct xfrm_tmpl *xt, struct xfrm_policy *xp,
int dir)
{
struct xfrm_user_acquire *ua;
struct nlmsghdr *nlh;
__u32 seq = xfrm_get_acqseq();
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_ACQUIRE, sizeof(*ua), 0);
if (nlh == NULL)
return -EMSGSIZE;
ua = nlmsg_data(nlh);
memcpy(&ua->id, &x->id, sizeof(ua->id));
memcpy(&ua->saddr, &x->props.saddr, sizeof(ua->saddr));
memcpy(&ua->sel, &x->sel, sizeof(ua->sel));
copy_to_user_policy(xp, &ua->policy, dir);
ua->aalgos = xt->aalgos;
ua->ealgos = xt->ealgos;
ua->calgos = xt->calgos;
ua->seq = x->km.seq = seq;
if (copy_to_user_tmpl(xp, skb) < 0)
goto nlmsg_failure;
if (copy_to_user_state_sec_ctx(x, skb))
goto nlmsg_failure;
if (copy_to_user_policy_type(xp->type, skb) < 0)
goto nlmsg_failure;
if (xfrm_mark_put(skb, &xp->mark))
goto nla_put_failure;
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static int xfrm_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *xt,
struct xfrm_policy *xp, int dir)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_acquire_msgsize(x, xp), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_acquire(skb, x, xt, xp, dir) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_ACQUIRE, GFP_ATOMIC);
}
/* User gives us xfrm_user_policy_info followed by an array of 0
* or more templates.
*/
static struct xfrm_policy *xfrm_compile_policy(struct sock *sk, int opt,
u8 *data, int len, int *dir)
{
struct net *net = sock_net(sk);
struct xfrm_userpolicy_info *p = (struct xfrm_userpolicy_info *)data;
struct xfrm_user_tmpl *ut = (struct xfrm_user_tmpl *) (p + 1);
struct xfrm_policy *xp;
int nr;
switch (sk->sk_family) {
case AF_INET:
if (opt != IP_XFRM_POLICY) {
*dir = -EOPNOTSUPP;
return NULL;
}
break;
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
case AF_INET6:
if (opt != IPV6_XFRM_POLICY) {
*dir = -EOPNOTSUPP;
return NULL;
}
break;
#endif
default:
*dir = -EINVAL;
return NULL;
}
*dir = -EINVAL;
if (len < sizeof(*p) ||
verify_newpolicy_info(p))
return NULL;
nr = ((len - sizeof(*p)) / sizeof(*ut));
if (validate_tmpl(nr, ut, p->sel.family))
return NULL;
if (p->dir > XFRM_POLICY_OUT)
return NULL;
xp = xfrm_policy_alloc(net, GFP_ATOMIC);
if (xp == NULL) {
*dir = -ENOBUFS;
return NULL;
}
copy_from_user_policy(xp, p);
xp->type = XFRM_POLICY_TYPE_MAIN;
copy_templates(xp, ut, nr);
*dir = p->dir;
return xp;
}
static inline size_t xfrm_polexpire_msgsize(struct xfrm_policy *xp)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_polexpire))
+ nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr)
+ nla_total_size(xfrm_user_sec_ctx_size(xp->security))
+ nla_total_size(sizeof(struct xfrm_mark))
+ userpolicy_type_attrsize();
}
static int build_polexpire(struct sk_buff *skb, struct xfrm_policy *xp,
int dir, const struct km_event *c)
{
struct xfrm_user_polexpire *upe;
struct nlmsghdr *nlh;
int hard = c->data.hard;
nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_POLEXPIRE, sizeof(*upe), 0);
if (nlh == NULL)
return -EMSGSIZE;
upe = nlmsg_data(nlh);
copy_to_user_policy(xp, &upe->pol, dir);
if (copy_to_user_tmpl(xp, skb) < 0)
goto nlmsg_failure;
if (copy_to_user_sec_ctx(xp, skb))
goto nlmsg_failure;
if (copy_to_user_policy_type(xp->type, skb) < 0)
goto nlmsg_failure;
if (xfrm_mark_put(skb, &xp->mark))
goto nla_put_failure;
upe->hard = !!hard;
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static int xfrm_exp_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
struct net *net = xp_net(xp);
struct sk_buff *skb;
skb = nlmsg_new(xfrm_polexpire_msgsize(xp), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_polexpire(skb, xp, dir, c) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC);
}
static int xfrm_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
struct net *net = xp_net(xp);
struct xfrm_userpolicy_info *p;
struct xfrm_userpolicy_id *id;
struct nlmsghdr *nlh;
struct sk_buff *skb;
int len = nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr);
int headlen;
headlen = sizeof(*p);
if (c->event == XFRM_MSG_DELPOLICY) {
len += nla_total_size(headlen);
headlen = sizeof(*id);
}
len += userpolicy_type_attrsize();
len += nla_total_size(sizeof(struct xfrm_mark));
len += NLMSG_ALIGN(headlen);
skb = nlmsg_new(len, GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0);
if (nlh == NULL)
goto nlmsg_failure;
p = nlmsg_data(nlh);
if (c->event == XFRM_MSG_DELPOLICY) {
struct nlattr *attr;
id = nlmsg_data(nlh);
memset(id, 0, sizeof(*id));
id->dir = dir;
if (c->data.byid)
id->index = xp->index;
else
memcpy(&id->sel, &xp->selector, sizeof(id->sel));
attr = nla_reserve(skb, XFRMA_POLICY, sizeof(*p));
if (attr == NULL)
goto nlmsg_failure;
p = nla_data(attr);
}
copy_to_user_policy(xp, p, dir);
if (copy_to_user_tmpl(xp, skb) < 0)
goto nlmsg_failure;
if (copy_to_user_policy_type(xp->type, skb) < 0)
goto nlmsg_failure;
if (xfrm_mark_put(skb, &xp->mark))
goto nla_put_failure;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC);
nla_put_failure:
nlmsg_failure:
kfree_skb(skb);
return -1;
}
static int xfrm_notify_policy_flush(const struct km_event *c)
{
struct net *net = c->net;
struct nlmsghdr *nlh;
struct sk_buff *skb;
skb = nlmsg_new(userpolicy_type_attrsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHPOLICY, 0, 0);
if (nlh == NULL)
goto nlmsg_failure;
if (copy_to_user_policy_type(c->data.type, skb) < 0)
goto nlmsg_failure;
nlmsg_end(skb, nlh);
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC);
nlmsg_failure:
kfree_skb(skb);
return -1;
}
static int xfrm_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
{
switch (c->event) {
case XFRM_MSG_NEWPOLICY:
case XFRM_MSG_UPDPOLICY:
case XFRM_MSG_DELPOLICY:
return xfrm_notify_policy(xp, dir, c);
case XFRM_MSG_FLUSHPOLICY:
return xfrm_notify_policy_flush(c);
case XFRM_MSG_POLEXPIRE:
return xfrm_exp_policy_notify(xp, dir, c);
default:
printk(KERN_NOTICE "xfrm_user: Unknown Policy event %d\n",
c->event);
}
return 0;
}
static inline size_t xfrm_report_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_report));
}
static int build_report(struct sk_buff *skb, u8 proto,
struct xfrm_selector *sel, xfrm_address_t *addr)
{
struct xfrm_user_report *ur;
struct nlmsghdr *nlh;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_REPORT, sizeof(*ur), 0);
if (nlh == NULL)
return -EMSGSIZE;
ur = nlmsg_data(nlh);
ur->proto = proto;
memcpy(&ur->sel, sel, sizeof(ur->sel));
if (addr)
NLA_PUT(skb, XFRMA_COADDR, sizeof(*addr), addr);
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static int xfrm_send_report(struct net *net, u8 proto,
struct xfrm_selector *sel, xfrm_address_t *addr)
{
struct sk_buff *skb;
skb = nlmsg_new(xfrm_report_msgsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_report(skb, proto, sel, addr) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_REPORT, GFP_ATOMIC);
}
static inline size_t xfrm_mapping_msgsize(void)
{
return NLMSG_ALIGN(sizeof(struct xfrm_user_mapping));
}
static int build_mapping(struct sk_buff *skb, struct xfrm_state *x,
xfrm_address_t *new_saddr, __be16 new_sport)
{
struct xfrm_user_mapping *um;
struct nlmsghdr *nlh;
nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MAPPING, sizeof(*um), 0);
if (nlh == NULL)
return -EMSGSIZE;
um = nlmsg_data(nlh);
memcpy(&um->id.daddr, &x->id.daddr, sizeof(um->id.daddr));
um->id.spi = x->id.spi;
um->id.family = x->props.family;
um->id.proto = x->id.proto;
memcpy(&um->new_saddr, new_saddr, sizeof(um->new_saddr));
memcpy(&um->old_saddr, &x->props.saddr, sizeof(um->old_saddr));
um->new_sport = new_sport;
um->old_sport = x->encap->encap_sport;
um->reqid = x->props.reqid;
return nlmsg_end(skb, nlh);
}
static int xfrm_send_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr,
__be16 sport)
{
struct net *net = xs_net(x);
struct sk_buff *skb;
if (x->id.proto != IPPROTO_ESP)
return -EINVAL;
if (!x->encap)
return -EINVAL;
skb = nlmsg_new(xfrm_mapping_msgsize(), GFP_ATOMIC);
if (skb == NULL)
return -ENOMEM;
if (build_mapping(skb, x, ipaddr, sport) < 0)
BUG();
return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MAPPING, GFP_ATOMIC);
}
static struct xfrm_mgr netlink_mgr = {
.id = "netlink",
.notify = xfrm_send_state_notify,
.acquire = xfrm_send_acquire,
.compile_policy = xfrm_compile_policy,
.notify_policy = xfrm_send_policy_notify,
.report = xfrm_send_report,
.migrate = xfrm_send_migrate,
.new_mapping = xfrm_send_mapping,
};
static int __net_init xfrm_user_net_init(struct net *net)
{
struct sock *nlsk;
nlsk = netlink_kernel_create(net, NETLINK_XFRM, XFRMNLGRP_MAX,
xfrm_netlink_rcv, NULL, THIS_MODULE);
if (nlsk == NULL)
return -ENOMEM;
net->xfrm.nlsk_stash = nlsk; /* Don't set to NULL */
rcu_assign_pointer(net->xfrm.nlsk, nlsk);
return 0;
}
static void __net_exit xfrm_user_net_exit(struct list_head *net_exit_list)
{
struct net *net;
list_for_each_entry(net, net_exit_list, exit_list)
rcu_assign_pointer(net->xfrm.nlsk, NULL);
synchronize_net();
list_for_each_entry(net, net_exit_list, exit_list)
netlink_kernel_release(net->xfrm.nlsk_stash);
}
static struct pernet_operations xfrm_user_net_ops = {
.init = xfrm_user_net_init,
.exit_batch = xfrm_user_net_exit,
};
static int __init xfrm_user_init(void)
{
int rv;
printk(KERN_INFO "Initializing XFRM netlink socket\n");
rv = register_pernet_subsys(&xfrm_user_net_ops);
if (rv < 0)
return rv;
rv = xfrm_register_km(&netlink_mgr);
if (rv < 0)
unregister_pernet_subsys(&xfrm_user_net_ops);
return rv;
}
static void __exit xfrm_user_exit(void)
{
xfrm_unregister_km(&netlink_mgr);
unregister_pernet_subsys(&xfrm_user_net_ops);
}
module_init(xfrm_user_init);
module_exit(xfrm_user_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_XFRM);
| gpl-2.0 |
drewis/android_kernel_grouper | drivers/net/ibm_newemac/core.c | 382 | 82432 | /*
* drivers/net/ibm_newemac/core.c
*
* Driver for PowerPC 4xx on-chip ethernet controller.
*
* Copyright 2007 Benjamin Herrenschmidt, IBM Corp.
* <benh@kernel.crashing.org>
*
* Based on the arch/ppc version of the driver:
*
* Copyright (c) 2004, 2005 Zultys Technologies.
* Eugene Surovegin <eugene.surovegin@zultys.com> or <ebs@ebshome.net>
*
* Based on original work by
* Matt Porter <mporter@kernel.crashing.org>
* (c) 2003 Benjamin Herrenschmidt <benh@kernel.crashing.org>
* Armin Kuster <akuster@mvista.com>
* Johnnie Peters <jpeters@mvista.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 <linux/sched.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/crc32.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/bitops.h>
#include <linux/workqueue.h>
#include <linux/of.h>
#include <linux/of_net.h>
#include <linux/slab.h>
#include <asm/processor.h>
#include <asm/io.h>
#include <asm/dma.h>
#include <asm/uaccess.h>
#include <asm/dcr.h>
#include <asm/dcr-regs.h>
#include "core.h"
/*
* Lack of dma_unmap_???? calls is intentional.
*
* API-correct usage requires additional support state information to be
* maintained for every RX and TX buffer descriptor (BD). Unfortunately, due to
* EMAC design (e.g. TX buffer passed from network stack can be split into
* several BDs, dma_map_single/dma_map_page can be used to map particular BD),
* maintaining such information will add additional overhead.
* Current DMA API implementation for 4xx processors only ensures cache coherency
* and dma_unmap_???? routines are empty and are likely to stay this way.
* I decided to omit dma_unmap_??? calls because I don't want to add additional
* complexity just for the sake of following some abstract API, when it doesn't
* add any real benefit to the driver. I understand that this decision maybe
* controversial, but I really tried to make code API-correct and efficient
* at the same time and didn't come up with code I liked :(. --ebs
*/
#define DRV_NAME "emac"
#define DRV_VERSION "3.54"
#define DRV_DESC "PPC 4xx OCP EMAC driver"
MODULE_DESCRIPTION(DRV_DESC);
MODULE_AUTHOR
("Eugene Surovegin <eugene.surovegin@zultys.com> or <ebs@ebshome.net>");
MODULE_LICENSE("GPL");
/*
* PPC64 doesn't (yet) have a cacheable_memcpy
*/
#ifdef CONFIG_PPC64
#define cacheable_memcpy(d,s,n) memcpy((d),(s),(n))
#endif
/* minimum number of free TX descriptors required to wake up TX process */
#define EMAC_TX_WAKEUP_THRESH (NUM_TX_BUFF / 4)
/* If packet size is less than this number, we allocate small skb and copy packet
* contents into it instead of just sending original big skb up
*/
#define EMAC_RX_COPY_THRESH CONFIG_IBM_NEW_EMAC_RX_COPY_THRESHOLD
/* Since multiple EMACs share MDIO lines in various ways, we need
* to avoid re-using the same PHY ID in cases where the arch didn't
* setup precise phy_map entries
*
* XXX This is something that needs to be reworked as we can have multiple
* EMAC "sets" (multiple ASICs containing several EMACs) though we can
* probably require in that case to have explicit PHY IDs in the device-tree
*/
static u32 busy_phy_map;
static DEFINE_MUTEX(emac_phy_map_lock);
/* This is the wait queue used to wait on any event related to probe, that
* is discovery of MALs, other EMACs, ZMII/RGMIIs, etc...
*/
static DECLARE_WAIT_QUEUE_HEAD(emac_probe_wait);
/* Having stable interface names is a doomed idea. However, it would be nice
* if we didn't have completely random interface names at boot too :-) It's
* just a matter of making everybody's life easier. Since we are doing
* threaded probing, it's a bit harder though. The base idea here is that
* we make up a list of all emacs in the device-tree before we register the
* driver. Every emac will then wait for the previous one in the list to
* initialize before itself. We should also keep that list ordered by
* cell_index.
* That list is only 4 entries long, meaning that additional EMACs don't
* get ordering guarantees unless EMAC_BOOT_LIST_SIZE is increased.
*/
#define EMAC_BOOT_LIST_SIZE 4
static struct device_node *emac_boot_list[EMAC_BOOT_LIST_SIZE];
/* How long should I wait for dependent devices ? */
#define EMAC_PROBE_DEP_TIMEOUT (HZ * 5)
/* I don't want to litter system log with timeout errors
* when we have brain-damaged PHY.
*/
static inline void emac_report_timeout_error(struct emac_instance *dev,
const char *error)
{
if (emac_has_feature(dev, EMAC_FTR_440GX_PHY_CLK_FIX |
EMAC_FTR_460EX_PHY_CLK_FIX |
EMAC_FTR_440EP_PHY_CLK_FIX))
DBG(dev, "%s" NL, error);
else if (net_ratelimit())
printk(KERN_ERR "%s: %s\n", dev->ofdev->dev.of_node->full_name,
error);
}
/* EMAC PHY clock workaround:
* 440EP/440GR has more sane SDR0_MFR register implementation than 440GX,
* which allows controlling each EMAC clock
*/
static inline void emac_rx_clk_tx(struct emac_instance *dev)
{
#ifdef CONFIG_PPC_DCR_NATIVE
if (emac_has_feature(dev, EMAC_FTR_440EP_PHY_CLK_FIX))
dcri_clrset(SDR0, SDR0_MFR,
0, SDR0_MFR_ECS >> dev->cell_index);
#endif
}
static inline void emac_rx_clk_default(struct emac_instance *dev)
{
#ifdef CONFIG_PPC_DCR_NATIVE
if (emac_has_feature(dev, EMAC_FTR_440EP_PHY_CLK_FIX))
dcri_clrset(SDR0, SDR0_MFR,
SDR0_MFR_ECS >> dev->cell_index, 0);
#endif
}
/* PHY polling intervals */
#define PHY_POLL_LINK_ON HZ
#define PHY_POLL_LINK_OFF (HZ / 5)
/* Graceful stop timeouts in us.
* We should allow up to 1 frame time (full-duplex, ignoring collisions)
*/
#define STOP_TIMEOUT_10 1230
#define STOP_TIMEOUT_100 124
#define STOP_TIMEOUT_1000 13
#define STOP_TIMEOUT_1000_JUMBO 73
static unsigned char default_mcast_addr[] = {
0x01, 0x80, 0xC2, 0x00, 0x00, 0x01
};
/* Please, keep in sync with struct ibm_emac_stats/ibm_emac_error_stats */
static const char emac_stats_keys[EMAC_ETHTOOL_STATS_COUNT][ETH_GSTRING_LEN] = {
"rx_packets", "rx_bytes", "tx_packets", "tx_bytes", "rx_packets_csum",
"tx_packets_csum", "tx_undo", "rx_dropped_stack", "rx_dropped_oom",
"rx_dropped_error", "rx_dropped_resize", "rx_dropped_mtu",
"rx_stopped", "rx_bd_errors", "rx_bd_overrun", "rx_bd_bad_packet",
"rx_bd_runt_packet", "rx_bd_short_event", "rx_bd_alignment_error",
"rx_bd_bad_fcs", "rx_bd_packet_too_long", "rx_bd_out_of_range",
"rx_bd_in_range", "rx_parity", "rx_fifo_overrun", "rx_overrun",
"rx_bad_packet", "rx_runt_packet", "rx_short_event",
"rx_alignment_error", "rx_bad_fcs", "rx_packet_too_long",
"rx_out_of_range", "rx_in_range", "tx_dropped", "tx_bd_errors",
"tx_bd_bad_fcs", "tx_bd_carrier_loss", "tx_bd_excessive_deferral",
"tx_bd_excessive_collisions", "tx_bd_late_collision",
"tx_bd_multple_collisions", "tx_bd_single_collision",
"tx_bd_underrun", "tx_bd_sqe", "tx_parity", "tx_underrun", "tx_sqe",
"tx_errors"
};
static irqreturn_t emac_irq(int irq, void *dev_instance);
static void emac_clean_tx_ring(struct emac_instance *dev);
static void __emac_set_multicast_list(struct emac_instance *dev);
static inline int emac_phy_supports_gige(int phy_mode)
{
return phy_mode == PHY_MODE_GMII ||
phy_mode == PHY_MODE_RGMII ||
phy_mode == PHY_MODE_SGMII ||
phy_mode == PHY_MODE_TBI ||
phy_mode == PHY_MODE_RTBI;
}
static inline int emac_phy_gpcs(int phy_mode)
{
return phy_mode == PHY_MODE_SGMII ||
phy_mode == PHY_MODE_TBI ||
phy_mode == PHY_MODE_RTBI;
}
static inline void emac_tx_enable(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
u32 r;
DBG(dev, "tx_enable" NL);
r = in_be32(&p->mr0);
if (!(r & EMAC_MR0_TXE))
out_be32(&p->mr0, r | EMAC_MR0_TXE);
}
static void emac_tx_disable(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
u32 r;
DBG(dev, "tx_disable" NL);
r = in_be32(&p->mr0);
if (r & EMAC_MR0_TXE) {
int n = dev->stop_timeout;
out_be32(&p->mr0, r & ~EMAC_MR0_TXE);
while (!(in_be32(&p->mr0) & EMAC_MR0_TXI) && n) {
udelay(1);
--n;
}
if (unlikely(!n))
emac_report_timeout_error(dev, "TX disable timeout");
}
}
static void emac_rx_enable(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
u32 r;
if (unlikely(test_bit(MAL_COMMAC_RX_STOPPED, &dev->commac.flags)))
goto out;
DBG(dev, "rx_enable" NL);
r = in_be32(&p->mr0);
if (!(r & EMAC_MR0_RXE)) {
if (unlikely(!(r & EMAC_MR0_RXI))) {
/* Wait if previous async disable is still in progress */
int n = dev->stop_timeout;
while (!(r = in_be32(&p->mr0) & EMAC_MR0_RXI) && n) {
udelay(1);
--n;
}
if (unlikely(!n))
emac_report_timeout_error(dev,
"RX disable timeout");
}
out_be32(&p->mr0, r | EMAC_MR0_RXE);
}
out:
;
}
static void emac_rx_disable(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
u32 r;
DBG(dev, "rx_disable" NL);
r = in_be32(&p->mr0);
if (r & EMAC_MR0_RXE) {
int n = dev->stop_timeout;
out_be32(&p->mr0, r & ~EMAC_MR0_RXE);
while (!(in_be32(&p->mr0) & EMAC_MR0_RXI) && n) {
udelay(1);
--n;
}
if (unlikely(!n))
emac_report_timeout_error(dev, "RX disable timeout");
}
}
static inline void emac_netif_stop(struct emac_instance *dev)
{
netif_tx_lock_bh(dev->ndev);
netif_addr_lock(dev->ndev);
dev->no_mcast = 1;
netif_addr_unlock(dev->ndev);
netif_tx_unlock_bh(dev->ndev);
dev->ndev->trans_start = jiffies; /* prevent tx timeout */
mal_poll_disable(dev->mal, &dev->commac);
netif_tx_disable(dev->ndev);
}
static inline void emac_netif_start(struct emac_instance *dev)
{
netif_tx_lock_bh(dev->ndev);
netif_addr_lock(dev->ndev);
dev->no_mcast = 0;
if (dev->mcast_pending && netif_running(dev->ndev))
__emac_set_multicast_list(dev);
netif_addr_unlock(dev->ndev);
netif_tx_unlock_bh(dev->ndev);
netif_wake_queue(dev->ndev);
/* NOTE: unconditional netif_wake_queue is only appropriate
* so long as all callers are assured to have free tx slots
* (taken from tg3... though the case where that is wrong is
* not terribly harmful)
*/
mal_poll_enable(dev->mal, &dev->commac);
}
static inline void emac_rx_disable_async(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
u32 r;
DBG(dev, "rx_disable_async" NL);
r = in_be32(&p->mr0);
if (r & EMAC_MR0_RXE)
out_be32(&p->mr0, r & ~EMAC_MR0_RXE);
}
static int emac_reset(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
int n = 20;
DBG(dev, "reset" NL);
if (!dev->reset_failed) {
/* 40x erratum suggests stopping RX channel before reset,
* we stop TX as well
*/
emac_rx_disable(dev);
emac_tx_disable(dev);
}
#ifdef CONFIG_PPC_DCR_NATIVE
/* Enable internal clock source */
if (emac_has_feature(dev, EMAC_FTR_460EX_PHY_CLK_FIX))
dcri_clrset(SDR0, SDR0_ETH_CFG,
0, SDR0_ETH_CFG_ECS << dev->cell_index);
#endif
out_be32(&p->mr0, EMAC_MR0_SRST);
while ((in_be32(&p->mr0) & EMAC_MR0_SRST) && n)
--n;
#ifdef CONFIG_PPC_DCR_NATIVE
/* Enable external clock source */
if (emac_has_feature(dev, EMAC_FTR_460EX_PHY_CLK_FIX))
dcri_clrset(SDR0, SDR0_ETH_CFG,
SDR0_ETH_CFG_ECS << dev->cell_index, 0);
#endif
if (n) {
dev->reset_failed = 0;
return 0;
} else {
emac_report_timeout_error(dev, "reset timeout");
dev->reset_failed = 1;
return -ETIMEDOUT;
}
}
static void emac_hash_mc(struct emac_instance *dev)
{
const int regs = EMAC_XAHT_REGS(dev);
u32 *gaht_base = emac_gaht_base(dev);
u32 gaht_temp[regs];
struct netdev_hw_addr *ha;
int i;
DBG(dev, "hash_mc %d" NL, netdev_mc_count(dev->ndev));
memset(gaht_temp, 0, sizeof (gaht_temp));
netdev_for_each_mc_addr(ha, dev->ndev) {
int slot, reg, mask;
DBG2(dev, "mc %pM" NL, ha->addr);
slot = EMAC_XAHT_CRC_TO_SLOT(dev,
ether_crc(ETH_ALEN, ha->addr));
reg = EMAC_XAHT_SLOT_TO_REG(dev, slot);
mask = EMAC_XAHT_SLOT_TO_MASK(dev, slot);
gaht_temp[reg] |= mask;
}
for (i = 0; i < regs; i++)
out_be32(gaht_base + i, gaht_temp[i]);
}
static inline u32 emac_iff2rmr(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
u32 r;
r = EMAC_RMR_SP | EMAC_RMR_SFCS | EMAC_RMR_IAE | EMAC_RMR_BAE;
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
r |= EMAC4_RMR_BASE;
else
r |= EMAC_RMR_BASE;
if (ndev->flags & IFF_PROMISC)
r |= EMAC_RMR_PME;
else if (ndev->flags & IFF_ALLMULTI ||
(netdev_mc_count(ndev) > EMAC_XAHT_SLOTS(dev)))
r |= EMAC_RMR_PMME;
else if (!netdev_mc_empty(ndev))
r |= EMAC_RMR_MAE;
return r;
}
static u32 __emac_calc_base_mr1(struct emac_instance *dev, int tx_size, int rx_size)
{
u32 ret = EMAC_MR1_VLE | EMAC_MR1_IST | EMAC_MR1_TR0_MULT;
DBG2(dev, "__emac_calc_base_mr1" NL);
switch(tx_size) {
case 2048:
ret |= EMAC_MR1_TFS_2K;
break;
default:
printk(KERN_WARNING "%s: Unknown Tx FIFO size %d\n",
dev->ndev->name, tx_size);
}
switch(rx_size) {
case 16384:
ret |= EMAC_MR1_RFS_16K;
break;
case 4096:
ret |= EMAC_MR1_RFS_4K;
break;
default:
printk(KERN_WARNING "%s: Unknown Rx FIFO size %d\n",
dev->ndev->name, rx_size);
}
return ret;
}
static u32 __emac4_calc_base_mr1(struct emac_instance *dev, int tx_size, int rx_size)
{
u32 ret = EMAC_MR1_VLE | EMAC_MR1_IST | EMAC4_MR1_TR |
EMAC4_MR1_OBCI(dev->opb_bus_freq / 1000000);
DBG2(dev, "__emac4_calc_base_mr1" NL);
switch(tx_size) {
case 16384:
ret |= EMAC4_MR1_TFS_16K;
break;
case 4096:
ret |= EMAC4_MR1_TFS_4K;
break;
case 2048:
ret |= EMAC4_MR1_TFS_2K;
break;
default:
printk(KERN_WARNING "%s: Unknown Tx FIFO size %d\n",
dev->ndev->name, tx_size);
}
switch(rx_size) {
case 16384:
ret |= EMAC4_MR1_RFS_16K;
break;
case 4096:
ret |= EMAC4_MR1_RFS_4K;
break;
case 2048:
ret |= EMAC4_MR1_RFS_2K;
break;
default:
printk(KERN_WARNING "%s: Unknown Rx FIFO size %d\n",
dev->ndev->name, rx_size);
}
return ret;
}
static u32 emac_calc_base_mr1(struct emac_instance *dev, int tx_size, int rx_size)
{
return emac_has_feature(dev, EMAC_FTR_EMAC4) ?
__emac4_calc_base_mr1(dev, tx_size, rx_size) :
__emac_calc_base_mr1(dev, tx_size, rx_size);
}
static inline u32 emac_calc_trtr(struct emac_instance *dev, unsigned int size)
{
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
return ((size >> 6) - 1) << EMAC_TRTR_SHIFT_EMAC4;
else
return ((size >> 6) - 1) << EMAC_TRTR_SHIFT;
}
static inline u32 emac_calc_rwmr(struct emac_instance *dev,
unsigned int low, unsigned int high)
{
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
return (low << 22) | ( (high & 0x3ff) << 6);
else
return (low << 23) | ( (high & 0x1ff) << 7);
}
static int emac_configure(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
struct net_device *ndev = dev->ndev;
int tx_size, rx_size, link = netif_carrier_ok(dev->ndev);
u32 r, mr1 = 0;
DBG(dev, "configure" NL);
if (!link) {
out_be32(&p->mr1, in_be32(&p->mr1)
| EMAC_MR1_FDE | EMAC_MR1_ILE);
udelay(100);
} else if (emac_reset(dev) < 0)
return -ETIMEDOUT;
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH))
tah_reset(dev->tah_dev);
DBG(dev, " link = %d duplex = %d, pause = %d, asym_pause = %d\n",
link, dev->phy.duplex, dev->phy.pause, dev->phy.asym_pause);
/* Default fifo sizes */
tx_size = dev->tx_fifo_size;
rx_size = dev->rx_fifo_size;
/* No link, force loopback */
if (!link)
mr1 = EMAC_MR1_FDE | EMAC_MR1_ILE;
/* Check for full duplex */
else if (dev->phy.duplex == DUPLEX_FULL)
mr1 |= EMAC_MR1_FDE | EMAC_MR1_MWSW_001;
/* Adjust fifo sizes, mr1 and timeouts based on link speed */
dev->stop_timeout = STOP_TIMEOUT_10;
switch (dev->phy.speed) {
case SPEED_1000:
if (emac_phy_gpcs(dev->phy.mode)) {
mr1 |= EMAC_MR1_MF_1000GPCS | EMAC_MR1_MF_IPPA(
(dev->phy.gpcs_address != 0xffffffff) ?
dev->phy.gpcs_address : dev->phy.address);
/* Put some arbitrary OUI, Manuf & Rev IDs so we can
* identify this GPCS PHY later.
*/
out_be32(&p->u1.emac4.ipcr, 0xdeadbeef);
} else
mr1 |= EMAC_MR1_MF_1000;
/* Extended fifo sizes */
tx_size = dev->tx_fifo_size_gige;
rx_size = dev->rx_fifo_size_gige;
if (dev->ndev->mtu > ETH_DATA_LEN) {
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
mr1 |= EMAC4_MR1_JPSM;
else
mr1 |= EMAC_MR1_JPSM;
dev->stop_timeout = STOP_TIMEOUT_1000_JUMBO;
} else
dev->stop_timeout = STOP_TIMEOUT_1000;
break;
case SPEED_100:
mr1 |= EMAC_MR1_MF_100;
dev->stop_timeout = STOP_TIMEOUT_100;
break;
default: /* make gcc happy */
break;
}
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
rgmii_set_speed(dev->rgmii_dev, dev->rgmii_port,
dev->phy.speed);
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
zmii_set_speed(dev->zmii_dev, dev->zmii_port, dev->phy.speed);
/* on 40x erratum forces us to NOT use integrated flow control,
* let's hope it works on 44x ;)
*/
if (!emac_has_feature(dev, EMAC_FTR_NO_FLOW_CONTROL_40x) &&
dev->phy.duplex == DUPLEX_FULL) {
if (dev->phy.pause)
mr1 |= EMAC_MR1_EIFC | EMAC_MR1_APP;
else if (dev->phy.asym_pause)
mr1 |= EMAC_MR1_APP;
}
/* Add base settings & fifo sizes & program MR1 */
mr1 |= emac_calc_base_mr1(dev, tx_size, rx_size);
out_be32(&p->mr1, mr1);
/* Set individual MAC address */
out_be32(&p->iahr, (ndev->dev_addr[0] << 8) | ndev->dev_addr[1]);
out_be32(&p->ialr, (ndev->dev_addr[2] << 24) |
(ndev->dev_addr[3] << 16) | (ndev->dev_addr[4] << 8) |
ndev->dev_addr[5]);
/* VLAN Tag Protocol ID */
out_be32(&p->vtpid, 0x8100);
/* Receive mode register */
r = emac_iff2rmr(ndev);
if (r & EMAC_RMR_MAE)
emac_hash_mc(dev);
out_be32(&p->rmr, r);
/* FIFOs thresholds */
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
r = EMAC4_TMR1((dev->mal_burst_size / dev->fifo_entry_size) + 1,
tx_size / 2 / dev->fifo_entry_size);
else
r = EMAC_TMR1((dev->mal_burst_size / dev->fifo_entry_size) + 1,
tx_size / 2 / dev->fifo_entry_size);
out_be32(&p->tmr1, r);
out_be32(&p->trtr, emac_calc_trtr(dev, tx_size / 2));
/* PAUSE frame is sent when RX FIFO reaches its high-water mark,
there should be still enough space in FIFO to allow the our link
partner time to process this frame and also time to send PAUSE
frame itself.
Here is the worst case scenario for the RX FIFO "headroom"
(from "The Switch Book") (100Mbps, without preamble, inter-frame gap):
1) One maximum-length frame on TX 1522 bytes
2) One PAUSE frame time 64 bytes
3) PAUSE frame decode time allowance 64 bytes
4) One maximum-length frame on RX 1522 bytes
5) Round-trip propagation delay of the link (100Mb) 15 bytes
----------
3187 bytes
I chose to set high-water mark to RX_FIFO_SIZE / 4 (1024 bytes)
low-water mark to RX_FIFO_SIZE / 8 (512 bytes)
*/
r = emac_calc_rwmr(dev, rx_size / 8 / dev->fifo_entry_size,
rx_size / 4 / dev->fifo_entry_size);
out_be32(&p->rwmr, r);
/* Set PAUSE timer to the maximum */
out_be32(&p->ptr, 0xffff);
/* IRQ sources */
r = EMAC_ISR_OVR | EMAC_ISR_BP | EMAC_ISR_SE |
EMAC_ISR_ALE | EMAC_ISR_BFCS | EMAC_ISR_PTLE | EMAC_ISR_ORE |
EMAC_ISR_IRE | EMAC_ISR_TE;
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
r |= EMAC4_ISR_TXPE | EMAC4_ISR_RXPE /* | EMAC4_ISR_TXUE |
EMAC4_ISR_RXOE | */;
out_be32(&p->iser, r);
/* We need to take GPCS PHY out of isolate mode after EMAC reset */
if (emac_phy_gpcs(dev->phy.mode)) {
if (dev->phy.gpcs_address != 0xffffffff)
emac_mii_reset_gpcs(&dev->phy);
else
emac_mii_reset_phy(&dev->phy);
}
return 0;
}
static void emac_reinitialize(struct emac_instance *dev)
{
DBG(dev, "reinitialize" NL);
emac_netif_stop(dev);
if (!emac_configure(dev)) {
emac_tx_enable(dev);
emac_rx_enable(dev);
}
emac_netif_start(dev);
}
static void emac_full_tx_reset(struct emac_instance *dev)
{
DBG(dev, "full_tx_reset" NL);
emac_tx_disable(dev);
mal_disable_tx_channel(dev->mal, dev->mal_tx_chan);
emac_clean_tx_ring(dev);
dev->tx_cnt = dev->tx_slot = dev->ack_slot = 0;
emac_configure(dev);
mal_enable_tx_channel(dev->mal, dev->mal_tx_chan);
emac_tx_enable(dev);
emac_rx_enable(dev);
}
static void emac_reset_work(struct work_struct *work)
{
struct emac_instance *dev = container_of(work, struct emac_instance, reset_work);
DBG(dev, "reset_work" NL);
mutex_lock(&dev->link_lock);
if (dev->opened) {
emac_netif_stop(dev);
emac_full_tx_reset(dev);
emac_netif_start(dev);
}
mutex_unlock(&dev->link_lock);
}
static void emac_tx_timeout(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
DBG(dev, "tx_timeout" NL);
schedule_work(&dev->reset_work);
}
static inline int emac_phy_done(struct emac_instance *dev, u32 stacr)
{
int done = !!(stacr & EMAC_STACR_OC);
if (emac_has_feature(dev, EMAC_FTR_STACR_OC_INVERT))
done = !done;
return done;
};
static int __emac_mdio_read(struct emac_instance *dev, u8 id, u8 reg)
{
struct emac_regs __iomem *p = dev->emacp;
u32 r = 0;
int n, err = -ETIMEDOUT;
mutex_lock(&dev->mdio_lock);
DBG2(dev, "mdio_read(%02x,%02x)" NL, id, reg);
/* Enable proper MDIO port */
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
zmii_get_mdio(dev->zmii_dev, dev->zmii_port);
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
rgmii_get_mdio(dev->rgmii_dev, dev->rgmii_port);
/* Wait for management interface to become idle */
n = 20;
while (!emac_phy_done(dev, in_be32(&p->stacr))) {
udelay(1);
if (!--n) {
DBG2(dev, " -> timeout wait idle\n");
goto bail;
}
}
/* Issue read command */
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
r = EMAC4_STACR_BASE(dev->opb_bus_freq);
else
r = EMAC_STACR_BASE(dev->opb_bus_freq);
if (emac_has_feature(dev, EMAC_FTR_STACR_OC_INVERT))
r |= EMAC_STACR_OC;
if (emac_has_feature(dev, EMAC_FTR_HAS_NEW_STACR))
r |= EMACX_STACR_STAC_READ;
else
r |= EMAC_STACR_STAC_READ;
r |= (reg & EMAC_STACR_PRA_MASK)
| ((id & EMAC_STACR_PCDA_MASK) << EMAC_STACR_PCDA_SHIFT);
out_be32(&p->stacr, r);
/* Wait for read to complete */
n = 200;
while (!emac_phy_done(dev, (r = in_be32(&p->stacr)))) {
udelay(1);
if (!--n) {
DBG2(dev, " -> timeout wait complete\n");
goto bail;
}
}
if (unlikely(r & EMAC_STACR_PHYE)) {
DBG(dev, "mdio_read(%02x, %02x) failed" NL, id, reg);
err = -EREMOTEIO;
goto bail;
}
r = ((r >> EMAC_STACR_PHYD_SHIFT) & EMAC_STACR_PHYD_MASK);
DBG2(dev, "mdio_read -> %04x" NL, r);
err = 0;
bail:
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
rgmii_put_mdio(dev->rgmii_dev, dev->rgmii_port);
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
zmii_put_mdio(dev->zmii_dev, dev->zmii_port);
mutex_unlock(&dev->mdio_lock);
return err == 0 ? r : err;
}
static void __emac_mdio_write(struct emac_instance *dev, u8 id, u8 reg,
u16 val)
{
struct emac_regs __iomem *p = dev->emacp;
u32 r = 0;
int n, err = -ETIMEDOUT;
mutex_lock(&dev->mdio_lock);
DBG2(dev, "mdio_write(%02x,%02x,%04x)" NL, id, reg, val);
/* Enable proper MDIO port */
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
zmii_get_mdio(dev->zmii_dev, dev->zmii_port);
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
rgmii_get_mdio(dev->rgmii_dev, dev->rgmii_port);
/* Wait for management interface to be idle */
n = 20;
while (!emac_phy_done(dev, in_be32(&p->stacr))) {
udelay(1);
if (!--n) {
DBG2(dev, " -> timeout wait idle\n");
goto bail;
}
}
/* Issue write command */
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
r = EMAC4_STACR_BASE(dev->opb_bus_freq);
else
r = EMAC_STACR_BASE(dev->opb_bus_freq);
if (emac_has_feature(dev, EMAC_FTR_STACR_OC_INVERT))
r |= EMAC_STACR_OC;
if (emac_has_feature(dev, EMAC_FTR_HAS_NEW_STACR))
r |= EMACX_STACR_STAC_WRITE;
else
r |= EMAC_STACR_STAC_WRITE;
r |= (reg & EMAC_STACR_PRA_MASK) |
((id & EMAC_STACR_PCDA_MASK) << EMAC_STACR_PCDA_SHIFT) |
(val << EMAC_STACR_PHYD_SHIFT);
out_be32(&p->stacr, r);
/* Wait for write to complete */
n = 200;
while (!emac_phy_done(dev, in_be32(&p->stacr))) {
udelay(1);
if (!--n) {
DBG2(dev, " -> timeout wait complete\n");
goto bail;
}
}
err = 0;
bail:
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
rgmii_put_mdio(dev->rgmii_dev, dev->rgmii_port);
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
zmii_put_mdio(dev->zmii_dev, dev->zmii_port);
mutex_unlock(&dev->mdio_lock);
}
static int emac_mdio_read(struct net_device *ndev, int id, int reg)
{
struct emac_instance *dev = netdev_priv(ndev);
int res;
res = __emac_mdio_read((dev->mdio_instance &&
dev->phy.gpcs_address != id) ?
dev->mdio_instance : dev,
(u8) id, (u8) reg);
return res;
}
static void emac_mdio_write(struct net_device *ndev, int id, int reg, int val)
{
struct emac_instance *dev = netdev_priv(ndev);
__emac_mdio_write((dev->mdio_instance &&
dev->phy.gpcs_address != id) ?
dev->mdio_instance : dev,
(u8) id, (u8) reg, (u16) val);
}
/* Tx lock BH */
static void __emac_set_multicast_list(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
u32 rmr = emac_iff2rmr(dev->ndev);
DBG(dev, "__multicast %08x" NL, rmr);
/* I decided to relax register access rules here to avoid
* full EMAC reset.
*
* There is a real problem with EMAC4 core if we use MWSW_001 bit
* in MR1 register and do a full EMAC reset.
* One TX BD status update is delayed and, after EMAC reset, it
* never happens, resulting in TX hung (it'll be recovered by TX
* timeout handler eventually, but this is just gross).
* So we either have to do full TX reset or try to cheat here :)
*
* The only required change is to RX mode register, so I *think* all
* we need is just to stop RX channel. This seems to work on all
* tested SoCs. --ebs
*
* If we need the full reset, we might just trigger the workqueue
* and do it async... a bit nasty but should work --BenH
*/
dev->mcast_pending = 0;
emac_rx_disable(dev);
if (rmr & EMAC_RMR_MAE)
emac_hash_mc(dev);
out_be32(&p->rmr, rmr);
emac_rx_enable(dev);
}
/* Tx lock BH */
static void emac_set_multicast_list(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
DBG(dev, "multicast" NL);
BUG_ON(!netif_running(dev->ndev));
if (dev->no_mcast) {
dev->mcast_pending = 1;
return;
}
__emac_set_multicast_list(dev);
}
static int emac_resize_rx_ring(struct emac_instance *dev, int new_mtu)
{
int rx_sync_size = emac_rx_sync_size(new_mtu);
int rx_skb_size = emac_rx_skb_size(new_mtu);
int i, ret = 0;
mutex_lock(&dev->link_lock);
emac_netif_stop(dev);
emac_rx_disable(dev);
mal_disable_rx_channel(dev->mal, dev->mal_rx_chan);
if (dev->rx_sg_skb) {
++dev->estats.rx_dropped_resize;
dev_kfree_skb(dev->rx_sg_skb);
dev->rx_sg_skb = NULL;
}
/* Make a first pass over RX ring and mark BDs ready, dropping
* non-processed packets on the way. We need this as a separate pass
* to simplify error recovery in the case of allocation failure later.
*/
for (i = 0; i < NUM_RX_BUFF; ++i) {
if (dev->rx_desc[i].ctrl & MAL_RX_CTRL_FIRST)
++dev->estats.rx_dropped_resize;
dev->rx_desc[i].data_len = 0;
dev->rx_desc[i].ctrl = MAL_RX_CTRL_EMPTY |
(i == (NUM_RX_BUFF - 1) ? MAL_RX_CTRL_WRAP : 0);
}
/* Reallocate RX ring only if bigger skb buffers are required */
if (rx_skb_size <= dev->rx_skb_size)
goto skip;
/* Second pass, allocate new skbs */
for (i = 0; i < NUM_RX_BUFF; ++i) {
struct sk_buff *skb = alloc_skb(rx_skb_size, GFP_ATOMIC);
if (!skb) {
ret = -ENOMEM;
goto oom;
}
BUG_ON(!dev->rx_skb[i]);
dev_kfree_skb(dev->rx_skb[i]);
skb_reserve(skb, EMAC_RX_SKB_HEADROOM + 2);
dev->rx_desc[i].data_ptr =
dma_map_single(&dev->ofdev->dev, skb->data - 2, rx_sync_size,
DMA_FROM_DEVICE) + 2;
dev->rx_skb[i] = skb;
}
skip:
/* Check if we need to change "Jumbo" bit in MR1 */
if ((new_mtu > ETH_DATA_LEN) ^ (dev->ndev->mtu > ETH_DATA_LEN)) {
/* This is to prevent starting RX channel in emac_rx_enable() */
set_bit(MAL_COMMAC_RX_STOPPED, &dev->commac.flags);
dev->ndev->mtu = new_mtu;
emac_full_tx_reset(dev);
}
mal_set_rcbs(dev->mal, dev->mal_rx_chan, emac_rx_size(new_mtu));
oom:
/* Restart RX */
clear_bit(MAL_COMMAC_RX_STOPPED, &dev->commac.flags);
dev->rx_slot = 0;
mal_enable_rx_channel(dev->mal, dev->mal_rx_chan);
emac_rx_enable(dev);
emac_netif_start(dev);
mutex_unlock(&dev->link_lock);
return ret;
}
/* Process ctx, rtnl_lock semaphore */
static int emac_change_mtu(struct net_device *ndev, int new_mtu)
{
struct emac_instance *dev = netdev_priv(ndev);
int ret = 0;
if (new_mtu < EMAC_MIN_MTU || new_mtu > dev->max_mtu)
return -EINVAL;
DBG(dev, "change_mtu(%d)" NL, new_mtu);
if (netif_running(ndev)) {
/* Check if we really need to reinitialize RX ring */
if (emac_rx_skb_size(ndev->mtu) != emac_rx_skb_size(new_mtu))
ret = emac_resize_rx_ring(dev, new_mtu);
}
if (!ret) {
ndev->mtu = new_mtu;
dev->rx_skb_size = emac_rx_skb_size(new_mtu);
dev->rx_sync_size = emac_rx_sync_size(new_mtu);
}
return ret;
}
static void emac_clean_tx_ring(struct emac_instance *dev)
{
int i;
for (i = 0; i < NUM_TX_BUFF; ++i) {
if (dev->tx_skb[i]) {
dev_kfree_skb(dev->tx_skb[i]);
dev->tx_skb[i] = NULL;
if (dev->tx_desc[i].ctrl & MAL_TX_CTRL_READY)
++dev->estats.tx_dropped;
}
dev->tx_desc[i].ctrl = 0;
dev->tx_desc[i].data_ptr = 0;
}
}
static void emac_clean_rx_ring(struct emac_instance *dev)
{
int i;
for (i = 0; i < NUM_RX_BUFF; ++i)
if (dev->rx_skb[i]) {
dev->rx_desc[i].ctrl = 0;
dev_kfree_skb(dev->rx_skb[i]);
dev->rx_skb[i] = NULL;
dev->rx_desc[i].data_ptr = 0;
}
if (dev->rx_sg_skb) {
dev_kfree_skb(dev->rx_sg_skb);
dev->rx_sg_skb = NULL;
}
}
static inline int emac_alloc_rx_skb(struct emac_instance *dev, int slot,
gfp_t flags)
{
struct sk_buff *skb = alloc_skb(dev->rx_skb_size, flags);
if (unlikely(!skb))
return -ENOMEM;
dev->rx_skb[slot] = skb;
dev->rx_desc[slot].data_len = 0;
skb_reserve(skb, EMAC_RX_SKB_HEADROOM + 2);
dev->rx_desc[slot].data_ptr =
dma_map_single(&dev->ofdev->dev, skb->data - 2, dev->rx_sync_size,
DMA_FROM_DEVICE) + 2;
wmb();
dev->rx_desc[slot].ctrl = MAL_RX_CTRL_EMPTY |
(slot == (NUM_RX_BUFF - 1) ? MAL_RX_CTRL_WRAP : 0);
return 0;
}
static void emac_print_link_status(struct emac_instance *dev)
{
if (netif_carrier_ok(dev->ndev))
printk(KERN_INFO "%s: link is up, %d %s%s\n",
dev->ndev->name, dev->phy.speed,
dev->phy.duplex == DUPLEX_FULL ? "FDX" : "HDX",
dev->phy.pause ? ", pause enabled" :
dev->phy.asym_pause ? ", asymmetric pause enabled" : "");
else
printk(KERN_INFO "%s: link is down\n", dev->ndev->name);
}
/* Process ctx, rtnl_lock semaphore */
static int emac_open(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
int err, i;
DBG(dev, "open" NL);
/* Setup error IRQ handler */
err = request_irq(dev->emac_irq, emac_irq, 0, "EMAC", dev);
if (err) {
printk(KERN_ERR "%s: failed to request IRQ %d\n",
ndev->name, dev->emac_irq);
return err;
}
/* Allocate RX ring */
for (i = 0; i < NUM_RX_BUFF; ++i)
if (emac_alloc_rx_skb(dev, i, GFP_KERNEL)) {
printk(KERN_ERR "%s: failed to allocate RX ring\n",
ndev->name);
goto oom;
}
dev->tx_cnt = dev->tx_slot = dev->ack_slot = dev->rx_slot = 0;
clear_bit(MAL_COMMAC_RX_STOPPED, &dev->commac.flags);
dev->rx_sg_skb = NULL;
mutex_lock(&dev->link_lock);
dev->opened = 1;
/* Start PHY polling now.
*/
if (dev->phy.address >= 0) {
int link_poll_interval;
if (dev->phy.def->ops->poll_link(&dev->phy)) {
dev->phy.def->ops->read_link(&dev->phy);
emac_rx_clk_default(dev);
netif_carrier_on(dev->ndev);
link_poll_interval = PHY_POLL_LINK_ON;
} else {
emac_rx_clk_tx(dev);
netif_carrier_off(dev->ndev);
link_poll_interval = PHY_POLL_LINK_OFF;
}
dev->link_polling = 1;
wmb();
schedule_delayed_work(&dev->link_work, link_poll_interval);
emac_print_link_status(dev);
} else
netif_carrier_on(dev->ndev);
/* Required for Pause packet support in EMAC */
dev_mc_add_global(ndev, default_mcast_addr);
emac_configure(dev);
mal_poll_add(dev->mal, &dev->commac);
mal_enable_tx_channel(dev->mal, dev->mal_tx_chan);
mal_set_rcbs(dev->mal, dev->mal_rx_chan, emac_rx_size(ndev->mtu));
mal_enable_rx_channel(dev->mal, dev->mal_rx_chan);
emac_tx_enable(dev);
emac_rx_enable(dev);
emac_netif_start(dev);
mutex_unlock(&dev->link_lock);
return 0;
oom:
emac_clean_rx_ring(dev);
free_irq(dev->emac_irq, dev);
return -ENOMEM;
}
/* BHs disabled */
#if 0
static int emac_link_differs(struct emac_instance *dev)
{
u32 r = in_be32(&dev->emacp->mr1);
int duplex = r & EMAC_MR1_FDE ? DUPLEX_FULL : DUPLEX_HALF;
int speed, pause, asym_pause;
if (r & EMAC_MR1_MF_1000)
speed = SPEED_1000;
else if (r & EMAC_MR1_MF_100)
speed = SPEED_100;
else
speed = SPEED_10;
switch (r & (EMAC_MR1_EIFC | EMAC_MR1_APP)) {
case (EMAC_MR1_EIFC | EMAC_MR1_APP):
pause = 1;
asym_pause = 0;
break;
case EMAC_MR1_APP:
pause = 0;
asym_pause = 1;
break;
default:
pause = asym_pause = 0;
}
return speed != dev->phy.speed || duplex != dev->phy.duplex ||
pause != dev->phy.pause || asym_pause != dev->phy.asym_pause;
}
#endif
static void emac_link_timer(struct work_struct *work)
{
struct emac_instance *dev =
container_of(to_delayed_work(work),
struct emac_instance, link_work);
int link_poll_interval;
mutex_lock(&dev->link_lock);
DBG2(dev, "link timer" NL);
if (!dev->opened)
goto bail;
if (dev->phy.def->ops->poll_link(&dev->phy)) {
if (!netif_carrier_ok(dev->ndev)) {
emac_rx_clk_default(dev);
/* Get new link parameters */
dev->phy.def->ops->read_link(&dev->phy);
netif_carrier_on(dev->ndev);
emac_netif_stop(dev);
emac_full_tx_reset(dev);
emac_netif_start(dev);
emac_print_link_status(dev);
}
link_poll_interval = PHY_POLL_LINK_ON;
} else {
if (netif_carrier_ok(dev->ndev)) {
emac_rx_clk_tx(dev);
netif_carrier_off(dev->ndev);
netif_tx_disable(dev->ndev);
emac_reinitialize(dev);
emac_print_link_status(dev);
}
link_poll_interval = PHY_POLL_LINK_OFF;
}
schedule_delayed_work(&dev->link_work, link_poll_interval);
bail:
mutex_unlock(&dev->link_lock);
}
static void emac_force_link_update(struct emac_instance *dev)
{
netif_carrier_off(dev->ndev);
smp_rmb();
if (dev->link_polling) {
cancel_delayed_work_sync(&dev->link_work);
if (dev->link_polling)
schedule_delayed_work(&dev->link_work, PHY_POLL_LINK_OFF);
}
}
/* Process ctx, rtnl_lock semaphore */
static int emac_close(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
DBG(dev, "close" NL);
if (dev->phy.address >= 0) {
dev->link_polling = 0;
cancel_delayed_work_sync(&dev->link_work);
}
mutex_lock(&dev->link_lock);
emac_netif_stop(dev);
dev->opened = 0;
mutex_unlock(&dev->link_lock);
emac_rx_disable(dev);
emac_tx_disable(dev);
mal_disable_rx_channel(dev->mal, dev->mal_rx_chan);
mal_disable_tx_channel(dev->mal, dev->mal_tx_chan);
mal_poll_del(dev->mal, &dev->commac);
emac_clean_tx_ring(dev);
emac_clean_rx_ring(dev);
free_irq(dev->emac_irq, dev);
netif_carrier_off(ndev);
return 0;
}
static inline u16 emac_tx_csum(struct emac_instance *dev,
struct sk_buff *skb)
{
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH) &&
(skb->ip_summed == CHECKSUM_PARTIAL)) {
++dev->stats.tx_packets_csum;
return EMAC_TX_CTRL_TAH_CSUM;
}
return 0;
}
static inline int emac_xmit_finish(struct emac_instance *dev, int len)
{
struct emac_regs __iomem *p = dev->emacp;
struct net_device *ndev = dev->ndev;
/* Send the packet out. If the if makes a significant perf
* difference, then we can store the TMR0 value in "dev"
* instead
*/
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
out_be32(&p->tmr0, EMAC4_TMR0_XMIT);
else
out_be32(&p->tmr0, EMAC_TMR0_XMIT);
if (unlikely(++dev->tx_cnt == NUM_TX_BUFF)) {
netif_stop_queue(ndev);
DBG2(dev, "stopped TX queue" NL);
}
ndev->trans_start = jiffies;
++dev->stats.tx_packets;
dev->stats.tx_bytes += len;
return NETDEV_TX_OK;
}
/* Tx lock BH */
static int emac_start_xmit(struct sk_buff *skb, struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
unsigned int len = skb->len;
int slot;
u16 ctrl = EMAC_TX_CTRL_GFCS | EMAC_TX_CTRL_GP | MAL_TX_CTRL_READY |
MAL_TX_CTRL_LAST | emac_tx_csum(dev, skb);
slot = dev->tx_slot++;
if (dev->tx_slot == NUM_TX_BUFF) {
dev->tx_slot = 0;
ctrl |= MAL_TX_CTRL_WRAP;
}
DBG2(dev, "xmit(%u) %d" NL, len, slot);
dev->tx_skb[slot] = skb;
dev->tx_desc[slot].data_ptr = dma_map_single(&dev->ofdev->dev,
skb->data, len,
DMA_TO_DEVICE);
dev->tx_desc[slot].data_len = (u16) len;
wmb();
dev->tx_desc[slot].ctrl = ctrl;
return emac_xmit_finish(dev, len);
}
static inline int emac_xmit_split(struct emac_instance *dev, int slot,
u32 pd, int len, int last, u16 base_ctrl)
{
while (1) {
u16 ctrl = base_ctrl;
int chunk = min(len, MAL_MAX_TX_SIZE);
len -= chunk;
slot = (slot + 1) % NUM_TX_BUFF;
if (last && !len)
ctrl |= MAL_TX_CTRL_LAST;
if (slot == NUM_TX_BUFF - 1)
ctrl |= MAL_TX_CTRL_WRAP;
dev->tx_skb[slot] = NULL;
dev->tx_desc[slot].data_ptr = pd;
dev->tx_desc[slot].data_len = (u16) chunk;
dev->tx_desc[slot].ctrl = ctrl;
++dev->tx_cnt;
if (!len)
break;
pd += chunk;
}
return slot;
}
/* Tx lock BH disabled (SG version for TAH equipped EMACs) */
static int emac_start_xmit_sg(struct sk_buff *skb, struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
int nr_frags = skb_shinfo(skb)->nr_frags;
int len = skb->len, chunk;
int slot, i;
u16 ctrl;
u32 pd;
/* This is common "fast" path */
if (likely(!nr_frags && len <= MAL_MAX_TX_SIZE))
return emac_start_xmit(skb, ndev);
len -= skb->data_len;
/* Note, this is only an *estimation*, we can still run out of empty
* slots because of the additional fragmentation into
* MAL_MAX_TX_SIZE-sized chunks
*/
if (unlikely(dev->tx_cnt + nr_frags + mal_tx_chunks(len) > NUM_TX_BUFF))
goto stop_queue;
ctrl = EMAC_TX_CTRL_GFCS | EMAC_TX_CTRL_GP | MAL_TX_CTRL_READY |
emac_tx_csum(dev, skb);
slot = dev->tx_slot;
/* skb data */
dev->tx_skb[slot] = NULL;
chunk = min(len, MAL_MAX_TX_SIZE);
dev->tx_desc[slot].data_ptr = pd =
dma_map_single(&dev->ofdev->dev, skb->data, len, DMA_TO_DEVICE);
dev->tx_desc[slot].data_len = (u16) chunk;
len -= chunk;
if (unlikely(len))
slot = emac_xmit_split(dev, slot, pd + chunk, len, !nr_frags,
ctrl);
/* skb fragments */
for (i = 0; i < nr_frags; ++i) {
struct skb_frag_struct *frag = &skb_shinfo(skb)->frags[i];
len = frag->size;
if (unlikely(dev->tx_cnt + mal_tx_chunks(len) >= NUM_TX_BUFF))
goto undo_frame;
pd = dma_map_page(&dev->ofdev->dev, frag->page, frag->page_offset, len,
DMA_TO_DEVICE);
slot = emac_xmit_split(dev, slot, pd, len, i == nr_frags - 1,
ctrl);
}
DBG2(dev, "xmit_sg(%u) %d - %d" NL, skb->len, dev->tx_slot, slot);
/* Attach skb to the last slot so we don't release it too early */
dev->tx_skb[slot] = skb;
/* Send the packet out */
if (dev->tx_slot == NUM_TX_BUFF - 1)
ctrl |= MAL_TX_CTRL_WRAP;
wmb();
dev->tx_desc[dev->tx_slot].ctrl = ctrl;
dev->tx_slot = (slot + 1) % NUM_TX_BUFF;
return emac_xmit_finish(dev, skb->len);
undo_frame:
/* Well, too bad. Our previous estimation was overly optimistic.
* Undo everything.
*/
while (slot != dev->tx_slot) {
dev->tx_desc[slot].ctrl = 0;
--dev->tx_cnt;
if (--slot < 0)
slot = NUM_TX_BUFF - 1;
}
++dev->estats.tx_undo;
stop_queue:
netif_stop_queue(ndev);
DBG2(dev, "stopped TX queue" NL);
return NETDEV_TX_BUSY;
}
/* Tx lock BHs */
static void emac_parse_tx_error(struct emac_instance *dev, u16 ctrl)
{
struct emac_error_stats *st = &dev->estats;
DBG(dev, "BD TX error %04x" NL, ctrl);
++st->tx_bd_errors;
if (ctrl & EMAC_TX_ST_BFCS)
++st->tx_bd_bad_fcs;
if (ctrl & EMAC_TX_ST_LCS)
++st->tx_bd_carrier_loss;
if (ctrl & EMAC_TX_ST_ED)
++st->tx_bd_excessive_deferral;
if (ctrl & EMAC_TX_ST_EC)
++st->tx_bd_excessive_collisions;
if (ctrl & EMAC_TX_ST_LC)
++st->tx_bd_late_collision;
if (ctrl & EMAC_TX_ST_MC)
++st->tx_bd_multple_collisions;
if (ctrl & EMAC_TX_ST_SC)
++st->tx_bd_single_collision;
if (ctrl & EMAC_TX_ST_UR)
++st->tx_bd_underrun;
if (ctrl & EMAC_TX_ST_SQE)
++st->tx_bd_sqe;
}
static void emac_poll_tx(void *param)
{
struct emac_instance *dev = param;
u32 bad_mask;
DBG2(dev, "poll_tx, %d %d" NL, dev->tx_cnt, dev->ack_slot);
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH))
bad_mask = EMAC_IS_BAD_TX_TAH;
else
bad_mask = EMAC_IS_BAD_TX;
netif_tx_lock_bh(dev->ndev);
if (dev->tx_cnt) {
u16 ctrl;
int slot = dev->ack_slot, n = 0;
again:
ctrl = dev->tx_desc[slot].ctrl;
if (!(ctrl & MAL_TX_CTRL_READY)) {
struct sk_buff *skb = dev->tx_skb[slot];
++n;
if (skb) {
dev_kfree_skb(skb);
dev->tx_skb[slot] = NULL;
}
slot = (slot + 1) % NUM_TX_BUFF;
if (unlikely(ctrl & bad_mask))
emac_parse_tx_error(dev, ctrl);
if (--dev->tx_cnt)
goto again;
}
if (n) {
dev->ack_slot = slot;
if (netif_queue_stopped(dev->ndev) &&
dev->tx_cnt < EMAC_TX_WAKEUP_THRESH)
netif_wake_queue(dev->ndev);
DBG2(dev, "tx %d pkts" NL, n);
}
}
netif_tx_unlock_bh(dev->ndev);
}
static inline void emac_recycle_rx_skb(struct emac_instance *dev, int slot,
int len)
{
struct sk_buff *skb = dev->rx_skb[slot];
DBG2(dev, "recycle %d %d" NL, slot, len);
if (len)
dma_map_single(&dev->ofdev->dev, skb->data - 2,
EMAC_DMA_ALIGN(len + 2), DMA_FROM_DEVICE);
dev->rx_desc[slot].data_len = 0;
wmb();
dev->rx_desc[slot].ctrl = MAL_RX_CTRL_EMPTY |
(slot == (NUM_RX_BUFF - 1) ? MAL_RX_CTRL_WRAP : 0);
}
static void emac_parse_rx_error(struct emac_instance *dev, u16 ctrl)
{
struct emac_error_stats *st = &dev->estats;
DBG(dev, "BD RX error %04x" NL, ctrl);
++st->rx_bd_errors;
if (ctrl & EMAC_RX_ST_OE)
++st->rx_bd_overrun;
if (ctrl & EMAC_RX_ST_BP)
++st->rx_bd_bad_packet;
if (ctrl & EMAC_RX_ST_RP)
++st->rx_bd_runt_packet;
if (ctrl & EMAC_RX_ST_SE)
++st->rx_bd_short_event;
if (ctrl & EMAC_RX_ST_AE)
++st->rx_bd_alignment_error;
if (ctrl & EMAC_RX_ST_BFCS)
++st->rx_bd_bad_fcs;
if (ctrl & EMAC_RX_ST_PTL)
++st->rx_bd_packet_too_long;
if (ctrl & EMAC_RX_ST_ORE)
++st->rx_bd_out_of_range;
if (ctrl & EMAC_RX_ST_IRE)
++st->rx_bd_in_range;
}
static inline void emac_rx_csum(struct emac_instance *dev,
struct sk_buff *skb, u16 ctrl)
{
#ifdef CONFIG_IBM_NEW_EMAC_TAH
if (!ctrl && dev->tah_dev) {
skb->ip_summed = CHECKSUM_UNNECESSARY;
++dev->stats.rx_packets_csum;
}
#endif
}
static inline int emac_rx_sg_append(struct emac_instance *dev, int slot)
{
if (likely(dev->rx_sg_skb != NULL)) {
int len = dev->rx_desc[slot].data_len;
int tot_len = dev->rx_sg_skb->len + len;
if (unlikely(tot_len + 2 > dev->rx_skb_size)) {
++dev->estats.rx_dropped_mtu;
dev_kfree_skb(dev->rx_sg_skb);
dev->rx_sg_skb = NULL;
} else {
cacheable_memcpy(skb_tail_pointer(dev->rx_sg_skb),
dev->rx_skb[slot]->data, len);
skb_put(dev->rx_sg_skb, len);
emac_recycle_rx_skb(dev, slot, len);
return 0;
}
}
emac_recycle_rx_skb(dev, slot, 0);
return -1;
}
/* NAPI poll context */
static int emac_poll_rx(void *param, int budget)
{
struct emac_instance *dev = param;
int slot = dev->rx_slot, received = 0;
DBG2(dev, "poll_rx(%d)" NL, budget);
again:
while (budget > 0) {
int len;
struct sk_buff *skb;
u16 ctrl = dev->rx_desc[slot].ctrl;
if (ctrl & MAL_RX_CTRL_EMPTY)
break;
skb = dev->rx_skb[slot];
mb();
len = dev->rx_desc[slot].data_len;
if (unlikely(!MAL_IS_SINGLE_RX(ctrl)))
goto sg;
ctrl &= EMAC_BAD_RX_MASK;
if (unlikely(ctrl && ctrl != EMAC_RX_TAH_BAD_CSUM)) {
emac_parse_rx_error(dev, ctrl);
++dev->estats.rx_dropped_error;
emac_recycle_rx_skb(dev, slot, 0);
len = 0;
goto next;
}
if (len < ETH_HLEN) {
++dev->estats.rx_dropped_stack;
emac_recycle_rx_skb(dev, slot, len);
goto next;
}
if (len && len < EMAC_RX_COPY_THRESH) {
struct sk_buff *copy_skb =
alloc_skb(len + EMAC_RX_SKB_HEADROOM + 2, GFP_ATOMIC);
if (unlikely(!copy_skb))
goto oom;
skb_reserve(copy_skb, EMAC_RX_SKB_HEADROOM + 2);
cacheable_memcpy(copy_skb->data - 2, skb->data - 2,
len + 2);
emac_recycle_rx_skb(dev, slot, len);
skb = copy_skb;
} else if (unlikely(emac_alloc_rx_skb(dev, slot, GFP_ATOMIC)))
goto oom;
skb_put(skb, len);
push_packet:
skb->protocol = eth_type_trans(skb, dev->ndev);
emac_rx_csum(dev, skb, ctrl);
if (unlikely(netif_receive_skb(skb) == NET_RX_DROP))
++dev->estats.rx_dropped_stack;
next:
++dev->stats.rx_packets;
skip:
dev->stats.rx_bytes += len;
slot = (slot + 1) % NUM_RX_BUFF;
--budget;
++received;
continue;
sg:
if (ctrl & MAL_RX_CTRL_FIRST) {
BUG_ON(dev->rx_sg_skb);
if (unlikely(emac_alloc_rx_skb(dev, slot, GFP_ATOMIC))) {
DBG(dev, "rx OOM %d" NL, slot);
++dev->estats.rx_dropped_oom;
emac_recycle_rx_skb(dev, slot, 0);
} else {
dev->rx_sg_skb = skb;
skb_put(skb, len);
}
} else if (!emac_rx_sg_append(dev, slot) &&
(ctrl & MAL_RX_CTRL_LAST)) {
skb = dev->rx_sg_skb;
dev->rx_sg_skb = NULL;
ctrl &= EMAC_BAD_RX_MASK;
if (unlikely(ctrl && ctrl != EMAC_RX_TAH_BAD_CSUM)) {
emac_parse_rx_error(dev, ctrl);
++dev->estats.rx_dropped_error;
dev_kfree_skb(skb);
len = 0;
} else
goto push_packet;
}
goto skip;
oom:
DBG(dev, "rx OOM %d" NL, slot);
/* Drop the packet and recycle skb */
++dev->estats.rx_dropped_oom;
emac_recycle_rx_skb(dev, slot, 0);
goto next;
}
if (received) {
DBG2(dev, "rx %d BDs" NL, received);
dev->rx_slot = slot;
}
if (unlikely(budget && test_bit(MAL_COMMAC_RX_STOPPED, &dev->commac.flags))) {
mb();
if (!(dev->rx_desc[slot].ctrl & MAL_RX_CTRL_EMPTY)) {
DBG2(dev, "rx restart" NL);
received = 0;
goto again;
}
if (dev->rx_sg_skb) {
DBG2(dev, "dropping partial rx packet" NL);
++dev->estats.rx_dropped_error;
dev_kfree_skb(dev->rx_sg_skb);
dev->rx_sg_skb = NULL;
}
clear_bit(MAL_COMMAC_RX_STOPPED, &dev->commac.flags);
mal_enable_rx_channel(dev->mal, dev->mal_rx_chan);
emac_rx_enable(dev);
dev->rx_slot = 0;
}
return received;
}
/* NAPI poll context */
static int emac_peek_rx(void *param)
{
struct emac_instance *dev = param;
return !(dev->rx_desc[dev->rx_slot].ctrl & MAL_RX_CTRL_EMPTY);
}
/* NAPI poll context */
static int emac_peek_rx_sg(void *param)
{
struct emac_instance *dev = param;
int slot = dev->rx_slot;
while (1) {
u16 ctrl = dev->rx_desc[slot].ctrl;
if (ctrl & MAL_RX_CTRL_EMPTY)
return 0;
else if (ctrl & MAL_RX_CTRL_LAST)
return 1;
slot = (slot + 1) % NUM_RX_BUFF;
/* I'm just being paranoid here :) */
if (unlikely(slot == dev->rx_slot))
return 0;
}
}
/* Hard IRQ */
static void emac_rxde(void *param)
{
struct emac_instance *dev = param;
++dev->estats.rx_stopped;
emac_rx_disable_async(dev);
}
/* Hard IRQ */
static irqreturn_t emac_irq(int irq, void *dev_instance)
{
struct emac_instance *dev = dev_instance;
struct emac_regs __iomem *p = dev->emacp;
struct emac_error_stats *st = &dev->estats;
u32 isr;
spin_lock(&dev->lock);
isr = in_be32(&p->isr);
out_be32(&p->isr, isr);
DBG(dev, "isr = %08x" NL, isr);
if (isr & EMAC4_ISR_TXPE)
++st->tx_parity;
if (isr & EMAC4_ISR_RXPE)
++st->rx_parity;
if (isr & EMAC4_ISR_TXUE)
++st->tx_underrun;
if (isr & EMAC4_ISR_RXOE)
++st->rx_fifo_overrun;
if (isr & EMAC_ISR_OVR)
++st->rx_overrun;
if (isr & EMAC_ISR_BP)
++st->rx_bad_packet;
if (isr & EMAC_ISR_RP)
++st->rx_runt_packet;
if (isr & EMAC_ISR_SE)
++st->rx_short_event;
if (isr & EMAC_ISR_ALE)
++st->rx_alignment_error;
if (isr & EMAC_ISR_BFCS)
++st->rx_bad_fcs;
if (isr & EMAC_ISR_PTLE)
++st->rx_packet_too_long;
if (isr & EMAC_ISR_ORE)
++st->rx_out_of_range;
if (isr & EMAC_ISR_IRE)
++st->rx_in_range;
if (isr & EMAC_ISR_SQE)
++st->tx_sqe;
if (isr & EMAC_ISR_TE)
++st->tx_errors;
spin_unlock(&dev->lock);
return IRQ_HANDLED;
}
static struct net_device_stats *emac_stats(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
struct emac_stats *st = &dev->stats;
struct emac_error_stats *est = &dev->estats;
struct net_device_stats *nst = &dev->nstats;
unsigned long flags;
DBG2(dev, "stats" NL);
/* Compute "legacy" statistics */
spin_lock_irqsave(&dev->lock, flags);
nst->rx_packets = (unsigned long)st->rx_packets;
nst->rx_bytes = (unsigned long)st->rx_bytes;
nst->tx_packets = (unsigned long)st->tx_packets;
nst->tx_bytes = (unsigned long)st->tx_bytes;
nst->rx_dropped = (unsigned long)(est->rx_dropped_oom +
est->rx_dropped_error +
est->rx_dropped_resize +
est->rx_dropped_mtu);
nst->tx_dropped = (unsigned long)est->tx_dropped;
nst->rx_errors = (unsigned long)est->rx_bd_errors;
nst->rx_fifo_errors = (unsigned long)(est->rx_bd_overrun +
est->rx_fifo_overrun +
est->rx_overrun);
nst->rx_frame_errors = (unsigned long)(est->rx_bd_alignment_error +
est->rx_alignment_error);
nst->rx_crc_errors = (unsigned long)(est->rx_bd_bad_fcs +
est->rx_bad_fcs);
nst->rx_length_errors = (unsigned long)(est->rx_bd_runt_packet +
est->rx_bd_short_event +
est->rx_bd_packet_too_long +
est->rx_bd_out_of_range +
est->rx_bd_in_range +
est->rx_runt_packet +
est->rx_short_event +
est->rx_packet_too_long +
est->rx_out_of_range +
est->rx_in_range);
nst->tx_errors = (unsigned long)(est->tx_bd_errors + est->tx_errors);
nst->tx_fifo_errors = (unsigned long)(est->tx_bd_underrun +
est->tx_underrun);
nst->tx_carrier_errors = (unsigned long)est->tx_bd_carrier_loss;
nst->collisions = (unsigned long)(est->tx_bd_excessive_deferral +
est->tx_bd_excessive_collisions +
est->tx_bd_late_collision +
est->tx_bd_multple_collisions);
spin_unlock_irqrestore(&dev->lock, flags);
return nst;
}
static struct mal_commac_ops emac_commac_ops = {
.poll_tx = &emac_poll_tx,
.poll_rx = &emac_poll_rx,
.peek_rx = &emac_peek_rx,
.rxde = &emac_rxde,
};
static struct mal_commac_ops emac_commac_sg_ops = {
.poll_tx = &emac_poll_tx,
.poll_rx = &emac_poll_rx,
.peek_rx = &emac_peek_rx_sg,
.rxde = &emac_rxde,
};
/* Ethtool support */
static int emac_ethtool_get_settings(struct net_device *ndev,
struct ethtool_cmd *cmd)
{
struct emac_instance *dev = netdev_priv(ndev);
cmd->supported = dev->phy.features;
cmd->port = PORT_MII;
cmd->phy_address = dev->phy.address;
cmd->transceiver =
dev->phy.address >= 0 ? XCVR_EXTERNAL : XCVR_INTERNAL;
mutex_lock(&dev->link_lock);
cmd->advertising = dev->phy.advertising;
cmd->autoneg = dev->phy.autoneg;
cmd->speed = dev->phy.speed;
cmd->duplex = dev->phy.duplex;
mutex_unlock(&dev->link_lock);
return 0;
}
static int emac_ethtool_set_settings(struct net_device *ndev,
struct ethtool_cmd *cmd)
{
struct emac_instance *dev = netdev_priv(ndev);
u32 f = dev->phy.features;
DBG(dev, "set_settings(%d, %d, %d, 0x%08x)" NL,
cmd->autoneg, cmd->speed, cmd->duplex, cmd->advertising);
/* Basic sanity checks */
if (dev->phy.address < 0)
return -EOPNOTSUPP;
if (cmd->autoneg != AUTONEG_ENABLE && cmd->autoneg != AUTONEG_DISABLE)
return -EINVAL;
if (cmd->autoneg == AUTONEG_ENABLE && cmd->advertising == 0)
return -EINVAL;
if (cmd->duplex != DUPLEX_HALF && cmd->duplex != DUPLEX_FULL)
return -EINVAL;
if (cmd->autoneg == AUTONEG_DISABLE) {
switch (cmd->speed) {
case SPEED_10:
if (cmd->duplex == DUPLEX_HALF &&
!(f & SUPPORTED_10baseT_Half))
return -EINVAL;
if (cmd->duplex == DUPLEX_FULL &&
!(f & SUPPORTED_10baseT_Full))
return -EINVAL;
break;
case SPEED_100:
if (cmd->duplex == DUPLEX_HALF &&
!(f & SUPPORTED_100baseT_Half))
return -EINVAL;
if (cmd->duplex == DUPLEX_FULL &&
!(f & SUPPORTED_100baseT_Full))
return -EINVAL;
break;
case SPEED_1000:
if (cmd->duplex == DUPLEX_HALF &&
!(f & SUPPORTED_1000baseT_Half))
return -EINVAL;
if (cmd->duplex == DUPLEX_FULL &&
!(f & SUPPORTED_1000baseT_Full))
return -EINVAL;
break;
default:
return -EINVAL;
}
mutex_lock(&dev->link_lock);
dev->phy.def->ops->setup_forced(&dev->phy, cmd->speed,
cmd->duplex);
mutex_unlock(&dev->link_lock);
} else {
if (!(f & SUPPORTED_Autoneg))
return -EINVAL;
mutex_lock(&dev->link_lock);
dev->phy.def->ops->setup_aneg(&dev->phy,
(cmd->advertising & f) |
(dev->phy.advertising &
(ADVERTISED_Pause |
ADVERTISED_Asym_Pause)));
mutex_unlock(&dev->link_lock);
}
emac_force_link_update(dev);
return 0;
}
static void emac_ethtool_get_ringparam(struct net_device *ndev,
struct ethtool_ringparam *rp)
{
rp->rx_max_pending = rp->rx_pending = NUM_RX_BUFF;
rp->tx_max_pending = rp->tx_pending = NUM_TX_BUFF;
}
static void emac_ethtool_get_pauseparam(struct net_device *ndev,
struct ethtool_pauseparam *pp)
{
struct emac_instance *dev = netdev_priv(ndev);
mutex_lock(&dev->link_lock);
if ((dev->phy.features & SUPPORTED_Autoneg) &&
(dev->phy.advertising & (ADVERTISED_Pause | ADVERTISED_Asym_Pause)))
pp->autoneg = 1;
if (dev->phy.duplex == DUPLEX_FULL) {
if (dev->phy.pause)
pp->rx_pause = pp->tx_pause = 1;
else if (dev->phy.asym_pause)
pp->tx_pause = 1;
}
mutex_unlock(&dev->link_lock);
}
static int emac_get_regs_len(struct emac_instance *dev)
{
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
return sizeof(struct emac_ethtool_regs_subhdr) +
EMAC4_ETHTOOL_REGS_SIZE(dev);
else
return sizeof(struct emac_ethtool_regs_subhdr) +
EMAC_ETHTOOL_REGS_SIZE(dev);
}
static int emac_ethtool_get_regs_len(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
int size;
size = sizeof(struct emac_ethtool_regs_hdr) +
emac_get_regs_len(dev) + mal_get_regs_len(dev->mal);
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
size += zmii_get_regs_len(dev->zmii_dev);
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
size += rgmii_get_regs_len(dev->rgmii_dev);
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH))
size += tah_get_regs_len(dev->tah_dev);
return size;
}
static void *emac_dump_regs(struct emac_instance *dev, void *buf)
{
struct emac_ethtool_regs_subhdr *hdr = buf;
hdr->index = dev->cell_index;
if (emac_has_feature(dev, EMAC_FTR_EMAC4)) {
hdr->version = EMAC4_ETHTOOL_REGS_VER;
memcpy_fromio(hdr + 1, dev->emacp, EMAC4_ETHTOOL_REGS_SIZE(dev));
return (void *)(hdr + 1) + EMAC4_ETHTOOL_REGS_SIZE(dev);
} else {
hdr->version = EMAC_ETHTOOL_REGS_VER;
memcpy_fromio(hdr + 1, dev->emacp, EMAC_ETHTOOL_REGS_SIZE(dev));
return (void *)(hdr + 1) + EMAC_ETHTOOL_REGS_SIZE(dev);
}
}
static void emac_ethtool_get_regs(struct net_device *ndev,
struct ethtool_regs *regs, void *buf)
{
struct emac_instance *dev = netdev_priv(ndev);
struct emac_ethtool_regs_hdr *hdr = buf;
hdr->components = 0;
buf = hdr + 1;
buf = mal_dump_regs(dev->mal, buf);
buf = emac_dump_regs(dev, buf);
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII)) {
hdr->components |= EMAC_ETHTOOL_REGS_ZMII;
buf = zmii_dump_regs(dev->zmii_dev, buf);
}
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII)) {
hdr->components |= EMAC_ETHTOOL_REGS_RGMII;
buf = rgmii_dump_regs(dev->rgmii_dev, buf);
}
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH)) {
hdr->components |= EMAC_ETHTOOL_REGS_TAH;
buf = tah_dump_regs(dev->tah_dev, buf);
}
}
static int emac_ethtool_nway_reset(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
int res = 0;
DBG(dev, "nway_reset" NL);
if (dev->phy.address < 0)
return -EOPNOTSUPP;
mutex_lock(&dev->link_lock);
if (!dev->phy.autoneg) {
res = -EINVAL;
goto out;
}
dev->phy.def->ops->setup_aneg(&dev->phy, dev->phy.advertising);
out:
mutex_unlock(&dev->link_lock);
emac_force_link_update(dev);
return res;
}
static int emac_ethtool_get_sset_count(struct net_device *ndev, int stringset)
{
if (stringset == ETH_SS_STATS)
return EMAC_ETHTOOL_STATS_COUNT;
else
return -EINVAL;
}
static void emac_ethtool_get_strings(struct net_device *ndev, u32 stringset,
u8 * buf)
{
if (stringset == ETH_SS_STATS)
memcpy(buf, &emac_stats_keys, sizeof(emac_stats_keys));
}
static void emac_ethtool_get_ethtool_stats(struct net_device *ndev,
struct ethtool_stats *estats,
u64 * tmp_stats)
{
struct emac_instance *dev = netdev_priv(ndev);
memcpy(tmp_stats, &dev->stats, sizeof(dev->stats));
tmp_stats += sizeof(dev->stats) / sizeof(u64);
memcpy(tmp_stats, &dev->estats, sizeof(dev->estats));
}
static void emac_ethtool_get_drvinfo(struct net_device *ndev,
struct ethtool_drvinfo *info)
{
struct emac_instance *dev = netdev_priv(ndev);
strcpy(info->driver, "ibm_emac");
strcpy(info->version, DRV_VERSION);
info->fw_version[0] = '\0';
sprintf(info->bus_info, "PPC 4xx EMAC-%d %s",
dev->cell_index, dev->ofdev->dev.of_node->full_name);
info->regdump_len = emac_ethtool_get_regs_len(ndev);
}
static const struct ethtool_ops emac_ethtool_ops = {
.get_settings = emac_ethtool_get_settings,
.set_settings = emac_ethtool_set_settings,
.get_drvinfo = emac_ethtool_get_drvinfo,
.get_regs_len = emac_ethtool_get_regs_len,
.get_regs = emac_ethtool_get_regs,
.nway_reset = emac_ethtool_nway_reset,
.get_ringparam = emac_ethtool_get_ringparam,
.get_pauseparam = emac_ethtool_get_pauseparam,
.get_strings = emac_ethtool_get_strings,
.get_sset_count = emac_ethtool_get_sset_count,
.get_ethtool_stats = emac_ethtool_get_ethtool_stats,
.get_link = ethtool_op_get_link,
};
static int emac_ioctl(struct net_device *ndev, struct ifreq *rq, int cmd)
{
struct emac_instance *dev = netdev_priv(ndev);
struct mii_ioctl_data *data = if_mii(rq);
DBG(dev, "ioctl %08x" NL, cmd);
if (dev->phy.address < 0)
return -EOPNOTSUPP;
switch (cmd) {
case SIOCGMIIPHY:
data->phy_id = dev->phy.address;
/* Fall through */
case SIOCGMIIREG:
data->val_out = emac_mdio_read(ndev, dev->phy.address,
data->reg_num);
return 0;
case SIOCSMIIREG:
emac_mdio_write(ndev, dev->phy.address, data->reg_num,
data->val_in);
return 0;
default:
return -EOPNOTSUPP;
}
}
struct emac_depentry {
u32 phandle;
struct device_node *node;
struct platform_device *ofdev;
void *drvdata;
};
#define EMAC_DEP_MAL_IDX 0
#define EMAC_DEP_ZMII_IDX 1
#define EMAC_DEP_RGMII_IDX 2
#define EMAC_DEP_TAH_IDX 3
#define EMAC_DEP_MDIO_IDX 4
#define EMAC_DEP_PREV_IDX 5
#define EMAC_DEP_COUNT 6
static int __devinit emac_check_deps(struct emac_instance *dev,
struct emac_depentry *deps)
{
int i, there = 0;
struct device_node *np;
for (i = 0; i < EMAC_DEP_COUNT; i++) {
/* no dependency on that item, allright */
if (deps[i].phandle == 0) {
there++;
continue;
}
/* special case for blist as the dependency might go away */
if (i == EMAC_DEP_PREV_IDX) {
np = *(dev->blist - 1);
if (np == NULL) {
deps[i].phandle = 0;
there++;
continue;
}
if (deps[i].node == NULL)
deps[i].node = of_node_get(np);
}
if (deps[i].node == NULL)
deps[i].node = of_find_node_by_phandle(deps[i].phandle);
if (deps[i].node == NULL)
continue;
if (deps[i].ofdev == NULL)
deps[i].ofdev = of_find_device_by_node(deps[i].node);
if (deps[i].ofdev == NULL)
continue;
if (deps[i].drvdata == NULL)
deps[i].drvdata = dev_get_drvdata(&deps[i].ofdev->dev);
if (deps[i].drvdata != NULL)
there++;
}
return there == EMAC_DEP_COUNT;
}
static void emac_put_deps(struct emac_instance *dev)
{
if (dev->mal_dev)
of_dev_put(dev->mal_dev);
if (dev->zmii_dev)
of_dev_put(dev->zmii_dev);
if (dev->rgmii_dev)
of_dev_put(dev->rgmii_dev);
if (dev->mdio_dev)
of_dev_put(dev->mdio_dev);
if (dev->tah_dev)
of_dev_put(dev->tah_dev);
}
static int __devinit emac_of_bus_notify(struct notifier_block *nb,
unsigned long action, void *data)
{
/* We are only intereted in device addition */
if (action == BUS_NOTIFY_BOUND_DRIVER)
wake_up_all(&emac_probe_wait);
return 0;
}
static struct notifier_block emac_of_bus_notifier __devinitdata = {
.notifier_call = emac_of_bus_notify
};
static int __devinit emac_wait_deps(struct emac_instance *dev)
{
struct emac_depentry deps[EMAC_DEP_COUNT];
int i, err;
memset(&deps, 0, sizeof(deps));
deps[EMAC_DEP_MAL_IDX].phandle = dev->mal_ph;
deps[EMAC_DEP_ZMII_IDX].phandle = dev->zmii_ph;
deps[EMAC_DEP_RGMII_IDX].phandle = dev->rgmii_ph;
if (dev->tah_ph)
deps[EMAC_DEP_TAH_IDX].phandle = dev->tah_ph;
if (dev->mdio_ph)
deps[EMAC_DEP_MDIO_IDX].phandle = dev->mdio_ph;
if (dev->blist && dev->blist > emac_boot_list)
deps[EMAC_DEP_PREV_IDX].phandle = 0xffffffffu;
bus_register_notifier(&platform_bus_type, &emac_of_bus_notifier);
wait_event_timeout(emac_probe_wait,
emac_check_deps(dev, deps),
EMAC_PROBE_DEP_TIMEOUT);
bus_unregister_notifier(&platform_bus_type, &emac_of_bus_notifier);
err = emac_check_deps(dev, deps) ? 0 : -ENODEV;
for (i = 0; i < EMAC_DEP_COUNT; i++) {
if (deps[i].node)
of_node_put(deps[i].node);
if (err && deps[i].ofdev)
of_dev_put(deps[i].ofdev);
}
if (err == 0) {
dev->mal_dev = deps[EMAC_DEP_MAL_IDX].ofdev;
dev->zmii_dev = deps[EMAC_DEP_ZMII_IDX].ofdev;
dev->rgmii_dev = deps[EMAC_DEP_RGMII_IDX].ofdev;
dev->tah_dev = deps[EMAC_DEP_TAH_IDX].ofdev;
dev->mdio_dev = deps[EMAC_DEP_MDIO_IDX].ofdev;
}
if (deps[EMAC_DEP_PREV_IDX].ofdev)
of_dev_put(deps[EMAC_DEP_PREV_IDX].ofdev);
return err;
}
static int __devinit emac_read_uint_prop(struct device_node *np, const char *name,
u32 *val, int fatal)
{
int len;
const u32 *prop = of_get_property(np, name, &len);
if (prop == NULL || len < sizeof(u32)) {
if (fatal)
printk(KERN_ERR "%s: missing %s property\n",
np->full_name, name);
return -ENODEV;
}
*val = *prop;
return 0;
}
static int __devinit emac_init_phy(struct emac_instance *dev)
{
struct device_node *np = dev->ofdev->dev.of_node;
struct net_device *ndev = dev->ndev;
u32 phy_map, adv;
int i;
dev->phy.dev = ndev;
dev->phy.mode = dev->phy_mode;
/* PHY-less configuration.
* XXX I probably should move these settings to the dev tree
*/
if (dev->phy_address == 0xffffffff && dev->phy_map == 0xffffffff) {
emac_reset(dev);
/* PHY-less configuration.
* XXX I probably should move these settings to the dev tree
*/
dev->phy.address = -1;
dev->phy.features = SUPPORTED_MII;
if (emac_phy_supports_gige(dev->phy_mode))
dev->phy.features |= SUPPORTED_1000baseT_Full;
else
dev->phy.features |= SUPPORTED_100baseT_Full;
dev->phy.pause = 1;
return 0;
}
mutex_lock(&emac_phy_map_lock);
phy_map = dev->phy_map | busy_phy_map;
DBG(dev, "PHY maps %08x %08x" NL, dev->phy_map, busy_phy_map);
dev->phy.mdio_read = emac_mdio_read;
dev->phy.mdio_write = emac_mdio_write;
/* Enable internal clock source */
#ifdef CONFIG_PPC_DCR_NATIVE
if (emac_has_feature(dev, EMAC_FTR_440GX_PHY_CLK_FIX))
dcri_clrset(SDR0, SDR0_MFR, 0, SDR0_MFR_ECS);
#endif
/* PHY clock workaround */
emac_rx_clk_tx(dev);
/* Enable internal clock source on 440GX*/
#ifdef CONFIG_PPC_DCR_NATIVE
if (emac_has_feature(dev, EMAC_FTR_440GX_PHY_CLK_FIX))
dcri_clrset(SDR0, SDR0_MFR, 0, SDR0_MFR_ECS);
#endif
/* Configure EMAC with defaults so we can at least use MDIO
* This is needed mostly for 440GX
*/
if (emac_phy_gpcs(dev->phy.mode)) {
/* XXX
* Make GPCS PHY address equal to EMAC index.
* We probably should take into account busy_phy_map
* and/or phy_map here.
*
* Note that the busy_phy_map is currently global
* while it should probably be per-ASIC...
*/
dev->phy.gpcs_address = dev->gpcs_address;
if (dev->phy.gpcs_address == 0xffffffff)
dev->phy.address = dev->cell_index;
}
emac_configure(dev);
if (dev->phy_address != 0xffffffff)
phy_map = ~(1 << dev->phy_address);
for (i = 0; i < 0x20; phy_map >>= 1, ++i)
if (!(phy_map & 1)) {
int r;
busy_phy_map |= 1 << i;
/* Quick check if there is a PHY at the address */
r = emac_mdio_read(dev->ndev, i, MII_BMCR);
if (r == 0xffff || r < 0)
continue;
if (!emac_mii_phy_probe(&dev->phy, i))
break;
}
/* Enable external clock source */
#ifdef CONFIG_PPC_DCR_NATIVE
if (emac_has_feature(dev, EMAC_FTR_440GX_PHY_CLK_FIX))
dcri_clrset(SDR0, SDR0_MFR, SDR0_MFR_ECS, 0);
#endif
mutex_unlock(&emac_phy_map_lock);
if (i == 0x20) {
printk(KERN_WARNING "%s: can't find PHY!\n", np->full_name);
return -ENXIO;
}
/* Init PHY */
if (dev->phy.def->ops->init)
dev->phy.def->ops->init(&dev->phy);
/* Disable any PHY features not supported by the platform */
dev->phy.def->features &= ~dev->phy_feat_exc;
/* Setup initial link parameters */
if (dev->phy.features & SUPPORTED_Autoneg) {
adv = dev->phy.features;
if (!emac_has_feature(dev, EMAC_FTR_NO_FLOW_CONTROL_40x))
adv |= ADVERTISED_Pause | ADVERTISED_Asym_Pause;
/* Restart autonegotiation */
dev->phy.def->ops->setup_aneg(&dev->phy, adv);
} else {
u32 f = dev->phy.def->features;
int speed = SPEED_10, fd = DUPLEX_HALF;
/* Select highest supported speed/duplex */
if (f & SUPPORTED_1000baseT_Full) {
speed = SPEED_1000;
fd = DUPLEX_FULL;
} else if (f & SUPPORTED_1000baseT_Half)
speed = SPEED_1000;
else if (f & SUPPORTED_100baseT_Full) {
speed = SPEED_100;
fd = DUPLEX_FULL;
} else if (f & SUPPORTED_100baseT_Half)
speed = SPEED_100;
else if (f & SUPPORTED_10baseT_Full)
fd = DUPLEX_FULL;
/* Force link parameters */
dev->phy.def->ops->setup_forced(&dev->phy, speed, fd);
}
return 0;
}
static int __devinit emac_init_config(struct emac_instance *dev)
{
struct device_node *np = dev->ofdev->dev.of_node;
const void *p;
/* Read config from device-tree */
if (emac_read_uint_prop(np, "mal-device", &dev->mal_ph, 1))
return -ENXIO;
if (emac_read_uint_prop(np, "mal-tx-channel", &dev->mal_tx_chan, 1))
return -ENXIO;
if (emac_read_uint_prop(np, "mal-rx-channel", &dev->mal_rx_chan, 1))
return -ENXIO;
if (emac_read_uint_prop(np, "cell-index", &dev->cell_index, 1))
return -ENXIO;
if (emac_read_uint_prop(np, "max-frame-size", &dev->max_mtu, 0))
dev->max_mtu = 1500;
if (emac_read_uint_prop(np, "rx-fifo-size", &dev->rx_fifo_size, 0))
dev->rx_fifo_size = 2048;
if (emac_read_uint_prop(np, "tx-fifo-size", &dev->tx_fifo_size, 0))
dev->tx_fifo_size = 2048;
if (emac_read_uint_prop(np, "rx-fifo-size-gige", &dev->rx_fifo_size_gige, 0))
dev->rx_fifo_size_gige = dev->rx_fifo_size;
if (emac_read_uint_prop(np, "tx-fifo-size-gige", &dev->tx_fifo_size_gige, 0))
dev->tx_fifo_size_gige = dev->tx_fifo_size;
if (emac_read_uint_prop(np, "phy-address", &dev->phy_address, 0))
dev->phy_address = 0xffffffff;
if (emac_read_uint_prop(np, "phy-map", &dev->phy_map, 0))
dev->phy_map = 0xffffffff;
if (emac_read_uint_prop(np, "gpcs-address", &dev->gpcs_address, 0))
dev->gpcs_address = 0xffffffff;
if (emac_read_uint_prop(np->parent, "clock-frequency", &dev->opb_bus_freq, 1))
return -ENXIO;
if (emac_read_uint_prop(np, "tah-device", &dev->tah_ph, 0))
dev->tah_ph = 0;
if (emac_read_uint_prop(np, "tah-channel", &dev->tah_port, 0))
dev->tah_port = 0;
if (emac_read_uint_prop(np, "mdio-device", &dev->mdio_ph, 0))
dev->mdio_ph = 0;
if (emac_read_uint_prop(np, "zmii-device", &dev->zmii_ph, 0))
dev->zmii_ph = 0;
if (emac_read_uint_prop(np, "zmii-channel", &dev->zmii_port, 0))
dev->zmii_port = 0xffffffff;
if (emac_read_uint_prop(np, "rgmii-device", &dev->rgmii_ph, 0))
dev->rgmii_ph = 0;
if (emac_read_uint_prop(np, "rgmii-channel", &dev->rgmii_port, 0))
dev->rgmii_port = 0xffffffff;
if (emac_read_uint_prop(np, "fifo-entry-size", &dev->fifo_entry_size, 0))
dev->fifo_entry_size = 16;
if (emac_read_uint_prop(np, "mal-burst-size", &dev->mal_burst_size, 0))
dev->mal_burst_size = 256;
/* PHY mode needs some decoding */
dev->phy_mode = of_get_phy_mode(np);
if (dev->phy_mode < 0)
dev->phy_mode = PHY_MODE_NA;
/* Check EMAC version */
if (of_device_is_compatible(np, "ibm,emac4sync")) {
dev->features |= (EMAC_FTR_EMAC4 | EMAC_FTR_EMAC4SYNC);
if (of_device_is_compatible(np, "ibm,emac-460ex") ||
of_device_is_compatible(np, "ibm,emac-460gt"))
dev->features |= EMAC_FTR_460EX_PHY_CLK_FIX;
if (of_device_is_compatible(np, "ibm,emac-405ex") ||
of_device_is_compatible(np, "ibm,emac-405exr"))
dev->features |= EMAC_FTR_440EP_PHY_CLK_FIX;
} else if (of_device_is_compatible(np, "ibm,emac4")) {
dev->features |= EMAC_FTR_EMAC4;
if (of_device_is_compatible(np, "ibm,emac-440gx"))
dev->features |= EMAC_FTR_440GX_PHY_CLK_FIX;
} else {
if (of_device_is_compatible(np, "ibm,emac-440ep") ||
of_device_is_compatible(np, "ibm,emac-440gr"))
dev->features |= EMAC_FTR_440EP_PHY_CLK_FIX;
if (of_device_is_compatible(np, "ibm,emac-405ez")) {
#ifdef CONFIG_IBM_NEW_EMAC_NO_FLOW_CTRL
dev->features |= EMAC_FTR_NO_FLOW_CONTROL_40x;
#else
printk(KERN_ERR "%s: Flow control not disabled!\n",
np->full_name);
return -ENXIO;
#endif
}
}
/* Fixup some feature bits based on the device tree */
if (of_get_property(np, "has-inverted-stacr-oc", NULL))
dev->features |= EMAC_FTR_STACR_OC_INVERT;
if (of_get_property(np, "has-new-stacr-staopc", NULL))
dev->features |= EMAC_FTR_HAS_NEW_STACR;
/* CAB lacks the appropriate properties */
if (of_device_is_compatible(np, "ibm,emac-axon"))
dev->features |= EMAC_FTR_HAS_NEW_STACR |
EMAC_FTR_STACR_OC_INVERT;
/* Enable TAH/ZMII/RGMII features as found */
if (dev->tah_ph != 0) {
#ifdef CONFIG_IBM_NEW_EMAC_TAH
dev->features |= EMAC_FTR_HAS_TAH;
#else
printk(KERN_ERR "%s: TAH support not enabled !\n",
np->full_name);
return -ENXIO;
#endif
}
if (dev->zmii_ph != 0) {
#ifdef CONFIG_IBM_NEW_EMAC_ZMII
dev->features |= EMAC_FTR_HAS_ZMII;
#else
printk(KERN_ERR "%s: ZMII support not enabled !\n",
np->full_name);
return -ENXIO;
#endif
}
if (dev->rgmii_ph != 0) {
#ifdef CONFIG_IBM_NEW_EMAC_RGMII
dev->features |= EMAC_FTR_HAS_RGMII;
#else
printk(KERN_ERR "%s: RGMII support not enabled !\n",
np->full_name);
return -ENXIO;
#endif
}
/* Read MAC-address */
p = of_get_property(np, "local-mac-address", NULL);
if (p == NULL) {
printk(KERN_ERR "%s: Can't find local-mac-address property\n",
np->full_name);
return -ENXIO;
}
memcpy(dev->ndev->dev_addr, p, 6);
/* IAHT and GAHT filter parameterization */
if (emac_has_feature(dev, EMAC_FTR_EMAC4SYNC)) {
dev->xaht_slots_shift = EMAC4SYNC_XAHT_SLOTS_SHIFT;
dev->xaht_width_shift = EMAC4SYNC_XAHT_WIDTH_SHIFT;
} else {
dev->xaht_slots_shift = EMAC4_XAHT_SLOTS_SHIFT;
dev->xaht_width_shift = EMAC4_XAHT_WIDTH_SHIFT;
}
DBG(dev, "features : 0x%08x / 0x%08x\n", dev->features, EMAC_FTRS_POSSIBLE);
DBG(dev, "tx_fifo_size : %d (%d gige)\n", dev->tx_fifo_size, dev->tx_fifo_size_gige);
DBG(dev, "rx_fifo_size : %d (%d gige)\n", dev->rx_fifo_size, dev->rx_fifo_size_gige);
DBG(dev, "max_mtu : %d\n", dev->max_mtu);
DBG(dev, "OPB freq : %d\n", dev->opb_bus_freq);
return 0;
}
static const struct net_device_ops emac_netdev_ops = {
.ndo_open = emac_open,
.ndo_stop = emac_close,
.ndo_get_stats = emac_stats,
.ndo_set_multicast_list = emac_set_multicast_list,
.ndo_do_ioctl = emac_ioctl,
.ndo_tx_timeout = emac_tx_timeout,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
.ndo_start_xmit = emac_start_xmit,
.ndo_change_mtu = eth_change_mtu,
};
static const struct net_device_ops emac_gige_netdev_ops = {
.ndo_open = emac_open,
.ndo_stop = emac_close,
.ndo_get_stats = emac_stats,
.ndo_set_multicast_list = emac_set_multicast_list,
.ndo_do_ioctl = emac_ioctl,
.ndo_tx_timeout = emac_tx_timeout,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
.ndo_start_xmit = emac_start_xmit_sg,
.ndo_change_mtu = emac_change_mtu,
};
static int __devinit emac_probe(struct platform_device *ofdev)
{
struct net_device *ndev;
struct emac_instance *dev;
struct device_node *np = ofdev->dev.of_node;
struct device_node **blist = NULL;
int err, i;
/* Skip unused/unwired EMACS. We leave the check for an unused
* property here for now, but new flat device trees should set a
* status property to "disabled" instead.
*/
if (of_get_property(np, "unused", NULL) || !of_device_is_available(np))
return -ENODEV;
/* Find ourselves in the bootlist if we are there */
for (i = 0; i < EMAC_BOOT_LIST_SIZE; i++)
if (emac_boot_list[i] == np)
blist = &emac_boot_list[i];
/* Allocate our net_device structure */
err = -ENOMEM;
ndev = alloc_etherdev(sizeof(struct emac_instance));
if (!ndev) {
printk(KERN_ERR "%s: could not allocate ethernet device!\n",
np->full_name);
goto err_gone;
}
dev = netdev_priv(ndev);
dev->ndev = ndev;
dev->ofdev = ofdev;
dev->blist = blist;
SET_NETDEV_DEV(ndev, &ofdev->dev);
/* Initialize some embedded data structures */
mutex_init(&dev->mdio_lock);
mutex_init(&dev->link_lock);
spin_lock_init(&dev->lock);
INIT_WORK(&dev->reset_work, emac_reset_work);
/* Init various config data based on device-tree */
err = emac_init_config(dev);
if (err != 0)
goto err_free;
/* Get interrupts. EMAC irq is mandatory, WOL irq is optional */
dev->emac_irq = irq_of_parse_and_map(np, 0);
dev->wol_irq = irq_of_parse_and_map(np, 1);
if (dev->emac_irq == NO_IRQ) {
printk(KERN_ERR "%s: Can't map main interrupt\n", np->full_name);
goto err_free;
}
ndev->irq = dev->emac_irq;
/* Map EMAC regs */
if (of_address_to_resource(np, 0, &dev->rsrc_regs)) {
printk(KERN_ERR "%s: Can't get registers address\n",
np->full_name);
goto err_irq_unmap;
}
// TODO : request_mem_region
dev->emacp = ioremap(dev->rsrc_regs.start,
resource_size(&dev->rsrc_regs));
if (dev->emacp == NULL) {
printk(KERN_ERR "%s: Can't map device registers!\n",
np->full_name);
err = -ENOMEM;
goto err_irq_unmap;
}
/* Wait for dependent devices */
err = emac_wait_deps(dev);
if (err) {
printk(KERN_ERR
"%s: Timeout waiting for dependent devices\n",
np->full_name);
/* display more info about what's missing ? */
goto err_reg_unmap;
}
dev->mal = dev_get_drvdata(&dev->mal_dev->dev);
if (dev->mdio_dev != NULL)
dev->mdio_instance = dev_get_drvdata(&dev->mdio_dev->dev);
/* Register with MAL */
dev->commac.ops = &emac_commac_ops;
dev->commac.dev = dev;
dev->commac.tx_chan_mask = MAL_CHAN_MASK(dev->mal_tx_chan);
dev->commac.rx_chan_mask = MAL_CHAN_MASK(dev->mal_rx_chan);
err = mal_register_commac(dev->mal, &dev->commac);
if (err) {
printk(KERN_ERR "%s: failed to register with mal %s!\n",
np->full_name, dev->mal_dev->dev.of_node->full_name);
goto err_rel_deps;
}
dev->rx_skb_size = emac_rx_skb_size(ndev->mtu);
dev->rx_sync_size = emac_rx_sync_size(ndev->mtu);
/* Get pointers to BD rings */
dev->tx_desc =
dev->mal->bd_virt + mal_tx_bd_offset(dev->mal, dev->mal_tx_chan);
dev->rx_desc =
dev->mal->bd_virt + mal_rx_bd_offset(dev->mal, dev->mal_rx_chan);
DBG(dev, "tx_desc %p" NL, dev->tx_desc);
DBG(dev, "rx_desc %p" NL, dev->rx_desc);
/* Clean rings */
memset(dev->tx_desc, 0, NUM_TX_BUFF * sizeof(struct mal_descriptor));
memset(dev->rx_desc, 0, NUM_RX_BUFF * sizeof(struct mal_descriptor));
memset(dev->tx_skb, 0, NUM_TX_BUFF * sizeof(struct sk_buff *));
memset(dev->rx_skb, 0, NUM_RX_BUFF * sizeof(struct sk_buff *));
/* Attach to ZMII, if needed */
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII) &&
(err = zmii_attach(dev->zmii_dev, dev->zmii_port, &dev->phy_mode)) != 0)
goto err_unreg_commac;
/* Attach to RGMII, if needed */
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII) &&
(err = rgmii_attach(dev->rgmii_dev, dev->rgmii_port, dev->phy_mode)) != 0)
goto err_detach_zmii;
/* Attach to TAH, if needed */
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH) &&
(err = tah_attach(dev->tah_dev, dev->tah_port)) != 0)
goto err_detach_rgmii;
/* Set some link defaults before we can find out real parameters */
dev->phy.speed = SPEED_100;
dev->phy.duplex = DUPLEX_FULL;
dev->phy.autoneg = AUTONEG_DISABLE;
dev->phy.pause = dev->phy.asym_pause = 0;
dev->stop_timeout = STOP_TIMEOUT_100;
INIT_DELAYED_WORK(&dev->link_work, emac_link_timer);
/* Find PHY if any */
err = emac_init_phy(dev);
if (err != 0)
goto err_detach_tah;
if (dev->tah_dev) {
ndev->hw_features = NETIF_F_IP_CSUM | NETIF_F_SG;
ndev->features |= ndev->hw_features | NETIF_F_RXCSUM;
}
ndev->watchdog_timeo = 5 * HZ;
if (emac_phy_supports_gige(dev->phy_mode)) {
ndev->netdev_ops = &emac_gige_netdev_ops;
dev->commac.ops = &emac_commac_sg_ops;
} else
ndev->netdev_ops = &emac_netdev_ops;
SET_ETHTOOL_OPS(ndev, &emac_ethtool_ops);
netif_carrier_off(ndev);
err = register_netdev(ndev);
if (err) {
printk(KERN_ERR "%s: failed to register net device (%d)!\n",
np->full_name, err);
goto err_detach_tah;
}
/* Set our drvdata last as we don't want them visible until we are
* fully initialized
*/
wmb();
dev_set_drvdata(&ofdev->dev, dev);
/* There's a new kid in town ! Let's tell everybody */
wake_up_all(&emac_probe_wait);
printk(KERN_INFO "%s: EMAC-%d %s, MAC %pM\n",
ndev->name, dev->cell_index, np->full_name, ndev->dev_addr);
if (dev->phy_mode == PHY_MODE_SGMII)
printk(KERN_NOTICE "%s: in SGMII mode\n", ndev->name);
if (dev->phy.address >= 0)
printk("%s: found %s PHY (0x%02x)\n", ndev->name,
dev->phy.def->name, dev->phy.address);
emac_dbg_register(dev);
/* Life is good */
return 0;
/* I have a bad feeling about this ... */
err_detach_tah:
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH))
tah_detach(dev->tah_dev, dev->tah_port);
err_detach_rgmii:
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
rgmii_detach(dev->rgmii_dev, dev->rgmii_port);
err_detach_zmii:
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
zmii_detach(dev->zmii_dev, dev->zmii_port);
err_unreg_commac:
mal_unregister_commac(dev->mal, &dev->commac);
err_rel_deps:
emac_put_deps(dev);
err_reg_unmap:
iounmap(dev->emacp);
err_irq_unmap:
if (dev->wol_irq != NO_IRQ)
irq_dispose_mapping(dev->wol_irq);
if (dev->emac_irq != NO_IRQ)
irq_dispose_mapping(dev->emac_irq);
err_free:
free_netdev(ndev);
err_gone:
/* if we were on the bootlist, remove us as we won't show up and
* wake up all waiters to notify them in case they were waiting
* on us
*/
if (blist) {
*blist = NULL;
wake_up_all(&emac_probe_wait);
}
return err;
}
static int __devexit emac_remove(struct platform_device *ofdev)
{
struct emac_instance *dev = dev_get_drvdata(&ofdev->dev);
DBG(dev, "remove" NL);
dev_set_drvdata(&ofdev->dev, NULL);
unregister_netdev(dev->ndev);
cancel_work_sync(&dev->reset_work);
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH))
tah_detach(dev->tah_dev, dev->tah_port);
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
rgmii_detach(dev->rgmii_dev, dev->rgmii_port);
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
zmii_detach(dev->zmii_dev, dev->zmii_port);
mal_unregister_commac(dev->mal, &dev->commac);
emac_put_deps(dev);
emac_dbg_unregister(dev);
iounmap(dev->emacp);
if (dev->wol_irq != NO_IRQ)
irq_dispose_mapping(dev->wol_irq);
if (dev->emac_irq != NO_IRQ)
irq_dispose_mapping(dev->emac_irq);
free_netdev(dev->ndev);
return 0;
}
/* XXX Features in here should be replaced by properties... */
static struct of_device_id emac_match[] =
{
{
.type = "network",
.compatible = "ibm,emac",
},
{
.type = "network",
.compatible = "ibm,emac4",
},
{
.type = "network",
.compatible = "ibm,emac4sync",
},
{},
};
MODULE_DEVICE_TABLE(of, emac_match);
static struct platform_driver emac_driver = {
.driver = {
.name = "emac",
.owner = THIS_MODULE,
.of_match_table = emac_match,
},
.probe = emac_probe,
.remove = emac_remove,
};
static void __init emac_make_bootlist(void)
{
struct device_node *np = NULL;
int j, max, i = 0, k;
int cell_indices[EMAC_BOOT_LIST_SIZE];
/* Collect EMACs */
while((np = of_find_all_nodes(np)) != NULL) {
const u32 *idx;
if (of_match_node(emac_match, np) == NULL)
continue;
if (of_get_property(np, "unused", NULL))
continue;
idx = of_get_property(np, "cell-index", NULL);
if (idx == NULL)
continue;
cell_indices[i] = *idx;
emac_boot_list[i++] = of_node_get(np);
if (i >= EMAC_BOOT_LIST_SIZE) {
of_node_put(np);
break;
}
}
max = i;
/* Bubble sort them (doh, what a creative algorithm :-) */
for (i = 0; max > 1 && (i < (max - 1)); i++)
for (j = i; j < max; j++) {
if (cell_indices[i] > cell_indices[j]) {
np = emac_boot_list[i];
emac_boot_list[i] = emac_boot_list[j];
emac_boot_list[j] = np;
k = cell_indices[i];
cell_indices[i] = cell_indices[j];
cell_indices[j] = k;
}
}
}
static int __init emac_init(void)
{
int rc;
printk(KERN_INFO DRV_DESC ", version " DRV_VERSION "\n");
/* Init debug stuff */
emac_init_debug();
/* Build EMAC boot list */
emac_make_bootlist();
/* Init submodules */
rc = mal_init();
if (rc)
goto err;
rc = zmii_init();
if (rc)
goto err_mal;
rc = rgmii_init();
if (rc)
goto err_zmii;
rc = tah_init();
if (rc)
goto err_rgmii;
rc = platform_driver_register(&emac_driver);
if (rc)
goto err_tah;
return 0;
err_tah:
tah_exit();
err_rgmii:
rgmii_exit();
err_zmii:
zmii_exit();
err_mal:
mal_exit();
err:
return rc;
}
static void __exit emac_exit(void)
{
int i;
platform_driver_unregister(&emac_driver);
tah_exit();
rgmii_exit();
zmii_exit();
mal_exit();
emac_fini_debug();
/* Destroy EMAC boot list */
for (i = 0; i < EMAC_BOOT_LIST_SIZE; i++)
if (emac_boot_list[i])
of_node_put(emac_boot_list[i]);
}
module_init(emac_init);
module_exit(emac_exit);
| gpl-2.0 |
thicklizard/Silence | drivers/rtc/rtc-lib.c | 382 | 2913 | /*
* rtc and date/time utility functions
*
* Copyright (C) 2005-06 Tower Technologies
* Author: Alessandro Zummo <a.zummo@towertech.it>
*
* based on arch/arm/common/rtctime.c and other bits
*
* 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/rtc.h>
static const unsigned char rtc_days_in_month[] = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
static const unsigned short rtc_ydays[2][13] = {
{ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
{ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
};
#define LEAPS_THRU_END_OF(y) ((y)/4 - (y)/100 + (y)/400)
int rtc_month_days(unsigned int month, unsigned int year)
{
return rtc_days_in_month[month] + (is_leap_year(year) && month == 1);
}
EXPORT_SYMBOL(rtc_month_days);
int rtc_year_days(unsigned int day, unsigned int month, unsigned int year)
{
return rtc_ydays[is_leap_year(year)][month] + day-1;
}
EXPORT_SYMBOL(rtc_year_days);
void rtc_time_to_tm(unsigned long time, struct rtc_time *tm)
{
unsigned int month, year;
int days;
days = time / 86400;
time -= (unsigned int) days * 86400;
tm->tm_wday = (days + 4) % 7;
year = 1970 + days / 365;
days -= (year - 1970) * 365
+ LEAPS_THRU_END_OF(year - 1)
- LEAPS_THRU_END_OF(1970 - 1);
if (days < 0) {
year -= 1;
days += 365 + is_leap_year(year);
}
tm->tm_year = year - 1900;
tm->tm_yday = days + 1;
for (month = 0; month < 11; month++) {
int newdays;
newdays = days - rtc_month_days(month, year);
if (newdays < 0)
break;
days = newdays;
}
tm->tm_mon = month;
tm->tm_mday = days + 1;
tm->tm_hour = time / 3600;
time -= tm->tm_hour * 3600;
tm->tm_min = time / 60;
tm->tm_sec = time - tm->tm_min * 60;
tm->tm_isdst = 0;
}
EXPORT_SYMBOL(rtc_time_to_tm);
int rtc_valid_tm(struct rtc_time *tm)
{
if (tm->tm_year < 70
|| ((unsigned)tm->tm_mon) >= 12
|| tm->tm_mday < 1
|| tm->tm_mday > rtc_month_days(tm->tm_mon, tm->tm_year + 1900)
|| ((unsigned)tm->tm_hour) >= 24
|| ((unsigned)tm->tm_min) >= 60
|| ((unsigned)tm->tm_sec) >= 60)
return -EINVAL;
return 0;
}
EXPORT_SYMBOL(rtc_valid_tm);
int rtc_tm_to_time(struct rtc_time *tm, unsigned long *time)
{
*time = mktime(tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
return 0;
}
EXPORT_SYMBOL(rtc_tm_to_time);
ktime_t rtc_tm_to_ktime(struct rtc_time tm)
{
time_t time;
rtc_tm_to_time(&tm, &time);
return ktime_set(time, 0);
}
EXPORT_SYMBOL_GPL(rtc_tm_to_ktime);
struct rtc_time rtc_ktime_to_tm(ktime_t kt)
{
struct timespec ts;
struct rtc_time ret;
ts = ktime_to_timespec(kt);
if (ts.tv_nsec)
ts.tv_sec++;
rtc_time_to_tm(ts.tv_sec, &ret);
return ret;
}
EXPORT_SYMBOL_GPL(rtc_ktime_to_tm);
MODULE_LICENSE("GPL");
| gpl-2.0 |
dpuyosa/android_kernel_wiko_l5460 | drivers/mtd/tests/stresstest.c | 1150 | 5648 | /*
* Copyright (C) 2006-2008 Nokia Corporation
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; see the file COPYING. If not, write to the Free Software
* Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Test random reads, writes and erases on MTD device.
*
* Author: Adrian Hunter <ext-adrian.hunter@nokia.com>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/err.h>
#include <linux/mtd/mtd.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/vmalloc.h>
#include <linux/random.h>
#include "mtd_test.h"
static int dev = -EINVAL;
module_param(dev, int, S_IRUGO);
MODULE_PARM_DESC(dev, "MTD device number to use");
static int count = 10000;
module_param(count, int, S_IRUGO);
MODULE_PARM_DESC(count, "Number of operations to do (default is 10000)");
static struct mtd_info *mtd;
static unsigned char *writebuf;
static unsigned char *readbuf;
static unsigned char *bbt;
static int *offsets;
static int pgsize;
static int bufsize;
static int ebcnt;
static int pgcnt;
static int rand_eb(void)
{
unsigned int eb;
again:
eb = prandom_u32();
/* Read or write up 2 eraseblocks at a time - hence 'ebcnt - 1' */
eb %= (ebcnt - 1);
if (bbt[eb])
goto again;
return eb;
}
static int rand_offs(void)
{
unsigned int offs;
offs = prandom_u32();
offs %= bufsize;
return offs;
}
static int rand_len(int offs)
{
unsigned int len;
len = prandom_u32();
len %= (bufsize - offs);
return len;
}
static int do_read(void)
{
int eb = rand_eb();
int offs = rand_offs();
int len = rand_len(offs);
loff_t addr;
if (bbt[eb + 1]) {
if (offs >= mtd->erasesize)
offs -= mtd->erasesize;
if (offs + len > mtd->erasesize)
len = mtd->erasesize - offs;
}
addr = eb * mtd->erasesize + offs;
return mtdtest_read(mtd, addr, len, readbuf);
}
static int do_write(void)
{
int eb = rand_eb(), offs, err, len;
loff_t addr;
offs = offsets[eb];
if (offs >= mtd->erasesize) {
err = mtdtest_erase_eraseblock(mtd, eb);
if (err)
return err;
offs = offsets[eb] = 0;
}
len = rand_len(offs);
len = ((len + pgsize - 1) / pgsize) * pgsize;
if (offs + len > mtd->erasesize) {
if (bbt[eb + 1])
len = mtd->erasesize - offs;
else {
err = mtdtest_erase_eraseblock(mtd, eb + 1);
if (err)
return err;
offsets[eb + 1] = 0;
}
}
addr = eb * mtd->erasesize + offs;
err = mtdtest_write(mtd, addr, len, writebuf);
if (unlikely(err))
return err;
offs += len;
while (offs > mtd->erasesize) {
offsets[eb++] = mtd->erasesize;
offs -= mtd->erasesize;
}
offsets[eb] = offs;
return 0;
}
static int do_operation(void)
{
if (prandom_u32() & 1)
return do_read();
else
return do_write();
}
static int __init mtd_stresstest_init(void)
{
int err;
int i, op;
uint64_t tmp;
printk(KERN_INFO "\n");
printk(KERN_INFO "=================================================\n");
if (dev < 0) {
pr_info("Please specify a valid mtd-device via module parameter\n");
pr_crit("CAREFUL: This test wipes all data on the specified MTD device!\n");
return -EINVAL;
}
pr_info("MTD device: %d\n", dev);
mtd = get_mtd_device(NULL, dev);
if (IS_ERR(mtd)) {
err = PTR_ERR(mtd);
pr_err("error: cannot get MTD device\n");
return err;
}
if (mtd->writesize == 1) {
pr_info("not NAND flash, assume page size is 512 "
"bytes.\n");
pgsize = 512;
} else
pgsize = mtd->writesize;
tmp = mtd->size;
do_div(tmp, mtd->erasesize);
ebcnt = tmp;
pgcnt = mtd->erasesize / pgsize;
pr_info("MTD device size %llu, eraseblock size %u, "
"page size %u, count of eraseblocks %u, pages per "
"eraseblock %u, OOB size %u\n",
(unsigned long long)mtd->size, mtd->erasesize,
pgsize, ebcnt, pgcnt, mtd->oobsize);
if (ebcnt < 2) {
pr_err("error: need at least 2 eraseblocks\n");
err = -ENOSPC;
goto out_put_mtd;
}
/* Read or write up 2 eraseblocks at a time */
bufsize = mtd->erasesize * 2;
err = -ENOMEM;
readbuf = vmalloc(bufsize);
writebuf = vmalloc(bufsize);
offsets = kmalloc(ebcnt * sizeof(int), GFP_KERNEL);
if (!readbuf || !writebuf || !offsets)
goto out;
for (i = 0; i < ebcnt; i++)
offsets[i] = mtd->erasesize;
prandom_bytes(writebuf, bufsize);
bbt = kzalloc(ebcnt, GFP_KERNEL);
if (!bbt)
goto out;
err = mtdtest_scan_for_bad_eraseblocks(mtd, bbt, 0, ebcnt);
if (err)
goto out;
/* Do operations */
pr_info("doing operations\n");
for (op = 0; op < count; op++) {
if ((op & 1023) == 0)
pr_info("%d operations done\n", op);
err = do_operation();
if (err)
goto out;
cond_resched();
}
pr_info("finished, %d operations done\n", op);
out:
kfree(offsets);
kfree(bbt);
vfree(writebuf);
vfree(readbuf);
out_put_mtd:
put_mtd_device(mtd);
if (err)
pr_info("error %d occurred\n", err);
printk(KERN_INFO "=================================================\n");
return err;
}
module_init(mtd_stresstest_init);
static void __exit mtd_stresstest_exit(void)
{
return;
}
module_exit(mtd_stresstest_exit);
MODULE_DESCRIPTION("Stress test module");
MODULE_AUTHOR("Adrian Hunter");
MODULE_LICENSE("GPL");
| gpl-2.0 |
davidmueller13/android_kernel_samsung_lt03lte | drivers/platform/msm/usb_bam.c | 1662 | 76450 | /* Copyright (c) 2011-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/types.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/stat.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/usb/msm_hsusb.h>
#include <mach/usb_bam.h>
#include <mach/sps.h>
#include <mach/ipa.h>
#include <linux/workqueue.h>
#include <linux/dma-mapping.h>
#include <mach/msm_smsm.h>
#include <linux/pm_runtime.h>
#define USB_THRESHOLD 512
#define USB_BAM_MAX_STR_LEN 50
#define USB_BAM_TIMEOUT (10*HZ)
enum usb_bam_sm {
USB_BAM_SM_INIT = 0,
USB_BAM_SM_PLUG_NOTIFIED,
USB_BAM_SM_PLUG_ACKED,
USB_BAM_SM_UNPLUG_NOTIFIED,
};
struct usb_bam_peer_handshake_info {
enum usb_bam_sm state;
bool client_ready;
bool ack_received;
int pending_work;
struct usb_bam_event_info reset_event;
};
struct usb_bam_sps_type {
struct sps_bam_props usb_props;
struct sps_pipe **sps_pipes;
struct sps_connect *sps_connections;
};
/**
* struct usb_bam_ctx_type - represents the usb bam driver entity
* @usb_bam_sps: holds the sps pipes the usb bam driver holds
* against the sps driver.
* @usb_bam_pdev: the platfrom device that represents the usb bam.
* @usb_bam_wq: Worqueue used for managing states of reset against
* a peer bam.
* @qscratch_ram1_reg: The memory region mapped to the qscratch
* registers.
* @max_connections: The maximum number of pipes that are configured
* in the platform data.
* @mem_clk: Clock that controls the usb bam driver memory in
* case the usb bam uses its private memory for the pipes.
* @mem_iface_clk: Clock that controls the usb bam private memory in
* case the usb bam uses its private memory for the pipes.
* @qdss_core_name: Stores the name of the core ("ssusb", "hsusb" or "hsic")
* that it used as a peer of the qdss in bam2bam mode.
* @h_bam: This array stores for each BAM ("ssusb", "hsusb" or "hsic") the
* handle/device of the sps driver.
* @pipes_enabled_per_bam: This array stores for each BAM
* ("ssusb", "hsusb" or "hsic") the number of pipes currently enabled.
* @inactivity_timer_ms: The timeout configuration per each bam for inactivity
* timer feature.
* @is_bam_inactivity: Is there no activity on all pipes belongs to a
* specific bam. (no activity = no data is pulled or pushed
* from/into ones of the pipes).
*/
struct usb_bam_ctx_type {
struct usb_bam_sps_type usb_bam_sps;
struct platform_device *usb_bam_pdev;
struct workqueue_struct *usb_bam_wq;
void __iomem *qscratch_ram1_reg;
u8 max_connections;
struct clk *mem_clk;
struct clk *mem_iface_clk;
char qdss_core_name[USB_BAM_MAX_STR_LEN];
u32 h_bam[MAX_BAMS];
u8 pipes_enabled_per_bam[MAX_BAMS];
u32 inactivity_timer_ms[MAX_BAMS];
bool is_bam_inactivity[MAX_BAMS];
struct completion reset_done;
};
static char *bam_enable_strings[MAX_BAMS] = {
[SSUSB_BAM] = "ssusb",
[HSUSB_BAM] = "hsusb",
[HSIC_BAM] = "hsic",
};
static enum usb_bam ipa_rm_bams[] = {HSUSB_BAM, HSIC_BAM};
static enum ipa_client_type ipa_rm_resource_prod[MAX_BAMS] = {
[HSUSB_BAM] = IPA_RM_RESOURCE_USB_PROD,
[HSIC_BAM] = IPA_RM_RESOURCE_HSIC_PROD,
};
static enum ipa_client_type ipa_rm_resource_cons[MAX_BAMS] = {
[HSUSB_BAM] = IPA_RM_RESOURCE_USB_CONS,
[HSIC_BAM] = IPA_RM_RESOURCE_HSIC_CONS,
};
static int usb_cons_request_resource(void);
static int usb_cons_release_resource(void);
static int hsic_cons_request_resource(void);
static int hsic_cons_release_resource(void);
static int (*request_resource_cb[MAX_BAMS])(void) = {
[HSUSB_BAM] = usb_cons_request_resource,
[HSIC_BAM] = hsic_cons_request_resource,
};
static int (*release_resource_cb[MAX_BAMS])(void) = {
[HSUSB_BAM] = usb_cons_release_resource,
[HSIC_BAM] = hsic_cons_release_resource,
};
struct usb_bam_ipa_handshake_info {
enum ipa_rm_event cur_prod_state[MAX_BAMS];
enum ipa_rm_event cur_cons_state[MAX_BAMS];
bool lpm_wait_handshake[MAX_BAMS];
int connect_complete;
bool lpm_wait_pipes;
int bus_suspend;
bool disconnected;
bool in_lpm[MAX_BAMS];
bool pending_lpm;
int (*wake_cb)(void *);
void *wake_param;
void (*start)(void *, enum usb_bam_pipe_dir);
void (*stop)(void *, enum usb_bam_pipe_dir);
void *start_stop_param;
u32 src_idx;
u32 dst_idx;
bool cons_stopped;
bool prod_stopped;
struct completion prod_avail[MAX_BAMS];
struct completion prod_released[MAX_BAMS];
struct mutex suspend_resume_mutex;
struct work_struct resume_work;
struct work_struct suspend_work;
struct work_struct finish_suspend_work;
};
struct usb_bam_hsic_host_info {
struct device *dev;
bool in_lpm;
};
static spinlock_t usb_bam_ipa_handshake_info_lock;
static struct usb_bam_ipa_handshake_info info;
static spinlock_t usb_bam_peer_handshake_info_lock;
static struct usb_bam_peer_handshake_info peer_handshake_info;
static spinlock_t usb_bam_lock; /* Protect ctx and usb_bam_connections */
static struct usb_bam_pipe_connect *usb_bam_connections;
static struct usb_bam_ctx_type ctx;
static struct usb_bam_hsic_host_info hsic_host_info;
static int __usb_bam_register_wake_cb(u8 idx, int (*callback)(void *user),
void *param, bool trigger_cb_per_pipe);
static void wait_for_prod_release(enum usb_bam cur_bam);
void msm_bam_set_hsic_host_dev(struct device *dev)
{
if (dev) {
/* Hold the device until allowing lpm */
info.in_lpm[HSIC_BAM] = false;
pr_debug("%s: Getting hsic device %x\n", __func__,
(int)dev);
pm_runtime_get(dev);
} else if (hsic_host_info.dev) {
pr_debug("%s: Putting hsic device %x\n", __func__,
(int)hsic_host_info.dev);
/* Just free previous device*/
info.in_lpm[HSIC_BAM] = true;
pm_runtime_put(hsic_host_info.dev);
}
hsic_host_info.dev = dev;
hsic_host_info.in_lpm = false;
}
static int get_bam_type_from_core_name(const char *name)
{
if (strnstr(name, bam_enable_strings[SSUSB_BAM],
USB_BAM_MAX_STR_LEN) ||
strnstr(name, "dwc3", USB_BAM_MAX_STR_LEN))
return SSUSB_BAM;
else if (strnstr(name, bam_enable_strings[HSIC_BAM],
USB_BAM_MAX_STR_LEN))
return HSIC_BAM;
else if (strnstr(name, bam_enable_strings[HSUSB_BAM],
USB_BAM_MAX_STR_LEN) ||
strnstr(name, "ci", USB_BAM_MAX_STR_LEN))
return HSUSB_BAM;
pr_err("%s: invalid BAM name(%s)\n", __func__, name);
return -EINVAL;
}
static bool bam_use_private_mem(enum usb_bam bam)
{
int i;
for (i = 0; i < ctx.max_connections; i++)
if (usb_bam_connections[i].bam_type == bam &&
usb_bam_connections[i].mem_type == USB_PRIVATE_MEM)
return true;
return false;
}
static void usb_bam_set_inactivity_timer(enum usb_bam bam)
{
struct sps_timer_ctrl timer_ctrl;
struct usb_bam_pipe_connect *pipe_connect;
struct sps_pipe *pipe = NULL;
int i;
pr_debug("%s: enter\n", __func__);
/*
* Since we configure global incativity timer for all pipes
* and not per each pipe, it is enough to use some pipe
* handle associated with this bam, so just find the first one.
* This pipe handle is required due to SPS driver API we use below.
*/
for (i = 0; i < ctx.max_connections; i++) {
pipe_connect = &usb_bam_connections[i];
if (pipe_connect->bam_type == bam &&
pipe_connect->enabled) {
pipe = ctx.usb_bam_sps.sps_pipes[i];
break;
}
}
if (!pipe) {
pr_warning("%s: Bam %s has no connected pipes\n", __func__,
bam_enable_strings[bam]);
return;
}
timer_ctrl.op = SPS_TIMER_OP_CONFIG;
timer_ctrl.mode = SPS_TIMER_MODE_ONESHOT;
timer_ctrl.timeout_msec = ctx.inactivity_timer_ms[bam];
sps_timer_ctrl(pipe, &timer_ctrl, NULL);
timer_ctrl.op = SPS_TIMER_OP_RESET;
sps_timer_ctrl(pipe, &timer_ctrl, NULL);
}
static int connect_pipe(u8 idx, u32 *usb_pipe_idx)
{
int ret, ram1_value;
enum usb_bam bam;
struct usb_bam_sps_type usb_bam_sps = ctx.usb_bam_sps;
struct sps_pipe **pipe = &(usb_bam_sps.sps_pipes[idx]);
struct sps_connect *sps_connection = &usb_bam_sps.sps_connections[idx];
struct msm_usb_bam_platform_data *pdata =
ctx.usb_bam_pdev->dev.platform_data;
struct usb_bam_pipe_connect *pipe_connect = &usb_bam_connections[idx];
enum usb_bam_pipe_dir dir = pipe_connect->dir;
struct sps_mem_buffer *data_buf = &(pipe_connect->data_mem_buf);
struct sps_mem_buffer *desc_buf = &(pipe_connect->desc_mem_buf);
*pipe = sps_alloc_endpoint();
if (*pipe == NULL) {
pr_err("%s: sps_alloc_endpoint failed\n", __func__);
return -ENOMEM;
}
ret = sps_get_config(*pipe, sps_connection);
if (ret) {
pr_err("%s: tx get config failed %d\n", __func__, ret);
goto free_sps_endpoint;
}
ret = sps_phy2h(pipe_connect->src_phy_addr, &(sps_connection->source));
if (ret) {
pr_err("%s: sps_phy2h failed (src BAM) %d\n", __func__, ret);
goto free_sps_endpoint;
}
sps_connection->src_pipe_index = pipe_connect->src_pipe_index;
ret = sps_phy2h(pipe_connect->dst_phy_addr,
&(sps_connection->destination));
if (ret) {
pr_err("%s: sps_phy2h failed (dst BAM) %d\n", __func__, ret);
goto free_sps_endpoint;
}
sps_connection->dest_pipe_index = pipe_connect->dst_pipe_index;
if (dir == USB_TO_PEER_PERIPHERAL) {
sps_connection->mode = SPS_MODE_SRC;
*usb_pipe_idx = pipe_connect->src_pipe_index;
} else {
sps_connection->mode = SPS_MODE_DEST;
*usb_pipe_idx = pipe_connect->dst_pipe_index;
}
switch (pipe_connect->mem_type) {
case SPS_PIPE_MEM:
pr_debug("%s: USB BAM using SPS pipe memory\n", __func__);
ret = sps_setup_bam2bam_fifo(
data_buf,
pipe_connect->data_fifo_base_offset,
pipe_connect->data_fifo_size, 1);
if (ret) {
pr_err("%s: data fifo setup failure %d\n", __func__,
ret);
goto free_sps_endpoint;
}
ret = sps_setup_bam2bam_fifo(
desc_buf,
pipe_connect->desc_fifo_base_offset,
pipe_connect->desc_fifo_size, 1);
if (ret) {
pr_err("%s: desc. fifo setup failure %d\n", __func__,
ret);
goto free_sps_endpoint;
}
break;
case USB_PRIVATE_MEM:
pr_debug("%s: USB BAM using private memory\n", __func__);
if (IS_ERR(ctx.mem_clk) || IS_ERR(ctx.mem_iface_clk)) {
pr_err("%s: Failed to enable USB mem_clk\n", __func__);
ret = IS_ERR(ctx.mem_clk);
goto free_sps_endpoint;
}
clk_prepare_enable(ctx.mem_clk);
clk_prepare_enable(ctx.mem_iface_clk);
/*
* Enable USB PRIVATE RAM to be used for BAM FIFOs
* HSUSB: Only RAM13 is used for BAM FIFOs
* SSUSB: RAM11, 12, 13 are used for BAM FIFOs
*/
bam = pipe_connect->bam_type;
if (bam < 0)
goto free_sps_endpoint;
if (bam == HSUSB_BAM)
ram1_value = 0x4;
else
ram1_value = 0x7;
pr_debug("Writing 0x%x to QSCRATCH_RAM1\n", ram1_value);
writel_relaxed(ram1_value, ctx.qscratch_ram1_reg);
/* fall through */
case OCI_MEM:
pr_debug("%s: USB BAM using oci memory\n", __func__);
data_buf->phys_base =
pipe_connect->data_fifo_base_offset +
pdata->usb_bam_fifo_baseaddr;
data_buf->size = pipe_connect->data_fifo_size;
data_buf->base =
ioremap(data_buf->phys_base, data_buf->size);
memset(data_buf->base, 0, data_buf->size);
desc_buf->phys_base =
pipe_connect->desc_fifo_base_offset +
pdata->usb_bam_fifo_baseaddr;
desc_buf->size = pipe_connect->desc_fifo_size;
desc_buf->base =
ioremap(desc_buf->phys_base, desc_buf->size);
memset(desc_buf->base, 0, desc_buf->size);
break;
case SYSTEM_MEM:
pr_debug("%s: USB BAM using system memory\n", __func__);
/* BAM would use system memory, allocate FIFOs */
data_buf->size = pipe_connect->data_fifo_size;
data_buf->base =
dma_alloc_coherent(&ctx.usb_bam_pdev->dev,
pipe_connect->data_fifo_size,
&(data_buf->phys_base),
0);
memset(data_buf->base, 0, pipe_connect->data_fifo_size);
desc_buf->size = pipe_connect->desc_fifo_size;
desc_buf->base =
dma_alloc_coherent(&ctx.usb_bam_pdev->dev,
pipe_connect->desc_fifo_size,
&(desc_buf->phys_base),
0);
memset(desc_buf->base, 0, pipe_connect->desc_fifo_size);
break;
default:
pr_err("%s: invalid mem type\n", __func__);
goto free_sps_endpoint;
}
sps_connection->data = *data_buf;
sps_connection->desc = *desc_buf;
sps_connection->event_thresh = 16;
sps_connection->options = SPS_O_AUTO_ENABLE;
ret = sps_connect(*pipe, sps_connection);
if (ret < 0) {
pr_err("%s: sps_connect failed %d\n", __func__, ret);
goto error;
}
return 0;
error:
sps_disconnect(*pipe);
free_sps_endpoint:
sps_free_endpoint(*pipe);
return ret;
}
static int connect_pipe_ipa(u8 idx,
struct usb_bam_connect_ipa_params *ipa_params)
{
int ret;
struct usb_bam_sps_type usb_bam_sps = ctx.usb_bam_sps;
enum usb_bam_pipe_dir dir = ipa_params->dir;
struct sps_pipe **pipe = &(usb_bam_sps.sps_pipes[idx]);
struct sps_connect *sps_connection = &usb_bam_sps.sps_connections[idx];
struct usb_bam_pipe_connect *pipe_connect = &usb_bam_connections[idx];
struct ipa_connect_params ipa_in_params;
struct ipa_sps_params sps_out_params;
u32 usb_handle, usb_phy_addr;
u32 clnt_hdl = 0;
memset(&ipa_in_params, 0, sizeof(ipa_in_params));
memset(&sps_out_params, 0, sizeof(sps_out_params));
if (dir == USB_TO_PEER_PERIPHERAL) {
usb_phy_addr = pipe_connect->src_phy_addr;
ipa_in_params.client_ep_idx = pipe_connect->src_pipe_index;
} else {
usb_phy_addr = pipe_connect->dst_phy_addr;
ipa_in_params.client_ep_idx = pipe_connect->dst_pipe_index;
}
/* Get HSUSB / HSIC bam handle */
ret = sps_phy2h(usb_phy_addr, &usb_handle);
if (ret) {
pr_err("%s: sps_phy2h failed (HSUSB/HSIC BAM) %d\n",
__func__, ret);
return ret;
}
pipe_connect->activity_notify = ipa_params->activity_notify;
pipe_connect->inactivity_notify = ipa_params->inactivity_notify;
pipe_connect->priv = ipa_params->priv;
/* IPA input parameters */
ipa_in_params.client_bam_hdl = usb_handle;
ipa_in_params.desc_fifo_sz = pipe_connect->desc_fifo_size;
ipa_in_params.data_fifo_sz = pipe_connect->data_fifo_size;
ipa_in_params.notify = ipa_params->notify;
ipa_in_params.priv = ipa_params->priv;
ipa_in_params.client = ipa_params->client;
/* If BAM is using dedicated SPS pipe memory, get it */
if (pipe_connect->mem_type == SPS_PIPE_MEM) {
pr_debug("%s: USB BAM using SPS pipe memory\n", __func__);
ret = sps_setup_bam2bam_fifo(
&pipe_connect->data_mem_buf,
pipe_connect->data_fifo_base_offset,
pipe_connect->data_fifo_size, 1);
if (ret) {
pr_err("%s: data fifo setup failure %d\n",
__func__, ret);
return ret;
}
ret = sps_setup_bam2bam_fifo(
&pipe_connect->desc_mem_buf,
pipe_connect->desc_fifo_base_offset,
pipe_connect->desc_fifo_size, 1);
if (ret) {
pr_err("%s: desc. fifo setup failure %d\n",
__func__, ret);
return ret;
}
ipa_in_params.desc = pipe_connect->desc_mem_buf;
ipa_in_params.data = pipe_connect->data_mem_buf;
}
memcpy(&ipa_in_params.ipa_ep_cfg, &ipa_params->ipa_ep_cfg,
sizeof(struct ipa_ep_cfg));
ret = ipa_connect(&ipa_in_params, &sps_out_params, &clnt_hdl);
if (ret) {
pr_err("%s: ipa_connect failed\n", __func__);
return ret;
}
pipe_connect->ipa_clnt_hdl = clnt_hdl;
*pipe = sps_alloc_endpoint();
if (*pipe == NULL) {
pr_err("%s: sps_alloc_endpoint failed\n", __func__);
ret = -ENOMEM;
goto disconnect_ipa;
}
ret = sps_get_config(*pipe, sps_connection);
if (ret) {
pr_err("%s: tx get config failed %d\n", __func__, ret);
goto free_sps_endpoints;
}
if (dir == USB_TO_PEER_PERIPHERAL) {
/* USB src IPA dest */
sps_connection->mode = SPS_MODE_SRC;
ipa_params->cons_clnt_hdl = clnt_hdl;
sps_connection->source = usb_handle;
sps_connection->destination = sps_out_params.ipa_bam_hdl;
sps_connection->src_pipe_index = pipe_connect->src_pipe_index;
sps_connection->dest_pipe_index = sps_out_params.ipa_ep_idx;
*(ipa_params->src_pipe) = sps_connection->src_pipe_index;
pipe_connect->dst_pipe_index = sps_out_params.ipa_ep_idx;
pr_debug("%s: BAM pipe usb[%x]->ipa[%x] connection\n",
__func__,
pipe_connect->src_pipe_index,
pipe_connect->dst_pipe_index);
sps_connection->options = SPS_O_NO_DISABLE;
} else {
/* IPA src, USB dest */
sps_connection->mode = SPS_MODE_DEST;
ipa_params->prod_clnt_hdl = clnt_hdl;
sps_connection->source = sps_out_params.ipa_bam_hdl;
sps_connection->destination = usb_handle;
sps_connection->src_pipe_index = sps_out_params.ipa_ep_idx;
sps_connection->dest_pipe_index = pipe_connect->dst_pipe_index;
*(ipa_params->dst_pipe) = sps_connection->dest_pipe_index;
pipe_connect->src_pipe_index = sps_out_params.ipa_ep_idx;
pr_debug("%s: BAM pipe ipa[%x]->usb[%x] connection\n",
__func__,
pipe_connect->src_pipe_index,
pipe_connect->dst_pipe_index);
sps_connection->options = 0;
}
sps_connection->data = sps_out_params.data;
sps_connection->desc = sps_out_params.desc;
sps_connection->event_thresh = 16;
sps_connection->options |= SPS_O_AUTO_ENABLE;
ret = sps_connect(*pipe, sps_connection);
if (ret < 0) {
pr_err("%s: sps_connect failed %d\n", __func__, ret);
goto error;
}
return 0;
error:
sps_disconnect(*pipe);
free_sps_endpoints:
sps_free_endpoint(*pipe);
disconnect_ipa:
ipa_disconnect(clnt_hdl);
return ret;
}
static int disconnect_pipe(u8 idx)
{
struct usb_bam_pipe_connect *pipe_connect =
&usb_bam_connections[idx];
struct sps_pipe *pipe = ctx.usb_bam_sps.sps_pipes[idx];
struct sps_connect *sps_connection =
&ctx.usb_bam_sps.sps_connections[idx];
sps_disconnect(pipe);
sps_free_endpoint(pipe);
switch (pipe_connect->mem_type) {
case SYSTEM_MEM:
pr_debug("%s: Freeing system memory used by PIPE\n", __func__);
if (sps_connection->data.phys_base)
dma_free_coherent(&ctx.usb_bam_pdev->dev,
sps_connection->data.size,
sps_connection->data.base,
sps_connection->data.phys_base);
if (sps_connection->desc.phys_base)
dma_free_coherent(&ctx.usb_bam_pdev->dev,
sps_connection->desc.size,
sps_connection->desc.base,
sps_connection->desc.phys_base);
break;
case USB_PRIVATE_MEM:
pr_debug("Freeing private memory used by BAM PIPE\n");
writel_relaxed(0x0, ctx.qscratch_ram1_reg);
clk_disable_unprepare(ctx.mem_clk);
clk_disable_unprepare(ctx.mem_iface_clk);
case OCI_MEM:
pr_debug("Freeing oci memory used by BAM PIPE\n");
iounmap(sps_connection->data.base);
iounmap(sps_connection->desc.base);
break;
case SPS_PIPE_MEM:
pr_debug("%s: nothing to be be\n", __func__);
break;
}
sps_connection->options &= ~SPS_O_AUTO_ENABLE;
return 0;
}
static void usb_bam_resume_core(enum usb_bam cur_bam)
{
struct usb_phy *trans = usb_get_transceiver();
if (cur_bam != HSUSB_BAM)
return;
BUG_ON(trans == NULL);
pr_debug("%s: resume core", __func__);
pm_runtime_resume(trans->dev);
}
static void usb_bam_start_lpm(bool disconnect)
{
struct usb_phy *trans = usb_get_transceiver();
BUG_ON(trans == NULL);
spin_lock(&usb_bam_ipa_handshake_info_lock);
info.lpm_wait_handshake[HSUSB_BAM] = false;
info.lpm_wait_pipes = 0;
if (disconnect)
pm_runtime_put_noidle(trans->dev);
if (info.pending_lpm) {
info.pending_lpm = 0;
spin_unlock(&usb_bam_ipa_handshake_info_lock);
pr_debug("%s: Going to LPM\n", __func__);
pm_runtime_suspend(trans->dev);
} else
spin_unlock(&usb_bam_ipa_handshake_info_lock);
}
int usb_bam_connect(u8 idx, u32 *bam_pipe_idx)
{
int ret;
struct usb_bam_pipe_connect *pipe_connect = &usb_bam_connections[idx];
struct msm_usb_bam_platform_data *pdata;
if (!ctx.usb_bam_pdev) {
pr_err("%s: usb_bam device not found\n", __func__);
return -ENODEV;
}
pdata = ctx.usb_bam_pdev->dev.platform_data;
if (pipe_connect->enabled) {
pr_debug("%s: connection %d was already established\n",
__func__, idx);
return 0;
}
if (!bam_pipe_idx) {
pr_err("%s: invalid bam_pipe_idx\n", __func__);
return -EINVAL;
}
if (idx < 0 || idx > ctx.max_connections) {
pr_err("idx is wrong %d", idx);
return -EINVAL;
}
spin_lock(&usb_bam_lock);
/* Check if BAM requires RESET before connect and reset of first pipe */
if ((pdata->reset_on_connect[pipe_connect->bam_type] == true) &&
(ctx.pipes_enabled_per_bam[pipe_connect->bam_type] == 0))
sps_device_reset(ctx.h_bam[pipe_connect->bam_type]);
spin_unlock(&usb_bam_lock);
ret = connect_pipe(idx, bam_pipe_idx);
if (ret) {
pr_err("%s: pipe connection[%d] failure\n", __func__, idx);
return ret;
}
pipe_connect->enabled = 1;
spin_lock(&usb_bam_lock);
ctx.pipes_enabled_per_bam[pipe_connect->bam_type] += 1;
spin_unlock(&usb_bam_lock);
return 0;
}
static int ipa_suspend_pipes(void)
{
struct usb_bam_pipe_connect *dst_pipe_connect, *src_pipe_connect;
int ret1, ret2;
dst_pipe_connect = &usb_bam_connections[info.dst_idx];
src_pipe_connect = &usb_bam_connections[info.src_idx];
if (dst_pipe_connect->ipa_clnt_hdl == -1 ||
src_pipe_connect->ipa_clnt_hdl == -1) {
pr_err("%s: One of handles is -1, not connected?", __func__);
}
ret1 = ipa_suspend(dst_pipe_connect->ipa_clnt_hdl);
if (ret1)
pr_err("%s: ipa_suspend on dst failed with %d", __func__, ret1);
ret2 = ipa_suspend(src_pipe_connect->ipa_clnt_hdl);
if (ret2)
pr_err("%s: ipa_suspend on src failed with %d", __func__, ret2);
return ret1 | ret2;
}
static int ipa_resume_pipes(void)
{
struct usb_bam_pipe_connect *dst_pipe_connect, *src_pipe_connect;
int ret1, ret2;
src_pipe_connect = &usb_bam_connections[info.src_idx];
dst_pipe_connect = &usb_bam_connections[info.dst_idx];
if (dst_pipe_connect->ipa_clnt_hdl == -1 ||
src_pipe_connect->ipa_clnt_hdl == -1) {
pr_err("%s: One of handles is -1, not connected?", __func__);
}
ret1 = ipa_resume(dst_pipe_connect->ipa_clnt_hdl);
if (ret1)
pr_err("%s: ipa_resume on dst failed with %d", __func__, ret1);
ret2 = ipa_resume(src_pipe_connect->ipa_clnt_hdl);
if (ret2)
pr_err("%s: ipa_resume on src failed with %d", __func__, ret2);
return ret1 | ret2;
}
static void usb_bam_finish_suspend(void)
{
int ret;
u32 cons_empty;
struct sps_pipe *cons_pipe = ctx.usb_bam_sps.sps_pipes[info.dst_idx];
struct usb_bam_pipe_connect *pipe_connect = &
usb_bam_connections[info.dst_idx];
enum usb_bam cur_bam = pipe_connect->bam_type;
if (cur_bam != HSUSB_BAM) {
pr_err("%s: Wrong type of BAM=%s\n", __func__,
bam_enable_strings[cur_bam]);
return;
}
mutex_lock(&info.suspend_resume_mutex);
spin_lock(&usb_bam_ipa_handshake_info_lock);
/* If cable was disconnected, let disconnection seq do everything */
if (info.disconnected || info.cons_stopped) {
spin_unlock(&usb_bam_ipa_handshake_info_lock);
mutex_unlock(&info.suspend_resume_mutex);
pr_debug("%s: Cable disconnected\n", __func__);
return;
}
/* If resume was called don't finish this work */
if (!info.bus_suspend) {
spin_unlock(&usb_bam_ipa_handshake_info_lock);
pr_err("%s: Bus resume in progress\n", __func__);
goto no_lpm;
}
spin_unlock(&usb_bam_ipa_handshake_info_lock);
ret = sps_is_pipe_empty(cons_pipe, &cons_empty);
if (ret) {
pr_err("%s: sps_is_pipe_empty failed with %d\n", __func__, ret);
goto no_lpm;
}
/* Stop CONS transfers and go to lpm if no more data in the pipe */
if (cons_empty) {
if (info.stop && !info.cons_stopped)
info.stop(info.start_stop_param,
PEER_PERIPHERAL_TO_USB);
pr_err("%s: Starting LPM on Bus Suspend\n", __func__);
info.cons_stopped = 1;
if (info.cur_cons_state[cur_bam] == IPA_RM_RESOURCE_RELEASED) {
ipa_rm_notify_completion(IPA_RM_RESOURCE_RELEASED,
ipa_rm_resource_cons[cur_bam]);
}
ipa_suspend_pipes();
usb_bam_start_lpm(0);
mutex_unlock(&info.suspend_resume_mutex);
return;
}
no_lpm:
/* Finish the handshake. Resume Sequence will start automatically
by the data in the pipes */
if (info.cur_cons_state[cur_bam] == IPA_RM_RESOURCE_RELEASED)
ipa_rm_notify_completion(IPA_RM_RESOURCE_RELEASED,
ipa_rm_resource_cons[cur_bam]);
mutex_unlock(&info.suspend_resume_mutex);
}
void usb_bam_finish_suspend_(struct work_struct *w)
{
usb_bam_finish_suspend();
}
static void usb_prod_notify_cb(void *user_data, enum ipa_rm_event event,
unsigned long data)
{
enum usb_bam *cur_bam = (void *)user_data;
switch (event) {
case IPA_RM_RESOURCE_GRANTED:
pr_debug("%s: %s_PROD resource granted\n",
__func__, bam_enable_strings[*cur_bam]);
info.cur_prod_state[*cur_bam] = IPA_RM_RESOURCE_GRANTED;
complete_all(&info.prod_avail[*cur_bam]);
break;
case IPA_RM_RESOURCE_RELEASED:
pr_debug("%s: %s_PROD resource released\n",
__func__, bam_enable_strings[*cur_bam]);
info.cur_prod_state[*cur_bam] = IPA_RM_RESOURCE_RELEASED;
complete_all(&info.prod_released[*cur_bam]);
break;
default:
break;
}
return;
}
/**
* usb_bam_resume_hsic_host: vote for hsic host core resume.
* In addition also resume all hsic pipes that are connected to
* the ipa peer bam.
*
* NOTE: This function should be called in a context that hold
* usb_bam_lock.
*/
static void usb_bam_resume_hsic_host(void)
{
int i;
struct usb_bam_pipe_connect *pipe_iter;
/* Exit from "full suspend" in case of hsic host */
if (hsic_host_info.dev && info.in_lpm[HSIC_BAM]) {
pr_debug("%s: Getting hsic device %x\n", __func__,
(int)hsic_host_info.dev);
pm_runtime_get(hsic_host_info.dev);
info.in_lpm[HSIC_BAM] = false;
for (i = 0; i < ctx.max_connections; i++) {
pipe_iter = &usb_bam_connections[i];
if (pipe_iter->bam_type == HSIC_BAM &&
pipe_iter->enabled &&
pipe_iter->suspended) {
spin_unlock(&usb_bam_lock);
ipa_resume(pipe_iter->ipa_clnt_hdl);
pipe_iter->suspended = false;
spin_lock(&usb_bam_lock);
}
}
}
}
static int cons_request_resource(enum usb_bam cur_bam)
{
int ret = -EINPROGRESS;
pr_debug("%s: Request %s_CONS resource\n",
__func__, bam_enable_strings[cur_bam]);
spin_lock(&usb_bam_ipa_handshake_info_lock);
info.cur_cons_state[cur_bam] = IPA_RM_RESOURCE_GRANTED;
spin_lock(&usb_bam_lock);
switch (cur_bam) {
case HSUSB_BAM:
if (ctx.pipes_enabled_per_bam[HSUSB_BAM] &&
info.connect_complete &&
!info.cons_stopped && !info.prod_stopped) {
pr_debug("%s: ACK on cons_request", __func__);
ret = 0;
} else if (ctx.pipes_enabled_per_bam[HSUSB_BAM] &&
info.connect_complete && info.bus_suspend) {
info.bus_suspend = 0;
if (info.wake_cb)
info.wake_cb(info.wake_param);
}
break;
case HSIC_BAM:
/*
* Vote for hsic resume, however the core
* resume may not be completed yet or on the other hand
* hsic core might already be resumed, due to a vote
* by other driver, in this case we will just renew our
* vote here.
*/
usb_bam_resume_hsic_host();
/*
* Return sucess if there are pipes connected
* and hsic core is actually not in lpm.
* If in lpm, grant will occur on resume
* finish (see msm_bam_hsic_notify_on_resume)
*/
if (ctx.pipes_enabled_per_bam[cur_bam] &&
!hsic_host_info.in_lpm) {
ret = 0;
}
break;
case SSUSB_BAM:
default:
break;
}
spin_unlock(&usb_bam_ipa_handshake_info_lock);
spin_unlock(&usb_bam_lock);
if (ret == -EINPROGRESS)
pr_debug("%s: EINPROGRESS on cons_request", __func__);
return ret;
}
static int usb_cons_request_resource(void)
{
return cons_request_resource(HSUSB_BAM);
}
static int hsic_cons_request_resource(void)
{
return cons_request_resource(HSIC_BAM);
}
static int cons_release_resource(enum usb_bam cur_bam)
{
pr_debug("%s: Release %s_CONS resource\n",
__func__, bam_enable_strings[cur_bam]);
info.cur_cons_state[cur_bam] = IPA_RM_RESOURCE_RELEASED;
spin_lock(&usb_bam_lock);
if (!ctx.pipes_enabled_per_bam[cur_bam]) {
spin_unlock(&usb_bam_lock);
pr_debug("%s: ACK on cons_release", __func__);
return 0;
}
spin_unlock(&usb_bam_lock);
if (cur_bam == HSUSB_BAM) {
spin_lock(&usb_bam_ipa_handshake_info_lock);
if (info.bus_suspend)
queue_work(ctx.usb_bam_wq, &info.finish_suspend_work);
spin_unlock(&usb_bam_ipa_handshake_info_lock);
pr_debug("%s: EINPROGRESS cons_release", __func__);
return -EINPROGRESS;
} else if (cur_bam == HSIC_BAM) {
/*
* Allow to go to lpm for now. Actual state will be checked
* in msm_bam_hsic_lpm_ok() just before going to lpm.
*/
if (hsic_host_info.dev && !info.in_lpm[HSIC_BAM]) {
pr_debug("%s: Putting hsic device %x\n", __func__,
(int)hsic_host_info.dev);
pm_runtime_put(hsic_host_info.dev);
info.in_lpm[HSIC_BAM] = true;
}
}
return 0;
}
static int hsic_cons_release_resource(void)
{
return cons_release_resource(HSIC_BAM);
}
static int usb_cons_release_resource(void)
{
return cons_release_resource(HSUSB_BAM);
}
static void usb_bam_ipa_create_resources(void)
{
struct ipa_rm_create_params usb_prod_create_params;
struct ipa_rm_create_params usb_cons_create_params;
enum usb_bam cur_bam;
int ret, i;
for (i = 0; i < ARRAY_SIZE(ipa_rm_bams); i++) {
/* Create USB/HSIC_PROD entity */
cur_bam = ipa_rm_bams[i];
memset(&usb_prod_create_params, 0,
sizeof(usb_prod_create_params));
usb_prod_create_params.name = ipa_rm_resource_prod[cur_bam];
usb_prod_create_params.reg_params.notify_cb =
usb_prod_notify_cb;
usb_prod_create_params.reg_params.user_data = &ipa_rm_bams[i];
ret = ipa_rm_create_resource(&usb_prod_create_params);
if (ret) {
pr_err("%s: Failed to create USB_PROD resource\n",
__func__);
return;
}
/* Create USB_CONS entity */
memset(&usb_cons_create_params, 0,
sizeof(usb_cons_create_params));
usb_cons_create_params.name = ipa_rm_resource_cons[cur_bam];
usb_cons_create_params.request_resource =
request_resource_cb[cur_bam];
usb_cons_create_params.release_resource =
release_resource_cb[cur_bam];
ret = ipa_rm_create_resource(&usb_cons_create_params);
if (ret) {
pr_err("%s: Failed to create USB_CONS resource\n",
__func__);
return ;
}
}
}
static void wait_for_prod_granted(enum usb_bam cur_bam)
{
int ret;
pr_debug("%s Request %s_PROD_RES\n", __func__,
bam_enable_strings[cur_bam]);
if (info.cur_cons_state[cur_bam] == IPA_RM_RESOURCE_GRANTED)
pr_debug("%s: CONS already granted for some reason\n",
__func__);
if (info.cur_prod_state[cur_bam] == IPA_RM_RESOURCE_GRANTED)
pr_debug("%s: PROD already granted for some reason\n",
__func__);
init_completion(&info.prod_avail[cur_bam]);
ret = ipa_rm_request_resource(ipa_rm_resource_prod[cur_bam]);
if (!ret) {
info.cur_prod_state[cur_bam] = IPA_RM_RESOURCE_GRANTED;
complete_all(&info.prod_avail[cur_bam]);
pr_debug("%s: PROD_GRANTED without wait\n", __func__);
} else if (ret == -EINPROGRESS) {
pr_debug("%s: Waiting for PROD_GRANTED\n", __func__);
if (!wait_for_completion_timeout(&info.prod_avail[cur_bam],
USB_BAM_TIMEOUT))
pr_err("%s: Timeout wainting for PROD_GRANTED\n",
__func__);
} else
pr_err("%s: ipa_rm_request_resource ret =%d\n", __func__, ret);
}
void notify_usb_connected(enum usb_bam cur_bam)
{
pr_debug("%s: enter\n", __func__);
spin_lock(&usb_bam_ipa_handshake_info_lock);
if (cur_bam == HSUSB_BAM)
info.connect_complete = 1;
spin_unlock(&usb_bam_ipa_handshake_info_lock);
if (info.cur_cons_state[cur_bam] == IPA_RM_RESOURCE_GRANTED) {
pr_debug("%s: Notify %s_CONS_GRANTED\n", __func__,
bam_enable_strings[cur_bam]);
ipa_rm_notify_completion(IPA_RM_RESOURCE_GRANTED,
ipa_rm_resource_cons[cur_bam]);
}
}
static void wait_for_prod_release(enum usb_bam cur_bam)
{
int ret;
if (info.cur_cons_state[cur_bam] == IPA_RM_RESOURCE_RELEASED)
pr_debug("%s consumer already released\n", __func__);
if (info.cur_prod_state[cur_bam] == IPA_RM_RESOURCE_RELEASED)
pr_debug("%s producer already released\n", __func__);
init_completion(&info.prod_released[cur_bam]);
pr_debug("%s: Releasing %s_PROD\n", __func__,
bam_enable_strings[cur_bam]);
ret = ipa_rm_release_resource(ipa_rm_resource_prod[cur_bam]);
if (!ret) {
pr_debug("%s: Released without waiting\n", __func__);
info.cur_prod_state[cur_bam] = IPA_RM_RESOURCE_RELEASED;
complete_all(&info.prod_released[cur_bam]);
} else if (ret == -EINPROGRESS) {
pr_debug("%s: Waiting for PROD_RELEASED\n", __func__);
if (!wait_for_completion_timeout(&info.prod_released[cur_bam],
USB_BAM_TIMEOUT))
pr_err("%s: Timeout waiting for PROD_RELEASED\n",
__func__);
} else
pr_err("%s: ipa_rm_request_resource ret =%d", __func__, ret);
}
static int check_pipes_empty(u8 src_idx, u8 dst_idx)
{
struct sps_pipe *prod_pipe, *cons_pipe;
u32 prod_empty, cons_empty;
/* If we have any remaints in the pipes we don't go to sleep */
prod_pipe = ctx.usb_bam_sps.sps_pipes[src_idx];
cons_pipe = ctx.usb_bam_sps.sps_pipes[dst_idx];
if (sps_is_pipe_empty(prod_pipe, &prod_empty) ||
sps_is_pipe_empty(cons_pipe, &cons_empty)) {
pr_err("%s: sps_is_pipe_empty failed with\n", __func__);
return 0;
}
if (!prod_empty || !cons_empty) {
pr_err("%s: pipes not empty prod=%d cond=%d", __func__,
prod_empty, cons_empty);
return 0;
}
return 1;
}
void usb_bam_suspend(struct usb_bam_connect_ipa_params *ipa_params)
{
struct usb_bam_pipe_connect *pipe_connect;
enum usb_bam cur_bam;
u8 src_idx, dst_idx;
if (!ipa_params) {
pr_err("%s: Invalid ipa params\n", __func__);
return;
}
src_idx = ipa_params->src_idx;
dst_idx = ipa_params->dst_idx;
if (src_idx >= ctx.max_connections || dst_idx >= ctx.max_connections) {
pr_err("%s: Invalid connection index src=%d dst=%d\n",
__func__, src_idx, dst_idx);
}
pipe_connect = &usb_bam_connections[src_idx];
cur_bam = pipe_connect->bam_type;
if (cur_bam != HSUSB_BAM)
return;
info.src_idx = src_idx;
info.dst_idx = dst_idx;
pr_err("%s: Starting suspend sequence(BAM=%s)\n", __func__,
bam_enable_strings[cur_bam]);
spin_lock(&usb_bam_ipa_handshake_info_lock);
info.bus_suspend = 1;
spin_unlock(&usb_bam_ipa_handshake_info_lock);
/* Stop PROD transfers */
if (info.stop) {
spin_lock(&usb_bam_ipa_handshake_info_lock);
info.stop(info.start_stop_param, USB_TO_PEER_PERIPHERAL);
info.prod_stopped = true;
spin_unlock(&usb_bam_ipa_handshake_info_lock);
}
spin_lock(&usb_bam_ipa_handshake_info_lock);
/* If cable was disconnected, let disconnection seq do everything */
if (info.disconnected) {
spin_unlock(&usb_bam_ipa_handshake_info_lock);
pr_debug("%s: Cable disconnected\n", __func__);
return;
}
/* Don't go to LPM if data in the pipes */
if (!check_pipes_empty(src_idx, dst_idx)) {
spin_unlock(&usb_bam_ipa_handshake_info_lock);
pr_err("%s: pipes not empty, won't start suspend", __func__);
return;
}
spin_unlock(&usb_bam_ipa_handshake_info_lock);
queue_work(ctx.usb_bam_wq, &info.suspend_work);
}
static void usb_bam_start_suspend(struct work_struct *w)
{
pr_debug("%s: enter", __func__);
mutex_lock(&info.suspend_resume_mutex);
spin_lock(&usb_bam_ipa_handshake_info_lock);
/* If cable was disconnected, let disconnection seq do everything */
if (info.disconnected) {
spin_unlock(&usb_bam_ipa_handshake_info_lock);
mutex_unlock(&info.suspend_resume_mutex);
pr_debug("%s: Cable disconnected\n", __func__);
return;
}
if (!info.bus_suspend) {
spin_unlock(&usb_bam_ipa_handshake_info_lock);
pr_err("%s: Resume started, not suspending", __func__);
mutex_unlock(&info.suspend_resume_mutex);
return;
}
/* Stop PROD transfers in case they were started */
if (info.stop && !info.prod_stopped) {
info.stop(info.start_stop_param, USB_TO_PEER_PERIPHERAL);
info.prod_stopped = true;
}
spin_unlock(&usb_bam_ipa_handshake_info_lock);
/* Don't start LPM seq if data in the pipes */
if (!check_pipes_empty(info.src_idx, info.dst_idx)) {
mutex_unlock(&info.suspend_resume_mutex);
return;
}
spin_lock(&usb_bam_ipa_handshake_info_lock);
info.lpm_wait_handshake[HSUSB_BAM] = true;
spin_unlock(&usb_bam_ipa_handshake_info_lock);
wait_for_prod_release(HSUSB_BAM);
mutex_unlock(&info.suspend_resume_mutex);
if (info.cur_cons_state[HSUSB_BAM] == IPA_RM_RESOURCE_RELEASED)
usb_bam_finish_suspend();
else
pr_debug("Consumer not released yet\n");
}
static void usb_bam_finish_resume(struct work_struct *w)
{
struct usb_phy *trans = usb_get_transceiver();
BUG_ON(trans == NULL);
pr_debug("%s: enter", __func__);
mutex_lock(&info.suspend_resume_mutex);
/* Suspend happened in the meantime */
spin_lock(&usb_bam_ipa_handshake_info_lock);
if (info.bus_suspend) {
spin_unlock(&usb_bam_ipa_handshake_info_lock);
pr_err("%s: Bus suspended, not resuming", __func__);
mutex_unlock(&info.suspend_resume_mutex);
return;
}
info.lpm_wait_handshake[HSUSB_BAM] = true;
spin_unlock(&usb_bam_ipa_handshake_info_lock);
wait_for_prod_granted(HSUSB_BAM);
notify_usb_connected(HSUSB_BAM);
if (info.cons_stopped) {
ipa_resume_pipes();
if (info.start) {
pr_debug("%s: Enqueue CONS transfer", __func__);
info.start(info.start_stop_param,
PEER_PERIPHERAL_TO_USB);
info.cons_stopped = 0;
}
}
if (info.start) {
spin_lock(&usb_bam_ipa_handshake_info_lock);
info.start(info.start_stop_param, USB_TO_PEER_PERIPHERAL);
info.prod_stopped = false;
spin_unlock(&usb_bam_ipa_handshake_info_lock);
}
if (info.cur_cons_state[HSUSB_BAM] == IPA_RM_RESOURCE_GRANTED) {
pr_debug("%s: Notify CONS_GRANTED\n", __func__);
ipa_rm_notify_completion(IPA_RM_RESOURCE_GRANTED,
ipa_rm_resource_cons[HSUSB_BAM]);
}
mutex_unlock(&info.suspend_resume_mutex);
pr_debug("%s: done", __func__);
}
void usb_bam_resume(struct usb_bam_connect_ipa_params *ipa_params)
{
enum usb_bam cur_bam;
u8 src_idx, dst_idx;
struct usb_bam_pipe_connect *pipe_connect;
pr_debug("%s: Resuming\n", __func__);
if (!ipa_params) {
pr_err("%s: Invalid ipa params\n", __func__);
return;
}
src_idx = ipa_params->src_idx;
dst_idx = ipa_params->dst_idx;
if (src_idx >= ctx.max_connections || dst_idx >= ctx.max_connections) {
pr_err("%s: Invalid connection index src=%d dst=%d\n",
__func__, src_idx, dst_idx);
return;
}
pipe_connect = &usb_bam_connections[src_idx];
cur_bam = pipe_connect->bam_type;
if (cur_bam != HSUSB_BAM)
return;
info.in_lpm[HSUSB_BAM] = false;
spin_lock(&usb_bam_ipa_handshake_info_lock);
info.bus_suspend = 0;
spin_unlock(&usb_bam_ipa_handshake_info_lock);
queue_work(ctx.usb_bam_wq, &info.resume_work);
}
void msm_bam_wait_for_hsic_prod_granted(void)
{
spin_lock(&usb_bam_lock);
ctx.is_bam_inactivity[HSIC_BAM] = false;
/* Get back to resume state including wakeup ipa */
usb_bam_resume_hsic_host();
/* Ensure getting the producer resource */
wait_for_prod_granted(HSIC_BAM);
spin_unlock(&usb_bam_lock);
}
void msm_bam_hsic_notify_on_resume(void)
{
spin_lock(&usb_bam_lock);
hsic_host_info.in_lpm = false;
/* HSIC resume completed. Notify CONS grant if CONS was requested */
notify_usb_connected(HSIC_BAM);
/*
* This function is called to notify the usb bam driver
* that the hsic core and hsic bam hw are fully resumed
* and clocked on. Therefore we can now set the inactivity
* timer to the hsic bam hw.
*/
if (ctx.inactivity_timer_ms[HSIC_BAM])
usb_bam_set_inactivity_timer(HSIC_BAM);
spin_unlock(&usb_bam_lock);
}
bool msm_bam_hsic_lpm_ok(void)
{
int i;
struct usb_bam_pipe_connect *pipe_iter;
if (hsic_host_info.dev) {
pr_debug("%s: Starting hsic full suspend sequence\n",
__func__);
/*
* Start low power mode by releasing the device
* only in case that indeed the resources were released
* and we are still in inactivity state (wake event
* have not been occured while we were waiting to the
* resources release)
*/
spin_lock(&usb_bam_lock);
if (info.cur_cons_state[HSIC_BAM] ==
IPA_RM_RESOURCE_RELEASED &&
info.cur_prod_state[HSIC_BAM] ==
IPA_RM_RESOURCE_RELEASED &&
ctx.is_bam_inactivity[HSIC_BAM] && info.in_lpm[HSIC_BAM]) {
/* HSIC host will go now to lpm */
pr_debug("%s: vote for suspend hsic %x\n",
__func__, (int)hsic_host_info.dev);
for (i = 0; i < ctx.max_connections; i++) {
pipe_iter =
&usb_bam_connections[i];
if (pipe_iter->bam_type == HSIC_BAM &&
pipe_iter->enabled &&
!pipe_iter->suspended) {
spin_unlock(&usb_bam_lock);
ipa_suspend(
pipe_iter->ipa_clnt_hdl);
pipe_iter->suspended = true;
spin_lock(&usb_bam_lock);
}
}
hsic_host_info.in_lpm = true;
spin_unlock(&usb_bam_lock);
return true;
}
/* We don't allow lpm, therefore renew our vote here */
if (info.in_lpm[HSIC_BAM]) {
pr_err("%s: Not allow lpm while ref count=0\n",
__func__);
pr_err("%s: inactivity=%d, c_s=%d p_s=%d lpm=%d\n",
__func__, ctx.is_bam_inactivity[HSIC_BAM],
info.cur_cons_state[HSIC_BAM],
info.cur_prod_state[HSIC_BAM],
info.in_lpm[HSIC_BAM]);
pm_runtime_get(hsic_host_info.dev);
info.in_lpm[HSIC_BAM] = false;
spin_unlock(&usb_bam_lock);
} else
spin_unlock(&usb_bam_lock);
return false;
}
return true;
}
int usb_bam_connect_ipa(struct usb_bam_connect_ipa_params *ipa_params)
{
u8 idx;
enum usb_bam cur_bam;
struct usb_bam_pipe_connect *pipe_connect;
int ret;
struct msm_usb_bam_platform_data *pdata =
ctx.usb_bam_pdev->dev.platform_data;
if (!ipa_params) {
pr_err("%s: Invalid ipa params\n",
__func__);
return -EINVAL;
}
if (ipa_params->dir == USB_TO_PEER_PERIPHERAL)
idx = ipa_params->src_idx;
else
idx = ipa_params->dst_idx;
if (idx >= ctx.max_connections) {
pr_err("%s: Invalid connection index\n",
__func__);
return -EINVAL;
}
pipe_connect = &usb_bam_connections[idx];
cur_bam = pipe_connect->bam_type;
if (pipe_connect->enabled) {
pr_err("%s: connection %d was already established\n",
__func__, idx);
return 0;
}
pr_debug("%s: enter", __func__);
if (cur_bam == HSUSB_BAM) {
mutex_lock(&info.suspend_resume_mutex);
spin_lock(&usb_bam_lock);
if (ctx.pipes_enabled_per_bam[HSUSB_BAM] == 0) {
spin_unlock(&usb_bam_lock);
spin_lock(&usb_bam_ipa_handshake_info_lock);
info.lpm_wait_handshake[HSUSB_BAM] = true;
info.connect_complete = 0;
info.disconnected = 0;
info.pending_lpm = 0;
info.lpm_wait_pipes = 1;
info.bus_suspend = 0;
info.cons_stopped = 0;
info.prod_stopped = 0;
spin_unlock(&usb_bam_ipa_handshake_info_lock);
usb_bam_resume_core(cur_bam);
} else
spin_unlock(&usb_bam_lock);
}
/* Check if BAM requires RESET before connect and reset first pipe */
spin_lock(&usb_bam_lock);
if ((pdata->reset_on_connect[cur_bam] == true) &&
(ctx.pipes_enabled_per_bam[cur_bam] == 0)) {
spin_unlock(&usb_bam_lock);
sps_device_reset(ctx.h_bam[cur_bam]);
/* On re-connect assume out from lpm for HSIC BAM */
if (cur_bam == HSIC_BAM && hsic_host_info.dev &&
info.in_lpm[HSIC_BAM]) {
pr_debug("%s: Getting hsic device %x\n",
__func__, (int)hsic_host_info.dev);
pm_runtime_get(hsic_host_info.dev);
}
/* On re-connect assume out from lpm for all BAMs */
info.in_lpm[cur_bam] = false;
} else
spin_unlock(&usb_bam_lock);
if (ipa_params->dir == USB_TO_PEER_PERIPHERAL) {
pr_debug("%s: Starting connect sequence\n", __func__);
wait_for_prod_granted(cur_bam);
}
ret = connect_pipe_ipa(idx, ipa_params);
if (ret) {
pr_err("%s: pipe connection failure\n", __func__);
if (cur_bam == HSUSB_BAM)
mutex_unlock(&info.suspend_resume_mutex);
return ret;
}
spin_lock(&usb_bam_lock);
pipe_connect->enabled = 1;
pipe_connect->suspended = 0;
/* Set global inactivity timer upon first pipe connection */
if (ctx.pipes_enabled_per_bam[pipe_connect->bam_type] == 0 &&
ctx.inactivity_timer_ms[pipe_connect->bam_type] &&
pipe_connect->inactivity_notify)
usb_bam_set_inactivity_timer(pipe_connect->bam_type);
ctx.pipes_enabled_per_bam[cur_bam] += 1;
spin_unlock(&usb_bam_lock);
if (ipa_params->dir == PEER_PERIPHERAL_TO_USB)
notify_usb_connected(cur_bam);
if (cur_bam == HSUSB_BAM)
mutex_unlock(&info.suspend_resume_mutex);
pr_debug("%s: done", __func__);
return 0;
}
EXPORT_SYMBOL(usb_bam_connect_ipa);
int usb_bam_client_ready(bool ready)
{
spin_lock(&usb_bam_peer_handshake_info_lock);
if (peer_handshake_info.client_ready == ready) {
pr_debug("%s: client state is already %d\n",
__func__, ready);
spin_unlock(&usb_bam_peer_handshake_info_lock);
return 0;
}
peer_handshake_info.client_ready = ready;
if (peer_handshake_info.state == USB_BAM_SM_PLUG_ACKED && !ready) {
pr_debug("Starting reset sequence");
INIT_COMPLETION(ctx.reset_done);
}
spin_unlock(&usb_bam_peer_handshake_info_lock);
if (!queue_work(ctx.usb_bam_wq,
&peer_handshake_info.reset_event.event_w)) {
spin_lock(&usb_bam_peer_handshake_info_lock);
peer_handshake_info.pending_work++;
spin_unlock(&usb_bam_peer_handshake_info_lock);
}
return 0;
}
static void usb_bam_work(struct work_struct *w)
{
int i;
struct usb_bam_event_info *event_info =
container_of(w, struct usb_bam_event_info, event_w);
struct usb_bam_pipe_connect *pipe_connect =
container_of(event_info, struct usb_bam_pipe_connect, event);
struct usb_bam_pipe_connect *pipe_iter;
int (*callback)(void *priv);
void *param = NULL;
switch (event_info->type) {
case USB_BAM_EVENT_WAKEUP:
case USB_BAM_EVENT_WAKEUP_PIPE:
pr_debug("%s recieved USB_BAM_EVENT_WAKEUP\n", __func__);
/*
* Make sure the PROD resource is granted before
* wakeup hsic host class driver (done by the callback below)
*/
if (pipe_connect->peer_bam == IPA_P_BAM &&
pipe_connect->bam_type == HSIC_BAM &&
info.cur_prod_state[HSIC_BAM] != IPA_RM_RESOURCE_GRANTED) {
wait_for_prod_granted(HSIC_BAM);
}
/*
* Check if need to resume the hsic host.
* On one hand, since we got the wakeup interrupt
* the hsic bam clocks are already enabled, so no need
* to actualluy resume the hardware... However, we still need
* to update the usb bam driver state (to set in_lpm=false),
* and to wake ipa (ipa_resume) and to hold again the hsic host
* device again to avoid it going to low poer mode next time
* until we complete releasing the hsic consumer and producer
* resources against the ipa resource manager.
*/
spin_lock(&usb_bam_lock);
if (pipe_connect->bam_type == HSIC_BAM)
usb_bam_resume_hsic_host();
spin_unlock(&usb_bam_lock);
/* Notify about wakeup / activity of the bam */
if (event_info->callback)
event_info->callback(event_info->param);
/*
* Reset inactivity timer counter if this pipe's bam
* has inactivity timeout.
*/
spin_lock(&usb_bam_lock);
if (ctx.inactivity_timer_ms[pipe_connect->bam_type])
usb_bam_set_inactivity_timer(pipe_connect->bam_type);
spin_unlock(&usb_bam_lock);
if (pipe_connect->bam_type == HSUSB_BAM) {
/* A2 wakeup not from LPM (CONS was up) */
wait_for_prod_granted(pipe_connect->bam_type);
if (info.start) {
pr_debug("%s: Enqueue PROD transfer", __func__);
info.start(info.start_stop_param,
USB_TO_PEER_PERIPHERAL);
}
}
break;
case USB_BAM_EVENT_INACTIVITY:
pr_debug("%s recieved USB_BAM_EVENT_INACTIVITY\n", __func__);
/*
* Since event info is one structure per pipe, it might be
* overriden when we will register the wakeup events below,
* and still we want ot register the wakeup events before we
* notify on the inactivity in order to identify the next
* activity as soon as possible.
*/
callback = event_info->callback;
param = event_info->param;
/*
* Upon inactivity, configure wakeup irq for all pipes
* that are into the usb bam.
*/
spin_lock(&usb_bam_lock);
for (i = 0; i < ctx.max_connections; i++) {
pipe_iter = &usb_bam_connections[i];
if (pipe_iter->bam_type ==
pipe_connect->bam_type &&
pipe_iter->dir ==
PEER_PERIPHERAL_TO_USB &&
pipe_iter->enabled) {
pr_debug("%s: Register wakeup on pipe %x\n",
__func__, (int)pipe_iter);
__usb_bam_register_wake_cb(i,
pipe_iter->activity_notify,
pipe_iter->priv,
false);
}
}
spin_unlock(&usb_bam_lock);
/* Notify about the inactivity to the USB class driver */
if (callback)
callback(param);
wait_for_prod_release(pipe_connect->bam_type);
pr_debug("%s: complete wait on hsic producer s=%d\n",
__func__, info.cur_prod_state[pipe_connect->bam_type]);
/*
* Allow to go to lpm for now if also consumer is down.
* If consumer is up, we will wait to the release consumer
* notification.
*/
if (hsic_host_info.dev &&
info.cur_cons_state[HSIC_BAM] ==
IPA_RM_RESOURCE_RELEASED && !info.in_lpm[HSIC_BAM]) {
pr_debug("%s: Putting hsic device %x\n", __func__,
(int)hsic_host_info.dev);
pm_runtime_put(hsic_host_info.dev);
info.in_lpm[HSIC_BAM] = true;
}
break;
default:
pr_err("%s: unknown usb bam event type %d\n", __func__,
event_info->type);
}
}
static void usb_bam_wake_cb(struct sps_event_notify *notify)
{
struct usb_bam_event_info *event_info =
(struct usb_bam_event_info *)notify->user;
struct usb_bam_pipe_connect *pipe_connect =
container_of(event_info,
struct usb_bam_pipe_connect,
event);
enum usb_bam bam = pipe_connect->bam_type;
spin_lock(&usb_bam_lock);
if (event_info->type == USB_BAM_EVENT_WAKEUP_PIPE)
queue_work(ctx.usb_bam_wq, &event_info->event_w);
else if (event_info->type == USB_BAM_EVENT_WAKEUP &&
ctx.is_bam_inactivity[bam]) {
/*
* Sps wake event is per pipe, so usb_bam_wake_cb is
* called per pipe. However, we want to filter the wake
* event to be wake event per all the pipes.
* Therefore, the first pipe that awaked will be considered
* as global bam wake event.
*/
ctx.is_bam_inactivity[bam] = false;
queue_work(ctx.usb_bam_wq, &event_info->event_w);
}
spin_unlock(&usb_bam_lock);
}
static void usb_bam_sm_work(struct work_struct *w)
{
pr_debug("%s: current state: %d\n", __func__,
peer_handshake_info.state);
spin_lock(&usb_bam_peer_handshake_info_lock);
switch (peer_handshake_info.state) {
case USB_BAM_SM_INIT:
if (peer_handshake_info.client_ready) {
spin_unlock(&usb_bam_peer_handshake_info_lock);
smsm_change_state(SMSM_APPS_STATE, 0,
SMSM_USB_PLUG_UNPLUG);
spin_lock(&usb_bam_peer_handshake_info_lock);
peer_handshake_info.state = USB_BAM_SM_PLUG_NOTIFIED;
}
break;
case USB_BAM_SM_PLUG_NOTIFIED:
if (peer_handshake_info.ack_received) {
peer_handshake_info.state = USB_BAM_SM_PLUG_ACKED;
peer_handshake_info.ack_received = 0;
}
break;
case USB_BAM_SM_PLUG_ACKED:
if (!peer_handshake_info.client_ready) {
spin_unlock(&usb_bam_peer_handshake_info_lock);
pr_debug("Starting A2 reset sequence");
smsm_change_state(SMSM_APPS_STATE,
SMSM_USB_PLUG_UNPLUG, 0);
spin_lock(&usb_bam_peer_handshake_info_lock);
peer_handshake_info.state = USB_BAM_SM_UNPLUG_NOTIFIED;
}
break;
case USB_BAM_SM_UNPLUG_NOTIFIED:
if (peer_handshake_info.ack_received) {
spin_unlock(&usb_bam_peer_handshake_info_lock);
peer_handshake_info.reset_event.
callback(peer_handshake_info.reset_event.param);
spin_lock(&usb_bam_peer_handshake_info_lock);
complete_all(&ctx.reset_done);
pr_debug("Finished reset sequence");
peer_handshake_info.state = USB_BAM_SM_INIT;
peer_handshake_info.ack_received = 0;
}
break;
}
if (peer_handshake_info.pending_work) {
peer_handshake_info.pending_work--;
spin_unlock(&usb_bam_peer_handshake_info_lock);
queue_work(ctx.usb_bam_wq,
&peer_handshake_info.reset_event.event_w);
spin_lock(&usb_bam_peer_handshake_info_lock);
}
spin_unlock(&usb_bam_peer_handshake_info_lock);
}
static void usb_bam_ack_toggle_cb(void *priv,
uint32_t old_state, uint32_t new_state)
{
static int last_processed_state;
int current_state;
spin_lock(&usb_bam_peer_handshake_info_lock);
current_state = new_state & SMSM_USB_PLUG_UNPLUG;
if (current_state == last_processed_state) {
spin_unlock(&usb_bam_peer_handshake_info_lock);
return;
}
last_processed_state = current_state;
peer_handshake_info.ack_received = true;
spin_unlock(&usb_bam_peer_handshake_info_lock);
if (!queue_work(ctx.usb_bam_wq,
&peer_handshake_info.reset_event.event_w)) {
spin_lock(&usb_bam_peer_handshake_info_lock);
peer_handshake_info.pending_work++;
spin_unlock(&usb_bam_peer_handshake_info_lock);
}
}
static int __usb_bam_register_wake_cb(u8 idx, int (*callback)(void *user),
void *param, bool trigger_cb_per_pipe)
{
struct sps_pipe *pipe = ctx.usb_bam_sps.sps_pipes[idx];
struct sps_connect *sps_connection;
struct usb_bam_pipe_connect *pipe_connect;
struct usb_bam_event_info *wake_event_info;
int ret;
if (idx < 0 || idx > ctx.max_connections) {
pr_err("%s:idx is wrong %d", __func__, idx);
return -EINVAL;
}
pipe = ctx.usb_bam_sps.sps_pipes[idx];
sps_connection = &ctx.usb_bam_sps.sps_connections[idx];
pipe_connect = &usb_bam_connections[idx];
wake_event_info = &pipe_connect->event;
wake_event_info->type = (trigger_cb_per_pipe ?
USB_BAM_EVENT_WAKEUP_PIPE :
USB_BAM_EVENT_WAKEUP);
wake_event_info->param = param;
wake_event_info->callback = callback;
wake_event_info->event.mode = SPS_TRIGGER_CALLBACK;
wake_event_info->event.xfer_done = NULL;
wake_event_info->event.callback = callback ? usb_bam_wake_cb : NULL;
wake_event_info->event.user = wake_event_info;
wake_event_info->event.options = SPS_O_WAKEUP;
ret = sps_register_event(pipe, &wake_event_info->event);
if (ret) {
pr_err("%s: sps_register_event() failed %d\n", __func__, ret);
return ret;
}
sps_connection->options = callback ?
(SPS_O_AUTO_ENABLE | SPS_O_WAKEUP | SPS_O_WAKEUP_IS_ONESHOT) :
SPS_O_AUTO_ENABLE;
ret = sps_set_config(pipe, sps_connection);
if (ret) {
pr_err("%s: sps_set_config() failed %d\n", __func__, ret);
return ret;
}
return 0;
}
int usb_bam_register_wake_cb(u8 idx, int (*callback)(void *user),
void *param)
{
info.wake_cb = callback;
info.wake_param = param;
return __usb_bam_register_wake_cb(idx, callback, param, true);
}
int usb_bam_register_start_stop_cbs(
void (*start)(void *, enum usb_bam_pipe_dir),
void (*stop)(void *, enum usb_bam_pipe_dir),
void *param)
{
info.start = start;
info.stop = stop;
info.start_stop_param = param;
return 0;
}
int usb_bam_register_peer_reset_cb(int (*callback)(void *), void *param)
{
u32 ret = 0;
if (callback) {
peer_handshake_info.reset_event.param = param;
peer_handshake_info.reset_event.callback = callback;
ret = smsm_state_cb_register(SMSM_MODEM_STATE,
SMSM_USB_PLUG_UNPLUG, usb_bam_ack_toggle_cb, NULL);
if (ret) {
pr_err("%s: failed to register SMSM callback\n",
__func__);
} else {
if (smsm_get_state(SMSM_MODEM_STATE) &
SMSM_USB_PLUG_UNPLUG)
usb_bam_ack_toggle_cb(NULL, 0,
SMSM_USB_PLUG_UNPLUG);
}
} else {
peer_handshake_info.reset_event.param = NULL;
peer_handshake_info.reset_event.callback = NULL;
smsm_state_cb_deregister(SMSM_MODEM_STATE,
SMSM_USB_PLUG_UNPLUG, usb_bam_ack_toggle_cb, NULL);
}
return ret;
}
int usb_bam_disconnect_pipe(u8 idx)
{
struct usb_bam_pipe_connect *pipe_connect;
int ret;
pipe_connect = &usb_bam_connections[idx];
if (!pipe_connect->enabled) {
pr_err("%s: connection %d isn't enabled\n",
__func__, idx);
return 0;
}
ret = disconnect_pipe(idx);
if (ret) {
pr_err("%s: src pipe disconnection failure\n", __func__);
return ret;
}
pipe_connect->enabled = 0;
spin_lock(&usb_bam_lock);
if (ctx.pipes_enabled_per_bam[pipe_connect->bam_type] == 0)
pr_err("%s: wrong pipes enabled counter for bam_type=%d\n",
__func__, pipe_connect->bam_type);
else
ctx.pipes_enabled_per_bam[pipe_connect->bam_type] -= 1;
spin_unlock(&usb_bam_lock);
return 0;
}
int usb_bam_disconnect_ipa(struct usb_bam_connect_ipa_params *ipa_params)
{
int ret;
u8 idx;
struct usb_bam_pipe_connect *pipe_connect;
struct sps_connect *sps_connection;
enum usb_bam cur_bam;
if (!ipa_params->prod_clnt_hdl && !ipa_params->cons_clnt_hdl) {
pr_err("%s: Both of the handles is missing\n", __func__);
return -EINVAL;
}
pr_debug("%s: Starting disconnect sequence\n", __func__);
mutex_lock(&info.suspend_resume_mutex);
/* Delay USB core to go into lpm before we finish our handshake */
if (ipa_params->prod_clnt_hdl) {
idx = ipa_params->dst_idx;
pipe_connect = &usb_bam_connections[idx];
pipe_connect->activity_notify = NULL;
pipe_connect->inactivity_notify = NULL;
pipe_connect->priv = NULL;
/* Do the release handshake with the A2 via RM */
cur_bam = pipe_connect->bam_type;
spin_lock(&usb_bam_ipa_handshake_info_lock);
if (cur_bam == HSUSB_BAM) {
info.connect_complete = 0;
info.lpm_wait_pipes = 1;
info.disconnected = 1;
}
spin_unlock(&usb_bam_ipa_handshake_info_lock);
wait_for_prod_release(cur_bam);
/* close USB -> IPA pipe */
usb_bam_resume_core(cur_bam);
ret = ipa_disconnect(ipa_params->prod_clnt_hdl);
if (ret) {
pr_err("%s: dst pipe disconnection failure\n",
__func__);
mutex_unlock(&info.suspend_resume_mutex);
return ret;
}
sps_connection = &ctx.usb_bam_sps.sps_connections[idx];
sps_connection->data.phys_base = 0;
sps_connection->desc.phys_base = 0;
ret = usb_bam_disconnect_pipe(idx);
if (ret) {
pr_err("%s: failure to disconnect pipe %d\n",
__func__, idx);
mutex_unlock(&info.suspend_resume_mutex);
return ret;
}
}
if (ipa_params->cons_clnt_hdl) {
idx = ipa_params->src_idx;
pipe_connect = &usb_bam_connections[idx];
pipe_connect->activity_notify = NULL;
pipe_connect->inactivity_notify = NULL;
pipe_connect->priv = NULL;
cur_bam = pipe_connect->bam_type;
/* close IPA -> USB pipe */
ret = ipa_disconnect(ipa_params->cons_clnt_hdl);
if (ret) {
pr_err("%s: src pipe disconnection failure\n",
__func__);
mutex_unlock(&info.suspend_resume_mutex);
return ret;
}
sps_connection = &ctx.usb_bam_sps.sps_connections[idx];
sps_connection->data.phys_base = 0;
sps_connection->desc.phys_base = 0;
ret = usb_bam_disconnect_pipe(idx);
if (ret) {
pr_err("%s: failure to disconnect pipe %d\n",
__func__, idx);
mutex_unlock(&info.suspend_resume_mutex);
return ret;
}
pipe_connect->ipa_clnt_hdl = -1;
if (info.cur_cons_state[cur_bam] == IPA_RM_RESOURCE_RELEASED) {
pr_debug("%s Notify CONS _RELEASED\n", __func__);
ipa_rm_notify_completion(IPA_RM_RESOURCE_RELEASED,
ipa_rm_resource_cons[cur_bam]);
}
if (cur_bam == HSUSB_BAM) {
/*
* Currently we have for HSUSB BAM only one consumer
* pipe. Therefore ending disconnect sequence and
* starting hsusb lpm. This limitation will be changed
* in future patch.
*/
pr_debug("%s Ended disconnect sequence\n", __func__);
usb_bam_start_lpm(1);
}
mutex_unlock(&info.suspend_resume_mutex);
return 0;
}
mutex_unlock(&info.suspend_resume_mutex);
return 0;
}
EXPORT_SYMBOL(usb_bam_disconnect_ipa);
void usb_bam_reset_complete(void)
{
pr_debug("Waiting for reset compelte");
if (wait_for_completion_interruptible_timeout(&ctx.reset_done,
10*HZ) <= 0)
pr_warn("Timeout while waiting for reset");
pr_debug("Finished Waiting for reset complete");
}
int usb_bam_a2_reset(bool to_reconnect)
{
struct usb_bam_pipe_connect *pipe_connect;
int i;
int ret = 0, ret_int;
u8 bam = -1;
int reconnect_pipe_idx[ctx.max_connections];
for (i = 0; i < ctx.max_connections; i++)
reconnect_pipe_idx[i] = -1;
/* Disconnect a2 pipes */
for (i = 0; i < ctx.max_connections; i++) {
pipe_connect = &usb_bam_connections[i];
if (strnstr(pipe_connect->name, "a2", USB_BAM_MAX_STR_LEN) &&
pipe_connect->enabled) {
if (pipe_connect->dir == USB_TO_PEER_PERIPHERAL)
reconnect_pipe_idx[i] =
pipe_connect->src_pipe_index;
else
reconnect_pipe_idx[i] =
pipe_connect->dst_pipe_index;
bam = pipe_connect->bam_type;
if (bam < 0) {
ret = -EINVAL;
continue;
}
ret_int = usb_bam_disconnect_pipe(i);
if (ret_int) {
pr_err("%s: failure to connect pipe %d\n",
__func__, i);
ret = ret_int;
continue;
}
}
}
/* Reset A2 (USB/HSIC) BAM */
if (bam != -1 && sps_device_reset(ctx.h_bam[bam]))
pr_err("%s: BAM reset failed\n", __func__);
if (!to_reconnect)
return ret;
/* Reconnect A2 pipes */
for (i = 0; i < ctx.max_connections; i++) {
pipe_connect = &usb_bam_connections[i];
if (reconnect_pipe_idx[i] != -1) {
ret_int = usb_bam_connect(i, &reconnect_pipe_idx[i]);
if (ret_int) {
pr_err("%s: failure to reconnect pipe %d\n",
__func__, i);
ret = ret_int;
continue;
}
}
}
return ret;
}
static void usb_bam_sps_events(enum sps_callback_case sps_cb_case, void *user)
{
int i;
enum usb_bam bam;
struct usb_bam_pipe_connect *pipe_connect;
struct usb_bam_event_info *event_info;
switch (sps_cb_case) {
case SPS_CALLBACK_BAM_TIMER_IRQ:
pr_debug("%s:recieved SPS_CALLBACK_BAM_TIMER_IRQ\n", __func__);
spin_lock(&usb_bam_lock);
bam = get_bam_type_from_core_name((char *)user);
ctx.is_bam_inactivity[bam] = true;
pr_debug("%s: Incativity happened on bam=%s,%d\n", __func__,
(char *)user, bam);
for (i = 0; i < ctx.max_connections; i++) {
pipe_connect = &usb_bam_connections[i];
/*
* Notify inactivity once, Since it is global
* for all pipes on bam. Notify only if we have
* connected pipes.
*/
if (pipe_connect->bam_type == bam &&
pipe_connect->enabled) {
event_info = &pipe_connect->event;
event_info->type = USB_BAM_EVENT_INACTIVITY;
event_info->param = pipe_connect->priv;
event_info->callback =
pipe_connect->inactivity_notify;
queue_work(ctx.usb_bam_wq,
&event_info->event_w);
break;
}
}
spin_unlock(&usb_bam_lock);
break;
default:
pr_debug("%s:received sps_cb_case=%d\n", __func__,
(int)sps_cb_case);
}
}
static struct msm_usb_bam_platform_data *usb_bam_dt_to_pdata(
struct platform_device *pdev)
{
struct msm_usb_bam_platform_data *pdata;
struct device_node *node = pdev->dev.of_node;
int rc = 0;
u8 i = 0;
bool reset_bam;
enum usb_bam bam;
u32 addr;
ctx.max_connections = 0;
pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata) {
pr_err("unable to allocate platform data\n");
return NULL;
}
rc = of_property_read_u32(node, "qcom,usb-bam-num-pipes",
&pdata->usb_bam_num_pipes);
if (rc) {
pr_err("Invalid usb bam num pipes property\n");
return NULL;
}
rc = of_property_read_u32(node, "qcom,usb-bam-fifo-baseaddr",
&addr);
if (rc)
pr_debug("%s: Invalid usb base address property\n", __func__);
else
pdata->usb_bam_fifo_baseaddr = addr;
pdata->ignore_core_reset_ack = of_property_read_bool(node,
"qcom,ignore-core-reset-ack");
pdata->disable_clk_gating = of_property_read_bool(node,
"qcom,disable-clk-gating");
for_each_child_of_node(pdev->dev.of_node, node)
ctx.max_connections++;
if (!ctx.max_connections) {
pr_err("%s: error: max_connections is zero\n", __func__);
goto err;
}
usb_bam_connections = devm_kzalloc(&pdev->dev, ctx.max_connections *
sizeof(struct usb_bam_pipe_connect), GFP_KERNEL);
if (!usb_bam_connections) {
pr_err("%s: devm_kzalloc failed(%d)\n", __func__, __LINE__);
return NULL;
}
/* retrieve device tree parameters */
for_each_child_of_node(pdev->dev.of_node, node) {
rc = of_property_read_string(node, "label",
&usb_bam_connections[i].name);
if (rc)
goto err;
rc = of_property_read_u32(node, "qcom,usb-bam-mem-type",
&usb_bam_connections[i].mem_type);
if (rc)
goto err;
if (usb_bam_connections[i].mem_type == USB_PRIVATE_MEM ||
usb_bam_connections[i].mem_type == OCI_MEM) {
if (!pdata->usb_bam_fifo_baseaddr) {
pr_err("%s: base address is missing\n",
__func__);
goto err;
}
}
rc = of_property_read_u32(node, "qcom,bam-type",
&usb_bam_connections[i].bam_type);
if (rc) {
pr_err("%s: bam type is missing in device tree\n",
__func__);
goto err;
}
bam = usb_bam_connections[i].bam_type;
rc = of_property_read_u32(node, "qcom,peer-bam",
&usb_bam_connections[i].peer_bam);
if (rc) {
pr_err("%s: peer bam is missing in device tree\n",
__func__);
goto err;
}
rc = of_property_read_u32(node, "qcom,dir",
&usb_bam_connections[i].dir);
if (rc) {
pr_err("%s: direction is missing in device tree\n",
__func__);
goto err;
}
rc = of_property_read_u32(node, "qcom,pipe-num",
&usb_bam_connections[i].pipe_num);
if (rc) {
pr_err("%s: pipe num is missing in device tree\n",
__func__);
goto err;
}
reset_bam = of_property_read_bool(node,
"qcom,reset-bam-on-connect");
if (reset_bam)
pdata->reset_on_connect[bam] = true;
of_property_read_u32(node, "qcom,src-bam-physical-address",
&usb_bam_connections[i].src_phy_addr);
of_property_read_u32(node, "qcom,src-bam-pipe-index",
&usb_bam_connections[i].src_pipe_index);
of_property_read_u32(node, "qcom,dst-bam-physical-address",
&usb_bam_connections[i].dst_phy_addr);
of_property_read_u32(node, "qcom,dst-bam-pipe-index",
&usb_bam_connections[i].dst_pipe_index);
of_property_read_u32(node, "qcom,data-fifo-offset",
&usb_bam_connections[i].data_fifo_base_offset);
rc = of_property_read_u32(node, "qcom,data-fifo-size",
&usb_bam_connections[i].data_fifo_size);
if (rc)
goto err;
of_property_read_u32(node, "qcom,descriptor-fifo-offset",
&usb_bam_connections[i].desc_fifo_base_offset);
rc = of_property_read_u32(node, "qcom,descriptor-fifo-size",
&usb_bam_connections[i].desc_fifo_size);
if (rc)
goto err;
i++;
}
pdata->connections = usb_bam_connections;
return pdata;
err:
pr_err("%s: failed\n", __func__);
return NULL;
}
static int usb_bam_init(int bam_idx)
{
int ret, irq;
void *usb_virt_addr;
struct msm_usb_bam_platform_data *pdata =
ctx.usb_bam_pdev->dev.platform_data;
struct resource *res, *ram_resource;
struct sps_bam_props props = ctx.usb_bam_sps.usb_props;
pr_debug("%s: usb_bam_init - %s\n", __func__,
bam_enable_strings[bam_idx]);
res = platform_get_resource_byname(ctx.usb_bam_pdev, IORESOURCE_MEM,
bam_enable_strings[bam_idx]);
if (!res) {
dev_dbg(&ctx.usb_bam_pdev->dev, "bam not initialized\n");
return 0;
}
irq = platform_get_irq_byname(ctx.usb_bam_pdev,
bam_enable_strings[bam_idx]);
if (irq < 0) {
dev_err(&ctx.usb_bam_pdev->dev, "Unable to get IRQ resource\n");
return irq;
}
usb_virt_addr = devm_ioremap(&ctx.usb_bam_pdev->dev, res->start,
resource_size(res));
if (!usb_virt_addr) {
pr_err("%s: ioremap failed\n", __func__);
return -ENOMEM;
}
/* Check if USB3 pipe memory needs to be enabled */
if (bam_idx == SSUSB_BAM && bam_use_private_mem(bam_idx)) {
pr_debug("%s: Enabling USB private memory for: %s\n", __func__,
bam_enable_strings[bam_idx]);
ram_resource = platform_get_resource_byname(ctx.usb_bam_pdev,
IORESOURCE_MEM, "qscratch_ram1_reg");
if (!res) {
dev_err(&ctx.usb_bam_pdev->dev, "Unable to get qscratch\n");
ret = -ENODEV;
goto free_bam_regs;
}
ctx.qscratch_ram1_reg = devm_ioremap(&ctx.usb_bam_pdev->dev,
ram_resource->start,
resource_size(ram_resource));
if (!ctx.qscratch_ram1_reg) {
pr_err("%s: ioremap failed for qscratch\n", __func__);
ret = -ENOMEM;
goto free_bam_regs;
}
}
props.phys_addr = res->start;
props.virt_addr = usb_virt_addr;
props.virt_size = resource_size(res);
props.irq = irq;
props.summing_threshold = USB_THRESHOLD;
props.event_threshold = USB_THRESHOLD;
props.num_pipes = pdata->usb_bam_num_pipes;
props.callback = usb_bam_sps_events;
props.user = bam_enable_strings[bam_idx];
props.options = SPS_BAM_OPT_IRQ_WAKEUP;
/*
* HSUSB and HSIC Cores don't support RESET ACK signal to BAMs
* Hence, let BAM to ignore acknowledge from USB while resetting PIPE
*/
if (pdata->ignore_core_reset_ack && bam_idx != SSUSB_BAM)
props.options = SPS_BAM_NO_EXT_P_RST;
if (pdata->disable_clk_gating)
props.options |= SPS_BAM_NO_LOCAL_CLK_GATING;
ret = sps_register_bam_device(&props, &(ctx.h_bam[bam_idx]));
if (ret < 0) {
pr_err("%s: register bam error %d\n", __func__, ret);
ret = -EFAULT;
goto free_qscratch_reg;
}
return 0;
free_qscratch_reg:
iounmap(ctx.qscratch_ram1_reg);
free_bam_regs:
iounmap(usb_virt_addr);
return ret;
}
static int enable_usb_bams(struct platform_device *pdev)
{
int ret, i;
for (i = 0; i < ARRAY_SIZE(bam_enable_strings); i++) {
ret = usb_bam_init(i);
if (ret) {
pr_err("failed to init usb bam %s\n",
bam_enable_strings[i]);
return ret;
}
}
ctx.usb_bam_sps.sps_pipes = devm_kzalloc(&pdev->dev,
ctx.max_connections * sizeof(struct sps_pipe *),
GFP_KERNEL);
if (!ctx.usb_bam_sps.sps_pipes) {
pr_err("%s: failed to allocate sps_pipes\n", __func__);
return -ENOMEM;
}
ctx.usb_bam_sps.sps_connections = devm_kzalloc(&pdev->dev,
ctx.max_connections * sizeof(struct sps_connect),
GFP_KERNEL);
if (!ctx.usb_bam_sps.sps_connections) {
pr_err("%s: failed to allocate sps_connections\n", __func__);
return -ENOMEM;
}
return 0;
}
static ssize_t
usb_bam_show_inactivity_timer(struct device *dev, struct device_attribute *attr,
char *buf)
{
char *buff = buf;
int i;
spin_lock(&usb_bam_lock);
for (i = 0; i < ARRAY_SIZE(bam_enable_strings); i++) {
buff += snprintf(buff, PAGE_SIZE, "%s: %dms\n",
bam_enable_strings[i],
ctx.inactivity_timer_ms[i]);
}
spin_unlock(&usb_bam_lock);
return buff - buf;
}
static ssize_t usb_bam_store_inactivity_timer(struct device *dev,
struct device_attribute *attr,
const char *buff, size_t count)
{
char buf[USB_BAM_MAX_STR_LEN];
char *trimmed_buf, *bam_str, *bam_name, *timer;
int timer_d;
enum usb_bam bam;
if (strnstr(buff, "help", USB_BAM_MAX_STR_LEN)) {
pr_info("Usage: <bam_name> <ms>,<bam_name> <ms>,...\n");
pr_info("\tbam_name: [%s, %s, %s]\n",
bam_enable_strings[SSUSB_BAM],
bam_enable_strings[HSUSB_BAM],
bam_enable_strings[HSIC_BAM]);
pr_info("\tms: time in ms. Use 0 to disable timer\n");
return count;
}
strlcpy(buf, buff, sizeof(buf));
trimmed_buf = strim(buf);
while (trimmed_buf) {
bam_str = strsep(&trimmed_buf, ",");
if (bam_str) {
bam_name = strsep(&bam_str, " ");
bam = get_bam_type_from_core_name(bam_name);
timer = strsep(&bam_str, " ");
sscanf(timer, "%d", &timer_d);
spin_lock(&usb_bam_lock);
/* Apply new timer setting if bam has running pipes */
if (ctx.inactivity_timer_ms[bam] != timer_d) {
ctx.inactivity_timer_ms[bam] = timer_d;
if (ctx.pipes_enabled_per_bam[bam] > 0 &&
!info.in_lpm[bam])
usb_bam_set_inactivity_timer(bam);
}
spin_unlock(&usb_bam_lock);
}
}
return count;
}
static DEVICE_ATTR(inactivity_timer, S_IWUSR | S_IRUSR,
usb_bam_show_inactivity_timer,
usb_bam_store_inactivity_timer);
static int usb_bam_probe(struct platform_device *pdev)
{
int ret, i;
struct msm_usb_bam_platform_data *pdata;
dev_dbg(&pdev->dev, "usb_bam_probe\n");
ret = device_create_file(&pdev->dev, &dev_attr_inactivity_timer);
if (ret) {
dev_err(&pdev->dev, "failed to create fs node\n");
return ret;
}
ctx.mem_clk = devm_clk_get(&pdev->dev, "mem_clk");
if (IS_ERR(ctx.mem_clk))
dev_dbg(&pdev->dev, "failed to get mem_clock\n");
ctx.mem_iface_clk = devm_clk_get(&pdev->dev, "mem_iface_clk");
if (IS_ERR(ctx.mem_iface_clk))
dev_dbg(&pdev->dev, "failed to get mem_iface_clock\n");
if (pdev->dev.of_node) {
dev_dbg(&pdev->dev, "device tree enabled\n");
pdata = usb_bam_dt_to_pdata(pdev);
if (!pdata)
return -EINVAL;
pdev->dev.platform_data = pdata;
} else if (!pdev->dev.platform_data) {
dev_err(&pdev->dev, "missing platform_data\n");
return -ENODEV;
} else {
pdata = pdev->dev.platform_data;
usb_bam_connections = pdata->connections;
ctx.max_connections = pdata->max_connections;
}
ctx.usb_bam_pdev = pdev;
for (i = 0; i < ctx.max_connections; i++) {
usb_bam_connections[i].enabled = 0;
INIT_WORK(&usb_bam_connections[i].event.event_w,
usb_bam_work);
}
for (i = 0; i < MAX_BAMS; i++) {
ctx.pipes_enabled_per_bam[i] = 0;
ctx.inactivity_timer_ms[i] = 0;
ctx.is_bam_inactivity[i] = false;
init_completion(&info.prod_avail[i]);
complete(&info.prod_avail[i]);
init_completion(&info.prod_released[i]);
complete(&info.prod_released[i]);
info.cur_prod_state[i] = IPA_RM_RESOURCE_RELEASED;
info.cur_cons_state[i] = IPA_RM_RESOURCE_RELEASED;
info.lpm_wait_handshake[i] = false;
}
INIT_WORK(&info.resume_work, usb_bam_finish_resume);
INIT_WORK(&info.suspend_work, usb_bam_start_suspend);
INIT_WORK(&info.finish_suspend_work, usb_bam_finish_suspend_);
mutex_init(&info.suspend_resume_mutex);
spin_lock_init(&usb_bam_peer_handshake_info_lock);
INIT_WORK(&peer_handshake_info.reset_event.event_w, usb_bam_sm_work);
init_completion(&ctx.reset_done);
complete(&ctx.reset_done);
ctx.usb_bam_wq = alloc_workqueue("usb_bam_wq",
WQ_UNBOUND | WQ_MEM_RECLAIM, 1);
if (!ctx.usb_bam_wq) {
pr_err("unable to create workqueue usb_bam_wq\n");
return -ENOMEM;
}
ret = enable_usb_bams(pdev);
if (ret) {
destroy_workqueue(ctx.usb_bam_wq);
return ret;
}
spin_lock_init(&usb_bam_ipa_handshake_info_lock);
usb_bam_ipa_create_resources();
spin_lock_init(&usb_bam_lock);
return ret;
}
int usb_bam_get_qdss_idx(u8 num)
{
return usb_bam_get_connection_idx(ctx.qdss_core_name, QDSS_P_BAM,
PEER_PERIPHERAL_TO_USB, num);
}
EXPORT_SYMBOL(usb_bam_get_qdss_idx);
void usb_bam_set_qdss_core(const char *qdss_core)
{
strlcpy(ctx.qdss_core_name, qdss_core, USB_BAM_MAX_STR_LEN);
}
int get_bam2bam_connection_info(u8 idx, u32 *usb_bam_handle,
u32 *usb_bam_pipe_idx, u32 *peer_pipe_idx,
struct sps_mem_buffer *desc_fifo, struct sps_mem_buffer *data_fifo)
{
struct usb_bam_pipe_connect *pipe_connect = &usb_bam_connections[idx];
enum usb_bam_pipe_dir dir = pipe_connect->dir;
struct sps_connect *sps_connection =
&ctx.usb_bam_sps.sps_connections[idx];
if (dir == USB_TO_PEER_PERIPHERAL) {
*usb_bam_handle = sps_connection->source;
*usb_bam_pipe_idx = sps_connection->src_pipe_index;
*peer_pipe_idx = sps_connection->dest_pipe_index;
} else {
*usb_bam_handle = sps_connection->destination;
*usb_bam_pipe_idx = sps_connection->dest_pipe_index;
*peer_pipe_idx = sps_connection->src_pipe_index;
}
if (data_fifo)
memcpy(data_fifo, &pipe_connect->data_mem_buf,
sizeof(struct sps_mem_buffer));
if (desc_fifo)
memcpy(desc_fifo, &pipe_connect->desc_mem_buf,
sizeof(struct sps_mem_buffer));
return 0;
}
EXPORT_SYMBOL(get_bam2bam_connection_info);
int usb_bam_get_connection_idx(const char *core_name, enum peer_bam client,
enum usb_bam_pipe_dir dir, u32 num)
{
u8 i;
int bam_type;
bam_type = get_bam_type_from_core_name(core_name);
if (bam_type < 0)
return -EINVAL;
for (i = 0; i < ctx.max_connections; i++)
if (usb_bam_connections[i].bam_type == bam_type &&
usb_bam_connections[i].peer_bam == client &&
usb_bam_connections[i].dir == dir &&
usb_bam_connections[i].pipe_num == num) {
pr_debug("%s: index %d was found\n", __func__, i);
return i;
}
pr_err("%s: failed for %s\n", __func__, core_name);
return -ENODEV;
}
EXPORT_SYMBOL(usb_bam_get_connection_idx);
bool msm_bam_lpm_ok(void)
{
spin_lock(&usb_bam_ipa_handshake_info_lock);
if (info.lpm_wait_handshake[HSUSB_BAM] || info.lpm_wait_pipes) {
info.pending_lpm = 1;
spin_unlock(&usb_bam_ipa_handshake_info_lock);
pr_err("%s: Scheduling LPM for later\n", __func__);
return 0;
} else {
info.pending_lpm = 0;
info.in_lpm[HSUSB_BAM] = true;
spin_unlock(&usb_bam_ipa_handshake_info_lock);
pr_err("%s: Going to LPM now\n", __func__);
return 1;
}
}
EXPORT_SYMBOL(msm_bam_lpm_ok);
void msm_bam_notify_lpm_resume()
{
/*
* If core was resumed from lpm, just clear the
* pending indication, in case it is set.
*/
info.pending_lpm = 0;
}
EXPORT_SYMBOL(msm_bam_notify_lpm_resume);
static int usb_bam_remove(struct platform_device *pdev)
{
destroy_workqueue(ctx.usb_bam_wq);
return 0;
}
static const struct of_device_id usb_bam_dt_match[] = {
{ .compatible = "qcom,usb-bam-msm",
},
{}
};
MODULE_DEVICE_TABLE(of, usb_bam_dt_match);
static struct platform_driver usb_bam_driver = {
.probe = usb_bam_probe,
.remove = usb_bam_remove,
.driver = {
.name = "usb_bam",
.of_match_table = usb_bam_dt_match,
},
};
static int __init init(void)
{
return platform_driver_register(&usb_bam_driver);
}
module_init(init);
static void __exit cleanup(void)
{
platform_driver_unregister(&usb_bam_driver);
}
module_exit(cleanup);
MODULE_DESCRIPTION("MSM USB BAM DRIVER");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
friendlyarm/linux-4.x.y | drivers/input/misc/cm109.c | 1918 | 24300 | /*
* Driver for the VoIP USB phones with CM109 chipsets.
*
* Copyright (C) 2007 - 2008 Alfred E. Heggestad <aeh@db.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, version 2.
*/
/*
* Tested devices:
* - Komunikate KIP1000
* - Genius G-talk
* - Allied-Telesis Corega USBPH01
* - ...
*
* This driver is based on the yealink.c driver
*
* Thanks to:
* - Authors of yealink.c
* - Thomas Reitmayr
* - Oliver Neukum for good review comments and code
* - Shaun Jackman <sjackman@gmail.com> for Genius G-talk keymap
* - Dmitry Torokhov for valuable input and review
*
* Todo:
* - Read/write EEPROM
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/rwsem.h>
#include <linux/usb/input.h>
#define DRIVER_VERSION "20080805"
#define DRIVER_AUTHOR "Alfred E. Heggestad"
#define DRIVER_DESC "CM109 phone driver"
static char *phone = "kip1000";
module_param(phone, charp, S_IRUSR);
MODULE_PARM_DESC(phone, "Phone name {kip1000, gtalk, usbph01, atcom}");
enum {
/* HID Registers */
HID_IR0 = 0x00, /* Record/Playback-mute button, Volume up/down */
HID_IR1 = 0x01, /* GPI, generic registers or EEPROM_DATA0 */
HID_IR2 = 0x02, /* Generic registers or EEPROM_DATA1 */
HID_IR3 = 0x03, /* Generic registers or EEPROM_CTRL */
HID_OR0 = 0x00, /* Mapping control, buzzer, SPDIF (offset 0x04) */
HID_OR1 = 0x01, /* GPO - General Purpose Output */
HID_OR2 = 0x02, /* Set GPIO to input/output mode */
HID_OR3 = 0x03, /* SPDIF status channel or EEPROM_CTRL */
/* HID_IR0 */
RECORD_MUTE = 1 << 3,
PLAYBACK_MUTE = 1 << 2,
VOLUME_DOWN = 1 << 1,
VOLUME_UP = 1 << 0,
/* HID_OR0 */
/* bits 7-6
0: HID_OR1-2 are used for GPO; HID_OR0, 3 are used for buzzer
and SPDIF
1: HID_OR0-3 are used as generic HID registers
2: Values written to HID_OR0-3 are also mapped to MCU_CTRL,
EEPROM_DATA0-1, EEPROM_CTRL (see Note)
3: Reserved
*/
HID_OR_GPO_BUZ_SPDIF = 0 << 6,
HID_OR_GENERIC_HID_REG = 1 << 6,
HID_OR_MAP_MCU_EEPROM = 2 << 6,
BUZZER_ON = 1 << 5,
/* up to 256 normal keys, up to 16 special keys */
KEYMAP_SIZE = 256 + 16,
};
/* CM109 protocol packet */
struct cm109_ctl_packet {
u8 byte[4];
} __attribute__ ((packed));
enum { USB_PKT_LEN = sizeof(struct cm109_ctl_packet) };
/* CM109 device structure */
struct cm109_dev {
struct input_dev *idev; /* input device */
struct usb_device *udev; /* usb device */
struct usb_interface *intf;
/* irq input channel */
struct cm109_ctl_packet *irq_data;
dma_addr_t irq_dma;
struct urb *urb_irq;
/* control output channel */
struct cm109_ctl_packet *ctl_data;
dma_addr_t ctl_dma;
struct usb_ctrlrequest *ctl_req;
struct urb *urb_ctl;
/*
* The 3 bitfields below are protected by ctl_submit_lock.
* They have to be separate since they are accessed from IRQ
* context.
*/
unsigned irq_urb_pending:1; /* irq_urb is in flight */
unsigned ctl_urb_pending:1; /* ctl_urb is in flight */
unsigned buzzer_pending:1; /* need to issue buzz command */
spinlock_t ctl_submit_lock;
unsigned char buzzer_state; /* on/off */
/* flags */
unsigned open:1;
unsigned resetting:1;
unsigned shutdown:1;
/* This mutex protects writes to the above flags */
struct mutex pm_mutex;
unsigned short keymap[KEYMAP_SIZE];
char phys[64]; /* physical device path */
int key_code; /* last reported key */
int keybit; /* 0=new scan 1,2,4,8=scan columns */
u8 gpi; /* Cached value of GPI (high nibble) */
};
/******************************************************************************
* CM109 key interface
*****************************************************************************/
static unsigned short special_keymap(int code)
{
if (code > 0xff) {
switch (code - 0xff) {
case RECORD_MUTE: return KEY_MUTE;
case PLAYBACK_MUTE: return KEY_MUTE;
case VOLUME_DOWN: return KEY_VOLUMEDOWN;
case VOLUME_UP: return KEY_VOLUMEUP;
}
}
return KEY_RESERVED;
}
/* Map device buttons to internal key events.
*
* The "up" and "down" keys, are symbolised by arrows on the button.
* The "pickup" and "hangup" keys are symbolised by a green and red phone
* on the button.
Komunikate KIP1000 Keyboard Matrix
-> -- 1 -- 2 -- 3 --> GPI pin 4 (0x10)
| | | |
<- -- 4 -- 5 -- 6 --> GPI pin 5 (0x20)
| | | |
END - 7 -- 8 -- 9 --> GPI pin 6 (0x40)
| | | |
OK -- * -- 0 -- # --> GPI pin 7 (0x80)
| | | |
/|\ /|\ /|\ /|\
| | | |
GPO
pin: 3 2 1 0
0x8 0x4 0x2 0x1
*/
static unsigned short keymap_kip1000(int scancode)
{
switch (scancode) { /* phone key: */
case 0x82: return KEY_NUMERIC_0; /* 0 */
case 0x14: return KEY_NUMERIC_1; /* 1 */
case 0x12: return KEY_NUMERIC_2; /* 2 */
case 0x11: return KEY_NUMERIC_3; /* 3 */
case 0x24: return KEY_NUMERIC_4; /* 4 */
case 0x22: return KEY_NUMERIC_5; /* 5 */
case 0x21: return KEY_NUMERIC_6; /* 6 */
case 0x44: return KEY_NUMERIC_7; /* 7 */
case 0x42: return KEY_NUMERIC_8; /* 8 */
case 0x41: return KEY_NUMERIC_9; /* 9 */
case 0x81: return KEY_NUMERIC_POUND; /* # */
case 0x84: return KEY_NUMERIC_STAR; /* * */
case 0x88: return KEY_ENTER; /* pickup */
case 0x48: return KEY_ESC; /* hangup */
case 0x28: return KEY_LEFT; /* IN */
case 0x18: return KEY_RIGHT; /* OUT */
default: return special_keymap(scancode);
}
}
/*
Contributed by Shaun Jackman <sjackman@gmail.com>
Genius G-Talk keyboard matrix
0 1 2 3
4: 0 4 8 Talk
5: 1 5 9 End
6: 2 6 # Up
7: 3 7 * Down
*/
static unsigned short keymap_gtalk(int scancode)
{
switch (scancode) {
case 0x11: return KEY_NUMERIC_0;
case 0x21: return KEY_NUMERIC_1;
case 0x41: return KEY_NUMERIC_2;
case 0x81: return KEY_NUMERIC_3;
case 0x12: return KEY_NUMERIC_4;
case 0x22: return KEY_NUMERIC_5;
case 0x42: return KEY_NUMERIC_6;
case 0x82: return KEY_NUMERIC_7;
case 0x14: return KEY_NUMERIC_8;
case 0x24: return KEY_NUMERIC_9;
case 0x44: return KEY_NUMERIC_POUND; /* # */
case 0x84: return KEY_NUMERIC_STAR; /* * */
case 0x18: return KEY_ENTER; /* Talk (green handset) */
case 0x28: return KEY_ESC; /* End (red handset) */
case 0x48: return KEY_UP; /* Menu up (rocker switch) */
case 0x88: return KEY_DOWN; /* Menu down (rocker switch) */
default: return special_keymap(scancode);
}
}
/*
* Keymap for Allied-Telesis Corega USBPH01
* http://www.alliedtelesis-corega.com/2/1344/1437/1360/chprd.html
*
* Contributed by july@nat.bg
*/
static unsigned short keymap_usbph01(int scancode)
{
switch (scancode) {
case 0x11: return KEY_NUMERIC_0; /* 0 */
case 0x21: return KEY_NUMERIC_1; /* 1 */
case 0x41: return KEY_NUMERIC_2; /* 2 */
case 0x81: return KEY_NUMERIC_3; /* 3 */
case 0x12: return KEY_NUMERIC_4; /* 4 */
case 0x22: return KEY_NUMERIC_5; /* 5 */
case 0x42: return KEY_NUMERIC_6; /* 6 */
case 0x82: return KEY_NUMERIC_7; /* 7 */
case 0x14: return KEY_NUMERIC_8; /* 8 */
case 0x24: return KEY_NUMERIC_9; /* 9 */
case 0x44: return KEY_NUMERIC_POUND; /* # */
case 0x84: return KEY_NUMERIC_STAR; /* * */
case 0x18: return KEY_ENTER; /* pickup */
case 0x28: return KEY_ESC; /* hangup */
case 0x48: return KEY_LEFT; /* IN */
case 0x88: return KEY_RIGHT; /* OUT */
default: return special_keymap(scancode);
}
}
/*
* Keymap for ATCom AU-100
* http://www.atcom.cn/products.html
* http://www.packetizer.com/products/au100/
* http://www.voip-info.org/wiki/view/AU-100
*
* Contributed by daniel@gimpelevich.san-francisco.ca.us
*/
static unsigned short keymap_atcom(int scancode)
{
switch (scancode) { /* phone key: */
case 0x82: return KEY_NUMERIC_0; /* 0 */
case 0x11: return KEY_NUMERIC_1; /* 1 */
case 0x12: return KEY_NUMERIC_2; /* 2 */
case 0x14: return KEY_NUMERIC_3; /* 3 */
case 0x21: return KEY_NUMERIC_4; /* 4 */
case 0x22: return KEY_NUMERIC_5; /* 5 */
case 0x24: return KEY_NUMERIC_6; /* 6 */
case 0x41: return KEY_NUMERIC_7; /* 7 */
case 0x42: return KEY_NUMERIC_8; /* 8 */
case 0x44: return KEY_NUMERIC_9; /* 9 */
case 0x84: return KEY_NUMERIC_POUND; /* # */
case 0x81: return KEY_NUMERIC_STAR; /* * */
case 0x18: return KEY_ENTER; /* pickup */
case 0x28: return KEY_ESC; /* hangup */
case 0x48: return KEY_LEFT; /* left arrow */
case 0x88: return KEY_RIGHT; /* right arrow */
default: return special_keymap(scancode);
}
}
static unsigned short (*keymap)(int) = keymap_kip1000;
/*
* Completes a request by converting the data into events for the
* input subsystem.
*/
static void report_key(struct cm109_dev *dev, int key)
{
struct input_dev *idev = dev->idev;
if (dev->key_code >= 0) {
/* old key up */
input_report_key(idev, dev->key_code, 0);
}
dev->key_code = key;
if (key >= 0) {
/* new valid key */
input_report_key(idev, key, 1);
}
input_sync(idev);
}
/******************************************************************************
* CM109 usb communication interface
*****************************************************************************/
static void cm109_submit_buzz_toggle(struct cm109_dev *dev)
{
int error;
if (dev->buzzer_state)
dev->ctl_data->byte[HID_OR0] |= BUZZER_ON;
else
dev->ctl_data->byte[HID_OR0] &= ~BUZZER_ON;
error = usb_submit_urb(dev->urb_ctl, GFP_ATOMIC);
if (error)
dev_err(&dev->intf->dev,
"%s: usb_submit_urb (urb_ctl) failed %d\n",
__func__, error);
}
/*
* IRQ handler
*/
static void cm109_urb_irq_callback(struct urb *urb)
{
struct cm109_dev *dev = urb->context;
const int status = urb->status;
int error;
dev_dbg(&dev->intf->dev, "### URB IRQ: [0x%02x 0x%02x 0x%02x 0x%02x] keybit=0x%02x\n",
dev->irq_data->byte[0],
dev->irq_data->byte[1],
dev->irq_data->byte[2],
dev->irq_data->byte[3],
dev->keybit);
if (status) {
if (status == -ESHUTDOWN)
return;
dev_err_ratelimited(&dev->intf->dev, "%s: urb status %d\n",
__func__, status);
goto out;
}
/* Special keys */
if (dev->irq_data->byte[HID_IR0] & 0x0f) {
const int code = (dev->irq_data->byte[HID_IR0] & 0x0f);
report_key(dev, dev->keymap[0xff + code]);
}
/* Scan key column */
if (dev->keybit == 0xf) {
/* Any changes ? */
if ((dev->gpi & 0xf0) == (dev->irq_data->byte[HID_IR1] & 0xf0))
goto out;
dev->gpi = dev->irq_data->byte[HID_IR1] & 0xf0;
dev->keybit = 0x1;
} else {
report_key(dev, dev->keymap[dev->irq_data->byte[HID_IR1]]);
dev->keybit <<= 1;
if (dev->keybit > 0x8)
dev->keybit = 0xf;
}
out:
spin_lock(&dev->ctl_submit_lock);
dev->irq_urb_pending = 0;
if (likely(!dev->shutdown)) {
if (dev->buzzer_state)
dev->ctl_data->byte[HID_OR0] |= BUZZER_ON;
else
dev->ctl_data->byte[HID_OR0] &= ~BUZZER_ON;
dev->ctl_data->byte[HID_OR1] = dev->keybit;
dev->ctl_data->byte[HID_OR2] = dev->keybit;
dev->buzzer_pending = 0;
dev->ctl_urb_pending = 1;
error = usb_submit_urb(dev->urb_ctl, GFP_ATOMIC);
if (error)
dev_err(&dev->intf->dev,
"%s: usb_submit_urb (urb_ctl) failed %d\n",
__func__, error);
}
spin_unlock(&dev->ctl_submit_lock);
}
static void cm109_urb_ctl_callback(struct urb *urb)
{
struct cm109_dev *dev = urb->context;
const int status = urb->status;
int error;
dev_dbg(&dev->intf->dev, "### URB CTL: [0x%02x 0x%02x 0x%02x 0x%02x]\n",
dev->ctl_data->byte[0],
dev->ctl_data->byte[1],
dev->ctl_data->byte[2],
dev->ctl_data->byte[3]);
if (status) {
if (status == -ESHUTDOWN)
return;
dev_err_ratelimited(&dev->intf->dev, "%s: urb status %d\n",
__func__, status);
}
spin_lock(&dev->ctl_submit_lock);
dev->ctl_urb_pending = 0;
if (likely(!dev->shutdown)) {
if (dev->buzzer_pending || status) {
dev->buzzer_pending = 0;
dev->ctl_urb_pending = 1;
cm109_submit_buzz_toggle(dev);
} else if (likely(!dev->irq_urb_pending)) {
/* ask for key data */
dev->irq_urb_pending = 1;
error = usb_submit_urb(dev->urb_irq, GFP_ATOMIC);
if (error)
dev_err(&dev->intf->dev,
"%s: usb_submit_urb (urb_irq) failed %d\n",
__func__, error);
}
}
spin_unlock(&dev->ctl_submit_lock);
}
static void cm109_toggle_buzzer_async(struct cm109_dev *dev)
{
unsigned long flags;
spin_lock_irqsave(&dev->ctl_submit_lock, flags);
if (dev->ctl_urb_pending) {
/* URB completion will resubmit */
dev->buzzer_pending = 1;
} else {
dev->ctl_urb_pending = 1;
cm109_submit_buzz_toggle(dev);
}
spin_unlock_irqrestore(&dev->ctl_submit_lock, flags);
}
static void cm109_toggle_buzzer_sync(struct cm109_dev *dev, int on)
{
int error;
if (on)
dev->ctl_data->byte[HID_OR0] |= BUZZER_ON;
else
dev->ctl_data->byte[HID_OR0] &= ~BUZZER_ON;
error = usb_control_msg(dev->udev,
usb_sndctrlpipe(dev->udev, 0),
dev->ctl_req->bRequest,
dev->ctl_req->bRequestType,
le16_to_cpu(dev->ctl_req->wValue),
le16_to_cpu(dev->ctl_req->wIndex),
dev->ctl_data,
USB_PKT_LEN, USB_CTRL_SET_TIMEOUT);
if (error < 0 && error != -EINTR)
dev_err(&dev->intf->dev, "%s: usb_control_msg() failed %d\n",
__func__, error);
}
static void cm109_stop_traffic(struct cm109_dev *dev)
{
dev->shutdown = 1;
/*
* Make sure other CPUs see this
*/
smp_wmb();
usb_kill_urb(dev->urb_ctl);
usb_kill_urb(dev->urb_irq);
cm109_toggle_buzzer_sync(dev, 0);
dev->shutdown = 0;
smp_wmb();
}
static void cm109_restore_state(struct cm109_dev *dev)
{
if (dev->open) {
/*
* Restore buzzer state.
* This will also kick regular URB submission
*/
cm109_toggle_buzzer_async(dev);
}
}
/******************************************************************************
* input event interface
*****************************************************************************/
static int cm109_input_open(struct input_dev *idev)
{
struct cm109_dev *dev = input_get_drvdata(idev);
int error;
error = usb_autopm_get_interface(dev->intf);
if (error < 0) {
dev_err(&idev->dev, "%s - cannot autoresume, result %d\n",
__func__, error);
return error;
}
mutex_lock(&dev->pm_mutex);
dev->buzzer_state = 0;
dev->key_code = -1; /* no keys pressed */
dev->keybit = 0xf;
/* issue INIT */
dev->ctl_data->byte[HID_OR0] = HID_OR_GPO_BUZ_SPDIF;
dev->ctl_data->byte[HID_OR1] = dev->keybit;
dev->ctl_data->byte[HID_OR2] = dev->keybit;
dev->ctl_data->byte[HID_OR3] = 0x00;
error = usb_submit_urb(dev->urb_ctl, GFP_KERNEL);
if (error)
dev_err(&dev->intf->dev, "%s: usb_submit_urb (urb_ctl) failed %d\n",
__func__, error);
else
dev->open = 1;
mutex_unlock(&dev->pm_mutex);
if (error)
usb_autopm_put_interface(dev->intf);
return error;
}
static void cm109_input_close(struct input_dev *idev)
{
struct cm109_dev *dev = input_get_drvdata(idev);
mutex_lock(&dev->pm_mutex);
/*
* Once we are here event delivery is stopped so we
* don't need to worry about someone starting buzzer
* again
*/
cm109_stop_traffic(dev);
dev->open = 0;
mutex_unlock(&dev->pm_mutex);
usb_autopm_put_interface(dev->intf);
}
static int cm109_input_ev(struct input_dev *idev, unsigned int type,
unsigned int code, int value)
{
struct cm109_dev *dev = input_get_drvdata(idev);
dev_dbg(&dev->intf->dev,
"input_ev: type=%u code=%u value=%d\n", type, code, value);
if (type != EV_SND)
return -EINVAL;
switch (code) {
case SND_TONE:
case SND_BELL:
dev->buzzer_state = !!value;
if (!dev->resetting)
cm109_toggle_buzzer_async(dev);
return 0;
default:
return -EINVAL;
}
}
/******************************************************************************
* Linux interface and usb initialisation
*****************************************************************************/
struct driver_info {
char *name;
};
static const struct driver_info info_cm109 = {
.name = "CM109 USB driver",
};
enum {
VENDOR_ID = 0x0d8c, /* C-Media Electronics */
PRODUCT_ID_CM109 = 0x000e, /* CM109 defines range 0x0008 - 0x000f */
};
/* table of devices that work with this driver */
static const struct usb_device_id cm109_usb_table[] = {
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE |
USB_DEVICE_ID_MATCH_INT_INFO,
.idVendor = VENDOR_ID,
.idProduct = PRODUCT_ID_CM109,
.bInterfaceClass = USB_CLASS_HID,
.bInterfaceSubClass = 0,
.bInterfaceProtocol = 0,
.driver_info = (kernel_ulong_t) &info_cm109
},
/* you can add more devices here with product ID 0x0008 - 0x000f */
{ }
};
static void cm109_usb_cleanup(struct cm109_dev *dev)
{
kfree(dev->ctl_req);
if (dev->ctl_data)
usb_free_coherent(dev->udev, USB_PKT_LEN,
dev->ctl_data, dev->ctl_dma);
if (dev->irq_data)
usb_free_coherent(dev->udev, USB_PKT_LEN,
dev->irq_data, dev->irq_dma);
usb_free_urb(dev->urb_irq); /* parameter validation in core/urb */
usb_free_urb(dev->urb_ctl); /* parameter validation in core/urb */
kfree(dev);
}
static void cm109_usb_disconnect(struct usb_interface *interface)
{
struct cm109_dev *dev = usb_get_intfdata(interface);
usb_set_intfdata(interface, NULL);
input_unregister_device(dev->idev);
cm109_usb_cleanup(dev);
}
static int cm109_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct driver_info *nfo = (struct driver_info *)id->driver_info;
struct usb_host_interface *interface;
struct usb_endpoint_descriptor *endpoint;
struct cm109_dev *dev;
struct input_dev *input_dev = NULL;
int ret, pipe, i;
int error = -ENOMEM;
interface = intf->cur_altsetting;
endpoint = &interface->endpoint[0].desc;
if (!usb_endpoint_is_int_in(endpoint))
return -ENODEV;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
spin_lock_init(&dev->ctl_submit_lock);
mutex_init(&dev->pm_mutex);
dev->udev = udev;
dev->intf = intf;
dev->idev = input_dev = input_allocate_device();
if (!input_dev)
goto err_out;
/* allocate usb buffers */
dev->irq_data = usb_alloc_coherent(udev, USB_PKT_LEN,
GFP_KERNEL, &dev->irq_dma);
if (!dev->irq_data)
goto err_out;
dev->ctl_data = usb_alloc_coherent(udev, USB_PKT_LEN,
GFP_KERNEL, &dev->ctl_dma);
if (!dev->ctl_data)
goto err_out;
dev->ctl_req = kmalloc(sizeof(*(dev->ctl_req)), GFP_KERNEL);
if (!dev->ctl_req)
goto err_out;
/* allocate urb structures */
dev->urb_irq = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->urb_irq)
goto err_out;
dev->urb_ctl = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->urb_ctl)
goto err_out;
/* get a handle to the interrupt data pipe */
pipe = usb_rcvintpipe(udev, endpoint->bEndpointAddress);
ret = usb_maxpacket(udev, pipe, usb_pipeout(pipe));
if (ret != USB_PKT_LEN)
dev_err(&intf->dev, "invalid payload size %d, expected %d\n",
ret, USB_PKT_LEN);
/* initialise irq urb */
usb_fill_int_urb(dev->urb_irq, udev, pipe, dev->irq_data,
USB_PKT_LEN,
cm109_urb_irq_callback, dev, endpoint->bInterval);
dev->urb_irq->transfer_dma = dev->irq_dma;
dev->urb_irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
dev->urb_irq->dev = udev;
/* initialise ctl urb */
dev->ctl_req->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE |
USB_DIR_OUT;
dev->ctl_req->bRequest = USB_REQ_SET_CONFIGURATION;
dev->ctl_req->wValue = cpu_to_le16(0x200);
dev->ctl_req->wIndex = cpu_to_le16(interface->desc.bInterfaceNumber);
dev->ctl_req->wLength = cpu_to_le16(USB_PKT_LEN);
usb_fill_control_urb(dev->urb_ctl, udev, usb_sndctrlpipe(udev, 0),
(void *)dev->ctl_req, dev->ctl_data, USB_PKT_LEN,
cm109_urb_ctl_callback, dev);
dev->urb_ctl->transfer_dma = dev->ctl_dma;
dev->urb_ctl->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
dev->urb_ctl->dev = udev;
/* find out the physical bus location */
usb_make_path(udev, dev->phys, sizeof(dev->phys));
strlcat(dev->phys, "/input0", sizeof(dev->phys));
/* register settings for the input device */
input_dev->name = nfo->name;
input_dev->phys = dev->phys;
usb_to_input_id(udev, &input_dev->id);
input_dev->dev.parent = &intf->dev;
input_set_drvdata(input_dev, dev);
input_dev->open = cm109_input_open;
input_dev->close = cm109_input_close;
input_dev->event = cm109_input_ev;
input_dev->keycode = dev->keymap;
input_dev->keycodesize = sizeof(unsigned char);
input_dev->keycodemax = ARRAY_SIZE(dev->keymap);
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_SND);
input_dev->sndbit[0] = BIT_MASK(SND_BELL) | BIT_MASK(SND_TONE);
/* register available key events */
for (i = 0; i < KEYMAP_SIZE; i++) {
unsigned short k = keymap(i);
dev->keymap[i] = k;
__set_bit(k, input_dev->keybit);
}
__clear_bit(KEY_RESERVED, input_dev->keybit);
error = input_register_device(dev->idev);
if (error)
goto err_out;
usb_set_intfdata(intf, dev);
return 0;
err_out:
input_free_device(input_dev);
cm109_usb_cleanup(dev);
return error;
}
static int cm109_usb_suspend(struct usb_interface *intf, pm_message_t message)
{
struct cm109_dev *dev = usb_get_intfdata(intf);
dev_info(&intf->dev, "cm109: usb_suspend (event=%d)\n", message.event);
mutex_lock(&dev->pm_mutex);
cm109_stop_traffic(dev);
mutex_unlock(&dev->pm_mutex);
return 0;
}
static int cm109_usb_resume(struct usb_interface *intf)
{
struct cm109_dev *dev = usb_get_intfdata(intf);
dev_info(&intf->dev, "cm109: usb_resume\n");
mutex_lock(&dev->pm_mutex);
cm109_restore_state(dev);
mutex_unlock(&dev->pm_mutex);
return 0;
}
static int cm109_usb_pre_reset(struct usb_interface *intf)
{
struct cm109_dev *dev = usb_get_intfdata(intf);
mutex_lock(&dev->pm_mutex);
/*
* Make sure input events don't try to toggle buzzer
* while we are resetting
*/
dev->resetting = 1;
smp_wmb();
cm109_stop_traffic(dev);
return 0;
}
static int cm109_usb_post_reset(struct usb_interface *intf)
{
struct cm109_dev *dev = usb_get_intfdata(intf);
dev->resetting = 0;
smp_wmb();
cm109_restore_state(dev);
mutex_unlock(&dev->pm_mutex);
return 0;
}
static struct usb_driver cm109_driver = {
.name = "cm109",
.probe = cm109_usb_probe,
.disconnect = cm109_usb_disconnect,
.suspend = cm109_usb_suspend,
.resume = cm109_usb_resume,
.reset_resume = cm109_usb_resume,
.pre_reset = cm109_usb_pre_reset,
.post_reset = cm109_usb_post_reset,
.id_table = cm109_usb_table,
.supports_autosuspend = 1,
};
static int __init cm109_select_keymap(void)
{
/* Load the phone keymap */
if (!strcasecmp(phone, "kip1000")) {
keymap = keymap_kip1000;
printk(KERN_INFO KBUILD_MODNAME ": "
"Keymap for Komunikate KIP1000 phone loaded\n");
} else if (!strcasecmp(phone, "gtalk")) {
keymap = keymap_gtalk;
printk(KERN_INFO KBUILD_MODNAME ": "
"Keymap for Genius G-talk phone loaded\n");
} else if (!strcasecmp(phone, "usbph01")) {
keymap = keymap_usbph01;
printk(KERN_INFO KBUILD_MODNAME ": "
"Keymap for Allied-Telesis Corega USBPH01 phone loaded\n");
} else if (!strcasecmp(phone, "atcom")) {
keymap = keymap_atcom;
printk(KERN_INFO KBUILD_MODNAME ": "
"Keymap for ATCom AU-100 phone loaded\n");
} else {
printk(KERN_ERR KBUILD_MODNAME ": "
"Unsupported phone: %s\n", phone);
return -EINVAL;
}
return 0;
}
static int __init cm109_init(void)
{
int err;
err = cm109_select_keymap();
if (err)
return err;
err = usb_register(&cm109_driver);
if (err)
return err;
printk(KERN_INFO KBUILD_MODNAME ": "
DRIVER_DESC ": " DRIVER_VERSION " (C) " DRIVER_AUTHOR "\n");
return 0;
}
static void __exit cm109_exit(void)
{
usb_deregister(&cm109_driver);
}
module_init(cm109_init);
module_exit(cm109_exit);
MODULE_DEVICE_TABLE(usb, cm109_usb_table);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
r1mikey/linux-picoxcell | arch/mips/bcm63xx/clk.c | 1918 | 7711 | /*
* 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) 2008 Maxime Bizon <mbizon@freebox.fr>
*/
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <bcm63xx_cpu.h>
#include <bcm63xx_io.h>
#include <bcm63xx_regs.h>
#include <bcm63xx_reset.h>
struct clk {
void (*set)(struct clk *, int);
unsigned int rate;
unsigned int usage;
int id;
};
static DEFINE_MUTEX(clocks_mutex);
static void clk_enable_unlocked(struct clk *clk)
{
if (clk->set && (clk->usage++) == 0)
clk->set(clk, 1);
}
static void clk_disable_unlocked(struct clk *clk)
{
if (clk->set && (--clk->usage) == 0)
clk->set(clk, 0);
}
static void bcm_hwclock_set(u32 mask, int enable)
{
u32 reg;
reg = bcm_perf_readl(PERF_CKCTL_REG);
if (enable)
reg |= mask;
else
reg &= ~mask;
bcm_perf_writel(reg, PERF_CKCTL_REG);
}
/*
* Ethernet MAC "misc" clock: dma clocks and main clock on 6348
*/
static void enet_misc_set(struct clk *clk, int enable)
{
u32 mask;
if (BCMCPU_IS_6338())
mask = CKCTL_6338_ENET_EN;
else if (BCMCPU_IS_6345())
mask = CKCTL_6345_ENET_EN;
else if (BCMCPU_IS_6348())
mask = CKCTL_6348_ENET_EN;
else
/* BCMCPU_IS_6358 */
mask = CKCTL_6358_EMUSB_EN;
bcm_hwclock_set(mask, enable);
}
static struct clk clk_enet_misc = {
.set = enet_misc_set,
};
/*
* Ethernet MAC clocks: only revelant on 6358, silently enable misc
* clocks
*/
static void enetx_set(struct clk *clk, int enable)
{
if (enable)
clk_enable_unlocked(&clk_enet_misc);
else
clk_disable_unlocked(&clk_enet_misc);
if (BCMCPU_IS_3368() || BCMCPU_IS_6358()) {
u32 mask;
if (clk->id == 0)
mask = CKCTL_6358_ENET0_EN;
else
mask = CKCTL_6358_ENET1_EN;
bcm_hwclock_set(mask, enable);
}
}
static struct clk clk_enet0 = {
.id = 0,
.set = enetx_set,
};
static struct clk clk_enet1 = {
.id = 1,
.set = enetx_set,
};
/*
* Ethernet PHY clock
*/
static void ephy_set(struct clk *clk, int enable)
{
if (BCMCPU_IS_3368() || BCMCPU_IS_6358())
bcm_hwclock_set(CKCTL_6358_EPHY_EN, enable);
}
static struct clk clk_ephy = {
.set = ephy_set,
};
/*
* Ethernet switch clock
*/
static void enetsw_set(struct clk *clk, int enable)
{
if (BCMCPU_IS_6328())
bcm_hwclock_set(CKCTL_6328_ROBOSW_EN, enable);
else if (BCMCPU_IS_6362())
bcm_hwclock_set(CKCTL_6362_ROBOSW_EN, enable);
else if (BCMCPU_IS_6368())
bcm_hwclock_set(CKCTL_6368_ROBOSW_EN |
CKCTL_6368_SWPKT_USB_EN |
CKCTL_6368_SWPKT_SAR_EN,
enable);
else
return;
if (enable) {
/* reset switch core afer clock change */
bcm63xx_core_set_reset(BCM63XX_RESET_ENETSW, 1);
msleep(10);
bcm63xx_core_set_reset(BCM63XX_RESET_ENETSW, 0);
msleep(10);
}
}
static struct clk clk_enetsw = {
.set = enetsw_set,
};
/*
* PCM clock
*/
static void pcm_set(struct clk *clk, int enable)
{
if (BCMCPU_IS_3368())
bcm_hwclock_set(CKCTL_3368_PCM_EN, enable);
if (BCMCPU_IS_6358())
bcm_hwclock_set(CKCTL_6358_PCM_EN, enable);
}
static struct clk clk_pcm = {
.set = pcm_set,
};
/*
* USB host clock
*/
static void usbh_set(struct clk *clk, int enable)
{
if (BCMCPU_IS_6328())
bcm_hwclock_set(CKCTL_6328_USBH_EN, enable);
else if (BCMCPU_IS_6348())
bcm_hwclock_set(CKCTL_6348_USBH_EN, enable);
else if (BCMCPU_IS_6362())
bcm_hwclock_set(CKCTL_6362_USBH_EN, enable);
else if (BCMCPU_IS_6368())
bcm_hwclock_set(CKCTL_6368_USBH_EN, enable);
}
static struct clk clk_usbh = {
.set = usbh_set,
};
/*
* USB device clock
*/
static void usbd_set(struct clk *clk, int enable)
{
if (BCMCPU_IS_6328())
bcm_hwclock_set(CKCTL_6328_USBD_EN, enable);
else if (BCMCPU_IS_6362())
bcm_hwclock_set(CKCTL_6362_USBD_EN, enable);
else if (BCMCPU_IS_6368())
bcm_hwclock_set(CKCTL_6368_USBD_EN, enable);
}
static struct clk clk_usbd = {
.set = usbd_set,
};
/*
* SPI clock
*/
static void spi_set(struct clk *clk, int enable)
{
u32 mask;
if (BCMCPU_IS_6338())
mask = CKCTL_6338_SPI_EN;
else if (BCMCPU_IS_6348())
mask = CKCTL_6348_SPI_EN;
else if (BCMCPU_IS_3368() || BCMCPU_IS_6358())
mask = CKCTL_6358_SPI_EN;
else if (BCMCPU_IS_6362())
mask = CKCTL_6362_SPI_EN;
else
/* BCMCPU_IS_6368 */
mask = CKCTL_6368_SPI_EN;
bcm_hwclock_set(mask, enable);
}
static struct clk clk_spi = {
.set = spi_set,
};
/*
* HSSPI clock
*/
static void hsspi_set(struct clk *clk, int enable)
{
u32 mask;
if (BCMCPU_IS_6328())
mask = CKCTL_6328_HSSPI_EN;
else if (BCMCPU_IS_6362())
mask = CKCTL_6362_HSSPI_EN;
else
return;
bcm_hwclock_set(mask, enable);
}
static struct clk clk_hsspi = {
.set = hsspi_set,
};
/*
* XTM clock
*/
static void xtm_set(struct clk *clk, int enable)
{
if (!BCMCPU_IS_6368())
return;
bcm_hwclock_set(CKCTL_6368_SAR_EN |
CKCTL_6368_SWPKT_SAR_EN, enable);
if (enable) {
/* reset sar core afer clock change */
bcm63xx_core_set_reset(BCM63XX_RESET_SAR, 1);
mdelay(1);
bcm63xx_core_set_reset(BCM63XX_RESET_SAR, 0);
mdelay(1);
}
}
static struct clk clk_xtm = {
.set = xtm_set,
};
/*
* IPsec clock
*/
static void ipsec_set(struct clk *clk, int enable)
{
if (BCMCPU_IS_6362())
bcm_hwclock_set(CKCTL_6362_IPSEC_EN, enable);
else if (BCMCPU_IS_6368())
bcm_hwclock_set(CKCTL_6368_IPSEC_EN, enable);
}
static struct clk clk_ipsec = {
.set = ipsec_set,
};
/*
* PCIe clock
*/
static void pcie_set(struct clk *clk, int enable)
{
if (BCMCPU_IS_6328())
bcm_hwclock_set(CKCTL_6328_PCIE_EN, enable);
else if (BCMCPU_IS_6362())
bcm_hwclock_set(CKCTL_6362_PCIE_EN, enable);
}
static struct clk clk_pcie = {
.set = pcie_set,
};
/*
* Internal peripheral clock
*/
static struct clk clk_periph = {
.rate = (50 * 1000 * 1000),
};
/*
* Linux clock API implementation
*/
int clk_enable(struct clk *clk)
{
mutex_lock(&clocks_mutex);
clk_enable_unlocked(clk);
mutex_unlock(&clocks_mutex);
return 0;
}
EXPORT_SYMBOL(clk_enable);
void clk_disable(struct clk *clk)
{
mutex_lock(&clocks_mutex);
clk_disable_unlocked(clk);
mutex_unlock(&clocks_mutex);
}
EXPORT_SYMBOL(clk_disable);
unsigned long clk_get_rate(struct clk *clk)
{
return clk->rate;
}
EXPORT_SYMBOL(clk_get_rate);
int clk_set_rate(struct clk *clk, unsigned long rate)
{
return 0;
}
EXPORT_SYMBOL_GPL(clk_set_rate);
long clk_round_rate(struct clk *clk, unsigned long rate)
{
return 0;
}
EXPORT_SYMBOL_GPL(clk_round_rate);
struct clk *clk_get(struct device *dev, const char *id)
{
if (!strcmp(id, "enet0"))
return &clk_enet0;
if (!strcmp(id, "enet1"))
return &clk_enet1;
if (!strcmp(id, "enetsw"))
return &clk_enetsw;
if (!strcmp(id, "ephy"))
return &clk_ephy;
if (!strcmp(id, "usbh"))
return &clk_usbh;
if (!strcmp(id, "usbd"))
return &clk_usbd;
if (!strcmp(id, "spi"))
return &clk_spi;
if (!strcmp(id, "hsspi"))
return &clk_hsspi;
if (!strcmp(id, "xtm"))
return &clk_xtm;
if (!strcmp(id, "periph"))
return &clk_periph;
if ((BCMCPU_IS_3368() || BCMCPU_IS_6358()) && !strcmp(id, "pcm"))
return &clk_pcm;
if ((BCMCPU_IS_6362() || BCMCPU_IS_6368()) && !strcmp(id, "ipsec"))
return &clk_ipsec;
if ((BCMCPU_IS_6328() || BCMCPU_IS_6362()) && !strcmp(id, "pcie"))
return &clk_pcie;
return ERR_PTR(-ENOENT);
}
EXPORT_SYMBOL(clk_get);
void clk_put(struct clk *clk)
{
}
EXPORT_SYMBOL(clk_put);
#define HSSPI_PLL_HZ_6328 133333333
#define HSSPI_PLL_HZ_6362 400000000
static int __init bcm63xx_clk_init(void)
{
switch (bcm63xx_get_cpu_id()) {
case BCM6328_CPU_ID:
clk_hsspi.rate = HSSPI_PLL_HZ_6328;
break;
case BCM6362_CPU_ID:
clk_hsspi.rate = HSSPI_PLL_HZ_6362;
break;
}
return 0;
}
arch_initcall(bcm63xx_clk_init);
| gpl-2.0 |
PatrikKT/android_kernel_huawei_y550 | sound/soc/samsung/ac97.c | 1918 | 13444 | /* sound/soc/samsung/ac97.c
*
* ALSA SoC Audio Layer - S3C AC97 Controller driver
* Evolved from s3c2443-ac97.c
*
* Copyright (c) 2010 Samsung Electronics Co. Ltd
* Author: Jaswinder Singh <jassisinghbrar@gmail.com>
* Credits: Graeme Gregory, Sean Choi
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/module.h>
#include <sound/soc.h>
#include <mach/dma.h>
#include "regs-ac97.h"
#include <linux/platform_data/asoc-s3c.h>
#include "dma.h"
#define AC_CMD_ADDR(x) (x << 16)
#define AC_CMD_DATA(x) (x & 0xffff)
#define S3C_AC97_DAI_PCM 0
#define S3C_AC97_DAI_MIC 1
struct s3c_ac97_info {
struct clk *ac97_clk;
void __iomem *regs;
struct mutex lock;
struct completion done;
};
static struct s3c_ac97_info s3c_ac97;
static struct s3c2410_dma_client s3c_dma_client_out = {
.name = "AC97 PCMOut"
};
static struct s3c2410_dma_client s3c_dma_client_in = {
.name = "AC97 PCMIn"
};
static struct s3c2410_dma_client s3c_dma_client_micin = {
.name = "AC97 MicIn"
};
static struct s3c_dma_params s3c_ac97_pcm_out = {
.client = &s3c_dma_client_out,
.dma_size = 4,
};
static struct s3c_dma_params s3c_ac97_pcm_in = {
.client = &s3c_dma_client_in,
.dma_size = 4,
};
static struct s3c_dma_params s3c_ac97_mic_in = {
.client = &s3c_dma_client_micin,
.dma_size = 4,
};
static void s3c_ac97_activate(struct snd_ac97 *ac97)
{
u32 ac_glbctrl, stat;
stat = readl(s3c_ac97.regs + S3C_AC97_GLBSTAT) & 0x7;
if (stat == S3C_AC97_GLBSTAT_MAINSTATE_ACTIVE)
return; /* Return if already active */
INIT_COMPLETION(s3c_ac97.done);
ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL);
ac_glbctrl = S3C_AC97_GLBCTRL_ACLINKON;
writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL);
msleep(1);
ac_glbctrl |= S3C_AC97_GLBCTRL_TRANSFERDATAENABLE;
writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL);
msleep(1);
ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL);
ac_glbctrl |= S3C_AC97_GLBCTRL_CODECREADYIE;
writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL);
if (!wait_for_completion_timeout(&s3c_ac97.done, HZ))
pr_err("AC97: Unable to activate!");
}
static unsigned short s3c_ac97_read(struct snd_ac97 *ac97,
unsigned short reg)
{
u32 ac_glbctrl, ac_codec_cmd;
u32 stat, addr, data;
mutex_lock(&s3c_ac97.lock);
s3c_ac97_activate(ac97);
INIT_COMPLETION(s3c_ac97.done);
ac_codec_cmd = readl(s3c_ac97.regs + S3C_AC97_CODEC_CMD);
ac_codec_cmd = S3C_AC97_CODEC_CMD_READ | AC_CMD_ADDR(reg);
writel(ac_codec_cmd, s3c_ac97.regs + S3C_AC97_CODEC_CMD);
udelay(50);
ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL);
ac_glbctrl |= S3C_AC97_GLBCTRL_CODECREADYIE;
writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL);
if (!wait_for_completion_timeout(&s3c_ac97.done, HZ))
pr_err("AC97: Unable to read!");
stat = readl(s3c_ac97.regs + S3C_AC97_STAT);
addr = (stat >> 16) & 0x7f;
data = (stat & 0xffff);
if (addr != reg)
pr_err("ac97: req addr = %02x, rep addr = %02x\n",
reg, addr);
mutex_unlock(&s3c_ac97.lock);
return (unsigned short)data;
}
static void s3c_ac97_write(struct snd_ac97 *ac97, unsigned short reg,
unsigned short val)
{
u32 ac_glbctrl, ac_codec_cmd;
mutex_lock(&s3c_ac97.lock);
s3c_ac97_activate(ac97);
INIT_COMPLETION(s3c_ac97.done);
ac_codec_cmd = readl(s3c_ac97.regs + S3C_AC97_CODEC_CMD);
ac_codec_cmd = AC_CMD_ADDR(reg) | AC_CMD_DATA(val);
writel(ac_codec_cmd, s3c_ac97.regs + S3C_AC97_CODEC_CMD);
udelay(50);
ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL);
ac_glbctrl |= S3C_AC97_GLBCTRL_CODECREADYIE;
writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL);
if (!wait_for_completion_timeout(&s3c_ac97.done, HZ))
pr_err("AC97: Unable to write!");
ac_codec_cmd = readl(s3c_ac97.regs + S3C_AC97_CODEC_CMD);
ac_codec_cmd |= S3C_AC97_CODEC_CMD_READ;
writel(ac_codec_cmd, s3c_ac97.regs + S3C_AC97_CODEC_CMD);
mutex_unlock(&s3c_ac97.lock);
}
static void s3c_ac97_cold_reset(struct snd_ac97 *ac97)
{
pr_debug("AC97: Cold reset\n");
writel(S3C_AC97_GLBCTRL_COLDRESET,
s3c_ac97.regs + S3C_AC97_GLBCTRL);
msleep(1);
writel(0, s3c_ac97.regs + S3C_AC97_GLBCTRL);
msleep(1);
}
static void s3c_ac97_warm_reset(struct snd_ac97 *ac97)
{
u32 stat;
stat = readl(s3c_ac97.regs + S3C_AC97_GLBSTAT) & 0x7;
if (stat == S3C_AC97_GLBSTAT_MAINSTATE_ACTIVE)
return; /* Return if already active */
pr_debug("AC97: Warm reset\n");
writel(S3C_AC97_GLBCTRL_WARMRESET, s3c_ac97.regs + S3C_AC97_GLBCTRL);
msleep(1);
writel(0, s3c_ac97.regs + S3C_AC97_GLBCTRL);
msleep(1);
s3c_ac97_activate(ac97);
}
static irqreturn_t s3c_ac97_irq(int irq, void *dev_id)
{
u32 ac_glbctrl, ac_glbstat;
ac_glbstat = readl(s3c_ac97.regs + S3C_AC97_GLBSTAT);
if (ac_glbstat & S3C_AC97_GLBSTAT_CODECREADY) {
ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL);
ac_glbctrl &= ~S3C_AC97_GLBCTRL_CODECREADYIE;
writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL);
complete(&s3c_ac97.done);
}
ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL);
ac_glbctrl |= (1<<30); /* Clear interrupt */
writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL);
return IRQ_HANDLED;
}
struct snd_ac97_bus_ops soc_ac97_ops = {
.read = s3c_ac97_read,
.write = s3c_ac97_write,
.warm_reset = s3c_ac97_warm_reset,
.reset = s3c_ac97_cold_reset,
};
EXPORT_SYMBOL_GPL(soc_ac97_ops);
static int s3c_ac97_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_dai *cpu_dai = rtd->cpu_dai;
struct s3c_dma_params *dma_data;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
dma_data = &s3c_ac97_pcm_out;
else
dma_data = &s3c_ac97_pcm_in;
snd_soc_dai_set_dma_data(cpu_dai, substream, dma_data);
return 0;
}
static int s3c_ac97_trigger(struct snd_pcm_substream *substream, int cmd,
struct snd_soc_dai *dai)
{
u32 ac_glbctrl;
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct s3c_dma_params *dma_data =
snd_soc_dai_get_dma_data(rtd->cpu_dai, substream);
ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL);
if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
ac_glbctrl &= ~S3C_AC97_GLBCTRL_PCMINTM_MASK;
else
ac_glbctrl &= ~S3C_AC97_GLBCTRL_PCMOUTTM_MASK;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
ac_glbctrl |= S3C_AC97_GLBCTRL_PCMINTM_DMA;
else
ac_glbctrl |= S3C_AC97_GLBCTRL_PCMOUTTM_DMA;
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
break;
}
writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL);
if (!dma_data->ops)
dma_data->ops = samsung_dma_get_ops();
dma_data->ops->started(dma_data->channel);
return 0;
}
static int s3c_ac97_hw_mic_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_dai *cpu_dai = rtd->cpu_dai;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
return -ENODEV;
else
snd_soc_dai_set_dma_data(cpu_dai, substream, &s3c_ac97_mic_in);
return 0;
}
static int s3c_ac97_mic_trigger(struct snd_pcm_substream *substream,
int cmd, struct snd_soc_dai *dai)
{
u32 ac_glbctrl;
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct s3c_dma_params *dma_data =
snd_soc_dai_get_dma_data(rtd->cpu_dai, substream);
ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL);
ac_glbctrl &= ~S3C_AC97_GLBCTRL_MICINTM_MASK;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
ac_glbctrl |= S3C_AC97_GLBCTRL_MICINTM_DMA;
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
break;
}
writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL);
if (!dma_data->ops)
dma_data->ops = samsung_dma_get_ops();
dma_data->ops->started(dma_data->channel);
return 0;
}
static const struct snd_soc_dai_ops s3c_ac97_dai_ops = {
.hw_params = s3c_ac97_hw_params,
.trigger = s3c_ac97_trigger,
};
static const struct snd_soc_dai_ops s3c_ac97_mic_dai_ops = {
.hw_params = s3c_ac97_hw_mic_params,
.trigger = s3c_ac97_mic_trigger,
};
static struct snd_soc_dai_driver s3c_ac97_dai[] = {
[S3C_AC97_DAI_PCM] = {
.name = "samsung-ac97",
.ac97_control = 1,
.playback = {
.stream_name = "AC97 Playback",
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,},
.capture = {
.stream_name = "AC97 Capture",
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,},
.ops = &s3c_ac97_dai_ops,
},
[S3C_AC97_DAI_MIC] = {
.name = "samsung-ac97-mic",
.ac97_control = 1,
.capture = {
.stream_name = "AC97 Mic Capture",
.channels_min = 1,
.channels_max = 1,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,},
.ops = &s3c_ac97_mic_dai_ops,
},
};
static const struct snd_soc_component_driver s3c_ac97_component = {
.name = "s3c-ac97",
};
static int s3c_ac97_probe(struct platform_device *pdev)
{
struct resource *mem_res, *dmatx_res, *dmarx_res, *dmamic_res, *irq_res;
struct s3c_audio_pdata *ac97_pdata;
int ret;
ac97_pdata = pdev->dev.platform_data;
if (!ac97_pdata || !ac97_pdata->cfg_gpio) {
dev_err(&pdev->dev, "cfg_gpio callback not provided!\n");
return -EINVAL;
}
/* Check for availability of necessary resource */
dmatx_res = platform_get_resource(pdev, IORESOURCE_DMA, 0);
if (!dmatx_res) {
dev_err(&pdev->dev, "Unable to get AC97-TX dma resource\n");
return -ENXIO;
}
dmarx_res = platform_get_resource(pdev, IORESOURCE_DMA, 1);
if (!dmarx_res) {
dev_err(&pdev->dev, "Unable to get AC97-RX dma resource\n");
return -ENXIO;
}
dmamic_res = platform_get_resource(pdev, IORESOURCE_DMA, 2);
if (!dmamic_res) {
dev_err(&pdev->dev, "Unable to get AC97-MIC dma resource\n");
return -ENXIO;
}
mem_res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem_res) {
dev_err(&pdev->dev, "Unable to get register resource\n");
return -ENXIO;
}
irq_res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!irq_res) {
dev_err(&pdev->dev, "AC97 IRQ not provided!\n");
return -ENXIO;
}
if (!request_mem_region(mem_res->start,
resource_size(mem_res), "ac97")) {
dev_err(&pdev->dev, "Unable to request register region\n");
return -EBUSY;
}
s3c_ac97_pcm_out.channel = dmatx_res->start;
s3c_ac97_pcm_out.dma_addr = mem_res->start + S3C_AC97_PCM_DATA;
s3c_ac97_pcm_in.channel = dmarx_res->start;
s3c_ac97_pcm_in.dma_addr = mem_res->start + S3C_AC97_PCM_DATA;
s3c_ac97_mic_in.channel = dmamic_res->start;
s3c_ac97_mic_in.dma_addr = mem_res->start + S3C_AC97_MIC_DATA;
init_completion(&s3c_ac97.done);
mutex_init(&s3c_ac97.lock);
s3c_ac97.regs = ioremap(mem_res->start, resource_size(mem_res));
if (s3c_ac97.regs == NULL) {
dev_err(&pdev->dev, "Unable to ioremap register region\n");
ret = -ENXIO;
goto err1;
}
s3c_ac97.ac97_clk = clk_get(&pdev->dev, "ac97");
if (IS_ERR(s3c_ac97.ac97_clk)) {
dev_err(&pdev->dev, "ac97 failed to get ac97_clock\n");
ret = -ENODEV;
goto err2;
}
clk_prepare_enable(s3c_ac97.ac97_clk);
if (ac97_pdata->cfg_gpio(pdev)) {
dev_err(&pdev->dev, "Unable to configure gpio\n");
ret = -EINVAL;
goto err3;
}
ret = request_irq(irq_res->start, s3c_ac97_irq,
0, "AC97", NULL);
if (ret < 0) {
dev_err(&pdev->dev, "ac97: interrupt request failed.\n");
goto err4;
}
ret = snd_soc_register_component(&pdev->dev, &s3c_ac97_component,
s3c_ac97_dai, ARRAY_SIZE(s3c_ac97_dai));
if (ret)
goto err5;
ret = asoc_dma_platform_register(&pdev->dev);
if (ret) {
dev_err(&pdev->dev, "failed to get register DMA: %d\n", ret);
goto err6;
}
return 0;
err6:
snd_soc_unregister_component(&pdev->dev);
err5:
free_irq(irq_res->start, NULL);
err4:
err3:
clk_disable_unprepare(s3c_ac97.ac97_clk);
clk_put(s3c_ac97.ac97_clk);
err2:
iounmap(s3c_ac97.regs);
err1:
release_mem_region(mem_res->start, resource_size(mem_res));
return ret;
}
static int s3c_ac97_remove(struct platform_device *pdev)
{
struct resource *mem_res, *irq_res;
asoc_dma_platform_unregister(&pdev->dev);
snd_soc_unregister_component(&pdev->dev);
irq_res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (irq_res)
free_irq(irq_res->start, NULL);
clk_disable_unprepare(s3c_ac97.ac97_clk);
clk_put(s3c_ac97.ac97_clk);
iounmap(s3c_ac97.regs);
mem_res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (mem_res)
release_mem_region(mem_res->start, resource_size(mem_res));
return 0;
}
static struct platform_driver s3c_ac97_driver = {
.probe = s3c_ac97_probe,
.remove = s3c_ac97_remove,
.driver = {
.name = "samsung-ac97",
.owner = THIS_MODULE,
},
};
module_platform_driver(s3c_ac97_driver);
MODULE_AUTHOR("Jaswinder Singh, <jassisinghbrar@gmail.com>");
MODULE_DESCRIPTION("AC97 driver for the Samsung SoC");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:samsung-ac97");
| gpl-2.0 |
xhteam/kernel_imx | arch/arm/mach-sa1100/pm.c | 2430 | 2663 | /*
* SA1100 Power Management Routines
*
* Copyright (c) 2001 Cliff Brake <cbrake@accelent.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License.
*
* History:
*
* 2001-02-06: Cliff Brake Initial code
*
* 2001-02-25: Sukjae Cho <sjcho@east.isi.edu> &
* Chester Kuo <chester@linux.org.tw>
* Save more value for the resume function! Support
* Bitsy/Assabet/Freebird board
*
* 2001-08-29: Nicolas Pitre <nico@fluxnic.net>
* Cleaned up, pushed platform dependent stuff
* in the platform specific files.
*
* 2002-05-27: Nicolas Pitre Killed sleep.h and the kmalloced save array.
* Storage is local on the stack now.
*/
#include <linux/init.h>
#include <linux/suspend.h>
#include <linux/errno.h>
#include <linux/time.h>
#include <mach/hardware.h>
#include <asm/memory.h>
#include <asm/system.h>
#include <asm/mach/time.h>
extern void sa1100_cpu_suspend(long);
#define SAVE(x) sleep_save[SLEEP_SAVE_##x] = x
#define RESTORE(x) x = sleep_save[SLEEP_SAVE_##x]
/*
* List of global SA11x0 peripheral registers to preserve.
* More ones like CP and general purpose register values are preserved
* on the stack and then the stack pointer is stored last in sleep.S.
*/
enum { SLEEP_SAVE_GPDR, SLEEP_SAVE_GAFR,
SLEEP_SAVE_PPDR, SLEEP_SAVE_PPSR, SLEEP_SAVE_PPAR, SLEEP_SAVE_PSDR,
SLEEP_SAVE_Ser1SDCR0,
SLEEP_SAVE_COUNT
};
static int sa11x0_pm_enter(suspend_state_t state)
{
unsigned long gpio, sleep_save[SLEEP_SAVE_COUNT];
gpio = GPLR;
/* save vital registers */
SAVE(GPDR);
SAVE(GAFR);
SAVE(PPDR);
SAVE(PPSR);
SAVE(PPAR);
SAVE(PSDR);
SAVE(Ser1SDCR0);
/* Clear previous reset status */
RCSR = RCSR_HWR | RCSR_SWR | RCSR_WDR | RCSR_SMR;
/* set resume return address */
PSPR = virt_to_phys(cpu_resume);
/* go zzz */
sa1100_cpu_suspend(PLAT_PHYS_OFFSET - PAGE_OFFSET);
cpu_init();
/*
* Ensure not to come back here if it wasn't intended
*/
PSPR = 0;
/*
* Ensure interrupt sources are disabled; we will re-init
* the interrupt subsystem via the device manager.
*/
ICLR = 0;
ICCR = 1;
ICMR = 0;
/* restore registers */
RESTORE(GPDR);
RESTORE(GAFR);
RESTORE(PPDR);
RESTORE(PPSR);
RESTORE(PPAR);
RESTORE(PSDR);
RESTORE(Ser1SDCR0);
GPSR = gpio;
GPCR = ~gpio;
/*
* Clear the peripheral sleep-hold bit.
*/
PSSR = PSSR_PH;
return 0;
}
static const struct platform_suspend_ops sa11x0_pm_ops = {
.enter = sa11x0_pm_enter,
.valid = suspend_valid_only_mem,
};
static int __init sa11x0_pm_init(void)
{
suspend_set_ops(&sa11x0_pm_ops);
return 0;
}
late_initcall(sa11x0_pm_init);
| gpl-2.0 |
binkybear/flounder | drivers/gpu/drm/nouveau/core/core/client.c | 2686 | 3272 | /*
* Copyright 2012 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 <core/object.h>
#include <core/client.h>
#include <core/handle.h>
#include <core/option.h>
#include <engine/device.h>
static void
nouveau_client_dtor(struct nouveau_object *object)
{
struct nouveau_client *client = (void *)object;
nouveau_object_ref(NULL, &client->device);
nouveau_handle_destroy(client->root);
nouveau_namedb_destroy(&client->base);
}
static struct nouveau_oclass
nouveau_client_oclass = {
.ofuncs = &(struct nouveau_ofuncs) {
.dtor = nouveau_client_dtor,
},
};
int
nouveau_client_create_(const char *name, u64 devname, const char *cfg,
const char *dbg, int length, void **pobject)
{
struct nouveau_object *device;
struct nouveau_client *client;
int ret;
device = (void *)nouveau_device_find(devname);
if (!device)
return -ENODEV;
ret = nouveau_namedb_create_(NULL, NULL, &nouveau_client_oclass,
NV_CLIENT_CLASS, NULL,
(1ULL << NVDEV_ENGINE_DEVICE),
length, pobject);
client = *pobject;
if (ret)
return ret;
ret = nouveau_handle_create(nv_object(client), ~0, ~0,
nv_object(client), &client->root);
if (ret)
return ret;
/* prevent init/fini being called, os in in charge of this */
atomic_set(&nv_object(client)->usecount, 2);
nouveau_object_ref(device, &client->device);
snprintf(client->name, sizeof(client->name), "%s", name);
client->debug = nouveau_dbgopt(dbg, "CLIENT");
return 0;
}
int
nouveau_client_init(struct nouveau_client *client)
{
int ret;
nv_debug(client, "init running\n");
ret = nouveau_handle_init(client->root);
nv_debug(client, "init completed with %d\n", ret);
return ret;
}
int
nouveau_client_fini(struct nouveau_client *client, bool suspend)
{
const char *name[2] = { "fini", "suspend" };
int ret;
nv_debug(client, "%s running\n", name[suspend]);
ret = nouveau_handle_fini(client->root, suspend);
nv_debug(client, "%s completed with %d\n", name[suspend], ret);
return ret;
}
const char *
nouveau_client_name(void *obj)
{
const char *client_name = "unknown";
struct nouveau_client *client = nouveau_client(obj);
if (client)
client_name = client->name;
return client_name;
}
| gpl-2.0 |
CyanHacker-Lollipop/kernel_moto_shamu | drivers/gpu/drm/nouveau/core/engine/graph/nv34.c | 2686 | 5357 | #include <core/os.h>
#include <core/class.h>
#include <core/engctx.h>
#include <core/enum.h>
#include <subdev/timer.h>
#include <subdev/fb.h>
#include <engine/graph.h>
#include "nv20.h"
#include "regs.h"
/*******************************************************************************
* Graphics object classes
******************************************************************************/
static struct nouveau_oclass
nv34_graph_sclass[] = {
{ 0x0012, &nv04_graph_ofuncs, NULL }, /* beta1 */
{ 0x0019, &nv04_graph_ofuncs, NULL }, /* clip */
{ 0x0030, &nv04_graph_ofuncs, NULL }, /* null */
{ 0x0039, &nv04_graph_ofuncs, NULL }, /* m2mf */
{ 0x0043, &nv04_graph_ofuncs, NULL }, /* rop */
{ 0x0044, &nv04_graph_ofuncs, NULL }, /* patt */
{ 0x004a, &nv04_graph_ofuncs, NULL }, /* gdi */
{ 0x0062, &nv04_graph_ofuncs, NULL }, /* surf2d */
{ 0x0072, &nv04_graph_ofuncs, NULL }, /* beta4 */
{ 0x0089, &nv04_graph_ofuncs, NULL }, /* sifm */
{ 0x008a, &nv04_graph_ofuncs, NULL }, /* ifc */
{ 0x009f, &nv04_graph_ofuncs, NULL }, /* imageblit */
{ 0x0362, &nv04_graph_ofuncs, NULL }, /* surf2d (nv30) */
{ 0x0389, &nv04_graph_ofuncs, NULL }, /* sifm (nv30) */
{ 0x038a, &nv04_graph_ofuncs, NULL }, /* ifc (nv30) */
{ 0x039e, &nv04_graph_ofuncs, NULL }, /* swzsurf (nv30) */
{ 0x0697, &nv04_graph_ofuncs, NULL }, /* rankine */
{},
};
/*******************************************************************************
* PGRAPH context
******************************************************************************/
static int
nv34_graph_context_ctor(struct nouveau_object *parent,
struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 size,
struct nouveau_object **pobject)
{
struct nv20_graph_chan *chan;
int ret, i;
ret = nouveau_graph_context_create(parent, engine, oclass, NULL, 0x46dc,
16, NVOBJ_FLAG_ZERO_ALLOC, &chan);
*pobject = nv_object(chan);
if (ret)
return ret;
chan->chid = nouveau_fifo_chan(parent)->chid;
nv_wo32(chan, 0x0028, 0x00000001 | (chan->chid << 24));
nv_wo32(chan, 0x040c, 0x01000101);
nv_wo32(chan, 0x0420, 0x00000111);
nv_wo32(chan, 0x0424, 0x00000060);
nv_wo32(chan, 0x0440, 0x00000080);
nv_wo32(chan, 0x0444, 0xffff0000);
nv_wo32(chan, 0x0448, 0x00000001);
nv_wo32(chan, 0x045c, 0x44400000);
nv_wo32(chan, 0x0480, 0xffff0000);
for (i = 0x04d4; i < 0x04dc; i += 4)
nv_wo32(chan, i, 0x0fff0000);
nv_wo32(chan, 0x04e0, 0x00011100);
for (i = 0x04fc; i < 0x053c; i += 4)
nv_wo32(chan, i, 0x07ff0000);
nv_wo32(chan, 0x0544, 0x4b7fffff);
nv_wo32(chan, 0x057c, 0x00000080);
nv_wo32(chan, 0x0580, 0x30201000);
nv_wo32(chan, 0x0584, 0x70605040);
nv_wo32(chan, 0x0588, 0xb8a89888);
nv_wo32(chan, 0x058c, 0xf8e8d8c8);
nv_wo32(chan, 0x05a0, 0xb0000000);
for (i = 0x05f0; i < 0x0630; i += 4)
nv_wo32(chan, i, 0x00010588);
for (i = 0x0630; i < 0x0670; i += 4)
nv_wo32(chan, i, 0x00030303);
for (i = 0x06b0; i < 0x06f0; i += 4)
nv_wo32(chan, i, 0x0008aae4);
for (i = 0x06f0; i < 0x0730; i += 4)
nv_wo32(chan, i, 0x01012000);
for (i = 0x0730; i < 0x0770; i += 4)
nv_wo32(chan, i, 0x00080008);
nv_wo32(chan, 0x0850, 0x00040000);
nv_wo32(chan, 0x0854, 0x00010000);
for (i = 0x0858; i < 0x0868; i += 4)
nv_wo32(chan, i, 0x00040004);
for (i = 0x15ac; i <= 0x271c ; i += 16) {
nv_wo32(chan, i + 0, 0x10700ff9);
nv_wo32(chan, i + 1, 0x0436086c);
nv_wo32(chan, i + 2, 0x000c001b);
}
for (i = 0x274c; i < 0x275c; i += 4)
nv_wo32(chan, i, 0x0000ffff);
nv_wo32(chan, 0x2ae0, 0x3f800000);
nv_wo32(chan, 0x2e9c, 0x3f800000);
nv_wo32(chan, 0x2eb0, 0x3f800000);
nv_wo32(chan, 0x2edc, 0x40000000);
nv_wo32(chan, 0x2ee0, 0x3f800000);
nv_wo32(chan, 0x2ee4, 0x3f000000);
nv_wo32(chan, 0x2eec, 0x40000000);
nv_wo32(chan, 0x2ef0, 0x3f800000);
nv_wo32(chan, 0x2ef8, 0xbf800000);
nv_wo32(chan, 0x2f00, 0xbf800000);
return 0;
}
static struct nouveau_oclass
nv34_graph_cclass = {
.handle = NV_ENGCTX(GR, 0x34),
.ofuncs = &(struct nouveau_ofuncs) {
.ctor = nv34_graph_context_ctor,
.dtor = _nouveau_graph_context_dtor,
.init = nv20_graph_context_init,
.fini = nv20_graph_context_fini,
.rd32 = _nouveau_graph_context_rd32,
.wr32 = _nouveau_graph_context_wr32,
},
};
/*******************************************************************************
* PGRAPH engine/subdev functions
******************************************************************************/
static int
nv34_graph_ctor(struct nouveau_object *parent, struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 size,
struct nouveau_object **pobject)
{
struct nv20_graph_priv *priv;
int ret;
ret = nouveau_graph_create(parent, engine, oclass, true, &priv);
*pobject = nv_object(priv);
if (ret)
return ret;
ret = nouveau_gpuobj_new(nv_object(priv), NULL, 32 * 4, 16,
NVOBJ_FLAG_ZERO_ALLOC, &priv->ctxtab);
if (ret)
return ret;
nv_subdev(priv)->unit = 0x00001000;
nv_subdev(priv)->intr = nv20_graph_intr;
nv_engine(priv)->cclass = &nv34_graph_cclass;
nv_engine(priv)->sclass = nv34_graph_sclass;
nv_engine(priv)->tile_prog = nv20_graph_tile_prog;
return 0;
}
struct nouveau_oclass
nv34_graph_oclass = {
.handle = NV_ENGINE(GR, 0x34),
.ofuncs = &(struct nouveau_ofuncs) {
.ctor = nv34_graph_ctor,
.dtor = nv20_graph_dtor,
.init = nv30_graph_init,
.fini = _nouveau_graph_fini,
},
};
| gpl-2.0 |
Silentlys/android_kernel_qcom_msm8916 | drivers/net/wireless/hostap/hostap_plx.c | 2686 | 16562 | #define PRISM2_PLX
/* Host AP driver's support for PC Cards on PCI adapters using PLX9052 is
* based on:
* - Host AP driver patch from james@madingley.org
* - linux-wlan-ng driver, Copyright (C) AbsoluteValue Systems, Inc.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/if.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/wireless.h>
#include <net/iw_handler.h>
#include <linux/ioport.h>
#include <linux/pci.h>
#include <asm/io.h>
#include "hostap_wlan.h"
static char *dev_info = "hostap_plx";
MODULE_AUTHOR("Jouni Malinen");
MODULE_DESCRIPTION("Support for Intersil Prism2-based 802.11 wireless LAN "
"cards (PLX).");
MODULE_SUPPORTED_DEVICE("Intersil Prism2-based WLAN cards (PLX)");
MODULE_LICENSE("GPL");
static int ignore_cis;
module_param(ignore_cis, int, 0444);
MODULE_PARM_DESC(ignore_cis, "Do not verify manfid information in CIS");
/* struct local_info::hw_priv */
struct hostap_plx_priv {
void __iomem *attr_mem;
unsigned int cor_offset;
};
#define PLX_MIN_ATTR_LEN 512 /* at least 2 x 256 is needed for CIS */
#define COR_SRESET 0x80
#define COR_LEVLREQ 0x40
#define COR_ENABLE_FUNC 0x01
/* PCI Configuration Registers */
#define PLX_PCIIPR 0x3d /* PCI Interrupt Pin */
/* Local Configuration Registers */
#define PLX_INTCSR 0x4c /* Interrupt Control/Status Register */
#define PLX_INTCSR_PCI_INTEN BIT(6) /* PCI Interrupt Enable */
#define PLX_CNTRL 0x50
#define PLX_CNTRL_SERIAL_EEPROM_PRESENT BIT(28)
#define PLXDEV(vendor,dev,str) { vendor, dev, PCI_ANY_ID, PCI_ANY_ID }
static DEFINE_PCI_DEVICE_TABLE(prism2_plx_id_table) = {
PLXDEV(0x10b7, 0x7770, "3Com AirConnect PCI 777A"),
PLXDEV(0x111a, 0x1023, "Siemens SpeedStream SS1023"),
PLXDEV(0x126c, 0x8030, "Nortel emobility"),
PLXDEV(0x1562, 0x0001, "Symbol LA-4123"),
PLXDEV(0x1385, 0x4100, "Netgear MA301"),
PLXDEV(0x15e8, 0x0130, "National Datacomm NCP130 (PLX9052)"),
PLXDEV(0x15e8, 0x0131, "National Datacomm NCP130 (TMD7160)"),
PLXDEV(0x1638, 0x1100, "Eumitcom WL11000"),
PLXDEV(0x16ab, 0x1100, "Global Sun Tech GL24110P"),
PLXDEV(0x16ab, 0x1101, "Global Sun Tech GL24110P (?)"),
PLXDEV(0x16ab, 0x1102, "Linksys WPC11 with WDT11"),
PLXDEV(0x16ab, 0x1103, "Longshine 8031"),
PLXDEV(0x16ec, 0x3685, "US Robotics USR2415"),
PLXDEV(0xec80, 0xec00, "Belkin F5D6000"),
{ 0 }
};
/* Array of known Prism2/2.5 PC Card manufactured ids. If your card's manfid
* is not listed here, you will need to add it here to get the driver
* initialized. */
static struct prism2_plx_manfid {
u16 manfid1, manfid2;
} prism2_plx_known_manfids[] = {
{ 0x000b, 0x7110 } /* D-Link DWL-650 Rev. P1 */,
{ 0x000b, 0x7300 } /* Philips 802.11b WLAN PCMCIA */,
{ 0x0101, 0x0777 } /* 3Com AirConnect PCI 777A */,
{ 0x0126, 0x8000 } /* Proxim RangeLAN */,
{ 0x0138, 0x0002 } /* Compaq WL100 */,
{ 0x0156, 0x0002 } /* Intersil Prism II Ref. Design (and others) */,
{ 0x026f, 0x030b } /* Buffalo WLI-CF-S11G */,
{ 0x0274, 0x1612 } /* Linksys WPC11 Ver 2.5 */,
{ 0x0274, 0x1613 } /* Linksys WPC11 Ver 3 */,
{ 0x028a, 0x0002 } /* D-Link DRC-650 */,
{ 0x0250, 0x0002 } /* Samsung SWL2000-N */,
{ 0xc250, 0x0002 } /* EMTAC A2424i */,
{ 0xd601, 0x0002 } /* Z-Com XI300 */,
{ 0xd601, 0x0005 } /* Zcomax XI-325H 200mW */,
{ 0, 0}
};
#ifdef PRISM2_IO_DEBUG
static inline void hfa384x_outb_debug(struct net_device *dev, int a, u8 v)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTB, a, v);
outb(v, dev->base_addr + a);
spin_unlock_irqrestore(&local->lock, flags);
}
static inline u8 hfa384x_inb_debug(struct net_device *dev, int a)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
u8 v;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
v = inb(dev->base_addr + a);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INB, a, v);
spin_unlock_irqrestore(&local->lock, flags);
return v;
}
static inline void hfa384x_outw_debug(struct net_device *dev, int a, u16 v)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTW, a, v);
outw(v, dev->base_addr + a);
spin_unlock_irqrestore(&local->lock, flags);
}
static inline u16 hfa384x_inw_debug(struct net_device *dev, int a)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
u16 v;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
v = inw(dev->base_addr + a);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INW, a, v);
spin_unlock_irqrestore(&local->lock, flags);
return v;
}
static inline void hfa384x_outsw_debug(struct net_device *dev, int a,
u8 *buf, int wc)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTSW, a, wc);
outsw(dev->base_addr + a, buf, wc);
spin_unlock_irqrestore(&local->lock, flags);
}
static inline void hfa384x_insw_debug(struct net_device *dev, int a,
u8 *buf, int wc)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INSW, a, wc);
insw(dev->base_addr + a, buf, wc);
spin_unlock_irqrestore(&local->lock, flags);
}
#define HFA384X_OUTB(v,a) hfa384x_outb_debug(dev, (a), (v))
#define HFA384X_INB(a) hfa384x_inb_debug(dev, (a))
#define HFA384X_OUTW(v,a) hfa384x_outw_debug(dev, (a), (v))
#define HFA384X_INW(a) hfa384x_inw_debug(dev, (a))
#define HFA384X_OUTSW(a, buf, wc) hfa384x_outsw_debug(dev, (a), (buf), (wc))
#define HFA384X_INSW(a, buf, wc) hfa384x_insw_debug(dev, (a), (buf), (wc))
#else /* PRISM2_IO_DEBUG */
#define HFA384X_OUTB(v,a) outb((v), dev->base_addr + (a))
#define HFA384X_INB(a) inb(dev->base_addr + (a))
#define HFA384X_OUTW(v,a) outw((v), dev->base_addr + (a))
#define HFA384X_INW(a) inw(dev->base_addr + (a))
#define HFA384X_INSW(a, buf, wc) insw(dev->base_addr + (a), buf, wc)
#define HFA384X_OUTSW(a, buf, wc) outsw(dev->base_addr + (a), buf, wc)
#endif /* PRISM2_IO_DEBUG */
static int hfa384x_from_bap(struct net_device *dev, u16 bap, void *buf,
int len)
{
u16 d_off;
u16 *pos;
d_off = (bap == 1) ? HFA384X_DATA1_OFF : HFA384X_DATA0_OFF;
pos = (u16 *) buf;
if (len / 2)
HFA384X_INSW(d_off, buf, len / 2);
pos += len / 2;
if (len & 1)
*((char *) pos) = HFA384X_INB(d_off);
return 0;
}
static int hfa384x_to_bap(struct net_device *dev, u16 bap, void *buf, int len)
{
u16 d_off;
u16 *pos;
d_off = (bap == 1) ? HFA384X_DATA1_OFF : HFA384X_DATA0_OFF;
pos = (u16 *) buf;
if (len / 2)
HFA384X_OUTSW(d_off, buf, len / 2);
pos += len / 2;
if (len & 1)
HFA384X_OUTB(*((char *) pos), d_off);
return 0;
}
/* FIX: This might change at some point.. */
#include "hostap_hw.c"
static void prism2_plx_cor_sreset(local_info_t *local)
{
unsigned char corsave;
struct hostap_plx_priv *hw_priv = local->hw_priv;
printk(KERN_DEBUG "%s: Doing reset via direct COR access.\n",
dev_info);
/* Set sreset bit of COR and clear it after hold time */
if (hw_priv->attr_mem == NULL) {
/* TMD7160 - COR at card's first I/O addr */
corsave = inb(hw_priv->cor_offset);
outb(corsave | COR_SRESET, hw_priv->cor_offset);
mdelay(2);
outb(corsave & ~COR_SRESET, hw_priv->cor_offset);
mdelay(2);
} else {
/* PLX9052 */
corsave = readb(hw_priv->attr_mem + hw_priv->cor_offset);
writeb(corsave | COR_SRESET,
hw_priv->attr_mem + hw_priv->cor_offset);
mdelay(2);
writeb(corsave & ~COR_SRESET,
hw_priv->attr_mem + hw_priv->cor_offset);
mdelay(2);
}
}
static void prism2_plx_genesis_reset(local_info_t *local, int hcr)
{
unsigned char corsave;
struct hostap_plx_priv *hw_priv = local->hw_priv;
if (hw_priv->attr_mem == NULL) {
/* TMD7160 - COR at card's first I/O addr */
corsave = inb(hw_priv->cor_offset);
outb(corsave | COR_SRESET, hw_priv->cor_offset);
mdelay(10);
outb(hcr, hw_priv->cor_offset + 2);
mdelay(10);
outb(corsave & ~COR_SRESET, hw_priv->cor_offset);
mdelay(10);
} else {
/* PLX9052 */
corsave = readb(hw_priv->attr_mem + hw_priv->cor_offset);
writeb(corsave | COR_SRESET,
hw_priv->attr_mem + hw_priv->cor_offset);
mdelay(10);
writeb(hcr, hw_priv->attr_mem + hw_priv->cor_offset + 2);
mdelay(10);
writeb(corsave & ~COR_SRESET,
hw_priv->attr_mem + hw_priv->cor_offset);
mdelay(10);
}
}
static struct prism2_helper_functions prism2_plx_funcs =
{
.card_present = NULL,
.cor_sreset = prism2_plx_cor_sreset,
.genesis_reset = prism2_plx_genesis_reset,
.hw_type = HOSTAP_HW_PLX,
};
static int prism2_plx_check_cis(void __iomem *attr_mem, int attr_len,
unsigned int *cor_offset,
unsigned int *cor_index)
{
#define CISTPL_CONFIG 0x1A
#define CISTPL_MANFID 0x20
#define CISTPL_END 0xFF
#define CIS_MAX_LEN 256
u8 *cis;
int i, pos;
unsigned int rmsz, rasz, manfid1, manfid2;
struct prism2_plx_manfid *manfid;
cis = kmalloc(CIS_MAX_LEN, GFP_KERNEL);
if (cis == NULL)
return -ENOMEM;
/* read CIS; it is in even offsets in the beginning of attr_mem */
for (i = 0; i < CIS_MAX_LEN; i++)
cis[i] = readb(attr_mem + 2 * i);
printk(KERN_DEBUG "%s: CIS: %02x %02x %02x %02x %02x %02x ...\n",
dev_info, cis[0], cis[1], cis[2], cis[3], cis[4], cis[5]);
/* set reasonable defaults for Prism2 cards just in case CIS parsing
* fails */
*cor_offset = 0x3e0;
*cor_index = 0x01;
manfid1 = manfid2 = 0;
pos = 0;
while (pos < CIS_MAX_LEN - 1 && cis[pos] != CISTPL_END) {
if (pos + 2 + cis[pos + 1] > CIS_MAX_LEN)
goto cis_error;
switch (cis[pos]) {
case CISTPL_CONFIG:
if (cis[pos + 1] < 2)
goto cis_error;
rmsz = (cis[pos + 2] & 0x3c) >> 2;
rasz = cis[pos + 2] & 0x03;
if (4 + rasz + rmsz > cis[pos + 1])
goto cis_error;
*cor_index = cis[pos + 3] & 0x3F;
*cor_offset = 0;
for (i = 0; i <= rasz; i++)
*cor_offset += cis[pos + 4 + i] << (8 * i);
printk(KERN_DEBUG "%s: cor_index=0x%x "
"cor_offset=0x%x\n", dev_info,
*cor_index, *cor_offset);
if (*cor_offset > attr_len) {
printk(KERN_ERR "%s: COR offset not within "
"attr_mem\n", dev_info);
kfree(cis);
return -1;
}
break;
case CISTPL_MANFID:
if (cis[pos + 1] < 4)
goto cis_error;
manfid1 = cis[pos + 2] + (cis[pos + 3] << 8);
manfid2 = cis[pos + 4] + (cis[pos + 5] << 8);
printk(KERN_DEBUG "%s: manfid=0x%04x, 0x%04x\n",
dev_info, manfid1, manfid2);
break;
}
pos += cis[pos + 1] + 2;
}
if (pos >= CIS_MAX_LEN || cis[pos] != CISTPL_END)
goto cis_error;
for (manfid = prism2_plx_known_manfids; manfid->manfid1 != 0; manfid++)
if (manfid1 == manfid->manfid1 && manfid2 == manfid->manfid2) {
kfree(cis);
return 0;
}
printk(KERN_INFO "%s: unknown manfid 0x%04x, 0x%04x - assuming this is"
" not supported card\n", dev_info, manfid1, manfid2);
goto fail;
cis_error:
printk(KERN_WARNING "%s: invalid CIS data\n", dev_info);
fail:
kfree(cis);
if (ignore_cis) {
printk(KERN_INFO "%s: ignore_cis parameter set - ignoring "
"errors during CIS verification\n", dev_info);
return 0;
}
return -1;
}
static int prism2_plx_probe(struct pci_dev *pdev,
const struct pci_device_id *id)
{
unsigned int pccard_ioaddr, plx_ioaddr;
unsigned long pccard_attr_mem;
unsigned int pccard_attr_len;
void __iomem *attr_mem = NULL;
unsigned int cor_offset = 0, cor_index = 0;
u32 reg;
local_info_t *local = NULL;
struct net_device *dev = NULL;
struct hostap_interface *iface;
static int cards_found /* = 0 */;
int irq_registered = 0;
int tmd7160;
struct hostap_plx_priv *hw_priv;
hw_priv = kzalloc(sizeof(*hw_priv), GFP_KERNEL);
if (hw_priv == NULL)
return -ENOMEM;
if (pci_enable_device(pdev))
goto err_out_free;
/* National Datacomm NCP130 based on TMD7160, not PLX9052. */
tmd7160 = (pdev->vendor == 0x15e8) && (pdev->device == 0x0131);
plx_ioaddr = pci_resource_start(pdev, 1);
pccard_ioaddr = pci_resource_start(pdev, tmd7160 ? 2 : 3);
if (tmd7160) {
/* TMD7160 */
attr_mem = NULL; /* no access to PC Card attribute memory */
printk(KERN_INFO "TMD7160 PCI/PCMCIA adapter: io=0x%x, "
"irq=%d, pccard_io=0x%x\n",
plx_ioaddr, pdev->irq, pccard_ioaddr);
cor_offset = plx_ioaddr;
cor_index = 0x04;
outb(cor_index | COR_LEVLREQ | COR_ENABLE_FUNC, plx_ioaddr);
mdelay(1);
reg = inb(plx_ioaddr);
if (reg != (cor_index | COR_LEVLREQ | COR_ENABLE_FUNC)) {
printk(KERN_ERR "%s: Error setting COR (expected="
"0x%02x, was=0x%02x)\n", dev_info,
cor_index | COR_LEVLREQ | COR_ENABLE_FUNC, reg);
goto fail;
}
} else {
/* PLX9052 */
pccard_attr_mem = pci_resource_start(pdev, 2);
pccard_attr_len = pci_resource_len(pdev, 2);
if (pccard_attr_len < PLX_MIN_ATTR_LEN)
goto fail;
attr_mem = ioremap(pccard_attr_mem, pccard_attr_len);
if (attr_mem == NULL) {
printk(KERN_ERR "%s: cannot remap attr_mem\n",
dev_info);
goto fail;
}
printk(KERN_INFO "PLX9052 PCI/PCMCIA adapter: "
"mem=0x%lx, plx_io=0x%x, irq=%d, pccard_io=0x%x\n",
pccard_attr_mem, plx_ioaddr, pdev->irq, pccard_ioaddr);
if (prism2_plx_check_cis(attr_mem, pccard_attr_len,
&cor_offset, &cor_index)) {
printk(KERN_INFO "Unknown PC Card CIS - not a "
"Prism2/2.5 card?\n");
goto fail;
}
printk(KERN_DEBUG "Prism2/2.5 PC Card detected in PLX9052 "
"adapter\n");
/* Write COR to enable PC Card */
writeb(cor_index | COR_LEVLREQ | COR_ENABLE_FUNC,
attr_mem + cor_offset);
/* Enable PCI interrupts if they are not already enabled */
reg = inl(plx_ioaddr + PLX_INTCSR);
printk(KERN_DEBUG "PLX_INTCSR=0x%x\n", reg);
if (!(reg & PLX_INTCSR_PCI_INTEN)) {
outl(reg | PLX_INTCSR_PCI_INTEN,
plx_ioaddr + PLX_INTCSR);
if (!(inl(plx_ioaddr + PLX_INTCSR) &
PLX_INTCSR_PCI_INTEN)) {
printk(KERN_WARNING "%s: Could not enable "
"Local Interrupts\n", dev_info);
goto fail;
}
}
reg = inl(plx_ioaddr + PLX_CNTRL);
printk(KERN_DEBUG "PLX_CNTRL=0x%x (Serial EEPROM "
"present=%d)\n",
reg, (reg & PLX_CNTRL_SERIAL_EEPROM_PRESENT) != 0);
/* should set PLX_PCIIPR to 0x01 (INTA#) if Serial EEPROM is
* not present; but are there really such cards in use(?) */
}
dev = prism2_init_local_data(&prism2_plx_funcs, cards_found,
&pdev->dev);
if (dev == NULL)
goto fail;
iface = netdev_priv(dev);
local = iface->local;
local->hw_priv = hw_priv;
cards_found++;
dev->irq = pdev->irq;
dev->base_addr = pccard_ioaddr;
hw_priv->attr_mem = attr_mem;
hw_priv->cor_offset = cor_offset;
pci_set_drvdata(pdev, dev);
if (request_irq(dev->irq, prism2_interrupt, IRQF_SHARED, dev->name,
dev)) {
printk(KERN_WARNING "%s: request_irq failed\n", dev->name);
goto fail;
} else
irq_registered = 1;
if (prism2_hw_config(dev, 1)) {
printk(KERN_DEBUG "%s: hardware initialization failed\n",
dev_info);
goto fail;
}
return hostap_hw_ready(dev);
fail:
if (irq_registered && dev)
free_irq(dev->irq, dev);
if (attr_mem)
iounmap(attr_mem);
pci_disable_device(pdev);
prism2_free_local_data(dev);
err_out_free:
kfree(hw_priv);
return -ENODEV;
}
static void prism2_plx_remove(struct pci_dev *pdev)
{
struct net_device *dev;
struct hostap_interface *iface;
struct hostap_plx_priv *hw_priv;
dev = pci_get_drvdata(pdev);
iface = netdev_priv(dev);
hw_priv = iface->local->hw_priv;
/* Reset the hardware, and ensure interrupts are disabled. */
prism2_plx_cor_sreset(iface->local);
hfa384x_disable_interrupts(dev);
if (hw_priv->attr_mem)
iounmap(hw_priv->attr_mem);
if (dev->irq)
free_irq(dev->irq, dev);
prism2_free_local_data(dev);
kfree(hw_priv);
pci_disable_device(pdev);
}
MODULE_DEVICE_TABLE(pci, prism2_plx_id_table);
static struct pci_driver prism2_plx_driver = {
.name = "hostap_plx",
.id_table = prism2_plx_id_table,
.probe = prism2_plx_probe,
.remove = prism2_plx_remove,
};
module_pci_driver(prism2_plx_driver);
| gpl-2.0 |
Klozz/XPerience_Kernel_msm8226_mmi_Falcon | drivers/net/wireless/iwlwifi/iwl-core.c | 3966 | 41834 | /******************************************************************************
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2008 - 2012 Intel Corporation. All rights reserved.
*
* 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.GPL.
*
* Contact Information:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*****************************************************************************/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/etherdevice.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <net/mac80211.h>
#include "iwl-eeprom.h"
#include "iwl-debug.h"
#include "iwl-core.h"
#include "iwl-io.h"
#include "iwl-power.h"
#include "iwl-shared.h"
#include "iwl-agn.h"
#include "iwl-trans.h"
const u8 iwl_bcast_addr[ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
#define MAX_BIT_RATE_40_MHZ 150 /* Mbps */
#define MAX_BIT_RATE_20_MHZ 72 /* Mbps */
static void iwl_init_ht_hw_capab(const struct iwl_priv *priv,
struct ieee80211_sta_ht_cap *ht_info,
enum ieee80211_band band)
{
u16 max_bit_rate = 0;
u8 rx_chains_num = hw_params(priv).rx_chains_num;
u8 tx_chains_num = hw_params(priv).tx_chains_num;
ht_info->cap = 0;
memset(&ht_info->mcs, 0, sizeof(ht_info->mcs));
ht_info->ht_supported = true;
if (cfg(priv)->ht_params &&
cfg(priv)->ht_params->ht_greenfield_support)
ht_info->cap |= IEEE80211_HT_CAP_GRN_FLD;
ht_info->cap |= IEEE80211_HT_CAP_SGI_20;
max_bit_rate = MAX_BIT_RATE_20_MHZ;
if (hw_params(priv).ht40_channel & BIT(band)) {
ht_info->cap |= IEEE80211_HT_CAP_SUP_WIDTH_20_40;
ht_info->cap |= IEEE80211_HT_CAP_SGI_40;
ht_info->mcs.rx_mask[4] = 0x01;
max_bit_rate = MAX_BIT_RATE_40_MHZ;
}
if (iwlagn_mod_params.amsdu_size_8K)
ht_info->cap |= IEEE80211_HT_CAP_MAX_AMSDU;
ht_info->ampdu_factor = CFG_HT_RX_AMPDU_FACTOR_DEF;
ht_info->ampdu_density = CFG_HT_MPDU_DENSITY_DEF;
ht_info->mcs.rx_mask[0] = 0xFF;
if (rx_chains_num >= 2)
ht_info->mcs.rx_mask[1] = 0xFF;
if (rx_chains_num >= 3)
ht_info->mcs.rx_mask[2] = 0xFF;
/* Highest supported Rx data rate */
max_bit_rate *= rx_chains_num;
WARN_ON(max_bit_rate & ~IEEE80211_HT_MCS_RX_HIGHEST_MASK);
ht_info->mcs.rx_highest = cpu_to_le16(max_bit_rate);
/* Tx MCS capabilities */
ht_info->mcs.tx_params = IEEE80211_HT_MCS_TX_DEFINED;
if (tx_chains_num != rx_chains_num) {
ht_info->mcs.tx_params |= IEEE80211_HT_MCS_TX_RX_DIFF;
ht_info->mcs.tx_params |= ((tx_chains_num - 1) <<
IEEE80211_HT_MCS_TX_MAX_STREAMS_SHIFT);
}
}
/**
* iwl_init_geos - Initialize mac80211's geo/channel info based from eeprom
*/
int iwl_init_geos(struct iwl_priv *priv)
{
struct iwl_channel_info *ch;
struct ieee80211_supported_band *sband;
struct ieee80211_channel *channels;
struct ieee80211_channel *geo_ch;
struct ieee80211_rate *rates;
int i = 0;
s8 max_tx_power = IWLAGN_TX_POWER_TARGET_POWER_MIN;
if (priv->bands[IEEE80211_BAND_2GHZ].n_bitrates ||
priv->bands[IEEE80211_BAND_5GHZ].n_bitrates) {
IWL_DEBUG_INFO(priv, "Geography modes already initialized.\n");
set_bit(STATUS_GEO_CONFIGURED, &priv->status);
return 0;
}
channels = kcalloc(priv->channel_count,
sizeof(struct ieee80211_channel), GFP_KERNEL);
if (!channels)
return -ENOMEM;
rates = kcalloc(IWL_RATE_COUNT_LEGACY, sizeof(struct ieee80211_rate),
GFP_KERNEL);
if (!rates) {
kfree(channels);
return -ENOMEM;
}
/* 5.2GHz channels start after the 2.4GHz channels */
sband = &priv->bands[IEEE80211_BAND_5GHZ];
sband->channels = &channels[ARRAY_SIZE(iwl_eeprom_band_1)];
/* just OFDM */
sband->bitrates = &rates[IWL_FIRST_OFDM_RATE];
sband->n_bitrates = IWL_RATE_COUNT_LEGACY - IWL_FIRST_OFDM_RATE;
if (hw_params(priv).sku & EEPROM_SKU_CAP_11N_ENABLE)
iwl_init_ht_hw_capab(priv, &sband->ht_cap,
IEEE80211_BAND_5GHZ);
sband = &priv->bands[IEEE80211_BAND_2GHZ];
sband->channels = channels;
/* OFDM & CCK */
sband->bitrates = rates;
sband->n_bitrates = IWL_RATE_COUNT_LEGACY;
if (hw_params(priv).sku & EEPROM_SKU_CAP_11N_ENABLE)
iwl_init_ht_hw_capab(priv, &sband->ht_cap,
IEEE80211_BAND_2GHZ);
priv->ieee_channels = channels;
priv->ieee_rates = rates;
for (i = 0; i < priv->channel_count; i++) {
ch = &priv->channel_info[i];
/* FIXME: might be removed if scan is OK */
if (!is_channel_valid(ch))
continue;
sband = &priv->bands[ch->band];
geo_ch = &sband->channels[sband->n_channels++];
geo_ch->center_freq =
ieee80211_channel_to_frequency(ch->channel, ch->band);
geo_ch->max_power = ch->max_power_avg;
geo_ch->max_antenna_gain = 0xff;
geo_ch->hw_value = ch->channel;
if (is_channel_valid(ch)) {
if (!(ch->flags & EEPROM_CHANNEL_IBSS))
geo_ch->flags |= IEEE80211_CHAN_NO_IBSS;
if (!(ch->flags & EEPROM_CHANNEL_ACTIVE))
geo_ch->flags |= IEEE80211_CHAN_PASSIVE_SCAN;
if (ch->flags & EEPROM_CHANNEL_RADAR)
geo_ch->flags |= IEEE80211_CHAN_RADAR;
geo_ch->flags |= ch->ht40_extension_channel;
if (ch->max_power_avg > max_tx_power)
max_tx_power = ch->max_power_avg;
} else {
geo_ch->flags |= IEEE80211_CHAN_DISABLED;
}
IWL_DEBUG_INFO(priv, "Channel %d Freq=%d[%sGHz] %s flag=0x%X\n",
ch->channel, geo_ch->center_freq,
is_channel_a_band(ch) ? "5.2" : "2.4",
geo_ch->flags & IEEE80211_CHAN_DISABLED ?
"restricted" : "valid",
geo_ch->flags);
}
priv->tx_power_device_lmt = max_tx_power;
priv->tx_power_user_lmt = max_tx_power;
priv->tx_power_next = max_tx_power;
if ((priv->bands[IEEE80211_BAND_5GHZ].n_channels == 0) &&
hw_params(priv).sku & EEPROM_SKU_CAP_BAND_52GHZ) {
IWL_INFO(priv, "Incorrectly detected BG card as ABG. "
"Please send your %s to maintainer.\n",
trans(priv)->hw_id_str);
hw_params(priv).sku &= ~EEPROM_SKU_CAP_BAND_52GHZ;
}
IWL_INFO(priv, "Tunable channels: %d 802.11bg, %d 802.11a channels\n",
priv->bands[IEEE80211_BAND_2GHZ].n_channels,
priv->bands[IEEE80211_BAND_5GHZ].n_channels);
set_bit(STATUS_GEO_CONFIGURED, &priv->status);
return 0;
}
/*
* iwl_free_geos - undo allocations in iwl_init_geos
*/
void iwl_free_geos(struct iwl_priv *priv)
{
kfree(priv->ieee_channels);
kfree(priv->ieee_rates);
clear_bit(STATUS_GEO_CONFIGURED, &priv->status);
}
static bool iwl_is_channel_extension(struct iwl_priv *priv,
enum ieee80211_band band,
u16 channel, u8 extension_chan_offset)
{
const struct iwl_channel_info *ch_info;
ch_info = iwl_get_channel_info(priv, band, channel);
if (!is_channel_valid(ch_info))
return false;
if (extension_chan_offset == IEEE80211_HT_PARAM_CHA_SEC_ABOVE)
return !(ch_info->ht40_extension_channel &
IEEE80211_CHAN_NO_HT40PLUS);
else if (extension_chan_offset == IEEE80211_HT_PARAM_CHA_SEC_BELOW)
return !(ch_info->ht40_extension_channel &
IEEE80211_CHAN_NO_HT40MINUS);
return false;
}
bool iwl_is_ht40_tx_allowed(struct iwl_priv *priv,
struct iwl_rxon_context *ctx,
struct ieee80211_sta_ht_cap *ht_cap)
{
if (!ctx->ht.enabled || !ctx->ht.is_40mhz)
return false;
/*
* We do not check for IEEE80211_HT_CAP_SUP_WIDTH_20_40
* the bit will not set if it is pure 40MHz case
*/
if (ht_cap && !ht_cap->ht_supported)
return false;
#ifdef CONFIG_IWLWIFI_DEBUGFS
if (priv->disable_ht40)
return false;
#endif
return iwl_is_channel_extension(priv, priv->band,
le16_to_cpu(ctx->staging.channel),
ctx->ht.extension_chan_offset);
}
static u16 iwl_adjust_beacon_interval(u16 beacon_val, u16 max_beacon_val)
{
u16 new_val;
u16 beacon_factor;
/*
* If mac80211 hasn't given us a beacon interval, program
* the default into the device (not checking this here
* would cause the adjustment below to return the maximum
* value, which may break PAN.)
*/
if (!beacon_val)
return DEFAULT_BEACON_INTERVAL;
/*
* If the beacon interval we obtained from the peer
* is too large, we'll have to wake up more often
* (and in IBSS case, we'll beacon too much)
*
* For example, if max_beacon_val is 4096, and the
* requested beacon interval is 7000, we'll have to
* use 3500 to be able to wake up on the beacons.
*
* This could badly influence beacon detection stats.
*/
beacon_factor = (beacon_val + max_beacon_val) / max_beacon_val;
new_val = beacon_val / beacon_factor;
if (!new_val)
new_val = max_beacon_val;
return new_val;
}
int iwl_send_rxon_timing(struct iwl_priv *priv, struct iwl_rxon_context *ctx)
{
u64 tsf;
s32 interval_tm, rem;
struct ieee80211_conf *conf = NULL;
u16 beacon_int;
struct ieee80211_vif *vif = ctx->vif;
conf = &priv->hw->conf;
lockdep_assert_held(&priv->mutex);
memset(&ctx->timing, 0, sizeof(struct iwl_rxon_time_cmd));
ctx->timing.timestamp = cpu_to_le64(priv->timestamp);
ctx->timing.listen_interval = cpu_to_le16(conf->listen_interval);
beacon_int = vif ? vif->bss_conf.beacon_int : 0;
/*
* TODO: For IBSS we need to get atim_window from mac80211,
* for now just always use 0
*/
ctx->timing.atim_window = 0;
if (ctx->ctxid == IWL_RXON_CTX_PAN &&
(!ctx->vif || ctx->vif->type != NL80211_IFTYPE_STATION) &&
iwl_is_associated(priv, IWL_RXON_CTX_BSS) &&
priv->contexts[IWL_RXON_CTX_BSS].vif &&
priv->contexts[IWL_RXON_CTX_BSS].vif->bss_conf.beacon_int) {
ctx->timing.beacon_interval =
priv->contexts[IWL_RXON_CTX_BSS].timing.beacon_interval;
beacon_int = le16_to_cpu(ctx->timing.beacon_interval);
} else if (ctx->ctxid == IWL_RXON_CTX_BSS &&
iwl_is_associated(priv, IWL_RXON_CTX_PAN) &&
priv->contexts[IWL_RXON_CTX_PAN].vif &&
priv->contexts[IWL_RXON_CTX_PAN].vif->bss_conf.beacon_int &&
(!iwl_is_associated_ctx(ctx) || !ctx->vif ||
!ctx->vif->bss_conf.beacon_int)) {
ctx->timing.beacon_interval =
priv->contexts[IWL_RXON_CTX_PAN].timing.beacon_interval;
beacon_int = le16_to_cpu(ctx->timing.beacon_interval);
} else {
beacon_int = iwl_adjust_beacon_interval(beacon_int,
IWL_MAX_UCODE_BEACON_INTERVAL * TIME_UNIT);
ctx->timing.beacon_interval = cpu_to_le16(beacon_int);
}
ctx->beacon_int = beacon_int;
tsf = priv->timestamp; /* tsf is modifed by do_div: copy it */
interval_tm = beacon_int * TIME_UNIT;
rem = do_div(tsf, interval_tm);
ctx->timing.beacon_init_val = cpu_to_le32(interval_tm - rem);
ctx->timing.dtim_period = vif ? (vif->bss_conf.dtim_period ?: 1) : 1;
IWL_DEBUG_ASSOC(priv,
"beacon interval %d beacon timer %d beacon tim %d\n",
le16_to_cpu(ctx->timing.beacon_interval),
le32_to_cpu(ctx->timing.beacon_init_val),
le16_to_cpu(ctx->timing.atim_window));
return iwl_dvm_send_cmd_pdu(priv, ctx->rxon_timing_cmd,
CMD_SYNC, sizeof(ctx->timing), &ctx->timing);
}
void iwl_set_rxon_hwcrypto(struct iwl_priv *priv, struct iwl_rxon_context *ctx,
int hw_decrypt)
{
struct iwl_rxon_cmd *rxon = &ctx->staging;
if (hw_decrypt)
rxon->filter_flags &= ~RXON_FILTER_DIS_DECRYPT_MSK;
else
rxon->filter_flags |= RXON_FILTER_DIS_DECRYPT_MSK;
}
/* validate RXON structure is valid */
int iwl_check_rxon_cmd(struct iwl_priv *priv, struct iwl_rxon_context *ctx)
{
struct iwl_rxon_cmd *rxon = &ctx->staging;
u32 errors = 0;
if (rxon->flags & RXON_FLG_BAND_24G_MSK) {
if (rxon->flags & RXON_FLG_TGJ_NARROW_BAND_MSK) {
IWL_WARN(priv, "check 2.4G: wrong narrow\n");
errors |= BIT(0);
}
if (rxon->flags & RXON_FLG_RADAR_DETECT_MSK) {
IWL_WARN(priv, "check 2.4G: wrong radar\n");
errors |= BIT(1);
}
} else {
if (!(rxon->flags & RXON_FLG_SHORT_SLOT_MSK)) {
IWL_WARN(priv, "check 5.2G: not short slot!\n");
errors |= BIT(2);
}
if (rxon->flags & RXON_FLG_CCK_MSK) {
IWL_WARN(priv, "check 5.2G: CCK!\n");
errors |= BIT(3);
}
}
if ((rxon->node_addr[0] | rxon->bssid_addr[0]) & 0x1) {
IWL_WARN(priv, "mac/bssid mcast!\n");
errors |= BIT(4);
}
/* make sure basic rates 6Mbps and 1Mbps are supported */
if ((rxon->ofdm_basic_rates & IWL_RATE_6M_MASK) == 0 &&
(rxon->cck_basic_rates & IWL_RATE_1M_MASK) == 0) {
IWL_WARN(priv, "neither 1 nor 6 are basic\n");
errors |= BIT(5);
}
if (le16_to_cpu(rxon->assoc_id) > 2007) {
IWL_WARN(priv, "aid > 2007\n");
errors |= BIT(6);
}
if ((rxon->flags & (RXON_FLG_CCK_MSK | RXON_FLG_SHORT_SLOT_MSK))
== (RXON_FLG_CCK_MSK | RXON_FLG_SHORT_SLOT_MSK)) {
IWL_WARN(priv, "CCK and short slot\n");
errors |= BIT(7);
}
if ((rxon->flags & (RXON_FLG_CCK_MSK | RXON_FLG_AUTO_DETECT_MSK))
== (RXON_FLG_CCK_MSK | RXON_FLG_AUTO_DETECT_MSK)) {
IWL_WARN(priv, "CCK and auto detect");
errors |= BIT(8);
}
if ((rxon->flags & (RXON_FLG_AUTO_DETECT_MSK |
RXON_FLG_TGG_PROTECT_MSK)) ==
RXON_FLG_TGG_PROTECT_MSK) {
IWL_WARN(priv, "TGg but no auto-detect\n");
errors |= BIT(9);
}
if (rxon->channel == 0) {
IWL_WARN(priv, "zero channel is invalid\n");
errors |= BIT(10);
}
WARN(errors, "Invalid RXON (%#x), channel %d",
errors, le16_to_cpu(rxon->channel));
return errors ? -EINVAL : 0;
}
/**
* iwl_full_rxon_required - check if full RXON (vs RXON_ASSOC) cmd is needed
* @priv: staging_rxon is compared to active_rxon
*
* If the RXON structure is changing enough to require a new tune,
* or is clearing the RXON_FILTER_ASSOC_MSK, then return 1 to indicate that
* a new tune (full RXON command, rather than RXON_ASSOC cmd) is required.
*/
int iwl_full_rxon_required(struct iwl_priv *priv,
struct iwl_rxon_context *ctx)
{
const struct iwl_rxon_cmd *staging = &ctx->staging;
const struct iwl_rxon_cmd *active = &ctx->active;
#define CHK(cond) \
if ((cond)) { \
IWL_DEBUG_INFO(priv, "need full RXON - " #cond "\n"); \
return 1; \
}
#define CHK_NEQ(c1, c2) \
if ((c1) != (c2)) { \
IWL_DEBUG_INFO(priv, "need full RXON - " \
#c1 " != " #c2 " - %d != %d\n", \
(c1), (c2)); \
return 1; \
}
/* These items are only settable from the full RXON command */
CHK(!iwl_is_associated_ctx(ctx));
CHK(compare_ether_addr(staging->bssid_addr, active->bssid_addr));
CHK(compare_ether_addr(staging->node_addr, active->node_addr));
CHK(compare_ether_addr(staging->wlap_bssid_addr,
active->wlap_bssid_addr));
CHK_NEQ(staging->dev_type, active->dev_type);
CHK_NEQ(staging->channel, active->channel);
CHK_NEQ(staging->air_propagation, active->air_propagation);
CHK_NEQ(staging->ofdm_ht_single_stream_basic_rates,
active->ofdm_ht_single_stream_basic_rates);
CHK_NEQ(staging->ofdm_ht_dual_stream_basic_rates,
active->ofdm_ht_dual_stream_basic_rates);
CHK_NEQ(staging->ofdm_ht_triple_stream_basic_rates,
active->ofdm_ht_triple_stream_basic_rates);
CHK_NEQ(staging->assoc_id, active->assoc_id);
/* flags, filter_flags, ofdm_basic_rates, and cck_basic_rates can
* be updated with the RXON_ASSOC command -- however only some
* flag transitions are allowed using RXON_ASSOC */
/* Check if we are not switching bands */
CHK_NEQ(staging->flags & RXON_FLG_BAND_24G_MSK,
active->flags & RXON_FLG_BAND_24G_MSK);
/* Check if we are switching association toggle */
CHK_NEQ(staging->filter_flags & RXON_FILTER_ASSOC_MSK,
active->filter_flags & RXON_FILTER_ASSOC_MSK);
#undef CHK
#undef CHK_NEQ
return 0;
}
static void _iwl_set_rxon_ht(struct iwl_priv *priv,
struct iwl_ht_config *ht_conf,
struct iwl_rxon_context *ctx)
{
struct iwl_rxon_cmd *rxon = &ctx->staging;
if (!ctx->ht.enabled) {
rxon->flags &= ~(RXON_FLG_CHANNEL_MODE_MSK |
RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK |
RXON_FLG_HT40_PROT_MSK |
RXON_FLG_HT_PROT_MSK);
return;
}
/* FIXME: if the definition of ht.protection changed, the "translation"
* will be needed for rxon->flags
*/
rxon->flags |= cpu_to_le32(ctx->ht.protection << RXON_FLG_HT_OPERATING_MODE_POS);
/* Set up channel bandwidth:
* 20 MHz only, 20/40 mixed or pure 40 if ht40 ok */
/* clear the HT channel mode before set the mode */
rxon->flags &= ~(RXON_FLG_CHANNEL_MODE_MSK |
RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK);
if (iwl_is_ht40_tx_allowed(priv, ctx, NULL)) {
/* pure ht40 */
if (ctx->ht.protection == IEEE80211_HT_OP_MODE_PROTECTION_20MHZ) {
rxon->flags |= RXON_FLG_CHANNEL_MODE_PURE_40;
/* Note: control channel is opposite of extension channel */
switch (ctx->ht.extension_chan_offset) {
case IEEE80211_HT_PARAM_CHA_SEC_ABOVE:
rxon->flags &= ~RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK;
break;
case IEEE80211_HT_PARAM_CHA_SEC_BELOW:
rxon->flags |= RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK;
break;
}
} else {
/* Note: control channel is opposite of extension channel */
switch (ctx->ht.extension_chan_offset) {
case IEEE80211_HT_PARAM_CHA_SEC_ABOVE:
rxon->flags &= ~(RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK);
rxon->flags |= RXON_FLG_CHANNEL_MODE_MIXED;
break;
case IEEE80211_HT_PARAM_CHA_SEC_BELOW:
rxon->flags |= RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK;
rxon->flags |= RXON_FLG_CHANNEL_MODE_MIXED;
break;
case IEEE80211_HT_PARAM_CHA_SEC_NONE:
default:
/* channel location only valid if in Mixed mode */
IWL_ERR(priv, "invalid extension channel offset\n");
break;
}
}
} else {
rxon->flags |= RXON_FLG_CHANNEL_MODE_LEGACY;
}
iwlagn_set_rxon_chain(priv, ctx);
IWL_DEBUG_ASSOC(priv, "rxon flags 0x%X operation mode :0x%X "
"extension channel offset 0x%x\n",
le32_to_cpu(rxon->flags), ctx->ht.protection,
ctx->ht.extension_chan_offset);
}
void iwl_set_rxon_ht(struct iwl_priv *priv, struct iwl_ht_config *ht_conf)
{
struct iwl_rxon_context *ctx;
for_each_context(priv, ctx)
_iwl_set_rxon_ht(priv, ht_conf, ctx);
}
/* Return valid, unused, channel for a passive scan to reset the RF */
u8 iwl_get_single_channel_number(struct iwl_priv *priv,
enum ieee80211_band band)
{
const struct iwl_channel_info *ch_info;
int i;
u8 channel = 0;
u8 min, max;
struct iwl_rxon_context *ctx;
if (band == IEEE80211_BAND_5GHZ) {
min = 14;
max = priv->channel_count;
} else {
min = 0;
max = 14;
}
for (i = min; i < max; i++) {
bool busy = false;
for_each_context(priv, ctx) {
busy = priv->channel_info[i].channel ==
le16_to_cpu(ctx->staging.channel);
if (busy)
break;
}
if (busy)
continue;
channel = priv->channel_info[i].channel;
ch_info = iwl_get_channel_info(priv, band, channel);
if (is_channel_valid(ch_info))
break;
}
return channel;
}
/**
* iwl_set_rxon_channel - Set the band and channel values in staging RXON
* @ch: requested channel as a pointer to struct ieee80211_channel
* NOTE: Does not commit to the hardware; it sets appropriate bit fields
* in the staging RXON flag structure based on the ch->band
*/
void iwl_set_rxon_channel(struct iwl_priv *priv, struct ieee80211_channel *ch,
struct iwl_rxon_context *ctx)
{
enum ieee80211_band band = ch->band;
u16 channel = ch->hw_value;
if ((le16_to_cpu(ctx->staging.channel) == channel) &&
(priv->band == band))
return;
ctx->staging.channel = cpu_to_le16(channel);
if (band == IEEE80211_BAND_5GHZ)
ctx->staging.flags &= ~RXON_FLG_BAND_24G_MSK;
else
ctx->staging.flags |= RXON_FLG_BAND_24G_MSK;
priv->band = band;
IWL_DEBUG_INFO(priv, "Staging channel set to %d [%d]\n", channel, band);
}
void iwl_set_flags_for_band(struct iwl_priv *priv,
struct iwl_rxon_context *ctx,
enum ieee80211_band band,
struct ieee80211_vif *vif)
{
if (band == IEEE80211_BAND_5GHZ) {
ctx->staging.flags &=
~(RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK
| RXON_FLG_CCK_MSK);
ctx->staging.flags |= RXON_FLG_SHORT_SLOT_MSK;
} else {
/* Copied from iwl_post_associate() */
if (vif && vif->bss_conf.use_short_slot)
ctx->staging.flags |= RXON_FLG_SHORT_SLOT_MSK;
else
ctx->staging.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
ctx->staging.flags |= RXON_FLG_BAND_24G_MSK;
ctx->staging.flags |= RXON_FLG_AUTO_DETECT_MSK;
ctx->staging.flags &= ~RXON_FLG_CCK_MSK;
}
}
/*
* initialize rxon structure with default values from eeprom
*/
void iwl_connection_init_rx_config(struct iwl_priv *priv,
struct iwl_rxon_context *ctx)
{
const struct iwl_channel_info *ch_info;
memset(&ctx->staging, 0, sizeof(ctx->staging));
if (!ctx->vif) {
ctx->staging.dev_type = ctx->unused_devtype;
} else switch (ctx->vif->type) {
case NL80211_IFTYPE_AP:
ctx->staging.dev_type = ctx->ap_devtype;
break;
case NL80211_IFTYPE_STATION:
ctx->staging.dev_type = ctx->station_devtype;
ctx->staging.filter_flags = RXON_FILTER_ACCEPT_GRP_MSK;
break;
case NL80211_IFTYPE_ADHOC:
ctx->staging.dev_type = ctx->ibss_devtype;
ctx->staging.flags = RXON_FLG_SHORT_PREAMBLE_MSK;
ctx->staging.filter_flags = RXON_FILTER_BCON_AWARE_MSK |
RXON_FILTER_ACCEPT_GRP_MSK;
break;
default:
IWL_ERR(priv, "Unsupported interface type %d\n",
ctx->vif->type);
break;
}
#if 0
/* TODO: Figure out when short_preamble would be set and cache from
* that */
if (!hw_to_local(priv->hw)->short_preamble)
ctx->staging.flags &= ~RXON_FLG_SHORT_PREAMBLE_MSK;
else
ctx->staging.flags |= RXON_FLG_SHORT_PREAMBLE_MSK;
#endif
ch_info = iwl_get_channel_info(priv, priv->band,
le16_to_cpu(ctx->active.channel));
if (!ch_info)
ch_info = &priv->channel_info[0];
ctx->staging.channel = cpu_to_le16(ch_info->channel);
priv->band = ch_info->band;
iwl_set_flags_for_band(priv, ctx, priv->band, ctx->vif);
ctx->staging.ofdm_basic_rates =
(IWL_OFDM_RATES_MASK >> IWL_FIRST_OFDM_RATE) & 0xFF;
ctx->staging.cck_basic_rates =
(IWL_CCK_RATES_MASK >> IWL_FIRST_CCK_RATE) & 0xF;
/* clear both MIX and PURE40 mode flag */
ctx->staging.flags &= ~(RXON_FLG_CHANNEL_MODE_MIXED |
RXON_FLG_CHANNEL_MODE_PURE_40);
if (ctx->vif)
memcpy(ctx->staging.node_addr, ctx->vif->addr, ETH_ALEN);
ctx->staging.ofdm_ht_single_stream_basic_rates = 0xff;
ctx->staging.ofdm_ht_dual_stream_basic_rates = 0xff;
ctx->staging.ofdm_ht_triple_stream_basic_rates = 0xff;
}
void iwl_set_rate(struct iwl_priv *priv)
{
const struct ieee80211_supported_band *hw = NULL;
struct ieee80211_rate *rate;
struct iwl_rxon_context *ctx;
int i;
hw = iwl_get_hw_mode(priv, priv->band);
if (!hw) {
IWL_ERR(priv, "Failed to set rate: unable to get hw mode\n");
return;
}
priv->active_rate = 0;
for (i = 0; i < hw->n_bitrates; i++) {
rate = &(hw->bitrates[i]);
if (rate->hw_value < IWL_RATE_COUNT_LEGACY)
priv->active_rate |= (1 << rate->hw_value);
}
IWL_DEBUG_RATE(priv, "Set active_rate = %0x\n", priv->active_rate);
for_each_context(priv, ctx) {
ctx->staging.cck_basic_rates =
(IWL_CCK_BASIC_RATES_MASK >> IWL_FIRST_CCK_RATE) & 0xF;
ctx->staging.ofdm_basic_rates =
(IWL_OFDM_BASIC_RATES_MASK >> IWL_FIRST_OFDM_RATE) & 0xFF;
}
}
void iwl_chswitch_done(struct iwl_priv *priv, bool is_success)
{
/*
* MULTI-FIXME
* See iwlagn_mac_channel_switch.
*/
struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
if (test_bit(STATUS_EXIT_PENDING, &priv->status))
return;
if (test_and_clear_bit(STATUS_CHANNEL_SWITCH_PENDING, &priv->status))
ieee80211_chswitch_done(ctx->vif, is_success);
}
#ifdef CONFIG_IWLWIFI_DEBUG
void iwl_print_rx_config_cmd(struct iwl_priv *priv,
enum iwl_rxon_context_id ctxid)
{
struct iwl_rxon_context *ctx = &priv->contexts[ctxid];
struct iwl_rxon_cmd *rxon = &ctx->staging;
IWL_DEBUG_RADIO(priv, "RX CONFIG:\n");
iwl_print_hex_dump(priv, IWL_DL_RADIO, (u8 *) rxon, sizeof(*rxon));
IWL_DEBUG_RADIO(priv, "u16 channel: 0x%x\n", le16_to_cpu(rxon->channel));
IWL_DEBUG_RADIO(priv, "u32 flags: 0x%08X\n", le32_to_cpu(rxon->flags));
IWL_DEBUG_RADIO(priv, "u32 filter_flags: 0x%08x\n",
le32_to_cpu(rxon->filter_flags));
IWL_DEBUG_RADIO(priv, "u8 dev_type: 0x%x\n", rxon->dev_type);
IWL_DEBUG_RADIO(priv, "u8 ofdm_basic_rates: 0x%02x\n",
rxon->ofdm_basic_rates);
IWL_DEBUG_RADIO(priv, "u8 cck_basic_rates: 0x%02x\n", rxon->cck_basic_rates);
IWL_DEBUG_RADIO(priv, "u8[6] node_addr: %pM\n", rxon->node_addr);
IWL_DEBUG_RADIO(priv, "u8[6] bssid_addr: %pM\n", rxon->bssid_addr);
IWL_DEBUG_RADIO(priv, "u16 assoc_id: 0x%x\n", le16_to_cpu(rxon->assoc_id));
}
#endif
static void iwlagn_fw_error(struct iwl_priv *priv, bool ondemand)
{
unsigned int reload_msec;
unsigned long reload_jiffies;
#ifdef CONFIG_IWLWIFI_DEBUG
if (iwl_have_debug_level(IWL_DL_FW_ERRORS))
iwl_print_rx_config_cmd(priv, IWL_RXON_CTX_BSS);
#endif
/* uCode is no longer loaded. */
priv->ucode_loaded = false;
/* Set the FW error flag -- cleared on iwl_down */
set_bit(STATUS_FW_ERROR, &priv->shrd->status);
/* Cancel currently queued command. */
clear_bit(STATUS_HCMD_ACTIVE, &priv->shrd->status);
iwl_abort_notification_waits(&priv->notif_wait);
/* Keep the restart process from trying to send host
* commands by clearing the ready bit */
clear_bit(STATUS_READY, &priv->status);
wake_up(&trans(priv)->wait_command_queue);
if (!ondemand) {
/*
* If firmware keep reloading, then it indicate something
* serious wrong and firmware having problem to recover
* from it. Instead of keep trying which will fill the syslog
* and hang the system, let's just stop it
*/
reload_jiffies = jiffies;
reload_msec = jiffies_to_msecs((long) reload_jiffies -
(long) priv->reload_jiffies);
priv->reload_jiffies = reload_jiffies;
if (reload_msec <= IWL_MIN_RELOAD_DURATION) {
priv->reload_count++;
if (priv->reload_count >= IWL_MAX_CONTINUE_RELOAD_CNT) {
IWL_ERR(priv, "BUG_ON, Stop restarting\n");
return;
}
} else
priv->reload_count = 0;
}
if (!test_bit(STATUS_EXIT_PENDING, &priv->status)) {
if (iwlagn_mod_params.restart_fw) {
IWL_DEBUG_FW_ERRORS(priv,
"Restarting adapter due to uCode error.\n");
queue_work(priv->workqueue, &priv->restart);
} else
IWL_DEBUG_FW_ERRORS(priv,
"Detected FW error, but not restarting\n");
}
}
int iwl_set_tx_power(struct iwl_priv *priv, s8 tx_power, bool force)
{
int ret;
s8 prev_tx_power;
bool defer;
struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
lockdep_assert_held(&priv->mutex);
if (priv->tx_power_user_lmt == tx_power && !force)
return 0;
if (tx_power < IWLAGN_TX_POWER_TARGET_POWER_MIN) {
IWL_WARN(priv,
"Requested user TXPOWER %d below lower limit %d.\n",
tx_power,
IWLAGN_TX_POWER_TARGET_POWER_MIN);
return -EINVAL;
}
if (tx_power > priv->tx_power_device_lmt) {
IWL_WARN(priv,
"Requested user TXPOWER %d above upper limit %d.\n",
tx_power, priv->tx_power_device_lmt);
return -EINVAL;
}
if (!iwl_is_ready_rf(priv))
return -EIO;
/* scan complete and commit_rxon use tx_power_next value,
* it always need to be updated for newest request */
priv->tx_power_next = tx_power;
/* do not set tx power when scanning or channel changing */
defer = test_bit(STATUS_SCANNING, &priv->status) ||
memcmp(&ctx->active, &ctx->staging, sizeof(ctx->staging));
if (defer && !force) {
IWL_DEBUG_INFO(priv, "Deferring tx power set\n");
return 0;
}
prev_tx_power = priv->tx_power_user_lmt;
priv->tx_power_user_lmt = tx_power;
ret = iwlagn_send_tx_power(priv);
/* if fail to set tx_power, restore the orig. tx power */
if (ret) {
priv->tx_power_user_lmt = prev_tx_power;
priv->tx_power_next = prev_tx_power;
}
return ret;
}
void iwl_send_bt_config(struct iwl_priv *priv)
{
struct iwl_bt_cmd bt_cmd = {
.lead_time = BT_LEAD_TIME_DEF,
.max_kill = BT_MAX_KILL_DEF,
.kill_ack_mask = 0,
.kill_cts_mask = 0,
};
if (!iwlagn_mod_params.bt_coex_active)
bt_cmd.flags = BT_COEX_DISABLE;
else
bt_cmd.flags = BT_COEX_ENABLE;
priv->bt_enable_flag = bt_cmd.flags;
IWL_DEBUG_INFO(priv, "BT coex %s\n",
(bt_cmd.flags == BT_COEX_DISABLE) ? "disable" : "active");
if (iwl_dvm_send_cmd_pdu(priv, REPLY_BT_CONFIG,
CMD_SYNC, sizeof(struct iwl_bt_cmd), &bt_cmd))
IWL_ERR(priv, "failed to send BT Coex Config\n");
}
int iwl_send_statistics_request(struct iwl_priv *priv, u8 flags, bool clear)
{
struct iwl_statistics_cmd statistics_cmd = {
.configuration_flags =
clear ? IWL_STATS_CONF_CLEAR_STATS : 0,
};
if (flags & CMD_ASYNC)
return iwl_dvm_send_cmd_pdu(priv, REPLY_STATISTICS_CMD,
CMD_ASYNC,
sizeof(struct iwl_statistics_cmd),
&statistics_cmd);
else
return iwl_dvm_send_cmd_pdu(priv, REPLY_STATISTICS_CMD,
CMD_SYNC,
sizeof(struct iwl_statistics_cmd),
&statistics_cmd);
}
#ifdef CONFIG_IWLWIFI_DEBUGFS
#define IWL_TRAFFIC_DUMP_SIZE (IWL_TRAFFIC_ENTRY_SIZE * IWL_TRAFFIC_ENTRIES)
void iwl_reset_traffic_log(struct iwl_priv *priv)
{
priv->tx_traffic_idx = 0;
priv->rx_traffic_idx = 0;
if (priv->tx_traffic)
memset(priv->tx_traffic, 0, IWL_TRAFFIC_DUMP_SIZE);
if (priv->rx_traffic)
memset(priv->rx_traffic, 0, IWL_TRAFFIC_DUMP_SIZE);
}
int iwl_alloc_traffic_mem(struct iwl_priv *priv)
{
u32 traffic_size = IWL_TRAFFIC_DUMP_SIZE;
if (iwl_have_debug_level(IWL_DL_TX)) {
if (!priv->tx_traffic) {
priv->tx_traffic =
kzalloc(traffic_size, GFP_KERNEL);
if (!priv->tx_traffic)
return -ENOMEM;
}
}
if (iwl_have_debug_level(IWL_DL_RX)) {
if (!priv->rx_traffic) {
priv->rx_traffic =
kzalloc(traffic_size, GFP_KERNEL);
if (!priv->rx_traffic)
return -ENOMEM;
}
}
iwl_reset_traffic_log(priv);
return 0;
}
void iwl_free_traffic_mem(struct iwl_priv *priv)
{
kfree(priv->tx_traffic);
priv->tx_traffic = NULL;
kfree(priv->rx_traffic);
priv->rx_traffic = NULL;
}
void iwl_dbg_log_tx_data_frame(struct iwl_priv *priv,
u16 length, struct ieee80211_hdr *header)
{
__le16 fc;
u16 len;
if (likely(!iwl_have_debug_level(IWL_DL_TX)))
return;
if (!priv->tx_traffic)
return;
fc = header->frame_control;
if (ieee80211_is_data(fc)) {
len = (length > IWL_TRAFFIC_ENTRY_SIZE)
? IWL_TRAFFIC_ENTRY_SIZE : length;
memcpy((priv->tx_traffic +
(priv->tx_traffic_idx * IWL_TRAFFIC_ENTRY_SIZE)),
header, len);
priv->tx_traffic_idx =
(priv->tx_traffic_idx + 1) % IWL_TRAFFIC_ENTRIES;
}
}
void iwl_dbg_log_rx_data_frame(struct iwl_priv *priv,
u16 length, struct ieee80211_hdr *header)
{
__le16 fc;
u16 len;
if (likely(!iwl_have_debug_level(IWL_DL_RX)))
return;
if (!priv->rx_traffic)
return;
fc = header->frame_control;
if (ieee80211_is_data(fc)) {
len = (length > IWL_TRAFFIC_ENTRY_SIZE)
? IWL_TRAFFIC_ENTRY_SIZE : length;
memcpy((priv->rx_traffic +
(priv->rx_traffic_idx * IWL_TRAFFIC_ENTRY_SIZE)),
header, len);
priv->rx_traffic_idx =
(priv->rx_traffic_idx + 1) % IWL_TRAFFIC_ENTRIES;
}
}
const char *get_mgmt_string(int cmd)
{
switch (cmd) {
IWL_CMD(MANAGEMENT_ASSOC_REQ);
IWL_CMD(MANAGEMENT_ASSOC_RESP);
IWL_CMD(MANAGEMENT_REASSOC_REQ);
IWL_CMD(MANAGEMENT_REASSOC_RESP);
IWL_CMD(MANAGEMENT_PROBE_REQ);
IWL_CMD(MANAGEMENT_PROBE_RESP);
IWL_CMD(MANAGEMENT_BEACON);
IWL_CMD(MANAGEMENT_ATIM);
IWL_CMD(MANAGEMENT_DISASSOC);
IWL_CMD(MANAGEMENT_AUTH);
IWL_CMD(MANAGEMENT_DEAUTH);
IWL_CMD(MANAGEMENT_ACTION);
default:
return "UNKNOWN";
}
}
const char *get_ctrl_string(int cmd)
{
switch (cmd) {
IWL_CMD(CONTROL_BACK_REQ);
IWL_CMD(CONTROL_BACK);
IWL_CMD(CONTROL_PSPOLL);
IWL_CMD(CONTROL_RTS);
IWL_CMD(CONTROL_CTS);
IWL_CMD(CONTROL_ACK);
IWL_CMD(CONTROL_CFEND);
IWL_CMD(CONTROL_CFENDACK);
default:
return "UNKNOWN";
}
}
void iwl_clear_traffic_stats(struct iwl_priv *priv)
{
memset(&priv->tx_stats, 0, sizeof(struct traffic_stats));
memset(&priv->rx_stats, 0, sizeof(struct traffic_stats));
}
/*
* if CONFIG_IWLWIFI_DEBUGFS defined, iwl_update_stats function will
* record all the MGMT, CTRL and DATA pkt for both TX and Rx pass.
* Use debugFs to display the rx/rx_statistics
* if CONFIG_IWLWIFI_DEBUGFS not being defined, then no MGMT and CTRL
* information will be recorded, but DATA pkt still will be recorded
* for the reason of iwl_led.c need to control the led blinking based on
* number of tx and rx data.
*
*/
void iwl_update_stats(struct iwl_priv *priv, bool is_tx, __le16 fc, u16 len)
{
struct traffic_stats *stats;
if (is_tx)
stats = &priv->tx_stats;
else
stats = &priv->rx_stats;
if (ieee80211_is_mgmt(fc)) {
switch (fc & cpu_to_le16(IEEE80211_FCTL_STYPE)) {
case cpu_to_le16(IEEE80211_STYPE_ASSOC_REQ):
stats->mgmt[MANAGEMENT_ASSOC_REQ]++;
break;
case cpu_to_le16(IEEE80211_STYPE_ASSOC_RESP):
stats->mgmt[MANAGEMENT_ASSOC_RESP]++;
break;
case cpu_to_le16(IEEE80211_STYPE_REASSOC_REQ):
stats->mgmt[MANAGEMENT_REASSOC_REQ]++;
break;
case cpu_to_le16(IEEE80211_STYPE_REASSOC_RESP):
stats->mgmt[MANAGEMENT_REASSOC_RESP]++;
break;
case cpu_to_le16(IEEE80211_STYPE_PROBE_REQ):
stats->mgmt[MANAGEMENT_PROBE_REQ]++;
break;
case cpu_to_le16(IEEE80211_STYPE_PROBE_RESP):
stats->mgmt[MANAGEMENT_PROBE_RESP]++;
break;
case cpu_to_le16(IEEE80211_STYPE_BEACON):
stats->mgmt[MANAGEMENT_BEACON]++;
break;
case cpu_to_le16(IEEE80211_STYPE_ATIM):
stats->mgmt[MANAGEMENT_ATIM]++;
break;
case cpu_to_le16(IEEE80211_STYPE_DISASSOC):
stats->mgmt[MANAGEMENT_DISASSOC]++;
break;
case cpu_to_le16(IEEE80211_STYPE_AUTH):
stats->mgmt[MANAGEMENT_AUTH]++;
break;
case cpu_to_le16(IEEE80211_STYPE_DEAUTH):
stats->mgmt[MANAGEMENT_DEAUTH]++;
break;
case cpu_to_le16(IEEE80211_STYPE_ACTION):
stats->mgmt[MANAGEMENT_ACTION]++;
break;
}
} else if (ieee80211_is_ctl(fc)) {
switch (fc & cpu_to_le16(IEEE80211_FCTL_STYPE)) {
case cpu_to_le16(IEEE80211_STYPE_BACK_REQ):
stats->ctrl[CONTROL_BACK_REQ]++;
break;
case cpu_to_le16(IEEE80211_STYPE_BACK):
stats->ctrl[CONTROL_BACK]++;
break;
case cpu_to_le16(IEEE80211_STYPE_PSPOLL):
stats->ctrl[CONTROL_PSPOLL]++;
break;
case cpu_to_le16(IEEE80211_STYPE_RTS):
stats->ctrl[CONTROL_RTS]++;
break;
case cpu_to_le16(IEEE80211_STYPE_CTS):
stats->ctrl[CONTROL_CTS]++;
break;
case cpu_to_le16(IEEE80211_STYPE_ACK):
stats->ctrl[CONTROL_ACK]++;
break;
case cpu_to_le16(IEEE80211_STYPE_CFEND):
stats->ctrl[CONTROL_CFEND]++;
break;
case cpu_to_le16(IEEE80211_STYPE_CFENDACK):
stats->ctrl[CONTROL_CFENDACK]++;
break;
}
} else {
/* data */
stats->data_cnt++;
stats->data_bytes += len;
}
}
#endif
static void iwl_force_rf_reset(struct iwl_priv *priv)
{
if (test_bit(STATUS_EXIT_PENDING, &priv->status))
return;
if (!iwl_is_any_associated(priv)) {
IWL_DEBUG_SCAN(priv, "force reset rejected: not associated\n");
return;
}
/*
* There is no easy and better way to force reset the radio,
* the only known method is switching channel which will force to
* reset and tune the radio.
* Use internal short scan (single channel) operation to should
* achieve this objective.
* Driver should reset the radio when number of consecutive missed
* beacon, or any other uCode error condition detected.
*/
IWL_DEBUG_INFO(priv, "perform radio reset.\n");
iwl_internal_short_hw_scan(priv);
}
int iwl_force_reset(struct iwl_priv *priv, int mode, bool external)
{
struct iwl_force_reset *force_reset;
if (test_bit(STATUS_EXIT_PENDING, &priv->status))
return -EINVAL;
if (mode >= IWL_MAX_FORCE_RESET) {
IWL_DEBUG_INFO(priv, "invalid reset request.\n");
return -EINVAL;
}
force_reset = &priv->force_reset[mode];
force_reset->reset_request_count++;
if (!external) {
if (force_reset->last_force_reset_jiffies &&
time_after(force_reset->last_force_reset_jiffies +
force_reset->reset_duration, jiffies)) {
IWL_DEBUG_INFO(priv, "force reset rejected\n");
force_reset->reset_reject_count++;
return -EAGAIN;
}
}
force_reset->reset_success_count++;
force_reset->last_force_reset_jiffies = jiffies;
IWL_DEBUG_INFO(priv, "perform force reset (%d)\n", mode);
switch (mode) {
case IWL_RF_RESET:
iwl_force_rf_reset(priv);
break;
case IWL_FW_RESET:
/*
* if the request is from external(ex: debugfs),
* then always perform the request in regardless the module
* parameter setting
* if the request is from internal (uCode error or driver
* detect failure), then fw_restart module parameter
* need to be check before performing firmware reload
*/
if (!external && !iwlagn_mod_params.restart_fw) {
IWL_DEBUG_INFO(priv, "Cancel firmware reload based on "
"module parameter setting\n");
break;
}
IWL_ERR(priv, "On demand firmware reload\n");
iwlagn_fw_error(priv, true);
break;
}
return 0;
}
int iwl_cmd_echo_test(struct iwl_priv *priv)
{
int ret;
struct iwl_host_cmd cmd = {
.id = REPLY_ECHO,
.len = { 0 },
.flags = CMD_SYNC,
};
ret = iwl_dvm_send_cmd(priv, &cmd);
if (ret)
IWL_ERR(priv, "echo testing fail: 0X%x\n", ret);
else
IWL_DEBUG_INFO(priv, "echo testing pass\n");
return ret;
}
static inline int iwl_check_stuck_queue(struct iwl_priv *priv, int txq)
{
if (iwl_trans_check_stuck_queue(trans(priv), txq)) {
int ret;
ret = iwl_force_reset(priv, IWL_FW_RESET, false);
return (ret == -EAGAIN) ? 0 : 1;
}
return 0;
}
/*
* Making watchdog tick be a quarter of timeout assure we will
* discover the queue hung between timeout and 1.25*timeout
*/
#define IWL_WD_TICK(timeout) ((timeout) / 4)
/*
* Watchdog timer callback, we check each tx queue for stuck, if if hung
* we reset the firmware. If everything is fine just rearm the timer.
*/
void iwl_bg_watchdog(unsigned long data)
{
struct iwl_priv *priv = (struct iwl_priv *)data;
int cnt;
unsigned long timeout;
if (test_bit(STATUS_EXIT_PENDING, &priv->status))
return;
if (iwl_is_rfkill(priv))
return;
timeout = hw_params(priv).wd_timeout;
if (timeout == 0)
return;
/* monitor and check for stuck queues */
for (cnt = 0; cnt < cfg(priv)->base_params->num_of_queues; cnt++)
if (iwl_check_stuck_queue(priv, cnt))
return;
mod_timer(&priv->watchdog, jiffies +
msecs_to_jiffies(IWL_WD_TICK(timeout)));
}
void iwl_setup_watchdog(struct iwl_priv *priv)
{
unsigned int timeout = hw_params(priv).wd_timeout;
if (!iwlagn_mod_params.wd_disable) {
/* use system default */
if (timeout && !cfg(priv)->base_params->wd_disable)
mod_timer(&priv->watchdog,
jiffies +
msecs_to_jiffies(IWL_WD_TICK(timeout)));
else
del_timer(&priv->watchdog);
} else {
/* module parameter overwrite default configuration */
if (timeout && iwlagn_mod_params.wd_disable == 2)
mod_timer(&priv->watchdog,
jiffies +
msecs_to_jiffies(IWL_WD_TICK(timeout)));
else
del_timer(&priv->watchdog);
}
}
/**
* iwl_beacon_time_mask_low - mask of lower 32 bit of beacon time
* @priv -- pointer to iwl_priv data structure
* @tsf_bits -- number of bits need to shift for masking)
*/
static inline u32 iwl_beacon_time_mask_low(struct iwl_priv *priv,
u16 tsf_bits)
{
return (1 << tsf_bits) - 1;
}
/**
* iwl_beacon_time_mask_high - mask of higher 32 bit of beacon time
* @priv -- pointer to iwl_priv data structure
* @tsf_bits -- number of bits need to shift for masking)
*/
static inline u32 iwl_beacon_time_mask_high(struct iwl_priv *priv,
u16 tsf_bits)
{
return ((1 << (32 - tsf_bits)) - 1) << tsf_bits;
}
/*
* extended beacon time format
* time in usec will be changed into a 32-bit value in extended:internal format
* the extended part is the beacon counts
* the internal part is the time in usec within one beacon interval
*/
u32 iwl_usecs_to_beacons(struct iwl_priv *priv, u32 usec, u32 beacon_interval)
{
u32 quot;
u32 rem;
u32 interval = beacon_interval * TIME_UNIT;
if (!interval || !usec)
return 0;
quot = (usec / interval) &
(iwl_beacon_time_mask_high(priv, IWLAGN_EXT_BEACON_TIME_POS) >>
IWLAGN_EXT_BEACON_TIME_POS);
rem = (usec % interval) & iwl_beacon_time_mask_low(priv,
IWLAGN_EXT_BEACON_TIME_POS);
return (quot << IWLAGN_EXT_BEACON_TIME_POS) + rem;
}
/* base is usually what we get from ucode with each received frame,
* the same as HW timer counter counting down
*/
__le32 iwl_add_beacon_time(struct iwl_priv *priv, u32 base,
u32 addon, u32 beacon_interval)
{
u32 base_low = base & iwl_beacon_time_mask_low(priv,
IWLAGN_EXT_BEACON_TIME_POS);
u32 addon_low = addon & iwl_beacon_time_mask_low(priv,
IWLAGN_EXT_BEACON_TIME_POS);
u32 interval = beacon_interval * TIME_UNIT;
u32 res = (base & iwl_beacon_time_mask_high(priv,
IWLAGN_EXT_BEACON_TIME_POS)) +
(addon & iwl_beacon_time_mask_high(priv,
IWLAGN_EXT_BEACON_TIME_POS));
if (base_low > addon_low)
res += base_low - addon_low;
else if (base_low < addon_low) {
res += interval + base_low - addon_low;
res += (1 << IWLAGN_EXT_BEACON_TIME_POS);
} else
res += (1 << IWLAGN_EXT_BEACON_TIME_POS);
return cpu_to_le32(res);
}
void iwl_nic_error(struct iwl_op_mode *op_mode)
{
struct iwl_priv *priv = IWL_OP_MODE_GET_DVM(op_mode);
iwlagn_fw_error(priv, false);
}
void iwl_set_hw_rfkill_state(struct iwl_op_mode *op_mode, bool state)
{
struct iwl_priv *priv = IWL_OP_MODE_GET_DVM(op_mode);
if (state)
set_bit(STATUS_RF_KILL_HW, &priv->status);
else
clear_bit(STATUS_RF_KILL_HW, &priv->status);
wiphy_rfkill_set_hw_state(priv->hw->wiphy, state);
}
void iwl_free_skb(struct iwl_op_mode *op_mode, struct sk_buff *skb)
{
struct ieee80211_tx_info *info;
info = IEEE80211_SKB_CB(skb);
kmem_cache_free(iwl_tx_cmd_pool, (info->driver_data[1]));
dev_kfree_skb_any(skb);
}
| gpl-2.0 |
avisconti/prova | arch/arm/mach-omap1/board-nokia770.c | 4734 | 6391 | /*
* linux/arch/arm/mach-omap1/board-nokia770.c
*
* Modified from board-generic.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/gpio.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/clk.h>
#include <linux/omapfb.h>
#include <linux/spi/spi.h>
#include <linux/spi/ads7846.h>
#include <linux/workqueue.h>
#include <linux/delay.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <plat/mux.h>
#include <plat/usb.h>
#include <plat/board.h>
#include <plat/keypad.h>
#include <plat/lcd_mipid.h>
#include <plat/mmc.h>
#include <plat/clock.h>
#include <mach/hardware.h>
#include "common.h"
#define ADS7846_PENDOWN_GPIO 15
static const unsigned int nokia770_keymap[] = {
KEY(1, 0, GROUP_0 | KEY_UP),
KEY(2, 0, GROUP_1 | KEY_F5),
KEY(0, 1, GROUP_0 | KEY_LEFT),
KEY(1, 1, GROUP_0 | KEY_ENTER),
KEY(2, 1, GROUP_0 | KEY_RIGHT),
KEY(0, 2, GROUP_1 | KEY_ESC),
KEY(1, 2, GROUP_0 | KEY_DOWN),
KEY(2, 2, GROUP_1 | KEY_F4),
KEY(0, 3, GROUP_2 | KEY_F7),
KEY(1, 3, GROUP_2 | KEY_F8),
KEY(2, 3, GROUP_2 | KEY_F6),
};
static struct resource nokia770_kp_resources[] = {
[0] = {
.start = INT_KEYBOARD,
.end = INT_KEYBOARD,
.flags = IORESOURCE_IRQ,
},
};
static const struct matrix_keymap_data nokia770_keymap_data = {
.keymap = nokia770_keymap,
.keymap_size = ARRAY_SIZE(nokia770_keymap),
};
static struct omap_kp_platform_data nokia770_kp_data = {
.rows = 8,
.cols = 8,
.keymap_data = &nokia770_keymap_data,
.delay = 4,
};
static struct platform_device nokia770_kp_device = {
.name = "omap-keypad",
.id = -1,
.dev = {
.platform_data = &nokia770_kp_data,
},
.num_resources = ARRAY_SIZE(nokia770_kp_resources),
.resource = nokia770_kp_resources,
};
static struct platform_device *nokia770_devices[] __initdata = {
&nokia770_kp_device,
};
static void mipid_shutdown(struct mipid_platform_data *pdata)
{
if (pdata->nreset_gpio != -1) {
printk(KERN_INFO "shutdown LCD\n");
gpio_set_value(pdata->nreset_gpio, 0);
msleep(120);
}
}
static struct mipid_platform_data nokia770_mipid_platform_data = {
.shutdown = mipid_shutdown,
};
static struct omap_lcd_config nokia770_lcd_config __initdata = {
.ctrl_name = "hwa742",
};
static void __init mipid_dev_init(void)
{
nokia770_mipid_platform_data.nreset_gpio = 13;
nokia770_mipid_platform_data.data_lines = 16;
omapfb_set_lcd_config(&nokia770_lcd_config);
}
static void __init ads7846_dev_init(void)
{
if (gpio_request(ADS7846_PENDOWN_GPIO, "ADS7846 pendown") < 0)
printk(KERN_ERR "can't get ads7846 pen down GPIO\n");
}
static int ads7846_get_pendown_state(void)
{
return !gpio_get_value(ADS7846_PENDOWN_GPIO);
}
static struct ads7846_platform_data nokia770_ads7846_platform_data __initdata = {
.x_max = 0x0fff,
.y_max = 0x0fff,
.x_plate_ohms = 180,
.pressure_max = 255,
.debounce_max = 10,
.debounce_tol = 3,
.debounce_rep = 1,
.get_pendown_state = ads7846_get_pendown_state,
};
static struct spi_board_info nokia770_spi_board_info[] __initdata = {
[0] = {
.modalias = "lcd_mipid",
.bus_num = 2,
.chip_select = 3,
.max_speed_hz = 12000000,
.platform_data = &nokia770_mipid_platform_data,
},
[1] = {
.modalias = "ads7846",
.bus_num = 2,
.chip_select = 0,
.max_speed_hz = 2500000,
.platform_data = &nokia770_ads7846_platform_data,
},
};
static void __init hwa742_dev_init(void)
{
clk_add_alias("hwa_sys_ck", NULL, "bclk", NULL);
}
/* assume no Mini-AB port */
static struct omap_usb_config nokia770_usb_config __initdata = {
.otg = 1,
.register_host = 1,
.register_dev = 1,
.hmc_mode = 16,
.pins[0] = 6,
};
#if defined(CONFIG_MMC_OMAP) || defined(CONFIG_MMC_OMAP_MODULE)
#define NOKIA770_GPIO_MMC_POWER 41
#define NOKIA770_GPIO_MMC_SWITCH 23
static int nokia770_mmc_set_power(struct device *dev, int slot, int power_on,
int vdd)
{
gpio_set_value(NOKIA770_GPIO_MMC_POWER, power_on);
return 0;
}
static int nokia770_mmc_get_cover_state(struct device *dev, int slot)
{
return gpio_get_value(NOKIA770_GPIO_MMC_SWITCH);
}
static struct omap_mmc_platform_data nokia770_mmc2_data = {
.nr_slots = 1,
.dma_mask = 0xffffffff,
.max_freq = 12000000,
.slots[0] = {
.set_power = nokia770_mmc_set_power,
.get_cover_state = nokia770_mmc_get_cover_state,
.ocr_mask = MMC_VDD_32_33|MMC_VDD_33_34,
.name = "mmcblk",
},
};
static struct omap_mmc_platform_data *nokia770_mmc_data[OMAP16XX_NR_MMC];
static void __init nokia770_mmc_init(void)
{
int ret;
ret = gpio_request(NOKIA770_GPIO_MMC_POWER, "MMC power");
if (ret < 0)
return;
gpio_direction_output(NOKIA770_GPIO_MMC_POWER, 0);
ret = gpio_request(NOKIA770_GPIO_MMC_SWITCH, "MMC cover");
if (ret < 0) {
gpio_free(NOKIA770_GPIO_MMC_POWER);
return;
}
gpio_direction_input(NOKIA770_GPIO_MMC_SWITCH);
/* Only the second MMC controller is used */
nokia770_mmc_data[1] = &nokia770_mmc2_data;
omap1_init_mmc(nokia770_mmc_data, OMAP16XX_NR_MMC);
}
#else
static inline void nokia770_mmc_init(void)
{
}
#endif
static void __init omap_nokia770_init(void)
{
/* On Nokia 770, the SleepX signal is masked with an
* MPUIO line by default. It has to be unmasked for it
* to become functional */
/* SleepX mask direction */
omap_writew((omap_readw(0xfffb5008) & ~2), 0xfffb5008);
/* Unmask SleepX signal */
omap_writew((omap_readw(0xfffb5004) & ~2), 0xfffb5004);
platform_add_devices(nokia770_devices, ARRAY_SIZE(nokia770_devices));
nokia770_spi_board_info[1].irq = gpio_to_irq(15);
spi_register_board_info(nokia770_spi_board_info,
ARRAY_SIZE(nokia770_spi_board_info));
omap_serial_init();
omap_register_i2c_bus(1, 100, NULL, 0);
hwa742_dev_init();
ads7846_dev_init();
mipid_dev_init();
omap1_usb_init(&nokia770_usb_config);
nokia770_mmc_init();
}
MACHINE_START(NOKIA770, "Nokia 770")
.atag_offset = 0x100,
.map_io = omap16xx_map_io,
.init_early = omap1_init_early,
.reserve = omap_reserve,
.init_irq = omap1_init_irq,
.init_machine = omap_nokia770_init,
.timer = &omap1_timer,
.restart = omap1_restart,
MACHINE_END
| gpl-2.0 |
santod/android_kernel_htc_dlxwl | arch/arm/mach-imx/imx53-dt.c | 4734 | 4609 | /*
* Copyright 2011 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright 2011 Linaro Ltd.
*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*/
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/irqdomain.h>
#include <linux/of_irq.h>
#include <linux/of_platform.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include <mach/common.h>
#include <mach/mx53.h>
/*
* Lookup table for attaching a specific name and platform_data pointer to
* devices as they get created by of_platform_populate(). Ideally this table
* would not exist, but the current clock implementation depends on some devices
* having a specific name.
*/
static const struct of_dev_auxdata imx53_auxdata_lookup[] __initconst = {
OF_DEV_AUXDATA("fsl,imx53-uart", MX53_UART1_BASE_ADDR, "imx21-uart.0", NULL),
OF_DEV_AUXDATA("fsl,imx53-uart", MX53_UART2_BASE_ADDR, "imx21-uart.1", NULL),
OF_DEV_AUXDATA("fsl,imx53-uart", MX53_UART3_BASE_ADDR, "imx21-uart.2", NULL),
OF_DEV_AUXDATA("fsl,imx53-uart", MX53_UART4_BASE_ADDR, "imx21-uart.3", NULL),
OF_DEV_AUXDATA("fsl,imx53-uart", MX53_UART5_BASE_ADDR, "imx21-uart.4", NULL),
OF_DEV_AUXDATA("fsl,imx53-fec", MX53_FEC_BASE_ADDR, "imx25-fec.0", NULL),
OF_DEV_AUXDATA("fsl,imx53-esdhc", MX53_ESDHC1_BASE_ADDR, "sdhci-esdhc-imx53.0", NULL),
OF_DEV_AUXDATA("fsl,imx53-esdhc", MX53_ESDHC2_BASE_ADDR, "sdhci-esdhc-imx53.1", NULL),
OF_DEV_AUXDATA("fsl,imx53-esdhc", MX53_ESDHC3_BASE_ADDR, "sdhci-esdhc-imx53.2", NULL),
OF_DEV_AUXDATA("fsl,imx53-esdhc", MX53_ESDHC4_BASE_ADDR, "sdhci-esdhc-imx53.3", NULL),
OF_DEV_AUXDATA("fsl,imx53-ecspi", MX53_ECSPI1_BASE_ADDR, "imx51-ecspi.0", NULL),
OF_DEV_AUXDATA("fsl,imx53-ecspi", MX53_ECSPI2_BASE_ADDR, "imx51-ecspi.1", NULL),
OF_DEV_AUXDATA("fsl,imx53-cspi", MX53_CSPI_BASE_ADDR, "imx35-cspi.0", NULL),
OF_DEV_AUXDATA("fsl,imx53-i2c", MX53_I2C1_BASE_ADDR, "imx-i2c.0", NULL),
OF_DEV_AUXDATA("fsl,imx53-i2c", MX53_I2C2_BASE_ADDR, "imx-i2c.1", NULL),
OF_DEV_AUXDATA("fsl,imx53-i2c", MX53_I2C3_BASE_ADDR, "imx-i2c.2", NULL),
OF_DEV_AUXDATA("fsl,imx53-sdma", MX53_SDMA_BASE_ADDR, "imx35-sdma", NULL),
OF_DEV_AUXDATA("fsl,imx53-wdt", MX53_WDOG1_BASE_ADDR, "imx2-wdt.0", NULL),
{ /* sentinel */ }
};
static int __init imx53_tzic_add_irq_domain(struct device_node *np,
struct device_node *interrupt_parent)
{
irq_domain_add_legacy(np, 128, 0, 0, &irq_domain_simple_ops, NULL);
return 0;
}
static int __init imx53_gpio_add_irq_domain(struct device_node *np,
struct device_node *interrupt_parent)
{
static int gpio_irq_base = MXC_GPIO_IRQ_START + ARCH_NR_GPIOS;
gpio_irq_base -= 32;
irq_domain_add_legacy(np, 32, gpio_irq_base, 0, &irq_domain_simple_ops, NULL);
return 0;
}
static const struct of_device_id imx53_irq_match[] __initconst = {
{ .compatible = "fsl,imx53-tzic", .data = imx53_tzic_add_irq_domain, },
{ .compatible = "fsl,imx53-gpio", .data = imx53_gpio_add_irq_domain, },
{ /* sentinel */ }
};
static const struct of_device_id imx53_iomuxc_of_match[] __initconst = {
{ .compatible = "fsl,imx53-iomuxc-ard", .data = imx53_ard_common_init, },
{ .compatible = "fsl,imx53-iomuxc-evk", .data = imx53_evk_common_init, },
{ .compatible = "fsl,imx53-iomuxc-qsb", .data = imx53_qsb_common_init, },
{ .compatible = "fsl,imx53-iomuxc-smd", .data = imx53_smd_common_init, },
{ /* sentinel */ }
};
static void __init imx53_dt_init(void)
{
struct device_node *node;
const struct of_device_id *of_id;
void (*func)(void);
of_irq_init(imx53_irq_match);
node = of_find_matching_node(NULL, imx53_iomuxc_of_match);
if (node) {
of_id = of_match_node(imx53_iomuxc_of_match, node);
func = of_id->data;
func();
of_node_put(node);
}
of_platform_populate(NULL, of_default_bus_match_table,
imx53_auxdata_lookup, NULL);
}
static void __init imx53_timer_init(void)
{
mx53_clocks_init_dt();
}
static struct sys_timer imx53_timer = {
.init = imx53_timer_init,
};
static const char *imx53_dt_board_compat[] __initdata = {
"fsl,imx53-ard",
"fsl,imx53-evk",
"fsl,imx53-qsb",
"fsl,imx53-smd",
"fsl,imx53",
NULL
};
DT_MACHINE_START(IMX53_DT, "Freescale i.MX53 (Device Tree Support)")
.map_io = mx53_map_io,
.init_early = imx53_init_early,
.init_irq = mx53_init_irq,
.handle_irq = imx53_handle_irq,
.timer = &imx53_timer,
.init_machine = imx53_dt_init,
.dt_compat = imx53_dt_board_compat,
.restart = mxc_restart,
MACHINE_END
| gpl-2.0 |
lyfkevin/Wind_iproj_JB_kernel_old | lib/hexdump.c | 4734 | 7158 | /*
* lib/hexdump.c
*
* 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. See README and COPYING for
* more details.
*/
#include <linux/types.h>
#include <linux/ctype.h>
#include <linux/kernel.h>
#include <linux/export.h>
const char hex_asc[] = "0123456789abcdef";
EXPORT_SYMBOL(hex_asc);
/**
* hex_to_bin - convert a hex digit to its real value
* @ch: ascii character represents hex digit
*
* hex_to_bin() converts one hex digit to its actual value or -1 in case of bad
* input.
*/
int hex_to_bin(char ch)
{
if ((ch >= '0') && (ch <= '9'))
return ch - '0';
ch = tolower(ch);
if ((ch >= 'a') && (ch <= 'f'))
return ch - 'a' + 10;
return -1;
}
EXPORT_SYMBOL(hex_to_bin);
/**
* hex2bin - convert an ascii hexadecimal string to its binary representation
* @dst: binary result
* @src: ascii hexadecimal string
* @count: result length
*
* Return 0 on success, -1 in case of bad input.
*/
int hex2bin(u8 *dst, const char *src, size_t count)
{
while (count--) {
int hi = hex_to_bin(*src++);
int lo = hex_to_bin(*src++);
if ((hi < 0) || (lo < 0))
return -1;
*dst++ = (hi << 4) | lo;
}
return 0;
}
EXPORT_SYMBOL(hex2bin);
/**
* hex_dump_to_buffer - convert a blob of data to "hex ASCII" in memory
* @buf: data blob to dump
* @len: number of bytes in the @buf
* @rowsize: number of bytes to print per line; must be 16 or 32
* @groupsize: number of bytes to print at a time (1, 2, 4, 8; default = 1)
* @linebuf: where to put the converted data
* @linebuflen: total size of @linebuf, including space for terminating NUL
* @ascii: include ASCII after the hex output
*
* hex_dump_to_buffer() works on one "line" of output at a time, i.e.,
* 16 or 32 bytes of input data converted to hex + ASCII output.
*
* Given a buffer of u8 data, hex_dump_to_buffer() converts the input data
* to a hex + ASCII dump at the supplied memory location.
* The converted output is always NUL-terminated.
*
* E.g.:
* hex_dump_to_buffer(frame->data, frame->len, 16, 1,
* linebuf, sizeof(linebuf), true);
*
* example output buffer:
* 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f @ABCDEFGHIJKLMNO
*/
void hex_dump_to_buffer(const void *buf, size_t len, int rowsize,
int groupsize, char *linebuf, size_t linebuflen,
bool ascii)
{
const u8 *ptr = buf;
u8 ch;
int j, lx = 0;
int ascii_column;
if (rowsize != 16 && rowsize != 32)
rowsize = 16;
if (!len)
goto nil;
if (len > rowsize) /* limit to one line at a time */
len = rowsize;
if ((len % groupsize) != 0) /* no mixed size output */
groupsize = 1;
switch (groupsize) {
case 8: {
const u64 *ptr8 = buf;
int ngroups = len / groupsize;
for (j = 0; j < ngroups; j++)
lx += scnprintf(linebuf + lx, linebuflen - lx,
"%s%16.16llx", j ? " " : "",
(unsigned long long)*(ptr8 + j));
ascii_column = 17 * ngroups + 2;
break;
}
case 4: {
const u32 *ptr4 = buf;
int ngroups = len / groupsize;
for (j = 0; j < ngroups; j++)
lx += scnprintf(linebuf + lx, linebuflen - lx,
"%s%8.8x", j ? " " : "", *(ptr4 + j));
ascii_column = 9 * ngroups + 2;
break;
}
case 2: {
const u16 *ptr2 = buf;
int ngroups = len / groupsize;
for (j = 0; j < ngroups; j++)
lx += scnprintf(linebuf + lx, linebuflen - lx,
"%s%4.4x", j ? " " : "", *(ptr2 + j));
ascii_column = 5 * ngroups + 2;
break;
}
default:
for (j = 0; (j < len) && (lx + 3) <= linebuflen; j++) {
ch = ptr[j];
linebuf[lx++] = hex_asc_hi(ch);
linebuf[lx++] = hex_asc_lo(ch);
linebuf[lx++] = ' ';
}
if (j)
lx--;
ascii_column = 3 * rowsize + 2;
break;
}
if (!ascii)
goto nil;
while (lx < (linebuflen - 1) && lx < (ascii_column - 1))
linebuf[lx++] = ' ';
for (j = 0; (j < len) && (lx + 2) < linebuflen; j++) {
ch = ptr[j];
linebuf[lx++] = (isascii(ch) && isprint(ch)) ? ch : '.';
}
nil:
linebuf[lx++] = '\0';
}
EXPORT_SYMBOL(hex_dump_to_buffer);
#ifdef CONFIG_PRINTK
/**
* print_hex_dump - print a text hex dump to syslog for a binary blob of data
* @level: kernel log level (e.g. KERN_DEBUG)
* @prefix_str: string to prefix each line with;
* caller supplies trailing spaces for alignment if desired
* @prefix_type: controls whether prefix of an offset, address, or none
* is printed (%DUMP_PREFIX_OFFSET, %DUMP_PREFIX_ADDRESS, %DUMP_PREFIX_NONE)
* @rowsize: number of bytes to print per line; must be 16 or 32
* @groupsize: number of bytes to print at a time (1, 2, 4, 8; default = 1)
* @buf: data blob to dump
* @len: number of bytes in the @buf
* @ascii: include ASCII after the hex output
*
* Given a buffer of u8 data, print_hex_dump() prints a hex + ASCII dump
* to the kernel log at the specified kernel log level, with an optional
* leading prefix.
*
* print_hex_dump() works on one "line" of output at a time, i.e.,
* 16 or 32 bytes of input data converted to hex + ASCII output.
* print_hex_dump() iterates over the entire input @buf, breaking it into
* "line size" chunks to format and print.
*
* E.g.:
* print_hex_dump(KERN_DEBUG, "raw data: ", DUMP_PREFIX_ADDRESS,
* 16, 1, frame->data, frame->len, true);
*
* Example output using %DUMP_PREFIX_OFFSET and 1-byte mode:
* 0009ab42: 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f @ABCDEFGHIJKLMNO
* Example output using %DUMP_PREFIX_ADDRESS and 4-byte mode:
* ffffffff88089af0: 73727170 77767574 7b7a7978 7f7e7d7c pqrstuvwxyz{|}~.
*/
void print_hex_dump(const char *level, const char *prefix_str, int prefix_type,
int rowsize, int groupsize,
const void *buf, size_t len, bool ascii)
{
const u8 *ptr = buf;
int i, linelen, remaining = len;
unsigned char linebuf[32 * 3 + 2 + 32 + 1];
if (rowsize != 16 && rowsize != 32)
rowsize = 16;
for (i = 0; i < len; i += rowsize) {
linelen = min(remaining, rowsize);
remaining -= rowsize;
hex_dump_to_buffer(ptr + i, linelen, rowsize, groupsize,
linebuf, sizeof(linebuf), ascii);
switch (prefix_type) {
case DUMP_PREFIX_ADDRESS:
printk("%s%s%p: %s\n",
level, prefix_str, ptr + i, linebuf);
break;
case DUMP_PREFIX_OFFSET:
printk("%s%s%.8x: %s\n", level, prefix_str, i, linebuf);
break;
default:
printk("%s%s%s\n", level, prefix_str, linebuf);
break;
}
}
}
EXPORT_SYMBOL(print_hex_dump);
/**
* print_hex_dump_bytes - shorthand form of print_hex_dump() with default params
* @prefix_str: string to prefix each line with;
* caller supplies trailing spaces for alignment if desired
* @prefix_type: controls whether prefix of an offset, address, or none
* is printed (%DUMP_PREFIX_OFFSET, %DUMP_PREFIX_ADDRESS, %DUMP_PREFIX_NONE)
* @buf: data blob to dump
* @len: number of bytes in the @buf
*
* Calls print_hex_dump(), with log level of KERN_DEBUG,
* rowsize of 16, groupsize of 1, and ASCII output included.
*/
void print_hex_dump_bytes(const char *prefix_str, int prefix_type,
const void *buf, size_t len)
{
print_hex_dump(KERN_DEBUG, prefix_str, prefix_type, 16, 1,
buf, len, true);
}
EXPORT_SYMBOL(print_hex_dump_bytes);
#endif
| gpl-2.0 |
davidmueller13/aospmmkernel2 | arch/arm/mach-s3c24xx/mach-gta02.c | 4734 | 14328 | /*
* linux/arch/arm/mach-s3c2442/mach-gta02.c
*
* S3C2442 Machine Support for Openmoko GTA02 / FreeRunner.
*
* Copyright (C) 2006-2009 by Openmoko, Inc.
* Authors: Harald Welte <laforge@openmoko.org>
* Andy Green <andy@openmoko.org>
* Werner Almesberger <werner@openmoko.org>
* All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/delay.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/gpio.h>
#include <linux/workqueue.h>
#include <linux/platform_device.h>
#include <linux/serial_core.h>
#include <linux/spi/spi.h>
#include <linux/spi/s3c24xx.h>
#include <linux/mmc/host.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/nand_ecc.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/io.h>
#include <linux/i2c.h>
#include <linux/regulator/machine.h>
#include <linux/mfd/pcf50633/core.h>
#include <linux/mfd/pcf50633/mbc.h>
#include <linux/mfd/pcf50633/adc.h>
#include <linux/mfd/pcf50633/gpio.h>
#include <linux/mfd/pcf50633/pmic.h>
#include <linux/mfd/pcf50633/backlight.h>
#include <linux/input.h>
#include <linux/gpio_keys.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <mach/regs-irq.h>
#include <mach/regs-gpio.h>
#include <mach/regs-gpioj.h>
#include <mach/fb.h>
#include <plat/usb-control.h>
#include <mach/regs-mem.h>
#include <mach/hardware.h>
#include <mach/gta02.h>
#include <plat/regs-serial.h>
#include <plat/nand.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/pm.h>
#include <plat/udc.h>
#include <plat/gpio-cfg.h>
#include <plat/iic.h>
#include <plat/ts.h>
#include "common.h"
static struct pcf50633 *gta02_pcf;
/*
* This gets called frequently when we paniced.
*/
static long gta02_panic_blink(int state)
{
long delay = 0;
char led;
led = (state) ? 1 : 0;
gpio_direction_output(GTA02_GPIO_AUX_LED, led);
return delay;
}
static struct map_desc gta02_iodesc[] __initdata = {
{
.virtual = 0xe0000000,
.pfn = __phys_to_pfn(S3C2410_CS3 + 0x01000000),
.length = SZ_1M,
.type = MT_DEVICE
},
};
#define UCON (S3C2410_UCON_DEFAULT | S3C2443_UCON_RXERR_IRQEN)
#define ULCON (S3C2410_LCON_CS8 | S3C2410_LCON_PNONE | S3C2410_LCON_STOPB)
#define UFCON (S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE)
static struct s3c2410_uartcfg gta02_uartcfgs[] = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
};
#ifdef CONFIG_CHARGER_PCF50633
/*
* On GTA02 the 1A charger features a 48K resistor to 0V on the ID pin.
* We use this to recognize that we can pull 1A from the USB socket.
*
* These constants are the measured pcf50633 ADC levels with the 1A
* charger / 48K resistor, and with no pulldown resistor.
*/
#define ADC_NOM_CHG_DETECT_1A 6
#define ADC_NOM_CHG_DETECT_USB 43
static void
gta02_configure_pmu_for_charger(struct pcf50633 *pcf, void *unused, int res)
{
int ma;
/* Interpret charger type */
if (res < ((ADC_NOM_CHG_DETECT_USB + ADC_NOM_CHG_DETECT_1A) / 2)) {
/*
* Sanity - stop GPO driving out now that we have a 1A charger
* GPO controls USB Host power generation on GTA02
*/
pcf50633_gpio_set(pcf, PCF50633_GPO, 0);
ma = 1000;
} else
ma = 100;
pcf50633_mbc_usb_curlim_set(pcf, ma);
}
static struct delayed_work gta02_charger_work;
static int gta02_usb_vbus_draw;
static void gta02_charger_worker(struct work_struct *work)
{
if (gta02_usb_vbus_draw) {
pcf50633_mbc_usb_curlim_set(gta02_pcf, gta02_usb_vbus_draw);
return;
}
#ifdef CONFIG_PCF50633_ADC
pcf50633_adc_async_read(gta02_pcf,
PCF50633_ADCC1_MUX_ADCIN1,
PCF50633_ADCC1_AVERAGE_16,
gta02_configure_pmu_for_charger,
NULL);
#else
/*
* If the PCF50633 ADC is disabled we fallback to a
* 100mA limit for safety.
*/
pcf50633_mbc_usb_curlim_set(pcf, 100);
#endif
}
#define GTA02_CHARGER_CONFIGURE_TIMEOUT ((3000 * HZ) / 1000)
static void gta02_pmu_event_callback(struct pcf50633 *pcf, int irq)
{
if (irq == PCF50633_IRQ_USBINS) {
schedule_delayed_work(>a02_charger_work,
GTA02_CHARGER_CONFIGURE_TIMEOUT);
return;
}
if (irq == PCF50633_IRQ_USBREM) {
cancel_delayed_work_sync(>a02_charger_work);
gta02_usb_vbus_draw = 0;
}
}
static void gta02_udc_vbus_draw(unsigned int ma)
{
if (!gta02_pcf)
return;
gta02_usb_vbus_draw = ma;
schedule_delayed_work(>a02_charger_work,
GTA02_CHARGER_CONFIGURE_TIMEOUT);
}
#else /* !CONFIG_CHARGER_PCF50633 */
#define gta02_pmu_event_callback NULL
#define gta02_udc_vbus_draw NULL
#endif
/*
* This is called when pc50633 is probed, unfortunately quite late in the
* day since it is an I2C bus device. Here we can belatedly define some
* platform devices with the advantage that we can mark the pcf50633 as the
* parent. This makes them get suspended and resumed with their parent
* the pcf50633 still around.
*/
static void gta02_pmu_attach_child_devices(struct pcf50633 *pcf);
static char *gta02_batteries[] = {
"battery",
};
static struct pcf50633_bl_platform_data gta02_backlight_data = {
.default_brightness = 0x3f,
.default_brightness_limit = 0,
.ramp_time = 5,
};
static struct pcf50633_platform_data gta02_pcf_pdata = {
.resumers = {
[0] = PCF50633_INT1_USBINS |
PCF50633_INT1_USBREM |
PCF50633_INT1_ALARM,
[1] = PCF50633_INT2_ONKEYF,
[2] = PCF50633_INT3_ONKEY1S,
[3] = PCF50633_INT4_LOWSYS |
PCF50633_INT4_LOWBAT |
PCF50633_INT4_HIGHTMP,
},
.batteries = gta02_batteries,
.num_batteries = ARRAY_SIZE(gta02_batteries),
.charger_reference_current_ma = 1000,
.backlight_data = >a02_backlight_data,
.reg_init_data = {
[PCF50633_REGULATOR_AUTO] = {
.constraints = {
.min_uV = 3300000,
.max_uV = 3300000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.always_on = 1,
.apply_uV = 1,
},
},
[PCF50633_REGULATOR_DOWN1] = {
.constraints = {
.min_uV = 1300000,
.max_uV = 1600000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.always_on = 1,
.apply_uV = 1,
},
},
[PCF50633_REGULATOR_DOWN2] = {
.constraints = {
.min_uV = 1800000,
.max_uV = 1800000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.apply_uV = 1,
.always_on = 1,
},
},
[PCF50633_REGULATOR_HCLDO] = {
.constraints = {
.min_uV = 2000000,
.max_uV = 3300000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE |
REGULATOR_CHANGE_STATUS,
},
},
[PCF50633_REGULATOR_LDO1] = {
.constraints = {
.min_uV = 3300000,
.max_uV = 3300000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.apply_uV = 1,
},
},
[PCF50633_REGULATOR_LDO2] = {
.constraints = {
.min_uV = 3300000,
.max_uV = 3300000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.apply_uV = 1,
},
},
[PCF50633_REGULATOR_LDO3] = {
.constraints = {
.min_uV = 3000000,
.max_uV = 3000000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.apply_uV = 1,
},
},
[PCF50633_REGULATOR_LDO4] = {
.constraints = {
.min_uV = 3200000,
.max_uV = 3200000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.apply_uV = 1,
},
},
[PCF50633_REGULATOR_LDO5] = {
.constraints = {
.min_uV = 3000000,
.max_uV = 3000000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.apply_uV = 1,
},
},
[PCF50633_REGULATOR_LDO6] = {
.constraints = {
.min_uV = 3000000,
.max_uV = 3000000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
},
},
[PCF50633_REGULATOR_MEMLDO] = {
.constraints = {
.min_uV = 1800000,
.max_uV = 1800000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
},
},
},
.probe_done = gta02_pmu_attach_child_devices,
.mbc_event_callback = gta02_pmu_event_callback,
};
/* NOR Flash. */
#define GTA02_FLASH_BASE 0x18000000 /* GCS3 */
#define GTA02_FLASH_SIZE 0x200000 /* 2MBytes */
static struct physmap_flash_data gta02_nor_flash_data = {
.width = 2,
};
static struct resource gta02_nor_flash_resource = {
.start = GTA02_FLASH_BASE,
.end = GTA02_FLASH_BASE + GTA02_FLASH_SIZE - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device gta02_nor_flash = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = >a02_nor_flash_data,
},
.resource = >a02_nor_flash_resource,
.num_resources = 1,
};
static struct platform_device s3c24xx_pwm_device = {
.name = "s3c24xx_pwm",
.num_resources = 0,
};
static struct platform_device gta02_dfbmcs320_device = {
.name = "dfbmcs320",
};
static struct i2c_board_info gta02_i2c_devs[] __initdata = {
{
I2C_BOARD_INFO("pcf50633", 0x73),
.irq = GTA02_IRQ_PCF50633,
.platform_data = >a02_pcf_pdata,
},
{
I2C_BOARD_INFO("wm8753", 0x1a),
},
};
static struct s3c2410_nand_set __initdata gta02_nand_sets[] = {
[0] = {
/*
* This name is also hard-coded in the boot loaders, so
* changing it would would require all users to upgrade
* their boot loaders, some of which are stored in a NOR
* that is considered to be immutable.
*/
.name = "neo1973-nand",
.nr_chips = 1,
.flash_bbt = 1,
},
};
/*
* Choose a set of timings derived from S3C@2442B MCP54
* data sheet (K5D2G13ACM-D075 MCP Memory).
*/
static struct s3c2410_platform_nand __initdata gta02_nand_info = {
.tacls = 0,
.twrph0 = 25,
.twrph1 = 15,
.nr_sets = ARRAY_SIZE(gta02_nand_sets),
.sets = gta02_nand_sets,
};
/* Get PMU to set USB current limit accordingly. */
static struct s3c2410_udc_mach_info gta02_udc_cfg __initdata = {
.vbus_draw = gta02_udc_vbus_draw,
.pullup_pin = GTA02_GPIO_USB_PULLUP,
};
/* USB */
static struct s3c2410_hcd_info gta02_usb_info __initdata = {
.port[0] = {
.flags = S3C_HCDFLG_USED,
},
.port[1] = {
.flags = 0,
},
};
/* Touchscreen */
static struct s3c2410_ts_mach_info gta02_ts_info = {
.delay = 10000,
.presc = 0xff, /* slow as we can go */
.oversampling_shift = 2,
};
/* Buttons */
static struct gpio_keys_button gta02_buttons[] = {
{
.gpio = GTA02_GPIO_AUX_KEY,
.code = KEY_PHONE,
.desc = "Aux",
.type = EV_KEY,
.debounce_interval = 100,
},
{
.gpio = GTA02_GPIO_HOLD_KEY,
.code = KEY_PAUSE,
.desc = "Hold",
.type = EV_KEY,
.debounce_interval = 100,
},
};
static struct gpio_keys_platform_data gta02_buttons_pdata = {
.buttons = gta02_buttons,
.nbuttons = ARRAY_SIZE(gta02_buttons),
};
static struct platform_device gta02_buttons_device = {
.name = "gpio-keys",
.id = -1,
.dev = {
.platform_data = >a02_buttons_pdata,
},
};
static void __init gta02_map_io(void)
{
s3c24xx_init_io(gta02_iodesc, ARRAY_SIZE(gta02_iodesc));
s3c24xx_init_clocks(12000000);
s3c24xx_init_uarts(gta02_uartcfgs, ARRAY_SIZE(gta02_uartcfgs));
}
/* These are the guys that don't need to be children of PMU. */
static struct platform_device *gta02_devices[] __initdata = {
&s3c_device_ohci,
&s3c_device_wdt,
&s3c_device_sdi,
&s3c_device_usbgadget,
&s3c_device_nand,
>a02_nor_flash,
&s3c24xx_pwm_device,
&s3c_device_iis,
&samsung_asoc_dma,
&s3c_device_i2c0,
>a02_dfbmcs320_device,
>a02_buttons_device,
&s3c_device_adc,
&s3c_device_ts,
};
/* These guys DO need to be children of PMU. */
static struct platform_device *gta02_devices_pmu_children[] = {
};
/*
* This is called when pc50633 is probed, quite late in the day since it is an
* I2C bus device. Here we can define platform devices with the advantage that
* we can mark the pcf50633 as the parent. This makes them get suspended and
* resumed with their parent the pcf50633 still around. All devices whose
* operation depends on something from pcf50633 must have this relationship
* made explicit like this, or suspend and resume will become an unreliable
* hellworld.
*/
static void gta02_pmu_attach_child_devices(struct pcf50633 *pcf)
{
int n;
/* Grab a copy of the now probed PMU pointer. */
gta02_pcf = pcf;
for (n = 0; n < ARRAY_SIZE(gta02_devices_pmu_children); n++)
gta02_devices_pmu_children[n]->dev.parent = pcf->dev;
platform_add_devices(gta02_devices_pmu_children,
ARRAY_SIZE(gta02_devices_pmu_children));
}
static void gta02_poweroff(void)
{
pcf50633_reg_set_bit_mask(gta02_pcf, PCF50633_REG_OOCSHDWN, 1, 1);
}
static void __init gta02_machine_init(void)
{
/* Set the panic callback to turn AUX LED on or off. */
panic_blink = gta02_panic_blink;
s3c_pm_init();
#ifdef CONFIG_CHARGER_PCF50633
INIT_DELAYED_WORK(>a02_charger_work, gta02_charger_worker);
#endif
s3c24xx_udc_set_platdata(>a02_udc_cfg);
s3c24xx_ts_set_platdata(>a02_ts_info);
s3c_ohci_set_platdata(>a02_usb_info);
s3c_nand_set_platdata(>a02_nand_info);
s3c_i2c0_set_platdata(NULL);
i2c_register_board_info(0, gta02_i2c_devs, ARRAY_SIZE(gta02_i2c_devs));
platform_add_devices(gta02_devices, ARRAY_SIZE(gta02_devices));
pm_power_off = gta02_poweroff;
regulator_has_full_constraints();
}
MACHINE_START(NEO1973_GTA02, "GTA02")
/* Maintainer: Nelson Castillo <arhuaco@freaks-unidos.net> */
.atag_offset = 0x100,
.map_io = gta02_map_io,
.init_irq = s3c24xx_init_irq,
.init_machine = gta02_machine_init,
.timer = &s3c24xx_timer,
.restart = s3c244x_restart,
MACHINE_END
| gpl-2.0 |
TheTypoMaster/android_kernel_samsung_smdk4412 | arch/arm/mach-omap1/board-palmte.c | 4734 | 6710 | /*
* linux/arch/arm/mach-omap1/board-palmte.c
*
* Modified from board-generic.c
*
* Support for the Palm Tungsten E PDA.
*
* Original version : Laurent Gonzalez
*
* Maintainers : http://palmtelinux.sf.net
* palmtelinux-developpers@lists.sf.net
*
* Copyright (c) 2006 Andrzej Zaborowski <balrog@zabor.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/gpio.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/input.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/interrupt.h>
#include <linux/apm-emulation.h>
#include <linux/omapfb.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <plat/flash.h>
#include <plat/mux.h>
#include <plat/usb.h>
#include <plat/tc.h>
#include <plat/dma.h>
#include <plat/board.h>
#include <plat/irda.h>
#include <plat/keypad.h>
#include <mach/hardware.h>
#include "common.h"
#define PALMTE_USBDETECT_GPIO 0
#define PALMTE_USB_OR_DC_GPIO 1
#define PALMTE_TSC_GPIO 4
#define PALMTE_PINTDAV_GPIO 6
#define PALMTE_MMC_WP_GPIO 8
#define PALMTE_MMC_POWER_GPIO 9
#define PALMTE_HDQ_GPIO 11
#define PALMTE_HEADPHONES_GPIO 14
#define PALMTE_SPEAKER_GPIO 15
#define PALMTE_DC_GPIO OMAP_MPUIO(2)
#define PALMTE_MMC_SWITCH_GPIO OMAP_MPUIO(4)
#define PALMTE_MMC1_GPIO OMAP_MPUIO(6)
#define PALMTE_MMC2_GPIO OMAP_MPUIO(7)
#define PALMTE_MMC3_GPIO OMAP_MPUIO(11)
static const unsigned int palmte_keymap[] = {
KEY(0, 0, KEY_F1), /* Calendar */
KEY(1, 0, KEY_F2), /* Contacts */
KEY(2, 0, KEY_F3), /* Tasks List */
KEY(3, 0, KEY_F4), /* Note Pad */
KEY(4, 0, KEY_POWER),
KEY(0, 1, KEY_LEFT),
KEY(1, 1, KEY_DOWN),
KEY(2, 1, KEY_UP),
KEY(3, 1, KEY_RIGHT),
KEY(4, 1, KEY_ENTER),
};
static const struct matrix_keymap_data palmte_keymap_data = {
.keymap = palmte_keymap,
.keymap_size = ARRAY_SIZE(palmte_keymap),
};
static struct omap_kp_platform_data palmte_kp_data = {
.rows = 8,
.cols = 8,
.keymap_data = &palmte_keymap_data,
.rep = true,
.delay = 12,
};
static struct resource palmte_kp_resources[] = {
[0] = {
.start = INT_KEYBOARD,
.end = INT_KEYBOARD,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device palmte_kp_device = {
.name = "omap-keypad",
.id = -1,
.dev = {
.platform_data = &palmte_kp_data,
},
.num_resources = ARRAY_SIZE(palmte_kp_resources),
.resource = palmte_kp_resources,
};
static struct mtd_partition palmte_rom_partitions[] = {
/* PalmOS "Small ROM", contains the bootloader and the debugger */
{
.name = "smallrom",
.offset = 0,
.size = 0xa000,
.mask_flags = MTD_WRITEABLE,
},
/* PalmOS "Big ROM", a filesystem with all the OS code and data */
{
.name = "bigrom",
.offset = SZ_128K,
/*
* 0x5f0000 bytes big in the multi-language ("EFIGS") version,
* 0x7b0000 bytes in the English-only ("enUS") version.
*/
.size = 0x7b0000,
.mask_flags = MTD_WRITEABLE,
},
};
static struct physmap_flash_data palmte_rom_data = {
.width = 2,
.set_vpp = omap1_set_vpp,
.parts = palmte_rom_partitions,
.nr_parts = ARRAY_SIZE(palmte_rom_partitions),
};
static struct resource palmte_rom_resource = {
.start = OMAP_CS0_PHYS,
.end = OMAP_CS0_PHYS + SZ_8M - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device palmte_rom_device = {
.name = "physmap-flash",
.id = -1,
.dev = {
.platform_data = &palmte_rom_data,
},
.num_resources = 1,
.resource = &palmte_rom_resource,
};
static struct platform_device palmte_lcd_device = {
.name = "lcd_palmte",
.id = -1,
};
static struct omap_backlight_config palmte_backlight_config = {
.default_intensity = 0xa0,
};
static struct platform_device palmte_backlight_device = {
.name = "omap-bl",
.id = -1,
.dev = {
.platform_data = &palmte_backlight_config,
},
};
static struct omap_irda_config palmte_irda_config = {
.transceiver_cap = IR_SIRMODE,
.rx_channel = OMAP_DMA_UART3_RX,
.tx_channel = OMAP_DMA_UART3_TX,
.dest_start = UART3_THR,
.src_start = UART3_RHR,
.tx_trigger = 0,
.rx_trigger = 0,
};
static struct resource palmte_irda_resources[] = {
[0] = {
.start = INT_UART3,
.end = INT_UART3,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device palmte_irda_device = {
.name = "omapirda",
.id = -1,
.dev = {
.platform_data = &palmte_irda_config,
},
.num_resources = ARRAY_SIZE(palmte_irda_resources),
.resource = palmte_irda_resources,
};
static struct platform_device *palmte_devices[] __initdata = {
&palmte_rom_device,
&palmte_kp_device,
&palmte_lcd_device,
&palmte_backlight_device,
&palmte_irda_device,
};
static struct omap_usb_config palmte_usb_config __initdata = {
.register_dev = 1, /* Mini-B only receptacle */
.hmc_mode = 0,
.pins[0] = 2,
};
static struct omap_lcd_config palmte_lcd_config __initdata = {
.ctrl_name = "internal",
};
static struct spi_board_info palmte_spi_info[] __initdata = {
{
.modalias = "tsc2102",
.bus_num = 2, /* uWire (officially) */
.chip_select = 0, /* As opposed to 3 */
.max_speed_hz = 8000000,
},
};
static void __init palmte_misc_gpio_setup(void)
{
/* Set TSC2102 PINTDAV pin as input (used by TSC2102 driver) */
if (gpio_request(PALMTE_PINTDAV_GPIO, "TSC2102 PINTDAV") < 0) {
printk(KERN_ERR "Could not reserve PINTDAV GPIO!\n");
return;
}
gpio_direction_input(PALMTE_PINTDAV_GPIO);
/* Set USB-or-DC-IN pin as input (unused) */
if (gpio_request(PALMTE_USB_OR_DC_GPIO, "USB/DC-IN") < 0) {
printk(KERN_ERR "Could not reserve cable signal GPIO!\n");
return;
}
gpio_direction_input(PALMTE_USB_OR_DC_GPIO);
}
static void __init omap_palmte_init(void)
{
/* mux pins for uarts */
omap_cfg_reg(UART1_TX);
omap_cfg_reg(UART1_RTS);
omap_cfg_reg(UART2_TX);
omap_cfg_reg(UART2_RTS);
omap_cfg_reg(UART3_TX);
omap_cfg_reg(UART3_RX);
platform_add_devices(palmte_devices, ARRAY_SIZE(palmte_devices));
palmte_spi_info[0].irq = gpio_to_irq(PALMTE_PINTDAV_GPIO);
spi_register_board_info(palmte_spi_info, ARRAY_SIZE(palmte_spi_info));
palmte_misc_gpio_setup();
omap_serial_init();
omap1_usb_init(&palmte_usb_config);
omap_register_i2c_bus(1, 100, NULL, 0);
omapfb_set_lcd_config(&palmte_lcd_config);
}
MACHINE_START(OMAP_PALMTE, "OMAP310 based Palm Tungsten E")
.atag_offset = 0x100,
.map_io = omap15xx_map_io,
.init_early = omap1_init_early,
.reserve = omap_reserve,
.init_irq = omap1_init_irq,
.init_machine = omap_palmte_init,
.timer = &omap1_timer,
.restart = omap1_restart,
MACHINE_END
| gpl-2.0 |
piasek1906/Piasek-KK-G2 | lib/hexdump.c | 4734 | 7158 | /*
* lib/hexdump.c
*
* 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. See README and COPYING for
* more details.
*/
#include <linux/types.h>
#include <linux/ctype.h>
#include <linux/kernel.h>
#include <linux/export.h>
const char hex_asc[] = "0123456789abcdef";
EXPORT_SYMBOL(hex_asc);
/**
* hex_to_bin - convert a hex digit to its real value
* @ch: ascii character represents hex digit
*
* hex_to_bin() converts one hex digit to its actual value or -1 in case of bad
* input.
*/
int hex_to_bin(char ch)
{
if ((ch >= '0') && (ch <= '9'))
return ch - '0';
ch = tolower(ch);
if ((ch >= 'a') && (ch <= 'f'))
return ch - 'a' + 10;
return -1;
}
EXPORT_SYMBOL(hex_to_bin);
/**
* hex2bin - convert an ascii hexadecimal string to its binary representation
* @dst: binary result
* @src: ascii hexadecimal string
* @count: result length
*
* Return 0 on success, -1 in case of bad input.
*/
int hex2bin(u8 *dst, const char *src, size_t count)
{
while (count--) {
int hi = hex_to_bin(*src++);
int lo = hex_to_bin(*src++);
if ((hi < 0) || (lo < 0))
return -1;
*dst++ = (hi << 4) | lo;
}
return 0;
}
EXPORT_SYMBOL(hex2bin);
/**
* hex_dump_to_buffer - convert a blob of data to "hex ASCII" in memory
* @buf: data blob to dump
* @len: number of bytes in the @buf
* @rowsize: number of bytes to print per line; must be 16 or 32
* @groupsize: number of bytes to print at a time (1, 2, 4, 8; default = 1)
* @linebuf: where to put the converted data
* @linebuflen: total size of @linebuf, including space for terminating NUL
* @ascii: include ASCII after the hex output
*
* hex_dump_to_buffer() works on one "line" of output at a time, i.e.,
* 16 or 32 bytes of input data converted to hex + ASCII output.
*
* Given a buffer of u8 data, hex_dump_to_buffer() converts the input data
* to a hex + ASCII dump at the supplied memory location.
* The converted output is always NUL-terminated.
*
* E.g.:
* hex_dump_to_buffer(frame->data, frame->len, 16, 1,
* linebuf, sizeof(linebuf), true);
*
* example output buffer:
* 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f @ABCDEFGHIJKLMNO
*/
void hex_dump_to_buffer(const void *buf, size_t len, int rowsize,
int groupsize, char *linebuf, size_t linebuflen,
bool ascii)
{
const u8 *ptr = buf;
u8 ch;
int j, lx = 0;
int ascii_column;
if (rowsize != 16 && rowsize != 32)
rowsize = 16;
if (!len)
goto nil;
if (len > rowsize) /* limit to one line at a time */
len = rowsize;
if ((len % groupsize) != 0) /* no mixed size output */
groupsize = 1;
switch (groupsize) {
case 8: {
const u64 *ptr8 = buf;
int ngroups = len / groupsize;
for (j = 0; j < ngroups; j++)
lx += scnprintf(linebuf + lx, linebuflen - lx,
"%s%16.16llx", j ? " " : "",
(unsigned long long)*(ptr8 + j));
ascii_column = 17 * ngroups + 2;
break;
}
case 4: {
const u32 *ptr4 = buf;
int ngroups = len / groupsize;
for (j = 0; j < ngroups; j++)
lx += scnprintf(linebuf + lx, linebuflen - lx,
"%s%8.8x", j ? " " : "", *(ptr4 + j));
ascii_column = 9 * ngroups + 2;
break;
}
case 2: {
const u16 *ptr2 = buf;
int ngroups = len / groupsize;
for (j = 0; j < ngroups; j++)
lx += scnprintf(linebuf + lx, linebuflen - lx,
"%s%4.4x", j ? " " : "", *(ptr2 + j));
ascii_column = 5 * ngroups + 2;
break;
}
default:
for (j = 0; (j < len) && (lx + 3) <= linebuflen; j++) {
ch = ptr[j];
linebuf[lx++] = hex_asc_hi(ch);
linebuf[lx++] = hex_asc_lo(ch);
linebuf[lx++] = ' ';
}
if (j)
lx--;
ascii_column = 3 * rowsize + 2;
break;
}
if (!ascii)
goto nil;
while (lx < (linebuflen - 1) && lx < (ascii_column - 1))
linebuf[lx++] = ' ';
for (j = 0; (j < len) && (lx + 2) < linebuflen; j++) {
ch = ptr[j];
linebuf[lx++] = (isascii(ch) && isprint(ch)) ? ch : '.';
}
nil:
linebuf[lx++] = '\0';
}
EXPORT_SYMBOL(hex_dump_to_buffer);
#ifdef CONFIG_PRINTK
/**
* print_hex_dump - print a text hex dump to syslog for a binary blob of data
* @level: kernel log level (e.g. KERN_DEBUG)
* @prefix_str: string to prefix each line with;
* caller supplies trailing spaces for alignment if desired
* @prefix_type: controls whether prefix of an offset, address, or none
* is printed (%DUMP_PREFIX_OFFSET, %DUMP_PREFIX_ADDRESS, %DUMP_PREFIX_NONE)
* @rowsize: number of bytes to print per line; must be 16 or 32
* @groupsize: number of bytes to print at a time (1, 2, 4, 8; default = 1)
* @buf: data blob to dump
* @len: number of bytes in the @buf
* @ascii: include ASCII after the hex output
*
* Given a buffer of u8 data, print_hex_dump() prints a hex + ASCII dump
* to the kernel log at the specified kernel log level, with an optional
* leading prefix.
*
* print_hex_dump() works on one "line" of output at a time, i.e.,
* 16 or 32 bytes of input data converted to hex + ASCII output.
* print_hex_dump() iterates over the entire input @buf, breaking it into
* "line size" chunks to format and print.
*
* E.g.:
* print_hex_dump(KERN_DEBUG, "raw data: ", DUMP_PREFIX_ADDRESS,
* 16, 1, frame->data, frame->len, true);
*
* Example output using %DUMP_PREFIX_OFFSET and 1-byte mode:
* 0009ab42: 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f @ABCDEFGHIJKLMNO
* Example output using %DUMP_PREFIX_ADDRESS and 4-byte mode:
* ffffffff88089af0: 73727170 77767574 7b7a7978 7f7e7d7c pqrstuvwxyz{|}~.
*/
void print_hex_dump(const char *level, const char *prefix_str, int prefix_type,
int rowsize, int groupsize,
const void *buf, size_t len, bool ascii)
{
const u8 *ptr = buf;
int i, linelen, remaining = len;
unsigned char linebuf[32 * 3 + 2 + 32 + 1];
if (rowsize != 16 && rowsize != 32)
rowsize = 16;
for (i = 0; i < len; i += rowsize) {
linelen = min(remaining, rowsize);
remaining -= rowsize;
hex_dump_to_buffer(ptr + i, linelen, rowsize, groupsize,
linebuf, sizeof(linebuf), ascii);
switch (prefix_type) {
case DUMP_PREFIX_ADDRESS:
printk("%s%s%p: %s\n",
level, prefix_str, ptr + i, linebuf);
break;
case DUMP_PREFIX_OFFSET:
printk("%s%s%.8x: %s\n", level, prefix_str, i, linebuf);
break;
default:
printk("%s%s%s\n", level, prefix_str, linebuf);
break;
}
}
}
EXPORT_SYMBOL(print_hex_dump);
/**
* print_hex_dump_bytes - shorthand form of print_hex_dump() with default params
* @prefix_str: string to prefix each line with;
* caller supplies trailing spaces for alignment if desired
* @prefix_type: controls whether prefix of an offset, address, or none
* is printed (%DUMP_PREFIX_OFFSET, %DUMP_PREFIX_ADDRESS, %DUMP_PREFIX_NONE)
* @buf: data blob to dump
* @len: number of bytes in the @buf
*
* Calls print_hex_dump(), with log level of KERN_DEBUG,
* rowsize of 16, groupsize of 1, and ASCII output included.
*/
void print_hex_dump_bytes(const char *prefix_str, int prefix_type,
const void *buf, size_t len)
{
print_hex_dump(KERN_DEBUG, prefix_str, prefix_type, 16, 1,
buf, len, true);
}
EXPORT_SYMBOL(print_hex_dump_bytes);
#endif
| gpl-2.0 |
Biktorgj/kminilte_kernel | drivers/ata/pata_rz1000.c | 5502 | 4070 | /*
* RZ1000/1001 driver based upon
*
* linux/drivers/ide/pci/rz1000.c Version 0.06 January 12, 2003
* Copyright (C) 1995-1998 Linus Torvalds & author (see below)
* Principal Author: mlord@pobox.com (Mark Lord)
*
* See linux/MAINTAINERS for address of current maintainer.
*
* This file provides support for disabling the buggy read-ahead
* mode of the RZ1000 IDE chipset, commonly used on Intel motherboards.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "pata_rz1000"
#define DRV_VERSION "0.2.4"
/**
* rz1000_set_mode - mode setting function
* @link: ATA link
* @unused: returned device on set_mode failure
*
* Use a non standard set_mode function. We don't want to be tuned. We
* would prefer to be BIOS generic but for the fact our hardware is
* whacked out.
*/
static int rz1000_set_mode(struct ata_link *link, struct ata_device **unused)
{
struct ata_device *dev;
ata_for_each_dev(dev, link, ENABLED) {
/* We don't really care */
dev->pio_mode = XFER_PIO_0;
dev->xfer_mode = XFER_PIO_0;
dev->xfer_shift = ATA_SHIFT_PIO;
dev->flags |= ATA_DFLAG_PIO;
ata_dev_info(dev, "configured for PIO\n");
}
return 0;
}
static struct scsi_host_template rz1000_sht = {
ATA_PIO_SHT(DRV_NAME),
};
static struct ata_port_operations rz1000_port_ops = {
.inherits = &ata_sff_port_ops,
.cable_detect = ata_cable_40wire,
.set_mode = rz1000_set_mode,
};
static int rz1000_fifo_disable(struct pci_dev *pdev)
{
u16 reg;
/* Be exceptionally paranoid as we must be sure to apply the fix */
if (pci_read_config_word(pdev, 0x40, ®) != 0)
return -1;
reg &= 0xDFFF;
if (pci_write_config_word(pdev, 0x40, reg) != 0)
return -1;
printk(KERN_INFO DRV_NAME ": disabled chipset readahead.\n");
return 0;
}
/**
* rz1000_init_one - Register RZ1000 ATA PCI device with kernel services
* @pdev: PCI device to register
* @ent: Entry in rz1000_pci_tbl matching with @pdev
*
* Configure an RZ1000 interface. This doesn't require much special
* handling except that we *MUST* kill the chipset readahead or the
* user may experience data corruption.
*/
static int rz1000_init_one (struct pci_dev *pdev, const struct pci_device_id *ent)
{
static const struct ata_port_info info = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.port_ops = &rz1000_port_ops
};
const struct ata_port_info *ppi[] = { &info, NULL };
ata_print_version_once(&pdev->dev, DRV_VERSION);
if (rz1000_fifo_disable(pdev) == 0)
return ata_pci_sff_init_one(pdev, ppi, &rz1000_sht, NULL, 0);
printk(KERN_ERR DRV_NAME ": failed to disable read-ahead on chipset..\n");
/* Not safe to use so skip */
return -ENODEV;
}
#ifdef CONFIG_PM
static int rz1000_reinit_one(struct pci_dev *pdev)
{
struct ata_host *host = dev_get_drvdata(&pdev->dev);
int rc;
rc = ata_pci_device_do_resume(pdev);
if (rc)
return rc;
/* If this fails on resume (which is a "can't happen" case), we
must stop as any progress risks data loss */
if (rz1000_fifo_disable(pdev))
panic("rz1000 fifo");
ata_host_resume(host);
return 0;
}
#endif
static const struct pci_device_id pata_rz1000[] = {
{ PCI_VDEVICE(PCTECH, PCI_DEVICE_ID_PCTECH_RZ1000), },
{ PCI_VDEVICE(PCTECH, PCI_DEVICE_ID_PCTECH_RZ1001), },
{ },
};
static struct pci_driver rz1000_pci_driver = {
.name = DRV_NAME,
.id_table = pata_rz1000,
.probe = rz1000_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM
.suspend = ata_pci_device_suspend,
.resume = rz1000_reinit_one,
#endif
};
static int __init rz1000_init(void)
{
return pci_register_driver(&rz1000_pci_driver);
}
static void __exit rz1000_exit(void)
{
pci_unregister_driver(&rz1000_pci_driver);
}
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("low-level driver for RZ1000 PCI ATA");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, pata_rz1000);
MODULE_VERSION(DRV_VERSION);
module_init(rz1000_init);
module_exit(rz1000_exit);
| gpl-2.0 |
EnJens/android_kernel_sony_pollux_windy_stock | drivers/ata/pata_rz1000.c | 5502 | 4070 | /*
* RZ1000/1001 driver based upon
*
* linux/drivers/ide/pci/rz1000.c Version 0.06 January 12, 2003
* Copyright (C) 1995-1998 Linus Torvalds & author (see below)
* Principal Author: mlord@pobox.com (Mark Lord)
*
* See linux/MAINTAINERS for address of current maintainer.
*
* This file provides support for disabling the buggy read-ahead
* mode of the RZ1000 IDE chipset, commonly used on Intel motherboards.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "pata_rz1000"
#define DRV_VERSION "0.2.4"
/**
* rz1000_set_mode - mode setting function
* @link: ATA link
* @unused: returned device on set_mode failure
*
* Use a non standard set_mode function. We don't want to be tuned. We
* would prefer to be BIOS generic but for the fact our hardware is
* whacked out.
*/
static int rz1000_set_mode(struct ata_link *link, struct ata_device **unused)
{
struct ata_device *dev;
ata_for_each_dev(dev, link, ENABLED) {
/* We don't really care */
dev->pio_mode = XFER_PIO_0;
dev->xfer_mode = XFER_PIO_0;
dev->xfer_shift = ATA_SHIFT_PIO;
dev->flags |= ATA_DFLAG_PIO;
ata_dev_info(dev, "configured for PIO\n");
}
return 0;
}
static struct scsi_host_template rz1000_sht = {
ATA_PIO_SHT(DRV_NAME),
};
static struct ata_port_operations rz1000_port_ops = {
.inherits = &ata_sff_port_ops,
.cable_detect = ata_cable_40wire,
.set_mode = rz1000_set_mode,
};
static int rz1000_fifo_disable(struct pci_dev *pdev)
{
u16 reg;
/* Be exceptionally paranoid as we must be sure to apply the fix */
if (pci_read_config_word(pdev, 0x40, ®) != 0)
return -1;
reg &= 0xDFFF;
if (pci_write_config_word(pdev, 0x40, reg) != 0)
return -1;
printk(KERN_INFO DRV_NAME ": disabled chipset readahead.\n");
return 0;
}
/**
* rz1000_init_one - Register RZ1000 ATA PCI device with kernel services
* @pdev: PCI device to register
* @ent: Entry in rz1000_pci_tbl matching with @pdev
*
* Configure an RZ1000 interface. This doesn't require much special
* handling except that we *MUST* kill the chipset readahead or the
* user may experience data corruption.
*/
static int rz1000_init_one (struct pci_dev *pdev, const struct pci_device_id *ent)
{
static const struct ata_port_info info = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.port_ops = &rz1000_port_ops
};
const struct ata_port_info *ppi[] = { &info, NULL };
ata_print_version_once(&pdev->dev, DRV_VERSION);
if (rz1000_fifo_disable(pdev) == 0)
return ata_pci_sff_init_one(pdev, ppi, &rz1000_sht, NULL, 0);
printk(KERN_ERR DRV_NAME ": failed to disable read-ahead on chipset..\n");
/* Not safe to use so skip */
return -ENODEV;
}
#ifdef CONFIG_PM
static int rz1000_reinit_one(struct pci_dev *pdev)
{
struct ata_host *host = dev_get_drvdata(&pdev->dev);
int rc;
rc = ata_pci_device_do_resume(pdev);
if (rc)
return rc;
/* If this fails on resume (which is a "can't happen" case), we
must stop as any progress risks data loss */
if (rz1000_fifo_disable(pdev))
panic("rz1000 fifo");
ata_host_resume(host);
return 0;
}
#endif
static const struct pci_device_id pata_rz1000[] = {
{ PCI_VDEVICE(PCTECH, PCI_DEVICE_ID_PCTECH_RZ1000), },
{ PCI_VDEVICE(PCTECH, PCI_DEVICE_ID_PCTECH_RZ1001), },
{ },
};
static struct pci_driver rz1000_pci_driver = {
.name = DRV_NAME,
.id_table = pata_rz1000,
.probe = rz1000_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM
.suspend = ata_pci_device_suspend,
.resume = rz1000_reinit_one,
#endif
};
static int __init rz1000_init(void)
{
return pci_register_driver(&rz1000_pci_driver);
}
static void __exit rz1000_exit(void)
{
pci_unregister_driver(&rz1000_pci_driver);
}
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("low-level driver for RZ1000 PCI ATA");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, pata_rz1000);
MODULE_VERSION(DRV_VERSION);
module_init(rz1000_init);
module_exit(rz1000_exit);
| gpl-2.0 |
MasterAwesome/android_kernel_oneplus_msm8974 | drivers/ata/pata_opti.c | 5502 | 5528 | /*
* pata_opti.c - ATI PATA for new ATA layer
* (C) 2005 Red Hat Inc
*
* Based on
* linux/drivers/ide/pci/opti621.c Version 0.7 Sept 10, 2002
*
* Copyright (C) 1996-1998 Linus Torvalds & authors (see below)
*
* Authors:
* Jaromir Koutek <miri@punknet.cz>,
* Jan Harkes <jaharkes@cwi.nl>,
* Mark Lord <mlord@pobox.com>
* Some parts of code are from ali14xx.c and from rz1000.c.
*
* Also consulted the FreeBSD prototype driver by Kevin Day to try
* and resolve some confusions. Further documentation can be found in
* Ralf Brown's interrupt list
*
* If you have other variants of the Opti range (Viper/Vendetta) please
* try this driver with those PCI idents and report back. For the later
* chips see the pata_optidma driver
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "pata_opti"
#define DRV_VERSION "0.2.9"
enum {
READ_REG = 0, /* index of Read cycle timing register */
WRITE_REG = 1, /* index of Write cycle timing register */
CNTRL_REG = 3, /* index of Control register */
STRAP_REG = 5, /* index of Strap register */
MISC_REG = 6 /* index of Miscellaneous register */
};
/**
* opti_pre_reset - probe begin
* @link: ATA link
* @deadline: deadline jiffies for the operation
*
* Set up cable type and use generic probe init
*/
static int opti_pre_reset(struct ata_link *link, unsigned long deadline)
{
struct ata_port *ap = link->ap;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
static const struct pci_bits opti_enable_bits[] = {
{ 0x45, 1, 0x80, 0x00 },
{ 0x40, 1, 0x08, 0x00 }
};
if (!pci_test_config_bits(pdev, &opti_enable_bits[ap->port_no]))
return -ENOENT;
return ata_sff_prereset(link, deadline);
}
/**
* opti_write_reg - control register setup
* @ap: ATA port
* @value: value
* @reg: control register number
*
* The Opti uses magic 'trapdoor' register accesses to do configuration
* rather than using PCI space as other controllers do. The double inw
* on the error register activates configuration mode. We can then write
* the control register
*/
static void opti_write_reg(struct ata_port *ap, u8 val, int reg)
{
void __iomem *regio = ap->ioaddr.cmd_addr;
/* These 3 unlock the control register access */
ioread16(regio + 1);
ioread16(regio + 1);
iowrite8(3, regio + 2);
/* Do the I/O */
iowrite8(val, regio + reg);
/* Relock */
iowrite8(0x83, regio + 2);
}
/**
* opti_set_piomode - set initial PIO mode data
* @ap: ATA interface
* @adev: ATA device
*
* Called to do the PIO mode setup. Timing numbers are taken from
* the FreeBSD driver then pre computed to keep the code clean. There
* are two tables depending on the hardware clock speed.
*/
static void opti_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
struct ata_device *pair = ata_dev_pair(adev);
int clock;
int pio = adev->pio_mode - XFER_PIO_0;
void __iomem *regio = ap->ioaddr.cmd_addr;
u8 addr;
/* Address table precomputed with prefetch off and a DCLK of 2 */
static const u8 addr_timing[2][5] = {
{ 0x30, 0x20, 0x20, 0x10, 0x10 },
{ 0x20, 0x20, 0x10, 0x10, 0x10 }
};
static const u8 data_rec_timing[2][5] = {
{ 0x6B, 0x56, 0x42, 0x32, 0x31 },
{ 0x58, 0x44, 0x32, 0x22, 0x21 }
};
iowrite8(0xff, regio + 5);
clock = ioread16(regio + 5) & 1;
/*
* As with many controllers the address setup time is shared
* and must suit both devices if present.
*/
addr = addr_timing[clock][pio];
if (pair) {
/* Hardware constraint */
u8 pair_addr = addr_timing[clock][pair->pio_mode - XFER_PIO_0];
if (pair_addr > addr)
addr = pair_addr;
}
/* Commence primary programming sequence */
opti_write_reg(ap, adev->devno, MISC_REG);
opti_write_reg(ap, data_rec_timing[clock][pio], READ_REG);
opti_write_reg(ap, data_rec_timing[clock][pio], WRITE_REG);
opti_write_reg(ap, addr, MISC_REG);
/* Programming sequence complete, override strapping */
opti_write_reg(ap, 0x85, CNTRL_REG);
}
static struct scsi_host_template opti_sht = {
ATA_PIO_SHT(DRV_NAME),
};
static struct ata_port_operations opti_port_ops = {
.inherits = &ata_sff_port_ops,
.cable_detect = ata_cable_40wire,
.set_piomode = opti_set_piomode,
.prereset = opti_pre_reset,
};
static int opti_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
static const struct ata_port_info info = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.port_ops = &opti_port_ops
};
const struct ata_port_info *ppi[] = { &info, NULL };
ata_print_version_once(&dev->dev, DRV_VERSION);
return ata_pci_sff_init_one(dev, ppi, &opti_sht, NULL, 0);
}
static const struct pci_device_id opti[] = {
{ PCI_VDEVICE(OPTI, PCI_DEVICE_ID_OPTI_82C621), 0 },
{ PCI_VDEVICE(OPTI, PCI_DEVICE_ID_OPTI_82C825), 1 },
{ },
};
static struct pci_driver opti_pci_driver = {
.name = DRV_NAME,
.id_table = opti,
.probe = opti_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM
.suspend = ata_pci_device_suspend,
.resume = ata_pci_device_resume,
#endif
};
static int __init opti_init(void)
{
return pci_register_driver(&opti_pci_driver);
}
static void __exit opti_exit(void)
{
pci_unregister_driver(&opti_pci_driver);
}
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("low-level driver for Opti 621/621X");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, opti);
MODULE_VERSION(DRV_VERSION);
module_init(opti_init);
module_exit(opti_exit);
| gpl-2.0 |
danonbrown/trltetmo-kernel | drivers/ide/ide-ioctls.c | 7550 | 6861 | /*
* IDE ioctls handling.
*/
#include <linux/export.h>
#include <linux/hdreg.h>
#include <linux/ide.h>
#include <linux/slab.h>
static const struct ide_ioctl_devset ide_ioctl_settings[] = {
{ HDIO_GET_32BIT, HDIO_SET_32BIT, &ide_devset_io_32bit },
{ HDIO_GET_KEEPSETTINGS, HDIO_SET_KEEPSETTINGS, &ide_devset_keepsettings },
{ HDIO_GET_UNMASKINTR, HDIO_SET_UNMASKINTR, &ide_devset_unmaskirq },
{ HDIO_GET_DMA, HDIO_SET_DMA, &ide_devset_using_dma },
{ -1, HDIO_SET_PIO_MODE, &ide_devset_pio_mode },
{ 0 }
};
int ide_setting_ioctl(ide_drive_t *drive, struct block_device *bdev,
unsigned int cmd, unsigned long arg,
const struct ide_ioctl_devset *s)
{
const struct ide_devset *ds;
int err = -EOPNOTSUPP;
for (; (ds = s->setting); s++) {
if (ds->get && s->get_ioctl == cmd)
goto read_val;
else if (ds->set && s->set_ioctl == cmd)
goto set_val;
}
return err;
read_val:
mutex_lock(&ide_setting_mtx);
err = ds->get(drive);
mutex_unlock(&ide_setting_mtx);
return err >= 0 ? put_user(err, (long __user *)arg) : err;
set_val:
if (bdev != bdev->bd_contains)
err = -EINVAL;
else {
if (!capable(CAP_SYS_ADMIN))
err = -EACCES;
else {
mutex_lock(&ide_setting_mtx);
err = ide_devset_execute(drive, ds, arg);
mutex_unlock(&ide_setting_mtx);
}
}
return err;
}
EXPORT_SYMBOL_GPL(ide_setting_ioctl);
static int ide_get_identity_ioctl(ide_drive_t *drive, unsigned int cmd,
unsigned long arg)
{
u16 *id = NULL;
int size = (cmd == HDIO_GET_IDENTITY) ? (ATA_ID_WORDS * 2) : 142;
int rc = 0;
if ((drive->dev_flags & IDE_DFLAG_ID_READ) == 0) {
rc = -ENOMSG;
goto out;
}
/* ata_id_to_hd_driveid() relies on 'id' to be fully allocated. */
id = kmalloc(ATA_ID_WORDS * 2, GFP_KERNEL);
if (id == NULL) {
rc = -ENOMEM;
goto out;
}
memcpy(id, drive->id, size);
ata_id_to_hd_driveid(id);
if (copy_to_user((void __user *)arg, id, size))
rc = -EFAULT;
kfree(id);
out:
return rc;
}
static int ide_get_nice_ioctl(ide_drive_t *drive, unsigned long arg)
{
return put_user((!!(drive->dev_flags & IDE_DFLAG_DSC_OVERLAP)
<< IDE_NICE_DSC_OVERLAP) |
(!!(drive->dev_flags & IDE_DFLAG_NICE1)
<< IDE_NICE_1), (long __user *)arg);
}
static int ide_set_nice_ioctl(ide_drive_t *drive, unsigned long arg)
{
if (arg != (arg & ((1 << IDE_NICE_DSC_OVERLAP) | (1 << IDE_NICE_1))))
return -EPERM;
if (((arg >> IDE_NICE_DSC_OVERLAP) & 1) &&
(drive->media != ide_tape))
return -EPERM;
if ((arg >> IDE_NICE_DSC_OVERLAP) & 1)
drive->dev_flags |= IDE_DFLAG_DSC_OVERLAP;
else
drive->dev_flags &= ~IDE_DFLAG_DSC_OVERLAP;
if ((arg >> IDE_NICE_1) & 1)
drive->dev_flags |= IDE_DFLAG_NICE1;
else
drive->dev_flags &= ~IDE_DFLAG_NICE1;
return 0;
}
static int ide_cmd_ioctl(ide_drive_t *drive, unsigned long arg)
{
u8 *buf = NULL;
int bufsize = 0, err = 0;
u8 args[4], xfer_rate = 0;
struct ide_cmd cmd;
struct ide_taskfile *tf = &cmd.tf;
if (NULL == (void *) arg) {
struct request *rq;
rq = blk_get_request(drive->queue, READ, __GFP_WAIT);
rq->cmd_type = REQ_TYPE_ATA_TASKFILE;
err = blk_execute_rq(drive->queue, NULL, rq, 0);
blk_put_request(rq);
return err;
}
if (copy_from_user(args, (void __user *)arg, 4))
return -EFAULT;
memset(&cmd, 0, sizeof(cmd));
tf->feature = args[2];
if (args[0] == ATA_CMD_SMART) {
tf->nsect = args[3];
tf->lbal = args[1];
tf->lbam = 0x4f;
tf->lbah = 0xc2;
cmd.valid.out.tf = IDE_VALID_OUT_TF;
cmd.valid.in.tf = IDE_VALID_NSECT;
} else {
tf->nsect = args[1];
cmd.valid.out.tf = IDE_VALID_FEATURE | IDE_VALID_NSECT;
cmd.valid.in.tf = IDE_VALID_NSECT;
}
tf->command = args[0];
cmd.protocol = args[3] ? ATA_PROT_PIO : ATA_PROT_NODATA;
if (args[3]) {
cmd.tf_flags |= IDE_TFLAG_IO_16BIT;
bufsize = SECTOR_SIZE * args[3];
buf = kzalloc(bufsize, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
}
if (tf->command == ATA_CMD_SET_FEATURES &&
tf->feature == SETFEATURES_XFER &&
tf->nsect >= XFER_SW_DMA_0) {
xfer_rate = ide_find_dma_mode(drive, tf->nsect);
if (xfer_rate != tf->nsect) {
err = -EINVAL;
goto abort;
}
cmd.tf_flags |= IDE_TFLAG_SET_XFER;
}
err = ide_raw_taskfile(drive, &cmd, buf, args[3]);
args[0] = tf->status;
args[1] = tf->error;
args[2] = tf->nsect;
abort:
if (copy_to_user((void __user *)arg, &args, 4))
err = -EFAULT;
if (buf) {
if (copy_to_user((void __user *)(arg + 4), buf, bufsize))
err = -EFAULT;
kfree(buf);
}
return err;
}
static int ide_task_ioctl(ide_drive_t *drive, unsigned long arg)
{
void __user *p = (void __user *)arg;
int err = 0;
u8 args[7];
struct ide_cmd cmd;
if (copy_from_user(args, p, 7))
return -EFAULT;
memset(&cmd, 0, sizeof(cmd));
memcpy(&cmd.tf.feature, &args[1], 6);
cmd.tf.command = args[0];
cmd.valid.out.tf = IDE_VALID_OUT_TF | IDE_VALID_DEVICE;
cmd.valid.in.tf = IDE_VALID_IN_TF | IDE_VALID_DEVICE;
err = ide_no_data_taskfile(drive, &cmd);
args[0] = cmd.tf.command;
memcpy(&args[1], &cmd.tf.feature, 6);
if (copy_to_user(p, args, 7))
err = -EFAULT;
return err;
}
static int generic_drive_reset(ide_drive_t *drive)
{
struct request *rq;
int ret = 0;
rq = blk_get_request(drive->queue, READ, __GFP_WAIT);
rq->cmd_type = REQ_TYPE_SPECIAL;
rq->cmd_len = 1;
rq->cmd[0] = REQ_DRIVE_RESET;
if (blk_execute_rq(drive->queue, NULL, rq, 1))
ret = rq->errors;
blk_put_request(rq);
return ret;
}
int generic_ide_ioctl(ide_drive_t *drive, struct block_device *bdev,
unsigned int cmd, unsigned long arg)
{
int err;
err = ide_setting_ioctl(drive, bdev, cmd, arg, ide_ioctl_settings);
if (err != -EOPNOTSUPP)
return err;
switch (cmd) {
case HDIO_OBSOLETE_IDENTITY:
case HDIO_GET_IDENTITY:
if (bdev != bdev->bd_contains)
return -EINVAL;
return ide_get_identity_ioctl(drive, cmd, arg);
case HDIO_GET_NICE:
return ide_get_nice_ioctl(drive, arg);
case HDIO_SET_NICE:
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
return ide_set_nice_ioctl(drive, arg);
#ifdef CONFIG_IDE_TASK_IOCTL
case HDIO_DRIVE_TASKFILE:
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
return -EACCES;
if (drive->media == ide_disk)
return ide_taskfile_ioctl(drive, arg);
return -ENOMSG;
#endif
case HDIO_DRIVE_CMD:
if (!capable(CAP_SYS_RAWIO))
return -EACCES;
return ide_cmd_ioctl(drive, arg);
case HDIO_DRIVE_TASK:
if (!capable(CAP_SYS_RAWIO))
return -EACCES;
return ide_task_ioctl(drive, arg);
case HDIO_DRIVE_RESET:
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
return generic_drive_reset(drive);
case HDIO_GET_BUSSTATE:
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
if (put_user(BUSSTATE_ON, (long __user *)arg))
return -EFAULT;
return 0;
case HDIO_SET_BUSSTATE:
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
return -EOPNOTSUPP;
default:
return -EINVAL;
}
}
EXPORT_SYMBOL(generic_ide_ioctl);
| gpl-2.0 |
davidmueller13/g3_kernel | drivers/ide/ide-ioctls.c | 7550 | 6861 | /*
* IDE ioctls handling.
*/
#include <linux/export.h>
#include <linux/hdreg.h>
#include <linux/ide.h>
#include <linux/slab.h>
static const struct ide_ioctl_devset ide_ioctl_settings[] = {
{ HDIO_GET_32BIT, HDIO_SET_32BIT, &ide_devset_io_32bit },
{ HDIO_GET_KEEPSETTINGS, HDIO_SET_KEEPSETTINGS, &ide_devset_keepsettings },
{ HDIO_GET_UNMASKINTR, HDIO_SET_UNMASKINTR, &ide_devset_unmaskirq },
{ HDIO_GET_DMA, HDIO_SET_DMA, &ide_devset_using_dma },
{ -1, HDIO_SET_PIO_MODE, &ide_devset_pio_mode },
{ 0 }
};
int ide_setting_ioctl(ide_drive_t *drive, struct block_device *bdev,
unsigned int cmd, unsigned long arg,
const struct ide_ioctl_devset *s)
{
const struct ide_devset *ds;
int err = -EOPNOTSUPP;
for (; (ds = s->setting); s++) {
if (ds->get && s->get_ioctl == cmd)
goto read_val;
else if (ds->set && s->set_ioctl == cmd)
goto set_val;
}
return err;
read_val:
mutex_lock(&ide_setting_mtx);
err = ds->get(drive);
mutex_unlock(&ide_setting_mtx);
return err >= 0 ? put_user(err, (long __user *)arg) : err;
set_val:
if (bdev != bdev->bd_contains)
err = -EINVAL;
else {
if (!capable(CAP_SYS_ADMIN))
err = -EACCES;
else {
mutex_lock(&ide_setting_mtx);
err = ide_devset_execute(drive, ds, arg);
mutex_unlock(&ide_setting_mtx);
}
}
return err;
}
EXPORT_SYMBOL_GPL(ide_setting_ioctl);
static int ide_get_identity_ioctl(ide_drive_t *drive, unsigned int cmd,
unsigned long arg)
{
u16 *id = NULL;
int size = (cmd == HDIO_GET_IDENTITY) ? (ATA_ID_WORDS * 2) : 142;
int rc = 0;
if ((drive->dev_flags & IDE_DFLAG_ID_READ) == 0) {
rc = -ENOMSG;
goto out;
}
/* ata_id_to_hd_driveid() relies on 'id' to be fully allocated. */
id = kmalloc(ATA_ID_WORDS * 2, GFP_KERNEL);
if (id == NULL) {
rc = -ENOMEM;
goto out;
}
memcpy(id, drive->id, size);
ata_id_to_hd_driveid(id);
if (copy_to_user((void __user *)arg, id, size))
rc = -EFAULT;
kfree(id);
out:
return rc;
}
static int ide_get_nice_ioctl(ide_drive_t *drive, unsigned long arg)
{
return put_user((!!(drive->dev_flags & IDE_DFLAG_DSC_OVERLAP)
<< IDE_NICE_DSC_OVERLAP) |
(!!(drive->dev_flags & IDE_DFLAG_NICE1)
<< IDE_NICE_1), (long __user *)arg);
}
static int ide_set_nice_ioctl(ide_drive_t *drive, unsigned long arg)
{
if (arg != (arg & ((1 << IDE_NICE_DSC_OVERLAP) | (1 << IDE_NICE_1))))
return -EPERM;
if (((arg >> IDE_NICE_DSC_OVERLAP) & 1) &&
(drive->media != ide_tape))
return -EPERM;
if ((arg >> IDE_NICE_DSC_OVERLAP) & 1)
drive->dev_flags |= IDE_DFLAG_DSC_OVERLAP;
else
drive->dev_flags &= ~IDE_DFLAG_DSC_OVERLAP;
if ((arg >> IDE_NICE_1) & 1)
drive->dev_flags |= IDE_DFLAG_NICE1;
else
drive->dev_flags &= ~IDE_DFLAG_NICE1;
return 0;
}
static int ide_cmd_ioctl(ide_drive_t *drive, unsigned long arg)
{
u8 *buf = NULL;
int bufsize = 0, err = 0;
u8 args[4], xfer_rate = 0;
struct ide_cmd cmd;
struct ide_taskfile *tf = &cmd.tf;
if (NULL == (void *) arg) {
struct request *rq;
rq = blk_get_request(drive->queue, READ, __GFP_WAIT);
rq->cmd_type = REQ_TYPE_ATA_TASKFILE;
err = blk_execute_rq(drive->queue, NULL, rq, 0);
blk_put_request(rq);
return err;
}
if (copy_from_user(args, (void __user *)arg, 4))
return -EFAULT;
memset(&cmd, 0, sizeof(cmd));
tf->feature = args[2];
if (args[0] == ATA_CMD_SMART) {
tf->nsect = args[3];
tf->lbal = args[1];
tf->lbam = 0x4f;
tf->lbah = 0xc2;
cmd.valid.out.tf = IDE_VALID_OUT_TF;
cmd.valid.in.tf = IDE_VALID_NSECT;
} else {
tf->nsect = args[1];
cmd.valid.out.tf = IDE_VALID_FEATURE | IDE_VALID_NSECT;
cmd.valid.in.tf = IDE_VALID_NSECT;
}
tf->command = args[0];
cmd.protocol = args[3] ? ATA_PROT_PIO : ATA_PROT_NODATA;
if (args[3]) {
cmd.tf_flags |= IDE_TFLAG_IO_16BIT;
bufsize = SECTOR_SIZE * args[3];
buf = kzalloc(bufsize, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
}
if (tf->command == ATA_CMD_SET_FEATURES &&
tf->feature == SETFEATURES_XFER &&
tf->nsect >= XFER_SW_DMA_0) {
xfer_rate = ide_find_dma_mode(drive, tf->nsect);
if (xfer_rate != tf->nsect) {
err = -EINVAL;
goto abort;
}
cmd.tf_flags |= IDE_TFLAG_SET_XFER;
}
err = ide_raw_taskfile(drive, &cmd, buf, args[3]);
args[0] = tf->status;
args[1] = tf->error;
args[2] = tf->nsect;
abort:
if (copy_to_user((void __user *)arg, &args, 4))
err = -EFAULT;
if (buf) {
if (copy_to_user((void __user *)(arg + 4), buf, bufsize))
err = -EFAULT;
kfree(buf);
}
return err;
}
static int ide_task_ioctl(ide_drive_t *drive, unsigned long arg)
{
void __user *p = (void __user *)arg;
int err = 0;
u8 args[7];
struct ide_cmd cmd;
if (copy_from_user(args, p, 7))
return -EFAULT;
memset(&cmd, 0, sizeof(cmd));
memcpy(&cmd.tf.feature, &args[1], 6);
cmd.tf.command = args[0];
cmd.valid.out.tf = IDE_VALID_OUT_TF | IDE_VALID_DEVICE;
cmd.valid.in.tf = IDE_VALID_IN_TF | IDE_VALID_DEVICE;
err = ide_no_data_taskfile(drive, &cmd);
args[0] = cmd.tf.command;
memcpy(&args[1], &cmd.tf.feature, 6);
if (copy_to_user(p, args, 7))
err = -EFAULT;
return err;
}
static int generic_drive_reset(ide_drive_t *drive)
{
struct request *rq;
int ret = 0;
rq = blk_get_request(drive->queue, READ, __GFP_WAIT);
rq->cmd_type = REQ_TYPE_SPECIAL;
rq->cmd_len = 1;
rq->cmd[0] = REQ_DRIVE_RESET;
if (blk_execute_rq(drive->queue, NULL, rq, 1))
ret = rq->errors;
blk_put_request(rq);
return ret;
}
int generic_ide_ioctl(ide_drive_t *drive, struct block_device *bdev,
unsigned int cmd, unsigned long arg)
{
int err;
err = ide_setting_ioctl(drive, bdev, cmd, arg, ide_ioctl_settings);
if (err != -EOPNOTSUPP)
return err;
switch (cmd) {
case HDIO_OBSOLETE_IDENTITY:
case HDIO_GET_IDENTITY:
if (bdev != bdev->bd_contains)
return -EINVAL;
return ide_get_identity_ioctl(drive, cmd, arg);
case HDIO_GET_NICE:
return ide_get_nice_ioctl(drive, arg);
case HDIO_SET_NICE:
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
return ide_set_nice_ioctl(drive, arg);
#ifdef CONFIG_IDE_TASK_IOCTL
case HDIO_DRIVE_TASKFILE:
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
return -EACCES;
if (drive->media == ide_disk)
return ide_taskfile_ioctl(drive, arg);
return -ENOMSG;
#endif
case HDIO_DRIVE_CMD:
if (!capable(CAP_SYS_RAWIO))
return -EACCES;
return ide_cmd_ioctl(drive, arg);
case HDIO_DRIVE_TASK:
if (!capable(CAP_SYS_RAWIO))
return -EACCES;
return ide_task_ioctl(drive, arg);
case HDIO_DRIVE_RESET:
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
return generic_drive_reset(drive);
case HDIO_GET_BUSSTATE:
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
if (put_user(BUSSTATE_ON, (long __user *)arg))
return -EFAULT;
return 0;
case HDIO_SET_BUSSTATE:
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
return -EOPNOTSUPP;
default:
return -EINVAL;
}
}
EXPORT_SYMBOL(generic_ide_ioctl);
| gpl-2.0 |
DevSwift/Kernel-3.4-U8500 | arch/powerpc/platforms/pseries/scanlog.c | 7806 | 5568 | /*
* c 2001 PPC 64 Team, IBM Corp
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* scan-log-data driver for PPC64 Todd Inglett <tinglett@vnet.ibm.com>
*
* When ppc64 hardware fails the service processor dumps internal state
* of the system. After a reboot the operating system can access a dump
* of this data using this driver. A dump exists if the device-tree
* /chosen/ibm,scan-log-data property exists.
*
* This driver exports /proc/powerpc/scan-log-dump which can be read.
* The driver supports only sequential reads.
*
* The driver looks at a write to the driver for the single word "reset".
* If given, the driver will reset the scanlog so the platform can free it.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/proc_fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <asm/rtas.h>
#include <asm/prom.h>
#define MODULE_VERS "1.0"
#define MODULE_NAME "scanlog"
/* Status returns from ibm,scan-log-dump */
#define SCANLOG_COMPLETE 0
#define SCANLOG_HWERROR -1
#define SCANLOG_CONTINUE 1
static unsigned int ibm_scan_log_dump; /* RTAS token */
static struct proc_dir_entry *proc_ppc64_scan_log_dump; /* The proc file */
static ssize_t scanlog_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file->f_path.dentry->d_inode;
struct proc_dir_entry *dp;
unsigned int *data;
int status;
unsigned long len, off;
unsigned int wait_time;
dp = PDE(inode);
data = (unsigned int *)dp->data;
if (count > RTAS_DATA_BUF_SIZE)
count = RTAS_DATA_BUF_SIZE;
if (count < 1024) {
/* This is the min supported by this RTAS call. Rather
* than do all the buffering we insist the user code handle
* larger reads. As long as cp works... :)
*/
printk(KERN_ERR "scanlog: cannot perform a small read (%ld)\n", count);
return -EINVAL;
}
if (!access_ok(VERIFY_WRITE, buf, count))
return -EFAULT;
for (;;) {
wait_time = 500; /* default wait if no data */
spin_lock(&rtas_data_buf_lock);
memcpy(rtas_data_buf, data, RTAS_DATA_BUF_SIZE);
status = rtas_call(ibm_scan_log_dump, 2, 1, NULL,
(u32) __pa(rtas_data_buf), (u32) count);
memcpy(data, rtas_data_buf, RTAS_DATA_BUF_SIZE);
spin_unlock(&rtas_data_buf_lock);
pr_debug("scanlog: status=%d, data[0]=%x, data[1]=%x, " \
"data[2]=%x\n", status, data[0], data[1], data[2]);
switch (status) {
case SCANLOG_COMPLETE:
pr_debug("scanlog: hit eof\n");
return 0;
case SCANLOG_HWERROR:
pr_debug("scanlog: hardware error reading data\n");
return -EIO;
case SCANLOG_CONTINUE:
/* We may or may not have data yet */
len = data[1];
off = data[2];
if (len > 0) {
if (copy_to_user(buf, ((char *)data)+off, len))
return -EFAULT;
return len;
}
/* Break to sleep default time */
break;
default:
/* Assume extended busy */
wait_time = rtas_busy_delay_time(status);
if (!wait_time) {
printk(KERN_ERR "scanlog: unknown error " \
"from rtas: %d\n", status);
return -EIO;
}
}
/* Apparently no data yet. Wait and try again. */
msleep_interruptible(wait_time);
}
/*NOTREACHED*/
}
static ssize_t scanlog_write(struct file * file, const char __user * buf,
size_t count, loff_t *ppos)
{
char stkbuf[20];
int status;
if (count > 19) count = 19;
if (copy_from_user (stkbuf, buf, count)) {
return -EFAULT;
}
stkbuf[count] = 0;
if (buf) {
if (strncmp(stkbuf, "reset", 5) == 0) {
pr_debug("scanlog: reset scanlog\n");
status = rtas_call(ibm_scan_log_dump, 2, 1, NULL, 0, 0);
pr_debug("scanlog: rtas returns %d\n", status);
}
}
return count;
}
static int scanlog_open(struct inode * inode, struct file * file)
{
struct proc_dir_entry *dp = PDE(inode);
unsigned int *data = (unsigned int *)dp->data;
if (data[0] != 0) {
/* This imperfect test stops a second copy of the
* data (or a reset while data is being copied)
*/
return -EBUSY;
}
data[0] = 0; /* re-init so we restart the scan */
return 0;
}
static int scanlog_release(struct inode * inode, struct file * file)
{
struct proc_dir_entry *dp = PDE(inode);
unsigned int *data = (unsigned int *)dp->data;
data[0] = 0;
return 0;
}
const struct file_operations scanlog_fops = {
.owner = THIS_MODULE,
.read = scanlog_read,
.write = scanlog_write,
.open = scanlog_open,
.release = scanlog_release,
.llseek = noop_llseek,
};
static int __init scanlog_init(void)
{
struct proc_dir_entry *ent;
void *data;
int err = -ENOMEM;
ibm_scan_log_dump = rtas_token("ibm,scan-log-dump");
if (ibm_scan_log_dump == RTAS_UNKNOWN_SERVICE)
return -ENODEV;
/* Ideally we could allocate a buffer < 4G */
data = kzalloc(RTAS_DATA_BUF_SIZE, GFP_KERNEL);
if (!data)
goto err;
ent = proc_create_data("powerpc/rtas/scan-log-dump", S_IRUSR, NULL,
&scanlog_fops, data);
if (!ent)
goto err;
proc_ppc64_scan_log_dump = ent;
return 0;
err:
kfree(data);
return err;
}
static void __exit scanlog_cleanup(void)
{
if (proc_ppc64_scan_log_dump) {
kfree(proc_ppc64_scan_log_dump->data);
remove_proc_entry("scan-log-dump", proc_ppc64_scan_log_dump->parent);
}
}
module_init(scanlog_init);
module_exit(scanlog_cleanup);
MODULE_LICENSE("GPL");
| gpl-2.0 |
manumanfred/kernel_tegra | arch/powerpc/platforms/pseries/scanlog.c | 7806 | 5568 | /*
* c 2001 PPC 64 Team, IBM Corp
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* scan-log-data driver for PPC64 Todd Inglett <tinglett@vnet.ibm.com>
*
* When ppc64 hardware fails the service processor dumps internal state
* of the system. After a reboot the operating system can access a dump
* of this data using this driver. A dump exists if the device-tree
* /chosen/ibm,scan-log-data property exists.
*
* This driver exports /proc/powerpc/scan-log-dump which can be read.
* The driver supports only sequential reads.
*
* The driver looks at a write to the driver for the single word "reset".
* If given, the driver will reset the scanlog so the platform can free it.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/proc_fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <asm/rtas.h>
#include <asm/prom.h>
#define MODULE_VERS "1.0"
#define MODULE_NAME "scanlog"
/* Status returns from ibm,scan-log-dump */
#define SCANLOG_COMPLETE 0
#define SCANLOG_HWERROR -1
#define SCANLOG_CONTINUE 1
static unsigned int ibm_scan_log_dump; /* RTAS token */
static struct proc_dir_entry *proc_ppc64_scan_log_dump; /* The proc file */
static ssize_t scanlog_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file->f_path.dentry->d_inode;
struct proc_dir_entry *dp;
unsigned int *data;
int status;
unsigned long len, off;
unsigned int wait_time;
dp = PDE(inode);
data = (unsigned int *)dp->data;
if (count > RTAS_DATA_BUF_SIZE)
count = RTAS_DATA_BUF_SIZE;
if (count < 1024) {
/* This is the min supported by this RTAS call. Rather
* than do all the buffering we insist the user code handle
* larger reads. As long as cp works... :)
*/
printk(KERN_ERR "scanlog: cannot perform a small read (%ld)\n", count);
return -EINVAL;
}
if (!access_ok(VERIFY_WRITE, buf, count))
return -EFAULT;
for (;;) {
wait_time = 500; /* default wait if no data */
spin_lock(&rtas_data_buf_lock);
memcpy(rtas_data_buf, data, RTAS_DATA_BUF_SIZE);
status = rtas_call(ibm_scan_log_dump, 2, 1, NULL,
(u32) __pa(rtas_data_buf), (u32) count);
memcpy(data, rtas_data_buf, RTAS_DATA_BUF_SIZE);
spin_unlock(&rtas_data_buf_lock);
pr_debug("scanlog: status=%d, data[0]=%x, data[1]=%x, " \
"data[2]=%x\n", status, data[0], data[1], data[2]);
switch (status) {
case SCANLOG_COMPLETE:
pr_debug("scanlog: hit eof\n");
return 0;
case SCANLOG_HWERROR:
pr_debug("scanlog: hardware error reading data\n");
return -EIO;
case SCANLOG_CONTINUE:
/* We may or may not have data yet */
len = data[1];
off = data[2];
if (len > 0) {
if (copy_to_user(buf, ((char *)data)+off, len))
return -EFAULT;
return len;
}
/* Break to sleep default time */
break;
default:
/* Assume extended busy */
wait_time = rtas_busy_delay_time(status);
if (!wait_time) {
printk(KERN_ERR "scanlog: unknown error " \
"from rtas: %d\n", status);
return -EIO;
}
}
/* Apparently no data yet. Wait and try again. */
msleep_interruptible(wait_time);
}
/*NOTREACHED*/
}
static ssize_t scanlog_write(struct file * file, const char __user * buf,
size_t count, loff_t *ppos)
{
char stkbuf[20];
int status;
if (count > 19) count = 19;
if (copy_from_user (stkbuf, buf, count)) {
return -EFAULT;
}
stkbuf[count] = 0;
if (buf) {
if (strncmp(stkbuf, "reset", 5) == 0) {
pr_debug("scanlog: reset scanlog\n");
status = rtas_call(ibm_scan_log_dump, 2, 1, NULL, 0, 0);
pr_debug("scanlog: rtas returns %d\n", status);
}
}
return count;
}
static int scanlog_open(struct inode * inode, struct file * file)
{
struct proc_dir_entry *dp = PDE(inode);
unsigned int *data = (unsigned int *)dp->data;
if (data[0] != 0) {
/* This imperfect test stops a second copy of the
* data (or a reset while data is being copied)
*/
return -EBUSY;
}
data[0] = 0; /* re-init so we restart the scan */
return 0;
}
static int scanlog_release(struct inode * inode, struct file * file)
{
struct proc_dir_entry *dp = PDE(inode);
unsigned int *data = (unsigned int *)dp->data;
data[0] = 0;
return 0;
}
const struct file_operations scanlog_fops = {
.owner = THIS_MODULE,
.read = scanlog_read,
.write = scanlog_write,
.open = scanlog_open,
.release = scanlog_release,
.llseek = noop_llseek,
};
static int __init scanlog_init(void)
{
struct proc_dir_entry *ent;
void *data;
int err = -ENOMEM;
ibm_scan_log_dump = rtas_token("ibm,scan-log-dump");
if (ibm_scan_log_dump == RTAS_UNKNOWN_SERVICE)
return -ENODEV;
/* Ideally we could allocate a buffer < 4G */
data = kzalloc(RTAS_DATA_BUF_SIZE, GFP_KERNEL);
if (!data)
goto err;
ent = proc_create_data("powerpc/rtas/scan-log-dump", S_IRUSR, NULL,
&scanlog_fops, data);
if (!ent)
goto err;
proc_ppc64_scan_log_dump = ent;
return 0;
err:
kfree(data);
return err;
}
static void __exit scanlog_cleanup(void)
{
if (proc_ppc64_scan_log_dump) {
kfree(proc_ppc64_scan_log_dump->data);
remove_proc_entry("scan-log-dump", proc_ppc64_scan_log_dump->parent);
}
}
module_init(scanlog_init);
module_exit(scanlog_cleanup);
MODULE_LICENSE("GPL");
| gpl-2.0 |
drsn0w/android_kernel_lge_bullhead | arch/mips/math-emu/sp_tint.c | 10366 | 3031 | /* IEEE754 floating point arithmetic
* single precision
*/
/*
* MIPS floating point support
* Copyright (C) 1994-2000 Algorithmics Ltd.
*
* ########################################################################
*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*
* ########################################################################
*/
#include <linux/kernel.h>
#include "ieee754sp.h"
int ieee754sp_tint(ieee754sp x)
{
COMPXSP;
CLEARCX;
EXPLODEXSP;
FLUSHXSP;
switch (xc) {
case IEEE754_CLASS_SNAN:
case IEEE754_CLASS_QNAN:
case IEEE754_CLASS_INF:
SETCX(IEEE754_INVALID_OPERATION);
return ieee754si_xcpt(ieee754si_indef(), "sp_tint", x);
case IEEE754_CLASS_ZERO:
return 0;
case IEEE754_CLASS_DNORM:
case IEEE754_CLASS_NORM:
break;
}
if (xe >= 31) {
/* look for valid corner case */
if (xe == 31 && xs && xm == SP_HIDDEN_BIT)
return -0x80000000;
/* Set invalid. We will only use overflow for floating
point overflow */
SETCX(IEEE754_INVALID_OPERATION);
return ieee754si_xcpt(ieee754si_indef(), "sp_tint", x);
}
/* oh gawd */
if (xe > SP_MBITS) {
xm <<= xe - SP_MBITS;
} else {
u32 residue;
int round;
int sticky;
int odd;
if (xe < -1) {
residue = xm;
round = 0;
sticky = residue != 0;
xm = 0;
} else {
/* Shifting a u32 32 times does not work,
* so we do it in two steps. Be aware that xe
* may be -1 */
residue = xm << (xe + 1);
residue <<= 31 - SP_MBITS;
round = (residue >> 31) != 0;
sticky = (residue << 1) != 0;
xm >>= SP_MBITS - xe;
}
odd = (xm & 0x1) != 0x0;
switch (ieee754_csr.rm) {
case IEEE754_RN:
if (round && (sticky || odd))
xm++;
break;
case IEEE754_RZ:
break;
case IEEE754_RU: /* toward +Infinity */
if ((round || sticky) && !xs)
xm++;
break;
case IEEE754_RD: /* toward -Infinity */
if ((round || sticky) && xs)
xm++;
break;
}
if ((xm >> 31) != 0) {
/* This can happen after rounding */
SETCX(IEEE754_INVALID_OPERATION);
return ieee754si_xcpt(ieee754si_indef(), "sp_tint", x);
}
if (round || sticky)
SETCX(IEEE754_INEXACT);
}
if (xs)
return -xm;
else
return xm;
}
unsigned int ieee754sp_tuns(ieee754sp x)
{
ieee754sp hb = ieee754sp_1e31();
/* what if x < 0 ?? */
if (ieee754sp_lt(x, hb))
return (unsigned) ieee754sp_tint(x);
return (unsigned) ieee754sp_tint(ieee754sp_sub(x, hb)) |
((unsigned) 1 << 31);
}
| gpl-2.0 |
PrestigeMod/Seine | arch/x86/kernel/io_delay.c | 13950 | 3047 | /*
* I/O delay strategies for inb_p/outb_p
*
* Allow for a DMI based override of port 0x80, needed for certain HP laptops
* and possibly other systems. Also allow for the gradual elimination of
* outb_p/inb_p API uses.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/dmi.h>
#include <linux/io.h>
int io_delay_type __read_mostly = CONFIG_DEFAULT_IO_DELAY_TYPE;
static int __initdata io_delay_override;
/*
* Paravirt wants native_io_delay to be a constant.
*/
void native_io_delay(void)
{
switch (io_delay_type) {
default:
case CONFIG_IO_DELAY_TYPE_0X80:
asm volatile ("outb %al, $0x80");
break;
case CONFIG_IO_DELAY_TYPE_0XED:
asm volatile ("outb %al, $0xed");
break;
case CONFIG_IO_DELAY_TYPE_UDELAY:
/*
* 2 usecs is an upper-bound for the outb delay but
* note that udelay doesn't have the bus-level
* side-effects that outb does, nor does udelay() have
* precise timings during very early bootup (the delays
* are shorter until calibrated):
*/
udelay(2);
case CONFIG_IO_DELAY_TYPE_NONE:
break;
}
}
EXPORT_SYMBOL(native_io_delay);
static int __init dmi_io_delay_0xed_port(const struct dmi_system_id *id)
{
if (io_delay_type == CONFIG_IO_DELAY_TYPE_0X80) {
pr_notice("%s: using 0xed I/O delay port\n", id->ident);
io_delay_type = CONFIG_IO_DELAY_TYPE_0XED;
}
return 0;
}
/*
* Quirk table for systems that misbehave (lock up, etc.) if port
* 0x80 is used:
*/
static struct dmi_system_id __initdata io_delay_0xed_port_dmi_table[] = {
{
.callback = dmi_io_delay_0xed_port,
.ident = "Compaq Presario V6000",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Quanta"),
DMI_MATCH(DMI_BOARD_NAME, "30B7")
}
},
{
.callback = dmi_io_delay_0xed_port,
.ident = "HP Pavilion dv9000z",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Quanta"),
DMI_MATCH(DMI_BOARD_NAME, "30B9")
}
},
{
.callback = dmi_io_delay_0xed_port,
.ident = "HP Pavilion dv6000",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Quanta"),
DMI_MATCH(DMI_BOARD_NAME, "30B8")
}
},
{
.callback = dmi_io_delay_0xed_port,
.ident = "HP Pavilion tx1000",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Quanta"),
DMI_MATCH(DMI_BOARD_NAME, "30BF")
}
},
{
.callback = dmi_io_delay_0xed_port,
.ident = "Presario F700",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Quanta"),
DMI_MATCH(DMI_BOARD_NAME, "30D3")
}
},
{ }
};
void __init io_delay_init(void)
{
if (!io_delay_override)
dmi_check_system(io_delay_0xed_port_dmi_table);
}
static int __init io_delay_param(char *s)
{
if (!s)
return -EINVAL;
if (!strcmp(s, "0x80"))
io_delay_type = CONFIG_IO_DELAY_TYPE_0X80;
else if (!strcmp(s, "0xed"))
io_delay_type = CONFIG_IO_DELAY_TYPE_0XED;
else if (!strcmp(s, "udelay"))
io_delay_type = CONFIG_IO_DELAY_TYPE_UDELAY;
else if (!strcmp(s, "none"))
io_delay_type = CONFIG_IO_DELAY_TYPE_NONE;
else
return -EINVAL;
io_delay_override = 1;
return 0;
}
early_param("io_delay", io_delay_param);
| gpl-2.0 |
embecosm/gcc | gcc/testsuite/gcc.dg/tree-ssa/cswtch.c | 127 | 1038 | /* { dg-do compile } */
/* { dg-options "-O2 -fdump-tree-switchconv" } */
/* { dg-do run } */
extern void abort (void);
static int X, Y;
int check(int param)
{
int a = 0;
int b = 1;
switch (param)
{
case -2:
a = 0;
b = -1;
break;
case 1:
case 2:
a = 8;
b = 6;
break;
case 3:
a = 9;
b = 5;
break;
case 6:
a = 10;
b = 4;
break;
default:
a = 16;
b = 1;
}
X = a;
Y = b;
return 0;
}
void assertions(int a, int b)
{
if (X != a || Y != b)
abort();
return;
}
int main ()
{
check (-10);
assertions (16, 1);
check (-2);
assertions (0, -1);
check(1);
assertions (8, 6);
check(2);
assertions (8, 6);
check(3);
assertions (9, 5);
check(5);
assertions (16, 1);
check(6);
assertions (10, 4);
check(12);
assertions (16, 1);
return 0;
}
/* { dg-final { scan-tree-dump "Switch converted" "switchconv" } } */
/* { dg-final { cleanup-tree-dump "switchconv" } } */
| gpl-2.0 |
nekromant/linux-rlx-upstream | drivers/tty/serial/crisv10.c | 127 | 128250 | /*
* Serial port driver for the ETRAX 100LX chip
*
* Copyright (C) 1998-2007 Axis Communications AB
*
* Many, many authors. Based once upon a time on serial.c for 16x50.
*
*/
static char *serial_version = "$Revision: 1.25 $";
#include <linux/types.h>
#include <linux/errno.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/mm.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/mutex.h>
#include <linux/bitops.h>
#include <linux/seq_file.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <asm/irq.h>
#include <asm/dma.h>
#include <arch/svinto.h>
#include <arch/system.h>
/* non-arch dependent serial structures are in linux/serial.h */
#include <linux/serial.h>
/* while we keep our own stuff (struct e100_serial) in a local .h file */
#include "crisv10.h"
#include <asm/fasttimer.h>
#include <arch/io_interface_mux.h>
#ifdef CONFIG_ETRAX_SERIAL_FAST_TIMER
#ifndef CONFIG_ETRAX_FAST_TIMER
#error "Enable FAST_TIMER to use SERIAL_FAST_TIMER"
#endif
#endif
#if defined(CONFIG_ETRAX_SERIAL_RX_TIMEOUT_TICKS) && \
(CONFIG_ETRAX_SERIAL_RX_TIMEOUT_TICKS == 0)
#error "RX_TIMEOUT_TICKS == 0 not allowed, use 1"
#endif
#if defined(CONFIG_ETRAX_RS485_ON_PA) && defined(CONFIG_ETRAX_RS485_ON_PORT_G)
#error "Disable either CONFIG_ETRAX_RS485_ON_PA or CONFIG_ETRAX_RS485_ON_PORT_G"
#endif
/*
* All of the compatibilty code so we can compile serial.c against
* older kernels is hidden in serial_compat.h
*/
#if defined(LOCAL_HEADERS)
#include "serial_compat.h"
#endif
struct tty_driver *serial_driver;
/* number of characters left in xmit buffer before we ask for more */
#define WAKEUP_CHARS 256
//#define SERIAL_DEBUG_INTR
//#define SERIAL_DEBUG_OPEN
//#define SERIAL_DEBUG_FLOW
//#define SERIAL_DEBUG_DATA
//#define SERIAL_DEBUG_THROTTLE
//#define SERIAL_DEBUG_IO /* Debug for Extra control and status pins */
//#define SERIAL_DEBUG_LINE 0 /* What serport we want to debug */
/* Enable this to use serial interrupts to handle when you
expect the first received event on the serial port to
be an error, break or similar. Used to be able to flash IRMA
from eLinux */
#define SERIAL_HANDLE_EARLY_ERRORS
/* Currently 16 descriptors x 128 bytes = 2048 bytes */
#define SERIAL_DESCR_BUF_SIZE 256
#define SERIAL_PRESCALE_BASE 3125000 /* 3.125MHz */
#define DEF_BAUD_BASE SERIAL_PRESCALE_BASE
/* We don't want to load the system with massive fast timer interrupt
* on high baudrates so limit it to 250 us (4kHz) */
#define MIN_FLUSH_TIME_USEC 250
/* Add an x here to log a lot of timer stuff */
#define TIMERD(x)
/* Debug details of interrupt handling */
#define DINTR1(x) /* irq on/off, errors */
#define DINTR2(x) /* tx and rx */
/* Debug flip buffer stuff */
#define DFLIP(x)
/* Debug flow control and overview of data flow */
#define DFLOW(x)
#define DBAUD(x)
#define DLOG_INT_TRIG(x)
//#define DEBUG_LOG_INCLUDED
#ifndef DEBUG_LOG_INCLUDED
#define DEBUG_LOG(line, string, value)
#else
struct debug_log_info
{
unsigned long time;
unsigned long timer_data;
// int line;
const char *string;
int value;
};
#define DEBUG_LOG_SIZE 4096
struct debug_log_info debug_log[DEBUG_LOG_SIZE];
int debug_log_pos = 0;
#define DEBUG_LOG(_line, _string, _value) do { \
if ((_line) == SERIAL_DEBUG_LINE) {\
debug_log_func(_line, _string, _value); \
}\
}while(0)
void debug_log_func(int line, const char *string, int value)
{
if (debug_log_pos < DEBUG_LOG_SIZE) {
debug_log[debug_log_pos].time = jiffies;
debug_log[debug_log_pos].timer_data = *R_TIMER_DATA;
// debug_log[debug_log_pos].line = line;
debug_log[debug_log_pos].string = string;
debug_log[debug_log_pos].value = value;
debug_log_pos++;
}
/*printk(string, value);*/
}
#endif
#ifndef CONFIG_ETRAX_SERIAL_RX_TIMEOUT_TICKS
/* Default number of timer ticks before flushing rx fifo
* When using "little data, low latency applications: use 0
* When using "much data applications (PPP)" use ~5
*/
#define CONFIG_ETRAX_SERIAL_RX_TIMEOUT_TICKS 5
#endif
unsigned long timer_data_to_ns(unsigned long timer_data);
static void change_speed(struct e100_serial *info);
static void rs_throttle(struct tty_struct * tty);
static void rs_wait_until_sent(struct tty_struct *tty, int timeout);
static int rs_write(struct tty_struct *tty,
const unsigned char *buf, int count);
#ifdef CONFIG_ETRAX_RS485
static int e100_write_rs485(struct tty_struct *tty,
const unsigned char *buf, int count);
#endif
static int get_lsr_info(struct e100_serial *info, unsigned int *value);
#define DEF_BAUD 115200 /* 115.2 kbit/s */
#define STD_FLAGS (ASYNC_BOOT_AUTOCONF | ASYNC_SKIP_TEST)
#define DEF_RX 0x20 /* or SERIAL_CTRL_W >> 8 */
/* Default value of tx_ctrl register: has txd(bit 7)=1 (idle) as default */
#define DEF_TX 0x80 /* or SERIAL_CTRL_B */
/* offsets from R_SERIALx_CTRL */
#define REG_DATA 0
#define REG_DATA_STATUS32 0 /* this is the 32 bit register R_SERIALx_READ */
#define REG_TR_DATA 0
#define REG_STATUS 1
#define REG_TR_CTRL 1
#define REG_REC_CTRL 2
#define REG_BAUD 3
#define REG_XOFF 4 /* this is a 32 bit register */
/* The bitfields are the same for all serial ports */
#define SER_RXD_MASK IO_MASK(R_SERIAL0_STATUS, rxd)
#define SER_DATA_AVAIL_MASK IO_MASK(R_SERIAL0_STATUS, data_avail)
#define SER_FRAMING_ERR_MASK IO_MASK(R_SERIAL0_STATUS, framing_err)
#define SER_PAR_ERR_MASK IO_MASK(R_SERIAL0_STATUS, par_err)
#define SER_OVERRUN_MASK IO_MASK(R_SERIAL0_STATUS, overrun)
#define SER_ERROR_MASK (SER_OVERRUN_MASK | SER_PAR_ERR_MASK | SER_FRAMING_ERR_MASK)
/* Values for info->errorcode */
#define ERRCODE_SET_BREAK (TTY_BREAK)
#define ERRCODE_INSERT 0x100
#define ERRCODE_INSERT_BREAK (ERRCODE_INSERT | TTY_BREAK)
#define FORCE_EOP(info) *R_SET_EOP = 1U << info->iseteop;
/*
* General note regarding the use of IO_* macros in this file:
*
* We will use the bits defined for DMA channel 6 when using various
* IO_* macros (e.g. IO_STATE, IO_MASK, IO_EXTRACT) and _assume_ they are
* the same for all channels (which of course they are).
*
* We will also use the bits defined for serial port 0 when writing commands
* to the different ports, as these bits too are the same for all ports.
*/
/* Mask for the irqs possibly enabled in R_IRQ_MASK1_RD etc. */
static const unsigned long e100_ser_int_mask = 0
#ifdef CONFIG_ETRAX_SERIAL_PORT0
| IO_MASK(R_IRQ_MASK1_RD, ser0_data) | IO_MASK(R_IRQ_MASK1_RD, ser0_ready)
#endif
#ifdef CONFIG_ETRAX_SERIAL_PORT1
| IO_MASK(R_IRQ_MASK1_RD, ser1_data) | IO_MASK(R_IRQ_MASK1_RD, ser1_ready)
#endif
#ifdef CONFIG_ETRAX_SERIAL_PORT2
| IO_MASK(R_IRQ_MASK1_RD, ser2_data) | IO_MASK(R_IRQ_MASK1_RD, ser2_ready)
#endif
#ifdef CONFIG_ETRAX_SERIAL_PORT3
| IO_MASK(R_IRQ_MASK1_RD, ser3_data) | IO_MASK(R_IRQ_MASK1_RD, ser3_ready)
#endif
;
unsigned long r_alt_ser_baudrate_shadow = 0;
/* this is the data for the four serial ports in the etrax100 */
/* DMA2(ser2), DMA4(ser3), DMA6(ser0) or DMA8(ser1) */
/* R_DMA_CHx_CLR_INTR, R_DMA_CHx_FIRST, R_DMA_CHx_CMD */
static struct e100_serial rs_table[] = {
{ .baud = DEF_BAUD,
.ioport = (unsigned char *)R_SERIAL0_CTRL,
.irq = 1U << 12, /* uses DMA 6 and 7 */
.oclrintradr = R_DMA_CH6_CLR_INTR,
.ofirstadr = R_DMA_CH6_FIRST,
.ocmdadr = R_DMA_CH6_CMD,
.ostatusadr = R_DMA_CH6_STATUS,
.iclrintradr = R_DMA_CH7_CLR_INTR,
.ifirstadr = R_DMA_CH7_FIRST,
.icmdadr = R_DMA_CH7_CMD,
.idescradr = R_DMA_CH7_DESCR,
.flags = STD_FLAGS,
.rx_ctrl = DEF_RX,
.tx_ctrl = DEF_TX,
.iseteop = 2,
.dma_owner = dma_ser0,
.io_if = if_serial_0,
#ifdef CONFIG_ETRAX_SERIAL_PORT0
.enabled = 1,
#ifdef CONFIG_ETRAX_SERIAL_PORT0_DMA6_OUT
.dma_out_enabled = 1,
.dma_out_nbr = SER0_TX_DMA_NBR,
.dma_out_irq_nbr = SER0_DMA_TX_IRQ_NBR,
.dma_out_irq_flags = 0,
.dma_out_irq_description = "serial 0 dma tr",
#else
.dma_out_enabled = 0,
.dma_out_nbr = UINT_MAX,
.dma_out_irq_nbr = 0,
.dma_out_irq_flags = 0,
.dma_out_irq_description = NULL,
#endif
#ifdef CONFIG_ETRAX_SERIAL_PORT0_DMA7_IN
.dma_in_enabled = 1,
.dma_in_nbr = SER0_RX_DMA_NBR,
.dma_in_irq_nbr = SER0_DMA_RX_IRQ_NBR,
.dma_in_irq_flags = 0,
.dma_in_irq_description = "serial 0 dma rec",
#else
.dma_in_enabled = 0,
.dma_in_nbr = UINT_MAX,
.dma_in_irq_nbr = 0,
.dma_in_irq_flags = 0,
.dma_in_irq_description = NULL,
#endif
#else
.enabled = 0,
.io_if_description = NULL,
.dma_out_enabled = 0,
.dma_in_enabled = 0
#endif
}, /* ttyS0 */
#ifndef CONFIG_SVINTO_SIM
{ .baud = DEF_BAUD,
.ioport = (unsigned char *)R_SERIAL1_CTRL,
.irq = 1U << 16, /* uses DMA 8 and 9 */
.oclrintradr = R_DMA_CH8_CLR_INTR,
.ofirstadr = R_DMA_CH8_FIRST,
.ocmdadr = R_DMA_CH8_CMD,
.ostatusadr = R_DMA_CH8_STATUS,
.iclrintradr = R_DMA_CH9_CLR_INTR,
.ifirstadr = R_DMA_CH9_FIRST,
.icmdadr = R_DMA_CH9_CMD,
.idescradr = R_DMA_CH9_DESCR,
.flags = STD_FLAGS,
.rx_ctrl = DEF_RX,
.tx_ctrl = DEF_TX,
.iseteop = 3,
.dma_owner = dma_ser1,
.io_if = if_serial_1,
#ifdef CONFIG_ETRAX_SERIAL_PORT1
.enabled = 1,
.io_if_description = "ser1",
#ifdef CONFIG_ETRAX_SERIAL_PORT1_DMA8_OUT
.dma_out_enabled = 1,
.dma_out_nbr = SER1_TX_DMA_NBR,
.dma_out_irq_nbr = SER1_DMA_TX_IRQ_NBR,
.dma_out_irq_flags = 0,
.dma_out_irq_description = "serial 1 dma tr",
#else
.dma_out_enabled = 0,
.dma_out_nbr = UINT_MAX,
.dma_out_irq_nbr = 0,
.dma_out_irq_flags = 0,
.dma_out_irq_description = NULL,
#endif
#ifdef CONFIG_ETRAX_SERIAL_PORT1_DMA9_IN
.dma_in_enabled = 1,
.dma_in_nbr = SER1_RX_DMA_NBR,
.dma_in_irq_nbr = SER1_DMA_RX_IRQ_NBR,
.dma_in_irq_flags = 0,
.dma_in_irq_description = "serial 1 dma rec",
#else
.dma_in_enabled = 0,
.dma_in_enabled = 0,
.dma_in_nbr = UINT_MAX,
.dma_in_irq_nbr = 0,
.dma_in_irq_flags = 0,
.dma_in_irq_description = NULL,
#endif
#else
.enabled = 0,
.io_if_description = NULL,
.dma_in_irq_nbr = 0,
.dma_out_enabled = 0,
.dma_in_enabled = 0
#endif
}, /* ttyS1 */
{ .baud = DEF_BAUD,
.ioport = (unsigned char *)R_SERIAL2_CTRL,
.irq = 1U << 4, /* uses DMA 2 and 3 */
.oclrintradr = R_DMA_CH2_CLR_INTR,
.ofirstadr = R_DMA_CH2_FIRST,
.ocmdadr = R_DMA_CH2_CMD,
.ostatusadr = R_DMA_CH2_STATUS,
.iclrintradr = R_DMA_CH3_CLR_INTR,
.ifirstadr = R_DMA_CH3_FIRST,
.icmdadr = R_DMA_CH3_CMD,
.idescradr = R_DMA_CH3_DESCR,
.flags = STD_FLAGS,
.rx_ctrl = DEF_RX,
.tx_ctrl = DEF_TX,
.iseteop = 0,
.dma_owner = dma_ser2,
.io_if = if_serial_2,
#ifdef CONFIG_ETRAX_SERIAL_PORT2
.enabled = 1,
.io_if_description = "ser2",
#ifdef CONFIG_ETRAX_SERIAL_PORT2_DMA2_OUT
.dma_out_enabled = 1,
.dma_out_nbr = SER2_TX_DMA_NBR,
.dma_out_irq_nbr = SER2_DMA_TX_IRQ_NBR,
.dma_out_irq_flags = 0,
.dma_out_irq_description = "serial 2 dma tr",
#else
.dma_out_enabled = 0,
.dma_out_nbr = UINT_MAX,
.dma_out_irq_nbr = 0,
.dma_out_irq_flags = 0,
.dma_out_irq_description = NULL,
#endif
#ifdef CONFIG_ETRAX_SERIAL_PORT2_DMA3_IN
.dma_in_enabled = 1,
.dma_in_nbr = SER2_RX_DMA_NBR,
.dma_in_irq_nbr = SER2_DMA_RX_IRQ_NBR,
.dma_in_irq_flags = 0,
.dma_in_irq_description = "serial 2 dma rec",
#else
.dma_in_enabled = 0,
.dma_in_nbr = UINT_MAX,
.dma_in_irq_nbr = 0,
.dma_in_irq_flags = 0,
.dma_in_irq_description = NULL,
#endif
#else
.enabled = 0,
.io_if_description = NULL,
.dma_out_enabled = 0,
.dma_in_enabled = 0
#endif
}, /* ttyS2 */
{ .baud = DEF_BAUD,
.ioport = (unsigned char *)R_SERIAL3_CTRL,
.irq = 1U << 8, /* uses DMA 4 and 5 */
.oclrintradr = R_DMA_CH4_CLR_INTR,
.ofirstadr = R_DMA_CH4_FIRST,
.ocmdadr = R_DMA_CH4_CMD,
.ostatusadr = R_DMA_CH4_STATUS,
.iclrintradr = R_DMA_CH5_CLR_INTR,
.ifirstadr = R_DMA_CH5_FIRST,
.icmdadr = R_DMA_CH5_CMD,
.idescradr = R_DMA_CH5_DESCR,
.flags = STD_FLAGS,
.rx_ctrl = DEF_RX,
.tx_ctrl = DEF_TX,
.iseteop = 1,
.dma_owner = dma_ser3,
.io_if = if_serial_3,
#ifdef CONFIG_ETRAX_SERIAL_PORT3
.enabled = 1,
.io_if_description = "ser3",
#ifdef CONFIG_ETRAX_SERIAL_PORT3_DMA4_OUT
.dma_out_enabled = 1,
.dma_out_nbr = SER3_TX_DMA_NBR,
.dma_out_irq_nbr = SER3_DMA_TX_IRQ_NBR,
.dma_out_irq_flags = 0,
.dma_out_irq_description = "serial 3 dma tr",
#else
.dma_out_enabled = 0,
.dma_out_nbr = UINT_MAX,
.dma_out_irq_nbr = 0,
.dma_out_irq_flags = 0,
.dma_out_irq_description = NULL,
#endif
#ifdef CONFIG_ETRAX_SERIAL_PORT3_DMA5_IN
.dma_in_enabled = 1,
.dma_in_nbr = SER3_RX_DMA_NBR,
.dma_in_irq_nbr = SER3_DMA_RX_IRQ_NBR,
.dma_in_irq_flags = 0,
.dma_in_irq_description = "serial 3 dma rec",
#else
.dma_in_enabled = 0,
.dma_in_nbr = UINT_MAX,
.dma_in_irq_nbr = 0,
.dma_in_irq_flags = 0,
.dma_in_irq_description = NULL
#endif
#else
.enabled = 0,
.io_if_description = NULL,
.dma_out_enabled = 0,
.dma_in_enabled = 0
#endif
} /* ttyS3 */
#endif
};
#define NR_PORTS (sizeof(rs_table)/sizeof(struct e100_serial))
#ifdef CONFIG_ETRAX_SERIAL_FAST_TIMER
static struct fast_timer fast_timers[NR_PORTS];
#endif
#ifdef CONFIG_ETRAX_SERIAL_PROC_ENTRY
#define PROCSTAT(x) x
struct ser_statistics_type {
int overrun_cnt;
int early_errors_cnt;
int ser_ints_ok_cnt;
int errors_cnt;
unsigned long int processing_flip;
unsigned long processing_flip_still_room;
unsigned long int timeout_flush_cnt;
int rx_dma_ints;
int tx_dma_ints;
int rx_tot;
int tx_tot;
};
static struct ser_statistics_type ser_stat[NR_PORTS];
#else
#define PROCSTAT(x)
#endif /* CONFIG_ETRAX_SERIAL_PROC_ENTRY */
/* RS-485 */
#if defined(CONFIG_ETRAX_RS485)
#ifdef CONFIG_ETRAX_FAST_TIMER
static struct fast_timer fast_timers_rs485[NR_PORTS];
#endif
#if defined(CONFIG_ETRAX_RS485_ON_PA)
static int rs485_pa_bit = CONFIG_ETRAX_RS485_ON_PA_BIT;
#endif
#if defined(CONFIG_ETRAX_RS485_ON_PORT_G)
static int rs485_port_g_bit = CONFIG_ETRAX_RS485_ON_PORT_G_BIT;
#endif
#endif
/* Info and macros needed for each ports extra control/status signals. */
#define E100_STRUCT_PORT(line, pinname) \
((CONFIG_ETRAX_SER##line##_##pinname##_ON_PA_BIT >= 0)? \
(R_PORT_PA_DATA): ( \
(CONFIG_ETRAX_SER##line##_##pinname##_ON_PB_BIT >= 0)? \
(R_PORT_PB_DATA):&dummy_ser[line]))
#define E100_STRUCT_SHADOW(line, pinname) \
((CONFIG_ETRAX_SER##line##_##pinname##_ON_PA_BIT >= 0)? \
(&port_pa_data_shadow): ( \
(CONFIG_ETRAX_SER##line##_##pinname##_ON_PB_BIT >= 0)? \
(&port_pb_data_shadow):&dummy_ser[line]))
#define E100_STRUCT_MASK(line, pinname) \
((CONFIG_ETRAX_SER##line##_##pinname##_ON_PA_BIT >= 0)? \
(1<<CONFIG_ETRAX_SER##line##_##pinname##_ON_PA_BIT): ( \
(CONFIG_ETRAX_SER##line##_##pinname##_ON_PB_BIT >= 0)? \
(1<<CONFIG_ETRAX_SER##line##_##pinname##_ON_PB_BIT):DUMMY_##pinname##_MASK))
#define DUMMY_DTR_MASK 1
#define DUMMY_RI_MASK 2
#define DUMMY_DSR_MASK 4
#define DUMMY_CD_MASK 8
static unsigned char dummy_ser[NR_PORTS] = {0xFF, 0xFF, 0xFF,0xFF};
/* If not all status pins are used or disabled, use mixed mode */
#ifdef CONFIG_ETRAX_SERIAL_PORT0
#define SER0_PA_BITSUM (CONFIG_ETRAX_SER0_DTR_ON_PA_BIT+CONFIG_ETRAX_SER0_RI_ON_PA_BIT+CONFIG_ETRAX_SER0_DSR_ON_PA_BIT+CONFIG_ETRAX_SER0_CD_ON_PA_BIT)
#if SER0_PA_BITSUM != -4
# if CONFIG_ETRAX_SER0_DTR_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER0_RI_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER0_DSR_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER0_CD_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
#endif
#define SER0_PB_BITSUM (CONFIG_ETRAX_SER0_DTR_ON_PB_BIT+CONFIG_ETRAX_SER0_RI_ON_PB_BIT+CONFIG_ETRAX_SER0_DSR_ON_PB_BIT+CONFIG_ETRAX_SER0_CD_ON_PB_BIT)
#if SER0_PB_BITSUM != -4
# if CONFIG_ETRAX_SER0_DTR_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER0_RI_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER0_DSR_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER0_CD_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
#endif
#endif /* PORT0 */
#ifdef CONFIG_ETRAX_SERIAL_PORT1
#define SER1_PA_BITSUM (CONFIG_ETRAX_SER1_DTR_ON_PA_BIT+CONFIG_ETRAX_SER1_RI_ON_PA_BIT+CONFIG_ETRAX_SER1_DSR_ON_PA_BIT+CONFIG_ETRAX_SER1_CD_ON_PA_BIT)
#if SER1_PA_BITSUM != -4
# if CONFIG_ETRAX_SER1_DTR_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER1_RI_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER1_DSR_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER1_CD_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
#endif
#define SER1_PB_BITSUM (CONFIG_ETRAX_SER1_DTR_ON_PB_BIT+CONFIG_ETRAX_SER1_RI_ON_PB_BIT+CONFIG_ETRAX_SER1_DSR_ON_PB_BIT+CONFIG_ETRAX_SER1_CD_ON_PB_BIT)
#if SER1_PB_BITSUM != -4
# if CONFIG_ETRAX_SER1_DTR_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER1_RI_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER1_DSR_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER1_CD_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
#endif
#endif /* PORT1 */
#ifdef CONFIG_ETRAX_SERIAL_PORT2
#define SER2_PA_BITSUM (CONFIG_ETRAX_SER2_DTR_ON_PA_BIT+CONFIG_ETRAX_SER2_RI_ON_PA_BIT+CONFIG_ETRAX_SER2_DSR_ON_PA_BIT+CONFIG_ETRAX_SER2_CD_ON_PA_BIT)
#if SER2_PA_BITSUM != -4
# if CONFIG_ETRAX_SER2_DTR_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER2_RI_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER2_DSR_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER2_CD_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
#endif
#define SER2_PB_BITSUM (CONFIG_ETRAX_SER2_DTR_ON_PB_BIT+CONFIG_ETRAX_SER2_RI_ON_PB_BIT+CONFIG_ETRAX_SER2_DSR_ON_PB_BIT+CONFIG_ETRAX_SER2_CD_ON_PB_BIT)
#if SER2_PB_BITSUM != -4
# if CONFIG_ETRAX_SER2_DTR_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER2_RI_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER2_DSR_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER2_CD_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
#endif
#endif /* PORT2 */
#ifdef CONFIG_ETRAX_SERIAL_PORT3
#define SER3_PA_BITSUM (CONFIG_ETRAX_SER3_DTR_ON_PA_BIT+CONFIG_ETRAX_SER3_RI_ON_PA_BIT+CONFIG_ETRAX_SER3_DSR_ON_PA_BIT+CONFIG_ETRAX_SER3_CD_ON_PA_BIT)
#if SER3_PA_BITSUM != -4
# if CONFIG_ETRAX_SER3_DTR_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER3_RI_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER3_DSR_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER3_CD_ON_PA_BIT == -1
# ifndef CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
#endif
#define SER3_PB_BITSUM (CONFIG_ETRAX_SER3_DTR_ON_PB_BIT+CONFIG_ETRAX_SER3_RI_ON_PB_BIT+CONFIG_ETRAX_SER3_DSR_ON_PB_BIT+CONFIG_ETRAX_SER3_CD_ON_PB_BIT)
#if SER3_PB_BITSUM != -4
# if CONFIG_ETRAX_SER3_DTR_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER3_RI_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER3_DSR_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
# if CONFIG_ETRAX_SER3_CD_ON_PB_BIT == -1
# ifndef CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED
# define CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED 1
# endif
# endif
#endif
#endif /* PORT3 */
#if defined(CONFIG_ETRAX_SER0_DTR_RI_DSR_CD_MIXED) || \
defined(CONFIG_ETRAX_SER1_DTR_RI_DSR_CD_MIXED) || \
defined(CONFIG_ETRAX_SER2_DTR_RI_DSR_CD_MIXED) || \
defined(CONFIG_ETRAX_SER3_DTR_RI_DSR_CD_MIXED)
#define CONFIG_ETRAX_SERX_DTR_RI_DSR_CD_MIXED
#endif
#ifdef CONFIG_ETRAX_SERX_DTR_RI_DSR_CD_MIXED
/* The pins can be mixed on PA and PB */
#define CONTROL_PINS_PORT_NOT_USED(line) \
&dummy_ser[line], &dummy_ser[line], \
&dummy_ser[line], &dummy_ser[line], \
&dummy_ser[line], &dummy_ser[line], \
&dummy_ser[line], &dummy_ser[line], \
DUMMY_DTR_MASK, DUMMY_RI_MASK, DUMMY_DSR_MASK, DUMMY_CD_MASK
struct control_pins
{
volatile unsigned char *dtr_port;
unsigned char *dtr_shadow;
volatile unsigned char *ri_port;
unsigned char *ri_shadow;
volatile unsigned char *dsr_port;
unsigned char *dsr_shadow;
volatile unsigned char *cd_port;
unsigned char *cd_shadow;
unsigned char dtr_mask;
unsigned char ri_mask;
unsigned char dsr_mask;
unsigned char cd_mask;
};
static const struct control_pins e100_modem_pins[NR_PORTS] =
{
/* Ser 0 */
{
#ifdef CONFIG_ETRAX_SERIAL_PORT0
E100_STRUCT_PORT(0,DTR), E100_STRUCT_SHADOW(0,DTR),
E100_STRUCT_PORT(0,RI), E100_STRUCT_SHADOW(0,RI),
E100_STRUCT_PORT(0,DSR), E100_STRUCT_SHADOW(0,DSR),
E100_STRUCT_PORT(0,CD), E100_STRUCT_SHADOW(0,CD),
E100_STRUCT_MASK(0,DTR),
E100_STRUCT_MASK(0,RI),
E100_STRUCT_MASK(0,DSR),
E100_STRUCT_MASK(0,CD)
#else
CONTROL_PINS_PORT_NOT_USED(0)
#endif
},
/* Ser 1 */
{
#ifdef CONFIG_ETRAX_SERIAL_PORT1
E100_STRUCT_PORT(1,DTR), E100_STRUCT_SHADOW(1,DTR),
E100_STRUCT_PORT(1,RI), E100_STRUCT_SHADOW(1,RI),
E100_STRUCT_PORT(1,DSR), E100_STRUCT_SHADOW(1,DSR),
E100_STRUCT_PORT(1,CD), E100_STRUCT_SHADOW(1,CD),
E100_STRUCT_MASK(1,DTR),
E100_STRUCT_MASK(1,RI),
E100_STRUCT_MASK(1,DSR),
E100_STRUCT_MASK(1,CD)
#else
CONTROL_PINS_PORT_NOT_USED(1)
#endif
},
/* Ser 2 */
{
#ifdef CONFIG_ETRAX_SERIAL_PORT2
E100_STRUCT_PORT(2,DTR), E100_STRUCT_SHADOW(2,DTR),
E100_STRUCT_PORT(2,RI), E100_STRUCT_SHADOW(2,RI),
E100_STRUCT_PORT(2,DSR), E100_STRUCT_SHADOW(2,DSR),
E100_STRUCT_PORT(2,CD), E100_STRUCT_SHADOW(2,CD),
E100_STRUCT_MASK(2,DTR),
E100_STRUCT_MASK(2,RI),
E100_STRUCT_MASK(2,DSR),
E100_STRUCT_MASK(2,CD)
#else
CONTROL_PINS_PORT_NOT_USED(2)
#endif
},
/* Ser 3 */
{
#ifdef CONFIG_ETRAX_SERIAL_PORT3
E100_STRUCT_PORT(3,DTR), E100_STRUCT_SHADOW(3,DTR),
E100_STRUCT_PORT(3,RI), E100_STRUCT_SHADOW(3,RI),
E100_STRUCT_PORT(3,DSR), E100_STRUCT_SHADOW(3,DSR),
E100_STRUCT_PORT(3,CD), E100_STRUCT_SHADOW(3,CD),
E100_STRUCT_MASK(3,DTR),
E100_STRUCT_MASK(3,RI),
E100_STRUCT_MASK(3,DSR),
E100_STRUCT_MASK(3,CD)
#else
CONTROL_PINS_PORT_NOT_USED(3)
#endif
}
};
#else /* CONFIG_ETRAX_SERX_DTR_RI_DSR_CD_MIXED */
/* All pins are on either PA or PB for each serial port */
#define CONTROL_PINS_PORT_NOT_USED(line) \
&dummy_ser[line], &dummy_ser[line], \
DUMMY_DTR_MASK, DUMMY_RI_MASK, DUMMY_DSR_MASK, DUMMY_CD_MASK
struct control_pins
{
volatile unsigned char *port;
unsigned char *shadow;
unsigned char dtr_mask;
unsigned char ri_mask;
unsigned char dsr_mask;
unsigned char cd_mask;
};
#define dtr_port port
#define dtr_shadow shadow
#define ri_port port
#define ri_shadow shadow
#define dsr_port port
#define dsr_shadow shadow
#define cd_port port
#define cd_shadow shadow
static const struct control_pins e100_modem_pins[NR_PORTS] =
{
/* Ser 0 */
{
#ifdef CONFIG_ETRAX_SERIAL_PORT0
E100_STRUCT_PORT(0,DTR), E100_STRUCT_SHADOW(0,DTR),
E100_STRUCT_MASK(0,DTR),
E100_STRUCT_MASK(0,RI),
E100_STRUCT_MASK(0,DSR),
E100_STRUCT_MASK(0,CD)
#else
CONTROL_PINS_PORT_NOT_USED(0)
#endif
},
/* Ser 1 */
{
#ifdef CONFIG_ETRAX_SERIAL_PORT1
E100_STRUCT_PORT(1,DTR), E100_STRUCT_SHADOW(1,DTR),
E100_STRUCT_MASK(1,DTR),
E100_STRUCT_MASK(1,RI),
E100_STRUCT_MASK(1,DSR),
E100_STRUCT_MASK(1,CD)
#else
CONTROL_PINS_PORT_NOT_USED(1)
#endif
},
/* Ser 2 */
{
#ifdef CONFIG_ETRAX_SERIAL_PORT2
E100_STRUCT_PORT(2,DTR), E100_STRUCT_SHADOW(2,DTR),
E100_STRUCT_MASK(2,DTR),
E100_STRUCT_MASK(2,RI),
E100_STRUCT_MASK(2,DSR),
E100_STRUCT_MASK(2,CD)
#else
CONTROL_PINS_PORT_NOT_USED(2)
#endif
},
/* Ser 3 */
{
#ifdef CONFIG_ETRAX_SERIAL_PORT3
E100_STRUCT_PORT(3,DTR), E100_STRUCT_SHADOW(3,DTR),
E100_STRUCT_MASK(3,DTR),
E100_STRUCT_MASK(3,RI),
E100_STRUCT_MASK(3,DSR),
E100_STRUCT_MASK(3,CD)
#else
CONTROL_PINS_PORT_NOT_USED(3)
#endif
}
};
#endif /* !CONFIG_ETRAX_SERX_DTR_RI_DSR_CD_MIXED */
#define E100_RTS_MASK 0x20
#define E100_CTS_MASK 0x40
/* All serial port signals are active low:
* active = 0 -> 3.3V to RS-232 driver -> -12V on RS-232 level
* inactive = 1 -> 0V to RS-232 driver -> +12V on RS-232 level
*
* These macros returns the pin value: 0=0V, >=1 = 3.3V on ETRAX chip
*/
/* Output */
#define E100_RTS_GET(info) ((info)->rx_ctrl & E100_RTS_MASK)
/* Input */
#define E100_CTS_GET(info) ((info)->ioport[REG_STATUS] & E100_CTS_MASK)
/* These are typically PA or PB and 0 means 0V, 1 means 3.3V */
/* Is an output */
#define E100_DTR_GET(info) ((*e100_modem_pins[(info)->line].dtr_shadow) & e100_modem_pins[(info)->line].dtr_mask)
/* Normally inputs */
#define E100_RI_GET(info) ((*e100_modem_pins[(info)->line].ri_port) & e100_modem_pins[(info)->line].ri_mask)
#define E100_CD_GET(info) ((*e100_modem_pins[(info)->line].cd_port) & e100_modem_pins[(info)->line].cd_mask)
/* Input */
#define E100_DSR_GET(info) ((*e100_modem_pins[(info)->line].dsr_port) & e100_modem_pins[(info)->line].dsr_mask)
/* Calculate the chartime depending on baudrate, numbor of bits etc. */
static void update_char_time(struct e100_serial * info)
{
tcflag_t cflags = info->port.tty->termios->c_cflag;
int bits;
/* calc. number of bits / data byte */
/* databits + startbit and 1 stopbit */
if ((cflags & CSIZE) == CS7)
bits = 9;
else
bits = 10;
if (cflags & CSTOPB) /* 2 stopbits ? */
bits++;
if (cflags & PARENB) /* parity bit ? */
bits++;
/* calc timeout */
info->char_time_usec = ((bits * 1000000) / info->baud) + 1;
info->flush_time_usec = 4*info->char_time_usec;
if (info->flush_time_usec < MIN_FLUSH_TIME_USEC)
info->flush_time_usec = MIN_FLUSH_TIME_USEC;
}
/*
* This function maps from the Bxxxx defines in asm/termbits.h into real
* baud rates.
*/
static int
cflag_to_baud(unsigned int cflag)
{
static int baud_table[] = {
0, 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400,
4800, 9600, 19200, 38400 };
static int ext_baud_table[] = {
0, 57600, 115200, 230400, 460800, 921600, 1843200, 6250000,
0, 0, 0, 0, 0, 0, 0, 0 };
if (cflag & CBAUDEX)
return ext_baud_table[(cflag & CBAUD) & ~CBAUDEX];
else
return baud_table[cflag & CBAUD];
}
/* and this maps to an etrax100 hardware baud constant */
static unsigned char
cflag_to_etrax_baud(unsigned int cflag)
{
char retval;
static char baud_table[] = {
-1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, 3, 4, 5, 6, 7 };
static char ext_baud_table[] = {
-1, 8, 9, 10, 11, 12, 13, 14, -1, -1, -1, -1, -1, -1, -1, -1 };
if (cflag & CBAUDEX)
retval = ext_baud_table[(cflag & CBAUD) & ~CBAUDEX];
else
retval = baud_table[cflag & CBAUD];
if (retval < 0) {
printk(KERN_WARNING "serdriver tried setting invalid baud rate, flags %x.\n", cflag);
retval = 5; /* choose default 9600 instead */
}
return retval | (retval << 4); /* choose same for both TX and RX */
}
/* Various static support functions */
/* Functions to set or clear DTR/RTS on the requested line */
/* It is complicated by the fact that RTS is a serial port register, while
* DTR might not be implemented in the HW at all, and if it is, it can be on
* any general port.
*/
static inline void
e100_dtr(struct e100_serial *info, int set)
{
#ifndef CONFIG_SVINTO_SIM
unsigned char mask = e100_modem_pins[info->line].dtr_mask;
#ifdef SERIAL_DEBUG_IO
printk("ser%i dtr %i mask: 0x%02X\n", info->line, set, mask);
printk("ser%i shadow before 0x%02X get: %i\n",
info->line, *e100_modem_pins[info->line].dtr_shadow,
E100_DTR_GET(info));
#endif
/* DTR is active low */
{
unsigned long flags;
local_irq_save(flags);
*e100_modem_pins[info->line].dtr_shadow &= ~mask;
*e100_modem_pins[info->line].dtr_shadow |= (set ? 0 : mask);
*e100_modem_pins[info->line].dtr_port = *e100_modem_pins[info->line].dtr_shadow;
local_irq_restore(flags);
}
#ifdef SERIAL_DEBUG_IO
printk("ser%i shadow after 0x%02X get: %i\n",
info->line, *e100_modem_pins[info->line].dtr_shadow,
E100_DTR_GET(info));
#endif
#endif
}
/* set = 0 means 3.3V on the pin, bitvalue: 0=active, 1=inactive
* 0=0V , 1=3.3V
*/
static inline void
e100_rts(struct e100_serial *info, int set)
{
#ifndef CONFIG_SVINTO_SIM
unsigned long flags;
local_irq_save(flags);
info->rx_ctrl &= ~E100_RTS_MASK;
info->rx_ctrl |= (set ? 0 : E100_RTS_MASK); /* RTS is active low */
info->ioport[REG_REC_CTRL] = info->rx_ctrl;
local_irq_restore(flags);
#ifdef SERIAL_DEBUG_IO
printk("ser%i rts %i\n", info->line, set);
#endif
#endif
}
/* If this behaves as a modem, RI and CD is an output */
static inline void
e100_ri_out(struct e100_serial *info, int set)
{
#ifndef CONFIG_SVINTO_SIM
/* RI is active low */
{
unsigned char mask = e100_modem_pins[info->line].ri_mask;
unsigned long flags;
local_irq_save(flags);
*e100_modem_pins[info->line].ri_shadow &= ~mask;
*e100_modem_pins[info->line].ri_shadow |= (set ? 0 : mask);
*e100_modem_pins[info->line].ri_port = *e100_modem_pins[info->line].ri_shadow;
local_irq_restore(flags);
}
#endif
}
static inline void
e100_cd_out(struct e100_serial *info, int set)
{
#ifndef CONFIG_SVINTO_SIM
/* CD is active low */
{
unsigned char mask = e100_modem_pins[info->line].cd_mask;
unsigned long flags;
local_irq_save(flags);
*e100_modem_pins[info->line].cd_shadow &= ~mask;
*e100_modem_pins[info->line].cd_shadow |= (set ? 0 : mask);
*e100_modem_pins[info->line].cd_port = *e100_modem_pins[info->line].cd_shadow;
local_irq_restore(flags);
}
#endif
}
static inline void
e100_disable_rx(struct e100_serial *info)
{
#ifndef CONFIG_SVINTO_SIM
/* disable the receiver */
info->ioport[REG_REC_CTRL] =
(info->rx_ctrl &= ~IO_MASK(R_SERIAL0_REC_CTRL, rec_enable));
#endif
}
static inline void
e100_enable_rx(struct e100_serial *info)
{
#ifndef CONFIG_SVINTO_SIM
/* enable the receiver */
info->ioport[REG_REC_CTRL] =
(info->rx_ctrl |= IO_MASK(R_SERIAL0_REC_CTRL, rec_enable));
#endif
}
/* the rx DMA uses both the dma_descr and the dma_eop interrupts */
static inline void
e100_disable_rxdma_irq(struct e100_serial *info)
{
#ifdef SERIAL_DEBUG_INTR
printk("rxdma_irq(%d): 0\n",info->line);
#endif
DINTR1(DEBUG_LOG(info->line,"IRQ disable_rxdma_irq %i\n", info->line));
*R_IRQ_MASK2_CLR = (info->irq << 2) | (info->irq << 3);
}
static inline void
e100_enable_rxdma_irq(struct e100_serial *info)
{
#ifdef SERIAL_DEBUG_INTR
printk("rxdma_irq(%d): 1\n",info->line);
#endif
DINTR1(DEBUG_LOG(info->line,"IRQ enable_rxdma_irq %i\n", info->line));
*R_IRQ_MASK2_SET = (info->irq << 2) | (info->irq << 3);
}
/* the tx DMA uses only dma_descr interrupt */
static void e100_disable_txdma_irq(struct e100_serial *info)
{
#ifdef SERIAL_DEBUG_INTR
printk("txdma_irq(%d): 0\n",info->line);
#endif
DINTR1(DEBUG_LOG(info->line,"IRQ disable_txdma_irq %i\n", info->line));
*R_IRQ_MASK2_CLR = info->irq;
}
static void e100_enable_txdma_irq(struct e100_serial *info)
{
#ifdef SERIAL_DEBUG_INTR
printk("txdma_irq(%d): 1\n",info->line);
#endif
DINTR1(DEBUG_LOG(info->line,"IRQ enable_txdma_irq %i\n", info->line));
*R_IRQ_MASK2_SET = info->irq;
}
static void e100_disable_txdma_channel(struct e100_serial *info)
{
unsigned long flags;
/* Disable output DMA channel for the serial port in question
* ( set to something other than serialX)
*/
local_irq_save(flags);
DFLOW(DEBUG_LOG(info->line, "disable_txdma_channel %i\n", info->line));
if (info->line == 0) {
if ((genconfig_shadow & IO_MASK(R_GEN_CONFIG, dma6)) ==
IO_STATE(R_GEN_CONFIG, dma6, serial0)) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma6);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma6, unused);
}
} else if (info->line == 1) {
if ((genconfig_shadow & IO_MASK(R_GEN_CONFIG, dma8)) ==
IO_STATE(R_GEN_CONFIG, dma8, serial1)) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma8);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma8, usb);
}
} else if (info->line == 2) {
if ((genconfig_shadow & IO_MASK(R_GEN_CONFIG, dma2)) ==
IO_STATE(R_GEN_CONFIG, dma2, serial2)) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma2);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma2, par0);
}
} else if (info->line == 3) {
if ((genconfig_shadow & IO_MASK(R_GEN_CONFIG, dma4)) ==
IO_STATE(R_GEN_CONFIG, dma4, serial3)) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma4);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma4, par1);
}
}
*R_GEN_CONFIG = genconfig_shadow;
local_irq_restore(flags);
}
static void e100_enable_txdma_channel(struct e100_serial *info)
{
unsigned long flags;
local_irq_save(flags);
DFLOW(DEBUG_LOG(info->line, "enable_txdma_channel %i\n", info->line));
/* Enable output DMA channel for the serial port in question */
if (info->line == 0) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma6);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma6, serial0);
} else if (info->line == 1) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma8);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma8, serial1);
} else if (info->line == 2) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma2);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma2, serial2);
} else if (info->line == 3) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma4);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma4, serial3);
}
*R_GEN_CONFIG = genconfig_shadow;
local_irq_restore(flags);
}
static void e100_disable_rxdma_channel(struct e100_serial *info)
{
unsigned long flags;
/* Disable input DMA channel for the serial port in question
* ( set to something other than serialX)
*/
local_irq_save(flags);
if (info->line == 0) {
if ((genconfig_shadow & IO_MASK(R_GEN_CONFIG, dma7)) ==
IO_STATE(R_GEN_CONFIG, dma7, serial0)) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma7);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma7, unused);
}
} else if (info->line == 1) {
if ((genconfig_shadow & IO_MASK(R_GEN_CONFIG, dma9)) ==
IO_STATE(R_GEN_CONFIG, dma9, serial1)) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma9);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma9, usb);
}
} else if (info->line == 2) {
if ((genconfig_shadow & IO_MASK(R_GEN_CONFIG, dma3)) ==
IO_STATE(R_GEN_CONFIG, dma3, serial2)) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma3);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma3, par0);
}
} else if (info->line == 3) {
if ((genconfig_shadow & IO_MASK(R_GEN_CONFIG, dma5)) ==
IO_STATE(R_GEN_CONFIG, dma5, serial3)) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma5);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma5, par1);
}
}
*R_GEN_CONFIG = genconfig_shadow;
local_irq_restore(flags);
}
static void e100_enable_rxdma_channel(struct e100_serial *info)
{
unsigned long flags;
local_irq_save(flags);
/* Enable input DMA channel for the serial port in question */
if (info->line == 0) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma7);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma7, serial0);
} else if (info->line == 1) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma9);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma9, serial1);
} else if (info->line == 2) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma3);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma3, serial2);
} else if (info->line == 3) {
genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, dma5);
genconfig_shadow |= IO_STATE(R_GEN_CONFIG, dma5, serial3);
}
*R_GEN_CONFIG = genconfig_shadow;
local_irq_restore(flags);
}
#ifdef SERIAL_HANDLE_EARLY_ERRORS
/* in order to detect and fix errors on the first byte
we have to use the serial interrupts as well. */
static inline void
e100_disable_serial_data_irq(struct e100_serial *info)
{
#ifdef SERIAL_DEBUG_INTR
printk("ser_irq(%d): 0\n",info->line);
#endif
DINTR1(DEBUG_LOG(info->line,"IRQ disable data_irq %i\n", info->line));
*R_IRQ_MASK1_CLR = (1U << (8+2*info->line));
}
static inline void
e100_enable_serial_data_irq(struct e100_serial *info)
{
#ifdef SERIAL_DEBUG_INTR
printk("ser_irq(%d): 1\n",info->line);
printk("**** %d = %d\n",
(8+2*info->line),
(1U << (8+2*info->line)));
#endif
DINTR1(DEBUG_LOG(info->line,"IRQ enable data_irq %i\n", info->line));
*R_IRQ_MASK1_SET = (1U << (8+2*info->line));
}
#endif
static inline void
e100_disable_serial_tx_ready_irq(struct e100_serial *info)
{
#ifdef SERIAL_DEBUG_INTR
printk("ser_tx_irq(%d): 0\n",info->line);
#endif
DINTR1(DEBUG_LOG(info->line,"IRQ disable ready_irq %i\n", info->line));
*R_IRQ_MASK1_CLR = (1U << (8+1+2*info->line));
}
static inline void
e100_enable_serial_tx_ready_irq(struct e100_serial *info)
{
#ifdef SERIAL_DEBUG_INTR
printk("ser_tx_irq(%d): 1\n",info->line);
printk("**** %d = %d\n",
(8+1+2*info->line),
(1U << (8+1+2*info->line)));
#endif
DINTR2(DEBUG_LOG(info->line,"IRQ enable ready_irq %i\n", info->line));
*R_IRQ_MASK1_SET = (1U << (8+1+2*info->line));
}
static inline void e100_enable_rx_irq(struct e100_serial *info)
{
if (info->uses_dma_in)
e100_enable_rxdma_irq(info);
else
e100_enable_serial_data_irq(info);
}
static inline void e100_disable_rx_irq(struct e100_serial *info)
{
if (info->uses_dma_in)
e100_disable_rxdma_irq(info);
else
e100_disable_serial_data_irq(info);
}
#if defined(CONFIG_ETRAX_RS485)
/* Enable RS-485 mode on selected port. This is UGLY. */
static int
e100_enable_rs485(struct tty_struct *tty, struct serial_rs485 *r)
{
struct e100_serial * info = (struct e100_serial *)tty->driver_data;
#if defined(CONFIG_ETRAX_RS485_ON_PA)
*R_PORT_PA_DATA = port_pa_data_shadow |= (1 << rs485_pa_bit);
#endif
#if defined(CONFIG_ETRAX_RS485_ON_PORT_G)
REG_SHADOW_SET(R_PORT_G_DATA, port_g_data_shadow,
rs485_port_g_bit, 1);
#endif
#if defined(CONFIG_ETRAX_RS485_LTC1387)
REG_SHADOW_SET(R_PORT_G_DATA, port_g_data_shadow,
CONFIG_ETRAX_RS485_LTC1387_DXEN_PORT_G_BIT, 1);
REG_SHADOW_SET(R_PORT_G_DATA, port_g_data_shadow,
CONFIG_ETRAX_RS485_LTC1387_RXEN_PORT_G_BIT, 1);
#endif
info->rs485 = *r;
/* Maximum delay before RTS equal to 1000 */
if (info->rs485.delay_rts_before_send >= 1000)
info->rs485.delay_rts_before_send = 1000;
/* printk("rts: on send = %i, after = %i, enabled = %i",
info->rs485.rts_on_send,
info->rs485.rts_after_sent,
info->rs485.enabled
);
*/
return 0;
}
static int
e100_write_rs485(struct tty_struct *tty,
const unsigned char *buf, int count)
{
struct e100_serial * info = (struct e100_serial *)tty->driver_data;
int old_value = (info->rs485.flags) & SER_RS485_ENABLED;
/* rs485 is always implicitly enabled if we're using the ioctl()
* but it doesn't have to be set in the serial_rs485
* (to be backward compatible with old apps)
* So we store, set and restore it.
*/
info->rs485.flags |= SER_RS485_ENABLED;
/* rs_write now deals with RS485 if enabled */
count = rs_write(tty, buf, count);
if (!old_value)
info->rs485.flags &= ~(SER_RS485_ENABLED);
return count;
}
#ifdef CONFIG_ETRAX_FAST_TIMER
/* Timer function to toggle RTS when using FAST_TIMER */
static void rs485_toggle_rts_timer_function(unsigned long data)
{
struct e100_serial *info = (struct e100_serial *)data;
fast_timers_rs485[info->line].function = NULL;
e100_rts(info, (info->rs485.flags & SER_RS485_RTS_AFTER_SEND));
#if defined(CONFIG_ETRAX_RS485_DISABLE_RECEIVER)
e100_enable_rx(info);
e100_enable_rx_irq(info);
#endif
}
#endif
#endif /* CONFIG_ETRAX_RS485 */
/*
* ------------------------------------------------------------
* rs_stop() and rs_start()
*
* This routines are called before setting or resetting tty->stopped.
* They enable or disable transmitter using the XOFF registers, as necessary.
* ------------------------------------------------------------
*/
static void
rs_stop(struct tty_struct *tty)
{
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
if (info) {
unsigned long flags;
unsigned long xoff;
local_irq_save(flags);
DFLOW(DEBUG_LOG(info->line, "XOFF rs_stop xmit %i\n",
CIRC_CNT(info->xmit.head,
info->xmit.tail,SERIAL_XMIT_SIZE)));
xoff = IO_FIELD(R_SERIAL0_XOFF, xoff_char,
STOP_CHAR(info->port.tty));
xoff |= IO_STATE(R_SERIAL0_XOFF, tx_stop, stop);
if (tty->termios->c_iflag & IXON ) {
xoff |= IO_STATE(R_SERIAL0_XOFF, auto_xoff, enable);
}
*((unsigned long *)&info->ioport[REG_XOFF]) = xoff;
local_irq_restore(flags);
}
}
static void
rs_start(struct tty_struct *tty)
{
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
if (info) {
unsigned long flags;
unsigned long xoff;
local_irq_save(flags);
DFLOW(DEBUG_LOG(info->line, "XOFF rs_start xmit %i\n",
CIRC_CNT(info->xmit.head,
info->xmit.tail,SERIAL_XMIT_SIZE)));
xoff = IO_FIELD(R_SERIAL0_XOFF, xoff_char, STOP_CHAR(tty));
xoff |= IO_STATE(R_SERIAL0_XOFF, tx_stop, enable);
if (tty->termios->c_iflag & IXON ) {
xoff |= IO_STATE(R_SERIAL0_XOFF, auto_xoff, enable);
}
*((unsigned long *)&info->ioport[REG_XOFF]) = xoff;
if (!info->uses_dma_out &&
info->xmit.head != info->xmit.tail && info->xmit.buf)
e100_enable_serial_tx_ready_irq(info);
local_irq_restore(flags);
}
}
/*
* ----------------------------------------------------------------------
*
* Here starts the interrupt handling routines. All of the following
* subroutines are declared as inline and are folded into
* rs_interrupt(). They were separated out for readability's sake.
*
* Note: rs_interrupt() is a "fast" interrupt, which means that it
* runs with interrupts turned off. People who may want to modify
* rs_interrupt() should try to keep the interrupt handler as fast as
* possible. After you are done making modifications, it is not a bad
* idea to do:
*
* gcc -S -DKERNEL -Wall -Wstrict-prototypes -O6 -fomit-frame-pointer serial.c
*
* and look at the resulting assemble code in serial.s.
*
* - Ted Ts'o (tytso@mit.edu), 7-Mar-93
* -----------------------------------------------------------------------
*/
/*
* This routine is used by the interrupt handler to schedule
* processing in the software interrupt portion of the driver.
*/
static void rs_sched_event(struct e100_serial *info, int event)
{
if (info->event & (1 << event))
return;
info->event |= 1 << event;
schedule_work(&info->work);
}
/* The output DMA channel is free - use it to send as many chars as possible
* NOTES:
* We don't pay attention to info->x_char, which means if the TTY wants to
* use XON/XOFF it will set info->x_char but we won't send any X char!
*
* To implement this, we'd just start a DMA send of 1 byte pointing at a
* buffer containing the X char, and skip updating xmit. We'd also have to
* check if the last sent char was the X char when we enter this function
* the next time, to avoid updating xmit with the sent X value.
*/
static void
transmit_chars_dma(struct e100_serial *info)
{
unsigned int c, sentl;
struct etrax_dma_descr *descr;
#ifdef CONFIG_SVINTO_SIM
/* This will output too little if tail is not 0 always since
* we don't reloop to send the other part. Anyway this SHOULD be a
* no-op - transmit_chars_dma would never really be called during sim
* since rs_write does not write into the xmit buffer then.
*/
if (info->xmit.tail)
printk("Error in serial.c:transmit_chars-dma(), tail!=0\n");
if (info->xmit.head != info->xmit.tail) {
SIMCOUT(info->xmit.buf + info->xmit.tail,
CIRC_CNT(info->xmit.head,
info->xmit.tail,
SERIAL_XMIT_SIZE));
info->xmit.head = info->xmit.tail; /* move back head */
info->tr_running = 0;
}
return;
#endif
/* acknowledge both dma_descr and dma_eop irq in R_DMA_CHx_CLR_INTR */
*info->oclrintradr =
IO_STATE(R_DMA_CH6_CLR_INTR, clr_descr, do) |
IO_STATE(R_DMA_CH6_CLR_INTR, clr_eop, do);
#ifdef SERIAL_DEBUG_INTR
if (info->line == SERIAL_DEBUG_LINE)
printk("tc\n");
#endif
if (!info->tr_running) {
/* weirdo... we shouldn't get here! */
printk(KERN_WARNING "Achtung: transmit_chars_dma with !tr_running\n");
return;
}
descr = &info->tr_descr;
/* first get the amount of bytes sent during the last DMA transfer,
and update xmit accordingly */
/* if the stop bit was not set, all data has been sent */
if (!(descr->status & d_stop)) {
sentl = descr->sw_len;
} else
/* otherwise we find the amount of data sent here */
sentl = descr->hw_len;
DFLOW(DEBUG_LOG(info->line, "TX %i done\n", sentl));
/* update stats */
info->icount.tx += sentl;
/* update xmit buffer */
info->xmit.tail = (info->xmit.tail + sentl) & (SERIAL_XMIT_SIZE - 1);
/* if there is only a few chars left in the buf, wake up the blocked
write if any */
if (CIRC_CNT(info->xmit.head,
info->xmit.tail,
SERIAL_XMIT_SIZE) < WAKEUP_CHARS)
rs_sched_event(info, RS_EVENT_WRITE_WAKEUP);
/* find out the largest amount of consecutive bytes we want to send now */
c = CIRC_CNT_TO_END(info->xmit.head, info->xmit.tail, SERIAL_XMIT_SIZE);
/* Don't send all in one DMA transfer - divide it so we wake up
* application before all is sent
*/
if (c >= 4*WAKEUP_CHARS)
c = c/2;
if (c <= 0) {
/* our job here is done, don't schedule any new DMA transfer */
info->tr_running = 0;
#if defined(CONFIG_ETRAX_RS485) && defined(CONFIG_ETRAX_FAST_TIMER)
if (info->rs485.flags & SER_RS485_ENABLED) {
/* Set a short timer to toggle RTS */
start_one_shot_timer(&fast_timers_rs485[info->line],
rs485_toggle_rts_timer_function,
(unsigned long)info,
info->char_time_usec*2,
"RS-485");
}
#endif /* RS485 */
return;
}
/* ok we can schedule a dma send of c chars starting at info->xmit.tail */
/* set up the descriptor correctly for output */
DFLOW(DEBUG_LOG(info->line, "TX %i\n", c));
descr->ctrl = d_int | d_eol | d_wait; /* Wait needed for tty_wait_until_sent() */
descr->sw_len = c;
descr->buf = virt_to_phys(info->xmit.buf + info->xmit.tail);
descr->status = 0;
*info->ofirstadr = virt_to_phys(descr); /* write to R_DMAx_FIRST */
*info->ocmdadr = IO_STATE(R_DMA_CH6_CMD, cmd, start);
/* DMA is now running (hopefully) */
} /* transmit_chars_dma */
static void
start_transmit(struct e100_serial *info)
{
#if 0
if (info->line == SERIAL_DEBUG_LINE)
printk("x\n");
#endif
info->tr_descr.sw_len = 0;
info->tr_descr.hw_len = 0;
info->tr_descr.status = 0;
info->tr_running = 1;
if (info->uses_dma_out)
transmit_chars_dma(info);
else
e100_enable_serial_tx_ready_irq(info);
} /* start_transmit */
#ifdef CONFIG_ETRAX_SERIAL_FAST_TIMER
static int serial_fast_timer_started = 0;
static int serial_fast_timer_expired = 0;
static void flush_timeout_function(unsigned long data);
#define START_FLUSH_FAST_TIMER_TIME(info, string, usec) {\
unsigned long timer_flags; \
local_irq_save(timer_flags); \
if (fast_timers[info->line].function == NULL) { \
serial_fast_timer_started++; \
TIMERD(DEBUG_LOG(info->line, "start_timer %i ", info->line)); \
TIMERD(DEBUG_LOG(info->line, "num started: %i\n", serial_fast_timer_started)); \
start_one_shot_timer(&fast_timers[info->line], \
flush_timeout_function, \
(unsigned long)info, \
(usec), \
string); \
} \
else { \
TIMERD(DEBUG_LOG(info->line, "timer %i already running\n", info->line)); \
} \
local_irq_restore(timer_flags); \
}
#define START_FLUSH_FAST_TIMER(info, string) START_FLUSH_FAST_TIMER_TIME(info, string, info->flush_time_usec)
#else
#define START_FLUSH_FAST_TIMER_TIME(info, string, usec)
#define START_FLUSH_FAST_TIMER(info, string)
#endif
static struct etrax_recv_buffer *
alloc_recv_buffer(unsigned int size)
{
struct etrax_recv_buffer *buffer;
if (!(buffer = kmalloc(sizeof *buffer + size, GFP_ATOMIC)))
return NULL;
buffer->next = NULL;
buffer->length = 0;
buffer->error = TTY_NORMAL;
return buffer;
}
static void
append_recv_buffer(struct e100_serial *info, struct etrax_recv_buffer *buffer)
{
unsigned long flags;
local_irq_save(flags);
if (!info->first_recv_buffer)
info->first_recv_buffer = buffer;
else
info->last_recv_buffer->next = buffer;
info->last_recv_buffer = buffer;
info->recv_cnt += buffer->length;
if (info->recv_cnt > info->max_recv_cnt)
info->max_recv_cnt = info->recv_cnt;
local_irq_restore(flags);
}
static int
add_char_and_flag(struct e100_serial *info, unsigned char data, unsigned char flag)
{
struct etrax_recv_buffer *buffer;
if (info->uses_dma_in) {
if (!(buffer = alloc_recv_buffer(4)))
return 0;
buffer->length = 1;
buffer->error = flag;
buffer->buffer[0] = data;
append_recv_buffer(info, buffer);
info->icount.rx++;
} else {
struct tty_struct *tty = info->port.tty;
tty_insert_flip_char(tty, data, flag);
info->icount.rx++;
}
return 1;
}
static unsigned int handle_descr_data(struct e100_serial *info,
struct etrax_dma_descr *descr,
unsigned int recvl)
{
struct etrax_recv_buffer *buffer = phys_to_virt(descr->buf) - sizeof *buffer;
if (info->recv_cnt + recvl > 65536) {
printk(KERN_WARNING
"%s: Too much pending incoming serial data! Dropping %u bytes.\n", __func__, recvl);
return 0;
}
buffer->length = recvl;
if (info->errorcode == ERRCODE_SET_BREAK)
buffer->error = TTY_BREAK;
info->errorcode = 0;
append_recv_buffer(info, buffer);
if (!(buffer = alloc_recv_buffer(SERIAL_DESCR_BUF_SIZE)))
panic("%s: Failed to allocate memory for receive buffer!\n", __func__);
descr->buf = virt_to_phys(buffer->buffer);
return recvl;
}
static unsigned int handle_all_descr_data(struct e100_serial *info)
{
struct etrax_dma_descr *descr;
unsigned int recvl;
unsigned int ret = 0;
while (1)
{
descr = &info->rec_descr[info->cur_rec_descr];
if (descr == phys_to_virt(*info->idescradr))
break;
if (++info->cur_rec_descr == SERIAL_RECV_DESCRIPTORS)
info->cur_rec_descr = 0;
/* find out how many bytes were read */
/* if the eop bit was not set, all data has been received */
if (!(descr->status & d_eop)) {
recvl = descr->sw_len;
} else {
/* otherwise we find the amount of data received here */
recvl = descr->hw_len;
}
/* Reset the status information */
descr->status = 0;
DFLOW( DEBUG_LOG(info->line, "RX %lu\n", recvl);
if (info->port.tty->stopped) {
unsigned char *buf = phys_to_virt(descr->buf);
DEBUG_LOG(info->line, "rx 0x%02X\n", buf[0]);
DEBUG_LOG(info->line, "rx 0x%02X\n", buf[1]);
DEBUG_LOG(info->line, "rx 0x%02X\n", buf[2]);
}
);
/* update stats */
info->icount.rx += recvl;
ret += handle_descr_data(info, descr, recvl);
}
return ret;
}
static void receive_chars_dma(struct e100_serial *info)
{
struct tty_struct *tty;
unsigned char rstat;
#ifdef CONFIG_SVINTO_SIM
/* No receive in the simulator. Will probably be when the rest of
* the serial interface works, and this piece will just be removed.
*/
return;
#endif
/* Acknowledge both dma_descr and dma_eop irq in R_DMA_CHx_CLR_INTR */
*info->iclrintradr =
IO_STATE(R_DMA_CH6_CLR_INTR, clr_descr, do) |
IO_STATE(R_DMA_CH6_CLR_INTR, clr_eop, do);
tty = info->port.tty;
if (!tty) /* Something wrong... */
return;
#ifdef SERIAL_HANDLE_EARLY_ERRORS
if (info->uses_dma_in)
e100_enable_serial_data_irq(info);
#endif
if (info->errorcode == ERRCODE_INSERT_BREAK)
add_char_and_flag(info, '\0', TTY_BREAK);
handle_all_descr_data(info);
/* Read the status register to detect errors */
rstat = info->ioport[REG_STATUS];
if (rstat & IO_MASK(R_SERIAL0_STATUS, xoff_detect) ) {
DFLOW(DEBUG_LOG(info->line, "XOFF detect stat %x\n", rstat));
}
if (rstat & SER_ERROR_MASK) {
/* If we got an error, we must reset it by reading the
* data_in field
*/
unsigned char data = info->ioport[REG_DATA];
PROCSTAT(ser_stat[info->line].errors_cnt++);
DEBUG_LOG(info->line, "#dERR: s d 0x%04X\n",
((rstat & SER_ERROR_MASK) << 8) | data);
if (rstat & SER_PAR_ERR_MASK)
add_char_and_flag(info, data, TTY_PARITY);
else if (rstat & SER_OVERRUN_MASK)
add_char_and_flag(info, data, TTY_OVERRUN);
else if (rstat & SER_FRAMING_ERR_MASK)
add_char_and_flag(info, data, TTY_FRAME);
}
START_FLUSH_FAST_TIMER(info, "receive_chars");
/* Restart the receiving DMA */
*info->icmdadr = IO_STATE(R_DMA_CH6_CMD, cmd, restart);
}
static int start_recv_dma(struct e100_serial *info)
{
struct etrax_dma_descr *descr = info->rec_descr;
struct etrax_recv_buffer *buffer;
int i;
/* Set up the receiving descriptors */
for (i = 0; i < SERIAL_RECV_DESCRIPTORS; i++) {
if (!(buffer = alloc_recv_buffer(SERIAL_DESCR_BUF_SIZE)))
panic("%s: Failed to allocate memory for receive buffer!\n", __func__);
descr[i].ctrl = d_int;
descr[i].buf = virt_to_phys(buffer->buffer);
descr[i].sw_len = SERIAL_DESCR_BUF_SIZE;
descr[i].hw_len = 0;
descr[i].status = 0;
descr[i].next = virt_to_phys(&descr[i+1]);
}
/* Link the last descriptor to the first */
descr[i-1].next = virt_to_phys(&descr[0]);
/* Start with the first descriptor in the list */
info->cur_rec_descr = 0;
/* Start the DMA */
*info->ifirstadr = virt_to_phys(&descr[info->cur_rec_descr]);
*info->icmdadr = IO_STATE(R_DMA_CH6_CMD, cmd, start);
/* Input DMA should be running now */
return 1;
}
static void
start_receive(struct e100_serial *info)
{
#ifdef CONFIG_SVINTO_SIM
/* No receive in the simulator. Will probably be when the rest of
* the serial interface works, and this piece will just be removed.
*/
return;
#endif
if (info->uses_dma_in) {
/* reset the input dma channel to be sure it works */
*info->icmdadr = IO_STATE(R_DMA_CH6_CMD, cmd, reset);
while (IO_EXTRACT(R_DMA_CH6_CMD, cmd, *info->icmdadr) ==
IO_STATE_VALUE(R_DMA_CH6_CMD, cmd, reset));
start_recv_dma(info);
}
}
/* the bits in the MASK2 register are laid out like this:
DMAI_EOP DMAI_DESCR DMAO_EOP DMAO_DESCR
where I is the input channel and O is the output channel for the port.
info->irq is the bit number for the DMAO_DESCR so to check the others we
shift info->irq to the left.
*/
/* dma output channel interrupt handler
this interrupt is called from DMA2(ser2), DMA4(ser3), DMA6(ser0) or
DMA8(ser1) when they have finished a descriptor with the intr flag set.
*/
static irqreturn_t
tr_interrupt(int irq, void *dev_id)
{
struct e100_serial *info;
unsigned long ireg;
int i;
int handled = 0;
#ifdef CONFIG_SVINTO_SIM
/* No receive in the simulator. Will probably be when the rest of
* the serial interface works, and this piece will just be removed.
*/
{
const char *s = "What? tr_interrupt in simulator??\n";
SIMCOUT(s,strlen(s));
}
return IRQ_HANDLED;
#endif
/* find out the line that caused this irq and get it from rs_table */
ireg = *R_IRQ_MASK2_RD; /* get the active irq bits for the dma channels */
for (i = 0; i < NR_PORTS; i++) {
info = rs_table + i;
if (!info->enabled || !info->uses_dma_out)
continue;
/* check for dma_descr (don't need to check for dma_eop in output dma for serial */
if (ireg & info->irq) {
handled = 1;
/* we can send a new dma bunch. make it so. */
DINTR2(DEBUG_LOG(info->line, "tr_interrupt %i\n", i));
/* Read jiffies_usec first,
* we want this time to be as late as possible
*/
PROCSTAT(ser_stat[info->line].tx_dma_ints++);
info->last_tx_active_usec = GET_JIFFIES_USEC();
info->last_tx_active = jiffies;
transmit_chars_dma(info);
}
/* FIXME: here we should really check for a change in the
status lines and if so call status_handle(info) */
}
return IRQ_RETVAL(handled);
} /* tr_interrupt */
/* dma input channel interrupt handler */
static irqreturn_t
rec_interrupt(int irq, void *dev_id)
{
struct e100_serial *info;
unsigned long ireg;
int i;
int handled = 0;
#ifdef CONFIG_SVINTO_SIM
/* No receive in the simulator. Will probably be when the rest of
* the serial interface works, and this piece will just be removed.
*/
{
const char *s = "What? rec_interrupt in simulator??\n";
SIMCOUT(s,strlen(s));
}
return IRQ_HANDLED;
#endif
/* find out the line that caused this irq and get it from rs_table */
ireg = *R_IRQ_MASK2_RD; /* get the active irq bits for the dma channels */
for (i = 0; i < NR_PORTS; i++) {
info = rs_table + i;
if (!info->enabled || !info->uses_dma_in)
continue;
/* check for both dma_eop and dma_descr for the input dma channel */
if (ireg & ((info->irq << 2) | (info->irq << 3))) {
handled = 1;
/* we have received something */
receive_chars_dma(info);
}
/* FIXME: here we should really check for a change in the
status lines and if so call status_handle(info) */
}
return IRQ_RETVAL(handled);
} /* rec_interrupt */
static int force_eop_if_needed(struct e100_serial *info)
{
/* We check data_avail bit to determine if data has
* arrived since last time
*/
unsigned char rstat = info->ioport[REG_STATUS];
/* error or datavail? */
if (rstat & SER_ERROR_MASK) {
/* Some error has occurred. If there has been valid data, an
* EOP interrupt will be made automatically. If no data, the
* normal ser_interrupt should be enabled and handle it.
* So do nothing!
*/
DEBUG_LOG(info->line, "timeout err: rstat 0x%03X\n",
rstat | (info->line << 8));
return 0;
}
if (rstat & SER_DATA_AVAIL_MASK) {
/* Ok data, no error, count it */
TIMERD(DEBUG_LOG(info->line, "timeout: rstat 0x%03X\n",
rstat | (info->line << 8)));
/* Read data to clear status flags */
(void)info->ioport[REG_DATA];
info->forced_eop = 0;
START_FLUSH_FAST_TIMER(info, "magic");
return 0;
}
/* hit the timeout, force an EOP for the input
* dma channel if we haven't already
*/
if (!info->forced_eop) {
info->forced_eop = 1;
PROCSTAT(ser_stat[info->line].timeout_flush_cnt++);
TIMERD(DEBUG_LOG(info->line, "timeout EOP %i\n", info->line));
FORCE_EOP(info);
}
return 1;
}
static void flush_to_flip_buffer(struct e100_serial *info)
{
struct tty_struct *tty;
struct etrax_recv_buffer *buffer;
unsigned long flags;
local_irq_save(flags);
tty = info->port.tty;
if (!tty) {
local_irq_restore(flags);
return;
}
while ((buffer = info->first_recv_buffer) != NULL) {
unsigned int count = buffer->length;
tty_insert_flip_string(tty, buffer->buffer, count);
info->recv_cnt -= count;
if (count == buffer->length) {
info->first_recv_buffer = buffer->next;
kfree(buffer);
} else {
buffer->length -= count;
memmove(buffer->buffer, buffer->buffer + count, buffer->length);
buffer->error = TTY_NORMAL;
}
}
if (!info->first_recv_buffer)
info->last_recv_buffer = NULL;
local_irq_restore(flags);
/* This includes a check for low-latency */
tty_flip_buffer_push(tty);
}
static void check_flush_timeout(struct e100_serial *info)
{
/* Flip what we've got (if we can) */
flush_to_flip_buffer(info);
/* We might need to flip later, but not to fast
* since the system is busy processing input... */
if (info->first_recv_buffer)
START_FLUSH_FAST_TIMER_TIME(info, "flip", 2000);
/* Force eop last, since data might have come while we're processing
* and if we started the slow timer above, we won't start a fast
* below.
*/
force_eop_if_needed(info);
}
#ifdef CONFIG_ETRAX_SERIAL_FAST_TIMER
static void flush_timeout_function(unsigned long data)
{
struct e100_serial *info = (struct e100_serial *)data;
fast_timers[info->line].function = NULL;
serial_fast_timer_expired++;
TIMERD(DEBUG_LOG(info->line, "flush_timout %i ", info->line));
TIMERD(DEBUG_LOG(info->line, "num expired: %i\n", serial_fast_timer_expired));
check_flush_timeout(info);
}
#else
/* dma fifo/buffer timeout handler
forces an end-of-packet for the dma input channel if no chars
have been received for CONFIG_ETRAX_SERIAL_RX_TIMEOUT_TICKS/100 s.
*/
static struct timer_list flush_timer;
static void
timed_flush_handler(unsigned long ptr)
{
struct e100_serial *info;
int i;
#ifdef CONFIG_SVINTO_SIM
return;
#endif
for (i = 0; i < NR_PORTS; i++) {
info = rs_table + i;
if (info->uses_dma_in)
check_flush_timeout(info);
}
/* restart flush timer */
mod_timer(&flush_timer, jiffies + CONFIG_ETRAX_SERIAL_RX_TIMEOUT_TICKS);
}
#endif
#ifdef SERIAL_HANDLE_EARLY_ERRORS
/* If there is an error (ie break) when the DMA is running and
* there are no bytes in the fifo the DMA is stopped and we get no
* eop interrupt. Thus we have to monitor the first bytes on a DMA
* transfer, and if it is without error we can turn the serial
* interrupts off.
*/
/*
BREAK handling on ETRAX 100:
ETRAX will generate interrupt although there is no stop bit between the
characters.
Depending on how long the break sequence is, the end of the breaksequence
will look differently:
| indicates start/end of a character.
B= Break character (0x00) with framing error.
E= Error byte with parity error received after B characters.
F= "Faked" valid byte received immediately after B characters.
V= Valid byte
1.
B BL ___________________________ V
.._|__________|__________| |valid data |
Multiple frame errors with data == 0x00 (B),
the timing matches up "perfectly" so no extra ending char is detected.
The RXD pin is 1 in the last interrupt, in that case
we set info->errorcode = ERRCODE_INSERT_BREAK, but we can't really
know if another byte will come and this really is case 2. below
(e.g F=0xFF or 0xFE)
If RXD pin is 0 we can expect another character (see 2. below).
2.
B B E or F__________________..__ V
.._|__________|__________|______ | |valid data
"valid" or
parity error
Multiple frame errors with data == 0x00 (B),
but the part of the break trigs is interpreted as a start bit (and possibly
some 0 bits followed by a number of 1 bits and a stop bit).
Depending on parity settings etc. this last character can be either
a fake "valid" char (F) or have a parity error (E).
If the character is valid it will be put in the buffer,
we set info->errorcode = ERRCODE_SET_BREAK so the receive interrupt
will set the flags so the tty will handle it,
if it's an error byte it will not be put in the buffer
and we set info->errorcode = ERRCODE_INSERT_BREAK.
To distinguish a V byte in 1. from an F byte in 2. we keep a timestamp
of the last faulty char (B) and compares it with the current time:
If the time elapsed time is less then 2*char_time_usec we will assume
it's a faked F char and not a Valid char and set
info->errorcode = ERRCODE_SET_BREAK.
Flaws in the above solution:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We use the timer to distinguish a F character from a V character,
if a V character is to close after the break we might make the wrong decision.
TODO: The break will be delayed until an F or V character is received.
*/
static
struct e100_serial * handle_ser_rx_interrupt_no_dma(struct e100_serial *info)
{
unsigned long data_read;
struct tty_struct *tty = info->port.tty;
if (!tty) {
printk("!NO TTY!\n");
return info;
}
/* Read data and status at the same time */
data_read = *((unsigned long *)&info->ioport[REG_DATA_STATUS32]);
more_data:
if (data_read & IO_MASK(R_SERIAL0_READ, xoff_detect) ) {
DFLOW(DEBUG_LOG(info->line, "XOFF detect\n", 0));
}
DINTR2(DEBUG_LOG(info->line, "ser_rx %c\n", IO_EXTRACT(R_SERIAL0_READ, data_in, data_read)));
if (data_read & ( IO_MASK(R_SERIAL0_READ, framing_err) |
IO_MASK(R_SERIAL0_READ, par_err) |
IO_MASK(R_SERIAL0_READ, overrun) )) {
/* An error */
info->last_rx_active_usec = GET_JIFFIES_USEC();
info->last_rx_active = jiffies;
DINTR1(DEBUG_LOG(info->line, "ser_rx err stat_data %04X\n", data_read));
DLOG_INT_TRIG(
if (!log_int_trig1_pos) {
log_int_trig1_pos = log_int_pos;
log_int(rdpc(), 0, 0);
}
);
if ( ((data_read & IO_MASK(R_SERIAL0_READ, data_in)) == 0) &&
(data_read & IO_MASK(R_SERIAL0_READ, framing_err)) ) {
/* Most likely a break, but we get interrupts over and
* over again.
*/
if (!info->break_detected_cnt) {
DEBUG_LOG(info->line, "#BRK start\n", 0);
}
if (data_read & IO_MASK(R_SERIAL0_READ, rxd)) {
/* The RX pin is high now, so the break
* must be over, but....
* we can't really know if we will get another
* last byte ending the break or not.
* And we don't know if the byte (if any) will
* have an error or look valid.
*/
DEBUG_LOG(info->line, "# BL BRK\n", 0);
info->errorcode = ERRCODE_INSERT_BREAK;
}
info->break_detected_cnt++;
} else {
/* The error does not look like a break, but could be
* the end of one
*/
if (info->break_detected_cnt) {
DEBUG_LOG(info->line, "EBRK %i\n", info->break_detected_cnt);
info->errorcode = ERRCODE_INSERT_BREAK;
} else {
unsigned char data = IO_EXTRACT(R_SERIAL0_READ,
data_in, data_read);
char flag = TTY_NORMAL;
if (info->errorcode == ERRCODE_INSERT_BREAK) {
struct tty_struct *tty = info->port.tty;
tty_insert_flip_char(tty, 0, flag);
info->icount.rx++;
}
if (data_read & IO_MASK(R_SERIAL0_READ, par_err)) {
info->icount.parity++;
flag = TTY_PARITY;
} else if (data_read & IO_MASK(R_SERIAL0_READ, overrun)) {
info->icount.overrun++;
flag = TTY_OVERRUN;
} else if (data_read & IO_MASK(R_SERIAL0_READ, framing_err)) {
info->icount.frame++;
flag = TTY_FRAME;
}
tty_insert_flip_char(tty, data, flag);
info->errorcode = 0;
}
info->break_detected_cnt = 0;
}
} else if (data_read & IO_MASK(R_SERIAL0_READ, data_avail)) {
/* No error */
DLOG_INT_TRIG(
if (!log_int_trig1_pos) {
if (log_int_pos >= log_int_size) {
log_int_pos = 0;
}
log_int_trig0_pos = log_int_pos;
log_int(rdpc(), 0, 0);
}
);
tty_insert_flip_char(tty,
IO_EXTRACT(R_SERIAL0_READ, data_in, data_read),
TTY_NORMAL);
} else {
DEBUG_LOG(info->line, "ser_rx int but no data_avail %08lX\n", data_read);
}
info->icount.rx++;
data_read = *((unsigned long *)&info->ioport[REG_DATA_STATUS32]);
if (data_read & IO_MASK(R_SERIAL0_READ, data_avail)) {
DEBUG_LOG(info->line, "ser_rx %c in loop\n", IO_EXTRACT(R_SERIAL0_READ, data_in, data_read));
goto more_data;
}
tty_flip_buffer_push(info->port.tty);
return info;
}
static struct e100_serial* handle_ser_rx_interrupt(struct e100_serial *info)
{
unsigned char rstat;
#ifdef SERIAL_DEBUG_INTR
printk("Interrupt from serport %d\n", i);
#endif
/* DEBUG_LOG(info->line, "ser_interrupt stat %03X\n", rstat | (i << 8)); */
if (!info->uses_dma_in) {
return handle_ser_rx_interrupt_no_dma(info);
}
/* DMA is used */
rstat = info->ioport[REG_STATUS];
if (rstat & IO_MASK(R_SERIAL0_STATUS, xoff_detect) ) {
DFLOW(DEBUG_LOG(info->line, "XOFF detect\n", 0));
}
if (rstat & SER_ERROR_MASK) {
unsigned char data;
info->last_rx_active_usec = GET_JIFFIES_USEC();
info->last_rx_active = jiffies;
/* If we got an error, we must reset it by reading the
* data_in field
*/
data = info->ioport[REG_DATA];
DINTR1(DEBUG_LOG(info->line, "ser_rx! %c\n", data));
DINTR1(DEBUG_LOG(info->line, "ser_rx err stat %02X\n", rstat));
if (!data && (rstat & SER_FRAMING_ERR_MASK)) {
/* Most likely a break, but we get interrupts over and
* over again.
*/
if (!info->break_detected_cnt) {
DEBUG_LOG(info->line, "#BRK start\n", 0);
}
if (rstat & SER_RXD_MASK) {
/* The RX pin is high now, so the break
* must be over, but....
* we can't really know if we will get another
* last byte ending the break or not.
* And we don't know if the byte (if any) will
* have an error or look valid.
*/
DEBUG_LOG(info->line, "# BL BRK\n", 0);
info->errorcode = ERRCODE_INSERT_BREAK;
}
info->break_detected_cnt++;
} else {
/* The error does not look like a break, but could be
* the end of one
*/
if (info->break_detected_cnt) {
DEBUG_LOG(info->line, "EBRK %i\n", info->break_detected_cnt);
info->errorcode = ERRCODE_INSERT_BREAK;
} else {
if (info->errorcode == ERRCODE_INSERT_BREAK) {
info->icount.brk++;
add_char_and_flag(info, '\0', TTY_BREAK);
}
if (rstat & SER_PAR_ERR_MASK) {
info->icount.parity++;
add_char_and_flag(info, data, TTY_PARITY);
} else if (rstat & SER_OVERRUN_MASK) {
info->icount.overrun++;
add_char_and_flag(info, data, TTY_OVERRUN);
} else if (rstat & SER_FRAMING_ERR_MASK) {
info->icount.frame++;
add_char_and_flag(info, data, TTY_FRAME);
}
info->errorcode = 0;
}
info->break_detected_cnt = 0;
DEBUG_LOG(info->line, "#iERR s d %04X\n",
((rstat & SER_ERROR_MASK) << 8) | data);
}
PROCSTAT(ser_stat[info->line].early_errors_cnt++);
} else { /* It was a valid byte, now let the DMA do the rest */
unsigned long curr_time_u = GET_JIFFIES_USEC();
unsigned long curr_time = jiffies;
if (info->break_detected_cnt) {
/* Detect if this character is a new valid char or the
* last char in a break sequence: If LSBits are 0 and
* MSBits are high AND the time is close to the
* previous interrupt we should discard it.
*/
long elapsed_usec =
(curr_time - info->last_rx_active) * (1000000/HZ) +
curr_time_u - info->last_rx_active_usec;
if (elapsed_usec < 2*info->char_time_usec) {
DEBUG_LOG(info->line, "FBRK %i\n", info->line);
/* Report as BREAK (error) and let
* receive_chars_dma() handle it
*/
info->errorcode = ERRCODE_SET_BREAK;
} else {
DEBUG_LOG(info->line, "Not end of BRK (V)%i\n", info->line);
}
DEBUG_LOG(info->line, "num brk %i\n", info->break_detected_cnt);
}
#ifdef SERIAL_DEBUG_INTR
printk("** OK, disabling ser_interrupts\n");
#endif
e100_disable_serial_data_irq(info);
DINTR2(DEBUG_LOG(info->line, "ser_rx OK %d\n", info->line));
info->break_detected_cnt = 0;
PROCSTAT(ser_stat[info->line].ser_ints_ok_cnt++);
}
/* Restarting the DMA never hurts */
*info->icmdadr = IO_STATE(R_DMA_CH6_CMD, cmd, restart);
START_FLUSH_FAST_TIMER(info, "ser_int");
return info;
} /* handle_ser_rx_interrupt */
static void handle_ser_tx_interrupt(struct e100_serial *info)
{
unsigned long flags;
if (info->x_char) {
unsigned char rstat;
DFLOW(DEBUG_LOG(info->line, "tx_int: xchar 0x%02X\n", info->x_char));
local_irq_save(flags);
rstat = info->ioport[REG_STATUS];
DFLOW(DEBUG_LOG(info->line, "stat %x\n", rstat));
info->ioport[REG_TR_DATA] = info->x_char;
info->icount.tx++;
info->x_char = 0;
/* We must enable since it is disabled in ser_interrupt */
e100_enable_serial_tx_ready_irq(info);
local_irq_restore(flags);
return;
}
if (info->uses_dma_out) {
unsigned char rstat;
int i;
/* We only use normal tx interrupt when sending x_char */
DFLOW(DEBUG_LOG(info->line, "tx_int: xchar sent\n", 0));
local_irq_save(flags);
rstat = info->ioport[REG_STATUS];
DFLOW(DEBUG_LOG(info->line, "stat %x\n", rstat));
e100_disable_serial_tx_ready_irq(info);
if (info->port.tty->stopped)
rs_stop(info->port.tty);
/* Enable the DMA channel and tell it to continue */
e100_enable_txdma_channel(info);
/* Wait 12 cycles before doing the DMA command */
for(i = 6; i > 0; i--)
nop();
*info->ocmdadr = IO_STATE(R_DMA_CH6_CMD, cmd, continue);
local_irq_restore(flags);
return;
}
/* Normal char-by-char interrupt */
if (info->xmit.head == info->xmit.tail
|| info->port.tty->stopped
|| info->port.tty->hw_stopped) {
DFLOW(DEBUG_LOG(info->line, "tx_int: stopped %i\n",
info->port.tty->stopped));
e100_disable_serial_tx_ready_irq(info);
info->tr_running = 0;
return;
}
DINTR2(DEBUG_LOG(info->line, "tx_int %c\n", info->xmit.buf[info->xmit.tail]));
/* Send a byte, rs485 timing is critical so turn of ints */
local_irq_save(flags);
info->ioport[REG_TR_DATA] = info->xmit.buf[info->xmit.tail];
info->xmit.tail = (info->xmit.tail + 1) & (SERIAL_XMIT_SIZE-1);
info->icount.tx++;
if (info->xmit.head == info->xmit.tail) {
#if defined(CONFIG_ETRAX_RS485) && defined(CONFIG_ETRAX_FAST_TIMER)
if (info->rs485.flags & SER_RS485_ENABLED) {
/* Set a short timer to toggle RTS */
start_one_shot_timer(&fast_timers_rs485[info->line],
rs485_toggle_rts_timer_function,
(unsigned long)info,
info->char_time_usec*2,
"RS-485");
}
#endif /* RS485 */
info->last_tx_active_usec = GET_JIFFIES_USEC();
info->last_tx_active = jiffies;
e100_disable_serial_tx_ready_irq(info);
info->tr_running = 0;
DFLOW(DEBUG_LOG(info->line, "tx_int: stop2\n", 0));
} else {
/* We must enable since it is disabled in ser_interrupt */
e100_enable_serial_tx_ready_irq(info);
}
local_irq_restore(flags);
if (CIRC_CNT(info->xmit.head,
info->xmit.tail,
SERIAL_XMIT_SIZE) < WAKEUP_CHARS)
rs_sched_event(info, RS_EVENT_WRITE_WAKEUP);
} /* handle_ser_tx_interrupt */
/* result of time measurements:
* RX duration 54-60 us when doing something, otherwise 6-9 us
* ser_int duration: just sending: 8-15 us normally, up to 73 us
*/
static irqreturn_t
ser_interrupt(int irq, void *dev_id)
{
static volatile int tx_started = 0;
struct e100_serial *info;
int i;
unsigned long flags;
unsigned long irq_mask1_rd;
unsigned long data_mask = (1 << (8+2*0)); /* ser0 data_avail */
int handled = 0;
static volatile unsigned long reentered_ready_mask = 0;
local_irq_save(flags);
irq_mask1_rd = *R_IRQ_MASK1_RD;
/* First handle all rx interrupts with ints disabled */
info = rs_table;
irq_mask1_rd &= e100_ser_int_mask;
for (i = 0; i < NR_PORTS; i++) {
/* Which line caused the data irq? */
if (irq_mask1_rd & data_mask) {
handled = 1;
handle_ser_rx_interrupt(info);
}
info += 1;
data_mask <<= 2;
}
/* Handle tx interrupts with interrupts enabled so we
* can take care of new data interrupts while transmitting
* We protect the tx part with the tx_started flag.
* We disable the tr_ready interrupts we are about to handle and
* unblock the serial interrupt so new serial interrupts may come.
*
* If we get a new interrupt:
* - it migth be due to synchronous serial ports.
* - serial irq will be blocked by general irq handler.
* - async data will be handled above (sync will be ignored).
* - tx_started flag will prevent us from trying to send again and
* we will exit fast - no need to unblock serial irq.
* - Next (sync) serial interrupt handler will be runned with
* disabled interrupt due to restore_flags() at end of function,
* so sync handler will not be preempted or reentered.
*/
if (!tx_started) {
unsigned long ready_mask;
unsigned long
tx_started = 1;
/* Only the tr_ready interrupts left */
irq_mask1_rd &= (IO_MASK(R_IRQ_MASK1_RD, ser0_ready) |
IO_MASK(R_IRQ_MASK1_RD, ser1_ready) |
IO_MASK(R_IRQ_MASK1_RD, ser2_ready) |
IO_MASK(R_IRQ_MASK1_RD, ser3_ready));
while (irq_mask1_rd) {
/* Disable those we are about to handle */
*R_IRQ_MASK1_CLR = irq_mask1_rd;
/* Unblock the serial interrupt */
*R_VECT_MASK_SET = IO_STATE(R_VECT_MASK_SET, serial, set);
local_irq_enable();
ready_mask = (1 << (8+1+2*0)); /* ser0 tr_ready */
info = rs_table;
for (i = 0; i < NR_PORTS; i++) {
/* Which line caused the ready irq? */
if (irq_mask1_rd & ready_mask) {
handled = 1;
handle_ser_tx_interrupt(info);
}
info += 1;
ready_mask <<= 2;
}
/* handle_ser_tx_interrupt enables tr_ready interrupts */
local_irq_disable();
/* Handle reentered TX interrupt */
irq_mask1_rd = reentered_ready_mask;
}
local_irq_disable();
tx_started = 0;
} else {
unsigned long ready_mask;
ready_mask = irq_mask1_rd & (IO_MASK(R_IRQ_MASK1_RD, ser0_ready) |
IO_MASK(R_IRQ_MASK1_RD, ser1_ready) |
IO_MASK(R_IRQ_MASK1_RD, ser2_ready) |
IO_MASK(R_IRQ_MASK1_RD, ser3_ready));
if (ready_mask) {
reentered_ready_mask |= ready_mask;
/* Disable those we are about to handle */
*R_IRQ_MASK1_CLR = ready_mask;
DFLOW(DEBUG_LOG(SERIAL_DEBUG_LINE, "ser_int reentered with TX %X\n", ready_mask));
}
}
local_irq_restore(flags);
return IRQ_RETVAL(handled);
} /* ser_interrupt */
#endif
/*
* -------------------------------------------------------------------
* Here ends the serial interrupt routines.
* -------------------------------------------------------------------
*/
/*
* This routine is used to handle the "bottom half" processing for the
* serial driver, known also the "software interrupt" processing.
* This processing is done at the kernel interrupt level, after the
* rs_interrupt() has returned, BUT WITH INTERRUPTS TURNED ON. This
* is where time-consuming activities which can not be done in the
* interrupt driver proper are done; the interrupt driver schedules
* them using rs_sched_event(), and they get done here.
*/
static void
do_softint(struct work_struct *work)
{
struct e100_serial *info;
struct tty_struct *tty;
info = container_of(work, struct e100_serial, work);
tty = info->port.tty;
if (!tty)
return;
if (test_and_clear_bit(RS_EVENT_WRITE_WAKEUP, &info->event))
tty_wakeup(tty);
}
static int
startup(struct e100_serial * info)
{
unsigned long flags;
unsigned long xmit_page;
int i;
xmit_page = get_zeroed_page(GFP_KERNEL);
if (!xmit_page)
return -ENOMEM;
local_irq_save(flags);
/* if it was already initialized, skip this */
if (info->flags & ASYNC_INITIALIZED) {
local_irq_restore(flags);
free_page(xmit_page);
return 0;
}
if (info->xmit.buf)
free_page(xmit_page);
else
info->xmit.buf = (unsigned char *) xmit_page;
#ifdef SERIAL_DEBUG_OPEN
printk("starting up ttyS%d (xmit_buf 0x%p)...\n", info->line, info->xmit.buf);
#endif
#ifdef CONFIG_SVINTO_SIM
/* Bits and pieces collected from below. Better to have them
in one ifdef:ed clause than to mix in a lot of ifdefs,
right? */
if (info->port.tty)
clear_bit(TTY_IO_ERROR, &info->port.tty->flags);
info->xmit.head = info->xmit.tail = 0;
info->first_recv_buffer = info->last_recv_buffer = NULL;
info->recv_cnt = info->max_recv_cnt = 0;
for (i = 0; i < SERIAL_RECV_DESCRIPTORS; i++)
info->rec_descr[i].buf = NULL;
/* No real action in the simulator, but may set info important
to ioctl. */
change_speed(info);
#else
/*
* Clear the FIFO buffers and disable them
* (they will be reenabled in change_speed())
*/
/*
* Reset the DMA channels and make sure their interrupts are cleared
*/
if (info->dma_in_enabled) {
info->uses_dma_in = 1;
e100_enable_rxdma_channel(info);
*info->icmdadr = IO_STATE(R_DMA_CH6_CMD, cmd, reset);
/* Wait until reset cycle is complete */
while (IO_EXTRACT(R_DMA_CH6_CMD, cmd, *info->icmdadr) ==
IO_STATE_VALUE(R_DMA_CH6_CMD, cmd, reset));
/* Make sure the irqs are cleared */
*info->iclrintradr =
IO_STATE(R_DMA_CH6_CLR_INTR, clr_descr, do) |
IO_STATE(R_DMA_CH6_CLR_INTR, clr_eop, do);
} else {
e100_disable_rxdma_channel(info);
}
if (info->dma_out_enabled) {
info->uses_dma_out = 1;
e100_enable_txdma_channel(info);
*info->ocmdadr = IO_STATE(R_DMA_CH6_CMD, cmd, reset);
while (IO_EXTRACT(R_DMA_CH6_CMD, cmd, *info->ocmdadr) ==
IO_STATE_VALUE(R_DMA_CH6_CMD, cmd, reset));
/* Make sure the irqs are cleared */
*info->oclrintradr =
IO_STATE(R_DMA_CH6_CLR_INTR, clr_descr, do) |
IO_STATE(R_DMA_CH6_CLR_INTR, clr_eop, do);
} else {
e100_disable_txdma_channel(info);
}
if (info->port.tty)
clear_bit(TTY_IO_ERROR, &info->port.tty->flags);
info->xmit.head = info->xmit.tail = 0;
info->first_recv_buffer = info->last_recv_buffer = NULL;
info->recv_cnt = info->max_recv_cnt = 0;
for (i = 0; i < SERIAL_RECV_DESCRIPTORS; i++)
info->rec_descr[i].buf = 0;
/*
* and set the speed and other flags of the serial port
* this will start the rx/tx as well
*/
#ifdef SERIAL_HANDLE_EARLY_ERRORS
e100_enable_serial_data_irq(info);
#endif
change_speed(info);
/* dummy read to reset any serial errors */
(void)info->ioport[REG_DATA];
/* enable the interrupts */
if (info->uses_dma_out)
e100_enable_txdma_irq(info);
e100_enable_rx_irq(info);
info->tr_running = 0; /* to be sure we don't lock up the transmitter */
/* setup the dma input descriptor and start dma */
start_receive(info);
/* for safety, make sure the descriptors last result is 0 bytes written */
info->tr_descr.sw_len = 0;
info->tr_descr.hw_len = 0;
info->tr_descr.status = 0;
/* enable RTS/DTR last */
e100_rts(info, 1);
e100_dtr(info, 1);
#endif /* CONFIG_SVINTO_SIM */
info->flags |= ASYNC_INITIALIZED;
local_irq_restore(flags);
return 0;
}
/*
* This routine will shutdown a serial port; interrupts are disabled, and
* DTR is dropped if the hangup on close termio flag is on.
*/
static void
shutdown(struct e100_serial * info)
{
unsigned long flags;
struct etrax_dma_descr *descr = info->rec_descr;
struct etrax_recv_buffer *buffer;
int i;
#ifndef CONFIG_SVINTO_SIM
/* shut down the transmitter and receiver */
DFLOW(DEBUG_LOG(info->line, "shutdown %i\n", info->line));
e100_disable_rx(info);
info->ioport[REG_TR_CTRL] = (info->tx_ctrl &= ~0x40);
/* disable interrupts, reset dma channels */
if (info->uses_dma_in) {
e100_disable_rxdma_irq(info);
*info->icmdadr = IO_STATE(R_DMA_CH6_CMD, cmd, reset);
info->uses_dma_in = 0;
} else {
e100_disable_serial_data_irq(info);
}
if (info->uses_dma_out) {
e100_disable_txdma_irq(info);
info->tr_running = 0;
*info->ocmdadr = IO_STATE(R_DMA_CH6_CMD, cmd, reset);
info->uses_dma_out = 0;
} else {
e100_disable_serial_tx_ready_irq(info);
info->tr_running = 0;
}
#endif /* CONFIG_SVINTO_SIM */
if (!(info->flags & ASYNC_INITIALIZED))
return;
#ifdef SERIAL_DEBUG_OPEN
printk("Shutting down serial port %d (irq %d)....\n", info->line,
info->irq);
#endif
local_irq_save(flags);
if (info->xmit.buf) {
free_page((unsigned long)info->xmit.buf);
info->xmit.buf = NULL;
}
for (i = 0; i < SERIAL_RECV_DESCRIPTORS; i++)
if (descr[i].buf) {
buffer = phys_to_virt(descr[i].buf) - sizeof *buffer;
kfree(buffer);
descr[i].buf = 0;
}
if (!info->port.tty || (info->port.tty->termios->c_cflag & HUPCL)) {
/* hang up DTR and RTS if HUPCL is enabled */
e100_dtr(info, 0);
e100_rts(info, 0); /* could check CRTSCTS before doing this */
}
if (info->port.tty)
set_bit(TTY_IO_ERROR, &info->port.tty->flags);
info->flags &= ~ASYNC_INITIALIZED;
local_irq_restore(flags);
}
/* change baud rate and other assorted parameters */
static void
change_speed(struct e100_serial *info)
{
unsigned int cflag;
unsigned long xoff;
unsigned long flags;
/* first some safety checks */
if (!info->port.tty || !info->port.tty->termios)
return;
if (!info->ioport)
return;
cflag = info->port.tty->termios->c_cflag;
/* possibly, the tx/rx should be disabled first to do this safely */
/* change baud-rate and write it to the hardware */
if ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_CUST) {
/* Special baudrate */
u32 mask = 0xFF << (info->line*8); /* Each port has 8 bits */
unsigned long alt_source =
IO_STATE(R_ALT_SER_BAUDRATE, ser0_rec, normal) |
IO_STATE(R_ALT_SER_BAUDRATE, ser0_tr, normal);
/* R_ALT_SER_BAUDRATE selects the source */
DBAUD(printk("Custom baudrate: baud_base/divisor %lu/%i\n",
(unsigned long)info->baud_base, info->custom_divisor));
if (info->baud_base == SERIAL_PRESCALE_BASE) {
/* 0, 2-65535 (0=65536) */
u16 divisor = info->custom_divisor;
/* R_SERIAL_PRESCALE (upper 16 bits of R_CLOCK_PRESCALE) */
/* baudrate is 3.125MHz/custom_divisor */
alt_source =
IO_STATE(R_ALT_SER_BAUDRATE, ser0_rec, prescale) |
IO_STATE(R_ALT_SER_BAUDRATE, ser0_tr, prescale);
alt_source = 0x11;
DBAUD(printk("Writing SERIAL_PRESCALE: divisor %i\n", divisor));
*R_SERIAL_PRESCALE = divisor;
info->baud = SERIAL_PRESCALE_BASE/divisor;
}
#ifdef CONFIG_ETRAX_EXTERN_PB6CLK_ENABLED
else if ((info->baud_base==CONFIG_ETRAX_EXTERN_PB6CLK_FREQ/8 &&
info->custom_divisor == 1) ||
(info->baud_base==CONFIG_ETRAX_EXTERN_PB6CLK_FREQ &&
info->custom_divisor == 8)) {
/* ext_clk selected */
alt_source =
IO_STATE(R_ALT_SER_BAUDRATE, ser0_rec, extern) |
IO_STATE(R_ALT_SER_BAUDRATE, ser0_tr, extern);
DBAUD(printk("using external baudrate: %lu\n", CONFIG_ETRAX_EXTERN_PB6CLK_FREQ/8));
info->baud = CONFIG_ETRAX_EXTERN_PB6CLK_FREQ/8;
}
#endif
else
{
/* Bad baudbase, we don't support using timer0
* for baudrate.
*/
printk(KERN_WARNING "Bad baud_base/custom_divisor: %lu/%i\n",
(unsigned long)info->baud_base, info->custom_divisor);
}
r_alt_ser_baudrate_shadow &= ~mask;
r_alt_ser_baudrate_shadow |= (alt_source << (info->line*8));
*R_ALT_SER_BAUDRATE = r_alt_ser_baudrate_shadow;
} else {
/* Normal baudrate */
/* Make sure we use normal baudrate */
u32 mask = 0xFF << (info->line*8); /* Each port has 8 bits */
unsigned long alt_source =
IO_STATE(R_ALT_SER_BAUDRATE, ser0_rec, normal) |
IO_STATE(R_ALT_SER_BAUDRATE, ser0_tr, normal);
r_alt_ser_baudrate_shadow &= ~mask;
r_alt_ser_baudrate_shadow |= (alt_source << (info->line*8));
#ifndef CONFIG_SVINTO_SIM
*R_ALT_SER_BAUDRATE = r_alt_ser_baudrate_shadow;
#endif /* CONFIG_SVINTO_SIM */
info->baud = cflag_to_baud(cflag);
#ifndef CONFIG_SVINTO_SIM
info->ioport[REG_BAUD] = cflag_to_etrax_baud(cflag);
#endif /* CONFIG_SVINTO_SIM */
}
#ifndef CONFIG_SVINTO_SIM
/* start with default settings and then fill in changes */
local_irq_save(flags);
/* 8 bit, no/even parity */
info->rx_ctrl &= ~(IO_MASK(R_SERIAL0_REC_CTRL, rec_bitnr) |
IO_MASK(R_SERIAL0_REC_CTRL, rec_par_en) |
IO_MASK(R_SERIAL0_REC_CTRL, rec_par));
/* 8 bit, no/even parity, 1 stop bit, no cts */
info->tx_ctrl &= ~(IO_MASK(R_SERIAL0_TR_CTRL, tr_bitnr) |
IO_MASK(R_SERIAL0_TR_CTRL, tr_par_en) |
IO_MASK(R_SERIAL0_TR_CTRL, tr_par) |
IO_MASK(R_SERIAL0_TR_CTRL, stop_bits) |
IO_MASK(R_SERIAL0_TR_CTRL, auto_cts));
if ((cflag & CSIZE) == CS7) {
/* set 7 bit mode */
info->tx_ctrl |= IO_STATE(R_SERIAL0_TR_CTRL, tr_bitnr, tr_7bit);
info->rx_ctrl |= IO_STATE(R_SERIAL0_REC_CTRL, rec_bitnr, rec_7bit);
}
if (cflag & CSTOPB) {
/* set 2 stop bit mode */
info->tx_ctrl |= IO_STATE(R_SERIAL0_TR_CTRL, stop_bits, two_bits);
}
if (cflag & PARENB) {
/* enable parity */
info->tx_ctrl |= IO_STATE(R_SERIAL0_TR_CTRL, tr_par_en, enable);
info->rx_ctrl |= IO_STATE(R_SERIAL0_REC_CTRL, rec_par_en, enable);
}
if (cflag & CMSPAR) {
/* enable stick parity, PARODD mean Mark which matches ETRAX */
info->tx_ctrl |= IO_STATE(R_SERIAL0_TR_CTRL, tr_stick_par, stick);
info->rx_ctrl |= IO_STATE(R_SERIAL0_REC_CTRL, rec_stick_par, stick);
}
if (cflag & PARODD) {
/* set odd parity (or Mark if CMSPAR) */
info->tx_ctrl |= IO_STATE(R_SERIAL0_TR_CTRL, tr_par, odd);
info->rx_ctrl |= IO_STATE(R_SERIAL0_REC_CTRL, rec_par, odd);
}
if (cflag & CRTSCTS) {
/* enable automatic CTS handling */
DFLOW(DEBUG_LOG(info->line, "FLOW auto_cts enabled\n", 0));
info->tx_ctrl |= IO_STATE(R_SERIAL0_TR_CTRL, auto_cts, active);
}
/* make sure the tx and rx are enabled */
info->tx_ctrl |= IO_STATE(R_SERIAL0_TR_CTRL, tr_enable, enable);
info->rx_ctrl |= IO_STATE(R_SERIAL0_REC_CTRL, rec_enable, enable);
/* actually write the control regs to the hardware */
info->ioport[REG_TR_CTRL] = info->tx_ctrl;
info->ioport[REG_REC_CTRL] = info->rx_ctrl;
xoff = IO_FIELD(R_SERIAL0_XOFF, xoff_char, STOP_CHAR(info->port.tty));
xoff |= IO_STATE(R_SERIAL0_XOFF, tx_stop, enable);
if (info->port.tty->termios->c_iflag & IXON ) {
DFLOW(DEBUG_LOG(info->line, "FLOW XOFF enabled 0x%02X\n",
STOP_CHAR(info->port.tty)));
xoff |= IO_STATE(R_SERIAL0_XOFF, auto_xoff, enable);
}
*((unsigned long *)&info->ioport[REG_XOFF]) = xoff;
local_irq_restore(flags);
#endif /* !CONFIG_SVINTO_SIM */
update_char_time(info);
} /* change_speed */
/* start transmitting chars NOW */
static void
rs_flush_chars(struct tty_struct *tty)
{
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
unsigned long flags;
if (info->tr_running ||
info->xmit.head == info->xmit.tail ||
tty->stopped ||
tty->hw_stopped ||
!info->xmit.buf)
return;
#ifdef SERIAL_DEBUG_FLOW
printk("rs_flush_chars\n");
#endif
/* this protection might not exactly be necessary here */
local_irq_save(flags);
start_transmit(info);
local_irq_restore(flags);
}
static int rs_raw_write(struct tty_struct *tty,
const unsigned char *buf, int count)
{
int c, ret = 0;
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
unsigned long flags;
/* first some sanity checks */
if (!tty || !info->xmit.buf)
return 0;
#ifdef SERIAL_DEBUG_DATA
if (info->line == SERIAL_DEBUG_LINE)
printk("rs_raw_write (%d), status %d\n",
count, info->ioport[REG_STATUS]);
#endif
#ifdef CONFIG_SVINTO_SIM
/* Really simple. The output is here and now. */
SIMCOUT(buf, count);
return count;
#endif
local_save_flags(flags);
DFLOW(DEBUG_LOG(info->line, "write count %i ", count));
DFLOW(DEBUG_LOG(info->line, "ldisc %i\n", tty->ldisc.chars_in_buffer(tty)));
/* The local_irq_disable/restore_flags pairs below are needed
* because the DMA interrupt handler moves the info->xmit values.
* the memcpy needs to be in the critical region unfortunately,
* because we need to read xmit values, memcpy, write xmit values
* in one atomic operation... this could perhaps be avoided by
* more clever design.
*/
local_irq_disable();
while (count) {
c = CIRC_SPACE_TO_END(info->xmit.head,
info->xmit.tail,
SERIAL_XMIT_SIZE);
if (count < c)
c = count;
if (c <= 0)
break;
memcpy(info->xmit.buf + info->xmit.head, buf, c);
info->xmit.head = (info->xmit.head + c) &
(SERIAL_XMIT_SIZE-1);
buf += c;
count -= c;
ret += c;
}
local_irq_restore(flags);
/* enable transmitter if not running, unless the tty is stopped
* this does not need IRQ protection since if tr_running == 0
* the IRQ's are not running anyway for this port.
*/
DFLOW(DEBUG_LOG(info->line, "write ret %i\n", ret));
if (info->xmit.head != info->xmit.tail &&
!tty->stopped &&
!tty->hw_stopped &&
!info->tr_running) {
start_transmit(info);
}
return ret;
} /* raw_raw_write() */
static int
rs_write(struct tty_struct *tty,
const unsigned char *buf, int count)
{
#if defined(CONFIG_ETRAX_RS485)
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
if (info->rs485.flags & SER_RS485_ENABLED)
{
/* If we are in RS-485 mode, we need to toggle RTS and disable
* the receiver before initiating a DMA transfer
*/
#ifdef CONFIG_ETRAX_FAST_TIMER
/* Abort any started timer */
fast_timers_rs485[info->line].function = NULL;
del_fast_timer(&fast_timers_rs485[info->line]);
#endif
e100_rts(info, (info->rs485.flags & SER_RS485_RTS_ON_SEND));
#if defined(CONFIG_ETRAX_RS485_DISABLE_RECEIVER)
e100_disable_rx(info);
e100_enable_rx_irq(info);
#endif
if (info->rs485.delay_rts_before_send > 0)
msleep(info->rs485.delay_rts_before_send);
}
#endif /* CONFIG_ETRAX_RS485 */
count = rs_raw_write(tty, buf, count);
#if defined(CONFIG_ETRAX_RS485)
if (info->rs485.flags & SER_RS485_ENABLED)
{
unsigned int val;
/* If we are in RS-485 mode the following has to be done:
* wait until DMA is ready
* wait on transmit shift register
* toggle RTS
* enable the receiver
*/
/* Sleep until all sent */
tty_wait_until_sent(tty, 0);
#ifdef CONFIG_ETRAX_FAST_TIMER
/* Now sleep a little more so that shift register is empty */
schedule_usleep(info->char_time_usec * 2);
#endif
/* wait on transmit shift register */
do{
get_lsr_info(info, &val);
}while (!(val & TIOCSER_TEMT));
e100_rts(info, (info->rs485.flags & SER_RS485_RTS_AFTER_SEND));
#if defined(CONFIG_ETRAX_RS485_DISABLE_RECEIVER)
e100_enable_rx(info);
e100_enable_rxdma_irq(info);
#endif
}
#endif /* CONFIG_ETRAX_RS485 */
return count;
} /* rs_write */
/* how much space is available in the xmit buffer? */
static int
rs_write_room(struct tty_struct *tty)
{
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
return CIRC_SPACE(info->xmit.head, info->xmit.tail, SERIAL_XMIT_SIZE);
}
/* How many chars are in the xmit buffer?
* This does not include any chars in the transmitter FIFO.
* Use wait_until_sent for waiting for FIFO drain.
*/
static int
rs_chars_in_buffer(struct tty_struct *tty)
{
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
return CIRC_CNT(info->xmit.head, info->xmit.tail, SERIAL_XMIT_SIZE);
}
/* discard everything in the xmit buffer */
static void
rs_flush_buffer(struct tty_struct *tty)
{
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
unsigned long flags;
local_irq_save(flags);
info->xmit.head = info->xmit.tail = 0;
local_irq_restore(flags);
tty_wakeup(tty);
}
/*
* This function is used to send a high-priority XON/XOFF character to
* the device
*
* Since we use DMA we don't check for info->x_char in transmit_chars_dma(),
* but we do it in handle_ser_tx_interrupt().
* We disable DMA channel and enable tx ready interrupt and write the
* character when possible.
*/
static void rs_send_xchar(struct tty_struct *tty, char ch)
{
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
unsigned long flags;
local_irq_save(flags);
if (info->uses_dma_out) {
/* Put the DMA on hold and disable the channel */
*info->ocmdadr = IO_STATE(R_DMA_CH6_CMD, cmd, hold);
while (IO_EXTRACT(R_DMA_CH6_CMD, cmd, *info->ocmdadr) !=
IO_STATE_VALUE(R_DMA_CH6_CMD, cmd, hold));
e100_disable_txdma_channel(info);
}
/* Must make sure transmitter is not stopped before we can transmit */
if (tty->stopped)
rs_start(tty);
/* Enable manual transmit interrupt and send from there */
DFLOW(DEBUG_LOG(info->line, "rs_send_xchar 0x%02X\n", ch));
info->x_char = ch;
e100_enable_serial_tx_ready_irq(info);
local_irq_restore(flags);
}
/*
* ------------------------------------------------------------
* rs_throttle()
*
* This routine is called by the upper-layer tty layer to signal that
* incoming characters should be throttled.
* ------------------------------------------------------------
*/
static void
rs_throttle(struct tty_struct * tty)
{
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
#ifdef SERIAL_DEBUG_THROTTLE
char buf[64];
printk("throttle %s: %lu....\n", tty_name(tty, buf),
(unsigned long)tty->ldisc.chars_in_buffer(tty));
#endif
DFLOW(DEBUG_LOG(info->line,"rs_throttle %lu\n", tty->ldisc.chars_in_buffer(tty)));
/* Do RTS before XOFF since XOFF might take some time */
if (tty->termios->c_cflag & CRTSCTS) {
/* Turn off RTS line */
e100_rts(info, 0);
}
if (I_IXOFF(tty))
rs_send_xchar(tty, STOP_CHAR(tty));
}
static void
rs_unthrottle(struct tty_struct * tty)
{
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
#ifdef SERIAL_DEBUG_THROTTLE
char buf[64];
printk("unthrottle %s: %lu....\n", tty_name(tty, buf),
(unsigned long)tty->ldisc.chars_in_buffer(tty));
#endif
DFLOW(DEBUG_LOG(info->line,"rs_unthrottle ldisc %d\n", tty->ldisc.chars_in_buffer(tty)));
DFLOW(DEBUG_LOG(info->line,"rs_unthrottle flip.count: %i\n", tty->flip.count));
/* Do RTS before XOFF since XOFF might take some time */
if (tty->termios->c_cflag & CRTSCTS) {
/* Assert RTS line */
e100_rts(info, 1);
}
if (I_IXOFF(tty)) {
if (info->x_char)
info->x_char = 0;
else
rs_send_xchar(tty, START_CHAR(tty));
}
}
/*
* ------------------------------------------------------------
* rs_ioctl() and friends
* ------------------------------------------------------------
*/
static int
get_serial_info(struct e100_serial * info,
struct serial_struct * retinfo)
{
struct serial_struct tmp;
/* this is all probably wrong, there are a lot of fields
* here that we don't have in e100_serial and maybe we
* should set them to something else than 0.
*/
if (!retinfo)
return -EFAULT;
memset(&tmp, 0, sizeof(tmp));
tmp.type = info->type;
tmp.line = info->line;
tmp.port = (int)info->ioport;
tmp.irq = info->irq;
tmp.flags = info->flags;
tmp.baud_base = info->baud_base;
tmp.close_delay = info->close_delay;
tmp.closing_wait = info->closing_wait;
tmp.custom_divisor = info->custom_divisor;
if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
return -EFAULT;
return 0;
}
static int
set_serial_info(struct e100_serial *info,
struct serial_struct *new_info)
{
struct serial_struct new_serial;
struct e100_serial old_info;
int retval = 0;
if (copy_from_user(&new_serial, new_info, sizeof(new_serial)))
return -EFAULT;
old_info = *info;
if (!capable(CAP_SYS_ADMIN)) {
if ((new_serial.type != info->type) ||
(new_serial.close_delay != info->close_delay) ||
((new_serial.flags & ~ASYNC_USR_MASK) !=
(info->flags & ~ASYNC_USR_MASK)))
return -EPERM;
info->flags = ((info->flags & ~ASYNC_USR_MASK) |
(new_serial.flags & ASYNC_USR_MASK));
goto check_and_exit;
}
if (info->count > 1)
return -EBUSY;
/*
* OK, past this point, all the error checking has been done.
* At this point, we start making changes.....
*/
info->baud_base = new_serial.baud_base;
info->flags = ((info->flags & ~ASYNC_FLAGS) |
(new_serial.flags & ASYNC_FLAGS));
info->custom_divisor = new_serial.custom_divisor;
info->type = new_serial.type;
info->close_delay = new_serial.close_delay;
info->closing_wait = new_serial.closing_wait;
info->port.tty->low_latency = (info->flags & ASYNC_LOW_LATENCY) ? 1 : 0;
check_and_exit:
if (info->flags & ASYNC_INITIALIZED) {
change_speed(info);
} else
retval = startup(info);
return retval;
}
/*
* get_lsr_info - get line status register info
*
* Purpose: Let user call ioctl() to get info when the UART physically
* is emptied. On bus types like RS485, the transmitter must
* release the bus after transmitting. This must be done when
* the transmit shift register is empty, not be done when the
* transmit holding register is empty. This functionality
* allows an RS485 driver to be written in user space.
*/
static int
get_lsr_info(struct e100_serial * info, unsigned int *value)
{
unsigned int result = TIOCSER_TEMT;
#ifndef CONFIG_SVINTO_SIM
unsigned long curr_time = jiffies;
unsigned long curr_time_usec = GET_JIFFIES_USEC();
unsigned long elapsed_usec =
(curr_time - info->last_tx_active) * 1000000/HZ +
curr_time_usec - info->last_tx_active_usec;
if (info->xmit.head != info->xmit.tail ||
elapsed_usec < 2*info->char_time_usec) {
result = 0;
}
#endif
if (copy_to_user(value, &result, sizeof(int)))
return -EFAULT;
return 0;
}
#ifdef SERIAL_DEBUG_IO
struct state_str
{
int state;
const char *str;
};
const struct state_str control_state_str[] = {
{TIOCM_DTR, "DTR" },
{TIOCM_RTS, "RTS"},
{TIOCM_ST, "ST?" },
{TIOCM_SR, "SR?" },
{TIOCM_CTS, "CTS" },
{TIOCM_CD, "CD" },
{TIOCM_RI, "RI" },
{TIOCM_DSR, "DSR" },
{0, NULL }
};
char *get_control_state_str(int MLines, char *s)
{
int i = 0;
s[0]='\0';
while (control_state_str[i].str != NULL) {
if (MLines & control_state_str[i].state) {
if (s[0] != '\0') {
strcat(s, ", ");
}
strcat(s, control_state_str[i].str);
}
i++;
}
return s;
}
#endif
static int
rs_break(struct tty_struct *tty, int break_state)
{
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
unsigned long flags;
if (!info->ioport)
return -EIO;
local_irq_save(flags);
if (break_state == -1) {
/* Go to manual mode and set the txd pin to 0 */
/* Clear bit 7 (txd) and 6 (tr_enable) */
info->tx_ctrl &= 0x3F;
} else {
/* Set bit 7 (txd) and 6 (tr_enable) */
info->tx_ctrl |= (0x80 | 0x40);
}
info->ioport[REG_TR_CTRL] = info->tx_ctrl;
local_irq_restore(flags);
return 0;
}
static int
rs_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear)
{
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
unsigned long flags;
local_irq_save(flags);
if (clear & TIOCM_RTS)
e100_rts(info, 0);
if (clear & TIOCM_DTR)
e100_dtr(info, 0);
/* Handle FEMALE behaviour */
if (clear & TIOCM_RI)
e100_ri_out(info, 0);
if (clear & TIOCM_CD)
e100_cd_out(info, 0);
if (set & TIOCM_RTS)
e100_rts(info, 1);
if (set & TIOCM_DTR)
e100_dtr(info, 1);
/* Handle FEMALE behaviour */
if (set & TIOCM_RI)
e100_ri_out(info, 1);
if (set & TIOCM_CD)
e100_cd_out(info, 1);
local_irq_restore(flags);
return 0;
}
static int
rs_tiocmget(struct tty_struct *tty)
{
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
unsigned int result;
unsigned long flags;
local_irq_save(flags);
result =
(!E100_RTS_GET(info) ? TIOCM_RTS : 0)
| (!E100_DTR_GET(info) ? TIOCM_DTR : 0)
| (!E100_RI_GET(info) ? TIOCM_RNG : 0)
| (!E100_DSR_GET(info) ? TIOCM_DSR : 0)
| (!E100_CD_GET(info) ? TIOCM_CAR : 0)
| (!E100_CTS_GET(info) ? TIOCM_CTS : 0);
local_irq_restore(flags);
#ifdef SERIAL_DEBUG_IO
printk(KERN_DEBUG "ser%i: modem state: %i 0x%08X\n",
info->line, result, result);
{
char s[100];
get_control_state_str(result, s);
printk(KERN_DEBUG "state: %s\n", s);
}
#endif
return result;
}
static int
rs_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct e100_serial * info = (struct e100_serial *)tty->driver_data;
if ((cmd != TIOCGSERIAL) && (cmd != TIOCSSERIAL) &&
(cmd != TIOCSERCONFIG) && (cmd != TIOCSERGWILD) &&
(cmd != TIOCSERSWILD) && (cmd != TIOCSERGSTRUCT)) {
if (tty->flags & (1 << TTY_IO_ERROR))
return -EIO;
}
switch (cmd) {
case TIOCGSERIAL:
return get_serial_info(info,
(struct serial_struct *) arg);
case TIOCSSERIAL:
return set_serial_info(info,
(struct serial_struct *) arg);
case TIOCSERGETLSR: /* Get line status register */
return get_lsr_info(info, (unsigned int *) arg);
case TIOCSERGSTRUCT:
if (copy_to_user((struct e100_serial *) arg,
info, sizeof(struct e100_serial)))
return -EFAULT;
return 0;
#if defined(CONFIG_ETRAX_RS485)
case TIOCSERSETRS485:
{
/* In this ioctl we still use the old structure
* rs485_control for backward compatibility
* (if we use serial_rs485, then old user-level code
* wouldn't work anymore...).
* The use of this ioctl is deprecated: use TIOCSRS485
* instead.*/
struct rs485_control rs485ctrl;
struct serial_rs485 rs485data;
printk(KERN_DEBUG "The use of this ioctl is deprecated. Use TIOCSRS485 instead\n");
if (copy_from_user(&rs485ctrl, (struct rs485_control *)arg,
sizeof(rs485ctrl)))
return -EFAULT;
rs485data.delay_rts_before_send = rs485ctrl.delay_rts_before_send;
rs485data.flags = 0;
if (rs485ctrl.enabled)
rs485data.flags |= SER_RS485_ENABLED;
else
rs485data.flags &= ~(SER_RS485_ENABLED);
if (rs485ctrl.rts_on_send)
rs485data.flags |= SER_RS485_RTS_ON_SEND;
else
rs485data.flags &= ~(SER_RS485_RTS_ON_SEND);
if (rs485ctrl.rts_after_sent)
rs485data.flags |= SER_RS485_RTS_AFTER_SEND;
else
rs485data.flags &= ~(SER_RS485_RTS_AFTER_SEND);
return e100_enable_rs485(tty, &rs485data);
}
case TIOCSRS485:
{
/* This is the new version of TIOCSRS485, with new
* data structure serial_rs485 */
struct serial_rs485 rs485data;
if (copy_from_user(&rs485data, (struct rs485_control *)arg,
sizeof(rs485data)))
return -EFAULT;
return e100_enable_rs485(tty, &rs485data);
}
case TIOCGRS485:
{
struct serial_rs485 *rs485data =
&(((struct e100_serial *)tty->driver_data)->rs485);
/* This is the ioctl to get RS485 data from user-space */
if (copy_to_user((struct serial_rs485 *) arg,
rs485data,
sizeof(struct serial_rs485)))
return -EFAULT;
break;
}
case TIOCSERWRRS485:
{
struct rs485_write rs485wr;
if (copy_from_user(&rs485wr, (struct rs485_write *)arg,
sizeof(rs485wr)))
return -EFAULT;
return e100_write_rs485(tty, rs485wr.outc, rs485wr.outc_size);
}
#endif
default:
return -ENOIOCTLCMD;
}
return 0;
}
static void
rs_set_termios(struct tty_struct *tty, struct ktermios *old_termios)
{
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
change_speed(info);
/* Handle turning off CRTSCTS */
if ((old_termios->c_cflag & CRTSCTS) &&
!(tty->termios->c_cflag & CRTSCTS)) {
tty->hw_stopped = 0;
rs_start(tty);
}
}
/*
* ------------------------------------------------------------
* rs_close()
*
* This routine is called when the serial port gets closed. First, we
* wait for the last remaining data to be sent. Then, we unlink its
* S structure from the interrupt chain if necessary, and we free
* that IRQ if nothing is left in the chain.
* ------------------------------------------------------------
*/
static void
rs_close(struct tty_struct *tty, struct file * filp)
{
struct e100_serial * info = (struct e100_serial *)tty->driver_data;
unsigned long flags;
if (!info)
return;
/* interrupts are disabled for this entire function */
local_irq_save(flags);
if (tty_hung_up_p(filp)) {
local_irq_restore(flags);
return;
}
#ifdef SERIAL_DEBUG_OPEN
printk("[%d] rs_close ttyS%d, count = %d\n", current->pid,
info->line, info->count);
#endif
if ((tty->count == 1) && (info->count != 1)) {
/*
* Uh, oh. tty->count is 1, which means that the tty
* structure will be freed. Info->count should always
* be one in these conditions. If it's greater than
* one, we've got real problems, since it means the
* serial port won't be shutdown.
*/
printk(KERN_ERR
"rs_close: bad serial port count; tty->count is 1, "
"info->count is %d\n", info->count);
info->count = 1;
}
if (--info->count < 0) {
printk(KERN_ERR "rs_close: bad serial port count for ttyS%d: %d\n",
info->line, info->count);
info->count = 0;
}
if (info->count) {
local_irq_restore(flags);
return;
}
info->flags |= ASYNC_CLOSING;
/*
* Save the termios structure, since this port may have
* separate termios for callout and dialin.
*/
if (info->flags & ASYNC_NORMAL_ACTIVE)
info->normal_termios = *tty->termios;
/*
* Now we wait for the transmit buffer to clear; and we notify
* the line discipline to only process XON/XOFF characters.
*/
tty->closing = 1;
if (info->closing_wait != ASYNC_CLOSING_WAIT_NONE)
tty_wait_until_sent(tty, info->closing_wait);
/*
* At this point we stop accepting input. To do this, we
* disable the serial receiver and the DMA receive interrupt.
*/
#ifdef SERIAL_HANDLE_EARLY_ERRORS
e100_disable_serial_data_irq(info);
#endif
#ifndef CONFIG_SVINTO_SIM
e100_disable_rx(info);
e100_disable_rx_irq(info);
if (info->flags & ASYNC_INITIALIZED) {
/*
* Before we drop DTR, make sure the UART transmitter
* has completely drained; this is especially
* important as we have a transmit FIFO!
*/
rs_wait_until_sent(tty, HZ);
}
#endif
shutdown(info);
rs_flush_buffer(tty);
tty_ldisc_flush(tty);
tty->closing = 0;
info->event = 0;
info->port.tty = NULL;
if (info->blocked_open) {
if (info->close_delay)
schedule_timeout_interruptible(info->close_delay);
wake_up_interruptible(&info->open_wait);
}
info->flags &= ~(ASYNC_NORMAL_ACTIVE|ASYNC_CLOSING);
wake_up_interruptible(&info->close_wait);
local_irq_restore(flags);
/* port closed */
#if defined(CONFIG_ETRAX_RS485)
if (info->rs485.flags & SER_RS485_ENABLED) {
info->rs485.flags &= ~(SER_RS485_ENABLED);
#if defined(CONFIG_ETRAX_RS485_ON_PA)
*R_PORT_PA_DATA = port_pa_data_shadow &= ~(1 << rs485_pa_bit);
#endif
#if defined(CONFIG_ETRAX_RS485_ON_PORT_G)
REG_SHADOW_SET(R_PORT_G_DATA, port_g_data_shadow,
rs485_port_g_bit, 0);
#endif
#if defined(CONFIG_ETRAX_RS485_LTC1387)
REG_SHADOW_SET(R_PORT_G_DATA, port_g_data_shadow,
CONFIG_ETRAX_RS485_LTC1387_DXEN_PORT_G_BIT, 0);
REG_SHADOW_SET(R_PORT_G_DATA, port_g_data_shadow,
CONFIG_ETRAX_RS485_LTC1387_RXEN_PORT_G_BIT, 0);
#endif
}
#endif
/*
* Release any allocated DMA irq's.
*/
if (info->dma_in_enabled) {
free_irq(info->dma_in_irq_nbr, info);
cris_free_dma(info->dma_in_nbr, info->dma_in_irq_description);
info->uses_dma_in = 0;
#ifdef SERIAL_DEBUG_OPEN
printk(KERN_DEBUG "DMA irq '%s' freed\n",
info->dma_in_irq_description);
#endif
}
if (info->dma_out_enabled) {
free_irq(info->dma_out_irq_nbr, info);
cris_free_dma(info->dma_out_nbr, info->dma_out_irq_description);
info->uses_dma_out = 0;
#ifdef SERIAL_DEBUG_OPEN
printk(KERN_DEBUG "DMA irq '%s' freed\n",
info->dma_out_irq_description);
#endif
}
}
/*
* rs_wait_until_sent() --- wait until the transmitter is empty
*/
static void rs_wait_until_sent(struct tty_struct *tty, int timeout)
{
unsigned long orig_jiffies;
struct e100_serial *info = (struct e100_serial *)tty->driver_data;
unsigned long curr_time = jiffies;
unsigned long curr_time_usec = GET_JIFFIES_USEC();
long elapsed_usec =
(curr_time - info->last_tx_active) * (1000000/HZ) +
curr_time_usec - info->last_tx_active_usec;
/*
* Check R_DMA_CHx_STATUS bit 0-6=number of available bytes in FIFO
* R_DMA_CHx_HWSW bit 31-16=nbr of bytes left in DMA buffer (0=64k)
*/
orig_jiffies = jiffies;
while (info->xmit.head != info->xmit.tail || /* More in send queue */
(*info->ostatusadr & 0x007f) || /* more in FIFO */
(elapsed_usec < 2*info->char_time_usec)) {
schedule_timeout_interruptible(1);
if (signal_pending(current))
break;
if (timeout && time_after(jiffies, orig_jiffies + timeout))
break;
curr_time = jiffies;
curr_time_usec = GET_JIFFIES_USEC();
elapsed_usec =
(curr_time - info->last_tx_active) * (1000000/HZ) +
curr_time_usec - info->last_tx_active_usec;
}
set_current_state(TASK_RUNNING);
}
/*
* rs_hangup() --- called by tty_hangup() when a hangup is signaled.
*/
void
rs_hangup(struct tty_struct *tty)
{
struct e100_serial * info = (struct e100_serial *)tty->driver_data;
rs_flush_buffer(tty);
shutdown(info);
info->event = 0;
info->count = 0;
info->flags &= ~ASYNC_NORMAL_ACTIVE;
info->port.tty = NULL;
wake_up_interruptible(&info->open_wait);
}
/*
* ------------------------------------------------------------
* rs_open() and friends
* ------------------------------------------------------------
*/
static int
block_til_ready(struct tty_struct *tty, struct file * filp,
struct e100_serial *info)
{
DECLARE_WAITQUEUE(wait, current);
unsigned long flags;
int retval;
int do_clocal = 0, extra_count = 0;
/*
* If the device is in the middle of being closed, then block
* until it's done, and then try again.
*/
if (tty_hung_up_p(filp) ||
(info->flags & ASYNC_CLOSING)) {
wait_event_interruptible_tty(info->close_wait,
!(info->flags & ASYNC_CLOSING));
#ifdef SERIAL_DO_RESTART
if (info->flags & ASYNC_HUP_NOTIFY)
return -EAGAIN;
else
return -ERESTARTSYS;
#else
return -EAGAIN;
#endif
}
/*
* If non-blocking mode is set, or the port is not enabled,
* then make the check up front and then exit.
*/
if ((filp->f_flags & O_NONBLOCK) ||
(tty->flags & (1 << TTY_IO_ERROR))) {
info->flags |= ASYNC_NORMAL_ACTIVE;
return 0;
}
if (tty->termios->c_cflag & CLOCAL) {
do_clocal = 1;
}
/*
* Block waiting for the carrier detect and the line to become
* free (i.e., not in use by the callout). While we are in
* this loop, info->count is dropped by one, so that
* rs_close() knows when to free things. We restore it upon
* exit, either normal or abnormal.
*/
retval = 0;
add_wait_queue(&info->open_wait, &wait);
#ifdef SERIAL_DEBUG_OPEN
printk("block_til_ready before block: ttyS%d, count = %d\n",
info->line, info->count);
#endif
local_irq_save(flags);
if (!tty_hung_up_p(filp)) {
extra_count++;
info->count--;
}
local_irq_restore(flags);
info->blocked_open++;
while (1) {
local_irq_save(flags);
/* assert RTS and DTR */
e100_rts(info, 1);
e100_dtr(info, 1);
local_irq_restore(flags);
set_current_state(TASK_INTERRUPTIBLE);
if (tty_hung_up_p(filp) ||
!(info->flags & ASYNC_INITIALIZED)) {
#ifdef SERIAL_DO_RESTART
if (info->flags & ASYNC_HUP_NOTIFY)
retval = -EAGAIN;
else
retval = -ERESTARTSYS;
#else
retval = -EAGAIN;
#endif
break;
}
if (!(info->flags & ASYNC_CLOSING) && do_clocal)
/* && (do_clocal || DCD_IS_ASSERTED) */
break;
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
#ifdef SERIAL_DEBUG_OPEN
printk("block_til_ready blocking: ttyS%d, count = %d\n",
info->line, info->count);
#endif
tty_unlock();
schedule();
tty_lock();
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&info->open_wait, &wait);
if (extra_count)
info->count++;
info->blocked_open--;
#ifdef SERIAL_DEBUG_OPEN
printk("block_til_ready after blocking: ttyS%d, count = %d\n",
info->line, info->count);
#endif
if (retval)
return retval;
info->flags |= ASYNC_NORMAL_ACTIVE;
return 0;
}
static void
deinit_port(struct e100_serial *info)
{
if (info->dma_out_enabled) {
cris_free_dma(info->dma_out_nbr, info->dma_out_irq_description);
free_irq(info->dma_out_irq_nbr, info);
}
if (info->dma_in_enabled) {
cris_free_dma(info->dma_in_nbr, info->dma_in_irq_description);
free_irq(info->dma_in_irq_nbr, info);
}
}
/*
* This routine is called whenever a serial port is opened.
* It performs the serial-specific initialization for the tty structure.
*/
static int
rs_open(struct tty_struct *tty, struct file * filp)
{
struct e100_serial *info;
int retval;
int allocated_resources = 0;
info = rs_table + tty->index;
if (!info->enabled)
return -ENODEV;
#ifdef SERIAL_DEBUG_OPEN
printk("[%d] rs_open %s, count = %d\n", current->pid, tty->name,
info->count);
#endif
info->count++;
tty->driver_data = info;
info->port.tty = tty;
tty->low_latency = !!(info->flags & ASYNC_LOW_LATENCY);
/*
* If the port is in the middle of closing, bail out now
*/
if (tty_hung_up_p(filp) ||
(info->flags & ASYNC_CLOSING)) {
wait_event_interruptible_tty(info->close_wait,
!(info->flags & ASYNC_CLOSING));
#ifdef SERIAL_DO_RESTART
return ((info->flags & ASYNC_HUP_NOTIFY) ?
-EAGAIN : -ERESTARTSYS);
#else
return -EAGAIN;
#endif
}
/*
* If DMA is enabled try to allocate the irq's.
*/
if (info->count == 1) {
allocated_resources = 1;
if (info->dma_in_enabled) {
if (request_irq(info->dma_in_irq_nbr,
rec_interrupt,
info->dma_in_irq_flags,
info->dma_in_irq_description,
info)) {
printk(KERN_WARNING "DMA irq '%s' busy; "
"falling back to non-DMA mode\n",
info->dma_in_irq_description);
/* Make sure we never try to use DMA in */
/* for the port again. */
info->dma_in_enabled = 0;
} else if (cris_request_dma(info->dma_in_nbr,
info->dma_in_irq_description,
DMA_VERBOSE_ON_ERROR,
info->dma_owner)) {
free_irq(info->dma_in_irq_nbr, info);
printk(KERN_WARNING "DMA '%s' busy; "
"falling back to non-DMA mode\n",
info->dma_in_irq_description);
/* Make sure we never try to use DMA in */
/* for the port again. */
info->dma_in_enabled = 0;
}
#ifdef SERIAL_DEBUG_OPEN
else
printk(KERN_DEBUG "DMA irq '%s' allocated\n",
info->dma_in_irq_description);
#endif
}
if (info->dma_out_enabled) {
if (request_irq(info->dma_out_irq_nbr,
tr_interrupt,
info->dma_out_irq_flags,
info->dma_out_irq_description,
info)) {
printk(KERN_WARNING "DMA irq '%s' busy; "
"falling back to non-DMA mode\n",
info->dma_out_irq_description);
/* Make sure we never try to use DMA out */
/* for the port again. */
info->dma_out_enabled = 0;
} else if (cris_request_dma(info->dma_out_nbr,
info->dma_out_irq_description,
DMA_VERBOSE_ON_ERROR,
info->dma_owner)) {
free_irq(info->dma_out_irq_nbr, info);
printk(KERN_WARNING "DMA '%s' busy; "
"falling back to non-DMA mode\n",
info->dma_out_irq_description);
/* Make sure we never try to use DMA out */
/* for the port again. */
info->dma_out_enabled = 0;
}
#ifdef SERIAL_DEBUG_OPEN
else
printk(KERN_DEBUG "DMA irq '%s' allocated\n",
info->dma_out_irq_description);
#endif
}
}
/*
* Start up the serial port
*/
retval = startup(info);
if (retval) {
if (allocated_resources)
deinit_port(info);
/* FIXME Decrease count info->count here too? */
return retval;
}
retval = block_til_ready(tty, filp, info);
if (retval) {
#ifdef SERIAL_DEBUG_OPEN
printk("rs_open returning after block_til_ready with %d\n",
retval);
#endif
if (allocated_resources)
deinit_port(info);
return retval;
}
if ((info->count == 1) && (info->flags & ASYNC_SPLIT_TERMIOS)) {
*tty->termios = info->normal_termios;
change_speed(info);
}
#ifdef SERIAL_DEBUG_OPEN
printk("rs_open ttyS%d successful...\n", info->line);
#endif
DLOG_INT_TRIG( log_int_pos = 0);
DFLIP( if (info->line == SERIAL_DEBUG_LINE) {
info->icount.rx = 0;
} );
return 0;
}
#ifdef CONFIG_PROC_FS
/*
* /proc fs routines....
*/
static void seq_line_info(struct seq_file *m, struct e100_serial *info)
{
unsigned long tmp;
seq_printf(m, "%d: uart:E100 port:%lX irq:%d",
info->line, (unsigned long)info->ioport, info->irq);
if (!info->ioport || (info->type == PORT_UNKNOWN)) {
seq_printf(m, "\n");
return;
}
seq_printf(m, " baud:%d", info->baud);
seq_printf(m, " tx:%lu rx:%lu",
(unsigned long)info->icount.tx,
(unsigned long)info->icount.rx);
tmp = CIRC_CNT(info->xmit.head, info->xmit.tail, SERIAL_XMIT_SIZE);
if (tmp)
seq_printf(m, " tx_pend:%lu/%lu",
(unsigned long)tmp,
(unsigned long)SERIAL_XMIT_SIZE);
seq_printf(m, " rx_pend:%lu/%lu",
(unsigned long)info->recv_cnt,
(unsigned long)info->max_recv_cnt);
#if 1
if (info->port.tty) {
if (info->port.tty->stopped)
seq_printf(m, " stopped:%i",
(int)info->port.tty->stopped);
if (info->port.tty->hw_stopped)
seq_printf(m, " hw_stopped:%i",
(int)info->port.tty->hw_stopped);
}
{
unsigned char rstat = info->ioport[REG_STATUS];
if (rstat & IO_MASK(R_SERIAL0_STATUS, xoff_detect))
seq_printf(m, " xoff_detect:1");
}
#endif
if (info->icount.frame)
seq_printf(m, " fe:%lu", (unsigned long)info->icount.frame);
if (info->icount.parity)
seq_printf(m, " pe:%lu", (unsigned long)info->icount.parity);
if (info->icount.brk)
seq_printf(m, " brk:%lu", (unsigned long)info->icount.brk);
if (info->icount.overrun)
seq_printf(m, " oe:%lu", (unsigned long)info->icount.overrun);
/*
* Last thing is the RS-232 status lines
*/
if (!E100_RTS_GET(info))
seq_puts(m, "|RTS");
if (!E100_CTS_GET(info))
seq_puts(m, "|CTS");
if (!E100_DTR_GET(info))
seq_puts(m, "|DTR");
if (!E100_DSR_GET(info))
seq_puts(m, "|DSR");
if (!E100_CD_GET(info))
seq_puts(m, "|CD");
if (!E100_RI_GET(info))
seq_puts(m, "|RI");
seq_puts(m, "\n");
}
static int crisv10_proc_show(struct seq_file *m, void *v)
{
int i;
seq_printf(m, "serinfo:1.0 driver:%s\n", serial_version);
for (i = 0; i < NR_PORTS; i++) {
if (!rs_table[i].enabled)
continue;
seq_line_info(m, &rs_table[i]);
}
#ifdef DEBUG_LOG_INCLUDED
for (i = 0; i < debug_log_pos; i++) {
seq_printf(m, "%-4i %lu.%lu ",
i, debug_log[i].time,
timer_data_to_ns(debug_log[i].timer_data));
seq_printf(m, debug_log[i].string, debug_log[i].value);
}
seq_printf(m, "debug_log %i/%i\n", i, DEBUG_LOG_SIZE);
debug_log_pos = 0;
#endif
return 0;
}
static int crisv10_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, crisv10_proc_show, NULL);
}
static const struct file_operations crisv10_proc_fops = {
.owner = THIS_MODULE,
.open = crisv10_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif
/* Finally, routines used to initialize the serial driver. */
static void show_serial_version(void)
{
printk(KERN_INFO
"ETRAX 100LX serial-driver %s, "
"(c) 2000-2004 Axis Communications AB\r\n",
&serial_version[11]); /* "$Revision: x.yy" */
}
/* rs_init inits the driver at boot (using the module_init chain) */
static const struct tty_operations rs_ops = {
.open = rs_open,
.close = rs_close,
.write = rs_write,
.flush_chars = rs_flush_chars,
.write_room = rs_write_room,
.chars_in_buffer = rs_chars_in_buffer,
.flush_buffer = rs_flush_buffer,
.ioctl = rs_ioctl,
.throttle = rs_throttle,
.unthrottle = rs_unthrottle,
.set_termios = rs_set_termios,
.stop = rs_stop,
.start = rs_start,
.hangup = rs_hangup,
.break_ctl = rs_break,
.send_xchar = rs_send_xchar,
.wait_until_sent = rs_wait_until_sent,
.tiocmget = rs_tiocmget,
.tiocmset = rs_tiocmset,
#ifdef CONFIG_PROC_FS
.proc_fops = &crisv10_proc_fops,
#endif
};
static int __init rs_init(void)
{
int i;
struct e100_serial *info;
struct tty_driver *driver = alloc_tty_driver(NR_PORTS);
if (!driver)
return -ENOMEM;
show_serial_version();
/* Setup the timed flush handler system */
#if !defined(CONFIG_ETRAX_SERIAL_FAST_TIMER)
setup_timer(&flush_timer, timed_flush_handler, 0);
mod_timer(&flush_timer, jiffies + 5);
#endif
#if defined(CONFIG_ETRAX_RS485)
#if defined(CONFIG_ETRAX_RS485_ON_PA)
if (cris_io_interface_allocate_pins(if_serial_0, 'a', rs485_pa_bit,
rs485_pa_bit)) {
printk(KERN_ERR "ETRAX100LX serial: Could not allocate "
"RS485 pin\n");
put_tty_driver(driver);
return -EBUSY;
}
#endif
#if defined(CONFIG_ETRAX_RS485_ON_PORT_G)
if (cris_io_interface_allocate_pins(if_serial_0, 'g', rs485_pa_bit,
rs485_port_g_bit)) {
printk(KERN_ERR "ETRAX100LX serial: Could not allocate "
"RS485 pin\n");
put_tty_driver(driver);
return -EBUSY;
}
#endif
#endif
/* Initialize the tty_driver structure */
driver->driver_name = "serial";
driver->name = "ttyS";
driver->major = TTY_MAJOR;
driver->minor_start = 64;
driver->type = TTY_DRIVER_TYPE_SERIAL;
driver->subtype = SERIAL_TYPE_NORMAL;
driver->init_termios = tty_std_termios;
driver->init_termios.c_cflag =
B115200 | CS8 | CREAD | HUPCL | CLOCAL; /* is normally B9600 default... */
driver->init_termios.c_ispeed = 115200;
driver->init_termios.c_ospeed = 115200;
driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
tty_set_operations(driver, &rs_ops);
serial_driver = driver;
if (tty_register_driver(driver))
panic("Couldn't register serial driver\n");
/* do some initializing for the separate ports */
for (i = 0, info = rs_table; i < NR_PORTS; i++,info++) {
if (info->enabled) {
if (cris_request_io_interface(info->io_if,
info->io_if_description)) {
printk(KERN_ERR "ETRAX100LX async serial: "
"Could not allocate IO pins for "
"%s, port %d\n",
info->io_if_description, i);
info->enabled = 0;
}
}
tty_port_init(&info->port);
info->uses_dma_in = 0;
info->uses_dma_out = 0;
info->line = i;
info->port.tty = NULL;
info->type = PORT_ETRAX;
info->tr_running = 0;
info->forced_eop = 0;
info->baud_base = DEF_BAUD_BASE;
info->custom_divisor = 0;
info->flags = 0;
info->close_delay = 5*HZ/10;
info->closing_wait = 30*HZ;
info->x_char = 0;
info->event = 0;
info->count = 0;
info->blocked_open = 0;
info->normal_termios = driver->init_termios;
init_waitqueue_head(&info->open_wait);
init_waitqueue_head(&info->close_wait);
info->xmit.buf = NULL;
info->xmit.tail = info->xmit.head = 0;
info->first_recv_buffer = info->last_recv_buffer = NULL;
info->recv_cnt = info->max_recv_cnt = 0;
info->last_tx_active_usec = 0;
info->last_tx_active = 0;
#if defined(CONFIG_ETRAX_RS485)
/* Set sane defaults */
info->rs485.flags &= ~(SER_RS485_RTS_ON_SEND);
info->rs485.flags |= SER_RS485_RTS_AFTER_SEND;
info->rs485.delay_rts_before_send = 0;
info->rs485.flags &= ~(SER_RS485_ENABLED);
#endif
INIT_WORK(&info->work, do_softint);
if (info->enabled) {
printk(KERN_INFO "%s%d at %p is a builtin UART with DMA\n",
serial_driver->name, info->line, info->ioport);
}
}
#ifdef CONFIG_ETRAX_FAST_TIMER
#ifdef CONFIG_ETRAX_SERIAL_FAST_TIMER
memset(fast_timers, 0, sizeof(fast_timers));
#endif
#ifdef CONFIG_ETRAX_RS485
memset(fast_timers_rs485, 0, sizeof(fast_timers_rs485));
#endif
fast_timer_init();
#endif
#ifndef CONFIG_SVINTO_SIM
#ifndef CONFIG_ETRAX_KGDB
/* Not needed in simulator. May only complicate stuff. */
/* hook the irq's for DMA channel 6 and 7, serial output and input, and some more... */
if (request_irq(SERIAL_IRQ_NBR, ser_interrupt,
IRQF_SHARED, "serial ", driver))
panic("%s: Failed to request irq8", __func__);
#endif
#endif /* CONFIG_SVINTO_SIM */
return 0;
}
/* this makes sure that rs_init is called during kernel boot */
module_init(rs_init);
| gpl-2.0 |
rothnic/Adam_Kernel | net/sunrpc/rpcb_clnt.c | 383 | 27134 | /*
* In-kernel rpcbind client supporting versions 2, 3, and 4 of the rpcbind
* protocol
*
* Based on RFC 1833: "Binding Protocols for ONC RPC Version 2" and
* RFC 3530: "Network File System (NFS) version 4 Protocol"
*
* Original: Gilles Quillard, Bull Open Source, 2005 <gilles.quillard@bull.net>
* Updated: Chuck Lever, Oracle Corporation, 2007 <chuck.lever@oracle.com>
*
* Descended from net/sunrpc/pmap_clnt.c,
* Copyright (C) 1996, Olaf Kirch <okir@monad.swb.de>
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/in6.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <net/ipv6.h>
#include <linux/sunrpc/clnt.h>
#include <linux/sunrpc/sched.h>
#include <linux/sunrpc/xprtsock.h>
#ifdef RPC_DEBUG
# define RPCDBG_FACILITY RPCDBG_BIND
#endif
#define RPCBIND_PROGRAM (100000u)
#define RPCBIND_PORT (111u)
#define RPCBVERS_2 (2u)
#define RPCBVERS_3 (3u)
#define RPCBVERS_4 (4u)
enum {
RPCBPROC_NULL,
RPCBPROC_SET,
RPCBPROC_UNSET,
RPCBPROC_GETPORT,
RPCBPROC_GETADDR = 3, /* alias for GETPORT */
RPCBPROC_DUMP,
RPCBPROC_CALLIT,
RPCBPROC_BCAST = 5, /* alias for CALLIT */
RPCBPROC_GETTIME,
RPCBPROC_UADDR2TADDR,
RPCBPROC_TADDR2UADDR,
RPCBPROC_GETVERSADDR,
RPCBPROC_INDIRECT,
RPCBPROC_GETADDRLIST,
RPCBPROC_GETSTAT,
};
#define RPCB_HIGHPROC_2 RPCBPROC_CALLIT
#define RPCB_HIGHPROC_3 RPCBPROC_TADDR2UADDR
#define RPCB_HIGHPROC_4 RPCBPROC_GETSTAT
/*
* r_owner
*
* The "owner" is allowed to unset a service in the rpcbind database.
*
* For AF_LOCAL SET/UNSET requests, rpcbind treats this string as a
* UID which it maps to a local user name via a password lookup.
* In all other cases it is ignored.
*
* For SET/UNSET requests, user space provides a value, even for
* network requests, and GETADDR uses an empty string. We follow
* those precedents here.
*/
#define RPCB_OWNER_STRING "0"
#define RPCB_MAXOWNERLEN sizeof(RPCB_OWNER_STRING)
/*
* XDR data type sizes
*/
#define RPCB_program_sz (1)
#define RPCB_version_sz (1)
#define RPCB_protocol_sz (1)
#define RPCB_port_sz (1)
#define RPCB_boolean_sz (1)
#define RPCB_netid_sz (1 + XDR_QUADLEN(RPCBIND_MAXNETIDLEN))
#define RPCB_addr_sz (1 + XDR_QUADLEN(RPCBIND_MAXUADDRLEN))
#define RPCB_ownerstring_sz (1 + XDR_QUADLEN(RPCB_MAXOWNERLEN))
/*
* XDR argument and result sizes
*/
#define RPCB_mappingargs_sz (RPCB_program_sz + RPCB_version_sz + \
RPCB_protocol_sz + RPCB_port_sz)
#define RPCB_getaddrargs_sz (RPCB_program_sz + RPCB_version_sz + \
RPCB_netid_sz + RPCB_addr_sz + \
RPCB_ownerstring_sz)
#define RPCB_getportres_sz RPCB_port_sz
#define RPCB_setres_sz RPCB_boolean_sz
/*
* Note that RFC 1833 does not put any size restrictions on the
* address string returned by the remote rpcbind database.
*/
#define RPCB_getaddrres_sz RPCB_addr_sz
static void rpcb_getport_done(struct rpc_task *, void *);
static void rpcb_map_release(void *data);
static struct rpc_program rpcb_program;
struct rpcbind_args {
struct rpc_xprt * r_xprt;
u32 r_prog;
u32 r_vers;
u32 r_prot;
unsigned short r_port;
const char * r_netid;
const char * r_addr;
const char * r_owner;
int r_status;
};
static struct rpc_procinfo rpcb_procedures2[];
static struct rpc_procinfo rpcb_procedures3[];
static struct rpc_procinfo rpcb_procedures4[];
struct rpcb_info {
u32 rpc_vers;
struct rpc_procinfo * rpc_proc;
};
static struct rpcb_info rpcb_next_version[];
static struct rpcb_info rpcb_next_version6[];
static const struct rpc_call_ops rpcb_getport_ops = {
.rpc_call_done = rpcb_getport_done,
.rpc_release = rpcb_map_release,
};
static void rpcb_wake_rpcbind_waiters(struct rpc_xprt *xprt, int status)
{
xprt_clear_binding(xprt);
rpc_wake_up_status(&xprt->binding, status);
}
static void rpcb_map_release(void *data)
{
struct rpcbind_args *map = data;
rpcb_wake_rpcbind_waiters(map->r_xprt, map->r_status);
xprt_put(map->r_xprt);
kfree(map->r_addr);
kfree(map);
}
static const struct sockaddr_in rpcb_inaddr_loopback = {
.sin_family = AF_INET,
.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
.sin_port = htons(RPCBIND_PORT),
};
static struct rpc_clnt *rpcb_create_local(struct sockaddr *addr,
size_t addrlen, u32 version)
{
struct rpc_create_args args = {
.protocol = XPRT_TRANSPORT_UDP,
.address = addr,
.addrsize = addrlen,
.servername = "localhost",
.program = &rpcb_program,
.version = version,
.authflavor = RPC_AUTH_UNIX,
.flags = RPC_CLNT_CREATE_NOPING,
};
return rpc_create(&args);
}
static struct rpc_clnt *rpcb_create(char *hostname, struct sockaddr *srvaddr,
size_t salen, int proto, u32 version)
{
struct rpc_create_args args = {
.protocol = proto,
.address = srvaddr,
.addrsize = salen,
.servername = hostname,
.program = &rpcb_program,
.version = version,
.authflavor = RPC_AUTH_UNIX,
.flags = (RPC_CLNT_CREATE_NOPING |
RPC_CLNT_CREATE_NONPRIVPORT),
};
switch (srvaddr->sa_family) {
case AF_INET:
((struct sockaddr_in *)srvaddr)->sin_port = htons(RPCBIND_PORT);
break;
case AF_INET6:
((struct sockaddr_in6 *)srvaddr)->sin6_port = htons(RPCBIND_PORT);
break;
default:
return NULL;
}
return rpc_create(&args);
}
static int rpcb_register_call(const u32 version, struct rpc_message *msg)
{
struct sockaddr *addr = (struct sockaddr *)&rpcb_inaddr_loopback;
size_t addrlen = sizeof(rpcb_inaddr_loopback);
struct rpc_clnt *rpcb_clnt;
int result, error = 0;
msg->rpc_resp = &result;
rpcb_clnt = rpcb_create_local(addr, addrlen, version);
if (!IS_ERR(rpcb_clnt)) {
error = rpc_call_sync(rpcb_clnt, msg, 0);
rpc_shutdown_client(rpcb_clnt);
} else
error = PTR_ERR(rpcb_clnt);
if (error < 0) {
dprintk("RPC: failed to contact local rpcbind "
"server (errno %d).\n", -error);
return error;
}
if (!result)
return -EACCES;
return 0;
}
/**
* rpcb_register - set or unset a port registration with the local rpcbind svc
* @prog: RPC program number to bind
* @vers: RPC version number to bind
* @prot: transport protocol to register
* @port: port value to register
*
* Returns zero if the registration request was dispatched successfully
* and the rpcbind daemon returned success. Otherwise, returns an errno
* value that reflects the nature of the error (request could not be
* dispatched, timed out, or rpcbind returned an error).
*
* RPC services invoke this function to advertise their contact
* information via the system's rpcbind daemon. RPC services
* invoke this function once for each [program, version, transport]
* tuple they wish to advertise.
*
* Callers may also unregister RPC services that are no longer
* available by setting the passed-in port to zero. This removes
* all registered transports for [program, version] from the local
* rpcbind database.
*
* This function uses rpcbind protocol version 2 to contact the
* local rpcbind daemon.
*
* Registration works over both AF_INET and AF_INET6, and services
* registered via this function are advertised as available for any
* address. If the local rpcbind daemon is listening on AF_INET6,
* services registered via this function will be advertised on
* IN6ADDR_ANY (ie available for all AF_INET and AF_INET6
* addresses).
*/
int rpcb_register(u32 prog, u32 vers, int prot, unsigned short port)
{
struct rpcbind_args map = {
.r_prog = prog,
.r_vers = vers,
.r_prot = prot,
.r_port = port,
};
struct rpc_message msg = {
.rpc_argp = &map,
};
dprintk("RPC: %sregistering (%u, %u, %d, %u) with local "
"rpcbind\n", (port ? "" : "un"),
prog, vers, prot, port);
msg.rpc_proc = &rpcb_procedures2[RPCBPROC_UNSET];
if (port)
msg.rpc_proc = &rpcb_procedures2[RPCBPROC_SET];
return rpcb_register_call(RPCBVERS_2, &msg);
}
/*
* Fill in AF_INET family-specific arguments to register
*/
static int rpcb_register_inet4(const struct sockaddr *sap,
struct rpc_message *msg)
{
const struct sockaddr_in *sin = (const struct sockaddr_in *)sap;
struct rpcbind_args *map = msg->rpc_argp;
unsigned short port = ntohs(sin->sin_port);
int result;
map->r_addr = rpc_sockaddr2uaddr(sap);
dprintk("RPC: %sregistering [%u, %u, %s, '%s'] with "
"local rpcbind\n", (port ? "" : "un"),
map->r_prog, map->r_vers,
map->r_addr, map->r_netid);
msg->rpc_proc = &rpcb_procedures4[RPCBPROC_UNSET];
if (port)
msg->rpc_proc = &rpcb_procedures4[RPCBPROC_SET];
result = rpcb_register_call(RPCBVERS_4, msg);
kfree(map->r_addr);
return result;
}
/*
* Fill in AF_INET6 family-specific arguments to register
*/
static int rpcb_register_inet6(const struct sockaddr *sap,
struct rpc_message *msg)
{
const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)sap;
struct rpcbind_args *map = msg->rpc_argp;
unsigned short port = ntohs(sin6->sin6_port);
int result;
map->r_addr = rpc_sockaddr2uaddr(sap);
dprintk("RPC: %sregistering [%u, %u, %s, '%s'] with "
"local rpcbind\n", (port ? "" : "un"),
map->r_prog, map->r_vers,
map->r_addr, map->r_netid);
msg->rpc_proc = &rpcb_procedures4[RPCBPROC_UNSET];
if (port)
msg->rpc_proc = &rpcb_procedures4[RPCBPROC_SET];
result = rpcb_register_call(RPCBVERS_4, msg);
kfree(map->r_addr);
return result;
}
static int rpcb_unregister_all_protofamilies(struct rpc_message *msg)
{
struct rpcbind_args *map = msg->rpc_argp;
dprintk("RPC: unregistering [%u, %u, '%s'] with "
"local rpcbind\n",
map->r_prog, map->r_vers, map->r_netid);
map->r_addr = "";
msg->rpc_proc = &rpcb_procedures4[RPCBPROC_UNSET];
return rpcb_register_call(RPCBVERS_4, msg);
}
/**
* rpcb_v4_register - set or unset a port registration with the local rpcbind
* @program: RPC program number of service to (un)register
* @version: RPC version number of service to (un)register
* @address: address family, IP address, and port to (un)register
* @netid: netid of transport protocol to (un)register
*
* Returns zero if the registration request was dispatched successfully
* and the rpcbind daemon returned success. Otherwise, returns an errno
* value that reflects the nature of the error (request could not be
* dispatched, timed out, or rpcbind returned an error).
*
* RPC services invoke this function to advertise their contact
* information via the system's rpcbind daemon. RPC services
* invoke this function once for each [program, version, address,
* netid] tuple they wish to advertise.
*
* Callers may also unregister RPC services that are registered at a
* specific address by setting the port number in @address to zero.
* They may unregister all registered protocol families at once for
* a service by passing a NULL @address argument. If @netid is ""
* then all netids for [program, version, address] are unregistered.
*
* This function uses rpcbind protocol version 4 to contact the
* local rpcbind daemon. The local rpcbind daemon must support
* version 4 of the rpcbind protocol in order for these functions
* to register a service successfully.
*
* Supported netids include "udp" and "tcp" for UDP and TCP over
* IPv4, and "udp6" and "tcp6" for UDP and TCP over IPv6,
* respectively.
*
* The contents of @address determine the address family and the
* port to be registered. The usual practice is to pass INADDR_ANY
* as the raw address, but specifying a non-zero address is also
* supported by this API if the caller wishes to advertise an RPC
* service on a specific network interface.
*
* Note that passing in INADDR_ANY does not create the same service
* registration as IN6ADDR_ANY. The former advertises an RPC
* service on any IPv4 address, but not on IPv6. The latter
* advertises the service on all IPv4 and IPv6 addresses.
*/
int rpcb_v4_register(const u32 program, const u32 version,
const struct sockaddr *address, const char *netid)
{
struct rpcbind_args map = {
.r_prog = program,
.r_vers = version,
.r_netid = netid,
.r_owner = RPCB_OWNER_STRING,
};
struct rpc_message msg = {
.rpc_argp = &map,
};
if (address == NULL)
return rpcb_unregister_all_protofamilies(&msg);
switch (address->sa_family) {
case AF_INET:
return rpcb_register_inet4(address, &msg);
case AF_INET6:
return rpcb_register_inet6(address, &msg);
}
return -EAFNOSUPPORT;
}
/**
* rpcb_getport_sync - obtain the port for an RPC service on a given host
* @sin: address of remote peer
* @prog: RPC program number to bind
* @vers: RPC version number to bind
* @prot: transport protocol to use to make this request
*
* Return value is the requested advertised port number,
* or a negative errno value.
*
* Called from outside the RPC client in a synchronous task context.
* Uses default timeout parameters specified by underlying transport.
*
* XXX: Needs to support IPv6
*/
int rpcb_getport_sync(struct sockaddr_in *sin, u32 prog, u32 vers, int prot)
{
struct rpcbind_args map = {
.r_prog = prog,
.r_vers = vers,
.r_prot = prot,
.r_port = 0,
};
struct rpc_message msg = {
.rpc_proc = &rpcb_procedures2[RPCBPROC_GETPORT],
.rpc_argp = &map,
.rpc_resp = &map,
};
struct rpc_clnt *rpcb_clnt;
int status;
dprintk("RPC: %s(%pI4, %u, %u, %d)\n",
__func__, &sin->sin_addr.s_addr, prog, vers, prot);
rpcb_clnt = rpcb_create(NULL, (struct sockaddr *)sin,
sizeof(*sin), prot, RPCBVERS_2);
if (IS_ERR(rpcb_clnt))
return PTR_ERR(rpcb_clnt);
status = rpc_call_sync(rpcb_clnt, &msg, 0);
rpc_shutdown_client(rpcb_clnt);
if (status >= 0) {
if (map.r_port != 0)
return map.r_port;
status = -EACCES;
}
return status;
}
EXPORT_SYMBOL_GPL(rpcb_getport_sync);
static struct rpc_task *rpcb_call_async(struct rpc_clnt *rpcb_clnt, struct rpcbind_args *map, struct rpc_procinfo *proc)
{
struct rpc_message msg = {
.rpc_proc = proc,
.rpc_argp = map,
.rpc_resp = map,
};
struct rpc_task_setup task_setup_data = {
.rpc_client = rpcb_clnt,
.rpc_message = &msg,
.callback_ops = &rpcb_getport_ops,
.callback_data = map,
.flags = RPC_TASK_ASYNC,
};
return rpc_run_task(&task_setup_data);
}
/*
* In the case where rpc clients have been cloned, we want to make
* sure that we use the program number/version etc of the actual
* owner of the xprt. To do so, we walk back up the tree of parents
* to find whoever created the transport and/or whoever has the
* autobind flag set.
*/
static struct rpc_clnt *rpcb_find_transport_owner(struct rpc_clnt *clnt)
{
struct rpc_clnt *parent = clnt->cl_parent;
while (parent != clnt) {
if (parent->cl_xprt != clnt->cl_xprt)
break;
if (clnt->cl_autobind)
break;
clnt = parent;
parent = parent->cl_parent;
}
return clnt;
}
/**
* rpcb_getport_async - obtain the port for a given RPC service on a given host
* @task: task that is waiting for portmapper request
*
* This one can be called for an ongoing RPC request, and can be used in
* an async (rpciod) context.
*/
void rpcb_getport_async(struct rpc_task *task)
{
struct rpc_clnt *clnt;
struct rpc_procinfo *proc;
u32 bind_version;
struct rpc_xprt *xprt;
struct rpc_clnt *rpcb_clnt;
static struct rpcbind_args *map;
struct rpc_task *child;
struct sockaddr_storage addr;
struct sockaddr *sap = (struct sockaddr *)&addr;
size_t salen;
int status;
clnt = rpcb_find_transport_owner(task->tk_client);
xprt = clnt->cl_xprt;
dprintk("RPC: %5u %s(%s, %u, %u, %d)\n",
task->tk_pid, __func__,
clnt->cl_server, clnt->cl_prog, clnt->cl_vers, xprt->prot);
/* Put self on the wait queue to ensure we get notified if
* some other task is already attempting to bind the port */
rpc_sleep_on(&xprt->binding, task, NULL);
if (xprt_test_and_set_binding(xprt)) {
dprintk("RPC: %5u %s: waiting for another binder\n",
task->tk_pid, __func__);
return;
}
/* Someone else may have bound if we slept */
if (xprt_bound(xprt)) {
status = 0;
dprintk("RPC: %5u %s: already bound\n",
task->tk_pid, __func__);
goto bailout_nofree;
}
/* Parent transport's destination address */
salen = rpc_peeraddr(clnt, sap, sizeof(addr));
/* Don't ever use rpcbind v2 for AF_INET6 requests */
switch (sap->sa_family) {
case AF_INET:
proc = rpcb_next_version[xprt->bind_index].rpc_proc;
bind_version = rpcb_next_version[xprt->bind_index].rpc_vers;
break;
case AF_INET6:
proc = rpcb_next_version6[xprt->bind_index].rpc_proc;
bind_version = rpcb_next_version6[xprt->bind_index].rpc_vers;
break;
default:
status = -EAFNOSUPPORT;
dprintk("RPC: %5u %s: bad address family\n",
task->tk_pid, __func__);
goto bailout_nofree;
}
if (proc == NULL) {
xprt->bind_index = 0;
status = -EPFNOSUPPORT;
dprintk("RPC: %5u %s: no more getport versions available\n",
task->tk_pid, __func__);
goto bailout_nofree;
}
dprintk("RPC: %5u %s: trying rpcbind version %u\n",
task->tk_pid, __func__, bind_version);
rpcb_clnt = rpcb_create(clnt->cl_server, sap, salen, xprt->prot,
bind_version);
if (IS_ERR(rpcb_clnt)) {
status = PTR_ERR(rpcb_clnt);
dprintk("RPC: %5u %s: rpcb_create failed, error %ld\n",
task->tk_pid, __func__, PTR_ERR(rpcb_clnt));
goto bailout_nofree;
}
map = kzalloc(sizeof(struct rpcbind_args), GFP_ATOMIC);
if (!map) {
status = -ENOMEM;
dprintk("RPC: %5u %s: no memory available\n",
task->tk_pid, __func__);
goto bailout_release_client;
}
map->r_prog = clnt->cl_prog;
map->r_vers = clnt->cl_vers;
map->r_prot = xprt->prot;
map->r_port = 0;
map->r_xprt = xprt_get(xprt);
map->r_status = -EIO;
switch (bind_version) {
case RPCBVERS_4:
case RPCBVERS_3:
map->r_netid = rpc_peeraddr2str(clnt, RPC_DISPLAY_NETID);
map->r_addr = rpc_sockaddr2uaddr(sap);
map->r_owner = "";
break;
case RPCBVERS_2:
map->r_addr = NULL;
break;
default:
BUG();
}
child = rpcb_call_async(rpcb_clnt, map, proc);
rpc_release_client(rpcb_clnt);
if (IS_ERR(child)) {
/* rpcb_map_release() has freed the arguments */
dprintk("RPC: %5u %s: rpc_run_task failed\n",
task->tk_pid, __func__);
return;
}
xprt->stat.bind_count++;
rpc_put_task(child);
return;
bailout_release_client:
rpc_release_client(rpcb_clnt);
bailout_nofree:
rpcb_wake_rpcbind_waiters(xprt, status);
task->tk_status = status;
}
EXPORT_SYMBOL_GPL(rpcb_getport_async);
/*
* Rpcbind child task calls this callback via tk_exit.
*/
static void rpcb_getport_done(struct rpc_task *child, void *data)
{
struct rpcbind_args *map = data;
struct rpc_xprt *xprt = map->r_xprt;
int status = child->tk_status;
/* Garbage reply: retry with a lesser rpcbind version */
if (status == -EIO)
status = -EPROTONOSUPPORT;
/* rpcbind server doesn't support this rpcbind protocol version */
if (status == -EPROTONOSUPPORT)
xprt->bind_index++;
if (status < 0) {
/* rpcbind server not available on remote host? */
xprt->ops->set_port(xprt, 0);
} else if (map->r_port == 0) {
/* Requested RPC service wasn't registered on remote host */
xprt->ops->set_port(xprt, 0);
status = -EACCES;
} else {
/* Succeeded */
xprt->ops->set_port(xprt, map->r_port);
xprt_set_bound(xprt);
status = 0;
}
dprintk("RPC: %5u rpcb_getport_done(status %d, port %u)\n",
child->tk_pid, status, map->r_port);
map->r_status = status;
}
/*
* XDR functions for rpcbind
*/
static int rpcb_enc_mapping(struct rpc_rqst *req, __be32 *p,
const struct rpcbind_args *rpcb)
{
struct rpc_task *task = req->rq_task;
struct xdr_stream xdr;
dprintk("RPC: %5u encoding PMAP_%s call (%u, %u, %d, %u)\n",
task->tk_pid, task->tk_msg.rpc_proc->p_name,
rpcb->r_prog, rpcb->r_vers, rpcb->r_prot, rpcb->r_port);
xdr_init_encode(&xdr, &req->rq_snd_buf, p);
p = xdr_reserve_space(&xdr, sizeof(__be32) * RPCB_mappingargs_sz);
if (unlikely(p == NULL))
return -EIO;
*p++ = htonl(rpcb->r_prog);
*p++ = htonl(rpcb->r_vers);
*p++ = htonl(rpcb->r_prot);
*p = htonl(rpcb->r_port);
return 0;
}
static int rpcb_dec_getport(struct rpc_rqst *req, __be32 *p,
struct rpcbind_args *rpcb)
{
struct rpc_task *task = req->rq_task;
struct xdr_stream xdr;
unsigned long port;
xdr_init_decode(&xdr, &req->rq_rcv_buf, p);
rpcb->r_port = 0;
p = xdr_inline_decode(&xdr, sizeof(__be32));
if (unlikely(p == NULL))
return -EIO;
port = ntohl(*p);
dprintk("RPC: %5u PMAP_%s result: %lu\n", task->tk_pid,
task->tk_msg.rpc_proc->p_name, port);
if (unlikely(port > USHORT_MAX))
return -EIO;
rpcb->r_port = port;
return 0;
}
static int rpcb_dec_set(struct rpc_rqst *req, __be32 *p,
unsigned int *boolp)
{
struct rpc_task *task = req->rq_task;
struct xdr_stream xdr;
xdr_init_decode(&xdr, &req->rq_rcv_buf, p);
p = xdr_inline_decode(&xdr, sizeof(__be32));
if (unlikely(p == NULL))
return -EIO;
*boolp = 0;
if (*p)
*boolp = 1;
dprintk("RPC: %5u RPCB_%s call %s\n",
task->tk_pid, task->tk_msg.rpc_proc->p_name,
(*boolp ? "succeeded" : "failed"));
return 0;
}
static int encode_rpcb_string(struct xdr_stream *xdr, const char *string,
const u32 maxstrlen)
{
u32 len;
__be32 *p;
if (unlikely(string == NULL))
return -EIO;
len = strlen(string);
if (unlikely(len > maxstrlen))
return -EIO;
p = xdr_reserve_space(xdr, sizeof(__be32) + len);
if (unlikely(p == NULL))
return -EIO;
xdr_encode_opaque(p, string, len);
return 0;
}
static int rpcb_enc_getaddr(struct rpc_rqst *req, __be32 *p,
const struct rpcbind_args *rpcb)
{
struct rpc_task *task = req->rq_task;
struct xdr_stream xdr;
dprintk("RPC: %5u encoding RPCB_%s call (%u, %u, '%s', '%s')\n",
task->tk_pid, task->tk_msg.rpc_proc->p_name,
rpcb->r_prog, rpcb->r_vers,
rpcb->r_netid, rpcb->r_addr);
xdr_init_encode(&xdr, &req->rq_snd_buf, p);
p = xdr_reserve_space(&xdr,
sizeof(__be32) * (RPCB_program_sz + RPCB_version_sz));
if (unlikely(p == NULL))
return -EIO;
*p++ = htonl(rpcb->r_prog);
*p = htonl(rpcb->r_vers);
if (encode_rpcb_string(&xdr, rpcb->r_netid, RPCBIND_MAXNETIDLEN))
return -EIO;
if (encode_rpcb_string(&xdr, rpcb->r_addr, RPCBIND_MAXUADDRLEN))
return -EIO;
if (encode_rpcb_string(&xdr, rpcb->r_owner, RPCB_MAXOWNERLEN))
return -EIO;
return 0;
}
static int rpcb_dec_getaddr(struct rpc_rqst *req, __be32 *p,
struct rpcbind_args *rpcb)
{
struct sockaddr_storage address;
struct sockaddr *sap = (struct sockaddr *)&address;
struct rpc_task *task = req->rq_task;
struct xdr_stream xdr;
u32 len;
rpcb->r_port = 0;
xdr_init_decode(&xdr, &req->rq_rcv_buf, p);
p = xdr_inline_decode(&xdr, sizeof(__be32));
if (unlikely(p == NULL))
goto out_fail;
len = ntohl(*p);
/*
* If the returned universal address is a null string,
* the requested RPC service was not registered.
*/
if (len == 0) {
dprintk("RPC: %5u RPCB reply: program not registered\n",
task->tk_pid);
return 0;
}
if (unlikely(len > RPCBIND_MAXUADDRLEN))
goto out_fail;
p = xdr_inline_decode(&xdr, len);
if (unlikely(p == NULL))
goto out_fail;
dprintk("RPC: %5u RPCB_%s reply: %s\n", task->tk_pid,
task->tk_msg.rpc_proc->p_name, (char *)p);
if (rpc_uaddr2sockaddr((char *)p, len, sap, sizeof(address)) == 0)
goto out_fail;
rpcb->r_port = rpc_get_port(sap);
return 0;
out_fail:
dprintk("RPC: %5u malformed RPCB_%s reply\n",
task->tk_pid, task->tk_msg.rpc_proc->p_name);
return -EIO;
}
/*
* Not all rpcbind procedures described in RFC 1833 are implemented
* since the Linux kernel RPC code requires only these.
*/
static struct rpc_procinfo rpcb_procedures2[] = {
[RPCBPROC_SET] = {
.p_proc = RPCBPROC_SET,
.p_encode = (kxdrproc_t)rpcb_enc_mapping,
.p_decode = (kxdrproc_t)rpcb_dec_set,
.p_arglen = RPCB_mappingargs_sz,
.p_replen = RPCB_setres_sz,
.p_statidx = RPCBPROC_SET,
.p_timer = 0,
.p_name = "SET",
},
[RPCBPROC_UNSET] = {
.p_proc = RPCBPROC_UNSET,
.p_encode = (kxdrproc_t)rpcb_enc_mapping,
.p_decode = (kxdrproc_t)rpcb_dec_set,
.p_arglen = RPCB_mappingargs_sz,
.p_replen = RPCB_setres_sz,
.p_statidx = RPCBPROC_UNSET,
.p_timer = 0,
.p_name = "UNSET",
},
[RPCBPROC_GETPORT] = {
.p_proc = RPCBPROC_GETPORT,
.p_encode = (kxdrproc_t)rpcb_enc_mapping,
.p_decode = (kxdrproc_t)rpcb_dec_getport,
.p_arglen = RPCB_mappingargs_sz,
.p_replen = RPCB_getportres_sz,
.p_statidx = RPCBPROC_GETPORT,
.p_timer = 0,
.p_name = "GETPORT",
},
};
static struct rpc_procinfo rpcb_procedures3[] = {
[RPCBPROC_SET] = {
.p_proc = RPCBPROC_SET,
.p_encode = (kxdrproc_t)rpcb_enc_getaddr,
.p_decode = (kxdrproc_t)rpcb_dec_set,
.p_arglen = RPCB_getaddrargs_sz,
.p_replen = RPCB_setres_sz,
.p_statidx = RPCBPROC_SET,
.p_timer = 0,
.p_name = "SET",
},
[RPCBPROC_UNSET] = {
.p_proc = RPCBPROC_UNSET,
.p_encode = (kxdrproc_t)rpcb_enc_getaddr,
.p_decode = (kxdrproc_t)rpcb_dec_set,
.p_arglen = RPCB_getaddrargs_sz,
.p_replen = RPCB_setres_sz,
.p_statidx = RPCBPROC_UNSET,
.p_timer = 0,
.p_name = "UNSET",
},
[RPCBPROC_GETADDR] = {
.p_proc = RPCBPROC_GETADDR,
.p_encode = (kxdrproc_t)rpcb_enc_getaddr,
.p_decode = (kxdrproc_t)rpcb_dec_getaddr,
.p_arglen = RPCB_getaddrargs_sz,
.p_replen = RPCB_getaddrres_sz,
.p_statidx = RPCBPROC_GETADDR,
.p_timer = 0,
.p_name = "GETADDR",
},
};
static struct rpc_procinfo rpcb_procedures4[] = {
[RPCBPROC_SET] = {
.p_proc = RPCBPROC_SET,
.p_encode = (kxdrproc_t)rpcb_enc_getaddr,
.p_decode = (kxdrproc_t)rpcb_dec_set,
.p_arglen = RPCB_getaddrargs_sz,
.p_replen = RPCB_setres_sz,
.p_statidx = RPCBPROC_SET,
.p_timer = 0,
.p_name = "SET",
},
[RPCBPROC_UNSET] = {
.p_proc = RPCBPROC_UNSET,
.p_encode = (kxdrproc_t)rpcb_enc_getaddr,
.p_decode = (kxdrproc_t)rpcb_dec_set,
.p_arglen = RPCB_getaddrargs_sz,
.p_replen = RPCB_setres_sz,
.p_statidx = RPCBPROC_UNSET,
.p_timer = 0,
.p_name = "UNSET",
},
[RPCBPROC_GETADDR] = {
.p_proc = RPCBPROC_GETADDR,
.p_encode = (kxdrproc_t)rpcb_enc_getaddr,
.p_decode = (kxdrproc_t)rpcb_dec_getaddr,
.p_arglen = RPCB_getaddrargs_sz,
.p_replen = RPCB_getaddrres_sz,
.p_statidx = RPCBPROC_GETADDR,
.p_timer = 0,
.p_name = "GETADDR",
},
};
static struct rpcb_info rpcb_next_version[] = {
{
.rpc_vers = RPCBVERS_2,
.rpc_proc = &rpcb_procedures2[RPCBPROC_GETPORT],
},
{
.rpc_proc = NULL,
},
};
static struct rpcb_info rpcb_next_version6[] = {
{
.rpc_vers = RPCBVERS_4,
.rpc_proc = &rpcb_procedures4[RPCBPROC_GETADDR],
},
{
.rpc_vers = RPCBVERS_3,
.rpc_proc = &rpcb_procedures3[RPCBPROC_GETADDR],
},
{
.rpc_proc = NULL,
},
};
static struct rpc_version rpcb_version2 = {
.number = RPCBVERS_2,
.nrprocs = RPCB_HIGHPROC_2,
.procs = rpcb_procedures2
};
static struct rpc_version rpcb_version3 = {
.number = RPCBVERS_3,
.nrprocs = RPCB_HIGHPROC_3,
.procs = rpcb_procedures3
};
static struct rpc_version rpcb_version4 = {
.number = RPCBVERS_4,
.nrprocs = RPCB_HIGHPROC_4,
.procs = rpcb_procedures4
};
static struct rpc_version *rpcb_version[] = {
NULL,
NULL,
&rpcb_version2,
&rpcb_version3,
&rpcb_version4
};
static struct rpc_stat rpcb_stats;
static struct rpc_program rpcb_program = {
.name = "rpcbind",
.number = RPCBIND_PROGRAM,
.nrvers = ARRAY_SIZE(rpcb_version),
.version = rpcb_version,
.stats = &rpcb_stats,
};
| gpl-2.0 |
andrepuschmann/linux-omap | arch/arm/mach-omap2/board-igep0020.c | 383 | 18041 | /*
* Copyright (C) 2009 Integration Software and Electronic Engineering.
*
* Modified from mach-omap2/board-generic.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/fixed.h>
#include <linux/i2c/twl.h>
#include <linux/mmc/host.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <plat/board.h>
#include <plat/common.h>
#include <plat/gpmc.h>
#include <plat/usb.h>
#include <video/omapdss.h>
#include <video/omap-panel-generic-dpi.h>
#include <plat/onenand.h>
#include "mux.h"
#include "hsmmc.h"
#include "sdram-numonyx-m65kxxxxam.h"
#include "common-board-devices.h"
#define IGEP2_SMSC911X_CS 5
#define IGEP2_SMSC911X_GPIO 176
#define IGEP2_GPIO_USBH_NRESET 24
#define IGEP2_GPIO_LED0_GREEN 26
#define IGEP2_GPIO_LED0_RED 27
#define IGEP2_GPIO_LED1_RED 28
#define IGEP2_GPIO_DVI_PUP 170
#define IGEP2_RB_GPIO_WIFI_NPD 94
#define IGEP2_RB_GPIO_WIFI_NRESET 95
#define IGEP2_RB_GPIO_BT_NRESET 137
#define IGEP2_RC_GPIO_WIFI_NPD 138
#define IGEP2_RC_GPIO_WIFI_NRESET 139
#define IGEP2_RC_GPIO_BT_NRESET 137
#define IGEP3_GPIO_LED0_GREEN 54
#define IGEP3_GPIO_LED0_RED 53
#define IGEP3_GPIO_LED1_RED 16
#define IGEP3_GPIO_USBH_NRESET 183
/*
* IGEP2 Hardware Revision Table
*
* --------------------------------------------------------------------------
* | Id. | Hw Rev. | HW0 (28) | WIFI_NPD | WIFI_NRESET | BT_NRESET |
* --------------------------------------------------------------------------
* | 0 | B | high | gpio94 | gpio95 | - |
* | 0 | B/C (B-compatible) | high | gpio94 | gpio95 | gpio137 |
* | 1 | C | low | gpio138 | gpio139 | gpio137 |
* --------------------------------------------------------------------------
*/
#define IGEP2_BOARD_HWREV_B 0
#define IGEP2_BOARD_HWREV_C 1
#define IGEP3_BOARD_HWREV 2
static u8 hwrev;
static void __init igep2_get_revision(void)
{
u8 ret;
if (machine_is_igep0030()) {
hwrev = IGEP3_BOARD_HWREV;
return;
}
omap_mux_init_gpio(IGEP2_GPIO_LED1_RED, OMAP_PIN_INPUT);
if (gpio_request_one(IGEP2_GPIO_LED1_RED, GPIOF_IN, "GPIO_HW0_REV")) {
pr_warning("IGEP2: Could not obtain gpio GPIO_HW0_REV\n");
pr_err("IGEP2: Unknown Hardware Revision\n");
return;
}
ret = gpio_get_value(IGEP2_GPIO_LED1_RED);
if (ret == 0) {
pr_info("IGEP2: Hardware Revision C (B-NON compatible)\n");
hwrev = IGEP2_BOARD_HWREV_C;
} else if (ret == 1) {
pr_info("IGEP2: Hardware Revision B/C (B compatible)\n");
hwrev = IGEP2_BOARD_HWREV_B;
} else {
pr_err("IGEP2: Unknown Hardware Revision\n");
hwrev = -1;
}
gpio_free(IGEP2_GPIO_LED1_RED);
}
#if defined(CONFIG_MTD_ONENAND_OMAP2) || \
defined(CONFIG_MTD_ONENAND_OMAP2_MODULE)
#define ONENAND_MAP 0x20000000
/* NAND04GR4E1A ( x2 Flash built-in COMBO POP MEMORY )
* Since the device is equipped with two DataRAMs, and two-plane NAND
* Flash memory array, these two component enables simultaneous program
* of 4KiB. Plane1 has only even blocks such as block0, block2, block4
* while Plane2 has only odd blocks such as block1, block3, block5.
* So MTD regards it as 4KiB page size and 256KiB block size 64*(2*2048)
*/
static struct mtd_partition igep_onenand_partitions[] = {
{
.name = "X-Loader",
.offset = 0,
.size = 2 * (64*(2*2048))
},
{
.name = "U-Boot",
.offset = MTDPART_OFS_APPEND,
.size = 6 * (64*(2*2048)),
},
{
.name = "Environment",
.offset = MTDPART_OFS_APPEND,
.size = 2 * (64*(2*2048)),
},
{
.name = "Kernel",
.offset = MTDPART_OFS_APPEND,
.size = 12 * (64*(2*2048)),
},
{
.name = "File System",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
},
};
static struct omap_onenand_platform_data igep_onenand_data = {
.parts = igep_onenand_partitions,
.nr_parts = ARRAY_SIZE(igep_onenand_partitions),
.dma_channel = -1, /* disable DMA in OMAP OneNAND driver */
};
static struct platform_device igep_onenand_device = {
.name = "omap2-onenand",
.id = -1,
.dev = {
.platform_data = &igep_onenand_data,
},
};
static void __init igep_flash_init(void)
{
u8 cs = 0;
u8 onenandcs = GPMC_CS_NUM + 1;
for (cs = 0; cs < GPMC_CS_NUM; cs++) {
u32 ret;
ret = gpmc_cs_read_reg(cs, GPMC_CS_CONFIG1);
/* Check if NAND/oneNAND is configured */
if ((ret & 0xC00) == 0x800)
/* NAND found */
pr_err("IGEP: Unsupported NAND found\n");
else {
ret = gpmc_cs_read_reg(cs, GPMC_CS_CONFIG7);
if ((ret & 0x3F) == (ONENAND_MAP >> 24))
/* ONENAND found */
onenandcs = cs;
}
}
if (onenandcs > GPMC_CS_NUM) {
pr_err("IGEP: Unable to find configuration in GPMC\n");
return;
}
igep_onenand_data.cs = onenandcs;
if (platform_device_register(&igep_onenand_device) < 0)
pr_err("IGEP: Unable to register OneNAND device\n");
}
#else
static void __init igep_flash_init(void) {}
#endif
#if defined(CONFIG_SMSC911X) || defined(CONFIG_SMSC911X_MODULE)
#include <linux/smsc911x.h>
#include <plat/gpmc-smsc911x.h>
static struct omap_smsc911x_platform_data smsc911x_cfg = {
.cs = IGEP2_SMSC911X_CS,
.gpio_irq = IGEP2_SMSC911X_GPIO,
.gpio_reset = -EINVAL,
.flags = SMSC911X_USE_32BIT | SMSC911X_SAVE_MAC_ADDRESS,
};
static inline void __init igep2_init_smsc911x(void)
{
gpmc_smsc911x_init(&smsc911x_cfg);
}
#else
static inline void __init igep2_init_smsc911x(void) { }
#endif
static struct regulator_consumer_supply igep_vmmc1_supply[] = {
REGULATOR_SUPPLY("vmmc", "omap_hsmmc.0"),
};
/* VMMC1 for OMAP VDD_MMC1 (i/o) and MMC1 card */
static struct regulator_init_data igep_vmmc1 = {
.constraints = {
.min_uV = 1850000,
.max_uV = 3150000,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE
| REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(igep_vmmc1_supply),
.consumer_supplies = igep_vmmc1_supply,
};
static struct regulator_consumer_supply igep_vio_supply[] = {
REGULATOR_SUPPLY("vmmc_aux", "omap_hsmmc.1"),
};
static struct regulator_init_data igep_vio = {
.constraints = {
.min_uV = 1800000,
.max_uV = 1800000,
.apply_uV = 1,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE
| REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(igep_vio_supply),
.consumer_supplies = igep_vio_supply,
};
static struct regulator_consumer_supply igep_vmmc2_supply[] = {
REGULATOR_SUPPLY("vmmc", "omap_hsmmc.1"),
};
static struct regulator_init_data igep_vmmc2 = {
.constraints = {
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.always_on = 1,
},
.num_consumer_supplies = ARRAY_SIZE(igep_vmmc2_supply),
.consumer_supplies = igep_vmmc2_supply,
};
static struct fixed_voltage_config igep_vwlan = {
.supply_name = "vwlan",
.microvolts = 3300000,
.gpio = -EINVAL,
.enabled_at_boot = 1,
.init_data = &igep_vmmc2,
};
static struct platform_device igep_vwlan_device = {
.name = "reg-fixed-voltage",
.id = 0,
.dev = {
.platform_data = &igep_vwlan,
},
};
static struct omap2_hsmmc_info mmc[] = {
{
.mmc = 1,
.caps = MMC_CAP_4_BIT_DATA,
.gpio_cd = -EINVAL,
.gpio_wp = -EINVAL,
},
#if defined(CONFIG_LIBERTAS_SDIO) || defined(CONFIG_LIBERTAS_SDIO_MODULE)
{
.mmc = 2,
.caps = MMC_CAP_4_BIT_DATA,
.gpio_cd = -EINVAL,
.gpio_wp = -EINVAL,
},
#endif
{} /* Terminator */
};
#if defined(CONFIG_LEDS_GPIO) || defined(CONFIG_LEDS_GPIO_MODULE)
#include <linux/leds.h>
static struct gpio_led igep_gpio_leds[] = {
[0] = {
.name = "gpio-led:red:d0",
.default_trigger = "default-off"
},
[1] = {
.name = "gpio-led:green:d0",
.default_trigger = "default-off",
},
[2] = {
.name = "gpio-led:red:d1",
.default_trigger = "default-off",
},
[3] = {
.name = "gpio-led:green:d1",
.default_trigger = "heartbeat",
.gpio = -EINVAL, /* gets replaced */
.active_low = 1,
},
};
static struct gpio_led_platform_data igep_led_pdata = {
.leds = igep_gpio_leds,
.num_leds = ARRAY_SIZE(igep_gpio_leds),
};
static struct platform_device igep_led_device = {
.name = "leds-gpio",
.id = -1,
.dev = {
.platform_data = &igep_led_pdata,
},
};
static void __init igep_leds_init(void)
{
if (machine_is_igep0020()) {
igep_gpio_leds[0].gpio = IGEP2_GPIO_LED0_RED;
igep_gpio_leds[1].gpio = IGEP2_GPIO_LED0_GREEN;
igep_gpio_leds[2].gpio = IGEP2_GPIO_LED1_RED;
} else {
igep_gpio_leds[0].gpio = IGEP3_GPIO_LED0_RED;
igep_gpio_leds[1].gpio = IGEP3_GPIO_LED0_GREEN;
igep_gpio_leds[2].gpio = IGEP3_GPIO_LED1_RED;
}
platform_device_register(&igep_led_device);
}
#else
static struct gpio igep_gpio_leds[] __initdata = {
{ -EINVAL, GPIOF_OUT_INIT_LOW, "gpio-led:red:d0" },
{ -EINVAL, GPIOF_OUT_INIT_LOW, "gpio-led:green:d0" },
{ -EINVAL, GPIOF_OUT_INIT_LOW, "gpio-led:red:d1" },
};
static inline void igep_leds_init(void)
{
int i;
if (machine_is_igep0020()) {
igep_gpio_leds[0].gpio = IGEP2_GPIO_LED0_RED;
igep_gpio_leds[1].gpio = IGEP2_GPIO_LED0_GREEN;
igep_gpio_leds[2].gpio = IGEP2_GPIO_LED1_RED;
} else {
igep_gpio_leds[0].gpio = IGEP3_GPIO_LED0_RED;
igep_gpio_leds[1].gpio = IGEP3_GPIO_LED0_GREEN;
igep_gpio_leds[2].gpio = IGEP3_GPIO_LED1_RED;
}
if (gpio_request_array(igep_gpio_leds, ARRAY_SIZE(igep_gpio_leds))) {
pr_warning("IGEP v2: Could not obtain leds gpios\n");
return;
}
for (i = 0; i < ARRAY_SIZE(igep_gpio_leds); i++)
gpio_export(igep_gpio_leds[i].gpio, 0);
}
#endif
static struct gpio igep2_twl_gpios[] = {
{ -EINVAL, GPIOF_IN, "GPIO_EHCI_NOC" },
{ -EINVAL, GPIOF_OUT_INIT_LOW, "GPIO_USBH_CPEN" },
};
static int igep_twl_gpio_setup(struct device *dev,
unsigned gpio, unsigned ngpio)
{
int ret;
/* gpio + 0 is "mmc0_cd" (input/IRQ) */
mmc[0].gpio_cd = gpio + 0;
omap2_hsmmc_init(mmc);
/* TWL4030_GPIO_MAX + 1 == ledB (out, active low LED) */
#if !defined(CONFIG_LEDS_GPIO) && !defined(CONFIG_LEDS_GPIO_MODULE)
ret = gpio_request_one(gpio + TWL4030_GPIO_MAX + 1, GPIOF_OUT_INIT_HIGH,
"gpio-led:green:d1");
if (ret == 0)
gpio_export(gpio + TWL4030_GPIO_MAX + 1, 0);
else
pr_warning("IGEP: Could not obtain gpio GPIO_LED1_GREEN\n");
#else
igep_gpio_leds[3].gpio = gpio + TWL4030_GPIO_MAX + 1;
#endif
if (machine_is_igep0030())
return 0;
/*
* REVISIT: need ehci-omap hooks for external VBUS
* power switch and overcurrent detect
*/
igep2_twl_gpios[0].gpio = gpio + 1;
/* TWL4030_GPIO_MAX + 0 == ledA, GPIO_USBH_CPEN (out, active low) */
igep2_twl_gpios[1].gpio = gpio + TWL4030_GPIO_MAX;
ret = gpio_request_array(igep2_twl_gpios, ARRAY_SIZE(igep2_twl_gpios));
if (ret < 0)
pr_err("IGEP2: Could not obtain gpio for USBH_CPEN");
return 0;
};
static struct twl4030_gpio_platform_data igep_twl4030_gpio_pdata = {
.gpio_base = OMAP_MAX_GPIO_LINES,
.irq_base = TWL4030_GPIO_IRQ_BASE,
.irq_end = TWL4030_GPIO_IRQ_END,
.use_leds = true,
.setup = igep_twl_gpio_setup,
};
static int igep2_enable_dvi(struct omap_dss_device *dssdev)
{
gpio_direction_output(IGEP2_GPIO_DVI_PUP, 1);
return 0;
}
static void igep2_disable_dvi(struct omap_dss_device *dssdev)
{
gpio_direction_output(IGEP2_GPIO_DVI_PUP, 0);
}
static struct panel_generic_dpi_data dvi_panel = {
.name = "generic",
.platform_enable = igep2_enable_dvi,
.platform_disable = igep2_disable_dvi,
};
static struct omap_dss_device igep2_dvi_device = {
.type = OMAP_DISPLAY_TYPE_DPI,
.name = "dvi",
.driver_name = "generic_dpi_panel",
.data = &dvi_panel,
.phy.dpi.data_lines = 24,
};
static struct omap_dss_device *igep2_dss_devices[] = {
&igep2_dvi_device
};
static struct omap_dss_board_info igep2_dss_data = {
.num_devices = ARRAY_SIZE(igep2_dss_devices),
.devices = igep2_dss_devices,
.default_device = &igep2_dvi_device,
};
static void __init igep2_display_init(void)
{
int err = gpio_request_one(IGEP2_GPIO_DVI_PUP, GPIOF_OUT_INIT_HIGH,
"GPIO_DVI_PUP");
if (err)
pr_err("IGEP v2: Could not obtain gpio GPIO_DVI_PUP\n");
}
static struct platform_device *igep_devices[] __initdata = {
&igep_vwlan_device,
};
static void __init igep_init_early(void)
{
omap2_init_common_infrastructure();
omap2_init_common_devices(m65kxxxxam_sdrc_params,
m65kxxxxam_sdrc_params);
}
static int igep2_keymap[] = {
KEY(0, 0, KEY_LEFT),
KEY(0, 1, KEY_RIGHT),
KEY(0, 2, KEY_A),
KEY(0, 3, KEY_B),
KEY(1, 0, KEY_DOWN),
KEY(1, 1, KEY_UP),
KEY(1, 2, KEY_E),
KEY(1, 3, KEY_F),
KEY(2, 0, KEY_ENTER),
KEY(2, 1, KEY_I),
KEY(2, 2, KEY_J),
KEY(2, 3, KEY_K),
KEY(3, 0, KEY_M),
KEY(3, 1, KEY_N),
KEY(3, 2, KEY_O),
KEY(3, 3, KEY_P)
};
static struct matrix_keymap_data igep2_keymap_data = {
.keymap = igep2_keymap,
.keymap_size = ARRAY_SIZE(igep2_keymap),
};
static struct twl4030_keypad_data igep2_keypad_pdata = {
.keymap_data = &igep2_keymap_data,
.rows = 4,
.cols = 4,
.rep = 1,
};
static struct twl4030_platform_data igep_twldata = {
/* platform_data for children goes here */
.gpio = &igep_twl4030_gpio_pdata,
.vmmc1 = &igep_vmmc1,
.vio = &igep_vio,
};
static struct i2c_board_info __initdata igep2_i2c3_boardinfo[] = {
{
I2C_BOARD_INFO("eeprom", 0x50),
},
};
static void __init igep_i2c_init(void)
{
int ret;
omap3_pmic_get_config(&igep_twldata, TWL_COMMON_PDATA_USB, 0);
if (machine_is_igep0020()) {
/*
* Bus 3 is attached to the DVI port where devices like the
* pico DLP projector don't work reliably with 400kHz
*/
ret = omap_register_i2c_bus(3, 100, igep2_i2c3_boardinfo,
ARRAY_SIZE(igep2_i2c3_boardinfo));
if (ret)
pr_warning("IGEP2: Could not register I2C3 bus (%d)\n", ret);
igep_twldata.keypad = &igep2_keypad_pdata;
/* Get common pmic data */
omap3_pmic_get_config(&igep_twldata, TWL_COMMON_PDATA_AUDIO,
TWL_COMMON_REGULATOR_VPLL2);
igep_twldata.vpll2->constraints.apply_uV = true;
igep_twldata.vpll2->constraints.name = "VDVI";
}
omap3_pmic_init("twl4030", &igep_twldata);
}
static const struct usbhs_omap_board_data igep2_usbhs_bdata __initconst = {
.port_mode[0] = OMAP_EHCI_PORT_MODE_PHY,
.port_mode[1] = OMAP_USBHS_PORT_MODE_UNUSED,
.port_mode[2] = OMAP_USBHS_PORT_MODE_UNUSED,
.phy_reset = true,
.reset_gpio_port[0] = IGEP2_GPIO_USBH_NRESET,
.reset_gpio_port[1] = -EINVAL,
.reset_gpio_port[2] = -EINVAL,
};
static const struct usbhs_omap_board_data igep3_usbhs_bdata __initconst = {
.port_mode[0] = OMAP_USBHS_PORT_MODE_UNUSED,
.port_mode[1] = OMAP_EHCI_PORT_MODE_PHY,
.port_mode[2] = OMAP_USBHS_PORT_MODE_UNUSED,
.phy_reset = true,
.reset_gpio_port[0] = -EINVAL,
.reset_gpio_port[1] = IGEP3_GPIO_USBH_NRESET,
.reset_gpio_port[2] = -EINVAL,
};
#ifdef CONFIG_OMAP_MUX
static struct omap_board_mux board_mux[] __initdata = {
{ .reg_offset = OMAP_MUX_TERMINATOR },
};
#endif
#if defined(CONFIG_LIBERTAS_SDIO) || defined(CONFIG_LIBERTAS_SDIO_MODULE)
static struct gpio igep_wlan_bt_gpios[] __initdata = {
{ -EINVAL, GPIOF_OUT_INIT_HIGH, "GPIO_WIFI_NPD" },
{ -EINVAL, GPIOF_OUT_INIT_HIGH, "GPIO_WIFI_NRESET" },
{ -EINVAL, GPIOF_OUT_INIT_HIGH, "GPIO_BT_NRESET" },
};
static void __init igep_wlan_bt_init(void)
{
int err;
/* GPIO's for WLAN-BT combo depends on hardware revision */
if (hwrev == IGEP2_BOARD_HWREV_B) {
igep_wlan_bt_gpios[0].gpio = IGEP2_RB_GPIO_WIFI_NPD;
igep_wlan_bt_gpios[1].gpio = IGEP2_RB_GPIO_WIFI_NRESET;
igep_wlan_bt_gpios[2].gpio = IGEP2_RB_GPIO_BT_NRESET;
} else if (hwrev == IGEP2_BOARD_HWREV_C || machine_is_igep0030()) {
igep_wlan_bt_gpios[0].gpio = IGEP2_RC_GPIO_WIFI_NPD;
igep_wlan_bt_gpios[1].gpio = IGEP2_RC_GPIO_WIFI_NRESET;
igep_wlan_bt_gpios[2].gpio = IGEP2_RC_GPIO_BT_NRESET;
} else
return;
err = gpio_request_array(igep_wlan_bt_gpios,
ARRAY_SIZE(igep_wlan_bt_gpios));
if (err) {
pr_warning("IGEP2: Could not obtain WIFI/BT gpios\n");
return;
}
gpio_export(igep_wlan_bt_gpios[0].gpio, 0);
gpio_export(igep_wlan_bt_gpios[1].gpio, 0);
gpio_export(igep_wlan_bt_gpios[2].gpio, 0);
gpio_set_value(igep_wlan_bt_gpios[1].gpio, 0);
udelay(10);
gpio_set_value(igep_wlan_bt_gpios[1].gpio, 1);
}
#else
static inline void __init igep_wlan_bt_init(void) { }
#endif
static void __init igep_init(void)
{
omap3_mux_init(board_mux, OMAP_PACKAGE_CBB);
/* Get IGEP2 hardware revision */
igep2_get_revision();
/* Register I2C busses and drivers */
igep_i2c_init();
platform_add_devices(igep_devices, ARRAY_SIZE(igep_devices));
omap_serial_init();
usb_musb_init(NULL);
igep_flash_init();
igep_leds_init();
/*
* WLAN-BT combo module from MuRata which has a Marvell WLAN
* (88W8686) + CSR Bluetooth chipset. Uses SDIO interface.
*/
igep_wlan_bt_init();
if (machine_is_igep0020()) {
omap_display_init(&igep2_dss_data);
igep2_display_init();
igep2_init_smsc911x();
usbhs_init(&igep2_usbhs_bdata);
} else {
usbhs_init(&igep3_usbhs_bdata);
}
}
MACHINE_START(IGEP0020, "IGEP v2 board")
.boot_params = 0x80000100,
.reserve = omap_reserve,
.map_io = omap3_map_io,
.init_early = igep_init_early,
.init_irq = omap3_init_irq,
.init_machine = igep_init,
.timer = &omap3_timer,
MACHINE_END
MACHINE_START(IGEP0030, "IGEP OMAP3 module")
.boot_params = 0x80000100,
.reserve = omap_reserve,
.map_io = omap3_map_io,
.init_early = igep_init_early,
.init_irq = omap3_init_irq,
.init_machine = igep_init,
.timer = &omap3_timer,
MACHINE_END
| gpl-2.0 |
flar2/ville-bulletproof | net/ipv4/netfilter/ipt_ah.c | 383 | 2056 | /* (C) 1999-2000 Yon Uriarte <yon@astaro.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/in.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/netfilter_ipv4/ipt_ah.h>
#include <linux/netfilter/x_tables.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Yon Uriarte <yon@astaro.de>");
MODULE_DESCRIPTION("Xtables: IPv4 IPsec-AH SPI match");
static inline bool
spi_match(u_int32_t min, u_int32_t max, u_int32_t spi, bool invert)
{
bool r;
pr_debug("spi_match:%c 0x%x <= 0x%x <= 0x%x\n",
invert ? '!' : ' ', min, spi, max);
r=(spi >= min && spi <= max) ^ invert;
pr_debug(" result %s\n", r ? "PASS" : "FAILED");
return r;
}
static bool ah_mt(const struct sk_buff *skb, struct xt_action_param *par)
{
struct ip_auth_hdr _ahdr;
const struct ip_auth_hdr *ah;
const struct ipt_ah *ahinfo = par->matchinfo;
if (par->fragoff != 0)
return false;
ah = skb_header_pointer(skb, par->thoff, sizeof(_ahdr), &_ahdr);
if (ah == NULL) {
pr_debug("Dropping evil AH tinygram.\n");
par->hotdrop = true;
return 0;
}
return spi_match(ahinfo->spis[0], ahinfo->spis[1],
ntohl(ah->spi),
!!(ahinfo->invflags & IPT_AH_INV_SPI));
}
static int ah_mt_check(const struct xt_mtchk_param *par)
{
const struct ipt_ah *ahinfo = par->matchinfo;
if (ahinfo->invflags & ~IPT_AH_INV_MASK) {
pr_debug("unknown flags %X\n", ahinfo->invflags);
return -EINVAL;
}
return 0;
}
static struct xt_match ah_mt_reg __read_mostly = {
.name = "ah",
.family = NFPROTO_IPV4,
.match = ah_mt,
.matchsize = sizeof(struct ipt_ah),
.proto = IPPROTO_AH,
.checkentry = ah_mt_check,
.me = THIS_MODULE,
};
static int __init ah_mt_init(void)
{
return xt_register_match(&ah_mt_reg);
}
static void __exit ah_mt_exit(void)
{
xt_unregister_match(&ah_mt_reg);
}
module_init(ah_mt_init);
module_exit(ah_mt_exit);
| gpl-2.0 |
jmztaylor/android_kernel_htc_m8ul | net/netfilter/nf_conntrack_proto.c | 383 | 9653 |
/* (C) 1999-2001 Paul `Rusty' Russell
* (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
* (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/types.h>
#include <linux/netfilter.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <linux/vmalloc.h>
#include <linux/stddef.h>
#include <linux/err.h>
#include <linux/percpu.h>
#include <linux/notifier.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/rtnetlink.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_l3proto.h>
#include <net/netfilter/nf_conntrack_l4proto.h>
#include <net/netfilter/nf_conntrack_core.h>
static struct nf_conntrack_l4proto __rcu **nf_ct_protos[PF_MAX] __read_mostly;
struct nf_conntrack_l3proto __rcu *nf_ct_l3protos[AF_MAX] __read_mostly;
EXPORT_SYMBOL_GPL(nf_ct_l3protos);
static DEFINE_MUTEX(nf_ct_proto_mutex);
#ifdef CONFIG_SYSCTL
static int
nf_ct_register_sysctl(struct ctl_table_header **header, struct ctl_path *path,
struct ctl_table *table, unsigned int *users)
{
if (*header == NULL) {
*header = register_sysctl_paths(path, table);
if (*header == NULL)
return -ENOMEM;
}
if (users != NULL)
(*users)++;
return 0;
}
static void
nf_ct_unregister_sysctl(struct ctl_table_header **header,
struct ctl_table *table, unsigned int *users)
{
if (users != NULL && --*users > 0)
return;
unregister_sysctl_table(*header);
*header = NULL;
}
#endif
struct nf_conntrack_l4proto *
__nf_ct_l4proto_find(u_int16_t l3proto, u_int8_t l4proto)
{
if (unlikely(l3proto >= AF_MAX || nf_ct_protos[l3proto] == NULL))
return &nf_conntrack_l4proto_generic;
return rcu_dereference(nf_ct_protos[l3proto][l4proto]);
}
EXPORT_SYMBOL_GPL(__nf_ct_l4proto_find);
struct nf_conntrack_l3proto *
nf_ct_l3proto_find_get(u_int16_t l3proto)
{
struct nf_conntrack_l3proto *p;
rcu_read_lock();
p = __nf_ct_l3proto_find(l3proto);
if (!try_module_get(p->me))
p = &nf_conntrack_l3proto_generic;
rcu_read_unlock();
return p;
}
EXPORT_SYMBOL_GPL(nf_ct_l3proto_find_get);
void nf_ct_l3proto_put(struct nf_conntrack_l3proto *p)
{
module_put(p->me);
}
EXPORT_SYMBOL_GPL(nf_ct_l3proto_put);
int
nf_ct_l3proto_try_module_get(unsigned short l3proto)
{
int ret;
struct nf_conntrack_l3proto *p;
retry: p = nf_ct_l3proto_find_get(l3proto);
if (p == &nf_conntrack_l3proto_generic) {
ret = request_module("nf_conntrack-%d", l3proto);
if (!ret)
goto retry;
return -EPROTOTYPE;
}
return 0;
}
EXPORT_SYMBOL_GPL(nf_ct_l3proto_try_module_get);
void nf_ct_l3proto_module_put(unsigned short l3proto)
{
struct nf_conntrack_l3proto *p;
rcu_read_lock();
p = __nf_ct_l3proto_find(l3proto);
module_put(p->me);
rcu_read_unlock();
}
EXPORT_SYMBOL_GPL(nf_ct_l3proto_module_put);
struct nf_conntrack_l4proto *
nf_ct_l4proto_find_get(u_int16_t l3num, u_int8_t l4num)
{
struct nf_conntrack_l4proto *p;
rcu_read_lock();
p = __nf_ct_l4proto_find(l3num, l4num);
if (!try_module_get(p->me))
p = &nf_conntrack_l4proto_generic;
rcu_read_unlock();
return p;
}
EXPORT_SYMBOL_GPL(nf_ct_l4proto_find_get);
void nf_ct_l4proto_put(struct nf_conntrack_l4proto *p)
{
module_put(p->me);
}
EXPORT_SYMBOL_GPL(nf_ct_l4proto_put);
static int kill_l3proto(struct nf_conn *i, void *data)
{
return nf_ct_l3num(i) == ((struct nf_conntrack_l3proto *)data)->l3proto;
}
static int kill_l4proto(struct nf_conn *i, void *data)
{
struct nf_conntrack_l4proto *l4proto;
l4proto = (struct nf_conntrack_l4proto *)data;
return nf_ct_protonum(i) == l4proto->l4proto &&
nf_ct_l3num(i) == l4proto->l3proto;
}
static int nf_ct_l3proto_register_sysctl(struct nf_conntrack_l3proto *l3proto)
{
int err = 0;
#ifdef CONFIG_SYSCTL
if (l3proto->ctl_table != NULL) {
err = nf_ct_register_sysctl(&l3proto->ctl_table_header,
l3proto->ctl_table_path,
l3proto->ctl_table, NULL);
}
#endif
return err;
}
static void nf_ct_l3proto_unregister_sysctl(struct nf_conntrack_l3proto *l3proto)
{
#ifdef CONFIG_SYSCTL
if (l3proto->ctl_table_header != NULL)
nf_ct_unregister_sysctl(&l3proto->ctl_table_header,
l3proto->ctl_table, NULL);
#endif
}
int nf_conntrack_l3proto_register(struct nf_conntrack_l3proto *proto)
{
int ret = 0;
struct nf_conntrack_l3proto *old;
if (proto->l3proto >= AF_MAX)
return -EBUSY;
if (proto->tuple_to_nlattr && !proto->nlattr_tuple_size)
return -EINVAL;
mutex_lock(&nf_ct_proto_mutex);
old = rcu_dereference_protected(nf_ct_l3protos[proto->l3proto],
lockdep_is_held(&nf_ct_proto_mutex));
if (old != &nf_conntrack_l3proto_generic) {
ret = -EBUSY;
goto out_unlock;
}
ret = nf_ct_l3proto_register_sysctl(proto);
if (ret < 0)
goto out_unlock;
if (proto->nlattr_tuple_size)
proto->nla_size = 3 * proto->nlattr_tuple_size();
rcu_assign_pointer(nf_ct_l3protos[proto->l3proto], proto);
out_unlock:
mutex_unlock(&nf_ct_proto_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(nf_conntrack_l3proto_register);
void nf_conntrack_l3proto_unregister(struct nf_conntrack_l3proto *proto)
{
struct net *net;
BUG_ON(proto->l3proto >= AF_MAX);
mutex_lock(&nf_ct_proto_mutex);
BUG_ON(rcu_dereference_protected(nf_ct_l3protos[proto->l3proto],
lockdep_is_held(&nf_ct_proto_mutex)
) != proto);
rcu_assign_pointer(nf_ct_l3protos[proto->l3proto],
&nf_conntrack_l3proto_generic);
nf_ct_l3proto_unregister_sysctl(proto);
mutex_unlock(&nf_ct_proto_mutex);
synchronize_rcu();
rtnl_lock();
for_each_net(net)
nf_ct_iterate_cleanup(net, kill_l3proto, proto);
rtnl_unlock();
}
EXPORT_SYMBOL_GPL(nf_conntrack_l3proto_unregister);
static int nf_ct_l4proto_register_sysctl(struct nf_conntrack_l4proto *l4proto)
{
int err = 0;
#ifdef CONFIG_SYSCTL
if (l4proto->ctl_table != NULL) {
err = nf_ct_register_sysctl(l4proto->ctl_table_header,
nf_net_netfilter_sysctl_path,
l4proto->ctl_table,
l4proto->ctl_table_users);
if (err < 0)
goto out;
}
#ifdef CONFIG_NF_CONNTRACK_PROC_COMPAT
if (l4proto->ctl_compat_table != NULL) {
err = nf_ct_register_sysctl(&l4proto->ctl_compat_table_header,
nf_net_ipv4_netfilter_sysctl_path,
l4proto->ctl_compat_table, NULL);
if (err == 0)
goto out;
nf_ct_unregister_sysctl(l4proto->ctl_table_header,
l4proto->ctl_table,
l4proto->ctl_table_users);
}
#endif
out:
#endif
return err;
}
static void nf_ct_l4proto_unregister_sysctl(struct nf_conntrack_l4proto *l4proto)
{
#ifdef CONFIG_SYSCTL
if (l4proto->ctl_table_header != NULL &&
*l4proto->ctl_table_header != NULL)
nf_ct_unregister_sysctl(l4proto->ctl_table_header,
l4proto->ctl_table,
l4proto->ctl_table_users);
#ifdef CONFIG_NF_CONNTRACK_PROC_COMPAT
if (l4proto->ctl_compat_table_header != NULL)
nf_ct_unregister_sysctl(&l4proto->ctl_compat_table_header,
l4proto->ctl_compat_table, NULL);
#endif
#endif
}
int nf_conntrack_l4proto_register(struct nf_conntrack_l4proto *l4proto)
{
int ret = 0;
if (l4proto->l3proto >= PF_MAX)
return -EBUSY;
if ((l4proto->to_nlattr && !l4proto->nlattr_size)
|| (l4proto->tuple_to_nlattr && !l4proto->nlattr_tuple_size))
return -EINVAL;
mutex_lock(&nf_ct_proto_mutex);
if (!nf_ct_protos[l4proto->l3proto]) {
struct nf_conntrack_l4proto __rcu **proto_array;
int i;
proto_array = kmalloc(MAX_NF_CT_PROTO *
sizeof(struct nf_conntrack_l4proto *),
GFP_KERNEL);
if (proto_array == NULL) {
ret = -ENOMEM;
goto out_unlock;
}
for (i = 0; i < MAX_NF_CT_PROTO; i++)
RCU_INIT_POINTER(proto_array[i], &nf_conntrack_l4proto_generic);
smp_wmb();
nf_ct_protos[l4proto->l3proto] = proto_array;
} else if (rcu_dereference_protected(
nf_ct_protos[l4proto->l3proto][l4proto->l4proto],
lockdep_is_held(&nf_ct_proto_mutex)
) != &nf_conntrack_l4proto_generic) {
ret = -EBUSY;
goto out_unlock;
}
ret = nf_ct_l4proto_register_sysctl(l4proto);
if (ret < 0)
goto out_unlock;
l4proto->nla_size = 0;
if (l4proto->nlattr_size)
l4proto->nla_size += l4proto->nlattr_size();
if (l4proto->nlattr_tuple_size)
l4proto->nla_size += 3 * l4proto->nlattr_tuple_size();
rcu_assign_pointer(nf_ct_protos[l4proto->l3proto][l4proto->l4proto],
l4proto);
out_unlock:
mutex_unlock(&nf_ct_proto_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(nf_conntrack_l4proto_register);
void nf_conntrack_l4proto_unregister(struct nf_conntrack_l4proto *l4proto)
{
struct net *net;
BUG_ON(l4proto->l3proto >= PF_MAX);
mutex_lock(&nf_ct_proto_mutex);
BUG_ON(rcu_dereference_protected(
nf_ct_protos[l4proto->l3proto][l4proto->l4proto],
lockdep_is_held(&nf_ct_proto_mutex)
) != l4proto);
rcu_assign_pointer(nf_ct_protos[l4proto->l3proto][l4proto->l4proto],
&nf_conntrack_l4proto_generic);
nf_ct_l4proto_unregister_sysctl(l4proto);
mutex_unlock(&nf_ct_proto_mutex);
synchronize_rcu();
rtnl_lock();
for_each_net(net)
nf_ct_iterate_cleanup(net, kill_l4proto, l4proto);
rtnl_unlock();
}
EXPORT_SYMBOL_GPL(nf_conntrack_l4proto_unregister);
int nf_conntrack_proto_init(void)
{
unsigned int i;
int err;
err = nf_ct_l4proto_register_sysctl(&nf_conntrack_l4proto_generic);
if (err < 0)
return err;
for (i = 0; i < AF_MAX; i++)
rcu_assign_pointer(nf_ct_l3protos[i],
&nf_conntrack_l3proto_generic);
return 0;
}
void nf_conntrack_proto_fini(void)
{
unsigned int i;
nf_ct_l4proto_unregister_sysctl(&nf_conntrack_l4proto_generic);
for (i = 0; i < PF_MAX; i++)
kfree(nf_ct_protos[i]);
}
| gpl-2.0 |
ac100-ru/old_ac100_kernel | arch/x86/mm/numa.c | 639 | 1638 | /* Common code for 32 and 64-bit NUMA */
#include <linux/topology.h>
#include <linux/module.h>
#include <linux/bootmem.h>
#ifdef CONFIG_DEBUG_PER_CPU_MAPS
# define DBG(x...) printk(KERN_DEBUG x)
#else
# define DBG(x...)
#endif
/*
* Which logical CPUs are on which nodes
*/
cpumask_var_t node_to_cpumask_map[MAX_NUMNODES];
EXPORT_SYMBOL(node_to_cpumask_map);
/*
* Allocate node_to_cpumask_map based on number of available nodes
* Requires node_possible_map to be valid.
*
* Note: node_to_cpumask() is not valid until after this is done.
* (Use CONFIG_DEBUG_PER_CPU_MAPS to check this.)
*/
void __init setup_node_to_cpumask_map(void)
{
unsigned int node, num = 0;
/* setup nr_node_ids if not done yet */
if (nr_node_ids == MAX_NUMNODES) {
for_each_node_mask(node, node_possible_map)
num = node;
nr_node_ids = num + 1;
}
/* allocate the map */
for (node = 0; node < nr_node_ids; node++)
alloc_bootmem_cpumask_var(&node_to_cpumask_map[node]);
/* cpumask_of_node() will now work */
pr_debug("Node to cpumask map for %d nodes\n", nr_node_ids);
}
#ifdef CONFIG_DEBUG_PER_CPU_MAPS
/*
* Returns a pointer to the bitmask of CPUs on Node 'node'.
*/
const struct cpumask *cpumask_of_node(int node)
{
if (node >= nr_node_ids) {
printk(KERN_WARNING
"cpumask_of_node(%d): node > nr_node_ids(%d)\n",
node, nr_node_ids);
dump_stack();
return cpu_none_mask;
}
if (node_to_cpumask_map[node] == NULL) {
printk(KERN_WARNING
"cpumask_of_node(%d): no node_to_cpumask_map!\n",
node);
dump_stack();
return cpu_online_mask;
}
return node_to_cpumask_map[node];
}
EXPORT_SYMBOL(cpumask_of_node);
#endif
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.