repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
nightscape/yoga-900-kernel | arch/nios2/kernel/sys_nios2.c | 1736 | 1210 | /*
* Copyright (C) 2013 Altera Corporation
* Copyright (C) 2011-2012 Tobias Klauser <tklauser@distanz.ch>
* Copyright (C) 2004 Microtronix Datacom Ltd.
*
* 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/export.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/syscalls.h>
#include <asm/cacheflush.h>
#include <asm/traps.h>
/* sys_cacheflush -- flush the processor cache. */
asmlinkage int sys_cacheflush(unsigned long addr, unsigned long len,
unsigned int op)
{
struct vm_area_struct *vma;
if (len == 0)
return 0;
/* We only support op 0 now, return error if op is non-zero.*/
if (op)
return -EINVAL;
/* Check for overflow */
if (addr + len < addr)
return -EFAULT;
/*
* Verify that the specified address region actually belongs
* to this process.
*/
vma = find_vma(current->mm, addr);
if (vma == NULL || addr < vma->vm_start || addr + len > vma->vm_end)
return -EFAULT;
flush_cache_range(vma, addr, addr + len);
return 0;
}
asmlinkage int sys_getpagesize(void)
{
return PAGE_SIZE;
}
| gpl-2.0 |
NX511J-dev/kernel_zte_nx511j | sound/isa/es1688/es1688.c | 2248 | 10359 | /*
* Driver for generic ESS AudioDrive ESx688 soundcards
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/init.h>
#include <linux/err.h>
#include <linux/isa.h>
#include <linux/isapnp.h>
#include <linux/time.h>
#include <linux/wait.h>
#include <linux/module.h>
#include <asm/dma.h>
#include <sound/core.h>
#include <sound/es1688.h>
#include <sound/mpu401.h>
#include <sound/opl3.h>
#define SNDRV_LEGACY_FIND_FREE_IRQ
#define SNDRV_LEGACY_FIND_FREE_DMA
#include <sound/initval.h>
#define CRD_NAME "Generic ESS ES1688/ES688 AudioDrive"
#define DEV_NAME "es1688"
MODULE_DESCRIPTION(CRD_NAME);
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{ESS,ES688 PnP AudioDrive,pnp:ESS0100},"
"{ESS,ES1688 PnP AudioDrive,pnp:ESS0102},"
"{ESS,ES688 AudioDrive,pnp:ESS6881},"
"{ESS,ES1688 AudioDrive,pnp:ESS1681}}");
MODULE_ALIAS("snd_es968");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
#ifdef CONFIG_PNP
static bool isapnp[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_ISAPNP;
#endif
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE; /* Enable this card */
static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0x220,0x240,0x260 */
static long fm_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* Usually 0x388 */
static long mpu_port[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = -1};
static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 5,7,9,10 */
static int mpu_irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 5,7,9,10 */
static int dma8[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 0,1,3 */
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for " CRD_NAME " soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for " CRD_NAME " soundcard.");
module_param_array(enable, bool, NULL, 0444);
#ifdef CONFIG_PNP
module_param_array(isapnp, bool, NULL, 0444);
MODULE_PARM_DESC(isapnp, "PnP detection for specified soundcard.");
#endif
MODULE_PARM_DESC(enable, "Enable " CRD_NAME " soundcard.");
module_param_array(port, long, NULL, 0444);
MODULE_PARM_DESC(port, "Port # for " CRD_NAME " driver.");
module_param_array(mpu_port, long, NULL, 0444);
MODULE_PARM_DESC(mpu_port, "MPU-401 port # for " CRD_NAME " driver.");
module_param_array(irq, int, NULL, 0444);
module_param_array(fm_port, long, NULL, 0444);
MODULE_PARM_DESC(fm_port, "FM port # for ES1688 driver.");
MODULE_PARM_DESC(irq, "IRQ # for " CRD_NAME " driver.");
module_param_array(mpu_irq, int, NULL, 0444);
MODULE_PARM_DESC(mpu_irq, "MPU-401 IRQ # for " CRD_NAME " driver.");
module_param_array(dma8, int, NULL, 0444);
MODULE_PARM_DESC(dma8, "8-bit DMA # for " CRD_NAME " driver.");
#ifdef CONFIG_PNP
#define is_isapnp_selected(dev) isapnp[dev]
#else
#define is_isapnp_selected(dev) 0
#endif
static int snd_es1688_match(struct device *dev, unsigned int n)
{
return enable[n] && !is_isapnp_selected(n);
}
static int snd_es1688_legacy_create(struct snd_card *card,
struct device *dev, unsigned int n)
{
struct snd_es1688 *chip = card->private_data;
static long possible_ports[] = {0x220, 0x240, 0x260};
static int possible_irqs[] = {5, 9, 10, 7, -1};
static int possible_dmas[] = {1, 3, 0, -1};
int i, error;
if (irq[n] == SNDRV_AUTO_IRQ) {
irq[n] = snd_legacy_find_free_irq(possible_irqs);
if (irq[n] < 0) {
dev_err(dev, "unable to find a free IRQ\n");
return -EBUSY;
}
}
if (dma8[n] == SNDRV_AUTO_DMA) {
dma8[n] = snd_legacy_find_free_dma(possible_dmas);
if (dma8[n] < 0) {
dev_err(dev, "unable to find a free DMA\n");
return -EBUSY;
}
}
if (port[n] != SNDRV_AUTO_PORT)
return snd_es1688_create(card, chip, port[n], mpu_port[n],
irq[n], mpu_irq[n], dma8[n], ES1688_HW_AUTO);
i = 0;
do {
port[n] = possible_ports[i];
error = snd_es1688_create(card, chip, port[n], mpu_port[n],
irq[n], mpu_irq[n], dma8[n], ES1688_HW_AUTO);
} while (error < 0 && ++i < ARRAY_SIZE(possible_ports));
return error;
}
static int snd_es1688_probe(struct snd_card *card, unsigned int n)
{
struct snd_es1688 *chip = card->private_data;
struct snd_opl3 *opl3;
struct snd_pcm *pcm;
int error;
error = snd_es1688_pcm(card, chip, 0, &pcm);
if (error < 0)
return error;
error = snd_es1688_mixer(card, chip);
if (error < 0)
return error;
strlcpy(card->driver, "ES1688", sizeof(card->driver));
strlcpy(card->shortname, pcm->name, sizeof(card->shortname));
snprintf(card->longname, sizeof(card->longname),
"%s at 0x%lx, irq %i, dma %i", pcm->name, chip->port,
chip->irq, chip->dma8);
if (fm_port[n] == SNDRV_AUTO_PORT)
fm_port[n] = port[n]; /* share the same port */
if (fm_port[n] > 0) {
if (snd_opl3_create(card, fm_port[n], fm_port[n] + 2,
OPL3_HW_OPL3, 0, &opl3) < 0)
dev_warn(card->dev,
"opl3 not detected at 0x%lx\n", fm_port[n]);
else {
error = snd_opl3_hwdep_new(opl3, 0, 1, NULL);
if (error < 0)
return error;
}
}
if (mpu_irq[n] >= 0 && mpu_irq[n] != SNDRV_AUTO_IRQ &&
chip->mpu_port > 0) {
error = snd_mpu401_uart_new(card, 0, MPU401_HW_ES1688,
chip->mpu_port, 0,
mpu_irq[n], NULL);
if (error < 0)
return error;
}
return snd_card_register(card);
}
static int snd_es1688_isa_probe(struct device *dev, unsigned int n)
{
struct snd_card *card;
int error;
error = snd_card_create(index[n], id[n], THIS_MODULE,
sizeof(struct snd_es1688), &card);
if (error < 0)
return error;
error = snd_es1688_legacy_create(card, dev, n);
if (error < 0)
goto out;
snd_card_set_dev(card, dev);
error = snd_es1688_probe(card, n);
if (error < 0)
goto out;
dev_set_drvdata(dev, card);
return 0;
out:
snd_card_free(card);
return error;
}
static int snd_es1688_isa_remove(struct device *dev, unsigned int n)
{
snd_card_free(dev_get_drvdata(dev));
dev_set_drvdata(dev, NULL);
return 0;
}
static struct isa_driver snd_es1688_driver = {
.match = snd_es1688_match,
.probe = snd_es1688_isa_probe,
.remove = snd_es1688_isa_remove,
#if 0 /* FIXME */
.suspend = snd_es1688_suspend,
.resume = snd_es1688_resume,
#endif
.driver = {
.name = DEV_NAME
}
};
static int snd_es968_pnp_is_probed;
#ifdef CONFIG_PNP
static int snd_card_es968_pnp(struct snd_card *card, unsigned int n,
struct pnp_card_link *pcard,
const struct pnp_card_device_id *pid)
{
struct snd_es1688 *chip = card->private_data;
struct pnp_dev *pdev;
int error;
pdev = pnp_request_card_device(pcard, pid->devs[0].id, NULL);
if (pdev == NULL)
return -ENODEV;
error = pnp_activate_dev(pdev);
if (error < 0) {
snd_printk(KERN_ERR "ES968 pnp configure failure\n");
return error;
}
port[n] = pnp_port_start(pdev, 0);
dma8[n] = pnp_dma(pdev, 0);
irq[n] = pnp_irq(pdev, 0);
return snd_es1688_create(card, chip, port[n], mpu_port[n], irq[n],
mpu_irq[n], dma8[n], ES1688_HW_AUTO);
}
static int snd_es968_pnp_detect(struct pnp_card_link *pcard,
const struct pnp_card_device_id *pid)
{
struct snd_card *card;
static unsigned int dev;
int error;
struct snd_es1688 *chip;
if (snd_es968_pnp_is_probed)
return -EBUSY;
for ( ; dev < SNDRV_CARDS; dev++) {
if (enable[dev] && isapnp[dev])
break;
}
if (dev == SNDRV_CARDS)
return -ENODEV;
error = snd_card_create(index[dev], id[dev], THIS_MODULE,
sizeof(struct snd_es1688), &card);
if (error < 0)
return error;
chip = card->private_data;
error = snd_card_es968_pnp(card, dev, pcard, pid);
if (error < 0) {
snd_card_free(card);
return error;
}
snd_card_set_dev(card, &pcard->card->dev);
error = snd_es1688_probe(card, dev);
if (error < 0)
return error;
pnp_set_card_drvdata(pcard, card);
snd_es968_pnp_is_probed = 1;
return 0;
}
static void snd_es968_pnp_remove(struct pnp_card_link *pcard)
{
snd_card_free(pnp_get_card_drvdata(pcard));
pnp_set_card_drvdata(pcard, NULL);
snd_es968_pnp_is_probed = 0;
}
#ifdef CONFIG_PM
static int snd_es968_pnp_suspend(struct pnp_card_link *pcard,
pm_message_t state)
{
struct snd_card *card = pnp_get_card_drvdata(pcard);
struct snd_es1688 *chip = card->private_data;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(chip->pcm);
return 0;
}
static int snd_es968_pnp_resume(struct pnp_card_link *pcard)
{
struct snd_card *card = pnp_get_card_drvdata(pcard);
struct snd_es1688 *chip = card->private_data;
snd_es1688_reset(chip);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif
static struct pnp_card_device_id snd_es968_pnpids[] = {
{ .id = "ESS0968", .devs = { { "@@@0968" }, } },
{ .id = "ESS0968", .devs = { { "ESS0968" }, } },
{ .id = "", } /* end */
};
MODULE_DEVICE_TABLE(pnp_card, snd_es968_pnpids);
static struct pnp_card_driver es968_pnpc_driver = {
.flags = PNP_DRIVER_RES_DISABLE,
.name = DEV_NAME " PnP",
.id_table = snd_es968_pnpids,
.probe = snd_es968_pnp_detect,
.remove = snd_es968_pnp_remove,
#ifdef CONFIG_PM
.suspend = snd_es968_pnp_suspend,
.resume = snd_es968_pnp_resume,
#endif
};
#endif
static int __init alsa_card_es1688_init(void)
{
#ifdef CONFIG_PNP
pnp_register_card_driver(&es968_pnpc_driver);
if (snd_es968_pnp_is_probed)
return 0;
pnp_unregister_card_driver(&es968_pnpc_driver);
#endif
return isa_register_driver(&snd_es1688_driver, SNDRV_CARDS);
}
static void __exit alsa_card_es1688_exit(void)
{
if (!snd_es968_pnp_is_probed) {
isa_unregister_driver(&snd_es1688_driver);
return;
}
#ifdef CONFIG_PNP
pnp_unregister_card_driver(&es968_pnpc_driver);
#endif
}
module_init(alsa_card_es1688_init);
module_exit(alsa_card_es1688_exit);
| gpl-2.0 |
Razdroid/razdroid-kernel | drivers/clk/clk-nomadik.c | 2248 | 1570 | #include <linux/clk.h>
#include <linux/clkdev.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/clk-provider.h>
/*
* The Nomadik clock tree is described in the STN8815A12 DB V4.2
* reference manual for the chip, page 94 ff.
*/
void __init nomadik_clk_init(void)
{
struct clk *clk;
clk = clk_register_fixed_rate(NULL, "apb_pclk", NULL, CLK_IS_ROOT, 0);
clk_register_clkdev(clk, "apb_pclk", NULL);
clk_register_clkdev(clk, NULL, "gpio.0");
clk_register_clkdev(clk, NULL, "gpio.1");
clk_register_clkdev(clk, NULL, "gpio.2");
clk_register_clkdev(clk, NULL, "gpio.3");
clk_register_clkdev(clk, NULL, "rng");
clk_register_clkdev(clk, NULL, "fsmc-nand");
/*
* The 2.4 MHz TIMCLK reference clock is active at boot time, this is
* actually the MXTALCLK @19.2 MHz divided by 8. This clock is used
* by the timers and watchdog. See page 105 ff.
*/
clk = clk_register_fixed_rate(NULL, "TIMCLK", NULL, CLK_IS_ROOT,
2400000);
clk_register_clkdev(clk, NULL, "mtu0");
clk_register_clkdev(clk, NULL, "mtu1");
/*
* At boot time, PLL2 is set to generate a set of fixed clocks,
* one of them is CLK48, the 48 MHz clock, routed to the UART, MMC/SD
* I2C, IrDA, USB and SSP blocks.
*/
clk = clk_register_fixed_rate(NULL, "CLK48", NULL, CLK_IS_ROOT,
48000000);
clk_register_clkdev(clk, NULL, "uart0");
clk_register_clkdev(clk, NULL, "uart1");
clk_register_clkdev(clk, NULL, "mmci");
clk_register_clkdev(clk, NULL, "ssp");
clk_register_clkdev(clk, NULL, "nmk-i2c.0");
clk_register_clkdev(clk, NULL, "nmk-i2c.1");
}
| gpl-2.0 |
7420dev/android_kernel_samsung_zero | arch/sh/kernel/cpu/sh3/setup-sh7705.c | 2504 | 5944 | /*
* SH7705 Setup
*
* Copyright (C) 2006 - 2009 Paul Mundt
* Copyright (C) 2007 Nobuhiro Iwamatsu
*
* 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/platform_device.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/serial.h>
#include <linux/serial_sci.h>
#include <linux/sh_timer.h>
#include <linux/sh_intc.h>
#include <asm/rtc.h>
#include <cpu/serial.h>
enum {
UNUSED = 0,
/* interrupt sources */
IRQ0, IRQ1, IRQ2, IRQ3, IRQ4, IRQ5,
PINT07, PINT815,
DMAC, SCIF0, SCIF2, ADC_ADI, USB,
TPU0, TPU1, TPU2, TPU3,
TMU0, TMU1, TMU2,
RTC, WDT, REF_RCMI,
};
static struct intc_vect vectors[] __initdata = {
/* IRQ0->5 are handled in setup-sh3.c */
INTC_VECT(PINT07, 0x700), INTC_VECT(PINT815, 0x720),
INTC_VECT(DMAC, 0x800), INTC_VECT(DMAC, 0x820),
INTC_VECT(DMAC, 0x840), INTC_VECT(DMAC, 0x860),
INTC_VECT(SCIF0, 0x880), INTC_VECT(SCIF0, 0x8a0),
INTC_VECT(SCIF0, 0x8e0),
INTC_VECT(SCIF2, 0x900), INTC_VECT(SCIF2, 0x920),
INTC_VECT(SCIF2, 0x960),
INTC_VECT(ADC_ADI, 0x980),
INTC_VECT(USB, 0xa20), INTC_VECT(USB, 0xa40),
INTC_VECT(TPU0, 0xc00), INTC_VECT(TPU1, 0xc20),
INTC_VECT(TPU2, 0xc80), INTC_VECT(TPU3, 0xca0),
INTC_VECT(TMU0, 0x400), INTC_VECT(TMU1, 0x420),
INTC_VECT(TMU2, 0x440), INTC_VECT(TMU2, 0x460),
INTC_VECT(RTC, 0x480), INTC_VECT(RTC, 0x4a0),
INTC_VECT(RTC, 0x4c0),
INTC_VECT(WDT, 0x560),
INTC_VECT(REF_RCMI, 0x580),
};
static struct intc_prio_reg prio_registers[] __initdata = {
{ 0xfffffee2, 0, 16, 4, /* IPRA */ { TMU0, TMU1, TMU2, RTC } },
{ 0xfffffee4, 0, 16, 4, /* IPRB */ { WDT, REF_RCMI, 0, 0 } },
{ 0xa4000016, 0, 16, 4, /* IPRC */ { IRQ3, IRQ2, IRQ1, IRQ0 } },
{ 0xa4000018, 0, 16, 4, /* IPRD */ { PINT07, PINT815, IRQ5, IRQ4 } },
{ 0xa400001a, 0, 16, 4, /* IPRE */ { DMAC, SCIF0, SCIF2, ADC_ADI } },
{ 0xa4080000, 0, 16, 4, /* IPRF */ { 0, 0, USB } },
{ 0xa4080002, 0, 16, 4, /* IPRG */ { TPU0, TPU1 } },
{ 0xa4080004, 0, 16, 4, /* IPRH */ { TPU2, TPU3 } },
};
static DECLARE_INTC_DESC(intc_desc, "sh7705", vectors, NULL,
NULL, prio_registers, NULL);
static struct plat_sci_port scif0_platform_data = {
.mapbase = 0xa4410000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_TIE | SCSCR_RIE | SCSCR_TE |
SCSCR_RE | SCSCR_CKE1 | SCSCR_CKE0,
.scbrr_algo_id = SCBRR_ALGO_4,
.type = PORT_SCIF,
.irqs = SCIx_IRQ_MUXED(evt2irq(0x900)),
.ops = &sh770x_sci_port_ops,
.regtype = SCIx_SH7705_SCIF_REGTYPE,
};
static struct platform_device scif0_device = {
.name = "sh-sci",
.id = 0,
.dev = {
.platform_data = &scif0_platform_data,
},
};
static struct plat_sci_port scif1_platform_data = {
.mapbase = 0xa4400000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_TIE | SCSCR_RIE | SCSCR_TE | SCSCR_RE,
.scbrr_algo_id = SCBRR_ALGO_4,
.type = PORT_SCIF,
.irqs = SCIx_IRQ_MUXED(evt2irq(0x880)),
.ops = &sh770x_sci_port_ops,
.regtype = SCIx_SH7705_SCIF_REGTYPE,
};
static struct platform_device scif1_device = {
.name = "sh-sci",
.id = 1,
.dev = {
.platform_data = &scif1_platform_data,
},
};
static struct resource rtc_resources[] = {
[0] = {
.start = 0xfffffec0,
.end = 0xfffffec0 + 0x1e,
.flags = IORESOURCE_IO,
},
[1] = {
.start = evt2irq(0x480),
.flags = IORESOURCE_IRQ,
},
};
static struct sh_rtc_platform_info rtc_info = {
.capabilities = RTC_CAP_4_DIGIT_YEAR,
};
static struct platform_device rtc_device = {
.name = "sh-rtc",
.id = -1,
.num_resources = ARRAY_SIZE(rtc_resources),
.resource = rtc_resources,
.dev = {
.platform_data = &rtc_info,
},
};
static struct sh_timer_config tmu0_platform_data = {
.channel_offset = 0x02,
.timer_bit = 0,
.clockevent_rating = 200,
};
static struct resource tmu0_resources[] = {
[0] = {
.start = 0xfffffe94,
.end = 0xfffffe9f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x400),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu0_device = {
.name = "sh_tmu",
.id = 0,
.dev = {
.platform_data = &tmu0_platform_data,
},
.resource = tmu0_resources,
.num_resources = ARRAY_SIZE(tmu0_resources),
};
static struct sh_timer_config tmu1_platform_data = {
.channel_offset = 0xe,
.timer_bit = 1,
.clocksource_rating = 200,
};
static struct resource tmu1_resources[] = {
[0] = {
.start = 0xfffffea0,
.end = 0xfffffeab,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x420),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu1_device = {
.name = "sh_tmu",
.id = 1,
.dev = {
.platform_data = &tmu1_platform_data,
},
.resource = tmu1_resources,
.num_resources = ARRAY_SIZE(tmu1_resources),
};
static struct sh_timer_config tmu2_platform_data = {
.channel_offset = 0x1a,
.timer_bit = 2,
};
static struct resource tmu2_resources[] = {
[0] = {
.start = 0xfffffeac,
.end = 0xfffffebb,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x440),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu2_device = {
.name = "sh_tmu",
.id = 2,
.dev = {
.platform_data = &tmu2_platform_data,
},
.resource = tmu2_resources,
.num_resources = ARRAY_SIZE(tmu2_resources),
};
static struct platform_device *sh7705_devices[] __initdata = {
&scif0_device,
&scif1_device,
&tmu0_device,
&tmu1_device,
&tmu2_device,
&rtc_device,
};
static int __init sh7705_devices_setup(void)
{
return platform_add_devices(sh7705_devices,
ARRAY_SIZE(sh7705_devices));
}
arch_initcall(sh7705_devices_setup);
static struct platform_device *sh7705_early_devices[] __initdata = {
&scif0_device,
&scif1_device,
&tmu0_device,
&tmu1_device,
&tmu2_device,
};
void __init plat_early_device_setup(void)
{
early_platform_add_devices(sh7705_early_devices,
ARRAY_SIZE(sh7705_early_devices));
}
void __init plat_irq_setup(void)
{
register_intc_controller(&intc_desc);
plat_irq_setup_sh3();
}
| gpl-2.0 |
energycsdx/kernel-msm-taoshan | net/ipv4/inetpeer.c | 2760 | 17799 | /*
* INETPEER - A storage for permanent information about peers
*
* This source is covered by the GNU GPL, the same as all kernel sources.
*
* Authors: Andrey V. Savochkin <saw@msu.ru>
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/random.h>
#include <linux/timer.h>
#include <linux/time.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/net.h>
#include <linux/workqueue.h>
#include <net/ip.h>
#include <net/inetpeer.h>
#include <net/secure_seq.h>
/*
* Theory of operations.
* We keep one entry for each peer IP address. The nodes contains long-living
* information about the peer which doesn't depend on routes.
* At this moment this information consists only of ID field for the next
* outgoing IP packet. This field is incremented with each packet as encoded
* in inet_getid() function (include/net/inetpeer.h).
* At the moment of writing this notes identifier of IP packets is generated
* to be unpredictable using this code only for packets subjected
* (actually or potentially) to defragmentation. I.e. DF packets less than
* PMTU in size uses a constant ID and do not use this code (see
* ip_select_ident() in include/net/ip.h).
*
* Route cache entries hold references to our nodes.
* New cache entries get references via lookup by destination IP address in
* the avl tree. The reference is grabbed only when it's needed i.e. only
* when we try to output IP packet which needs an unpredictable ID (see
* __ip_select_ident() in net/ipv4/route.c).
* Nodes are removed only when reference counter goes to 0.
* When it's happened the node may be removed when a sufficient amount of
* time has been passed since its last use. The less-recently-used entry can
* also be removed if the pool is overloaded i.e. if the total amount of
* entries is greater-or-equal than the threshold.
*
* Node pool is organised as an AVL tree.
* Such an implementation has been chosen not just for fun. It's a way to
* prevent easy and efficient DoS attacks by creating hash collisions. A huge
* amount of long living nodes in a single hash slot would significantly delay
* lookups performed with disabled BHs.
*
* Serialisation issues.
* 1. Nodes may appear in the tree only with the pool lock held.
* 2. Nodes may disappear from the tree only with the pool lock held
* AND reference count being 0.
* 3. Global variable peer_total is modified under the pool lock.
* 4. struct inet_peer fields modification:
* avl_left, avl_right, avl_parent, avl_height: pool lock
* refcnt: atomically against modifications on other CPU;
* usually under some other lock to prevent node disappearing
* daddr: unchangeable
* ip_id_count: atomic value (no lock needed)
*/
static struct kmem_cache *peer_cachep __read_mostly;
static LIST_HEAD(gc_list);
static const int gc_delay = 60 * HZ;
static struct delayed_work gc_work;
static DEFINE_SPINLOCK(gc_lock);
#define node_height(x) x->avl_height
#define peer_avl_empty ((struct inet_peer *)&peer_fake_node)
#define peer_avl_empty_rcu ((struct inet_peer __rcu __force *)&peer_fake_node)
static const struct inet_peer peer_fake_node = {
.avl_left = peer_avl_empty_rcu,
.avl_right = peer_avl_empty_rcu,
.avl_height = 0
};
struct inet_peer_base {
struct inet_peer __rcu *root;
seqlock_t lock;
int total;
};
static struct inet_peer_base v4_peers = {
.root = peer_avl_empty_rcu,
.lock = __SEQLOCK_UNLOCKED(v4_peers.lock),
.total = 0,
};
static struct inet_peer_base v6_peers = {
.root = peer_avl_empty_rcu,
.lock = __SEQLOCK_UNLOCKED(v6_peers.lock),
.total = 0,
};
#define PEER_MAXDEPTH 40 /* sufficient for about 2^27 nodes */
/* Exported for sysctl_net_ipv4. */
int inet_peer_threshold __read_mostly = 65536 + 128; /* start to throw entries more
* aggressively at this stage */
int inet_peer_minttl __read_mostly = 120 * HZ; /* TTL under high load: 120 sec */
int inet_peer_maxttl __read_mostly = 10 * 60 * HZ; /* usual time to live: 10 min */
static void inetpeer_gc_worker(struct work_struct *work)
{
struct inet_peer *p, *n;
LIST_HEAD(list);
spin_lock_bh(&gc_lock);
list_replace_init(&gc_list, &list);
spin_unlock_bh(&gc_lock);
if (list_empty(&list))
return;
list_for_each_entry_safe(p, n, &list, gc_list) {
if(need_resched())
cond_resched();
if (p->avl_left != peer_avl_empty) {
list_add_tail(&p->avl_left->gc_list, &list);
p->avl_left = peer_avl_empty;
}
if (p->avl_right != peer_avl_empty) {
list_add_tail(&p->avl_right->gc_list, &list);
p->avl_right = peer_avl_empty;
}
n = list_entry(p->gc_list.next, struct inet_peer, gc_list);
if (!atomic_read(&p->refcnt)) {
list_del(&p->gc_list);
kmem_cache_free(peer_cachep, p);
}
}
if (list_empty(&list))
return;
spin_lock_bh(&gc_lock);
list_splice(&list, &gc_list);
spin_unlock_bh(&gc_lock);
schedule_delayed_work(&gc_work, gc_delay);
}
/* Called from ip_output.c:ip_init */
void __init inet_initpeers(void)
{
struct sysinfo si;
/* Use the straight interface to information about memory. */
si_meminfo(&si);
/* The values below were suggested by Alexey Kuznetsov
* <kuznet@ms2.inr.ac.ru>. I don't have any opinion about the values
* myself. --SAW
*/
if (si.totalram <= (32768*1024)/PAGE_SIZE)
inet_peer_threshold >>= 1; /* max pool size about 1MB on IA32 */
if (si.totalram <= (16384*1024)/PAGE_SIZE)
inet_peer_threshold >>= 1; /* about 512KB */
if (si.totalram <= (8192*1024)/PAGE_SIZE)
inet_peer_threshold >>= 2; /* about 128KB */
peer_cachep = kmem_cache_create("inet_peer_cache",
sizeof(struct inet_peer),
0, SLAB_HWCACHE_ALIGN | SLAB_PANIC,
NULL);
INIT_DELAYED_WORK_DEFERRABLE(&gc_work, inetpeer_gc_worker);
}
static int addr_compare(const struct inetpeer_addr *a,
const struct inetpeer_addr *b)
{
int i, n = (a->family == AF_INET ? 1 : 4);
for (i = 0; i < n; i++) {
if (a->addr.a6[i] == b->addr.a6[i])
continue;
if ((__force u32)a->addr.a6[i] < (__force u32)b->addr.a6[i])
return -1;
return 1;
}
return 0;
}
#define rcu_deref_locked(X, BASE) \
rcu_dereference_protected(X, lockdep_is_held(&(BASE)->lock.lock))
/*
* Called with local BH disabled and the pool lock held.
*/
#define lookup(_daddr, _stack, _base) \
({ \
struct inet_peer *u; \
struct inet_peer __rcu **v; \
\
stackptr = _stack; \
*stackptr++ = &_base->root; \
for (u = rcu_deref_locked(_base->root, _base); \
u != peer_avl_empty; ) { \
int cmp = addr_compare(_daddr, &u->daddr); \
if (cmp == 0) \
break; \
if (cmp == -1) \
v = &u->avl_left; \
else \
v = &u->avl_right; \
*stackptr++ = v; \
u = rcu_deref_locked(*v, _base); \
} \
u; \
})
/*
* Called with rcu_read_lock()
* Because we hold no lock against a writer, its quite possible we fall
* in an endless loop.
* But every pointer we follow is guaranteed to be valid thanks to RCU.
* We exit from this function if number of links exceeds PEER_MAXDEPTH
*/
static struct inet_peer *lookup_rcu(const struct inetpeer_addr *daddr,
struct inet_peer_base *base)
{
struct inet_peer *u = rcu_dereference(base->root);
int count = 0;
while (u != peer_avl_empty) {
int cmp = addr_compare(daddr, &u->daddr);
if (cmp == 0) {
/* Before taking a reference, check if this entry was
* deleted (refcnt=-1)
*/
if (!atomic_add_unless(&u->refcnt, 1, -1))
u = NULL;
return u;
}
if (cmp == -1)
u = rcu_dereference(u->avl_left);
else
u = rcu_dereference(u->avl_right);
if (unlikely(++count == PEER_MAXDEPTH))
break;
}
return NULL;
}
/* Called with local BH disabled and the pool lock held. */
#define lookup_rightempty(start, base) \
({ \
struct inet_peer *u; \
struct inet_peer __rcu **v; \
*stackptr++ = &start->avl_left; \
v = &start->avl_left; \
for (u = rcu_deref_locked(*v, base); \
u->avl_right != peer_avl_empty_rcu; ) { \
v = &u->avl_right; \
*stackptr++ = v; \
u = rcu_deref_locked(*v, base); \
} \
u; \
})
/* Called with local BH disabled and the pool lock held.
* Variable names are the proof of operation correctness.
* Look into mm/map_avl.c for more detail description of the ideas.
*/
static void peer_avl_rebalance(struct inet_peer __rcu **stack[],
struct inet_peer __rcu ***stackend,
struct inet_peer_base *base)
{
struct inet_peer __rcu **nodep;
struct inet_peer *node, *l, *r;
int lh, rh;
while (stackend > stack) {
nodep = *--stackend;
node = rcu_deref_locked(*nodep, base);
l = rcu_deref_locked(node->avl_left, base);
r = rcu_deref_locked(node->avl_right, base);
lh = node_height(l);
rh = node_height(r);
if (lh > rh + 1) { /* l: RH+2 */
struct inet_peer *ll, *lr, *lrl, *lrr;
int lrh;
ll = rcu_deref_locked(l->avl_left, base);
lr = rcu_deref_locked(l->avl_right, base);
lrh = node_height(lr);
if (lrh <= node_height(ll)) { /* ll: RH+1 */
RCU_INIT_POINTER(node->avl_left, lr); /* lr: RH or RH+1 */
RCU_INIT_POINTER(node->avl_right, r); /* r: RH */
node->avl_height = lrh + 1; /* RH+1 or RH+2 */
RCU_INIT_POINTER(l->avl_left, ll); /* ll: RH+1 */
RCU_INIT_POINTER(l->avl_right, node); /* node: RH+1 or RH+2 */
l->avl_height = node->avl_height + 1;
RCU_INIT_POINTER(*nodep, l);
} else { /* ll: RH, lr: RH+1 */
lrl = rcu_deref_locked(lr->avl_left, base);/* lrl: RH or RH-1 */
lrr = rcu_deref_locked(lr->avl_right, base);/* lrr: RH or RH-1 */
RCU_INIT_POINTER(node->avl_left, lrr); /* lrr: RH or RH-1 */
RCU_INIT_POINTER(node->avl_right, r); /* r: RH */
node->avl_height = rh + 1; /* node: RH+1 */
RCU_INIT_POINTER(l->avl_left, ll); /* ll: RH */
RCU_INIT_POINTER(l->avl_right, lrl); /* lrl: RH or RH-1 */
l->avl_height = rh + 1; /* l: RH+1 */
RCU_INIT_POINTER(lr->avl_left, l); /* l: RH+1 */
RCU_INIT_POINTER(lr->avl_right, node); /* node: RH+1 */
lr->avl_height = rh + 2;
RCU_INIT_POINTER(*nodep, lr);
}
} else if (rh > lh + 1) { /* r: LH+2 */
struct inet_peer *rr, *rl, *rlr, *rll;
int rlh;
rr = rcu_deref_locked(r->avl_right, base);
rl = rcu_deref_locked(r->avl_left, base);
rlh = node_height(rl);
if (rlh <= node_height(rr)) { /* rr: LH+1 */
RCU_INIT_POINTER(node->avl_right, rl); /* rl: LH or LH+1 */
RCU_INIT_POINTER(node->avl_left, l); /* l: LH */
node->avl_height = rlh + 1; /* LH+1 or LH+2 */
RCU_INIT_POINTER(r->avl_right, rr); /* rr: LH+1 */
RCU_INIT_POINTER(r->avl_left, node); /* node: LH+1 or LH+2 */
r->avl_height = node->avl_height + 1;
RCU_INIT_POINTER(*nodep, r);
} else { /* rr: RH, rl: RH+1 */
rlr = rcu_deref_locked(rl->avl_right, base);/* rlr: LH or LH-1 */
rll = rcu_deref_locked(rl->avl_left, base);/* rll: LH or LH-1 */
RCU_INIT_POINTER(node->avl_right, rll); /* rll: LH or LH-1 */
RCU_INIT_POINTER(node->avl_left, l); /* l: LH */
node->avl_height = lh + 1; /* node: LH+1 */
RCU_INIT_POINTER(r->avl_right, rr); /* rr: LH */
RCU_INIT_POINTER(r->avl_left, rlr); /* rlr: LH or LH-1 */
r->avl_height = lh + 1; /* r: LH+1 */
RCU_INIT_POINTER(rl->avl_right, r); /* r: LH+1 */
RCU_INIT_POINTER(rl->avl_left, node); /* node: LH+1 */
rl->avl_height = lh + 2;
RCU_INIT_POINTER(*nodep, rl);
}
} else {
node->avl_height = (lh > rh ? lh : rh) + 1;
}
}
}
/* Called with local BH disabled and the pool lock held. */
#define link_to_pool(n, base) \
do { \
n->avl_height = 1; \
n->avl_left = peer_avl_empty_rcu; \
n->avl_right = peer_avl_empty_rcu; \
/* lockless readers can catch us now */ \
rcu_assign_pointer(**--stackptr, n); \
peer_avl_rebalance(stack, stackptr, base); \
} while (0)
static void inetpeer_free_rcu(struct rcu_head *head)
{
kmem_cache_free(peer_cachep, container_of(head, struct inet_peer, rcu));
}
static void unlink_from_pool(struct inet_peer *p, struct inet_peer_base *base,
struct inet_peer __rcu **stack[PEER_MAXDEPTH])
{
struct inet_peer __rcu ***stackptr, ***delp;
if (lookup(&p->daddr, stack, base) != p)
BUG();
delp = stackptr - 1; /* *delp[0] == p */
if (p->avl_left == peer_avl_empty_rcu) {
*delp[0] = p->avl_right;
--stackptr;
} else {
/* look for a node to insert instead of p */
struct inet_peer *t;
t = lookup_rightempty(p, base);
BUG_ON(rcu_deref_locked(*stackptr[-1], base) != t);
**--stackptr = t->avl_left;
/* t is removed, t->daddr > x->daddr for any
* x in p->avl_left subtree.
* Put t in the old place of p. */
RCU_INIT_POINTER(*delp[0], t);
t->avl_left = p->avl_left;
t->avl_right = p->avl_right;
t->avl_height = p->avl_height;
BUG_ON(delp[1] != &p->avl_left);
delp[1] = &t->avl_left; /* was &p->avl_left */
}
peer_avl_rebalance(stack, stackptr, base);
base->total--;
call_rcu(&p->rcu, inetpeer_free_rcu);
}
static struct inet_peer_base *family_to_base(int family)
{
return family == AF_INET ? &v4_peers : &v6_peers;
}
/* perform garbage collect on all items stacked during a lookup */
static int inet_peer_gc(struct inet_peer_base *base,
struct inet_peer __rcu **stack[PEER_MAXDEPTH],
struct inet_peer __rcu ***stackptr)
{
struct inet_peer *p, *gchead = NULL;
__u32 delta, ttl;
int cnt = 0;
if (base->total >= inet_peer_threshold)
ttl = 0; /* be aggressive */
else
ttl = inet_peer_maxttl
- (inet_peer_maxttl - inet_peer_minttl) / HZ *
base->total / inet_peer_threshold * HZ;
stackptr--; /* last stack slot is peer_avl_empty */
while (stackptr > stack) {
stackptr--;
p = rcu_deref_locked(**stackptr, base);
if (atomic_read(&p->refcnt) == 0) {
smp_rmb();
delta = (__u32)jiffies - p->dtime;
if (delta >= ttl &&
atomic_cmpxchg(&p->refcnt, 0, -1) == 0) {
p->gc_next = gchead;
gchead = p;
}
}
}
while ((p = gchead) != NULL) {
gchead = p->gc_next;
cnt++;
unlink_from_pool(p, base, stack);
}
return cnt;
}
struct inet_peer *inet_getpeer(const struct inetpeer_addr *daddr, int create)
{
struct inet_peer __rcu **stack[PEER_MAXDEPTH], ***stackptr;
struct inet_peer_base *base = family_to_base(daddr->family);
struct inet_peer *p;
unsigned int sequence;
int invalidated, gccnt = 0;
/* Attempt a lockless lookup first.
* Because of a concurrent writer, we might not find an existing entry.
*/
rcu_read_lock();
sequence = read_seqbegin(&base->lock);
p = lookup_rcu(daddr, base);
invalidated = read_seqretry(&base->lock, sequence);
rcu_read_unlock();
if (p)
return p;
/* If no writer did a change during our lookup, we can return early. */
if (!create && !invalidated)
return NULL;
/* retry an exact lookup, taking the lock before.
* At least, nodes should be hot in our cache.
*/
write_seqlock_bh(&base->lock);
relookup:
p = lookup(daddr, stack, base);
if (p != peer_avl_empty) {
atomic_inc(&p->refcnt);
write_sequnlock_bh(&base->lock);
return p;
}
if (!gccnt) {
gccnt = inet_peer_gc(base, stack, stackptr);
if (gccnt && create)
goto relookup;
}
p = create ? kmem_cache_alloc(peer_cachep, GFP_ATOMIC) : NULL;
if (p) {
p->daddr = *daddr;
atomic_set(&p->refcnt, 1);
atomic_set(&p->rid, 0);
atomic_set(&p->ip_id_count,
(daddr->family == AF_INET) ?
secure_ip_id(daddr->addr.a4) :
secure_ipv6_id(daddr->addr.a6));
p->tcp_ts_stamp = 0;
p->metrics[RTAX_LOCK-1] = INETPEER_METRICS_NEW;
p->rate_tokens = 0;
p->rate_last = 0;
p->pmtu_expires = 0;
p->pmtu_orig = 0;
memset(&p->redirect_learned, 0, sizeof(p->redirect_learned));
INIT_LIST_HEAD(&p->gc_list);
/* Link the node. */
link_to_pool(p, base);
base->total++;
}
write_sequnlock_bh(&base->lock);
return p;
}
EXPORT_SYMBOL_GPL(inet_getpeer);
void inet_putpeer(struct inet_peer *p)
{
p->dtime = (__u32)jiffies;
smp_mb__before_atomic_dec();
atomic_dec(&p->refcnt);
}
EXPORT_SYMBOL_GPL(inet_putpeer);
/*
* Check transmit rate limitation for given message.
* The rate information is held in the inet_peer entries now.
* This function is generic and could be used for other purposes
* too. It uses a Token bucket filter as suggested by Alexey Kuznetsov.
*
* Note that the same inet_peer fields are modified by functions in
* route.c too, but these work for packet destinations while xrlim_allow
* works for icmp destinations. This means the rate limiting information
* for one "ip object" is shared - and these ICMPs are twice limited:
* by source and by destination.
*
* RFC 1812: 4.3.2.8 SHOULD be able to limit error message rate
* SHOULD allow setting of rate limits
*
* Shared between ICMPv4 and ICMPv6.
*/
#define XRLIM_BURST_FACTOR 6
bool inet_peer_xrlim_allow(struct inet_peer *peer, int timeout)
{
unsigned long now, token;
bool rc = false;
if (!peer)
return true;
token = peer->rate_tokens;
now = jiffies;
token += now - peer->rate_last;
peer->rate_last = now;
if (token > XRLIM_BURST_FACTOR * timeout)
token = XRLIM_BURST_FACTOR * timeout;
if (token >= timeout) {
token -= timeout;
rc = true;
}
peer->rate_tokens = token;
return rc;
}
EXPORT_SYMBOL(inet_peer_xrlim_allow);
void inetpeer_invalidate_tree(int family)
{
struct inet_peer *old, *new, *prev;
struct inet_peer_base *base = family_to_base(family);
write_seqlock_bh(&base->lock);
old = base->root;
if (old == peer_avl_empty_rcu)
goto out;
new = peer_avl_empty_rcu;
prev = cmpxchg(&base->root, old, new);
if (prev == old) {
base->total = 0;
spin_lock(&gc_lock);
list_add_tail(&prev->gc_list, &gc_list);
spin_unlock(&gc_lock);
schedule_delayed_work(&gc_work, gc_delay);
}
out:
write_sequnlock_bh(&base->lock);
}
EXPORT_SYMBOL(inetpeer_invalidate_tree);
| gpl-2.0 |
dsb9938/DNA_JB_KERNEL | net/phonet/socket.c | 3528 | 18370 | /*
* File: socket.c
*
* Phonet sockets
*
* Copyright (C) 2008 Nokia Corporation.
*
* Contact: Remi Denis-Courmont <remi.denis-courmont@nokia.com>
* Original author: Sakari Ailus <sakari.ailus@nokia.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <linux/gfp.h>
#include <linux/kernel.h>
#include <linux/net.h>
#include <linux/poll.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <linux/phonet.h>
#include <linux/export.h>
#include <net/phonet/phonet.h>
#include <net/phonet/pep.h>
#include <net/phonet/pn_dev.h>
static int pn_socket_release(struct socket *sock)
{
struct sock *sk = sock->sk;
if (sk) {
sock->sk = NULL;
sk->sk_prot->close(sk, 0);
}
return 0;
}
#define PN_HASHSIZE 16
#define PN_HASHMASK (PN_HASHSIZE-1)
static struct {
struct hlist_head hlist[PN_HASHSIZE];
struct mutex lock;
} pnsocks;
void __init pn_sock_init(void)
{
unsigned i;
for (i = 0; i < PN_HASHSIZE; i++)
INIT_HLIST_HEAD(pnsocks.hlist + i);
mutex_init(&pnsocks.lock);
}
static struct hlist_head *pn_hash_list(u16 obj)
{
return pnsocks.hlist + (obj & PN_HASHMASK);
}
/*
* Find address based on socket address, match only certain fields.
* Also grab sock if it was found. Remember to sock_put it later.
*/
struct sock *pn_find_sock_by_sa(struct net *net, const struct sockaddr_pn *spn)
{
struct hlist_node *node;
struct sock *sknode;
struct sock *rval = NULL;
u16 obj = pn_sockaddr_get_object(spn);
u8 res = spn->spn_resource;
struct hlist_head *hlist = pn_hash_list(obj);
rcu_read_lock();
sk_for_each_rcu(sknode, node, hlist) {
struct pn_sock *pn = pn_sk(sknode);
BUG_ON(!pn->sobject); /* unbound socket */
if (!net_eq(sock_net(sknode), net))
continue;
if (pn_port(obj)) {
/* Look up socket by port */
if (pn_port(pn->sobject) != pn_port(obj))
continue;
} else {
/* If port is zero, look up by resource */
if (pn->resource != res)
continue;
}
if (pn_addr(pn->sobject) &&
pn_addr(pn->sobject) != pn_addr(obj))
continue;
rval = sknode;
sock_hold(sknode);
break;
}
rcu_read_unlock();
return rval;
}
/* Deliver a broadcast packet (only in bottom-half) */
void pn_deliver_sock_broadcast(struct net *net, struct sk_buff *skb)
{
struct hlist_head *hlist = pnsocks.hlist;
unsigned h;
rcu_read_lock();
for (h = 0; h < PN_HASHSIZE; h++) {
struct hlist_node *node;
struct sock *sknode;
sk_for_each(sknode, node, hlist) {
struct sk_buff *clone;
if (!net_eq(sock_net(sknode), net))
continue;
if (!sock_flag(sknode, SOCK_BROADCAST))
continue;
clone = skb_clone(skb, GFP_ATOMIC);
if (clone) {
sock_hold(sknode);
sk_receive_skb(sknode, clone, 0);
}
}
hlist++;
}
rcu_read_unlock();
}
void pn_sock_hash(struct sock *sk)
{
struct hlist_head *hlist = pn_hash_list(pn_sk(sk)->sobject);
mutex_lock(&pnsocks.lock);
sk_add_node_rcu(sk, hlist);
mutex_unlock(&pnsocks.lock);
}
EXPORT_SYMBOL(pn_sock_hash);
void pn_sock_unhash(struct sock *sk)
{
mutex_lock(&pnsocks.lock);
sk_del_node_init_rcu(sk);
mutex_unlock(&pnsocks.lock);
pn_sock_unbind_all_res(sk);
synchronize_rcu();
}
EXPORT_SYMBOL(pn_sock_unhash);
static DEFINE_MUTEX(port_mutex);
static int pn_socket_bind(struct socket *sock, struct sockaddr *addr, int len)
{
struct sock *sk = sock->sk;
struct pn_sock *pn = pn_sk(sk);
struct sockaddr_pn *spn = (struct sockaddr_pn *)addr;
int err;
u16 handle;
u8 saddr;
if (sk->sk_prot->bind)
return sk->sk_prot->bind(sk, addr, len);
if (len < sizeof(struct sockaddr_pn))
return -EINVAL;
if (spn->spn_family != AF_PHONET)
return -EAFNOSUPPORT;
handle = pn_sockaddr_get_object((struct sockaddr_pn *)addr);
saddr = pn_addr(handle);
if (saddr && phonet_address_lookup(sock_net(sk), saddr))
return -EADDRNOTAVAIL;
lock_sock(sk);
if (sk->sk_state != TCP_CLOSE || pn_port(pn->sobject)) {
err = -EINVAL; /* attempt to rebind */
goto out;
}
WARN_ON(sk_hashed(sk));
mutex_lock(&port_mutex);
err = sk->sk_prot->get_port(sk, pn_port(handle));
if (err)
goto out_port;
/* get_port() sets the port, bind() sets the address if applicable */
pn->sobject = pn_object(saddr, pn_port(pn->sobject));
pn->resource = spn->spn_resource;
/* Enable RX on the socket */
sk->sk_prot->hash(sk);
out_port:
mutex_unlock(&port_mutex);
out:
release_sock(sk);
return err;
}
static int pn_socket_autobind(struct socket *sock)
{
struct sockaddr_pn sa;
int err;
memset(&sa, 0, sizeof(sa));
sa.spn_family = AF_PHONET;
err = pn_socket_bind(sock, (struct sockaddr *)&sa,
sizeof(struct sockaddr_pn));
if (err != -EINVAL)
return err;
BUG_ON(!pn_port(pn_sk(sock->sk)->sobject));
return 0; /* socket was already bound */
}
static int pn_socket_connect(struct socket *sock, struct sockaddr *addr,
int len, int flags)
{
struct sock *sk = sock->sk;
struct pn_sock *pn = pn_sk(sk);
struct sockaddr_pn *spn = (struct sockaddr_pn *)addr;
struct task_struct *tsk = current;
long timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
int err;
if (pn_socket_autobind(sock))
return -ENOBUFS;
if (len < sizeof(struct sockaddr_pn))
return -EINVAL;
if (spn->spn_family != AF_PHONET)
return -EAFNOSUPPORT;
lock_sock(sk);
switch (sock->state) {
case SS_UNCONNECTED:
if (sk->sk_state != TCP_CLOSE) {
err = -EISCONN;
goto out;
}
break;
case SS_CONNECTING:
err = -EALREADY;
goto out;
default:
err = -EISCONN;
goto out;
}
pn->dobject = pn_sockaddr_get_object(spn);
pn->resource = pn_sockaddr_get_resource(spn);
sock->state = SS_CONNECTING;
err = sk->sk_prot->connect(sk, addr, len);
if (err) {
sock->state = SS_UNCONNECTED;
pn->dobject = 0;
goto out;
}
while (sk->sk_state == TCP_SYN_SENT) {
DEFINE_WAIT(wait);
if (!timeo) {
err = -EINPROGRESS;
goto out;
}
if (signal_pending(tsk)) {
err = sock_intr_errno(timeo);
goto out;
}
prepare_to_wait_exclusive(sk_sleep(sk), &wait,
TASK_INTERRUPTIBLE);
release_sock(sk);
timeo = schedule_timeout(timeo);
lock_sock(sk);
finish_wait(sk_sleep(sk), &wait);
}
if ((1 << sk->sk_state) & (TCPF_SYN_RECV|TCPF_ESTABLISHED))
err = 0;
else if (sk->sk_state == TCP_CLOSE_WAIT)
err = -ECONNRESET;
else
err = -ECONNREFUSED;
sock->state = err ? SS_UNCONNECTED : SS_CONNECTED;
out:
release_sock(sk);
return err;
}
static int pn_socket_accept(struct socket *sock, struct socket *newsock,
int flags)
{
struct sock *sk = sock->sk;
struct sock *newsk;
int err;
if (unlikely(sk->sk_state != TCP_LISTEN))
return -EINVAL;
newsk = sk->sk_prot->accept(sk, flags, &err);
if (!newsk)
return err;
lock_sock(newsk);
sock_graft(newsk, newsock);
newsock->state = SS_CONNECTED;
release_sock(newsk);
return 0;
}
static int pn_socket_getname(struct socket *sock, struct sockaddr *addr,
int *sockaddr_len, int peer)
{
struct sock *sk = sock->sk;
struct pn_sock *pn = pn_sk(sk);
memset(addr, 0, sizeof(struct sockaddr_pn));
addr->sa_family = AF_PHONET;
if (!peer) /* Race with bind() here is userland's problem. */
pn_sockaddr_set_object((struct sockaddr_pn *)addr,
pn->sobject);
*sockaddr_len = sizeof(struct sockaddr_pn);
return 0;
}
static unsigned int pn_socket_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
struct pep_sock *pn = pep_sk(sk);
unsigned int mask = 0;
poll_wait(file, sk_sleep(sk), wait);
if (sk->sk_state == TCP_CLOSE)
return POLLERR;
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
if (!skb_queue_empty(&pn->ctrlreq_queue))
mask |= POLLPRI;
if (!mask && sk->sk_state == TCP_CLOSE_WAIT)
return POLLHUP;
if (sk->sk_state == TCP_ESTABLISHED &&
atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf &&
atomic_read(&pn->tx_credits))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
return mask;
}
static int pn_socket_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
struct sock *sk = sock->sk;
struct pn_sock *pn = pn_sk(sk);
if (cmd == SIOCPNGETOBJECT) {
struct net_device *dev;
u16 handle;
u8 saddr;
if (get_user(handle, (__u16 __user *)arg))
return -EFAULT;
lock_sock(sk);
if (sk->sk_bound_dev_if)
dev = dev_get_by_index(sock_net(sk),
sk->sk_bound_dev_if);
else
dev = phonet_device_get(sock_net(sk));
if (dev && (dev->flags & IFF_UP))
saddr = phonet_address_get(dev, pn_addr(handle));
else
saddr = PN_NO_ADDR;
release_sock(sk);
if (dev)
dev_put(dev);
if (saddr == PN_NO_ADDR)
return -EHOSTUNREACH;
handle = pn_object(saddr, pn_port(pn->sobject));
return put_user(handle, (__u16 __user *)arg);
}
return sk->sk_prot->ioctl(sk, cmd, arg);
}
static int pn_socket_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int err = 0;
if (pn_socket_autobind(sock))
return -ENOBUFS;
lock_sock(sk);
if (sock->state != SS_UNCONNECTED) {
err = -EINVAL;
goto out;
}
if (sk->sk_state != TCP_LISTEN) {
sk->sk_state = TCP_LISTEN;
sk->sk_ack_backlog = 0;
}
sk->sk_max_ack_backlog = backlog;
out:
release_sock(sk);
return err;
}
static int pn_socket_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t total_len)
{
struct sock *sk = sock->sk;
if (pn_socket_autobind(sock))
return -EAGAIN;
return sk->sk_prot->sendmsg(iocb, sk, m, total_len);
}
const struct proto_ops phonet_dgram_ops = {
.family = AF_PHONET,
.owner = THIS_MODULE,
.release = pn_socket_release,
.bind = pn_socket_bind,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = pn_socket_getname,
.poll = datagram_poll,
.ioctl = pn_socket_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
#ifdef CONFIG_COMPAT
.compat_setsockopt = sock_no_setsockopt,
.compat_getsockopt = sock_no_getsockopt,
#endif
.sendmsg = pn_socket_sendmsg,
.recvmsg = sock_common_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
const struct proto_ops phonet_stream_ops = {
.family = AF_PHONET,
.owner = THIS_MODULE,
.release = pn_socket_release,
.bind = pn_socket_bind,
.connect = pn_socket_connect,
.socketpair = sock_no_socketpair,
.accept = pn_socket_accept,
.getname = pn_socket_getname,
.poll = pn_socket_poll,
.ioctl = pn_socket_ioctl,
.listen = pn_socket_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_common_setsockopt,
.getsockopt = sock_common_getsockopt,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_sock_common_setsockopt,
.compat_getsockopt = compat_sock_common_getsockopt,
#endif
.sendmsg = pn_socket_sendmsg,
.recvmsg = sock_common_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
EXPORT_SYMBOL(phonet_stream_ops);
/* allocate port for a socket */
int pn_sock_get_port(struct sock *sk, unsigned short sport)
{
static int port_cur;
struct net *net = sock_net(sk);
struct pn_sock *pn = pn_sk(sk);
struct sockaddr_pn try_sa;
struct sock *tmpsk;
memset(&try_sa, 0, sizeof(struct sockaddr_pn));
try_sa.spn_family = AF_PHONET;
WARN_ON(!mutex_is_locked(&port_mutex));
if (!sport) {
/* search free port */
int port, pmin, pmax;
phonet_get_local_port_range(&pmin, &pmax);
for (port = pmin; port <= pmax; port++) {
port_cur++;
if (port_cur < pmin || port_cur > pmax)
port_cur = pmin;
pn_sockaddr_set_port(&try_sa, port_cur);
tmpsk = pn_find_sock_by_sa(net, &try_sa);
if (tmpsk == NULL) {
sport = port_cur;
goto found;
} else
sock_put(tmpsk);
}
} else {
/* try to find specific port */
pn_sockaddr_set_port(&try_sa, sport);
tmpsk = pn_find_sock_by_sa(net, &try_sa);
if (tmpsk == NULL)
/* No sock there! We can use that port... */
goto found;
else
sock_put(tmpsk);
}
/* the port must be in use already */
return -EADDRINUSE;
found:
pn->sobject = pn_object(pn_addr(pn->sobject), sport);
return 0;
}
EXPORT_SYMBOL(pn_sock_get_port);
#ifdef CONFIG_PROC_FS
static struct sock *pn_sock_get_idx(struct seq_file *seq, loff_t pos)
{
struct net *net = seq_file_net(seq);
struct hlist_head *hlist = pnsocks.hlist;
struct hlist_node *node;
struct sock *sknode;
unsigned h;
for (h = 0; h < PN_HASHSIZE; h++) {
sk_for_each_rcu(sknode, node, hlist) {
if (!net_eq(net, sock_net(sknode)))
continue;
if (!pos)
return sknode;
pos--;
}
hlist++;
}
return NULL;
}
static struct sock *pn_sock_get_next(struct seq_file *seq, struct sock *sk)
{
struct net *net = seq_file_net(seq);
do
sk = sk_next(sk);
while (sk && !net_eq(net, sock_net(sk)));
return sk;
}
static void *pn_sock_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(rcu)
{
rcu_read_lock();
return *pos ? pn_sock_get_idx(seq, *pos - 1) : SEQ_START_TOKEN;
}
static void *pn_sock_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct sock *sk;
if (v == SEQ_START_TOKEN)
sk = pn_sock_get_idx(seq, 0);
else
sk = pn_sock_get_next(seq, v);
(*pos)++;
return sk;
}
static void pn_sock_seq_stop(struct seq_file *seq, void *v)
__releases(rcu)
{
rcu_read_unlock();
}
static int pn_sock_seq_show(struct seq_file *seq, void *v)
{
int len;
if (v == SEQ_START_TOKEN)
seq_printf(seq, "%s%n", "pt loc rem rs st tx_queue rx_queue "
" uid inode ref pointer drops", &len);
else {
struct sock *sk = v;
struct pn_sock *pn = pn_sk(sk);
seq_printf(seq, "%2d %04X:%04X:%02X %02X %08X:%08X %5d %lu "
"%d %pK %d%n",
sk->sk_protocol, pn->sobject, pn->dobject,
pn->resource, sk->sk_state,
sk_wmem_alloc_get(sk), sk_rmem_alloc_get(sk),
sock_i_uid(sk), sock_i_ino(sk),
atomic_read(&sk->sk_refcnt), sk,
atomic_read(&sk->sk_drops), &len);
}
seq_printf(seq, "%*s\n", 127 - len, "");
return 0;
}
static const struct seq_operations pn_sock_seq_ops = {
.start = pn_sock_seq_start,
.next = pn_sock_seq_next,
.stop = pn_sock_seq_stop,
.show = pn_sock_seq_show,
};
static int pn_sock_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &pn_sock_seq_ops,
sizeof(struct seq_net_private));
}
const struct file_operations pn_sock_seq_fops = {
.owner = THIS_MODULE,
.open = pn_sock_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
static struct {
struct sock *sk[256];
} pnres;
/*
* Find and hold socket based on resource.
*/
struct sock *pn_find_sock_by_res(struct net *net, u8 res)
{
struct sock *sk;
if (!net_eq(net, &init_net))
return NULL;
rcu_read_lock();
sk = rcu_dereference(pnres.sk[res]);
if (sk)
sock_hold(sk);
rcu_read_unlock();
return sk;
}
static DEFINE_MUTEX(resource_mutex);
int pn_sock_bind_res(struct sock *sk, u8 res)
{
int ret = -EADDRINUSE;
if (!net_eq(sock_net(sk), &init_net))
return -ENOIOCTLCMD;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (pn_socket_autobind(sk->sk_socket))
return -EAGAIN;
mutex_lock(&resource_mutex);
if (pnres.sk[res] == NULL) {
sock_hold(sk);
rcu_assign_pointer(pnres.sk[res], sk);
ret = 0;
}
mutex_unlock(&resource_mutex);
return ret;
}
int pn_sock_unbind_res(struct sock *sk, u8 res)
{
int ret = -ENOENT;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
mutex_lock(&resource_mutex);
if (pnres.sk[res] == sk) {
RCU_INIT_POINTER(pnres.sk[res], NULL);
ret = 0;
}
mutex_unlock(&resource_mutex);
if (ret == 0) {
synchronize_rcu();
sock_put(sk);
}
return ret;
}
void pn_sock_unbind_all_res(struct sock *sk)
{
unsigned res, match = 0;
mutex_lock(&resource_mutex);
for (res = 0; res < 256; res++) {
if (pnres.sk[res] == sk) {
RCU_INIT_POINTER(pnres.sk[res], NULL);
match++;
}
}
mutex_unlock(&resource_mutex);
while (match > 0) {
__sock_put(sk);
match--;
}
/* Caller is responsible for RCU sync before final sock_put() */
}
#ifdef CONFIG_PROC_FS
static struct sock **pn_res_get_idx(struct seq_file *seq, loff_t pos)
{
struct net *net = seq_file_net(seq);
unsigned i;
if (!net_eq(net, &init_net))
return NULL;
for (i = 0; i < 256; i++) {
if (pnres.sk[i] == NULL)
continue;
if (!pos)
return pnres.sk + i;
pos--;
}
return NULL;
}
static struct sock **pn_res_get_next(struct seq_file *seq, struct sock **sk)
{
struct net *net = seq_file_net(seq);
unsigned i;
BUG_ON(!net_eq(net, &init_net));
for (i = (sk - pnres.sk) + 1; i < 256; i++)
if (pnres.sk[i])
return pnres.sk + i;
return NULL;
}
static void *pn_res_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(resource_mutex)
{
mutex_lock(&resource_mutex);
return *pos ? pn_res_get_idx(seq, *pos - 1) : SEQ_START_TOKEN;
}
static void *pn_res_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct sock **sk;
if (v == SEQ_START_TOKEN)
sk = pn_res_get_idx(seq, 0);
else
sk = pn_res_get_next(seq, v);
(*pos)++;
return sk;
}
static void pn_res_seq_stop(struct seq_file *seq, void *v)
__releases(resource_mutex)
{
mutex_unlock(&resource_mutex);
}
static int pn_res_seq_show(struct seq_file *seq, void *v)
{
int len;
if (v == SEQ_START_TOKEN)
seq_printf(seq, "%s%n", "rs uid inode", &len);
else {
struct sock **psk = v;
struct sock *sk = *psk;
seq_printf(seq, "%02X %5d %lu%n",
(int) (psk - pnres.sk), sock_i_uid(sk),
sock_i_ino(sk), &len);
}
seq_printf(seq, "%*s\n", 63 - len, "");
return 0;
}
static const struct seq_operations pn_res_seq_ops = {
.start = pn_res_seq_start,
.next = pn_res_seq_next,
.stop = pn_res_seq_stop,
.show = pn_res_seq_show,
};
static int pn_res_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &pn_res_seq_ops,
sizeof(struct seq_net_private));
}
const struct file_operations pn_res_seq_fops = {
.owner = THIS_MODULE,
.open = pn_res_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
| gpl-2.0 |
jdkoreclipse/incrediblec_2.6.38 | arch/ia64/sn/kernel/io_acpi_init.c | 3784 | 15177 | /*
* 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) 2006 Silicon Graphics, Inc. All rights reserved.
*/
#include <asm/sn/types.h>
#include <asm/sn/addrs.h>
#include <asm/sn/pcidev.h>
#include <asm/sn/pcibus_provider_defs.h>
#include <asm/sn/sn_sal.h>
#include "xtalk/hubdev.h"
#include <linux/acpi.h>
#include <linux/slab.h>
/*
* The code in this file will only be executed when running with
* a PROM that has ACPI IO support. (i.e., SN_ACPI_BASE_SUPPORT() == 1)
*/
/*
* This value must match the UUID the PROM uses
* (io/acpi/defblk.c) when building a vendor descriptor.
*/
struct acpi_vendor_uuid sn_uuid = {
.subtype = 0,
.data = { 0x2c, 0xc6, 0xa6, 0xfe, 0x9c, 0x44, 0xda, 0x11,
0xa2, 0x7c, 0x08, 0x00, 0x69, 0x13, 0xea, 0x51 },
};
struct sn_pcidev_match {
u8 bus;
unsigned int devfn;
acpi_handle handle;
};
/*
* Perform the early IO init in PROM.
*/
static long
sal_ioif_init(u64 *result)
{
struct ia64_sal_retval isrv = {0,0,0,0};
SAL_CALL_NOLOCK(isrv,
SN_SAL_IOIF_INIT, 0, 0, 0, 0, 0, 0, 0);
*result = isrv.v0;
return isrv.status;
}
/*
* sn_acpi_hubdev_init() - This function is called by acpi_ns_get_device_callback()
* for all SGIHUB and SGITIO acpi devices defined in the
* DSDT. It obtains the hubdev_info pointer from the
* ACPI vendor resource, which the PROM setup, and sets up the
* hubdev_info in the pda.
*/
static acpi_status __init
sn_acpi_hubdev_init(acpi_handle handle, u32 depth, void *context, void **ret)
{
struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
struct acpi_buffer name_buffer = { ACPI_ALLOCATE_BUFFER, NULL };
u64 addr;
struct hubdev_info *hubdev;
struct hubdev_info *hubdev_ptr;
int i;
u64 nasid;
struct acpi_resource *resource;
acpi_status status;
struct acpi_resource_vendor_typed *vendor;
extern void sn_common_hubdev_init(struct hubdev_info *);
status = acpi_get_vendor_resource(handle, METHOD_NAME__CRS,
&sn_uuid, &buffer);
if (ACPI_FAILURE(status)) {
acpi_get_name(handle, ACPI_FULL_PATHNAME, &name_buffer);
printk(KERN_ERR
"sn_acpi_hubdev_init: acpi_get_vendor_resource() "
"(0x%x) failed for: %s\n", status,
(char *)name_buffer.pointer);
kfree(name_buffer.pointer);
return AE_OK; /* Continue walking namespace */
}
resource = buffer.pointer;
vendor = &resource->data.vendor_typed;
if ((vendor->byte_length - sizeof(struct acpi_vendor_uuid)) !=
sizeof(struct hubdev_info *)) {
acpi_get_name(handle, ACPI_FULL_PATHNAME, &name_buffer);
printk(KERN_ERR
"sn_acpi_hubdev_init: Invalid vendor data length: "
"%d for: %s\n",
vendor->byte_length, (char *)name_buffer.pointer);
kfree(name_buffer.pointer);
goto exit;
}
memcpy(&addr, vendor->byte_data, sizeof(struct hubdev_info *));
hubdev_ptr = __va((struct hubdev_info *) addr);
nasid = hubdev_ptr->hdi_nasid;
i = nasid_to_cnodeid(nasid);
hubdev = (struct hubdev_info *)(NODEPDA(i)->pdinfo);
*hubdev = *hubdev_ptr;
sn_common_hubdev_init(hubdev);
exit:
kfree(buffer.pointer);
return AE_OK; /* Continue walking namespace */
}
/*
* sn_get_bussoft_ptr() - The pcibus_bussoft pointer is found in
* the ACPI Vendor resource for this bus.
*/
static struct pcibus_bussoft *
sn_get_bussoft_ptr(struct pci_bus *bus)
{
u64 addr;
struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
struct acpi_buffer name_buffer = { ACPI_ALLOCATE_BUFFER, NULL };
acpi_handle handle;
struct pcibus_bussoft *prom_bussoft_ptr;
struct acpi_resource *resource;
acpi_status status;
struct acpi_resource_vendor_typed *vendor;
handle = PCI_CONTROLLER(bus)->acpi_handle;
status = acpi_get_vendor_resource(handle, METHOD_NAME__CRS,
&sn_uuid, &buffer);
if (ACPI_FAILURE(status)) {
acpi_get_name(handle, ACPI_FULL_PATHNAME, &name_buffer);
printk(KERN_ERR "%s: "
"acpi_get_vendor_resource() failed (0x%x) for: %s\n",
__func__, status, (char *)name_buffer.pointer);
kfree(name_buffer.pointer);
return NULL;
}
resource = buffer.pointer;
vendor = &resource->data.vendor_typed;
if ((vendor->byte_length - sizeof(struct acpi_vendor_uuid)) !=
sizeof(struct pcibus_bussoft *)) {
printk(KERN_ERR
"%s: Invalid vendor data length %d\n",
__func__, vendor->byte_length);
kfree(buffer.pointer);
return NULL;
}
memcpy(&addr, vendor->byte_data, sizeof(struct pcibus_bussoft *));
prom_bussoft_ptr = __va((struct pcibus_bussoft *) addr);
kfree(buffer.pointer);
return prom_bussoft_ptr;
}
/*
* sn_extract_device_info - Extract the pcidev_info and the sn_irq_info
* pointers from the vendor resource using the
* provided acpi handle, and copy the structures
* into the argument buffers.
*/
static int
sn_extract_device_info(acpi_handle handle, struct pcidev_info **pcidev_info,
struct sn_irq_info **sn_irq_info)
{
u64 addr;
struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
struct acpi_buffer name_buffer = { ACPI_ALLOCATE_BUFFER, NULL };
struct sn_irq_info *irq_info, *irq_info_prom;
struct pcidev_info *pcidev_ptr, *pcidev_prom_ptr;
struct acpi_resource *resource;
int ret = 0;
acpi_status status;
struct acpi_resource_vendor_typed *vendor;
/*
* The pointer to this device's pcidev_info structure in
* the PROM, is in the vendor resource.
*/
status = acpi_get_vendor_resource(handle, METHOD_NAME__CRS,
&sn_uuid, &buffer);
if (ACPI_FAILURE(status)) {
acpi_get_name(handle, ACPI_FULL_PATHNAME, &name_buffer);
printk(KERN_ERR
"%s: acpi_get_vendor_resource() failed (0x%x) for: %s\n",
__func__, status, (char *)name_buffer.pointer);
kfree(name_buffer.pointer);
return 1;
}
resource = buffer.pointer;
vendor = &resource->data.vendor_typed;
if ((vendor->byte_length - sizeof(struct acpi_vendor_uuid)) !=
sizeof(struct pci_devdev_info *)) {
acpi_get_name(handle, ACPI_FULL_PATHNAME, &name_buffer);
printk(KERN_ERR
"%s: Invalid vendor data length: %d for: %s\n",
__func__, vendor->byte_length,
(char *)name_buffer.pointer);
kfree(name_buffer.pointer);
ret = 1;
goto exit;
}
pcidev_ptr = kzalloc(sizeof(struct pcidev_info), GFP_KERNEL);
if (!pcidev_ptr)
panic("%s: Unable to alloc memory for pcidev_info", __func__);
memcpy(&addr, vendor->byte_data, sizeof(struct pcidev_info *));
pcidev_prom_ptr = __va(addr);
memcpy(pcidev_ptr, pcidev_prom_ptr, sizeof(struct pcidev_info));
/* Get the IRQ info */
irq_info = kzalloc(sizeof(struct sn_irq_info), GFP_KERNEL);
if (!irq_info)
panic("%s: Unable to alloc memory for sn_irq_info", __func__);
if (pcidev_ptr->pdi_sn_irq_info) {
irq_info_prom = __va(pcidev_ptr->pdi_sn_irq_info);
memcpy(irq_info, irq_info_prom, sizeof(struct sn_irq_info));
}
*pcidev_info = pcidev_ptr;
*sn_irq_info = irq_info;
exit:
kfree(buffer.pointer);
return ret;
}
static unsigned int
get_host_devfn(acpi_handle device_handle, acpi_handle rootbus_handle)
{
unsigned long long adr;
acpi_handle child;
unsigned int devfn;
int function;
acpi_handle parent;
int slot;
acpi_status status;
struct acpi_buffer name_buffer = { ACPI_ALLOCATE_BUFFER, NULL };
acpi_get_name(device_handle, ACPI_FULL_PATHNAME, &name_buffer);
/*
* Do an upward search to find the root bus device, and
* obtain the host devfn from the previous child device.
*/
child = device_handle;
while (child) {
status = acpi_get_parent(child, &parent);
if (ACPI_FAILURE(status)) {
printk(KERN_ERR "%s: acpi_get_parent() failed "
"(0x%x) for: %s\n", __func__, status,
(char *)name_buffer.pointer);
panic("%s: Unable to find host devfn\n", __func__);
}
if (parent == rootbus_handle)
break;
child = parent;
}
if (!child) {
printk(KERN_ERR "%s: Unable to find root bus for: %s\n",
__func__, (char *)name_buffer.pointer);
BUG();
}
status = acpi_evaluate_integer(child, METHOD_NAME__ADR, NULL, &adr);
if (ACPI_FAILURE(status)) {
printk(KERN_ERR "%s: Unable to get _ADR (0x%x) for: %s\n",
__func__, status, (char *)name_buffer.pointer);
panic("%s: Unable to find host devfn\n", __func__);
}
kfree(name_buffer.pointer);
slot = (adr >> 16) & 0xffff;
function = adr & 0xffff;
devfn = PCI_DEVFN(slot, function);
return devfn;
}
/*
* find_matching_device - Callback routine to find the ACPI device
* that matches up with our pci_dev device.
* Matching is done on bus number and devfn.
* To find the bus number for a particular
* ACPI device, we must look at the _BBN method
* of its parent.
*/
static acpi_status
find_matching_device(acpi_handle handle, u32 lvl, void *context, void **rv)
{
unsigned long long bbn = -1;
unsigned long long adr;
acpi_handle parent = NULL;
acpi_status status;
unsigned int devfn;
int function;
int slot;
struct sn_pcidev_match *info = context;
struct acpi_buffer name_buffer = { ACPI_ALLOCATE_BUFFER, NULL };
status = acpi_evaluate_integer(handle, METHOD_NAME__ADR, NULL,
&adr);
if (ACPI_SUCCESS(status)) {
status = acpi_get_parent(handle, &parent);
if (ACPI_FAILURE(status)) {
acpi_get_name(handle, ACPI_FULL_PATHNAME, &name_buffer);
printk(KERN_ERR
"%s: acpi_get_parent() failed (0x%x) for: %s\n",
__func__, status, (char *)name_buffer.pointer);
kfree(name_buffer.pointer);
return AE_OK;
}
status = acpi_evaluate_integer(parent, METHOD_NAME__BBN,
NULL, &bbn);
if (ACPI_FAILURE(status)) {
acpi_get_name(handle, ACPI_FULL_PATHNAME, &name_buffer);
printk(KERN_ERR
"%s: Failed to find _BBN in parent of: %s\n",
__func__, (char *)name_buffer.pointer);
kfree(name_buffer.pointer);
return AE_OK;
}
slot = (adr >> 16) & 0xffff;
function = adr & 0xffff;
devfn = PCI_DEVFN(slot, function);
if ((info->devfn == devfn) && (info->bus == bbn)) {
/* We have a match! */
info->handle = handle;
return 1;
}
}
return AE_OK;
}
/*
* sn_acpi_get_pcidev_info - Search ACPI namespace for the acpi
* device matching the specified pci_dev,
* and return the pcidev info and irq info.
*/
int
sn_acpi_get_pcidev_info(struct pci_dev *dev, struct pcidev_info **pcidev_info,
struct sn_irq_info **sn_irq_info)
{
unsigned int host_devfn;
struct sn_pcidev_match pcidev_match;
acpi_handle rootbus_handle;
unsigned long long segment;
acpi_status status;
struct acpi_buffer name_buffer = { ACPI_ALLOCATE_BUFFER, NULL };
rootbus_handle = PCI_CONTROLLER(dev)->acpi_handle;
status = acpi_evaluate_integer(rootbus_handle, METHOD_NAME__SEG, NULL,
&segment);
if (ACPI_SUCCESS(status)) {
if (segment != pci_domain_nr(dev)) {
acpi_get_name(rootbus_handle, ACPI_FULL_PATHNAME,
&name_buffer);
printk(KERN_ERR
"%s: Segment number mismatch, 0x%llx vs 0x%x for: %s\n",
__func__, segment, pci_domain_nr(dev),
(char *)name_buffer.pointer);
kfree(name_buffer.pointer);
return 1;
}
} else {
acpi_get_name(rootbus_handle, ACPI_FULL_PATHNAME, &name_buffer);
printk(KERN_ERR "%s: Unable to get __SEG from: %s\n",
__func__, (char *)name_buffer.pointer);
kfree(name_buffer.pointer);
return 1;
}
/*
* We want to search all devices in this segment/domain
* of the ACPI namespace for the matching ACPI device,
* which holds the pcidev_info pointer in its vendor resource.
*/
pcidev_match.bus = dev->bus->number;
pcidev_match.devfn = dev->devfn;
pcidev_match.handle = NULL;
acpi_walk_namespace(ACPI_TYPE_DEVICE, rootbus_handle, ACPI_UINT32_MAX,
find_matching_device, NULL, &pcidev_match, NULL);
if (!pcidev_match.handle) {
printk(KERN_ERR
"%s: Could not find matching ACPI device for %s.\n",
__func__, pci_name(dev));
return 1;
}
if (sn_extract_device_info(pcidev_match.handle, pcidev_info, sn_irq_info))
return 1;
/* Build up the pcidev_info.pdi_slot_host_handle */
host_devfn = get_host_devfn(pcidev_match.handle, rootbus_handle);
(*pcidev_info)->pdi_slot_host_handle =
((unsigned long) pci_domain_nr(dev) << 40) |
/* bus == 0 */
host_devfn;
return 0;
}
/*
* sn_acpi_slot_fixup - Obtain the pcidev_info and sn_irq_info.
* Perform any SN specific slot fixup.
* At present there does not appear to be
* any generic way to handle a ROM image
* that has been shadowed by the PROM, so
* we pass a pointer to it within the
* pcidev_info structure.
*/
void
sn_acpi_slot_fixup(struct pci_dev *dev)
{
void __iomem *addr;
struct pcidev_info *pcidev_info = NULL;
struct sn_irq_info *sn_irq_info = NULL;
size_t image_size, size;
if (sn_acpi_get_pcidev_info(dev, &pcidev_info, &sn_irq_info)) {
panic("%s: Failure obtaining pcidev_info for %s\n",
__func__, pci_name(dev));
}
if (pcidev_info->pdi_pio_mapped_addr[PCI_ROM_RESOURCE]) {
/*
* A valid ROM image exists and has been shadowed by the
* PROM. Setup the pci_dev ROM resource with the address
* of the shadowed copy, and the actual length of the ROM image.
*/
size = pci_resource_len(dev, PCI_ROM_RESOURCE);
addr = ioremap(pcidev_info->pdi_pio_mapped_addr[PCI_ROM_RESOURCE],
size);
image_size = pci_get_rom_size(dev, addr, size);
dev->resource[PCI_ROM_RESOURCE].start = (unsigned long) addr;
dev->resource[PCI_ROM_RESOURCE].end =
(unsigned long) addr + image_size - 1;
dev->resource[PCI_ROM_RESOURCE].flags |= IORESOURCE_ROM_BIOS_COPY;
}
sn_pci_fixup_slot(dev, pcidev_info, sn_irq_info);
}
EXPORT_SYMBOL(sn_acpi_slot_fixup);
/*
* sn_acpi_bus_fixup - Perform SN specific setup of software structs
* (pcibus_bussoft, pcidev_info) and hardware
* registers, for the specified bus and devices under it.
*/
void
sn_acpi_bus_fixup(struct pci_bus *bus)
{
struct pci_dev *pci_dev = NULL;
struct pcibus_bussoft *prom_bussoft_ptr;
if (!bus->parent) { /* If root bus */
prom_bussoft_ptr = sn_get_bussoft_ptr(bus);
if (prom_bussoft_ptr == NULL) {
printk(KERN_ERR
"%s: 0x%04x:0x%02x Unable to "
"obtain prom_bussoft_ptr\n",
__func__, pci_domain_nr(bus), bus->number);
return;
}
sn_common_bus_fixup(bus, prom_bussoft_ptr);
}
list_for_each_entry(pci_dev, &bus->devices, bus_list) {
sn_acpi_slot_fixup(pci_dev);
}
}
/*
* sn_io_acpi_init - PROM has ACPI support for IO, defining at a minimum the
* nodes and root buses in the DSDT. As a result, bus scanning
* will be initiated by the Linux ACPI code.
*/
void __init
sn_io_acpi_init(void)
{
u64 result;
long status;
/* SN Altix does not follow the IOSAPIC IRQ routing model */
acpi_irq_model = ACPI_IRQ_MODEL_PLATFORM;
/* Setup hubdev_info for all SGIHUB/SGITIO devices */
acpi_get_devices("SGIHUB", sn_acpi_hubdev_init, NULL, NULL);
acpi_get_devices("SGITIO", sn_acpi_hubdev_init, NULL, NULL);
status = sal_ioif_init(&result);
if (status || result)
panic("sal_ioif_init failed: [%lx] %s\n",
status, ia64_sal_strerror(status));
}
| gpl-2.0 |
mlachwani/Android_4.4.2_MotoG_Kernel | arch/mips/sgi-ip27/ip27-memory.c | 4552 | 12031 | /*
* 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) 2000, 05 by Ralf Baechle (ralf@linux-mips.org)
* Copyright (C) 2000 by Silicon Graphics, Inc.
* Copyright (C) 2004 by Christoph Hellwig
*
* On SGI IP27 the ARC memory configuration data is completly bogus but
* alternate easier to use mechanisms are available.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/memblock.h>
#include <linux/mm.h>
#include <linux/mmzone.h>
#include <linux/module.h>
#include <linux/nodemask.h>
#include <linux/swap.h>
#include <linux/bootmem.h>
#include <linux/pfn.h>
#include <linux/highmem.h>
#include <asm/page.h>
#include <asm/pgalloc.h>
#include <asm/sections.h>
#include <asm/sn/arch.h>
#include <asm/sn/hub.h>
#include <asm/sn/klconfig.h>
#include <asm/sn/sn_private.h>
#define SLOT_PFNSHIFT (SLOT_SHIFT - PAGE_SHIFT)
#define PFN_NASIDSHFT (NASID_SHFT - PAGE_SHIFT)
struct node_data *__node_data[MAX_COMPACT_NODES];
EXPORT_SYMBOL(__node_data);
static int fine_mode;
static int is_fine_dirmode(void)
{
return (((LOCAL_HUB_L(NI_STATUS_REV_ID) & NSRI_REGIONSIZE_MASK)
>> NSRI_REGIONSIZE_SHFT) & REGIONSIZE_FINE);
}
static hubreg_t get_region(cnodeid_t cnode)
{
if (fine_mode)
return COMPACT_TO_NASID_NODEID(cnode) >> NASID_TO_FINEREG_SHFT;
else
return COMPACT_TO_NASID_NODEID(cnode) >> NASID_TO_COARSEREG_SHFT;
}
static hubreg_t region_mask;
static void gen_region_mask(hubreg_t *region_mask)
{
cnodeid_t cnode;
(*region_mask) = 0;
for_each_online_node(cnode) {
(*region_mask) |= 1ULL << get_region(cnode);
}
}
#define rou_rflag rou_flags
static int router_distance;
static void router_recurse(klrou_t *router_a, klrou_t *router_b, int depth)
{
klrou_t *router;
lboard_t *brd;
int port;
if (router_a->rou_rflag == 1)
return;
if (depth >= router_distance)
return;
router_a->rou_rflag = 1;
for (port = 1; port <= MAX_ROUTER_PORTS; port++) {
if (router_a->rou_port[port].port_nasid == INVALID_NASID)
continue;
brd = (lboard_t *)NODE_OFFSET_TO_K0(
router_a->rou_port[port].port_nasid,
router_a->rou_port[port].port_offset);
if (brd->brd_type == KLTYPE_ROUTER) {
router = (klrou_t *)NODE_OFFSET_TO_K0(NASID_GET(brd), brd->brd_compts[0]);
if (router == router_b) {
if (depth < router_distance)
router_distance = depth;
}
else
router_recurse(router, router_b, depth + 1);
}
}
router_a->rou_rflag = 0;
}
unsigned char __node_distances[MAX_COMPACT_NODES][MAX_COMPACT_NODES];
static int __init compute_node_distance(nasid_t nasid_a, nasid_t nasid_b)
{
klrou_t *router, *router_a = NULL, *router_b = NULL;
lboard_t *brd, *dest_brd;
cnodeid_t cnode;
nasid_t nasid;
int port;
/* Figure out which routers nodes in question are connected to */
for_each_online_node(cnode) {
nasid = COMPACT_TO_NASID_NODEID(cnode);
if (nasid == -1) continue;
brd = find_lboard_class((lboard_t *)KL_CONFIG_INFO(nasid),
KLTYPE_ROUTER);
if (!brd)
continue;
do {
if (brd->brd_flags & DUPLICATE_BOARD)
continue;
router = (klrou_t *)NODE_OFFSET_TO_K0(NASID_GET(brd), brd->brd_compts[0]);
router->rou_rflag = 0;
for (port = 1; port <= MAX_ROUTER_PORTS; port++) {
if (router->rou_port[port].port_nasid == INVALID_NASID)
continue;
dest_brd = (lboard_t *)NODE_OFFSET_TO_K0(
router->rou_port[port].port_nasid,
router->rou_port[port].port_offset);
if (dest_brd->brd_type == KLTYPE_IP27) {
if (dest_brd->brd_nasid == nasid_a)
router_a = router;
if (dest_brd->brd_nasid == nasid_b)
router_b = router;
}
}
} while ((brd = find_lboard_class(KLCF_NEXT(brd), KLTYPE_ROUTER)));
}
if (router_a == NULL) {
printk("node_distance: router_a NULL\n");
return -1;
}
if (router_b == NULL) {
printk("node_distance: router_b NULL\n");
return -1;
}
if (nasid_a == nasid_b)
return 0;
if (router_a == router_b)
return 1;
router_distance = 100;
router_recurse(router_a, router_b, 2);
return router_distance;
}
static void __init init_topology_matrix(void)
{
nasid_t nasid, nasid2;
cnodeid_t row, col;
for (row = 0; row < MAX_COMPACT_NODES; row++)
for (col = 0; col < MAX_COMPACT_NODES; col++)
__node_distances[row][col] = -1;
for_each_online_node(row) {
nasid = COMPACT_TO_NASID_NODEID(row);
for_each_online_node(col) {
nasid2 = COMPACT_TO_NASID_NODEID(col);
__node_distances[row][col] =
compute_node_distance(nasid, nasid2);
}
}
}
static void __init dump_topology(void)
{
nasid_t nasid;
cnodeid_t cnode;
lboard_t *brd, *dest_brd;
int port;
int router_num = 0;
klrou_t *router;
cnodeid_t row, col;
printk("************** Topology ********************\n");
printk(" ");
for_each_online_node(col)
printk("%02d ", col);
printk("\n");
for_each_online_node(row) {
printk("%02d ", row);
for_each_online_node(col)
printk("%2d ", node_distance(row, col));
printk("\n");
}
for_each_online_node(cnode) {
nasid = COMPACT_TO_NASID_NODEID(cnode);
if (nasid == -1) continue;
brd = find_lboard_class((lboard_t *)KL_CONFIG_INFO(nasid),
KLTYPE_ROUTER);
if (!brd)
continue;
do {
if (brd->brd_flags & DUPLICATE_BOARD)
continue;
printk("Router %d:", router_num);
router_num++;
router = (klrou_t *)NODE_OFFSET_TO_K0(NASID_GET(brd), brd->brd_compts[0]);
for (port = 1; port <= MAX_ROUTER_PORTS; port++) {
if (router->rou_port[port].port_nasid == INVALID_NASID)
continue;
dest_brd = (lboard_t *)NODE_OFFSET_TO_K0(
router->rou_port[port].port_nasid,
router->rou_port[port].port_offset);
if (dest_brd->brd_type == KLTYPE_IP27)
printk(" %d", dest_brd->brd_nasid);
if (dest_brd->brd_type == KLTYPE_ROUTER)
printk(" r");
}
printk("\n");
} while ( (brd = find_lboard_class(KLCF_NEXT(brd), KLTYPE_ROUTER)) );
}
}
static pfn_t __init slot_getbasepfn(cnodeid_t cnode, int slot)
{
nasid_t nasid = COMPACT_TO_NASID_NODEID(cnode);
return ((pfn_t)nasid << PFN_NASIDSHFT) | (slot << SLOT_PFNSHIFT);
}
static pfn_t __init slot_psize_compute(cnodeid_t node, int slot)
{
nasid_t nasid;
lboard_t *brd;
klmembnk_t *banks;
unsigned long size;
nasid = COMPACT_TO_NASID_NODEID(node);
/* Find the node board */
brd = find_lboard((lboard_t *)KL_CONFIG_INFO(nasid), KLTYPE_IP27);
if (!brd)
return 0;
/* Get the memory bank structure */
banks = (klmembnk_t *) find_first_component(brd, KLSTRUCT_MEMBNK);
if (!banks)
return 0;
/* Size in _Megabytes_ */
size = (unsigned long)banks->membnk_bnksz[slot/4];
/* hack for 128 dimm banks */
if (size <= 128) {
if (slot % 4 == 0) {
size <<= 20; /* size in bytes */
return(size >> PAGE_SHIFT);
} else
return 0;
} else {
size /= 4;
size <<= 20;
return size >> PAGE_SHIFT;
}
}
static void __init mlreset(void)
{
int i;
master_nasid = get_nasid();
fine_mode = is_fine_dirmode();
/*
* Probe for all CPUs - this creates the cpumask and sets up the
* mapping tables. We need to do this as early as possible.
*/
#ifdef CONFIG_SMP
cpu_node_probe();
#endif
init_topology_matrix();
dump_topology();
gen_region_mask(®ion_mask);
setup_replication_mask();
/*
* Set all nodes' calias sizes to 8k
*/
for_each_online_node(i) {
nasid_t nasid;
nasid = COMPACT_TO_NASID_NODEID(i);
/*
* Always have node 0 in the region mask, otherwise
* CALIAS accesses get exceptions since the hub
* thinks it is a node 0 address.
*/
REMOTE_HUB_S(nasid, PI_REGION_PRESENT, (region_mask | 1));
#ifdef CONFIG_REPLICATE_EXHANDLERS
REMOTE_HUB_S(nasid, PI_CALIAS_SIZE, PI_CALIAS_SIZE_8K);
#else
REMOTE_HUB_S(nasid, PI_CALIAS_SIZE, PI_CALIAS_SIZE_0);
#endif
#ifdef LATER
/*
* Set up all hubs to have a big window pointing at
* widget 0. Memory mode, widget 0, offset 0
*/
REMOTE_HUB_S(nasid, IIO_ITTE(SWIN0_BIGWIN),
((HUB_PIO_MAP_TO_MEM << IIO_ITTE_IOSP_SHIFT) |
(0 << IIO_ITTE_WIDGET_SHIFT)));
#endif
}
}
static void __init szmem(void)
{
pfn_t slot_psize, slot0sz = 0, nodebytes; /* Hack to detect problem configs */
int slot;
cnodeid_t node;
num_physpages = 0;
for_each_online_node(node) {
nodebytes = 0;
for (slot = 0; slot < MAX_MEM_SLOTS; slot++) {
slot_psize = slot_psize_compute(node, slot);
if (slot == 0)
slot0sz = slot_psize;
/*
* We need to refine the hack when we have replicated
* kernel text.
*/
nodebytes += (1LL << SLOT_SHIFT);
if (!slot_psize)
continue;
if ((nodebytes >> PAGE_SHIFT) * (sizeof(struct page)) >
(slot0sz << PAGE_SHIFT)) {
printk("Ignoring slot %d onwards on node %d\n",
slot, node);
slot = MAX_MEM_SLOTS;
continue;
}
num_physpages += slot_psize;
memblock_add_node(PFN_PHYS(slot_getbasepfn(node, slot)),
PFN_PHYS(slot_psize), node);
}
}
}
static void __init node_mem_init(cnodeid_t node)
{
pfn_t slot_firstpfn = slot_getbasepfn(node, 0);
pfn_t slot_freepfn = node_getfirstfree(node);
unsigned long bootmap_size;
pfn_t start_pfn, end_pfn;
get_pfn_range_for_nid(node, &start_pfn, &end_pfn);
/*
* Allocate the node data structures on the node first.
*/
__node_data[node] = __va(slot_freepfn << PAGE_SHIFT);
NODE_DATA(node)->bdata = &bootmem_node_data[node];
NODE_DATA(node)->node_start_pfn = start_pfn;
NODE_DATA(node)->node_spanned_pages = end_pfn - start_pfn;
cpus_clear(hub_data(node)->h_cpus);
slot_freepfn += PFN_UP(sizeof(struct pglist_data) +
sizeof(struct hub_data));
bootmap_size = init_bootmem_node(NODE_DATA(node), slot_freepfn,
start_pfn, end_pfn);
free_bootmem_with_active_regions(node, end_pfn);
reserve_bootmem_node(NODE_DATA(node), slot_firstpfn << PAGE_SHIFT,
((slot_freepfn - slot_firstpfn) << PAGE_SHIFT) + bootmap_size,
BOOTMEM_DEFAULT);
sparse_memory_present_with_active_regions(node);
}
/*
* A node with nothing. We use it to avoid any special casing in
* cpumask_of_node
*/
static struct node_data null_node = {
.hub = {
.h_cpus = CPU_MASK_NONE
}
};
/*
* Currently, the intranode memory hole support assumes that each slot
* contains at least 32 MBytes of memory. We assume all bootmem data
* fits on the first slot.
*/
void __init prom_meminit(void)
{
cnodeid_t node;
mlreset();
szmem();
for (node = 0; node < MAX_COMPACT_NODES; node++) {
if (node_online(node)) {
node_mem_init(node);
continue;
}
__node_data[node] = &null_node;
}
}
void __init prom_free_prom_memory(void)
{
/* We got nothing to free here ... */
}
extern unsigned long setup_zero_pages(void);
void __init paging_init(void)
{
unsigned long zones_size[MAX_NR_ZONES] = {0, };
unsigned node;
pagetable_init();
for_each_online_node(node) {
pfn_t start_pfn, end_pfn;
get_pfn_range_for_nid(node, &start_pfn, &end_pfn);
if (end_pfn > max_low_pfn)
max_low_pfn = end_pfn;
}
zones_size[ZONE_NORMAL] = max_low_pfn;
free_area_init_nodes(zones_size);
}
void __init mem_init(void)
{
unsigned long codesize, datasize, initsize, tmp;
unsigned node;
high_memory = (void *) __va(num_physpages << PAGE_SHIFT);
for_each_online_node(node) {
/*
* This will free up the bootmem, ie, slot 0 memory.
*/
totalram_pages += free_all_bootmem_node(NODE_DATA(node));
}
totalram_pages -= setup_zero_pages(); /* This comes from node 0 */
codesize = (unsigned long) &_etext - (unsigned long) &_text;
datasize = (unsigned long) &_edata - (unsigned long) &_etext;
initsize = (unsigned long) &__init_end - (unsigned long) &__init_begin;
tmp = nr_free_pages();
printk(KERN_INFO "Memory: %luk/%luk available (%ldk kernel code, "
"%ldk reserved, %ldk data, %ldk init, %ldk highmem)\n",
tmp << (PAGE_SHIFT-10),
num_physpages << (PAGE_SHIFT-10),
codesize >> 10,
(num_physpages - tmp) << (PAGE_SHIFT-10),
datasize >> 10,
initsize >> 10,
totalhigh_pages << (PAGE_SHIFT-10));
}
| gpl-2.0 |
yank555-lu/Hammerhead-3.4-lollipop | arch/mips/pci/pci-bcm63xx.c | 4552 | 6754 | /*
* 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/types.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <asm/bootinfo.h>
#include "pci-bcm63xx.h"
/*
* Allow PCI to be disabled at runtime depending on board nvram
* configuration
*/
int bcm63xx_pci_enabled;
static struct resource bcm_pci_mem_resource = {
.name = "bcm63xx PCI memory space",
.start = BCM_PCI_MEM_BASE_PA,
.end = BCM_PCI_MEM_END_PA,
.flags = IORESOURCE_MEM
};
static struct resource bcm_pci_io_resource = {
.name = "bcm63xx PCI IO space",
.start = BCM_PCI_IO_BASE_PA,
#ifdef CONFIG_CARDBUS
.end = BCM_PCI_IO_HALF_PA,
#else
.end = BCM_PCI_IO_END_PA,
#endif
.flags = IORESOURCE_IO
};
struct pci_controller bcm63xx_controller = {
.pci_ops = &bcm63xx_pci_ops,
.io_resource = &bcm_pci_io_resource,
.mem_resource = &bcm_pci_mem_resource,
};
/*
* We handle cardbus via a fake Cardbus bridge, memory and io spaces
* have to be clearly separated from PCI one since we have different
* memory decoder.
*/
#ifdef CONFIG_CARDBUS
static struct resource bcm_cb_mem_resource = {
.name = "bcm63xx Cardbus memory space",
.start = BCM_CB_MEM_BASE_PA,
.end = BCM_CB_MEM_END_PA,
.flags = IORESOURCE_MEM
};
static struct resource bcm_cb_io_resource = {
.name = "bcm63xx Cardbus IO space",
.start = BCM_PCI_IO_HALF_PA + 1,
.end = BCM_PCI_IO_END_PA,
.flags = IORESOURCE_IO
};
struct pci_controller bcm63xx_cb_controller = {
.pci_ops = &bcm63xx_cb_ops,
.io_resource = &bcm_cb_io_resource,
.mem_resource = &bcm_cb_mem_resource,
};
#endif
static u32 bcm63xx_int_cfg_readl(u32 reg)
{
u32 tmp;
tmp = reg & MPI_PCICFGCTL_CFGADDR_MASK;
tmp |= MPI_PCICFGCTL_WRITEEN_MASK;
bcm_mpi_writel(tmp, MPI_PCICFGCTL_REG);
iob();
return bcm_mpi_readl(MPI_PCICFGDATA_REG);
}
static void bcm63xx_int_cfg_writel(u32 val, u32 reg)
{
u32 tmp;
tmp = reg & MPI_PCICFGCTL_CFGADDR_MASK;
tmp |= MPI_PCICFGCTL_WRITEEN_MASK;
bcm_mpi_writel(tmp, MPI_PCICFGCTL_REG);
bcm_mpi_writel(val, MPI_PCICFGDATA_REG);
}
void __iomem *pci_iospace_start;
static int __init bcm63xx_pci_init(void)
{
unsigned int mem_size;
u32 val;
if (!BCMCPU_IS_6348() && !BCMCPU_IS_6358() && !BCMCPU_IS_6368())
return -ENODEV;
if (!bcm63xx_pci_enabled)
return -ENODEV;
/*
* configuration access are done through IO space, remap 4
* first bytes to access it from CPU.
*
* this means that no io access from CPU should happen while
* we do a configuration cycle, but there's no way we can add
* a spinlock for each io access, so this is currently kind of
* broken on SMP.
*/
pci_iospace_start = ioremap_nocache(BCM_PCI_IO_BASE_PA, 4);
if (!pci_iospace_start)
return -ENOMEM;
/* setup local bus to PCI access (PCI memory) */
val = BCM_PCI_MEM_BASE_PA & MPI_L2P_BASE_MASK;
bcm_mpi_writel(val, MPI_L2PMEMBASE1_REG);
bcm_mpi_writel(~(BCM_PCI_MEM_SIZE - 1), MPI_L2PMEMRANGE1_REG);
bcm_mpi_writel(val | MPI_L2PREMAP_ENABLED_MASK, MPI_L2PMEMREMAP1_REG);
/* set Cardbus IDSEL (type 0 cfg access on primary bus for
* this IDSEL will be done on Cardbus instead) */
val = bcm_pcmcia_readl(PCMCIA_C1_REG);
val &= ~PCMCIA_C1_CBIDSEL_MASK;
val |= (CARDBUS_PCI_IDSEL << PCMCIA_C1_CBIDSEL_SHIFT);
bcm_pcmcia_writel(val, PCMCIA_C1_REG);
#ifdef CONFIG_CARDBUS
/* setup local bus to PCI access (Cardbus memory) */
val = BCM_CB_MEM_BASE_PA & MPI_L2P_BASE_MASK;
bcm_mpi_writel(val, MPI_L2PMEMBASE2_REG);
bcm_mpi_writel(~(BCM_CB_MEM_SIZE - 1), MPI_L2PMEMRANGE2_REG);
val |= MPI_L2PREMAP_ENABLED_MASK | MPI_L2PREMAP_IS_CARDBUS_MASK;
bcm_mpi_writel(val, MPI_L2PMEMREMAP2_REG);
#else
/* disable second access windows */
bcm_mpi_writel(0, MPI_L2PMEMREMAP2_REG);
#endif
/* setup local bus to PCI access (IO memory), we have only 1
* IO window for both PCI and cardbus, but it cannot handle
* both at the same time, assume standard PCI for now, if
* cardbus card has IO zone, PCI fixup will change window to
* cardbus */
val = BCM_PCI_IO_BASE_PA & MPI_L2P_BASE_MASK;
bcm_mpi_writel(val, MPI_L2PIOBASE_REG);
bcm_mpi_writel(~(BCM_PCI_IO_SIZE - 1), MPI_L2PIORANGE_REG);
bcm_mpi_writel(val | MPI_L2PREMAP_ENABLED_MASK, MPI_L2PIOREMAP_REG);
/* enable PCI related GPIO pins */
bcm_mpi_writel(MPI_LOCBUSCTL_EN_PCI_GPIO_MASK, MPI_LOCBUSCTL_REG);
/* setup PCI to local bus access, used by PCI device to target
* local RAM while bus mastering */
bcm63xx_int_cfg_writel(0, PCI_BASE_ADDRESS_3);
if (BCMCPU_IS_6358() || BCMCPU_IS_6368())
val = MPI_SP0_REMAP_ENABLE_MASK;
else
val = 0;
bcm_mpi_writel(val, MPI_SP0_REMAP_REG);
bcm63xx_int_cfg_writel(0x0, PCI_BASE_ADDRESS_4);
bcm_mpi_writel(0, MPI_SP1_REMAP_REG);
mem_size = bcm63xx_get_memory_size();
/* 6348 before rev b0 exposes only 16 MB of RAM memory through
* PCI, throw a warning if we have more memory */
if (BCMCPU_IS_6348() && (bcm63xx_get_cpu_rev() & 0xf0) == 0xa0) {
if (mem_size > (16 * 1024 * 1024))
printk(KERN_WARNING "bcm63xx: this CPU "
"revision cannot handle more than 16MB "
"of RAM for PCI bus mastering\n");
} else {
/* setup sp0 range to local RAM size */
bcm_mpi_writel(~(mem_size - 1), MPI_SP0_RANGE_REG);
bcm_mpi_writel(0, MPI_SP1_RANGE_REG);
}
/* change host bridge retry counter to infinite number of
* retry, needed for some broadcom wifi cards with Silicon
* Backplane bus where access to srom seems very slow */
val = bcm63xx_int_cfg_readl(BCMPCI_REG_TIMERS);
val &= ~REG_TIMER_RETRY_MASK;
bcm63xx_int_cfg_writel(val, BCMPCI_REG_TIMERS);
/* enable memory decoder and bus mastering */
val = bcm63xx_int_cfg_readl(PCI_COMMAND);
val |= (PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER);
bcm63xx_int_cfg_writel(val, PCI_COMMAND);
/* enable read prefetching & disable byte swapping for bus
* mastering transfers */
val = bcm_mpi_readl(MPI_PCIMODESEL_REG);
val &= ~MPI_PCIMODESEL_BAR1_NOSWAP_MASK;
val &= ~MPI_PCIMODESEL_BAR2_NOSWAP_MASK;
val &= ~MPI_PCIMODESEL_PREFETCH_MASK;
val |= (8 << MPI_PCIMODESEL_PREFETCH_SHIFT);
bcm_mpi_writel(val, MPI_PCIMODESEL_REG);
/* enable pci interrupt */
val = bcm_mpi_readl(MPI_LOCINT_REG);
val |= MPI_LOCINT_MASK(MPI_LOCINT_EXT_PCI_INT);
bcm_mpi_writel(val, MPI_LOCINT_REG);
register_pci_controller(&bcm63xx_controller);
#ifdef CONFIG_CARDBUS
register_pci_controller(&bcm63xx_cb_controller);
#endif
/* mark memory space used for IO mapping as reserved */
request_mem_region(BCM_PCI_IO_BASE_PA, BCM_PCI_IO_SIZE,
"bcm63xx PCI IO space");
return 0;
}
arch_initcall(bcm63xx_pci_init);
| gpl-2.0 |
oppo-source/Find7-5.0-kernel-source | arch/mips/alchemy/devboards/bcsr.c | 4552 | 3626 | /*
* bcsr.h -- Db1xxx/Pb1xxx Devboard CPLD registers ("BCSR") abstraction.
*
* All Alchemy development boards (except, of course, the weird PB1000)
* have a few registers in a CPLD with standardised layout; they mostly
* only differ in base address.
* All registers are 16bits wide with 32bit spacing.
*/
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/irq.h>
#include <asm/addrspace.h>
#include <asm/io.h>
#include <asm/mach-db1x00/bcsr.h>
static struct bcsr_reg {
void __iomem *raddr;
spinlock_t lock;
} bcsr_regs[BCSR_CNT];
static void __iomem *bcsr_virt; /* KSEG1 addr of BCSR base */
static int bcsr_csc_base; /* linux-irq of first cascaded irq */
void __init bcsr_init(unsigned long bcsr1_phys, unsigned long bcsr2_phys)
{
int i;
bcsr1_phys = KSEG1ADDR(CPHYSADDR(bcsr1_phys));
bcsr2_phys = KSEG1ADDR(CPHYSADDR(bcsr2_phys));
bcsr_virt = (void __iomem *)bcsr1_phys;
for (i = 0; i < BCSR_CNT; i++) {
if (i >= BCSR_HEXLEDS)
bcsr_regs[i].raddr = (void __iomem *)bcsr2_phys +
(0x04 * (i - BCSR_HEXLEDS));
else
bcsr_regs[i].raddr = (void __iomem *)bcsr1_phys +
(0x04 * i);
spin_lock_init(&bcsr_regs[i].lock);
}
}
unsigned short bcsr_read(enum bcsr_id reg)
{
unsigned short r;
unsigned long flags;
spin_lock_irqsave(&bcsr_regs[reg].lock, flags);
r = __raw_readw(bcsr_regs[reg].raddr);
spin_unlock_irqrestore(&bcsr_regs[reg].lock, flags);
return r;
}
EXPORT_SYMBOL_GPL(bcsr_read);
void bcsr_write(enum bcsr_id reg, unsigned short val)
{
unsigned long flags;
spin_lock_irqsave(&bcsr_regs[reg].lock, flags);
__raw_writew(val, bcsr_regs[reg].raddr);
wmb();
spin_unlock_irqrestore(&bcsr_regs[reg].lock, flags);
}
EXPORT_SYMBOL_GPL(bcsr_write);
void bcsr_mod(enum bcsr_id reg, unsigned short clr, unsigned short set)
{
unsigned short r;
unsigned long flags;
spin_lock_irqsave(&bcsr_regs[reg].lock, flags);
r = __raw_readw(bcsr_regs[reg].raddr);
r &= ~clr;
r |= set;
__raw_writew(r, bcsr_regs[reg].raddr);
wmb();
spin_unlock_irqrestore(&bcsr_regs[reg].lock, flags);
}
EXPORT_SYMBOL_GPL(bcsr_mod);
/*
* DB1200/PB1200 CPLD IRQ muxer
*/
static void bcsr_csc_handler(unsigned int irq, struct irq_desc *d)
{
unsigned short bisr = __raw_readw(bcsr_virt + BCSR_REG_INTSTAT);
disable_irq_nosync(irq);
for ( ; bisr; bisr &= bisr - 1)
generic_handle_irq(bcsr_csc_base + __ffs(bisr));
enable_irq(irq);
}
static void bcsr_irq_mask(struct irq_data *d)
{
unsigned short v = 1 << (d->irq - bcsr_csc_base);
__raw_writew(v, bcsr_virt + BCSR_REG_MASKCLR);
wmb();
}
static void bcsr_irq_maskack(struct irq_data *d)
{
unsigned short v = 1 << (d->irq - bcsr_csc_base);
__raw_writew(v, bcsr_virt + BCSR_REG_MASKCLR);
__raw_writew(v, bcsr_virt + BCSR_REG_INTSTAT); /* ack */
wmb();
}
static void bcsr_irq_unmask(struct irq_data *d)
{
unsigned short v = 1 << (d->irq - bcsr_csc_base);
__raw_writew(v, bcsr_virt + BCSR_REG_MASKSET);
wmb();
}
static struct irq_chip bcsr_irq_type = {
.name = "CPLD",
.irq_mask = bcsr_irq_mask,
.irq_mask_ack = bcsr_irq_maskack,
.irq_unmask = bcsr_irq_unmask,
};
void __init bcsr_init_irq(int csc_start, int csc_end, int hook_irq)
{
unsigned int irq;
/* mask & enable & ack all */
__raw_writew(0xffff, bcsr_virt + BCSR_REG_MASKCLR);
__raw_writew(0xffff, bcsr_virt + BCSR_REG_INTSET);
__raw_writew(0xffff, bcsr_virt + BCSR_REG_INTSTAT);
wmb();
bcsr_csc_base = csc_start;
for (irq = csc_start; irq <= csc_end; irq++)
irq_set_chip_and_handler_name(irq, &bcsr_irq_type,
handle_level_irq, "level");
irq_set_chained_handler(hook_irq, bcsr_csc_handler);
}
| gpl-2.0 |
qingdear/lemax | drivers/isdn/hisax/nj_s.c | 4808 | 8283 | /* $Id: nj_s.c,v 2.13.2.4 2004/01/16 01:53:48 keil Exp $
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/init.h>
#include "hisax.h"
#include "isac.h"
#include "isdnl1.h"
#include <linux/pci.h>
#include <linux/interrupt.h>
#include <linux/ppp_defs.h>
#include "netjet.h"
static const char *NETjet_S_revision = "$Revision: 2.13.2.4 $";
static u_char dummyrr(struct IsdnCardState *cs, int chan, u_char off)
{
return (5);
}
static void dummywr(struct IsdnCardState *cs, int chan, u_char off, u_char value)
{
}
static irqreturn_t
netjet_s_interrupt(int intno, void *dev_id)
{
struct IsdnCardState *cs = dev_id;
u_char val, s1val, s0val;
u_long flags;
spin_lock_irqsave(&cs->lock, flags);
s1val = bytein(cs->hw.njet.base + NETJET_IRQSTAT1);
if (!(s1val & NETJET_ISACIRQ)) {
val = NETjet_ReadIC(cs, ISAC_ISTA);
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "tiger: i1 %x %x", s1val, val);
if (val) {
isac_interrupt(cs, val);
NETjet_WriteIC(cs, ISAC_MASK, 0xFF);
NETjet_WriteIC(cs, ISAC_MASK, 0x0);
}
s1val = 1;
} else
s1val = 0;
/*
* read/write stat0 is better, because lower IRQ rate
* Note the IRQ is on for 125 us if a condition match
* thats long on modern CPU and so the IRQ is reentered
* all the time.
*/
s0val = bytein(cs->hw.njet.base + NETJET_IRQSTAT0);
if ((s0val | s1val) == 0) { // shared IRQ
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_NONE;
}
if (s0val)
byteout(cs->hw.njet.base + NETJET_IRQSTAT0, s0val);
/* start new code 13/07/00 GE */
/* set bits in sval to indicate which page is free */
if (inl(cs->hw.njet.base + NETJET_DMA_WRITE_ADR) <
inl(cs->hw.njet.base + NETJET_DMA_WRITE_IRQ))
/* the 2nd write page is free */
s0val = 0x08;
else /* the 1st write page is free */
s0val = 0x04;
if (inl(cs->hw.njet.base + NETJET_DMA_READ_ADR) <
inl(cs->hw.njet.base + NETJET_DMA_READ_IRQ))
/* the 2nd read page is free */
s0val |= 0x02;
else /* the 1st read page is free */
s0val |= 0x01;
if (s0val != cs->hw.njet.last_is0) /* we have a DMA interrupt */
{
if (test_and_set_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags)) {
printk(KERN_WARNING "nj LOCK_ATOMIC s0val %x->%x\n",
cs->hw.njet.last_is0, s0val);
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_HANDLED;
}
cs->hw.njet.irqstat0 = s0val;
if ((cs->hw.njet.irqstat0 & NETJET_IRQM0_READ) !=
(cs->hw.njet.last_is0 & NETJET_IRQM0_READ))
/* we have a read dma int */
read_tiger(cs);
if ((cs->hw.njet.irqstat0 & NETJET_IRQM0_WRITE) !=
(cs->hw.njet.last_is0 & NETJET_IRQM0_WRITE))
/* we have a write dma int */
write_tiger(cs);
/* end new code 13/07/00 GE */
test_and_clear_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags);
}
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_HANDLED;
}
static void
reset_netjet_s(struct IsdnCardState *cs)
{
cs->hw.njet.ctrl_reg = 0xff; /* Reset On */
byteout(cs->hw.njet.base + NETJET_CTRL, cs->hw.njet.ctrl_reg);
mdelay(10);
/* now edge triggered for TJ320 GE 13/07/00 */
/* see comment in IRQ function */
if (cs->subtyp) /* TJ320 */
cs->hw.njet.ctrl_reg = 0x40; /* Reset Off and status read clear */
else
cs->hw.njet.ctrl_reg = 0x00; /* Reset Off and status read clear */
byteout(cs->hw.njet.base + NETJET_CTRL, cs->hw.njet.ctrl_reg);
mdelay(10);
cs->hw.njet.auxd = 0;
cs->hw.njet.dmactrl = 0;
byteout(cs->hw.njet.base + NETJET_AUXCTRL, ~NETJET_ISACIRQ);
byteout(cs->hw.njet.base + NETJET_IRQMASK1, NETJET_ISACIRQ);
byteout(cs->hw.njet.auxa, cs->hw.njet.auxd);
}
static int
NETjet_S_card_msg(struct IsdnCardState *cs, int mt, void *arg)
{
u_long flags;
switch (mt) {
case CARD_RESET:
spin_lock_irqsave(&cs->lock, flags);
reset_netjet_s(cs);
spin_unlock_irqrestore(&cs->lock, flags);
return (0);
case CARD_RELEASE:
release_io_netjet(cs);
return (0);
case CARD_INIT:
reset_netjet_s(cs);
inittiger(cs);
spin_lock_irqsave(&cs->lock, flags);
clear_pending_isac_ints(cs);
initisac(cs);
/* Reenable all IRQ */
cs->writeisac(cs, ISAC_MASK, 0);
spin_unlock_irqrestore(&cs->lock, flags);
return (0);
case CARD_TEST:
return (0);
}
return (0);
}
static int njs_pci_probe(struct pci_dev *dev_netjet, struct IsdnCardState *cs)
{
u32 cfg;
if (pci_enable_device(dev_netjet))
return (0);
pci_set_master(dev_netjet);
cs->irq = dev_netjet->irq;
if (!cs->irq) {
printk(KERN_WARNING "NETjet-S: No IRQ for PCI card found\n");
return (0);
}
cs->hw.njet.base = pci_resource_start(dev_netjet, 0);
if (!cs->hw.njet.base) {
printk(KERN_WARNING "NETjet-S: No IO-Adr for PCI card found\n");
return (0);
}
/* the TJ300 and TJ320 must be detected, the IRQ handling is different
* unfortunately the chips use the same device ID, but the TJ320 has
* the bit20 in status PCI cfg register set
*/
pci_read_config_dword(dev_netjet, 0x04, &cfg);
if (cfg & 0x00100000)
cs->subtyp = 1; /* TJ320 */
else
cs->subtyp = 0; /* TJ300 */
/* 2001/10/04 Christoph Ersfeld, Formula-n Europe AG www.formula-n.com */
if ((dev_netjet->subsystem_vendor == 0x55) &&
(dev_netjet->subsystem_device == 0x02)) {
printk(KERN_WARNING "Netjet: You tried to load this driver with an incompatible TigerJet-card\n");
printk(KERN_WARNING "Use type=41 for Formula-n enter:now ISDN PCI and compatible\n");
return (0);
}
/* end new code */
return (1);
}
static int njs_cs_init(struct IsdnCard *card, struct IsdnCardState *cs)
{
cs->hw.njet.auxa = cs->hw.njet.base + NETJET_AUXDATA;
cs->hw.njet.isac = cs->hw.njet.base | NETJET_ISAC_OFF;
cs->hw.njet.ctrl_reg = 0xff; /* Reset On */
byteout(cs->hw.njet.base + NETJET_CTRL, cs->hw.njet.ctrl_reg);
mdelay(10);
cs->hw.njet.ctrl_reg = 0x00; /* Reset Off and status read clear */
byteout(cs->hw.njet.base + NETJET_CTRL, cs->hw.njet.ctrl_reg);
mdelay(10);
cs->hw.njet.auxd = 0xC0;
cs->hw.njet.dmactrl = 0;
byteout(cs->hw.njet.base + NETJET_AUXCTRL, ~NETJET_ISACIRQ);
byteout(cs->hw.njet.base + NETJET_IRQMASK1, NETJET_ISACIRQ);
byteout(cs->hw.njet.auxa, cs->hw.njet.auxd);
switch (((NETjet_ReadIC(cs, ISAC_RBCH) >> 5) & 3))
{
case 0:
return 1; /* end loop */
case 3:
printk(KERN_WARNING "NETjet-S: NETspider-U PCI card found\n");
return -1; /* continue looping */
default:
printk(KERN_WARNING "NETjet-S: No PCI card found\n");
return 0; /* end loop & function */
}
return 1; /* end loop */
}
static int njs_cs_init_rest(struct IsdnCard *card, struct IsdnCardState *cs)
{
const int bytecnt = 256;
printk(KERN_INFO
"NETjet-S: %s card configured at %#lx IRQ %d\n",
cs->subtyp ? "TJ320" : "TJ300", cs->hw.njet.base, cs->irq);
if (!request_region(cs->hw.njet.base, bytecnt, "netjet-s isdn")) {
printk(KERN_WARNING
"HiSax: NETjet-S config port %#lx-%#lx already in use\n",
cs->hw.njet.base,
cs->hw.njet.base + bytecnt);
return (0);
}
cs->readisac = &NETjet_ReadIC;
cs->writeisac = &NETjet_WriteIC;
cs->readisacfifo = &NETjet_ReadICfifo;
cs->writeisacfifo = &NETjet_WriteICfifo;
cs->BC_Read_Reg = &dummyrr;
cs->BC_Write_Reg = &dummywr;
cs->BC_Send_Data = &netjet_fill_dma;
setup_isac(cs);
cs->cardmsg = &NETjet_S_card_msg;
cs->irq_func = &netjet_s_interrupt;
cs->irq_flags |= IRQF_SHARED;
ISACVersion(cs, "NETjet-S:");
return (1);
}
static struct pci_dev *dev_netjet = NULL;
int setup_netjet_s(struct IsdnCard *card)
{
int ret;
struct IsdnCardState *cs = card->cs;
char tmp[64];
#ifdef __BIG_ENDIAN
#error "not running on big endian machines now"
#endif
strcpy(tmp, NETjet_S_revision);
printk(KERN_INFO "HiSax: Traverse Tech. NETjet-S driver Rev. %s\n", HiSax_getrev(tmp));
if (cs->typ != ISDN_CTYPE_NETJET_S)
return (0);
test_and_clear_bit(FLG_LOCK_ATOMIC, &cs->HW_Flags);
for (;;)
{
if ((dev_netjet = hisax_find_pci_device(PCI_VENDOR_ID_TIGERJET,
PCI_DEVICE_ID_TIGERJET_300, dev_netjet))) {
ret = njs_pci_probe(dev_netjet, cs);
if (!ret)
return (0);
} else {
printk(KERN_WARNING "NETjet-S: No PCI card found\n");
return (0);
}
ret = njs_cs_init(card, cs);
if (!ret)
return (0);
if (ret > 0)
break;
/* otherwise, ret < 0, continue looping */
}
return njs_cs_init_rest(card, cs);
}
| gpl-2.0 |
FusionSP/android_kernel_samsung_klte | drivers/staging/rtl8712/rtl871x_xmit.c | 4808 | 31738 | /******************************************************************************
* rtl871x_xmit.c
*
* Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved.
* Linux device driver for RTL8192SU
*
* 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
*
* Modifications for inclusion into the Linux staging tree are
* Copyright(c) 2010 Larry Finger. All rights reserved.
*
* Contact information:
* WLAN FAE <wlanfae@realtek.com>
* Larry Finger <Larry.Finger@lwfinger.net>
*
******************************************************************************/
#define _RTL871X_XMIT_C_
#include "osdep_service.h"
#include "drv_types.h"
#include "rtl871x_byteorder.h"
#include "wifi.h"
#include "osdep_intf.h"
#include "usb_ops.h"
static const u8 P802_1H_OUI[P80211_OUI_LEN] = {0x00, 0x00, 0xf8};
static const u8 RFC1042_OUI[P80211_OUI_LEN] = {0x00, 0x00, 0x00};
static void init_hwxmits(struct hw_xmit *phwxmit, sint entry);
static void alloc_hwxmits(struct _adapter *padapter);
static void free_hwxmits(struct _adapter *padapter);
static void _init_txservq(struct tx_servq *ptxservq)
{
_init_listhead(&ptxservq->tx_pending);
_init_queue(&ptxservq->sta_pending);
ptxservq->qcnt = 0;
}
void _r8712_init_sta_xmit_priv(struct sta_xmit_priv *psta_xmitpriv)
{
memset((unsigned char *)psta_xmitpriv, 0,
sizeof(struct sta_xmit_priv));
spin_lock_init(&psta_xmitpriv->lock);
_init_txservq(&psta_xmitpriv->be_q);
_init_txservq(&psta_xmitpriv->bk_q);
_init_txservq(&psta_xmitpriv->vi_q);
_init_txservq(&psta_xmitpriv->vo_q);
_init_listhead(&psta_xmitpriv->legacy_dz);
_init_listhead(&psta_xmitpriv->apsd);
}
sint _r8712_init_xmit_priv(struct xmit_priv *pxmitpriv,
struct _adapter *padapter)
{
sint i;
struct xmit_buf *pxmitbuf;
struct xmit_frame *pxframe;
memset((unsigned char *)pxmitpriv, 0, sizeof(struct xmit_priv));
spin_lock_init(&pxmitpriv->lock);
/*
Please insert all the queue initializaiton using _init_queue below
*/
pxmitpriv->adapter = padapter;
_init_queue(&pxmitpriv->be_pending);
_init_queue(&pxmitpriv->bk_pending);
_init_queue(&pxmitpriv->vi_pending);
_init_queue(&pxmitpriv->vo_pending);
_init_queue(&pxmitpriv->bm_pending);
_init_queue(&pxmitpriv->legacy_dz_queue);
_init_queue(&pxmitpriv->apsd_queue);
_init_queue(&pxmitpriv->free_xmit_queue);
/*
Please allocate memory with the sz = (struct xmit_frame) * NR_XMITFRAME,
and initialize free_xmit_frame below.
Please also apply free_txobj to link_up all the xmit_frames...
*/
pxmitpriv->pallocated_frame_buf = _malloc(NR_XMITFRAME *
sizeof(struct xmit_frame) + 4);
if (pxmitpriv->pallocated_frame_buf == NULL) {
pxmitpriv->pxmit_frame_buf = NULL;
return _FAIL;
}
pxmitpriv->pxmit_frame_buf = pxmitpriv->pallocated_frame_buf + 4 -
((addr_t) (pxmitpriv->pallocated_frame_buf) & 3);
pxframe = (struct xmit_frame *) pxmitpriv->pxmit_frame_buf;
for (i = 0; i < NR_XMITFRAME; i++) {
_init_listhead(&(pxframe->list));
pxframe->padapter = padapter;
pxframe->frame_tag = DATA_FRAMETAG;
pxframe->pkt = NULL;
pxframe->buf_addr = NULL;
pxframe->pxmitbuf = NULL;
list_insert_tail(&(pxframe->list),
&(pxmitpriv->free_xmit_queue.queue));
pxframe++;
}
pxmitpriv->free_xmitframe_cnt = NR_XMITFRAME;
/*
init xmit hw_txqueue
*/
_r8712_init_hw_txqueue(&pxmitpriv->be_txqueue, BE_QUEUE_INX);
_r8712_init_hw_txqueue(&pxmitpriv->bk_txqueue, BK_QUEUE_INX);
_r8712_init_hw_txqueue(&pxmitpriv->vi_txqueue, VI_QUEUE_INX);
_r8712_init_hw_txqueue(&pxmitpriv->vo_txqueue, VO_QUEUE_INX);
_r8712_init_hw_txqueue(&pxmitpriv->bmc_txqueue, BMC_QUEUE_INX);
pxmitpriv->frag_len = MAX_FRAG_THRESHOLD;
pxmitpriv->txirp_cnt = 1;
/*per AC pending irp*/
pxmitpriv->beq_cnt = 0;
pxmitpriv->bkq_cnt = 0;
pxmitpriv->viq_cnt = 0;
pxmitpriv->voq_cnt = 0;
/*init xmit_buf*/
_init_queue(&pxmitpriv->free_xmitbuf_queue);
_init_queue(&pxmitpriv->pending_xmitbuf_queue);
pxmitpriv->pallocated_xmitbuf = _malloc(NR_XMITBUFF *
sizeof(struct xmit_buf) + 4);
if (pxmitpriv->pallocated_xmitbuf == NULL)
return _FAIL;
pxmitpriv->pxmitbuf = pxmitpriv->pallocated_xmitbuf + 4 -
((addr_t)(pxmitpriv->pallocated_xmitbuf) & 3);
pxmitbuf = (struct xmit_buf *)pxmitpriv->pxmitbuf;
for (i = 0; i < NR_XMITBUFF; i++) {
_init_listhead(&pxmitbuf->list);
pxmitbuf->pallocated_buf = _malloc(MAX_XMITBUF_SZ +
XMITBUF_ALIGN_SZ);
if (pxmitbuf->pallocated_buf == NULL)
return _FAIL;
pxmitbuf->pbuf = pxmitbuf->pallocated_buf + XMITBUF_ALIGN_SZ -
((addr_t) (pxmitbuf->pallocated_buf) &
(XMITBUF_ALIGN_SZ - 1));
r8712_xmit_resource_alloc(padapter, pxmitbuf);
list_insert_tail(&pxmitbuf->list,
&(pxmitpriv->free_xmitbuf_queue.queue));
pxmitbuf++;
}
pxmitpriv->free_xmitbuf_cnt = NR_XMITBUFF;
_init_workitem(&padapter->wkFilterRxFF0, r8712_SetFilter, padapter);
alloc_hwxmits(padapter);
init_hwxmits(pxmitpriv->hwxmits, pxmitpriv->hwxmit_entry);
tasklet_init(&pxmitpriv->xmit_tasklet,
(void(*)(unsigned long))r8712_xmit_bh,
(unsigned long)padapter);
return _SUCCESS;
}
void _free_xmit_priv(struct xmit_priv *pxmitpriv)
{
int i;
struct _adapter *padapter = pxmitpriv->adapter;
struct xmit_frame *pxmitframe = (struct xmit_frame *)
pxmitpriv->pxmit_frame_buf;
struct xmit_buf *pxmitbuf = (struct xmit_buf *)pxmitpriv->pxmitbuf;
if (pxmitpriv->pxmit_frame_buf == NULL)
return;
for (i = 0; i < NR_XMITFRAME; i++) {
r8712_xmit_complete(padapter, pxmitframe);
pxmitframe++;
}
for (i = 0; i < NR_XMITBUFF; i++) {
r8712_xmit_resource_free(padapter, pxmitbuf);
kfree(pxmitbuf->pallocated_buf);
pxmitbuf++;
}
kfree(pxmitpriv->pallocated_frame_buf);
kfree(pxmitpriv->pallocated_xmitbuf);
free_hwxmits(padapter);
}
sint r8712_update_attrib(struct _adapter *padapter, _pkt *pkt,
struct pkt_attrib *pattrib)
{
uint i;
struct pkt_file pktfile;
struct sta_info *psta = NULL;
struct ethhdr etherhdr;
struct tx_cmd txdesc;
sint bmcast;
struct sta_priv *pstapriv = &padapter->stapriv;
struct security_priv *psecuritypriv = &padapter->securitypriv;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct qos_priv *pqospriv = &pmlmepriv->qospriv;
_r8712_open_pktfile(pkt, &pktfile);
i = _r8712_pktfile_read(&pktfile, (unsigned char *)ðerhdr, ETH_HLEN);
pattrib->ether_type = ntohs(etherhdr.h_proto);
{
u8 bool;
/*If driver xmit ARP packet, driver can set ps mode to initial
* setting. It stands for getting DHCP or fix IP.*/
if (pattrib->ether_type == 0x0806) {
if (padapter->pwrctrlpriv.pwr_mode !=
padapter->registrypriv.power_mgnt) {
_cancel_timer(&(pmlmepriv->dhcp_timer), &bool);
r8712_set_ps_mode(padapter, padapter->registrypriv.
power_mgnt, padapter->registrypriv.smart_ps);
}
}
}
memcpy(pattrib->dst, ðerhdr.h_dest, ETH_ALEN);
memcpy(pattrib->src, ðerhdr.h_source, ETH_ALEN);
pattrib->pctrl = 0;
if ((check_fwstate(pmlmepriv, WIFI_ADHOC_STATE) == true) ||
(check_fwstate(pmlmepriv, WIFI_ADHOC_MASTER_STATE) == true)) {
memcpy(pattrib->ra, pattrib->dst, ETH_ALEN);
memcpy(pattrib->ta, pattrib->src, ETH_ALEN);
} else if (check_fwstate(pmlmepriv, WIFI_STATION_STATE)) {
memcpy(pattrib->ra, get_bssid(pmlmepriv), ETH_ALEN);
memcpy(pattrib->ta, pattrib->src, ETH_ALEN);
} else if (check_fwstate(pmlmepriv, WIFI_AP_STATE)) {
memcpy(pattrib->ra, pattrib->dst, ETH_ALEN);
memcpy(pattrib->ta, get_bssid(pmlmepriv), ETH_ALEN);
} else if (check_fwstate(pmlmepriv, WIFI_MP_STATE) == true) {
/*firstly, filter packet not belongs to mp*/
if (pattrib->ether_type != 0x8712)
return _FAIL;
/* for mp storing the txcmd per packet,
* according to the info of txcmd to update pattrib */
/*get MP_TXDESC_SIZE bytes txcmd per packet*/
i = _r8712_pktfile_read(&pktfile, (u8 *)&txdesc, TXDESC_SIZE);
memcpy(pattrib->ra, pattrib->dst, ETH_ALEN);
memcpy(pattrib->ta, pattrib->src, ETH_ALEN);
pattrib->pctrl = 1;
}
/* r8712_xmitframe_coalesce() overwrite this!*/
pattrib->pktlen = pktfile.pkt_len;
if (ETH_P_IP == pattrib->ether_type) {
/* The following is for DHCP and ARP packet, we use cck1M to
* tx these packets and let LPS awake some time
* to prevent DHCP protocol fail */
u8 tmp[24];
_r8712_pktfile_read(&pktfile, &tmp[0], 24);
pattrib->dhcp_pkt = 0;
if (pktfile.pkt_len > 282) {/*MINIMUM_DHCP_PACKET_SIZE)*/
if (ETH_P_IP == pattrib->ether_type) {/* IP header*/
if (((tmp[21] == 68) && (tmp[23] == 67)) ||
((tmp[21] == 67) && (tmp[23] == 68))) {
/* 68 : UDP BOOTP client
* 67 : UDP BOOTP server
* Use low rate to send DHCP packet.*/
pattrib->dhcp_pkt = 1;
}
}
}
}
bmcast = IS_MCAST(pattrib->ra);
/* get sta_info*/
if (bmcast) {
psta = r8712_get_bcmc_stainfo(padapter);
pattrib->mac_id = 4;
} else {
if (check_fwstate(pmlmepriv, WIFI_MP_STATE) == true) {
psta = r8712_get_stainfo(pstapriv,
get_bssid(pmlmepriv));
pattrib->mac_id = 5;
} else {
psta = r8712_get_stainfo(pstapriv, pattrib->ra);
if (psta == NULL) /* drop the pkt */
return _FAIL;
if (check_fwstate(pmlmepriv, WIFI_STATION_STATE))
pattrib->mac_id = 5;
else
pattrib->mac_id = psta->mac_id;
}
}
if (psta) {
pattrib->psta = psta;
} else {
/* if we cannot get psta => drrp the pkt */
return _FAIL;
}
pattrib->ack_policy = 0;
/* get ether_hdr_len */
pattrib->pkt_hdrlen = ETH_HLEN;
if (pqospriv->qos_option)
r8712_set_qos(&pktfile, pattrib);
else {
pattrib->hdrlen = WLAN_HDR_A3_LEN;
pattrib->subtype = WIFI_DATA_TYPE;
pattrib->priority = 0;
}
if (psta->ieee8021x_blocked == true) {
pattrib->encrypt = 0;
if ((pattrib->ether_type != 0x888e) &&
(check_fwstate(pmlmepriv, WIFI_MP_STATE) == false))
return _FAIL;
} else
GET_ENCRY_ALGO(psecuritypriv, psta, pattrib->encrypt, bmcast);
switch (pattrib->encrypt) {
case _WEP40_:
case _WEP104_:
pattrib->iv_len = 4;
pattrib->icv_len = 4;
break;
case _TKIP_:
pattrib->iv_len = 8;
pattrib->icv_len = 4;
if (padapter->securitypriv.busetkipkey == _FAIL)
return _FAIL;
break;
case _AES_:
pattrib->iv_len = 8;
pattrib->icv_len = 8;
break;
default:
pattrib->iv_len = 0;
pattrib->icv_len = 0;
break;
}
if (pattrib->encrypt &&
((padapter->securitypriv.sw_encrypt == true) ||
(psecuritypriv->hw_decrypted == false)))
pattrib->bswenc = true;
else
pattrib->bswenc = false;
/* if in MP_STATE, update pkt_attrib from mp_txcmd, and overwrite
* some settings above.*/
if (check_fwstate(pmlmepriv, WIFI_MP_STATE) == true)
pattrib->priority = (txdesc.txdw1 >> QSEL_SHT) & 0x1f;
return _SUCCESS;
}
static sint xmitframe_addmic(struct _adapter *padapter,
struct xmit_frame *pxmitframe)
{
u32 curfragnum, length, datalen;
u8 *pframe, *payload, mic[8];
struct mic_data micdata;
struct sta_info *stainfo;
struct qos_priv *pqospriv = &(padapter->mlmepriv.qospriv);
struct pkt_attrib *pattrib = &pxmitframe->attrib;
struct security_priv *psecuritypriv = &padapter->securitypriv;
struct xmit_priv *pxmitpriv = &padapter->xmitpriv;
u8 priority[4] = {0x0, 0x0, 0x0, 0x0};
sint bmcst = IS_MCAST(pattrib->ra);
if (pattrib->psta)
stainfo = pattrib->psta;
else
stainfo = r8712_get_stainfo(&padapter->stapriv,
&pattrib->ra[0]);
if (pattrib->encrypt == _TKIP_) {
/*encode mic code*/
if (stainfo != NULL) {
u8 null_key[16] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0};
datalen = pattrib->pktlen - pattrib->hdrlen;
pframe = pxmitframe->buf_addr + TXDESC_OFFSET;
if (bmcst) {
if (!memcmp(psecuritypriv->XGrptxmickey
[psecuritypriv->XGrpKeyid].skey,
null_key, 16))
return _FAIL;
/*start to calculate the mic code*/
r8712_secmicsetkey(&micdata,
psecuritypriv->
XGrptxmickey[psecuritypriv->
XGrpKeyid].skey);
} else {
if (!memcmp(&stainfo->tkiptxmickey.skey[0],
null_key, 16))
return _FAIL;
/* start to calculate the mic code */
r8712_secmicsetkey(&micdata,
&stainfo->tkiptxmickey.skey[0]);
}
if (pframe[1] & 1) { /* ToDS==1 */
r8712_secmicappend(&micdata,
&pframe[16], 6); /*DA*/
if (pframe[1]&2) /* From Ds==1 */
r8712_secmicappend(&micdata,
&pframe[24], 6);
else
r8712_secmicappend(&micdata,
&pframe[10], 6);
} else { /* ToDS==0 */
r8712_secmicappend(&micdata,
&pframe[4], 6); /* DA */
if (pframe[1]&2) /* From Ds==1 */
r8712_secmicappend(&micdata,
&pframe[16], 6);
else
r8712_secmicappend(&micdata,
&pframe[10], 6);
}
if (pqospriv->qos_option == 1)
priority[0] = (u8)pxmitframe->
attrib.priority;
r8712_secmicappend(&micdata, &priority[0], 4);
payload = pframe;
for (curfragnum = 0; curfragnum < pattrib->nr_frags;
curfragnum++) {
payload = (u8 *)RND4((addr_t)(payload));
payload = payload+pattrib->
hdrlen+pattrib->iv_len;
if ((curfragnum + 1) == pattrib->nr_frags) {
length = pattrib->last_txcmdsz -
pattrib->hdrlen -
pattrib->iv_len -
((psecuritypriv->sw_encrypt)
? pattrib->icv_len : 0);
r8712_secmicappend(&micdata, payload,
length);
payload = payload+length;
} else{
length = pxmitpriv->frag_len -
pattrib->hdrlen-pattrib->iv_len -
((psecuritypriv->sw_encrypt) ?
pattrib->icv_len : 0);
r8712_secmicappend(&micdata, payload,
length);
payload = payload + length +
pattrib->icv_len;
}
}
r8712_secgetmic(&micdata, &(mic[0]));
/* add mic code and add the mic code length in
* last_txcmdsz */
memcpy(payload, &(mic[0]), 8);
pattrib->last_txcmdsz += 8;
payload = payload-pattrib->last_txcmdsz + 8;
}
}
return _SUCCESS;
}
static sint xmitframe_swencrypt(struct _adapter *padapter,
struct xmit_frame *pxmitframe)
{
struct pkt_attrib *pattrib = &pxmitframe->attrib;
if (pattrib->bswenc) {
switch (pattrib->encrypt) {
case _WEP40_:
case _WEP104_:
r8712_wep_encrypt(padapter, (u8 *)pxmitframe);
break;
case _TKIP_:
r8712_tkip_encrypt(padapter, (u8 *)pxmitframe);
break;
case _AES_:
r8712_aes_encrypt(padapter, (u8 *)pxmitframe);
break;
default:
break;
}
}
return _SUCCESS;
}
static sint make_wlanhdr(struct _adapter *padapter , u8 *hdr,
struct pkt_attrib *pattrib)
{
u16 *qc;
struct ieee80211_hdr *pwlanhdr = (struct ieee80211_hdr *)hdr;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct qos_priv *pqospriv = &pmlmepriv->qospriv;
u16 *fctrl = &pwlanhdr->frame_ctl;
memset(hdr, 0, WLANHDR_OFFSET);
SetFrameSubType(fctrl, pattrib->subtype);
if (pattrib->subtype & WIFI_DATA_TYPE) {
if ((check_fwstate(pmlmepriv, WIFI_STATION_STATE) == true)) {
/* to_ds = 1, fr_ds = 0; */
SetToDs(fctrl);
memcpy(pwlanhdr->addr1, get_bssid(pmlmepriv),
ETH_ALEN);
memcpy(pwlanhdr->addr2, pattrib->src, ETH_ALEN);
memcpy(pwlanhdr->addr3, pattrib->dst, ETH_ALEN);
} else if ((check_fwstate(pmlmepriv, WIFI_AP_STATE) == true)) {
/* to_ds = 0, fr_ds = 1; */
SetFrDs(fctrl);
memcpy(pwlanhdr->addr1, pattrib->dst, ETH_ALEN);
memcpy(pwlanhdr->addr2, get_bssid(pmlmepriv),
ETH_ALEN);
memcpy(pwlanhdr->addr3, pattrib->src, ETH_ALEN);
} else if ((check_fwstate(pmlmepriv, WIFI_ADHOC_STATE) == true)
|| (check_fwstate(pmlmepriv, WIFI_ADHOC_MASTER_STATE)
== true)) {
memcpy(pwlanhdr->addr1, pattrib->dst, ETH_ALEN);
memcpy(pwlanhdr->addr2, pattrib->src, ETH_ALEN);
memcpy(pwlanhdr->addr3, get_bssid(pmlmepriv),
ETH_ALEN);
} else if (check_fwstate(pmlmepriv, WIFI_MP_STATE) == true) {
memcpy(pwlanhdr->addr1, pattrib->dst, ETH_ALEN);
memcpy(pwlanhdr->addr2, pattrib->src, ETH_ALEN);
memcpy(pwlanhdr->addr3, get_bssid(pmlmepriv),
ETH_ALEN);
} else
return _FAIL;
if (pattrib->encrypt)
SetPrivacy(fctrl);
if (pqospriv->qos_option) {
qc = (unsigned short *)(hdr + pattrib->hdrlen - 2);
if (pattrib->priority)
SetPriority(qc, pattrib->priority);
SetAckpolicy(qc, pattrib->ack_policy);
}
/* TODO: fill HT Control Field */
/* Update Seq Num will be handled by f/w */
{
struct sta_info *psta;
sint bmcst = IS_MCAST(pattrib->ra);
if (pattrib->psta)
psta = pattrib->psta;
else {
if (bmcst)
psta = r8712_get_bcmc_stainfo(padapter);
else
psta =
r8712_get_stainfo(&padapter->stapriv,
pattrib->ra);
}
if (psta) {
psta->sta_xmitpriv.txseq_tid
[pattrib->priority]++;
psta->sta_xmitpriv.txseq_tid[pattrib->priority]
&= 0xFFF;
pattrib->seqnum = psta->sta_xmitpriv.
txseq_tid[pattrib->priority];
SetSeqNum(hdr, pattrib->seqnum);
}
}
}
return _SUCCESS;
}
static sint r8712_put_snap(u8 *data, u16 h_proto)
{
struct ieee80211_snap_hdr *snap;
const u8 *oui;
snap = (struct ieee80211_snap_hdr *)data;
snap->dsap = 0xaa;
snap->ssap = 0xaa;
snap->ctrl = 0x03;
if (h_proto == 0x8137 || h_proto == 0x80f3)
oui = P802_1H_OUI;
else
oui = RFC1042_OUI;
snap->oui[0] = oui[0];
snap->oui[1] = oui[1];
snap->oui[2] = oui[2];
*(u16 *)(data + SNAP_SIZE) = htons(h_proto);
return SNAP_SIZE + sizeof(u16);
}
/*
* This sub-routine will perform all the following:
* 1. remove 802.3 header.
* 2. create wlan_header, based on the info in pxmitframe
* 3. append sta's iv/ext-iv
* 4. append LLC
* 5. move frag chunk from pframe to pxmitframe->mem
* 6. apply sw-encrypt, if necessary.
*/
sint r8712_xmitframe_coalesce(struct _adapter *padapter, _pkt *pkt,
struct xmit_frame *pxmitframe)
{
struct pkt_file pktfile;
sint frg_len, mpdu_len, llc_sz;
u32 mem_sz;
u8 frg_inx;
addr_t addr;
u8 *pframe, *mem_start, *ptxdesc;
struct sta_info *psta;
struct security_priv *psecuritypriv = &padapter->securitypriv;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct xmit_priv *pxmitpriv = &padapter->xmitpriv;
struct pkt_attrib *pattrib = &pxmitframe->attrib;
u8 *pbuf_start;
sint bmcst = IS_MCAST(pattrib->ra);
if (pattrib->psta == NULL)
return _FAIL;
psta = pattrib->psta;
if (pxmitframe->buf_addr == NULL)
return _FAIL;
pbuf_start = pxmitframe->buf_addr;
ptxdesc = pbuf_start;
mem_start = pbuf_start + TXDESC_OFFSET;
if (make_wlanhdr(padapter, mem_start, pattrib) == _FAIL)
return _FAIL;
_r8712_open_pktfile(pkt, &pktfile);
_r8712_pktfile_read(&pktfile, NULL, (uint) pattrib->pkt_hdrlen);
if (check_fwstate(pmlmepriv, WIFI_MP_STATE) == true) {
/* truncate TXDESC_SIZE bytes txcmd if at mp mode for 871x */
if (pattrib->ether_type == 0x8712) {
/* take care - update_txdesc overwrite this */
_r8712_pktfile_read(&pktfile, ptxdesc, TXDESC_SIZE);
}
}
pattrib->pktlen = pktfile.pkt_len;
frg_inx = 0;
frg_len = pxmitpriv->frag_len - 4;
while (1) {
llc_sz = 0;
mpdu_len = frg_len;
pframe = mem_start;
SetMFrag(mem_start);
pframe += pattrib->hdrlen;
mpdu_len -= pattrib->hdrlen;
/* adding icv, if necessary...*/
if (pattrib->iv_len) {
if (psta != NULL) {
switch (pattrib->encrypt) {
case _WEP40_:
case _WEP104_:
WEP_IV(pattrib->iv, psta->txpn,
(u8)psecuritypriv->
PrivacyKeyIndex);
break;
case _TKIP_:
if (bmcst)
TKIP_IV(pattrib->iv,
psta->txpn,
(u8)psecuritypriv->
XGrpKeyid);
else
TKIP_IV(pattrib->iv, psta->txpn,
0);
break;
case _AES_:
if (bmcst)
AES_IV(pattrib->iv, psta->txpn,
(u8)psecuritypriv->
XGrpKeyid);
else
AES_IV(pattrib->iv, psta->txpn,
0);
break;
}
}
memcpy(pframe, pattrib->iv, pattrib->iv_len);
pframe += pattrib->iv_len;
mpdu_len -= pattrib->iv_len;
}
if (frg_inx == 0) {
llc_sz = r8712_put_snap(pframe, pattrib->ether_type);
pframe += llc_sz;
mpdu_len -= llc_sz;
}
if ((pattrib->icv_len > 0) && (pattrib->bswenc))
mpdu_len -= pattrib->icv_len;
if (bmcst)
mem_sz = _r8712_pktfile_read(&pktfile, pframe,
pattrib->pktlen);
else
mem_sz = _r8712_pktfile_read(&pktfile, pframe,
mpdu_len);
pframe += mem_sz;
if ((pattrib->icv_len > 0) && (pattrib->bswenc)) {
memcpy(pframe, pattrib->icv, pattrib->icv_len);
pframe += pattrib->icv_len;
}
frg_inx++;
if (bmcst || (r8712_endofpktfile(&pktfile) == true)) {
pattrib->nr_frags = frg_inx;
pattrib->last_txcmdsz = pattrib->hdrlen +
pattrib->iv_len +
((pattrib->nr_frags == 1) ?
llc_sz : 0) +
((pattrib->bswenc) ?
pattrib->icv_len : 0) + mem_sz;
ClearMFrag(mem_start);
break;
}
addr = (addr_t)(pframe);
mem_start = (unsigned char *)RND4(addr) + TXDESC_OFFSET;
memcpy(mem_start, pbuf_start + TXDESC_OFFSET, pattrib->hdrlen);
}
if (xmitframe_addmic(padapter, pxmitframe) == _FAIL)
return _FAIL;
xmitframe_swencrypt(padapter, pxmitframe);
return _SUCCESS;
}
void r8712_update_protection(struct _adapter *padapter, u8 *ie, uint ie_len)
{
uint protection;
u8 *perp;
sint erp_len;
struct xmit_priv *pxmitpriv = &padapter->xmitpriv;
struct registry_priv *pregistrypriv = &padapter->registrypriv;
switch (pxmitpriv->vcs_setting) {
case DISABLE_VCS:
pxmitpriv->vcs = NONE_VCS;
break;
case ENABLE_VCS:
break;
case AUTO_VCS:
default:
perp = r8712_get_ie(ie, _ERPINFO_IE_, &erp_len, ie_len);
if (perp == NULL)
pxmitpriv->vcs = NONE_VCS;
else {
protection = (*(perp + 2)) & BIT(1);
if (protection) {
if (pregistrypriv->vcs_type == RTS_CTS)
pxmitpriv->vcs = RTS_CTS;
else
pxmitpriv->vcs = CTS_TO_SELF;
} else
pxmitpriv->vcs = NONE_VCS;
}
break;
}
}
struct xmit_buf *r8712_alloc_xmitbuf(struct xmit_priv *pxmitpriv)
{
unsigned long irqL;
struct xmit_buf *pxmitbuf = NULL;
struct list_head *plist, *phead;
struct __queue *pfree_xmitbuf_queue = &pxmitpriv->free_xmitbuf_queue;
spin_lock_irqsave(&pfree_xmitbuf_queue->lock, irqL);
if (_queue_empty(pfree_xmitbuf_queue) == true)
pxmitbuf = NULL;
else {
phead = get_list_head(pfree_xmitbuf_queue);
plist = get_next(phead);
pxmitbuf = LIST_CONTAINOR(plist, struct xmit_buf, list);
list_delete(&(pxmitbuf->list));
}
if (pxmitbuf != NULL)
pxmitpriv->free_xmitbuf_cnt--;
spin_unlock_irqrestore(&pfree_xmitbuf_queue->lock, irqL);
return pxmitbuf;
}
int r8712_free_xmitbuf(struct xmit_priv *pxmitpriv, struct xmit_buf *pxmitbuf)
{
unsigned long irqL;
struct __queue *pfree_xmitbuf_queue = &pxmitpriv->free_xmitbuf_queue;
if (pxmitbuf == NULL)
return _FAIL;
spin_lock_irqsave(&pfree_xmitbuf_queue->lock, irqL);
list_delete(&pxmitbuf->list);
list_insert_tail(&(pxmitbuf->list), get_list_head(pfree_xmitbuf_queue));
pxmitpriv->free_xmitbuf_cnt++;
spin_unlock_irqrestore(&pfree_xmitbuf_queue->lock, irqL);
return _SUCCESS;
}
/*
Calling context:
1. OS_TXENTRY
2. RXENTRY (rx_thread or RX_ISR/RX_CallBack)
If we turn on USE_RXTHREAD, then, no need for critical section.
Otherwise, we must use _enter/_exit critical to protect free_xmit_queue...
Must be very very cautious...
*/
struct xmit_frame *r8712_alloc_xmitframe(struct xmit_priv *pxmitpriv)
{
/*
Please remember to use all the osdep_service api,
and lock/unlock or _enter/_exit critical to protect
pfree_xmit_queue
*/
unsigned long irqL;
struct xmit_frame *pxframe = NULL;
struct list_head *plist, *phead;
struct __queue *pfree_xmit_queue = &pxmitpriv->free_xmit_queue;
spin_lock_irqsave(&pfree_xmit_queue->lock, irqL);
if (_queue_empty(pfree_xmit_queue) == true)
pxframe = NULL;
else {
phead = get_list_head(pfree_xmit_queue);
plist = get_next(phead);
pxframe = LIST_CONTAINOR(plist, struct xmit_frame, list);
list_delete(&(pxframe->list));
}
if (pxframe != NULL) {
pxmitpriv->free_xmitframe_cnt--;
pxframe->buf_addr = NULL;
pxframe->pxmitbuf = NULL;
pxframe->attrib.psta = NULL;
pxframe->pkt = NULL;
}
spin_unlock_irqrestore(&pfree_xmit_queue->lock, irqL);
return pxframe;
}
void r8712_free_xmitframe(struct xmit_priv *pxmitpriv,
struct xmit_frame *pxmitframe)
{
unsigned long irqL;
struct __queue *pfree_xmit_queue = &pxmitpriv->free_xmit_queue;
struct _adapter *padapter = pxmitpriv->adapter;
struct sk_buff *pndis_pkt = NULL;
if (pxmitframe == NULL)
return;
spin_lock_irqsave(&pfree_xmit_queue->lock, irqL);
list_delete(&pxmitframe->list);
if (pxmitframe->pkt) {
pndis_pkt = pxmitframe->pkt;
pxmitframe->pkt = NULL;
}
list_insert_tail(&pxmitframe->list, get_list_head(pfree_xmit_queue));
pxmitpriv->free_xmitframe_cnt++;
spin_unlock_irqrestore(&pfree_xmit_queue->lock, irqL);
if (netif_queue_stopped(padapter->pnetdev))
netif_wake_queue(padapter->pnetdev);
}
void r8712_free_xmitframe_ex(struct xmit_priv *pxmitpriv,
struct xmit_frame *pxmitframe)
{
if (pxmitframe == NULL)
return;
if (pxmitframe->frame_tag == DATA_FRAMETAG)
r8712_free_xmitframe(pxmitpriv, pxmitframe);
}
void r8712_free_xmitframe_queue(struct xmit_priv *pxmitpriv,
struct __queue *pframequeue)
{
unsigned long irqL;
struct list_head *plist, *phead;
struct xmit_frame *pxmitframe;
spin_lock_irqsave(&(pframequeue->lock), irqL);
phead = get_list_head(pframequeue);
plist = get_next(phead);
while (end_of_queue_search(phead, plist) == false) {
pxmitframe = LIST_CONTAINOR(plist, struct xmit_frame, list);
plist = get_next(plist);
r8712_free_xmitframe(pxmitpriv, pxmitframe);
}
spin_unlock_irqrestore(&(pframequeue->lock), irqL);
}
static inline struct tx_servq *get_sta_pending(struct _adapter *padapter,
struct __queue **ppstapending,
struct sta_info *psta, sint up)
{
struct tx_servq *ptxservq;
struct hw_xmit *phwxmits = padapter->xmitpriv.hwxmits;
switch (up) {
case 1:
case 2:
ptxservq = &(psta->sta_xmitpriv.bk_q);
*ppstapending = &padapter->xmitpriv.bk_pending;
(phwxmits+3)->accnt++;
break;
case 4:
case 5:
ptxservq = &(psta->sta_xmitpriv.vi_q);
*ppstapending = &padapter->xmitpriv.vi_pending;
(phwxmits+1)->accnt++;
break;
case 6:
case 7:
ptxservq = &(psta->sta_xmitpriv.vo_q);
*ppstapending = &padapter->xmitpriv.vo_pending;
(phwxmits+0)->accnt++;
break;
case 0:
case 3:
default:
ptxservq = &(psta->sta_xmitpriv.be_q);
*ppstapending = &padapter->xmitpriv.be_pending;
(phwxmits + 2)->accnt++;
break;
}
return ptxservq;
}
/*
* Will enqueue pxmitframe to the proper queue, and indicate it
* to xx_pending list.....
*/
sint r8712_xmit_classifier(struct _adapter *padapter,
struct xmit_frame *pxmitframe)
{
unsigned long irqL0;
struct __queue *pstapending;
struct sta_info *psta;
struct tx_servq *ptxservq;
struct pkt_attrib *pattrib = &pxmitframe->attrib;
struct sta_priv *pstapriv = &padapter->stapriv;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
sint bmcst = IS_MCAST(pattrib->ra);
if (pattrib->psta)
psta = pattrib->psta;
else {
if (bmcst)
psta = r8712_get_bcmc_stainfo(padapter);
else {
if (check_fwstate(pmlmepriv, WIFI_MP_STATE) == true)
psta = r8712_get_stainfo(pstapriv,
get_bssid(pmlmepriv));
else
psta = r8712_get_stainfo(pstapriv, pattrib->ra);
}
}
if (psta == NULL)
return _FAIL;
ptxservq = get_sta_pending(padapter, &pstapending,
psta, pattrib->priority);
spin_lock_irqsave(&pstapending->lock, irqL0);
if (is_list_empty(&ptxservq->tx_pending))
list_insert_tail(&ptxservq->tx_pending,
get_list_head(pstapending));
list_insert_tail(&pxmitframe->list,
get_list_head(&ptxservq->sta_pending));
ptxservq->qcnt++;
spin_unlock_irqrestore(&pstapending->lock, irqL0);
return _SUCCESS;
}
static void alloc_hwxmits(struct _adapter *padapter)
{
struct hw_xmit *hwxmits;
struct xmit_priv *pxmitpriv = &padapter->xmitpriv;
pxmitpriv->hwxmit_entry = HWXMIT_ENTRY;
pxmitpriv->hwxmits = (struct hw_xmit *)_malloc(sizeof(struct hw_xmit) *
pxmitpriv->hwxmit_entry);
if (pxmitpriv->hwxmits == NULL)
return;
hwxmits = pxmitpriv->hwxmits;
if (pxmitpriv->hwxmit_entry == 5) {
pxmitpriv->bmc_txqueue.head = 0;
hwxmits[0] .phwtxqueue = &pxmitpriv->bmc_txqueue;
hwxmits[0] .sta_queue = &pxmitpriv->bm_pending;
pxmitpriv->vo_txqueue.head = 0;
hwxmits[1] .phwtxqueue = &pxmitpriv->vo_txqueue;
hwxmits[1] .sta_queue = &pxmitpriv->vo_pending;
pxmitpriv->vi_txqueue.head = 0;
hwxmits[2] .phwtxqueue = &pxmitpriv->vi_txqueue;
hwxmits[2] .sta_queue = &pxmitpriv->vi_pending;
pxmitpriv->bk_txqueue.head = 0;
hwxmits[3] .phwtxqueue = &pxmitpriv->bk_txqueue;
hwxmits[3] .sta_queue = &pxmitpriv->bk_pending;
pxmitpriv->be_txqueue.head = 0;
hwxmits[4] .phwtxqueue = &pxmitpriv->be_txqueue;
hwxmits[4] .sta_queue = &pxmitpriv->be_pending;
} else if (pxmitpriv->hwxmit_entry == 4) {
pxmitpriv->vo_txqueue.head = 0;
hwxmits[0] .phwtxqueue = &pxmitpriv->vo_txqueue;
hwxmits[0] .sta_queue = &pxmitpriv->vo_pending;
pxmitpriv->vi_txqueue.head = 0;
hwxmits[1] .phwtxqueue = &pxmitpriv->vi_txqueue;
hwxmits[1] .sta_queue = &pxmitpriv->vi_pending;
pxmitpriv->be_txqueue.head = 0;
hwxmits[2] .phwtxqueue = &pxmitpriv->be_txqueue;
hwxmits[2] .sta_queue = &pxmitpriv->be_pending;
pxmitpriv->bk_txqueue.head = 0;
hwxmits[3] .phwtxqueue = &pxmitpriv->bk_txqueue;
hwxmits[3] .sta_queue = &pxmitpriv->bk_pending;
}
}
static void free_hwxmits(struct _adapter *padapter)
{
struct xmit_priv *pxmitpriv = &padapter->xmitpriv;
kfree(pxmitpriv->hwxmits);
}
static void init_hwxmits(struct hw_xmit *phwxmit, sint entry)
{
sint i;
for (i = 0; i < entry; i++, phwxmit++) {
spin_lock_init(&phwxmit->xmit_lock);
_init_listhead(&phwxmit->pending);
phwxmit->txcmdcnt = 0;
phwxmit->accnt = 0;
}
}
void xmitframe_xmitbuf_attach(struct xmit_frame *pxmitframe,
struct xmit_buf *pxmitbuf)
{
/* pxmitbuf attach to pxmitframe */
pxmitframe->pxmitbuf = pxmitbuf;
/* urb and irp connection */
pxmitframe->pxmit_urb[0] = pxmitbuf->pxmit_urb[0];
/* buffer addr assoc */
pxmitframe->buf_addr = pxmitbuf->pbuf;
/* pxmitframe attach to pxmitbuf */
pxmitbuf->priv_data = pxmitframe;
}
/*
* tx_action == 0 == no frames to transmit
* tx_action > 0 ==> we have frames to transmit
* tx_action < 0 ==> we have frames to transmit, but TXFF is not even enough
* to transmit 1 frame.
*/
int r8712_pre_xmit(struct _adapter *padapter, struct xmit_frame *pxmitframe)
{
unsigned long irqL;
int ret;
struct xmit_buf *pxmitbuf = NULL;
struct xmit_priv *pxmitpriv = &padapter->xmitpriv;
struct pkt_attrib *pattrib = &pxmitframe->attrib;
r8712_do_queue_select(padapter, pattrib);
spin_lock_irqsave(&pxmitpriv->lock, irqL);
if (r8712_txframes_sta_ac_pending(padapter, pattrib) > 0) {
ret = false;
r8712_xmit_enqueue(padapter, pxmitframe);
spin_unlock_irqrestore(&pxmitpriv->lock, irqL);
return ret;
}
pxmitbuf = r8712_alloc_xmitbuf(pxmitpriv);
if (pxmitbuf == NULL) { /*enqueue packet*/
ret = false;
r8712_xmit_enqueue(padapter, pxmitframe);
spin_unlock_irqrestore(&pxmitpriv->lock, irqL);
} else { /*dump packet directly*/
spin_unlock_irqrestore(&pxmitpriv->lock, irqL);
ret = true;
xmitframe_xmitbuf_attach(pxmitframe, pxmitbuf);
r8712_xmit_direct(padapter, pxmitframe);
}
return ret;
}
| gpl-2.0 |
Snuzzo/funky_kernel | fs/jffs2/read.c | 4808 | 7016 | /*
* JFFS2 -- Journalling Flash File System, Version 2.
*
* Copyright © 2001-2007 Red Hat, Inc.
*
* Created by David Woodhouse <dwmw2@infradead.org>
*
* For licensing information, see the file 'LICENCE' in this directory.
*
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/crc32.h>
#include <linux/pagemap.h>
#include <linux/mtd/mtd.h>
#include <linux/compiler.h>
#include "nodelist.h"
#include "compr.h"
int jffs2_read_dnode(struct jffs2_sb_info *c, struct jffs2_inode_info *f,
struct jffs2_full_dnode *fd, unsigned char *buf,
int ofs, int len)
{
struct jffs2_raw_inode *ri;
size_t readlen;
uint32_t crc;
unsigned char *decomprbuf = NULL;
unsigned char *readbuf = NULL;
int ret = 0;
ri = jffs2_alloc_raw_inode();
if (!ri)
return -ENOMEM;
ret = jffs2_flash_read(c, ref_offset(fd->raw), sizeof(*ri), &readlen, (char *)ri);
if (ret) {
jffs2_free_raw_inode(ri);
printk(KERN_WARNING "Error reading node from 0x%08x: %d\n", ref_offset(fd->raw), ret);
return ret;
}
if (readlen != sizeof(*ri)) {
jffs2_free_raw_inode(ri);
printk(KERN_WARNING "Short read from 0x%08x: wanted 0x%zx bytes, got 0x%zx\n",
ref_offset(fd->raw), sizeof(*ri), readlen);
return -EIO;
}
crc = crc32(0, ri, sizeof(*ri)-8);
D1(printk(KERN_DEBUG "Node read from %08x: node_crc %08x, calculated CRC %08x. dsize %x, csize %x, offset %x, buf %p\n",
ref_offset(fd->raw), je32_to_cpu(ri->node_crc),
crc, je32_to_cpu(ri->dsize), je32_to_cpu(ri->csize),
je32_to_cpu(ri->offset), buf));
if (crc != je32_to_cpu(ri->node_crc)) {
printk(KERN_WARNING "Node CRC %08x != calculated CRC %08x for node at %08x\n",
je32_to_cpu(ri->node_crc), crc, ref_offset(fd->raw));
ret = -EIO;
goto out_ri;
}
/* There was a bug where we wrote hole nodes out with csize/dsize
swapped. Deal with it */
if (ri->compr == JFFS2_COMPR_ZERO && !je32_to_cpu(ri->dsize) &&
je32_to_cpu(ri->csize)) {
ri->dsize = ri->csize;
ri->csize = cpu_to_je32(0);
}
D1(if(ofs + len > je32_to_cpu(ri->dsize)) {
printk(KERN_WARNING "jffs2_read_dnode() asked for %d bytes at %d from %d-byte node\n",
len, ofs, je32_to_cpu(ri->dsize));
ret = -EINVAL;
goto out_ri;
});
if (ri->compr == JFFS2_COMPR_ZERO) {
memset(buf, 0, len);
goto out_ri;
}
/* Cases:
Reading whole node and it's uncompressed - read directly to buffer provided, check CRC.
Reading whole node and it's compressed - read into comprbuf, check CRC and decompress to buffer provided
Reading partial node and it's uncompressed - read into readbuf, check CRC, and copy
Reading partial node and it's compressed - read into readbuf, check checksum, decompress to decomprbuf and copy
*/
if (ri->compr == JFFS2_COMPR_NONE && len == je32_to_cpu(ri->dsize)) {
readbuf = buf;
} else {
readbuf = kmalloc(je32_to_cpu(ri->csize), GFP_KERNEL);
if (!readbuf) {
ret = -ENOMEM;
goto out_ri;
}
}
if (ri->compr != JFFS2_COMPR_NONE) {
if (len < je32_to_cpu(ri->dsize)) {
decomprbuf = kmalloc(je32_to_cpu(ri->dsize), GFP_KERNEL);
if (!decomprbuf) {
ret = -ENOMEM;
goto out_readbuf;
}
} else {
decomprbuf = buf;
}
} else {
decomprbuf = readbuf;
}
D2(printk(KERN_DEBUG "Read %d bytes to %p\n", je32_to_cpu(ri->csize),
readbuf));
ret = jffs2_flash_read(c, (ref_offset(fd->raw)) + sizeof(*ri),
je32_to_cpu(ri->csize), &readlen, readbuf);
if (!ret && readlen != je32_to_cpu(ri->csize))
ret = -EIO;
if (ret)
goto out_decomprbuf;
crc = crc32(0, readbuf, je32_to_cpu(ri->csize));
if (crc != je32_to_cpu(ri->data_crc)) {
printk(KERN_WARNING "Data CRC %08x != calculated CRC %08x for node at %08x\n",
je32_to_cpu(ri->data_crc), crc, ref_offset(fd->raw));
ret = -EIO;
goto out_decomprbuf;
}
D2(printk(KERN_DEBUG "Data CRC matches calculated CRC %08x\n", crc));
if (ri->compr != JFFS2_COMPR_NONE) {
D2(printk(KERN_DEBUG "Decompress %d bytes from %p to %d bytes at %p\n",
je32_to_cpu(ri->csize), readbuf, je32_to_cpu(ri->dsize), decomprbuf));
ret = jffs2_decompress(c, f, ri->compr | (ri->usercompr << 8), readbuf, decomprbuf, je32_to_cpu(ri->csize), je32_to_cpu(ri->dsize));
if (ret) {
printk(KERN_WARNING "Error: jffs2_decompress returned %d\n", ret);
goto out_decomprbuf;
}
}
if (len < je32_to_cpu(ri->dsize)) {
memcpy(buf, decomprbuf+ofs, len);
}
out_decomprbuf:
if(decomprbuf != buf && decomprbuf != readbuf)
kfree(decomprbuf);
out_readbuf:
if(readbuf != buf)
kfree(readbuf);
out_ri:
jffs2_free_raw_inode(ri);
return ret;
}
int jffs2_read_inode_range(struct jffs2_sb_info *c, struct jffs2_inode_info *f,
unsigned char *buf, uint32_t offset, uint32_t len)
{
uint32_t end = offset + len;
struct jffs2_node_frag *frag;
int ret;
D1(printk(KERN_DEBUG "jffs2_read_inode_range: ino #%u, range 0x%08x-0x%08x\n",
f->inocache->ino, offset, offset+len));
frag = jffs2_lookup_node_frag(&f->fragtree, offset);
/* XXX FIXME: Where a single physical node actually shows up in two
frags, we read it twice. Don't do that. */
/* Now we're pointing at the first frag which overlaps our page
* (or perhaps is before it, if we've been asked to read off the
* end of the file). */
while(offset < end) {
D2(printk(KERN_DEBUG "jffs2_read_inode_range: offset %d, end %d\n", offset, end));
if (unlikely(!frag || frag->ofs > offset ||
frag->ofs + frag->size <= offset)) {
uint32_t holesize = end - offset;
if (frag && frag->ofs > offset) {
D1(printk(KERN_NOTICE "Eep. Hole in ino #%u fraglist. frag->ofs = 0x%08x, offset = 0x%08x\n", f->inocache->ino, frag->ofs, offset));
holesize = min(holesize, frag->ofs - offset);
}
D1(printk(KERN_DEBUG "Filling non-frag hole from %d-%d\n", offset, offset+holesize));
memset(buf, 0, holesize);
buf += holesize;
offset += holesize;
continue;
} else if (unlikely(!frag->node)) {
uint32_t holeend = min(end, frag->ofs + frag->size);
D1(printk(KERN_DEBUG "Filling frag hole from %d-%d (frag 0x%x 0x%x)\n", offset, holeend, frag->ofs, frag->ofs + frag->size));
memset(buf, 0, holeend - offset);
buf += holeend - offset;
offset = holeend;
frag = frag_next(frag);
continue;
} else {
uint32_t readlen;
uint32_t fragofs; /* offset within the frag to start reading */
fragofs = offset - frag->ofs;
readlen = min(frag->size - fragofs, end - offset);
D1(printk(KERN_DEBUG "Reading %d-%d from node at 0x%08x (%d)\n",
frag->ofs+fragofs, frag->ofs+fragofs+readlen,
ref_offset(frag->node->raw), ref_flags(frag->node->raw)));
ret = jffs2_read_dnode(c, f, frag->node, buf, fragofs + frag->ofs - frag->node->ofs, readlen);
D2(printk(KERN_DEBUG "node read done\n"));
if (ret) {
D1(printk(KERN_DEBUG"jffs2_read_inode_range error %d\n",ret));
memset(buf, 0, readlen);
return ret;
}
buf += readlen;
offset += readlen;
frag = frag_next(frag);
D2(printk(KERN_DEBUG "node read was OK. Looping\n"));
}
}
return 0;
}
| gpl-2.0 |
slz/samsung-kernel-msm7x30 | fs/xfs/xfs_itable.c | 4808 | 20030 | /*
* Copyright (c) 2000-2002,2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_alloc_btree.h"
#include "xfs_ialloc_btree.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_ialloc.h"
#include "xfs_itable.h"
#include "xfs_error.h"
#include "xfs_btree.h"
#include "xfs_trace.h"
STATIC int
xfs_internal_inum(
xfs_mount_t *mp,
xfs_ino_t ino)
{
return (ino == mp->m_sb.sb_rbmino || ino == mp->m_sb.sb_rsumino ||
(xfs_sb_version_hasquota(&mp->m_sb) &&
(ino == mp->m_sb.sb_uquotino || ino == mp->m_sb.sb_gquotino)));
}
/*
* Return stat information for one inode.
* Return 0 if ok, else errno.
*/
int
xfs_bulkstat_one_int(
struct xfs_mount *mp, /* mount point for filesystem */
xfs_ino_t ino, /* inode to get data for */
void __user *buffer, /* buffer to place output in */
int ubsize, /* size of buffer */
bulkstat_one_fmt_pf formatter, /* formatter, copy to user */
int *ubused, /* bytes used by me */
int *stat) /* BULKSTAT_RV_... */
{
struct xfs_icdinode *dic; /* dinode core info pointer */
struct xfs_inode *ip; /* incore inode pointer */
struct xfs_bstat *buf; /* return buffer */
int error = 0; /* error value */
*stat = BULKSTAT_RV_NOTHING;
if (!buffer || xfs_internal_inum(mp, ino))
return XFS_ERROR(EINVAL);
buf = kmem_alloc(sizeof(*buf), KM_SLEEP | KM_MAYFAIL);
if (!buf)
return XFS_ERROR(ENOMEM);
error = xfs_iget(mp, NULL, ino,
(XFS_IGET_DONTCACHE | XFS_IGET_UNTRUSTED),
XFS_ILOCK_SHARED, &ip);
if (error) {
*stat = BULKSTAT_RV_NOTHING;
goto out_free;
}
ASSERT(ip != NULL);
ASSERT(ip->i_imap.im_blkno != 0);
dic = &ip->i_d;
/* xfs_iget returns the following without needing
* further change.
*/
buf->bs_nlink = dic->di_nlink;
buf->bs_projid_lo = dic->di_projid_lo;
buf->bs_projid_hi = dic->di_projid_hi;
buf->bs_ino = ino;
buf->bs_mode = dic->di_mode;
buf->bs_uid = dic->di_uid;
buf->bs_gid = dic->di_gid;
buf->bs_size = dic->di_size;
buf->bs_atime.tv_sec = dic->di_atime.t_sec;
buf->bs_atime.tv_nsec = dic->di_atime.t_nsec;
buf->bs_mtime.tv_sec = dic->di_mtime.t_sec;
buf->bs_mtime.tv_nsec = dic->di_mtime.t_nsec;
buf->bs_ctime.tv_sec = dic->di_ctime.t_sec;
buf->bs_ctime.tv_nsec = dic->di_ctime.t_nsec;
buf->bs_xflags = xfs_ip2xflags(ip);
buf->bs_extsize = dic->di_extsize << mp->m_sb.sb_blocklog;
buf->bs_extents = dic->di_nextents;
buf->bs_gen = dic->di_gen;
memset(buf->bs_pad, 0, sizeof(buf->bs_pad));
buf->bs_dmevmask = dic->di_dmevmask;
buf->bs_dmstate = dic->di_dmstate;
buf->bs_aextents = dic->di_anextents;
buf->bs_forkoff = XFS_IFORK_BOFF(ip);
switch (dic->di_format) {
case XFS_DINODE_FMT_DEV:
buf->bs_rdev = ip->i_df.if_u2.if_rdev;
buf->bs_blksize = BLKDEV_IOSIZE;
buf->bs_blocks = 0;
break;
case XFS_DINODE_FMT_LOCAL:
case XFS_DINODE_FMT_UUID:
buf->bs_rdev = 0;
buf->bs_blksize = mp->m_sb.sb_blocksize;
buf->bs_blocks = 0;
break;
case XFS_DINODE_FMT_EXTENTS:
case XFS_DINODE_FMT_BTREE:
buf->bs_rdev = 0;
buf->bs_blksize = mp->m_sb.sb_blocksize;
buf->bs_blocks = dic->di_nblocks + ip->i_delayed_blks;
break;
}
xfs_iunlock(ip, XFS_ILOCK_SHARED);
IRELE(ip);
error = formatter(buffer, ubsize, ubused, buf);
if (!error)
*stat = BULKSTAT_RV_DIDONE;
out_free:
kmem_free(buf);
return error;
}
/* Return 0 on success or positive error */
STATIC int
xfs_bulkstat_one_fmt(
void __user *ubuffer,
int ubsize,
int *ubused,
const xfs_bstat_t *buffer)
{
if (ubsize < sizeof(*buffer))
return XFS_ERROR(ENOMEM);
if (copy_to_user(ubuffer, buffer, sizeof(*buffer)))
return XFS_ERROR(EFAULT);
if (ubused)
*ubused = sizeof(*buffer);
return 0;
}
int
xfs_bulkstat_one(
xfs_mount_t *mp, /* mount point for filesystem */
xfs_ino_t ino, /* inode number to get data for */
void __user *buffer, /* buffer to place output in */
int ubsize, /* size of buffer */
int *ubused, /* bytes used by me */
int *stat) /* BULKSTAT_RV_... */
{
return xfs_bulkstat_one_int(mp, ino, buffer, ubsize,
xfs_bulkstat_one_fmt, ubused, stat);
}
#define XFS_BULKSTAT_UBLEFT(ubleft) ((ubleft) >= statstruct_size)
/*
* Return stat information in bulk (by-inode) for the filesystem.
*/
int /* error status */
xfs_bulkstat(
xfs_mount_t *mp, /* mount point for filesystem */
xfs_ino_t *lastinop, /* last inode returned */
int *ubcountp, /* size of buffer/count returned */
bulkstat_one_pf formatter, /* func that'd fill a single buf */
size_t statstruct_size, /* sizeof struct filling */
char __user *ubuffer, /* buffer with inode stats */
int *done) /* 1 if there are more stats to get */
{
xfs_agblock_t agbno=0;/* allocation group block number */
xfs_buf_t *agbp; /* agi header buffer */
xfs_agi_t *agi; /* agi header data */
xfs_agino_t agino; /* inode # in allocation group */
xfs_agnumber_t agno; /* allocation group number */
int chunkidx; /* current index into inode chunk */
int clustidx; /* current index into inode cluster */
xfs_btree_cur_t *cur; /* btree cursor for ialloc btree */
int end_of_ag; /* set if we've seen the ag end */
int error; /* error code */
int fmterror;/* bulkstat formatter result */
int i; /* loop index */
int icount; /* count of inodes good in irbuf */
size_t irbsize; /* size of irec buffer in bytes */
xfs_ino_t ino; /* inode number (filesystem) */
xfs_inobt_rec_incore_t *irbp; /* current irec buffer pointer */
xfs_inobt_rec_incore_t *irbuf; /* start of irec buffer */
xfs_inobt_rec_incore_t *irbufend; /* end of good irec buffer entries */
xfs_ino_t lastino; /* last inode number returned */
int nbcluster; /* # of blocks in a cluster */
int nicluster; /* # of inodes in a cluster */
int nimask; /* mask for inode clusters */
int nirbuf; /* size of irbuf */
int rval; /* return value error code */
int tmp; /* result value from btree calls */
int ubcount; /* size of user's buffer */
int ubleft; /* bytes left in user's buffer */
char __user *ubufp; /* pointer into user's buffer */
int ubelem; /* spaces used in user's buffer */
int ubused; /* bytes used by formatter */
xfs_buf_t *bp; /* ptr to on-disk inode cluster buf */
/*
* Get the last inode value, see if there's nothing to do.
*/
ino = (xfs_ino_t)*lastinop;
lastino = ino;
agno = XFS_INO_TO_AGNO(mp, ino);
agino = XFS_INO_TO_AGINO(mp, ino);
if (agno >= mp->m_sb.sb_agcount ||
ino != XFS_AGINO_TO_INO(mp, agno, agino)) {
*done = 1;
*ubcountp = 0;
return 0;
}
if (!ubcountp || *ubcountp <= 0) {
return EINVAL;
}
ubcount = *ubcountp; /* statstruct's */
ubleft = ubcount * statstruct_size; /* bytes */
*ubcountp = ubelem = 0;
*done = 0;
fmterror = 0;
ubufp = ubuffer;
nicluster = mp->m_sb.sb_blocksize >= XFS_INODE_CLUSTER_SIZE(mp) ?
mp->m_sb.sb_inopblock :
(XFS_INODE_CLUSTER_SIZE(mp) >> mp->m_sb.sb_inodelog);
nimask = ~(nicluster - 1);
nbcluster = nicluster >> mp->m_sb.sb_inopblog;
irbuf = kmem_zalloc_greedy(&irbsize, PAGE_SIZE, PAGE_SIZE * 4);
if (!irbuf)
return ENOMEM;
nirbuf = irbsize / sizeof(*irbuf);
/*
* Loop over the allocation groups, starting from the last
* inode returned; 0 means start of the allocation group.
*/
rval = 0;
while (XFS_BULKSTAT_UBLEFT(ubleft) && agno < mp->m_sb.sb_agcount) {
cond_resched();
bp = NULL;
error = xfs_ialloc_read_agi(mp, NULL, agno, &agbp);
if (error) {
/*
* Skip this allocation group and go to the next one.
*/
agno++;
agino = 0;
continue;
}
agi = XFS_BUF_TO_AGI(agbp);
/*
* Allocate and initialize a btree cursor for ialloc btree.
*/
cur = xfs_inobt_init_cursor(mp, NULL, agbp, agno);
irbp = irbuf;
irbufend = irbuf + nirbuf;
end_of_ag = 0;
/*
* If we're returning in the middle of an allocation group,
* we need to get the remainder of the chunk we're in.
*/
if (agino > 0) {
xfs_inobt_rec_incore_t r;
/*
* Lookup the inode chunk that this inode lives in.
*/
error = xfs_inobt_lookup(cur, agino, XFS_LOOKUP_LE,
&tmp);
if (!error && /* no I/O error */
tmp && /* lookup succeeded */
/* got the record, should always work */
!(error = xfs_inobt_get_rec(cur, &r, &i)) &&
i == 1 &&
/* this is the right chunk */
agino < r.ir_startino + XFS_INODES_PER_CHUNK &&
/* lastino was not last in chunk */
(chunkidx = agino - r.ir_startino + 1) <
XFS_INODES_PER_CHUNK &&
/* there are some left allocated */
xfs_inobt_maskn(chunkidx,
XFS_INODES_PER_CHUNK - chunkidx) &
~r.ir_free) {
/*
* Grab the chunk record. Mark all the
* uninteresting inodes (because they're
* before our start point) free.
*/
for (i = 0; i < chunkidx; i++) {
if (XFS_INOBT_MASK(i) & ~r.ir_free)
r.ir_freecount++;
}
r.ir_free |= xfs_inobt_maskn(0, chunkidx);
irbp->ir_startino = r.ir_startino;
irbp->ir_freecount = r.ir_freecount;
irbp->ir_free = r.ir_free;
irbp++;
agino = r.ir_startino + XFS_INODES_PER_CHUNK;
icount = XFS_INODES_PER_CHUNK - r.ir_freecount;
} else {
/*
* If any of those tests failed, bump the
* inode number (just in case).
*/
agino++;
icount = 0;
}
/*
* In any case, increment to the next record.
*/
if (!error)
error = xfs_btree_increment(cur, 0, &tmp);
} else {
/*
* Start of ag. Lookup the first inode chunk.
*/
error = xfs_inobt_lookup(cur, 0, XFS_LOOKUP_GE, &tmp);
icount = 0;
}
/*
* Loop through inode btree records in this ag,
* until we run out of inodes or space in the buffer.
*/
while (irbp < irbufend && icount < ubcount) {
xfs_inobt_rec_incore_t r;
/*
* Loop as long as we're unable to read the
* inode btree.
*/
while (error) {
agino += XFS_INODES_PER_CHUNK;
if (XFS_AGINO_TO_AGBNO(mp, agino) >=
be32_to_cpu(agi->agi_length))
break;
error = xfs_inobt_lookup(cur, agino,
XFS_LOOKUP_GE, &tmp);
cond_resched();
}
/*
* If ran off the end of the ag either with an error,
* or the normal way, set end and stop collecting.
*/
if (error) {
end_of_ag = 1;
break;
}
error = xfs_inobt_get_rec(cur, &r, &i);
if (error || i == 0) {
end_of_ag = 1;
break;
}
/*
* If this chunk has any allocated inodes, save it.
* Also start read-ahead now for this chunk.
*/
if (r.ir_freecount < XFS_INODES_PER_CHUNK) {
/*
* Loop over all clusters in the next chunk.
* Do a readahead if there are any allocated
* inodes in that cluster.
*/
agbno = XFS_AGINO_TO_AGBNO(mp, r.ir_startino);
for (chunkidx = 0;
chunkidx < XFS_INODES_PER_CHUNK;
chunkidx += nicluster,
agbno += nbcluster) {
if (xfs_inobt_maskn(chunkidx, nicluster)
& ~r.ir_free)
xfs_btree_reada_bufs(mp, agno,
agbno, nbcluster);
}
irbp->ir_startino = r.ir_startino;
irbp->ir_freecount = r.ir_freecount;
irbp->ir_free = r.ir_free;
irbp++;
icount += XFS_INODES_PER_CHUNK - r.ir_freecount;
}
/*
* Set agino to after this chunk and bump the cursor.
*/
agino = r.ir_startino + XFS_INODES_PER_CHUNK;
error = xfs_btree_increment(cur, 0, &tmp);
cond_resched();
}
/*
* Drop the btree buffers and the agi buffer.
* We can't hold any of the locks these represent
* when calling iget.
*/
xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
xfs_buf_relse(agbp);
/*
* Now format all the good inodes into the user's buffer.
*/
irbufend = irbp;
for (irbp = irbuf;
irbp < irbufend && XFS_BULKSTAT_UBLEFT(ubleft); irbp++) {
/*
* Now process this chunk of inodes.
*/
for (agino = irbp->ir_startino, chunkidx = clustidx = 0;
XFS_BULKSTAT_UBLEFT(ubleft) &&
irbp->ir_freecount < XFS_INODES_PER_CHUNK;
chunkidx++, clustidx++, agino++) {
ASSERT(chunkidx < XFS_INODES_PER_CHUNK);
/*
* Recompute agbno if this is the
* first inode of the cluster.
*
* Careful with clustidx. There can be
* multiple clusters per chunk, a single
* cluster per chunk or a cluster that has
* inodes represented from several different
* chunks (if blocksize is large).
*
* Because of this, the starting clustidx is
* initialized to zero in this loop but must
* later be reset after reading in the cluster
* buffer.
*/
if ((chunkidx & (nicluster - 1)) == 0) {
agbno = XFS_AGINO_TO_AGBNO(mp,
irbp->ir_startino) +
((chunkidx & nimask) >>
mp->m_sb.sb_inopblog);
}
ino = XFS_AGINO_TO_INO(mp, agno, agino);
/*
* Skip if this inode is free.
*/
if (XFS_INOBT_MASK(chunkidx) & irbp->ir_free) {
lastino = ino;
continue;
}
/*
* Count used inodes as free so we can tell
* when the chunk is used up.
*/
irbp->ir_freecount++;
/*
* Get the inode and fill in a single buffer.
*/
ubused = statstruct_size;
error = formatter(mp, ino, ubufp, ubleft,
&ubused, &fmterror);
if (fmterror == BULKSTAT_RV_NOTHING) {
if (error && error != ENOENT &&
error != EINVAL) {
ubleft = 0;
rval = error;
break;
}
lastino = ino;
continue;
}
if (fmterror == BULKSTAT_RV_GIVEUP) {
ubleft = 0;
ASSERT(error);
rval = error;
break;
}
if (ubufp)
ubufp += ubused;
ubleft -= ubused;
ubelem++;
lastino = ino;
}
cond_resched();
}
if (bp)
xfs_buf_relse(bp);
/*
* Set up for the next loop iteration.
*/
if (XFS_BULKSTAT_UBLEFT(ubleft)) {
if (end_of_ag) {
agno++;
agino = 0;
} else
agino = XFS_INO_TO_AGINO(mp, lastino);
} else
break;
}
/*
* Done, we're either out of filesystem or space to put the data.
*/
kmem_free_large(irbuf);
*ubcountp = ubelem;
/*
* Found some inodes, return them now and return the error next time.
*/
if (ubelem)
rval = 0;
if (agno >= mp->m_sb.sb_agcount) {
/*
* If we ran out of filesystem, mark lastino as off
* the end of the filesystem, so the next call
* will return immediately.
*/
*lastinop = (xfs_ino_t)XFS_AGINO_TO_INO(mp, agno, 0);
*done = 1;
} else
*lastinop = (xfs_ino_t)lastino;
return rval;
}
/*
* Return stat information in bulk (by-inode) for the filesystem.
* Special case for non-sequential one inode bulkstat.
*/
int /* error status */
xfs_bulkstat_single(
xfs_mount_t *mp, /* mount point for filesystem */
xfs_ino_t *lastinop, /* inode to return */
char __user *buffer, /* buffer with inode stats */
int *done) /* 1 if there are more stats to get */
{
int count; /* count value for bulkstat call */
int error; /* return value */
xfs_ino_t ino; /* filesystem inode number */
int res; /* result from bs1 */
/*
* note that requesting valid inode numbers which are not allocated
* to inodes will most likely cause xfs_itobp to generate warning
* messages about bad magic numbers. This is ok. The fact that
* the inode isn't actually an inode is handled by the
* error check below. Done this way to make the usual case faster
* at the expense of the error case.
*/
ino = (xfs_ino_t)*lastinop;
error = xfs_bulkstat_one(mp, ino, buffer, sizeof(xfs_bstat_t), 0, &res);
if (error) {
/*
* Special case way failed, do it the "long" way
* to see if that works.
*/
(*lastinop)--;
count = 1;
if (xfs_bulkstat(mp, lastinop, &count, xfs_bulkstat_one,
sizeof(xfs_bstat_t), buffer, done))
return error;
if (count == 0 || (xfs_ino_t)*lastinop != ino)
return error == EFSCORRUPTED ?
XFS_ERROR(EINVAL) : error;
else
return 0;
}
*done = 0;
return 0;
}
int
xfs_inumbers_fmt(
void __user *ubuffer, /* buffer to write to */
const xfs_inogrp_t *buffer, /* buffer to read from */
long count, /* # of elements to read */
long *written) /* # of bytes written */
{
if (copy_to_user(ubuffer, buffer, count * sizeof(*buffer)))
return -EFAULT;
*written = count * sizeof(*buffer);
return 0;
}
/*
* Return inode number table for the filesystem.
*/
int /* error status */
xfs_inumbers(
xfs_mount_t *mp, /* mount point for filesystem */
xfs_ino_t *lastino, /* last inode returned */
int *count, /* size of buffer/count returned */
void __user *ubuffer,/* buffer with inode descriptions */
inumbers_fmt_pf formatter)
{
xfs_buf_t *agbp;
xfs_agino_t agino;
xfs_agnumber_t agno;
int bcount;
xfs_inogrp_t *buffer;
int bufidx;
xfs_btree_cur_t *cur;
int error;
xfs_inobt_rec_incore_t r;
int i;
xfs_ino_t ino;
int left;
int tmp;
ino = (xfs_ino_t)*lastino;
agno = XFS_INO_TO_AGNO(mp, ino);
agino = XFS_INO_TO_AGINO(mp, ino);
left = *count;
*count = 0;
bcount = MIN(left, (int)(PAGE_SIZE / sizeof(*buffer)));
buffer = kmem_alloc(bcount * sizeof(*buffer), KM_SLEEP);
error = bufidx = 0;
cur = NULL;
agbp = NULL;
while (left > 0 && agno < mp->m_sb.sb_agcount) {
if (agbp == NULL) {
error = xfs_ialloc_read_agi(mp, NULL, agno, &agbp);
if (error) {
/*
* If we can't read the AGI of this ag,
* then just skip to the next one.
*/
ASSERT(cur == NULL);
agbp = NULL;
agno++;
agino = 0;
continue;
}
cur = xfs_inobt_init_cursor(mp, NULL, agbp, agno);
error = xfs_inobt_lookup(cur, agino, XFS_LOOKUP_GE,
&tmp);
if (error) {
xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
cur = NULL;
xfs_buf_relse(agbp);
agbp = NULL;
/*
* Move up the last inode in the current
* chunk. The lookup_ge will always get
* us the first inode in the next chunk.
*/
agino += XFS_INODES_PER_CHUNK - 1;
continue;
}
}
error = xfs_inobt_get_rec(cur, &r, &i);
if (error || i == 0) {
xfs_buf_relse(agbp);
agbp = NULL;
xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
cur = NULL;
agno++;
agino = 0;
continue;
}
agino = r.ir_startino + XFS_INODES_PER_CHUNK - 1;
buffer[bufidx].xi_startino =
XFS_AGINO_TO_INO(mp, agno, r.ir_startino);
buffer[bufidx].xi_alloccount =
XFS_INODES_PER_CHUNK - r.ir_freecount;
buffer[bufidx].xi_allocmask = ~r.ir_free;
bufidx++;
left--;
if (bufidx == bcount) {
long written;
if (formatter(ubuffer, buffer, bufidx, &written)) {
error = XFS_ERROR(EFAULT);
break;
}
ubuffer += written;
*count += bufidx;
bufidx = 0;
}
if (left) {
error = xfs_btree_increment(cur, 0, &tmp);
if (error) {
xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
cur = NULL;
xfs_buf_relse(agbp);
agbp = NULL;
/*
* The agino value has already been bumped.
* Just try to skip up to it.
*/
agino += XFS_INODES_PER_CHUNK;
continue;
}
}
}
if (!error) {
if (bufidx) {
long written;
if (formatter(ubuffer, buffer, bufidx, &written))
error = XFS_ERROR(EFAULT);
else
*count += bufidx;
}
*lastino = XFS_AGINO_TO_INO(mp, agno, agino);
}
kmem_free(buffer);
if (cur)
xfs_btree_del_cursor(cur, (error ? XFS_BTREE_ERROR :
XFS_BTREE_NOERROR));
if (agbp)
xfs_buf_relse(agbp);
return error;
}
| gpl-2.0 |
detule/linux-msm-d2 | drivers/net/ethernet/stmicro/stmmac/stmmac_platform.c | 4808 | 7021 | /*******************************************************************************
This contains the functions to handle the platform driver.
Copyright (C) 2007-2011 STMicroelectronics Ltd
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Author: Giuseppe Cavallaro <peppe.cavallaro@st.com>
*******************************************************************************/
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/of_net.h>
#include "stmmac.h"
#ifdef CONFIG_OF
static int __devinit stmmac_probe_config_dt(struct platform_device *pdev,
struct plat_stmmacenet_data *plat,
const char **mac)
{
struct device_node *np = pdev->dev.of_node;
if (!np)
return -ENODEV;
*mac = of_get_mac_address(np);
plat->interface = of_get_phy_mode(np);
plat->mdio_bus_data = devm_kzalloc(&pdev->dev,
sizeof(struct stmmac_mdio_bus_data),
GFP_KERNEL);
/*
* Currently only the properties needed on SPEAr600
* are provided. All other properties should be added
* once needed on other platforms.
*/
if (of_device_is_compatible(np, "st,spear600-gmac")) {
plat->pbl = 8;
plat->has_gmac = 1;
plat->pmt = 1;
}
return 0;
}
#else
static int __devinit stmmac_probe_config_dt(struct platform_device *pdev,
struct plat_stmmacenet_data *plat,
const char **mac)
{
return -ENOSYS;
}
#endif /* CONFIG_OF */
/**
* stmmac_pltfr_probe
* @pdev: platform device pointer
* Description: platform_device probe function. It allocates
* the necessary resources and invokes the main to init
* the net device, register the mdio bus etc.
*/
static int stmmac_pltfr_probe(struct platform_device *pdev)
{
int ret = 0;
struct resource *res;
void __iomem *addr = NULL;
struct stmmac_priv *priv = NULL;
struct plat_stmmacenet_data *plat_dat = NULL;
const char *mac = NULL;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENODEV;
if (!request_mem_region(res->start, resource_size(res), pdev->name)) {
pr_err("%s: ERROR: memory allocation failed"
"cannot get the I/O addr 0x%x\n",
__func__, (unsigned int)res->start);
return -EBUSY;
}
addr = ioremap(res->start, resource_size(res));
if (!addr) {
pr_err("%s: ERROR: memory mapping failed", __func__);
ret = -ENOMEM;
goto out_release_region;
}
if (pdev->dev.of_node) {
plat_dat = devm_kzalloc(&pdev->dev,
sizeof(struct plat_stmmacenet_data),
GFP_KERNEL);
if (!plat_dat) {
pr_err("%s: ERROR: no memory", __func__);
ret = -ENOMEM;
goto out_unmap;
}
ret = stmmac_probe_config_dt(pdev, plat_dat, &mac);
if (ret) {
pr_err("%s: main dt probe failed", __func__);
goto out_unmap;
}
} else {
plat_dat = pdev->dev.platform_data;
}
/* Custom initialisation (if needed)*/
if (plat_dat->init) {
ret = plat_dat->init(pdev);
if (unlikely(ret))
goto out_unmap;
}
priv = stmmac_dvr_probe(&(pdev->dev), plat_dat, addr);
if (!priv) {
pr_err("%s: main driver probe failed", __func__);
goto out_unmap;
}
/* Get MAC address if available (DT) */
if (mac)
memcpy(priv->dev->dev_addr, mac, ETH_ALEN);
/* Get the MAC information */
priv->dev->irq = platform_get_irq_byname(pdev, "macirq");
if (priv->dev->irq == -ENXIO) {
pr_err("%s: ERROR: MAC IRQ configuration "
"information not found\n", __func__);
ret = -ENXIO;
goto out_unmap;
}
/*
* On some platforms e.g. SPEAr the wake up irq differs from the mac irq
* The external wake up irq can be passed through the platform code
* named as "eth_wake_irq"
*
* In case the wake up interrupt is not passed from the platform
* so the driver will continue to use the mac irq (ndev->irq)
*/
priv->wol_irq = platform_get_irq_byname(pdev, "eth_wake_irq");
if (priv->wol_irq == -ENXIO)
priv->wol_irq = priv->dev->irq;
platform_set_drvdata(pdev, priv->dev);
pr_debug("STMMAC platform driver registration completed");
return 0;
out_unmap:
iounmap(addr);
platform_set_drvdata(pdev, NULL);
out_release_region:
release_mem_region(res->start, resource_size(res));
return ret;
}
/**
* stmmac_pltfr_remove
* @pdev: platform device pointer
* Description: this function calls the main to free the net resources
* and calls the platforms hook and release the resources (e.g. mem).
*/
static int stmmac_pltfr_remove(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct stmmac_priv *priv = netdev_priv(ndev);
struct resource *res;
int ret = stmmac_dvr_remove(ndev);
if (priv->plat->exit)
priv->plat->exit(pdev);
if (priv->plat->exit)
priv->plat->exit(pdev);
platform_set_drvdata(pdev, NULL);
iounmap((void *)priv->ioaddr);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(res->start, resource_size(res));
return ret;
}
#ifdef CONFIG_PM
static int stmmac_pltfr_suspend(struct device *dev)
{
struct net_device *ndev = dev_get_drvdata(dev);
return stmmac_suspend(ndev);
}
static int stmmac_pltfr_resume(struct device *dev)
{
struct net_device *ndev = dev_get_drvdata(dev);
return stmmac_resume(ndev);
}
int stmmac_pltfr_freeze(struct device *dev)
{
struct net_device *ndev = dev_get_drvdata(dev);
return stmmac_freeze(ndev);
}
int stmmac_pltfr_restore(struct device *dev)
{
struct net_device *ndev = dev_get_drvdata(dev);
return stmmac_restore(ndev);
}
static const struct dev_pm_ops stmmac_pltfr_pm_ops = {
.suspend = stmmac_pltfr_suspend,
.resume = stmmac_pltfr_resume,
.freeze = stmmac_pltfr_freeze,
.thaw = stmmac_pltfr_restore,
.restore = stmmac_pltfr_restore,
};
#else
static const struct dev_pm_ops stmmac_pltfr_pm_ops;
#endif /* CONFIG_PM */
static const struct of_device_id stmmac_dt_ids[] = {
{ .compatible = "st,spear600-gmac", },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, stmmac_dt_ids);
static struct platform_driver stmmac_driver = {
.probe = stmmac_pltfr_probe,
.remove = stmmac_pltfr_remove,
.driver = {
.name = STMMAC_RESOURCE_NAME,
.owner = THIS_MODULE,
.pm = &stmmac_pltfr_pm_ops,
.of_match_table = of_match_ptr(stmmac_dt_ids),
},
};
module_platform_driver(stmmac_driver);
MODULE_DESCRIPTION("STMMAC 10/100/1000 Ethernet PLATFORM driver");
MODULE_AUTHOR("Giuseppe Cavallaro <peppe.cavallaro@st.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
csimmonds/rowboat-kernel | drivers/scsi/dtc.c | 5064 | 13348 |
#define AUTOSENSE
#define PSEUDO_DMA
#define DONT_USE_INTR
#define UNSAFE /* Leave interrupts enabled during pseudo-dma I/O */
#define xNDEBUG (NDEBUG_INTR+NDEBUG_RESELECTION+\
NDEBUG_SELECTION+NDEBUG_ARBITRATION)
#define DMA_WORKS_RIGHT
/*
* DTC 3180/3280 driver, by
* Ray Van Tassle rayvt@comm.mot.com
*
* taken from ...
* Trantor T128/T128F/T228 driver by...
*
* Drew Eckhardt
* Visionary Computing
* (Unix and Linux consulting and custom programming)
* drew@colorado.edu
* +1 (303) 440-4894
*
* DISTRIBUTION RELEASE 1.
*
* For more information, please consult
*
* NCR 5380 Family
* SCSI Protocol Controller
* Databook
*/
/*
* Options :
* AUTOSENSE - if defined, REQUEST SENSE will be performed automatically
* for commands that return with a CHECK CONDITION status.
*
* PSEUDO_DMA - enables PSEUDO-DMA hardware, should give a 3-4X performance
* increase compared to polled I/O.
*
* PARITY - enable parity checking. Not supported.
*
* UNSAFE - leave interrupts enabled during pseudo-DMA transfers.
* You probably want this.
*
* The card is detected and initialized in one of several ways :
* 1. Autoprobe (default) - since the board is memory mapped,
* a BIOS signature is scanned for to locate the registers.
* An interrupt is triggered to autoprobe for the interrupt
* line.
*
* 2. With command line overrides - dtc=address,irq may be
* used on the LILO command line to override the defaults.
*
*/
/*----------------------------------------------------------------*/
/* the following will set the monitor border color (useful to find
where something crashed or gets stuck at */
/* 1 = blue
2 = green
3 = cyan
4 = red
5 = magenta
6 = yellow
7 = white
*/
#if 0
#define rtrc(i) {inb(0x3da); outb(0x31, 0x3c0); outb((i), 0x3c0);}
#else
#define rtrc(i) {}
#endif
#include <asm/system.h>
#include <linux/module.h>
#include <linux/signal.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/stat.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include "scsi.h"
#include <scsi/scsi_host.h>
#include "dtc.h"
#define AUTOPROBE_IRQ
#include "NCR5380.h"
#define DTC_PUBLIC_RELEASE 2
/*
* The DTC3180 & 3280 boards are memory mapped.
*
*/
/*
*/
/* Offset from DTC_5380_OFFSET */
#define DTC_CONTROL_REG 0x100 /* rw */
#define D_CR_ACCESS 0x80 /* ro set=can access 3280 registers */
#define CSR_DIR_READ 0x40 /* rw direction, 1 = read 0 = write */
#define CSR_RESET 0x80 /* wo Resets 53c400 */
#define CSR_5380_REG 0x80 /* ro 5380 registers can be accessed */
#define CSR_TRANS_DIR 0x40 /* rw Data transfer direction */
#define CSR_SCSI_BUFF_INTR 0x20 /* rw Enable int on transfer ready */
#define CSR_5380_INTR 0x10 /* rw Enable 5380 interrupts */
#define CSR_SHARED_INTR 0x08 /* rw Interrupt sharing */
#define CSR_HOST_BUF_NOT_RDY 0x04 /* ro Host buffer not ready */
#define CSR_SCSI_BUF_RDY 0x02 /* ro SCSI buffer ready */
#define CSR_GATED_5380_IRQ 0x01 /* ro Last block xferred */
#define CSR_INT_BASE (CSR_SCSI_BUFF_INTR | CSR_5380_INTR)
#define DTC_BLK_CNT 0x101 /* rw
* # of 128-byte blocks to transfer */
#define D_CR_ACCESS 0x80 /* ro set=can access 3280 registers */
#define DTC_SWITCH_REG 0x3982 /* ro - DIP switches */
#define DTC_RESUME_XFER 0x3982 /* wo - resume data xfer
* after disconnect/reconnect*/
#define DTC_5380_OFFSET 0x3880 /* 8 registers here, see NCR5380.h */
/*!!!! for dtc, it's a 128 byte buffer at 3900 !!! */
#define DTC_DATA_BUF 0x3900 /* rw 128 bytes long */
static struct override {
unsigned int address;
int irq;
} overrides
#ifdef OVERRIDE
[] __initdata = OVERRIDE;
#else
[4] __initdata = {
{ 0, IRQ_AUTO }, { 0, IRQ_AUTO }, { 0, IRQ_AUTO }, { 0, IRQ_AUTO }
};
#endif
#define NO_OVERRIDES ARRAY_SIZE(overrides)
static struct base {
unsigned long address;
int noauto;
} bases[] __initdata = {
{ 0xcc000, 0 },
{ 0xc8000, 0 },
{ 0xdc000, 0 },
{ 0xd8000, 0 }
};
#define NO_BASES ARRAY_SIZE(bases)
static const struct signature {
const char *string;
int offset;
} signatures[] = {
{"DATA TECHNOLOGY CORPORATION BIOS", 0x25},
};
#define NO_SIGNATURES ARRAY_SIZE(signatures)
#ifndef MODULE
/*
* Function : dtc_setup(char *str, int *ints)
*
* Purpose : LILO command line initialization of the overrides array,
*
* Inputs : str - unused, ints - array of integer parameters with ints[0]
* equal to the number of ints.
*
*/
static void __init dtc_setup(char *str, int *ints)
{
static int commandline_current = 0;
int i;
if (ints[0] != 2)
printk("dtc_setup: usage dtc=address,irq\n");
else if (commandline_current < NO_OVERRIDES) {
overrides[commandline_current].address = ints[1];
overrides[commandline_current].irq = ints[2];
for (i = 0; i < NO_BASES; ++i)
if (bases[i].address == ints[1]) {
bases[i].noauto = 1;
break;
}
++commandline_current;
}
}
#endif
/*
* Function : int dtc_detect(struct scsi_host_template * tpnt)
*
* Purpose : detects and initializes DTC 3180/3280 controllers
* that were autoprobed, overridden on the LILO command line,
* or specified at compile time.
*
* Inputs : tpnt - template for this SCSI adapter.
*
* Returns : 1 if a host adapter was found, 0 if not.
*
*/
static int __init dtc_detect(struct scsi_host_template * tpnt)
{
static int current_override = 0, current_base = 0;
struct Scsi_Host *instance;
unsigned int addr;
void __iomem *base;
int sig, count;
tpnt->proc_name = "dtc3x80";
tpnt->proc_info = &dtc_proc_info;
for (count = 0; current_override < NO_OVERRIDES; ++current_override) {
addr = 0;
base = NULL;
if (overrides[current_override].address) {
addr = overrides[current_override].address;
base = ioremap(addr, 0x2000);
if (!base)
addr = 0;
} else
for (; !addr && (current_base < NO_BASES); ++current_base) {
#if (DTCDEBUG & DTCDEBUG_INIT)
printk(KERN_DEBUG "scsi-dtc : probing address %08x\n", bases[current_base].address);
#endif
if (bases[current_base].noauto)
continue;
base = ioremap(bases[current_base].address, 0x2000);
if (!base)
continue;
for (sig = 0; sig < NO_SIGNATURES; ++sig) {
if (check_signature(base + signatures[sig].offset, signatures[sig].string, strlen(signatures[sig].string))) {
addr = bases[current_base].address;
#if (DTCDEBUG & DTCDEBUG_INIT)
printk(KERN_DEBUG "scsi-dtc : detected board.\n");
#endif
goto found;
}
}
iounmap(base);
}
#if defined(DTCDEBUG) && (DTCDEBUG & DTCDEBUG_INIT)
printk(KERN_DEBUG "scsi-dtc : base = %08x\n", addr);
#endif
if (!addr)
break;
found:
instance = scsi_register(tpnt, sizeof(struct NCR5380_hostdata));
if (instance == NULL)
break;
instance->base = addr;
((struct NCR5380_hostdata *)(instance)->hostdata)->base = base;
NCR5380_init(instance, 0);
NCR5380_write(DTC_CONTROL_REG, CSR_5380_INTR); /* Enable int's */
if (overrides[current_override].irq != IRQ_AUTO)
instance->irq = overrides[current_override].irq;
else
instance->irq = NCR5380_probe_irq(instance, DTC_IRQS);
#ifndef DONT_USE_INTR
/* With interrupts enabled, it will sometimes hang when doing heavy
* reads. So better not enable them until I finger it out. */
if (instance->irq != SCSI_IRQ_NONE)
if (request_irq(instance->irq, dtc_intr, IRQF_DISABLED,
"dtc", instance)) {
printk(KERN_ERR "scsi%d : IRQ%d not free, interrupts disabled\n", instance->host_no, instance->irq);
instance->irq = SCSI_IRQ_NONE;
}
if (instance->irq == SCSI_IRQ_NONE) {
printk(KERN_WARNING "scsi%d : interrupts not enabled. for better interactive performance,\n", instance->host_no);
printk(KERN_WARNING "scsi%d : please jumper the board for a free IRQ.\n", instance->host_no);
}
#else
if (instance->irq != SCSI_IRQ_NONE)
printk(KERN_WARNING "scsi%d : interrupts not used. Might as well not jumper it.\n", instance->host_no);
instance->irq = SCSI_IRQ_NONE;
#endif
#if defined(DTCDEBUG) && (DTCDEBUG & DTCDEBUG_INIT)
printk("scsi%d : irq = %d\n", instance->host_no, instance->irq);
#endif
printk(KERN_INFO "scsi%d : at 0x%05X", instance->host_no, (int) instance->base);
if (instance->irq == SCSI_IRQ_NONE)
printk(" interrupts disabled");
else
printk(" irq %d", instance->irq);
printk(" options CAN_QUEUE=%d CMD_PER_LUN=%d release=%d", CAN_QUEUE, CMD_PER_LUN, DTC_PUBLIC_RELEASE);
NCR5380_print_options(instance);
printk("\n");
++current_override;
++count;
}
return count;
}
/*
* Function : int dtc_biosparam(Disk * disk, struct block_device *dev, int *ip)
*
* Purpose : Generates a BIOS / DOS compatible H-C-S mapping for
* the specified device / size.
*
* Inputs : size = size of device in sectors (512 bytes), dev = block device
* major / minor, ip[] = {heads, sectors, cylinders}
*
* Returns : always 0 (success), initializes ip
*
*/
/*
* XXX Most SCSI boards use this mapping, I could be incorrect. Some one
* using hard disks on a trantor should verify that this mapping corresponds
* to that used by the BIOS / ASPI driver by running the linux fdisk program
* and matching the H_C_S coordinates to what DOS uses.
*/
static int dtc_biosparam(struct scsi_device *sdev, struct block_device *dev,
sector_t capacity, int *ip)
{
int size = capacity;
ip[0] = 64;
ip[1] = 32;
ip[2] = size >> 11;
return 0;
}
/****************************************************************
* Function : int NCR5380_pread (struct Scsi_Host *instance,
* unsigned char *dst, int len)
*
* Purpose : Fast 5380 pseudo-dma read function, reads len bytes to
* dst
*
* Inputs : dst = destination, len = length in bytes
*
* Returns : 0 on success, non zero on a failure such as a watchdog
* timeout.
*/
static int dtc_maxi = 0;
static int dtc_wmaxi = 0;
static inline int NCR5380_pread(struct Scsi_Host *instance, unsigned char *dst, int len)
{
unsigned char *d = dst;
int i; /* For counting time spent in the poll-loop */
NCR5380_local_declare();
NCR5380_setup(instance);
i = 0;
NCR5380_read(RESET_PARITY_INTERRUPT_REG);
NCR5380_write(MODE_REG, MR_ENABLE_EOP_INTR | MR_DMA_MODE);
if (instance->irq == SCSI_IRQ_NONE)
NCR5380_write(DTC_CONTROL_REG, CSR_DIR_READ);
else
NCR5380_write(DTC_CONTROL_REG, CSR_DIR_READ | CSR_INT_BASE);
NCR5380_write(DTC_BLK_CNT, len >> 7); /* Block count */
rtrc(1);
while (len > 0) {
rtrc(2);
while (NCR5380_read(DTC_CONTROL_REG) & CSR_HOST_BUF_NOT_RDY)
++i;
rtrc(3);
memcpy_fromio(d, base + DTC_DATA_BUF, 128);
d += 128;
len -= 128;
rtrc(7);
/*** with int's on, it sometimes hangs after here.
* Looks like something makes HBNR go away. */
}
rtrc(4);
while (!(NCR5380_read(DTC_CONTROL_REG) & D_CR_ACCESS))
++i;
NCR5380_write(MODE_REG, 0); /* Clear the operating mode */
rtrc(0);
NCR5380_read(RESET_PARITY_INTERRUPT_REG);
if (i > dtc_maxi)
dtc_maxi = i;
return (0);
}
/****************************************************************
* Function : int NCR5380_pwrite (struct Scsi_Host *instance,
* unsigned char *src, int len)
*
* Purpose : Fast 5380 pseudo-dma write function, transfers len bytes from
* src
*
* Inputs : src = source, len = length in bytes
*
* Returns : 0 on success, non zero on a failure such as a watchdog
* timeout.
*/
static inline int NCR5380_pwrite(struct Scsi_Host *instance, unsigned char *src, int len)
{
int i;
NCR5380_local_declare();
NCR5380_setup(instance);
NCR5380_read(RESET_PARITY_INTERRUPT_REG);
NCR5380_write(MODE_REG, MR_ENABLE_EOP_INTR | MR_DMA_MODE);
/* set direction (write) */
if (instance->irq == SCSI_IRQ_NONE)
NCR5380_write(DTC_CONTROL_REG, 0);
else
NCR5380_write(DTC_CONTROL_REG, CSR_5380_INTR);
NCR5380_write(DTC_BLK_CNT, len >> 7); /* Block count */
for (i = 0; len > 0; ++i) {
rtrc(5);
/* Poll until the host buffer can accept data. */
while (NCR5380_read(DTC_CONTROL_REG) & CSR_HOST_BUF_NOT_RDY)
++i;
rtrc(3);
memcpy_toio(base + DTC_DATA_BUF, src, 128);
src += 128;
len -= 128;
}
rtrc(4);
while (!(NCR5380_read(DTC_CONTROL_REG) & D_CR_ACCESS))
++i;
rtrc(6);
/* Wait until the last byte has been sent to the disk */
while (!(NCR5380_read(TARGET_COMMAND_REG) & TCR_LAST_BYTE_SENT))
++i;
rtrc(7);
/* Check for parity error here. fixme. */
NCR5380_write(MODE_REG, 0); /* Clear the operating mode */
rtrc(0);
if (i > dtc_wmaxi)
dtc_wmaxi = i;
return (0);
}
MODULE_LICENSE("GPL");
#include "NCR5380.c"
static int dtc_release(struct Scsi_Host *shost)
{
NCR5380_local_declare();
NCR5380_setup(shost);
if (shost->irq)
free_irq(shost->irq, shost);
NCR5380_exit(shost);
if (shost->io_port && shost->n_io_port)
release_region(shost->io_port, shost->n_io_port);
scsi_unregister(shost);
iounmap(base);
return 0;
}
static struct scsi_host_template driver_template = {
.name = "DTC 3180/3280 ",
.detect = dtc_detect,
.release = dtc_release,
.queuecommand = dtc_queue_command,
.eh_abort_handler = dtc_abort,
.eh_bus_reset_handler = dtc_bus_reset,
.bios_param = dtc_biosparam,
.can_queue = CAN_QUEUE,
.this_id = 7,
.sg_tablesize = SG_ALL,
.cmd_per_lun = CMD_PER_LUN,
.use_clustering = DISABLE_CLUSTERING,
};
#include "scsi_module.c"
| gpl-2.0 |
Pafcholini/Nadia-kernel-LL-N910F-EUR-LL-OpenSource | fs/ext2/xip.c | 5832 | 2034 | /*
* linux/fs/ext2/xip.c
*
* Copyright (C) 2005 IBM Corporation
* Author: Carsten Otte (cotte@de.ibm.com)
*/
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/genhd.h>
#include <linux/buffer_head.h>
#include <linux/blkdev.h>
#include "ext2.h"
#include "xip.h"
static inline int
__inode_direct_access(struct inode *inode, sector_t block,
void **kaddr, unsigned long *pfn)
{
struct block_device *bdev = inode->i_sb->s_bdev;
const struct block_device_operations *ops = bdev->bd_disk->fops;
sector_t sector;
sector = block * (PAGE_SIZE / 512); /* ext2 block to bdev sector */
BUG_ON(!ops->direct_access);
return ops->direct_access(bdev, sector, kaddr, pfn);
}
static inline int
__ext2_get_block(struct inode *inode, pgoff_t pgoff, int create,
sector_t *result)
{
struct buffer_head tmp;
int rc;
memset(&tmp, 0, sizeof(struct buffer_head));
rc = ext2_get_block(inode, pgoff, &tmp, create);
*result = tmp.b_blocknr;
/* did we get a sparse block (hole in the file)? */
if (!tmp.b_blocknr && !rc) {
BUG_ON(create);
rc = -ENODATA;
}
return rc;
}
int
ext2_clear_xip_target(struct inode *inode, sector_t block)
{
void *kaddr;
unsigned long pfn;
int rc;
rc = __inode_direct_access(inode, block, &kaddr, &pfn);
if (!rc)
clear_page(kaddr);
return rc;
}
void ext2_xip_verify_sb(struct super_block *sb)
{
struct ext2_sb_info *sbi = EXT2_SB(sb);
if ((sbi->s_mount_opt & EXT2_MOUNT_XIP) &&
!sb->s_bdev->bd_disk->fops->direct_access) {
sbi->s_mount_opt &= (~EXT2_MOUNT_XIP);
ext2_msg(sb, KERN_WARNING,
"warning: ignoring xip option - "
"not supported by bdev");
}
}
int ext2_get_xip_mem(struct address_space *mapping, pgoff_t pgoff, int create,
void **kmem, unsigned long *pfn)
{
int rc;
sector_t block;
/* first, retrieve the sector number */
rc = __ext2_get_block(mapping->host, pgoff, create, &block);
if (rc)
return rc;
/* retrieve address of the target data */
rc = __inode_direct_access(mapping->host, block, kmem, pfn);
return rc;
}
| gpl-2.0 |
namhyung/linux | arch/ia64/sn/kernel/sn2/timer.c | 8904 | 1525 | /*
* linux/arch/ia64/sn/kernel/sn2/timer.c
*
* Copyright (C) 2003 Silicon Graphics, Inc.
* Copyright (C) 2003 Hewlett-Packard Co
* David Mosberger <davidm@hpl.hp.com>: updated for new timer-interpolation infrastructure
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/time.h>
#include <linux/interrupt.h>
#include <linux/clocksource.h>
#include <asm/hw_irq.h>
#include <asm/timex.h>
#include <asm/sn/leds.h>
#include <asm/sn/shub_mmr.h>
#include <asm/sn/clksupport.h>
extern unsigned long sn_rtc_cycles_per_second;
static cycle_t read_sn2(struct clocksource *cs)
{
return (cycle_t)readq(RTC_COUNTER_ADDR);
}
static struct clocksource clocksource_sn2 = {
.name = "sn2_rtc",
.rating = 450,
.read = read_sn2,
.mask = (1LL << 55) - 1,
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
/*
* sn udelay uses the RTC instead of the ITC because the ITC is not
* synchronized across all CPUs, and the thread may migrate to another CPU
* if preemption is enabled.
*/
static void
ia64_sn_udelay (unsigned long usecs)
{
unsigned long start = rtc_time();
unsigned long end = start +
usecs * sn_rtc_cycles_per_second / 1000000;
while (time_before((unsigned long)rtc_time(), end))
cpu_relax();
}
void __init sn_timer_init(void)
{
clocksource_sn2.archdata.fsys_mmio = RTC_COUNTER_ADDR;
clocksource_register_hz(&clocksource_sn2, sn_rtc_cycles_per_second);
ia64_udelay = &ia64_sn_udelay;
}
| gpl-2.0 |
Jetson-TX1-AndroidTV/android_kernel_shield_tv_video4linux | net/netfilter/xt_pkttype.c | 13768 | 1686 | /* (C) 1999-2001 Michal Ludvig <michal@logix.cz>
*
* 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/skbuff.h>
#include <linux/if_ether.h>
#include <linux/if_packet.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/netfilter/xt_pkttype.h>
#include <linux/netfilter/x_tables.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Michal Ludvig <michal@logix.cz>");
MODULE_DESCRIPTION("Xtables: link layer packet type match");
MODULE_ALIAS("ipt_pkttype");
MODULE_ALIAS("ip6t_pkttype");
static bool
pkttype_mt(const struct sk_buff *skb, struct xt_action_param *par)
{
const struct xt_pkttype_info *info = par->matchinfo;
u_int8_t type;
if (skb->pkt_type != PACKET_LOOPBACK)
type = skb->pkt_type;
else if (par->family == NFPROTO_IPV4 &&
ipv4_is_multicast(ip_hdr(skb)->daddr))
type = PACKET_MULTICAST;
else if (par->family == NFPROTO_IPV6 &&
ipv6_hdr(skb)->daddr.s6_addr[0] == 0xFF)
type = PACKET_MULTICAST;
else
type = PACKET_BROADCAST;
return (type == info->pkttype) ^ info->invert;
}
static struct xt_match pkttype_mt_reg __read_mostly = {
.name = "pkttype",
.revision = 0,
.family = NFPROTO_UNSPEC,
.match = pkttype_mt,
.matchsize = sizeof(struct xt_pkttype_info),
.me = THIS_MODULE,
};
static int __init pkttype_mt_init(void)
{
return xt_register_match(&pkttype_mt_reg);
}
static void __exit pkttype_mt_exit(void)
{
xt_unregister_match(&pkttype_mt_reg);
}
module_init(pkttype_mt_init);
module_exit(pkttype_mt_exit);
| gpl-2.0 |
houstar/linux-3.8.8 | arch/avr32/mach-at32ap/at32ap700x.c | 201 | 54718 | /*
* Copyright (C) 2005-2006 Atmel 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/clk.h>
#include <linux/delay.h>
#include <linux/dw_dmac.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <linux/gpio.h>
#include <linux/spi/spi.h>
#include <linux/usb/atmel_usba_udc.h>
#include <mach/atmel-mci.h>
#include <linux/atmel-mci.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <mach/at32ap700x.h>
#include <mach/board.h>
#include <mach/hmatrix.h>
#include <mach/portmux.h>
#include <mach/sram.h>
#include <sound/atmel-abdac.h>
#include <sound/atmel-ac97c.h>
#include <video/atmel_lcdc.h>
#include "clock.h"
#include "pio.h"
#include "pm.h"
#define PBMEM(base) \
{ \
.start = base, \
.end = base + 0x3ff, \
.flags = IORESOURCE_MEM, \
}
#define IRQ(num) \
{ \
.start = num, \
.end = num, \
.flags = IORESOURCE_IRQ, \
}
#define NAMED_IRQ(num, _name) \
{ \
.start = num, \
.end = num, \
.name = _name, \
.flags = IORESOURCE_IRQ, \
}
/* REVISIT these assume *every* device supports DMA, but several
* don't ... tc, smc, pio, rtc, watchdog, pwm, ps2, and more.
*/
#define DEFINE_DEV(_name, _id) \
static u64 _name##_id##_dma_mask = DMA_BIT_MASK(32); \
static struct platform_device _name##_id##_device = { \
.name = #_name, \
.id = _id, \
.dev = { \
.dma_mask = &_name##_id##_dma_mask, \
.coherent_dma_mask = DMA_BIT_MASK(32), \
}, \
.resource = _name##_id##_resource, \
.num_resources = ARRAY_SIZE(_name##_id##_resource), \
}
#define DEFINE_DEV_DATA(_name, _id) \
static u64 _name##_id##_dma_mask = DMA_BIT_MASK(32); \
static struct platform_device _name##_id##_device = { \
.name = #_name, \
.id = _id, \
.dev = { \
.dma_mask = &_name##_id##_dma_mask, \
.platform_data = &_name##_id##_data, \
.coherent_dma_mask = DMA_BIT_MASK(32), \
}, \
.resource = _name##_id##_resource, \
.num_resources = ARRAY_SIZE(_name##_id##_resource), \
}
#define select_peripheral(port, pin_mask, periph, flags) \
at32_select_periph(GPIO_##port##_BASE, pin_mask, \
GPIO_##periph, flags)
#define DEV_CLK(_name, devname, bus, _index) \
static struct clk devname##_##_name = { \
.name = #_name, \
.dev = &devname##_device.dev, \
.parent = &bus##_clk, \
.mode = bus##_clk_mode, \
.get_rate = bus##_clk_get_rate, \
.index = _index, \
}
static DEFINE_SPINLOCK(pm_lock);
static struct clk osc0;
static struct clk osc1;
static unsigned long osc_get_rate(struct clk *clk)
{
return at32_board_osc_rates[clk->index];
}
static unsigned long pll_get_rate(struct clk *clk, unsigned long control)
{
unsigned long div, mul, rate;
div = PM_BFEXT(PLLDIV, control) + 1;
mul = PM_BFEXT(PLLMUL, control) + 1;
rate = clk->parent->get_rate(clk->parent);
rate = (rate + div / 2) / div;
rate *= mul;
return rate;
}
static long pll_set_rate(struct clk *clk, unsigned long rate,
u32 *pll_ctrl)
{
unsigned long mul;
unsigned long mul_best_fit = 0;
unsigned long div;
unsigned long div_min;
unsigned long div_max;
unsigned long div_best_fit = 0;
unsigned long base;
unsigned long pll_in;
unsigned long actual = 0;
unsigned long rate_error;
unsigned long rate_error_prev = ~0UL;
u32 ctrl;
/* Rate must be between 80 MHz and 200 Mhz. */
if (rate < 80000000UL || rate > 200000000UL)
return -EINVAL;
ctrl = PM_BF(PLLOPT, 4);
base = clk->parent->get_rate(clk->parent);
/* PLL input frequency must be between 6 MHz and 32 MHz. */
div_min = DIV_ROUND_UP(base, 32000000UL);
div_max = base / 6000000UL;
if (div_max < div_min)
return -EINVAL;
for (div = div_min; div <= div_max; div++) {
pll_in = (base + div / 2) / div;
mul = (rate + pll_in / 2) / pll_in;
if (mul == 0)
continue;
actual = pll_in * mul;
rate_error = abs(actual - rate);
if (rate_error < rate_error_prev) {
mul_best_fit = mul;
div_best_fit = div;
rate_error_prev = rate_error;
}
if (rate_error == 0)
break;
}
if (div_best_fit == 0)
return -EINVAL;
ctrl |= PM_BF(PLLMUL, mul_best_fit - 1);
ctrl |= PM_BF(PLLDIV, div_best_fit - 1);
ctrl |= PM_BF(PLLCOUNT, 16);
if (clk->parent == &osc1)
ctrl |= PM_BIT(PLLOSC);
*pll_ctrl = ctrl;
return actual;
}
static unsigned long pll0_get_rate(struct clk *clk)
{
u32 control;
control = pm_readl(PLL0);
return pll_get_rate(clk, control);
}
static void pll1_mode(struct clk *clk, int enabled)
{
unsigned long timeout;
u32 status;
u32 ctrl;
ctrl = pm_readl(PLL1);
if (enabled) {
if (!PM_BFEXT(PLLMUL, ctrl) && !PM_BFEXT(PLLDIV, ctrl)) {
pr_debug("clk %s: failed to enable, rate not set\n",
clk->name);
return;
}
ctrl |= PM_BIT(PLLEN);
pm_writel(PLL1, ctrl);
/* Wait for PLL lock. */
for (timeout = 10000; timeout; timeout--) {
status = pm_readl(ISR);
if (status & PM_BIT(LOCK1))
break;
udelay(10);
}
if (!(status & PM_BIT(LOCK1)))
printk(KERN_ERR "clk %s: timeout waiting for lock\n",
clk->name);
} else {
ctrl &= ~PM_BIT(PLLEN);
pm_writel(PLL1, ctrl);
}
}
static unsigned long pll1_get_rate(struct clk *clk)
{
u32 control;
control = pm_readl(PLL1);
return pll_get_rate(clk, control);
}
static long pll1_set_rate(struct clk *clk, unsigned long rate, int apply)
{
u32 ctrl = 0;
unsigned long actual_rate;
actual_rate = pll_set_rate(clk, rate, &ctrl);
if (apply) {
if (actual_rate != rate)
return -EINVAL;
if (clk->users > 0)
return -EBUSY;
pr_debug(KERN_INFO "clk %s: new rate %lu (actual rate %lu)\n",
clk->name, rate, actual_rate);
pm_writel(PLL1, ctrl);
}
return actual_rate;
}
static int pll1_set_parent(struct clk *clk, struct clk *parent)
{
u32 ctrl;
if (clk->users > 0)
return -EBUSY;
ctrl = pm_readl(PLL1);
WARN_ON(ctrl & PM_BIT(PLLEN));
if (parent == &osc0)
ctrl &= ~PM_BIT(PLLOSC);
else if (parent == &osc1)
ctrl |= PM_BIT(PLLOSC);
else
return -EINVAL;
pm_writel(PLL1, ctrl);
clk->parent = parent;
return 0;
}
/*
* The AT32AP7000 has five primary clock sources: One 32kHz
* oscillator, two crystal oscillators and two PLLs.
*/
static struct clk osc32k = {
.name = "osc32k",
.get_rate = osc_get_rate,
.users = 1,
.index = 0,
};
static struct clk osc0 = {
.name = "osc0",
.get_rate = osc_get_rate,
.users = 1,
.index = 1,
};
static struct clk osc1 = {
.name = "osc1",
.get_rate = osc_get_rate,
.index = 2,
};
static struct clk pll0 = {
.name = "pll0",
.get_rate = pll0_get_rate,
.parent = &osc0,
};
static struct clk pll1 = {
.name = "pll1",
.mode = pll1_mode,
.get_rate = pll1_get_rate,
.set_rate = pll1_set_rate,
.set_parent = pll1_set_parent,
.parent = &osc0,
};
/*
* The main clock can be either osc0 or pll0. The boot loader may
* have chosen one for us, so we don't really know which one until we
* have a look at the SM.
*/
static struct clk *main_clock;
/*
* Synchronous clocks are generated from the main clock. The clocks
* must satisfy the constraint
* fCPU >= fHSB >= fPB
* i.e. each clock must not be faster than its parent.
*/
static unsigned long bus_clk_get_rate(struct clk *clk, unsigned int shift)
{
return main_clock->get_rate(main_clock) >> shift;
};
static void cpu_clk_mode(struct clk *clk, int enabled)
{
unsigned long flags;
u32 mask;
spin_lock_irqsave(&pm_lock, flags);
mask = pm_readl(CPU_MASK);
if (enabled)
mask |= 1 << clk->index;
else
mask &= ~(1 << clk->index);
pm_writel(CPU_MASK, mask);
spin_unlock_irqrestore(&pm_lock, flags);
}
static unsigned long cpu_clk_get_rate(struct clk *clk)
{
unsigned long cksel, shift = 0;
cksel = pm_readl(CKSEL);
if (cksel & PM_BIT(CPUDIV))
shift = PM_BFEXT(CPUSEL, cksel) + 1;
return bus_clk_get_rate(clk, shift);
}
static long cpu_clk_set_rate(struct clk *clk, unsigned long rate, int apply)
{
u32 control;
unsigned long parent_rate, child_div, actual_rate, div;
parent_rate = clk->parent->get_rate(clk->parent);
control = pm_readl(CKSEL);
if (control & PM_BIT(HSBDIV))
child_div = 1 << (PM_BFEXT(HSBSEL, control) + 1);
else
child_div = 1;
if (rate > 3 * (parent_rate / 4) || child_div == 1) {
actual_rate = parent_rate;
control &= ~PM_BIT(CPUDIV);
} else {
unsigned int cpusel;
div = (parent_rate + rate / 2) / rate;
if (div > child_div)
div = child_div;
cpusel = (div > 1) ? (fls(div) - 2) : 0;
control = PM_BIT(CPUDIV) | PM_BFINS(CPUSEL, cpusel, control);
actual_rate = parent_rate / (1 << (cpusel + 1));
}
pr_debug("clk %s: new rate %lu (actual rate %lu)\n",
clk->name, rate, actual_rate);
if (apply)
pm_writel(CKSEL, control);
return actual_rate;
}
static void hsb_clk_mode(struct clk *clk, int enabled)
{
unsigned long flags;
u32 mask;
spin_lock_irqsave(&pm_lock, flags);
mask = pm_readl(HSB_MASK);
if (enabled)
mask |= 1 << clk->index;
else
mask &= ~(1 << clk->index);
pm_writel(HSB_MASK, mask);
spin_unlock_irqrestore(&pm_lock, flags);
}
static unsigned long hsb_clk_get_rate(struct clk *clk)
{
unsigned long cksel, shift = 0;
cksel = pm_readl(CKSEL);
if (cksel & PM_BIT(HSBDIV))
shift = PM_BFEXT(HSBSEL, cksel) + 1;
return bus_clk_get_rate(clk, shift);
}
void pba_clk_mode(struct clk *clk, int enabled)
{
unsigned long flags;
u32 mask;
spin_lock_irqsave(&pm_lock, flags);
mask = pm_readl(PBA_MASK);
if (enabled)
mask |= 1 << clk->index;
else
mask &= ~(1 << clk->index);
pm_writel(PBA_MASK, mask);
spin_unlock_irqrestore(&pm_lock, flags);
}
unsigned long pba_clk_get_rate(struct clk *clk)
{
unsigned long cksel, shift = 0;
cksel = pm_readl(CKSEL);
if (cksel & PM_BIT(PBADIV))
shift = PM_BFEXT(PBASEL, cksel) + 1;
return bus_clk_get_rate(clk, shift);
}
static void pbb_clk_mode(struct clk *clk, int enabled)
{
unsigned long flags;
u32 mask;
spin_lock_irqsave(&pm_lock, flags);
mask = pm_readl(PBB_MASK);
if (enabled)
mask |= 1 << clk->index;
else
mask &= ~(1 << clk->index);
pm_writel(PBB_MASK, mask);
spin_unlock_irqrestore(&pm_lock, flags);
}
static unsigned long pbb_clk_get_rate(struct clk *clk)
{
unsigned long cksel, shift = 0;
cksel = pm_readl(CKSEL);
if (cksel & PM_BIT(PBBDIV))
shift = PM_BFEXT(PBBSEL, cksel) + 1;
return bus_clk_get_rate(clk, shift);
}
static struct clk cpu_clk = {
.name = "cpu",
.get_rate = cpu_clk_get_rate,
.set_rate = cpu_clk_set_rate,
.users = 1,
};
static struct clk hsb_clk = {
.name = "hsb",
.parent = &cpu_clk,
.get_rate = hsb_clk_get_rate,
};
static struct clk pba_clk = {
.name = "pba",
.parent = &hsb_clk,
.mode = hsb_clk_mode,
.get_rate = pba_clk_get_rate,
.index = 1,
};
static struct clk pbb_clk = {
.name = "pbb",
.parent = &hsb_clk,
.mode = hsb_clk_mode,
.get_rate = pbb_clk_get_rate,
.users = 1,
.index = 2,
};
/* --------------------------------------------------------------------
* Generic Clock operations
* -------------------------------------------------------------------- */
static void genclk_mode(struct clk *clk, int enabled)
{
u32 control;
control = pm_readl(GCCTRL(clk->index));
if (enabled)
control |= PM_BIT(CEN);
else
control &= ~PM_BIT(CEN);
pm_writel(GCCTRL(clk->index), control);
}
static unsigned long genclk_get_rate(struct clk *clk)
{
u32 control;
unsigned long div = 1;
control = pm_readl(GCCTRL(clk->index));
if (control & PM_BIT(DIVEN))
div = 2 * (PM_BFEXT(DIV, control) + 1);
return clk->parent->get_rate(clk->parent) / div;
}
static long genclk_set_rate(struct clk *clk, unsigned long rate, int apply)
{
u32 control;
unsigned long parent_rate, actual_rate, div;
parent_rate = clk->parent->get_rate(clk->parent);
control = pm_readl(GCCTRL(clk->index));
if (rate > 3 * parent_rate / 4) {
actual_rate = parent_rate;
control &= ~PM_BIT(DIVEN);
} else {
div = (parent_rate + rate) / (2 * rate) - 1;
control = PM_BFINS(DIV, div, control) | PM_BIT(DIVEN);
actual_rate = parent_rate / (2 * (div + 1));
}
dev_dbg(clk->dev, "clk %s: new rate %lu (actual rate %lu)\n",
clk->name, rate, actual_rate);
if (apply)
pm_writel(GCCTRL(clk->index), control);
return actual_rate;
}
int genclk_set_parent(struct clk *clk, struct clk *parent)
{
u32 control;
dev_dbg(clk->dev, "clk %s: new parent %s (was %s)\n",
clk->name, parent->name, clk->parent->name);
control = pm_readl(GCCTRL(clk->index));
if (parent == &osc1 || parent == &pll1)
control |= PM_BIT(OSCSEL);
else if (parent == &osc0 || parent == &pll0)
control &= ~PM_BIT(OSCSEL);
else
return -EINVAL;
if (parent == &pll0 || parent == &pll1)
control |= PM_BIT(PLLSEL);
else
control &= ~PM_BIT(PLLSEL);
pm_writel(GCCTRL(clk->index), control);
clk->parent = parent;
return 0;
}
static void __init genclk_init_parent(struct clk *clk)
{
u32 control;
struct clk *parent;
BUG_ON(clk->index > 7);
control = pm_readl(GCCTRL(clk->index));
if (control & PM_BIT(OSCSEL))
parent = (control & PM_BIT(PLLSEL)) ? &pll1 : &osc1;
else
parent = (control & PM_BIT(PLLSEL)) ? &pll0 : &osc0;
clk->parent = parent;
}
static struct dw_dma_platform_data dw_dmac0_data = {
.nr_channels = 3,
.block_size = 4095U,
.nr_masters = 2,
.data_width = { 2, 2, 0, 0 },
};
static struct resource dw_dmac0_resource[] = {
PBMEM(0xff200000),
IRQ(2),
};
DEFINE_DEV_DATA(dw_dmac, 0);
DEV_CLK(hclk, dw_dmac0, hsb, 10);
/* --------------------------------------------------------------------
* System peripherals
* -------------------------------------------------------------------- */
static struct resource at32_pm0_resource[] = {
{
.start = 0xfff00000,
.end = 0xfff0007f,
.flags = IORESOURCE_MEM,
},
IRQ(20),
};
static struct resource at32ap700x_rtc0_resource[] = {
{
.start = 0xfff00080,
.end = 0xfff000af,
.flags = IORESOURCE_MEM,
},
IRQ(21),
};
static struct resource at32_wdt0_resource[] = {
{
.start = 0xfff000b0,
.end = 0xfff000cf,
.flags = IORESOURCE_MEM,
},
};
static struct resource at32_eic0_resource[] = {
{
.start = 0xfff00100,
.end = 0xfff0013f,
.flags = IORESOURCE_MEM,
},
IRQ(19),
};
DEFINE_DEV(at32_pm, 0);
DEFINE_DEV(at32ap700x_rtc, 0);
DEFINE_DEV(at32_wdt, 0);
DEFINE_DEV(at32_eic, 0);
/*
* Peripheral clock for PM, RTC, WDT and EIC. PM will ensure that this
* is always running.
*/
static struct clk at32_pm_pclk = {
.name = "pclk",
.dev = &at32_pm0_device.dev,
.parent = &pbb_clk,
.mode = pbb_clk_mode,
.get_rate = pbb_clk_get_rate,
.users = 1,
.index = 0,
};
static struct resource intc0_resource[] = {
PBMEM(0xfff00400),
};
struct platform_device at32_intc0_device = {
.name = "intc",
.id = 0,
.resource = intc0_resource,
.num_resources = ARRAY_SIZE(intc0_resource),
};
DEV_CLK(pclk, at32_intc0, pbb, 1);
static struct clk ebi_clk = {
.name = "ebi",
.parent = &hsb_clk,
.mode = hsb_clk_mode,
.get_rate = hsb_clk_get_rate,
.users = 1,
};
static struct clk hramc_clk = {
.name = "hramc",
.parent = &hsb_clk,
.mode = hsb_clk_mode,
.get_rate = hsb_clk_get_rate,
.users = 1,
.index = 3,
};
static struct clk sdramc_clk = {
.name = "sdramc_clk",
.parent = &pbb_clk,
.mode = pbb_clk_mode,
.get_rate = pbb_clk_get_rate,
.users = 1,
.index = 14,
};
static struct resource smc0_resource[] = {
PBMEM(0xfff03400),
};
DEFINE_DEV(smc, 0);
DEV_CLK(pclk, smc0, pbb, 13);
DEV_CLK(mck, smc0, hsb, 0);
static struct platform_device pdc_device = {
.name = "pdc",
.id = 0,
};
DEV_CLK(hclk, pdc, hsb, 4);
DEV_CLK(pclk, pdc, pba, 16);
static struct clk pico_clk = {
.name = "pico",
.parent = &cpu_clk,
.mode = cpu_clk_mode,
.get_rate = cpu_clk_get_rate,
.users = 1,
};
/* --------------------------------------------------------------------
* HMATRIX
* -------------------------------------------------------------------- */
struct clk at32_hmatrix_clk = {
.name = "hmatrix_clk",
.parent = &pbb_clk,
.mode = pbb_clk_mode,
.get_rate = pbb_clk_get_rate,
.index = 2,
.users = 1,
};
/*
* Set bits in the HMATRIX Special Function Register (SFR) used by the
* External Bus Interface (EBI). This can be used to enable special
* features like CompactFlash support, NAND Flash support, etc. on
* certain chipselects.
*/
static inline void set_ebi_sfr_bits(u32 mask)
{
hmatrix_sfr_set_bits(HMATRIX_SLAVE_EBI, mask);
}
/* --------------------------------------------------------------------
* Timer/Counter (TC)
* -------------------------------------------------------------------- */
static struct resource at32_tcb0_resource[] = {
PBMEM(0xfff00c00),
IRQ(22),
};
static struct platform_device at32_tcb0_device = {
.name = "atmel_tcb",
.id = 0,
.resource = at32_tcb0_resource,
.num_resources = ARRAY_SIZE(at32_tcb0_resource),
};
DEV_CLK(t0_clk, at32_tcb0, pbb, 3);
static struct resource at32_tcb1_resource[] = {
PBMEM(0xfff01000),
IRQ(23),
};
static struct platform_device at32_tcb1_device = {
.name = "atmel_tcb",
.id = 1,
.resource = at32_tcb1_resource,
.num_resources = ARRAY_SIZE(at32_tcb1_resource),
};
DEV_CLK(t0_clk, at32_tcb1, pbb, 4);
/* --------------------------------------------------------------------
* PIO
* -------------------------------------------------------------------- */
static struct resource pio0_resource[] = {
PBMEM(0xffe02800),
IRQ(13),
};
DEFINE_DEV(pio, 0);
DEV_CLK(mck, pio0, pba, 10);
static struct resource pio1_resource[] = {
PBMEM(0xffe02c00),
IRQ(14),
};
DEFINE_DEV(pio, 1);
DEV_CLK(mck, pio1, pba, 11);
static struct resource pio2_resource[] = {
PBMEM(0xffe03000),
IRQ(15),
};
DEFINE_DEV(pio, 2);
DEV_CLK(mck, pio2, pba, 12);
static struct resource pio3_resource[] = {
PBMEM(0xffe03400),
IRQ(16),
};
DEFINE_DEV(pio, 3);
DEV_CLK(mck, pio3, pba, 13);
static struct resource pio4_resource[] = {
PBMEM(0xffe03800),
IRQ(17),
};
DEFINE_DEV(pio, 4);
DEV_CLK(mck, pio4, pba, 14);
static int __init system_device_init(void)
{
platform_device_register(&at32_pm0_device);
platform_device_register(&at32_intc0_device);
platform_device_register(&at32ap700x_rtc0_device);
platform_device_register(&at32_wdt0_device);
platform_device_register(&at32_eic0_device);
platform_device_register(&smc0_device);
platform_device_register(&pdc_device);
platform_device_register(&dw_dmac0_device);
platform_device_register(&at32_tcb0_device);
platform_device_register(&at32_tcb1_device);
platform_device_register(&pio0_device);
platform_device_register(&pio1_device);
platform_device_register(&pio2_device);
platform_device_register(&pio3_device);
platform_device_register(&pio4_device);
return 0;
}
core_initcall(system_device_init);
/* --------------------------------------------------------------------
* PSIF
* -------------------------------------------------------------------- */
static struct resource atmel_psif0_resource[] __initdata = {
{
.start = 0xffe03c00,
.end = 0xffe03cff,
.flags = IORESOURCE_MEM,
},
IRQ(18),
};
static struct clk atmel_psif0_pclk = {
.name = "pclk",
.parent = &pba_clk,
.mode = pba_clk_mode,
.get_rate = pba_clk_get_rate,
.index = 15,
};
static struct resource atmel_psif1_resource[] __initdata = {
{
.start = 0xffe03d00,
.end = 0xffe03dff,
.flags = IORESOURCE_MEM,
},
IRQ(18),
};
static struct clk atmel_psif1_pclk = {
.name = "pclk",
.parent = &pba_clk,
.mode = pba_clk_mode,
.get_rate = pba_clk_get_rate,
.index = 15,
};
struct platform_device *__init at32_add_device_psif(unsigned int id)
{
struct platform_device *pdev;
u32 pin_mask;
if (!(id == 0 || id == 1))
return NULL;
pdev = platform_device_alloc("atmel_psif", id);
if (!pdev)
return NULL;
switch (id) {
case 0:
pin_mask = (1 << 8) | (1 << 9); /* CLOCK & DATA */
if (platform_device_add_resources(pdev, atmel_psif0_resource,
ARRAY_SIZE(atmel_psif0_resource)))
goto err_add_resources;
atmel_psif0_pclk.dev = &pdev->dev;
select_peripheral(PIOA, pin_mask, PERIPH_A, 0);
break;
case 1:
pin_mask = (1 << 11) | (1 << 12); /* CLOCK & DATA */
if (platform_device_add_resources(pdev, atmel_psif1_resource,
ARRAY_SIZE(atmel_psif1_resource)))
goto err_add_resources;
atmel_psif1_pclk.dev = &pdev->dev;
select_peripheral(PIOB, pin_mask, PERIPH_A, 0);
break;
default:
return NULL;
}
platform_device_add(pdev);
return pdev;
err_add_resources:
platform_device_put(pdev);
return NULL;
}
/* --------------------------------------------------------------------
* USART
* -------------------------------------------------------------------- */
static struct atmel_uart_data atmel_usart0_data = {
.use_dma_tx = 1,
.use_dma_rx = 1,
};
static struct resource atmel_usart0_resource[] = {
PBMEM(0xffe00c00),
IRQ(6),
};
DEFINE_DEV_DATA(atmel_usart, 0);
DEV_CLK(usart, atmel_usart0, pba, 3);
static struct atmel_uart_data atmel_usart1_data = {
.use_dma_tx = 1,
.use_dma_rx = 1,
};
static struct resource atmel_usart1_resource[] = {
PBMEM(0xffe01000),
IRQ(7),
};
DEFINE_DEV_DATA(atmel_usart, 1);
DEV_CLK(usart, atmel_usart1, pba, 4);
static struct atmel_uart_data atmel_usart2_data = {
.use_dma_tx = 1,
.use_dma_rx = 1,
};
static struct resource atmel_usart2_resource[] = {
PBMEM(0xffe01400),
IRQ(8),
};
DEFINE_DEV_DATA(atmel_usart, 2);
DEV_CLK(usart, atmel_usart2, pba, 5);
static struct atmel_uart_data atmel_usart3_data = {
.use_dma_tx = 1,
.use_dma_rx = 1,
};
static struct resource atmel_usart3_resource[] = {
PBMEM(0xffe01800),
IRQ(9),
};
DEFINE_DEV_DATA(atmel_usart, 3);
DEV_CLK(usart, atmel_usart3, pba, 6);
static inline void configure_usart0_pins(int flags)
{
u32 pin_mask = (1 << 8) | (1 << 9); /* RXD & TXD */
if (flags & ATMEL_USART_RTS) pin_mask |= (1 << 6);
if (flags & ATMEL_USART_CTS) pin_mask |= (1 << 7);
if (flags & ATMEL_USART_CLK) pin_mask |= (1 << 10);
select_peripheral(PIOA, pin_mask, PERIPH_B, AT32_GPIOF_PULLUP);
}
static inline void configure_usart1_pins(int flags)
{
u32 pin_mask = (1 << 17) | (1 << 18); /* RXD & TXD */
if (flags & ATMEL_USART_RTS) pin_mask |= (1 << 19);
if (flags & ATMEL_USART_CTS) pin_mask |= (1 << 20);
if (flags & ATMEL_USART_CLK) pin_mask |= (1 << 16);
select_peripheral(PIOA, pin_mask, PERIPH_A, AT32_GPIOF_PULLUP);
}
static inline void configure_usart2_pins(int flags)
{
u32 pin_mask = (1 << 26) | (1 << 27); /* RXD & TXD */
if (flags & ATMEL_USART_RTS) pin_mask |= (1 << 30);
if (flags & ATMEL_USART_CTS) pin_mask |= (1 << 29);
if (flags & ATMEL_USART_CLK) pin_mask |= (1 << 28);
select_peripheral(PIOB, pin_mask, PERIPH_B, AT32_GPIOF_PULLUP);
}
static inline void configure_usart3_pins(int flags)
{
u32 pin_mask = (1 << 18) | (1 << 17); /* RXD & TXD */
if (flags & ATMEL_USART_RTS) pin_mask |= (1 << 16);
if (flags & ATMEL_USART_CTS) pin_mask |= (1 << 15);
if (flags & ATMEL_USART_CLK) pin_mask |= (1 << 19);
select_peripheral(PIOB, pin_mask, PERIPH_B, AT32_GPIOF_PULLUP);
}
static struct platform_device *__initdata at32_usarts[4];
void __init at32_map_usart(unsigned int hw_id, unsigned int line, int flags)
{
struct platform_device *pdev;
struct atmel_uart_data *pdata;
switch (hw_id) {
case 0:
pdev = &atmel_usart0_device;
configure_usart0_pins(flags);
break;
case 1:
pdev = &atmel_usart1_device;
configure_usart1_pins(flags);
break;
case 2:
pdev = &atmel_usart2_device;
configure_usart2_pins(flags);
break;
case 3:
pdev = &atmel_usart3_device;
configure_usart3_pins(flags);
break;
default:
return;
}
if (PXSEG(pdev->resource[0].start) == P4SEG) {
/* Addresses in the P4 segment are permanently mapped 1:1 */
struct atmel_uart_data *data = pdev->dev.platform_data;
data->regs = (void __iomem *)pdev->resource[0].start;
}
pdev->id = line;
pdata = pdev->dev.platform_data;
pdata->num = line;
at32_usarts[line] = pdev;
}
struct platform_device *__init at32_add_device_usart(unsigned int id)
{
platform_device_register(at32_usarts[id]);
return at32_usarts[id];
}
void __init at32_setup_serial_console(unsigned int usart_id)
{
atmel_default_console_device = at32_usarts[usart_id];
}
/* --------------------------------------------------------------------
* Ethernet
* -------------------------------------------------------------------- */
#ifdef CONFIG_CPU_AT32AP7000
static struct macb_platform_data macb0_data;
static struct resource macb0_resource[] = {
PBMEM(0xfff01800),
IRQ(25),
};
DEFINE_DEV_DATA(macb, 0);
DEV_CLK(hclk, macb0, hsb, 8);
DEV_CLK(pclk, macb0, pbb, 6);
static struct macb_platform_data macb1_data;
static struct resource macb1_resource[] = {
PBMEM(0xfff01c00),
IRQ(26),
};
DEFINE_DEV_DATA(macb, 1);
DEV_CLK(hclk, macb1, hsb, 9);
DEV_CLK(pclk, macb1, pbb, 7);
struct platform_device *__init
at32_add_device_eth(unsigned int id, struct macb_platform_data *data)
{
struct platform_device *pdev;
u32 pin_mask;
switch (id) {
case 0:
pdev = &macb0_device;
pin_mask = (1 << 3); /* TXD0 */
pin_mask |= (1 << 4); /* TXD1 */
pin_mask |= (1 << 7); /* TXEN */
pin_mask |= (1 << 8); /* TXCK */
pin_mask |= (1 << 9); /* RXD0 */
pin_mask |= (1 << 10); /* RXD1 */
pin_mask |= (1 << 13); /* RXER */
pin_mask |= (1 << 15); /* RXDV */
pin_mask |= (1 << 16); /* MDC */
pin_mask |= (1 << 17); /* MDIO */
if (!data->is_rmii) {
pin_mask |= (1 << 0); /* COL */
pin_mask |= (1 << 1); /* CRS */
pin_mask |= (1 << 2); /* TXER */
pin_mask |= (1 << 5); /* TXD2 */
pin_mask |= (1 << 6); /* TXD3 */
pin_mask |= (1 << 11); /* RXD2 */
pin_mask |= (1 << 12); /* RXD3 */
pin_mask |= (1 << 14); /* RXCK */
#ifndef CONFIG_BOARD_MIMC200
pin_mask |= (1 << 18); /* SPD */
#endif
}
select_peripheral(PIOC, pin_mask, PERIPH_A, 0);
break;
case 1:
pdev = &macb1_device;
pin_mask = (1 << 13); /* TXD0 */
pin_mask |= (1 << 14); /* TXD1 */
pin_mask |= (1 << 11); /* TXEN */
pin_mask |= (1 << 12); /* TXCK */
pin_mask |= (1 << 10); /* RXD0 */
pin_mask |= (1 << 6); /* RXD1 */
pin_mask |= (1 << 5); /* RXER */
pin_mask |= (1 << 4); /* RXDV */
pin_mask |= (1 << 3); /* MDC */
pin_mask |= (1 << 2); /* MDIO */
#ifndef CONFIG_BOARD_MIMC200
if (!data->is_rmii)
pin_mask |= (1 << 15); /* SPD */
#endif
select_peripheral(PIOD, pin_mask, PERIPH_B, 0);
if (!data->is_rmii) {
pin_mask = (1 << 19); /* COL */
pin_mask |= (1 << 23); /* CRS */
pin_mask |= (1 << 26); /* TXER */
pin_mask |= (1 << 27); /* TXD2 */
pin_mask |= (1 << 28); /* TXD3 */
pin_mask |= (1 << 29); /* RXD2 */
pin_mask |= (1 << 30); /* RXD3 */
pin_mask |= (1 << 24); /* RXCK */
select_peripheral(PIOC, pin_mask, PERIPH_B, 0);
}
break;
default:
return NULL;
}
memcpy(pdev->dev.platform_data, data, sizeof(struct macb_platform_data));
platform_device_register(pdev);
return pdev;
}
#endif
/* --------------------------------------------------------------------
* SPI
* -------------------------------------------------------------------- */
static struct resource atmel_spi0_resource[] = {
PBMEM(0xffe00000),
IRQ(3),
};
DEFINE_DEV(atmel_spi, 0);
DEV_CLK(spi_clk, atmel_spi0, pba, 0);
static struct resource atmel_spi1_resource[] = {
PBMEM(0xffe00400),
IRQ(4),
};
DEFINE_DEV(atmel_spi, 1);
DEV_CLK(spi_clk, atmel_spi1, pba, 1);
void __init
at32_spi_setup_slaves(unsigned int bus_num, struct spi_board_info *b, unsigned int n)
{
/*
* Manage the chipselects as GPIOs, normally using the same pins
* the SPI controller expects; but boards can use other pins.
*/
static u8 __initdata spi_pins[][4] = {
{ GPIO_PIN_PA(3), GPIO_PIN_PA(4),
GPIO_PIN_PA(5), GPIO_PIN_PA(20) },
{ GPIO_PIN_PB(2), GPIO_PIN_PB(3),
GPIO_PIN_PB(4), GPIO_PIN_PA(27) },
};
unsigned int pin, mode;
/* There are only 2 SPI controllers */
if (bus_num > 1)
return;
for (; n; n--, b++) {
b->bus_num = bus_num;
if (b->chip_select >= 4)
continue;
pin = (unsigned)b->controller_data;
if (!pin) {
pin = spi_pins[bus_num][b->chip_select];
b->controller_data = (void *)pin;
}
mode = AT32_GPIOF_OUTPUT;
if (!(b->mode & SPI_CS_HIGH))
mode |= AT32_GPIOF_HIGH;
at32_select_gpio(pin, mode);
}
}
struct platform_device *__init
at32_add_device_spi(unsigned int id, struct spi_board_info *b, unsigned int n)
{
struct platform_device *pdev;
u32 pin_mask;
switch (id) {
case 0:
pdev = &atmel_spi0_device;
pin_mask = (1 << 1) | (1 << 2); /* MOSI & SCK */
/* pullup MISO so a level is always defined */
select_peripheral(PIOA, (1 << 0), PERIPH_A, AT32_GPIOF_PULLUP);
select_peripheral(PIOA, pin_mask, PERIPH_A, 0);
at32_spi_setup_slaves(0, b, n);
break;
case 1:
pdev = &atmel_spi1_device;
pin_mask = (1 << 1) | (1 << 5); /* MOSI */
/* pullup MISO so a level is always defined */
select_peripheral(PIOB, (1 << 0), PERIPH_B, AT32_GPIOF_PULLUP);
select_peripheral(PIOB, pin_mask, PERIPH_B, 0);
at32_spi_setup_slaves(1, b, n);
break;
default:
return NULL;
}
spi_register_board_info(b, n);
platform_device_register(pdev);
return pdev;
}
/* --------------------------------------------------------------------
* TWI
* -------------------------------------------------------------------- */
static struct resource atmel_twi0_resource[] __initdata = {
PBMEM(0xffe00800),
IRQ(5),
};
static struct clk atmel_twi0_pclk = {
.name = "twi_pclk",
.parent = &pba_clk,
.mode = pba_clk_mode,
.get_rate = pba_clk_get_rate,
.index = 2,
};
struct platform_device *__init at32_add_device_twi(unsigned int id,
struct i2c_board_info *b,
unsigned int n)
{
struct platform_device *pdev;
u32 pin_mask;
if (id != 0)
return NULL;
pdev = platform_device_alloc("atmel_twi", id);
if (!pdev)
return NULL;
if (platform_device_add_resources(pdev, atmel_twi0_resource,
ARRAY_SIZE(atmel_twi0_resource)))
goto err_add_resources;
pin_mask = (1 << 6) | (1 << 7); /* SDA & SDL */
select_peripheral(PIOA, pin_mask, PERIPH_A, 0);
atmel_twi0_pclk.dev = &pdev->dev;
if (b)
i2c_register_board_info(id, b, n);
platform_device_add(pdev);
return pdev;
err_add_resources:
platform_device_put(pdev);
return NULL;
}
/* --------------------------------------------------------------------
* MMC
* -------------------------------------------------------------------- */
static struct resource atmel_mci0_resource[] __initdata = {
PBMEM(0xfff02400),
IRQ(28),
};
static struct clk atmel_mci0_pclk = {
.name = "mci_clk",
.parent = &pbb_clk,
.mode = pbb_clk_mode,
.get_rate = pbb_clk_get_rate,
.index = 9,
};
struct platform_device *__init
at32_add_device_mci(unsigned int id, struct mci_platform_data *data)
{
struct platform_device *pdev;
struct mci_dma_data *slave;
u32 pioa_mask;
u32 piob_mask;
if (id != 0 || !data)
return NULL;
/* Must have at least one usable slot */
if (!data->slot[0].bus_width && !data->slot[1].bus_width)
return NULL;
pdev = platform_device_alloc("atmel_mci", id);
if (!pdev)
goto fail;
if (platform_device_add_resources(pdev, atmel_mci0_resource,
ARRAY_SIZE(atmel_mci0_resource)))
goto fail;
slave = kzalloc(sizeof(struct mci_dma_data), GFP_KERNEL);
if (!slave)
goto fail;
slave->sdata.dma_dev = &dw_dmac0_device.dev;
slave->sdata.cfg_hi = (DWC_CFGH_SRC_PER(0)
| DWC_CFGH_DST_PER(1));
slave->sdata.cfg_lo &= ~(DWC_CFGL_HS_DST_POL
| DWC_CFGL_HS_SRC_POL);
data->dma_slave = slave;
if (platform_device_add_data(pdev, data,
sizeof(struct mci_platform_data)))
goto fail_free;
/* CLK line is common to both slots */
pioa_mask = 1 << 10;
switch (data->slot[0].bus_width) {
case 4:
pioa_mask |= 1 << 13; /* DATA1 */
pioa_mask |= 1 << 14; /* DATA2 */
pioa_mask |= 1 << 15; /* DATA3 */
/* fall through */
case 1:
pioa_mask |= 1 << 11; /* CMD */
pioa_mask |= 1 << 12; /* DATA0 */
if (gpio_is_valid(data->slot[0].detect_pin))
at32_select_gpio(data->slot[0].detect_pin, 0);
if (gpio_is_valid(data->slot[0].wp_pin))
at32_select_gpio(data->slot[0].wp_pin, 0);
break;
case 0:
/* Slot is unused */
break;
default:
goto fail_free;
}
select_peripheral(PIOA, pioa_mask, PERIPH_A, 0);
piob_mask = 0;
switch (data->slot[1].bus_width) {
case 4:
piob_mask |= 1 << 8; /* DATA1 */
piob_mask |= 1 << 9; /* DATA2 */
piob_mask |= 1 << 10; /* DATA3 */
/* fall through */
case 1:
piob_mask |= 1 << 6; /* CMD */
piob_mask |= 1 << 7; /* DATA0 */
select_peripheral(PIOB, piob_mask, PERIPH_B, 0);
if (gpio_is_valid(data->slot[1].detect_pin))
at32_select_gpio(data->slot[1].detect_pin, 0);
if (gpio_is_valid(data->slot[1].wp_pin))
at32_select_gpio(data->slot[1].wp_pin, 0);
break;
case 0:
/* Slot is unused */
break;
default:
if (!data->slot[0].bus_width)
goto fail_free;
data->slot[1].bus_width = 0;
break;
}
atmel_mci0_pclk.dev = &pdev->dev;
platform_device_add(pdev);
return pdev;
fail_free:
kfree(slave);
fail:
data->dma_slave = NULL;
platform_device_put(pdev);
return NULL;
}
/* --------------------------------------------------------------------
* LCDC
* -------------------------------------------------------------------- */
#if defined(CONFIG_CPU_AT32AP7000) || defined(CONFIG_CPU_AT32AP7002)
static struct atmel_lcdfb_info atmel_lcdfb0_data;
static struct resource atmel_lcdfb0_resource[] = {
{
.start = 0xff000000,
.end = 0xff000fff,
.flags = IORESOURCE_MEM,
},
IRQ(1),
{
/* Placeholder for pre-allocated fb memory */
.start = 0x00000000,
.end = 0x00000000,
.flags = 0,
},
};
DEFINE_DEV_DATA(atmel_lcdfb, 0);
DEV_CLK(hck1, atmel_lcdfb0, hsb, 7);
static struct clk atmel_lcdfb0_pixclk = {
.name = "lcdc_clk",
.dev = &atmel_lcdfb0_device.dev,
.mode = genclk_mode,
.get_rate = genclk_get_rate,
.set_rate = genclk_set_rate,
.set_parent = genclk_set_parent,
.index = 7,
};
struct platform_device *__init
at32_add_device_lcdc(unsigned int id, struct atmel_lcdfb_info *data,
unsigned long fbmem_start, unsigned long fbmem_len,
u64 pin_mask)
{
struct platform_device *pdev;
struct atmel_lcdfb_info *info;
struct fb_monspecs *monspecs;
struct fb_videomode *modedb;
unsigned int modedb_size;
u32 portc_mask, portd_mask, porte_mask;
/*
* Do a deep copy of the fb data, monspecs and modedb. Make
* sure all allocations are done before setting up the
* portmux.
*/
monspecs = kmemdup(data->default_monspecs,
sizeof(struct fb_monspecs), GFP_KERNEL);
if (!monspecs)
return NULL;
modedb_size = sizeof(struct fb_videomode) * monspecs->modedb_len;
modedb = kmemdup(monspecs->modedb, modedb_size, GFP_KERNEL);
if (!modedb)
goto err_dup_modedb;
monspecs->modedb = modedb;
switch (id) {
case 0:
pdev = &atmel_lcdfb0_device;
if (pin_mask == 0ULL)
/* Default to "full" lcdc control signals and 24bit */
pin_mask = ATMEL_LCDC_PRI_24BIT | ATMEL_LCDC_PRI_CONTROL;
/* LCDC on port C */
portc_mask = pin_mask & 0xfff80000;
select_peripheral(PIOC, portc_mask, PERIPH_A, 0);
/* LCDC on port D */
portd_mask = pin_mask & 0x0003ffff;
select_peripheral(PIOD, portd_mask, PERIPH_A, 0);
/* LCDC on port E */
porte_mask = (pin_mask >> 32) & 0x0007ffff;
select_peripheral(PIOE, porte_mask, PERIPH_B, 0);
clk_set_parent(&atmel_lcdfb0_pixclk, &pll0);
clk_set_rate(&atmel_lcdfb0_pixclk, clk_get_rate(&pll0));
break;
default:
goto err_invalid_id;
}
if (fbmem_len) {
pdev->resource[2].start = fbmem_start;
pdev->resource[2].end = fbmem_start + fbmem_len - 1;
pdev->resource[2].flags = IORESOURCE_MEM;
}
info = pdev->dev.platform_data;
memcpy(info, data, sizeof(struct atmel_lcdfb_info));
info->default_monspecs = monspecs;
platform_device_register(pdev);
return pdev;
err_invalid_id:
kfree(modedb);
err_dup_modedb:
kfree(monspecs);
return NULL;
}
#endif
/* --------------------------------------------------------------------
* PWM
* -------------------------------------------------------------------- */
static struct resource atmel_pwm0_resource[] __initdata = {
PBMEM(0xfff01400),
IRQ(24),
};
static struct clk atmel_pwm0_mck = {
.name = "pwm_clk",
.parent = &pbb_clk,
.mode = pbb_clk_mode,
.get_rate = pbb_clk_get_rate,
.index = 5,
};
struct platform_device *__init at32_add_device_pwm(u32 mask)
{
struct platform_device *pdev;
u32 pin_mask;
if (!mask)
return NULL;
pdev = platform_device_alloc("atmel_pwm", 0);
if (!pdev)
return NULL;
if (platform_device_add_resources(pdev, atmel_pwm0_resource,
ARRAY_SIZE(atmel_pwm0_resource)))
goto out_free_pdev;
if (platform_device_add_data(pdev, &mask, sizeof(mask)))
goto out_free_pdev;
pin_mask = 0;
if (mask & (1 << 0))
pin_mask |= (1 << 28);
if (mask & (1 << 1))
pin_mask |= (1 << 29);
if (pin_mask > 0)
select_peripheral(PIOA, pin_mask, PERIPH_A, 0);
pin_mask = 0;
if (mask & (1 << 2))
pin_mask |= (1 << 21);
if (mask & (1 << 3))
pin_mask |= (1 << 22);
if (pin_mask > 0)
select_peripheral(PIOA, pin_mask, PERIPH_B, 0);
atmel_pwm0_mck.dev = &pdev->dev;
platform_device_add(pdev);
return pdev;
out_free_pdev:
platform_device_put(pdev);
return NULL;
}
/* --------------------------------------------------------------------
* SSC
* -------------------------------------------------------------------- */
static struct resource ssc0_resource[] = {
PBMEM(0xffe01c00),
IRQ(10),
};
DEFINE_DEV(ssc, 0);
DEV_CLK(pclk, ssc0, pba, 7);
static struct resource ssc1_resource[] = {
PBMEM(0xffe02000),
IRQ(11),
};
DEFINE_DEV(ssc, 1);
DEV_CLK(pclk, ssc1, pba, 8);
static struct resource ssc2_resource[] = {
PBMEM(0xffe02400),
IRQ(12),
};
DEFINE_DEV(ssc, 2);
DEV_CLK(pclk, ssc2, pba, 9);
struct platform_device *__init
at32_add_device_ssc(unsigned int id, unsigned int flags)
{
struct platform_device *pdev;
u32 pin_mask = 0;
switch (id) {
case 0:
pdev = &ssc0_device;
if (flags & ATMEL_SSC_RF)
pin_mask |= (1 << 21); /* RF */
if (flags & ATMEL_SSC_RK)
pin_mask |= (1 << 22); /* RK */
if (flags & ATMEL_SSC_TK)
pin_mask |= (1 << 23); /* TK */
if (flags & ATMEL_SSC_TF)
pin_mask |= (1 << 24); /* TF */
if (flags & ATMEL_SSC_TD)
pin_mask |= (1 << 25); /* TD */
if (flags & ATMEL_SSC_RD)
pin_mask |= (1 << 26); /* RD */
if (pin_mask > 0)
select_peripheral(PIOA, pin_mask, PERIPH_A, 0);
break;
case 1:
pdev = &ssc1_device;
if (flags & ATMEL_SSC_RF)
pin_mask |= (1 << 0); /* RF */
if (flags & ATMEL_SSC_RK)
pin_mask |= (1 << 1); /* RK */
if (flags & ATMEL_SSC_TK)
pin_mask |= (1 << 2); /* TK */
if (flags & ATMEL_SSC_TF)
pin_mask |= (1 << 3); /* TF */
if (flags & ATMEL_SSC_TD)
pin_mask |= (1 << 4); /* TD */
if (flags & ATMEL_SSC_RD)
pin_mask |= (1 << 5); /* RD */
if (pin_mask > 0)
select_peripheral(PIOA, pin_mask, PERIPH_B, 0);
break;
case 2:
pdev = &ssc2_device;
if (flags & ATMEL_SSC_TD)
pin_mask |= (1 << 13); /* TD */
if (flags & ATMEL_SSC_RD)
pin_mask |= (1 << 14); /* RD */
if (flags & ATMEL_SSC_TK)
pin_mask |= (1 << 15); /* TK */
if (flags & ATMEL_SSC_TF)
pin_mask |= (1 << 16); /* TF */
if (flags & ATMEL_SSC_RF)
pin_mask |= (1 << 17); /* RF */
if (flags & ATMEL_SSC_RK)
pin_mask |= (1 << 18); /* RK */
if (pin_mask > 0)
select_peripheral(PIOB, pin_mask, PERIPH_A, 0);
break;
default:
return NULL;
}
platform_device_register(pdev);
return pdev;
}
/* --------------------------------------------------------------------
* USB Device Controller
* -------------------------------------------------------------------- */
static struct resource usba0_resource[] __initdata = {
{
.start = 0xff300000,
.end = 0xff3fffff,
.flags = IORESOURCE_MEM,
}, {
.start = 0xfff03000,
.end = 0xfff033ff,
.flags = IORESOURCE_MEM,
},
IRQ(31),
};
static struct clk usba0_pclk = {
.name = "pclk",
.parent = &pbb_clk,
.mode = pbb_clk_mode,
.get_rate = pbb_clk_get_rate,
.index = 12,
};
static struct clk usba0_hclk = {
.name = "hclk",
.parent = &hsb_clk,
.mode = hsb_clk_mode,
.get_rate = hsb_clk_get_rate,
.index = 6,
};
#define EP(nam, idx, maxpkt, maxbk, dma, isoc) \
[idx] = { \
.name = nam, \
.index = idx, \
.fifo_size = maxpkt, \
.nr_banks = maxbk, \
.can_dma = dma, \
.can_isoc = isoc, \
}
static struct usba_ep_data at32_usba_ep[] __initdata = {
EP("ep0", 0, 64, 1, 0, 0),
EP("ep1", 1, 512, 2, 1, 1),
EP("ep2", 2, 512, 2, 1, 1),
EP("ep3-int", 3, 64, 3, 1, 0),
EP("ep4-int", 4, 64, 3, 1, 0),
EP("ep5", 5, 1024, 3, 1, 1),
EP("ep6", 6, 1024, 3, 1, 1),
};
#undef EP
struct platform_device *__init
at32_add_device_usba(unsigned int id, struct usba_platform_data *data)
{
/*
* pdata doesn't have room for any endpoints, so we need to
* append room for the ones we need right after it.
*/
struct {
struct usba_platform_data pdata;
struct usba_ep_data ep[7];
} usba_data;
struct platform_device *pdev;
if (id != 0)
return NULL;
pdev = platform_device_alloc("atmel_usba_udc", 0);
if (!pdev)
return NULL;
if (platform_device_add_resources(pdev, usba0_resource,
ARRAY_SIZE(usba0_resource)))
goto out_free_pdev;
if (data) {
usba_data.pdata.vbus_pin = data->vbus_pin;
usba_data.pdata.vbus_pin_inverted = data->vbus_pin_inverted;
} else {
usba_data.pdata.vbus_pin = -EINVAL;
usba_data.pdata.vbus_pin_inverted = -EINVAL;
}
data = &usba_data.pdata;
data->num_ep = ARRAY_SIZE(at32_usba_ep);
memcpy(data->ep, at32_usba_ep, sizeof(at32_usba_ep));
if (platform_device_add_data(pdev, data, sizeof(usba_data)))
goto out_free_pdev;
if (gpio_is_valid(data->vbus_pin))
at32_select_gpio(data->vbus_pin, 0);
usba0_pclk.dev = &pdev->dev;
usba0_hclk.dev = &pdev->dev;
platform_device_add(pdev);
return pdev;
out_free_pdev:
platform_device_put(pdev);
return NULL;
}
/* --------------------------------------------------------------------
* IDE / CompactFlash
* -------------------------------------------------------------------- */
#if defined(CONFIG_CPU_AT32AP7000) || defined(CONFIG_CPU_AT32AP7001)
static struct resource at32_smc_cs4_resource[] __initdata = {
{
.start = 0x04000000,
.end = 0x07ffffff,
.flags = IORESOURCE_MEM,
},
IRQ(~0UL), /* Magic IRQ will be overridden */
};
static struct resource at32_smc_cs5_resource[] __initdata = {
{
.start = 0x20000000,
.end = 0x23ffffff,
.flags = IORESOURCE_MEM,
},
IRQ(~0UL), /* Magic IRQ will be overridden */
};
static int __init at32_init_ide_or_cf(struct platform_device *pdev,
unsigned int cs, unsigned int extint)
{
static unsigned int extint_pin_map[4] __initdata = {
(1 << 25),
(1 << 26),
(1 << 27),
(1 << 28),
};
static bool common_pins_initialized __initdata = false;
unsigned int extint_pin;
int ret;
u32 pin_mask;
if (extint >= ARRAY_SIZE(extint_pin_map))
return -EINVAL;
extint_pin = extint_pin_map[extint];
switch (cs) {
case 4:
ret = platform_device_add_resources(pdev,
at32_smc_cs4_resource,
ARRAY_SIZE(at32_smc_cs4_resource));
if (ret)
return ret;
/* NCS4 -> OE_N */
select_peripheral(PIOE, (1 << 21), PERIPH_A, 0);
hmatrix_sfr_set_bits(HMATRIX_SLAVE_EBI, HMATRIX_EBI_CF0_ENABLE);
break;
case 5:
ret = platform_device_add_resources(pdev,
at32_smc_cs5_resource,
ARRAY_SIZE(at32_smc_cs5_resource));
if (ret)
return ret;
/* NCS5 -> OE_N */
select_peripheral(PIOE, (1 << 22), PERIPH_A, 0);
hmatrix_sfr_set_bits(HMATRIX_SLAVE_EBI, HMATRIX_EBI_CF1_ENABLE);
break;
default:
return -EINVAL;
}
if (!common_pins_initialized) {
pin_mask = (1 << 19); /* CFCE1 -> CS0_N */
pin_mask |= (1 << 20); /* CFCE2 -> CS1_N */
pin_mask |= (1 << 23); /* CFRNW -> DIR */
pin_mask |= (1 << 24); /* NWAIT <- IORDY */
select_peripheral(PIOE, pin_mask, PERIPH_A, 0);
common_pins_initialized = true;
}
select_peripheral(PIOB, extint_pin, PERIPH_A, AT32_GPIOF_DEGLITCH);
pdev->resource[1].start = EIM_IRQ_BASE + extint;
pdev->resource[1].end = pdev->resource[1].start;
return 0;
}
struct platform_device *__init
at32_add_device_ide(unsigned int id, unsigned int extint,
struct ide_platform_data *data)
{
struct platform_device *pdev;
pdev = platform_device_alloc("at32_ide", id);
if (!pdev)
goto fail;
if (platform_device_add_data(pdev, data,
sizeof(struct ide_platform_data)))
goto fail;
if (at32_init_ide_or_cf(pdev, data->cs, extint))
goto fail;
platform_device_add(pdev);
return pdev;
fail:
platform_device_put(pdev);
return NULL;
}
struct platform_device *__init
at32_add_device_cf(unsigned int id, unsigned int extint,
struct cf_platform_data *data)
{
struct platform_device *pdev;
pdev = platform_device_alloc("at32_cf", id);
if (!pdev)
goto fail;
if (platform_device_add_data(pdev, data,
sizeof(struct cf_platform_data)))
goto fail;
if (at32_init_ide_or_cf(pdev, data->cs, extint))
goto fail;
if (gpio_is_valid(data->detect_pin))
at32_select_gpio(data->detect_pin, AT32_GPIOF_DEGLITCH);
if (gpio_is_valid(data->reset_pin))
at32_select_gpio(data->reset_pin, 0);
if (gpio_is_valid(data->vcc_pin))
at32_select_gpio(data->vcc_pin, 0);
/* READY is used as extint, so we can't select it as gpio */
platform_device_add(pdev);
return pdev;
fail:
platform_device_put(pdev);
return NULL;
}
#endif
/* --------------------------------------------------------------------
* NAND Flash / SmartMedia
* -------------------------------------------------------------------- */
static struct resource smc_cs3_resource[] __initdata = {
{
.start = 0x0c000000,
.end = 0x0fffffff,
.flags = IORESOURCE_MEM,
}, {
.start = 0xfff03c00,
.end = 0xfff03fff,
.flags = IORESOURCE_MEM,
},
};
struct platform_device *__init
at32_add_device_nand(unsigned int id, struct atmel_nand_data *data)
{
struct platform_device *pdev;
if (id != 0 || !data)
return NULL;
pdev = platform_device_alloc("atmel_nand", id);
if (!pdev)
goto fail;
if (platform_device_add_resources(pdev, smc_cs3_resource,
ARRAY_SIZE(smc_cs3_resource)))
goto fail;
if (platform_device_add_data(pdev, data,
sizeof(struct atmel_nand_data)))
goto fail;
hmatrix_sfr_set_bits(HMATRIX_SLAVE_EBI, HMATRIX_EBI_NAND_ENABLE);
if (data->enable_pin)
at32_select_gpio(data->enable_pin,
AT32_GPIOF_OUTPUT | AT32_GPIOF_HIGH);
if (data->rdy_pin)
at32_select_gpio(data->rdy_pin, 0);
if (data->det_pin)
at32_select_gpio(data->det_pin, 0);
platform_device_add(pdev);
return pdev;
fail:
platform_device_put(pdev);
return NULL;
}
/* --------------------------------------------------------------------
* AC97C
* -------------------------------------------------------------------- */
static struct resource atmel_ac97c0_resource[] __initdata = {
PBMEM(0xfff02800),
IRQ(29),
};
static struct clk atmel_ac97c0_pclk = {
.name = "pclk",
.parent = &pbb_clk,
.mode = pbb_clk_mode,
.get_rate = pbb_clk_get_rate,
.index = 10,
};
struct platform_device *__init
at32_add_device_ac97c(unsigned int id, struct ac97c_platform_data *data,
unsigned int flags)
{
struct platform_device *pdev;
struct dw_dma_slave *rx_dws;
struct dw_dma_slave *tx_dws;
struct ac97c_platform_data _data;
u32 pin_mask;
if (id != 0)
return NULL;
pdev = platform_device_alloc("atmel_ac97c", id);
if (!pdev)
return NULL;
if (platform_device_add_resources(pdev, atmel_ac97c0_resource,
ARRAY_SIZE(atmel_ac97c0_resource)))
goto out_free_resources;
if (!data) {
data = &_data;
memset(data, 0, sizeof(struct ac97c_platform_data));
data->reset_pin = -ENODEV;
}
rx_dws = &data->rx_dws;
tx_dws = &data->tx_dws;
/* Check if DMA slave interface for capture should be configured. */
if (flags & AC97C_CAPTURE) {
rx_dws->dma_dev = &dw_dmac0_device.dev;
rx_dws->cfg_hi = DWC_CFGH_SRC_PER(3);
rx_dws->cfg_lo &= ~(DWC_CFGL_HS_DST_POL | DWC_CFGL_HS_SRC_POL);
rx_dws->src_master = 0;
rx_dws->dst_master = 1;
}
/* Check if DMA slave interface for playback should be configured. */
if (flags & AC97C_PLAYBACK) {
tx_dws->dma_dev = &dw_dmac0_device.dev;
tx_dws->cfg_hi = DWC_CFGH_DST_PER(4);
tx_dws->cfg_lo &= ~(DWC_CFGL_HS_DST_POL | DWC_CFGL_HS_SRC_POL);
tx_dws->src_master = 0;
tx_dws->dst_master = 1;
}
if (platform_device_add_data(pdev, data,
sizeof(struct ac97c_platform_data)))
goto out_free_resources;
/* SDO | SYNC | SCLK | SDI */
pin_mask = (1 << 20) | (1 << 21) | (1 << 22) | (1 << 23);
select_peripheral(PIOB, pin_mask, PERIPH_B, 0);
if (gpio_is_valid(data->reset_pin))
at32_select_gpio(data->reset_pin, AT32_GPIOF_OUTPUT
| AT32_GPIOF_HIGH);
atmel_ac97c0_pclk.dev = &pdev->dev;
platform_device_add(pdev);
return pdev;
out_free_resources:
platform_device_put(pdev);
return NULL;
}
/* --------------------------------------------------------------------
* ABDAC
* -------------------------------------------------------------------- */
static struct resource abdac0_resource[] __initdata = {
PBMEM(0xfff02000),
IRQ(27),
};
static struct clk abdac0_pclk = {
.name = "pclk",
.parent = &pbb_clk,
.mode = pbb_clk_mode,
.get_rate = pbb_clk_get_rate,
.index = 8,
};
static struct clk abdac0_sample_clk = {
.name = "sample_clk",
.mode = genclk_mode,
.get_rate = genclk_get_rate,
.set_rate = genclk_set_rate,
.set_parent = genclk_set_parent,
.index = 6,
};
struct platform_device *__init
at32_add_device_abdac(unsigned int id, struct atmel_abdac_pdata *data)
{
struct platform_device *pdev;
struct dw_dma_slave *dws;
u32 pin_mask;
if (id != 0 || !data)
return NULL;
pdev = platform_device_alloc("atmel_abdac", id);
if (!pdev)
return NULL;
if (platform_device_add_resources(pdev, abdac0_resource,
ARRAY_SIZE(abdac0_resource)))
goto out_free_resources;
dws = &data->dws;
dws->dma_dev = &dw_dmac0_device.dev;
dws->cfg_hi = DWC_CFGH_DST_PER(2);
dws->cfg_lo &= ~(DWC_CFGL_HS_DST_POL | DWC_CFGL_HS_SRC_POL);
dws->src_master = 0;
dws->dst_master = 1;
if (platform_device_add_data(pdev, data,
sizeof(struct atmel_abdac_pdata)))
goto out_free_resources;
pin_mask = (1 << 20) | (1 << 22); /* DATA1 & DATAN1 */
pin_mask |= (1 << 21) | (1 << 23); /* DATA0 & DATAN0 */
select_peripheral(PIOB, pin_mask, PERIPH_A, 0);
abdac0_pclk.dev = &pdev->dev;
abdac0_sample_clk.dev = &pdev->dev;
platform_device_add(pdev);
return pdev;
out_free_resources:
platform_device_put(pdev);
return NULL;
}
/* --------------------------------------------------------------------
* GCLK
* -------------------------------------------------------------------- */
static struct clk gclk0 = {
.name = "gclk0",
.mode = genclk_mode,
.get_rate = genclk_get_rate,
.set_rate = genclk_set_rate,
.set_parent = genclk_set_parent,
.index = 0,
};
static struct clk gclk1 = {
.name = "gclk1",
.mode = genclk_mode,
.get_rate = genclk_get_rate,
.set_rate = genclk_set_rate,
.set_parent = genclk_set_parent,
.index = 1,
};
static struct clk gclk2 = {
.name = "gclk2",
.mode = genclk_mode,
.get_rate = genclk_get_rate,
.set_rate = genclk_set_rate,
.set_parent = genclk_set_parent,
.index = 2,
};
static struct clk gclk3 = {
.name = "gclk3",
.mode = genclk_mode,
.get_rate = genclk_get_rate,
.set_rate = genclk_set_rate,
.set_parent = genclk_set_parent,
.index = 3,
};
static struct clk gclk4 = {
.name = "gclk4",
.mode = genclk_mode,
.get_rate = genclk_get_rate,
.set_rate = genclk_set_rate,
.set_parent = genclk_set_parent,
.index = 4,
};
static __initdata struct clk *init_clocks[] = {
&osc32k,
&osc0,
&osc1,
&pll0,
&pll1,
&cpu_clk,
&hsb_clk,
&pba_clk,
&pbb_clk,
&at32_pm_pclk,
&at32_intc0_pclk,
&at32_hmatrix_clk,
&ebi_clk,
&hramc_clk,
&sdramc_clk,
&smc0_pclk,
&smc0_mck,
&pdc_hclk,
&pdc_pclk,
&dw_dmac0_hclk,
&pico_clk,
&pio0_mck,
&pio1_mck,
&pio2_mck,
&pio3_mck,
&pio4_mck,
&at32_tcb0_t0_clk,
&at32_tcb1_t0_clk,
&atmel_psif0_pclk,
&atmel_psif1_pclk,
&atmel_usart0_usart,
&atmel_usart1_usart,
&atmel_usart2_usart,
&atmel_usart3_usart,
&atmel_pwm0_mck,
#if defined(CONFIG_CPU_AT32AP7000)
&macb0_hclk,
&macb0_pclk,
&macb1_hclk,
&macb1_pclk,
#endif
&atmel_spi0_spi_clk,
&atmel_spi1_spi_clk,
&atmel_twi0_pclk,
&atmel_mci0_pclk,
#if defined(CONFIG_CPU_AT32AP7000) || defined(CONFIG_CPU_AT32AP7002)
&atmel_lcdfb0_hck1,
&atmel_lcdfb0_pixclk,
#endif
&ssc0_pclk,
&ssc1_pclk,
&ssc2_pclk,
&usba0_hclk,
&usba0_pclk,
&atmel_ac97c0_pclk,
&abdac0_pclk,
&abdac0_sample_clk,
&gclk0,
&gclk1,
&gclk2,
&gclk3,
&gclk4,
};
void __init setup_platform(void)
{
u32 cpu_mask = 0, hsb_mask = 0, pba_mask = 0, pbb_mask = 0;
int i;
if (pm_readl(MCCTRL) & PM_BIT(PLLSEL)) {
main_clock = &pll0;
cpu_clk.parent = &pll0;
} else {
main_clock = &osc0;
cpu_clk.parent = &osc0;
}
if (pm_readl(PLL0) & PM_BIT(PLLOSC))
pll0.parent = &osc1;
if (pm_readl(PLL1) & PM_BIT(PLLOSC))
pll1.parent = &osc1;
genclk_init_parent(&gclk0);
genclk_init_parent(&gclk1);
genclk_init_parent(&gclk2);
genclk_init_parent(&gclk3);
genclk_init_parent(&gclk4);
#if defined(CONFIG_CPU_AT32AP7000) || defined(CONFIG_CPU_AT32AP7002)
genclk_init_parent(&atmel_lcdfb0_pixclk);
#endif
genclk_init_parent(&abdac0_sample_clk);
/*
* Build initial dynamic clock list by registering all clocks
* from the array.
* At the same time, turn on all clocks that have at least one
* user already, and turn off everything else. We only do this
* for module clocks, and even though it isn't particularly
* pretty to check the address of the mode function, it should
* do the trick...
*/
for (i = 0; i < ARRAY_SIZE(init_clocks); i++) {
struct clk *clk = init_clocks[i];
/* first, register clock */
at32_clk_register(clk);
if (clk->users == 0)
continue;
if (clk->mode == &cpu_clk_mode)
cpu_mask |= 1 << clk->index;
else if (clk->mode == &hsb_clk_mode)
hsb_mask |= 1 << clk->index;
else if (clk->mode == &pba_clk_mode)
pba_mask |= 1 << clk->index;
else if (clk->mode == &pbb_clk_mode)
pbb_mask |= 1 << clk->index;
}
pm_writel(CPU_MASK, cpu_mask);
pm_writel(HSB_MASK, hsb_mask);
pm_writel(PBA_MASK, pba_mask);
pm_writel(PBB_MASK, pbb_mask);
/* Initialize the port muxes */
at32_init_pio(&pio0_device);
at32_init_pio(&pio1_device);
at32_init_pio(&pio2_device);
at32_init_pio(&pio3_device);
at32_init_pio(&pio4_device);
}
struct gen_pool *sram_pool;
static int __init sram_init(void)
{
struct gen_pool *pool;
/* 1KiB granularity */
pool = gen_pool_create(10, -1);
if (!pool)
goto fail;
if (gen_pool_add(pool, 0x24000000, 0x8000, -1))
goto err_pool_add;
sram_pool = pool;
return 0;
err_pool_add:
gen_pool_destroy(pool);
fail:
pr_err("Failed to create SRAM pool\n");
return -ENOMEM;
}
core_initcall(sram_init);
| gpl-2.0 |
mdmower/android_kernel_htc_msm8960 | kernel/kthread.c | 457 | 17405 | /* Kernel thread helper functions.
* Copyright (C) 2004 IBM Corporation, Rusty Russell.
*
* Creation is done via kthreadd, so that we get a clean environment
* even if we're invoked from userspace (think modprobe, hotplug cpu,
* etc.).
*/
#include <linux/sched.h>
#include <linux/kthread.h>
#include <linux/completion.h>
#include <linux/err.h>
#include <linux/cpuset.h>
#include <linux/unistd.h>
#include <linux/file.h>
#include <linux/export.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/freezer.h>
#include <trace/events/sched.h>
static DEFINE_SPINLOCK(kthread_create_lock);
static LIST_HEAD(kthread_create_list);
struct task_struct *kthreadd_task;
struct kthread_create_info
{
/* Information passed to kthread() from kthreadd. */
int (*threadfn)(void *data);
void *data;
int node;
/* Result passed back to kthread_create() from kthreadd. */
struct task_struct *result;
struct completion done;
struct list_head list;
};
struct kthread {
unsigned long flags;
unsigned int cpu;
void *data;
struct completion parked;
struct completion exited;
};
enum KTHREAD_BITS {
KTHREAD_IS_PER_CPU = 0,
KTHREAD_SHOULD_STOP,
KTHREAD_SHOULD_PARK,
KTHREAD_IS_PARKED,
};
#define to_kthread(tsk) \
container_of((tsk)->vfork_done, struct kthread, exited)
/**
* kthread_should_stop - should this kthread return now?
*
* When someone calls kthread_stop() on your kthread, it will be woken
* and this will return true. You should then return, and your return
* value will be passed through to kthread_stop().
*/
bool kthread_should_stop(void)
{
return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
}
EXPORT_SYMBOL(kthread_should_stop);
/**
* kthread_should_park - should this kthread park now?
*
* When someone calls kthread_park() on your kthread, it will be woken
* and this will return true. You should then do the necessary
* cleanup and call kthread_parkme()
*
* Similar to kthread_should_stop(), but this keeps the thread alive
* and in a park position. kthread_unpark() "restarts" the thread and
* calls the thread function again.
*/
bool kthread_should_park(void)
{
return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(current)->flags);
}
/**
* kthread_freezable_should_stop - should this freezable kthread return now?
* @was_frozen: optional out parameter, indicates whether %current was frozen
*
* kthread_should_stop() for freezable kthreads, which will enter
* refrigerator if necessary. This function is safe from kthread_stop() /
* freezer deadlock and freezable kthreads should use this function instead
* of calling try_to_freeze() directly.
*/
bool kthread_freezable_should_stop(bool *was_frozen)
{
bool frozen = false;
might_sleep();
if (unlikely(freezing(current)))
frozen = __refrigerator(true);
if (was_frozen)
*was_frozen = frozen;
return kthread_should_stop();
}
EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
/**
* kthread_data - return data value specified on kthread creation
* @task: kthread task in question
*
* Return the data value specified when kthread @task was created.
* The caller is responsible for ensuring the validity of @task when
* calling this function.
*/
void *kthread_data(struct task_struct *task)
{
return to_kthread(task)->data;
}
static void __kthread_parkme(struct kthread *self)
{
__set_current_state(TASK_PARKED);
while (test_bit(KTHREAD_SHOULD_PARK, &self->flags)) {
if (!test_and_set_bit(KTHREAD_IS_PARKED, &self->flags))
complete(&self->parked);
schedule();
__set_current_state(TASK_PARKED);
}
clear_bit(KTHREAD_IS_PARKED, &self->flags);
__set_current_state(TASK_RUNNING);
}
void kthread_parkme(void)
{
__kthread_parkme(to_kthread(current));
}
static int kthread(void *_create)
{
/* Copy data: it's on kthread's stack */
struct kthread_create_info *create = _create;
int (*threadfn)(void *data) = create->threadfn;
void *data = create->data;
struct kthread self;
int ret;
self.flags = 0;
self.data = data;
init_completion(&self.exited);
init_completion(&self.parked);
current->vfork_done = &self.exited;
/* OK, tell user we're spawned, wait for stop or wakeup */
__set_current_state(TASK_UNINTERRUPTIBLE);
create->result = current;
complete(&create->done);
schedule();
ret = -EINTR;
if (!test_bit(KTHREAD_SHOULD_STOP, &self.flags)) {
__kthread_parkme(&self);
ret = threadfn(data);
}
/* we can't just return, we must preserve "self" on stack */
do_exit(ret);
}
/* called from do_fork() to get node information for about to be created task */
int tsk_fork_get_node(struct task_struct *tsk)
{
#ifdef CONFIG_NUMA
if (tsk == kthreadd_task)
return tsk->pref_node_fork;
#endif
return numa_node_id();
}
static void create_kthread(struct kthread_create_info *create)
{
int pid;
#ifdef CONFIG_NUMA
current->pref_node_fork = create->node;
#endif
/* We want our own signal handler (we take no signals by default). */
pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
if (pid < 0) {
create->result = ERR_PTR(pid);
complete(&create->done);
}
}
/**
* kthread_create_on_node - create a kthread.
* @threadfn: the function to run until signal_pending(current).
* @data: data ptr for @threadfn.
* @node: memory node number.
* @namefmt: printf-style name for the thread.
*
* Description: This helper function creates and names a kernel
* thread. The thread will be stopped: use wake_up_process() to start
* it. See also kthread_run().
*
* If thread is going to be bound on a particular cpu, give its node
* in @node, to get NUMA affinity for kthread stack, or else give -1.
* When woken, the thread will run @threadfn() with @data as its
* argument. @threadfn() can either call do_exit() directly if it is a
* standalone thread for which no one will call kthread_stop(), or
* return when 'kthread_should_stop()' is true (which means
* kthread_stop() has been called). The return value should be zero
* or a negative error number; it will be passed to kthread_stop().
*
* Returns a task_struct or ERR_PTR(-ENOMEM).
*/
struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),
void *data, int node,
const char namefmt[],
...)
{
struct kthread_create_info create;
create.threadfn = threadfn;
create.data = data;
create.node = node;
init_completion(&create.done);
spin_lock(&kthread_create_lock);
list_add_tail(&create.list, &kthread_create_list);
spin_unlock(&kthread_create_lock);
wake_up_process(kthreadd_task);
wait_for_completion(&create.done);
if (!IS_ERR(create.result)) {
static const struct sched_param param = { .sched_priority = 0 };
va_list args;
va_start(args, namefmt);
vsnprintf(create.result->comm, sizeof(create.result->comm),
namefmt, args);
va_end(args);
/*
* root may have changed our (kthreadd's) priority or CPU mask.
* The kernel thread should not inherit these properties.
*/
sched_setscheduler_nocheck(create.result, SCHED_NORMAL, ¶m);
set_cpus_allowed_ptr(create.result, cpu_all_mask);
}
return create.result;
}
EXPORT_SYMBOL(kthread_create_on_node);
static void __kthread_bind(struct task_struct *p, unsigned int cpu, long state)
{
/* Must have done schedule() in kthread() before we set_task_cpu */
if (!wait_task_inactive(p, state)) {
WARN_ON(1);
return;
}
/* It's safe because the task is inactive. */
do_set_cpus_allowed(p, cpumask_of(cpu));
p->flags |= PF_THREAD_BOUND;
}
/**
* kthread_bind - bind a just-created kthread to a cpu.
* @p: thread created by kthread_create().
* @cpu: cpu (might not be online, must be possible) for @k to run on.
*
* Description: This function is equivalent to set_cpus_allowed(),
* except that @cpu doesn't need to be online, and the thread must be
* stopped (i.e., just returned from kthread_create()).
*/
void kthread_bind(struct task_struct *p, unsigned int cpu)
{
__kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE);
}
EXPORT_SYMBOL(kthread_bind);
/**
* kthread_create_on_cpu - Create a cpu bound kthread
* @threadfn: the function to run until signal_pending(current).
* @data: data ptr for @threadfn.
* @cpu: The cpu on which the thread should be bound,
* @namefmt: printf-style name for the thread. Format is restricted
* to "name.*%u". Code fills in cpu number.
*
* Description: This helper function creates and names a kernel thread
* The thread will be woken and put into park mode.
*/
struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
void *data, unsigned int cpu,
const char *namefmt)
{
struct task_struct *p;
p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt,
cpu);
if (IS_ERR(p))
return p;
set_bit(KTHREAD_IS_PER_CPU, &to_kthread(p)->flags);
to_kthread(p)->cpu = cpu;
/* Park the thread to get it out of TASK_UNINTERRUPTIBLE state */
kthread_park(p);
return p;
}
static struct kthread *task_get_live_kthread(struct task_struct *k)
{
struct kthread *kthread;
get_task_struct(k);
kthread = to_kthread(k);
/* It might have exited */
barrier();
if (k->vfork_done != NULL)
return kthread;
return NULL;
}
static void __kthread_unpark(struct task_struct *k, struct kthread *kthread)
{
clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
/*
* We clear the IS_PARKED bit here as we don't wait
* until the task has left the park code. So if we'd
* park before that happens we'd see the IS_PARKED bit
* which might be about to be cleared.
*/
if (test_and_clear_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags))
__kthread_bind(k, kthread->cpu, TASK_PARKED);
wake_up_state(k, TASK_PARKED);
}
}
/**
* kthread_unpark - unpark a thread created by kthread_create().
* @k: thread created by kthread_create().
*
* Sets kthread_should_park() for @k to return false, wakes it, and
* waits for it to return. If the thread is marked percpu then its
* bound to the cpu again.
*/
void kthread_unpark(struct task_struct *k)
{
struct kthread *kthread = task_get_live_kthread(k);
if (kthread)
__kthread_unpark(k, kthread);
put_task_struct(k);
}
/**
* kthread_park - park a thread created by kthread_create().
* @k: thread created by kthread_create().
*
* Sets kthread_should_park() for @k to return true, wakes it, and
* waits for it to return. This can also be called after kthread_create()
* instead of calling wake_up_process(): the thread will park without
* calling threadfn().
*
* Returns 0 if the thread is parked, -ENOSYS if the thread exited.
* If called by the kthread itself just the park bit is set.
*/
int kthread_park(struct task_struct *k)
{
struct kthread *kthread = task_get_live_kthread(k);
int ret = -ENOSYS;
if (kthread) {
if (!test_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
if (k != current) {
wake_up_process(k);
wait_for_completion(&kthread->parked);
}
}
ret = 0;
}
put_task_struct(k);
return ret;
}
/**
* kthread_stop - stop a thread created by kthread_create().
* @k: thread created by kthread_create().
*
* Sets kthread_should_stop() for @k to return true, wakes it, and
* waits for it to exit. This can also be called after kthread_create()
* instead of calling wake_up_process(): the thread will exit without
* calling threadfn().
*
* If threadfn() may call do_exit() itself, the caller must ensure
* task_struct can't go away.
*
* Returns the result of threadfn(), or %-EINTR if wake_up_process()
* was never called.
*/
int kthread_stop(struct task_struct *k)
{
struct kthread *kthread = task_get_live_kthread(k);
int ret;
trace_sched_kthread_stop(k);
if (kthread) {
set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
__kthread_unpark(k, kthread);
wake_up_process(k);
wait_for_completion(&kthread->exited);
}
ret = k->exit_code;
put_task_struct(k);
trace_sched_kthread_stop_ret(ret);
return ret;
}
EXPORT_SYMBOL(kthread_stop);
int kthreadd(void *unused)
{
struct task_struct *tsk = current;
/* Setup a clean context for our children to inherit. */
set_task_comm(tsk, "kthreadd");
ignore_signals(tsk);
set_cpus_allowed_ptr(tsk, cpu_all_mask);
set_mems_allowed(node_states[N_HIGH_MEMORY]);
current->flags |= PF_NOFREEZE;
for (;;) {
set_current_state(TASK_INTERRUPTIBLE);
if (list_empty(&kthread_create_list))
schedule();
__set_current_state(TASK_RUNNING);
spin_lock(&kthread_create_lock);
while (!list_empty(&kthread_create_list)) {
struct kthread_create_info *create;
create = list_entry(kthread_create_list.next,
struct kthread_create_info, list);
list_del_init(&create->list);
spin_unlock(&kthread_create_lock);
create_kthread(create);
spin_lock(&kthread_create_lock);
}
spin_unlock(&kthread_create_lock);
}
return 0;
}
void __init_kthread_worker(struct kthread_worker *worker,
const char *name,
struct lock_class_key *key)
{
spin_lock_init(&worker->lock);
lockdep_set_class_and_name(&worker->lock, key, name);
INIT_LIST_HEAD(&worker->work_list);
worker->task = NULL;
}
EXPORT_SYMBOL_GPL(__init_kthread_worker);
/**
* kthread_worker_fn - kthread function to process kthread_worker
* @worker_ptr: pointer to initialized kthread_worker
*
* This function can be used as @threadfn to kthread_create() or
* kthread_run() with @worker_ptr argument pointing to an initialized
* kthread_worker. The started kthread will process work_list until
* the it is stopped with kthread_stop(). A kthread can also call
* this function directly after extra initialization.
*
* Different kthreads can be used for the same kthread_worker as long
* as there's only one kthread attached to it at any given time. A
* kthread_worker without an attached kthread simply collects queued
* kthread_works.
*/
int kthread_worker_fn(void *worker_ptr)
{
struct kthread_worker *worker = worker_ptr;
struct kthread_work *work;
WARN_ON(worker->task);
worker->task = current;
repeat:
set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
if (kthread_should_stop()) {
__set_current_state(TASK_RUNNING);
spin_lock_irq(&worker->lock);
worker->task = NULL;
spin_unlock_irq(&worker->lock);
return 0;
}
work = NULL;
spin_lock_irq(&worker->lock);
if (!list_empty(&worker->work_list)) {
work = list_first_entry(&worker->work_list,
struct kthread_work, node);
list_del_init(&work->node);
}
worker->current_work = work;
spin_unlock_irq(&worker->lock);
if (work) {
__set_current_state(TASK_RUNNING);
work->func(work);
} else if (!freezing(current))
schedule();
try_to_freeze();
goto repeat;
}
EXPORT_SYMBOL_GPL(kthread_worker_fn);
/* insert @work before @pos in @worker */
static void insert_kthread_work(struct kthread_worker *worker,
struct kthread_work *work,
struct list_head *pos)
{
lockdep_assert_held(&worker->lock);
list_add_tail(&work->node, pos);
work->worker = worker;
if (likely(worker->task))
wake_up_process(worker->task);
}
/**
* queue_kthread_work - queue a kthread_work
* @worker: target kthread_worker
* @work: kthread_work to queue
*
* Queue @work to work processor @task for async execution. @task
* must have been created with kthread_worker_create(). Returns %true
* if @work was successfully queued, %false if it was already pending.
*/
bool queue_kthread_work(struct kthread_worker *worker,
struct kthread_work *work)
{
bool ret = false;
unsigned long flags;
spin_lock_irqsave(&worker->lock, flags);
if (list_empty(&work->node)) {
insert_kthread_work(worker, work, &worker->work_list);
ret = true;
}
spin_unlock_irqrestore(&worker->lock, flags);
return ret;
}
EXPORT_SYMBOL_GPL(queue_kthread_work);
struct kthread_flush_work {
struct kthread_work work;
struct completion done;
};
static void kthread_flush_work_fn(struct kthread_work *work)
{
struct kthread_flush_work *fwork =
container_of(work, struct kthread_flush_work, work);
complete(&fwork->done);
}
/**
* flush_kthread_work - flush a kthread_work
* @work: work to flush
*
* If @work is queued or executing, wait for it to finish execution.
*/
void flush_kthread_work(struct kthread_work *work)
{
struct kthread_flush_work fwork = {
KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
COMPLETION_INITIALIZER_ONSTACK(fwork.done),
};
struct kthread_worker *worker;
bool noop = false;
retry:
worker = work->worker;
if (!worker)
return;
spin_lock_irq(&worker->lock);
if (work->worker != worker) {
spin_unlock_irq(&worker->lock);
goto retry;
}
if (!list_empty(&work->node))
insert_kthread_work(worker, &fwork.work, work->node.next);
else if (worker->current_work == work)
insert_kthread_work(worker, &fwork.work, worker->work_list.next);
else
noop = true;
spin_unlock_irq(&worker->lock);
if (!noop)
wait_for_completion(&fwork.done);
}
EXPORT_SYMBOL_GPL(flush_kthread_work);
/**
* flush_kthread_worker - flush all current works on a kthread_worker
* @worker: worker to flush
*
* Wait until all currently executing or pending works on @worker are
* finished.
*/
void flush_kthread_worker(struct kthread_worker *worker)
{
struct kthread_flush_work fwork = {
KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
COMPLETION_INITIALIZER_ONSTACK(fwork.done),
};
queue_kthread_work(worker, &fwork.work);
wait_for_completion(&fwork.done);
}
EXPORT_SYMBOL_GPL(flush_kthread_worker);
| gpl-2.0 |
ayushtyagi28/android_kernel_cyanogen_msm8994 | arch/powerpc/kernel/pci_64.c | 1993 | 7828 | /*
* Port for PPC64 David Engebretsen, IBM Corp.
* Contains common pci routines for ppc64 platform, pSeries and iSeries brands.
*
* Copyright (C) 2003 Anton Blanchard <anton@au.ibm.com>, IBM
* Rework, based on alpha PCI code.
*
* 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.
*/
#undef DEBUG
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/export.h>
#include <linux/mm.h>
#include <linux/list.h>
#include <linux/syscalls.h>
#include <linux/irq.h>
#include <linux/vmalloc.h>
#include <asm/processor.h>
#include <asm/io.h>
#include <asm/prom.h>
#include <asm/pci-bridge.h>
#include <asm/byteorder.h>
#include <asm/machdep.h>
#include <asm/ppc-pci.h>
/* pci_io_base -- the base address from which io bars are offsets.
* This is the lowest I/O base address (so bar values are always positive),
* and it *must* be the start of ISA space if an ISA bus exists because
* ISA drivers use hard coded offsets. If no ISA bus exists nothing
* is mapped on the first 64K of IO space
*/
unsigned long pci_io_base = ISA_IO_BASE;
EXPORT_SYMBOL(pci_io_base);
static int __init pcibios_init(void)
{
struct pci_controller *hose, *tmp;
printk(KERN_INFO "PCI: Probing PCI hardware\n");
/* For now, override phys_mem_access_prot. If we need it,g
* later, we may move that initialization to each ppc_md
*/
ppc_md.phys_mem_access_prot = pci_phys_mem_access_prot;
/* On ppc64, we always enable PCI domains and we keep domain 0
* backward compatible in /proc for video cards
*/
pci_add_flags(PCI_ENABLE_PROC_DOMAINS | PCI_COMPAT_DOMAIN_0);
/* Scan all of the recorded PCI controllers. */
list_for_each_entry_safe(hose, tmp, &hose_list, list_node) {
pcibios_scan_phb(hose);
pci_bus_add_devices(hose->bus);
}
/* Call common code to handle resource allocation */
pcibios_resource_survey();
printk(KERN_DEBUG "PCI: Probing PCI hardware done\n");
return 0;
}
subsys_initcall(pcibios_init);
int pcibios_unmap_io_space(struct pci_bus *bus)
{
struct pci_controller *hose;
WARN_ON(bus == NULL);
/* If this is not a PHB, we only flush the hash table over
* the area mapped by this bridge. We don't play with the PTE
* mappings since we might have to deal with sub-page alignemnts
* so flushing the hash table is the only sane way to make sure
* that no hash entries are covering that removed bridge area
* while still allowing other busses overlapping those pages
*
* Note: If we ever support P2P hotplug on Book3E, we'll have
* to do an appropriate TLB flush here too
*/
if (bus->self) {
#ifdef CONFIG_PPC_STD_MMU_64
struct resource *res = bus->resource[0];
#endif
pr_debug("IO unmapping for PCI-PCI bridge %s\n",
pci_name(bus->self));
#ifdef CONFIG_PPC_STD_MMU_64
__flush_hash_table_range(&init_mm, res->start + _IO_BASE,
res->end + _IO_BASE + 1);
#endif
return 0;
}
/* Get the host bridge */
hose = pci_bus_to_host(bus);
/* Check if we have IOs allocated */
if (hose->io_base_alloc == 0)
return 0;
pr_debug("IO unmapping for PHB %s\n", hose->dn->full_name);
pr_debug(" alloc=0x%p\n", hose->io_base_alloc);
/* This is a PHB, we fully unmap the IO area */
vunmap(hose->io_base_alloc);
return 0;
}
EXPORT_SYMBOL_GPL(pcibios_unmap_io_space);
static int pcibios_map_phb_io_space(struct pci_controller *hose)
{
struct vm_struct *area;
unsigned long phys_page;
unsigned long size_page;
unsigned long io_virt_offset;
phys_page = _ALIGN_DOWN(hose->io_base_phys, PAGE_SIZE);
size_page = _ALIGN_UP(hose->pci_io_size, PAGE_SIZE);
/* Make sure IO area address is clear */
hose->io_base_alloc = NULL;
/* If there's no IO to map on that bus, get away too */
if (hose->pci_io_size == 0 || hose->io_base_phys == 0)
return 0;
/* Let's allocate some IO space for that guy. We don't pass
* VM_IOREMAP because we don't care about alignment tricks that
* the core does in that case. Maybe we should due to stupid card
* with incomplete address decoding but I'd rather not deal with
* those outside of the reserved 64K legacy region.
*/
area = __get_vm_area(size_page, 0, PHB_IO_BASE, PHB_IO_END);
if (area == NULL)
return -ENOMEM;
hose->io_base_alloc = area->addr;
hose->io_base_virt = (void __iomem *)(area->addr +
hose->io_base_phys - phys_page);
pr_debug("IO mapping for PHB %s\n", hose->dn->full_name);
pr_debug(" phys=0x%016llx, virt=0x%p (alloc=0x%p)\n",
hose->io_base_phys, hose->io_base_virt, hose->io_base_alloc);
pr_debug(" size=0x%016llx (alloc=0x%016lx)\n",
hose->pci_io_size, size_page);
/* Establish the mapping */
if (__ioremap_at(phys_page, area->addr, size_page,
_PAGE_NO_CACHE | _PAGE_GUARDED) == NULL)
return -ENOMEM;
/* Fixup hose IO resource */
io_virt_offset = pcibios_io_space_offset(hose);
hose->io_resource.start += io_virt_offset;
hose->io_resource.end += io_virt_offset;
pr_debug(" hose->io_resource=%pR\n", &hose->io_resource);
return 0;
}
int pcibios_map_io_space(struct pci_bus *bus)
{
WARN_ON(bus == NULL);
/* If this not a PHB, nothing to do, page tables still exist and
* thus HPTEs will be faulted in when needed
*/
if (bus->self) {
pr_debug("IO mapping for PCI-PCI bridge %s\n",
pci_name(bus->self));
pr_debug(" virt=0x%016llx...0x%016llx\n",
bus->resource[0]->start + _IO_BASE,
bus->resource[0]->end + _IO_BASE);
return 0;
}
return pcibios_map_phb_io_space(pci_bus_to_host(bus));
}
EXPORT_SYMBOL_GPL(pcibios_map_io_space);
void pcibios_setup_phb_io_space(struct pci_controller *hose)
{
pcibios_map_phb_io_space(hose);
}
#define IOBASE_BRIDGE_NUMBER 0
#define IOBASE_MEMORY 1
#define IOBASE_IO 2
#define IOBASE_ISA_IO 3
#define IOBASE_ISA_MEM 4
long sys_pciconfig_iobase(long which, unsigned long in_bus,
unsigned long in_devfn)
{
struct pci_controller* hose;
struct list_head *ln;
struct pci_bus *bus = NULL;
struct device_node *hose_node;
/* Argh ! Please forgive me for that hack, but that's the
* simplest way to get existing XFree to not lockup on some
* G5 machines... So when something asks for bus 0 io base
* (bus 0 is HT root), we return the AGP one instead.
*/
if (in_bus == 0 && of_machine_is_compatible("MacRISC4")) {
struct device_node *agp;
agp = of_find_compatible_node(NULL, NULL, "u3-agp");
if (agp)
in_bus = 0xf0;
of_node_put(agp);
}
/* That syscall isn't quite compatible with PCI domains, but it's
* used on pre-domains setup. We return the first match
*/
for (ln = pci_root_buses.next; ln != &pci_root_buses; ln = ln->next) {
bus = pci_bus_b(ln);
if (in_bus >= bus->number && in_bus <= bus->busn_res.end)
break;
bus = NULL;
}
if (bus == NULL || bus->dev.of_node == NULL)
return -ENODEV;
hose_node = bus->dev.of_node;
hose = PCI_DN(hose_node)->phb;
switch (which) {
case IOBASE_BRIDGE_NUMBER:
return (long)hose->first_busno;
case IOBASE_MEMORY:
return (long)hose->mem_offset[0];
case IOBASE_IO:
return (long)hose->io_base_phys;
case IOBASE_ISA_IO:
return (long)isa_io_base;
case IOBASE_ISA_MEM:
return -EINVAL;
}
return -EOPNOTSUPP;
}
#ifdef CONFIG_NUMA
int pcibus_to_node(struct pci_bus *bus)
{
struct pci_controller *phb = pci_bus_to_host(bus);
return phb->node;
}
EXPORT_SYMBOL(pcibus_to_node);
#endif
static void quirk_radeon_32bit_msi(struct pci_dev *dev)
{
struct pci_dn *pdn = pci_get_pdn(dev);
if (pdn)
pdn->force_32bit_msi = 1;
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x68f2, quirk_radeon_32bit_msi);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0xaa68, quirk_radeon_32bit_msi);
| gpl-2.0 |
djvoleur/G_N92XP-R4_AOJ6 | drivers/mmc/host/cb710-mmc.c | 2249 | 21977 | /*
* cb710/mmc.c
*
* Copyright by Michał Mirosław, 2008-2009
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include "cb710-mmc.h"
static const u8 cb710_clock_divider_log2[8] = {
/* 1, 2, 4, 8, 16, 32, 128, 512 */
0, 1, 2, 3, 4, 5, 7, 9
};
#define CB710_MAX_DIVIDER_IDX \
(ARRAY_SIZE(cb710_clock_divider_log2) - 1)
static const u8 cb710_src_freq_mhz[16] = {
33, 10, 20, 25, 30, 35, 40, 45,
50, 55, 60, 65, 70, 75, 80, 85
};
static void cb710_mmc_select_clock_divider(struct mmc_host *mmc, int hz)
{
struct cb710_slot *slot = cb710_mmc_to_slot(mmc);
struct pci_dev *pdev = cb710_slot_to_chip(slot)->pdev;
u32 src_freq_idx;
u32 divider_idx;
int src_hz;
/* on CB710 in HP nx9500:
* src_freq_idx == 0
* indexes 1-7 work as written in the table
* indexes 0,8-15 give no clock output
*/
pci_read_config_dword(pdev, 0x48, &src_freq_idx);
src_freq_idx = (src_freq_idx >> 16) & 0xF;
src_hz = cb710_src_freq_mhz[src_freq_idx] * 1000000;
for (divider_idx = 0; divider_idx < CB710_MAX_DIVIDER_IDX; ++divider_idx) {
if (hz >= src_hz >> cb710_clock_divider_log2[divider_idx])
break;
}
if (src_freq_idx)
divider_idx |= 0x8;
else if (divider_idx == 0)
divider_idx = 1;
cb710_pci_update_config_reg(pdev, 0x40, ~0xF0000000, divider_idx << 28);
dev_dbg(cb710_slot_dev(slot),
"clock set to %d Hz, wanted %d Hz; src_freq_idx = %d, divider_idx = %d|%d\n",
src_hz >> cb710_clock_divider_log2[divider_idx & 7],
hz, src_freq_idx, divider_idx & 7, divider_idx & 8);
}
static void __cb710_mmc_enable_irq(struct cb710_slot *slot,
unsigned short enable, unsigned short mask)
{
/* clear global IE
* - it gets set later if any interrupt sources are enabled */
mask |= CB710_MMC_IE_IRQ_ENABLE;
/* look like interrupt is fired whenever
* WORD[0x0C] & WORD[0x10] != 0;
* -> bit 15 port 0x0C seems to be global interrupt enable
*/
enable = (cb710_read_port_16(slot, CB710_MMC_IRQ_ENABLE_PORT)
& ~mask) | enable;
if (enable)
enable |= CB710_MMC_IE_IRQ_ENABLE;
cb710_write_port_16(slot, CB710_MMC_IRQ_ENABLE_PORT, enable);
}
static void cb710_mmc_enable_irq(struct cb710_slot *slot,
unsigned short enable, unsigned short mask)
{
struct cb710_mmc_reader *reader = mmc_priv(cb710_slot_to_mmc(slot));
unsigned long flags;
spin_lock_irqsave(&reader->irq_lock, flags);
/* this is the only thing irq_lock protects */
__cb710_mmc_enable_irq(slot, enable, mask);
spin_unlock_irqrestore(&reader->irq_lock, flags);
}
static void cb710_mmc_reset_events(struct cb710_slot *slot)
{
cb710_write_port_8(slot, CB710_MMC_STATUS0_PORT, 0xFF);
cb710_write_port_8(slot, CB710_MMC_STATUS1_PORT, 0xFF);
cb710_write_port_8(slot, CB710_MMC_STATUS2_PORT, 0xFF);
}
static void cb710_mmc_enable_4bit_data(struct cb710_slot *slot, int enable)
{
if (enable)
cb710_modify_port_8(slot, CB710_MMC_CONFIG1_PORT,
CB710_MMC_C1_4BIT_DATA_BUS, 0);
else
cb710_modify_port_8(slot, CB710_MMC_CONFIG1_PORT,
0, CB710_MMC_C1_4BIT_DATA_BUS);
}
static int cb710_check_event(struct cb710_slot *slot, u8 what)
{
u16 status;
status = cb710_read_port_16(slot, CB710_MMC_STATUS_PORT);
if (status & CB710_MMC_S0_FIFO_UNDERFLOW) {
/* it is just a guess, so log it */
dev_dbg(cb710_slot_dev(slot),
"CHECK : ignoring bit 6 in status %04X\n", status);
cb710_write_port_8(slot, CB710_MMC_STATUS0_PORT,
CB710_MMC_S0_FIFO_UNDERFLOW);
status &= ~CB710_MMC_S0_FIFO_UNDERFLOW;
}
if (status & CB710_MMC_STATUS_ERROR_EVENTS) {
dev_dbg(cb710_slot_dev(slot),
"CHECK : returning EIO on status %04X\n", status);
cb710_write_port_8(slot, CB710_MMC_STATUS0_PORT, status & 0xFF);
cb710_write_port_8(slot, CB710_MMC_STATUS1_PORT,
CB710_MMC_S1_RESET);
return -EIO;
}
/* 'what' is a bit in MMC_STATUS1 */
if ((status >> 8) & what) {
cb710_write_port_8(slot, CB710_MMC_STATUS1_PORT, what);
return 1;
}
return 0;
}
static int cb710_wait_for_event(struct cb710_slot *slot, u8 what)
{
int err = 0;
unsigned limit = 2000000; /* FIXME: real timeout */
#ifdef CONFIG_CB710_DEBUG
u32 e, x;
e = cb710_read_port_32(slot, CB710_MMC_STATUS_PORT);
#endif
while (!(err = cb710_check_event(slot, what))) {
if (!--limit) {
cb710_dump_regs(cb710_slot_to_chip(slot),
CB710_DUMP_REGS_MMC);
err = -ETIMEDOUT;
break;
}
udelay(1);
}
#ifdef CONFIG_CB710_DEBUG
x = cb710_read_port_32(slot, CB710_MMC_STATUS_PORT);
limit = 2000000 - limit;
if (limit > 100)
dev_dbg(cb710_slot_dev(slot),
"WAIT10: waited %d loops, what %d, entry val %08X, exit val %08X\n",
limit, what, e, x);
#endif
return err < 0 ? err : 0;
}
static int cb710_wait_while_busy(struct cb710_slot *slot, uint8_t mask)
{
unsigned limit = 500000; /* FIXME: real timeout */
int err = 0;
#ifdef CONFIG_CB710_DEBUG
u32 e, x;
e = cb710_read_port_32(slot, CB710_MMC_STATUS_PORT);
#endif
while (cb710_read_port_8(slot, CB710_MMC_STATUS2_PORT) & mask) {
if (!--limit) {
cb710_dump_regs(cb710_slot_to_chip(slot),
CB710_DUMP_REGS_MMC);
err = -ETIMEDOUT;
break;
}
udelay(1);
}
#ifdef CONFIG_CB710_DEBUG
x = cb710_read_port_32(slot, CB710_MMC_STATUS_PORT);
limit = 500000 - limit;
if (limit > 100)
dev_dbg(cb710_slot_dev(slot),
"WAIT12: waited %d loops, mask %02X, entry val %08X, exit val %08X\n",
limit, mask, e, x);
#endif
return err;
}
static void cb710_mmc_set_transfer_size(struct cb710_slot *slot,
size_t count, size_t blocksize)
{
cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20);
cb710_write_port_32(slot, CB710_MMC_TRANSFER_SIZE_PORT,
((count - 1) << 16)|(blocksize - 1));
dev_vdbg(cb710_slot_dev(slot), "set up for %zu block%s of %zu bytes\n",
count, count == 1 ? "" : "s", blocksize);
}
static void cb710_mmc_fifo_hack(struct cb710_slot *slot)
{
/* without this, received data is prepended with 8-bytes of zeroes */
u32 r1, r2;
int ok = 0;
r1 = cb710_read_port_32(slot, CB710_MMC_DATA_PORT);
r2 = cb710_read_port_32(slot, CB710_MMC_DATA_PORT);
if (cb710_read_port_8(slot, CB710_MMC_STATUS0_PORT)
& CB710_MMC_S0_FIFO_UNDERFLOW) {
cb710_write_port_8(slot, CB710_MMC_STATUS0_PORT,
CB710_MMC_S0_FIFO_UNDERFLOW);
ok = 1;
}
dev_dbg(cb710_slot_dev(slot),
"FIFO-read-hack: expected STATUS0 bit was %s\n",
ok ? "set." : "NOT SET!");
dev_dbg(cb710_slot_dev(slot),
"FIFO-read-hack: dwords ignored: %08X %08X - %s\n",
r1, r2, (r1|r2) ? "BAD (NOT ZERO)!" : "ok");
}
static int cb710_mmc_receive_pio(struct cb710_slot *slot,
struct sg_mapping_iter *miter, size_t dw_count)
{
if (!(cb710_read_port_8(slot, CB710_MMC_STATUS2_PORT) & CB710_MMC_S2_FIFO_READY)) {
int err = cb710_wait_for_event(slot,
CB710_MMC_S1_PIO_TRANSFER_DONE);
if (err)
return err;
}
cb710_sg_dwiter_write_from_io(miter,
slot->iobase + CB710_MMC_DATA_PORT, dw_count);
return 0;
}
static bool cb710_is_transfer_size_supported(struct mmc_data *data)
{
return !(data->blksz & 15 && (data->blocks != 1 || data->blksz != 8));
}
static int cb710_mmc_receive(struct cb710_slot *slot, struct mmc_data *data)
{
struct sg_mapping_iter miter;
size_t len, blocks = data->blocks;
int err = 0;
/* TODO: I don't know how/if the hardware handles non-16B-boundary blocks
* except single 8B block */
if (unlikely(data->blksz & 15 && (data->blocks != 1 || data->blksz != 8)))
return -EINVAL;
sg_miter_start(&miter, data->sg, data->sg_len, SG_MITER_TO_SG);
cb710_modify_port_8(slot, CB710_MMC_CONFIG2_PORT,
15, CB710_MMC_C2_READ_PIO_SIZE_MASK);
cb710_mmc_fifo_hack(slot);
while (blocks-- > 0) {
len = data->blksz;
while (len >= 16) {
err = cb710_mmc_receive_pio(slot, &miter, 4);
if (err)
goto out;
len -= 16;
}
if (!len)
continue;
cb710_modify_port_8(slot, CB710_MMC_CONFIG2_PORT,
len - 1, CB710_MMC_C2_READ_PIO_SIZE_MASK);
len = (len >= 8) ? 4 : 2;
err = cb710_mmc_receive_pio(slot, &miter, len);
if (err)
goto out;
}
out:
sg_miter_stop(&miter);
return err;
}
static int cb710_mmc_send(struct cb710_slot *slot, struct mmc_data *data)
{
struct sg_mapping_iter miter;
size_t len, blocks = data->blocks;
int err = 0;
/* TODO: I don't know how/if the hardware handles multiple
* non-16B-boundary blocks */
if (unlikely(data->blocks > 1 && data->blksz & 15))
return -EINVAL;
sg_miter_start(&miter, data->sg, data->sg_len, SG_MITER_FROM_SG);
cb710_modify_port_8(slot, CB710_MMC_CONFIG2_PORT,
0, CB710_MMC_C2_READ_PIO_SIZE_MASK);
while (blocks-- > 0) {
len = (data->blksz + 15) >> 4;
do {
if (!(cb710_read_port_8(slot, CB710_MMC_STATUS2_PORT)
& CB710_MMC_S2_FIFO_EMPTY)) {
err = cb710_wait_for_event(slot,
CB710_MMC_S1_PIO_TRANSFER_DONE);
if (err)
goto out;
}
cb710_sg_dwiter_read_to_io(&miter,
slot->iobase + CB710_MMC_DATA_PORT, 4);
} while (--len);
}
out:
sg_miter_stop(&miter);
return err;
}
static u16 cb710_encode_cmd_flags(struct cb710_mmc_reader *reader,
struct mmc_command *cmd)
{
unsigned int flags = cmd->flags;
u16 cb_flags = 0;
/* Windows driver returned 0 for commands for which no response
* is expected. It happened that there were only two such commands
* used: MMC_GO_IDLE_STATE and MMC_GO_INACTIVE_STATE so it might
* as well be a bug in that driver.
*
* Original driver set bit 14 for MMC/SD application
* commands. There's no difference 'on the wire' and
* it apparently works without it anyway.
*/
switch (flags & MMC_CMD_MASK) {
case MMC_CMD_AC: cb_flags = CB710_MMC_CMD_AC; break;
case MMC_CMD_ADTC: cb_flags = CB710_MMC_CMD_ADTC; break;
case MMC_CMD_BC: cb_flags = CB710_MMC_CMD_BC; break;
case MMC_CMD_BCR: cb_flags = CB710_MMC_CMD_BCR; break;
}
if (flags & MMC_RSP_BUSY)
cb_flags |= CB710_MMC_RSP_BUSY;
cb_flags |= cmd->opcode << CB710_MMC_CMD_CODE_SHIFT;
if (cmd->data && (cmd->data->flags & MMC_DATA_READ))
cb_flags |= CB710_MMC_DATA_READ;
if (flags & MMC_RSP_PRESENT) {
/* Windows driver set 01 at bits 4,3 except for
* MMC_SET_BLOCKLEN where it set 10. Maybe the
* hardware can do something special about this
* command? The original driver looks buggy/incomplete
* anyway so we ignore this for now.
*
* I assume that 00 here means no response is expected.
*/
cb_flags |= CB710_MMC_RSP_PRESENT;
if (flags & MMC_RSP_136)
cb_flags |= CB710_MMC_RSP_136;
if (!(flags & MMC_RSP_CRC))
cb_flags |= CB710_MMC_RSP_NO_CRC;
}
return cb_flags;
}
static void cb710_receive_response(struct cb710_slot *slot,
struct mmc_command *cmd)
{
unsigned rsp_opcode, wanted_opcode;
/* Looks like final byte with CRC is always stripped (same as SDHCI) */
if (cmd->flags & MMC_RSP_136) {
u32 resp[4];
resp[0] = cb710_read_port_32(slot, CB710_MMC_RESPONSE3_PORT);
resp[1] = cb710_read_port_32(slot, CB710_MMC_RESPONSE2_PORT);
resp[2] = cb710_read_port_32(slot, CB710_MMC_RESPONSE1_PORT);
resp[3] = cb710_read_port_32(slot, CB710_MMC_RESPONSE0_PORT);
rsp_opcode = resp[0] >> 24;
cmd->resp[0] = (resp[0] << 8)|(resp[1] >> 24);
cmd->resp[1] = (resp[1] << 8)|(resp[2] >> 24);
cmd->resp[2] = (resp[2] << 8)|(resp[3] >> 24);
cmd->resp[3] = (resp[3] << 8);
} else {
rsp_opcode = cb710_read_port_32(slot, CB710_MMC_RESPONSE1_PORT) & 0x3F;
cmd->resp[0] = cb710_read_port_32(slot, CB710_MMC_RESPONSE0_PORT);
}
wanted_opcode = (cmd->flags & MMC_RSP_OPCODE) ? cmd->opcode : 0x3F;
if (rsp_opcode != wanted_opcode)
cmd->error = -EILSEQ;
}
static int cb710_mmc_transfer_data(struct cb710_slot *slot,
struct mmc_data *data)
{
int error, to;
if (data->flags & MMC_DATA_READ)
error = cb710_mmc_receive(slot, data);
else
error = cb710_mmc_send(slot, data);
to = cb710_wait_for_event(slot, CB710_MMC_S1_DATA_TRANSFER_DONE);
if (!error)
error = to;
if (!error)
data->bytes_xfered = data->blksz * data->blocks;
return error;
}
static int cb710_mmc_command(struct mmc_host *mmc, struct mmc_command *cmd)
{
struct cb710_slot *slot = cb710_mmc_to_slot(mmc);
struct cb710_mmc_reader *reader = mmc_priv(mmc);
struct mmc_data *data = cmd->data;
u16 cb_cmd = cb710_encode_cmd_flags(reader, cmd);
dev_dbg(cb710_slot_dev(slot), "cmd request: 0x%04X\n", cb_cmd);
if (data) {
if (!cb710_is_transfer_size_supported(data)) {
data->error = -EINVAL;
return -1;
}
cb710_mmc_set_transfer_size(slot, data->blocks, data->blksz);
}
cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20|CB710_MMC_S2_BUSY_10);
cb710_write_port_16(slot, CB710_MMC_CMD_TYPE_PORT, cb_cmd);
cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20);
cb710_write_port_32(slot, CB710_MMC_CMD_PARAM_PORT, cmd->arg);
cb710_mmc_reset_events(slot);
cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20);
cb710_modify_port_8(slot, CB710_MMC_CONFIG0_PORT, 0x01, 0);
cmd->error = cb710_wait_for_event(slot, CB710_MMC_S1_COMMAND_SENT);
if (cmd->error)
return -1;
if (cmd->flags & MMC_RSP_PRESENT) {
cb710_receive_response(slot, cmd);
if (cmd->error)
return -1;
}
if (data)
data->error = cb710_mmc_transfer_data(slot, data);
return 0;
}
static void cb710_mmc_request(struct mmc_host *mmc, struct mmc_request *mrq)
{
struct cb710_slot *slot = cb710_mmc_to_slot(mmc);
struct cb710_mmc_reader *reader = mmc_priv(mmc);
WARN_ON(reader->mrq != NULL);
reader->mrq = mrq;
cb710_mmc_enable_irq(slot, CB710_MMC_IE_TEST_MASK, 0);
if (!cb710_mmc_command(mmc, mrq->cmd) && mrq->stop)
cb710_mmc_command(mmc, mrq->stop);
tasklet_schedule(&reader->finish_req_tasklet);
}
static int cb710_mmc_powerup(struct cb710_slot *slot)
{
#ifdef CONFIG_CB710_DEBUG
struct cb710_chip *chip = cb710_slot_to_chip(slot);
#endif
int err;
/* a lot of magic for now */
dev_dbg(cb710_slot_dev(slot), "bus powerup\n");
cb710_dump_regs(chip, CB710_DUMP_REGS_MMC);
err = cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20);
if (unlikely(err))
return err;
cb710_modify_port_8(slot, CB710_MMC_CONFIG1_PORT, 0x80, 0);
cb710_modify_port_8(slot, CB710_MMC_CONFIG3_PORT, 0x80, 0);
cb710_dump_regs(chip, CB710_DUMP_REGS_MMC);
mdelay(1);
dev_dbg(cb710_slot_dev(slot), "after delay 1\n");
cb710_dump_regs(chip, CB710_DUMP_REGS_MMC);
err = cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20);
if (unlikely(err))
return err;
cb710_modify_port_8(slot, CB710_MMC_CONFIG1_PORT, 0x09, 0);
cb710_dump_regs(chip, CB710_DUMP_REGS_MMC);
mdelay(1);
dev_dbg(cb710_slot_dev(slot), "after delay 2\n");
cb710_dump_regs(chip, CB710_DUMP_REGS_MMC);
err = cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20);
if (unlikely(err))
return err;
cb710_modify_port_8(slot, CB710_MMC_CONFIG1_PORT, 0, 0x08);
cb710_dump_regs(chip, CB710_DUMP_REGS_MMC);
mdelay(2);
dev_dbg(cb710_slot_dev(slot), "after delay 3\n");
cb710_dump_regs(chip, CB710_DUMP_REGS_MMC);
cb710_modify_port_8(slot, CB710_MMC_CONFIG0_PORT, 0x06, 0);
cb710_modify_port_8(slot, CB710_MMC_CONFIG1_PORT, 0x70, 0);
cb710_modify_port_8(slot, CB710_MMC_CONFIG2_PORT, 0x80, 0);
cb710_modify_port_8(slot, CB710_MMC_CONFIG3_PORT, 0x03, 0);
cb710_dump_regs(chip, CB710_DUMP_REGS_MMC);
err = cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20);
if (unlikely(err))
return err;
/* This port behaves weird: quick byte reads of 0x08,0x09 return
* 0xFF,0x00 after writing 0xFFFF to 0x08; it works correctly when
* read/written from userspace... What am I missing here?
* (it doesn't depend on write-to-read delay) */
cb710_write_port_16(slot, CB710_MMC_CONFIGB_PORT, 0xFFFF);
cb710_modify_port_8(slot, CB710_MMC_CONFIG0_PORT, 0x06, 0);
cb710_dump_regs(chip, CB710_DUMP_REGS_MMC);
dev_dbg(cb710_slot_dev(slot), "bus powerup finished\n");
return cb710_check_event(slot, 0);
}
static void cb710_mmc_powerdown(struct cb710_slot *slot)
{
cb710_modify_port_8(slot, CB710_MMC_CONFIG1_PORT, 0, 0x81);
cb710_modify_port_8(slot, CB710_MMC_CONFIG3_PORT, 0, 0x80);
}
static void cb710_mmc_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct cb710_slot *slot = cb710_mmc_to_slot(mmc);
struct cb710_mmc_reader *reader = mmc_priv(mmc);
int err;
cb710_mmc_select_clock_divider(mmc, ios->clock);
if (ios->power_mode != reader->last_power_mode)
switch (ios->power_mode) {
case MMC_POWER_ON:
err = cb710_mmc_powerup(slot);
if (err) {
dev_warn(cb710_slot_dev(slot),
"powerup failed (%d)- retrying\n", err);
cb710_mmc_powerdown(slot);
udelay(1);
err = cb710_mmc_powerup(slot);
if (err)
dev_warn(cb710_slot_dev(slot),
"powerup retry failed (%d) - expect errors\n",
err);
}
reader->last_power_mode = MMC_POWER_ON;
break;
case MMC_POWER_OFF:
cb710_mmc_powerdown(slot);
reader->last_power_mode = MMC_POWER_OFF;
break;
case MMC_POWER_UP:
default:
/* ignore */;
}
cb710_mmc_enable_4bit_data(slot, ios->bus_width != MMC_BUS_WIDTH_1);
cb710_mmc_enable_irq(slot, CB710_MMC_IE_TEST_MASK, 0);
}
static int cb710_mmc_get_ro(struct mmc_host *mmc)
{
struct cb710_slot *slot = cb710_mmc_to_slot(mmc);
return cb710_read_port_8(slot, CB710_MMC_STATUS3_PORT)
& CB710_MMC_S3_WRITE_PROTECTED;
}
static int cb710_mmc_get_cd(struct mmc_host *mmc)
{
struct cb710_slot *slot = cb710_mmc_to_slot(mmc);
return cb710_read_port_8(slot, CB710_MMC_STATUS3_PORT)
& CB710_MMC_S3_CARD_DETECTED;
}
static int cb710_mmc_irq_handler(struct cb710_slot *slot)
{
struct mmc_host *mmc = cb710_slot_to_mmc(slot);
struct cb710_mmc_reader *reader = mmc_priv(mmc);
u32 status, config1, config2, irqen;
status = cb710_read_port_32(slot, CB710_MMC_STATUS_PORT);
irqen = cb710_read_port_32(slot, CB710_MMC_IRQ_ENABLE_PORT);
config2 = cb710_read_port_32(slot, CB710_MMC_CONFIGB_PORT);
config1 = cb710_read_port_32(slot, CB710_MMC_CONFIG_PORT);
dev_dbg(cb710_slot_dev(slot), "interrupt; status: %08X, "
"ie: %08X, c2: %08X, c1: %08X\n",
status, irqen, config2, config1);
if (status & (CB710_MMC_S1_CARD_CHANGED << 8)) {
/* ack the event */
cb710_write_port_8(slot, CB710_MMC_STATUS1_PORT,
CB710_MMC_S1_CARD_CHANGED);
if ((irqen & CB710_MMC_IE_CISTATUS_MASK)
== CB710_MMC_IE_CISTATUS_MASK)
mmc_detect_change(mmc, HZ/5);
} else {
dev_dbg(cb710_slot_dev(slot), "unknown interrupt (test)\n");
spin_lock(&reader->irq_lock);
__cb710_mmc_enable_irq(slot, 0, CB710_MMC_IE_TEST_MASK);
spin_unlock(&reader->irq_lock);
}
return 1;
}
static void cb710_mmc_finish_request_tasklet(unsigned long data)
{
struct mmc_host *mmc = (void *)data;
struct cb710_mmc_reader *reader = mmc_priv(mmc);
struct mmc_request *mrq = reader->mrq;
reader->mrq = NULL;
mmc_request_done(mmc, mrq);
}
static const struct mmc_host_ops cb710_mmc_host = {
.request = cb710_mmc_request,
.set_ios = cb710_mmc_set_ios,
.get_ro = cb710_mmc_get_ro,
.get_cd = cb710_mmc_get_cd,
};
#ifdef CONFIG_PM
static int cb710_mmc_suspend(struct platform_device *pdev, pm_message_t state)
{
struct cb710_slot *slot = cb710_pdev_to_slot(pdev);
struct mmc_host *mmc = cb710_slot_to_mmc(slot);
int err;
err = mmc_suspend_host(mmc);
if (err)
return err;
cb710_mmc_enable_irq(slot, 0, ~0);
return 0;
}
static int cb710_mmc_resume(struct platform_device *pdev)
{
struct cb710_slot *slot = cb710_pdev_to_slot(pdev);
struct mmc_host *mmc = cb710_slot_to_mmc(slot);
cb710_mmc_enable_irq(slot, 0, ~0);
return mmc_resume_host(mmc);
}
#endif /* CONFIG_PM */
static int cb710_mmc_init(struct platform_device *pdev)
{
struct cb710_slot *slot = cb710_pdev_to_slot(pdev);
struct cb710_chip *chip = cb710_slot_to_chip(slot);
struct mmc_host *mmc;
struct cb710_mmc_reader *reader;
int err;
u32 val;
mmc = mmc_alloc_host(sizeof(*reader), cb710_slot_dev(slot));
if (!mmc)
return -ENOMEM;
dev_set_drvdata(&pdev->dev, mmc);
/* harmless (maybe) magic */
pci_read_config_dword(chip->pdev, 0x48, &val);
val = cb710_src_freq_mhz[(val >> 16) & 0xF];
dev_dbg(cb710_slot_dev(slot), "source frequency: %dMHz\n", val);
val *= 1000000;
mmc->ops = &cb710_mmc_host;
mmc->f_max = val;
mmc->f_min = val >> cb710_clock_divider_log2[CB710_MAX_DIVIDER_IDX];
mmc->ocr_avail = MMC_VDD_32_33|MMC_VDD_33_34;
mmc->caps = MMC_CAP_4_BIT_DATA;
reader = mmc_priv(mmc);
tasklet_init(&reader->finish_req_tasklet,
cb710_mmc_finish_request_tasklet, (unsigned long)mmc);
spin_lock_init(&reader->irq_lock);
cb710_dump_regs(chip, CB710_DUMP_REGS_MMC);
cb710_mmc_enable_irq(slot, 0, ~0);
cb710_set_irq_handler(slot, cb710_mmc_irq_handler);
err = mmc_add_host(mmc);
if (unlikely(err))
goto err_free_mmc;
dev_dbg(cb710_slot_dev(slot), "mmc_hostname is %s\n",
mmc_hostname(mmc));
cb710_mmc_enable_irq(slot, CB710_MMC_IE_CARD_INSERTION_STATUS, 0);
return 0;
err_free_mmc:
dev_dbg(cb710_slot_dev(slot), "mmc_add_host() failed: %d\n", err);
cb710_set_irq_handler(slot, NULL);
mmc_free_host(mmc);
return err;
}
static int cb710_mmc_exit(struct platform_device *pdev)
{
struct cb710_slot *slot = cb710_pdev_to_slot(pdev);
struct mmc_host *mmc = cb710_slot_to_mmc(slot);
struct cb710_mmc_reader *reader = mmc_priv(mmc);
cb710_mmc_enable_irq(slot, 0, CB710_MMC_IE_CARD_INSERTION_STATUS);
mmc_remove_host(mmc);
/* IRQs should be disabled now, but let's stay on the safe side */
cb710_mmc_enable_irq(slot, 0, ~0);
cb710_set_irq_handler(slot, NULL);
/* clear config ports - just in case */
cb710_write_port_32(slot, CB710_MMC_CONFIG_PORT, 0);
cb710_write_port_16(slot, CB710_MMC_CONFIGB_PORT, 0);
tasklet_kill(&reader->finish_req_tasklet);
mmc_free_host(mmc);
return 0;
}
static struct platform_driver cb710_mmc_driver = {
.driver.name = "cb710-mmc",
.probe = cb710_mmc_init,
.remove = cb710_mmc_exit,
#ifdef CONFIG_PM
.suspend = cb710_mmc_suspend,
.resume = cb710_mmc_resume,
#endif
};
module_platform_driver(cb710_mmc_driver);
MODULE_AUTHOR("Michał Mirosław <mirq-linux@rere.qmqm.pl>");
MODULE_DESCRIPTION("ENE CB710 memory card reader driver - MMC/SD part");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:cb710-mmc");
| gpl-2.0 |
burstlam/pantech_kernel_A850 | drivers/net/wireless/wl12xx/tx.c | 4809 | 28896 | /*
* This file is part of wl1271
*
* Copyright (C) 2009 Nokia Corporation
*
* Contact: Luciano Coelho <luciano.coelho@nokia.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/etherdevice.h>
#include "wl12xx.h"
#include "debug.h"
#include "io.h"
#include "reg.h"
#include "ps.h"
#include "tx.h"
#include "event.h"
static int wl1271_set_default_wep_key(struct wl1271 *wl,
struct wl12xx_vif *wlvif, u8 id)
{
int ret;
bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS);
if (is_ap)
ret = wl12xx_cmd_set_default_wep_key(wl, id,
wlvif->ap.bcast_hlid);
else
ret = wl12xx_cmd_set_default_wep_key(wl, id, wlvif->sta.hlid);
if (ret < 0)
return ret;
wl1271_debug(DEBUG_CRYPT, "default wep key idx: %d", (int)id);
return 0;
}
static int wl1271_alloc_tx_id(struct wl1271 *wl, struct sk_buff *skb)
{
int id;
id = find_first_zero_bit(wl->tx_frames_map, ACX_TX_DESCRIPTORS);
if (id >= ACX_TX_DESCRIPTORS)
return -EBUSY;
__set_bit(id, wl->tx_frames_map);
wl->tx_frames[id] = skb;
wl->tx_frames_cnt++;
return id;
}
static void wl1271_free_tx_id(struct wl1271 *wl, int id)
{
if (__test_and_clear_bit(id, wl->tx_frames_map)) {
if (unlikely(wl->tx_frames_cnt == ACX_TX_DESCRIPTORS))
clear_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags);
wl->tx_frames[id] = NULL;
wl->tx_frames_cnt--;
}
}
static void wl1271_tx_ap_update_inconnection_sta(struct wl1271 *wl,
struct sk_buff *skb)
{
struct ieee80211_hdr *hdr;
/*
* add the station to the known list before transmitting the
* authentication response. this way it won't get de-authed by FW
* when transmitting too soon.
*/
hdr = (struct ieee80211_hdr *)(skb->data +
sizeof(struct wl1271_tx_hw_descr));
if (ieee80211_is_auth(hdr->frame_control))
wl1271_acx_set_inconnection_sta(wl, hdr->addr1);
}
static void wl1271_tx_regulate_link(struct wl1271 *wl,
struct wl12xx_vif *wlvif,
u8 hlid)
{
bool fw_ps, single_sta;
u8 tx_pkts;
if (WARN_ON(!test_bit(hlid, wlvif->links_map)))
return;
fw_ps = test_bit(hlid, (unsigned long *)&wl->ap_fw_ps_map);
tx_pkts = wl->links[hlid].allocated_pkts;
single_sta = (wl->active_sta_count == 1);
/*
* if in FW PS and there is enough data in FW we can put the link
* into high-level PS and clean out its TX queues.
* Make an exception if this is the only connected station. In this
* case FW-memory congestion is not a problem.
*/
if (!single_sta && fw_ps && tx_pkts >= WL1271_PS_STA_MAX_PACKETS)
wl12xx_ps_link_start(wl, wlvif, hlid, true);
}
bool wl12xx_is_dummy_packet(struct wl1271 *wl, struct sk_buff *skb)
{
return wl->dummy_packet == skb;
}
u8 wl12xx_tx_get_hlid_ap(struct wl1271 *wl, struct wl12xx_vif *wlvif,
struct sk_buff *skb)
{
struct ieee80211_tx_info *control = IEEE80211_SKB_CB(skb);
if (control->control.sta) {
struct wl1271_station *wl_sta;
wl_sta = (struct wl1271_station *)
control->control.sta->drv_priv;
return wl_sta->hlid;
} else {
struct ieee80211_hdr *hdr;
if (!test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags))
return wl->system_hlid;
hdr = (struct ieee80211_hdr *)skb->data;
if (ieee80211_is_mgmt(hdr->frame_control))
return wlvif->ap.global_hlid;
else
return wlvif->ap.bcast_hlid;
}
}
u8 wl12xx_tx_get_hlid(struct wl1271 *wl, struct wl12xx_vif *wlvif,
struct sk_buff *skb)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
if (!wlvif || wl12xx_is_dummy_packet(wl, skb))
return wl->system_hlid;
if (wlvif->bss_type == BSS_TYPE_AP_BSS)
return wl12xx_tx_get_hlid_ap(wl, wlvif, skb);
if ((test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) ||
test_bit(WLVIF_FLAG_IBSS_JOINED, &wlvif->flags)) &&
!ieee80211_is_auth(hdr->frame_control) &&
!ieee80211_is_assoc_req(hdr->frame_control))
return wlvif->sta.hlid;
else
return wlvif->dev_hlid;
}
static unsigned int wl12xx_calc_packet_alignment(struct wl1271 *wl,
unsigned int packet_length)
{
if (wl->quirks & WL12XX_QUIRK_NO_BLOCKSIZE_ALIGNMENT)
return ALIGN(packet_length, WL1271_TX_ALIGN_TO);
else
return ALIGN(packet_length, WL12XX_BUS_BLOCK_SIZE);
}
static int wl1271_tx_allocate(struct wl1271 *wl, struct wl12xx_vif *wlvif,
struct sk_buff *skb, u32 extra, u32 buf_offset,
u8 hlid)
{
struct wl1271_tx_hw_descr *desc;
u32 total_len = skb->len + sizeof(struct wl1271_tx_hw_descr) + extra;
u32 len;
u32 total_blocks;
int id, ret = -EBUSY, ac;
u32 spare_blocks = wl->tx_spare_blocks;
bool is_dummy = false;
if (buf_offset + total_len > WL1271_AGGR_BUFFER_SIZE)
return -EAGAIN;
/* allocate free identifier for the packet */
id = wl1271_alloc_tx_id(wl, skb);
if (id < 0)
return id;
/* approximate the number of blocks required for this packet
in the firmware */
len = wl12xx_calc_packet_alignment(wl, total_len);
/* in case of a dummy packet, use default amount of spare mem blocks */
if (unlikely(wl12xx_is_dummy_packet(wl, skb))) {
is_dummy = true;
spare_blocks = TX_HW_BLOCK_SPARE_DEFAULT;
}
total_blocks = (len + TX_HW_BLOCK_SIZE - 1) / TX_HW_BLOCK_SIZE +
spare_blocks;
if (total_blocks <= wl->tx_blocks_available) {
desc = (struct wl1271_tx_hw_descr *)skb_push(
skb, total_len - skb->len);
/* HW descriptor fields change between wl127x and wl128x */
if (wl->chip.id == CHIP_ID_1283_PG20) {
desc->wl128x_mem.total_mem_blocks = total_blocks;
} else {
desc->wl127x_mem.extra_blocks = spare_blocks;
desc->wl127x_mem.total_mem_blocks = total_blocks;
}
desc->id = id;
wl->tx_blocks_available -= total_blocks;
wl->tx_allocated_blocks += total_blocks;
/* If the FW was empty before, arm the Tx watchdog */
if (wl->tx_allocated_blocks == total_blocks)
wl12xx_rearm_tx_watchdog_locked(wl);
ac = wl1271_tx_get_queue(skb_get_queue_mapping(skb));
wl->tx_allocated_pkts[ac]++;
if (!is_dummy && wlvif &&
wlvif->bss_type == BSS_TYPE_AP_BSS &&
test_bit(hlid, wlvif->ap.sta_hlid_map))
wl->links[hlid].allocated_pkts++;
ret = 0;
wl1271_debug(DEBUG_TX,
"tx_allocate: size: %d, blocks: %d, id: %d",
total_len, total_blocks, id);
} else {
wl1271_free_tx_id(wl, id);
}
return ret;
}
static void wl1271_tx_fill_hdr(struct wl1271 *wl, struct wl12xx_vif *wlvif,
struct sk_buff *skb, u32 extra,
struct ieee80211_tx_info *control, u8 hlid)
{
struct timespec ts;
struct wl1271_tx_hw_descr *desc;
int aligned_len, ac, rate_idx;
s64 hosttime;
u16 tx_attr = 0;
__le16 frame_control;
struct ieee80211_hdr *hdr;
u8 *frame_start;
bool is_dummy;
desc = (struct wl1271_tx_hw_descr *) skb->data;
frame_start = (u8 *)(desc + 1);
hdr = (struct ieee80211_hdr *)(frame_start + extra);
frame_control = hdr->frame_control;
/* relocate space for security header */
if (extra) {
int hdrlen = ieee80211_hdrlen(frame_control);
memmove(frame_start, hdr, hdrlen);
}
/* configure packet life time */
getnstimeofday(&ts);
hosttime = (timespec_to_ns(&ts) >> 10);
desc->start_time = cpu_to_le32(hosttime - wl->time_offset);
is_dummy = wl12xx_is_dummy_packet(wl, skb);
if (is_dummy || !wlvif || wlvif->bss_type != BSS_TYPE_AP_BSS)
desc->life_time = cpu_to_le16(TX_HW_MGMT_PKT_LIFETIME_TU);
else
desc->life_time = cpu_to_le16(TX_HW_AP_MODE_PKT_LIFETIME_TU);
/* queue */
ac = wl1271_tx_get_queue(skb_get_queue_mapping(skb));
desc->tid = skb->priority;
if (is_dummy) {
/*
* FW expects the dummy packet to have an invalid session id -
* any session id that is different than the one set in the join
*/
tx_attr = (SESSION_COUNTER_INVALID <<
TX_HW_ATTR_OFST_SESSION_COUNTER) &
TX_HW_ATTR_SESSION_COUNTER;
tx_attr |= TX_HW_ATTR_TX_DUMMY_REQ;
} else if (wlvif) {
/* configure the tx attributes */
tx_attr = wlvif->session_counter <<
TX_HW_ATTR_OFST_SESSION_COUNTER;
}
desc->hlid = hlid;
if (is_dummy || !wlvif)
rate_idx = 0;
else if (wlvif->bss_type != BSS_TYPE_AP_BSS) {
/* if the packets are destined for AP (have a STA entry)
send them with AP rate policies, otherwise use default
basic rates */
if (control->flags & IEEE80211_TX_CTL_NO_CCK_RATE)
rate_idx = wlvif->sta.p2p_rate_idx;
else if (control->control.sta)
rate_idx = wlvif->sta.ap_rate_idx;
else
rate_idx = wlvif->sta.basic_rate_idx;
} else {
if (hlid == wlvif->ap.global_hlid)
rate_idx = wlvif->ap.mgmt_rate_idx;
else if (hlid == wlvif->ap.bcast_hlid)
rate_idx = wlvif->ap.bcast_rate_idx;
else
rate_idx = wlvif->ap.ucast_rate_idx[ac];
}
tx_attr |= rate_idx << TX_HW_ATTR_OFST_RATE_POLICY;
desc->reserved = 0;
aligned_len = wl12xx_calc_packet_alignment(wl, skb->len);
if (wl->chip.id == CHIP_ID_1283_PG20) {
desc->wl128x_mem.extra_bytes = aligned_len - skb->len;
desc->length = cpu_to_le16(aligned_len >> 2);
wl1271_debug(DEBUG_TX, "tx_fill_hdr: hlid: %d "
"tx_attr: 0x%x len: %d life: %d mem: %d",
desc->hlid, tx_attr,
le16_to_cpu(desc->length),
le16_to_cpu(desc->life_time),
desc->wl128x_mem.total_mem_blocks);
} else {
int pad;
/* Store the aligned length in terms of words */
desc->length = cpu_to_le16(aligned_len >> 2);
/* calculate number of padding bytes */
pad = aligned_len - skb->len;
tx_attr |= pad << TX_HW_ATTR_OFST_LAST_WORD_PAD;
wl1271_debug(DEBUG_TX, "tx_fill_hdr: pad: %d hlid: %d "
"tx_attr: 0x%x len: %d life: %d mem: %d", pad,
desc->hlid, tx_attr,
le16_to_cpu(desc->length),
le16_to_cpu(desc->life_time),
desc->wl127x_mem.total_mem_blocks);
}
/* for WEP shared auth - no fw encryption is needed */
if (ieee80211_is_auth(frame_control) &&
ieee80211_has_protected(frame_control))
tx_attr |= TX_HW_ATTR_HOST_ENCRYPT;
desc->tx_attr = cpu_to_le16(tx_attr);
}
/* caller must hold wl->mutex */
static int wl1271_prepare_tx_frame(struct wl1271 *wl, struct wl12xx_vif *wlvif,
struct sk_buff *skb, u32 buf_offset)
{
struct ieee80211_tx_info *info;
u32 extra = 0;
int ret = 0;
u32 total_len;
u8 hlid;
bool is_dummy;
if (!skb)
return -EINVAL;
info = IEEE80211_SKB_CB(skb);
/* TODO: handle dummy packets on multi-vifs */
is_dummy = wl12xx_is_dummy_packet(wl, skb);
if (info->control.hw_key &&
info->control.hw_key->cipher == WLAN_CIPHER_SUITE_TKIP)
extra = WL1271_EXTRA_SPACE_TKIP;
if (info->control.hw_key) {
bool is_wep;
u8 idx = info->control.hw_key->hw_key_idx;
u32 cipher = info->control.hw_key->cipher;
is_wep = (cipher == WLAN_CIPHER_SUITE_WEP40) ||
(cipher == WLAN_CIPHER_SUITE_WEP104);
if (unlikely(is_wep && wlvif->default_key != idx)) {
ret = wl1271_set_default_wep_key(wl, wlvif, idx);
if (ret < 0)
return ret;
wlvif->default_key = idx;
}
}
hlid = wl12xx_tx_get_hlid(wl, wlvif, skb);
if (hlid == WL12XX_INVALID_LINK_ID) {
wl1271_error("invalid hlid. dropping skb 0x%p", skb);
return -EINVAL;
}
ret = wl1271_tx_allocate(wl, wlvif, skb, extra, buf_offset, hlid);
if (ret < 0)
return ret;
wl1271_tx_fill_hdr(wl, wlvif, skb, extra, info, hlid);
if (!is_dummy && wlvif && wlvif->bss_type == BSS_TYPE_AP_BSS) {
wl1271_tx_ap_update_inconnection_sta(wl, skb);
wl1271_tx_regulate_link(wl, wlvif, hlid);
}
/*
* The length of each packet is stored in terms of
* words. Thus, we must pad the skb data to make sure its
* length is aligned. The number of padding bytes is computed
* and set in wl1271_tx_fill_hdr.
* In special cases, we want to align to a specific block size
* (eg. for wl128x with SDIO we align to 256).
*/
total_len = wl12xx_calc_packet_alignment(wl, skb->len);
memcpy(wl->aggr_buf + buf_offset, skb->data, skb->len);
memset(wl->aggr_buf + buf_offset + skb->len, 0, total_len - skb->len);
/* Revert side effects in the dummy packet skb, so it can be reused */
if (is_dummy)
skb_pull(skb, sizeof(struct wl1271_tx_hw_descr));
return total_len;
}
u32 wl1271_tx_enabled_rates_get(struct wl1271 *wl, u32 rate_set,
enum ieee80211_band rate_band)
{
struct ieee80211_supported_band *band;
u32 enabled_rates = 0;
int bit;
band = wl->hw->wiphy->bands[rate_band];
for (bit = 0; bit < band->n_bitrates; bit++) {
if (rate_set & 0x1)
enabled_rates |= band->bitrates[bit].hw_value;
rate_set >>= 1;
}
/* MCS rates indication are on bits 16 - 23 */
rate_set >>= HW_HT_RATES_OFFSET - band->n_bitrates;
for (bit = 0; bit < 8; bit++) {
if (rate_set & 0x1)
enabled_rates |= (CONF_HW_BIT_RATE_MCS_0 << bit);
rate_set >>= 1;
}
return enabled_rates;
}
void wl1271_handle_tx_low_watermark(struct wl1271 *wl)
{
unsigned long flags;
int i;
for (i = 0; i < NUM_TX_QUEUES; i++) {
if (test_bit(i, &wl->stopped_queues_map) &&
wl->tx_queue_count[i] <= WL1271_TX_QUEUE_LOW_WATERMARK) {
/* firmware buffer has space, restart queues */
spin_lock_irqsave(&wl->wl_lock, flags);
ieee80211_wake_queue(wl->hw,
wl1271_tx_get_mac80211_queue(i));
clear_bit(i, &wl->stopped_queues_map);
spin_unlock_irqrestore(&wl->wl_lock, flags);
}
}
}
static struct sk_buff_head *wl1271_select_queue(struct wl1271 *wl,
struct sk_buff_head *queues)
{
int i, q = -1, ac;
u32 min_pkts = 0xffffffff;
/*
* Find a non-empty ac where:
* 1. There are packets to transmit
* 2. The FW has the least allocated blocks
*
* We prioritize the ACs according to VO>VI>BE>BK
*/
for (i = 0; i < NUM_TX_QUEUES; i++) {
ac = wl1271_tx_get_queue(i);
if (!skb_queue_empty(&queues[ac]) &&
(wl->tx_allocated_pkts[ac] < min_pkts)) {
q = ac;
min_pkts = wl->tx_allocated_pkts[q];
}
}
if (q == -1)
return NULL;
return &queues[q];
}
static struct sk_buff *wl12xx_lnk_skb_dequeue(struct wl1271 *wl,
struct wl1271_link *lnk)
{
struct sk_buff *skb;
unsigned long flags;
struct sk_buff_head *queue;
queue = wl1271_select_queue(wl, lnk->tx_queue);
if (!queue)
return NULL;
skb = skb_dequeue(queue);
if (skb) {
int q = wl1271_tx_get_queue(skb_get_queue_mapping(skb));
spin_lock_irqsave(&wl->wl_lock, flags);
WARN_ON_ONCE(wl->tx_queue_count[q] <= 0);
wl->tx_queue_count[q]--;
spin_unlock_irqrestore(&wl->wl_lock, flags);
}
return skb;
}
static struct sk_buff *wl12xx_vif_skb_dequeue(struct wl1271 *wl,
struct wl12xx_vif *wlvif)
{
struct sk_buff *skb = NULL;
int i, h, start_hlid;
/* start from the link after the last one */
start_hlid = (wlvif->last_tx_hlid + 1) % WL12XX_MAX_LINKS;
/* dequeue according to AC, round robin on each link */
for (i = 0; i < WL12XX_MAX_LINKS; i++) {
h = (start_hlid + i) % WL12XX_MAX_LINKS;
/* only consider connected stations */
if (!test_bit(h, wlvif->links_map))
continue;
skb = wl12xx_lnk_skb_dequeue(wl, &wl->links[h]);
if (!skb)
continue;
wlvif->last_tx_hlid = h;
break;
}
if (!skb)
wlvif->last_tx_hlid = 0;
return skb;
}
static struct sk_buff *wl1271_skb_dequeue(struct wl1271 *wl)
{
unsigned long flags;
struct wl12xx_vif *wlvif = wl->last_wlvif;
struct sk_buff *skb = NULL;
/* continue from last wlvif (round robin) */
if (wlvif) {
wl12xx_for_each_wlvif_continue(wl, wlvif) {
skb = wl12xx_vif_skb_dequeue(wl, wlvif);
if (skb) {
wl->last_wlvif = wlvif;
break;
}
}
}
/* dequeue from the system HLID before the restarting wlvif list */
if (!skb)
skb = wl12xx_lnk_skb_dequeue(wl, &wl->links[wl->system_hlid]);
/* do a new pass over the wlvif list */
if (!skb) {
wl12xx_for_each_wlvif(wl, wlvif) {
skb = wl12xx_vif_skb_dequeue(wl, wlvif);
if (skb) {
wl->last_wlvif = wlvif;
break;
}
/*
* No need to continue after last_wlvif. The previous
* pass should have found it.
*/
if (wlvif == wl->last_wlvif)
break;
}
}
if (!skb &&
test_and_clear_bit(WL1271_FLAG_DUMMY_PACKET_PENDING, &wl->flags)) {
int q;
skb = wl->dummy_packet;
q = wl1271_tx_get_queue(skb_get_queue_mapping(skb));
spin_lock_irqsave(&wl->wl_lock, flags);
WARN_ON_ONCE(wl->tx_queue_count[q] <= 0);
wl->tx_queue_count[q]--;
spin_unlock_irqrestore(&wl->wl_lock, flags);
}
return skb;
}
static void wl1271_skb_queue_head(struct wl1271 *wl, struct wl12xx_vif *wlvif,
struct sk_buff *skb)
{
unsigned long flags;
int q = wl1271_tx_get_queue(skb_get_queue_mapping(skb));
if (wl12xx_is_dummy_packet(wl, skb)) {
set_bit(WL1271_FLAG_DUMMY_PACKET_PENDING, &wl->flags);
} else {
u8 hlid = wl12xx_tx_get_hlid(wl, wlvif, skb);
skb_queue_head(&wl->links[hlid].tx_queue[q], skb);
/* make sure we dequeue the same packet next time */
wlvif->last_tx_hlid = (hlid + WL12XX_MAX_LINKS - 1) %
WL12XX_MAX_LINKS;
}
spin_lock_irqsave(&wl->wl_lock, flags);
wl->tx_queue_count[q]++;
spin_unlock_irqrestore(&wl->wl_lock, flags);
}
static bool wl1271_tx_is_data_present(struct sk_buff *skb)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)(skb->data);
return ieee80211_is_data_present(hdr->frame_control);
}
void wl12xx_rearm_rx_streaming(struct wl1271 *wl, unsigned long *active_hlids)
{
struct wl12xx_vif *wlvif;
u32 timeout;
u8 hlid;
if (!wl->conf.rx_streaming.interval)
return;
if (!wl->conf.rx_streaming.always &&
!test_bit(WL1271_FLAG_SOFT_GEMINI, &wl->flags))
return;
timeout = wl->conf.rx_streaming.duration;
wl12xx_for_each_wlvif_sta(wl, wlvif) {
bool found = false;
for_each_set_bit(hlid, active_hlids, WL12XX_MAX_LINKS) {
if (test_bit(hlid, wlvif->links_map)) {
found = true;
break;
}
}
if (!found)
continue;
/* enable rx streaming */
if (!test_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags))
ieee80211_queue_work(wl->hw,
&wlvif->rx_streaming_enable_work);
mod_timer(&wlvif->rx_streaming_timer,
jiffies + msecs_to_jiffies(timeout));
}
}
void wl1271_tx_work_locked(struct wl1271 *wl)
{
struct wl12xx_vif *wlvif;
struct sk_buff *skb;
struct wl1271_tx_hw_descr *desc;
u32 buf_offset = 0;
bool sent_packets = false;
unsigned long active_hlids[BITS_TO_LONGS(WL12XX_MAX_LINKS)] = {0};
int ret;
if (unlikely(wl->state == WL1271_STATE_OFF))
return;
while ((skb = wl1271_skb_dequeue(wl))) {
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
bool has_data = false;
wlvif = NULL;
if (!wl12xx_is_dummy_packet(wl, skb) && info->control.vif)
wlvif = wl12xx_vif_to_data(info->control.vif);
has_data = wlvif && wl1271_tx_is_data_present(skb);
ret = wl1271_prepare_tx_frame(wl, wlvif, skb, buf_offset);
if (ret == -EAGAIN) {
/*
* Aggregation buffer is full.
* Flush buffer and try again.
*/
wl1271_skb_queue_head(wl, wlvif, skb);
wl1271_write(wl, WL1271_SLV_MEM_DATA, wl->aggr_buf,
buf_offset, true);
sent_packets = true;
buf_offset = 0;
continue;
} else if (ret == -EBUSY) {
/*
* Firmware buffer is full.
* Queue back last skb, and stop aggregating.
*/
wl1271_skb_queue_head(wl, wlvif, skb);
/* No work left, avoid scheduling redundant tx work */
set_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags);
goto out_ack;
} else if (ret < 0) {
if (wl12xx_is_dummy_packet(wl, skb))
/*
* fw still expects dummy packet,
* so re-enqueue it
*/
wl1271_skb_queue_head(wl, wlvif, skb);
else
ieee80211_free_txskb(wl->hw, skb);
goto out_ack;
}
buf_offset += ret;
wl->tx_packets_count++;
if (has_data) {
desc = (struct wl1271_tx_hw_descr *) skb->data;
__set_bit(desc->hlid, active_hlids);
}
}
out_ack:
if (buf_offset) {
wl1271_write(wl, WL1271_SLV_MEM_DATA, wl->aggr_buf,
buf_offset, true);
sent_packets = true;
}
if (sent_packets) {
/*
* Interrupt the firmware with the new packets. This is only
* required for older hardware revisions
*/
if (wl->quirks & WL12XX_QUIRK_END_OF_TRANSACTION)
wl1271_write32(wl, WL1271_HOST_WR_ACCESS,
wl->tx_packets_count);
wl1271_handle_tx_low_watermark(wl);
}
wl12xx_rearm_rx_streaming(wl, active_hlids);
}
void wl1271_tx_work(struct work_struct *work)
{
struct wl1271 *wl = container_of(work, struct wl1271, tx_work);
int ret;
mutex_lock(&wl->mutex);
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl1271_tx_work_locked(wl);
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static u8 wl1271_tx_get_rate_flags(u8 rate_class_index)
{
u8 flags = 0;
if (rate_class_index >= CONF_HW_RXTX_RATE_MCS_MIN &&
rate_class_index <= CONF_HW_RXTX_RATE_MCS_MAX)
flags |= IEEE80211_TX_RC_MCS;
if (rate_class_index == CONF_HW_RXTX_RATE_MCS7_SGI)
flags |= IEEE80211_TX_RC_SHORT_GI;
return flags;
}
static void wl1271_tx_complete_packet(struct wl1271 *wl,
struct wl1271_tx_hw_res_descr *result)
{
struct ieee80211_tx_info *info;
struct ieee80211_vif *vif;
struct wl12xx_vif *wlvif;
struct sk_buff *skb;
int id = result->id;
int rate = -1;
u8 rate_flags = 0;
u8 retries = 0;
/* check for id legality */
if (unlikely(id >= ACX_TX_DESCRIPTORS || wl->tx_frames[id] == NULL)) {
wl1271_warning("TX result illegal id: %d", id);
return;
}
skb = wl->tx_frames[id];
info = IEEE80211_SKB_CB(skb);
if (wl12xx_is_dummy_packet(wl, skb)) {
wl1271_free_tx_id(wl, id);
return;
}
/* info->control is valid as long as we don't update info->status */
vif = info->control.vif;
wlvif = wl12xx_vif_to_data(vif);
/* update the TX status info */
if (result->status == TX_SUCCESS) {
if (!(info->flags & IEEE80211_TX_CTL_NO_ACK))
info->flags |= IEEE80211_TX_STAT_ACK;
rate = wl1271_rate_to_idx(result->rate_class_index,
wlvif->band);
rate_flags = wl1271_tx_get_rate_flags(result->rate_class_index);
retries = result->ack_failures;
} else if (result->status == TX_RETRY_EXCEEDED) {
wl->stats.excessive_retries++;
retries = result->ack_failures;
}
info->status.rates[0].idx = rate;
info->status.rates[0].count = retries;
info->status.rates[0].flags = rate_flags;
info->status.ack_signal = -1;
wl->stats.retry_count += result->ack_failures;
/*
* update sequence number only when relevant, i.e. only in
* sessions of TKIP, AES and GEM (not in open or WEP sessions)
*/
if (info->control.hw_key &&
(info->control.hw_key->cipher == WLAN_CIPHER_SUITE_TKIP ||
info->control.hw_key->cipher == WLAN_CIPHER_SUITE_CCMP ||
info->control.hw_key->cipher == WL1271_CIPHER_SUITE_GEM)) {
u8 fw_lsb = result->tx_security_sequence_number_lsb;
u8 cur_lsb = wlvif->tx_security_last_seq_lsb;
/*
* update security sequence number, taking care of potential
* wrap-around
*/
wlvif->tx_security_seq += (fw_lsb - cur_lsb) & 0xff;
wlvif->tx_security_last_seq_lsb = fw_lsb;
}
/* remove private header from packet */
skb_pull(skb, sizeof(struct wl1271_tx_hw_descr));
/* remove TKIP header space if present */
if (info->control.hw_key &&
info->control.hw_key->cipher == WLAN_CIPHER_SUITE_TKIP) {
int hdrlen = ieee80211_get_hdrlen_from_skb(skb);
memmove(skb->data + WL1271_EXTRA_SPACE_TKIP, skb->data,
hdrlen);
skb_pull(skb, WL1271_EXTRA_SPACE_TKIP);
}
wl1271_debug(DEBUG_TX, "tx status id %u skb 0x%p failures %u rate 0x%x"
" status 0x%x",
result->id, skb, result->ack_failures,
result->rate_class_index, result->status);
/* return the packet to the stack */
skb_queue_tail(&wl->deferred_tx_queue, skb);
queue_work(wl->freezable_wq, &wl->netstack_work);
wl1271_free_tx_id(wl, result->id);
}
/* Called upon reception of a TX complete interrupt */
void wl1271_tx_complete(struct wl1271 *wl)
{
struct wl1271_acx_mem_map *memmap =
(struct wl1271_acx_mem_map *)wl->target_mem_map;
u32 count, fw_counter;
u32 i;
/* read the tx results from the chipset */
wl1271_read(wl, le32_to_cpu(memmap->tx_result),
wl->tx_res_if, sizeof(*wl->tx_res_if), false);
fw_counter = le32_to_cpu(wl->tx_res_if->tx_result_fw_counter);
/* write host counter to chipset (to ack) */
wl1271_write32(wl, le32_to_cpu(memmap->tx_result) +
offsetof(struct wl1271_tx_hw_res_if,
tx_result_host_counter), fw_counter);
count = fw_counter - wl->tx_results_count;
wl1271_debug(DEBUG_TX, "tx_complete received, packets: %d", count);
/* verify that the result buffer is not getting overrun */
if (unlikely(count > TX_HW_RESULT_QUEUE_LEN))
wl1271_warning("TX result overflow from chipset: %d", count);
/* process the results */
for (i = 0; i < count; i++) {
struct wl1271_tx_hw_res_descr *result;
u8 offset = wl->tx_results_count & TX_HW_RESULT_QUEUE_LEN_MASK;
/* process the packet */
result = &(wl->tx_res_if->tx_results_queue[offset]);
wl1271_tx_complete_packet(wl, result);
wl->tx_results_count++;
}
}
void wl1271_tx_reset_link_queues(struct wl1271 *wl, u8 hlid)
{
struct sk_buff *skb;
int i;
unsigned long flags;
struct ieee80211_tx_info *info;
int total[NUM_TX_QUEUES];
for (i = 0; i < NUM_TX_QUEUES; i++) {
total[i] = 0;
while ((skb = skb_dequeue(&wl->links[hlid].tx_queue[i]))) {
wl1271_debug(DEBUG_TX, "link freeing skb 0x%p", skb);
if (!wl12xx_is_dummy_packet(wl, skb)) {
info = IEEE80211_SKB_CB(skb);
info->status.rates[0].idx = -1;
info->status.rates[0].count = 0;
ieee80211_tx_status_ni(wl->hw, skb);
}
total[i]++;
}
}
spin_lock_irqsave(&wl->wl_lock, flags);
for (i = 0; i < NUM_TX_QUEUES; i++)
wl->tx_queue_count[i] -= total[i];
spin_unlock_irqrestore(&wl->wl_lock, flags);
wl1271_handle_tx_low_watermark(wl);
}
/* caller must hold wl->mutex and TX must be stopped */
void wl12xx_tx_reset_wlvif(struct wl1271 *wl, struct wl12xx_vif *wlvif)
{
int i;
/* TX failure */
for_each_set_bit(i, wlvif->links_map, WL12XX_MAX_LINKS) {
if (wlvif->bss_type == BSS_TYPE_AP_BSS)
wl1271_free_sta(wl, wlvif, i);
else
wlvif->sta.ba_rx_bitmap = 0;
wl->links[i].allocated_pkts = 0;
wl->links[i].prev_freed_pkts = 0;
}
wlvif->last_tx_hlid = 0;
}
/* caller must hold wl->mutex and TX must be stopped */
void wl12xx_tx_reset(struct wl1271 *wl, bool reset_tx_queues)
{
int i;
struct sk_buff *skb;
struct ieee80211_tx_info *info;
/* only reset the queues if something bad happened */
if (WARN_ON_ONCE(wl1271_tx_total_queue_count(wl) != 0)) {
for (i = 0; i < WL12XX_MAX_LINKS; i++)
wl1271_tx_reset_link_queues(wl, i);
for (i = 0; i < NUM_TX_QUEUES; i++)
wl->tx_queue_count[i] = 0;
}
wl->stopped_queues_map = 0;
/*
* Make sure the driver is at a consistent state, in case this
* function is called from a context other than interface removal.
* This call will always wake the TX queues.
*/
if (reset_tx_queues)
wl1271_handle_tx_low_watermark(wl);
for (i = 0; i < ACX_TX_DESCRIPTORS; i++) {
if (wl->tx_frames[i] == NULL)
continue;
skb = wl->tx_frames[i];
wl1271_free_tx_id(wl, i);
wl1271_debug(DEBUG_TX, "freeing skb 0x%p", skb);
if (!wl12xx_is_dummy_packet(wl, skb)) {
/*
* Remove private headers before passing the skb to
* mac80211
*/
info = IEEE80211_SKB_CB(skb);
skb_pull(skb, sizeof(struct wl1271_tx_hw_descr));
if (info->control.hw_key &&
info->control.hw_key->cipher ==
WLAN_CIPHER_SUITE_TKIP) {
int hdrlen = ieee80211_get_hdrlen_from_skb(skb);
memmove(skb->data + WL1271_EXTRA_SPACE_TKIP,
skb->data, hdrlen);
skb_pull(skb, WL1271_EXTRA_SPACE_TKIP);
}
info->status.rates[0].idx = -1;
info->status.rates[0].count = 0;
ieee80211_tx_status_ni(wl->hw, skb);
}
}
}
#define WL1271_TX_FLUSH_TIMEOUT 500000
/* caller must *NOT* hold wl->mutex */
void wl1271_tx_flush(struct wl1271 *wl)
{
unsigned long timeout;
int i;
timeout = jiffies + usecs_to_jiffies(WL1271_TX_FLUSH_TIMEOUT);
while (!time_after(jiffies, timeout)) {
mutex_lock(&wl->mutex);
wl1271_debug(DEBUG_TX, "flushing tx buffer: %d %d",
wl->tx_frames_cnt,
wl1271_tx_total_queue_count(wl));
if ((wl->tx_frames_cnt == 0) &&
(wl1271_tx_total_queue_count(wl) == 0)) {
mutex_unlock(&wl->mutex);
return;
}
mutex_unlock(&wl->mutex);
msleep(1);
}
wl1271_warning("Unable to flush all TX buffers, timed out.");
/* forcibly flush all Tx buffers on our queues */
mutex_lock(&wl->mutex);
for (i = 0; i < WL12XX_MAX_LINKS; i++)
wl1271_tx_reset_link_queues(wl, i);
mutex_unlock(&wl->mutex);
}
u32 wl1271_tx_min_rate_get(struct wl1271 *wl, u32 rate_set)
{
if (WARN_ON(!rate_set))
return 0;
return BIT(__ffs(rate_set));
}
| gpl-2.0 |
jejecule/kernel_despair_find7 | fs/xfs/xfs_da_btree.c | 4809 | 66859 | /*
* Copyright (c) 2000-2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_da_btree.h"
#include "xfs_bmap_btree.h"
#include "xfs_dir2.h"
#include "xfs_dir2_format.h"
#include "xfs_dir2_priv.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_inode_item.h"
#include "xfs_alloc.h"
#include "xfs_bmap.h"
#include "xfs_attr.h"
#include "xfs_attr_leaf.h"
#include "xfs_error.h"
#include "xfs_trace.h"
/*
* xfs_da_btree.c
*
* Routines to implement directories as Btrees of hashed names.
*/
/*========================================================================
* Function prototypes for the kernel.
*========================================================================*/
/*
* Routines used for growing the Btree.
*/
STATIC int xfs_da_root_split(xfs_da_state_t *state,
xfs_da_state_blk_t *existing_root,
xfs_da_state_blk_t *new_child);
STATIC int xfs_da_node_split(xfs_da_state_t *state,
xfs_da_state_blk_t *existing_blk,
xfs_da_state_blk_t *split_blk,
xfs_da_state_blk_t *blk_to_add,
int treelevel,
int *result);
STATIC void xfs_da_node_rebalance(xfs_da_state_t *state,
xfs_da_state_blk_t *node_blk_1,
xfs_da_state_blk_t *node_blk_2);
STATIC void xfs_da_node_add(xfs_da_state_t *state,
xfs_da_state_blk_t *old_node_blk,
xfs_da_state_blk_t *new_node_blk);
/*
* Routines used for shrinking the Btree.
*/
STATIC int xfs_da_root_join(xfs_da_state_t *state,
xfs_da_state_blk_t *root_blk);
STATIC int xfs_da_node_toosmall(xfs_da_state_t *state, int *retval);
STATIC void xfs_da_node_remove(xfs_da_state_t *state,
xfs_da_state_blk_t *drop_blk);
STATIC void xfs_da_node_unbalance(xfs_da_state_t *state,
xfs_da_state_blk_t *src_node_blk,
xfs_da_state_blk_t *dst_node_blk);
/*
* Utility routines.
*/
STATIC uint xfs_da_node_lasthash(xfs_dabuf_t *bp, int *count);
STATIC int xfs_da_node_order(xfs_dabuf_t *node1_bp, xfs_dabuf_t *node2_bp);
STATIC xfs_dabuf_t *xfs_da_buf_make(int nbuf, xfs_buf_t **bps);
STATIC int xfs_da_blk_unlink(xfs_da_state_t *state,
xfs_da_state_blk_t *drop_blk,
xfs_da_state_blk_t *save_blk);
STATIC void xfs_da_state_kill_altpath(xfs_da_state_t *state);
/*========================================================================
* Routines used for growing the Btree.
*========================================================================*/
/*
* Create the initial contents of an intermediate node.
*/
int
xfs_da_node_create(xfs_da_args_t *args, xfs_dablk_t blkno, int level,
xfs_dabuf_t **bpp, int whichfork)
{
xfs_da_intnode_t *node;
xfs_dabuf_t *bp;
int error;
xfs_trans_t *tp;
trace_xfs_da_node_create(args);
tp = args->trans;
error = xfs_da_get_buf(tp, args->dp, blkno, -1, &bp, whichfork);
if (error)
return(error);
ASSERT(bp != NULL);
node = bp->data;
node->hdr.info.forw = 0;
node->hdr.info.back = 0;
node->hdr.info.magic = cpu_to_be16(XFS_DA_NODE_MAGIC);
node->hdr.info.pad = 0;
node->hdr.count = 0;
node->hdr.level = cpu_to_be16(level);
xfs_da_log_buf(tp, bp,
XFS_DA_LOGRANGE(node, &node->hdr, sizeof(node->hdr)));
*bpp = bp;
return(0);
}
/*
* Split a leaf node, rebalance, then possibly split
* intermediate nodes, rebalance, etc.
*/
int /* error */
xfs_da_split(xfs_da_state_t *state)
{
xfs_da_state_blk_t *oldblk, *newblk, *addblk;
xfs_da_intnode_t *node;
xfs_dabuf_t *bp;
int max, action, error, i;
trace_xfs_da_split(state->args);
/*
* Walk back up the tree splitting/inserting/adjusting as necessary.
* If we need to insert and there isn't room, split the node, then
* decide which fragment to insert the new block from below into.
* Note that we may split the root this way, but we need more fixup.
*/
max = state->path.active - 1;
ASSERT((max >= 0) && (max < XFS_DA_NODE_MAXDEPTH));
ASSERT(state->path.blk[max].magic == XFS_ATTR_LEAF_MAGIC ||
state->path.blk[max].magic == XFS_DIR2_LEAFN_MAGIC);
addblk = &state->path.blk[max]; /* initial dummy value */
for (i = max; (i >= 0) && addblk; state->path.active--, i--) {
oldblk = &state->path.blk[i];
newblk = &state->altpath.blk[i];
/*
* If a leaf node then
* Allocate a new leaf node, then rebalance across them.
* else if an intermediate node then
* We split on the last layer, must we split the node?
*/
switch (oldblk->magic) {
case XFS_ATTR_LEAF_MAGIC:
error = xfs_attr_leaf_split(state, oldblk, newblk);
if ((error != 0) && (error != ENOSPC)) {
return(error); /* GROT: attr is inconsistent */
}
if (!error) {
addblk = newblk;
break;
}
/*
* Entry wouldn't fit, split the leaf again.
*/
state->extravalid = 1;
if (state->inleaf) {
state->extraafter = 0; /* before newblk */
trace_xfs_attr_leaf_split_before(state->args);
error = xfs_attr_leaf_split(state, oldblk,
&state->extrablk);
} else {
state->extraafter = 1; /* after newblk */
trace_xfs_attr_leaf_split_after(state->args);
error = xfs_attr_leaf_split(state, newblk,
&state->extrablk);
}
if (error)
return(error); /* GROT: attr inconsistent */
addblk = newblk;
break;
case XFS_DIR2_LEAFN_MAGIC:
error = xfs_dir2_leafn_split(state, oldblk, newblk);
if (error)
return error;
addblk = newblk;
break;
case XFS_DA_NODE_MAGIC:
error = xfs_da_node_split(state, oldblk, newblk, addblk,
max - i, &action);
xfs_da_buf_done(addblk->bp);
addblk->bp = NULL;
if (error)
return(error); /* GROT: dir is inconsistent */
/*
* Record the newly split block for the next time thru?
*/
if (action)
addblk = newblk;
else
addblk = NULL;
break;
}
/*
* Update the btree to show the new hashval for this child.
*/
xfs_da_fixhashpath(state, &state->path);
/*
* If we won't need this block again, it's getting dropped
* from the active path by the loop control, so we need
* to mark it done now.
*/
if (i > 0 || !addblk)
xfs_da_buf_done(oldblk->bp);
}
if (!addblk)
return(0);
/*
* Split the root node.
*/
ASSERT(state->path.active == 0);
oldblk = &state->path.blk[0];
error = xfs_da_root_split(state, oldblk, addblk);
if (error) {
xfs_da_buf_done(oldblk->bp);
xfs_da_buf_done(addblk->bp);
addblk->bp = NULL;
return(error); /* GROT: dir is inconsistent */
}
/*
* Update pointers to the node which used to be block 0 and
* just got bumped because of the addition of a new root node.
* There might be three blocks involved if a double split occurred,
* and the original block 0 could be at any position in the list.
*/
node = oldblk->bp->data;
if (node->hdr.info.forw) {
if (be32_to_cpu(node->hdr.info.forw) == addblk->blkno) {
bp = addblk->bp;
} else {
ASSERT(state->extravalid);
bp = state->extrablk.bp;
}
node = bp->data;
node->hdr.info.back = cpu_to_be32(oldblk->blkno);
xfs_da_log_buf(state->args->trans, bp,
XFS_DA_LOGRANGE(node, &node->hdr.info,
sizeof(node->hdr.info)));
}
node = oldblk->bp->data;
if (node->hdr.info.back) {
if (be32_to_cpu(node->hdr.info.back) == addblk->blkno) {
bp = addblk->bp;
} else {
ASSERT(state->extravalid);
bp = state->extrablk.bp;
}
node = bp->data;
node->hdr.info.forw = cpu_to_be32(oldblk->blkno);
xfs_da_log_buf(state->args->trans, bp,
XFS_DA_LOGRANGE(node, &node->hdr.info,
sizeof(node->hdr.info)));
}
xfs_da_buf_done(oldblk->bp);
xfs_da_buf_done(addblk->bp);
addblk->bp = NULL;
return(0);
}
/*
* Split the root. We have to create a new root and point to the two
* parts (the split old root) that we just created. Copy block zero to
* the EOF, extending the inode in process.
*/
STATIC int /* error */
xfs_da_root_split(xfs_da_state_t *state, xfs_da_state_blk_t *blk1,
xfs_da_state_blk_t *blk2)
{
xfs_da_intnode_t *node, *oldroot;
xfs_da_args_t *args;
xfs_dablk_t blkno;
xfs_dabuf_t *bp;
int error, size;
xfs_inode_t *dp;
xfs_trans_t *tp;
xfs_mount_t *mp;
xfs_dir2_leaf_t *leaf;
trace_xfs_da_root_split(state->args);
/*
* Copy the existing (incorrect) block from the root node position
* to a free space somewhere.
*/
args = state->args;
ASSERT(args != NULL);
error = xfs_da_grow_inode(args, &blkno);
if (error)
return(error);
dp = args->dp;
tp = args->trans;
mp = state->mp;
error = xfs_da_get_buf(tp, dp, blkno, -1, &bp, args->whichfork);
if (error)
return(error);
ASSERT(bp != NULL);
node = bp->data;
oldroot = blk1->bp->data;
if (oldroot->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC)) {
size = (int)((char *)&oldroot->btree[be16_to_cpu(oldroot->hdr.count)] -
(char *)oldroot);
} else {
ASSERT(oldroot->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAFN_MAGIC));
leaf = (xfs_dir2_leaf_t *)oldroot;
size = (int)((char *)&leaf->ents[be16_to_cpu(leaf->hdr.count)] -
(char *)leaf);
}
memcpy(node, oldroot, size);
xfs_da_log_buf(tp, bp, 0, size - 1);
xfs_da_buf_done(blk1->bp);
blk1->bp = bp;
blk1->blkno = blkno;
/*
* Set up the new root node.
*/
error = xfs_da_node_create(args,
(args->whichfork == XFS_DATA_FORK) ? mp->m_dirleafblk : 0,
be16_to_cpu(node->hdr.level) + 1, &bp, args->whichfork);
if (error)
return(error);
node = bp->data;
node->btree[0].hashval = cpu_to_be32(blk1->hashval);
node->btree[0].before = cpu_to_be32(blk1->blkno);
node->btree[1].hashval = cpu_to_be32(blk2->hashval);
node->btree[1].before = cpu_to_be32(blk2->blkno);
node->hdr.count = cpu_to_be16(2);
#ifdef DEBUG
if (oldroot->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAFN_MAGIC)) {
ASSERT(blk1->blkno >= mp->m_dirleafblk &&
blk1->blkno < mp->m_dirfreeblk);
ASSERT(blk2->blkno >= mp->m_dirleafblk &&
blk2->blkno < mp->m_dirfreeblk);
}
#endif
/* Header is already logged by xfs_da_node_create */
xfs_da_log_buf(tp, bp,
XFS_DA_LOGRANGE(node, node->btree,
sizeof(xfs_da_node_entry_t) * 2));
xfs_da_buf_done(bp);
return(0);
}
/*
* Split the node, rebalance, then add the new entry.
*/
STATIC int /* error */
xfs_da_node_split(xfs_da_state_t *state, xfs_da_state_blk_t *oldblk,
xfs_da_state_blk_t *newblk,
xfs_da_state_blk_t *addblk,
int treelevel, int *result)
{
xfs_da_intnode_t *node;
xfs_dablk_t blkno;
int newcount, error;
int useextra;
trace_xfs_da_node_split(state->args);
node = oldblk->bp->data;
ASSERT(node->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC));
/*
* With V2 dirs the extra block is data or freespace.
*/
useextra = state->extravalid && state->args->whichfork == XFS_ATTR_FORK;
newcount = 1 + useextra;
/*
* Do we have to split the node?
*/
if ((be16_to_cpu(node->hdr.count) + newcount) > state->node_ents) {
/*
* Allocate a new node, add to the doubly linked chain of
* nodes, then move some of our excess entries into it.
*/
error = xfs_da_grow_inode(state->args, &blkno);
if (error)
return(error); /* GROT: dir is inconsistent */
error = xfs_da_node_create(state->args, blkno, treelevel,
&newblk->bp, state->args->whichfork);
if (error)
return(error); /* GROT: dir is inconsistent */
newblk->blkno = blkno;
newblk->magic = XFS_DA_NODE_MAGIC;
xfs_da_node_rebalance(state, oldblk, newblk);
error = xfs_da_blk_link(state, oldblk, newblk);
if (error)
return(error);
*result = 1;
} else {
*result = 0;
}
/*
* Insert the new entry(s) into the correct block
* (updating last hashval in the process).
*
* xfs_da_node_add() inserts BEFORE the given index,
* and as a result of using node_lookup_int() we always
* point to a valid entry (not after one), but a split
* operation always results in a new block whose hashvals
* FOLLOW the current block.
*
* If we had double-split op below us, then add the extra block too.
*/
node = oldblk->bp->data;
if (oldblk->index <= be16_to_cpu(node->hdr.count)) {
oldblk->index++;
xfs_da_node_add(state, oldblk, addblk);
if (useextra) {
if (state->extraafter)
oldblk->index++;
xfs_da_node_add(state, oldblk, &state->extrablk);
state->extravalid = 0;
}
} else {
newblk->index++;
xfs_da_node_add(state, newblk, addblk);
if (useextra) {
if (state->extraafter)
newblk->index++;
xfs_da_node_add(state, newblk, &state->extrablk);
state->extravalid = 0;
}
}
return(0);
}
/*
* Balance the btree elements between two intermediate nodes,
* usually one full and one empty.
*
* NOTE: if blk2 is empty, then it will get the upper half of blk1.
*/
STATIC void
xfs_da_node_rebalance(xfs_da_state_t *state, xfs_da_state_blk_t *blk1,
xfs_da_state_blk_t *blk2)
{
xfs_da_intnode_t *node1, *node2, *tmpnode;
xfs_da_node_entry_t *btree_s, *btree_d;
int count, tmp;
xfs_trans_t *tp;
trace_xfs_da_node_rebalance(state->args);
node1 = blk1->bp->data;
node2 = blk2->bp->data;
/*
* Figure out how many entries need to move, and in which direction.
* Swap the nodes around if that makes it simpler.
*/
if ((be16_to_cpu(node1->hdr.count) > 0) && (be16_to_cpu(node2->hdr.count) > 0) &&
((be32_to_cpu(node2->btree[0].hashval) < be32_to_cpu(node1->btree[0].hashval)) ||
(be32_to_cpu(node2->btree[be16_to_cpu(node2->hdr.count)-1].hashval) <
be32_to_cpu(node1->btree[be16_to_cpu(node1->hdr.count)-1].hashval)))) {
tmpnode = node1;
node1 = node2;
node2 = tmpnode;
}
ASSERT(node1->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC));
ASSERT(node2->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC));
count = (be16_to_cpu(node1->hdr.count) - be16_to_cpu(node2->hdr.count)) / 2;
if (count == 0)
return;
tp = state->args->trans;
/*
* Two cases: high-to-low and low-to-high.
*/
if (count > 0) {
/*
* Move elements in node2 up to make a hole.
*/
if ((tmp = be16_to_cpu(node2->hdr.count)) > 0) {
tmp *= (uint)sizeof(xfs_da_node_entry_t);
btree_s = &node2->btree[0];
btree_d = &node2->btree[count];
memmove(btree_d, btree_s, tmp);
}
/*
* Move the req'd B-tree elements from high in node1 to
* low in node2.
*/
be16_add_cpu(&node2->hdr.count, count);
tmp = count * (uint)sizeof(xfs_da_node_entry_t);
btree_s = &node1->btree[be16_to_cpu(node1->hdr.count) - count];
btree_d = &node2->btree[0];
memcpy(btree_d, btree_s, tmp);
be16_add_cpu(&node1->hdr.count, -count);
} else {
/*
* Move the req'd B-tree elements from low in node2 to
* high in node1.
*/
count = -count;
tmp = count * (uint)sizeof(xfs_da_node_entry_t);
btree_s = &node2->btree[0];
btree_d = &node1->btree[be16_to_cpu(node1->hdr.count)];
memcpy(btree_d, btree_s, tmp);
be16_add_cpu(&node1->hdr.count, count);
xfs_da_log_buf(tp, blk1->bp,
XFS_DA_LOGRANGE(node1, btree_d, tmp));
/*
* Move elements in node2 down to fill the hole.
*/
tmp = be16_to_cpu(node2->hdr.count) - count;
tmp *= (uint)sizeof(xfs_da_node_entry_t);
btree_s = &node2->btree[count];
btree_d = &node2->btree[0];
memmove(btree_d, btree_s, tmp);
be16_add_cpu(&node2->hdr.count, -count);
}
/*
* Log header of node 1 and all current bits of node 2.
*/
xfs_da_log_buf(tp, blk1->bp,
XFS_DA_LOGRANGE(node1, &node1->hdr, sizeof(node1->hdr)));
xfs_da_log_buf(tp, blk2->bp,
XFS_DA_LOGRANGE(node2, &node2->hdr,
sizeof(node2->hdr) +
sizeof(node2->btree[0]) * be16_to_cpu(node2->hdr.count)));
/*
* Record the last hashval from each block for upward propagation.
* (note: don't use the swapped node pointers)
*/
node1 = blk1->bp->data;
node2 = blk2->bp->data;
blk1->hashval = be32_to_cpu(node1->btree[be16_to_cpu(node1->hdr.count)-1].hashval);
blk2->hashval = be32_to_cpu(node2->btree[be16_to_cpu(node2->hdr.count)-1].hashval);
/*
* Adjust the expected index for insertion.
*/
if (blk1->index >= be16_to_cpu(node1->hdr.count)) {
blk2->index = blk1->index - be16_to_cpu(node1->hdr.count);
blk1->index = be16_to_cpu(node1->hdr.count) + 1; /* make it invalid */
}
}
/*
* Add a new entry to an intermediate node.
*/
STATIC void
xfs_da_node_add(xfs_da_state_t *state, xfs_da_state_blk_t *oldblk,
xfs_da_state_blk_t *newblk)
{
xfs_da_intnode_t *node;
xfs_da_node_entry_t *btree;
int tmp;
trace_xfs_da_node_add(state->args);
node = oldblk->bp->data;
ASSERT(node->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC));
ASSERT((oldblk->index >= 0) && (oldblk->index <= be16_to_cpu(node->hdr.count)));
ASSERT(newblk->blkno != 0);
if (state->args->whichfork == XFS_DATA_FORK)
ASSERT(newblk->blkno >= state->mp->m_dirleafblk &&
newblk->blkno < state->mp->m_dirfreeblk);
/*
* We may need to make some room before we insert the new node.
*/
tmp = 0;
btree = &node->btree[ oldblk->index ];
if (oldblk->index < be16_to_cpu(node->hdr.count)) {
tmp = (be16_to_cpu(node->hdr.count) - oldblk->index) * (uint)sizeof(*btree);
memmove(btree + 1, btree, tmp);
}
btree->hashval = cpu_to_be32(newblk->hashval);
btree->before = cpu_to_be32(newblk->blkno);
xfs_da_log_buf(state->args->trans, oldblk->bp,
XFS_DA_LOGRANGE(node, btree, tmp + sizeof(*btree)));
be16_add_cpu(&node->hdr.count, 1);
xfs_da_log_buf(state->args->trans, oldblk->bp,
XFS_DA_LOGRANGE(node, &node->hdr, sizeof(node->hdr)));
/*
* Copy the last hash value from the oldblk to propagate upwards.
*/
oldblk->hashval = be32_to_cpu(node->btree[be16_to_cpu(node->hdr.count)-1 ].hashval);
}
/*========================================================================
* Routines used for shrinking the Btree.
*========================================================================*/
/*
* Deallocate an empty leaf node, remove it from its parent,
* possibly deallocating that block, etc...
*/
int
xfs_da_join(xfs_da_state_t *state)
{
xfs_da_state_blk_t *drop_blk, *save_blk;
int action, error;
trace_xfs_da_join(state->args);
action = 0;
drop_blk = &state->path.blk[ state->path.active-1 ];
save_blk = &state->altpath.blk[ state->path.active-1 ];
ASSERT(state->path.blk[0].magic == XFS_DA_NODE_MAGIC);
ASSERT(drop_blk->magic == XFS_ATTR_LEAF_MAGIC ||
drop_blk->magic == XFS_DIR2_LEAFN_MAGIC);
/*
* Walk back up the tree joining/deallocating as necessary.
* When we stop dropping blocks, break out.
*/
for ( ; state->path.active >= 2; drop_blk--, save_blk--,
state->path.active--) {
/*
* See if we can combine the block with a neighbor.
* (action == 0) => no options, just leave
* (action == 1) => coalesce, then unlink
* (action == 2) => block empty, unlink it
*/
switch (drop_blk->magic) {
case XFS_ATTR_LEAF_MAGIC:
error = xfs_attr_leaf_toosmall(state, &action);
if (error)
return(error);
if (action == 0)
return(0);
xfs_attr_leaf_unbalance(state, drop_blk, save_blk);
break;
case XFS_DIR2_LEAFN_MAGIC:
error = xfs_dir2_leafn_toosmall(state, &action);
if (error)
return error;
if (action == 0)
return 0;
xfs_dir2_leafn_unbalance(state, drop_blk, save_blk);
break;
case XFS_DA_NODE_MAGIC:
/*
* Remove the offending node, fixup hashvals,
* check for a toosmall neighbor.
*/
xfs_da_node_remove(state, drop_blk);
xfs_da_fixhashpath(state, &state->path);
error = xfs_da_node_toosmall(state, &action);
if (error)
return(error);
if (action == 0)
return 0;
xfs_da_node_unbalance(state, drop_blk, save_blk);
break;
}
xfs_da_fixhashpath(state, &state->altpath);
error = xfs_da_blk_unlink(state, drop_blk, save_blk);
xfs_da_state_kill_altpath(state);
if (error)
return(error);
error = xfs_da_shrink_inode(state->args, drop_blk->blkno,
drop_blk->bp);
drop_blk->bp = NULL;
if (error)
return(error);
}
/*
* We joined all the way to the top. If it turns out that
* we only have one entry in the root, make the child block
* the new root.
*/
xfs_da_node_remove(state, drop_blk);
xfs_da_fixhashpath(state, &state->path);
error = xfs_da_root_join(state, &state->path.blk[0]);
return(error);
}
#ifdef DEBUG
static void
xfs_da_blkinfo_onlychild_validate(struct xfs_da_blkinfo *blkinfo, __u16 level)
{
__be16 magic = blkinfo->magic;
if (level == 1) {
ASSERT(magic == cpu_to_be16(XFS_DIR2_LEAFN_MAGIC) ||
magic == cpu_to_be16(XFS_ATTR_LEAF_MAGIC));
} else
ASSERT(magic == cpu_to_be16(XFS_DA_NODE_MAGIC));
ASSERT(!blkinfo->forw);
ASSERT(!blkinfo->back);
}
#else /* !DEBUG */
#define xfs_da_blkinfo_onlychild_validate(blkinfo, level)
#endif /* !DEBUG */
/*
* We have only one entry in the root. Copy the only remaining child of
* the old root to block 0 as the new root node.
*/
STATIC int
xfs_da_root_join(xfs_da_state_t *state, xfs_da_state_blk_t *root_blk)
{
xfs_da_intnode_t *oldroot;
xfs_da_args_t *args;
xfs_dablk_t child;
xfs_dabuf_t *bp;
int error;
trace_xfs_da_root_join(state->args);
args = state->args;
ASSERT(args != NULL);
ASSERT(root_blk->magic == XFS_DA_NODE_MAGIC);
oldroot = root_blk->bp->data;
ASSERT(oldroot->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC));
ASSERT(!oldroot->hdr.info.forw);
ASSERT(!oldroot->hdr.info.back);
/*
* If the root has more than one child, then don't do anything.
*/
if (be16_to_cpu(oldroot->hdr.count) > 1)
return(0);
/*
* Read in the (only) child block, then copy those bytes into
* the root block's buffer and free the original child block.
*/
child = be32_to_cpu(oldroot->btree[0].before);
ASSERT(child != 0);
error = xfs_da_read_buf(args->trans, args->dp, child, -1, &bp,
args->whichfork);
if (error)
return(error);
ASSERT(bp != NULL);
xfs_da_blkinfo_onlychild_validate(bp->data,
be16_to_cpu(oldroot->hdr.level));
memcpy(root_blk->bp->data, bp->data, state->blocksize);
xfs_da_log_buf(args->trans, root_blk->bp, 0, state->blocksize - 1);
error = xfs_da_shrink_inode(args, child, bp);
return(error);
}
/*
* Check a node block and its neighbors to see if the block should be
* collapsed into one or the other neighbor. Always keep the block
* with the smaller block number.
* If the current block is over 50% full, don't try to join it, return 0.
* If the block is empty, fill in the state structure and return 2.
* If it can be collapsed, fill in the state structure and return 1.
* If nothing can be done, return 0.
*/
STATIC int
xfs_da_node_toosmall(xfs_da_state_t *state, int *action)
{
xfs_da_intnode_t *node;
xfs_da_state_blk_t *blk;
xfs_da_blkinfo_t *info;
int count, forward, error, retval, i;
xfs_dablk_t blkno;
xfs_dabuf_t *bp;
/*
* Check for the degenerate case of the block being over 50% full.
* If so, it's not worth even looking to see if we might be able
* to coalesce with a sibling.
*/
blk = &state->path.blk[ state->path.active-1 ];
info = blk->bp->data;
ASSERT(info->magic == cpu_to_be16(XFS_DA_NODE_MAGIC));
node = (xfs_da_intnode_t *)info;
count = be16_to_cpu(node->hdr.count);
if (count > (state->node_ents >> 1)) {
*action = 0; /* blk over 50%, don't try to join */
return(0); /* blk over 50%, don't try to join */
}
/*
* Check for the degenerate case of the block being empty.
* If the block is empty, we'll simply delete it, no need to
* coalesce it with a sibling block. We choose (arbitrarily)
* to merge with the forward block unless it is NULL.
*/
if (count == 0) {
/*
* Make altpath point to the block we want to keep and
* path point to the block we want to drop (this one).
*/
forward = (info->forw != 0);
memcpy(&state->altpath, &state->path, sizeof(state->path));
error = xfs_da_path_shift(state, &state->altpath, forward,
0, &retval);
if (error)
return(error);
if (retval) {
*action = 0;
} else {
*action = 2;
}
return(0);
}
/*
* Examine each sibling block to see if we can coalesce with
* at least 25% free space to spare. We need to figure out
* whether to merge with the forward or the backward block.
* We prefer coalescing with the lower numbered sibling so as
* to shrink a directory over time.
*/
/* start with smaller blk num */
forward = (be32_to_cpu(info->forw) < be32_to_cpu(info->back));
for (i = 0; i < 2; forward = !forward, i++) {
if (forward)
blkno = be32_to_cpu(info->forw);
else
blkno = be32_to_cpu(info->back);
if (blkno == 0)
continue;
error = xfs_da_read_buf(state->args->trans, state->args->dp,
blkno, -1, &bp, state->args->whichfork);
if (error)
return(error);
ASSERT(bp != NULL);
node = (xfs_da_intnode_t *)info;
count = state->node_ents;
count -= state->node_ents >> 2;
count -= be16_to_cpu(node->hdr.count);
node = bp->data;
ASSERT(node->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC));
count -= be16_to_cpu(node->hdr.count);
xfs_da_brelse(state->args->trans, bp);
if (count >= 0)
break; /* fits with at least 25% to spare */
}
if (i >= 2) {
*action = 0;
return(0);
}
/*
* Make altpath point to the block we want to keep (the lower
* numbered block) and path point to the block we want to drop.
*/
memcpy(&state->altpath, &state->path, sizeof(state->path));
if (blkno < blk->blkno) {
error = xfs_da_path_shift(state, &state->altpath, forward,
0, &retval);
if (error) {
return(error);
}
if (retval) {
*action = 0;
return(0);
}
} else {
error = xfs_da_path_shift(state, &state->path, forward,
0, &retval);
if (error) {
return(error);
}
if (retval) {
*action = 0;
return(0);
}
}
*action = 1;
return(0);
}
/*
* Walk back up the tree adjusting hash values as necessary,
* when we stop making changes, return.
*/
void
xfs_da_fixhashpath(xfs_da_state_t *state, xfs_da_state_path_t *path)
{
xfs_da_state_blk_t *blk;
xfs_da_intnode_t *node;
xfs_da_node_entry_t *btree;
xfs_dahash_t lasthash=0;
int level, count;
level = path->active-1;
blk = &path->blk[ level ];
switch (blk->magic) {
case XFS_ATTR_LEAF_MAGIC:
lasthash = xfs_attr_leaf_lasthash(blk->bp, &count);
if (count == 0)
return;
break;
case XFS_DIR2_LEAFN_MAGIC:
lasthash = xfs_dir2_leafn_lasthash(blk->bp, &count);
if (count == 0)
return;
break;
case XFS_DA_NODE_MAGIC:
lasthash = xfs_da_node_lasthash(blk->bp, &count);
if (count == 0)
return;
break;
}
for (blk--, level--; level >= 0; blk--, level--) {
node = blk->bp->data;
ASSERT(node->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC));
btree = &node->btree[ blk->index ];
if (be32_to_cpu(btree->hashval) == lasthash)
break;
blk->hashval = lasthash;
btree->hashval = cpu_to_be32(lasthash);
xfs_da_log_buf(state->args->trans, blk->bp,
XFS_DA_LOGRANGE(node, btree, sizeof(*btree)));
lasthash = be32_to_cpu(node->btree[be16_to_cpu(node->hdr.count)-1].hashval);
}
}
/*
* Remove an entry from an intermediate node.
*/
STATIC void
xfs_da_node_remove(xfs_da_state_t *state, xfs_da_state_blk_t *drop_blk)
{
xfs_da_intnode_t *node;
xfs_da_node_entry_t *btree;
int tmp;
trace_xfs_da_node_remove(state->args);
node = drop_blk->bp->data;
ASSERT(drop_blk->index < be16_to_cpu(node->hdr.count));
ASSERT(drop_blk->index >= 0);
/*
* Copy over the offending entry, or just zero it out.
*/
btree = &node->btree[drop_blk->index];
if (drop_blk->index < (be16_to_cpu(node->hdr.count)-1)) {
tmp = be16_to_cpu(node->hdr.count) - drop_blk->index - 1;
tmp *= (uint)sizeof(xfs_da_node_entry_t);
memmove(btree, btree + 1, tmp);
xfs_da_log_buf(state->args->trans, drop_blk->bp,
XFS_DA_LOGRANGE(node, btree, tmp));
btree = &node->btree[be16_to_cpu(node->hdr.count)-1];
}
memset((char *)btree, 0, sizeof(xfs_da_node_entry_t));
xfs_da_log_buf(state->args->trans, drop_blk->bp,
XFS_DA_LOGRANGE(node, btree, sizeof(*btree)));
be16_add_cpu(&node->hdr.count, -1);
xfs_da_log_buf(state->args->trans, drop_blk->bp,
XFS_DA_LOGRANGE(node, &node->hdr, sizeof(node->hdr)));
/*
* Copy the last hash value from the block to propagate upwards.
*/
btree--;
drop_blk->hashval = be32_to_cpu(btree->hashval);
}
/*
* Unbalance the btree elements between two intermediate nodes,
* move all Btree elements from one node into another.
*/
STATIC void
xfs_da_node_unbalance(xfs_da_state_t *state, xfs_da_state_blk_t *drop_blk,
xfs_da_state_blk_t *save_blk)
{
xfs_da_intnode_t *drop_node, *save_node;
xfs_da_node_entry_t *btree;
int tmp;
xfs_trans_t *tp;
trace_xfs_da_node_unbalance(state->args);
drop_node = drop_blk->bp->data;
save_node = save_blk->bp->data;
ASSERT(drop_node->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC));
ASSERT(save_node->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC));
tp = state->args->trans;
/*
* If the dying block has lower hashvals, then move all the
* elements in the remaining block up to make a hole.
*/
if ((be32_to_cpu(drop_node->btree[0].hashval) < be32_to_cpu(save_node->btree[ 0 ].hashval)) ||
(be32_to_cpu(drop_node->btree[be16_to_cpu(drop_node->hdr.count)-1].hashval) <
be32_to_cpu(save_node->btree[be16_to_cpu(save_node->hdr.count)-1].hashval)))
{
btree = &save_node->btree[be16_to_cpu(drop_node->hdr.count)];
tmp = be16_to_cpu(save_node->hdr.count) * (uint)sizeof(xfs_da_node_entry_t);
memmove(btree, &save_node->btree[0], tmp);
btree = &save_node->btree[0];
xfs_da_log_buf(tp, save_blk->bp,
XFS_DA_LOGRANGE(save_node, btree,
(be16_to_cpu(save_node->hdr.count) + be16_to_cpu(drop_node->hdr.count)) *
sizeof(xfs_da_node_entry_t)));
} else {
btree = &save_node->btree[be16_to_cpu(save_node->hdr.count)];
xfs_da_log_buf(tp, save_blk->bp,
XFS_DA_LOGRANGE(save_node, btree,
be16_to_cpu(drop_node->hdr.count) *
sizeof(xfs_da_node_entry_t)));
}
/*
* Move all the B-tree elements from drop_blk to save_blk.
*/
tmp = be16_to_cpu(drop_node->hdr.count) * (uint)sizeof(xfs_da_node_entry_t);
memcpy(btree, &drop_node->btree[0], tmp);
be16_add_cpu(&save_node->hdr.count, be16_to_cpu(drop_node->hdr.count));
xfs_da_log_buf(tp, save_blk->bp,
XFS_DA_LOGRANGE(save_node, &save_node->hdr,
sizeof(save_node->hdr)));
/*
* Save the last hashval in the remaining block for upward propagation.
*/
save_blk->hashval = be32_to_cpu(save_node->btree[be16_to_cpu(save_node->hdr.count)-1].hashval);
}
/*========================================================================
* Routines used for finding things in the Btree.
*========================================================================*/
/*
* Walk down the Btree looking for a particular filename, filling
* in the state structure as we go.
*
* We will set the state structure to point to each of the elements
* in each of the nodes where either the hashval is or should be.
*
* We support duplicate hashval's so for each entry in the current
* node that could contain the desired hashval, descend. This is a
* pruned depth-first tree search.
*/
int /* error */
xfs_da_node_lookup_int(xfs_da_state_t *state, int *result)
{
xfs_da_state_blk_t *blk;
xfs_da_blkinfo_t *curr;
xfs_da_intnode_t *node;
xfs_da_node_entry_t *btree;
xfs_dablk_t blkno;
int probe, span, max, error, retval;
xfs_dahash_t hashval, btreehashval;
xfs_da_args_t *args;
args = state->args;
/*
* Descend thru the B-tree searching each level for the right
* node to use, until the right hashval is found.
*/
blkno = (args->whichfork == XFS_DATA_FORK)? state->mp->m_dirleafblk : 0;
for (blk = &state->path.blk[0], state->path.active = 1;
state->path.active <= XFS_DA_NODE_MAXDEPTH;
blk++, state->path.active++) {
/*
* Read the next node down in the tree.
*/
blk->blkno = blkno;
error = xfs_da_read_buf(args->trans, args->dp, blkno,
-1, &blk->bp, args->whichfork);
if (error) {
blk->blkno = 0;
state->path.active--;
return(error);
}
curr = blk->bp->data;
blk->magic = be16_to_cpu(curr->magic);
ASSERT(blk->magic == XFS_DA_NODE_MAGIC ||
blk->magic == XFS_DIR2_LEAFN_MAGIC ||
blk->magic == XFS_ATTR_LEAF_MAGIC);
/*
* Search an intermediate node for a match.
*/
if (blk->magic == XFS_DA_NODE_MAGIC) {
node = blk->bp->data;
max = be16_to_cpu(node->hdr.count);
blk->hashval = be32_to_cpu(node->btree[max-1].hashval);
/*
* Binary search. (note: small blocks will skip loop)
*/
probe = span = max / 2;
hashval = args->hashval;
for (btree = &node->btree[probe]; span > 4;
btree = &node->btree[probe]) {
span /= 2;
btreehashval = be32_to_cpu(btree->hashval);
if (btreehashval < hashval)
probe += span;
else if (btreehashval > hashval)
probe -= span;
else
break;
}
ASSERT((probe >= 0) && (probe < max));
ASSERT((span <= 4) || (be32_to_cpu(btree->hashval) == hashval));
/*
* Since we may have duplicate hashval's, find the first
* matching hashval in the node.
*/
while ((probe > 0) && (be32_to_cpu(btree->hashval) >= hashval)) {
btree--;
probe--;
}
while ((probe < max) && (be32_to_cpu(btree->hashval) < hashval)) {
btree++;
probe++;
}
/*
* Pick the right block to descend on.
*/
if (probe == max) {
blk->index = max-1;
blkno = be32_to_cpu(node->btree[max-1].before);
} else {
blk->index = probe;
blkno = be32_to_cpu(btree->before);
}
} else if (blk->magic == XFS_ATTR_LEAF_MAGIC) {
blk->hashval = xfs_attr_leaf_lasthash(blk->bp, NULL);
break;
} else if (blk->magic == XFS_DIR2_LEAFN_MAGIC) {
blk->hashval = xfs_dir2_leafn_lasthash(blk->bp, NULL);
break;
}
}
/*
* A leaf block that ends in the hashval that we are interested in
* (final hashval == search hashval) means that the next block may
* contain more entries with the same hashval, shift upward to the
* next leaf and keep searching.
*/
for (;;) {
if (blk->magic == XFS_DIR2_LEAFN_MAGIC) {
retval = xfs_dir2_leafn_lookup_int(blk->bp, args,
&blk->index, state);
} else if (blk->magic == XFS_ATTR_LEAF_MAGIC) {
retval = xfs_attr_leaf_lookup_int(blk->bp, args);
blk->index = args->index;
args->blkno = blk->blkno;
} else {
ASSERT(0);
return XFS_ERROR(EFSCORRUPTED);
}
if (((retval == ENOENT) || (retval == ENOATTR)) &&
(blk->hashval == args->hashval)) {
error = xfs_da_path_shift(state, &state->path, 1, 1,
&retval);
if (error)
return(error);
if (retval == 0) {
continue;
} else if (blk->magic == XFS_ATTR_LEAF_MAGIC) {
/* path_shift() gives ENOENT */
retval = XFS_ERROR(ENOATTR);
}
}
break;
}
*result = retval;
return(0);
}
/*========================================================================
* Utility routines.
*========================================================================*/
/*
* Link a new block into a doubly linked list of blocks (of whatever type).
*/
int /* error */
xfs_da_blk_link(xfs_da_state_t *state, xfs_da_state_blk_t *old_blk,
xfs_da_state_blk_t *new_blk)
{
xfs_da_blkinfo_t *old_info, *new_info, *tmp_info;
xfs_da_args_t *args;
int before=0, error;
xfs_dabuf_t *bp;
/*
* Set up environment.
*/
args = state->args;
ASSERT(args != NULL);
old_info = old_blk->bp->data;
new_info = new_blk->bp->data;
ASSERT(old_blk->magic == XFS_DA_NODE_MAGIC ||
old_blk->magic == XFS_DIR2_LEAFN_MAGIC ||
old_blk->magic == XFS_ATTR_LEAF_MAGIC);
ASSERT(old_blk->magic == be16_to_cpu(old_info->magic));
ASSERT(new_blk->magic == be16_to_cpu(new_info->magic));
ASSERT(old_blk->magic == new_blk->magic);
switch (old_blk->magic) {
case XFS_ATTR_LEAF_MAGIC:
before = xfs_attr_leaf_order(old_blk->bp, new_blk->bp);
break;
case XFS_DIR2_LEAFN_MAGIC:
before = xfs_dir2_leafn_order(old_blk->bp, new_blk->bp);
break;
case XFS_DA_NODE_MAGIC:
before = xfs_da_node_order(old_blk->bp, new_blk->bp);
break;
}
/*
* Link blocks in appropriate order.
*/
if (before) {
/*
* Link new block in before existing block.
*/
trace_xfs_da_link_before(args);
new_info->forw = cpu_to_be32(old_blk->blkno);
new_info->back = old_info->back;
if (old_info->back) {
error = xfs_da_read_buf(args->trans, args->dp,
be32_to_cpu(old_info->back),
-1, &bp, args->whichfork);
if (error)
return(error);
ASSERT(bp != NULL);
tmp_info = bp->data;
ASSERT(be16_to_cpu(tmp_info->magic) == be16_to_cpu(old_info->magic));
ASSERT(be32_to_cpu(tmp_info->forw) == old_blk->blkno);
tmp_info->forw = cpu_to_be32(new_blk->blkno);
xfs_da_log_buf(args->trans, bp, 0, sizeof(*tmp_info)-1);
xfs_da_buf_done(bp);
}
old_info->back = cpu_to_be32(new_blk->blkno);
} else {
/*
* Link new block in after existing block.
*/
trace_xfs_da_link_after(args);
new_info->forw = old_info->forw;
new_info->back = cpu_to_be32(old_blk->blkno);
if (old_info->forw) {
error = xfs_da_read_buf(args->trans, args->dp,
be32_to_cpu(old_info->forw),
-1, &bp, args->whichfork);
if (error)
return(error);
ASSERT(bp != NULL);
tmp_info = bp->data;
ASSERT(tmp_info->magic == old_info->magic);
ASSERT(be32_to_cpu(tmp_info->back) == old_blk->blkno);
tmp_info->back = cpu_to_be32(new_blk->blkno);
xfs_da_log_buf(args->trans, bp, 0, sizeof(*tmp_info)-1);
xfs_da_buf_done(bp);
}
old_info->forw = cpu_to_be32(new_blk->blkno);
}
xfs_da_log_buf(args->trans, old_blk->bp, 0, sizeof(*tmp_info) - 1);
xfs_da_log_buf(args->trans, new_blk->bp, 0, sizeof(*tmp_info) - 1);
return(0);
}
/*
* Compare two intermediate nodes for "order".
*/
STATIC int
xfs_da_node_order(xfs_dabuf_t *node1_bp, xfs_dabuf_t *node2_bp)
{
xfs_da_intnode_t *node1, *node2;
node1 = node1_bp->data;
node2 = node2_bp->data;
ASSERT(node1->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC) &&
node2->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC));
if ((be16_to_cpu(node1->hdr.count) > 0) && (be16_to_cpu(node2->hdr.count) > 0) &&
((be32_to_cpu(node2->btree[0].hashval) <
be32_to_cpu(node1->btree[0].hashval)) ||
(be32_to_cpu(node2->btree[be16_to_cpu(node2->hdr.count)-1].hashval) <
be32_to_cpu(node1->btree[be16_to_cpu(node1->hdr.count)-1].hashval)))) {
return(1);
}
return(0);
}
/*
* Pick up the last hashvalue from an intermediate node.
*/
STATIC uint
xfs_da_node_lasthash(xfs_dabuf_t *bp, int *count)
{
xfs_da_intnode_t *node;
node = bp->data;
ASSERT(node->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC));
if (count)
*count = be16_to_cpu(node->hdr.count);
if (!node->hdr.count)
return(0);
return be32_to_cpu(node->btree[be16_to_cpu(node->hdr.count)-1].hashval);
}
/*
* Unlink a block from a doubly linked list of blocks.
*/
STATIC int /* error */
xfs_da_blk_unlink(xfs_da_state_t *state, xfs_da_state_blk_t *drop_blk,
xfs_da_state_blk_t *save_blk)
{
xfs_da_blkinfo_t *drop_info, *save_info, *tmp_info;
xfs_da_args_t *args;
xfs_dabuf_t *bp;
int error;
/*
* Set up environment.
*/
args = state->args;
ASSERT(args != NULL);
save_info = save_blk->bp->data;
drop_info = drop_blk->bp->data;
ASSERT(save_blk->magic == XFS_DA_NODE_MAGIC ||
save_blk->magic == XFS_DIR2_LEAFN_MAGIC ||
save_blk->magic == XFS_ATTR_LEAF_MAGIC);
ASSERT(save_blk->magic == be16_to_cpu(save_info->magic));
ASSERT(drop_blk->magic == be16_to_cpu(drop_info->magic));
ASSERT(save_blk->magic == drop_blk->magic);
ASSERT((be32_to_cpu(save_info->forw) == drop_blk->blkno) ||
(be32_to_cpu(save_info->back) == drop_blk->blkno));
ASSERT((be32_to_cpu(drop_info->forw) == save_blk->blkno) ||
(be32_to_cpu(drop_info->back) == save_blk->blkno));
/*
* Unlink the leaf block from the doubly linked chain of leaves.
*/
if (be32_to_cpu(save_info->back) == drop_blk->blkno) {
trace_xfs_da_unlink_back(args);
save_info->back = drop_info->back;
if (drop_info->back) {
error = xfs_da_read_buf(args->trans, args->dp,
be32_to_cpu(drop_info->back),
-1, &bp, args->whichfork);
if (error)
return(error);
ASSERT(bp != NULL);
tmp_info = bp->data;
ASSERT(tmp_info->magic == save_info->magic);
ASSERT(be32_to_cpu(tmp_info->forw) == drop_blk->blkno);
tmp_info->forw = cpu_to_be32(save_blk->blkno);
xfs_da_log_buf(args->trans, bp, 0,
sizeof(*tmp_info) - 1);
xfs_da_buf_done(bp);
}
} else {
trace_xfs_da_unlink_forward(args);
save_info->forw = drop_info->forw;
if (drop_info->forw) {
error = xfs_da_read_buf(args->trans, args->dp,
be32_to_cpu(drop_info->forw),
-1, &bp, args->whichfork);
if (error)
return(error);
ASSERT(bp != NULL);
tmp_info = bp->data;
ASSERT(tmp_info->magic == save_info->magic);
ASSERT(be32_to_cpu(tmp_info->back) == drop_blk->blkno);
tmp_info->back = cpu_to_be32(save_blk->blkno);
xfs_da_log_buf(args->trans, bp, 0,
sizeof(*tmp_info) - 1);
xfs_da_buf_done(bp);
}
}
xfs_da_log_buf(args->trans, save_blk->bp, 0, sizeof(*save_info) - 1);
return(0);
}
/*
* Move a path "forward" or "!forward" one block at the current level.
*
* This routine will adjust a "path" to point to the next block
* "forward" (higher hashvalues) or "!forward" (lower hashvals) in the
* Btree, including updating pointers to the intermediate nodes between
* the new bottom and the root.
*/
int /* error */
xfs_da_path_shift(xfs_da_state_t *state, xfs_da_state_path_t *path,
int forward, int release, int *result)
{
xfs_da_state_blk_t *blk;
xfs_da_blkinfo_t *info;
xfs_da_intnode_t *node;
xfs_da_args_t *args;
xfs_dablk_t blkno=0;
int level, error;
/*
* Roll up the Btree looking for the first block where our
* current index is not at the edge of the block. Note that
* we skip the bottom layer because we want the sibling block.
*/
args = state->args;
ASSERT(args != NULL);
ASSERT(path != NULL);
ASSERT((path->active > 0) && (path->active < XFS_DA_NODE_MAXDEPTH));
level = (path->active-1) - 1; /* skip bottom layer in path */
for (blk = &path->blk[level]; level >= 0; blk--, level--) {
ASSERT(blk->bp != NULL);
node = blk->bp->data;
ASSERT(node->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC));
if (forward && (blk->index < be16_to_cpu(node->hdr.count)-1)) {
blk->index++;
blkno = be32_to_cpu(node->btree[blk->index].before);
break;
} else if (!forward && (blk->index > 0)) {
blk->index--;
blkno = be32_to_cpu(node->btree[blk->index].before);
break;
}
}
if (level < 0) {
*result = XFS_ERROR(ENOENT); /* we're out of our tree */
ASSERT(args->op_flags & XFS_DA_OP_OKNOENT);
return(0);
}
/*
* Roll down the edge of the subtree until we reach the
* same depth we were at originally.
*/
for (blk++, level++; level < path->active; blk++, level++) {
/*
* Release the old block.
* (if it's dirty, trans won't actually let go)
*/
if (release)
xfs_da_brelse(args->trans, blk->bp);
/*
* Read the next child block.
*/
blk->blkno = blkno;
error = xfs_da_read_buf(args->trans, args->dp, blkno, -1,
&blk->bp, args->whichfork);
if (error)
return(error);
ASSERT(blk->bp != NULL);
info = blk->bp->data;
ASSERT(info->magic == cpu_to_be16(XFS_DA_NODE_MAGIC) ||
info->magic == cpu_to_be16(XFS_DIR2_LEAFN_MAGIC) ||
info->magic == cpu_to_be16(XFS_ATTR_LEAF_MAGIC));
blk->magic = be16_to_cpu(info->magic);
if (blk->magic == XFS_DA_NODE_MAGIC) {
node = (xfs_da_intnode_t *)info;
blk->hashval = be32_to_cpu(node->btree[be16_to_cpu(node->hdr.count)-1].hashval);
if (forward)
blk->index = 0;
else
blk->index = be16_to_cpu(node->hdr.count)-1;
blkno = be32_to_cpu(node->btree[blk->index].before);
} else {
ASSERT(level == path->active-1);
blk->index = 0;
switch(blk->magic) {
case XFS_ATTR_LEAF_MAGIC:
blk->hashval = xfs_attr_leaf_lasthash(blk->bp,
NULL);
break;
case XFS_DIR2_LEAFN_MAGIC:
blk->hashval = xfs_dir2_leafn_lasthash(blk->bp,
NULL);
break;
default:
ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC ||
blk->magic == XFS_DIR2_LEAFN_MAGIC);
break;
}
}
}
*result = 0;
return(0);
}
/*========================================================================
* Utility routines.
*========================================================================*/
/*
* Implement a simple hash on a character string.
* Rotate the hash value by 7 bits, then XOR each character in.
* This is implemented with some source-level loop unrolling.
*/
xfs_dahash_t
xfs_da_hashname(const __uint8_t *name, int namelen)
{
xfs_dahash_t hash;
/*
* Do four characters at a time as long as we can.
*/
for (hash = 0; namelen >= 4; namelen -= 4, name += 4)
hash = (name[0] << 21) ^ (name[1] << 14) ^ (name[2] << 7) ^
(name[3] << 0) ^ rol32(hash, 7 * 4);
/*
* Now do the rest of the characters.
*/
switch (namelen) {
case 3:
return (name[0] << 14) ^ (name[1] << 7) ^ (name[2] << 0) ^
rol32(hash, 7 * 3);
case 2:
return (name[0] << 7) ^ (name[1] << 0) ^ rol32(hash, 7 * 2);
case 1:
return (name[0] << 0) ^ rol32(hash, 7 * 1);
default: /* case 0: */
return hash;
}
}
enum xfs_dacmp
xfs_da_compname(
struct xfs_da_args *args,
const unsigned char *name,
int len)
{
return (args->namelen == len && memcmp(args->name, name, len) == 0) ?
XFS_CMP_EXACT : XFS_CMP_DIFFERENT;
}
static xfs_dahash_t
xfs_default_hashname(
struct xfs_name *name)
{
return xfs_da_hashname(name->name, name->len);
}
const struct xfs_nameops xfs_default_nameops = {
.hashname = xfs_default_hashname,
.compname = xfs_da_compname
};
int
xfs_da_grow_inode_int(
struct xfs_da_args *args,
xfs_fileoff_t *bno,
int count)
{
struct xfs_trans *tp = args->trans;
struct xfs_inode *dp = args->dp;
int w = args->whichfork;
xfs_drfsbno_t nblks = dp->i_d.di_nblocks;
struct xfs_bmbt_irec map, *mapp;
int nmap, error, got, i, mapi;
/*
* Find a spot in the file space to put the new block.
*/
error = xfs_bmap_first_unused(tp, dp, count, bno, w);
if (error)
return error;
/*
* Try mapping it in one filesystem block.
*/
nmap = 1;
ASSERT(args->firstblock != NULL);
error = xfs_bmapi_write(tp, dp, *bno, count,
xfs_bmapi_aflag(w)|XFS_BMAPI_METADATA|XFS_BMAPI_CONTIG,
args->firstblock, args->total, &map, &nmap,
args->flist);
if (error)
return error;
ASSERT(nmap <= 1);
if (nmap == 1) {
mapp = ↦
mapi = 1;
} else if (nmap == 0 && count > 1) {
xfs_fileoff_t b;
int c;
/*
* If we didn't get it and the block might work if fragmented,
* try without the CONTIG flag. Loop until we get it all.
*/
mapp = kmem_alloc(sizeof(*mapp) * count, KM_SLEEP);
for (b = *bno, mapi = 0; b < *bno + count; ) {
nmap = MIN(XFS_BMAP_MAX_NMAP, count);
c = (int)(*bno + count - b);
error = xfs_bmapi_write(tp, dp, b, c,
xfs_bmapi_aflag(w)|XFS_BMAPI_METADATA,
args->firstblock, args->total,
&mapp[mapi], &nmap, args->flist);
if (error)
goto out_free_map;
if (nmap < 1)
break;
mapi += nmap;
b = mapp[mapi - 1].br_startoff +
mapp[mapi - 1].br_blockcount;
}
} else {
mapi = 0;
mapp = NULL;
}
/*
* Count the blocks we got, make sure it matches the total.
*/
for (i = 0, got = 0; i < mapi; i++)
got += mapp[i].br_blockcount;
if (got != count || mapp[0].br_startoff != *bno ||
mapp[mapi - 1].br_startoff + mapp[mapi - 1].br_blockcount !=
*bno + count) {
error = XFS_ERROR(ENOSPC);
goto out_free_map;
}
/* account for newly allocated blocks in reserved blocks total */
args->total -= dp->i_d.di_nblocks - nblks;
out_free_map:
if (mapp != &map)
kmem_free(mapp);
return error;
}
/*
* Add a block to the btree ahead of the file.
* Return the new block number to the caller.
*/
int
xfs_da_grow_inode(
struct xfs_da_args *args,
xfs_dablk_t *new_blkno)
{
xfs_fileoff_t bno;
int count;
int error;
trace_xfs_da_grow_inode(args);
if (args->whichfork == XFS_DATA_FORK) {
bno = args->dp->i_mount->m_dirleafblk;
count = args->dp->i_mount->m_dirblkfsbs;
} else {
bno = 0;
count = 1;
}
error = xfs_da_grow_inode_int(args, &bno, count);
if (!error)
*new_blkno = (xfs_dablk_t)bno;
return error;
}
/*
* Ick. We need to always be able to remove a btree block, even
* if there's no space reservation because the filesystem is full.
* This is called if xfs_bunmapi on a btree block fails due to ENOSPC.
* It swaps the target block with the last block in the file. The
* last block in the file can always be removed since it can't cause
* a bmap btree split to do that.
*/
STATIC int
xfs_da_swap_lastblock(xfs_da_args_t *args, xfs_dablk_t *dead_blknop,
xfs_dabuf_t **dead_bufp)
{
xfs_dablk_t dead_blkno, last_blkno, sib_blkno, par_blkno;
xfs_dabuf_t *dead_buf, *last_buf, *sib_buf, *par_buf;
xfs_fileoff_t lastoff;
xfs_inode_t *ip;
xfs_trans_t *tp;
xfs_mount_t *mp;
int error, w, entno, level, dead_level;
xfs_da_blkinfo_t *dead_info, *sib_info;
xfs_da_intnode_t *par_node, *dead_node;
xfs_dir2_leaf_t *dead_leaf2;
xfs_dahash_t dead_hash;
trace_xfs_da_swap_lastblock(args);
dead_buf = *dead_bufp;
dead_blkno = *dead_blknop;
tp = args->trans;
ip = args->dp;
w = args->whichfork;
ASSERT(w == XFS_DATA_FORK);
mp = ip->i_mount;
lastoff = mp->m_dirfreeblk;
error = xfs_bmap_last_before(tp, ip, &lastoff, w);
if (error)
return error;
if (unlikely(lastoff == 0)) {
XFS_ERROR_REPORT("xfs_da_swap_lastblock(1)", XFS_ERRLEVEL_LOW,
mp);
return XFS_ERROR(EFSCORRUPTED);
}
/*
* Read the last block in the btree space.
*/
last_blkno = (xfs_dablk_t)lastoff - mp->m_dirblkfsbs;
if ((error = xfs_da_read_buf(tp, ip, last_blkno, -1, &last_buf, w)))
return error;
/*
* Copy the last block into the dead buffer and log it.
*/
memcpy(dead_buf->data, last_buf->data, mp->m_dirblksize);
xfs_da_log_buf(tp, dead_buf, 0, mp->m_dirblksize - 1);
dead_info = dead_buf->data;
/*
* Get values from the moved block.
*/
if (dead_info->magic == cpu_to_be16(XFS_DIR2_LEAFN_MAGIC)) {
dead_leaf2 = (xfs_dir2_leaf_t *)dead_info;
dead_level = 0;
dead_hash = be32_to_cpu(dead_leaf2->ents[be16_to_cpu(dead_leaf2->hdr.count) - 1].hashval);
} else {
ASSERT(dead_info->magic == cpu_to_be16(XFS_DA_NODE_MAGIC));
dead_node = (xfs_da_intnode_t *)dead_info;
dead_level = be16_to_cpu(dead_node->hdr.level);
dead_hash = be32_to_cpu(dead_node->btree[be16_to_cpu(dead_node->hdr.count) - 1].hashval);
}
sib_buf = par_buf = NULL;
/*
* If the moved block has a left sibling, fix up the pointers.
*/
if ((sib_blkno = be32_to_cpu(dead_info->back))) {
if ((error = xfs_da_read_buf(tp, ip, sib_blkno, -1, &sib_buf, w)))
goto done;
sib_info = sib_buf->data;
if (unlikely(
be32_to_cpu(sib_info->forw) != last_blkno ||
sib_info->magic != dead_info->magic)) {
XFS_ERROR_REPORT("xfs_da_swap_lastblock(2)",
XFS_ERRLEVEL_LOW, mp);
error = XFS_ERROR(EFSCORRUPTED);
goto done;
}
sib_info->forw = cpu_to_be32(dead_blkno);
xfs_da_log_buf(tp, sib_buf,
XFS_DA_LOGRANGE(sib_info, &sib_info->forw,
sizeof(sib_info->forw)));
xfs_da_buf_done(sib_buf);
sib_buf = NULL;
}
/*
* If the moved block has a right sibling, fix up the pointers.
*/
if ((sib_blkno = be32_to_cpu(dead_info->forw))) {
if ((error = xfs_da_read_buf(tp, ip, sib_blkno, -1, &sib_buf, w)))
goto done;
sib_info = sib_buf->data;
if (unlikely(
be32_to_cpu(sib_info->back) != last_blkno ||
sib_info->magic != dead_info->magic)) {
XFS_ERROR_REPORT("xfs_da_swap_lastblock(3)",
XFS_ERRLEVEL_LOW, mp);
error = XFS_ERROR(EFSCORRUPTED);
goto done;
}
sib_info->back = cpu_to_be32(dead_blkno);
xfs_da_log_buf(tp, sib_buf,
XFS_DA_LOGRANGE(sib_info, &sib_info->back,
sizeof(sib_info->back)));
xfs_da_buf_done(sib_buf);
sib_buf = NULL;
}
par_blkno = mp->m_dirleafblk;
level = -1;
/*
* Walk down the tree looking for the parent of the moved block.
*/
for (;;) {
if ((error = xfs_da_read_buf(tp, ip, par_blkno, -1, &par_buf, w)))
goto done;
par_node = par_buf->data;
if (unlikely(par_node->hdr.info.magic !=
cpu_to_be16(XFS_DA_NODE_MAGIC) ||
(level >= 0 && level != be16_to_cpu(par_node->hdr.level) + 1))) {
XFS_ERROR_REPORT("xfs_da_swap_lastblock(4)",
XFS_ERRLEVEL_LOW, mp);
error = XFS_ERROR(EFSCORRUPTED);
goto done;
}
level = be16_to_cpu(par_node->hdr.level);
for (entno = 0;
entno < be16_to_cpu(par_node->hdr.count) &&
be32_to_cpu(par_node->btree[entno].hashval) < dead_hash;
entno++)
continue;
if (unlikely(entno == be16_to_cpu(par_node->hdr.count))) {
XFS_ERROR_REPORT("xfs_da_swap_lastblock(5)",
XFS_ERRLEVEL_LOW, mp);
error = XFS_ERROR(EFSCORRUPTED);
goto done;
}
par_blkno = be32_to_cpu(par_node->btree[entno].before);
if (level == dead_level + 1)
break;
xfs_da_brelse(tp, par_buf);
par_buf = NULL;
}
/*
* We're in the right parent block.
* Look for the right entry.
*/
for (;;) {
for (;
entno < be16_to_cpu(par_node->hdr.count) &&
be32_to_cpu(par_node->btree[entno].before) != last_blkno;
entno++)
continue;
if (entno < be16_to_cpu(par_node->hdr.count))
break;
par_blkno = be32_to_cpu(par_node->hdr.info.forw);
xfs_da_brelse(tp, par_buf);
par_buf = NULL;
if (unlikely(par_blkno == 0)) {
XFS_ERROR_REPORT("xfs_da_swap_lastblock(6)",
XFS_ERRLEVEL_LOW, mp);
error = XFS_ERROR(EFSCORRUPTED);
goto done;
}
if ((error = xfs_da_read_buf(tp, ip, par_blkno, -1, &par_buf, w)))
goto done;
par_node = par_buf->data;
if (unlikely(
be16_to_cpu(par_node->hdr.level) != level ||
par_node->hdr.info.magic != cpu_to_be16(XFS_DA_NODE_MAGIC))) {
XFS_ERROR_REPORT("xfs_da_swap_lastblock(7)",
XFS_ERRLEVEL_LOW, mp);
error = XFS_ERROR(EFSCORRUPTED);
goto done;
}
entno = 0;
}
/*
* Update the parent entry pointing to the moved block.
*/
par_node->btree[entno].before = cpu_to_be32(dead_blkno);
xfs_da_log_buf(tp, par_buf,
XFS_DA_LOGRANGE(par_node, &par_node->btree[entno].before,
sizeof(par_node->btree[entno].before)));
xfs_da_buf_done(par_buf);
xfs_da_buf_done(dead_buf);
*dead_blknop = last_blkno;
*dead_bufp = last_buf;
return 0;
done:
if (par_buf)
xfs_da_brelse(tp, par_buf);
if (sib_buf)
xfs_da_brelse(tp, sib_buf);
xfs_da_brelse(tp, last_buf);
return error;
}
/*
* Remove a btree block from a directory or attribute.
*/
int
xfs_da_shrink_inode(xfs_da_args_t *args, xfs_dablk_t dead_blkno,
xfs_dabuf_t *dead_buf)
{
xfs_inode_t *dp;
int done, error, w, count;
xfs_trans_t *tp;
xfs_mount_t *mp;
trace_xfs_da_shrink_inode(args);
dp = args->dp;
w = args->whichfork;
tp = args->trans;
mp = dp->i_mount;
if (w == XFS_DATA_FORK)
count = mp->m_dirblkfsbs;
else
count = 1;
for (;;) {
/*
* Remove extents. If we get ENOSPC for a dir we have to move
* the last block to the place we want to kill.
*/
if ((error = xfs_bunmapi(tp, dp, dead_blkno, count,
xfs_bmapi_aflag(w)|XFS_BMAPI_METADATA,
0, args->firstblock, args->flist,
&done)) == ENOSPC) {
if (w != XFS_DATA_FORK)
break;
if ((error = xfs_da_swap_lastblock(args, &dead_blkno,
&dead_buf)))
break;
} else {
break;
}
}
xfs_da_binval(tp, dead_buf);
return error;
}
/*
* See if the mapping(s) for this btree block are valid, i.e.
* don't contain holes, are logically contiguous, and cover the whole range.
*/
STATIC int
xfs_da_map_covers_blocks(
int nmap,
xfs_bmbt_irec_t *mapp,
xfs_dablk_t bno,
int count)
{
int i;
xfs_fileoff_t off;
for (i = 0, off = bno; i < nmap; i++) {
if (mapp[i].br_startblock == HOLESTARTBLOCK ||
mapp[i].br_startblock == DELAYSTARTBLOCK) {
return 0;
}
if (off != mapp[i].br_startoff) {
return 0;
}
off += mapp[i].br_blockcount;
}
return off == bno + count;
}
/*
* Make a dabuf.
* Used for get_buf, read_buf, read_bufr, and reada_buf.
*/
STATIC int
xfs_da_do_buf(
xfs_trans_t *trans,
xfs_inode_t *dp,
xfs_dablk_t bno,
xfs_daddr_t *mappedbnop,
xfs_dabuf_t **bpp,
int whichfork,
int caller)
{
xfs_buf_t *bp = NULL;
xfs_buf_t **bplist;
int error=0;
int i;
xfs_bmbt_irec_t map;
xfs_bmbt_irec_t *mapp;
xfs_daddr_t mappedbno;
xfs_mount_t *mp;
int nbplist=0;
int nfsb;
int nmap;
xfs_dabuf_t *rbp;
mp = dp->i_mount;
nfsb = (whichfork == XFS_DATA_FORK) ? mp->m_dirblkfsbs : 1;
mappedbno = *mappedbnop;
/*
* Caller doesn't have a mapping. -2 means don't complain
* if we land in a hole.
*/
if (mappedbno == -1 || mappedbno == -2) {
/*
* Optimize the one-block case.
*/
if (nfsb == 1)
mapp = ↦
else
mapp = kmem_alloc(sizeof(*mapp) * nfsb, KM_SLEEP);
nmap = nfsb;
error = xfs_bmapi_read(dp, (xfs_fileoff_t)bno, nfsb, mapp,
&nmap, xfs_bmapi_aflag(whichfork));
if (error)
goto exit0;
} else {
map.br_startblock = XFS_DADDR_TO_FSB(mp, mappedbno);
map.br_startoff = (xfs_fileoff_t)bno;
map.br_blockcount = nfsb;
mapp = ↦
nmap = 1;
}
if (!xfs_da_map_covers_blocks(nmap, mapp, bno, nfsb)) {
error = mappedbno == -2 ? 0 : XFS_ERROR(EFSCORRUPTED);
if (unlikely(error == EFSCORRUPTED)) {
if (xfs_error_level >= XFS_ERRLEVEL_LOW) {
xfs_alert(mp, "%s: bno %lld dir: inode %lld",
__func__, (long long)bno,
(long long)dp->i_ino);
for (i = 0; i < nmap; i++) {
xfs_alert(mp,
"[%02d] br_startoff %lld br_startblock %lld br_blockcount %lld br_state %d",
i,
(long long)mapp[i].br_startoff,
(long long)mapp[i].br_startblock,
(long long)mapp[i].br_blockcount,
mapp[i].br_state);
}
}
XFS_ERROR_REPORT("xfs_da_do_buf(1)",
XFS_ERRLEVEL_LOW, mp);
}
goto exit0;
}
if (caller != 3 && nmap > 1) {
bplist = kmem_alloc(sizeof(*bplist) * nmap, KM_SLEEP);
nbplist = 0;
} else
bplist = NULL;
/*
* Turn the mapping(s) into buffer(s).
*/
for (i = 0; i < nmap; i++) {
int nmapped;
mappedbno = XFS_FSB_TO_DADDR(mp, mapp[i].br_startblock);
if (i == 0)
*mappedbnop = mappedbno;
nmapped = (int)XFS_FSB_TO_BB(mp, mapp[i].br_blockcount);
switch (caller) {
case 0:
bp = xfs_trans_get_buf(trans, mp->m_ddev_targp,
mappedbno, nmapped, 0);
error = bp ? bp->b_error : XFS_ERROR(EIO);
break;
case 1:
case 2:
bp = NULL;
error = xfs_trans_read_buf(mp, trans, mp->m_ddev_targp,
mappedbno, nmapped, 0, &bp);
break;
case 3:
xfs_buf_readahead(mp->m_ddev_targp, mappedbno, nmapped);
error = 0;
bp = NULL;
break;
}
if (error) {
if (bp)
xfs_trans_brelse(trans, bp);
goto exit1;
}
if (!bp)
continue;
if (caller == 1) {
if (whichfork == XFS_ATTR_FORK)
xfs_buf_set_ref(bp, XFS_ATTR_BTREE_REF);
else
xfs_buf_set_ref(bp, XFS_DIR_BTREE_REF);
}
if (bplist) {
bplist[nbplist++] = bp;
}
}
/*
* Build a dabuf structure.
*/
if (bplist) {
rbp = xfs_da_buf_make(nbplist, bplist);
} else if (bp)
rbp = xfs_da_buf_make(1, &bp);
else
rbp = NULL;
/*
* For read_buf, check the magic number.
*/
if (caller == 1) {
xfs_dir2_data_hdr_t *hdr = rbp->data;
xfs_dir2_free_t *free = rbp->data;
xfs_da_blkinfo_t *info = rbp->data;
uint magic, magic1;
magic = be16_to_cpu(info->magic);
magic1 = be32_to_cpu(hdr->magic);
if (unlikely(
XFS_TEST_ERROR((magic != XFS_DA_NODE_MAGIC) &&
(magic != XFS_ATTR_LEAF_MAGIC) &&
(magic != XFS_DIR2_LEAF1_MAGIC) &&
(magic != XFS_DIR2_LEAFN_MAGIC) &&
(magic1 != XFS_DIR2_BLOCK_MAGIC) &&
(magic1 != XFS_DIR2_DATA_MAGIC) &&
(free->hdr.magic != cpu_to_be32(XFS_DIR2_FREE_MAGIC)),
mp, XFS_ERRTAG_DA_READ_BUF,
XFS_RANDOM_DA_READ_BUF))) {
trace_xfs_da_btree_corrupt(rbp->bps[0], _RET_IP_);
XFS_CORRUPTION_ERROR("xfs_da_do_buf(2)",
XFS_ERRLEVEL_LOW, mp, info);
error = XFS_ERROR(EFSCORRUPTED);
xfs_da_brelse(trans, rbp);
nbplist = 0;
goto exit1;
}
}
if (bplist) {
kmem_free(bplist);
}
if (mapp != &map) {
kmem_free(mapp);
}
if (bpp)
*bpp = rbp;
return 0;
exit1:
if (bplist) {
for (i = 0; i < nbplist; i++)
xfs_trans_brelse(trans, bplist[i]);
kmem_free(bplist);
}
exit0:
if (mapp != &map)
kmem_free(mapp);
if (bpp)
*bpp = NULL;
return error;
}
/*
* Get a buffer for the dir/attr block.
*/
int
xfs_da_get_buf(
xfs_trans_t *trans,
xfs_inode_t *dp,
xfs_dablk_t bno,
xfs_daddr_t mappedbno,
xfs_dabuf_t **bpp,
int whichfork)
{
return xfs_da_do_buf(trans, dp, bno, &mappedbno, bpp, whichfork, 0);
}
/*
* Get a buffer for the dir/attr block, fill in the contents.
*/
int
xfs_da_read_buf(
xfs_trans_t *trans,
xfs_inode_t *dp,
xfs_dablk_t bno,
xfs_daddr_t mappedbno,
xfs_dabuf_t **bpp,
int whichfork)
{
return xfs_da_do_buf(trans, dp, bno, &mappedbno, bpp, whichfork, 1);
}
/*
* Readahead the dir/attr block.
*/
xfs_daddr_t
xfs_da_reada_buf(
xfs_trans_t *trans,
xfs_inode_t *dp,
xfs_dablk_t bno,
int whichfork)
{
xfs_daddr_t rval;
rval = -1;
if (xfs_da_do_buf(trans, dp, bno, &rval, NULL, whichfork, 3))
return -1;
else
return rval;
}
kmem_zone_t *xfs_da_state_zone; /* anchor for state struct zone */
kmem_zone_t *xfs_dabuf_zone; /* dabuf zone */
/*
* Allocate a dir-state structure.
* We don't put them on the stack since they're large.
*/
xfs_da_state_t *
xfs_da_state_alloc(void)
{
return kmem_zone_zalloc(xfs_da_state_zone, KM_NOFS);
}
/*
* Kill the altpath contents of a da-state structure.
*/
STATIC void
xfs_da_state_kill_altpath(xfs_da_state_t *state)
{
int i;
for (i = 0; i < state->altpath.active; i++) {
if (state->altpath.blk[i].bp) {
if (state->altpath.blk[i].bp != state->path.blk[i].bp)
xfs_da_buf_done(state->altpath.blk[i].bp);
state->altpath.blk[i].bp = NULL;
}
}
state->altpath.active = 0;
}
/*
* Free a da-state structure.
*/
void
xfs_da_state_free(xfs_da_state_t *state)
{
int i;
xfs_da_state_kill_altpath(state);
for (i = 0; i < state->path.active; i++) {
if (state->path.blk[i].bp)
xfs_da_buf_done(state->path.blk[i].bp);
}
if (state->extravalid && state->extrablk.bp)
xfs_da_buf_done(state->extrablk.bp);
#ifdef DEBUG
memset((char *)state, 0, sizeof(*state));
#endif /* DEBUG */
kmem_zone_free(xfs_da_state_zone, state);
}
/*
* Create a dabuf.
*/
/* ARGSUSED */
STATIC xfs_dabuf_t *
xfs_da_buf_make(int nbuf, xfs_buf_t **bps)
{
xfs_buf_t *bp;
xfs_dabuf_t *dabuf;
int i;
int off;
if (nbuf == 1)
dabuf = kmem_zone_alloc(xfs_dabuf_zone, KM_NOFS);
else
dabuf = kmem_alloc(XFS_DA_BUF_SIZE(nbuf), KM_NOFS);
dabuf->dirty = 0;
if (nbuf == 1) {
dabuf->nbuf = 1;
bp = bps[0];
dabuf->bbcount = (short)BTOBB(XFS_BUF_COUNT(bp));
dabuf->data = bp->b_addr;
dabuf->bps[0] = bp;
} else {
dabuf->nbuf = nbuf;
for (i = 0, dabuf->bbcount = 0; i < nbuf; i++) {
dabuf->bps[i] = bp = bps[i];
dabuf->bbcount += BTOBB(XFS_BUF_COUNT(bp));
}
dabuf->data = kmem_alloc(BBTOB(dabuf->bbcount), KM_SLEEP);
for (i = off = 0; i < nbuf; i++, off += XFS_BUF_COUNT(bp)) {
bp = bps[i];
memcpy((char *)dabuf->data + off, bp->b_addr,
XFS_BUF_COUNT(bp));
}
}
return dabuf;
}
/*
* Un-dirty a dabuf.
*/
STATIC void
xfs_da_buf_clean(xfs_dabuf_t *dabuf)
{
xfs_buf_t *bp;
int i;
int off;
if (dabuf->dirty) {
ASSERT(dabuf->nbuf > 1);
dabuf->dirty = 0;
for (i = off = 0; i < dabuf->nbuf;
i++, off += XFS_BUF_COUNT(bp)) {
bp = dabuf->bps[i];
memcpy(bp->b_addr, dabuf->data + off,
XFS_BUF_COUNT(bp));
}
}
}
/*
* Release a dabuf.
*/
void
xfs_da_buf_done(xfs_dabuf_t *dabuf)
{
ASSERT(dabuf);
ASSERT(dabuf->nbuf && dabuf->data && dabuf->bbcount && dabuf->bps[0]);
if (dabuf->dirty)
xfs_da_buf_clean(dabuf);
if (dabuf->nbuf > 1) {
kmem_free(dabuf->data);
kmem_free(dabuf);
} else {
kmem_zone_free(xfs_dabuf_zone, dabuf);
}
}
/*
* Log transaction from a dabuf.
*/
void
xfs_da_log_buf(xfs_trans_t *tp, xfs_dabuf_t *dabuf, uint first, uint last)
{
xfs_buf_t *bp;
uint f;
int i;
uint l;
int off;
ASSERT(dabuf->nbuf && dabuf->data && dabuf->bbcount && dabuf->bps[0]);
if (dabuf->nbuf == 1) {
ASSERT(dabuf->data == dabuf->bps[0]->b_addr);
xfs_trans_log_buf(tp, dabuf->bps[0], first, last);
return;
}
dabuf->dirty = 1;
ASSERT(first <= last);
for (i = off = 0; i < dabuf->nbuf; i++, off += XFS_BUF_COUNT(bp)) {
bp = dabuf->bps[i];
f = off;
l = f + XFS_BUF_COUNT(bp) - 1;
if (f < first)
f = first;
if (l > last)
l = last;
if (f <= l)
xfs_trans_log_buf(tp, bp, f - off, l - off);
/*
* B_DONE is set by xfs_trans_log buf.
* If we don't set it on a new buffer (get not read)
* then if we don't put anything in the buffer it won't
* be set, and at commit it it released into the cache,
* and then a read will fail.
*/
else if (!(XFS_BUF_ISDONE(bp)))
XFS_BUF_DONE(bp);
}
ASSERT(last < off);
}
/*
* Release dabuf from a transaction.
* Have to free up the dabuf before the buffers are released,
* since the synchronization on the dabuf is really the lock on the buffer.
*/
void
xfs_da_brelse(xfs_trans_t *tp, xfs_dabuf_t *dabuf)
{
xfs_buf_t *bp;
xfs_buf_t **bplist;
int i;
int nbuf;
ASSERT(dabuf->nbuf && dabuf->data && dabuf->bbcount && dabuf->bps[0]);
if ((nbuf = dabuf->nbuf) == 1) {
bplist = &bp;
bp = dabuf->bps[0];
} else {
bplist = kmem_alloc(nbuf * sizeof(*bplist), KM_SLEEP);
memcpy(bplist, dabuf->bps, nbuf * sizeof(*bplist));
}
xfs_da_buf_done(dabuf);
for (i = 0; i < nbuf; i++)
xfs_trans_brelse(tp, bplist[i]);
if (bplist != &bp)
kmem_free(bplist);
}
/*
* Invalidate dabuf from a transaction.
*/
void
xfs_da_binval(xfs_trans_t *tp, xfs_dabuf_t *dabuf)
{
xfs_buf_t *bp;
xfs_buf_t **bplist;
int i;
int nbuf;
ASSERT(dabuf->nbuf && dabuf->data && dabuf->bbcount && dabuf->bps[0]);
if ((nbuf = dabuf->nbuf) == 1) {
bplist = &bp;
bp = dabuf->bps[0];
} else {
bplist = kmem_alloc(nbuf * sizeof(*bplist), KM_SLEEP);
memcpy(bplist, dabuf->bps, nbuf * sizeof(*bplist));
}
xfs_da_buf_done(dabuf);
for (i = 0; i < nbuf; i++)
xfs_trans_binval(tp, bplist[i]);
if (bplist != &bp)
kmem_free(bplist);
}
/*
* Get the first daddr from a dabuf.
*/
xfs_daddr_t
xfs_da_blkno(xfs_dabuf_t *dabuf)
{
ASSERT(dabuf->nbuf);
ASSERT(dabuf->data);
return XFS_BUF_ADDR(dabuf->bps[0]);
}
| gpl-2.0 |
mhmtemnacr/android_kernel_samsung_matissewifi | drivers/video/backlight/cr_bllcd.c | 4809 | 7525 | /*
* Copyright (c) Intel Corp. 2007.
* All Rights Reserved.
*
* Intel funded Tungsten Graphics (http://www.tungstengraphics.com) to
* develop this driver.
*
* This file is part of the Carillo Ranch video subsystem driver.
* The Carillo Ranch video subsystem driver is free software;
* you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* The Carillo Ranch video subsystem driver is distributed
* in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this driver; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Authors:
* Thomas Hellstrom <thomas-at-tungstengraphics-dot-com>
* Alan Hourihane <alanh-at-tungstengraphics-dot-com>
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/mutex.h>
#include <linux/fb.h>
#include <linux/backlight.h>
#include <linux/lcd.h>
#include <linux/pci.h>
#include <linux/slab.h>
/* The LVDS- and panel power controls sits on the
* GPIO port of the ISA bridge.
*/
#define CRVML_DEVICE_LPC 0x27B8
#define CRVML_REG_GPIOBAR 0x48
#define CRVML_REG_GPIOEN 0x4C
#define CRVML_GPIOEN_BIT (1 << 4)
#define CRVML_PANEL_PORT 0x38
#define CRVML_LVDS_ON 0x00000001
#define CRVML_PANEL_ON 0x00000002
#define CRVML_BACKLIGHT_OFF 0x00000004
/* The PLL Clock register sits on Host bridge */
#define CRVML_DEVICE_MCH 0x5001
#define CRVML_REG_MCHBAR 0x44
#define CRVML_REG_MCHEN 0x54
#define CRVML_MCHEN_BIT (1 << 28)
#define CRVML_MCHMAP_SIZE 4096
#define CRVML_REG_CLOCK 0xc3c
#define CRVML_CLOCK_SHIFT 8
#define CRVML_CLOCK_MASK 0x00000f00
static struct pci_dev *lpc_dev;
static u32 gpio_bar;
struct cr_panel {
struct backlight_device *cr_backlight_device;
struct lcd_device *cr_lcd_device;
};
static int cr_backlight_set_intensity(struct backlight_device *bd)
{
int intensity = bd->props.brightness;
u32 addr = gpio_bar + CRVML_PANEL_PORT;
u32 cur = inl(addr);
if (bd->props.power == FB_BLANK_UNBLANK)
intensity = FB_BLANK_UNBLANK;
if (bd->props.fb_blank == FB_BLANK_UNBLANK)
intensity = FB_BLANK_UNBLANK;
if (bd->props.power == FB_BLANK_POWERDOWN)
intensity = FB_BLANK_POWERDOWN;
if (bd->props.fb_blank == FB_BLANK_POWERDOWN)
intensity = FB_BLANK_POWERDOWN;
if (intensity == FB_BLANK_UNBLANK) { /* FULL ON */
cur &= ~CRVML_BACKLIGHT_OFF;
outl(cur, addr);
} else if (intensity == FB_BLANK_POWERDOWN) { /* OFF */
cur |= CRVML_BACKLIGHT_OFF;
outl(cur, addr);
} /* anything else, don't bother */
return 0;
}
static int cr_backlight_get_intensity(struct backlight_device *bd)
{
u32 addr = gpio_bar + CRVML_PANEL_PORT;
u32 cur = inl(addr);
u8 intensity;
if (cur & CRVML_BACKLIGHT_OFF)
intensity = FB_BLANK_POWERDOWN;
else
intensity = FB_BLANK_UNBLANK;
return intensity;
}
static const struct backlight_ops cr_backlight_ops = {
.get_brightness = cr_backlight_get_intensity,
.update_status = cr_backlight_set_intensity,
};
static void cr_panel_on(void)
{
u32 addr = gpio_bar + CRVML_PANEL_PORT;
u32 cur = inl(addr);
if (!(cur & CRVML_PANEL_ON)) {
/* Make sure LVDS controller is down. */
if (cur & 0x00000001) {
cur &= ~CRVML_LVDS_ON;
outl(cur, addr);
}
/* Power up Panel */
schedule_timeout(HZ / 10);
cur |= CRVML_PANEL_ON;
outl(cur, addr);
}
/* Power up LVDS controller */
if (!(cur & CRVML_LVDS_ON)) {
schedule_timeout(HZ / 10);
outl(cur | CRVML_LVDS_ON, addr);
}
}
static void cr_panel_off(void)
{
u32 addr = gpio_bar + CRVML_PANEL_PORT;
u32 cur = inl(addr);
/* Power down LVDS controller first to avoid high currents */
if (cur & CRVML_LVDS_ON) {
cur &= ~CRVML_LVDS_ON;
outl(cur, addr);
}
if (cur & CRVML_PANEL_ON) {
schedule_timeout(HZ / 10);
outl(cur & ~CRVML_PANEL_ON, addr);
}
}
static int cr_lcd_set_power(struct lcd_device *ld, int power)
{
if (power == FB_BLANK_UNBLANK)
cr_panel_on();
if (power == FB_BLANK_POWERDOWN)
cr_panel_off();
return 0;
}
static struct lcd_ops cr_lcd_ops = {
.set_power = cr_lcd_set_power,
};
static int cr_backlight_probe(struct platform_device *pdev)
{
struct backlight_properties props;
struct backlight_device *bdp;
struct lcd_device *ldp;
struct cr_panel *crp;
u8 dev_en;
lpc_dev = pci_get_device(PCI_VENDOR_ID_INTEL,
CRVML_DEVICE_LPC, NULL);
if (!lpc_dev) {
printk("INTEL CARILLO RANCH LPC not found.\n");
return -ENODEV;
}
pci_read_config_byte(lpc_dev, CRVML_REG_GPIOEN, &dev_en);
if (!(dev_en & CRVML_GPIOEN_BIT)) {
printk(KERN_ERR
"Carillo Ranch GPIO device was not enabled.\n");
pci_dev_put(lpc_dev);
return -ENODEV;
}
memset(&props, 0, sizeof(struct backlight_properties));
props.type = BACKLIGHT_RAW;
bdp = backlight_device_register("cr-backlight", &pdev->dev, NULL,
&cr_backlight_ops, &props);
if (IS_ERR(bdp)) {
pci_dev_put(lpc_dev);
return PTR_ERR(bdp);
}
ldp = lcd_device_register("cr-lcd", &pdev->dev, NULL, &cr_lcd_ops);
if (IS_ERR(ldp)) {
backlight_device_unregister(bdp);
pci_dev_put(lpc_dev);
return PTR_ERR(ldp);
}
pci_read_config_dword(lpc_dev, CRVML_REG_GPIOBAR,
&gpio_bar);
gpio_bar &= ~0x3F;
crp = devm_kzalloc(&pdev->dev, sizeof(*crp), GFP_KERNEL);
if (!crp) {
lcd_device_unregister(ldp);
backlight_device_unregister(bdp);
pci_dev_put(lpc_dev);
return -ENOMEM;
}
crp->cr_backlight_device = bdp;
crp->cr_lcd_device = ldp;
crp->cr_backlight_device->props.power = FB_BLANK_UNBLANK;
crp->cr_backlight_device->props.brightness = 0;
cr_backlight_set_intensity(crp->cr_backlight_device);
cr_lcd_set_power(crp->cr_lcd_device, FB_BLANK_UNBLANK);
platform_set_drvdata(pdev, crp);
return 0;
}
static int cr_backlight_remove(struct platform_device *pdev)
{
struct cr_panel *crp = platform_get_drvdata(pdev);
crp->cr_backlight_device->props.power = FB_BLANK_POWERDOWN;
crp->cr_backlight_device->props.brightness = 0;
crp->cr_backlight_device->props.max_brightness = 0;
cr_backlight_set_intensity(crp->cr_backlight_device);
cr_lcd_set_power(crp->cr_lcd_device, FB_BLANK_POWERDOWN);
backlight_device_unregister(crp->cr_backlight_device);
lcd_device_unregister(crp->cr_lcd_device);
pci_dev_put(lpc_dev);
return 0;
}
static struct platform_driver cr_backlight_driver = {
.probe = cr_backlight_probe,
.remove = cr_backlight_remove,
.driver = {
.name = "cr_backlight",
},
};
static struct platform_device *crp;
static int __init cr_backlight_init(void)
{
int ret = platform_driver_register(&cr_backlight_driver);
if (ret)
return ret;
crp = platform_device_register_simple("cr_backlight", -1, NULL, 0);
if (IS_ERR(crp)) {
platform_driver_unregister(&cr_backlight_driver);
return PTR_ERR(crp);
}
printk("Carillo Ranch Backlight Driver Initialized.\n");
return 0;
}
static void __exit cr_backlight_exit(void)
{
platform_device_unregister(crp);
platform_driver_unregister(&cr_backlight_driver);
}
module_init(cr_backlight_init);
module_exit(cr_backlight_exit);
MODULE_AUTHOR("Tungsten Graphics Inc.");
MODULE_DESCRIPTION("Carillo Ranch Backlight Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
horuscentro/android_kernel_motorola_msm8226 | drivers/isdn/gigaset/i4l.c | 4809 | 18537 | /*
* Stuff used by all variants of the driver
*
* Copyright (c) 2001 by Stefan Eilers,
* Hansjoerg Lipp <hjlipp@web.de>,
* Tilman Schmidt <tilman@imap.cc>.
*
* =====================================================================
* 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 "gigaset.h"
#include <linux/isdnif.h>
#include <linux/export.h>
#define SBUFSIZE 4096 /* sk_buff payload size */
#define TRANSBUFSIZE 768 /* bytes per skb for transparent receive */
#define HW_HDR_LEN 2 /* Header size used to store ack info */
#define MAX_BUF_SIZE (SBUFSIZE - HW_HDR_LEN) /* max data packet from LL */
/* == Handling of I4L IO =====================================================*/
/* writebuf_from_LL
* called by LL to transmit data on an open channel
* inserts the buffer data into the send queue and starts the transmission
* Note that this operation must not sleep!
* When the buffer is processed completely, gigaset_skb_sent() should be called.
* parameters:
* driverID driver ID as assigned by LL
* channel channel number
* ack if != 0 LL wants to be notified on completion via
* statcallb(ISDN_STAT_BSENT)
* skb skb containing data to send
* return value:
* number of accepted bytes
* 0 if temporarily unable to accept data (out of buffer space)
* <0 on error (eg. -EINVAL)
*/
static int writebuf_from_LL(int driverID, int channel, int ack,
struct sk_buff *skb)
{
struct cardstate *cs = gigaset_get_cs_by_id(driverID);
struct bc_state *bcs;
unsigned char *ack_header;
unsigned len;
if (!cs) {
pr_err("%s: invalid driver ID (%d)\n", __func__, driverID);
return -ENODEV;
}
if (channel < 0 || channel >= cs->channels) {
dev_err(cs->dev, "%s: invalid channel ID (%d)\n",
__func__, channel);
return -ENODEV;
}
bcs = &cs->bcs[channel];
/* can only handle linear sk_buffs */
if (skb_linearize(skb) < 0) {
dev_err(cs->dev, "%s: skb_linearize failed\n", __func__);
return -ENOMEM;
}
len = skb->len;
gig_dbg(DEBUG_LLDATA,
"Receiving data from LL (id: %d, ch: %d, ack: %d, sz: %d)",
driverID, channel, ack, len);
if (!len) {
if (ack)
dev_notice(cs->dev, "%s: not ACKing empty packet\n",
__func__);
return 0;
}
if (len > MAX_BUF_SIZE) {
dev_err(cs->dev, "%s: packet too large (%d bytes)\n",
__func__, len);
return -EINVAL;
}
/* set up acknowledgement header */
if (skb_headroom(skb) < HW_HDR_LEN) {
/* should never happen */
dev_err(cs->dev, "%s: insufficient skb headroom\n", __func__);
return -ENOMEM;
}
skb_set_mac_header(skb, -HW_HDR_LEN);
skb->mac_len = HW_HDR_LEN;
ack_header = skb_mac_header(skb);
if (ack) {
ack_header[0] = len & 0xff;
ack_header[1] = len >> 8;
} else {
ack_header[0] = ack_header[1] = 0;
}
gig_dbg(DEBUG_MCMD, "skb: len=%u, ack=%d: %02x %02x",
len, ack, ack_header[0], ack_header[1]);
/* pass to device-specific module */
return cs->ops->send_skb(bcs, skb);
}
/**
* gigaset_skb_sent() - acknowledge sending an skb
* @bcs: B channel descriptor structure.
* @skb: sent data.
*
* Called by hardware module {bas,ser,usb}_gigaset when the data in a
* skb has been successfully sent, for signalling completion to the LL.
*/
void gigaset_skb_sent(struct bc_state *bcs, struct sk_buff *skb)
{
isdn_if *iif = bcs->cs->iif;
unsigned char *ack_header = skb_mac_header(skb);
unsigned len;
isdn_ctrl response;
++bcs->trans_up;
if (skb->len)
dev_warn(bcs->cs->dev, "%s: skb->len==%d\n",
__func__, skb->len);
len = ack_header[0] + ((unsigned) ack_header[1] << 8);
if (len) {
gig_dbg(DEBUG_MCMD, "ACKing to LL (id: %d, ch: %d, sz: %u)",
bcs->cs->myid, bcs->channel, len);
response.driver = bcs->cs->myid;
response.command = ISDN_STAT_BSENT;
response.arg = bcs->channel;
response.parm.length = len;
iif->statcallb(&response);
}
}
EXPORT_SYMBOL_GPL(gigaset_skb_sent);
/**
* gigaset_skb_rcvd() - pass received skb to LL
* @bcs: B channel descriptor structure.
* @skb: received data.
*
* Called by hardware module {bas,ser,usb}_gigaset when user data has
* been successfully received, for passing to the LL.
* Warning: skb must not be accessed anymore!
*/
void gigaset_skb_rcvd(struct bc_state *bcs, struct sk_buff *skb)
{
isdn_if *iif = bcs->cs->iif;
iif->rcvcallb_skb(bcs->cs->myid, bcs->channel, skb);
bcs->trans_down++;
}
EXPORT_SYMBOL_GPL(gigaset_skb_rcvd);
/**
* gigaset_isdn_rcv_err() - signal receive error
* @bcs: B channel descriptor structure.
*
* Called by hardware module {bas,ser,usb}_gigaset when a receive error
* has occurred, for signalling to the LL.
*/
void gigaset_isdn_rcv_err(struct bc_state *bcs)
{
isdn_if *iif = bcs->cs->iif;
isdn_ctrl response;
/* if currently ignoring packets, just count down */
if (bcs->ignore) {
bcs->ignore--;
return;
}
/* update statistics */
bcs->corrupted++;
/* error -> LL */
gig_dbg(DEBUG_CMD, "sending L1ERR");
response.driver = bcs->cs->myid;
response.command = ISDN_STAT_L1ERR;
response.arg = bcs->channel;
response.parm.errcode = ISDN_STAT_L1ERR_RECV;
iif->statcallb(&response);
}
EXPORT_SYMBOL_GPL(gigaset_isdn_rcv_err);
/* This function will be called by LL to send commands
* NOTE: LL ignores the returned value, for commands other than ISDN_CMD_IOCTL,
* so don't put too much effort into it.
*/
static int command_from_LL(isdn_ctrl *cntrl)
{
struct cardstate *cs;
struct bc_state *bcs;
int retval = 0;
char **commands;
int ch;
int i;
size_t l;
gig_dbg(DEBUG_CMD, "driver: %d, command: %d, arg: 0x%lx",
cntrl->driver, cntrl->command, cntrl->arg);
cs = gigaset_get_cs_by_id(cntrl->driver);
if (cs == NULL) {
pr_err("%s: invalid driver ID (%d)\n", __func__, cntrl->driver);
return -ENODEV;
}
ch = cntrl->arg & 0xff;
switch (cntrl->command) {
case ISDN_CMD_IOCTL:
dev_warn(cs->dev, "ISDN_CMD_IOCTL not supported\n");
return -EINVAL;
case ISDN_CMD_DIAL:
gig_dbg(DEBUG_CMD,
"ISDN_CMD_DIAL (phone: %s, msn: %s, si1: %d, si2: %d)",
cntrl->parm.setup.phone, cntrl->parm.setup.eazmsn,
cntrl->parm.setup.si1, cntrl->parm.setup.si2);
if (ch >= cs->channels) {
dev_err(cs->dev,
"ISDN_CMD_DIAL: invalid channel (%d)\n", ch);
return -EINVAL;
}
bcs = cs->bcs + ch;
if (!gigaset_get_channel(bcs)) {
dev_err(cs->dev, "ISDN_CMD_DIAL: channel not free\n");
return -EBUSY;
}
switch (bcs->proto2) {
case L2_HDLC:
bcs->rx_bufsize = SBUFSIZE;
break;
default: /* assume transparent */
bcs->rx_bufsize = TRANSBUFSIZE;
}
dev_kfree_skb(bcs->rx_skb);
gigaset_new_rx_skb(bcs);
commands = kzalloc(AT_NUM * (sizeof *commands), GFP_ATOMIC);
if (!commands) {
gigaset_free_channel(bcs);
dev_err(cs->dev, "ISDN_CMD_DIAL: out of memory\n");
return -ENOMEM;
}
l = 3 + strlen(cntrl->parm.setup.phone);
commands[AT_DIAL] = kmalloc(l, GFP_ATOMIC);
if (!commands[AT_DIAL])
goto oom;
if (cntrl->parm.setup.phone[0] == '*' &&
cntrl->parm.setup.phone[1] == '*') {
/* internal call: translate ** prefix to CTP value */
commands[AT_TYPE] = kstrdup("^SCTP=0\r", GFP_ATOMIC);
if (!commands[AT_TYPE])
goto oom;
snprintf(commands[AT_DIAL], l,
"D%s\r", cntrl->parm.setup.phone + 2);
} else {
commands[AT_TYPE] = kstrdup("^SCTP=1\r", GFP_ATOMIC);
if (!commands[AT_TYPE])
goto oom;
snprintf(commands[AT_DIAL], l,
"D%s\r", cntrl->parm.setup.phone);
}
l = strlen(cntrl->parm.setup.eazmsn);
if (l) {
l += 8;
commands[AT_MSN] = kmalloc(l, GFP_ATOMIC);
if (!commands[AT_MSN])
goto oom;
snprintf(commands[AT_MSN], l, "^SMSN=%s\r",
cntrl->parm.setup.eazmsn);
}
switch (cntrl->parm.setup.si1) {
case 1: /* audio */
/* BC = 9090A3: 3.1 kHz audio, A-law */
commands[AT_BC] = kstrdup("^SBC=9090A3\r", GFP_ATOMIC);
if (!commands[AT_BC])
goto oom;
break;
case 7: /* data */
default: /* hope the app knows what it is doing */
/* BC = 8890: unrestricted digital information */
commands[AT_BC] = kstrdup("^SBC=8890\r", GFP_ATOMIC);
if (!commands[AT_BC])
goto oom;
}
/* ToDo: other si1 values, inspect si2, set HLC/LLC */
commands[AT_PROTO] = kmalloc(9, GFP_ATOMIC);
if (!commands[AT_PROTO])
goto oom;
snprintf(commands[AT_PROTO], 9, "^SBPR=%u\r", bcs->proto2);
commands[AT_ISO] = kmalloc(9, GFP_ATOMIC);
if (!commands[AT_ISO])
goto oom;
snprintf(commands[AT_ISO], 9, "^SISO=%u\r",
(unsigned) bcs->channel + 1);
if (!gigaset_add_event(cs, &bcs->at_state, EV_DIAL, commands,
bcs->at_state.seq_index, NULL)) {
for (i = 0; i < AT_NUM; ++i)
kfree(commands[i]);
kfree(commands);
gigaset_free_channel(bcs);
return -ENOMEM;
}
gigaset_schedule_event(cs);
break;
case ISDN_CMD_ACCEPTD:
gig_dbg(DEBUG_CMD, "ISDN_CMD_ACCEPTD");
if (ch >= cs->channels) {
dev_err(cs->dev,
"ISDN_CMD_ACCEPTD: invalid channel (%d)\n", ch);
return -EINVAL;
}
bcs = cs->bcs + ch;
switch (bcs->proto2) {
case L2_HDLC:
bcs->rx_bufsize = SBUFSIZE;
break;
default: /* assume transparent */
bcs->rx_bufsize = TRANSBUFSIZE;
}
dev_kfree_skb(bcs->rx_skb);
gigaset_new_rx_skb(bcs);
if (!gigaset_add_event(cs, &bcs->at_state,
EV_ACCEPT, NULL, 0, NULL))
return -ENOMEM;
gigaset_schedule_event(cs);
break;
case ISDN_CMD_HANGUP:
gig_dbg(DEBUG_CMD, "ISDN_CMD_HANGUP");
if (ch >= cs->channels) {
dev_err(cs->dev,
"ISDN_CMD_HANGUP: invalid channel (%d)\n", ch);
return -EINVAL;
}
bcs = cs->bcs + ch;
if (!gigaset_add_event(cs, &bcs->at_state,
EV_HUP, NULL, 0, NULL))
return -ENOMEM;
gigaset_schedule_event(cs);
break;
case ISDN_CMD_CLREAZ: /* Do not signal incoming signals */
dev_info(cs->dev, "ignoring ISDN_CMD_CLREAZ\n");
break;
case ISDN_CMD_SETEAZ: /* Signal incoming calls for given MSN */
dev_info(cs->dev, "ignoring ISDN_CMD_SETEAZ (%s)\n",
cntrl->parm.num);
break;
case ISDN_CMD_SETL2: /* Set L2 to given protocol */
if (ch >= cs->channels) {
dev_err(cs->dev,
"ISDN_CMD_SETL2: invalid channel (%d)\n", ch);
return -EINVAL;
}
bcs = cs->bcs + ch;
if (bcs->chstate & CHS_D_UP) {
dev_err(cs->dev,
"ISDN_CMD_SETL2: channel active (%d)\n", ch);
return -EINVAL;
}
switch (cntrl->arg >> 8) {
case ISDN_PROTO_L2_HDLC:
gig_dbg(DEBUG_CMD, "ISDN_CMD_SETL2: setting L2_HDLC");
bcs->proto2 = L2_HDLC;
break;
case ISDN_PROTO_L2_TRANS:
gig_dbg(DEBUG_CMD, "ISDN_CMD_SETL2: setting L2_VOICE");
bcs->proto2 = L2_VOICE;
break;
default:
dev_err(cs->dev,
"ISDN_CMD_SETL2: unsupported protocol (%lu)\n",
cntrl->arg >> 8);
return -EINVAL;
}
break;
case ISDN_CMD_SETL3: /* Set L3 to given protocol */
gig_dbg(DEBUG_CMD, "ISDN_CMD_SETL3");
if (ch >= cs->channels) {
dev_err(cs->dev,
"ISDN_CMD_SETL3: invalid channel (%d)\n", ch);
return -EINVAL;
}
if (cntrl->arg >> 8 != ISDN_PROTO_L3_TRANS) {
dev_err(cs->dev,
"ISDN_CMD_SETL3: unsupported protocol (%lu)\n",
cntrl->arg >> 8);
return -EINVAL;
}
break;
default:
gig_dbg(DEBUG_CMD, "unknown command %d from LL",
cntrl->command);
return -EINVAL;
}
return retval;
oom:
dev_err(bcs->cs->dev, "out of memory\n");
for (i = 0; i < AT_NUM; ++i)
kfree(commands[i]);
kfree(commands);
gigaset_free_channel(bcs);
return -ENOMEM;
}
static void gigaset_i4l_cmd(struct cardstate *cs, int cmd)
{
isdn_if *iif = cs->iif;
isdn_ctrl command;
command.driver = cs->myid;
command.command = cmd;
command.arg = 0;
iif->statcallb(&command);
}
static void gigaset_i4l_channel_cmd(struct bc_state *bcs, int cmd)
{
isdn_if *iif = bcs->cs->iif;
isdn_ctrl command;
command.driver = bcs->cs->myid;
command.command = cmd;
command.arg = bcs->channel;
iif->statcallb(&command);
}
/**
* gigaset_isdn_icall() - signal incoming call
* @at_state: connection state structure.
*
* Called by main module to notify the LL that an incoming call has been
* received. @at_state contains the parameters of the call.
*
* Return value: call disposition (ICALL_*)
*/
int gigaset_isdn_icall(struct at_state_t *at_state)
{
struct cardstate *cs = at_state->cs;
struct bc_state *bcs = at_state->bcs;
isdn_if *iif = cs->iif;
isdn_ctrl response;
int retval;
/* fill ICALL structure */
response.parm.setup.si1 = 0; /* default: unknown */
response.parm.setup.si2 = 0;
response.parm.setup.screen = 0;
response.parm.setup.plan = 0;
if (!at_state->str_var[STR_ZBC]) {
/* no BC (internal call): assume speech, A-law */
response.parm.setup.si1 = 1;
} else if (!strcmp(at_state->str_var[STR_ZBC], "8890")) {
/* unrestricted digital information */
response.parm.setup.si1 = 7;
} else if (!strcmp(at_state->str_var[STR_ZBC], "8090A3")) {
/* speech, A-law */
response.parm.setup.si1 = 1;
} else if (!strcmp(at_state->str_var[STR_ZBC], "9090A3")) {
/* 3,1 kHz audio, A-law */
response.parm.setup.si1 = 1;
response.parm.setup.si2 = 2;
} else {
dev_warn(cs->dev, "RING ignored - unsupported BC %s\n",
at_state->str_var[STR_ZBC]);
return ICALL_IGNORE;
}
if (at_state->str_var[STR_NMBR]) {
strlcpy(response.parm.setup.phone, at_state->str_var[STR_NMBR],
sizeof response.parm.setup.phone);
} else
response.parm.setup.phone[0] = 0;
if (at_state->str_var[STR_ZCPN]) {
strlcpy(response.parm.setup.eazmsn, at_state->str_var[STR_ZCPN],
sizeof response.parm.setup.eazmsn);
} else
response.parm.setup.eazmsn[0] = 0;
if (!bcs) {
dev_notice(cs->dev, "no channel for incoming call\n");
response.command = ISDN_STAT_ICALLW;
response.arg = 0;
} else {
gig_dbg(DEBUG_CMD, "Sending ICALL");
response.command = ISDN_STAT_ICALL;
response.arg = bcs->channel;
}
response.driver = cs->myid;
retval = iif->statcallb(&response);
gig_dbg(DEBUG_CMD, "Response: %d", retval);
switch (retval) {
case 0: /* no takers */
return ICALL_IGNORE;
case 1: /* alerting */
bcs->chstate |= CHS_NOTIFY_LL;
return ICALL_ACCEPT;
case 2: /* reject */
return ICALL_REJECT;
case 3: /* incomplete */
dev_warn(cs->dev,
"LL requested unsupported feature: Incomplete Number\n");
return ICALL_IGNORE;
case 4: /* proceeding */
/* Gigaset will send ALERTING anyway.
* There doesn't seem to be a way to avoid this.
*/
return ICALL_ACCEPT;
case 5: /* deflect */
dev_warn(cs->dev,
"LL requested unsupported feature: Call Deflection\n");
return ICALL_IGNORE;
default:
dev_err(cs->dev, "LL error %d on ICALL\n", retval);
return ICALL_IGNORE;
}
}
/**
* gigaset_isdn_connD() - signal D channel connect
* @bcs: B channel descriptor structure.
*
* Called by main module to notify the LL that the D channel connection has
* been established.
*/
void gigaset_isdn_connD(struct bc_state *bcs)
{
gig_dbg(DEBUG_CMD, "sending DCONN");
gigaset_i4l_channel_cmd(bcs, ISDN_STAT_DCONN);
}
/**
* gigaset_isdn_hupD() - signal D channel hangup
* @bcs: B channel descriptor structure.
*
* Called by main module to notify the LL that the D channel connection has
* been shut down.
*/
void gigaset_isdn_hupD(struct bc_state *bcs)
{
gig_dbg(DEBUG_CMD, "sending DHUP");
gigaset_i4l_channel_cmd(bcs, ISDN_STAT_DHUP);
}
/**
* gigaset_isdn_connB() - signal B channel connect
* @bcs: B channel descriptor structure.
*
* Called by main module to notify the LL that the B channel connection has
* been established.
*/
void gigaset_isdn_connB(struct bc_state *bcs)
{
gig_dbg(DEBUG_CMD, "sending BCONN");
gigaset_i4l_channel_cmd(bcs, ISDN_STAT_BCONN);
}
/**
* gigaset_isdn_hupB() - signal B channel hangup
* @bcs: B channel descriptor structure.
*
* Called by main module to notify the LL that the B channel connection has
* been shut down.
*/
void gigaset_isdn_hupB(struct bc_state *bcs)
{
gig_dbg(DEBUG_CMD, "sending BHUP");
gigaset_i4l_channel_cmd(bcs, ISDN_STAT_BHUP);
}
/**
* gigaset_isdn_start() - signal device availability
* @cs: device descriptor structure.
*
* Called by main module to notify the LL that the device is available for
* use.
*/
void gigaset_isdn_start(struct cardstate *cs)
{
gig_dbg(DEBUG_CMD, "sending RUN");
gigaset_i4l_cmd(cs, ISDN_STAT_RUN);
}
/**
* gigaset_isdn_stop() - signal device unavailability
* @cs: device descriptor structure.
*
* Called by main module to notify the LL that the device is no longer
* available for use.
*/
void gigaset_isdn_stop(struct cardstate *cs)
{
gig_dbg(DEBUG_CMD, "sending STOP");
gigaset_i4l_cmd(cs, ISDN_STAT_STOP);
}
/**
* gigaset_isdn_regdev() - register to LL
* @cs: device descriptor structure.
* @isdnid: device name.
*
* Return value: 1 for success, 0 for failure
*/
int gigaset_isdn_regdev(struct cardstate *cs, const char *isdnid)
{
isdn_if *iif;
iif = kmalloc(sizeof *iif, GFP_KERNEL);
if (!iif) {
pr_err("out of memory\n");
return 0;
}
if (snprintf(iif->id, sizeof iif->id, "%s_%u", isdnid, cs->minor_index)
>= sizeof iif->id) {
pr_err("ID too long: %s\n", isdnid);
kfree(iif);
return 0;
}
iif->owner = THIS_MODULE;
iif->channels = cs->channels;
iif->maxbufsize = MAX_BUF_SIZE;
iif->features = ISDN_FEATURE_L2_TRANS |
ISDN_FEATURE_L2_HDLC |
ISDN_FEATURE_L2_X75I |
ISDN_FEATURE_L3_TRANS |
ISDN_FEATURE_P_EURO;
iif->hl_hdrlen = HW_HDR_LEN; /* Area for storing ack */
iif->command = command_from_LL;
iif->writebuf_skb = writebuf_from_LL;
iif->writecmd = NULL; /* Don't support isdnctrl */
iif->readstat = NULL; /* Don't support isdnctrl */
iif->rcvcallb_skb = NULL; /* Will be set by LL */
iif->statcallb = NULL; /* Will be set by LL */
if (!register_isdn(iif)) {
pr_err("register_isdn failed\n");
kfree(iif);
return 0;
}
cs->iif = iif;
cs->myid = iif->channels; /* Set my device id */
cs->hw_hdr_len = HW_HDR_LEN;
return 1;
}
/**
* gigaset_isdn_unregdev() - unregister device from LL
* @cs: device descriptor structure.
*/
void gigaset_isdn_unregdev(struct cardstate *cs)
{
gig_dbg(DEBUG_CMD, "sending UNLOAD");
gigaset_i4l_cmd(cs, ISDN_STAT_UNLOAD);
kfree(cs->iif);
cs->iif = NULL;
}
/**
* gigaset_isdn_regdrv() - register driver to LL
*/
void gigaset_isdn_regdrv(void)
{
pr_info("ISDN4Linux interface\n");
/* nothing to do */
}
/**
* gigaset_isdn_unregdrv() - unregister driver from LL
*/
void gigaset_isdn_unregdrv(void)
{
/* nothing to do */
}
| gpl-2.0 |
xiaolvmu/villec2-kernel | fs/xfs/xfs_attr.c | 4809 | 56695 | /*
* Copyright (c) 2000-2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_da_btree.h"
#include "xfs_bmap_btree.h"
#include "xfs_attr_sf.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_alloc.h"
#include "xfs_inode_item.h"
#include "xfs_bmap.h"
#include "xfs_attr.h"
#include "xfs_attr_leaf.h"
#include "xfs_error.h"
#include "xfs_quota.h"
#include "xfs_trans_space.h"
#include "xfs_rw.h"
#include "xfs_vnodeops.h"
#include "xfs_trace.h"
/*
* xfs_attr.c
*
* Provide the external interfaces to manage attribute lists.
*/
/*========================================================================
* Function prototypes for the kernel.
*========================================================================*/
/*
* Internal routines when attribute list fits inside the inode.
*/
STATIC int xfs_attr_shortform_addname(xfs_da_args_t *args);
/*
* Internal routines when attribute list is one block.
*/
STATIC int xfs_attr_leaf_get(xfs_da_args_t *args);
STATIC int xfs_attr_leaf_addname(xfs_da_args_t *args);
STATIC int xfs_attr_leaf_removename(xfs_da_args_t *args);
STATIC int xfs_attr_leaf_list(xfs_attr_list_context_t *context);
/*
* Internal routines when attribute list is more than one block.
*/
STATIC int xfs_attr_node_get(xfs_da_args_t *args);
STATIC int xfs_attr_node_addname(xfs_da_args_t *args);
STATIC int xfs_attr_node_removename(xfs_da_args_t *args);
STATIC int xfs_attr_node_list(xfs_attr_list_context_t *context);
STATIC int xfs_attr_fillstate(xfs_da_state_t *state);
STATIC int xfs_attr_refillstate(xfs_da_state_t *state);
/*
* Routines to manipulate out-of-line attribute values.
*/
STATIC int xfs_attr_rmtval_set(xfs_da_args_t *args);
STATIC int xfs_attr_rmtval_remove(xfs_da_args_t *args);
#define ATTR_RMTVALUE_MAPSIZE 1 /* # of map entries at once */
STATIC int
xfs_attr_name_to_xname(
struct xfs_name *xname,
const unsigned char *aname)
{
if (!aname)
return EINVAL;
xname->name = aname;
xname->len = strlen((char *)aname);
if (xname->len >= MAXNAMELEN)
return EFAULT; /* match IRIX behaviour */
return 0;
}
STATIC int
xfs_inode_hasattr(
struct xfs_inode *ip)
{
if (!XFS_IFORK_Q(ip) ||
(ip->i_d.di_aformat == XFS_DINODE_FMT_EXTENTS &&
ip->i_d.di_anextents == 0))
return 0;
return 1;
}
/*========================================================================
* Overall external interface routines.
*========================================================================*/
STATIC int
xfs_attr_get_int(
struct xfs_inode *ip,
struct xfs_name *name,
unsigned char *value,
int *valuelenp,
int flags)
{
xfs_da_args_t args;
int error;
if (!xfs_inode_hasattr(ip))
return ENOATTR;
/*
* Fill in the arg structure for this request.
*/
memset((char *)&args, 0, sizeof(args));
args.name = name->name;
args.namelen = name->len;
args.value = value;
args.valuelen = *valuelenp;
args.flags = flags;
args.hashval = xfs_da_hashname(args.name, args.namelen);
args.dp = ip;
args.whichfork = XFS_ATTR_FORK;
/*
* Decide on what work routines to call based on the inode size.
*/
if (ip->i_d.di_aformat == XFS_DINODE_FMT_LOCAL) {
error = xfs_attr_shortform_getvalue(&args);
} else if (xfs_bmap_one_block(ip, XFS_ATTR_FORK)) {
error = xfs_attr_leaf_get(&args);
} else {
error = xfs_attr_node_get(&args);
}
/*
* Return the number of bytes in the value to the caller.
*/
*valuelenp = args.valuelen;
if (error == EEXIST)
error = 0;
return(error);
}
int
xfs_attr_get(
xfs_inode_t *ip,
const unsigned char *name,
unsigned char *value,
int *valuelenp,
int flags)
{
int error;
struct xfs_name xname;
XFS_STATS_INC(xs_attr_get);
if (XFS_FORCED_SHUTDOWN(ip->i_mount))
return(EIO);
error = xfs_attr_name_to_xname(&xname, name);
if (error)
return error;
xfs_ilock(ip, XFS_ILOCK_SHARED);
error = xfs_attr_get_int(ip, &xname, value, valuelenp, flags);
xfs_iunlock(ip, XFS_ILOCK_SHARED);
return(error);
}
/*
* Calculate how many blocks we need for the new attribute,
*/
STATIC int
xfs_attr_calc_size(
struct xfs_inode *ip,
int namelen,
int valuelen,
int *local)
{
struct xfs_mount *mp = ip->i_mount;
int size;
int nblks;
/*
* Determine space new attribute will use, and if it would be
* "local" or "remote" (note: local != inline).
*/
size = xfs_attr_leaf_newentsize(namelen, valuelen,
mp->m_sb.sb_blocksize, local);
nblks = XFS_DAENTER_SPACE_RES(mp, XFS_ATTR_FORK);
if (*local) {
if (size > (mp->m_sb.sb_blocksize >> 1)) {
/* Double split possible */
nblks *= 2;
}
} else {
/*
* Out of line attribute, cannot double split, but
* make room for the attribute value itself.
*/
uint dblocks = XFS_B_TO_FSB(mp, valuelen);
nblks += dblocks;
nblks += XFS_NEXTENTADD_SPACE_RES(mp, dblocks, XFS_ATTR_FORK);
}
return nblks;
}
STATIC int
xfs_attr_set_int(
struct xfs_inode *dp,
struct xfs_name *name,
unsigned char *value,
int valuelen,
int flags)
{
xfs_da_args_t args;
xfs_fsblock_t firstblock;
xfs_bmap_free_t flist;
int error, err2, committed;
xfs_mount_t *mp = dp->i_mount;
int rsvd = (flags & ATTR_ROOT) != 0;
int local;
/*
* Attach the dquots to the inode.
*/
error = xfs_qm_dqattach(dp, 0);
if (error)
return error;
/*
* If the inode doesn't have an attribute fork, add one.
* (inode must not be locked when we call this routine)
*/
if (XFS_IFORK_Q(dp) == 0) {
int sf_size = sizeof(xfs_attr_sf_hdr_t) +
XFS_ATTR_SF_ENTSIZE_BYNAME(name->len, valuelen);
if ((error = xfs_bmap_add_attrfork(dp, sf_size, rsvd)))
return(error);
}
/*
* Fill in the arg structure for this request.
*/
memset((char *)&args, 0, sizeof(args));
args.name = name->name;
args.namelen = name->len;
args.value = value;
args.valuelen = valuelen;
args.flags = flags;
args.hashval = xfs_da_hashname(args.name, args.namelen);
args.dp = dp;
args.firstblock = &firstblock;
args.flist = &flist;
args.whichfork = XFS_ATTR_FORK;
args.op_flags = XFS_DA_OP_ADDNAME | XFS_DA_OP_OKNOENT;
/* Size is now blocks for attribute data */
args.total = xfs_attr_calc_size(dp, name->len, valuelen, &local);
/*
* Start our first transaction of the day.
*
* All future transactions during this code must be "chained" off
* this one via the trans_dup() call. All transactions will contain
* the inode, and the inode will always be marked with trans_ihold().
* Since the inode will be locked in all transactions, we must log
* the inode in every transaction to let it float upward through
* the log.
*/
args.trans = xfs_trans_alloc(mp, XFS_TRANS_ATTR_SET);
/*
* Root fork attributes can use reserved data blocks for this
* operation if necessary
*/
if (rsvd)
args.trans->t_flags |= XFS_TRANS_RESERVE;
if ((error = xfs_trans_reserve(args.trans, args.total,
XFS_ATTRSET_LOG_RES(mp, args.total), 0,
XFS_TRANS_PERM_LOG_RES, XFS_ATTRSET_LOG_COUNT))) {
xfs_trans_cancel(args.trans, 0);
return(error);
}
xfs_ilock(dp, XFS_ILOCK_EXCL);
error = xfs_trans_reserve_quota_nblks(args.trans, dp, args.total, 0,
rsvd ? XFS_QMOPT_RES_REGBLKS | XFS_QMOPT_FORCE_RES :
XFS_QMOPT_RES_REGBLKS);
if (error) {
xfs_iunlock(dp, XFS_ILOCK_EXCL);
xfs_trans_cancel(args.trans, XFS_TRANS_RELEASE_LOG_RES);
return (error);
}
xfs_trans_ijoin(args.trans, dp, 0);
/*
* If the attribute list is non-existent or a shortform list,
* upgrade it to a single-leaf-block attribute list.
*/
if ((dp->i_d.di_aformat == XFS_DINODE_FMT_LOCAL) ||
((dp->i_d.di_aformat == XFS_DINODE_FMT_EXTENTS) &&
(dp->i_d.di_anextents == 0))) {
/*
* Build initial attribute list (if required).
*/
if (dp->i_d.di_aformat == XFS_DINODE_FMT_EXTENTS)
xfs_attr_shortform_create(&args);
/*
* Try to add the attr to the attribute list in
* the inode.
*/
error = xfs_attr_shortform_addname(&args);
if (error != ENOSPC) {
/*
* Commit the shortform mods, and we're done.
* NOTE: this is also the error path (EEXIST, etc).
*/
ASSERT(args.trans != NULL);
/*
* If this is a synchronous mount, make sure that
* the transaction goes to disk before returning
* to the user.
*/
if (mp->m_flags & XFS_MOUNT_WSYNC) {
xfs_trans_set_sync(args.trans);
}
if (!error && (flags & ATTR_KERNOTIME) == 0) {
xfs_trans_ichgtime(args.trans, dp,
XFS_ICHGTIME_CHG);
}
err2 = xfs_trans_commit(args.trans,
XFS_TRANS_RELEASE_LOG_RES);
xfs_iunlock(dp, XFS_ILOCK_EXCL);
return(error == 0 ? err2 : error);
}
/*
* It won't fit in the shortform, transform to a leaf block.
* GROT: another possible req'mt for a double-split btree op.
*/
xfs_bmap_init(args.flist, args.firstblock);
error = xfs_attr_shortform_to_leaf(&args);
if (!error) {
error = xfs_bmap_finish(&args.trans, args.flist,
&committed);
}
if (error) {
ASSERT(committed);
args.trans = NULL;
xfs_bmap_cancel(&flist);
goto out;
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args.trans, dp, 0);
/*
* Commit the leaf transformation. We'll need another (linked)
* transaction to add the new attribute to the leaf.
*/
error = xfs_trans_roll(&args.trans, dp);
if (error)
goto out;
}
if (xfs_bmap_one_block(dp, XFS_ATTR_FORK)) {
error = xfs_attr_leaf_addname(&args);
} else {
error = xfs_attr_node_addname(&args);
}
if (error) {
goto out;
}
/*
* If this is a synchronous mount, make sure that the
* transaction goes to disk before returning to the user.
*/
if (mp->m_flags & XFS_MOUNT_WSYNC) {
xfs_trans_set_sync(args.trans);
}
if ((flags & ATTR_KERNOTIME) == 0)
xfs_trans_ichgtime(args.trans, dp, XFS_ICHGTIME_CHG);
/*
* Commit the last in the sequence of transactions.
*/
xfs_trans_log_inode(args.trans, dp, XFS_ILOG_CORE);
error = xfs_trans_commit(args.trans, XFS_TRANS_RELEASE_LOG_RES);
xfs_iunlock(dp, XFS_ILOCK_EXCL);
return(error);
out:
if (args.trans)
xfs_trans_cancel(args.trans,
XFS_TRANS_RELEASE_LOG_RES|XFS_TRANS_ABORT);
xfs_iunlock(dp, XFS_ILOCK_EXCL);
return(error);
}
int
xfs_attr_set(
xfs_inode_t *dp,
const unsigned char *name,
unsigned char *value,
int valuelen,
int flags)
{
int error;
struct xfs_name xname;
XFS_STATS_INC(xs_attr_set);
if (XFS_FORCED_SHUTDOWN(dp->i_mount))
return (EIO);
error = xfs_attr_name_to_xname(&xname, name);
if (error)
return error;
return xfs_attr_set_int(dp, &xname, value, valuelen, flags);
}
/*
* Generic handler routine to remove a name from an attribute list.
* Transitions attribute list from Btree to shortform as necessary.
*/
STATIC int
xfs_attr_remove_int(xfs_inode_t *dp, struct xfs_name *name, int flags)
{
xfs_da_args_t args;
xfs_fsblock_t firstblock;
xfs_bmap_free_t flist;
int error;
xfs_mount_t *mp = dp->i_mount;
/*
* Fill in the arg structure for this request.
*/
memset((char *)&args, 0, sizeof(args));
args.name = name->name;
args.namelen = name->len;
args.flags = flags;
args.hashval = xfs_da_hashname(args.name, args.namelen);
args.dp = dp;
args.firstblock = &firstblock;
args.flist = &flist;
args.total = 0;
args.whichfork = XFS_ATTR_FORK;
/*
* we have no control over the attribute names that userspace passes us
* to remove, so we have to allow the name lookup prior to attribute
* removal to fail.
*/
args.op_flags = XFS_DA_OP_OKNOENT;
/*
* Attach the dquots to the inode.
*/
error = xfs_qm_dqattach(dp, 0);
if (error)
return error;
/*
* Start our first transaction of the day.
*
* All future transactions during this code must be "chained" off
* this one via the trans_dup() call. All transactions will contain
* the inode, and the inode will always be marked with trans_ihold().
* Since the inode will be locked in all transactions, we must log
* the inode in every transaction to let it float upward through
* the log.
*/
args.trans = xfs_trans_alloc(mp, XFS_TRANS_ATTR_RM);
/*
* Root fork attributes can use reserved data blocks for this
* operation if necessary
*/
if (flags & ATTR_ROOT)
args.trans->t_flags |= XFS_TRANS_RESERVE;
if ((error = xfs_trans_reserve(args.trans,
XFS_ATTRRM_SPACE_RES(mp),
XFS_ATTRRM_LOG_RES(mp),
0, XFS_TRANS_PERM_LOG_RES,
XFS_ATTRRM_LOG_COUNT))) {
xfs_trans_cancel(args.trans, 0);
return(error);
}
xfs_ilock(dp, XFS_ILOCK_EXCL);
/*
* No need to make quota reservations here. We expect to release some
* blocks not allocate in the common case.
*/
xfs_trans_ijoin(args.trans, dp, 0);
/*
* Decide on what work routines to call based on the inode size.
*/
if (!xfs_inode_hasattr(dp)) {
error = XFS_ERROR(ENOATTR);
goto out;
}
if (dp->i_d.di_aformat == XFS_DINODE_FMT_LOCAL) {
ASSERT(dp->i_afp->if_flags & XFS_IFINLINE);
error = xfs_attr_shortform_remove(&args);
if (error) {
goto out;
}
} else if (xfs_bmap_one_block(dp, XFS_ATTR_FORK)) {
error = xfs_attr_leaf_removename(&args);
} else {
error = xfs_attr_node_removename(&args);
}
if (error) {
goto out;
}
/*
* If this is a synchronous mount, make sure that the
* transaction goes to disk before returning to the user.
*/
if (mp->m_flags & XFS_MOUNT_WSYNC) {
xfs_trans_set_sync(args.trans);
}
if ((flags & ATTR_KERNOTIME) == 0)
xfs_trans_ichgtime(args.trans, dp, XFS_ICHGTIME_CHG);
/*
* Commit the last in the sequence of transactions.
*/
xfs_trans_log_inode(args.trans, dp, XFS_ILOG_CORE);
error = xfs_trans_commit(args.trans, XFS_TRANS_RELEASE_LOG_RES);
xfs_iunlock(dp, XFS_ILOCK_EXCL);
return(error);
out:
if (args.trans)
xfs_trans_cancel(args.trans,
XFS_TRANS_RELEASE_LOG_RES|XFS_TRANS_ABORT);
xfs_iunlock(dp, XFS_ILOCK_EXCL);
return(error);
}
int
xfs_attr_remove(
xfs_inode_t *dp,
const unsigned char *name,
int flags)
{
int error;
struct xfs_name xname;
XFS_STATS_INC(xs_attr_remove);
if (XFS_FORCED_SHUTDOWN(dp->i_mount))
return (EIO);
error = xfs_attr_name_to_xname(&xname, name);
if (error)
return error;
xfs_ilock(dp, XFS_ILOCK_SHARED);
if (!xfs_inode_hasattr(dp)) {
xfs_iunlock(dp, XFS_ILOCK_SHARED);
return XFS_ERROR(ENOATTR);
}
xfs_iunlock(dp, XFS_ILOCK_SHARED);
return xfs_attr_remove_int(dp, &xname, flags);
}
int
xfs_attr_list_int(xfs_attr_list_context_t *context)
{
int error;
xfs_inode_t *dp = context->dp;
XFS_STATS_INC(xs_attr_list);
if (XFS_FORCED_SHUTDOWN(dp->i_mount))
return EIO;
xfs_ilock(dp, XFS_ILOCK_SHARED);
/*
* Decide on what work routines to call based on the inode size.
*/
if (!xfs_inode_hasattr(dp)) {
error = 0;
} else if (dp->i_d.di_aformat == XFS_DINODE_FMT_LOCAL) {
error = xfs_attr_shortform_list(context);
} else if (xfs_bmap_one_block(dp, XFS_ATTR_FORK)) {
error = xfs_attr_leaf_list(context);
} else {
error = xfs_attr_node_list(context);
}
xfs_iunlock(dp, XFS_ILOCK_SHARED);
return error;
}
#define ATTR_ENTBASESIZE /* minimum bytes used by an attr */ \
(((struct attrlist_ent *) 0)->a_name - (char *) 0)
#define ATTR_ENTSIZE(namelen) /* actual bytes used by an attr */ \
((ATTR_ENTBASESIZE + (namelen) + 1 + sizeof(u_int32_t)-1) \
& ~(sizeof(u_int32_t)-1))
/*
* Format an attribute and copy it out to the user's buffer.
* Take care to check values and protect against them changing later,
* we may be reading them directly out of a user buffer.
*/
/*ARGSUSED*/
STATIC int
xfs_attr_put_listent(
xfs_attr_list_context_t *context,
int flags,
unsigned char *name,
int namelen,
int valuelen,
unsigned char *value)
{
struct attrlist *alist = (struct attrlist *)context->alist;
attrlist_ent_t *aep;
int arraytop;
ASSERT(!(context->flags & ATTR_KERNOVAL));
ASSERT(context->count >= 0);
ASSERT(context->count < (ATTR_MAX_VALUELEN/8));
ASSERT(context->firstu >= sizeof(*alist));
ASSERT(context->firstu <= context->bufsize);
/*
* Only list entries in the right namespace.
*/
if (((context->flags & ATTR_SECURE) == 0) !=
((flags & XFS_ATTR_SECURE) == 0))
return 0;
if (((context->flags & ATTR_ROOT) == 0) !=
((flags & XFS_ATTR_ROOT) == 0))
return 0;
arraytop = sizeof(*alist) +
context->count * sizeof(alist->al_offset[0]);
context->firstu -= ATTR_ENTSIZE(namelen);
if (context->firstu < arraytop) {
trace_xfs_attr_list_full(context);
alist->al_more = 1;
context->seen_enough = 1;
return 1;
}
aep = (attrlist_ent_t *)&context->alist[context->firstu];
aep->a_valuelen = valuelen;
memcpy(aep->a_name, name, namelen);
aep->a_name[namelen] = 0;
alist->al_offset[context->count++] = context->firstu;
alist->al_count = context->count;
trace_xfs_attr_list_add(context);
return 0;
}
/*
* Generate a list of extended attribute names and optionally
* also value lengths. Positive return value follows the XFS
* convention of being an error, zero or negative return code
* is the length of the buffer returned (negated), indicating
* success.
*/
int
xfs_attr_list(
xfs_inode_t *dp,
char *buffer,
int bufsize,
int flags,
attrlist_cursor_kern_t *cursor)
{
xfs_attr_list_context_t context;
struct attrlist *alist;
int error;
/*
* Validate the cursor.
*/
if (cursor->pad1 || cursor->pad2)
return(XFS_ERROR(EINVAL));
if ((cursor->initted == 0) &&
(cursor->hashval || cursor->blkno || cursor->offset))
return XFS_ERROR(EINVAL);
/*
* Check for a properly aligned buffer.
*/
if (((long)buffer) & (sizeof(int)-1))
return XFS_ERROR(EFAULT);
if (flags & ATTR_KERNOVAL)
bufsize = 0;
/*
* Initialize the output buffer.
*/
memset(&context, 0, sizeof(context));
context.dp = dp;
context.cursor = cursor;
context.resynch = 1;
context.flags = flags;
context.alist = buffer;
context.bufsize = (bufsize & ~(sizeof(int)-1)); /* align */
context.firstu = context.bufsize;
context.put_listent = xfs_attr_put_listent;
alist = (struct attrlist *)context.alist;
alist->al_count = 0;
alist->al_more = 0;
alist->al_offset[0] = context.bufsize;
error = xfs_attr_list_int(&context);
ASSERT(error >= 0);
return error;
}
int /* error */
xfs_attr_inactive(xfs_inode_t *dp)
{
xfs_trans_t *trans;
xfs_mount_t *mp;
int error;
mp = dp->i_mount;
ASSERT(! XFS_NOT_DQATTACHED(mp, dp));
xfs_ilock(dp, XFS_ILOCK_SHARED);
if (!xfs_inode_hasattr(dp) ||
dp->i_d.di_aformat == XFS_DINODE_FMT_LOCAL) {
xfs_iunlock(dp, XFS_ILOCK_SHARED);
return 0;
}
xfs_iunlock(dp, XFS_ILOCK_SHARED);
/*
* Start our first transaction of the day.
*
* All future transactions during this code must be "chained" off
* this one via the trans_dup() call. All transactions will contain
* the inode, and the inode will always be marked with trans_ihold().
* Since the inode will be locked in all transactions, we must log
* the inode in every transaction to let it float upward through
* the log.
*/
trans = xfs_trans_alloc(mp, XFS_TRANS_ATTRINVAL);
if ((error = xfs_trans_reserve(trans, 0, XFS_ATTRINVAL_LOG_RES(mp), 0,
XFS_TRANS_PERM_LOG_RES,
XFS_ATTRINVAL_LOG_COUNT))) {
xfs_trans_cancel(trans, 0);
return(error);
}
xfs_ilock(dp, XFS_ILOCK_EXCL);
/*
* No need to make quota reservations here. We expect to release some
* blocks, not allocate, in the common case.
*/
xfs_trans_ijoin(trans, dp, 0);
/*
* Decide on what work routines to call based on the inode size.
*/
if (!xfs_inode_hasattr(dp) ||
dp->i_d.di_aformat == XFS_DINODE_FMT_LOCAL) {
error = 0;
goto out;
}
error = xfs_attr_root_inactive(&trans, dp);
if (error)
goto out;
error = xfs_itruncate_extents(&trans, dp, XFS_ATTR_FORK, 0);
if (error)
goto out;
error = xfs_trans_commit(trans, XFS_TRANS_RELEASE_LOG_RES);
xfs_iunlock(dp, XFS_ILOCK_EXCL);
return(error);
out:
xfs_trans_cancel(trans, XFS_TRANS_RELEASE_LOG_RES|XFS_TRANS_ABORT);
xfs_iunlock(dp, XFS_ILOCK_EXCL);
return(error);
}
/*========================================================================
* External routines when attribute list is inside the inode
*========================================================================*/
/*
* Add a name to the shortform attribute list structure
* This is the external routine.
*/
STATIC int
xfs_attr_shortform_addname(xfs_da_args_t *args)
{
int newsize, forkoff, retval;
trace_xfs_attr_sf_addname(args);
retval = xfs_attr_shortform_lookup(args);
if ((args->flags & ATTR_REPLACE) && (retval == ENOATTR)) {
return(retval);
} else if (retval == EEXIST) {
if (args->flags & ATTR_CREATE)
return(retval);
retval = xfs_attr_shortform_remove(args);
ASSERT(retval == 0);
}
if (args->namelen >= XFS_ATTR_SF_ENTSIZE_MAX ||
args->valuelen >= XFS_ATTR_SF_ENTSIZE_MAX)
return(XFS_ERROR(ENOSPC));
newsize = XFS_ATTR_SF_TOTSIZE(args->dp);
newsize += XFS_ATTR_SF_ENTSIZE_BYNAME(args->namelen, args->valuelen);
forkoff = xfs_attr_shortform_bytesfit(args->dp, newsize);
if (!forkoff)
return(XFS_ERROR(ENOSPC));
xfs_attr_shortform_add(args, forkoff);
return(0);
}
/*========================================================================
* External routines when attribute list is one block
*========================================================================*/
/*
* Add a name to the leaf attribute list structure
*
* This leaf block cannot have a "remote" value, we only call this routine
* if bmap_one_block() says there is only one block (ie: no remote blks).
*/
STATIC int
xfs_attr_leaf_addname(xfs_da_args_t *args)
{
xfs_inode_t *dp;
xfs_dabuf_t *bp;
int retval, error, committed, forkoff;
trace_xfs_attr_leaf_addname(args);
/*
* Read the (only) block in the attribute list in.
*/
dp = args->dp;
args->blkno = 0;
error = xfs_da_read_buf(args->trans, args->dp, args->blkno, -1, &bp,
XFS_ATTR_FORK);
if (error)
return(error);
ASSERT(bp != NULL);
/*
* Look up the given attribute in the leaf block. Figure out if
* the given flags produce an error or call for an atomic rename.
*/
retval = xfs_attr_leaf_lookup_int(bp, args);
if ((args->flags & ATTR_REPLACE) && (retval == ENOATTR)) {
xfs_da_brelse(args->trans, bp);
return(retval);
} else if (retval == EEXIST) {
if (args->flags & ATTR_CREATE) { /* pure create op */
xfs_da_brelse(args->trans, bp);
return(retval);
}
trace_xfs_attr_leaf_replace(args);
args->op_flags |= XFS_DA_OP_RENAME; /* an atomic rename */
args->blkno2 = args->blkno; /* set 2nd entry info*/
args->index2 = args->index;
args->rmtblkno2 = args->rmtblkno;
args->rmtblkcnt2 = args->rmtblkcnt;
}
/*
* Add the attribute to the leaf block, transitioning to a Btree
* if required.
*/
retval = xfs_attr_leaf_add(bp, args);
xfs_da_buf_done(bp);
if (retval == ENOSPC) {
/*
* Promote the attribute list to the Btree format, then
* Commit that transaction so that the node_addname() call
* can manage its own transactions.
*/
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr_leaf_to_node(args);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
/*
* Commit the current trans (including the inode) and start
* a new one.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
/*
* Fob the whole rest of the problem off on the Btree code.
*/
error = xfs_attr_node_addname(args);
return(error);
}
/*
* Commit the transaction that added the attr name so that
* later routines can manage their own transactions.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
/*
* If there was an out-of-line value, allocate the blocks we
* identified for its storage and copy the value. This is done
* after we create the attribute so that we don't overflow the
* maximum size of a transaction and/or hit a deadlock.
*/
if (args->rmtblkno > 0) {
error = xfs_attr_rmtval_set(args);
if (error)
return(error);
}
/*
* If this is an atomic rename operation, we must "flip" the
* incomplete flags on the "new" and "old" attribute/value pairs
* so that one disappears and one appears atomically. Then we
* must remove the "old" attribute/value pair.
*/
if (args->op_flags & XFS_DA_OP_RENAME) {
/*
* In a separate transaction, set the incomplete flag on the
* "old" attr and clear the incomplete flag on the "new" attr.
*/
error = xfs_attr_leaf_flipflags(args);
if (error)
return(error);
/*
* Dismantle the "old" attribute/value pair by removing
* a "remote" value (if it exists).
*/
args->index = args->index2;
args->blkno = args->blkno2;
args->rmtblkno = args->rmtblkno2;
args->rmtblkcnt = args->rmtblkcnt2;
if (args->rmtblkno) {
error = xfs_attr_rmtval_remove(args);
if (error)
return(error);
}
/*
* Read in the block containing the "old" attr, then
* remove the "old" attr from that block (neat, huh!)
*/
error = xfs_da_read_buf(args->trans, args->dp, args->blkno, -1,
&bp, XFS_ATTR_FORK);
if (error)
return(error);
ASSERT(bp != NULL);
(void)xfs_attr_leaf_remove(bp, args);
/*
* If the result is small enough, shrink it all into the inode.
*/
if ((forkoff = xfs_attr_shortform_allfit(bp, dp))) {
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr_leaf_to_shortform(bp, args, forkoff);
/* bp is gone due to xfs_da_shrink_inode */
if (!error) {
error = xfs_bmap_finish(&args->trans,
args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans
* and started a new one. We need the inode to be
* in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
} else
xfs_da_buf_done(bp);
/*
* Commit the remove and start the next trans in series.
*/
error = xfs_trans_roll(&args->trans, dp);
} else if (args->rmtblkno > 0) {
/*
* Added a "remote" value, just clear the incomplete flag.
*/
error = xfs_attr_leaf_clearflag(args);
}
return(error);
}
/*
* Remove a name from the leaf attribute list structure
*
* This leaf block cannot have a "remote" value, we only call this routine
* if bmap_one_block() says there is only one block (ie: no remote blks).
*/
STATIC int
xfs_attr_leaf_removename(xfs_da_args_t *args)
{
xfs_inode_t *dp;
xfs_dabuf_t *bp;
int error, committed, forkoff;
trace_xfs_attr_leaf_removename(args);
/*
* Remove the attribute.
*/
dp = args->dp;
args->blkno = 0;
error = xfs_da_read_buf(args->trans, args->dp, args->blkno, -1, &bp,
XFS_ATTR_FORK);
if (error) {
return(error);
}
ASSERT(bp != NULL);
error = xfs_attr_leaf_lookup_int(bp, args);
if (error == ENOATTR) {
xfs_da_brelse(args->trans, bp);
return(error);
}
(void)xfs_attr_leaf_remove(bp, args);
/*
* If the result is small enough, shrink it all into the inode.
*/
if ((forkoff = xfs_attr_shortform_allfit(bp, dp))) {
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr_leaf_to_shortform(bp, args, forkoff);
/* bp is gone due to xfs_da_shrink_inode */
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
} else
xfs_da_buf_done(bp);
return(0);
}
/*
* Look up a name in a leaf attribute list structure.
*
* This leaf block cannot have a "remote" value, we only call this routine
* if bmap_one_block() says there is only one block (ie: no remote blks).
*/
STATIC int
xfs_attr_leaf_get(xfs_da_args_t *args)
{
xfs_dabuf_t *bp;
int error;
args->blkno = 0;
error = xfs_da_read_buf(args->trans, args->dp, args->blkno, -1, &bp,
XFS_ATTR_FORK);
if (error)
return(error);
ASSERT(bp != NULL);
error = xfs_attr_leaf_lookup_int(bp, args);
if (error != EEXIST) {
xfs_da_brelse(args->trans, bp);
return(error);
}
error = xfs_attr_leaf_getvalue(bp, args);
xfs_da_brelse(args->trans, bp);
if (!error && (args->rmtblkno > 0) && !(args->flags & ATTR_KERNOVAL)) {
error = xfs_attr_rmtval_get(args);
}
return(error);
}
/*
* Copy out attribute entries for attr_list(), for leaf attribute lists.
*/
STATIC int
xfs_attr_leaf_list(xfs_attr_list_context_t *context)
{
xfs_attr_leafblock_t *leaf;
int error;
xfs_dabuf_t *bp;
context->cursor->blkno = 0;
error = xfs_da_read_buf(NULL, context->dp, 0, -1, &bp, XFS_ATTR_FORK);
if (error)
return XFS_ERROR(error);
ASSERT(bp != NULL);
leaf = bp->data;
if (unlikely(leaf->hdr.info.magic != cpu_to_be16(XFS_ATTR_LEAF_MAGIC))) {
XFS_CORRUPTION_ERROR("xfs_attr_leaf_list", XFS_ERRLEVEL_LOW,
context->dp->i_mount, leaf);
xfs_da_brelse(NULL, bp);
return XFS_ERROR(EFSCORRUPTED);
}
error = xfs_attr_leaf_list_int(bp, context);
xfs_da_brelse(NULL, bp);
return XFS_ERROR(error);
}
/*========================================================================
* External routines when attribute list size > XFS_LBSIZE(mp).
*========================================================================*/
/*
* Add a name to a Btree-format attribute list.
*
* This will involve walking down the Btree, and may involve splitting
* leaf nodes and even splitting intermediate nodes up to and including
* the root node (a special case of an intermediate node).
*
* "Remote" attribute values confuse the issue and atomic rename operations
* add a whole extra layer of confusion on top of that.
*/
STATIC int
xfs_attr_node_addname(xfs_da_args_t *args)
{
xfs_da_state_t *state;
xfs_da_state_blk_t *blk;
xfs_inode_t *dp;
xfs_mount_t *mp;
int committed, retval, error;
trace_xfs_attr_node_addname(args);
/*
* Fill in bucket of arguments/results/context to carry around.
*/
dp = args->dp;
mp = dp->i_mount;
restart:
state = xfs_da_state_alloc();
state->args = args;
state->mp = mp;
state->blocksize = state->mp->m_sb.sb_blocksize;
state->node_ents = state->mp->m_attr_node_ents;
/*
* Search to see if name already exists, and get back a pointer
* to where it should go.
*/
error = xfs_da_node_lookup_int(state, &retval);
if (error)
goto out;
blk = &state->path.blk[ state->path.active-1 ];
ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC);
if ((args->flags & ATTR_REPLACE) && (retval == ENOATTR)) {
goto out;
} else if (retval == EEXIST) {
if (args->flags & ATTR_CREATE)
goto out;
trace_xfs_attr_node_replace(args);
args->op_flags |= XFS_DA_OP_RENAME; /* atomic rename op */
args->blkno2 = args->blkno; /* set 2nd entry info*/
args->index2 = args->index;
args->rmtblkno2 = args->rmtblkno;
args->rmtblkcnt2 = args->rmtblkcnt;
args->rmtblkno = 0;
args->rmtblkcnt = 0;
}
retval = xfs_attr_leaf_add(blk->bp, state->args);
if (retval == ENOSPC) {
if (state->path.active == 1) {
/*
* Its really a single leaf node, but it had
* out-of-line values so it looked like it *might*
* have been a b-tree.
*/
xfs_da_state_free(state);
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr_leaf_to_node(args);
if (!error) {
error = xfs_bmap_finish(&args->trans,
args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
goto out;
}
/*
* bmap_finish() may have committed the last trans
* and started a new one. We need the inode to be
* in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
/*
* Commit the node conversion and start the next
* trans in the chain.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
goto out;
goto restart;
}
/*
* Split as many Btree elements as required.
* This code tracks the new and old attr's location
* in the index/blkno/rmtblkno/rmtblkcnt fields and
* in the index2/blkno2/rmtblkno2/rmtblkcnt2 fields.
*/
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_da_split(state);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
goto out;
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
} else {
/*
* Addition succeeded, update Btree hashvals.
*/
xfs_da_fixhashpath(state, &state->path);
}
/*
* Kill the state structure, we're done with it and need to
* allow the buffers to come back later.
*/
xfs_da_state_free(state);
state = NULL;
/*
* Commit the leaf addition or btree split and start the next
* trans in the chain.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
goto out;
/*
* If there was an out-of-line value, allocate the blocks we
* identified for its storage and copy the value. This is done
* after we create the attribute so that we don't overflow the
* maximum size of a transaction and/or hit a deadlock.
*/
if (args->rmtblkno > 0) {
error = xfs_attr_rmtval_set(args);
if (error)
return(error);
}
/*
* If this is an atomic rename operation, we must "flip" the
* incomplete flags on the "new" and "old" attribute/value pairs
* so that one disappears and one appears atomically. Then we
* must remove the "old" attribute/value pair.
*/
if (args->op_flags & XFS_DA_OP_RENAME) {
/*
* In a separate transaction, set the incomplete flag on the
* "old" attr and clear the incomplete flag on the "new" attr.
*/
error = xfs_attr_leaf_flipflags(args);
if (error)
goto out;
/*
* Dismantle the "old" attribute/value pair by removing
* a "remote" value (if it exists).
*/
args->index = args->index2;
args->blkno = args->blkno2;
args->rmtblkno = args->rmtblkno2;
args->rmtblkcnt = args->rmtblkcnt2;
if (args->rmtblkno) {
error = xfs_attr_rmtval_remove(args);
if (error)
return(error);
}
/*
* Re-find the "old" attribute entry after any split ops.
* The INCOMPLETE flag means that we will find the "old"
* attr, not the "new" one.
*/
args->flags |= XFS_ATTR_INCOMPLETE;
state = xfs_da_state_alloc();
state->args = args;
state->mp = mp;
state->blocksize = state->mp->m_sb.sb_blocksize;
state->node_ents = state->mp->m_attr_node_ents;
state->inleaf = 0;
error = xfs_da_node_lookup_int(state, &retval);
if (error)
goto out;
/*
* Remove the name and update the hashvals in the tree.
*/
blk = &state->path.blk[ state->path.active-1 ];
ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC);
error = xfs_attr_leaf_remove(blk->bp, args);
xfs_da_fixhashpath(state, &state->path);
/*
* Check to see if the tree needs to be collapsed.
*/
if (retval && (state->path.active > 1)) {
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_da_join(state);
if (!error) {
error = xfs_bmap_finish(&args->trans,
args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
goto out;
}
/*
* bmap_finish() may have committed the last trans
* and started a new one. We need the inode to be
* in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
}
/*
* Commit and start the next trans in the chain.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
goto out;
} else if (args->rmtblkno > 0) {
/*
* Added a "remote" value, just clear the incomplete flag.
*/
error = xfs_attr_leaf_clearflag(args);
if (error)
goto out;
}
retval = error = 0;
out:
if (state)
xfs_da_state_free(state);
if (error)
return(error);
return(retval);
}
/*
* Remove a name from a B-tree attribute list.
*
* This will involve walking down the Btree, and may involve joining
* leaf nodes and even joining intermediate nodes up to and including
* the root node (a special case of an intermediate node).
*/
STATIC int
xfs_attr_node_removename(xfs_da_args_t *args)
{
xfs_da_state_t *state;
xfs_da_state_blk_t *blk;
xfs_inode_t *dp;
xfs_dabuf_t *bp;
int retval, error, committed, forkoff;
trace_xfs_attr_node_removename(args);
/*
* Tie a string around our finger to remind us where we are.
*/
dp = args->dp;
state = xfs_da_state_alloc();
state->args = args;
state->mp = dp->i_mount;
state->blocksize = state->mp->m_sb.sb_blocksize;
state->node_ents = state->mp->m_attr_node_ents;
/*
* Search to see if name exists, and get back a pointer to it.
*/
error = xfs_da_node_lookup_int(state, &retval);
if (error || (retval != EEXIST)) {
if (error == 0)
error = retval;
goto out;
}
/*
* If there is an out-of-line value, de-allocate the blocks.
* This is done before we remove the attribute so that we don't
* overflow the maximum size of a transaction and/or hit a deadlock.
*/
blk = &state->path.blk[ state->path.active-1 ];
ASSERT(blk->bp != NULL);
ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC);
if (args->rmtblkno > 0) {
/*
* Fill in disk block numbers in the state structure
* so that we can get the buffers back after we commit
* several transactions in the following calls.
*/
error = xfs_attr_fillstate(state);
if (error)
goto out;
/*
* Mark the attribute as INCOMPLETE, then bunmapi() the
* remote value.
*/
error = xfs_attr_leaf_setflag(args);
if (error)
goto out;
error = xfs_attr_rmtval_remove(args);
if (error)
goto out;
/*
* Refill the state structure with buffers, the prior calls
* released our buffers.
*/
error = xfs_attr_refillstate(state);
if (error)
goto out;
}
/*
* Remove the name and update the hashvals in the tree.
*/
blk = &state->path.blk[ state->path.active-1 ];
ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC);
retval = xfs_attr_leaf_remove(blk->bp, args);
xfs_da_fixhashpath(state, &state->path);
/*
* Check to see if the tree needs to be collapsed.
*/
if (retval && (state->path.active > 1)) {
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_da_join(state);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
goto out;
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
/*
* Commit the Btree join operation and start a new trans.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
goto out;
}
/*
* If the result is small enough, push it all into the inode.
*/
if (xfs_bmap_one_block(dp, XFS_ATTR_FORK)) {
/*
* Have to get rid of the copy of this dabuf in the state.
*/
ASSERT(state->path.active == 1);
ASSERT(state->path.blk[0].bp);
xfs_da_buf_done(state->path.blk[0].bp);
state->path.blk[0].bp = NULL;
error = xfs_da_read_buf(args->trans, args->dp, 0, -1, &bp,
XFS_ATTR_FORK);
if (error)
goto out;
ASSERT((((xfs_attr_leafblock_t *)bp->data)->hdr.info.magic) ==
cpu_to_be16(XFS_ATTR_LEAF_MAGIC));
if ((forkoff = xfs_attr_shortform_allfit(bp, dp))) {
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_attr_leaf_to_shortform(bp, args, forkoff);
/* bp is gone due to xfs_da_shrink_inode */
if (!error) {
error = xfs_bmap_finish(&args->trans,
args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
goto out;
}
/*
* bmap_finish() may have committed the last trans
* and started a new one. We need the inode to be
* in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
} else
xfs_da_brelse(args->trans, bp);
}
error = 0;
out:
xfs_da_state_free(state);
return(error);
}
/*
* Fill in the disk block numbers in the state structure for the buffers
* that are attached to the state structure.
* This is done so that we can quickly reattach ourselves to those buffers
* after some set of transaction commits have released these buffers.
*/
STATIC int
xfs_attr_fillstate(xfs_da_state_t *state)
{
xfs_da_state_path_t *path;
xfs_da_state_blk_t *blk;
int level;
/*
* Roll down the "path" in the state structure, storing the on-disk
* block number for those buffers in the "path".
*/
path = &state->path;
ASSERT((path->active >= 0) && (path->active < XFS_DA_NODE_MAXDEPTH));
for (blk = path->blk, level = 0; level < path->active; blk++, level++) {
if (blk->bp) {
blk->disk_blkno = xfs_da_blkno(blk->bp);
xfs_da_buf_done(blk->bp);
blk->bp = NULL;
} else {
blk->disk_blkno = 0;
}
}
/*
* Roll down the "altpath" in the state structure, storing the on-disk
* block number for those buffers in the "altpath".
*/
path = &state->altpath;
ASSERT((path->active >= 0) && (path->active < XFS_DA_NODE_MAXDEPTH));
for (blk = path->blk, level = 0; level < path->active; blk++, level++) {
if (blk->bp) {
blk->disk_blkno = xfs_da_blkno(blk->bp);
xfs_da_buf_done(blk->bp);
blk->bp = NULL;
} else {
blk->disk_blkno = 0;
}
}
return(0);
}
/*
* Reattach the buffers to the state structure based on the disk block
* numbers stored in the state structure.
* This is done after some set of transaction commits have released those
* buffers from our grip.
*/
STATIC int
xfs_attr_refillstate(xfs_da_state_t *state)
{
xfs_da_state_path_t *path;
xfs_da_state_blk_t *blk;
int level, error;
/*
* Roll down the "path" in the state structure, storing the on-disk
* block number for those buffers in the "path".
*/
path = &state->path;
ASSERT((path->active >= 0) && (path->active < XFS_DA_NODE_MAXDEPTH));
for (blk = path->blk, level = 0; level < path->active; blk++, level++) {
if (blk->disk_blkno) {
error = xfs_da_read_buf(state->args->trans,
state->args->dp,
blk->blkno, blk->disk_blkno,
&blk->bp, XFS_ATTR_FORK);
if (error)
return(error);
} else {
blk->bp = NULL;
}
}
/*
* Roll down the "altpath" in the state structure, storing the on-disk
* block number for those buffers in the "altpath".
*/
path = &state->altpath;
ASSERT((path->active >= 0) && (path->active < XFS_DA_NODE_MAXDEPTH));
for (blk = path->blk, level = 0; level < path->active; blk++, level++) {
if (blk->disk_blkno) {
error = xfs_da_read_buf(state->args->trans,
state->args->dp,
blk->blkno, blk->disk_blkno,
&blk->bp, XFS_ATTR_FORK);
if (error)
return(error);
} else {
blk->bp = NULL;
}
}
return(0);
}
/*
* Look up a filename in a node attribute list.
*
* This routine gets called for any attribute fork that has more than one
* block, ie: both true Btree attr lists and for single-leaf-blocks with
* "remote" values taking up more blocks.
*/
STATIC int
xfs_attr_node_get(xfs_da_args_t *args)
{
xfs_da_state_t *state;
xfs_da_state_blk_t *blk;
int error, retval;
int i;
state = xfs_da_state_alloc();
state->args = args;
state->mp = args->dp->i_mount;
state->blocksize = state->mp->m_sb.sb_blocksize;
state->node_ents = state->mp->m_attr_node_ents;
/*
* Search to see if name exists, and get back a pointer to it.
*/
error = xfs_da_node_lookup_int(state, &retval);
if (error) {
retval = error;
} else if (retval == EEXIST) {
blk = &state->path.blk[ state->path.active-1 ];
ASSERT(blk->bp != NULL);
ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC);
/*
* Get the value, local or "remote"
*/
retval = xfs_attr_leaf_getvalue(blk->bp, args);
if (!retval && (args->rmtblkno > 0)
&& !(args->flags & ATTR_KERNOVAL)) {
retval = xfs_attr_rmtval_get(args);
}
}
/*
* If not in a transaction, we have to release all the buffers.
*/
for (i = 0; i < state->path.active; i++) {
xfs_da_brelse(args->trans, state->path.blk[i].bp);
state->path.blk[i].bp = NULL;
}
xfs_da_state_free(state);
return(retval);
}
STATIC int /* error */
xfs_attr_node_list(xfs_attr_list_context_t *context)
{
attrlist_cursor_kern_t *cursor;
xfs_attr_leafblock_t *leaf;
xfs_da_intnode_t *node;
xfs_da_node_entry_t *btree;
int error, i;
xfs_dabuf_t *bp;
cursor = context->cursor;
cursor->initted = 1;
/*
* Do all sorts of validation on the passed-in cursor structure.
* If anything is amiss, ignore the cursor and look up the hashval
* starting from the btree root.
*/
bp = NULL;
if (cursor->blkno > 0) {
error = xfs_da_read_buf(NULL, context->dp, cursor->blkno, -1,
&bp, XFS_ATTR_FORK);
if ((error != 0) && (error != EFSCORRUPTED))
return(error);
if (bp) {
node = bp->data;
switch (be16_to_cpu(node->hdr.info.magic)) {
case XFS_DA_NODE_MAGIC:
trace_xfs_attr_list_wrong_blk(context);
xfs_da_brelse(NULL, bp);
bp = NULL;
break;
case XFS_ATTR_LEAF_MAGIC:
leaf = bp->data;
if (cursor->hashval > be32_to_cpu(leaf->entries[
be16_to_cpu(leaf->hdr.count)-1].hashval)) {
trace_xfs_attr_list_wrong_blk(context);
xfs_da_brelse(NULL, bp);
bp = NULL;
} else if (cursor->hashval <=
be32_to_cpu(leaf->entries[0].hashval)) {
trace_xfs_attr_list_wrong_blk(context);
xfs_da_brelse(NULL, bp);
bp = NULL;
}
break;
default:
trace_xfs_attr_list_wrong_blk(context);
xfs_da_brelse(NULL, bp);
bp = NULL;
}
}
}
/*
* We did not find what we expected given the cursor's contents,
* so we start from the top and work down based on the hash value.
* Note that start of node block is same as start of leaf block.
*/
if (bp == NULL) {
cursor->blkno = 0;
for (;;) {
error = xfs_da_read_buf(NULL, context->dp,
cursor->blkno, -1, &bp,
XFS_ATTR_FORK);
if (error)
return(error);
if (unlikely(bp == NULL)) {
XFS_ERROR_REPORT("xfs_attr_node_list(2)",
XFS_ERRLEVEL_LOW,
context->dp->i_mount);
return(XFS_ERROR(EFSCORRUPTED));
}
node = bp->data;
if (node->hdr.info.magic ==
cpu_to_be16(XFS_ATTR_LEAF_MAGIC))
break;
if (unlikely(node->hdr.info.magic !=
cpu_to_be16(XFS_DA_NODE_MAGIC))) {
XFS_CORRUPTION_ERROR("xfs_attr_node_list(3)",
XFS_ERRLEVEL_LOW,
context->dp->i_mount,
node);
xfs_da_brelse(NULL, bp);
return(XFS_ERROR(EFSCORRUPTED));
}
btree = node->btree;
for (i = 0; i < be16_to_cpu(node->hdr.count);
btree++, i++) {
if (cursor->hashval
<= be32_to_cpu(btree->hashval)) {
cursor->blkno = be32_to_cpu(btree->before);
trace_xfs_attr_list_node_descend(context,
btree);
break;
}
}
if (i == be16_to_cpu(node->hdr.count)) {
xfs_da_brelse(NULL, bp);
return(0);
}
xfs_da_brelse(NULL, bp);
}
}
ASSERT(bp != NULL);
/*
* Roll upward through the blocks, processing each leaf block in
* order. As long as there is space in the result buffer, keep
* adding the information.
*/
for (;;) {
leaf = bp->data;
if (unlikely(leaf->hdr.info.magic !=
cpu_to_be16(XFS_ATTR_LEAF_MAGIC))) {
XFS_CORRUPTION_ERROR("xfs_attr_node_list(4)",
XFS_ERRLEVEL_LOW,
context->dp->i_mount, leaf);
xfs_da_brelse(NULL, bp);
return(XFS_ERROR(EFSCORRUPTED));
}
error = xfs_attr_leaf_list_int(bp, context);
if (error) {
xfs_da_brelse(NULL, bp);
return error;
}
if (context->seen_enough || leaf->hdr.info.forw == 0)
break;
cursor->blkno = be32_to_cpu(leaf->hdr.info.forw);
xfs_da_brelse(NULL, bp);
error = xfs_da_read_buf(NULL, context->dp, cursor->blkno, -1,
&bp, XFS_ATTR_FORK);
if (error)
return(error);
if (unlikely((bp == NULL))) {
XFS_ERROR_REPORT("xfs_attr_node_list(5)",
XFS_ERRLEVEL_LOW,
context->dp->i_mount);
return(XFS_ERROR(EFSCORRUPTED));
}
}
xfs_da_brelse(NULL, bp);
return(0);
}
/*========================================================================
* External routines for manipulating out-of-line attribute values.
*========================================================================*/
/*
* Read the value associated with an attribute from the out-of-line buffer
* that we stored it in.
*/
int
xfs_attr_rmtval_get(xfs_da_args_t *args)
{
xfs_bmbt_irec_t map[ATTR_RMTVALUE_MAPSIZE];
xfs_mount_t *mp;
xfs_daddr_t dblkno;
void *dst;
xfs_buf_t *bp;
int nmap, error, tmp, valuelen, blkcnt, i;
xfs_dablk_t lblkno;
ASSERT(!(args->flags & ATTR_KERNOVAL));
mp = args->dp->i_mount;
dst = args->value;
valuelen = args->valuelen;
lblkno = args->rmtblkno;
while (valuelen > 0) {
nmap = ATTR_RMTVALUE_MAPSIZE;
error = xfs_bmapi_read(args->dp, (xfs_fileoff_t)lblkno,
args->rmtblkcnt, map, &nmap,
XFS_BMAPI_ATTRFORK);
if (error)
return(error);
ASSERT(nmap >= 1);
for (i = 0; (i < nmap) && (valuelen > 0); i++) {
ASSERT((map[i].br_startblock != DELAYSTARTBLOCK) &&
(map[i].br_startblock != HOLESTARTBLOCK));
dblkno = XFS_FSB_TO_DADDR(mp, map[i].br_startblock);
blkcnt = XFS_FSB_TO_BB(mp, map[i].br_blockcount);
error = xfs_read_buf(mp, mp->m_ddev_targp, dblkno,
blkcnt, XBF_LOCK | XBF_DONT_BLOCK,
&bp);
if (error)
return(error);
tmp = (valuelen < XFS_BUF_SIZE(bp))
? valuelen : XFS_BUF_SIZE(bp);
xfs_buf_iomove(bp, 0, tmp, dst, XBRW_READ);
xfs_buf_relse(bp);
dst += tmp;
valuelen -= tmp;
lblkno += map[i].br_blockcount;
}
}
ASSERT(valuelen == 0);
return(0);
}
/*
* Write the value associated with an attribute into the out-of-line buffer
* that we have defined for it.
*/
STATIC int
xfs_attr_rmtval_set(xfs_da_args_t *args)
{
xfs_mount_t *mp;
xfs_fileoff_t lfileoff;
xfs_inode_t *dp;
xfs_bmbt_irec_t map;
xfs_daddr_t dblkno;
void *src;
xfs_buf_t *bp;
xfs_dablk_t lblkno;
int blkcnt, valuelen, nmap, error, tmp, committed;
dp = args->dp;
mp = dp->i_mount;
src = args->value;
/*
* Find a "hole" in the attribute address space large enough for
* us to drop the new attribute's value into.
*/
blkcnt = XFS_B_TO_FSB(mp, args->valuelen);
lfileoff = 0;
error = xfs_bmap_first_unused(args->trans, args->dp, blkcnt, &lfileoff,
XFS_ATTR_FORK);
if (error) {
return(error);
}
args->rmtblkno = lblkno = (xfs_dablk_t)lfileoff;
args->rmtblkcnt = blkcnt;
/*
* Roll through the "value", allocating blocks on disk as required.
*/
while (blkcnt > 0) {
/*
* Allocate a single extent, up to the size of the value.
*/
xfs_bmap_init(args->flist, args->firstblock);
nmap = 1;
error = xfs_bmapi_write(args->trans, dp, (xfs_fileoff_t)lblkno,
blkcnt,
XFS_BMAPI_ATTRFORK | XFS_BMAPI_METADATA,
args->firstblock, args->total, &map, &nmap,
args->flist);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
ASSERT(nmap == 1);
ASSERT((map.br_startblock != DELAYSTARTBLOCK) &&
(map.br_startblock != HOLESTARTBLOCK));
lblkno += map.br_blockcount;
blkcnt -= map.br_blockcount;
/*
* Start the next trans in the chain.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
}
/*
* Roll through the "value", copying the attribute value to the
* already-allocated blocks. Blocks are written synchronously
* so that we can know they are all on disk before we turn off
* the INCOMPLETE flag.
*/
lblkno = args->rmtblkno;
valuelen = args->valuelen;
while (valuelen > 0) {
/*
* Try to remember where we decided to put the value.
*/
xfs_bmap_init(args->flist, args->firstblock);
nmap = 1;
error = xfs_bmapi_read(dp, (xfs_fileoff_t)lblkno,
args->rmtblkcnt, &map, &nmap,
XFS_BMAPI_ATTRFORK);
if (error)
return(error);
ASSERT(nmap == 1);
ASSERT((map.br_startblock != DELAYSTARTBLOCK) &&
(map.br_startblock != HOLESTARTBLOCK));
dblkno = XFS_FSB_TO_DADDR(mp, map.br_startblock),
blkcnt = XFS_FSB_TO_BB(mp, map.br_blockcount);
bp = xfs_buf_get(mp->m_ddev_targp, dblkno, blkcnt,
XBF_LOCK | XBF_DONT_BLOCK);
if (!bp)
return ENOMEM;
tmp = (valuelen < XFS_BUF_SIZE(bp)) ? valuelen :
XFS_BUF_SIZE(bp);
xfs_buf_iomove(bp, 0, tmp, src, XBRW_WRITE);
if (tmp < XFS_BUF_SIZE(bp))
xfs_buf_zero(bp, tmp, XFS_BUF_SIZE(bp) - tmp);
error = xfs_bwrite(bp); /* GROT: NOTE: synchronous write */
xfs_buf_relse(bp);
if (error)
return error;
src += tmp;
valuelen -= tmp;
lblkno += map.br_blockcount;
}
ASSERT(valuelen == 0);
return(0);
}
/*
* Remove the value associated with an attribute by deleting the
* out-of-line buffer that it is stored on.
*/
STATIC int
xfs_attr_rmtval_remove(xfs_da_args_t *args)
{
xfs_mount_t *mp;
xfs_bmbt_irec_t map;
xfs_buf_t *bp;
xfs_daddr_t dblkno;
xfs_dablk_t lblkno;
int valuelen, blkcnt, nmap, error, done, committed;
mp = args->dp->i_mount;
/*
* Roll through the "value", invalidating the attribute value's
* blocks.
*/
lblkno = args->rmtblkno;
valuelen = args->rmtblkcnt;
while (valuelen > 0) {
/*
* Try to remember where we decided to put the value.
*/
nmap = 1;
error = xfs_bmapi_read(args->dp, (xfs_fileoff_t)lblkno,
args->rmtblkcnt, &map, &nmap,
XFS_BMAPI_ATTRFORK);
if (error)
return(error);
ASSERT(nmap == 1);
ASSERT((map.br_startblock != DELAYSTARTBLOCK) &&
(map.br_startblock != HOLESTARTBLOCK));
dblkno = XFS_FSB_TO_DADDR(mp, map.br_startblock),
blkcnt = XFS_FSB_TO_BB(mp, map.br_blockcount);
/*
* If the "remote" value is in the cache, remove it.
*/
bp = xfs_incore(mp->m_ddev_targp, dblkno, blkcnt, XBF_TRYLOCK);
if (bp) {
xfs_buf_stale(bp);
xfs_buf_relse(bp);
bp = NULL;
}
valuelen -= map.br_blockcount;
lblkno += map.br_blockcount;
}
/*
* Keep de-allocating extents until the remote-value region is gone.
*/
lblkno = args->rmtblkno;
blkcnt = args->rmtblkcnt;
done = 0;
while (!done) {
xfs_bmap_init(args->flist, args->firstblock);
error = xfs_bunmapi(args->trans, args->dp, lblkno, blkcnt,
XFS_BMAPI_ATTRFORK | XFS_BMAPI_METADATA,
1, args->firstblock, args->flist,
&done);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, args->dp, 0);
/*
* Close out trans and start the next one in the chain.
*/
error = xfs_trans_roll(&args->trans, args->dp);
if (error)
return (error);
}
return(0);
}
| gpl-2.0 |
infected-lp/android_kernel_sony_msm8974 | drivers/net/ethernet/intel/ixgbe/ixgbe_82599.c | 4809 | 68773 | /*******************************************************************************
Intel 10 Gigabit PCI Express Linux driver
Copyright(c) 1999 - 2012 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include "ixgbe.h"
#include "ixgbe_phy.h"
#include "ixgbe_mbx.h"
#define IXGBE_82599_MAX_TX_QUEUES 128
#define IXGBE_82599_MAX_RX_QUEUES 128
#define IXGBE_82599_RAR_ENTRIES 128
#define IXGBE_82599_MC_TBL_SIZE 128
#define IXGBE_82599_VFT_TBL_SIZE 128
#define IXGBE_82599_RX_PB_SIZE 512
static void ixgbe_disable_tx_laser_multispeed_fiber(struct ixgbe_hw *hw);
static void ixgbe_enable_tx_laser_multispeed_fiber(struct ixgbe_hw *hw);
static void ixgbe_flap_tx_laser_multispeed_fiber(struct ixgbe_hw *hw);
static s32 ixgbe_setup_mac_link_multispeed_fiber(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg,
bool autoneg_wait_to_complete);
static s32 ixgbe_setup_mac_link_smartspeed(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg,
bool autoneg_wait_to_complete);
static s32 ixgbe_start_mac_link_82599(struct ixgbe_hw *hw,
bool autoneg_wait_to_complete);
static s32 ixgbe_setup_mac_link_82599(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg,
bool autoneg_wait_to_complete);
static s32 ixgbe_setup_copper_link_82599(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg,
bool autoneg_wait_to_complete);
static s32 ixgbe_verify_fw_version_82599(struct ixgbe_hw *hw);
static bool ixgbe_verify_lesm_fw_enabled_82599(struct ixgbe_hw *hw);
static void ixgbe_init_mac_link_ops_82599(struct ixgbe_hw *hw)
{
struct ixgbe_mac_info *mac = &hw->mac;
/* enable the laser control functions for SFP+ fiber */
if (mac->ops.get_media_type(hw) == ixgbe_media_type_fiber) {
mac->ops.disable_tx_laser =
&ixgbe_disable_tx_laser_multispeed_fiber;
mac->ops.enable_tx_laser =
&ixgbe_enable_tx_laser_multispeed_fiber;
mac->ops.flap_tx_laser = &ixgbe_flap_tx_laser_multispeed_fiber;
} else {
mac->ops.disable_tx_laser = NULL;
mac->ops.enable_tx_laser = NULL;
mac->ops.flap_tx_laser = NULL;
}
if (hw->phy.multispeed_fiber) {
/* Set up dual speed SFP+ support */
mac->ops.setup_link = &ixgbe_setup_mac_link_multispeed_fiber;
} else {
if ((mac->ops.get_media_type(hw) ==
ixgbe_media_type_backplane) &&
(hw->phy.smart_speed == ixgbe_smart_speed_auto ||
hw->phy.smart_speed == ixgbe_smart_speed_on) &&
!ixgbe_verify_lesm_fw_enabled_82599(hw))
mac->ops.setup_link = &ixgbe_setup_mac_link_smartspeed;
else
mac->ops.setup_link = &ixgbe_setup_mac_link_82599;
}
}
static s32 ixgbe_setup_sfp_modules_82599(struct ixgbe_hw *hw)
{
s32 ret_val = 0;
u32 reg_anlp1 = 0;
u32 i = 0;
u16 list_offset, data_offset, data_value;
if (hw->phy.sfp_type != ixgbe_sfp_type_unknown) {
ixgbe_init_mac_link_ops_82599(hw);
hw->phy.ops.reset = NULL;
ret_val = ixgbe_get_sfp_init_sequence_offsets(hw, &list_offset,
&data_offset);
if (ret_val != 0)
goto setup_sfp_out;
/* PHY config will finish before releasing the semaphore */
ret_val = hw->mac.ops.acquire_swfw_sync(hw,
IXGBE_GSSR_MAC_CSR_SM);
if (ret_val != 0) {
ret_val = IXGBE_ERR_SWFW_SYNC;
goto setup_sfp_out;
}
hw->eeprom.ops.read(hw, ++data_offset, &data_value);
while (data_value != 0xffff) {
IXGBE_WRITE_REG(hw, IXGBE_CORECTL, data_value);
IXGBE_WRITE_FLUSH(hw);
hw->eeprom.ops.read(hw, ++data_offset, &data_value);
}
/* Release the semaphore */
hw->mac.ops.release_swfw_sync(hw, IXGBE_GSSR_MAC_CSR_SM);
/*
* Delay obtaining semaphore again to allow FW access,
* semaphore_delay is in ms usleep_range needs us.
*/
usleep_range(hw->eeprom.semaphore_delay * 1000,
hw->eeprom.semaphore_delay * 2000);
/* Now restart DSP by setting Restart_AN and clearing LMS */
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, ((IXGBE_READ_REG(hw,
IXGBE_AUTOC) & ~IXGBE_AUTOC_LMS_MASK) |
IXGBE_AUTOC_AN_RESTART));
/* Wait for AN to leave state 0 */
for (i = 0; i < 10; i++) {
usleep_range(4000, 8000);
reg_anlp1 = IXGBE_READ_REG(hw, IXGBE_ANLP1);
if (reg_anlp1 & IXGBE_ANLP1_AN_STATE_MASK)
break;
}
if (!(reg_anlp1 & IXGBE_ANLP1_AN_STATE_MASK)) {
hw_dbg(hw, "sfp module setup not complete\n");
ret_val = IXGBE_ERR_SFP_SETUP_NOT_COMPLETE;
goto setup_sfp_out;
}
/* Restart DSP by setting Restart_AN and return to SFI mode */
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, (IXGBE_READ_REG(hw,
IXGBE_AUTOC) | IXGBE_AUTOC_LMS_10G_SERIAL |
IXGBE_AUTOC_AN_RESTART));
}
setup_sfp_out:
return ret_val;
}
static s32 ixgbe_get_invariants_82599(struct ixgbe_hw *hw)
{
struct ixgbe_mac_info *mac = &hw->mac;
ixgbe_init_mac_link_ops_82599(hw);
mac->mcft_size = IXGBE_82599_MC_TBL_SIZE;
mac->vft_size = IXGBE_82599_VFT_TBL_SIZE;
mac->num_rar_entries = IXGBE_82599_RAR_ENTRIES;
mac->max_rx_queues = IXGBE_82599_MAX_RX_QUEUES;
mac->max_tx_queues = IXGBE_82599_MAX_TX_QUEUES;
mac->max_msix_vectors = ixgbe_get_pcie_msix_count_generic(hw);
return 0;
}
/**
* ixgbe_init_phy_ops_82599 - PHY/SFP specific init
* @hw: pointer to hardware structure
*
* Initialize any function pointers that were not able to be
* set during get_invariants because the PHY/SFP type was
* not known. Perform the SFP init if necessary.
*
**/
static s32 ixgbe_init_phy_ops_82599(struct ixgbe_hw *hw)
{
struct ixgbe_mac_info *mac = &hw->mac;
struct ixgbe_phy_info *phy = &hw->phy;
s32 ret_val = 0;
/* Identify the PHY or SFP module */
ret_val = phy->ops.identify(hw);
/* Setup function pointers based on detected SFP module and speeds */
ixgbe_init_mac_link_ops_82599(hw);
/* If copper media, overwrite with copper function pointers */
if (mac->ops.get_media_type(hw) == ixgbe_media_type_copper) {
mac->ops.setup_link = &ixgbe_setup_copper_link_82599;
mac->ops.get_link_capabilities =
&ixgbe_get_copper_link_capabilities_generic;
}
/* Set necessary function pointers based on phy type */
switch (hw->phy.type) {
case ixgbe_phy_tn:
phy->ops.check_link = &ixgbe_check_phy_link_tnx;
phy->ops.setup_link = &ixgbe_setup_phy_link_tnx;
phy->ops.get_firmware_version =
&ixgbe_get_phy_firmware_version_tnx;
break;
default:
break;
}
return ret_val;
}
/**
* ixgbe_get_link_capabilities_82599 - Determines link capabilities
* @hw: pointer to hardware structure
* @speed: pointer to link speed
* @negotiation: true when autoneg or autotry is enabled
*
* Determines the link capabilities by reading the AUTOC register.
**/
static s32 ixgbe_get_link_capabilities_82599(struct ixgbe_hw *hw,
ixgbe_link_speed *speed,
bool *negotiation)
{
s32 status = 0;
u32 autoc = 0;
/* Determine 1G link capabilities off of SFP+ type */
if (hw->phy.sfp_type == ixgbe_sfp_type_1g_cu_core0 ||
hw->phy.sfp_type == ixgbe_sfp_type_1g_cu_core1) {
*speed = IXGBE_LINK_SPEED_1GB_FULL;
*negotiation = true;
goto out;
}
/*
* Determine link capabilities based on the stored value of AUTOC,
* which represents EEPROM defaults. If AUTOC value has not been
* stored, use the current register value.
*/
if (hw->mac.orig_link_settings_stored)
autoc = hw->mac.orig_autoc;
else
autoc = IXGBE_READ_REG(hw, IXGBE_AUTOC);
switch (autoc & IXGBE_AUTOC_LMS_MASK) {
case IXGBE_AUTOC_LMS_1G_LINK_NO_AN:
*speed = IXGBE_LINK_SPEED_1GB_FULL;
*negotiation = false;
break;
case IXGBE_AUTOC_LMS_10G_LINK_NO_AN:
*speed = IXGBE_LINK_SPEED_10GB_FULL;
*negotiation = false;
break;
case IXGBE_AUTOC_LMS_1G_AN:
*speed = IXGBE_LINK_SPEED_1GB_FULL;
*negotiation = true;
break;
case IXGBE_AUTOC_LMS_10G_SERIAL:
*speed = IXGBE_LINK_SPEED_10GB_FULL;
*negotiation = false;
break;
case IXGBE_AUTOC_LMS_KX4_KX_KR:
case IXGBE_AUTOC_LMS_KX4_KX_KR_1G_AN:
*speed = IXGBE_LINK_SPEED_UNKNOWN;
if (autoc & IXGBE_AUTOC_KR_SUPP)
*speed |= IXGBE_LINK_SPEED_10GB_FULL;
if (autoc & IXGBE_AUTOC_KX4_SUPP)
*speed |= IXGBE_LINK_SPEED_10GB_FULL;
if (autoc & IXGBE_AUTOC_KX_SUPP)
*speed |= IXGBE_LINK_SPEED_1GB_FULL;
*negotiation = true;
break;
case IXGBE_AUTOC_LMS_KX4_KX_KR_SGMII:
*speed = IXGBE_LINK_SPEED_100_FULL;
if (autoc & IXGBE_AUTOC_KR_SUPP)
*speed |= IXGBE_LINK_SPEED_10GB_FULL;
if (autoc & IXGBE_AUTOC_KX4_SUPP)
*speed |= IXGBE_LINK_SPEED_10GB_FULL;
if (autoc & IXGBE_AUTOC_KX_SUPP)
*speed |= IXGBE_LINK_SPEED_1GB_FULL;
*negotiation = true;
break;
case IXGBE_AUTOC_LMS_SGMII_1G_100M:
*speed = IXGBE_LINK_SPEED_1GB_FULL | IXGBE_LINK_SPEED_100_FULL;
*negotiation = false;
break;
default:
status = IXGBE_ERR_LINK_SETUP;
goto out;
break;
}
if (hw->phy.multispeed_fiber) {
*speed |= IXGBE_LINK_SPEED_10GB_FULL |
IXGBE_LINK_SPEED_1GB_FULL;
*negotiation = true;
}
out:
return status;
}
/**
* ixgbe_get_media_type_82599 - Get media type
* @hw: pointer to hardware structure
*
* Returns the media type (fiber, copper, backplane)
**/
static enum ixgbe_media_type ixgbe_get_media_type_82599(struct ixgbe_hw *hw)
{
enum ixgbe_media_type media_type;
/* Detect if there is a copper PHY attached. */
switch (hw->phy.type) {
case ixgbe_phy_cu_unknown:
case ixgbe_phy_tn:
media_type = ixgbe_media_type_copper;
goto out;
default:
break;
}
switch (hw->device_id) {
case IXGBE_DEV_ID_82599_KX4:
case IXGBE_DEV_ID_82599_KX4_MEZZ:
case IXGBE_DEV_ID_82599_COMBO_BACKPLANE:
case IXGBE_DEV_ID_82599_KR:
case IXGBE_DEV_ID_82599_BACKPLANE_FCOE:
case IXGBE_DEV_ID_82599_XAUI_LOM:
/* Default device ID is mezzanine card KX/KX4 */
media_type = ixgbe_media_type_backplane;
break;
case IXGBE_DEV_ID_82599_SFP:
case IXGBE_DEV_ID_82599_SFP_FCOE:
case IXGBE_DEV_ID_82599_SFP_EM:
case IXGBE_DEV_ID_82599_SFP_SF2:
case IXGBE_DEV_ID_82599_SFP_SF_QP:
case IXGBE_DEV_ID_82599EN_SFP:
media_type = ixgbe_media_type_fiber;
break;
case IXGBE_DEV_ID_82599_CX4:
media_type = ixgbe_media_type_cx4;
break;
case IXGBE_DEV_ID_82599_T3_LOM:
media_type = ixgbe_media_type_copper;
break;
case IXGBE_DEV_ID_82599_LS:
media_type = ixgbe_media_type_fiber_lco;
break;
default:
media_type = ixgbe_media_type_unknown;
break;
}
out:
return media_type;
}
/**
* ixgbe_start_mac_link_82599 - Setup MAC link settings
* @hw: pointer to hardware structure
* @autoneg_wait_to_complete: true when waiting for completion is needed
*
* Configures link settings based on values in the ixgbe_hw struct.
* Restarts the link. Performs autonegotiation if needed.
**/
static s32 ixgbe_start_mac_link_82599(struct ixgbe_hw *hw,
bool autoneg_wait_to_complete)
{
u32 autoc_reg;
u32 links_reg;
u32 i;
s32 status = 0;
/* Restart link */
autoc_reg = IXGBE_READ_REG(hw, IXGBE_AUTOC);
autoc_reg |= IXGBE_AUTOC_AN_RESTART;
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, autoc_reg);
/* Only poll for autoneg to complete if specified to do so */
if (autoneg_wait_to_complete) {
if ((autoc_reg & IXGBE_AUTOC_LMS_MASK) ==
IXGBE_AUTOC_LMS_KX4_KX_KR ||
(autoc_reg & IXGBE_AUTOC_LMS_MASK) ==
IXGBE_AUTOC_LMS_KX4_KX_KR_1G_AN ||
(autoc_reg & IXGBE_AUTOC_LMS_MASK) ==
IXGBE_AUTOC_LMS_KX4_KX_KR_SGMII) {
links_reg = 0; /* Just in case Autoneg time = 0 */
for (i = 0; i < IXGBE_AUTO_NEG_TIME; i++) {
links_reg = IXGBE_READ_REG(hw, IXGBE_LINKS);
if (links_reg & IXGBE_LINKS_KX_AN_COMP)
break;
msleep(100);
}
if (!(links_reg & IXGBE_LINKS_KX_AN_COMP)) {
status = IXGBE_ERR_AUTONEG_NOT_COMPLETE;
hw_dbg(hw, "Autoneg did not complete.\n");
}
}
}
/* Add delay to filter out noises during initial link setup */
msleep(50);
return status;
}
/**
* ixgbe_disable_tx_laser_multispeed_fiber - Disable Tx laser
* @hw: pointer to hardware structure
*
* The base drivers may require better control over SFP+ module
* PHY states. This includes selectively shutting down the Tx
* laser on the PHY, effectively halting physical link.
**/
static void ixgbe_disable_tx_laser_multispeed_fiber(struct ixgbe_hw *hw)
{
u32 esdp_reg = IXGBE_READ_REG(hw, IXGBE_ESDP);
/* Disable tx laser; allow 100us to go dark per spec */
esdp_reg |= IXGBE_ESDP_SDP3;
IXGBE_WRITE_REG(hw, IXGBE_ESDP, esdp_reg);
IXGBE_WRITE_FLUSH(hw);
udelay(100);
}
/**
* ixgbe_enable_tx_laser_multispeed_fiber - Enable Tx laser
* @hw: pointer to hardware structure
*
* The base drivers may require better control over SFP+ module
* PHY states. This includes selectively turning on the Tx
* laser on the PHY, effectively starting physical link.
**/
static void ixgbe_enable_tx_laser_multispeed_fiber(struct ixgbe_hw *hw)
{
u32 esdp_reg = IXGBE_READ_REG(hw, IXGBE_ESDP);
/* Enable tx laser; allow 100ms to light up */
esdp_reg &= ~IXGBE_ESDP_SDP3;
IXGBE_WRITE_REG(hw, IXGBE_ESDP, esdp_reg);
IXGBE_WRITE_FLUSH(hw);
msleep(100);
}
/**
* ixgbe_flap_tx_laser_multispeed_fiber - Flap Tx laser
* @hw: pointer to hardware structure
*
* When the driver changes the link speeds that it can support,
* it sets autotry_restart to true to indicate that we need to
* initiate a new autotry session with the link partner. To do
* so, we set the speed then disable and re-enable the tx laser, to
* alert the link partner that it also needs to restart autotry on its
* end. This is consistent with true clause 37 autoneg, which also
* involves a loss of signal.
**/
static void ixgbe_flap_tx_laser_multispeed_fiber(struct ixgbe_hw *hw)
{
if (hw->mac.autotry_restart) {
ixgbe_disable_tx_laser_multispeed_fiber(hw);
ixgbe_enable_tx_laser_multispeed_fiber(hw);
hw->mac.autotry_restart = false;
}
}
/**
* ixgbe_setup_mac_link_multispeed_fiber - Set MAC link speed
* @hw: pointer to hardware structure
* @speed: new link speed
* @autoneg: true if autonegotiation enabled
* @autoneg_wait_to_complete: true when waiting for completion is needed
*
* Set the link speed in the AUTOC register and restarts link.
**/
static s32 ixgbe_setup_mac_link_multispeed_fiber(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg,
bool autoneg_wait_to_complete)
{
s32 status = 0;
ixgbe_link_speed link_speed = IXGBE_LINK_SPEED_UNKNOWN;
ixgbe_link_speed highest_link_speed = IXGBE_LINK_SPEED_UNKNOWN;
u32 speedcnt = 0;
u32 esdp_reg = IXGBE_READ_REG(hw, IXGBE_ESDP);
u32 i = 0;
bool link_up = false;
bool negotiation;
/* Mask off requested but non-supported speeds */
status = hw->mac.ops.get_link_capabilities(hw, &link_speed,
&negotiation);
if (status != 0)
return status;
speed &= link_speed;
/*
* Try each speed one by one, highest priority first. We do this in
* software because 10gb fiber doesn't support speed autonegotiation.
*/
if (speed & IXGBE_LINK_SPEED_10GB_FULL) {
speedcnt++;
highest_link_speed = IXGBE_LINK_SPEED_10GB_FULL;
/* If we already have link at this speed, just jump out */
status = hw->mac.ops.check_link(hw, &link_speed, &link_up,
false);
if (status != 0)
return status;
if ((link_speed == IXGBE_LINK_SPEED_10GB_FULL) && link_up)
goto out;
/* Set the module link speed */
esdp_reg |= (IXGBE_ESDP_SDP5_DIR | IXGBE_ESDP_SDP5);
IXGBE_WRITE_REG(hw, IXGBE_ESDP, esdp_reg);
IXGBE_WRITE_FLUSH(hw);
/* Allow module to change analog characteristics (1G->10G) */
msleep(40);
status = ixgbe_setup_mac_link_82599(hw,
IXGBE_LINK_SPEED_10GB_FULL,
autoneg,
autoneg_wait_to_complete);
if (status != 0)
return status;
/* Flap the tx laser if it has not already been done */
hw->mac.ops.flap_tx_laser(hw);
/*
* Wait for the controller to acquire link. Per IEEE 802.3ap,
* Section 73.10.2, we may have to wait up to 500ms if KR is
* attempted. 82599 uses the same timing for 10g SFI.
*/
for (i = 0; i < 5; i++) {
/* Wait for the link partner to also set speed */
msleep(100);
/* If we have link, just jump out */
status = hw->mac.ops.check_link(hw, &link_speed,
&link_up, false);
if (status != 0)
return status;
if (link_up)
goto out;
}
}
if (speed & IXGBE_LINK_SPEED_1GB_FULL) {
speedcnt++;
if (highest_link_speed == IXGBE_LINK_SPEED_UNKNOWN)
highest_link_speed = IXGBE_LINK_SPEED_1GB_FULL;
/* If we already have link at this speed, just jump out */
status = hw->mac.ops.check_link(hw, &link_speed, &link_up,
false);
if (status != 0)
return status;
if ((link_speed == IXGBE_LINK_SPEED_1GB_FULL) && link_up)
goto out;
/* Set the module link speed */
esdp_reg &= ~IXGBE_ESDP_SDP5;
esdp_reg |= IXGBE_ESDP_SDP5_DIR;
IXGBE_WRITE_REG(hw, IXGBE_ESDP, esdp_reg);
IXGBE_WRITE_FLUSH(hw);
/* Allow module to change analog characteristics (10G->1G) */
msleep(40);
status = ixgbe_setup_mac_link_82599(hw,
IXGBE_LINK_SPEED_1GB_FULL,
autoneg,
autoneg_wait_to_complete);
if (status != 0)
return status;
/* Flap the tx laser if it has not already been done */
hw->mac.ops.flap_tx_laser(hw);
/* Wait for the link partner to also set speed */
msleep(100);
/* If we have link, just jump out */
status = hw->mac.ops.check_link(hw, &link_speed, &link_up,
false);
if (status != 0)
return status;
if (link_up)
goto out;
}
/*
* We didn't get link. Configure back to the highest speed we tried,
* (if there was more than one). We call ourselves back with just the
* single highest speed that the user requested.
*/
if (speedcnt > 1)
status = ixgbe_setup_mac_link_multispeed_fiber(hw,
highest_link_speed,
autoneg,
autoneg_wait_to_complete);
out:
/* Set autoneg_advertised value based on input link speed */
hw->phy.autoneg_advertised = 0;
if (speed & IXGBE_LINK_SPEED_10GB_FULL)
hw->phy.autoneg_advertised |= IXGBE_LINK_SPEED_10GB_FULL;
if (speed & IXGBE_LINK_SPEED_1GB_FULL)
hw->phy.autoneg_advertised |= IXGBE_LINK_SPEED_1GB_FULL;
return status;
}
/**
* ixgbe_setup_mac_link_smartspeed - Set MAC link speed using SmartSpeed
* @hw: pointer to hardware structure
* @speed: new link speed
* @autoneg: true if autonegotiation enabled
* @autoneg_wait_to_complete: true when waiting for completion is needed
*
* Implements the Intel SmartSpeed algorithm.
**/
static s32 ixgbe_setup_mac_link_smartspeed(struct ixgbe_hw *hw,
ixgbe_link_speed speed, bool autoneg,
bool autoneg_wait_to_complete)
{
s32 status = 0;
ixgbe_link_speed link_speed = IXGBE_LINK_SPEED_UNKNOWN;
s32 i, j;
bool link_up = false;
u32 autoc_reg = IXGBE_READ_REG(hw, IXGBE_AUTOC);
/* Set autoneg_advertised value based on input link speed */
hw->phy.autoneg_advertised = 0;
if (speed & IXGBE_LINK_SPEED_10GB_FULL)
hw->phy.autoneg_advertised |= IXGBE_LINK_SPEED_10GB_FULL;
if (speed & IXGBE_LINK_SPEED_1GB_FULL)
hw->phy.autoneg_advertised |= IXGBE_LINK_SPEED_1GB_FULL;
if (speed & IXGBE_LINK_SPEED_100_FULL)
hw->phy.autoneg_advertised |= IXGBE_LINK_SPEED_100_FULL;
/*
* Implement Intel SmartSpeed algorithm. SmartSpeed will reduce the
* autoneg advertisement if link is unable to be established at the
* highest negotiated rate. This can sometimes happen due to integrity
* issues with the physical media connection.
*/
/* First, try to get link with full advertisement */
hw->phy.smart_speed_active = false;
for (j = 0; j < IXGBE_SMARTSPEED_MAX_RETRIES; j++) {
status = ixgbe_setup_mac_link_82599(hw, speed, autoneg,
autoneg_wait_to_complete);
if (status != 0)
goto out;
/*
* Wait for the controller to acquire link. Per IEEE 802.3ap,
* Section 73.10.2, we may have to wait up to 500ms if KR is
* attempted, or 200ms if KX/KX4/BX/BX4 is attempted, per
* Table 9 in the AN MAS.
*/
for (i = 0; i < 5; i++) {
mdelay(100);
/* If we have link, just jump out */
status = hw->mac.ops.check_link(hw, &link_speed,
&link_up, false);
if (status != 0)
goto out;
if (link_up)
goto out;
}
}
/*
* We didn't get link. If we advertised KR plus one of KX4/KX
* (or BX4/BX), then disable KR and try again.
*/
if (((autoc_reg & IXGBE_AUTOC_KR_SUPP) == 0) ||
((autoc_reg & IXGBE_AUTOC_KX4_KX_SUPP_MASK) == 0))
goto out;
/* Turn SmartSpeed on to disable KR support */
hw->phy.smart_speed_active = true;
status = ixgbe_setup_mac_link_82599(hw, speed, autoneg,
autoneg_wait_to_complete);
if (status != 0)
goto out;
/*
* Wait for the controller to acquire link. 600ms will allow for
* the AN link_fail_inhibit_timer as well for multiple cycles of
* parallel detect, both 10g and 1g. This allows for the maximum
* connect attempts as defined in the AN MAS table 73-7.
*/
for (i = 0; i < 6; i++) {
mdelay(100);
/* If we have link, just jump out */
status = hw->mac.ops.check_link(hw, &link_speed,
&link_up, false);
if (status != 0)
goto out;
if (link_up)
goto out;
}
/* We didn't get link. Turn SmartSpeed back off. */
hw->phy.smart_speed_active = false;
status = ixgbe_setup_mac_link_82599(hw, speed, autoneg,
autoneg_wait_to_complete);
out:
if (link_up && (link_speed == IXGBE_LINK_SPEED_1GB_FULL))
hw_dbg(hw, "Smartspeed has downgraded the link speed from "
"the maximum advertised\n");
return status;
}
/**
* ixgbe_setup_mac_link_82599 - Set MAC link speed
* @hw: pointer to hardware structure
* @speed: new link speed
* @autoneg: true if autonegotiation enabled
* @autoneg_wait_to_complete: true when waiting for completion is needed
*
* Set the link speed in the AUTOC register and restarts link.
**/
static s32 ixgbe_setup_mac_link_82599(struct ixgbe_hw *hw,
ixgbe_link_speed speed, bool autoneg,
bool autoneg_wait_to_complete)
{
s32 status = 0;
u32 autoc = IXGBE_READ_REG(hw, IXGBE_AUTOC);
u32 autoc2 = IXGBE_READ_REG(hw, IXGBE_AUTOC2);
u32 start_autoc = autoc;
u32 orig_autoc = 0;
u32 link_mode = autoc & IXGBE_AUTOC_LMS_MASK;
u32 pma_pmd_1g = autoc & IXGBE_AUTOC_1G_PMA_PMD_MASK;
u32 pma_pmd_10g_serial = autoc2 & IXGBE_AUTOC2_10G_SERIAL_PMA_PMD_MASK;
u32 links_reg;
u32 i;
ixgbe_link_speed link_capabilities = IXGBE_LINK_SPEED_UNKNOWN;
/* Check to see if speed passed in is supported. */
status = hw->mac.ops.get_link_capabilities(hw, &link_capabilities,
&autoneg);
if (status != 0)
goto out;
speed &= link_capabilities;
if (speed == IXGBE_LINK_SPEED_UNKNOWN) {
status = IXGBE_ERR_LINK_SETUP;
goto out;
}
/* Use stored value (EEPROM defaults) of AUTOC to find KR/KX4 support*/
if (hw->mac.orig_link_settings_stored)
orig_autoc = hw->mac.orig_autoc;
else
orig_autoc = autoc;
if (link_mode == IXGBE_AUTOC_LMS_KX4_KX_KR ||
link_mode == IXGBE_AUTOC_LMS_KX4_KX_KR_1G_AN ||
link_mode == IXGBE_AUTOC_LMS_KX4_KX_KR_SGMII) {
/* Set KX4/KX/KR support according to speed requested */
autoc &= ~(IXGBE_AUTOC_KX4_KX_SUPP_MASK | IXGBE_AUTOC_KR_SUPP);
if (speed & IXGBE_LINK_SPEED_10GB_FULL)
if (orig_autoc & IXGBE_AUTOC_KX4_SUPP)
autoc |= IXGBE_AUTOC_KX4_SUPP;
if ((orig_autoc & IXGBE_AUTOC_KR_SUPP) &&
(hw->phy.smart_speed_active == false))
autoc |= IXGBE_AUTOC_KR_SUPP;
if (speed & IXGBE_LINK_SPEED_1GB_FULL)
autoc |= IXGBE_AUTOC_KX_SUPP;
} else if ((pma_pmd_1g == IXGBE_AUTOC_1G_SFI) &&
(link_mode == IXGBE_AUTOC_LMS_1G_LINK_NO_AN ||
link_mode == IXGBE_AUTOC_LMS_1G_AN)) {
/* Switch from 1G SFI to 10G SFI if requested */
if ((speed == IXGBE_LINK_SPEED_10GB_FULL) &&
(pma_pmd_10g_serial == IXGBE_AUTOC2_10G_SFI)) {
autoc &= ~IXGBE_AUTOC_LMS_MASK;
autoc |= IXGBE_AUTOC_LMS_10G_SERIAL;
}
} else if ((pma_pmd_10g_serial == IXGBE_AUTOC2_10G_SFI) &&
(link_mode == IXGBE_AUTOC_LMS_10G_SERIAL)) {
/* Switch from 10G SFI to 1G SFI if requested */
if ((speed == IXGBE_LINK_SPEED_1GB_FULL) &&
(pma_pmd_1g == IXGBE_AUTOC_1G_SFI)) {
autoc &= ~IXGBE_AUTOC_LMS_MASK;
if (autoneg)
autoc |= IXGBE_AUTOC_LMS_1G_AN;
else
autoc |= IXGBE_AUTOC_LMS_1G_LINK_NO_AN;
}
}
if (autoc != start_autoc) {
/* Restart link */
autoc |= IXGBE_AUTOC_AN_RESTART;
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, autoc);
/* Only poll for autoneg to complete if specified to do so */
if (autoneg_wait_to_complete) {
if (link_mode == IXGBE_AUTOC_LMS_KX4_KX_KR ||
link_mode == IXGBE_AUTOC_LMS_KX4_KX_KR_1G_AN ||
link_mode == IXGBE_AUTOC_LMS_KX4_KX_KR_SGMII) {
links_reg = 0; /*Just in case Autoneg time=0*/
for (i = 0; i < IXGBE_AUTO_NEG_TIME; i++) {
links_reg =
IXGBE_READ_REG(hw, IXGBE_LINKS);
if (links_reg & IXGBE_LINKS_KX_AN_COMP)
break;
msleep(100);
}
if (!(links_reg & IXGBE_LINKS_KX_AN_COMP)) {
status =
IXGBE_ERR_AUTONEG_NOT_COMPLETE;
hw_dbg(hw, "Autoneg did not "
"complete.\n");
}
}
}
/* Add delay to filter out noises during initial link setup */
msleep(50);
}
out:
return status;
}
/**
* ixgbe_setup_copper_link_82599 - Set the PHY autoneg advertised field
* @hw: pointer to hardware structure
* @speed: new link speed
* @autoneg: true if autonegotiation enabled
* @autoneg_wait_to_complete: true if waiting is needed to complete
*
* Restarts link on PHY and MAC based on settings passed in.
**/
static s32 ixgbe_setup_copper_link_82599(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg,
bool autoneg_wait_to_complete)
{
s32 status;
/* Setup the PHY according to input speed */
status = hw->phy.ops.setup_link_speed(hw, speed, autoneg,
autoneg_wait_to_complete);
/* Set up MAC */
ixgbe_start_mac_link_82599(hw, autoneg_wait_to_complete);
return status;
}
/**
* ixgbe_reset_hw_82599 - Perform hardware reset
* @hw: pointer to hardware structure
*
* Resets the hardware by resetting the transmit and receive units, masks
* and clears all interrupts, perform a PHY reset, and perform a link (MAC)
* reset.
**/
static s32 ixgbe_reset_hw_82599(struct ixgbe_hw *hw)
{
ixgbe_link_speed link_speed;
s32 status;
u32 ctrl, i, autoc, autoc2;
bool link_up = false;
/* Call adapter stop to disable tx/rx and clear interrupts */
status = hw->mac.ops.stop_adapter(hw);
if (status != 0)
goto reset_hw_out;
/* flush pending Tx transactions */
ixgbe_clear_tx_pending(hw);
/* PHY ops must be identified and initialized prior to reset */
/* Identify PHY and related function pointers */
status = hw->phy.ops.init(hw);
if (status == IXGBE_ERR_SFP_NOT_SUPPORTED)
goto reset_hw_out;
/* Setup SFP module if there is one present. */
if (hw->phy.sfp_setup_needed) {
status = hw->mac.ops.setup_sfp(hw);
hw->phy.sfp_setup_needed = false;
}
if (status == IXGBE_ERR_SFP_NOT_SUPPORTED)
goto reset_hw_out;
/* Reset PHY */
if (hw->phy.reset_disable == false && hw->phy.ops.reset != NULL)
hw->phy.ops.reset(hw);
mac_reset_top:
/*
* Issue global reset to the MAC. Needs to be SW reset if link is up.
* If link reset is used when link is up, it might reset the PHY when
* mng is using it. If link is down or the flag to force full link
* reset is set, then perform link reset.
*/
ctrl = IXGBE_CTRL_LNK_RST;
if (!hw->force_full_reset) {
hw->mac.ops.check_link(hw, &link_speed, &link_up, false);
if (link_up)
ctrl = IXGBE_CTRL_RST;
}
ctrl |= IXGBE_READ_REG(hw, IXGBE_CTRL);
IXGBE_WRITE_REG(hw, IXGBE_CTRL, ctrl);
IXGBE_WRITE_FLUSH(hw);
/* Poll for reset bit to self-clear indicating reset is complete */
for (i = 0; i < 10; i++) {
udelay(1);
ctrl = IXGBE_READ_REG(hw, IXGBE_CTRL);
if (!(ctrl & IXGBE_CTRL_RST_MASK))
break;
}
if (ctrl & IXGBE_CTRL_RST_MASK) {
status = IXGBE_ERR_RESET_FAILED;
hw_dbg(hw, "Reset polling failed to complete.\n");
}
msleep(50);
/*
* Double resets are required for recovery from certain error
* conditions. Between resets, it is necessary to stall to allow time
* for any pending HW events to complete.
*/
if (hw->mac.flags & IXGBE_FLAGS_DOUBLE_RESET_REQUIRED) {
hw->mac.flags &= ~IXGBE_FLAGS_DOUBLE_RESET_REQUIRED;
goto mac_reset_top;
}
/*
* Store the original AUTOC/AUTOC2 values if they have not been
* stored off yet. Otherwise restore the stored original
* values since the reset operation sets back to defaults.
*/
autoc = IXGBE_READ_REG(hw, IXGBE_AUTOC);
autoc2 = IXGBE_READ_REG(hw, IXGBE_AUTOC2);
if (hw->mac.orig_link_settings_stored == false) {
hw->mac.orig_autoc = autoc;
hw->mac.orig_autoc2 = autoc2;
hw->mac.orig_link_settings_stored = true;
} else {
if (autoc != hw->mac.orig_autoc)
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, (hw->mac.orig_autoc |
IXGBE_AUTOC_AN_RESTART));
if ((autoc2 & IXGBE_AUTOC2_UPPER_MASK) !=
(hw->mac.orig_autoc2 & IXGBE_AUTOC2_UPPER_MASK)) {
autoc2 &= ~IXGBE_AUTOC2_UPPER_MASK;
autoc2 |= (hw->mac.orig_autoc2 &
IXGBE_AUTOC2_UPPER_MASK);
IXGBE_WRITE_REG(hw, IXGBE_AUTOC2, autoc2);
}
}
/* Store the permanent mac address */
hw->mac.ops.get_mac_addr(hw, hw->mac.perm_addr);
/*
* Store MAC address from RAR0, clear receive address registers, and
* clear the multicast table. Also reset num_rar_entries to 128,
* since we modify this value when programming the SAN MAC address.
*/
hw->mac.num_rar_entries = 128;
hw->mac.ops.init_rx_addrs(hw);
/* Store the permanent SAN mac address */
hw->mac.ops.get_san_mac_addr(hw, hw->mac.san_addr);
/* Add the SAN MAC address to the RAR only if it's a valid address */
if (ixgbe_validate_mac_addr(hw->mac.san_addr) == 0) {
hw->mac.ops.set_rar(hw, hw->mac.num_rar_entries - 1,
hw->mac.san_addr, 0, IXGBE_RAH_AV);
/* Reserve the last RAR for the SAN MAC address */
hw->mac.num_rar_entries--;
}
/* Store the alternative WWNN/WWPN prefix */
hw->mac.ops.get_wwn_prefix(hw, &hw->mac.wwnn_prefix,
&hw->mac.wwpn_prefix);
reset_hw_out:
return status;
}
/**
* ixgbe_reinit_fdir_tables_82599 - Reinitialize Flow Director tables.
* @hw: pointer to hardware structure
**/
s32 ixgbe_reinit_fdir_tables_82599(struct ixgbe_hw *hw)
{
int i;
u32 fdirctrl = IXGBE_READ_REG(hw, IXGBE_FDIRCTRL);
fdirctrl &= ~IXGBE_FDIRCTRL_INIT_DONE;
/*
* Before starting reinitialization process,
* FDIRCMD.CMD must be zero.
*/
for (i = 0; i < IXGBE_FDIRCMD_CMD_POLL; i++) {
if (!(IXGBE_READ_REG(hw, IXGBE_FDIRCMD) &
IXGBE_FDIRCMD_CMD_MASK))
break;
udelay(10);
}
if (i >= IXGBE_FDIRCMD_CMD_POLL) {
hw_dbg(hw, "Flow Director previous command isn't complete, "
"aborting table re-initialization.\n");
return IXGBE_ERR_FDIR_REINIT_FAILED;
}
IXGBE_WRITE_REG(hw, IXGBE_FDIRFREE, 0);
IXGBE_WRITE_FLUSH(hw);
/*
* 82599 adapters flow director init flow cannot be restarted,
* Workaround 82599 silicon errata by performing the following steps
* before re-writing the FDIRCTRL control register with the same value.
* - write 1 to bit 8 of FDIRCMD register &
* - write 0 to bit 8 of FDIRCMD register
*/
IXGBE_WRITE_REG(hw, IXGBE_FDIRCMD,
(IXGBE_READ_REG(hw, IXGBE_FDIRCMD) |
IXGBE_FDIRCMD_CLEARHT));
IXGBE_WRITE_FLUSH(hw);
IXGBE_WRITE_REG(hw, IXGBE_FDIRCMD,
(IXGBE_READ_REG(hw, IXGBE_FDIRCMD) &
~IXGBE_FDIRCMD_CLEARHT));
IXGBE_WRITE_FLUSH(hw);
/*
* Clear FDIR Hash register to clear any leftover hashes
* waiting to be programmed.
*/
IXGBE_WRITE_REG(hw, IXGBE_FDIRHASH, 0x00);
IXGBE_WRITE_FLUSH(hw);
IXGBE_WRITE_REG(hw, IXGBE_FDIRCTRL, fdirctrl);
IXGBE_WRITE_FLUSH(hw);
/* Poll init-done after we write FDIRCTRL register */
for (i = 0; i < IXGBE_FDIR_INIT_DONE_POLL; i++) {
if (IXGBE_READ_REG(hw, IXGBE_FDIRCTRL) &
IXGBE_FDIRCTRL_INIT_DONE)
break;
udelay(10);
}
if (i >= IXGBE_FDIR_INIT_DONE_POLL) {
hw_dbg(hw, "Flow Director Signature poll time exceeded!\n");
return IXGBE_ERR_FDIR_REINIT_FAILED;
}
/* Clear FDIR statistics registers (read to clear) */
IXGBE_READ_REG(hw, IXGBE_FDIRUSTAT);
IXGBE_READ_REG(hw, IXGBE_FDIRFSTAT);
IXGBE_READ_REG(hw, IXGBE_FDIRMATCH);
IXGBE_READ_REG(hw, IXGBE_FDIRMISS);
IXGBE_READ_REG(hw, IXGBE_FDIRLEN);
return 0;
}
/**
* ixgbe_fdir_enable_82599 - Initialize Flow Director control registers
* @hw: pointer to hardware structure
* @fdirctrl: value to write to flow director control register
**/
static void ixgbe_fdir_enable_82599(struct ixgbe_hw *hw, u32 fdirctrl)
{
int i;
/* Prime the keys for hashing */
IXGBE_WRITE_REG(hw, IXGBE_FDIRHKEY, IXGBE_ATR_BUCKET_HASH_KEY);
IXGBE_WRITE_REG(hw, IXGBE_FDIRSKEY, IXGBE_ATR_SIGNATURE_HASH_KEY);
/*
* Poll init-done after we write the register. Estimated times:
* 10G: PBALLOC = 11b, timing is 60us
* 1G: PBALLOC = 11b, timing is 600us
* 100M: PBALLOC = 11b, timing is 6ms
*
* Multiple these timings by 4 if under full Rx load
*
* So we'll poll for IXGBE_FDIR_INIT_DONE_POLL times, sleeping for
* 1 msec per poll time. If we're at line rate and drop to 100M, then
* this might not finish in our poll time, but we can live with that
* for now.
*/
IXGBE_WRITE_REG(hw, IXGBE_FDIRCTRL, fdirctrl);
IXGBE_WRITE_FLUSH(hw);
for (i = 0; i < IXGBE_FDIR_INIT_DONE_POLL; i++) {
if (IXGBE_READ_REG(hw, IXGBE_FDIRCTRL) &
IXGBE_FDIRCTRL_INIT_DONE)
break;
usleep_range(1000, 2000);
}
if (i >= IXGBE_FDIR_INIT_DONE_POLL)
hw_dbg(hw, "Flow Director poll time exceeded!\n");
}
/**
* ixgbe_init_fdir_signature_82599 - Initialize Flow Director signature filters
* @hw: pointer to hardware structure
* @fdirctrl: value to write to flow director control register, initially
* contains just the value of the Rx packet buffer allocation
**/
s32 ixgbe_init_fdir_signature_82599(struct ixgbe_hw *hw, u32 fdirctrl)
{
/*
* Continue setup of fdirctrl register bits:
* Move the flexible bytes to use the ethertype - shift 6 words
* Set the maximum length per hash bucket to 0xA filters
* Send interrupt when 64 filters are left
*/
fdirctrl |= (0x6 << IXGBE_FDIRCTRL_FLEX_SHIFT) |
(0xA << IXGBE_FDIRCTRL_MAX_LENGTH_SHIFT) |
(4 << IXGBE_FDIRCTRL_FULL_THRESH_SHIFT);
/* write hashes and fdirctrl register, poll for completion */
ixgbe_fdir_enable_82599(hw, fdirctrl);
return 0;
}
/**
* ixgbe_init_fdir_perfect_82599 - Initialize Flow Director perfect filters
* @hw: pointer to hardware structure
* @fdirctrl: value to write to flow director control register, initially
* contains just the value of the Rx packet buffer allocation
**/
s32 ixgbe_init_fdir_perfect_82599(struct ixgbe_hw *hw, u32 fdirctrl)
{
/*
* Continue setup of fdirctrl register bits:
* Turn perfect match filtering on
* Report hash in RSS field of Rx wb descriptor
* Initialize the drop queue
* Move the flexible bytes to use the ethertype - shift 6 words
* Set the maximum length per hash bucket to 0xA filters
* Send interrupt when 64 (0x4 * 16) filters are left
*/
fdirctrl |= IXGBE_FDIRCTRL_PERFECT_MATCH |
IXGBE_FDIRCTRL_REPORT_STATUS |
(IXGBE_FDIR_DROP_QUEUE << IXGBE_FDIRCTRL_DROP_Q_SHIFT) |
(0x6 << IXGBE_FDIRCTRL_FLEX_SHIFT) |
(0xA << IXGBE_FDIRCTRL_MAX_LENGTH_SHIFT) |
(4 << IXGBE_FDIRCTRL_FULL_THRESH_SHIFT);
/* write hashes and fdirctrl register, poll for completion */
ixgbe_fdir_enable_82599(hw, fdirctrl);
return 0;
}
/*
* These defines allow us to quickly generate all of the necessary instructions
* in the function below by simply calling out IXGBE_COMPUTE_SIG_HASH_ITERATION
* for values 0 through 15
*/
#define IXGBE_ATR_COMMON_HASH_KEY \
(IXGBE_ATR_BUCKET_HASH_KEY & IXGBE_ATR_SIGNATURE_HASH_KEY)
#define IXGBE_COMPUTE_SIG_HASH_ITERATION(_n) \
do { \
u32 n = (_n); \
if (IXGBE_ATR_COMMON_HASH_KEY & (0x01 << n)) \
common_hash ^= lo_hash_dword >> n; \
else if (IXGBE_ATR_BUCKET_HASH_KEY & (0x01 << n)) \
bucket_hash ^= lo_hash_dword >> n; \
else if (IXGBE_ATR_SIGNATURE_HASH_KEY & (0x01 << n)) \
sig_hash ^= lo_hash_dword << (16 - n); \
if (IXGBE_ATR_COMMON_HASH_KEY & (0x01 << (n + 16))) \
common_hash ^= hi_hash_dword >> n; \
else if (IXGBE_ATR_BUCKET_HASH_KEY & (0x01 << (n + 16))) \
bucket_hash ^= hi_hash_dword >> n; \
else if (IXGBE_ATR_SIGNATURE_HASH_KEY & (0x01 << (n + 16))) \
sig_hash ^= hi_hash_dword << (16 - n); \
} while (0);
/**
* ixgbe_atr_compute_sig_hash_82599 - Compute the signature hash
* @stream: input bitstream to compute the hash on
*
* This function is almost identical to the function above but contains
* several optomizations such as unwinding all of the loops, letting the
* compiler work out all of the conditional ifs since the keys are static
* defines, and computing two keys at once since the hashed dword stream
* will be the same for both keys.
**/
static u32 ixgbe_atr_compute_sig_hash_82599(union ixgbe_atr_hash_dword input,
union ixgbe_atr_hash_dword common)
{
u32 hi_hash_dword, lo_hash_dword, flow_vm_vlan;
u32 sig_hash = 0, bucket_hash = 0, common_hash = 0;
/* record the flow_vm_vlan bits as they are a key part to the hash */
flow_vm_vlan = ntohl(input.dword);
/* generate common hash dword */
hi_hash_dword = ntohl(common.dword);
/* low dword is word swapped version of common */
lo_hash_dword = (hi_hash_dword >> 16) | (hi_hash_dword << 16);
/* apply flow ID/VM pool/VLAN ID bits to hash words */
hi_hash_dword ^= flow_vm_vlan ^ (flow_vm_vlan >> 16);
/* Process bits 0 and 16 */
IXGBE_COMPUTE_SIG_HASH_ITERATION(0);
/*
* apply flow ID/VM pool/VLAN ID bits to lo hash dword, we had to
* delay this because bit 0 of the stream should not be processed
* so we do not add the vlan until after bit 0 was processed
*/
lo_hash_dword ^= flow_vm_vlan ^ (flow_vm_vlan << 16);
/* Process remaining 30 bit of the key */
IXGBE_COMPUTE_SIG_HASH_ITERATION(1);
IXGBE_COMPUTE_SIG_HASH_ITERATION(2);
IXGBE_COMPUTE_SIG_HASH_ITERATION(3);
IXGBE_COMPUTE_SIG_HASH_ITERATION(4);
IXGBE_COMPUTE_SIG_HASH_ITERATION(5);
IXGBE_COMPUTE_SIG_HASH_ITERATION(6);
IXGBE_COMPUTE_SIG_HASH_ITERATION(7);
IXGBE_COMPUTE_SIG_HASH_ITERATION(8);
IXGBE_COMPUTE_SIG_HASH_ITERATION(9);
IXGBE_COMPUTE_SIG_HASH_ITERATION(10);
IXGBE_COMPUTE_SIG_HASH_ITERATION(11);
IXGBE_COMPUTE_SIG_HASH_ITERATION(12);
IXGBE_COMPUTE_SIG_HASH_ITERATION(13);
IXGBE_COMPUTE_SIG_HASH_ITERATION(14);
IXGBE_COMPUTE_SIG_HASH_ITERATION(15);
/* combine common_hash result with signature and bucket hashes */
bucket_hash ^= common_hash;
bucket_hash &= IXGBE_ATR_HASH_MASK;
sig_hash ^= common_hash << 16;
sig_hash &= IXGBE_ATR_HASH_MASK << 16;
/* return completed signature hash */
return sig_hash ^ bucket_hash;
}
/**
* ixgbe_atr_add_signature_filter_82599 - Adds a signature hash filter
* @hw: pointer to hardware structure
* @input: unique input dword
* @common: compressed common input dword
* @queue: queue index to direct traffic to
**/
s32 ixgbe_fdir_add_signature_filter_82599(struct ixgbe_hw *hw,
union ixgbe_atr_hash_dword input,
union ixgbe_atr_hash_dword common,
u8 queue)
{
u64 fdirhashcmd;
u32 fdircmd;
/*
* Get the flow_type in order to program FDIRCMD properly
* lowest 2 bits are FDIRCMD.L4TYPE, third lowest bit is FDIRCMD.IPV6
*/
switch (input.formatted.flow_type) {
case IXGBE_ATR_FLOW_TYPE_TCPV4:
case IXGBE_ATR_FLOW_TYPE_UDPV4:
case IXGBE_ATR_FLOW_TYPE_SCTPV4:
case IXGBE_ATR_FLOW_TYPE_TCPV6:
case IXGBE_ATR_FLOW_TYPE_UDPV6:
case IXGBE_ATR_FLOW_TYPE_SCTPV6:
break;
default:
hw_dbg(hw, " Error on flow type input\n");
return IXGBE_ERR_CONFIG;
}
/* configure FDIRCMD register */
fdircmd = IXGBE_FDIRCMD_CMD_ADD_FLOW | IXGBE_FDIRCMD_FILTER_UPDATE |
IXGBE_FDIRCMD_LAST | IXGBE_FDIRCMD_QUEUE_EN;
fdircmd |= input.formatted.flow_type << IXGBE_FDIRCMD_FLOW_TYPE_SHIFT;
fdircmd |= (u32)queue << IXGBE_FDIRCMD_RX_QUEUE_SHIFT;
/*
* The lower 32-bits of fdirhashcmd is for FDIRHASH, the upper 32-bits
* is for FDIRCMD. Then do a 64-bit register write from FDIRHASH.
*/
fdirhashcmd = (u64)fdircmd << 32;
fdirhashcmd |= ixgbe_atr_compute_sig_hash_82599(input, common);
IXGBE_WRITE_REG64(hw, IXGBE_FDIRHASH, fdirhashcmd);
hw_dbg(hw, "Tx Queue=%x hash=%x\n", queue, (u32)fdirhashcmd);
return 0;
}
#define IXGBE_COMPUTE_BKT_HASH_ITERATION(_n) \
do { \
u32 n = (_n); \
if (IXGBE_ATR_BUCKET_HASH_KEY & (0x01 << n)) \
bucket_hash ^= lo_hash_dword >> n; \
if (IXGBE_ATR_BUCKET_HASH_KEY & (0x01 << (n + 16))) \
bucket_hash ^= hi_hash_dword >> n; \
} while (0);
/**
* ixgbe_atr_compute_perfect_hash_82599 - Compute the perfect filter hash
* @atr_input: input bitstream to compute the hash on
* @input_mask: mask for the input bitstream
*
* This function serves two main purposes. First it applys the input_mask
* to the atr_input resulting in a cleaned up atr_input data stream.
* Secondly it computes the hash and stores it in the bkt_hash field at
* the end of the input byte stream. This way it will be available for
* future use without needing to recompute the hash.
**/
void ixgbe_atr_compute_perfect_hash_82599(union ixgbe_atr_input *input,
union ixgbe_atr_input *input_mask)
{
u32 hi_hash_dword, lo_hash_dword, flow_vm_vlan;
u32 bucket_hash = 0;
/* Apply masks to input data */
input->dword_stream[0] &= input_mask->dword_stream[0];
input->dword_stream[1] &= input_mask->dword_stream[1];
input->dword_stream[2] &= input_mask->dword_stream[2];
input->dword_stream[3] &= input_mask->dword_stream[3];
input->dword_stream[4] &= input_mask->dword_stream[4];
input->dword_stream[5] &= input_mask->dword_stream[5];
input->dword_stream[6] &= input_mask->dword_stream[6];
input->dword_stream[7] &= input_mask->dword_stream[7];
input->dword_stream[8] &= input_mask->dword_stream[8];
input->dword_stream[9] &= input_mask->dword_stream[9];
input->dword_stream[10] &= input_mask->dword_stream[10];
/* record the flow_vm_vlan bits as they are a key part to the hash */
flow_vm_vlan = ntohl(input->dword_stream[0]);
/* generate common hash dword */
hi_hash_dword = ntohl(input->dword_stream[1] ^
input->dword_stream[2] ^
input->dword_stream[3] ^
input->dword_stream[4] ^
input->dword_stream[5] ^
input->dword_stream[6] ^
input->dword_stream[7] ^
input->dword_stream[8] ^
input->dword_stream[9] ^
input->dword_stream[10]);
/* low dword is word swapped version of common */
lo_hash_dword = (hi_hash_dword >> 16) | (hi_hash_dword << 16);
/* apply flow ID/VM pool/VLAN ID bits to hash words */
hi_hash_dword ^= flow_vm_vlan ^ (flow_vm_vlan >> 16);
/* Process bits 0 and 16 */
IXGBE_COMPUTE_BKT_HASH_ITERATION(0);
/*
* apply flow ID/VM pool/VLAN ID bits to lo hash dword, we had to
* delay this because bit 0 of the stream should not be processed
* so we do not add the vlan until after bit 0 was processed
*/
lo_hash_dword ^= flow_vm_vlan ^ (flow_vm_vlan << 16);
/* Process remaining 30 bit of the key */
IXGBE_COMPUTE_BKT_HASH_ITERATION(1);
IXGBE_COMPUTE_BKT_HASH_ITERATION(2);
IXGBE_COMPUTE_BKT_HASH_ITERATION(3);
IXGBE_COMPUTE_BKT_HASH_ITERATION(4);
IXGBE_COMPUTE_BKT_HASH_ITERATION(5);
IXGBE_COMPUTE_BKT_HASH_ITERATION(6);
IXGBE_COMPUTE_BKT_HASH_ITERATION(7);
IXGBE_COMPUTE_BKT_HASH_ITERATION(8);
IXGBE_COMPUTE_BKT_HASH_ITERATION(9);
IXGBE_COMPUTE_BKT_HASH_ITERATION(10);
IXGBE_COMPUTE_BKT_HASH_ITERATION(11);
IXGBE_COMPUTE_BKT_HASH_ITERATION(12);
IXGBE_COMPUTE_BKT_HASH_ITERATION(13);
IXGBE_COMPUTE_BKT_HASH_ITERATION(14);
IXGBE_COMPUTE_BKT_HASH_ITERATION(15);
/*
* Limit hash to 13 bits since max bucket count is 8K.
* Store result at the end of the input stream.
*/
input->formatted.bkt_hash = bucket_hash & 0x1FFF;
}
/**
* ixgbe_get_fdirtcpm_82599 - generate a tcp port from atr_input_masks
* @input_mask: mask to be bit swapped
*
* The source and destination port masks for flow director are bit swapped
* in that bit 15 effects bit 0, 14 effects 1, 13, 2 etc. In order to
* generate a correctly swapped value we need to bit swap the mask and that
* is what is accomplished by this function.
**/
static u32 ixgbe_get_fdirtcpm_82599(union ixgbe_atr_input *input_mask)
{
u32 mask = ntohs(input_mask->formatted.dst_port);
mask <<= IXGBE_FDIRTCPM_DPORTM_SHIFT;
mask |= ntohs(input_mask->formatted.src_port);
mask = ((mask & 0x55555555) << 1) | ((mask & 0xAAAAAAAA) >> 1);
mask = ((mask & 0x33333333) << 2) | ((mask & 0xCCCCCCCC) >> 2);
mask = ((mask & 0x0F0F0F0F) << 4) | ((mask & 0xF0F0F0F0) >> 4);
return ((mask & 0x00FF00FF) << 8) | ((mask & 0xFF00FF00) >> 8);
}
/*
* These two macros are meant to address the fact that we have registers
* that are either all or in part big-endian. As a result on big-endian
* systems we will end up byte swapping the value to little-endian before
* it is byte swapped again and written to the hardware in the original
* big-endian format.
*/
#define IXGBE_STORE_AS_BE32(_value) \
(((u32)(_value) >> 24) | (((u32)(_value) & 0x00FF0000) >> 8) | \
(((u32)(_value) & 0x0000FF00) << 8) | ((u32)(_value) << 24))
#define IXGBE_WRITE_REG_BE32(a, reg, value) \
IXGBE_WRITE_REG((a), (reg), IXGBE_STORE_AS_BE32(ntohl(value)))
#define IXGBE_STORE_AS_BE16(_value) \
ntohs(((u16)(_value) >> 8) | ((u16)(_value) << 8))
s32 ixgbe_fdir_set_input_mask_82599(struct ixgbe_hw *hw,
union ixgbe_atr_input *input_mask)
{
/* mask IPv6 since it is currently not supported */
u32 fdirm = IXGBE_FDIRM_DIPv6;
u32 fdirtcpm;
/*
* Program the relevant mask registers. If src/dst_port or src/dst_addr
* are zero, then assume a full mask for that field. Also assume that
* a VLAN of 0 is unspecified, so mask that out as well. L4type
* cannot be masked out in this implementation.
*
* This also assumes IPv4 only. IPv6 masking isn't supported at this
* point in time.
*/
/* verify bucket hash is cleared on hash generation */
if (input_mask->formatted.bkt_hash)
hw_dbg(hw, " bucket hash should always be 0 in mask\n");
/* Program FDIRM and verify partial masks */
switch (input_mask->formatted.vm_pool & 0x7F) {
case 0x0:
fdirm |= IXGBE_FDIRM_POOL;
case 0x7F:
break;
default:
hw_dbg(hw, " Error on vm pool mask\n");
return IXGBE_ERR_CONFIG;
}
switch (input_mask->formatted.flow_type & IXGBE_ATR_L4TYPE_MASK) {
case 0x0:
fdirm |= IXGBE_FDIRM_L4P;
if (input_mask->formatted.dst_port ||
input_mask->formatted.src_port) {
hw_dbg(hw, " Error on src/dst port mask\n");
return IXGBE_ERR_CONFIG;
}
case IXGBE_ATR_L4TYPE_MASK:
break;
default:
hw_dbg(hw, " Error on flow type mask\n");
return IXGBE_ERR_CONFIG;
}
switch (ntohs(input_mask->formatted.vlan_id) & 0xEFFF) {
case 0x0000:
/* mask VLAN ID, fall through to mask VLAN priority */
fdirm |= IXGBE_FDIRM_VLANID;
case 0x0FFF:
/* mask VLAN priority */
fdirm |= IXGBE_FDIRM_VLANP;
break;
case 0xE000:
/* mask VLAN ID only, fall through */
fdirm |= IXGBE_FDIRM_VLANID;
case 0xEFFF:
/* no VLAN fields masked */
break;
default:
hw_dbg(hw, " Error on VLAN mask\n");
return IXGBE_ERR_CONFIG;
}
switch (input_mask->formatted.flex_bytes & 0xFFFF) {
case 0x0000:
/* Mask Flex Bytes, fall through */
fdirm |= IXGBE_FDIRM_FLEX;
case 0xFFFF:
break;
default:
hw_dbg(hw, " Error on flexible byte mask\n");
return IXGBE_ERR_CONFIG;
}
/* Now mask VM pool and destination IPv6 - bits 5 and 2 */
IXGBE_WRITE_REG(hw, IXGBE_FDIRM, fdirm);
/* store the TCP/UDP port masks, bit reversed from port layout */
fdirtcpm = ixgbe_get_fdirtcpm_82599(input_mask);
/* write both the same so that UDP and TCP use the same mask */
IXGBE_WRITE_REG(hw, IXGBE_FDIRTCPM, ~fdirtcpm);
IXGBE_WRITE_REG(hw, IXGBE_FDIRUDPM, ~fdirtcpm);
/* store source and destination IP masks (big-enian) */
IXGBE_WRITE_REG_BE32(hw, IXGBE_FDIRSIP4M,
~input_mask->formatted.src_ip[0]);
IXGBE_WRITE_REG_BE32(hw, IXGBE_FDIRDIP4M,
~input_mask->formatted.dst_ip[0]);
return 0;
}
s32 ixgbe_fdir_write_perfect_filter_82599(struct ixgbe_hw *hw,
union ixgbe_atr_input *input,
u16 soft_id, u8 queue)
{
u32 fdirport, fdirvlan, fdirhash, fdircmd;
/* currently IPv6 is not supported, must be programmed with 0 */
IXGBE_WRITE_REG_BE32(hw, IXGBE_FDIRSIPv6(0),
input->formatted.src_ip[0]);
IXGBE_WRITE_REG_BE32(hw, IXGBE_FDIRSIPv6(1),
input->formatted.src_ip[1]);
IXGBE_WRITE_REG_BE32(hw, IXGBE_FDIRSIPv6(2),
input->formatted.src_ip[2]);
/* record the source address (big-endian) */
IXGBE_WRITE_REG_BE32(hw, IXGBE_FDIRIPSA, input->formatted.src_ip[0]);
/* record the first 32 bits of the destination address (big-endian) */
IXGBE_WRITE_REG_BE32(hw, IXGBE_FDIRIPDA, input->formatted.dst_ip[0]);
/* record source and destination port (little-endian)*/
fdirport = ntohs(input->formatted.dst_port);
fdirport <<= IXGBE_FDIRPORT_DESTINATION_SHIFT;
fdirport |= ntohs(input->formatted.src_port);
IXGBE_WRITE_REG(hw, IXGBE_FDIRPORT, fdirport);
/* record vlan (little-endian) and flex_bytes(big-endian) */
fdirvlan = IXGBE_STORE_AS_BE16(input->formatted.flex_bytes);
fdirvlan <<= IXGBE_FDIRVLAN_FLEX_SHIFT;
fdirvlan |= ntohs(input->formatted.vlan_id);
IXGBE_WRITE_REG(hw, IXGBE_FDIRVLAN, fdirvlan);
/* configure FDIRHASH register */
fdirhash = input->formatted.bkt_hash;
fdirhash |= soft_id << IXGBE_FDIRHASH_SIG_SW_INDEX_SHIFT;
IXGBE_WRITE_REG(hw, IXGBE_FDIRHASH, fdirhash);
/*
* flush all previous writes to make certain registers are
* programmed prior to issuing the command
*/
IXGBE_WRITE_FLUSH(hw);
/* configure FDIRCMD register */
fdircmd = IXGBE_FDIRCMD_CMD_ADD_FLOW | IXGBE_FDIRCMD_FILTER_UPDATE |
IXGBE_FDIRCMD_LAST | IXGBE_FDIRCMD_QUEUE_EN;
if (queue == IXGBE_FDIR_DROP_QUEUE)
fdircmd |= IXGBE_FDIRCMD_DROP;
fdircmd |= input->formatted.flow_type << IXGBE_FDIRCMD_FLOW_TYPE_SHIFT;
fdircmd |= (u32)queue << IXGBE_FDIRCMD_RX_QUEUE_SHIFT;
fdircmd |= (u32)input->formatted.vm_pool << IXGBE_FDIRCMD_VT_POOL_SHIFT;
IXGBE_WRITE_REG(hw, IXGBE_FDIRCMD, fdircmd);
return 0;
}
s32 ixgbe_fdir_erase_perfect_filter_82599(struct ixgbe_hw *hw,
union ixgbe_atr_input *input,
u16 soft_id)
{
u32 fdirhash;
u32 fdircmd = 0;
u32 retry_count;
s32 err = 0;
/* configure FDIRHASH register */
fdirhash = input->formatted.bkt_hash;
fdirhash |= soft_id << IXGBE_FDIRHASH_SIG_SW_INDEX_SHIFT;
IXGBE_WRITE_REG(hw, IXGBE_FDIRHASH, fdirhash);
/* flush hash to HW */
IXGBE_WRITE_FLUSH(hw);
/* Query if filter is present */
IXGBE_WRITE_REG(hw, IXGBE_FDIRCMD, IXGBE_FDIRCMD_CMD_QUERY_REM_FILT);
for (retry_count = 10; retry_count; retry_count--) {
/* allow 10us for query to process */
udelay(10);
/* verify query completed successfully */
fdircmd = IXGBE_READ_REG(hw, IXGBE_FDIRCMD);
if (!(fdircmd & IXGBE_FDIRCMD_CMD_MASK))
break;
}
if (!retry_count)
err = IXGBE_ERR_FDIR_REINIT_FAILED;
/* if filter exists in hardware then remove it */
if (fdircmd & IXGBE_FDIRCMD_FILTER_VALID) {
IXGBE_WRITE_REG(hw, IXGBE_FDIRHASH, fdirhash);
IXGBE_WRITE_FLUSH(hw);
IXGBE_WRITE_REG(hw, IXGBE_FDIRCMD,
IXGBE_FDIRCMD_CMD_REMOVE_FLOW);
}
return err;
}
/**
* ixgbe_read_analog_reg8_82599 - Reads 8 bit Omer analog register
* @hw: pointer to hardware structure
* @reg: analog register to read
* @val: read value
*
* Performs read operation to Omer analog register specified.
**/
static s32 ixgbe_read_analog_reg8_82599(struct ixgbe_hw *hw, u32 reg, u8 *val)
{
u32 core_ctl;
IXGBE_WRITE_REG(hw, IXGBE_CORECTL, IXGBE_CORECTL_WRITE_CMD |
(reg << 8));
IXGBE_WRITE_FLUSH(hw);
udelay(10);
core_ctl = IXGBE_READ_REG(hw, IXGBE_CORECTL);
*val = (u8)core_ctl;
return 0;
}
/**
* ixgbe_write_analog_reg8_82599 - Writes 8 bit Omer analog register
* @hw: pointer to hardware structure
* @reg: atlas register to write
* @val: value to write
*
* Performs write operation to Omer analog register specified.
**/
static s32 ixgbe_write_analog_reg8_82599(struct ixgbe_hw *hw, u32 reg, u8 val)
{
u32 core_ctl;
core_ctl = (reg << 8) | val;
IXGBE_WRITE_REG(hw, IXGBE_CORECTL, core_ctl);
IXGBE_WRITE_FLUSH(hw);
udelay(10);
return 0;
}
/**
* ixgbe_start_hw_82599 - Prepare hardware for Tx/Rx
* @hw: pointer to hardware structure
*
* Starts the hardware using the generic start_hw function
* and the generation start_hw function.
* Then performs revision-specific operations, if any.
**/
static s32 ixgbe_start_hw_82599(struct ixgbe_hw *hw)
{
s32 ret_val = 0;
ret_val = ixgbe_start_hw_generic(hw);
if (ret_val != 0)
goto out;
ret_val = ixgbe_start_hw_gen2(hw);
if (ret_val != 0)
goto out;
/* We need to run link autotry after the driver loads */
hw->mac.autotry_restart = true;
hw->mac.rx_pb_size = IXGBE_82599_RX_PB_SIZE;
if (ret_val == 0)
ret_val = ixgbe_verify_fw_version_82599(hw);
out:
return ret_val;
}
/**
* ixgbe_identify_phy_82599 - Get physical layer module
* @hw: pointer to hardware structure
*
* Determines the physical layer module found on the current adapter.
* If PHY already detected, maintains current PHY type in hw struct,
* otherwise executes the PHY detection routine.
**/
static s32 ixgbe_identify_phy_82599(struct ixgbe_hw *hw)
{
s32 status = IXGBE_ERR_PHY_ADDR_INVALID;
/* Detect PHY if not unknown - returns success if already detected. */
status = ixgbe_identify_phy_generic(hw);
if (status != 0) {
/* 82599 10GBASE-T requires an external PHY */
if (hw->mac.ops.get_media_type(hw) == ixgbe_media_type_copper)
goto out;
else
status = ixgbe_identify_sfp_module_generic(hw);
}
/* Set PHY type none if no PHY detected */
if (hw->phy.type == ixgbe_phy_unknown) {
hw->phy.type = ixgbe_phy_none;
status = 0;
}
/* Return error if SFP module has been detected but is not supported */
if (hw->phy.type == ixgbe_phy_sfp_unsupported)
status = IXGBE_ERR_SFP_NOT_SUPPORTED;
out:
return status;
}
/**
* ixgbe_get_supported_physical_layer_82599 - Returns physical layer type
* @hw: pointer to hardware structure
*
* Determines physical layer capabilities of the current configuration.
**/
static u32 ixgbe_get_supported_physical_layer_82599(struct ixgbe_hw *hw)
{
u32 physical_layer = IXGBE_PHYSICAL_LAYER_UNKNOWN;
u32 autoc = IXGBE_READ_REG(hw, IXGBE_AUTOC);
u32 autoc2 = IXGBE_READ_REG(hw, IXGBE_AUTOC2);
u32 pma_pmd_10g_serial = autoc2 & IXGBE_AUTOC2_10G_SERIAL_PMA_PMD_MASK;
u32 pma_pmd_10g_parallel = autoc & IXGBE_AUTOC_10G_PMA_PMD_MASK;
u32 pma_pmd_1g = autoc & IXGBE_AUTOC_1G_PMA_PMD_MASK;
u16 ext_ability = 0;
u8 comp_codes_10g = 0;
u8 comp_codes_1g = 0;
hw->phy.ops.identify(hw);
switch (hw->phy.type) {
case ixgbe_phy_tn:
case ixgbe_phy_cu_unknown:
hw->phy.ops.read_reg(hw, MDIO_PMA_EXTABLE, MDIO_MMD_PMAPMD,
&ext_ability);
if (ext_ability & MDIO_PMA_EXTABLE_10GBT)
physical_layer |= IXGBE_PHYSICAL_LAYER_10GBASE_T;
if (ext_ability & MDIO_PMA_EXTABLE_1000BT)
physical_layer |= IXGBE_PHYSICAL_LAYER_1000BASE_T;
if (ext_ability & MDIO_PMA_EXTABLE_100BTX)
physical_layer |= IXGBE_PHYSICAL_LAYER_100BASE_TX;
goto out;
default:
break;
}
switch (autoc & IXGBE_AUTOC_LMS_MASK) {
case IXGBE_AUTOC_LMS_1G_AN:
case IXGBE_AUTOC_LMS_1G_LINK_NO_AN:
if (pma_pmd_1g == IXGBE_AUTOC_1G_KX_BX) {
physical_layer = IXGBE_PHYSICAL_LAYER_1000BASE_KX |
IXGBE_PHYSICAL_LAYER_1000BASE_BX;
goto out;
} else
/* SFI mode so read SFP module */
goto sfp_check;
break;
case IXGBE_AUTOC_LMS_10G_LINK_NO_AN:
if (pma_pmd_10g_parallel == IXGBE_AUTOC_10G_CX4)
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_CX4;
else if (pma_pmd_10g_parallel == IXGBE_AUTOC_10G_KX4)
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_KX4;
else if (pma_pmd_10g_parallel == IXGBE_AUTOC_10G_XAUI)
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_XAUI;
goto out;
break;
case IXGBE_AUTOC_LMS_10G_SERIAL:
if (pma_pmd_10g_serial == IXGBE_AUTOC2_10G_KR) {
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_KR;
goto out;
} else if (pma_pmd_10g_serial == IXGBE_AUTOC2_10G_SFI)
goto sfp_check;
break;
case IXGBE_AUTOC_LMS_KX4_KX_KR:
case IXGBE_AUTOC_LMS_KX4_KX_KR_1G_AN:
if (autoc & IXGBE_AUTOC_KX_SUPP)
physical_layer |= IXGBE_PHYSICAL_LAYER_1000BASE_KX;
if (autoc & IXGBE_AUTOC_KX4_SUPP)
physical_layer |= IXGBE_PHYSICAL_LAYER_10GBASE_KX4;
if (autoc & IXGBE_AUTOC_KR_SUPP)
physical_layer |= IXGBE_PHYSICAL_LAYER_10GBASE_KR;
goto out;
break;
default:
goto out;
break;
}
sfp_check:
/* SFP check must be done last since DA modules are sometimes used to
* test KR mode - we need to id KR mode correctly before SFP module.
* Call identify_sfp because the pluggable module may have changed */
hw->phy.ops.identify_sfp(hw);
if (hw->phy.sfp_type == ixgbe_sfp_type_not_present)
goto out;
switch (hw->phy.type) {
case ixgbe_phy_sfp_passive_tyco:
case ixgbe_phy_sfp_passive_unknown:
physical_layer = IXGBE_PHYSICAL_LAYER_SFP_PLUS_CU;
break;
case ixgbe_phy_sfp_ftl_active:
case ixgbe_phy_sfp_active_unknown:
physical_layer = IXGBE_PHYSICAL_LAYER_SFP_ACTIVE_DA;
break;
case ixgbe_phy_sfp_avago:
case ixgbe_phy_sfp_ftl:
case ixgbe_phy_sfp_intel:
case ixgbe_phy_sfp_unknown:
hw->phy.ops.read_i2c_eeprom(hw,
IXGBE_SFF_1GBE_COMP_CODES, &comp_codes_1g);
hw->phy.ops.read_i2c_eeprom(hw,
IXGBE_SFF_10GBE_COMP_CODES, &comp_codes_10g);
if (comp_codes_10g & IXGBE_SFF_10GBASESR_CAPABLE)
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_SR;
else if (comp_codes_10g & IXGBE_SFF_10GBASELR_CAPABLE)
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_LR;
else if (comp_codes_1g & IXGBE_SFF_1GBASET_CAPABLE)
physical_layer = IXGBE_PHYSICAL_LAYER_1000BASE_T;
break;
default:
break;
}
out:
return physical_layer;
}
/**
* ixgbe_enable_rx_dma_82599 - Enable the Rx DMA unit on 82599
* @hw: pointer to hardware structure
* @regval: register value to write to RXCTRL
*
* Enables the Rx DMA unit for 82599
**/
static s32 ixgbe_enable_rx_dma_82599(struct ixgbe_hw *hw, u32 regval)
{
/*
* Workaround for 82599 silicon errata when enabling the Rx datapath.
* If traffic is incoming before we enable the Rx unit, it could hang
* the Rx DMA unit. Therefore, make sure the security engine is
* completely disabled prior to enabling the Rx unit.
*/
hw->mac.ops.disable_rx_buff(hw);
IXGBE_WRITE_REG(hw, IXGBE_RXCTRL, regval);
hw->mac.ops.enable_rx_buff(hw);
return 0;
}
/**
* ixgbe_verify_fw_version_82599 - verify fw version for 82599
* @hw: pointer to hardware structure
*
* Verifies that installed the firmware version is 0.6 or higher
* for SFI devices. All 82599 SFI devices should have version 0.6 or higher.
*
* Returns IXGBE_ERR_EEPROM_VERSION if the FW is not present or
* if the FW version is not supported.
**/
static s32 ixgbe_verify_fw_version_82599(struct ixgbe_hw *hw)
{
s32 status = IXGBE_ERR_EEPROM_VERSION;
u16 fw_offset, fw_ptp_cfg_offset;
u16 fw_version = 0;
/* firmware check is only necessary for SFI devices */
if (hw->phy.media_type != ixgbe_media_type_fiber) {
status = 0;
goto fw_version_out;
}
/* get the offset to the Firmware Module block */
hw->eeprom.ops.read(hw, IXGBE_FW_PTR, &fw_offset);
if ((fw_offset == 0) || (fw_offset == 0xFFFF))
goto fw_version_out;
/* get the offset to the Pass Through Patch Configuration block */
hw->eeprom.ops.read(hw, (fw_offset +
IXGBE_FW_PASSTHROUGH_PATCH_CONFIG_PTR),
&fw_ptp_cfg_offset);
if ((fw_ptp_cfg_offset == 0) || (fw_ptp_cfg_offset == 0xFFFF))
goto fw_version_out;
/* get the firmware version */
hw->eeprom.ops.read(hw, (fw_ptp_cfg_offset +
IXGBE_FW_PATCH_VERSION_4),
&fw_version);
if (fw_version > 0x5)
status = 0;
fw_version_out:
return status;
}
/**
* ixgbe_verify_lesm_fw_enabled_82599 - Checks LESM FW module state.
* @hw: pointer to hardware structure
*
* Returns true if the LESM FW module is present and enabled. Otherwise
* returns false. Smart Speed must be disabled if LESM FW module is enabled.
**/
static bool ixgbe_verify_lesm_fw_enabled_82599(struct ixgbe_hw *hw)
{
bool lesm_enabled = false;
u16 fw_offset, fw_lesm_param_offset, fw_lesm_state;
s32 status;
/* get the offset to the Firmware Module block */
status = hw->eeprom.ops.read(hw, IXGBE_FW_PTR, &fw_offset);
if ((status != 0) ||
(fw_offset == 0) || (fw_offset == 0xFFFF))
goto out;
/* get the offset to the LESM Parameters block */
status = hw->eeprom.ops.read(hw, (fw_offset +
IXGBE_FW_LESM_PARAMETERS_PTR),
&fw_lesm_param_offset);
if ((status != 0) ||
(fw_lesm_param_offset == 0) || (fw_lesm_param_offset == 0xFFFF))
goto out;
/* get the lesm state word */
status = hw->eeprom.ops.read(hw, (fw_lesm_param_offset +
IXGBE_FW_LESM_STATE_1),
&fw_lesm_state);
if ((status == 0) &&
(fw_lesm_state & IXGBE_FW_LESM_STATE_ENABLED))
lesm_enabled = true;
out:
return lesm_enabled;
}
/**
* ixgbe_read_eeprom_buffer_82599 - Read EEPROM word(s) using
* fastest available method
*
* @hw: pointer to hardware structure
* @offset: offset of word in EEPROM to read
* @words: number of words
* @data: word(s) read from the EEPROM
*
* Retrieves 16 bit word(s) read from EEPROM
**/
static s32 ixgbe_read_eeprom_buffer_82599(struct ixgbe_hw *hw, u16 offset,
u16 words, u16 *data)
{
struct ixgbe_eeprom_info *eeprom = &hw->eeprom;
s32 ret_val = IXGBE_ERR_CONFIG;
/*
* If EEPROM is detected and can be addressed using 14 bits,
* use EERD otherwise use bit bang
*/
if ((eeprom->type == ixgbe_eeprom_spi) &&
(offset + (words - 1) <= IXGBE_EERD_MAX_ADDR))
ret_val = ixgbe_read_eerd_buffer_generic(hw, offset, words,
data);
else
ret_val = ixgbe_read_eeprom_buffer_bit_bang_generic(hw, offset,
words,
data);
return ret_val;
}
/**
* ixgbe_read_eeprom_82599 - Read EEPROM word using
* fastest available method
*
* @hw: pointer to hardware structure
* @offset: offset of word in the EEPROM to read
* @data: word read from the EEPROM
*
* Reads a 16 bit word from the EEPROM
**/
static s32 ixgbe_read_eeprom_82599(struct ixgbe_hw *hw,
u16 offset, u16 *data)
{
struct ixgbe_eeprom_info *eeprom = &hw->eeprom;
s32 ret_val = IXGBE_ERR_CONFIG;
/*
* If EEPROM is detected and can be addressed using 14 bits,
* use EERD otherwise use bit bang
*/
if ((eeprom->type == ixgbe_eeprom_spi) &&
(offset <= IXGBE_EERD_MAX_ADDR))
ret_val = ixgbe_read_eerd_generic(hw, offset, data);
else
ret_val = ixgbe_read_eeprom_bit_bang_generic(hw, offset, data);
return ret_val;
}
static struct ixgbe_mac_operations mac_ops_82599 = {
.init_hw = &ixgbe_init_hw_generic,
.reset_hw = &ixgbe_reset_hw_82599,
.start_hw = &ixgbe_start_hw_82599,
.clear_hw_cntrs = &ixgbe_clear_hw_cntrs_generic,
.get_media_type = &ixgbe_get_media_type_82599,
.get_supported_physical_layer = &ixgbe_get_supported_physical_layer_82599,
.enable_rx_dma = &ixgbe_enable_rx_dma_82599,
.disable_rx_buff = &ixgbe_disable_rx_buff_generic,
.enable_rx_buff = &ixgbe_enable_rx_buff_generic,
.get_mac_addr = &ixgbe_get_mac_addr_generic,
.get_san_mac_addr = &ixgbe_get_san_mac_addr_generic,
.get_device_caps = &ixgbe_get_device_caps_generic,
.get_wwn_prefix = &ixgbe_get_wwn_prefix_generic,
.stop_adapter = &ixgbe_stop_adapter_generic,
.get_bus_info = &ixgbe_get_bus_info_generic,
.set_lan_id = &ixgbe_set_lan_id_multi_port_pcie,
.read_analog_reg8 = &ixgbe_read_analog_reg8_82599,
.write_analog_reg8 = &ixgbe_write_analog_reg8_82599,
.setup_link = &ixgbe_setup_mac_link_82599,
.set_rxpba = &ixgbe_set_rxpba_generic,
.check_link = &ixgbe_check_mac_link_generic,
.get_link_capabilities = &ixgbe_get_link_capabilities_82599,
.led_on = &ixgbe_led_on_generic,
.led_off = &ixgbe_led_off_generic,
.blink_led_start = &ixgbe_blink_led_start_generic,
.blink_led_stop = &ixgbe_blink_led_stop_generic,
.set_rar = &ixgbe_set_rar_generic,
.clear_rar = &ixgbe_clear_rar_generic,
.set_vmdq = &ixgbe_set_vmdq_generic,
.clear_vmdq = &ixgbe_clear_vmdq_generic,
.init_rx_addrs = &ixgbe_init_rx_addrs_generic,
.update_mc_addr_list = &ixgbe_update_mc_addr_list_generic,
.enable_mc = &ixgbe_enable_mc_generic,
.disable_mc = &ixgbe_disable_mc_generic,
.clear_vfta = &ixgbe_clear_vfta_generic,
.set_vfta = &ixgbe_set_vfta_generic,
.fc_enable = &ixgbe_fc_enable_generic,
.set_fw_drv_ver = &ixgbe_set_fw_drv_ver_generic,
.init_uta_tables = &ixgbe_init_uta_tables_generic,
.setup_sfp = &ixgbe_setup_sfp_modules_82599,
.set_mac_anti_spoofing = &ixgbe_set_mac_anti_spoofing,
.set_vlan_anti_spoofing = &ixgbe_set_vlan_anti_spoofing,
.acquire_swfw_sync = &ixgbe_acquire_swfw_sync,
.release_swfw_sync = &ixgbe_release_swfw_sync,
};
static struct ixgbe_eeprom_operations eeprom_ops_82599 = {
.init_params = &ixgbe_init_eeprom_params_generic,
.read = &ixgbe_read_eeprom_82599,
.read_buffer = &ixgbe_read_eeprom_buffer_82599,
.write = &ixgbe_write_eeprom_generic,
.write_buffer = &ixgbe_write_eeprom_buffer_bit_bang_generic,
.calc_checksum = &ixgbe_calc_eeprom_checksum_generic,
.validate_checksum = &ixgbe_validate_eeprom_checksum_generic,
.update_checksum = &ixgbe_update_eeprom_checksum_generic,
};
static struct ixgbe_phy_operations phy_ops_82599 = {
.identify = &ixgbe_identify_phy_82599,
.identify_sfp = &ixgbe_identify_sfp_module_generic,
.init = &ixgbe_init_phy_ops_82599,
.reset = &ixgbe_reset_phy_generic,
.read_reg = &ixgbe_read_phy_reg_generic,
.write_reg = &ixgbe_write_phy_reg_generic,
.setup_link = &ixgbe_setup_phy_link_generic,
.setup_link_speed = &ixgbe_setup_phy_link_speed_generic,
.read_i2c_byte = &ixgbe_read_i2c_byte_generic,
.write_i2c_byte = &ixgbe_write_i2c_byte_generic,
.read_i2c_eeprom = &ixgbe_read_i2c_eeprom_generic,
.write_i2c_eeprom = &ixgbe_write_i2c_eeprom_generic,
.check_overtemp = &ixgbe_tn_check_overtemp,
};
struct ixgbe_info ixgbe_82599_info = {
.mac = ixgbe_mac_82599EB,
.get_invariants = &ixgbe_get_invariants_82599,
.mac_ops = &mac_ops_82599,
.eeprom_ops = &eeprom_ops_82599,
.phy_ops = &phy_ops_82599,
.mbx_ops = &mbx_ops_generic,
};
| gpl-2.0 |
Split-Screen/android_kernel_samsung_exynos5410 | drivers/staging/line6/driver.c | 4809 | 32122 | /*
* Line6 Linux USB driver - 0.9.1beta
*
* Copyright (C) 2004-2010 Markus Grabner (grabner@icg.tugraz.at)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include "audio.h"
#include "capture.h"
#include "control.h"
#include "driver.h"
#include "midi.h"
#include "playback.h"
#include "pod.h"
#include "podhd.h"
#include "revision.h"
#include "toneport.h"
#include "usbdefs.h"
#include "variax.h"
#define DRIVER_AUTHOR "Markus Grabner <grabner@icg.tugraz.at>"
#define DRIVER_DESC "Line6 USB Driver"
#define DRIVER_VERSION "0.9.1beta" DRIVER_REVISION
/* table of devices that work with this driver */
static const struct usb_device_id line6_id_table[] = {
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_BASSPODXT)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_BASSPODXTLIVE)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_BASSPODXTPRO)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_GUITARPORT)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_POCKETPOD)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_PODHD300)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_PODHD500)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_PODSTUDIO_GX)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_PODSTUDIO_UX1)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_PODSTUDIO_UX2)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_PODX3)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_PODX3LIVE)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_PODXT)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_PODXTLIVE)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_PODXTPRO)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_TONEPORT_GX)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_TONEPORT_UX1)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_TONEPORT_UX2)},
{USB_DEVICE(LINE6_VENDOR_ID, LINE6_DEVID_VARIAX)},
{},
};
MODULE_DEVICE_TABLE(usb, line6_id_table);
/* *INDENT-OFF* */
static struct line6_properties line6_properties_table[] = {
{ LINE6_BIT_BASSPODXT, "BassPODxt", "BassPODxt", LINE6_BIT_CONTROL_PCM_HWMON },
{ LINE6_BIT_BASSPODXTLIVE, "BassPODxtLive", "BassPODxt Live", LINE6_BIT_CONTROL_PCM_HWMON },
{ LINE6_BIT_BASSPODXTPRO, "BassPODxtPro", "BassPODxt Pro", LINE6_BIT_CONTROL_PCM_HWMON },
{ LINE6_BIT_GUITARPORT, "GuitarPort", "GuitarPort", LINE6_BIT_PCM },
{ LINE6_BIT_POCKETPOD, "PocketPOD", "Pocket POD", LINE6_BIT_CONTROL },
{ LINE6_BIT_PODHD300, "PODHD300", "POD HD300", LINE6_BIT_CONTROL_PCM_HWMON },
{ LINE6_BIT_PODHD500, "PODHD500", "POD HD500", LINE6_BIT_CONTROL_PCM_HWMON },
{ LINE6_BIT_PODSTUDIO_GX, "PODStudioGX", "POD Studio GX", LINE6_BIT_PCM },
{ LINE6_BIT_PODSTUDIO_UX1, "PODStudioUX1", "POD Studio UX1", LINE6_BIT_PCM },
{ LINE6_BIT_PODSTUDIO_UX2, "PODStudioUX2", "POD Studio UX2", LINE6_BIT_PCM },
{ LINE6_BIT_PODX3, "PODX3", "POD X3", LINE6_BIT_PCM },
{ LINE6_BIT_PODX3LIVE, "PODX3Live", "POD X3 Live", LINE6_BIT_PCM },
{ LINE6_BIT_PODXT, "PODxt", "PODxt", LINE6_BIT_CONTROL_PCM_HWMON },
{ LINE6_BIT_PODXTLIVE, "PODxtLive", "PODxt Live", LINE6_BIT_CONTROL_PCM_HWMON },
{ LINE6_BIT_PODXTPRO, "PODxtPro", "PODxt Pro", LINE6_BIT_CONTROL_PCM_HWMON },
{ LINE6_BIT_TONEPORT_GX, "TonePortGX", "TonePort GX", LINE6_BIT_PCM },
{ LINE6_BIT_TONEPORT_UX1, "TonePortUX1", "TonePort UX1", LINE6_BIT_PCM },
{ LINE6_BIT_TONEPORT_UX2, "TonePortUX2", "TonePort UX2", LINE6_BIT_PCM },
{ LINE6_BIT_VARIAX, "Variax", "Variax Workbench", LINE6_BIT_CONTROL },
};
/* *INDENT-ON* */
/*
This is Line6's MIDI manufacturer ID.
*/
const unsigned char line6_midi_id[] = {
0x00, 0x01, 0x0c
};
/*
Code to request version of POD, Variax interface
(and maybe other devices).
*/
static const char line6_request_version0[] = {
0xf0, 0x7e, 0x7f, 0x06, 0x01, 0xf7
};
/*
Copy of version request code with GFP_KERNEL flag for use in URB.
*/
static const char *line6_request_version;
struct usb_line6 *line6_devices[LINE6_MAX_DEVICES];
/**
Class for asynchronous messages.
*/
struct message {
struct usb_line6 *line6;
const char *buffer;
int size;
int done;
};
/*
Forward declarations.
*/
static void line6_data_received(struct urb *urb);
static int line6_send_raw_message_async_part(struct message *msg,
struct urb *urb);
/*
Start to listen on endpoint.
*/
static int line6_start_listen(struct usb_line6 *line6)
{
int err;
usb_fill_int_urb(line6->urb_listen, line6->usbdev,
usb_rcvintpipe(line6->usbdev, line6->ep_control_read),
line6->buffer_listen, LINE6_BUFSIZE_LISTEN,
line6_data_received, line6, line6->interval);
line6->urb_listen->actual_length = 0;
err = usb_submit_urb(line6->urb_listen, GFP_ATOMIC);
return err;
}
/*
Stop listening on endpoint.
*/
static void line6_stop_listen(struct usb_line6 *line6)
{
usb_kill_urb(line6->urb_listen);
}
#ifdef CONFIG_LINE6_USB_DUMP_ANY
/*
Write hexdump to syslog.
*/
void line6_write_hexdump(struct usb_line6 *line6, char dir,
const unsigned char *buffer, int size)
{
static const int BYTES_PER_LINE = 8;
char hexdump[100];
char asc[BYTES_PER_LINE + 1];
int i, j;
for (i = 0; i < size; i += BYTES_PER_LINE) {
int hexdumpsize = sizeof(hexdump);
char *p = hexdump;
int n = min(size - i, BYTES_PER_LINE);
asc[n] = 0;
for (j = 0; j < BYTES_PER_LINE; ++j) {
int bytes;
if (j < n) {
unsigned char val = buffer[i + j];
bytes = snprintf(p, hexdumpsize, " %02X", val);
asc[j] = ((val >= 0x20)
&& (val < 0x7f)) ? val : '.';
} else
bytes = snprintf(p, hexdumpsize, " ");
if (bytes > hexdumpsize)
break; /* buffer overflow */
p += bytes;
hexdumpsize -= bytes;
}
dev_info(line6->ifcdev, "%c%04X:%s %s\n", dir, i, hexdump, asc);
}
}
#endif
#ifdef CONFIG_LINE6_USB_DUMP_CTRL
/*
Dump URB data to syslog.
*/
static void line6_dump_urb(struct urb *urb)
{
struct usb_line6 *line6 = (struct usb_line6 *)urb->context;
if (urb->status < 0)
return;
line6_write_hexdump(line6, 'R', (unsigned char *)urb->transfer_buffer,
urb->actual_length);
}
#endif
/*
Send raw message in pieces of wMaxPacketSize bytes.
*/
int line6_send_raw_message(struct usb_line6 *line6, const char *buffer,
int size)
{
int i, done = 0;
#ifdef CONFIG_LINE6_USB_DUMP_CTRL
line6_write_hexdump(line6, 'S', buffer, size);
#endif
for (i = 0; i < size; i += line6->max_packet_size) {
int partial;
const char *frag_buf = buffer + i;
int frag_size = min(line6->max_packet_size, size - i);
int retval;
retval = usb_interrupt_msg(line6->usbdev,
usb_sndintpipe(line6->usbdev,
line6->ep_control_write),
(char *)frag_buf, frag_size,
&partial, LINE6_TIMEOUT * HZ);
if (retval) {
dev_err(line6->ifcdev,
"usb_interrupt_msg failed (%d)\n", retval);
break;
}
done += frag_size;
}
return done;
}
/*
Notification of completion of asynchronous request transmission.
*/
static void line6_async_request_sent(struct urb *urb)
{
struct message *msg = (struct message *)urb->context;
if (msg->done >= msg->size) {
usb_free_urb(urb);
kfree(msg);
} else
line6_send_raw_message_async_part(msg, urb);
}
/*
Asynchronously send part of a raw message.
*/
static int line6_send_raw_message_async_part(struct message *msg,
struct urb *urb)
{
int retval;
struct usb_line6 *line6 = msg->line6;
int done = msg->done;
int bytes = min(msg->size - done, line6->max_packet_size);
usb_fill_int_urb(urb, line6->usbdev,
usb_sndintpipe(line6->usbdev, line6->ep_control_write),
(char *)msg->buffer + done, bytes,
line6_async_request_sent, msg, line6->interval);
#ifdef CONFIG_LINE6_USB_DUMP_CTRL
line6_write_hexdump(line6, 'S', (char *)msg->buffer + done, bytes);
#endif
msg->done += bytes;
retval = usb_submit_urb(urb, GFP_ATOMIC);
if (retval < 0) {
dev_err(line6->ifcdev, "%s: usb_submit_urb failed (%d)\n",
__func__, retval);
usb_free_urb(urb);
kfree(msg);
return -EINVAL;
}
return 0;
}
/*
Setup and start timer.
*/
void line6_start_timer(struct timer_list *timer, unsigned int msecs,
void (*function) (unsigned long), unsigned long data)
{
setup_timer(timer, function, data);
timer->expires = jiffies + msecs * HZ / 1000;
add_timer(timer);
}
/*
Asynchronously send raw message.
*/
int line6_send_raw_message_async(struct usb_line6 *line6, const char *buffer,
int size)
{
struct message *msg;
struct urb *urb;
/* create message: */
msg = kmalloc(sizeof(struct message), GFP_ATOMIC);
if (msg == NULL) {
dev_err(line6->ifcdev, "Out of memory\n");
return -ENOMEM;
}
/* create URB: */
urb = usb_alloc_urb(0, GFP_ATOMIC);
if (urb == NULL) {
kfree(msg);
dev_err(line6->ifcdev, "Out of memory\n");
return -ENOMEM;
}
/* set message data: */
msg->line6 = line6;
msg->buffer = buffer;
msg->size = size;
msg->done = 0;
/* start sending: */
return line6_send_raw_message_async_part(msg, urb);
}
/*
Send asynchronous device version request.
*/
int line6_version_request_async(struct usb_line6 *line6)
{
return line6_send_raw_message_async(line6, line6_request_version,
sizeof(line6_request_version0));
}
/*
Send sysex message in pieces of wMaxPacketSize bytes.
*/
int line6_send_sysex_message(struct usb_line6 *line6, const char *buffer,
int size)
{
return line6_send_raw_message(line6, buffer,
size + SYSEX_EXTRA_SIZE) -
SYSEX_EXTRA_SIZE;
}
/*
Send sysex message in pieces of wMaxPacketSize bytes.
*/
int line6_send_sysex_message_async(struct usb_line6 *line6, const char *buffer,
int size)
{
return line6_send_raw_message_async(line6, buffer,
size + SYSEX_EXTRA_SIZE) -
SYSEX_EXTRA_SIZE;
}
/*
Allocate buffer for sysex message and prepare header.
@param code sysex message code
@param size number of bytes between code and sysex end
*/
char *line6_alloc_sysex_buffer(struct usb_line6 *line6, int code1, int code2,
int size)
{
char *buffer = kmalloc(size + SYSEX_EXTRA_SIZE, GFP_ATOMIC);
if (!buffer) {
dev_err(line6->ifcdev, "out of memory\n");
return NULL;
}
buffer[0] = LINE6_SYSEX_BEGIN;
memcpy(buffer + 1, line6_midi_id, sizeof(line6_midi_id));
buffer[sizeof(line6_midi_id) + 1] = code1;
buffer[sizeof(line6_midi_id) + 2] = code2;
buffer[sizeof(line6_midi_id) + 3 + size] = LINE6_SYSEX_END;
return buffer;
}
/*
Notification of data received from the Line6 device.
*/
static void line6_data_received(struct urb *urb)
{
struct usb_line6 *line6 = (struct usb_line6 *)urb->context;
struct MidiBuffer *mb = &line6->line6midi->midibuf_in;
int done;
if (urb->status == -ESHUTDOWN)
return;
#ifdef CONFIG_LINE6_USB_DUMP_CTRL
line6_dump_urb(urb);
#endif
done =
line6_midibuf_write(mb, urb->transfer_buffer, urb->actual_length);
if (done < urb->actual_length) {
line6_midibuf_ignore(mb, done);
DEBUG_MESSAGES(dev_err
(line6->ifcdev,
"%d %d buffer overflow - message skipped\n",
done, urb->actual_length));
}
for (;;) {
done =
line6_midibuf_read(mb, line6->buffer_message,
LINE6_MESSAGE_MAXLEN);
if (done == 0)
break;
/* MIDI input filter */
if (line6_midibuf_skip_message
(mb, line6->line6midi->midi_mask_receive))
continue;
line6->message_length = done;
#ifdef CONFIG_LINE6_USB_DUMP_MIDI
line6_write_hexdump(line6, 'r', line6->buffer_message, done);
#endif
line6_midi_receive(line6, line6->buffer_message, done);
switch (line6->usbdev->descriptor.idProduct) {
case LINE6_DEVID_BASSPODXT:
case LINE6_DEVID_BASSPODXTLIVE:
case LINE6_DEVID_BASSPODXTPRO:
case LINE6_DEVID_PODXT:
case LINE6_DEVID_PODXTPRO:
case LINE6_DEVID_POCKETPOD:
line6_pod_process_message((struct usb_line6_pod *)
line6);
break;
case LINE6_DEVID_PODHD300:
case LINE6_DEVID_PODHD500:
break; /* let userspace handle MIDI */
case LINE6_DEVID_PODXTLIVE:
switch (line6->interface_number) {
case PODXTLIVE_INTERFACE_POD:
line6_pod_process_message((struct usb_line6_pod
*)line6);
break;
case PODXTLIVE_INTERFACE_VARIAX:
line6_variax_process_message((struct
usb_line6_variax
*)line6);
break;
default:
dev_err(line6->ifcdev,
"PODxt Live interface %d not supported\n",
line6->interface_number);
}
break;
case LINE6_DEVID_VARIAX:
line6_variax_process_message((struct usb_line6_variax *)
line6);
break;
default:
MISSING_CASE;
}
}
line6_start_listen(line6);
}
/*
Send channel number (i.e., switch to a different sound).
*/
int line6_send_program(struct usb_line6 *line6, int value)
{
int retval;
unsigned char *buffer;
int partial;
buffer = kmalloc(2, GFP_KERNEL);
if (!buffer) {
dev_err(line6->ifcdev, "out of memory\n");
return -ENOMEM;
}
buffer[0] = LINE6_PROGRAM_CHANGE | LINE6_CHANNEL_HOST;
buffer[1] = value;
#ifdef CONFIG_LINE6_USB_DUMP_CTRL
line6_write_hexdump(line6, 'S', buffer, 2);
#endif
retval = usb_interrupt_msg(line6->usbdev,
usb_sndintpipe(line6->usbdev,
line6->ep_control_write),
buffer, 2, &partial, LINE6_TIMEOUT * HZ);
if (retval)
dev_err(line6->ifcdev, "usb_interrupt_msg failed (%d)\n",
retval);
kfree(buffer);
return retval;
}
/*
Transmit Line6 control parameter.
*/
int line6_transmit_parameter(struct usb_line6 *line6, int param, int value)
{
int retval;
unsigned char *buffer;
int partial;
buffer = kmalloc(3, GFP_KERNEL);
if (!buffer) {
dev_err(line6->ifcdev, "out of memory\n");
return -ENOMEM;
}
buffer[0] = LINE6_PARAM_CHANGE | LINE6_CHANNEL_HOST;
buffer[1] = param;
buffer[2] = value;
#ifdef CONFIG_LINE6_USB_DUMP_CTRL
line6_write_hexdump(line6, 'S', buffer, 3);
#endif
retval = usb_interrupt_msg(line6->usbdev,
usb_sndintpipe(line6->usbdev,
line6->ep_control_write),
buffer, 3, &partial, LINE6_TIMEOUT * HZ);
if (retval)
dev_err(line6->ifcdev, "usb_interrupt_msg failed (%d)\n",
retval);
kfree(buffer);
return retval;
}
/*
Read data from device.
*/
int line6_read_data(struct usb_line6 *line6, int address, void *data,
size_t datalen)
{
struct usb_device *usbdev = line6->usbdev;
int ret;
unsigned char len;
/* query the serial number: */
ret = usb_control_msg(usbdev, usb_sndctrlpipe(usbdev, 0), 0x67,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
(datalen << 8) | 0x21, address,
NULL, 0, LINE6_TIMEOUT * HZ);
if (ret < 0) {
dev_err(line6->ifcdev, "read request failed (error %d)\n", ret);
return ret;
}
/* Wait for data length. We'll get a couple of 0xff until length arrives. */
do {
ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0), 0x67,
USB_TYPE_VENDOR | USB_RECIP_DEVICE |
USB_DIR_IN,
0x0012, 0x0000, &len, 1,
LINE6_TIMEOUT * HZ);
if (ret < 0) {
dev_err(line6->ifcdev,
"receive length failed (error %d)\n", ret);
return ret;
}
} while (len == 0xff);
if (len != datalen) {
/* should be equal or something went wrong */
dev_err(line6->ifcdev,
"length mismatch (expected %d, got %d)\n",
(int)datalen, (int)len);
return -EINVAL;
}
/* receive the result: */
ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0), 0x67,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
0x0013, 0x0000, data, datalen,
LINE6_TIMEOUT * HZ);
if (ret < 0) {
dev_err(line6->ifcdev, "read failed (error %d)\n", ret);
return ret;
}
return 0;
}
/*
Write data to device.
*/
int line6_write_data(struct usb_line6 *line6, int address, void *data,
size_t datalen)
{
struct usb_device *usbdev = line6->usbdev;
int ret;
unsigned char status;
ret = usb_control_msg(usbdev, usb_sndctrlpipe(usbdev, 0), 0x67,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
0x0022, address, data, datalen,
LINE6_TIMEOUT * HZ);
if (ret < 0) {
dev_err(line6->ifcdev,
"write request failed (error %d)\n", ret);
return ret;
}
do {
ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0),
0x67,
USB_TYPE_VENDOR | USB_RECIP_DEVICE |
USB_DIR_IN,
0x0012, 0x0000,
&status, 1, LINE6_TIMEOUT * HZ);
if (ret < 0) {
dev_err(line6->ifcdev,
"receiving status failed (error %d)\n", ret);
return ret;
}
} while (status == 0xff);
if (status != 0) {
dev_err(line6->ifcdev, "write failed (error %d)\n", ret);
return -EINVAL;
}
return 0;
}
/*
Read Line6 device serial number.
(POD, TonePort, GuitarPort)
*/
int line6_read_serial_number(struct usb_line6 *line6, int *serial_number)
{
return line6_read_data(line6, 0x80d0, serial_number,
sizeof(*serial_number));
}
/*
No operation (i.e., unsupported).
*/
ssize_t line6_nop_read(struct device *dev, struct device_attribute *attr,
char *buf)
{
return 0;
}
/*
No operation (i.e., unsupported).
*/
ssize_t line6_nop_write(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
return count;
}
/*
"write" request on "raw" special file.
*/
#ifdef CONFIG_LINE6_USB_RAW
ssize_t line6_set_raw(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct usb_interface *interface = to_usb_interface(dev);
struct usb_line6 *line6 = usb_get_intfdata(interface);
line6_send_raw_message(line6, buf, count);
return count;
}
#endif
/*
Generic destructor.
*/
static void line6_destruct(struct usb_interface *interface)
{
struct usb_line6 *line6;
if (interface == NULL)
return;
line6 = usb_get_intfdata(interface);
if (line6 == NULL)
return;
/* free buffer memory first: */
kfree(line6->buffer_message);
kfree(line6->buffer_listen);
/* then free URBs: */
usb_free_urb(line6->urb_listen);
/* make sure the device isn't destructed twice: */
usb_set_intfdata(interface, NULL);
/* free interface data: */
kfree(line6);
}
/*
Probe USB device.
*/
static int line6_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
int devtype;
struct usb_device *usbdev;
struct usb_line6 *line6;
const struct line6_properties *properties;
int devnum;
int interface_number, alternate = 0;
int product;
int size = 0;
int ep_read = 0, ep_write = 0;
int ret;
if (interface == NULL)
return -ENODEV;
usbdev = interface_to_usbdev(interface);
if (usbdev == NULL)
return -ENODEV;
/* we don't handle multiple configurations */
if (usbdev->descriptor.bNumConfigurations != 1) {
ret = -ENODEV;
goto err_put;
}
/* check vendor and product id */
for (devtype = ARRAY_SIZE(line6_id_table) - 1; devtype--;) {
u16 idVendor = le16_to_cpu(usbdev->descriptor.idVendor);
u16 idProduct = le16_to_cpu(usbdev->descriptor.idProduct);
if (idVendor == line6_id_table[devtype].idVendor &&
idProduct == line6_id_table[devtype].idProduct)
break;
}
if (devtype < 0) {
ret = -ENODEV;
goto err_put;
}
/* find free slot in device table: */
for (devnum = 0; devnum < LINE6_MAX_DEVICES; ++devnum)
if (line6_devices[devnum] == NULL)
break;
if (devnum == LINE6_MAX_DEVICES) {
ret = -ENODEV;
goto err_put;
}
/* initialize device info: */
properties = &line6_properties_table[devtype];
dev_info(&interface->dev, "Line6 %s found\n", properties->name);
product = le16_to_cpu(usbdev->descriptor.idProduct);
/* query interface number */
interface_number = interface->cur_altsetting->desc.bInterfaceNumber;
switch (product) {
case LINE6_DEVID_BASSPODXTLIVE:
case LINE6_DEVID_PODXTLIVE:
case LINE6_DEVID_VARIAX:
alternate = 1;
break;
case LINE6_DEVID_POCKETPOD:
switch (interface_number) {
case 0:
return 0; /* this interface has no endpoints */
case 1:
alternate = 0;
break;
default:
MISSING_CASE;
}
break;
case LINE6_DEVID_PODHD500:
case LINE6_DEVID_PODX3:
case LINE6_DEVID_PODX3LIVE:
switch (interface_number) {
case 0:
alternate = 1;
break;
case 1:
alternate = 0;
break;
default:
MISSING_CASE;
}
break;
case LINE6_DEVID_BASSPODXT:
case LINE6_DEVID_BASSPODXTPRO:
case LINE6_DEVID_PODXT:
case LINE6_DEVID_PODXTPRO:
case LINE6_DEVID_PODHD300:
alternate = 5;
break;
case LINE6_DEVID_GUITARPORT:
case LINE6_DEVID_PODSTUDIO_GX:
case LINE6_DEVID_PODSTUDIO_UX1:
case LINE6_DEVID_TONEPORT_GX:
case LINE6_DEVID_TONEPORT_UX1:
alternate = 2; /* 1..4 seem to be ok */
break;
case LINE6_DEVID_TONEPORT_UX2:
case LINE6_DEVID_PODSTUDIO_UX2:
switch (interface_number) {
case 0:
/* defaults to 44.1kHz, 16-bit */
alternate = 2;
break;
case 1:
/* don't know yet what this is ...
alternate = 1;
break;
*/
return -ENODEV;
default:
MISSING_CASE;
}
break;
default:
MISSING_CASE;
ret = -ENODEV;
goto err_put;
}
ret = usb_set_interface(usbdev, interface_number, alternate);
if (ret < 0) {
dev_err(&interface->dev, "set_interface failed\n");
goto err_put;
}
/* initialize device data based on product id: */
switch (product) {
case LINE6_DEVID_BASSPODXT:
case LINE6_DEVID_BASSPODXTLIVE:
case LINE6_DEVID_BASSPODXTPRO:
case LINE6_DEVID_PODXT:
case LINE6_DEVID_PODXTPRO:
size = sizeof(struct usb_line6_pod);
ep_read = 0x84;
ep_write = 0x03;
break;
case LINE6_DEVID_PODHD300:
size = sizeof(struct usb_line6_podhd);
ep_read = 0x84;
ep_write = 0x03;
break;
case LINE6_DEVID_PODHD500:
size = sizeof(struct usb_line6_podhd);
ep_read = 0x81;
ep_write = 0x01;
break;
case LINE6_DEVID_POCKETPOD:
size = sizeof(struct usb_line6_pod);
ep_read = 0x82;
ep_write = 0x02;
break;
case LINE6_DEVID_PODX3:
case LINE6_DEVID_PODX3LIVE:
/* currently unused! */
size = sizeof(struct usb_line6_pod);
ep_read = 0x81;
ep_write = 0x01;
break;
case LINE6_DEVID_PODSTUDIO_GX:
case LINE6_DEVID_PODSTUDIO_UX1:
case LINE6_DEVID_PODSTUDIO_UX2:
case LINE6_DEVID_TONEPORT_GX:
case LINE6_DEVID_TONEPORT_UX1:
case LINE6_DEVID_TONEPORT_UX2:
case LINE6_DEVID_GUITARPORT:
size = sizeof(struct usb_line6_toneport);
/* these don't have a control channel */
break;
case LINE6_DEVID_PODXTLIVE:
switch (interface_number) {
case PODXTLIVE_INTERFACE_POD:
size = sizeof(struct usb_line6_pod);
ep_read = 0x84;
ep_write = 0x03;
break;
case PODXTLIVE_INTERFACE_VARIAX:
size = sizeof(struct usb_line6_variax);
ep_read = 0x86;
ep_write = 0x05;
break;
default:
ret = -ENODEV;
goto err_put;
}
break;
case LINE6_DEVID_VARIAX:
size = sizeof(struct usb_line6_variax);
ep_read = 0x82;
ep_write = 0x01;
break;
default:
MISSING_CASE;
ret = -ENODEV;
goto err_put;
}
if (size == 0) {
dev_err(&interface->dev,
"driver bug: interface data size not set\n");
ret = -ENODEV;
goto err_put;
}
line6 = kzalloc(size, GFP_KERNEL);
if (line6 == NULL) {
dev_err(&interface->dev, "Out of memory\n");
ret = -ENODEV;
goto err_put;
}
/* store basic data: */
line6->interface_number = interface_number;
line6->properties = properties;
line6->usbdev = usbdev;
line6->ifcdev = &interface->dev;
line6->ep_control_read = ep_read;
line6->ep_control_write = ep_write;
line6->product = product;
/* get data from endpoint descriptor (see usb_maxpacket): */
{
struct usb_host_endpoint *ep;
unsigned epnum =
usb_pipeendpoint(usb_rcvintpipe(usbdev, ep_read));
ep = usbdev->ep_in[epnum];
if (ep != NULL) {
line6->interval = ep->desc.bInterval;
line6->max_packet_size =
le16_to_cpu(ep->desc.wMaxPacketSize);
} else {
line6->interval = LINE6_FALLBACK_INTERVAL;
line6->max_packet_size = LINE6_FALLBACK_MAXPACKETSIZE;
dev_err(line6->ifcdev,
"endpoint not available, using fallback values");
}
}
usb_set_intfdata(interface, line6);
if (properties->capabilities & LINE6_BIT_CONTROL) {
/* initialize USB buffers: */
line6->buffer_listen =
kmalloc(LINE6_BUFSIZE_LISTEN, GFP_KERNEL);
if (line6->buffer_listen == NULL) {
dev_err(&interface->dev, "Out of memory\n");
ret = -ENOMEM;
goto err_destruct;
}
line6->buffer_message =
kmalloc(LINE6_MESSAGE_MAXLEN, GFP_KERNEL);
if (line6->buffer_message == NULL) {
dev_err(&interface->dev, "Out of memory\n");
ret = -ENOMEM;
goto err_destruct;
}
line6->urb_listen = usb_alloc_urb(0, GFP_KERNEL);
if (line6->urb_listen == NULL) {
dev_err(&interface->dev, "Out of memory\n");
line6_destruct(interface);
ret = -ENOMEM;
goto err_destruct;
}
ret = line6_start_listen(line6);
if (ret < 0) {
dev_err(&interface->dev, "%s: usb_submit_urb failed\n",
__func__);
goto err_destruct;
}
}
/* initialize device data based on product id: */
switch (product) {
case LINE6_DEVID_BASSPODXT:
case LINE6_DEVID_BASSPODXTLIVE:
case LINE6_DEVID_BASSPODXTPRO:
case LINE6_DEVID_POCKETPOD:
case LINE6_DEVID_PODX3:
case LINE6_DEVID_PODX3LIVE:
case LINE6_DEVID_PODXT:
case LINE6_DEVID_PODXTPRO:
ret = line6_pod_init(interface, (struct usb_line6_pod *)line6);
break;
case LINE6_DEVID_PODHD300:
case LINE6_DEVID_PODHD500:
ret = line6_podhd_init(interface,
(struct usb_line6_podhd *)line6);
break;
case LINE6_DEVID_PODXTLIVE:
switch (interface_number) {
case PODXTLIVE_INTERFACE_POD:
ret =
line6_pod_init(interface,
(struct usb_line6_pod *)line6);
break;
case PODXTLIVE_INTERFACE_VARIAX:
ret =
line6_variax_init(interface,
(struct usb_line6_variax *)line6);
break;
default:
dev_err(&interface->dev,
"PODxt Live interface %d not supported\n",
interface_number);
ret = -ENODEV;
}
break;
case LINE6_DEVID_VARIAX:
ret =
line6_variax_init(interface,
(struct usb_line6_variax *)line6);
break;
case LINE6_DEVID_PODSTUDIO_GX:
case LINE6_DEVID_PODSTUDIO_UX1:
case LINE6_DEVID_PODSTUDIO_UX2:
case LINE6_DEVID_TONEPORT_GX:
case LINE6_DEVID_TONEPORT_UX1:
case LINE6_DEVID_TONEPORT_UX2:
case LINE6_DEVID_GUITARPORT:
ret =
line6_toneport_init(interface,
(struct usb_line6_toneport *)line6);
break;
default:
MISSING_CASE;
ret = -ENODEV;
}
if (ret < 0)
goto err_destruct;
ret = sysfs_create_link(&interface->dev.kobj, &usbdev->dev.kobj,
"usb_device");
if (ret < 0)
goto err_destruct;
/* creation of additional special files should go here */
dev_info(&interface->dev, "Line6 %s now attached\n",
line6->properties->name);
line6_devices[devnum] = line6;
switch (product) {
case LINE6_DEVID_PODX3:
case LINE6_DEVID_PODX3LIVE:
dev_info(&interface->dev,
"NOTE: the Line6 %s is detected, but not yet supported\n",
line6->properties->name);
}
/* increment reference counters: */
usb_get_intf(interface);
usb_get_dev(usbdev);
return 0;
err_destruct:
line6_destruct(interface);
err_put:
return ret;
}
/*
Line6 device disconnected.
*/
static void line6_disconnect(struct usb_interface *interface)
{
struct usb_line6 *line6;
struct usb_device *usbdev;
int interface_number, i;
if (interface == NULL)
return;
usbdev = interface_to_usbdev(interface);
if (usbdev == NULL)
return;
/* removal of additional special files should go here */
sysfs_remove_link(&interface->dev.kobj, "usb_device");
interface_number = interface->cur_altsetting->desc.bInterfaceNumber;
line6 = usb_get_intfdata(interface);
if (line6 != NULL) {
if (line6->urb_listen != NULL)
line6_stop_listen(line6);
if (usbdev != line6->usbdev)
dev_err(line6->ifcdev,
"driver bug: inconsistent usb device\n");
switch (line6->usbdev->descriptor.idProduct) {
case LINE6_DEVID_BASSPODXT:
case LINE6_DEVID_BASSPODXTLIVE:
case LINE6_DEVID_BASSPODXTPRO:
case LINE6_DEVID_POCKETPOD:
case LINE6_DEVID_PODX3:
case LINE6_DEVID_PODX3LIVE:
case LINE6_DEVID_PODXT:
case LINE6_DEVID_PODXTPRO:
line6_pod_disconnect(interface);
break;
case LINE6_DEVID_PODHD300:
case LINE6_DEVID_PODHD500:
line6_podhd_disconnect(interface);
break;
case LINE6_DEVID_PODXTLIVE:
switch (interface_number) {
case PODXTLIVE_INTERFACE_POD:
line6_pod_disconnect(interface);
break;
case PODXTLIVE_INTERFACE_VARIAX:
line6_variax_disconnect(interface);
break;
}
break;
case LINE6_DEVID_VARIAX:
line6_variax_disconnect(interface);
break;
case LINE6_DEVID_PODSTUDIO_GX:
case LINE6_DEVID_PODSTUDIO_UX1:
case LINE6_DEVID_PODSTUDIO_UX2:
case LINE6_DEVID_TONEPORT_GX:
case LINE6_DEVID_TONEPORT_UX1:
case LINE6_DEVID_TONEPORT_UX2:
case LINE6_DEVID_GUITARPORT:
line6_toneport_disconnect(interface);
break;
default:
MISSING_CASE;
}
dev_info(&interface->dev, "Line6 %s now disconnected\n",
line6->properties->name);
for (i = LINE6_MAX_DEVICES; i--;)
if (line6_devices[i] == line6)
line6_devices[i] = NULL;
}
line6_destruct(interface);
/* decrement reference counters: */
usb_put_intf(interface);
usb_put_dev(usbdev);
}
#ifdef CONFIG_PM
/*
Suspend Line6 device.
*/
static int line6_suspend(struct usb_interface *interface, pm_message_t message)
{
struct usb_line6 *line6 = usb_get_intfdata(interface);
struct snd_line6_pcm *line6pcm = line6->line6pcm;
snd_power_change_state(line6->card, SNDRV_CTL_POWER_D3hot);
if (line6->properties->capabilities & LINE6_BIT_CONTROL)
line6_stop_listen(line6);
if (line6pcm != NULL) {
snd_pcm_suspend_all(line6pcm->pcm);
line6_pcm_disconnect(line6pcm);
line6pcm->flags = 0;
}
return 0;
}
/*
Resume Line6 device.
*/
static int line6_resume(struct usb_interface *interface)
{
struct usb_line6 *line6 = usb_get_intfdata(interface);
if (line6->properties->capabilities & LINE6_BIT_CONTROL)
line6_start_listen(line6);
snd_power_change_state(line6->card, SNDRV_CTL_POWER_D0);
return 0;
}
/*
Resume Line6 device after reset.
*/
static int line6_reset_resume(struct usb_interface *interface)
{
struct usb_line6 *line6 = usb_get_intfdata(interface);
switch (line6->usbdev->descriptor.idProduct) {
case LINE6_DEVID_PODSTUDIO_GX:
case LINE6_DEVID_PODSTUDIO_UX1:
case LINE6_DEVID_PODSTUDIO_UX2:
case LINE6_DEVID_TONEPORT_GX:
case LINE6_DEVID_TONEPORT_UX1:
case LINE6_DEVID_TONEPORT_UX2:
case LINE6_DEVID_GUITARPORT:
line6_toneport_reset_resume((struct usb_line6_toneport *)line6);
}
return line6_resume(interface);
}
#endif /* CONFIG_PM */
static struct usb_driver line6_driver = {
.name = DRIVER_NAME,
.probe = line6_probe,
.disconnect = line6_disconnect,
#ifdef CONFIG_PM
.suspend = line6_suspend,
.resume = line6_resume,
.reset_resume = line6_reset_resume,
#endif
.id_table = line6_id_table,
};
/*
Module initialization.
*/
static int __init line6_init(void)
{
int i, retval;
printk(KERN_INFO "%s driver version %s\n", DRIVER_NAME, DRIVER_VERSION);
for (i = LINE6_MAX_DEVICES; i--;)
line6_devices[i] = NULL;
retval = usb_register(&line6_driver);
if (retval) {
err("usb_register failed. Error number %d", retval);
return retval;
}
line6_request_version = kmalloc(sizeof(line6_request_version0),
GFP_KERNEL);
if (line6_request_version == NULL) {
err("Out of memory");
return -ENOMEM;
}
memcpy((char *)line6_request_version, line6_request_version0,
sizeof(line6_request_version0));
return retval;
}
/*
Module cleanup.
*/
static void __exit line6_exit(void)
{
int i;
struct usb_line6 *line6;
struct snd_line6_pcm *line6pcm;
/* stop all PCM channels */
for (i = LINE6_MAX_DEVICES; i--;) {
line6 = line6_devices[i];
if (line6 == NULL)
continue;
line6pcm = line6->line6pcm;
if (line6pcm == NULL)
continue;
line6_pcm_release(line6pcm, ~0);
}
usb_deregister(&line6_driver);
kfree(line6_request_version);
}
module_init(line6_init);
module_exit(line6_exit);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
MODULE_VERSION(DRIVER_VERSION);
| gpl-2.0 |
lg-devs/android_kernel_lge_msm8610 | drivers/infiniband/hw/qib/qib_uc.c | 4809 | 14508 | /*
* Copyright (c) 2006, 2007, 2008, 2009, 2010 QLogic Corporation.
* All rights reserved.
* Copyright (c) 2005, 2006 PathScale, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "qib.h"
/* cut down ridiculously long IB macro names */
#define OP(x) IB_OPCODE_UC_##x
/**
* qib_make_uc_req - construct a request packet (SEND, RDMA write)
* @qp: a pointer to the QP
*
* Return 1 if constructed; otherwise, return 0.
*/
int qib_make_uc_req(struct qib_qp *qp)
{
struct qib_other_headers *ohdr;
struct qib_swqe *wqe;
unsigned long flags;
u32 hwords;
u32 bth0;
u32 len;
u32 pmtu = qp->pmtu;
int ret = 0;
spin_lock_irqsave(&qp->s_lock, flags);
if (!(ib_qib_state_ops[qp->state] & QIB_PROCESS_SEND_OK)) {
if (!(ib_qib_state_ops[qp->state] & QIB_FLUSH_SEND))
goto bail;
/* We are in the error state, flush the work request. */
if (qp->s_last == qp->s_head)
goto bail;
/* If DMAs are in progress, we can't flush immediately. */
if (atomic_read(&qp->s_dma_busy)) {
qp->s_flags |= QIB_S_WAIT_DMA;
goto bail;
}
wqe = get_swqe_ptr(qp, qp->s_last);
qib_send_complete(qp, wqe, IB_WC_WR_FLUSH_ERR);
goto done;
}
ohdr = &qp->s_hdr.u.oth;
if (qp->remote_ah_attr.ah_flags & IB_AH_GRH)
ohdr = &qp->s_hdr.u.l.oth;
/* header size in 32-bit words LRH+BTH = (8+12)/4. */
hwords = 5;
bth0 = 0;
/* Get the next send request. */
wqe = get_swqe_ptr(qp, qp->s_cur);
qp->s_wqe = NULL;
switch (qp->s_state) {
default:
if (!(ib_qib_state_ops[qp->state] &
QIB_PROCESS_NEXT_SEND_OK))
goto bail;
/* Check if send work queue is empty. */
if (qp->s_cur == qp->s_head)
goto bail;
/*
* Start a new request.
*/
wqe->psn = qp->s_next_psn;
qp->s_psn = qp->s_next_psn;
qp->s_sge.sge = wqe->sg_list[0];
qp->s_sge.sg_list = wqe->sg_list + 1;
qp->s_sge.num_sge = wqe->wr.num_sge;
qp->s_sge.total_len = wqe->length;
len = wqe->length;
qp->s_len = len;
switch (wqe->wr.opcode) {
case IB_WR_SEND:
case IB_WR_SEND_WITH_IMM:
if (len > pmtu) {
qp->s_state = OP(SEND_FIRST);
len = pmtu;
break;
}
if (wqe->wr.opcode == IB_WR_SEND)
qp->s_state = OP(SEND_ONLY);
else {
qp->s_state =
OP(SEND_ONLY_WITH_IMMEDIATE);
/* Immediate data comes after the BTH */
ohdr->u.imm_data = wqe->wr.ex.imm_data;
hwords += 1;
}
if (wqe->wr.send_flags & IB_SEND_SOLICITED)
bth0 |= IB_BTH_SOLICITED;
qp->s_wqe = wqe;
if (++qp->s_cur >= qp->s_size)
qp->s_cur = 0;
break;
case IB_WR_RDMA_WRITE:
case IB_WR_RDMA_WRITE_WITH_IMM:
ohdr->u.rc.reth.vaddr =
cpu_to_be64(wqe->wr.wr.rdma.remote_addr);
ohdr->u.rc.reth.rkey =
cpu_to_be32(wqe->wr.wr.rdma.rkey);
ohdr->u.rc.reth.length = cpu_to_be32(len);
hwords += sizeof(struct ib_reth) / 4;
if (len > pmtu) {
qp->s_state = OP(RDMA_WRITE_FIRST);
len = pmtu;
break;
}
if (wqe->wr.opcode == IB_WR_RDMA_WRITE)
qp->s_state = OP(RDMA_WRITE_ONLY);
else {
qp->s_state =
OP(RDMA_WRITE_ONLY_WITH_IMMEDIATE);
/* Immediate data comes after the RETH */
ohdr->u.rc.imm_data = wqe->wr.ex.imm_data;
hwords += 1;
if (wqe->wr.send_flags & IB_SEND_SOLICITED)
bth0 |= IB_BTH_SOLICITED;
}
qp->s_wqe = wqe;
if (++qp->s_cur >= qp->s_size)
qp->s_cur = 0;
break;
default:
goto bail;
}
break;
case OP(SEND_FIRST):
qp->s_state = OP(SEND_MIDDLE);
/* FALLTHROUGH */
case OP(SEND_MIDDLE):
len = qp->s_len;
if (len > pmtu) {
len = pmtu;
break;
}
if (wqe->wr.opcode == IB_WR_SEND)
qp->s_state = OP(SEND_LAST);
else {
qp->s_state = OP(SEND_LAST_WITH_IMMEDIATE);
/* Immediate data comes after the BTH */
ohdr->u.imm_data = wqe->wr.ex.imm_data;
hwords += 1;
}
if (wqe->wr.send_flags & IB_SEND_SOLICITED)
bth0 |= IB_BTH_SOLICITED;
qp->s_wqe = wqe;
if (++qp->s_cur >= qp->s_size)
qp->s_cur = 0;
break;
case OP(RDMA_WRITE_FIRST):
qp->s_state = OP(RDMA_WRITE_MIDDLE);
/* FALLTHROUGH */
case OP(RDMA_WRITE_MIDDLE):
len = qp->s_len;
if (len > pmtu) {
len = pmtu;
break;
}
if (wqe->wr.opcode == IB_WR_RDMA_WRITE)
qp->s_state = OP(RDMA_WRITE_LAST);
else {
qp->s_state =
OP(RDMA_WRITE_LAST_WITH_IMMEDIATE);
/* Immediate data comes after the BTH */
ohdr->u.imm_data = wqe->wr.ex.imm_data;
hwords += 1;
if (wqe->wr.send_flags & IB_SEND_SOLICITED)
bth0 |= IB_BTH_SOLICITED;
}
qp->s_wqe = wqe;
if (++qp->s_cur >= qp->s_size)
qp->s_cur = 0;
break;
}
qp->s_len -= len;
qp->s_hdrwords = hwords;
qp->s_cur_sge = &qp->s_sge;
qp->s_cur_size = len;
qib_make_ruc_header(qp, ohdr, bth0 | (qp->s_state << 24),
qp->s_next_psn++ & QIB_PSN_MASK);
done:
ret = 1;
goto unlock;
bail:
qp->s_flags &= ~QIB_S_BUSY;
unlock:
spin_unlock_irqrestore(&qp->s_lock, flags);
return ret;
}
/**
* qib_uc_rcv - handle an incoming UC packet
* @ibp: the port the packet came in on
* @hdr: the header of the packet
* @has_grh: true if the packet has a GRH
* @data: the packet data
* @tlen: the length of the packet
* @qp: the QP for this packet.
*
* This is called from qib_qp_rcv() to process an incoming UC packet
* for the given QP.
* Called at interrupt level.
*/
void qib_uc_rcv(struct qib_ibport *ibp, struct qib_ib_header *hdr,
int has_grh, void *data, u32 tlen, struct qib_qp *qp)
{
struct qib_other_headers *ohdr;
u32 opcode;
u32 hdrsize;
u32 psn;
u32 pad;
struct ib_wc wc;
u32 pmtu = qp->pmtu;
struct ib_reth *reth;
int ret;
/* Check for GRH */
if (!has_grh) {
ohdr = &hdr->u.oth;
hdrsize = 8 + 12; /* LRH + BTH */
} else {
ohdr = &hdr->u.l.oth;
hdrsize = 8 + 40 + 12; /* LRH + GRH + BTH */
}
opcode = be32_to_cpu(ohdr->bth[0]);
if (qib_ruc_check_hdr(ibp, hdr, has_grh, qp, opcode))
return;
psn = be32_to_cpu(ohdr->bth[2]);
opcode >>= 24;
/* Compare the PSN verses the expected PSN. */
if (unlikely(qib_cmp24(psn, qp->r_psn) != 0)) {
/*
* Handle a sequence error.
* Silently drop any current message.
*/
qp->r_psn = psn;
inv:
if (qp->r_state == OP(SEND_FIRST) ||
qp->r_state == OP(SEND_MIDDLE)) {
set_bit(QIB_R_REWIND_SGE, &qp->r_aflags);
qp->r_sge.num_sge = 0;
} else
while (qp->r_sge.num_sge) {
atomic_dec(&qp->r_sge.sge.mr->refcount);
if (--qp->r_sge.num_sge)
qp->r_sge.sge = *qp->r_sge.sg_list++;
}
qp->r_state = OP(SEND_LAST);
switch (opcode) {
case OP(SEND_FIRST):
case OP(SEND_ONLY):
case OP(SEND_ONLY_WITH_IMMEDIATE):
goto send_first;
case OP(RDMA_WRITE_FIRST):
case OP(RDMA_WRITE_ONLY):
case OP(RDMA_WRITE_ONLY_WITH_IMMEDIATE):
goto rdma_first;
default:
goto drop;
}
}
/* Check for opcode sequence errors. */
switch (qp->r_state) {
case OP(SEND_FIRST):
case OP(SEND_MIDDLE):
if (opcode == OP(SEND_MIDDLE) ||
opcode == OP(SEND_LAST) ||
opcode == OP(SEND_LAST_WITH_IMMEDIATE))
break;
goto inv;
case OP(RDMA_WRITE_FIRST):
case OP(RDMA_WRITE_MIDDLE):
if (opcode == OP(RDMA_WRITE_MIDDLE) ||
opcode == OP(RDMA_WRITE_LAST) ||
opcode == OP(RDMA_WRITE_LAST_WITH_IMMEDIATE))
break;
goto inv;
default:
if (opcode == OP(SEND_FIRST) ||
opcode == OP(SEND_ONLY) ||
opcode == OP(SEND_ONLY_WITH_IMMEDIATE) ||
opcode == OP(RDMA_WRITE_FIRST) ||
opcode == OP(RDMA_WRITE_ONLY) ||
opcode == OP(RDMA_WRITE_ONLY_WITH_IMMEDIATE))
break;
goto inv;
}
if (qp->state == IB_QPS_RTR && !(qp->r_flags & QIB_R_COMM_EST)) {
qp->r_flags |= QIB_R_COMM_EST;
if (qp->ibqp.event_handler) {
struct ib_event ev;
ev.device = qp->ibqp.device;
ev.element.qp = &qp->ibqp;
ev.event = IB_EVENT_COMM_EST;
qp->ibqp.event_handler(&ev, qp->ibqp.qp_context);
}
}
/* OK, process the packet. */
switch (opcode) {
case OP(SEND_FIRST):
case OP(SEND_ONLY):
case OP(SEND_ONLY_WITH_IMMEDIATE):
send_first:
if (test_and_clear_bit(QIB_R_REWIND_SGE, &qp->r_aflags))
qp->r_sge = qp->s_rdma_read_sge;
else {
ret = qib_get_rwqe(qp, 0);
if (ret < 0)
goto op_err;
if (!ret)
goto drop;
/*
* qp->s_rdma_read_sge will be the owner
* of the mr references.
*/
qp->s_rdma_read_sge = qp->r_sge;
}
qp->r_rcv_len = 0;
if (opcode == OP(SEND_ONLY))
goto no_immediate_data;
else if (opcode == OP(SEND_ONLY_WITH_IMMEDIATE))
goto send_last_imm;
/* FALLTHROUGH */
case OP(SEND_MIDDLE):
/* Check for invalid length PMTU or posted rwqe len. */
if (unlikely(tlen != (hdrsize + pmtu + 4)))
goto rewind;
qp->r_rcv_len += pmtu;
if (unlikely(qp->r_rcv_len > qp->r_len))
goto rewind;
qib_copy_sge(&qp->r_sge, data, pmtu, 0);
break;
case OP(SEND_LAST_WITH_IMMEDIATE):
send_last_imm:
wc.ex.imm_data = ohdr->u.imm_data;
hdrsize += 4;
wc.wc_flags = IB_WC_WITH_IMM;
goto send_last;
case OP(SEND_LAST):
no_immediate_data:
wc.ex.imm_data = 0;
wc.wc_flags = 0;
send_last:
/* Get the number of bytes the message was padded by. */
pad = (be32_to_cpu(ohdr->bth[0]) >> 20) & 3;
/* Check for invalid length. */
/* XXX LAST len should be >= 1 */
if (unlikely(tlen < (hdrsize + pad + 4)))
goto rewind;
/* Don't count the CRC. */
tlen -= (hdrsize + pad + 4);
wc.byte_len = tlen + qp->r_rcv_len;
if (unlikely(wc.byte_len > qp->r_len))
goto rewind;
wc.opcode = IB_WC_RECV;
last_imm:
qib_copy_sge(&qp->r_sge, data, tlen, 0);
while (qp->s_rdma_read_sge.num_sge) {
atomic_dec(&qp->s_rdma_read_sge.sge.mr->refcount);
if (--qp->s_rdma_read_sge.num_sge)
qp->s_rdma_read_sge.sge =
*qp->s_rdma_read_sge.sg_list++;
}
wc.wr_id = qp->r_wr_id;
wc.status = IB_WC_SUCCESS;
wc.qp = &qp->ibqp;
wc.src_qp = qp->remote_qpn;
wc.slid = qp->remote_ah_attr.dlid;
wc.sl = qp->remote_ah_attr.sl;
/* zero fields that are N/A */
wc.vendor_err = 0;
wc.pkey_index = 0;
wc.dlid_path_bits = 0;
wc.port_num = 0;
/* Signal completion event if the solicited bit is set. */
qib_cq_enter(to_icq(qp->ibqp.recv_cq), &wc,
(ohdr->bth[0] &
cpu_to_be32(IB_BTH_SOLICITED)) != 0);
break;
case OP(RDMA_WRITE_FIRST):
case OP(RDMA_WRITE_ONLY):
case OP(RDMA_WRITE_ONLY_WITH_IMMEDIATE): /* consume RWQE */
rdma_first:
if (unlikely(!(qp->qp_access_flags &
IB_ACCESS_REMOTE_WRITE))) {
goto drop;
}
reth = &ohdr->u.rc.reth;
hdrsize += sizeof(*reth);
qp->r_len = be32_to_cpu(reth->length);
qp->r_rcv_len = 0;
qp->r_sge.sg_list = NULL;
if (qp->r_len != 0) {
u32 rkey = be32_to_cpu(reth->rkey);
u64 vaddr = be64_to_cpu(reth->vaddr);
int ok;
/* Check rkey */
ok = qib_rkey_ok(qp, &qp->r_sge.sge, qp->r_len,
vaddr, rkey, IB_ACCESS_REMOTE_WRITE);
if (unlikely(!ok))
goto drop;
qp->r_sge.num_sge = 1;
} else {
qp->r_sge.num_sge = 0;
qp->r_sge.sge.mr = NULL;
qp->r_sge.sge.vaddr = NULL;
qp->r_sge.sge.length = 0;
qp->r_sge.sge.sge_length = 0;
}
if (opcode == OP(RDMA_WRITE_ONLY))
goto rdma_last;
else if (opcode == OP(RDMA_WRITE_ONLY_WITH_IMMEDIATE)) {
wc.ex.imm_data = ohdr->u.rc.imm_data;
goto rdma_last_imm;
}
/* FALLTHROUGH */
case OP(RDMA_WRITE_MIDDLE):
/* Check for invalid length PMTU or posted rwqe len. */
if (unlikely(tlen != (hdrsize + pmtu + 4)))
goto drop;
qp->r_rcv_len += pmtu;
if (unlikely(qp->r_rcv_len > qp->r_len))
goto drop;
qib_copy_sge(&qp->r_sge, data, pmtu, 1);
break;
case OP(RDMA_WRITE_LAST_WITH_IMMEDIATE):
wc.ex.imm_data = ohdr->u.imm_data;
rdma_last_imm:
hdrsize += 4;
wc.wc_flags = IB_WC_WITH_IMM;
/* Get the number of bytes the message was padded by. */
pad = (be32_to_cpu(ohdr->bth[0]) >> 20) & 3;
/* Check for invalid length. */
/* XXX LAST len should be >= 1 */
if (unlikely(tlen < (hdrsize + pad + 4)))
goto drop;
/* Don't count the CRC. */
tlen -= (hdrsize + pad + 4);
if (unlikely(tlen + qp->r_rcv_len != qp->r_len))
goto drop;
if (test_and_clear_bit(QIB_R_REWIND_SGE, &qp->r_aflags))
while (qp->s_rdma_read_sge.num_sge) {
atomic_dec(&qp->s_rdma_read_sge.sge.mr->
refcount);
if (--qp->s_rdma_read_sge.num_sge)
qp->s_rdma_read_sge.sge =
*qp->s_rdma_read_sge.sg_list++;
}
else {
ret = qib_get_rwqe(qp, 1);
if (ret < 0)
goto op_err;
if (!ret)
goto drop;
}
wc.byte_len = qp->r_len;
wc.opcode = IB_WC_RECV_RDMA_WITH_IMM;
goto last_imm;
case OP(RDMA_WRITE_LAST):
rdma_last:
/* Get the number of bytes the message was padded by. */
pad = (be32_to_cpu(ohdr->bth[0]) >> 20) & 3;
/* Check for invalid length. */
/* XXX LAST len should be >= 1 */
if (unlikely(tlen < (hdrsize + pad + 4)))
goto drop;
/* Don't count the CRC. */
tlen -= (hdrsize + pad + 4);
if (unlikely(tlen + qp->r_rcv_len != qp->r_len))
goto drop;
qib_copy_sge(&qp->r_sge, data, tlen, 1);
while (qp->r_sge.num_sge) {
atomic_dec(&qp->r_sge.sge.mr->refcount);
if (--qp->r_sge.num_sge)
qp->r_sge.sge = *qp->r_sge.sg_list++;
}
break;
default:
/* Drop packet for unknown opcodes. */
goto drop;
}
qp->r_psn++;
qp->r_state = opcode;
return;
rewind:
set_bit(QIB_R_REWIND_SGE, &qp->r_aflags);
qp->r_sge.num_sge = 0;
drop:
ibp->n_pkt_drops++;
return;
op_err:
qib_rc_error(qp, IB_WC_LOC_QP_OP_ERR);
return;
}
| gpl-2.0 |
nmenon/linux-omap-ti-pm | sound/synth/emux/emux.c | 4809 | 4303 | /*
* Copyright (C) 2000 Takashi Iwai <tiwai@suse.de>
*
* Routines for control of EMU WaveTable chip
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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/wait.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <linux/init.h>
#include "emux_voice.h"
MODULE_AUTHOR("Takashi Iwai");
MODULE_DESCRIPTION("Routines for control of EMU WaveTable chip");
MODULE_LICENSE("GPL");
/*
* create a new hardware dependent device for Emu8000/Emu10k1
*/
int snd_emux_new(struct snd_emux **remu)
{
struct snd_emux *emu;
*remu = NULL;
emu = kzalloc(sizeof(*emu), GFP_KERNEL);
if (emu == NULL)
return -ENOMEM;
spin_lock_init(&emu->voice_lock);
mutex_init(&emu->register_mutex);
emu->client = -1;
#ifdef CONFIG_SND_SEQUENCER_OSS
emu->oss_synth = NULL;
#endif
emu->max_voices = 0;
emu->use_time = 0;
init_timer(&emu->tlist);
emu->tlist.function = snd_emux_timer_callback;
emu->tlist.data = (unsigned long)emu;
emu->timer_active = 0;
*remu = emu;
return 0;
}
EXPORT_SYMBOL(snd_emux_new);
/*
*/
static int sf_sample_new(void *private_data, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr,
const void __user *buf, long count)
{
struct snd_emux *emu = private_data;
return emu->ops.sample_new(emu, sp, hdr, buf, count);
}
static int sf_sample_free(void *private_data, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr)
{
struct snd_emux *emu = private_data;
return emu->ops.sample_free(emu, sp, hdr);
}
static void sf_sample_reset(void *private_data)
{
struct snd_emux *emu = private_data;
emu->ops.sample_reset(emu);
}
int snd_emux_register(struct snd_emux *emu, struct snd_card *card, int index, char *name)
{
int err;
struct snd_sf_callback sf_cb;
if (snd_BUG_ON(!emu->hw || emu->max_voices <= 0))
return -EINVAL;
if (snd_BUG_ON(!card || !name))
return -EINVAL;
emu->card = card;
emu->name = kstrdup(name, GFP_KERNEL);
emu->voices = kcalloc(emu->max_voices, sizeof(struct snd_emux_voice),
GFP_KERNEL);
if (emu->voices == NULL)
return -ENOMEM;
/* create soundfont list */
memset(&sf_cb, 0, sizeof(sf_cb));
sf_cb.private_data = emu;
if (emu->ops.sample_new)
sf_cb.sample_new = sf_sample_new;
if (emu->ops.sample_free)
sf_cb.sample_free = sf_sample_free;
if (emu->ops.sample_reset)
sf_cb.sample_reset = sf_sample_reset;
emu->sflist = snd_sf_new(&sf_cb, emu->memhdr);
if (emu->sflist == NULL)
return -ENOMEM;
if ((err = snd_emux_init_hwdep(emu)) < 0)
return err;
snd_emux_init_voices(emu);
snd_emux_init_seq(emu, card, index);
#ifdef CONFIG_SND_SEQUENCER_OSS
snd_emux_init_seq_oss(emu);
#endif
snd_emux_init_virmidi(emu, card);
#ifdef CONFIG_PROC_FS
snd_emux_proc_init(emu, card, index);
#endif
return 0;
}
EXPORT_SYMBOL(snd_emux_register);
/*
*/
int snd_emux_free(struct snd_emux *emu)
{
unsigned long flags;
if (! emu)
return -EINVAL;
spin_lock_irqsave(&emu->voice_lock, flags);
if (emu->timer_active)
del_timer(&emu->tlist);
spin_unlock_irqrestore(&emu->voice_lock, flags);
#ifdef CONFIG_PROC_FS
snd_emux_proc_free(emu);
#endif
snd_emux_delete_virmidi(emu);
#ifdef CONFIG_SND_SEQUENCER_OSS
snd_emux_detach_seq_oss(emu);
#endif
snd_emux_detach_seq(emu);
snd_emux_delete_hwdep(emu);
if (emu->sflist)
snd_sf_free(emu->sflist);
kfree(emu->voices);
kfree(emu->name);
kfree(emu);
return 0;
}
EXPORT_SYMBOL(snd_emux_free);
/*
* INIT part
*/
static int __init alsa_emux_init(void)
{
return 0;
}
static void __exit alsa_emux_exit(void)
{
}
module_init(alsa_emux_init)
module_exit(alsa_emux_exit)
| gpl-2.0 |
nels83/android_kernel_common | drivers/isdn/mISDN/dsp_core.c | 4809 | 33953 | /*
* Author Andreas Eversberg (jolly@eversberg.eu)
* Based on source code structure by
* Karsten Keil (keil@isdn4linux.de)
*
* This file is (c) under GNU PUBLIC LICENSE
* For changes and modifications please read
* ../../../Documentation/isdn/mISDN.cert
*
* Thanks to Karsten Keil (great drivers)
* Cologne Chip (great chips)
*
* This module does:
* Real-time tone generation
* DTMF detection
* Real-time cross-connection and conferrence
* Compensate jitter due to system load and hardware fault.
* All features are done in kernel space and will be realized
* using hardware, if available and supported by chip set.
* Blowfish encryption/decryption
*/
/* STRUCTURE:
*
* The dsp module provides layer 2 for b-channels (64kbit). It provides
* transparent audio forwarding with special digital signal processing:
*
* - (1) generation of tones
* - (2) detection of dtmf tones
* - (3) crossconnecting and conferences (clocking)
* - (4) echo generation for delay test
* - (5) volume control
* - (6) disable receive data
* - (7) pipeline
* - (8) encryption/decryption
*
* Look:
* TX RX
* ------upper layer------
* | ^
* | |(6)
* v |
* +-----+-------------+-----+
* |(3)(4) |
* | CMX |
* | |
* | +-------------+
* | | ^
* | | |
* |+---------+| +----+----+
* ||(1) || |(2) |
* || || | |
* || Tones || | DTMF |
* || || | |
* || || | |
* |+----+----+| +----+----+
* +-----+-----+ ^
* | |
* v |
* +----+----+ +----+----+
* |(5) | |(5) |
* | | | |
* |TX Volume| |RX Volume|
* | | | |
* | | | |
* +----+----+ +----+----+
* | ^
* | |
* v |
* +----+-------------+----+
* |(7) |
* | |
* | Pipeline Processing |
* | |
* | |
* +----+-------------+----+
* | ^
* | |
* v |
* +----+----+ +----+----+
* |(8) | |(8) |
* | | | |
* | Encrypt | | Decrypt |
* | | | |
* | | | |
* +----+----+ +----+----+
* | ^
* | |
* v |
* ------card layer------
* TX RX
*
* Above you can see the logical data flow. If software is used to do the
* process, it is actually the real data flow. If hardware is used, data
* may not flow, but hardware commands to the card, to provide the data flow
* as shown.
*
* NOTE: The channel must be activated in order to make dsp work, even if
* no data flow to the upper layer is intended. Activation can be done
* after and before controlling the setting using PH_CONTROL requests.
*
* DTMF: Will be detected by hardware if possible. It is done before CMX
* processing.
*
* Tones: Will be generated via software if endless looped audio fifos are
* not supported by hardware. Tones will override all data from CMX.
* It is not required to join a conference to use tones at any time.
*
* CMX: Is transparent when not used. When it is used, it will do
* crossconnections and conferences via software if not possible through
* hardware. If hardware capability is available, hardware is used.
*
* Echo: Is generated by CMX and is used to check performance of hard and
* software CMX.
*
* The CMX has special functions for conferences with one, two and more
* members. It will allow different types of data flow. Receive and transmit
* data to/form upper layer may be swithed on/off individually without losing
* features of CMX, Tones and DTMF.
*
* Echo Cancellation: Sometimes we like to cancel echo from the interface.
* Note that a VoIP call may not have echo caused by the IP phone. The echo
* is generated by the telephone line connected to it. Because the delay
* is high, it becomes an echo. RESULT: Echo Cachelation is required if
* both echo AND delay is applied to an interface.
* Remember that software CMX always generates a more or less delay.
*
* If all used features can be realized in hardware, and if transmit and/or
* receive data ist disabled, the card may not send/receive any data at all.
* Not receiving is useful if only announcements are played. Not sending is
* useful if an answering machine records audio. Not sending and receiving is
* useful during most states of the call. If supported by hardware, tones
* will be played without cpu load. Small PBXs and NT-Mode applications will
* not need expensive hardware when processing calls.
*
*
* LOCKING:
*
* When data is received from upper or lower layer (card), the complete dsp
* module is locked by a global lock. This lock MUST lock irq, because it
* must lock timer events by DSP poll timer.
* When data is ready to be transmitted down, the data is queued and sent
* outside lock and timer event.
* PH_CONTROL must not change any settings, join or split conference members
* during process of data.
*
* HDLC:
*
* It works quite the same as transparent, except that HDLC data is forwarded
* to all other conference members if no hardware bridging is possible.
* Send data will be writte to sendq. Sendq will be sent if confirm is received.
* Conference cannot join, if one member is not hdlc.
*
*/
#include <linux/delay.h>
#include <linux/gfp.h>
#include <linux/mISDNif.h>
#include <linux/mISDNdsp.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include "core.h"
#include "dsp.h"
static const char *mISDN_dsp_revision = "2.0";
static int debug;
static int options;
static int poll;
static int dtmfthreshold = 100;
MODULE_AUTHOR("Andreas Eversberg");
module_param(debug, uint, S_IRUGO | S_IWUSR);
module_param(options, uint, S_IRUGO | S_IWUSR);
module_param(poll, uint, S_IRUGO | S_IWUSR);
module_param(dtmfthreshold, uint, S_IRUGO | S_IWUSR);
MODULE_LICENSE("GPL");
/*int spinnest = 0;*/
spinlock_t dsp_lock; /* global dsp lock */
struct list_head dsp_ilist;
struct list_head conf_ilist;
int dsp_debug;
int dsp_options;
int dsp_poll, dsp_tics;
/* check if rx may be turned off or must be turned on */
static void
dsp_rx_off_member(struct dsp *dsp)
{
struct mISDN_ctrl_req cq;
int rx_off = 1;
memset(&cq, 0, sizeof(cq));
if (!dsp->features_rx_off)
return;
/* not disabled */
if (!dsp->rx_disabled)
rx_off = 0;
/* software dtmf */
else if (dsp->dtmf.software)
rx_off = 0;
/* echo in software */
else if (dsp->echo.software)
rx_off = 0;
/* bridge in software */
else if (dsp->conf && dsp->conf->software)
rx_off = 0;
/* data is not required by user space and not required
* for echo dtmf detection, soft-echo, soft-bridging */
if (rx_off == dsp->rx_is_off)
return;
if (!dsp->ch.peer) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: no peer, no rx_off\n",
__func__);
return;
}
cq.op = MISDN_CTRL_RX_OFF;
cq.p1 = rx_off;
if (dsp->ch.peer->ctrl(dsp->ch.peer, CONTROL_CHANNEL, &cq)) {
printk(KERN_DEBUG "%s: 2nd CONTROL_CHANNEL failed\n",
__func__);
return;
}
dsp->rx_is_off = rx_off;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: %s set rx_off = %d\n",
__func__, dsp->name, rx_off);
}
static void
dsp_rx_off(struct dsp *dsp)
{
struct dsp_conf_member *member;
if (dsp_options & DSP_OPT_NOHARDWARE)
return;
/* no conf */
if (!dsp->conf) {
dsp_rx_off_member(dsp);
return;
}
/* check all members in conf */
list_for_each_entry(member, &dsp->conf->mlist, list) {
dsp_rx_off_member(member->dsp);
}
}
/* enable "fill empty" feature */
static void
dsp_fill_empty(struct dsp *dsp)
{
struct mISDN_ctrl_req cq;
memset(&cq, 0, sizeof(cq));
if (!dsp->ch.peer) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: no peer, no fill_empty\n",
__func__);
return;
}
cq.op = MISDN_CTRL_FILL_EMPTY;
cq.p1 = 1;
if (dsp->ch.peer->ctrl(dsp->ch.peer, CONTROL_CHANNEL, &cq)) {
printk(KERN_DEBUG "%s: CONTROL_CHANNEL failed\n",
__func__);
return;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: %s set fill_empty = 1\n",
__func__, dsp->name);
}
static int
dsp_control_req(struct dsp *dsp, struct mISDNhead *hh, struct sk_buff *skb)
{
struct sk_buff *nskb;
int ret = 0;
int cont;
u8 *data;
int len;
if (skb->len < sizeof(int))
printk(KERN_ERR "%s: PH_CONTROL message too short\n", __func__);
cont = *((int *)skb->data);
len = skb->len - sizeof(int);
data = skb->data + sizeof(int);
switch (cont) {
case DTMF_TONE_START: /* turn on DTMF */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: start dtmf\n", __func__);
if (len == sizeof(int)) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_NOTICE "changing DTMF Threshold "
"to %d\n", *((int *)data));
dsp->dtmf.treshold = (*(int *)data) * 10000;
}
dsp->dtmf.enable = 1;
/* init goertzel */
dsp_dtmf_goertzel_init(dsp);
/* check dtmf hardware */
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
break;
case DTMF_TONE_STOP: /* turn off DTMF */
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: stop dtmf\n", __func__);
dsp->dtmf.enable = 0;
dsp->dtmf.hardware = 0;
dsp->dtmf.software = 0;
break;
case DSP_CONF_JOIN: /* join / update conference */
if (len < sizeof(int)) {
ret = -EINVAL;
break;
}
if (*((u32 *)data) == 0)
goto conf_split;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: join conference %d\n",
__func__, *((u32 *)data));
ret = dsp_cmx_conf(dsp, *((u32 *)data));
/* dsp_cmx_hardware will also be called here */
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_CONF_SPLIT: /* remove from conference */
conf_split:
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: release conference\n", __func__);
ret = dsp_cmx_conf(dsp, 0);
/* dsp_cmx_hardware will also be called here */
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
dsp_rx_off(dsp);
break;
case DSP_TONE_PATT_ON: /* play tone */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len < sizeof(int)) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: turn tone 0x%x on\n",
__func__, *((int *)skb->data));
ret = dsp_tone(dsp, *((int *)data));
if (!ret) {
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
}
if (!dsp->tone.tone)
goto tone_off;
break;
case DSP_TONE_PATT_OFF: /* stop tone */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: turn tone off\n", __func__);
dsp_tone(dsp, 0);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
/* reset tx buffers (user space data) */
tone_off:
dsp->rx_W = 0;
dsp->rx_R = 0;
break;
case DSP_VOL_CHANGE_TX: /* change volume */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len < sizeof(int)) {
ret = -EINVAL;
break;
}
dsp->tx_volume = *((int *)data);
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: change tx vol to %d\n",
__func__, dsp->tx_volume);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
break;
case DSP_VOL_CHANGE_RX: /* change volume */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len < sizeof(int)) {
ret = -EINVAL;
break;
}
dsp->rx_volume = *((int *)data);
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: change rx vol to %d\n",
__func__, dsp->tx_volume);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
break;
case DSP_ECHO_ON: /* enable echo */
dsp->echo.software = 1; /* soft echo */
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: enable cmx-echo\n", __func__);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_ECHO_OFF: /* disable echo */
dsp->echo.software = 0;
dsp->echo.hardware = 0;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: disable cmx-echo\n", __func__);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_RECEIVE_ON: /* enable receive to user space */
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: enable receive to user "
"space\n", __func__);
dsp->rx_disabled = 0;
dsp_rx_off(dsp);
break;
case DSP_RECEIVE_OFF: /* disable receive to user space */
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: disable receive to "
"user space\n", __func__);
dsp->rx_disabled = 1;
dsp_rx_off(dsp);
break;
case DSP_MIX_ON: /* enable mixing of tx data */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: enable mixing of "
"tx-data with conf mebers\n", __func__);
dsp->tx_mix = 1;
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_MIX_OFF: /* disable mixing of tx data */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: disable mixing of "
"tx-data with conf mebers\n", __func__);
dsp->tx_mix = 0;
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_TXDATA_ON: /* enable txdata */
dsp->tx_data = 1;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: enable tx-data\n", __func__);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_TXDATA_OFF: /* disable txdata */
dsp->tx_data = 0;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: disable tx-data\n", __func__);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_DELAY: /* use delay algorithm instead of dynamic
jitter algorithm */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len < sizeof(int)) {
ret = -EINVAL;
break;
}
dsp->cmx_delay = (*((int *)data)) << 3;
/* milliseconds to samples */
if (dsp->cmx_delay >= (CMX_BUFF_HALF >> 1))
/* clip to half of maximum usable buffer
(half of half buffer) */
dsp->cmx_delay = (CMX_BUFF_HALF >> 1) - 1;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: use delay algorithm to "
"compensate jitter (%d samples)\n",
__func__, dsp->cmx_delay);
break;
case DSP_JITTER: /* use dynamic jitter algorithm instead of
delay algorithm */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
dsp->cmx_delay = 0;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: use jitter algorithm to "
"compensate jitter\n", __func__);
break;
case DSP_TX_DEJITTER: /* use dynamic jitter algorithm for tx-buffer */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
dsp->tx_dejitter = 1;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: use dejitter on TX "
"buffer\n", __func__);
break;
case DSP_TX_DEJ_OFF: /* use tx-buffer without dejittering*/
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
dsp->tx_dejitter = 0;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: use TX buffer without "
"dejittering\n", __func__);
break;
case DSP_PIPELINE_CFG:
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len > 0 && ((char *)data)[len - 1]) {
printk(KERN_DEBUG "%s: pipeline config string "
"is not NULL terminated!\n", __func__);
ret = -EINVAL;
} else {
dsp->pipeline.inuse = 1;
dsp_cmx_hardware(dsp->conf, dsp);
ret = dsp_pipeline_build(&dsp->pipeline,
len > 0 ? data : NULL);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
}
break;
case DSP_BF_ENABLE_KEY: /* turn blowfish on */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len < 4 || len > 56) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: turn blowfish on (key "
"not shown)\n", __func__);
ret = dsp_bf_init(dsp, (u8 *)data, len);
/* set new cont */
if (!ret)
cont = DSP_BF_ACCEPT;
else
cont = DSP_BF_REJECT;
/* send indication if it worked to set it */
nskb = _alloc_mISDN_skb(PH_CONTROL_IND, MISDN_ID_ANY,
sizeof(int), &cont, GFP_ATOMIC);
if (nskb) {
if (dsp->up) {
if (dsp->up->send(dsp->up, nskb))
dev_kfree_skb(nskb);
} else
dev_kfree_skb(nskb);
}
if (!ret) {
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
}
break;
case DSP_BF_DISABLE: /* turn blowfish off */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: turn blowfish off\n", __func__);
dsp_bf_cleanup(dsp);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
break;
default:
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: ctrl req %x unhandled\n",
__func__, cont);
ret = -EINVAL;
}
return ret;
}
static void
get_features(struct mISDNchannel *ch)
{
struct dsp *dsp = container_of(ch, struct dsp, ch);
struct mISDN_ctrl_req cq;
if (!ch->peer) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: no peer, no features\n",
__func__);
return;
}
memset(&cq, 0, sizeof(cq));
cq.op = MISDN_CTRL_GETOP;
if (ch->peer->ctrl(ch->peer, CONTROL_CHANNEL, &cq) < 0) {
printk(KERN_DEBUG "%s: CONTROL_CHANNEL failed\n",
__func__);
return;
}
if (cq.op & MISDN_CTRL_RX_OFF)
dsp->features_rx_off = 1;
if (cq.op & MISDN_CTRL_FILL_EMPTY)
dsp->features_fill_empty = 1;
if (dsp_options & DSP_OPT_NOHARDWARE)
return;
if ((cq.op & MISDN_CTRL_HW_FEATURES_OP)) {
cq.op = MISDN_CTRL_HW_FEATURES;
*((u_long *)&cq.p1) = (u_long)&dsp->features;
if (ch->peer->ctrl(ch->peer, CONTROL_CHANNEL, &cq)) {
printk(KERN_DEBUG "%s: 2nd CONTROL_CHANNEL failed\n",
__func__);
}
} else
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: features not supported for %s\n",
__func__, dsp->name);
}
static int
dsp_function(struct mISDNchannel *ch, struct sk_buff *skb)
{
struct dsp *dsp = container_of(ch, struct dsp, ch);
struct mISDNhead *hh;
int ret = 0;
u8 *digits = NULL;
u_long flags;
hh = mISDN_HEAD_P(skb);
switch (hh->prim) {
/* FROM DOWN */
case (PH_DATA_CNF):
dsp->data_pending = 0;
/* trigger next hdlc frame, if any */
if (dsp->hdlc) {
spin_lock_irqsave(&dsp_lock, flags);
if (dsp->b_active)
schedule_work(&dsp->workq);
spin_unlock_irqrestore(&dsp_lock, flags);
}
break;
case (PH_DATA_IND):
case (DL_DATA_IND):
if (skb->len < 1) {
ret = -EINVAL;
break;
}
if (dsp->rx_is_off) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: rx-data during rx_off"
" for %s\n",
__func__, dsp->name);
}
if (dsp->hdlc) {
/* hdlc */
spin_lock_irqsave(&dsp_lock, flags);
dsp_cmx_hdlc(dsp, skb);
spin_unlock_irqrestore(&dsp_lock, flags);
if (dsp->rx_disabled) {
/* if receive is not allowed */
break;
}
hh->prim = DL_DATA_IND;
if (dsp->up)
return dsp->up->send(dsp->up, skb);
break;
}
spin_lock_irqsave(&dsp_lock, flags);
/* decrypt if enabled */
if (dsp->bf_enable)
dsp_bf_decrypt(dsp, skb->data, skb->len);
/* pipeline */
if (dsp->pipeline.inuse)
dsp_pipeline_process_rx(&dsp->pipeline, skb->data,
skb->len, hh->id);
/* change volume if requested */
if (dsp->rx_volume)
dsp_change_volume(skb, dsp->rx_volume);
/* check if dtmf soft decoding is turned on */
if (dsp->dtmf.software) {
digits = dsp_dtmf_goertzel_decode(dsp, skb->data,
skb->len, (dsp_options & DSP_OPT_ULAW) ? 1 : 0);
}
/* we need to process receive data if software */
if (dsp->conf && dsp->conf->software) {
/* process data from card at cmx */
dsp_cmx_receive(dsp, skb);
}
spin_unlock_irqrestore(&dsp_lock, flags);
/* send dtmf result, if any */
if (digits) {
while (*digits) {
int k;
struct sk_buff *nskb;
if (dsp_debug & DEBUG_DSP_DTMF)
printk(KERN_DEBUG "%s: digit"
"(%c) to layer %s\n",
__func__, *digits, dsp->name);
k = *digits | DTMF_TONE_VAL;
nskb = _alloc_mISDN_skb(PH_CONTROL_IND,
MISDN_ID_ANY, sizeof(int), &k,
GFP_ATOMIC);
if (nskb) {
if (dsp->up) {
if (dsp->up->send(
dsp->up, nskb))
dev_kfree_skb(nskb);
} else
dev_kfree_skb(nskb);
}
digits++;
}
}
if (dsp->rx_disabled) {
/* if receive is not allowed */
break;
}
hh->prim = DL_DATA_IND;
if (dsp->up)
return dsp->up->send(dsp->up, skb);
break;
case (PH_CONTROL_IND):
if (dsp_debug & DEBUG_DSP_DTMFCOEFF)
printk(KERN_DEBUG "%s: PH_CONTROL INDICATION "
"received: %x (len %d) %s\n", __func__,
hh->id, skb->len, dsp->name);
switch (hh->id) {
case (DTMF_HFC_COEF): /* getting coefficients */
if (!dsp->dtmf.hardware) {
if (dsp_debug & DEBUG_DSP_DTMFCOEFF)
printk(KERN_DEBUG "%s: ignoring DTMF "
"coefficients from HFC\n",
__func__);
break;
}
digits = dsp_dtmf_goertzel_decode(dsp, skb->data,
skb->len, 2);
while (*digits) {
int k;
struct sk_buff *nskb;
if (dsp_debug & DEBUG_DSP_DTMF)
printk(KERN_DEBUG "%s: digit"
"(%c) to layer %s\n",
__func__, *digits, dsp->name);
k = *digits | DTMF_TONE_VAL;
nskb = _alloc_mISDN_skb(PH_CONTROL_IND,
MISDN_ID_ANY, sizeof(int), &k,
GFP_ATOMIC);
if (nskb) {
if (dsp->up) {
if (dsp->up->send(
dsp->up, nskb))
dev_kfree_skb(nskb);
} else
dev_kfree_skb(nskb);
}
digits++;
}
break;
case (HFC_VOL_CHANGE_TX): /* change volume */
if (skb->len != sizeof(int)) {
ret = -EINVAL;
break;
}
spin_lock_irqsave(&dsp_lock, flags);
dsp->tx_volume = *((int *)skb->data);
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: change tx volume to "
"%d\n", __func__, dsp->tx_volume);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
spin_unlock_irqrestore(&dsp_lock, flags);
break;
default:
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: ctrl ind %x unhandled "
"%s\n", __func__, hh->id, dsp->name);
ret = -EINVAL;
}
break;
case (PH_ACTIVATE_IND):
case (PH_ACTIVATE_CNF):
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: b_channel is now active %s\n",
__func__, dsp->name);
/* bchannel now active */
spin_lock_irqsave(&dsp_lock, flags);
dsp->b_active = 1;
dsp->data_pending = 0;
dsp->rx_init = 1;
/* rx_W and rx_R will be adjusted on first frame */
dsp->rx_W = 0;
dsp->rx_R = 0;
memset(dsp->rx_buff, 0, sizeof(dsp->rx_buff));
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
spin_unlock_irqrestore(&dsp_lock, flags);
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: done with activation, sending "
"confirm to user space. %s\n", __func__,
dsp->name);
/* send activation to upper layer */
hh->prim = DL_ESTABLISH_CNF;
if (dsp->up)
return dsp->up->send(dsp->up, skb);
break;
case (PH_DEACTIVATE_IND):
case (PH_DEACTIVATE_CNF):
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: b_channel is now inactive %s\n",
__func__, dsp->name);
/* bchannel now inactive */
spin_lock_irqsave(&dsp_lock, flags);
dsp->b_active = 0;
dsp->data_pending = 0;
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
spin_unlock_irqrestore(&dsp_lock, flags);
hh->prim = DL_RELEASE_CNF;
if (dsp->up)
return dsp->up->send(dsp->up, skb);
break;
/* FROM UP */
case (DL_DATA_REQ):
case (PH_DATA_REQ):
if (skb->len < 1) {
ret = -EINVAL;
break;
}
if (dsp->hdlc) {
/* hdlc */
if (!dsp->b_active) {
ret = -EIO;
break;
}
hh->prim = PH_DATA_REQ;
spin_lock_irqsave(&dsp_lock, flags);
skb_queue_tail(&dsp->sendq, skb);
schedule_work(&dsp->workq);
spin_unlock_irqrestore(&dsp_lock, flags);
return 0;
}
/* send data to tx-buffer (if no tone is played) */
if (!dsp->tone.tone) {
spin_lock_irqsave(&dsp_lock, flags);
dsp_cmx_transmit(dsp, skb);
spin_unlock_irqrestore(&dsp_lock, flags);
}
break;
case (PH_CONTROL_REQ):
spin_lock_irqsave(&dsp_lock, flags);
ret = dsp_control_req(dsp, hh, skb);
spin_unlock_irqrestore(&dsp_lock, flags);
break;
case (DL_ESTABLISH_REQ):
case (PH_ACTIVATE_REQ):
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: activating b_channel %s\n",
__func__, dsp->name);
if (dsp->dtmf.hardware || dsp->dtmf.software)
dsp_dtmf_goertzel_init(dsp);
get_features(ch);
/* enable fill_empty feature */
if (dsp->features_fill_empty)
dsp_fill_empty(dsp);
/* send ph_activate */
hh->prim = PH_ACTIVATE_REQ;
if (ch->peer)
return ch->recv(ch->peer, skb);
break;
case (DL_RELEASE_REQ):
case (PH_DEACTIVATE_REQ):
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: releasing b_channel %s\n",
__func__, dsp->name);
spin_lock_irqsave(&dsp_lock, flags);
dsp->tone.tone = 0;
dsp->tone.hardware = 0;
dsp->tone.software = 0;
if (timer_pending(&dsp->tone.tl))
del_timer(&dsp->tone.tl);
if (dsp->conf)
dsp_cmx_conf(dsp, 0); /* dsp_cmx_hardware will also be
called here */
skb_queue_purge(&dsp->sendq);
spin_unlock_irqrestore(&dsp_lock, flags);
hh->prim = PH_DEACTIVATE_REQ;
if (ch->peer)
return ch->recv(ch->peer, skb);
break;
default:
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: msg %x unhandled %s\n",
__func__, hh->prim, dsp->name);
ret = -EINVAL;
}
if (!ret)
dev_kfree_skb(skb);
return ret;
}
static int
dsp_ctrl(struct mISDNchannel *ch, u_int cmd, void *arg)
{
struct dsp *dsp = container_of(ch, struct dsp, ch);
u_long flags;
int err = 0;
if (debug & DEBUG_DSP_CTRL)
printk(KERN_DEBUG "%s:(%x)\n", __func__, cmd);
switch (cmd) {
case OPEN_CHANNEL:
break;
case CLOSE_CHANNEL:
if (dsp->ch.peer)
dsp->ch.peer->ctrl(dsp->ch.peer, CLOSE_CHANNEL, NULL);
/* wait until workqueue has finished,
* must lock here, or we may hit send-process currently
* queueing. */
spin_lock_irqsave(&dsp_lock, flags);
dsp->b_active = 0;
spin_unlock_irqrestore(&dsp_lock, flags);
/* MUST not be locked, because it waits until queue is done. */
cancel_work_sync(&dsp->workq);
spin_lock_irqsave(&dsp_lock, flags);
if (timer_pending(&dsp->tone.tl))
del_timer(&dsp->tone.tl);
skb_queue_purge(&dsp->sendq);
if (dsp_debug & DEBUG_DSP_CTRL)
printk(KERN_DEBUG "%s: releasing member %s\n",
__func__, dsp->name);
dsp->b_active = 0;
dsp_cmx_conf(dsp, 0); /* dsp_cmx_hardware will also be called
here */
dsp_pipeline_destroy(&dsp->pipeline);
if (dsp_debug & DEBUG_DSP_CTRL)
printk(KERN_DEBUG "%s: remove & destroy object %s\n",
__func__, dsp->name);
list_del(&dsp->list);
spin_unlock_irqrestore(&dsp_lock, flags);
if (dsp_debug & DEBUG_DSP_CTRL)
printk(KERN_DEBUG "%s: dsp instance released\n",
__func__);
vfree(dsp);
module_put(THIS_MODULE);
break;
}
return err;
}
static void
dsp_send_bh(struct work_struct *work)
{
struct dsp *dsp = container_of(work, struct dsp, workq);
struct sk_buff *skb;
struct mISDNhead *hh;
if (dsp->hdlc && dsp->data_pending)
return; /* wait until data has been acknowledged */
/* send queued data */
while ((skb = skb_dequeue(&dsp->sendq))) {
/* in locked date, we must have still data in queue */
if (dsp->data_pending) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: fifo full %s, this is "
"no bug!\n", __func__, dsp->name);
/* flush transparent data, if not acked */
dev_kfree_skb(skb);
continue;
}
hh = mISDN_HEAD_P(skb);
if (hh->prim == DL_DATA_REQ) {
/* send packet up */
if (dsp->up) {
if (dsp->up->send(dsp->up, skb))
dev_kfree_skb(skb);
} else
dev_kfree_skb(skb);
} else {
/* send packet down */
if (dsp->ch.peer) {
dsp->data_pending = 1;
if (dsp->ch.recv(dsp->ch.peer, skb)) {
dev_kfree_skb(skb);
dsp->data_pending = 0;
}
} else
dev_kfree_skb(skb);
}
}
}
static int
dspcreate(struct channel_req *crq)
{
struct dsp *ndsp;
u_long flags;
if (crq->protocol != ISDN_P_B_L2DSP
&& crq->protocol != ISDN_P_B_L2DSPHDLC)
return -EPROTONOSUPPORT;
ndsp = vzalloc(sizeof(struct dsp));
if (!ndsp) {
printk(KERN_ERR "%s: vmalloc struct dsp failed\n", __func__);
return -ENOMEM;
}
if (dsp_debug & DEBUG_DSP_CTRL)
printk(KERN_DEBUG "%s: creating new dsp instance\n", __func__);
/* default enabled */
INIT_WORK(&ndsp->workq, (void *)dsp_send_bh);
skb_queue_head_init(&ndsp->sendq);
ndsp->ch.send = dsp_function;
ndsp->ch.ctrl = dsp_ctrl;
ndsp->up = crq->ch;
crq->ch = &ndsp->ch;
if (crq->protocol == ISDN_P_B_L2DSP) {
crq->protocol = ISDN_P_B_RAW;
ndsp->hdlc = 0;
} else {
crq->protocol = ISDN_P_B_HDLC;
ndsp->hdlc = 1;
}
if (!try_module_get(THIS_MODULE))
printk(KERN_WARNING "%s:cannot get module\n",
__func__);
sprintf(ndsp->name, "DSP_C%x(0x%p)",
ndsp->up->st->dev->id + 1, ndsp);
/* set frame size to start */
ndsp->features.hfc_id = -1; /* current PCM id */
ndsp->features.pcm_id = -1; /* current PCM id */
ndsp->pcm_slot_rx = -1; /* current CPM slot */
ndsp->pcm_slot_tx = -1;
ndsp->pcm_bank_rx = -1;
ndsp->pcm_bank_tx = -1;
ndsp->hfc_conf = -1; /* current conference number */
/* set tone timer */
ndsp->tone.tl.function = (void *)dsp_tone_timeout;
ndsp->tone.tl.data = (long) ndsp;
init_timer(&ndsp->tone.tl);
if (dtmfthreshold < 20 || dtmfthreshold > 500)
dtmfthreshold = 200;
ndsp->dtmf.treshold = dtmfthreshold * 10000;
/* init pipeline append to list */
spin_lock_irqsave(&dsp_lock, flags);
dsp_pipeline_init(&ndsp->pipeline);
list_add_tail(&ndsp->list, &dsp_ilist);
spin_unlock_irqrestore(&dsp_lock, flags);
return 0;
}
static struct Bprotocol DSP = {
.Bprotocols = (1 << (ISDN_P_B_L2DSP & ISDN_P_B_MASK))
| (1 << (ISDN_P_B_L2DSPHDLC & ISDN_P_B_MASK)),
.name = "dsp",
.create = dspcreate
};
static int __init dsp_init(void)
{
int err;
int tics;
printk(KERN_INFO "DSP module %s\n", mISDN_dsp_revision);
dsp_options = options;
dsp_debug = debug;
/* set packet size */
dsp_poll = poll;
if (dsp_poll) {
if (dsp_poll > MAX_POLL) {
printk(KERN_ERR "%s: Wrong poll value (%d), use %d "
"maximum.\n", __func__, poll, MAX_POLL);
err = -EINVAL;
return err;
}
if (dsp_poll < 8) {
printk(KERN_ERR "%s: Wrong poll value (%d), use 8 "
"minimum.\n", __func__, dsp_poll);
err = -EINVAL;
return err;
}
dsp_tics = poll * HZ / 8000;
if (dsp_tics * 8000 != poll * HZ) {
printk(KERN_INFO "mISDN_dsp: Cannot clock every %d "
"samples (0,125 ms). It is not a multiple of "
"%d HZ.\n", poll, HZ);
err = -EINVAL;
return err;
}
} else {
poll = 8;
while (poll <= MAX_POLL) {
tics = (poll * HZ) / 8000;
if (tics * 8000 == poll * HZ) {
dsp_tics = tics;
dsp_poll = poll;
if (poll >= 64)
break;
}
poll++;
}
}
if (dsp_poll == 0) {
printk(KERN_INFO "mISDN_dsp: There is no multiple of kernel "
"clock that equals exactly the duration of 8-256 "
"samples. (Choose kernel clock speed like 100, 250, "
"300, 1000)\n");
err = -EINVAL;
return err;
}
printk(KERN_INFO "mISDN_dsp: DSP clocks every %d samples. This equals "
"%d jiffies.\n", dsp_poll, dsp_tics);
spin_lock_init(&dsp_lock);
INIT_LIST_HEAD(&dsp_ilist);
INIT_LIST_HEAD(&conf_ilist);
/* init conversion tables */
dsp_audio_generate_law_tables();
dsp_silence = (dsp_options & DSP_OPT_ULAW) ? 0xff : 0x2a;
dsp_audio_law_to_s32 = (dsp_options & DSP_OPT_ULAW) ?
dsp_audio_ulaw_to_s32 : dsp_audio_alaw_to_s32;
dsp_audio_generate_s2law_table();
dsp_audio_generate_seven();
dsp_audio_generate_mix_table();
if (dsp_options & DSP_OPT_ULAW)
dsp_audio_generate_ulaw_samples();
dsp_audio_generate_volume_changes();
err = dsp_pipeline_module_init();
if (err) {
printk(KERN_ERR "mISDN_dsp: Can't initialize pipeline, "
"error(%d)\n", err);
return err;
}
err = mISDN_register_Bprotocol(&DSP);
if (err) {
printk(KERN_ERR "Can't register %s error(%d)\n", DSP.name, err);
return err;
}
/* set sample timer */
dsp_spl_tl.function = (void *)dsp_cmx_send;
dsp_spl_tl.data = 0;
init_timer(&dsp_spl_tl);
dsp_spl_tl.expires = jiffies + dsp_tics;
dsp_spl_jiffies = dsp_spl_tl.expires;
add_timer(&dsp_spl_tl);
return 0;
}
static void __exit dsp_cleanup(void)
{
mISDN_unregister_Bprotocol(&DSP);
if (timer_pending(&dsp_spl_tl))
del_timer(&dsp_spl_tl);
if (!list_empty(&dsp_ilist)) {
printk(KERN_ERR "mISDN_dsp: Audio DSP object inst list not "
"empty.\n");
}
if (!list_empty(&conf_ilist)) {
printk(KERN_ERR "mISDN_dsp: Conference list not empty. Not "
"all memory freed.\n");
}
dsp_pipeline_module_exit();
}
module_init(dsp_init);
module_exit(dsp_cleanup);
| gpl-2.0 |
MoKee/android_kernel_htc_msm8960 | drivers/isdn/mISDN/dsp_core.c | 4809 | 33953 | /*
* Author Andreas Eversberg (jolly@eversberg.eu)
* Based on source code structure by
* Karsten Keil (keil@isdn4linux.de)
*
* This file is (c) under GNU PUBLIC LICENSE
* For changes and modifications please read
* ../../../Documentation/isdn/mISDN.cert
*
* Thanks to Karsten Keil (great drivers)
* Cologne Chip (great chips)
*
* This module does:
* Real-time tone generation
* DTMF detection
* Real-time cross-connection and conferrence
* Compensate jitter due to system load and hardware fault.
* All features are done in kernel space and will be realized
* using hardware, if available and supported by chip set.
* Blowfish encryption/decryption
*/
/* STRUCTURE:
*
* The dsp module provides layer 2 for b-channels (64kbit). It provides
* transparent audio forwarding with special digital signal processing:
*
* - (1) generation of tones
* - (2) detection of dtmf tones
* - (3) crossconnecting and conferences (clocking)
* - (4) echo generation for delay test
* - (5) volume control
* - (6) disable receive data
* - (7) pipeline
* - (8) encryption/decryption
*
* Look:
* TX RX
* ------upper layer------
* | ^
* | |(6)
* v |
* +-----+-------------+-----+
* |(3)(4) |
* | CMX |
* | |
* | +-------------+
* | | ^
* | | |
* |+---------+| +----+----+
* ||(1) || |(2) |
* || || | |
* || Tones || | DTMF |
* || || | |
* || || | |
* |+----+----+| +----+----+
* +-----+-----+ ^
* | |
* v |
* +----+----+ +----+----+
* |(5) | |(5) |
* | | | |
* |TX Volume| |RX Volume|
* | | | |
* | | | |
* +----+----+ +----+----+
* | ^
* | |
* v |
* +----+-------------+----+
* |(7) |
* | |
* | Pipeline Processing |
* | |
* | |
* +----+-------------+----+
* | ^
* | |
* v |
* +----+----+ +----+----+
* |(8) | |(8) |
* | | | |
* | Encrypt | | Decrypt |
* | | | |
* | | | |
* +----+----+ +----+----+
* | ^
* | |
* v |
* ------card layer------
* TX RX
*
* Above you can see the logical data flow. If software is used to do the
* process, it is actually the real data flow. If hardware is used, data
* may not flow, but hardware commands to the card, to provide the data flow
* as shown.
*
* NOTE: The channel must be activated in order to make dsp work, even if
* no data flow to the upper layer is intended. Activation can be done
* after and before controlling the setting using PH_CONTROL requests.
*
* DTMF: Will be detected by hardware if possible. It is done before CMX
* processing.
*
* Tones: Will be generated via software if endless looped audio fifos are
* not supported by hardware. Tones will override all data from CMX.
* It is not required to join a conference to use tones at any time.
*
* CMX: Is transparent when not used. When it is used, it will do
* crossconnections and conferences via software if not possible through
* hardware. If hardware capability is available, hardware is used.
*
* Echo: Is generated by CMX and is used to check performance of hard and
* software CMX.
*
* The CMX has special functions for conferences with one, two and more
* members. It will allow different types of data flow. Receive and transmit
* data to/form upper layer may be swithed on/off individually without losing
* features of CMX, Tones and DTMF.
*
* Echo Cancellation: Sometimes we like to cancel echo from the interface.
* Note that a VoIP call may not have echo caused by the IP phone. The echo
* is generated by the telephone line connected to it. Because the delay
* is high, it becomes an echo. RESULT: Echo Cachelation is required if
* both echo AND delay is applied to an interface.
* Remember that software CMX always generates a more or less delay.
*
* If all used features can be realized in hardware, and if transmit and/or
* receive data ist disabled, the card may not send/receive any data at all.
* Not receiving is useful if only announcements are played. Not sending is
* useful if an answering machine records audio. Not sending and receiving is
* useful during most states of the call. If supported by hardware, tones
* will be played without cpu load. Small PBXs and NT-Mode applications will
* not need expensive hardware when processing calls.
*
*
* LOCKING:
*
* When data is received from upper or lower layer (card), the complete dsp
* module is locked by a global lock. This lock MUST lock irq, because it
* must lock timer events by DSP poll timer.
* When data is ready to be transmitted down, the data is queued and sent
* outside lock and timer event.
* PH_CONTROL must not change any settings, join or split conference members
* during process of data.
*
* HDLC:
*
* It works quite the same as transparent, except that HDLC data is forwarded
* to all other conference members if no hardware bridging is possible.
* Send data will be writte to sendq. Sendq will be sent if confirm is received.
* Conference cannot join, if one member is not hdlc.
*
*/
#include <linux/delay.h>
#include <linux/gfp.h>
#include <linux/mISDNif.h>
#include <linux/mISDNdsp.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include "core.h"
#include "dsp.h"
static const char *mISDN_dsp_revision = "2.0";
static int debug;
static int options;
static int poll;
static int dtmfthreshold = 100;
MODULE_AUTHOR("Andreas Eversberg");
module_param(debug, uint, S_IRUGO | S_IWUSR);
module_param(options, uint, S_IRUGO | S_IWUSR);
module_param(poll, uint, S_IRUGO | S_IWUSR);
module_param(dtmfthreshold, uint, S_IRUGO | S_IWUSR);
MODULE_LICENSE("GPL");
/*int spinnest = 0;*/
spinlock_t dsp_lock; /* global dsp lock */
struct list_head dsp_ilist;
struct list_head conf_ilist;
int dsp_debug;
int dsp_options;
int dsp_poll, dsp_tics;
/* check if rx may be turned off or must be turned on */
static void
dsp_rx_off_member(struct dsp *dsp)
{
struct mISDN_ctrl_req cq;
int rx_off = 1;
memset(&cq, 0, sizeof(cq));
if (!dsp->features_rx_off)
return;
/* not disabled */
if (!dsp->rx_disabled)
rx_off = 0;
/* software dtmf */
else if (dsp->dtmf.software)
rx_off = 0;
/* echo in software */
else if (dsp->echo.software)
rx_off = 0;
/* bridge in software */
else if (dsp->conf && dsp->conf->software)
rx_off = 0;
/* data is not required by user space and not required
* for echo dtmf detection, soft-echo, soft-bridging */
if (rx_off == dsp->rx_is_off)
return;
if (!dsp->ch.peer) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: no peer, no rx_off\n",
__func__);
return;
}
cq.op = MISDN_CTRL_RX_OFF;
cq.p1 = rx_off;
if (dsp->ch.peer->ctrl(dsp->ch.peer, CONTROL_CHANNEL, &cq)) {
printk(KERN_DEBUG "%s: 2nd CONTROL_CHANNEL failed\n",
__func__);
return;
}
dsp->rx_is_off = rx_off;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: %s set rx_off = %d\n",
__func__, dsp->name, rx_off);
}
static void
dsp_rx_off(struct dsp *dsp)
{
struct dsp_conf_member *member;
if (dsp_options & DSP_OPT_NOHARDWARE)
return;
/* no conf */
if (!dsp->conf) {
dsp_rx_off_member(dsp);
return;
}
/* check all members in conf */
list_for_each_entry(member, &dsp->conf->mlist, list) {
dsp_rx_off_member(member->dsp);
}
}
/* enable "fill empty" feature */
static void
dsp_fill_empty(struct dsp *dsp)
{
struct mISDN_ctrl_req cq;
memset(&cq, 0, sizeof(cq));
if (!dsp->ch.peer) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: no peer, no fill_empty\n",
__func__);
return;
}
cq.op = MISDN_CTRL_FILL_EMPTY;
cq.p1 = 1;
if (dsp->ch.peer->ctrl(dsp->ch.peer, CONTROL_CHANNEL, &cq)) {
printk(KERN_DEBUG "%s: CONTROL_CHANNEL failed\n",
__func__);
return;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: %s set fill_empty = 1\n",
__func__, dsp->name);
}
static int
dsp_control_req(struct dsp *dsp, struct mISDNhead *hh, struct sk_buff *skb)
{
struct sk_buff *nskb;
int ret = 0;
int cont;
u8 *data;
int len;
if (skb->len < sizeof(int))
printk(KERN_ERR "%s: PH_CONTROL message too short\n", __func__);
cont = *((int *)skb->data);
len = skb->len - sizeof(int);
data = skb->data + sizeof(int);
switch (cont) {
case DTMF_TONE_START: /* turn on DTMF */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: start dtmf\n", __func__);
if (len == sizeof(int)) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_NOTICE "changing DTMF Threshold "
"to %d\n", *((int *)data));
dsp->dtmf.treshold = (*(int *)data) * 10000;
}
dsp->dtmf.enable = 1;
/* init goertzel */
dsp_dtmf_goertzel_init(dsp);
/* check dtmf hardware */
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
break;
case DTMF_TONE_STOP: /* turn off DTMF */
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: stop dtmf\n", __func__);
dsp->dtmf.enable = 0;
dsp->dtmf.hardware = 0;
dsp->dtmf.software = 0;
break;
case DSP_CONF_JOIN: /* join / update conference */
if (len < sizeof(int)) {
ret = -EINVAL;
break;
}
if (*((u32 *)data) == 0)
goto conf_split;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: join conference %d\n",
__func__, *((u32 *)data));
ret = dsp_cmx_conf(dsp, *((u32 *)data));
/* dsp_cmx_hardware will also be called here */
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_CONF_SPLIT: /* remove from conference */
conf_split:
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: release conference\n", __func__);
ret = dsp_cmx_conf(dsp, 0);
/* dsp_cmx_hardware will also be called here */
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
dsp_rx_off(dsp);
break;
case DSP_TONE_PATT_ON: /* play tone */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len < sizeof(int)) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: turn tone 0x%x on\n",
__func__, *((int *)skb->data));
ret = dsp_tone(dsp, *((int *)data));
if (!ret) {
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
}
if (!dsp->tone.tone)
goto tone_off;
break;
case DSP_TONE_PATT_OFF: /* stop tone */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: turn tone off\n", __func__);
dsp_tone(dsp, 0);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
/* reset tx buffers (user space data) */
tone_off:
dsp->rx_W = 0;
dsp->rx_R = 0;
break;
case DSP_VOL_CHANGE_TX: /* change volume */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len < sizeof(int)) {
ret = -EINVAL;
break;
}
dsp->tx_volume = *((int *)data);
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: change tx vol to %d\n",
__func__, dsp->tx_volume);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
break;
case DSP_VOL_CHANGE_RX: /* change volume */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len < sizeof(int)) {
ret = -EINVAL;
break;
}
dsp->rx_volume = *((int *)data);
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: change rx vol to %d\n",
__func__, dsp->tx_volume);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
break;
case DSP_ECHO_ON: /* enable echo */
dsp->echo.software = 1; /* soft echo */
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: enable cmx-echo\n", __func__);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_ECHO_OFF: /* disable echo */
dsp->echo.software = 0;
dsp->echo.hardware = 0;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: disable cmx-echo\n", __func__);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_RECEIVE_ON: /* enable receive to user space */
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: enable receive to user "
"space\n", __func__);
dsp->rx_disabled = 0;
dsp_rx_off(dsp);
break;
case DSP_RECEIVE_OFF: /* disable receive to user space */
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: disable receive to "
"user space\n", __func__);
dsp->rx_disabled = 1;
dsp_rx_off(dsp);
break;
case DSP_MIX_ON: /* enable mixing of tx data */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: enable mixing of "
"tx-data with conf mebers\n", __func__);
dsp->tx_mix = 1;
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_MIX_OFF: /* disable mixing of tx data */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: disable mixing of "
"tx-data with conf mebers\n", __func__);
dsp->tx_mix = 0;
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_TXDATA_ON: /* enable txdata */
dsp->tx_data = 1;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: enable tx-data\n", __func__);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_TXDATA_OFF: /* disable txdata */
dsp->tx_data = 0;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: disable tx-data\n", __func__);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
if (dsp_debug & DEBUG_DSP_CMX)
dsp_cmx_debug(dsp);
break;
case DSP_DELAY: /* use delay algorithm instead of dynamic
jitter algorithm */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len < sizeof(int)) {
ret = -EINVAL;
break;
}
dsp->cmx_delay = (*((int *)data)) << 3;
/* milliseconds to samples */
if (dsp->cmx_delay >= (CMX_BUFF_HALF >> 1))
/* clip to half of maximum usable buffer
(half of half buffer) */
dsp->cmx_delay = (CMX_BUFF_HALF >> 1) - 1;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: use delay algorithm to "
"compensate jitter (%d samples)\n",
__func__, dsp->cmx_delay);
break;
case DSP_JITTER: /* use dynamic jitter algorithm instead of
delay algorithm */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
dsp->cmx_delay = 0;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: use jitter algorithm to "
"compensate jitter\n", __func__);
break;
case DSP_TX_DEJITTER: /* use dynamic jitter algorithm for tx-buffer */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
dsp->tx_dejitter = 1;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: use dejitter on TX "
"buffer\n", __func__);
break;
case DSP_TX_DEJ_OFF: /* use tx-buffer without dejittering*/
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
dsp->tx_dejitter = 0;
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: use TX buffer without "
"dejittering\n", __func__);
break;
case DSP_PIPELINE_CFG:
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len > 0 && ((char *)data)[len - 1]) {
printk(KERN_DEBUG "%s: pipeline config string "
"is not NULL terminated!\n", __func__);
ret = -EINVAL;
} else {
dsp->pipeline.inuse = 1;
dsp_cmx_hardware(dsp->conf, dsp);
ret = dsp_pipeline_build(&dsp->pipeline,
len > 0 ? data : NULL);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
}
break;
case DSP_BF_ENABLE_KEY: /* turn blowfish on */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (len < 4 || len > 56) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: turn blowfish on (key "
"not shown)\n", __func__);
ret = dsp_bf_init(dsp, (u8 *)data, len);
/* set new cont */
if (!ret)
cont = DSP_BF_ACCEPT;
else
cont = DSP_BF_REJECT;
/* send indication if it worked to set it */
nskb = _alloc_mISDN_skb(PH_CONTROL_IND, MISDN_ID_ANY,
sizeof(int), &cont, GFP_ATOMIC);
if (nskb) {
if (dsp->up) {
if (dsp->up->send(dsp->up, nskb))
dev_kfree_skb(nskb);
} else
dev_kfree_skb(nskb);
}
if (!ret) {
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
}
break;
case DSP_BF_DISABLE: /* turn blowfish off */
if (dsp->hdlc) {
ret = -EINVAL;
break;
}
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: turn blowfish off\n", __func__);
dsp_bf_cleanup(dsp);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
break;
default:
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: ctrl req %x unhandled\n",
__func__, cont);
ret = -EINVAL;
}
return ret;
}
static void
get_features(struct mISDNchannel *ch)
{
struct dsp *dsp = container_of(ch, struct dsp, ch);
struct mISDN_ctrl_req cq;
if (!ch->peer) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: no peer, no features\n",
__func__);
return;
}
memset(&cq, 0, sizeof(cq));
cq.op = MISDN_CTRL_GETOP;
if (ch->peer->ctrl(ch->peer, CONTROL_CHANNEL, &cq) < 0) {
printk(KERN_DEBUG "%s: CONTROL_CHANNEL failed\n",
__func__);
return;
}
if (cq.op & MISDN_CTRL_RX_OFF)
dsp->features_rx_off = 1;
if (cq.op & MISDN_CTRL_FILL_EMPTY)
dsp->features_fill_empty = 1;
if (dsp_options & DSP_OPT_NOHARDWARE)
return;
if ((cq.op & MISDN_CTRL_HW_FEATURES_OP)) {
cq.op = MISDN_CTRL_HW_FEATURES;
*((u_long *)&cq.p1) = (u_long)&dsp->features;
if (ch->peer->ctrl(ch->peer, CONTROL_CHANNEL, &cq)) {
printk(KERN_DEBUG "%s: 2nd CONTROL_CHANNEL failed\n",
__func__);
}
} else
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: features not supported for %s\n",
__func__, dsp->name);
}
static int
dsp_function(struct mISDNchannel *ch, struct sk_buff *skb)
{
struct dsp *dsp = container_of(ch, struct dsp, ch);
struct mISDNhead *hh;
int ret = 0;
u8 *digits = NULL;
u_long flags;
hh = mISDN_HEAD_P(skb);
switch (hh->prim) {
/* FROM DOWN */
case (PH_DATA_CNF):
dsp->data_pending = 0;
/* trigger next hdlc frame, if any */
if (dsp->hdlc) {
spin_lock_irqsave(&dsp_lock, flags);
if (dsp->b_active)
schedule_work(&dsp->workq);
spin_unlock_irqrestore(&dsp_lock, flags);
}
break;
case (PH_DATA_IND):
case (DL_DATA_IND):
if (skb->len < 1) {
ret = -EINVAL;
break;
}
if (dsp->rx_is_off) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: rx-data during rx_off"
" for %s\n",
__func__, dsp->name);
}
if (dsp->hdlc) {
/* hdlc */
spin_lock_irqsave(&dsp_lock, flags);
dsp_cmx_hdlc(dsp, skb);
spin_unlock_irqrestore(&dsp_lock, flags);
if (dsp->rx_disabled) {
/* if receive is not allowed */
break;
}
hh->prim = DL_DATA_IND;
if (dsp->up)
return dsp->up->send(dsp->up, skb);
break;
}
spin_lock_irqsave(&dsp_lock, flags);
/* decrypt if enabled */
if (dsp->bf_enable)
dsp_bf_decrypt(dsp, skb->data, skb->len);
/* pipeline */
if (dsp->pipeline.inuse)
dsp_pipeline_process_rx(&dsp->pipeline, skb->data,
skb->len, hh->id);
/* change volume if requested */
if (dsp->rx_volume)
dsp_change_volume(skb, dsp->rx_volume);
/* check if dtmf soft decoding is turned on */
if (dsp->dtmf.software) {
digits = dsp_dtmf_goertzel_decode(dsp, skb->data,
skb->len, (dsp_options & DSP_OPT_ULAW) ? 1 : 0);
}
/* we need to process receive data if software */
if (dsp->conf && dsp->conf->software) {
/* process data from card at cmx */
dsp_cmx_receive(dsp, skb);
}
spin_unlock_irqrestore(&dsp_lock, flags);
/* send dtmf result, if any */
if (digits) {
while (*digits) {
int k;
struct sk_buff *nskb;
if (dsp_debug & DEBUG_DSP_DTMF)
printk(KERN_DEBUG "%s: digit"
"(%c) to layer %s\n",
__func__, *digits, dsp->name);
k = *digits | DTMF_TONE_VAL;
nskb = _alloc_mISDN_skb(PH_CONTROL_IND,
MISDN_ID_ANY, sizeof(int), &k,
GFP_ATOMIC);
if (nskb) {
if (dsp->up) {
if (dsp->up->send(
dsp->up, nskb))
dev_kfree_skb(nskb);
} else
dev_kfree_skb(nskb);
}
digits++;
}
}
if (dsp->rx_disabled) {
/* if receive is not allowed */
break;
}
hh->prim = DL_DATA_IND;
if (dsp->up)
return dsp->up->send(dsp->up, skb);
break;
case (PH_CONTROL_IND):
if (dsp_debug & DEBUG_DSP_DTMFCOEFF)
printk(KERN_DEBUG "%s: PH_CONTROL INDICATION "
"received: %x (len %d) %s\n", __func__,
hh->id, skb->len, dsp->name);
switch (hh->id) {
case (DTMF_HFC_COEF): /* getting coefficients */
if (!dsp->dtmf.hardware) {
if (dsp_debug & DEBUG_DSP_DTMFCOEFF)
printk(KERN_DEBUG "%s: ignoring DTMF "
"coefficients from HFC\n",
__func__);
break;
}
digits = dsp_dtmf_goertzel_decode(dsp, skb->data,
skb->len, 2);
while (*digits) {
int k;
struct sk_buff *nskb;
if (dsp_debug & DEBUG_DSP_DTMF)
printk(KERN_DEBUG "%s: digit"
"(%c) to layer %s\n",
__func__, *digits, dsp->name);
k = *digits | DTMF_TONE_VAL;
nskb = _alloc_mISDN_skb(PH_CONTROL_IND,
MISDN_ID_ANY, sizeof(int), &k,
GFP_ATOMIC);
if (nskb) {
if (dsp->up) {
if (dsp->up->send(
dsp->up, nskb))
dev_kfree_skb(nskb);
} else
dev_kfree_skb(nskb);
}
digits++;
}
break;
case (HFC_VOL_CHANGE_TX): /* change volume */
if (skb->len != sizeof(int)) {
ret = -EINVAL;
break;
}
spin_lock_irqsave(&dsp_lock, flags);
dsp->tx_volume = *((int *)skb->data);
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: change tx volume to "
"%d\n", __func__, dsp->tx_volume);
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
spin_unlock_irqrestore(&dsp_lock, flags);
break;
default:
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: ctrl ind %x unhandled "
"%s\n", __func__, hh->id, dsp->name);
ret = -EINVAL;
}
break;
case (PH_ACTIVATE_IND):
case (PH_ACTIVATE_CNF):
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: b_channel is now active %s\n",
__func__, dsp->name);
/* bchannel now active */
spin_lock_irqsave(&dsp_lock, flags);
dsp->b_active = 1;
dsp->data_pending = 0;
dsp->rx_init = 1;
/* rx_W and rx_R will be adjusted on first frame */
dsp->rx_W = 0;
dsp->rx_R = 0;
memset(dsp->rx_buff, 0, sizeof(dsp->rx_buff));
dsp_cmx_hardware(dsp->conf, dsp);
dsp_dtmf_hardware(dsp);
dsp_rx_off(dsp);
spin_unlock_irqrestore(&dsp_lock, flags);
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: done with activation, sending "
"confirm to user space. %s\n", __func__,
dsp->name);
/* send activation to upper layer */
hh->prim = DL_ESTABLISH_CNF;
if (dsp->up)
return dsp->up->send(dsp->up, skb);
break;
case (PH_DEACTIVATE_IND):
case (PH_DEACTIVATE_CNF):
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: b_channel is now inactive %s\n",
__func__, dsp->name);
/* bchannel now inactive */
spin_lock_irqsave(&dsp_lock, flags);
dsp->b_active = 0;
dsp->data_pending = 0;
dsp_cmx_hardware(dsp->conf, dsp);
dsp_rx_off(dsp);
spin_unlock_irqrestore(&dsp_lock, flags);
hh->prim = DL_RELEASE_CNF;
if (dsp->up)
return dsp->up->send(dsp->up, skb);
break;
/* FROM UP */
case (DL_DATA_REQ):
case (PH_DATA_REQ):
if (skb->len < 1) {
ret = -EINVAL;
break;
}
if (dsp->hdlc) {
/* hdlc */
if (!dsp->b_active) {
ret = -EIO;
break;
}
hh->prim = PH_DATA_REQ;
spin_lock_irqsave(&dsp_lock, flags);
skb_queue_tail(&dsp->sendq, skb);
schedule_work(&dsp->workq);
spin_unlock_irqrestore(&dsp_lock, flags);
return 0;
}
/* send data to tx-buffer (if no tone is played) */
if (!dsp->tone.tone) {
spin_lock_irqsave(&dsp_lock, flags);
dsp_cmx_transmit(dsp, skb);
spin_unlock_irqrestore(&dsp_lock, flags);
}
break;
case (PH_CONTROL_REQ):
spin_lock_irqsave(&dsp_lock, flags);
ret = dsp_control_req(dsp, hh, skb);
spin_unlock_irqrestore(&dsp_lock, flags);
break;
case (DL_ESTABLISH_REQ):
case (PH_ACTIVATE_REQ):
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: activating b_channel %s\n",
__func__, dsp->name);
if (dsp->dtmf.hardware || dsp->dtmf.software)
dsp_dtmf_goertzel_init(dsp);
get_features(ch);
/* enable fill_empty feature */
if (dsp->features_fill_empty)
dsp_fill_empty(dsp);
/* send ph_activate */
hh->prim = PH_ACTIVATE_REQ;
if (ch->peer)
return ch->recv(ch->peer, skb);
break;
case (DL_RELEASE_REQ):
case (PH_DEACTIVATE_REQ):
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: releasing b_channel %s\n",
__func__, dsp->name);
spin_lock_irqsave(&dsp_lock, flags);
dsp->tone.tone = 0;
dsp->tone.hardware = 0;
dsp->tone.software = 0;
if (timer_pending(&dsp->tone.tl))
del_timer(&dsp->tone.tl);
if (dsp->conf)
dsp_cmx_conf(dsp, 0); /* dsp_cmx_hardware will also be
called here */
skb_queue_purge(&dsp->sendq);
spin_unlock_irqrestore(&dsp_lock, flags);
hh->prim = PH_DEACTIVATE_REQ;
if (ch->peer)
return ch->recv(ch->peer, skb);
break;
default:
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: msg %x unhandled %s\n",
__func__, hh->prim, dsp->name);
ret = -EINVAL;
}
if (!ret)
dev_kfree_skb(skb);
return ret;
}
static int
dsp_ctrl(struct mISDNchannel *ch, u_int cmd, void *arg)
{
struct dsp *dsp = container_of(ch, struct dsp, ch);
u_long flags;
int err = 0;
if (debug & DEBUG_DSP_CTRL)
printk(KERN_DEBUG "%s:(%x)\n", __func__, cmd);
switch (cmd) {
case OPEN_CHANNEL:
break;
case CLOSE_CHANNEL:
if (dsp->ch.peer)
dsp->ch.peer->ctrl(dsp->ch.peer, CLOSE_CHANNEL, NULL);
/* wait until workqueue has finished,
* must lock here, or we may hit send-process currently
* queueing. */
spin_lock_irqsave(&dsp_lock, flags);
dsp->b_active = 0;
spin_unlock_irqrestore(&dsp_lock, flags);
/* MUST not be locked, because it waits until queue is done. */
cancel_work_sync(&dsp->workq);
spin_lock_irqsave(&dsp_lock, flags);
if (timer_pending(&dsp->tone.tl))
del_timer(&dsp->tone.tl);
skb_queue_purge(&dsp->sendq);
if (dsp_debug & DEBUG_DSP_CTRL)
printk(KERN_DEBUG "%s: releasing member %s\n",
__func__, dsp->name);
dsp->b_active = 0;
dsp_cmx_conf(dsp, 0); /* dsp_cmx_hardware will also be called
here */
dsp_pipeline_destroy(&dsp->pipeline);
if (dsp_debug & DEBUG_DSP_CTRL)
printk(KERN_DEBUG "%s: remove & destroy object %s\n",
__func__, dsp->name);
list_del(&dsp->list);
spin_unlock_irqrestore(&dsp_lock, flags);
if (dsp_debug & DEBUG_DSP_CTRL)
printk(KERN_DEBUG "%s: dsp instance released\n",
__func__);
vfree(dsp);
module_put(THIS_MODULE);
break;
}
return err;
}
static void
dsp_send_bh(struct work_struct *work)
{
struct dsp *dsp = container_of(work, struct dsp, workq);
struct sk_buff *skb;
struct mISDNhead *hh;
if (dsp->hdlc && dsp->data_pending)
return; /* wait until data has been acknowledged */
/* send queued data */
while ((skb = skb_dequeue(&dsp->sendq))) {
/* in locked date, we must have still data in queue */
if (dsp->data_pending) {
if (dsp_debug & DEBUG_DSP_CORE)
printk(KERN_DEBUG "%s: fifo full %s, this is "
"no bug!\n", __func__, dsp->name);
/* flush transparent data, if not acked */
dev_kfree_skb(skb);
continue;
}
hh = mISDN_HEAD_P(skb);
if (hh->prim == DL_DATA_REQ) {
/* send packet up */
if (dsp->up) {
if (dsp->up->send(dsp->up, skb))
dev_kfree_skb(skb);
} else
dev_kfree_skb(skb);
} else {
/* send packet down */
if (dsp->ch.peer) {
dsp->data_pending = 1;
if (dsp->ch.recv(dsp->ch.peer, skb)) {
dev_kfree_skb(skb);
dsp->data_pending = 0;
}
} else
dev_kfree_skb(skb);
}
}
}
static int
dspcreate(struct channel_req *crq)
{
struct dsp *ndsp;
u_long flags;
if (crq->protocol != ISDN_P_B_L2DSP
&& crq->protocol != ISDN_P_B_L2DSPHDLC)
return -EPROTONOSUPPORT;
ndsp = vzalloc(sizeof(struct dsp));
if (!ndsp) {
printk(KERN_ERR "%s: vmalloc struct dsp failed\n", __func__);
return -ENOMEM;
}
if (dsp_debug & DEBUG_DSP_CTRL)
printk(KERN_DEBUG "%s: creating new dsp instance\n", __func__);
/* default enabled */
INIT_WORK(&ndsp->workq, (void *)dsp_send_bh);
skb_queue_head_init(&ndsp->sendq);
ndsp->ch.send = dsp_function;
ndsp->ch.ctrl = dsp_ctrl;
ndsp->up = crq->ch;
crq->ch = &ndsp->ch;
if (crq->protocol == ISDN_P_B_L2DSP) {
crq->protocol = ISDN_P_B_RAW;
ndsp->hdlc = 0;
} else {
crq->protocol = ISDN_P_B_HDLC;
ndsp->hdlc = 1;
}
if (!try_module_get(THIS_MODULE))
printk(KERN_WARNING "%s:cannot get module\n",
__func__);
sprintf(ndsp->name, "DSP_C%x(0x%p)",
ndsp->up->st->dev->id + 1, ndsp);
/* set frame size to start */
ndsp->features.hfc_id = -1; /* current PCM id */
ndsp->features.pcm_id = -1; /* current PCM id */
ndsp->pcm_slot_rx = -1; /* current CPM slot */
ndsp->pcm_slot_tx = -1;
ndsp->pcm_bank_rx = -1;
ndsp->pcm_bank_tx = -1;
ndsp->hfc_conf = -1; /* current conference number */
/* set tone timer */
ndsp->tone.tl.function = (void *)dsp_tone_timeout;
ndsp->tone.tl.data = (long) ndsp;
init_timer(&ndsp->tone.tl);
if (dtmfthreshold < 20 || dtmfthreshold > 500)
dtmfthreshold = 200;
ndsp->dtmf.treshold = dtmfthreshold * 10000;
/* init pipeline append to list */
spin_lock_irqsave(&dsp_lock, flags);
dsp_pipeline_init(&ndsp->pipeline);
list_add_tail(&ndsp->list, &dsp_ilist);
spin_unlock_irqrestore(&dsp_lock, flags);
return 0;
}
static struct Bprotocol DSP = {
.Bprotocols = (1 << (ISDN_P_B_L2DSP & ISDN_P_B_MASK))
| (1 << (ISDN_P_B_L2DSPHDLC & ISDN_P_B_MASK)),
.name = "dsp",
.create = dspcreate
};
static int __init dsp_init(void)
{
int err;
int tics;
printk(KERN_INFO "DSP module %s\n", mISDN_dsp_revision);
dsp_options = options;
dsp_debug = debug;
/* set packet size */
dsp_poll = poll;
if (dsp_poll) {
if (dsp_poll > MAX_POLL) {
printk(KERN_ERR "%s: Wrong poll value (%d), use %d "
"maximum.\n", __func__, poll, MAX_POLL);
err = -EINVAL;
return err;
}
if (dsp_poll < 8) {
printk(KERN_ERR "%s: Wrong poll value (%d), use 8 "
"minimum.\n", __func__, dsp_poll);
err = -EINVAL;
return err;
}
dsp_tics = poll * HZ / 8000;
if (dsp_tics * 8000 != poll * HZ) {
printk(KERN_INFO "mISDN_dsp: Cannot clock every %d "
"samples (0,125 ms). It is not a multiple of "
"%d HZ.\n", poll, HZ);
err = -EINVAL;
return err;
}
} else {
poll = 8;
while (poll <= MAX_POLL) {
tics = (poll * HZ) / 8000;
if (tics * 8000 == poll * HZ) {
dsp_tics = tics;
dsp_poll = poll;
if (poll >= 64)
break;
}
poll++;
}
}
if (dsp_poll == 0) {
printk(KERN_INFO "mISDN_dsp: There is no multiple of kernel "
"clock that equals exactly the duration of 8-256 "
"samples. (Choose kernel clock speed like 100, 250, "
"300, 1000)\n");
err = -EINVAL;
return err;
}
printk(KERN_INFO "mISDN_dsp: DSP clocks every %d samples. This equals "
"%d jiffies.\n", dsp_poll, dsp_tics);
spin_lock_init(&dsp_lock);
INIT_LIST_HEAD(&dsp_ilist);
INIT_LIST_HEAD(&conf_ilist);
/* init conversion tables */
dsp_audio_generate_law_tables();
dsp_silence = (dsp_options & DSP_OPT_ULAW) ? 0xff : 0x2a;
dsp_audio_law_to_s32 = (dsp_options & DSP_OPT_ULAW) ?
dsp_audio_ulaw_to_s32 : dsp_audio_alaw_to_s32;
dsp_audio_generate_s2law_table();
dsp_audio_generate_seven();
dsp_audio_generate_mix_table();
if (dsp_options & DSP_OPT_ULAW)
dsp_audio_generate_ulaw_samples();
dsp_audio_generate_volume_changes();
err = dsp_pipeline_module_init();
if (err) {
printk(KERN_ERR "mISDN_dsp: Can't initialize pipeline, "
"error(%d)\n", err);
return err;
}
err = mISDN_register_Bprotocol(&DSP);
if (err) {
printk(KERN_ERR "Can't register %s error(%d)\n", DSP.name, err);
return err;
}
/* set sample timer */
dsp_spl_tl.function = (void *)dsp_cmx_send;
dsp_spl_tl.data = 0;
init_timer(&dsp_spl_tl);
dsp_spl_tl.expires = jiffies + dsp_tics;
dsp_spl_jiffies = dsp_spl_tl.expires;
add_timer(&dsp_spl_tl);
return 0;
}
static void __exit dsp_cleanup(void)
{
mISDN_unregister_Bprotocol(&DSP);
if (timer_pending(&dsp_spl_tl))
del_timer(&dsp_spl_tl);
if (!list_empty(&dsp_ilist)) {
printk(KERN_ERR "mISDN_dsp: Audio DSP object inst list not "
"empty.\n");
}
if (!list_empty(&conf_ilist)) {
printk(KERN_ERR "mISDN_dsp: Conference list not empty. Not "
"all memory freed.\n");
}
dsp_pipeline_module_exit();
}
module_init(dsp_init);
module_exit(dsp_cleanup);
| gpl-2.0 |
crpalmer/android_kernel_motorola_msm8974 | drivers/hwmon/sch5627.c | 4809 | 19692 | /***************************************************************************
* Copyright (C) 2010-2012 Hans de Goede <hdegoede@redhat.com> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/platform_device.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include "sch56xx-common.h"
#define DRVNAME "sch5627"
#define DEVNAME DRVNAME /* We only support one model */
#define SCH5627_HWMON_ID 0xa5
#define SCH5627_COMPANY_ID 0x5c
#define SCH5627_PRIMARY_ID 0xa0
#define SCH5627_REG_BUILD_CODE 0x39
#define SCH5627_REG_BUILD_ID 0x3a
#define SCH5627_REG_HWMON_ID 0x3c
#define SCH5627_REG_HWMON_REV 0x3d
#define SCH5627_REG_COMPANY_ID 0x3e
#define SCH5627_REG_PRIMARY_ID 0x3f
#define SCH5627_REG_CTRL 0x40
#define SCH5627_NO_TEMPS 8
#define SCH5627_NO_FANS 4
#define SCH5627_NO_IN 5
static const u16 SCH5627_REG_TEMP_MSB[SCH5627_NO_TEMPS] = {
0x2B, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x180, 0x181 };
static const u16 SCH5627_REG_TEMP_LSN[SCH5627_NO_TEMPS] = {
0xE2, 0xE1, 0xE1, 0xE5, 0xE5, 0xE6, 0x182, 0x182 };
static const u16 SCH5627_REG_TEMP_HIGH_NIBBLE[SCH5627_NO_TEMPS] = {
0, 0, 1, 1, 0, 0, 0, 1 };
static const u16 SCH5627_REG_TEMP_HIGH[SCH5627_NO_TEMPS] = {
0x61, 0x57, 0x59, 0x5B, 0x5D, 0x5F, 0x184, 0x186 };
static const u16 SCH5627_REG_TEMP_ABS[SCH5627_NO_TEMPS] = {
0x9B, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x1A8, 0x1A9 };
static const u16 SCH5627_REG_FAN[SCH5627_NO_FANS] = {
0x2C, 0x2E, 0x30, 0x32 };
static const u16 SCH5627_REG_FAN_MIN[SCH5627_NO_FANS] = {
0x62, 0x64, 0x66, 0x68 };
static const u16 SCH5627_REG_IN_MSB[SCH5627_NO_IN] = {
0x22, 0x23, 0x24, 0x25, 0x189 };
static const u16 SCH5627_REG_IN_LSN[SCH5627_NO_IN] = {
0xE4, 0xE4, 0xE3, 0xE3, 0x18A };
static const u16 SCH5627_REG_IN_HIGH_NIBBLE[SCH5627_NO_IN] = {
1, 0, 1, 0, 1 };
static const u16 SCH5627_REG_IN_FACTOR[SCH5627_NO_IN] = {
10745, 3660, 9765, 10745, 3660 };
static const char * const SCH5627_IN_LABELS[SCH5627_NO_IN] = {
"VCC", "VTT", "VBAT", "VTR", "V_IN" };
struct sch5627_data {
unsigned short addr;
struct device *hwmon_dev;
struct sch56xx_watchdog_data *watchdog;
u8 control;
u8 temp_max[SCH5627_NO_TEMPS];
u8 temp_crit[SCH5627_NO_TEMPS];
u16 fan_min[SCH5627_NO_FANS];
struct mutex update_lock;
unsigned long last_battery; /* In jiffies */
char valid; /* !=0 if following fields are valid */
unsigned long last_updated; /* In jiffies */
u16 temp[SCH5627_NO_TEMPS];
u16 fan[SCH5627_NO_FANS];
u16 in[SCH5627_NO_IN];
};
static struct sch5627_data *sch5627_update_device(struct device *dev)
{
struct sch5627_data *data = dev_get_drvdata(dev);
struct sch5627_data *ret = data;
int i, val;
mutex_lock(&data->update_lock);
/* Trigger a Vbat voltage measurement every 5 minutes */
if (time_after(jiffies, data->last_battery + 300 * HZ)) {
sch56xx_write_virtual_reg(data->addr, SCH5627_REG_CTRL,
data->control | 0x10);
data->last_battery = jiffies;
}
/* Cache the values for 1 second */
if (time_after(jiffies, data->last_updated + HZ) || !data->valid) {
for (i = 0; i < SCH5627_NO_TEMPS; i++) {
val = sch56xx_read_virtual_reg12(data->addr,
SCH5627_REG_TEMP_MSB[i],
SCH5627_REG_TEMP_LSN[i],
SCH5627_REG_TEMP_HIGH_NIBBLE[i]);
if (unlikely(val < 0)) {
ret = ERR_PTR(val);
goto abort;
}
data->temp[i] = val;
}
for (i = 0; i < SCH5627_NO_FANS; i++) {
val = sch56xx_read_virtual_reg16(data->addr,
SCH5627_REG_FAN[i]);
if (unlikely(val < 0)) {
ret = ERR_PTR(val);
goto abort;
}
data->fan[i] = val;
}
for (i = 0; i < SCH5627_NO_IN; i++) {
val = sch56xx_read_virtual_reg12(data->addr,
SCH5627_REG_IN_MSB[i],
SCH5627_REG_IN_LSN[i],
SCH5627_REG_IN_HIGH_NIBBLE[i]);
if (unlikely(val < 0)) {
ret = ERR_PTR(val);
goto abort;
}
data->in[i] = val;
}
data->last_updated = jiffies;
data->valid = 1;
}
abort:
mutex_unlock(&data->update_lock);
return ret;
}
static int __devinit sch5627_read_limits(struct sch5627_data *data)
{
int i, val;
for (i = 0; i < SCH5627_NO_TEMPS; i++) {
/*
* Note what SMSC calls ABS, is what lm_sensors calls max
* (aka high), and HIGH is what lm_sensors calls crit.
*/
val = sch56xx_read_virtual_reg(data->addr,
SCH5627_REG_TEMP_ABS[i]);
if (val < 0)
return val;
data->temp_max[i] = val;
val = sch56xx_read_virtual_reg(data->addr,
SCH5627_REG_TEMP_HIGH[i]);
if (val < 0)
return val;
data->temp_crit[i] = val;
}
for (i = 0; i < SCH5627_NO_FANS; i++) {
val = sch56xx_read_virtual_reg16(data->addr,
SCH5627_REG_FAN_MIN[i]);
if (val < 0)
return val;
data->fan_min[i] = val;
}
return 0;
}
static int reg_to_temp(u16 reg)
{
return (reg * 625) / 10 - 64000;
}
static int reg_to_temp_limit(u8 reg)
{
return (reg - 64) * 1000;
}
static int reg_to_rpm(u16 reg)
{
if (reg == 0)
return -EIO;
if (reg == 0xffff)
return 0;
return 5400540 / reg;
}
static ssize_t show_name(struct device *dev, struct device_attribute *devattr,
char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", DEVNAME);
}
static ssize_t show_temp(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct sch5627_data *data = sch5627_update_device(dev);
int val;
if (IS_ERR(data))
return PTR_ERR(data);
val = reg_to_temp(data->temp[attr->index]);
return snprintf(buf, PAGE_SIZE, "%d\n", val);
}
static ssize_t show_temp_fault(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct sch5627_data *data = sch5627_update_device(dev);
if (IS_ERR(data))
return PTR_ERR(data);
return snprintf(buf, PAGE_SIZE, "%d\n", data->temp[attr->index] == 0);
}
static ssize_t show_temp_max(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct sch5627_data *data = dev_get_drvdata(dev);
int val;
val = reg_to_temp_limit(data->temp_max[attr->index]);
return snprintf(buf, PAGE_SIZE, "%d\n", val);
}
static ssize_t show_temp_crit(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct sch5627_data *data = dev_get_drvdata(dev);
int val;
val = reg_to_temp_limit(data->temp_crit[attr->index]);
return snprintf(buf, PAGE_SIZE, "%d\n", val);
}
static ssize_t show_fan(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct sch5627_data *data = sch5627_update_device(dev);
int val;
if (IS_ERR(data))
return PTR_ERR(data);
val = reg_to_rpm(data->fan[attr->index]);
if (val < 0)
return val;
return snprintf(buf, PAGE_SIZE, "%d\n", val);
}
static ssize_t show_fan_fault(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct sch5627_data *data = sch5627_update_device(dev);
if (IS_ERR(data))
return PTR_ERR(data);
return snprintf(buf, PAGE_SIZE, "%d\n",
data->fan[attr->index] == 0xffff);
}
static ssize_t show_fan_min(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct sch5627_data *data = dev_get_drvdata(dev);
int val = reg_to_rpm(data->fan_min[attr->index]);
if (val < 0)
return val;
return snprintf(buf, PAGE_SIZE, "%d\n", val);
}
static ssize_t show_in(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct sch5627_data *data = sch5627_update_device(dev);
int val;
if (IS_ERR(data))
return PTR_ERR(data);
val = DIV_ROUND_CLOSEST(
data->in[attr->index] * SCH5627_REG_IN_FACTOR[attr->index],
10000);
return snprintf(buf, PAGE_SIZE, "%d\n", val);
}
static ssize_t show_in_label(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
return snprintf(buf, PAGE_SIZE, "%s\n",
SCH5627_IN_LABELS[attr->index]);
}
static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_temp, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_input, S_IRUGO, show_temp, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_input, S_IRUGO, show_temp, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_input, S_IRUGO, show_temp, NULL, 3);
static SENSOR_DEVICE_ATTR(temp5_input, S_IRUGO, show_temp, NULL, 4);
static SENSOR_DEVICE_ATTR(temp6_input, S_IRUGO, show_temp, NULL, 5);
static SENSOR_DEVICE_ATTR(temp7_input, S_IRUGO, show_temp, NULL, 6);
static SENSOR_DEVICE_ATTR(temp8_input, S_IRUGO, show_temp, NULL, 7);
static SENSOR_DEVICE_ATTR(temp1_fault, S_IRUGO, show_temp_fault, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_fault, S_IRUGO, show_temp_fault, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_fault, S_IRUGO, show_temp_fault, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_fault, S_IRUGO, show_temp_fault, NULL, 3);
static SENSOR_DEVICE_ATTR(temp5_fault, S_IRUGO, show_temp_fault, NULL, 4);
static SENSOR_DEVICE_ATTR(temp6_fault, S_IRUGO, show_temp_fault, NULL, 5);
static SENSOR_DEVICE_ATTR(temp7_fault, S_IRUGO, show_temp_fault, NULL, 6);
static SENSOR_DEVICE_ATTR(temp8_fault, S_IRUGO, show_temp_fault, NULL, 7);
static SENSOR_DEVICE_ATTR(temp1_max, S_IRUGO, show_temp_max, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_max, S_IRUGO, show_temp_max, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_max, S_IRUGO, show_temp_max, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_max, S_IRUGO, show_temp_max, NULL, 3);
static SENSOR_DEVICE_ATTR(temp5_max, S_IRUGO, show_temp_max, NULL, 4);
static SENSOR_DEVICE_ATTR(temp6_max, S_IRUGO, show_temp_max, NULL, 5);
static SENSOR_DEVICE_ATTR(temp7_max, S_IRUGO, show_temp_max, NULL, 6);
static SENSOR_DEVICE_ATTR(temp8_max, S_IRUGO, show_temp_max, NULL, 7);
static SENSOR_DEVICE_ATTR(temp1_crit, S_IRUGO, show_temp_crit, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_crit, S_IRUGO, show_temp_crit, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_crit, S_IRUGO, show_temp_crit, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_crit, S_IRUGO, show_temp_crit, NULL, 3);
static SENSOR_DEVICE_ATTR(temp5_crit, S_IRUGO, show_temp_crit, NULL, 4);
static SENSOR_DEVICE_ATTR(temp6_crit, S_IRUGO, show_temp_crit, NULL, 5);
static SENSOR_DEVICE_ATTR(temp7_crit, S_IRUGO, show_temp_crit, NULL, 6);
static SENSOR_DEVICE_ATTR(temp8_crit, S_IRUGO, show_temp_crit, NULL, 7);
static SENSOR_DEVICE_ATTR(fan1_input, S_IRUGO, show_fan, NULL, 0);
static SENSOR_DEVICE_ATTR(fan2_input, S_IRUGO, show_fan, NULL, 1);
static SENSOR_DEVICE_ATTR(fan3_input, S_IRUGO, show_fan, NULL, 2);
static SENSOR_DEVICE_ATTR(fan4_input, S_IRUGO, show_fan, NULL, 3);
static SENSOR_DEVICE_ATTR(fan1_fault, S_IRUGO, show_fan_fault, NULL, 0);
static SENSOR_DEVICE_ATTR(fan2_fault, S_IRUGO, show_fan_fault, NULL, 1);
static SENSOR_DEVICE_ATTR(fan3_fault, S_IRUGO, show_fan_fault, NULL, 2);
static SENSOR_DEVICE_ATTR(fan4_fault, S_IRUGO, show_fan_fault, NULL, 3);
static SENSOR_DEVICE_ATTR(fan1_min, S_IRUGO, show_fan_min, NULL, 0);
static SENSOR_DEVICE_ATTR(fan2_min, S_IRUGO, show_fan_min, NULL, 1);
static SENSOR_DEVICE_ATTR(fan3_min, S_IRUGO, show_fan_min, NULL, 2);
static SENSOR_DEVICE_ATTR(fan4_min, S_IRUGO, show_fan_min, NULL, 3);
static SENSOR_DEVICE_ATTR(in0_input, S_IRUGO, show_in, NULL, 0);
static SENSOR_DEVICE_ATTR(in1_input, S_IRUGO, show_in, NULL, 1);
static SENSOR_DEVICE_ATTR(in2_input, S_IRUGO, show_in, NULL, 2);
static SENSOR_DEVICE_ATTR(in3_input, S_IRUGO, show_in, NULL, 3);
static SENSOR_DEVICE_ATTR(in4_input, S_IRUGO, show_in, NULL, 4);
static SENSOR_DEVICE_ATTR(in0_label, S_IRUGO, show_in_label, NULL, 0);
static SENSOR_DEVICE_ATTR(in1_label, S_IRUGO, show_in_label, NULL, 1);
static SENSOR_DEVICE_ATTR(in2_label, S_IRUGO, show_in_label, NULL, 2);
static SENSOR_DEVICE_ATTR(in3_label, S_IRUGO, show_in_label, NULL, 3);
static struct attribute *sch5627_attributes[] = {
&dev_attr_name.attr,
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp2_input.dev_attr.attr,
&sensor_dev_attr_temp3_input.dev_attr.attr,
&sensor_dev_attr_temp4_input.dev_attr.attr,
&sensor_dev_attr_temp5_input.dev_attr.attr,
&sensor_dev_attr_temp6_input.dev_attr.attr,
&sensor_dev_attr_temp7_input.dev_attr.attr,
&sensor_dev_attr_temp8_input.dev_attr.attr,
&sensor_dev_attr_temp1_fault.dev_attr.attr,
&sensor_dev_attr_temp2_fault.dev_attr.attr,
&sensor_dev_attr_temp3_fault.dev_attr.attr,
&sensor_dev_attr_temp4_fault.dev_attr.attr,
&sensor_dev_attr_temp5_fault.dev_attr.attr,
&sensor_dev_attr_temp6_fault.dev_attr.attr,
&sensor_dev_attr_temp7_fault.dev_attr.attr,
&sensor_dev_attr_temp8_fault.dev_attr.attr,
&sensor_dev_attr_temp1_max.dev_attr.attr,
&sensor_dev_attr_temp2_max.dev_attr.attr,
&sensor_dev_attr_temp3_max.dev_attr.attr,
&sensor_dev_attr_temp4_max.dev_attr.attr,
&sensor_dev_attr_temp5_max.dev_attr.attr,
&sensor_dev_attr_temp6_max.dev_attr.attr,
&sensor_dev_attr_temp7_max.dev_attr.attr,
&sensor_dev_attr_temp8_max.dev_attr.attr,
&sensor_dev_attr_temp1_crit.dev_attr.attr,
&sensor_dev_attr_temp2_crit.dev_attr.attr,
&sensor_dev_attr_temp3_crit.dev_attr.attr,
&sensor_dev_attr_temp4_crit.dev_attr.attr,
&sensor_dev_attr_temp5_crit.dev_attr.attr,
&sensor_dev_attr_temp6_crit.dev_attr.attr,
&sensor_dev_attr_temp7_crit.dev_attr.attr,
&sensor_dev_attr_temp8_crit.dev_attr.attr,
&sensor_dev_attr_fan1_input.dev_attr.attr,
&sensor_dev_attr_fan2_input.dev_attr.attr,
&sensor_dev_attr_fan3_input.dev_attr.attr,
&sensor_dev_attr_fan4_input.dev_attr.attr,
&sensor_dev_attr_fan1_fault.dev_attr.attr,
&sensor_dev_attr_fan2_fault.dev_attr.attr,
&sensor_dev_attr_fan3_fault.dev_attr.attr,
&sensor_dev_attr_fan4_fault.dev_attr.attr,
&sensor_dev_attr_fan1_min.dev_attr.attr,
&sensor_dev_attr_fan2_min.dev_attr.attr,
&sensor_dev_attr_fan3_min.dev_attr.attr,
&sensor_dev_attr_fan4_min.dev_attr.attr,
&sensor_dev_attr_in0_input.dev_attr.attr,
&sensor_dev_attr_in1_input.dev_attr.attr,
&sensor_dev_attr_in2_input.dev_attr.attr,
&sensor_dev_attr_in3_input.dev_attr.attr,
&sensor_dev_attr_in4_input.dev_attr.attr,
&sensor_dev_attr_in0_label.dev_attr.attr,
&sensor_dev_attr_in1_label.dev_attr.attr,
&sensor_dev_attr_in2_label.dev_attr.attr,
&sensor_dev_attr_in3_label.dev_attr.attr,
/* No in4_label as in4 is a generic input pin */
NULL
};
static const struct attribute_group sch5627_group = {
.attrs = sch5627_attributes,
};
static int sch5627_remove(struct platform_device *pdev)
{
struct sch5627_data *data = platform_get_drvdata(pdev);
if (data->watchdog)
sch56xx_watchdog_unregister(data->watchdog);
if (data->hwmon_dev)
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&pdev->dev.kobj, &sch5627_group);
platform_set_drvdata(pdev, NULL);
kfree(data);
return 0;
}
static int __devinit sch5627_probe(struct platform_device *pdev)
{
struct sch5627_data *data;
int err, build_code, build_id, hwmon_rev, val;
data = kzalloc(sizeof(struct sch5627_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
data->addr = platform_get_resource(pdev, IORESOURCE_IO, 0)->start;
mutex_init(&data->update_lock);
platform_set_drvdata(pdev, data);
val = sch56xx_read_virtual_reg(data->addr, SCH5627_REG_HWMON_ID);
if (val < 0) {
err = val;
goto error;
}
if (val != SCH5627_HWMON_ID) {
pr_err("invalid %s id: 0x%02X (expected 0x%02X)\n", "hwmon",
val, SCH5627_HWMON_ID);
err = -ENODEV;
goto error;
}
val = sch56xx_read_virtual_reg(data->addr, SCH5627_REG_COMPANY_ID);
if (val < 0) {
err = val;
goto error;
}
if (val != SCH5627_COMPANY_ID) {
pr_err("invalid %s id: 0x%02X (expected 0x%02X)\n", "company",
val, SCH5627_COMPANY_ID);
err = -ENODEV;
goto error;
}
val = sch56xx_read_virtual_reg(data->addr, SCH5627_REG_PRIMARY_ID);
if (val < 0) {
err = val;
goto error;
}
if (val != SCH5627_PRIMARY_ID) {
pr_err("invalid %s id: 0x%02X (expected 0x%02X)\n", "primary",
val, SCH5627_PRIMARY_ID);
err = -ENODEV;
goto error;
}
build_code = sch56xx_read_virtual_reg(data->addr,
SCH5627_REG_BUILD_CODE);
if (build_code < 0) {
err = build_code;
goto error;
}
build_id = sch56xx_read_virtual_reg16(data->addr,
SCH5627_REG_BUILD_ID);
if (build_id < 0) {
err = build_id;
goto error;
}
hwmon_rev = sch56xx_read_virtual_reg(data->addr,
SCH5627_REG_HWMON_REV);
if (hwmon_rev < 0) {
err = hwmon_rev;
goto error;
}
val = sch56xx_read_virtual_reg(data->addr, SCH5627_REG_CTRL);
if (val < 0) {
err = val;
goto error;
}
data->control = val;
if (!(data->control & 0x01)) {
pr_err("hardware monitoring not enabled\n");
err = -ENODEV;
goto error;
}
/* Trigger a Vbat voltage measurement, so that we get a valid reading
the first time we read Vbat */
sch56xx_write_virtual_reg(data->addr, SCH5627_REG_CTRL,
data->control | 0x10);
data->last_battery = jiffies;
/*
* Read limits, we do this only once as reading a register on
* the sch5627 is quite expensive (and they don't change).
*/
err = sch5627_read_limits(data);
if (err)
goto error;
pr_info("found %s chip at %#hx\n", DEVNAME, data->addr);
pr_info("firmware build: code 0x%02X, id 0x%04X, hwmon: rev 0x%02X\n",
build_code, build_id, hwmon_rev);
/* Register sysfs interface files */
err = sysfs_create_group(&pdev->dev.kobj, &sch5627_group);
if (err)
goto error;
data->hwmon_dev = hwmon_device_register(&pdev->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
data->hwmon_dev = NULL;
goto error;
}
/* Note failing to register the watchdog is not a fatal error */
data->watchdog = sch56xx_watchdog_register(data->addr,
(build_code << 24) | (build_id << 8) | hwmon_rev,
&data->update_lock, 1);
return 0;
error:
sch5627_remove(pdev);
return err;
}
static struct platform_driver sch5627_driver = {
.driver = {
.owner = THIS_MODULE,
.name = DRVNAME,
},
.probe = sch5627_probe,
.remove = sch5627_remove,
};
module_platform_driver(sch5627_driver);
MODULE_DESCRIPTION("SMSC SCH5627 Hardware Monitoring Driver");
MODULE_AUTHOR("Hans de Goede <hdegoede@redhat.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
chrisc93/android_kernel_samsung_jf | arch/x86/mm/memtest.c | 5065 | 3168 | #include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/init.h>
#include <linux/pfn.h>
#include <linux/memblock.h>
static u64 patterns[] __initdata = {
0,
0xffffffffffffffffULL,
0x5555555555555555ULL,
0xaaaaaaaaaaaaaaaaULL,
0x1111111111111111ULL,
0x2222222222222222ULL,
0x4444444444444444ULL,
0x8888888888888888ULL,
0x3333333333333333ULL,
0x6666666666666666ULL,
0x9999999999999999ULL,
0xccccccccccccccccULL,
0x7777777777777777ULL,
0xbbbbbbbbbbbbbbbbULL,
0xddddddddddddddddULL,
0xeeeeeeeeeeeeeeeeULL,
0x7a6c7258554e494cULL, /* yeah ;-) */
};
static void __init reserve_bad_mem(u64 pattern, u64 start_bad, u64 end_bad)
{
printk(KERN_INFO " %016llx bad mem addr %010llx - %010llx reserved\n",
(unsigned long long) pattern,
(unsigned long long) start_bad,
(unsigned long long) end_bad);
memblock_reserve(start_bad, end_bad - start_bad);
}
static void __init memtest(u64 pattern, u64 start_phys, u64 size)
{
u64 *p, *start, *end;
u64 start_bad, last_bad;
u64 start_phys_aligned;
const size_t incr = sizeof(pattern);
start_phys_aligned = ALIGN(start_phys, incr);
start = __va(start_phys_aligned);
end = start + (size - (start_phys_aligned - start_phys)) / incr;
start_bad = 0;
last_bad = 0;
for (p = start; p < end; p++)
*p = pattern;
for (p = start; p < end; p++, start_phys_aligned += incr) {
if (*p == pattern)
continue;
if (start_phys_aligned == last_bad + incr) {
last_bad += incr;
continue;
}
if (start_bad)
reserve_bad_mem(pattern, start_bad, last_bad + incr);
start_bad = last_bad = start_phys_aligned;
}
if (start_bad)
reserve_bad_mem(pattern, start_bad, last_bad + incr);
}
static void __init do_one_pass(u64 pattern, u64 start, u64 end)
{
u64 i;
phys_addr_t this_start, this_end;
for_each_free_mem_range(i, MAX_NUMNODES, &this_start, &this_end, NULL) {
this_start = clamp_t(phys_addr_t, this_start, start, end);
this_end = clamp_t(phys_addr_t, this_end, start, end);
if (this_start < this_end) {
printk(KERN_INFO " %010llx - %010llx pattern %016llx\n",
(unsigned long long)this_start,
(unsigned long long)this_end,
(unsigned long long)cpu_to_be64(pattern));
memtest(pattern, this_start, this_end - this_start);
}
}
}
/* default is disabled */
static int memtest_pattern __initdata;
static int __init parse_memtest(char *arg)
{
if (arg)
memtest_pattern = simple_strtoul(arg, NULL, 0);
else
memtest_pattern = ARRAY_SIZE(patterns);
return 0;
}
early_param("memtest", parse_memtest);
void __init early_memtest(unsigned long start, unsigned long end)
{
unsigned int i;
unsigned int idx = 0;
if (!memtest_pattern)
return;
printk(KERN_INFO "early_memtest: # of tests: %d\n", memtest_pattern);
for (i = 0; i < memtest_pattern; i++) {
idx = i % ARRAY_SIZE(patterns);
do_one_pass(patterns[idx], start, end);
}
if (idx > 0) {
printk(KERN_INFO "early_memtest: wipe out "
"test pattern from memory\n");
/* additional test with pattern 0 will do this */
do_one_pass(0, start, end);
}
}
| gpl-2.0 |
FreonRoms/freon_kernel_samsung_d2 | arch/arm/mach-cns3xxx/devices.c | 5065 | 2729 | /*
* CNS3xxx common devices
*
* Copyright 2008 Cavium Networks
* Scott Shu
* Copyright 2010 MontaVista Software, LLC.
* Anton Vorontsov <avorontsov@mvista.com>
*
* This file 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/init.h>
#include <linux/compiler.h>
#include <linux/dma-mapping.h>
#include <linux/platform_device.h>
#include <mach/cns3xxx.h>
#include <mach/irqs.h>
#include <mach/pm.h>
#include "core.h"
#include "devices.h"
/*
* AHCI
*/
static struct resource cns3xxx_ahci_resource[] = {
[0] = {
.start = CNS3XXX_SATA2_BASE,
.end = CNS3XXX_SATA2_BASE + CNS3XXX_SATA2_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_CNS3XXX_SATA,
.end = IRQ_CNS3XXX_SATA,
.flags = IORESOURCE_IRQ,
},
};
static u64 cns3xxx_ahci_dmamask = DMA_BIT_MASK(32);
static struct platform_device cns3xxx_ahci_pdev = {
.name = "ahci",
.id = 0,
.resource = cns3xxx_ahci_resource,
.num_resources = ARRAY_SIZE(cns3xxx_ahci_resource),
.dev = {
.dma_mask = &cns3xxx_ahci_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
void __init cns3xxx_ahci_init(void)
{
u32 tmp;
tmp = __raw_readl(MISC_SATA_POWER_MODE);
tmp |= 0x1 << 16; /* Disable SATA PHY 0 from SLUMBER Mode */
tmp |= 0x1 << 17; /* Disable SATA PHY 1 from SLUMBER Mode */
__raw_writel(tmp, MISC_SATA_POWER_MODE);
/* Enable SATA PHY */
cns3xxx_pwr_power_up(0x1 << PM_PLL_HM_PD_CTRL_REG_OFFSET_SATA_PHY0);
cns3xxx_pwr_power_up(0x1 << PM_PLL_HM_PD_CTRL_REG_OFFSET_SATA_PHY1);
/* Enable SATA Clock */
cns3xxx_pwr_clk_en(0x1 << PM_CLK_GATE_REG_OFFSET_SATA);
/* De-Asscer SATA Reset */
cns3xxx_pwr_soft_rst(CNS3XXX_PWR_SOFTWARE_RST(SATA));
platform_device_register(&cns3xxx_ahci_pdev);
}
/*
* SDHCI
*/
static struct resource cns3xxx_sdhci_resources[] = {
[0] = {
.start = CNS3XXX_SDIO_BASE,
.end = CNS3XXX_SDIO_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_CNS3XXX_SDIO,
.end = IRQ_CNS3XXX_SDIO,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device cns3xxx_sdhci_pdev = {
.name = "sdhci-cns3xxx",
.id = 0,
.num_resources = ARRAY_SIZE(cns3xxx_sdhci_resources),
.resource = cns3xxx_sdhci_resources,
};
void __init cns3xxx_sdhci_init(void)
{
u32 __iomem *gpioa = IOMEM(CNS3XXX_MISC_BASE_VIRT + 0x0014);
u32 gpioa_pins = __raw_readl(gpioa);
/* MMC/SD pins share with GPIOA */
gpioa_pins |= 0x1fff0004;
__raw_writel(gpioa_pins, gpioa);
cns3xxx_pwr_clk_en(CNS3XXX_PWR_CLK_EN(SDIO));
cns3xxx_pwr_soft_rst(CNS3XXX_PWR_SOFTWARE_RST(SDIO));
platform_device_register(&cns3xxx_sdhci_pdev);
}
| gpl-2.0 |
thanhphat11/Android_kernel_xiaomi_ALL | arch/blackfin/kernel/kgdb_test.c | 8905 | 2461 | /*
* arch/blackfin/kernel/kgdb_test.c - Blackfin kgdb tests
*
* Copyright 2005-2008 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/proc_fs.h>
#include <asm/current.h>
#include <asm/uaccess.h>
#include <asm/blackfin.h>
/* Symbols are here for kgdb test to poke directly */
static char cmdline[256];
static size_t len;
#ifndef CONFIG_SMP
static int num1 __attribute__((l1_data));
void kgdb_l1_test(void) __attribute__((l1_text));
void kgdb_l1_test(void)
{
pr_alert("L1(before change) : data variable addr = 0x%p, data value is %d\n", &num1, num1);
pr_alert("L1 : code function addr = 0x%p\n", kgdb_l1_test);
num1 = num1 + 10;
pr_alert("L1(after change) : data variable addr = 0x%p, data value is %d\n", &num1, num1);
}
#endif
#if L2_LENGTH
static int num2 __attribute__((l2));
void kgdb_l2_test(void) __attribute__((l2));
void kgdb_l2_test(void)
{
pr_alert("L2(before change) : data variable addr = 0x%p, data value is %d\n", &num2, num2);
pr_alert("L2 : code function addr = 0x%p\n", kgdb_l2_test);
num2 = num2 + 20;
pr_alert("L2(after change) : data variable addr = 0x%p, data value is %d\n", &num2, num2);
}
#endif
noinline int kgdb_test(char *name, int len, int count, int z)
{
pr_alert("kgdb name(%d): %s, %d, %d\n", len, name, count, z);
count = z;
return count;
}
static ssize_t
kgdb_test_proc_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
kgdb_test("hello world!", 12, 0x55, 0x10);
#ifndef CONFIG_SMP
kgdb_l1_test();
#endif
#if L2_LENGTH
kgdb_l2_test();
#endif
return 0;
}
static ssize_t
kgdb_test_proc_write(struct file *file, const char __user *buffer,
size_t count, loff_t *pos)
{
len = min_t(size_t, 255, count);
memcpy(cmdline, buffer, count);
cmdline[len] = 0;
return len;
}
static const struct file_operations kgdb_test_proc_fops = {
.owner = THIS_MODULE,
.read = kgdb_test_proc_read,
.write = kgdb_test_proc_write,
.llseek = noop_llseek,
};
static int __init kgdbtest_init(void)
{
struct proc_dir_entry *entry;
#if L2_LENGTH
num2 = 0;
#endif
entry = proc_create("kgdbtest", 0, NULL, &kgdb_test_proc_fops);
if (entry == NULL)
return -ENOMEM;
return 0;
}
static void __exit kgdbtest_exit(void)
{
remove_proc_entry("kgdbtest", NULL);
}
module_init(kgdbtest_init);
module_exit(kgdbtest_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
CyanogenMod/android_kernel_xiaomi_cancro | drivers/usb/dwc3/core.c | 202 | 20962 | /**
* core.c - DesignWare USB3 DRD Controller Core file
*
* Copyright (C) 2010-2011 Texas Instruments Incorporated - http://www.ti.com
*
* Authors: Felipe Balbi <balbi@ti.com>,
* Sebastian Andrzej Siewior <bigeasy@linutronix.de>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The names of the above-listed copyright holders 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") version 2, as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/io.h>
#include <linux/list.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/of.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include "core.h"
#include "gadget.h"
#include "io.h"
#include "debug.h"
static char *maximum_speed = "super";
module_param(maximum_speed, charp, 0);
MODULE_PARM_DESC(maximum_speed, "Maximum supported speed.");
/* -------------------------------------------------------------------------- */
#define DWC3_DEVS_POSSIBLE 32
static DECLARE_BITMAP(dwc3_devs, DWC3_DEVS_POSSIBLE);
int dwc3_get_device_id(void)
{
int id;
again:
id = find_first_zero_bit(dwc3_devs, DWC3_DEVS_POSSIBLE);
if (id < DWC3_DEVS_POSSIBLE) {
int old;
old = test_and_set_bit(id, dwc3_devs);
if (old)
goto again;
} else {
pr_err("dwc3: no space for new device\n");
id = -ENOMEM;
}
return id;
}
EXPORT_SYMBOL_GPL(dwc3_get_device_id);
void dwc3_put_device_id(int id)
{
int ret;
if (id < 0)
return;
ret = test_bit(id, dwc3_devs);
WARN(!ret, "dwc3: ID %d not in use\n", id);
smp_mb__before_clear_bit();
clear_bit(id, dwc3_devs);
}
EXPORT_SYMBOL_GPL(dwc3_put_device_id);
void dwc3_set_mode(struct dwc3 *dwc, u32 mode)
{
u32 reg;
reg = dwc3_readl(dwc->regs, DWC3_GCTL);
reg &= ~(DWC3_GCTL_PRTCAPDIR(DWC3_GCTL_PRTCAP_OTG));
reg |= DWC3_GCTL_PRTCAPDIR(mode);
/*
* Set this bit so that device attempts three more times at SS, even
* if it failed previously to operate in SS mode.
*/
reg |= DWC3_GCTL_U2RSTECN;
reg &= ~(DWC3_GCTL_SOFITPSYNC);
reg &= ~(DWC3_GCTL_PWRDNSCALEMASK);
reg |= DWC3_GCTL_PWRDNSCALE(2);
reg |= DWC3_GCTL_U2EXIT_LFPS;
dwc3_writel(dwc->regs, DWC3_GCTL, reg);
if (mode == DWC3_GCTL_PRTCAP_OTG || mode == DWC3_GCTL_PRTCAP_HOST) {
/*
* Allow ITP generated off of ref clk based counter instead
* of UTMI/ULPI clk based counter, when superspeed only is
* active so that UTMI/ULPI PHY can be suspened.
*
* Starting with revision 2.50A, GFLADJ_REFCLK_LPM_SEL is used
* instead.
*/
if (dwc->revision < DWC3_REVISION_250A) {
reg = dwc3_readl(dwc->regs, DWC3_GCTL);
reg |= DWC3_GCTL_SOFITPSYNC;
dwc3_writel(dwc->regs, DWC3_GCTL, reg);
} else {
reg = dwc3_readl(dwc->regs, DWC3_GFLADJ);
reg |= DWC3_GFLADJ_REFCLK_LPM_SEL;
dwc3_writel(dwc->regs, DWC3_GFLADJ, reg);
}
}
reg = dwc3_readl(dwc->regs, DWC3_GUSB3PIPECTL(0));
reg |= DWC3_GUSB3PIPECTL_SUSPHY;
dwc3_writel(dwc->regs, DWC3_GUSB3PIPECTL(0), reg);
reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
reg |= DWC3_GUSB2PHYCFG_SUSPHY;
dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
}
/**
* dwc3_core_soft_reset - Issues core soft reset and PHY reset
* @dwc: pointer to our context structure
*/
static void dwc3_core_soft_reset(struct dwc3 *dwc)
{
u32 reg;
/* Before Resetting PHY, put Core in Reset */
reg = dwc3_readl(dwc->regs, DWC3_GCTL);
reg |= DWC3_GCTL_CORESOFTRESET;
dwc3_writel(dwc->regs, DWC3_GCTL, reg);
dwc3_notify_event(dwc, DWC3_CONTROLLER_RESET_EVENT);
/* Assert USB3 PHY reset */
reg = dwc3_readl(dwc->regs, DWC3_GUSB3PIPECTL(0));
reg |= DWC3_GUSB3PIPECTL_PHYSOFTRST;
dwc3_writel(dwc->regs, DWC3_GUSB3PIPECTL(0), reg);
/* Assert USB2 PHY reset */
reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
reg |= DWC3_GUSB2PHYCFG_PHYSOFTRST;
dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
mdelay(100);
/* Clear USB3 PHY reset */
reg = dwc3_readl(dwc->regs, DWC3_GUSB3PIPECTL(0));
reg &= ~DWC3_GUSB3PIPECTL_PHYSOFTRST;
dwc3_writel(dwc->regs, DWC3_GUSB3PIPECTL(0), reg);
/* Clear USB2 PHY reset */
reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
reg &= ~DWC3_GUSB2PHYCFG_PHYSOFTRST;
dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
mdelay(100);
/* After PHYs are stable we can take Core out of reset state */
reg = dwc3_readl(dwc->regs, DWC3_GCTL);
reg &= ~DWC3_GCTL_CORESOFTRESET;
dwc3_writel(dwc->regs, DWC3_GCTL, reg);
dwc3_notify_event(dwc, DWC3_CONTROLLER_POST_RESET_EVENT);
}
/**
* dwc3_free_one_event_buffer - Frees one event buffer
* @dwc: Pointer to our controller context structure
* @evt: Pointer to event buffer to be freed
*/
static void dwc3_free_one_event_buffer(struct dwc3 *dwc,
struct dwc3_event_buffer *evt)
{
dma_free_coherent(dwc->dev, evt->length, evt->buf, evt->dma);
kfree(evt);
}
/**
* dwc3_alloc_one_event_buffer - Allocates one event buffer structure
* @dwc: Pointer to our controller context structure
* @length: size of the event buffer
*
* Returns a pointer to the allocated event buffer structure on success
* otherwise ERR_PTR(errno).
*/
static struct dwc3_event_buffer *__devinit
dwc3_alloc_one_event_buffer(struct dwc3 *dwc, unsigned length)
{
struct dwc3_event_buffer *evt;
evt = kzalloc(sizeof(*evt), GFP_KERNEL);
if (!evt)
return ERR_PTR(-ENOMEM);
evt->dwc = dwc;
evt->length = length;
evt->buf = dma_alloc_coherent(dwc->dev, length,
&evt->dma, GFP_KERNEL);
if (!evt->buf) {
kfree(evt);
return ERR_PTR(-ENOMEM);
}
return evt;
}
/**
* dwc3_free_event_buffers - frees all allocated event buffers
* @dwc: Pointer to our controller context structure
*/
static void dwc3_free_event_buffers(struct dwc3 *dwc)
{
struct dwc3_event_buffer *evt;
int i;
for (i = 0; i < dwc->num_event_buffers; i++) {
evt = dwc->ev_buffs[i];
if (evt)
dwc3_free_one_event_buffer(dwc, evt);
}
kfree(dwc->ev_buffs);
}
/**
* dwc3_alloc_event_buffers - Allocates @num event buffers of size @length
* @dwc: pointer to our controller context structure
* @length: size of event buffer
*
* Returns 0 on success otherwise negative errno. In the error case, dwc
* may contain some buffers allocated but not all which were requested.
*/
static int __devinit dwc3_alloc_event_buffers(struct dwc3 *dwc, unsigned length)
{
int num;
int i;
num = DWC3_NUM_INT(dwc->hwparams.hwparams1);
dwc->num_event_buffers = num;
dwc->ev_buffs = kzalloc(sizeof(*dwc->ev_buffs) * num, GFP_KERNEL);
if (!dwc->ev_buffs) {
dev_err(dwc->dev, "can't allocate event buffers array\n");
return -ENOMEM;
}
for (i = 0; i < num; i++) {
struct dwc3_event_buffer *evt;
/*
* As SW workaround, allocate 8 bytes more than size of event
* buffer given to USB Controller to avoid possible memory
* corruption caused by event buffer overflow when Hw writes
* Vendor Device test event which could be of 12 bytes.
*/
evt = dwc3_alloc_one_event_buffer(dwc, (length + 8));
if (IS_ERR(evt)) {
dev_err(dwc->dev, "can't allocate event buffer\n");
return PTR_ERR(evt);
}
dwc->ev_buffs[i] = evt;
}
return 0;
}
/**
* dwc3_event_buffers_setup - setup our allocated event buffers
* @dwc: pointer to our controller context structure
*
* Returns 0 on success otherwise negative errno.
*/
int dwc3_event_buffers_setup(struct dwc3 *dwc)
{
struct dwc3_event_buffer *evt;
int n;
for (n = 0; n < dwc->num_event_buffers; n++) {
evt = dwc->ev_buffs[n];
dev_dbg(dwc->dev, "Event buf %p dma %08llx length %d\n",
evt->buf, (unsigned long long) evt->dma,
evt->length);
evt->lpos = 0;
dwc3_writel(dwc->regs, DWC3_GEVNTADRLO(n),
lower_32_bits(evt->dma));
dwc3_writel(dwc->regs, DWC3_GEVNTADRHI(n),
upper_32_bits(evt->dma));
dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(n),
(evt->length - 8) & 0xffff);
dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(n), 0);
}
return 0;
}
static void dwc3_event_buffers_cleanup(struct dwc3 *dwc)
{
struct dwc3_event_buffer *evt;
int n;
for (n = 0; n < dwc->num_event_buffers; n++) {
evt = dwc->ev_buffs[n];
evt->lpos = 0;
dwc3_writel(dwc->regs, DWC3_GEVNTADRLO(n), 0);
dwc3_writel(dwc->regs, DWC3_GEVNTADRHI(n), 0);
dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(n), 0);
dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(n), 0);
}
}
static void dwc3_cache_hwparams(struct dwc3 *dwc)
{
struct dwc3_hwparams *parms = &dwc->hwparams;
parms->hwparams0 = dwc3_readl(dwc->regs, DWC3_GHWPARAMS0);
parms->hwparams1 = dwc3_readl(dwc->regs, DWC3_GHWPARAMS1);
parms->hwparams2 = dwc3_readl(dwc->regs, DWC3_GHWPARAMS2);
parms->hwparams3 = dwc3_readl(dwc->regs, DWC3_GHWPARAMS3);
parms->hwparams4 = dwc3_readl(dwc->regs, DWC3_GHWPARAMS4);
parms->hwparams5 = dwc3_readl(dwc->regs, DWC3_GHWPARAMS5);
parms->hwparams6 = dwc3_readl(dwc->regs, DWC3_GHWPARAMS6);
parms->hwparams7 = dwc3_readl(dwc->regs, DWC3_GHWPARAMS7);
parms->hwparams8 = dwc3_readl(dwc->regs, DWC3_GHWPARAMS8);
}
/**
* dwc3_core_init - Low-level initialization of DWC3 Core
* @dwc: Pointer to our controller context structure
*
* Returns 0 on success otherwise negative errno.
*/
static int dwc3_core_init(struct dwc3 *dwc)
{
unsigned long timeout;
u32 reg;
int ret;
reg = dwc3_readl(dwc->regs, DWC3_GSNPSID);
/* This should read as U3 followed by revision number */
if ((reg & DWC3_GSNPSID_MASK) != 0x55330000) {
dev_err(dwc->dev, "this is not a DesignWare USB3 DRD Core\n");
ret = -ENODEV;
goto err0;
}
dwc->revision = reg;
/* issue device SoftReset too */
timeout = jiffies + msecs_to_jiffies(500);
dwc3_writel(dwc->regs, DWC3_DCTL, DWC3_DCTL_CSFTRST);
do {
reg = dwc3_readl(dwc->regs, DWC3_DCTL);
if (!(reg & DWC3_DCTL_CSFTRST))
break;
if (time_after(jiffies, timeout)) {
dev_err(dwc->dev, "Reset Timed Out\n");
ret = -ETIMEDOUT;
goto err0;
}
cpu_relax();
} while (true);
dwc3_core_soft_reset(dwc);
dwc3_cache_hwparams(dwc);
reg = dwc3_readl(dwc->regs, DWC3_GCTL);
reg &= ~DWC3_GCTL_SCALEDOWN_MASK;
reg &= ~DWC3_GCTL_DISSCRAMBLE;
switch (DWC3_GHWPARAMS1_EN_PWROPT(dwc->hwparams.hwparams1)) {
case DWC3_GHWPARAMS1_EN_PWROPT_CLK:
reg &= ~DWC3_GCTL_DSBLCLKGTNG;
break;
default:
dev_dbg(dwc->dev, "No power optimization available\n");
}
/*
* WORKAROUND: DWC3 revisions <1.90a have a bug
* where the device can fail to connect at SuperSpeed
* and falls back to high-speed mode which causes
* the device to enter a Connect/Disconnect loop
*/
if (dwc->revision < DWC3_REVISION_190A)
reg |= DWC3_GCTL_U2RSTECN;
dwc3_writel(dwc->regs, DWC3_GCTL, reg);
/*
* The default value of GUCTL[31:22] should be 0x8. But on cores
* revision < 2.30a, the default value is mistakenly overridden
* with 0x0. Restore the correct default value.
*/
if (dwc->revision < DWC3_REVISION_230A) {
reg = dwc3_readl(dwc->regs, DWC3_GUCTL);
reg &= ~DWC3_GUCTL_REFCLKPER;
reg |= 0x8 << __ffs(DWC3_GUCTL_REFCLKPER);
dwc3_writel(dwc->regs, DWC3_GUCTL, reg);
}
/*
* Currently, the default and the recommended value for GUSB3PIPECTL
* [21:19] in the RTL is 3'b100 or 32 consecutive errors. Based on
* analysis and experiments in the lab, it is found that there is a
* relatively low probability of getting 32 consecutive word errors
* in the presence of random recovered noise (during electrical idle).
* This can delay the entry to a low power state such that for
* applications where the link stays in a non-U0 state for a short
* duration (< 1 microsecond), the local PHY does not enter the low
* power state prior to receiving a potential LFPS wakeup. This causes
* the PHY CDR (Clock and Data Recovery) operation to be unstable for
* some Synopsys PHYs.
*
* The proposal now is to change the default and the recommended value
* for GUSB3PIPECTL[21:19] in the RTL from 3'b100 to a minimum of
* 3'b001. Perform the same in software for controllers prior to 2.30a
* revision.
*/
if (dwc->revision < DWC3_REVISION_230A) {
reg = dwc3_readl(dwc->regs, DWC3_GUSB3PIPECTL(0));
reg &= ~DWC3_GUSB3PIPECTL_DELAY_P1P2P3;
reg |= 1 << __ffs(DWC3_GUSB3PIPECTL_DELAY_P1P2P3);
/*
* Receiver Detection in U3/Rx.Det is mistakenly disabled in
* cores < 2.30a. Fix it here.
*/
reg &= ~DWC3_GUSB3PIPECTL_DIS_RXDET_U3_RXDET;
dwc3_writel(dwc->regs, DWC3_GUSB3PIPECTL(0), reg);
}
/*
* clear Elastic buffer mode in GUSBPIPE_CTRL(0) register, otherwise
* it results in high link errors and could cause SS mode transfer
* failure.
*/
reg = dwc3_readl(dwc->regs, DWC3_GUSB3PIPECTL(0));
reg &= ~DWC3_GUSB3PIPECTL_ELASTIC_BUF_MODE;
dwc3_writel(dwc->regs, DWC3_GUSB3PIPECTL(0), reg);
if (!dwc->ev_buffs) {
ret = dwc3_alloc_event_buffers(dwc, DWC3_EVENT_BUFFERS_SIZE);
if (ret) {
dev_err(dwc->dev, "failed to allocate event buffers\n");
ret = -ENOMEM;
goto err1;
}
}
ret = dwc3_event_buffers_setup(dwc);
if (ret) {
dev_err(dwc->dev, "failed to setup event buffers\n");
goto err1;
}
return 0;
err1:
dwc3_free_event_buffers(dwc);
err0:
return ret;
}
static void dwc3_core_exit(struct dwc3 *dwc)
{
dwc3_event_buffers_cleanup(dwc);
dwc3_free_event_buffers(dwc);
}
/* XHCI reset, resets other CORE registers as well, re-init those */
void dwc3_post_host_reset_core_init(struct dwc3 *dwc)
{
dwc3_core_init(dwc);
dwc3_gadget_restart(dwc);
dwc3_notify_event(dwc, DWC3_CONTROLLER_POST_INITIALIZATION_EVENT);
}
static void (*notify_event) (struct dwc3 *, unsigned);
void dwc3_set_notifier(void (*notify)(struct dwc3 *, unsigned))
{
notify_event = notify;
}
EXPORT_SYMBOL(dwc3_set_notifier);
int dwc3_notify_event(struct dwc3 *dwc, unsigned event)
{
int ret = 0;
if (dwc->notify_event)
dwc->notify_event(dwc, event);
else
ret = -ENODEV;
return ret;
}
EXPORT_SYMBOL(dwc3_notify_event);
#define DWC3_ALIGN_MASK (16 - 1)
static u64 dwc3_dma_mask = DMA_BIT_MASK(64);
static int __devinit dwc3_probe(struct platform_device *pdev)
{
struct device_node *node = pdev->dev.of_node;
struct resource *res;
struct dwc3 *dwc;
struct device *dev = &pdev->dev;
int ret = -ENOMEM;
void __iomem *regs;
void *mem;
u8 mode;
bool host_only_mode;
mem = devm_kzalloc(dev, sizeof(*dwc) + DWC3_ALIGN_MASK, GFP_KERNEL);
if (!mem) {
dev_err(dev, "not enough memory\n");
return -ENOMEM;
}
dwc = PTR_ALIGN(mem, DWC3_ALIGN_MASK + 1);
dwc->mem = mem;
if (!dev->dma_mask)
dev->dma_mask = &dwc3_dma_mask;
if (!dev->coherent_dma_mask)
dev->coherent_dma_mask = DMA_BIT_MASK(64);
dwc->notify_event = notify_event;
res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!res) {
dev_err(dev, "missing IRQ\n");
return -ENODEV;
}
dwc->xhci_resources[1].start = res->start;
dwc->xhci_resources[1].end = res->end;
dwc->xhci_resources[1].flags = res->flags;
dwc->xhci_resources[1].name = res->name;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(dev, "missing memory resource\n");
return -ENODEV;
}
dwc->xhci_resources[0].start = res->start;
dwc->xhci_resources[0].end = dwc->xhci_resources[0].start +
DWC3_XHCI_REGS_END;
dwc->xhci_resources[0].flags = res->flags;
dwc->xhci_resources[0].name = res->name;
/*
* Request memory region but exclude xHCI regs,
* since it will be requested by the xhci-plat driver.
*/
res = devm_request_mem_region(dev, res->start + DWC3_GLOBALS_REGS_START,
resource_size(res) - DWC3_GLOBALS_REGS_START,
dev_name(dev));
if (!res) {
dev_err(dev, "can't request mem region\n");
return -ENOMEM;
}
regs = devm_ioremap_nocache(dev, res->start, resource_size(res));
if (!regs) {
dev_err(dev, "ioremap failed\n");
return -ENOMEM;
}
spin_lock_init(&dwc->lock);
platform_set_drvdata(pdev, dwc);
dwc->regs = regs;
dwc->regs_size = resource_size(res);
dwc->dev = dev;
if (!strncmp("super", maximum_speed, 5))
dwc->maximum_speed = DWC3_DCFG_SUPERSPEED;
else if (!strncmp("high", maximum_speed, 4))
dwc->maximum_speed = DWC3_DCFG_HIGHSPEED;
else if (!strncmp("full", maximum_speed, 4))
dwc->maximum_speed = DWC3_DCFG_FULLSPEED1;
else if (!strncmp("low", maximum_speed, 3))
dwc->maximum_speed = DWC3_DCFG_LOWSPEED;
else
dwc->maximum_speed = DWC3_DCFG_SUPERSPEED;
dwc->needs_fifo_resize = of_property_read_bool(node, "tx-fifo-resize");
host_only_mode = of_property_read_bool(node, "host-only-mode");
pm_runtime_no_callbacks(dev);
pm_runtime_set_active(dev);
pm_runtime_enable(dev);
ret = dwc3_core_init(dwc);
if (ret) {
dev_err(dev, "failed to initialize core\n");
return ret;
}
mode = DWC3_MODE(dwc->hwparams.hwparams0);
/* Override mode if user selects host-only config with DRD core */
if (host_only_mode && (mode == DWC3_MODE_DRD)) {
dev_dbg(dev, "host only mode selected\n");
mode = DWC3_MODE_HOST;
}
switch (mode) {
case DWC3_MODE_DEVICE:
dwc3_set_mode(dwc, DWC3_GCTL_PRTCAP_DEVICE);
ret = dwc3_gadget_init(dwc);
if (ret) {
dev_err(dev, "failed to initialize gadget\n");
goto err1;
}
break;
case DWC3_MODE_HOST:
dwc3_set_mode(dwc, DWC3_GCTL_PRTCAP_HOST);
ret = dwc3_host_init(dwc);
if (ret) {
dev_err(dev, "failed to initialize host\n");
goto err1;
}
break;
case DWC3_MODE_DRD:
dwc3_set_mode(dwc, DWC3_GCTL_PRTCAP_OTG);
ret = dwc3_otg_init(dwc);
if (ret) {
dev_err(dev, "failed to initialize otg\n");
goto err1;
}
ret = dwc3_host_init(dwc);
if (ret) {
dev_err(dev, "failed to initialize host\n");
dwc3_otg_exit(dwc);
goto err1;
}
ret = dwc3_gadget_init(dwc);
if (ret) {
dev_err(dev, "failed to initialize gadget\n");
dwc3_host_exit(dwc);
dwc3_otg_exit(dwc);
goto err1;
}
break;
default:
dev_err(dev, "Unsupported mode of operation %d\n", mode);
goto err1;
}
dwc->mode = mode;
ret = dwc3_debugfs_init(dwc);
if (ret) {
dev_err(dev, "failed to initialize debugfs\n");
goto err2;
}
dwc3_notify_event(dwc, DWC3_CONTROLLER_POST_INITIALIZATION_EVENT);
return 0;
err2:
switch (mode) {
case DWC3_MODE_DEVICE:
dwc3_gadget_exit(dwc);
break;
case DWC3_MODE_HOST:
dwc3_host_exit(dwc);
break;
case DWC3_MODE_DRD:
dwc3_gadget_exit(dwc);
dwc3_host_exit(dwc);
dwc3_otg_exit(dwc);
break;
default:
/* do nothing */
break;
}
err1:
dwc3_core_exit(dwc);
return ret;
}
static int __devexit dwc3_remove(struct platform_device *pdev)
{
struct dwc3 *dwc = platform_get_drvdata(pdev);
struct resource *res;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
pm_runtime_disable(&pdev->dev);
dwc3_debugfs_exit(dwc);
switch (dwc->mode) {
case DWC3_MODE_DEVICE:
dwc3_gadget_exit(dwc);
break;
case DWC3_MODE_HOST:
dwc3_host_exit(dwc);
break;
case DWC3_MODE_DRD:
dwc3_gadget_exit(dwc);
dwc3_host_exit(dwc);
dwc3_otg_exit(dwc);
break;
default:
/* do nothing */
break;
}
dwc3_core_exit(dwc);
return 0;
}
#ifdef CONFIG_OF
static const struct of_device_id of_dwc3_match[] = {
{
.compatible = "synopsys,dwc3"
},
{ },
};
MODULE_DEVICE_TABLE(of, of_dwc3_match);
#endif
static struct platform_driver dwc3_driver = {
.probe = dwc3_probe,
.remove = __devexit_p(dwc3_remove),
.driver = {
.name = "dwc3",
.of_match_table = of_match_ptr(of_dwc3_match),
},
};
module_platform_driver(dwc3_driver);
MODULE_ALIAS("platform:dwc3");
MODULE_AUTHOR("Felipe Balbi <balbi@ti.com>");
MODULE_LICENSE("Dual BSD/GPL");
MODULE_DESCRIPTION("DesignWare USB3 DRD Controller Driver");
| gpl-2.0 |
quarnster/boxeebox-xbmc | lib/libUPnP/Neptune/Source/Tests/Tls1/TlsTest1.cpp | 202 | 15523 | /*****************************************************************
|
| TLS Test Program 1
|
| (c) 2001-2006 Gilles Boccon-Gibod
| Author: Gilles Boccon-Gibod (bok@bok.net)
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Neptune.h"
#include "NptDebug.h"
#include "TlsClientPrivate1.h"
#include "TlsClientPrivate2.h"
#if defined(WIN32) && defined(_DEBUG)
#include <crtdbg.h>
#endif
#define CHECK(x) \
do { \
if (!(x)) { \
fprintf(stderr, "ERROR line %d \n", __LINE__); \
} \
} while(0)
const char*
GetCipherSuiteName(unsigned int id)
{
switch (id) {
case 0: return "NOT SET";
case NPT_TLS_RSA_WITH_RC4_128_MD5: return "RSA-WITH-RC4-128-MD5";
case NPT_TLS_RSA_WITH_RC4_128_SHA: return "RSA-WITH-RC4-128-SHA";
case NPT_TLS_RSA_WITH_AES_128_CBC_SHA: return "RSA-WITH-AES-128-CBC-SHA";
case NPT_TLS_RSA_WITH_AES_256_CBC_SHA: return "RSA-WITH-AES-256-CBC-SHA";
default: return "UNKNOWN";
}
}
static const char* EquifaxCA =
"MIIDIDCCAomgAwIBAgIENd70zzANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJV\n"
"UzEQMA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2Vy\n"
"dGlmaWNhdGUgQXV0aG9yaXR5MB4XDTk4MDgyMjE2NDE1MVoXDTE4MDgyMjE2NDE1\n"
"MVowTjELMAkGA1UEBhMCVVMxEDAOBgNVBAoTB0VxdWlmYXgxLTArBgNVBAsTJEVx\n"
"dWlmYXggU2VjdXJlIENlcnRpZmljYXRlIEF1dGhvcml0eTCBnzANBgkqhkiG9w0B\n"
"AQEFAAOBjQAwgYkCgYEAwV2xWGcIYu6gmi0fCG2RFGiYCh7+2gRvE4RiIcPRfM6f\n"
"BeC4AfBONOziipUEZKzxa1NfBbPLZ4C/QgKO/t0BCezhABRP/PvwDN1Dulsr4R+A\n"
"cJkVV5MW8Q+XarfCaCMczE1ZMKxRHjuvK9buY0V7xdlfUNLjUA86iOe/FP3gx7kC\n"
"AwEAAaOCAQkwggEFMHAGA1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEQ\n"
"MA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2VydGlm\n"
"aWNhdGUgQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMBoGA1UdEAQTMBGBDzIwMTgw\n"
"ODIyMTY0MTUxWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUSOZo+SvSspXXR9gj\n"
"IBBPM5iQn9QwHQYDVR0OBBYEFEjmaPkr0rKV10fYIyAQTzOYkJ/UMAwGA1UdEwQF\n"
"MAMBAf8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUA\n"
"A4GBAFjOKer89961zgK5F7WF0bnj4JXMJTENAKaSbn+2kmOeUJXRmm/kEd5jhW6Y\n"
"7qj/WsjTVbJmcVfewCHrPSqnI0kBBIZCe/zuf6IWUrVnZ9NA2zsmWLIodz2uFHdh\n"
"1voqZiegDfqnc1zqcPGUIWVEX/r87yloqaKHee9570+sB3c4\n";
static void
PrintCertificateInfo(NPT_TlsCertificateInfo& cert_info)
{
printf("[6] Fingerprints:\n");
printf("MD5: %s\n", NPT_HexString(cert_info.fingerprint.md5, sizeof(cert_info.fingerprint.md5), ":").GetChars());
printf("SHA1: %s\n", NPT_HexString(cert_info.fingerprint.sha1, sizeof(cert_info.fingerprint.sha1), ":").GetChars());
printf("Subject Certificate:\n");
printf(" Common Name = %s\n", cert_info.subject.common_name.GetChars());
printf(" Organization = %s\n", cert_info.subject.organization.GetChars());
printf(" Organizational Name = %s\n", cert_info.subject.organizational_name.GetChars());
printf("Issuer Certificate:\n");
printf(" Common Name = %s\n", cert_info.issuer.common_name.GetChars());
printf(" Organization = %s\n", cert_info.issuer.organization.GetChars());
printf(" Organizational Name = %s\n", cert_info.issuer.organizational_name.GetChars());
printf("Issue Date: %d/%d/%d %02d:%02d:%02d\n", cert_info.issue_date.m_Year,
cert_info.issue_date.m_Month,
cert_info.issue_date.m_Day,
cert_info.issue_date.m_Hours,
cert_info.issue_date.m_Minutes,
cert_info.issue_date.m_Seconds);
printf("Expiration Date: %d/%d/%d %02d:%02d:%02d\n", cert_info.expiration_date.m_Year,
cert_info.expiration_date.m_Month,
cert_info.expiration_date.m_Day,
cert_info.expiration_date.m_Hours,
cert_info.expiration_date.m_Minutes,
cert_info.expiration_date.m_Seconds);
for (NPT_List<NPT_String>::Iterator i = cert_info.alternate_names.GetFirstItem();
i;
++i) {
printf("DNS Name: %s\n", (*i).GetChars());
}
printf("\n");
}
static void
PrintCertificateChain(NPT_TlsSession& session)
{
NPT_Ordinal position = 0;
NPT_Result result;
do {
NPT_TlsCertificateInfo info;
result = session.GetPeerCertificateInfo(info, position++);
if (NPT_SUCCEEDED(result)) {
PrintCertificateInfo(info);
}
} while (NPT_SUCCEEDED(result));
}
static void
PrintSessionInfo(NPT_TlsSession& session)
{
NPT_Result result;
NPT_DataBuffer session_id;
result = session.GetSessionId(session_id);
CHECK(result == NPT_SUCCESS);
//CHECK(session_id.GetDataSize() > 0);
printf("[5] Session ID: ");
printf("%s", NPT_HexString(session_id.GetData(), session_id.GetDataSize()).GetChars());
printf("\n");
PrintCertificateChain(session);
printf("[7] Cipher Type = %d (%s)\n", session.GetCipherSuiteId(), GetCipherSuiteName(session.GetCipherSuiteId()));
}
static int
TestRemoteServer(const char* hostname, unsigned int port, bool verify_cert, NPT_Result expected_cert_verif_result, bool client_key)
{
printf("[1] Connecting to %s...\n", hostname);
NPT_Socket* client_socket = new NPT_TcpClientSocket();
NPT_IpAddress server_ip;
NPT_Result result = server_ip.ResolveName(hostname);
if (NPT_FAILED(result)) {
printf("!ERROR cannot resolve hostname\n");
return 1;
}
NPT_SocketAddress server_addr(server_ip, port);
result = client_socket->Connect(server_addr);
printf("[2] Connection result = %d (%s)\n", result, NPT_ResultText(result));
if (NPT_FAILED(result)) {
printf("!ERROR cannot connect\n");
return 1;
}
NPT_InputStreamReference input;
NPT_OutputStreamReference output;
client_socket->GetInputStream(input);
client_socket->GetOutputStream(output);
delete client_socket;
NPT_TlsContext context(NPT_TlsContext::OPTION_VERIFY_LATER);
NPT_DataBuffer ta_data;
NPT_Base64::Decode(EquifaxCA, NPT_StringLength(EquifaxCA), ta_data);
result = context.AddTrustAnchor(ta_data.GetData(), ta_data.GetDataSize());
if (NPT_FAILED(result)) {
printf("!ERROR: context->AddTrustAnchor() \n");
return 1;
}
result = context.AddTrustAnchors(NPT_Tls::GetDefaultTrustAnchors(0));
if (NPT_FAILED(result)) {
printf("!ERROR: context->AddTrustAnchors() \n");
return 1;
}
if (client_key) {
/* self-signed cert */
result = context.LoadKey(NPT_TLS_KEY_FORMAT_PKCS8, TestClient_p8_1, TestClient_p8_1_len, "neptune");
CHECK(result == NPT_SUCCESS);
result = context.SelfSignCertificate("MyClientCommonName", "MyClientOrganization", "MyClientOrganizationalName");
}
NPT_TlsClientSession session(context, input, output);
printf("[3] Performing Handshake\n");
result = session.Handshake();
printf("[4] Handshake Result = %d (%s)\n", result, NPT_ResultText(result));
if (NPT_FAILED(result)) {
printf("!ERROR handshake failed\n");
return 1;
}
PrintSessionInfo(session);
if (verify_cert) {
result = session.VerifyPeerCertificate();
printf("[9] Certificate Verification Result = %d (%s)\n", result, NPT_ResultText(result));
if (result != expected_cert_verif_result) {
printf("!ERROR, cert verification expected %d, got %d\n", expected_cert_verif_result, result);
return 1;
}
}
NPT_InputStreamReference ssl_input;
NPT_OutputStreamReference ssl_output;
session.GetInputStream(ssl_input);
session.GetOutputStream(ssl_output);
printf("[10] Getting / Document\n");
ssl_output->WriteString("GET / HTTP/1.0\n\n");
for (;;) {
unsigned char buffer[1];
NPT_Size bytes_read = 0;
result = ssl_input->Read(&buffer[0], 1, &bytes_read);
if (NPT_SUCCEEDED(result)) {
CHECK(bytes_read == 1);
printf("%c", buffer[0]);
} else {
if (result != NPT_ERROR_EOS && result != NPT_ERROR_CONNECTION_ABORTED) {
printf("!ERROR: Read() returned %d (%s)\n", result, NPT_ResultText(result));
}
break;
}
}
printf("[9] SUCCESS\n");
return 0;
}
class TlsTestServer : public NPT_Thread
{
void Run();
public:
TlsTestServer(int mode) : m_Mode(mode) {}
int m_Mode;
NPT_SharedVariable m_Ready;
NPT_SocketInfo m_SocketInfo;
};
void
TlsTestServer::Run()
{
printf("@@@ starting TLS server\n");
NPT_TcpServerSocket socket;
NPT_SocketAddress address(NPT_IpAddress::Any, 0);
NPT_Result result = socket.Bind(address);
if (NPT_FAILED(result)) {
fprintf(stderr, "@@@ Bind failed (%d)\n", result);
return;
}
result = socket.GetInfo(m_SocketInfo);
if (NPT_FAILED(result)) {
fprintf(stderr, "@@@ GetInfo failed (%d)\n", result);
return;
}
socket.Listen(5);
m_Ready.SetValue(1);
printf("@@@ Waiting for connection\n");
NPT_Socket* client = NULL;
socket.WaitForNewClient(client);
printf("@@@ Client connected\n");
NPT_TlsContext tls_context(m_Mode?(NPT_TlsContext::OPTION_REQUIRE_CLIENT_CERTIFICATE | NPT_TlsContext::OPTION_VERIFY_LATER):0);
/* self-signed cert */
result = tls_context.LoadKey(NPT_TLS_KEY_FORMAT_PKCS8, TestClient_p8_1, TestClient_p8_1_len, "neptune");
CHECK(result == NPT_SUCCESS);
result = tls_context.SelfSignCertificate("MyServerCommonName", "MyServerOrganization", "MyServerOrganizationalName");
NPT_InputStreamReference socket_input;
NPT_OutputStreamReference socket_output;
client->GetInputStream(socket_input);
client->GetOutputStream(socket_output);
NPT_TlsServerSession session(tls_context, socket_input, socket_output);
delete client;
result = session.Handshake();
if (m_Mode == 1) {
/* expect a self-signed client cert */
result = session.VerifyPeerCertificate();
printf("@@@ Certificate Verification Result = %d (%s)\n", result, NPT_ResultText(result));
if (result != NPT_ERROR_TLS_CERTIFICATE_SELF_SIGNED) {
printf("!ERROR, cert verification expected %d, got %d\n", NPT_ERROR_TLS_CERTIFICATE_SELF_SIGNED, result);
return;
}
PrintCertificateChain(session);
} else {
if (NPT_FAILED(result)) {
fprintf(stderr, "@@@ Handshake failed (%d : %s)\n", result, NPT_ResultText(result));
return;
}
}
NPT_OutputStreamReference tls_output;
session.GetOutputStream(tls_output);
tls_output->WriteString("Hello, Client\n");
printf("@@@ TLS server done\n");
//NPT_System::Sleep(1.0);
}
static void
TestLocalServer()
{
TlsTestServer* server = new TlsTestServer(0);
server->Start();
server->m_Ready.WaitUntilEquals(1);
TestRemoteServer("127.0.0.1", server->m_SocketInfo.local_address.GetPort(), true, NPT_ERROR_TLS_CERTIFICATE_SELF_SIGNED, true);
server->Wait();
delete server;
server = new TlsTestServer(1);
server->Start();
server->m_Ready.WaitUntilEquals(1);
TestRemoteServer("127.0.0.1", server->m_SocketInfo.local_address.GetPort(), true, NPT_ERROR_TLS_CERTIFICATE_SELF_SIGNED, true);
server->Wait();
delete server;
}
static void
TestPrivateKeys()
{
NPT_TlsContext context;
NPT_Result result;
NPT_DataBuffer key_data;
NPT_Base64::Decode(TestClient_rsa_priv_base64_1, NPT_StringLength(TestClient_rsa_priv_base64_1), key_data);
result = context.LoadKey(NPT_TLS_KEY_FORMAT_RSA_PRIVATE, key_data.GetData(), key_data.GetDataSize(), NULL);
CHECK(result == NPT_SUCCESS);
result = context.LoadKey(NPT_TLS_KEY_FORMAT_PKCS8, TestClient_p8_1, TestClient_p8_1_len, NULL);
CHECK(result != NPT_SUCCESS);
result = context.LoadKey(NPT_TLS_KEY_FORMAT_PKCS8, TestClient_p8_1, TestClient_p8_1_len, "neptune");
CHECK(result == NPT_SUCCESS);
}
class TestTlsConnector : public NPT_HttpTlsConnector
{
public:
virtual NPT_Result VerifyPeer(NPT_TlsClientSession& session,
const char* hostname) {
printf("+++ Verifying Peer (hostname=%s)\n", hostname);
PrintSessionInfo(session);
return NPT_HttpTlsConnector::VerifyPeer(session, hostname);
}
};
static void
TestHttpConnector(const char* hostname)
{
TestTlsConnector connector;
NPT_HttpClient client(&connector, false);
NPT_String url_string = "https://";
url_string += hostname;
url_string += "/index.html";
NPT_HttpUrl url(url_string);
NPT_HttpRequest request(url, NPT_HTTP_METHOD_GET);
NPT_HttpResponse* response = NULL;
NPT_Result result = client.SendRequest(request, response);
CHECK(result == NPT_SUCCESS);
if (NPT_SUCCEEDED(result)) {
CHECK(response->GetEntity() != NULL);
if (response->GetEntity()) {
printf("+++ HTTP Response: code=%d, type=%s, len=%d\n",
response->GetStatusCode(),
response->GetEntity()->GetContentType().GetChars(),
(int)response->GetEntity()->GetContentLength());
}
} else {
printf("!ERROR: SendRequest returns %d (%s)\n", result, NPT_ResultText(result));
}
delete response;
}
static void
TestDnsNameMatch()
{
CHECK(!NPT_Tls::MatchDnsName(NULL, NULL));
CHECK(!NPT_Tls::MatchDnsName(NULL, ""));
CHECK(!NPT_Tls::MatchDnsName(NULL, "a"));
CHECK(!NPT_Tls::MatchDnsName(NULL, "a.com"));
CHECK(!NPT_Tls::MatchDnsName(NULL, "*"));
CHECK(!NPT_Tls::MatchDnsName("", NULL));
CHECK(!NPT_Tls::MatchDnsName("", ""));
CHECK(!NPT_Tls::MatchDnsName("", "a"));
CHECK(!NPT_Tls::MatchDnsName("", "a.com"));
CHECK(!NPT_Tls::MatchDnsName("", "*"));
CHECK(!NPT_Tls::MatchDnsName("*", "*"));
CHECK(!NPT_Tls::MatchDnsName("a", "*"));
CHECK(!NPT_Tls::MatchDnsName("a.com", "*"));
CHECK(!NPT_Tls::MatchDnsName("a.com", "b.com"));
CHECK(!NPT_Tls::MatchDnsName("a.com", "*.a.com"));
CHECK(NPT_Tls::MatchDnsName("a.com", "a.com"));
CHECK(NPT_Tls::MatchDnsName("b.a.com", "*.a.com"));
CHECK(NPT_Tls::MatchDnsName("a.com", "A.com"));
CHECK(NPT_Tls::MatchDnsName("a.com", "a.COM"));
}
int
main(int argc, char** argv)
{
/* test dns name matching */
TestDnsNameMatch();
/* test private keys */
TestPrivateKeys();
/* test a local connection */
TestLocalServer();
/* test a connection */
const char* hostname = argc==2?argv[1]:"zebulon.bok.net";
TestRemoteServer(hostname, 443, true, NPT_SUCCESS, false);
/* test using the http connector */
TestHttpConnector(hostname);
}
| gpl-2.0 |
ps3dev/binutils-2.21.1-PS3 | bfd/pei-arm-wince.c | 202 | 1220 | /* BFD back-end for ARM WINCE PE IMAGE COFF files.
Copyright 2006, 2007 Free Software Foundation, Inc.
This file is part of BFD, the Binary File Descriptor library.
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 3 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. */
#define TARGET_UNDERSCORE 0
#define USER_LABEL_PREFIX ""
#define TARGET_LITTLE_SYM arm_wince_pei_little_vec
#define TARGET_LITTLE_NAME "pei-arm-wince-little"
#define TARGET_BIG_SYM arm_wince_pei_big_vec
#define TARGET_BIG_NAME "pei-arm-wince-big"
#define LOCAL_LABEL_PREFIX "."
#include "pei-arm.c"
| gpl-2.0 |
motley-git/TF201-Kernel-Lite | drivers/net/caif/tegra_caif_sspi.c | 458 | 10710 | /*
* Copyright (c) 2011, NVIDIA Corporation.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/wait.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/delay.h>
#include <linux/spi/spi.h>
#include <linux/tegra_caif.h>
#include <mach/spi.h>
#include <net/caif/caif_spi.h>
MODULE_LICENSE("GPL");
#define SPI_CAIF_PAD_TRANSACTION_SIZE(x) \
(((x) > 4) ? ((((x) + 15) / 16) * 16) : (x))
struct sspi_struct {
struct cfspi_dev sdev;
struct cfspi_xfer *xfer;
};
static struct sspi_struct slave;
static struct platform_device slave_device;
static struct spi_device *tegra_caif_spi_slave_device;
int tegra_caif_sspi_gpio_spi_int;
int tegra_caif_sspi_gpio_spi_ss;
int tegra_caif_sspi_gpio_reset;
int tegra_caif_sspi_gpio_power;
int tegra_caif_sspi_gpio_awr;
int tegra_caif_sspi_gpio_cwr;
static int __devinit tegra_caif_spi_slave_probe(struct spi_device *spi);
static int tegra_caif_spi_slave_remove(struct spi_device *spi)
{
return 0;
}
#ifdef CONFIG_PM
static int tegra_caif_spi_slave_suspend(struct spi_device *spi
, pm_message_t mesg)
{
return 0;
}
#endif /* CONFIG_PM */
#ifdef CONFIG_PM
static int tegra_caif_spi_slave_resume(struct spi_device *spi)
{
return 0;
}
#endif /* CONFIG_PM */
static struct spi_driver tegra_caif_spi_slave_driver = {
.driver = {
.name = "baseband_spi_slave0.0",
.owner = THIS_MODULE,
},
.probe = tegra_caif_spi_slave_probe,
.remove = __devexit_p(tegra_caif_spi_slave_remove),
#ifdef CONFIG_PM
.suspend = tegra_caif_spi_slave_suspend,
.resume = tegra_caif_spi_slave_resume,
#endif /* CONFIG_PM */
};
void tegra_caif_modem_power(int on)
{
static int u3xx_on;
int err;
int cnt = 0;
int val = 0;
if (u3xx_on == on)
return;
u3xx_on = on;
if (u3xx_on) {
/* turn on u3xx modem */
err = gpio_request(tegra_caif_sspi_gpio_reset
, "caif_sspi_reset");
if (err < 0)
goto err1;
err = gpio_request(tegra_caif_sspi_gpio_power
, "caif_sspi_power");
if (err < 0)
goto err2;
err = gpio_request(tegra_caif_sspi_gpio_awr
, "caif_sspi_awr");
if (err < 0)
goto err3;
err = gpio_request(tegra_caif_sspi_gpio_cwr
, "caif_sspi_cwr");
if (err < 0)
goto err4;
err = gpio_direction_output(tegra_caif_sspi_gpio_reset
, 0 /* asserted */);
if (err < 0)
goto err5;
err = gpio_direction_output(tegra_caif_sspi_gpio_power
, 0 /* off */);
if (err < 0)
goto err6;
err = gpio_direction_output(tegra_caif_sspi_gpio_awr
, 0);
if (err < 0)
goto err7;
err = gpio_direction_input(tegra_caif_sspi_gpio_cwr);
if (err < 0)
goto err8;
gpio_set_value(tegra_caif_sspi_gpio_power, 0);
gpio_set_value(tegra_caif_sspi_gpio_reset, 0);
msleep(800);
/* pulse modem power on for 300 ms */
gpio_set_value(tegra_caif_sspi_gpio_reset
, 1 /* deasserted */);
msleep(300);
gpio_set_value(tegra_caif_sspi_gpio_power, 1);
msleep(300);
gpio_set_value(tegra_caif_sspi_gpio_power, 0);
msleep(100);
/* set awr high */
gpio_set_value(tegra_caif_sspi_gpio_awr, 1);
val = gpio_get_value(tegra_caif_sspi_gpio_cwr);
while (!val) {
/* wait for cwr to go high */
val = gpio_get_value(tegra_caif_sspi_gpio_cwr);
pr_info(".");
msleep(100);
cnt++;
if (cnt > 200) {
pr_err("\nWaiting for CWR timed out - ERROR\n");
break;
}
}
}
return;
err8:
err7:
err6:
err5:
gpio_free(tegra_caif_sspi_gpio_cwr);
err4:
gpio_free(tegra_caif_sspi_gpio_awr);
err3:
gpio_free(tegra_caif_sspi_gpio_power);
err2:
gpio_free(tegra_caif_sspi_gpio_reset);
err1:
return;
}
static irqreturn_t sspi_irq(int irq, void *arg)
{
/* You only need to trigger on an edge to the active state of the
* SS signal. Once a edge is detected, the ss_cb() function should
* be called with the parameter assert set to true. It is OK
* (and even advised) to call the ss_cb() function in IRQ context
* in order not to add any delay.
*/
int val;
struct cfspi_dev *sdev = (struct cfspi_dev *)arg;
val = gpio_get_value(tegra_caif_sspi_gpio_spi_ss);
if (val)
return IRQ_HANDLED;
sdev->ifc->ss_cb(true, sdev->ifc);
return IRQ_HANDLED;
}
static int sspi_callback(void *arg)
{
/* for each spi_sync() call
* - sspi_callback() called before spi transfer
* - sspi_complete() called after spi transfer
*/
/* set master interrupt gpio pin active (tells master to
* start spi clock)
*/
udelay(MIN_TRANSITION_TIME_USEC);
gpio_set_value(tegra_caif_sspi_gpio_spi_int, 1);
return 0;
}
static void sspi_complete(void *context)
{
/* Normally the DMA or the SPI framework will call you back
* in something similar to this. The only thing you need to
* do is to call the xfer_done_cb() function, providing the pointer
* to the CAIF SPI interface. It is OK to call this function
* from IRQ context.
*/
struct cfspi_dev *sdev = (struct cfspi_dev *)context;
sdev->ifc->xfer_done_cb(sdev->ifc);
}
static void swap_byte(unsigned char *buf, unsigned int bufsiz)
{
unsigned int i;
unsigned char tmp;
for (i = 0; i < bufsiz; i += 2) {
tmp = buf[i];
buf[i] = buf[i+1];
buf[i+1] = tmp;
}
}
static int sspi_init_xfer(struct cfspi_xfer *xfer, struct cfspi_dev *dev)
{
/* Store transfer info. For a normal implementation you should
* set up your DMA here and make sure that you are ready to
* receive the data from the master SPI.
*/
struct sspi_struct *sspi = (struct sspi_struct *)dev->priv;
struct spi_message m;
struct spi_transfer t;
int err;
sspi->xfer = xfer;
if (!tegra_caif_spi_slave_device)
return -ENODEV;
err = spi_tegra_register_callback(tegra_caif_spi_slave_device,
sspi_callback, sspi);
if (err < 0) {
pr_err("\nspi_tegra_register_callback() failed\n");
return -ENODEV;
}
memset(&t, 0, sizeof(t));
t.tx_buf = xfer->va_tx;
swap_byte(xfer->va_tx, xfer->tx_dma_len);
t.rx_buf = xfer->va_rx;
t.len = max(xfer->tx_dma_len, xfer->rx_dma_len);
t.len = SPI_CAIF_PAD_TRANSACTION_SIZE(t.len);
t.bits_per_word = 16;
/* SPI controller clock should be 4 times the spi_clk */
t.speed_hz = (SPI_MASTER_CLK_MHZ * 4 * 1000000);
spi_message_init(&m);
spi_message_add_tail(&t, &m);
dmb();
err = spi_sync(tegra_caif_spi_slave_device, &m);
dmb();
swap_byte(xfer->va_tx, xfer->tx_dma_len);
swap_byte(xfer->va_rx, xfer->rx_dma_len);
sspi_complete(&sspi->sdev);
if (err < 0) {
pr_err("spi_init_xfer - spi_sync() err %d\n", err);
return err;
}
return 0;
}
void sspi_sig_xfer(bool xfer, struct cfspi_dev *dev)
{
/* If xfer is true then you should assert the SPI_INT to indicate to
* the master that you are ready to recieve the data from the master
* SPI. If xfer is false then you should de-assert SPI_INT to indicate
* that the transfer is done.
*/
if (xfer)
gpio_set_value(tegra_caif_sspi_gpio_spi_int, 1);
else
gpio_set_value(tegra_caif_sspi_gpio_spi_int, 0);
}
static void sspi_release(struct device *dev)
{
/*
* Here you should release your SPI device resources.
*/
}
static int __init sspi_init(void)
{
/* Here you should initialize your SPI device by providing the
* necessary functions, clock speed, name and private data. Once
* done, you can register your device with the
* platform_device_register() function. This function will return
* with the CAIF SPI interface initialized. This is probably also
* the place where you should set up your GPIOs, interrupts and SPI
* resources.
*/
int res = 0;
/* Register Tegra SPI protocol driver. */
res = spi_register_driver(&tegra_caif_spi_slave_driver);
if (res < 0)
return res;
/* Initialize slave device. */
slave.sdev.init_xfer = sspi_init_xfer;
slave.sdev.sig_xfer = sspi_sig_xfer;
slave.sdev.clk_mhz = SPI_MASTER_CLK_MHZ;
slave.sdev.priv = &slave;
slave.sdev.name = "spi_sspi";
slave_device.dev.release = sspi_release;
/* Initialize platform device. */
slave_device.name = "cfspi_sspi";
slave_device.dev.platform_data = &slave.sdev;
/* Register platform device. */
res = platform_device_register(&slave_device);
if (res)
return -ENODEV;
return res;
}
static void __exit sspi_exit(void)
{
/* Delete platfrom device. */
platform_device_del(&slave_device);
/* Free Tegra SPI protocol driver. */
spi_unregister_driver(&tegra_caif_spi_slave_driver);
/* Free Tegra GPIO interrupts. */
disable_irq(gpio_to_irq(tegra_caif_sspi_gpio_spi_ss));
free_irq(gpio_to_irq(tegra_caif_sspi_gpio_spi_ss), &slave_device);
/* Free Tegra GPIOs. */
gpio_free(tegra_caif_sspi_gpio_spi_ss);
gpio_free(tegra_caif_sspi_gpio_spi_int);
}
static int __devinit tegra_caif_spi_slave_probe(struct spi_device *spi)
{
struct tegra_caif_platform_data *pdata;
int res;
if (!spi)
return -ENODEV;
pdata = spi->dev.platform_data;
if (!pdata)
return -ENODEV;
tegra_caif_sspi_gpio_spi_int = pdata->spi_int;
tegra_caif_sspi_gpio_spi_ss = pdata->spi_ss;
tegra_caif_sspi_gpio_reset = pdata->reset;
tegra_caif_sspi_gpio_power = pdata->power;
tegra_caif_sspi_gpio_awr = pdata->awr;
tegra_caif_sspi_gpio_cwr = pdata->cwr;
tegra_caif_spi_slave_device = spi;
/* Initialize Tegra GPIOs. */
res = gpio_request(tegra_caif_sspi_gpio_spi_int, "caif_sspi_spi_int");
if (res < 0)
goto err1;
res = gpio_request(tegra_caif_sspi_gpio_spi_ss, "caif_sspi_ss");
if (res < 0)
goto err2;
res = gpio_direction_output(tegra_caif_sspi_gpio_spi_int, 0);
if (res < 0)
goto err3;
res = gpio_direction_input(tegra_caif_sspi_gpio_spi_ss);
if (res < 0)
goto err4;
tegra_caif_modem_power(1);
msleep(2000);
/* Initialize Tegra GPIO interrupts. */
res = request_irq(gpio_to_irq(tegra_caif_sspi_gpio_spi_ss),
sspi_irq, IRQF_TRIGGER_FALLING, "caif_sspi_ss_irq",
&slave.sdev);
if (res < 0)
goto err5;
return 0;
err5:
free_irq(gpio_to_irq(tegra_caif_sspi_gpio_spi_ss), &slave_device);
err4:
err3:
gpio_free(tegra_caif_sspi_gpio_spi_ss);
err2:
gpio_free(tegra_caif_sspi_gpio_spi_int);
err1:
return res;
}
module_init(sspi_init);
module_exit(sspi_exit);
| gpl-2.0 |
aatjitra/PR25 | drivers/gpu/drm/drm_ioc32.c | 458 | 32648 | /**
* \file drm_ioc32.c
*
* 32-bit ioctl compatibility routines for the DRM.
*
* \author Paul Mackerras <paulus@samba.org>
*
* Copyright (C) Paul Mackerras 2005.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHOR 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/compat.h>
#include <linux/ratelimit.h>
#include "drmP.h"
#include "drm_core.h"
#define DRM_IOCTL_VERSION32 DRM_IOWR(0x00, drm_version32_t)
#define DRM_IOCTL_GET_UNIQUE32 DRM_IOWR(0x01, drm_unique32_t)
#define DRM_IOCTL_GET_MAP32 DRM_IOWR(0x04, drm_map32_t)
#define DRM_IOCTL_GET_CLIENT32 DRM_IOWR(0x05, drm_client32_t)
#define DRM_IOCTL_GET_STATS32 DRM_IOR( 0x06, drm_stats32_t)
#define DRM_IOCTL_SET_UNIQUE32 DRM_IOW( 0x10, drm_unique32_t)
#define DRM_IOCTL_ADD_MAP32 DRM_IOWR(0x15, drm_map32_t)
#define DRM_IOCTL_ADD_BUFS32 DRM_IOWR(0x16, drm_buf_desc32_t)
#define DRM_IOCTL_MARK_BUFS32 DRM_IOW( 0x17, drm_buf_desc32_t)
#define DRM_IOCTL_INFO_BUFS32 DRM_IOWR(0x18, drm_buf_info32_t)
#define DRM_IOCTL_MAP_BUFS32 DRM_IOWR(0x19, drm_buf_map32_t)
#define DRM_IOCTL_FREE_BUFS32 DRM_IOW( 0x1a, drm_buf_free32_t)
#define DRM_IOCTL_RM_MAP32 DRM_IOW( 0x1b, drm_map32_t)
#define DRM_IOCTL_SET_SAREA_CTX32 DRM_IOW( 0x1c, drm_ctx_priv_map32_t)
#define DRM_IOCTL_GET_SAREA_CTX32 DRM_IOWR(0x1d, drm_ctx_priv_map32_t)
#define DRM_IOCTL_RES_CTX32 DRM_IOWR(0x26, drm_ctx_res32_t)
#define DRM_IOCTL_DMA32 DRM_IOWR(0x29, drm_dma32_t)
#define DRM_IOCTL_AGP_ENABLE32 DRM_IOW( 0x32, drm_agp_mode32_t)
#define DRM_IOCTL_AGP_INFO32 DRM_IOR( 0x33, drm_agp_info32_t)
#define DRM_IOCTL_AGP_ALLOC32 DRM_IOWR(0x34, drm_agp_buffer32_t)
#define DRM_IOCTL_AGP_FREE32 DRM_IOW( 0x35, drm_agp_buffer32_t)
#define DRM_IOCTL_AGP_BIND32 DRM_IOW( 0x36, drm_agp_binding32_t)
#define DRM_IOCTL_AGP_UNBIND32 DRM_IOW( 0x37, drm_agp_binding32_t)
#define DRM_IOCTL_SG_ALLOC32 DRM_IOW( 0x38, drm_scatter_gather32_t)
#define DRM_IOCTL_SG_FREE32 DRM_IOW( 0x39, drm_scatter_gather32_t)
#define DRM_IOCTL_UPDATE_DRAW32 DRM_IOW( 0x3f, drm_update_draw32_t)
#define DRM_IOCTL_WAIT_VBLANK32 DRM_IOWR(0x3a, drm_wait_vblank32_t)
typedef struct drm_version_32 {
int version_major; /**< Major version */
int version_minor; /**< Minor version */
int version_patchlevel; /**< Patch level */
u32 name_len; /**< Length of name buffer */
u32 name; /**< Name of driver */
u32 date_len; /**< Length of date buffer */
u32 date; /**< User-space buffer to hold date */
u32 desc_len; /**< Length of desc buffer */
u32 desc; /**< User-space buffer to hold desc */
} drm_version32_t;
static int compat_drm_version(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_version32_t v32;
struct drm_version __user *version;
int err;
if (copy_from_user(&v32, (void __user *)arg, sizeof(v32)))
return -EFAULT;
version = compat_alloc_user_space(sizeof(*version));
if (!access_ok(VERIFY_WRITE, version, sizeof(*version)))
return -EFAULT;
if (__put_user(v32.name_len, &version->name_len)
|| __put_user((void __user *)(unsigned long)v32.name,
&version->name)
|| __put_user(v32.date_len, &version->date_len)
|| __put_user((void __user *)(unsigned long)v32.date,
&version->date)
|| __put_user(v32.desc_len, &version->desc_len)
|| __put_user((void __user *)(unsigned long)v32.desc,
&version->desc))
return -EFAULT;
err = drm_ioctl(file,
DRM_IOCTL_VERSION, (unsigned long)version);
if (err)
return err;
if (__get_user(v32.version_major, &version->version_major)
|| __get_user(v32.version_minor, &version->version_minor)
|| __get_user(v32.version_patchlevel, &version->version_patchlevel)
|| __get_user(v32.name_len, &version->name_len)
|| __get_user(v32.date_len, &version->date_len)
|| __get_user(v32.desc_len, &version->desc_len))
return -EFAULT;
if (copy_to_user((void __user *)arg, &v32, sizeof(v32)))
return -EFAULT;
return 0;
}
typedef struct drm_unique32 {
u32 unique_len; /**< Length of unique */
u32 unique; /**< Unique name for driver instantiation */
} drm_unique32_t;
static int compat_drm_getunique(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_unique32_t uq32;
struct drm_unique __user *u;
int err;
if (copy_from_user(&uq32, (void __user *)arg, sizeof(uq32)))
return -EFAULT;
u = compat_alloc_user_space(sizeof(*u));
if (!access_ok(VERIFY_WRITE, u, sizeof(*u)))
return -EFAULT;
if (__put_user(uq32.unique_len, &u->unique_len)
|| __put_user((void __user *)(unsigned long)uq32.unique,
&u->unique))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_GET_UNIQUE, (unsigned long)u);
if (err)
return err;
if (__get_user(uq32.unique_len, &u->unique_len))
return -EFAULT;
if (copy_to_user((void __user *)arg, &uq32, sizeof(uq32)))
return -EFAULT;
return 0;
}
static int compat_drm_setunique(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_unique32_t uq32;
struct drm_unique __user *u;
if (copy_from_user(&uq32, (void __user *)arg, sizeof(uq32)))
return -EFAULT;
u = compat_alloc_user_space(sizeof(*u));
if (!access_ok(VERIFY_WRITE, u, sizeof(*u)))
return -EFAULT;
if (__put_user(uq32.unique_len, &u->unique_len)
|| __put_user((void __user *)(unsigned long)uq32.unique,
&u->unique))
return -EFAULT;
return drm_ioctl(file, DRM_IOCTL_SET_UNIQUE, (unsigned long)u);
}
typedef struct drm_map32 {
u32 offset; /**< Requested physical address (0 for SAREA)*/
u32 size; /**< Requested physical size (bytes) */
enum drm_map_type type; /**< Type of memory to map */
enum drm_map_flags flags; /**< Flags */
u32 handle; /**< User-space: "Handle" to pass to mmap() */
int mtrr; /**< MTRR slot used */
} drm_map32_t;
static int compat_drm_getmap(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_map32_t __user *argp = (void __user *)arg;
drm_map32_t m32;
struct drm_map __user *map;
int idx, err;
void *handle;
if (get_user(idx, &argp->offset))
return -EFAULT;
map = compat_alloc_user_space(sizeof(*map));
if (!access_ok(VERIFY_WRITE, map, sizeof(*map)))
return -EFAULT;
if (__put_user(idx, &map->offset))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_GET_MAP, (unsigned long)map);
if (err)
return err;
if (__get_user(m32.offset, &map->offset)
|| __get_user(m32.size, &map->size)
|| __get_user(m32.type, &map->type)
|| __get_user(m32.flags, &map->flags)
|| __get_user(handle, &map->handle)
|| __get_user(m32.mtrr, &map->mtrr))
return -EFAULT;
m32.handle = (unsigned long)handle;
if (copy_to_user(argp, &m32, sizeof(m32)))
return -EFAULT;
return 0;
}
static int compat_drm_addmap(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_map32_t __user *argp = (void __user *)arg;
drm_map32_t m32;
struct drm_map __user *map;
int err;
void *handle;
if (copy_from_user(&m32, argp, sizeof(m32)))
return -EFAULT;
map = compat_alloc_user_space(sizeof(*map));
if (!access_ok(VERIFY_WRITE, map, sizeof(*map)))
return -EFAULT;
if (__put_user(m32.offset, &map->offset)
|| __put_user(m32.size, &map->size)
|| __put_user(m32.type, &map->type)
|| __put_user(m32.flags, &map->flags))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_ADD_MAP, (unsigned long)map);
if (err)
return err;
if (__get_user(m32.offset, &map->offset)
|| __get_user(m32.mtrr, &map->mtrr)
|| __get_user(handle, &map->handle))
return -EFAULT;
m32.handle = (unsigned long)handle;
if (m32.handle != (unsigned long)handle)
printk_ratelimited(KERN_ERR "compat_drm_addmap truncated handle"
" %p for type %d offset %x\n",
handle, m32.type, m32.offset);
if (copy_to_user(argp, &m32, sizeof(m32)))
return -EFAULT;
return 0;
}
static int compat_drm_rmmap(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_map32_t __user *argp = (void __user *)arg;
struct drm_map __user *map;
u32 handle;
if (get_user(handle, &argp->handle))
return -EFAULT;
map = compat_alloc_user_space(sizeof(*map));
if (!access_ok(VERIFY_WRITE, map, sizeof(*map)))
return -EFAULT;
if (__put_user((void *)(unsigned long)handle, &map->handle))
return -EFAULT;
return drm_ioctl(file, DRM_IOCTL_RM_MAP, (unsigned long)map);
}
typedef struct drm_client32 {
int idx; /**< Which client desired? */
int auth; /**< Is client authenticated? */
u32 pid; /**< Process ID */
u32 uid; /**< User ID */
u32 magic; /**< Magic */
u32 iocs; /**< Ioctl count */
} drm_client32_t;
static int compat_drm_getclient(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_client32_t c32;
drm_client32_t __user *argp = (void __user *)arg;
struct drm_client __user *client;
int idx, err;
if (get_user(idx, &argp->idx))
return -EFAULT;
client = compat_alloc_user_space(sizeof(*client));
if (!access_ok(VERIFY_WRITE, client, sizeof(*client)))
return -EFAULT;
if (__put_user(idx, &client->idx))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_GET_CLIENT, (unsigned long)client);
if (err)
return err;
if (__get_user(c32.idx, &client->idx)
|| __get_user(c32.auth, &client->auth)
|| __get_user(c32.pid, &client->pid)
|| __get_user(c32.uid, &client->uid)
|| __get_user(c32.magic, &client->magic)
|| __get_user(c32.iocs, &client->iocs))
return -EFAULT;
if (copy_to_user(argp, &c32, sizeof(c32)))
return -EFAULT;
return 0;
}
typedef struct drm_stats32 {
u32 count;
struct {
u32 value;
enum drm_stat_type type;
} data[15];
} drm_stats32_t;
static int compat_drm_getstats(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_stats32_t s32;
drm_stats32_t __user *argp = (void __user *)arg;
struct drm_stats __user *stats;
int i, err;
stats = compat_alloc_user_space(sizeof(*stats));
if (!access_ok(VERIFY_WRITE, stats, sizeof(*stats)))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_GET_STATS, (unsigned long)stats);
if (err)
return err;
if (__get_user(s32.count, &stats->count))
return -EFAULT;
for (i = 0; i < 15; ++i)
if (__get_user(s32.data[i].value, &stats->data[i].value)
|| __get_user(s32.data[i].type, &stats->data[i].type))
return -EFAULT;
if (copy_to_user(argp, &s32, sizeof(s32)))
return -EFAULT;
return 0;
}
typedef struct drm_buf_desc32 {
int count; /**< Number of buffers of this size */
int size; /**< Size in bytes */
int low_mark; /**< Low water mark */
int high_mark; /**< High water mark */
int flags;
u32 agp_start; /**< Start address in the AGP aperture */
} drm_buf_desc32_t;
static int compat_drm_addbufs(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_buf_desc32_t __user *argp = (void __user *)arg;
struct drm_buf_desc __user *buf;
int err;
unsigned long agp_start;
buf = compat_alloc_user_space(sizeof(*buf));
if (!access_ok(VERIFY_WRITE, buf, sizeof(*buf))
|| !access_ok(VERIFY_WRITE, argp, sizeof(*argp)))
return -EFAULT;
if (__copy_in_user(buf, argp, offsetof(drm_buf_desc32_t, agp_start))
|| __get_user(agp_start, &argp->agp_start)
|| __put_user(agp_start, &buf->agp_start))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_ADD_BUFS, (unsigned long)buf);
if (err)
return err;
if (__copy_in_user(argp, buf, offsetof(drm_buf_desc32_t, agp_start))
|| __get_user(agp_start, &buf->agp_start)
|| __put_user(agp_start, &argp->agp_start))
return -EFAULT;
return 0;
}
static int compat_drm_markbufs(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_buf_desc32_t b32;
drm_buf_desc32_t __user *argp = (void __user *)arg;
struct drm_buf_desc __user *buf;
if (copy_from_user(&b32, argp, sizeof(b32)))
return -EFAULT;
buf = compat_alloc_user_space(sizeof(*buf));
if (!access_ok(VERIFY_WRITE, buf, sizeof(*buf)))
return -EFAULT;
if (__put_user(b32.size, &buf->size)
|| __put_user(b32.low_mark, &buf->low_mark)
|| __put_user(b32.high_mark, &buf->high_mark))
return -EFAULT;
return drm_ioctl(file, DRM_IOCTL_MARK_BUFS, (unsigned long)buf);
}
typedef struct drm_buf_info32 {
int count; /**< Entries in list */
u32 list;
} drm_buf_info32_t;
static int compat_drm_infobufs(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_buf_info32_t req32;
drm_buf_info32_t __user *argp = (void __user *)arg;
drm_buf_desc32_t __user *to;
struct drm_buf_info __user *request;
struct drm_buf_desc __user *list;
size_t nbytes;
int i, err;
int count, actual;
if (copy_from_user(&req32, argp, sizeof(req32)))
return -EFAULT;
count = req32.count;
to = (drm_buf_desc32_t __user *) (unsigned long)req32.list;
if (count < 0)
count = 0;
if (count > 0
&& !access_ok(VERIFY_WRITE, to, count * sizeof(drm_buf_desc32_t)))
return -EFAULT;
nbytes = sizeof(*request) + count * sizeof(struct drm_buf_desc);
request = compat_alloc_user_space(nbytes);
if (!access_ok(VERIFY_WRITE, request, nbytes))
return -EFAULT;
list = (struct drm_buf_desc *) (request + 1);
if (__put_user(count, &request->count)
|| __put_user(list, &request->list))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_INFO_BUFS, (unsigned long)request);
if (err)
return err;
if (__get_user(actual, &request->count))
return -EFAULT;
if (count >= actual)
for (i = 0; i < actual; ++i)
if (__copy_in_user(&to[i], &list[i],
offsetof(struct drm_buf_desc, flags)))
return -EFAULT;
if (__put_user(actual, &argp->count))
return -EFAULT;
return 0;
}
typedef struct drm_buf_pub32 {
int idx; /**< Index into the master buffer list */
int total; /**< Buffer size */
int used; /**< Amount of buffer in use (for DMA) */
u32 address; /**< Address of buffer */
} drm_buf_pub32_t;
typedef struct drm_buf_map32 {
int count; /**< Length of the buffer list */
u32 virtual; /**< Mmap'd area in user-virtual */
u32 list; /**< Buffer information */
} drm_buf_map32_t;
static int compat_drm_mapbufs(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_buf_map32_t __user *argp = (void __user *)arg;
drm_buf_map32_t req32;
drm_buf_pub32_t __user *list32;
struct drm_buf_map __user *request;
struct drm_buf_pub __user *list;
int i, err;
int count, actual;
size_t nbytes;
void __user *addr;
if (copy_from_user(&req32, argp, sizeof(req32)))
return -EFAULT;
count = req32.count;
list32 = (void __user *)(unsigned long)req32.list;
if (count < 0)
return -EINVAL;
nbytes = sizeof(*request) + count * sizeof(struct drm_buf_pub);
request = compat_alloc_user_space(nbytes);
if (!access_ok(VERIFY_WRITE, request, nbytes))
return -EFAULT;
list = (struct drm_buf_pub *) (request + 1);
if (__put_user(count, &request->count)
|| __put_user(list, &request->list))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_MAP_BUFS, (unsigned long)request);
if (err)
return err;
if (__get_user(actual, &request->count))
return -EFAULT;
if (count >= actual)
for (i = 0; i < actual; ++i)
if (__copy_in_user(&list32[i], &list[i],
offsetof(struct drm_buf_pub, address))
|| __get_user(addr, &list[i].address)
|| __put_user((unsigned long)addr,
&list32[i].address))
return -EFAULT;
if (__put_user(actual, &argp->count)
|| __get_user(addr, &request->virtual)
|| __put_user((unsigned long)addr, &argp->virtual))
return -EFAULT;
return 0;
}
typedef struct drm_buf_free32 {
int count;
u32 list;
} drm_buf_free32_t;
static int compat_drm_freebufs(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_buf_free32_t req32;
struct drm_buf_free __user *request;
drm_buf_free32_t __user *argp = (void __user *)arg;
if (copy_from_user(&req32, argp, sizeof(req32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request)))
return -EFAULT;
if (__put_user(req32.count, &request->count)
|| __put_user((int __user *)(unsigned long)req32.list,
&request->list))
return -EFAULT;
return drm_ioctl(file, DRM_IOCTL_FREE_BUFS, (unsigned long)request);
}
typedef struct drm_ctx_priv_map32 {
unsigned int ctx_id; /**< Context requesting private mapping */
u32 handle; /**< Handle of map */
} drm_ctx_priv_map32_t;
static int compat_drm_setsareactx(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_ctx_priv_map32_t req32;
struct drm_ctx_priv_map __user *request;
drm_ctx_priv_map32_t __user *argp = (void __user *)arg;
if (copy_from_user(&req32, argp, sizeof(req32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request)))
return -EFAULT;
if (__put_user(req32.ctx_id, &request->ctx_id)
|| __put_user((void *)(unsigned long)req32.handle,
&request->handle))
return -EFAULT;
return drm_ioctl(file, DRM_IOCTL_SET_SAREA_CTX, (unsigned long)request);
}
static int compat_drm_getsareactx(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct drm_ctx_priv_map __user *request;
drm_ctx_priv_map32_t __user *argp = (void __user *)arg;
int err;
unsigned int ctx_id;
void *handle;
if (!access_ok(VERIFY_WRITE, argp, sizeof(*argp))
|| __get_user(ctx_id, &argp->ctx_id))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request)))
return -EFAULT;
if (__put_user(ctx_id, &request->ctx_id))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_GET_SAREA_CTX, (unsigned long)request);
if (err)
return err;
if (__get_user(handle, &request->handle)
|| __put_user((unsigned long)handle, &argp->handle))
return -EFAULT;
return 0;
}
typedef struct drm_ctx_res32 {
int count;
u32 contexts;
} drm_ctx_res32_t;
static int compat_drm_resctx(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_ctx_res32_t __user *argp = (void __user *)arg;
drm_ctx_res32_t res32;
struct drm_ctx_res __user *res;
int err;
if (copy_from_user(&res32, argp, sizeof(res32)))
return -EFAULT;
res = compat_alloc_user_space(sizeof(*res));
if (!access_ok(VERIFY_WRITE, res, sizeof(*res)))
return -EFAULT;
if (__put_user(res32.count, &res->count)
|| __put_user((struct drm_ctx __user *) (unsigned long)res32.contexts,
&res->contexts))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_RES_CTX, (unsigned long)res);
if (err)
return err;
if (__get_user(res32.count, &res->count)
|| __put_user(res32.count, &argp->count))
return -EFAULT;
return 0;
}
typedef struct drm_dma32 {
int context; /**< Context handle */
int send_count; /**< Number of buffers to send */
u32 send_indices; /**< List of handles to buffers */
u32 send_sizes; /**< Lengths of data to send */
enum drm_dma_flags flags; /**< Flags */
int request_count; /**< Number of buffers requested */
int request_size; /**< Desired size for buffers */
u32 request_indices; /**< Buffer information */
u32 request_sizes;
int granted_count; /**< Number of buffers granted */
} drm_dma32_t;
static int compat_drm_dma(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_dma32_t d32;
drm_dma32_t __user *argp = (void __user *)arg;
struct drm_dma __user *d;
int err;
if (copy_from_user(&d32, argp, sizeof(d32)))
return -EFAULT;
d = compat_alloc_user_space(sizeof(*d));
if (!access_ok(VERIFY_WRITE, d, sizeof(*d)))
return -EFAULT;
if (__put_user(d32.context, &d->context)
|| __put_user(d32.send_count, &d->send_count)
|| __put_user((int __user *)(unsigned long)d32.send_indices,
&d->send_indices)
|| __put_user((int __user *)(unsigned long)d32.send_sizes,
&d->send_sizes)
|| __put_user(d32.flags, &d->flags)
|| __put_user(d32.request_count, &d->request_count)
|| __put_user((int __user *)(unsigned long)d32.request_indices,
&d->request_indices)
|| __put_user((int __user *)(unsigned long)d32.request_sizes,
&d->request_sizes))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_DMA, (unsigned long)d);
if (err)
return err;
if (__get_user(d32.request_size, &d->request_size)
|| __get_user(d32.granted_count, &d->granted_count)
|| __put_user(d32.request_size, &argp->request_size)
|| __put_user(d32.granted_count, &argp->granted_count))
return -EFAULT;
return 0;
}
#if __OS_HAS_AGP
typedef struct drm_agp_mode32 {
u32 mode; /**< AGP mode */
} drm_agp_mode32_t;
static int compat_drm_agp_enable(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_agp_mode32_t __user *argp = (void __user *)arg;
drm_agp_mode32_t m32;
struct drm_agp_mode __user *mode;
if (get_user(m32.mode, &argp->mode))
return -EFAULT;
mode = compat_alloc_user_space(sizeof(*mode));
if (put_user(m32.mode, &mode->mode))
return -EFAULT;
return drm_ioctl(file, DRM_IOCTL_AGP_ENABLE, (unsigned long)mode);
}
typedef struct drm_agp_info32 {
int agp_version_major;
int agp_version_minor;
u32 mode;
u32 aperture_base; /* physical address */
u32 aperture_size; /* bytes */
u32 memory_allowed; /* bytes */
u32 memory_used;
/* PCI information */
unsigned short id_vendor;
unsigned short id_device;
} drm_agp_info32_t;
static int compat_drm_agp_info(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_agp_info32_t __user *argp = (void __user *)arg;
drm_agp_info32_t i32;
struct drm_agp_info __user *info;
int err;
info = compat_alloc_user_space(sizeof(*info));
if (!access_ok(VERIFY_WRITE, info, sizeof(*info)))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_AGP_INFO, (unsigned long)info);
if (err)
return err;
if (__get_user(i32.agp_version_major, &info->agp_version_major)
|| __get_user(i32.agp_version_minor, &info->agp_version_minor)
|| __get_user(i32.mode, &info->mode)
|| __get_user(i32.aperture_base, &info->aperture_base)
|| __get_user(i32.aperture_size, &info->aperture_size)
|| __get_user(i32.memory_allowed, &info->memory_allowed)
|| __get_user(i32.memory_used, &info->memory_used)
|| __get_user(i32.id_vendor, &info->id_vendor)
|| __get_user(i32.id_device, &info->id_device))
return -EFAULT;
if (copy_to_user(argp, &i32, sizeof(i32)))
return -EFAULT;
return 0;
}
typedef struct drm_agp_buffer32 {
u32 size; /**< In bytes -- will round to page boundary */
u32 handle; /**< Used for binding / unbinding */
u32 type; /**< Type of memory to allocate */
u32 physical; /**< Physical used by i810 */
} drm_agp_buffer32_t;
static int compat_drm_agp_alloc(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_agp_buffer32_t __user *argp = (void __user *)arg;
drm_agp_buffer32_t req32;
struct drm_agp_buffer __user *request;
int err;
if (copy_from_user(&req32, argp, sizeof(req32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| __put_user(req32.size, &request->size)
|| __put_user(req32.type, &request->type))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_AGP_ALLOC, (unsigned long)request);
if (err)
return err;
if (__get_user(req32.handle, &request->handle)
|| __get_user(req32.physical, &request->physical)
|| copy_to_user(argp, &req32, sizeof(req32))) {
drm_ioctl(file, DRM_IOCTL_AGP_FREE, (unsigned long)request);
return -EFAULT;
}
return 0;
}
static int compat_drm_agp_free(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_agp_buffer32_t __user *argp = (void __user *)arg;
struct drm_agp_buffer __user *request;
u32 handle;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| get_user(handle, &argp->handle)
|| __put_user(handle, &request->handle))
return -EFAULT;
return drm_ioctl(file, DRM_IOCTL_AGP_FREE, (unsigned long)request);
}
typedef struct drm_agp_binding32 {
u32 handle; /**< From drm_agp_buffer */
u32 offset; /**< In bytes -- will round to page boundary */
} drm_agp_binding32_t;
static int compat_drm_agp_bind(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_agp_binding32_t __user *argp = (void __user *)arg;
drm_agp_binding32_t req32;
struct drm_agp_binding __user *request;
if (copy_from_user(&req32, argp, sizeof(req32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| __put_user(req32.handle, &request->handle)
|| __put_user(req32.offset, &request->offset))
return -EFAULT;
return drm_ioctl(file, DRM_IOCTL_AGP_BIND, (unsigned long)request);
}
static int compat_drm_agp_unbind(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_agp_binding32_t __user *argp = (void __user *)arg;
struct drm_agp_binding __user *request;
u32 handle;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| get_user(handle, &argp->handle)
|| __put_user(handle, &request->handle))
return -EFAULT;
return drm_ioctl(file, DRM_IOCTL_AGP_UNBIND, (unsigned long)request);
}
#endif /* __OS_HAS_AGP */
typedef struct drm_scatter_gather32 {
u32 size; /**< In bytes -- will round to page boundary */
u32 handle; /**< Used for mapping / unmapping */
} drm_scatter_gather32_t;
static int compat_drm_sg_alloc(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_scatter_gather32_t __user *argp = (void __user *)arg;
struct drm_scatter_gather __user *request;
int err;
unsigned long x;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| !access_ok(VERIFY_WRITE, argp, sizeof(*argp))
|| __get_user(x, &argp->size)
|| __put_user(x, &request->size))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_SG_ALLOC, (unsigned long)request);
if (err)
return err;
/* XXX not sure about the handle conversion here... */
if (__get_user(x, &request->handle)
|| __put_user(x >> PAGE_SHIFT, &argp->handle))
return -EFAULT;
return 0;
}
static int compat_drm_sg_free(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_scatter_gather32_t __user *argp = (void __user *)arg;
struct drm_scatter_gather __user *request;
unsigned long x;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| !access_ok(VERIFY_WRITE, argp, sizeof(*argp))
|| __get_user(x, &argp->handle)
|| __put_user(x << PAGE_SHIFT, &request->handle))
return -EFAULT;
return drm_ioctl(file, DRM_IOCTL_SG_FREE, (unsigned long)request);
}
#if defined(CONFIG_X86) || defined(CONFIG_IA64)
typedef struct drm_update_draw32 {
drm_drawable_t handle;
unsigned int type;
unsigned int num;
/* 64-bit version has a 32-bit pad here */
u64 data; /**< Pointer */
} __attribute__((packed)) drm_update_draw32_t;
static int compat_drm_update_draw(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_update_draw32_t update32;
struct drm_update_draw __user *request;
int err;
if (copy_from_user(&update32, (void __user *)arg, sizeof(update32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request)) ||
__put_user(update32.handle, &request->handle) ||
__put_user(update32.type, &request->type) ||
__put_user(update32.num, &request->num) ||
__put_user(update32.data, &request->data))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_UPDATE_DRAW, (unsigned long)request);
return err;
}
#endif
struct drm_wait_vblank_request32 {
enum drm_vblank_seq_type type;
unsigned int sequence;
u32 signal;
};
struct drm_wait_vblank_reply32 {
enum drm_vblank_seq_type type;
unsigned int sequence;
s32 tval_sec;
s32 tval_usec;
};
typedef union drm_wait_vblank32 {
struct drm_wait_vblank_request32 request;
struct drm_wait_vblank_reply32 reply;
} drm_wait_vblank32_t;
static int compat_drm_wait_vblank(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_wait_vblank32_t __user *argp = (void __user *)arg;
drm_wait_vblank32_t req32;
union drm_wait_vblank __user *request;
int err;
if (copy_from_user(&req32, argp, sizeof(req32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| __put_user(req32.request.type, &request->request.type)
|| __put_user(req32.request.sequence, &request->request.sequence)
|| __put_user(req32.request.signal, &request->request.signal))
return -EFAULT;
err = drm_ioctl(file, DRM_IOCTL_WAIT_VBLANK, (unsigned long)request);
if (err)
return err;
if (__get_user(req32.reply.type, &request->reply.type)
|| __get_user(req32.reply.sequence, &request->reply.sequence)
|| __get_user(req32.reply.tval_sec, &request->reply.tval_sec)
|| __get_user(req32.reply.tval_usec, &request->reply.tval_usec))
return -EFAULT;
if (copy_to_user(argp, &req32, sizeof(req32)))
return -EFAULT;
return 0;
}
drm_ioctl_compat_t *drm_compat_ioctls[] = {
[DRM_IOCTL_NR(DRM_IOCTL_VERSION32)] = compat_drm_version,
[DRM_IOCTL_NR(DRM_IOCTL_GET_UNIQUE32)] = compat_drm_getunique,
[DRM_IOCTL_NR(DRM_IOCTL_GET_MAP32)] = compat_drm_getmap,
[DRM_IOCTL_NR(DRM_IOCTL_GET_CLIENT32)] = compat_drm_getclient,
[DRM_IOCTL_NR(DRM_IOCTL_GET_STATS32)] = compat_drm_getstats,
[DRM_IOCTL_NR(DRM_IOCTL_SET_UNIQUE32)] = compat_drm_setunique,
[DRM_IOCTL_NR(DRM_IOCTL_ADD_MAP32)] = compat_drm_addmap,
[DRM_IOCTL_NR(DRM_IOCTL_ADD_BUFS32)] = compat_drm_addbufs,
[DRM_IOCTL_NR(DRM_IOCTL_MARK_BUFS32)] = compat_drm_markbufs,
[DRM_IOCTL_NR(DRM_IOCTL_INFO_BUFS32)] = compat_drm_infobufs,
[DRM_IOCTL_NR(DRM_IOCTL_MAP_BUFS32)] = compat_drm_mapbufs,
[DRM_IOCTL_NR(DRM_IOCTL_FREE_BUFS32)] = compat_drm_freebufs,
[DRM_IOCTL_NR(DRM_IOCTL_RM_MAP32)] = compat_drm_rmmap,
[DRM_IOCTL_NR(DRM_IOCTL_SET_SAREA_CTX32)] = compat_drm_setsareactx,
[DRM_IOCTL_NR(DRM_IOCTL_GET_SAREA_CTX32)] = compat_drm_getsareactx,
[DRM_IOCTL_NR(DRM_IOCTL_RES_CTX32)] = compat_drm_resctx,
[DRM_IOCTL_NR(DRM_IOCTL_DMA32)] = compat_drm_dma,
#if __OS_HAS_AGP
[DRM_IOCTL_NR(DRM_IOCTL_AGP_ENABLE32)] = compat_drm_agp_enable,
[DRM_IOCTL_NR(DRM_IOCTL_AGP_INFO32)] = compat_drm_agp_info,
[DRM_IOCTL_NR(DRM_IOCTL_AGP_ALLOC32)] = compat_drm_agp_alloc,
[DRM_IOCTL_NR(DRM_IOCTL_AGP_FREE32)] = compat_drm_agp_free,
[DRM_IOCTL_NR(DRM_IOCTL_AGP_BIND32)] = compat_drm_agp_bind,
[DRM_IOCTL_NR(DRM_IOCTL_AGP_UNBIND32)] = compat_drm_agp_unbind,
#endif
[DRM_IOCTL_NR(DRM_IOCTL_SG_ALLOC32)] = compat_drm_sg_alloc,
[DRM_IOCTL_NR(DRM_IOCTL_SG_FREE32)] = compat_drm_sg_free,
#if defined(CONFIG_X86) || defined(CONFIG_IA64)
[DRM_IOCTL_NR(DRM_IOCTL_UPDATE_DRAW32)] = compat_drm_update_draw,
#endif
[DRM_IOCTL_NR(DRM_IOCTL_WAIT_VBLANK32)] = compat_drm_wait_vblank,
};
/**
* Called whenever a 32-bit process running under a 64-bit kernel
* performs an ioctl on /dev/drm.
*
* \param file_priv DRM file private.
* \param cmd command.
* \param arg user argument.
* \return zero on success or negative number on failure.
*/
long drm_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
unsigned int nr = DRM_IOCTL_NR(cmd);
drm_ioctl_compat_t *fn;
int ret;
/* Assume that ioctls without an explicit compat routine will just
* work. This may not always be a good assumption, but it's better
* than always failing.
*/
if (nr >= ARRAY_SIZE(drm_compat_ioctls))
return drm_ioctl(filp, cmd, arg);
fn = drm_compat_ioctls[nr];
if (fn != NULL)
ret = (*fn) (filp, cmd, arg);
else
ret = drm_ioctl(filp, cmd, arg);
return ret;
}
EXPORT_SYMBOL(drm_compat_ioctl);
| gpl-2.0 |
jforge/linux | drivers/usb/dwc3/ulpi.c | 714 | 2039 | /**
* ulpi.c - DesignWare USB3 Controller's ULPI PHY interface
*
* Copyright (C) 2015 Intel Corporation
*
* Author: Heikki Krogerus <heikki.krogerus@linux.intel.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/ulpi/regs.h>
#include "core.h"
#include "io.h"
#define DWC3_ULPI_ADDR(a) \
((a >= ULPI_EXT_VENDOR_SPECIFIC) ? \
DWC3_GUSB2PHYACC_ADDR(ULPI_ACCESS_EXTENDED) | \
DWC3_GUSB2PHYACC_EXTEND_ADDR(a) : DWC3_GUSB2PHYACC_ADDR(a))
static int dwc3_ulpi_busyloop(struct dwc3 *dwc)
{
unsigned count = 1000;
u32 reg;
while (count--) {
reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYACC(0));
if (!(reg & DWC3_GUSB2PHYACC_BUSY))
return 0;
cpu_relax();
}
return -ETIMEDOUT;
}
static int dwc3_ulpi_read(struct ulpi_ops *ops, u8 addr)
{
struct dwc3 *dwc = dev_get_drvdata(ops->dev);
u32 reg;
int ret;
reg = DWC3_GUSB2PHYACC_NEWREGREQ | DWC3_ULPI_ADDR(addr);
dwc3_writel(dwc->regs, DWC3_GUSB2PHYACC(0), reg);
ret = dwc3_ulpi_busyloop(dwc);
if (ret)
return ret;
reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYACC(0));
return DWC3_GUSB2PHYACC_DATA(reg);
}
static int dwc3_ulpi_write(struct ulpi_ops *ops, u8 addr, u8 val)
{
struct dwc3 *dwc = dev_get_drvdata(ops->dev);
u32 reg;
reg = DWC3_GUSB2PHYACC_NEWREGREQ | DWC3_ULPI_ADDR(addr);
reg |= DWC3_GUSB2PHYACC_WRITE | val;
dwc3_writel(dwc->regs, DWC3_GUSB2PHYACC(0), reg);
return dwc3_ulpi_busyloop(dwc);
}
static struct ulpi_ops dwc3_ulpi_ops = {
.read = dwc3_ulpi_read,
.write = dwc3_ulpi_write,
};
int dwc3_ulpi_init(struct dwc3 *dwc)
{
/* Register the interface */
dwc->ulpi = ulpi_register_interface(dwc->dev, &dwc3_ulpi_ops);
if (IS_ERR(dwc->ulpi)) {
dev_err(dwc->dev, "failed to register ULPI interface");
return PTR_ERR(dwc->ulpi);
}
return 0;
}
void dwc3_ulpi_exit(struct dwc3 *dwc)
{
if (dwc->ulpi) {
ulpi_unregister_interface(dwc->ulpi);
dwc->ulpi = NULL;
}
}
| gpl-2.0 |
MikeC84/mac_kernel_htc_flounder | drivers/watchdog/da9055_wdt.c | 2250 | 5235 | /*
* System monitoring driver for DA9055 PMICs.
*
* Copyright(c) 2012 Dialog Semiconductor Ltd.
*
* Author: David Dajun Chen <dchen@diasemi.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/watchdog.h>
#include <linux/delay.h>
#include <linux/mfd/da9055/core.h>
#include <linux/mfd/da9055/reg.h>
static bool nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout,
"Watchdog cannot be stopped once started (default="
__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
#define DA9055_DEF_TIMEOUT 4
#define DA9055_TWDMIN 256
struct da9055_wdt_data {
struct watchdog_device wdt;
struct da9055 *da9055;
struct kref kref;
};
static const struct {
u8 reg_val;
int user_time; /* In seconds */
} da9055_wdt_maps[] = {
{ 0, 0 },
{ 1, 2 },
{ 2, 4 },
{ 3, 8 },
{ 4, 16 },
{ 5, 32 },
{ 5, 33 }, /* Actual time 32.768s so included both 32s and 33s */
{ 6, 65 },
{ 6, 66 }, /* Actual time 65.536s so include both, 65s and 66s */
{ 7, 131 },
};
static int da9055_wdt_set_timeout(struct watchdog_device *wdt_dev,
unsigned int timeout)
{
struct da9055_wdt_data *driver_data = watchdog_get_drvdata(wdt_dev);
struct da9055 *da9055 = driver_data->da9055;
int ret, i;
for (i = 0; i < ARRAY_SIZE(da9055_wdt_maps); i++)
if (da9055_wdt_maps[i].user_time == timeout)
break;
if (i == ARRAY_SIZE(da9055_wdt_maps))
ret = -EINVAL;
else
ret = da9055_reg_update(da9055, DA9055_REG_CONTROL_B,
DA9055_TWDSCALE_MASK,
da9055_wdt_maps[i].reg_val <<
DA9055_TWDSCALE_SHIFT);
if (ret < 0) {
dev_err(da9055->dev,
"Failed to update timescale bit, %d\n", ret);
return ret;
}
wdt_dev->timeout = timeout;
return 0;
}
static int da9055_wdt_ping(struct watchdog_device *wdt_dev)
{
struct da9055_wdt_data *driver_data = watchdog_get_drvdata(wdt_dev);
struct da9055 *da9055 = driver_data->da9055;
/*
* We have a minimum time for watchdog window called TWDMIN. A write
* to the watchdog before this elapsed time will cause an error.
*/
mdelay(DA9055_TWDMIN);
/* Reset the watchdog timer */
return da9055_reg_update(da9055, DA9055_REG_CONTROL_E,
DA9055_WATCHDOG_MASK, 1);
}
static void da9055_wdt_release_resources(struct kref *r)
{
}
static void da9055_wdt_ref(struct watchdog_device *wdt_dev)
{
struct da9055_wdt_data *driver_data = watchdog_get_drvdata(wdt_dev);
kref_get(&driver_data->kref);
}
static void da9055_wdt_unref(struct watchdog_device *wdt_dev)
{
struct da9055_wdt_data *driver_data = watchdog_get_drvdata(wdt_dev);
kref_put(&driver_data->kref, da9055_wdt_release_resources);
}
static int da9055_wdt_start(struct watchdog_device *wdt_dev)
{
return da9055_wdt_set_timeout(wdt_dev, wdt_dev->timeout);
}
static int da9055_wdt_stop(struct watchdog_device *wdt_dev)
{
return da9055_wdt_set_timeout(wdt_dev, 0);
}
static struct watchdog_info da9055_wdt_info = {
.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING,
.identity = "DA9055 Watchdog",
};
static const struct watchdog_ops da9055_wdt_ops = {
.owner = THIS_MODULE,
.start = da9055_wdt_start,
.stop = da9055_wdt_stop,
.ping = da9055_wdt_ping,
.set_timeout = da9055_wdt_set_timeout,
.ref = da9055_wdt_ref,
.unref = da9055_wdt_unref,
};
static int da9055_wdt_probe(struct platform_device *pdev)
{
struct da9055 *da9055 = dev_get_drvdata(pdev->dev.parent);
struct da9055_wdt_data *driver_data;
struct watchdog_device *da9055_wdt;
int ret;
driver_data = devm_kzalloc(&pdev->dev, sizeof(*driver_data),
GFP_KERNEL);
if (!driver_data) {
dev_err(da9055->dev, "Failed to allocate watchdog device\n");
return -ENOMEM;
}
driver_data->da9055 = da9055;
da9055_wdt = &driver_data->wdt;
da9055_wdt->timeout = DA9055_DEF_TIMEOUT;
da9055_wdt->info = &da9055_wdt_info;
da9055_wdt->ops = &da9055_wdt_ops;
watchdog_set_nowayout(da9055_wdt, nowayout);
watchdog_set_drvdata(da9055_wdt, driver_data);
kref_init(&driver_data->kref);
ret = da9055_wdt_stop(da9055_wdt);
if (ret < 0) {
dev_err(&pdev->dev, "Failed to stop watchdog, %d\n", ret);
goto err;
}
dev_set_drvdata(&pdev->dev, driver_data);
ret = watchdog_register_device(&driver_data->wdt);
if (ret != 0)
dev_err(da9055->dev, "watchdog_register_device() failed: %d\n",
ret);
err:
return ret;
}
static int da9055_wdt_remove(struct platform_device *pdev)
{
struct da9055_wdt_data *driver_data = dev_get_drvdata(&pdev->dev);
watchdog_unregister_device(&driver_data->wdt);
kref_put(&driver_data->kref, da9055_wdt_release_resources);
return 0;
}
static struct platform_driver da9055_wdt_driver = {
.probe = da9055_wdt_probe,
.remove = da9055_wdt_remove,
.driver = {
.name = "da9055-watchdog",
},
};
module_platform_driver(da9055_wdt_driver);
MODULE_AUTHOR("David Dajun Chen <dchen@diasemi.com>");
MODULE_DESCRIPTION("DA9055 watchdog");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:da9055-watchdog");
| gpl-2.0 |
mus1711/nitro_kernel | drivers/video/omap2/dss/dispc-compat.c | 2250 | 15595 | /*
* Copyright (C) 2012 Texas Instruments
* Author: Tomi Valkeinen <tomi.valkeinen@ti.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define DSS_SUBSYS_NAME "APPLY"
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/jiffies.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/seq_file.h>
#include <video/omapdss.h>
#include "dss.h"
#include "dss_features.h"
#include "dispc-compat.h"
#define DISPC_IRQ_MASK_ERROR (DISPC_IRQ_GFX_FIFO_UNDERFLOW | \
DISPC_IRQ_OCP_ERR | \
DISPC_IRQ_VID1_FIFO_UNDERFLOW | \
DISPC_IRQ_VID2_FIFO_UNDERFLOW | \
DISPC_IRQ_SYNC_LOST | \
DISPC_IRQ_SYNC_LOST_DIGIT)
#define DISPC_MAX_NR_ISRS 8
struct omap_dispc_isr_data {
omap_dispc_isr_t isr;
void *arg;
u32 mask;
};
struct dispc_irq_stats {
unsigned long last_reset;
unsigned irq_count;
unsigned irqs[32];
};
static struct {
spinlock_t irq_lock;
u32 irq_error_mask;
struct omap_dispc_isr_data registered_isr[DISPC_MAX_NR_ISRS];
u32 error_irqs;
struct work_struct error_work;
#ifdef CONFIG_OMAP2_DSS_COLLECT_IRQ_STATS
spinlock_t irq_stats_lock;
struct dispc_irq_stats irq_stats;
#endif
} dispc_compat;
#ifdef CONFIG_OMAP2_DSS_COLLECT_IRQ_STATS
static void dispc_dump_irqs(struct seq_file *s)
{
unsigned long flags;
struct dispc_irq_stats stats;
spin_lock_irqsave(&dispc_compat.irq_stats_lock, flags);
stats = dispc_compat.irq_stats;
memset(&dispc_compat.irq_stats, 0, sizeof(dispc_compat.irq_stats));
dispc_compat.irq_stats.last_reset = jiffies;
spin_unlock_irqrestore(&dispc_compat.irq_stats_lock, flags);
seq_printf(s, "period %u ms\n",
jiffies_to_msecs(jiffies - stats.last_reset));
seq_printf(s, "irqs %d\n", stats.irq_count);
#define PIS(x) \
seq_printf(s, "%-20s %10d\n", #x, stats.irqs[ffs(DISPC_IRQ_##x)-1]);
PIS(FRAMEDONE);
PIS(VSYNC);
PIS(EVSYNC_EVEN);
PIS(EVSYNC_ODD);
PIS(ACBIAS_COUNT_STAT);
PIS(PROG_LINE_NUM);
PIS(GFX_FIFO_UNDERFLOW);
PIS(GFX_END_WIN);
PIS(PAL_GAMMA_MASK);
PIS(OCP_ERR);
PIS(VID1_FIFO_UNDERFLOW);
PIS(VID1_END_WIN);
PIS(VID2_FIFO_UNDERFLOW);
PIS(VID2_END_WIN);
if (dss_feat_get_num_ovls() > 3) {
PIS(VID3_FIFO_UNDERFLOW);
PIS(VID3_END_WIN);
}
PIS(SYNC_LOST);
PIS(SYNC_LOST_DIGIT);
PIS(WAKEUP);
if (dss_has_feature(FEAT_MGR_LCD2)) {
PIS(FRAMEDONE2);
PIS(VSYNC2);
PIS(ACBIAS_COUNT_STAT2);
PIS(SYNC_LOST2);
}
if (dss_has_feature(FEAT_MGR_LCD3)) {
PIS(FRAMEDONE3);
PIS(VSYNC3);
PIS(ACBIAS_COUNT_STAT3);
PIS(SYNC_LOST3);
}
#undef PIS
}
#endif
/* dispc.irq_lock has to be locked by the caller */
static void _omap_dispc_set_irqs(void)
{
u32 mask;
int i;
struct omap_dispc_isr_data *isr_data;
mask = dispc_compat.irq_error_mask;
for (i = 0; i < DISPC_MAX_NR_ISRS; i++) {
isr_data = &dispc_compat.registered_isr[i];
if (isr_data->isr == NULL)
continue;
mask |= isr_data->mask;
}
dispc_write_irqenable(mask);
}
int omap_dispc_register_isr(omap_dispc_isr_t isr, void *arg, u32 mask)
{
int i;
int ret;
unsigned long flags;
struct omap_dispc_isr_data *isr_data;
if (isr == NULL)
return -EINVAL;
spin_lock_irqsave(&dispc_compat.irq_lock, flags);
/* check for duplicate entry */
for (i = 0; i < DISPC_MAX_NR_ISRS; i++) {
isr_data = &dispc_compat.registered_isr[i];
if (isr_data->isr == isr && isr_data->arg == arg &&
isr_data->mask == mask) {
ret = -EINVAL;
goto err;
}
}
isr_data = NULL;
ret = -EBUSY;
for (i = 0; i < DISPC_MAX_NR_ISRS; i++) {
isr_data = &dispc_compat.registered_isr[i];
if (isr_data->isr != NULL)
continue;
isr_data->isr = isr;
isr_data->arg = arg;
isr_data->mask = mask;
ret = 0;
break;
}
if (ret)
goto err;
_omap_dispc_set_irqs();
spin_unlock_irqrestore(&dispc_compat.irq_lock, flags);
return 0;
err:
spin_unlock_irqrestore(&dispc_compat.irq_lock, flags);
return ret;
}
EXPORT_SYMBOL(omap_dispc_register_isr);
int omap_dispc_unregister_isr(omap_dispc_isr_t isr, void *arg, u32 mask)
{
int i;
unsigned long flags;
int ret = -EINVAL;
struct omap_dispc_isr_data *isr_data;
spin_lock_irqsave(&dispc_compat.irq_lock, flags);
for (i = 0; i < DISPC_MAX_NR_ISRS; i++) {
isr_data = &dispc_compat.registered_isr[i];
if (isr_data->isr != isr || isr_data->arg != arg ||
isr_data->mask != mask)
continue;
/* found the correct isr */
isr_data->isr = NULL;
isr_data->arg = NULL;
isr_data->mask = 0;
ret = 0;
break;
}
if (ret == 0)
_omap_dispc_set_irqs();
spin_unlock_irqrestore(&dispc_compat.irq_lock, flags);
return ret;
}
EXPORT_SYMBOL(omap_dispc_unregister_isr);
static void print_irq_status(u32 status)
{
if ((status & dispc_compat.irq_error_mask) == 0)
return;
#define PIS(x) (status & DISPC_IRQ_##x) ? (#x " ") : ""
pr_debug("DISPC IRQ: 0x%x: %s%s%s%s%s%s%s%s%s\n",
status,
PIS(OCP_ERR),
PIS(GFX_FIFO_UNDERFLOW),
PIS(VID1_FIFO_UNDERFLOW),
PIS(VID2_FIFO_UNDERFLOW),
dss_feat_get_num_ovls() > 3 ? PIS(VID3_FIFO_UNDERFLOW) : "",
PIS(SYNC_LOST),
PIS(SYNC_LOST_DIGIT),
dss_has_feature(FEAT_MGR_LCD2) ? PIS(SYNC_LOST2) : "",
dss_has_feature(FEAT_MGR_LCD3) ? PIS(SYNC_LOST3) : "");
#undef PIS
}
/* Called from dss.c. Note that we don't touch clocks here,
* but we presume they are on because we got an IRQ. However,
* an irq handler may turn the clocks off, so we may not have
* clock later in the function. */
static irqreturn_t omap_dispc_irq_handler(int irq, void *arg)
{
int i;
u32 irqstatus, irqenable;
u32 handledirqs = 0;
u32 unhandled_errors;
struct omap_dispc_isr_data *isr_data;
struct omap_dispc_isr_data registered_isr[DISPC_MAX_NR_ISRS];
spin_lock(&dispc_compat.irq_lock);
irqstatus = dispc_read_irqstatus();
irqenable = dispc_read_irqenable();
/* IRQ is not for us */
if (!(irqstatus & irqenable)) {
spin_unlock(&dispc_compat.irq_lock);
return IRQ_NONE;
}
#ifdef CONFIG_OMAP2_DSS_COLLECT_IRQ_STATS
spin_lock(&dispc_compat.irq_stats_lock);
dispc_compat.irq_stats.irq_count++;
dss_collect_irq_stats(irqstatus, dispc_compat.irq_stats.irqs);
spin_unlock(&dispc_compat.irq_stats_lock);
#endif
print_irq_status(irqstatus);
/* Ack the interrupt. Do it here before clocks are possibly turned
* off */
dispc_clear_irqstatus(irqstatus);
/* flush posted write */
dispc_read_irqstatus();
/* make a copy and unlock, so that isrs can unregister
* themselves */
memcpy(registered_isr, dispc_compat.registered_isr,
sizeof(registered_isr));
spin_unlock(&dispc_compat.irq_lock);
for (i = 0; i < DISPC_MAX_NR_ISRS; i++) {
isr_data = ®istered_isr[i];
if (!isr_data->isr)
continue;
if (isr_data->mask & irqstatus) {
isr_data->isr(isr_data->arg, irqstatus);
handledirqs |= isr_data->mask;
}
}
spin_lock(&dispc_compat.irq_lock);
unhandled_errors = irqstatus & ~handledirqs & dispc_compat.irq_error_mask;
if (unhandled_errors) {
dispc_compat.error_irqs |= unhandled_errors;
dispc_compat.irq_error_mask &= ~unhandled_errors;
_omap_dispc_set_irqs();
schedule_work(&dispc_compat.error_work);
}
spin_unlock(&dispc_compat.irq_lock);
return IRQ_HANDLED;
}
static void dispc_error_worker(struct work_struct *work)
{
int i;
u32 errors;
unsigned long flags;
static const unsigned fifo_underflow_bits[] = {
DISPC_IRQ_GFX_FIFO_UNDERFLOW,
DISPC_IRQ_VID1_FIFO_UNDERFLOW,
DISPC_IRQ_VID2_FIFO_UNDERFLOW,
DISPC_IRQ_VID3_FIFO_UNDERFLOW,
};
spin_lock_irqsave(&dispc_compat.irq_lock, flags);
errors = dispc_compat.error_irqs;
dispc_compat.error_irqs = 0;
spin_unlock_irqrestore(&dispc_compat.irq_lock, flags);
dispc_runtime_get();
for (i = 0; i < omap_dss_get_num_overlays(); ++i) {
struct omap_overlay *ovl;
unsigned bit;
ovl = omap_dss_get_overlay(i);
bit = fifo_underflow_bits[i];
if (bit & errors) {
DSSERR("FIFO UNDERFLOW on %s, disabling the overlay\n",
ovl->name);
dispc_ovl_enable(ovl->id, false);
dispc_mgr_go(ovl->manager->id);
msleep(50);
}
}
for (i = 0; i < omap_dss_get_num_overlay_managers(); ++i) {
struct omap_overlay_manager *mgr;
unsigned bit;
mgr = omap_dss_get_overlay_manager(i);
bit = dispc_mgr_get_sync_lost_irq(i);
if (bit & errors) {
int j;
DSSERR("SYNC_LOST on channel %s, restarting the output "
"with video overlays disabled\n",
mgr->name);
dss_mgr_disable(mgr);
for (j = 0; j < omap_dss_get_num_overlays(); ++j) {
struct omap_overlay *ovl;
ovl = omap_dss_get_overlay(j);
if (ovl->id != OMAP_DSS_GFX &&
ovl->manager == mgr)
ovl->disable(ovl);
}
dss_mgr_enable(mgr);
}
}
if (errors & DISPC_IRQ_OCP_ERR) {
DSSERR("OCP_ERR\n");
for (i = 0; i < omap_dss_get_num_overlay_managers(); ++i) {
struct omap_overlay_manager *mgr;
mgr = omap_dss_get_overlay_manager(i);
dss_mgr_disable(mgr);
}
}
spin_lock_irqsave(&dispc_compat.irq_lock, flags);
dispc_compat.irq_error_mask |= errors;
_omap_dispc_set_irqs();
spin_unlock_irqrestore(&dispc_compat.irq_lock, flags);
dispc_runtime_put();
}
int dss_dispc_initialize_irq(void)
{
int r;
#ifdef CONFIG_OMAP2_DSS_COLLECT_IRQ_STATS
spin_lock_init(&dispc_compat.irq_stats_lock);
dispc_compat.irq_stats.last_reset = jiffies;
dss_debugfs_create_file("dispc_irq", dispc_dump_irqs);
#endif
spin_lock_init(&dispc_compat.irq_lock);
memset(dispc_compat.registered_isr, 0,
sizeof(dispc_compat.registered_isr));
dispc_compat.irq_error_mask = DISPC_IRQ_MASK_ERROR;
if (dss_has_feature(FEAT_MGR_LCD2))
dispc_compat.irq_error_mask |= DISPC_IRQ_SYNC_LOST2;
if (dss_has_feature(FEAT_MGR_LCD3))
dispc_compat.irq_error_mask |= DISPC_IRQ_SYNC_LOST3;
if (dss_feat_get_num_ovls() > 3)
dispc_compat.irq_error_mask |= DISPC_IRQ_VID3_FIFO_UNDERFLOW;
/*
* there's SYNC_LOST_DIGIT waiting after enabling the DSS,
* so clear it
*/
dispc_clear_irqstatus(dispc_read_irqstatus());
INIT_WORK(&dispc_compat.error_work, dispc_error_worker);
_omap_dispc_set_irqs();
r = dispc_request_irq(omap_dispc_irq_handler, &dispc_compat);
if (r) {
DSSERR("dispc_request_irq failed\n");
return r;
}
return 0;
}
void dss_dispc_uninitialize_irq(void)
{
dispc_free_irq(&dispc_compat);
}
static void dispc_mgr_disable_isr(void *data, u32 mask)
{
struct completion *compl = data;
complete(compl);
}
static void dispc_mgr_enable_lcd_out(enum omap_channel channel)
{
dispc_mgr_enable(channel, true);
}
static void dispc_mgr_disable_lcd_out(enum omap_channel channel)
{
DECLARE_COMPLETION_ONSTACK(framedone_compl);
int r;
u32 irq;
if (dispc_mgr_is_enabled(channel) == false)
return;
/*
* When we disable LCD output, we need to wait for FRAMEDONE to know
* that DISPC has finished with the LCD output.
*/
irq = dispc_mgr_get_framedone_irq(channel);
r = omap_dispc_register_isr(dispc_mgr_disable_isr, &framedone_compl,
irq);
if (r)
DSSERR("failed to register FRAMEDONE isr\n");
dispc_mgr_enable(channel, false);
/* if we couldn't register for framedone, just sleep and exit */
if (r) {
msleep(100);
return;
}
if (!wait_for_completion_timeout(&framedone_compl,
msecs_to_jiffies(100)))
DSSERR("timeout waiting for FRAME DONE\n");
r = omap_dispc_unregister_isr(dispc_mgr_disable_isr, &framedone_compl,
irq);
if (r)
DSSERR("failed to unregister FRAMEDONE isr\n");
}
static void dispc_digit_out_enable_isr(void *data, u32 mask)
{
struct completion *compl = data;
/* ignore any sync lost interrupts */
if (mask & (DISPC_IRQ_EVSYNC_EVEN | DISPC_IRQ_EVSYNC_ODD))
complete(compl);
}
static void dispc_mgr_enable_digit_out(void)
{
DECLARE_COMPLETION_ONSTACK(vsync_compl);
int r;
u32 irq_mask;
if (dispc_mgr_is_enabled(OMAP_DSS_CHANNEL_DIGIT) == true)
return;
/*
* Digit output produces some sync lost interrupts during the first
* frame when enabling. Those need to be ignored, so we register for the
* sync lost irq to prevent the error handler from triggering.
*/
irq_mask = dispc_mgr_get_vsync_irq(OMAP_DSS_CHANNEL_DIGIT) |
dispc_mgr_get_sync_lost_irq(OMAP_DSS_CHANNEL_DIGIT);
r = omap_dispc_register_isr(dispc_digit_out_enable_isr, &vsync_compl,
irq_mask);
if (r) {
DSSERR("failed to register %x isr\n", irq_mask);
return;
}
dispc_mgr_enable(OMAP_DSS_CHANNEL_DIGIT, true);
/* wait for the first evsync */
if (!wait_for_completion_timeout(&vsync_compl, msecs_to_jiffies(100)))
DSSERR("timeout waiting for digit out to start\n");
r = omap_dispc_unregister_isr(dispc_digit_out_enable_isr, &vsync_compl,
irq_mask);
if (r)
DSSERR("failed to unregister %x isr\n", irq_mask);
}
static void dispc_mgr_disable_digit_out(void)
{
DECLARE_COMPLETION_ONSTACK(framedone_compl);
int r, i;
u32 irq_mask;
int num_irqs;
if (dispc_mgr_is_enabled(OMAP_DSS_CHANNEL_DIGIT) == false)
return;
/*
* When we disable the digit output, we need to wait for FRAMEDONE to
* know that DISPC has finished with the output.
*/
irq_mask = dispc_mgr_get_framedone_irq(OMAP_DSS_CHANNEL_DIGIT);
num_irqs = 1;
if (!irq_mask) {
/*
* omap 2/3 don't have framedone irq for TV, so we need to use
* vsyncs for this.
*/
irq_mask = dispc_mgr_get_vsync_irq(OMAP_DSS_CHANNEL_DIGIT);
/*
* We need to wait for both even and odd vsyncs. Note that this
* is not totally reliable, as we could get a vsync interrupt
* before we disable the output, which leads to timeout in the
* wait_for_completion.
*/
num_irqs = 2;
}
r = omap_dispc_register_isr(dispc_mgr_disable_isr, &framedone_compl,
irq_mask);
if (r)
DSSERR("failed to register %x isr\n", irq_mask);
dispc_mgr_enable(OMAP_DSS_CHANNEL_DIGIT, false);
/* if we couldn't register the irq, just sleep and exit */
if (r) {
msleep(100);
return;
}
for (i = 0; i < num_irqs; ++i) {
if (!wait_for_completion_timeout(&framedone_compl,
msecs_to_jiffies(100)))
DSSERR("timeout waiting for digit out to stop\n");
}
r = omap_dispc_unregister_isr(dispc_mgr_disable_isr, &framedone_compl,
irq_mask);
if (r)
DSSERR("failed to unregister %x isr\n", irq_mask);
}
void dispc_mgr_enable_sync(enum omap_channel channel)
{
if (dss_mgr_is_lcd(channel))
dispc_mgr_enable_lcd_out(channel);
else if (channel == OMAP_DSS_CHANNEL_DIGIT)
dispc_mgr_enable_digit_out();
else
WARN_ON(1);
}
void dispc_mgr_disable_sync(enum omap_channel channel)
{
if (dss_mgr_is_lcd(channel))
dispc_mgr_disable_lcd_out(channel);
else if (channel == OMAP_DSS_CHANNEL_DIGIT)
dispc_mgr_disable_digit_out();
else
WARN_ON(1);
}
int omap_dispc_wait_for_irq_interruptible_timeout(u32 irqmask,
unsigned long timeout)
{
void dispc_irq_wait_handler(void *data, u32 mask)
{
complete((struct completion *)data);
}
int r;
DECLARE_COMPLETION_ONSTACK(completion);
r = omap_dispc_register_isr(dispc_irq_wait_handler, &completion,
irqmask);
if (r)
return r;
timeout = wait_for_completion_interruptible_timeout(&completion,
timeout);
omap_dispc_unregister_isr(dispc_irq_wait_handler, &completion, irqmask);
if (timeout == 0)
return -ETIMEDOUT;
if (timeout == -ERESTARTSYS)
return -ERESTARTSYS;
return 0;
}
| gpl-2.0 |
Silentlys/android_kernel_xiaomi_redmi2 | arch/sh/kernel/cpu/sh4a/setup-sh7780.c | 2506 | 16271 | /*
* SH7780 Setup
*
* Copyright (C) 2006 Paul Mundt
*
* 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/platform_device.h>
#include <linux/init.h>
#include <linux/serial.h>
#include <linux/io.h>
#include <linux/serial_sci.h>
#include <linux/sh_dma.h>
#include <linux/sh_timer.h>
#include <linux/sh_intc.h>
#include <cpu/dma-register.h>
static struct plat_sci_port scif0_platform_data = {
.mapbase = 0xffe00000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE | SCSCR_REIE | SCSCR_CKE1,
.scbrr_algo_id = SCBRR_ALGO_1,
.type = PORT_SCIF,
.irqs = SCIx_IRQ_MUXED(evt2irq(0x700)),
.regtype = SCIx_SH4_SCIF_FIFODATA_REGTYPE,
};
static struct platform_device scif0_device = {
.name = "sh-sci",
.id = 0,
.dev = {
.platform_data = &scif0_platform_data,
},
};
static struct plat_sci_port scif1_platform_data = {
.mapbase = 0xffe10000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE | SCSCR_REIE | SCSCR_CKE1,
.scbrr_algo_id = SCBRR_ALGO_1,
.type = PORT_SCIF,
.irqs = SCIx_IRQ_MUXED(evt2irq(0xb80)),
.regtype = SCIx_SH4_SCIF_FIFODATA_REGTYPE,
};
static struct platform_device scif1_device = {
.name = "sh-sci",
.id = 1,
.dev = {
.platform_data = &scif1_platform_data,
},
};
static struct sh_timer_config tmu0_platform_data = {
.channel_offset = 0x04,
.timer_bit = 0,
.clockevent_rating = 200,
};
static struct resource tmu0_resources[] = {
[0] = {
.start = 0xffd80008,
.end = 0xffd80013,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x580),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu0_device = {
.name = "sh_tmu",
.id = 0,
.dev = {
.platform_data = &tmu0_platform_data,
},
.resource = tmu0_resources,
.num_resources = ARRAY_SIZE(tmu0_resources),
};
static struct sh_timer_config tmu1_platform_data = {
.channel_offset = 0x10,
.timer_bit = 1,
.clocksource_rating = 200,
};
static struct resource tmu1_resources[] = {
[0] = {
.start = 0xffd80014,
.end = 0xffd8001f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x5a0),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu1_device = {
.name = "sh_tmu",
.id = 1,
.dev = {
.platform_data = &tmu1_platform_data,
},
.resource = tmu1_resources,
.num_resources = ARRAY_SIZE(tmu1_resources),
};
static struct sh_timer_config tmu2_platform_data = {
.channel_offset = 0x1c,
.timer_bit = 2,
};
static struct resource tmu2_resources[] = {
[0] = {
.start = 0xffd80020,
.end = 0xffd8002f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x5c0),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu2_device = {
.name = "sh_tmu",
.id = 2,
.dev = {
.platform_data = &tmu2_platform_data,
},
.resource = tmu2_resources,
.num_resources = ARRAY_SIZE(tmu2_resources),
};
static struct sh_timer_config tmu3_platform_data = {
.channel_offset = 0x04,
.timer_bit = 0,
};
static struct resource tmu3_resources[] = {
[0] = {
.start = 0xffdc0008,
.end = 0xffdc0013,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0xe00),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu3_device = {
.name = "sh_tmu",
.id = 3,
.dev = {
.platform_data = &tmu3_platform_data,
},
.resource = tmu3_resources,
.num_resources = ARRAY_SIZE(tmu3_resources),
};
static struct sh_timer_config tmu4_platform_data = {
.channel_offset = 0x10,
.timer_bit = 1,
};
static struct resource tmu4_resources[] = {
[0] = {
.start = 0xffdc0014,
.end = 0xffdc001f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0xe20),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu4_device = {
.name = "sh_tmu",
.id = 4,
.dev = {
.platform_data = &tmu4_platform_data,
},
.resource = tmu4_resources,
.num_resources = ARRAY_SIZE(tmu4_resources),
};
static struct sh_timer_config tmu5_platform_data = {
.channel_offset = 0x1c,
.timer_bit = 2,
};
static struct resource tmu5_resources[] = {
[0] = {
.start = 0xffdc0020,
.end = 0xffdc002b,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0xe40),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu5_device = {
.name = "sh_tmu",
.id = 5,
.dev = {
.platform_data = &tmu5_platform_data,
},
.resource = tmu5_resources,
.num_resources = ARRAY_SIZE(tmu5_resources),
};
static struct resource rtc_resources[] = {
[0] = {
.start = 0xffe80000,
.end = 0xffe80000 + 0x58 - 1,
.flags = IORESOURCE_IO,
},
[1] = {
/* Shared Period/Carry/Alarm IRQ */
.start = evt2irq(0x480),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device rtc_device = {
.name = "sh-rtc",
.id = -1,
.num_resources = ARRAY_SIZE(rtc_resources),
.resource = rtc_resources,
};
/* DMA */
static const struct sh_dmae_channel sh7780_dmae0_channels[] = {
{
.offset = 0,
.dmars = 0,
.dmars_bit = 0,
}, {
.offset = 0x10,
.dmars = 0,
.dmars_bit = 8,
}, {
.offset = 0x20,
.dmars = 4,
.dmars_bit = 0,
}, {
.offset = 0x30,
.dmars = 4,
.dmars_bit = 8,
}, {
.offset = 0x50,
.dmars = 8,
.dmars_bit = 0,
}, {
.offset = 0x60,
.dmars = 8,
.dmars_bit = 8,
}
};
static const struct sh_dmae_channel sh7780_dmae1_channels[] = {
{
.offset = 0,
}, {
.offset = 0x10,
}, {
.offset = 0x20,
}, {
.offset = 0x30,
}, {
.offset = 0x50,
}, {
.offset = 0x60,
}
};
static const unsigned int ts_shift[] = TS_SHIFT;
static struct sh_dmae_pdata dma0_platform_data = {
.channel = sh7780_dmae0_channels,
.channel_num = ARRAY_SIZE(sh7780_dmae0_channels),
.ts_low_shift = CHCR_TS_LOW_SHIFT,
.ts_low_mask = CHCR_TS_LOW_MASK,
.ts_high_shift = CHCR_TS_HIGH_SHIFT,
.ts_high_mask = CHCR_TS_HIGH_MASK,
.ts_shift = ts_shift,
.ts_shift_num = ARRAY_SIZE(ts_shift),
.dmaor_init = DMAOR_INIT,
};
static struct sh_dmae_pdata dma1_platform_data = {
.channel = sh7780_dmae1_channels,
.channel_num = ARRAY_SIZE(sh7780_dmae1_channels),
.ts_low_shift = CHCR_TS_LOW_SHIFT,
.ts_low_mask = CHCR_TS_LOW_MASK,
.ts_high_shift = CHCR_TS_HIGH_SHIFT,
.ts_high_mask = CHCR_TS_HIGH_MASK,
.ts_shift = ts_shift,
.ts_shift_num = ARRAY_SIZE(ts_shift),
.dmaor_init = DMAOR_INIT,
};
static struct resource sh7780_dmae0_resources[] = {
[0] = {
/* Channel registers and DMAOR */
.start = 0xfc808020,
.end = 0xfc80808f,
.flags = IORESOURCE_MEM,
},
[1] = {
/* DMARSx */
.start = 0xfc809000,
.end = 0xfc80900b,
.flags = IORESOURCE_MEM,
},
{
/*
* Real DMA error vector is 0x6c0, and channel
* vectors are 0x640-0x6a0, 0x780-0x7a0
*/
.name = "error_irq",
.start = evt2irq(0x640),
.end = evt2irq(0x640),
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_SHAREABLE,
},
};
static struct resource sh7780_dmae1_resources[] = {
[0] = {
/* Channel registers and DMAOR */
.start = 0xfc818020,
.end = 0xfc81808f,
.flags = IORESOURCE_MEM,
},
/* DMAC1 has no DMARS */
{
/*
* Real DMA error vector is 0x6c0, and channel
* vectors are 0x7c0-0x7e0, 0xd80-0xde0
*/
.name = "error_irq",
.start = evt2irq(0x7c0),
.end = evt2irq(0x7c0),
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_SHAREABLE,
},
};
static struct platform_device dma0_device = {
.name = "sh-dma-engine",
.id = 0,
.resource = sh7780_dmae0_resources,
.num_resources = ARRAY_SIZE(sh7780_dmae0_resources),
.dev = {
.platform_data = &dma0_platform_data,
},
};
static struct platform_device dma1_device = {
.name = "sh-dma-engine",
.id = 1,
.resource = sh7780_dmae1_resources,
.num_resources = ARRAY_SIZE(sh7780_dmae1_resources),
.dev = {
.platform_data = &dma1_platform_data,
},
};
static struct platform_device *sh7780_devices[] __initdata = {
&scif0_device,
&scif1_device,
&tmu0_device,
&tmu1_device,
&tmu2_device,
&tmu3_device,
&tmu4_device,
&tmu5_device,
&rtc_device,
&dma0_device,
&dma1_device,
};
static int __init sh7780_devices_setup(void)
{
return platform_add_devices(sh7780_devices,
ARRAY_SIZE(sh7780_devices));
}
arch_initcall(sh7780_devices_setup);
static struct platform_device *sh7780_early_devices[] __initdata = {
&scif0_device,
&scif1_device,
&tmu0_device,
&tmu1_device,
&tmu2_device,
&tmu3_device,
&tmu4_device,
&tmu5_device,
};
void __init plat_early_device_setup(void)
{
if (mach_is_sh2007()) {
scif0_platform_data.scscr &= ~SCSCR_CKE1;
scif0_platform_data.scbrr_algo_id = SCBRR_ALGO_2;
scif1_platform_data.scscr &= ~SCSCR_CKE1;
scif1_platform_data.scbrr_algo_id = SCBRR_ALGO_2;
}
early_platform_add_devices(sh7780_early_devices,
ARRAY_SIZE(sh7780_early_devices));
}
enum {
UNUSED = 0,
/* interrupt sources */
IRL_LLLL, IRL_LLLH, IRL_LLHL, IRL_LLHH,
IRL_LHLL, IRL_LHLH, IRL_LHHL, IRL_LHHH,
IRL_HLLL, IRL_HLLH, IRL_HLHL, IRL_HLHH,
IRL_HHLL, IRL_HHLH, IRL_HHHL,
IRQ0, IRQ1, IRQ2, IRQ3, IRQ4, IRQ5, IRQ6, IRQ7,
RTC, WDT, TMU0, TMU1, TMU2, TMU2_TICPI,
HUDI, DMAC0, SCIF0, DMAC1, CMT, HAC,
PCISERR, PCIINTA, PCIINTB, PCIINTC, PCIINTD, PCIC5,
SCIF1, SIOF, HSPI, MMCIF, TMU3, TMU4, TMU5, SSI, FLCTL, GPIO,
/* interrupt groups */
TMU012, TMU345,
};
static struct intc_vect vectors[] __initdata = {
INTC_VECT(RTC, 0x480), INTC_VECT(RTC, 0x4a0),
INTC_VECT(RTC, 0x4c0),
INTC_VECT(WDT, 0x560),
INTC_VECT(TMU0, 0x580), INTC_VECT(TMU1, 0x5a0),
INTC_VECT(TMU2, 0x5c0), INTC_VECT(TMU2_TICPI, 0x5e0),
INTC_VECT(HUDI, 0x600),
INTC_VECT(DMAC0, 0x640), INTC_VECT(DMAC0, 0x660),
INTC_VECT(DMAC0, 0x680), INTC_VECT(DMAC0, 0x6a0),
INTC_VECT(DMAC0, 0x6c0),
INTC_VECT(SCIF0, 0x700), INTC_VECT(SCIF0, 0x720),
INTC_VECT(SCIF0, 0x740), INTC_VECT(SCIF0, 0x760),
INTC_VECT(DMAC0, 0x780), INTC_VECT(DMAC0, 0x7a0),
INTC_VECT(DMAC1, 0x7c0), INTC_VECT(DMAC1, 0x7e0),
INTC_VECT(CMT, 0x900), INTC_VECT(HAC, 0x980),
INTC_VECT(PCISERR, 0xa00), INTC_VECT(PCIINTA, 0xa20),
INTC_VECT(PCIINTB, 0xa40), INTC_VECT(PCIINTC, 0xa60),
INTC_VECT(PCIINTD, 0xa80), INTC_VECT(PCIC5, 0xaa0),
INTC_VECT(PCIC5, 0xac0), INTC_VECT(PCIC5, 0xae0),
INTC_VECT(PCIC5, 0xb00), INTC_VECT(PCIC5, 0xb20),
INTC_VECT(SCIF1, 0xb80), INTC_VECT(SCIF1, 0xba0),
INTC_VECT(SCIF1, 0xbc0), INTC_VECT(SCIF1, 0xbe0),
INTC_VECT(SIOF, 0xc00), INTC_VECT(HSPI, 0xc80),
INTC_VECT(MMCIF, 0xd00), INTC_VECT(MMCIF, 0xd20),
INTC_VECT(MMCIF, 0xd40), INTC_VECT(MMCIF, 0xd60),
INTC_VECT(DMAC1, 0xd80), INTC_VECT(DMAC1, 0xda0),
INTC_VECT(DMAC1, 0xdc0), INTC_VECT(DMAC1, 0xde0),
INTC_VECT(TMU3, 0xe00), INTC_VECT(TMU4, 0xe20),
INTC_VECT(TMU5, 0xe40),
INTC_VECT(SSI, 0xe80),
INTC_VECT(FLCTL, 0xf00), INTC_VECT(FLCTL, 0xf20),
INTC_VECT(FLCTL, 0xf40), INTC_VECT(FLCTL, 0xf60),
INTC_VECT(GPIO, 0xf80), INTC_VECT(GPIO, 0xfa0),
INTC_VECT(GPIO, 0xfc0), INTC_VECT(GPIO, 0xfe0),
};
static struct intc_group groups[] __initdata = {
INTC_GROUP(TMU012, TMU0, TMU1, TMU2, TMU2_TICPI),
INTC_GROUP(TMU345, TMU3, TMU4, TMU5),
};
static struct intc_mask_reg mask_registers[] __initdata = {
{ 0xffd40038, 0xffd4003c, 32, /* INT2MSKR / INT2MSKCR */
{ 0, 0, 0, 0, 0, 0, GPIO, FLCTL,
SSI, MMCIF, HSPI, SIOF, PCIC5, PCIINTD, PCIINTC, PCIINTB,
PCIINTA, PCISERR, HAC, CMT, 0, 0, DMAC1, DMAC0,
HUDI, 0, WDT, SCIF1, SCIF0, RTC, TMU345, TMU012 } },
};
static struct intc_prio_reg prio_registers[] __initdata = {
{ 0xffd40000, 0, 32, 8, /* INT2PRI0 */ { TMU0, TMU1,
TMU2, TMU2_TICPI } },
{ 0xffd40004, 0, 32, 8, /* INT2PRI1 */ { TMU3, TMU4, TMU5, RTC } },
{ 0xffd40008, 0, 32, 8, /* INT2PRI2 */ { SCIF0, SCIF1, WDT } },
{ 0xffd4000c, 0, 32, 8, /* INT2PRI3 */ { HUDI, DMAC0, DMAC1 } },
{ 0xffd40010, 0, 32, 8, /* INT2PRI4 */ { CMT, HAC,
PCISERR, PCIINTA, } },
{ 0xffd40014, 0, 32, 8, /* INT2PRI5 */ { PCIINTB, PCIINTC,
PCIINTD, PCIC5 } },
{ 0xffd40018, 0, 32, 8, /* INT2PRI6 */ { SIOF, HSPI, MMCIF, SSI } },
{ 0xffd4001c, 0, 32, 8, /* INT2PRI7 */ { FLCTL, GPIO } },
};
static DECLARE_INTC_DESC(intc_desc, "sh7780", vectors, groups,
mask_registers, prio_registers, NULL);
/* Support for external interrupt pins in IRQ mode */
static struct intc_vect irq_vectors[] __initdata = {
INTC_VECT(IRQ0, 0x240), INTC_VECT(IRQ1, 0x280),
INTC_VECT(IRQ2, 0x2c0), INTC_VECT(IRQ3, 0x300),
INTC_VECT(IRQ4, 0x340), INTC_VECT(IRQ5, 0x380),
INTC_VECT(IRQ6, 0x3c0), INTC_VECT(IRQ7, 0x200),
};
static struct intc_mask_reg irq_mask_registers[] __initdata = {
{ 0xffd00044, 0xffd00064, 32, /* INTMSK0 / INTMSKCLR0 */
{ IRQ0, IRQ1, IRQ2, IRQ3, IRQ4, IRQ5, IRQ6, IRQ7 } },
};
static struct intc_prio_reg irq_prio_registers[] __initdata = {
{ 0xffd00010, 0, 32, 4, /* INTPRI */ { IRQ0, IRQ1, IRQ2, IRQ3,
IRQ4, IRQ5, IRQ6, IRQ7 } },
};
static struct intc_sense_reg irq_sense_registers[] __initdata = {
{ 0xffd0001c, 32, 2, /* ICR1 */ { IRQ0, IRQ1, IRQ2, IRQ3,
IRQ4, IRQ5, IRQ6, IRQ7 } },
};
static struct intc_mask_reg irq_ack_registers[] __initdata = {
{ 0xffd00024, 0, 32, /* INTREQ */
{ IRQ0, IRQ1, IRQ2, IRQ3, IRQ4, IRQ5, IRQ6, IRQ7 } },
};
static DECLARE_INTC_DESC_ACK(intc_irq_desc, "sh7780-irq", irq_vectors,
NULL, irq_mask_registers, irq_prio_registers,
irq_sense_registers, irq_ack_registers);
/* External interrupt pins in IRL mode */
static struct intc_vect irl_vectors[] __initdata = {
INTC_VECT(IRL_LLLL, 0x200), INTC_VECT(IRL_LLLH, 0x220),
INTC_VECT(IRL_LLHL, 0x240), INTC_VECT(IRL_LLHH, 0x260),
INTC_VECT(IRL_LHLL, 0x280), INTC_VECT(IRL_LHLH, 0x2a0),
INTC_VECT(IRL_LHHL, 0x2c0), INTC_VECT(IRL_LHHH, 0x2e0),
INTC_VECT(IRL_HLLL, 0x300), INTC_VECT(IRL_HLLH, 0x320),
INTC_VECT(IRL_HLHL, 0x340), INTC_VECT(IRL_HLHH, 0x360),
INTC_VECT(IRL_HHLL, 0x380), INTC_VECT(IRL_HHLH, 0x3a0),
INTC_VECT(IRL_HHHL, 0x3c0),
};
static struct intc_mask_reg irl3210_mask_registers[] __initdata = {
{ 0xffd40080, 0xffd40084, 32, /* INTMSK2 / INTMSKCLR2 */
{ IRL_LLLL, IRL_LLLH, IRL_LLHL, IRL_LLHH,
IRL_LHLL, IRL_LHLH, IRL_LHHL, IRL_LHHH,
IRL_HLLL, IRL_HLLH, IRL_HLHL, IRL_HLHH,
IRL_HHLL, IRL_HHLH, IRL_HHHL, } },
};
static struct intc_mask_reg irl7654_mask_registers[] __initdata = {
{ 0xffd40080, 0xffd40084, 32, /* INTMSK2 / INTMSKCLR2 */
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
IRL_LLLL, IRL_LLLH, IRL_LLHL, IRL_LLHH,
IRL_LHLL, IRL_LHLH, IRL_LHHL, IRL_LHHH,
IRL_HLLL, IRL_HLLH, IRL_HLHL, IRL_HLHH,
IRL_HHLL, IRL_HHLH, IRL_HHHL, } },
};
static DECLARE_INTC_DESC(intc_irl7654_desc, "sh7780-irl7654", irl_vectors,
NULL, irl7654_mask_registers, NULL, NULL);
static DECLARE_INTC_DESC(intc_irl3210_desc, "sh7780-irl3210", irl_vectors,
NULL, irl3210_mask_registers, NULL, NULL);
#define INTC_ICR0 0xffd00000
#define INTC_INTMSK0 0xffd00044
#define INTC_INTMSK1 0xffd00048
#define INTC_INTMSK2 0xffd40080
#define INTC_INTMSKCLR1 0xffd00068
#define INTC_INTMSKCLR2 0xffd40084
void __init plat_irq_setup(void)
{
/* disable IRQ7-0 */
__raw_writel(0xff000000, INTC_INTMSK0);
/* disable IRL3-0 + IRL7-4 */
__raw_writel(0xc0000000, INTC_INTMSK1);
__raw_writel(0xfffefffe, INTC_INTMSK2);
/* select IRL mode for IRL3-0 + IRL7-4 */
__raw_writel(__raw_readl(INTC_ICR0) & ~0x00c00000, INTC_ICR0);
/* disable holding function, ie enable "SH-4 Mode" */
__raw_writel(__raw_readl(INTC_ICR0) | 0x00200000, INTC_ICR0);
register_intc_controller(&intc_desc);
}
void __init plat_irq_setup_pins(int mode)
{
switch (mode) {
case IRQ_MODE_IRQ:
/* select IRQ mode for IRL3-0 + IRL7-4 */
__raw_writel(__raw_readl(INTC_ICR0) | 0x00c00000, INTC_ICR0);
register_intc_controller(&intc_irq_desc);
break;
case IRQ_MODE_IRL7654:
/* enable IRL7-4 but don't provide any masking */
__raw_writel(0x40000000, INTC_INTMSKCLR1);
__raw_writel(0x0000fffe, INTC_INTMSKCLR2);
break;
case IRQ_MODE_IRL3210:
/* enable IRL0-3 but don't provide any masking */
__raw_writel(0x80000000, INTC_INTMSKCLR1);
__raw_writel(0xfffe0000, INTC_INTMSKCLR2);
break;
case IRQ_MODE_IRL7654_MASK:
/* enable IRL7-4 and mask using cpu intc controller */
__raw_writel(0x40000000, INTC_INTMSKCLR1);
register_intc_controller(&intc_irl7654_desc);
break;
case IRQ_MODE_IRL3210_MASK:
/* enable IRL0-3 and mask using cpu intc controller */
__raw_writel(0x80000000, INTC_INTMSKCLR1);
register_intc_controller(&intc_irl3210_desc);
break;
default:
BUG();
}
}
| gpl-2.0 |
fledermaus/steamos_kernel | drivers/hwmon/ab8500.c | 2762 | 5471 | /*
* Copyright (C) ST-Ericsson 2010 - 2013
* Author: Martin Persson <martin.persson@stericsson.com>
* Hongbo Zhang <hongbo.zhang@linaro.org>
* License Terms: GNU General Public License v2
*
* When the AB8500 thermal warning temperature is reached (threshold cannot
* be changed by SW), an interrupt is set, and if no further action is taken
* within a certain time frame, pm_power off will be called.
*
* When AB8500 thermal shutdown temperature is reached a hardware shutdown of
* the AB8500 will occur.
*/
#include <linux/err.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/mfd/abx500.h>
#include <linux/mfd/abx500/ab8500-bm.h>
#include <linux/mfd/abx500/ab8500-gpadc.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/power/ab8500.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include "abx500.h"
#define DEFAULT_POWER_OFF_DELAY (HZ * 10)
#define THERMAL_VCC 1800
#define PULL_UP_RESISTOR 47000
/* Number of monitored sensors should not greater than NUM_SENSORS */
#define NUM_MONITORED_SENSORS 4
struct ab8500_gpadc_cfg {
const struct abx500_res_to_temp *temp_tbl;
int tbl_sz;
int vcc;
int r_up;
};
struct ab8500_temp {
struct ab8500_gpadc *gpadc;
struct ab8500_btemp *btemp;
struct delayed_work power_off_work;
struct ab8500_gpadc_cfg cfg;
struct abx500_temp *abx500_data;
};
/*
* The hardware connection is like this:
* VCC----[ R_up ]-----[ NTC ]----GND
* where R_up is pull-up resistance, and GPADC measures voltage on NTC.
* and res_to_temp table is strictly sorted by falling resistance values.
*/
static int ab8500_voltage_to_temp(struct ab8500_gpadc_cfg *cfg,
int v_ntc, int *temp)
{
int r_ntc, i = 0, tbl_sz = cfg->tbl_sz;
const struct abx500_res_to_temp *tbl = cfg->temp_tbl;
if (cfg->vcc < 0 || v_ntc >= cfg->vcc)
return -EINVAL;
r_ntc = v_ntc * cfg->r_up / (cfg->vcc - v_ntc);
if (r_ntc > tbl[0].resist || r_ntc < tbl[tbl_sz - 1].resist)
return -EINVAL;
while (!(r_ntc <= tbl[i].resist && r_ntc > tbl[i + 1].resist) &&
i < tbl_sz - 2)
i++;
/* return milli-Celsius */
*temp = tbl[i].temp * 1000 + ((tbl[i + 1].temp - tbl[i].temp) * 1000 *
(r_ntc - tbl[i].resist)) / (tbl[i + 1].resist - tbl[i].resist);
return 0;
}
static int ab8500_read_sensor(struct abx500_temp *data, u8 sensor, int *temp)
{
int voltage, ret;
struct ab8500_temp *ab8500_data = data->plat_data;
if (sensor == BAT_CTRL) {
*temp = ab8500_btemp_get_batctrl_temp(ab8500_data->btemp);
} else if (sensor == BTEMP_BALL) {
*temp = ab8500_btemp_get_temp(ab8500_data->btemp);
} else {
voltage = ab8500_gpadc_convert(ab8500_data->gpadc, sensor);
if (voltage < 0)
return voltage;
ret = ab8500_voltage_to_temp(&ab8500_data->cfg, voltage, temp);
if (ret < 0)
return ret;
}
return 0;
}
static void ab8500_thermal_power_off(struct work_struct *work)
{
struct ab8500_temp *ab8500_data = container_of(work,
struct ab8500_temp, power_off_work.work);
struct abx500_temp *abx500_data = ab8500_data->abx500_data;
dev_warn(&abx500_data->pdev->dev, "Power off due to critical temp\n");
pm_power_off();
}
static ssize_t ab8500_show_name(struct device *dev,
struct device_attribute *devattr, char *buf)
{
return sprintf(buf, "ab8500\n");
}
static ssize_t ab8500_show_label(struct device *dev,
struct device_attribute *devattr, char *buf)
{
char *label;
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
int index = attr->index;
switch (index) {
case 1:
label = "ext_adc1";
break;
case 2:
label = "ext_adc2";
break;
case 3:
label = "bat_temp";
break;
case 4:
label = "bat_ctrl";
break;
default:
return -EINVAL;
}
return sprintf(buf, "%s\n", label);
}
static int ab8500_temp_irq_handler(int irq, struct abx500_temp *data)
{
struct ab8500_temp *ab8500_data = data->plat_data;
dev_warn(&data->pdev->dev, "Power off in %d s\n",
DEFAULT_POWER_OFF_DELAY / HZ);
schedule_delayed_work(&ab8500_data->power_off_work,
DEFAULT_POWER_OFF_DELAY);
return 0;
}
int abx500_hwmon_init(struct abx500_temp *data)
{
struct ab8500_temp *ab8500_data;
ab8500_data = devm_kzalloc(&data->pdev->dev, sizeof(*ab8500_data),
GFP_KERNEL);
if (!ab8500_data)
return -ENOMEM;
ab8500_data->gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
if (IS_ERR(ab8500_data->gpadc))
return PTR_ERR(ab8500_data->gpadc);
ab8500_data->btemp = ab8500_btemp_get();
if (IS_ERR(ab8500_data->btemp))
return PTR_ERR(ab8500_data->btemp);
INIT_DELAYED_WORK(&ab8500_data->power_off_work,
ab8500_thermal_power_off);
ab8500_data->cfg.vcc = THERMAL_VCC;
ab8500_data->cfg.r_up = PULL_UP_RESISTOR;
ab8500_data->cfg.temp_tbl = ab8500_temp_tbl_a_thermistor;
ab8500_data->cfg.tbl_sz = ab8500_temp_tbl_a_size;
data->plat_data = ab8500_data;
/*
* ADC_AUX1 and ADC_AUX2, connected to external NTC
* BTEMP_BALL and BAT_CTRL, fixed usage
*/
data->gpadc_addr[0] = ADC_AUX1;
data->gpadc_addr[1] = ADC_AUX2;
data->gpadc_addr[2] = BTEMP_BALL;
data->gpadc_addr[3] = BAT_CTRL;
data->monitored_sensors = NUM_MONITORED_SENSORS;
data->ops.read_sensor = ab8500_read_sensor;
data->ops.irq_handler = ab8500_temp_irq_handler;
data->ops.show_name = ab8500_show_name;
data->ops.show_label = ab8500_show_label;
data->ops.is_visible = NULL;
return 0;
}
EXPORT_SYMBOL(abx500_hwmon_init);
MODULE_AUTHOR("Hongbo Zhang <hongbo.zhang@linaro.org>");
MODULE_DESCRIPTION("AB8500 temperature driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
myjang0507/Polaris-slte- | drivers/staging/netlogic/platform_net.c | 2762 | 6532 | /*
* Copyright (c) 2003-2012 Broadcom Corporation
* All Rights Reserved
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* 1. Redistributions of source code must retain the above copyright
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the Broadcom
* license below:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY BROADCOM ``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 BROADCOM OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/resource.h>
#include <linux/phy.h>
#include <asm/netlogic/haldefs.h>
#include <asm/netlogic/common.h>
#include <asm/netlogic/xlr/fmn.h>
#include <asm/netlogic/xlr/xlr.h>
#include <asm/netlogic/psb-bootinfo.h>
#include <asm/netlogic/xlr/pic.h>
#include <asm/netlogic/xlr/iomap.h>
#include "platform_net.h"
/* Linux Net */
#define MAX_NUM_GMAC 8
#define MAX_NUM_XLS_GMAC 8
#define MAX_NUM_XLR_GMAC 4
static u32 xlr_gmac_offsets[] = {
NETLOGIC_IO_GMAC_0_OFFSET, NETLOGIC_IO_GMAC_1_OFFSET,
NETLOGIC_IO_GMAC_2_OFFSET, NETLOGIC_IO_GMAC_3_OFFSET,
NETLOGIC_IO_GMAC_4_OFFSET, NETLOGIC_IO_GMAC_5_OFFSET,
NETLOGIC_IO_GMAC_6_OFFSET, NETLOGIC_IO_GMAC_7_OFFSET
};
static u32 xlr_gmac_irqs[] = { PIC_GMAC_0_IRQ, PIC_GMAC_1_IRQ,
PIC_GMAC_2_IRQ, PIC_GMAC_3_IRQ,
PIC_GMAC_4_IRQ, PIC_GMAC_5_IRQ,
PIC_GMAC_6_IRQ, PIC_GMAC_7_IRQ
};
static struct xlr_net_data ndata[MAX_NUM_GMAC];
static struct resource xlr_net_res[8][2];
static struct platform_device xlr_net_dev[8];
static u32 __iomem *gmac0_addr;
static u32 __iomem *gmac4_addr;
static u32 __iomem *gpio_addr;
static void config_mac(struct xlr_net_data *nd, int phy, u32 __iomem *serdes,
u32 __iomem *pcs, int rfr, int tx, int *bkt_size,
struct xlr_fmn_info *gmac_fmn_info, int phy_addr)
{
nd->cpu_mask = nlm_current_node()->coremask;
nd->phy_interface = phy;
nd->rfr_station = rfr;
nd->tx_stnid = tx;
nd->mii_addr = gmac0_addr;
nd->serdes_addr = serdes;
nd->pcs_addr = pcs;
nd->gpio_addr = gpio_addr;
nd->bucket_size = bkt_size;
nd->gmac_fmn_info = gmac_fmn_info;
nd->phy_addr = phy_addr;
}
static void net_device_init(int id, struct resource *res, int offset, int irq)
{
res[0].name = "gmac";
res[0].start = CPHYSADDR(nlm_mmio_base(offset));
res[0].end = res[0].start + 0xfff;
res[0].flags = IORESOURCE_MEM;
res[1].name = "gmac";
res[1].start = irq;
res[1].end = irq;
res[1].flags = IORESOURCE_IRQ;
xlr_net_dev[id].name = "xlr-net";
xlr_net_dev[id].id = id;
xlr_net_dev[id].num_resources = 2;
xlr_net_dev[id].resource = res;
xlr_net_dev[id].dev.platform_data = &ndata[id];
}
static void xls_gmac_init(void)
{
int mac;
gmac4_addr = ioremap(CPHYSADDR(
nlm_mmio_base(NETLOGIC_IO_GMAC_4_OFFSET)), 0xfff);
/* Passing GPIO base for serdes init. Only needed on sgmii ports*/
gpio_addr = ioremap(CPHYSADDR(
nlm_mmio_base(NETLOGIC_IO_GPIO_OFFSET)), 0xfff);
switch (nlm_prom_info.board_major_version) {
case 12:
/* first block RGMII or XAUI, use RGMII */
config_mac(&ndata[0],
PHY_INTERFACE_MODE_RGMII,
gmac0_addr, /* serdes */
gmac0_addr, /* pcs */
FMN_STNID_GMACRFR_0,
FMN_STNID_GMAC0_TX0,
xlr_board_fmn_config.bucket_size,
&xlr_board_fmn_config.gmac[0],
0);
net_device_init(0, xlr_net_res[0], xlr_gmac_offsets[0],
xlr_gmac_irqs[0]);
platform_device_register(&xlr_net_dev[0]);
/* second block is XAUI, not supported yet */
break;
default:
/* default XLS config, all ports SGMII */
for (mac = 0; mac < 4; mac++) {
config_mac(&ndata[mac],
PHY_INTERFACE_MODE_SGMII,
gmac0_addr, /* serdes */
gmac0_addr, /* pcs */
FMN_STNID_GMACRFR_0,
FMN_STNID_GMAC0_TX0 + mac,
xlr_board_fmn_config.bucket_size,
&xlr_board_fmn_config.gmac[0],
/* PHY address according to chip/board */
mac + 0x10);
net_device_init(mac, xlr_net_res[mac],
xlr_gmac_offsets[mac],
xlr_gmac_irqs[mac]);
platform_device_register(&xlr_net_dev[mac]);
}
for (mac = 4; mac < MAX_NUM_XLS_GMAC; mac++) {
config_mac(&ndata[mac],
PHY_INTERFACE_MODE_SGMII,
gmac4_addr, /* serdes */
gmac4_addr, /* pcs */
FMN_STNID_GMAC1_FR_0,
FMN_STNID_GMAC1_TX0 + mac - 4,
xlr_board_fmn_config.bucket_size,
&xlr_board_fmn_config.gmac[1],
/* PHY address according to chip/board */
mac + 0x10);
net_device_init(mac, xlr_net_res[mac],
xlr_gmac_offsets[mac],
xlr_gmac_irqs[mac]);
platform_device_register(&xlr_net_dev[mac]);
}
}
}
static void xlr_gmac_init(void)
{
int mac;
/* assume all GMACs for now */
for (mac = 0; mac < MAX_NUM_XLR_GMAC; mac++) {
config_mac(&ndata[mac],
PHY_INTERFACE_MODE_RGMII,
0,
0,
FMN_STNID_GMACRFR_0,
FMN_STNID_GMAC0_TX0,
xlr_board_fmn_config.bucket_size,
&xlr_board_fmn_config.gmac[0],
mac);
net_device_init(mac, xlr_net_res[mac], xlr_gmac_offsets[mac],
xlr_gmac_irqs[mac]);
platform_device_register(&xlr_net_dev[mac]);
}
}
static int __init xlr_net_init(void)
{
gmac0_addr = ioremap(CPHYSADDR(
nlm_mmio_base(NETLOGIC_IO_GMAC_0_OFFSET)), 0xfff);
if (nlm_chip_is_xls())
xls_gmac_init();
else
xlr_gmac_init();
return 0;
}
arch_initcall(xlr_net_init);
| gpl-2.0 |
MoKee/android_kernel_samsung_hlte | sound/pci/hda/patch_ca0132.c | 3274 | 28340 | /*
* HD audio interface patch for Creative CA0132 chip
*
* Copyright (c) 2011, Creative Technology Ltd.
*
* Based on patch_ca0110.c
* Copyright (c) 2008 Takashi Iwai <tiwai@suse.de>
*
* This driver is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This driver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/mutex.h>
#include <linux/module.h>
#include <sound/core.h>
#include "hda_codec.h"
#include "hda_local.h"
#define WIDGET_CHIP_CTRL 0x15
#define WIDGET_DSP_CTRL 0x16
#define WUH_MEM_CONNID 10
#define DSP_MEM_CONNID 16
enum hda_cmd_vendor_io {
/* for DspIO node */
VENDOR_DSPIO_SCP_WRITE_DATA_LOW = 0x000,
VENDOR_DSPIO_SCP_WRITE_DATA_HIGH = 0x100,
VENDOR_DSPIO_STATUS = 0xF01,
VENDOR_DSPIO_SCP_POST_READ_DATA = 0x702,
VENDOR_DSPIO_SCP_READ_DATA = 0xF02,
VENDOR_DSPIO_DSP_INIT = 0x703,
VENDOR_DSPIO_SCP_POST_COUNT_QUERY = 0x704,
VENDOR_DSPIO_SCP_READ_COUNT = 0xF04,
/* for ChipIO node */
VENDOR_CHIPIO_ADDRESS_LOW = 0x000,
VENDOR_CHIPIO_ADDRESS_HIGH = 0x100,
VENDOR_CHIPIO_STREAM_FORMAT = 0x200,
VENDOR_CHIPIO_DATA_LOW = 0x300,
VENDOR_CHIPIO_DATA_HIGH = 0x400,
VENDOR_CHIPIO_GET_PARAMETER = 0xF00,
VENDOR_CHIPIO_STATUS = 0xF01,
VENDOR_CHIPIO_HIC_POST_READ = 0x702,
VENDOR_CHIPIO_HIC_READ_DATA = 0xF03,
VENDOR_CHIPIO_CT_EXTENSIONS_ENABLE = 0x70A,
VENDOR_CHIPIO_PLL_PMU_WRITE = 0x70C,
VENDOR_CHIPIO_PLL_PMU_READ = 0xF0C,
VENDOR_CHIPIO_8051_ADDRESS_LOW = 0x70D,
VENDOR_CHIPIO_8051_ADDRESS_HIGH = 0x70E,
VENDOR_CHIPIO_FLAG_SET = 0x70F,
VENDOR_CHIPIO_FLAGS_GET = 0xF0F,
VENDOR_CHIPIO_PARAMETER_SET = 0x710,
VENDOR_CHIPIO_PARAMETER_GET = 0xF10,
VENDOR_CHIPIO_PORT_ALLOC_CONFIG_SET = 0x711,
VENDOR_CHIPIO_PORT_ALLOC_SET = 0x712,
VENDOR_CHIPIO_PORT_ALLOC_GET = 0xF12,
VENDOR_CHIPIO_PORT_FREE_SET = 0x713,
VENDOR_CHIPIO_PARAMETER_EX_ID_GET = 0xF17,
VENDOR_CHIPIO_PARAMETER_EX_ID_SET = 0x717,
VENDOR_CHIPIO_PARAMETER_EX_VALUE_GET = 0xF18,
VENDOR_CHIPIO_PARAMETER_EX_VALUE_SET = 0x718
};
/*
* Control flag IDs
*/
enum control_flag_id {
/* Connection manager stream setup is bypassed/enabled */
CONTROL_FLAG_C_MGR = 0,
/* DSP DMA is bypassed/enabled */
CONTROL_FLAG_DMA = 1,
/* 8051 'idle' mode is disabled/enabled */
CONTROL_FLAG_IDLE_ENABLE = 2,
/* Tracker for the SPDIF-in path is bypassed/enabled */
CONTROL_FLAG_TRACKER = 3,
/* DigitalOut to Spdif2Out connection is disabled/enabled */
CONTROL_FLAG_SPDIF2OUT = 4,
/* Digital Microphone is disabled/enabled */
CONTROL_FLAG_DMIC = 5,
/* ADC_B rate is 48 kHz/96 kHz */
CONTROL_FLAG_ADC_B_96KHZ = 6,
/* ADC_C rate is 48 kHz/96 kHz */
CONTROL_FLAG_ADC_C_96KHZ = 7,
/* DAC rate is 48 kHz/96 kHz (affects all DACs) */
CONTROL_FLAG_DAC_96KHZ = 8,
/* DSP rate is 48 kHz/96 kHz */
CONTROL_FLAG_DSP_96KHZ = 9,
/* SRC clock is 98 MHz/196 MHz (196 MHz forces rate to 96 KHz) */
CONTROL_FLAG_SRC_CLOCK_196MHZ = 10,
/* SRC rate is 48 kHz/96 kHz (48 kHz disabled when clock is 196 MHz) */
CONTROL_FLAG_SRC_RATE_96KHZ = 11,
/* Decode Loop (DSP->SRC->DSP) is disabled/enabled */
CONTROL_FLAG_DECODE_LOOP = 12,
/* De-emphasis filter on DAC-1 disabled/enabled */
CONTROL_FLAG_DAC1_DEEMPHASIS = 13,
/* De-emphasis filter on DAC-2 disabled/enabled */
CONTROL_FLAG_DAC2_DEEMPHASIS = 14,
/* De-emphasis filter on DAC-3 disabled/enabled */
CONTROL_FLAG_DAC3_DEEMPHASIS = 15,
/* High-pass filter on ADC_B disabled/enabled */
CONTROL_FLAG_ADC_B_HIGH_PASS = 16,
/* High-pass filter on ADC_C disabled/enabled */
CONTROL_FLAG_ADC_C_HIGH_PASS = 17,
/* Common mode on Port_A disabled/enabled */
CONTROL_FLAG_PORT_A_COMMON_MODE = 18,
/* Common mode on Port_D disabled/enabled */
CONTROL_FLAG_PORT_D_COMMON_MODE = 19,
/* Impedance for ramp generator on Port_A 16 Ohm/10K Ohm */
CONTROL_FLAG_PORT_A_10KOHM_LOAD = 20,
/* Impedance for ramp generator on Port_D, 16 Ohm/10K Ohm */
CONTROL_FLAG_PORT_D_10K0HM_LOAD = 21,
/* ASI rate is 48kHz/96kHz */
CONTROL_FLAG_ASI_96KHZ = 22,
/* DAC power settings able to control attached ports no/yes */
CONTROL_FLAG_DACS_CONTROL_PORTS = 23,
/* Clock Stop OK reporting is disabled/enabled */
CONTROL_FLAG_CONTROL_STOP_OK_ENABLE = 24,
/* Number of control flags */
CONTROL_FLAGS_MAX = (CONTROL_FLAG_CONTROL_STOP_OK_ENABLE+1)
};
/*
* Control parameter IDs
*/
enum control_parameter_id {
/* 0: force HDA, 1: allow DSP if HDA Spdif1Out stream is idle */
CONTROL_PARAM_SPDIF1_SOURCE = 2,
/* Stream Control */
/* Select stream with the given ID */
CONTROL_PARAM_STREAM_ID = 24,
/* Source connection point for the selected stream */
CONTROL_PARAM_STREAM_SOURCE_CONN_POINT = 25,
/* Destination connection point for the selected stream */
CONTROL_PARAM_STREAM_DEST_CONN_POINT = 26,
/* Number of audio channels in the selected stream */
CONTROL_PARAM_STREAMS_CHANNELS = 27,
/*Enable control for the selected stream */
CONTROL_PARAM_STREAM_CONTROL = 28,
/* Connection Point Control */
/* Select connection point with the given ID */
CONTROL_PARAM_CONN_POINT_ID = 29,
/* Connection point sample rate */
CONTROL_PARAM_CONN_POINT_SAMPLE_RATE = 30,
/* Node Control */
/* Select HDA node with the given ID */
CONTROL_PARAM_NODE_ID = 31
};
/*
* Dsp Io Status codes
*/
enum hda_vendor_status_dspio {
/* Success */
VENDOR_STATUS_DSPIO_OK = 0x00,
/* Busy, unable to accept new command, the host must retry */
VENDOR_STATUS_DSPIO_BUSY = 0x01,
/* SCP command queue is full */
VENDOR_STATUS_DSPIO_SCP_COMMAND_QUEUE_FULL = 0x02,
/* SCP response queue is empty */
VENDOR_STATUS_DSPIO_SCP_RESPONSE_QUEUE_EMPTY = 0x03
};
/*
* Chip Io Status codes
*/
enum hda_vendor_status_chipio {
/* Success */
VENDOR_STATUS_CHIPIO_OK = 0x00,
/* Busy, unable to accept new command, the host must retry */
VENDOR_STATUS_CHIPIO_BUSY = 0x01
};
/*
* CA0132 sample rate
*/
enum ca0132_sample_rate {
SR_6_000 = 0x00,
SR_8_000 = 0x01,
SR_9_600 = 0x02,
SR_11_025 = 0x03,
SR_16_000 = 0x04,
SR_22_050 = 0x05,
SR_24_000 = 0x06,
SR_32_000 = 0x07,
SR_44_100 = 0x08,
SR_48_000 = 0x09,
SR_88_200 = 0x0A,
SR_96_000 = 0x0B,
SR_144_000 = 0x0C,
SR_176_400 = 0x0D,
SR_192_000 = 0x0E,
SR_384_000 = 0x0F,
SR_COUNT = 0x10,
SR_RATE_UNKNOWN = 0x1F
};
/*
* Scp Helper function
*/
enum get_set {
IS_SET = 0,
IS_GET = 1,
};
/*
* Duplicated from ca0110 codec
*/
static void init_output(struct hda_codec *codec, hda_nid_t pin, hda_nid_t dac)
{
if (pin) {
snd_hda_codec_write(codec, pin, 0,
AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP);
if (get_wcaps(codec, pin) & AC_WCAP_OUT_AMP)
snd_hda_codec_write(codec, pin, 0,
AC_VERB_SET_AMP_GAIN_MUTE,
AMP_OUT_UNMUTE);
}
if (dac)
snd_hda_codec_write(codec, dac, 0,
AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_ZERO);
}
static void init_input(struct hda_codec *codec, hda_nid_t pin, hda_nid_t adc)
{
if (pin) {
snd_hda_codec_write(codec, pin, 0,
AC_VERB_SET_PIN_WIDGET_CONTROL,
PIN_VREF80);
if (get_wcaps(codec, pin) & AC_WCAP_IN_AMP)
snd_hda_codec_write(codec, pin, 0,
AC_VERB_SET_AMP_GAIN_MUTE,
AMP_IN_UNMUTE(0));
}
if (adc)
snd_hda_codec_write(codec, adc, 0, AC_VERB_SET_AMP_GAIN_MUTE,
AMP_IN_UNMUTE(0));
}
static char *dirstr[2] = { "Playback", "Capture" };
static int _add_switch(struct hda_codec *codec, hda_nid_t nid, const char *pfx,
int chan, int dir)
{
char namestr[44];
int type = dir ? HDA_INPUT : HDA_OUTPUT;
struct snd_kcontrol_new knew =
HDA_CODEC_MUTE_MONO(namestr, nid, chan, 0, type);
sprintf(namestr, "%s %s Switch", pfx, dirstr[dir]);
return snd_hda_ctl_add(codec, nid, snd_ctl_new1(&knew, codec));
}
static int _add_volume(struct hda_codec *codec, hda_nid_t nid, const char *pfx,
int chan, int dir)
{
char namestr[44];
int type = dir ? HDA_INPUT : HDA_OUTPUT;
struct snd_kcontrol_new knew =
HDA_CODEC_VOLUME_MONO(namestr, nid, chan, 0, type);
sprintf(namestr, "%s %s Volume", pfx, dirstr[dir]);
return snd_hda_ctl_add(codec, nid, snd_ctl_new1(&knew, codec));
}
#define add_out_switch(codec, nid, pfx) _add_switch(codec, nid, pfx, 3, 0)
#define add_out_volume(codec, nid, pfx) _add_volume(codec, nid, pfx, 3, 0)
#define add_in_switch(codec, nid, pfx) _add_switch(codec, nid, pfx, 3, 1)
#define add_in_volume(codec, nid, pfx) _add_volume(codec, nid, pfx, 3, 1)
#define add_mono_switch(codec, nid, pfx, chan) \
_add_switch(codec, nid, pfx, chan, 0)
#define add_mono_volume(codec, nid, pfx, chan) \
_add_volume(codec, nid, pfx, chan, 0)
#define add_in_mono_switch(codec, nid, pfx, chan) \
_add_switch(codec, nid, pfx, chan, 1)
#define add_in_mono_volume(codec, nid, pfx, chan) \
_add_volume(codec, nid, pfx, chan, 1)
/*
* CA0132 specific
*/
struct ca0132_spec {
struct auto_pin_cfg autocfg;
struct hda_multi_out multiout;
hda_nid_t out_pins[AUTO_CFG_MAX_OUTS];
hda_nid_t dacs[AUTO_CFG_MAX_OUTS];
hda_nid_t hp_dac;
hda_nid_t input_pins[AUTO_PIN_LAST];
hda_nid_t adcs[AUTO_PIN_LAST];
hda_nid_t dig_out;
hda_nid_t dig_in;
unsigned int num_inputs;
long curr_hp_switch;
long curr_hp_volume[2];
long curr_speaker_switch;
struct mutex chipio_mutex;
const char *input_labels[AUTO_PIN_LAST];
struct hda_pcm pcm_rec[2]; /* PCM information */
};
/* Chip access helper function */
static int chipio_send(struct hda_codec *codec,
unsigned int reg,
unsigned int data)
{
unsigned int res;
int retry = 50;
/* send bits of data specified by reg */
do {
res = snd_hda_codec_read(codec, WIDGET_CHIP_CTRL, 0,
reg, data);
if (res == VENDOR_STATUS_CHIPIO_OK)
return 0;
} while (--retry);
return -EIO;
}
/*
* Write chip address through the vendor widget -- NOT protected by the Mutex!
*/
static int chipio_write_address(struct hda_codec *codec,
unsigned int chip_addx)
{
int res;
/* send low 16 bits of the address */
res = chipio_send(codec, VENDOR_CHIPIO_ADDRESS_LOW,
chip_addx & 0xffff);
if (res != -EIO) {
/* send high 16 bits of the address */
res = chipio_send(codec, VENDOR_CHIPIO_ADDRESS_HIGH,
chip_addx >> 16);
}
return res;
}
/*
* Write data through the vendor widget -- NOT protected by the Mutex!
*/
static int chipio_write_data(struct hda_codec *codec, unsigned int data)
{
int res;
/* send low 16 bits of the data */
res = chipio_send(codec, VENDOR_CHIPIO_DATA_LOW, data & 0xffff);
if (res != -EIO) {
/* send high 16 bits of the data */
res = chipio_send(codec, VENDOR_CHIPIO_DATA_HIGH,
data >> 16);
}
return res;
}
/*
* Read data through the vendor widget -- NOT protected by the Mutex!
*/
static int chipio_read_data(struct hda_codec *codec, unsigned int *data)
{
int res;
/* post read */
res = chipio_send(codec, VENDOR_CHIPIO_HIC_POST_READ, 0);
if (res != -EIO) {
/* read status */
res = chipio_send(codec, VENDOR_CHIPIO_STATUS, 0);
}
if (res != -EIO) {
/* read data */
*data = snd_hda_codec_read(codec, WIDGET_CHIP_CTRL, 0,
VENDOR_CHIPIO_HIC_READ_DATA,
0);
}
return res;
}
/*
* Write given value to the given address through the chip I/O widget.
* protected by the Mutex
*/
static int chipio_write(struct hda_codec *codec,
unsigned int chip_addx, const unsigned int data)
{
struct ca0132_spec *spec = codec->spec;
int err;
mutex_lock(&spec->chipio_mutex);
/* write the address, and if successful proceed to write data */
err = chipio_write_address(codec, chip_addx);
if (err < 0)
goto exit;
err = chipio_write_data(codec, data);
if (err < 0)
goto exit;
exit:
mutex_unlock(&spec->chipio_mutex);
return err;
}
/*
* Read the given address through the chip I/O widget
* protected by the Mutex
*/
static int chipio_read(struct hda_codec *codec,
unsigned int chip_addx, unsigned int *data)
{
struct ca0132_spec *spec = codec->spec;
int err;
mutex_lock(&spec->chipio_mutex);
/* write the address, and if successful proceed to write data */
err = chipio_write_address(codec, chip_addx);
if (err < 0)
goto exit;
err = chipio_read_data(codec, data);
if (err < 0)
goto exit;
exit:
mutex_unlock(&spec->chipio_mutex);
return err;
}
/*
* PCM stuffs
*/
static void ca0132_setup_stream(struct hda_codec *codec, hda_nid_t nid,
u32 stream_tag,
int channel_id, int format)
{
unsigned int oldval, newval;
if (!nid)
return;
snd_printdd("ca0132_setup_stream: "
"NID=0x%x, stream=0x%x, channel=%d, format=0x%x\n",
nid, stream_tag, channel_id, format);
/* update the format-id if changed */
oldval = snd_hda_codec_read(codec, nid, 0,
AC_VERB_GET_STREAM_FORMAT,
0);
if (oldval != format) {
msleep(20);
snd_hda_codec_write(codec, nid, 0,
AC_VERB_SET_STREAM_FORMAT,
format);
}
oldval = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_CONV, 0);
newval = (stream_tag << 4) | channel_id;
if (oldval != newval) {
snd_hda_codec_write(codec, nid, 0,
AC_VERB_SET_CHANNEL_STREAMID,
newval);
}
}
static void ca0132_cleanup_stream(struct hda_codec *codec, hda_nid_t nid)
{
snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_STREAM_FORMAT, 0);
snd_hda_codec_write(codec, nid, 0, AC_VERB_SET_CHANNEL_STREAMID, 0);
}
/*
* PCM callbacks
*/
static int ca0132_playback_pcm_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct ca0132_spec *spec = codec->spec;
ca0132_setup_stream(codec, spec->dacs[0], stream_tag, 0, format);
return 0;
}
static int ca0132_playback_pcm_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct ca0132_spec *spec = codec->spec;
ca0132_cleanup_stream(codec, spec->dacs[0]);
return 0;
}
/*
* Digital out
*/
static int ca0132_dig_playback_pcm_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct ca0132_spec *spec = codec->spec;
ca0132_setup_stream(codec, spec->dig_out, stream_tag, 0, format);
return 0;
}
static int ca0132_dig_playback_pcm_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct ca0132_spec *spec = codec->spec;
ca0132_cleanup_stream(codec, spec->dig_out);
return 0;
}
/*
* Analog capture
*/
static int ca0132_capture_pcm_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct ca0132_spec *spec = codec->spec;
ca0132_setup_stream(codec, spec->adcs[substream->number],
stream_tag, 0, format);
return 0;
}
static int ca0132_capture_pcm_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct ca0132_spec *spec = codec->spec;
ca0132_cleanup_stream(codec, spec->adcs[substream->number]);
return 0;
}
/*
* Digital capture
*/
static int ca0132_dig_capture_pcm_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct ca0132_spec *spec = codec->spec;
ca0132_setup_stream(codec, spec->dig_in, stream_tag, 0, format);
return 0;
}
static int ca0132_dig_capture_pcm_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct ca0132_spec *spec = codec->spec;
ca0132_cleanup_stream(codec, spec->dig_in);
return 0;
}
/*
*/
static struct hda_pcm_stream ca0132_pcm_analog_playback = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
.ops = {
.prepare = ca0132_playback_pcm_prepare,
.cleanup = ca0132_playback_pcm_cleanup
},
};
static struct hda_pcm_stream ca0132_pcm_analog_capture = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
.ops = {
.prepare = ca0132_capture_pcm_prepare,
.cleanup = ca0132_capture_pcm_cleanup
},
};
static struct hda_pcm_stream ca0132_pcm_digital_playback = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
.ops = {
.prepare = ca0132_dig_playback_pcm_prepare,
.cleanup = ca0132_dig_playback_pcm_cleanup
},
};
static struct hda_pcm_stream ca0132_pcm_digital_capture = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
.ops = {
.prepare = ca0132_dig_capture_pcm_prepare,
.cleanup = ca0132_dig_capture_pcm_cleanup
},
};
static int ca0132_build_pcms(struct hda_codec *codec)
{
struct ca0132_spec *spec = codec->spec;
struct hda_pcm *info = spec->pcm_rec;
codec->pcm_info = info;
codec->num_pcms = 0;
info->name = "CA0132 Analog";
info->stream[SNDRV_PCM_STREAM_PLAYBACK] = ca0132_pcm_analog_playback;
info->stream[SNDRV_PCM_STREAM_PLAYBACK].nid = spec->dacs[0];
info->stream[SNDRV_PCM_STREAM_PLAYBACK].channels_max =
spec->multiout.max_channels;
info->stream[SNDRV_PCM_STREAM_CAPTURE] = ca0132_pcm_analog_capture;
info->stream[SNDRV_PCM_STREAM_CAPTURE].substreams = spec->num_inputs;
info->stream[SNDRV_PCM_STREAM_CAPTURE].nid = spec->adcs[0];
codec->num_pcms++;
if (!spec->dig_out && !spec->dig_in)
return 0;
info++;
info->name = "CA0132 Digital";
info->pcm_type = HDA_PCM_TYPE_SPDIF;
if (spec->dig_out) {
info->stream[SNDRV_PCM_STREAM_PLAYBACK] =
ca0132_pcm_digital_playback;
info->stream[SNDRV_PCM_STREAM_PLAYBACK].nid = spec->dig_out;
}
if (spec->dig_in) {
info->stream[SNDRV_PCM_STREAM_CAPTURE] =
ca0132_pcm_digital_capture;
info->stream[SNDRV_PCM_STREAM_CAPTURE].nid = spec->dig_in;
}
codec->num_pcms++;
return 0;
}
#define REG_CODEC_MUTE 0x18b014
#define REG_CODEC_HP_VOL_L 0x18b070
#define REG_CODEC_HP_VOL_R 0x18b074
static int ca0132_hp_switch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ca0132_spec *spec = codec->spec;
long *valp = ucontrol->value.integer.value;
*valp = spec->curr_hp_switch;
return 0;
}
static int ca0132_hp_switch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ca0132_spec *spec = codec->spec;
long *valp = ucontrol->value.integer.value;
unsigned int data;
int err;
/* any change? */
if (spec->curr_hp_switch == *valp)
return 0;
snd_hda_power_up(codec);
err = chipio_read(codec, REG_CODEC_MUTE, &data);
if (err < 0)
goto exit;
/* *valp 0 is mute, 1 is unmute */
data = (data & 0x7f) | (*valp ? 0 : 0x80);
err = chipio_write(codec, REG_CODEC_MUTE, data);
if (err < 0)
goto exit;
spec->curr_hp_switch = *valp;
exit:
snd_hda_power_down(codec);
return err < 0 ? err : 1;
}
static int ca0132_speaker_switch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ca0132_spec *spec = codec->spec;
long *valp = ucontrol->value.integer.value;
*valp = spec->curr_speaker_switch;
return 0;
}
static int ca0132_speaker_switch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ca0132_spec *spec = codec->spec;
long *valp = ucontrol->value.integer.value;
unsigned int data;
int err;
/* any change? */
if (spec->curr_speaker_switch == *valp)
return 0;
snd_hda_power_up(codec);
err = chipio_read(codec, REG_CODEC_MUTE, &data);
if (err < 0)
goto exit;
/* *valp 0 is mute, 1 is unmute */
data = (data & 0xef) | (*valp ? 0 : 0x10);
err = chipio_write(codec, REG_CODEC_MUTE, data);
if (err < 0)
goto exit;
spec->curr_speaker_switch = *valp;
exit:
snd_hda_power_down(codec);
return err < 0 ? err : 1;
}
static int ca0132_hp_volume_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ca0132_spec *spec = codec->spec;
long *valp = ucontrol->value.integer.value;
*valp++ = spec->curr_hp_volume[0];
*valp = spec->curr_hp_volume[1];
return 0;
}
static int ca0132_hp_volume_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct ca0132_spec *spec = codec->spec;
long *valp = ucontrol->value.integer.value;
long left_vol, right_vol;
unsigned int data;
int val;
int err;
left_vol = *valp++;
right_vol = *valp;
/* any change? */
if ((spec->curr_hp_volume[0] == left_vol) &&
(spec->curr_hp_volume[1] == right_vol))
return 0;
snd_hda_power_up(codec);
err = chipio_read(codec, REG_CODEC_HP_VOL_L, &data);
if (err < 0)
goto exit;
val = 31 - left_vol;
data = (data & 0xe0) | val;
err = chipio_write(codec, REG_CODEC_HP_VOL_L, data);
if (err < 0)
goto exit;
val = 31 - right_vol;
data = (data & 0xe0) | val;
err = chipio_write(codec, REG_CODEC_HP_VOL_R, data);
if (err < 0)
goto exit;
spec->curr_hp_volume[0] = left_vol;
spec->curr_hp_volume[1] = right_vol;
exit:
snd_hda_power_down(codec);
return err < 0 ? err : 1;
}
static int add_hp_switch(struct hda_codec *codec, hda_nid_t nid)
{
struct snd_kcontrol_new knew =
HDA_CODEC_MUTE_MONO("Headphone Playback Switch",
nid, 1, 0, HDA_OUTPUT);
knew.get = ca0132_hp_switch_get;
knew.put = ca0132_hp_switch_put;
return snd_hda_ctl_add(codec, nid, snd_ctl_new1(&knew, codec));
}
static int add_hp_volume(struct hda_codec *codec, hda_nid_t nid)
{
struct snd_kcontrol_new knew =
HDA_CODEC_VOLUME_MONO("Headphone Playback Volume",
nid, 3, 0, HDA_OUTPUT);
knew.get = ca0132_hp_volume_get;
knew.put = ca0132_hp_volume_put;
return snd_hda_ctl_add(codec, nid, snd_ctl_new1(&knew, codec));
}
static int add_speaker_switch(struct hda_codec *codec, hda_nid_t nid)
{
struct snd_kcontrol_new knew =
HDA_CODEC_MUTE_MONO("Speaker Playback Switch",
nid, 1, 0, HDA_OUTPUT);
knew.get = ca0132_speaker_switch_get;
knew.put = ca0132_speaker_switch_put;
return snd_hda_ctl_add(codec, nid, snd_ctl_new1(&knew, codec));
}
static void ca0132_fix_hp_caps(struct hda_codec *codec)
{
struct ca0132_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
unsigned int caps;
/* set mute-capable, 1db step, 32 steps, ofs 6 */
caps = 0x80031f06;
snd_hda_override_amp_caps(codec, cfg->hp_pins[0], HDA_OUTPUT, caps);
}
static int ca0132_build_controls(struct hda_codec *codec)
{
struct ca0132_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
int i, err;
if (spec->multiout.num_dacs) {
err = add_speaker_switch(codec, spec->out_pins[0]);
if (err < 0)
return err;
}
if (cfg->hp_outs) {
ca0132_fix_hp_caps(codec);
err = add_hp_switch(codec, cfg->hp_pins[0]);
if (err < 0)
return err;
err = add_hp_volume(codec, cfg->hp_pins[0]);
if (err < 0)
return err;
}
for (i = 0; i < spec->num_inputs; i++) {
const char *label = spec->input_labels[i];
err = add_in_switch(codec, spec->adcs[i], label);
if (err < 0)
return err;
err = add_in_volume(codec, spec->adcs[i], label);
if (err < 0)
return err;
if (cfg->inputs[i].type == AUTO_PIN_MIC) {
/* add Mic-Boost */
err = add_in_mono_volume(codec, spec->input_pins[i],
"Mic Boost", 1);
if (err < 0)
return err;
}
}
if (spec->dig_out) {
err = snd_hda_create_spdif_out_ctls(codec, spec->dig_out,
spec->dig_out);
if (err < 0)
return err;
err = add_out_volume(codec, spec->dig_out, "IEC958");
if (err < 0)
return err;
}
if (spec->dig_in) {
err = snd_hda_create_spdif_in_ctls(codec, spec->dig_in);
if (err < 0)
return err;
err = add_in_volume(codec, spec->dig_in, "IEC958");
if (err < 0)
return err;
}
return 0;
}
static void ca0132_set_ct_ext(struct hda_codec *codec, int enable)
{
/* Set Creative extension */
snd_printdd("SET CREATIVE EXTENSION\n");
snd_hda_codec_write(codec, WIDGET_CHIP_CTRL, 0,
VENDOR_CHIPIO_CT_EXTENSIONS_ENABLE,
enable);
msleep(20);
}
static void ca0132_config(struct hda_codec *codec)
{
struct ca0132_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
/* line-outs */
cfg->line_outs = 1;
cfg->line_out_pins[0] = 0x0b; /* front */
cfg->line_out_type = AUTO_PIN_LINE_OUT;
spec->dacs[0] = 0x02;
spec->out_pins[0] = 0x0b;
spec->multiout.dac_nids = spec->dacs;
spec->multiout.num_dacs = 1;
spec->multiout.max_channels = 2;
/* headphone */
cfg->hp_outs = 1;
cfg->hp_pins[0] = 0x0f;
spec->hp_dac = 0;
spec->multiout.hp_nid = 0;
/* inputs */
cfg->num_inputs = 2; /* Mic-in and line-in */
cfg->inputs[0].pin = 0x12;
cfg->inputs[0].type = AUTO_PIN_MIC;
cfg->inputs[1].pin = 0x11;
cfg->inputs[1].type = AUTO_PIN_LINE_IN;
/* Mic-in */
spec->input_pins[0] = 0x12;
spec->input_labels[0] = "Mic-In";
spec->adcs[0] = 0x07;
/* Line-In */
spec->input_pins[1] = 0x11;
spec->input_labels[1] = "Line-In";
spec->adcs[1] = 0x08;
spec->num_inputs = 2;
}
static void ca0132_init_chip(struct hda_codec *codec)
{
struct ca0132_spec *spec = codec->spec;
mutex_init(&spec->chipio_mutex);
}
static void ca0132_exit_chip(struct hda_codec *codec)
{
/* put any chip cleanup stuffs here. */
}
static int ca0132_init(struct hda_codec *codec)
{
struct ca0132_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
int i;
for (i = 0; i < spec->multiout.num_dacs; i++) {
init_output(codec, spec->out_pins[i],
spec->multiout.dac_nids[i]);
}
init_output(codec, cfg->hp_pins[0], spec->hp_dac);
init_output(codec, cfg->dig_out_pins[0], spec->dig_out);
for (i = 0; i < spec->num_inputs; i++)
init_input(codec, spec->input_pins[i], spec->adcs[i]);
init_input(codec, cfg->dig_in_pin, spec->dig_in);
ca0132_set_ct_ext(codec, 1);
return 0;
}
static void ca0132_free(struct hda_codec *codec)
{
ca0132_set_ct_ext(codec, 0);
ca0132_exit_chip(codec);
kfree(codec->spec);
}
static struct hda_codec_ops ca0132_patch_ops = {
.build_controls = ca0132_build_controls,
.build_pcms = ca0132_build_pcms,
.init = ca0132_init,
.free = ca0132_free,
};
static int patch_ca0132(struct hda_codec *codec)
{
struct ca0132_spec *spec;
snd_printdd("patch_ca0132\n");
spec = kzalloc(sizeof(*spec), GFP_KERNEL);
if (!spec)
return -ENOMEM;
codec->spec = spec;
ca0132_init_chip(codec);
ca0132_config(codec);
codec->patch_ops = ca0132_patch_ops;
return 0;
}
/*
* patch entries
*/
static struct hda_codec_preset snd_hda_preset_ca0132[] = {
{ .id = 0x11020011, .name = "CA0132", .patch = patch_ca0132 },
{} /* terminator */
};
MODULE_ALIAS("snd-hda-codec-id:11020011");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Creative CA0132, CA0132 HD-audio codec");
static struct hda_codec_preset_list ca0132_list = {
.preset = snd_hda_preset_ca0132,
.owner = THIS_MODULE,
};
static int __init patch_ca0132_init(void)
{
return snd_hda_add_codec_preset(&ca0132_list);
}
static void __exit patch_ca0132_exit(void)
{
snd_hda_delete_codec_preset(&ca0132_list);
}
module_init(patch_ca0132_init)
module_exit(patch_ca0132_exit)
| gpl-2.0 |
EPDCenterSpain/kernel_Archos_97b_Titan | drivers/media/video/ivtv/ivtv-controls.c | 3530 | 3235 | /*
ioctl control functions
Copyright (C) 2003-2004 Kevin Thayer <nufan_wfk at yahoo.com>
Copyright (C) 2005-2007 Hans Verkuil <hverkuil@xs4all.nl>
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 "ivtv-driver.h"
#include "ivtv-ioctl.h"
#include "ivtv-controls.h"
static int ivtv_s_stream_vbi_fmt(struct cx2341x_handler *cxhdl, u32 fmt)
{
struct ivtv *itv = container_of(cxhdl, struct ivtv, cxhdl);
/* First try to allocate sliced VBI buffers if needed. */
if (fmt && itv->vbi.sliced_mpeg_data[0] == NULL) {
int i;
for (i = 0; i < IVTV_VBI_FRAMES; i++) {
/* Yuck, hardcoded. Needs to be a define */
itv->vbi.sliced_mpeg_data[i] = kmalloc(2049, GFP_KERNEL);
if (itv->vbi.sliced_mpeg_data[i] == NULL) {
while (--i >= 0) {
kfree(itv->vbi.sliced_mpeg_data[i]);
itv->vbi.sliced_mpeg_data[i] = NULL;
}
return -ENOMEM;
}
}
}
itv->vbi.insert_mpeg = fmt;
if (itv->vbi.insert_mpeg == 0) {
return 0;
}
/* Need sliced data for mpeg insertion */
if (ivtv_get_service_set(itv->vbi.sliced_in) == 0) {
if (itv->is_60hz)
itv->vbi.sliced_in->service_set = V4L2_SLICED_CAPTION_525;
else
itv->vbi.sliced_in->service_set = V4L2_SLICED_WSS_625;
ivtv_expand_service_set(itv->vbi.sliced_in, itv->is_50hz);
}
return 0;
}
static int ivtv_s_video_encoding(struct cx2341x_handler *cxhdl, u32 val)
{
struct ivtv *itv = container_of(cxhdl, struct ivtv, cxhdl);
int is_mpeg1 = val == V4L2_MPEG_VIDEO_ENCODING_MPEG_1;
struct v4l2_mbus_framefmt fmt;
/* fix videodecoder resolution */
fmt.width = cxhdl->width / (is_mpeg1 ? 2 : 1);
fmt.height = cxhdl->height;
fmt.code = V4L2_MBUS_FMT_FIXED;
v4l2_subdev_call(itv->sd_video, video, s_mbus_fmt, &fmt);
return 0;
}
static int ivtv_s_audio_sampling_freq(struct cx2341x_handler *cxhdl, u32 idx)
{
static const u32 freqs[3] = { 44100, 48000, 32000 };
struct ivtv *itv = container_of(cxhdl, struct ivtv, cxhdl);
/* The audio clock of the digitizer must match the codec sample
rate otherwise you get some very strange effects. */
if (idx < ARRAY_SIZE(freqs))
ivtv_call_all(itv, audio, s_clock_freq, freqs[idx]);
return 0;
}
static int ivtv_s_audio_mode(struct cx2341x_handler *cxhdl, u32 val)
{
struct ivtv *itv = container_of(cxhdl, struct ivtv, cxhdl);
itv->dualwatch_stereo_mode = val;
return 0;
}
struct cx2341x_handler_ops ivtv_cxhdl_ops = {
.s_audio_mode = ivtv_s_audio_mode,
.s_audio_sampling_freq = ivtv_s_audio_sampling_freq,
.s_video_encoding = ivtv_s_video_encoding,
.s_stream_vbi_fmt = ivtv_s_stream_vbi_fmt,
};
| gpl-2.0 |
iceblu3710/SUNXI_XENOMAI | drivers/video/logo/logo.c | 4554 | 2446 |
/*
* Linux logo to be displayed on boot
*
* Copyright (C) 1996 Larry Ewing (lewing@isc.tamu.edu)
* Copyright (C) 1996,1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
* Copyright (C) 2001 Greg Banks <gnb@alphalink.com.au>
* Copyright (C) 2001 Jan-Benedict Glaw <jbglaw@lug-owl.de>
* Copyright (C) 2003 Geert Uytterhoeven <geert@linux-m68k.org>
*/
#include <linux/linux_logo.h>
#include <linux/stddef.h>
#include <linux/module.h>
#ifdef CONFIG_M68K
#include <asm/setup.h>
#endif
#ifdef CONFIG_MIPS
#include <asm/bootinfo.h>
#endif
static int nologo;
module_param(nologo, bool, 0);
MODULE_PARM_DESC(nologo, "Disables startup logo");
/* logo's are marked __initdata. Use __init_refok to tell
* modpost that it is intended that this function uses data
* marked __initdata.
*/
const struct linux_logo * __init_refok fb_find_logo(int depth)
{
const struct linux_logo *logo = NULL;
if (nologo)
return NULL;
if (depth >= 1) {
#ifdef CONFIG_LOGO_LINUX_MONO
/* Generic Linux logo */
logo = &logo_linux_mono;
#endif
#ifdef CONFIG_LOGO_SUPERH_MONO
/* SuperH Linux logo */
logo = &logo_superh_mono;
#endif
}
if (depth >= 4) {
#ifdef CONFIG_LOGO_LINUX_VGA16
/* Generic Linux logo */
logo = &logo_linux_vga16;
#endif
#ifdef CONFIG_LOGO_BLACKFIN_VGA16
/* Blackfin processor logo */
logo = &logo_blackfin_vga16;
#endif
#ifdef CONFIG_LOGO_SUPERH_VGA16
/* SuperH Linux logo */
logo = &logo_superh_vga16;
#endif
}
if (depth >= 8) {
#ifdef CONFIG_LOGO_LINUX_CLUT224
/* Generic Linux logo */
logo = &logo_linux_clut224;
#endif
#ifdef CONFIG_LOGO_BLACKFIN_CLUT224
/* Blackfin Linux logo */
logo = &logo_blackfin_clut224;
#endif
#ifdef CONFIG_LOGO_DEC_CLUT224
/* DEC Linux logo on MIPS/MIPS64 or ALPHA */
logo = &logo_dec_clut224;
#endif
#ifdef CONFIG_LOGO_MAC_CLUT224
/* Macintosh Linux logo on m68k */
if (MACH_IS_MAC)
logo = &logo_mac_clut224;
#endif
#ifdef CONFIG_LOGO_PARISC_CLUT224
/* PA-RISC Linux logo */
logo = &logo_parisc_clut224;
#endif
#ifdef CONFIG_LOGO_SGI_CLUT224
/* SGI Linux logo on MIPS/MIPS64 and VISWS */
logo = &logo_sgi_clut224;
#endif
#ifdef CONFIG_LOGO_SUN_CLUT224
/* Sun Linux logo */
logo = &logo_sun_clut224;
#endif
#ifdef CONFIG_LOGO_SUPERH_CLUT224
/* SuperH Linux logo */
logo = &logo_superh_clut224;
#endif
#ifdef CONFIG_LOGO_M32R_CLUT224
/* M32R Linux logo */
logo = &logo_m32r_clut224;
#endif
}
return logo;
}
EXPORT_SYMBOL_GPL(fb_find_logo);
| gpl-2.0 |
BanBxda/Sense_5.5-JB-M7 | drivers/net/ethernet/stmicro/stmmac/enh_desc.c | 4554 | 9448 | /*******************************************************************************
This contains the functions to handle the enhanced descriptors.
Copyright (C) 2007-2009 STMicroelectronics Ltd
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Author: Giuseppe Cavallaro <peppe.cavallaro@st.com>
*******************************************************************************/
#include "common.h"
#include "descs_com.h"
static int enh_desc_get_tx_status(void *data, struct stmmac_extra_stats *x,
struct dma_desc *p, void __iomem *ioaddr)
{
int ret = 0;
struct net_device_stats *stats = (struct net_device_stats *)data;
if (unlikely(p->des01.etx.error_summary)) {
CHIP_DBG(KERN_ERR "GMAC TX error... 0x%08x\n", p->des01.etx);
if (unlikely(p->des01.etx.jabber_timeout)) {
CHIP_DBG(KERN_ERR "\tjabber_timeout error\n");
x->tx_jabber++;
}
if (unlikely(p->des01.etx.frame_flushed)) {
CHIP_DBG(KERN_ERR "\tframe_flushed error\n");
x->tx_frame_flushed++;
dwmac_dma_flush_tx_fifo(ioaddr);
}
if (unlikely(p->des01.etx.loss_carrier)) {
CHIP_DBG(KERN_ERR "\tloss_carrier error\n");
x->tx_losscarrier++;
stats->tx_carrier_errors++;
}
if (unlikely(p->des01.etx.no_carrier)) {
CHIP_DBG(KERN_ERR "\tno_carrier error\n");
x->tx_carrier++;
stats->tx_carrier_errors++;
}
if (unlikely(p->des01.etx.late_collision)) {
CHIP_DBG(KERN_ERR "\tlate_collision error\n");
stats->collisions += p->des01.etx.collision_count;
}
if (unlikely(p->des01.etx.excessive_collisions)) {
CHIP_DBG(KERN_ERR "\texcessive_collisions\n");
stats->collisions += p->des01.etx.collision_count;
}
if (unlikely(p->des01.etx.excessive_deferral)) {
CHIP_DBG(KERN_INFO "\texcessive tx_deferral\n");
x->tx_deferred++;
}
if (unlikely(p->des01.etx.underflow_error)) {
CHIP_DBG(KERN_ERR "\tunderflow error\n");
dwmac_dma_flush_tx_fifo(ioaddr);
x->tx_underflow++;
}
if (unlikely(p->des01.etx.ip_header_error)) {
CHIP_DBG(KERN_ERR "\tTX IP header csum error\n");
x->tx_ip_header_error++;
}
if (unlikely(p->des01.etx.payload_error)) {
CHIP_DBG(KERN_ERR "\tAddr/Payload csum error\n");
x->tx_payload_error++;
dwmac_dma_flush_tx_fifo(ioaddr);
}
ret = -1;
}
if (unlikely(p->des01.etx.deferred)) {
CHIP_DBG(KERN_INFO "GMAC TX status: tx deferred\n");
x->tx_deferred++;
}
#ifdef STMMAC_VLAN_TAG_USED
if (p->des01.etx.vlan_frame) {
CHIP_DBG(KERN_INFO "GMAC TX status: VLAN frame\n");
x->tx_vlan++;
}
#endif
return ret;
}
static int enh_desc_get_tx_len(struct dma_desc *p)
{
return p->des01.etx.buffer1_size;
}
static int enh_desc_coe_rdes0(int ipc_err, int type, int payload_err)
{
int ret = good_frame;
u32 status = (type << 2 | ipc_err << 1 | payload_err) & 0x7;
/* bits 5 7 0 | Frame status
* ----------------------------------------------------------
* 0 0 0 | IEEE 802.3 Type frame (length < 1536 octects)
* 1 0 0 | IPv4/6 No CSUM errorS.
* 1 0 1 | IPv4/6 CSUM PAYLOAD error
* 1 1 0 | IPv4/6 CSUM IP HR error
* 1 1 1 | IPv4/6 IP PAYLOAD AND HEADER errorS
* 0 0 1 | IPv4/6 unsupported IP PAYLOAD
* 0 1 1 | COE bypassed.. no IPv4/6 frame
* 0 1 0 | Reserved.
*/
if (status == 0x0) {
CHIP_DBG(KERN_INFO "RX Des0 status: IEEE 802.3 Type frame.\n");
ret = llc_snap;
} else if (status == 0x4) {
CHIP_DBG(KERN_INFO "RX Des0 status: IPv4/6 No CSUM errorS.\n");
ret = good_frame;
} else if (status == 0x5) {
CHIP_DBG(KERN_ERR "RX Des0 status: IPv4/6 Payload Error.\n");
ret = csum_none;
} else if (status == 0x6) {
CHIP_DBG(KERN_ERR "RX Des0 status: IPv4/6 Header Error.\n");
ret = csum_none;
} else if (status == 0x7) {
CHIP_DBG(KERN_ERR
"RX Des0 status: IPv4/6 Header and Payload Error.\n");
ret = csum_none;
} else if (status == 0x1) {
CHIP_DBG(KERN_ERR
"RX Des0 status: IPv4/6 unsupported IP PAYLOAD.\n");
ret = discard_frame;
} else if (status == 0x3) {
CHIP_DBG(KERN_ERR "RX Des0 status: No IPv4, IPv6 frame.\n");
ret = discard_frame;
}
return ret;
}
static int enh_desc_get_rx_status(void *data, struct stmmac_extra_stats *x,
struct dma_desc *p)
{
int ret = good_frame;
struct net_device_stats *stats = (struct net_device_stats *)data;
if (unlikely(p->des01.erx.error_summary)) {
CHIP_DBG(KERN_ERR "GMAC RX Error Summary 0x%08x\n",
p->des01.erx);
if (unlikely(p->des01.erx.descriptor_error)) {
CHIP_DBG(KERN_ERR "\tdescriptor error\n");
x->rx_desc++;
stats->rx_length_errors++;
}
if (unlikely(p->des01.erx.overflow_error)) {
CHIP_DBG(KERN_ERR "\toverflow error\n");
x->rx_gmac_overflow++;
}
if (unlikely(p->des01.erx.ipc_csum_error))
CHIP_DBG(KERN_ERR "\tIPC Csum Error/Giant frame\n");
if (unlikely(p->des01.erx.late_collision)) {
CHIP_DBG(KERN_ERR "\tlate_collision error\n");
stats->collisions++;
stats->collisions++;
}
if (unlikely(p->des01.erx.receive_watchdog)) {
CHIP_DBG(KERN_ERR "\treceive_watchdog error\n");
x->rx_watchdog++;
}
if (unlikely(p->des01.erx.error_gmii)) {
CHIP_DBG(KERN_ERR "\tReceive Error\n");
x->rx_mii++;
}
if (unlikely(p->des01.erx.crc_error)) {
CHIP_DBG(KERN_ERR "\tCRC error\n");
x->rx_crc++;
stats->rx_crc_errors++;
}
ret = discard_frame;
}
/* After a payload csum error, the ES bit is set.
* It doesn't match with the information reported into the databook.
* At any rate, we need to understand if the CSUM hw computation is ok
* and report this info to the upper layers. */
ret = enh_desc_coe_rdes0(p->des01.erx.ipc_csum_error,
p->des01.erx.frame_type, p->des01.erx.payload_csum_error);
if (unlikely(p->des01.erx.dribbling)) {
CHIP_DBG(KERN_ERR "GMAC RX: dribbling error\n");
x->dribbling_bit++;
}
if (unlikely(p->des01.erx.sa_filter_fail)) {
CHIP_DBG(KERN_ERR "GMAC RX : Source Address filter fail\n");
x->sa_rx_filter_fail++;
ret = discard_frame;
}
if (unlikely(p->des01.erx.da_filter_fail)) {
CHIP_DBG(KERN_ERR "GMAC RX : Dest Address filter fail\n");
x->da_rx_filter_fail++;
ret = discard_frame;
}
if (unlikely(p->des01.erx.length_error)) {
CHIP_DBG(KERN_ERR "GMAC RX: length_error error\n");
x->rx_length++;
ret = discard_frame;
}
#ifdef STMMAC_VLAN_TAG_USED
if (p->des01.erx.vlan_tag) {
CHIP_DBG(KERN_INFO "GMAC RX: VLAN frame tagged\n");
x->rx_vlan++;
}
#endif
return ret;
}
static void enh_desc_init_rx_desc(struct dma_desc *p, unsigned int ring_size,
int disable_rx_ic)
{
int i;
for (i = 0; i < ring_size; i++) {
p->des01.erx.own = 1;
p->des01.erx.buffer1_size = BUF_SIZE_8KiB - 1;
ehn_desc_rx_set_on_ring_chain(p, (i == ring_size - 1));
if (disable_rx_ic)
p->des01.erx.disable_ic = 1;
p++;
}
}
static void enh_desc_init_tx_desc(struct dma_desc *p, unsigned int ring_size)
{
int i;
for (i = 0; i < ring_size; i++) {
p->des01.etx.own = 0;
ehn_desc_tx_set_on_ring_chain(p, (i == ring_size - 1));
p++;
}
}
static int enh_desc_get_tx_owner(struct dma_desc *p)
{
return p->des01.etx.own;
}
static int enh_desc_get_rx_owner(struct dma_desc *p)
{
return p->des01.erx.own;
}
static void enh_desc_set_tx_owner(struct dma_desc *p)
{
p->des01.etx.own = 1;
}
static void enh_desc_set_rx_owner(struct dma_desc *p)
{
p->des01.erx.own = 1;
}
static int enh_desc_get_tx_ls(struct dma_desc *p)
{
return p->des01.etx.last_segment;
}
static void enh_desc_release_tx_desc(struct dma_desc *p)
{
int ter = p->des01.etx.end_ring;
memset(p, 0, offsetof(struct dma_desc, des2));
enh_desc_end_tx_desc(p, ter);
}
static void enh_desc_prepare_tx_desc(struct dma_desc *p, int is_fs, int len,
int csum_flag)
{
p->des01.etx.first_segment = is_fs;
enh_set_tx_desc_len(p, len);
if (likely(csum_flag))
p->des01.etx.checksum_insertion = cic_full;
}
static void enh_desc_clear_tx_ic(struct dma_desc *p)
{
p->des01.etx.interrupt = 0;
}
static void enh_desc_close_tx_desc(struct dma_desc *p)
{
p->des01.etx.last_segment = 1;
p->des01.etx.interrupt = 1;
}
static int enh_desc_get_rx_frame_len(struct dma_desc *p)
{
return p->des01.erx.frame_length;
}
const struct stmmac_desc_ops enh_desc_ops = {
.tx_status = enh_desc_get_tx_status,
.rx_status = enh_desc_get_rx_status,
.get_tx_len = enh_desc_get_tx_len,
.init_rx_desc = enh_desc_init_rx_desc,
.init_tx_desc = enh_desc_init_tx_desc,
.get_tx_owner = enh_desc_get_tx_owner,
.get_rx_owner = enh_desc_get_rx_owner,
.release_tx_desc = enh_desc_release_tx_desc,
.prepare_tx_desc = enh_desc_prepare_tx_desc,
.clear_tx_ic = enh_desc_clear_tx_ic,
.close_tx_desc = enh_desc_close_tx_desc,
.get_tx_ls = enh_desc_get_tx_ls,
.set_tx_owner = enh_desc_set_tx_owner,
.set_rx_owner = enh_desc_set_rx_owner,
.get_rx_frame_len = enh_desc_get_rx_frame_len,
};
| gpl-2.0 |
invisiblek/android_kernel_sony_sonys4 | drivers/usb/serial/cyberjack.c | 4810 | 13003 | /*
* REINER SCT cyberJack pinpad/e-com USB Chipcard Reader Driver
*
* Copyright (C) 2001 REINER SCT
* Author: Matthias Bruestle
*
* Contact: support@reiner-sct.com (see MAINTAINERS)
*
* This program is largely derived from work by the linux-usb group
* and associated source files. Please see the usb/serial files for
* individual credits and copyrights.
*
* 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.
*
* Thanks to Greg Kroah-Hartman (greg@kroah.com) for his help and
* patience.
*
* In case of problems, please write to the contact e-mail address
* mentioned above.
*
* Please note that later models of the cyberjack reader family are
* supported by a libusb-based userspace device driver.
*
* Homepage: http://www.reiner-sct.de/support/treiber_cyberjack.php#linux
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
#define CYBERJACK_LOCAL_BUF_SIZE 32
static bool debug;
/*
* Version Information
*/
#define DRIVER_VERSION "v1.01"
#define DRIVER_AUTHOR "Matthias Bruestle"
#define DRIVER_DESC "REINER SCT cyberJack pinpad/e-com USB Chipcard Reader Driver"
#define CYBERJACK_VENDOR_ID 0x0C4B
#define CYBERJACK_PRODUCT_ID 0x0100
/* Function prototypes */
static int cyberjack_startup(struct usb_serial *serial);
static void cyberjack_disconnect(struct usb_serial *serial);
static void cyberjack_release(struct usb_serial *serial);
static int cyberjack_open(struct tty_struct *tty,
struct usb_serial_port *port);
static void cyberjack_close(struct usb_serial_port *port);
static int cyberjack_write(struct tty_struct *tty,
struct usb_serial_port *port, const unsigned char *buf, int count);
static int cyberjack_write_room(struct tty_struct *tty);
static void cyberjack_read_int_callback(struct urb *urb);
static void cyberjack_read_bulk_callback(struct urb *urb);
static void cyberjack_write_bulk_callback(struct urb *urb);
static const struct usb_device_id id_table[] = {
{ USB_DEVICE(CYBERJACK_VENDOR_ID, CYBERJACK_PRODUCT_ID) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, id_table);
static struct usb_driver cyberjack_driver = {
.name = "cyberjack",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = id_table,
};
static struct usb_serial_driver cyberjack_device = {
.driver = {
.owner = THIS_MODULE,
.name = "cyberjack",
},
.description = "Reiner SCT Cyberjack USB card reader",
.id_table = id_table,
.num_ports = 1,
.attach = cyberjack_startup,
.disconnect = cyberjack_disconnect,
.release = cyberjack_release,
.open = cyberjack_open,
.close = cyberjack_close,
.write = cyberjack_write,
.write_room = cyberjack_write_room,
.read_int_callback = cyberjack_read_int_callback,
.read_bulk_callback = cyberjack_read_bulk_callback,
.write_bulk_callback = cyberjack_write_bulk_callback,
};
static struct usb_serial_driver * const serial_drivers[] = {
&cyberjack_device, NULL
};
struct cyberjack_private {
spinlock_t lock; /* Lock for SMP */
short rdtodo; /* Bytes still to read */
unsigned char wrbuf[5*64]; /* Buffer for collecting data to write */
short wrfilled; /* Overall data size we already got */
short wrsent; /* Data already sent */
};
/* do some startup allocations not currently performed by usb_serial_probe() */
static int cyberjack_startup(struct usb_serial *serial)
{
struct cyberjack_private *priv;
int i;
dbg("%s", __func__);
/* allocate the private data structure */
priv = kmalloc(sizeof(struct cyberjack_private), GFP_KERNEL);
if (!priv)
return -ENOMEM;
/* set initial values */
spin_lock_init(&priv->lock);
priv->rdtodo = 0;
priv->wrfilled = 0;
priv->wrsent = 0;
usb_set_serial_port_data(serial->port[0], priv);
init_waitqueue_head(&serial->port[0]->write_wait);
for (i = 0; i < serial->num_ports; ++i) {
int result;
result = usb_submit_urb(serial->port[i]->interrupt_in_urb,
GFP_KERNEL);
if (result)
dev_err(&serial->dev->dev,
"usb_submit_urb(read int) failed\n");
dbg("%s - usb_submit_urb(int urb)", __func__);
}
return 0;
}
static void cyberjack_disconnect(struct usb_serial *serial)
{
int i;
dbg("%s", __func__);
for (i = 0; i < serial->num_ports; ++i)
usb_kill_urb(serial->port[i]->interrupt_in_urb);
}
static void cyberjack_release(struct usb_serial *serial)
{
int i;
dbg("%s", __func__);
for (i = 0; i < serial->num_ports; ++i) {
/* My special items, the standard routines free my urbs */
kfree(usb_get_serial_port_data(serial->port[i]));
}
}
static int cyberjack_open(struct tty_struct *tty,
struct usb_serial_port *port)
{
struct cyberjack_private *priv;
unsigned long flags;
int result = 0;
dbg("%s - port %d", __func__, port->number);
dbg("%s - usb_clear_halt", __func__);
usb_clear_halt(port->serial->dev, port->write_urb->pipe);
priv = usb_get_serial_port_data(port);
spin_lock_irqsave(&priv->lock, flags);
priv->rdtodo = 0;
priv->wrfilled = 0;
priv->wrsent = 0;
spin_unlock_irqrestore(&priv->lock, flags);
return result;
}
static void cyberjack_close(struct usb_serial_port *port)
{
dbg("%s - port %d", __func__, port->number);
if (port->serial->dev) {
/* shutdown any bulk reads that might be going on */
usb_kill_urb(port->write_urb);
usb_kill_urb(port->read_urb);
}
}
static int cyberjack_write(struct tty_struct *tty,
struct usb_serial_port *port, const unsigned char *buf, int count)
{
struct cyberjack_private *priv = usb_get_serial_port_data(port);
unsigned long flags;
int result;
int wrexpected;
dbg("%s - port %d", __func__, port->number);
if (count == 0) {
dbg("%s - write request of 0 bytes", __func__);
return 0;
}
if (!test_and_clear_bit(0, &port->write_urbs_free)) {
dbg("%s - already writing", __func__);
return 0;
}
spin_lock_irqsave(&priv->lock, flags);
if (count+priv->wrfilled > sizeof(priv->wrbuf)) {
/* To much data for buffer. Reset buffer. */
priv->wrfilled = 0;
spin_unlock_irqrestore(&priv->lock, flags);
set_bit(0, &port->write_urbs_free);
return 0;
}
/* Copy data */
memcpy(priv->wrbuf + priv->wrfilled, buf, count);
usb_serial_debug_data(debug, &port->dev, __func__, count,
priv->wrbuf + priv->wrfilled);
priv->wrfilled += count;
if (priv->wrfilled >= 3) {
wrexpected = ((int)priv->wrbuf[2]<<8)+priv->wrbuf[1]+3;
dbg("%s - expected data: %d", __func__, wrexpected);
} else
wrexpected = sizeof(priv->wrbuf);
if (priv->wrfilled >= wrexpected) {
/* We have enough data to begin transmission */
int length;
dbg("%s - transmitting data (frame 1)", __func__);
length = (wrexpected > port->bulk_out_size) ?
port->bulk_out_size : wrexpected;
memcpy(port->write_urb->transfer_buffer, priv->wrbuf, length);
priv->wrsent = length;
/* set up our urb */
port->write_urb->transfer_buffer_length = length;
/* send the data out the bulk port */
result = usb_submit_urb(port->write_urb, GFP_ATOMIC);
if (result) {
dev_err(&port->dev,
"%s - failed submitting write urb, error %d",
__func__, result);
/* Throw away data. No better idea what to do with it. */
priv->wrfilled = 0;
priv->wrsent = 0;
spin_unlock_irqrestore(&priv->lock, flags);
set_bit(0, &port->write_urbs_free);
return 0;
}
dbg("%s - priv->wrsent=%d", __func__, priv->wrsent);
dbg("%s - priv->wrfilled=%d", __func__, priv->wrfilled);
if (priv->wrsent >= priv->wrfilled) {
dbg("%s - buffer cleaned", __func__);
memset(priv->wrbuf, 0, sizeof(priv->wrbuf));
priv->wrfilled = 0;
priv->wrsent = 0;
}
}
spin_unlock_irqrestore(&priv->lock, flags);
return count;
}
static int cyberjack_write_room(struct tty_struct *tty)
{
/* FIXME: .... */
return CYBERJACK_LOCAL_BUF_SIZE;
}
static void cyberjack_read_int_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct cyberjack_private *priv = usb_get_serial_port_data(port);
unsigned char *data = urb->transfer_buffer;
int status = urb->status;
int result;
dbg("%s - port %d", __func__, port->number);
/* the urb might have been killed. */
if (status)
return;
usb_serial_debug_data(debug, &port->dev, __func__,
urb->actual_length, data);
/* React only to interrupts signaling a bulk_in transfer */
if (urb->actual_length == 4 && data[0] == 0x01) {
short old_rdtodo;
/* This is a announcement of coming bulk_ins. */
unsigned short size = ((unsigned short)data[3]<<8)+data[2]+3;
spin_lock(&priv->lock);
old_rdtodo = priv->rdtodo;
if (old_rdtodo + size < old_rdtodo) {
dbg("To many bulk_in urbs to do.");
spin_unlock(&priv->lock);
goto resubmit;
}
/* "+=" is probably more fault tollerant than "=" */
priv->rdtodo += size;
dbg("%s - rdtodo: %d", __func__, priv->rdtodo);
spin_unlock(&priv->lock);
if (!old_rdtodo) {
result = usb_submit_urb(port->read_urb, GFP_ATOMIC);
if (result)
dev_err(&port->dev, "%s - failed resubmitting "
"read urb, error %d\n",
__func__, result);
dbg("%s - usb_submit_urb(read urb)", __func__);
}
}
resubmit:
result = usb_submit_urb(port->interrupt_in_urb, GFP_ATOMIC);
if (result)
dev_err(&port->dev, "usb_submit_urb(read int) failed\n");
dbg("%s - usb_submit_urb(int urb)", __func__);
}
static void cyberjack_read_bulk_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct cyberjack_private *priv = usb_get_serial_port_data(port);
struct tty_struct *tty;
unsigned char *data = urb->transfer_buffer;
short todo;
int result;
int status = urb->status;
dbg("%s - port %d", __func__, port->number);
usb_serial_debug_data(debug, &port->dev, __func__,
urb->actual_length, data);
if (status) {
dbg("%s - nonzero read bulk status received: %d",
__func__, status);
return;
}
tty = tty_port_tty_get(&port->port);
if (!tty) {
dbg("%s - ignoring since device not open", __func__);
return;
}
if (urb->actual_length) {
tty_insert_flip_string(tty, data, urb->actual_length);
tty_flip_buffer_push(tty);
}
tty_kref_put(tty);
spin_lock(&priv->lock);
/* Reduce urbs to do by one. */
priv->rdtodo -= urb->actual_length;
/* Just to be sure */
if (priv->rdtodo < 0)
priv->rdtodo = 0;
todo = priv->rdtodo;
spin_unlock(&priv->lock);
dbg("%s - rdtodo: %d", __func__, todo);
/* Continue to read if we have still urbs to do. */
if (todo /* || (urb->actual_length==port->bulk_in_endpointAddress)*/) {
result = usb_submit_urb(port->read_urb, GFP_ATOMIC);
if (result)
dev_err(&port->dev, "%s - failed resubmitting read "
"urb, error %d\n", __func__, result);
dbg("%s - usb_submit_urb(read urb)", __func__);
}
}
static void cyberjack_write_bulk_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct cyberjack_private *priv = usb_get_serial_port_data(port);
int status = urb->status;
dbg("%s - port %d", __func__, port->number);
set_bit(0, &port->write_urbs_free);
if (status) {
dbg("%s - nonzero write bulk status received: %d",
__func__, status);
return;
}
spin_lock(&priv->lock);
/* only do something if we have more data to send */
if (priv->wrfilled) {
int length, blksize, result;
dbg("%s - transmitting data (frame n)", __func__);
length = ((priv->wrfilled - priv->wrsent) > port->bulk_out_size) ?
port->bulk_out_size : (priv->wrfilled - priv->wrsent);
memcpy(port->write_urb->transfer_buffer,
priv->wrbuf + priv->wrsent, length);
priv->wrsent += length;
/* set up our urb */
port->write_urb->transfer_buffer_length = length;
/* send the data out the bulk port */
result = usb_submit_urb(port->write_urb, GFP_ATOMIC);
if (result) {
dev_err(&port->dev,
"%s - failed submitting write urb, error %d\n",
__func__, result);
/* Throw away data. No better idea what to do with it. */
priv->wrfilled = 0;
priv->wrsent = 0;
goto exit;
}
dbg("%s - priv->wrsent=%d", __func__, priv->wrsent);
dbg("%s - priv->wrfilled=%d", __func__, priv->wrfilled);
blksize = ((int)priv->wrbuf[2]<<8)+priv->wrbuf[1]+3;
if (priv->wrsent >= priv->wrfilled ||
priv->wrsent >= blksize) {
dbg("%s - buffer cleaned", __func__);
memset(priv->wrbuf, 0, sizeof(priv->wrbuf));
priv->wrfilled = 0;
priv->wrsent = 0;
}
}
exit:
spin_unlock(&priv->lock);
usb_serial_port_softint(port);
}
module_usb_serial_driver(cyberjack_driver, serial_drivers);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_VERSION(DRIVER_VERSION);
MODULE_LICENSE("GPL");
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");
| gpl-2.0 |
rutvik95/android_kernel_samsung_i9060 | drivers/edac/r82600_edac.c | 4810 | 11844 | /*
* Radisys 82600 Embedded chipset Memory Controller kernel module
* (C) 2005 EADS Astrium
* This file may be distributed under the terms of the
* GNU General Public License.
*
* Written by Tim Small <tim@buttersideup.com>, based on work by Thayne
* Harbaugh, Dan Hollis <goemon at anime dot net> and others.
*
* $Id: edac_r82600.c,v 1.1.2.6 2005/10/05 00:43:44 dsp_llnl Exp $
*
* Written with reference to 82600 High Integration Dual PCI System
* Controller Data Book:
* www.radisys.com/files/support_downloads/007-01277-0002.82600DataBook.pdf
* references to this document given in []
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/edac.h>
#include "edac_core.h"
#define R82600_REVISION " Ver: 2.0.2"
#define EDAC_MOD_STR "r82600_edac"
#define r82600_printk(level, fmt, arg...) \
edac_printk(level, "r82600", fmt, ##arg)
#define r82600_mc_printk(mci, level, fmt, arg...) \
edac_mc_chipset_printk(mci, level, "r82600", fmt, ##arg)
/* Radisys say "The 82600 integrates a main memory SDRAM controller that
* supports up to four banks of memory. The four banks can support a mix of
* sizes of 64 bit wide (72 bits with ECC) Synchronous DRAM (SDRAM) DIMMs,
* each of which can be any size from 16MB to 512MB. Both registered (control
* signals buffered) and unbuffered DIMM types are supported. Mixing of
* registered and unbuffered DIMMs as well as mixing of ECC and non-ECC DIMMs
* is not allowed. The 82600 SDRAM interface operates at the same frequency as
* the CPU bus, 66MHz, 100MHz or 133MHz."
*/
#define R82600_NR_CSROWS 4
#define R82600_NR_CHANS 1
#define R82600_NR_DIMMS 4
#define R82600_BRIDGE_ID 0x8200
/* Radisys 82600 register addresses - device 0 function 0 - PCI bridge */
#define R82600_DRAMC 0x57 /* Various SDRAM related control bits
* all bits are R/W
*
* 7 SDRAM ISA Hole Enable
* 6 Flash Page Mode Enable
* 5 ECC Enable: 1=ECC 0=noECC
* 4 DRAM DIMM Type: 1=
* 3 BIOS Alias Disable
* 2 SDRAM BIOS Flash Write Enable
* 1:0 SDRAM Refresh Rate: 00=Disabled
* 01=7.8usec (256Mbit SDRAMs)
* 10=15.6us 11=125usec
*/
#define R82600_SDRAMC 0x76 /* "SDRAM Control Register"
* More SDRAM related control bits
* all bits are R/W
*
* 15:8 Reserved.
*
* 7:5 Special SDRAM Mode Select
*
* 4 Force ECC
*
* 1=Drive ECC bits to 0 during
* write cycles (i.e. ECC test mode)
*
* 0=Normal ECC functioning
*
* 3 Enhanced Paging Enable
*
* 2 CAS# Latency 0=3clks 1=2clks
*
* 1 RAS# to CAS# Delay 0=3 1=2
*
* 0 RAS# Precharge 0=3 1=2
*/
#define R82600_EAP 0x80 /* ECC Error Address Pointer Register
*
* 31 Disable Hardware Scrubbing (RW)
* 0=Scrub on corrected read
* 1=Don't scrub on corrected read
*
* 30:12 Error Address Pointer (RO)
* Upper 19 bits of error address
*
* 11:4 Syndrome Bits (RO)
*
* 3 BSERR# on multibit error (RW)
* 1=enable 0=disable
*
* 2 NMI on Single Bit Eror (RW)
* 1=NMI triggered by SBE n.b. other
* prerequeists
* 0=NMI not triggered
*
* 1 MBE (R/WC)
* read 1=MBE at EAP (see above)
* read 0=no MBE, or SBE occurred first
* write 1=Clear MBE status (must also
* clear SBE)
* write 0=NOP
*
* 1 SBE (R/WC)
* read 1=SBE at EAP (see above)
* read 0=no SBE, or MBE occurred first
* write 1=Clear SBE status (must also
* clear MBE)
* write 0=NOP
*/
#define R82600_DRBA 0x60 /* + 0x60..0x63 SDRAM Row Boundary Address
* Registers
*
* 7:0 Address lines 30:24 - upper limit of
* each row [p57]
*/
struct r82600_error_info {
u32 eapr;
};
static bool disable_hardware_scrub;
static struct edac_pci_ctl_info *r82600_pci;
static void r82600_get_error_info(struct mem_ctl_info *mci,
struct r82600_error_info *info)
{
struct pci_dev *pdev;
pdev = to_pci_dev(mci->dev);
pci_read_config_dword(pdev, R82600_EAP, &info->eapr);
if (info->eapr & BIT(0))
/* Clear error to allow next error to be reported [p.62] */
pci_write_bits32(pdev, R82600_EAP,
((u32) BIT(0) & (u32) BIT(1)),
((u32) BIT(0) & (u32) BIT(1)));
if (info->eapr & BIT(1))
/* Clear error to allow next error to be reported [p.62] */
pci_write_bits32(pdev, R82600_EAP,
((u32) BIT(0) & (u32) BIT(1)),
((u32) BIT(0) & (u32) BIT(1)));
}
static int r82600_process_error_info(struct mem_ctl_info *mci,
struct r82600_error_info *info,
int handle_errors)
{
int error_found;
u32 eapaddr, page;
u32 syndrome;
error_found = 0;
/* bits 30:12 store the upper 19 bits of the 32 bit error address */
eapaddr = ((info->eapr >> 12) & 0x7FFF) << 13;
/* Syndrome in bits 11:4 [p.62] */
syndrome = (info->eapr >> 4) & 0xFF;
/* the R82600 reports at less than page *
* granularity (upper 19 bits only) */
page = eapaddr >> PAGE_SHIFT;
if (info->eapr & BIT(0)) { /* CE? */
error_found = 1;
if (handle_errors)
edac_mc_handle_ce(mci, page, 0, /* not avail */
syndrome,
edac_mc_find_csrow_by_page(mci, page),
0, mci->ctl_name);
}
if (info->eapr & BIT(1)) { /* UE? */
error_found = 1;
if (handle_errors)
/* 82600 doesn't give enough info */
edac_mc_handle_ue(mci, page, 0,
edac_mc_find_csrow_by_page(mci, page),
mci->ctl_name);
}
return error_found;
}
static void r82600_check(struct mem_ctl_info *mci)
{
struct r82600_error_info info;
debugf1("MC%d: %s()\n", mci->mc_idx, __func__);
r82600_get_error_info(mci, &info);
r82600_process_error_info(mci, &info, 1);
}
static inline int ecc_enabled(u8 dramcr)
{
return dramcr & BIT(5);
}
static void r82600_init_csrows(struct mem_ctl_info *mci, struct pci_dev *pdev,
u8 dramcr)
{
struct csrow_info *csrow;
int index;
u8 drbar; /* SDRAM Row Boundary Address Register */
u32 row_high_limit, row_high_limit_last;
u32 reg_sdram, ecc_on, row_base;
ecc_on = ecc_enabled(dramcr);
reg_sdram = dramcr & BIT(4);
row_high_limit_last = 0;
for (index = 0; index < mci->nr_csrows; index++) {
csrow = &mci->csrows[index];
/* find the DRAM Chip Select Base address and mask */
pci_read_config_byte(pdev, R82600_DRBA + index, &drbar);
debugf1("%s() Row=%d DRBA = %#0x\n", __func__, index, drbar);
row_high_limit = ((u32) drbar << 24);
/* row_high_limit = ((u32)drbar << 24) | 0xffffffUL; */
debugf1("%s() Row=%d, Boundary Address=%#0x, Last = %#0x\n",
__func__, index, row_high_limit, row_high_limit_last);
/* Empty row [p.57] */
if (row_high_limit == row_high_limit_last)
continue;
row_base = row_high_limit_last;
csrow->first_page = row_base >> PAGE_SHIFT;
csrow->last_page = (row_high_limit >> PAGE_SHIFT) - 1;
csrow->nr_pages = csrow->last_page - csrow->first_page + 1;
/* Error address is top 19 bits - so granularity is *
* 14 bits */
csrow->grain = 1 << 14;
csrow->mtype = reg_sdram ? MEM_RDDR : MEM_DDR;
/* FIXME - check that this is unknowable with this chipset */
csrow->dtype = DEV_UNKNOWN;
/* Mode is global on 82600 */
csrow->edac_mode = ecc_on ? EDAC_SECDED : EDAC_NONE;
row_high_limit_last = row_high_limit;
}
}
static int r82600_probe1(struct pci_dev *pdev, int dev_idx)
{
struct mem_ctl_info *mci;
u8 dramcr;
u32 eapr;
u32 scrub_disabled;
u32 sdram_refresh_rate;
struct r82600_error_info discard;
debugf0("%s()\n", __func__);
pci_read_config_byte(pdev, R82600_DRAMC, &dramcr);
pci_read_config_dword(pdev, R82600_EAP, &eapr);
scrub_disabled = eapr & BIT(31);
sdram_refresh_rate = dramcr & (BIT(0) | BIT(1));
debugf2("%s(): sdram refresh rate = %#0x\n", __func__,
sdram_refresh_rate);
debugf2("%s(): DRAMC register = %#0x\n", __func__, dramcr);
mci = edac_mc_alloc(0, R82600_NR_CSROWS, R82600_NR_CHANS, 0);
if (mci == NULL)
return -ENOMEM;
debugf0("%s(): mci = %p\n", __func__, mci);
mci->dev = &pdev->dev;
mci->mtype_cap = MEM_FLAG_RDDR | MEM_FLAG_DDR;
mci->edac_ctl_cap = EDAC_FLAG_NONE | EDAC_FLAG_EC | EDAC_FLAG_SECDED;
/* FIXME try to work out if the chip leads have been used for COM2
* instead on this board? [MA6?] MAYBE:
*/
/* On the R82600, the pins for memory bits 72:65 - i.e. the *
* EC bits are shared with the pins for COM2 (!), so if COM2 *
* is enabled, we assume COM2 is wired up, and thus no EDAC *
* is possible. */
mci->edac_cap = EDAC_FLAG_NONE | EDAC_FLAG_EC | EDAC_FLAG_SECDED;
if (ecc_enabled(dramcr)) {
if (scrub_disabled)
debugf3("%s(): mci = %p - Scrubbing disabled! EAP: "
"%#0x\n", __func__, mci, eapr);
} else
mci->edac_cap = EDAC_FLAG_NONE;
mci->mod_name = EDAC_MOD_STR;
mci->mod_ver = R82600_REVISION;
mci->ctl_name = "R82600";
mci->dev_name = pci_name(pdev);
mci->edac_check = r82600_check;
mci->ctl_page_to_phys = NULL;
r82600_init_csrows(mci, pdev, dramcr);
r82600_get_error_info(mci, &discard); /* clear counters */
/* Here we assume that we will never see multiple instances of this
* type of memory controller. The ID is therefore hardcoded to 0.
*/
if (edac_mc_add_mc(mci)) {
debugf3("%s(): failed edac_mc_add_mc()\n", __func__);
goto fail;
}
/* get this far and it's successful */
if (disable_hardware_scrub) {
debugf3("%s(): Disabling Hardware Scrub (scrub on error)\n",
__func__);
pci_write_bits32(pdev, R82600_EAP, BIT(31), BIT(31));
}
/* allocating generic PCI control info */
r82600_pci = edac_pci_create_generic_ctl(&pdev->dev, EDAC_MOD_STR);
if (!r82600_pci) {
printk(KERN_WARNING
"%s(): Unable to create PCI control\n",
__func__);
printk(KERN_WARNING
"%s(): PCI error report via EDAC not setup\n",
__func__);
}
debugf3("%s(): success\n", __func__);
return 0;
fail:
edac_mc_free(mci);
return -ENODEV;
}
/* returns count (>= 0), or negative on error */
static int __devinit r82600_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
debugf0("%s()\n", __func__);
/* don't need to call pci_enable_device() */
return r82600_probe1(pdev, ent->driver_data);
}
static void __devexit r82600_remove_one(struct pci_dev *pdev)
{
struct mem_ctl_info *mci;
debugf0("%s()\n", __func__);
if (r82600_pci)
edac_pci_release_generic_ctl(r82600_pci);
if ((mci = edac_mc_del_mc(&pdev->dev)) == NULL)
return;
edac_mc_free(mci);
}
static DEFINE_PCI_DEVICE_TABLE(r82600_pci_tbl) = {
{
PCI_DEVICE(PCI_VENDOR_ID_RADISYS, R82600_BRIDGE_ID)
},
{
0,
} /* 0 terminated list. */
};
MODULE_DEVICE_TABLE(pci, r82600_pci_tbl);
static struct pci_driver r82600_driver = {
.name = EDAC_MOD_STR,
.probe = r82600_init_one,
.remove = __devexit_p(r82600_remove_one),
.id_table = r82600_pci_tbl,
};
static int __init r82600_init(void)
{
/* Ensure that the OPSTATE is set correctly for POLL or NMI */
opstate_init();
return pci_register_driver(&r82600_driver);
}
static void __exit r82600_exit(void)
{
pci_unregister_driver(&r82600_driver);
}
module_init(r82600_init);
module_exit(r82600_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Tim Small <tim@buttersideup.com> - WPAD Ltd. "
"on behalf of EADS Astrium");
MODULE_DESCRIPTION("MC support for Radisys 82600 memory controllers");
module_param(disable_hardware_scrub, bool, 0644);
MODULE_PARM_DESC(disable_hardware_scrub,
"If set, disable the chipset's automatic scrub for CEs");
module_param(edac_op_state, int, 0444);
MODULE_PARM_DESC(edac_op_state, "EDAC Error Reporting state: 0=Poll,1=NMI");
| gpl-2.0 |
sktjdgns1189/android_kernel_samsung_jalteskt | drivers/edac/i82875p_edac.c | 4810 | 14868 | /*
* Intel D82875P Memory Controller kernel module
* (C) 2003 Linux Networx (http://lnxi.com)
* This file may be distributed under the terms of the
* GNU General Public License.
*
* Written by Thayne Harbaugh
* Contributors:
* Wang Zhenyu at intel.com
*
* $Id: edac_i82875p.c,v 1.5.2.11 2005/10/05 00:43:44 dsp_llnl Exp $
*
* Note: E7210 appears same as D82875P - zhenyu.z.wang at intel.com
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/edac.h>
#include "edac_core.h"
#define I82875P_REVISION " Ver: 2.0.2"
#define EDAC_MOD_STR "i82875p_edac"
#define i82875p_printk(level, fmt, arg...) \
edac_printk(level, "i82875p", fmt, ##arg)
#define i82875p_mc_printk(mci, level, fmt, arg...) \
edac_mc_chipset_printk(mci, level, "i82875p", fmt, ##arg)
#ifndef PCI_DEVICE_ID_INTEL_82875_0
#define PCI_DEVICE_ID_INTEL_82875_0 0x2578
#endif /* PCI_DEVICE_ID_INTEL_82875_0 */
#ifndef PCI_DEVICE_ID_INTEL_82875_6
#define PCI_DEVICE_ID_INTEL_82875_6 0x257e
#endif /* PCI_DEVICE_ID_INTEL_82875_6 */
/* four csrows in dual channel, eight in single channel */
#define I82875P_NR_CSROWS(nr_chans) (8/(nr_chans))
/* Intel 82875p register addresses - device 0 function 0 - DRAM Controller */
#define I82875P_EAP 0x58 /* Error Address Pointer (32b)
*
* 31:12 block address
* 11:0 reserved
*/
#define I82875P_DERRSYN 0x5c /* DRAM Error Syndrome (8b)
*
* 7:0 DRAM ECC Syndrome
*/
#define I82875P_DES 0x5d /* DRAM Error Status (8b)
*
* 7:1 reserved
* 0 Error channel 0/1
*/
#define I82875P_ERRSTS 0xc8 /* Error Status Register (16b)
*
* 15:10 reserved
* 9 non-DRAM lock error (ndlock)
* 8 Sftwr Generated SMI
* 7 ECC UE
* 6 reserved
* 5 MCH detects unimplemented cycle
* 4 AGP access outside GA
* 3 Invalid AGP access
* 2 Invalid GA translation table
* 1 Unsupported AGP command
* 0 ECC CE
*/
#define I82875P_ERRCMD 0xca /* Error Command (16b)
*
* 15:10 reserved
* 9 SERR on non-DRAM lock
* 8 SERR on ECC UE
* 7 SERR on ECC CE
* 6 target abort on high exception
* 5 detect unimplemented cyc
* 4 AGP access outside of GA
* 3 SERR on invalid AGP access
* 2 invalid translation table
* 1 SERR on unsupported AGP command
* 0 reserved
*/
/* Intel 82875p register addresses - device 6 function 0 - DRAM Controller */
#define I82875P_PCICMD6 0x04 /* PCI Command Register (16b)
*
* 15:10 reserved
* 9 fast back-to-back - ro 0
* 8 SERR enable - ro 0
* 7 addr/data stepping - ro 0
* 6 parity err enable - ro 0
* 5 VGA palette snoop - ro 0
* 4 mem wr & invalidate - ro 0
* 3 special cycle - ro 0
* 2 bus master - ro 0
* 1 mem access dev6 - 0(dis),1(en)
* 0 IO access dev3 - 0(dis),1(en)
*/
#define I82875P_BAR6 0x10 /* Mem Delays Base ADDR Reg (32b)
*
* 31:12 mem base addr [31:12]
* 11:4 address mask - ro 0
* 3 prefetchable - ro 0(non),1(pre)
* 2:1 mem type - ro 0
* 0 mem space - ro 0
*/
/* Intel 82875p MMIO register space - device 0 function 0 - MMR space */
#define I82875P_DRB_SHIFT 26 /* 64MiB grain */
#define I82875P_DRB 0x00 /* DRAM Row Boundary (8b x 8)
*
* 7 reserved
* 6:0 64MiB row boundary addr
*/
#define I82875P_DRA 0x10 /* DRAM Row Attribute (4b x 8)
*
* 7 reserved
* 6:4 row attr row 1
* 3 reserved
* 2:0 row attr row 0
*
* 000 = 4KiB
* 001 = 8KiB
* 010 = 16KiB
* 011 = 32KiB
*/
#define I82875P_DRC 0x68 /* DRAM Controller Mode (32b)
*
* 31:30 reserved
* 29 init complete
* 28:23 reserved
* 22:21 nr chan 00=1,01=2
* 20 reserved
* 19:18 Data Integ Mode 00=none,01=ecc
* 17:11 reserved
* 10:8 refresh mode
* 7 reserved
* 6:4 mode select
* 3:2 reserved
* 1:0 DRAM type 01=DDR
*/
enum i82875p_chips {
I82875P = 0,
};
struct i82875p_pvt {
struct pci_dev *ovrfl_pdev;
void __iomem *ovrfl_window;
};
struct i82875p_dev_info {
const char *ctl_name;
};
struct i82875p_error_info {
u16 errsts;
u32 eap;
u8 des;
u8 derrsyn;
u16 errsts2;
};
static const struct i82875p_dev_info i82875p_devs[] = {
[I82875P] = {
.ctl_name = "i82875p"},
};
static struct pci_dev *mci_pdev; /* init dev: in case that AGP code has
* already registered driver
*/
static struct edac_pci_ctl_info *i82875p_pci;
static void i82875p_get_error_info(struct mem_ctl_info *mci,
struct i82875p_error_info *info)
{
struct pci_dev *pdev;
pdev = to_pci_dev(mci->dev);
/*
* This is a mess because there is no atomic way to read all the
* registers at once and the registers can transition from CE being
* overwritten by UE.
*/
pci_read_config_word(pdev, I82875P_ERRSTS, &info->errsts);
if (!(info->errsts & 0x0081))
return;
pci_read_config_dword(pdev, I82875P_EAP, &info->eap);
pci_read_config_byte(pdev, I82875P_DES, &info->des);
pci_read_config_byte(pdev, I82875P_DERRSYN, &info->derrsyn);
pci_read_config_word(pdev, I82875P_ERRSTS, &info->errsts2);
/*
* If the error is the same then we can for both reads then
* the first set of reads is valid. If there is a change then
* there is a CE no info and the second set of reads is valid
* and should be UE info.
*/
if ((info->errsts ^ info->errsts2) & 0x0081) {
pci_read_config_dword(pdev, I82875P_EAP, &info->eap);
pci_read_config_byte(pdev, I82875P_DES, &info->des);
pci_read_config_byte(pdev, I82875P_DERRSYN, &info->derrsyn);
}
pci_write_bits16(pdev, I82875P_ERRSTS, 0x0081, 0x0081);
}
static int i82875p_process_error_info(struct mem_ctl_info *mci,
struct i82875p_error_info *info,
int handle_errors)
{
int row, multi_chan;
multi_chan = mci->csrows[0].nr_channels - 1;
if (!(info->errsts & 0x0081))
return 0;
if (!handle_errors)
return 1;
if ((info->errsts ^ info->errsts2) & 0x0081) {
edac_mc_handle_ce_no_info(mci, "UE overwrote CE");
info->errsts = info->errsts2;
}
info->eap >>= PAGE_SHIFT;
row = edac_mc_find_csrow_by_page(mci, info->eap);
if (info->errsts & 0x0080)
edac_mc_handle_ue(mci, info->eap, 0, row, "i82875p UE");
else
edac_mc_handle_ce(mci, info->eap, 0, info->derrsyn, row,
multi_chan ? (info->des & 0x1) : 0,
"i82875p CE");
return 1;
}
static void i82875p_check(struct mem_ctl_info *mci)
{
struct i82875p_error_info info;
debugf1("MC%d: %s()\n", mci->mc_idx, __func__);
i82875p_get_error_info(mci, &info);
i82875p_process_error_info(mci, &info, 1);
}
/* Return 0 on success or 1 on failure. */
static int i82875p_setup_overfl_dev(struct pci_dev *pdev,
struct pci_dev **ovrfl_pdev,
void __iomem **ovrfl_window)
{
struct pci_dev *dev;
void __iomem *window;
int err;
*ovrfl_pdev = NULL;
*ovrfl_window = NULL;
dev = pci_get_device(PCI_VEND_DEV(INTEL, 82875_6), NULL);
if (dev == NULL) {
/* Intel tells BIOS developers to hide device 6 which
* configures the overflow device access containing
* the DRBs - this is where we expose device 6.
* http://www.x86-secret.com/articles/tweak/pat/patsecrets-2.htm
*/
pci_write_bits8(pdev, 0xf4, 0x2, 0x2);
dev = pci_scan_single_device(pdev->bus, PCI_DEVFN(6, 0));
if (dev == NULL)
return 1;
err = pci_bus_add_device(dev);
if (err) {
i82875p_printk(KERN_ERR,
"%s(): pci_bus_add_device() Failed\n",
__func__);
}
pci_bus_assign_resources(dev->bus);
}
*ovrfl_pdev = dev;
if (pci_enable_device(dev)) {
i82875p_printk(KERN_ERR, "%s(): Failed to enable overflow "
"device\n", __func__);
return 1;
}
if (pci_request_regions(dev, pci_name(dev))) {
#ifdef CORRECT_BIOS
goto fail0;
#endif
}
/* cache is irrelevant for PCI bus reads/writes */
window = pci_ioremap_bar(dev, 0);
if (window == NULL) {
i82875p_printk(KERN_ERR, "%s(): Failed to ioremap bar6\n",
__func__);
goto fail1;
}
*ovrfl_window = window;
return 0;
fail1:
pci_release_regions(dev);
#ifdef CORRECT_BIOS
fail0:
pci_disable_device(dev);
#endif
/* NOTE: the ovrfl proc entry and pci_dev are intentionally left */
return 1;
}
/* Return 1 if dual channel mode is active. Else return 0. */
static inline int dual_channel_active(u32 drc)
{
return (drc >> 21) & 0x1;
}
static void i82875p_init_csrows(struct mem_ctl_info *mci,
struct pci_dev *pdev,
void __iomem * ovrfl_window, u32 drc)
{
struct csrow_info *csrow;
unsigned long last_cumul_size;
u8 value;
u32 drc_ddim; /* DRAM Data Integrity Mode 0=none,2=edac */
u32 cumul_size;
int index;
drc_ddim = (drc >> 18) & 0x1;
last_cumul_size = 0;
/* The dram row boundary (DRB) reg values are boundary address
* for each DRAM row with a granularity of 32 or 64MB (single/dual
* channel operation). DRB regs are cumulative; therefore DRB7 will
* contain the total memory contained in all eight rows.
*/
for (index = 0; index < mci->nr_csrows; index++) {
csrow = &mci->csrows[index];
value = readb(ovrfl_window + I82875P_DRB + index);
cumul_size = value << (I82875P_DRB_SHIFT - PAGE_SHIFT);
debugf3("%s(): (%d) cumul_size 0x%x\n", __func__, index,
cumul_size);
if (cumul_size == last_cumul_size)
continue; /* not populated */
csrow->first_page = last_cumul_size;
csrow->last_page = cumul_size - 1;
csrow->nr_pages = cumul_size - last_cumul_size;
last_cumul_size = cumul_size;
csrow->grain = 1 << 12; /* I82875P_EAP has 4KiB reolution */
csrow->mtype = MEM_DDR;
csrow->dtype = DEV_UNKNOWN;
csrow->edac_mode = drc_ddim ? EDAC_SECDED : EDAC_NONE;
}
}
static int i82875p_probe1(struct pci_dev *pdev, int dev_idx)
{
int rc = -ENODEV;
struct mem_ctl_info *mci;
struct i82875p_pvt *pvt;
struct pci_dev *ovrfl_pdev;
void __iomem *ovrfl_window;
u32 drc;
u32 nr_chans;
struct i82875p_error_info discard;
debugf0("%s()\n", __func__);
ovrfl_pdev = pci_get_device(PCI_VEND_DEV(INTEL, 82875_6), NULL);
if (i82875p_setup_overfl_dev(pdev, &ovrfl_pdev, &ovrfl_window))
return -ENODEV;
drc = readl(ovrfl_window + I82875P_DRC);
nr_chans = dual_channel_active(drc) + 1;
mci = edac_mc_alloc(sizeof(*pvt), I82875P_NR_CSROWS(nr_chans),
nr_chans, 0);
if (!mci) {
rc = -ENOMEM;
goto fail0;
}
/* Keeps mci available after edac_mc_del_mc() till edac_mc_free() */
kobject_get(&mci->edac_mci_kobj);
debugf3("%s(): init mci\n", __func__);
mci->dev = &pdev->dev;
mci->mtype_cap = MEM_FLAG_DDR;
mci->edac_ctl_cap = EDAC_FLAG_NONE | EDAC_FLAG_SECDED;
mci->edac_cap = EDAC_FLAG_UNKNOWN;
mci->mod_name = EDAC_MOD_STR;
mci->mod_ver = I82875P_REVISION;
mci->ctl_name = i82875p_devs[dev_idx].ctl_name;
mci->dev_name = pci_name(pdev);
mci->edac_check = i82875p_check;
mci->ctl_page_to_phys = NULL;
debugf3("%s(): init pvt\n", __func__);
pvt = (struct i82875p_pvt *)mci->pvt_info;
pvt->ovrfl_pdev = ovrfl_pdev;
pvt->ovrfl_window = ovrfl_window;
i82875p_init_csrows(mci, pdev, ovrfl_window, drc);
i82875p_get_error_info(mci, &discard); /* clear counters */
/* Here we assume that we will never see multiple instances of this
* type of memory controller. The ID is therefore hardcoded to 0.
*/
if (edac_mc_add_mc(mci)) {
debugf3("%s(): failed edac_mc_add_mc()\n", __func__);
goto fail1;
}
/* allocating generic PCI control info */
i82875p_pci = edac_pci_create_generic_ctl(&pdev->dev, EDAC_MOD_STR);
if (!i82875p_pci) {
printk(KERN_WARNING
"%s(): Unable to create PCI control\n",
__func__);
printk(KERN_WARNING
"%s(): PCI error report via EDAC not setup\n",
__func__);
}
/* get this far and it's successful */
debugf3("%s(): success\n", __func__);
return 0;
fail1:
kobject_put(&mci->edac_mci_kobj);
edac_mc_free(mci);
fail0:
iounmap(ovrfl_window);
pci_release_regions(ovrfl_pdev);
pci_disable_device(ovrfl_pdev);
/* NOTE: the ovrfl proc entry and pci_dev are intentionally left */
return rc;
}
/* returns count (>= 0), or negative on error */
static int __devinit i82875p_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
int rc;
debugf0("%s()\n", __func__);
i82875p_printk(KERN_INFO, "i82875p init one\n");
if (pci_enable_device(pdev) < 0)
return -EIO;
rc = i82875p_probe1(pdev, ent->driver_data);
if (mci_pdev == NULL)
mci_pdev = pci_dev_get(pdev);
return rc;
}
static void __devexit i82875p_remove_one(struct pci_dev *pdev)
{
struct mem_ctl_info *mci;
struct i82875p_pvt *pvt = NULL;
debugf0("%s()\n", __func__);
if (i82875p_pci)
edac_pci_release_generic_ctl(i82875p_pci);
if ((mci = edac_mc_del_mc(&pdev->dev)) == NULL)
return;
pvt = (struct i82875p_pvt *)mci->pvt_info;
if (pvt->ovrfl_window)
iounmap(pvt->ovrfl_window);
if (pvt->ovrfl_pdev) {
#ifdef CORRECT_BIOS
pci_release_regions(pvt->ovrfl_pdev);
#endif /*CORRECT_BIOS */
pci_disable_device(pvt->ovrfl_pdev);
pci_dev_put(pvt->ovrfl_pdev);
}
edac_mc_free(mci);
}
static DEFINE_PCI_DEVICE_TABLE(i82875p_pci_tbl) = {
{
PCI_VEND_DEV(INTEL, 82875_0), PCI_ANY_ID, PCI_ANY_ID, 0, 0,
I82875P},
{
0,
} /* 0 terminated list. */
};
MODULE_DEVICE_TABLE(pci, i82875p_pci_tbl);
static struct pci_driver i82875p_driver = {
.name = EDAC_MOD_STR,
.probe = i82875p_init_one,
.remove = __devexit_p(i82875p_remove_one),
.id_table = i82875p_pci_tbl,
};
static int __init i82875p_init(void)
{
int pci_rc;
debugf3("%s()\n", __func__);
/* Ensure that the OPSTATE is set correctly for POLL or NMI */
opstate_init();
pci_rc = pci_register_driver(&i82875p_driver);
if (pci_rc < 0)
goto fail0;
if (mci_pdev == NULL) {
mci_pdev = pci_get_device(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_82875_0, NULL);
if (!mci_pdev) {
debugf0("875p pci_get_device fail\n");
pci_rc = -ENODEV;
goto fail1;
}
pci_rc = i82875p_init_one(mci_pdev, i82875p_pci_tbl);
if (pci_rc < 0) {
debugf0("875p init fail\n");
pci_rc = -ENODEV;
goto fail1;
}
}
return 0;
fail1:
pci_unregister_driver(&i82875p_driver);
fail0:
if (mci_pdev != NULL)
pci_dev_put(mci_pdev);
return pci_rc;
}
static void __exit i82875p_exit(void)
{
debugf3("%s()\n", __func__);
i82875p_remove_one(mci_pdev);
pci_dev_put(mci_pdev);
pci_unregister_driver(&i82875p_driver);
}
module_init(i82875p_init);
module_exit(i82875p_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Linux Networx (http://lnxi.com) Thayne Harbaugh");
MODULE_DESCRIPTION("MC support for Intel 82875 memory hub controllers");
module_param(edac_op_state, int, 0444);
MODULE_PARM_DESC(edac_op_state, "EDAC Error Reporting state: 0=Poll,1=NMI");
| gpl-2.0 |
galaxyfreak/18.6-eagle-stock | net/tipc/msg.c | 4810 | 9962 | /*
* net/tipc/msg.c: TIPC message header routines
*
* Copyright (c) 2000-2006, Ericsson AB
* Copyright (c) 2005, 2010-2011, Wind River Systems
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the names of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "core.h"
#include "msg.h"
u32 tipc_msg_tot_importance(struct tipc_msg *m)
{
if (likely(msg_isdata(m))) {
if (likely(msg_orignode(m) == tipc_own_addr))
return msg_importance(m);
return msg_importance(m) + 4;
}
if ((msg_user(m) == MSG_FRAGMENTER) &&
(msg_type(m) == FIRST_FRAGMENT))
return msg_importance(msg_get_wrapped(m));
return msg_importance(m);
}
void tipc_msg_init(struct tipc_msg *m, u32 user, u32 type,
u32 hsize, u32 destnode)
{
memset(m, 0, hsize);
msg_set_version(m);
msg_set_user(m, user);
msg_set_hdr_sz(m, hsize);
msg_set_size(m, hsize);
msg_set_prevnode(m, tipc_own_addr);
msg_set_type(m, type);
msg_set_orignode(m, tipc_own_addr);
msg_set_destnode(m, destnode);
}
/**
* tipc_msg_build - create message using specified header and data
*
* Note: Caller must not hold any locks in case copy_from_user() is interrupted!
*
* Returns message data size or errno
*/
int tipc_msg_build(struct tipc_msg *hdr, struct iovec const *msg_sect,
u32 num_sect, unsigned int total_len,
int max_size, int usrmem, struct sk_buff **buf)
{
int dsz, sz, hsz, pos, res, cnt;
dsz = total_len;
pos = hsz = msg_hdr_sz(hdr);
sz = hsz + dsz;
msg_set_size(hdr, sz);
if (unlikely(sz > max_size)) {
*buf = NULL;
return dsz;
}
*buf = tipc_buf_acquire(sz);
if (!(*buf))
return -ENOMEM;
skb_copy_to_linear_data(*buf, hdr, hsz);
for (res = 1, cnt = 0; res && (cnt < num_sect); cnt++) {
if (likely(usrmem))
res = !copy_from_user((*buf)->data + pos,
msg_sect[cnt].iov_base,
msg_sect[cnt].iov_len);
else
skb_copy_to_linear_data_offset(*buf, pos,
msg_sect[cnt].iov_base,
msg_sect[cnt].iov_len);
pos += msg_sect[cnt].iov_len;
}
if (likely(res))
return dsz;
kfree_skb(*buf);
*buf = NULL;
return -EFAULT;
}
#ifdef CONFIG_TIPC_DEBUG
void tipc_msg_dbg(struct print_buf *buf, struct tipc_msg *msg, const char *str)
{
u32 usr = msg_user(msg);
tipc_printf(buf, KERN_DEBUG);
tipc_printf(buf, str);
switch (usr) {
case MSG_BUNDLER:
tipc_printf(buf, "BNDL::");
tipc_printf(buf, "MSGS(%u):", msg_msgcnt(msg));
break;
case BCAST_PROTOCOL:
tipc_printf(buf, "BCASTP::");
break;
case MSG_FRAGMENTER:
tipc_printf(buf, "FRAGM::");
switch (msg_type(msg)) {
case FIRST_FRAGMENT:
tipc_printf(buf, "FIRST:");
break;
case FRAGMENT:
tipc_printf(buf, "BODY:");
break;
case LAST_FRAGMENT:
tipc_printf(buf, "LAST:");
break;
default:
tipc_printf(buf, "UNKNOWN:%x", msg_type(msg));
}
tipc_printf(buf, "NO(%u/%u):", msg_long_msgno(msg),
msg_fragm_no(msg));
break;
case TIPC_LOW_IMPORTANCE:
case TIPC_MEDIUM_IMPORTANCE:
case TIPC_HIGH_IMPORTANCE:
case TIPC_CRITICAL_IMPORTANCE:
tipc_printf(buf, "DAT%u:", msg_user(msg));
if (msg_short(msg)) {
tipc_printf(buf, "CON:");
break;
}
switch (msg_type(msg)) {
case TIPC_CONN_MSG:
tipc_printf(buf, "CON:");
break;
case TIPC_MCAST_MSG:
tipc_printf(buf, "MCST:");
break;
case TIPC_NAMED_MSG:
tipc_printf(buf, "NAM:");
break;
case TIPC_DIRECT_MSG:
tipc_printf(buf, "DIR:");
break;
default:
tipc_printf(buf, "UNKNOWN TYPE %u", msg_type(msg));
}
if (msg_reroute_cnt(msg))
tipc_printf(buf, "REROUTED(%u):",
msg_reroute_cnt(msg));
break;
case NAME_DISTRIBUTOR:
tipc_printf(buf, "NMD::");
switch (msg_type(msg)) {
case PUBLICATION:
tipc_printf(buf, "PUBL(%u):", (msg_size(msg) - msg_hdr_sz(msg)) / 20); /* Items */
break;
case WITHDRAWAL:
tipc_printf(buf, "WDRW:");
break;
default:
tipc_printf(buf, "UNKNOWN:%x", msg_type(msg));
}
if (msg_reroute_cnt(msg))
tipc_printf(buf, "REROUTED(%u):",
msg_reroute_cnt(msg));
break;
case CONN_MANAGER:
tipc_printf(buf, "CONN_MNG:");
switch (msg_type(msg)) {
case CONN_PROBE:
tipc_printf(buf, "PROBE:");
break;
case CONN_PROBE_REPLY:
tipc_printf(buf, "PROBE_REPLY:");
break;
case CONN_ACK:
tipc_printf(buf, "CONN_ACK:");
tipc_printf(buf, "ACK(%u):", msg_msgcnt(msg));
break;
default:
tipc_printf(buf, "UNKNOWN TYPE:%x", msg_type(msg));
}
if (msg_reroute_cnt(msg))
tipc_printf(buf, "REROUTED(%u):", msg_reroute_cnt(msg));
break;
case LINK_PROTOCOL:
switch (msg_type(msg)) {
case STATE_MSG:
tipc_printf(buf, "STATE:");
tipc_printf(buf, "%s:", msg_probe(msg) ? "PRB" : "");
tipc_printf(buf, "NXS(%u):", msg_next_sent(msg));
tipc_printf(buf, "GAP(%u):", msg_seq_gap(msg));
tipc_printf(buf, "LSTBC(%u):", msg_last_bcast(msg));
break;
case RESET_MSG:
tipc_printf(buf, "RESET:");
if (msg_size(msg) != msg_hdr_sz(msg))
tipc_printf(buf, "BEAR:%s:", msg_data(msg));
break;
case ACTIVATE_MSG:
tipc_printf(buf, "ACTIVATE:");
break;
default:
tipc_printf(buf, "UNKNOWN TYPE:%x", msg_type(msg));
}
tipc_printf(buf, "PLANE(%c):", msg_net_plane(msg));
tipc_printf(buf, "SESS(%u):", msg_session(msg));
break;
case CHANGEOVER_PROTOCOL:
tipc_printf(buf, "TUNL:");
switch (msg_type(msg)) {
case DUPLICATE_MSG:
tipc_printf(buf, "DUPL:");
break;
case ORIGINAL_MSG:
tipc_printf(buf, "ORIG:");
tipc_printf(buf, "EXP(%u)", msg_msgcnt(msg));
break;
default:
tipc_printf(buf, "UNKNOWN TYPE:%x", msg_type(msg));
}
break;
case LINK_CONFIG:
tipc_printf(buf, "CFG:");
switch (msg_type(msg)) {
case DSC_REQ_MSG:
tipc_printf(buf, "DSC_REQ:");
break;
case DSC_RESP_MSG:
tipc_printf(buf, "DSC_RESP:");
break;
default:
tipc_printf(buf, "UNKNOWN TYPE:%x:", msg_type(msg));
break;
}
break;
default:
tipc_printf(buf, "UNKNOWN USER:");
}
switch (usr) {
case CONN_MANAGER:
case TIPC_LOW_IMPORTANCE:
case TIPC_MEDIUM_IMPORTANCE:
case TIPC_HIGH_IMPORTANCE:
case TIPC_CRITICAL_IMPORTANCE:
switch (msg_errcode(msg)) {
case TIPC_OK:
break;
case TIPC_ERR_NO_NAME:
tipc_printf(buf, "NO_NAME:");
break;
case TIPC_ERR_NO_PORT:
tipc_printf(buf, "NO_PORT:");
break;
case TIPC_ERR_NO_NODE:
tipc_printf(buf, "NO_PROC:");
break;
case TIPC_ERR_OVERLOAD:
tipc_printf(buf, "OVERLOAD:");
break;
case TIPC_CONN_SHUTDOWN:
tipc_printf(buf, "SHUTDOWN:");
break;
default:
tipc_printf(buf, "UNKNOWN ERROR(%x):",
msg_errcode(msg));
}
default:
break;
}
tipc_printf(buf, "HZ(%u):", msg_hdr_sz(msg));
tipc_printf(buf, "SZ(%u):", msg_size(msg));
tipc_printf(buf, "SQNO(%u):", msg_seqno(msg));
if (msg_non_seq(msg))
tipc_printf(buf, "NOSEQ:");
else
tipc_printf(buf, "ACK(%u):", msg_ack(msg));
tipc_printf(buf, "BACK(%u):", msg_bcast_ack(msg));
tipc_printf(buf, "PRND(%x)", msg_prevnode(msg));
if (msg_isdata(msg)) {
if (msg_named(msg)) {
tipc_printf(buf, "NTYP(%u):", msg_nametype(msg));
tipc_printf(buf, "NINST(%u)", msg_nameinst(msg));
}
}
if ((usr != LINK_PROTOCOL) && (usr != LINK_CONFIG) &&
(usr != MSG_BUNDLER)) {
if (!msg_short(msg)) {
tipc_printf(buf, ":ORIG(%x:%u):",
msg_orignode(msg), msg_origport(msg));
tipc_printf(buf, ":DEST(%x:%u):",
msg_destnode(msg), msg_destport(msg));
} else {
tipc_printf(buf, ":OPRT(%u):", msg_origport(msg));
tipc_printf(buf, ":DPRT(%u):", msg_destport(msg));
}
}
if (msg_user(msg) == NAME_DISTRIBUTOR) {
tipc_printf(buf, ":ONOD(%x):", msg_orignode(msg));
tipc_printf(buf, ":DNOD(%x):", msg_destnode(msg));
}
if (msg_user(msg) == LINK_CONFIG) {
struct tipc_media_addr orig;
tipc_printf(buf, ":DDOM(%x):", msg_dest_domain(msg));
tipc_printf(buf, ":NETID(%u):", msg_bc_netid(msg));
memcpy(orig.value, msg_media_addr(msg), sizeof(orig.value));
orig.media_id = 0;
orig.broadcast = 0;
tipc_media_addr_printf(buf, &orig);
}
if (msg_user(msg) == BCAST_PROTOCOL) {
tipc_printf(buf, "BCNACK:AFTER(%u):", msg_bcgap_after(msg));
tipc_printf(buf, "TO(%u):", msg_bcgap_to(msg));
}
tipc_printf(buf, "\n");
if ((usr == CHANGEOVER_PROTOCOL) && (msg_msgcnt(msg)))
tipc_msg_dbg(buf, msg_get_wrapped(msg), " /");
if ((usr == MSG_FRAGMENTER) && (msg_type(msg) == FIRST_FRAGMENT))
tipc_msg_dbg(buf, msg_get_wrapped(msg), " /");
}
#endif
| gpl-2.0 |
binkybear/furnace_kernel_lge_hammerhead | drivers/clocksource/sh_tmu.c | 4810 | 10943 | /*
* SuperH Timer Support - TMU
*
* Copyright (C) 2009 Magnus Damm
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <linux/irq.h>
#include <linux/err.h>
#include <linux/clocksource.h>
#include <linux/clockchips.h>
#include <linux/sh_timer.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/pm_domain.h>
struct sh_tmu_priv {
void __iomem *mapbase;
struct clk *clk;
struct irqaction irqaction;
struct platform_device *pdev;
unsigned long rate;
unsigned long periodic;
struct clock_event_device ced;
struct clocksource cs;
};
static DEFINE_SPINLOCK(sh_tmu_lock);
#define TSTR -1 /* shared register */
#define TCOR 0 /* channel register */
#define TCNT 1 /* channel register */
#define TCR 2 /* channel register */
static inline unsigned long sh_tmu_read(struct sh_tmu_priv *p, int reg_nr)
{
struct sh_timer_config *cfg = p->pdev->dev.platform_data;
void __iomem *base = p->mapbase;
unsigned long offs;
if (reg_nr == TSTR)
return ioread8(base - cfg->channel_offset);
offs = reg_nr << 2;
if (reg_nr == TCR)
return ioread16(base + offs);
else
return ioread32(base + offs);
}
static inline void sh_tmu_write(struct sh_tmu_priv *p, int reg_nr,
unsigned long value)
{
struct sh_timer_config *cfg = p->pdev->dev.platform_data;
void __iomem *base = p->mapbase;
unsigned long offs;
if (reg_nr == TSTR) {
iowrite8(value, base - cfg->channel_offset);
return;
}
offs = reg_nr << 2;
if (reg_nr == TCR)
iowrite16(value, base + offs);
else
iowrite32(value, base + offs);
}
static void sh_tmu_start_stop_ch(struct sh_tmu_priv *p, int start)
{
struct sh_timer_config *cfg = p->pdev->dev.platform_data;
unsigned long flags, value;
/* start stop register shared by multiple timer channels */
spin_lock_irqsave(&sh_tmu_lock, flags);
value = sh_tmu_read(p, TSTR);
if (start)
value |= 1 << cfg->timer_bit;
else
value &= ~(1 << cfg->timer_bit);
sh_tmu_write(p, TSTR, value);
spin_unlock_irqrestore(&sh_tmu_lock, flags);
}
static int sh_tmu_enable(struct sh_tmu_priv *p)
{
int ret;
/* enable clock */
ret = clk_enable(p->clk);
if (ret) {
dev_err(&p->pdev->dev, "cannot enable clock\n");
return ret;
}
/* make sure channel is disabled */
sh_tmu_start_stop_ch(p, 0);
/* maximum timeout */
sh_tmu_write(p, TCOR, 0xffffffff);
sh_tmu_write(p, TCNT, 0xffffffff);
/* configure channel to parent clock / 4, irq off */
p->rate = clk_get_rate(p->clk) / 4;
sh_tmu_write(p, TCR, 0x0000);
/* enable channel */
sh_tmu_start_stop_ch(p, 1);
return 0;
}
static void sh_tmu_disable(struct sh_tmu_priv *p)
{
/* disable channel */
sh_tmu_start_stop_ch(p, 0);
/* disable interrupts in TMU block */
sh_tmu_write(p, TCR, 0x0000);
/* stop clock */
clk_disable(p->clk);
}
static void sh_tmu_set_next(struct sh_tmu_priv *p, unsigned long delta,
int periodic)
{
/* stop timer */
sh_tmu_start_stop_ch(p, 0);
/* acknowledge interrupt */
sh_tmu_read(p, TCR);
/* enable interrupt */
sh_tmu_write(p, TCR, 0x0020);
/* reload delta value in case of periodic timer */
if (periodic)
sh_tmu_write(p, TCOR, delta);
else
sh_tmu_write(p, TCOR, 0xffffffff);
sh_tmu_write(p, TCNT, delta);
/* start timer */
sh_tmu_start_stop_ch(p, 1);
}
static irqreturn_t sh_tmu_interrupt(int irq, void *dev_id)
{
struct sh_tmu_priv *p = dev_id;
/* disable or acknowledge interrupt */
if (p->ced.mode == CLOCK_EVT_MODE_ONESHOT)
sh_tmu_write(p, TCR, 0x0000);
else
sh_tmu_write(p, TCR, 0x0020);
/* notify clockevent layer */
p->ced.event_handler(&p->ced);
return IRQ_HANDLED;
}
static struct sh_tmu_priv *cs_to_sh_tmu(struct clocksource *cs)
{
return container_of(cs, struct sh_tmu_priv, cs);
}
static cycle_t sh_tmu_clocksource_read(struct clocksource *cs)
{
struct sh_tmu_priv *p = cs_to_sh_tmu(cs);
return sh_tmu_read(p, TCNT) ^ 0xffffffff;
}
static int sh_tmu_clocksource_enable(struct clocksource *cs)
{
struct sh_tmu_priv *p = cs_to_sh_tmu(cs);
int ret;
ret = sh_tmu_enable(p);
if (!ret)
__clocksource_updatefreq_hz(cs, p->rate);
return ret;
}
static void sh_tmu_clocksource_disable(struct clocksource *cs)
{
sh_tmu_disable(cs_to_sh_tmu(cs));
}
static int sh_tmu_register_clocksource(struct sh_tmu_priv *p,
char *name, unsigned long rating)
{
struct clocksource *cs = &p->cs;
cs->name = name;
cs->rating = rating;
cs->read = sh_tmu_clocksource_read;
cs->enable = sh_tmu_clocksource_enable;
cs->disable = sh_tmu_clocksource_disable;
cs->mask = CLOCKSOURCE_MASK(32);
cs->flags = CLOCK_SOURCE_IS_CONTINUOUS;
dev_info(&p->pdev->dev, "used as clock source\n");
/* Register with dummy 1 Hz value, gets updated in ->enable() */
clocksource_register_hz(cs, 1);
return 0;
}
static struct sh_tmu_priv *ced_to_sh_tmu(struct clock_event_device *ced)
{
return container_of(ced, struct sh_tmu_priv, ced);
}
static void sh_tmu_clock_event_start(struct sh_tmu_priv *p, int periodic)
{
struct clock_event_device *ced = &p->ced;
sh_tmu_enable(p);
/* TODO: calculate good shift from rate and counter bit width */
ced->shift = 32;
ced->mult = div_sc(p->rate, NSEC_PER_SEC, ced->shift);
ced->max_delta_ns = clockevent_delta2ns(0xffffffff, ced);
ced->min_delta_ns = 5000;
if (periodic) {
p->periodic = (p->rate + HZ/2) / HZ;
sh_tmu_set_next(p, p->periodic, 1);
}
}
static void sh_tmu_clock_event_mode(enum clock_event_mode mode,
struct clock_event_device *ced)
{
struct sh_tmu_priv *p = ced_to_sh_tmu(ced);
int disabled = 0;
/* deal with old setting first */
switch (ced->mode) {
case CLOCK_EVT_MODE_PERIODIC:
case CLOCK_EVT_MODE_ONESHOT:
sh_tmu_disable(p);
disabled = 1;
break;
default:
break;
}
switch (mode) {
case CLOCK_EVT_MODE_PERIODIC:
dev_info(&p->pdev->dev, "used for periodic clock events\n");
sh_tmu_clock_event_start(p, 1);
break;
case CLOCK_EVT_MODE_ONESHOT:
dev_info(&p->pdev->dev, "used for oneshot clock events\n");
sh_tmu_clock_event_start(p, 0);
break;
case CLOCK_EVT_MODE_UNUSED:
if (!disabled)
sh_tmu_disable(p);
break;
case CLOCK_EVT_MODE_SHUTDOWN:
default:
break;
}
}
static int sh_tmu_clock_event_next(unsigned long delta,
struct clock_event_device *ced)
{
struct sh_tmu_priv *p = ced_to_sh_tmu(ced);
BUG_ON(ced->mode != CLOCK_EVT_MODE_ONESHOT);
/* program new delta value */
sh_tmu_set_next(p, delta, 0);
return 0;
}
static void sh_tmu_register_clockevent(struct sh_tmu_priv *p,
char *name, unsigned long rating)
{
struct clock_event_device *ced = &p->ced;
int ret;
memset(ced, 0, sizeof(*ced));
ced->name = name;
ced->features = CLOCK_EVT_FEAT_PERIODIC;
ced->features |= CLOCK_EVT_FEAT_ONESHOT;
ced->rating = rating;
ced->cpumask = cpumask_of(0);
ced->set_next_event = sh_tmu_clock_event_next;
ced->set_mode = sh_tmu_clock_event_mode;
dev_info(&p->pdev->dev, "used for clock events\n");
clockevents_register_device(ced);
ret = setup_irq(p->irqaction.irq, &p->irqaction);
if (ret) {
dev_err(&p->pdev->dev, "failed to request irq %d\n",
p->irqaction.irq);
return;
}
}
static int sh_tmu_register(struct sh_tmu_priv *p, char *name,
unsigned long clockevent_rating,
unsigned long clocksource_rating)
{
if (clockevent_rating)
sh_tmu_register_clockevent(p, name, clockevent_rating);
else if (clocksource_rating)
sh_tmu_register_clocksource(p, name, clocksource_rating);
return 0;
}
static int sh_tmu_setup(struct sh_tmu_priv *p, struct platform_device *pdev)
{
struct sh_timer_config *cfg = pdev->dev.platform_data;
struct resource *res;
int irq, ret;
ret = -ENXIO;
memset(p, 0, sizeof(*p));
p->pdev = pdev;
if (!cfg) {
dev_err(&p->pdev->dev, "missing platform data\n");
goto err0;
}
platform_set_drvdata(pdev, p);
res = platform_get_resource(p->pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&p->pdev->dev, "failed to get I/O memory\n");
goto err0;
}
irq = platform_get_irq(p->pdev, 0);
if (irq < 0) {
dev_err(&p->pdev->dev, "failed to get irq\n");
goto err0;
}
/* map memory, let mapbase point to our channel */
p->mapbase = ioremap_nocache(res->start, resource_size(res));
if (p->mapbase == NULL) {
dev_err(&p->pdev->dev, "failed to remap I/O memory\n");
goto err0;
}
/* setup data for setup_irq() (too early for request_irq()) */
p->irqaction.name = dev_name(&p->pdev->dev);
p->irqaction.handler = sh_tmu_interrupt;
p->irqaction.dev_id = p;
p->irqaction.irq = irq;
p->irqaction.flags = IRQF_DISABLED | IRQF_TIMER | \
IRQF_IRQPOLL | IRQF_NOBALANCING;
/* get hold of clock */
p->clk = clk_get(&p->pdev->dev, "tmu_fck");
if (IS_ERR(p->clk)) {
dev_err(&p->pdev->dev, "cannot get clock\n");
ret = PTR_ERR(p->clk);
goto err1;
}
return sh_tmu_register(p, (char *)dev_name(&p->pdev->dev),
cfg->clockevent_rating,
cfg->clocksource_rating);
err1:
iounmap(p->mapbase);
err0:
return ret;
}
static int __devinit sh_tmu_probe(struct platform_device *pdev)
{
struct sh_tmu_priv *p = platform_get_drvdata(pdev);
int ret;
if (!is_early_platform_device(pdev))
pm_genpd_dev_always_on(&pdev->dev, true);
if (p) {
dev_info(&pdev->dev, "kept as earlytimer\n");
return 0;
}
p = kmalloc(sizeof(*p), GFP_KERNEL);
if (p == NULL) {
dev_err(&pdev->dev, "failed to allocate driver data\n");
return -ENOMEM;
}
ret = sh_tmu_setup(p, pdev);
if (ret) {
kfree(p);
platform_set_drvdata(pdev, NULL);
}
return ret;
}
static int __devexit sh_tmu_remove(struct platform_device *pdev)
{
return -EBUSY; /* cannot unregister clockevent and clocksource */
}
static struct platform_driver sh_tmu_device_driver = {
.probe = sh_tmu_probe,
.remove = __devexit_p(sh_tmu_remove),
.driver = {
.name = "sh_tmu",
}
};
static int __init sh_tmu_init(void)
{
return platform_driver_register(&sh_tmu_device_driver);
}
static void __exit sh_tmu_exit(void)
{
platform_driver_unregister(&sh_tmu_device_driver);
}
early_platform_init("earlytimer", &sh_tmu_device_driver);
module_init(sh_tmu_init);
module_exit(sh_tmu_exit);
MODULE_AUTHOR("Magnus Damm");
MODULE_DESCRIPTION("SuperH TMU Timer Driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
xixi012023/sultan-kernel-vivid-homeslice-ION | drivers/infiniband/hw/qib/qib_eeprom.c | 8650 | 13019 | /*
* Copyright (c) 2006, 2007, 2008, 2009 QLogic Corporation. All rights reserved.
* Copyright (c) 2003, 2004, 2005, 2006 PathScale, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include "qib.h"
/*
* Functions specific to the serial EEPROM on cards handled by ib_qib.
* The actual serail interface code is in qib_twsi.c. This file is a client
*/
/**
* qib_eeprom_read - receives bytes from the eeprom via I2C
* @dd: the qlogic_ib device
* @eeprom_offset: address to read from
* @buffer: where to store result
* @len: number of bytes to receive
*/
int qib_eeprom_read(struct qib_devdata *dd, u8 eeprom_offset,
void *buff, int len)
{
int ret;
ret = mutex_lock_interruptible(&dd->eep_lock);
if (!ret) {
ret = qib_twsi_reset(dd);
if (ret)
qib_dev_err(dd, "EEPROM Reset for read failed\n");
else
ret = qib_twsi_blk_rd(dd, dd->twsi_eeprom_dev,
eeprom_offset, buff, len);
mutex_unlock(&dd->eep_lock);
}
return ret;
}
/*
* Actually update the eeprom, first doing write enable if
* needed, then restoring write enable state.
* Must be called with eep_lock held
*/
static int eeprom_write_with_enable(struct qib_devdata *dd, u8 offset,
const void *buf, int len)
{
int ret, pwen;
pwen = dd->f_eeprom_wen(dd, 1);
ret = qib_twsi_reset(dd);
if (ret)
qib_dev_err(dd, "EEPROM Reset for write failed\n");
else
ret = qib_twsi_blk_wr(dd, dd->twsi_eeprom_dev,
offset, buf, len);
dd->f_eeprom_wen(dd, pwen);
return ret;
}
/**
* qib_eeprom_write - writes data to the eeprom via I2C
* @dd: the qlogic_ib device
* @eeprom_offset: where to place data
* @buffer: data to write
* @len: number of bytes to write
*/
int qib_eeprom_write(struct qib_devdata *dd, u8 eeprom_offset,
const void *buff, int len)
{
int ret;
ret = mutex_lock_interruptible(&dd->eep_lock);
if (!ret) {
ret = eeprom_write_with_enable(dd, eeprom_offset, buff, len);
mutex_unlock(&dd->eep_lock);
}
return ret;
}
static u8 flash_csum(struct qib_flash *ifp, int adjust)
{
u8 *ip = (u8 *) ifp;
u8 csum = 0, len;
/*
* Limit length checksummed to max length of actual data.
* Checksum of erased eeprom will still be bad, but we avoid
* reading past the end of the buffer we were passed.
*/
len = ifp->if_length;
if (len > sizeof(struct qib_flash))
len = sizeof(struct qib_flash);
while (len--)
csum += *ip++;
csum -= ifp->if_csum;
csum = ~csum;
if (adjust)
ifp->if_csum = csum;
return csum;
}
/**
* qib_get_eeprom_info- get the GUID et al. from the TSWI EEPROM device
* @dd: the qlogic_ib device
*
* We have the capability to use the nguid field, and get
* the guid from the first chip's flash, to use for all of them.
*/
void qib_get_eeprom_info(struct qib_devdata *dd)
{
void *buf;
struct qib_flash *ifp;
__be64 guid;
int len, eep_stat;
u8 csum, *bguid;
int t = dd->unit;
struct qib_devdata *dd0 = qib_lookup(0);
if (t && dd0->nguid > 1 && t <= dd0->nguid) {
u8 oguid;
dd->base_guid = dd0->base_guid;
bguid = (u8 *) &dd->base_guid;
oguid = bguid[7];
bguid[7] += t;
if (oguid > bguid[7]) {
if (bguid[6] == 0xff) {
if (bguid[5] == 0xff) {
qib_dev_err(dd, "Can't set %s GUID"
" from base, wraps to"
" OUI!\n",
qib_get_unit_name(t));
dd->base_guid = 0;
goto bail;
}
bguid[5]++;
}
bguid[6]++;
}
dd->nguid = 1;
goto bail;
}
/*
* Read full flash, not just currently used part, since it may have
* been written with a newer definition.
* */
len = sizeof(struct qib_flash);
buf = vmalloc(len);
if (!buf) {
qib_dev_err(dd, "Couldn't allocate memory to read %u "
"bytes from eeprom for GUID\n", len);
goto bail;
}
/*
* Use "public" eeprom read function, which does locking and
* figures out device. This will migrate to chip-specific.
*/
eep_stat = qib_eeprom_read(dd, 0, buf, len);
if (eep_stat) {
qib_dev_err(dd, "Failed reading GUID from eeprom\n");
goto done;
}
ifp = (struct qib_flash *)buf;
csum = flash_csum(ifp, 0);
if (csum != ifp->if_csum) {
qib_devinfo(dd->pcidev, "Bad I2C flash checksum: "
"0x%x, not 0x%x\n", csum, ifp->if_csum);
goto done;
}
if (*(__be64 *) ifp->if_guid == cpu_to_be64(0) ||
*(__be64 *) ifp->if_guid == ~cpu_to_be64(0)) {
qib_dev_err(dd, "Invalid GUID %llx from flash; ignoring\n",
*(unsigned long long *) ifp->if_guid);
/* don't allow GUID if all 0 or all 1's */
goto done;
}
/* complain, but allow it */
if (*(u64 *) ifp->if_guid == 0x100007511000000ULL)
qib_devinfo(dd->pcidev, "Warning, GUID %llx is "
"default, probably not correct!\n",
*(unsigned long long *) ifp->if_guid);
bguid = ifp->if_guid;
if (!bguid[0] && !bguid[1] && !bguid[2]) {
/*
* Original incorrect GUID format in flash; fix in
* core copy, by shifting up 2 octets; don't need to
* change top octet, since both it and shifted are 0.
*/
bguid[1] = bguid[3];
bguid[2] = bguid[4];
bguid[3] = 0;
bguid[4] = 0;
guid = *(__be64 *) ifp->if_guid;
} else
guid = *(__be64 *) ifp->if_guid;
dd->base_guid = guid;
dd->nguid = ifp->if_numguid;
/*
* Things are slightly complicated by the desire to transparently
* support both the Pathscale 10-digit serial number and the QLogic
* 13-character version.
*/
if ((ifp->if_fversion > 1) && ifp->if_sprefix[0] &&
((u8 *) ifp->if_sprefix)[0] != 0xFF) {
char *snp = dd->serial;
/*
* This board has a Serial-prefix, which is stored
* elsewhere for backward-compatibility.
*/
memcpy(snp, ifp->if_sprefix, sizeof ifp->if_sprefix);
snp[sizeof ifp->if_sprefix] = '\0';
len = strlen(snp);
snp += len;
len = (sizeof dd->serial) - len;
if (len > sizeof ifp->if_serial)
len = sizeof ifp->if_serial;
memcpy(snp, ifp->if_serial, len);
} else
memcpy(dd->serial, ifp->if_serial,
sizeof ifp->if_serial);
if (!strstr(ifp->if_comment, "Tested successfully"))
qib_dev_err(dd, "Board SN %s did not pass functional "
"test: %s\n", dd->serial, ifp->if_comment);
memcpy(&dd->eep_st_errs, &ifp->if_errcntp, QIB_EEP_LOG_CNT);
/*
* Power-on (actually "active") hours are kept as little-endian value
* in EEPROM, but as seconds in a (possibly as small as 24-bit)
* atomic_t while running.
*/
atomic_set(&dd->active_time, 0);
dd->eep_hrs = ifp->if_powerhour[0] | (ifp->if_powerhour[1] << 8);
done:
vfree(buf);
bail:;
}
/**
* qib_update_eeprom_log - copy active-time and error counters to eeprom
* @dd: the qlogic_ib device
*
* Although the time is kept as seconds in the qib_devdata struct, it is
* rounded to hours for re-write, as we have only 16 bits in EEPROM.
* First-cut code reads whole (expected) struct qib_flash, modifies,
* re-writes. Future direction: read/write only what we need, assuming
* that the EEPROM had to have been "good enough" for driver init, and
* if not, we aren't making it worse.
*
*/
int qib_update_eeprom_log(struct qib_devdata *dd)
{
void *buf;
struct qib_flash *ifp;
int len, hi_water;
uint32_t new_time, new_hrs;
u8 csum;
int ret, idx;
unsigned long flags;
/* first, check if we actually need to do anything. */
ret = 0;
for (idx = 0; idx < QIB_EEP_LOG_CNT; ++idx) {
if (dd->eep_st_new_errs[idx]) {
ret = 1;
break;
}
}
new_time = atomic_read(&dd->active_time);
if (ret == 0 && new_time < 3600)
goto bail;
/*
* The quick-check above determined that there is something worthy
* of logging, so get current contents and do a more detailed idea.
* read full flash, not just currently used part, since it may have
* been written with a newer definition
*/
len = sizeof(struct qib_flash);
buf = vmalloc(len);
ret = 1;
if (!buf) {
qib_dev_err(dd, "Couldn't allocate memory to read %u "
"bytes from eeprom for logging\n", len);
goto bail;
}
/* Grab semaphore and read current EEPROM. If we get an
* error, let go, but if not, keep it until we finish write.
*/
ret = mutex_lock_interruptible(&dd->eep_lock);
if (ret) {
qib_dev_err(dd, "Unable to acquire EEPROM for logging\n");
goto free_bail;
}
ret = qib_twsi_blk_rd(dd, dd->twsi_eeprom_dev, 0, buf, len);
if (ret) {
mutex_unlock(&dd->eep_lock);
qib_dev_err(dd, "Unable read EEPROM for logging\n");
goto free_bail;
}
ifp = (struct qib_flash *)buf;
csum = flash_csum(ifp, 0);
if (csum != ifp->if_csum) {
mutex_unlock(&dd->eep_lock);
qib_dev_err(dd, "EEPROM cks err (0x%02X, S/B 0x%02X)\n",
csum, ifp->if_csum);
ret = 1;
goto free_bail;
}
hi_water = 0;
spin_lock_irqsave(&dd->eep_st_lock, flags);
for (idx = 0; idx < QIB_EEP_LOG_CNT; ++idx) {
int new_val = dd->eep_st_new_errs[idx];
if (new_val) {
/*
* If we have seen any errors, add to EEPROM values
* We need to saturate at 0xFF (255) and we also
* would need to adjust the checksum if we were
* trying to minimize EEPROM traffic
* Note that we add to actual current count in EEPROM,
* in case it was altered while we were running.
*/
new_val += ifp->if_errcntp[idx];
if (new_val > 0xFF)
new_val = 0xFF;
if (ifp->if_errcntp[idx] != new_val) {
ifp->if_errcntp[idx] = new_val;
hi_water = offsetof(struct qib_flash,
if_errcntp) + idx;
}
/*
* update our shadow (used to minimize EEPROM
* traffic), to match what we are about to write.
*/
dd->eep_st_errs[idx] = new_val;
dd->eep_st_new_errs[idx] = 0;
}
}
/*
* Now update active-time. We would like to round to the nearest hour
* but unless atomic_t are sure to be proper signed ints we cannot,
* because we need to account for what we "transfer" to EEPROM and
* if we log an hour at 31 minutes, then we would need to set
* active_time to -29 to accurately count the _next_ hour.
*/
if (new_time >= 3600) {
new_hrs = new_time / 3600;
atomic_sub((new_hrs * 3600), &dd->active_time);
new_hrs += dd->eep_hrs;
if (new_hrs > 0xFFFF)
new_hrs = 0xFFFF;
dd->eep_hrs = new_hrs;
if ((new_hrs & 0xFF) != ifp->if_powerhour[0]) {
ifp->if_powerhour[0] = new_hrs & 0xFF;
hi_water = offsetof(struct qib_flash, if_powerhour);
}
if ((new_hrs >> 8) != ifp->if_powerhour[1]) {
ifp->if_powerhour[1] = new_hrs >> 8;
hi_water = offsetof(struct qib_flash, if_powerhour) + 1;
}
}
/*
* There is a tiny possibility that we could somehow fail to write
* the EEPROM after updating our shadows, but problems from holding
* the spinlock too long are a much bigger issue.
*/
spin_unlock_irqrestore(&dd->eep_st_lock, flags);
if (hi_water) {
/* we made some change to the data, uopdate cksum and write */
csum = flash_csum(ifp, 1);
ret = eeprom_write_with_enable(dd, 0, buf, hi_water + 1);
}
mutex_unlock(&dd->eep_lock);
if (ret)
qib_dev_err(dd, "Failed updating EEPROM\n");
free_bail:
vfree(buf);
bail:
return ret;
}
/**
* qib_inc_eeprom_err - increment one of the four error counters
* that are logged to EEPROM.
* @dd: the qlogic_ib device
* @eidx: 0..3, the counter to increment
* @incr: how much to add
*
* Each counter is 8-bits, and saturates at 255 (0xFF). They
* are copied to the EEPROM (aka flash) whenever qib_update_eeprom_log()
* is called, but it can only be called in a context that allows sleep.
* This function can be called even at interrupt level.
*/
void qib_inc_eeprom_err(struct qib_devdata *dd, u32 eidx, u32 incr)
{
uint new_val;
unsigned long flags;
spin_lock_irqsave(&dd->eep_st_lock, flags);
new_val = dd->eep_st_new_errs[eidx] + incr;
if (new_val > 255)
new_val = 255;
dd->eep_st_new_errs[eidx] = new_val;
spin_unlock_irqrestore(&dd->eep_st_lock, flags);
}
| gpl-2.0 |
ignacio28/android_kernel_lge_msm8610 | arch/mips/emma/common/prom.c | 9418 | 1880 | /*
* Copyright (C) NEC Electronics Corporation 2004-2006
*
* This file is based on the arch/mips/ddb5xxx/common/prom.c
*
* Copyright 2001 MontaVista Software Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/bootmem.h>
#include <asm/addrspace.h>
#include <asm/bootinfo.h>
#include <asm/emma/emma2rh.h>
const char *get_system_type(void)
{
#ifdef CONFIG_NEC_MARKEINS
return "NEC EMMA2RH Mark-eins";
#else
#error Unknown NEC board
#endif
}
/* [jsun@junsun.net] PMON passes arguments in C main() style */
void __init prom_init(void)
{
int argc = fw_arg0;
char **arg = (char **)fw_arg1;
int i;
/* if user passes kernel args, ignore the default one */
if (argc > 1)
arcs_cmdline[0] = '\0';
/* arg[0] is "g", the rest is boot parameters */
for (i = 1; i < argc; i++) {
if (strlen(arcs_cmdline) + strlen(arg[i]) + 1
>= sizeof(arcs_cmdline))
break;
strcat(arcs_cmdline, arg[i]);
strcat(arcs_cmdline, " ");
}
#ifdef CONFIG_NEC_MARKEINS
add_memory_region(0, EMMA2RH_RAM_SIZE, BOOT_MEM_RAM);
#else
#error Unknown NEC board
#endif
}
void __init prom_free_prom_memory(void)
{
}
| gpl-2.0 |
gentu/android_kernel_zte_nx503a | arch/powerpc/boot/cuboot-acadia.c | 14026 | 4964 | /*
* Old U-boot compatibility for Acadia
*
* Author: Josh Boyer <jwboyer@linux.vnet.ibm.com>
*
* Copyright 2008 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 "ops.h"
#include "io.h"
#include "dcr.h"
#include "stdio.h"
#include "4xx.h"
#include "44x.h"
#include "cuboot.h"
#define TARGET_4xx
#include "ppcboot.h"
static bd_t bd;
#define CPR_PERD0_SPIDV_MASK 0x000F0000 /* SPI Clock Divider */
#define PLLC_SRC_MASK 0x20000000 /* PLL feedback source */
#define PLLD_FBDV_MASK 0x1F000000 /* PLL feedback divider value */
#define PLLD_FWDVA_MASK 0x000F0000 /* PLL forward divider A value */
#define PLLD_FWDVB_MASK 0x00000700 /* PLL forward divider B value */
#define PRIMAD_CPUDV_MASK 0x0F000000 /* CPU Clock Divisor Mask */
#define PRIMAD_PLBDV_MASK 0x000F0000 /* PLB Clock Divisor Mask */
#define PRIMAD_OPBDV_MASK 0x00000F00 /* OPB Clock Divisor Mask */
#define PRIMAD_EBCDV_MASK 0x0000000F /* EBC Clock Divisor Mask */
#define PERD0_PWMDV_MASK 0xFF000000 /* PWM Divider Mask */
#define PERD0_SPIDV_MASK 0x000F0000 /* SPI Divider Mask */
#define PERD0_U0DV_MASK 0x0000FF00 /* UART 0 Divider Mask */
#define PERD0_U1DV_MASK 0x000000FF /* UART 1 Divider Mask */
static void get_clocks(void)
{
unsigned long sysclk, cpr_plld, cpr_pllc, cpr_primad, plloutb, i;
unsigned long pllFwdDiv, pllFwdDivB, pllFbkDiv, pllPlbDiv, pllExtBusDiv;
unsigned long pllOpbDiv, freqEBC, freqUART, freqOPB;
unsigned long div; /* total divisor udiv * bdiv */
unsigned long umin; /* minimum udiv */
unsigned short diff; /* smallest diff */
unsigned long udiv; /* best udiv */
unsigned short idiff; /* current diff */
unsigned short ibdiv; /* current bdiv */
unsigned long est; /* current estimate */
unsigned long baud;
void *np;
/* read the sysclk value from the CPLD */
sysclk = (in_8((unsigned char *)0x80000000) == 0xc) ? 66666666 : 33333000;
/*
* Read PLL Mode registers
*/
cpr_plld = CPR0_READ(DCRN_CPR0_PLLD);
cpr_pllc = CPR0_READ(DCRN_CPR0_PLLC);
/*
* Determine forward divider A
*/
pllFwdDiv = ((cpr_plld & PLLD_FWDVA_MASK) >> 16);
/*
* Determine forward divider B
*/
pllFwdDivB = ((cpr_plld & PLLD_FWDVB_MASK) >> 8);
if (pllFwdDivB == 0)
pllFwdDivB = 8;
/*
* Determine FBK_DIV.
*/
pllFbkDiv = ((cpr_plld & PLLD_FBDV_MASK) >> 24);
if (pllFbkDiv == 0)
pllFbkDiv = 256;
/*
* Read CPR_PRIMAD register
*/
cpr_primad = CPR0_READ(DCRN_CPR0_PRIMAD);
/*
* Determine PLB_DIV.
*/
pllPlbDiv = ((cpr_primad & PRIMAD_PLBDV_MASK) >> 16);
if (pllPlbDiv == 0)
pllPlbDiv = 16;
/*
* Determine EXTBUS_DIV.
*/
pllExtBusDiv = (cpr_primad & PRIMAD_EBCDV_MASK);
if (pllExtBusDiv == 0)
pllExtBusDiv = 16;
/*
* Determine OPB_DIV.
*/
pllOpbDiv = ((cpr_primad & PRIMAD_OPBDV_MASK) >> 8);
if (pllOpbDiv == 0)
pllOpbDiv = 16;
/* There is a bug in U-Boot that prevents us from using
* bd.bi_opbfreq because U-Boot doesn't populate it for
* 405EZ. We get to calculate it, yay!
*/
freqOPB = (sysclk *pllFbkDiv) /pllOpbDiv;
freqEBC = (sysclk * pllFbkDiv) / pllExtBusDiv;
plloutb = ((sysclk * ((cpr_pllc & PLLC_SRC_MASK) ?
pllFwdDivB : pllFwdDiv) *
pllFbkDiv) / pllFwdDivB);
np = find_node_by_alias("serial0");
if (getprop(np, "current-speed", &baud, sizeof(baud)) != sizeof(baud))
fatal("no current-speed property\n\r");
udiv = 256; /* Assume lowest possible serial clk */
div = plloutb / (16 * baud); /* total divisor */
umin = (plloutb / freqOPB) << 1; /* 2 x OPB divisor */
diff = 256; /* highest possible */
/* i is the test udiv value -- start with the largest
* possible (256) to minimize serial clock and constrain
* search to umin.
*/
for (i = 256; i > umin; i--) {
ibdiv = div / i;
est = i * ibdiv;
idiff = (est > div) ? (est-div) : (div-est);
if (idiff == 0) {
udiv = i;
break; /* can't do better */
} else if (idiff < diff) {
udiv = i; /* best so far */
diff = idiff; /* update lowest diff*/
}
}
freqUART = plloutb / udiv;
dt_fixup_cpu_clocks(bd.bi_procfreq, bd.bi_intfreq, bd.bi_plb_busfreq);
dt_fixup_clock("/plb/ebc", freqEBC);
dt_fixup_clock("/plb/opb", freqOPB);
dt_fixup_clock("/plb/opb/serial@ef600300", freqUART);
dt_fixup_clock("/plb/opb/serial@ef600400", freqUART);
}
static void acadia_fixups(void)
{
dt_fixup_memory(bd.bi_memstart, bd.bi_memsize);
get_clocks();
dt_fixup_mac_address_by_alias("ethernet0", bd.bi_enetaddr);
}
void platform_init(unsigned long r3, unsigned long r4, unsigned long r5,
unsigned long r6, unsigned long r7)
{
CUBOOT_INIT();
platform_ops.fixups = acadia_fixups;
platform_ops.exit = ibm40x_dbcr_reset;
fdt_init(_dtb_start);
serial_console_init();
}
| gpl-2.0 |
TheTypoMaster/SM-G360T1_kernel | drivers/coresight/coresight-rpm-etm.c | 459 | 9398 | /* Copyright (c) 2013-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/init.h>
#include <linux/types.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/err.h>
#include <linux/sysfs.h>
#include <linux/mutex.h>
#include <linux/of_coresight.h>
#include <linux/coresight.h>
#include "coresight-qmi.h"
#ifdef CONFIG_CORESIGHT_RPM_ETM_DEFAULT_ENABLE
static int boot_enable = 1;
#else
static int boot_enable;
#endif
module_param_named(
boot_enable, boot_enable, int, S_IRUGO
);
struct rpm_etm_drvdata {
struct device *dev;
struct coresight_device *csdev;
struct mutex mutex;
struct workqueue_struct *wq;
struct qmi_handle *handle;
struct work_struct work_svc_arrive;
struct work_struct work_svc_exit;
struct work_struct work_rcv_msg;
struct notifier_block nb;
};
static int rpm_etm_enable(struct coresight_device *csdev)
{
struct rpm_etm_drvdata *drvdata =
dev_get_drvdata(csdev->dev.parent);
struct coresight_set_etm_req_msg_v01 req;
struct coresight_set_etm_resp_msg_v01 resp = { { 0, 0 } };
struct msg_desc req_desc, resp_desc;
int ret;
mutex_lock(&drvdata->mutex);
/*
* The QMI handle may be NULL in the following scenarios:
* 1. QMI service is not present
* 2. QMI service is present but attempt to enable remote ETM is earlier
* than service is ready to handle request
* 3. Connection between QMI client and QMI service failed
*
* Enable CoreSight without processing further QMI commands which
* provides the option to enable remote ETM by other means.
*/
if (!drvdata->handle) {
dev_info(drvdata->dev,
"%s: QMI service unavailable. Skipping QMI requests\n",
__func__);
goto out;
}
req.state = CORESIGHT_ETM_STATE_ENABLED_V01;
req_desc.msg_id = CORESIGHT_QMI_SET_ETM_REQ_V01;
req_desc.max_msg_len = CORESIGHT_QMI_SET_ETM_REQ_MAX_LEN;
req_desc.ei_array = coresight_set_etm_req_msg_v01_ei;
resp_desc.msg_id = CORESIGHT_QMI_SET_ETM_RESP_V01;
resp_desc.max_msg_len = CORESIGHT_QMI_SET_ETM_RESP_MAX_LEN;
resp_desc.ei_array = coresight_set_etm_resp_msg_v01_ei;
ret = qmi_send_req_wait(drvdata->handle, &req_desc, &req, sizeof(req),
&resp_desc, &resp, sizeof(resp), TIMEOUT_MS);
if (ret < 0) {
dev_err(drvdata->dev, "%s: QMI send req failed %d\n", __func__,
ret);
goto err;
}
if (resp.resp.result != QMI_RESULT_SUCCESS_V01) {
dev_err(drvdata->dev, "%s: QMI request failed %d %d\n",
__func__, resp.resp.result, resp.resp.error);
ret = -EREMOTEIO;
goto err;
}
out:
mutex_unlock(&drvdata->mutex);
dev_info(drvdata->dev, "RPM ETM tracing enabled\n");
return 0;
err:
mutex_unlock(&drvdata->mutex);
return ret;
}
static void rpm_etm_disable(struct coresight_device *csdev)
{
struct rpm_etm_drvdata *drvdata =
dev_get_drvdata(csdev->dev.parent);
struct coresight_set_etm_req_msg_v01 req;
struct coresight_set_etm_resp_msg_v01 resp = { { 0, 0 } };
struct msg_desc req_desc, resp_desc;
int ret;
mutex_lock(&drvdata->mutex);
if (!drvdata->handle) {
dev_info(drvdata->dev,
"%s: QMI service unavailable. Skipping QMI requests\n",
__func__);
goto out;
}
req.state = CORESIGHT_ETM_STATE_DISABLED_V01;
req_desc.msg_id = CORESIGHT_QMI_SET_ETM_REQ_V01;
req_desc.max_msg_len = CORESIGHT_QMI_SET_ETM_REQ_MAX_LEN;
req_desc.ei_array = coresight_set_etm_req_msg_v01_ei;
resp_desc.msg_id = CORESIGHT_QMI_SET_ETM_RESP_V01;
resp_desc.max_msg_len = CORESIGHT_QMI_SET_ETM_RESP_MAX_LEN;
resp_desc.ei_array = coresight_set_etm_resp_msg_v01_ei;
ret = qmi_send_req_wait(drvdata->handle, &req_desc, &req, sizeof(req),
&resp_desc, &resp, sizeof(resp), TIMEOUT_MS);
if (ret < 0) {
dev_err(drvdata->dev, "%s: QMI send req failed %d\n", __func__,
ret);
goto err;
}
if (resp.resp.result != QMI_RESULT_SUCCESS_V01) {
dev_err(drvdata->dev, "%s: QMI request failed %d %d\n",
__func__, resp.resp.result, resp.resp.error);
goto err;
}
out:
mutex_unlock(&drvdata->mutex);
dev_info(drvdata->dev, "RPM ETM tracing disabled\n");
return;
err:
mutex_unlock(&drvdata->mutex);
}
static const struct coresight_ops_source rpm_etm_source_ops = {
.enable = rpm_etm_enable,
.disable = rpm_etm_disable,
};
static const struct coresight_ops rpm_cs_ops = {
.source_ops = &rpm_etm_source_ops,
};
static void rpm_etm_rcv_msg(struct work_struct *work)
{
struct rpm_etm_drvdata *drvdata = container_of(work,
struct rpm_etm_drvdata,
work_rcv_msg);
if (qmi_recv_msg(drvdata->handle) < 0)
dev_err(drvdata->dev, "%s: Error receiving QMI message\n",
__func__);
}
static void rpm_etm_notify(struct qmi_handle *handle,
enum qmi_event_type event, void *notify_priv)
{
struct rpm_etm_drvdata *drvdata =
(struct rpm_etm_drvdata *)notify_priv;
switch (event) {
case QMI_RECV_MSG:
queue_work(drvdata->wq, &drvdata->work_rcv_msg);
break;
default:
break;
}
}
static void rpm_etm_svc_arrive(struct work_struct *work)
{
struct rpm_etm_drvdata *drvdata = container_of(work,
struct rpm_etm_drvdata,
work_svc_arrive);
drvdata->handle = qmi_handle_create(rpm_etm_notify, drvdata);
if (!drvdata->handle) {
dev_err(drvdata->dev, "%s: QMI client handle alloc failed\n",
__func__);
return;
}
if (qmi_connect_to_service(drvdata->handle, CORESIGHT_QMI_SVC_ID,
CORESIGHT_QMI_VERSION,
CORESIGHT_SVC_INST_ID_RPM_V01) < 0) {
dev_err(drvdata->dev,
"%s: Could not connect handle to service\n", __func__);
qmi_handle_destroy(drvdata->handle);
drvdata->handle = NULL;
}
}
static void rpm_etm_svc_exit(struct work_struct *work)
{
struct rpm_etm_drvdata *drvdata = container_of(work,
struct rpm_etm_drvdata,
work_svc_exit);
qmi_handle_destroy(drvdata->handle);
drvdata->handle = NULL;
}
static int rpm_etm_svc_event_notify(struct notifier_block *this,
unsigned long event,
void *data)
{
struct rpm_etm_drvdata *drvdata = container_of(this,
struct rpm_etm_drvdata,
nb);
switch (event) {
case QMI_SERVER_ARRIVE:
queue_work(drvdata->wq, &drvdata->work_svc_arrive);
break;
case QMI_SERVER_EXIT:
queue_work(drvdata->wq, &drvdata->work_svc_exit);
break;
default:
break;
}
return 0;
}
static int rpm_etm_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct coresight_platform_data *pdata;
struct rpm_etm_drvdata *drvdata;
struct coresight_desc *desc;
int ret;
if (pdev->dev.of_node) {
pdata = of_get_coresight_platform_data(dev, pdev->dev.of_node);
if (IS_ERR(pdata))
return PTR_ERR(pdata);
pdev->dev.platform_data = pdata;
}
drvdata = devm_kzalloc(dev, sizeof(*drvdata), GFP_KERNEL);
if (!drvdata)
return -ENOMEM;
drvdata->dev = &pdev->dev;
platform_set_drvdata(pdev, drvdata);
desc = devm_kzalloc(dev, sizeof(*desc), GFP_KERNEL);
if (!desc)
return -ENOMEM;
mutex_init(&drvdata->mutex);
drvdata->nb.notifier_call = rpm_etm_svc_event_notify;
drvdata->wq = create_singlethread_workqueue("rpm-etm");
if (!drvdata->wq)
return -EFAULT;
INIT_WORK(&drvdata->work_svc_arrive, rpm_etm_svc_arrive);
INIT_WORK(&drvdata->work_svc_exit, rpm_etm_svc_exit);
INIT_WORK(&drvdata->work_rcv_msg, rpm_etm_rcv_msg);
ret = qmi_svc_event_notifier_register(CORESIGHT_QMI_SVC_ID,
CORESIGHT_QMI_VERSION,
CORESIGHT_SVC_INST_ID_RPM_V01,
&drvdata->nb);
if (ret < 0)
goto err0;
desc->type = CORESIGHT_DEV_TYPE_SOURCE;
desc->subtype.source_subtype = CORESIGHT_DEV_SUBTYPE_SOURCE_PROC;
desc->ops = &rpm_cs_ops;
desc->pdata = pdev->dev.platform_data;
desc->dev = &pdev->dev;
desc->owner = THIS_MODULE;
drvdata->csdev = coresight_register(desc);
if (IS_ERR(drvdata->csdev)) {
ret = PTR_ERR(drvdata->csdev);
goto err1;
}
dev_info(dev, "RPM ETM initialized\n");
if (boot_enable)
coresight_enable(drvdata->csdev);
return 0;
err1:
qmi_svc_event_notifier_unregister(CORESIGHT_QMI_SVC_ID,
CORESIGHT_QMI_VERSION,
CORESIGHT_SVC_INST_ID_RPM_V01,
&drvdata->nb);
err0:
destroy_workqueue(drvdata->wq);
return ret;
}
static int rpm_etm_remove(struct platform_device *pdev)
{
struct rpm_etm_drvdata *drvdata = platform_get_drvdata(pdev);
coresight_unregister(drvdata->csdev);
return 0;
}
static struct of_device_id rpm_etm_match[] = {
{.compatible = "qcom,coresight-rpm-etm"},
{}
};
static struct platform_driver rpm_etm_driver = {
.probe = rpm_etm_probe,
.remove = rpm_etm_remove,
.driver = {
.name = "coresight-rpm-etm",
.owner = THIS_MODULE,
.of_match_table = rpm_etm_match,
},
};
int __init rpm_etm_init(void)
{
return platform_driver_register(&rpm_etm_driver);
}
module_init(rpm_etm_init);
void __exit rpm_etm_exit(void)
{
platform_driver_unregister(&rpm_etm_driver);
}
module_exit(rpm_etm_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("CoreSight RPM ETM driver");
| gpl-2.0 |
k0nane/Twilight_Zone_kernel | drivers/s390/char/keyboard.c | 715 | 12698 | /*
* drivers/s390/char/keyboard.c
* ebcdic keycode functions for s390 console drivers
*
* S390 version
* Copyright (C) 2003 IBM Deutschland Entwicklung GmbH, IBM Corporation
* Author(s): Martin Schwidefsky (schwidefsky@de.ibm.com),
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/sysrq.h>
#include <linux/consolemap.h>
#include <linux/kbd_kern.h>
#include <linux/kbd_diacr.h>
#include <asm/uaccess.h>
#include "keyboard.h"
/*
* Handler Tables.
*/
#define K_HANDLERS\
k_self, k_fn, k_spec, k_ignore,\
k_dead, k_ignore, k_ignore, k_ignore,\
k_ignore, k_ignore, k_ignore, k_ignore,\
k_ignore, k_ignore, k_ignore, k_ignore
typedef void (k_handler_fn)(struct kbd_data *, unsigned char);
static k_handler_fn K_HANDLERS;
static k_handler_fn *k_handler[16] = { K_HANDLERS };
/* maximum values each key_handler can handle */
static const int kbd_max_vals[] = {
255, ARRAY_SIZE(func_table) - 1, NR_FN_HANDLER - 1, 0,
NR_DEAD - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
static const int KBD_NR_TYPES = ARRAY_SIZE(kbd_max_vals);
static unsigned char ret_diacr[NR_DEAD] = {
'`', '\'', '^', '~', '"', ','
};
/*
* Alloc/free of kbd_data structures.
*/
struct kbd_data *
kbd_alloc(void) {
struct kbd_data *kbd;
int i, len;
kbd = kzalloc(sizeof(struct kbd_data), GFP_KERNEL);
if (!kbd)
goto out;
kbd->key_maps = kzalloc(sizeof(key_maps), GFP_KERNEL);
if (!kbd->key_maps)
goto out_kbd;
for (i = 0; i < ARRAY_SIZE(key_maps); i++) {
if (key_maps[i]) {
kbd->key_maps[i] =
kmalloc(sizeof(u_short)*NR_KEYS, GFP_KERNEL);
if (!kbd->key_maps[i])
goto out_maps;
memcpy(kbd->key_maps[i], key_maps[i],
sizeof(u_short)*NR_KEYS);
}
}
kbd->func_table = kzalloc(sizeof(func_table), GFP_KERNEL);
if (!kbd->func_table)
goto out_maps;
for (i = 0; i < ARRAY_SIZE(func_table); i++) {
if (func_table[i]) {
len = strlen(func_table[i]) + 1;
kbd->func_table[i] = kmalloc(len, GFP_KERNEL);
if (!kbd->func_table[i])
goto out_func;
memcpy(kbd->func_table[i], func_table[i], len);
}
}
kbd->fn_handler =
kzalloc(sizeof(fn_handler_fn *) * NR_FN_HANDLER, GFP_KERNEL);
if (!kbd->fn_handler)
goto out_func;
kbd->accent_table =
kmalloc(sizeof(struct kbdiacruc)*MAX_DIACR, GFP_KERNEL);
if (!kbd->accent_table)
goto out_fn_handler;
memcpy(kbd->accent_table, accent_table,
sizeof(struct kbdiacruc)*MAX_DIACR);
kbd->accent_table_size = accent_table_size;
return kbd;
out_fn_handler:
kfree(kbd->fn_handler);
out_func:
for (i = 0; i < ARRAY_SIZE(func_table); i++)
kfree(kbd->func_table[i]);
kfree(kbd->func_table);
out_maps:
for (i = 0; i < ARRAY_SIZE(key_maps); i++)
kfree(kbd->key_maps[i]);
kfree(kbd->key_maps);
out_kbd:
kfree(kbd);
out:
return NULL;
}
void
kbd_free(struct kbd_data *kbd)
{
int i;
kfree(kbd->accent_table);
kfree(kbd->fn_handler);
for (i = 0; i < ARRAY_SIZE(func_table); i++)
kfree(kbd->func_table[i]);
kfree(kbd->func_table);
for (i = 0; i < ARRAY_SIZE(key_maps); i++)
kfree(kbd->key_maps[i]);
kfree(kbd->key_maps);
kfree(kbd);
}
/*
* Generate ascii -> ebcdic translation table from kbd_data.
*/
void
kbd_ascebc(struct kbd_data *kbd, unsigned char *ascebc)
{
unsigned short *keymap, keysym;
int i, j, k;
memset(ascebc, 0x40, 256);
for (i = 0; i < ARRAY_SIZE(key_maps); i++) {
keymap = kbd->key_maps[i];
if (!keymap)
continue;
for (j = 0; j < NR_KEYS; j++) {
k = ((i & 1) << 7) + j;
keysym = keymap[j];
if (KTYP(keysym) == (KT_LATIN | 0xf0) ||
KTYP(keysym) == (KT_LETTER | 0xf0))
ascebc[KVAL(keysym)] = k;
else if (KTYP(keysym) == (KT_DEAD | 0xf0))
ascebc[ret_diacr[KVAL(keysym)]] = k;
}
}
}
#if 0
/*
* Generate ebcdic -> ascii translation table from kbd_data.
*/
void
kbd_ebcasc(struct kbd_data *kbd, unsigned char *ebcasc)
{
unsigned short *keymap, keysym;
int i, j, k;
memset(ebcasc, ' ', 256);
for (i = 0; i < ARRAY_SIZE(key_maps); i++) {
keymap = kbd->key_maps[i];
if (!keymap)
continue;
for (j = 0; j < NR_KEYS; j++) {
keysym = keymap[j];
k = ((i & 1) << 7) + j;
if (KTYP(keysym) == (KT_LATIN | 0xf0) ||
KTYP(keysym) == (KT_LETTER | 0xf0))
ebcasc[k] = KVAL(keysym);
else if (KTYP(keysym) == (KT_DEAD | 0xf0))
ebcasc[k] = ret_diacr[KVAL(keysym)];
}
}
}
#endif
/*
* We have a combining character DIACR here, followed by the character CH.
* If the combination occurs in the table, return the corresponding value.
* Otherwise, if CH is a space or equals DIACR, return DIACR.
* Otherwise, conclude that DIACR was not combining after all,
* queue it and return CH.
*/
static unsigned int
handle_diacr(struct kbd_data *kbd, unsigned int ch)
{
int i, d;
d = kbd->diacr;
kbd->diacr = 0;
for (i = 0; i < kbd->accent_table_size; i++) {
if (kbd->accent_table[i].diacr == d &&
kbd->accent_table[i].base == ch)
return kbd->accent_table[i].result;
}
if (ch == ' ' || ch == d)
return d;
kbd_put_queue(kbd->tty, d);
return ch;
}
/*
* Handle dead key.
*/
static void
k_dead(struct kbd_data *kbd, unsigned char value)
{
value = ret_diacr[value];
kbd->diacr = (kbd->diacr ? handle_diacr(kbd, value) : value);
}
/*
* Normal character handler.
*/
static void
k_self(struct kbd_data *kbd, unsigned char value)
{
if (kbd->diacr)
value = handle_diacr(kbd, value);
kbd_put_queue(kbd->tty, value);
}
/*
* Special key handlers
*/
static void
k_ignore(struct kbd_data *kbd, unsigned char value)
{
}
/*
* Function key handler.
*/
static void
k_fn(struct kbd_data *kbd, unsigned char value)
{
if (kbd->func_table[value])
kbd_puts_queue(kbd->tty, kbd->func_table[value]);
}
static void
k_spec(struct kbd_data *kbd, unsigned char value)
{
if (value >= NR_FN_HANDLER)
return;
if (kbd->fn_handler[value])
kbd->fn_handler[value](kbd);
}
/*
* Put utf8 character to tty flip buffer.
* UTF-8 is defined for words of up to 31 bits,
* but we need only 16 bits here
*/
static void
to_utf8(struct tty_struct *tty, ushort c)
{
if (c < 0x80)
/* 0******* */
kbd_put_queue(tty, c);
else if (c < 0x800) {
/* 110***** 10****** */
kbd_put_queue(tty, 0xc0 | (c >> 6));
kbd_put_queue(tty, 0x80 | (c & 0x3f));
} else {
/* 1110**** 10****** 10****** */
kbd_put_queue(tty, 0xe0 | (c >> 12));
kbd_put_queue(tty, 0x80 | ((c >> 6) & 0x3f));
kbd_put_queue(tty, 0x80 | (c & 0x3f));
}
}
/*
* Process keycode.
*/
void
kbd_keycode(struct kbd_data *kbd, unsigned int keycode)
{
unsigned short keysym;
unsigned char type, value;
if (!kbd || !kbd->tty)
return;
if (keycode >= 384)
keysym = kbd->key_maps[5][keycode - 384];
else if (keycode >= 256)
keysym = kbd->key_maps[4][keycode - 256];
else if (keycode >= 128)
keysym = kbd->key_maps[1][keycode - 128];
else
keysym = kbd->key_maps[0][keycode];
type = KTYP(keysym);
if (type >= 0xf0) {
type -= 0xf0;
if (type == KT_LETTER)
type = KT_LATIN;
value = KVAL(keysym);
#ifdef CONFIG_MAGIC_SYSRQ /* Handle the SysRq Hack */
if (kbd->sysrq) {
if (kbd->sysrq == K(KT_LATIN, '-')) {
kbd->sysrq = 0;
handle_sysrq(value, kbd->tty);
return;
}
if (value == '-') {
kbd->sysrq = K(KT_LATIN, '-');
return;
}
/* Incomplete sysrq sequence. */
(*k_handler[KTYP(kbd->sysrq)])(kbd, KVAL(kbd->sysrq));
kbd->sysrq = 0;
} else if ((type == KT_LATIN && value == '^') ||
(type == KT_DEAD && ret_diacr[value] == '^')) {
kbd->sysrq = K(type, value);
return;
}
#endif
(*k_handler[type])(kbd, value);
} else
to_utf8(kbd->tty, keysym);
}
/*
* Ioctl stuff.
*/
static int
do_kdsk_ioctl(struct kbd_data *kbd, struct kbentry __user *user_kbe,
int cmd, int perm)
{
struct kbentry tmp;
ushort *key_map, val, ov;
if (copy_from_user(&tmp, user_kbe, sizeof(struct kbentry)))
return -EFAULT;
#if NR_KEYS < 256
if (tmp.kb_index >= NR_KEYS)
return -EINVAL;
#endif
#if MAX_NR_KEYMAPS < 256
if (tmp.kb_table >= MAX_NR_KEYMAPS)
return -EINVAL;
#endif
switch (cmd) {
case KDGKBENT:
key_map = kbd->key_maps[tmp.kb_table];
if (key_map) {
val = U(key_map[tmp.kb_index]);
if (KTYP(val) >= KBD_NR_TYPES)
val = K_HOLE;
} else
val = (tmp.kb_index ? K_HOLE : K_NOSUCHMAP);
return put_user(val, &user_kbe->kb_value);
case KDSKBENT:
if (!perm)
return -EPERM;
if (!tmp.kb_index && tmp.kb_value == K_NOSUCHMAP) {
/* disallocate map */
key_map = kbd->key_maps[tmp.kb_table];
if (key_map) {
kbd->key_maps[tmp.kb_table] = NULL;
kfree(key_map);
}
break;
}
if (KTYP(tmp.kb_value) >= KBD_NR_TYPES)
return -EINVAL;
if (KVAL(tmp.kb_value) > kbd_max_vals[KTYP(tmp.kb_value)])
return -EINVAL;
if (!(key_map = kbd->key_maps[tmp.kb_table])) {
int j;
key_map = kmalloc(sizeof(plain_map),
GFP_KERNEL);
if (!key_map)
return -ENOMEM;
kbd->key_maps[tmp.kb_table] = key_map;
for (j = 0; j < NR_KEYS; j++)
key_map[j] = U(K_HOLE);
}
ov = U(key_map[tmp.kb_index]);
if (tmp.kb_value == ov)
break; /* nothing to do */
/*
* Attention Key.
*/
if (((ov == K_SAK) || (tmp.kb_value == K_SAK)) &&
!capable(CAP_SYS_ADMIN))
return -EPERM;
key_map[tmp.kb_index] = U(tmp.kb_value);
break;
}
return 0;
}
static int
do_kdgkb_ioctl(struct kbd_data *kbd, struct kbsentry __user *u_kbs,
int cmd, int perm)
{
unsigned char kb_func;
char *p;
int len;
/* Get u_kbs->kb_func. */
if (get_user(kb_func, &u_kbs->kb_func))
return -EFAULT;
#if MAX_NR_FUNC < 256
if (kb_func >= MAX_NR_FUNC)
return -EINVAL;
#endif
switch (cmd) {
case KDGKBSENT:
p = kbd->func_table[kb_func];
if (p) {
len = strlen(p);
if (len >= sizeof(u_kbs->kb_string))
len = sizeof(u_kbs->kb_string) - 1;
if (copy_to_user(u_kbs->kb_string, p, len))
return -EFAULT;
} else
len = 0;
if (put_user('\0', u_kbs->kb_string + len))
return -EFAULT;
break;
case KDSKBSENT:
if (!perm)
return -EPERM;
len = strnlen_user(u_kbs->kb_string,
sizeof(u_kbs->kb_string) - 1);
if (!len)
return -EFAULT;
if (len > sizeof(u_kbs->kb_string) - 1)
return -EINVAL;
p = kmalloc(len + 1, GFP_KERNEL);
if (!p)
return -ENOMEM;
if (copy_from_user(p, u_kbs->kb_string, len)) {
kfree(p);
return -EFAULT;
}
p[len] = 0;
kfree(kbd->func_table[kb_func]);
kbd->func_table[kb_func] = p;
break;
}
return 0;
}
int
kbd_ioctl(struct kbd_data *kbd, struct file *file,
unsigned int cmd, unsigned long arg)
{
void __user *argp;
int ct, perm;
argp = (void __user *)arg;
/*
* To have permissions to do most of the vt ioctls, we either have
* to be the owner of the tty, or have CAP_SYS_TTY_CONFIG.
*/
perm = current->signal->tty == kbd->tty || capable(CAP_SYS_TTY_CONFIG);
switch (cmd) {
case KDGKBTYPE:
return put_user(KB_101, (char __user *)argp);
case KDGKBENT:
case KDSKBENT:
return do_kdsk_ioctl(kbd, argp, cmd, perm);
case KDGKBSENT:
case KDSKBSENT:
return do_kdgkb_ioctl(kbd, argp, cmd, perm);
case KDGKBDIACR:
{
struct kbdiacrs __user *a = argp;
struct kbdiacr diacr;
int i;
if (put_user(kbd->accent_table_size, &a->kb_cnt))
return -EFAULT;
for (i = 0; i < kbd->accent_table_size; i++) {
diacr.diacr = kbd->accent_table[i].diacr;
diacr.base = kbd->accent_table[i].base;
diacr.result = kbd->accent_table[i].result;
if (copy_to_user(a->kbdiacr + i, &diacr, sizeof(struct kbdiacr)))
return -EFAULT;
}
return 0;
}
case KDGKBDIACRUC:
{
struct kbdiacrsuc __user *a = argp;
ct = kbd->accent_table_size;
if (put_user(ct, &a->kb_cnt))
return -EFAULT;
if (copy_to_user(a->kbdiacruc, kbd->accent_table,
ct * sizeof(struct kbdiacruc)))
return -EFAULT;
return 0;
}
case KDSKBDIACR:
{
struct kbdiacrs __user *a = argp;
struct kbdiacr diacr;
int i;
if (!perm)
return -EPERM;
if (get_user(ct, &a->kb_cnt))
return -EFAULT;
if (ct >= MAX_DIACR)
return -EINVAL;
kbd->accent_table_size = ct;
for (i = 0; i < ct; i++) {
if (copy_from_user(&diacr, a->kbdiacr + i, sizeof(struct kbdiacr)))
return -EFAULT;
kbd->accent_table[i].diacr = diacr.diacr;
kbd->accent_table[i].base = diacr.base;
kbd->accent_table[i].result = diacr.result;
}
return 0;
}
case KDSKBDIACRUC:
{
struct kbdiacrsuc __user *a = argp;
if (!perm)
return -EPERM;
if (get_user(ct, &a->kb_cnt))
return -EFAULT;
if (ct >= MAX_DIACR)
return -EINVAL;
kbd->accent_table_size = ct;
if (copy_from_user(kbd->accent_table, a->kbdiacruc,
ct * sizeof(struct kbdiacruc)))
return -EFAULT;
return 0;
}
default:
return -ENOIOCTLCMD;
}
}
EXPORT_SYMBOL(kbd_ioctl);
EXPORT_SYMBOL(kbd_ascebc);
EXPORT_SYMBOL(kbd_free);
EXPORT_SYMBOL(kbd_alloc);
EXPORT_SYMBOL(kbd_keycode);
| gpl-2.0 |
lukino563/normandy_lulz_kernel | arch/x86/kernel/cpu/perf_event_intel.c | 715 | 51857 | /*
* Per core/cpu state
*
* Used to coordinate shared registers between HT threads or
* among events on a single PMU.
*/
#include <linux/stddef.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <asm/hardirq.h>
#include <asm/apic.h>
#include "perf_event.h"
/*
* Intel PerfMon, used on Core and later.
*/
static u64 intel_perfmon_event_map[PERF_COUNT_HW_MAX] __read_mostly =
{
[PERF_COUNT_HW_CPU_CYCLES] = 0x003c,
[PERF_COUNT_HW_INSTRUCTIONS] = 0x00c0,
[PERF_COUNT_HW_CACHE_REFERENCES] = 0x4f2e,
[PERF_COUNT_HW_CACHE_MISSES] = 0x412e,
[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x00c4,
[PERF_COUNT_HW_BRANCH_MISSES] = 0x00c5,
[PERF_COUNT_HW_BUS_CYCLES] = 0x013c,
[PERF_COUNT_HW_REF_CPU_CYCLES] = 0x0300, /* pseudo-encoding */
};
static struct event_constraint intel_core_event_constraints[] __read_mostly =
{
INTEL_EVENT_CONSTRAINT(0x11, 0x2), /* FP_ASSIST */
INTEL_EVENT_CONSTRAINT(0x12, 0x2), /* MUL */
INTEL_EVENT_CONSTRAINT(0x13, 0x2), /* DIV */
INTEL_EVENT_CONSTRAINT(0x14, 0x1), /* CYCLES_DIV_BUSY */
INTEL_EVENT_CONSTRAINT(0x19, 0x2), /* DELAYED_BYPASS */
INTEL_EVENT_CONSTRAINT(0xc1, 0x1), /* FP_COMP_INSTR_RET */
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_core2_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
INTEL_EVENT_CONSTRAINT(0x10, 0x1), /* FP_COMP_OPS_EXE */
INTEL_EVENT_CONSTRAINT(0x11, 0x2), /* FP_ASSIST */
INTEL_EVENT_CONSTRAINT(0x12, 0x2), /* MUL */
INTEL_EVENT_CONSTRAINT(0x13, 0x2), /* DIV */
INTEL_EVENT_CONSTRAINT(0x14, 0x1), /* CYCLES_DIV_BUSY */
INTEL_EVENT_CONSTRAINT(0x18, 0x1), /* IDLE_DURING_DIV */
INTEL_EVENT_CONSTRAINT(0x19, 0x2), /* DELAYED_BYPASS */
INTEL_EVENT_CONSTRAINT(0xa1, 0x1), /* RS_UOPS_DISPATCH_CYCLES */
INTEL_EVENT_CONSTRAINT(0xc9, 0x1), /* ITLB_MISS_RETIRED (T30-9) */
INTEL_EVENT_CONSTRAINT(0xcb, 0x1), /* MEM_LOAD_RETIRED */
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_nehalem_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
INTEL_EVENT_CONSTRAINT(0x40, 0x3), /* L1D_CACHE_LD */
INTEL_EVENT_CONSTRAINT(0x41, 0x3), /* L1D_CACHE_ST */
INTEL_EVENT_CONSTRAINT(0x42, 0x3), /* L1D_CACHE_LOCK */
INTEL_EVENT_CONSTRAINT(0x43, 0x3), /* L1D_ALL_REF */
INTEL_EVENT_CONSTRAINT(0x48, 0x3), /* L1D_PEND_MISS */
INTEL_EVENT_CONSTRAINT(0x4e, 0x3), /* L1D_PREFETCH */
INTEL_EVENT_CONSTRAINT(0x51, 0x3), /* L1D */
INTEL_EVENT_CONSTRAINT(0x63, 0x3), /* CACHE_LOCK_CYCLES */
EVENT_CONSTRAINT_END
};
static struct extra_reg intel_nehalem_extra_regs[] __read_mostly =
{
INTEL_EVENT_EXTRA_REG(0xb7, MSR_OFFCORE_RSP_0, 0xffff, RSP_0),
EVENT_EXTRA_END
};
static struct event_constraint intel_westmere_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
INTEL_EVENT_CONSTRAINT(0x51, 0x3), /* L1D */
INTEL_EVENT_CONSTRAINT(0x60, 0x1), /* OFFCORE_REQUESTS_OUTSTANDING */
INTEL_EVENT_CONSTRAINT(0x63, 0x3), /* CACHE_LOCK_CYCLES */
INTEL_EVENT_CONSTRAINT(0xb3, 0x1), /* SNOOPQ_REQUEST_OUTSTANDING */
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_snb_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
INTEL_EVENT_CONSTRAINT(0x48, 0x4), /* L1D_PEND_MISS.PENDING */
INTEL_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PREC_DIST */
INTEL_EVENT_CONSTRAINT(0xcd, 0x8), /* MEM_TRANS_RETIRED.LOAD_LATENCY */
EVENT_CONSTRAINT_END
};
static struct extra_reg intel_westmere_extra_regs[] __read_mostly =
{
INTEL_EVENT_EXTRA_REG(0xb7, MSR_OFFCORE_RSP_0, 0xffff, RSP_0),
INTEL_EVENT_EXTRA_REG(0xbb, MSR_OFFCORE_RSP_1, 0xffff, RSP_1),
EVENT_EXTRA_END
};
static struct event_constraint intel_v1_event_constraints[] __read_mostly =
{
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_gen_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
EVENT_CONSTRAINT_END
};
static struct extra_reg intel_snb_extra_regs[] __read_mostly = {
INTEL_EVENT_EXTRA_REG(0xb7, MSR_OFFCORE_RSP_0, 0x3f807f8fffull, RSP_0),
INTEL_EVENT_EXTRA_REG(0xbb, MSR_OFFCORE_RSP_1, 0x3f807f8fffull, RSP_1),
EVENT_EXTRA_END
};
static struct extra_reg intel_snbep_extra_regs[] __read_mostly = {
INTEL_EVENT_EXTRA_REG(0xb7, MSR_OFFCORE_RSP_0, 0x3fffff8fffull, RSP_0),
INTEL_EVENT_EXTRA_REG(0xbb, MSR_OFFCORE_RSP_1, 0x3fffff8fffull, RSP_1),
EVENT_EXTRA_END
};
static u64 intel_pmu_event_map(int hw_event)
{
return intel_perfmon_event_map[hw_event];
}
static __initconst const u64 snb_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0xf1d0, /* MEM_UOP_RETIRED.LOADS */
[ C(RESULT_MISS) ] = 0x0151, /* L1D.REPLACEMENT */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0xf2d0, /* MEM_UOP_RETIRED.STORES */
[ C(RESULT_MISS) ] = 0x0851, /* L1D.ALL_M_REPLACEMENT */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x024e, /* HW_PRE_REQ.DL1_MISS */
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0280, /* ICACHE.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
/* OFFCORE_RESPONSE.ANY_DATA.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_DATA.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_WRITE) ] = {
/* OFFCORE_RESPONSE.ANY_RFO.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_RFO.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
/* OFFCORE_RESPONSE.PREFETCH.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.PREFETCH.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x81d0, /* MEM_UOP_RETIRED.ALL_LOADS */
[ C(RESULT_MISS) ] = 0x0108, /* DTLB_LOAD_MISSES.CAUSES_A_WALK */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x82d0, /* MEM_UOP_RETIRED.ALL_STORES */
[ C(RESULT_MISS) ] = 0x0149, /* DTLB_STORE_MISSES.MISS_CAUSES_A_WALK */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x1085, /* ITLB_MISSES.STLB_HIT */
[ C(RESULT_MISS) ] = 0x0185, /* ITLB_MISSES.CAUSES_A_WALK */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ALL_BRANCHES */
[ C(RESULT_MISS) ] = 0x00c5, /* BR_MISP_RETIRED.ALL_BRANCHES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(NODE) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
};
static __initconst const u64 westmere_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x010b, /* MEM_INST_RETIRED.LOADS */
[ C(RESULT_MISS) ] = 0x0151, /* L1D.REPL */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x020b, /* MEM_INST_RETURED.STORES */
[ C(RESULT_MISS) ] = 0x0251, /* L1D.M_REPL */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x014e, /* L1D_PREFETCH.REQUESTS */
[ C(RESULT_MISS) ] = 0x024e, /* L1D_PREFETCH.MISS */
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0380, /* L1I.READS */
[ C(RESULT_MISS) ] = 0x0280, /* L1I.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
/* OFFCORE_RESPONSE.ANY_DATA.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_DATA.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
/*
* Use RFO, not WRITEBACK, because a write miss would typically occur
* on RFO.
*/
[ C(OP_WRITE) ] = {
/* OFFCORE_RESPONSE.ANY_RFO.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_RFO.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
/* OFFCORE_RESPONSE.PREFETCH.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.PREFETCH.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x010b, /* MEM_INST_RETIRED.LOADS */
[ C(RESULT_MISS) ] = 0x0108, /* DTLB_LOAD_MISSES.ANY */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x020b, /* MEM_INST_RETURED.STORES */
[ C(RESULT_MISS) ] = 0x010c, /* MEM_STORE_RETIRED.DTLB_MISS */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x01c0, /* INST_RETIRED.ANY_P */
[ C(RESULT_MISS) ] = 0x0185, /* ITLB_MISSES.ANY */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ALL_BRANCHES */
[ C(RESULT_MISS) ] = 0x03e8, /* BPU_CLEARS.ANY */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(NODE) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
},
};
/*
* Nehalem/Westmere MSR_OFFCORE_RESPONSE bits;
* See IA32 SDM Vol 3B 30.6.1.3
*/
#define NHM_DMND_DATA_RD (1 << 0)
#define NHM_DMND_RFO (1 << 1)
#define NHM_DMND_IFETCH (1 << 2)
#define NHM_DMND_WB (1 << 3)
#define NHM_PF_DATA_RD (1 << 4)
#define NHM_PF_DATA_RFO (1 << 5)
#define NHM_PF_IFETCH (1 << 6)
#define NHM_OFFCORE_OTHER (1 << 7)
#define NHM_UNCORE_HIT (1 << 8)
#define NHM_OTHER_CORE_HIT_SNP (1 << 9)
#define NHM_OTHER_CORE_HITM (1 << 10)
/* reserved */
#define NHM_REMOTE_CACHE_FWD (1 << 12)
#define NHM_REMOTE_DRAM (1 << 13)
#define NHM_LOCAL_DRAM (1 << 14)
#define NHM_NON_DRAM (1 << 15)
#define NHM_LOCAL (NHM_LOCAL_DRAM|NHM_REMOTE_CACHE_FWD)
#define NHM_REMOTE (NHM_REMOTE_DRAM)
#define NHM_DMND_READ (NHM_DMND_DATA_RD)
#define NHM_DMND_WRITE (NHM_DMND_RFO|NHM_DMND_WB)
#define NHM_DMND_PREFETCH (NHM_PF_DATA_RD|NHM_PF_DATA_RFO)
#define NHM_L3_HIT (NHM_UNCORE_HIT|NHM_OTHER_CORE_HIT_SNP|NHM_OTHER_CORE_HITM)
#define NHM_L3_MISS (NHM_NON_DRAM|NHM_LOCAL_DRAM|NHM_REMOTE_DRAM|NHM_REMOTE_CACHE_FWD)
#define NHM_L3_ACCESS (NHM_L3_HIT|NHM_L3_MISS)
static __initconst const u64 nehalem_hw_cache_extra_regs
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(LL ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_READ|NHM_L3_ACCESS,
[ C(RESULT_MISS) ] = NHM_DMND_READ|NHM_L3_MISS,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_WRITE|NHM_L3_ACCESS,
[ C(RESULT_MISS) ] = NHM_DMND_WRITE|NHM_L3_MISS,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_PREFETCH|NHM_L3_ACCESS,
[ C(RESULT_MISS) ] = NHM_DMND_PREFETCH|NHM_L3_MISS,
},
},
[ C(NODE) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_READ|NHM_LOCAL|NHM_REMOTE,
[ C(RESULT_MISS) ] = NHM_DMND_READ|NHM_REMOTE,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_WRITE|NHM_LOCAL|NHM_REMOTE,
[ C(RESULT_MISS) ] = NHM_DMND_WRITE|NHM_REMOTE,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_PREFETCH|NHM_LOCAL|NHM_REMOTE,
[ C(RESULT_MISS) ] = NHM_DMND_PREFETCH|NHM_REMOTE,
},
},
};
static __initconst const u64 nehalem_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x010b, /* MEM_INST_RETIRED.LOADS */
[ C(RESULT_MISS) ] = 0x0151, /* L1D.REPL */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x020b, /* MEM_INST_RETURED.STORES */
[ C(RESULT_MISS) ] = 0x0251, /* L1D.M_REPL */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x014e, /* L1D_PREFETCH.REQUESTS */
[ C(RESULT_MISS) ] = 0x024e, /* L1D_PREFETCH.MISS */
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0380, /* L1I.READS */
[ C(RESULT_MISS) ] = 0x0280, /* L1I.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
/* OFFCORE_RESPONSE.ANY_DATA.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_DATA.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
/*
* Use RFO, not WRITEBACK, because a write miss would typically occur
* on RFO.
*/
[ C(OP_WRITE) ] = {
/* OFFCORE_RESPONSE.ANY_RFO.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_RFO.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
/* OFFCORE_RESPONSE.PREFETCH.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.PREFETCH.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI (alias) */
[ C(RESULT_MISS) ] = 0x0108, /* DTLB_LOAD_MISSES.ANY */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI (alias) */
[ C(RESULT_MISS) ] = 0x010c, /* MEM_STORE_RETIRED.DTLB_MISS */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x01c0, /* INST_RETIRED.ANY_P */
[ C(RESULT_MISS) ] = 0x20c8, /* ITLB_MISS_RETIRED */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ALL_BRANCHES */
[ C(RESULT_MISS) ] = 0x03e8, /* BPU_CLEARS.ANY */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(NODE) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
},
};
static __initconst const u64 core2_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI */
[ C(RESULT_MISS) ] = 0x0140, /* L1D_CACHE_LD.I_STATE */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI */
[ C(RESULT_MISS) ] = 0x0141, /* L1D_CACHE_ST.I_STATE */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x104e, /* L1D_PREFETCH.REQUESTS */
[ C(RESULT_MISS) ] = 0,
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0080, /* L1I.READS */
[ C(RESULT_MISS) ] = 0x0081, /* L1I.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x4f29, /* L2_LD.MESI */
[ C(RESULT_MISS) ] = 0x4129, /* L2_LD.ISTATE */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x4f2A, /* L2_ST.MESI */
[ C(RESULT_MISS) ] = 0x412A, /* L2_ST.ISTATE */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI (alias) */
[ C(RESULT_MISS) ] = 0x0208, /* DTLB_MISSES.MISS_LD */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI (alias) */
[ C(RESULT_MISS) ] = 0x0808, /* DTLB_MISSES.MISS_ST */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c0, /* INST_RETIRED.ANY_P */
[ C(RESULT_MISS) ] = 0x1282, /* ITLBMISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ANY */
[ C(RESULT_MISS) ] = 0x00c5, /* BP_INST_RETIRED.MISPRED */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
};
static __initconst const u64 atom_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x2140, /* L1D_CACHE.LD */
[ C(RESULT_MISS) ] = 0,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x2240, /* L1D_CACHE.ST */
[ C(RESULT_MISS) ] = 0,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0380, /* L1I.READS */
[ C(RESULT_MISS) ] = 0x0280, /* L1I.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x4f29, /* L2_LD.MESI */
[ C(RESULT_MISS) ] = 0x4129, /* L2_LD.ISTATE */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x4f2A, /* L2_ST.MESI */
[ C(RESULT_MISS) ] = 0x412A, /* L2_ST.ISTATE */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x2140, /* L1D_CACHE_LD.MESI (alias) */
[ C(RESULT_MISS) ] = 0x0508, /* DTLB_MISSES.MISS_LD */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x2240, /* L1D_CACHE_ST.MESI (alias) */
[ C(RESULT_MISS) ] = 0x0608, /* DTLB_MISSES.MISS_ST */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c0, /* INST_RETIRED.ANY_P */
[ C(RESULT_MISS) ] = 0x0282, /* ITLB.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ANY */
[ C(RESULT_MISS) ] = 0x00c5, /* BP_INST_RETIRED.MISPRED */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
};
static inline bool intel_pmu_needs_lbr_smpl(struct perf_event *event)
{
/* user explicitly requested branch sampling */
if (has_branch_stack(event))
return true;
/* implicit branch sampling to correct PEBS skid */
if (x86_pmu.intel_cap.pebs_trap && event->attr.precise_ip > 1)
return true;
return false;
}
static void intel_pmu_disable_all(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0);
if (test_bit(X86_PMC_IDX_FIXED_BTS, cpuc->active_mask))
intel_pmu_disable_bts();
intel_pmu_pebs_disable_all();
intel_pmu_lbr_disable_all();
}
static void intel_pmu_enable_all(int added)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
intel_pmu_pebs_enable_all();
intel_pmu_lbr_enable_all();
wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL,
x86_pmu.intel_ctrl & ~cpuc->intel_ctrl_guest_mask);
if (test_bit(X86_PMC_IDX_FIXED_BTS, cpuc->active_mask)) {
struct perf_event *event =
cpuc->events[X86_PMC_IDX_FIXED_BTS];
if (WARN_ON_ONCE(!event))
return;
intel_pmu_enable_bts(event->hw.config);
}
}
/*
* Workaround for:
* Intel Errata AAK100 (model 26)
* Intel Errata AAP53 (model 30)
* Intel Errata BD53 (model 44)
*
* The official story:
* These chips need to be 'reset' when adding counters by programming the
* magic three (non-counting) events 0x4300B5, 0x4300D2, and 0x4300B1 either
* in sequence on the same PMC or on different PMCs.
*
* In practise it appears some of these events do in fact count, and
* we need to programm all 4 events.
*/
static void intel_pmu_nhm_workaround(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
static const unsigned long nhm_magic[4] = {
0x4300B5,
0x4300D2,
0x4300B1,
0x4300B1
};
struct perf_event *event;
int i;
/*
* The Errata requires below steps:
* 1) Clear MSR_IA32_PEBS_ENABLE and MSR_CORE_PERF_GLOBAL_CTRL;
* 2) Configure 4 PERFEVTSELx with the magic events and clear
* the corresponding PMCx;
* 3) set bit0~bit3 of MSR_CORE_PERF_GLOBAL_CTRL;
* 4) Clear MSR_CORE_PERF_GLOBAL_CTRL;
* 5) Clear 4 pairs of ERFEVTSELx and PMCx;
*/
/*
* The real steps we choose are a little different from above.
* A) To reduce MSR operations, we don't run step 1) as they
* are already cleared before this function is called;
* B) Call x86_perf_event_update to save PMCx before configuring
* PERFEVTSELx with magic number;
* C) With step 5), we do clear only when the PERFEVTSELx is
* not used currently.
* D) Call x86_perf_event_set_period to restore PMCx;
*/
/* We always operate 4 pairs of PERF Counters */
for (i = 0; i < 4; i++) {
event = cpuc->events[i];
if (event)
x86_perf_event_update(event);
}
for (i = 0; i < 4; i++) {
wrmsrl(MSR_ARCH_PERFMON_EVENTSEL0 + i, nhm_magic[i]);
wrmsrl(MSR_ARCH_PERFMON_PERFCTR0 + i, 0x0);
}
wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0xf);
wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0x0);
for (i = 0; i < 4; i++) {
event = cpuc->events[i];
if (event) {
x86_perf_event_set_period(event);
__x86_pmu_enable_event(&event->hw,
ARCH_PERFMON_EVENTSEL_ENABLE);
} else
wrmsrl(MSR_ARCH_PERFMON_EVENTSEL0 + i, 0x0);
}
}
static void intel_pmu_nhm_enable_all(int added)
{
if (added)
intel_pmu_nhm_workaround();
intel_pmu_enable_all(added);
}
static inline u64 intel_pmu_get_status(void)
{
u64 status;
rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
return status;
}
static inline void intel_pmu_ack_status(u64 ack)
{
wrmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, ack);
}
static void intel_pmu_disable_fixed(struct hw_perf_event *hwc)
{
int idx = hwc->idx - X86_PMC_IDX_FIXED;
u64 ctrl_val, mask;
mask = 0xfULL << (idx * 4);
rdmsrl(hwc->config_base, ctrl_val);
ctrl_val &= ~mask;
wrmsrl(hwc->config_base, ctrl_val);
}
static void intel_pmu_disable_event(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
if (unlikely(hwc->idx == X86_PMC_IDX_FIXED_BTS)) {
intel_pmu_disable_bts();
intel_pmu_drain_bts_buffer();
return;
}
cpuc->intel_ctrl_guest_mask &= ~(1ull << hwc->idx);
cpuc->intel_ctrl_host_mask &= ~(1ull << hwc->idx);
/*
* must disable before any actual event
* because any event may be combined with LBR
*/
if (intel_pmu_needs_lbr_smpl(event))
intel_pmu_lbr_disable(event);
if (unlikely(hwc->config_base == MSR_ARCH_PERFMON_FIXED_CTR_CTRL)) {
intel_pmu_disable_fixed(hwc);
return;
}
x86_pmu_disable_event(event);
if (unlikely(event->attr.precise_ip))
intel_pmu_pebs_disable(event);
}
static void intel_pmu_enable_fixed(struct hw_perf_event *hwc)
{
int idx = hwc->idx - X86_PMC_IDX_FIXED;
u64 ctrl_val, bits, mask;
/*
* Enable IRQ generation (0x8),
* and enable ring-3 counting (0x2) and ring-0 counting (0x1)
* if requested:
*/
bits = 0x8ULL;
if (hwc->config & ARCH_PERFMON_EVENTSEL_USR)
bits |= 0x2;
if (hwc->config & ARCH_PERFMON_EVENTSEL_OS)
bits |= 0x1;
/*
* ANY bit is supported in v3 and up
*/
if (x86_pmu.version > 2 && hwc->config & ARCH_PERFMON_EVENTSEL_ANY)
bits |= 0x4;
bits <<= (idx * 4);
mask = 0xfULL << (idx * 4);
rdmsrl(hwc->config_base, ctrl_val);
ctrl_val &= ~mask;
ctrl_val |= bits;
wrmsrl(hwc->config_base, ctrl_val);
}
static void intel_pmu_enable_event(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
if (unlikely(hwc->idx == X86_PMC_IDX_FIXED_BTS)) {
if (!__this_cpu_read(cpu_hw_events.enabled))
return;
intel_pmu_enable_bts(hwc->config);
return;
}
/*
* must enabled before any actual event
* because any event may be combined with LBR
*/
if (intel_pmu_needs_lbr_smpl(event))
intel_pmu_lbr_enable(event);
if (event->attr.exclude_host)
cpuc->intel_ctrl_guest_mask |= (1ull << hwc->idx);
if (event->attr.exclude_guest)
cpuc->intel_ctrl_host_mask |= (1ull << hwc->idx);
if (unlikely(hwc->config_base == MSR_ARCH_PERFMON_FIXED_CTR_CTRL)) {
intel_pmu_enable_fixed(hwc);
return;
}
if (unlikely(event->attr.precise_ip))
intel_pmu_pebs_enable(event);
__x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
}
/*
* Save and restart an expired event. Called by NMI contexts,
* so it has to be careful about preempting normal event ops:
*/
int intel_pmu_save_and_restart(struct perf_event *event)
{
x86_perf_event_update(event);
return x86_perf_event_set_period(event);
}
static void intel_pmu_reset(void)
{
struct debug_store *ds = __this_cpu_read(cpu_hw_events.ds);
unsigned long flags;
int idx;
if (!x86_pmu.num_counters)
return;
local_irq_save(flags);
printk("clearing PMU state on CPU#%d\n", smp_processor_id());
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
checking_wrmsrl(x86_pmu_config_addr(idx), 0ull);
checking_wrmsrl(x86_pmu_event_addr(idx), 0ull);
}
for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++)
checking_wrmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, 0ull);
if (ds)
ds->bts_index = ds->bts_buffer_base;
local_irq_restore(flags);
}
/*
* This handler is triggered by the local APIC, so the APIC IRQ handling
* rules apply:
*/
static int intel_pmu_handle_irq(struct pt_regs *regs)
{
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
int bit, loops;
u64 status;
int handled;
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
/*
* Some chipsets need to unmask the LVTPC in a particular spot
* inside the nmi handler. As a result, the unmasking was pushed
* into all the nmi handlers.
*
* This handler doesn't seem to have any issues with the unmasking
* so it was left at the top.
*/
apic_write(APIC_LVTPC, APIC_DM_NMI);
intel_pmu_disable_all();
handled = intel_pmu_drain_bts_buffer();
status = intel_pmu_get_status();
if (!status) {
intel_pmu_enable_all(0);
return handled;
}
loops = 0;
again:
intel_pmu_ack_status(status);
if (++loops > 100) {
WARN_ONCE(1, "perfevents: irq loop stuck!\n");
perf_event_print_debug();
intel_pmu_reset();
goto done;
}
inc_irq_stat(apic_perf_irqs);
intel_pmu_lbr_read();
/*
* CondChgd bit 63 doesn't mean any overflow status. Ignore
* and clear the bit.
*/
if (__test_and_clear_bit(63, (unsigned long *)&status)) {
if (!status)
goto done;
}
/*
* PEBS overflow sets bit 62 in the global status register
*/
if (__test_and_clear_bit(62, (unsigned long *)&status)) {
handled++;
x86_pmu.drain_pebs(regs);
}
for_each_set_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) {
struct perf_event *event = cpuc->events[bit];
handled++;
if (!test_bit(bit, cpuc->active_mask))
continue;
if (!intel_pmu_save_and_restart(event))
continue;
data.period = event->hw.last_period;
if (has_branch_stack(event))
data.br_stack = &cpuc->lbr_stack;
if (perf_event_overflow(event, &data, regs))
x86_pmu_stop(event, 0);
}
/*
* Repeat if there is more work to be done:
*/
status = intel_pmu_get_status();
if (status)
goto again;
done:
intel_pmu_enable_all(0);
return handled;
}
static struct event_constraint *
intel_bts_constraints(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
unsigned int hw_event, bts_event;
if (event->attr.freq)
return NULL;
hw_event = hwc->config & INTEL_ARCH_EVENT_MASK;
bts_event = x86_pmu.event_map(PERF_COUNT_HW_BRANCH_INSTRUCTIONS);
if (unlikely(hw_event == bts_event && hwc->sample_period == 1))
return &bts_constraint;
return NULL;
}
static bool intel_try_alt_er(struct perf_event *event, int orig_idx)
{
if (!(x86_pmu.er_flags & ERF_HAS_RSP_1))
return false;
if (event->hw.extra_reg.idx == EXTRA_REG_RSP_0) {
event->hw.config &= ~INTEL_ARCH_EVENT_MASK;
event->hw.config |= 0x01bb;
event->hw.extra_reg.idx = EXTRA_REG_RSP_1;
event->hw.extra_reg.reg = MSR_OFFCORE_RSP_1;
} else if (event->hw.extra_reg.idx == EXTRA_REG_RSP_1) {
event->hw.config &= ~INTEL_ARCH_EVENT_MASK;
event->hw.config |= 0x01b7;
event->hw.extra_reg.idx = EXTRA_REG_RSP_0;
event->hw.extra_reg.reg = MSR_OFFCORE_RSP_0;
}
if (event->hw.extra_reg.idx == orig_idx)
return false;
return true;
}
/*
* manage allocation of shared extra msr for certain events
*
* sharing can be:
* per-cpu: to be shared between the various events on a single PMU
* per-core: per-cpu + shared by HT threads
*/
static struct event_constraint *
__intel_shared_reg_get_constraints(struct cpu_hw_events *cpuc,
struct perf_event *event,
struct hw_perf_event_extra *reg)
{
struct event_constraint *c = &emptyconstraint;
struct er_account *era;
unsigned long flags;
int orig_idx = reg->idx;
/* already allocated shared msr */
if (reg->alloc)
return NULL; /* call x86_get_event_constraint() */
again:
era = &cpuc->shared_regs->regs[reg->idx];
/*
* we use spin_lock_irqsave() to avoid lockdep issues when
* passing a fake cpuc
*/
raw_spin_lock_irqsave(&era->lock, flags);
if (!atomic_read(&era->ref) || era->config == reg->config) {
/* lock in msr value */
era->config = reg->config;
era->reg = reg->reg;
/* one more user */
atomic_inc(&era->ref);
/* no need to reallocate during incremental event scheduling */
reg->alloc = 1;
/*
* need to call x86_get_event_constraint()
* to check if associated event has constraints
*/
c = NULL;
} else if (intel_try_alt_er(event, orig_idx)) {
raw_spin_unlock_irqrestore(&era->lock, flags);
goto again;
}
raw_spin_unlock_irqrestore(&era->lock, flags);
return c;
}
static void
__intel_shared_reg_put_constraints(struct cpu_hw_events *cpuc,
struct hw_perf_event_extra *reg)
{
struct er_account *era;
/*
* only put constraint if extra reg was actually
* allocated. Also takes care of event which do
* not use an extra shared reg
*/
if (!reg->alloc)
return;
era = &cpuc->shared_regs->regs[reg->idx];
/* one fewer user */
atomic_dec(&era->ref);
/* allocate again next time */
reg->alloc = 0;
}
static struct event_constraint *
intel_shared_regs_constraints(struct cpu_hw_events *cpuc,
struct perf_event *event)
{
struct event_constraint *c = NULL, *d;
struct hw_perf_event_extra *xreg, *breg;
xreg = &event->hw.extra_reg;
if (xreg->idx != EXTRA_REG_NONE) {
c = __intel_shared_reg_get_constraints(cpuc, event, xreg);
if (c == &emptyconstraint)
return c;
}
breg = &event->hw.branch_reg;
if (breg->idx != EXTRA_REG_NONE) {
d = __intel_shared_reg_get_constraints(cpuc, event, breg);
if (d == &emptyconstraint) {
__intel_shared_reg_put_constraints(cpuc, xreg);
c = d;
}
}
return c;
}
struct event_constraint *
x86_get_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event)
{
struct event_constraint *c;
if (x86_pmu.event_constraints) {
for_each_event_constraint(c, x86_pmu.event_constraints) {
if ((event->hw.config & c->cmask) == c->code)
return c;
}
}
return &unconstrained;
}
static struct event_constraint *
intel_get_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event)
{
struct event_constraint *c;
c = intel_bts_constraints(event);
if (c)
return c;
c = intel_pebs_constraints(event);
if (c)
return c;
c = intel_shared_regs_constraints(cpuc, event);
if (c)
return c;
return x86_get_event_constraints(cpuc, event);
}
static void
intel_put_shared_regs_event_constraints(struct cpu_hw_events *cpuc,
struct perf_event *event)
{
struct hw_perf_event_extra *reg;
reg = &event->hw.extra_reg;
if (reg->idx != EXTRA_REG_NONE)
__intel_shared_reg_put_constraints(cpuc, reg);
reg = &event->hw.branch_reg;
if (reg->idx != EXTRA_REG_NONE)
__intel_shared_reg_put_constraints(cpuc, reg);
}
static void intel_put_event_constraints(struct cpu_hw_events *cpuc,
struct perf_event *event)
{
intel_put_shared_regs_event_constraints(cpuc, event);
}
static int intel_pmu_hw_config(struct perf_event *event)
{
int ret = x86_pmu_hw_config(event);
if (ret)
return ret;
if (event->attr.precise_ip &&
(event->hw.config & X86_RAW_EVENT_MASK) == 0x003c) {
/*
* Use an alternative encoding for CPU_CLK_UNHALTED.THREAD_P
* (0x003c) so that we can use it with PEBS.
*
* The regular CPU_CLK_UNHALTED.THREAD_P event (0x003c) isn't
* PEBS capable. However we can use INST_RETIRED.ANY_P
* (0x00c0), which is a PEBS capable event, to get the same
* count.
*
* INST_RETIRED.ANY_P counts the number of cycles that retires
* CNTMASK instructions. By setting CNTMASK to a value (16)
* larger than the maximum number of instructions that can be
* retired per cycle (4) and then inverting the condition, we
* count all cycles that retire 16 or less instructions, which
* is every cycle.
*
* Thereby we gain a PEBS capable cycle counter.
*/
u64 alt_config = X86_CONFIG(.event=0xc0, .inv=1, .cmask=16);
alt_config |= (event->hw.config & ~X86_RAW_EVENT_MASK);
event->hw.config = alt_config;
}
if (intel_pmu_needs_lbr_smpl(event)) {
ret = intel_pmu_setup_lbr_filter(event);
if (ret)
return ret;
}
if (event->attr.type != PERF_TYPE_RAW)
return 0;
if (!(event->attr.config & ARCH_PERFMON_EVENTSEL_ANY))
return 0;
if (x86_pmu.version < 3)
return -EINVAL;
if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
return -EACCES;
event->hw.config |= ARCH_PERFMON_EVENTSEL_ANY;
return 0;
}
struct perf_guest_switch_msr *perf_guest_get_msrs(int *nr)
{
if (x86_pmu.guest_get_msrs)
return x86_pmu.guest_get_msrs(nr);
*nr = 0;
return NULL;
}
EXPORT_SYMBOL_GPL(perf_guest_get_msrs);
static struct perf_guest_switch_msr *intel_guest_get_msrs(int *nr)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct perf_guest_switch_msr *arr = cpuc->guest_switch_msrs;
arr[0].msr = MSR_CORE_PERF_GLOBAL_CTRL;
arr[0].host = x86_pmu.intel_ctrl & ~cpuc->intel_ctrl_guest_mask;
arr[0].guest = x86_pmu.intel_ctrl & ~cpuc->intel_ctrl_host_mask;
*nr = 1;
return arr;
}
static struct perf_guest_switch_msr *core_guest_get_msrs(int *nr)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct perf_guest_switch_msr *arr = cpuc->guest_switch_msrs;
int idx;
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
struct perf_event *event = cpuc->events[idx];
arr[idx].msr = x86_pmu_config_addr(idx);
arr[idx].host = arr[idx].guest = 0;
if (!test_bit(idx, cpuc->active_mask))
continue;
arr[idx].host = arr[idx].guest =
event->hw.config | ARCH_PERFMON_EVENTSEL_ENABLE;
if (event->attr.exclude_host)
arr[idx].host &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
else if (event->attr.exclude_guest)
arr[idx].guest &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
}
*nr = x86_pmu.num_counters;
return arr;
}
static void core_pmu_enable_event(struct perf_event *event)
{
if (!event->attr.exclude_host)
x86_pmu_enable_event(event);
}
static void core_pmu_enable_all(int added)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
int idx;
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
if (!test_bit(idx, cpuc->active_mask) ||
cpuc->events[idx]->attr.exclude_host)
continue;
__x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
}
}
PMU_FORMAT_ATTR(event, "config:0-7" );
PMU_FORMAT_ATTR(umask, "config:8-15" );
PMU_FORMAT_ATTR(edge, "config:18" );
PMU_FORMAT_ATTR(pc, "config:19" );
PMU_FORMAT_ATTR(any, "config:21" ); /* v3 + */
PMU_FORMAT_ATTR(inv, "config:23" );
PMU_FORMAT_ATTR(cmask, "config:24-31" );
static struct attribute *intel_arch_formats_attr[] = {
&format_attr_event.attr,
&format_attr_umask.attr,
&format_attr_edge.attr,
&format_attr_pc.attr,
&format_attr_inv.attr,
&format_attr_cmask.attr,
NULL,
};
static __initconst const struct x86_pmu core_pmu = {
.name = "core",
.handle_irq = x86_pmu_handle_irq,
.disable_all = x86_pmu_disable_all,
.enable_all = core_pmu_enable_all,
.enable = core_pmu_enable_event,
.disable = x86_pmu_disable_event,
.hw_config = x86_pmu_hw_config,
.schedule_events = x86_schedule_events,
.eventsel = MSR_ARCH_PERFMON_EVENTSEL0,
.perfctr = MSR_ARCH_PERFMON_PERFCTR0,
.event_map = intel_pmu_event_map,
.max_events = ARRAY_SIZE(intel_perfmon_event_map),
.apic = 1,
/*
* Intel PMCs cannot be accessed sanely above 32 bit width,
* so we install an artificial 1<<31 period regardless of
* the generic event period:
*/
.max_period = (1ULL << 31) - 1,
.get_event_constraints = intel_get_event_constraints,
.put_event_constraints = intel_put_event_constraints,
.event_constraints = intel_core_event_constraints,
.guest_get_msrs = core_guest_get_msrs,
.format_attrs = intel_arch_formats_attr,
};
struct intel_shared_regs *allocate_shared_regs(int cpu)
{
struct intel_shared_regs *regs;
int i;
regs = kzalloc_node(sizeof(struct intel_shared_regs),
GFP_KERNEL, cpu_to_node(cpu));
if (regs) {
/*
* initialize the locks to keep lockdep happy
*/
for (i = 0; i < EXTRA_REG_MAX; i++)
raw_spin_lock_init(®s->regs[i].lock);
regs->core_id = -1;
}
return regs;
}
static int intel_pmu_cpu_prepare(int cpu)
{
struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
if (!(x86_pmu.extra_regs || x86_pmu.lbr_sel_map))
return NOTIFY_OK;
cpuc->shared_regs = allocate_shared_regs(cpu);
if (!cpuc->shared_regs)
return NOTIFY_BAD;
return NOTIFY_OK;
}
static void intel_pmu_cpu_starting(int cpu)
{
struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
int core_id = topology_core_id(cpu);
int i;
init_debug_store_on_cpu(cpu);
/*
* Deal with CPUs that don't clear their LBRs on power-up.
*/
intel_pmu_lbr_reset();
cpuc->lbr_sel = NULL;
if (!cpuc->shared_regs)
return;
if (!(x86_pmu.er_flags & ERF_NO_HT_SHARING)) {
for_each_cpu(i, topology_thread_cpumask(cpu)) {
struct intel_shared_regs *pc;
pc = per_cpu(cpu_hw_events, i).shared_regs;
if (pc && pc->core_id == core_id) {
cpuc->kfree_on_online = cpuc->shared_regs;
cpuc->shared_regs = pc;
break;
}
}
cpuc->shared_regs->core_id = core_id;
cpuc->shared_regs->refcnt++;
}
if (x86_pmu.lbr_sel_map)
cpuc->lbr_sel = &cpuc->shared_regs->regs[EXTRA_REG_LBR];
}
static void intel_pmu_cpu_dying(int cpu)
{
struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
struct intel_shared_regs *pc;
pc = cpuc->shared_regs;
if (pc) {
if (pc->core_id == -1 || --pc->refcnt == 0)
kfree(pc);
cpuc->shared_regs = NULL;
}
fini_debug_store_on_cpu(cpu);
}
static void intel_pmu_flush_branch_stack(void)
{
/*
* Intel LBR does not tag entries with the
* PID of the current task, then we need to
* flush it on ctxsw
* For now, we simply reset it
*/
if (x86_pmu.lbr_nr)
intel_pmu_lbr_reset();
}
PMU_FORMAT_ATTR(offcore_rsp, "config1:0-63");
static struct attribute *intel_arch3_formats_attr[] = {
&format_attr_event.attr,
&format_attr_umask.attr,
&format_attr_edge.attr,
&format_attr_pc.attr,
&format_attr_any.attr,
&format_attr_inv.attr,
&format_attr_cmask.attr,
&format_attr_offcore_rsp.attr, /* XXX do NHM/WSM + SNB breakout */
NULL,
};
static __initconst const struct x86_pmu intel_pmu = {
.name = "Intel",
.handle_irq = intel_pmu_handle_irq,
.disable_all = intel_pmu_disable_all,
.enable_all = intel_pmu_enable_all,
.enable = intel_pmu_enable_event,
.disable = intel_pmu_disable_event,
.hw_config = intel_pmu_hw_config,
.schedule_events = x86_schedule_events,
.eventsel = MSR_ARCH_PERFMON_EVENTSEL0,
.perfctr = MSR_ARCH_PERFMON_PERFCTR0,
.event_map = intel_pmu_event_map,
.max_events = ARRAY_SIZE(intel_perfmon_event_map),
.apic = 1,
/*
* Intel PMCs cannot be accessed sanely above 32 bit width,
* so we install an artificial 1<<31 period regardless of
* the generic event period:
*/
.max_period = (1ULL << 31) - 1,
.get_event_constraints = intel_get_event_constraints,
.put_event_constraints = intel_put_event_constraints,
.format_attrs = intel_arch3_formats_attr,
.cpu_prepare = intel_pmu_cpu_prepare,
.cpu_starting = intel_pmu_cpu_starting,
.cpu_dying = intel_pmu_cpu_dying,
.guest_get_msrs = intel_guest_get_msrs,
.flush_branch_stack = intel_pmu_flush_branch_stack,
};
static __init void intel_clovertown_quirk(void)
{
/*
* PEBS is unreliable due to:
*
* AJ67 - PEBS may experience CPL leaks
* AJ68 - PEBS PMI may be delayed by one event
* AJ69 - GLOBAL_STATUS[62] will only be set when DEBUGCTL[12]
* AJ106 - FREEZE_LBRS_ON_PMI doesn't work in combination with PEBS
*
* AJ67 could be worked around by restricting the OS/USR flags.
* AJ69 could be worked around by setting PMU_FREEZE_ON_PMI.
*
* AJ106 could possibly be worked around by not allowing LBR
* usage from PEBS, including the fixup.
* AJ68 could possibly be worked around by always programming
* a pebs_event_reset[0] value and coping with the lost events.
*
* But taken together it might just make sense to not enable PEBS on
* these chips.
*/
printk(KERN_WARNING "PEBS disabled due to CPU errata.\n");
x86_pmu.pebs = 0;
x86_pmu.pebs_constraints = NULL;
}
static __init void intel_sandybridge_quirk(void)
{
printk(KERN_WARNING "PEBS disabled due to CPU errata.\n");
x86_pmu.pebs = 0;
x86_pmu.pebs_constraints = NULL;
}
static const struct { int id; char *name; } intel_arch_events_map[] __initconst = {
{ PERF_COUNT_HW_CPU_CYCLES, "cpu cycles" },
{ PERF_COUNT_HW_INSTRUCTIONS, "instructions" },
{ PERF_COUNT_HW_BUS_CYCLES, "bus cycles" },
{ PERF_COUNT_HW_CACHE_REFERENCES, "cache references" },
{ PERF_COUNT_HW_CACHE_MISSES, "cache misses" },
{ PERF_COUNT_HW_BRANCH_INSTRUCTIONS, "branch instructions" },
{ PERF_COUNT_HW_BRANCH_MISSES, "branch misses" },
};
static __init void intel_arch_events_quirk(void)
{
int bit;
/* disable event that reported as not presend by cpuid */
for_each_set_bit(bit, x86_pmu.events_mask, ARRAY_SIZE(intel_arch_events_map)) {
intel_perfmon_event_map[intel_arch_events_map[bit].id] = 0;
printk(KERN_WARNING "CPUID marked event: \'%s\' unavailable\n",
intel_arch_events_map[bit].name);
}
}
static __init void intel_nehalem_quirk(void)
{
union cpuid10_ebx ebx;
ebx.full = x86_pmu.events_maskl;
if (ebx.split.no_branch_misses_retired) {
/*
* Erratum AAJ80 detected, we work it around by using
* the BR_MISP_EXEC.ANY event. This will over-count
* branch-misses, but it's still much better than the
* architectural event which is often completely bogus:
*/
intel_perfmon_event_map[PERF_COUNT_HW_BRANCH_MISSES] = 0x7f89;
ebx.split.no_branch_misses_retired = 0;
x86_pmu.events_maskl = ebx.full;
printk(KERN_INFO "CPU erratum AAJ80 worked around\n");
}
}
__init int intel_pmu_init(void)
{
union cpuid10_edx edx;
union cpuid10_eax eax;
union cpuid10_ebx ebx;
unsigned int unused;
int version;
if (!cpu_has(&boot_cpu_data, X86_FEATURE_ARCH_PERFMON)) {
switch (boot_cpu_data.x86) {
case 0x6:
return p6_pmu_init();
case 0xf:
return p4_pmu_init();
}
return -ENODEV;
}
/*
* Check whether the Architectural PerfMon supports
* Branch Misses Retired hw_event or not.
*/
cpuid(10, &eax.full, &ebx.full, &unused, &edx.full);
if (eax.split.mask_length < ARCH_PERFMON_EVENTS_COUNT)
return -ENODEV;
version = eax.split.version_id;
if (version < 2)
x86_pmu = core_pmu;
else
x86_pmu = intel_pmu;
x86_pmu.version = version;
x86_pmu.num_counters = eax.split.num_counters;
x86_pmu.cntval_bits = eax.split.bit_width;
x86_pmu.cntval_mask = (1ULL << eax.split.bit_width) - 1;
x86_pmu.events_maskl = ebx.full;
x86_pmu.events_mask_len = eax.split.mask_length;
/*
* Quirk: v2 perfmon does not report fixed-purpose events, so
* assume at least 3 events:
*/
if (version > 1)
x86_pmu.num_counters_fixed = max((int)edx.split.num_counters_fixed, 3);
/*
* v2 and above have a perf capabilities MSR
*/
if (version > 1) {
u64 capabilities;
rdmsrl(MSR_IA32_PERF_CAPABILITIES, capabilities);
x86_pmu.intel_cap.capabilities = capabilities;
}
intel_ds_init();
x86_add_quirk(intel_arch_events_quirk); /* Install first, so it runs last */
/*
* Install the hw-cache-events table:
*/
switch (boot_cpu_data.x86_model) {
case 14: /* 65 nm core solo/duo, "Yonah" */
pr_cont("Core events, ");
break;
case 15: /* original 65 nm celeron/pentium/core2/xeon, "Merom"/"Conroe" */
x86_add_quirk(intel_clovertown_quirk);
case 22: /* single-core 65 nm celeron/core2solo "Merom-L"/"Conroe-L" */
case 23: /* current 45 nm celeron/core2/xeon "Penryn"/"Wolfdale" */
case 29: /* six-core 45 nm xeon "Dunnington" */
memcpy(hw_cache_event_ids, core2_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
intel_pmu_lbr_init_core();
x86_pmu.event_constraints = intel_core2_event_constraints;
x86_pmu.pebs_constraints = intel_core2_pebs_event_constraints;
pr_cont("Core2 events, ");
break;
case 26: /* 45 nm nehalem, "Bloomfield" */
case 30: /* 45 nm nehalem, "Lynnfield" */
case 46: /* 45 nm nehalem-ex, "Beckton" */
memcpy(hw_cache_event_ids, nehalem_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, nehalem_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_nhm();
x86_pmu.event_constraints = intel_nehalem_event_constraints;
x86_pmu.pebs_constraints = intel_nehalem_pebs_event_constraints;
x86_pmu.enable_all = intel_pmu_nhm_enable_all;
x86_pmu.extra_regs = intel_nehalem_extra_regs;
/* UOPS_ISSUED.STALLED_CYCLES */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
/* UOPS_EXECUTED.CORE_ACTIVE_CYCLES,c=1,i=1 */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =
X86_CONFIG(.event=0xb1, .umask=0x3f, .inv=1, .cmask=1);
x86_add_quirk(intel_nehalem_quirk);
pr_cont("Nehalem events, ");
break;
case 28: /* Atom */
memcpy(hw_cache_event_ids, atom_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
intel_pmu_lbr_init_atom();
x86_pmu.event_constraints = intel_gen_event_constraints;
x86_pmu.pebs_constraints = intel_atom_pebs_event_constraints;
pr_cont("Atom events, ");
break;
case 37: /* 32 nm nehalem, "Clarkdale" */
case 44: /* 32 nm nehalem, "Gulftown" */
case 47: /* 32 nm Xeon E7 */
memcpy(hw_cache_event_ids, westmere_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, nehalem_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_nhm();
x86_pmu.event_constraints = intel_westmere_event_constraints;
x86_pmu.enable_all = intel_pmu_nhm_enable_all;
x86_pmu.pebs_constraints = intel_westmere_pebs_event_constraints;
x86_pmu.extra_regs = intel_westmere_extra_regs;
x86_pmu.er_flags |= ERF_HAS_RSP_1;
/* UOPS_ISSUED.STALLED_CYCLES */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
/* UOPS_EXECUTED.CORE_ACTIVE_CYCLES,c=1,i=1 */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =
X86_CONFIG(.event=0xb1, .umask=0x3f, .inv=1, .cmask=1);
pr_cont("Westmere events, ");
break;
case 42: /* SandyBridge */
x86_add_quirk(intel_sandybridge_quirk);
case 45: /* SandyBridge, "Romely-EP" */
memcpy(hw_cache_event_ids, snb_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
intel_pmu_lbr_init_snb();
x86_pmu.event_constraints = intel_snb_event_constraints;
x86_pmu.pebs_constraints = intel_snb_pebs_event_constraints;
if (boot_cpu_data.x86_model == 45)
x86_pmu.extra_regs = intel_snbep_extra_regs;
else
x86_pmu.extra_regs = intel_snb_extra_regs;
/* all extra regs are per-cpu when HT is on */
x86_pmu.er_flags |= ERF_HAS_RSP_1;
x86_pmu.er_flags |= ERF_NO_HT_SHARING;
/* UOPS_ISSUED.ANY,c=1,i=1 to count stall cycles */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
/* UOPS_DISPATCHED.THREAD,c=1,i=1 to count stall cycles*/
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =
X86_CONFIG(.event=0xb1, .umask=0x01, .inv=1, .cmask=1);
pr_cont("SandyBridge events, ");
break;
default:
switch (x86_pmu.version) {
case 1:
x86_pmu.event_constraints = intel_v1_event_constraints;
pr_cont("generic architected perfmon v1, ");
break;
default:
/*
* default constraints for v2 and up
*/
x86_pmu.event_constraints = intel_gen_event_constraints;
pr_cont("generic architected perfmon, ");
break;
}
}
return 0;
}
| gpl-2.0 |
TheTypoMaster/ubuntu-utopic | drivers/net/ethernet/mellanox/mlx5/core/srq.c | 1227 | 6050 | /*
* Copyright (c) 2013, Mellanox Technologies 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/kernel.h>
#include <linux/module.h>
#include <linux/mlx5/driver.h>
#include <linux/mlx5/cmd.h>
#include <linux/mlx5/srq.h>
#include <rdma/ib_verbs.h>
#include "mlx5_core.h"
void mlx5_srq_event(struct mlx5_core_dev *dev, u32 srqn, int event_type)
{
struct mlx5_srq_table *table = &dev->priv.srq_table;
struct mlx5_core_srq *srq;
spin_lock(&table->lock);
srq = radix_tree_lookup(&table->tree, srqn);
if (srq)
atomic_inc(&srq->refcount);
spin_unlock(&table->lock);
if (!srq) {
mlx5_core_warn(dev, "Async event for bogus SRQ 0x%08x\n", srqn);
return;
}
srq->event(srq, event_type);
if (atomic_dec_and_test(&srq->refcount))
complete(&srq->free);
}
struct mlx5_core_srq *mlx5_core_get_srq(struct mlx5_core_dev *dev, u32 srqn)
{
struct mlx5_srq_table *table = &dev->priv.srq_table;
struct mlx5_core_srq *srq;
spin_lock(&table->lock);
srq = radix_tree_lookup(&table->tree, srqn);
if (srq)
atomic_inc(&srq->refcount);
spin_unlock(&table->lock);
return srq;
}
EXPORT_SYMBOL(mlx5_core_get_srq);
int mlx5_core_create_srq(struct mlx5_core_dev *dev, struct mlx5_core_srq *srq,
struct mlx5_create_srq_mbox_in *in, int inlen)
{
struct mlx5_create_srq_mbox_out out;
struct mlx5_srq_table *table = &dev->priv.srq_table;
struct mlx5_destroy_srq_mbox_in din;
struct mlx5_destroy_srq_mbox_out dout;
int err;
memset(&out, 0, sizeof(out));
in->hdr.opcode = cpu_to_be16(MLX5_CMD_OP_CREATE_SRQ);
err = mlx5_cmd_exec(dev, in, inlen, &out, sizeof(out));
if (err)
return err;
if (out.hdr.status)
return mlx5_cmd_status_to_err(&out.hdr);
srq->srqn = be32_to_cpu(out.srqn) & 0xffffff;
atomic_set(&srq->refcount, 1);
init_completion(&srq->free);
spin_lock_irq(&table->lock);
err = radix_tree_insert(&table->tree, srq->srqn, srq);
spin_unlock_irq(&table->lock);
if (err) {
mlx5_core_warn(dev, "err %d, srqn 0x%x\n", err, srq->srqn);
goto err_cmd;
}
return 0;
err_cmd:
memset(&din, 0, sizeof(din));
memset(&dout, 0, sizeof(dout));
din.srqn = cpu_to_be32(srq->srqn);
din.hdr.opcode = cpu_to_be16(MLX5_CMD_OP_DESTROY_SRQ);
mlx5_cmd_exec(dev, &din, sizeof(din), &dout, sizeof(dout));
return err;
}
EXPORT_SYMBOL(mlx5_core_create_srq);
int mlx5_core_destroy_srq(struct mlx5_core_dev *dev, struct mlx5_core_srq *srq)
{
struct mlx5_destroy_srq_mbox_in in;
struct mlx5_destroy_srq_mbox_out out;
struct mlx5_srq_table *table = &dev->priv.srq_table;
struct mlx5_core_srq *tmp;
int err;
spin_lock_irq(&table->lock);
tmp = radix_tree_delete(&table->tree, srq->srqn);
spin_unlock_irq(&table->lock);
if (!tmp) {
mlx5_core_warn(dev, "srq 0x%x not found in tree\n", srq->srqn);
return -EINVAL;
}
if (tmp != srq) {
mlx5_core_warn(dev, "corruption on srqn 0x%x\n", srq->srqn);
return -EINVAL;
}
memset(&in, 0, sizeof(in));
memset(&out, 0, sizeof(out));
in.hdr.opcode = cpu_to_be16(MLX5_CMD_OP_DESTROY_SRQ);
in.srqn = cpu_to_be32(srq->srqn);
err = mlx5_cmd_exec(dev, &in, sizeof(in), &out, sizeof(out));
if (err)
return err;
if (out.hdr.status)
return mlx5_cmd_status_to_err(&out.hdr);
if (atomic_dec_and_test(&srq->refcount))
complete(&srq->free);
wait_for_completion(&srq->free);
return 0;
}
EXPORT_SYMBOL(mlx5_core_destroy_srq);
int mlx5_core_query_srq(struct mlx5_core_dev *dev, struct mlx5_core_srq *srq,
struct mlx5_query_srq_mbox_out *out)
{
struct mlx5_query_srq_mbox_in in;
int err;
memset(&in, 0, sizeof(in));
memset(out, 0, sizeof(*out));
in.hdr.opcode = cpu_to_be16(MLX5_CMD_OP_QUERY_SRQ);
in.srqn = cpu_to_be32(srq->srqn);
err = mlx5_cmd_exec(dev, &in, sizeof(in), out, sizeof(*out));
if (err)
return err;
if (out->hdr.status)
return mlx5_cmd_status_to_err(&out->hdr);
return err;
}
EXPORT_SYMBOL(mlx5_core_query_srq);
int mlx5_core_arm_srq(struct mlx5_core_dev *dev, struct mlx5_core_srq *srq,
u16 lwm, int is_srq)
{
struct mlx5_arm_srq_mbox_in in;
struct mlx5_arm_srq_mbox_out out;
int err;
memset(&in, 0, sizeof(in));
memset(&out, 0, sizeof(out));
in.hdr.opcode = cpu_to_be16(MLX5_CMD_OP_ARM_RQ);
in.hdr.opmod = cpu_to_be16(!!is_srq);
in.srqn = cpu_to_be32(srq->srqn);
in.lwm = cpu_to_be16(lwm);
err = mlx5_cmd_exec(dev, &in, sizeof(in), &out, sizeof(out));
if (err)
return err;
if (out.hdr.status)
return mlx5_cmd_status_to_err(&out.hdr);
return err;
}
EXPORT_SYMBOL(mlx5_core_arm_srq);
void mlx5_init_srq_table(struct mlx5_core_dev *dev)
{
struct mlx5_srq_table *table = &dev->priv.srq_table;
spin_lock_init(&table->lock);
INIT_RADIX_TREE(&table->tree, GFP_ATOMIC);
}
void mlx5_cleanup_srq_table(struct mlx5_core_dev *dev)
{
/* nothing */
}
| gpl-2.0 |
chrisch1974/htc7x30-2.6-flyer | Documentation/accounting/getdelays.c | 1483 | 12224 | /* getdelays.c
*
* Utility to get per-pid and per-tgid delay accounting statistics
* Also illustrates usage of the taskstats interface
*
* Copyright (C) Shailabh Nagar, IBM Corp. 2005
* Copyright (C) Balbir Singh, IBM Corp. 2006
* Copyright (c) Jay Lan, SGI. 2006
*
* Compile with
* gcc -I/usr/src/linux/include getdelays.c -o getdelays
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <poll.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <signal.h>
#include <linux/genetlink.h>
#include <linux/taskstats.h>
#include <linux/cgroupstats.h>
/*
* Generic macros for dealing with netlink sockets. Might be duplicated
* elsewhere. It is recommended that commercial grade applications use
* libnl or libnetlink and use the interfaces provided by the library
*/
#define GENLMSG_DATA(glh) ((void *)(NLMSG_DATA(glh) + GENL_HDRLEN))
#define GENLMSG_PAYLOAD(glh) (NLMSG_PAYLOAD(glh, 0) - GENL_HDRLEN)
#define NLA_DATA(na) ((void *)((char*)(na) + NLA_HDRLEN))
#define NLA_PAYLOAD(len) (len - NLA_HDRLEN)
#define err(code, fmt, arg...) \
do { \
fprintf(stderr, fmt, ##arg); \
exit(code); \
} while (0)
int done;
int rcvbufsz;
char name[100];
int dbg;
int print_delays;
int print_io_accounting;
int print_task_context_switch_counts;
__u64 stime, utime;
#define PRINTF(fmt, arg...) { \
if (dbg) { \
printf(fmt, ##arg); \
} \
}
/* Maximum size of response requested or message sent */
#define MAX_MSG_SIZE 1024
/* Maximum number of cpus expected to be specified in a cpumask */
#define MAX_CPUS 32
struct msgtemplate {
struct nlmsghdr n;
struct genlmsghdr g;
char buf[MAX_MSG_SIZE];
};
char cpumask[100+6*MAX_CPUS];
static void usage(void)
{
fprintf(stderr, "getdelays [-dilv] [-w logfile] [-r bufsize] "
"[-m cpumask] [-t tgid] [-p pid]\n");
fprintf(stderr, " -d: print delayacct stats\n");
fprintf(stderr, " -i: print IO accounting (works only with -p)\n");
fprintf(stderr, " -l: listen forever\n");
fprintf(stderr, " -v: debug on\n");
fprintf(stderr, " -C: container path\n");
}
/*
* Create a raw netlink socket and bind
*/
static int create_nl_socket(int protocol)
{
int fd;
struct sockaddr_nl local;
fd = socket(AF_NETLINK, SOCK_RAW, protocol);
if (fd < 0)
return -1;
if (rcvbufsz)
if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF,
&rcvbufsz, sizeof(rcvbufsz)) < 0) {
fprintf(stderr, "Unable to set socket rcv buf size "
"to %d\n",
rcvbufsz);
return -1;
}
memset(&local, 0, sizeof(local));
local.nl_family = AF_NETLINK;
if (bind(fd, (struct sockaddr *) &local, sizeof(local)) < 0)
goto error;
return fd;
error:
close(fd);
return -1;
}
static int send_cmd(int sd, __u16 nlmsg_type, __u32 nlmsg_pid,
__u8 genl_cmd, __u16 nla_type,
void *nla_data, int nla_len)
{
struct nlattr *na;
struct sockaddr_nl nladdr;
int r, buflen;
char *buf;
struct msgtemplate msg;
msg.n.nlmsg_len = NLMSG_LENGTH(GENL_HDRLEN);
msg.n.nlmsg_type = nlmsg_type;
msg.n.nlmsg_flags = NLM_F_REQUEST;
msg.n.nlmsg_seq = 0;
msg.n.nlmsg_pid = nlmsg_pid;
msg.g.cmd = genl_cmd;
msg.g.version = 0x1;
na = (struct nlattr *) GENLMSG_DATA(&msg);
na->nla_type = nla_type;
na->nla_len = nla_len + 1 + NLA_HDRLEN;
memcpy(NLA_DATA(na), nla_data, nla_len);
msg.n.nlmsg_len += NLMSG_ALIGN(na->nla_len);
buf = (char *) &msg;
buflen = msg.n.nlmsg_len ;
memset(&nladdr, 0, sizeof(nladdr));
nladdr.nl_family = AF_NETLINK;
while ((r = sendto(sd, buf, buflen, 0, (struct sockaddr *) &nladdr,
sizeof(nladdr))) < buflen) {
if (r > 0) {
buf += r;
buflen -= r;
} else if (errno != EAGAIN)
return -1;
}
return 0;
}
/*
* Probe the controller in genetlink to find the family id
* for the TASKSTATS family
*/
static int get_family_id(int sd)
{
struct {
struct nlmsghdr n;
struct genlmsghdr g;
char buf[256];
} ans;
int id = 0, rc;
struct nlattr *na;
int rep_len;
strcpy(name, TASKSTATS_GENL_NAME);
rc = send_cmd(sd, GENL_ID_CTRL, getpid(), CTRL_CMD_GETFAMILY,
CTRL_ATTR_FAMILY_NAME, (void *)name,
strlen(TASKSTATS_GENL_NAME)+1);
rep_len = recv(sd, &ans, sizeof(ans), 0);
if (ans.n.nlmsg_type == NLMSG_ERROR ||
(rep_len < 0) || !NLMSG_OK((&ans.n), rep_len))
return 0;
na = (struct nlattr *) GENLMSG_DATA(&ans);
na = (struct nlattr *) ((char *) na + NLA_ALIGN(na->nla_len));
if (na->nla_type == CTRL_ATTR_FAMILY_ID) {
id = *(__u16 *) NLA_DATA(na);
}
return id;
}
static void print_delayacct(struct taskstats *t)
{
printf("\n\nCPU %15s%15s%15s%15s\n"
" %15llu%15llu%15llu%15llu\n"
"IO %15s%15s\n"
" %15llu%15llu\n"
"SWAP %15s%15s\n"
" %15llu%15llu\n"
"RECLAIM %12s%15s\n"
" %15llu%15llu\n",
"count", "real total", "virtual total", "delay total",
(unsigned long long)t->cpu_count,
(unsigned long long)t->cpu_run_real_total,
(unsigned long long)t->cpu_run_virtual_total,
(unsigned long long)t->cpu_delay_total,
"count", "delay total",
(unsigned long long)t->blkio_count,
(unsigned long long)t->blkio_delay_total,
"count", "delay total",
(unsigned long long)t->swapin_count,
(unsigned long long)t->swapin_delay_total,
"count", "delay total",
(unsigned long long)t->freepages_count,
(unsigned long long)t->freepages_delay_total);
}
static void task_context_switch_counts(struct taskstats *t)
{
printf("\n\nTask %15s%15s\n"
" %15llu%15llu\n",
"voluntary", "nonvoluntary",
(unsigned long long)t->nvcsw, (unsigned long long)t->nivcsw);
}
static void print_cgroupstats(struct cgroupstats *c)
{
printf("sleeping %llu, blocked %llu, running %llu, stopped %llu, "
"uninterruptible %llu\n", (unsigned long long)c->nr_sleeping,
(unsigned long long)c->nr_io_wait,
(unsigned long long)c->nr_running,
(unsigned long long)c->nr_stopped,
(unsigned long long)c->nr_uninterruptible);
}
static void print_ioacct(struct taskstats *t)
{
printf("%s: read=%llu, write=%llu, cancelled_write=%llu\n",
t->ac_comm,
(unsigned long long)t->read_bytes,
(unsigned long long)t->write_bytes,
(unsigned long long)t->cancelled_write_bytes);
}
int main(int argc, char *argv[])
{
int c, rc, rep_len, aggr_len, len2;
int cmd_type = TASKSTATS_CMD_ATTR_UNSPEC;
__u16 id;
__u32 mypid;
struct nlattr *na;
int nl_sd = -1;
int len = 0;
pid_t tid = 0;
pid_t rtid = 0;
int fd = 0;
int count = 0;
int write_file = 0;
int maskset = 0;
char *logfile = NULL;
int loop = 0;
int containerset = 0;
char containerpath[1024];
int cfd = 0;
struct msgtemplate msg;
while (1) {
c = getopt(argc, argv, "qdiw:r:m:t:p:vlC:");
if (c < 0)
break;
switch (c) {
case 'd':
printf("print delayacct stats ON\n");
print_delays = 1;
break;
case 'i':
printf("printing IO accounting\n");
print_io_accounting = 1;
break;
case 'q':
printf("printing task/process context switch rates\n");
print_task_context_switch_counts = 1;
break;
case 'C':
containerset = 1;
strncpy(containerpath, optarg, strlen(optarg) + 1);
break;
case 'w':
logfile = strdup(optarg);
printf("write to file %s\n", logfile);
write_file = 1;
break;
case 'r':
rcvbufsz = atoi(optarg);
printf("receive buf size %d\n", rcvbufsz);
if (rcvbufsz < 0)
err(1, "Invalid rcv buf size\n");
break;
case 'm':
strncpy(cpumask, optarg, sizeof(cpumask));
maskset = 1;
printf("cpumask %s maskset %d\n", cpumask, maskset);
break;
case 't':
tid = atoi(optarg);
if (!tid)
err(1, "Invalid tgid\n");
cmd_type = TASKSTATS_CMD_ATTR_TGID;
break;
case 'p':
tid = atoi(optarg);
if (!tid)
err(1, "Invalid pid\n");
cmd_type = TASKSTATS_CMD_ATTR_PID;
break;
case 'v':
printf("debug on\n");
dbg = 1;
break;
case 'l':
printf("listen forever\n");
loop = 1;
break;
default:
usage();
exit(-1);
}
}
if (write_file) {
fd = open(logfile, O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1) {
perror("Cannot open output file\n");
exit(1);
}
}
if ((nl_sd = create_nl_socket(NETLINK_GENERIC)) < 0)
err(1, "error creating Netlink socket\n");
mypid = getpid();
id = get_family_id(nl_sd);
if (!id) {
fprintf(stderr, "Error getting family id, errno %d\n", errno);
goto err;
}
PRINTF("family id %d\n", id);
if (maskset) {
rc = send_cmd(nl_sd, id, mypid, TASKSTATS_CMD_GET,
TASKSTATS_CMD_ATTR_REGISTER_CPUMASK,
&cpumask, strlen(cpumask) + 1);
PRINTF("Sent register cpumask, retval %d\n", rc);
if (rc < 0) {
fprintf(stderr, "error sending register cpumask\n");
goto err;
}
}
if (tid && containerset) {
fprintf(stderr, "Select either -t or -C, not both\n");
goto err;
}
if (tid) {
rc = send_cmd(nl_sd, id, mypid, TASKSTATS_CMD_GET,
cmd_type, &tid, sizeof(__u32));
PRINTF("Sent pid/tgid, retval %d\n", rc);
if (rc < 0) {
fprintf(stderr, "error sending tid/tgid cmd\n");
goto done;
}
}
if (containerset) {
cfd = open(containerpath, O_RDONLY);
if (cfd < 0) {
perror("error opening container file");
goto err;
}
rc = send_cmd(nl_sd, id, mypid, CGROUPSTATS_CMD_GET,
CGROUPSTATS_CMD_ATTR_FD, &cfd, sizeof(__u32));
if (rc < 0) {
perror("error sending cgroupstats command");
goto err;
}
}
if (!maskset && !tid && !containerset) {
usage();
goto err;
}
do {
int i;
rep_len = recv(nl_sd, &msg, sizeof(msg), 0);
PRINTF("received %d bytes\n", rep_len);
if (rep_len < 0) {
fprintf(stderr, "nonfatal reply error: errno %d\n",
errno);
continue;
}
if (msg.n.nlmsg_type == NLMSG_ERROR ||
!NLMSG_OK((&msg.n), rep_len)) {
struct nlmsgerr *err = NLMSG_DATA(&msg);
fprintf(stderr, "fatal reply error, errno %d\n",
err->error);
goto done;
}
PRINTF("nlmsghdr size=%zu, nlmsg_len=%d, rep_len=%d\n",
sizeof(struct nlmsghdr), msg.n.nlmsg_len, rep_len);
rep_len = GENLMSG_PAYLOAD(&msg.n);
na = (struct nlattr *) GENLMSG_DATA(&msg);
len = 0;
i = 0;
while (len < rep_len) {
len += NLA_ALIGN(na->nla_len);
switch (na->nla_type) {
case TASKSTATS_TYPE_AGGR_TGID:
/* Fall through */
case TASKSTATS_TYPE_AGGR_PID:
aggr_len = NLA_PAYLOAD(na->nla_len);
len2 = 0;
/* For nested attributes, na follows */
na = (struct nlattr *) NLA_DATA(na);
done = 0;
while (len2 < aggr_len) {
switch (na->nla_type) {
case TASKSTATS_TYPE_PID:
rtid = *(int *) NLA_DATA(na);
if (print_delays)
printf("PID\t%d\n", rtid);
break;
case TASKSTATS_TYPE_TGID:
rtid = *(int *) NLA_DATA(na);
if (print_delays)
printf("TGID\t%d\n", rtid);
break;
case TASKSTATS_TYPE_STATS:
count++;
if (print_delays)
print_delayacct((struct taskstats *) NLA_DATA(na));
if (print_io_accounting)
print_ioacct((struct taskstats *) NLA_DATA(na));
if (print_task_context_switch_counts)
task_context_switch_counts((struct taskstats *) NLA_DATA(na));
if (fd) {
if (write(fd, NLA_DATA(na), na->nla_len) < 0) {
err(1,"write error\n");
}
}
if (!loop)
goto done;
break;
default:
fprintf(stderr, "Unknown nested"
" nla_type %d\n",
na->nla_type);
break;
}
len2 += NLA_ALIGN(na->nla_len);
na = (struct nlattr *) ((char *) na + len2);
}
break;
case CGROUPSTATS_TYPE_CGROUP_STATS:
print_cgroupstats(NLA_DATA(na));
break;
default:
fprintf(stderr, "Unknown nla_type %d\n",
na->nla_type);
break;
}
na = (struct nlattr *) (GENLMSG_DATA(&msg) + len);
}
} while (loop);
done:
if (maskset) {
rc = send_cmd(nl_sd, id, mypid, TASKSTATS_CMD_GET,
TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK,
&cpumask, strlen(cpumask) + 1);
printf("Sent deregister mask, retval %d\n", rc);
if (rc < 0)
err(rc, "error sending deregister cpumask\n");
}
err:
close(nl_sd);
if (fd)
close(fd);
if (cfd)
close(cfd);
return 0;
}
| gpl-2.0 |
Jazz-823/kernel_ayame | drivers/input/touchscreen/mk712.c | 1739 | 5792 | /*
* ICS MK712 touchscreen controller driver
*
* Copyright (c) 1999-2002 Transmeta Corporation
* Copyright (c) 2005 Rick Koch <n1gp@hotmail.com>
* Copyright (c) 2005 Vojtech Pavlik <vojtech@suse.cz>
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
/*
* This driver supports the ICS MicroClock MK712 TouchScreen controller,
* found in Gateway AOL Connected Touchpad computers.
*
* Documentation for ICS MK712 can be found at:
* http://www.icst.com/pdf/mk712.pdf
*/
/*
* 1999-12-18: original version, Daniel Quinlan
* 1999-12-19: added anti-jitter code, report pen-up events, fixed mk712_poll
* to use queue_empty, Nathan Laredo
* 1999-12-20: improved random point rejection, Nathan Laredo
* 2000-01-05: checked in new anti-jitter code, changed mouse protocol, fixed
* queue code, added module options, other fixes, Daniel Quinlan
* 2002-03-15: Clean up for kernel merge <alan@redhat.com>
* Fixed multi open race, fixed memory checks, fixed resource
* allocation, fixed close/powerdown bug, switched to new init
* 2005-01-18: Ported to 2.6 from 2.4.28, Rick Koch
* 2005-02-05: Rewritten for the input layer, Vojtech Pavlik
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <asm/io.h>
MODULE_AUTHOR("Daniel Quinlan <quinlan@pathname.com>, Vojtech Pavlik <vojtech@suse.cz>");
MODULE_DESCRIPTION("ICS MicroClock MK712 TouchScreen driver");
MODULE_LICENSE("GPL");
static unsigned int mk712_io = 0x260; /* Also 0x200, 0x208, 0x300 */
module_param_named(io, mk712_io, uint, 0);
MODULE_PARM_DESC(io, "I/O base address of MK712 touchscreen controller");
static unsigned int mk712_irq = 10; /* Also 12, 14, 15 */
module_param_named(irq, mk712_irq, uint, 0);
MODULE_PARM_DESC(irq, "IRQ of MK712 touchscreen controller");
/* eight 8-bit registers */
#define MK712_STATUS 0
#define MK712_X 2
#define MK712_Y 4
#define MK712_CONTROL 6
#define MK712_RATE 7
/* status */
#define MK712_STATUS_TOUCH 0x10
#define MK712_CONVERSION_COMPLETE 0x80
/* control */
#define MK712_ENABLE_INT 0x01
#define MK712_INT_ON_CONVERSION_COMPLETE 0x02
#define MK712_INT_ON_CHANGE_IN_TOUCH_STATUS 0x04
#define MK712_ENABLE_PERIODIC_CONVERSIONS 0x10
#define MK712_READ_ONE_POINT 0x20
#define MK712_POWERUP 0x40
static struct input_dev *mk712_dev;
static DEFINE_SPINLOCK(mk712_lock);
static irqreturn_t mk712_interrupt(int irq, void *dev_id)
{
unsigned char status;
static int debounce = 1;
static unsigned short last_x;
static unsigned short last_y;
spin_lock(&mk712_lock);
status = inb(mk712_io + MK712_STATUS);
if (~status & MK712_CONVERSION_COMPLETE) {
debounce = 1;
goto end;
}
if (~status & MK712_STATUS_TOUCH) {
debounce = 1;
input_report_key(mk712_dev, BTN_TOUCH, 0);
goto end;
}
if (debounce) {
debounce = 0;
goto end;
}
input_report_key(mk712_dev, BTN_TOUCH, 1);
input_report_abs(mk712_dev, ABS_X, last_x);
input_report_abs(mk712_dev, ABS_Y, last_y);
end:
last_x = inw(mk712_io + MK712_X) & 0x0fff;
last_y = inw(mk712_io + MK712_Y) & 0x0fff;
input_sync(mk712_dev);
spin_unlock(&mk712_lock);
return IRQ_HANDLED;
}
static int mk712_open(struct input_dev *dev)
{
unsigned long flags;
spin_lock_irqsave(&mk712_lock, flags);
outb(0, mk712_io + MK712_CONTROL); /* Reset */
outb(MK712_ENABLE_INT | MK712_INT_ON_CONVERSION_COMPLETE |
MK712_INT_ON_CHANGE_IN_TOUCH_STATUS |
MK712_ENABLE_PERIODIC_CONVERSIONS |
MK712_POWERUP, mk712_io + MK712_CONTROL);
outb(10, mk712_io + MK712_RATE); /* 187 points per second */
spin_unlock_irqrestore(&mk712_lock, flags);
return 0;
}
static void mk712_close(struct input_dev *dev)
{
unsigned long flags;
spin_lock_irqsave(&mk712_lock, flags);
outb(0, mk712_io + MK712_CONTROL);
spin_unlock_irqrestore(&mk712_lock, flags);
}
static int __init mk712_init(void)
{
int err;
if (!request_region(mk712_io, 8, "mk712")) {
printk(KERN_WARNING "mk712: unable to get IO region\n");
return -ENODEV;
}
outb(0, mk712_io + MK712_CONTROL);
if ((inw(mk712_io + MK712_X) & 0xf000) || /* Sanity check */
(inw(mk712_io + MK712_Y) & 0xf000) ||
(inw(mk712_io + MK712_STATUS) & 0xf333)) {
printk(KERN_WARNING "mk712: device not present\n");
err = -ENODEV;
goto fail1;
}
mk712_dev = input_allocate_device();
if (!mk712_dev) {
printk(KERN_ERR "mk712: not enough memory\n");
err = -ENOMEM;
goto fail1;
}
mk712_dev->name = "ICS MicroClock MK712 TouchScreen";
mk712_dev->phys = "isa0260/input0";
mk712_dev->id.bustype = BUS_ISA;
mk712_dev->id.vendor = 0x0005;
mk712_dev->id.product = 0x0001;
mk712_dev->id.version = 0x0100;
mk712_dev->open = mk712_open;
mk712_dev->close = mk712_close;
mk712_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
mk712_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
input_set_abs_params(mk712_dev, ABS_X, 0, 0xfff, 88, 0);
input_set_abs_params(mk712_dev, ABS_Y, 0, 0xfff, 88, 0);
if (request_irq(mk712_irq, mk712_interrupt, 0, "mk712", mk712_dev)) {
printk(KERN_WARNING "mk712: unable to get IRQ\n");
err = -EBUSY;
goto fail1;
}
err = input_register_device(mk712_dev);
if (err)
goto fail2;
return 0;
fail2: free_irq(mk712_irq, mk712_dev);
fail1: input_free_device(mk712_dev);
release_region(mk712_io, 8);
return err;
}
static void __exit mk712_exit(void)
{
input_unregister_device(mk712_dev);
free_irq(mk712_irq, mk712_dev);
release_region(mk712_io, 8);
}
module_init(mk712_init);
module_exit(mk712_exit);
| gpl-2.0 |
leexdon/linux | drivers/w1/masters/ds1wm.c | 1739 | 15671 | /*
* 1-wire busmaster driver for DS1WM and ASICs with embedded DS1WMs
* such as HP iPAQs (including h5xxx, h2200, and devices with ASIC3
* like hx4700).
*
* Copyright (c) 2004-2005, Szabolcs Gyurko <szabolcs.gyurko@tlt.hu>
* Copyright (c) 2004-2007, Matt Reimer <mreimer@vpop.net>
*
* Use consistent with the GNU GPL is permitted,
* provided that this copyright notice is
* preserved in its entirety in all copies and derived works.
*/
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/pm.h>
#include <linux/platform_device.h>
#include <linux/err.h>
#include <linux/delay.h>
#include <linux/mfd/core.h>
#include <linux/mfd/ds1wm.h>
#include <linux/slab.h>
#include <asm/io.h>
#include "../w1.h"
#include "../w1_int.h"
#define DS1WM_CMD 0x00 /* R/W 4 bits command */
#define DS1WM_DATA 0x01 /* R/W 8 bits, transmit/receive buffer */
#define DS1WM_INT 0x02 /* R/W interrupt status */
#define DS1WM_INT_EN 0x03 /* R/W interrupt enable */
#define DS1WM_CLKDIV 0x04 /* R/W 5 bits of divisor and pre-scale */
#define DS1WM_CNTRL 0x05 /* R/W master control register (not used yet) */
#define DS1WM_CMD_1W_RESET (1 << 0) /* force reset on 1-wire bus */
#define DS1WM_CMD_SRA (1 << 1) /* enable Search ROM accelerator mode */
#define DS1WM_CMD_DQ_OUTPUT (1 << 2) /* write only - forces bus low */
#define DS1WM_CMD_DQ_INPUT (1 << 3) /* read only - reflects state of bus */
#define DS1WM_CMD_RST (1 << 5) /* software reset */
#define DS1WM_CMD_OD (1 << 7) /* overdrive */
#define DS1WM_INT_PD (1 << 0) /* presence detect */
#define DS1WM_INT_PDR (1 << 1) /* presence detect result */
#define DS1WM_INT_TBE (1 << 2) /* tx buffer empty */
#define DS1WM_INT_TSRE (1 << 3) /* tx shift register empty */
#define DS1WM_INT_RBF (1 << 4) /* rx buffer full */
#define DS1WM_INT_RSRF (1 << 5) /* rx shift register full */
#define DS1WM_INTEN_EPD (1 << 0) /* enable presence detect int */
#define DS1WM_INTEN_IAS (1 << 1) /* INTR active state */
#define DS1WM_INTEN_ETBE (1 << 2) /* enable tx buffer empty int */
#define DS1WM_INTEN_ETMT (1 << 3) /* enable tx shift register empty int */
#define DS1WM_INTEN_ERBF (1 << 4) /* enable rx buffer full int */
#define DS1WM_INTEN_ERSRF (1 << 5) /* enable rx shift register full int */
#define DS1WM_INTEN_DQO (1 << 6) /* enable direct bus driving ops */
#define DS1WM_INTEN_NOT_IAS (~DS1WM_INTEN_IAS) /* all but INTR active state */
#define DS1WM_TIMEOUT (HZ * 5)
static struct {
unsigned long freq;
unsigned long divisor;
} freq[] = {
{ 1000000, 0x80 },
{ 2000000, 0x84 },
{ 3000000, 0x81 },
{ 4000000, 0x88 },
{ 5000000, 0x82 },
{ 6000000, 0x85 },
{ 7000000, 0x83 },
{ 8000000, 0x8c },
{ 10000000, 0x86 },
{ 12000000, 0x89 },
{ 14000000, 0x87 },
{ 16000000, 0x90 },
{ 20000000, 0x8a },
{ 24000000, 0x8d },
{ 28000000, 0x8b },
{ 32000000, 0x94 },
{ 40000000, 0x8e },
{ 48000000, 0x91 },
{ 56000000, 0x8f },
{ 64000000, 0x98 },
{ 80000000, 0x92 },
{ 96000000, 0x95 },
{ 112000000, 0x93 },
{ 128000000, 0x9c },
/* you can continue this table, consult the OPERATION - CLOCK DIVISOR
section of the ds1wm spec sheet. */
};
struct ds1wm_data {
void __iomem *map;
int bus_shift; /* # of shifts to calc register offsets */
struct platform_device *pdev;
const struct mfd_cell *cell;
int irq;
int slave_present;
void *reset_complete;
void *read_complete;
void *write_complete;
int read_error;
/* last byte received */
u8 read_byte;
/* byte to write that makes all intr disabled, */
/* considering active_state (IAS) (optimization) */
u8 int_en_reg_none;
unsigned int reset_recover_delay; /* see ds1wm.h */
};
static inline void ds1wm_write_register(struct ds1wm_data *ds1wm_data, u32 reg,
u8 val)
{
__raw_writeb(val, ds1wm_data->map + (reg << ds1wm_data->bus_shift));
}
static inline u8 ds1wm_read_register(struct ds1wm_data *ds1wm_data, u32 reg)
{
return __raw_readb(ds1wm_data->map + (reg << ds1wm_data->bus_shift));
}
static irqreturn_t ds1wm_isr(int isr, void *data)
{
struct ds1wm_data *ds1wm_data = data;
u8 intr;
u8 inten = ds1wm_read_register(ds1wm_data, DS1WM_INT_EN);
/* if no bits are set in int enable register (except the IAS)
than go no further, reading the regs below has side effects */
if (!(inten & DS1WM_INTEN_NOT_IAS))
return IRQ_NONE;
ds1wm_write_register(ds1wm_data,
DS1WM_INT_EN, ds1wm_data->int_en_reg_none);
/* this read action clears the INTR and certain flags in ds1wm */
intr = ds1wm_read_register(ds1wm_data, DS1WM_INT);
ds1wm_data->slave_present = (intr & DS1WM_INT_PDR) ? 0 : 1;
if ((intr & DS1WM_INT_TSRE) && ds1wm_data->write_complete) {
inten &= ~DS1WM_INTEN_ETMT;
complete(ds1wm_data->write_complete);
}
if (intr & DS1WM_INT_RBF) {
/* this read clears the RBF flag */
ds1wm_data->read_byte = ds1wm_read_register(ds1wm_data,
DS1WM_DATA);
inten &= ~DS1WM_INTEN_ERBF;
if (ds1wm_data->read_complete)
complete(ds1wm_data->read_complete);
}
if ((intr & DS1WM_INT_PD) && ds1wm_data->reset_complete) {
inten &= ~DS1WM_INTEN_EPD;
complete(ds1wm_data->reset_complete);
}
ds1wm_write_register(ds1wm_data, DS1WM_INT_EN, inten);
return IRQ_HANDLED;
}
static int ds1wm_reset(struct ds1wm_data *ds1wm_data)
{
unsigned long timeleft;
DECLARE_COMPLETION_ONSTACK(reset_done);
ds1wm_data->reset_complete = &reset_done;
/* enable Presence detect only */
ds1wm_write_register(ds1wm_data, DS1WM_INT_EN, DS1WM_INTEN_EPD |
ds1wm_data->int_en_reg_none);
ds1wm_write_register(ds1wm_data, DS1WM_CMD, DS1WM_CMD_1W_RESET);
timeleft = wait_for_completion_timeout(&reset_done, DS1WM_TIMEOUT);
ds1wm_data->reset_complete = NULL;
if (!timeleft) {
dev_err(&ds1wm_data->pdev->dev, "reset failed, timed out\n");
return 1;
}
if (!ds1wm_data->slave_present) {
dev_dbg(&ds1wm_data->pdev->dev, "reset: no devices found\n");
return 1;
}
if (ds1wm_data->reset_recover_delay)
msleep(ds1wm_data->reset_recover_delay);
return 0;
}
static int ds1wm_write(struct ds1wm_data *ds1wm_data, u8 data)
{
unsigned long timeleft;
DECLARE_COMPLETION_ONSTACK(write_done);
ds1wm_data->write_complete = &write_done;
ds1wm_write_register(ds1wm_data, DS1WM_INT_EN,
ds1wm_data->int_en_reg_none | DS1WM_INTEN_ETMT);
ds1wm_write_register(ds1wm_data, DS1WM_DATA, data);
timeleft = wait_for_completion_timeout(&write_done, DS1WM_TIMEOUT);
ds1wm_data->write_complete = NULL;
if (!timeleft) {
dev_err(&ds1wm_data->pdev->dev, "write failed, timed out\n");
return -ETIMEDOUT;
}
return 0;
}
static u8 ds1wm_read(struct ds1wm_data *ds1wm_data, unsigned char write_data)
{
unsigned long timeleft;
u8 intEnable = DS1WM_INTEN_ERBF | ds1wm_data->int_en_reg_none;
DECLARE_COMPLETION_ONSTACK(read_done);
ds1wm_read_register(ds1wm_data, DS1WM_DATA);
ds1wm_data->read_complete = &read_done;
ds1wm_write_register(ds1wm_data, DS1WM_INT_EN, intEnable);
ds1wm_write_register(ds1wm_data, DS1WM_DATA, write_data);
timeleft = wait_for_completion_timeout(&read_done, DS1WM_TIMEOUT);
ds1wm_data->read_complete = NULL;
if (!timeleft) {
dev_err(&ds1wm_data->pdev->dev, "read failed, timed out\n");
ds1wm_data->read_error = -ETIMEDOUT;
return 0xFF;
}
ds1wm_data->read_error = 0;
return ds1wm_data->read_byte;
}
static int ds1wm_find_divisor(int gclk)
{
int i;
for (i = ARRAY_SIZE(freq)-1; i >= 0; --i)
if (gclk >= freq[i].freq)
return freq[i].divisor;
return 0;
}
static void ds1wm_up(struct ds1wm_data *ds1wm_data)
{
int divisor;
struct device *dev = &ds1wm_data->pdev->dev;
struct ds1wm_driver_data *plat = dev_get_platdata(dev);
if (ds1wm_data->cell->enable)
ds1wm_data->cell->enable(ds1wm_data->pdev);
divisor = ds1wm_find_divisor(plat->clock_rate);
dev_dbg(dev, "found divisor 0x%x for clock %d\n",
divisor, plat->clock_rate);
if (divisor == 0) {
dev_err(dev, "no suitable divisor for %dHz clock\n",
plat->clock_rate);
return;
}
ds1wm_write_register(ds1wm_data, DS1WM_CLKDIV, divisor);
/* Let the w1 clock stabilize. */
msleep(1);
ds1wm_reset(ds1wm_data);
}
static void ds1wm_down(struct ds1wm_data *ds1wm_data)
{
ds1wm_reset(ds1wm_data);
/* Disable interrupts. */
ds1wm_write_register(ds1wm_data, DS1WM_INT_EN,
ds1wm_data->int_en_reg_none);
if (ds1wm_data->cell->disable)
ds1wm_data->cell->disable(ds1wm_data->pdev);
}
/* --------------------------------------------------------------------- */
/* w1 methods */
static u8 ds1wm_read_byte(void *data)
{
struct ds1wm_data *ds1wm_data = data;
return ds1wm_read(ds1wm_data, 0xff);
}
static void ds1wm_write_byte(void *data, u8 byte)
{
struct ds1wm_data *ds1wm_data = data;
ds1wm_write(ds1wm_data, byte);
}
static u8 ds1wm_reset_bus(void *data)
{
struct ds1wm_data *ds1wm_data = data;
ds1wm_reset(ds1wm_data);
return 0;
}
static void ds1wm_search(void *data, struct w1_master *master_dev,
u8 search_type, w1_slave_found_callback slave_found)
{
struct ds1wm_data *ds1wm_data = data;
int i;
int ms_discrep_bit = -1;
u64 r = 0; /* holds the progress of the search */
u64 r_prime, d;
unsigned slaves_found = 0;
unsigned int pass = 0;
dev_dbg(&ds1wm_data->pdev->dev, "search begin\n");
while (true) {
++pass;
if (pass > 100) {
dev_dbg(&ds1wm_data->pdev->dev,
"too many attempts (100), search aborted\n");
return;
}
mutex_lock(&master_dev->bus_mutex);
if (ds1wm_reset(ds1wm_data)) {
mutex_unlock(&master_dev->bus_mutex);
dev_dbg(&ds1wm_data->pdev->dev,
"pass: %d reset error (or no slaves)\n", pass);
break;
}
dev_dbg(&ds1wm_data->pdev->dev,
"pass: %d r : %0#18llx writing SEARCH_ROM\n", pass, r);
ds1wm_write(ds1wm_data, search_type);
dev_dbg(&ds1wm_data->pdev->dev,
"pass: %d entering ASM\n", pass);
ds1wm_write_register(ds1wm_data, DS1WM_CMD, DS1WM_CMD_SRA);
dev_dbg(&ds1wm_data->pdev->dev,
"pass: %d beginning nibble loop\n", pass);
r_prime = 0;
d = 0;
/* we work one nibble at a time */
/* each nibble is interleaved to form a byte */
for (i = 0; i < 16; i++) {
unsigned char resp, _r, _r_prime, _d;
_r = (r >> (4*i)) & 0xf;
_r = ((_r & 0x1) << 1) |
((_r & 0x2) << 2) |
((_r & 0x4) << 3) |
((_r & 0x8) << 4);
/* writes _r, then reads back: */
resp = ds1wm_read(ds1wm_data, _r);
if (ds1wm_data->read_error) {
dev_err(&ds1wm_data->pdev->dev,
"pass: %d nibble: %d read error\n", pass, i);
break;
}
_r_prime = ((resp & 0x02) >> 1) |
((resp & 0x08) >> 2) |
((resp & 0x20) >> 3) |
((resp & 0x80) >> 4);
_d = ((resp & 0x01) >> 0) |
((resp & 0x04) >> 1) |
((resp & 0x10) >> 2) |
((resp & 0x40) >> 3);
r_prime |= (unsigned long long) _r_prime << (i * 4);
d |= (unsigned long long) _d << (i * 4);
}
if (ds1wm_data->read_error) {
mutex_unlock(&master_dev->bus_mutex);
dev_err(&ds1wm_data->pdev->dev,
"pass: %d read error, retrying\n", pass);
break;
}
dev_dbg(&ds1wm_data->pdev->dev,
"pass: %d r\': %0#18llx d:%0#18llx\n",
pass, r_prime, d);
dev_dbg(&ds1wm_data->pdev->dev,
"pass: %d nibble loop complete, exiting ASM\n", pass);
ds1wm_write_register(ds1wm_data, DS1WM_CMD, ~DS1WM_CMD_SRA);
dev_dbg(&ds1wm_data->pdev->dev,
"pass: %d resetting bus\n", pass);
ds1wm_reset(ds1wm_data);
mutex_unlock(&master_dev->bus_mutex);
if ((r_prime & ((u64)1 << 63)) && (d & ((u64)1 << 63))) {
dev_err(&ds1wm_data->pdev->dev,
"pass: %d bus error, retrying\n", pass);
continue; /* start over */
}
dev_dbg(&ds1wm_data->pdev->dev,
"pass: %d found %0#18llx\n", pass, r_prime);
slave_found(master_dev, r_prime);
++slaves_found;
dev_dbg(&ds1wm_data->pdev->dev,
"pass: %d complete, preparing next pass\n", pass);
/* any discrepency found which we already choose the
'1' branch is now is now irrelevant we reveal the
next branch with this: */
d &= ~r;
/* find last bit set, i.e. the most signif. bit set */
ms_discrep_bit = fls64(d) - 1;
dev_dbg(&ds1wm_data->pdev->dev,
"pass: %d new d:%0#18llx MS discrep bit:%d\n",
pass, d, ms_discrep_bit);
/* prev_ms_discrep_bit = ms_discrep_bit;
prepare for next ROM search: */
if (ms_discrep_bit == -1)
break;
r = (r & ~(~0ull << (ms_discrep_bit))) | 1 << ms_discrep_bit;
} /* end while true */
dev_dbg(&ds1wm_data->pdev->dev,
"pass: %d total: %d search done ms d bit pos: %d\n", pass,
slaves_found, ms_discrep_bit);
}
/* --------------------------------------------------------------------- */
static struct w1_bus_master ds1wm_master = {
.read_byte = ds1wm_read_byte,
.write_byte = ds1wm_write_byte,
.reset_bus = ds1wm_reset_bus,
.search = ds1wm_search,
};
static int ds1wm_probe(struct platform_device *pdev)
{
struct ds1wm_data *ds1wm_data;
struct ds1wm_driver_data *plat;
struct resource *res;
int ret;
if (!pdev)
return -ENODEV;
ds1wm_data = devm_kzalloc(&pdev->dev, sizeof(*ds1wm_data), GFP_KERNEL);
if (!ds1wm_data)
return -ENOMEM;
platform_set_drvdata(pdev, ds1wm_data);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENXIO;
ds1wm_data->map = devm_ioremap(&pdev->dev, res->start,
resource_size(res));
if (!ds1wm_data->map)
return -ENOMEM;
/* calculate bus shift from mem resource */
ds1wm_data->bus_shift = resource_size(res) >> 3;
ds1wm_data->pdev = pdev;
ds1wm_data->cell = mfd_get_cell(pdev);
if (!ds1wm_data->cell)
return -ENODEV;
plat = dev_get_platdata(&pdev->dev);
if (!plat)
return -ENODEV;
res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!res)
return -ENXIO;
ds1wm_data->irq = res->start;
ds1wm_data->int_en_reg_none = (plat->active_high ? DS1WM_INTEN_IAS : 0);
ds1wm_data->reset_recover_delay = plat->reset_recover_delay;
if (res->flags & IORESOURCE_IRQ_HIGHEDGE)
irq_set_irq_type(ds1wm_data->irq, IRQ_TYPE_EDGE_RISING);
if (res->flags & IORESOURCE_IRQ_LOWEDGE)
irq_set_irq_type(ds1wm_data->irq, IRQ_TYPE_EDGE_FALLING);
ret = devm_request_irq(&pdev->dev, ds1wm_data->irq, ds1wm_isr,
IRQF_SHARED, "ds1wm", ds1wm_data);
if (ret)
return ret;
ds1wm_up(ds1wm_data);
ds1wm_master.data = (void *)ds1wm_data;
ret = w1_add_master_device(&ds1wm_master);
if (ret)
goto err;
return 0;
err:
ds1wm_down(ds1wm_data);
return ret;
}
#ifdef CONFIG_PM
static int ds1wm_suspend(struct platform_device *pdev, pm_message_t state)
{
struct ds1wm_data *ds1wm_data = platform_get_drvdata(pdev);
ds1wm_down(ds1wm_data);
return 0;
}
static int ds1wm_resume(struct platform_device *pdev)
{
struct ds1wm_data *ds1wm_data = platform_get_drvdata(pdev);
ds1wm_up(ds1wm_data);
return 0;
}
#else
#define ds1wm_suspend NULL
#define ds1wm_resume NULL
#endif
static int ds1wm_remove(struct platform_device *pdev)
{
struct ds1wm_data *ds1wm_data = platform_get_drvdata(pdev);
w1_remove_master_device(&ds1wm_master);
ds1wm_down(ds1wm_data);
return 0;
}
static struct platform_driver ds1wm_driver = {
.driver = {
.name = "ds1wm",
},
.probe = ds1wm_probe,
.remove = ds1wm_remove,
.suspend = ds1wm_suspend,
.resume = ds1wm_resume
};
static int __init ds1wm_init(void)
{
pr_info("DS1WM w1 busmaster driver - (c) 2004 Szabolcs Gyurko\n");
return platform_driver_register(&ds1wm_driver);
}
static void __exit ds1wm_exit(void)
{
platform_driver_unregister(&ds1wm_driver);
}
module_init(ds1wm_init);
module_exit(ds1wm_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Szabolcs Gyurko <szabolcs.gyurko@tlt.hu>, "
"Matt Reimer <mreimer@vpop.net>,"
"Jean-Francois Dagenais <dagenaisj@sonatest.com>");
MODULE_DESCRIPTION("DS1WM w1 busmaster driver");
| gpl-2.0 |
thanhphat11/Kernel_N4_N910SLK | drivers/media/usb/gspca/pac7311.c | 2251 | 19961 | /*
* Pixart PAC7311 library
* Copyright (C) 2005 Thomas Kaiser thomas@kaiser-linux.li
*
* V4L2 by Jean-Francois Moine <http://moinejf.free.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Some documentation about various registers as determined by trial and error.
*
* Register page 1:
*
* Address Description
* 0x08 Unknown compressor related, must always be 8 except when not
* in 640x480 resolution and page 4 reg 2 <= 3 then set it to 9 !
* 0x1b Auto white balance related, bit 0 is AWB enable (inverted)
* bits 345 seem to toggle per color gains on/off (inverted)
* 0x78 Global control, bit 6 controls the LED (inverted)
* 0x80 Compression balance, interesting settings:
* 0x01 Use this to allow the camera to switch to higher compr.
* on the fly. Needed to stay within bandwidth @ 640x480@30
* 0x1c From usb captures under Windows for 640x480
* 0x2a Values >= this switch the camera to a lower compression,
* using the same table for both luminance and chrominance.
* This gives a sharper picture. Usable only at 640x480@ <
* 15 fps or 320x240 / 160x120. Note currently the driver
* does not use this as the quality gain is small and the
* generated JPG-s are only understood by v4l-utils >= 0.8.9
* 0x3f From usb captures under Windows for 320x240
* 0x69 From usb captures under Windows for 160x120
*
* Register page 4:
*
* Address Description
* 0x02 Clock divider 2-63, fps =~ 60 / val. Must be a multiple of 3 on
* the 7302, so one of 3, 6, 9, ..., except when between 6 and 12?
* 0x0f Master gain 1-245, low value = high gain
* 0x10 Another gain 0-15, limited influence (1-2x gain I guess)
* 0x21 Bitfield: 0-1 unused, 2-3 vflip/hflip, 4-5 unknown, 6-7 unused
* Note setting vflip disabled leads to a much lower image quality,
* so we always vflip, and tell userspace to flip it back
* 0x27 Seems to toggle various gains on / off, Setting bit 7 seems to
* completely disable the analog amplification block. Set to 0x68
* for max gain, 0x14 for minimal gain.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define MODULE_NAME "pac7311"
#include <linux/input.h>
#include "gspca.h"
/* Include pac common sof detection functions */
#include "pac_common.h"
#define PAC7311_GAIN_DEFAULT 122
#define PAC7311_EXPOSURE_DEFAULT 3 /* 20 fps, avoid using high compr. */
MODULE_AUTHOR("Thomas Kaiser thomas@kaiser-linux.li");
MODULE_DESCRIPTION("Pixart PAC7311");
MODULE_LICENSE("GPL");
struct sd {
struct gspca_dev gspca_dev; /* !! must be the first item */
struct v4l2_ctrl *contrast;
struct v4l2_ctrl *hflip;
u8 sof_read;
u8 autogain_ignore_frames;
atomic_t avg_lum;
};
static const struct v4l2_pix_format vga_mode[] = {
{160, 120, V4L2_PIX_FMT_PJPG, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 160 * 120 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 2},
{320, 240, V4L2_PIX_FMT_PJPG, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 1},
{640, 480, V4L2_PIX_FMT_PJPG, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 0},
};
#define LOAD_PAGE4 254
#define END_OF_SEQUENCE 0
static const __u8 init_7311[] = {
0xff, 0x01,
0x78, 0x40, /* Bit_0=start stream, Bit_6=LED */
0x78, 0x40, /* Bit_0=start stream, Bit_6=LED */
0x78, 0x44, /* Bit_0=start stream, Bit_6=LED */
0xff, 0x04,
0x27, 0x80,
0x28, 0xca,
0x29, 0x53,
0x2a, 0x0e,
0xff, 0x01,
0x3e, 0x20,
};
static const __u8 start_7311[] = {
/* index, len, [value]* */
0xff, 1, 0x01, /* page 1 */
0x02, 43, 0x48, 0x0a, 0x40, 0x08, 0x00, 0x00, 0x08, 0x00,
0x06, 0xff, 0x11, 0xff, 0x5a, 0x30, 0x90, 0x4c,
0x00, 0x07, 0x00, 0x0a, 0x10, 0x00, 0xa0, 0x10,
0x02, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00,
0x3e, 42, 0x00, 0x00, 0x78, 0x52, 0x4a, 0x52, 0x78, 0x6e,
0x48, 0x46, 0x48, 0x6e, 0x5f, 0x49, 0x42, 0x49,
0x5f, 0x5f, 0x49, 0x42, 0x49, 0x5f, 0x6e, 0x48,
0x46, 0x48, 0x6e, 0x78, 0x52, 0x4a, 0x52, 0x78,
0x00, 0x00, 0x09, 0x1b, 0x34, 0x49, 0x5c, 0x9b,
0xd0, 0xff,
0x78, 6, 0x44, 0x00, 0xf2, 0x01, 0x01, 0x80,
0x7f, 18, 0x2a, 0x1c, 0x00, 0xc8, 0x02, 0x58, 0x03, 0x84,
0x12, 0x00, 0x1a, 0x04, 0x08, 0x0c, 0x10, 0x14,
0x18, 0x20,
0x96, 3, 0x01, 0x08, 0x04,
0xa0, 4, 0x44, 0x44, 0x44, 0x04,
0xf0, 13, 0x01, 0x00, 0x00, 0x00, 0x22, 0x00, 0x20, 0x00,
0x3f, 0x00, 0x0a, 0x01, 0x00,
0xff, 1, 0x04, /* page 4 */
0, LOAD_PAGE4, /* load the page 4 */
0x11, 1, 0x01,
0, END_OF_SEQUENCE /* end of sequence */
};
#define SKIP 0xaa
/* page 4 - the value SKIP says skip the index - see reg_w_page() */
static const __u8 page4_7311[] = {
SKIP, SKIP, 0x04, 0x54, 0x07, 0x2b, 0x09, 0x0f,
0x09, 0x00, SKIP, SKIP, 0x07, 0x00, 0x00, 0x62,
0x08, SKIP, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x03, 0xa0, 0x01, 0xf4, SKIP,
SKIP, 0x00, 0x08, SKIP, 0x03, SKIP, 0x00, 0x68,
0xca, 0x10, 0x06, 0x78, 0x00, 0x00, 0x00, 0x00,
0x23, 0x28, 0x04, 0x11, 0x00, 0x00
};
static void reg_w_buf(struct gspca_dev *gspca_dev,
__u8 index,
const u8 *buffer, int len)
{
int ret;
if (gspca_dev->usb_err < 0)
return;
memcpy(gspca_dev->usb_buf, buffer, len);
ret = usb_control_msg(gspca_dev->dev,
usb_sndctrlpipe(gspca_dev->dev, 0),
0, /* request */
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, /* value */
index, gspca_dev->usb_buf, len,
500);
if (ret < 0) {
pr_err("reg_w_buf() failed index 0x%02x, error %d\n",
index, ret);
gspca_dev->usb_err = ret;
}
}
static void reg_w(struct gspca_dev *gspca_dev,
__u8 index,
__u8 value)
{
int ret;
if (gspca_dev->usb_err < 0)
return;
gspca_dev->usb_buf[0] = value;
ret = usb_control_msg(gspca_dev->dev,
usb_sndctrlpipe(gspca_dev->dev, 0),
0, /* request */
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, index, gspca_dev->usb_buf, 1,
500);
if (ret < 0) {
pr_err("reg_w() failed index 0x%02x, value 0x%02x, error %d\n",
index, value, ret);
gspca_dev->usb_err = ret;
}
}
static void reg_w_seq(struct gspca_dev *gspca_dev,
const __u8 *seq, int len)
{
while (--len >= 0) {
reg_w(gspca_dev, seq[0], seq[1]);
seq += 2;
}
}
/* load the beginning of a page */
static void reg_w_page(struct gspca_dev *gspca_dev,
const __u8 *page, int len)
{
int index;
int ret = 0;
if (gspca_dev->usb_err < 0)
return;
for (index = 0; index < len; index++) {
if (page[index] == SKIP) /* skip this index */
continue;
gspca_dev->usb_buf[0] = page[index];
ret = usb_control_msg(gspca_dev->dev,
usb_sndctrlpipe(gspca_dev->dev, 0),
0, /* request */
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0, index, gspca_dev->usb_buf, 1,
500);
if (ret < 0) {
pr_err("reg_w_page() failed index 0x%02x, value 0x%02x, error %d\n",
index, page[index], ret);
gspca_dev->usb_err = ret;
break;
}
}
}
/* output a variable sequence */
static void reg_w_var(struct gspca_dev *gspca_dev,
const __u8 *seq,
const __u8 *page4, unsigned int page4_len)
{
int index, len;
for (;;) {
index = *seq++;
len = *seq++;
switch (len) {
case END_OF_SEQUENCE:
return;
case LOAD_PAGE4:
reg_w_page(gspca_dev, page4, page4_len);
break;
default:
if (len > USB_BUF_SZ) {
PERR("Incorrect variable sequence");
return;
}
while (len > 0) {
if (len < 8) {
reg_w_buf(gspca_dev,
index, seq, len);
seq += len;
break;
}
reg_w_buf(gspca_dev, index, seq, 8);
seq += 8;
index += 8;
len -= 8;
}
}
}
/* not reached */
}
/* this function is called at probe time for pac7311 */
static int sd_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id)
{
struct cam *cam = &gspca_dev->cam;
cam->cam_mode = vga_mode;
cam->nmodes = ARRAY_SIZE(vga_mode);
cam->input_flags = V4L2_IN_ST_VFLIP;
return 0;
}
static void setcontrast(struct gspca_dev *gspca_dev, s32 val)
{
reg_w(gspca_dev, 0xff, 0x04);
reg_w(gspca_dev, 0x10, val);
/* load registers to sensor (Bit 0, auto clear) */
reg_w(gspca_dev, 0x11, 0x01);
}
static void setgain(struct gspca_dev *gspca_dev, s32 val)
{
reg_w(gspca_dev, 0xff, 0x04); /* page 4 */
reg_w(gspca_dev, 0x0e, 0x00);
reg_w(gspca_dev, 0x0f, gspca_dev->gain->maximum - val + 1);
/* load registers to sensor (Bit 0, auto clear) */
reg_w(gspca_dev, 0x11, 0x01);
}
static void setexposure(struct gspca_dev *gspca_dev, s32 val)
{
reg_w(gspca_dev, 0xff, 0x04); /* page 4 */
reg_w(gspca_dev, 0x02, val);
/* load registers to sensor (Bit 0, auto clear) */
reg_w(gspca_dev, 0x11, 0x01);
/*
* Page 1 register 8 must always be 0x08 except when not in
* 640x480 mode and page 4 reg 2 <= 3 then it must be 9
*/
reg_w(gspca_dev, 0xff, 0x01);
if (gspca_dev->width != 640 && val <= 3)
reg_w(gspca_dev, 0x08, 0x09);
else
reg_w(gspca_dev, 0x08, 0x08);
/*
* Page1 register 80 sets the compression balance, normally we
* want / use 0x1c, but for 640x480@30fps we must allow the
* camera to use higher compression or we may run out of
* bandwidth.
*/
if (gspca_dev->width == 640 && val == 2)
reg_w(gspca_dev, 0x80, 0x01);
else
reg_w(gspca_dev, 0x80, 0x1c);
/* load registers to sensor (Bit 0, auto clear) */
reg_w(gspca_dev, 0x11, 0x01);
}
static void sethvflip(struct gspca_dev *gspca_dev, s32 hflip, s32 vflip)
{
__u8 data;
reg_w(gspca_dev, 0xff, 0x04); /* page 4 */
data = (hflip ? 0x04 : 0x00) |
(vflip ? 0x08 : 0x00);
reg_w(gspca_dev, 0x21, data);
/* load registers to sensor (Bit 0, auto clear) */
reg_w(gspca_dev, 0x11, 0x01);
}
/* this function is called at probe and resume time for pac7311 */
static int sd_init(struct gspca_dev *gspca_dev)
{
reg_w_seq(gspca_dev, init_7311, sizeof(init_7311)/2);
return gspca_dev->usb_err;
}
static int sd_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct gspca_dev *gspca_dev =
container_of(ctrl->handler, struct gspca_dev, ctrl_handler);
struct sd *sd = (struct sd *)gspca_dev;
gspca_dev->usb_err = 0;
if (ctrl->id == V4L2_CID_AUTOGAIN && ctrl->is_new && ctrl->val) {
/* when switching to autogain set defaults to make sure
we are on a valid point of the autogain gain /
exposure knee graph, and give this change time to
take effect before doing autogain. */
gspca_dev->exposure->val = PAC7311_EXPOSURE_DEFAULT;
gspca_dev->gain->val = PAC7311_GAIN_DEFAULT;
sd->autogain_ignore_frames = PAC_AUTOGAIN_IGNORE_FRAMES;
}
if (!gspca_dev->streaming)
return 0;
switch (ctrl->id) {
case V4L2_CID_CONTRAST:
setcontrast(gspca_dev, ctrl->val);
break;
case V4L2_CID_AUTOGAIN:
if (gspca_dev->exposure->is_new || (ctrl->is_new && ctrl->val))
setexposure(gspca_dev, gspca_dev->exposure->val);
if (gspca_dev->gain->is_new || (ctrl->is_new && ctrl->val))
setgain(gspca_dev, gspca_dev->gain->val);
break;
case V4L2_CID_HFLIP:
sethvflip(gspca_dev, sd->hflip->val, 1);
break;
default:
return -EINVAL;
}
return gspca_dev->usb_err;
}
static const struct v4l2_ctrl_ops sd_ctrl_ops = {
.s_ctrl = sd_s_ctrl,
};
/* this function is called at probe time */
static int sd_init_controls(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
struct v4l2_ctrl_handler *hdl = &gspca_dev->ctrl_handler;
gspca_dev->vdev.ctrl_handler = hdl;
v4l2_ctrl_handler_init(hdl, 5);
sd->contrast = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_CONTRAST, 0, 15, 1, 7);
gspca_dev->autogain = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_AUTOGAIN, 0, 1, 1, 1);
gspca_dev->exposure = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_EXPOSURE, 2, 63, 1,
PAC7311_EXPOSURE_DEFAULT);
gspca_dev->gain = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_GAIN, 0, 244, 1,
PAC7311_GAIN_DEFAULT);
sd->hflip = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_HFLIP, 0, 1, 1, 0);
if (hdl->error) {
pr_err("Could not initialize controls\n");
return hdl->error;
}
v4l2_ctrl_auto_cluster(3, &gspca_dev->autogain, 0, false);
return 0;
}
/* -- start the camera -- */
static int sd_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->sof_read = 0;
reg_w_var(gspca_dev, start_7311,
page4_7311, sizeof(page4_7311));
setcontrast(gspca_dev, v4l2_ctrl_g_ctrl(sd->contrast));
setgain(gspca_dev, v4l2_ctrl_g_ctrl(gspca_dev->gain));
setexposure(gspca_dev, v4l2_ctrl_g_ctrl(gspca_dev->exposure));
sethvflip(gspca_dev, v4l2_ctrl_g_ctrl(sd->hflip), 1);
/* set correct resolution */
switch (gspca_dev->cam.cam_mode[(int) gspca_dev->curr_mode].priv) {
case 2: /* 160x120 */
reg_w(gspca_dev, 0xff, 0x01);
reg_w(gspca_dev, 0x17, 0x20);
reg_w(gspca_dev, 0x87, 0x10);
break;
case 1: /* 320x240 */
reg_w(gspca_dev, 0xff, 0x01);
reg_w(gspca_dev, 0x17, 0x30);
reg_w(gspca_dev, 0x87, 0x11);
break;
case 0: /* 640x480 */
reg_w(gspca_dev, 0xff, 0x01);
reg_w(gspca_dev, 0x17, 0x00);
reg_w(gspca_dev, 0x87, 0x12);
break;
}
sd->sof_read = 0;
sd->autogain_ignore_frames = 0;
atomic_set(&sd->avg_lum, -1);
/* start stream */
reg_w(gspca_dev, 0xff, 0x01);
reg_w(gspca_dev, 0x78, 0x05);
return gspca_dev->usb_err;
}
static void sd_stopN(struct gspca_dev *gspca_dev)
{
reg_w(gspca_dev, 0xff, 0x04);
reg_w(gspca_dev, 0x27, 0x80);
reg_w(gspca_dev, 0x28, 0xca);
reg_w(gspca_dev, 0x29, 0x53);
reg_w(gspca_dev, 0x2a, 0x0e);
reg_w(gspca_dev, 0xff, 0x01);
reg_w(gspca_dev, 0x3e, 0x20);
reg_w(gspca_dev, 0x78, 0x44); /* Bit_0=start stream, Bit_6=LED */
reg_w(gspca_dev, 0x78, 0x44); /* Bit_0=start stream, Bit_6=LED */
reg_w(gspca_dev, 0x78, 0x44); /* Bit_0=start stream, Bit_6=LED */
}
static void do_autogain(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int avg_lum = atomic_read(&sd->avg_lum);
int desired_lum, deadzone;
if (avg_lum == -1)
return;
desired_lum = 170;
deadzone = 20;
if (sd->autogain_ignore_frames > 0)
sd->autogain_ignore_frames--;
else if (gspca_coarse_grained_expo_autogain(gspca_dev, avg_lum,
desired_lum, deadzone))
sd->autogain_ignore_frames = PAC_AUTOGAIN_IGNORE_FRAMES;
}
/* JPEG header, part 1 */
static const unsigned char pac_jpeg_header1[] = {
0xff, 0xd8, /* SOI: Start of Image */
0xff, 0xc0, /* SOF0: Start of Frame (Baseline DCT) */
0x00, 0x11, /* length = 17 bytes (including this length field) */
0x08 /* Precision: 8 */
/* 2 bytes is placed here: number of image lines */
/* 2 bytes is placed here: samples per line */
};
/* JPEG header, continued */
static const unsigned char pac_jpeg_header2[] = {
0x03, /* Number of image components: 3 */
0x01, 0x21, 0x00, /* ID=1, Subsampling 1x1, Quantization table: 0 */
0x02, 0x11, 0x01, /* ID=2, Subsampling 2x1, Quantization table: 1 */
0x03, 0x11, 0x01, /* ID=3, Subsampling 2x1, Quantization table: 1 */
0xff, 0xda, /* SOS: Start Of Scan */
0x00, 0x0c, /* length = 12 bytes (including this length field) */
0x03, /* number of components: 3 */
0x01, 0x00, /* selector 1, table 0x00 */
0x02, 0x11, /* selector 2, table 0x11 */
0x03, 0x11, /* selector 3, table 0x11 */
0x00, 0x3f, /* Spectral selection: 0 .. 63 */
0x00 /* Successive approximation: 0 */
};
static void pac_start_frame(struct gspca_dev *gspca_dev,
__u16 lines, __u16 samples_per_line)
{
unsigned char tmpbuf[4];
gspca_frame_add(gspca_dev, FIRST_PACKET,
pac_jpeg_header1, sizeof(pac_jpeg_header1));
tmpbuf[0] = lines >> 8;
tmpbuf[1] = lines & 0xff;
tmpbuf[2] = samples_per_line >> 8;
tmpbuf[3] = samples_per_line & 0xff;
gspca_frame_add(gspca_dev, INTER_PACKET,
tmpbuf, sizeof(tmpbuf));
gspca_frame_add(gspca_dev, INTER_PACKET,
pac_jpeg_header2, sizeof(pac_jpeg_header2));
}
/* this function is run at interrupt level */
static void sd_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, /* isoc packet */
int len) /* iso packet length */
{
struct sd *sd = (struct sd *) gspca_dev;
u8 *image;
unsigned char *sof;
sof = pac_find_sof(gspca_dev, &sd->sof_read, data, len);
if (sof) {
int n, lum_offset, footer_length;
/*
* 6 bytes after the FF D9 EOF marker a number of lumination
* bytes are send corresponding to different parts of the
* image, the 14th and 15th byte after the EOF seem to
* correspond to the center of the image.
*/
lum_offset = 24 + sizeof pac_sof_marker;
footer_length = 26;
/* Finish decoding current frame */
n = (sof - data) - (footer_length + sizeof pac_sof_marker);
if (n < 0) {
gspca_dev->image_len += n;
n = 0;
} else {
gspca_frame_add(gspca_dev, INTER_PACKET, data, n);
}
image = gspca_dev->image;
if (image != NULL
&& image[gspca_dev->image_len - 2] == 0xff
&& image[gspca_dev->image_len - 1] == 0xd9)
gspca_frame_add(gspca_dev, LAST_PACKET, NULL, 0);
n = sof - data;
len -= n;
data = sof;
/* Get average lumination */
if (gspca_dev->last_packet_type == LAST_PACKET &&
n >= lum_offset)
atomic_set(&sd->avg_lum, data[-lum_offset] +
data[-lum_offset + 1]);
else
atomic_set(&sd->avg_lum, -1);
/* Start the new frame with the jpeg header */
pac_start_frame(gspca_dev,
gspca_dev->height, gspca_dev->width);
}
gspca_frame_add(gspca_dev, INTER_PACKET, data, len);
}
#if IS_ENABLED(CONFIG_INPUT)
static int sd_int_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, /* interrupt packet data */
int len) /* interrupt packet length */
{
int ret = -EINVAL;
u8 data0, data1;
if (len == 2) {
data0 = data[0];
data1 = data[1];
if ((data0 == 0x00 && data1 == 0x11) ||
(data0 == 0x22 && data1 == 0x33) ||
(data0 == 0x44 && data1 == 0x55) ||
(data0 == 0x66 && data1 == 0x77) ||
(data0 == 0x88 && data1 == 0x99) ||
(data0 == 0xaa && data1 == 0xbb) ||
(data0 == 0xcc && data1 == 0xdd) ||
(data0 == 0xee && data1 == 0xff)) {
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 1);
input_sync(gspca_dev->input_dev);
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 0);
input_sync(gspca_dev->input_dev);
ret = 0;
}
}
return ret;
}
#endif
static const struct sd_desc sd_desc = {
.name = MODULE_NAME,
.config = sd_config,
.init = sd_init,
.init_controls = sd_init_controls,
.start = sd_start,
.stopN = sd_stopN,
.pkt_scan = sd_pkt_scan,
.dq_callback = do_autogain,
#if IS_ENABLED(CONFIG_INPUT)
.int_pkt_scan = sd_int_pkt_scan,
#endif
};
/* -- module initialisation -- */
static const struct usb_device_id device_table[] = {
{USB_DEVICE(0x093a, 0x2600)},
{USB_DEVICE(0x093a, 0x2601)},
{USB_DEVICE(0x093a, 0x2603)},
{USB_DEVICE(0x093a, 0x2608)},
{USB_DEVICE(0x093a, 0x260e)},
{USB_DEVICE(0x093a, 0x260f)},
{}
};
MODULE_DEVICE_TABLE(usb, device_table);
/* -- device connect -- */
static int sd_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
return gspca_dev_probe(intf, id, &sd_desc, sizeof(struct sd),
THIS_MODULE);
}
static struct usb_driver sd_driver = {
.name = MODULE_NAME,
.id_table = device_table,
.probe = sd_probe,
.disconnect = gspca_disconnect,
#ifdef CONFIG_PM
.suspend = gspca_suspend,
.resume = gspca_resume,
.reset_resume = gspca_resume,
#endif
};
module_usb_driver(sd_driver);
| gpl-2.0 |
honor6-dev/android_kernel_huawei_h60 | drivers/mfd/htc-i2cpld.c | 2251 | 18368 | /*
* htc-i2cpld.c
* Chip driver for an unknown CPLD chip found on omap850 HTC devices like
* the HTC Wizard and HTC Herald.
* The cpld is located on the i2c bus and acts as an input/output GPIO
* extender.
*
* Copyright (C) 2009 Cory Maccarrone <darkstar6262@gmail.com>
*
* Based on work done in the linwizard project
* Copyright (C) 2008-2009 Angelo Arrifano <miknix@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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/irq.h>
#include <linux/spinlock.h>
#include <linux/htcpld.h>
#include <linux/gpio.h>
#include <linux/slab.h>
struct htcpld_chip {
spinlock_t lock;
/* chip info */
u8 reset;
u8 addr;
struct device *dev;
struct i2c_client *client;
/* Output details */
u8 cache_out;
struct gpio_chip chip_out;
/* Input details */
u8 cache_in;
struct gpio_chip chip_in;
u16 irqs_enabled;
uint irq_start;
int nirqs;
unsigned int flow_type;
/*
* Work structure to allow for setting values outside of any
* possible interrupt context
*/
struct work_struct set_val_work;
};
struct htcpld_data {
/* irq info */
u16 irqs_enabled;
uint irq_start;
int nirqs;
uint chained_irq;
unsigned int int_reset_gpio_hi;
unsigned int int_reset_gpio_lo;
/* htcpld info */
struct htcpld_chip *chip;
unsigned int nchips;
};
/* There does not appear to be a way to proactively mask interrupts
* on the htcpld chip itself. So, we simply ignore interrupts that
* aren't desired. */
static void htcpld_mask(struct irq_data *data)
{
struct htcpld_chip *chip = irq_data_get_irq_chip_data(data);
chip->irqs_enabled &= ~(1 << (data->irq - chip->irq_start));
pr_debug("HTCPLD mask %d %04x\n", data->irq, chip->irqs_enabled);
}
static void htcpld_unmask(struct irq_data *data)
{
struct htcpld_chip *chip = irq_data_get_irq_chip_data(data);
chip->irqs_enabled |= 1 << (data->irq - chip->irq_start);
pr_debug("HTCPLD unmask %d %04x\n", data->irq, chip->irqs_enabled);
}
static int htcpld_set_type(struct irq_data *data, unsigned int flags)
{
struct htcpld_chip *chip = irq_data_get_irq_chip_data(data);
if (flags & ~IRQ_TYPE_SENSE_MASK)
return -EINVAL;
/* We only allow edge triggering */
if (flags & (IRQ_TYPE_LEVEL_LOW|IRQ_TYPE_LEVEL_HIGH))
return -EINVAL;
chip->flow_type = flags;
return 0;
}
static struct irq_chip htcpld_muxed_chip = {
.name = "htcpld",
.irq_mask = htcpld_mask,
.irq_unmask = htcpld_unmask,
.irq_set_type = htcpld_set_type,
};
/* To properly dispatch IRQ events, we need to read from the
* chip. This is an I2C action that could possibly sleep
* (which is bad in interrupt context) -- so we use a threaded
* interrupt handler to get around that.
*/
static irqreturn_t htcpld_handler(int irq, void *dev)
{
struct htcpld_data *htcpld = dev;
unsigned int i;
unsigned long flags;
int irqpin;
if (!htcpld) {
pr_debug("htcpld is null in ISR\n");
return IRQ_HANDLED;
}
/*
* For each chip, do a read of the chip and trigger any interrupts
* desired. The interrupts will be triggered from LSB to MSB (i.e.
* bit 0 first, then bit 1, etc.)
*
* For chips that have no interrupt range specified, just skip 'em.
*/
for (i = 0; i < htcpld->nchips; i++) {
struct htcpld_chip *chip = &htcpld->chip[i];
struct i2c_client *client;
int val;
unsigned long uval, old_val;
if (!chip) {
pr_debug("chip %d is null in ISR\n", i);
continue;
}
if (chip->nirqs == 0)
continue;
client = chip->client;
if (!client) {
pr_debug("client %d is null in ISR\n", i);
continue;
}
/* Scan the chip */
val = i2c_smbus_read_byte_data(client, chip->cache_out);
if (val < 0) {
/* Throw a warning and skip this chip */
dev_warn(chip->dev, "Unable to read from chip: %d\n",
val);
continue;
}
uval = (unsigned long)val;
spin_lock_irqsave(&chip->lock, flags);
/* Save away the old value so we can compare it */
old_val = chip->cache_in;
/* Write the new value */
chip->cache_in = uval;
spin_unlock_irqrestore(&chip->lock, flags);
/*
* For each bit in the data (starting at bit 0), trigger
* associated interrupts.
*/
for (irqpin = 0; irqpin < chip->nirqs; irqpin++) {
unsigned oldb, newb, type = chip->flow_type;
irq = chip->irq_start + irqpin;
/* Run the IRQ handler, but only if the bit value
* changed, and the proper flags are set */
oldb = (old_val >> irqpin) & 1;
newb = (uval >> irqpin) & 1;
if ((!oldb && newb && (type & IRQ_TYPE_EDGE_RISING)) ||
(oldb && !newb && (type & IRQ_TYPE_EDGE_FALLING))) {
pr_debug("fire IRQ %d\n", irqpin);
generic_handle_irq(irq);
}
}
}
/*
* In order to continue receiving interrupts, the int_reset_gpio must
* be asserted.
*/
if (htcpld->int_reset_gpio_hi)
gpio_set_value(htcpld->int_reset_gpio_hi, 1);
if (htcpld->int_reset_gpio_lo)
gpio_set_value(htcpld->int_reset_gpio_lo, 0);
return IRQ_HANDLED;
}
/*
* The GPIO set routines can be called from interrupt context, especially if,
* for example they're attached to the led-gpio framework and a trigger is
* enabled. As such, we declared work above in the htcpld_chip structure,
* and that work is scheduled in the set routine. The kernel can then run
* the I2C functions, which will sleep, in process context.
*/
static void htcpld_chip_set(struct gpio_chip *chip, unsigned offset, int val)
{
struct i2c_client *client;
struct htcpld_chip *chip_data;
unsigned long flags;
chip_data = container_of(chip, struct htcpld_chip, chip_out);
if (!chip_data)
return;
client = chip_data->client;
if (client == NULL)
return;
spin_lock_irqsave(&chip_data->lock, flags);
if (val)
chip_data->cache_out |= (1 << offset);
else
chip_data->cache_out &= ~(1 << offset);
spin_unlock_irqrestore(&chip_data->lock, flags);
schedule_work(&(chip_data->set_val_work));
}
static void htcpld_chip_set_ni(struct work_struct *work)
{
struct htcpld_chip *chip_data;
struct i2c_client *client;
chip_data = container_of(work, struct htcpld_chip, set_val_work);
client = chip_data->client;
i2c_smbus_read_byte_data(client, chip_data->cache_out);
}
static int htcpld_chip_get(struct gpio_chip *chip, unsigned offset)
{
struct htcpld_chip *chip_data;
int val = 0;
int is_input = 0;
/* Try out first */
chip_data = container_of(chip, struct htcpld_chip, chip_out);
if (!chip_data) {
/* Try in */
is_input = 1;
chip_data = container_of(chip, struct htcpld_chip, chip_in);
if (!chip_data)
return -EINVAL;
}
/* Determine if this is an input or output GPIO */
if (!is_input)
/* Use the output cache */
val = (chip_data->cache_out >> offset) & 1;
else
/* Use the input cache */
val = (chip_data->cache_in >> offset) & 1;
if (val)
return 1;
else
return 0;
}
static int htcpld_direction_output(struct gpio_chip *chip,
unsigned offset, int value)
{
htcpld_chip_set(chip, offset, value);
return 0;
}
static int htcpld_direction_input(struct gpio_chip *chip,
unsigned offset)
{
/*
* No-op: this function can only be called on the input chip.
* We do however make sure the offset is within range.
*/
return (offset < chip->ngpio) ? 0 : -EINVAL;
}
static int htcpld_chip_to_irq(struct gpio_chip *chip, unsigned offset)
{
struct htcpld_chip *chip_data;
chip_data = container_of(chip, struct htcpld_chip, chip_in);
if (offset < chip_data->nirqs)
return chip_data->irq_start + offset;
else
return -EINVAL;
}
static void htcpld_chip_reset(struct i2c_client *client)
{
struct htcpld_chip *chip_data = i2c_get_clientdata(client);
if (!chip_data)
return;
i2c_smbus_read_byte_data(
client, (chip_data->cache_out = chip_data->reset));
}
static int htcpld_setup_chip_irq(
struct platform_device *pdev,
int chip_index)
{
struct htcpld_data *htcpld;
struct device *dev = &pdev->dev;
struct htcpld_core_platform_data *pdata;
struct htcpld_chip *chip;
struct htcpld_chip_platform_data *plat_chip_data;
unsigned int irq, irq_end;
int ret = 0;
/* Get the platform and driver data */
pdata = dev->platform_data;
htcpld = platform_get_drvdata(pdev);
chip = &htcpld->chip[chip_index];
plat_chip_data = &pdata->chip[chip_index];
/* Setup irq handlers */
irq_end = chip->irq_start + chip->nirqs;
for (irq = chip->irq_start; irq < irq_end; irq++) {
irq_set_chip_and_handler(irq, &htcpld_muxed_chip,
handle_simple_irq);
irq_set_chip_data(irq, chip);
#ifdef CONFIG_ARM
set_irq_flags(irq, IRQF_VALID | IRQF_PROBE);
#else
irq_set_probe(irq);
#endif
}
return ret;
}
static int htcpld_register_chip_i2c(
struct platform_device *pdev,
int chip_index)
{
struct htcpld_data *htcpld;
struct device *dev = &pdev->dev;
struct htcpld_core_platform_data *pdata;
struct htcpld_chip *chip;
struct htcpld_chip_platform_data *plat_chip_data;
struct i2c_adapter *adapter;
struct i2c_client *client;
struct i2c_board_info info;
/* Get the platform and driver data */
pdata = dev->platform_data;
htcpld = platform_get_drvdata(pdev);
chip = &htcpld->chip[chip_index];
plat_chip_data = &pdata->chip[chip_index];
adapter = i2c_get_adapter(pdata->i2c_adapter_id);
if (adapter == NULL) {
/* Eek, no such I2C adapter! Bail out. */
dev_warn(dev, "Chip at i2c address 0x%x: Invalid i2c adapter %d\n",
plat_chip_data->addr, pdata->i2c_adapter_id);
return -ENODEV;
}
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_READ_BYTE_DATA)) {
dev_warn(dev, "i2c adapter %d non-functional\n",
pdata->i2c_adapter_id);
return -EINVAL;
}
memset(&info, 0, sizeof(struct i2c_board_info));
info.addr = plat_chip_data->addr;
strlcpy(info.type, "htcpld-chip", I2C_NAME_SIZE);
info.platform_data = chip;
/* Add the I2C device. This calls the probe() function. */
client = i2c_new_device(adapter, &info);
if (!client) {
/* I2C device registration failed, contineu with the next */
dev_warn(dev, "Unable to add I2C device for 0x%x\n",
plat_chip_data->addr);
return -ENODEV;
}
i2c_set_clientdata(client, chip);
snprintf(client->name, I2C_NAME_SIZE, "Chip_0x%d", client->addr);
chip->client = client;
/* Reset the chip */
htcpld_chip_reset(client);
chip->cache_in = i2c_smbus_read_byte_data(client, chip->cache_out);
return 0;
}
static void htcpld_unregister_chip_i2c(
struct platform_device *pdev,
int chip_index)
{
struct htcpld_data *htcpld;
struct htcpld_chip *chip;
/* Get the platform and driver data */
htcpld = platform_get_drvdata(pdev);
chip = &htcpld->chip[chip_index];
if (chip->client)
i2c_unregister_device(chip->client);
}
static int htcpld_register_chip_gpio(
struct platform_device *pdev,
int chip_index)
{
struct htcpld_data *htcpld;
struct device *dev = &pdev->dev;
struct htcpld_core_platform_data *pdata;
struct htcpld_chip *chip;
struct htcpld_chip_platform_data *plat_chip_data;
struct gpio_chip *gpio_chip;
int ret = 0;
/* Get the platform and driver data */
pdata = dev->platform_data;
htcpld = platform_get_drvdata(pdev);
chip = &htcpld->chip[chip_index];
plat_chip_data = &pdata->chip[chip_index];
/* Setup the GPIO chips */
gpio_chip = &(chip->chip_out);
gpio_chip->label = "htcpld-out";
gpio_chip->dev = dev;
gpio_chip->owner = THIS_MODULE;
gpio_chip->get = htcpld_chip_get;
gpio_chip->set = htcpld_chip_set;
gpio_chip->direction_input = NULL;
gpio_chip->direction_output = htcpld_direction_output;
gpio_chip->base = plat_chip_data->gpio_out_base;
gpio_chip->ngpio = plat_chip_data->num_gpios;
gpio_chip = &(chip->chip_in);
gpio_chip->label = "htcpld-in";
gpio_chip->dev = dev;
gpio_chip->owner = THIS_MODULE;
gpio_chip->get = htcpld_chip_get;
gpio_chip->set = NULL;
gpio_chip->direction_input = htcpld_direction_input;
gpio_chip->direction_output = NULL;
gpio_chip->to_irq = htcpld_chip_to_irq;
gpio_chip->base = plat_chip_data->gpio_in_base;
gpio_chip->ngpio = plat_chip_data->num_gpios;
/* Add the GPIO chips */
ret = gpiochip_add(&(chip->chip_out));
if (ret) {
dev_warn(dev, "Unable to register output GPIOs for 0x%x: %d\n",
plat_chip_data->addr, ret);
return ret;
}
ret = gpiochip_add(&(chip->chip_in));
if (ret) {
int error;
dev_warn(dev, "Unable to register input GPIOs for 0x%x: %d\n",
plat_chip_data->addr, ret);
error = gpiochip_remove(&(chip->chip_out));
if (error)
dev_warn(dev, "Error while trying to unregister gpio chip: %d\n", error);
return ret;
}
return 0;
}
static int htcpld_setup_chips(struct platform_device *pdev)
{
struct htcpld_data *htcpld;
struct device *dev = &pdev->dev;
struct htcpld_core_platform_data *pdata;
int i;
/* Get the platform and driver data */
pdata = dev->platform_data;
htcpld = platform_get_drvdata(pdev);
/* Setup each chip's output GPIOs */
htcpld->nchips = pdata->num_chip;
htcpld->chip = kzalloc(sizeof(struct htcpld_chip) * htcpld->nchips,
GFP_KERNEL);
if (!htcpld->chip) {
dev_warn(dev, "Unable to allocate memory for chips\n");
return -ENOMEM;
}
/* Add the chips as best we can */
for (i = 0; i < htcpld->nchips; i++) {
int ret;
/* Setup the HTCPLD chips */
htcpld->chip[i].reset = pdata->chip[i].reset;
htcpld->chip[i].cache_out = pdata->chip[i].reset;
htcpld->chip[i].cache_in = 0;
htcpld->chip[i].dev = dev;
htcpld->chip[i].irq_start = pdata->chip[i].irq_base;
htcpld->chip[i].nirqs = pdata->chip[i].num_irqs;
INIT_WORK(&(htcpld->chip[i].set_val_work), &htcpld_chip_set_ni);
spin_lock_init(&(htcpld->chip[i].lock));
/* Setup the interrupts for the chip */
if (htcpld->chained_irq) {
ret = htcpld_setup_chip_irq(pdev, i);
if (ret)
continue;
}
/* Register the chip with I2C */
ret = htcpld_register_chip_i2c(pdev, i);
if (ret)
continue;
/* Register the chips with the GPIO subsystem */
ret = htcpld_register_chip_gpio(pdev, i);
if (ret) {
/* Unregister the chip from i2c and continue */
htcpld_unregister_chip_i2c(pdev, i);
continue;
}
dev_info(dev, "Registered chip at 0x%x\n", pdata->chip[i].addr);
}
return 0;
}
static int htcpld_core_probe(struct platform_device *pdev)
{
struct htcpld_data *htcpld;
struct device *dev = &pdev->dev;
struct htcpld_core_platform_data *pdata;
struct resource *res;
int ret = 0;
if (!dev)
return -ENODEV;
pdata = dev->platform_data;
if (!pdata) {
dev_warn(dev, "Platform data not found for htcpld core!\n");
return -ENXIO;
}
htcpld = kzalloc(sizeof(struct htcpld_data), GFP_KERNEL);
if (!htcpld)
return -ENOMEM;
/* Find chained irq */
ret = -EINVAL;
res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (res) {
int flags;
htcpld->chained_irq = res->start;
/* Setup the chained interrupt handler */
flags = IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING;
ret = request_threaded_irq(htcpld->chained_irq,
NULL, htcpld_handler,
flags, pdev->name, htcpld);
if (ret) {
dev_warn(dev, "Unable to setup chained irq handler: %d\n", ret);
goto fail;
} else
device_init_wakeup(dev, 0);
}
/* Set the driver data */
platform_set_drvdata(pdev, htcpld);
/* Setup the htcpld chips */
ret = htcpld_setup_chips(pdev);
if (ret)
goto fail;
/* Request the GPIO(s) for the int reset and set them up */
if (pdata->int_reset_gpio_hi) {
ret = gpio_request(pdata->int_reset_gpio_hi, "htcpld-core");
if (ret) {
/*
* If it failed, that sucks, but we can probably
* continue on without it.
*/
dev_warn(dev, "Unable to request int_reset_gpio_hi -- interrupts may not work\n");
htcpld->int_reset_gpio_hi = 0;
} else {
htcpld->int_reset_gpio_hi = pdata->int_reset_gpio_hi;
gpio_set_value(htcpld->int_reset_gpio_hi, 1);
}
}
if (pdata->int_reset_gpio_lo) {
ret = gpio_request(pdata->int_reset_gpio_lo, "htcpld-core");
if (ret) {
/*
* If it failed, that sucks, but we can probably
* continue on without it.
*/
dev_warn(dev, "Unable to request int_reset_gpio_lo -- interrupts may not work\n");
htcpld->int_reset_gpio_lo = 0;
} else {
htcpld->int_reset_gpio_lo = pdata->int_reset_gpio_lo;
gpio_set_value(htcpld->int_reset_gpio_lo, 0);
}
}
dev_info(dev, "Initialized successfully\n");
return 0;
fail:
kfree(htcpld);
return ret;
}
/* The I2C Driver -- used internally */
static const struct i2c_device_id htcpld_chip_id[] = {
{ "htcpld-chip", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, htcpld_chip_id);
static struct i2c_driver htcpld_chip_driver = {
.driver = {
.name = "htcpld-chip",
},
.id_table = htcpld_chip_id,
};
/* The Core Driver */
static struct platform_driver htcpld_core_driver = {
.driver = {
.name = "i2c-htcpld",
},
};
static int __init htcpld_core_init(void)
{
int ret;
/* Register the I2C Chip driver */
ret = i2c_add_driver(&htcpld_chip_driver);
if (ret)
return ret;
/* Probe for our chips */
return platform_driver_probe(&htcpld_core_driver, htcpld_core_probe);
}
static void __exit htcpld_core_exit(void)
{
i2c_del_driver(&htcpld_chip_driver);
platform_driver_unregister(&htcpld_core_driver);
}
module_init(htcpld_core_init);
module_exit(htcpld_core_exit);
MODULE_AUTHOR("Cory Maccarrone <darkstar6262@gmail.com>");
MODULE_DESCRIPTION("I2C HTC PLD Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Sunfong/sunfong-samsung-3.0 | drivers/usb/gadget/fusb300_udc.c | 2507 | 42556 | /*
* Fusb300 UDC (USB gadget)
*
* Copyright (C) 2010 Faraday Technology Corp.
*
* Author : Yuan-hsin Chen <yhchen@faraday-tech.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <linux/dma-mapping.h>
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include "fusb300_udc.h"
MODULE_DESCRIPTION("FUSB300 USB gadget driver");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Yuan Hsin Chen <yhchen@faraday-tech.com>");
MODULE_ALIAS("platform:fusb300_udc");
#define DRIVER_VERSION "20 October 2010"
static const char udc_name[] = "fusb300_udc";
static const char * const fusb300_ep_name[] = {
"ep0", "ep1", "ep2", "ep3", "ep4", "ep5", "ep6", "ep7", "ep8", "ep9",
"ep10", "ep11", "ep12", "ep13", "ep14", "ep15"
};
static void done(struct fusb300_ep *ep, struct fusb300_request *req,
int status);
static void fusb300_enable_bit(struct fusb300 *fusb300, u32 offset,
u32 value)
{
u32 reg = ioread32(fusb300->reg + offset);
reg |= value;
iowrite32(reg, fusb300->reg + offset);
}
static void fusb300_disable_bit(struct fusb300 *fusb300, u32 offset,
u32 value)
{
u32 reg = ioread32(fusb300->reg + offset);
reg &= ~value;
iowrite32(reg, fusb300->reg + offset);
}
static void fusb300_ep_setting(struct fusb300_ep *ep,
struct fusb300_ep_info info)
{
ep->epnum = info.epnum;
ep->type = info.type;
}
static int fusb300_ep_release(struct fusb300_ep *ep)
{
if (!ep->epnum)
return 0;
ep->epnum = 0;
ep->stall = 0;
ep->wedged = 0;
return 0;
}
static void fusb300_set_fifo_entry(struct fusb300 *fusb300,
u32 ep)
{
u32 val = ioread32(fusb300->reg + FUSB300_OFFSET_EPSET1(ep));
val &= ~FUSB300_EPSET1_FIFOENTRY_MSK;
val |= FUSB300_EPSET1_FIFOENTRY(FUSB300_FIFO_ENTRY_NUM);
iowrite32(val, fusb300->reg + FUSB300_OFFSET_EPSET1(ep));
}
static void fusb300_set_start_entry(struct fusb300 *fusb300,
u8 ep)
{
u32 reg = ioread32(fusb300->reg + FUSB300_OFFSET_EPSET1(ep));
u32 start_entry = fusb300->fifo_entry_num * FUSB300_FIFO_ENTRY_NUM;
reg &= ~FUSB300_EPSET1_START_ENTRY_MSK ;
reg |= FUSB300_EPSET1_START_ENTRY(start_entry);
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_EPSET1(ep));
if (fusb300->fifo_entry_num == FUSB300_MAX_FIFO_ENTRY) {
fusb300->fifo_entry_num = 0;
fusb300->addrofs = 0;
pr_err("fifo entry is over the maximum number!\n");
} else
fusb300->fifo_entry_num++;
}
/* set fusb300_set_start_entry first before fusb300_set_epaddrofs */
static void fusb300_set_epaddrofs(struct fusb300 *fusb300,
struct fusb300_ep_info info)
{
u32 reg = ioread32(fusb300->reg + FUSB300_OFFSET_EPSET2(info.epnum));
reg &= ~FUSB300_EPSET2_ADDROFS_MSK;
reg |= FUSB300_EPSET2_ADDROFS(fusb300->addrofs);
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_EPSET2(info.epnum));
fusb300->addrofs += (info.maxpacket + 7) / 8 * FUSB300_FIFO_ENTRY_NUM;
}
static void ep_fifo_setting(struct fusb300 *fusb300,
struct fusb300_ep_info info)
{
fusb300_set_fifo_entry(fusb300, info.epnum);
fusb300_set_start_entry(fusb300, info.epnum);
fusb300_set_epaddrofs(fusb300, info);
}
static void fusb300_set_eptype(struct fusb300 *fusb300,
struct fusb300_ep_info info)
{
u32 reg = ioread32(fusb300->reg + FUSB300_OFFSET_EPSET1(info.epnum));
reg &= ~FUSB300_EPSET1_TYPE_MSK;
reg |= FUSB300_EPSET1_TYPE(info.type);
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_EPSET1(info.epnum));
}
static void fusb300_set_epdir(struct fusb300 *fusb300,
struct fusb300_ep_info info)
{
u32 reg;
if (!info.dir_in)
return;
reg = ioread32(fusb300->reg + FUSB300_OFFSET_EPSET1(info.epnum));
reg &= ~FUSB300_EPSET1_DIR_MSK;
reg |= FUSB300_EPSET1_DIRIN;
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_EPSET1(info.epnum));
}
static void fusb300_set_ep_active(struct fusb300 *fusb300,
u8 ep)
{
u32 reg = ioread32(fusb300->reg + FUSB300_OFFSET_EPSET1(ep));
reg |= FUSB300_EPSET1_ACTEN;
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_EPSET1(ep));
}
static void fusb300_set_epmps(struct fusb300 *fusb300,
struct fusb300_ep_info info)
{
u32 reg = ioread32(fusb300->reg + FUSB300_OFFSET_EPSET2(info.epnum));
reg &= ~FUSB300_EPSET2_MPS_MSK;
reg |= FUSB300_EPSET2_MPS(info.maxpacket);
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_EPSET2(info.epnum));
}
static void fusb300_set_interval(struct fusb300 *fusb300,
struct fusb300_ep_info info)
{
u32 reg = ioread32(fusb300->reg + FUSB300_OFFSET_EPSET1(info.epnum));
reg &= ~FUSB300_EPSET1_INTERVAL(0x7);
reg |= FUSB300_EPSET1_INTERVAL(info.interval);
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_EPSET1(info.epnum));
}
static void fusb300_set_bwnum(struct fusb300 *fusb300,
struct fusb300_ep_info info)
{
u32 reg = ioread32(fusb300->reg + FUSB300_OFFSET_EPSET1(info.epnum));
reg &= ~FUSB300_EPSET1_BWNUM(0x3);
reg |= FUSB300_EPSET1_BWNUM(info.bw_num);
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_EPSET1(info.epnum));
}
static void set_ep_reg(struct fusb300 *fusb300,
struct fusb300_ep_info info)
{
fusb300_set_eptype(fusb300, info);
fusb300_set_epdir(fusb300, info);
fusb300_set_epmps(fusb300, info);
if (info.interval)
fusb300_set_interval(fusb300, info);
if (info.bw_num)
fusb300_set_bwnum(fusb300, info);
fusb300_set_ep_active(fusb300, info.epnum);
}
static int config_ep(struct fusb300_ep *ep,
const struct usb_endpoint_descriptor *desc)
{
struct fusb300 *fusb300 = ep->fusb300;
struct fusb300_ep_info info;
ep->desc = desc;
info.interval = 0;
info.addrofs = 0;
info.bw_num = 0;
info.type = desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
info.dir_in = (desc->bEndpointAddress & USB_ENDPOINT_DIR_MASK) ? 1 : 0;
info.maxpacket = le16_to_cpu(desc->wMaxPacketSize);
info.epnum = desc->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
if ((info.type == USB_ENDPOINT_XFER_INT) ||
(info.type == USB_ENDPOINT_XFER_ISOC)) {
info.interval = desc->bInterval;
if (info.type == USB_ENDPOINT_XFER_ISOC)
info.bw_num = ((desc->wMaxPacketSize & 0x1800) >> 11);
}
ep_fifo_setting(fusb300, info);
set_ep_reg(fusb300, info);
fusb300_ep_setting(ep, info);
fusb300->ep[info.epnum] = ep;
return 0;
}
static int fusb300_enable(struct usb_ep *_ep,
const struct usb_endpoint_descriptor *desc)
{
struct fusb300_ep *ep;
ep = container_of(_ep, struct fusb300_ep, ep);
if (ep->fusb300->reenum) {
ep->fusb300->fifo_entry_num = 0;
ep->fusb300->addrofs = 0;
ep->fusb300->reenum = 0;
}
return config_ep(ep, desc);
}
static int fusb300_disable(struct usb_ep *_ep)
{
struct fusb300_ep *ep;
struct fusb300_request *req;
unsigned long flags;
ep = container_of(_ep, struct fusb300_ep, ep);
BUG_ON(!ep);
while (!list_empty(&ep->queue)) {
req = list_entry(ep->queue.next, struct fusb300_request, queue);
spin_lock_irqsave(&ep->fusb300->lock, flags);
done(ep, req, -ECONNRESET);
spin_unlock_irqrestore(&ep->fusb300->lock, flags);
}
return fusb300_ep_release(ep);
}
static struct usb_request *fusb300_alloc_request(struct usb_ep *_ep,
gfp_t gfp_flags)
{
struct fusb300_request *req;
req = kzalloc(sizeof(struct fusb300_request), gfp_flags);
if (!req)
return NULL;
INIT_LIST_HEAD(&req->queue);
return &req->req;
}
static void fusb300_free_request(struct usb_ep *_ep, struct usb_request *_req)
{
struct fusb300_request *req;
req = container_of(_req, struct fusb300_request, req);
kfree(req);
}
static int enable_fifo_int(struct fusb300_ep *ep)
{
struct fusb300 *fusb300 = ep->fusb300;
if (ep->epnum) {
fusb300_enable_bit(fusb300, FUSB300_OFFSET_IGER0,
FUSB300_IGER0_EEPn_FIFO_INT(ep->epnum));
} else {
pr_err("can't enable_fifo_int ep0\n");
return -EINVAL;
}
return 0;
}
static int disable_fifo_int(struct fusb300_ep *ep)
{
struct fusb300 *fusb300 = ep->fusb300;
if (ep->epnum) {
fusb300_disable_bit(fusb300, FUSB300_OFFSET_IGER0,
FUSB300_IGER0_EEPn_FIFO_INT(ep->epnum));
} else {
pr_err("can't disable_fifo_int ep0\n");
return -EINVAL;
}
return 0;
}
static void fusb300_set_cxlen(struct fusb300 *fusb300, u32 length)
{
u32 reg;
reg = ioread32(fusb300->reg + FUSB300_OFFSET_CSR);
reg &= ~FUSB300_CSR_LEN_MSK;
reg |= FUSB300_CSR_LEN(length);
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_CSR);
}
/* write data to cx fifo */
static void fusb300_wrcxf(struct fusb300_ep *ep,
struct fusb300_request *req)
{
int i = 0;
u8 *tmp;
u32 data;
struct fusb300 *fusb300 = ep->fusb300;
u32 length = req->req.length - req->req.actual;
tmp = req->req.buf + req->req.actual;
if (length > SS_CTL_MAX_PACKET_SIZE) {
fusb300_set_cxlen(fusb300, SS_CTL_MAX_PACKET_SIZE);
for (i = (SS_CTL_MAX_PACKET_SIZE >> 2); i > 0; i--) {
data = *tmp | *(tmp + 1) << 8 | *(tmp + 2) << 16 |
*(tmp + 3) << 24;
iowrite32(data, fusb300->reg + FUSB300_OFFSET_CXPORT);
tmp += 4;
}
req->req.actual += SS_CTL_MAX_PACKET_SIZE;
} else { /* length is less than max packet size */
fusb300_set_cxlen(fusb300, length);
for (i = length >> 2; i > 0; i--) {
data = *tmp | *(tmp + 1) << 8 | *(tmp + 2) << 16 |
*(tmp + 3) << 24;
printk(KERN_DEBUG " 0x%x\n", data);
iowrite32(data, fusb300->reg + FUSB300_OFFSET_CXPORT);
tmp = tmp + 4;
}
switch (length % 4) {
case 1:
data = *tmp;
printk(KERN_DEBUG " 0x%x\n", data);
iowrite32(data, fusb300->reg + FUSB300_OFFSET_CXPORT);
break;
case 2:
data = *tmp | *(tmp + 1) << 8;
printk(KERN_DEBUG " 0x%x\n", data);
iowrite32(data, fusb300->reg + FUSB300_OFFSET_CXPORT);
break;
case 3:
data = *tmp | *(tmp + 1) << 8 | *(tmp + 2) << 16;
printk(KERN_DEBUG " 0x%x\n", data);
iowrite32(data, fusb300->reg + FUSB300_OFFSET_CXPORT);
break;
default:
break;
}
req->req.actual += length;
}
}
static void fusb300_set_epnstall(struct fusb300 *fusb300, u8 ep)
{
fusb300_enable_bit(fusb300, FUSB300_OFFSET_EPSET0(ep),
FUSB300_EPSET0_STL);
}
static void fusb300_clear_epnstall(struct fusb300 *fusb300, u8 ep)
{
u32 reg = ioread32(fusb300->reg + FUSB300_OFFSET_EPSET0(ep));
if (reg & FUSB300_EPSET0_STL) {
printk(KERN_DEBUG "EP%d stall... Clear!!\n", ep);
reg &= ~FUSB300_EPSET0_STL;
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_EPSET0(ep));
}
}
static void ep0_queue(struct fusb300_ep *ep, struct fusb300_request *req)
{
if (ep->fusb300->ep0_dir) { /* if IN */
if (req->req.length) {
fusb300_wrcxf(ep, req);
} else
printk(KERN_DEBUG "%s : req->req.length = 0x%x\n",
__func__, req->req.length);
if ((req->req.length == req->req.actual) ||
(req->req.actual < ep->ep.maxpacket))
done(ep, req, 0);
} else { /* OUT */
if (!req->req.length)
done(ep, req, 0);
else
fusb300_enable_bit(ep->fusb300, FUSB300_OFFSET_IGER1,
FUSB300_IGER1_CX_OUT_INT);
}
}
static int fusb300_queue(struct usb_ep *_ep, struct usb_request *_req,
gfp_t gfp_flags)
{
struct fusb300_ep *ep;
struct fusb300_request *req;
unsigned long flags;
int request = 0;
ep = container_of(_ep, struct fusb300_ep, ep);
req = container_of(_req, struct fusb300_request, req);
if (ep->fusb300->gadget.speed == USB_SPEED_UNKNOWN)
return -ESHUTDOWN;
spin_lock_irqsave(&ep->fusb300->lock, flags);
if (list_empty(&ep->queue))
request = 1;
list_add_tail(&req->queue, &ep->queue);
req->req.actual = 0;
req->req.status = -EINPROGRESS;
if (ep->desc == NULL) /* ep0 */
ep0_queue(ep, req);
else if (request && !ep->stall)
enable_fifo_int(ep);
spin_unlock_irqrestore(&ep->fusb300->lock, flags);
return 0;
}
static int fusb300_dequeue(struct usb_ep *_ep, struct usb_request *_req)
{
struct fusb300_ep *ep;
struct fusb300_request *req;
unsigned long flags;
ep = container_of(_ep, struct fusb300_ep, ep);
req = container_of(_req, struct fusb300_request, req);
spin_lock_irqsave(&ep->fusb300->lock, flags);
if (!list_empty(&ep->queue))
done(ep, req, -ECONNRESET);
spin_unlock_irqrestore(&ep->fusb300->lock, flags);
return 0;
}
static int fusb300_set_halt_and_wedge(struct usb_ep *_ep, int value, int wedge)
{
struct fusb300_ep *ep;
struct fusb300 *fusb300;
unsigned long flags;
int ret = 0;
ep = container_of(_ep, struct fusb300_ep, ep);
fusb300 = ep->fusb300;
spin_lock_irqsave(&ep->fusb300->lock, flags);
if (!list_empty(&ep->queue)) {
ret = -EAGAIN;
goto out;
}
if (value) {
fusb300_set_epnstall(fusb300, ep->epnum);
ep->stall = 1;
if (wedge)
ep->wedged = 1;
} else {
fusb300_clear_epnstall(fusb300, ep->epnum);
ep->stall = 0;
ep->wedged = 0;
}
out:
spin_unlock_irqrestore(&ep->fusb300->lock, flags);
return ret;
}
static int fusb300_set_halt(struct usb_ep *_ep, int value)
{
return fusb300_set_halt_and_wedge(_ep, value, 0);
}
static int fusb300_set_wedge(struct usb_ep *_ep)
{
return fusb300_set_halt_and_wedge(_ep, 1, 1);
}
static void fusb300_fifo_flush(struct usb_ep *_ep)
{
}
static struct usb_ep_ops fusb300_ep_ops = {
.enable = fusb300_enable,
.disable = fusb300_disable,
.alloc_request = fusb300_alloc_request,
.free_request = fusb300_free_request,
.queue = fusb300_queue,
.dequeue = fusb300_dequeue,
.set_halt = fusb300_set_halt,
.fifo_flush = fusb300_fifo_flush,
.set_wedge = fusb300_set_wedge,
};
/*****************************************************************************/
static void fusb300_clear_int(struct fusb300 *fusb300, u32 offset,
u32 value)
{
iowrite32(value, fusb300->reg + offset);
}
static void fusb300_reset(void)
{
}
static void fusb300_set_cxstall(struct fusb300 *fusb300)
{
fusb300_enable_bit(fusb300, FUSB300_OFFSET_CSR,
FUSB300_CSR_STL);
}
static void fusb300_set_cxdone(struct fusb300 *fusb300)
{
fusb300_enable_bit(fusb300, FUSB300_OFFSET_CSR,
FUSB300_CSR_DONE);
}
/* read data from cx fifo */
void fusb300_rdcxf(struct fusb300 *fusb300,
u8 *buffer, u32 length)
{
int i = 0;
u8 *tmp;
u32 data;
tmp = buffer;
for (i = (length >> 2); i > 0; i--) {
data = ioread32(fusb300->reg + FUSB300_OFFSET_CXPORT);
printk(KERN_DEBUG " 0x%x\n", data);
*tmp = data & 0xFF;
*(tmp + 1) = (data >> 8) & 0xFF;
*(tmp + 2) = (data >> 16) & 0xFF;
*(tmp + 3) = (data >> 24) & 0xFF;
tmp = tmp + 4;
}
switch (length % 4) {
case 1:
data = ioread32(fusb300->reg + FUSB300_OFFSET_CXPORT);
printk(KERN_DEBUG " 0x%x\n", data);
*tmp = data & 0xFF;
break;
case 2:
data = ioread32(fusb300->reg + FUSB300_OFFSET_CXPORT);
printk(KERN_DEBUG " 0x%x\n", data);
*tmp = data & 0xFF;
*(tmp + 1) = (data >> 8) & 0xFF;
break;
case 3:
data = ioread32(fusb300->reg + FUSB300_OFFSET_CXPORT);
printk(KERN_DEBUG " 0x%x\n", data);
*tmp = data & 0xFF;
*(tmp + 1) = (data >> 8) & 0xFF;
*(tmp + 2) = (data >> 16) & 0xFF;
break;
default:
break;
}
}
#if 0
static void fusb300_dbg_fifo(struct fusb300_ep *ep,
u8 entry, u16 length)
{
u32 reg;
u32 i = 0;
u32 j = 0;
reg = ioread32(ep->fusb300->reg + FUSB300_OFFSET_GTM);
reg &= ~(FUSB300_GTM_TST_EP_ENTRY(0xF) |
FUSB300_GTM_TST_EP_NUM(0xF) | FUSB300_GTM_TST_FIFO_DEG);
reg |= (FUSB300_GTM_TST_EP_ENTRY(entry) |
FUSB300_GTM_TST_EP_NUM(ep->epnum) | FUSB300_GTM_TST_FIFO_DEG);
iowrite32(reg, ep->fusb300->reg + FUSB300_OFFSET_GTM);
for (i = 0; i < (length >> 2); i++) {
if (i * 4 == 1024)
break;
reg = ioread32(ep->fusb300->reg +
FUSB300_OFFSET_BUFDBG_START + i * 4);
printk(KERN_DEBUG" 0x%-8x", reg);
j++;
if ((j % 4) == 0)
printk(KERN_DEBUG "\n");
}
if (length % 4) {
reg = ioread32(ep->fusb300->reg +
FUSB300_OFFSET_BUFDBG_START + i * 4);
printk(KERN_DEBUG " 0x%x\n", reg);
}
if ((j % 4) != 0)
printk(KERN_DEBUG "\n");
fusb300_disable_bit(ep->fusb300, FUSB300_OFFSET_GTM,
FUSB300_GTM_TST_FIFO_DEG);
}
static void fusb300_cmp_dbg_fifo(struct fusb300_ep *ep,
u8 entry, u16 length, u8 *golden)
{
u32 reg;
u32 i = 0;
u32 golden_value;
u8 *tmp;
tmp = golden;
printk(KERN_DEBUG "fusb300_cmp_dbg_fifo (entry %d) : start\n", entry);
reg = ioread32(ep->fusb300->reg + FUSB300_OFFSET_GTM);
reg &= ~(FUSB300_GTM_TST_EP_ENTRY(0xF) |
FUSB300_GTM_TST_EP_NUM(0xF) | FUSB300_GTM_TST_FIFO_DEG);
reg |= (FUSB300_GTM_TST_EP_ENTRY(entry) |
FUSB300_GTM_TST_EP_NUM(ep->epnum) | FUSB300_GTM_TST_FIFO_DEG);
iowrite32(reg, ep->fusb300->reg + FUSB300_OFFSET_GTM);
for (i = 0; i < (length >> 2); i++) {
if (i * 4 == 1024)
break;
golden_value = *tmp | *(tmp + 1) << 8 |
*(tmp + 2) << 16 | *(tmp + 3) << 24;
reg = ioread32(ep->fusb300->reg +
FUSB300_OFFSET_BUFDBG_START + i*4);
if (reg != golden_value) {
printk(KERN_DEBUG "0x%x : ", (u32)(ep->fusb300->reg +
FUSB300_OFFSET_BUFDBG_START + i*4));
printk(KERN_DEBUG " golden = 0x%x, reg = 0x%x\n",
golden_value, reg);
}
tmp += 4;
}
switch (length % 4) {
case 1:
golden_value = *tmp;
case 2:
golden_value = *tmp | *(tmp + 1) << 8;
case 3:
golden_value = *tmp | *(tmp + 1) << 8 | *(tmp + 2) << 16;
default:
break;
reg = ioread32(ep->fusb300->reg + FUSB300_OFFSET_BUFDBG_START + i*4);
if (reg != golden_value) {
printk(KERN_DEBUG "0x%x:", (u32)(ep->fusb300->reg +
FUSB300_OFFSET_BUFDBG_START + i*4));
printk(KERN_DEBUG " golden = 0x%x, reg = 0x%x\n",
golden_value, reg);
}
}
printk(KERN_DEBUG "fusb300_cmp_dbg_fifo : end\n");
fusb300_disable_bit(ep->fusb300, FUSB300_OFFSET_GTM,
FUSB300_GTM_TST_FIFO_DEG);
}
#endif
static void fusb300_rdfifo(struct fusb300_ep *ep,
struct fusb300_request *req,
u32 length)
{
int i = 0;
u8 *tmp;
u32 data, reg;
struct fusb300 *fusb300 = ep->fusb300;
tmp = req->req.buf + req->req.actual;
req->req.actual += length;
if (req->req.actual > req->req.length)
printk(KERN_DEBUG "req->req.actual > req->req.length\n");
for (i = (length >> 2); i > 0; i--) {
data = ioread32(fusb300->reg +
FUSB300_OFFSET_EPPORT(ep->epnum));
*tmp = data & 0xFF;
*(tmp + 1) = (data >> 8) & 0xFF;
*(tmp + 2) = (data >> 16) & 0xFF;
*(tmp + 3) = (data >> 24) & 0xFF;
tmp = tmp + 4;
}
switch (length % 4) {
case 1:
data = ioread32(fusb300->reg +
FUSB300_OFFSET_EPPORT(ep->epnum));
*tmp = data & 0xFF;
break;
case 2:
data = ioread32(fusb300->reg +
FUSB300_OFFSET_EPPORT(ep->epnum));
*tmp = data & 0xFF;
*(tmp + 1) = (data >> 8) & 0xFF;
break;
case 3:
data = ioread32(fusb300->reg +
FUSB300_OFFSET_EPPORT(ep->epnum));
*tmp = data & 0xFF;
*(tmp + 1) = (data >> 8) & 0xFF;
*(tmp + 2) = (data >> 16) & 0xFF;
break;
default:
break;
}
do {
reg = ioread32(fusb300->reg + FUSB300_OFFSET_IGR1);
reg &= FUSB300_IGR1_SYNF0_EMPTY_INT;
if (i)
printk(KERN_INFO "sync fifo is not empty!\n");
i++;
} while (!reg);
}
/* write data to fifo */
static void fusb300_wrfifo(struct fusb300_ep *ep,
struct fusb300_request *req)
{
int i = 0;
u8 *tmp;
u32 data, reg;
struct fusb300 *fusb300 = ep->fusb300;
tmp = req->req.buf;
req->req.actual = req->req.length;
for (i = (req->req.length >> 2); i > 0; i--) {
data = *tmp | *(tmp + 1) << 8 |
*(tmp + 2) << 16 | *(tmp + 3) << 24;
iowrite32(data, fusb300->reg +
FUSB300_OFFSET_EPPORT(ep->epnum));
tmp += 4;
}
switch (req->req.length % 4) {
case 1:
data = *tmp;
iowrite32(data, fusb300->reg +
FUSB300_OFFSET_EPPORT(ep->epnum));
break;
case 2:
data = *tmp | *(tmp + 1) << 8;
iowrite32(data, fusb300->reg +
FUSB300_OFFSET_EPPORT(ep->epnum));
break;
case 3:
data = *tmp | *(tmp + 1) << 8 | *(tmp + 2) << 16;
iowrite32(data, fusb300->reg +
FUSB300_OFFSET_EPPORT(ep->epnum));
break;
default:
break;
}
do {
reg = ioread32(fusb300->reg + FUSB300_OFFSET_IGR1);
reg &= FUSB300_IGR1_SYNF0_EMPTY_INT;
if (i)
printk(KERN_INFO"sync fifo is not empty!\n");
i++;
} while (!reg);
}
static u8 fusb300_get_epnstall(struct fusb300 *fusb300, u8 ep)
{
u8 value;
u32 reg = ioread32(fusb300->reg + FUSB300_OFFSET_EPSET0(ep));
value = reg & FUSB300_EPSET0_STL;
return value;
}
static u8 fusb300_get_cxstall(struct fusb300 *fusb300)
{
u8 value;
u32 reg = ioread32(fusb300->reg + FUSB300_OFFSET_CSR);
value = (reg & FUSB300_CSR_STL) >> 1;
return value;
}
static void request_error(struct fusb300 *fusb300)
{
fusb300_set_cxstall(fusb300);
printk(KERN_DEBUG "request error!!\n");
}
static void get_status(struct fusb300 *fusb300, struct usb_ctrlrequest *ctrl)
__releases(fusb300->lock)
__acquires(fusb300->lock)
{
u8 ep;
u16 status = 0;
u16 w_index = ctrl->wIndex;
switch (ctrl->bRequestType & USB_RECIP_MASK) {
case USB_RECIP_DEVICE:
status = 1 << USB_DEVICE_SELF_POWERED;
break;
case USB_RECIP_INTERFACE:
status = 0;
break;
case USB_RECIP_ENDPOINT:
ep = w_index & USB_ENDPOINT_NUMBER_MASK;
if (ep) {
if (fusb300_get_epnstall(fusb300, ep))
status = 1 << USB_ENDPOINT_HALT;
} else {
if (fusb300_get_cxstall(fusb300))
status = 0;
}
break;
default:
request_error(fusb300);
return; /* exit */
}
fusb300->ep0_data = cpu_to_le16(status);
fusb300->ep0_req->buf = &fusb300->ep0_data;
fusb300->ep0_req->length = 2;
spin_unlock(&fusb300->lock);
fusb300_queue(fusb300->gadget.ep0, fusb300->ep0_req, GFP_KERNEL);
spin_lock(&fusb300->lock);
}
static void set_feature(struct fusb300 *fusb300, struct usb_ctrlrequest *ctrl)
{
u8 ep;
switch (ctrl->bRequestType & USB_RECIP_MASK) {
case USB_RECIP_DEVICE:
fusb300_set_cxdone(fusb300);
break;
case USB_RECIP_INTERFACE:
fusb300_set_cxdone(fusb300);
break;
case USB_RECIP_ENDPOINT: {
u16 w_index = le16_to_cpu(ctrl->wIndex);
ep = w_index & USB_ENDPOINT_NUMBER_MASK;
if (ep)
fusb300_set_epnstall(fusb300, ep);
else
fusb300_set_cxstall(fusb300);
fusb300_set_cxdone(fusb300);
}
break;
default:
request_error(fusb300);
break;
}
}
static void fusb300_clear_seqnum(struct fusb300 *fusb300, u8 ep)
{
fusb300_enable_bit(fusb300, FUSB300_OFFSET_EPSET0(ep),
FUSB300_EPSET0_CLRSEQNUM);
}
static void clear_feature(struct fusb300 *fusb300, struct usb_ctrlrequest *ctrl)
{
struct fusb300_ep *ep =
fusb300->ep[ctrl->wIndex & USB_ENDPOINT_NUMBER_MASK];
switch (ctrl->bRequestType & USB_RECIP_MASK) {
case USB_RECIP_DEVICE:
fusb300_set_cxdone(fusb300);
break;
case USB_RECIP_INTERFACE:
fusb300_set_cxdone(fusb300);
break;
case USB_RECIP_ENDPOINT:
if (ctrl->wIndex & USB_ENDPOINT_NUMBER_MASK) {
if (ep->wedged) {
fusb300_set_cxdone(fusb300);
break;
}
if (ep->stall) {
ep->stall = 0;
fusb300_clear_seqnum(fusb300, ep->epnum);
fusb300_clear_epnstall(fusb300, ep->epnum);
if (!list_empty(&ep->queue))
enable_fifo_int(ep);
}
}
fusb300_set_cxdone(fusb300);
break;
default:
request_error(fusb300);
break;
}
}
static void fusb300_set_dev_addr(struct fusb300 *fusb300, u16 addr)
{
u32 reg = ioread32(fusb300->reg + FUSB300_OFFSET_DAR);
reg &= ~FUSB300_DAR_DRVADDR_MSK;
reg |= FUSB300_DAR_DRVADDR(addr);
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_DAR);
}
static void set_address(struct fusb300 *fusb300, struct usb_ctrlrequest *ctrl)
{
if (ctrl->wValue >= 0x0100)
request_error(fusb300);
else {
fusb300_set_dev_addr(fusb300, ctrl->wValue);
fusb300_set_cxdone(fusb300);
}
}
#define UVC_COPY_DESCRIPTORS(mem, src) \
do { \
const struct usb_descriptor_header * const *__src; \
for (__src = src; *__src; ++__src) { \
memcpy(mem, *__src, (*__src)->bLength); \
mem += (*__src)->bLength; \
} \
} while (0)
static void fusb300_ep0_complete(struct usb_ep *ep,
struct usb_request *req)
{
}
static int setup_packet(struct fusb300 *fusb300, struct usb_ctrlrequest *ctrl)
{
u8 *p = (u8 *)ctrl;
u8 ret = 0;
u8 i = 0;
fusb300_rdcxf(fusb300, p, 8);
fusb300->ep0_dir = ctrl->bRequestType & USB_DIR_IN;
fusb300->ep0_length = ctrl->wLength;
/* check request */
if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) {
switch (ctrl->bRequest) {
case USB_REQ_GET_STATUS:
get_status(fusb300, ctrl);
break;
case USB_REQ_CLEAR_FEATURE:
clear_feature(fusb300, ctrl);
break;
case USB_REQ_SET_FEATURE:
set_feature(fusb300, ctrl);
break;
case USB_REQ_SET_ADDRESS:
set_address(fusb300, ctrl);
break;
case USB_REQ_SET_CONFIGURATION:
fusb300_enable_bit(fusb300, FUSB300_OFFSET_DAR,
FUSB300_DAR_SETCONFG);
/* clear sequence number */
for (i = 1; i <= FUSB300_MAX_NUM_EP; i++)
fusb300_clear_seqnum(fusb300, i);
fusb300->reenum = 1;
ret = 1;
break;
default:
ret = 1;
break;
}
} else
ret = 1;
return ret;
}
static void fusb300_set_ep_bycnt(struct fusb300_ep *ep, u32 bycnt)
{
struct fusb300 *fusb300 = ep->fusb300;
u32 reg = ioread32(fusb300->reg + FUSB300_OFFSET_EPFFR(ep->epnum));
reg &= ~FUSB300_FFR_BYCNT;
reg |= bycnt & FUSB300_FFR_BYCNT;
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_EPFFR(ep->epnum));
}
static void done(struct fusb300_ep *ep, struct fusb300_request *req,
int status)
{
list_del_init(&req->queue);
/* don't modify queue heads during completion callback */
if (ep->fusb300->gadget.speed == USB_SPEED_UNKNOWN)
req->req.status = -ESHUTDOWN;
else
req->req.status = status;
spin_unlock(&ep->fusb300->lock);
req->req.complete(&ep->ep, &req->req);
spin_lock(&ep->fusb300->lock);
if (ep->epnum) {
disable_fifo_int(ep);
if (!list_empty(&ep->queue))
enable_fifo_int(ep);
} else
fusb300_set_cxdone(ep->fusb300);
}
void fusb300_fill_idma_prdtbl(struct fusb300_ep *ep,
struct fusb300_request *req)
{
u32 value;
u32 reg;
/* wait SW owner */
do {
reg = ioread32(ep->fusb300->reg +
FUSB300_OFFSET_EPPRD_W0(ep->epnum));
reg &= FUSB300_EPPRD0_H;
} while (reg);
iowrite32((u32) req->req.buf, ep->fusb300->reg +
FUSB300_OFFSET_EPPRD_W1(ep->epnum));
value = FUSB300_EPPRD0_BTC(req->req.length) | FUSB300_EPPRD0_H |
FUSB300_EPPRD0_F | FUSB300_EPPRD0_L | FUSB300_EPPRD0_I;
iowrite32(value, ep->fusb300->reg + FUSB300_OFFSET_EPPRD_W0(ep->epnum));
iowrite32(0x0, ep->fusb300->reg + FUSB300_OFFSET_EPPRD_W2(ep->epnum));
fusb300_enable_bit(ep->fusb300, FUSB300_OFFSET_EPPRDRDY,
FUSB300_EPPRDR_EP_PRD_RDY(ep->epnum));
}
static void fusb300_wait_idma_finished(struct fusb300_ep *ep)
{
u32 reg;
do {
reg = ioread32(ep->fusb300->reg + FUSB300_OFFSET_IGR1);
if ((reg & FUSB300_IGR1_VBUS_CHG_INT) ||
(reg & FUSB300_IGR1_WARM_RST_INT) ||
(reg & FUSB300_IGR1_HOT_RST_INT) ||
(reg & FUSB300_IGR1_USBRST_INT)
)
goto IDMA_RESET;
reg = ioread32(ep->fusb300->reg + FUSB300_OFFSET_IGR0);
reg &= FUSB300_IGR0_EPn_PRD_INT(ep->epnum);
} while (!reg);
fusb300_clear_int(ep->fusb300, FUSB300_OFFSET_IGR0,
FUSB300_IGR0_EPn_PRD_INT(ep->epnum));
IDMA_RESET:
fusb300_clear_int(ep->fusb300, FUSB300_OFFSET_IGER0,
FUSB300_IGER0_EEPn_PRD_INT(ep->epnum));
}
static void fusb300_set_idma(struct fusb300_ep *ep,
struct fusb300_request *req)
{
dma_addr_t d;
u8 *tmp = NULL;
d = dma_map_single(NULL, req->req.buf, req->req.length, DMA_TO_DEVICE);
if (dma_mapping_error(NULL, d)) {
kfree(req->req.buf);
printk(KERN_DEBUG "dma_mapping_error\n");
}
dma_sync_single_for_device(NULL, d, req->req.length, DMA_TO_DEVICE);
fusb300_enable_bit(ep->fusb300, FUSB300_OFFSET_IGER0,
FUSB300_IGER0_EEPn_PRD_INT(ep->epnum));
tmp = req->req.buf;
req->req.buf = (u8 *)d;
fusb300_fill_idma_prdtbl(ep, req);
/* check idma is done */
fusb300_wait_idma_finished(ep);
req->req.buf = tmp;
if (d)
dma_unmap_single(NULL, d, req->req.length, DMA_TO_DEVICE);
}
static void in_ep_fifo_handler(struct fusb300_ep *ep)
{
struct fusb300_request *req = list_entry(ep->queue.next,
struct fusb300_request, queue);
if (req->req.length) {
#if 0
fusb300_set_ep_bycnt(ep, req->req.length);
fusb300_wrfifo(ep, req);
#else
fusb300_set_idma(ep, req);
#endif
}
done(ep, req, 0);
}
static void out_ep_fifo_handler(struct fusb300_ep *ep)
{
struct fusb300 *fusb300 = ep->fusb300;
struct fusb300_request *req = list_entry(ep->queue.next,
struct fusb300_request, queue);
u32 reg = ioread32(fusb300->reg + FUSB300_OFFSET_EPFFR(ep->epnum));
u32 length = reg & FUSB300_FFR_BYCNT;
fusb300_rdfifo(ep, req, length);
/* finish out transfer */
if ((req->req.length == req->req.actual) || (length < ep->ep.maxpacket))
done(ep, req, 0);
}
static void check_device_mode(struct fusb300 *fusb300)
{
u32 reg = ioread32(fusb300->reg + FUSB300_OFFSET_GCR);
switch (reg & FUSB300_GCR_DEVEN_MSK) {
case FUSB300_GCR_DEVEN_SS:
fusb300->gadget.speed = USB_SPEED_SUPER;
break;
case FUSB300_GCR_DEVEN_HS:
fusb300->gadget.speed = USB_SPEED_HIGH;
break;
case FUSB300_GCR_DEVEN_FS:
fusb300->gadget.speed = USB_SPEED_FULL;
break;
default:
fusb300->gadget.speed = USB_SPEED_UNKNOWN;
break;
}
printk(KERN_INFO "dev_mode = %d\n", (reg & FUSB300_GCR_DEVEN_MSK));
}
static void fusb300_ep0out(struct fusb300 *fusb300)
{
struct fusb300_ep *ep = fusb300->ep[0];
u32 reg;
if (!list_empty(&ep->queue)) {
struct fusb300_request *req;
req = list_first_entry(&ep->queue,
struct fusb300_request, queue);
if (req->req.length)
fusb300_rdcxf(ep->fusb300, req->req.buf,
req->req.length);
done(ep, req, 0);
reg = ioread32(fusb300->reg + FUSB300_OFFSET_IGER1);
reg &= ~FUSB300_IGER1_CX_OUT_INT;
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_IGER1);
} else
pr_err("%s : empty queue\n", __func__);
}
static void fusb300_ep0in(struct fusb300 *fusb300)
{
struct fusb300_request *req;
struct fusb300_ep *ep = fusb300->ep[0];
if ((!list_empty(&ep->queue)) && (fusb300->ep0_dir)) {
req = list_entry(ep->queue.next,
struct fusb300_request, queue);
if (req->req.length)
fusb300_wrcxf(ep, req);
if ((req->req.length - req->req.actual) < ep->ep.maxpacket)
done(ep, req, 0);
} else
fusb300_set_cxdone(fusb300);
}
static void fusb300_grp2_handler(void)
{
}
static void fusb300_grp3_handler(void)
{
}
static void fusb300_grp4_handler(void)
{
}
static void fusb300_grp5_handler(void)
{
}
static irqreturn_t fusb300_irq(int irq, void *_fusb300)
{
struct fusb300 *fusb300 = _fusb300;
u32 int_grp1 = ioread32(fusb300->reg + FUSB300_OFFSET_IGR1);
u32 int_grp1_en = ioread32(fusb300->reg + FUSB300_OFFSET_IGER1);
u32 int_grp0 = ioread32(fusb300->reg + FUSB300_OFFSET_IGR0);
u32 int_grp0_en = ioread32(fusb300->reg + FUSB300_OFFSET_IGER0);
struct usb_ctrlrequest ctrl;
u8 in;
u32 reg;
int i;
spin_lock(&fusb300->lock);
int_grp1 &= int_grp1_en;
int_grp0 &= int_grp0_en;
if (int_grp1 & FUSB300_IGR1_WARM_RST_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_WARM_RST_INT);
printk(KERN_INFO"fusb300_warmreset\n");
fusb300_reset();
}
if (int_grp1 & FUSB300_IGR1_HOT_RST_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_HOT_RST_INT);
printk(KERN_INFO"fusb300_hotreset\n");
fusb300_reset();
}
if (int_grp1 & FUSB300_IGR1_USBRST_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_USBRST_INT);
fusb300_reset();
}
/* COMABT_INT has a highest priority */
if (int_grp1 & FUSB300_IGR1_CX_COMABT_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_CX_COMABT_INT);
printk(KERN_INFO"fusb300_ep0abt\n");
}
if (int_grp1 & FUSB300_IGR1_VBUS_CHG_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_VBUS_CHG_INT);
printk(KERN_INFO"fusb300_vbus_change\n");
}
if (int_grp1 & FUSB300_IGR1_U3_EXIT_FAIL_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_U3_EXIT_FAIL_INT);
}
if (int_grp1 & FUSB300_IGR1_U2_EXIT_FAIL_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_U2_EXIT_FAIL_INT);
}
if (int_grp1 & FUSB300_IGR1_U1_EXIT_FAIL_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_U1_EXIT_FAIL_INT);
}
if (int_grp1 & FUSB300_IGR1_U2_ENTRY_FAIL_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_U2_ENTRY_FAIL_INT);
}
if (int_grp1 & FUSB300_IGR1_U1_ENTRY_FAIL_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_U1_ENTRY_FAIL_INT);
}
if (int_grp1 & FUSB300_IGR1_U3_EXIT_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_U3_EXIT_INT);
printk(KERN_INFO "FUSB300_IGR1_U3_EXIT_INT\n");
}
if (int_grp1 & FUSB300_IGR1_U2_EXIT_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_U2_EXIT_INT);
printk(KERN_INFO "FUSB300_IGR1_U2_EXIT_INT\n");
}
if (int_grp1 & FUSB300_IGR1_U1_EXIT_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_U1_EXIT_INT);
printk(KERN_INFO "FUSB300_IGR1_U1_EXIT_INT\n");
}
if (int_grp1 & FUSB300_IGR1_U3_ENTRY_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_U3_ENTRY_INT);
printk(KERN_INFO "FUSB300_IGR1_U3_ENTRY_INT\n");
fusb300_enable_bit(fusb300, FUSB300_OFFSET_SSCR1,
FUSB300_SSCR1_GO_U3_DONE);
}
if (int_grp1 & FUSB300_IGR1_U2_ENTRY_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_U2_ENTRY_INT);
printk(KERN_INFO "FUSB300_IGR1_U2_ENTRY_INT\n");
}
if (int_grp1 & FUSB300_IGR1_U1_ENTRY_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_U1_ENTRY_INT);
printk(KERN_INFO "FUSB300_IGR1_U1_ENTRY_INT\n");
}
if (int_grp1 & FUSB300_IGR1_RESM_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_RESM_INT);
printk(KERN_INFO "fusb300_resume\n");
}
if (int_grp1 & FUSB300_IGR1_SUSP_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_SUSP_INT);
printk(KERN_INFO "fusb300_suspend\n");
}
if (int_grp1 & FUSB300_IGR1_HS_LPM_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_HS_LPM_INT);
printk(KERN_INFO "fusb300_HS_LPM_INT\n");
}
if (int_grp1 & FUSB300_IGR1_DEV_MODE_CHG_INT) {
fusb300_clear_int(fusb300, FUSB300_OFFSET_IGR1,
FUSB300_IGR1_DEV_MODE_CHG_INT);
check_device_mode(fusb300);
}
if (int_grp1 & FUSB300_IGR1_CX_COMFAIL_INT) {
fusb300_set_cxstall(fusb300);
printk(KERN_INFO "fusb300_ep0fail\n");
}
if (int_grp1 & FUSB300_IGR1_CX_SETUP_INT) {
printk(KERN_INFO "fusb300_ep0setup\n");
if (setup_packet(fusb300, &ctrl)) {
spin_unlock(&fusb300->lock);
if (fusb300->driver->setup(&fusb300->gadget, &ctrl) < 0)
fusb300_set_cxstall(fusb300);
spin_lock(&fusb300->lock);
}
}
if (int_grp1 & FUSB300_IGR1_CX_CMDEND_INT)
printk(KERN_INFO "fusb300_cmdend\n");
if (int_grp1 & FUSB300_IGR1_CX_OUT_INT) {
printk(KERN_INFO "fusb300_cxout\n");
fusb300_ep0out(fusb300);
}
if (int_grp1 & FUSB300_IGR1_CX_IN_INT) {
printk(KERN_INFO "fusb300_cxin\n");
fusb300_ep0in(fusb300);
}
if (int_grp1 & FUSB300_IGR1_INTGRP5)
fusb300_grp5_handler();
if (int_grp1 & FUSB300_IGR1_INTGRP4)
fusb300_grp4_handler();
if (int_grp1 & FUSB300_IGR1_INTGRP3)
fusb300_grp3_handler();
if (int_grp1 & FUSB300_IGR1_INTGRP2)
fusb300_grp2_handler();
if (int_grp0) {
for (i = 1; i < FUSB300_MAX_NUM_EP; i++) {
if (int_grp0 & FUSB300_IGR0_EPn_FIFO_INT(i)) {
reg = ioread32(fusb300->reg +
FUSB300_OFFSET_EPSET1(i));
in = (reg & FUSB300_EPSET1_DIRIN) ? 1 : 0;
if (in)
in_ep_fifo_handler(fusb300->ep[i]);
else
out_ep_fifo_handler(fusb300->ep[i]);
}
}
}
spin_unlock(&fusb300->lock);
return IRQ_HANDLED;
}
static void fusb300_set_u2_timeout(struct fusb300 *fusb300,
u32 time)
{
u32 reg;
reg = ioread32(fusb300->reg + FUSB300_OFFSET_TT);
reg &= ~0xff;
reg |= FUSB300_SSCR2_U2TIMEOUT(time);
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_TT);
}
static void fusb300_set_u1_timeout(struct fusb300 *fusb300,
u32 time)
{
u32 reg;
reg = ioread32(fusb300->reg + FUSB300_OFFSET_TT);
reg &= ~(0xff << 8);
reg |= FUSB300_SSCR2_U1TIMEOUT(time);
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_TT);
}
static void init_controller(struct fusb300 *fusb300)
{
u32 reg;
u32 mask = 0;
u32 val = 0;
/* split on */
mask = val = FUSB300_AHBBCR_S0_SPLIT_ON | FUSB300_AHBBCR_S1_SPLIT_ON;
reg = ioread32(fusb300->reg + FUSB300_OFFSET_AHBCR);
reg &= ~mask;
reg |= val;
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_AHBCR);
/* enable high-speed LPM */
mask = val = FUSB300_HSCR_HS_LPM_PERMIT;
reg = ioread32(fusb300->reg + FUSB300_OFFSET_HSCR);
reg &= ~mask;
reg |= val;
iowrite32(reg, fusb300->reg + FUSB300_OFFSET_HSCR);
/*set u1 u2 timmer*/
fusb300_set_u2_timeout(fusb300, 0xff);
fusb300_set_u1_timeout(fusb300, 0xff);
/* enable all grp1 interrupt */
iowrite32(0xcfffff9f, fusb300->reg + FUSB300_OFFSET_IGER1);
}
/*------------------------------------------------------------------------*/
static struct fusb300 *the_controller;
int usb_gadget_probe_driver(struct usb_gadget_driver *driver,
int (*bind)(struct usb_gadget *))
{
struct fusb300 *fusb300 = the_controller;
int retval;
if (!driver
|| driver->speed < USB_SPEED_FULL
|| !bind
|| !driver->setup)
return -EINVAL;
if (!fusb300)
return -ENODEV;
if (fusb300->driver)
return -EBUSY;
/* hook up the driver */
driver->driver.bus = NULL;
fusb300->driver = driver;
fusb300->gadget.dev.driver = &driver->driver;
retval = device_add(&fusb300->gadget.dev);
if (retval) {
pr_err("device_add error (%d)\n", retval);
goto error;
}
retval = bind(&fusb300->gadget);
if (retval) {
pr_err("bind to driver error (%d)\n", retval);
device_del(&fusb300->gadget.dev);
goto error;
}
return 0;
error:
fusb300->driver = NULL;
fusb300->gadget.dev.driver = NULL;
return retval;
}
EXPORT_SYMBOL(usb_gadget_probe_driver);
int usb_gadget_unregister_driver(struct usb_gadget_driver *driver)
{
struct fusb300 *fusb300 = the_controller;
if (driver != fusb300->driver || !driver->unbind)
return -EINVAL;
driver->unbind(&fusb300->gadget);
fusb300->gadget.dev.driver = NULL;
init_controller(fusb300);
device_del(&fusb300->gadget.dev);
fusb300->driver = NULL;
return 0;
}
EXPORT_SYMBOL(usb_gadget_unregister_driver);
/*--------------------------------------------------------------------------*/
static int fusb300_udc_pullup(struct usb_gadget *_gadget, int is_active)
{
return 0;
}
static struct usb_gadget_ops fusb300_gadget_ops = {
.pullup = fusb300_udc_pullup,
};
static int __exit fusb300_remove(struct platform_device *pdev)
{
struct fusb300 *fusb300 = dev_get_drvdata(&pdev->dev);
iounmap(fusb300->reg);
free_irq(platform_get_irq(pdev, 0), fusb300);
fusb300_free_request(&fusb300->ep[0]->ep, fusb300->ep0_req);
kfree(fusb300);
return 0;
}
static int __init fusb300_probe(struct platform_device *pdev)
{
struct resource *res, *ires, *ires1;
void __iomem *reg = NULL;
struct fusb300 *fusb300 = NULL;
struct fusb300_ep *_ep[FUSB300_MAX_NUM_EP];
int ret = 0;
int i;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
ret = -ENODEV;
pr_err("platform_get_resource error.\n");
goto clean_up;
}
ires = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!ires) {
ret = -ENODEV;
dev_err(&pdev->dev,
"platform_get_resource IORESOURCE_IRQ error.\n");
goto clean_up;
}
ires1 = platform_get_resource(pdev, IORESOURCE_IRQ, 1);
if (!ires1) {
ret = -ENODEV;
dev_err(&pdev->dev,
"platform_get_resource IORESOURCE_IRQ 1 error.\n");
goto clean_up;
}
reg = ioremap(res->start, resource_size(res));
if (reg == NULL) {
ret = -ENOMEM;
pr_err("ioremap error.\n");
goto clean_up;
}
/* initialize udc */
fusb300 = kzalloc(sizeof(struct fusb300), GFP_KERNEL);
if (fusb300 == NULL) {
pr_err("kzalloc error\n");
goto clean_up;
}
for (i = 0; i < FUSB300_MAX_NUM_EP; i++) {
_ep[i] = kzalloc(sizeof(struct fusb300_ep), GFP_KERNEL);
if (_ep[i] == NULL) {
pr_err("_ep kzalloc error\n");
goto clean_up;
}
fusb300->ep[i] = _ep[i];
}
spin_lock_init(&fusb300->lock);
dev_set_drvdata(&pdev->dev, fusb300);
fusb300->gadget.ops = &fusb300_gadget_ops;
device_initialize(&fusb300->gadget.dev);
dev_set_name(&fusb300->gadget.dev, "gadget");
fusb300->gadget.is_dualspeed = 1;
fusb300->gadget.dev.parent = &pdev->dev;
fusb300->gadget.dev.dma_mask = pdev->dev.dma_mask;
fusb300->gadget.dev.release = pdev->dev.release;
fusb300->gadget.name = udc_name;
fusb300->reg = reg;
ret = request_irq(ires->start, fusb300_irq, IRQF_DISABLED | IRQF_SHARED,
udc_name, fusb300);
if (ret < 0) {
pr_err("request_irq error (%d)\n", ret);
goto clean_up;
}
ret = request_irq(ires1->start, fusb300_irq,
IRQF_DISABLED | IRQF_SHARED, udc_name, fusb300);
if (ret < 0) {
pr_err("request_irq1 error (%d)\n", ret);
goto clean_up;
}
INIT_LIST_HEAD(&fusb300->gadget.ep_list);
for (i = 0; i < FUSB300_MAX_NUM_EP ; i++) {
struct fusb300_ep *ep = fusb300->ep[i];
if (i != 0) {
INIT_LIST_HEAD(&fusb300->ep[i]->ep.ep_list);
list_add_tail(&fusb300->ep[i]->ep.ep_list,
&fusb300->gadget.ep_list);
}
ep->fusb300 = fusb300;
INIT_LIST_HEAD(&ep->queue);
ep->ep.name = fusb300_ep_name[i];
ep->ep.ops = &fusb300_ep_ops;
ep->ep.maxpacket = HS_BULK_MAX_PACKET_SIZE;
}
fusb300->ep[0]->ep.maxpacket = HS_CTL_MAX_PACKET_SIZE;
fusb300->ep[0]->epnum = 0;
fusb300->gadget.ep0 = &fusb300->ep[0]->ep;
INIT_LIST_HEAD(&fusb300->gadget.ep0->ep_list);
the_controller = fusb300;
fusb300->ep0_req = fusb300_alloc_request(&fusb300->ep[0]->ep,
GFP_KERNEL);
if (fusb300->ep0_req == NULL)
goto clean_up3;
init_controller(fusb300);
dev_info(&pdev->dev, "version %s\n", DRIVER_VERSION);
return 0;
clean_up3:
free_irq(ires->start, fusb300);
clean_up:
if (fusb300) {
if (fusb300->ep0_req)
fusb300_free_request(&fusb300->ep[0]->ep,
fusb300->ep0_req);
kfree(fusb300);
}
if (reg)
iounmap(reg);
return ret;
}
static struct platform_driver fusb300_driver = {
.remove = __exit_p(fusb300_remove),
.driver = {
.name = (char *) udc_name,
.owner = THIS_MODULE,
},
};
static int __init fusb300_udc_init(void)
{
return platform_driver_probe(&fusb300_driver, fusb300_probe);
}
module_init(fusb300_udc_init);
static void __exit fusb300_udc_cleanup(void)
{
platform_driver_unregister(&fusb300_driver);
}
module_exit(fusb300_udc_cleanup);
| gpl-2.0 |
storm31/android_kernel_samsung_aries | sound/soc/codecs/tpa6130a2.c | 2763 | 11814 | /*
* ALSA SoC Texas Instruments TPA6130A2 headset stereo amplifier driver
*
* Copyright (C) Nokia Corporation
*
* Author: Peter Ujfalusi <peter.ujfalusi@ti.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/device.h>
#include <linux/i2c.h>
#include <linux/gpio.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
#include <sound/tpa6130a2-plat.h>
#include <sound/soc.h>
#include <sound/tlv.h>
#include "tpa6130a2.h"
static struct i2c_client *tpa6130a2_client;
/* This struct is used to save the context */
struct tpa6130a2_data {
struct mutex mutex;
unsigned char regs[TPA6130A2_CACHEREGNUM];
struct regulator *supply;
int power_gpio;
u8 power_state:1;
enum tpa_model id;
};
static int tpa6130a2_i2c_read(int reg)
{
struct tpa6130a2_data *data;
int val;
BUG_ON(tpa6130a2_client == NULL);
data = i2c_get_clientdata(tpa6130a2_client);
/* If powered off, return the cached value */
if (data->power_state) {
val = i2c_smbus_read_byte_data(tpa6130a2_client, reg);
if (val < 0)
dev_err(&tpa6130a2_client->dev, "Read failed\n");
else
data->regs[reg] = val;
} else {
val = data->regs[reg];
}
return val;
}
static int tpa6130a2_i2c_write(int reg, u8 value)
{
struct tpa6130a2_data *data;
int val = 0;
BUG_ON(tpa6130a2_client == NULL);
data = i2c_get_clientdata(tpa6130a2_client);
if (data->power_state) {
val = i2c_smbus_write_byte_data(tpa6130a2_client, reg, value);
if (val < 0) {
dev_err(&tpa6130a2_client->dev, "Write failed\n");
return val;
}
}
/* Either powered on or off, we save the context */
data->regs[reg] = value;
return val;
}
static u8 tpa6130a2_read(int reg)
{
struct tpa6130a2_data *data;
BUG_ON(tpa6130a2_client == NULL);
data = i2c_get_clientdata(tpa6130a2_client);
return data->regs[reg];
}
static int tpa6130a2_initialize(void)
{
struct tpa6130a2_data *data;
int i, ret = 0;
BUG_ON(tpa6130a2_client == NULL);
data = i2c_get_clientdata(tpa6130a2_client);
for (i = 1; i < TPA6130A2_REG_VERSION; i++) {
ret = tpa6130a2_i2c_write(i, data->regs[i]);
if (ret < 0)
break;
}
return ret;
}
static int tpa6130a2_power(u8 power)
{
struct tpa6130a2_data *data;
u8 val;
int ret = 0;
BUG_ON(tpa6130a2_client == NULL);
data = i2c_get_clientdata(tpa6130a2_client);
mutex_lock(&data->mutex);
if (power == data->power_state)
goto exit;
if (power) {
ret = regulator_enable(data->supply);
if (ret != 0) {
dev_err(&tpa6130a2_client->dev,
"Failed to enable supply: %d\n", ret);
goto exit;
}
/* Power on */
if (data->power_gpio >= 0)
gpio_set_value(data->power_gpio, 1);
data->power_state = 1;
ret = tpa6130a2_initialize();
if (ret < 0) {
dev_err(&tpa6130a2_client->dev,
"Failed to initialize chip\n");
if (data->power_gpio >= 0)
gpio_set_value(data->power_gpio, 0);
regulator_disable(data->supply);
data->power_state = 0;
goto exit;
}
} else {
/* set SWS */
val = tpa6130a2_read(TPA6130A2_REG_CONTROL);
val |= TPA6130A2_SWS;
tpa6130a2_i2c_write(TPA6130A2_REG_CONTROL, val);
/* Power off */
if (data->power_gpio >= 0)
gpio_set_value(data->power_gpio, 0);
ret = regulator_disable(data->supply);
if (ret != 0) {
dev_err(&tpa6130a2_client->dev,
"Failed to disable supply: %d\n", ret);
goto exit;
}
data->power_state = 0;
}
exit:
mutex_unlock(&data->mutex);
return ret;
}
static int tpa6130a2_get_volsw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct soc_mixer_control *mc =
(struct soc_mixer_control *)kcontrol->private_value;
struct tpa6130a2_data *data;
unsigned int reg = mc->reg;
unsigned int shift = mc->shift;
int max = mc->max;
unsigned int mask = (1 << fls(max)) - 1;
unsigned int invert = mc->invert;
BUG_ON(tpa6130a2_client == NULL);
data = i2c_get_clientdata(tpa6130a2_client);
mutex_lock(&data->mutex);
ucontrol->value.integer.value[0] =
(tpa6130a2_read(reg) >> shift) & mask;
if (invert)
ucontrol->value.integer.value[0] =
max - ucontrol->value.integer.value[0];
mutex_unlock(&data->mutex);
return 0;
}
static int tpa6130a2_put_volsw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct soc_mixer_control *mc =
(struct soc_mixer_control *)kcontrol->private_value;
struct tpa6130a2_data *data;
unsigned int reg = mc->reg;
unsigned int shift = mc->shift;
int max = mc->max;
unsigned int mask = (1 << fls(max)) - 1;
unsigned int invert = mc->invert;
unsigned int val = (ucontrol->value.integer.value[0] & mask);
unsigned int val_reg;
BUG_ON(tpa6130a2_client == NULL);
data = i2c_get_clientdata(tpa6130a2_client);
if (invert)
val = max - val;
mutex_lock(&data->mutex);
val_reg = tpa6130a2_read(reg);
if (((val_reg >> shift) & mask) == val) {
mutex_unlock(&data->mutex);
return 0;
}
val_reg &= ~(mask << shift);
val_reg |= val << shift;
tpa6130a2_i2c_write(reg, val_reg);
mutex_unlock(&data->mutex);
return 1;
}
/*
* TPA6130 volume. From -59.5 to 4 dB with increasing step size when going
* down in gain.
*/
static const unsigned int tpa6130_tlv[] = {
TLV_DB_RANGE_HEAD(10),
0, 1, TLV_DB_SCALE_ITEM(-5950, 600, 0),
2, 3, TLV_DB_SCALE_ITEM(-5000, 250, 0),
4, 5, TLV_DB_SCALE_ITEM(-4550, 160, 0),
6, 7, TLV_DB_SCALE_ITEM(-4140, 190, 0),
8, 9, TLV_DB_SCALE_ITEM(-3650, 120, 0),
10, 11, TLV_DB_SCALE_ITEM(-3330, 160, 0),
12, 13, TLV_DB_SCALE_ITEM(-3040, 180, 0),
14, 20, TLV_DB_SCALE_ITEM(-2710, 110, 0),
21, 37, TLV_DB_SCALE_ITEM(-1960, 74, 0),
38, 63, TLV_DB_SCALE_ITEM(-720, 45, 0),
};
static const struct snd_kcontrol_new tpa6130a2_controls[] = {
SOC_SINGLE_EXT_TLV("TPA6130A2 Headphone Playback Volume",
TPA6130A2_REG_VOL_MUTE, 0, 0x3f, 0,
tpa6130a2_get_volsw, tpa6130a2_put_volsw,
tpa6130_tlv),
};
static const unsigned int tpa6140_tlv[] = {
TLV_DB_RANGE_HEAD(3),
0, 8, TLV_DB_SCALE_ITEM(-5900, 400, 0),
9, 16, TLV_DB_SCALE_ITEM(-2500, 200, 0),
17, 31, TLV_DB_SCALE_ITEM(-1000, 100, 0),
};
static const struct snd_kcontrol_new tpa6140a2_controls[] = {
SOC_SINGLE_EXT_TLV("TPA6140A2 Headphone Playback Volume",
TPA6130A2_REG_VOL_MUTE, 1, 0x1f, 0,
tpa6130a2_get_volsw, tpa6130a2_put_volsw,
tpa6140_tlv),
};
/*
* Enable or disable channel (left or right)
* The bit number for mute and amplifier are the same per channel:
* bit 6: Right channel
* bit 7: Left channel
* in both registers.
*/
static void tpa6130a2_channel_enable(u8 channel, int enable)
{
u8 val;
if (enable) {
/* Enable channel */
/* Enable amplifier */
val = tpa6130a2_read(TPA6130A2_REG_CONTROL);
val |= channel;
val &= ~TPA6130A2_SWS;
tpa6130a2_i2c_write(TPA6130A2_REG_CONTROL, val);
/* Unmute channel */
val = tpa6130a2_read(TPA6130A2_REG_VOL_MUTE);
val &= ~channel;
tpa6130a2_i2c_write(TPA6130A2_REG_VOL_MUTE, val);
} else {
/* Disable channel */
/* Mute channel */
val = tpa6130a2_read(TPA6130A2_REG_VOL_MUTE);
val |= channel;
tpa6130a2_i2c_write(TPA6130A2_REG_VOL_MUTE, val);
/* Disable amplifier */
val = tpa6130a2_read(TPA6130A2_REG_CONTROL);
val &= ~channel;
tpa6130a2_i2c_write(TPA6130A2_REG_CONTROL, val);
}
}
int tpa6130a2_stereo_enable(struct snd_soc_codec *codec, int enable)
{
int ret = 0;
if (enable) {
ret = tpa6130a2_power(1);
if (ret < 0)
return ret;
tpa6130a2_channel_enable(TPA6130A2_HP_EN_R | TPA6130A2_HP_EN_L,
1);
} else {
tpa6130a2_channel_enable(TPA6130A2_HP_EN_R | TPA6130A2_HP_EN_L,
0);
ret = tpa6130a2_power(0);
}
return ret;
}
EXPORT_SYMBOL_GPL(tpa6130a2_stereo_enable);
int tpa6130a2_add_controls(struct snd_soc_codec *codec)
{
struct tpa6130a2_data *data;
if (tpa6130a2_client == NULL)
return -ENODEV;
data = i2c_get_clientdata(tpa6130a2_client);
if (data->id == TPA6140A2)
return snd_soc_add_controls(codec, tpa6140a2_controls,
ARRAY_SIZE(tpa6140a2_controls));
else
return snd_soc_add_controls(codec, tpa6130a2_controls,
ARRAY_SIZE(tpa6130a2_controls));
}
EXPORT_SYMBOL_GPL(tpa6130a2_add_controls);
static int __devinit tpa6130a2_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct device *dev;
struct tpa6130a2_data *data;
struct tpa6130a2_platform_data *pdata;
const char *regulator;
int ret;
dev = &client->dev;
if (client->dev.platform_data == NULL) {
dev_err(dev, "Platform data not set\n");
dump_stack();
return -ENODEV;
}
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (data == NULL) {
dev_err(dev, "Can not allocate memory\n");
return -ENOMEM;
}
tpa6130a2_client = client;
i2c_set_clientdata(tpa6130a2_client, data);
pdata = client->dev.platform_data;
data->power_gpio = pdata->power_gpio;
data->id = pdata->id;
mutex_init(&data->mutex);
/* Set default register values */
data->regs[TPA6130A2_REG_CONTROL] = TPA6130A2_SWS;
data->regs[TPA6130A2_REG_VOL_MUTE] = TPA6130A2_MUTE_R |
TPA6130A2_MUTE_L;
if (data->power_gpio >= 0) {
ret = gpio_request(data->power_gpio, "tpa6130a2 enable");
if (ret < 0) {
dev_err(dev, "Failed to request power GPIO (%d)\n",
data->power_gpio);
goto err_gpio;
}
gpio_direction_output(data->power_gpio, 0);
}
switch (data->id) {
default:
dev_warn(dev, "Unknown TPA model (%d). Assuming 6130A2\n",
pdata->id);
case TPA6130A2:
regulator = "Vdd";
break;
case TPA6140A2:
regulator = "AVdd";
break;
}
data->supply = regulator_get(dev, regulator);
if (IS_ERR(data->supply)) {
ret = PTR_ERR(data->supply);
dev_err(dev, "Failed to request supply: %d\n", ret);
goto err_regulator;
}
ret = tpa6130a2_power(1);
if (ret != 0)
goto err_power;
/* Read version */
ret = tpa6130a2_i2c_read(TPA6130A2_REG_VERSION) &
TPA6130A2_VERSION_MASK;
if ((ret != 1) && (ret != 2))
dev_warn(dev, "UNTESTED version detected (%d)\n", ret);
/* Disable the chip */
ret = tpa6130a2_power(0);
if (ret != 0)
goto err_power;
return 0;
err_power:
regulator_put(data->supply);
err_regulator:
if (data->power_gpio >= 0)
gpio_free(data->power_gpio);
err_gpio:
kfree(data);
i2c_set_clientdata(tpa6130a2_client, NULL);
tpa6130a2_client = NULL;
return ret;
}
static int __devexit tpa6130a2_remove(struct i2c_client *client)
{
struct tpa6130a2_data *data = i2c_get_clientdata(client);
tpa6130a2_power(0);
if (data->power_gpio >= 0)
gpio_free(data->power_gpio);
regulator_put(data->supply);
kfree(data);
tpa6130a2_client = NULL;
return 0;
}
static const struct i2c_device_id tpa6130a2_id[] = {
{ "tpa6130a2", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, tpa6130a2_id);
static struct i2c_driver tpa6130a2_i2c_driver = {
.driver = {
.name = "tpa6130a2",
.owner = THIS_MODULE,
},
.probe = tpa6130a2_probe,
.remove = __devexit_p(tpa6130a2_remove),
.id_table = tpa6130a2_id,
};
static int __init tpa6130a2_init(void)
{
return i2c_add_driver(&tpa6130a2_i2c_driver);
}
static void __exit tpa6130a2_exit(void)
{
i2c_del_driver(&tpa6130a2_i2c_driver);
}
MODULE_AUTHOR("Peter Ujfalusi <peter.ujfalusi@ti.com>");
MODULE_DESCRIPTION("TPA6130A2 Headphone amplifier driver");
MODULE_LICENSE("GPL");
module_init(tpa6130a2_init);
module_exit(tpa6130a2_exit);
| gpl-2.0 |
dschensen/android_kernel_samsung_smdk4412 | drivers/net/tulip/eeprom.c | 2763 | 12698 | /*
drivers/net/tulip/eeprom.c
Copyright 2000,2001 The Linux Kernel Team
Written/copyright 1994-2001 by Donald Becker.
This software may be used and distributed according to the terms
of the GNU General Public License, incorporated herein by reference.
Please refer to Documentation/DocBook/tulip-user.{pdf,ps,html}
for more information on this driver.
Please submit bug reports to http://bugzilla.kernel.org/.
*/
#include <linux/pci.h>
#include <linux/slab.h>
#include "tulip.h"
#include <linux/init.h>
#include <asm/unaligned.h>
/* Serial EEPROM section. */
/* The main routine to parse the very complicated SROM structure.
Search www.digital.com for "21X4 SROM" to get details.
This code is very complex, and will require changes to support
additional cards, so I'll be verbose about what is going on.
*/
/* Known cards that have old-style EEPROMs. */
static struct eeprom_fixup eeprom_fixups[] __devinitdata = {
{"Asante", 0, 0, 0x94, {0x1e00, 0x0000, 0x0800, 0x0100, 0x018c,
0x0000, 0x0000, 0xe078, 0x0001, 0x0050, 0x0018 }},
{"SMC9332DST", 0, 0, 0xC0, { 0x1e00, 0x0000, 0x0800, 0x041f,
0x0000, 0x009E, /* 10baseT */
0x0004, 0x009E, /* 10baseT-FD */
0x0903, 0x006D, /* 100baseTx */
0x0905, 0x006D, /* 100baseTx-FD */ }},
{"Cogent EM100", 0, 0, 0x92, { 0x1e00, 0x0000, 0x0800, 0x063f,
0x0107, 0x8021, /* 100baseFx */
0x0108, 0x8021, /* 100baseFx-FD */
0x0100, 0x009E, /* 10baseT */
0x0104, 0x009E, /* 10baseT-FD */
0x0103, 0x006D, /* 100baseTx */
0x0105, 0x006D, /* 100baseTx-FD */ }},
{"Maxtech NX-110", 0, 0, 0xE8, { 0x1e00, 0x0000, 0x0800, 0x0513,
0x1001, 0x009E, /* 10base2, CSR12 0x10*/
0x0000, 0x009E, /* 10baseT */
0x0004, 0x009E, /* 10baseT-FD */
0x0303, 0x006D, /* 100baseTx, CSR12 0x03 */
0x0305, 0x006D, /* 100baseTx-FD CSR12 0x03 */}},
{"Accton EN1207", 0, 0, 0xE8, { 0x1e00, 0x0000, 0x0800, 0x051F,
0x1B01, 0x0000, /* 10base2, CSR12 0x1B */
0x0B00, 0x009E, /* 10baseT, CSR12 0x0B */
0x0B04, 0x009E, /* 10baseT-FD,CSR12 0x0B */
0x1B03, 0x006D, /* 100baseTx, CSR12 0x1B */
0x1B05, 0x006D, /* 100baseTx-FD CSR12 0x1B */
}},
{"NetWinder", 0x00, 0x10, 0x57,
/* Default media = MII
* MII block, reset sequence (3) = 0x0821 0x0000 0x0001, capabilities 0x01e1
*/
{ 0x1e00, 0x0000, 0x000b, 0x8f01, 0x0103, 0x0300, 0x0821, 0x000, 0x0001, 0x0000, 0x01e1 }
},
{"Cobalt Microserver", 0, 0x10, 0xE0, {0x1e00, /* 0 == controller #, 1e == offset */
0x0000, /* 0 == high offset, 0 == gap */
0x0800, /* Default Autoselect */
0x8001, /* 1 leaf, extended type, bogus len */
0x0003, /* Type 3 (MII), PHY #0 */
0x0400, /* 0 init instr, 4 reset instr */
0x0801, /* Set control mode, GP0 output */
0x0000, /* Drive GP0 Low (RST is active low) */
0x0800, /* control mode, GP0 input (undriven) */
0x0000, /* clear control mode */
0x7800, /* 100TX FDX + HDX, 10bT FDX + HDX */
0x01e0, /* Advertise all above */
0x5000, /* FDX all above */
0x1800, /* Set fast TTM in 100bt modes */
0x0000, /* PHY cannot be unplugged */
}},
{NULL}};
static const char *block_name[] __devinitdata = {
"21140 non-MII",
"21140 MII PHY",
"21142 Serial PHY",
"21142 MII PHY",
"21143 SYM PHY",
"21143 reset method"
};
/**
* tulip_build_fake_mediatable - Build a fake mediatable entry.
* @tp: Ptr to the tulip private data.
*
* Some cards like the 3x5 HSC cards (J3514A) do not have a standard
* srom and can not be handled under the fixup routine. These cards
* still need a valid mediatable entry for correct csr12 setup and
* mii handling.
*
* Since this is currently a parisc-linux specific function, the
* #ifdef __hppa__ should completely optimize this function away for
* non-parisc hardware.
*/
static void __devinit tulip_build_fake_mediatable(struct tulip_private *tp)
{
#ifdef CONFIG_GSC
if (tp->flags & NEEDS_FAKE_MEDIA_TABLE) {
static unsigned char leafdata[] =
{ 0x01, /* phy number */
0x02, /* gpr setup sequence length */
0x02, 0x00, /* gpr setup sequence */
0x02, /* phy reset sequence length */
0x01, 0x00, /* phy reset sequence */
0x00, 0x78, /* media capabilities */
0x00, 0xe0, /* nway advertisement */
0x00, 0x05, /* fdx bit map */
0x00, 0x06 /* ttm bit map */
};
tp->mtable = kmalloc(sizeof(struct mediatable) +
sizeof(struct medialeaf), GFP_KERNEL);
if (tp->mtable == NULL)
return; /* Horrible, impossible failure. */
tp->mtable->defaultmedia = 0x800;
tp->mtable->leafcount = 1;
tp->mtable->csr12dir = 0x3f; /* inputs on bit7 for hsc-pci, bit6 for pci-fx */
tp->mtable->has_nonmii = 0;
tp->mtable->has_reset = 0;
tp->mtable->has_mii = 1;
tp->mtable->csr15dir = tp->mtable->csr15val = 0;
tp->mtable->mleaf[0].type = 1;
tp->mtable->mleaf[0].media = 11;
tp->mtable->mleaf[0].leafdata = &leafdata[0];
tp->flags |= HAS_PHY_IRQ;
tp->csr12_shadow = -1;
}
#endif
}
void __devinit tulip_parse_eeprom(struct net_device *dev)
{
/*
dev is not registered at this point, so logging messages can't
use dev_<level> or netdev_<level> but dev->name is good via a
hack in the caller
*/
/* The last media info list parsed, for multiport boards. */
static struct mediatable *last_mediatable;
static unsigned char *last_ee_data;
static int controller_index;
struct tulip_private *tp = netdev_priv(dev);
unsigned char *ee_data = tp->eeprom;
int i;
tp->mtable = NULL;
/* Detect an old-style (SA only) EEPROM layout:
memcmp(eedata, eedata+16, 8). */
for (i = 0; i < 8; i ++)
if (ee_data[i] != ee_data[16+i])
break;
if (i >= 8) {
if (ee_data[0] == 0xff) {
if (last_mediatable) {
controller_index++;
pr_info("%s: Controller %d of multiport board\n",
dev->name, controller_index);
tp->mtable = last_mediatable;
ee_data = last_ee_data;
goto subsequent_board;
} else
pr_info("%s: Missing EEPROM, this interface may not work correctly!\n",
dev->name);
return;
}
/* Do a fix-up based on the vendor half of the station address prefix. */
for (i = 0; eeprom_fixups[i].name; i++) {
if (dev->dev_addr[0] == eeprom_fixups[i].addr0 &&
dev->dev_addr[1] == eeprom_fixups[i].addr1 &&
dev->dev_addr[2] == eeprom_fixups[i].addr2) {
if (dev->dev_addr[2] == 0xE8 && ee_data[0x1a] == 0x55)
i++; /* An Accton EN1207, not an outlaw Maxtech. */
memcpy(ee_data + 26, eeprom_fixups[i].newtable,
sizeof(eeprom_fixups[i].newtable));
pr_info("%s: Old format EEPROM on '%s' board. Using substitute media control info\n",
dev->name, eeprom_fixups[i].name);
break;
}
}
if (eeprom_fixups[i].name == NULL) { /* No fixup found. */
pr_info("%s: Old style EEPROM with no media selection information\n",
dev->name);
return;
}
}
controller_index = 0;
if (ee_data[19] > 1) { /* Multiport board. */
last_ee_data = ee_data;
}
subsequent_board:
if (ee_data[27] == 0) { /* No valid media table. */
tulip_build_fake_mediatable(tp);
} else {
unsigned char *p = (void *)ee_data + ee_data[27];
unsigned char csr12dir = 0;
int count, new_advertise = 0;
struct mediatable *mtable;
u16 media = get_u16(p);
p += 2;
if (tp->flags & CSR12_IN_SROM)
csr12dir = *p++;
count = *p++;
/* there is no phy information, don't even try to build mtable */
if (count == 0) {
if (tulip_debug > 0)
pr_warn("%s: no phy info, aborting mtable build\n",
dev->name);
return;
}
mtable = kmalloc(sizeof(struct mediatable) +
count * sizeof(struct medialeaf),
GFP_KERNEL);
if (mtable == NULL)
return; /* Horrible, impossible failure. */
last_mediatable = tp->mtable = mtable;
mtable->defaultmedia = media;
mtable->leafcount = count;
mtable->csr12dir = csr12dir;
mtable->has_nonmii = mtable->has_mii = mtable->has_reset = 0;
mtable->csr15dir = mtable->csr15val = 0;
pr_info("%s: EEPROM default media type %s\n",
dev->name,
media & 0x0800 ? "Autosense"
: medianame[media & MEDIA_MASK]);
for (i = 0; i < count; i++) {
struct medialeaf *leaf = &mtable->mleaf[i];
if ((p[0] & 0x80) == 0) { /* 21140 Compact block. */
leaf->type = 0;
leaf->media = p[0] & 0x3f;
leaf->leafdata = p;
if ((p[2] & 0x61) == 0x01) /* Bogus, but Znyx boards do it. */
mtable->has_mii = 1;
p += 4;
} else {
leaf->type = p[1];
if (p[1] == 0x05) {
mtable->has_reset = i;
leaf->media = p[2] & 0x0f;
} else if (tp->chip_id == DM910X && p[1] == 0x80) {
/* Hack to ignore Davicom delay period block */
mtable->leafcount--;
count--;
i--;
leaf->leafdata = p + 2;
p += (p[0] & 0x3f) + 1;
continue;
} else if (p[1] & 1) {
int gpr_len, reset_len;
mtable->has_mii = 1;
leaf->media = 11;
gpr_len=p[3]*2;
reset_len=p[4+gpr_len]*2;
new_advertise |= get_u16(&p[7+gpr_len+reset_len]);
} else {
mtable->has_nonmii = 1;
leaf->media = p[2] & MEDIA_MASK;
/* Davicom's media number for 100BaseTX is strange */
if (tp->chip_id == DM910X && leaf->media == 1)
leaf->media = 3;
switch (leaf->media) {
case 0: new_advertise |= 0x0020; break;
case 4: new_advertise |= 0x0040; break;
case 3: new_advertise |= 0x0080; break;
case 5: new_advertise |= 0x0100; break;
case 6: new_advertise |= 0x0200; break;
}
if (p[1] == 2 && leaf->media == 0) {
if (p[2] & 0x40) {
u32 base15 = get_unaligned((u16*)&p[7]);
mtable->csr15dir =
(get_unaligned((u16*)&p[9])<<16) + base15;
mtable->csr15val =
(get_unaligned((u16*)&p[11])<<16) + base15;
} else {
mtable->csr15dir = get_unaligned((u16*)&p[3])<<16;
mtable->csr15val = get_unaligned((u16*)&p[5])<<16;
}
}
}
leaf->leafdata = p + 2;
p += (p[0] & 0x3f) + 1;
}
if (tulip_debug > 1 && leaf->media == 11) {
unsigned char *bp = leaf->leafdata;
pr_info("%s: MII interface PHY %d, setup/reset sequences %d/%d long, capabilities %02x %02x\n",
dev->name,
bp[0], bp[1], bp[2 + bp[1]*2],
bp[5 + bp[2 + bp[1]*2]*2],
bp[4 + bp[2 + bp[1]*2]*2]);
}
pr_info("%s: Index #%d - Media %s (#%d) described by a %s (%d) block\n",
dev->name,
i, medianame[leaf->media & 15], leaf->media,
leaf->type < ARRAY_SIZE(block_name) ? block_name[leaf->type] : "<unknown>",
leaf->type);
}
if (new_advertise)
tp->sym_advertise = new_advertise;
}
}
/* Reading a serial EEPROM is a "bit" grungy, but we work our way through:->.*/
/* EEPROM_Ctrl bits. */
#define EE_SHIFT_CLK 0x02 /* EEPROM shift clock. */
#define EE_CS 0x01 /* EEPROM chip select. */
#define EE_DATA_WRITE 0x04 /* Data from the Tulip to EEPROM. */
#define EE_WRITE_0 0x01
#define EE_WRITE_1 0x05
#define EE_DATA_READ 0x08 /* Data from the EEPROM chip. */
#define EE_ENB (0x4800 | EE_CS)
/* Delay between EEPROM clock transitions.
Even at 33Mhz current PCI implementations don't overrun the EEPROM clock.
We add a bus turn-around to insure that this remains true. */
#define eeprom_delay() ioread32(ee_addr)
/* The EEPROM commands include the alway-set leading bit. */
#define EE_READ_CMD (6)
/* Note: this routine returns extra data bits for size detection. */
int __devinit tulip_read_eeprom(struct net_device *dev, int location, int addr_len)
{
int i;
unsigned retval = 0;
struct tulip_private *tp = netdev_priv(dev);
void __iomem *ee_addr = tp->base_addr + CSR9;
int read_cmd = location | (EE_READ_CMD << addr_len);
/* If location is past the end of what we can address, don't
* read some other location (ie truncate). Just return zero.
*/
if (location > (1 << addr_len) - 1)
return 0;
iowrite32(EE_ENB & ~EE_CS, ee_addr);
iowrite32(EE_ENB, ee_addr);
/* Shift the read command bits out. */
for (i = 4 + addr_len; i >= 0; i--) {
short dataval = (read_cmd & (1 << i)) ? EE_DATA_WRITE : 0;
iowrite32(EE_ENB | dataval, ee_addr);
eeprom_delay();
iowrite32(EE_ENB | dataval | EE_SHIFT_CLK, ee_addr);
eeprom_delay();
retval = (retval << 1) | ((ioread32(ee_addr) & EE_DATA_READ) ? 1 : 0);
}
iowrite32(EE_ENB, ee_addr);
eeprom_delay();
for (i = 16; i > 0; i--) {
iowrite32(EE_ENB | EE_SHIFT_CLK, ee_addr);
eeprom_delay();
retval = (retval << 1) | ((ioread32(ee_addr) & EE_DATA_READ) ? 1 : 0);
iowrite32(EE_ENB, ee_addr);
eeprom_delay();
}
/* Terminate the EEPROM access. */
iowrite32(EE_ENB & ~EE_CS, ee_addr);
return (tp->flags & HAS_SWAPPED_SEEPROM) ? swab16(retval) : retval;
}
| gpl-2.0 |
AOKP/kernel_samsung_jf | drivers/rapidio/devices/tsi721.c | 3275 | 67377 | /*
* RapidIO mport driver for Tsi721 PCIExpress-to-SRIO bridge
*
* Copyright 2011 Integrated Device Technology, Inc.
* Alexandre Bounine <alexandre.bounine@idt.com>
* Chul Kim <chul.kim@idt.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/io.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/rio.h>
#include <linux/rio_drv.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <linux/kfifo.h>
#include <linux/delay.h>
#include "tsi721.h"
#define DEBUG_PW /* Inbound Port-Write debugging */
static void tsi721_omsg_handler(struct tsi721_device *priv, int ch);
static void tsi721_imsg_handler(struct tsi721_device *priv, int ch);
/**
* tsi721_lcread - read from local SREP config space
* @mport: RapidIO master port info
* @index: ID of RapdiIO interface
* @offset: Offset into configuration space
* @len: Length (in bytes) of the maintenance transaction
* @data: Value to be read into
*
* Generates a local SREP space read. Returns %0 on
* success or %-EINVAL on failure.
*/
static int tsi721_lcread(struct rio_mport *mport, int index, u32 offset,
int len, u32 *data)
{
struct tsi721_device *priv = mport->priv;
if (len != sizeof(u32))
return -EINVAL; /* only 32-bit access is supported */
*data = ioread32(priv->regs + offset);
return 0;
}
/**
* tsi721_lcwrite - write into local SREP config space
* @mport: RapidIO master port info
* @index: ID of RapdiIO interface
* @offset: Offset into configuration space
* @len: Length (in bytes) of the maintenance transaction
* @data: Value to be written
*
* Generates a local write into SREP configuration space. Returns %0 on
* success or %-EINVAL on failure.
*/
static int tsi721_lcwrite(struct rio_mport *mport, int index, u32 offset,
int len, u32 data)
{
struct tsi721_device *priv = mport->priv;
if (len != sizeof(u32))
return -EINVAL; /* only 32-bit access is supported */
iowrite32(data, priv->regs + offset);
return 0;
}
/**
* tsi721_maint_dma - Helper function to generate RapidIO maintenance
* transactions using designated Tsi721 DMA channel.
* @priv: pointer to tsi721 private data
* @sys_size: RapdiIO transport system size
* @destid: Destination ID of transaction
* @hopcount: Number of hops to target device
* @offset: Offset into configuration space
* @len: Length (in bytes) of the maintenance transaction
* @data: Location to be read from or write into
* @do_wr: Operation flag (1 == MAINT_WR)
*
* Generates a RapidIO maintenance transaction (Read or Write).
* Returns %0 on success and %-EINVAL or %-EFAULT on failure.
*/
static int tsi721_maint_dma(struct tsi721_device *priv, u32 sys_size,
u16 destid, u8 hopcount, u32 offset, int len,
u32 *data, int do_wr)
{
struct tsi721_dma_desc *bd_ptr;
u32 rd_count, swr_ptr, ch_stat;
int i, err = 0;
u32 op = do_wr ? MAINT_WR : MAINT_RD;
if (offset > (RIO_MAINT_SPACE_SZ - len) || (len != sizeof(u32)))
return -EINVAL;
bd_ptr = priv->bdma[TSI721_DMACH_MAINT].bd_base;
rd_count = ioread32(
priv->regs + TSI721_DMAC_DRDCNT(TSI721_DMACH_MAINT));
/* Initialize DMA descriptor */
bd_ptr[0].type_id = cpu_to_le32((DTYPE2 << 29) | (op << 19) | destid);
bd_ptr[0].bcount = cpu_to_le32((sys_size << 26) | 0x04);
bd_ptr[0].raddr_lo = cpu_to_le32((hopcount << 24) | offset);
bd_ptr[0].raddr_hi = 0;
if (do_wr)
bd_ptr[0].data[0] = cpu_to_be32p(data);
else
bd_ptr[0].data[0] = 0xffffffff;
mb();
/* Start DMA operation */
iowrite32(rd_count + 2,
priv->regs + TSI721_DMAC_DWRCNT(TSI721_DMACH_MAINT));
ioread32(priv->regs + TSI721_DMAC_DWRCNT(TSI721_DMACH_MAINT));
i = 0;
/* Wait until DMA transfer is finished */
while ((ch_stat = ioread32(priv->regs +
TSI721_DMAC_STS(TSI721_DMACH_MAINT))) & TSI721_DMAC_STS_RUN) {
udelay(1);
if (++i >= 5000000) {
dev_dbg(&priv->pdev->dev,
"%s : DMA[%d] read timeout ch_status=%x\n",
__func__, TSI721_DMACH_MAINT, ch_stat);
if (!do_wr)
*data = 0xffffffff;
err = -EIO;
goto err_out;
}
}
if (ch_stat & TSI721_DMAC_STS_ABORT) {
/* If DMA operation aborted due to error,
* reinitialize DMA channel
*/
dev_dbg(&priv->pdev->dev, "%s : DMA ABORT ch_stat=%x\n",
__func__, ch_stat);
dev_dbg(&priv->pdev->dev, "OP=%d : destid=%x hc=%x off=%x\n",
do_wr ? MAINT_WR : MAINT_RD, destid, hopcount, offset);
iowrite32(TSI721_DMAC_INT_ALL,
priv->regs + TSI721_DMAC_INT(TSI721_DMACH_MAINT));
iowrite32(TSI721_DMAC_CTL_INIT,
priv->regs + TSI721_DMAC_CTL(TSI721_DMACH_MAINT));
udelay(10);
iowrite32(0, priv->regs +
TSI721_DMAC_DWRCNT(TSI721_DMACH_MAINT));
udelay(1);
if (!do_wr)
*data = 0xffffffff;
err = -EIO;
goto err_out;
}
if (!do_wr)
*data = be32_to_cpu(bd_ptr[0].data[0]);
/*
* Update descriptor status FIFO RD pointer.
* NOTE: Skipping check and clear FIFO entries because we are waiting
* for transfer to be completed.
*/
swr_ptr = ioread32(priv->regs + TSI721_DMAC_DSWP(TSI721_DMACH_MAINT));
iowrite32(swr_ptr, priv->regs + TSI721_DMAC_DSRP(TSI721_DMACH_MAINT));
err_out:
return err;
}
/**
* tsi721_cread_dma - Generate a RapidIO maintenance read transaction
* using Tsi721 BDMA engine.
* @mport: RapidIO master port control structure
* @index: ID of RapdiIO interface
* @destid: Destination ID of transaction
* @hopcount: Number of hops to target device
* @offset: Offset into configuration space
* @len: Length (in bytes) of the maintenance transaction
* @val: Location to be read into
*
* Generates a RapidIO maintenance read transaction.
* Returns %0 on success and %-EINVAL or %-EFAULT on failure.
*/
static int tsi721_cread_dma(struct rio_mport *mport, int index, u16 destid,
u8 hopcount, u32 offset, int len, u32 *data)
{
struct tsi721_device *priv = mport->priv;
return tsi721_maint_dma(priv, mport->sys_size, destid, hopcount,
offset, len, data, 0);
}
/**
* tsi721_cwrite_dma - Generate a RapidIO maintenance write transaction
* using Tsi721 BDMA engine
* @mport: RapidIO master port control structure
* @index: ID of RapdiIO interface
* @destid: Destination ID of transaction
* @hopcount: Number of hops to target device
* @offset: Offset into configuration space
* @len: Length (in bytes) of the maintenance transaction
* @val: Value to be written
*
* Generates a RapidIO maintenance write transaction.
* Returns %0 on success and %-EINVAL or %-EFAULT on failure.
*/
static int tsi721_cwrite_dma(struct rio_mport *mport, int index, u16 destid,
u8 hopcount, u32 offset, int len, u32 data)
{
struct tsi721_device *priv = mport->priv;
u32 temp = data;
return tsi721_maint_dma(priv, mport->sys_size, destid, hopcount,
offset, len, &temp, 1);
}
/**
* tsi721_pw_handler - Tsi721 inbound port-write interrupt handler
* @mport: RapidIO master port structure
*
* Handles inbound port-write interrupts. Copies PW message from an internal
* buffer into PW message FIFO and schedules deferred routine to process
* queued messages.
*/
static int
tsi721_pw_handler(struct rio_mport *mport)
{
struct tsi721_device *priv = mport->priv;
u32 pw_stat;
u32 pw_buf[TSI721_RIO_PW_MSG_SIZE/sizeof(u32)];
pw_stat = ioread32(priv->regs + TSI721_RIO_PW_RX_STAT);
if (pw_stat & TSI721_RIO_PW_RX_STAT_PW_VAL) {
pw_buf[0] = ioread32(priv->regs + TSI721_RIO_PW_RX_CAPT(0));
pw_buf[1] = ioread32(priv->regs + TSI721_RIO_PW_RX_CAPT(1));
pw_buf[2] = ioread32(priv->regs + TSI721_RIO_PW_RX_CAPT(2));
pw_buf[3] = ioread32(priv->regs + TSI721_RIO_PW_RX_CAPT(3));
/* Queue PW message (if there is room in FIFO),
* otherwise discard it.
*/
spin_lock(&priv->pw_fifo_lock);
if (kfifo_avail(&priv->pw_fifo) >= TSI721_RIO_PW_MSG_SIZE)
kfifo_in(&priv->pw_fifo, pw_buf,
TSI721_RIO_PW_MSG_SIZE);
else
priv->pw_discard_count++;
spin_unlock(&priv->pw_fifo_lock);
}
/* Clear pending PW interrupts */
iowrite32(TSI721_RIO_PW_RX_STAT_PW_DISC | TSI721_RIO_PW_RX_STAT_PW_VAL,
priv->regs + TSI721_RIO_PW_RX_STAT);
schedule_work(&priv->pw_work);
return 0;
}
static void tsi721_pw_dpc(struct work_struct *work)
{
struct tsi721_device *priv = container_of(work, struct tsi721_device,
pw_work);
u32 msg_buffer[RIO_PW_MSG_SIZE/sizeof(u32)]; /* Use full size PW message
buffer for RIO layer */
/*
* Process port-write messages
*/
while (kfifo_out_spinlocked(&priv->pw_fifo, (unsigned char *)msg_buffer,
TSI721_RIO_PW_MSG_SIZE, &priv->pw_fifo_lock)) {
/* Process one message */
#ifdef DEBUG_PW
{
u32 i;
pr_debug("%s : Port-Write Message:", __func__);
for (i = 0; i < RIO_PW_MSG_SIZE/sizeof(u32); ) {
pr_debug("0x%02x: %08x %08x %08x %08x", i*4,
msg_buffer[i], msg_buffer[i + 1],
msg_buffer[i + 2], msg_buffer[i + 3]);
i += 4;
}
pr_debug("\n");
}
#endif
/* Pass the port-write message to RIO core for processing */
rio_inb_pwrite_handler((union rio_pw_msg *)msg_buffer);
}
}
/**
* tsi721_pw_enable - enable/disable port-write interface init
* @mport: Master port implementing the port write unit
* @enable: 1=enable; 0=disable port-write message handling
*/
static int tsi721_pw_enable(struct rio_mport *mport, int enable)
{
struct tsi721_device *priv = mport->priv;
u32 rval;
rval = ioread32(priv->regs + TSI721_RIO_EM_INT_ENABLE);
if (enable)
rval |= TSI721_RIO_EM_INT_ENABLE_PW_RX;
else
rval &= ~TSI721_RIO_EM_INT_ENABLE_PW_RX;
/* Clear pending PW interrupts */
iowrite32(TSI721_RIO_PW_RX_STAT_PW_DISC | TSI721_RIO_PW_RX_STAT_PW_VAL,
priv->regs + TSI721_RIO_PW_RX_STAT);
/* Update enable bits */
iowrite32(rval, priv->regs + TSI721_RIO_EM_INT_ENABLE);
return 0;
}
/**
* tsi721_dsend - Send a RapidIO doorbell
* @mport: RapidIO master port info
* @index: ID of RapidIO interface
* @destid: Destination ID of target device
* @data: 16-bit info field of RapidIO doorbell
*
* Sends a RapidIO doorbell message. Always returns %0.
*/
static int tsi721_dsend(struct rio_mport *mport, int index,
u16 destid, u16 data)
{
struct tsi721_device *priv = mport->priv;
u32 offset;
offset = (((mport->sys_size) ? RIO_TT_CODE_16 : RIO_TT_CODE_8) << 18) |
(destid << 2);
dev_dbg(&priv->pdev->dev,
"Send Doorbell 0x%04x to destID 0x%x\n", data, destid);
iowrite16be(data, priv->odb_base + offset);
return 0;
}
/**
* tsi721_dbell_handler - Tsi721 doorbell interrupt handler
* @mport: RapidIO master port structure
*
* Handles inbound doorbell interrupts. Copies doorbell entry from an internal
* buffer into DB message FIFO and schedules deferred routine to process
* queued DBs.
*/
static int
tsi721_dbell_handler(struct rio_mport *mport)
{
struct tsi721_device *priv = mport->priv;
u32 regval;
/* Disable IDB interrupts */
regval = ioread32(priv->regs + TSI721_SR_CHINTE(IDB_QUEUE));
regval &= ~TSI721_SR_CHINT_IDBQRCV;
iowrite32(regval,
priv->regs + TSI721_SR_CHINTE(IDB_QUEUE));
schedule_work(&priv->idb_work);
return 0;
}
static void tsi721_db_dpc(struct work_struct *work)
{
struct tsi721_device *priv = container_of(work, struct tsi721_device,
idb_work);
struct rio_mport *mport;
struct rio_dbell *dbell;
int found = 0;
u32 wr_ptr, rd_ptr;
u64 *idb_entry;
u32 regval;
union {
u64 msg;
u8 bytes[8];
} idb;
/*
* Process queued inbound doorbells
*/
mport = priv->mport;
wr_ptr = ioread32(priv->regs + TSI721_IDQ_WP(IDB_QUEUE)) % IDB_QSIZE;
rd_ptr = ioread32(priv->regs + TSI721_IDQ_RP(IDB_QUEUE)) % IDB_QSIZE;
while (wr_ptr != rd_ptr) {
idb_entry = (u64 *)(priv->idb_base +
(TSI721_IDB_ENTRY_SIZE * rd_ptr));
rd_ptr++;
rd_ptr %= IDB_QSIZE;
idb.msg = *idb_entry;
*idb_entry = 0;
/* Process one doorbell */
list_for_each_entry(dbell, &mport->dbells, node) {
if ((dbell->res->start <= DBELL_INF(idb.bytes)) &&
(dbell->res->end >= DBELL_INF(idb.bytes))) {
found = 1;
break;
}
}
if (found) {
dbell->dinb(mport, dbell->dev_id, DBELL_SID(idb.bytes),
DBELL_TID(idb.bytes), DBELL_INF(idb.bytes));
} else {
dev_dbg(&priv->pdev->dev,
"spurious inb doorbell, sid %2.2x tid %2.2x"
" info %4.4x\n", DBELL_SID(idb.bytes),
DBELL_TID(idb.bytes), DBELL_INF(idb.bytes));
}
}
iowrite32(rd_ptr & (IDB_QSIZE - 1),
priv->regs + TSI721_IDQ_RP(IDB_QUEUE));
/* Re-enable IDB interrupts */
regval = ioread32(priv->regs + TSI721_SR_CHINTE(IDB_QUEUE));
regval |= TSI721_SR_CHINT_IDBQRCV;
iowrite32(regval,
priv->regs + TSI721_SR_CHINTE(IDB_QUEUE));
}
/**
* tsi721_irqhandler - Tsi721 interrupt handler
* @irq: Linux interrupt number
* @ptr: Pointer to interrupt-specific data (mport structure)
*
* Handles Tsi721 interrupts signaled using MSI and INTA. Checks reported
* interrupt events and calls an event-specific handler(s).
*/
static irqreturn_t tsi721_irqhandler(int irq, void *ptr)
{
struct rio_mport *mport = (struct rio_mport *)ptr;
struct tsi721_device *priv = mport->priv;
u32 dev_int;
u32 dev_ch_int;
u32 intval;
u32 ch_inte;
dev_int = ioread32(priv->regs + TSI721_DEV_INT);
if (!dev_int)
return IRQ_NONE;
dev_ch_int = ioread32(priv->regs + TSI721_DEV_CHAN_INT);
if (dev_int & TSI721_DEV_INT_SR2PC_CH) {
/* Service SR2PC Channel interrupts */
if (dev_ch_int & TSI721_INT_SR2PC_CHAN(IDB_QUEUE)) {
/* Service Inbound Doorbell interrupt */
intval = ioread32(priv->regs +
TSI721_SR_CHINT(IDB_QUEUE));
if (intval & TSI721_SR_CHINT_IDBQRCV)
tsi721_dbell_handler(mport);
else
dev_info(&priv->pdev->dev,
"Unsupported SR_CH_INT %x\n", intval);
/* Clear interrupts */
iowrite32(intval,
priv->regs + TSI721_SR_CHINT(IDB_QUEUE));
ioread32(priv->regs + TSI721_SR_CHINT(IDB_QUEUE));
}
}
if (dev_int & TSI721_DEV_INT_SMSG_CH) {
int ch;
/*
* Service channel interrupts from Messaging Engine
*/
if (dev_ch_int & TSI721_INT_IMSG_CHAN_M) { /* Inbound Msg */
/* Disable signaled OB MSG Channel interrupts */
ch_inte = ioread32(priv->regs + TSI721_DEV_CHAN_INTE);
ch_inte &= ~(dev_ch_int & TSI721_INT_IMSG_CHAN_M);
iowrite32(ch_inte, priv->regs + TSI721_DEV_CHAN_INTE);
/*
* Process Inbound Message interrupt for each MBOX
*/
for (ch = 4; ch < RIO_MAX_MBOX + 4; ch++) {
if (!(dev_ch_int & TSI721_INT_IMSG_CHAN(ch)))
continue;
tsi721_imsg_handler(priv, ch);
}
}
if (dev_ch_int & TSI721_INT_OMSG_CHAN_M) { /* Outbound Msg */
/* Disable signaled OB MSG Channel interrupts */
ch_inte = ioread32(priv->regs + TSI721_DEV_CHAN_INTE);
ch_inte &= ~(dev_ch_int & TSI721_INT_OMSG_CHAN_M);
iowrite32(ch_inte, priv->regs + TSI721_DEV_CHAN_INTE);
/*
* Process Outbound Message interrupts for each MBOX
*/
for (ch = 0; ch < RIO_MAX_MBOX; ch++) {
if (!(dev_ch_int & TSI721_INT_OMSG_CHAN(ch)))
continue;
tsi721_omsg_handler(priv, ch);
}
}
}
if (dev_int & TSI721_DEV_INT_SRIO) {
/* Service SRIO MAC interrupts */
intval = ioread32(priv->regs + TSI721_RIO_EM_INT_STAT);
if (intval & TSI721_RIO_EM_INT_STAT_PW_RX)
tsi721_pw_handler(mport);
}
return IRQ_HANDLED;
}
static void tsi721_interrupts_init(struct tsi721_device *priv)
{
u32 intr;
/* Enable IDB interrupts */
iowrite32(TSI721_SR_CHINT_ALL,
priv->regs + TSI721_SR_CHINT(IDB_QUEUE));
iowrite32(TSI721_SR_CHINT_IDBQRCV,
priv->regs + TSI721_SR_CHINTE(IDB_QUEUE));
iowrite32(TSI721_INT_SR2PC_CHAN(IDB_QUEUE),
priv->regs + TSI721_DEV_CHAN_INTE);
/* Enable SRIO MAC interrupts */
iowrite32(TSI721_RIO_EM_DEV_INT_EN_INT,
priv->regs + TSI721_RIO_EM_DEV_INT_EN);
if (priv->flags & TSI721_USING_MSIX)
intr = TSI721_DEV_INT_SRIO;
else
intr = TSI721_DEV_INT_SR2PC_CH | TSI721_DEV_INT_SRIO |
TSI721_DEV_INT_SMSG_CH;
iowrite32(intr, priv->regs + TSI721_DEV_INTE);
ioread32(priv->regs + TSI721_DEV_INTE);
}
#ifdef CONFIG_PCI_MSI
/**
* tsi721_omsg_msix - MSI-X interrupt handler for outbound messaging
* @irq: Linux interrupt number
* @ptr: Pointer to interrupt-specific data (mport structure)
*
* Handles outbound messaging interrupts signaled using MSI-X.
*/
static irqreturn_t tsi721_omsg_msix(int irq, void *ptr)
{
struct tsi721_device *priv = ((struct rio_mport *)ptr)->priv;
int mbox;
mbox = (irq - priv->msix[TSI721_VECT_OMB0_DONE].vector) % RIO_MAX_MBOX;
tsi721_omsg_handler(priv, mbox);
return IRQ_HANDLED;
}
/**
* tsi721_imsg_msix - MSI-X interrupt handler for inbound messaging
* @irq: Linux interrupt number
* @ptr: Pointer to interrupt-specific data (mport structure)
*
* Handles inbound messaging interrupts signaled using MSI-X.
*/
static irqreturn_t tsi721_imsg_msix(int irq, void *ptr)
{
struct tsi721_device *priv = ((struct rio_mport *)ptr)->priv;
int mbox;
mbox = (irq - priv->msix[TSI721_VECT_IMB0_RCV].vector) % RIO_MAX_MBOX;
tsi721_imsg_handler(priv, mbox + 4);
return IRQ_HANDLED;
}
/**
* tsi721_srio_msix - Tsi721 MSI-X SRIO MAC interrupt handler
* @irq: Linux interrupt number
* @ptr: Pointer to interrupt-specific data (mport structure)
*
* Handles Tsi721 interrupts from SRIO MAC.
*/
static irqreturn_t tsi721_srio_msix(int irq, void *ptr)
{
struct tsi721_device *priv = ((struct rio_mport *)ptr)->priv;
u32 srio_int;
/* Service SRIO MAC interrupts */
srio_int = ioread32(priv->regs + TSI721_RIO_EM_INT_STAT);
if (srio_int & TSI721_RIO_EM_INT_STAT_PW_RX)
tsi721_pw_handler((struct rio_mport *)ptr);
return IRQ_HANDLED;
}
/**
* tsi721_sr2pc_ch_msix - Tsi721 MSI-X SR2PC Channel interrupt handler
* @irq: Linux interrupt number
* @ptr: Pointer to interrupt-specific data (mport structure)
*
* Handles Tsi721 interrupts from SR2PC Channel.
* NOTE: At this moment services only one SR2PC channel associated with inbound
* doorbells.
*/
static irqreturn_t tsi721_sr2pc_ch_msix(int irq, void *ptr)
{
struct tsi721_device *priv = ((struct rio_mport *)ptr)->priv;
u32 sr_ch_int;
/* Service Inbound DB interrupt from SR2PC channel */
sr_ch_int = ioread32(priv->regs + TSI721_SR_CHINT(IDB_QUEUE));
if (sr_ch_int & TSI721_SR_CHINT_IDBQRCV)
tsi721_dbell_handler((struct rio_mport *)ptr);
/* Clear interrupts */
iowrite32(sr_ch_int, priv->regs + TSI721_SR_CHINT(IDB_QUEUE));
/* Read back to ensure that interrupt was cleared */
sr_ch_int = ioread32(priv->regs + TSI721_SR_CHINT(IDB_QUEUE));
return IRQ_HANDLED;
}
/**
* tsi721_request_msix - register interrupt service for MSI-X mode.
* @mport: RapidIO master port structure
*
* Registers MSI-X interrupt service routines for interrupts that are active
* immediately after mport initialization. Messaging interrupt service routines
* should be registered during corresponding open requests.
*/
static int tsi721_request_msix(struct rio_mport *mport)
{
struct tsi721_device *priv = mport->priv;
int err = 0;
err = request_irq(priv->msix[TSI721_VECT_IDB].vector,
tsi721_sr2pc_ch_msix, 0,
priv->msix[TSI721_VECT_IDB].irq_name, (void *)mport);
if (err)
goto out;
err = request_irq(priv->msix[TSI721_VECT_PWRX].vector,
tsi721_srio_msix, 0,
priv->msix[TSI721_VECT_PWRX].irq_name, (void *)mport);
if (err)
free_irq(
priv->msix[TSI721_VECT_IDB].vector,
(void *)mport);
out:
return err;
}
/**
* tsi721_enable_msix - Attempts to enable MSI-X support for Tsi721.
* @priv: pointer to tsi721 private data
*
* Configures MSI-X support for Tsi721. Supports only an exact number
* of requested vectors.
*/
static int tsi721_enable_msix(struct tsi721_device *priv)
{
struct msix_entry entries[TSI721_VECT_MAX];
int err;
int i;
entries[TSI721_VECT_IDB].entry = TSI721_MSIX_SR2PC_IDBQ_RCV(IDB_QUEUE);
entries[TSI721_VECT_PWRX].entry = TSI721_MSIX_SRIO_MAC_INT;
/*
* Initialize MSI-X entries for Messaging Engine:
* this driver supports four RIO mailboxes (inbound and outbound)
* NOTE: Inbound message MBOX 0...4 use IB channels 4...7. Therefore
* offset +4 is added to IB MBOX number.
*/
for (i = 0; i < RIO_MAX_MBOX; i++) {
entries[TSI721_VECT_IMB0_RCV + i].entry =
TSI721_MSIX_IMSG_DQ_RCV(i + 4);
entries[TSI721_VECT_IMB0_INT + i].entry =
TSI721_MSIX_IMSG_INT(i + 4);
entries[TSI721_VECT_OMB0_DONE + i].entry =
TSI721_MSIX_OMSG_DONE(i);
entries[TSI721_VECT_OMB0_INT + i].entry =
TSI721_MSIX_OMSG_INT(i);
}
err = pci_enable_msix(priv->pdev, entries, ARRAY_SIZE(entries));
if (err) {
if (err > 0)
dev_info(&priv->pdev->dev,
"Only %d MSI-X vectors available, "
"not using MSI-X\n", err);
return err;
}
/*
* Copy MSI-X vector information into tsi721 private structure
*/
priv->msix[TSI721_VECT_IDB].vector = entries[TSI721_VECT_IDB].vector;
snprintf(priv->msix[TSI721_VECT_IDB].irq_name, IRQ_DEVICE_NAME_MAX,
DRV_NAME "-idb@pci:%s", pci_name(priv->pdev));
priv->msix[TSI721_VECT_PWRX].vector = entries[TSI721_VECT_PWRX].vector;
snprintf(priv->msix[TSI721_VECT_PWRX].irq_name, IRQ_DEVICE_NAME_MAX,
DRV_NAME "-pwrx@pci:%s", pci_name(priv->pdev));
for (i = 0; i < RIO_MAX_MBOX; i++) {
priv->msix[TSI721_VECT_IMB0_RCV + i].vector =
entries[TSI721_VECT_IMB0_RCV + i].vector;
snprintf(priv->msix[TSI721_VECT_IMB0_RCV + i].irq_name,
IRQ_DEVICE_NAME_MAX, DRV_NAME "-imbr%d@pci:%s",
i, pci_name(priv->pdev));
priv->msix[TSI721_VECT_IMB0_INT + i].vector =
entries[TSI721_VECT_IMB0_INT + i].vector;
snprintf(priv->msix[TSI721_VECT_IMB0_INT + i].irq_name,
IRQ_DEVICE_NAME_MAX, DRV_NAME "-imbi%d@pci:%s",
i, pci_name(priv->pdev));
priv->msix[TSI721_VECT_OMB0_DONE + i].vector =
entries[TSI721_VECT_OMB0_DONE + i].vector;
snprintf(priv->msix[TSI721_VECT_OMB0_DONE + i].irq_name,
IRQ_DEVICE_NAME_MAX, DRV_NAME "-ombd%d@pci:%s",
i, pci_name(priv->pdev));
priv->msix[TSI721_VECT_OMB0_INT + i].vector =
entries[TSI721_VECT_OMB0_INT + i].vector;
snprintf(priv->msix[TSI721_VECT_OMB0_INT + i].irq_name,
IRQ_DEVICE_NAME_MAX, DRV_NAME "-ombi%d@pci:%s",
i, pci_name(priv->pdev));
}
return 0;
}
#endif /* CONFIG_PCI_MSI */
static int tsi721_request_irq(struct rio_mport *mport)
{
struct tsi721_device *priv = mport->priv;
int err;
#ifdef CONFIG_PCI_MSI
if (priv->flags & TSI721_USING_MSIX)
err = tsi721_request_msix(mport);
else
#endif
err = request_irq(priv->pdev->irq, tsi721_irqhandler,
(priv->flags & TSI721_USING_MSI) ? 0 : IRQF_SHARED,
DRV_NAME, (void *)mport);
if (err)
dev_err(&priv->pdev->dev,
"Unable to allocate interrupt, Error: %d\n", err);
return err;
}
/**
* tsi721_init_pc2sr_mapping - initializes outbound (PCIe->SRIO)
* translation regions.
* @priv: pointer to tsi721 private data
*
* Disables SREP translation regions.
*/
static void tsi721_init_pc2sr_mapping(struct tsi721_device *priv)
{
int i;
/* Disable all PC2SR translation windows */
for (i = 0; i < TSI721_OBWIN_NUM; i++)
iowrite32(0, priv->regs + TSI721_OBWINLB(i));
}
/**
* tsi721_init_sr2pc_mapping - initializes inbound (SRIO->PCIe)
* translation regions.
* @priv: pointer to tsi721 private data
*
* Disables inbound windows.
*/
static void tsi721_init_sr2pc_mapping(struct tsi721_device *priv)
{
int i;
/* Disable all SR2PC inbound windows */
for (i = 0; i < TSI721_IBWIN_NUM; i++)
iowrite32(0, priv->regs + TSI721_IBWINLB(i));
}
/**
* tsi721_port_write_init - Inbound port write interface init
* @priv: pointer to tsi721 private data
*
* Initializes inbound port write handler.
* Returns %0 on success or %-ENOMEM on failure.
*/
static int tsi721_port_write_init(struct tsi721_device *priv)
{
priv->pw_discard_count = 0;
INIT_WORK(&priv->pw_work, tsi721_pw_dpc);
spin_lock_init(&priv->pw_fifo_lock);
if (kfifo_alloc(&priv->pw_fifo,
TSI721_RIO_PW_MSG_SIZE * 32, GFP_KERNEL)) {
dev_err(&priv->pdev->dev, "PW FIFO allocation failed\n");
return -ENOMEM;
}
/* Use reliable port-write capture mode */
iowrite32(TSI721_RIO_PW_CTL_PWC_REL, priv->regs + TSI721_RIO_PW_CTL);
return 0;
}
static int tsi721_doorbell_init(struct tsi721_device *priv)
{
/* Outbound Doorbells do not require any setup.
* Tsi721 uses dedicated PCI BAR1 to generate doorbells.
* That BAR1 was mapped during the probe routine.
*/
/* Initialize Inbound Doorbell processing DPC and queue */
priv->db_discard_count = 0;
INIT_WORK(&priv->idb_work, tsi721_db_dpc);
/* Allocate buffer for inbound doorbells queue */
priv->idb_base = dma_zalloc_coherent(&priv->pdev->dev,
IDB_QSIZE * TSI721_IDB_ENTRY_SIZE,
&priv->idb_dma, GFP_KERNEL);
if (!priv->idb_base)
return -ENOMEM;
dev_dbg(&priv->pdev->dev, "Allocated IDB buffer @ %p (phys = %llx)\n",
priv->idb_base, (unsigned long long)priv->idb_dma);
iowrite32(TSI721_IDQ_SIZE_VAL(IDB_QSIZE),
priv->regs + TSI721_IDQ_SIZE(IDB_QUEUE));
iowrite32(((u64)priv->idb_dma >> 32),
priv->regs + TSI721_IDQ_BASEU(IDB_QUEUE));
iowrite32(((u64)priv->idb_dma & TSI721_IDQ_BASEL_ADDR),
priv->regs + TSI721_IDQ_BASEL(IDB_QUEUE));
/* Enable accepting all inbound doorbells */
iowrite32(0, priv->regs + TSI721_IDQ_MASK(IDB_QUEUE));
iowrite32(TSI721_IDQ_INIT, priv->regs + TSI721_IDQ_CTL(IDB_QUEUE));
iowrite32(0, priv->regs + TSI721_IDQ_RP(IDB_QUEUE));
return 0;
}
static void tsi721_doorbell_free(struct tsi721_device *priv)
{
if (priv->idb_base == NULL)
return;
/* Free buffer allocated for inbound doorbell queue */
dma_free_coherent(&priv->pdev->dev, IDB_QSIZE * TSI721_IDB_ENTRY_SIZE,
priv->idb_base, priv->idb_dma);
priv->idb_base = NULL;
}
static int tsi721_bdma_ch_init(struct tsi721_device *priv, int chnum)
{
struct tsi721_dma_desc *bd_ptr;
u64 *sts_ptr;
dma_addr_t bd_phys, sts_phys;
int sts_size;
int bd_num = priv->bdma[chnum].bd_num;
dev_dbg(&priv->pdev->dev, "Init Block DMA Engine, CH%d\n", chnum);
/*
* Initialize DMA channel for maintenance requests
*/
/* Allocate space for DMA descriptors */
bd_ptr = dma_zalloc_coherent(&priv->pdev->dev,
bd_num * sizeof(struct tsi721_dma_desc),
&bd_phys, GFP_KERNEL);
if (!bd_ptr)
return -ENOMEM;
priv->bdma[chnum].bd_phys = bd_phys;
priv->bdma[chnum].bd_base = bd_ptr;
dev_dbg(&priv->pdev->dev, "DMA descriptors @ %p (phys = %llx)\n",
bd_ptr, (unsigned long long)bd_phys);
/* Allocate space for descriptor status FIFO */
sts_size = (bd_num >= TSI721_DMA_MINSTSSZ) ?
bd_num : TSI721_DMA_MINSTSSZ;
sts_size = roundup_pow_of_two(sts_size);
sts_ptr = dma_zalloc_coherent(&priv->pdev->dev,
sts_size * sizeof(struct tsi721_dma_sts),
&sts_phys, GFP_KERNEL);
if (!sts_ptr) {
/* Free space allocated for DMA descriptors */
dma_free_coherent(&priv->pdev->dev,
bd_num * sizeof(struct tsi721_dma_desc),
bd_ptr, bd_phys);
priv->bdma[chnum].bd_base = NULL;
return -ENOMEM;
}
priv->bdma[chnum].sts_phys = sts_phys;
priv->bdma[chnum].sts_base = sts_ptr;
priv->bdma[chnum].sts_size = sts_size;
dev_dbg(&priv->pdev->dev,
"desc status FIFO @ %p (phys = %llx) size=0x%x\n",
sts_ptr, (unsigned long long)sts_phys, sts_size);
/* Initialize DMA descriptors ring */
bd_ptr[bd_num - 1].type_id = cpu_to_le32(DTYPE3 << 29);
bd_ptr[bd_num - 1].next_lo = cpu_to_le32((u64)bd_phys &
TSI721_DMAC_DPTRL_MASK);
bd_ptr[bd_num - 1].next_hi = cpu_to_le32((u64)bd_phys >> 32);
/* Setup DMA descriptor pointers */
iowrite32(((u64)bd_phys >> 32),
priv->regs + TSI721_DMAC_DPTRH(chnum));
iowrite32(((u64)bd_phys & TSI721_DMAC_DPTRL_MASK),
priv->regs + TSI721_DMAC_DPTRL(chnum));
/* Setup descriptor status FIFO */
iowrite32(((u64)sts_phys >> 32),
priv->regs + TSI721_DMAC_DSBH(chnum));
iowrite32(((u64)sts_phys & TSI721_DMAC_DSBL_MASK),
priv->regs + TSI721_DMAC_DSBL(chnum));
iowrite32(TSI721_DMAC_DSSZ_SIZE(sts_size),
priv->regs + TSI721_DMAC_DSSZ(chnum));
/* Clear interrupt bits */
iowrite32(TSI721_DMAC_INT_ALL,
priv->regs + TSI721_DMAC_INT(chnum));
ioread32(priv->regs + TSI721_DMAC_INT(chnum));
/* Toggle DMA channel initialization */
iowrite32(TSI721_DMAC_CTL_INIT, priv->regs + TSI721_DMAC_CTL(chnum));
ioread32(priv->regs + TSI721_DMAC_CTL(chnum));
udelay(10);
return 0;
}
static int tsi721_bdma_ch_free(struct tsi721_device *priv, int chnum)
{
u32 ch_stat;
if (priv->bdma[chnum].bd_base == NULL)
return 0;
/* Check if DMA channel still running */
ch_stat = ioread32(priv->regs + TSI721_DMAC_STS(chnum));
if (ch_stat & TSI721_DMAC_STS_RUN)
return -EFAULT;
/* Put DMA channel into init state */
iowrite32(TSI721_DMAC_CTL_INIT,
priv->regs + TSI721_DMAC_CTL(chnum));
/* Free space allocated for DMA descriptors */
dma_free_coherent(&priv->pdev->dev,
priv->bdma[chnum].bd_num * sizeof(struct tsi721_dma_desc),
priv->bdma[chnum].bd_base, priv->bdma[chnum].bd_phys);
priv->bdma[chnum].bd_base = NULL;
/* Free space allocated for status FIFO */
dma_free_coherent(&priv->pdev->dev,
priv->bdma[chnum].sts_size * sizeof(struct tsi721_dma_sts),
priv->bdma[chnum].sts_base, priv->bdma[chnum].sts_phys);
priv->bdma[chnum].sts_base = NULL;
return 0;
}
static int tsi721_bdma_init(struct tsi721_device *priv)
{
/* Initialize BDMA channel allocated for RapidIO maintenance read/write
* request generation
*/
priv->bdma[TSI721_DMACH_MAINT].bd_num = 2;
if (tsi721_bdma_ch_init(priv, TSI721_DMACH_MAINT)) {
dev_err(&priv->pdev->dev, "Unable to initialize maintenance DMA"
" channel %d, aborting\n", TSI721_DMACH_MAINT);
return -ENOMEM;
}
return 0;
}
static void tsi721_bdma_free(struct tsi721_device *priv)
{
tsi721_bdma_ch_free(priv, TSI721_DMACH_MAINT);
}
/* Enable Inbound Messaging Interrupts */
static void
tsi721_imsg_interrupt_enable(struct tsi721_device *priv, int ch,
u32 inte_mask)
{
u32 rval;
if (!inte_mask)
return;
/* Clear pending Inbound Messaging interrupts */
iowrite32(inte_mask, priv->regs + TSI721_IBDMAC_INT(ch));
/* Enable Inbound Messaging interrupts */
rval = ioread32(priv->regs + TSI721_IBDMAC_INTE(ch));
iowrite32(rval | inte_mask, priv->regs + TSI721_IBDMAC_INTE(ch));
if (priv->flags & TSI721_USING_MSIX)
return; /* Finished if we are in MSI-X mode */
/*
* For MSI and INTA interrupt signalling we need to enable next levels
*/
/* Enable Device Channel Interrupt */
rval = ioread32(priv->regs + TSI721_DEV_CHAN_INTE);
iowrite32(rval | TSI721_INT_IMSG_CHAN(ch),
priv->regs + TSI721_DEV_CHAN_INTE);
}
/* Disable Inbound Messaging Interrupts */
static void
tsi721_imsg_interrupt_disable(struct tsi721_device *priv, int ch,
u32 inte_mask)
{
u32 rval;
if (!inte_mask)
return;
/* Clear pending Inbound Messaging interrupts */
iowrite32(inte_mask, priv->regs + TSI721_IBDMAC_INT(ch));
/* Disable Inbound Messaging interrupts */
rval = ioread32(priv->regs + TSI721_IBDMAC_INTE(ch));
rval &= ~inte_mask;
iowrite32(rval, priv->regs + TSI721_IBDMAC_INTE(ch));
if (priv->flags & TSI721_USING_MSIX)
return; /* Finished if we are in MSI-X mode */
/*
* For MSI and INTA interrupt signalling we need to disable next levels
*/
/* Disable Device Channel Interrupt */
rval = ioread32(priv->regs + TSI721_DEV_CHAN_INTE);
rval &= ~TSI721_INT_IMSG_CHAN(ch);
iowrite32(rval, priv->regs + TSI721_DEV_CHAN_INTE);
}
/* Enable Outbound Messaging interrupts */
static void
tsi721_omsg_interrupt_enable(struct tsi721_device *priv, int ch,
u32 inte_mask)
{
u32 rval;
if (!inte_mask)
return;
/* Clear pending Outbound Messaging interrupts */
iowrite32(inte_mask, priv->regs + TSI721_OBDMAC_INT(ch));
/* Enable Outbound Messaging channel interrupts */
rval = ioread32(priv->regs + TSI721_OBDMAC_INTE(ch));
iowrite32(rval | inte_mask, priv->regs + TSI721_OBDMAC_INTE(ch));
if (priv->flags & TSI721_USING_MSIX)
return; /* Finished if we are in MSI-X mode */
/*
* For MSI and INTA interrupt signalling we need to enable next levels
*/
/* Enable Device Channel Interrupt */
rval = ioread32(priv->regs + TSI721_DEV_CHAN_INTE);
iowrite32(rval | TSI721_INT_OMSG_CHAN(ch),
priv->regs + TSI721_DEV_CHAN_INTE);
}
/* Disable Outbound Messaging interrupts */
static void
tsi721_omsg_interrupt_disable(struct tsi721_device *priv, int ch,
u32 inte_mask)
{
u32 rval;
if (!inte_mask)
return;
/* Clear pending Outbound Messaging interrupts */
iowrite32(inte_mask, priv->regs + TSI721_OBDMAC_INT(ch));
/* Disable Outbound Messaging interrupts */
rval = ioread32(priv->regs + TSI721_OBDMAC_INTE(ch));
rval &= ~inte_mask;
iowrite32(rval, priv->regs + TSI721_OBDMAC_INTE(ch));
if (priv->flags & TSI721_USING_MSIX)
return; /* Finished if we are in MSI-X mode */
/*
* For MSI and INTA interrupt signalling we need to disable next levels
*/
/* Disable Device Channel Interrupt */
rval = ioread32(priv->regs + TSI721_DEV_CHAN_INTE);
rval &= ~TSI721_INT_OMSG_CHAN(ch);
iowrite32(rval, priv->regs + TSI721_DEV_CHAN_INTE);
}
/**
* tsi721_add_outb_message - Add message to the Tsi721 outbound message queue
* @mport: Master port with outbound message queue
* @rdev: Target of outbound message
* @mbox: Outbound mailbox
* @buffer: Message to add to outbound queue
* @len: Length of message
*/
static int
tsi721_add_outb_message(struct rio_mport *mport, struct rio_dev *rdev, int mbox,
void *buffer, size_t len)
{
struct tsi721_device *priv = mport->priv;
struct tsi721_omsg_desc *desc;
u32 tx_slot;
if (!priv->omsg_init[mbox] ||
len > TSI721_MSG_MAX_SIZE || len < 8)
return -EINVAL;
tx_slot = priv->omsg_ring[mbox].tx_slot;
/* Copy copy message into transfer buffer */
memcpy(priv->omsg_ring[mbox].omq_base[tx_slot], buffer, len);
if (len & 0x7)
len += 8;
/* Build descriptor associated with buffer */
desc = priv->omsg_ring[mbox].omd_base;
desc[tx_slot].type_id = cpu_to_le32((DTYPE4 << 29) | rdev->destid);
if (tx_slot % 4 == 0)
desc[tx_slot].type_id |= cpu_to_le32(TSI721_OMD_IOF);
desc[tx_slot].msg_info =
cpu_to_le32((mport->sys_size << 26) | (mbox << 22) |
(0xe << 12) | (len & 0xff8));
desc[tx_slot].bufptr_lo =
cpu_to_le32((u64)priv->omsg_ring[mbox].omq_phys[tx_slot] &
0xffffffff);
desc[tx_slot].bufptr_hi =
cpu_to_le32((u64)priv->omsg_ring[mbox].omq_phys[tx_slot] >> 32);
priv->omsg_ring[mbox].wr_count++;
/* Go to next descriptor */
if (++priv->omsg_ring[mbox].tx_slot == priv->omsg_ring[mbox].size) {
priv->omsg_ring[mbox].tx_slot = 0;
/* Move through the ring link descriptor at the end */
priv->omsg_ring[mbox].wr_count++;
}
mb();
/* Set new write count value */
iowrite32(priv->omsg_ring[mbox].wr_count,
priv->regs + TSI721_OBDMAC_DWRCNT(mbox));
ioread32(priv->regs + TSI721_OBDMAC_DWRCNT(mbox));
return 0;
}
/**
* tsi721_omsg_handler - Outbound Message Interrupt Handler
* @priv: pointer to tsi721 private data
* @ch: number of OB MSG channel to service
*
* Services channel interrupts from outbound messaging engine.
*/
static void tsi721_omsg_handler(struct tsi721_device *priv, int ch)
{
u32 omsg_int;
spin_lock(&priv->omsg_ring[ch].lock);
omsg_int = ioread32(priv->regs + TSI721_OBDMAC_INT(ch));
if (omsg_int & TSI721_OBDMAC_INT_ST_FULL)
dev_info(&priv->pdev->dev,
"OB MBOX%d: Status FIFO is full\n", ch);
if (omsg_int & (TSI721_OBDMAC_INT_DONE | TSI721_OBDMAC_INT_IOF_DONE)) {
u32 srd_ptr;
u64 *sts_ptr, last_ptr = 0, prev_ptr = 0;
int i, j;
u32 tx_slot;
/*
* Find last successfully processed descriptor
*/
/* Check and clear descriptor status FIFO entries */
srd_ptr = priv->omsg_ring[ch].sts_rdptr;
sts_ptr = priv->omsg_ring[ch].sts_base;
j = srd_ptr * 8;
while (sts_ptr[j]) {
for (i = 0; i < 8 && sts_ptr[j]; i++, j++) {
prev_ptr = last_ptr;
last_ptr = le64_to_cpu(sts_ptr[j]);
sts_ptr[j] = 0;
}
++srd_ptr;
srd_ptr %= priv->omsg_ring[ch].sts_size;
j = srd_ptr * 8;
}
if (last_ptr == 0)
goto no_sts_update;
priv->omsg_ring[ch].sts_rdptr = srd_ptr;
iowrite32(srd_ptr, priv->regs + TSI721_OBDMAC_DSRP(ch));
if (!priv->mport->outb_msg[ch].mcback)
goto no_sts_update;
/* Inform upper layer about transfer completion */
tx_slot = (last_ptr - (u64)priv->omsg_ring[ch].omd_phys)/
sizeof(struct tsi721_omsg_desc);
/*
* Check if this is a Link Descriptor (LD).
* If yes, ignore LD and use descriptor processed
* before LD.
*/
if (tx_slot == priv->omsg_ring[ch].size) {
if (prev_ptr)
tx_slot = (prev_ptr -
(u64)priv->omsg_ring[ch].omd_phys)/
sizeof(struct tsi721_omsg_desc);
else
goto no_sts_update;
}
/* Move slot index to the next message to be sent */
++tx_slot;
if (tx_slot == priv->omsg_ring[ch].size)
tx_slot = 0;
BUG_ON(tx_slot >= priv->omsg_ring[ch].size);
priv->mport->outb_msg[ch].mcback(priv->mport,
priv->omsg_ring[ch].dev_id, ch,
tx_slot);
}
no_sts_update:
if (omsg_int & TSI721_OBDMAC_INT_ERROR) {
/*
* Outbound message operation aborted due to error,
* reinitialize OB MSG channel
*/
dev_dbg(&priv->pdev->dev, "OB MSG ABORT ch_stat=%x\n",
ioread32(priv->regs + TSI721_OBDMAC_STS(ch)));
iowrite32(TSI721_OBDMAC_INT_ERROR,
priv->regs + TSI721_OBDMAC_INT(ch));
iowrite32(TSI721_OBDMAC_CTL_INIT,
priv->regs + TSI721_OBDMAC_CTL(ch));
ioread32(priv->regs + TSI721_OBDMAC_CTL(ch));
/* Inform upper level to clear all pending tx slots */
if (priv->mport->outb_msg[ch].mcback)
priv->mport->outb_msg[ch].mcback(priv->mport,
priv->omsg_ring[ch].dev_id, ch,
priv->omsg_ring[ch].tx_slot);
/* Synch tx_slot tracking */
iowrite32(priv->omsg_ring[ch].tx_slot,
priv->regs + TSI721_OBDMAC_DRDCNT(ch));
ioread32(priv->regs + TSI721_OBDMAC_DRDCNT(ch));
priv->omsg_ring[ch].wr_count = priv->omsg_ring[ch].tx_slot;
priv->omsg_ring[ch].sts_rdptr = 0;
}
/* Clear channel interrupts */
iowrite32(omsg_int, priv->regs + TSI721_OBDMAC_INT(ch));
if (!(priv->flags & TSI721_USING_MSIX)) {
u32 ch_inte;
/* Re-enable channel interrupts */
ch_inte = ioread32(priv->regs + TSI721_DEV_CHAN_INTE);
ch_inte |= TSI721_INT_OMSG_CHAN(ch);
iowrite32(ch_inte, priv->regs + TSI721_DEV_CHAN_INTE);
}
spin_unlock(&priv->omsg_ring[ch].lock);
}
/**
* tsi721_open_outb_mbox - Initialize Tsi721 outbound mailbox
* @mport: Master port implementing Outbound Messaging Engine
* @dev_id: Device specific pointer to pass on event
* @mbox: Mailbox to open
* @entries: Number of entries in the outbound mailbox ring
*/
static int tsi721_open_outb_mbox(struct rio_mport *mport, void *dev_id,
int mbox, int entries)
{
struct tsi721_device *priv = mport->priv;
struct tsi721_omsg_desc *bd_ptr;
int i, rc = 0;
if ((entries < TSI721_OMSGD_MIN_RING_SIZE) ||
(entries > (TSI721_OMSGD_RING_SIZE)) ||
(!is_power_of_2(entries)) || mbox >= RIO_MAX_MBOX) {
rc = -EINVAL;
goto out;
}
priv->omsg_ring[mbox].dev_id = dev_id;
priv->omsg_ring[mbox].size = entries;
priv->omsg_ring[mbox].sts_rdptr = 0;
spin_lock_init(&priv->omsg_ring[mbox].lock);
/* Outbound Msg Buffer allocation based on
the number of maximum descriptor entries */
for (i = 0; i < entries; i++) {
priv->omsg_ring[mbox].omq_base[i] =
dma_alloc_coherent(
&priv->pdev->dev, TSI721_MSG_BUFFER_SIZE,
&priv->omsg_ring[mbox].omq_phys[i],
GFP_KERNEL);
if (priv->omsg_ring[mbox].omq_base[i] == NULL) {
dev_dbg(&priv->pdev->dev,
"Unable to allocate OB MSG data buffer for"
" MBOX%d\n", mbox);
rc = -ENOMEM;
goto out_buf;
}
}
/* Outbound message descriptor allocation */
priv->omsg_ring[mbox].omd_base = dma_alloc_coherent(
&priv->pdev->dev,
(entries + 1) * sizeof(struct tsi721_omsg_desc),
&priv->omsg_ring[mbox].omd_phys, GFP_KERNEL);
if (priv->omsg_ring[mbox].omd_base == NULL) {
dev_dbg(&priv->pdev->dev,
"Unable to allocate OB MSG descriptor memory "
"for MBOX%d\n", mbox);
rc = -ENOMEM;
goto out_buf;
}
priv->omsg_ring[mbox].tx_slot = 0;
/* Outbound message descriptor status FIFO allocation */
priv->omsg_ring[mbox].sts_size = roundup_pow_of_two(entries + 1);
priv->omsg_ring[mbox].sts_base = dma_zalloc_coherent(&priv->pdev->dev,
priv->omsg_ring[mbox].sts_size *
sizeof(struct tsi721_dma_sts),
&priv->omsg_ring[mbox].sts_phys, GFP_KERNEL);
if (priv->omsg_ring[mbox].sts_base == NULL) {
dev_dbg(&priv->pdev->dev,
"Unable to allocate OB MSG descriptor status FIFO "
"for MBOX%d\n", mbox);
rc = -ENOMEM;
goto out_desc;
}
/*
* Configure Outbound Messaging Engine
*/
/* Setup Outbound Message descriptor pointer */
iowrite32(((u64)priv->omsg_ring[mbox].omd_phys >> 32),
priv->regs + TSI721_OBDMAC_DPTRH(mbox));
iowrite32(((u64)priv->omsg_ring[mbox].omd_phys &
TSI721_OBDMAC_DPTRL_MASK),
priv->regs + TSI721_OBDMAC_DPTRL(mbox));
/* Setup Outbound Message descriptor status FIFO */
iowrite32(((u64)priv->omsg_ring[mbox].sts_phys >> 32),
priv->regs + TSI721_OBDMAC_DSBH(mbox));
iowrite32(((u64)priv->omsg_ring[mbox].sts_phys &
TSI721_OBDMAC_DSBL_MASK),
priv->regs + TSI721_OBDMAC_DSBL(mbox));
iowrite32(TSI721_DMAC_DSSZ_SIZE(priv->omsg_ring[mbox].sts_size),
priv->regs + (u32)TSI721_OBDMAC_DSSZ(mbox));
/* Enable interrupts */
#ifdef CONFIG_PCI_MSI
if (priv->flags & TSI721_USING_MSIX) {
/* Request interrupt service if we are in MSI-X mode */
rc = request_irq(
priv->msix[TSI721_VECT_OMB0_DONE + mbox].vector,
tsi721_omsg_msix, 0,
priv->msix[TSI721_VECT_OMB0_DONE + mbox].irq_name,
(void *)mport);
if (rc) {
dev_dbg(&priv->pdev->dev,
"Unable to allocate MSI-X interrupt for "
"OBOX%d-DONE\n", mbox);
goto out_stat;
}
rc = request_irq(priv->msix[TSI721_VECT_OMB0_INT + mbox].vector,
tsi721_omsg_msix, 0,
priv->msix[TSI721_VECT_OMB0_INT + mbox].irq_name,
(void *)mport);
if (rc) {
dev_dbg(&priv->pdev->dev,
"Unable to allocate MSI-X interrupt for "
"MBOX%d-INT\n", mbox);
free_irq(
priv->msix[TSI721_VECT_OMB0_DONE + mbox].vector,
(void *)mport);
goto out_stat;
}
}
#endif /* CONFIG_PCI_MSI */
tsi721_omsg_interrupt_enable(priv, mbox, TSI721_OBDMAC_INT_ALL);
/* Initialize Outbound Message descriptors ring */
bd_ptr = priv->omsg_ring[mbox].omd_base;
bd_ptr[entries].type_id = cpu_to_le32(DTYPE5 << 29);
bd_ptr[entries].msg_info = 0;
bd_ptr[entries].next_lo =
cpu_to_le32((u64)priv->omsg_ring[mbox].omd_phys &
TSI721_OBDMAC_DPTRL_MASK);
bd_ptr[entries].next_hi =
cpu_to_le32((u64)priv->omsg_ring[mbox].omd_phys >> 32);
priv->omsg_ring[mbox].wr_count = 0;
mb();
/* Initialize Outbound Message engine */
iowrite32(TSI721_OBDMAC_CTL_INIT, priv->regs + TSI721_OBDMAC_CTL(mbox));
ioread32(priv->regs + TSI721_OBDMAC_DWRCNT(mbox));
udelay(10);
priv->omsg_init[mbox] = 1;
return 0;
#ifdef CONFIG_PCI_MSI
out_stat:
dma_free_coherent(&priv->pdev->dev,
priv->omsg_ring[mbox].sts_size * sizeof(struct tsi721_dma_sts),
priv->omsg_ring[mbox].sts_base,
priv->omsg_ring[mbox].sts_phys);
priv->omsg_ring[mbox].sts_base = NULL;
#endif /* CONFIG_PCI_MSI */
out_desc:
dma_free_coherent(&priv->pdev->dev,
(entries + 1) * sizeof(struct tsi721_omsg_desc),
priv->omsg_ring[mbox].omd_base,
priv->omsg_ring[mbox].omd_phys);
priv->omsg_ring[mbox].omd_base = NULL;
out_buf:
for (i = 0; i < priv->omsg_ring[mbox].size; i++) {
if (priv->omsg_ring[mbox].omq_base[i]) {
dma_free_coherent(&priv->pdev->dev,
TSI721_MSG_BUFFER_SIZE,
priv->omsg_ring[mbox].omq_base[i],
priv->omsg_ring[mbox].omq_phys[i]);
priv->omsg_ring[mbox].omq_base[i] = NULL;
}
}
out:
return rc;
}
/**
* tsi721_close_outb_mbox - Close Tsi721 outbound mailbox
* @mport: Master port implementing the outbound message unit
* @mbox: Mailbox to close
*/
static void tsi721_close_outb_mbox(struct rio_mport *mport, int mbox)
{
struct tsi721_device *priv = mport->priv;
u32 i;
if (!priv->omsg_init[mbox])
return;
priv->omsg_init[mbox] = 0;
/* Disable Interrupts */
tsi721_omsg_interrupt_disable(priv, mbox, TSI721_OBDMAC_INT_ALL);
#ifdef CONFIG_PCI_MSI
if (priv->flags & TSI721_USING_MSIX) {
free_irq(priv->msix[TSI721_VECT_OMB0_DONE + mbox].vector,
(void *)mport);
free_irq(priv->msix[TSI721_VECT_OMB0_INT + mbox].vector,
(void *)mport);
}
#endif /* CONFIG_PCI_MSI */
/* Free OMSG Descriptor Status FIFO */
dma_free_coherent(&priv->pdev->dev,
priv->omsg_ring[mbox].sts_size * sizeof(struct tsi721_dma_sts),
priv->omsg_ring[mbox].sts_base,
priv->omsg_ring[mbox].sts_phys);
priv->omsg_ring[mbox].sts_base = NULL;
/* Free OMSG descriptors */
dma_free_coherent(&priv->pdev->dev,
(priv->omsg_ring[mbox].size + 1) *
sizeof(struct tsi721_omsg_desc),
priv->omsg_ring[mbox].omd_base,
priv->omsg_ring[mbox].omd_phys);
priv->omsg_ring[mbox].omd_base = NULL;
/* Free message buffers */
for (i = 0; i < priv->omsg_ring[mbox].size; i++) {
if (priv->omsg_ring[mbox].omq_base[i]) {
dma_free_coherent(&priv->pdev->dev,
TSI721_MSG_BUFFER_SIZE,
priv->omsg_ring[mbox].omq_base[i],
priv->omsg_ring[mbox].omq_phys[i]);
priv->omsg_ring[mbox].omq_base[i] = NULL;
}
}
}
/**
* tsi721_imsg_handler - Inbound Message Interrupt Handler
* @priv: pointer to tsi721 private data
* @ch: inbound message channel number to service
*
* Services channel interrupts from inbound messaging engine.
*/
static void tsi721_imsg_handler(struct tsi721_device *priv, int ch)
{
u32 mbox = ch - 4;
u32 imsg_int;
spin_lock(&priv->imsg_ring[mbox].lock);
imsg_int = ioread32(priv->regs + TSI721_IBDMAC_INT(ch));
if (imsg_int & TSI721_IBDMAC_INT_SRTO)
dev_info(&priv->pdev->dev, "IB MBOX%d SRIO timeout\n",
mbox);
if (imsg_int & TSI721_IBDMAC_INT_PC_ERROR)
dev_info(&priv->pdev->dev, "IB MBOX%d PCIe error\n",
mbox);
if (imsg_int & TSI721_IBDMAC_INT_FQ_LOW)
dev_info(&priv->pdev->dev,
"IB MBOX%d IB free queue low\n", mbox);
/* Clear IB channel interrupts */
iowrite32(imsg_int, priv->regs + TSI721_IBDMAC_INT(ch));
/* If an IB Msg is received notify the upper layer */
if (imsg_int & TSI721_IBDMAC_INT_DQ_RCV &&
priv->mport->inb_msg[mbox].mcback)
priv->mport->inb_msg[mbox].mcback(priv->mport,
priv->imsg_ring[mbox].dev_id, mbox, -1);
if (!(priv->flags & TSI721_USING_MSIX)) {
u32 ch_inte;
/* Re-enable channel interrupts */
ch_inte = ioread32(priv->regs + TSI721_DEV_CHAN_INTE);
ch_inte |= TSI721_INT_IMSG_CHAN(ch);
iowrite32(ch_inte, priv->regs + TSI721_DEV_CHAN_INTE);
}
spin_unlock(&priv->imsg_ring[mbox].lock);
}
/**
* tsi721_open_inb_mbox - Initialize Tsi721 inbound mailbox
* @mport: Master port implementing the Inbound Messaging Engine
* @dev_id: Device specific pointer to pass on event
* @mbox: Mailbox to open
* @entries: Number of entries in the inbound mailbox ring
*/
static int tsi721_open_inb_mbox(struct rio_mport *mport, void *dev_id,
int mbox, int entries)
{
struct tsi721_device *priv = mport->priv;
int ch = mbox + 4;
int i;
u64 *free_ptr;
int rc = 0;
if ((entries < TSI721_IMSGD_MIN_RING_SIZE) ||
(entries > TSI721_IMSGD_RING_SIZE) ||
(!is_power_of_2(entries)) || mbox >= RIO_MAX_MBOX) {
rc = -EINVAL;
goto out;
}
/* Initialize IB Messaging Ring */
priv->imsg_ring[mbox].dev_id = dev_id;
priv->imsg_ring[mbox].size = entries;
priv->imsg_ring[mbox].rx_slot = 0;
priv->imsg_ring[mbox].desc_rdptr = 0;
priv->imsg_ring[mbox].fq_wrptr = 0;
for (i = 0; i < priv->imsg_ring[mbox].size; i++)
priv->imsg_ring[mbox].imq_base[i] = NULL;
spin_lock_init(&priv->imsg_ring[mbox].lock);
/* Allocate buffers for incoming messages */
priv->imsg_ring[mbox].buf_base =
dma_alloc_coherent(&priv->pdev->dev,
entries * TSI721_MSG_BUFFER_SIZE,
&priv->imsg_ring[mbox].buf_phys,
GFP_KERNEL);
if (priv->imsg_ring[mbox].buf_base == NULL) {
dev_err(&priv->pdev->dev,
"Failed to allocate buffers for IB MBOX%d\n", mbox);
rc = -ENOMEM;
goto out;
}
/* Allocate memory for circular free list */
priv->imsg_ring[mbox].imfq_base =
dma_alloc_coherent(&priv->pdev->dev,
entries * 8,
&priv->imsg_ring[mbox].imfq_phys,
GFP_KERNEL);
if (priv->imsg_ring[mbox].imfq_base == NULL) {
dev_err(&priv->pdev->dev,
"Failed to allocate free queue for IB MBOX%d\n", mbox);
rc = -ENOMEM;
goto out_buf;
}
/* Allocate memory for Inbound message descriptors */
priv->imsg_ring[mbox].imd_base =
dma_alloc_coherent(&priv->pdev->dev,
entries * sizeof(struct tsi721_imsg_desc),
&priv->imsg_ring[mbox].imd_phys, GFP_KERNEL);
if (priv->imsg_ring[mbox].imd_base == NULL) {
dev_err(&priv->pdev->dev,
"Failed to allocate descriptor memory for IB MBOX%d\n",
mbox);
rc = -ENOMEM;
goto out_dma;
}
/* Fill free buffer pointer list */
free_ptr = priv->imsg_ring[mbox].imfq_base;
for (i = 0; i < entries; i++)
free_ptr[i] = cpu_to_le64(
(u64)(priv->imsg_ring[mbox].buf_phys) +
i * 0x1000);
mb();
/*
* For mapping of inbound SRIO Messages into appropriate queues we need
* to set Inbound Device ID register in the messaging engine. We do it
* once when first inbound mailbox is requested.
*/
if (!(priv->flags & TSI721_IMSGID_SET)) {
iowrite32((u32)priv->mport->host_deviceid,
priv->regs + TSI721_IB_DEVID);
priv->flags |= TSI721_IMSGID_SET;
}
/*
* Configure Inbound Messaging channel (ch = mbox + 4)
*/
/* Setup Inbound Message free queue */
iowrite32(((u64)priv->imsg_ring[mbox].imfq_phys >> 32),
priv->regs + TSI721_IBDMAC_FQBH(ch));
iowrite32(((u64)priv->imsg_ring[mbox].imfq_phys &
TSI721_IBDMAC_FQBL_MASK),
priv->regs+TSI721_IBDMAC_FQBL(ch));
iowrite32(TSI721_DMAC_DSSZ_SIZE(entries),
priv->regs + TSI721_IBDMAC_FQSZ(ch));
/* Setup Inbound Message descriptor queue */
iowrite32(((u64)priv->imsg_ring[mbox].imd_phys >> 32),
priv->regs + TSI721_IBDMAC_DQBH(ch));
iowrite32(((u32)priv->imsg_ring[mbox].imd_phys &
(u32)TSI721_IBDMAC_DQBL_MASK),
priv->regs+TSI721_IBDMAC_DQBL(ch));
iowrite32(TSI721_DMAC_DSSZ_SIZE(entries),
priv->regs + TSI721_IBDMAC_DQSZ(ch));
/* Enable interrupts */
#ifdef CONFIG_PCI_MSI
if (priv->flags & TSI721_USING_MSIX) {
/* Request interrupt service if we are in MSI-X mode */
rc = request_irq(priv->msix[TSI721_VECT_IMB0_RCV + mbox].vector,
tsi721_imsg_msix, 0,
priv->msix[TSI721_VECT_IMB0_RCV + mbox].irq_name,
(void *)mport);
if (rc) {
dev_dbg(&priv->pdev->dev,
"Unable to allocate MSI-X interrupt for "
"IBOX%d-DONE\n", mbox);
goto out_desc;
}
rc = request_irq(priv->msix[TSI721_VECT_IMB0_INT + mbox].vector,
tsi721_imsg_msix, 0,
priv->msix[TSI721_VECT_IMB0_INT + mbox].irq_name,
(void *)mport);
if (rc) {
dev_dbg(&priv->pdev->dev,
"Unable to allocate MSI-X interrupt for "
"IBOX%d-INT\n", mbox);
free_irq(
priv->msix[TSI721_VECT_IMB0_RCV + mbox].vector,
(void *)mport);
goto out_desc;
}
}
#endif /* CONFIG_PCI_MSI */
tsi721_imsg_interrupt_enable(priv, ch, TSI721_IBDMAC_INT_ALL);
/* Initialize Inbound Message Engine */
iowrite32(TSI721_IBDMAC_CTL_INIT, priv->regs + TSI721_IBDMAC_CTL(ch));
ioread32(priv->regs + TSI721_IBDMAC_CTL(ch));
udelay(10);
priv->imsg_ring[mbox].fq_wrptr = entries - 1;
iowrite32(entries - 1, priv->regs + TSI721_IBDMAC_FQWP(ch));
priv->imsg_init[mbox] = 1;
return 0;
#ifdef CONFIG_PCI_MSI
out_desc:
dma_free_coherent(&priv->pdev->dev,
priv->imsg_ring[mbox].size * sizeof(struct tsi721_imsg_desc),
priv->imsg_ring[mbox].imd_base,
priv->imsg_ring[mbox].imd_phys);
priv->imsg_ring[mbox].imd_base = NULL;
#endif /* CONFIG_PCI_MSI */
out_dma:
dma_free_coherent(&priv->pdev->dev,
priv->imsg_ring[mbox].size * 8,
priv->imsg_ring[mbox].imfq_base,
priv->imsg_ring[mbox].imfq_phys);
priv->imsg_ring[mbox].imfq_base = NULL;
out_buf:
dma_free_coherent(&priv->pdev->dev,
priv->imsg_ring[mbox].size * TSI721_MSG_BUFFER_SIZE,
priv->imsg_ring[mbox].buf_base,
priv->imsg_ring[mbox].buf_phys);
priv->imsg_ring[mbox].buf_base = NULL;
out:
return rc;
}
/**
* tsi721_close_inb_mbox - Shut down Tsi721 inbound mailbox
* @mport: Master port implementing the Inbound Messaging Engine
* @mbox: Mailbox to close
*/
static void tsi721_close_inb_mbox(struct rio_mport *mport, int mbox)
{
struct tsi721_device *priv = mport->priv;
u32 rx_slot;
int ch = mbox + 4;
if (!priv->imsg_init[mbox]) /* mbox isn't initialized yet */
return;
priv->imsg_init[mbox] = 0;
/* Disable Inbound Messaging Engine */
/* Disable Interrupts */
tsi721_imsg_interrupt_disable(priv, ch, TSI721_OBDMAC_INT_MASK);
#ifdef CONFIG_PCI_MSI
if (priv->flags & TSI721_USING_MSIX) {
free_irq(priv->msix[TSI721_VECT_IMB0_RCV + mbox].vector,
(void *)mport);
free_irq(priv->msix[TSI721_VECT_IMB0_INT + mbox].vector,
(void *)mport);
}
#endif /* CONFIG_PCI_MSI */
/* Clear Inbound Buffer Queue */
for (rx_slot = 0; rx_slot < priv->imsg_ring[mbox].size; rx_slot++)
priv->imsg_ring[mbox].imq_base[rx_slot] = NULL;
/* Free memory allocated for message buffers */
dma_free_coherent(&priv->pdev->dev,
priv->imsg_ring[mbox].size * TSI721_MSG_BUFFER_SIZE,
priv->imsg_ring[mbox].buf_base,
priv->imsg_ring[mbox].buf_phys);
priv->imsg_ring[mbox].buf_base = NULL;
/* Free memory allocated for free pointr list */
dma_free_coherent(&priv->pdev->dev,
priv->imsg_ring[mbox].size * 8,
priv->imsg_ring[mbox].imfq_base,
priv->imsg_ring[mbox].imfq_phys);
priv->imsg_ring[mbox].imfq_base = NULL;
/* Free memory allocated for RX descriptors */
dma_free_coherent(&priv->pdev->dev,
priv->imsg_ring[mbox].size * sizeof(struct tsi721_imsg_desc),
priv->imsg_ring[mbox].imd_base,
priv->imsg_ring[mbox].imd_phys);
priv->imsg_ring[mbox].imd_base = NULL;
}
/**
* tsi721_add_inb_buffer - Add buffer to the Tsi721 inbound message queue
* @mport: Master port implementing the Inbound Messaging Engine
* @mbox: Inbound mailbox number
* @buf: Buffer to add to inbound queue
*/
static int tsi721_add_inb_buffer(struct rio_mport *mport, int mbox, void *buf)
{
struct tsi721_device *priv = mport->priv;
u32 rx_slot;
int rc = 0;
rx_slot = priv->imsg_ring[mbox].rx_slot;
if (priv->imsg_ring[mbox].imq_base[rx_slot]) {
dev_err(&priv->pdev->dev,
"Error adding inbound buffer %d, buffer exists\n",
rx_slot);
rc = -EINVAL;
goto out;
}
priv->imsg_ring[mbox].imq_base[rx_slot] = buf;
if (++priv->imsg_ring[mbox].rx_slot == priv->imsg_ring[mbox].size)
priv->imsg_ring[mbox].rx_slot = 0;
out:
return rc;
}
/**
* tsi721_get_inb_message - Fetch inbound message from the Tsi721 MSG Queue
* @mport: Master port implementing the Inbound Messaging Engine
* @mbox: Inbound mailbox number
*
* Returns pointer to the message on success or NULL on failure.
*/
static void *tsi721_get_inb_message(struct rio_mport *mport, int mbox)
{
struct tsi721_device *priv = mport->priv;
struct tsi721_imsg_desc *desc;
u32 rx_slot;
void *rx_virt = NULL;
u64 rx_phys;
void *buf = NULL;
u64 *free_ptr;
int ch = mbox + 4;
int msg_size;
if (!priv->imsg_init[mbox])
return NULL;
desc = priv->imsg_ring[mbox].imd_base;
desc += priv->imsg_ring[mbox].desc_rdptr;
if (!(le32_to_cpu(desc->msg_info) & TSI721_IMD_HO))
goto out;
rx_slot = priv->imsg_ring[mbox].rx_slot;
while (priv->imsg_ring[mbox].imq_base[rx_slot] == NULL) {
if (++rx_slot == priv->imsg_ring[mbox].size)
rx_slot = 0;
}
rx_phys = ((u64)le32_to_cpu(desc->bufptr_hi) << 32) |
le32_to_cpu(desc->bufptr_lo);
rx_virt = priv->imsg_ring[mbox].buf_base +
(rx_phys - (u64)priv->imsg_ring[mbox].buf_phys);
buf = priv->imsg_ring[mbox].imq_base[rx_slot];
msg_size = le32_to_cpu(desc->msg_info) & TSI721_IMD_BCOUNT;
if (msg_size == 0)
msg_size = RIO_MAX_MSG_SIZE;
memcpy(buf, rx_virt, msg_size);
priv->imsg_ring[mbox].imq_base[rx_slot] = NULL;
desc->msg_info &= cpu_to_le32(~TSI721_IMD_HO);
if (++priv->imsg_ring[mbox].desc_rdptr == priv->imsg_ring[mbox].size)
priv->imsg_ring[mbox].desc_rdptr = 0;
iowrite32(priv->imsg_ring[mbox].desc_rdptr,
priv->regs + TSI721_IBDMAC_DQRP(ch));
/* Return free buffer into the pointer list */
free_ptr = priv->imsg_ring[mbox].imfq_base;
free_ptr[priv->imsg_ring[mbox].fq_wrptr] = cpu_to_le64(rx_phys);
if (++priv->imsg_ring[mbox].fq_wrptr == priv->imsg_ring[mbox].size)
priv->imsg_ring[mbox].fq_wrptr = 0;
iowrite32(priv->imsg_ring[mbox].fq_wrptr,
priv->regs + TSI721_IBDMAC_FQWP(ch));
out:
return buf;
}
/**
* tsi721_messages_init - Initialization of Messaging Engine
* @priv: pointer to tsi721 private data
*
* Configures Tsi721 messaging engine.
*/
static int tsi721_messages_init(struct tsi721_device *priv)
{
int ch;
iowrite32(0, priv->regs + TSI721_SMSG_ECC_LOG);
iowrite32(0, priv->regs + TSI721_RETRY_GEN_CNT);
iowrite32(0, priv->regs + TSI721_RETRY_RX_CNT);
/* Set SRIO Message Request/Response Timeout */
iowrite32(TSI721_RQRPTO_VAL, priv->regs + TSI721_RQRPTO);
/* Initialize Inbound Messaging Engine Registers */
for (ch = 0; ch < TSI721_IMSG_CHNUM; ch++) {
/* Clear interrupt bits */
iowrite32(TSI721_IBDMAC_INT_MASK,
priv->regs + TSI721_IBDMAC_INT(ch));
/* Clear Status */
iowrite32(0, priv->regs + TSI721_IBDMAC_STS(ch));
iowrite32(TSI721_SMSG_ECC_COR_LOG_MASK,
priv->regs + TSI721_SMSG_ECC_COR_LOG(ch));
iowrite32(TSI721_SMSG_ECC_NCOR_MASK,
priv->regs + TSI721_SMSG_ECC_NCOR(ch));
}
return 0;
}
/**
* tsi721_disable_ints - disables all device interrupts
* @priv: pointer to tsi721 private data
*/
static void tsi721_disable_ints(struct tsi721_device *priv)
{
int ch;
/* Disable all device level interrupts */
iowrite32(0, priv->regs + TSI721_DEV_INTE);
/* Disable all Device Channel interrupts */
iowrite32(0, priv->regs + TSI721_DEV_CHAN_INTE);
/* Disable all Inbound Msg Channel interrupts */
for (ch = 0; ch < TSI721_IMSG_CHNUM; ch++)
iowrite32(0, priv->regs + TSI721_IBDMAC_INTE(ch));
/* Disable all Outbound Msg Channel interrupts */
for (ch = 0; ch < TSI721_OMSG_CHNUM; ch++)
iowrite32(0, priv->regs + TSI721_OBDMAC_INTE(ch));
/* Disable all general messaging interrupts */
iowrite32(0, priv->regs + TSI721_SMSG_INTE);
/* Disable all BDMA Channel interrupts */
for (ch = 0; ch < TSI721_DMA_MAXCH; ch++)
iowrite32(0, priv->regs + TSI721_DMAC_INTE(ch));
/* Disable all general BDMA interrupts */
iowrite32(0, priv->regs + TSI721_BDMA_INTE);
/* Disable all SRIO Channel interrupts */
for (ch = 0; ch < TSI721_SRIO_MAXCH; ch++)
iowrite32(0, priv->regs + TSI721_SR_CHINTE(ch));
/* Disable all general SR2PC interrupts */
iowrite32(0, priv->regs + TSI721_SR2PC_GEN_INTE);
/* Disable all PC2SR interrupts */
iowrite32(0, priv->regs + TSI721_PC2SR_INTE);
/* Disable all I2C interrupts */
iowrite32(0, priv->regs + TSI721_I2C_INT_ENABLE);
/* Disable SRIO MAC interrupts */
iowrite32(0, priv->regs + TSI721_RIO_EM_INT_ENABLE);
iowrite32(0, priv->regs + TSI721_RIO_EM_DEV_INT_EN);
}
/**
* tsi721_setup_mport - Setup Tsi721 as RapidIO subsystem master port
* @priv: pointer to tsi721 private data
*
* Configures Tsi721 as RapidIO master port.
*/
static int __devinit tsi721_setup_mport(struct tsi721_device *priv)
{
struct pci_dev *pdev = priv->pdev;
int err = 0;
struct rio_ops *ops;
struct rio_mport *mport;
ops = kzalloc(sizeof(struct rio_ops), GFP_KERNEL);
if (!ops) {
dev_dbg(&pdev->dev, "Unable to allocate memory for rio_ops\n");
return -ENOMEM;
}
ops->lcread = tsi721_lcread;
ops->lcwrite = tsi721_lcwrite;
ops->cread = tsi721_cread_dma;
ops->cwrite = tsi721_cwrite_dma;
ops->dsend = tsi721_dsend;
ops->open_inb_mbox = tsi721_open_inb_mbox;
ops->close_inb_mbox = tsi721_close_inb_mbox;
ops->open_outb_mbox = tsi721_open_outb_mbox;
ops->close_outb_mbox = tsi721_close_outb_mbox;
ops->add_outb_message = tsi721_add_outb_message;
ops->add_inb_buffer = tsi721_add_inb_buffer;
ops->get_inb_message = tsi721_get_inb_message;
mport = kzalloc(sizeof(struct rio_mport), GFP_KERNEL);
if (!mport) {
kfree(ops);
dev_dbg(&pdev->dev, "Unable to allocate memory for mport\n");
return -ENOMEM;
}
mport->ops = ops;
mport->index = 0;
mport->sys_size = 0; /* small system */
mport->phy_type = RIO_PHY_SERIAL;
mport->priv = (void *)priv;
mport->phys_efptr = 0x100;
INIT_LIST_HEAD(&mport->dbells);
rio_init_dbell_res(&mport->riores[RIO_DOORBELL_RESOURCE], 0, 0xffff);
rio_init_mbox_res(&mport->riores[RIO_INB_MBOX_RESOURCE], 0, 3);
rio_init_mbox_res(&mport->riores[RIO_OUTB_MBOX_RESOURCE], 0, 3);
strcpy(mport->name, "Tsi721 mport");
/* Hook up interrupt handler */
#ifdef CONFIG_PCI_MSI
if (!tsi721_enable_msix(priv))
priv->flags |= TSI721_USING_MSIX;
else if (!pci_enable_msi(pdev))
priv->flags |= TSI721_USING_MSI;
else
dev_info(&pdev->dev,
"MSI/MSI-X is not available. Using legacy INTx.\n");
#endif /* CONFIG_PCI_MSI */
err = tsi721_request_irq(mport);
if (!err) {
tsi721_interrupts_init(priv);
ops->pwenable = tsi721_pw_enable;
} else
dev_err(&pdev->dev, "Unable to get assigned PCI IRQ "
"vector %02X err=0x%x\n", pdev->irq, err);
/* Enable SRIO link */
iowrite32(ioread32(priv->regs + TSI721_DEVCTL) |
TSI721_DEVCTL_SRBOOT_CMPL,
priv->regs + TSI721_DEVCTL);
rio_register_mport(mport);
priv->mport = mport;
if (mport->host_deviceid >= 0)
iowrite32(RIO_PORT_GEN_HOST | RIO_PORT_GEN_MASTER |
RIO_PORT_GEN_DISCOVERED,
priv->regs + (0x100 + RIO_PORT_GEN_CTL_CSR));
else
iowrite32(0, priv->regs + (0x100 + RIO_PORT_GEN_CTL_CSR));
return 0;
}
static int __devinit tsi721_probe(struct pci_dev *pdev,
const struct pci_device_id *id)
{
struct tsi721_device *priv;
int i, cap;
int err;
u32 regval;
priv = kzalloc(sizeof(struct tsi721_device), GFP_KERNEL);
if (priv == NULL) {
dev_err(&pdev->dev, "Failed to allocate memory for device\n");
err = -ENOMEM;
goto err_exit;
}
err = pci_enable_device(pdev);
if (err) {
dev_err(&pdev->dev, "Failed to enable PCI device\n");
goto err_clean;
}
priv->pdev = pdev;
#ifdef DEBUG
for (i = 0; i <= PCI_STD_RESOURCE_END; i++) {
dev_dbg(&pdev->dev, "res[%d] @ 0x%llx (0x%lx, 0x%lx)\n",
i, (unsigned long long)pci_resource_start(pdev, i),
(unsigned long)pci_resource_len(pdev, i),
pci_resource_flags(pdev, i));
}
#endif
/*
* Verify BAR configuration
*/
/* BAR_0 (registers) must be 512KB+ in 32-bit address space */
if (!(pci_resource_flags(pdev, BAR_0) & IORESOURCE_MEM) ||
pci_resource_flags(pdev, BAR_0) & IORESOURCE_MEM_64 ||
pci_resource_len(pdev, BAR_0) < TSI721_REG_SPACE_SIZE) {
dev_err(&pdev->dev,
"Missing or misconfigured CSR BAR0, aborting.\n");
err = -ENODEV;
goto err_disable_pdev;
}
/* BAR_1 (outbound doorbells) must be 16MB+ in 32-bit address space */
if (!(pci_resource_flags(pdev, BAR_1) & IORESOURCE_MEM) ||
pci_resource_flags(pdev, BAR_1) & IORESOURCE_MEM_64 ||
pci_resource_len(pdev, BAR_1) < TSI721_DB_WIN_SIZE) {
dev_err(&pdev->dev,
"Missing or misconfigured Doorbell BAR1, aborting.\n");
err = -ENODEV;
goto err_disable_pdev;
}
/*
* BAR_2 and BAR_4 (outbound translation) must be in 64-bit PCIe address
* space.
* NOTE: BAR_2 and BAR_4 are not used by this version of driver.
* It may be a good idea to keep them disabled using HW configuration
* to save PCI memory space.
*/
if ((pci_resource_flags(pdev, BAR_2) & IORESOURCE_MEM) &&
(pci_resource_flags(pdev, BAR_2) & IORESOURCE_MEM_64)) {
dev_info(&pdev->dev, "Outbound BAR2 is not used but enabled.\n");
}
if ((pci_resource_flags(pdev, BAR_4) & IORESOURCE_MEM) &&
(pci_resource_flags(pdev, BAR_4) & IORESOURCE_MEM_64)) {
dev_info(&pdev->dev, "Outbound BAR4 is not used but enabled.\n");
}
err = pci_request_regions(pdev, DRV_NAME);
if (err) {
dev_err(&pdev->dev, "Cannot obtain PCI resources, "
"aborting.\n");
goto err_disable_pdev;
}
pci_set_master(pdev);
priv->regs = pci_ioremap_bar(pdev, BAR_0);
if (!priv->regs) {
dev_err(&pdev->dev,
"Unable to map device registers space, aborting\n");
err = -ENOMEM;
goto err_free_res;
}
priv->odb_base = pci_ioremap_bar(pdev, BAR_1);
if (!priv->odb_base) {
dev_err(&pdev->dev,
"Unable to map outbound doorbells space, aborting\n");
err = -ENOMEM;
goto err_unmap_bars;
}
/* Configure DMA attributes. */
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) {
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32))) {
dev_info(&pdev->dev, "Unable to set DMA mask\n");
goto err_unmap_bars;
}
if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)))
dev_info(&pdev->dev, "Unable to set consistent DMA mask\n");
} else {
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
if (err)
dev_info(&pdev->dev, "Unable to set consistent DMA mask\n");
}
cap = pci_pcie_cap(pdev);
BUG_ON(cap == 0);
/* Clear "no snoop" and "relaxed ordering" bits, use default MRRS. */
pci_read_config_dword(pdev, cap + PCI_EXP_DEVCTL, ®val);
regval &= ~(PCI_EXP_DEVCTL_READRQ | PCI_EXP_DEVCTL_RELAX_EN |
PCI_EXP_DEVCTL_NOSNOOP_EN);
regval |= 0x2 << MAX_READ_REQUEST_SZ_SHIFT;
pci_write_config_dword(pdev, cap + PCI_EXP_DEVCTL, regval);
/* Adjust PCIe completion timeout. */
pci_read_config_dword(pdev, cap + PCI_EXP_DEVCTL2, ®val);
regval &= ~(0x0f);
pci_write_config_dword(pdev, cap + PCI_EXP_DEVCTL2, regval | 0x2);
/*
* FIXUP: correct offsets of MSI-X tables in the MSI-X Capability Block
*/
pci_write_config_dword(pdev, TSI721_PCIECFG_EPCTL, 0x01);
pci_write_config_dword(pdev, TSI721_PCIECFG_MSIXTBL,
TSI721_MSIXTBL_OFFSET);
pci_write_config_dword(pdev, TSI721_PCIECFG_MSIXPBA,
TSI721_MSIXPBA_OFFSET);
pci_write_config_dword(pdev, TSI721_PCIECFG_EPCTL, 0);
/* End of FIXUP */
tsi721_disable_ints(priv);
tsi721_init_pc2sr_mapping(priv);
tsi721_init_sr2pc_mapping(priv);
if (tsi721_bdma_init(priv)) {
dev_err(&pdev->dev, "BDMA initialization failed, aborting\n");
err = -ENOMEM;
goto err_unmap_bars;
}
err = tsi721_doorbell_init(priv);
if (err)
goto err_free_bdma;
tsi721_port_write_init(priv);
err = tsi721_messages_init(priv);
if (err)
goto err_free_consistent;
err = tsi721_setup_mport(priv);
if (err)
goto err_free_consistent;
return 0;
err_free_consistent:
tsi721_doorbell_free(priv);
err_free_bdma:
tsi721_bdma_free(priv);
err_unmap_bars:
if (priv->regs)
iounmap(priv->regs);
if (priv->odb_base)
iounmap(priv->odb_base);
err_free_res:
pci_release_regions(pdev);
pci_clear_master(pdev);
err_disable_pdev:
pci_disable_device(pdev);
err_clean:
kfree(priv);
err_exit:
return err;
}
static DEFINE_PCI_DEVICE_TABLE(tsi721_pci_tbl) = {
{ PCI_DEVICE(PCI_VENDOR_ID_IDT, PCI_DEVICE_ID_TSI721) },
{ 0, } /* terminate list */
};
MODULE_DEVICE_TABLE(pci, tsi721_pci_tbl);
static struct pci_driver tsi721_driver = {
.name = "tsi721",
.id_table = tsi721_pci_tbl,
.probe = tsi721_probe,
};
static int __init tsi721_init(void)
{
return pci_register_driver(&tsi721_driver);
}
static void __exit tsi721_exit(void)
{
pci_unregister_driver(&tsi721_driver);
}
device_initcall(tsi721_init);
| gpl-2.0 |
skelton/G5_444 | drivers/gpio/max7301.c | 3531 | 2798 | /*
* drivers/gpio/max7301.c
*
* Copyright (C) 2006 Juergen Beisert, Pengutronix
* Copyright (C) 2008 Guennadi Liakhovetski, Pengutronix
* Copyright (C) 2009 Wolfram Sang, Pengutronix
*
* 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.
*
* Check max730x.c for further details.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/spi/spi.h>
#include <linux/spi/max7301.h>
/* A write to the MAX7301 means one message with one transfer */
static int max7301_spi_write(struct device *dev, unsigned int reg,
unsigned int val)
{
struct spi_device *spi = to_spi_device(dev);
u16 word = ((reg & 0x7F) << 8) | (val & 0xFF);
return spi_write(spi, (const u8 *)&word, sizeof(word));
}
/* A read from the MAX7301 means two transfers; here, one message each */
static int max7301_spi_read(struct device *dev, unsigned int reg)
{
int ret;
u16 word;
struct spi_device *spi = to_spi_device(dev);
word = 0x8000 | (reg << 8);
ret = spi_write(spi, (const u8 *)&word, sizeof(word));
if (ret)
return ret;
/*
* This relies on the fact, that a transfer with NULL tx_buf shifts out
* zero bytes (=NOOP for MAX7301)
*/
ret = spi_read(spi, (u8 *)&word, sizeof(word));
if (ret)
return ret;
return word & 0xff;
}
static int __devinit max7301_probe(struct spi_device *spi)
{
struct max7301 *ts;
int ret;
/* bits_per_word cannot be configured in platform data */
spi->bits_per_word = 16;
ret = spi_setup(spi);
if (ret < 0)
return ret;
ts = kzalloc(sizeof(struct max7301), GFP_KERNEL);
if (!ts)
return -ENOMEM;
ts->read = max7301_spi_read;
ts->write = max7301_spi_write;
ts->dev = &spi->dev;
ret = __max730x_probe(ts);
if (ret)
kfree(ts);
return ret;
}
static int __devexit max7301_remove(struct spi_device *spi)
{
return __max730x_remove(&spi->dev);
}
static const struct spi_device_id max7301_id[] = {
{ "max7301", 0 },
{ }
};
MODULE_DEVICE_TABLE(spi, max7301_id);
static struct spi_driver max7301_driver = {
.driver = {
.name = "max7301",
.owner = THIS_MODULE,
},
.probe = max7301_probe,
.remove = __devexit_p(max7301_remove),
.id_table = max7301_id,
};
static int __init max7301_init(void)
{
return spi_register_driver(&max7301_driver);
}
/* register after spi postcore initcall and before
* subsys initcalls that may rely on these GPIOs
*/
subsys_initcall(max7301_init);
static void __exit max7301_exit(void)
{
spi_unregister_driver(&max7301_driver);
}
module_exit(max7301_exit);
MODULE_AUTHOR("Juergen Beisert, Wolfram Sang");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("MAX7301 GPIO-Expander");
| gpl-2.0 |
hyuh/kernel-jewel | arch/x86/kernel/kvmclock.c | 4043 | 6157 | /* KVM paravirtual clock driver. A clocksource implementation
Copyright (C) 2008 Glauber de Oliveira Costa, Red Hat Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/clocksource.h>
#include <linux/kvm_para.h>
#include <asm/pvclock.h>
#include <asm/msr.h>
#include <asm/apic.h>
#include <linux/percpu.h>
#include <asm/x86_init.h>
#include <asm/reboot.h>
static int kvmclock = 1;
static int msr_kvm_system_time = MSR_KVM_SYSTEM_TIME;
static int msr_kvm_wall_clock = MSR_KVM_WALL_CLOCK;
static int parse_no_kvmclock(char *arg)
{
kvmclock = 0;
return 0;
}
early_param("no-kvmclock", parse_no_kvmclock);
/* The hypervisor will put information about time periodically here */
static DEFINE_PER_CPU_SHARED_ALIGNED(struct pvclock_vcpu_time_info, hv_clock);
static struct pvclock_wall_clock wall_clock;
/*
* The wallclock is the time of day when we booted. Since then, some time may
* have elapsed since the hypervisor wrote the data. So we try to account for
* that with system time
*/
static unsigned long kvm_get_wallclock(void)
{
struct pvclock_vcpu_time_info *vcpu_time;
struct timespec ts;
int low, high;
low = (int)__pa_symbol(&wall_clock);
high = ((u64)__pa_symbol(&wall_clock) >> 32);
native_write_msr(msr_kvm_wall_clock, low, high);
vcpu_time = &get_cpu_var(hv_clock);
pvclock_read_wallclock(&wall_clock, vcpu_time, &ts);
put_cpu_var(hv_clock);
return ts.tv_sec;
}
static int kvm_set_wallclock(unsigned long now)
{
return -1;
}
static cycle_t kvm_clock_read(void)
{
struct pvclock_vcpu_time_info *src;
cycle_t ret;
preempt_disable_notrace();
src = &__get_cpu_var(hv_clock);
ret = pvclock_clocksource_read(src);
preempt_enable_notrace();
return ret;
}
static cycle_t kvm_clock_get_cycles(struct clocksource *cs)
{
return kvm_clock_read();
}
/*
* If we don't do that, there is the possibility that the guest
* will calibrate under heavy load - thus, getting a lower lpj -
* and execute the delays themselves without load. This is wrong,
* because no delay loop can finish beforehand.
* Any heuristics is subject to fail, because ultimately, a large
* poll of guests can be running and trouble each other. So we preset
* lpj here
*/
static unsigned long kvm_get_tsc_khz(void)
{
struct pvclock_vcpu_time_info *src;
src = &per_cpu(hv_clock, 0);
return pvclock_tsc_khz(src);
}
static void kvm_get_preset_lpj(void)
{
unsigned long khz;
u64 lpj;
khz = kvm_get_tsc_khz();
lpj = ((u64)khz * 1000);
do_div(lpj, HZ);
preset_lpj = lpj;
}
static struct clocksource kvm_clock = {
.name = "kvm-clock",
.read = kvm_clock_get_cycles,
.rating = 400,
.mask = CLOCKSOURCE_MASK(64),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
int kvm_register_clock(char *txt)
{
int cpu = smp_processor_id();
int low, high, ret;
low = (int)__pa(&per_cpu(hv_clock, cpu)) | 1;
high = ((u64)__pa(&per_cpu(hv_clock, cpu)) >> 32);
ret = native_write_msr_safe(msr_kvm_system_time, low, high);
printk(KERN_INFO "kvm-clock: cpu %d, msr %x:%x, %s\n",
cpu, high, low, txt);
return ret;
}
static void kvm_save_sched_clock_state(void)
{
}
static void kvm_restore_sched_clock_state(void)
{
kvm_register_clock("primary cpu clock, resume");
}
#ifdef CONFIG_X86_LOCAL_APIC
static void __cpuinit kvm_setup_secondary_clock(void)
{
/*
* Now that the first cpu already had this clocksource initialized,
* we shouldn't fail.
*/
WARN_ON(kvm_register_clock("secondary cpu clock"));
}
#endif
/*
* After the clock is registered, the host will keep writing to the
* registered memory location. If the guest happens to shutdown, this memory
* won't be valid. In cases like kexec, in which you install a new kernel, this
* means a random memory location will be kept being written. So before any
* kind of shutdown from our side, we unregister the clock by writting anything
* that does not have the 'enable' bit set in the msr
*/
#ifdef CONFIG_KEXEC
static void kvm_crash_shutdown(struct pt_regs *regs)
{
native_write_msr(msr_kvm_system_time, 0, 0);
kvm_disable_steal_time();
native_machine_crash_shutdown(regs);
}
#endif
static void kvm_shutdown(void)
{
native_write_msr(msr_kvm_system_time, 0, 0);
kvm_disable_steal_time();
native_machine_shutdown();
}
void __init kvmclock_init(void)
{
if (!kvm_para_available())
return;
if (kvmclock && kvm_para_has_feature(KVM_FEATURE_CLOCKSOURCE2)) {
msr_kvm_system_time = MSR_KVM_SYSTEM_TIME_NEW;
msr_kvm_wall_clock = MSR_KVM_WALL_CLOCK_NEW;
} else if (!(kvmclock && kvm_para_has_feature(KVM_FEATURE_CLOCKSOURCE)))
return;
printk(KERN_INFO "kvm-clock: Using msrs %x and %x",
msr_kvm_system_time, msr_kvm_wall_clock);
if (kvm_register_clock("boot clock"))
return;
pv_time_ops.sched_clock = kvm_clock_read;
x86_platform.calibrate_tsc = kvm_get_tsc_khz;
x86_platform.get_wallclock = kvm_get_wallclock;
x86_platform.set_wallclock = kvm_set_wallclock;
#ifdef CONFIG_X86_LOCAL_APIC
x86_cpuinit.early_percpu_clock_init =
kvm_setup_secondary_clock;
#endif
x86_platform.save_sched_clock_state = kvm_save_sched_clock_state;
x86_platform.restore_sched_clock_state = kvm_restore_sched_clock_state;
machine_ops.shutdown = kvm_shutdown;
#ifdef CONFIG_KEXEC
machine_ops.crash_shutdown = kvm_crash_shutdown;
#endif
kvm_get_preset_lpj();
clocksource_register_hz(&kvm_clock, NSEC_PER_SEC);
pv_info.paravirt_enabled = 1;
pv_info.name = "KVM";
if (kvm_para_has_feature(KVM_FEATURE_CLOCKSOURCE_STABLE_BIT))
pvclock_set_flags(PVCLOCK_TSC_STABLE_BIT);
}
| gpl-2.0 |
shinkumara/royss_shinkumara_kernel | drivers/net/ethernet/brocade/bna/bfa_ioc.c | 4811 | 66686 | /*
* Linux network driver for Brocade Converged Network Adapter.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (GPL) Version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
/*
* Copyright (c) 2005-2010 Brocade Communications Systems, Inc.
* All rights reserved
* www.brocade.com
*/
#include "bfa_ioc.h"
#include "bfi_reg.h"
#include "bfa_defs.h"
/**
* IOC local definitions
*/
/**
* Asic specific macros : see bfa_hw_cb.c and bfa_hw_ct.c for details.
*/
#define bfa_ioc_firmware_lock(__ioc) \
((__ioc)->ioc_hwif->ioc_firmware_lock(__ioc))
#define bfa_ioc_firmware_unlock(__ioc) \
((__ioc)->ioc_hwif->ioc_firmware_unlock(__ioc))
#define bfa_ioc_reg_init(__ioc) ((__ioc)->ioc_hwif->ioc_reg_init(__ioc))
#define bfa_ioc_map_port(__ioc) ((__ioc)->ioc_hwif->ioc_map_port(__ioc))
#define bfa_ioc_notify_fail(__ioc) \
((__ioc)->ioc_hwif->ioc_notify_fail(__ioc))
#define bfa_ioc_sync_start(__ioc) \
((__ioc)->ioc_hwif->ioc_sync_start(__ioc))
#define bfa_ioc_sync_join(__ioc) \
((__ioc)->ioc_hwif->ioc_sync_join(__ioc))
#define bfa_ioc_sync_leave(__ioc) \
((__ioc)->ioc_hwif->ioc_sync_leave(__ioc))
#define bfa_ioc_sync_ack(__ioc) \
((__ioc)->ioc_hwif->ioc_sync_ack(__ioc))
#define bfa_ioc_sync_complete(__ioc) \
((__ioc)->ioc_hwif->ioc_sync_complete(__ioc))
#define bfa_ioc_mbox_cmd_pending(__ioc) \
(!list_empty(&((__ioc)->mbox_mod.cmd_q)) || \
readl((__ioc)->ioc_regs.hfn_mbox_cmd))
static bool bfa_nw_auto_recover = true;
/*
* forward declarations
*/
static void bfa_ioc_hw_sem_init(struct bfa_ioc *ioc);
static void bfa_ioc_hw_sem_get(struct bfa_ioc *ioc);
static void bfa_ioc_hw_sem_get_cancel(struct bfa_ioc *ioc);
static void bfa_ioc_hwinit(struct bfa_ioc *ioc, bool force);
static void bfa_ioc_poll_fwinit(struct bfa_ioc *ioc);
static void bfa_ioc_send_enable(struct bfa_ioc *ioc);
static void bfa_ioc_send_disable(struct bfa_ioc *ioc);
static void bfa_ioc_send_getattr(struct bfa_ioc *ioc);
static void bfa_ioc_hb_monitor(struct bfa_ioc *ioc);
static void bfa_ioc_hb_stop(struct bfa_ioc *ioc);
static void bfa_ioc_reset(struct bfa_ioc *ioc, bool force);
static void bfa_ioc_mbox_poll(struct bfa_ioc *ioc);
static void bfa_ioc_mbox_flush(struct bfa_ioc *ioc);
static void bfa_ioc_recover(struct bfa_ioc *ioc);
static void bfa_ioc_check_attr_wwns(struct bfa_ioc *ioc);
static void bfa_ioc_event_notify(struct bfa_ioc *, enum bfa_ioc_event);
static void bfa_ioc_disable_comp(struct bfa_ioc *ioc);
static void bfa_ioc_lpu_stop(struct bfa_ioc *ioc);
static void bfa_nw_ioc_debug_save_ftrc(struct bfa_ioc *ioc);
static void bfa_ioc_fail_notify(struct bfa_ioc *ioc);
static void bfa_ioc_pf_enabled(struct bfa_ioc *ioc);
static void bfa_ioc_pf_disabled(struct bfa_ioc *ioc);
static void bfa_ioc_pf_failed(struct bfa_ioc *ioc);
static void bfa_ioc_pf_hwfailed(struct bfa_ioc *ioc);
static void bfa_ioc_pf_fwmismatch(struct bfa_ioc *ioc);
static void bfa_ioc_boot(struct bfa_ioc *ioc, u32 boot_type,
u32 boot_param);
static u32 bfa_ioc_smem_pgnum(struct bfa_ioc *ioc, u32 fmaddr);
static void bfa_ioc_get_adapter_serial_num(struct bfa_ioc *ioc,
char *serial_num);
static void bfa_ioc_get_adapter_fw_ver(struct bfa_ioc *ioc,
char *fw_ver);
static void bfa_ioc_get_pci_chip_rev(struct bfa_ioc *ioc,
char *chip_rev);
static void bfa_ioc_get_adapter_optrom_ver(struct bfa_ioc *ioc,
char *optrom_ver);
static void bfa_ioc_get_adapter_manufacturer(struct bfa_ioc *ioc,
char *manufacturer);
static void bfa_ioc_get_adapter_model(struct bfa_ioc *ioc, char *model);
static u64 bfa_ioc_get_pwwn(struct bfa_ioc *ioc);
/**
* IOC state machine definitions/declarations
*/
enum ioc_event {
IOC_E_RESET = 1, /*!< IOC reset request */
IOC_E_ENABLE = 2, /*!< IOC enable request */
IOC_E_DISABLE = 3, /*!< IOC disable request */
IOC_E_DETACH = 4, /*!< driver detach cleanup */
IOC_E_ENABLED = 5, /*!< f/w enabled */
IOC_E_FWRSP_GETATTR = 6, /*!< IOC get attribute response */
IOC_E_DISABLED = 7, /*!< f/w disabled */
IOC_E_PFFAILED = 8, /*!< failure notice by iocpf sm */
IOC_E_HBFAIL = 9, /*!< heartbeat failure */
IOC_E_HWERROR = 10, /*!< hardware error interrupt */
IOC_E_TIMEOUT = 11, /*!< timeout */
IOC_E_HWFAILED = 12, /*!< PCI mapping failure notice */
};
bfa_fsm_state_decl(bfa_ioc, uninit, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, reset, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, enabling, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, getattr, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, op, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, fail_retry, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, fail, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, disabling, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, disabled, struct bfa_ioc, enum ioc_event);
bfa_fsm_state_decl(bfa_ioc, hwfail, struct bfa_ioc, enum ioc_event);
static struct bfa_sm_table ioc_sm_table[] = {
{BFA_SM(bfa_ioc_sm_uninit), BFA_IOC_UNINIT},
{BFA_SM(bfa_ioc_sm_reset), BFA_IOC_RESET},
{BFA_SM(bfa_ioc_sm_enabling), BFA_IOC_ENABLING},
{BFA_SM(bfa_ioc_sm_getattr), BFA_IOC_GETATTR},
{BFA_SM(bfa_ioc_sm_op), BFA_IOC_OPERATIONAL},
{BFA_SM(bfa_ioc_sm_fail_retry), BFA_IOC_INITFAIL},
{BFA_SM(bfa_ioc_sm_fail), BFA_IOC_FAIL},
{BFA_SM(bfa_ioc_sm_disabling), BFA_IOC_DISABLING},
{BFA_SM(bfa_ioc_sm_disabled), BFA_IOC_DISABLED},
{BFA_SM(bfa_ioc_sm_hwfail), BFA_IOC_HWFAIL},
};
/*
* Forward declareations for iocpf state machine
*/
static void bfa_iocpf_enable(struct bfa_ioc *ioc);
static void bfa_iocpf_disable(struct bfa_ioc *ioc);
static void bfa_iocpf_fail(struct bfa_ioc *ioc);
static void bfa_iocpf_initfail(struct bfa_ioc *ioc);
static void bfa_iocpf_getattrfail(struct bfa_ioc *ioc);
static void bfa_iocpf_stop(struct bfa_ioc *ioc);
/**
* IOCPF state machine events
*/
enum iocpf_event {
IOCPF_E_ENABLE = 1, /*!< IOCPF enable request */
IOCPF_E_DISABLE = 2, /*!< IOCPF disable request */
IOCPF_E_STOP = 3, /*!< stop on driver detach */
IOCPF_E_FWREADY = 4, /*!< f/w initialization done */
IOCPF_E_FWRSP_ENABLE = 5, /*!< enable f/w response */
IOCPF_E_FWRSP_DISABLE = 6, /*!< disable f/w response */
IOCPF_E_FAIL = 7, /*!< failure notice by ioc sm */
IOCPF_E_INITFAIL = 8, /*!< init fail notice by ioc sm */
IOCPF_E_GETATTRFAIL = 9, /*!< init fail notice by ioc sm */
IOCPF_E_SEMLOCKED = 10, /*!< h/w semaphore is locked */
IOCPF_E_TIMEOUT = 11, /*!< f/w response timeout */
IOCPF_E_SEM_ERROR = 12, /*!< h/w sem mapping error */
};
/**
* IOCPF states
*/
enum bfa_iocpf_state {
BFA_IOCPF_RESET = 1, /*!< IOC is in reset state */
BFA_IOCPF_SEMWAIT = 2, /*!< Waiting for IOC h/w semaphore */
BFA_IOCPF_HWINIT = 3, /*!< IOC h/w is being initialized */
BFA_IOCPF_READY = 4, /*!< IOCPF is initialized */
BFA_IOCPF_INITFAIL = 5, /*!< IOCPF failed */
BFA_IOCPF_FAIL = 6, /*!< IOCPF failed */
BFA_IOCPF_DISABLING = 7, /*!< IOCPF is being disabled */
BFA_IOCPF_DISABLED = 8, /*!< IOCPF is disabled */
BFA_IOCPF_FWMISMATCH = 9, /*!< IOC f/w different from drivers */
};
bfa_fsm_state_decl(bfa_iocpf, reset, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, fwcheck, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, mismatch, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, semwait, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, hwinit, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, enabling, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, ready, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, initfail_sync, struct bfa_iocpf,
enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, initfail, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, fail_sync, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, fail, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, disabling, struct bfa_iocpf, enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, disabling_sync, struct bfa_iocpf,
enum iocpf_event);
bfa_fsm_state_decl(bfa_iocpf, disabled, struct bfa_iocpf, enum iocpf_event);
static struct bfa_sm_table iocpf_sm_table[] = {
{BFA_SM(bfa_iocpf_sm_reset), BFA_IOCPF_RESET},
{BFA_SM(bfa_iocpf_sm_fwcheck), BFA_IOCPF_FWMISMATCH},
{BFA_SM(bfa_iocpf_sm_mismatch), BFA_IOCPF_FWMISMATCH},
{BFA_SM(bfa_iocpf_sm_semwait), BFA_IOCPF_SEMWAIT},
{BFA_SM(bfa_iocpf_sm_hwinit), BFA_IOCPF_HWINIT},
{BFA_SM(bfa_iocpf_sm_enabling), BFA_IOCPF_HWINIT},
{BFA_SM(bfa_iocpf_sm_ready), BFA_IOCPF_READY},
{BFA_SM(bfa_iocpf_sm_initfail_sync), BFA_IOCPF_INITFAIL},
{BFA_SM(bfa_iocpf_sm_initfail), BFA_IOCPF_INITFAIL},
{BFA_SM(bfa_iocpf_sm_fail_sync), BFA_IOCPF_FAIL},
{BFA_SM(bfa_iocpf_sm_fail), BFA_IOCPF_FAIL},
{BFA_SM(bfa_iocpf_sm_disabling), BFA_IOCPF_DISABLING},
{BFA_SM(bfa_iocpf_sm_disabling_sync), BFA_IOCPF_DISABLING},
{BFA_SM(bfa_iocpf_sm_disabled), BFA_IOCPF_DISABLED},
};
/**
* IOC State Machine
*/
/**
* Beginning state. IOC uninit state.
*/
static void
bfa_ioc_sm_uninit_entry(struct bfa_ioc *ioc)
{
}
/**
* IOC is in uninit state.
*/
static void
bfa_ioc_sm_uninit(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_RESET:
bfa_fsm_set_state(ioc, bfa_ioc_sm_reset);
break;
default:
bfa_sm_fault(event);
}
}
/**
* Reset entry actions -- initialize state machine
*/
static void
bfa_ioc_sm_reset_entry(struct bfa_ioc *ioc)
{
bfa_fsm_set_state(&ioc->iocpf, bfa_iocpf_sm_reset);
}
/**
* IOC is in reset state.
*/
static void
bfa_ioc_sm_reset(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_ENABLE:
bfa_fsm_set_state(ioc, bfa_ioc_sm_enabling);
break;
case IOC_E_DISABLE:
bfa_ioc_disable_comp(ioc);
break;
case IOC_E_DETACH:
bfa_fsm_set_state(ioc, bfa_ioc_sm_uninit);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_ioc_sm_enabling_entry(struct bfa_ioc *ioc)
{
bfa_iocpf_enable(ioc);
}
/**
* Host IOC function is being enabled, awaiting response from firmware.
* Semaphore is acquired.
*/
static void
bfa_ioc_sm_enabling(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_ENABLED:
bfa_fsm_set_state(ioc, bfa_ioc_sm_getattr);
break;
case IOC_E_PFFAILED:
/* !!! fall through !!! */
case IOC_E_HWERROR:
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
bfa_fsm_set_state(ioc, bfa_ioc_sm_fail);
if (event != IOC_E_PFFAILED)
bfa_iocpf_initfail(ioc);
break;
case IOC_E_HWFAILED:
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
bfa_fsm_set_state(ioc, bfa_ioc_sm_hwfail);
break;
case IOC_E_DISABLE:
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabling);
break;
case IOC_E_DETACH:
bfa_fsm_set_state(ioc, bfa_ioc_sm_uninit);
bfa_iocpf_stop(ioc);
break;
case IOC_E_ENABLE:
break;
default:
bfa_sm_fault(event);
}
}
/**
* Semaphore should be acquired for version check.
*/
static void
bfa_ioc_sm_getattr_entry(struct bfa_ioc *ioc)
{
mod_timer(&ioc->ioc_timer, jiffies +
msecs_to_jiffies(BFA_IOC_TOV));
bfa_ioc_send_getattr(ioc);
}
/**
* IOC configuration in progress. Timer is active.
*/
static void
bfa_ioc_sm_getattr(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_FWRSP_GETATTR:
del_timer(&ioc->ioc_timer);
bfa_ioc_check_attr_wwns(ioc);
bfa_ioc_hb_monitor(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_op);
break;
case IOC_E_PFFAILED:
case IOC_E_HWERROR:
del_timer(&ioc->ioc_timer);
/* fall through */
case IOC_E_TIMEOUT:
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
bfa_fsm_set_state(ioc, bfa_ioc_sm_fail);
if (event != IOC_E_PFFAILED)
bfa_iocpf_getattrfail(ioc);
break;
case IOC_E_DISABLE:
del_timer(&ioc->ioc_timer);
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabling);
break;
case IOC_E_ENABLE:
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_ioc_sm_op_entry(struct bfa_ioc *ioc)
{
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_OK);
bfa_ioc_event_notify(ioc, BFA_IOC_E_ENABLED);
}
static void
bfa_ioc_sm_op(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_ENABLE:
break;
case IOC_E_DISABLE:
bfa_ioc_hb_stop(ioc);
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabling);
break;
case IOC_E_PFFAILED:
case IOC_E_HWERROR:
bfa_ioc_hb_stop(ioc);
/* !!! fall through !!! */
case IOC_E_HBFAIL:
if (ioc->iocpf.auto_recover)
bfa_fsm_set_state(ioc, bfa_ioc_sm_fail_retry);
else
bfa_fsm_set_state(ioc, bfa_ioc_sm_fail);
bfa_ioc_fail_notify(ioc);
if (event != IOC_E_PFFAILED)
bfa_iocpf_fail(ioc);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_ioc_sm_disabling_entry(struct bfa_ioc *ioc)
{
bfa_iocpf_disable(ioc);
}
/**
* IOC is being disabled
*/
static void
bfa_ioc_sm_disabling(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_DISABLED:
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabled);
break;
case IOC_E_HWERROR:
/*
* No state change. Will move to disabled state
* after iocpf sm completes failure processing and
* moves to disabled state.
*/
bfa_iocpf_fail(ioc);
break;
case IOC_E_HWFAILED:
bfa_fsm_set_state(ioc, bfa_ioc_sm_hwfail);
bfa_ioc_disable_comp(ioc);
break;
default:
bfa_sm_fault(event);
}
}
/**
* IOC disable completion entry.
*/
static void
bfa_ioc_sm_disabled_entry(struct bfa_ioc *ioc)
{
bfa_ioc_disable_comp(ioc);
}
static void
bfa_ioc_sm_disabled(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_ENABLE:
bfa_fsm_set_state(ioc, bfa_ioc_sm_enabling);
break;
case IOC_E_DISABLE:
ioc->cbfn->disable_cbfn(ioc->bfa);
break;
case IOC_E_DETACH:
bfa_fsm_set_state(ioc, bfa_ioc_sm_uninit);
bfa_iocpf_stop(ioc);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_ioc_sm_fail_retry_entry(struct bfa_ioc *ioc)
{
}
/**
* Hardware initialization retry.
*/
static void
bfa_ioc_sm_fail_retry(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_ENABLED:
bfa_fsm_set_state(ioc, bfa_ioc_sm_getattr);
break;
case IOC_E_PFFAILED:
case IOC_E_HWERROR:
/**
* Initialization retry failed.
*/
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
bfa_fsm_set_state(ioc, bfa_ioc_sm_fail);
if (event != IOC_E_PFFAILED)
bfa_iocpf_initfail(ioc);
break;
case IOC_E_HWFAILED:
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
bfa_fsm_set_state(ioc, bfa_ioc_sm_hwfail);
break;
case IOC_E_ENABLE:
break;
case IOC_E_DISABLE:
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabling);
break;
case IOC_E_DETACH:
bfa_fsm_set_state(ioc, bfa_ioc_sm_uninit);
bfa_iocpf_stop(ioc);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_ioc_sm_fail_entry(struct bfa_ioc *ioc)
{
}
/**
* IOC failure.
*/
static void
bfa_ioc_sm_fail(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_ENABLE:
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
break;
case IOC_E_DISABLE:
bfa_fsm_set_state(ioc, bfa_ioc_sm_disabling);
break;
case IOC_E_DETACH:
bfa_fsm_set_state(ioc, bfa_ioc_sm_uninit);
bfa_iocpf_stop(ioc);
break;
case IOC_E_HWERROR:
/* HB failure notification, ignore. */
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_ioc_sm_hwfail_entry(struct bfa_ioc *ioc)
{
}
/**
* IOC failure.
*/
static void
bfa_ioc_sm_hwfail(struct bfa_ioc *ioc, enum ioc_event event)
{
switch (event) {
case IOC_E_ENABLE:
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
break;
case IOC_E_DISABLE:
ioc->cbfn->disable_cbfn(ioc->bfa);
break;
case IOC_E_DETACH:
bfa_fsm_set_state(ioc, bfa_ioc_sm_uninit);
break;
default:
bfa_sm_fault(event);
}
}
/**
* IOCPF State Machine
*/
/**
* Reset entry actions -- initialize state machine
*/
static void
bfa_iocpf_sm_reset_entry(struct bfa_iocpf *iocpf)
{
iocpf->fw_mismatch_notified = false;
iocpf->auto_recover = bfa_nw_auto_recover;
}
/**
* Beginning state. IOC is in reset state.
*/
static void
bfa_iocpf_sm_reset(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
switch (event) {
case IOCPF_E_ENABLE:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fwcheck);
break;
case IOCPF_E_STOP:
break;
default:
bfa_sm_fault(event);
}
}
/**
* Semaphore should be acquired for version check.
*/
static void
bfa_iocpf_sm_fwcheck_entry(struct bfa_iocpf *iocpf)
{
bfa_ioc_hw_sem_init(iocpf->ioc);
bfa_ioc_hw_sem_get(iocpf->ioc);
}
/**
* Awaiting h/w semaphore to continue with version check.
*/
static void
bfa_iocpf_sm_fwcheck(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_SEMLOCKED:
if (bfa_ioc_firmware_lock(ioc)) {
if (bfa_ioc_sync_start(ioc)) {
bfa_ioc_sync_join(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_hwinit);
} else {
bfa_ioc_firmware_unlock(ioc);
bfa_nw_ioc_hw_sem_release(ioc);
mod_timer(&ioc->sem_timer, jiffies +
msecs_to_jiffies(BFA_IOC_HWSEM_TOV));
}
} else {
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_mismatch);
}
break;
case IOCPF_E_SEM_ERROR:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fail);
bfa_ioc_pf_hwfailed(ioc);
break;
case IOCPF_E_DISABLE:
bfa_ioc_hw_sem_get_cancel(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_reset);
bfa_ioc_pf_disabled(ioc);
break;
case IOCPF_E_STOP:
bfa_ioc_hw_sem_get_cancel(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_reset);
break;
default:
bfa_sm_fault(event);
}
}
/**
* Notify enable completion callback
*/
static void
bfa_iocpf_sm_mismatch_entry(struct bfa_iocpf *iocpf)
{
/* Call only the first time sm enters fwmismatch state. */
if (!iocpf->fw_mismatch_notified)
bfa_ioc_pf_fwmismatch(iocpf->ioc);
iocpf->fw_mismatch_notified = true;
mod_timer(&(iocpf->ioc)->iocpf_timer, jiffies +
msecs_to_jiffies(BFA_IOC_TOV));
}
/**
* Awaiting firmware version match.
*/
static void
bfa_iocpf_sm_mismatch(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_TIMEOUT:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fwcheck);
break;
case IOCPF_E_DISABLE:
del_timer(&ioc->iocpf_timer);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_reset);
bfa_ioc_pf_disabled(ioc);
break;
case IOCPF_E_STOP:
del_timer(&ioc->iocpf_timer);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_reset);
break;
default:
bfa_sm_fault(event);
}
}
/**
* Request for semaphore.
*/
static void
bfa_iocpf_sm_semwait_entry(struct bfa_iocpf *iocpf)
{
bfa_ioc_hw_sem_get(iocpf->ioc);
}
/**
* Awaiting semaphore for h/w initialzation.
*/
static void
bfa_iocpf_sm_semwait(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_SEMLOCKED:
if (bfa_ioc_sync_complete(ioc)) {
bfa_ioc_sync_join(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_hwinit);
} else {
bfa_nw_ioc_hw_sem_release(ioc);
mod_timer(&ioc->sem_timer, jiffies +
msecs_to_jiffies(BFA_IOC_HWSEM_TOV));
}
break;
case IOCPF_E_SEM_ERROR:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fail);
bfa_ioc_pf_hwfailed(ioc);
break;
case IOCPF_E_DISABLE:
bfa_ioc_hw_sem_get_cancel(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabling_sync);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_hwinit_entry(struct bfa_iocpf *iocpf)
{
iocpf->poll_time = 0;
bfa_ioc_reset(iocpf->ioc, false);
}
/**
* Hardware is being initialized. Interrupts are enabled.
* Holding hardware semaphore lock.
*/
static void
bfa_iocpf_sm_hwinit(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_FWREADY:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_enabling);
break;
case IOCPF_E_TIMEOUT:
bfa_nw_ioc_hw_sem_release(ioc);
bfa_ioc_pf_failed(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_initfail_sync);
break;
case IOCPF_E_DISABLE:
del_timer(&ioc->iocpf_timer);
bfa_ioc_sync_leave(ioc);
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabled);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_enabling_entry(struct bfa_iocpf *iocpf)
{
mod_timer(&(iocpf->ioc)->iocpf_timer, jiffies +
msecs_to_jiffies(BFA_IOC_TOV));
/**
* Enable Interrupts before sending fw IOC ENABLE cmd.
*/
iocpf->ioc->cbfn->reset_cbfn(iocpf->ioc->bfa);
bfa_ioc_send_enable(iocpf->ioc);
}
/**
* Host IOC function is being enabled, awaiting response from firmware.
* Semaphore is acquired.
*/
static void
bfa_iocpf_sm_enabling(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_FWRSP_ENABLE:
del_timer(&ioc->iocpf_timer);
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_ready);
break;
case IOCPF_E_INITFAIL:
del_timer(&ioc->iocpf_timer);
/*
* !!! fall through !!!
*/
case IOCPF_E_TIMEOUT:
bfa_nw_ioc_hw_sem_release(ioc);
if (event == IOCPF_E_TIMEOUT)
bfa_ioc_pf_failed(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_initfail_sync);
break;
case IOCPF_E_DISABLE:
del_timer(&ioc->iocpf_timer);
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabling);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_ready_entry(struct bfa_iocpf *iocpf)
{
bfa_ioc_pf_enabled(iocpf->ioc);
}
static void
bfa_iocpf_sm_ready(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
switch (event) {
case IOCPF_E_DISABLE:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabling);
break;
case IOCPF_E_GETATTRFAIL:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_initfail_sync);
break;
case IOCPF_E_FAIL:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fail_sync);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_disabling_entry(struct bfa_iocpf *iocpf)
{
mod_timer(&(iocpf->ioc)->iocpf_timer, jiffies +
msecs_to_jiffies(BFA_IOC_TOV));
bfa_ioc_send_disable(iocpf->ioc);
}
/**
* IOC is being disabled
*/
static void
bfa_iocpf_sm_disabling(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_FWRSP_DISABLE:
del_timer(&ioc->iocpf_timer);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabling_sync);
break;
case IOCPF_E_FAIL:
del_timer(&ioc->iocpf_timer);
/*
* !!! fall through !!!
*/
case IOCPF_E_TIMEOUT:
writel(BFI_IOC_FAIL, ioc->ioc_regs.ioc_fwstate);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabling_sync);
break;
case IOCPF_E_FWRSP_ENABLE:
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_disabling_sync_entry(struct bfa_iocpf *iocpf)
{
bfa_ioc_hw_sem_get(iocpf->ioc);
}
/**
* IOC hb ack request is being removed.
*/
static void
bfa_iocpf_sm_disabling_sync(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_SEMLOCKED:
bfa_ioc_sync_leave(ioc);
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabled);
break;
case IOCPF_E_SEM_ERROR:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fail);
bfa_ioc_pf_hwfailed(ioc);
break;
case IOCPF_E_FAIL:
break;
default:
bfa_sm_fault(event);
}
}
/**
* IOC disable completion entry.
*/
static void
bfa_iocpf_sm_disabled_entry(struct bfa_iocpf *iocpf)
{
bfa_ioc_mbox_flush(iocpf->ioc);
bfa_ioc_pf_disabled(iocpf->ioc);
}
static void
bfa_iocpf_sm_disabled(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_ENABLE:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_semwait);
break;
case IOCPF_E_STOP:
bfa_ioc_firmware_unlock(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_reset);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_initfail_sync_entry(struct bfa_iocpf *iocpf)
{
bfa_nw_ioc_debug_save_ftrc(iocpf->ioc);
bfa_ioc_hw_sem_get(iocpf->ioc);
}
/**
* Hardware initialization failed.
*/
static void
bfa_iocpf_sm_initfail_sync(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_SEMLOCKED:
bfa_ioc_notify_fail(ioc);
bfa_ioc_sync_leave(ioc);
writel(BFI_IOC_FAIL, ioc->ioc_regs.ioc_fwstate);
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_initfail);
break;
case IOCPF_E_SEM_ERROR:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fail);
bfa_ioc_pf_hwfailed(ioc);
break;
case IOCPF_E_DISABLE:
bfa_ioc_hw_sem_get_cancel(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabling_sync);
break;
case IOCPF_E_STOP:
bfa_ioc_hw_sem_get_cancel(ioc);
bfa_ioc_firmware_unlock(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_reset);
break;
case IOCPF_E_FAIL:
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_initfail_entry(struct bfa_iocpf *iocpf)
{
}
/**
* Hardware initialization failed.
*/
static void
bfa_iocpf_sm_initfail(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_DISABLE:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabled);
break;
case IOCPF_E_STOP:
bfa_ioc_firmware_unlock(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_reset);
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_fail_sync_entry(struct bfa_iocpf *iocpf)
{
/**
* Mark IOC as failed in hardware and stop firmware.
*/
bfa_ioc_lpu_stop(iocpf->ioc);
/**
* Flush any queued up mailbox requests.
*/
bfa_ioc_mbox_flush(iocpf->ioc);
bfa_ioc_hw_sem_get(iocpf->ioc);
}
/**
* IOC is in failed state.
*/
static void
bfa_iocpf_sm_fail_sync(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
struct bfa_ioc *ioc = iocpf->ioc;
switch (event) {
case IOCPF_E_SEMLOCKED:
bfa_ioc_sync_ack(ioc);
bfa_ioc_notify_fail(ioc);
if (!iocpf->auto_recover) {
bfa_ioc_sync_leave(ioc);
writel(BFI_IOC_FAIL, ioc->ioc_regs.ioc_fwstate);
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fail);
} else {
if (bfa_ioc_sync_complete(ioc))
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_hwinit);
else {
bfa_nw_ioc_hw_sem_release(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_semwait);
}
}
break;
case IOCPF_E_SEM_ERROR:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_fail);
bfa_ioc_pf_hwfailed(ioc);
break;
case IOCPF_E_DISABLE:
bfa_ioc_hw_sem_get_cancel(ioc);
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabling_sync);
break;
case IOCPF_E_FAIL:
break;
default:
bfa_sm_fault(event);
}
}
static void
bfa_iocpf_sm_fail_entry(struct bfa_iocpf *iocpf)
{
}
/**
* @brief
* IOC is in failed state.
*/
static void
bfa_iocpf_sm_fail(struct bfa_iocpf *iocpf, enum iocpf_event event)
{
switch (event) {
case IOCPF_E_DISABLE:
bfa_fsm_set_state(iocpf, bfa_iocpf_sm_disabled);
break;
default:
bfa_sm_fault(event);
}
}
/**
* BFA IOC private functions
*/
/**
* Notify common modules registered for notification.
*/
static void
bfa_ioc_event_notify(struct bfa_ioc *ioc, enum bfa_ioc_event event)
{
struct bfa_ioc_notify *notify;
struct list_head *qe;
list_for_each(qe, &ioc->notify_q) {
notify = (struct bfa_ioc_notify *)qe;
notify->cbfn(notify->cbarg, event);
}
}
static void
bfa_ioc_disable_comp(struct bfa_ioc *ioc)
{
ioc->cbfn->disable_cbfn(ioc->bfa);
bfa_ioc_event_notify(ioc, BFA_IOC_E_DISABLED);
}
bool
bfa_nw_ioc_sem_get(void __iomem *sem_reg)
{
u32 r32;
int cnt = 0;
#define BFA_SEM_SPINCNT 3000
r32 = readl(sem_reg);
while ((r32 & 1) && (cnt < BFA_SEM_SPINCNT)) {
cnt++;
udelay(2);
r32 = readl(sem_reg);
}
if (!(r32 & 1))
return true;
return false;
}
void
bfa_nw_ioc_sem_release(void __iomem *sem_reg)
{
readl(sem_reg);
writel(1, sem_reg);
}
static void
bfa_ioc_hw_sem_init(struct bfa_ioc *ioc)
{
struct bfi_ioc_image_hdr fwhdr;
u32 fwstate = readl(ioc->ioc_regs.ioc_fwstate);
if (fwstate == BFI_IOC_UNINIT)
return;
bfa_nw_ioc_fwver_get(ioc, &fwhdr);
if (swab32(fwhdr.exec) == BFI_FWBOOT_TYPE_NORMAL)
return;
writel(BFI_IOC_UNINIT, ioc->ioc_regs.ioc_fwstate);
/*
* Try to lock and then unlock the semaphore.
*/
readl(ioc->ioc_regs.ioc_sem_reg);
writel(1, ioc->ioc_regs.ioc_sem_reg);
}
static void
bfa_ioc_hw_sem_get(struct bfa_ioc *ioc)
{
u32 r32;
/**
* First read to the semaphore register will return 0, subsequent reads
* will return 1. Semaphore is released by writing 1 to the register
*/
r32 = readl(ioc->ioc_regs.ioc_sem_reg);
if (r32 == ~0) {
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_SEM_ERROR);
return;
}
if (!(r32 & 1)) {
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_SEMLOCKED);
return;
}
mod_timer(&ioc->sem_timer, jiffies +
msecs_to_jiffies(BFA_IOC_HWSEM_TOV));
}
void
bfa_nw_ioc_hw_sem_release(struct bfa_ioc *ioc)
{
writel(1, ioc->ioc_regs.ioc_sem_reg);
}
static void
bfa_ioc_hw_sem_get_cancel(struct bfa_ioc *ioc)
{
del_timer(&ioc->sem_timer);
}
/**
* @brief
* Initialize LPU local memory (aka secondary memory / SRAM)
*/
static void
bfa_ioc_lmem_init(struct bfa_ioc *ioc)
{
u32 pss_ctl;
int i;
#define PSS_LMEM_INIT_TIME 10000
pss_ctl = readl(ioc->ioc_regs.pss_ctl_reg);
pss_ctl &= ~__PSS_LMEM_RESET;
pss_ctl |= __PSS_LMEM_INIT_EN;
/*
* i2c workaround 12.5khz clock
*/
pss_ctl |= __PSS_I2C_CLK_DIV(3UL);
writel(pss_ctl, ioc->ioc_regs.pss_ctl_reg);
/**
* wait for memory initialization to be complete
*/
i = 0;
do {
pss_ctl = readl(ioc->ioc_regs.pss_ctl_reg);
i++;
} while (!(pss_ctl & __PSS_LMEM_INIT_DONE) && (i < PSS_LMEM_INIT_TIME));
/**
* If memory initialization is not successful, IOC timeout will catch
* such failures.
*/
BUG_ON(!(pss_ctl & __PSS_LMEM_INIT_DONE));
pss_ctl &= ~(__PSS_LMEM_INIT_DONE | __PSS_LMEM_INIT_EN);
writel(pss_ctl, ioc->ioc_regs.pss_ctl_reg);
}
static void
bfa_ioc_lpu_start(struct bfa_ioc *ioc)
{
u32 pss_ctl;
/**
* Take processor out of reset.
*/
pss_ctl = readl(ioc->ioc_regs.pss_ctl_reg);
pss_ctl &= ~__PSS_LPU0_RESET;
writel(pss_ctl, ioc->ioc_regs.pss_ctl_reg);
}
static void
bfa_ioc_lpu_stop(struct bfa_ioc *ioc)
{
u32 pss_ctl;
/**
* Put processors in reset.
*/
pss_ctl = readl(ioc->ioc_regs.pss_ctl_reg);
pss_ctl |= (__PSS_LPU0_RESET | __PSS_LPU1_RESET);
writel(pss_ctl, ioc->ioc_regs.pss_ctl_reg);
}
/**
* Get driver and firmware versions.
*/
void
bfa_nw_ioc_fwver_get(struct bfa_ioc *ioc, struct bfi_ioc_image_hdr *fwhdr)
{
u32 pgnum;
u32 loff = 0;
int i;
u32 *fwsig = (u32 *) fwhdr;
pgnum = bfa_ioc_smem_pgnum(ioc, loff);
writel(pgnum, ioc->ioc_regs.host_page_num_fn);
for (i = 0; i < (sizeof(struct bfi_ioc_image_hdr) / sizeof(u32));
i++) {
fwsig[i] =
swab32(readl((loff) + (ioc->ioc_regs.smem_page_start)));
loff += sizeof(u32);
}
}
/**
* Returns TRUE if same.
*/
bool
bfa_nw_ioc_fwver_cmp(struct bfa_ioc *ioc, struct bfi_ioc_image_hdr *fwhdr)
{
struct bfi_ioc_image_hdr *drv_fwhdr;
int i;
drv_fwhdr = (struct bfi_ioc_image_hdr *)
bfa_cb_image_get_chunk(bfa_ioc_asic_gen(ioc), 0);
for (i = 0; i < BFI_IOC_MD5SUM_SZ; i++) {
if (fwhdr->md5sum[i] != drv_fwhdr->md5sum[i])
return false;
}
return true;
}
/**
* Return true if current running version is valid. Firmware signature and
* execution context (driver/bios) must match.
*/
static bool
bfa_ioc_fwver_valid(struct bfa_ioc *ioc, u32 boot_env)
{
struct bfi_ioc_image_hdr fwhdr, *drv_fwhdr;
bfa_nw_ioc_fwver_get(ioc, &fwhdr);
drv_fwhdr = (struct bfi_ioc_image_hdr *)
bfa_cb_image_get_chunk(bfa_ioc_asic_gen(ioc), 0);
if (fwhdr.signature != drv_fwhdr->signature)
return false;
if (swab32(fwhdr.bootenv) != boot_env)
return false;
return bfa_nw_ioc_fwver_cmp(ioc, &fwhdr);
}
/**
* Conditionally flush any pending message from firmware at start.
*/
static void
bfa_ioc_msgflush(struct bfa_ioc *ioc)
{
u32 r32;
r32 = readl(ioc->ioc_regs.lpu_mbox_cmd);
if (r32)
writel(1, ioc->ioc_regs.lpu_mbox_cmd);
}
/**
* @img ioc_init_logic.jpg
*/
static void
bfa_ioc_hwinit(struct bfa_ioc *ioc, bool force)
{
enum bfi_ioc_state ioc_fwstate;
bool fwvalid;
u32 boot_env;
ioc_fwstate = readl(ioc->ioc_regs.ioc_fwstate);
if (force)
ioc_fwstate = BFI_IOC_UNINIT;
boot_env = BFI_FWBOOT_ENV_OS;
/**
* check if firmware is valid
*/
fwvalid = (ioc_fwstate == BFI_IOC_UNINIT) ?
false : bfa_ioc_fwver_valid(ioc, boot_env);
if (!fwvalid) {
bfa_ioc_boot(ioc, BFI_FWBOOT_TYPE_NORMAL, boot_env);
bfa_ioc_poll_fwinit(ioc);
return;
}
/**
* If hardware initialization is in progress (initialized by other IOC),
* just wait for an initialization completion interrupt.
*/
if (ioc_fwstate == BFI_IOC_INITING) {
bfa_ioc_poll_fwinit(ioc);
return;
}
/**
* If IOC function is disabled and firmware version is same,
* just re-enable IOC.
*/
if (ioc_fwstate == BFI_IOC_DISABLED || ioc_fwstate == BFI_IOC_OP) {
/**
* When using MSI-X any pending firmware ready event should
* be flushed. Otherwise MSI-X interrupts are not delivered.
*/
bfa_ioc_msgflush(ioc);
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_FWREADY);
return;
}
/**
* Initialize the h/w for any other states.
*/
bfa_ioc_boot(ioc, BFI_FWBOOT_TYPE_NORMAL, boot_env);
bfa_ioc_poll_fwinit(ioc);
}
void
bfa_nw_ioc_timeout(void *ioc_arg)
{
struct bfa_ioc *ioc = (struct bfa_ioc *) ioc_arg;
bfa_fsm_send_event(ioc, IOC_E_TIMEOUT);
}
static void
bfa_ioc_mbox_send(struct bfa_ioc *ioc, void *ioc_msg, int len)
{
u32 *msgp = (u32 *) ioc_msg;
u32 i;
BUG_ON(!(len <= BFI_IOC_MSGLEN_MAX));
/*
* first write msg to mailbox registers
*/
for (i = 0; i < len / sizeof(u32); i++)
writel(cpu_to_le32(msgp[i]),
ioc->ioc_regs.hfn_mbox + i * sizeof(u32));
for (; i < BFI_IOC_MSGLEN_MAX / sizeof(u32); i++)
writel(0, ioc->ioc_regs.hfn_mbox + i * sizeof(u32));
/*
* write 1 to mailbox CMD to trigger LPU event
*/
writel(1, ioc->ioc_regs.hfn_mbox_cmd);
(void) readl(ioc->ioc_regs.hfn_mbox_cmd);
}
static void
bfa_ioc_send_enable(struct bfa_ioc *ioc)
{
struct bfi_ioc_ctrl_req enable_req;
struct timeval tv;
bfi_h2i_set(enable_req.mh, BFI_MC_IOC, BFI_IOC_H2I_ENABLE_REQ,
bfa_ioc_portid(ioc));
enable_req.clscode = htons(ioc->clscode);
do_gettimeofday(&tv);
enable_req.tv_sec = ntohl(tv.tv_sec);
bfa_ioc_mbox_send(ioc, &enable_req, sizeof(struct bfi_ioc_ctrl_req));
}
static void
bfa_ioc_send_disable(struct bfa_ioc *ioc)
{
struct bfi_ioc_ctrl_req disable_req;
bfi_h2i_set(disable_req.mh, BFI_MC_IOC, BFI_IOC_H2I_DISABLE_REQ,
bfa_ioc_portid(ioc));
bfa_ioc_mbox_send(ioc, &disable_req, sizeof(struct bfi_ioc_ctrl_req));
}
static void
bfa_ioc_send_getattr(struct bfa_ioc *ioc)
{
struct bfi_ioc_getattr_req attr_req;
bfi_h2i_set(attr_req.mh, BFI_MC_IOC, BFI_IOC_H2I_GETATTR_REQ,
bfa_ioc_portid(ioc));
bfa_dma_be_addr_set(attr_req.attr_addr, ioc->attr_dma.pa);
bfa_ioc_mbox_send(ioc, &attr_req, sizeof(attr_req));
}
void
bfa_nw_ioc_hb_check(void *cbarg)
{
struct bfa_ioc *ioc = cbarg;
u32 hb_count;
hb_count = readl(ioc->ioc_regs.heartbeat);
if (ioc->hb_count == hb_count) {
bfa_ioc_recover(ioc);
return;
} else {
ioc->hb_count = hb_count;
}
bfa_ioc_mbox_poll(ioc);
mod_timer(&ioc->hb_timer, jiffies +
msecs_to_jiffies(BFA_IOC_HB_TOV));
}
static void
bfa_ioc_hb_monitor(struct bfa_ioc *ioc)
{
ioc->hb_count = readl(ioc->ioc_regs.heartbeat);
mod_timer(&ioc->hb_timer, jiffies +
msecs_to_jiffies(BFA_IOC_HB_TOV));
}
static void
bfa_ioc_hb_stop(struct bfa_ioc *ioc)
{
del_timer(&ioc->hb_timer);
}
/**
* @brief
* Initiate a full firmware download.
*/
static void
bfa_ioc_download_fw(struct bfa_ioc *ioc, u32 boot_type,
u32 boot_env)
{
u32 *fwimg;
u32 pgnum;
u32 loff = 0;
u32 chunkno = 0;
u32 i;
u32 asicmode;
/**
* Initialize LMEM first before code download
*/
bfa_ioc_lmem_init(ioc);
fwimg = bfa_cb_image_get_chunk(bfa_ioc_asic_gen(ioc), chunkno);
pgnum = bfa_ioc_smem_pgnum(ioc, loff);
writel(pgnum, ioc->ioc_regs.host_page_num_fn);
for (i = 0; i < bfa_cb_image_get_size(bfa_ioc_asic_gen(ioc)); i++) {
if (BFA_IOC_FLASH_CHUNK_NO(i) != chunkno) {
chunkno = BFA_IOC_FLASH_CHUNK_NO(i);
fwimg = bfa_cb_image_get_chunk(bfa_ioc_asic_gen(ioc),
BFA_IOC_FLASH_CHUNK_ADDR(chunkno));
}
/**
* write smem
*/
writel((swab32(fwimg[BFA_IOC_FLASH_OFFSET_IN_CHUNK(i)])),
((ioc->ioc_regs.smem_page_start) + (loff)));
loff += sizeof(u32);
/**
* handle page offset wrap around
*/
loff = PSS_SMEM_PGOFF(loff);
if (loff == 0) {
pgnum++;
writel(pgnum,
ioc->ioc_regs.host_page_num_fn);
}
}
writel(bfa_ioc_smem_pgnum(ioc, 0),
ioc->ioc_regs.host_page_num_fn);
/*
* Set boot type, env and device mode at the end.
*/
asicmode = BFI_FWBOOT_DEVMODE(ioc->asic_gen, ioc->asic_mode,
ioc->port0_mode, ioc->port1_mode);
writel(asicmode, ((ioc->ioc_regs.smem_page_start)
+ BFI_FWBOOT_DEVMODE_OFF));
writel(boot_type, ((ioc->ioc_regs.smem_page_start)
+ (BFI_FWBOOT_TYPE_OFF)));
writel(boot_env, ((ioc->ioc_regs.smem_page_start)
+ (BFI_FWBOOT_ENV_OFF)));
}
static void
bfa_ioc_reset(struct bfa_ioc *ioc, bool force)
{
bfa_ioc_hwinit(ioc, force);
}
/**
* BFA ioc enable reply by firmware
*/
static void
bfa_ioc_enable_reply(struct bfa_ioc *ioc, enum bfa_mode port_mode,
u8 cap_bm)
{
struct bfa_iocpf *iocpf = &ioc->iocpf;
ioc->port_mode = ioc->port_mode_cfg = port_mode;
ioc->ad_cap_bm = cap_bm;
bfa_fsm_send_event(iocpf, IOCPF_E_FWRSP_ENABLE);
}
/**
* @brief
* Update BFA configuration from firmware configuration.
*/
static void
bfa_ioc_getattr_reply(struct bfa_ioc *ioc)
{
struct bfi_ioc_attr *attr = ioc->attr;
attr->adapter_prop = ntohl(attr->adapter_prop);
attr->card_type = ntohl(attr->card_type);
attr->maxfrsize = ntohs(attr->maxfrsize);
bfa_fsm_send_event(ioc, IOC_E_FWRSP_GETATTR);
}
/**
* Attach time initialization of mbox logic.
*/
static void
bfa_ioc_mbox_attach(struct bfa_ioc *ioc)
{
struct bfa_ioc_mbox_mod *mod = &ioc->mbox_mod;
int mc;
INIT_LIST_HEAD(&mod->cmd_q);
for (mc = 0; mc < BFI_MC_MAX; mc++) {
mod->mbhdlr[mc].cbfn = NULL;
mod->mbhdlr[mc].cbarg = ioc->bfa;
}
}
/**
* Mbox poll timer -- restarts any pending mailbox requests.
*/
static void
bfa_ioc_mbox_poll(struct bfa_ioc *ioc)
{
struct bfa_ioc_mbox_mod *mod = &ioc->mbox_mod;
struct bfa_mbox_cmd *cmd;
bfa_mbox_cmd_cbfn_t cbfn;
void *cbarg;
u32 stat;
/**
* If no command pending, do nothing
*/
if (list_empty(&mod->cmd_q))
return;
/**
* If previous command is not yet fetched by firmware, do nothing
*/
stat = readl(ioc->ioc_regs.hfn_mbox_cmd);
if (stat)
return;
/**
* Enqueue command to firmware.
*/
bfa_q_deq(&mod->cmd_q, &cmd);
bfa_ioc_mbox_send(ioc, cmd->msg, sizeof(cmd->msg));
/**
* Give a callback to the client, indicating that the command is sent
*/
if (cmd->cbfn) {
cbfn = cmd->cbfn;
cbarg = cmd->cbarg;
cmd->cbfn = NULL;
cbfn(cbarg);
}
}
/**
* Cleanup any pending requests.
*/
static void
bfa_ioc_mbox_flush(struct bfa_ioc *ioc)
{
struct bfa_ioc_mbox_mod *mod = &ioc->mbox_mod;
struct bfa_mbox_cmd *cmd;
while (!list_empty(&mod->cmd_q))
bfa_q_deq(&mod->cmd_q, &cmd);
}
/**
* Read data from SMEM to host through PCI memmap
*
* @param[in] ioc memory for IOC
* @param[in] tbuf app memory to store data from smem
* @param[in] soff smem offset
* @param[in] sz size of smem in bytes
*/
static int
bfa_nw_ioc_smem_read(struct bfa_ioc *ioc, void *tbuf, u32 soff, u32 sz)
{
u32 pgnum, loff, r32;
int i, len;
u32 *buf = tbuf;
pgnum = PSS_SMEM_PGNUM(ioc->ioc_regs.smem_pg0, soff);
loff = PSS_SMEM_PGOFF(soff);
/*
* Hold semaphore to serialize pll init and fwtrc.
*/
if (bfa_nw_ioc_sem_get(ioc->ioc_regs.ioc_init_sem_reg) == 0)
return 1;
writel(pgnum, ioc->ioc_regs.host_page_num_fn);
len = sz/sizeof(u32);
for (i = 0; i < len; i++) {
r32 = swab32(readl((loff) + (ioc->ioc_regs.smem_page_start)));
buf[i] = be32_to_cpu(r32);
loff += sizeof(u32);
/**
* handle page offset wrap around
*/
loff = PSS_SMEM_PGOFF(loff);
if (loff == 0) {
pgnum++;
writel(pgnum, ioc->ioc_regs.host_page_num_fn);
}
}
writel(PSS_SMEM_PGNUM(ioc->ioc_regs.smem_pg0, 0),
ioc->ioc_regs.host_page_num_fn);
/*
* release semaphore
*/
readl(ioc->ioc_regs.ioc_init_sem_reg);
writel(1, ioc->ioc_regs.ioc_init_sem_reg);
return 0;
}
/**
* Retrieve saved firmware trace from a prior IOC failure.
*/
int
bfa_nw_ioc_debug_fwtrc(struct bfa_ioc *ioc, void *trcdata, int *trclen)
{
u32 loff = BFI_IOC_TRC_OFF + BNA_DBG_FWTRC_LEN * ioc->port_id;
int tlen, status = 0;
tlen = *trclen;
if (tlen > BNA_DBG_FWTRC_LEN)
tlen = BNA_DBG_FWTRC_LEN;
status = bfa_nw_ioc_smem_read(ioc, trcdata, loff, tlen);
*trclen = tlen;
return status;
}
/**
* Save firmware trace if configured.
*/
static void
bfa_nw_ioc_debug_save_ftrc(struct bfa_ioc *ioc)
{
int tlen;
if (ioc->dbg_fwsave_once) {
ioc->dbg_fwsave_once = 0;
if (ioc->dbg_fwsave_len) {
tlen = ioc->dbg_fwsave_len;
bfa_nw_ioc_debug_fwtrc(ioc, ioc->dbg_fwsave, &tlen);
}
}
}
/**
* Retrieve saved firmware trace from a prior IOC failure.
*/
int
bfa_nw_ioc_debug_fwsave(struct bfa_ioc *ioc, void *trcdata, int *trclen)
{
int tlen;
if (ioc->dbg_fwsave_len == 0)
return BFA_STATUS_ENOFSAVE;
tlen = *trclen;
if (tlen > ioc->dbg_fwsave_len)
tlen = ioc->dbg_fwsave_len;
memcpy(trcdata, ioc->dbg_fwsave, tlen);
*trclen = tlen;
return BFA_STATUS_OK;
}
static void
bfa_ioc_fail_notify(struct bfa_ioc *ioc)
{
/**
* Notify driver and common modules registered for notification.
*/
ioc->cbfn->hbfail_cbfn(ioc->bfa);
bfa_ioc_event_notify(ioc, BFA_IOC_E_FAILED);
bfa_nw_ioc_debug_save_ftrc(ioc);
}
/**
* IOCPF to IOC interface
*/
static void
bfa_ioc_pf_enabled(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(ioc, IOC_E_ENABLED);
}
static void
bfa_ioc_pf_disabled(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(ioc, IOC_E_DISABLED);
}
static void
bfa_ioc_pf_failed(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(ioc, IOC_E_PFFAILED);
}
static void
bfa_ioc_pf_hwfailed(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(ioc, IOC_E_HWFAILED);
}
static void
bfa_ioc_pf_fwmismatch(struct bfa_ioc *ioc)
{
/**
* Provide enable completion callback and AEN notification.
*/
ioc->cbfn->enable_cbfn(ioc->bfa, BFA_STATUS_IOC_FAILURE);
}
/**
* IOC public
*/
static enum bfa_status
bfa_ioc_pll_init(struct bfa_ioc *ioc)
{
/*
* Hold semaphore so that nobody can access the chip during init.
*/
bfa_nw_ioc_sem_get(ioc->ioc_regs.ioc_init_sem_reg);
bfa_ioc_pll_init_asic(ioc);
ioc->pllinit = true;
/*
* release semaphore.
*/
bfa_nw_ioc_sem_release(ioc->ioc_regs.ioc_init_sem_reg);
return BFA_STATUS_OK;
}
/**
* Interface used by diag module to do firmware boot with memory test
* as the entry vector.
*/
static void
bfa_ioc_boot(struct bfa_ioc *ioc, enum bfi_fwboot_type boot_type,
u32 boot_env)
{
bfa_ioc_stats(ioc, ioc_boots);
if (bfa_ioc_pll_init(ioc) != BFA_STATUS_OK)
return;
/**
* Initialize IOC state of all functions on a chip reset.
*/
if (boot_type == BFI_FWBOOT_TYPE_MEMTEST) {
writel(BFI_IOC_MEMTEST, ioc->ioc_regs.ioc_fwstate);
writel(BFI_IOC_MEMTEST, ioc->ioc_regs.alt_ioc_fwstate);
} else {
writel(BFI_IOC_INITING, ioc->ioc_regs.ioc_fwstate);
writel(BFI_IOC_INITING, ioc->ioc_regs.alt_ioc_fwstate);
}
bfa_ioc_msgflush(ioc);
bfa_ioc_download_fw(ioc, boot_type, boot_env);
bfa_ioc_lpu_start(ioc);
}
/**
* Enable/disable IOC failure auto recovery.
*/
void
bfa_nw_ioc_auto_recover(bool auto_recover)
{
bfa_nw_auto_recover = auto_recover;
}
static bool
bfa_ioc_msgget(struct bfa_ioc *ioc, void *mbmsg)
{
u32 *msgp = mbmsg;
u32 r32;
int i;
r32 = readl(ioc->ioc_regs.lpu_mbox_cmd);
if ((r32 & 1) == 0)
return false;
/**
* read the MBOX msg
*/
for (i = 0; i < (sizeof(union bfi_ioc_i2h_msg_u) / sizeof(u32));
i++) {
r32 = readl(ioc->ioc_regs.lpu_mbox +
i * sizeof(u32));
msgp[i] = htonl(r32);
}
/**
* turn off mailbox interrupt by clearing mailbox status
*/
writel(1, ioc->ioc_regs.lpu_mbox_cmd);
readl(ioc->ioc_regs.lpu_mbox_cmd);
return true;
}
static void
bfa_ioc_isr(struct bfa_ioc *ioc, struct bfi_mbmsg *m)
{
union bfi_ioc_i2h_msg_u *msg;
struct bfa_iocpf *iocpf = &ioc->iocpf;
msg = (union bfi_ioc_i2h_msg_u *) m;
bfa_ioc_stats(ioc, ioc_isrs);
switch (msg->mh.msg_id) {
case BFI_IOC_I2H_HBEAT:
break;
case BFI_IOC_I2H_ENABLE_REPLY:
bfa_ioc_enable_reply(ioc,
(enum bfa_mode)msg->fw_event.port_mode,
msg->fw_event.cap_bm);
break;
case BFI_IOC_I2H_DISABLE_REPLY:
bfa_fsm_send_event(iocpf, IOCPF_E_FWRSP_DISABLE);
break;
case BFI_IOC_I2H_GETATTR_REPLY:
bfa_ioc_getattr_reply(ioc);
break;
default:
BUG_ON(1);
}
}
/**
* IOC attach time initialization and setup.
*
* @param[in] ioc memory for IOC
* @param[in] bfa driver instance structure
*/
void
bfa_nw_ioc_attach(struct bfa_ioc *ioc, void *bfa, struct bfa_ioc_cbfn *cbfn)
{
ioc->bfa = bfa;
ioc->cbfn = cbfn;
ioc->fcmode = false;
ioc->pllinit = false;
ioc->dbg_fwsave_once = true;
ioc->iocpf.ioc = ioc;
bfa_ioc_mbox_attach(ioc);
INIT_LIST_HEAD(&ioc->notify_q);
bfa_fsm_set_state(ioc, bfa_ioc_sm_uninit);
bfa_fsm_send_event(ioc, IOC_E_RESET);
}
/**
* Driver detach time IOC cleanup.
*/
void
bfa_nw_ioc_detach(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(ioc, IOC_E_DETACH);
/* Done with detach, empty the notify_q. */
INIT_LIST_HEAD(&ioc->notify_q);
}
/**
* Setup IOC PCI properties.
*
* @param[in] pcidev PCI device information for this IOC
*/
void
bfa_nw_ioc_pci_init(struct bfa_ioc *ioc, struct bfa_pcidev *pcidev,
enum bfi_pcifn_class clscode)
{
ioc->clscode = clscode;
ioc->pcidev = *pcidev;
/**
* Initialize IOC and device personality
*/
ioc->port0_mode = ioc->port1_mode = BFI_PORT_MODE_FC;
ioc->asic_mode = BFI_ASIC_MODE_FC;
switch (pcidev->device_id) {
case PCI_DEVICE_ID_BROCADE_CT:
ioc->asic_gen = BFI_ASIC_GEN_CT;
ioc->port0_mode = ioc->port1_mode = BFI_PORT_MODE_ETH;
ioc->asic_mode = BFI_ASIC_MODE_ETH;
ioc->port_mode = ioc->port_mode_cfg = BFA_MODE_CNA;
ioc->ad_cap_bm = BFA_CM_CNA;
break;
case BFA_PCI_DEVICE_ID_CT2:
ioc->asic_gen = BFI_ASIC_GEN_CT2;
if (clscode == BFI_PCIFN_CLASS_FC &&
pcidev->ssid == BFA_PCI_CT2_SSID_FC) {
ioc->asic_mode = BFI_ASIC_MODE_FC16;
ioc->fcmode = true;
ioc->port_mode = ioc->port_mode_cfg = BFA_MODE_HBA;
ioc->ad_cap_bm = BFA_CM_HBA;
} else {
ioc->port0_mode = ioc->port1_mode = BFI_PORT_MODE_ETH;
ioc->asic_mode = BFI_ASIC_MODE_ETH;
if (pcidev->ssid == BFA_PCI_CT2_SSID_FCoE) {
ioc->port_mode =
ioc->port_mode_cfg = BFA_MODE_CNA;
ioc->ad_cap_bm = BFA_CM_CNA;
} else {
ioc->port_mode =
ioc->port_mode_cfg = BFA_MODE_NIC;
ioc->ad_cap_bm = BFA_CM_NIC;
}
}
break;
default:
BUG_ON(1);
}
/**
* Set asic specific interfaces.
*/
if (ioc->asic_gen == BFI_ASIC_GEN_CT)
bfa_nw_ioc_set_ct_hwif(ioc);
else {
WARN_ON(ioc->asic_gen != BFI_ASIC_GEN_CT2);
bfa_nw_ioc_set_ct2_hwif(ioc);
bfa_nw_ioc_ct2_poweron(ioc);
}
bfa_ioc_map_port(ioc);
bfa_ioc_reg_init(ioc);
}
/**
* Initialize IOC dma memory
*
* @param[in] dm_kva kernel virtual address of IOC dma memory
* @param[in] dm_pa physical address of IOC dma memory
*/
void
bfa_nw_ioc_mem_claim(struct bfa_ioc *ioc, u8 *dm_kva, u64 dm_pa)
{
/**
* dma memory for firmware attribute
*/
ioc->attr_dma.kva = dm_kva;
ioc->attr_dma.pa = dm_pa;
ioc->attr = (struct bfi_ioc_attr *) dm_kva;
}
/**
* Return size of dma memory required.
*/
u32
bfa_nw_ioc_meminfo(void)
{
return roundup(sizeof(struct bfi_ioc_attr), BFA_DMA_ALIGN_SZ);
}
void
bfa_nw_ioc_enable(struct bfa_ioc *ioc)
{
bfa_ioc_stats(ioc, ioc_enables);
ioc->dbg_fwsave_once = true;
bfa_fsm_send_event(ioc, IOC_E_ENABLE);
}
void
bfa_nw_ioc_disable(struct bfa_ioc *ioc)
{
bfa_ioc_stats(ioc, ioc_disables);
bfa_fsm_send_event(ioc, IOC_E_DISABLE);
}
/**
* Initialize memory for saving firmware trace.
*/
void
bfa_nw_ioc_debug_memclaim(struct bfa_ioc *ioc, void *dbg_fwsave)
{
ioc->dbg_fwsave = dbg_fwsave;
ioc->dbg_fwsave_len = ioc->iocpf.auto_recover ? BNA_DBG_FWTRC_LEN : 0;
}
static u32
bfa_ioc_smem_pgnum(struct bfa_ioc *ioc, u32 fmaddr)
{
return PSS_SMEM_PGNUM(ioc->ioc_regs.smem_pg0, fmaddr);
}
/**
* Register mailbox message handler function, to be called by common modules
*/
void
bfa_nw_ioc_mbox_regisr(struct bfa_ioc *ioc, enum bfi_mclass mc,
bfa_ioc_mbox_mcfunc_t cbfn, void *cbarg)
{
struct bfa_ioc_mbox_mod *mod = &ioc->mbox_mod;
mod->mbhdlr[mc].cbfn = cbfn;
mod->mbhdlr[mc].cbarg = cbarg;
}
/**
* Queue a mailbox command request to firmware. Waits if mailbox is busy.
* Responsibility of caller to serialize
*
* @param[in] ioc IOC instance
* @param[i] cmd Mailbox command
*/
bool
bfa_nw_ioc_mbox_queue(struct bfa_ioc *ioc, struct bfa_mbox_cmd *cmd,
bfa_mbox_cmd_cbfn_t cbfn, void *cbarg)
{
struct bfa_ioc_mbox_mod *mod = &ioc->mbox_mod;
u32 stat;
cmd->cbfn = cbfn;
cmd->cbarg = cbarg;
/**
* If a previous command is pending, queue new command
*/
if (!list_empty(&mod->cmd_q)) {
list_add_tail(&cmd->qe, &mod->cmd_q);
return true;
}
/**
* If mailbox is busy, queue command for poll timer
*/
stat = readl(ioc->ioc_regs.hfn_mbox_cmd);
if (stat) {
list_add_tail(&cmd->qe, &mod->cmd_q);
return true;
}
/**
* mailbox is free -- queue command to firmware
*/
bfa_ioc_mbox_send(ioc, cmd->msg, sizeof(cmd->msg));
return false;
}
/**
* Handle mailbox interrupts
*/
void
bfa_nw_ioc_mbox_isr(struct bfa_ioc *ioc)
{
struct bfa_ioc_mbox_mod *mod = &ioc->mbox_mod;
struct bfi_mbmsg m;
int mc;
if (bfa_ioc_msgget(ioc, &m)) {
/**
* Treat IOC message class as special.
*/
mc = m.mh.msg_class;
if (mc == BFI_MC_IOC) {
bfa_ioc_isr(ioc, &m);
return;
}
if ((mc >= BFI_MC_MAX) || (mod->mbhdlr[mc].cbfn == NULL))
return;
mod->mbhdlr[mc].cbfn(mod->mbhdlr[mc].cbarg, &m);
}
bfa_ioc_lpu_read_stat(ioc);
/**
* Try to send pending mailbox commands
*/
bfa_ioc_mbox_poll(ioc);
}
void
bfa_nw_ioc_error_isr(struct bfa_ioc *ioc)
{
bfa_ioc_stats(ioc, ioc_hbfails);
bfa_ioc_stats_hb_count(ioc, ioc->hb_count);
bfa_fsm_send_event(ioc, IOC_E_HWERROR);
}
/**
* return true if IOC is disabled
*/
bool
bfa_nw_ioc_is_disabled(struct bfa_ioc *ioc)
{
return bfa_fsm_cmp_state(ioc, bfa_ioc_sm_disabling) ||
bfa_fsm_cmp_state(ioc, bfa_ioc_sm_disabled);
}
/**
* return true if IOC is operational
*/
bool
bfa_nw_ioc_is_operational(struct bfa_ioc *ioc)
{
return bfa_fsm_cmp_state(ioc, bfa_ioc_sm_op);
}
/**
* Add to IOC heartbeat failure notification queue. To be used by common
* modules such as cee, port, diag.
*/
void
bfa_nw_ioc_notify_register(struct bfa_ioc *ioc,
struct bfa_ioc_notify *notify)
{
list_add_tail(¬ify->qe, &ioc->notify_q);
}
#define BFA_MFG_NAME "Brocade"
static void
bfa_ioc_get_adapter_attr(struct bfa_ioc *ioc,
struct bfa_adapter_attr *ad_attr)
{
struct bfi_ioc_attr *ioc_attr;
ioc_attr = ioc->attr;
bfa_ioc_get_adapter_serial_num(ioc, ad_attr->serial_num);
bfa_ioc_get_adapter_fw_ver(ioc, ad_attr->fw_ver);
bfa_ioc_get_adapter_optrom_ver(ioc, ad_attr->optrom_ver);
bfa_ioc_get_adapter_manufacturer(ioc, ad_attr->manufacturer);
memcpy(&ad_attr->vpd, &ioc_attr->vpd,
sizeof(struct bfa_mfg_vpd));
ad_attr->nports = bfa_ioc_get_nports(ioc);
ad_attr->max_speed = bfa_ioc_speed_sup(ioc);
bfa_ioc_get_adapter_model(ioc, ad_attr->model);
/* For now, model descr uses same model string */
bfa_ioc_get_adapter_model(ioc, ad_attr->model_descr);
ad_attr->card_type = ioc_attr->card_type;
ad_attr->is_mezz = bfa_mfg_is_mezz(ioc_attr->card_type);
if (BFI_ADAPTER_IS_SPECIAL(ioc_attr->adapter_prop))
ad_attr->prototype = 1;
else
ad_attr->prototype = 0;
ad_attr->pwwn = bfa_ioc_get_pwwn(ioc);
ad_attr->mac = bfa_nw_ioc_get_mac(ioc);
ad_attr->pcie_gen = ioc_attr->pcie_gen;
ad_attr->pcie_lanes = ioc_attr->pcie_lanes;
ad_attr->pcie_lanes_orig = ioc_attr->pcie_lanes_orig;
ad_attr->asic_rev = ioc_attr->asic_rev;
bfa_ioc_get_pci_chip_rev(ioc, ad_attr->hw_ver);
}
static enum bfa_ioc_type
bfa_ioc_get_type(struct bfa_ioc *ioc)
{
if (ioc->clscode == BFI_PCIFN_CLASS_ETH)
return BFA_IOC_TYPE_LL;
BUG_ON(!(ioc->clscode == BFI_PCIFN_CLASS_FC));
return (ioc->attr->port_mode == BFI_PORT_MODE_FC)
? BFA_IOC_TYPE_FC : BFA_IOC_TYPE_FCoE;
}
static void
bfa_ioc_get_adapter_serial_num(struct bfa_ioc *ioc, char *serial_num)
{
memset(serial_num, 0, BFA_ADAPTER_SERIAL_NUM_LEN);
memcpy(serial_num,
(void *)ioc->attr->brcd_serialnum,
BFA_ADAPTER_SERIAL_NUM_LEN);
}
static void
bfa_ioc_get_adapter_fw_ver(struct bfa_ioc *ioc, char *fw_ver)
{
memset(fw_ver, 0, BFA_VERSION_LEN);
memcpy(fw_ver, ioc->attr->fw_version, BFA_VERSION_LEN);
}
static void
bfa_ioc_get_pci_chip_rev(struct bfa_ioc *ioc, char *chip_rev)
{
BUG_ON(!(chip_rev));
memset(chip_rev, 0, BFA_IOC_CHIP_REV_LEN);
chip_rev[0] = 'R';
chip_rev[1] = 'e';
chip_rev[2] = 'v';
chip_rev[3] = '-';
chip_rev[4] = ioc->attr->asic_rev;
chip_rev[5] = '\0';
}
static void
bfa_ioc_get_adapter_optrom_ver(struct bfa_ioc *ioc, char *optrom_ver)
{
memset(optrom_ver, 0, BFA_VERSION_LEN);
memcpy(optrom_ver, ioc->attr->optrom_version,
BFA_VERSION_LEN);
}
static void
bfa_ioc_get_adapter_manufacturer(struct bfa_ioc *ioc, char *manufacturer)
{
memset(manufacturer, 0, BFA_ADAPTER_MFG_NAME_LEN);
memcpy(manufacturer, BFA_MFG_NAME, BFA_ADAPTER_MFG_NAME_LEN);
}
static void
bfa_ioc_get_adapter_model(struct bfa_ioc *ioc, char *model)
{
struct bfi_ioc_attr *ioc_attr;
BUG_ON(!(model));
memset(model, 0, BFA_ADAPTER_MODEL_NAME_LEN);
ioc_attr = ioc->attr;
snprintf(model, BFA_ADAPTER_MODEL_NAME_LEN, "%s-%u",
BFA_MFG_NAME, ioc_attr->card_type);
}
static enum bfa_ioc_state
bfa_ioc_get_state(struct bfa_ioc *ioc)
{
enum bfa_iocpf_state iocpf_st;
enum bfa_ioc_state ioc_st = bfa_sm_to_state(ioc_sm_table, ioc->fsm);
if (ioc_st == BFA_IOC_ENABLING ||
ioc_st == BFA_IOC_FAIL || ioc_st == BFA_IOC_INITFAIL) {
iocpf_st = bfa_sm_to_state(iocpf_sm_table, ioc->iocpf.fsm);
switch (iocpf_st) {
case BFA_IOCPF_SEMWAIT:
ioc_st = BFA_IOC_SEMWAIT;
break;
case BFA_IOCPF_HWINIT:
ioc_st = BFA_IOC_HWINIT;
break;
case BFA_IOCPF_FWMISMATCH:
ioc_st = BFA_IOC_FWMISMATCH;
break;
case BFA_IOCPF_FAIL:
ioc_st = BFA_IOC_FAIL;
break;
case BFA_IOCPF_INITFAIL:
ioc_st = BFA_IOC_INITFAIL;
break;
default:
break;
}
}
return ioc_st;
}
void
bfa_nw_ioc_get_attr(struct bfa_ioc *ioc, struct bfa_ioc_attr *ioc_attr)
{
memset((void *)ioc_attr, 0, sizeof(struct bfa_ioc_attr));
ioc_attr->state = bfa_ioc_get_state(ioc);
ioc_attr->port_id = ioc->port_id;
ioc_attr->port_mode = ioc->port_mode;
ioc_attr->port_mode_cfg = ioc->port_mode_cfg;
ioc_attr->cap_bm = ioc->ad_cap_bm;
ioc_attr->ioc_type = bfa_ioc_get_type(ioc);
bfa_ioc_get_adapter_attr(ioc, &ioc_attr->adapter_attr);
ioc_attr->pci_attr.device_id = ioc->pcidev.device_id;
ioc_attr->pci_attr.pcifn = ioc->pcidev.pci_func;
bfa_ioc_get_pci_chip_rev(ioc, ioc_attr->pci_attr.chip_rev);
}
/**
* WWN public
*/
static u64
bfa_ioc_get_pwwn(struct bfa_ioc *ioc)
{
return ioc->attr->pwwn;
}
mac_t
bfa_nw_ioc_get_mac(struct bfa_ioc *ioc)
{
return ioc->attr->mac;
}
/**
* Firmware failure detected. Start recovery actions.
*/
static void
bfa_ioc_recover(struct bfa_ioc *ioc)
{
pr_crit("Heart Beat of IOC has failed\n");
bfa_ioc_stats(ioc, ioc_hbfails);
bfa_ioc_stats_hb_count(ioc, ioc->hb_count);
bfa_fsm_send_event(ioc, IOC_E_HBFAIL);
}
static void
bfa_ioc_check_attr_wwns(struct bfa_ioc *ioc)
{
if (bfa_ioc_get_type(ioc) == BFA_IOC_TYPE_LL)
return;
}
/**
* @dg hal_iocpf_pvt BFA IOC PF private functions
* @{
*/
static void
bfa_iocpf_enable(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_ENABLE);
}
static void
bfa_iocpf_disable(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_DISABLE);
}
static void
bfa_iocpf_fail(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_FAIL);
}
static void
bfa_iocpf_initfail(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_INITFAIL);
}
static void
bfa_iocpf_getattrfail(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_GETATTRFAIL);
}
static void
bfa_iocpf_stop(struct bfa_ioc *ioc)
{
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_STOP);
}
void
bfa_nw_iocpf_timeout(void *ioc_arg)
{
struct bfa_ioc *ioc = (struct bfa_ioc *) ioc_arg;
enum bfa_iocpf_state iocpf_st;
iocpf_st = bfa_sm_to_state(iocpf_sm_table, ioc->iocpf.fsm);
if (iocpf_st == BFA_IOCPF_HWINIT)
bfa_ioc_poll_fwinit(ioc);
else
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_TIMEOUT);
}
void
bfa_nw_iocpf_sem_timeout(void *ioc_arg)
{
struct bfa_ioc *ioc = (struct bfa_ioc *) ioc_arg;
bfa_ioc_hw_sem_get(ioc);
}
static void
bfa_ioc_poll_fwinit(struct bfa_ioc *ioc)
{
u32 fwstate = readl(ioc->ioc_regs.ioc_fwstate);
if (fwstate == BFI_IOC_DISABLED) {
bfa_fsm_send_event(&ioc->iocpf, IOCPF_E_FWREADY);
return;
}
if (ioc->iocpf.poll_time >= BFA_IOC_TOV) {
bfa_nw_iocpf_timeout(ioc);
} else {
ioc->iocpf.poll_time += BFA_IOC_POLL_TOV;
mod_timer(&ioc->iocpf_timer, jiffies +
msecs_to_jiffies(BFA_IOC_POLL_TOV));
}
}
/*
* Flash module specific
*/
/*
* FLASH DMA buffer should be big enough to hold both MFG block and
* asic block(64k) at the same time and also should be 2k aligned to
* avoid write segement to cross sector boundary.
*/
#define BFA_FLASH_SEG_SZ 2048
#define BFA_FLASH_DMA_BUF_SZ \
roundup(0x010000 + sizeof(struct bfa_mfg_block), BFA_FLASH_SEG_SZ)
static void
bfa_flash_cb(struct bfa_flash *flash)
{
flash->op_busy = 0;
if (flash->cbfn)
flash->cbfn(flash->cbarg, flash->status);
}
static void
bfa_flash_notify(void *cbarg, enum bfa_ioc_event event)
{
struct bfa_flash *flash = cbarg;
switch (event) {
case BFA_IOC_E_DISABLED:
case BFA_IOC_E_FAILED:
if (flash->op_busy) {
flash->status = BFA_STATUS_IOC_FAILURE;
flash->cbfn(flash->cbarg, flash->status);
flash->op_busy = 0;
}
break;
default:
break;
}
}
/*
* Send flash write request.
*
* @param[in] cbarg - callback argument
*/
static void
bfa_flash_write_send(struct bfa_flash *flash)
{
struct bfi_flash_write_req *msg =
(struct bfi_flash_write_req *) flash->mb.msg;
u32 len;
msg->type = be32_to_cpu(flash->type);
msg->instance = flash->instance;
msg->offset = be32_to_cpu(flash->addr_off + flash->offset);
len = (flash->residue < BFA_FLASH_DMA_BUF_SZ) ?
flash->residue : BFA_FLASH_DMA_BUF_SZ;
msg->length = be32_to_cpu(len);
/* indicate if it's the last msg of the whole write operation */
msg->last = (len == flash->residue) ? 1 : 0;
bfi_h2i_set(msg->mh, BFI_MC_FLASH, BFI_FLASH_H2I_WRITE_REQ,
bfa_ioc_portid(flash->ioc));
bfa_alen_set(&msg->alen, len, flash->dbuf_pa);
memcpy(flash->dbuf_kva, flash->ubuf + flash->offset, len);
bfa_nw_ioc_mbox_queue(flash->ioc, &flash->mb, NULL, NULL);
flash->residue -= len;
flash->offset += len;
}
/*
* Send flash read request.
*
* @param[in] cbarg - callback argument
*/
static void
bfa_flash_read_send(void *cbarg)
{
struct bfa_flash *flash = cbarg;
struct bfi_flash_read_req *msg =
(struct bfi_flash_read_req *) flash->mb.msg;
u32 len;
msg->type = be32_to_cpu(flash->type);
msg->instance = flash->instance;
msg->offset = be32_to_cpu(flash->addr_off + flash->offset);
len = (flash->residue < BFA_FLASH_DMA_BUF_SZ) ?
flash->residue : BFA_FLASH_DMA_BUF_SZ;
msg->length = be32_to_cpu(len);
bfi_h2i_set(msg->mh, BFI_MC_FLASH, BFI_FLASH_H2I_READ_REQ,
bfa_ioc_portid(flash->ioc));
bfa_alen_set(&msg->alen, len, flash->dbuf_pa);
bfa_nw_ioc_mbox_queue(flash->ioc, &flash->mb, NULL, NULL);
}
/*
* Process flash response messages upon receiving interrupts.
*
* @param[in] flasharg - flash structure
* @param[in] msg - message structure
*/
static void
bfa_flash_intr(void *flasharg, struct bfi_mbmsg *msg)
{
struct bfa_flash *flash = flasharg;
u32 status;
union {
struct bfi_flash_query_rsp *query;
struct bfi_flash_write_rsp *write;
struct bfi_flash_read_rsp *read;
struct bfi_mbmsg *msg;
} m;
m.msg = msg;
/* receiving response after ioc failure */
if (!flash->op_busy && msg->mh.msg_id != BFI_FLASH_I2H_EVENT)
return;
switch (msg->mh.msg_id) {
case BFI_FLASH_I2H_QUERY_RSP:
status = be32_to_cpu(m.query->status);
if (status == BFA_STATUS_OK) {
u32 i;
struct bfa_flash_attr *attr, *f;
attr = (struct bfa_flash_attr *) flash->ubuf;
f = (struct bfa_flash_attr *) flash->dbuf_kva;
attr->status = be32_to_cpu(f->status);
attr->npart = be32_to_cpu(f->npart);
for (i = 0; i < attr->npart; i++) {
attr->part[i].part_type =
be32_to_cpu(f->part[i].part_type);
attr->part[i].part_instance =
be32_to_cpu(f->part[i].part_instance);
attr->part[i].part_off =
be32_to_cpu(f->part[i].part_off);
attr->part[i].part_size =
be32_to_cpu(f->part[i].part_size);
attr->part[i].part_len =
be32_to_cpu(f->part[i].part_len);
attr->part[i].part_status =
be32_to_cpu(f->part[i].part_status);
}
}
flash->status = status;
bfa_flash_cb(flash);
break;
case BFI_FLASH_I2H_WRITE_RSP:
status = be32_to_cpu(m.write->status);
if (status != BFA_STATUS_OK || flash->residue == 0) {
flash->status = status;
bfa_flash_cb(flash);
} else
bfa_flash_write_send(flash);
break;
case BFI_FLASH_I2H_READ_RSP:
status = be32_to_cpu(m.read->status);
if (status != BFA_STATUS_OK) {
flash->status = status;
bfa_flash_cb(flash);
} else {
u32 len = be32_to_cpu(m.read->length);
memcpy(flash->ubuf + flash->offset,
flash->dbuf_kva, len);
flash->residue -= len;
flash->offset += len;
if (flash->residue == 0) {
flash->status = status;
bfa_flash_cb(flash);
} else
bfa_flash_read_send(flash);
}
break;
case BFI_FLASH_I2H_BOOT_VER_RSP:
case BFI_FLASH_I2H_EVENT:
break;
default:
WARN_ON(1);
}
}
/*
* Flash memory info API.
*/
u32
bfa_nw_flash_meminfo(void)
{
return roundup(BFA_FLASH_DMA_BUF_SZ, BFA_DMA_ALIGN_SZ);
}
/*
* Flash attach API.
*
* @param[in] flash - flash structure
* @param[in] ioc - ioc structure
* @param[in] dev - device structure
*/
void
bfa_nw_flash_attach(struct bfa_flash *flash, struct bfa_ioc *ioc, void *dev)
{
flash->ioc = ioc;
flash->cbfn = NULL;
flash->cbarg = NULL;
flash->op_busy = 0;
bfa_nw_ioc_mbox_regisr(flash->ioc, BFI_MC_FLASH, bfa_flash_intr, flash);
bfa_q_qe_init(&flash->ioc_notify);
bfa_ioc_notify_init(&flash->ioc_notify, bfa_flash_notify, flash);
list_add_tail(&flash->ioc_notify.qe, &flash->ioc->notify_q);
}
/*
* Claim memory for flash
*
* @param[in] flash - flash structure
* @param[in] dm_kva - pointer to virtual memory address
* @param[in] dm_pa - physical memory address
*/
void
bfa_nw_flash_memclaim(struct bfa_flash *flash, u8 *dm_kva, u64 dm_pa)
{
flash->dbuf_kva = dm_kva;
flash->dbuf_pa = dm_pa;
memset(flash->dbuf_kva, 0, BFA_FLASH_DMA_BUF_SZ);
dm_kva += roundup(BFA_FLASH_DMA_BUF_SZ, BFA_DMA_ALIGN_SZ);
dm_pa += roundup(BFA_FLASH_DMA_BUF_SZ, BFA_DMA_ALIGN_SZ);
}
/*
* Get flash attribute.
*
* @param[in] flash - flash structure
* @param[in] attr - flash attribute structure
* @param[in] cbfn - callback function
* @param[in] cbarg - callback argument
*
* Return status.
*/
enum bfa_status
bfa_nw_flash_get_attr(struct bfa_flash *flash, struct bfa_flash_attr *attr,
bfa_cb_flash cbfn, void *cbarg)
{
struct bfi_flash_query_req *msg =
(struct bfi_flash_query_req *) flash->mb.msg;
if (!bfa_nw_ioc_is_operational(flash->ioc))
return BFA_STATUS_IOC_NON_OP;
if (flash->op_busy)
return BFA_STATUS_DEVBUSY;
flash->op_busy = 1;
flash->cbfn = cbfn;
flash->cbarg = cbarg;
flash->ubuf = (u8 *) attr;
bfi_h2i_set(msg->mh, BFI_MC_FLASH, BFI_FLASH_H2I_QUERY_REQ,
bfa_ioc_portid(flash->ioc));
bfa_alen_set(&msg->alen, sizeof(struct bfa_flash_attr), flash->dbuf_pa);
bfa_nw_ioc_mbox_queue(flash->ioc, &flash->mb, NULL, NULL);
return BFA_STATUS_OK;
}
/*
* Update flash partition.
*
* @param[in] flash - flash structure
* @param[in] type - flash partition type
* @param[in] instance - flash partition instance
* @param[in] buf - update data buffer
* @param[in] len - data buffer length
* @param[in] offset - offset relative to the partition starting address
* @param[in] cbfn - callback function
* @param[in] cbarg - callback argument
*
* Return status.
*/
enum bfa_status
bfa_nw_flash_update_part(struct bfa_flash *flash, u32 type, u8 instance,
void *buf, u32 len, u32 offset,
bfa_cb_flash cbfn, void *cbarg)
{
if (!bfa_nw_ioc_is_operational(flash->ioc))
return BFA_STATUS_IOC_NON_OP;
/*
* 'len' must be in word (4-byte) boundary
*/
if (!len || (len & 0x03))
return BFA_STATUS_FLASH_BAD_LEN;
if (type == BFA_FLASH_PART_MFG)
return BFA_STATUS_EINVAL;
if (flash->op_busy)
return BFA_STATUS_DEVBUSY;
flash->op_busy = 1;
flash->cbfn = cbfn;
flash->cbarg = cbarg;
flash->type = type;
flash->instance = instance;
flash->residue = len;
flash->offset = 0;
flash->addr_off = offset;
flash->ubuf = buf;
bfa_flash_write_send(flash);
return BFA_STATUS_OK;
}
/*
* Read flash partition.
*
* @param[in] flash - flash structure
* @param[in] type - flash partition type
* @param[in] instance - flash partition instance
* @param[in] buf - read data buffer
* @param[in] len - data buffer length
* @param[in] offset - offset relative to the partition starting address
* @param[in] cbfn - callback function
* @param[in] cbarg - callback argument
*
* Return status.
*/
enum bfa_status
bfa_nw_flash_read_part(struct bfa_flash *flash, u32 type, u8 instance,
void *buf, u32 len, u32 offset,
bfa_cb_flash cbfn, void *cbarg)
{
if (!bfa_nw_ioc_is_operational(flash->ioc))
return BFA_STATUS_IOC_NON_OP;
/*
* 'len' must be in word (4-byte) boundary
*/
if (!len || (len & 0x03))
return BFA_STATUS_FLASH_BAD_LEN;
if (flash->op_busy)
return BFA_STATUS_DEVBUSY;
flash->op_busy = 1;
flash->cbfn = cbfn;
flash->cbarg = cbarg;
flash->type = type;
flash->instance = instance;
flash->residue = len;
flash->offset = 0;
flash->addr_off = offset;
flash->ubuf = buf;
bfa_flash_read_send(flash);
return BFA_STATUS_OK;
}
| gpl-2.0 |
DirtyUnicorns/android_kernel_lge_g3 | drivers/net/wireless/rtlwifi/rc.c | 4811 | 7859 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#include "wifi.h"
#include "base.h"
#include "rc.h"
/*
*Finds the highest rate index we can use
*if skb is special data like DHCP/EAPOL, we set should
*it to lowest rate CCK_1M, otherwise we set rate to
*CCK11M or OFDM_54M based on wireless mode.
*/
static u8 _rtl_rc_get_highest_rix(struct rtl_priv *rtlpriv,
struct ieee80211_sta *sta,
struct sk_buff *skb, bool not_data)
{
struct rtl_mac *rtlmac = rtl_mac(rtlpriv);
struct rtl_hal *rtlhal = rtl_hal(rtlpriv);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct rtl_sta_info *sta_entry = NULL;
u8 wireless_mode = 0;
/*
*this rate is no use for true rate, firmware
*will control rate at all it just used for
*1.show in iwconfig in B/G mode
*2.in rtl_get_tcb_desc when we check rate is
* 1M we will not use FW rate but user rate.
*/
if (rtlmac->opmode == NL80211_IFTYPE_AP ||
rtlmac->opmode == NL80211_IFTYPE_ADHOC) {
if (sta) {
sta_entry = (struct rtl_sta_info *) sta->drv_priv;
wireless_mode = sta_entry->wireless_mode;
} else {
return 0;
}
} else {
wireless_mode = rtlmac->mode;
}
if (rtl_is_special_data(rtlpriv->mac80211.hw, skb, true) ||
not_data) {
return 0;
} else {
if (rtlhal->current_bandtype == BAND_ON_2_4G) {
if (wireless_mode == WIRELESS_MODE_B) {
return B_MODE_MAX_RIX;
} else if (wireless_mode == WIRELESS_MODE_G) {
return G_MODE_MAX_RIX;
} else {
if (get_rf_type(rtlphy) != RF_2T2R)
return N_MODE_MCS7_RIX;
else
return N_MODE_MCS15_RIX;
}
} else {
if (wireless_mode == WIRELESS_MODE_A) {
return A_MODE_MAX_RIX;
} else {
if (get_rf_type(rtlphy) != RF_2T2R)
return N_MODE_MCS7_RIX;
else
return N_MODE_MCS15_RIX;
}
}
}
}
static void _rtl_rc_rate_set_series(struct rtl_priv *rtlpriv,
struct ieee80211_sta *sta,
struct ieee80211_tx_rate *rate,
struct ieee80211_tx_rate_control *txrc,
u8 tries, char rix, int rtsctsenable,
bool not_data)
{
struct rtl_mac *mac = rtl_mac(rtlpriv);
u8 sgi_20 = 0, sgi_40 = 0;
if (sta) {
sgi_20 = sta->ht_cap.cap & IEEE80211_HT_CAP_SGI_20;
sgi_40 = sta->ht_cap.cap & IEEE80211_HT_CAP_SGI_40;
}
rate->count = tries;
rate->idx = rix >= 0x00 ? rix : 0x00;
if (!not_data) {
if (txrc->short_preamble)
rate->flags |= IEEE80211_TX_RC_USE_SHORT_PREAMBLE;
if (mac->opmode == NL80211_IFTYPE_AP ||
mac->opmode == NL80211_IFTYPE_ADHOC) {
if (sta && (sta->ht_cap.cap &
IEEE80211_HT_CAP_SUP_WIDTH_20_40))
rate->flags |= IEEE80211_TX_RC_40_MHZ_WIDTH;
} else {
if (mac->bw_40)
rate->flags |= IEEE80211_TX_RC_40_MHZ_WIDTH;
}
if (sgi_20 || sgi_40)
rate->flags |= IEEE80211_TX_RC_SHORT_GI;
if (sta && sta->ht_cap.ht_supported)
rate->flags |= IEEE80211_TX_RC_MCS;
}
}
static void rtl_get_rate(void *ppriv, struct ieee80211_sta *sta,
void *priv_sta, struct ieee80211_tx_rate_control *txrc)
{
struct rtl_priv *rtlpriv = ppriv;
struct sk_buff *skb = txrc->skb;
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ieee80211_tx_rate *rates = tx_info->control.rates;
__le16 fc = rtl_get_fc(skb);
u8 try_per_rate, i, rix;
bool not_data = !ieee80211_is_data(fc);
if (rate_control_send_low(sta, priv_sta, txrc))
return;
rix = _rtl_rc_get_highest_rix(rtlpriv, sta, skb, not_data);
try_per_rate = 1;
_rtl_rc_rate_set_series(rtlpriv, sta, &rates[0], txrc,
try_per_rate, rix, 1, not_data);
if (!not_data) {
for (i = 1; i < 4; i++)
_rtl_rc_rate_set_series(rtlpriv, sta, &rates[i],
txrc, i, (rix - i), 1,
not_data);
}
}
static bool _rtl_tx_aggr_check(struct rtl_priv *rtlpriv,
struct rtl_sta_info *sta_entry, u16 tid)
{
struct rtl_mac *mac = rtl_mac(rtlpriv);
if (mac->act_scanning)
return false;
if (mac->opmode == NL80211_IFTYPE_STATION &&
mac->cnt_after_linked < 3)
return false;
if (sta_entry->tids[tid].agg.agg_state == RTL_AGG_STOP)
return true;
return false;
}
/*mac80211 Rate Control callbacks*/
static void rtl_tx_status(void *ppriv,
struct ieee80211_supported_band *sband,
struct ieee80211_sta *sta, void *priv_sta,
struct sk_buff *skb)
{
struct rtl_priv *rtlpriv = ppriv;
struct rtl_mac *mac = rtl_mac(rtlpriv);
struct ieee80211_hdr *hdr = rtl_get_hdr(skb);
__le16 fc = rtl_get_fc(skb);
struct rtl_sta_info *sta_entry;
if (!priv_sta || !ieee80211_is_data(fc))
return;
if (rtl_is_special_data(mac->hw, skb, true))
return;
if (is_multicast_ether_addr(ieee80211_get_DA(hdr))
|| is_broadcast_ether_addr(ieee80211_get_DA(hdr)))
return;
if (sta) {
/* Check if aggregation has to be enabled for this tid */
sta_entry = (struct rtl_sta_info *) sta->drv_priv;
if ((sta->ht_cap.ht_supported) &&
!(skb->protocol == cpu_to_be16(ETH_P_PAE))) {
if (ieee80211_is_data_qos(fc)) {
u8 tid = rtl_get_tid(skb);
if (_rtl_tx_aggr_check(rtlpriv, sta_entry,
tid)) {
sta_entry->tids[tid].agg.agg_state =
RTL_AGG_PROGRESS;
ieee80211_start_tx_ba_session(sta,
tid, 5000);
}
}
}
}
}
static void rtl_rate_init(void *ppriv,
struct ieee80211_supported_band *sband,
struct ieee80211_sta *sta, void *priv_sta)
{
}
static void rtl_rate_update(void *ppriv,
struct ieee80211_supported_band *sband,
struct ieee80211_sta *sta, void *priv_sta,
u32 changed,
enum nl80211_channel_type oper_chan_type)
{
}
static void *rtl_rate_alloc(struct ieee80211_hw *hw,
struct dentry *debugfsdir)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
return rtlpriv;
}
static void rtl_rate_free(void *rtlpriv)
{
return;
}
static void *rtl_rate_alloc_sta(void *ppriv,
struct ieee80211_sta *sta, gfp_t gfp)
{
struct rtl_priv *rtlpriv = ppriv;
struct rtl_rate_priv *rate_priv;
rate_priv = kzalloc(sizeof(struct rtl_rate_priv), gfp);
if (!rate_priv) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Unable to allocate private rc structure\n");
return NULL;
}
rtlpriv->rate_priv = rate_priv;
return rate_priv;
}
static void rtl_rate_free_sta(void *rtlpriv,
struct ieee80211_sta *sta, void *priv_sta)
{
struct rtl_rate_priv *rate_priv = priv_sta;
kfree(rate_priv);
}
static struct rate_control_ops rtl_rate_ops = {
.module = NULL,
.name = "rtl_rc",
.alloc = rtl_rate_alloc,
.free = rtl_rate_free,
.alloc_sta = rtl_rate_alloc_sta,
.free_sta = rtl_rate_free_sta,
.rate_init = rtl_rate_init,
.rate_update = rtl_rate_update,
.tx_status = rtl_tx_status,
.get_rate = rtl_get_rate,
};
int rtl_rate_control_register(void)
{
return ieee80211_rate_control_register(&rtl_rate_ops);
}
void rtl_rate_control_unregister(void)
{
ieee80211_rate_control_unregister(&rtl_rate_ops);
}
| gpl-2.0 |
VM12/android_kernel_oneplus_msm8974 | drivers/media/video/s5p-tv/hdmi_drv.c | 4811 | 28090 | /*
* Samsung HDMI interface driver
*
* Copyright (c) 2010-2011 Samsung Electronics Co., Ltd.
*
* Tomasz Stanislawski, <t.stanislaws@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundiation. either version 2 of the License,
* or (at your option) any later version
*/
#ifdef CONFIG_VIDEO_SAMSUNG_S5P_HDMI_DEBUG
#define DEBUG
#endif
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/io.h>
#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <media/v4l2-subdev.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/bug.h>
#include <linux/pm_runtime.h>
#include <linux/clk.h>
#include <linux/regulator/consumer.h>
#include <media/s5p_hdmi.h>
#include <media/v4l2-common.h>
#include <media/v4l2-dev.h>
#include <media/v4l2-device.h>
#include "regs-hdmi.h"
MODULE_AUTHOR("Tomasz Stanislawski, <t.stanislaws@samsung.com>");
MODULE_DESCRIPTION("Samsung HDMI");
MODULE_LICENSE("GPL");
/* default preset configured on probe */
#define HDMI_DEFAULT_PRESET V4L2_DV_1080P60
struct hdmi_resources {
struct clk *hdmi;
struct clk *sclk_hdmi;
struct clk *sclk_pixel;
struct clk *sclk_hdmiphy;
struct clk *hdmiphy;
struct regulator_bulk_data *regul_bulk;
int regul_count;
};
struct hdmi_device {
/** base address of HDMI registers */
void __iomem *regs;
/** HDMI interrupt */
unsigned int irq;
/** pointer to device parent */
struct device *dev;
/** subdev generated by HDMI device */
struct v4l2_subdev sd;
/** V4L2 device structure */
struct v4l2_device v4l2_dev;
/** subdev of HDMIPHY interface */
struct v4l2_subdev *phy_sd;
/** subdev of MHL interface */
struct v4l2_subdev *mhl_sd;
/** configuration of current graphic mode */
const struct hdmi_preset_conf *cur_conf;
/** current preset */
u32 cur_preset;
/** other resources */
struct hdmi_resources res;
};
struct hdmi_tg_regs {
u8 cmd;
u8 h_fsz_l;
u8 h_fsz_h;
u8 hact_st_l;
u8 hact_st_h;
u8 hact_sz_l;
u8 hact_sz_h;
u8 v_fsz_l;
u8 v_fsz_h;
u8 vsync_l;
u8 vsync_h;
u8 vsync2_l;
u8 vsync2_h;
u8 vact_st_l;
u8 vact_st_h;
u8 vact_sz_l;
u8 vact_sz_h;
u8 field_chg_l;
u8 field_chg_h;
u8 vact_st2_l;
u8 vact_st2_h;
u8 vsync_top_hdmi_l;
u8 vsync_top_hdmi_h;
u8 vsync_bot_hdmi_l;
u8 vsync_bot_hdmi_h;
u8 field_top_hdmi_l;
u8 field_top_hdmi_h;
u8 field_bot_hdmi_l;
u8 field_bot_hdmi_h;
};
struct hdmi_core_regs {
u8 h_blank[2];
u8 v_blank[3];
u8 h_v_line[3];
u8 vsync_pol[1];
u8 int_pro_mode[1];
u8 v_blank_f[3];
u8 h_sync_gen[3];
u8 v_sync_gen1[3];
u8 v_sync_gen2[3];
u8 v_sync_gen3[3];
};
struct hdmi_preset_conf {
struct hdmi_core_regs core;
struct hdmi_tg_regs tg;
struct v4l2_mbus_framefmt mbus_fmt;
};
static struct platform_device_id hdmi_driver_types[] = {
{
.name = "s5pv210-hdmi",
}, {
.name = "exynos4-hdmi",
}, {
/* end node */
}
};
static const struct v4l2_subdev_ops hdmi_sd_ops;
static struct hdmi_device *sd_to_hdmi_dev(struct v4l2_subdev *sd)
{
return container_of(sd, struct hdmi_device, sd);
}
static inline
void hdmi_write(struct hdmi_device *hdev, u32 reg_id, u32 value)
{
writel(value, hdev->regs + reg_id);
}
static inline
void hdmi_write_mask(struct hdmi_device *hdev, u32 reg_id, u32 value, u32 mask)
{
u32 old = readl(hdev->regs + reg_id);
value = (value & mask) | (old & ~mask);
writel(value, hdev->regs + reg_id);
}
static inline
void hdmi_writeb(struct hdmi_device *hdev, u32 reg_id, u8 value)
{
writeb(value, hdev->regs + reg_id);
}
static inline u32 hdmi_read(struct hdmi_device *hdev, u32 reg_id)
{
return readl(hdev->regs + reg_id);
}
static irqreturn_t hdmi_irq_handler(int irq, void *dev_data)
{
struct hdmi_device *hdev = dev_data;
u32 intc_flag;
(void)irq;
intc_flag = hdmi_read(hdev, HDMI_INTC_FLAG);
/* clearing flags for HPD plug/unplug */
if (intc_flag & HDMI_INTC_FLAG_HPD_UNPLUG) {
printk(KERN_INFO "unplugged\n");
hdmi_write_mask(hdev, HDMI_INTC_FLAG, ~0,
HDMI_INTC_FLAG_HPD_UNPLUG);
}
if (intc_flag & HDMI_INTC_FLAG_HPD_PLUG) {
printk(KERN_INFO "plugged\n");
hdmi_write_mask(hdev, HDMI_INTC_FLAG, ~0,
HDMI_INTC_FLAG_HPD_PLUG);
}
return IRQ_HANDLED;
}
static void hdmi_reg_init(struct hdmi_device *hdev)
{
/* enable HPD interrupts */
hdmi_write_mask(hdev, HDMI_INTC_CON, ~0, HDMI_INTC_EN_GLOBAL |
HDMI_INTC_EN_HPD_PLUG | HDMI_INTC_EN_HPD_UNPLUG);
/* choose DVI mode */
hdmi_write_mask(hdev, HDMI_MODE_SEL,
HDMI_MODE_DVI_EN, HDMI_MODE_MASK);
hdmi_write_mask(hdev, HDMI_CON_2, ~0,
HDMI_DVI_PERAMBLE_EN | HDMI_DVI_BAND_EN);
/* disable bluescreen */
hdmi_write_mask(hdev, HDMI_CON_0, 0, HDMI_BLUE_SCR_EN);
/* choose bluescreen (fecal) color */
hdmi_writeb(hdev, HDMI_BLUE_SCREEN_0, 0x12);
hdmi_writeb(hdev, HDMI_BLUE_SCREEN_1, 0x34);
hdmi_writeb(hdev, HDMI_BLUE_SCREEN_2, 0x56);
}
static void hdmi_timing_apply(struct hdmi_device *hdev,
const struct hdmi_preset_conf *conf)
{
const struct hdmi_core_regs *core = &conf->core;
const struct hdmi_tg_regs *tg = &conf->tg;
/* setting core registers */
hdmi_writeb(hdev, HDMI_H_BLANK_0, core->h_blank[0]);
hdmi_writeb(hdev, HDMI_H_BLANK_1, core->h_blank[1]);
hdmi_writeb(hdev, HDMI_V_BLANK_0, core->v_blank[0]);
hdmi_writeb(hdev, HDMI_V_BLANK_1, core->v_blank[1]);
hdmi_writeb(hdev, HDMI_V_BLANK_2, core->v_blank[2]);
hdmi_writeb(hdev, HDMI_H_V_LINE_0, core->h_v_line[0]);
hdmi_writeb(hdev, HDMI_H_V_LINE_1, core->h_v_line[1]);
hdmi_writeb(hdev, HDMI_H_V_LINE_2, core->h_v_line[2]);
hdmi_writeb(hdev, HDMI_VSYNC_POL, core->vsync_pol[0]);
hdmi_writeb(hdev, HDMI_INT_PRO_MODE, core->int_pro_mode[0]);
hdmi_writeb(hdev, HDMI_V_BLANK_F_0, core->v_blank_f[0]);
hdmi_writeb(hdev, HDMI_V_BLANK_F_1, core->v_blank_f[1]);
hdmi_writeb(hdev, HDMI_V_BLANK_F_2, core->v_blank_f[2]);
hdmi_writeb(hdev, HDMI_H_SYNC_GEN_0, core->h_sync_gen[0]);
hdmi_writeb(hdev, HDMI_H_SYNC_GEN_1, core->h_sync_gen[1]);
hdmi_writeb(hdev, HDMI_H_SYNC_GEN_2, core->h_sync_gen[2]);
hdmi_writeb(hdev, HDMI_V_SYNC_GEN_1_0, core->v_sync_gen1[0]);
hdmi_writeb(hdev, HDMI_V_SYNC_GEN_1_1, core->v_sync_gen1[1]);
hdmi_writeb(hdev, HDMI_V_SYNC_GEN_1_2, core->v_sync_gen1[2]);
hdmi_writeb(hdev, HDMI_V_SYNC_GEN_2_0, core->v_sync_gen2[0]);
hdmi_writeb(hdev, HDMI_V_SYNC_GEN_2_1, core->v_sync_gen2[1]);
hdmi_writeb(hdev, HDMI_V_SYNC_GEN_2_2, core->v_sync_gen2[2]);
hdmi_writeb(hdev, HDMI_V_SYNC_GEN_3_0, core->v_sync_gen3[0]);
hdmi_writeb(hdev, HDMI_V_SYNC_GEN_3_1, core->v_sync_gen3[1]);
hdmi_writeb(hdev, HDMI_V_SYNC_GEN_3_2, core->v_sync_gen3[2]);
/* Timing generator registers */
hdmi_writeb(hdev, HDMI_TG_H_FSZ_L, tg->h_fsz_l);
hdmi_writeb(hdev, HDMI_TG_H_FSZ_H, tg->h_fsz_h);
hdmi_writeb(hdev, HDMI_TG_HACT_ST_L, tg->hact_st_l);
hdmi_writeb(hdev, HDMI_TG_HACT_ST_H, tg->hact_st_h);
hdmi_writeb(hdev, HDMI_TG_HACT_SZ_L, tg->hact_sz_l);
hdmi_writeb(hdev, HDMI_TG_HACT_SZ_H, tg->hact_sz_h);
hdmi_writeb(hdev, HDMI_TG_V_FSZ_L, tg->v_fsz_l);
hdmi_writeb(hdev, HDMI_TG_V_FSZ_H, tg->v_fsz_h);
hdmi_writeb(hdev, HDMI_TG_VSYNC_L, tg->vsync_l);
hdmi_writeb(hdev, HDMI_TG_VSYNC_H, tg->vsync_h);
hdmi_writeb(hdev, HDMI_TG_VSYNC2_L, tg->vsync2_l);
hdmi_writeb(hdev, HDMI_TG_VSYNC2_H, tg->vsync2_h);
hdmi_writeb(hdev, HDMI_TG_VACT_ST_L, tg->vact_st_l);
hdmi_writeb(hdev, HDMI_TG_VACT_ST_H, tg->vact_st_h);
hdmi_writeb(hdev, HDMI_TG_VACT_SZ_L, tg->vact_sz_l);
hdmi_writeb(hdev, HDMI_TG_VACT_SZ_H, tg->vact_sz_h);
hdmi_writeb(hdev, HDMI_TG_FIELD_CHG_L, tg->field_chg_l);
hdmi_writeb(hdev, HDMI_TG_FIELD_CHG_H, tg->field_chg_h);
hdmi_writeb(hdev, HDMI_TG_VACT_ST2_L, tg->vact_st2_l);
hdmi_writeb(hdev, HDMI_TG_VACT_ST2_H, tg->vact_st2_h);
hdmi_writeb(hdev, HDMI_TG_VSYNC_TOP_HDMI_L, tg->vsync_top_hdmi_l);
hdmi_writeb(hdev, HDMI_TG_VSYNC_TOP_HDMI_H, tg->vsync_top_hdmi_h);
hdmi_writeb(hdev, HDMI_TG_VSYNC_BOT_HDMI_L, tg->vsync_bot_hdmi_l);
hdmi_writeb(hdev, HDMI_TG_VSYNC_BOT_HDMI_H, tg->vsync_bot_hdmi_h);
hdmi_writeb(hdev, HDMI_TG_FIELD_TOP_HDMI_L, tg->field_top_hdmi_l);
hdmi_writeb(hdev, HDMI_TG_FIELD_TOP_HDMI_H, tg->field_top_hdmi_h);
hdmi_writeb(hdev, HDMI_TG_FIELD_BOT_HDMI_L, tg->field_bot_hdmi_l);
hdmi_writeb(hdev, HDMI_TG_FIELD_BOT_HDMI_H, tg->field_bot_hdmi_h);
}
static int hdmi_conf_apply(struct hdmi_device *hdmi_dev)
{
struct device *dev = hdmi_dev->dev;
const struct hdmi_preset_conf *conf = hdmi_dev->cur_conf;
struct v4l2_dv_preset preset;
int ret;
dev_dbg(dev, "%s\n", __func__);
/* reset hdmiphy */
hdmi_write_mask(hdmi_dev, HDMI_PHY_RSTOUT, ~0, HDMI_PHY_SW_RSTOUT);
mdelay(10);
hdmi_write_mask(hdmi_dev, HDMI_PHY_RSTOUT, 0, HDMI_PHY_SW_RSTOUT);
mdelay(10);
/* configure presets */
preset.preset = hdmi_dev->cur_preset;
ret = v4l2_subdev_call(hdmi_dev->phy_sd, video, s_dv_preset, &preset);
if (ret) {
dev_err(dev, "failed to set preset (%u)\n", preset.preset);
return ret;
}
/* resetting HDMI core */
hdmi_write_mask(hdmi_dev, HDMI_CORE_RSTOUT, 0, HDMI_CORE_SW_RSTOUT);
mdelay(10);
hdmi_write_mask(hdmi_dev, HDMI_CORE_RSTOUT, ~0, HDMI_CORE_SW_RSTOUT);
mdelay(10);
hdmi_reg_init(hdmi_dev);
/* setting core registers */
hdmi_timing_apply(hdmi_dev, conf);
return 0;
}
static void hdmi_dumpregs(struct hdmi_device *hdev, char *prefix)
{
#define DUMPREG(reg_id) \
dev_dbg(hdev->dev, "%s:" #reg_id " = %08x\n", prefix, \
readl(hdev->regs + reg_id))
dev_dbg(hdev->dev, "%s: ---- CONTROL REGISTERS ----\n", prefix);
DUMPREG(HDMI_INTC_FLAG);
DUMPREG(HDMI_INTC_CON);
DUMPREG(HDMI_HPD_STATUS);
DUMPREG(HDMI_PHY_RSTOUT);
DUMPREG(HDMI_PHY_VPLL);
DUMPREG(HDMI_PHY_CMU);
DUMPREG(HDMI_CORE_RSTOUT);
dev_dbg(hdev->dev, "%s: ---- CORE REGISTERS ----\n", prefix);
DUMPREG(HDMI_CON_0);
DUMPREG(HDMI_CON_1);
DUMPREG(HDMI_CON_2);
DUMPREG(HDMI_SYS_STATUS);
DUMPREG(HDMI_PHY_STATUS);
DUMPREG(HDMI_STATUS_EN);
DUMPREG(HDMI_HPD);
DUMPREG(HDMI_MODE_SEL);
DUMPREG(HDMI_HPD_GEN);
DUMPREG(HDMI_DC_CONTROL);
DUMPREG(HDMI_VIDEO_PATTERN_GEN);
dev_dbg(hdev->dev, "%s: ---- CORE SYNC REGISTERS ----\n", prefix);
DUMPREG(HDMI_H_BLANK_0);
DUMPREG(HDMI_H_BLANK_1);
DUMPREG(HDMI_V_BLANK_0);
DUMPREG(HDMI_V_BLANK_1);
DUMPREG(HDMI_V_BLANK_2);
DUMPREG(HDMI_H_V_LINE_0);
DUMPREG(HDMI_H_V_LINE_1);
DUMPREG(HDMI_H_V_LINE_2);
DUMPREG(HDMI_VSYNC_POL);
DUMPREG(HDMI_INT_PRO_MODE);
DUMPREG(HDMI_V_BLANK_F_0);
DUMPREG(HDMI_V_BLANK_F_1);
DUMPREG(HDMI_V_BLANK_F_2);
DUMPREG(HDMI_H_SYNC_GEN_0);
DUMPREG(HDMI_H_SYNC_GEN_1);
DUMPREG(HDMI_H_SYNC_GEN_2);
DUMPREG(HDMI_V_SYNC_GEN_1_0);
DUMPREG(HDMI_V_SYNC_GEN_1_1);
DUMPREG(HDMI_V_SYNC_GEN_1_2);
DUMPREG(HDMI_V_SYNC_GEN_2_0);
DUMPREG(HDMI_V_SYNC_GEN_2_1);
DUMPREG(HDMI_V_SYNC_GEN_2_2);
DUMPREG(HDMI_V_SYNC_GEN_3_0);
DUMPREG(HDMI_V_SYNC_GEN_3_1);
DUMPREG(HDMI_V_SYNC_GEN_3_2);
dev_dbg(hdev->dev, "%s: ---- TG REGISTERS ----\n", prefix);
DUMPREG(HDMI_TG_CMD);
DUMPREG(HDMI_TG_H_FSZ_L);
DUMPREG(HDMI_TG_H_FSZ_H);
DUMPREG(HDMI_TG_HACT_ST_L);
DUMPREG(HDMI_TG_HACT_ST_H);
DUMPREG(HDMI_TG_HACT_SZ_L);
DUMPREG(HDMI_TG_HACT_SZ_H);
DUMPREG(HDMI_TG_V_FSZ_L);
DUMPREG(HDMI_TG_V_FSZ_H);
DUMPREG(HDMI_TG_VSYNC_L);
DUMPREG(HDMI_TG_VSYNC_H);
DUMPREG(HDMI_TG_VSYNC2_L);
DUMPREG(HDMI_TG_VSYNC2_H);
DUMPREG(HDMI_TG_VACT_ST_L);
DUMPREG(HDMI_TG_VACT_ST_H);
DUMPREG(HDMI_TG_VACT_SZ_L);
DUMPREG(HDMI_TG_VACT_SZ_H);
DUMPREG(HDMI_TG_FIELD_CHG_L);
DUMPREG(HDMI_TG_FIELD_CHG_H);
DUMPREG(HDMI_TG_VACT_ST2_L);
DUMPREG(HDMI_TG_VACT_ST2_H);
DUMPREG(HDMI_TG_VSYNC_TOP_HDMI_L);
DUMPREG(HDMI_TG_VSYNC_TOP_HDMI_H);
DUMPREG(HDMI_TG_VSYNC_BOT_HDMI_L);
DUMPREG(HDMI_TG_VSYNC_BOT_HDMI_H);
DUMPREG(HDMI_TG_FIELD_TOP_HDMI_L);
DUMPREG(HDMI_TG_FIELD_TOP_HDMI_H);
DUMPREG(HDMI_TG_FIELD_BOT_HDMI_L);
DUMPREG(HDMI_TG_FIELD_BOT_HDMI_H);
#undef DUMPREG
}
static const struct hdmi_preset_conf hdmi_conf_480p = {
.core = {
.h_blank = {0x8a, 0x00},
.v_blank = {0x0d, 0x6a, 0x01},
.h_v_line = {0x0d, 0xa2, 0x35},
.vsync_pol = {0x01},
.int_pro_mode = {0x00},
.v_blank_f = {0x00, 0x00, 0x00},
.h_sync_gen = {0x0e, 0x30, 0x11},
.v_sync_gen1 = {0x0f, 0x90, 0x00},
/* other don't care */
},
.tg = {
0x00, /* cmd */
0x5a, 0x03, /* h_fsz */
0x8a, 0x00, 0xd0, 0x02, /* hact */
0x0d, 0x02, /* v_fsz */
0x01, 0x00, 0x33, 0x02, /* vsync */
0x2d, 0x00, 0xe0, 0x01, /* vact */
0x33, 0x02, /* field_chg */
0x49, 0x02, /* vact_st2 */
0x01, 0x00, 0x33, 0x02, /* vsync top/bot */
0x01, 0x00, 0x33, 0x02, /* field top/bot */
},
.mbus_fmt = {
.width = 720,
.height = 480,
.code = V4L2_MBUS_FMT_FIXED, /* means RGB888 */
.field = V4L2_FIELD_NONE,
.colorspace = V4L2_COLORSPACE_SRGB,
},
};
static const struct hdmi_preset_conf hdmi_conf_720p60 = {
.core = {
.h_blank = {0x72, 0x01},
.v_blank = {0xee, 0xf2, 0x00},
.h_v_line = {0xee, 0x22, 0x67},
.vsync_pol = {0x00},
.int_pro_mode = {0x00},
.v_blank_f = {0x00, 0x00, 0x00}, /* don't care */
.h_sync_gen = {0x6c, 0x50, 0x02},
.v_sync_gen1 = {0x0a, 0x50, 0x00},
/* other don't care */
},
.tg = {
0x00, /* cmd */
0x72, 0x06, /* h_fsz */
0x72, 0x01, 0x00, 0x05, /* hact */
0xee, 0x02, /* v_fsz */
0x01, 0x00, 0x33, 0x02, /* vsync */
0x1e, 0x00, 0xd0, 0x02, /* vact */
0x33, 0x02, /* field_chg */
0x49, 0x02, /* vact_st2 */
0x01, 0x00, 0x33, 0x02, /* vsync top/bot */
0x01, 0x00, 0x33, 0x02, /* field top/bot */
},
.mbus_fmt = {
.width = 1280,
.height = 720,
.code = V4L2_MBUS_FMT_FIXED, /* means RGB888 */
.field = V4L2_FIELD_NONE,
.colorspace = V4L2_COLORSPACE_SRGB,
},
};
static const struct hdmi_preset_conf hdmi_conf_1080p50 = {
.core = {
.h_blank = {0xd0, 0x02},
.v_blank = {0x65, 0x6c, 0x01},
.h_v_line = {0x65, 0x04, 0xa5},
.vsync_pol = {0x00},
.int_pro_mode = {0x00},
.v_blank_f = {0x00, 0x00, 0x00}, /* don't care */
.h_sync_gen = {0x0e, 0xea, 0x08},
.v_sync_gen1 = {0x09, 0x40, 0x00},
/* other don't care */
},
.tg = {
0x00, /* cmd */
0x98, 0x08, /* h_fsz */
0x18, 0x01, 0x80, 0x07, /* hact */
0x65, 0x04, /* v_fsz */
0x01, 0x00, 0x33, 0x02, /* vsync */
0x2d, 0x00, 0x38, 0x04, /* vact */
0x33, 0x02, /* field_chg */
0x49, 0x02, /* vact_st2 */
0x01, 0x00, 0x33, 0x02, /* vsync top/bot */
0x01, 0x00, 0x33, 0x02, /* field top/bot */
},
.mbus_fmt = {
.width = 1920,
.height = 1080,
.code = V4L2_MBUS_FMT_FIXED, /* means RGB888 */
.field = V4L2_FIELD_NONE,
.colorspace = V4L2_COLORSPACE_SRGB,
},
};
static const struct hdmi_preset_conf hdmi_conf_1080p60 = {
.core = {
.h_blank = {0x18, 0x01},
.v_blank = {0x65, 0x6c, 0x01},
.h_v_line = {0x65, 0x84, 0x89},
.vsync_pol = {0x00},
.int_pro_mode = {0x00},
.v_blank_f = {0x00, 0x00, 0x00}, /* don't care */
.h_sync_gen = {0x56, 0x08, 0x02},
.v_sync_gen1 = {0x09, 0x40, 0x00},
/* other don't care */
},
.tg = {
0x00, /* cmd */
0x98, 0x08, /* h_fsz */
0x18, 0x01, 0x80, 0x07, /* hact */
0x65, 0x04, /* v_fsz */
0x01, 0x00, 0x33, 0x02, /* vsync */
0x2d, 0x00, 0x38, 0x04, /* vact */
0x33, 0x02, /* field_chg */
0x48, 0x02, /* vact_st2 */
0x01, 0x00, 0x01, 0x00, /* vsync top/bot */
0x01, 0x00, 0x33, 0x02, /* field top/bot */
},
.mbus_fmt = {
.width = 1920,
.height = 1080,
.code = V4L2_MBUS_FMT_FIXED, /* means RGB888 */
.field = V4L2_FIELD_NONE,
.colorspace = V4L2_COLORSPACE_SRGB,
},
};
static const struct {
u32 preset;
const struct hdmi_preset_conf *conf;
} hdmi_conf[] = {
{ V4L2_DV_480P59_94, &hdmi_conf_480p },
{ V4L2_DV_720P59_94, &hdmi_conf_720p60 },
{ V4L2_DV_1080P50, &hdmi_conf_1080p50 },
{ V4L2_DV_1080P30, &hdmi_conf_1080p60 },
{ V4L2_DV_1080P60, &hdmi_conf_1080p60 },
};
static const struct hdmi_preset_conf *hdmi_preset2conf(u32 preset)
{
int i;
for (i = 0; i < ARRAY_SIZE(hdmi_conf); ++i)
if (hdmi_conf[i].preset == preset)
return hdmi_conf[i].conf;
return NULL;
}
static int hdmi_streamon(struct hdmi_device *hdev)
{
struct device *dev = hdev->dev;
struct hdmi_resources *res = &hdev->res;
int ret, tries;
dev_dbg(dev, "%s\n", __func__);
ret = v4l2_subdev_call(hdev->phy_sd, video, s_stream, 1);
if (ret)
return ret;
/* waiting for HDMIPHY's PLL to get to steady state */
for (tries = 100; tries; --tries) {
u32 val = hdmi_read(hdev, HDMI_PHY_STATUS);
if (val & HDMI_PHY_STATUS_READY)
break;
mdelay(1);
}
/* steady state not achieved */
if (tries == 0) {
dev_err(dev, "hdmiphy's pll could not reach steady state.\n");
v4l2_subdev_call(hdev->phy_sd, video, s_stream, 0);
hdmi_dumpregs(hdev, "hdmiphy - s_stream");
return -EIO;
}
/* starting MHL */
ret = v4l2_subdev_call(hdev->mhl_sd, video, s_stream, 1);
if (hdev->mhl_sd && ret) {
v4l2_subdev_call(hdev->phy_sd, video, s_stream, 0);
hdmi_dumpregs(hdev, "mhl - s_stream");
return -EIO;
}
/* hdmiphy clock is used for HDMI in streaming mode */
clk_disable(res->sclk_hdmi);
clk_set_parent(res->sclk_hdmi, res->sclk_hdmiphy);
clk_enable(res->sclk_hdmi);
/* enable HDMI and timing generator */
hdmi_write_mask(hdev, HDMI_CON_0, ~0, HDMI_EN);
hdmi_write_mask(hdev, HDMI_TG_CMD, ~0, HDMI_TG_EN);
hdmi_dumpregs(hdev, "streamon");
return 0;
}
static int hdmi_streamoff(struct hdmi_device *hdev)
{
struct device *dev = hdev->dev;
struct hdmi_resources *res = &hdev->res;
dev_dbg(dev, "%s\n", __func__);
hdmi_write_mask(hdev, HDMI_CON_0, 0, HDMI_EN);
hdmi_write_mask(hdev, HDMI_TG_CMD, 0, HDMI_TG_EN);
/* pixel(vpll) clock is used for HDMI in config mode */
clk_disable(res->sclk_hdmi);
clk_set_parent(res->sclk_hdmi, res->sclk_pixel);
clk_enable(res->sclk_hdmi);
v4l2_subdev_call(hdev->mhl_sd, video, s_stream, 0);
v4l2_subdev_call(hdev->phy_sd, video, s_stream, 0);
hdmi_dumpregs(hdev, "streamoff");
return 0;
}
static int hdmi_s_stream(struct v4l2_subdev *sd, int enable)
{
struct hdmi_device *hdev = sd_to_hdmi_dev(sd);
struct device *dev = hdev->dev;
dev_dbg(dev, "%s(%d)\n", __func__, enable);
if (enable)
return hdmi_streamon(hdev);
return hdmi_streamoff(hdev);
}
static void hdmi_resource_poweron(struct hdmi_resources *res)
{
/* turn HDMI power on */
regulator_bulk_enable(res->regul_count, res->regul_bulk);
/* power-on hdmi physical interface */
clk_enable(res->hdmiphy);
/* use VPP as parent clock; HDMIPHY is not working yet */
clk_set_parent(res->sclk_hdmi, res->sclk_pixel);
/* turn clocks on */
clk_enable(res->sclk_hdmi);
}
static void hdmi_resource_poweroff(struct hdmi_resources *res)
{
/* turn clocks off */
clk_disable(res->sclk_hdmi);
/* power-off hdmiphy */
clk_disable(res->hdmiphy);
/* turn HDMI power off */
regulator_bulk_disable(res->regul_count, res->regul_bulk);
}
static int hdmi_s_power(struct v4l2_subdev *sd, int on)
{
struct hdmi_device *hdev = sd_to_hdmi_dev(sd);
int ret;
if (on)
ret = pm_runtime_get_sync(hdev->dev);
else
ret = pm_runtime_put_sync(hdev->dev);
/* only values < 0 indicate errors */
return IS_ERR_VALUE(ret) ? ret : 0;
}
static int hdmi_s_dv_preset(struct v4l2_subdev *sd,
struct v4l2_dv_preset *preset)
{
struct hdmi_device *hdev = sd_to_hdmi_dev(sd);
struct device *dev = hdev->dev;
const struct hdmi_preset_conf *conf;
conf = hdmi_preset2conf(preset->preset);
if (conf == NULL) {
dev_err(dev, "preset (%u) not supported\n", preset->preset);
return -EINVAL;
}
hdev->cur_conf = conf;
hdev->cur_preset = preset->preset;
return 0;
}
static int hdmi_g_dv_preset(struct v4l2_subdev *sd,
struct v4l2_dv_preset *preset)
{
memset(preset, 0, sizeof(*preset));
preset->preset = sd_to_hdmi_dev(sd)->cur_preset;
return 0;
}
static int hdmi_g_mbus_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *fmt)
{
struct hdmi_device *hdev = sd_to_hdmi_dev(sd);
struct device *dev = hdev->dev;
dev_dbg(dev, "%s\n", __func__);
if (!hdev->cur_conf)
return -EINVAL;
*fmt = hdev->cur_conf->mbus_fmt;
return 0;
}
static int hdmi_enum_dv_presets(struct v4l2_subdev *sd,
struct v4l2_dv_enum_preset *preset)
{
if (preset->index >= ARRAY_SIZE(hdmi_conf))
return -EINVAL;
return v4l_fill_dv_preset_info(hdmi_conf[preset->index].preset, preset);
}
static const struct v4l2_subdev_core_ops hdmi_sd_core_ops = {
.s_power = hdmi_s_power,
};
static const struct v4l2_subdev_video_ops hdmi_sd_video_ops = {
.s_dv_preset = hdmi_s_dv_preset,
.g_dv_preset = hdmi_g_dv_preset,
.enum_dv_presets = hdmi_enum_dv_presets,
.g_mbus_fmt = hdmi_g_mbus_fmt,
.s_stream = hdmi_s_stream,
};
static const struct v4l2_subdev_ops hdmi_sd_ops = {
.core = &hdmi_sd_core_ops,
.video = &hdmi_sd_video_ops,
};
static int hdmi_runtime_suspend(struct device *dev)
{
struct v4l2_subdev *sd = dev_get_drvdata(dev);
struct hdmi_device *hdev = sd_to_hdmi_dev(sd);
dev_dbg(dev, "%s\n", __func__);
v4l2_subdev_call(hdev->mhl_sd, core, s_power, 0);
hdmi_resource_poweroff(&hdev->res);
return 0;
}
static int hdmi_runtime_resume(struct device *dev)
{
struct v4l2_subdev *sd = dev_get_drvdata(dev);
struct hdmi_device *hdev = sd_to_hdmi_dev(sd);
int ret = 0;
dev_dbg(dev, "%s\n", __func__);
hdmi_resource_poweron(&hdev->res);
ret = hdmi_conf_apply(hdev);
if (ret)
goto fail;
/* starting MHL */
ret = v4l2_subdev_call(hdev->mhl_sd, core, s_power, 1);
if (hdev->mhl_sd && ret)
goto fail;
dev_dbg(dev, "poweron succeed\n");
return 0;
fail:
hdmi_resource_poweroff(&hdev->res);
dev_err(dev, "poweron failed\n");
return ret;
}
static const struct dev_pm_ops hdmi_pm_ops = {
.runtime_suspend = hdmi_runtime_suspend,
.runtime_resume = hdmi_runtime_resume,
};
static void hdmi_resources_cleanup(struct hdmi_device *hdev)
{
struct hdmi_resources *res = &hdev->res;
dev_dbg(hdev->dev, "HDMI resource cleanup\n");
/* put clocks, power */
if (res->regul_count)
regulator_bulk_free(res->regul_count, res->regul_bulk);
/* kfree is NULL-safe */
kfree(res->regul_bulk);
if (!IS_ERR_OR_NULL(res->hdmiphy))
clk_put(res->hdmiphy);
if (!IS_ERR_OR_NULL(res->sclk_hdmiphy))
clk_put(res->sclk_hdmiphy);
if (!IS_ERR_OR_NULL(res->sclk_pixel))
clk_put(res->sclk_pixel);
if (!IS_ERR_OR_NULL(res->sclk_hdmi))
clk_put(res->sclk_hdmi);
if (!IS_ERR_OR_NULL(res->hdmi))
clk_put(res->hdmi);
memset(res, 0, sizeof *res);
}
static int hdmi_resources_init(struct hdmi_device *hdev)
{
struct device *dev = hdev->dev;
struct hdmi_resources *res = &hdev->res;
static char *supply[] = {
"hdmi-en",
"vdd",
"vdd_osc",
"vdd_pll",
};
int i, ret;
dev_dbg(dev, "HDMI resource init\n");
memset(res, 0, sizeof *res);
/* get clocks, power */
res->hdmi = clk_get(dev, "hdmi");
if (IS_ERR_OR_NULL(res->hdmi)) {
dev_err(dev, "failed to get clock 'hdmi'\n");
goto fail;
}
res->sclk_hdmi = clk_get(dev, "sclk_hdmi");
if (IS_ERR_OR_NULL(res->sclk_hdmi)) {
dev_err(dev, "failed to get clock 'sclk_hdmi'\n");
goto fail;
}
res->sclk_pixel = clk_get(dev, "sclk_pixel");
if (IS_ERR_OR_NULL(res->sclk_pixel)) {
dev_err(dev, "failed to get clock 'sclk_pixel'\n");
goto fail;
}
res->sclk_hdmiphy = clk_get(dev, "sclk_hdmiphy");
if (IS_ERR_OR_NULL(res->sclk_hdmiphy)) {
dev_err(dev, "failed to get clock 'sclk_hdmiphy'\n");
goto fail;
}
res->hdmiphy = clk_get(dev, "hdmiphy");
if (IS_ERR_OR_NULL(res->hdmiphy)) {
dev_err(dev, "failed to get clock 'hdmiphy'\n");
goto fail;
}
res->regul_bulk = kcalloc(ARRAY_SIZE(supply),
sizeof(res->regul_bulk[0]), GFP_KERNEL);
if (!res->regul_bulk) {
dev_err(dev, "failed to get memory for regulators\n");
goto fail;
}
for (i = 0; i < ARRAY_SIZE(supply); ++i) {
res->regul_bulk[i].supply = supply[i];
res->regul_bulk[i].consumer = NULL;
}
ret = regulator_bulk_get(dev, ARRAY_SIZE(supply), res->regul_bulk);
if (ret) {
dev_err(dev, "failed to get regulators\n");
goto fail;
}
res->regul_count = ARRAY_SIZE(supply);
return 0;
fail:
dev_err(dev, "HDMI resource init - failed\n");
hdmi_resources_cleanup(hdev);
return -ENODEV;
}
static int __devinit hdmi_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct resource *res;
struct i2c_adapter *adapter;
struct v4l2_subdev *sd;
struct hdmi_device *hdmi_dev = NULL;
struct s5p_hdmi_platform_data *pdata = dev->platform_data;
int ret;
dev_dbg(dev, "probe start\n");
if (!pdata) {
dev_err(dev, "platform data is missing\n");
ret = -ENODEV;
goto fail;
}
hdmi_dev = devm_kzalloc(&pdev->dev, sizeof(*hdmi_dev), GFP_KERNEL);
if (!hdmi_dev) {
dev_err(dev, "out of memory\n");
ret = -ENOMEM;
goto fail;
}
hdmi_dev->dev = dev;
ret = hdmi_resources_init(hdmi_dev);
if (ret)
goto fail;
/* mapping HDMI registers */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res == NULL) {
dev_err(dev, "get memory resource failed.\n");
ret = -ENXIO;
goto fail_init;
}
hdmi_dev->regs = devm_ioremap(&pdev->dev, res->start,
resource_size(res));
if (hdmi_dev->regs == NULL) {
dev_err(dev, "register mapping failed.\n");
ret = -ENXIO;
goto fail_init;
}
res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (res == NULL) {
dev_err(dev, "get interrupt resource failed.\n");
ret = -ENXIO;
goto fail_init;
}
ret = devm_request_irq(&pdev->dev, res->start, hdmi_irq_handler, 0,
"hdmi", hdmi_dev);
if (ret) {
dev_err(dev, "request interrupt failed.\n");
goto fail_init;
}
hdmi_dev->irq = res->start;
/* setting v4l2 name to prevent WARN_ON in v4l2_device_register */
strlcpy(hdmi_dev->v4l2_dev.name, dev_name(dev),
sizeof(hdmi_dev->v4l2_dev.name));
/* passing NULL owner prevents driver from erasing drvdata */
ret = v4l2_device_register(NULL, &hdmi_dev->v4l2_dev);
if (ret) {
dev_err(dev, "could not register v4l2 device.\n");
goto fail_init;
}
/* testing if hdmiphy info is present */
if (!pdata->hdmiphy_info) {
dev_err(dev, "hdmiphy info is missing in platform data\n");
ret = -ENXIO;
goto fail_vdev;
}
adapter = i2c_get_adapter(pdata->hdmiphy_bus);
if (adapter == NULL) {
dev_err(dev, "hdmiphy adapter request failed\n");
ret = -ENXIO;
goto fail_vdev;
}
hdmi_dev->phy_sd = v4l2_i2c_new_subdev_board(&hdmi_dev->v4l2_dev,
adapter, pdata->hdmiphy_info, NULL);
/* on failure or not adapter is no longer useful */
i2c_put_adapter(adapter);
if (hdmi_dev->phy_sd == NULL) {
dev_err(dev, "missing subdev for hdmiphy\n");
ret = -ENODEV;
goto fail_vdev;
}
/* initialization of MHL interface if present */
if (pdata->mhl_info) {
adapter = i2c_get_adapter(pdata->mhl_bus);
if (adapter == NULL) {
dev_err(dev, "MHL adapter request failed\n");
ret = -ENXIO;
goto fail_vdev;
}
hdmi_dev->mhl_sd = v4l2_i2c_new_subdev_board(
&hdmi_dev->v4l2_dev, adapter,
pdata->mhl_info, NULL);
/* on failure or not adapter is no longer useful */
i2c_put_adapter(adapter);
if (hdmi_dev->mhl_sd == NULL) {
dev_err(dev, "missing subdev for MHL\n");
ret = -ENODEV;
goto fail_vdev;
}
}
clk_enable(hdmi_dev->res.hdmi);
pm_runtime_enable(dev);
sd = &hdmi_dev->sd;
v4l2_subdev_init(sd, &hdmi_sd_ops);
sd->owner = THIS_MODULE;
strlcpy(sd->name, "s5p-hdmi", sizeof sd->name);
hdmi_dev->cur_preset = HDMI_DEFAULT_PRESET;
/* FIXME: missing fail preset is not supported */
hdmi_dev->cur_conf = hdmi_preset2conf(hdmi_dev->cur_preset);
/* storing subdev for call that have only access to struct device */
dev_set_drvdata(dev, sd);
dev_info(dev, "probe successful\n");
return 0;
fail_vdev:
v4l2_device_unregister(&hdmi_dev->v4l2_dev);
fail_init:
hdmi_resources_cleanup(hdmi_dev);
fail:
dev_err(dev, "probe failed\n");
return ret;
}
static int __devexit hdmi_remove(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct v4l2_subdev *sd = dev_get_drvdata(dev);
struct hdmi_device *hdmi_dev = sd_to_hdmi_dev(sd);
pm_runtime_disable(dev);
clk_disable(hdmi_dev->res.hdmi);
v4l2_device_unregister(&hdmi_dev->v4l2_dev);
disable_irq(hdmi_dev->irq);
hdmi_resources_cleanup(hdmi_dev);
dev_info(dev, "remove successful\n");
return 0;
}
static struct platform_driver hdmi_driver __refdata = {
.probe = hdmi_probe,
.remove = __devexit_p(hdmi_remove),
.id_table = hdmi_driver_types,
.driver = {
.name = "s5p-hdmi",
.owner = THIS_MODULE,
.pm = &hdmi_pm_ops,
}
};
module_platform_driver(hdmi_driver);
| gpl-2.0 |
h2o64/kernel_msm | drivers/pci/pci-acpi.c | 4811 | 9780 | /*
* File: pci-acpi.c
* Purpose: Provide PCI support in ACPI
*
* Copyright (C) 2005 David Shaohua Li <shaohua.li@intel.com>
* Copyright (C) 2004 Tom Long Nguyen <tom.l.nguyen@intel.com>
* Copyright (C) 2004 Intel Corp.
*/
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/module.h>
#include <linux/pci-aspm.h>
#include <acpi/acpi.h>
#include <acpi/acpi_bus.h>
#include <linux/pci-acpi.h>
#include <linux/pm_runtime.h>
#include "pci.h"
static DEFINE_MUTEX(pci_acpi_pm_notify_mtx);
/**
* pci_acpi_wake_bus - Wake-up notification handler for root buses.
* @handle: ACPI handle of a device the notification is for.
* @event: Type of the signaled event.
* @context: PCI root bus to wake up devices on.
*/
static void pci_acpi_wake_bus(acpi_handle handle, u32 event, void *context)
{
struct pci_bus *pci_bus = context;
if (event == ACPI_NOTIFY_DEVICE_WAKE && pci_bus)
pci_pme_wakeup_bus(pci_bus);
}
/**
* pci_acpi_wake_dev - Wake-up notification handler for PCI devices.
* @handle: ACPI handle of a device the notification is for.
* @event: Type of the signaled event.
* @context: PCI device object to wake up.
*/
static void pci_acpi_wake_dev(acpi_handle handle, u32 event, void *context)
{
struct pci_dev *pci_dev = context;
if (event != ACPI_NOTIFY_DEVICE_WAKE || !pci_dev)
return;
if (!pci_dev->pm_cap || !pci_dev->pme_support
|| pci_check_pme_status(pci_dev)) {
if (pci_dev->pme_poll)
pci_dev->pme_poll = false;
pci_wakeup_event(pci_dev);
pm_runtime_resume(&pci_dev->dev);
}
if (pci_dev->subordinate)
pci_pme_wakeup_bus(pci_dev->subordinate);
}
/**
* add_pm_notifier - Register PM notifier for given ACPI device.
* @dev: ACPI device to add the notifier for.
* @context: PCI device or bus to check for PME status if an event is signaled.
*
* NOTE: @dev need not be a run-wake or wake-up device to be a valid source of
* PM wake-up events. For example, wake-up events may be generated for bridges
* if one of the devices below the bridge is signaling PME, even if the bridge
* itself doesn't have a wake-up GPE associated with it.
*/
static acpi_status add_pm_notifier(struct acpi_device *dev,
acpi_notify_handler handler,
void *context)
{
acpi_status status = AE_ALREADY_EXISTS;
mutex_lock(&pci_acpi_pm_notify_mtx);
if (dev->wakeup.flags.notifier_present)
goto out;
status = acpi_install_notify_handler(dev->handle,
ACPI_SYSTEM_NOTIFY,
handler, context);
if (ACPI_FAILURE(status))
goto out;
dev->wakeup.flags.notifier_present = true;
out:
mutex_unlock(&pci_acpi_pm_notify_mtx);
return status;
}
/**
* remove_pm_notifier - Unregister PM notifier from given ACPI device.
* @dev: ACPI device to remove the notifier from.
*/
static acpi_status remove_pm_notifier(struct acpi_device *dev,
acpi_notify_handler handler)
{
acpi_status status = AE_BAD_PARAMETER;
mutex_lock(&pci_acpi_pm_notify_mtx);
if (!dev->wakeup.flags.notifier_present)
goto out;
status = acpi_remove_notify_handler(dev->handle,
ACPI_SYSTEM_NOTIFY,
handler);
if (ACPI_FAILURE(status))
goto out;
dev->wakeup.flags.notifier_present = false;
out:
mutex_unlock(&pci_acpi_pm_notify_mtx);
return status;
}
/**
* pci_acpi_add_bus_pm_notifier - Register PM notifier for given PCI bus.
* @dev: ACPI device to add the notifier for.
* @pci_bus: PCI bus to walk checking for PME status if an event is signaled.
*/
acpi_status pci_acpi_add_bus_pm_notifier(struct acpi_device *dev,
struct pci_bus *pci_bus)
{
return add_pm_notifier(dev, pci_acpi_wake_bus, pci_bus);
}
/**
* pci_acpi_remove_bus_pm_notifier - Unregister PCI bus PM notifier.
* @dev: ACPI device to remove the notifier from.
*/
acpi_status pci_acpi_remove_bus_pm_notifier(struct acpi_device *dev)
{
return remove_pm_notifier(dev, pci_acpi_wake_bus);
}
/**
* pci_acpi_add_pm_notifier - Register PM notifier for given PCI device.
* @dev: ACPI device to add the notifier for.
* @pci_dev: PCI device to check for the PME status if an event is signaled.
*/
acpi_status pci_acpi_add_pm_notifier(struct acpi_device *dev,
struct pci_dev *pci_dev)
{
return add_pm_notifier(dev, pci_acpi_wake_dev, pci_dev);
}
/**
* pci_acpi_remove_pm_notifier - Unregister PCI device PM notifier.
* @dev: ACPI device to remove the notifier from.
*/
acpi_status pci_acpi_remove_pm_notifier(struct acpi_device *dev)
{
return remove_pm_notifier(dev, pci_acpi_wake_dev);
}
/*
* _SxD returns the D-state with the highest power
* (lowest D-state number) supported in the S-state "x".
*
* If the devices does not have a _PRW
* (Power Resources for Wake) supporting system wakeup from "x"
* then the OS is free to choose a lower power (higher number
* D-state) than the return value from _SxD.
*
* But if _PRW is enabled at S-state "x", the OS
* must not choose a power lower than _SxD --
* unless the device has an _SxW method specifying
* the lowest power (highest D-state number) the device
* may enter while still able to wake the system.
*
* ie. depending on global OS policy:
*
* if (_PRW at S-state x)
* choose from highest power _SxD to lowest power _SxW
* else // no _PRW at S-state x
* choose highest power _SxD or any lower power
*/
static pci_power_t acpi_pci_choose_state(struct pci_dev *pdev)
{
int acpi_state;
acpi_state = acpi_pm_device_sleep_state(&pdev->dev, NULL);
if (acpi_state < 0)
return PCI_POWER_ERROR;
switch (acpi_state) {
case ACPI_STATE_D0:
return PCI_D0;
case ACPI_STATE_D1:
return PCI_D1;
case ACPI_STATE_D2:
return PCI_D2;
case ACPI_STATE_D3_HOT:
return PCI_D3hot;
case ACPI_STATE_D3_COLD:
return PCI_D3cold;
}
return PCI_POWER_ERROR;
}
static bool acpi_pci_power_manageable(struct pci_dev *dev)
{
acpi_handle handle = DEVICE_ACPI_HANDLE(&dev->dev);
return handle ? acpi_bus_power_manageable(handle) : false;
}
static int acpi_pci_set_power_state(struct pci_dev *dev, pci_power_t state)
{
acpi_handle handle = DEVICE_ACPI_HANDLE(&dev->dev);
acpi_handle tmp;
static const u8 state_conv[] = {
[PCI_D0] = ACPI_STATE_D0,
[PCI_D1] = ACPI_STATE_D1,
[PCI_D2] = ACPI_STATE_D2,
[PCI_D3hot] = ACPI_STATE_D3,
[PCI_D3cold] = ACPI_STATE_D3
};
int error = -EINVAL;
/* If the ACPI device has _EJ0, ignore the device */
if (!handle || ACPI_SUCCESS(acpi_get_handle(handle, "_EJ0", &tmp)))
return -ENODEV;
switch (state) {
case PCI_D0:
case PCI_D1:
case PCI_D2:
case PCI_D3hot:
case PCI_D3cold:
error = acpi_bus_set_power(handle, state_conv[state]);
}
if (!error)
dev_printk(KERN_INFO, &dev->dev,
"power state changed by ACPI to D%d\n", state);
return error;
}
static bool acpi_pci_can_wakeup(struct pci_dev *dev)
{
acpi_handle handle = DEVICE_ACPI_HANDLE(&dev->dev);
return handle ? acpi_bus_can_wakeup(handle) : false;
}
static void acpi_pci_propagate_wakeup_enable(struct pci_bus *bus, bool enable)
{
while (bus->parent) {
if (!acpi_pm_device_sleep_wake(&bus->self->dev, enable))
return;
bus = bus->parent;
}
/* We have reached the root bus. */
if (bus->bridge)
acpi_pm_device_sleep_wake(bus->bridge, enable);
}
static int acpi_pci_sleep_wake(struct pci_dev *dev, bool enable)
{
if (acpi_pci_can_wakeup(dev))
return acpi_pm_device_sleep_wake(&dev->dev, enable);
acpi_pci_propagate_wakeup_enable(dev->bus, enable);
return 0;
}
static void acpi_pci_propagate_run_wake(struct pci_bus *bus, bool enable)
{
while (bus->parent) {
struct pci_dev *bridge = bus->self;
if (bridge->pme_interrupt)
return;
if (!acpi_pm_device_run_wake(&bridge->dev, enable))
return;
bus = bus->parent;
}
/* We have reached the root bus. */
if (bus->bridge)
acpi_pm_device_run_wake(bus->bridge, enable);
}
static int acpi_pci_run_wake(struct pci_dev *dev, bool enable)
{
if (dev->pme_interrupt)
return 0;
if (!acpi_pm_device_run_wake(&dev->dev, enable))
return 0;
acpi_pci_propagate_run_wake(dev->bus, enable);
return 0;
}
static struct pci_platform_pm_ops acpi_pci_platform_pm = {
.is_manageable = acpi_pci_power_manageable,
.set_state = acpi_pci_set_power_state,
.choose_state = acpi_pci_choose_state,
.can_wakeup = acpi_pci_can_wakeup,
.sleep_wake = acpi_pci_sleep_wake,
.run_wake = acpi_pci_run_wake,
};
/* ACPI bus type */
static int acpi_pci_find_device(struct device *dev, acpi_handle *handle)
{
struct pci_dev * pci_dev;
u64 addr;
pci_dev = to_pci_dev(dev);
/* Please ref to ACPI spec for the syntax of _ADR */
addr = (PCI_SLOT(pci_dev->devfn) << 16) | PCI_FUNC(pci_dev->devfn);
*handle = acpi_get_child(DEVICE_ACPI_HANDLE(dev->parent), addr);
if (!*handle)
return -ENODEV;
return 0;
}
static int acpi_pci_find_root_bridge(struct device *dev, acpi_handle *handle)
{
int num;
unsigned int seg, bus;
/*
* The string should be the same as root bridge's name
* Please look at 'pci_scan_bus_parented'
*/
num = sscanf(dev_name(dev), "pci%04x:%02x", &seg, &bus);
if (num != 2)
return -ENODEV;
*handle = acpi_get_pci_rootbridge_handle(seg, bus);
if (!*handle)
return -ENODEV;
return 0;
}
static struct acpi_bus_type acpi_pci_bus = {
.bus = &pci_bus_type,
.find_device = acpi_pci_find_device,
.find_bridge = acpi_pci_find_root_bridge,
};
static int __init acpi_pci_init(void)
{
int ret;
if (acpi_gbl_FADT.boot_flags & ACPI_FADT_NO_MSI) {
printk(KERN_INFO"ACPI FADT declares the system doesn't support MSI, so disable it\n");
pci_no_msi();
}
if (acpi_gbl_FADT.boot_flags & ACPI_FADT_NO_ASPM) {
printk(KERN_INFO"ACPI FADT declares the system doesn't support PCIe ASPM, so disable it\n");
pcie_no_aspm();
}
ret = register_acpi_bus_type(&acpi_pci_bus);
if (ret)
return 0;
pci_set_platform_pm(&acpi_pci_platform_pm);
return 0;
}
arch_initcall(acpi_pci_init);
| gpl-2.0 |
Docker-J/Sail_STOCK | drivers/media/video/msp3400-driver.c | 4811 | 26556 | /*
* Programming the mspx4xx sound processor family
*
* (c) 1997-2001 Gerd Knorr <kraxel@bytesex.org>
*
* what works and what doesn't:
*
* AM-Mono
* Support for Hauppauge cards added (decoding handled by tuner) added by
* Frederic Crozat <fcrozat@mail.dotcom.fr>
*
* FM-Mono
* should work. The stereo modes are backward compatible to FM-mono,
* therefore FM-Mono should be allways available.
*
* FM-Stereo (B/G, used in germany)
* should work, with autodetect
*
* FM-Stereo (satellite)
* should work, no autodetect (i.e. default is mono, but you can
* switch to stereo -- untested)
*
* NICAM (B/G, L , used in UK, Scandinavia, Spain and France)
* should work, with autodetect. Support for NICAM was added by
* Pekka Pietikainen <pp@netppl.fi>
*
* TODO:
* - better SAT support
*
* 980623 Thomas Sailer (sailer@ife.ee.ethz.ch)
* using soundcore instead of OSS
*
* 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/module.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/videodev2.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <media/msp3400.h>
#include <media/tvaudio.h>
#include "msp3400-driver.h"
/* ---------------------------------------------------------------------- */
MODULE_DESCRIPTION("device driver for msp34xx TV sound processor");
MODULE_AUTHOR("Gerd Knorr");
MODULE_LICENSE("GPL");
/* module parameters */
static int opmode = OPMODE_AUTO;
int msp_debug; /* msp_debug output */
bool msp_once; /* no continuous stereo monitoring */
bool msp_amsound; /* hard-wire AM sound at 6.5 Hz (france),
the autoscan seems work well only with FM... */
int msp_standard = 1; /* Override auto detect of audio msp_standard,
if needed. */
bool msp_dolby;
int msp_stereo_thresh = 0x190; /* a2 threshold for stereo/bilingual
(msp34xxg only) 0x00a0-0x03c0 */
/* read-only */
module_param(opmode, int, 0444);
/* read-write */
module_param_named(once, msp_once, bool, 0644);
module_param_named(debug, msp_debug, int, 0644);
module_param_named(stereo_threshold, msp_stereo_thresh, int, 0644);
module_param_named(standard, msp_standard, int, 0644);
module_param_named(amsound, msp_amsound, bool, 0644);
module_param_named(dolby, msp_dolby, bool, 0644);
MODULE_PARM_DESC(opmode, "Forces a MSP3400 opmode. 0=Manual, 1=Autodetect, 2=Autodetect and autoselect");
MODULE_PARM_DESC(once, "No continuous stereo monitoring");
MODULE_PARM_DESC(debug, "Enable debug messages [0-3]");
MODULE_PARM_DESC(stereo_threshold, "Sets signal threshold to activate stereo");
MODULE_PARM_DESC(standard, "Specify audio standard: 32 = NTSC, 64 = radio, Default: Autodetect");
MODULE_PARM_DESC(amsound, "Hardwire AM sound at 6.5Hz (France), FM can autoscan");
MODULE_PARM_DESC(dolby, "Activates Dolby processing");
/* ---------------------------------------------------------------------- */
/* control subaddress */
#define I2C_MSP_CONTROL 0x00
/* demodulator unit subaddress */
#define I2C_MSP_DEM 0x10
/* DSP unit subaddress */
#define I2C_MSP_DSP 0x12
/* ----------------------------------------------------------------------- */
/* functions for talking to the MSP3400C Sound processor */
int msp_reset(struct i2c_client *client)
{
/* reset and read revision code */
static u8 reset_off[3] = { I2C_MSP_CONTROL, 0x80, 0x00 };
static u8 reset_on[3] = { I2C_MSP_CONTROL, 0x00, 0x00 };
static u8 write[3] = { I2C_MSP_DSP + 1, 0x00, 0x1e };
u8 read[2];
struct i2c_msg reset[2] = {
{ client->addr, I2C_M_IGNORE_NAK, 3, reset_off },
{ client->addr, I2C_M_IGNORE_NAK, 3, reset_on },
};
struct i2c_msg test[2] = {
{ client->addr, 0, 3, write },
{ client->addr, I2C_M_RD, 2, read },
};
v4l_dbg(3, msp_debug, client, "msp_reset\n");
if (i2c_transfer(client->adapter, &reset[0], 1) != 1 ||
i2c_transfer(client->adapter, &reset[1], 1) != 1 ||
i2c_transfer(client->adapter, test, 2) != 2) {
v4l_err(client, "chip reset failed\n");
return -1;
}
return 0;
}
static int msp_read(struct i2c_client *client, int dev, int addr)
{
int err, retval;
u8 write[3];
u8 read[2];
struct i2c_msg msgs[2] = {
{ client->addr, 0, 3, write },
{ client->addr, I2C_M_RD, 2, read }
};
write[0] = dev + 1;
write[1] = addr >> 8;
write[2] = addr & 0xff;
for (err = 0; err < 3; err++) {
if (i2c_transfer(client->adapter, msgs, 2) == 2)
break;
v4l_warn(client, "I/O error #%d (read 0x%02x/0x%02x)\n", err,
dev, addr);
schedule_timeout_interruptible(msecs_to_jiffies(10));
}
if (err == 3) {
v4l_warn(client, "resetting chip, sound will go off.\n");
msp_reset(client);
return -1;
}
retval = read[0] << 8 | read[1];
v4l_dbg(3, msp_debug, client, "msp_read(0x%x, 0x%x): 0x%x\n",
dev, addr, retval);
return retval;
}
int msp_read_dem(struct i2c_client *client, int addr)
{
return msp_read(client, I2C_MSP_DEM, addr);
}
int msp_read_dsp(struct i2c_client *client, int addr)
{
return msp_read(client, I2C_MSP_DSP, addr);
}
static int msp_write(struct i2c_client *client, int dev, int addr, int val)
{
int err;
u8 buffer[5];
buffer[0] = dev;
buffer[1] = addr >> 8;
buffer[2] = addr & 0xff;
buffer[3] = val >> 8;
buffer[4] = val & 0xff;
v4l_dbg(3, msp_debug, client, "msp_write(0x%x, 0x%x, 0x%x)\n",
dev, addr, val);
for (err = 0; err < 3; err++) {
if (i2c_master_send(client, buffer, 5) == 5)
break;
v4l_warn(client, "I/O error #%d (write 0x%02x/0x%02x)\n", err,
dev, addr);
schedule_timeout_interruptible(msecs_to_jiffies(10));
}
if (err == 3) {
v4l_warn(client, "resetting chip, sound will go off.\n");
msp_reset(client);
return -1;
}
return 0;
}
int msp_write_dem(struct i2c_client *client, int addr, int val)
{
return msp_write(client, I2C_MSP_DEM, addr, val);
}
int msp_write_dsp(struct i2c_client *client, int addr, int val)
{
return msp_write(client, I2C_MSP_DSP, addr, val);
}
/* ----------------------------------------------------------------------- *
* bits 9 8 5 - SCART DSP input Select:
* 0 0 0 - SCART 1 to DSP input (reset position)
* 0 1 0 - MONO to DSP input
* 1 0 0 - SCART 2 to DSP input
* 1 1 1 - Mute DSP input
*
* bits 11 10 6 - SCART 1 Output Select:
* 0 0 0 - undefined (reset position)
* 0 1 0 - SCART 2 Input to SCART 1 Output (for devices with 2 SCARTS)
* 1 0 0 - MONO input to SCART 1 Output
* 1 1 0 - SCART 1 DA to SCART 1 Output
* 0 0 1 - SCART 2 DA to SCART 1 Output
* 0 1 1 - SCART 1 Input to SCART 1 Output
* 1 1 1 - Mute SCART 1 Output
*
* bits 13 12 7 - SCART 2 Output Select (for devices with 2 Output SCART):
* 0 0 0 - SCART 1 DA to SCART 2 Output (reset position)
* 0 1 0 - SCART 1 Input to SCART 2 Output
* 1 0 0 - MONO input to SCART 2 Output
* 0 0 1 - SCART 2 DA to SCART 2 Output
* 0 1 1 - SCART 2 Input to SCART 2 Output
* 1 1 0 - Mute SCART 2 Output
*
* Bits 4 to 0 should be zero.
* ----------------------------------------------------------------------- */
static int scarts[3][9] = {
/* MASK IN1 IN2 IN3 IN4 IN1_DA IN2_DA MONO MUTE */
/* SCART DSP Input select */
{ 0x0320, 0x0000, 0x0200, 0x0300, 0x0020, -1, -1, 0x0100, 0x0320 },
/* SCART1 Output select */
{ 0x0c40, 0x0440, 0x0400, 0x0000, 0x0840, 0x0c00, 0x0040, 0x0800, 0x0c40 },
/* SCART2 Output select */
{ 0x3080, 0x1000, 0x1080, 0x2080, 0x3080, 0x0000, 0x0080, 0x2000, 0x3000 },
};
static char *scart_names[] = {
"in1", "in2", "in3", "in4", "in1 da", "in2 da", "mono", "mute"
};
void msp_set_scart(struct i2c_client *client, int in, int out)
{
struct msp_state *state = to_state(i2c_get_clientdata(client));
state->in_scart = in;
if (in >= 0 && in <= 7 && out >= 0 && out <= 2) {
if (-1 == scarts[out][in + 1])
return;
state->acb &= ~scarts[out][0];
state->acb |= scarts[out][in + 1];
} else
state->acb = 0xf60; /* Mute Input and SCART 1 Output */
v4l_dbg(1, msp_debug, client, "scart switch: %s => %d (ACB=0x%04x)\n",
scart_names[in], out, state->acb);
msp_write_dsp(client, 0x13, state->acb);
/* Sets I2S speed 0 = 1.024 Mbps, 1 = 2.048 Mbps */
if (state->has_i2s_conf)
msp_write_dem(client, 0x40, state->i2s_mode);
}
/* ------------------------------------------------------------------------ */
static void msp_wake_thread(struct i2c_client *client)
{
struct msp_state *state = to_state(i2c_get_clientdata(client));
if (NULL == state->kthread)
return;
state->watch_stereo = 0;
state->restart = 1;
wake_up_interruptible(&state->wq);
}
int msp_sleep(struct msp_state *state, int timeout)
{
DECLARE_WAITQUEUE(wait, current);
add_wait_queue(&state->wq, &wait);
if (!kthread_should_stop()) {
if (timeout < 0) {
set_current_state(TASK_INTERRUPTIBLE);
schedule();
} else {
schedule_timeout_interruptible
(msecs_to_jiffies(timeout));
}
}
remove_wait_queue(&state->wq, &wait);
try_to_freeze();
return state->restart;
}
/* ------------------------------------------------------------------------ */
static int msp_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct msp_state *state = ctrl_to_state(ctrl);
struct i2c_client *client = v4l2_get_subdevdata(&state->sd);
int val = ctrl->val;
switch (ctrl->id) {
case V4L2_CID_AUDIO_VOLUME: {
/* audio volume cluster */
int reallymuted = state->muted->val | state->scan_in_progress;
if (!reallymuted)
val = (val * 0x7f / 65535) << 8;
v4l_dbg(1, msp_debug, client, "mute=%s scanning=%s volume=%d\n",
state->muted->val ? "on" : "off",
state->scan_in_progress ? "yes" : "no",
state->volume->val);
msp_write_dsp(client, 0x0000, val);
msp_write_dsp(client, 0x0007, reallymuted ? 0x1 : (val | 0x1));
if (state->has_scart2_out_volume)
msp_write_dsp(client, 0x0040, reallymuted ? 0x1 : (val | 0x1));
if (state->has_headphones)
msp_write_dsp(client, 0x0006, val);
break;
}
case V4L2_CID_AUDIO_BASS:
val = ((val - 32768) * 0x60 / 65535) << 8;
msp_write_dsp(client, 0x0002, val);
if (state->has_headphones)
msp_write_dsp(client, 0x0031, val);
break;
case V4L2_CID_AUDIO_TREBLE:
val = ((val - 32768) * 0x60 / 65535) << 8;
msp_write_dsp(client, 0x0003, val);
if (state->has_headphones)
msp_write_dsp(client, 0x0032, val);
break;
case V4L2_CID_AUDIO_LOUDNESS:
val = val ? ((5 * 4) << 8) : 0;
msp_write_dsp(client, 0x0004, val);
if (state->has_headphones)
msp_write_dsp(client, 0x0033, val);
break;
case V4L2_CID_AUDIO_BALANCE:
val = (u8)((val / 256) - 128);
msp_write_dsp(client, 0x0001, val << 8);
if (state->has_headphones)
msp_write_dsp(client, 0x0030, val << 8);
break;
default:
return -EINVAL;
}
return 0;
}
void msp_update_volume(struct msp_state *state)
{
/* Force an update of the volume/mute cluster */
v4l2_ctrl_lock(state->volume);
state->volume->val = state->volume->cur.val;
state->muted->val = state->muted->cur.val;
msp_s_ctrl(state->volume);
v4l2_ctrl_unlock(state->volume);
}
/* --- v4l2 ioctls --- */
static int msp_s_radio(struct v4l2_subdev *sd)
{
struct msp_state *state = to_state(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
if (state->radio)
return 0;
state->radio = 1;
v4l_dbg(1, msp_debug, client, "switching to radio mode\n");
state->watch_stereo = 0;
switch (state->opmode) {
case OPMODE_MANUAL:
/* set msp3400 to FM radio mode */
msp3400c_set_mode(client, MSP_MODE_FM_RADIO);
msp3400c_set_carrier(client, MSP_CARRIER(10.7),
MSP_CARRIER(10.7));
msp_update_volume(state);
break;
case OPMODE_AUTODETECT:
case OPMODE_AUTOSELECT:
/* the thread will do for us */
msp_wake_thread(client);
break;
}
return 0;
}
static int msp_s_frequency(struct v4l2_subdev *sd, struct v4l2_frequency *freq)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
/* new channel -- kick audio carrier scan */
msp_wake_thread(client);
return 0;
}
static int msp_querystd(struct v4l2_subdev *sd, v4l2_std_id *id)
{
struct msp_state *state = to_state(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
*id &= state->detected_std;
v4l_dbg(2, msp_debug, client,
"detected standard: %s(0x%08Lx)\n",
msp_standard_std_name(state->std), state->detected_std);
return 0;
}
static int msp_s_std(struct v4l2_subdev *sd, v4l2_std_id id)
{
struct msp_state *state = to_state(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
int update = state->radio || state->v4l2_std != id;
state->v4l2_std = id;
state->radio = 0;
if (update)
msp_wake_thread(client);
return 0;
}
static int msp_s_routing(struct v4l2_subdev *sd,
u32 input, u32 output, u32 config)
{
struct msp_state *state = to_state(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
int tuner = (input >> 3) & 1;
int sc_in = input & 0x7;
int sc1_out = output & 0xf;
int sc2_out = (output >> 4) & 0xf;
u16 val, reg;
int i;
int extern_input = 1;
if (state->route_in == input && state->route_out == output)
return 0;
state->route_in = input;
state->route_out = output;
/* check if the tuner input is used */
for (i = 0; i < 5; i++) {
if (((input >> (4 + i * 4)) & 0xf) == 0)
extern_input = 0;
}
state->mode = extern_input ? MSP_MODE_EXTERN : MSP_MODE_AM_DETECT;
state->rxsubchans = V4L2_TUNER_SUB_STEREO;
msp_set_scart(client, sc_in, 0);
msp_set_scart(client, sc1_out, 1);
msp_set_scart(client, sc2_out, 2);
msp_set_audmode(client);
reg = (state->opmode == OPMODE_AUTOSELECT) ? 0x30 : 0xbb;
val = msp_read_dem(client, reg);
msp_write_dem(client, reg, (val & ~0x100) | (tuner << 8));
/* wake thread when a new input is chosen */
msp_wake_thread(client);
return 0;
}
static int msp_g_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *vt)
{
struct msp_state *state = to_state(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
if (vt->type != V4L2_TUNER_ANALOG_TV)
return 0;
if (!state->radio) {
if (state->opmode == OPMODE_AUTOSELECT)
msp_detect_stereo(client);
vt->rxsubchans = state->rxsubchans;
}
vt->audmode = state->audmode;
vt->capability |= V4L2_TUNER_CAP_STEREO |
V4L2_TUNER_CAP_LANG1 | V4L2_TUNER_CAP_LANG2;
return 0;
}
static int msp_s_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *vt)
{
struct msp_state *state = to_state(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
if (state->radio) /* TODO: add mono/stereo support for radio */
return 0;
if (state->audmode == vt->audmode)
return 0;
state->audmode = vt->audmode;
/* only set audmode */
msp_set_audmode(client);
return 0;
}
static int msp_s_i2s_clock_freq(struct v4l2_subdev *sd, u32 freq)
{
struct msp_state *state = to_state(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
v4l_dbg(1, msp_debug, client, "Setting I2S speed to %d\n", freq);
switch (freq) {
case 1024000:
state->i2s_mode = 0;
break;
case 2048000:
state->i2s_mode = 1;
break;
default:
return -EINVAL;
}
return 0;
}
static int msp_g_chip_ident(struct v4l2_subdev *sd, struct v4l2_dbg_chip_ident *chip)
{
struct msp_state *state = to_state(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
return v4l2_chip_ident_i2c_client(client, chip, state->ident,
(state->rev1 << 16) | state->rev2);
}
static int msp_log_status(struct v4l2_subdev *sd)
{
struct msp_state *state = to_state(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
const char *p;
char prefix[V4L2_SUBDEV_NAME_SIZE + 20];
if (state->opmode == OPMODE_AUTOSELECT)
msp_detect_stereo(client);
v4l_info(client, "%s rev1 = 0x%04x rev2 = 0x%04x\n",
client->name, state->rev1, state->rev2);
snprintf(prefix, sizeof(prefix), "%s: Audio: ", sd->name);
v4l2_ctrl_handler_log_status(&state->hdl, prefix);
switch (state->mode) {
case MSP_MODE_AM_DETECT: p = "AM (for carrier detect)"; break;
case MSP_MODE_FM_RADIO: p = "FM Radio"; break;
case MSP_MODE_FM_TERRA: p = "Terrestrial FM-mono/stereo"; break;
case MSP_MODE_FM_SAT: p = "Satellite FM-mono"; break;
case MSP_MODE_FM_NICAM1: p = "NICAM/FM (B/G, D/K)"; break;
case MSP_MODE_FM_NICAM2: p = "NICAM/FM (I)"; break;
case MSP_MODE_AM_NICAM: p = "NICAM/AM (L)"; break;
case MSP_MODE_BTSC: p = "BTSC"; break;
case MSP_MODE_EXTERN: p = "External input"; break;
default: p = "unknown"; break;
}
if (state->mode == MSP_MODE_EXTERN) {
v4l_info(client, "Mode: %s\n", p);
} else if (state->opmode == OPMODE_MANUAL) {
v4l_info(client, "Mode: %s (%s%s)\n", p,
(state->rxsubchans & V4L2_TUNER_SUB_STEREO) ? "stereo" : "mono",
(state->rxsubchans & V4L2_TUNER_SUB_LANG2) ? ", dual" : "");
} else {
if (state->opmode == OPMODE_AUTODETECT)
v4l_info(client, "Mode: %s\n", p);
v4l_info(client, "Standard: %s (%s%s)\n",
msp_standard_std_name(state->std),
(state->rxsubchans & V4L2_TUNER_SUB_STEREO) ? "stereo" : "mono",
(state->rxsubchans & V4L2_TUNER_SUB_LANG2) ? ", dual" : "");
}
v4l_info(client, "Audmode: 0x%04x\n", state->audmode);
v4l_info(client, "Routing: 0x%08x (input) 0x%08x (output)\n",
state->route_in, state->route_out);
v4l_info(client, "ACB: 0x%04x\n", state->acb);
return 0;
}
static int msp_suspend(struct i2c_client *client, pm_message_t state)
{
v4l_dbg(1, msp_debug, client, "suspend\n");
msp_reset(client);
return 0;
}
static int msp_resume(struct i2c_client *client)
{
v4l_dbg(1, msp_debug, client, "resume\n");
msp_wake_thread(client);
return 0;
}
/* ----------------------------------------------------------------------- */
static const struct v4l2_ctrl_ops msp_ctrl_ops = {
.s_ctrl = msp_s_ctrl,
};
static const struct v4l2_subdev_core_ops msp_core_ops = {
.log_status = msp_log_status,
.g_chip_ident = msp_g_chip_ident,
.g_ext_ctrls = v4l2_subdev_g_ext_ctrls,
.try_ext_ctrls = v4l2_subdev_try_ext_ctrls,
.s_ext_ctrls = v4l2_subdev_s_ext_ctrls,
.g_ctrl = v4l2_subdev_g_ctrl,
.s_ctrl = v4l2_subdev_s_ctrl,
.queryctrl = v4l2_subdev_queryctrl,
.querymenu = v4l2_subdev_querymenu,
.s_std = msp_s_std,
};
static const struct v4l2_subdev_video_ops msp_video_ops = {
.querystd = msp_querystd,
};
static const struct v4l2_subdev_tuner_ops msp_tuner_ops = {
.s_frequency = msp_s_frequency,
.g_tuner = msp_g_tuner,
.s_tuner = msp_s_tuner,
.s_radio = msp_s_radio,
};
static const struct v4l2_subdev_audio_ops msp_audio_ops = {
.s_routing = msp_s_routing,
.s_i2s_clock_freq = msp_s_i2s_clock_freq,
};
static const struct v4l2_subdev_ops msp_ops = {
.core = &msp_core_ops,
.video = &msp_video_ops,
.tuner = &msp_tuner_ops,
.audio = &msp_audio_ops,
};
/* ----------------------------------------------------------------------- */
static int msp_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
struct msp_state *state;
struct v4l2_subdev *sd;
struct v4l2_ctrl_handler *hdl;
int (*thread_func)(void *data) = NULL;
int msp_hard;
int msp_family;
int msp_revision;
int msp_product, msp_prod_hi, msp_prod_lo;
int msp_rom;
if (!id)
strlcpy(client->name, "msp3400", sizeof(client->name));
if (msp_reset(client) == -1) {
v4l_dbg(1, msp_debug, client, "msp3400 not found\n");
return -ENODEV;
}
state = kzalloc(sizeof(*state), GFP_KERNEL);
if (!state)
return -ENOMEM;
sd = &state->sd;
v4l2_i2c_subdev_init(sd, client, &msp_ops);
state->v4l2_std = V4L2_STD_NTSC;
state->detected_std = V4L2_STD_ALL;
state->audmode = V4L2_TUNER_MODE_STEREO;
state->input = -1;
state->i2s_mode = 0;
init_waitqueue_head(&state->wq);
/* These are the reset input/output positions */
state->route_in = MSP_INPUT_DEFAULT;
state->route_out = MSP_OUTPUT_DEFAULT;
state->rev1 = msp_read_dsp(client, 0x1e);
if (state->rev1 != -1)
state->rev2 = msp_read_dsp(client, 0x1f);
v4l_dbg(1, msp_debug, client, "rev1=0x%04x, rev2=0x%04x\n",
state->rev1, state->rev2);
if (state->rev1 == -1 || (state->rev1 == 0 && state->rev2 == 0)) {
v4l_dbg(1, msp_debug, client,
"not an msp3400 (cannot read chip version)\n");
kfree(state);
return -ENODEV;
}
msp_family = ((state->rev1 >> 4) & 0x0f) + 3;
msp_product = (state->rev2 >> 8) & 0xff;
msp_prod_hi = msp_product / 10;
msp_prod_lo = msp_product % 10;
msp_revision = (state->rev1 & 0x0f) + '@';
msp_hard = ((state->rev1 >> 8) & 0xff) + '@';
msp_rom = state->rev2 & 0x1f;
/* Rev B=2, C=3, D=4, G=7 */
state->ident = msp_family * 10000 + 4000 + msp_product * 10 +
msp_revision - '@';
/* Has NICAM support: all mspx41x and mspx45x products have NICAM */
state->has_nicam =
msp_prod_hi == 1 || msp_prod_hi == 5;
/* Has radio support: was added with revision G */
state->has_radio =
msp_revision >= 'G';
/* Has headphones output: not for stripped down products */
state->has_headphones =
msp_prod_lo < 5;
/* Has scart2 input: not in stripped down products of the '3' family */
state->has_scart2 =
msp_family >= 4 || msp_prod_lo < 7;
/* Has scart3 input: not in stripped down products of the '3' family */
state->has_scart3 =
msp_family >= 4 || msp_prod_lo < 5;
/* Has scart4 input: not in pre D revisions, not in stripped D revs */
state->has_scart4 =
msp_family >= 4 || (msp_revision >= 'D' && msp_prod_lo < 5);
/* Has scart2 output: not in stripped down products of
* the '3' family */
state->has_scart2_out =
msp_family >= 4 || msp_prod_lo < 5;
/* Has scart2 a volume control? Not in pre-D revisions. */
state->has_scart2_out_volume =
msp_revision > 'C' && state->has_scart2_out;
/* Has a configurable i2s out? */
state->has_i2s_conf =
msp_revision >= 'G' && msp_prod_lo < 7;
/* Has subwoofer output: not in pre-D revs and not in stripped down
* products */
state->has_subwoofer =
msp_revision >= 'D' && msp_prod_lo < 5;
/* Has soundprocessing (bass/treble/balance/loudness/equalizer):
* not in stripped down products */
state->has_sound_processing =
msp_prod_lo < 7;
/* Has Virtual Dolby Surround: only in msp34x1 */
state->has_virtual_dolby_surround =
msp_revision == 'G' && msp_prod_lo == 1;
/* Has Virtual Dolby Surround & Dolby Pro Logic: only in msp34x2 */
state->has_dolby_pro_logic =
msp_revision == 'G' && msp_prod_lo == 2;
/* The msp343xG supports BTSC only and cannot do Automatic Standard
* Detection. */
state->force_btsc =
msp_family == 3 && msp_revision == 'G' && msp_prod_hi == 3;
state->opmode = opmode;
if (state->opmode == OPMODE_AUTO) {
/* MSP revision G and up have both autodetect and autoselect */
if (msp_revision >= 'G')
state->opmode = OPMODE_AUTOSELECT;
/* MSP revision D and up have autodetect */
else if (msp_revision >= 'D')
state->opmode = OPMODE_AUTODETECT;
else
state->opmode = OPMODE_MANUAL;
}
hdl = &state->hdl;
v4l2_ctrl_handler_init(hdl, 6);
if (state->has_sound_processing) {
v4l2_ctrl_new_std(hdl, &msp_ctrl_ops,
V4L2_CID_AUDIO_BASS, 0, 65535, 65535 / 100, 32768);
v4l2_ctrl_new_std(hdl, &msp_ctrl_ops,
V4L2_CID_AUDIO_TREBLE, 0, 65535, 65535 / 100, 32768);
v4l2_ctrl_new_std(hdl, &msp_ctrl_ops,
V4L2_CID_AUDIO_LOUDNESS, 0, 1, 1, 0);
}
state->volume = v4l2_ctrl_new_std(hdl, &msp_ctrl_ops,
V4L2_CID_AUDIO_VOLUME, 0, 65535, 65535 / 100, 58880);
v4l2_ctrl_new_std(hdl, &msp_ctrl_ops,
V4L2_CID_AUDIO_BALANCE, 0, 65535, 65535 / 100, 32768);
state->muted = v4l2_ctrl_new_std(hdl, &msp_ctrl_ops,
V4L2_CID_AUDIO_MUTE, 0, 1, 1, 0);
sd->ctrl_handler = hdl;
if (hdl->error) {
int err = hdl->error;
v4l2_ctrl_handler_free(hdl);
kfree(state);
return err;
}
v4l2_ctrl_cluster(2, &state->volume);
v4l2_ctrl_handler_setup(hdl);
/* hello world :-) */
v4l_info(client, "MSP%d4%02d%c-%c%d found @ 0x%x (%s)\n",
msp_family, msp_product,
msp_revision, msp_hard, msp_rom,
client->addr << 1, client->adapter->name);
v4l_info(client, "%s ", client->name);
if (state->has_nicam && state->has_radio)
printk(KERN_CONT "supports nicam and radio, ");
else if (state->has_nicam)
printk(KERN_CONT "supports nicam, ");
else if (state->has_radio)
printk(KERN_CONT "supports radio, ");
printk(KERN_CONT "mode is ");
/* version-specific initialization */
switch (state->opmode) {
case OPMODE_MANUAL:
printk(KERN_CONT "manual");
thread_func = msp3400c_thread;
break;
case OPMODE_AUTODETECT:
printk(KERN_CONT "autodetect");
thread_func = msp3410d_thread;
break;
case OPMODE_AUTOSELECT:
printk(KERN_CONT "autodetect and autoselect");
thread_func = msp34xxg_thread;
break;
}
printk(KERN_CONT "\n");
/* startup control thread if needed */
if (thread_func) {
state->kthread = kthread_run(thread_func, client, "msp34xx");
if (IS_ERR(state->kthread))
v4l_warn(client, "kernel_thread() failed\n");
msp_wake_thread(client);
}
return 0;
}
static int msp_remove(struct i2c_client *client)
{
struct msp_state *state = to_state(i2c_get_clientdata(client));
v4l2_device_unregister_subdev(&state->sd);
/* shutdown control thread */
if (state->kthread) {
state->restart = 1;
kthread_stop(state->kthread);
}
msp_reset(client);
v4l2_ctrl_handler_free(&state->hdl);
kfree(state);
return 0;
}
/* ----------------------------------------------------------------------- */
static const struct i2c_device_id msp_id[] = {
{ "msp3400", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, msp_id);
static struct i2c_driver msp_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "msp3400",
},
.probe = msp_probe,
.remove = msp_remove,
.suspend = msp_suspend,
.resume = msp_resume,
.id_table = msp_id,
};
module_i2c_driver(msp_driver);
/*
* Overrides for Emacs so that we follow Linus's tabbing style.
* ---------------------------------------------------------------------------
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
slayher/android_kernel_samsung_hlte | drivers/power/max8997_charger.c | 5067 | 5421 | /*
* max8997_charger.c - Power supply consumer driver for the Maxim 8997/8966
*
* Copyright (C) 2011 Samsung Electronics
* 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
*/
#include <linux/err.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/mfd/max8997.h>
#include <linux/mfd/max8997-private.h>
struct charger_data {
struct device *dev;
struct max8997_dev *iodev;
struct power_supply battery;
};
static enum power_supply_property max8997_battery_props[] = {
POWER_SUPPLY_PROP_STATUS, /* "FULL" or "NOT FULL" only. */
POWER_SUPPLY_PROP_PRESENT, /* the presence of battery */
POWER_SUPPLY_PROP_ONLINE, /* charger is active or not */
};
/* Note that the charger control is done by a current regulator "CHARGER" */
static int max8997_battery_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct charger_data *charger = container_of(psy,
struct charger_data, battery);
struct i2c_client *i2c = charger->iodev->i2c;
int ret;
u8 reg;
switch (psp) {
case POWER_SUPPLY_PROP_STATUS:
val->intval = 0;
ret = max8997_read_reg(i2c, MAX8997_REG_STATUS4, ®);
if (ret)
return ret;
if ((reg & (1 << 0)) == 0x1)
val->intval = POWER_SUPPLY_STATUS_FULL;
break;
case POWER_SUPPLY_PROP_PRESENT:
val->intval = 0;
ret = max8997_read_reg(i2c, MAX8997_REG_STATUS4, ®);
if (ret)
return ret;
if ((reg & (1 << 2)) == 0x0)
val->intval = 1;
break;
case POWER_SUPPLY_PROP_ONLINE:
val->intval = 0;
ret = max8997_read_reg(i2c, MAX8997_REG_STATUS4, ®);
if (ret)
return ret;
/* DCINOK */
if (reg & (1 << 1))
val->intval = 1;
break;
default:
return -EINVAL;
}
return 0;
}
static __devinit int max8997_battery_probe(struct platform_device *pdev)
{
int ret = 0;
struct charger_data *charger;
struct max8997_dev *iodev = dev_get_drvdata(pdev->dev.parent);
struct max8997_platform_data *pdata = dev_get_platdata(iodev->dev);
if (!pdata)
return -EINVAL;
if (pdata->eoc_mA) {
int val = (pdata->eoc_mA - 50) / 10;
if (val < 0)
val = 0;
if (val > 0xf)
val = 0xf;
ret = max8997_update_reg(iodev->i2c,
MAX8997_REG_MBCCTRL5, val, 0xf);
if (ret < 0) {
dev_err(&pdev->dev, "Cannot use i2c bus.\n");
return ret;
}
}
switch (pdata->timeout) {
case 5:
ret = max8997_update_reg(iodev->i2c, MAX8997_REG_MBCCTRL1,
0x2 << 4, 0x7 << 4);
break;
case 6:
ret = max8997_update_reg(iodev->i2c, MAX8997_REG_MBCCTRL1,
0x3 << 4, 0x7 << 4);
break;
case 7:
ret = max8997_update_reg(iodev->i2c, MAX8997_REG_MBCCTRL1,
0x4 << 4, 0x7 << 4);
break;
case 0:
ret = max8997_update_reg(iodev->i2c, MAX8997_REG_MBCCTRL1,
0x7 << 4, 0x7 << 4);
break;
default:
dev_err(&pdev->dev, "incorrect timeout value (%d)\n",
pdata->timeout);
return -EINVAL;
}
if (ret < 0) {
dev_err(&pdev->dev, "Cannot use i2c bus.\n");
return ret;
}
charger = kzalloc(sizeof(struct charger_data), GFP_KERNEL);
if (charger == NULL) {
dev_err(&pdev->dev, "Cannot allocate memory.\n");
return -ENOMEM;
}
platform_set_drvdata(pdev, charger);
charger->battery.name = "max8997_pmic";
charger->battery.type = POWER_SUPPLY_TYPE_BATTERY;
charger->battery.get_property = max8997_battery_get_property;
charger->battery.properties = max8997_battery_props;
charger->battery.num_properties = ARRAY_SIZE(max8997_battery_props);
charger->dev = &pdev->dev;
charger->iodev = iodev;
ret = power_supply_register(&pdev->dev, &charger->battery);
if (ret) {
dev_err(&pdev->dev, "failed: power supply register\n");
goto err;
}
return 0;
err:
kfree(charger);
return ret;
}
static int __devexit max8997_battery_remove(struct platform_device *pdev)
{
struct charger_data *charger = platform_get_drvdata(pdev);
power_supply_unregister(&charger->battery);
kfree(charger);
return 0;
}
static const struct platform_device_id max8997_battery_id[] = {
{ "max8997-battery", 0 },
{ }
};
static struct platform_driver max8997_battery_driver = {
.driver = {
.name = "max8997-battery",
.owner = THIS_MODULE,
},
.probe = max8997_battery_probe,
.remove = __devexit_p(max8997_battery_remove),
.id_table = max8997_battery_id,
};
static int __init max8997_battery_init(void)
{
return platform_driver_register(&max8997_battery_driver);
}
subsys_initcall(max8997_battery_init);
static void __exit max8997_battery_cleanup(void)
{
platform_driver_unregister(&max8997_battery_driver);
}
module_exit(max8997_battery_cleanup);
MODULE_DESCRIPTION("MAXIM 8997/8966 battery control driver");
MODULE_AUTHOR("MyungJoo Ham <myungjoo.ham@samsung.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
bestmjh47/android_kernel_kttech_e100_kk | arch/mips/pci/pci-rc32434.c | 5323 | 7483 | /*
* BRIEF MODULE DESCRIPTION
* PCI initialization for IDT EB434 board
*
* Copyright 2004 IDT Inc. (rischelp@idt.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 SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <asm/mach-rc32434/rc32434.h>
#include <asm/mach-rc32434/pci.h>
#define PCI_ACCESS_READ 0
#define PCI_ACCESS_WRITE 1
/* define an unsigned array for the PCI registers */
static unsigned int korina_cnfg_regs[25] = {
KORINA_CNFG1, KORINA_CNFG2, KORINA_CNFG3, KORINA_CNFG4,
KORINA_CNFG5, KORINA_CNFG6, KORINA_CNFG7, KORINA_CNFG8,
KORINA_CNFG9, KORINA_CNFG10, KORINA_CNFG11, KORINA_CNFG12,
KORINA_CNFG13, KORINA_CNFG14, KORINA_CNFG15, KORINA_CNFG16,
KORINA_CNFG17, KORINA_CNFG18, KORINA_CNFG19, KORINA_CNFG20,
KORINA_CNFG21, KORINA_CNFG22, KORINA_CNFG23, KORINA_CNFG24
};
static struct resource rc32434_res_pci_mem1;
static struct resource rc32434_res_pci_mem2;
static struct resource rc32434_res_pci_mem1 = {
.name = "PCI MEM1",
.start = 0x50000000,
.end = 0x5FFFFFFF,
.flags = IORESOURCE_MEM,
.parent = &rc32434_res_pci_mem1,
.sibling = NULL,
.child = &rc32434_res_pci_mem2
};
static struct resource rc32434_res_pci_mem2 = {
.name = "PCI Mem2",
.start = 0x60000000,
.end = 0x6FFFFFFF,
.flags = IORESOURCE_MEM,
.parent = &rc32434_res_pci_mem1,
.sibling = NULL,
.child = NULL
};
static struct resource rc32434_res_pci_io1 = {
.name = "PCI I/O1",
.start = 0x18800000,
.end = 0x188FFFFF,
.flags = IORESOURCE_IO,
};
extern struct pci_ops rc32434_pci_ops;
#define PCI_MEM1_START PCI_ADDR_START
#define PCI_MEM1_END (PCI_ADDR_START + CPUTOPCI_MEM_WIN - 1)
#define PCI_MEM2_START (PCI_ADDR_START + CPUTOPCI_MEM_WIN)
#define PCI_MEM2_END (PCI_ADDR_START + (2 * CPUTOPCI_MEM_WIN) - 1)
#define PCI_IO1_START (PCI_ADDR_START + (2 * CPUTOPCI_MEM_WIN))
#define PCI_IO1_END \
(PCI_ADDR_START + (2 * CPUTOPCI_MEM_WIN) + CPUTOPCI_IO_WIN - 1)
#define PCI_IO2_START \
(PCI_ADDR_START + (2 * CPUTOPCI_MEM_WIN) + CPUTOPCI_IO_WIN)
#define PCI_IO2_END \
(PCI_ADDR_START + (2 * CPUTOPCI_MEM_WIN) + (2 * CPUTOPCI_IO_WIN) - 1)
struct pci_controller rc32434_controller2;
struct pci_controller rc32434_controller = {
.pci_ops = &rc32434_pci_ops,
.mem_resource = &rc32434_res_pci_mem1,
.io_resource = &rc32434_res_pci_io1,
.mem_offset = 0,
.io_offset = 0,
};
#ifdef __MIPSEB__
#define PCI_ENDIAN_FLAG PCILBAC_sb_m
#else
#define PCI_ENDIAN_FLAG 0
#endif
static int __init rc32434_pcibridge_init(void)
{
unsigned int pcicvalue, pcicdata = 0;
unsigned int dummyread, pcicntlval;
int loopCount;
unsigned int pci_config_addr;
pcicvalue = rc32434_pci->pcic;
pcicvalue = (pcicvalue >> PCIM_SHFT) & PCIM_BIT_LEN;
if (!((pcicvalue == PCIM_H_EA) ||
(pcicvalue == PCIM_H_IA_FIX) ||
(pcicvalue == PCIM_H_IA_RR))) {
pr_err("PCI init error!!!\n");
/* Not in Host Mode, return ERROR */
return -1;
}
/* Enables the Idle Grant mode, Arbiter Parking */
pcicdata |= (PCI_CTL_IGM | PCI_CTL_EAP | PCI_CTL_EN);
rc32434_pci->pcic = pcicdata; /* Enable the PCI bus Interface */
/* Zero out the PCI status & PCI Status Mask */
for (;;) {
pcicdata = rc32434_pci->pcis;
if (!(pcicdata & PCI_STAT_RIP))
break;
}
rc32434_pci->pcis = 0;
rc32434_pci->pcism = 0xFFFFFFFF;
/* Zero out the PCI decoupled registers */
rc32434_pci->pcidac = 0; /*
* disable PCI decoupled accesses at
* initialization
*/
rc32434_pci->pcidas = 0; /* clear the status */
rc32434_pci->pcidasm = 0x0000007F; /* Mask all the interrupts */
/* Mask PCI Messaging Interrupts */
rc32434_pci_msg->pciiic = 0;
rc32434_pci_msg->pciiim = 0xFFFFFFFF;
rc32434_pci_msg->pciioic = 0;
rc32434_pci_msg->pciioim = 0;
/* Setup PCILB0 as Memory Window */
rc32434_pci->pcilba[0].address = (unsigned int) (PCI_ADDR_START);
/* setup the PCI map address as same as the local address */
rc32434_pci->pcilba[0].mapping = (unsigned int) (PCI_ADDR_START);
/* Setup PCILBA1 as MEM */
rc32434_pci->pcilba[0].control =
(((SIZE_256MB & 0x1f) << PCI_LBAC_SIZE_BIT) | PCI_ENDIAN_FLAG);
dummyread = rc32434_pci->pcilba[0].control; /* flush the CPU write Buffers */
rc32434_pci->pcilba[1].address = 0x60000000;
rc32434_pci->pcilba[1].mapping = 0x60000000;
/* setup PCILBA2 as IO Window */
rc32434_pci->pcilba[1].control =
(((SIZE_256MB & 0x1f) << PCI_LBAC_SIZE_BIT) | PCI_ENDIAN_FLAG);
dummyread = rc32434_pci->pcilba[1].control; /* flush the CPU write Buffers */
rc32434_pci->pcilba[2].address = 0x18C00000;
rc32434_pci->pcilba[2].mapping = 0x18FFFFFF;
/* setup PCILBA2 as IO Window */
rc32434_pci->pcilba[2].control =
(((SIZE_4MB & 0x1f) << PCI_LBAC_SIZE_BIT) | PCI_ENDIAN_FLAG);
dummyread = rc32434_pci->pcilba[2].control; /* flush the CPU write Buffers */
/* Setup PCILBA3 as IO Window */
rc32434_pci->pcilba[3].address = 0x18800000;
rc32434_pci->pcilba[3].mapping = 0x18800000;
rc32434_pci->pcilba[3].control =
((((SIZE_1MB & 0x1ff) << PCI_LBAC_SIZE_BIT) | PCI_LBAC_MSI) |
PCI_ENDIAN_FLAG);
dummyread = rc32434_pci->pcilba[3].control; /* flush the CPU write Buffers */
pci_config_addr = (unsigned int) (0x80000004);
for (loopCount = 0; loopCount < 24; loopCount++) {
rc32434_pci->pcicfga = pci_config_addr;
dummyread = rc32434_pci->pcicfga;
rc32434_pci->pcicfgd = korina_cnfg_regs[loopCount];
dummyread = rc32434_pci->pcicfgd;
pci_config_addr += 4;
}
rc32434_pci->pcitc =
(unsigned int) ((PCITC_RTIMER_VAL & 0xff) << PCI_TC_RTIMER_BIT) |
((PCITC_DTIMER_VAL & 0xff) << PCI_TC_DTIMER_BIT);
pcicntlval = rc32434_pci->pcic;
pcicntlval &= ~PCI_CTL_TNR;
rc32434_pci->pcic = pcicntlval;
pcicntlval = rc32434_pci->pcic;
return 0;
}
static int __init rc32434_pci_init(void)
{
void __iomem *io_map_base;
pr_info("PCI: Initializing PCI\n");
ioport_resource.start = rc32434_res_pci_io1.start;
ioport_resource.end = rc32434_res_pci_io1.end;
rc32434_pcibridge_init();
io_map_base = ioremap(rc32434_res_pci_io1.start,
resource_size(&rc32434_res_pci_io1));
if (!io_map_base)
return -ENOMEM;
rc32434_controller.io_map_base =
(unsigned long)io_map_base - rc32434_res_pci_io1.start;
register_pci_controller(&rc32434_controller);
rc32434_sync();
return 0;
}
arch_initcall(rc32434_pci_init);
| gpl-2.0 |
NitroKK/kernel_lge_iproj | drivers/staging/rtl8192u/ieee80211/ieee80211_crypt_ccmp.c | 7883 | 11400 | /*
* Host AP crypt: host-based CCMP encryption implementation for Host AP driver
*
* Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.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. See README and COPYING for
* more details.
*/
//#include <linux/config.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/random.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/if_ether.h>
#include <linux/if_arp.h>
#include <asm/string.h>
#include <linux/wireless.h>
#include "ieee80211.h"
#include <linux/crypto.h>
#include <linux/scatterlist.h>
MODULE_AUTHOR("Jouni Malinen");
MODULE_DESCRIPTION("Host AP crypt: CCMP");
MODULE_LICENSE("GPL");
#define AES_BLOCK_LEN 16
#define CCMP_HDR_LEN 8
#define CCMP_MIC_LEN 8
#define CCMP_TK_LEN 16
#define CCMP_PN_LEN 6
struct ieee80211_ccmp_data {
u8 key[CCMP_TK_LEN];
int key_set;
u8 tx_pn[CCMP_PN_LEN];
u8 rx_pn[CCMP_PN_LEN];
u32 dot11RSNAStatsCCMPFormatErrors;
u32 dot11RSNAStatsCCMPReplays;
u32 dot11RSNAStatsCCMPDecryptErrors;
int key_idx;
struct crypto_tfm *tfm;
/* scratch buffers for virt_to_page() (crypto API) */
u8 tx_b0[AES_BLOCK_LEN], tx_b[AES_BLOCK_LEN],
tx_e[AES_BLOCK_LEN], tx_s0[AES_BLOCK_LEN];
u8 rx_b0[AES_BLOCK_LEN], rx_b[AES_BLOCK_LEN], rx_a[AES_BLOCK_LEN];
};
void ieee80211_ccmp_aes_encrypt(struct crypto_tfm *tfm,
const u8 pt[16], u8 ct[16])
{
crypto_cipher_encrypt_one((void*)tfm, ct, pt);
}
static void * ieee80211_ccmp_init(int key_idx)
{
struct ieee80211_ccmp_data *priv;
priv = kzalloc(sizeof(*priv), GFP_ATOMIC);
if (priv == NULL)
goto fail;
priv->key_idx = key_idx;
priv->tfm = (void*)crypto_alloc_cipher("aes", 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(priv->tfm)) {
printk(KERN_DEBUG "ieee80211_crypt_ccmp: could not allocate "
"crypto API aes\n");
priv->tfm = NULL;
goto fail;
}
return priv;
fail:
if (priv) {
if (priv->tfm)
crypto_free_cipher((void*)priv->tfm);
kfree(priv);
}
return NULL;
}
static void ieee80211_ccmp_deinit(void *priv)
{
struct ieee80211_ccmp_data *_priv = priv;
if (_priv && _priv->tfm)
crypto_free_cipher((void*)_priv->tfm);
kfree(priv);
}
static inline void xor_block(u8 *b, u8 *a, size_t len)
{
int i;
for (i = 0; i < len; i++)
b[i] ^= a[i];
}
static void ccmp_init_blocks(struct crypto_tfm *tfm,
struct ieee80211_hdr_4addr *hdr,
u8 *pn, size_t dlen, u8 *b0, u8 *auth,
u8 *s0)
{
u8 *pos, qc = 0;
size_t aad_len;
u16 fc;
int a4_included, qc_included;
u8 aad[2 * AES_BLOCK_LEN];
fc = le16_to_cpu(hdr->frame_ctl);
a4_included = ((fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) ==
(IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS));
/*
qc_included = ((WLAN_FC_GET_TYPE(fc) == IEEE80211_FTYPE_DATA) &&
(WLAN_FC_GET_STYPE(fc) & 0x08));
*/
// fixed by David :2006.9.6
qc_included = ((WLAN_FC_GET_TYPE(fc) == IEEE80211_FTYPE_DATA) &&
(WLAN_FC_GET_STYPE(fc) & 0x80));
aad_len = 22;
if (a4_included)
aad_len += 6;
if (qc_included) {
pos = (u8 *) &hdr->addr4;
if (a4_included)
pos += 6;
qc = *pos & 0x0f;
aad_len += 2;
}
/* CCM Initial Block:
* Flag (Include authentication header, M=3 (8-octet MIC),
* L=1 (2-octet Dlen))
* Nonce: 0x00 | A2 | PN
* Dlen */
b0[0] = 0x59;
b0[1] = qc;
memcpy(b0 + 2, hdr->addr2, ETH_ALEN);
memcpy(b0 + 8, pn, CCMP_PN_LEN);
b0[14] = (dlen >> 8) & 0xff;
b0[15] = dlen & 0xff;
/* AAD:
* FC with bits 4..6 and 11..13 masked to zero; 14 is always one
* A1 | A2 | A3
* SC with bits 4..15 (seq#) masked to zero
* A4 (if present)
* QC (if present)
*/
pos = (u8 *) hdr;
aad[0] = 0; /* aad_len >> 8 */
aad[1] = aad_len & 0xff;
aad[2] = pos[0] & 0x8f;
aad[3] = pos[1] & 0xc7;
memcpy(aad + 4, hdr->addr1, 3 * ETH_ALEN);
pos = (u8 *) &hdr->seq_ctl;
aad[22] = pos[0] & 0x0f;
aad[23] = 0; /* all bits masked */
memset(aad + 24, 0, 8);
if (a4_included)
memcpy(aad + 24, hdr->addr4, ETH_ALEN);
if (qc_included) {
aad[a4_included ? 30 : 24] = qc;
/* rest of QC masked */
}
/* Start with the first block and AAD */
ieee80211_ccmp_aes_encrypt(tfm, b0, auth);
xor_block(auth, aad, AES_BLOCK_LEN);
ieee80211_ccmp_aes_encrypt(tfm, auth, auth);
xor_block(auth, &aad[AES_BLOCK_LEN], AES_BLOCK_LEN);
ieee80211_ccmp_aes_encrypt(tfm, auth, auth);
b0[0] &= 0x07;
b0[14] = b0[15] = 0;
ieee80211_ccmp_aes_encrypt(tfm, b0, s0);
}
static int ieee80211_ccmp_encrypt(struct sk_buff *skb, int hdr_len, void *priv)
{
struct ieee80211_ccmp_data *key = priv;
int data_len, i;
u8 *pos;
struct ieee80211_hdr_4addr *hdr;
cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
if (skb_headroom(skb) < CCMP_HDR_LEN ||
skb_tailroom(skb) < CCMP_MIC_LEN ||
skb->len < hdr_len)
return -1;
data_len = skb->len - hdr_len;
pos = skb_push(skb, CCMP_HDR_LEN);
memmove(pos, pos + CCMP_HDR_LEN, hdr_len);
pos += hdr_len;
// mic = skb_put(skb, CCMP_MIC_LEN);
i = CCMP_PN_LEN - 1;
while (i >= 0) {
key->tx_pn[i]++;
if (key->tx_pn[i] != 0)
break;
i--;
}
*pos++ = key->tx_pn[5];
*pos++ = key->tx_pn[4];
*pos++ = 0;
*pos++ = (key->key_idx << 6) | (1 << 5) /* Ext IV included */;
*pos++ = key->tx_pn[3];
*pos++ = key->tx_pn[2];
*pos++ = key->tx_pn[1];
*pos++ = key->tx_pn[0];
hdr = (struct ieee80211_hdr_4addr *) skb->data;
if (!tcb_desc->bHwSec)
{
int blocks, last, len;
u8 *mic;
u8 *b0 = key->tx_b0;
u8 *b = key->tx_b;
u8 *e = key->tx_e;
u8 *s0 = key->tx_s0;
//mic is moved to here by john
mic = skb_put(skb, CCMP_MIC_LEN);
ccmp_init_blocks(key->tfm, hdr, key->tx_pn, data_len, b0, b, s0);
blocks = (data_len + AES_BLOCK_LEN - 1) / AES_BLOCK_LEN;
last = data_len % AES_BLOCK_LEN;
for (i = 1; i <= blocks; i++) {
len = (i == blocks && last) ? last : AES_BLOCK_LEN;
/* Authentication */
xor_block(b, pos, len);
ieee80211_ccmp_aes_encrypt(key->tfm, b, b);
/* Encryption, with counter */
b0[14] = (i >> 8) & 0xff;
b0[15] = i & 0xff;
ieee80211_ccmp_aes_encrypt(key->tfm, b0, e);
xor_block(pos, e, len);
pos += len;
}
for (i = 0; i < CCMP_MIC_LEN; i++)
mic[i] = b[i] ^ s0[i];
}
return 0;
}
static int ieee80211_ccmp_decrypt(struct sk_buff *skb, int hdr_len, void *priv)
{
struct ieee80211_ccmp_data *key = priv;
u8 keyidx, *pos;
struct ieee80211_hdr_4addr *hdr;
cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
u8 pn[6];
if (skb->len < hdr_len + CCMP_HDR_LEN + CCMP_MIC_LEN) {
key->dot11RSNAStatsCCMPFormatErrors++;
return -1;
}
hdr = (struct ieee80211_hdr_4addr *) skb->data;
pos = skb->data + hdr_len;
keyidx = pos[3];
if (!(keyidx & (1 << 5))) {
if (net_ratelimit()) {
printk(KERN_DEBUG "CCMP: received packet without ExtIV"
" flag from %pM\n", hdr->addr2);
}
key->dot11RSNAStatsCCMPFormatErrors++;
return -2;
}
keyidx >>= 6;
if (key->key_idx != keyidx) {
printk(KERN_DEBUG "CCMP: RX tkey->key_idx=%d frame "
"keyidx=%d priv=%p\n", key->key_idx, keyidx, priv);
return -6;
}
if (!key->key_set) {
if (net_ratelimit()) {
printk(KERN_DEBUG "CCMP: received packet from %pM"
" with keyid=%d that does not have a configured"
" key\n", hdr->addr2, keyidx);
}
return -3;
}
pn[0] = pos[7];
pn[1] = pos[6];
pn[2] = pos[5];
pn[3] = pos[4];
pn[4] = pos[1];
pn[5] = pos[0];
pos += 8;
if (memcmp(pn, key->rx_pn, CCMP_PN_LEN) <= 0) {
if (net_ratelimit()) {
printk(KERN_DEBUG "CCMP: replay detected: STA=%pM"
" previous PN %pm received PN %pm\n",
hdr->addr2, key->rx_pn, pn);
}
key->dot11RSNAStatsCCMPReplays++;
return -4;
}
if (!tcb_desc->bHwSec)
{
size_t data_len = skb->len - hdr_len - CCMP_HDR_LEN - CCMP_MIC_LEN;
u8 *mic = skb->data + skb->len - CCMP_MIC_LEN;
u8 *b0 = key->rx_b0;
u8 *b = key->rx_b;
u8 *a = key->rx_a;
int i, blocks, last, len;
ccmp_init_blocks(key->tfm, hdr, pn, data_len, b0, a, b);
xor_block(mic, b, CCMP_MIC_LEN);
blocks = (data_len + AES_BLOCK_LEN - 1) / AES_BLOCK_LEN;
last = data_len % AES_BLOCK_LEN;
for (i = 1; i <= blocks; i++) {
len = (i == blocks && last) ? last : AES_BLOCK_LEN;
/* Decrypt, with counter */
b0[14] = (i >> 8) & 0xff;
b0[15] = i & 0xff;
ieee80211_ccmp_aes_encrypt(key->tfm, b0, b);
xor_block(pos, b, len);
/* Authentication */
xor_block(a, pos, len);
ieee80211_ccmp_aes_encrypt(key->tfm, a, a);
pos += len;
}
if (memcmp(mic, a, CCMP_MIC_LEN) != 0) {
if (net_ratelimit()) {
printk(KERN_DEBUG "CCMP: decrypt failed: STA="
"%pM\n", hdr->addr2);
}
key->dot11RSNAStatsCCMPDecryptErrors++;
return -5;
}
memcpy(key->rx_pn, pn, CCMP_PN_LEN);
}
/* Remove hdr and MIC */
memmove(skb->data + CCMP_HDR_LEN, skb->data, hdr_len);
skb_pull(skb, CCMP_HDR_LEN);
skb_trim(skb, skb->len - CCMP_MIC_LEN);
return keyidx;
}
static int ieee80211_ccmp_set_key(void *key, int len, u8 *seq, void *priv)
{
struct ieee80211_ccmp_data *data = priv;
int keyidx;
struct crypto_tfm *tfm = data->tfm;
keyidx = data->key_idx;
memset(data, 0, sizeof(*data));
data->key_idx = keyidx;
data->tfm = tfm;
if (len == CCMP_TK_LEN) {
memcpy(data->key, key, CCMP_TK_LEN);
data->key_set = 1;
if (seq) {
data->rx_pn[0] = seq[5];
data->rx_pn[1] = seq[4];
data->rx_pn[2] = seq[3];
data->rx_pn[3] = seq[2];
data->rx_pn[4] = seq[1];
data->rx_pn[5] = seq[0];
}
crypto_cipher_setkey((void*)data->tfm, data->key, CCMP_TK_LEN);
} else if (len == 0)
data->key_set = 0;
else
return -1;
return 0;
}
static int ieee80211_ccmp_get_key(void *key, int len, u8 *seq, void *priv)
{
struct ieee80211_ccmp_data *data = priv;
if (len < CCMP_TK_LEN)
return -1;
if (!data->key_set)
return 0;
memcpy(key, data->key, CCMP_TK_LEN);
if (seq) {
seq[0] = data->tx_pn[5];
seq[1] = data->tx_pn[4];
seq[2] = data->tx_pn[3];
seq[3] = data->tx_pn[2];
seq[4] = data->tx_pn[1];
seq[5] = data->tx_pn[0];
}
return CCMP_TK_LEN;
}
static char * ieee80211_ccmp_print_stats(char *p, void *priv)
{
struct ieee80211_ccmp_data *ccmp = priv;
p += sprintf(p, "key[%d] alg=CCMP key_set=%d "
"tx_pn=%pm rx_pn=%pm "
"format_errors=%d replays=%d decrypt_errors=%d\n",
ccmp->key_idx, ccmp->key_set,
ccmp->tx_pn, ccmp->rx_pn,
ccmp->dot11RSNAStatsCCMPFormatErrors,
ccmp->dot11RSNAStatsCCMPReplays,
ccmp->dot11RSNAStatsCCMPDecryptErrors);
return p;
}
void ieee80211_ccmp_null(void)
{
// printk("============>%s()\n", __FUNCTION__);
return;
}
static struct ieee80211_crypto_ops ieee80211_crypt_ccmp = {
.name = "CCMP",
.init = ieee80211_ccmp_init,
.deinit = ieee80211_ccmp_deinit,
.encrypt_mpdu = ieee80211_ccmp_encrypt,
.decrypt_mpdu = ieee80211_ccmp_decrypt,
.encrypt_msdu = NULL,
.decrypt_msdu = NULL,
.set_key = ieee80211_ccmp_set_key,
.get_key = ieee80211_ccmp_get_key,
.print_stats = ieee80211_ccmp_print_stats,
.extra_prefix_len = CCMP_HDR_LEN,
.extra_postfix_len = CCMP_MIC_LEN,
.owner = THIS_MODULE,
};
int __init ieee80211_crypto_ccmp_init(void)
{
return ieee80211_register_crypto_ops(&ieee80211_crypt_ccmp);
}
void __exit ieee80211_crypto_ccmp_exit(void)
{
ieee80211_unregister_crypto_ops(&ieee80211_crypt_ccmp);
}
| gpl-2.0 |
Loller79/Solid_Kernel-GPROJ | drivers/ide/macide.c | 10187 | 3048 | /*
* Macintosh IDE Driver
*
* Copyright (C) 1998 by Michael Schmitz
*
* This driver was written based on information obtained from the MacOS IDE
* driver binary by Mikael Forselius
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/module.h>
#include <asm/macintosh.h>
#include <asm/macints.h>
#include <asm/mac_baboon.h>
#define IDE_BASE 0x50F1A000 /* Base address of IDE controller */
/*
* Generic IDE registers as offsets from the base
* These match MkLinux so they should be correct.
*/
#define IDE_CONTROL 0x38 /* control/altstatus */
/*
* Mac-specific registers
*/
/*
* this register is odd; it doesn't seem to do much and it's
* not word-aligned like virtually every other hardware register
* on the Mac...
*/
#define IDE_IFR 0x101 /* (0x101) IDE interrupt flags on Quadra:
*
* Bit 0+1: some interrupt flags
* Bit 2+3: some interrupt enable
* Bit 4: ??
* Bit 5: IDE interrupt flag (any hwif)
* Bit 6: maybe IDE interrupt enable (any hwif) ??
* Bit 7: Any interrupt condition
*/
volatile unsigned char *ide_ifr = (unsigned char *) (IDE_BASE + IDE_IFR);
int macide_test_irq(ide_hwif_t *hwif)
{
if (*ide_ifr & 0x20)
return 1;
return 0;
}
static void macide_clear_irq(ide_drive_t *drive)
{
*ide_ifr &= ~0x20;
}
static void __init macide_setup_ports(struct ide_hw *hw, unsigned long base,
int irq)
{
int i;
memset(hw, 0, sizeof(*hw));
for (i = 0; i < 8; i++)
hw->io_ports_array[i] = base + i * 4;
hw->io_ports.ctl_addr = base + IDE_CONTROL;
hw->irq = irq;
}
static const struct ide_port_ops macide_port_ops = {
.clear_irq = macide_clear_irq,
.test_irq = macide_test_irq,
};
static const struct ide_port_info macide_port_info = {
.port_ops = &macide_port_ops,
.host_flags = IDE_HFLAG_MMIO | IDE_HFLAG_NO_DMA,
.irq_flags = IRQF_SHARED,
.chipset = ide_generic,
};
static const char *mac_ide_name[] =
{ "Quadra", "Powerbook", "Powerbook Baboon" };
/*
* Probe for a Macintosh IDE interface
*/
static int __init macide_init(void)
{
unsigned long base;
int irq;
struct ide_hw hw, *hws[] = { &hw };
struct ide_port_info d = macide_port_info;
if (!MACH_IS_MAC)
return -ENODEV;
switch (macintosh_config->ide_type) {
case MAC_IDE_QUADRA:
base = IDE_BASE;
irq = IRQ_NUBUS_F;
break;
case MAC_IDE_PB:
base = IDE_BASE;
irq = IRQ_NUBUS_C;
break;
case MAC_IDE_BABOON:
base = BABOON_BASE;
d.port_ops = NULL;
irq = IRQ_BABOON_1;
break;
default:
return -ENODEV;
}
printk(KERN_INFO "ide: Macintosh %s IDE controller\n",
mac_ide_name[macintosh_config->ide_type - 1]);
macide_setup_ports(&hw, base, irq);
return ide_host_add(&d, hws, 1, NULL);
}
module_init(macide_init);
MODULE_LICENSE("GPL");
| gpl-2.0 |
chrisdiamand/linux | drivers/media/pci/cx18/cx18-av-audio.c | 12747 | 13482 | /*
* cx18 ADEC audio functions
*
* Derived from cx25840-audio.c
*
* Copyright (C) 2007 Hans Verkuil <hverkuil@xs4all.nl>
* Copyright (C) 2008 Andy Walls <awalls@md.metrocast.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 "cx18-driver.h"
static int set_audclk_freq(struct cx18 *cx, u32 freq)
{
struct cx18_av_state *state = &cx->av_state;
if (freq != 32000 && freq != 44100 && freq != 48000)
return -EINVAL;
/*
* The PLL parameters are based on the external crystal frequency that
* would ideally be:
*
* NTSC Color subcarrier freq * 8 =
* 4.5 MHz/286 * 455/2 * 8 = 28.63636363... MHz
*
* The accidents of history and rationale that explain from where this
* combination of magic numbers originate can be found in:
*
* [1] Abrahams, I. C., "Choice of Chrominance Subcarrier Frequency in
* the NTSC Standards", Proceedings of the I-R-E, January 1954, pp 79-80
*
* [2] Abrahams, I. C., "The 'Frequency Interleaving' Principle in the
* NTSC Standards", Proceedings of the I-R-E, January 1954, pp 81-83
*
* As Mike Bradley has rightly pointed out, it's not the exact crystal
* frequency that matters, only that all parts of the driver and
* firmware are using the same value (close to the ideal value).
*
* Since I have a strong suspicion that, if the firmware ever assumes a
* crystal value at all, it will assume 28.636360 MHz, the crystal
* freq used in calculations in this driver will be:
*
* xtal_freq = 28.636360 MHz
*
* an error of less than 0.13 ppm which is way, way better than any off
* the shelf crystal will have for accuracy anyway.
*
* Below I aim to run the PLLs' VCOs near 400 MHz to minimze error.
*
* Many thanks to Jeff Campbell and Mike Bradley for their extensive
* investigation, experimentation, testing, and suggested solutions of
* of audio/video sync problems with SVideo and CVBS captures.
*/
if (state->aud_input > CX18_AV_AUDIO_SERIAL2) {
switch (freq) {
case 32000:
/*
* VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04
* AUX_PLL Integer = 0x0d, AUX PLL Post Divider = 0x20
*/
cx18_av_write4(cx, 0x108, 0x200d040f);
/* VID_PLL Fraction = 0x2be2fe */
/* xtal * 0xf.15f17f0/4 = 108 MHz: 432 MHz pre-postdiv*/
cx18_av_write4(cx, 0x10c, 0x002be2fe);
/* AUX_PLL Fraction = 0x176740c */
/* xtal * 0xd.bb3a060/0x20 = 32000 * 384: 393 MHz p-pd*/
cx18_av_write4(cx, 0x110, 0x0176740c);
/* src3/4/6_ctl */
/* 0x1.f77f = (4 * xtal/8*2/455) / 32000 */
cx18_av_write4(cx, 0x900, 0x0801f77f);
cx18_av_write4(cx, 0x904, 0x0801f77f);
cx18_av_write4(cx, 0x90c, 0x0801f77f);
/* SA_MCLK_SEL=1, SA_MCLK_DIV=0x20 */
cx18_av_write(cx, 0x127, 0x60);
/* AUD_COUNT = 0x2fff = 8 samples * 4 * 384 - 1 */
cx18_av_write4(cx, 0x12c, 0x11202fff);
/*
* EN_AV_LOCK = 0
* VID_COUNT = 0x0d2ef8 = 107999.000 * 8 =
* ((8 samples/32,000) * (13,500,000 * 8) * 4 - 1) * 8
*/
cx18_av_write4(cx, 0x128, 0xa00d2ef8);
break;
case 44100:
/*
* VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04
* AUX_PLL Integer = 0x0e, AUX PLL Post Divider = 0x18
*/
cx18_av_write4(cx, 0x108, 0x180e040f);
/* VID_PLL Fraction = 0x2be2fe */
/* xtal * 0xf.15f17f0/4 = 108 MHz: 432 MHz pre-postdiv*/
cx18_av_write4(cx, 0x10c, 0x002be2fe);
/* AUX_PLL Fraction = 0x062a1f2 */
/* xtal * 0xe.3150f90/0x18 = 44100 * 384: 406 MHz p-pd*/
cx18_av_write4(cx, 0x110, 0x0062a1f2);
/* src3/4/6_ctl */
/* 0x1.6d59 = (4 * xtal/8*2/455) / 44100 */
cx18_av_write4(cx, 0x900, 0x08016d59);
cx18_av_write4(cx, 0x904, 0x08016d59);
cx18_av_write4(cx, 0x90c, 0x08016d59);
/* SA_MCLK_SEL=1, SA_MCLK_DIV=0x18 */
cx18_av_write(cx, 0x127, 0x58);
/* AUD_COUNT = 0x92ff = 49 samples * 2 * 384 - 1 */
cx18_av_write4(cx, 0x12c, 0x112092ff);
/*
* EN_AV_LOCK = 0
* VID_COUNT = 0x1d4bf8 = 239999.000 * 8 =
* ((49 samples/44,100) * (13,500,000 * 8) * 2 - 1) * 8
*/
cx18_av_write4(cx, 0x128, 0xa01d4bf8);
break;
case 48000:
/*
* VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04
* AUX_PLL Integer = 0x0e, AUX PLL Post Divider = 0x16
*/
cx18_av_write4(cx, 0x108, 0x160e040f);
/* VID_PLL Fraction = 0x2be2fe */
/* xtal * 0xf.15f17f0/4 = 108 MHz: 432 MHz pre-postdiv*/
cx18_av_write4(cx, 0x10c, 0x002be2fe);
/* AUX_PLL Fraction = 0x05227ad */
/* xtal * 0xe.2913d68/0x16 = 48000 * 384: 406 MHz p-pd*/
cx18_av_write4(cx, 0x110, 0x005227ad);
/* src3/4/6_ctl */
/* 0x1.4faa = (4 * xtal/8*2/455) / 48000 */
cx18_av_write4(cx, 0x900, 0x08014faa);
cx18_av_write4(cx, 0x904, 0x08014faa);
cx18_av_write4(cx, 0x90c, 0x08014faa);
/* SA_MCLK_SEL=1, SA_MCLK_DIV=0x16 */
cx18_av_write(cx, 0x127, 0x56);
/* AUD_COUNT = 0x5fff = 4 samples * 16 * 384 - 1 */
cx18_av_write4(cx, 0x12c, 0x11205fff);
/*
* EN_AV_LOCK = 0
* VID_COUNT = 0x1193f8 = 143999.000 * 8 =
* ((4 samples/48,000) * (13,500,000 * 8) * 16 - 1) * 8
*/
cx18_av_write4(cx, 0x128, 0xa01193f8);
break;
}
} else {
switch (freq) {
case 32000:
/*
* VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04
* AUX_PLL Integer = 0x0d, AUX PLL Post Divider = 0x30
*/
cx18_av_write4(cx, 0x108, 0x300d040f);
/* VID_PLL Fraction = 0x2be2fe */
/* xtal * 0xf.15f17f0/4 = 108 MHz: 432 MHz pre-postdiv*/
cx18_av_write4(cx, 0x10c, 0x002be2fe);
/* AUX_PLL Fraction = 0x176740c */
/* xtal * 0xd.bb3a060/0x30 = 32000 * 256: 393 MHz p-pd*/
cx18_av_write4(cx, 0x110, 0x0176740c);
/* src1_ctl */
/* 0x1.0000 = 32000/32000 */
cx18_av_write4(cx, 0x8f8, 0x08010000);
/* src3/4/6_ctl */
/* 0x2.0000 = 2 * (32000/32000) */
cx18_av_write4(cx, 0x900, 0x08020000);
cx18_av_write4(cx, 0x904, 0x08020000);
cx18_av_write4(cx, 0x90c, 0x08020000);
/* SA_MCLK_SEL=1, SA_MCLK_DIV=0x30 */
cx18_av_write(cx, 0x127, 0x70);
/* AUD_COUNT = 0x1fff = 8 samples * 4 * 256 - 1 */
cx18_av_write4(cx, 0x12c, 0x11201fff);
/*
* EN_AV_LOCK = 0
* VID_COUNT = 0x0d2ef8 = 107999.000 * 8 =
* ((8 samples/32,000) * (13,500,000 * 8) * 4 - 1) * 8
*/
cx18_av_write4(cx, 0x128, 0xa00d2ef8);
break;
case 44100:
/*
* VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04
* AUX_PLL Integer = 0x0e, AUX PLL Post Divider = 0x24
*/
cx18_av_write4(cx, 0x108, 0x240e040f);
/* VID_PLL Fraction = 0x2be2fe */
/* xtal * 0xf.15f17f0/4 = 108 MHz: 432 MHz pre-postdiv*/
cx18_av_write4(cx, 0x10c, 0x002be2fe);
/* AUX_PLL Fraction = 0x062a1f2 */
/* xtal * 0xe.3150f90/0x24 = 44100 * 256: 406 MHz p-pd*/
cx18_av_write4(cx, 0x110, 0x0062a1f2);
/* src1_ctl */
/* 0x1.60cd = 44100/32000 */
cx18_av_write4(cx, 0x8f8, 0x080160cd);
/* src3/4/6_ctl */
/* 0x1.7385 = 2 * (32000/44100) */
cx18_av_write4(cx, 0x900, 0x08017385);
cx18_av_write4(cx, 0x904, 0x08017385);
cx18_av_write4(cx, 0x90c, 0x08017385);
/* SA_MCLK_SEL=1, SA_MCLK_DIV=0x24 */
cx18_av_write(cx, 0x127, 0x64);
/* AUD_COUNT = 0x61ff = 49 samples * 2 * 256 - 1 */
cx18_av_write4(cx, 0x12c, 0x112061ff);
/*
* EN_AV_LOCK = 0
* VID_COUNT = 0x1d4bf8 = 239999.000 * 8 =
* ((49 samples/44,100) * (13,500,000 * 8) * 2 - 1) * 8
*/
cx18_av_write4(cx, 0x128, 0xa01d4bf8);
break;
case 48000:
/*
* VID_PLL Integer = 0x0f, VID_PLL Post Divider = 0x04
* AUX_PLL Integer = 0x0d, AUX PLL Post Divider = 0x20
*/
cx18_av_write4(cx, 0x108, 0x200d040f);
/* VID_PLL Fraction = 0x2be2fe */
/* xtal * 0xf.15f17f0/4 = 108 MHz: 432 MHz pre-postdiv*/
cx18_av_write4(cx, 0x10c, 0x002be2fe);
/* AUX_PLL Fraction = 0x176740c */
/* xtal * 0xd.bb3a060/0x20 = 48000 * 256: 393 MHz p-pd*/
cx18_av_write4(cx, 0x110, 0x0176740c);
/* src1_ctl */
/* 0x1.8000 = 48000/32000 */
cx18_av_write4(cx, 0x8f8, 0x08018000);
/* src3/4/6_ctl */
/* 0x1.5555 = 2 * (32000/48000) */
cx18_av_write4(cx, 0x900, 0x08015555);
cx18_av_write4(cx, 0x904, 0x08015555);
cx18_av_write4(cx, 0x90c, 0x08015555);
/* SA_MCLK_SEL=1, SA_MCLK_DIV=0x20 */
cx18_av_write(cx, 0x127, 0x60);
/* AUD_COUNT = 0x3fff = 4 samples * 16 * 256 - 1 */
cx18_av_write4(cx, 0x12c, 0x11203fff);
/*
* EN_AV_LOCK = 0
* VID_COUNT = 0x1193f8 = 143999.000 * 8 =
* ((4 samples/48,000) * (13,500,000 * 8) * 16 - 1) * 8
*/
cx18_av_write4(cx, 0x128, 0xa01193f8);
break;
}
}
state->audclk_freq = freq;
return 0;
}
void cx18_av_audio_set_path(struct cx18 *cx)
{
struct cx18_av_state *state = &cx->av_state;
u8 v;
/* stop microcontroller */
v = cx18_av_read(cx, 0x803) & ~0x10;
cx18_av_write_expect(cx, 0x803, v, v, 0x1f);
/* assert soft reset */
v = cx18_av_read(cx, 0x810) | 0x01;
cx18_av_write_expect(cx, 0x810, v, v, 0x0f);
/* Mute everything to prevent the PFFT! */
cx18_av_write(cx, 0x8d3, 0x1f);
if (state->aud_input <= CX18_AV_AUDIO_SERIAL2) {
/* Set Path1 to Serial Audio Input */
cx18_av_write4(cx, 0x8d0, 0x01011012);
/* The microcontroller should not be started for the
* non-tuner inputs: autodetection is specific for
* TV audio. */
} else {
/* Set Path1 to Analog Demod Main Channel */
cx18_av_write4(cx, 0x8d0, 0x1f063870);
}
set_audclk_freq(cx, state->audclk_freq);
/* deassert soft reset */
v = cx18_av_read(cx, 0x810) & ~0x01;
cx18_av_write_expect(cx, 0x810, v, v, 0x0f);
if (state->aud_input > CX18_AV_AUDIO_SERIAL2) {
/* When the microcontroller detects the
* audio format, it will unmute the lines */
v = cx18_av_read(cx, 0x803) | 0x10;
cx18_av_write_expect(cx, 0x803, v, v, 0x1f);
}
}
static void set_volume(struct cx18 *cx, int volume)
{
/* First convert the volume to msp3400 values (0-127) */
int vol = volume >> 9;
/* now scale it up to cx18_av values
* -114dB to -96dB maps to 0
* this should be 19, but in my testing that was 4dB too loud */
if (vol <= 23)
vol = 0;
else
vol -= 23;
/* PATH1_VOLUME */
cx18_av_write(cx, 0x8d4, 228 - (vol * 2));
}
static void set_bass(struct cx18 *cx, int bass)
{
/* PATH1_EQ_BASS_VOL */
cx18_av_and_or(cx, 0x8d9, ~0x3f, 48 - (bass * 48 / 0xffff));
}
static void set_treble(struct cx18 *cx, int treble)
{
/* PATH1_EQ_TREBLE_VOL */
cx18_av_and_or(cx, 0x8db, ~0x3f, 48 - (treble * 48 / 0xffff));
}
static void set_balance(struct cx18 *cx, int balance)
{
int bal = balance >> 8;
if (bal > 0x80) {
/* PATH1_BAL_LEFT */
cx18_av_and_or(cx, 0x8d5, 0x7f, 0x80);
/* PATH1_BAL_LEVEL */
cx18_av_and_or(cx, 0x8d5, ~0x7f, bal & 0x7f);
} else {
/* PATH1_BAL_LEFT */
cx18_av_and_or(cx, 0x8d5, 0x7f, 0x00);
/* PATH1_BAL_LEVEL */
cx18_av_and_or(cx, 0x8d5, ~0x7f, 0x80 - bal);
}
}
static void set_mute(struct cx18 *cx, int mute)
{
struct cx18_av_state *state = &cx->av_state;
u8 v;
if (state->aud_input > CX18_AV_AUDIO_SERIAL2) {
/* Must turn off microcontroller in order to mute sound.
* Not sure if this is the best method, but it does work.
* If the microcontroller is running, then it will undo any
* changes to the mute register. */
v = cx18_av_read(cx, 0x803);
if (mute) {
/* disable microcontroller */
v &= ~0x10;
cx18_av_write_expect(cx, 0x803, v, v, 0x1f);
cx18_av_write(cx, 0x8d3, 0x1f);
} else {
/* enable microcontroller */
v |= 0x10;
cx18_av_write_expect(cx, 0x803, v, v, 0x1f);
}
} else {
/* SRC1_MUTE_EN */
cx18_av_and_or(cx, 0x8d3, ~0x2, mute ? 0x02 : 0x00);
}
}
int cx18_av_s_clock_freq(struct v4l2_subdev *sd, u32 freq)
{
struct cx18 *cx = v4l2_get_subdevdata(sd);
struct cx18_av_state *state = &cx->av_state;
int retval;
u8 v;
if (state->aud_input > CX18_AV_AUDIO_SERIAL2) {
v = cx18_av_read(cx, 0x803) & ~0x10;
cx18_av_write_expect(cx, 0x803, v, v, 0x1f);
cx18_av_write(cx, 0x8d3, 0x1f);
}
v = cx18_av_read(cx, 0x810) | 0x1;
cx18_av_write_expect(cx, 0x810, v, v, 0x0f);
retval = set_audclk_freq(cx, freq);
v = cx18_av_read(cx, 0x810) & ~0x1;
cx18_av_write_expect(cx, 0x810, v, v, 0x0f);
if (state->aud_input > CX18_AV_AUDIO_SERIAL2) {
v = cx18_av_read(cx, 0x803) | 0x10;
cx18_av_write_expect(cx, 0x803, v, v, 0x1f);
}
return retval;
}
static int cx18_av_audio_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct v4l2_subdev *sd = to_sd(ctrl);
struct cx18 *cx = v4l2_get_subdevdata(sd);
switch (ctrl->id) {
case V4L2_CID_AUDIO_VOLUME:
set_volume(cx, ctrl->val);
break;
case V4L2_CID_AUDIO_BASS:
set_bass(cx, ctrl->val);
break;
case V4L2_CID_AUDIO_TREBLE:
set_treble(cx, ctrl->val);
break;
case V4L2_CID_AUDIO_BALANCE:
set_balance(cx, ctrl->val);
break;
case V4L2_CID_AUDIO_MUTE:
set_mute(cx, ctrl->val);
break;
default:
return -EINVAL;
}
return 0;
}
const struct v4l2_ctrl_ops cx18_av_audio_ctrl_ops = {
.s_ctrl = cx18_av_audio_s_ctrl,
};
| gpl-2.0 |
Evil-Green/Lonas_KL-GT-I9300-1 | arch/frv/kernel/uaccess.c | 13515 | 2170 | /* uaccess.c: userspace access functions
*
* Copyright (C) 2004 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/mm.h>
#include <linux/module.h>
#include <asm/uaccess.h>
/*****************************************************************************/
/*
* copy a null terminated string from userspace
*/
long strncpy_from_user(char *dst, const char __user *src, long count)
{
unsigned long max;
char *p, ch;
long err = -EFAULT;
BUG_ON(count < 0);
p = dst;
#ifndef CONFIG_MMU
if ((unsigned long) src < memory_start)
goto error;
#endif
if ((unsigned long) src >= get_addr_limit())
goto error;
max = get_addr_limit() - (unsigned long) src;
if ((unsigned long) count > max) {
memset(dst + max, 0, count - max);
count = max;
}
err = 0;
for (; count > 0; count--, p++, src++) {
__get_user_asm(err, ch, src, "ub", "=r");
if (err < 0)
goto error;
if (!ch)
break;
*p = ch;
}
err = p - dst; /* return length excluding NUL */
error:
if (count > 0)
memset(p, 0, count); /* clear remainder of buffer [security] */
return err;
} /* end strncpy_from_user() */
EXPORT_SYMBOL(strncpy_from_user);
/*****************************************************************************/
/*
* Return the size of a string (including the ending 0)
*
* Return 0 on exception, a value greater than N if too long
*/
long strnlen_user(const char __user *src, long count)
{
const char __user *p;
long err = 0;
char ch;
BUG_ON(count < 0);
#ifndef CONFIG_MMU
if ((unsigned long) src < memory_start)
return 0;
#endif
if ((unsigned long) src >= get_addr_limit())
return 0;
for (p = src; count > 0; count--, p++) {
__get_user_asm(err, ch, p, "ub", "=r");
if (err < 0)
return 0;
if (!ch)
break;
}
return p - src + 1; /* return length including NUL */
} /* end strnlen_user() */
EXPORT_SYMBOL(strnlen_user);
| gpl-2.0 |
Evervolv/android_kernel_htc_qsd8k | drivers/media/video/tvaudio.c | 204 | 63624 | /*
* Driver for simple i2c audio chips.
*
* Copyright (c) 2000 Gerd Knorr
* based on code by:
* Eric Sandeen (eric_sandeen@bigfoot.com)
* Steve VanDeBogart (vandebo@uclink.berkeley.edu)
* Greg Alexander (galexand@acm.org)
*
* Copyright(c) 2005-2008 Mauro Carvalho Chehab
* - Some cleanups, code fixes, etc
* - Convert it to V4L2 API
*
* This code is placed under the terms of the GNU General Public License
*
* OPTIONS:
* debug - set to 1 if you'd like to see debug messages
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/videodev2.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <media/tvaudio.h>
#include <media/v4l2-device.h>
#include <media/v4l2-chip-ident.h>
#include <media/i2c-addr.h>
/* ---------------------------------------------------------------------- */
/* insmod args */
static int debug; /* insmod parameter */
module_param(debug, int, 0644);
MODULE_DESCRIPTION("device driver for various i2c TV sound decoder / audiomux chips");
MODULE_AUTHOR("Eric Sandeen, Steve VanDeBogart, Greg Alexander, Gerd Knorr");
MODULE_LICENSE("GPL");
#define UNSET (-1U)
/* ---------------------------------------------------------------------- */
/* our structs */
#define MAXREGS 256
struct CHIPSTATE;
typedef int (*getvalue)(int);
typedef int (*checkit)(struct CHIPSTATE*);
typedef int (*initialize)(struct CHIPSTATE*);
typedef int (*getmode)(struct CHIPSTATE*);
typedef void (*setmode)(struct CHIPSTATE*, int mode);
/* i2c command */
typedef struct AUDIOCMD {
int count; /* # of bytes to send */
unsigned char bytes[MAXREGS+1]; /* addr, data, data, ... */
} audiocmd;
/* chip description */
struct CHIPDESC {
char *name; /* chip name */
int addr_lo, addr_hi; /* i2c address range */
int registers; /* # of registers */
int *insmodopt;
checkit checkit;
initialize initialize;
int flags;
#define CHIP_HAS_VOLUME 1
#define CHIP_HAS_BASSTREBLE 2
#define CHIP_HAS_INPUTSEL 4
#define CHIP_NEED_CHECKMODE 8
/* various i2c command sequences */
audiocmd init;
/* which register has which value */
int leftreg,rightreg,treblereg,bassreg;
/* initialize with (defaults to 65535/65535/32768/32768 */
int leftinit,rightinit,trebleinit,bassinit;
/* functions to convert the values (v4l -> chip) */
getvalue volfunc,treblefunc,bassfunc;
/* get/set mode */
getmode getmode;
setmode setmode;
/* input switch register + values for v4l inputs */
int inputreg;
int inputmap[4];
int inputmute;
int inputmask;
};
/* current state of the chip */
struct CHIPSTATE {
struct v4l2_subdev sd;
/* chip-specific description - should point to
an entry at CHIPDESC table */
struct CHIPDESC *desc;
/* shadow register set */
audiocmd shadow;
/* current settings */
__u16 left,right,treble,bass,muted,mode;
int prevmode;
int radio;
int input;
/* thread */
struct task_struct *thread;
struct timer_list wt;
int watch_stereo;
int audmode;
};
static inline struct CHIPSTATE *to_state(struct v4l2_subdev *sd)
{
return container_of(sd, struct CHIPSTATE, sd);
}
/* ---------------------------------------------------------------------- */
/* i2c I/O functions */
static int chip_write(struct CHIPSTATE *chip, int subaddr, int val)
{
struct v4l2_subdev *sd = &chip->sd;
struct i2c_client *c = v4l2_get_subdevdata(sd);
unsigned char buffer[2];
if (subaddr < 0) {
v4l2_dbg(1, debug, sd, "chip_write: 0x%x\n", val);
chip->shadow.bytes[1] = val;
buffer[0] = val;
if (1 != i2c_master_send(c, buffer, 1)) {
v4l2_warn(sd, "I/O error (write 0x%x)\n", val);
return -1;
}
} else {
if (subaddr + 1 >= ARRAY_SIZE(chip->shadow.bytes)) {
v4l2_info(sd,
"Tried to access a non-existent register: %d\n",
subaddr);
return -EINVAL;
}
v4l2_dbg(1, debug, sd, "chip_write: reg%d=0x%x\n",
subaddr, val);
chip->shadow.bytes[subaddr+1] = val;
buffer[0] = subaddr;
buffer[1] = val;
if (2 != i2c_master_send(c, buffer, 2)) {
v4l2_warn(sd, "I/O error (write reg%d=0x%x)\n",
subaddr, val);
return -1;
}
}
return 0;
}
static int chip_write_masked(struct CHIPSTATE *chip,
int subaddr, int val, int mask)
{
struct v4l2_subdev *sd = &chip->sd;
if (mask != 0) {
if (subaddr < 0) {
val = (chip->shadow.bytes[1] & ~mask) | (val & mask);
} else {
if (subaddr + 1 >= ARRAY_SIZE(chip->shadow.bytes)) {
v4l2_info(sd,
"Tried to access a non-existent register: %d\n",
subaddr);
return -EINVAL;
}
val = (chip->shadow.bytes[subaddr+1] & ~mask) | (val & mask);
}
}
return chip_write(chip, subaddr, val);
}
static int chip_read(struct CHIPSTATE *chip)
{
struct v4l2_subdev *sd = &chip->sd;
struct i2c_client *c = v4l2_get_subdevdata(sd);
unsigned char buffer;
if (1 != i2c_master_recv(c, &buffer, 1)) {
v4l2_warn(sd, "I/O error (read)\n");
return -1;
}
v4l2_dbg(1, debug, sd, "chip_read: 0x%x\n", buffer);
return buffer;
}
static int chip_read2(struct CHIPSTATE *chip, int subaddr)
{
struct v4l2_subdev *sd = &chip->sd;
struct i2c_client *c = v4l2_get_subdevdata(sd);
unsigned char write[1];
unsigned char read[1];
struct i2c_msg msgs[2] = {
{ c->addr, 0, 1, write },
{ c->addr, I2C_M_RD, 1, read }
};
write[0] = subaddr;
if (2 != i2c_transfer(c->adapter, msgs, 2)) {
v4l2_warn(sd, "I/O error (read2)\n");
return -1;
}
v4l2_dbg(1, debug, sd, "chip_read2: reg%d=0x%x\n",
subaddr, read[0]);
return read[0];
}
static int chip_cmd(struct CHIPSTATE *chip, char *name, audiocmd *cmd)
{
struct v4l2_subdev *sd = &chip->sd;
struct i2c_client *c = v4l2_get_subdevdata(sd);
int i;
if (0 == cmd->count)
return 0;
if (cmd->count + cmd->bytes[0] - 1 >= ARRAY_SIZE(chip->shadow.bytes)) {
v4l2_info(sd,
"Tried to access a non-existent register range: %d to %d\n",
cmd->bytes[0] + 1, cmd->bytes[0] + cmd->count - 1);
return -EINVAL;
}
/* FIXME: it seems that the shadow bytes are wrong bellow !*/
/* update our shadow register set; print bytes if (debug > 0) */
v4l2_dbg(1, debug, sd, "chip_cmd(%s): reg=%d, data:",
name, cmd->bytes[0]);
for (i = 1; i < cmd->count; i++) {
if (debug)
printk(KERN_CONT " 0x%x", cmd->bytes[i]);
chip->shadow.bytes[i+cmd->bytes[0]] = cmd->bytes[i];
}
if (debug)
printk(KERN_CONT "\n");
/* send data to the chip */
if (cmd->count != i2c_master_send(c, cmd->bytes, cmd->count)) {
v4l2_warn(sd, "I/O error (%s)\n", name);
return -1;
}
return 0;
}
/* ---------------------------------------------------------------------- */
/* kernel thread for doing i2c stuff asyncronly
* right now it is used only to check the audio mode (mono/stereo/whatever)
* some time after switching to another TV channel, then turn on stereo
* if available, ...
*/
static void chip_thread_wake(unsigned long data)
{
struct CHIPSTATE *chip = (struct CHIPSTATE*)data;
wake_up_process(chip->thread);
}
static int chip_thread(void *data)
{
struct CHIPSTATE *chip = data;
struct CHIPDESC *desc = chip->desc;
struct v4l2_subdev *sd = &chip->sd;
int mode;
v4l2_dbg(1, debug, sd, "thread started\n");
set_freezable();
for (;;) {
set_current_state(TASK_INTERRUPTIBLE);
if (!kthread_should_stop())
schedule();
set_current_state(TASK_RUNNING);
try_to_freeze();
if (kthread_should_stop())
break;
v4l2_dbg(1, debug, sd, "thread wakeup\n");
/* don't do anything for radio or if mode != auto */
if (chip->radio || chip->mode != 0)
continue;
/* have a look what's going on */
mode = desc->getmode(chip);
if (mode == chip->prevmode)
continue;
/* chip detected a new audio mode - set it */
v4l2_dbg(1, debug, sd, "thread checkmode\n");
chip->prevmode = mode;
if (mode & V4L2_TUNER_MODE_STEREO)
desc->setmode(chip, V4L2_TUNER_MODE_STEREO);
if (mode & V4L2_TUNER_MODE_LANG1_LANG2)
desc->setmode(chip, V4L2_TUNER_MODE_STEREO);
else if (mode & V4L2_TUNER_MODE_LANG1)
desc->setmode(chip, V4L2_TUNER_MODE_LANG1);
else if (mode & V4L2_TUNER_MODE_LANG2)
desc->setmode(chip, V4L2_TUNER_MODE_LANG2);
else
desc->setmode(chip, V4L2_TUNER_MODE_MONO);
/* schedule next check */
mod_timer(&chip->wt, jiffies+msecs_to_jiffies(2000));
}
v4l2_dbg(1, debug, sd, "thread exiting\n");
return 0;
}
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - defines+functions for tda9840 */
#define TDA9840_SW 0x00
#define TDA9840_LVADJ 0x02
#define TDA9840_STADJ 0x03
#define TDA9840_TEST 0x04
#define TDA9840_MONO 0x10
#define TDA9840_STEREO 0x2a
#define TDA9840_DUALA 0x12
#define TDA9840_DUALB 0x1e
#define TDA9840_DUALAB 0x1a
#define TDA9840_DUALBA 0x16
#define TDA9840_EXTERNAL 0x7a
#define TDA9840_DS_DUAL 0x20 /* Dual sound identified */
#define TDA9840_ST_STEREO 0x40 /* Stereo sound identified */
#define TDA9840_PONRES 0x80 /* Power-on reset detected if = 1 */
#define TDA9840_TEST_INT1SN 0x1 /* Integration time 0.5s when set */
#define TDA9840_TEST_INTFU 0x02 /* Disables integrator function */
static int tda9840_getmode(struct CHIPSTATE *chip)
{
struct v4l2_subdev *sd = &chip->sd;
int val, mode;
val = chip_read(chip);
mode = V4L2_TUNER_MODE_MONO;
if (val & TDA9840_DS_DUAL)
mode |= V4L2_TUNER_MODE_LANG1 | V4L2_TUNER_MODE_LANG2;
if (val & TDA9840_ST_STEREO)
mode |= V4L2_TUNER_MODE_STEREO;
v4l2_dbg(1, debug, sd, "tda9840_getmode(): raw chip read: %d, return: %d\n",
val, mode);
return mode;
}
static void tda9840_setmode(struct CHIPSTATE *chip, int mode)
{
int update = 1;
int t = chip->shadow.bytes[TDA9840_SW + 1] & ~0x7e;
switch (mode) {
case V4L2_TUNER_MODE_MONO:
t |= TDA9840_MONO;
break;
case V4L2_TUNER_MODE_STEREO:
t |= TDA9840_STEREO;
break;
case V4L2_TUNER_MODE_LANG1:
t |= TDA9840_DUALA;
break;
case V4L2_TUNER_MODE_LANG2:
t |= TDA9840_DUALB;
break;
default:
update = 0;
}
if (update)
chip_write(chip, TDA9840_SW, t);
}
static int tda9840_checkit(struct CHIPSTATE *chip)
{
int rc;
rc = chip_read(chip);
/* lower 5 bits should be 0 */
return ((rc & 0x1f) == 0) ? 1 : 0;
}
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - defines+functions for tda985x */
/* subaddresses for TDA9855 */
#define TDA9855_VR 0x00 /* Volume, right */
#define TDA9855_VL 0x01 /* Volume, left */
#define TDA9855_BA 0x02 /* Bass */
#define TDA9855_TR 0x03 /* Treble */
#define TDA9855_SW 0x04 /* Subwoofer - not connected on DTV2000 */
/* subaddresses for TDA9850 */
#define TDA9850_C4 0x04 /* Control 1 for TDA9850 */
/* subaddesses for both chips */
#define TDA985x_C5 0x05 /* Control 2 for TDA9850, Control 1 for TDA9855 */
#define TDA985x_C6 0x06 /* Control 3 for TDA9850, Control 2 for TDA9855 */
#define TDA985x_C7 0x07 /* Control 4 for TDA9850, Control 3 for TDA9855 */
#define TDA985x_A1 0x08 /* Alignment 1 for both chips */
#define TDA985x_A2 0x09 /* Alignment 2 for both chips */
#define TDA985x_A3 0x0a /* Alignment 3 for both chips */
/* Masks for bits in TDA9855 subaddresses */
/* 0x00 - VR in TDA9855 */
/* 0x01 - VL in TDA9855 */
/* lower 7 bits control gain from -71dB (0x28) to 16dB (0x7f)
* in 1dB steps - mute is 0x27 */
/* 0x02 - BA in TDA9855 */
/* lower 5 bits control bass gain from -12dB (0x06) to 16.5dB (0x19)
* in .5dB steps - 0 is 0x0E */
/* 0x03 - TR in TDA9855 */
/* 4 bits << 1 control treble gain from -12dB (0x3) to 12dB (0xb)
* in 3dB steps - 0 is 0x7 */
/* Masks for bits in both chips' subaddresses */
/* 0x04 - SW in TDA9855, C4/Control 1 in TDA9850 */
/* Unique to TDA9855: */
/* 4 bits << 2 control subwoofer/surround gain from -14db (0x1) to 14db (0xf)
* in 3dB steps - mute is 0x0 */
/* Unique to TDA9850: */
/* lower 4 bits control stereo noise threshold, over which stereo turns off
* set to values of 0x00 through 0x0f for Ster1 through Ster16 */
/* 0x05 - C5 - Control 1 in TDA9855 , Control 2 in TDA9850*/
/* Unique to TDA9855: */
#define TDA9855_MUTE 1<<7 /* GMU, Mute at outputs */
#define TDA9855_AVL 1<<6 /* AVL, Automatic Volume Level */
#define TDA9855_LOUD 1<<5 /* Loudness, 1==off */
#define TDA9855_SUR 1<<3 /* Surround / Subwoofer 1==.5(L-R) 0==.5(L+R) */
/* Bits 0 to 3 select various combinations
* of line in and line out, only the
* interesting ones are defined */
#define TDA9855_EXT 1<<2 /* Selects inputs LIR and LIL. Pins 41 & 12 */
#define TDA9855_INT 0 /* Selects inputs LOR and LOL. (internal) */
/* Unique to TDA9850: */
/* lower 4 bits contol SAP noise threshold, over which SAP turns off
* set to values of 0x00 through 0x0f for SAP1 through SAP16 */
/* 0x06 - C6 - Control 2 in TDA9855, Control 3 in TDA9850 */
/* Common to TDA9855 and TDA9850: */
#define TDA985x_SAP 3<<6 /* Selects SAP output, mute if not received */
#define TDA985x_STEREO 1<<6 /* Selects Stereo ouput, mono if not received */
#define TDA985x_MONO 0 /* Forces Mono output */
#define TDA985x_LMU 1<<3 /* Mute (LOR/LOL for 9855, OUTL/OUTR for 9850) */
/* Unique to TDA9855: */
#define TDA9855_TZCM 1<<5 /* If set, don't mute till zero crossing */
#define TDA9855_VZCM 1<<4 /* If set, don't change volume till zero crossing*/
#define TDA9855_LINEAR 0 /* Linear Stereo */
#define TDA9855_PSEUDO 1 /* Pseudo Stereo */
#define TDA9855_SPAT_30 2 /* Spatial Stereo, 30% anti-phase crosstalk */
#define TDA9855_SPAT_50 3 /* Spatial Stereo, 52% anti-phase crosstalk */
#define TDA9855_E_MONO 7 /* Forced mono - mono select elseware, so useless*/
/* 0x07 - C7 - Control 3 in TDA9855, Control 4 in TDA9850 */
/* Common to both TDA9855 and TDA9850: */
/* lower 4 bits control input gain from -3.5dB (0x0) to 4dB (0xF)
* in .5dB steps - 0dB is 0x7 */
/* 0x08, 0x09 - A1 and A2 (read/write) */
/* Common to both TDA9855 and TDA9850: */
/* lower 5 bites are wideband and spectral expander alignment
* from 0x00 to 0x1f - nominal at 0x0f and 0x10 (read/write) */
#define TDA985x_STP 1<<5 /* Stereo Pilot/detect (read-only) */
#define TDA985x_SAPP 1<<6 /* SAP Pilot/detect (read-only) */
#define TDA985x_STS 1<<7 /* Stereo trigger 1= <35mV 0= <30mV (write-only)*/
/* 0x0a - A3 */
/* Common to both TDA9855 and TDA9850: */
/* lower 3 bits control timing current for alignment: -30% (0x0), -20% (0x1),
* -10% (0x2), nominal (0x3), +10% (0x6), +20% (0x5), +30% (0x4) */
#define TDA985x_ADJ 1<<7 /* Stereo adjust on/off (wideband and spectral */
static int tda9855_volume(int val) { return val/0x2e8+0x27; }
static int tda9855_bass(int val) { return val/0xccc+0x06; }
static int tda9855_treble(int val) { return (val/0x1c71+0x3)<<1; }
static int tda985x_getmode(struct CHIPSTATE *chip)
{
int mode;
mode = ((TDA985x_STP | TDA985x_SAPP) &
chip_read(chip)) >> 4;
/* Add mono mode regardless of SAP and stereo */
/* Allows forced mono */
return mode | V4L2_TUNER_MODE_MONO;
}
static void tda985x_setmode(struct CHIPSTATE *chip, int mode)
{
int update = 1;
int c6 = chip->shadow.bytes[TDA985x_C6+1] & 0x3f;
switch (mode) {
case V4L2_TUNER_MODE_MONO:
c6 |= TDA985x_MONO;
break;
case V4L2_TUNER_MODE_STEREO:
c6 |= TDA985x_STEREO;
break;
case V4L2_TUNER_MODE_LANG1:
c6 |= TDA985x_SAP;
break;
default:
update = 0;
}
if (update)
chip_write(chip,TDA985x_C6,c6);
}
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - defines+functions for tda9873h */
/* Subaddresses for TDA9873H */
#define TDA9873_SW 0x00 /* Switching */
#define TDA9873_AD 0x01 /* Adjust */
#define TDA9873_PT 0x02 /* Port */
/* Subaddress 0x00: Switching Data
* B7..B0:
*
* B1, B0: Input source selection
* 0, 0 internal
* 1, 0 external stereo
* 0, 1 external mono
*/
#define TDA9873_INP_MASK 3
#define TDA9873_INTERNAL 0
#define TDA9873_EXT_STEREO 2
#define TDA9873_EXT_MONO 1
/* B3, B2: output signal select
* B4 : transmission mode
* 0, 0, 1 Mono
* 1, 0, 0 Stereo
* 1, 1, 1 Stereo (reversed channel)
* 0, 0, 0 Dual AB
* 0, 0, 1 Dual AA
* 0, 1, 0 Dual BB
* 0, 1, 1 Dual BA
*/
#define TDA9873_TR_MASK (7 << 2)
#define TDA9873_TR_MONO 4
#define TDA9873_TR_STEREO 1 << 4
#define TDA9873_TR_REVERSE (1 << 3) & (1 << 2)
#define TDA9873_TR_DUALA 1 << 2
#define TDA9873_TR_DUALB 1 << 3
/* output level controls
* B5: output level switch (0 = reduced gain, 1 = normal gain)
* B6: mute (1 = muted)
* B7: auto-mute (1 = auto-mute enabled)
*/
#define TDA9873_GAIN_NORMAL 1 << 5
#define TDA9873_MUTE 1 << 6
#define TDA9873_AUTOMUTE 1 << 7
/* Subaddress 0x01: Adjust/standard */
/* Lower 4 bits (C3..C0) control stereo adjustment on R channel (-0.6 - +0.7 dB)
* Recommended value is +0 dB
*/
#define TDA9873_STEREO_ADJ 0x06 /* 0dB gain */
/* Bits C6..C4 control FM stantard
* C6, C5, C4
* 0, 0, 0 B/G (PAL FM)
* 0, 0, 1 M
* 0, 1, 0 D/K(1)
* 0, 1, 1 D/K(2)
* 1, 0, 0 D/K(3)
* 1, 0, 1 I
*/
#define TDA9873_BG 0
#define TDA9873_M 1
#define TDA9873_DK1 2
#define TDA9873_DK2 3
#define TDA9873_DK3 4
#define TDA9873_I 5
/* C7 controls identification response time (1=fast/0=normal)
*/
#define TDA9873_IDR_NORM 0
#define TDA9873_IDR_FAST 1 << 7
/* Subaddress 0x02: Port data */
/* E1, E0 free programmable ports P1/P2
0, 0 both ports low
0, 1 P1 high
1, 0 P2 high
1, 1 both ports high
*/
#define TDA9873_PORTS 3
/* E2: test port */
#define TDA9873_TST_PORT 1 << 2
/* E5..E3 control mono output channel (together with transmission mode bit B4)
*
* E5 E4 E3 B4 OUTM
* 0 0 0 0 mono
* 0 0 1 0 DUAL B
* 0 1 0 1 mono (from stereo decoder)
*/
#define TDA9873_MOUT_MONO 0
#define TDA9873_MOUT_FMONO 0
#define TDA9873_MOUT_DUALA 0
#define TDA9873_MOUT_DUALB 1 << 3
#define TDA9873_MOUT_ST 1 << 4
#define TDA9873_MOUT_EXTM (1 << 4 ) & (1 << 3)
#define TDA9873_MOUT_EXTL 1 << 5
#define TDA9873_MOUT_EXTR (1 << 5 ) & (1 << 3)
#define TDA9873_MOUT_EXTLR (1 << 5 ) & (1 << 4)
#define TDA9873_MOUT_MUTE (1 << 5 ) & (1 << 4) & (1 << 3)
/* Status bits: (chip read) */
#define TDA9873_PONR 0 /* Power-on reset detected if = 1 */
#define TDA9873_STEREO 2 /* Stereo sound is identified */
#define TDA9873_DUAL 4 /* Dual sound is identified */
static int tda9873_getmode(struct CHIPSTATE *chip)
{
struct v4l2_subdev *sd = &chip->sd;
int val,mode;
val = chip_read(chip);
mode = V4L2_TUNER_MODE_MONO;
if (val & TDA9873_STEREO)
mode |= V4L2_TUNER_MODE_STEREO;
if (val & TDA9873_DUAL)
mode |= V4L2_TUNER_MODE_LANG1 | V4L2_TUNER_MODE_LANG2;
v4l2_dbg(1, debug, sd, "tda9873_getmode(): raw chip read: %d, return: %d\n",
val, mode);
return mode;
}
static void tda9873_setmode(struct CHIPSTATE *chip, int mode)
{
struct v4l2_subdev *sd = &chip->sd;
int sw_data = chip->shadow.bytes[TDA9873_SW+1] & ~ TDA9873_TR_MASK;
/* int adj_data = chip->shadow.bytes[TDA9873_AD+1] ; */
if ((sw_data & TDA9873_INP_MASK) != TDA9873_INTERNAL) {
v4l2_dbg(1, debug, sd, "tda9873_setmode(): external input\n");
return;
}
v4l2_dbg(1, debug, sd, "tda9873_setmode(): chip->shadow.bytes[%d] = %d\n", TDA9873_SW+1, chip->shadow.bytes[TDA9873_SW+1]);
v4l2_dbg(1, debug, sd, "tda9873_setmode(): sw_data = %d\n", sw_data);
switch (mode) {
case V4L2_TUNER_MODE_MONO:
sw_data |= TDA9873_TR_MONO;
break;
case V4L2_TUNER_MODE_STEREO:
sw_data |= TDA9873_TR_STEREO;
break;
case V4L2_TUNER_MODE_LANG1:
sw_data |= TDA9873_TR_DUALA;
break;
case V4L2_TUNER_MODE_LANG2:
sw_data |= TDA9873_TR_DUALB;
break;
default:
chip->mode = 0;
return;
}
chip_write(chip, TDA9873_SW, sw_data);
v4l2_dbg(1, debug, sd, "tda9873_setmode(): req. mode %d; chip_write: %d\n",
mode, sw_data);
}
static int tda9873_checkit(struct CHIPSTATE *chip)
{
int rc;
if (-1 == (rc = chip_read2(chip,254)))
return 0;
return (rc & ~0x1f) == 0x80;
}
/* ---------------------------------------------------------------------- */
/* audio chip description - defines+functions for tda9874h and tda9874a */
/* Dariusz Kowalewski <darekk@automex.pl> */
/* Subaddresses for TDA9874H and TDA9874A (slave rx) */
#define TDA9874A_AGCGR 0x00 /* AGC gain */
#define TDA9874A_GCONR 0x01 /* general config */
#define TDA9874A_MSR 0x02 /* monitor select */
#define TDA9874A_C1FRA 0x03 /* carrier 1 freq. */
#define TDA9874A_C1FRB 0x04 /* carrier 1 freq. */
#define TDA9874A_C1FRC 0x05 /* carrier 1 freq. */
#define TDA9874A_C2FRA 0x06 /* carrier 2 freq. */
#define TDA9874A_C2FRB 0x07 /* carrier 2 freq. */
#define TDA9874A_C2FRC 0x08 /* carrier 2 freq. */
#define TDA9874A_DCR 0x09 /* demodulator config */
#define TDA9874A_FMER 0x0a /* FM de-emphasis */
#define TDA9874A_FMMR 0x0b /* FM dematrix */
#define TDA9874A_C1OLAR 0x0c /* ch.1 output level adj. */
#define TDA9874A_C2OLAR 0x0d /* ch.2 output level adj. */
#define TDA9874A_NCONR 0x0e /* NICAM config */
#define TDA9874A_NOLAR 0x0f /* NICAM output level adj. */
#define TDA9874A_NLELR 0x10 /* NICAM lower error limit */
#define TDA9874A_NUELR 0x11 /* NICAM upper error limit */
#define TDA9874A_AMCONR 0x12 /* audio mute control */
#define TDA9874A_SDACOSR 0x13 /* stereo DAC output select */
#define TDA9874A_AOSR 0x14 /* analog output select */
#define TDA9874A_DAICONR 0x15 /* digital audio interface config */
#define TDA9874A_I2SOSR 0x16 /* I2S-bus output select */
#define TDA9874A_I2SOLAR 0x17 /* I2S-bus output level adj. */
#define TDA9874A_MDACOSR 0x18 /* mono DAC output select (tda9874a) */
#define TDA9874A_ESP 0xFF /* easy standard progr. (tda9874a) */
/* Subaddresses for TDA9874H and TDA9874A (slave tx) */
#define TDA9874A_DSR 0x00 /* device status */
#define TDA9874A_NSR 0x01 /* NICAM status */
#define TDA9874A_NECR 0x02 /* NICAM error count */
#define TDA9874A_DR1 0x03 /* add. data LSB */
#define TDA9874A_DR2 0x04 /* add. data MSB */
#define TDA9874A_LLRA 0x05 /* monitor level read-out LSB */
#define TDA9874A_LLRB 0x06 /* monitor level read-out MSB */
#define TDA9874A_SIFLR 0x07 /* SIF level */
#define TDA9874A_TR2 252 /* test reg. 2 */
#define TDA9874A_TR1 253 /* test reg. 1 */
#define TDA9874A_DIC 254 /* device id. code */
#define TDA9874A_SIC 255 /* software id. code */
static int tda9874a_mode = 1; /* 0: A2, 1: NICAM */
static int tda9874a_GCONR = 0xc0; /* default config. input pin: SIFSEL=0 */
static int tda9874a_NCONR = 0x01; /* default NICAM config.: AMSEL=0,AMUTE=1 */
static int tda9874a_ESP = 0x07; /* default standard: NICAM D/K */
static int tda9874a_dic = -1; /* device id. code */
/* insmod options for tda9874a */
static unsigned int tda9874a_SIF = UNSET;
static unsigned int tda9874a_AMSEL = UNSET;
static unsigned int tda9874a_STD = UNSET;
module_param(tda9874a_SIF, int, 0444);
module_param(tda9874a_AMSEL, int, 0444);
module_param(tda9874a_STD, int, 0444);
/*
* initialization table for tda9874 decoder:
* - carrier 1 freq. registers (3 bytes)
* - carrier 2 freq. registers (3 bytes)
* - demudulator config register
* - FM de-emphasis register (slow identification mode)
* Note: frequency registers must be written in single i2c transfer.
*/
static struct tda9874a_MODES {
char *name;
audiocmd cmd;
} tda9874a_modelist[9] = {
{ "A2, B/G", /* default */
{ 9, { TDA9874A_C1FRA, 0x72,0x95,0x55, 0x77,0xA0,0x00, 0x00,0x00 }} },
{ "A2, M (Korea)",
{ 9, { TDA9874A_C1FRA, 0x5D,0xC0,0x00, 0x62,0x6A,0xAA, 0x20,0x22 }} },
{ "A2, D/K (1)",
{ 9, { TDA9874A_C1FRA, 0x87,0x6A,0xAA, 0x82,0x60,0x00, 0x00,0x00 }} },
{ "A2, D/K (2)",
{ 9, { TDA9874A_C1FRA, 0x87,0x6A,0xAA, 0x8C,0x75,0x55, 0x00,0x00 }} },
{ "A2, D/K (3)",
{ 9, { TDA9874A_C1FRA, 0x87,0x6A,0xAA, 0x77,0xA0,0x00, 0x00,0x00 }} },
{ "NICAM, I",
{ 9, { TDA9874A_C1FRA, 0x7D,0x00,0x00, 0x88,0x8A,0xAA, 0x08,0x33 }} },
{ "NICAM, B/G",
{ 9, { TDA9874A_C1FRA, 0x72,0x95,0x55, 0x79,0xEA,0xAA, 0x08,0x33 }} },
{ "NICAM, D/K",
{ 9, { TDA9874A_C1FRA, 0x87,0x6A,0xAA, 0x79,0xEA,0xAA, 0x08,0x33 }} },
{ "NICAM, L",
{ 9, { TDA9874A_C1FRA, 0x87,0x6A,0xAA, 0x79,0xEA,0xAA, 0x09,0x33 }} }
};
static int tda9874a_setup(struct CHIPSTATE *chip)
{
struct v4l2_subdev *sd = &chip->sd;
chip_write(chip, TDA9874A_AGCGR, 0x00); /* 0 dB */
chip_write(chip, TDA9874A_GCONR, tda9874a_GCONR);
chip_write(chip, TDA9874A_MSR, (tda9874a_mode) ? 0x03:0x02);
if(tda9874a_dic == 0x11) {
chip_write(chip, TDA9874A_FMMR, 0x80);
} else { /* dic == 0x07 */
chip_cmd(chip,"tda9874_modelist",&tda9874a_modelist[tda9874a_STD].cmd);
chip_write(chip, TDA9874A_FMMR, 0x00);
}
chip_write(chip, TDA9874A_C1OLAR, 0x00); /* 0 dB */
chip_write(chip, TDA9874A_C2OLAR, 0x00); /* 0 dB */
chip_write(chip, TDA9874A_NCONR, tda9874a_NCONR);
chip_write(chip, TDA9874A_NOLAR, 0x00); /* 0 dB */
/* Note: If signal quality is poor you may want to change NICAM */
/* error limit registers (NLELR and NUELR) to some greater values. */
/* Then the sound would remain stereo, but won't be so clear. */
chip_write(chip, TDA9874A_NLELR, 0x14); /* default */
chip_write(chip, TDA9874A_NUELR, 0x50); /* default */
if(tda9874a_dic == 0x11) {
chip_write(chip, TDA9874A_AMCONR, 0xf9);
chip_write(chip, TDA9874A_SDACOSR, (tda9874a_mode) ? 0x81:0x80);
chip_write(chip, TDA9874A_AOSR, 0x80);
chip_write(chip, TDA9874A_MDACOSR, (tda9874a_mode) ? 0x82:0x80);
chip_write(chip, TDA9874A_ESP, tda9874a_ESP);
} else { /* dic == 0x07 */
chip_write(chip, TDA9874A_AMCONR, 0xfb);
chip_write(chip, TDA9874A_SDACOSR, (tda9874a_mode) ? 0x81:0x80);
chip_write(chip, TDA9874A_AOSR, 0x00); /* or 0x10 */
}
v4l2_dbg(1, debug, sd, "tda9874a_setup(): %s [0x%02X].\n",
tda9874a_modelist[tda9874a_STD].name,tda9874a_STD);
return 1;
}
static int tda9874a_getmode(struct CHIPSTATE *chip)
{
struct v4l2_subdev *sd = &chip->sd;
int dsr,nsr,mode;
int necr; /* just for debugging */
mode = V4L2_TUNER_MODE_MONO;
if(-1 == (dsr = chip_read2(chip,TDA9874A_DSR)))
return mode;
if(-1 == (nsr = chip_read2(chip,TDA9874A_NSR)))
return mode;
if(-1 == (necr = chip_read2(chip,TDA9874A_NECR)))
return mode;
/* need to store dsr/nsr somewhere */
chip->shadow.bytes[MAXREGS-2] = dsr;
chip->shadow.bytes[MAXREGS-1] = nsr;
if(tda9874a_mode) {
/* Note: DSR.RSSF and DSR.AMSTAT bits are also checked.
* If NICAM auto-muting is enabled, DSR.AMSTAT=1 indicates
* that sound has (temporarily) switched from NICAM to
* mono FM (or AM) on 1st sound carrier due to high NICAM bit
* error count. So in fact there is no stereo in this case :-(
* But changing the mode to V4L2_TUNER_MODE_MONO would switch
* external 4052 multiplexer in audio_hook().
*/
if(nsr & 0x02) /* NSR.S/MB=1 */
mode |= V4L2_TUNER_MODE_STEREO;
if(nsr & 0x01) /* NSR.D/SB=1 */
mode |= V4L2_TUNER_MODE_LANG1 | V4L2_TUNER_MODE_LANG2;
} else {
if(dsr & 0x02) /* DSR.IDSTE=1 */
mode |= V4L2_TUNER_MODE_STEREO;
if(dsr & 0x04) /* DSR.IDDUA=1 */
mode |= V4L2_TUNER_MODE_LANG1 | V4L2_TUNER_MODE_LANG2;
}
v4l2_dbg(1, debug, sd, "tda9874a_getmode(): DSR=0x%X, NSR=0x%X, NECR=0x%X, return: %d.\n",
dsr, nsr, necr, mode);
return mode;
}
static void tda9874a_setmode(struct CHIPSTATE *chip, int mode)
{
struct v4l2_subdev *sd = &chip->sd;
/* Disable/enable NICAM auto-muting (based on DSR.RSSF status bit). */
/* If auto-muting is disabled, we can hear a signal of degrading quality. */
if (tda9874a_mode) {
if(chip->shadow.bytes[MAXREGS-2] & 0x20) /* DSR.RSSF=1 */
tda9874a_NCONR &= 0xfe; /* enable */
else
tda9874a_NCONR |= 0x01; /* disable */
chip_write(chip, TDA9874A_NCONR, tda9874a_NCONR);
}
/* Note: TDA9874A supports automatic FM dematrixing (FMMR register)
* and has auto-select function for audio output (AOSR register).
* Old TDA9874H doesn't support these features.
* TDA9874A also has additional mono output pin (OUTM), which
* on same (all?) tv-cards is not used, anyway (as well as MONOIN).
*/
if(tda9874a_dic == 0x11) {
int aosr = 0x80;
int mdacosr = (tda9874a_mode) ? 0x82:0x80;
switch(mode) {
case V4L2_TUNER_MODE_MONO:
case V4L2_TUNER_MODE_STEREO:
break;
case V4L2_TUNER_MODE_LANG1:
aosr = 0x80; /* auto-select, dual A/A */
mdacosr = (tda9874a_mode) ? 0x82:0x80;
break;
case V4L2_TUNER_MODE_LANG2:
aosr = 0xa0; /* auto-select, dual B/B */
mdacosr = (tda9874a_mode) ? 0x83:0x81;
break;
default:
chip->mode = 0;
return;
}
chip_write(chip, TDA9874A_AOSR, aosr);
chip_write(chip, TDA9874A_MDACOSR, mdacosr);
v4l2_dbg(1, debug, sd, "tda9874a_setmode(): req. mode %d; AOSR=0x%X, MDACOSR=0x%X.\n",
mode, aosr, mdacosr);
} else { /* dic == 0x07 */
int fmmr,aosr;
switch(mode) {
case V4L2_TUNER_MODE_MONO:
fmmr = 0x00; /* mono */
aosr = 0x10; /* A/A */
break;
case V4L2_TUNER_MODE_STEREO:
if(tda9874a_mode) {
fmmr = 0x00;
aosr = 0x00; /* handled by NICAM auto-mute */
} else {
fmmr = (tda9874a_ESP == 1) ? 0x05 : 0x04; /* stereo */
aosr = 0x00;
}
break;
case V4L2_TUNER_MODE_LANG1:
fmmr = 0x02; /* dual */
aosr = 0x10; /* dual A/A */
break;
case V4L2_TUNER_MODE_LANG2:
fmmr = 0x02; /* dual */
aosr = 0x20; /* dual B/B */
break;
default:
chip->mode = 0;
return;
}
chip_write(chip, TDA9874A_FMMR, fmmr);
chip_write(chip, TDA9874A_AOSR, aosr);
v4l2_dbg(1, debug, sd, "tda9874a_setmode(): req. mode %d; FMMR=0x%X, AOSR=0x%X.\n",
mode, fmmr, aosr);
}
}
static int tda9874a_checkit(struct CHIPSTATE *chip)
{
struct v4l2_subdev *sd = &chip->sd;
int dic,sic; /* device id. and software id. codes */
if(-1 == (dic = chip_read2(chip,TDA9874A_DIC)))
return 0;
if(-1 == (sic = chip_read2(chip,TDA9874A_SIC)))
return 0;
v4l2_dbg(1, debug, sd, "tda9874a_checkit(): DIC=0x%X, SIC=0x%X.\n", dic, sic);
if((dic == 0x11)||(dic == 0x07)) {
v4l2_info(sd, "found tda9874%s.\n", (dic == 0x11) ? "a" : "h");
tda9874a_dic = dic; /* remember device id. */
return 1;
}
return 0; /* not found */
}
static int tda9874a_initialize(struct CHIPSTATE *chip)
{
if (tda9874a_SIF > 2)
tda9874a_SIF = 1;
if (tda9874a_STD >= ARRAY_SIZE(tda9874a_modelist))
tda9874a_STD = 0;
if(tda9874a_AMSEL > 1)
tda9874a_AMSEL = 0;
if(tda9874a_SIF == 1)
tda9874a_GCONR = 0xc0; /* sound IF input 1 */
else
tda9874a_GCONR = 0xc1; /* sound IF input 2 */
tda9874a_ESP = tda9874a_STD;
tda9874a_mode = (tda9874a_STD < 5) ? 0 : 1;
if(tda9874a_AMSEL == 0)
tda9874a_NCONR = 0x01; /* auto-mute: analog mono input */
else
tda9874a_NCONR = 0x05; /* auto-mute: 1st carrier FM or AM */
tda9874a_setup(chip);
return 0;
}
/* ---------------------------------------------------------------------- */
/* audio chip description - defines+functions for tda9875 */
/* The TDA9875 is made by Philips Semiconductor
* http://www.semiconductors.philips.com
* TDA9875: I2C-bus controlled DSP audio processor, FM demodulator
*
*/
/* subaddresses for TDA9875 */
#define TDA9875_MUT 0x12 /*General mute (value --> 0b11001100*/
#define TDA9875_CFG 0x01 /* Config register (value --> 0b00000000 */
#define TDA9875_DACOS 0x13 /*DAC i/o select (ADC) 0b0000100*/
#define TDA9875_LOSR 0x16 /*Line output select regirter 0b0100 0001*/
#define TDA9875_CH1V 0x0c /*Channel 1 volume (mute)*/
#define TDA9875_CH2V 0x0d /*Channel 2 volume (mute)*/
#define TDA9875_SC1 0x14 /*SCART 1 in (mono)*/
#define TDA9875_SC2 0x15 /*SCART 2 in (mono)*/
#define TDA9875_ADCIS 0x17 /*ADC input select (mono) 0b0110 000*/
#define TDA9875_AER 0x19 /*Audio effect (AVL+Pseudo) 0b0000 0110*/
#define TDA9875_MCS 0x18 /*Main channel select (DAC) 0b0000100*/
#define TDA9875_MVL 0x1a /* Main volume gauche */
#define TDA9875_MVR 0x1b /* Main volume droite */
#define TDA9875_MBA 0x1d /* Main Basse */
#define TDA9875_MTR 0x1e /* Main treble */
#define TDA9875_ACS 0x1f /* Auxilary channel select (FM) 0b0000000*/
#define TDA9875_AVL 0x20 /* Auxilary volume gauche */
#define TDA9875_AVR 0x21 /* Auxilary volume droite */
#define TDA9875_ABA 0x22 /* Auxilary Basse */
#define TDA9875_ATR 0x23 /* Auxilary treble */
#define TDA9875_MSR 0x02 /* Monitor select register */
#define TDA9875_C1MSB 0x03 /* Carrier 1 (FM) frequency register MSB */
#define TDA9875_C1MIB 0x04 /* Carrier 1 (FM) frequency register (16-8]b */
#define TDA9875_C1LSB 0x05 /* Carrier 1 (FM) frequency register LSB */
#define TDA9875_C2MSB 0x06 /* Carrier 2 (nicam) frequency register MSB */
#define TDA9875_C2MIB 0x07 /* Carrier 2 (nicam) frequency register (16-8]b */
#define TDA9875_C2LSB 0x08 /* Carrier 2 (nicam) frequency register LSB */
#define TDA9875_DCR 0x09 /* Demodulateur configuration regirter*/
#define TDA9875_DEEM 0x0a /* FM de-emphasis regirter*/
#define TDA9875_FMAT 0x0b /* FM Matrix regirter*/
/* values */
#define TDA9875_MUTE_ON 0xff /* general mute */
#define TDA9875_MUTE_OFF 0xcc /* general no mute */
static int tda9875_initialize(struct CHIPSTATE *chip)
{
chip_write(chip, TDA9875_CFG, 0xd0); /*reg de config 0 (reset)*/
chip_write(chip, TDA9875_MSR, 0x03); /* Monitor 0b00000XXX*/
chip_write(chip, TDA9875_C1MSB, 0x00); /*Car1(FM) MSB XMHz*/
chip_write(chip, TDA9875_C1MIB, 0x00); /*Car1(FM) MIB XMHz*/
chip_write(chip, TDA9875_C1LSB, 0x00); /*Car1(FM) LSB XMHz*/
chip_write(chip, TDA9875_C2MSB, 0x00); /*Car2(NICAM) MSB XMHz*/
chip_write(chip, TDA9875_C2MIB, 0x00); /*Car2(NICAM) MIB XMHz*/
chip_write(chip, TDA9875_C2LSB, 0x00); /*Car2(NICAM) LSB XMHz*/
chip_write(chip, TDA9875_DCR, 0x00); /*Demod config 0x00*/
chip_write(chip, TDA9875_DEEM, 0x44); /*DE-Emph 0b0100 0100*/
chip_write(chip, TDA9875_FMAT, 0x00); /*FM Matrix reg 0x00*/
chip_write(chip, TDA9875_SC1, 0x00); /* SCART 1 (SC1)*/
chip_write(chip, TDA9875_SC2, 0x01); /* SCART 2 (sc2)*/
chip_write(chip, TDA9875_CH1V, 0x10); /* Channel volume 1 mute*/
chip_write(chip, TDA9875_CH2V, 0x10); /* Channel volume 2 mute */
chip_write(chip, TDA9875_DACOS, 0x02); /* sig DAC i/o(in:nicam)*/
chip_write(chip, TDA9875_ADCIS, 0x6f); /* sig ADC input(in:mono)*/
chip_write(chip, TDA9875_LOSR, 0x00); /* line out (in:mono)*/
chip_write(chip, TDA9875_AER, 0x00); /*06 Effect (AVL+PSEUDO) */
chip_write(chip, TDA9875_MCS, 0x44); /* Main ch select (DAC) */
chip_write(chip, TDA9875_MVL, 0x03); /* Vol Main left 10dB */
chip_write(chip, TDA9875_MVR, 0x03); /* Vol Main right 10dB*/
chip_write(chip, TDA9875_MBA, 0x00); /* Main Bass Main 0dB*/
chip_write(chip, TDA9875_MTR, 0x00); /* Main Treble Main 0dB*/
chip_write(chip, TDA9875_ACS, 0x44); /* Aux chan select (dac)*/
chip_write(chip, TDA9875_AVL, 0x00); /* Vol Aux left 0dB*/
chip_write(chip, TDA9875_AVR, 0x00); /* Vol Aux right 0dB*/
chip_write(chip, TDA9875_ABA, 0x00); /* Aux Bass Main 0dB*/
chip_write(chip, TDA9875_ATR, 0x00); /* Aux Aigus Main 0dB*/
chip_write(chip, TDA9875_MUT, 0xcc); /* General mute */
return 0;
}
static int tda9875_volume(int val) { return (unsigned char)(val / 602 - 84); }
static int tda9875_bass(int val) { return (unsigned char)(max(-12, val / 2115 - 15)); }
static int tda9875_treble(int val) { return (unsigned char)(val / 2622 - 12); }
/* ----------------------------------------------------------------------- */
/* *********************** *
* i2c interface functions *
* *********************** */
static int tda9875_checkit(struct CHIPSTATE *chip)
{
struct v4l2_subdev *sd = &chip->sd;
int dic, rev;
dic = chip_read2(chip, 254);
rev = chip_read2(chip, 255);
if (dic == 0 || dic == 2) { /* tda9875 and tda9875A */
v4l2_info(sd, "found tda9875%s rev. %d.\n",
dic == 0 ? "" : "A", rev);
return 1;
}
return 0;
}
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - defines+functions for tea6420 */
#define TEA6300_VL 0x00 /* volume left */
#define TEA6300_VR 0x01 /* volume right */
#define TEA6300_BA 0x02 /* bass */
#define TEA6300_TR 0x03 /* treble */
#define TEA6300_FA 0x04 /* fader control */
#define TEA6300_S 0x05 /* switch register */
/* values for those registers: */
#define TEA6300_S_SA 0x01 /* stereo A input */
#define TEA6300_S_SB 0x02 /* stereo B */
#define TEA6300_S_SC 0x04 /* stereo C */
#define TEA6300_S_GMU 0x80 /* general mute */
#define TEA6320_V 0x00 /* volume (0-5)/loudness off (6)/zero crossing mute(7) */
#define TEA6320_FFR 0x01 /* fader front right (0-5) */
#define TEA6320_FFL 0x02 /* fader front left (0-5) */
#define TEA6320_FRR 0x03 /* fader rear right (0-5) */
#define TEA6320_FRL 0x04 /* fader rear left (0-5) */
#define TEA6320_BA 0x05 /* bass (0-4) */
#define TEA6320_TR 0x06 /* treble (0-4) */
#define TEA6320_S 0x07 /* switch register */
/* values for those registers: */
#define TEA6320_S_SA 0x07 /* stereo A input */
#define TEA6320_S_SB 0x06 /* stereo B */
#define TEA6320_S_SC 0x05 /* stereo C */
#define TEA6320_S_SD 0x04 /* stereo D */
#define TEA6320_S_GMU 0x80 /* general mute */
#define TEA6420_S_SA 0x00 /* stereo A input */
#define TEA6420_S_SB 0x01 /* stereo B */
#define TEA6420_S_SC 0x02 /* stereo C */
#define TEA6420_S_SD 0x03 /* stereo D */
#define TEA6420_S_SE 0x04 /* stereo E */
#define TEA6420_S_GMU 0x05 /* general mute */
static int tea6300_shift10(int val) { return val >> 10; }
static int tea6300_shift12(int val) { return val >> 12; }
/* Assumes 16bit input (values 0x3f to 0x0c are unique, values less than */
/* 0x0c mirror those immediately higher) */
static int tea6320_volume(int val) { return (val / (65535/(63-12)) + 12) & 0x3f; }
static int tea6320_shift11(int val) { return val >> 11; }
static int tea6320_initialize(struct CHIPSTATE * chip)
{
chip_write(chip, TEA6320_FFR, 0x3f);
chip_write(chip, TEA6320_FFL, 0x3f);
chip_write(chip, TEA6320_FRR, 0x3f);
chip_write(chip, TEA6320_FRL, 0x3f);
return 0;
}
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - defines+functions for tda8425 */
#define TDA8425_VL 0x00 /* volume left */
#define TDA8425_VR 0x01 /* volume right */
#define TDA8425_BA 0x02 /* bass */
#define TDA8425_TR 0x03 /* treble */
#define TDA8425_S1 0x08 /* switch functions */
/* values for those registers: */
#define TDA8425_S1_OFF 0xEE /* audio off (mute on) */
#define TDA8425_S1_CH1 0xCE /* audio channel 1 (mute off) - "linear stereo" mode */
#define TDA8425_S1_CH2 0xCF /* audio channel 2 (mute off) - "linear stereo" mode */
#define TDA8425_S1_MU 0x20 /* mute bit */
#define TDA8425_S1_STEREO 0x18 /* stereo bits */
#define TDA8425_S1_STEREO_SPATIAL 0x18 /* spatial stereo */
#define TDA8425_S1_STEREO_LINEAR 0x08 /* linear stereo */
#define TDA8425_S1_STEREO_PSEUDO 0x10 /* pseudo stereo */
#define TDA8425_S1_STEREO_MONO 0x00 /* forced mono */
#define TDA8425_S1_ML 0x06 /* language selector */
#define TDA8425_S1_ML_SOUND_A 0x02 /* sound a */
#define TDA8425_S1_ML_SOUND_B 0x04 /* sound b */
#define TDA8425_S1_ML_STEREO 0x06 /* stereo */
#define TDA8425_S1_IS 0x01 /* channel selector */
static int tda8425_shift10(int val) { return (val >> 10) | 0xc0; }
static int tda8425_shift12(int val) { return (val >> 12) | 0xf0; }
static void tda8425_setmode(struct CHIPSTATE *chip, int mode)
{
int s1 = chip->shadow.bytes[TDA8425_S1+1] & 0xe1;
if (mode & V4L2_TUNER_MODE_LANG1) {
s1 |= TDA8425_S1_ML_SOUND_A;
s1 |= TDA8425_S1_STEREO_PSEUDO;
} else if (mode & V4L2_TUNER_MODE_LANG2) {
s1 |= TDA8425_S1_ML_SOUND_B;
s1 |= TDA8425_S1_STEREO_PSEUDO;
} else {
s1 |= TDA8425_S1_ML_STEREO;
if (mode & V4L2_TUNER_MODE_MONO)
s1 |= TDA8425_S1_STEREO_MONO;
if (mode & V4L2_TUNER_MODE_STEREO)
s1 |= TDA8425_S1_STEREO_SPATIAL;
}
chip_write(chip,TDA8425_S1,s1);
}
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - defines+functions for pic16c54 (PV951) */
/* the registers of 16C54, I2C sub address. */
#define PIC16C54_REG_KEY_CODE 0x01 /* Not use. */
#define PIC16C54_REG_MISC 0x02
/* bit definition of the RESET register, I2C data. */
#define PIC16C54_MISC_RESET_REMOTE_CTL 0x01 /* bit 0, Reset to receive the key */
/* code of remote controller */
#define PIC16C54_MISC_MTS_MAIN 0x02 /* bit 1 */
#define PIC16C54_MISC_MTS_SAP 0x04 /* bit 2 */
#define PIC16C54_MISC_MTS_BOTH 0x08 /* bit 3 */
#define PIC16C54_MISC_SND_MUTE 0x10 /* bit 4, Mute Audio(Line-in and Tuner) */
#define PIC16C54_MISC_SND_NOTMUTE 0x20 /* bit 5 */
#define PIC16C54_MISC_SWITCH_TUNER 0x40 /* bit 6 , Switch to Line-in */
#define PIC16C54_MISC_SWITCH_LINE 0x80 /* bit 7 , Switch to Tuner */
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - defines+functions for TA8874Z */
/* write 1st byte */
#define TA8874Z_LED_STE 0x80
#define TA8874Z_LED_BIL 0x40
#define TA8874Z_LED_EXT 0x20
#define TA8874Z_MONO_SET 0x10
#define TA8874Z_MUTE 0x08
#define TA8874Z_F_MONO 0x04
#define TA8874Z_MODE_SUB 0x02
#define TA8874Z_MODE_MAIN 0x01
/* write 2nd byte */
/*#define TA8874Z_TI 0x80 */ /* test mode */
#define TA8874Z_SEPARATION 0x3f
#define TA8874Z_SEPARATION_DEFAULT 0x10
/* read */
#define TA8874Z_B1 0x80
#define TA8874Z_B0 0x40
#define TA8874Z_CHAG_FLAG 0x20
/*
* B1 B0
* mono L H
* stereo L L
* BIL H L
*/
static int ta8874z_getmode(struct CHIPSTATE *chip)
{
int val, mode;
val = chip_read(chip);
mode = V4L2_TUNER_MODE_MONO;
if (val & TA8874Z_B1){
mode |= V4L2_TUNER_MODE_LANG1 | V4L2_TUNER_MODE_LANG2;
}else if (!(val & TA8874Z_B0)){
mode |= V4L2_TUNER_MODE_STEREO;
}
/* v4l_dbg(1, debug, chip->c, "ta8874z_getmode(): raw chip read: 0x%02x, return: 0x%02x\n", val, mode); */
return mode;
}
static audiocmd ta8874z_stereo = { 2, {0, TA8874Z_SEPARATION_DEFAULT}};
static audiocmd ta8874z_mono = {2, { TA8874Z_MONO_SET, TA8874Z_SEPARATION_DEFAULT}};
static audiocmd ta8874z_main = {2, { 0, TA8874Z_SEPARATION_DEFAULT}};
static audiocmd ta8874z_sub = {2, { TA8874Z_MODE_SUB, TA8874Z_SEPARATION_DEFAULT}};
static void ta8874z_setmode(struct CHIPSTATE *chip, int mode)
{
struct v4l2_subdev *sd = &chip->sd;
int update = 1;
audiocmd *t = NULL;
v4l2_dbg(1, debug, sd, "ta8874z_setmode(): mode: 0x%02x\n", mode);
switch(mode){
case V4L2_TUNER_MODE_MONO:
t = &ta8874z_mono;
break;
case V4L2_TUNER_MODE_STEREO:
t = &ta8874z_stereo;
break;
case V4L2_TUNER_MODE_LANG1:
t = &ta8874z_main;
break;
case V4L2_TUNER_MODE_LANG2:
t = &ta8874z_sub;
break;
default:
update = 0;
}
if(update)
chip_cmd(chip, "TA8874Z", t);
}
static int ta8874z_checkit(struct CHIPSTATE *chip)
{
int rc;
rc = chip_read(chip);
return ((rc & 0x1f) == 0x1f) ? 1 : 0;
}
/* ---------------------------------------------------------------------- */
/* audio chip descriptions - struct CHIPDESC */
/* insmod options to enable/disable individual audio chips */
static int tda8425 = 1;
static int tda9840 = 1;
static int tda9850 = 1;
static int tda9855 = 1;
static int tda9873 = 1;
static int tda9874a = 1;
static int tda9875 = 1;
static int tea6300; /* default 0 - address clash with msp34xx */
static int tea6320; /* default 0 - address clash with msp34xx */
static int tea6420 = 1;
static int pic16c54 = 1;
static int ta8874z; /* default 0 - address clash with tda9840 */
module_param(tda8425, int, 0444);
module_param(tda9840, int, 0444);
module_param(tda9850, int, 0444);
module_param(tda9855, int, 0444);
module_param(tda9873, int, 0444);
module_param(tda9874a, int, 0444);
module_param(tda9875, int, 0444);
module_param(tea6300, int, 0444);
module_param(tea6320, int, 0444);
module_param(tea6420, int, 0444);
module_param(pic16c54, int, 0444);
module_param(ta8874z, int, 0444);
static struct CHIPDESC chiplist[] = {
{
.name = "tda9840",
.insmodopt = &tda9840,
.addr_lo = I2C_ADDR_TDA9840 >> 1,
.addr_hi = I2C_ADDR_TDA9840 >> 1,
.registers = 5,
.flags = CHIP_NEED_CHECKMODE,
/* callbacks */
.checkit = tda9840_checkit,
.getmode = tda9840_getmode,
.setmode = tda9840_setmode,
.init = { 2, { TDA9840_TEST, TDA9840_TEST_INT1SN
/* ,TDA9840_SW, TDA9840_MONO */} }
},
{
.name = "tda9873h",
.insmodopt = &tda9873,
.addr_lo = I2C_ADDR_TDA985x_L >> 1,
.addr_hi = I2C_ADDR_TDA985x_H >> 1,
.registers = 3,
.flags = CHIP_HAS_INPUTSEL | CHIP_NEED_CHECKMODE,
/* callbacks */
.checkit = tda9873_checkit,
.getmode = tda9873_getmode,
.setmode = tda9873_setmode,
.init = { 4, { TDA9873_SW, 0xa4, 0x06, 0x03 } },
.inputreg = TDA9873_SW,
.inputmute = TDA9873_MUTE | TDA9873_AUTOMUTE,
.inputmap = {0xa0, 0xa2, 0xa0, 0xa0},
.inputmask = TDA9873_INP_MASK|TDA9873_MUTE|TDA9873_AUTOMUTE,
},
{
.name = "tda9874h/a",
.insmodopt = &tda9874a,
.addr_lo = I2C_ADDR_TDA9874 >> 1,
.addr_hi = I2C_ADDR_TDA9874 >> 1,
.flags = CHIP_NEED_CHECKMODE,
/* callbacks */
.initialize = tda9874a_initialize,
.checkit = tda9874a_checkit,
.getmode = tda9874a_getmode,
.setmode = tda9874a_setmode,
},
{
.name = "tda9875",
.insmodopt = &tda9875,
.addr_lo = I2C_ADDR_TDA9875 >> 1,
.addr_hi = I2C_ADDR_TDA9875 >> 1,
.flags = CHIP_HAS_VOLUME | CHIP_HAS_BASSTREBLE,
/* callbacks */
.initialize = tda9875_initialize,
.checkit = tda9875_checkit,
.volfunc = tda9875_volume,
.bassfunc = tda9875_bass,
.treblefunc = tda9875_treble,
.leftreg = TDA9875_MVL,
.rightreg = TDA9875_MVR,
.bassreg = TDA9875_MBA,
.treblereg = TDA9875_MTR,
.leftinit = 58880,
.rightinit = 58880,
},
{
.name = "tda9850",
.insmodopt = &tda9850,
.addr_lo = I2C_ADDR_TDA985x_L >> 1,
.addr_hi = I2C_ADDR_TDA985x_H >> 1,
.registers = 11,
.getmode = tda985x_getmode,
.setmode = tda985x_setmode,
.init = { 8, { TDA9850_C4, 0x08, 0x08, TDA985x_STEREO, 0x07, 0x10, 0x10, 0x03 } }
},
{
.name = "tda9855",
.insmodopt = &tda9855,
.addr_lo = I2C_ADDR_TDA985x_L >> 1,
.addr_hi = I2C_ADDR_TDA985x_H >> 1,
.registers = 11,
.flags = CHIP_HAS_VOLUME | CHIP_HAS_BASSTREBLE,
.leftreg = TDA9855_VL,
.rightreg = TDA9855_VR,
.bassreg = TDA9855_BA,
.treblereg = TDA9855_TR,
/* callbacks */
.volfunc = tda9855_volume,
.bassfunc = tda9855_bass,
.treblefunc = tda9855_treble,
.getmode = tda985x_getmode,
.setmode = tda985x_setmode,
.init = { 12, { 0, 0x6f, 0x6f, 0x0e, 0x07<<1, 0x8<<2,
TDA9855_MUTE | TDA9855_AVL | TDA9855_LOUD | TDA9855_INT,
TDA985x_STEREO | TDA9855_LINEAR | TDA9855_TZCM | TDA9855_VZCM,
0x07, 0x10, 0x10, 0x03 }}
},
{
.name = "tea6300",
.insmodopt = &tea6300,
.addr_lo = I2C_ADDR_TEA6300 >> 1,
.addr_hi = I2C_ADDR_TEA6300 >> 1,
.registers = 6,
.flags = CHIP_HAS_VOLUME | CHIP_HAS_BASSTREBLE | CHIP_HAS_INPUTSEL,
.leftreg = TEA6300_VR,
.rightreg = TEA6300_VL,
.bassreg = TEA6300_BA,
.treblereg = TEA6300_TR,
/* callbacks */
.volfunc = tea6300_shift10,
.bassfunc = tea6300_shift12,
.treblefunc = tea6300_shift12,
.inputreg = TEA6300_S,
.inputmap = { TEA6300_S_SA, TEA6300_S_SB, TEA6300_S_SC },
.inputmute = TEA6300_S_GMU,
},
{
.name = "tea6320",
.insmodopt = &tea6320,
.addr_lo = I2C_ADDR_TEA6300 >> 1,
.addr_hi = I2C_ADDR_TEA6300 >> 1,
.registers = 8,
.flags = CHIP_HAS_VOLUME | CHIP_HAS_BASSTREBLE | CHIP_HAS_INPUTSEL,
.leftreg = TEA6320_V,
.rightreg = TEA6320_V,
.bassreg = TEA6320_BA,
.treblereg = TEA6320_TR,
/* callbacks */
.initialize = tea6320_initialize,
.volfunc = tea6320_volume,
.bassfunc = tea6320_shift11,
.treblefunc = tea6320_shift11,
.inputreg = TEA6320_S,
.inputmap = { TEA6320_S_SA, TEA6420_S_SB, TEA6300_S_SC, TEA6320_S_SD },
.inputmute = TEA6300_S_GMU,
},
{
.name = "tea6420",
.insmodopt = &tea6420,
.addr_lo = I2C_ADDR_TEA6420 >> 1,
.addr_hi = I2C_ADDR_TEA6420 >> 1,
.registers = 1,
.flags = CHIP_HAS_INPUTSEL,
.inputreg = -1,
.inputmap = { TEA6420_S_SA, TEA6420_S_SB, TEA6420_S_SC },
.inputmute = TEA6300_S_GMU,
},
{
.name = "tda8425",
.insmodopt = &tda8425,
.addr_lo = I2C_ADDR_TDA8425 >> 1,
.addr_hi = I2C_ADDR_TDA8425 >> 1,
.registers = 9,
.flags = CHIP_HAS_VOLUME | CHIP_HAS_BASSTREBLE | CHIP_HAS_INPUTSEL,
.leftreg = TDA8425_VL,
.rightreg = TDA8425_VR,
.bassreg = TDA8425_BA,
.treblereg = TDA8425_TR,
/* callbacks */
.volfunc = tda8425_shift10,
.bassfunc = tda8425_shift12,
.treblefunc = tda8425_shift12,
.setmode = tda8425_setmode,
.inputreg = TDA8425_S1,
.inputmap = { TDA8425_S1_CH1, TDA8425_S1_CH1, TDA8425_S1_CH1 },
.inputmute = TDA8425_S1_OFF,
},
{
.name = "pic16c54 (PV951)",
.insmodopt = &pic16c54,
.addr_lo = I2C_ADDR_PIC16C54 >> 1,
.addr_hi = I2C_ADDR_PIC16C54>> 1,
.registers = 2,
.flags = CHIP_HAS_INPUTSEL,
.inputreg = PIC16C54_REG_MISC,
.inputmap = {PIC16C54_MISC_SND_NOTMUTE|PIC16C54_MISC_SWITCH_TUNER,
PIC16C54_MISC_SND_NOTMUTE|PIC16C54_MISC_SWITCH_LINE,
PIC16C54_MISC_SND_NOTMUTE|PIC16C54_MISC_SWITCH_LINE,
PIC16C54_MISC_SND_MUTE},
.inputmute = PIC16C54_MISC_SND_MUTE,
},
{
.name = "ta8874z",
.checkit = ta8874z_checkit,
.insmodopt = &ta8874z,
.addr_lo = I2C_ADDR_TDA9840 >> 1,
.addr_hi = I2C_ADDR_TDA9840 >> 1,
.registers = 2,
.flags = CHIP_NEED_CHECKMODE,
/* callbacks */
.getmode = ta8874z_getmode,
.setmode = ta8874z_setmode,
.init = {2, { TA8874Z_MONO_SET, TA8874Z_SEPARATION_DEFAULT}},
},
{ .name = NULL } /* EOF */
};
/* ---------------------------------------------------------------------- */
static int tvaudio_g_ctrl(struct v4l2_subdev *sd,
struct v4l2_control *ctrl)
{
struct CHIPSTATE *chip = to_state(sd);
struct CHIPDESC *desc = chip->desc;
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
if (!(desc->flags & CHIP_HAS_INPUTSEL))
break;
ctrl->value=chip->muted;
return 0;
case V4L2_CID_AUDIO_VOLUME:
if (!(desc->flags & CHIP_HAS_VOLUME))
break;
ctrl->value = max(chip->left,chip->right);
return 0;
case V4L2_CID_AUDIO_BALANCE:
{
int volume;
if (!(desc->flags & CHIP_HAS_VOLUME))
break;
volume = max(chip->left,chip->right);
if (volume)
ctrl->value=(32768*min(chip->left,chip->right))/volume;
else
ctrl->value=32768;
return 0;
}
case V4L2_CID_AUDIO_BASS:
if (!(desc->flags & CHIP_HAS_BASSTREBLE))
break;
ctrl->value = chip->bass;
return 0;
case V4L2_CID_AUDIO_TREBLE:
if (!(desc->flags & CHIP_HAS_BASSTREBLE))
break;
ctrl->value = chip->treble;
return 0;
}
return -EINVAL;
}
static int tvaudio_s_ctrl(struct v4l2_subdev *sd,
struct v4l2_control *ctrl)
{
struct CHIPSTATE *chip = to_state(sd);
struct CHIPDESC *desc = chip->desc;
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
if (!(desc->flags & CHIP_HAS_INPUTSEL))
break;
if (ctrl->value < 0 || ctrl->value >= 2)
return -ERANGE;
chip->muted = ctrl->value;
if (chip->muted)
chip_write_masked(chip,desc->inputreg,desc->inputmute,desc->inputmask);
else
chip_write_masked(chip,desc->inputreg,
desc->inputmap[chip->input],desc->inputmask);
return 0;
case V4L2_CID_AUDIO_VOLUME:
{
int volume,balance;
if (!(desc->flags & CHIP_HAS_VOLUME))
break;
volume = max(chip->left,chip->right);
if (volume)
balance=(32768*min(chip->left,chip->right))/volume;
else
balance=32768;
volume=ctrl->value;
chip->left = (min(65536 - balance,32768) * volume) / 32768;
chip->right = (min(balance,volume *(__u16)32768)) / 32768;
chip_write(chip,desc->leftreg,desc->volfunc(chip->left));
chip_write(chip,desc->rightreg,desc->volfunc(chip->right));
return 0;
}
case V4L2_CID_AUDIO_BALANCE:
{
int volume, balance;
if (!(desc->flags & CHIP_HAS_VOLUME))
break;
volume = max(chip->left,chip->right);
balance = ctrl->value;
chip_write(chip,desc->leftreg,desc->volfunc(chip->left));
chip_write(chip,desc->rightreg,desc->volfunc(chip->right));
return 0;
}
case V4L2_CID_AUDIO_BASS:
if (!(desc->flags & CHIP_HAS_BASSTREBLE))
break;
chip->bass = ctrl->value;
chip_write(chip,desc->bassreg,desc->bassfunc(chip->bass));
return 0;
case V4L2_CID_AUDIO_TREBLE:
if (!(desc->flags & CHIP_HAS_BASSTREBLE))
break;
chip->treble = ctrl->value;
chip_write(chip,desc->treblereg,desc->treblefunc(chip->treble));
return 0;
}
return -EINVAL;
}
/* ---------------------------------------------------------------------- */
/* video4linux interface */
static int tvaudio_s_radio(struct v4l2_subdev *sd)
{
struct CHIPSTATE *chip = to_state(sd);
chip->radio = 1;
chip->watch_stereo = 0;
/* del_timer(&chip->wt); */
return 0;
}
static int tvaudio_queryctrl(struct v4l2_subdev *sd, struct v4l2_queryctrl *qc)
{
struct CHIPSTATE *chip = to_state(sd);
struct CHIPDESC *desc = chip->desc;
switch (qc->id) {
case V4L2_CID_AUDIO_MUTE:
if (desc->flags & CHIP_HAS_INPUTSEL)
return v4l2_ctrl_query_fill(qc, 0, 1, 1, 0);
break;
case V4L2_CID_AUDIO_VOLUME:
if (desc->flags & CHIP_HAS_VOLUME)
return v4l2_ctrl_query_fill(qc, 0, 65535, 65535 / 100, 58880);
break;
case V4L2_CID_AUDIO_BALANCE:
if (desc->flags & CHIP_HAS_VOLUME)
return v4l2_ctrl_query_fill(qc, 0, 65535, 65535 / 100, 32768);
break;
case V4L2_CID_AUDIO_BASS:
case V4L2_CID_AUDIO_TREBLE:
if (desc->flags & CHIP_HAS_BASSTREBLE)
return v4l2_ctrl_query_fill(qc, 0, 65535, 65535 / 100, 32768);
break;
default:
break;
}
return -EINVAL;
}
static int tvaudio_s_routing(struct v4l2_subdev *sd,
u32 input, u32 output, u32 config)
{
struct CHIPSTATE *chip = to_state(sd);
struct CHIPDESC *desc = chip->desc;
if (!(desc->flags & CHIP_HAS_INPUTSEL))
return 0;
if (input >= 4)
return -EINVAL;
/* There are four inputs: tuner, radio, extern and intern. */
chip->input = input;
if (chip->muted)
return 0;
chip_write_masked(chip, desc->inputreg,
desc->inputmap[chip->input], desc->inputmask);
return 0;
}
static int tvaudio_s_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *vt)
{
struct CHIPSTATE *chip = to_state(sd);
struct CHIPDESC *desc = chip->desc;
int mode = 0;
if (!desc->setmode)
return 0;
if (chip->radio)
return 0;
switch (vt->audmode) {
case V4L2_TUNER_MODE_MONO:
case V4L2_TUNER_MODE_STEREO:
case V4L2_TUNER_MODE_LANG1:
case V4L2_TUNER_MODE_LANG2:
mode = vt->audmode;
break;
case V4L2_TUNER_MODE_LANG1_LANG2:
mode = V4L2_TUNER_MODE_STEREO;
break;
default:
return -EINVAL;
}
chip->audmode = vt->audmode;
if (mode) {
chip->watch_stereo = 0;
/* del_timer(&chip->wt); */
chip->mode = mode;
desc->setmode(chip, mode);
}
return 0;
}
static int tvaudio_g_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *vt)
{
struct CHIPSTATE *chip = to_state(sd);
struct CHIPDESC *desc = chip->desc;
int mode = V4L2_TUNER_MODE_MONO;
if (!desc->getmode)
return 0;
if (chip->radio)
return 0;
vt->audmode = chip->audmode;
vt->rxsubchans = 0;
vt->capability = V4L2_TUNER_CAP_STEREO |
V4L2_TUNER_CAP_LANG1 | V4L2_TUNER_CAP_LANG2;
mode = desc->getmode(chip);
if (mode & V4L2_TUNER_MODE_MONO)
vt->rxsubchans |= V4L2_TUNER_SUB_MONO;
if (mode & V4L2_TUNER_MODE_STEREO)
vt->rxsubchans |= V4L2_TUNER_SUB_STEREO;
/* Note: for SAP it should be mono/lang2 or stereo/lang2.
When this module is converted fully to v4l2, then this
should change for those chips that can detect SAP. */
if (mode & V4L2_TUNER_MODE_LANG1)
vt->rxsubchans = V4L2_TUNER_SUB_LANG1 |
V4L2_TUNER_SUB_LANG2;
return 0;
}
static int tvaudio_s_std(struct v4l2_subdev *sd, v4l2_std_id std)
{
struct CHIPSTATE *chip = to_state(sd);
chip->radio = 0;
return 0;
}
static int tvaudio_s_frequency(struct v4l2_subdev *sd, struct v4l2_frequency *freq)
{
struct CHIPSTATE *chip = to_state(sd);
struct CHIPDESC *desc = chip->desc;
chip->mode = 0; /* automatic */
/* For chips that provide getmode and setmode, and doesn't
automatically follows the stereo carrier, a kthread is
created to set the audio standard. In this case, when then
the video channel is changed, tvaudio starts on MONO mode.
After waiting for 2 seconds, the kernel thread is called,
to follow whatever audio standard is pointed by the
audio carrier.
*/
if (chip->thread) {
desc->setmode(chip, V4L2_TUNER_MODE_MONO);
if (chip->prevmode != V4L2_TUNER_MODE_MONO)
chip->prevmode = -1; /* reset previous mode */
mod_timer(&chip->wt, jiffies+msecs_to_jiffies(2000));
}
return 0;
}
static int tvaudio_g_chip_ident(struct v4l2_subdev *sd, struct v4l2_dbg_chip_ident *chip)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_TVAUDIO, 0);
}
/* ----------------------------------------------------------------------- */
static const struct v4l2_subdev_core_ops tvaudio_core_ops = {
.g_chip_ident = tvaudio_g_chip_ident,
.queryctrl = tvaudio_queryctrl,
.g_ctrl = tvaudio_g_ctrl,
.s_ctrl = tvaudio_s_ctrl,
.s_std = tvaudio_s_std,
};
static const struct v4l2_subdev_tuner_ops tvaudio_tuner_ops = {
.s_radio = tvaudio_s_radio,
.s_frequency = tvaudio_s_frequency,
.s_tuner = tvaudio_s_tuner,
.g_tuner = tvaudio_g_tuner,
};
static const struct v4l2_subdev_audio_ops tvaudio_audio_ops = {
.s_routing = tvaudio_s_routing,
};
static const struct v4l2_subdev_ops tvaudio_ops = {
.core = &tvaudio_core_ops,
.tuner = &tvaudio_tuner_ops,
.audio = &tvaudio_audio_ops,
};
/* ----------------------------------------------------------------------- */
/* i2c registration */
static int tvaudio_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
struct CHIPSTATE *chip;
struct CHIPDESC *desc;
struct v4l2_subdev *sd;
if (debug) {
printk(KERN_INFO "tvaudio: TV audio decoder + audio/video mux driver\n");
printk(KERN_INFO "tvaudio: known chips: ");
for (desc = chiplist; desc->name != NULL; desc++)
printk("%s%s", (desc == chiplist) ? "" : ", ", desc->name);
printk("\n");
}
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (!chip)
return -ENOMEM;
sd = &chip->sd;
v4l2_i2c_subdev_init(sd, client, &tvaudio_ops);
/* find description for the chip */
v4l2_dbg(1, debug, sd, "chip found @ 0x%x\n", client->addr<<1);
for (desc = chiplist; desc->name != NULL; desc++) {
if (0 == *(desc->insmodopt))
continue;
if (client->addr < desc->addr_lo ||
client->addr > desc->addr_hi)
continue;
if (desc->checkit && !desc->checkit(chip))
continue;
break;
}
if (desc->name == NULL) {
v4l2_dbg(1, debug, sd, "no matching chip description found\n");
kfree(chip);
return -EIO;
}
v4l2_info(sd, "%s found @ 0x%x (%s)\n", desc->name, client->addr<<1, client->adapter->name);
if (desc->flags) {
v4l2_dbg(1, debug, sd, "matches:%s%s%s.\n",
(desc->flags & CHIP_HAS_VOLUME) ? " volume" : "",
(desc->flags & CHIP_HAS_BASSTREBLE) ? " bass/treble" : "",
(desc->flags & CHIP_HAS_INPUTSEL) ? " audiomux" : "");
}
/* fill required data structures */
if (!id)
strlcpy(client->name, desc->name, I2C_NAME_SIZE);
chip->desc = desc;
chip->shadow.count = desc->registers+1;
chip->prevmode = -1;
chip->audmode = V4L2_TUNER_MODE_LANG1;
/* initialization */
if (desc->initialize != NULL)
desc->initialize(chip);
else
chip_cmd(chip, "init", &desc->init);
if (desc->flags & CHIP_HAS_VOLUME) {
if (!desc->volfunc) {
/* This shouldn't be happen. Warn user, but keep working
without volume controls
*/
v4l2_info(sd, "volume callback undefined!\n");
desc->flags &= ~CHIP_HAS_VOLUME;
} else {
chip->left = desc->leftinit ? desc->leftinit : 65535;
chip->right = desc->rightinit ? desc->rightinit : 65535;
chip_write(chip, desc->leftreg,
desc->volfunc(chip->left));
chip_write(chip, desc->rightreg,
desc->volfunc(chip->right));
}
}
if (desc->flags & CHIP_HAS_BASSTREBLE) {
if (!desc->bassfunc || !desc->treblefunc) {
/* This shouldn't be happen. Warn user, but keep working
without bass/treble controls
*/
v4l2_info(sd, "bass/treble callbacks undefined!\n");
desc->flags &= ~CHIP_HAS_BASSTREBLE;
} else {
chip->treble = desc->trebleinit ?
desc->trebleinit : 32768;
chip->bass = desc->bassinit ?
desc->bassinit : 32768;
chip_write(chip, desc->bassreg,
desc->bassfunc(chip->bass));
chip_write(chip, desc->treblereg,
desc->treblefunc(chip->treble));
}
}
chip->thread = NULL;
init_timer(&chip->wt);
if (desc->flags & CHIP_NEED_CHECKMODE) {
if (!desc->getmode || !desc->setmode) {
/* This shouldn't be happen. Warn user, but keep working
without kthread
*/
v4l2_info(sd, "set/get mode callbacks undefined!\n");
return 0;
}
/* start async thread */
chip->wt.function = chip_thread_wake;
chip->wt.data = (unsigned long)chip;
chip->thread = kthread_run(chip_thread, chip, client->name);
if (IS_ERR(chip->thread)) {
v4l2_warn(sd, "failed to create kthread\n");
chip->thread = NULL;
}
}
return 0;
}
static int tvaudio_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
struct CHIPSTATE *chip = to_state(sd);
del_timer_sync(&chip->wt);
if (chip->thread) {
/* shutdown async thread */
kthread_stop(chip->thread);
chip->thread = NULL;
}
v4l2_device_unregister_subdev(sd);
kfree(chip);
return 0;
}
/* This driver supports many devices and the idea is to let the driver
detect which device is present. So rather than listing all supported
devices here, we pretend to support a single, fake device type. */
static const struct i2c_device_id tvaudio_id[] = {
{ "tvaudio", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, tvaudio_id);
static struct i2c_driver tvaudio_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "tvaudio",
},
.probe = tvaudio_probe,
.remove = tvaudio_remove,
.id_table = tvaudio_id,
};
static __init int init_tvaudio(void)
{
return i2c_add_driver(&tvaudio_driver);
}
static __exit void exit_tvaudio(void)
{
i2c_del_driver(&tvaudio_driver);
}
module_init(init_tvaudio);
module_exit(exit_tvaudio);
| gpl-2.0 |
ivanmmj/CommunityEris | fs/ubifs/xattr.c | 204 | 15822 | /*
* This file is part of UBIFS.
*
* Copyright (C) 2006-2008 Nokia Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Authors: Artem Bityutskiy (Битюцкий Артём)
* Adrian Hunter
*/
/*
* This file implements UBIFS extended attributes support.
*
* Extended attributes are implemented as regular inodes with attached data,
* which limits extended attribute size to UBIFS block size (4KiB). Names of
* extended attributes are described by extended attribute entries (xentries),
* which are almost identical to directory entries, but have different key type.
*
* In other words, the situation with extended attributes is very similar to
* directories. Indeed, any inode (but of course not xattr inodes) may have a
* number of associated xentries, just like directory inodes have associated
* directory entries. Extended attribute entries store the name of the extended
* attribute, the host inode number, and the extended attribute inode number.
* Similarly, direntries store the name, the parent and the target inode
* numbers. Thus, most of the common UBIFS mechanisms may be re-used for
* extended attributes.
*
* The number of extended attributes is not limited, but there is Linux
* limitation on the maximum possible size of the list of all extended
* attributes associated with an inode (%XATTR_LIST_MAX), so UBIFS makes sure
* the sum of all extended attribute names of the inode does not exceed that
* limit.
*
* Extended attributes are synchronous, which means they are written to the
* flash media synchronously and there is no write-back for extended attribute
* inodes. The extended attribute values are not stored in compressed form on
* the media.
*
* Since extended attributes are represented by regular inodes, they are cached
* in the VFS inode cache. The xentries are cached in the LNC cache (see
* tnc.c).
*
* ACL support is not implemented.
*/
#include <linux/xattr.h>
#include <linux/posix_acl_xattr.h>
#include "ubifs.h"
/*
* Limit the number of extended attributes per inode so that the total size
* (@xattr_size) is guaranteeded to fit in an 'unsigned int'.
*/
#define MAX_XATTRS_PER_INODE 65535
/*
* Extended attribute type constants.
*
* USER_XATTR: user extended attribute ("user.*")
* TRUSTED_XATTR: trusted extended attribute ("trusted.*)
* SECURITY_XATTR: security extended attribute ("security.*")
*/
enum {
USER_XATTR,
TRUSTED_XATTR,
SECURITY_XATTR,
};
static struct inode_operations none_inode_operations;
static struct address_space_operations none_address_operations;
static struct file_operations none_file_operations;
/**
* create_xattr - create an extended attribute.
* @c: UBIFS file-system description object
* @host: host inode
* @nm: extended attribute name
* @value: extended attribute value
* @size: size of extended attribute value
*
* This is a helper function which creates an extended attribute of name @nm
* and value @value for inode @host. The host inode is also updated on flash
* because the ctime and extended attribute accounting data changes. This
* function returns zero in case of success and a negative error code in case
* of failure.
*/
static int create_xattr(struct ubifs_info *c, struct inode *host,
const struct qstr *nm, const void *value, int size)
{
int err;
struct inode *inode;
struct ubifs_inode *ui, *host_ui = ubifs_inode(host);
struct ubifs_budget_req req = { .new_ino = 1, .new_dent = 1,
.new_ino_d = ALIGN(size, 8), .dirtied_ino = 1,
.dirtied_ino_d = ALIGN(host_ui->data_len, 8) };
if (host_ui->xattr_cnt >= MAX_XATTRS_PER_INODE)
return -ENOSPC;
/*
* Linux limits the maximum size of the extended attribute names list
* to %XATTR_LIST_MAX. This means we should not allow creating more
* extended attributes if the name list becomes larger. This limitation
* is artificial for UBIFS, though.
*/
if (host_ui->xattr_names + host_ui->xattr_cnt +
nm->len + 1 > XATTR_LIST_MAX)
return -ENOSPC;
err = ubifs_budget_space(c, &req);
if (err)
return err;
inode = ubifs_new_inode(c, host, S_IFREG | S_IRWXUGO);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
goto out_budg;
}
/* Re-define all operations to be "nothing" */
inode->i_mapping->a_ops = &none_address_operations;
inode->i_op = &none_inode_operations;
inode->i_fop = &none_file_operations;
inode->i_flags |= S_SYNC | S_NOATIME | S_NOCMTIME | S_NOQUOTA;
ui = ubifs_inode(inode);
ui->xattr = 1;
ui->flags |= UBIFS_XATTR_FL;
ui->data = kmalloc(size, GFP_NOFS);
if (!ui->data) {
err = -ENOMEM;
goto out_free;
}
memcpy(ui->data, value, size);
inode->i_size = ui->ui_size = size;
ui->data_len = size;
mutex_lock(&host_ui->ui_mutex);
host->i_ctime = ubifs_current_time(host);
host_ui->xattr_cnt += 1;
host_ui->xattr_size += CALC_DENT_SIZE(nm->len);
host_ui->xattr_size += CALC_XATTR_BYTES(size);
host_ui->xattr_names += nm->len;
err = ubifs_jnl_update(c, host, nm, inode, 0, 1);
if (err)
goto out_cancel;
mutex_unlock(&host_ui->ui_mutex);
ubifs_release_budget(c, &req);
insert_inode_hash(inode);
iput(inode);
return 0;
out_cancel:
host_ui->xattr_cnt -= 1;
host_ui->xattr_size -= CALC_DENT_SIZE(nm->len);
host_ui->xattr_size -= CALC_XATTR_BYTES(size);
mutex_unlock(&host_ui->ui_mutex);
out_free:
make_bad_inode(inode);
iput(inode);
out_budg:
ubifs_release_budget(c, &req);
return err;
}
/**
* change_xattr - change an extended attribute.
* @c: UBIFS file-system description object
* @host: host inode
* @inode: extended attribute inode
* @value: extended attribute value
* @size: size of extended attribute value
*
* This helper function changes the value of extended attribute @inode with new
* data from @value. Returns zero in case of success and a negative error code
* in case of failure.
*/
static int change_xattr(struct ubifs_info *c, struct inode *host,
struct inode *inode, const void *value, int size)
{
int err;
struct ubifs_inode *host_ui = ubifs_inode(host);
struct ubifs_inode *ui = ubifs_inode(inode);
struct ubifs_budget_req req = { .dirtied_ino = 2,
.dirtied_ino_d = ALIGN(size, 8) + ALIGN(host_ui->data_len, 8) };
ubifs_assert(ui->data_len == inode->i_size);
err = ubifs_budget_space(c, &req);
if (err)
return err;
kfree(ui->data);
ui->data = kmalloc(size, GFP_NOFS);
if (!ui->data) {
err = -ENOMEM;
goto out_free;
}
memcpy(ui->data, value, size);
inode->i_size = ui->ui_size = size;
ui->data_len = size;
mutex_lock(&host_ui->ui_mutex);
host->i_ctime = ubifs_current_time(host);
host_ui->xattr_size -= CALC_XATTR_BYTES(ui->data_len);
host_ui->xattr_size += CALC_XATTR_BYTES(size);
/*
* It is important to write the host inode after the xattr inode
* because if the host inode gets synchronized (via 'fsync()'), then
* the extended attribute inode gets synchronized, because it goes
* before the host inode in the write-buffer.
*/
err = ubifs_jnl_change_xattr(c, inode, host);
if (err)
goto out_cancel;
mutex_unlock(&host_ui->ui_mutex);
ubifs_release_budget(c, &req);
return 0;
out_cancel:
host_ui->xattr_size -= CALC_XATTR_BYTES(size);
host_ui->xattr_size += CALC_XATTR_BYTES(ui->data_len);
mutex_unlock(&host_ui->ui_mutex);
make_bad_inode(inode);
out_free:
ubifs_release_budget(c, &req);
return err;
}
/**
* check_namespace - check extended attribute name-space.
* @nm: extended attribute name
*
* This function makes sure the extended attribute name belongs to one of the
* supported extended attribute name-spaces. Returns name-space index in case
* of success and a negative error code in case of failure.
*/
static int check_namespace(const struct qstr *nm)
{
int type;
if (nm->len > UBIFS_MAX_NLEN)
return -ENAMETOOLONG;
if (!strncmp(nm->name, XATTR_TRUSTED_PREFIX,
XATTR_TRUSTED_PREFIX_LEN)) {
if (nm->name[sizeof(XATTR_TRUSTED_PREFIX) - 1] == '\0')
return -EINVAL;
type = TRUSTED_XATTR;
} else if (!strncmp(nm->name, XATTR_USER_PREFIX,
XATTR_USER_PREFIX_LEN)) {
if (nm->name[XATTR_USER_PREFIX_LEN] == '\0')
return -EINVAL;
type = USER_XATTR;
} else if (!strncmp(nm->name, XATTR_SECURITY_PREFIX,
XATTR_SECURITY_PREFIX_LEN)) {
if (nm->name[sizeof(XATTR_SECURITY_PREFIX) - 1] == '\0')
return -EINVAL;
type = SECURITY_XATTR;
} else
return -EOPNOTSUPP;
return type;
}
static struct inode *iget_xattr(struct ubifs_info *c, ino_t inum)
{
struct inode *inode;
inode = ubifs_iget(c->vfs_sb, inum);
if (IS_ERR(inode)) {
ubifs_err("dead extended attribute entry, error %d",
(int)PTR_ERR(inode));
return inode;
}
if (ubifs_inode(inode)->xattr)
return inode;
ubifs_err("corrupt extended attribute entry");
iput(inode);
return ERR_PTR(-EINVAL);
}
int ubifs_setxattr(struct dentry *dentry, const char *name,
const void *value, size_t size, int flags)
{
struct inode *inode, *host = dentry->d_inode;
struct ubifs_info *c = host->i_sb->s_fs_info;
struct qstr nm = { .name = name, .len = strlen(name) };
struct ubifs_dent_node *xent;
union ubifs_key key;
int err, type;
dbg_gen("xattr '%s', host ino %lu ('%.*s'), size %zd", name,
host->i_ino, dentry->d_name.len, dentry->d_name.name, size);
ubifs_assert(mutex_is_locked(&host->i_mutex));
if (size > UBIFS_MAX_INO_DATA)
return -ERANGE;
type = check_namespace(&nm);
if (type < 0)
return type;
xent = kmalloc(UBIFS_MAX_XENT_NODE_SZ, GFP_NOFS);
if (!xent)
return -ENOMEM;
/*
* The extended attribute entries are stored in LNC, so multiple
* look-ups do not involve reading the flash.
*/
xent_key_init(c, &key, host->i_ino, &nm);
err = ubifs_tnc_lookup_nm(c, &key, xent, &nm);
if (err) {
if (err != -ENOENT)
goto out_free;
if (flags & XATTR_REPLACE)
/* We are asked not to create the xattr */
err = -ENODATA;
else
err = create_xattr(c, host, &nm, value, size);
goto out_free;
}
if (flags & XATTR_CREATE) {
/* We are asked not to replace the xattr */
err = -EEXIST;
goto out_free;
}
inode = iget_xattr(c, le64_to_cpu(xent->inum));
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
goto out_free;
}
err = change_xattr(c, host, inode, value, size);
iput(inode);
out_free:
kfree(xent);
return err;
}
ssize_t ubifs_getxattr(struct dentry *dentry, const char *name, void *buf,
size_t size)
{
struct inode *inode, *host = dentry->d_inode;
struct ubifs_info *c = host->i_sb->s_fs_info;
struct qstr nm = { .name = name, .len = strlen(name) };
struct ubifs_inode *ui;
struct ubifs_dent_node *xent;
union ubifs_key key;
int err;
dbg_gen("xattr '%s', ino %lu ('%.*s'), buf size %zd", name,
host->i_ino, dentry->d_name.len, dentry->d_name.name, size);
err = check_namespace(&nm);
if (err < 0)
return err;
xent = kmalloc(UBIFS_MAX_XENT_NODE_SZ, GFP_NOFS);
if (!xent)
return -ENOMEM;
xent_key_init(c, &key, host->i_ino, &nm);
err = ubifs_tnc_lookup_nm(c, &key, xent, &nm);
if (err) {
if (err == -ENOENT)
err = -ENODATA;
goto out_unlock;
}
inode = iget_xattr(c, le64_to_cpu(xent->inum));
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
goto out_unlock;
}
ui = ubifs_inode(inode);
ubifs_assert(inode->i_size == ui->data_len);
ubifs_assert(ubifs_inode(host)->xattr_size > ui->data_len);
if (buf) {
/* If @buf is %NULL we are supposed to return the length */
if (ui->data_len > size) {
dbg_err("buffer size %zd, xattr len %d",
size, ui->data_len);
err = -ERANGE;
goto out_iput;
}
memcpy(buf, ui->data, ui->data_len);
}
err = ui->data_len;
out_iput:
iput(inode);
out_unlock:
kfree(xent);
return err;
}
ssize_t ubifs_listxattr(struct dentry *dentry, char *buffer, size_t size)
{
union ubifs_key key;
struct inode *host = dentry->d_inode;
struct ubifs_info *c = host->i_sb->s_fs_info;
struct ubifs_inode *host_ui = ubifs_inode(host);
struct ubifs_dent_node *xent, *pxent = NULL;
int err, len, written = 0;
struct qstr nm = { .name = NULL };
dbg_gen("ino %lu ('%.*s'), buffer size %zd", host->i_ino,
dentry->d_name.len, dentry->d_name.name, size);
len = host_ui->xattr_names + host_ui->xattr_cnt;
if (!buffer)
/*
* We should return the minimum buffer size which will fit a
* null-terminated list of all the extended attribute names.
*/
return len;
if (len > size)
return -ERANGE;
lowest_xent_key(c, &key, host->i_ino);
while (1) {
int type;
xent = ubifs_tnc_next_ent(c, &key, &nm);
if (IS_ERR(xent)) {
err = PTR_ERR(xent);
break;
}
nm.name = xent->name;
nm.len = le16_to_cpu(xent->nlen);
type = check_namespace(&nm);
if (unlikely(type < 0)) {
err = type;
break;
}
/* Show trusted namespace only for "power" users */
if (type != TRUSTED_XATTR || capable(CAP_SYS_ADMIN)) {
memcpy(buffer + written, nm.name, nm.len + 1);
written += nm.len + 1;
}
kfree(pxent);
pxent = xent;
key_read(c, &xent->key, &key);
}
kfree(pxent);
if (err != -ENOENT) {
ubifs_err("cannot find next direntry, error %d", err);
return err;
}
ubifs_assert(written <= size);
return written;
}
static int remove_xattr(struct ubifs_info *c, struct inode *host,
struct inode *inode, const struct qstr *nm)
{
int err;
struct ubifs_inode *host_ui = ubifs_inode(host);
struct ubifs_inode *ui = ubifs_inode(inode);
struct ubifs_budget_req req = { .dirtied_ino = 2, .mod_dent = 1,
.dirtied_ino_d = ALIGN(host_ui->data_len, 8) };
ubifs_assert(ui->data_len == inode->i_size);
err = ubifs_budget_space(c, &req);
if (err)
return err;
mutex_lock(&host_ui->ui_mutex);
host->i_ctime = ubifs_current_time(host);
host_ui->xattr_cnt -= 1;
host_ui->xattr_size -= CALC_DENT_SIZE(nm->len);
host_ui->xattr_size -= CALC_XATTR_BYTES(ui->data_len);
host_ui->xattr_names -= nm->len;
err = ubifs_jnl_delete_xattr(c, host, inode, nm);
if (err)
goto out_cancel;
mutex_unlock(&host_ui->ui_mutex);
ubifs_release_budget(c, &req);
return 0;
out_cancel:
host_ui->xattr_cnt += 1;
host_ui->xattr_size += CALC_DENT_SIZE(nm->len);
host_ui->xattr_size += CALC_XATTR_BYTES(ui->data_len);
mutex_unlock(&host_ui->ui_mutex);
ubifs_release_budget(c, &req);
make_bad_inode(inode);
return err;
}
int ubifs_removexattr(struct dentry *dentry, const char *name)
{
struct inode *inode, *host = dentry->d_inode;
struct ubifs_info *c = host->i_sb->s_fs_info;
struct qstr nm = { .name = name, .len = strlen(name) };
struct ubifs_dent_node *xent;
union ubifs_key key;
int err;
dbg_gen("xattr '%s', ino %lu ('%.*s')", name,
host->i_ino, dentry->d_name.len, dentry->d_name.name);
ubifs_assert(mutex_is_locked(&host->i_mutex));
err = check_namespace(&nm);
if (err < 0)
return err;
xent = kmalloc(UBIFS_MAX_XENT_NODE_SZ, GFP_NOFS);
if (!xent)
return -ENOMEM;
xent_key_init(c, &key, host->i_ino, &nm);
err = ubifs_tnc_lookup_nm(c, &key, xent, &nm);
if (err) {
if (err == -ENOENT)
err = -ENODATA;
goto out_free;
}
inode = iget_xattr(c, le64_to_cpu(xent->inum));
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
goto out_free;
}
ubifs_assert(inode->i_nlink == 1);
inode->i_nlink = 0;
err = remove_xattr(c, host, inode, &nm);
if (err)
inode->i_nlink = 1;
/* If @i_nlink is 0, 'iput()' will delete the inode */
iput(inode);
out_free:
kfree(xent);
return err;
}
| gpl-2.0 |
major91/HTC_X515E_major-kernel | drivers/media/video/msm/gemini_8x60/msm_gemini_platform.c | 204 | 6860 | /* Copyright (c) 2010, Code Aurora Forum. All rights reserved.
*
* 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.
* * Neither the name of Code Aurora Forum, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED "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 COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Alternatively, and instead of the terms immediately above, this
* software may be relicensed by the recipient at their option under the
* terms of the GNU General Public License version 2 ("GPL") and only
* version 2. If the recipient chooses to relicense the software under
* the GPL, then the recipient shall replace all of the text immediately
* above and including this paragraph with the text immediately below
* and between the words START OF ALTERNATE GPL TERMS and END OF
* ALTERNATE GPL TERMS and such notices and license terms shall apply
* INSTEAD OF the notices and licensing terms given above.
*
* START OF ALTERNATE GPL TERMS
*
* Copyright (c) 2010, Code Aurora Forum. All rights reserved.
*
* This software was originally licensed under the Code Aurora Forum
* Inc. Dual BSD/GPL License version 1.1 and relicensed as permitted
* under the terms thereof by a recipient under the General Public
* License Version 2.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* END OF ALTERNATE GPL TERMS
*/
#include <linux/module.h>
#include <linux/pm_qos_params.h>
#include <linux/clk.h>
#include <mach/clk.h>
#include <linux/io.h>
#include <linux/android_pmem.h>
/*#include <mach/msm_reqs.h>*/
#ifdef CONFIG_MSM_CAMERA_7X30
#include <mach/camera-7x30.h>
#elif defined(CONFIG_MSM_CAMERA_8X60)
#include <mach/camera-8x60.h>
#endif
#include "msm_gemini_platform.h"
#include "msm_gemini_common.h"
#include "msm_gemini_hw.h"
#ifdef CONFIG_MSM_NPA_SYSTEM_BUS
/* NPA Flow ID */
#define MSM_SYSTEM_BUS_RATE MSM_AXI_FLOW_JPEG_12MP
#else
/* AXI rate in KHz */
#define MSM_SYSTEM_BUS_RATE 160000
#endif
void msm_gemini_platform_p2v(struct file *file)
{
put_pmem_file(file);
}
uint32_t msm_gemini_platform_v2p(int fd, uint32_t len, struct file **file_p)
{
unsigned long paddr;
unsigned long kvstart;
unsigned long size;
int rc;
rc = get_pmem_file(fd, &paddr, &kvstart, &size, file_p);
if (rc < 0) {
GMN_PR_ERR("%s: get_pmem_file fd %d error %d\n", __func__, fd,
rc);
return 0;
}
/* validate user input */
if (len > size) {
GMN_PR_ERR("%s: invalid offset + len\n", __func__);
return 0;
}
return paddr;
}
int msm_gemini_platform_init(struct platform_device *pdev,
struct resource **mem,
void **base,
int *irq,
irqreturn_t (*handler) (int, void *),
void *context)
{
int rc = -1;
int gemini_irq;
struct resource *gemini_mem, *gemini_io, *gemini_irq_res;
void *gemini_base;
gemini_mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!gemini_mem) {
GMN_PR_ERR("%s: no mem resource?\n", __func__);
return -ENODEV;
}
gemini_irq_res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!gemini_irq_res) {
GMN_PR_ERR("no irq resource?\n");
return -ENODEV;
}
gemini_irq = gemini_irq_res->start;
gemini_io = request_mem_region(gemini_mem->start,
resource_size(gemini_mem), pdev->name);
if (!gemini_io) {
GMN_PR_ERR("%s: region already claimed\n", __func__);
return -EBUSY;
}
gemini_base = ioremap(gemini_mem->start, resource_size(gemini_mem));
if (!gemini_base) {
rc = -ENOMEM;
GMN_PR_ERR("%s: ioremap failed\n", __func__);
goto fail1;
}
rc = msm_camio_jpeg_clk_enable();
if (rc) {
GMN_PR_ERR("%s: clk failed rc = %d\n", __func__, rc);
goto fail2;
}
msm_gemini_hw_init(gemini_base, resource_size(gemini_mem));
rc = request_irq(gemini_irq, handler, IRQF_TRIGGER_RISING, "gemini",
context);
if (rc) {
GMN_PR_ERR("%s: request_irq failed, %d, JPEG = %d\n", __func__,
gemini_irq, INT_JPEG);
goto fail3;
}
*mem = gemini_mem;
*base = gemini_base;
*irq = gemini_irq;
GMN_DBG("%s:%d] success\n", __func__, __LINE__);
return rc;
fail3:
msm_camio_jpeg_clk_disable();
fail2:
iounmap(gemini_base);
fail1:
release_mem_region(gemini_mem->start, resource_size(gemini_mem));
GMN_DBG("%s:%d] fail\n", __func__, __LINE__);
return rc;
}
int msm_gemini_platform_release(struct resource *mem, void *base, int irq,
void *context)
{
int result;
free_irq(irq, context);
result = msm_camio_jpeg_clk_disable();
iounmap(base);
release_mem_region(mem->start, resource_size(mem));
GMN_DBG("%s:%d] success\n", __func__, __LINE__);
return result;
}
| gpl-2.0 |
einon/staging-et131x | arch/blackfin/kernel/signal.c | 460 | 7132 | /*
* Copyright 2004-2010 Analog Devices Inc.
*
* Licensed under the GPL-2 or later
*/
#include <linux/signal.h>
#include <linux/syscalls.h>
#include <linux/ptrace.h>
#include <linux/tty.h>
#include <linux/personality.h>
#include <linux/binfmts.h>
#include <linux/uaccess.h>
#include <linux/tracehook.h>
#include <asm/cacheflush.h>
#include <asm/ucontext.h>
#include <asm/fixed_code.h>
#include <asm/syscall.h>
/* Location of the trace bit in SYSCFG. */
#define TRACE_BITS 0x0001
struct fdpic_func_descriptor {
unsigned long text;
unsigned long GOT;
};
struct rt_sigframe {
int sig;
struct siginfo *pinfo;
void *puc;
/* This is no longer needed by the kernel, but unfortunately userspace
* code expects it to be there. */
char retcode[8];
struct siginfo info;
struct ucontext uc;
};
static inline int
rt_restore_sigcontext(struct pt_regs *regs, struct sigcontext __user *sc, int *pr0)
{
unsigned long usp = 0;
int err = 0;
/* Always make any pending restarted system calls return -EINTR */
current_thread_info()->restart_block.fn = do_no_restart_syscall;
#define RESTORE(x) err |= __get_user(regs->x, &sc->sc_##x)
/* restore passed registers */
RESTORE(r0); RESTORE(r1); RESTORE(r2); RESTORE(r3);
RESTORE(r4); RESTORE(r5); RESTORE(r6); RESTORE(r7);
RESTORE(p0); RESTORE(p1); RESTORE(p2); RESTORE(p3);
RESTORE(p4); RESTORE(p5);
err |= __get_user(usp, &sc->sc_usp);
wrusp(usp);
RESTORE(a0w); RESTORE(a1w);
RESTORE(a0x); RESTORE(a1x);
RESTORE(astat);
RESTORE(rets);
RESTORE(pc);
RESTORE(retx);
RESTORE(fp);
RESTORE(i0); RESTORE(i1); RESTORE(i2); RESTORE(i3);
RESTORE(m0); RESTORE(m1); RESTORE(m2); RESTORE(m3);
RESTORE(l0); RESTORE(l1); RESTORE(l2); RESTORE(l3);
RESTORE(b0); RESTORE(b1); RESTORE(b2); RESTORE(b3);
RESTORE(lc0); RESTORE(lc1);
RESTORE(lt0); RESTORE(lt1);
RESTORE(lb0); RESTORE(lb1);
RESTORE(seqstat);
regs->orig_p0 = -1; /* disable syscall checks */
*pr0 = regs->r0;
return err;
}
asmlinkage int sys_rt_sigreturn(void)
{
struct pt_regs *regs = current_pt_regs();
unsigned long usp = rdusp();
struct rt_sigframe *frame = (struct rt_sigframe *)(usp);
sigset_t set;
int r0;
if (!access_ok(VERIFY_READ, frame, sizeof(*frame)))
goto badframe;
if (__copy_from_user(&set, &frame->uc.uc_sigmask, sizeof(set)))
goto badframe;
set_current_blocked(&set);
if (rt_restore_sigcontext(regs, &frame->uc.uc_mcontext, &r0))
goto badframe;
if (restore_altstack(&frame->uc.uc_stack))
goto badframe;
return r0;
badframe:
force_sig(SIGSEGV, current);
return 0;
}
static inline int rt_setup_sigcontext(struct sigcontext *sc, struct pt_regs *regs)
{
int err = 0;
#define SETUP(x) err |= __put_user(regs->x, &sc->sc_##x)
SETUP(r0); SETUP(r1); SETUP(r2); SETUP(r3);
SETUP(r4); SETUP(r5); SETUP(r6); SETUP(r7);
SETUP(p0); SETUP(p1); SETUP(p2); SETUP(p3);
SETUP(p4); SETUP(p5);
err |= __put_user(rdusp(), &sc->sc_usp);
SETUP(a0w); SETUP(a1w);
SETUP(a0x); SETUP(a1x);
SETUP(astat);
SETUP(rets);
SETUP(pc);
SETUP(retx);
SETUP(fp);
SETUP(i0); SETUP(i1); SETUP(i2); SETUP(i3);
SETUP(m0); SETUP(m1); SETUP(m2); SETUP(m3);
SETUP(l0); SETUP(l1); SETUP(l2); SETUP(l3);
SETUP(b0); SETUP(b1); SETUP(b2); SETUP(b3);
SETUP(lc0); SETUP(lc1);
SETUP(lt0); SETUP(lt1);
SETUP(lb0); SETUP(lb1);
SETUP(seqstat);
return err;
}
static inline void *get_sigframe(struct ksignal *ksig,
size_t frame_size)
{
unsigned long usp = sigsp(rdusp(), ksig);
return (void *)((usp - frame_size) & -8UL);
}
static int
setup_rt_frame(struct ksignal *ksig, sigset_t *set, struct pt_regs *regs)
{
struct rt_sigframe *frame;
int err = 0;
frame = get_sigframe(ksig, sizeof(*frame));
err |= __put_user((current_thread_info()->exec_domain
&& current_thread_info()->exec_domain->signal_invmap
&& ksig->sig < 32
? current_thread_info()->exec_domain->
signal_invmap[ksig->sig] : ksig->sig), &frame->sig);
err |= __put_user(&frame->info, &frame->pinfo);
err |= __put_user(&frame->uc, &frame->puc);
err |= copy_siginfo_to_user(&frame->info, &ksig->info);
/* Create the ucontext. */
err |= __put_user(0, &frame->uc.uc_flags);
err |= __put_user(0, &frame->uc.uc_link);
err |= __save_altstack(&frame->uc.uc_stack, rdusp());
err |= rt_setup_sigcontext(&frame->uc.uc_mcontext, regs);
err |= copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set));
if (err)
return -EFAULT;
/* Set up registers for signal handler */
if (current->personality & FDPIC_FUNCPTRS) {
struct fdpic_func_descriptor __user *funcptr =
(struct fdpic_func_descriptor *) ksig->ka.sa.sa_handler;
u32 pc, p3;
err |= __get_user(pc, &funcptr->text);
err |= __get_user(p3, &funcptr->GOT);
if (err)
return -EFAULT;
regs->pc = pc;
regs->p3 = p3;
} else
regs->pc = (unsigned long)ksig->ka.sa.sa_handler;
wrusp((unsigned long)frame);
regs->rets = SIGRETURN_STUB;
regs->r0 = frame->sig;
regs->r1 = (unsigned long)(&frame->info);
regs->r2 = (unsigned long)(&frame->uc);
return 0;
}
static inline void
handle_restart(struct pt_regs *regs, struct k_sigaction *ka, int has_handler)
{
switch (regs->r0) {
case -ERESTARTNOHAND:
if (!has_handler)
goto do_restart;
regs->r0 = -EINTR;
break;
case -ERESTARTSYS:
if (has_handler && !(ka->sa.sa_flags & SA_RESTART)) {
regs->r0 = -EINTR;
break;
}
/* fallthrough */
case -ERESTARTNOINTR:
do_restart:
regs->p0 = regs->orig_p0;
regs->r0 = regs->orig_r0;
regs->pc -= 2;
break;
case -ERESTART_RESTARTBLOCK:
regs->p0 = __NR_restart_syscall;
regs->pc -= 2;
break;
}
}
/*
* OK, we're invoking a handler
*/
static void
handle_signal(struct ksignal *ksig, struct pt_regs *regs)
{
int ret;
/* are we from a system call? to see pt_regs->orig_p0 */
if (regs->orig_p0 >= 0)
/* If so, check system call restarting.. */
handle_restart(regs, &ksig->ka, 1);
/* set up the stack frame */
ret = setup_rt_frame(ksig, sigmask_to_save(), regs);
signal_setup_done(ret, ksig, test_thread_flag(TIF_SINGLESTEP));
}
/*
* Note that 'init' is a special process: it doesn't get signals it doesn't
* want to handle. Thus you cannot kill init even with a SIGKILL even by
* mistake.
*
* Note that we go through the signals twice: once to check the signals
* that the kernel can handle, and then we build all the user-level signal
* handling stack-frames in one go after that.
*/
asmlinkage void do_signal(struct pt_regs *regs)
{
struct ksignal ksig;
current->thread.esp0 = (unsigned long)regs;
if (get_signal(&ksig)) {
/* Whee! Actually deliver the signal. */
handle_signal(&ksig, regs);
return;
}
/* Did we come from a system call? */
if (regs->orig_p0 >= 0)
/* Restart the system call - no handlers present */
handle_restart(regs, NULL, 0);
/* if there's no signal to deliver, we just put the saved sigmask
* back */
restore_saved_sigmask();
}
/*
* notification of userspace execution resumption
*/
asmlinkage void do_notify_resume(struct pt_regs *regs)
{
if (test_thread_flag(TIF_SIGPENDING))
do_signal(regs);
if (test_thread_flag(TIF_NOTIFY_RESUME)) {
clear_thread_flag(TIF_NOTIFY_RESUME);
tracehook_notify_resume(regs);
}
}
| gpl-2.0 |
HinTak/linux | drivers/net/ethernet/cavium/common/cavium_ptp.c | 460 | 8944 | // SPDX-License-Identifier: GPL-2.0
/* cavium_ptp.c - PTP 1588 clock on Cavium hardware
* Copyright (c) 2003-2015, 2017 Cavium, Inc.
*/
#include <linux/device.h>
#include <linux/module.h>
#include <linux/timecounter.h>
#include <linux/pci.h>
#include "cavium_ptp.h"
#define DRV_NAME "cavium_ptp"
#define PCI_DEVICE_ID_CAVIUM_PTP 0xA00C
#define PCI_SUBSYS_DEVID_88XX_PTP 0xA10C
#define PCI_SUBSYS_DEVID_81XX_PTP 0XA20C
#define PCI_SUBSYS_DEVID_83XX_PTP 0xA30C
#define PCI_DEVICE_ID_CAVIUM_RST 0xA00E
#define PCI_PTP_BAR_NO 0
#define PCI_RST_BAR_NO 0
#define PTP_CLOCK_CFG 0xF00ULL
#define PTP_CLOCK_CFG_PTP_EN BIT(0)
#define PTP_CLOCK_LO 0xF08ULL
#define PTP_CLOCK_HI 0xF10ULL
#define PTP_CLOCK_COMP 0xF18ULL
#define RST_BOOT 0x1600ULL
#define CLOCK_BASE_RATE 50000000ULL
static u64 ptp_cavium_clock_get(void)
{
struct pci_dev *pdev;
void __iomem *base;
u64 ret = CLOCK_BASE_RATE * 16;
pdev = pci_get_device(PCI_VENDOR_ID_CAVIUM,
PCI_DEVICE_ID_CAVIUM_RST, NULL);
if (!pdev)
goto error;
base = pci_ioremap_bar(pdev, PCI_RST_BAR_NO);
if (!base)
goto error_put_pdev;
ret = CLOCK_BASE_RATE * ((readq(base + RST_BOOT) >> 33) & 0x3f);
iounmap(base);
error_put_pdev:
pci_dev_put(pdev);
error:
return ret;
}
struct cavium_ptp *cavium_ptp_get(void)
{
struct cavium_ptp *ptp;
struct pci_dev *pdev;
pdev = pci_get_device(PCI_VENDOR_ID_CAVIUM,
PCI_DEVICE_ID_CAVIUM_PTP, NULL);
if (!pdev)
return ERR_PTR(-ENODEV);
ptp = pci_get_drvdata(pdev);
if (!ptp)
ptp = ERR_PTR(-EPROBE_DEFER);
if (IS_ERR(ptp))
pci_dev_put(pdev);
return ptp;
}
EXPORT_SYMBOL(cavium_ptp_get);
void cavium_ptp_put(struct cavium_ptp *ptp)
{
if (!ptp)
return;
pci_dev_put(ptp->pdev);
}
EXPORT_SYMBOL(cavium_ptp_put);
/**
* cavium_ptp_adjfine() - Adjust ptp frequency
* @ptp_info: PTP clock info
* @scaled_ppm: how much to adjust by, in parts per million, but with a
* 16 bit binary fractional field
*/
static int cavium_ptp_adjfine(struct ptp_clock_info *ptp_info, long scaled_ppm)
{
struct cavium_ptp *clock =
container_of(ptp_info, struct cavium_ptp, ptp_info);
unsigned long flags;
u64 comp;
u64 adj;
bool neg_adj = false;
if (scaled_ppm < 0) {
neg_adj = true;
scaled_ppm = -scaled_ppm;
}
/* The hardware adds the clock compensation value to the PTP clock
* on every coprocessor clock cycle. Typical convention is that it
* represent number of nanosecond betwen each cycle. In this
* convention compensation value is in 64 bit fixed-point
* representation where upper 32 bits are number of nanoseconds
* and lower is fractions of nanosecond.
* The scaled_ppm represent the ratio in "parts per bilion" by which the
* compensation value should be corrected.
* To calculate new compenstation value we use 64bit fixed point
* arithmetic on following formula
* comp = tbase + tbase * scaled_ppm / (1M * 2^16)
* where tbase is the basic compensation value calculated initialy
* in cavium_ptp_init() -> tbase = 1/Hz. Then we use endian
* independent structure definition to write data to PTP register.
*/
comp = ((u64)1000000000ull << 32) / clock->clock_rate;
adj = comp * scaled_ppm;
adj >>= 16;
adj = div_u64(adj, 1000000ull);
comp = neg_adj ? comp - adj : comp + adj;
spin_lock_irqsave(&clock->spin_lock, flags);
writeq(comp, clock->reg_base + PTP_CLOCK_COMP);
spin_unlock_irqrestore(&clock->spin_lock, flags);
return 0;
}
/**
* cavium_ptp_adjtime() - Adjust ptp time
* @ptp_info: PTP clock info
* @delta: how much to adjust by, in nanosecs
*/
static int cavium_ptp_adjtime(struct ptp_clock_info *ptp_info, s64 delta)
{
struct cavium_ptp *clock =
container_of(ptp_info, struct cavium_ptp, ptp_info);
unsigned long flags;
spin_lock_irqsave(&clock->spin_lock, flags);
timecounter_adjtime(&clock->time_counter, delta);
spin_unlock_irqrestore(&clock->spin_lock, flags);
/* Sync, for network driver to get latest value */
smp_mb();
return 0;
}
/**
* cavium_ptp_gettime() - Get hardware clock time with adjustment
* @ptp_info: PTP clock info
* @ts: timespec
*/
static int cavium_ptp_gettime(struct ptp_clock_info *ptp_info,
struct timespec64 *ts)
{
struct cavium_ptp *clock =
container_of(ptp_info, struct cavium_ptp, ptp_info);
unsigned long flags;
u64 nsec;
spin_lock_irqsave(&clock->spin_lock, flags);
nsec = timecounter_read(&clock->time_counter);
spin_unlock_irqrestore(&clock->spin_lock, flags);
*ts = ns_to_timespec64(nsec);
return 0;
}
/**
* cavium_ptp_settime() - Set hardware clock time. Reset adjustment
* @ptp_info: PTP clock info
* @ts: timespec
*/
static int cavium_ptp_settime(struct ptp_clock_info *ptp_info,
const struct timespec64 *ts)
{
struct cavium_ptp *clock =
container_of(ptp_info, struct cavium_ptp, ptp_info);
unsigned long flags;
u64 nsec;
nsec = timespec64_to_ns(ts);
spin_lock_irqsave(&clock->spin_lock, flags);
timecounter_init(&clock->time_counter, &clock->cycle_counter, nsec);
spin_unlock_irqrestore(&clock->spin_lock, flags);
return 0;
}
/**
* cavium_ptp_enable() - Request to enable or disable an ancillary feature.
* @ptp_info: PTP clock info
* @rq: request
* @on: is it on
*/
static int cavium_ptp_enable(struct ptp_clock_info *ptp_info,
struct ptp_clock_request *rq, int on)
{
return -EOPNOTSUPP;
}
static u64 cavium_ptp_cc_read(const struct cyclecounter *cc)
{
struct cavium_ptp *clock =
container_of(cc, struct cavium_ptp, cycle_counter);
return readq(clock->reg_base + PTP_CLOCK_HI);
}
static int cavium_ptp_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct device *dev = &pdev->dev;
struct cavium_ptp *clock;
struct cyclecounter *cc;
u64 clock_cfg;
u64 clock_comp;
int err;
clock = devm_kzalloc(dev, sizeof(*clock), GFP_KERNEL);
if (!clock) {
err = -ENOMEM;
goto error;
}
clock->pdev = pdev;
err = pcim_enable_device(pdev);
if (err)
goto error_free;
err = pcim_iomap_regions(pdev, 1 << PCI_PTP_BAR_NO, pci_name(pdev));
if (err)
goto error_free;
clock->reg_base = pcim_iomap_table(pdev)[PCI_PTP_BAR_NO];
spin_lock_init(&clock->spin_lock);
cc = &clock->cycle_counter;
cc->read = cavium_ptp_cc_read;
cc->mask = CYCLECOUNTER_MASK(64);
cc->mult = 1;
cc->shift = 0;
timecounter_init(&clock->time_counter, &clock->cycle_counter,
ktime_to_ns(ktime_get_real()));
clock->clock_rate = ptp_cavium_clock_get();
clock->ptp_info = (struct ptp_clock_info) {
.owner = THIS_MODULE,
.name = "ThunderX PTP",
.max_adj = 1000000000ull,
.n_ext_ts = 0,
.n_pins = 0,
.pps = 0,
.adjfine = cavium_ptp_adjfine,
.adjtime = cavium_ptp_adjtime,
.gettime64 = cavium_ptp_gettime,
.settime64 = cavium_ptp_settime,
.enable = cavium_ptp_enable,
};
clock_cfg = readq(clock->reg_base + PTP_CLOCK_CFG);
clock_cfg |= PTP_CLOCK_CFG_PTP_EN;
writeq(clock_cfg, clock->reg_base + PTP_CLOCK_CFG);
clock_comp = ((u64)1000000000ull << 32) / clock->clock_rate;
writeq(clock_comp, clock->reg_base + PTP_CLOCK_COMP);
clock->ptp_clock = ptp_clock_register(&clock->ptp_info, dev);
if (IS_ERR(clock->ptp_clock)) {
err = PTR_ERR(clock->ptp_clock);
goto error_stop;
}
pci_set_drvdata(pdev, clock);
return 0;
error_stop:
clock_cfg = readq(clock->reg_base + PTP_CLOCK_CFG);
clock_cfg &= ~PTP_CLOCK_CFG_PTP_EN;
writeq(clock_cfg, clock->reg_base + PTP_CLOCK_CFG);
pcim_iounmap_regions(pdev, 1 << PCI_PTP_BAR_NO);
error_free:
devm_kfree(dev, clock);
error:
/* For `cavium_ptp_get()` we need to differentiate between the case
* when the core has not tried to probe this device and the case when
* the probe failed. In the later case we pretend that the
* initialization was successful and keep the error in
* `dev->driver_data`.
*/
pci_set_drvdata(pdev, ERR_PTR(err));
return 0;
}
static void cavium_ptp_remove(struct pci_dev *pdev)
{
struct cavium_ptp *clock = pci_get_drvdata(pdev);
u64 clock_cfg;
if (IS_ERR_OR_NULL(clock))
return;
ptp_clock_unregister(clock->ptp_clock);
clock_cfg = readq(clock->reg_base + PTP_CLOCK_CFG);
clock_cfg &= ~PTP_CLOCK_CFG_PTP_EN;
writeq(clock_cfg, clock->reg_base + PTP_CLOCK_CFG);
}
static const struct pci_device_id cavium_ptp_id_table[] = {
{ PCI_DEVICE_SUB(PCI_VENDOR_ID_CAVIUM, PCI_DEVICE_ID_CAVIUM_PTP,
PCI_VENDOR_ID_CAVIUM, PCI_SUBSYS_DEVID_88XX_PTP) },
{ PCI_DEVICE_SUB(PCI_VENDOR_ID_CAVIUM, PCI_DEVICE_ID_CAVIUM_PTP,
PCI_VENDOR_ID_CAVIUM, PCI_SUBSYS_DEVID_81XX_PTP) },
{ PCI_DEVICE_SUB(PCI_VENDOR_ID_CAVIUM, PCI_DEVICE_ID_CAVIUM_PTP,
PCI_VENDOR_ID_CAVIUM, PCI_SUBSYS_DEVID_83XX_PTP) },
{ 0, }
};
static struct pci_driver cavium_ptp_driver = {
.name = DRV_NAME,
.id_table = cavium_ptp_id_table,
.probe = cavium_ptp_probe,
.remove = cavium_ptp_remove,
};
module_pci_driver(cavium_ptp_driver);
MODULE_DESCRIPTION(DRV_NAME);
MODULE_AUTHOR("Cavium Networks <support@cavium.com>");
MODULE_LICENSE("GPL v2");
MODULE_DEVICE_TABLE(pci, cavium_ptp_id_table);
| gpl-2.0 |
vbatts/linux | drivers/dma/mxs-dma.c | 716 | 24215 | /*
* Copyright 2011 Freescale Semiconductor, Inc. All Rights Reserved.
*
* Refer to drivers/dma/imx-sdma.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/init.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/clk.h>
#include <linux/wait.h>
#include <linux/sched.h>
#include <linux/semaphore.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/dmaengine.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/stmp_device.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/of_dma.h>
#include <linux/list.h>
#include <asm/irq.h>
#include "dmaengine.h"
/*
* NOTE: The term "PIO" throughout the mxs-dma implementation means
* PIO mode of mxs apbh-dma and apbx-dma. With this working mode,
* dma can program the controller registers of peripheral devices.
*/
#define dma_is_apbh(mxs_dma) ((mxs_dma)->type == MXS_DMA_APBH)
#define apbh_is_old(mxs_dma) ((mxs_dma)->dev_id == IMX23_DMA)
#define HW_APBHX_CTRL0 0x000
#define BM_APBH_CTRL0_APB_BURST8_EN (1 << 29)
#define BM_APBH_CTRL0_APB_BURST_EN (1 << 28)
#define BP_APBH_CTRL0_RESET_CHANNEL 16
#define HW_APBHX_CTRL1 0x010
#define HW_APBHX_CTRL2 0x020
#define HW_APBHX_CHANNEL_CTRL 0x030
#define BP_APBHX_CHANNEL_CTRL_RESET_CHANNEL 16
/*
* The offset of NXTCMDAR register is different per both dma type and version,
* while stride for each channel is all the same 0x70.
*/
#define HW_APBHX_CHn_NXTCMDAR(d, n) \
(((dma_is_apbh(d) && apbh_is_old(d)) ? 0x050 : 0x110) + (n) * 0x70)
#define HW_APBHX_CHn_SEMA(d, n) \
(((dma_is_apbh(d) && apbh_is_old(d)) ? 0x080 : 0x140) + (n) * 0x70)
#define HW_APBHX_CHn_BAR(d, n) \
(((dma_is_apbh(d) && apbh_is_old(d)) ? 0x070 : 0x130) + (n) * 0x70)
#define HW_APBX_CHn_DEBUG1(d, n) (0x150 + (n) * 0x70)
/*
* ccw bits definitions
*
* COMMAND: 0..1 (2)
* CHAIN: 2 (1)
* IRQ: 3 (1)
* NAND_LOCK: 4 (1) - not implemented
* NAND_WAIT4READY: 5 (1) - not implemented
* DEC_SEM: 6 (1)
* WAIT4END: 7 (1)
* HALT_ON_TERMINATE: 8 (1)
* TERMINATE_FLUSH: 9 (1)
* RESERVED: 10..11 (2)
* PIO_NUM: 12..15 (4)
*/
#define BP_CCW_COMMAND 0
#define BM_CCW_COMMAND (3 << 0)
#define CCW_CHAIN (1 << 2)
#define CCW_IRQ (1 << 3)
#define CCW_DEC_SEM (1 << 6)
#define CCW_WAIT4END (1 << 7)
#define CCW_HALT_ON_TERM (1 << 8)
#define CCW_TERM_FLUSH (1 << 9)
#define BP_CCW_PIO_NUM 12
#define BM_CCW_PIO_NUM (0xf << 12)
#define BF_CCW(value, field) (((value) << BP_CCW_##field) & BM_CCW_##field)
#define MXS_DMA_CMD_NO_XFER 0
#define MXS_DMA_CMD_WRITE 1
#define MXS_DMA_CMD_READ 2
#define MXS_DMA_CMD_DMA_SENSE 3 /* not implemented */
struct mxs_dma_ccw {
u32 next;
u16 bits;
u16 xfer_bytes;
#define MAX_XFER_BYTES 0xff00
u32 bufaddr;
#define MXS_PIO_WORDS 16
u32 pio_words[MXS_PIO_WORDS];
};
#define CCW_BLOCK_SIZE (4 * PAGE_SIZE)
#define NUM_CCW (int)(CCW_BLOCK_SIZE / sizeof(struct mxs_dma_ccw))
struct mxs_dma_chan {
struct mxs_dma_engine *mxs_dma;
struct dma_chan chan;
struct dma_async_tx_descriptor desc;
struct tasklet_struct tasklet;
unsigned int chan_irq;
struct mxs_dma_ccw *ccw;
dma_addr_t ccw_phys;
int desc_count;
enum dma_status status;
unsigned int flags;
bool reset;
#define MXS_DMA_SG_LOOP (1 << 0)
#define MXS_DMA_USE_SEMAPHORE (1 << 1)
};
#define MXS_DMA_CHANNELS 16
#define MXS_DMA_CHANNELS_MASK 0xffff
enum mxs_dma_devtype {
MXS_DMA_APBH,
MXS_DMA_APBX,
};
enum mxs_dma_id {
IMX23_DMA,
IMX28_DMA,
};
struct mxs_dma_engine {
enum mxs_dma_id dev_id;
enum mxs_dma_devtype type;
void __iomem *base;
struct clk *clk;
struct dma_device dma_device;
struct device_dma_parameters dma_parms;
struct mxs_dma_chan mxs_chans[MXS_DMA_CHANNELS];
struct platform_device *pdev;
unsigned int nr_channels;
};
struct mxs_dma_type {
enum mxs_dma_id id;
enum mxs_dma_devtype type;
};
static struct mxs_dma_type mxs_dma_types[] = {
{
.id = IMX23_DMA,
.type = MXS_DMA_APBH,
}, {
.id = IMX23_DMA,
.type = MXS_DMA_APBX,
}, {
.id = IMX28_DMA,
.type = MXS_DMA_APBH,
}, {
.id = IMX28_DMA,
.type = MXS_DMA_APBX,
}
};
static const struct platform_device_id mxs_dma_ids[] = {
{
.name = "imx23-dma-apbh",
.driver_data = (kernel_ulong_t) &mxs_dma_types[0],
}, {
.name = "imx23-dma-apbx",
.driver_data = (kernel_ulong_t) &mxs_dma_types[1],
}, {
.name = "imx28-dma-apbh",
.driver_data = (kernel_ulong_t) &mxs_dma_types[2],
}, {
.name = "imx28-dma-apbx",
.driver_data = (kernel_ulong_t) &mxs_dma_types[3],
}, {
/* end of list */
}
};
static const struct of_device_id mxs_dma_dt_ids[] = {
{ .compatible = "fsl,imx23-dma-apbh", .data = &mxs_dma_ids[0], },
{ .compatible = "fsl,imx23-dma-apbx", .data = &mxs_dma_ids[1], },
{ .compatible = "fsl,imx28-dma-apbh", .data = &mxs_dma_ids[2], },
{ .compatible = "fsl,imx28-dma-apbx", .data = &mxs_dma_ids[3], },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, mxs_dma_dt_ids);
static struct mxs_dma_chan *to_mxs_dma_chan(struct dma_chan *chan)
{
return container_of(chan, struct mxs_dma_chan, chan);
}
static void mxs_dma_reset_chan(struct dma_chan *chan)
{
struct mxs_dma_chan *mxs_chan = to_mxs_dma_chan(chan);
struct mxs_dma_engine *mxs_dma = mxs_chan->mxs_dma;
int chan_id = mxs_chan->chan.chan_id;
/*
* mxs dma channel resets can cause a channel stall. To recover from a
* channel stall, we have to reset the whole DMA engine. To avoid this,
* we use cyclic DMA with semaphores, that are enhanced in
* mxs_dma_int_handler. To reset the channel, we can simply stop writing
* into the semaphore counter.
*/
if (mxs_chan->flags & MXS_DMA_USE_SEMAPHORE &&
mxs_chan->flags & MXS_DMA_SG_LOOP) {
mxs_chan->reset = true;
} else if (dma_is_apbh(mxs_dma) && apbh_is_old(mxs_dma)) {
writel(1 << (chan_id + BP_APBH_CTRL0_RESET_CHANNEL),
mxs_dma->base + HW_APBHX_CTRL0 + STMP_OFFSET_REG_SET);
} else {
unsigned long elapsed = 0;
const unsigned long max_wait = 50000; /* 50ms */
void __iomem *reg_dbg1 = mxs_dma->base +
HW_APBX_CHn_DEBUG1(mxs_dma, chan_id);
/*
* On i.MX28 APBX, the DMA channel can stop working if we reset
* the channel while it is in READ_FLUSH (0x08) state.
* We wait here until we leave the state. Then we trigger the
* reset. Waiting a maximum of 50ms, the kernel shouldn't crash
* because of this.
*/
while ((readl(reg_dbg1) & 0xf) == 0x8 && elapsed < max_wait) {
udelay(100);
elapsed += 100;
}
if (elapsed >= max_wait)
dev_err(&mxs_chan->mxs_dma->pdev->dev,
"Failed waiting for the DMA channel %d to leave state READ_FLUSH, trying to reset channel in READ_FLUSH state now\n",
chan_id);
writel(1 << (chan_id + BP_APBHX_CHANNEL_CTRL_RESET_CHANNEL),
mxs_dma->base + HW_APBHX_CHANNEL_CTRL + STMP_OFFSET_REG_SET);
}
mxs_chan->status = DMA_COMPLETE;
}
static void mxs_dma_enable_chan(struct dma_chan *chan)
{
struct mxs_dma_chan *mxs_chan = to_mxs_dma_chan(chan);
struct mxs_dma_engine *mxs_dma = mxs_chan->mxs_dma;
int chan_id = mxs_chan->chan.chan_id;
/* set cmd_addr up */
writel(mxs_chan->ccw_phys,
mxs_dma->base + HW_APBHX_CHn_NXTCMDAR(mxs_dma, chan_id));
/* write 1 to SEMA to kick off the channel */
if (mxs_chan->flags & MXS_DMA_USE_SEMAPHORE &&
mxs_chan->flags & MXS_DMA_SG_LOOP) {
/* A cyclic DMA consists of at least 2 segments, so initialize
* the semaphore with 2 so we have enough time to add 1 to the
* semaphore if we need to */
writel(2, mxs_dma->base + HW_APBHX_CHn_SEMA(mxs_dma, chan_id));
} else {
writel(1, mxs_dma->base + HW_APBHX_CHn_SEMA(mxs_dma, chan_id));
}
mxs_chan->reset = false;
}
static void mxs_dma_disable_chan(struct dma_chan *chan)
{
struct mxs_dma_chan *mxs_chan = to_mxs_dma_chan(chan);
mxs_chan->status = DMA_COMPLETE;
}
static int mxs_dma_pause_chan(struct dma_chan *chan)
{
struct mxs_dma_chan *mxs_chan = to_mxs_dma_chan(chan);
struct mxs_dma_engine *mxs_dma = mxs_chan->mxs_dma;
int chan_id = mxs_chan->chan.chan_id;
/* freeze the channel */
if (dma_is_apbh(mxs_dma) && apbh_is_old(mxs_dma))
writel(1 << chan_id,
mxs_dma->base + HW_APBHX_CTRL0 + STMP_OFFSET_REG_SET);
else
writel(1 << chan_id,
mxs_dma->base + HW_APBHX_CHANNEL_CTRL + STMP_OFFSET_REG_SET);
mxs_chan->status = DMA_PAUSED;
return 0;
}
static int mxs_dma_resume_chan(struct dma_chan *chan)
{
struct mxs_dma_chan *mxs_chan = to_mxs_dma_chan(chan);
struct mxs_dma_engine *mxs_dma = mxs_chan->mxs_dma;
int chan_id = mxs_chan->chan.chan_id;
/* unfreeze the channel */
if (dma_is_apbh(mxs_dma) && apbh_is_old(mxs_dma))
writel(1 << chan_id,
mxs_dma->base + HW_APBHX_CTRL0 + STMP_OFFSET_REG_CLR);
else
writel(1 << chan_id,
mxs_dma->base + HW_APBHX_CHANNEL_CTRL + STMP_OFFSET_REG_CLR);
mxs_chan->status = DMA_IN_PROGRESS;
return 0;
}
static dma_cookie_t mxs_dma_tx_submit(struct dma_async_tx_descriptor *tx)
{
return dma_cookie_assign(tx);
}
static void mxs_dma_tasklet(unsigned long data)
{
struct mxs_dma_chan *mxs_chan = (struct mxs_dma_chan *) data;
if (mxs_chan->desc.callback)
mxs_chan->desc.callback(mxs_chan->desc.callback_param);
}
static int mxs_dma_irq_to_chan(struct mxs_dma_engine *mxs_dma, int irq)
{
int i;
for (i = 0; i != mxs_dma->nr_channels; ++i)
if (mxs_dma->mxs_chans[i].chan_irq == irq)
return i;
return -EINVAL;
}
static irqreturn_t mxs_dma_int_handler(int irq, void *dev_id)
{
struct mxs_dma_engine *mxs_dma = dev_id;
struct mxs_dma_chan *mxs_chan;
u32 completed;
u32 err;
int chan = mxs_dma_irq_to_chan(mxs_dma, irq);
if (chan < 0)
return IRQ_NONE;
/* completion status */
completed = readl(mxs_dma->base + HW_APBHX_CTRL1);
completed = (completed >> chan) & 0x1;
/* Clear interrupt */
writel((1 << chan),
mxs_dma->base + HW_APBHX_CTRL1 + STMP_OFFSET_REG_CLR);
/* error status */
err = readl(mxs_dma->base + HW_APBHX_CTRL2);
err &= (1 << (MXS_DMA_CHANNELS + chan)) | (1 << chan);
/*
* error status bit is in the upper 16 bits, error irq bit in the lower
* 16 bits. We transform it into a simpler error code:
* err: 0x00 = no error, 0x01 = TERMINATION, 0x02 = BUS_ERROR
*/
err = (err >> (MXS_DMA_CHANNELS + chan)) + (err >> chan);
/* Clear error irq */
writel((1 << chan),
mxs_dma->base + HW_APBHX_CTRL2 + STMP_OFFSET_REG_CLR);
/*
* When both completion and error of termination bits set at the
* same time, we do not take it as an error. IOW, it only becomes
* an error we need to handle here in case of either it's a bus
* error or a termination error with no completion. 0x01 is termination
* error, so we can subtract err & completed to get the real error case.
*/
err -= err & completed;
mxs_chan = &mxs_dma->mxs_chans[chan];
if (err) {
dev_dbg(mxs_dma->dma_device.dev,
"%s: error in channel %d\n", __func__,
chan);
mxs_chan->status = DMA_ERROR;
mxs_dma_reset_chan(&mxs_chan->chan);
} else if (mxs_chan->status != DMA_COMPLETE) {
if (mxs_chan->flags & MXS_DMA_SG_LOOP) {
mxs_chan->status = DMA_IN_PROGRESS;
if (mxs_chan->flags & MXS_DMA_USE_SEMAPHORE)
writel(1, mxs_dma->base +
HW_APBHX_CHn_SEMA(mxs_dma, chan));
} else {
mxs_chan->status = DMA_COMPLETE;
}
}
if (mxs_chan->status == DMA_COMPLETE) {
if (mxs_chan->reset)
return IRQ_HANDLED;
dma_cookie_complete(&mxs_chan->desc);
}
/* schedule tasklet on this channel */
tasklet_schedule(&mxs_chan->tasklet);
return IRQ_HANDLED;
}
static int mxs_dma_alloc_chan_resources(struct dma_chan *chan)
{
struct mxs_dma_chan *mxs_chan = to_mxs_dma_chan(chan);
struct mxs_dma_engine *mxs_dma = mxs_chan->mxs_dma;
int ret;
mxs_chan->ccw = dma_zalloc_coherent(mxs_dma->dma_device.dev,
CCW_BLOCK_SIZE,
&mxs_chan->ccw_phys, GFP_KERNEL);
if (!mxs_chan->ccw) {
ret = -ENOMEM;
goto err_alloc;
}
if (mxs_chan->chan_irq != NO_IRQ) {
ret = request_irq(mxs_chan->chan_irq, mxs_dma_int_handler,
0, "mxs-dma", mxs_dma);
if (ret)
goto err_irq;
}
ret = clk_prepare_enable(mxs_dma->clk);
if (ret)
goto err_clk;
mxs_dma_reset_chan(chan);
dma_async_tx_descriptor_init(&mxs_chan->desc, chan);
mxs_chan->desc.tx_submit = mxs_dma_tx_submit;
/* the descriptor is ready */
async_tx_ack(&mxs_chan->desc);
return 0;
err_clk:
free_irq(mxs_chan->chan_irq, mxs_dma);
err_irq:
dma_free_coherent(mxs_dma->dma_device.dev, CCW_BLOCK_SIZE,
mxs_chan->ccw, mxs_chan->ccw_phys);
err_alloc:
return ret;
}
static void mxs_dma_free_chan_resources(struct dma_chan *chan)
{
struct mxs_dma_chan *mxs_chan = to_mxs_dma_chan(chan);
struct mxs_dma_engine *mxs_dma = mxs_chan->mxs_dma;
mxs_dma_disable_chan(chan);
free_irq(mxs_chan->chan_irq, mxs_dma);
dma_free_coherent(mxs_dma->dma_device.dev, CCW_BLOCK_SIZE,
mxs_chan->ccw, mxs_chan->ccw_phys);
clk_disable_unprepare(mxs_dma->clk);
}
/*
* How to use the flags for ->device_prep_slave_sg() :
* [1] If there is only one DMA command in the DMA chain, the code should be:
* ......
* ->device_prep_slave_sg(DMA_CTRL_ACK);
* ......
* [2] If there are two DMA commands in the DMA chain, the code should be
* ......
* ->device_prep_slave_sg(0);
* ......
* ->device_prep_slave_sg(DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
* ......
* [3] If there are more than two DMA commands in the DMA chain, the code
* should be:
* ......
* ->device_prep_slave_sg(0); // First
* ......
* ->device_prep_slave_sg(DMA_PREP_INTERRUPT [| DMA_CTRL_ACK]);
* ......
* ->device_prep_slave_sg(DMA_PREP_INTERRUPT | DMA_CTRL_ACK); // Last
* ......
*/
static struct dma_async_tx_descriptor *mxs_dma_prep_slave_sg(
struct dma_chan *chan, struct scatterlist *sgl,
unsigned int sg_len, enum dma_transfer_direction direction,
unsigned long flags, void *context)
{
struct mxs_dma_chan *mxs_chan = to_mxs_dma_chan(chan);
struct mxs_dma_engine *mxs_dma = mxs_chan->mxs_dma;
struct mxs_dma_ccw *ccw;
struct scatterlist *sg;
u32 i, j;
u32 *pio;
bool append = flags & DMA_PREP_INTERRUPT;
int idx = append ? mxs_chan->desc_count : 0;
if (mxs_chan->status == DMA_IN_PROGRESS && !append)
return NULL;
if (sg_len + (append ? idx : 0) > NUM_CCW) {
dev_err(mxs_dma->dma_device.dev,
"maximum number of sg exceeded: %d > %d\n",
sg_len, NUM_CCW);
goto err_out;
}
mxs_chan->status = DMA_IN_PROGRESS;
mxs_chan->flags = 0;
/*
* If the sg is prepared with append flag set, the sg
* will be appended to the last prepared sg.
*/
if (append) {
BUG_ON(idx < 1);
ccw = &mxs_chan->ccw[idx - 1];
ccw->next = mxs_chan->ccw_phys + sizeof(*ccw) * idx;
ccw->bits |= CCW_CHAIN;
ccw->bits &= ~CCW_IRQ;
ccw->bits &= ~CCW_DEC_SEM;
} else {
idx = 0;
}
if (direction == DMA_TRANS_NONE) {
ccw = &mxs_chan->ccw[idx++];
pio = (u32 *) sgl;
for (j = 0; j < sg_len;)
ccw->pio_words[j++] = *pio++;
ccw->bits = 0;
ccw->bits |= CCW_IRQ;
ccw->bits |= CCW_DEC_SEM;
if (flags & DMA_CTRL_ACK)
ccw->bits |= CCW_WAIT4END;
ccw->bits |= CCW_HALT_ON_TERM;
ccw->bits |= CCW_TERM_FLUSH;
ccw->bits |= BF_CCW(sg_len, PIO_NUM);
ccw->bits |= BF_CCW(MXS_DMA_CMD_NO_XFER, COMMAND);
} else {
for_each_sg(sgl, sg, sg_len, i) {
if (sg_dma_len(sg) > MAX_XFER_BYTES) {
dev_err(mxs_dma->dma_device.dev, "maximum bytes for sg entry exceeded: %d > %d\n",
sg_dma_len(sg), MAX_XFER_BYTES);
goto err_out;
}
ccw = &mxs_chan->ccw[idx++];
ccw->next = mxs_chan->ccw_phys + sizeof(*ccw) * idx;
ccw->bufaddr = sg->dma_address;
ccw->xfer_bytes = sg_dma_len(sg);
ccw->bits = 0;
ccw->bits |= CCW_CHAIN;
ccw->bits |= CCW_HALT_ON_TERM;
ccw->bits |= CCW_TERM_FLUSH;
ccw->bits |= BF_CCW(direction == DMA_DEV_TO_MEM ?
MXS_DMA_CMD_WRITE : MXS_DMA_CMD_READ,
COMMAND);
if (i + 1 == sg_len) {
ccw->bits &= ~CCW_CHAIN;
ccw->bits |= CCW_IRQ;
ccw->bits |= CCW_DEC_SEM;
if (flags & DMA_CTRL_ACK)
ccw->bits |= CCW_WAIT4END;
}
}
}
mxs_chan->desc_count = idx;
return &mxs_chan->desc;
err_out:
mxs_chan->status = DMA_ERROR;
return NULL;
}
static struct dma_async_tx_descriptor *mxs_dma_prep_dma_cyclic(
struct dma_chan *chan, dma_addr_t dma_addr, size_t buf_len,
size_t period_len, enum dma_transfer_direction direction,
unsigned long flags)
{
struct mxs_dma_chan *mxs_chan = to_mxs_dma_chan(chan);
struct mxs_dma_engine *mxs_dma = mxs_chan->mxs_dma;
u32 num_periods = buf_len / period_len;
u32 i = 0, buf = 0;
if (mxs_chan->status == DMA_IN_PROGRESS)
return NULL;
mxs_chan->status = DMA_IN_PROGRESS;
mxs_chan->flags |= MXS_DMA_SG_LOOP;
mxs_chan->flags |= MXS_DMA_USE_SEMAPHORE;
if (num_periods > NUM_CCW) {
dev_err(mxs_dma->dma_device.dev,
"maximum number of sg exceeded: %d > %d\n",
num_periods, NUM_CCW);
goto err_out;
}
if (period_len > MAX_XFER_BYTES) {
dev_err(mxs_dma->dma_device.dev,
"maximum period size exceeded: %d > %d\n",
period_len, MAX_XFER_BYTES);
goto err_out;
}
while (buf < buf_len) {
struct mxs_dma_ccw *ccw = &mxs_chan->ccw[i];
if (i + 1 == num_periods)
ccw->next = mxs_chan->ccw_phys;
else
ccw->next = mxs_chan->ccw_phys + sizeof(*ccw) * (i + 1);
ccw->bufaddr = dma_addr;
ccw->xfer_bytes = period_len;
ccw->bits = 0;
ccw->bits |= CCW_CHAIN;
ccw->bits |= CCW_IRQ;
ccw->bits |= CCW_HALT_ON_TERM;
ccw->bits |= CCW_TERM_FLUSH;
ccw->bits |= CCW_DEC_SEM;
ccw->bits |= BF_CCW(direction == DMA_DEV_TO_MEM ?
MXS_DMA_CMD_WRITE : MXS_DMA_CMD_READ, COMMAND);
dma_addr += period_len;
buf += period_len;
i++;
}
mxs_chan->desc_count = i;
return &mxs_chan->desc;
err_out:
mxs_chan->status = DMA_ERROR;
return NULL;
}
static int mxs_dma_terminate_all(struct dma_chan *chan)
{
mxs_dma_reset_chan(chan);
mxs_dma_disable_chan(chan);
return 0;
}
static enum dma_status mxs_dma_tx_status(struct dma_chan *chan,
dma_cookie_t cookie, struct dma_tx_state *txstate)
{
struct mxs_dma_chan *mxs_chan = to_mxs_dma_chan(chan);
struct mxs_dma_engine *mxs_dma = mxs_chan->mxs_dma;
u32 residue = 0;
if (mxs_chan->status == DMA_IN_PROGRESS &&
mxs_chan->flags & MXS_DMA_SG_LOOP) {
struct mxs_dma_ccw *last_ccw;
u32 bar;
last_ccw = &mxs_chan->ccw[mxs_chan->desc_count - 1];
residue = last_ccw->xfer_bytes + last_ccw->bufaddr;
bar = readl(mxs_dma->base +
HW_APBHX_CHn_BAR(mxs_dma, chan->chan_id));
residue -= bar;
}
dma_set_tx_state(txstate, chan->completed_cookie, chan->cookie,
residue);
return mxs_chan->status;
}
static int __init mxs_dma_init(struct mxs_dma_engine *mxs_dma)
{
int ret;
ret = clk_prepare_enable(mxs_dma->clk);
if (ret)
return ret;
ret = stmp_reset_block(mxs_dma->base);
if (ret)
goto err_out;
/* enable apbh burst */
if (dma_is_apbh(mxs_dma)) {
writel(BM_APBH_CTRL0_APB_BURST_EN,
mxs_dma->base + HW_APBHX_CTRL0 + STMP_OFFSET_REG_SET);
writel(BM_APBH_CTRL0_APB_BURST8_EN,
mxs_dma->base + HW_APBHX_CTRL0 + STMP_OFFSET_REG_SET);
}
/* enable irq for all the channels */
writel(MXS_DMA_CHANNELS_MASK << MXS_DMA_CHANNELS,
mxs_dma->base + HW_APBHX_CTRL1 + STMP_OFFSET_REG_SET);
err_out:
clk_disable_unprepare(mxs_dma->clk);
return ret;
}
struct mxs_dma_filter_param {
struct device_node *of_node;
unsigned int chan_id;
};
static bool mxs_dma_filter_fn(struct dma_chan *chan, void *fn_param)
{
struct mxs_dma_filter_param *param = fn_param;
struct mxs_dma_chan *mxs_chan = to_mxs_dma_chan(chan);
struct mxs_dma_engine *mxs_dma = mxs_chan->mxs_dma;
int chan_irq;
if (mxs_dma->dma_device.dev->of_node != param->of_node)
return false;
if (chan->chan_id != param->chan_id)
return false;
chan_irq = platform_get_irq(mxs_dma->pdev, param->chan_id);
if (chan_irq < 0)
return false;
mxs_chan->chan_irq = chan_irq;
return true;
}
static struct dma_chan *mxs_dma_xlate(struct of_phandle_args *dma_spec,
struct of_dma *ofdma)
{
struct mxs_dma_engine *mxs_dma = ofdma->of_dma_data;
dma_cap_mask_t mask = mxs_dma->dma_device.cap_mask;
struct mxs_dma_filter_param param;
if (dma_spec->args_count != 1)
return NULL;
param.of_node = ofdma->of_node;
param.chan_id = dma_spec->args[0];
if (param.chan_id >= mxs_dma->nr_channels)
return NULL;
return dma_request_channel(mask, mxs_dma_filter_fn, ¶m);
}
static int __init mxs_dma_probe(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
const struct platform_device_id *id_entry;
const struct of_device_id *of_id;
const struct mxs_dma_type *dma_type;
struct mxs_dma_engine *mxs_dma;
struct resource *iores;
int ret, i;
mxs_dma = devm_kzalloc(&pdev->dev, sizeof(*mxs_dma), GFP_KERNEL);
if (!mxs_dma)
return -ENOMEM;
ret = of_property_read_u32(np, "dma-channels", &mxs_dma->nr_channels);
if (ret) {
dev_err(&pdev->dev, "failed to read dma-channels\n");
return ret;
}
of_id = of_match_device(mxs_dma_dt_ids, &pdev->dev);
if (of_id)
id_entry = of_id->data;
else
id_entry = platform_get_device_id(pdev);
dma_type = (struct mxs_dma_type *)id_entry->driver_data;
mxs_dma->type = dma_type->type;
mxs_dma->dev_id = dma_type->id;
iores = platform_get_resource(pdev, IORESOURCE_MEM, 0);
mxs_dma->base = devm_ioremap_resource(&pdev->dev, iores);
if (IS_ERR(mxs_dma->base))
return PTR_ERR(mxs_dma->base);
mxs_dma->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(mxs_dma->clk))
return PTR_ERR(mxs_dma->clk);
dma_cap_set(DMA_SLAVE, mxs_dma->dma_device.cap_mask);
dma_cap_set(DMA_CYCLIC, mxs_dma->dma_device.cap_mask);
INIT_LIST_HEAD(&mxs_dma->dma_device.channels);
/* Initialize channel parameters */
for (i = 0; i < MXS_DMA_CHANNELS; i++) {
struct mxs_dma_chan *mxs_chan = &mxs_dma->mxs_chans[i];
mxs_chan->mxs_dma = mxs_dma;
mxs_chan->chan.device = &mxs_dma->dma_device;
dma_cookie_init(&mxs_chan->chan);
tasklet_init(&mxs_chan->tasklet, mxs_dma_tasklet,
(unsigned long) mxs_chan);
/* Add the channel to mxs_chan list */
list_add_tail(&mxs_chan->chan.device_node,
&mxs_dma->dma_device.channels);
}
ret = mxs_dma_init(mxs_dma);
if (ret)
return ret;
mxs_dma->pdev = pdev;
mxs_dma->dma_device.dev = &pdev->dev;
/* mxs_dma gets 65535 bytes maximum sg size */
mxs_dma->dma_device.dev->dma_parms = &mxs_dma->dma_parms;
dma_set_max_seg_size(mxs_dma->dma_device.dev, MAX_XFER_BYTES);
mxs_dma->dma_device.device_alloc_chan_resources = mxs_dma_alloc_chan_resources;
mxs_dma->dma_device.device_free_chan_resources = mxs_dma_free_chan_resources;
mxs_dma->dma_device.device_tx_status = mxs_dma_tx_status;
mxs_dma->dma_device.device_prep_slave_sg = mxs_dma_prep_slave_sg;
mxs_dma->dma_device.device_prep_dma_cyclic = mxs_dma_prep_dma_cyclic;
mxs_dma->dma_device.device_pause = mxs_dma_pause_chan;
mxs_dma->dma_device.device_resume = mxs_dma_resume_chan;
mxs_dma->dma_device.device_terminate_all = mxs_dma_terminate_all;
mxs_dma->dma_device.src_addr_widths = BIT(DMA_SLAVE_BUSWIDTH_4_BYTES);
mxs_dma->dma_device.dst_addr_widths = BIT(DMA_SLAVE_BUSWIDTH_4_BYTES);
mxs_dma->dma_device.directions = BIT(DMA_DEV_TO_MEM) | BIT(DMA_MEM_TO_DEV);
mxs_dma->dma_device.residue_granularity = DMA_RESIDUE_GRANULARITY_BURST;
mxs_dma->dma_device.device_issue_pending = mxs_dma_enable_chan;
ret = dma_async_device_register(&mxs_dma->dma_device);
if (ret) {
dev_err(mxs_dma->dma_device.dev, "unable to register\n");
return ret;
}
ret = of_dma_controller_register(np, mxs_dma_xlate, mxs_dma);
if (ret) {
dev_err(mxs_dma->dma_device.dev,
"failed to register controller\n");
dma_async_device_unregister(&mxs_dma->dma_device);
}
dev_info(mxs_dma->dma_device.dev, "initialized\n");
return 0;
}
static struct platform_driver mxs_dma_driver = {
.driver = {
.name = "mxs-dma",
.of_match_table = mxs_dma_dt_ids,
},
.id_table = mxs_dma_ids,
};
static int __init mxs_dma_module_init(void)
{
return platform_driver_probe(&mxs_dma_driver, mxs_dma_probe);
}
subsys_initcall(mxs_dma_module_init);
| gpl-2.0 |
KainXS/android_kernel_huawei_y301a2 | arch/arm/mach-msm/devices-msm7x25.c | 1996 | 24132 | /*
* Copyright (C) 2008 Google, Inc.
* Copyright (c) 2008-2012, 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 <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <asm/clkdev.h>
#include <mach/irqs.h>
#include <mach/msm_iomap.h>
#include <mach/dma.h>
#include <mach/board.h>
#include "devices.h"
#include "smd_private.h"
#include <asm/mach/flash.h>
#include <asm/mach/mmc.h>
#include <mach/msm_hsusb.h>
#include <mach/usbdiag.h>
#include <mach/rpc_hsusb.h>
#include "clock-pcom.h"
static struct resource resources_uart1[] = {
{
.start = INT_UART1,
.end = INT_UART1,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART1_PHYS,
.end = MSM_UART1_PHYS + MSM_UART1_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
static struct resource resources_uart2[] = {
{
.start = INT_UART2,
.end = INT_UART2,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART2_PHYS,
.end = MSM_UART2_PHYS + MSM_UART2_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
static struct resource resources_uart3[] = {
{
.start = INT_UART3,
.end = INT_UART3,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART3_PHYS,
.end = MSM_UART3_PHYS + MSM_UART3_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm_device_uart1 = {
.name = "msm_serial",
.id = 0,
.num_resources = ARRAY_SIZE(resources_uart1),
.resource = resources_uart1,
};
struct platform_device msm_device_uart2 = {
.name = "msm_serial",
.id = 1,
.num_resources = ARRAY_SIZE(resources_uart2),
.resource = resources_uart2,
};
struct platform_device msm_device_uart3 = {
.name = "msm_serial",
.id = 2,
.num_resources = ARRAY_SIZE(resources_uart3),
.resource = resources_uart3,
};
#define MSM_UART1DM_PHYS 0xA0200000
#define MSM_UART2DM_PHYS 0xA0300000
static struct resource msm_uart1_dm_resources[] = {
{
.start = MSM_UART1DM_PHYS,
.end = MSM_UART1DM_PHYS + PAGE_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_UART1DM_IRQ,
.end = INT_UART1DM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = INT_UART1DM_RX,
.end = INT_UART1DM_RX,
.flags = IORESOURCE_IRQ,
},
{
.start = DMOV_HSUART1_TX_CHAN,
.end = DMOV_HSUART1_RX_CHAN,
.name = "uartdm_channels",
.flags = IORESOURCE_DMA,
},
{
.start = DMOV_HSUART1_TX_CRCI,
.end = DMOV_HSUART1_RX_CRCI,
.name = "uartdm_crci",
.flags = IORESOURCE_DMA,
},
};
static u64 msm_uart_dm1_dma_mask = DMA_BIT_MASK(32);
struct platform_device msm_device_uart_dm1 = {
.name = "msm_serial_hs",
.id = 0,
.num_resources = ARRAY_SIZE(msm_uart1_dm_resources),
.resource = msm_uart1_dm_resources,
.dev = {
.dma_mask = &msm_uart_dm1_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
static struct resource msm_uart2_dm_resources[] = {
{
.start = MSM_UART2DM_PHYS,
.end = MSM_UART2DM_PHYS + PAGE_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_UART2DM_IRQ,
.end = INT_UART2DM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = INT_UART2DM_RX,
.end = INT_UART2DM_RX,
.flags = IORESOURCE_IRQ,
},
{
.start = DMOV_HSUART2_TX_CHAN,
.end = DMOV_HSUART2_RX_CHAN,
.name = "uartdm_channels",
.flags = IORESOURCE_DMA,
},
{
.start = DMOV_HSUART2_TX_CRCI,
.end = DMOV_HSUART2_RX_CRCI,
.name = "uartdm_crci",
.flags = IORESOURCE_DMA,
},
};
static u64 msm_uart_dm2_dma_mask = DMA_BIT_MASK(32);
struct platform_device msm_device_uart_dm2 = {
.name = "msm_serial_hs",
.id = 1,
.num_resources = ARRAY_SIZE(msm_uart2_dm_resources),
.resource = msm_uart2_dm_resources,
.dev = {
.dma_mask = &msm_uart_dm2_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
#define MSM_I2C_SIZE SZ_4K
#define MSM_I2C_PHYS 0xA9900000
static struct resource resources_i2c[] = {
{
.start = MSM_I2C_PHYS,
.end = MSM_I2C_PHYS + MSM_I2C_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_PWB_I2C,
.end = INT_PWB_I2C,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_device_i2c = {
.name = "msm_i2c",
.id = 0,
.num_resources = ARRAY_SIZE(resources_i2c),
.resource = resources_i2c,
};
#define MSM_HSUSB_PHYS 0xA0800000
static struct resource resources_hsusb_otg[] = {
{
.start = MSM_HSUSB_PHYS,
.end = MSM_HSUSB_PHYS + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_USB_HS,
.end = INT_USB_HS,
.flags = IORESOURCE_IRQ,
},
};
static u64 dma_mask = 0xffffffffULL;
struct platform_device msm_device_hsusb_otg = {
.name = "msm_hsusb_otg",
.id = -1,
.num_resources = ARRAY_SIZE(resources_hsusb_otg),
.resource = resources_hsusb_otg,
.dev = {
.dma_mask = &dma_mask,
.coherent_dma_mask = 0xffffffffULL,
},
};
static struct resource resources_hsusb_peripheral[] = {
{
.start = MSM_HSUSB_PHYS,
.end = MSM_HSUSB_PHYS + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_USB_HS,
.end = INT_USB_HS,
.flags = IORESOURCE_IRQ,
},
};
static struct resource resources_gadget_peripheral[] = {
{
.start = MSM_HSUSB_PHYS,
.end = MSM_HSUSB_PHYS + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_USB_HS,
.end = INT_USB_HS,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_device_hsusb_peripheral = {
.name = "msm_hsusb_peripheral",
.id = -1,
.num_resources = ARRAY_SIZE(resources_hsusb_peripheral),
.resource = resources_hsusb_peripheral,
.dev = {
.dma_mask = &dma_mask,
.coherent_dma_mask = 0xffffffffULL,
},
};
struct platform_device msm_device_gadget_peripheral = {
.name = "msm_hsusb",
.id = -1,
.num_resources = ARRAY_SIZE(resources_gadget_peripheral),
.resource = resources_gadget_peripheral,
.dev = {
.dma_mask = &dma_mask,
.coherent_dma_mask = 0xffffffffULL,
},
};
static struct resource resources_hsusb_host[] = {
{
.start = MSM_HSUSB_PHYS,
.end = MSM_HSUSB_PHYS + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_USB_HS,
.end = INT_USB_HS,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_device_hsusb_host = {
.name = "msm_hsusb_host",
.id = 0,
.num_resources = ARRAY_SIZE(resources_hsusb_host),
.resource = resources_hsusb_host,
.dev = {
.dma_mask = &dma_mask,
.coherent_dma_mask = 0xffffffffULL,
},
};
static struct platform_device *msm_host_devices[] = {
&msm_device_hsusb_host,
};
int msm_add_host(unsigned int host, struct msm_usb_host_platform_data *plat)
{
struct platform_device *pdev;
pdev = msm_host_devices[host];
if (!pdev)
return -ENODEV;
pdev->dev.platform_data = plat;
return platform_device_register(pdev);
}
#ifdef CONFIG_USB_ANDROID_DIAG
struct usb_diag_platform_data usb_diag_pdata = {
.ch_name = DIAG_LEGACY,
.update_pid_and_serial_num = usb_diag_update_pid_and_serial_num,
};
struct platform_device usb_diag_device = {
.name = "usb_diag",
.id = -1,
.dev = {
.platform_data = &usb_diag_pdata,
},
};
#endif
#ifdef CONFIG_USB_F_SERIAL
static struct usb_gadget_fserial_platform_data fserial_pdata = {
.no_ports = 2,
};
struct platform_device usb_gadget_fserial_device = {
.name = "usb_fserial",
.id = -1,
.dev = {
.platform_data = &fserial_pdata,
},
};
#endif
#define MSM_NAND_PHYS 0xA0A00000
static struct resource resources_nand[] = {
[0] = {
.name = "msm_nand_dmac",
.start = DMOV_NAND_CHAN,
.end = DMOV_NAND_CHAN,
.flags = IORESOURCE_DMA,
},
[1] = {
.name = "msm_nand_phys",
.start = MSM_NAND_PHYS,
.end = MSM_NAND_PHYS + 0x7FF,
.flags = IORESOURCE_MEM,
},
};
static struct resource resources_otg[] = {
{
.start = MSM_HSUSB_PHYS,
.end = MSM_HSUSB_PHYS + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_USB_HS,
.end = INT_USB_HS,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_device_otg = {
.name = "msm_otg",
.id = -1,
.num_resources = ARRAY_SIZE(resources_otg),
.resource = resources_otg,
.dev = {
.coherent_dma_mask = 0xffffffffULL,
},
};
struct flash_platform_data msm_nand_data = {
.parts = NULL,
.nr_parts = 0,
};
struct platform_device msm_device_nand = {
.name = "msm_nand",
.id = -1,
.num_resources = ARRAY_SIZE(resources_nand),
.resource = resources_nand,
.dev = {
.platform_data = &msm_nand_data,
},
};
struct platform_device msm_device_smd = {
.name = "msm_smd",
.id = -1,
};
static struct resource msm_dmov_resource[] = {
{
.start = INT_ADM_AARM,
.flags = IORESOURCE_IRQ,
},
{
.start = 0xA9700000,
.end = 0xA9700000 + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
};
static struct msm_dmov_pdata msm_dmov_pdata = {
.sd = 3,
.sd_size = 0x400,
};
struct platform_device msm_device_dmov = {
.name = "msm_dmov",
.id = -1,
.resource = msm_dmov_resource,
.num_resources = ARRAY_SIZE(msm_dmov_resource),
.dev = {
.platform_data = &msm_dmov_pdata,
},
};
#define MSM_SDC1_BASE 0xA0400000
#define MSM_SDC2_BASE 0xA0500000
#define MSM_SDC3_BASE 0xA0600000
#define MSM_SDC4_BASE 0xA0700000
static struct resource resources_sdc1[] = {
{
.name = "core_mem",
.start = MSM_SDC1_BASE,
.end = MSM_SDC1_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "core_irq",
.start = INT_SDC1_0,
.end = INT_SDC1_1,
.flags = IORESOURCE_IRQ,
},
{
.name = "dma_chnl",
.start = DMOV_SDC1_CHAN,
.end = DMOV_SDC1_CHAN,
.flags = IORESOURCE_DMA,
},
{
.name = "dma_crci",
.start = DMOV_SDC1_CRCI,
.end = DMOV_SDC1_CRCI,
.flags = IORESOURCE_DMA,
}
};
static struct resource resources_sdc2[] = {
{
.name = "core_mem",
.start = MSM_SDC2_BASE,
.end = MSM_SDC2_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "core_irq",
.start = INT_SDC2_0,
.end = INT_SDC2_1,
.flags = IORESOURCE_IRQ,
},
{
.name = "dma_chnl",
.start = DMOV_SDC2_CHAN,
.end = DMOV_SDC2_CHAN,
.flags = IORESOURCE_DMA,
},
{
.name = "dma_crci",
.start = DMOV_SDC2_CRCI,
.end = DMOV_SDC2_CRCI,
.flags = IORESOURCE_DMA,
}
};
static struct resource resources_sdc3[] = {
{
.name = "core_mem",
.start = MSM_SDC3_BASE,
.end = MSM_SDC3_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "core_irq",
.start = INT_SDC3_0,
.end = INT_SDC3_1,
.flags = IORESOURCE_IRQ,
},
{
.name = "dma_chnl",
.start = DMOV_SDC3_CHAN,
.end = DMOV_SDC3_CHAN,
.flags = IORESOURCE_DMA,
},
{
.name = "dma_crci",
.start = DMOV_SDC3_CRCI,
.end = DMOV_SDC3_CRCI,
.flags = IORESOURCE_DMA,
},
};
static struct resource resources_sdc4[] = {
{
.name = "core_mem",
.start = MSM_SDC4_BASE,
.end = MSM_SDC4_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "core_irq",
.start = INT_SDC4_0,
.end = INT_SDC4_1,
.flags = IORESOURCE_IRQ,
},
{
.name = "dma_chnl",
.start = DMOV_SDC4_CHAN,
.end = DMOV_SDC4_CHAN,
.flags = IORESOURCE_DMA,
},
{
.name = "dma_crci",
.start = DMOV_SDC4_CRCI,
.end = DMOV_SDC4_CRCI,
.flags = IORESOURCE_DMA,
},
};
struct platform_device msm_device_sdc1 = {
.name = "msm_sdcc",
.id = 1,
.num_resources = ARRAY_SIZE(resources_sdc1),
.resource = resources_sdc1,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device msm_device_sdc2 = {
.name = "msm_sdcc",
.id = 2,
.num_resources = ARRAY_SIZE(resources_sdc2),
.resource = resources_sdc2,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device msm_device_sdc3 = {
.name = "msm_sdcc",
.id = 3,
.num_resources = ARRAY_SIZE(resources_sdc3),
.resource = resources_sdc3,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device msm_device_sdc4 = {
.name = "msm_sdcc",
.id = 4,
.num_resources = ARRAY_SIZE(resources_sdc4),
.resource = resources_sdc4,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
static struct platform_device *msm_sdcc_devices[] __initdata = {
&msm_device_sdc1,
&msm_device_sdc2,
&msm_device_sdc3,
&msm_device_sdc4,
};
int __init msm_add_sdcc(unsigned int controller, struct mmc_platform_data *plat)
{
struct platform_device *pdev;
if (controller < 1 || controller > 4)
return -EINVAL;
pdev = msm_sdcc_devices[controller-1];
pdev->dev.platform_data = plat;
return platform_device_register(pdev);
}
#define RAMFS_INFO_MAGICNUMBER 0x654D4D43
#define RAMFS_INFO_VERSION 0x00000001
#define RAMFS_MODEMSTORAGE_ID 0x4D454653
static struct resource rmt_storage_resources[] = {
{
.flags = IORESOURCE_MEM,
},
};
static struct platform_device rmt_storage_device = {
.name = "rmt_storage",
.id = -1,
.num_resources = ARRAY_SIZE(rmt_storage_resources),
.resource = rmt_storage_resources,
};
struct shared_ramfs_entry {
uint32_t client_id; /* Client id to uniquely identify a client */
uint32_t base_addr; /* Base address of shared RAMFS memory */
uint32_t size; /* Size of the shared RAMFS memory */
uint32_t reserved; /* Reserved attribute for future use */
};
struct shared_ramfs_table {
uint32_t magic_id; /* Identify RAMFS details in SMEM */
uint32_t version; /* Version of shared_ramfs_table */
uint32_t entries; /* Total number of valid entries */
struct shared_ramfs_entry ramfs_entry[3]; /* List all entries */
};
int __init rmt_storage_add_ramfs(void)
{
struct shared_ramfs_table *ramfs_table;
struct shared_ramfs_entry *ramfs_entry;
int index;
ramfs_table = smem_alloc(SMEM_SEFS_INFO,
sizeof(struct shared_ramfs_table));
if (!ramfs_table) {
printk(KERN_WARNING "%s: No RAMFS table in SMEM\n", __func__);
return -ENOENT;
}
if ((ramfs_table->magic_id != (u32) RAMFS_INFO_MAGICNUMBER) ||
(ramfs_table->version != (u32) RAMFS_INFO_VERSION)) {
printk(KERN_WARNING "%s: Magic / Version mismatch:, "
"magic_id=%#x, format_version=%#x\n", __func__,
ramfs_table->magic_id, ramfs_table->version);
return -ENOENT;
}
for (index = 0; index < ramfs_table->entries; index++) {
ramfs_entry = &ramfs_table->ramfs_entry[index];
/* Find a match for the Modem Storage RAMFS area */
if (ramfs_entry->client_id == (u32) RAMFS_MODEMSTORAGE_ID) {
printk(KERN_INFO "%s: RAMFS Info (from SMEM): "
"Baseaddr = 0x%08x, Size = 0x%08x\n", __func__,
ramfs_entry->base_addr, ramfs_entry->size);
rmt_storage_resources[0].start = ramfs_entry->base_addr;
rmt_storage_resources[0].end = ramfs_entry->base_addr +
ramfs_entry->size - 1;
platform_device_register(&rmt_storage_device);
return 0;
}
}
return -ENOENT;
}
#if defined(CONFIG_FB_MSM_MDP40)
#define MDP_BASE 0xA3F00000
#define PMDH_BASE 0xAD600000
#define EMDH_BASE 0xAD700000
#define TVENC_BASE 0xAD400000
#else
#define MDP_BASE 0xAA200000
#define PMDH_BASE 0xAA600000
#define EMDH_BASE 0xAA700000
#define TVENC_BASE 0xAA400000
#endif
static struct resource msm_mdp_resources[] = {
{
.name = "mdp",
.start = MDP_BASE,
.end = MDP_BASE + 0x000F0000 - 1,
.flags = IORESOURCE_MEM,
},
{
.start = INT_MDP,
.end = INT_MDP,
.flags = IORESOURCE_IRQ,
},
};
static struct resource msm_mddi_resources[] = {
{
.name = "pmdh",
.start = PMDH_BASE,
.end = PMDH_BASE + PAGE_SIZE - 1,
.flags = IORESOURCE_MEM,
}
};
static struct resource msm_mddi_ext_resources[] = {
{
.name = "emdh",
.start = EMDH_BASE,
.end = EMDH_BASE + PAGE_SIZE - 1,
.flags = IORESOURCE_MEM,
}
};
static struct resource msm_ebi2_lcd_resources[] = {
{
.name = "base",
.start = 0xa0d00000,
.end = 0xa0d00000 + PAGE_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "lcd01",
.start = 0x98000000,
.end = 0x98000000 + 0x80000 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "lcd02",
.start = 0x9c000000,
.end = 0x9c000000 + 0x80000 - 1,
.flags = IORESOURCE_MEM,
},
};
static struct resource msm_tvenc_resources[] = {
{
.name = "tvenc",
.start = TVENC_BASE,
.end = TVENC_BASE + PAGE_SIZE - 1,
.flags = IORESOURCE_MEM,
}
};
static struct platform_device msm_mdp_device = {
.name = "mdp",
.id = 0,
.num_resources = ARRAY_SIZE(msm_mdp_resources),
.resource = msm_mdp_resources,
};
static struct platform_device msm_mddi_device = {
.name = "mddi",
.id = 0,
.num_resources = ARRAY_SIZE(msm_mddi_resources),
.resource = msm_mddi_resources,
};
static struct platform_device msm_mddi_ext_device = {
.name = "mddi_ext",
.id = 0,
.num_resources = ARRAY_SIZE(msm_mddi_ext_resources),
.resource = msm_mddi_ext_resources,
};
static struct platform_device msm_ebi2_lcd_device = {
.name = "ebi2_lcd",
.id = 0,
.num_resources = ARRAY_SIZE(msm_ebi2_lcd_resources),
.resource = msm_ebi2_lcd_resources,
};
struct platform_device msm_lcdc_device = {
.name = "lcdc",
.id = 0,
};
static struct platform_device msm_tvenc_device = {
.name = "tvenc",
.id = 0,
.num_resources = ARRAY_SIZE(msm_tvenc_resources),
.resource = msm_tvenc_resources,
};
/* TSIF begin */
#if defined(CONFIG_TSIF) || defined(CONFIG_TSIF_MODULE)
#define MSM_TSIF_PHYS (0xa0100000)
#define MSM_TSIF_SIZE (0x200)
static struct resource tsif_resources[] = {
[0] = {
.flags = IORESOURCE_IRQ,
.start = INT_TSIF_IRQ,
.end = INT_TSIF_IRQ,
},
[1] = {
.flags = IORESOURCE_MEM,
.start = MSM_TSIF_PHYS,
.end = MSM_TSIF_PHYS + MSM_TSIF_SIZE - 1,
},
[2] = {
.flags = IORESOURCE_DMA,
.start = DMOV_TSIF_CHAN,
.end = DMOV_TSIF_CRCI,
},
};
static void tsif_release(struct device *dev)
{
dev_info(dev, "release\n");
}
struct platform_device msm_device_tsif = {
.name = "msm_tsif",
.id = 0,
.num_resources = ARRAY_SIZE(tsif_resources),
.resource = tsif_resources,
.dev = {
.release = tsif_release,
},
};
#endif /* defined(CONFIG_TSIF) || defined(CONFIG_TSIF_MODULE) */
/* TSIF end */
#define MSM_TSSC_PHYS 0xAA300000
static struct resource resources_tssc[] = {
{
.start = MSM_TSSC_PHYS,
.end = MSM_TSSC_PHYS + SZ_4K - 1,
.name = "tssc",
.flags = IORESOURCE_MEM,
},
{
.start = INT_TCHSCRN1,
.end = INT_TCHSCRN1,
.name = "tssc1",
.flags = IORESOURCE_IRQ | IRQF_TRIGGER_RISING,
},
{
.start = INT_TCHSCRN2,
.end = INT_TCHSCRN2,
.name = "tssc2",
.flags = IORESOURCE_IRQ | IRQF_TRIGGER_RISING,
},
};
struct platform_device msm_device_tssc = {
.name = "msm_touchscreen",
.id = 0,
.num_resources = ARRAY_SIZE(resources_tssc),
.resource = resources_tssc,
};
static void __init msm_register_device(struct platform_device *pdev, void *data)
{
int ret;
pdev->dev.platform_data = data;
ret = platform_device_register(pdev);
if (ret)
dev_err(&pdev->dev,
"%s: platform_device_register() failed = %d\n",
__func__, ret);
}
void __init msm_fb_register_device(char *name, void *data)
{
if (!strncmp(name, "mdp", 3))
msm_register_device(&msm_mdp_device, data);
else if (!strncmp(name, "pmdh", 4))
msm_register_device(&msm_mddi_device, data);
else if (!strncmp(name, "emdh", 4))
msm_register_device(&msm_mddi_ext_device, data);
else if (!strncmp(name, "ebi2", 4))
msm_register_device(&msm_ebi2_lcd_device, data);
else if (!strncmp(name, "tvenc", 5))
msm_register_device(&msm_tvenc_device, data);
else if (!strncmp(name, "lcdc", 4))
msm_register_device(&msm_lcdc_device, data);
else
printk(KERN_ERR "%s: unknown device! %s\n", __func__, name);
}
static struct platform_device msm_camera_device = {
.name = "msm_camera",
.id = 0,
};
void __init msm_camera_register_device(void *res, uint32_t num,
void *data)
{
msm_camera_device.num_resources = num;
msm_camera_device.resource = res;
msm_register_device(&msm_camera_device, data);
}
static DEFINE_CLK_PCOM(adm_clk, ADM_CLK, 0);
static DEFINE_CLK_PCOM(adsp_clk, ADSP_CLK, 0);
static DEFINE_CLK_PCOM(ebi1_clk, EBI1_CLK, CLK_MIN);
static DEFINE_CLK_PCOM(ebi2_clk, EBI2_CLK, 0);
static DEFINE_CLK_PCOM(ecodec_clk, ECODEC_CLK, 0);
static DEFINE_CLK_PCOM(gp_clk, GP_CLK, 0);
static DEFINE_CLK_PCOM(i2c_clk, I2C_CLK, 0);
static DEFINE_CLK_PCOM(icodec_rx_clk, ICODEC_RX_CLK, 0);
static DEFINE_CLK_PCOM(icodec_tx_clk, ICODEC_TX_CLK, 0);
static DEFINE_CLK_PCOM(imem_clk, IMEM_CLK, OFF);
static DEFINE_CLK_PCOM(mdc_clk, MDC_CLK, 0);
static DEFINE_CLK_PCOM(pmdh_clk, PMDH_CLK, OFF | CLK_MINMAX);
static DEFINE_CLK_PCOM(mdp_clk, MDP_CLK, OFF);
static DEFINE_CLK_PCOM(mdp_lcdc_pclk_clk, MDP_LCDC_PCLK_CLK, 0);
static DEFINE_CLK_PCOM(mdp_lcdc_pad_pclk_clk, MDP_LCDC_PAD_PCLK_CLK, 0);
static DEFINE_CLK_PCOM(mdp_vsync_clk, MDP_VSYNC_CLK, OFF);
static DEFINE_CLK_PCOM(pbus_clk, PBUS_CLK, CLK_MIN);
static DEFINE_CLK_PCOM(pcm_clk, PCM_CLK, 0);
static DEFINE_CLK_PCOM(sdac_clk, SDAC_CLK, OFF);
static DEFINE_CLK_PCOM(sdc1_clk, SDC1_CLK, OFF);
static DEFINE_CLK_PCOM(sdc1_p_clk, SDC1_P_CLK, OFF);
static DEFINE_CLK_PCOM(sdc2_clk, SDC2_CLK, OFF);
static DEFINE_CLK_PCOM(sdc2_p_clk, SDC2_P_CLK, OFF);
static DEFINE_CLK_PCOM(sdc3_clk, SDC3_CLK, OFF);
static DEFINE_CLK_PCOM(sdc3_p_clk, SDC3_P_CLK, OFF);
static DEFINE_CLK_PCOM(sdc4_clk, SDC4_CLK, OFF);
static DEFINE_CLK_PCOM(sdc4_p_clk, SDC4_P_CLK, OFF);
static DEFINE_CLK_PCOM(uart1_clk, UART1_CLK, OFF);
static DEFINE_CLK_PCOM(uart2_clk, UART2_CLK, 0);
static DEFINE_CLK_PCOM(uart3_clk, UART3_CLK, OFF);
static DEFINE_CLK_PCOM(uart1dm_clk, UART1DM_CLK, OFF);
static DEFINE_CLK_PCOM(uart2dm_clk, UART2DM_CLK, 0);
static DEFINE_CLK_PCOM(usb_hs_clk, USB_HS_CLK, OFF);
static DEFINE_CLK_PCOM(usb_hs_p_clk, USB_HS_P_CLK, OFF);
static DEFINE_CLK_PCOM(usb_otg_clk, USB_OTG_CLK, 0);
static DEFINE_CLK_PCOM(vdc_clk, VDC_CLK, OFF | CLK_MIN);
static DEFINE_CLK_PCOM(vfe_clk, VFE_CLK, OFF);
static DEFINE_CLK_PCOM(vfe_mdc_clk, VFE_MDC_CLK, OFF);
struct clk_lookup msm_clocks_7x25[] = {
CLK_LOOKUP("core_clk", adm_clk.c, "msm_dmov"),
CLK_LOOKUP("adsp_clk", adsp_clk.c, NULL),
CLK_LOOKUP("ebi1_clk", ebi1_clk.c, NULL),
CLK_LOOKUP("ebi2_clk", ebi2_clk.c, NULL),
CLK_LOOKUP("ecodec_clk", ecodec_clk.c, NULL),
CLK_LOOKUP("core_clk", gp_clk.c, NULL),
CLK_LOOKUP("core_clk", i2c_clk.c, "msm_i2c.0"),
CLK_LOOKUP("icodec_rx_clk", icodec_rx_clk.c, NULL),
CLK_LOOKUP("icodec_tx_clk", icodec_tx_clk.c, NULL),
CLK_LOOKUP("mem_clk", imem_clk.c, NULL),
CLK_LOOKUP("mdc_clk", mdc_clk.c, NULL),
CLK_LOOKUP("mddi_clk", pmdh_clk.c, NULL),
CLK_LOOKUP("mdp_clk", mdp_clk.c, NULL),
CLK_LOOKUP("mdp_lcdc_pclk_clk", mdp_lcdc_pclk_clk.c, NULL),
CLK_LOOKUP("mdp_lcdc_pad_pclk_clk", mdp_lcdc_pad_pclk_clk.c, NULL),
CLK_LOOKUP("mdp_vsync_clk", mdp_vsync_clk.c, NULL),
CLK_LOOKUP("pbus_clk", pbus_clk.c, NULL),
CLK_LOOKUP("pcm_clk", pcm_clk.c, NULL),
CLK_LOOKUP("sdac_clk", sdac_clk.c, NULL),
CLK_LOOKUP("core_clk", sdc1_clk.c, "msm_sdcc.1"),
CLK_LOOKUP("iface_clk", sdc1_p_clk.c, "msm_sdcc.1"),
CLK_LOOKUP("core_clk", sdc2_clk.c, "msm_sdcc.2"),
CLK_LOOKUP("iface_clk", sdc2_p_clk.c, "msm_sdcc.2"),
CLK_LOOKUP("core_clk", sdc3_clk.c, "msm_sdcc.3"),
CLK_LOOKUP("iface_clk", sdc3_p_clk.c, "msm_sdcc.3"),
CLK_LOOKUP("core_clk", sdc4_clk.c, "msm_sdcc.4"),
CLK_LOOKUP("iface_clk", sdc4_p_clk.c, "msm_sdcc.4"),
CLK_LOOKUP("core_clk", uart1_clk.c, "msm_serial.0"),
CLK_LOOKUP("core_clk", uart2_clk.c, "msm_serial.1"),
CLK_LOOKUP("core_clk", uart3_clk.c, "msm_serial.2"),
CLK_LOOKUP("core_clk", uart1dm_clk.c, "msm_serial_hs.0"),
CLK_LOOKUP("core_clk", uart2dm_clk.c, "msm_serial_hs.1"),
CLK_LOOKUP("alt_core_clk", usb_hs_clk.c, "msm_otg"),
CLK_LOOKUP("iface_clk", usb_hs_p_clk.c, "msm_otg"),
CLK_LOOKUP("alt_core_clk", usb_hs_clk.c, "msm_hsusb_peripheral"),
CLK_LOOKUP("iface_clk", usb_hs_p_clk.c, "msm_hsusb_peripheral"),
CLK_LOOKUP("alt_core_clk", usb_otg_clk.c, NULL),
CLK_LOOKUP("vdc_clk", vdc_clk.c, NULL),
CLK_LOOKUP("vfe_clk", vfe_clk.c, NULL),
CLK_LOOKUP("vfe_mdc_clk", vfe_mdc_clk.c, NULL),
};
unsigned msm_num_clocks_7x25 = ARRAY_SIZE(msm_clocks_7x25);
| gpl-2.0 |
hsarkanen/linux-imx6 | drivers/gpu/drm/drm_vm.c | 1996 | 18482 | /**
* \file drm_vm.c
* Memory mapping for DRM
*
* \author Rickard E. (Rik) Faith <faith@valinux.com>
* \author Gareth Hughes <gareth@valinux.com>
*/
/*
* Created: Mon Jan 4 08:58:31 1999 by faith@valinux.com
*
* Copyright 1999 Precision Insight, Inc., Cedar Park, Texas.
* Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* 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 <drm/drmP.h>
#include <linux/export.h>
#if defined(__ia64__)
#include <linux/efi.h>
#include <linux/slab.h>
#endif
static void drm_vm_open(struct vm_area_struct *vma);
static void drm_vm_close(struct vm_area_struct *vma);
static pgprot_t drm_io_prot(uint32_t map_type, struct vm_area_struct *vma)
{
pgprot_t tmp = vm_get_page_prot(vma->vm_flags);
#if defined(__i386__) || defined(__x86_64__)
if (boot_cpu_data.x86 > 3 && map_type != _DRM_AGP) {
pgprot_val(tmp) |= _PAGE_PCD;
pgprot_val(tmp) &= ~_PAGE_PWT;
}
#elif defined(__powerpc__)
pgprot_val(tmp) |= _PAGE_NO_CACHE;
if (map_type == _DRM_REGISTERS)
pgprot_val(tmp) |= _PAGE_GUARDED;
#elif defined(__ia64__)
if (efi_range_is_wc(vma->vm_start, vma->vm_end -
vma->vm_start))
tmp = pgprot_writecombine(tmp);
else
tmp = pgprot_noncached(tmp);
#elif defined(__sparc__) || defined(__arm__) || defined(__mips__)
tmp = pgprot_noncached(tmp);
#endif
return tmp;
}
static pgprot_t drm_dma_prot(uint32_t map_type, struct vm_area_struct *vma)
{
pgprot_t tmp = vm_get_page_prot(vma->vm_flags);
#if defined(__powerpc__) && defined(CONFIG_NOT_COHERENT_CACHE)
tmp |= _PAGE_NO_CACHE;
#endif
return tmp;
}
/**
* \c fault method for AGP virtual memory.
*
* \param vma virtual memory area.
* \param address access address.
* \return pointer to the page structure.
*
* Find the right map and if it's AGP memory find the real physical page to
* map, get the page, increment the use count and return it.
*/
#if __OS_HAS_AGP
static int drm_do_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct drm_file *priv = vma->vm_file->private_data;
struct drm_device *dev = priv->minor->dev;
struct drm_local_map *map = NULL;
struct drm_map_list *r_list;
struct drm_hash_item *hash;
/*
* Find the right map
*/
if (!drm_core_has_AGP(dev))
goto vm_fault_error;
if (!dev->agp || !dev->agp->cant_use_aperture)
goto vm_fault_error;
if (drm_ht_find_item(&dev->map_hash, vma->vm_pgoff, &hash))
goto vm_fault_error;
r_list = drm_hash_entry(hash, struct drm_map_list, hash);
map = r_list->map;
if (map && map->type == _DRM_AGP) {
/*
* Using vm_pgoff as a selector forces us to use this unusual
* addressing scheme.
*/
resource_size_t offset = (unsigned long)vmf->virtual_address -
vma->vm_start;
resource_size_t baddr = map->offset + offset;
struct drm_agp_mem *agpmem;
struct page *page;
#ifdef __alpha__
/*
* Adjust to a bus-relative address
*/
baddr -= dev->hose->mem_space->start;
#endif
/*
* It's AGP memory - find the real physical page to map
*/
list_for_each_entry(agpmem, &dev->agp->memory, head) {
if (agpmem->bound <= baddr &&
agpmem->bound + agpmem->pages * PAGE_SIZE > baddr)
break;
}
if (&agpmem->head == &dev->agp->memory)
goto vm_fault_error;
/*
* Get the page, inc the use count, and return it
*/
offset = (baddr - agpmem->bound) >> PAGE_SHIFT;
page = agpmem->memory->pages[offset];
get_page(page);
vmf->page = page;
DRM_DEBUG
("baddr = 0x%llx page = 0x%p, offset = 0x%llx, count=%d\n",
(unsigned long long)baddr,
agpmem->memory->pages[offset],
(unsigned long long)offset,
page_count(page));
return 0;
}
vm_fault_error:
return VM_FAULT_SIGBUS; /* Disallow mremap */
}
#else /* __OS_HAS_AGP */
static int drm_do_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
return VM_FAULT_SIGBUS;
}
#endif /* __OS_HAS_AGP */
/**
* \c nopage method for shared virtual memory.
*
* \param vma virtual memory area.
* \param address access address.
* \return pointer to the page structure.
*
* Get the mapping, find the real physical page to map, get the page, and
* return it.
*/
static int drm_do_vm_shm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct drm_local_map *map = vma->vm_private_data;
unsigned long offset;
unsigned long i;
struct page *page;
if (!map)
return VM_FAULT_SIGBUS; /* Nothing allocated */
offset = (unsigned long)vmf->virtual_address - vma->vm_start;
i = (unsigned long)map->handle + offset;
page = vmalloc_to_page((void *)i);
if (!page)
return VM_FAULT_SIGBUS;
get_page(page);
vmf->page = page;
DRM_DEBUG("shm_fault 0x%lx\n", offset);
return 0;
}
/**
* \c close method for shared virtual memory.
*
* \param vma virtual memory area.
*
* Deletes map information if we are the last
* person to close a mapping and it's not in the global maplist.
*/
static void drm_vm_shm_close(struct vm_area_struct *vma)
{
struct drm_file *priv = vma->vm_file->private_data;
struct drm_device *dev = priv->minor->dev;
struct drm_vma_entry *pt, *temp;
struct drm_local_map *map;
struct drm_map_list *r_list;
int found_maps = 0;
DRM_DEBUG("0x%08lx,0x%08lx\n",
vma->vm_start, vma->vm_end - vma->vm_start);
atomic_dec(&dev->vma_count);
map = vma->vm_private_data;
mutex_lock(&dev->struct_mutex);
list_for_each_entry_safe(pt, temp, &dev->vmalist, head) {
if (pt->vma->vm_private_data == map)
found_maps++;
if (pt->vma == vma) {
list_del(&pt->head);
kfree(pt);
}
}
/* We were the only map that was found */
if (found_maps == 1 && map->flags & _DRM_REMOVABLE) {
/* Check to see if we are in the maplist, if we are not, then
* we delete this mappings information.
*/
found_maps = 0;
list_for_each_entry(r_list, &dev->maplist, head) {
if (r_list->map == map)
found_maps++;
}
if (!found_maps) {
drm_dma_handle_t dmah;
switch (map->type) {
case _DRM_REGISTERS:
case _DRM_FRAME_BUFFER:
if (drm_core_has_MTRR(dev) && map->mtrr >= 0) {
int retcode;
retcode = mtrr_del(map->mtrr,
map->offset,
map->size);
DRM_DEBUG("mtrr_del = %d\n", retcode);
}
iounmap(map->handle);
break;
case _DRM_SHM:
vfree(map->handle);
break;
case _DRM_AGP:
case _DRM_SCATTER_GATHER:
break;
case _DRM_CONSISTENT:
dmah.vaddr = map->handle;
dmah.busaddr = map->offset;
dmah.size = map->size;
__drm_pci_free(dev, &dmah);
break;
case _DRM_GEM:
DRM_ERROR("tried to rmmap GEM object\n");
break;
}
kfree(map);
}
}
mutex_unlock(&dev->struct_mutex);
}
/**
* \c fault method for DMA virtual memory.
*
* \param vma virtual memory area.
* \param address access address.
* \return pointer to the page structure.
*
* Determine the page number from the page offset and get it from drm_device_dma::pagelist.
*/
static int drm_do_vm_dma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct drm_file *priv = vma->vm_file->private_data;
struct drm_device *dev = priv->minor->dev;
struct drm_device_dma *dma = dev->dma;
unsigned long offset;
unsigned long page_nr;
struct page *page;
if (!dma)
return VM_FAULT_SIGBUS; /* Error */
if (!dma->pagelist)
return VM_FAULT_SIGBUS; /* Nothing allocated */
offset = (unsigned long)vmf->virtual_address - vma->vm_start; /* vm_[pg]off[set] should be 0 */
page_nr = offset >> PAGE_SHIFT; /* page_nr could just be vmf->pgoff */
page = virt_to_page((dma->pagelist[page_nr] + (offset & (~PAGE_MASK))));
get_page(page);
vmf->page = page;
DRM_DEBUG("dma_fault 0x%lx (page %lu)\n", offset, page_nr);
return 0;
}
/**
* \c fault method for scatter-gather virtual memory.
*
* \param vma virtual memory area.
* \param address access address.
* \return pointer to the page structure.
*
* Determine the map offset from the page offset and get it from drm_sg_mem::pagelist.
*/
static int drm_do_vm_sg_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct drm_local_map *map = vma->vm_private_data;
struct drm_file *priv = vma->vm_file->private_data;
struct drm_device *dev = priv->minor->dev;
struct drm_sg_mem *entry = dev->sg;
unsigned long offset;
unsigned long map_offset;
unsigned long page_offset;
struct page *page;
if (!entry)
return VM_FAULT_SIGBUS; /* Error */
if (!entry->pagelist)
return VM_FAULT_SIGBUS; /* Nothing allocated */
offset = (unsigned long)vmf->virtual_address - vma->vm_start;
map_offset = map->offset - (unsigned long)dev->sg->virtual;
page_offset = (offset >> PAGE_SHIFT) + (map_offset >> PAGE_SHIFT);
page = entry->pagelist[page_offset];
get_page(page);
vmf->page = page;
return 0;
}
static int drm_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
return drm_do_vm_fault(vma, vmf);
}
static int drm_vm_shm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
return drm_do_vm_shm_fault(vma, vmf);
}
static int drm_vm_dma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
return drm_do_vm_dma_fault(vma, vmf);
}
static int drm_vm_sg_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
return drm_do_vm_sg_fault(vma, vmf);
}
/** AGP virtual memory operations */
static const struct vm_operations_struct drm_vm_ops = {
.fault = drm_vm_fault,
.open = drm_vm_open,
.close = drm_vm_close,
};
/** Shared virtual memory operations */
static const struct vm_operations_struct drm_vm_shm_ops = {
.fault = drm_vm_shm_fault,
.open = drm_vm_open,
.close = drm_vm_shm_close,
};
/** DMA virtual memory operations */
static const struct vm_operations_struct drm_vm_dma_ops = {
.fault = drm_vm_dma_fault,
.open = drm_vm_open,
.close = drm_vm_close,
};
/** Scatter-gather virtual memory operations */
static const struct vm_operations_struct drm_vm_sg_ops = {
.fault = drm_vm_sg_fault,
.open = drm_vm_open,
.close = drm_vm_close,
};
/**
* \c open method for shared virtual memory.
*
* \param vma virtual memory area.
*
* Create a new drm_vma_entry structure as the \p vma private data entry and
* add it to drm_device::vmalist.
*/
void drm_vm_open_locked(struct drm_device *dev,
struct vm_area_struct *vma)
{
struct drm_vma_entry *vma_entry;
DRM_DEBUG("0x%08lx,0x%08lx\n",
vma->vm_start, vma->vm_end - vma->vm_start);
atomic_inc(&dev->vma_count);
vma_entry = kmalloc(sizeof(*vma_entry), GFP_KERNEL);
if (vma_entry) {
vma_entry->vma = vma;
vma_entry->pid = current->pid;
list_add(&vma_entry->head, &dev->vmalist);
}
}
EXPORT_SYMBOL_GPL(drm_vm_open_locked);
static void drm_vm_open(struct vm_area_struct *vma)
{
struct drm_file *priv = vma->vm_file->private_data;
struct drm_device *dev = priv->minor->dev;
mutex_lock(&dev->struct_mutex);
drm_vm_open_locked(dev, vma);
mutex_unlock(&dev->struct_mutex);
}
void drm_vm_close_locked(struct drm_device *dev,
struct vm_area_struct *vma)
{
struct drm_vma_entry *pt, *temp;
DRM_DEBUG("0x%08lx,0x%08lx\n",
vma->vm_start, vma->vm_end - vma->vm_start);
atomic_dec(&dev->vma_count);
list_for_each_entry_safe(pt, temp, &dev->vmalist, head) {
if (pt->vma == vma) {
list_del(&pt->head);
kfree(pt);
break;
}
}
}
/**
* \c close method for all virtual memory types.
*
* \param vma virtual memory area.
*
* Search the \p vma private data entry in drm_device::vmalist, unlink it, and
* free it.
*/
static void drm_vm_close(struct vm_area_struct *vma)
{
struct drm_file *priv = vma->vm_file->private_data;
struct drm_device *dev = priv->minor->dev;
mutex_lock(&dev->struct_mutex);
drm_vm_close_locked(dev, vma);
mutex_unlock(&dev->struct_mutex);
}
/**
* mmap DMA memory.
*
* \param file_priv DRM file private.
* \param vma virtual memory area.
* \return zero on success or a negative number on failure.
*
* Sets the virtual memory area operations structure to vm_dma_ops, the file
* pointer, and calls vm_open().
*/
static int drm_mmap_dma(struct file *filp, struct vm_area_struct *vma)
{
struct drm_file *priv = filp->private_data;
struct drm_device *dev;
struct drm_device_dma *dma;
unsigned long length = vma->vm_end - vma->vm_start;
dev = priv->minor->dev;
dma = dev->dma;
DRM_DEBUG("start = 0x%lx, end = 0x%lx, page offset = 0x%lx\n",
vma->vm_start, vma->vm_end, vma->vm_pgoff);
/* Length must match exact page count */
if (!dma || (length >> PAGE_SHIFT) != dma->page_count) {
return -EINVAL;
}
if (!capable(CAP_SYS_ADMIN) &&
(dma->flags & _DRM_DMA_USE_PCI_RO)) {
vma->vm_flags &= ~(VM_WRITE | VM_MAYWRITE);
#if defined(__i386__) || defined(__x86_64__)
pgprot_val(vma->vm_page_prot) &= ~_PAGE_RW;
#else
/* Ye gads this is ugly. With more thought
we could move this up higher and use
`protection_map' instead. */
vma->vm_page_prot =
__pgprot(pte_val
(pte_wrprotect
(__pte(pgprot_val(vma->vm_page_prot)))));
#endif
}
vma->vm_ops = &drm_vm_dma_ops;
vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
drm_vm_open_locked(dev, vma);
return 0;
}
static resource_size_t drm_core_get_reg_ofs(struct drm_device *dev)
{
#ifdef __alpha__
return dev->hose->dense_mem_base;
#else
return 0;
#endif
}
/**
* mmap DMA memory.
*
* \param file_priv DRM file private.
* \param vma virtual memory area.
* \return zero on success or a negative number on failure.
*
* If the virtual memory area has no offset associated with it then it's a DMA
* area, so calls mmap_dma(). Otherwise searches the map in drm_device::maplist,
* checks that the restricted flag is not set, sets the virtual memory operations
* according to the mapping type and remaps the pages. Finally sets the file
* pointer and calls vm_open().
*/
int drm_mmap_locked(struct file *filp, struct vm_area_struct *vma)
{
struct drm_file *priv = filp->private_data;
struct drm_device *dev = priv->minor->dev;
struct drm_local_map *map = NULL;
resource_size_t offset = 0;
struct drm_hash_item *hash;
DRM_DEBUG("start = 0x%lx, end = 0x%lx, page offset = 0x%lx\n",
vma->vm_start, vma->vm_end, vma->vm_pgoff);
if (!priv->authenticated)
return -EACCES;
/* We check for "dma". On Apple's UniNorth, it's valid to have
* the AGP mapped at physical address 0
* --BenH.
*/
if (!vma->vm_pgoff
#if __OS_HAS_AGP
&& (!dev->agp
|| dev->agp->agp_info.device->vendor != PCI_VENDOR_ID_APPLE)
#endif
)
return drm_mmap_dma(filp, vma);
if (drm_ht_find_item(&dev->map_hash, vma->vm_pgoff, &hash)) {
DRM_ERROR("Could not find map\n");
return -EINVAL;
}
map = drm_hash_entry(hash, struct drm_map_list, hash)->map;
if (!map || ((map->flags & _DRM_RESTRICTED) && !capable(CAP_SYS_ADMIN)))
return -EPERM;
/* Check for valid size. */
if (map->size < vma->vm_end - vma->vm_start)
return -EINVAL;
if (!capable(CAP_SYS_ADMIN) && (map->flags & _DRM_READ_ONLY)) {
vma->vm_flags &= ~(VM_WRITE | VM_MAYWRITE);
#if defined(__i386__) || defined(__x86_64__)
pgprot_val(vma->vm_page_prot) &= ~_PAGE_RW;
#else
/* Ye gads this is ugly. With more thought
we could move this up higher and use
`protection_map' instead. */
vma->vm_page_prot =
__pgprot(pte_val
(pte_wrprotect
(__pte(pgprot_val(vma->vm_page_prot)))));
#endif
}
switch (map->type) {
#if !defined(__arm__)
case _DRM_AGP:
if (drm_core_has_AGP(dev) && dev->agp->cant_use_aperture) {
/*
* On some platforms we can't talk to bus dma address from the CPU, so for
* memory of type DRM_AGP, we'll deal with sorting out the real physical
* pages and mappings in fault()
*/
#if defined(__powerpc__)
pgprot_val(vma->vm_page_prot) |= _PAGE_NO_CACHE;
#endif
vma->vm_ops = &drm_vm_ops;
break;
}
/* fall through to _DRM_FRAME_BUFFER... */
#endif
case _DRM_FRAME_BUFFER:
case _DRM_REGISTERS:
offset = drm_core_get_reg_ofs(dev);
vma->vm_flags |= VM_IO; /* not in core dump */
vma->vm_page_prot = drm_io_prot(map->type, vma);
if (io_remap_pfn_range(vma, vma->vm_start,
(map->offset + offset) >> PAGE_SHIFT,
vma->vm_end - vma->vm_start,
vma->vm_page_prot))
return -EAGAIN;
DRM_DEBUG(" Type = %d; start = 0x%lx, end = 0x%lx,"
" offset = 0x%llx\n",
map->type,
vma->vm_start, vma->vm_end, (unsigned long long)(map->offset + offset));
vma->vm_ops = &drm_vm_ops;
break;
case _DRM_CONSISTENT:
/* Consistent memory is really like shared memory. But
* it's allocated in a different way, so avoid fault */
if (remap_pfn_range(vma, vma->vm_start,
page_to_pfn(virt_to_page(map->handle)),
vma->vm_end - vma->vm_start, vma->vm_page_prot))
return -EAGAIN;
vma->vm_page_prot = drm_dma_prot(map->type, vma);
/* fall through to _DRM_SHM */
case _DRM_SHM:
vma->vm_ops = &drm_vm_shm_ops;
vma->vm_private_data = (void *)map;
break;
case _DRM_SCATTER_GATHER:
vma->vm_ops = &drm_vm_sg_ops;
vma->vm_private_data = (void *)map;
vma->vm_page_prot = drm_dma_prot(map->type, vma);
break;
default:
return -EINVAL; /* This should never happen. */
}
vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
drm_vm_open_locked(dev, vma);
return 0;
}
int drm_mmap(struct file *filp, struct vm_area_struct *vma)
{
struct drm_file *priv = filp->private_data;
struct drm_device *dev = priv->minor->dev;
int ret;
if (drm_device_is_unplugged(dev))
return -ENODEV;
mutex_lock(&dev->struct_mutex);
ret = drm_mmap_locked(filp, vma);
mutex_unlock(&dev->struct_mutex);
return ret;
}
EXPORT_SYMBOL(drm_mmap);
| gpl-2.0 |
The-Demon12/msm8916 | drivers/watchdog/mtx-1_wdt.c | 2252 | 6447 | /*
* Driver for the MTX-1 Watchdog.
*
* (C) Copyright 2005 4G Systems <info@4g-systems.biz>,
* All Rights Reserved.
* http://www.4g-systems.biz
*
* (C) Copyright 2007 OpenWrt.org, Florian Fainelli <florian@openwrt.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Neither Michael Stickel nor 4G Systems admit liability nor provide
* warranty for any of this software. This material is provided
* "AS-IS" and at no charge.
*
* (c) Copyright 2005 4G Systems <info@4g-systems.biz>
*
* Release 0.01.
* Author: Michael Stickel michael.stickel@4g-systems.biz
*
* Release 0.02.
* Author: Florian Fainelli florian@openwrt.org
* use the Linux watchdog/timer APIs
*
* The Watchdog is configured to reset the MTX-1
* if it is not triggered for 100 seconds.
* It should not be triggered more often than 1.6 seconds.
*
* A timer triggers the watchdog every 5 seconds, until
* it is opened for the first time. After the first open
* it MUST be triggered every 2..95 seconds.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/miscdevice.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/timer.h>
#include <linux/completion.h>
#include <linux/jiffies.h>
#include <linux/watchdog.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include <linux/gpio.h>
#include <asm/mach-au1x00/au1000.h>
#define MTX1_WDT_INTERVAL (5 * HZ)
static int ticks = 100 * HZ;
static struct {
struct completion stop;
spinlock_t lock;
int running;
struct timer_list timer;
int queue;
int default_ticks;
unsigned long inuse;
unsigned gpio;
unsigned int gstate;
} mtx1_wdt_device;
static void mtx1_wdt_trigger(unsigned long unused)
{
spin_lock(&mtx1_wdt_device.lock);
if (mtx1_wdt_device.running)
ticks--;
/* toggle wdt gpio */
mtx1_wdt_device.gstate = !mtx1_wdt_device.gstate;
gpio_set_value(mtx1_wdt_device.gpio, mtx1_wdt_device.gstate);
if (mtx1_wdt_device.queue && ticks)
mod_timer(&mtx1_wdt_device.timer, jiffies + MTX1_WDT_INTERVAL);
else
complete(&mtx1_wdt_device.stop);
spin_unlock(&mtx1_wdt_device.lock);
}
static void mtx1_wdt_reset(void)
{
ticks = mtx1_wdt_device.default_ticks;
}
static void mtx1_wdt_start(void)
{
unsigned long flags;
spin_lock_irqsave(&mtx1_wdt_device.lock, flags);
if (!mtx1_wdt_device.queue) {
mtx1_wdt_device.queue = 1;
mtx1_wdt_device.gstate = 1;
gpio_set_value(mtx1_wdt_device.gpio, 1);
mod_timer(&mtx1_wdt_device.timer, jiffies + MTX1_WDT_INTERVAL);
}
mtx1_wdt_device.running++;
spin_unlock_irqrestore(&mtx1_wdt_device.lock, flags);
}
static int mtx1_wdt_stop(void)
{
unsigned long flags;
spin_lock_irqsave(&mtx1_wdt_device.lock, flags);
if (mtx1_wdt_device.queue) {
mtx1_wdt_device.queue = 0;
mtx1_wdt_device.gstate = 0;
gpio_set_value(mtx1_wdt_device.gpio, 0);
}
ticks = mtx1_wdt_device.default_ticks;
spin_unlock_irqrestore(&mtx1_wdt_device.lock, flags);
return 0;
}
/* Filesystem functions */
static int mtx1_wdt_open(struct inode *inode, struct file *file)
{
if (test_and_set_bit(0, &mtx1_wdt_device.inuse))
return -EBUSY;
return nonseekable_open(inode, file);
}
static int mtx1_wdt_release(struct inode *inode, struct file *file)
{
clear_bit(0, &mtx1_wdt_device.inuse);
return 0;
}
static long mtx1_wdt_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
void __user *argp = (void __user *)arg;
int __user *p = (int __user *)argp;
unsigned int value;
static const struct watchdog_info ident = {
.options = WDIOF_CARDRESET,
.identity = "MTX-1 WDT",
};
switch (cmd) {
case WDIOC_GETSUPPORT:
if (copy_to_user(argp, &ident, sizeof(ident)))
return -EFAULT;
break;
case WDIOC_GETSTATUS:
case WDIOC_GETBOOTSTATUS:
put_user(0, p);
break;
case WDIOC_SETOPTIONS:
if (get_user(value, p))
return -EFAULT;
if (value & WDIOS_ENABLECARD)
mtx1_wdt_start();
else if (value & WDIOS_DISABLECARD)
mtx1_wdt_stop();
else
return -EINVAL;
return 0;
case WDIOC_KEEPALIVE:
mtx1_wdt_reset();
break;
default:
return -ENOTTY;
}
return 0;
}
static ssize_t mtx1_wdt_write(struct file *file, const char *buf,
size_t count, loff_t *ppos)
{
if (!count)
return -EIO;
mtx1_wdt_reset();
return count;
}
static const struct file_operations mtx1_wdt_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.unlocked_ioctl = mtx1_wdt_ioctl,
.open = mtx1_wdt_open,
.write = mtx1_wdt_write,
.release = mtx1_wdt_release,
};
static struct miscdevice mtx1_wdt_misc = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &mtx1_wdt_fops,
};
static int mtx1_wdt_probe(struct platform_device *pdev)
{
int ret;
mtx1_wdt_device.gpio = pdev->resource[0].start;
ret = gpio_request_one(mtx1_wdt_device.gpio,
GPIOF_OUT_INIT_HIGH, "mtx1-wdt");
if (ret < 0) {
dev_err(&pdev->dev, "failed to request gpio");
return ret;
}
spin_lock_init(&mtx1_wdt_device.lock);
init_completion(&mtx1_wdt_device.stop);
mtx1_wdt_device.queue = 0;
clear_bit(0, &mtx1_wdt_device.inuse);
setup_timer(&mtx1_wdt_device.timer, mtx1_wdt_trigger, 0L);
mtx1_wdt_device.default_ticks = ticks;
ret = misc_register(&mtx1_wdt_misc);
if (ret < 0) {
dev_err(&pdev->dev, "failed to register\n");
return ret;
}
mtx1_wdt_start();
dev_info(&pdev->dev, "MTX-1 Watchdog driver\n");
return 0;
}
static int mtx1_wdt_remove(struct platform_device *pdev)
{
/* FIXME: do we need to lock this test ? */
if (mtx1_wdt_device.queue) {
mtx1_wdt_device.queue = 0;
wait_for_completion(&mtx1_wdt_device.stop);
}
gpio_free(mtx1_wdt_device.gpio);
misc_deregister(&mtx1_wdt_misc);
return 0;
}
static struct platform_driver mtx1_wdt_driver = {
.probe = mtx1_wdt_probe,
.remove = mtx1_wdt_remove,
.driver.name = "mtx1-wdt",
.driver.owner = THIS_MODULE,
};
module_platform_driver(mtx1_wdt_driver);
MODULE_AUTHOR("Michael Stickel, Florian Fainelli");
MODULE_DESCRIPTION("Driver for the MTX-1 watchdog");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
MODULE_ALIAS("platform:mtx1-wdt");
| gpl-2.0 |
visi0nary/mt6735-kernel-3.10.61 | drivers/video/omap2/dss/display-sysfs.c | 2252 | 7799 | /*
* Copyright (C) 2009 Nokia Corporation
* Author: Tomi Valkeinen <tomi.valkeinen@nokia.com>
*
* Some code and ideas taken from drivers/video/omap/ driver
* by Imre Deak.
*
* 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/>.
*/
#define DSS_SUBSYS_NAME "DISPLAY"
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/jiffies.h>
#include <linux/platform_device.h>
#include <video/omapdss.h>
#include "dss.h"
#include "dss_features.h"
static ssize_t display_enabled_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
bool enabled = dssdev->state != OMAP_DSS_DISPLAY_DISABLED;
return snprintf(buf, PAGE_SIZE, "%d\n", enabled);
}
static ssize_t display_enabled_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
int r;
bool enabled;
r = strtobool(buf, &enabled);
if (r)
return r;
if (enabled != (dssdev->state != OMAP_DSS_DISPLAY_DISABLED)) {
if (enabled) {
r = dssdev->driver->enable(dssdev);
if (r)
return r;
} else {
dssdev->driver->disable(dssdev);
}
}
return size;
}
static ssize_t display_tear_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
return snprintf(buf, PAGE_SIZE, "%d\n",
dssdev->driver->get_te ?
dssdev->driver->get_te(dssdev) : 0);
}
static ssize_t display_tear_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
int r;
bool te;
if (!dssdev->driver->enable_te || !dssdev->driver->get_te)
return -ENOENT;
r = strtobool(buf, &te);
if (r)
return r;
r = dssdev->driver->enable_te(dssdev, te);
if (r)
return r;
return size;
}
static ssize_t display_timings_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
struct omap_video_timings t;
if (!dssdev->driver->get_timings)
return -ENOENT;
dssdev->driver->get_timings(dssdev, &t);
return snprintf(buf, PAGE_SIZE, "%u,%u/%u/%u/%u,%u/%u/%u/%u\n",
t.pixel_clock,
t.x_res, t.hfp, t.hbp, t.hsw,
t.y_res, t.vfp, t.vbp, t.vsw);
}
static ssize_t display_timings_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
struct omap_video_timings t = dssdev->panel.timings;
int r, found;
if (!dssdev->driver->set_timings || !dssdev->driver->check_timings)
return -ENOENT;
found = 0;
#ifdef CONFIG_OMAP2_DSS_VENC
if (strncmp("pal", buf, 3) == 0) {
t = omap_dss_pal_timings;
found = 1;
} else if (strncmp("ntsc", buf, 4) == 0) {
t = omap_dss_ntsc_timings;
found = 1;
}
#endif
if (!found && sscanf(buf, "%u,%hu/%hu/%hu/%hu,%hu/%hu/%hu/%hu",
&t.pixel_clock,
&t.x_res, &t.hfp, &t.hbp, &t.hsw,
&t.y_res, &t.vfp, &t.vbp, &t.vsw) != 9)
return -EINVAL;
r = dssdev->driver->check_timings(dssdev, &t);
if (r)
return r;
dssdev->driver->disable(dssdev);
dssdev->driver->set_timings(dssdev, &t);
r = dssdev->driver->enable(dssdev);
if (r)
return r;
return size;
}
static ssize_t display_rotate_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
int rotate;
if (!dssdev->driver->get_rotate)
return -ENOENT;
rotate = dssdev->driver->get_rotate(dssdev);
return snprintf(buf, PAGE_SIZE, "%u\n", rotate);
}
static ssize_t display_rotate_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
int rot, r;
if (!dssdev->driver->set_rotate || !dssdev->driver->get_rotate)
return -ENOENT;
r = kstrtoint(buf, 0, &rot);
if (r)
return r;
r = dssdev->driver->set_rotate(dssdev, rot);
if (r)
return r;
return size;
}
static ssize_t display_mirror_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
int mirror;
if (!dssdev->driver->get_mirror)
return -ENOENT;
mirror = dssdev->driver->get_mirror(dssdev);
return snprintf(buf, PAGE_SIZE, "%u\n", mirror);
}
static ssize_t display_mirror_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
int r;
bool mirror;
if (!dssdev->driver->set_mirror || !dssdev->driver->get_mirror)
return -ENOENT;
r = strtobool(buf, &mirror);
if (r)
return r;
r = dssdev->driver->set_mirror(dssdev, mirror);
if (r)
return r;
return size;
}
static ssize_t display_wss_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
unsigned int wss;
if (!dssdev->driver->get_wss)
return -ENOENT;
wss = dssdev->driver->get_wss(dssdev);
return snprintf(buf, PAGE_SIZE, "0x%05x\n", wss);
}
static ssize_t display_wss_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct omap_dss_device *dssdev = to_dss_device(dev);
u32 wss;
int r;
if (!dssdev->driver->get_wss || !dssdev->driver->set_wss)
return -ENOENT;
r = kstrtou32(buf, 0, &wss);
if (r)
return r;
if (wss > 0xfffff)
return -EINVAL;
r = dssdev->driver->set_wss(dssdev, wss);
if (r)
return r;
return size;
}
static DEVICE_ATTR(enabled, S_IRUGO|S_IWUSR,
display_enabled_show, display_enabled_store);
static DEVICE_ATTR(tear_elim, S_IRUGO|S_IWUSR,
display_tear_show, display_tear_store);
static DEVICE_ATTR(timings, S_IRUGO|S_IWUSR,
display_timings_show, display_timings_store);
static DEVICE_ATTR(rotate, S_IRUGO|S_IWUSR,
display_rotate_show, display_rotate_store);
static DEVICE_ATTR(mirror, S_IRUGO|S_IWUSR,
display_mirror_show, display_mirror_store);
static DEVICE_ATTR(wss, S_IRUGO|S_IWUSR,
display_wss_show, display_wss_store);
static struct device_attribute *display_sysfs_attrs[] = {
&dev_attr_enabled,
&dev_attr_tear_elim,
&dev_attr_timings,
&dev_attr_rotate,
&dev_attr_mirror,
&dev_attr_wss,
NULL
};
int display_init_sysfs(struct platform_device *pdev,
struct omap_dss_device *dssdev)
{
struct device_attribute *attr;
int i, r;
/* create device sysfs files */
i = 0;
while ((attr = display_sysfs_attrs[i++]) != NULL) {
r = device_create_file(&dssdev->dev, attr);
if (r) {
for (i = i - 2; i >= 0; i--) {
attr = display_sysfs_attrs[i];
device_remove_file(&dssdev->dev, attr);
}
DSSERR("failed to create sysfs file\n");
return r;
}
}
/* create display? sysfs links */
r = sysfs_create_link(&pdev->dev.kobj, &dssdev->dev.kobj,
dev_name(&dssdev->dev));
if (r) {
while ((attr = display_sysfs_attrs[i++]) != NULL)
device_remove_file(&dssdev->dev, attr);
DSSERR("failed to create sysfs display link\n");
return r;
}
return 0;
}
void display_uninit_sysfs(struct platform_device *pdev,
struct omap_dss_device *dssdev)
{
struct device_attribute *attr;
int i = 0;
sysfs_remove_link(&pdev->dev.kobj, dev_name(&dssdev->dev));
while ((attr = display_sysfs_attrs[i++]) != NULL)
device_remove_file(&dssdev->dev, attr);
}
| gpl-2.0 |
semdoc/kernel_moto_shamu | arch/powerpc/sysdev/mpic_msgr.c | 2252 | 7032 | /*
* Copyright 2011-2012, Meador Inge, Mentor Graphics Corporation.
*
* Some ideas based on un-pushed work done by Vivek Mahajan, Jason Jin, and
* Mingkai Hu from Freescale Semiconductor, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2 of the
* License.
*
*/
#include <linux/list.h>
#include <linux/of_platform.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/export.h>
#include <linux/slab.h>
#include <asm/prom.h>
#include <asm/hw_irq.h>
#include <asm/ppc-pci.h>
#include <asm/mpic_msgr.h>
#define MPIC_MSGR_REGISTERS_PER_BLOCK 4
#define MPIC_MSGR_STRIDE 0x10
#define MPIC_MSGR_MER_OFFSET 0x100
#define MSGR_INUSE 0
#define MSGR_FREE 1
static struct mpic_msgr **mpic_msgrs;
static unsigned int mpic_msgr_count;
static DEFINE_RAW_SPINLOCK(msgrs_lock);
static inline void _mpic_msgr_mer_write(struct mpic_msgr *msgr, u32 value)
{
out_be32(msgr->mer, value);
}
static inline u32 _mpic_msgr_mer_read(struct mpic_msgr *msgr)
{
return in_be32(msgr->mer);
}
static inline void _mpic_msgr_disable(struct mpic_msgr *msgr)
{
u32 mer = _mpic_msgr_mer_read(msgr);
_mpic_msgr_mer_write(msgr, mer & ~(1 << msgr->num));
}
struct mpic_msgr *mpic_msgr_get(unsigned int reg_num)
{
unsigned long flags;
struct mpic_msgr *msgr;
/* Assume busy until proven otherwise. */
msgr = ERR_PTR(-EBUSY);
if (reg_num >= mpic_msgr_count)
return ERR_PTR(-ENODEV);
raw_spin_lock_irqsave(&msgrs_lock, flags);
msgr = mpic_msgrs[reg_num];
if (msgr->in_use == MSGR_FREE)
msgr->in_use = MSGR_INUSE;
raw_spin_unlock_irqrestore(&msgrs_lock, flags);
return msgr;
}
EXPORT_SYMBOL_GPL(mpic_msgr_get);
void mpic_msgr_put(struct mpic_msgr *msgr)
{
unsigned long flags;
raw_spin_lock_irqsave(&msgr->lock, flags);
msgr->in_use = MSGR_FREE;
_mpic_msgr_disable(msgr);
raw_spin_unlock_irqrestore(&msgr->lock, flags);
}
EXPORT_SYMBOL_GPL(mpic_msgr_put);
void mpic_msgr_enable(struct mpic_msgr *msgr)
{
unsigned long flags;
u32 mer;
raw_spin_lock_irqsave(&msgr->lock, flags);
mer = _mpic_msgr_mer_read(msgr);
_mpic_msgr_mer_write(msgr, mer | (1 << msgr->num));
raw_spin_unlock_irqrestore(&msgr->lock, flags);
}
EXPORT_SYMBOL_GPL(mpic_msgr_enable);
void mpic_msgr_disable(struct mpic_msgr *msgr)
{
unsigned long flags;
raw_spin_lock_irqsave(&msgr->lock, flags);
_mpic_msgr_disable(msgr);
raw_spin_unlock_irqrestore(&msgr->lock, flags);
}
EXPORT_SYMBOL_GPL(mpic_msgr_disable);
/* The following three functions are used to compute the order and number of
* the message register blocks. They are clearly very inefficent. However,
* they are called *only* a few times during device initialization.
*/
static unsigned int mpic_msgr_number_of_blocks(void)
{
unsigned int count;
struct device_node *aliases;
count = 0;
aliases = of_find_node_by_name(NULL, "aliases");
if (aliases) {
char buf[32];
for (;;) {
snprintf(buf, sizeof(buf), "mpic-msgr-block%d", count);
if (!of_find_property(aliases, buf, NULL))
break;
count += 1;
}
}
return count;
}
static unsigned int mpic_msgr_number_of_registers(void)
{
return mpic_msgr_number_of_blocks() * MPIC_MSGR_REGISTERS_PER_BLOCK;
}
static int mpic_msgr_block_number(struct device_node *node)
{
struct device_node *aliases;
unsigned int index, number_of_blocks;
char buf[64];
number_of_blocks = mpic_msgr_number_of_blocks();
aliases = of_find_node_by_name(NULL, "aliases");
if (!aliases)
return -1;
for (index = 0; index < number_of_blocks; ++index) {
struct property *prop;
snprintf(buf, sizeof(buf), "mpic-msgr-block%d", index);
prop = of_find_property(aliases, buf, NULL);
if (node == of_find_node_by_path(prop->value))
break;
}
return index == number_of_blocks ? -1 : index;
}
/* The probe function for a single message register block.
*/
static int mpic_msgr_probe(struct platform_device *dev)
{
void __iomem *msgr_block_addr;
int block_number;
struct resource rsrc;
unsigned int i;
unsigned int irq_index;
struct device_node *np = dev->dev.of_node;
unsigned int receive_mask;
const unsigned int *prop;
if (!np) {
dev_err(&dev->dev, "Device OF-Node is NULL");
return -EFAULT;
}
/* Allocate the message register array upon the first device
* registered.
*/
if (!mpic_msgrs) {
mpic_msgr_count = mpic_msgr_number_of_registers();
dev_info(&dev->dev, "Found %d message registers\n",
mpic_msgr_count);
mpic_msgrs = kzalloc(sizeof(struct mpic_msgr) * mpic_msgr_count,
GFP_KERNEL);
if (!mpic_msgrs) {
dev_err(&dev->dev,
"No memory for message register blocks\n");
return -ENOMEM;
}
}
dev_info(&dev->dev, "Of-device full name %s\n", np->full_name);
/* IO map the message register block. */
of_address_to_resource(np, 0, &rsrc);
msgr_block_addr = ioremap(rsrc.start, rsrc.end - rsrc.start);
if (!msgr_block_addr) {
dev_err(&dev->dev, "Failed to iomap MPIC message registers");
return -EFAULT;
}
/* Ensure the block has a defined order. */
block_number = mpic_msgr_block_number(np);
if (block_number < 0) {
dev_err(&dev->dev,
"Failed to find message register block alias\n");
return -ENODEV;
}
dev_info(&dev->dev, "Setting up message register block %d\n",
block_number);
/* Grab the receive mask which specifies what registers can receive
* interrupts.
*/
prop = of_get_property(np, "mpic-msgr-receive-mask", NULL);
receive_mask = (prop) ? *prop : 0xF;
/* Build up the appropriate message register data structures. */
for (i = 0, irq_index = 0; i < MPIC_MSGR_REGISTERS_PER_BLOCK; ++i) {
struct mpic_msgr *msgr;
unsigned int reg_number;
msgr = kzalloc(sizeof(struct mpic_msgr), GFP_KERNEL);
if (!msgr) {
dev_err(&dev->dev, "No memory for message register\n");
return -ENOMEM;
}
reg_number = block_number * MPIC_MSGR_REGISTERS_PER_BLOCK + i;
msgr->base = msgr_block_addr + i * MPIC_MSGR_STRIDE;
msgr->mer = (u32 *)((u8 *)msgr->base + MPIC_MSGR_MER_OFFSET);
msgr->in_use = MSGR_FREE;
msgr->num = i;
raw_spin_lock_init(&msgr->lock);
if (receive_mask & (1 << i)) {
struct resource irq;
if (of_irq_to_resource(np, irq_index, &irq) == NO_IRQ) {
dev_err(&dev->dev,
"Missing interrupt specifier");
kfree(msgr);
return -EFAULT;
}
msgr->irq = irq.start;
irq_index += 1;
} else {
msgr->irq = NO_IRQ;
}
mpic_msgrs[reg_number] = msgr;
mpic_msgr_disable(msgr);
dev_info(&dev->dev, "Register %d initialized: irq %d\n",
reg_number, msgr->irq);
}
return 0;
}
static const struct of_device_id mpic_msgr_ids[] = {
{
.compatible = "fsl,mpic-v3.1-msgr",
.data = NULL,
},
{}
};
static struct platform_driver mpic_msgr_driver = {
.driver = {
.name = "mpic-msgr",
.owner = THIS_MODULE,
.of_match_table = mpic_msgr_ids,
},
.probe = mpic_msgr_probe,
};
static __init int mpic_msgr_init(void)
{
return platform_driver_register(&mpic_msgr_driver);
}
subsys_initcall(mpic_msgr_init);
| gpl-2.0 |
Kali-/android_kernel_sony_msm8974 | drivers/net/ethernet/oki-semi/pch_gbe/pch_gbe_main.c | 3276 | 79102 | /*
* Copyright (C) 1999 - 2010 Intel Corporation.
* Copyright (C) 2010 - 2012 LAPIS SEMICONDUCTOR CO., LTD.
*
* This code was derived from the Intel e1000e Linux driver.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include "pch_gbe.h"
#include "pch_gbe_api.h"
#include <linux/module.h>
#ifdef CONFIG_PCH_PTP
#include <linux/net_tstamp.h>
#include <linux/ptp_classify.h>
#endif
#define DRV_VERSION "1.00"
const char pch_driver_version[] = DRV_VERSION;
#define PCI_DEVICE_ID_INTEL_IOH1_GBE 0x8802 /* Pci device ID */
#define PCH_GBE_MAR_ENTRIES 16
#define PCH_GBE_SHORT_PKT 64
#define DSC_INIT16 0xC000
#define PCH_GBE_DMA_ALIGN 0
#define PCH_GBE_DMA_PADDING 2
#define PCH_GBE_WATCHDOG_PERIOD (1 * HZ) /* watchdog time */
#define PCH_GBE_COPYBREAK_DEFAULT 256
#define PCH_GBE_PCI_BAR 1
#define PCH_GBE_RESERVE_MEMORY 0x200000 /* 2MB */
/* Macros for ML7223 */
#define PCI_VENDOR_ID_ROHM 0x10db
#define PCI_DEVICE_ID_ROHM_ML7223_GBE 0x8013
/* Macros for ML7831 */
#define PCI_DEVICE_ID_ROHM_ML7831_GBE 0x8802
#define PCH_GBE_TX_WEIGHT 64
#define PCH_GBE_RX_WEIGHT 64
#define PCH_GBE_RX_BUFFER_WRITE 16
/* Initialize the wake-on-LAN settings */
#define PCH_GBE_WL_INIT_SETTING (PCH_GBE_WLC_MP)
#define PCH_GBE_MAC_RGMII_CTRL_SETTING ( \
PCH_GBE_CHIP_TYPE_INTERNAL | \
PCH_GBE_RGMII_MODE_RGMII \
)
/* Ethertype field values */
#define PCH_GBE_MAX_RX_BUFFER_SIZE 0x2880
#define PCH_GBE_MAX_JUMBO_FRAME_SIZE 10318
#define PCH_GBE_FRAME_SIZE_2048 2048
#define PCH_GBE_FRAME_SIZE_4096 4096
#define PCH_GBE_FRAME_SIZE_8192 8192
#define PCH_GBE_GET_DESC(R, i, type) (&(((struct type *)((R).desc))[i]))
#define PCH_GBE_RX_DESC(R, i) PCH_GBE_GET_DESC(R, i, pch_gbe_rx_desc)
#define PCH_GBE_TX_DESC(R, i) PCH_GBE_GET_DESC(R, i, pch_gbe_tx_desc)
#define PCH_GBE_DESC_UNUSED(R) \
((((R)->next_to_clean > (R)->next_to_use) ? 0 : (R)->count) + \
(R)->next_to_clean - (R)->next_to_use - 1)
/* Pause packet value */
#define PCH_GBE_PAUSE_PKT1_VALUE 0x00C28001
#define PCH_GBE_PAUSE_PKT2_VALUE 0x00000100
#define PCH_GBE_PAUSE_PKT4_VALUE 0x01000888
#define PCH_GBE_PAUSE_PKT5_VALUE 0x0000FFFF
#define PCH_GBE_ETH_ALEN 6
/* This defines the bits that are set in the Interrupt Mask
* Set/Read Register. Each bit is documented below:
* o RXT0 = Receiver Timer Interrupt (ring 0)
* o TXDW = Transmit Descriptor Written Back
* o RXDMT0 = Receive Descriptor Minimum Threshold hit (ring 0)
* o RXSEQ = Receive Sequence Error
* o LSC = Link Status Change
*/
#define PCH_GBE_INT_ENABLE_MASK ( \
PCH_GBE_INT_RX_DMA_CMPLT | \
PCH_GBE_INT_RX_DSC_EMP | \
PCH_GBE_INT_RX_FIFO_ERR | \
PCH_GBE_INT_WOL_DET | \
PCH_GBE_INT_TX_CMPLT \
)
#define PCH_GBE_INT_DISABLE_ALL 0
#ifdef CONFIG_PCH_PTP
/* Macros for ieee1588 */
#define TICKS_NS_SHIFT 5
/* 0x40 Time Synchronization Channel Control Register Bits */
#define MASTER_MODE (1<<0)
#define SLAVE_MODE (0<<0)
#define V2_MODE (1<<31)
#define CAP_MODE0 (0<<16)
#define CAP_MODE2 (1<<17)
/* 0x44 Time Synchronization Channel Event Register Bits */
#define TX_SNAPSHOT_LOCKED (1<<0)
#define RX_SNAPSHOT_LOCKED (1<<1)
#endif
static unsigned int copybreak __read_mostly = PCH_GBE_COPYBREAK_DEFAULT;
static int pch_gbe_mdio_read(struct net_device *netdev, int addr, int reg);
static void pch_gbe_mdio_write(struct net_device *netdev, int addr, int reg,
int data);
#ifdef CONFIG_PCH_PTP
static struct sock_filter ptp_filter[] = {
PTP_FILTER
};
static int pch_ptp_match(struct sk_buff *skb, u16 uid_hi, u32 uid_lo, u16 seqid)
{
u8 *data = skb->data;
unsigned int offset;
u16 *hi, *id;
u32 lo;
if ((sk_run_filter(skb, ptp_filter) != PTP_CLASS_V2_IPV4) &&
(sk_run_filter(skb, ptp_filter) != PTP_CLASS_V1_IPV4)) {
return 0;
}
offset = ETH_HLEN + IPV4_HLEN(data) + UDP_HLEN;
if (skb->len < offset + OFF_PTP_SEQUENCE_ID + sizeof(seqid))
return 0;
hi = (u16 *)(data + offset + OFF_PTP_SOURCE_UUID);
id = (u16 *)(data + offset + OFF_PTP_SEQUENCE_ID);
memcpy(&lo, &hi[1], sizeof(lo));
return (uid_hi == *hi &&
uid_lo == lo &&
seqid == *id);
}
static void pch_rx_timestamp(
struct pch_gbe_adapter *adapter, struct sk_buff *skb)
{
struct skb_shared_hwtstamps *shhwtstamps;
struct pci_dev *pdev;
u64 ns;
u32 hi, lo, val;
u16 uid, seq;
if (!adapter->hwts_rx_en)
return;
/* Get ieee1588's dev information */
pdev = adapter->ptp_pdev;
val = pch_ch_event_read(pdev);
if (!(val & RX_SNAPSHOT_LOCKED))
return;
lo = pch_src_uuid_lo_read(pdev);
hi = pch_src_uuid_hi_read(pdev);
uid = hi & 0xffff;
seq = (hi >> 16) & 0xffff;
if (!pch_ptp_match(skb, htons(uid), htonl(lo), htons(seq)))
goto out;
ns = pch_rx_snap_read(pdev);
ns <<= TICKS_NS_SHIFT;
shhwtstamps = skb_hwtstamps(skb);
memset(shhwtstamps, 0, sizeof(*shhwtstamps));
shhwtstamps->hwtstamp = ns_to_ktime(ns);
out:
pch_ch_event_write(pdev, RX_SNAPSHOT_LOCKED);
}
static void pch_tx_timestamp(
struct pch_gbe_adapter *adapter, struct sk_buff *skb)
{
struct skb_shared_hwtstamps shhwtstamps;
struct pci_dev *pdev;
struct skb_shared_info *shtx;
u64 ns;
u32 cnt, val;
shtx = skb_shinfo(skb);
if (unlikely(shtx->tx_flags & SKBTX_HW_TSTAMP && adapter->hwts_tx_en))
shtx->tx_flags |= SKBTX_IN_PROGRESS;
else
return;
/* Get ieee1588's dev information */
pdev = adapter->ptp_pdev;
/*
* This really stinks, but we have to poll for the Tx time stamp.
* Usually, the time stamp is ready after 4 to 6 microseconds.
*/
for (cnt = 0; cnt < 100; cnt++) {
val = pch_ch_event_read(pdev);
if (val & TX_SNAPSHOT_LOCKED)
break;
udelay(1);
}
if (!(val & TX_SNAPSHOT_LOCKED)) {
shtx->tx_flags &= ~SKBTX_IN_PROGRESS;
return;
}
ns = pch_tx_snap_read(pdev);
ns <<= TICKS_NS_SHIFT;
memset(&shhwtstamps, 0, sizeof(shhwtstamps));
shhwtstamps.hwtstamp = ns_to_ktime(ns);
skb_tstamp_tx(skb, &shhwtstamps);
pch_ch_event_write(pdev, TX_SNAPSHOT_LOCKED);
}
static int hwtstamp_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
struct hwtstamp_config cfg;
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pci_dev *pdev;
if (copy_from_user(&cfg, ifr->ifr_data, sizeof(cfg)))
return -EFAULT;
if (cfg.flags) /* reserved for future extensions */
return -EINVAL;
/* Get ieee1588's dev information */
pdev = adapter->ptp_pdev;
switch (cfg.tx_type) {
case HWTSTAMP_TX_OFF:
adapter->hwts_tx_en = 0;
break;
case HWTSTAMP_TX_ON:
adapter->hwts_tx_en = 1;
break;
default:
return -ERANGE;
}
switch (cfg.rx_filter) {
case HWTSTAMP_FILTER_NONE:
adapter->hwts_rx_en = 0;
break;
case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
adapter->hwts_rx_en = 0;
pch_ch_control_write(pdev, (SLAVE_MODE | CAP_MODE0));
break;
case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
adapter->hwts_rx_en = 1;
pch_ch_control_write(pdev, (MASTER_MODE | CAP_MODE0));
break;
case HWTSTAMP_FILTER_PTP_V2_EVENT:
adapter->hwts_rx_en = 1;
pch_ch_control_write(pdev, (V2_MODE | CAP_MODE2));
break;
default:
return -ERANGE;
}
/* Clear out any old time stamps. */
pch_ch_event_write(pdev, TX_SNAPSHOT_LOCKED | RX_SNAPSHOT_LOCKED);
return copy_to_user(ifr->ifr_data, &cfg, sizeof(cfg)) ? -EFAULT : 0;
}
#endif
inline void pch_gbe_mac_load_mac_addr(struct pch_gbe_hw *hw)
{
iowrite32(0x01, &hw->reg->MAC_ADDR_LOAD);
}
/**
* pch_gbe_mac_read_mac_addr - Read MAC address
* @hw: Pointer to the HW structure
* Returns
* 0: Successful.
*/
s32 pch_gbe_mac_read_mac_addr(struct pch_gbe_hw *hw)
{
u32 adr1a, adr1b;
adr1a = ioread32(&hw->reg->mac_adr[0].high);
adr1b = ioread32(&hw->reg->mac_adr[0].low);
hw->mac.addr[0] = (u8)(adr1a & 0xFF);
hw->mac.addr[1] = (u8)((adr1a >> 8) & 0xFF);
hw->mac.addr[2] = (u8)((adr1a >> 16) & 0xFF);
hw->mac.addr[3] = (u8)((adr1a >> 24) & 0xFF);
hw->mac.addr[4] = (u8)(adr1b & 0xFF);
hw->mac.addr[5] = (u8)((adr1b >> 8) & 0xFF);
pr_debug("hw->mac.addr : %pM\n", hw->mac.addr);
return 0;
}
/**
* pch_gbe_wait_clr_bit - Wait to clear a bit
* @reg: Pointer of register
* @busy: Busy bit
*/
static void pch_gbe_wait_clr_bit(void *reg, u32 bit)
{
u32 tmp;
/* wait busy */
tmp = 1000;
while ((ioread32(reg) & bit) && --tmp)
cpu_relax();
if (!tmp)
pr_err("Error: busy bit is not cleared\n");
}
/**
* pch_gbe_wait_clr_bit_irq - Wait to clear a bit for interrupt context
* @reg: Pointer of register
* @busy: Busy bit
*/
static int pch_gbe_wait_clr_bit_irq(void *reg, u32 bit)
{
u32 tmp;
int ret = -1;
/* wait busy */
tmp = 20;
while ((ioread32(reg) & bit) && --tmp)
udelay(5);
if (!tmp)
pr_err("Error: busy bit is not cleared\n");
else
ret = 0;
return ret;
}
/**
* pch_gbe_mac_mar_set - Set MAC address register
* @hw: Pointer to the HW structure
* @addr: Pointer to the MAC address
* @index: MAC address array register
*/
static void pch_gbe_mac_mar_set(struct pch_gbe_hw *hw, u8 * addr, u32 index)
{
u32 mar_low, mar_high, adrmask;
pr_debug("index : 0x%x\n", index);
/*
* HW expects these in little endian so we reverse the byte order
* from network order (big endian) to little endian
*/
mar_high = ((u32) addr[0] | ((u32) addr[1] << 8) |
((u32) addr[2] << 16) | ((u32) addr[3] << 24));
mar_low = ((u32) addr[4] | ((u32) addr[5] << 8));
/* Stop the MAC Address of index. */
adrmask = ioread32(&hw->reg->ADDR_MASK);
iowrite32((adrmask | (0x0001 << index)), &hw->reg->ADDR_MASK);
/* wait busy */
pch_gbe_wait_clr_bit(&hw->reg->ADDR_MASK, PCH_GBE_BUSY);
/* Set the MAC address to the MAC address 1A/1B register */
iowrite32(mar_high, &hw->reg->mac_adr[index].high);
iowrite32(mar_low, &hw->reg->mac_adr[index].low);
/* Start the MAC address of index */
iowrite32((adrmask & ~(0x0001 << index)), &hw->reg->ADDR_MASK);
/* wait busy */
pch_gbe_wait_clr_bit(&hw->reg->ADDR_MASK, PCH_GBE_BUSY);
}
/**
* pch_gbe_mac_reset_hw - Reset hardware
* @hw: Pointer to the HW structure
*/
static void pch_gbe_mac_reset_hw(struct pch_gbe_hw *hw)
{
/* Read the MAC address. and store to the private data */
pch_gbe_mac_read_mac_addr(hw);
iowrite32(PCH_GBE_ALL_RST, &hw->reg->RESET);
#ifdef PCH_GBE_MAC_IFOP_RGMII
iowrite32(PCH_GBE_MODE_GMII_ETHER, &hw->reg->MODE);
#endif
pch_gbe_wait_clr_bit(&hw->reg->RESET, PCH_GBE_ALL_RST);
/* Setup the receive address */
pch_gbe_mac_mar_set(hw, hw->mac.addr, 0);
return;
}
static void pch_gbe_mac_reset_rx(struct pch_gbe_hw *hw)
{
/* Read the MAC address. and store to the private data */
pch_gbe_mac_read_mac_addr(hw);
iowrite32(PCH_GBE_RX_RST, &hw->reg->RESET);
pch_gbe_wait_clr_bit_irq(&hw->reg->RESET, PCH_GBE_RX_RST);
/* Setup the MAC address */
pch_gbe_mac_mar_set(hw, hw->mac.addr, 0);
return;
}
/**
* pch_gbe_mac_init_rx_addrs - Initialize receive address's
* @hw: Pointer to the HW structure
* @mar_count: Receive address registers
*/
static void pch_gbe_mac_init_rx_addrs(struct pch_gbe_hw *hw, u16 mar_count)
{
u32 i;
/* Setup the receive address */
pch_gbe_mac_mar_set(hw, hw->mac.addr, 0);
/* Zero out the other receive addresses */
for (i = 1; i < mar_count; i++) {
iowrite32(0, &hw->reg->mac_adr[i].high);
iowrite32(0, &hw->reg->mac_adr[i].low);
}
iowrite32(0xFFFE, &hw->reg->ADDR_MASK);
/* wait busy */
pch_gbe_wait_clr_bit(&hw->reg->ADDR_MASK, PCH_GBE_BUSY);
}
/**
* pch_gbe_mac_mc_addr_list_update - Update Multicast addresses
* @hw: Pointer to the HW structure
* @mc_addr_list: Array of multicast addresses to program
* @mc_addr_count: Number of multicast addresses to program
* @mar_used_count: The first MAC Address register free to program
* @mar_total_num: Total number of supported MAC Address Registers
*/
static void pch_gbe_mac_mc_addr_list_update(struct pch_gbe_hw *hw,
u8 *mc_addr_list, u32 mc_addr_count,
u32 mar_used_count, u32 mar_total_num)
{
u32 i, adrmask;
/* Load the first set of multicast addresses into the exact
* filters (RAR). If there are not enough to fill the RAR
* array, clear the filters.
*/
for (i = mar_used_count; i < mar_total_num; i++) {
if (mc_addr_count) {
pch_gbe_mac_mar_set(hw, mc_addr_list, i);
mc_addr_count--;
mc_addr_list += PCH_GBE_ETH_ALEN;
} else {
/* Clear MAC address mask */
adrmask = ioread32(&hw->reg->ADDR_MASK);
iowrite32((adrmask | (0x0001 << i)),
&hw->reg->ADDR_MASK);
/* wait busy */
pch_gbe_wait_clr_bit(&hw->reg->ADDR_MASK, PCH_GBE_BUSY);
/* Clear MAC address */
iowrite32(0, &hw->reg->mac_adr[i].high);
iowrite32(0, &hw->reg->mac_adr[i].low);
}
}
}
/**
* pch_gbe_mac_force_mac_fc - Force the MAC's flow control settings
* @hw: Pointer to the HW structure
* Returns
* 0: Successful.
* Negative value: Failed.
*/
s32 pch_gbe_mac_force_mac_fc(struct pch_gbe_hw *hw)
{
struct pch_gbe_mac_info *mac = &hw->mac;
u32 rx_fctrl;
pr_debug("mac->fc = %u\n", mac->fc);
rx_fctrl = ioread32(&hw->reg->RX_FCTRL);
switch (mac->fc) {
case PCH_GBE_FC_NONE:
rx_fctrl &= ~PCH_GBE_FL_CTRL_EN;
mac->tx_fc_enable = false;
break;
case PCH_GBE_FC_RX_PAUSE:
rx_fctrl |= PCH_GBE_FL_CTRL_EN;
mac->tx_fc_enable = false;
break;
case PCH_GBE_FC_TX_PAUSE:
rx_fctrl &= ~PCH_GBE_FL_CTRL_EN;
mac->tx_fc_enable = true;
break;
case PCH_GBE_FC_FULL:
rx_fctrl |= PCH_GBE_FL_CTRL_EN;
mac->tx_fc_enable = true;
break;
default:
pr_err("Flow control param set incorrectly\n");
return -EINVAL;
}
if (mac->link_duplex == DUPLEX_HALF)
rx_fctrl &= ~PCH_GBE_FL_CTRL_EN;
iowrite32(rx_fctrl, &hw->reg->RX_FCTRL);
pr_debug("RX_FCTRL reg : 0x%08x mac->tx_fc_enable : %d\n",
ioread32(&hw->reg->RX_FCTRL), mac->tx_fc_enable);
return 0;
}
/**
* pch_gbe_mac_set_wol_event - Set wake-on-lan event
* @hw: Pointer to the HW structure
* @wu_evt: Wake up event
*/
static void pch_gbe_mac_set_wol_event(struct pch_gbe_hw *hw, u32 wu_evt)
{
u32 addr_mask;
pr_debug("wu_evt : 0x%08x ADDR_MASK reg : 0x%08x\n",
wu_evt, ioread32(&hw->reg->ADDR_MASK));
if (wu_evt) {
/* Set Wake-On-Lan address mask */
addr_mask = ioread32(&hw->reg->ADDR_MASK);
iowrite32(addr_mask, &hw->reg->WOL_ADDR_MASK);
/* wait busy */
pch_gbe_wait_clr_bit(&hw->reg->WOL_ADDR_MASK, PCH_GBE_WLA_BUSY);
iowrite32(0, &hw->reg->WOL_ST);
iowrite32((wu_evt | PCH_GBE_WLC_WOL_MODE), &hw->reg->WOL_CTRL);
iowrite32(0x02, &hw->reg->TCPIP_ACC);
iowrite32(PCH_GBE_INT_ENABLE_MASK, &hw->reg->INT_EN);
} else {
iowrite32(0, &hw->reg->WOL_CTRL);
iowrite32(0, &hw->reg->WOL_ST);
}
return;
}
/**
* pch_gbe_mac_ctrl_miim - Control MIIM interface
* @hw: Pointer to the HW structure
* @addr: Address of PHY
* @dir: Operetion. (Write or Read)
* @reg: Access register of PHY
* @data: Write data.
*
* Returns: Read date.
*/
u16 pch_gbe_mac_ctrl_miim(struct pch_gbe_hw *hw, u32 addr, u32 dir, u32 reg,
u16 data)
{
u32 data_out = 0;
unsigned int i;
unsigned long flags;
spin_lock_irqsave(&hw->miim_lock, flags);
for (i = 100; i; --i) {
if ((ioread32(&hw->reg->MIIM) & PCH_GBE_MIIM_OPER_READY))
break;
udelay(20);
}
if (i == 0) {
pr_err("pch-gbe.miim won't go Ready\n");
spin_unlock_irqrestore(&hw->miim_lock, flags);
return 0; /* No way to indicate timeout error */
}
iowrite32(((reg << PCH_GBE_MIIM_REG_ADDR_SHIFT) |
(addr << PCH_GBE_MIIM_PHY_ADDR_SHIFT) |
dir | data), &hw->reg->MIIM);
for (i = 0; i < 100; i++) {
udelay(20);
data_out = ioread32(&hw->reg->MIIM);
if ((data_out & PCH_GBE_MIIM_OPER_READY))
break;
}
spin_unlock_irqrestore(&hw->miim_lock, flags);
pr_debug("PHY %s: reg=%d, data=0x%04X\n",
dir == PCH_GBE_MIIM_OPER_READ ? "READ" : "WRITE", reg,
dir == PCH_GBE_MIIM_OPER_READ ? data_out : data);
return (u16) data_out;
}
/**
* pch_gbe_mac_set_pause_packet - Set pause packet
* @hw: Pointer to the HW structure
*/
static void pch_gbe_mac_set_pause_packet(struct pch_gbe_hw *hw)
{
unsigned long tmp2, tmp3;
/* Set Pause packet */
tmp2 = hw->mac.addr[1];
tmp2 = (tmp2 << 8) | hw->mac.addr[0];
tmp2 = PCH_GBE_PAUSE_PKT2_VALUE | (tmp2 << 16);
tmp3 = hw->mac.addr[5];
tmp3 = (tmp3 << 8) | hw->mac.addr[4];
tmp3 = (tmp3 << 8) | hw->mac.addr[3];
tmp3 = (tmp3 << 8) | hw->mac.addr[2];
iowrite32(PCH_GBE_PAUSE_PKT1_VALUE, &hw->reg->PAUSE_PKT1);
iowrite32(tmp2, &hw->reg->PAUSE_PKT2);
iowrite32(tmp3, &hw->reg->PAUSE_PKT3);
iowrite32(PCH_GBE_PAUSE_PKT4_VALUE, &hw->reg->PAUSE_PKT4);
iowrite32(PCH_GBE_PAUSE_PKT5_VALUE, &hw->reg->PAUSE_PKT5);
/* Transmit Pause Packet */
iowrite32(PCH_GBE_PS_PKT_RQ, &hw->reg->PAUSE_REQ);
pr_debug("PAUSE_PKT1-5 reg : 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
ioread32(&hw->reg->PAUSE_PKT1), ioread32(&hw->reg->PAUSE_PKT2),
ioread32(&hw->reg->PAUSE_PKT3), ioread32(&hw->reg->PAUSE_PKT4),
ioread32(&hw->reg->PAUSE_PKT5));
return;
}
/**
* pch_gbe_alloc_queues - Allocate memory for all rings
* @adapter: Board private structure to initialize
* Returns
* 0: Successfully
* Negative value: Failed
*/
static int pch_gbe_alloc_queues(struct pch_gbe_adapter *adapter)
{
adapter->tx_ring = kzalloc(sizeof(*adapter->tx_ring), GFP_KERNEL);
if (!adapter->tx_ring)
return -ENOMEM;
adapter->rx_ring = kzalloc(sizeof(*adapter->rx_ring), GFP_KERNEL);
if (!adapter->rx_ring) {
kfree(adapter->tx_ring);
return -ENOMEM;
}
return 0;
}
/**
* pch_gbe_init_stats - Initialize status
* @adapter: Board private structure to initialize
*/
static void pch_gbe_init_stats(struct pch_gbe_adapter *adapter)
{
memset(&adapter->stats, 0, sizeof(adapter->stats));
return;
}
/**
* pch_gbe_init_phy - Initialize PHY
* @adapter: Board private structure to initialize
* Returns
* 0: Successfully
* Negative value: Failed
*/
static int pch_gbe_init_phy(struct pch_gbe_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
u32 addr;
u16 bmcr, stat;
/* Discover phy addr by searching addrs in order {1,0,2,..., 31} */
for (addr = 0; addr < PCH_GBE_PHY_REGS_LEN; addr++) {
adapter->mii.phy_id = (addr == 0) ? 1 : (addr == 1) ? 0 : addr;
bmcr = pch_gbe_mdio_read(netdev, adapter->mii.phy_id, MII_BMCR);
stat = pch_gbe_mdio_read(netdev, adapter->mii.phy_id, MII_BMSR);
stat = pch_gbe_mdio_read(netdev, adapter->mii.phy_id, MII_BMSR);
if (!((bmcr == 0xFFFF) || ((stat == 0) && (bmcr == 0))))
break;
}
adapter->hw.phy.addr = adapter->mii.phy_id;
pr_debug("phy_addr = %d\n", adapter->mii.phy_id);
if (addr == 32)
return -EAGAIN;
/* Selected the phy and isolate the rest */
for (addr = 0; addr < PCH_GBE_PHY_REGS_LEN; addr++) {
if (addr != adapter->mii.phy_id) {
pch_gbe_mdio_write(netdev, addr, MII_BMCR,
BMCR_ISOLATE);
} else {
bmcr = pch_gbe_mdio_read(netdev, addr, MII_BMCR);
pch_gbe_mdio_write(netdev, addr, MII_BMCR,
bmcr & ~BMCR_ISOLATE);
}
}
/* MII setup */
adapter->mii.phy_id_mask = 0x1F;
adapter->mii.reg_num_mask = 0x1F;
adapter->mii.dev = adapter->netdev;
adapter->mii.mdio_read = pch_gbe_mdio_read;
adapter->mii.mdio_write = pch_gbe_mdio_write;
adapter->mii.supports_gmii = mii_check_gmii_support(&adapter->mii);
return 0;
}
/**
* pch_gbe_mdio_read - The read function for mii
* @netdev: Network interface device structure
* @addr: Phy ID
* @reg: Access location
* Returns
* 0: Successfully
* Negative value: Failed
*/
static int pch_gbe_mdio_read(struct net_device *netdev, int addr, int reg)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
return pch_gbe_mac_ctrl_miim(hw, addr, PCH_GBE_HAL_MIIM_READ, reg,
(u16) 0);
}
/**
* pch_gbe_mdio_write - The write function for mii
* @netdev: Network interface device structure
* @addr: Phy ID (not used)
* @reg: Access location
* @data: Write data
*/
static void pch_gbe_mdio_write(struct net_device *netdev,
int addr, int reg, int data)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
pch_gbe_mac_ctrl_miim(hw, addr, PCH_GBE_HAL_MIIM_WRITE, reg, data);
}
/**
* pch_gbe_reset_task - Reset processing at the time of transmission timeout
* @work: Pointer of board private structure
*/
static void pch_gbe_reset_task(struct work_struct *work)
{
struct pch_gbe_adapter *adapter;
adapter = container_of(work, struct pch_gbe_adapter, reset_task);
rtnl_lock();
pch_gbe_reinit_locked(adapter);
rtnl_unlock();
}
/**
* pch_gbe_reinit_locked- Re-initialization
* @adapter: Board private structure
*/
void pch_gbe_reinit_locked(struct pch_gbe_adapter *adapter)
{
pch_gbe_down(adapter);
pch_gbe_up(adapter);
}
/**
* pch_gbe_reset - Reset GbE
* @adapter: Board private structure
*/
void pch_gbe_reset(struct pch_gbe_adapter *adapter)
{
pch_gbe_mac_reset_hw(&adapter->hw);
/* Setup the receive address. */
pch_gbe_mac_init_rx_addrs(&adapter->hw, PCH_GBE_MAR_ENTRIES);
if (pch_gbe_hal_init_hw(&adapter->hw))
pr_err("Hardware Error\n");
}
/**
* pch_gbe_free_irq - Free an interrupt
* @adapter: Board private structure
*/
static void pch_gbe_free_irq(struct pch_gbe_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
free_irq(adapter->pdev->irq, netdev);
if (adapter->have_msi) {
pci_disable_msi(adapter->pdev);
pr_debug("call pci_disable_msi\n");
}
}
/**
* pch_gbe_irq_disable - Mask off interrupt generation on the NIC
* @adapter: Board private structure
*/
static void pch_gbe_irq_disable(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
atomic_inc(&adapter->irq_sem);
iowrite32(0, &hw->reg->INT_EN);
ioread32(&hw->reg->INT_ST);
synchronize_irq(adapter->pdev->irq);
pr_debug("INT_EN reg : 0x%08x\n", ioread32(&hw->reg->INT_EN));
}
/**
* pch_gbe_irq_enable - Enable default interrupt generation settings
* @adapter: Board private structure
*/
static void pch_gbe_irq_enable(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
if (likely(atomic_dec_and_test(&adapter->irq_sem)))
iowrite32(PCH_GBE_INT_ENABLE_MASK, &hw->reg->INT_EN);
ioread32(&hw->reg->INT_ST);
pr_debug("INT_EN reg : 0x%08x\n", ioread32(&hw->reg->INT_EN));
}
/**
* pch_gbe_setup_tctl - configure the Transmit control registers
* @adapter: Board private structure
*/
static void pch_gbe_setup_tctl(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
u32 tx_mode, tcpip;
tx_mode = PCH_GBE_TM_LONG_PKT |
PCH_GBE_TM_ST_AND_FD |
PCH_GBE_TM_SHORT_PKT |
PCH_GBE_TM_TH_TX_STRT_8 |
PCH_GBE_TM_TH_ALM_EMP_4 | PCH_GBE_TM_TH_ALM_FULL_8;
iowrite32(tx_mode, &hw->reg->TX_MODE);
tcpip = ioread32(&hw->reg->TCPIP_ACC);
tcpip |= PCH_GBE_TX_TCPIPACC_EN;
iowrite32(tcpip, &hw->reg->TCPIP_ACC);
return;
}
/**
* pch_gbe_configure_tx - Configure Transmit Unit after Reset
* @adapter: Board private structure
*/
static void pch_gbe_configure_tx(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
u32 tdba, tdlen, dctrl;
pr_debug("dma addr = 0x%08llx size = 0x%08x\n",
(unsigned long long)adapter->tx_ring->dma,
adapter->tx_ring->size);
/* Setup the HW Tx Head and Tail descriptor pointers */
tdba = adapter->tx_ring->dma;
tdlen = adapter->tx_ring->size - 0x10;
iowrite32(tdba, &hw->reg->TX_DSC_BASE);
iowrite32(tdlen, &hw->reg->TX_DSC_SIZE);
iowrite32(tdba, &hw->reg->TX_DSC_SW_P);
/* Enables Transmission DMA */
dctrl = ioread32(&hw->reg->DMA_CTRL);
dctrl |= PCH_GBE_TX_DMA_EN;
iowrite32(dctrl, &hw->reg->DMA_CTRL);
}
/**
* pch_gbe_setup_rctl - Configure the receive control registers
* @adapter: Board private structure
*/
static void pch_gbe_setup_rctl(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
u32 rx_mode, tcpip;
rx_mode = PCH_GBE_ADD_FIL_EN | PCH_GBE_MLT_FIL_EN |
PCH_GBE_RH_ALM_EMP_4 | PCH_GBE_RH_ALM_FULL_4 | PCH_GBE_RH_RD_TRG_8;
iowrite32(rx_mode, &hw->reg->RX_MODE);
tcpip = ioread32(&hw->reg->TCPIP_ACC);
tcpip |= PCH_GBE_RX_TCPIPACC_OFF;
tcpip &= ~PCH_GBE_RX_TCPIPACC_EN;
iowrite32(tcpip, &hw->reg->TCPIP_ACC);
return;
}
/**
* pch_gbe_configure_rx - Configure Receive Unit after Reset
* @adapter: Board private structure
*/
static void pch_gbe_configure_rx(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
u32 rdba, rdlen, rctl, rxdma;
pr_debug("dma adr = 0x%08llx size = 0x%08x\n",
(unsigned long long)adapter->rx_ring->dma,
adapter->rx_ring->size);
pch_gbe_mac_force_mac_fc(hw);
/* Disables Receive MAC */
rctl = ioread32(&hw->reg->MAC_RX_EN);
iowrite32((rctl & ~PCH_GBE_MRE_MAC_RX_EN), &hw->reg->MAC_RX_EN);
/* Disables Receive DMA */
rxdma = ioread32(&hw->reg->DMA_CTRL);
rxdma &= ~PCH_GBE_RX_DMA_EN;
iowrite32(rxdma, &hw->reg->DMA_CTRL);
pr_debug("MAC_RX_EN reg = 0x%08x DMA_CTRL reg = 0x%08x\n",
ioread32(&hw->reg->MAC_RX_EN),
ioread32(&hw->reg->DMA_CTRL));
/* Setup the HW Rx Head and Tail Descriptor Pointers and
* the Base and Length of the Rx Descriptor Ring */
rdba = adapter->rx_ring->dma;
rdlen = adapter->rx_ring->size - 0x10;
iowrite32(rdba, &hw->reg->RX_DSC_BASE);
iowrite32(rdlen, &hw->reg->RX_DSC_SIZE);
iowrite32((rdba + rdlen), &hw->reg->RX_DSC_SW_P);
}
/**
* pch_gbe_unmap_and_free_tx_resource - Unmap and free tx socket buffer
* @adapter: Board private structure
* @buffer_info: Buffer information structure
*/
static void pch_gbe_unmap_and_free_tx_resource(
struct pch_gbe_adapter *adapter, struct pch_gbe_buffer *buffer_info)
{
if (buffer_info->mapped) {
dma_unmap_single(&adapter->pdev->dev, buffer_info->dma,
buffer_info->length, DMA_TO_DEVICE);
buffer_info->mapped = false;
}
if (buffer_info->skb) {
dev_kfree_skb_any(buffer_info->skb);
buffer_info->skb = NULL;
}
}
/**
* pch_gbe_unmap_and_free_rx_resource - Unmap and free rx socket buffer
* @adapter: Board private structure
* @buffer_info: Buffer information structure
*/
static void pch_gbe_unmap_and_free_rx_resource(
struct pch_gbe_adapter *adapter,
struct pch_gbe_buffer *buffer_info)
{
if (buffer_info->mapped) {
dma_unmap_single(&adapter->pdev->dev, buffer_info->dma,
buffer_info->length, DMA_FROM_DEVICE);
buffer_info->mapped = false;
}
if (buffer_info->skb) {
dev_kfree_skb_any(buffer_info->skb);
buffer_info->skb = NULL;
}
}
/**
* pch_gbe_clean_tx_ring - Free Tx Buffers
* @adapter: Board private structure
* @tx_ring: Ring to be cleaned
*/
static void pch_gbe_clean_tx_ring(struct pch_gbe_adapter *adapter,
struct pch_gbe_tx_ring *tx_ring)
{
struct pch_gbe_hw *hw = &adapter->hw;
struct pch_gbe_buffer *buffer_info;
unsigned long size;
unsigned int i;
/* Free all the Tx ring sk_buffs */
for (i = 0; i < tx_ring->count; i++) {
buffer_info = &tx_ring->buffer_info[i];
pch_gbe_unmap_and_free_tx_resource(adapter, buffer_info);
}
pr_debug("call pch_gbe_unmap_and_free_tx_resource() %d count\n", i);
size = (unsigned long)sizeof(struct pch_gbe_buffer) * tx_ring->count;
memset(tx_ring->buffer_info, 0, size);
/* Zero out the descriptor ring */
memset(tx_ring->desc, 0, tx_ring->size);
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
iowrite32(tx_ring->dma, &hw->reg->TX_DSC_HW_P);
iowrite32((tx_ring->size - 0x10), &hw->reg->TX_DSC_SIZE);
}
/**
* pch_gbe_clean_rx_ring - Free Rx Buffers
* @adapter: Board private structure
* @rx_ring: Ring to free buffers from
*/
static void
pch_gbe_clean_rx_ring(struct pch_gbe_adapter *adapter,
struct pch_gbe_rx_ring *rx_ring)
{
struct pch_gbe_hw *hw = &adapter->hw;
struct pch_gbe_buffer *buffer_info;
unsigned long size;
unsigned int i;
/* Free all the Rx ring sk_buffs */
for (i = 0; i < rx_ring->count; i++) {
buffer_info = &rx_ring->buffer_info[i];
pch_gbe_unmap_and_free_rx_resource(adapter, buffer_info);
}
pr_debug("call pch_gbe_unmap_and_free_rx_resource() %d count\n", i);
size = (unsigned long)sizeof(struct pch_gbe_buffer) * rx_ring->count;
memset(rx_ring->buffer_info, 0, size);
/* Zero out the descriptor ring */
memset(rx_ring->desc, 0, rx_ring->size);
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
iowrite32(rx_ring->dma, &hw->reg->RX_DSC_HW_P);
iowrite32((rx_ring->size - 0x10), &hw->reg->RX_DSC_SIZE);
}
static void pch_gbe_set_rgmii_ctrl(struct pch_gbe_adapter *adapter, u16 speed,
u16 duplex)
{
struct pch_gbe_hw *hw = &adapter->hw;
unsigned long rgmii = 0;
/* Set the RGMII control. */
#ifdef PCH_GBE_MAC_IFOP_RGMII
switch (speed) {
case SPEED_10:
rgmii = (PCH_GBE_RGMII_RATE_2_5M |
PCH_GBE_MAC_RGMII_CTRL_SETTING);
break;
case SPEED_100:
rgmii = (PCH_GBE_RGMII_RATE_25M |
PCH_GBE_MAC_RGMII_CTRL_SETTING);
break;
case SPEED_1000:
rgmii = (PCH_GBE_RGMII_RATE_125M |
PCH_GBE_MAC_RGMII_CTRL_SETTING);
break;
}
iowrite32(rgmii, &hw->reg->RGMII_CTRL);
#else /* GMII */
rgmii = 0;
iowrite32(rgmii, &hw->reg->RGMII_CTRL);
#endif
}
static void pch_gbe_set_mode(struct pch_gbe_adapter *adapter, u16 speed,
u16 duplex)
{
struct net_device *netdev = adapter->netdev;
struct pch_gbe_hw *hw = &adapter->hw;
unsigned long mode = 0;
/* Set the communication mode */
switch (speed) {
case SPEED_10:
mode = PCH_GBE_MODE_MII_ETHER;
netdev->tx_queue_len = 10;
break;
case SPEED_100:
mode = PCH_GBE_MODE_MII_ETHER;
netdev->tx_queue_len = 100;
break;
case SPEED_1000:
mode = PCH_GBE_MODE_GMII_ETHER;
break;
}
if (duplex == DUPLEX_FULL)
mode |= PCH_GBE_MODE_FULL_DUPLEX;
else
mode |= PCH_GBE_MODE_HALF_DUPLEX;
iowrite32(mode, &hw->reg->MODE);
}
/**
* pch_gbe_watchdog - Watchdog process
* @data: Board private structure
*/
static void pch_gbe_watchdog(unsigned long data)
{
struct pch_gbe_adapter *adapter = (struct pch_gbe_adapter *)data;
struct net_device *netdev = adapter->netdev;
struct pch_gbe_hw *hw = &adapter->hw;
pr_debug("right now = %ld\n", jiffies);
pch_gbe_update_stats(adapter);
if ((mii_link_ok(&adapter->mii)) && (!netif_carrier_ok(netdev))) {
struct ethtool_cmd cmd = { .cmd = ETHTOOL_GSET };
netdev->tx_queue_len = adapter->tx_queue_len;
/* mii library handles link maintenance tasks */
if (mii_ethtool_gset(&adapter->mii, &cmd)) {
pr_err("ethtool get setting Error\n");
mod_timer(&adapter->watchdog_timer,
round_jiffies(jiffies +
PCH_GBE_WATCHDOG_PERIOD));
return;
}
hw->mac.link_speed = ethtool_cmd_speed(&cmd);
hw->mac.link_duplex = cmd.duplex;
/* Set the RGMII control. */
pch_gbe_set_rgmii_ctrl(adapter, hw->mac.link_speed,
hw->mac.link_duplex);
/* Set the communication mode */
pch_gbe_set_mode(adapter, hw->mac.link_speed,
hw->mac.link_duplex);
netdev_dbg(netdev,
"Link is Up %d Mbps %s-Duplex\n",
hw->mac.link_speed,
cmd.duplex == DUPLEX_FULL ? "Full" : "Half");
netif_carrier_on(netdev);
netif_wake_queue(netdev);
} else if ((!mii_link_ok(&adapter->mii)) &&
(netif_carrier_ok(netdev))) {
netdev_dbg(netdev, "NIC Link is Down\n");
hw->mac.link_speed = SPEED_10;
hw->mac.link_duplex = DUPLEX_HALF;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
}
mod_timer(&adapter->watchdog_timer,
round_jiffies(jiffies + PCH_GBE_WATCHDOG_PERIOD));
}
/**
* pch_gbe_tx_queue - Carry out queuing of the transmission data
* @adapter: Board private structure
* @tx_ring: Tx descriptor ring structure
* @skb: Sockt buffer structure
*/
static void pch_gbe_tx_queue(struct pch_gbe_adapter *adapter,
struct pch_gbe_tx_ring *tx_ring,
struct sk_buff *skb)
{
struct pch_gbe_hw *hw = &adapter->hw;
struct pch_gbe_tx_desc *tx_desc;
struct pch_gbe_buffer *buffer_info;
struct sk_buff *tmp_skb;
unsigned int frame_ctrl;
unsigned int ring_num;
/*-- Set frame control --*/
frame_ctrl = 0;
if (unlikely(skb->len < PCH_GBE_SHORT_PKT))
frame_ctrl |= PCH_GBE_TXD_CTRL_APAD;
if (skb->ip_summed == CHECKSUM_NONE)
frame_ctrl |= PCH_GBE_TXD_CTRL_TCPIP_ACC_OFF;
/* Performs checksum processing */
/*
* It is because the hardware accelerator does not support a checksum,
* when the received data size is less than 64 bytes.
*/
if (skb->len < PCH_GBE_SHORT_PKT && skb->ip_summed != CHECKSUM_NONE) {
frame_ctrl |= PCH_GBE_TXD_CTRL_APAD |
PCH_GBE_TXD_CTRL_TCPIP_ACC_OFF;
if (skb->protocol == htons(ETH_P_IP)) {
struct iphdr *iph = ip_hdr(skb);
unsigned int offset;
iph->check = 0;
iph->check = ip_fast_csum((u8 *) iph, iph->ihl);
offset = skb_transport_offset(skb);
if (iph->protocol == IPPROTO_TCP) {
skb->csum = 0;
tcp_hdr(skb)->check = 0;
skb->csum = skb_checksum(skb, offset,
skb->len - offset, 0);
tcp_hdr(skb)->check =
csum_tcpudp_magic(iph->saddr,
iph->daddr,
skb->len - offset,
IPPROTO_TCP,
skb->csum);
} else if (iph->protocol == IPPROTO_UDP) {
skb->csum = 0;
udp_hdr(skb)->check = 0;
skb->csum =
skb_checksum(skb, offset,
skb->len - offset, 0);
udp_hdr(skb)->check =
csum_tcpudp_magic(iph->saddr,
iph->daddr,
skb->len - offset,
IPPROTO_UDP,
skb->csum);
}
}
}
ring_num = tx_ring->next_to_use;
if (unlikely((ring_num + 1) == tx_ring->count))
tx_ring->next_to_use = 0;
else
tx_ring->next_to_use = ring_num + 1;
buffer_info = &tx_ring->buffer_info[ring_num];
tmp_skb = buffer_info->skb;
/* [Header:14][payload] ---> [Header:14][paddong:2][payload] */
memcpy(tmp_skb->data, skb->data, ETH_HLEN);
tmp_skb->data[ETH_HLEN] = 0x00;
tmp_skb->data[ETH_HLEN + 1] = 0x00;
tmp_skb->len = skb->len;
memcpy(&tmp_skb->data[ETH_HLEN + 2], &skb->data[ETH_HLEN],
(skb->len - ETH_HLEN));
/*-- Set Buffer information --*/
buffer_info->length = tmp_skb->len;
buffer_info->dma = dma_map_single(&adapter->pdev->dev, tmp_skb->data,
buffer_info->length,
DMA_TO_DEVICE);
if (dma_mapping_error(&adapter->pdev->dev, buffer_info->dma)) {
pr_err("TX DMA map failed\n");
buffer_info->dma = 0;
buffer_info->time_stamp = 0;
tx_ring->next_to_use = ring_num;
return;
}
buffer_info->mapped = true;
buffer_info->time_stamp = jiffies;
/*-- Set Tx descriptor --*/
tx_desc = PCH_GBE_TX_DESC(*tx_ring, ring_num);
tx_desc->buffer_addr = (buffer_info->dma);
tx_desc->length = (tmp_skb->len);
tx_desc->tx_words_eob = ((tmp_skb->len + 3));
tx_desc->tx_frame_ctrl = (frame_ctrl);
tx_desc->gbec_status = (DSC_INIT16);
if (unlikely(++ring_num == tx_ring->count))
ring_num = 0;
/* Update software pointer of TX descriptor */
iowrite32(tx_ring->dma +
(int)sizeof(struct pch_gbe_tx_desc) * ring_num,
&hw->reg->TX_DSC_SW_P);
#ifdef CONFIG_PCH_PTP
pch_tx_timestamp(adapter, skb);
#endif
dev_kfree_skb_any(skb);
}
/**
* pch_gbe_update_stats - Update the board statistics counters
* @adapter: Board private structure
*/
void pch_gbe_update_stats(struct pch_gbe_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct pch_gbe_hw_stats *stats = &adapter->stats;
unsigned long flags;
/*
* Prevent stats update while adapter is being reset, or if the pci
* connection is down.
*/
if ((pdev->error_state) && (pdev->error_state != pci_channel_io_normal))
return;
spin_lock_irqsave(&adapter->stats_lock, flags);
/* Update device status "adapter->stats" */
stats->rx_errors = stats->rx_crc_errors + stats->rx_frame_errors;
stats->tx_errors = stats->tx_length_errors +
stats->tx_aborted_errors +
stats->tx_carrier_errors + stats->tx_timeout_count;
/* Update network device status "adapter->net_stats" */
netdev->stats.rx_packets = stats->rx_packets;
netdev->stats.rx_bytes = stats->rx_bytes;
netdev->stats.rx_dropped = stats->rx_dropped;
netdev->stats.tx_packets = stats->tx_packets;
netdev->stats.tx_bytes = stats->tx_bytes;
netdev->stats.tx_dropped = stats->tx_dropped;
/* Fill out the OS statistics structure */
netdev->stats.multicast = stats->multicast;
netdev->stats.collisions = stats->collisions;
/* Rx Errors */
netdev->stats.rx_errors = stats->rx_errors;
netdev->stats.rx_crc_errors = stats->rx_crc_errors;
netdev->stats.rx_frame_errors = stats->rx_frame_errors;
/* Tx Errors */
netdev->stats.tx_errors = stats->tx_errors;
netdev->stats.tx_aborted_errors = stats->tx_aborted_errors;
netdev->stats.tx_carrier_errors = stats->tx_carrier_errors;
spin_unlock_irqrestore(&adapter->stats_lock, flags);
}
static void pch_gbe_stop_receive(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
u32 rxdma;
u16 value;
int ret;
/* Disable Receive DMA */
rxdma = ioread32(&hw->reg->DMA_CTRL);
rxdma &= ~PCH_GBE_RX_DMA_EN;
iowrite32(rxdma, &hw->reg->DMA_CTRL);
/* Wait Rx DMA BUS is IDLE */
ret = pch_gbe_wait_clr_bit_irq(&hw->reg->RX_DMA_ST, PCH_GBE_IDLE_CHECK);
if (ret) {
/* Disable Bus master */
pci_read_config_word(adapter->pdev, PCI_COMMAND, &value);
value &= ~PCI_COMMAND_MASTER;
pci_write_config_word(adapter->pdev, PCI_COMMAND, value);
/* Stop Receive */
pch_gbe_mac_reset_rx(hw);
/* Enable Bus master */
value |= PCI_COMMAND_MASTER;
pci_write_config_word(adapter->pdev, PCI_COMMAND, value);
} else {
/* Stop Receive */
pch_gbe_mac_reset_rx(hw);
}
}
static void pch_gbe_start_receive(struct pch_gbe_hw *hw)
{
u32 rxdma;
/* Enables Receive DMA */
rxdma = ioread32(&hw->reg->DMA_CTRL);
rxdma |= PCH_GBE_RX_DMA_EN;
iowrite32(rxdma, &hw->reg->DMA_CTRL);
/* Enables Receive */
iowrite32(PCH_GBE_MRE_MAC_RX_EN, &hw->reg->MAC_RX_EN);
return;
}
/**
* pch_gbe_intr - Interrupt Handler
* @irq: Interrupt number
* @data: Pointer to a network interface device structure
* Returns
* - IRQ_HANDLED: Our interrupt
* - IRQ_NONE: Not our interrupt
*/
static irqreturn_t pch_gbe_intr(int irq, void *data)
{
struct net_device *netdev = data;
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
u32 int_st;
u32 int_en;
/* Check request status */
int_st = ioread32(&hw->reg->INT_ST);
int_st = int_st & ioread32(&hw->reg->INT_EN);
/* When request status is no interruption factor */
if (unlikely(!int_st))
return IRQ_NONE; /* Not our interrupt. End processing. */
pr_debug("%s occur int_st = 0x%08x\n", __func__, int_st);
if (int_st & PCH_GBE_INT_RX_FRAME_ERR)
adapter->stats.intr_rx_frame_err_count++;
if (int_st & PCH_GBE_INT_RX_FIFO_ERR)
if (!adapter->rx_stop_flag) {
adapter->stats.intr_rx_fifo_err_count++;
pr_debug("Rx fifo over run\n");
adapter->rx_stop_flag = true;
int_en = ioread32(&hw->reg->INT_EN);
iowrite32((int_en & ~PCH_GBE_INT_RX_FIFO_ERR),
&hw->reg->INT_EN);
pch_gbe_stop_receive(adapter);
int_st |= ioread32(&hw->reg->INT_ST);
int_st = int_st & ioread32(&hw->reg->INT_EN);
}
if (int_st & PCH_GBE_INT_RX_DMA_ERR)
adapter->stats.intr_rx_dma_err_count++;
if (int_st & PCH_GBE_INT_TX_FIFO_ERR)
adapter->stats.intr_tx_fifo_err_count++;
if (int_st & PCH_GBE_INT_TX_DMA_ERR)
adapter->stats.intr_tx_dma_err_count++;
if (int_st & PCH_GBE_INT_TCPIP_ERR)
adapter->stats.intr_tcpip_err_count++;
/* When Rx descriptor is empty */
if ((int_st & PCH_GBE_INT_RX_DSC_EMP)) {
adapter->stats.intr_rx_dsc_empty_count++;
pr_debug("Rx descriptor is empty\n");
int_en = ioread32(&hw->reg->INT_EN);
iowrite32((int_en & ~PCH_GBE_INT_RX_DSC_EMP), &hw->reg->INT_EN);
if (hw->mac.tx_fc_enable) {
/* Set Pause packet */
pch_gbe_mac_set_pause_packet(hw);
}
}
/* When request status is Receive interruption */
if ((int_st & (PCH_GBE_INT_RX_DMA_CMPLT | PCH_GBE_INT_TX_CMPLT)) ||
(adapter->rx_stop_flag)) {
if (likely(napi_schedule_prep(&adapter->napi))) {
/* Enable only Rx Descriptor empty */
atomic_inc(&adapter->irq_sem);
int_en = ioread32(&hw->reg->INT_EN);
int_en &=
~(PCH_GBE_INT_RX_DMA_CMPLT | PCH_GBE_INT_TX_CMPLT);
iowrite32(int_en, &hw->reg->INT_EN);
/* Start polling for NAPI */
__napi_schedule(&adapter->napi);
}
}
pr_debug("return = 0x%08x INT_EN reg = 0x%08x\n",
IRQ_HANDLED, ioread32(&hw->reg->INT_EN));
return IRQ_HANDLED;
}
/**
* pch_gbe_alloc_rx_buffers - Replace used receive buffers; legacy & extended
* @adapter: Board private structure
* @rx_ring: Rx descriptor ring
* @cleaned_count: Cleaned count
*/
static void
pch_gbe_alloc_rx_buffers(struct pch_gbe_adapter *adapter,
struct pch_gbe_rx_ring *rx_ring, int cleaned_count)
{
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct pch_gbe_hw *hw = &adapter->hw;
struct pch_gbe_rx_desc *rx_desc;
struct pch_gbe_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
unsigned int bufsz;
bufsz = adapter->rx_buffer_len + NET_IP_ALIGN;
i = rx_ring->next_to_use;
while ((cleaned_count--)) {
buffer_info = &rx_ring->buffer_info[i];
skb = netdev_alloc_skb(netdev, bufsz);
if (unlikely(!skb)) {
/* Better luck next round */
adapter->stats.rx_alloc_buff_failed++;
break;
}
/* align */
skb_reserve(skb, NET_IP_ALIGN);
buffer_info->skb = skb;
buffer_info->dma = dma_map_single(&pdev->dev,
buffer_info->rx_buffer,
buffer_info->length,
DMA_FROM_DEVICE);
if (dma_mapping_error(&adapter->pdev->dev, buffer_info->dma)) {
dev_kfree_skb(skb);
buffer_info->skb = NULL;
buffer_info->dma = 0;
adapter->stats.rx_alloc_buff_failed++;
break; /* while !buffer_info->skb */
}
buffer_info->mapped = true;
rx_desc = PCH_GBE_RX_DESC(*rx_ring, i);
rx_desc->buffer_addr = (buffer_info->dma);
rx_desc->gbec_status = DSC_INIT16;
pr_debug("i = %d buffer_info->dma = 0x08%llx buffer_info->length = 0x%x\n",
i, (unsigned long long)buffer_info->dma,
buffer_info->length);
if (unlikely(++i == rx_ring->count))
i = 0;
}
if (likely(rx_ring->next_to_use != i)) {
rx_ring->next_to_use = i;
if (unlikely(i-- == 0))
i = (rx_ring->count - 1);
iowrite32(rx_ring->dma +
(int)sizeof(struct pch_gbe_rx_desc) * i,
&hw->reg->RX_DSC_SW_P);
}
return;
}
static int
pch_gbe_alloc_rx_buffers_pool(struct pch_gbe_adapter *adapter,
struct pch_gbe_rx_ring *rx_ring, int cleaned_count)
{
struct pci_dev *pdev = adapter->pdev;
struct pch_gbe_buffer *buffer_info;
unsigned int i;
unsigned int bufsz;
unsigned int size;
bufsz = adapter->rx_buffer_len;
size = rx_ring->count * bufsz + PCH_GBE_RESERVE_MEMORY;
rx_ring->rx_buff_pool = dma_alloc_coherent(&pdev->dev, size,
&rx_ring->rx_buff_pool_logic,
GFP_KERNEL);
if (!rx_ring->rx_buff_pool) {
pr_err("Unable to allocate memory for the receive pool buffer\n");
return -ENOMEM;
}
memset(rx_ring->rx_buff_pool, 0, size);
rx_ring->rx_buff_pool_size = size;
for (i = 0; i < rx_ring->count; i++) {
buffer_info = &rx_ring->buffer_info[i];
buffer_info->rx_buffer = rx_ring->rx_buff_pool + bufsz * i;
buffer_info->length = bufsz;
}
return 0;
}
/**
* pch_gbe_alloc_tx_buffers - Allocate transmit buffers
* @adapter: Board private structure
* @tx_ring: Tx descriptor ring
*/
static void pch_gbe_alloc_tx_buffers(struct pch_gbe_adapter *adapter,
struct pch_gbe_tx_ring *tx_ring)
{
struct pch_gbe_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
unsigned int bufsz;
struct pch_gbe_tx_desc *tx_desc;
bufsz =
adapter->hw.mac.max_frame_size + PCH_GBE_DMA_ALIGN + NET_IP_ALIGN;
for (i = 0; i < tx_ring->count; i++) {
buffer_info = &tx_ring->buffer_info[i];
skb = netdev_alloc_skb(adapter->netdev, bufsz);
skb_reserve(skb, PCH_GBE_DMA_ALIGN);
buffer_info->skb = skb;
tx_desc = PCH_GBE_TX_DESC(*tx_ring, i);
tx_desc->gbec_status = (DSC_INIT16);
}
return;
}
/**
* pch_gbe_clean_tx - Reclaim resources after transmit completes
* @adapter: Board private structure
* @tx_ring: Tx descriptor ring
* Returns
* true: Cleaned the descriptor
* false: Not cleaned the descriptor
*/
static bool
pch_gbe_clean_tx(struct pch_gbe_adapter *adapter,
struct pch_gbe_tx_ring *tx_ring)
{
struct pch_gbe_tx_desc *tx_desc;
struct pch_gbe_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
unsigned int cleaned_count = 0;
bool cleaned = true;
pr_debug("next_to_clean : %d\n", tx_ring->next_to_clean);
i = tx_ring->next_to_clean;
tx_desc = PCH_GBE_TX_DESC(*tx_ring, i);
pr_debug("gbec_status:0x%04x dma_status:0x%04x\n",
tx_desc->gbec_status, tx_desc->dma_status);
while ((tx_desc->gbec_status & DSC_INIT16) == 0x0000) {
pr_debug("gbec_status:0x%04x\n", tx_desc->gbec_status);
buffer_info = &tx_ring->buffer_info[i];
skb = buffer_info->skb;
if ((tx_desc->gbec_status & PCH_GBE_TXD_GMAC_STAT_ABT)) {
adapter->stats.tx_aborted_errors++;
pr_err("Transfer Abort Error\n");
} else if ((tx_desc->gbec_status & PCH_GBE_TXD_GMAC_STAT_CRSER)
) {
adapter->stats.tx_carrier_errors++;
pr_err("Transfer Carrier Sense Error\n");
} else if ((tx_desc->gbec_status & PCH_GBE_TXD_GMAC_STAT_EXCOL)
) {
adapter->stats.tx_aborted_errors++;
pr_err("Transfer Collision Abort Error\n");
} else if ((tx_desc->gbec_status &
(PCH_GBE_TXD_GMAC_STAT_SNGCOL |
PCH_GBE_TXD_GMAC_STAT_MLTCOL))) {
adapter->stats.collisions++;
adapter->stats.tx_packets++;
adapter->stats.tx_bytes += skb->len;
pr_debug("Transfer Collision\n");
} else if ((tx_desc->gbec_status & PCH_GBE_TXD_GMAC_STAT_CMPLT)
) {
adapter->stats.tx_packets++;
adapter->stats.tx_bytes += skb->len;
}
if (buffer_info->mapped) {
pr_debug("unmap buffer_info->dma : %d\n", i);
dma_unmap_single(&adapter->pdev->dev, buffer_info->dma,
buffer_info->length, DMA_TO_DEVICE);
buffer_info->mapped = false;
}
if (buffer_info->skb) {
pr_debug("trim buffer_info->skb : %d\n", i);
skb_trim(buffer_info->skb, 0);
}
tx_desc->gbec_status = DSC_INIT16;
if (unlikely(++i == tx_ring->count))
i = 0;
tx_desc = PCH_GBE_TX_DESC(*tx_ring, i);
/* weight of a sort for tx, to avoid endless transmit cleanup */
if (cleaned_count++ == PCH_GBE_TX_WEIGHT) {
cleaned = false;
break;
}
}
pr_debug("called pch_gbe_unmap_and_free_tx_resource() %d count\n",
cleaned_count);
/* Recover from running out of Tx resources in xmit_frame */
spin_lock(&tx_ring->tx_lock);
if (unlikely(cleaned && (netif_queue_stopped(adapter->netdev)))) {
netif_wake_queue(adapter->netdev);
adapter->stats.tx_restart_count++;
pr_debug("Tx wake queue\n");
}
tx_ring->next_to_clean = i;
pr_debug("next_to_clean : %d\n", tx_ring->next_to_clean);
spin_unlock(&tx_ring->tx_lock);
return cleaned;
}
/**
* pch_gbe_clean_rx - Send received data up the network stack; legacy
* @adapter: Board private structure
* @rx_ring: Rx descriptor ring
* @work_done: Completed count
* @work_to_do: Request count
* Returns
* true: Cleaned the descriptor
* false: Not cleaned the descriptor
*/
static bool
pch_gbe_clean_rx(struct pch_gbe_adapter *adapter,
struct pch_gbe_rx_ring *rx_ring,
int *work_done, int work_to_do)
{
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct pch_gbe_buffer *buffer_info;
struct pch_gbe_rx_desc *rx_desc;
u32 length;
unsigned int i;
unsigned int cleaned_count = 0;
bool cleaned = false;
struct sk_buff *skb;
u8 dma_status;
u16 gbec_status;
u32 tcp_ip_status;
i = rx_ring->next_to_clean;
while (*work_done < work_to_do) {
/* Check Rx descriptor status */
rx_desc = PCH_GBE_RX_DESC(*rx_ring, i);
if (rx_desc->gbec_status == DSC_INIT16)
break;
cleaned = true;
cleaned_count++;
dma_status = rx_desc->dma_status;
gbec_status = rx_desc->gbec_status;
tcp_ip_status = rx_desc->tcp_ip_status;
rx_desc->gbec_status = DSC_INIT16;
buffer_info = &rx_ring->buffer_info[i];
skb = buffer_info->skb;
buffer_info->skb = NULL;
/* unmap dma */
dma_unmap_single(&pdev->dev, buffer_info->dma,
buffer_info->length, DMA_FROM_DEVICE);
buffer_info->mapped = false;
pr_debug("RxDecNo = 0x%04x Status[DMA:0x%02x GBE:0x%04x "
"TCP:0x%08x] BufInf = 0x%p\n",
i, dma_status, gbec_status, tcp_ip_status,
buffer_info);
/* Error check */
if (unlikely(gbec_status & PCH_GBE_RXD_GMAC_STAT_NOTOCTAL)) {
adapter->stats.rx_frame_errors++;
pr_err("Receive Not Octal Error\n");
} else if (unlikely(gbec_status &
PCH_GBE_RXD_GMAC_STAT_NBLERR)) {
adapter->stats.rx_frame_errors++;
pr_err("Receive Nibble Error\n");
} else if (unlikely(gbec_status &
PCH_GBE_RXD_GMAC_STAT_CRCERR)) {
adapter->stats.rx_crc_errors++;
pr_err("Receive CRC Error\n");
} else {
/* get receive length */
/* length convert[-3], length includes FCS length */
length = (rx_desc->rx_words_eob) - 3 - ETH_FCS_LEN;
if (rx_desc->rx_words_eob & 0x02)
length = length - 4;
/*
* buffer_info->rx_buffer: [Header:14][payload]
* skb->data: [Reserve:2][Header:14][payload]
*/
memcpy(skb->data, buffer_info->rx_buffer, length);
/* update status of driver */
adapter->stats.rx_bytes += length;
adapter->stats.rx_packets++;
if ((gbec_status & PCH_GBE_RXD_GMAC_STAT_MARMLT))
adapter->stats.multicast++;
/* Write meta date of skb */
skb_put(skb, length);
#ifdef CONFIG_PCH_PTP
pch_rx_timestamp(adapter, skb);
#endif
skb->protocol = eth_type_trans(skb, netdev);
if (tcp_ip_status & PCH_GBE_RXD_ACC_STAT_TCPIPOK)
skb->ip_summed = CHECKSUM_NONE;
else
skb->ip_summed = CHECKSUM_UNNECESSARY;
napi_gro_receive(&adapter->napi, skb);
(*work_done)++;
pr_debug("Receive skb->ip_summed: %d length: %d\n",
skb->ip_summed, length);
}
/* return some buffers to hardware, one at a time is too slow */
if (unlikely(cleaned_count >= PCH_GBE_RX_BUFFER_WRITE)) {
pch_gbe_alloc_rx_buffers(adapter, rx_ring,
cleaned_count);
cleaned_count = 0;
}
if (++i == rx_ring->count)
i = 0;
}
rx_ring->next_to_clean = i;
if (cleaned_count)
pch_gbe_alloc_rx_buffers(adapter, rx_ring, cleaned_count);
return cleaned;
}
/**
* pch_gbe_setup_tx_resources - Allocate Tx resources (Descriptors)
* @adapter: Board private structure
* @tx_ring: Tx descriptor ring (for a specific queue) to setup
* Returns
* 0: Successfully
* Negative value: Failed
*/
int pch_gbe_setup_tx_resources(struct pch_gbe_adapter *adapter,
struct pch_gbe_tx_ring *tx_ring)
{
struct pci_dev *pdev = adapter->pdev;
struct pch_gbe_tx_desc *tx_desc;
int size;
int desNo;
size = (int)sizeof(struct pch_gbe_buffer) * tx_ring->count;
tx_ring->buffer_info = vzalloc(size);
if (!tx_ring->buffer_info)
return -ENOMEM;
tx_ring->size = tx_ring->count * (int)sizeof(struct pch_gbe_tx_desc);
tx_ring->desc = dma_alloc_coherent(&pdev->dev, tx_ring->size,
&tx_ring->dma, GFP_KERNEL);
if (!tx_ring->desc) {
vfree(tx_ring->buffer_info);
pr_err("Unable to allocate memory for the transmit descriptor ring\n");
return -ENOMEM;
}
memset(tx_ring->desc, 0, tx_ring->size);
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
spin_lock_init(&tx_ring->tx_lock);
for (desNo = 0; desNo < tx_ring->count; desNo++) {
tx_desc = PCH_GBE_TX_DESC(*tx_ring, desNo);
tx_desc->gbec_status = DSC_INIT16;
}
pr_debug("tx_ring->desc = 0x%p tx_ring->dma = 0x%08llx\n"
"next_to_clean = 0x%08x next_to_use = 0x%08x\n",
tx_ring->desc, (unsigned long long)tx_ring->dma,
tx_ring->next_to_clean, tx_ring->next_to_use);
return 0;
}
/**
* pch_gbe_setup_rx_resources - Allocate Rx resources (Descriptors)
* @adapter: Board private structure
* @rx_ring: Rx descriptor ring (for a specific queue) to setup
* Returns
* 0: Successfully
* Negative value: Failed
*/
int pch_gbe_setup_rx_resources(struct pch_gbe_adapter *adapter,
struct pch_gbe_rx_ring *rx_ring)
{
struct pci_dev *pdev = adapter->pdev;
struct pch_gbe_rx_desc *rx_desc;
int size;
int desNo;
size = (int)sizeof(struct pch_gbe_buffer) * rx_ring->count;
rx_ring->buffer_info = vzalloc(size);
if (!rx_ring->buffer_info)
return -ENOMEM;
rx_ring->size = rx_ring->count * (int)sizeof(struct pch_gbe_rx_desc);
rx_ring->desc = dma_alloc_coherent(&pdev->dev, rx_ring->size,
&rx_ring->dma, GFP_KERNEL);
if (!rx_ring->desc) {
pr_err("Unable to allocate memory for the receive descriptor ring\n");
vfree(rx_ring->buffer_info);
return -ENOMEM;
}
memset(rx_ring->desc, 0, rx_ring->size);
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
for (desNo = 0; desNo < rx_ring->count; desNo++) {
rx_desc = PCH_GBE_RX_DESC(*rx_ring, desNo);
rx_desc->gbec_status = DSC_INIT16;
}
pr_debug("rx_ring->desc = 0x%p rx_ring->dma = 0x%08llx "
"next_to_clean = 0x%08x next_to_use = 0x%08x\n",
rx_ring->desc, (unsigned long long)rx_ring->dma,
rx_ring->next_to_clean, rx_ring->next_to_use);
return 0;
}
/**
* pch_gbe_free_tx_resources - Free Tx Resources
* @adapter: Board private structure
* @tx_ring: Tx descriptor ring for a specific queue
*/
void pch_gbe_free_tx_resources(struct pch_gbe_adapter *adapter,
struct pch_gbe_tx_ring *tx_ring)
{
struct pci_dev *pdev = adapter->pdev;
pch_gbe_clean_tx_ring(adapter, tx_ring);
vfree(tx_ring->buffer_info);
tx_ring->buffer_info = NULL;
pci_free_consistent(pdev, tx_ring->size, tx_ring->desc, tx_ring->dma);
tx_ring->desc = NULL;
}
/**
* pch_gbe_free_rx_resources - Free Rx Resources
* @adapter: Board private structure
* @rx_ring: Ring to clean the resources from
*/
void pch_gbe_free_rx_resources(struct pch_gbe_adapter *adapter,
struct pch_gbe_rx_ring *rx_ring)
{
struct pci_dev *pdev = adapter->pdev;
pch_gbe_clean_rx_ring(adapter, rx_ring);
vfree(rx_ring->buffer_info);
rx_ring->buffer_info = NULL;
pci_free_consistent(pdev, rx_ring->size, rx_ring->desc, rx_ring->dma);
rx_ring->desc = NULL;
}
/**
* pch_gbe_request_irq - Allocate an interrupt line
* @adapter: Board private structure
* Returns
* 0: Successfully
* Negative value: Failed
*/
static int pch_gbe_request_irq(struct pch_gbe_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int err;
int flags;
flags = IRQF_SHARED;
adapter->have_msi = false;
err = pci_enable_msi(adapter->pdev);
pr_debug("call pci_enable_msi\n");
if (err) {
pr_debug("call pci_enable_msi - Error: %d\n", err);
} else {
flags = 0;
adapter->have_msi = true;
}
err = request_irq(adapter->pdev->irq, &pch_gbe_intr,
flags, netdev->name, netdev);
if (err)
pr_err("Unable to allocate interrupt Error: %d\n", err);
pr_debug("adapter->have_msi : %d flags : 0x%04x return : 0x%04x\n",
adapter->have_msi, flags, err);
return err;
}
static void pch_gbe_set_multi(struct net_device *netdev);
/**
* pch_gbe_up - Up GbE network device
* @adapter: Board private structure
* Returns
* 0: Successfully
* Negative value: Failed
*/
int pch_gbe_up(struct pch_gbe_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct pch_gbe_tx_ring *tx_ring = adapter->tx_ring;
struct pch_gbe_rx_ring *rx_ring = adapter->rx_ring;
int err;
/* Ensure we have a valid MAC */
if (!is_valid_ether_addr(adapter->hw.mac.addr)) {
pr_err("Error: Invalid MAC address\n");
return -EINVAL;
}
/* hardware has been reset, we need to reload some things */
pch_gbe_set_multi(netdev);
pch_gbe_setup_tctl(adapter);
pch_gbe_configure_tx(adapter);
pch_gbe_setup_rctl(adapter);
pch_gbe_configure_rx(adapter);
err = pch_gbe_request_irq(adapter);
if (err) {
pr_err("Error: can't bring device up\n");
return err;
}
err = pch_gbe_alloc_rx_buffers_pool(adapter, rx_ring, rx_ring->count);
if (err) {
pr_err("Error: can't bring device up\n");
return err;
}
pch_gbe_alloc_tx_buffers(adapter, tx_ring);
pch_gbe_alloc_rx_buffers(adapter, rx_ring, rx_ring->count);
adapter->tx_queue_len = netdev->tx_queue_len;
pch_gbe_start_receive(&adapter->hw);
mod_timer(&adapter->watchdog_timer, jiffies);
napi_enable(&adapter->napi);
pch_gbe_irq_enable(adapter);
netif_start_queue(adapter->netdev);
return 0;
}
/**
* pch_gbe_down - Down GbE network device
* @adapter: Board private structure
*/
void pch_gbe_down(struct pch_gbe_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct pch_gbe_rx_ring *rx_ring = adapter->rx_ring;
/* signal that we're down so the interrupt handler does not
* reschedule our watchdog timer */
napi_disable(&adapter->napi);
atomic_set(&adapter->irq_sem, 0);
pch_gbe_irq_disable(adapter);
pch_gbe_free_irq(adapter);
del_timer_sync(&adapter->watchdog_timer);
netdev->tx_queue_len = adapter->tx_queue_len;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
pch_gbe_reset(adapter);
pch_gbe_clean_tx_ring(adapter, adapter->tx_ring);
pch_gbe_clean_rx_ring(adapter, adapter->rx_ring);
pci_free_consistent(adapter->pdev, rx_ring->rx_buff_pool_size,
rx_ring->rx_buff_pool, rx_ring->rx_buff_pool_logic);
rx_ring->rx_buff_pool_logic = 0;
rx_ring->rx_buff_pool_size = 0;
rx_ring->rx_buff_pool = NULL;
}
/**
* pch_gbe_sw_init - Initialize general software structures (struct pch_gbe_adapter)
* @adapter: Board private structure to initialize
* Returns
* 0: Successfully
* Negative value: Failed
*/
static int pch_gbe_sw_init(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
adapter->rx_buffer_len = PCH_GBE_FRAME_SIZE_2048;
hw->mac.max_frame_size = netdev->mtu + ETH_HLEN + ETH_FCS_LEN;
hw->mac.min_frame_size = ETH_ZLEN + ETH_FCS_LEN;
/* Initialize the hardware-specific values */
if (pch_gbe_hal_setup_init_funcs(hw)) {
pr_err("Hardware Initialization Failure\n");
return -EIO;
}
if (pch_gbe_alloc_queues(adapter)) {
pr_err("Unable to allocate memory for queues\n");
return -ENOMEM;
}
spin_lock_init(&adapter->hw.miim_lock);
spin_lock_init(&adapter->stats_lock);
spin_lock_init(&adapter->ethtool_lock);
atomic_set(&adapter->irq_sem, 0);
pch_gbe_irq_disable(adapter);
pch_gbe_init_stats(adapter);
pr_debug("rx_buffer_len : %d mac.min_frame_size : %d mac.max_frame_size : %d\n",
(u32) adapter->rx_buffer_len,
hw->mac.min_frame_size, hw->mac.max_frame_size);
return 0;
}
/**
* pch_gbe_open - Called when a network interface is made active
* @netdev: Network interface device structure
* Returns
* 0: Successfully
* Negative value: Failed
*/
static int pch_gbe_open(struct net_device *netdev)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
int err;
/* allocate transmit descriptors */
err = pch_gbe_setup_tx_resources(adapter, adapter->tx_ring);
if (err)
goto err_setup_tx;
/* allocate receive descriptors */
err = pch_gbe_setup_rx_resources(adapter, adapter->rx_ring);
if (err)
goto err_setup_rx;
pch_gbe_hal_power_up_phy(hw);
err = pch_gbe_up(adapter);
if (err)
goto err_up;
pr_debug("Success End\n");
return 0;
err_up:
if (!adapter->wake_up_evt)
pch_gbe_hal_power_down_phy(hw);
pch_gbe_free_rx_resources(adapter, adapter->rx_ring);
err_setup_rx:
pch_gbe_free_tx_resources(adapter, adapter->tx_ring);
err_setup_tx:
pch_gbe_reset(adapter);
pr_err("Error End\n");
return err;
}
/**
* pch_gbe_stop - Disables a network interface
* @netdev: Network interface device structure
* Returns
* 0: Successfully
*/
static int pch_gbe_stop(struct net_device *netdev)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
pch_gbe_down(adapter);
if (!adapter->wake_up_evt)
pch_gbe_hal_power_down_phy(hw);
pch_gbe_free_tx_resources(adapter, adapter->tx_ring);
pch_gbe_free_rx_resources(adapter, adapter->rx_ring);
return 0;
}
/**
* pch_gbe_xmit_frame - Packet transmitting start
* @skb: Socket buffer structure
* @netdev: Network interface device structure
* Returns
* - NETDEV_TX_OK: Normal end
* - NETDEV_TX_BUSY: Error end
*/
static int pch_gbe_xmit_frame(struct sk_buff *skb, struct net_device *netdev)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_tx_ring *tx_ring = adapter->tx_ring;
unsigned long flags;
if (unlikely(skb->len > (adapter->hw.mac.max_frame_size - 4))) {
pr_err("Transfer length Error: skb len: %d > max: %d\n",
skb->len, adapter->hw.mac.max_frame_size);
dev_kfree_skb_any(skb);
adapter->stats.tx_length_errors++;
return NETDEV_TX_OK;
}
if (!spin_trylock_irqsave(&tx_ring->tx_lock, flags)) {
/* Collision - tell upper layer to requeue */
return NETDEV_TX_LOCKED;
}
if (unlikely(!PCH_GBE_DESC_UNUSED(tx_ring))) {
netif_stop_queue(netdev);
spin_unlock_irqrestore(&tx_ring->tx_lock, flags);
pr_debug("Return : BUSY next_to use : 0x%08x next_to clean : 0x%08x\n",
tx_ring->next_to_use, tx_ring->next_to_clean);
return NETDEV_TX_BUSY;
}
/* CRC,ITAG no support */
pch_gbe_tx_queue(adapter, tx_ring, skb);
spin_unlock_irqrestore(&tx_ring->tx_lock, flags);
return NETDEV_TX_OK;
}
/**
* pch_gbe_get_stats - Get System Network Statistics
* @netdev: Network interface device structure
* Returns: The current stats
*/
static struct net_device_stats *pch_gbe_get_stats(struct net_device *netdev)
{
/* only return the current stats */
return &netdev->stats;
}
/**
* pch_gbe_set_multi - Multicast and Promiscuous mode set
* @netdev: Network interface device structure
*/
static void pch_gbe_set_multi(struct net_device *netdev)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
struct netdev_hw_addr *ha;
u8 *mta_list;
u32 rctl;
int i;
int mc_count;
pr_debug("netdev->flags : 0x%08x\n", netdev->flags);
/* Check for Promiscuous and All Multicast modes */
rctl = ioread32(&hw->reg->RX_MODE);
mc_count = netdev_mc_count(netdev);
if ((netdev->flags & IFF_PROMISC)) {
rctl &= ~PCH_GBE_ADD_FIL_EN;
rctl &= ~PCH_GBE_MLT_FIL_EN;
} else if ((netdev->flags & IFF_ALLMULTI)) {
/* all the multicasting receive permissions */
rctl |= PCH_GBE_ADD_FIL_EN;
rctl &= ~PCH_GBE_MLT_FIL_EN;
} else {
if (mc_count >= PCH_GBE_MAR_ENTRIES) {
/* all the multicasting receive permissions */
rctl |= PCH_GBE_ADD_FIL_EN;
rctl &= ~PCH_GBE_MLT_FIL_EN;
} else {
rctl |= (PCH_GBE_ADD_FIL_EN | PCH_GBE_MLT_FIL_EN);
}
}
iowrite32(rctl, &hw->reg->RX_MODE);
if (mc_count >= PCH_GBE_MAR_ENTRIES)
return;
mta_list = kmalloc(mc_count * ETH_ALEN, GFP_ATOMIC);
if (!mta_list)
return;
/* The shared function expects a packed array of only addresses. */
i = 0;
netdev_for_each_mc_addr(ha, netdev) {
if (i == mc_count)
break;
memcpy(mta_list + (i++ * ETH_ALEN), &ha->addr, ETH_ALEN);
}
pch_gbe_mac_mc_addr_list_update(hw, mta_list, i, 1,
PCH_GBE_MAR_ENTRIES);
kfree(mta_list);
pr_debug("RX_MODE reg(check bit31,30 ADD,MLT) : 0x%08x netdev->mc_count : 0x%08x\n",
ioread32(&hw->reg->RX_MODE), mc_count);
}
/**
* pch_gbe_set_mac - Change the Ethernet Address of the NIC
* @netdev: Network interface device structure
* @addr: Pointer to an address structure
* Returns
* 0: Successfully
* -EADDRNOTAVAIL: Failed
*/
static int pch_gbe_set_mac(struct net_device *netdev, void *addr)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct sockaddr *skaddr = addr;
int ret_val;
if (!is_valid_ether_addr(skaddr->sa_data)) {
ret_val = -EADDRNOTAVAIL;
} else {
memcpy(netdev->dev_addr, skaddr->sa_data, netdev->addr_len);
memcpy(adapter->hw.mac.addr, skaddr->sa_data, netdev->addr_len);
pch_gbe_mac_mar_set(&adapter->hw, adapter->hw.mac.addr, 0);
ret_val = 0;
}
pr_debug("ret_val : 0x%08x\n", ret_val);
pr_debug("dev_addr : %pM\n", netdev->dev_addr);
pr_debug("mac_addr : %pM\n", adapter->hw.mac.addr);
pr_debug("MAC_ADR1AB reg : 0x%08x 0x%08x\n",
ioread32(&adapter->hw.reg->mac_adr[0].high),
ioread32(&adapter->hw.reg->mac_adr[0].low));
return ret_val;
}
/**
* pch_gbe_change_mtu - Change the Maximum Transfer Unit
* @netdev: Network interface device structure
* @new_mtu: New value for maximum frame size
* Returns
* 0: Successfully
* -EINVAL: Failed
*/
static int pch_gbe_change_mtu(struct net_device *netdev, int new_mtu)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
int max_frame;
unsigned long old_rx_buffer_len = adapter->rx_buffer_len;
int err;
max_frame = new_mtu + ETH_HLEN + ETH_FCS_LEN;
if ((max_frame < ETH_ZLEN + ETH_FCS_LEN) ||
(max_frame > PCH_GBE_MAX_JUMBO_FRAME_SIZE)) {
pr_err("Invalid MTU setting\n");
return -EINVAL;
}
if (max_frame <= PCH_GBE_FRAME_SIZE_2048)
adapter->rx_buffer_len = PCH_GBE_FRAME_SIZE_2048;
else if (max_frame <= PCH_GBE_FRAME_SIZE_4096)
adapter->rx_buffer_len = PCH_GBE_FRAME_SIZE_4096;
else if (max_frame <= PCH_GBE_FRAME_SIZE_8192)
adapter->rx_buffer_len = PCH_GBE_FRAME_SIZE_8192;
else
adapter->rx_buffer_len = PCH_GBE_MAX_RX_BUFFER_SIZE;
if (netif_running(netdev)) {
pch_gbe_down(adapter);
err = pch_gbe_up(adapter);
if (err) {
adapter->rx_buffer_len = old_rx_buffer_len;
pch_gbe_up(adapter);
return -ENOMEM;
} else {
netdev->mtu = new_mtu;
adapter->hw.mac.max_frame_size = max_frame;
}
} else {
pch_gbe_reset(adapter);
netdev->mtu = new_mtu;
adapter->hw.mac.max_frame_size = max_frame;
}
pr_debug("max_frame : %d rx_buffer_len : %d mtu : %d max_frame_size : %d\n",
max_frame, (u32) adapter->rx_buffer_len, netdev->mtu,
adapter->hw.mac.max_frame_size);
return 0;
}
/**
* pch_gbe_set_features - Reset device after features changed
* @netdev: Network interface device structure
* @features: New features
* Returns
* 0: HW state updated successfully
*/
static int pch_gbe_set_features(struct net_device *netdev,
netdev_features_t features)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
netdev_features_t changed = features ^ netdev->features;
if (!(changed & NETIF_F_RXCSUM))
return 0;
if (netif_running(netdev))
pch_gbe_reinit_locked(adapter);
else
pch_gbe_reset(adapter);
return 0;
}
/**
* pch_gbe_ioctl - Controls register through a MII interface
* @netdev: Network interface device structure
* @ifr: Pointer to ifr structure
* @cmd: Control command
* Returns
* 0: Successfully
* Negative value: Failed
*/
static int pch_gbe_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
pr_debug("cmd : 0x%04x\n", cmd);
#ifdef CONFIG_PCH_PTP
if (cmd == SIOCSHWTSTAMP)
return hwtstamp_ioctl(netdev, ifr, cmd);
#endif
return generic_mii_ioctl(&adapter->mii, if_mii(ifr), cmd, NULL);
}
/**
* pch_gbe_tx_timeout - Respond to a Tx Hang
* @netdev: Network interface device structure
*/
static void pch_gbe_tx_timeout(struct net_device *netdev)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
/* Do the reset outside of interrupt context */
adapter->stats.tx_timeout_count++;
schedule_work(&adapter->reset_task);
}
/**
* pch_gbe_napi_poll - NAPI receive and transfer polling callback
* @napi: Pointer of polling device struct
* @budget: The maximum number of a packet
* Returns
* false: Exit the polling mode
* true: Continue the polling mode
*/
static int pch_gbe_napi_poll(struct napi_struct *napi, int budget)
{
struct pch_gbe_adapter *adapter =
container_of(napi, struct pch_gbe_adapter, napi);
int work_done = 0;
bool poll_end_flag = false;
bool cleaned = false;
u32 int_en;
pr_debug("budget : %d\n", budget);
pch_gbe_clean_rx(adapter, adapter->rx_ring, &work_done, budget);
cleaned = pch_gbe_clean_tx(adapter, adapter->tx_ring);
if (!cleaned)
work_done = budget;
/* If no Tx and not enough Rx work done,
* exit the polling mode
*/
if (work_done < budget)
poll_end_flag = true;
if (poll_end_flag) {
napi_complete(napi);
if (adapter->rx_stop_flag) {
adapter->rx_stop_flag = false;
pch_gbe_start_receive(&adapter->hw);
}
pch_gbe_irq_enable(adapter);
} else
if (adapter->rx_stop_flag) {
adapter->rx_stop_flag = false;
pch_gbe_start_receive(&adapter->hw);
int_en = ioread32(&adapter->hw.reg->INT_EN);
iowrite32((int_en | PCH_GBE_INT_RX_FIFO_ERR),
&adapter->hw.reg->INT_EN);
}
pr_debug("poll_end_flag : %d work_done : %d budget : %d\n",
poll_end_flag, work_done, budget);
return work_done;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/**
* pch_gbe_netpoll - Used by things like netconsole to send skbs
* @netdev: Network interface device structure
*/
static void pch_gbe_netpoll(struct net_device *netdev)
{
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
disable_irq(adapter->pdev->irq);
pch_gbe_intr(adapter->pdev->irq, netdev);
enable_irq(adapter->pdev->irq);
}
#endif
static const struct net_device_ops pch_gbe_netdev_ops = {
.ndo_open = pch_gbe_open,
.ndo_stop = pch_gbe_stop,
.ndo_start_xmit = pch_gbe_xmit_frame,
.ndo_get_stats = pch_gbe_get_stats,
.ndo_set_mac_address = pch_gbe_set_mac,
.ndo_tx_timeout = pch_gbe_tx_timeout,
.ndo_change_mtu = pch_gbe_change_mtu,
.ndo_set_features = pch_gbe_set_features,
.ndo_do_ioctl = pch_gbe_ioctl,
.ndo_set_rx_mode = pch_gbe_set_multi,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = pch_gbe_netpoll,
#endif
};
static pci_ers_result_t pch_gbe_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
netif_device_detach(netdev);
if (netif_running(netdev))
pch_gbe_down(adapter);
pci_disable_device(pdev);
/* Request a slot slot reset. */
return PCI_ERS_RESULT_NEED_RESET;
}
static pci_ers_result_t pch_gbe_io_slot_reset(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
if (pci_enable_device(pdev)) {
pr_err("Cannot re-enable PCI device after reset\n");
return PCI_ERS_RESULT_DISCONNECT;
}
pci_set_master(pdev);
pci_enable_wake(pdev, PCI_D0, 0);
pch_gbe_hal_power_up_phy(hw);
pch_gbe_reset(adapter);
/* Clear wake up status */
pch_gbe_mac_set_wol_event(hw, 0);
return PCI_ERS_RESULT_RECOVERED;
}
static void pch_gbe_io_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
if (netif_running(netdev)) {
if (pch_gbe_up(adapter)) {
pr_debug("can't bring device back up after reset\n");
return;
}
}
netif_device_attach(netdev);
}
static int __pch_gbe_suspend(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
u32 wufc = adapter->wake_up_evt;
int retval = 0;
netif_device_detach(netdev);
if (netif_running(netdev))
pch_gbe_down(adapter);
if (wufc) {
pch_gbe_set_multi(netdev);
pch_gbe_setup_rctl(adapter);
pch_gbe_configure_rx(adapter);
pch_gbe_set_rgmii_ctrl(adapter, hw->mac.link_speed,
hw->mac.link_duplex);
pch_gbe_set_mode(adapter, hw->mac.link_speed,
hw->mac.link_duplex);
pch_gbe_mac_set_wol_event(hw, wufc);
pci_disable_device(pdev);
} else {
pch_gbe_hal_power_down_phy(hw);
pch_gbe_mac_set_wol_event(hw, wufc);
pci_disable_device(pdev);
}
return retval;
}
#ifdef CONFIG_PM
static int pch_gbe_suspend(struct device *device)
{
struct pci_dev *pdev = to_pci_dev(device);
return __pch_gbe_suspend(pdev);
}
static int pch_gbe_resume(struct device *device)
{
struct pci_dev *pdev = to_pci_dev(device);
struct net_device *netdev = pci_get_drvdata(pdev);
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
struct pch_gbe_hw *hw = &adapter->hw;
u32 err;
err = pci_enable_device(pdev);
if (err) {
pr_err("Cannot enable PCI device from suspend\n");
return err;
}
pci_set_master(pdev);
pch_gbe_hal_power_up_phy(hw);
pch_gbe_reset(adapter);
/* Clear wake on lan control and status */
pch_gbe_mac_set_wol_event(hw, 0);
if (netif_running(netdev))
pch_gbe_up(adapter);
netif_device_attach(netdev);
return 0;
}
#endif /* CONFIG_PM */
static void pch_gbe_shutdown(struct pci_dev *pdev)
{
__pch_gbe_suspend(pdev);
if (system_state == SYSTEM_POWER_OFF) {
pci_wake_from_d3(pdev, true);
pci_set_power_state(pdev, PCI_D3hot);
}
}
static void pch_gbe_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct pch_gbe_adapter *adapter = netdev_priv(netdev);
cancel_work_sync(&adapter->reset_task);
unregister_netdev(netdev);
pch_gbe_hal_phy_hw_reset(&adapter->hw);
kfree(adapter->tx_ring);
kfree(adapter->rx_ring);
iounmap(adapter->hw.reg);
pci_release_regions(pdev);
free_netdev(netdev);
pci_disable_device(pdev);
}
static int pch_gbe_probe(struct pci_dev *pdev,
const struct pci_device_id *pci_id)
{
struct net_device *netdev;
struct pch_gbe_adapter *adapter;
int ret;
ret = pci_enable_device(pdev);
if (ret)
return ret;
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64))
|| pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64))) {
ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (ret) {
ret = pci_set_consistent_dma_mask(pdev,
DMA_BIT_MASK(32));
if (ret) {
dev_err(&pdev->dev, "ERR: No usable DMA "
"configuration, aborting\n");
goto err_disable_device;
}
}
}
ret = pci_request_regions(pdev, KBUILD_MODNAME);
if (ret) {
dev_err(&pdev->dev,
"ERR: Can't reserve PCI I/O and memory resources\n");
goto err_disable_device;
}
pci_set_master(pdev);
netdev = alloc_etherdev((int)sizeof(struct pch_gbe_adapter));
if (!netdev) {
ret = -ENOMEM;
goto err_release_pci;
}
SET_NETDEV_DEV(netdev, &pdev->dev);
pci_set_drvdata(pdev, netdev);
adapter = netdev_priv(netdev);
adapter->netdev = netdev;
adapter->pdev = pdev;
adapter->hw.back = adapter;
adapter->hw.reg = pci_iomap(pdev, PCH_GBE_PCI_BAR, 0);
if (!adapter->hw.reg) {
ret = -EIO;
dev_err(&pdev->dev, "Can't ioremap\n");
goto err_free_netdev;
}
#ifdef CONFIG_PCH_PTP
adapter->ptp_pdev = pci_get_bus_and_slot(adapter->pdev->bus->number,
PCI_DEVFN(12, 4));
if (ptp_filter_init(ptp_filter, ARRAY_SIZE(ptp_filter))) {
pr_err("Bad ptp filter\n");
return -EINVAL;
}
#endif
netdev->netdev_ops = &pch_gbe_netdev_ops;
netdev->watchdog_timeo = PCH_GBE_WATCHDOG_PERIOD;
netif_napi_add(netdev, &adapter->napi,
pch_gbe_napi_poll, PCH_GBE_RX_WEIGHT);
netdev->hw_features = NETIF_F_RXCSUM |
NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM;
netdev->features = netdev->hw_features;
pch_gbe_set_ethtool_ops(netdev);
pch_gbe_mac_load_mac_addr(&adapter->hw);
pch_gbe_mac_reset_hw(&adapter->hw);
/* setup the private structure */
ret = pch_gbe_sw_init(adapter);
if (ret)
goto err_iounmap;
/* Initialize PHY */
ret = pch_gbe_init_phy(adapter);
if (ret) {
dev_err(&pdev->dev, "PHY initialize error\n");
goto err_free_adapter;
}
pch_gbe_hal_get_bus_info(&adapter->hw);
/* Read the MAC address. and store to the private data */
ret = pch_gbe_hal_read_mac_addr(&adapter->hw);
if (ret) {
dev_err(&pdev->dev, "MAC address Read Error\n");
goto err_free_adapter;
}
memcpy(netdev->dev_addr, adapter->hw.mac.addr, netdev->addr_len);
if (!is_valid_ether_addr(netdev->dev_addr)) {
/*
* If the MAC is invalid (or just missing), display a warning
* but do not abort setting up the device. pch_gbe_up will
* prevent the interface from being brought up until a valid MAC
* is set.
*/
dev_err(&pdev->dev, "Invalid MAC address, "
"interface disabled.\n");
}
setup_timer(&adapter->watchdog_timer, pch_gbe_watchdog,
(unsigned long)adapter);
INIT_WORK(&adapter->reset_task, pch_gbe_reset_task);
pch_gbe_check_options(adapter);
/* initialize the wol settings based on the eeprom settings */
adapter->wake_up_evt = PCH_GBE_WL_INIT_SETTING;
dev_info(&pdev->dev, "MAC address : %pM\n", netdev->dev_addr);
/* reset the hardware with the new settings */
pch_gbe_reset(adapter);
ret = register_netdev(netdev);
if (ret)
goto err_free_adapter;
/* tell the stack to leave us alone until pch_gbe_open() is called */
netif_carrier_off(netdev);
netif_stop_queue(netdev);
dev_dbg(&pdev->dev, "PCH Network Connection\n");
device_set_wakeup_enable(&pdev->dev, 1);
return 0;
err_free_adapter:
pch_gbe_hal_phy_hw_reset(&adapter->hw);
kfree(adapter->tx_ring);
kfree(adapter->rx_ring);
err_iounmap:
iounmap(adapter->hw.reg);
err_free_netdev:
free_netdev(netdev);
err_release_pci:
pci_release_regions(pdev);
err_disable_device:
pci_disable_device(pdev);
return ret;
}
static DEFINE_PCI_DEVICE_TABLE(pch_gbe_pcidev_id) = {
{.vendor = PCI_VENDOR_ID_INTEL,
.device = PCI_DEVICE_ID_INTEL_IOH1_GBE,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
.class = (PCI_CLASS_NETWORK_ETHERNET << 8),
.class_mask = (0xFFFF00)
},
{.vendor = PCI_VENDOR_ID_ROHM,
.device = PCI_DEVICE_ID_ROHM_ML7223_GBE,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
.class = (PCI_CLASS_NETWORK_ETHERNET << 8),
.class_mask = (0xFFFF00)
},
{.vendor = PCI_VENDOR_ID_ROHM,
.device = PCI_DEVICE_ID_ROHM_ML7831_GBE,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
.class = (PCI_CLASS_NETWORK_ETHERNET << 8),
.class_mask = (0xFFFF00)
},
/* required last entry */
{0}
};
#ifdef CONFIG_PM
static const struct dev_pm_ops pch_gbe_pm_ops = {
.suspend = pch_gbe_suspend,
.resume = pch_gbe_resume,
.freeze = pch_gbe_suspend,
.thaw = pch_gbe_resume,
.poweroff = pch_gbe_suspend,
.restore = pch_gbe_resume,
};
#endif
static struct pci_error_handlers pch_gbe_err_handler = {
.error_detected = pch_gbe_io_error_detected,
.slot_reset = pch_gbe_io_slot_reset,
.resume = pch_gbe_io_resume
};
static struct pci_driver pch_gbe_driver = {
.name = KBUILD_MODNAME,
.id_table = pch_gbe_pcidev_id,
.probe = pch_gbe_probe,
.remove = pch_gbe_remove,
#ifdef CONFIG_PM
.driver.pm = &pch_gbe_pm_ops,
#endif
.shutdown = pch_gbe_shutdown,
.err_handler = &pch_gbe_err_handler
};
static int __init pch_gbe_init_module(void)
{
int ret;
ret = pci_register_driver(&pch_gbe_driver);
if (copybreak != PCH_GBE_COPYBREAK_DEFAULT) {
if (copybreak == 0) {
pr_info("copybreak disabled\n");
} else {
pr_info("copybreak enabled for packets <= %u bytes\n",
copybreak);
}
}
return ret;
}
static void __exit pch_gbe_exit_module(void)
{
pci_unregister_driver(&pch_gbe_driver);
}
module_init(pch_gbe_init_module);
module_exit(pch_gbe_exit_module);
MODULE_DESCRIPTION("EG20T PCH Gigabit ethernet Driver");
MODULE_AUTHOR("LAPIS SEMICONDUCTOR, <tshimizu818@gmail.com>");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
MODULE_DEVICE_TABLE(pci, pch_gbe_pcidev_id);
module_param(copybreak, uint, 0644);
MODULE_PARM_DESC(copybreak,
"Maximum size of packet that is copied to a new buffer on receive");
/* pch_gbe_main.c */
| gpl-2.0 |
brinlyaus/sturdy-eureka | drivers/video/auo_k190x.c | 4044 | 28261 | /*
* Common code for AUO-K190X framebuffer drivers
*
* Copyright (C) 2012 Heiko Stuebner <heiko@sntech.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/gpio.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/fb.h>
#include <linux/delay.h>
#include <linux/uaccess.h>
#include <linux/vmalloc.h>
#include <linux/regulator/consumer.h>
#include <video/auo_k190xfb.h>
#include "auo_k190x.h"
struct panel_info {
int w;
int h;
};
/* table of panel specific parameters to be indexed into by the board drivers */
static struct panel_info panel_table[] = {
/* standard 6" */
[AUOK190X_RESOLUTION_800_600] = {
.w = 800,
.h = 600,
},
/* standard 9" */
[AUOK190X_RESOLUTION_1024_768] = {
.w = 1024,
.h = 768,
},
[AUOK190X_RESOLUTION_600_800] = {
.w = 600,
.h = 800,
},
[AUOK190X_RESOLUTION_768_1024] = {
.w = 768,
.h = 1024,
},
};
/*
* private I80 interface to the board driver
*/
static void auok190x_issue_data(struct auok190xfb_par *par, u16 data)
{
par->board->set_ctl(par, AUOK190X_I80_WR, 0);
par->board->set_hdb(par, data);
par->board->set_ctl(par, AUOK190X_I80_WR, 1);
}
static void auok190x_issue_cmd(struct auok190xfb_par *par, u16 data)
{
par->board->set_ctl(par, AUOK190X_I80_DC, 0);
auok190x_issue_data(par, data);
par->board->set_ctl(par, AUOK190X_I80_DC, 1);
}
/**
* Conversion of 16bit color to 4bit grayscale
* does roughly (0.3 * R + 0.6 G + 0.1 B) / 2
*/
static inline int rgb565_to_gray4(u16 data, struct fb_var_screeninfo *var)
{
return ((((data & 0xF800) >> var->red.offset) * 77 +
((data & 0x07E0) >> (var->green.offset + 1)) * 151 +
((data & 0x1F) >> var->blue.offset) * 28) >> 8 >> 1);
}
static int auok190x_issue_pixels_rgb565(struct auok190xfb_par *par, int size,
u16 *data)
{
struct fb_var_screeninfo *var = &par->info->var;
struct device *dev = par->info->device;
int i;
u16 tmp;
if (size & 7) {
dev_err(dev, "issue_pixels: size %d must be a multiple of 8\n",
size);
return -EINVAL;
}
for (i = 0; i < (size >> 2); i++) {
par->board->set_ctl(par, AUOK190X_I80_WR, 0);
tmp = (rgb565_to_gray4(data[4*i], var) & 0x000F);
tmp |= (rgb565_to_gray4(data[4*i+1], var) << 4) & 0x00F0;
tmp |= (rgb565_to_gray4(data[4*i+2], var) << 8) & 0x0F00;
tmp |= (rgb565_to_gray4(data[4*i+3], var) << 12) & 0xF000;
par->board->set_hdb(par, tmp);
par->board->set_ctl(par, AUOK190X_I80_WR, 1);
}
return 0;
}
static int auok190x_issue_pixels_gray8(struct auok190xfb_par *par, int size,
u16 *data)
{
struct device *dev = par->info->device;
int i;
u16 tmp;
if (size & 3) {
dev_err(dev, "issue_pixels: size %d must be a multiple of 4\n",
size);
return -EINVAL;
}
for (i = 0; i < (size >> 1); i++) {
par->board->set_ctl(par, AUOK190X_I80_WR, 0);
/* simple reduction of 8bit staticgray to 4bit gray
* combines 4 * 4bit pixel values into a 16bit value
*/
tmp = (data[2*i] & 0xF0) >> 4;
tmp |= (data[2*i] & 0xF000) >> 8;
tmp |= (data[2*i+1] & 0xF0) << 4;
tmp |= (data[2*i+1] & 0xF000);
par->board->set_hdb(par, tmp);
par->board->set_ctl(par, AUOK190X_I80_WR, 1);
}
return 0;
}
static int auok190x_issue_pixels(struct auok190xfb_par *par, int size,
u16 *data)
{
struct fb_info *info = par->info;
struct device *dev = par->info->device;
if (info->var.bits_per_pixel == 8 && info->var.grayscale)
auok190x_issue_pixels_gray8(par, size, data);
else if (info->var.bits_per_pixel == 16)
auok190x_issue_pixels_rgb565(par, size, data);
else
dev_err(dev, "unsupported color mode (bits: %d, gray: %d)\n",
info->var.bits_per_pixel, info->var.grayscale);
return 0;
}
static u16 auok190x_read_data(struct auok190xfb_par *par)
{
u16 data;
par->board->set_ctl(par, AUOK190X_I80_OE, 0);
data = par->board->get_hdb(par);
par->board->set_ctl(par, AUOK190X_I80_OE, 1);
return data;
}
/*
* Command interface for the controller drivers
*/
void auok190x_send_command_nowait(struct auok190xfb_par *par, u16 data)
{
par->board->set_ctl(par, AUOK190X_I80_CS, 0);
auok190x_issue_cmd(par, data);
par->board->set_ctl(par, AUOK190X_I80_CS, 1);
}
EXPORT_SYMBOL_GPL(auok190x_send_command_nowait);
void auok190x_send_cmdargs_nowait(struct auok190xfb_par *par, u16 cmd,
int argc, u16 *argv)
{
int i;
par->board->set_ctl(par, AUOK190X_I80_CS, 0);
auok190x_issue_cmd(par, cmd);
for (i = 0; i < argc; i++)
auok190x_issue_data(par, argv[i]);
par->board->set_ctl(par, AUOK190X_I80_CS, 1);
}
EXPORT_SYMBOL_GPL(auok190x_send_cmdargs_nowait);
int auok190x_send_command(struct auok190xfb_par *par, u16 data)
{
int ret;
ret = par->board->wait_for_rdy(par);
if (ret)
return ret;
auok190x_send_command_nowait(par, data);
return 0;
}
EXPORT_SYMBOL_GPL(auok190x_send_command);
int auok190x_send_cmdargs(struct auok190xfb_par *par, u16 cmd,
int argc, u16 *argv)
{
int ret;
ret = par->board->wait_for_rdy(par);
if (ret)
return ret;
auok190x_send_cmdargs_nowait(par, cmd, argc, argv);
return 0;
}
EXPORT_SYMBOL_GPL(auok190x_send_cmdargs);
int auok190x_read_cmdargs(struct auok190xfb_par *par, u16 cmd,
int argc, u16 *argv)
{
int i, ret;
ret = par->board->wait_for_rdy(par);
if (ret)
return ret;
par->board->set_ctl(par, AUOK190X_I80_CS, 0);
auok190x_issue_cmd(par, cmd);
for (i = 0; i < argc; i++)
argv[i] = auok190x_read_data(par);
par->board->set_ctl(par, AUOK190X_I80_CS, 1);
return 0;
}
EXPORT_SYMBOL_GPL(auok190x_read_cmdargs);
void auok190x_send_cmdargs_pixels_nowait(struct auok190xfb_par *par, u16 cmd,
int argc, u16 *argv, int size, u16 *data)
{
int i;
par->board->set_ctl(par, AUOK190X_I80_CS, 0);
auok190x_issue_cmd(par, cmd);
for (i = 0; i < argc; i++)
auok190x_issue_data(par, argv[i]);
auok190x_issue_pixels(par, size, data);
par->board->set_ctl(par, AUOK190X_I80_CS, 1);
}
EXPORT_SYMBOL_GPL(auok190x_send_cmdargs_pixels_nowait);
int auok190x_send_cmdargs_pixels(struct auok190xfb_par *par, u16 cmd,
int argc, u16 *argv, int size, u16 *data)
{
int ret;
ret = par->board->wait_for_rdy(par);
if (ret)
return ret;
auok190x_send_cmdargs_pixels_nowait(par, cmd, argc, argv, size, data);
return 0;
}
EXPORT_SYMBOL_GPL(auok190x_send_cmdargs_pixels);
/*
* fbdefio callbacks - common on both controllers.
*/
static void auok190xfb_dpy_first_io(struct fb_info *info)
{
/* tell runtime-pm that we wish to use the device in a short time */
pm_runtime_get(info->device);
}
/* this is called back from the deferred io workqueue */
static void auok190xfb_dpy_deferred_io(struct fb_info *info,
struct list_head *pagelist)
{
struct fb_deferred_io *fbdefio = info->fbdefio;
struct auok190xfb_par *par = info->par;
u16 line_length = info->fix.line_length;
u16 yres = info->var.yres;
u16 y1 = 0, h = 0;
int prev_index = -1;
struct page *cur;
int h_inc;
int threshold;
if (!list_empty(pagelist))
/* the device resume should've been requested through first_io,
* if the resume did not finish until now, wait for it.
*/
pm_runtime_barrier(info->device);
else
/* We reached this via the fsync or some other way.
* In either case the first_io function did not run,
* so we runtime_resume the device here synchronously.
*/
pm_runtime_get_sync(info->device);
/* Do a full screen update every n updates to prevent
* excessive darkening of the Sipix display.
* If we do this, there is no need to walk the pages.
*/
if (par->need_refresh(par)) {
par->update_all(par);
goto out;
}
/* height increment is fixed per page */
h_inc = DIV_ROUND_UP(PAGE_SIZE , line_length);
/* calculate number of pages from pixel height */
threshold = par->consecutive_threshold / h_inc;
if (threshold < 1)
threshold = 1;
/* walk the written page list and swizzle the data */
list_for_each_entry(cur, &fbdefio->pagelist, lru) {
if (prev_index < 0) {
/* just starting so assign first page */
y1 = (cur->index << PAGE_SHIFT) / line_length;
h = h_inc;
} else if ((cur->index - prev_index) <= threshold) {
/* page is within our threshold for single updates */
h += h_inc * (cur->index - prev_index);
} else {
/* page not consecutive, issue previous update first */
par->update_partial(par, y1, y1 + h);
/* start over with our non consecutive page */
y1 = (cur->index << PAGE_SHIFT) / line_length;
h = h_inc;
}
prev_index = cur->index;
}
/* if we still have any pages to update we do so now */
if (h >= yres)
/* its a full screen update, just do it */
par->update_all(par);
else
par->update_partial(par, y1, min((u16) (y1 + h), yres));
out:
pm_runtime_mark_last_busy(info->device);
pm_runtime_put_autosuspend(info->device);
}
/*
* framebuffer operations
*/
/*
* this is the slow path from userspace. they can seek and write to
* the fb. it's inefficient to do anything less than a full screen draw
*/
static ssize_t auok190xfb_write(struct fb_info *info, const char __user *buf,
size_t count, loff_t *ppos)
{
struct auok190xfb_par *par = info->par;
unsigned long p = *ppos;
void *dst;
int err = 0;
unsigned long total_size;
if (info->state != FBINFO_STATE_RUNNING)
return -EPERM;
total_size = info->fix.smem_len;
if (p > total_size)
return -EFBIG;
if (count > total_size) {
err = -EFBIG;
count = total_size;
}
if (count + p > total_size) {
if (!err)
err = -ENOSPC;
count = total_size - p;
}
dst = (void *)(info->screen_base + p);
if (copy_from_user(dst, buf, count))
err = -EFAULT;
if (!err)
*ppos += count;
par->update_all(par);
return (err) ? err : count;
}
static void auok190xfb_fillrect(struct fb_info *info,
const struct fb_fillrect *rect)
{
struct auok190xfb_par *par = info->par;
sys_fillrect(info, rect);
par->update_all(par);
}
static void auok190xfb_copyarea(struct fb_info *info,
const struct fb_copyarea *area)
{
struct auok190xfb_par *par = info->par;
sys_copyarea(info, area);
par->update_all(par);
}
static void auok190xfb_imageblit(struct fb_info *info,
const struct fb_image *image)
{
struct auok190xfb_par *par = info->par;
sys_imageblit(info, image);
par->update_all(par);
}
static int auok190xfb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct device *dev = info->device;
struct auok190xfb_par *par = info->par;
struct panel_info *panel = &panel_table[par->resolution];
int size;
/*
* Color depth
*/
if (var->bits_per_pixel == 8 && var->grayscale == 1) {
/*
* For 8-bit grayscale, R, G, and B offset are equal.
*/
var->red.length = 8;
var->red.offset = 0;
var->red.msb_right = 0;
var->green.length = 8;
var->green.offset = 0;
var->green.msb_right = 0;
var->blue.length = 8;
var->blue.offset = 0;
var->blue.msb_right = 0;
var->transp.length = 0;
var->transp.offset = 0;
var->transp.msb_right = 0;
} else if (var->bits_per_pixel == 16) {
var->red.length = 5;
var->red.offset = 11;
var->red.msb_right = 0;
var->green.length = 6;
var->green.offset = 5;
var->green.msb_right = 0;
var->blue.length = 5;
var->blue.offset = 0;
var->blue.msb_right = 0;
var->transp.length = 0;
var->transp.offset = 0;
var->transp.msb_right = 0;
} else {
dev_warn(dev, "unsupported color mode (bits: %d, grayscale: %d)\n",
info->var.bits_per_pixel, info->var.grayscale);
return -EINVAL;
}
/*
* Dimensions
*/
switch (var->rotate) {
case FB_ROTATE_UR:
case FB_ROTATE_UD:
var->xres = panel->w;
var->yres = panel->h;
break;
case FB_ROTATE_CW:
case FB_ROTATE_CCW:
var->xres = panel->h;
var->yres = panel->w;
break;
default:
dev_dbg(dev, "Invalid rotation request\n");
return -EINVAL;
}
var->xres_virtual = var->xres;
var->yres_virtual = var->yres;
/*
* Memory limit
*/
size = var->xres_virtual * var->yres_virtual * var->bits_per_pixel / 8;
if (size > info->fix.smem_len) {
dev_err(dev, "Memory limit exceeded, requested %dK\n",
size >> 10);
return -ENOMEM;
}
return 0;
}
static int auok190xfb_set_fix(struct fb_info *info)
{
struct fb_fix_screeninfo *fix = &info->fix;
struct fb_var_screeninfo *var = &info->var;
fix->line_length = var->xres_virtual * var->bits_per_pixel / 8;
fix->type = FB_TYPE_PACKED_PIXELS;
fix->accel = FB_ACCEL_NONE;
fix->visual = (var->grayscale) ? FB_VISUAL_STATIC_PSEUDOCOLOR
: FB_VISUAL_TRUECOLOR;
fix->xpanstep = 0;
fix->ypanstep = 0;
fix->ywrapstep = 0;
return 0;
}
static int auok190xfb_set_par(struct fb_info *info)
{
struct auok190xfb_par *par = info->par;
par->rotation = info->var.rotate;
auok190xfb_set_fix(info);
/* reinit the controller to honor the rotation */
par->init(par);
/* wait for init to complete */
par->board->wait_for_rdy(par);
return 0;
}
static struct fb_ops auok190xfb_ops = {
.owner = THIS_MODULE,
.fb_read = fb_sys_read,
.fb_write = auok190xfb_write,
.fb_fillrect = auok190xfb_fillrect,
.fb_copyarea = auok190xfb_copyarea,
.fb_imageblit = auok190xfb_imageblit,
.fb_check_var = auok190xfb_check_var,
.fb_set_par = auok190xfb_set_par,
};
/*
* Controller-functions common to both K1900 and K1901
*/
static int auok190x_read_temperature(struct auok190xfb_par *par)
{
struct device *dev = par->info->device;
u16 data[4];
int temp;
pm_runtime_get_sync(dev);
mutex_lock(&(par->io_lock));
auok190x_read_cmdargs(par, AUOK190X_CMD_READ_VERSION, 4, data);
mutex_unlock(&(par->io_lock));
pm_runtime_mark_last_busy(dev);
pm_runtime_put_autosuspend(dev);
/* sanitize and split of half-degrees for now */
temp = ((data[0] & AUOK190X_VERSION_TEMP_MASK) >> 1);
/* handle positive and negative temperatures */
if (temp >= 201)
return (255 - temp + 1) * (-1);
else
return temp;
}
static void auok190x_identify(struct auok190xfb_par *par)
{
struct device *dev = par->info->device;
u16 data[4];
pm_runtime_get_sync(dev);
mutex_lock(&(par->io_lock));
auok190x_read_cmdargs(par, AUOK190X_CMD_READ_VERSION, 4, data);
mutex_unlock(&(par->io_lock));
par->epd_type = data[1] & AUOK190X_VERSION_TEMP_MASK;
par->panel_size_int = AUOK190X_VERSION_SIZE_INT(data[2]);
par->panel_size_float = AUOK190X_VERSION_SIZE_FLOAT(data[2]);
par->panel_model = AUOK190X_VERSION_MODEL(data[2]);
par->tcon_version = AUOK190X_VERSION_TCON(data[3]);
par->lut_version = AUOK190X_VERSION_LUT(data[3]);
dev_dbg(dev, "panel %d.%din, model 0x%x, EPD 0x%x TCON-rev 0x%x, LUT-rev 0x%x",
par->panel_size_int, par->panel_size_float, par->panel_model,
par->epd_type, par->tcon_version, par->lut_version);
pm_runtime_mark_last_busy(dev);
pm_runtime_put_autosuspend(dev);
}
/*
* Sysfs functions
*/
static ssize_t update_mode_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct fb_info *info = dev_get_drvdata(dev);
struct auok190xfb_par *par = info->par;
return sprintf(buf, "%d\n", par->update_mode);
}
static ssize_t update_mode_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct fb_info *info = dev_get_drvdata(dev);
struct auok190xfb_par *par = info->par;
int mode, ret;
ret = kstrtoint(buf, 10, &mode);
if (ret)
return ret;
par->update_mode = mode;
/* if we enter a better mode, do a full update */
if (par->last_mode > 1 && mode < par->last_mode)
par->update_all(par);
return count;
}
static ssize_t flash_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct fb_info *info = dev_get_drvdata(dev);
struct auok190xfb_par *par = info->par;
return sprintf(buf, "%d\n", par->flash);
}
static ssize_t flash_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct fb_info *info = dev_get_drvdata(dev);
struct auok190xfb_par *par = info->par;
int flash, ret;
ret = kstrtoint(buf, 10, &flash);
if (ret)
return ret;
if (flash > 0)
par->flash = 1;
else
par->flash = 0;
return count;
}
static ssize_t temp_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct fb_info *info = dev_get_drvdata(dev);
struct auok190xfb_par *par = info->par;
int temp;
temp = auok190x_read_temperature(par);
return sprintf(buf, "%d\n", temp);
}
static DEVICE_ATTR(update_mode, 0644, update_mode_show, update_mode_store);
static DEVICE_ATTR(flash, 0644, flash_show, flash_store);
static DEVICE_ATTR(temp, 0644, temp_show, NULL);
static struct attribute *auok190x_attributes[] = {
&dev_attr_update_mode.attr,
&dev_attr_flash.attr,
&dev_attr_temp.attr,
NULL
};
static const struct attribute_group auok190x_attr_group = {
.attrs = auok190x_attributes,
};
static int auok190x_power(struct auok190xfb_par *par, bool on)
{
struct auok190x_board *board = par->board;
int ret;
if (on) {
/* We should maintain POWER up for at least 80ms before set
* RST_N and SLP_N to high (TCON spec 20100803_v35 p59)
*/
ret = regulator_enable(par->regulator);
if (ret)
return ret;
msleep(200);
gpio_set_value(board->gpio_nrst, 1);
gpio_set_value(board->gpio_nsleep, 1);
msleep(200);
} else {
regulator_disable(par->regulator);
gpio_set_value(board->gpio_nrst, 0);
gpio_set_value(board->gpio_nsleep, 0);
}
return 0;
}
/*
* Recovery - powercycle the controller
*/
static void auok190x_recover(struct auok190xfb_par *par)
{
struct device *dev = par->info->device;
auok190x_power(par, 0);
msleep(100);
auok190x_power(par, 1);
/* after powercycling the device, it's always active */
pm_runtime_set_active(dev);
par->standby = 0;
par->init(par);
/* wait for init to complete */
par->board->wait_for_rdy(par);
}
/*
* Power-management
*/
#ifdef CONFIG_PM
static int auok190x_runtime_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct fb_info *info = platform_get_drvdata(pdev);
struct auok190xfb_par *par = info->par;
struct auok190x_board *board = par->board;
u16 standby_param;
/* take and keep the lock until we are resumed, as the controller
* will never reach the non-busy state when in standby mode
*/
mutex_lock(&(par->io_lock));
if (par->standby) {
dev_warn(dev, "already in standby, runtime-pm pairing mismatch\n");
mutex_unlock(&(par->io_lock));
return 0;
}
/* according to runtime_pm.txt runtime_suspend only means, that the
* device will not process data and will not communicate with the CPU
* As we hold the lock, this stays true even without standby
*/
if (board->quirks & AUOK190X_QUIRK_STANDBYBROKEN) {
dev_dbg(dev, "runtime suspend without standby\n");
goto finish;
} else if (board->quirks & AUOK190X_QUIRK_STANDBYPARAM) {
/* for some TCON versions STANDBY expects a parameter (0) but
* it seems the real tcon version has to be determined yet.
*/
dev_dbg(dev, "runtime suspend with additional empty param\n");
standby_param = 0;
auok190x_send_cmdargs(par, AUOK190X_CMD_STANDBY, 1,
&standby_param);
} else {
dev_dbg(dev, "runtime suspend without param\n");
auok190x_send_command(par, AUOK190X_CMD_STANDBY);
}
msleep(64);
finish:
par->standby = 1;
return 0;
}
static int auok190x_runtime_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct fb_info *info = platform_get_drvdata(pdev);
struct auok190xfb_par *par = info->par;
struct auok190x_board *board = par->board;
if (!par->standby) {
dev_warn(dev, "not in standby, runtime-pm pairing mismatch\n");
return 0;
}
if (board->quirks & AUOK190X_QUIRK_STANDBYBROKEN) {
dev_dbg(dev, "runtime resume without standby\n");
} else {
/* when in standby, controller is always busy
* and only accepts the wakeup command
*/
dev_dbg(dev, "runtime resume from standby\n");
auok190x_send_command_nowait(par, AUOK190X_CMD_WAKEUP);
msleep(160);
/* wait for the controller to be ready and release the lock */
board->wait_for_rdy(par);
}
par->standby = 0;
mutex_unlock(&(par->io_lock));
return 0;
}
static int auok190x_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct fb_info *info = platform_get_drvdata(pdev);
struct auok190xfb_par *par = info->par;
struct auok190x_board *board = par->board;
int ret;
dev_dbg(dev, "suspend\n");
if (board->quirks & AUOK190X_QUIRK_STANDBYBROKEN) {
/* suspend via powering off the ic */
dev_dbg(dev, "suspend with broken standby\n");
auok190x_power(par, 0);
} else {
dev_dbg(dev, "suspend using sleep\n");
/* the sleep state can only be entered from the standby state.
* pm_runtime_get_noresume gets called before the suspend call.
* So the devices usage count is >0 but it is not necessarily
* active.
*/
if (!pm_runtime_status_suspended(dev)) {
ret = auok190x_runtime_suspend(dev);
if (ret < 0) {
dev_err(dev, "auok190x_runtime_suspend failed with %d\n",
ret);
return ret;
}
par->manual_standby = 1;
}
gpio_direction_output(board->gpio_nsleep, 0);
}
msleep(100);
return 0;
}
static int auok190x_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct fb_info *info = platform_get_drvdata(pdev);
struct auok190xfb_par *par = info->par;
struct auok190x_board *board = par->board;
dev_dbg(dev, "resume\n");
if (board->quirks & AUOK190X_QUIRK_STANDBYBROKEN) {
dev_dbg(dev, "resume with broken standby\n");
auok190x_power(par, 1);
par->init(par);
} else {
dev_dbg(dev, "resume from sleep\n");
/* device should be in runtime suspend when we were suspended
* and pm_runtime_put_sync gets called after this function.
* So there is no need to touch the standby mode here at all.
*/
gpio_direction_output(board->gpio_nsleep, 1);
msleep(100);
/* an additional init call seems to be necessary after sleep */
auok190x_runtime_resume(dev);
par->init(par);
/* if we were runtime-suspended before, suspend again*/
if (!par->manual_standby)
auok190x_runtime_suspend(dev);
else
par->manual_standby = 0;
}
return 0;
}
#endif
const struct dev_pm_ops auok190x_pm = {
SET_RUNTIME_PM_OPS(auok190x_runtime_suspend, auok190x_runtime_resume,
NULL)
SET_SYSTEM_SLEEP_PM_OPS(auok190x_suspend, auok190x_resume)
};
EXPORT_SYMBOL_GPL(auok190x_pm);
/*
* Common probe and remove code
*/
int auok190x_common_probe(struct platform_device *pdev,
struct auok190x_init_data *init)
{
struct auok190x_board *board = init->board;
struct auok190xfb_par *par;
struct fb_info *info;
struct panel_info *panel;
int videomemorysize, ret;
unsigned char *videomemory;
/* check board contents */
if (!board->init || !board->cleanup || !board->wait_for_rdy
|| !board->set_ctl || !board->set_hdb || !board->get_hdb
|| !board->setup_irq)
return -EINVAL;
info = framebuffer_alloc(sizeof(struct auok190xfb_par), &pdev->dev);
if (!info)
return -ENOMEM;
par = info->par;
par->info = info;
par->board = board;
par->recover = auok190x_recover;
par->update_partial = init->update_partial;
par->update_all = init->update_all;
par->need_refresh = init->need_refresh;
par->init = init->init;
/* init update modes */
par->update_cnt = 0;
par->update_mode = -1;
par->last_mode = -1;
par->flash = 0;
par->regulator = regulator_get(info->device, "vdd");
if (IS_ERR(par->regulator)) {
ret = PTR_ERR(par->regulator);
dev_err(info->device, "Failed to get regulator: %d\n", ret);
goto err_reg;
}
ret = board->init(par);
if (ret) {
dev_err(info->device, "board init failed, %d\n", ret);
goto err_board;
}
ret = gpio_request(board->gpio_nsleep, "AUOK190x sleep");
if (ret) {
dev_err(info->device, "could not request sleep gpio, %d\n",
ret);
goto err_gpio1;
}
ret = gpio_direction_output(board->gpio_nsleep, 0);
if (ret) {
dev_err(info->device, "could not set sleep gpio, %d\n", ret);
goto err_gpio2;
}
ret = gpio_request(board->gpio_nrst, "AUOK190x reset");
if (ret) {
dev_err(info->device, "could not request reset gpio, %d\n",
ret);
goto err_gpio2;
}
ret = gpio_direction_output(board->gpio_nrst, 0);
if (ret) {
dev_err(info->device, "could not set reset gpio, %d\n", ret);
goto err_gpio3;
}
ret = auok190x_power(par, 1);
if (ret) {
dev_err(info->device, "could not power on the device, %d\n",
ret);
goto err_gpio3;
}
mutex_init(&par->io_lock);
init_waitqueue_head(&par->waitq);
ret = par->board->setup_irq(par->info);
if (ret) {
dev_err(info->device, "could not setup ready-irq, %d\n", ret);
goto err_irq;
}
/* wait for init to complete */
par->board->wait_for_rdy(par);
/*
* From here on the controller can talk to us
*/
/* initialise fix, var, resolution and rotation */
strlcpy(info->fix.id, init->id, 16);
info->var.bits_per_pixel = 8;
info->var.grayscale = 1;
panel = &panel_table[board->resolution];
par->resolution = board->resolution;
par->rotation = 0;
/* videomemory handling */
videomemorysize = roundup((panel->w * panel->h) * 2, PAGE_SIZE);
videomemory = vmalloc(videomemorysize);
if (!videomemory) {
ret = -ENOMEM;
goto err_irq;
}
memset(videomemory, 0, videomemorysize);
info->screen_base = (char *)videomemory;
info->fix.smem_len = videomemorysize;
info->flags = FBINFO_FLAG_DEFAULT | FBINFO_VIRTFB;
info->fbops = &auok190xfb_ops;
ret = auok190xfb_check_var(&info->var, info);
if (ret)
goto err_defio;
auok190xfb_set_fix(info);
/* deferred io init */
info->fbdefio = devm_kzalloc(info->device,
sizeof(struct fb_deferred_io),
GFP_KERNEL);
if (!info->fbdefio) {
dev_err(info->device, "Failed to allocate memory\n");
ret = -ENOMEM;
goto err_defio;
}
dev_dbg(info->device, "targeting %d frames per second\n", board->fps);
info->fbdefio->delay = HZ / board->fps;
info->fbdefio->first_io = auok190xfb_dpy_first_io,
info->fbdefio->deferred_io = auok190xfb_dpy_deferred_io,
fb_deferred_io_init(info);
/* color map */
ret = fb_alloc_cmap(&info->cmap, 256, 0);
if (ret < 0) {
dev_err(info->device, "Failed to allocate colormap\n");
goto err_cmap;
}
/* controller init */
par->consecutive_threshold = 100;
par->init(par);
auok190x_identify(par);
platform_set_drvdata(pdev, info);
ret = register_framebuffer(info);
if (ret < 0)
goto err_regfb;
ret = sysfs_create_group(&info->device->kobj, &auok190x_attr_group);
if (ret)
goto err_sysfs;
dev_info(info->device, "fb%d: %dx%d using %dK of video memory\n",
info->node, info->var.xres, info->var.yres,
videomemorysize >> 10);
/* increase autosuspend_delay when we use alternative methods
* for runtime_pm
*/
par->autosuspend_delay = (board->quirks & AUOK190X_QUIRK_STANDBYBROKEN)
? 1000 : 200;
pm_runtime_set_active(info->device);
pm_runtime_enable(info->device);
pm_runtime_set_autosuspend_delay(info->device, par->autosuspend_delay);
pm_runtime_use_autosuspend(info->device);
return 0;
err_sysfs:
unregister_framebuffer(info);
err_regfb:
fb_dealloc_cmap(&info->cmap);
err_cmap:
fb_deferred_io_cleanup(info);
err_defio:
vfree((void *)info->screen_base);
err_irq:
auok190x_power(par, 0);
err_gpio3:
gpio_free(board->gpio_nrst);
err_gpio2:
gpio_free(board->gpio_nsleep);
err_gpio1:
board->cleanup(par);
err_board:
regulator_put(par->regulator);
err_reg:
framebuffer_release(info);
return ret;
}
EXPORT_SYMBOL_GPL(auok190x_common_probe);
int auok190x_common_remove(struct platform_device *pdev)
{
struct fb_info *info = platform_get_drvdata(pdev);
struct auok190xfb_par *par = info->par;
struct auok190x_board *board = par->board;
pm_runtime_disable(info->device);
sysfs_remove_group(&info->device->kobj, &auok190x_attr_group);
unregister_framebuffer(info);
fb_dealloc_cmap(&info->cmap);
fb_deferred_io_cleanup(info);
vfree((void *)info->screen_base);
auok190x_power(par, 0);
gpio_free(board->gpio_nrst);
gpio_free(board->gpio_nsleep);
board->cleanup(par);
regulator_put(par->regulator);
framebuffer_release(info);
return 0;
}
EXPORT_SYMBOL_GPL(auok190x_common_remove);
MODULE_DESCRIPTION("Common code for AUO-K190X controllers");
MODULE_AUTHOR("Heiko Stuebner <heiko@sntech.de>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.