repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
pbystrup/CHIP-linux | arch/sh/kernel/cpu/sh4a/clock-sh7786.c | 546 | 6456 | /*
* arch/sh/kernel/cpu/sh4a/clock-sh7786.c
*
* SH7786 support for the clock framework
*
* Copyright (C) 2010 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/init.h>
#include <linux/kernel.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/clkdev.h>
#include <asm/clock.h>
#include <asm/freq.h>
/*
* Default rate for the root input clock, reset this with clk_set_rate()
* from the platform code.
*/
static struct clk extal_clk = {
.rate = 33333333,
};
static unsigned long pll_recalc(struct clk *clk)
{
int multiplier;
/*
* Clock modes 0, 1, and 2 use an x64 multiplier against PLL1,
* while modes 3, 4, and 5 use an x32.
*/
multiplier = (sh_mv.mv_mode_pins() & 0xf) < 3 ? 64 : 32;
return clk->parent->rate * multiplier;
}
static struct sh_clk_ops pll_clk_ops = {
.recalc = pll_recalc,
};
static struct clk pll_clk = {
.ops = &pll_clk_ops,
.parent = &extal_clk,
.flags = CLK_ENABLE_ON_INIT,
};
static struct clk *clks[] = {
&extal_clk,
&pll_clk,
};
static unsigned int div2[] = { 1, 2, 4, 6, 8, 12, 16, 18,
24, 32, 36, 48 };
static struct clk_div_mult_table div4_div_mult_table = {
.divisors = div2,
.nr_divisors = ARRAY_SIZE(div2),
};
static struct clk_div4_table div4_table = {
.div_mult_table = &div4_div_mult_table,
};
enum { DIV4_I, DIV4_SH, DIV4_B, DIV4_DDR, DIV4_DU, DIV4_P, DIV4_NR };
#define DIV4(_bit, _mask, _flags) \
SH_CLK_DIV4(&pll_clk, FRQMR1, _bit, _mask, _flags)
struct clk div4_clks[DIV4_NR] = {
[DIV4_P] = DIV4(0, 0x0b40, 0),
[DIV4_DU] = DIV4(4, 0x0010, 0),
[DIV4_DDR] = DIV4(12, 0x0002, CLK_ENABLE_ON_INIT),
[DIV4_B] = DIV4(16, 0x0360, CLK_ENABLE_ON_INIT),
[DIV4_SH] = DIV4(20, 0x0002, CLK_ENABLE_ON_INIT),
[DIV4_I] = DIV4(28, 0x0006, CLK_ENABLE_ON_INIT),
};
#define MSTPCR0 0xffc40030
#define MSTPCR1 0xffc40034
enum { MSTP029, MSTP028, MSTP027, MSTP026, MSTP025, MSTP024,
MSTP023, MSTP022, MSTP021, MSTP020, MSTP017, MSTP016,
MSTP015, MSTP014, MSTP011, MSTP010, MSTP009, MSTP008,
MSTP005, MSTP004, MSTP002,
MSTP112, MSTP110, MSTP109, MSTP108,
MSTP105, MSTP104, MSTP103, MSTP102,
MSTP_NR };
static struct clk mstp_clks[MSTP_NR] = {
/* MSTPCR0 */
[MSTP029] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 29, 0),
[MSTP028] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 28, 0),
[MSTP027] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 27, 0),
[MSTP026] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 26, 0),
[MSTP025] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 25, 0),
[MSTP024] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 24, 0),
[MSTP023] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 23, 0),
[MSTP022] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 22, 0),
[MSTP021] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 21, 0),
[MSTP020] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 20, 0),
[MSTP017] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 17, 0),
[MSTP016] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 16, 0),
[MSTP015] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 15, 0),
[MSTP014] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 14, 0),
[MSTP011] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 11, 0),
[MSTP010] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 10, 0),
[MSTP009] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 9, 0),
[MSTP008] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 8, 0),
[MSTP005] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 5, 0),
[MSTP004] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 4, 0),
[MSTP002] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 2, 0),
/* MSTPCR1 */
[MSTP112] = SH_CLK_MSTP32(NULL, MSTPCR1, 12, 0),
[MSTP110] = SH_CLK_MSTP32(NULL, MSTPCR1, 10, 0),
[MSTP109] = SH_CLK_MSTP32(NULL, MSTPCR1, 9, 0),
[MSTP108] = SH_CLK_MSTP32(NULL, MSTPCR1, 8, 0),
[MSTP105] = SH_CLK_MSTP32(NULL, MSTPCR1, 5, 0),
[MSTP104] = SH_CLK_MSTP32(NULL, MSTPCR1, 4, 0),
[MSTP103] = SH_CLK_MSTP32(NULL, MSTPCR1, 3, 0),
[MSTP102] = SH_CLK_MSTP32(NULL, MSTPCR1, 2, 0),
};
static struct clk_lookup lookups[] = {
/* main clocks */
CLKDEV_CON_ID("extal", &extal_clk),
CLKDEV_CON_ID("pll_clk", &pll_clk),
/* DIV4 clocks */
CLKDEV_CON_ID("peripheral_clk", &div4_clks[DIV4_P]),
CLKDEV_CON_ID("du_clk", &div4_clks[DIV4_DU]),
CLKDEV_CON_ID("ddr_clk", &div4_clks[DIV4_DDR]),
CLKDEV_CON_ID("bus_clk", &div4_clks[DIV4_B]),
CLKDEV_CON_ID("shyway_clk", &div4_clks[DIV4_SH]),
CLKDEV_CON_ID("cpu_clk", &div4_clks[DIV4_I]),
/* MSTP32 clocks */
CLKDEV_ICK_ID("sci_fck", "sh-sci.5", &mstp_clks[MSTP029]),
CLKDEV_ICK_ID("sci_fck", "sh-sci.4", &mstp_clks[MSTP028]),
CLKDEV_ICK_ID("sci_fck", "sh-sci.3", &mstp_clks[MSTP027]),
CLKDEV_ICK_ID("sci_fck", "sh-sci.2", &mstp_clks[MSTP026]),
CLKDEV_ICK_ID("sci_fck", "sh-sci.1", &mstp_clks[MSTP025]),
CLKDEV_ICK_ID("sci_fck", "sh-sci.0", &mstp_clks[MSTP024]),
CLKDEV_CON_ID("ssi3_fck", &mstp_clks[MSTP023]),
CLKDEV_CON_ID("ssi2_fck", &mstp_clks[MSTP022]),
CLKDEV_CON_ID("ssi1_fck", &mstp_clks[MSTP021]),
CLKDEV_CON_ID("ssi0_fck", &mstp_clks[MSTP020]),
CLKDEV_CON_ID("hac1_fck", &mstp_clks[MSTP017]),
CLKDEV_CON_ID("hac0_fck", &mstp_clks[MSTP016]),
CLKDEV_CON_ID("i2c1_fck", &mstp_clks[MSTP015]),
CLKDEV_CON_ID("i2c0_fck", &mstp_clks[MSTP014]),
CLKDEV_ICK_ID("fck", "sh-tmu.0", &mstp_clks[MSTP008]),
CLKDEV_ICK_ID("fck", "sh-tmu.1", &mstp_clks[MSTP009]),
CLKDEV_ICK_ID("fck", "sh-tmu.2", &mstp_clks[MSTP010]),
CLKDEV_ICK_ID("fck", "sh-tmu.3", &mstp_clks[MSTP011]),
CLKDEV_CON_ID("sdif1_fck", &mstp_clks[MSTP005]),
CLKDEV_CON_ID("sdif0_fck", &mstp_clks[MSTP004]),
CLKDEV_CON_ID("hspi_fck", &mstp_clks[MSTP002]),
CLKDEV_CON_ID("usb_fck", &mstp_clks[MSTP112]),
CLKDEV_CON_ID("pcie2_fck", &mstp_clks[MSTP110]),
CLKDEV_CON_ID("pcie1_fck", &mstp_clks[MSTP109]),
CLKDEV_CON_ID("pcie0_fck", &mstp_clks[MSTP108]),
CLKDEV_CON_ID("dmac_11_6_fck", &mstp_clks[MSTP105]),
CLKDEV_CON_ID("dmac_5_0_fck", &mstp_clks[MSTP104]),
CLKDEV_CON_ID("du_fck", &mstp_clks[MSTP103]),
CLKDEV_CON_ID("ether_fck", &mstp_clks[MSTP102]),
};
int __init arch_clk_init(void)
{
int i, ret = 0;
for (i = 0; i < ARRAY_SIZE(clks); i++)
ret |= clk_register(clks[i]);
clkdev_add_table(lookups, ARRAY_SIZE(lookups));
if (!ret)
ret = sh_clk_div4_register(div4_clks, ARRAY_SIZE(div4_clks),
&div4_table);
if (!ret)
ret = sh_clk_mstp_register(mstp_clks, MSTP_NR);
return ret;
}
| gpl-2.0 |
playfulgod/android_kernel_lge_ms910 | drivers/media/video/cx23885/cx23885-vbi.c | 802 | 6738 | /*
* Driver for the Conexant CX23885 PCIe bridge
*
* Copyright (c) 2007 Steven Toth <stoth@linuxtv.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include "cx23885.h"
static unsigned int vbibufs = 4;
module_param(vbibufs, int, 0644);
MODULE_PARM_DESC(vbibufs, "number of vbi buffers, range 2-32");
static unsigned int vbi_debug;
module_param(vbi_debug, int, 0644);
MODULE_PARM_DESC(vbi_debug, "enable debug messages [vbi]");
#define dprintk(level, fmt, arg...)\
do { if (vbi_debug >= level)\
printk(KERN_DEBUG "%s/0: " fmt, dev->name, ## arg);\
} while (0)
/* ------------------------------------------------------------------ */
int cx23885_vbi_fmt(struct file *file, void *priv,
struct v4l2_format *f)
{
struct cx23885_fh *fh = priv;
struct cx23885_dev *dev = fh->dev;
if (dev->tvnorm & V4L2_STD_525_60) {
/* ntsc */
f->fmt.vbi.sampling_rate = 28636363;
f->fmt.vbi.start[0] = 10;
f->fmt.vbi.start[1] = 273;
} else if (dev->tvnorm & V4L2_STD_625_50) {
/* pal */
f->fmt.vbi.sampling_rate = 35468950;
f->fmt.vbi.start[0] = 7 - 1;
f->fmt.vbi.start[1] = 319 - 1;
}
return 0;
}
static int cx23885_start_vbi_dma(struct cx23885_dev *dev,
struct cx23885_dmaqueue *q,
struct cx23885_buffer *buf)
{
/* setup fifo + format */
cx23885_sram_channel_setup(dev, &dev->sram_channels[SRAM_CH02],
buf->vb.width, buf->risc.dma);
/* reset counter */
q->count = 1;
/* enable irqs */
cx_set(PCI_INT_MSK, cx_read(PCI_INT_MSK) | 0x01);
cx_set(VID_A_INT_MSK, 0x000022);
/* start dma */
cx_set(DEV_CNTRL2, (1<<5));
cx_set(VID_A_DMA_CTL, 0x00000022);
return 0;
}
static int cx23885_restart_vbi_queue(struct cx23885_dev *dev,
struct cx23885_dmaqueue *q)
{
struct cx23885_buffer *buf;
struct list_head *item;
if (list_empty(&q->active))
return 0;
buf = list_entry(q->active.next, struct cx23885_buffer, vb.queue);
dprintk(2, "restart_queue [%p/%d]: restart dma\n",
buf, buf->vb.i);
cx23885_start_vbi_dma(dev, q, buf);
list_for_each(item, &q->active) {
buf = list_entry(item, struct cx23885_buffer, vb.queue);
buf->count = q->count++;
}
mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
return 0;
}
void cx23885_vbi_timeout(unsigned long data)
{
struct cx23885_dev *dev = (struct cx23885_dev *)data;
struct cx23885_dmaqueue *q = &dev->vbiq;
struct cx23885_buffer *buf;
unsigned long flags;
cx23885_sram_channel_dump(dev, &dev->sram_channels[SRAM_CH02]);
cx_clear(VID_A_DMA_CTL, 0x22);
spin_lock_irqsave(&dev->slock, flags);
while (!list_empty(&q->active)) {
buf = list_entry(q->active.next, struct cx23885_buffer,
vb.queue);
list_del(&buf->vb.queue);
buf->vb.state = VIDEOBUF_ERROR;
wake_up(&buf->vb.done);
printk("%s/0: [%p/%d] timeout - dma=0x%08lx\n", dev->name,
buf, buf->vb.i, (unsigned long)buf->risc.dma);
}
cx23885_restart_vbi_queue(dev, q);
spin_unlock_irqrestore(&dev->slock, flags);
}
/* ------------------------------------------------------------------ */
#define VBI_LINE_LENGTH 2048
#define VBI_LINE_COUNT 17
static int
vbi_setup(struct videobuf_queue *q, unsigned int *count, unsigned int *size)
{
*size = VBI_LINE_COUNT * VBI_LINE_LENGTH * 2;
if (0 == *count)
*count = vbibufs;
if (*count < 2)
*count = 2;
if (*count > 32)
*count = 32;
return 0;
}
static int
vbi_prepare(struct videobuf_queue *q, struct videobuf_buffer *vb,
enum v4l2_field field)
{
struct cx23885_fh *fh = q->priv_data;
struct cx23885_dev *dev = fh->dev;
struct cx23885_buffer *buf = container_of(vb,
struct cx23885_buffer, vb);
struct videobuf_dmabuf *dma = videobuf_to_dma(&buf->vb);
unsigned int size;
int rc;
size = VBI_LINE_COUNT * VBI_LINE_LENGTH * 2;
if (0 != buf->vb.baddr && buf->vb.bsize < size)
return -EINVAL;
if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
buf->vb.width = VBI_LINE_LENGTH;
buf->vb.height = VBI_LINE_COUNT;
buf->vb.size = size;
buf->vb.field = V4L2_FIELD_SEQ_TB;
rc = videobuf_iolock(q, &buf->vb, NULL);
if (0 != rc)
goto fail;
cx23885_risc_buffer(dev->pci, &buf->risc,
dma->sglist,
0, buf->vb.width * buf->vb.height,
buf->vb.width, 0,
buf->vb.height);
}
buf->vb.state = VIDEOBUF_PREPARED;
return 0;
fail:
cx23885_free_buffer(q, buf);
return rc;
}
static void
vbi_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
{
struct cx23885_buffer *buf =
container_of(vb, struct cx23885_buffer, vb);
struct cx23885_buffer *prev;
struct cx23885_fh *fh = vq->priv_data;
struct cx23885_dev *dev = fh->dev;
struct cx23885_dmaqueue *q = &dev->vbiq;
/* add jump to stopper */
buf->risc.jmp[0] = cpu_to_le32(RISC_JUMP | RISC_IRQ1 | RISC_CNT_INC);
buf->risc.jmp[1] = cpu_to_le32(q->stopper.dma);
buf->risc.jmp[2] = cpu_to_le32(0); /* bits 63-32 */
if (list_empty(&q->active)) {
list_add_tail(&buf->vb.queue, &q->active);
cx23885_start_vbi_dma(dev, q, buf);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = q->count++;
mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
dprintk(2, "[%p/%d] vbi_queue - first active\n",
buf, buf->vb.i);
} else {
prev = list_entry(q->active.prev, struct cx23885_buffer,
vb.queue);
list_add_tail(&buf->vb.queue, &q->active);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = q->count++;
prev->risc.jmp[1] = cpu_to_le32(buf->risc.dma);
prev->risc.jmp[2] = cpu_to_le32(0); /* Bits 63-32 */
dprintk(2, "[%p/%d] buffer_queue - append to active\n",
buf, buf->vb.i);
}
}
static void vbi_release(struct videobuf_queue *q, struct videobuf_buffer *vb)
{
struct cx23885_buffer *buf =
container_of(vb, struct cx23885_buffer, vb);
cx23885_free_buffer(q, buf);
}
struct videobuf_queue_ops cx23885_vbi_qops = {
.buf_setup = vbi_setup,
.buf_prepare = vbi_prepare,
.buf_queue = vbi_queue,
.buf_release = vbi_release,
};
/* ------------------------------------------------------------------ */
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
tcp209/kernel_samsung_epic4gtouch | drivers/media/video/cx88/cx88-alsa.c | 802 | 23068 | /*
*
* Support for audio capture
* PCI function #1 of the cx2388x.
*
* (c) 2007 Trent Piepho <xyzzy@speakeasy.org>
* (c) 2005,2006 Ricardo Cerqueira <v4l@cerqueira.org>
* (c) 2005 Mauro Carvalho Chehab <mchehab@infradead.org>
* Based on a dummy cx88 module by Gerd Knorr <kraxel@bytesex.org>
* Based on dummy.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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/vmalloc.h>
#include <linux/dma-mapping.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <asm/delay.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/control.h>
#include <sound/initval.h>
#include <sound/tlv.h>
#include "cx88.h"
#include "cx88-reg.h"
#define dprintk(level,fmt, arg...) if (debug >= level) \
printk(KERN_INFO "%s/1: " fmt, chip->core->name , ## arg)
#define dprintk_core(level,fmt, arg...) if (debug >= level) \
printk(KERN_DEBUG "%s/1: " fmt, chip->core->name , ## arg)
/****************************************************************************
Data type declarations - Can be moded to a header file later
****************************************************************************/
struct cx88_audio_dev {
struct cx88_core *core;
struct cx88_dmaqueue q;
/* pci i/o */
struct pci_dev *pci;
/* audio controls */
int irq;
struct snd_card *card;
spinlock_t reg_lock;
atomic_t count;
unsigned int dma_size;
unsigned int period_size;
unsigned int num_periods;
struct videobuf_dmabuf *dma_risc;
struct cx88_buffer *buf;
struct snd_pcm_substream *substream;
};
typedef struct cx88_audio_dev snd_cx88_card_t;
/****************************************************************************
Module global static vars
****************************************************************************/
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static int enable[SNDRV_CARDS] = {1, [1 ... (SNDRV_CARDS - 1)] = 1};
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable cx88x soundcard. default enabled.");
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for cx88x capture interface(s).");
/****************************************************************************
Module macros
****************************************************************************/
MODULE_DESCRIPTION("ALSA driver module for cx2388x based TV cards");
MODULE_AUTHOR("Ricardo Cerqueira");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@infradead.org>");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Conexant,23881},"
"{{Conexant,23882},"
"{{Conexant,23883}");
static unsigned int debug;
module_param(debug,int,0644);
MODULE_PARM_DESC(debug,"enable debug messages");
/****************************************************************************
Module specific funtions
****************************************************************************/
/*
* BOARD Specific: Sets audio DMA
*/
static int _cx88_start_audio_dma(snd_cx88_card_t *chip)
{
struct cx88_buffer *buf = chip->buf;
struct cx88_core *core=chip->core;
struct sram_channel *audio_ch = &cx88_sram_channels[SRAM_CH25];
/* Make sure RISC/FIFO are off before changing FIFO/RISC settings */
cx_clear(MO_AUD_DMACNTRL, 0x11);
/* setup fifo + format - out channel */
cx88_sram_channel_setup(chip->core, audio_ch, buf->bpl, buf->risc.dma);
/* sets bpl size */
cx_write(MO_AUDD_LNGTH, buf->bpl);
/* reset counter */
cx_write(MO_AUDD_GPCNTRL, GP_COUNT_CONTROL_RESET);
atomic_set(&chip->count, 0);
dprintk(1, "Start audio DMA, %d B/line, %d lines/FIFO, %d periods, %d "
"byte buffer\n", buf->bpl, cx_read(audio_ch->cmds_start + 8)>>1,
chip->num_periods, buf->bpl * chip->num_periods);
/* Enables corresponding bits at AUD_INT_STAT */
cx_write(MO_AUD_INTMSK, AUD_INT_OPC_ERR | AUD_INT_DN_SYNC |
AUD_INT_DN_RISCI2 | AUD_INT_DN_RISCI1);
/* Clean any pending interrupt bits already set */
cx_write(MO_AUD_INTSTAT, ~0);
/* enable audio irqs */
cx_set(MO_PCI_INTMSK, chip->core->pci_irqmask | PCI_INT_AUDINT);
/* start dma */
cx_set(MO_DEV_CNTRL2, (1<<5)); /* Enables Risc Processor */
cx_set(MO_AUD_DMACNTRL, 0x11); /* audio downstream FIFO and RISC enable */
if (debug)
cx88_sram_channel_dump(chip->core, audio_ch);
return 0;
}
/*
* BOARD Specific: Resets audio DMA
*/
static int _cx88_stop_audio_dma(snd_cx88_card_t *chip)
{
struct cx88_core *core=chip->core;
dprintk(1, "Stopping audio DMA\n");
/* stop dma */
cx_clear(MO_AUD_DMACNTRL, 0x11);
/* disable irqs */
cx_clear(MO_PCI_INTMSK, PCI_INT_AUDINT);
cx_clear(MO_AUD_INTMSK, AUD_INT_OPC_ERR | AUD_INT_DN_SYNC |
AUD_INT_DN_RISCI2 | AUD_INT_DN_RISCI1);
if (debug)
cx88_sram_channel_dump(chip->core, &cx88_sram_channels[SRAM_CH25]);
return 0;
}
#define MAX_IRQ_LOOP 50
/*
* BOARD Specific: IRQ dma bits
*/
static char *cx88_aud_irqs[32] = {
"dn_risci1", "up_risci1", "rds_dn_risc1", /* 0-2 */
NULL, /* reserved */
"dn_risci2", "up_risci2", "rds_dn_risc2", /* 4-6 */
NULL, /* reserved */
"dnf_of", "upf_uf", "rds_dnf_uf", /* 8-10 */
NULL, /* reserved */
"dn_sync", "up_sync", "rds_dn_sync", /* 12-14 */
NULL, /* reserved */
"opc_err", "par_err", "rip_err", /* 16-18 */
"pci_abort", "ber_irq", "mchg_irq" /* 19-21 */
};
/*
* BOARD Specific: Threats IRQ audio specific calls
*/
static void cx8801_aud_irq(snd_cx88_card_t *chip)
{
struct cx88_core *core = chip->core;
u32 status, mask;
status = cx_read(MO_AUD_INTSTAT);
mask = cx_read(MO_AUD_INTMSK);
if (0 == (status & mask))
return;
cx_write(MO_AUD_INTSTAT, status);
if (debug > 1 || (status & mask & ~0xff))
cx88_print_irqbits(core->name, "irq aud",
cx88_aud_irqs, ARRAY_SIZE(cx88_aud_irqs),
status, mask);
/* risc op code error */
if (status & AUD_INT_OPC_ERR) {
printk(KERN_WARNING "%s/1: Audio risc op code error\n",core->name);
cx_clear(MO_AUD_DMACNTRL, 0x11);
cx88_sram_channel_dump(core, &cx88_sram_channels[SRAM_CH25]);
}
if (status & AUD_INT_DN_SYNC) {
dprintk(1, "Downstream sync error\n");
cx_write(MO_AUDD_GPCNTRL, GP_COUNT_CONTROL_RESET);
return;
}
/* risc1 downstream */
if (status & AUD_INT_DN_RISCI1) {
atomic_set(&chip->count, cx_read(MO_AUDD_GPCNT));
snd_pcm_period_elapsed(chip->substream);
}
/* FIXME: Any other status should deserve a special handling? */
}
/*
* BOARD Specific: Handles IRQ calls
*/
static irqreturn_t cx8801_irq(int irq, void *dev_id)
{
snd_cx88_card_t *chip = dev_id;
struct cx88_core *core = chip->core;
u32 status;
int loop, handled = 0;
for (loop = 0; loop < MAX_IRQ_LOOP; loop++) {
status = cx_read(MO_PCI_INTSTAT) &
(core->pci_irqmask | PCI_INT_AUDINT);
if (0 == status)
goto out;
dprintk(3, "cx8801_irq loop %d/%d, status %x\n",
loop, MAX_IRQ_LOOP, status);
handled = 1;
cx_write(MO_PCI_INTSTAT, status);
if (status & core->pci_irqmask)
cx88_core_irq(core, status);
if (status & PCI_INT_AUDINT)
cx8801_aud_irq(chip);
}
if (MAX_IRQ_LOOP == loop) {
printk(KERN_ERR
"%s/1: IRQ loop detected, disabling interrupts\n",
core->name);
cx_clear(MO_PCI_INTMSK, PCI_INT_AUDINT);
}
out:
return IRQ_RETVAL(handled);
}
static int dsp_buffer_free(snd_cx88_card_t *chip)
{
BUG_ON(!chip->dma_size);
dprintk(2,"Freeing buffer\n");
videobuf_sg_dma_unmap(&chip->pci->dev, chip->dma_risc);
videobuf_dma_free(chip->dma_risc);
btcx_riscmem_free(chip->pci,&chip->buf->risc);
kfree(chip->buf);
chip->dma_risc = NULL;
chip->dma_size = 0;
return 0;
}
/****************************************************************************
ALSA PCM Interface
****************************************************************************/
/*
* Digital hardware definition
*/
#define DEFAULT_FIFO_SIZE 4096
static struct snd_pcm_hardware snd_cx88_digital_hw = {
.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP_VALID,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_48000,
.rate_min = 48000,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
/* Analog audio output will be full of clicks and pops if there
are not exactly four lines in the SRAM FIFO buffer. */
.period_bytes_min = DEFAULT_FIFO_SIZE/4,
.period_bytes_max = DEFAULT_FIFO_SIZE/4,
.periods_min = 1,
.periods_max = 1024,
.buffer_bytes_max = (1024*1024),
};
/*
* audio pcm capture open callback
*/
static int snd_cx88_pcm_open(struct snd_pcm_substream *substream)
{
snd_cx88_card_t *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
if (!chip) {
printk(KERN_ERR "BUG: cx88 can't find device struct."
" Can't proceed with open\n");
return -ENODEV;
}
err = snd_pcm_hw_constraint_pow2(runtime, 0, SNDRV_PCM_HW_PARAM_PERIODS);
if (err < 0)
goto _error;
chip->substream = substream;
runtime->hw = snd_cx88_digital_hw;
if (cx88_sram_channels[SRAM_CH25].fifo_size != DEFAULT_FIFO_SIZE) {
unsigned int bpl = cx88_sram_channels[SRAM_CH25].fifo_size / 4;
bpl &= ~7; /* must be multiple of 8 */
runtime->hw.period_bytes_min = bpl;
runtime->hw.period_bytes_max = bpl;
}
return 0;
_error:
dprintk(1,"Error opening PCM!\n");
return err;
}
/*
* audio close callback
*/
static int snd_cx88_close(struct snd_pcm_substream *substream)
{
return 0;
}
/*
* hw_params callback
*/
static int snd_cx88_hw_params(struct snd_pcm_substream * substream,
struct snd_pcm_hw_params * hw_params)
{
snd_cx88_card_t *chip = snd_pcm_substream_chip(substream);
struct videobuf_dmabuf *dma;
struct cx88_buffer *buf;
int ret;
if (substream->runtime->dma_area) {
dsp_buffer_free(chip);
substream->runtime->dma_area = NULL;
}
chip->period_size = params_period_bytes(hw_params);
chip->num_periods = params_periods(hw_params);
chip->dma_size = chip->period_size * params_periods(hw_params);
BUG_ON(!chip->dma_size);
BUG_ON(chip->num_periods & (chip->num_periods-1));
buf = videobuf_sg_alloc(sizeof(*buf));
if (NULL == buf)
return -ENOMEM;
buf->vb.memory = V4L2_MEMORY_MMAP;
buf->vb.field = V4L2_FIELD_NONE;
buf->vb.width = chip->period_size;
buf->bpl = chip->period_size;
buf->vb.height = chip->num_periods;
buf->vb.size = chip->dma_size;
dma = videobuf_to_dma(&buf->vb);
videobuf_dma_init(dma);
ret = videobuf_dma_init_kernel(dma, PCI_DMA_FROMDEVICE,
(PAGE_ALIGN(buf->vb.size) >> PAGE_SHIFT));
if (ret < 0)
goto error;
ret = videobuf_sg_dma_map(&chip->pci->dev, dma);
if (ret < 0)
goto error;
ret = cx88_risc_databuffer(chip->pci, &buf->risc, dma->sglist,
buf->vb.width, buf->vb.height, 1);
if (ret < 0)
goto error;
/* Loop back to start of program */
buf->risc.jmp[0] = cpu_to_le32(RISC_JUMP|RISC_IRQ1|RISC_CNT_INC);
buf->risc.jmp[1] = cpu_to_le32(buf->risc.dma);
buf->vb.state = VIDEOBUF_PREPARED;
chip->buf = buf;
chip->dma_risc = dma;
substream->runtime->dma_area = chip->dma_risc->vmalloc;
substream->runtime->dma_bytes = chip->dma_size;
substream->runtime->dma_addr = 0;
return 0;
error:
kfree(buf);
return ret;
}
/*
* hw free callback
*/
static int snd_cx88_hw_free(struct snd_pcm_substream * substream)
{
snd_cx88_card_t *chip = snd_pcm_substream_chip(substream);
if (substream->runtime->dma_area) {
dsp_buffer_free(chip);
substream->runtime->dma_area = NULL;
}
return 0;
}
/*
* prepare callback
*/
static int snd_cx88_prepare(struct snd_pcm_substream *substream)
{
return 0;
}
/*
* trigger callback
*/
static int snd_cx88_card_trigger(struct snd_pcm_substream *substream, int cmd)
{
snd_cx88_card_t *chip = snd_pcm_substream_chip(substream);
int err;
/* Local interrupts are already disabled by ALSA */
spin_lock(&chip->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
err=_cx88_start_audio_dma(chip);
break;
case SNDRV_PCM_TRIGGER_STOP:
err=_cx88_stop_audio_dma(chip);
break;
default:
err=-EINVAL;
break;
}
spin_unlock(&chip->reg_lock);
return err;
}
/*
* pointer callback
*/
static snd_pcm_uframes_t snd_cx88_pointer(struct snd_pcm_substream *substream)
{
snd_cx88_card_t *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
u16 count;
count = atomic_read(&chip->count);
// dprintk(2, "%s - count %d (+%u), period %d, frame %lu\n", __func__,
// count, new, count & (runtime->periods-1),
// runtime->period_size * (count & (runtime->periods-1)));
return runtime->period_size * (count & (runtime->periods-1));
}
/*
* page callback (needed for mmap)
*/
static struct page *snd_cx88_page(struct snd_pcm_substream *substream,
unsigned long offset)
{
void *pageptr = substream->runtime->dma_area + offset;
return vmalloc_to_page(pageptr);
}
/*
* operators
*/
static struct snd_pcm_ops snd_cx88_pcm_ops = {
.open = snd_cx88_pcm_open,
.close = snd_cx88_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_cx88_hw_params,
.hw_free = snd_cx88_hw_free,
.prepare = snd_cx88_prepare,
.trigger = snd_cx88_card_trigger,
.pointer = snd_cx88_pointer,
.page = snd_cx88_page,
};
/*
* create a PCM device
*/
static int __devinit snd_cx88_pcm(snd_cx88_card_t *chip, int device, char *name)
{
int err;
struct snd_pcm *pcm;
err = snd_pcm_new(chip->card, name, device, 0, 1, &pcm);
if (err < 0)
return err;
pcm->private_data = chip;
strcpy(pcm->name, name);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_cx88_pcm_ops);
return 0;
}
/****************************************************************************
CONTROL INTERFACE
****************************************************************************/
static int snd_cx88_volume_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *info)
{
info->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
info->count = 2;
info->value.integer.min = 0;
info->value.integer.max = 0x3f;
return 0;
}
static int snd_cx88_volume_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *value)
{
snd_cx88_card_t *chip = snd_kcontrol_chip(kcontrol);
struct cx88_core *core=chip->core;
int vol = 0x3f - (cx_read(AUD_VOL_CTL) & 0x3f),
bal = cx_read(AUD_BAL_CTL);
value->value.integer.value[(bal & 0x40) ? 0 : 1] = vol;
vol -= (bal & 0x3f);
value->value.integer.value[(bal & 0x40) ? 1 : 0] = vol < 0 ? 0 : vol;
return 0;
}
/* OK - TODO: test it */
static int snd_cx88_volume_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *value)
{
snd_cx88_card_t *chip = snd_kcontrol_chip(kcontrol);
struct cx88_core *core=chip->core;
int left, right, v, b;
int changed = 0;
u32 old;
left = value->value.integer.value[0] & 0x3f;
right = value->value.integer.value[1] & 0x3f;
b = right - left;
if (b < 0) {
v = 0x3f - left;
b = (-b) | 0x40;
} else {
v = 0x3f - right;
}
/* Do we really know this will always be called with IRQs on? */
spin_lock_irq(&chip->reg_lock);
old = cx_read(AUD_VOL_CTL);
if (v != (old & 0x3f)) {
cx_write(AUD_VOL_CTL, (old & ~0x3f) | v);
changed = 1;
}
if (cx_read(AUD_BAL_CTL) != b) {
cx_write(AUD_BAL_CTL, b);
changed = 1;
}
spin_unlock_irq(&chip->reg_lock);
return changed;
}
static const DECLARE_TLV_DB_SCALE(snd_cx88_db_scale, -6300, 100, 0);
static struct snd_kcontrol_new snd_cx88_volume = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ,
.name = "Playback Volume",
.info = snd_cx88_volume_info,
.get = snd_cx88_volume_get,
.put = snd_cx88_volume_put,
.tlv.p = snd_cx88_db_scale,
};
static int snd_cx88_switch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *value)
{
snd_cx88_card_t *chip = snd_kcontrol_chip(kcontrol);
struct cx88_core *core = chip->core;
u32 bit = kcontrol->private_value;
value->value.integer.value[0] = !(cx_read(AUD_VOL_CTL) & bit);
return 0;
}
static int snd_cx88_switch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *value)
{
snd_cx88_card_t *chip = snd_kcontrol_chip(kcontrol);
struct cx88_core *core = chip->core;
u32 bit = kcontrol->private_value;
int ret = 0;
u32 vol;
spin_lock_irq(&chip->reg_lock);
vol = cx_read(AUD_VOL_CTL);
if (value->value.integer.value[0] != !(vol & bit)) {
vol ^= bit;
cx_write(AUD_VOL_CTL, vol);
ret = 1;
}
spin_unlock_irq(&chip->reg_lock);
return ret;
}
static struct snd_kcontrol_new snd_cx88_dac_switch = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Playback Switch",
.info = snd_ctl_boolean_mono_info,
.get = snd_cx88_switch_get,
.put = snd_cx88_switch_put,
.private_value = (1<<8),
};
static struct snd_kcontrol_new snd_cx88_source_switch = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Switch",
.info = snd_ctl_boolean_mono_info,
.get = snd_cx88_switch_get,
.put = snd_cx88_switch_put,
.private_value = (1<<6),
};
/****************************************************************************
Basic Flow for Sound Devices
****************************************************************************/
/*
* PCI ID Table - 14f1:8801 and 14f1:8811 means function 1: Audio
* Only boards with eeprom and byte 1 at eeprom=1 have it
*/
static struct pci_device_id cx88_audio_pci_tbl[] __devinitdata = {
{0x14f1,0x8801,PCI_ANY_ID,PCI_ANY_ID,0,0,0},
{0x14f1,0x8811,PCI_ANY_ID,PCI_ANY_ID,0,0,0},
{0, }
};
MODULE_DEVICE_TABLE(pci, cx88_audio_pci_tbl);
/*
* Chip-specific destructor
*/
static int snd_cx88_free(snd_cx88_card_t *chip)
{
if (chip->irq >= 0)
free_irq(chip->irq, chip);
cx88_core_put(chip->core,chip->pci);
pci_disable_device(chip->pci);
return 0;
}
/*
* Component Destructor
*/
static void snd_cx88_dev_free(struct snd_card * card)
{
snd_cx88_card_t *chip = card->private_data;
snd_cx88_free(chip);
}
/*
* Alsa Constructor - Component probe
*/
static int devno;
static int __devinit snd_cx88_create(struct snd_card *card,
struct pci_dev *pci,
snd_cx88_card_t **rchip)
{
snd_cx88_card_t *chip;
struct cx88_core *core;
int err;
unsigned char pci_lat;
*rchip = NULL;
err = pci_enable_device(pci);
if (err < 0)
return err;
pci_set_master(pci);
chip = (snd_cx88_card_t *) card->private_data;
core = cx88_core_get(pci);
if (NULL == core) {
err = -EINVAL;
return err;
}
if (!pci_dma_supported(pci,DMA_BIT_MASK(32))) {
dprintk(0, "%s/1: Oops: no 32bit PCI DMA ???\n",core->name);
err = -EIO;
cx88_core_put(core,pci);
return err;
}
/* pci init */
chip->card = card;
chip->pci = pci;
chip->irq = -1;
spin_lock_init(&chip->reg_lock);
chip->core = core;
/* get irq */
err = request_irq(chip->pci->irq, cx8801_irq,
IRQF_SHARED | IRQF_DISABLED, chip->core->name, chip);
if (err < 0) {
dprintk(0, "%s: can't get IRQ %d\n",
chip->core->name, chip->pci->irq);
return err;
}
/* print pci info */
pci_read_config_byte(pci, PCI_LATENCY_TIMER, &pci_lat);
dprintk(1,"ALSA %s/%i: found at %s, rev: %d, irq: %d, "
"latency: %d, mmio: 0x%llx\n", core->name, devno,
pci_name(pci), pci->revision, pci->irq,
pci_lat, (unsigned long long)pci_resource_start(pci,0));
chip->irq = pci->irq;
synchronize_irq(chip->irq);
snd_card_set_dev(card, &pci->dev);
*rchip = chip;
return 0;
}
static int __devinit cx88_audio_initdev(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
struct snd_card *card;
snd_cx88_card_t *chip;
int err;
if (devno >= SNDRV_CARDS)
return (-ENODEV);
if (!enable[devno]) {
++devno;
return (-ENOENT);
}
err = snd_card_create(index[devno], id[devno], THIS_MODULE,
sizeof(snd_cx88_card_t), &card);
if (err < 0)
return err;
card->private_free = snd_cx88_dev_free;
err = snd_cx88_create(card, pci, &chip);
if (err < 0)
goto error;
err = snd_cx88_pcm(chip, 0, "CX88 Digital");
if (err < 0)
goto error;
err = snd_ctl_add(card, snd_ctl_new1(&snd_cx88_volume, chip));
if (err < 0)
goto error;
err = snd_ctl_add(card, snd_ctl_new1(&snd_cx88_dac_switch, chip));
if (err < 0)
goto error;
err = snd_ctl_add(card, snd_ctl_new1(&snd_cx88_source_switch, chip));
if (err < 0)
goto error;
strcpy (card->driver, "CX88x");
sprintf(card->shortname, "Conexant CX%x", pci->device);
sprintf(card->longname, "%s at %#llx",
card->shortname,(unsigned long long)pci_resource_start(pci, 0));
strcpy (card->mixername, "CX88");
dprintk (0, "%s/%i: ALSA support for cx2388x boards\n",
card->driver,devno);
err = snd_card_register(card);
if (err < 0)
goto error;
pci_set_drvdata(pci,card);
devno++;
return 0;
error:
snd_card_free(card);
return err;
}
/*
* ALSA destructor
*/
static void __devexit cx88_audio_finidev(struct pci_dev *pci)
{
struct cx88_audio_dev *card = pci_get_drvdata(pci);
snd_card_free((void *)card);
pci_set_drvdata(pci, NULL);
devno--;
}
/*
* PCI driver definition
*/
static struct pci_driver cx88_audio_pci_driver = {
.name = "cx88_audio",
.id_table = cx88_audio_pci_tbl,
.probe = cx88_audio_initdev,
.remove = __devexit_p(cx88_audio_finidev),
};
/****************************************************************************
LINUX MODULE INIT
****************************************************************************/
/*
* module init
*/
static int __init cx88_audio_init(void)
{
printk(KERN_INFO "cx2388x alsa driver version %d.%d.%d loaded\n",
(CX88_VERSION_CODE >> 16) & 0xff,
(CX88_VERSION_CODE >> 8) & 0xff,
CX88_VERSION_CODE & 0xff);
#ifdef SNAPSHOT
printk(KERN_INFO "cx2388x: snapshot date %04d-%02d-%02d\n",
SNAPSHOT/10000, (SNAPSHOT/100)%100, SNAPSHOT%100);
#endif
return pci_register_driver(&cx88_audio_pci_driver);
}
/*
* module remove
*/
static void __exit cx88_audio_fini(void)
{
pci_unregister_driver(&cx88_audio_pci_driver);
}
module_init(cx88_audio_init);
module_exit(cx88_audio_fini);
/* ----------------------------------------------------------- */
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
krizhanovsky/linux-3.10.10-sync_sockets | arch/arm/mach-virt/virt.c | 1058 | 1326 | /*
* Dummy Virtual Machine - does what it says on the tin.
*
* Copyright (C) 2012 ARM Ltd
* Authors: Will Deacon <will.deacon@arm.com>,
* Marc Zyngier <marc.zyngier@arm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/irqchip.h>
#include <linux/of_irq.h>
#include <linux/of_platform.h>
#include <linux/smp.h>
#include <asm/mach/arch.h>
static void __init virt_init(void)
{
of_platform_populate(NULL, of_default_bus_match_table, NULL, NULL);
}
static const char *virt_dt_match[] = {
"linux,dummy-virt",
"xen,xenvm",
NULL
};
extern struct smp_operations virt_smp_ops;
DT_MACHINE_START(VIRT, "Dummy Virtual Machine")
.init_irq = irqchip_init,
.init_machine = virt_init,
.smp = smp_ops(virt_smp_ops),
.dt_compat = virt_dt_match,
MACHINE_END
| gpl-2.0 |
kbc-developers/android_kernel_samsung_exynos4210jpn | drivers/usb/core/hcd-pci.c | 1058 | 16112 | /*
* (C) Copyright David Brownell 2000-2002
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/usb.h>
#include <linux/usb/hcd.h>
#include <asm/io.h>
#include <asm/irq.h>
#ifdef CONFIG_PPC_PMAC
#include <asm/machdep.h>
#include <asm/pmac_feature.h>
#include <asm/pci-bridge.h>
#include <asm/prom.h>
#endif
#include "usb.h"
/* PCI-based HCs are common, but plenty of non-PCI HCs are used too */
#ifdef CONFIG_PM_SLEEP
/* Coordinate handoffs between EHCI and companion controllers
* during system resume
*/
static DEFINE_MUTEX(companions_mutex);
#define CL_UHCI PCI_CLASS_SERIAL_USB_UHCI
#define CL_OHCI PCI_CLASS_SERIAL_USB_OHCI
#define CL_EHCI PCI_CLASS_SERIAL_USB_EHCI
enum companion_action {
SET_HS_COMPANION, CLEAR_HS_COMPANION, WAIT_FOR_COMPANIONS
};
static void companion_common(struct pci_dev *pdev, struct usb_hcd *hcd,
enum companion_action action)
{
struct pci_dev *companion;
struct usb_hcd *companion_hcd;
unsigned int slot = PCI_SLOT(pdev->devfn);
/* Iterate through other PCI functions in the same slot.
* If pdev is OHCI or UHCI then we are looking for EHCI, and
* vice versa.
*/
companion = NULL;
for_each_pci_dev(companion) {
if (companion->bus != pdev->bus ||
PCI_SLOT(companion->devfn) != slot)
continue;
companion_hcd = pci_get_drvdata(companion);
if (!companion_hcd)
continue;
/* For SET_HS_COMPANION, store a pointer to the EHCI bus in
* the OHCI/UHCI companion bus structure.
* For CLEAR_HS_COMPANION, clear the pointer to the EHCI bus
* in the OHCI/UHCI companion bus structure.
* For WAIT_FOR_COMPANIONS, wait until the OHCI/UHCI
* companion controllers have fully resumed.
*/
if ((pdev->class == CL_OHCI || pdev->class == CL_UHCI) &&
companion->class == CL_EHCI) {
/* action must be SET_HS_COMPANION */
dev_dbg(&companion->dev, "HS companion for %s\n",
dev_name(&pdev->dev));
hcd->self.hs_companion = &companion_hcd->self;
} else if (pdev->class == CL_EHCI &&
(companion->class == CL_OHCI ||
companion->class == CL_UHCI)) {
switch (action) {
case SET_HS_COMPANION:
dev_dbg(&pdev->dev, "HS companion for %s\n",
dev_name(&companion->dev));
companion_hcd->self.hs_companion = &hcd->self;
break;
case CLEAR_HS_COMPANION:
companion_hcd->self.hs_companion = NULL;
break;
case WAIT_FOR_COMPANIONS:
device_pm_wait_for_dev(&pdev->dev,
&companion->dev);
break;
}
}
}
}
static void set_hs_companion(struct pci_dev *pdev, struct usb_hcd *hcd)
{
mutex_lock(&companions_mutex);
dev_set_drvdata(&pdev->dev, hcd);
companion_common(pdev, hcd, SET_HS_COMPANION);
mutex_unlock(&companions_mutex);
}
static void clear_hs_companion(struct pci_dev *pdev, struct usb_hcd *hcd)
{
mutex_lock(&companions_mutex);
dev_set_drvdata(&pdev->dev, NULL);
/* If pdev is OHCI or UHCI, just clear its hs_companion pointer */
if (pdev->class == CL_OHCI || pdev->class == CL_UHCI)
hcd->self.hs_companion = NULL;
/* Otherwise search for companion buses and clear their pointers */
else
companion_common(pdev, hcd, CLEAR_HS_COMPANION);
mutex_unlock(&companions_mutex);
}
static void wait_for_companions(struct pci_dev *pdev, struct usb_hcd *hcd)
{
/* Only EHCI controllers need to wait.
* No locking is needed because a controller cannot be resumed
* while one of its companions is getting unbound.
*/
if (pdev->class == CL_EHCI)
companion_common(pdev, hcd, WAIT_FOR_COMPANIONS);
}
#else /* !CONFIG_PM_SLEEP */
static inline void set_hs_companion(struct pci_dev *d, struct usb_hcd *h) {}
static inline void clear_hs_companion(struct pci_dev *d, struct usb_hcd *h) {}
static inline void wait_for_companions(struct pci_dev *d, struct usb_hcd *h) {}
#endif /* !CONFIG_PM_SLEEP */
/*-------------------------------------------------------------------------*/
/* configure so an HC device and id are always provided */
/* always called with process context; sleeping is OK */
/**
* usb_hcd_pci_probe - initialize PCI-based HCDs
* @dev: USB Host Controller being probed
* @id: pci hotplug id connecting controller to HCD framework
* Context: !in_interrupt()
*
* Allocates basic PCI resources for this USB host controller, and
* then invokes the start() method for the HCD associated with it
* through the hotplug entry's driver_data.
*
* Store this function in the HCD's struct pci_driver as probe().
*/
int usb_hcd_pci_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
struct hc_driver *driver;
struct usb_hcd *hcd;
int retval;
if (usb_disabled())
return -ENODEV;
if (!id)
return -EINVAL;
driver = (struct hc_driver *)id->driver_data;
if (!driver)
return -EINVAL;
if (pci_enable_device(dev) < 0)
return -ENODEV;
dev->current_state = PCI_D0;
/* The xHCI driver supports MSI and MSI-X,
* so don't fail if the BIOS doesn't provide a legacy IRQ.
*/
if (!dev->irq && (driver->flags & HCD_MASK) != HCD_USB3) {
dev_err(&dev->dev,
"Found HC with no IRQ. Check BIOS/PCI %s setup!\n",
pci_name(dev));
retval = -ENODEV;
goto disable_pci;
}
hcd = usb_create_hcd(driver, &dev->dev, pci_name(dev));
if (!hcd) {
retval = -ENOMEM;
goto disable_pci;
}
if (driver->flags & HCD_MEMORY) {
/* EHCI, OHCI */
hcd->rsrc_start = pci_resource_start(dev, 0);
hcd->rsrc_len = pci_resource_len(dev, 0);
if (!request_mem_region(hcd->rsrc_start, hcd->rsrc_len,
driver->description)) {
dev_dbg(&dev->dev, "controller already in use\n");
retval = -EBUSY;
goto clear_companion;
}
hcd->regs = ioremap_nocache(hcd->rsrc_start, hcd->rsrc_len);
if (hcd->regs == NULL) {
dev_dbg(&dev->dev, "error mapping memory\n");
retval = -EFAULT;
goto release_mem_region;
}
} else {
/* UHCI */
int region;
for (region = 0; region < PCI_ROM_RESOURCE; region++) {
if (!(pci_resource_flags(dev, region) &
IORESOURCE_IO))
continue;
hcd->rsrc_start = pci_resource_start(dev, region);
hcd->rsrc_len = pci_resource_len(dev, region);
if (request_region(hcd->rsrc_start, hcd->rsrc_len,
driver->description))
break;
}
if (region == PCI_ROM_RESOURCE) {
dev_dbg(&dev->dev, "no i/o regions available\n");
retval = -EBUSY;
goto clear_companion;
}
}
pci_set_master(dev);
retval = usb_add_hcd(hcd, dev->irq, IRQF_DISABLED | IRQF_SHARED);
if (retval != 0)
goto unmap_registers;
set_hs_companion(dev, hcd);
if (pci_dev_run_wake(dev))
pm_runtime_put_noidle(&dev->dev);
return retval;
unmap_registers:
if (driver->flags & HCD_MEMORY) {
iounmap(hcd->regs);
release_mem_region:
release_mem_region(hcd->rsrc_start, hcd->rsrc_len);
} else
release_region(hcd->rsrc_start, hcd->rsrc_len);
clear_companion:
clear_hs_companion(dev, hcd);
usb_put_hcd(hcd);
disable_pci:
pci_disable_device(dev);
dev_err(&dev->dev, "init %s fail, %d\n", pci_name(dev), retval);
return retval;
}
EXPORT_SYMBOL_GPL(usb_hcd_pci_probe);
/* may be called without controller electrically present */
/* may be called with controller, bus, and devices active */
/**
* usb_hcd_pci_remove - shutdown processing for PCI-based HCDs
* @dev: USB Host Controller being removed
* Context: !in_interrupt()
*
* Reverses the effect of usb_hcd_pci_probe(), first invoking
* the HCD's stop() method. It is always called from a thread
* context, normally "rmmod", "apmd", or something similar.
*
* Store this function in the HCD's struct pci_driver as remove().
*/
void usb_hcd_pci_remove(struct pci_dev *dev)
{
struct usb_hcd *hcd;
hcd = pci_get_drvdata(dev);
if (!hcd)
return;
if (pci_dev_run_wake(dev))
pm_runtime_get_noresume(&dev->dev);
/* Fake an interrupt request in order to give the driver a chance
* to test whether the controller hardware has been removed (e.g.,
* cardbus physical eject).
*/
local_irq_disable();
usb_hcd_irq(0, hcd);
local_irq_enable();
usb_remove_hcd(hcd);
if (hcd->driver->flags & HCD_MEMORY) {
iounmap(hcd->regs);
release_mem_region(hcd->rsrc_start, hcd->rsrc_len);
} else {
release_region(hcd->rsrc_start, hcd->rsrc_len);
}
clear_hs_companion(dev, hcd);
usb_put_hcd(hcd);
pci_disable_device(dev);
}
EXPORT_SYMBOL_GPL(usb_hcd_pci_remove);
/**
* usb_hcd_pci_shutdown - shutdown host controller
* @dev: USB Host Controller being shutdown
*/
void usb_hcd_pci_shutdown(struct pci_dev *dev)
{
struct usb_hcd *hcd;
hcd = pci_get_drvdata(dev);
if (!hcd)
return;
if (test_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags) &&
hcd->driver->shutdown) {
hcd->driver->shutdown(hcd);
pci_disable_device(dev);
}
}
EXPORT_SYMBOL_GPL(usb_hcd_pci_shutdown);
#ifdef CONFIG_PM
#ifdef CONFIG_PPC_PMAC
static void powermac_set_asic(struct pci_dev *pci_dev, int enable)
{
/* Enanble or disable ASIC clocks for USB */
if (machine_is(powermac)) {
struct device_node *of_node;
of_node = pci_device_to_OF_node(pci_dev);
if (of_node)
pmac_call_feature(PMAC_FTR_USB_ENABLE,
of_node, 0, enable);
}
}
#else
static inline void powermac_set_asic(struct pci_dev *pci_dev, int enable)
{}
#endif /* CONFIG_PPC_PMAC */
static int check_root_hub_suspended(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct usb_hcd *hcd = pci_get_drvdata(pci_dev);
if (HCD_RH_RUNNING(hcd)) {
dev_warn(dev, "Root hub is not suspended\n");
return -EBUSY;
}
if (hcd->shared_hcd) {
hcd = hcd->shared_hcd;
if (HCD_RH_RUNNING(hcd)) {
dev_warn(dev, "Secondary root hub is not suspended\n");
return -EBUSY;
}
}
return 0;
}
static int suspend_common(struct device *dev, bool do_wakeup)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct usb_hcd *hcd = pci_get_drvdata(pci_dev);
int retval;
/* Root hub suspend should have stopped all downstream traffic,
* and all bus master traffic. And done so for both the interface
* and the stub usb_device (which we check here). But maybe it
* didn't; writing sysfs power/state files ignores such rules...
*/
retval = check_root_hub_suspended(dev);
if (retval)
return retval;
if (hcd->driver->pci_suspend && !HCD_DEAD(hcd)) {
/* Optimization: Don't suspend if a root-hub wakeup is
* pending and it would cause the HCD to wake up anyway.
*/
if (do_wakeup && HCD_WAKEUP_PENDING(hcd))
return -EBUSY;
if (do_wakeup && hcd->shared_hcd &&
HCD_WAKEUP_PENDING(hcd->shared_hcd))
return -EBUSY;
retval = hcd->driver->pci_suspend(hcd, do_wakeup);
suspend_report_result(hcd->driver->pci_suspend, retval);
/* Check again in case wakeup raced with pci_suspend */
if ((retval == 0 && do_wakeup && HCD_WAKEUP_PENDING(hcd)) ||
(retval == 0 && do_wakeup && hcd->shared_hcd &&
HCD_WAKEUP_PENDING(hcd->shared_hcd))) {
if (hcd->driver->pci_resume)
hcd->driver->pci_resume(hcd, false);
retval = -EBUSY;
}
if (retval)
return retval;
}
/* If MSI-X is enabled, the driver will have synchronized all vectors
* in pci_suspend(). If MSI or legacy PCI is enabled, that will be
* synchronized here.
*/
if (!hcd->msix_enabled)
synchronize_irq(pci_dev->irq);
/* Downstream ports from this root hub should already be quiesced, so
* there will be no DMA activity. Now we can shut down the upstream
* link (except maybe for PME# resume signaling). We'll enter a
* low power state during suspend_noirq, if the hardware allows.
*/
pci_disable_device(pci_dev);
return retval;
}
static int resume_common(struct device *dev, int event)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct usb_hcd *hcd = pci_get_drvdata(pci_dev);
int retval;
if (HCD_RH_RUNNING(hcd) ||
(hcd->shared_hcd &&
HCD_RH_RUNNING(hcd->shared_hcd))) {
dev_dbg(dev, "can't resume, not suspended!\n");
return 0;
}
retval = pci_enable_device(pci_dev);
if (retval < 0) {
dev_err(dev, "can't re-enable after resume, %d!\n", retval);
return retval;
}
pci_set_master(pci_dev);
clear_bit(HCD_FLAG_SAW_IRQ, &hcd->flags);
if (hcd->shared_hcd)
clear_bit(HCD_FLAG_SAW_IRQ, &hcd->shared_hcd->flags);
if (hcd->driver->pci_resume && !HCD_DEAD(hcd)) {
if (event != PM_EVENT_AUTO_RESUME)
wait_for_companions(pci_dev, hcd);
retval = hcd->driver->pci_resume(hcd,
event == PM_EVENT_RESTORE);
if (retval) {
dev_err(dev, "PCI post-resume error %d!\n", retval);
if (hcd->shared_hcd)
usb_hc_died(hcd->shared_hcd);
usb_hc_died(hcd);
}
}
return retval;
}
#ifdef CONFIG_PM_SLEEP
static int hcd_pci_suspend(struct device *dev)
{
return suspend_common(dev, device_may_wakeup(dev));
}
static int hcd_pci_suspend_noirq(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct usb_hcd *hcd = pci_get_drvdata(pci_dev);
int retval;
retval = check_root_hub_suspended(dev);
if (retval)
return retval;
pci_save_state(pci_dev);
/* If the root hub is dead rather than suspended, disallow remote
* wakeup. usb_hc_died() should ensure that both hosts are marked as
* dying, so we only need to check the primary roothub.
*/
if (HCD_DEAD(hcd))
device_set_wakeup_enable(dev, 0);
dev_dbg(dev, "wakeup: %d\n", device_may_wakeup(dev));
/* Possibly enable remote wakeup,
* choose the appropriate low-power state, and go to that state.
*/
retval = pci_prepare_to_sleep(pci_dev);
if (retval == -EIO) { /* Low-power not supported */
dev_dbg(dev, "--> PCI D0 legacy\n");
retval = 0;
} else if (retval == 0) {
dev_dbg(dev, "--> PCI %s\n",
pci_power_name(pci_dev->current_state));
} else {
suspend_report_result(pci_prepare_to_sleep, retval);
return retval;
}
powermac_set_asic(pci_dev, 0);
return retval;
}
static int hcd_pci_resume_noirq(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
powermac_set_asic(pci_dev, 1);
/* Go back to D0 and disable remote wakeup */
pci_back_from_sleep(pci_dev);
return 0;
}
static int hcd_pci_resume(struct device *dev)
{
return resume_common(dev, PM_EVENT_RESUME);
}
static int hcd_pci_restore(struct device *dev)
{
return resume_common(dev, PM_EVENT_RESTORE);
}
#else
#define hcd_pci_suspend NULL
#define hcd_pci_suspend_noirq NULL
#define hcd_pci_resume_noirq NULL
#define hcd_pci_resume NULL
#define hcd_pci_restore NULL
#endif /* CONFIG_PM_SLEEP */
#ifdef CONFIG_PM_RUNTIME
static int hcd_pci_runtime_suspend(struct device *dev)
{
int retval;
retval = suspend_common(dev, true);
if (retval == 0)
powermac_set_asic(to_pci_dev(dev), 0);
dev_dbg(dev, "hcd_pci_runtime_suspend: %d\n", retval);
return retval;
}
static int hcd_pci_runtime_resume(struct device *dev)
{
int retval;
powermac_set_asic(to_pci_dev(dev), 1);
retval = resume_common(dev, PM_EVENT_AUTO_RESUME);
dev_dbg(dev, "hcd_pci_runtime_resume: %d\n", retval);
return retval;
}
#else
#define hcd_pci_runtime_suspend NULL
#define hcd_pci_runtime_resume NULL
#endif /* CONFIG_PM_RUNTIME */
const struct dev_pm_ops usb_hcd_pci_pm_ops = {
.suspend = hcd_pci_suspend,
.suspend_noirq = hcd_pci_suspend_noirq,
.resume_noirq = hcd_pci_resume_noirq,
.resume = hcd_pci_resume,
.freeze = check_root_hub_suspended,
.freeze_noirq = check_root_hub_suspended,
.thaw_noirq = NULL,
.thaw = NULL,
.poweroff = hcd_pci_suspend,
.poweroff_noirq = hcd_pci_suspend_noirq,
.restore_noirq = hcd_pci_resume_noirq,
.restore = hcd_pci_restore,
.runtime_suspend = hcd_pci_runtime_suspend,
.runtime_resume = hcd_pci_runtime_resume,
};
EXPORT_SYMBOL_GPL(usb_hcd_pci_pm_ops);
#endif /* CONFIG_PM */
| gpl-2.0 |
d8ahazard/AngryDragon-Source | drivers/gpu/drm/i830/i830_irq.c | 1570 | 5030 | /* i830_dma.c -- DMA support for the I830 -*- linux-c -*-
*
* Copyright 2002 Tungsten Graphics, Inc.
* 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
* TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Authors: Keith Whitwell <keith@tungstengraphics.com>
*
*/
#include "drmP.h"
#include "drm.h"
#include "i830_drm.h"
#include "i830_drv.h"
#include <linux/interrupt.h> /* For task queue support */
#include <linux/delay.h>
irqreturn_t i830_driver_irq_handler(DRM_IRQ_ARGS)
{
struct drm_device *dev = (struct drm_device *) arg;
drm_i830_private_t *dev_priv = (drm_i830_private_t *) dev->dev_private;
u16 temp;
temp = I830_READ16(I830REG_INT_IDENTITY_R);
DRM_DEBUG("%x\n", temp);
if (!(temp & 2))
return IRQ_NONE;
I830_WRITE16(I830REG_INT_IDENTITY_R, temp);
atomic_inc(&dev_priv->irq_received);
wake_up_interruptible(&dev_priv->irq_queue);
return IRQ_HANDLED;
}
static int i830_emit_irq(struct drm_device * dev)
{
drm_i830_private_t *dev_priv = dev->dev_private;
RING_LOCALS;
DRM_DEBUG("%s\n", __func__);
atomic_inc(&dev_priv->irq_emitted);
BEGIN_LP_RING(2);
OUT_RING(0);
OUT_RING(GFX_OP_USER_INTERRUPT);
ADVANCE_LP_RING();
return atomic_read(&dev_priv->irq_emitted);
}
static int i830_wait_irq(struct drm_device * dev, int irq_nr)
{
drm_i830_private_t *dev_priv = (drm_i830_private_t *) dev->dev_private;
DECLARE_WAITQUEUE(entry, current);
unsigned long end = jiffies + HZ * 3;
int ret = 0;
DRM_DEBUG("%s\n", __func__);
if (atomic_read(&dev_priv->irq_received) >= irq_nr)
return 0;
dev_priv->sarea_priv->perf_boxes |= I830_BOX_WAIT;
add_wait_queue(&dev_priv->irq_queue, &entry);
for (;;) {
__set_current_state(TASK_INTERRUPTIBLE);
if (atomic_read(&dev_priv->irq_received) >= irq_nr)
break;
if ((signed)(end - jiffies) <= 0) {
DRM_ERROR("timeout iir %x imr %x ier %x hwstam %x\n",
I830_READ16(I830REG_INT_IDENTITY_R),
I830_READ16(I830REG_INT_MASK_R),
I830_READ16(I830REG_INT_ENABLE_R),
I830_READ16(I830REG_HWSTAM));
ret = -EBUSY; /* Lockup? Missed irq? */
break;
}
schedule_timeout(HZ * 3);
if (signal_pending(current)) {
ret = -EINTR;
break;
}
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(&dev_priv->irq_queue, &entry);
return ret;
}
/* Needs the lock as it touches the ring.
*/
int i830_irq_emit(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
drm_i830_private_t *dev_priv = dev->dev_private;
drm_i830_irq_emit_t *emit = data;
int result;
LOCK_TEST_WITH_RETURN(dev, file_priv);
if (!dev_priv) {
DRM_ERROR("%s called with no initialization\n", __func__);
return -EINVAL;
}
result = i830_emit_irq(dev);
if (copy_to_user(emit->irq_seq, &result, sizeof(int))) {
DRM_ERROR("copy_to_user\n");
return -EFAULT;
}
return 0;
}
/* Doesn't need the hardware lock.
*/
int i830_irq_wait(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
drm_i830_private_t *dev_priv = dev->dev_private;
drm_i830_irq_wait_t *irqwait = data;
if (!dev_priv) {
DRM_ERROR("%s called with no initialization\n", __func__);
return -EINVAL;
}
return i830_wait_irq(dev, irqwait->irq_seq);
}
/* drm_dma.h hooks
*/
void i830_driver_irq_preinstall(struct drm_device * dev)
{
drm_i830_private_t *dev_priv = (drm_i830_private_t *) dev->dev_private;
I830_WRITE16(I830REG_HWSTAM, 0xffff);
I830_WRITE16(I830REG_INT_MASK_R, 0x0);
I830_WRITE16(I830REG_INT_ENABLE_R, 0x0);
atomic_set(&dev_priv->irq_received, 0);
atomic_set(&dev_priv->irq_emitted, 0);
init_waitqueue_head(&dev_priv->irq_queue);
}
void i830_driver_irq_postinstall(struct drm_device * dev)
{
drm_i830_private_t *dev_priv = (drm_i830_private_t *) dev->dev_private;
I830_WRITE16(I830REG_INT_ENABLE_R, 0x2);
}
void i830_driver_irq_uninstall(struct drm_device * dev)
{
drm_i830_private_t *dev_priv = (drm_i830_private_t *) dev->dev_private;
if (!dev_priv)
return;
I830_WRITE16(I830REG_INT_MASK_R, 0xffff);
I830_WRITE16(I830REG_INT_ENABLE_R, 0x0);
}
| gpl-2.0 |
Schischu/xoom-ElementalX | sound/pci/emu10k1/voice.c | 4642 | 4616 | /*
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
* Creative Labs, Inc.
* Lee Revell <rlrevell@joe-job.com>
* Routines for control of EMU10K1 chips - voice manager
*
* Rewrote voice allocator for multichannel support - rlrevell 12/2004
*
* BUGS:
* --
*
* TODO:
* --
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/time.h>
#include <sound/core.h>
#include <sound/emu10k1.h>
/* Previously the voice allocator started at 0 every time. The new voice
* allocator uses a round robin scheme. The next free voice is tracked in
* the card record and each allocation begins where the last left off. The
* hardware requires stereo interleaved voices be aligned to an even/odd
* boundary. For multichannel voice allocation we ensure than the block of
* voices does not cross the 32 voice boundary. This simplifies the
* multichannel support and ensures we can use a single write to the
* (set|clear)_loop_stop registers. Otherwise (for example) the voices would
* get out of sync when pausing/resuming a stream.
* --rlrevell
*/
static int voice_alloc(struct snd_emu10k1 *emu, int type, int number,
struct snd_emu10k1_voice **rvoice)
{
struct snd_emu10k1_voice *voice;
int i, j, k, first_voice, last_voice, skip;
*rvoice = NULL;
first_voice = last_voice = 0;
for (i = emu->next_free_voice, j = 0; j < NUM_G ; i += number, j += number) {
/*
printk(KERN_DEBUG "i %d j %d next free %d!\n",
i, j, emu->next_free_voice);
*/
i %= NUM_G;
/* stereo voices must be even/odd */
if ((number == 2) && (i % 2)) {
i++;
continue;
}
skip = 0;
for (k = 0; k < number; k++) {
voice = &emu->voices[(i+k) % NUM_G];
if (voice->use) {
skip = 1;
break;
}
}
if (!skip) {
/* printk(KERN_DEBUG "allocated voice %d\n", i); */
first_voice = i;
last_voice = (i + number) % NUM_G;
emu->next_free_voice = last_voice;
break;
}
}
if (first_voice == last_voice)
return -ENOMEM;
for (i = 0; i < number; i++) {
voice = &emu->voices[(first_voice + i) % NUM_G];
/*
printk(kERN_DEBUG "voice alloc - %i, %i of %i\n",
voice->number, idx-first_voice+1, number);
*/
voice->use = 1;
switch (type) {
case EMU10K1_PCM:
voice->pcm = 1;
break;
case EMU10K1_SYNTH:
voice->synth = 1;
break;
case EMU10K1_MIDI:
voice->midi = 1;
break;
case EMU10K1_EFX:
voice->efx = 1;
break;
}
}
*rvoice = &emu->voices[first_voice];
return 0;
}
int snd_emu10k1_voice_alloc(struct snd_emu10k1 *emu, int type, int number,
struct snd_emu10k1_voice **rvoice)
{
unsigned long flags;
int result;
if (snd_BUG_ON(!rvoice))
return -EINVAL;
if (snd_BUG_ON(!number))
return -EINVAL;
spin_lock_irqsave(&emu->voice_lock, flags);
for (;;) {
result = voice_alloc(emu, type, number, rvoice);
if (result == 0 || type == EMU10K1_SYNTH || type == EMU10K1_MIDI)
break;
/* free a voice from synth */
if (emu->get_synth_voice) {
result = emu->get_synth_voice(emu);
if (result >= 0) {
struct snd_emu10k1_voice *pvoice = &emu->voices[result];
pvoice->interrupt = NULL;
pvoice->use = pvoice->pcm = pvoice->synth = pvoice->midi = pvoice->efx = 0;
pvoice->epcm = NULL;
}
}
if (result < 0)
break;
}
spin_unlock_irqrestore(&emu->voice_lock, flags);
return result;
}
EXPORT_SYMBOL(snd_emu10k1_voice_alloc);
int snd_emu10k1_voice_free(struct snd_emu10k1 *emu,
struct snd_emu10k1_voice *pvoice)
{
unsigned long flags;
if (snd_BUG_ON(!pvoice))
return -EINVAL;
spin_lock_irqsave(&emu->voice_lock, flags);
pvoice->interrupt = NULL;
pvoice->use = pvoice->pcm = pvoice->synth = pvoice->midi = pvoice->efx = 0;
pvoice->epcm = NULL;
snd_emu10k1_voice_init(emu, pvoice->number);
spin_unlock_irqrestore(&emu->voice_lock, flags);
return 0;
}
EXPORT_SYMBOL(snd_emu10k1_voice_free);
| gpl-2.0 |
RepoBackups/Canuck | drivers/pci/hotplug/acpi_pcihp.c | 7458 | 13447 | /*
* Common ACPI functions for hot plug platforms
*
* Copyright (C) 2006 Intel Corporation
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Send feedback to <kristen.c.accardi@intel.com>
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/pci_hotplug.h>
#include <linux/acpi.h>
#include <linux/pci-acpi.h>
#include <linux/slab.h>
#define MY_NAME "acpi_pcihp"
#define dbg(fmt, arg...) do { if (debug_acpi) printk(KERN_DEBUG "%s: %s: " fmt , MY_NAME , __func__ , ## arg); } while (0)
#define err(format, arg...) printk(KERN_ERR "%s: " format , MY_NAME , ## arg)
#define info(format, arg...) printk(KERN_INFO "%s: " format , MY_NAME , ## arg)
#define warn(format, arg...) printk(KERN_WARNING "%s: " format , MY_NAME , ## arg)
#define METHOD_NAME__SUN "_SUN"
#define METHOD_NAME_OSHP "OSHP"
static bool debug_acpi;
static acpi_status
decode_type0_hpx_record(union acpi_object *record, struct hotplug_params *hpx)
{
int i;
union acpi_object *fields = record->package.elements;
u32 revision = fields[1].integer.value;
switch (revision) {
case 1:
if (record->package.count != 6)
return AE_ERROR;
for (i = 2; i < 6; i++)
if (fields[i].type != ACPI_TYPE_INTEGER)
return AE_ERROR;
hpx->t0 = &hpx->type0_data;
hpx->t0->revision = revision;
hpx->t0->cache_line_size = fields[2].integer.value;
hpx->t0->latency_timer = fields[3].integer.value;
hpx->t0->enable_serr = fields[4].integer.value;
hpx->t0->enable_perr = fields[5].integer.value;
break;
default:
printk(KERN_WARNING
"%s: Type 0 Revision %d record not supported\n",
__func__, revision);
return AE_ERROR;
}
return AE_OK;
}
static acpi_status
decode_type1_hpx_record(union acpi_object *record, struct hotplug_params *hpx)
{
int i;
union acpi_object *fields = record->package.elements;
u32 revision = fields[1].integer.value;
switch (revision) {
case 1:
if (record->package.count != 5)
return AE_ERROR;
for (i = 2; i < 5; i++)
if (fields[i].type != ACPI_TYPE_INTEGER)
return AE_ERROR;
hpx->t1 = &hpx->type1_data;
hpx->t1->revision = revision;
hpx->t1->max_mem_read = fields[2].integer.value;
hpx->t1->avg_max_split = fields[3].integer.value;
hpx->t1->tot_max_split = fields[4].integer.value;
break;
default:
printk(KERN_WARNING
"%s: Type 1 Revision %d record not supported\n",
__func__, revision);
return AE_ERROR;
}
return AE_OK;
}
static acpi_status
decode_type2_hpx_record(union acpi_object *record, struct hotplug_params *hpx)
{
int i;
union acpi_object *fields = record->package.elements;
u32 revision = fields[1].integer.value;
switch (revision) {
case 1:
if (record->package.count != 18)
return AE_ERROR;
for (i = 2; i < 18; i++)
if (fields[i].type != ACPI_TYPE_INTEGER)
return AE_ERROR;
hpx->t2 = &hpx->type2_data;
hpx->t2->revision = revision;
hpx->t2->unc_err_mask_and = fields[2].integer.value;
hpx->t2->unc_err_mask_or = fields[3].integer.value;
hpx->t2->unc_err_sever_and = fields[4].integer.value;
hpx->t2->unc_err_sever_or = fields[5].integer.value;
hpx->t2->cor_err_mask_and = fields[6].integer.value;
hpx->t2->cor_err_mask_or = fields[7].integer.value;
hpx->t2->adv_err_cap_and = fields[8].integer.value;
hpx->t2->adv_err_cap_or = fields[9].integer.value;
hpx->t2->pci_exp_devctl_and = fields[10].integer.value;
hpx->t2->pci_exp_devctl_or = fields[11].integer.value;
hpx->t2->pci_exp_lnkctl_and = fields[12].integer.value;
hpx->t2->pci_exp_lnkctl_or = fields[13].integer.value;
hpx->t2->sec_unc_err_sever_and = fields[14].integer.value;
hpx->t2->sec_unc_err_sever_or = fields[15].integer.value;
hpx->t2->sec_unc_err_mask_and = fields[16].integer.value;
hpx->t2->sec_unc_err_mask_or = fields[17].integer.value;
break;
default:
printk(KERN_WARNING
"%s: Type 2 Revision %d record not supported\n",
__func__, revision);
return AE_ERROR;
}
return AE_OK;
}
static acpi_status
acpi_run_hpx(acpi_handle handle, struct hotplug_params *hpx)
{
acpi_status status;
struct acpi_buffer buffer = {ACPI_ALLOCATE_BUFFER, NULL};
union acpi_object *package, *record, *fields;
u32 type;
int i;
/* Clear the return buffer with zeros */
memset(hpx, 0, sizeof(struct hotplug_params));
status = acpi_evaluate_object(handle, "_HPX", NULL, &buffer);
if (ACPI_FAILURE(status))
return status;
package = (union acpi_object *)buffer.pointer;
if (package->type != ACPI_TYPE_PACKAGE) {
status = AE_ERROR;
goto exit;
}
for (i = 0; i < package->package.count; i++) {
record = &package->package.elements[i];
if (record->type != ACPI_TYPE_PACKAGE) {
status = AE_ERROR;
goto exit;
}
fields = record->package.elements;
if (fields[0].type != ACPI_TYPE_INTEGER ||
fields[1].type != ACPI_TYPE_INTEGER) {
status = AE_ERROR;
goto exit;
}
type = fields[0].integer.value;
switch (type) {
case 0:
status = decode_type0_hpx_record(record, hpx);
if (ACPI_FAILURE(status))
goto exit;
break;
case 1:
status = decode_type1_hpx_record(record, hpx);
if (ACPI_FAILURE(status))
goto exit;
break;
case 2:
status = decode_type2_hpx_record(record, hpx);
if (ACPI_FAILURE(status))
goto exit;
break;
default:
printk(KERN_ERR "%s: Type %d record not supported\n",
__func__, type);
status = AE_ERROR;
goto exit;
}
}
exit:
kfree(buffer.pointer);
return status;
}
static acpi_status
acpi_run_hpp(acpi_handle handle, struct hotplug_params *hpp)
{
acpi_status status;
struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
union acpi_object *package, *fields;
int i;
memset(hpp, 0, sizeof(struct hotplug_params));
status = acpi_evaluate_object(handle, "_HPP", NULL, &buffer);
if (ACPI_FAILURE(status))
return status;
package = (union acpi_object *) buffer.pointer;
if (package->type != ACPI_TYPE_PACKAGE ||
package->package.count != 4) {
status = AE_ERROR;
goto exit;
}
fields = package->package.elements;
for (i = 0; i < 4; i++) {
if (fields[i].type != ACPI_TYPE_INTEGER) {
status = AE_ERROR;
goto exit;
}
}
hpp->t0 = &hpp->type0_data;
hpp->t0->revision = 1;
hpp->t0->cache_line_size = fields[0].integer.value;
hpp->t0->latency_timer = fields[1].integer.value;
hpp->t0->enable_serr = fields[2].integer.value;
hpp->t0->enable_perr = fields[3].integer.value;
exit:
kfree(buffer.pointer);
return status;
}
/* acpi_run_oshp - get control of hotplug from the firmware
*
* @handle - the handle of the hotplug controller.
*/
static acpi_status acpi_run_oshp(acpi_handle handle)
{
acpi_status status;
struct acpi_buffer string = { ACPI_ALLOCATE_BUFFER, NULL };
acpi_get_name(handle, ACPI_FULL_PATHNAME, &string);
/* run OSHP */
status = acpi_evaluate_object(handle, METHOD_NAME_OSHP, NULL, NULL);
if (ACPI_FAILURE(status))
if (status != AE_NOT_FOUND)
printk(KERN_ERR "%s:%s OSHP fails=0x%x\n",
__func__, (char *)string.pointer, status);
else
dbg("%s:%s OSHP not found\n",
__func__, (char *)string.pointer);
else
pr_debug("%s:%s OSHP passes\n", __func__,
(char *)string.pointer);
kfree(string.pointer);
return status;
}
/* pci_get_hp_params
*
* @dev - the pci_dev for which we want parameters
* @hpp - allocated by the caller
*/
int pci_get_hp_params(struct pci_dev *dev, struct hotplug_params *hpp)
{
acpi_status status;
acpi_handle handle, phandle;
struct pci_bus *pbus;
handle = NULL;
for (pbus = dev->bus; pbus; pbus = pbus->parent) {
handle = acpi_pci_get_bridge_handle(pbus);
if (handle)
break;
}
/*
* _HPP settings apply to all child buses, until another _HPP is
* encountered. If we don't find an _HPP for the input pci dev,
* look for it in the parent device scope since that would apply to
* this pci dev.
*/
while (handle) {
status = acpi_run_hpx(handle, hpp);
if (ACPI_SUCCESS(status))
return 0;
status = acpi_run_hpp(handle, hpp);
if (ACPI_SUCCESS(status))
return 0;
if (acpi_is_root_bridge(handle))
break;
status = acpi_get_parent(handle, &phandle);
if (ACPI_FAILURE(status))
break;
handle = phandle;
}
return -ENODEV;
}
EXPORT_SYMBOL_GPL(pci_get_hp_params);
/**
* acpi_get_hp_hw_control_from_firmware
* @dev: the pci_dev of the bridge that has a hotplug controller
* @flags: requested control bits for _OSC
*
* Attempt to take hotplug control from firmware.
*/
int acpi_get_hp_hw_control_from_firmware(struct pci_dev *pdev, u32 flags)
{
acpi_status status;
acpi_handle chandle, handle;
struct acpi_buffer string = { ACPI_ALLOCATE_BUFFER, NULL };
flags &= OSC_SHPC_NATIVE_HP_CONTROL;
if (!flags) {
err("Invalid flags %u specified!\n", flags);
return -EINVAL;
}
/*
* Per PCI firmware specification, we should run the ACPI _OSC
* method to get control of hotplug hardware before using it. If
* an _OSC is missing, we look for an OSHP to do the same thing.
* To handle different BIOS behavior, we look for _OSC on a root
* bridge preferentially (according to PCI fw spec). Later for
* OSHP within the scope of the hotplug controller and its parents,
* up to the host bridge under which this controller exists.
*/
handle = acpi_find_root_bridge_handle(pdev);
if (handle) {
acpi_get_name(handle, ACPI_FULL_PATHNAME, &string);
dbg("Trying to get hotplug control for %s\n",
(char *)string.pointer);
status = acpi_pci_osc_control_set(handle, &flags, flags);
if (ACPI_SUCCESS(status))
goto got_one;
if (status == AE_SUPPORT)
goto no_control;
kfree(string.pointer);
string = (struct acpi_buffer){ ACPI_ALLOCATE_BUFFER, NULL };
}
handle = DEVICE_ACPI_HANDLE(&pdev->dev);
if (!handle) {
/*
* This hotplug controller was not listed in the ACPI name
* space at all. Try to get acpi handle of parent pci bus.
*/
struct pci_bus *pbus;
for (pbus = pdev->bus; pbus; pbus = pbus->parent) {
handle = acpi_pci_get_bridge_handle(pbus);
if (handle)
break;
}
}
while (handle) {
acpi_get_name(handle, ACPI_FULL_PATHNAME, &string);
dbg("Trying to get hotplug control for %s \n",
(char *)string.pointer);
status = acpi_run_oshp(handle);
if (ACPI_SUCCESS(status))
goto got_one;
if (acpi_is_root_bridge(handle))
break;
chandle = handle;
status = acpi_get_parent(chandle, &handle);
if (ACPI_FAILURE(status))
break;
}
no_control:
dbg("Cannot get control of hotplug hardware for pci %s\n",
pci_name(pdev));
kfree(string.pointer);
return -ENODEV;
got_one:
dbg("Gained control for hotplug HW for pci %s (%s)\n",
pci_name(pdev), (char *)string.pointer);
kfree(string.pointer);
return 0;
}
EXPORT_SYMBOL(acpi_get_hp_hw_control_from_firmware);
static int pcihp_is_ejectable(acpi_handle handle)
{
acpi_status status;
acpi_handle tmp;
unsigned long long removable;
status = acpi_get_handle(handle, "_ADR", &tmp);
if (ACPI_FAILURE(status))
return 0;
status = acpi_get_handle(handle, "_EJ0", &tmp);
if (ACPI_SUCCESS(status))
return 1;
status = acpi_evaluate_integer(handle, "_RMV", NULL, &removable);
if (ACPI_SUCCESS(status) && removable)
return 1;
return 0;
}
/**
* acpi_pcihp_check_ejectable - check if handle is ejectable ACPI PCI slot
* @pbus: the PCI bus of the PCI slot corresponding to 'handle'
* @handle: ACPI handle to check
*
* Return 1 if handle is ejectable PCI slot, 0 otherwise.
*/
int acpi_pci_check_ejectable(struct pci_bus *pbus, acpi_handle handle)
{
acpi_handle bridge_handle, parent_handle;
if (!(bridge_handle = acpi_pci_get_bridge_handle(pbus)))
return 0;
if ((ACPI_FAILURE(acpi_get_parent(handle, &parent_handle))))
return 0;
if (bridge_handle != parent_handle)
return 0;
return pcihp_is_ejectable(handle);
}
EXPORT_SYMBOL_GPL(acpi_pci_check_ejectable);
static acpi_status
check_hotplug(acpi_handle handle, u32 lvl, void *context, void **rv)
{
int *found = (int *)context;
if (pcihp_is_ejectable(handle)) {
*found = 1;
return AE_CTRL_TERMINATE;
}
return AE_OK;
}
/**
* acpi_pci_detect_ejectable - check if the PCI bus has ejectable slots
* @handle - handle of the PCI bus to scan
*
* Returns 1 if the PCI bus has ACPI based ejectable slots, 0 otherwise.
*/
int acpi_pci_detect_ejectable(acpi_handle handle)
{
int found = 0;
if (!handle)
return found;
acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
check_hotplug, NULL, (void *)&found, NULL);
return found;
}
EXPORT_SYMBOL_GPL(acpi_pci_detect_ejectable);
module_param(debug_acpi, bool, 0644);
MODULE_PARM_DESC(debug_acpi, "Debugging mode for ACPI enabled or not");
| gpl-2.0 |
FrancescoCG/Crazy-Kernel1-TW-Kernel | drivers/macintosh/therm_pm72.c | 8226 | 63960 | /*
* Device driver for the thermostats & fan controller of the
* Apple G5 "PowerMac7,2" desktop machines.
*
* (c) Copyright IBM Corp. 2003-2004
*
* Maintained by: Benjamin Herrenschmidt
* <benh@kernel.crashing.org>
*
*
* The algorithm used is the PID control algorithm, used the same
* way the published Darwin code does, using the same values that
* are present in the Darwin 7.0 snapshot property lists.
*
* As far as the CPUs control loops are concerned, I use the
* calibration & PID constants provided by the EEPROM,
* I do _not_ embed any value from the property lists, as the ones
* provided by Darwin 7.0 seem to always have an older version that
* what I've seen on the actual computers.
* It would be interesting to verify that though. Darwin has a
* version code of 1.0.0d11 for all control loops it seems, while
* so far, the machines EEPROMs contain a dataset versioned 1.0.0f
*
* Darwin doesn't provide source to all parts, some missing
* bits like the AppleFCU driver or the actual scale of some
* of the values returned by sensors had to be "guessed" some
* way... or based on what Open Firmware does.
*
* I didn't yet figure out how to get the slots power consumption
* out of the FCU, so that part has not been implemented yet and
* the slots fan is set to a fixed 50% PWM, hoping this value is
* safe enough ...
*
* Note: I have observed strange oscillations of the CPU control
* loop on a dual G5 here. When idle, the CPU exhaust fan tend to
* oscillates slowly (over several minutes) between the minimum
* of 300RPMs and approx. 1000 RPMs. I don't know what is causing
* this, it could be some incorrect constant or an error in the
* way I ported the algorithm, or it could be just normal. I
* don't have full understanding on the way Apple tweaked the PID
* algorithm for the CPU control, it is definitely not a standard
* implementation...
*
* TODO: - Check MPU structure version/signature
* - Add things like /sbin/overtemp for non-critical
* overtemp conditions so userland can take some policy
* decisions, like slowing down CPUs
* - Deal with fan and i2c failures in a better way
* - Maybe do a generic PID based on params used for
* U3 and Drives ? Definitely need to factor code a bit
* better... also make sensor detection more robust using
* the device-tree to probe for them
* - Figure out how to get the slots consumption and set the
* slots fan accordingly
*
* History:
*
* Nov. 13, 2003 : 0.5
* - First release
*
* Nov. 14, 2003 : 0.6
* - Read fan speed from FCU, low level fan routines now deal
* with errors & check fan status, though higher level don't
* do much.
* - Move a bunch of definitions to .h file
*
* Nov. 18, 2003 : 0.7
* - Fix build on ppc64 kernel
* - Move back statics definitions to .c file
* - Avoid calling schedule_timeout with a negative number
*
* Dec. 18, 2003 : 0.8
* - Fix typo when reading back fan speed on 2 CPU machines
*
* Mar. 11, 2004 : 0.9
* - Rework code accessing the ADC chips, make it more robust and
* closer to the chip spec. Also make sure it is configured properly,
* I've seen yet unexplained cases where on startup, I would have stale
* values in the configuration register
* - Switch back to use of target fan speed for PID, thus lowering
* pressure on i2c
*
* Oct. 20, 2004 : 1.1
* - Add device-tree lookup for fan IDs, should detect liquid cooling
* pumps when present
* - Enable driver for PowerMac7,3 machines
* - Split the U3/Backside cooling on U3 & U3H versions as Darwin does
* - Add new CPU cooling algorithm for machines with liquid cooling
* - Workaround for some PowerMac7,3 with empty "fan" node in the devtree
* - Fix a signed/unsigned compare issue in some PID loops
*
* Mar. 10, 2005 : 1.2
* - Add basic support for Xserve G5
* - Retrieve pumps min/max from EEPROM image in device-tree (broken)
* - Use min/max macros here or there
* - Latest darwin updated U3H min fan speed to 20% PWM
*
* July. 06, 2006 : 1.3
* - Fix setting of RPM fans on Xserve G5 (they were going too fast)
* - Add missing slots fan control loop for Xserve G5
* - Lower fixed slots fan speed from 50% to 40% on desktop G5s. We
* still can't properly implement the control loop for these, so let's
* reduce the noise a little bit, it appears that 40% still gives us
* a pretty good air flow
* - Add code to "tickle" the FCU regulary so it doesn't think that
* we are gone while in fact, the machine just didn't need any fan
* speed change lately
*
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/wait.h>
#include <linux/reboot.h>
#include <linux/kmod.h>
#include <linux/i2c.h>
#include <linux/kthread.h>
#include <linux/mutex.h>
#include <linux/of_device.h>
#include <linux/of_platform.h>
#include <asm/prom.h>
#include <asm/machdep.h>
#include <asm/io.h>
#include <asm/sections.h>
#include <asm/macio.h>
#include "therm_pm72.h"
#define VERSION "1.3"
#undef DEBUG
#ifdef DEBUG
#define DBG(args...) printk(args)
#else
#define DBG(args...) do { } while(0)
#endif
/*
* Driver statics
*/
static struct platform_device * of_dev;
static struct i2c_adapter * u3_0;
static struct i2c_adapter * u3_1;
static struct i2c_adapter * k2;
static struct i2c_client * fcu;
static struct cpu_pid_state processor_state[2];
static struct basckside_pid_params backside_params;
static struct backside_pid_state backside_state;
static struct drives_pid_state drives_state;
static struct dimm_pid_state dimms_state;
static struct slots_pid_state slots_state;
static int state;
static int cpu_count;
static int cpu_pid_type;
static struct task_struct *ctrl_task;
static struct completion ctrl_complete;
static int critical_state;
static int rackmac;
static s32 dimm_output_clamp;
static int fcu_rpm_shift;
static int fcu_tickle_ticks;
static DEFINE_MUTEX(driver_lock);
/*
* We have 3 types of CPU PID control. One is "split" old style control
* for intake & exhaust fans, the other is "combined" control for both
* CPUs that also deals with the pumps when present. To be "compatible"
* with OS X at this point, we only use "COMBINED" on the machines that
* are identified as having the pumps (though that identification is at
* least dodgy). Ultimately, we could probably switch completely to this
* algorithm provided we hack it to deal with the UP case
*/
#define CPU_PID_TYPE_SPLIT 0
#define CPU_PID_TYPE_COMBINED 1
#define CPU_PID_TYPE_RACKMAC 2
/*
* This table describes all fans in the FCU. The "id" and "type" values
* are defaults valid for all earlier machines. Newer machines will
* eventually override the table content based on the device-tree
*/
struct fcu_fan_table
{
char* loc; /* location code */
int type; /* 0 = rpm, 1 = pwm, 2 = pump */
int id; /* id or -1 */
};
#define FCU_FAN_RPM 0
#define FCU_FAN_PWM 1
#define FCU_FAN_ABSENT_ID -1
#define FCU_FAN_COUNT ARRAY_SIZE(fcu_fans)
struct fcu_fan_table fcu_fans[] = {
[BACKSIDE_FAN_PWM_INDEX] = {
.loc = "BACKSIDE,SYS CTRLR FAN",
.type = FCU_FAN_PWM,
.id = BACKSIDE_FAN_PWM_DEFAULT_ID,
},
[DRIVES_FAN_RPM_INDEX] = {
.loc = "DRIVE BAY",
.type = FCU_FAN_RPM,
.id = DRIVES_FAN_RPM_DEFAULT_ID,
},
[SLOTS_FAN_PWM_INDEX] = {
.loc = "SLOT,PCI FAN",
.type = FCU_FAN_PWM,
.id = SLOTS_FAN_PWM_DEFAULT_ID,
},
[CPUA_INTAKE_FAN_RPM_INDEX] = {
.loc = "CPU A INTAKE",
.type = FCU_FAN_RPM,
.id = CPUA_INTAKE_FAN_RPM_DEFAULT_ID,
},
[CPUA_EXHAUST_FAN_RPM_INDEX] = {
.loc = "CPU A EXHAUST",
.type = FCU_FAN_RPM,
.id = CPUA_EXHAUST_FAN_RPM_DEFAULT_ID,
},
[CPUB_INTAKE_FAN_RPM_INDEX] = {
.loc = "CPU B INTAKE",
.type = FCU_FAN_RPM,
.id = CPUB_INTAKE_FAN_RPM_DEFAULT_ID,
},
[CPUB_EXHAUST_FAN_RPM_INDEX] = {
.loc = "CPU B EXHAUST",
.type = FCU_FAN_RPM,
.id = CPUB_EXHAUST_FAN_RPM_DEFAULT_ID,
},
/* pumps aren't present by default, have to be looked up in the
* device-tree
*/
[CPUA_PUMP_RPM_INDEX] = {
.loc = "CPU A PUMP",
.type = FCU_FAN_RPM,
.id = FCU_FAN_ABSENT_ID,
},
[CPUB_PUMP_RPM_INDEX] = {
.loc = "CPU B PUMP",
.type = FCU_FAN_RPM,
.id = FCU_FAN_ABSENT_ID,
},
/* Xserve fans */
[CPU_A1_FAN_RPM_INDEX] = {
.loc = "CPU A 1",
.type = FCU_FAN_RPM,
.id = FCU_FAN_ABSENT_ID,
},
[CPU_A2_FAN_RPM_INDEX] = {
.loc = "CPU A 2",
.type = FCU_FAN_RPM,
.id = FCU_FAN_ABSENT_ID,
},
[CPU_A3_FAN_RPM_INDEX] = {
.loc = "CPU A 3",
.type = FCU_FAN_RPM,
.id = FCU_FAN_ABSENT_ID,
},
[CPU_B1_FAN_RPM_INDEX] = {
.loc = "CPU B 1",
.type = FCU_FAN_RPM,
.id = FCU_FAN_ABSENT_ID,
},
[CPU_B2_FAN_RPM_INDEX] = {
.loc = "CPU B 2",
.type = FCU_FAN_RPM,
.id = FCU_FAN_ABSENT_ID,
},
[CPU_B3_FAN_RPM_INDEX] = {
.loc = "CPU B 3",
.type = FCU_FAN_RPM,
.id = FCU_FAN_ABSENT_ID,
},
};
static struct i2c_driver therm_pm72_driver;
/*
* Utility function to create an i2c_client structure and
* attach it to one of u3 adapters
*/
static struct i2c_client *attach_i2c_chip(int id, const char *name)
{
struct i2c_client *clt;
struct i2c_adapter *adap;
struct i2c_board_info info;
if (id & 0x200)
adap = k2;
else if (id & 0x100)
adap = u3_1;
else
adap = u3_0;
if (adap == NULL)
return NULL;
memset(&info, 0, sizeof(struct i2c_board_info));
info.addr = (id >> 1) & 0x7f;
strlcpy(info.type, "therm_pm72", I2C_NAME_SIZE);
clt = i2c_new_device(adap, &info);
if (!clt) {
printk(KERN_ERR "therm_pm72: Failed to attach to i2c ID 0x%x\n", id);
return NULL;
}
/*
* Let i2c-core delete that device on driver removal.
* This is safe because i2c-core holds the core_lock mutex for us.
*/
list_add_tail(&clt->detected, &therm_pm72_driver.clients);
return clt;
}
/*
* Here are the i2c chip access wrappers
*/
static void initialize_adc(struct cpu_pid_state *state)
{
int rc;
u8 buf[2];
/* Read ADC the configuration register and cache it. We
* also make sure Config2 contains proper values, I've seen
* cases where we got stale grabage in there, thus preventing
* proper reading of conv. values
*/
/* Clear Config2 */
buf[0] = 5;
buf[1] = 0;
i2c_master_send(state->monitor, buf, 2);
/* Read & cache Config1 */
buf[0] = 1;
rc = i2c_master_send(state->monitor, buf, 1);
if (rc > 0) {
rc = i2c_master_recv(state->monitor, buf, 1);
if (rc > 0) {
state->adc_config = buf[0];
DBG("ADC config reg: %02x\n", state->adc_config);
/* Disable shutdown mode */
state->adc_config &= 0xfe;
buf[0] = 1;
buf[1] = state->adc_config;
rc = i2c_master_send(state->monitor, buf, 2);
}
}
if (rc <= 0)
printk(KERN_ERR "therm_pm72: Error reading ADC config"
" register !\n");
}
static int read_smon_adc(struct cpu_pid_state *state, int chan)
{
int rc, data, tries = 0;
u8 buf[2];
for (;;) {
/* Set channel */
buf[0] = 1;
buf[1] = (state->adc_config & 0x1f) | (chan << 5);
rc = i2c_master_send(state->monitor, buf, 2);
if (rc <= 0)
goto error;
/* Wait for conversion */
msleep(1);
/* Switch to data register */
buf[0] = 4;
rc = i2c_master_send(state->monitor, buf, 1);
if (rc <= 0)
goto error;
/* Read result */
rc = i2c_master_recv(state->monitor, buf, 2);
if (rc < 0)
goto error;
data = ((u16)buf[0]) << 8 | (u16)buf[1];
return data >> 6;
error:
DBG("Error reading ADC, retrying...\n");
if (++tries > 10) {
printk(KERN_ERR "therm_pm72: Error reading ADC !\n");
return -1;
}
msleep(10);
}
}
static int read_lm87_reg(struct i2c_client * chip, int reg)
{
int rc, tries = 0;
u8 buf;
for (;;) {
/* Set address */
buf = (u8)reg;
rc = i2c_master_send(chip, &buf, 1);
if (rc <= 0)
goto error;
rc = i2c_master_recv(chip, &buf, 1);
if (rc <= 0)
goto error;
return (int)buf;
error:
DBG("Error reading LM87, retrying...\n");
if (++tries > 10) {
printk(KERN_ERR "therm_pm72: Error reading LM87 !\n");
return -1;
}
msleep(10);
}
}
static int fan_read_reg(int reg, unsigned char *buf, int nb)
{
int tries, nr, nw;
buf[0] = reg;
tries = 0;
for (;;) {
nw = i2c_master_send(fcu, buf, 1);
if (nw > 0 || (nw < 0 && nw != -EIO) || tries >= 100)
break;
msleep(10);
++tries;
}
if (nw <= 0) {
printk(KERN_ERR "Failure writing address to FCU: %d", nw);
return -EIO;
}
tries = 0;
for (;;) {
nr = i2c_master_recv(fcu, buf, nb);
if (nr > 0 || (nr < 0 && nr != -ENODEV) || tries >= 100)
break;
msleep(10);
++tries;
}
if (nr <= 0)
printk(KERN_ERR "Failure reading data from FCU: %d", nw);
return nr;
}
static int fan_write_reg(int reg, const unsigned char *ptr, int nb)
{
int tries, nw;
unsigned char buf[16];
buf[0] = reg;
memcpy(buf+1, ptr, nb);
++nb;
tries = 0;
for (;;) {
nw = i2c_master_send(fcu, buf, nb);
if (nw > 0 || (nw < 0 && nw != -EIO) || tries >= 100)
break;
msleep(10);
++tries;
}
if (nw < 0)
printk(KERN_ERR "Failure writing to FCU: %d", nw);
return nw;
}
static int start_fcu(void)
{
unsigned char buf = 0xff;
int rc;
rc = fan_write_reg(0xe, &buf, 1);
if (rc < 0)
return -EIO;
rc = fan_write_reg(0x2e, &buf, 1);
if (rc < 0)
return -EIO;
rc = fan_read_reg(0, &buf, 1);
if (rc < 0)
return -EIO;
fcu_rpm_shift = (buf == 1) ? 2 : 3;
printk(KERN_DEBUG "FCU Initialized, RPM fan shift is %d\n",
fcu_rpm_shift);
return 0;
}
static int set_rpm_fan(int fan_index, int rpm)
{
unsigned char buf[2];
int rc, id, min, max;
if (fcu_fans[fan_index].type != FCU_FAN_RPM)
return -EINVAL;
id = fcu_fans[fan_index].id;
if (id == FCU_FAN_ABSENT_ID)
return -EINVAL;
min = 2400 >> fcu_rpm_shift;
max = 56000 >> fcu_rpm_shift;
if (rpm < min)
rpm = min;
else if (rpm > max)
rpm = max;
buf[0] = rpm >> (8 - fcu_rpm_shift);
buf[1] = rpm << fcu_rpm_shift;
rc = fan_write_reg(0x10 + (id * 2), buf, 2);
if (rc < 0)
return -EIO;
return 0;
}
static int get_rpm_fan(int fan_index, int programmed)
{
unsigned char failure;
unsigned char active;
unsigned char buf[2];
int rc, id, reg_base;
if (fcu_fans[fan_index].type != FCU_FAN_RPM)
return -EINVAL;
id = fcu_fans[fan_index].id;
if (id == FCU_FAN_ABSENT_ID)
return -EINVAL;
rc = fan_read_reg(0xb, &failure, 1);
if (rc != 1)
return -EIO;
if ((failure & (1 << id)) != 0)
return -EFAULT;
rc = fan_read_reg(0xd, &active, 1);
if (rc != 1)
return -EIO;
if ((active & (1 << id)) == 0)
return -ENXIO;
/* Programmed value or real current speed */
reg_base = programmed ? 0x10 : 0x11;
rc = fan_read_reg(reg_base + (id * 2), buf, 2);
if (rc != 2)
return -EIO;
return (buf[0] << (8 - fcu_rpm_shift)) | buf[1] >> fcu_rpm_shift;
}
static int set_pwm_fan(int fan_index, int pwm)
{
unsigned char buf[2];
int rc, id;
if (fcu_fans[fan_index].type != FCU_FAN_PWM)
return -EINVAL;
id = fcu_fans[fan_index].id;
if (id == FCU_FAN_ABSENT_ID)
return -EINVAL;
if (pwm < 10)
pwm = 10;
else if (pwm > 100)
pwm = 100;
pwm = (pwm * 2559) / 1000;
buf[0] = pwm;
rc = fan_write_reg(0x30 + (id * 2), buf, 1);
if (rc < 0)
return rc;
return 0;
}
static int get_pwm_fan(int fan_index)
{
unsigned char failure;
unsigned char active;
unsigned char buf[2];
int rc, id;
if (fcu_fans[fan_index].type != FCU_FAN_PWM)
return -EINVAL;
id = fcu_fans[fan_index].id;
if (id == FCU_FAN_ABSENT_ID)
return -EINVAL;
rc = fan_read_reg(0x2b, &failure, 1);
if (rc != 1)
return -EIO;
if ((failure & (1 << id)) != 0)
return -EFAULT;
rc = fan_read_reg(0x2d, &active, 1);
if (rc != 1)
return -EIO;
if ((active & (1 << id)) == 0)
return -ENXIO;
/* Programmed value or real current speed */
rc = fan_read_reg(0x30 + (id * 2), buf, 1);
if (rc != 1)
return -EIO;
return (buf[0] * 1000) / 2559;
}
static void tickle_fcu(void)
{
int pwm;
pwm = get_pwm_fan(SLOTS_FAN_PWM_INDEX);
DBG("FCU Tickle, slots fan is: %d\n", pwm);
if (pwm < 0)
pwm = 100;
if (!rackmac) {
pwm = SLOTS_FAN_DEFAULT_PWM;
} else if (pwm < SLOTS_PID_OUTPUT_MIN)
pwm = SLOTS_PID_OUTPUT_MIN;
/* That is hopefully enough to make the FCU happy */
set_pwm_fan(SLOTS_FAN_PWM_INDEX, pwm);
}
/*
* Utility routine to read the CPU calibration EEPROM data
* from the device-tree
*/
static int read_eeprom(int cpu, struct mpu_data *out)
{
struct device_node *np;
char nodename[64];
const u8 *data;
int len;
/* prom.c routine for finding a node by path is a bit brain dead
* and requires exact @xxx unit numbers. This is a bit ugly but
* will work for these machines
*/
sprintf(nodename, "/u3@0,f8000000/i2c@f8001000/cpuid@a%d", cpu ? 2 : 0);
np = of_find_node_by_path(nodename);
if (np == NULL) {
printk(KERN_ERR "therm_pm72: Failed to retrieve cpuid node from device-tree\n");
return -ENODEV;
}
data = of_get_property(np, "cpuid", &len);
if (data == NULL) {
printk(KERN_ERR "therm_pm72: Failed to retrieve cpuid property from device-tree\n");
of_node_put(np);
return -ENODEV;
}
memcpy(out, data, sizeof(struct mpu_data));
of_node_put(np);
return 0;
}
static void fetch_cpu_pumps_minmax(void)
{
struct cpu_pid_state *state0 = &processor_state[0];
struct cpu_pid_state *state1 = &processor_state[1];
u16 pump_min = 0, pump_max = 0xffff;
u16 tmp[4];
/* Try to fetch pumps min/max infos from eeprom */
memcpy(&tmp, &state0->mpu.processor_part_num, 8);
if (tmp[0] != 0xffff && tmp[1] != 0xffff) {
pump_min = max(pump_min, tmp[0]);
pump_max = min(pump_max, tmp[1]);
}
if (tmp[2] != 0xffff && tmp[3] != 0xffff) {
pump_min = max(pump_min, tmp[2]);
pump_max = min(pump_max, tmp[3]);
}
/* Double check the values, this _IS_ needed as the EEPROM on
* some dual 2.5Ghz G5s seem, at least, to have both min & max
* same to the same value ... (grrrr)
*/
if (pump_min == pump_max || pump_min == 0 || pump_max == 0xffff) {
pump_min = CPU_PUMP_OUTPUT_MIN;
pump_max = CPU_PUMP_OUTPUT_MAX;
}
state0->pump_min = state1->pump_min = pump_min;
state0->pump_max = state1->pump_max = pump_max;
}
/*
* Now, unfortunately, sysfs doesn't give us a nice void * we could
* pass around to the attribute functions, so we don't really have
* choice but implement a bunch of them...
*
* That sucks a bit, we take the lock because FIX32TOPRINT evaluates
* the input twice... I accept patches :)
*/
#define BUILD_SHOW_FUNC_FIX(name, data) \
static ssize_t show_##name(struct device *dev, struct device_attribute *attr, char *buf) \
{ \
ssize_t r; \
mutex_lock(&driver_lock); \
r = sprintf(buf, "%d.%03d", FIX32TOPRINT(data)); \
mutex_unlock(&driver_lock); \
return r; \
}
#define BUILD_SHOW_FUNC_INT(name, data) \
static ssize_t show_##name(struct device *dev, struct device_attribute *attr, char *buf) \
{ \
return sprintf(buf, "%d", data); \
}
BUILD_SHOW_FUNC_FIX(cpu0_temperature, processor_state[0].last_temp)
BUILD_SHOW_FUNC_FIX(cpu0_voltage, processor_state[0].voltage)
BUILD_SHOW_FUNC_FIX(cpu0_current, processor_state[0].current_a)
BUILD_SHOW_FUNC_INT(cpu0_exhaust_fan_rpm, processor_state[0].rpm)
BUILD_SHOW_FUNC_INT(cpu0_intake_fan_rpm, processor_state[0].intake_rpm)
BUILD_SHOW_FUNC_FIX(cpu1_temperature, processor_state[1].last_temp)
BUILD_SHOW_FUNC_FIX(cpu1_voltage, processor_state[1].voltage)
BUILD_SHOW_FUNC_FIX(cpu1_current, processor_state[1].current_a)
BUILD_SHOW_FUNC_INT(cpu1_exhaust_fan_rpm, processor_state[1].rpm)
BUILD_SHOW_FUNC_INT(cpu1_intake_fan_rpm, processor_state[1].intake_rpm)
BUILD_SHOW_FUNC_FIX(backside_temperature, backside_state.last_temp)
BUILD_SHOW_FUNC_INT(backside_fan_pwm, backside_state.pwm)
BUILD_SHOW_FUNC_FIX(drives_temperature, drives_state.last_temp)
BUILD_SHOW_FUNC_INT(drives_fan_rpm, drives_state.rpm)
BUILD_SHOW_FUNC_FIX(slots_temperature, slots_state.last_temp)
BUILD_SHOW_FUNC_INT(slots_fan_pwm, slots_state.pwm)
BUILD_SHOW_FUNC_FIX(dimms_temperature, dimms_state.last_temp)
static DEVICE_ATTR(cpu0_temperature,S_IRUGO,show_cpu0_temperature,NULL);
static DEVICE_ATTR(cpu0_voltage,S_IRUGO,show_cpu0_voltage,NULL);
static DEVICE_ATTR(cpu0_current,S_IRUGO,show_cpu0_current,NULL);
static DEVICE_ATTR(cpu0_exhaust_fan_rpm,S_IRUGO,show_cpu0_exhaust_fan_rpm,NULL);
static DEVICE_ATTR(cpu0_intake_fan_rpm,S_IRUGO,show_cpu0_intake_fan_rpm,NULL);
static DEVICE_ATTR(cpu1_temperature,S_IRUGO,show_cpu1_temperature,NULL);
static DEVICE_ATTR(cpu1_voltage,S_IRUGO,show_cpu1_voltage,NULL);
static DEVICE_ATTR(cpu1_current,S_IRUGO,show_cpu1_current,NULL);
static DEVICE_ATTR(cpu1_exhaust_fan_rpm,S_IRUGO,show_cpu1_exhaust_fan_rpm,NULL);
static DEVICE_ATTR(cpu1_intake_fan_rpm,S_IRUGO,show_cpu1_intake_fan_rpm,NULL);
static DEVICE_ATTR(backside_temperature,S_IRUGO,show_backside_temperature,NULL);
static DEVICE_ATTR(backside_fan_pwm,S_IRUGO,show_backside_fan_pwm,NULL);
static DEVICE_ATTR(drives_temperature,S_IRUGO,show_drives_temperature,NULL);
static DEVICE_ATTR(drives_fan_rpm,S_IRUGO,show_drives_fan_rpm,NULL);
static DEVICE_ATTR(slots_temperature,S_IRUGO,show_slots_temperature,NULL);
static DEVICE_ATTR(slots_fan_pwm,S_IRUGO,show_slots_fan_pwm,NULL);
static DEVICE_ATTR(dimms_temperature,S_IRUGO,show_dimms_temperature,NULL);
/*
* CPUs fans control loop
*/
static int do_read_one_cpu_values(struct cpu_pid_state *state, s32 *temp, s32 *power)
{
s32 ltemp, volts, amps;
int index, rc = 0;
/* Default (in case of error) */
*temp = state->cur_temp;
*power = state->cur_power;
if (cpu_pid_type == CPU_PID_TYPE_RACKMAC)
index = (state->index == 0) ?
CPU_A1_FAN_RPM_INDEX : CPU_B1_FAN_RPM_INDEX;
else
index = (state->index == 0) ?
CPUA_EXHAUST_FAN_RPM_INDEX : CPUB_EXHAUST_FAN_RPM_INDEX;
/* Read current fan status */
rc = get_rpm_fan(index, !RPM_PID_USE_ACTUAL_SPEED);
if (rc < 0) {
/* XXX What do we do now ? Nothing for now, keep old value, but
* return error upstream
*/
DBG(" cpu %d, fan reading error !\n", state->index);
} else {
state->rpm = rc;
DBG(" cpu %d, exhaust RPM: %d\n", state->index, state->rpm);
}
/* Get some sensor readings and scale it */
ltemp = read_smon_adc(state, 1);
if (ltemp == -1) {
/* XXX What do we do now ? */
state->overtemp++;
if (rc == 0)
rc = -EIO;
DBG(" cpu %d, temp reading error !\n", state->index);
} else {
/* Fixup temperature according to diode calibration
*/
DBG(" cpu %d, temp raw: %04x, m_diode: %04x, b_diode: %04x\n",
state->index,
ltemp, state->mpu.mdiode, state->mpu.bdiode);
*temp = ((s32)ltemp * (s32)state->mpu.mdiode + ((s32)state->mpu.bdiode << 12)) >> 2;
state->last_temp = *temp;
DBG(" temp: %d.%03d\n", FIX32TOPRINT((*temp)));
}
/*
* Read voltage & current and calculate power
*/
volts = read_smon_adc(state, 3);
amps = read_smon_adc(state, 4);
/* Scale voltage and current raw sensor values according to fixed scales
* obtained in Darwin and calculate power from I and V
*/
volts *= ADC_CPU_VOLTAGE_SCALE;
amps *= ADC_CPU_CURRENT_SCALE;
*power = (((u64)volts) * ((u64)amps)) >> 16;
state->voltage = volts;
state->current_a = amps;
state->last_power = *power;
DBG(" cpu %d, current: %d.%03d, voltage: %d.%03d, power: %d.%03d W\n",
state->index, FIX32TOPRINT(state->current_a),
FIX32TOPRINT(state->voltage), FIX32TOPRINT(*power));
return 0;
}
static void do_cpu_pid(struct cpu_pid_state *state, s32 temp, s32 power)
{
s32 power_target, integral, derivative, proportional, adj_in_target, sval;
s64 integ_p, deriv_p, prop_p, sum;
int i;
/* Calculate power target value (could be done once for all)
* and convert to a 16.16 fp number
*/
power_target = ((u32)(state->mpu.pmaxh - state->mpu.padjmax)) << 16;
DBG(" power target: %d.%03d, error: %d.%03d\n",
FIX32TOPRINT(power_target), FIX32TOPRINT(power_target - power));
/* Store temperature and power in history array */
state->cur_temp = (state->cur_temp + 1) % CPU_TEMP_HISTORY_SIZE;
state->temp_history[state->cur_temp] = temp;
state->cur_power = (state->cur_power + 1) % state->count_power;
state->power_history[state->cur_power] = power;
state->error_history[state->cur_power] = power_target - power;
/* If first loop, fill the history table */
if (state->first) {
for (i = 0; i < (state->count_power - 1); i++) {
state->cur_power = (state->cur_power + 1) % state->count_power;
state->power_history[state->cur_power] = power;
state->error_history[state->cur_power] = power_target - power;
}
for (i = 0; i < (CPU_TEMP_HISTORY_SIZE - 1); i++) {
state->cur_temp = (state->cur_temp + 1) % CPU_TEMP_HISTORY_SIZE;
state->temp_history[state->cur_temp] = temp;
}
state->first = 0;
}
/* Calculate the integral term normally based on the "power" values */
sum = 0;
integral = 0;
for (i = 0; i < state->count_power; i++)
integral += state->error_history[i];
integral *= CPU_PID_INTERVAL;
DBG(" integral: %08x\n", integral);
/* Calculate the adjusted input (sense value).
* G_r is 12.20
* integ is 16.16
* so the result is 28.36
*
* input target is mpu.ttarget, input max is mpu.tmax
*/
integ_p = ((s64)state->mpu.pid_gr) * (s64)integral;
DBG(" integ_p: %d\n", (int)(integ_p >> 36));
sval = (state->mpu.tmax << 16) - ((integ_p >> 20) & 0xffffffff);
adj_in_target = (state->mpu.ttarget << 16);
if (adj_in_target > sval)
adj_in_target = sval;
DBG(" adj_in_target: %d.%03d, ttarget: %d\n", FIX32TOPRINT(adj_in_target),
state->mpu.ttarget);
/* Calculate the derivative term */
derivative = state->temp_history[state->cur_temp] -
state->temp_history[(state->cur_temp + CPU_TEMP_HISTORY_SIZE - 1)
% CPU_TEMP_HISTORY_SIZE];
derivative /= CPU_PID_INTERVAL;
deriv_p = ((s64)state->mpu.pid_gd) * (s64)derivative;
DBG(" deriv_p: %d\n", (int)(deriv_p >> 36));
sum += deriv_p;
/* Calculate the proportional term */
proportional = temp - adj_in_target;
prop_p = ((s64)state->mpu.pid_gp) * (s64)proportional;
DBG(" prop_p: %d\n", (int)(prop_p >> 36));
sum += prop_p;
/* Scale sum */
sum >>= 36;
DBG(" sum: %d\n", (int)sum);
state->rpm += (s32)sum;
}
static void do_monitor_cpu_combined(void)
{
struct cpu_pid_state *state0 = &processor_state[0];
struct cpu_pid_state *state1 = &processor_state[1];
s32 temp0, power0, temp1, power1;
s32 temp_combi, power_combi;
int rc, intake, pump;
rc = do_read_one_cpu_values(state0, &temp0, &power0);
if (rc < 0) {
/* XXX What do we do now ? */
}
state1->overtemp = 0;
rc = do_read_one_cpu_values(state1, &temp1, &power1);
if (rc < 0) {
/* XXX What do we do now ? */
}
if (state1->overtemp)
state0->overtemp++;
temp_combi = max(temp0, temp1);
power_combi = max(power0, power1);
/* Check tmax, increment overtemp if we are there. At tmax+8, we go
* full blown immediately and try to trigger a shutdown
*/
if (temp_combi >= ((state0->mpu.tmax + 8) << 16)) {
printk(KERN_WARNING "Warning ! Temperature way above maximum (%d) !\n",
temp_combi >> 16);
state0->overtemp += CPU_MAX_OVERTEMP / 4;
} else if (temp_combi > (state0->mpu.tmax << 16)) {
state0->overtemp++;
printk(KERN_WARNING "Temperature %d above max %d. overtemp %d\n",
temp_combi >> 16, state0->mpu.tmax, state0->overtemp);
} else {
if (state0->overtemp)
printk(KERN_WARNING "Temperature back down to %d\n",
temp_combi >> 16);
state0->overtemp = 0;
}
if (state0->overtemp >= CPU_MAX_OVERTEMP)
critical_state = 1;
if (state0->overtemp > 0) {
state0->rpm = state0->mpu.rmaxn_exhaust_fan;
state0->intake_rpm = intake = state0->mpu.rmaxn_intake_fan;
pump = state0->pump_max;
goto do_set_fans;
}
/* Do the PID */
do_cpu_pid(state0, temp_combi, power_combi);
/* Range check */
state0->rpm = max(state0->rpm, (int)state0->mpu.rminn_exhaust_fan);
state0->rpm = min(state0->rpm, (int)state0->mpu.rmaxn_exhaust_fan);
/* Calculate intake fan speed */
intake = (state0->rpm * CPU_INTAKE_SCALE) >> 16;
intake = max(intake, (int)state0->mpu.rminn_intake_fan);
intake = min(intake, (int)state0->mpu.rmaxn_intake_fan);
state0->intake_rpm = intake;
/* Calculate pump speed */
pump = (state0->rpm * state0->pump_max) /
state0->mpu.rmaxn_exhaust_fan;
pump = min(pump, state0->pump_max);
pump = max(pump, state0->pump_min);
do_set_fans:
/* We copy values from state 0 to state 1 for /sysfs */
state1->rpm = state0->rpm;
state1->intake_rpm = state0->intake_rpm;
DBG("** CPU %d RPM: %d Ex, %d, Pump: %d, In, overtemp: %d\n",
state1->index, (int)state1->rpm, intake, pump, state1->overtemp);
/* We should check for errors, shouldn't we ? But then, what
* do we do once the error occurs ? For FCU notified fan
* failures (-EFAULT) we probably want to notify userland
* some way...
*/
set_rpm_fan(CPUA_INTAKE_FAN_RPM_INDEX, intake);
set_rpm_fan(CPUA_EXHAUST_FAN_RPM_INDEX, state0->rpm);
set_rpm_fan(CPUB_INTAKE_FAN_RPM_INDEX, intake);
set_rpm_fan(CPUB_EXHAUST_FAN_RPM_INDEX, state0->rpm);
if (fcu_fans[CPUA_PUMP_RPM_INDEX].id != FCU_FAN_ABSENT_ID)
set_rpm_fan(CPUA_PUMP_RPM_INDEX, pump);
if (fcu_fans[CPUB_PUMP_RPM_INDEX].id != FCU_FAN_ABSENT_ID)
set_rpm_fan(CPUB_PUMP_RPM_INDEX, pump);
}
static void do_monitor_cpu_split(struct cpu_pid_state *state)
{
s32 temp, power;
int rc, intake;
/* Read current fan status */
rc = do_read_one_cpu_values(state, &temp, &power);
if (rc < 0) {
/* XXX What do we do now ? */
}
/* Check tmax, increment overtemp if we are there. At tmax+8, we go
* full blown immediately and try to trigger a shutdown
*/
if (temp >= ((state->mpu.tmax + 8) << 16)) {
printk(KERN_WARNING "Warning ! CPU %d temperature way above maximum"
" (%d) !\n",
state->index, temp >> 16);
state->overtemp += CPU_MAX_OVERTEMP / 4;
} else if (temp > (state->mpu.tmax << 16)) {
state->overtemp++;
printk(KERN_WARNING "CPU %d temperature %d above max %d. overtemp %d\n",
state->index, temp >> 16, state->mpu.tmax, state->overtemp);
} else {
if (state->overtemp)
printk(KERN_WARNING "CPU %d temperature back down to %d\n",
state->index, temp >> 16);
state->overtemp = 0;
}
if (state->overtemp >= CPU_MAX_OVERTEMP)
critical_state = 1;
if (state->overtemp > 0) {
state->rpm = state->mpu.rmaxn_exhaust_fan;
state->intake_rpm = intake = state->mpu.rmaxn_intake_fan;
goto do_set_fans;
}
/* Do the PID */
do_cpu_pid(state, temp, power);
/* Range check */
state->rpm = max(state->rpm, (int)state->mpu.rminn_exhaust_fan);
state->rpm = min(state->rpm, (int)state->mpu.rmaxn_exhaust_fan);
/* Calculate intake fan */
intake = (state->rpm * CPU_INTAKE_SCALE) >> 16;
intake = max(intake, (int)state->mpu.rminn_intake_fan);
intake = min(intake, (int)state->mpu.rmaxn_intake_fan);
state->intake_rpm = intake;
do_set_fans:
DBG("** CPU %d RPM: %d Ex, %d In, overtemp: %d\n",
state->index, (int)state->rpm, intake, state->overtemp);
/* We should check for errors, shouldn't we ? But then, what
* do we do once the error occurs ? For FCU notified fan
* failures (-EFAULT) we probably want to notify userland
* some way...
*/
if (state->index == 0) {
set_rpm_fan(CPUA_INTAKE_FAN_RPM_INDEX, intake);
set_rpm_fan(CPUA_EXHAUST_FAN_RPM_INDEX, state->rpm);
} else {
set_rpm_fan(CPUB_INTAKE_FAN_RPM_INDEX, intake);
set_rpm_fan(CPUB_EXHAUST_FAN_RPM_INDEX, state->rpm);
}
}
static void do_monitor_cpu_rack(struct cpu_pid_state *state)
{
s32 temp, power, fan_min;
int rc;
/* Read current fan status */
rc = do_read_one_cpu_values(state, &temp, &power);
if (rc < 0) {
/* XXX What do we do now ? */
}
/* Check tmax, increment overtemp if we are there. At tmax+8, we go
* full blown immediately and try to trigger a shutdown
*/
if (temp >= ((state->mpu.tmax + 8) << 16)) {
printk(KERN_WARNING "Warning ! CPU %d temperature way above maximum"
" (%d) !\n",
state->index, temp >> 16);
state->overtemp = CPU_MAX_OVERTEMP / 4;
} else if (temp > (state->mpu.tmax << 16)) {
state->overtemp++;
printk(KERN_WARNING "CPU %d temperature %d above max %d. overtemp %d\n",
state->index, temp >> 16, state->mpu.tmax, state->overtemp);
} else {
if (state->overtemp)
printk(KERN_WARNING "CPU %d temperature back down to %d\n",
state->index, temp >> 16);
state->overtemp = 0;
}
if (state->overtemp >= CPU_MAX_OVERTEMP)
critical_state = 1;
if (state->overtemp > 0) {
state->rpm = state->intake_rpm = state->mpu.rmaxn_intake_fan;
goto do_set_fans;
}
/* Do the PID */
do_cpu_pid(state, temp, power);
/* Check clamp from dimms */
fan_min = dimm_output_clamp;
fan_min = max(fan_min, (int)state->mpu.rminn_intake_fan);
DBG(" CPU min mpu = %d, min dimm = %d\n",
state->mpu.rminn_intake_fan, dimm_output_clamp);
state->rpm = max(state->rpm, (int)fan_min);
state->rpm = min(state->rpm, (int)state->mpu.rmaxn_intake_fan);
state->intake_rpm = state->rpm;
do_set_fans:
DBG("** CPU %d RPM: %d overtemp: %d\n",
state->index, (int)state->rpm, state->overtemp);
/* We should check for errors, shouldn't we ? But then, what
* do we do once the error occurs ? For FCU notified fan
* failures (-EFAULT) we probably want to notify userland
* some way...
*/
if (state->index == 0) {
set_rpm_fan(CPU_A1_FAN_RPM_INDEX, state->rpm);
set_rpm_fan(CPU_A2_FAN_RPM_INDEX, state->rpm);
set_rpm_fan(CPU_A3_FAN_RPM_INDEX, state->rpm);
} else {
set_rpm_fan(CPU_B1_FAN_RPM_INDEX, state->rpm);
set_rpm_fan(CPU_B2_FAN_RPM_INDEX, state->rpm);
set_rpm_fan(CPU_B3_FAN_RPM_INDEX, state->rpm);
}
}
/*
* Initialize the state structure for one CPU control loop
*/
static int init_processor_state(struct cpu_pid_state *state, int index)
{
int err;
state->index = index;
state->first = 1;
state->rpm = (cpu_pid_type == CPU_PID_TYPE_RACKMAC) ? 4000 : 1000;
state->overtemp = 0;
state->adc_config = 0x00;
if (index == 0)
state->monitor = attach_i2c_chip(SUPPLY_MONITOR_ID, "CPU0_monitor");
else if (index == 1)
state->monitor = attach_i2c_chip(SUPPLY_MONITORB_ID, "CPU1_monitor");
if (state->monitor == NULL)
goto fail;
if (read_eeprom(index, &state->mpu))
goto fail;
state->count_power = state->mpu.tguardband;
if (state->count_power > CPU_POWER_HISTORY_SIZE) {
printk(KERN_WARNING "Warning ! too many power history slots\n");
state->count_power = CPU_POWER_HISTORY_SIZE;
}
DBG("CPU %d Using %d power history entries\n", index, state->count_power);
if (index == 0) {
err = device_create_file(&of_dev->dev, &dev_attr_cpu0_temperature);
err |= device_create_file(&of_dev->dev, &dev_attr_cpu0_voltage);
err |= device_create_file(&of_dev->dev, &dev_attr_cpu0_current);
err |= device_create_file(&of_dev->dev, &dev_attr_cpu0_exhaust_fan_rpm);
err |= device_create_file(&of_dev->dev, &dev_attr_cpu0_intake_fan_rpm);
} else {
err = device_create_file(&of_dev->dev, &dev_attr_cpu1_temperature);
err |= device_create_file(&of_dev->dev, &dev_attr_cpu1_voltage);
err |= device_create_file(&of_dev->dev, &dev_attr_cpu1_current);
err |= device_create_file(&of_dev->dev, &dev_attr_cpu1_exhaust_fan_rpm);
err |= device_create_file(&of_dev->dev, &dev_attr_cpu1_intake_fan_rpm);
}
if (err)
printk(KERN_WARNING "Failed to create some of the attribute"
"files for CPU %d\n", index);
return 0;
fail:
state->monitor = NULL;
return -ENODEV;
}
/*
* Dispose of the state data for one CPU control loop
*/
static void dispose_processor_state(struct cpu_pid_state *state)
{
if (state->monitor == NULL)
return;
if (state->index == 0) {
device_remove_file(&of_dev->dev, &dev_attr_cpu0_temperature);
device_remove_file(&of_dev->dev, &dev_attr_cpu0_voltage);
device_remove_file(&of_dev->dev, &dev_attr_cpu0_current);
device_remove_file(&of_dev->dev, &dev_attr_cpu0_exhaust_fan_rpm);
device_remove_file(&of_dev->dev, &dev_attr_cpu0_intake_fan_rpm);
} else {
device_remove_file(&of_dev->dev, &dev_attr_cpu1_temperature);
device_remove_file(&of_dev->dev, &dev_attr_cpu1_voltage);
device_remove_file(&of_dev->dev, &dev_attr_cpu1_current);
device_remove_file(&of_dev->dev, &dev_attr_cpu1_exhaust_fan_rpm);
device_remove_file(&of_dev->dev, &dev_attr_cpu1_intake_fan_rpm);
}
state->monitor = NULL;
}
/*
* Motherboard backside & U3 heatsink fan control loop
*/
static void do_monitor_backside(struct backside_pid_state *state)
{
s32 temp, integral, derivative, fan_min;
s64 integ_p, deriv_p, prop_p, sum;
int i, rc;
if (--state->ticks != 0)
return;
state->ticks = backside_params.interval;
DBG("backside:\n");
/* Check fan status */
rc = get_pwm_fan(BACKSIDE_FAN_PWM_INDEX);
if (rc < 0) {
printk(KERN_WARNING "Error %d reading backside fan !\n", rc);
/* XXX What do we do now ? */
} else
state->pwm = rc;
DBG(" current pwm: %d\n", state->pwm);
/* Get some sensor readings */
temp = i2c_smbus_read_byte_data(state->monitor, MAX6690_EXT_TEMP) << 16;
state->last_temp = temp;
DBG(" temp: %d.%03d, target: %d.%03d\n", FIX32TOPRINT(temp),
FIX32TOPRINT(backside_params.input_target));
/* Store temperature and error in history array */
state->cur_sample = (state->cur_sample + 1) % BACKSIDE_PID_HISTORY_SIZE;
state->sample_history[state->cur_sample] = temp;
state->error_history[state->cur_sample] = temp - backside_params.input_target;
/* If first loop, fill the history table */
if (state->first) {
for (i = 0; i < (BACKSIDE_PID_HISTORY_SIZE - 1); i++) {
state->cur_sample = (state->cur_sample + 1) %
BACKSIDE_PID_HISTORY_SIZE;
state->sample_history[state->cur_sample] = temp;
state->error_history[state->cur_sample] =
temp - backside_params.input_target;
}
state->first = 0;
}
/* Calculate the integral term */
sum = 0;
integral = 0;
for (i = 0; i < BACKSIDE_PID_HISTORY_SIZE; i++)
integral += state->error_history[i];
integral *= backside_params.interval;
DBG(" integral: %08x\n", integral);
integ_p = ((s64)backside_params.G_r) * (s64)integral;
DBG(" integ_p: %d\n", (int)(integ_p >> 36));
sum += integ_p;
/* Calculate the derivative term */
derivative = state->error_history[state->cur_sample] -
state->error_history[(state->cur_sample + BACKSIDE_PID_HISTORY_SIZE - 1)
% BACKSIDE_PID_HISTORY_SIZE];
derivative /= backside_params.interval;
deriv_p = ((s64)backside_params.G_d) * (s64)derivative;
DBG(" deriv_p: %d\n", (int)(deriv_p >> 36));
sum += deriv_p;
/* Calculate the proportional term */
prop_p = ((s64)backside_params.G_p) * (s64)(state->error_history[state->cur_sample]);
DBG(" prop_p: %d\n", (int)(prop_p >> 36));
sum += prop_p;
/* Scale sum */
sum >>= 36;
DBG(" sum: %d\n", (int)sum);
if (backside_params.additive)
state->pwm += (s32)sum;
else
state->pwm = sum;
/* Check for clamp */
fan_min = (dimm_output_clamp * 100) / 14000;
fan_min = max(fan_min, backside_params.output_min);
state->pwm = max(state->pwm, fan_min);
state->pwm = min(state->pwm, backside_params.output_max);
DBG("** BACKSIDE PWM: %d\n", (int)state->pwm);
set_pwm_fan(BACKSIDE_FAN_PWM_INDEX, state->pwm);
}
/*
* Initialize the state structure for the backside fan control loop
*/
static int init_backside_state(struct backside_pid_state *state)
{
struct device_node *u3;
int u3h = 1; /* conservative by default */
int err;
/*
* There are different PID params for machines with U3 and machines
* with U3H, pick the right ones now
*/
u3 = of_find_node_by_path("/u3@0,f8000000");
if (u3 != NULL) {
const u32 *vers = of_get_property(u3, "device-rev", NULL);
if (vers)
if (((*vers) & 0x3f) < 0x34)
u3h = 0;
of_node_put(u3);
}
if (rackmac) {
backside_params.G_d = BACKSIDE_PID_RACK_G_d;
backside_params.input_target = BACKSIDE_PID_RACK_INPUT_TARGET;
backside_params.output_min = BACKSIDE_PID_U3H_OUTPUT_MIN;
backside_params.interval = BACKSIDE_PID_RACK_INTERVAL;
backside_params.G_p = BACKSIDE_PID_RACK_G_p;
backside_params.G_r = BACKSIDE_PID_G_r;
backside_params.output_max = BACKSIDE_PID_OUTPUT_MAX;
backside_params.additive = 0;
} else if (u3h) {
backside_params.G_d = BACKSIDE_PID_U3H_G_d;
backside_params.input_target = BACKSIDE_PID_U3H_INPUT_TARGET;
backside_params.output_min = BACKSIDE_PID_U3H_OUTPUT_MIN;
backside_params.interval = BACKSIDE_PID_INTERVAL;
backside_params.G_p = BACKSIDE_PID_G_p;
backside_params.G_r = BACKSIDE_PID_G_r;
backside_params.output_max = BACKSIDE_PID_OUTPUT_MAX;
backside_params.additive = 1;
} else {
backside_params.G_d = BACKSIDE_PID_U3_G_d;
backside_params.input_target = BACKSIDE_PID_U3_INPUT_TARGET;
backside_params.output_min = BACKSIDE_PID_U3_OUTPUT_MIN;
backside_params.interval = BACKSIDE_PID_INTERVAL;
backside_params.G_p = BACKSIDE_PID_G_p;
backside_params.G_r = BACKSIDE_PID_G_r;
backside_params.output_max = BACKSIDE_PID_OUTPUT_MAX;
backside_params.additive = 1;
}
state->ticks = 1;
state->first = 1;
state->pwm = 50;
state->monitor = attach_i2c_chip(BACKSIDE_MAX_ID, "backside_temp");
if (state->monitor == NULL)
return -ENODEV;
err = device_create_file(&of_dev->dev, &dev_attr_backside_temperature);
err |= device_create_file(&of_dev->dev, &dev_attr_backside_fan_pwm);
if (err)
printk(KERN_WARNING "Failed to create attribute file(s)"
" for backside fan\n");
return 0;
}
/*
* Dispose of the state data for the backside control loop
*/
static void dispose_backside_state(struct backside_pid_state *state)
{
if (state->monitor == NULL)
return;
device_remove_file(&of_dev->dev, &dev_attr_backside_temperature);
device_remove_file(&of_dev->dev, &dev_attr_backside_fan_pwm);
state->monitor = NULL;
}
/*
* Drives bay fan control loop
*/
static void do_monitor_drives(struct drives_pid_state *state)
{
s32 temp, integral, derivative;
s64 integ_p, deriv_p, prop_p, sum;
int i, rc;
if (--state->ticks != 0)
return;
state->ticks = DRIVES_PID_INTERVAL;
DBG("drives:\n");
/* Check fan status */
rc = get_rpm_fan(DRIVES_FAN_RPM_INDEX, !RPM_PID_USE_ACTUAL_SPEED);
if (rc < 0) {
printk(KERN_WARNING "Error %d reading drives fan !\n", rc);
/* XXX What do we do now ? */
} else
state->rpm = rc;
DBG(" current rpm: %d\n", state->rpm);
/* Get some sensor readings */
temp = le16_to_cpu(i2c_smbus_read_word_data(state->monitor,
DS1775_TEMP)) << 8;
state->last_temp = temp;
DBG(" temp: %d.%03d, target: %d.%03d\n", FIX32TOPRINT(temp),
FIX32TOPRINT(DRIVES_PID_INPUT_TARGET));
/* Store temperature and error in history array */
state->cur_sample = (state->cur_sample + 1) % DRIVES_PID_HISTORY_SIZE;
state->sample_history[state->cur_sample] = temp;
state->error_history[state->cur_sample] = temp - DRIVES_PID_INPUT_TARGET;
/* If first loop, fill the history table */
if (state->first) {
for (i = 0; i < (DRIVES_PID_HISTORY_SIZE - 1); i++) {
state->cur_sample = (state->cur_sample + 1) %
DRIVES_PID_HISTORY_SIZE;
state->sample_history[state->cur_sample] = temp;
state->error_history[state->cur_sample] =
temp - DRIVES_PID_INPUT_TARGET;
}
state->first = 0;
}
/* Calculate the integral term */
sum = 0;
integral = 0;
for (i = 0; i < DRIVES_PID_HISTORY_SIZE; i++)
integral += state->error_history[i];
integral *= DRIVES_PID_INTERVAL;
DBG(" integral: %08x\n", integral);
integ_p = ((s64)DRIVES_PID_G_r) * (s64)integral;
DBG(" integ_p: %d\n", (int)(integ_p >> 36));
sum += integ_p;
/* Calculate the derivative term */
derivative = state->error_history[state->cur_sample] -
state->error_history[(state->cur_sample + DRIVES_PID_HISTORY_SIZE - 1)
% DRIVES_PID_HISTORY_SIZE];
derivative /= DRIVES_PID_INTERVAL;
deriv_p = ((s64)DRIVES_PID_G_d) * (s64)derivative;
DBG(" deriv_p: %d\n", (int)(deriv_p >> 36));
sum += deriv_p;
/* Calculate the proportional term */
prop_p = ((s64)DRIVES_PID_G_p) * (s64)(state->error_history[state->cur_sample]);
DBG(" prop_p: %d\n", (int)(prop_p >> 36));
sum += prop_p;
/* Scale sum */
sum >>= 36;
DBG(" sum: %d\n", (int)sum);
state->rpm += (s32)sum;
state->rpm = max(state->rpm, DRIVES_PID_OUTPUT_MIN);
state->rpm = min(state->rpm, DRIVES_PID_OUTPUT_MAX);
DBG("** DRIVES RPM: %d\n", (int)state->rpm);
set_rpm_fan(DRIVES_FAN_RPM_INDEX, state->rpm);
}
/*
* Initialize the state structure for the drives bay fan control loop
*/
static int init_drives_state(struct drives_pid_state *state)
{
int err;
state->ticks = 1;
state->first = 1;
state->rpm = 1000;
state->monitor = attach_i2c_chip(DRIVES_DALLAS_ID, "drives_temp");
if (state->monitor == NULL)
return -ENODEV;
err = device_create_file(&of_dev->dev, &dev_attr_drives_temperature);
err |= device_create_file(&of_dev->dev, &dev_attr_drives_fan_rpm);
if (err)
printk(KERN_WARNING "Failed to create attribute file(s)"
" for drives bay fan\n");
return 0;
}
/*
* Dispose of the state data for the drives control loop
*/
static void dispose_drives_state(struct drives_pid_state *state)
{
if (state->monitor == NULL)
return;
device_remove_file(&of_dev->dev, &dev_attr_drives_temperature);
device_remove_file(&of_dev->dev, &dev_attr_drives_fan_rpm);
state->monitor = NULL;
}
/*
* DIMMs temp control loop
*/
static void do_monitor_dimms(struct dimm_pid_state *state)
{
s32 temp, integral, derivative, fan_min;
s64 integ_p, deriv_p, prop_p, sum;
int i;
if (--state->ticks != 0)
return;
state->ticks = DIMM_PID_INTERVAL;
DBG("DIMM:\n");
DBG(" current value: %d\n", state->output);
temp = read_lm87_reg(state->monitor, LM87_INT_TEMP);
if (temp < 0)
return;
temp <<= 16;
state->last_temp = temp;
DBG(" temp: %d.%03d, target: %d.%03d\n", FIX32TOPRINT(temp),
FIX32TOPRINT(DIMM_PID_INPUT_TARGET));
/* Store temperature and error in history array */
state->cur_sample = (state->cur_sample + 1) % DIMM_PID_HISTORY_SIZE;
state->sample_history[state->cur_sample] = temp;
state->error_history[state->cur_sample] = temp - DIMM_PID_INPUT_TARGET;
/* If first loop, fill the history table */
if (state->first) {
for (i = 0; i < (DIMM_PID_HISTORY_SIZE - 1); i++) {
state->cur_sample = (state->cur_sample + 1) %
DIMM_PID_HISTORY_SIZE;
state->sample_history[state->cur_sample] = temp;
state->error_history[state->cur_sample] =
temp - DIMM_PID_INPUT_TARGET;
}
state->first = 0;
}
/* Calculate the integral term */
sum = 0;
integral = 0;
for (i = 0; i < DIMM_PID_HISTORY_SIZE; i++)
integral += state->error_history[i];
integral *= DIMM_PID_INTERVAL;
DBG(" integral: %08x\n", integral);
integ_p = ((s64)DIMM_PID_G_r) * (s64)integral;
DBG(" integ_p: %d\n", (int)(integ_p >> 36));
sum += integ_p;
/* Calculate the derivative term */
derivative = state->error_history[state->cur_sample] -
state->error_history[(state->cur_sample + DIMM_PID_HISTORY_SIZE - 1)
% DIMM_PID_HISTORY_SIZE];
derivative /= DIMM_PID_INTERVAL;
deriv_p = ((s64)DIMM_PID_G_d) * (s64)derivative;
DBG(" deriv_p: %d\n", (int)(deriv_p >> 36));
sum += deriv_p;
/* Calculate the proportional term */
prop_p = ((s64)DIMM_PID_G_p) * (s64)(state->error_history[state->cur_sample]);
DBG(" prop_p: %d\n", (int)(prop_p >> 36));
sum += prop_p;
/* Scale sum */
sum >>= 36;
DBG(" sum: %d\n", (int)sum);
state->output = (s32)sum;
state->output = max(state->output, DIMM_PID_OUTPUT_MIN);
state->output = min(state->output, DIMM_PID_OUTPUT_MAX);
dimm_output_clamp = state->output;
DBG("** DIMM clamp value: %d\n", (int)state->output);
/* Backside PID is only every 5 seconds, force backside fan clamping now */
fan_min = (dimm_output_clamp * 100) / 14000;
fan_min = max(fan_min, backside_params.output_min);
if (backside_state.pwm < fan_min) {
backside_state.pwm = fan_min;
DBG(" -> applying clamp to backside fan now: %d !\n", fan_min);
set_pwm_fan(BACKSIDE_FAN_PWM_INDEX, fan_min);
}
}
/*
* Initialize the state structure for the DIMM temp control loop
*/
static int init_dimms_state(struct dimm_pid_state *state)
{
state->ticks = 1;
state->first = 1;
state->output = 4000;
state->monitor = attach_i2c_chip(XSERVE_DIMMS_LM87, "dimms_temp");
if (state->monitor == NULL)
return -ENODEV;
if (device_create_file(&of_dev->dev, &dev_attr_dimms_temperature))
printk(KERN_WARNING "Failed to create attribute file"
" for DIMM temperature\n");
return 0;
}
/*
* Dispose of the state data for the DIMM control loop
*/
static void dispose_dimms_state(struct dimm_pid_state *state)
{
if (state->monitor == NULL)
return;
device_remove_file(&of_dev->dev, &dev_attr_dimms_temperature);
state->monitor = NULL;
}
/*
* Slots fan control loop
*/
static void do_monitor_slots(struct slots_pid_state *state)
{
s32 temp, integral, derivative;
s64 integ_p, deriv_p, prop_p, sum;
int i, rc;
if (--state->ticks != 0)
return;
state->ticks = SLOTS_PID_INTERVAL;
DBG("slots:\n");
/* Check fan status */
rc = get_pwm_fan(SLOTS_FAN_PWM_INDEX);
if (rc < 0) {
printk(KERN_WARNING "Error %d reading slots fan !\n", rc);
/* XXX What do we do now ? */
} else
state->pwm = rc;
DBG(" current pwm: %d\n", state->pwm);
/* Get some sensor readings */
temp = le16_to_cpu(i2c_smbus_read_word_data(state->monitor,
DS1775_TEMP)) << 8;
state->last_temp = temp;
DBG(" temp: %d.%03d, target: %d.%03d\n", FIX32TOPRINT(temp),
FIX32TOPRINT(SLOTS_PID_INPUT_TARGET));
/* Store temperature and error in history array */
state->cur_sample = (state->cur_sample + 1) % SLOTS_PID_HISTORY_SIZE;
state->sample_history[state->cur_sample] = temp;
state->error_history[state->cur_sample] = temp - SLOTS_PID_INPUT_TARGET;
/* If first loop, fill the history table */
if (state->first) {
for (i = 0; i < (SLOTS_PID_HISTORY_SIZE - 1); i++) {
state->cur_sample = (state->cur_sample + 1) %
SLOTS_PID_HISTORY_SIZE;
state->sample_history[state->cur_sample] = temp;
state->error_history[state->cur_sample] =
temp - SLOTS_PID_INPUT_TARGET;
}
state->first = 0;
}
/* Calculate the integral term */
sum = 0;
integral = 0;
for (i = 0; i < SLOTS_PID_HISTORY_SIZE; i++)
integral += state->error_history[i];
integral *= SLOTS_PID_INTERVAL;
DBG(" integral: %08x\n", integral);
integ_p = ((s64)SLOTS_PID_G_r) * (s64)integral;
DBG(" integ_p: %d\n", (int)(integ_p >> 36));
sum += integ_p;
/* Calculate the derivative term */
derivative = state->error_history[state->cur_sample] -
state->error_history[(state->cur_sample + SLOTS_PID_HISTORY_SIZE - 1)
% SLOTS_PID_HISTORY_SIZE];
derivative /= SLOTS_PID_INTERVAL;
deriv_p = ((s64)SLOTS_PID_G_d) * (s64)derivative;
DBG(" deriv_p: %d\n", (int)(deriv_p >> 36));
sum += deriv_p;
/* Calculate the proportional term */
prop_p = ((s64)SLOTS_PID_G_p) * (s64)(state->error_history[state->cur_sample]);
DBG(" prop_p: %d\n", (int)(prop_p >> 36));
sum += prop_p;
/* Scale sum */
sum >>= 36;
DBG(" sum: %d\n", (int)sum);
state->pwm = (s32)sum;
state->pwm = max(state->pwm, SLOTS_PID_OUTPUT_MIN);
state->pwm = min(state->pwm, SLOTS_PID_OUTPUT_MAX);
DBG("** DRIVES PWM: %d\n", (int)state->pwm);
set_pwm_fan(SLOTS_FAN_PWM_INDEX, state->pwm);
}
/*
* Initialize the state structure for the slots bay fan control loop
*/
static int init_slots_state(struct slots_pid_state *state)
{
int err;
state->ticks = 1;
state->first = 1;
state->pwm = 50;
state->monitor = attach_i2c_chip(XSERVE_SLOTS_LM75, "slots_temp");
if (state->monitor == NULL)
return -ENODEV;
err = device_create_file(&of_dev->dev, &dev_attr_slots_temperature);
err |= device_create_file(&of_dev->dev, &dev_attr_slots_fan_pwm);
if (err)
printk(KERN_WARNING "Failed to create attribute file(s)"
" for slots bay fan\n");
return 0;
}
/*
* Dispose of the state data for the slots control loop
*/
static void dispose_slots_state(struct slots_pid_state *state)
{
if (state->monitor == NULL)
return;
device_remove_file(&of_dev->dev, &dev_attr_slots_temperature);
device_remove_file(&of_dev->dev, &dev_attr_slots_fan_pwm);
state->monitor = NULL;
}
static int call_critical_overtemp(void)
{
char *argv[] = { critical_overtemp_path, NULL };
static char *envp[] = { "HOME=/",
"TERM=linux",
"PATH=/sbin:/usr/sbin:/bin:/usr/bin",
NULL };
return call_usermodehelper(critical_overtemp_path,
argv, envp, UMH_WAIT_EXEC);
}
/*
* Here's the kernel thread that calls the various control loops
*/
static int main_control_loop(void *x)
{
DBG("main_control_loop started\n");
mutex_lock(&driver_lock);
if (start_fcu() < 0) {
printk(KERN_ERR "kfand: failed to start FCU\n");
mutex_unlock(&driver_lock);
goto out;
}
/* Set the PCI fan once for now on non-RackMac */
if (!rackmac)
set_pwm_fan(SLOTS_FAN_PWM_INDEX, SLOTS_FAN_DEFAULT_PWM);
/* Initialize ADCs */
initialize_adc(&processor_state[0]);
if (processor_state[1].monitor != NULL)
initialize_adc(&processor_state[1]);
fcu_tickle_ticks = FCU_TICKLE_TICKS;
mutex_unlock(&driver_lock);
while (state == state_attached) {
unsigned long elapsed, start;
start = jiffies;
mutex_lock(&driver_lock);
/* Tickle the FCU just in case */
if (--fcu_tickle_ticks < 0) {
fcu_tickle_ticks = FCU_TICKLE_TICKS;
tickle_fcu();
}
/* First, we always calculate the new DIMMs state on an Xserve */
if (rackmac)
do_monitor_dimms(&dimms_state);
/* Then, the CPUs */
if (cpu_pid_type == CPU_PID_TYPE_COMBINED)
do_monitor_cpu_combined();
else if (cpu_pid_type == CPU_PID_TYPE_RACKMAC) {
do_monitor_cpu_rack(&processor_state[0]);
if (processor_state[1].monitor != NULL)
do_monitor_cpu_rack(&processor_state[1]);
// better deal with UP
} else {
do_monitor_cpu_split(&processor_state[0]);
if (processor_state[1].monitor != NULL)
do_monitor_cpu_split(&processor_state[1]);
// better deal with UP
}
/* Then, the rest */
do_monitor_backside(&backside_state);
if (rackmac)
do_monitor_slots(&slots_state);
else
do_monitor_drives(&drives_state);
mutex_unlock(&driver_lock);
if (critical_state == 1) {
printk(KERN_WARNING "Temperature control detected a critical condition\n");
printk(KERN_WARNING "Attempting to shut down...\n");
if (call_critical_overtemp()) {
printk(KERN_WARNING "Can't call %s, power off now!\n",
critical_overtemp_path);
machine_power_off();
}
}
if (critical_state > 0)
critical_state++;
if (critical_state > MAX_CRITICAL_STATE) {
printk(KERN_WARNING "Shutdown timed out, power off now !\n");
machine_power_off();
}
// FIXME: Deal with signals
elapsed = jiffies - start;
if (elapsed < HZ)
schedule_timeout_interruptible(HZ - elapsed);
}
out:
DBG("main_control_loop ended\n");
ctrl_task = 0;
complete_and_exit(&ctrl_complete, 0);
}
/*
* Dispose the control loops when tearing down
*/
static void dispose_control_loops(void)
{
dispose_processor_state(&processor_state[0]);
dispose_processor_state(&processor_state[1]);
dispose_backside_state(&backside_state);
dispose_drives_state(&drives_state);
dispose_slots_state(&slots_state);
dispose_dimms_state(&dimms_state);
}
/*
* Create the control loops. U3-0 i2c bus is up, so we can now
* get to the various sensors
*/
static int create_control_loops(void)
{
struct device_node *np;
/* Count CPUs from the device-tree, we don't care how many are
* actually used by Linux
*/
cpu_count = 0;
for (np = NULL; NULL != (np = of_find_node_by_type(np, "cpu"));)
cpu_count++;
DBG("counted %d CPUs in the device-tree\n", cpu_count);
/* Decide the type of PID algorithm to use based on the presence of
* the pumps, though that may not be the best way, that is good enough
* for now
*/
if (rackmac)
cpu_pid_type = CPU_PID_TYPE_RACKMAC;
else if (of_machine_is_compatible("PowerMac7,3")
&& (cpu_count > 1)
&& fcu_fans[CPUA_PUMP_RPM_INDEX].id != FCU_FAN_ABSENT_ID
&& fcu_fans[CPUB_PUMP_RPM_INDEX].id != FCU_FAN_ABSENT_ID) {
printk(KERN_INFO "Liquid cooling pumps detected, using new algorithm !\n");
cpu_pid_type = CPU_PID_TYPE_COMBINED;
} else
cpu_pid_type = CPU_PID_TYPE_SPLIT;
/* Create control loops for everything. If any fail, everything
* fails
*/
if (init_processor_state(&processor_state[0], 0))
goto fail;
if (cpu_pid_type == CPU_PID_TYPE_COMBINED)
fetch_cpu_pumps_minmax();
if (cpu_count > 1 && init_processor_state(&processor_state[1], 1))
goto fail;
if (init_backside_state(&backside_state))
goto fail;
if (rackmac && init_dimms_state(&dimms_state))
goto fail;
if (rackmac && init_slots_state(&slots_state))
goto fail;
if (!rackmac && init_drives_state(&drives_state))
goto fail;
DBG("all control loops up !\n");
return 0;
fail:
DBG("failure creating control loops, disposing\n");
dispose_control_loops();
return -ENODEV;
}
/*
* Start the control loops after everything is up, that is create
* the thread that will make them run
*/
static void start_control_loops(void)
{
init_completion(&ctrl_complete);
ctrl_task = kthread_run(main_control_loop, NULL, "kfand");
}
/*
* Stop the control loops when tearing down
*/
static void stop_control_loops(void)
{
if (ctrl_task)
wait_for_completion(&ctrl_complete);
}
/*
* Attach to the i2c FCU after detecting U3-1 bus
*/
static int attach_fcu(void)
{
fcu = attach_i2c_chip(FAN_CTRLER_ID, "fcu");
if (fcu == NULL)
return -ENODEV;
DBG("FCU attached\n");
return 0;
}
/*
* Detach from the i2c FCU when tearing down
*/
static void detach_fcu(void)
{
fcu = NULL;
}
/*
* Attach to the i2c controller. We probe the various chips based
* on the device-tree nodes and build everything for the driver to
* run, we then kick the driver monitoring thread
*/
static int therm_pm72_attach(struct i2c_adapter *adapter)
{
mutex_lock(&driver_lock);
/* Check state */
if (state == state_detached)
state = state_attaching;
if (state != state_attaching) {
mutex_unlock(&driver_lock);
return 0;
}
/* Check if we are looking for one of these */
if (u3_0 == NULL && !strcmp(adapter->name, "u3 0")) {
u3_0 = adapter;
DBG("found U3-0\n");
if (k2 || !rackmac)
if (create_control_loops())
u3_0 = NULL;
} else if (u3_1 == NULL && !strcmp(adapter->name, "u3 1")) {
u3_1 = adapter;
DBG("found U3-1, attaching FCU\n");
if (attach_fcu())
u3_1 = NULL;
} else if (k2 == NULL && !strcmp(adapter->name, "mac-io 0")) {
k2 = adapter;
DBG("Found K2\n");
if (u3_0 && rackmac)
if (create_control_loops())
k2 = NULL;
}
/* We got all we need, start control loops */
if (u3_0 != NULL && u3_1 != NULL && (k2 || !rackmac)) {
DBG("everything up, starting control loops\n");
state = state_attached;
start_control_loops();
}
mutex_unlock(&driver_lock);
return 0;
}
static int therm_pm72_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
/* Always succeed, the real work was done in therm_pm72_attach() */
return 0;
}
/*
* Called when any of the devices which participates into thermal management
* is going away.
*/
static int therm_pm72_remove(struct i2c_client *client)
{
struct i2c_adapter *adapter = client->adapter;
mutex_lock(&driver_lock);
if (state != state_detached)
state = state_detaching;
/* Stop control loops if any */
DBG("stopping control loops\n");
mutex_unlock(&driver_lock);
stop_control_loops();
mutex_lock(&driver_lock);
if (u3_0 != NULL && !strcmp(adapter->name, "u3 0")) {
DBG("lost U3-0, disposing control loops\n");
dispose_control_loops();
u3_0 = NULL;
}
if (u3_1 != NULL && !strcmp(adapter->name, "u3 1")) {
DBG("lost U3-1, detaching FCU\n");
detach_fcu();
u3_1 = NULL;
}
if (u3_0 == NULL && u3_1 == NULL)
state = state_detached;
mutex_unlock(&driver_lock);
return 0;
}
/*
* i2c_driver structure to attach to the host i2c controller
*/
static const struct i2c_device_id therm_pm72_id[] = {
/*
* Fake device name, thermal management is done by several
* chips but we don't need to differentiate between them at
* this point.
*/
{ "therm_pm72", 0 },
{ }
};
static struct i2c_driver therm_pm72_driver = {
.driver = {
.name = "therm_pm72",
},
.attach_adapter = therm_pm72_attach,
.probe = therm_pm72_probe,
.remove = therm_pm72_remove,
.id_table = therm_pm72_id,
};
static int fan_check_loc_match(const char *loc, int fan)
{
char tmp[64];
char *c, *e;
strlcpy(tmp, fcu_fans[fan].loc, 64);
c = tmp;
for (;;) {
e = strchr(c, ',');
if (e)
*e = 0;
if (strcmp(loc, c) == 0)
return 1;
if (e == NULL)
break;
c = e + 1;
}
return 0;
}
static void fcu_lookup_fans(struct device_node *fcu_node)
{
struct device_node *np = NULL;
int i;
/* The table is filled by default with values that are suitable
* for the old machines without device-tree informations. We scan
* the device-tree and override those values with whatever is
* there
*/
DBG("Looking up FCU controls in device-tree...\n");
while ((np = of_get_next_child(fcu_node, np)) != NULL) {
int type = -1;
const char *loc;
const u32 *reg;
DBG(" control: %s, type: %s\n", np->name, np->type);
/* Detect control type */
if (!strcmp(np->type, "fan-rpm-control") ||
!strcmp(np->type, "fan-rpm"))
type = FCU_FAN_RPM;
if (!strcmp(np->type, "fan-pwm-control") ||
!strcmp(np->type, "fan-pwm"))
type = FCU_FAN_PWM;
/* Only care about fans for now */
if (type == -1)
continue;
/* Lookup for a matching location */
loc = of_get_property(np, "location", NULL);
reg = of_get_property(np, "reg", NULL);
if (loc == NULL || reg == NULL)
continue;
DBG(" matching location: %s, reg: 0x%08x\n", loc, *reg);
for (i = 0; i < FCU_FAN_COUNT; i++) {
int fan_id;
if (!fan_check_loc_match(loc, i))
continue;
DBG(" location match, index: %d\n", i);
fcu_fans[i].id = FCU_FAN_ABSENT_ID;
if (type != fcu_fans[i].type) {
printk(KERN_WARNING "therm_pm72: Fan type mismatch "
"in device-tree for %s\n", np->full_name);
break;
}
if (type == FCU_FAN_RPM)
fan_id = ((*reg) - 0x10) / 2;
else
fan_id = ((*reg) - 0x30) / 2;
if (fan_id > 7) {
printk(KERN_WARNING "therm_pm72: Can't parse "
"fan ID in device-tree for %s\n", np->full_name);
break;
}
DBG(" fan id -> %d, type -> %d\n", fan_id, type);
fcu_fans[i].id = fan_id;
}
}
/* Now dump the array */
printk(KERN_INFO "Detected fan controls:\n");
for (i = 0; i < FCU_FAN_COUNT; i++) {
if (fcu_fans[i].id == FCU_FAN_ABSENT_ID)
continue;
printk(KERN_INFO " %d: %s fan, id %d, location: %s\n", i,
fcu_fans[i].type == FCU_FAN_RPM ? "RPM" : "PWM",
fcu_fans[i].id, fcu_fans[i].loc);
}
}
static int fcu_of_probe(struct platform_device* dev)
{
state = state_detached;
of_dev = dev;
dev_info(&dev->dev, "PowerMac G5 Thermal control driver %s\n", VERSION);
/* Lookup the fans in the device tree */
fcu_lookup_fans(dev->dev.of_node);
/* Add the driver */
return i2c_add_driver(&therm_pm72_driver);
}
static int fcu_of_remove(struct platform_device* dev)
{
i2c_del_driver(&therm_pm72_driver);
return 0;
}
static const struct of_device_id fcu_match[] =
{
{
.type = "fcu",
},
{},
};
MODULE_DEVICE_TABLE(of, fcu_match);
static struct platform_driver fcu_of_platform_driver =
{
.driver = {
.name = "temperature",
.owner = THIS_MODULE,
.of_match_table = fcu_match,
},
.probe = fcu_of_probe,
.remove = fcu_of_remove
};
/*
* Check machine type, attach to i2c controller
*/
static int __init therm_pm72_init(void)
{
rackmac = of_machine_is_compatible("RackMac3,1");
if (!of_machine_is_compatible("PowerMac7,2") &&
!of_machine_is_compatible("PowerMac7,3") &&
!rackmac)
return -ENODEV;
return platform_driver_register(&fcu_of_platform_driver);
}
static void __exit therm_pm72_exit(void)
{
platform_driver_unregister(&fcu_of_platform_driver);
}
module_init(therm_pm72_init);
module_exit(therm_pm72_exit);
MODULE_AUTHOR("Benjamin Herrenschmidt <benh@kernel.crashing.org>");
MODULE_DESCRIPTION("Driver for Apple's PowerMac G5 thermal control");
MODULE_LICENSE("GPL");
| gpl-2.0 |
n-l-v/android_kernel_htc_totemc2 | drivers/media/video/uvc/uvc_isight.c | 9762 | 3903 | /*
* uvc_isight.c -- USB Video Class driver - iSight support
*
* Copyright (C) 2006-2007
* Ivan N. Zlatev <contact@i-nz.net>
* Copyright (C) 2008-2009
* Laurent Pinchart <laurent.pinchart@ideasonboard.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/usb.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include "uvcvideo.h"
/* Built-in iSight webcams implements most of UVC 1.0 except a
* different packet format. Instead of sending a header at the
* beginning of each isochronous transfer payload, the webcam sends a
* single header per image (on its own in a packet), followed by
* packets containing data only.
*
* Offset Size (bytes) Description
* ------------------------------------------------------------------
* 0x00 1 Header length
* 0x01 1 Flags (UVC-compliant)
* 0x02 4 Always equal to '11223344'
* 0x06 8 Always equal to 'deadbeefdeadface'
* 0x0e 16 Unknown
*
* The header can be prefixed by an optional, unknown-purpose byte.
*/
static int isight_decode(struct uvc_video_queue *queue, struct uvc_buffer *buf,
const __u8 *data, unsigned int len)
{
static const __u8 hdr[] = {
0x11, 0x22, 0x33, 0x44,
0xde, 0xad, 0xbe, 0xef,
0xde, 0xad, 0xfa, 0xce
};
unsigned int maxlen, nbytes;
__u8 *mem;
int is_header = 0;
if (buf == NULL)
return 0;
if ((len >= 14 && memcmp(&data[2], hdr, 12) == 0) ||
(len >= 15 && memcmp(&data[3], hdr, 12) == 0)) {
uvc_trace(UVC_TRACE_FRAME, "iSight header found\n");
is_header = 1;
}
/* Synchronize to the input stream by waiting for a header packet. */
if (buf->state != UVC_BUF_STATE_ACTIVE) {
if (!is_header) {
uvc_trace(UVC_TRACE_FRAME, "Dropping packet (out of "
"sync).\n");
return 0;
}
buf->state = UVC_BUF_STATE_ACTIVE;
}
/* Mark the buffer as done if we're at the beginning of a new frame.
*
* Empty buffers (bytesused == 0) don't trigger end of frame detection
* as it doesn't make sense to return an empty buffer.
*/
if (is_header && buf->bytesused != 0) {
buf->state = UVC_BUF_STATE_DONE;
return -EAGAIN;
}
/* Copy the video data to the buffer. Skip header packets, as they
* contain no data.
*/
if (!is_header) {
maxlen = buf->length - buf->bytesused;
mem = buf->mem + buf->bytesused;
nbytes = min(len, maxlen);
memcpy(mem, data, nbytes);
buf->bytesused += nbytes;
if (len > maxlen || buf->bytesused == buf->length) {
uvc_trace(UVC_TRACE_FRAME, "Frame complete "
"(overflow).\n");
buf->state = UVC_BUF_STATE_DONE;
}
}
return 0;
}
void uvc_video_decode_isight(struct urb *urb, struct uvc_streaming *stream,
struct uvc_buffer *buf)
{
int ret, i;
for (i = 0; i < urb->number_of_packets; ++i) {
if (urb->iso_frame_desc[i].status < 0) {
uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
"lost (%d).\n",
urb->iso_frame_desc[i].status);
}
/* Decode the payload packet.
* uvc_video_decode is entered twice when a frame transition
* has been detected because the end of frame can only be
* reliably detected when the first packet of the new frame
* is processed. The first pass detects the transition and
* closes the previous frame's buffer, the second pass
* processes the data of the first payload of the new frame.
*/
do {
ret = isight_decode(&stream->queue, buf,
urb->transfer_buffer +
urb->iso_frame_desc[i].offset,
urb->iso_frame_desc[i].actual_length);
if (buf == NULL)
break;
if (buf->state == UVC_BUF_STATE_DONE ||
buf->state == UVC_BUF_STATE_ERROR)
buf = uvc_queue_next_buffer(&stream->queue,
buf);
} while (ret == -EAGAIN);
}
}
| gpl-2.0 |
zeroblade1984/LG_MSM8974 | kernel/exec_domain.c | 10530 | 4393 | /*
* Handling of different ABIs (personalities).
*
* We group personalities into execution domains which have their
* own handlers for kernel entry points, signal mapping, etc...
*
* 2001-05-06 Complete rewrite, Christoph Hellwig (hch@infradead.org)
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kmod.h>
#include <linux/module.h>
#include <linux/personality.h>
#include <linux/proc_fs.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/syscalls.h>
#include <linux/sysctl.h>
#include <linux/types.h>
#include <linux/fs_struct.h>
static void default_handler(int, struct pt_regs *);
static struct exec_domain *exec_domains = &default_exec_domain;
static DEFINE_RWLOCK(exec_domains_lock);
static unsigned long ident_map[32] = {
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31
};
struct exec_domain default_exec_domain = {
.name = "Linux", /* name */
.handler = default_handler, /* lcall7 causes a seg fault. */
.pers_low = 0, /* PER_LINUX personality. */
.pers_high = 0, /* PER_LINUX personality. */
.signal_map = ident_map, /* Identity map signals. */
.signal_invmap = ident_map, /* - both ways. */
};
static void
default_handler(int segment, struct pt_regs *regp)
{
set_personality(0);
if (current_thread_info()->exec_domain->handler != default_handler)
current_thread_info()->exec_domain->handler(segment, regp);
else
send_sig(SIGSEGV, current, 1);
}
static struct exec_domain *
lookup_exec_domain(unsigned int personality)
{
unsigned int pers = personality(personality);
struct exec_domain *ep;
read_lock(&exec_domains_lock);
for (ep = exec_domains; ep; ep = ep->next) {
if (pers >= ep->pers_low && pers <= ep->pers_high)
if (try_module_get(ep->module))
goto out;
}
#ifdef CONFIG_MODULES
read_unlock(&exec_domains_lock);
request_module("personality-%d", pers);
read_lock(&exec_domains_lock);
for (ep = exec_domains; ep; ep = ep->next) {
if (pers >= ep->pers_low && pers <= ep->pers_high)
if (try_module_get(ep->module))
goto out;
}
#endif
ep = &default_exec_domain;
out:
read_unlock(&exec_domains_lock);
return (ep);
}
int
register_exec_domain(struct exec_domain *ep)
{
struct exec_domain *tmp;
int err = -EBUSY;
if (ep == NULL)
return -EINVAL;
if (ep->next != NULL)
return -EBUSY;
write_lock(&exec_domains_lock);
for (tmp = exec_domains; tmp; tmp = tmp->next) {
if (tmp == ep)
goto out;
}
ep->next = exec_domains;
exec_domains = ep;
err = 0;
out:
write_unlock(&exec_domains_lock);
return (err);
}
int
unregister_exec_domain(struct exec_domain *ep)
{
struct exec_domain **epp;
epp = &exec_domains;
write_lock(&exec_domains_lock);
for (epp = &exec_domains; *epp; epp = &(*epp)->next) {
if (ep == *epp)
goto unregister;
}
write_unlock(&exec_domains_lock);
return -EINVAL;
unregister:
*epp = ep->next;
ep->next = NULL;
write_unlock(&exec_domains_lock);
return 0;
}
int __set_personality(unsigned int personality)
{
struct exec_domain *oep = current_thread_info()->exec_domain;
current_thread_info()->exec_domain = lookup_exec_domain(personality);
current->personality = personality;
module_put(oep->module);
return 0;
}
#ifdef CONFIG_PROC_FS
static int execdomains_proc_show(struct seq_file *m, void *v)
{
struct exec_domain *ep;
read_lock(&exec_domains_lock);
for (ep = exec_domains; ep; ep = ep->next)
seq_printf(m, "%d-%d\t%-16s\t[%s]\n",
ep->pers_low, ep->pers_high, ep->name,
module_name(ep->module));
read_unlock(&exec_domains_lock);
return 0;
}
static int execdomains_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, execdomains_proc_show, NULL);
}
static const struct file_operations execdomains_proc_fops = {
.open = execdomains_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __init proc_execdomains_init(void)
{
proc_create("execdomains", 0, NULL, &execdomains_proc_fops);
return 0;
}
module_init(proc_execdomains_init);
#endif
SYSCALL_DEFINE1(personality, unsigned int, personality)
{
unsigned int old = current->personality;
if (personality != 0xffffffff)
set_personality(personality);
return old;
}
EXPORT_SYMBOL(register_exec_domain);
EXPORT_SYMBOL(unregister_exec_domain);
EXPORT_SYMBOL(__set_personality);
| gpl-2.0 |
paprikon/android_kernel_htc_bliss | fs/ramfs/file-mmu.c | 11554 | 1537 | /* file-mmu.c: ramfs MMU-based file operations
*
* Resizable simple ram filesystem for Linux.
*
* Copyright (C) 2000 Linus Torvalds.
* 2000 Transmeta Corp.
*
* Usage limits added by David Gibson, Linuxcare Australia.
* This file is released under the GPL.
*/
/*
* NOTE! This filesystem is probably most useful
* not as a real filesystem, but as an example of
* how virtual filesystems can be written.
*
* It doesn't get much simpler than this. Consider
* that this file implements the full semantics of
* a POSIX-compliant read-write filesystem.
*
* Note in particular how the filesystem does not
* need to implement any data structures of its own
* to keep track of the virtual data: using the VFS
* caches is sufficient.
*/
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/ramfs.h>
#include "internal.h"
const struct address_space_operations ramfs_aops = {
.readpage = simple_readpage,
.write_begin = simple_write_begin,
.write_end = simple_write_end,
.set_page_dirty = __set_page_dirty_no_writeback,
};
const struct file_operations ramfs_file_operations = {
.read = do_sync_read,
.aio_read = generic_file_aio_read,
.write = do_sync_write,
.aio_write = generic_file_aio_write,
.mmap = generic_file_mmap,
.fsync = noop_fsync,
.splice_read = generic_file_splice_read,
.splice_write = generic_file_splice_write,
.llseek = generic_file_llseek,
};
const struct inode_operations ramfs_file_inode_operations = {
.setattr = simple_setattr,
.getattr = simple_getattr,
};
| gpl-2.0 |
SlimSaber/android_kernel_oppo_msm8974 | net/irda/ircomm/ircomm_event.c | 12322 | 7085 | /*********************************************************************
*
* Filename: ircomm_event.c
* Version: 1.0
* Description: IrCOMM layer state machine
* Status: Stable
* Author: Dag Brattli <dagb@cs.uit.no>
* Created at: Sun Jun 6 20:33:11 1999
* Modified at: Sun Dec 12 13:44:32 1999
* Modified by: Dag Brattli <dagb@cs.uit.no>
*
* Copyright (c) 1999 Dag Brattli, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
********************************************************************/
#include <linux/proc_fs.h>
#include <linux/init.h>
#include <net/irda/irda.h>
#include <net/irda/irlmp.h>
#include <net/irda/iriap.h>
#include <net/irda/irttp.h>
#include <net/irda/irias_object.h>
#include <net/irda/ircomm_core.h>
#include <net/irda/ircomm_event.h>
static int ircomm_state_idle(struct ircomm_cb *self, IRCOMM_EVENT event,
struct sk_buff *skb, struct ircomm_info *info);
static int ircomm_state_waiti(struct ircomm_cb *self, IRCOMM_EVENT event,
struct sk_buff *skb, struct ircomm_info *info);
static int ircomm_state_waitr(struct ircomm_cb *self, IRCOMM_EVENT event,
struct sk_buff *skb, struct ircomm_info *info);
static int ircomm_state_conn(struct ircomm_cb *self, IRCOMM_EVENT event,
struct sk_buff *skb, struct ircomm_info *info);
const char *const ircomm_state[] = {
"IRCOMM_IDLE",
"IRCOMM_WAITI",
"IRCOMM_WAITR",
"IRCOMM_CONN",
};
#ifdef CONFIG_IRDA_DEBUG
static const char *const ircomm_event[] = {
"IRCOMM_CONNECT_REQUEST",
"IRCOMM_CONNECT_RESPONSE",
"IRCOMM_TTP_CONNECT_INDICATION",
"IRCOMM_LMP_CONNECT_INDICATION",
"IRCOMM_TTP_CONNECT_CONFIRM",
"IRCOMM_LMP_CONNECT_CONFIRM",
"IRCOMM_LMP_DISCONNECT_INDICATION",
"IRCOMM_TTP_DISCONNECT_INDICATION",
"IRCOMM_DISCONNECT_REQUEST",
"IRCOMM_TTP_DATA_INDICATION",
"IRCOMM_LMP_DATA_INDICATION",
"IRCOMM_DATA_REQUEST",
"IRCOMM_CONTROL_REQUEST",
"IRCOMM_CONTROL_INDICATION",
};
#endif /* CONFIG_IRDA_DEBUG */
static int (*state[])(struct ircomm_cb *self, IRCOMM_EVENT event,
struct sk_buff *skb, struct ircomm_info *info) =
{
ircomm_state_idle,
ircomm_state_waiti,
ircomm_state_waitr,
ircomm_state_conn,
};
/*
* Function ircomm_state_idle (self, event, skb)
*
* IrCOMM is currently idle
*
*/
static int ircomm_state_idle(struct ircomm_cb *self, IRCOMM_EVENT event,
struct sk_buff *skb, struct ircomm_info *info)
{
int ret = 0;
switch (event) {
case IRCOMM_CONNECT_REQUEST:
ircomm_next_state(self, IRCOMM_WAITI);
ret = self->issue.connect_request(self, skb, info);
break;
case IRCOMM_TTP_CONNECT_INDICATION:
case IRCOMM_LMP_CONNECT_INDICATION:
ircomm_next_state(self, IRCOMM_WAITR);
ircomm_connect_indication(self, skb, info);
break;
default:
IRDA_DEBUG(4, "%s(), unknown event: %s\n", __func__ ,
ircomm_event[event]);
ret = -EINVAL;
}
return ret;
}
/*
* Function ircomm_state_waiti (self, event, skb)
*
* The IrCOMM user has requested an IrCOMM connection to the remote
* device and is awaiting confirmation
*/
static int ircomm_state_waiti(struct ircomm_cb *self, IRCOMM_EVENT event,
struct sk_buff *skb, struct ircomm_info *info)
{
int ret = 0;
switch (event) {
case IRCOMM_TTP_CONNECT_CONFIRM:
case IRCOMM_LMP_CONNECT_CONFIRM:
ircomm_next_state(self, IRCOMM_CONN);
ircomm_connect_confirm(self, skb, info);
break;
case IRCOMM_TTP_DISCONNECT_INDICATION:
case IRCOMM_LMP_DISCONNECT_INDICATION:
ircomm_next_state(self, IRCOMM_IDLE);
ircomm_disconnect_indication(self, skb, info);
break;
default:
IRDA_DEBUG(0, "%s(), unknown event: %s\n", __func__ ,
ircomm_event[event]);
ret = -EINVAL;
}
return ret;
}
/*
* Function ircomm_state_waitr (self, event, skb)
*
* IrCOMM has received an incoming connection request and is awaiting
* response from the user
*/
static int ircomm_state_waitr(struct ircomm_cb *self, IRCOMM_EVENT event,
struct sk_buff *skb, struct ircomm_info *info)
{
int ret = 0;
switch (event) {
case IRCOMM_CONNECT_RESPONSE:
ircomm_next_state(self, IRCOMM_CONN);
ret = self->issue.connect_response(self, skb);
break;
case IRCOMM_DISCONNECT_REQUEST:
ircomm_next_state(self, IRCOMM_IDLE);
ret = self->issue.disconnect_request(self, skb, info);
break;
case IRCOMM_TTP_DISCONNECT_INDICATION:
case IRCOMM_LMP_DISCONNECT_INDICATION:
ircomm_next_state(self, IRCOMM_IDLE);
ircomm_disconnect_indication(self, skb, info);
break;
default:
IRDA_DEBUG(0, "%s(), unknown event = %s\n", __func__ ,
ircomm_event[event]);
ret = -EINVAL;
}
return ret;
}
/*
* Function ircomm_state_conn (self, event, skb)
*
* IrCOMM is connected to the peer IrCOMM device
*
*/
static int ircomm_state_conn(struct ircomm_cb *self, IRCOMM_EVENT event,
struct sk_buff *skb, struct ircomm_info *info)
{
int ret = 0;
switch (event) {
case IRCOMM_DATA_REQUEST:
ret = self->issue.data_request(self, skb, 0);
break;
case IRCOMM_TTP_DATA_INDICATION:
ircomm_process_data(self, skb);
break;
case IRCOMM_LMP_DATA_INDICATION:
ircomm_data_indication(self, skb);
break;
case IRCOMM_CONTROL_REQUEST:
/* Just send a separate frame for now */
ret = self->issue.data_request(self, skb, skb->len);
break;
case IRCOMM_TTP_DISCONNECT_INDICATION:
case IRCOMM_LMP_DISCONNECT_INDICATION:
ircomm_next_state(self, IRCOMM_IDLE);
ircomm_disconnect_indication(self, skb, info);
break;
case IRCOMM_DISCONNECT_REQUEST:
ircomm_next_state(self, IRCOMM_IDLE);
ret = self->issue.disconnect_request(self, skb, info);
break;
default:
IRDA_DEBUG(0, "%s(), unknown event = %s\n", __func__ ,
ircomm_event[event]);
ret = -EINVAL;
}
return ret;
}
/*
* Function ircomm_do_event (self, event, skb)
*
* Process event
*
*/
int ircomm_do_event(struct ircomm_cb *self, IRCOMM_EVENT event,
struct sk_buff *skb, struct ircomm_info *info)
{
IRDA_DEBUG(4, "%s: state=%s, event=%s\n", __func__ ,
ircomm_state[self->state], ircomm_event[event]);
return (*state[self->state])(self, event, skb, info);
}
/*
* Function ircomm_next_state (self, state)
*
* Switch state
*
*/
void ircomm_next_state(struct ircomm_cb *self, IRCOMM_STATE state)
{
self->state = state;
IRDA_DEBUG(4, "%s: next state=%s, service type=%d\n", __func__ ,
ircomm_state[self->state], self->service_type);
}
| gpl-2.0 |
xinchoubiology/gcc | gcc/config/sparc/sparc-c.c | 35 | 1634 | /* Subroutines used for macro/preprocessor support on SPARC.
Copyright (C) 2011-2014 Free Software Foundation, Inc.
This file is part of GCC.
GCC 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, or (at your option)
any later version.
GCC 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 GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "tree.h"
#include "tm_p.h"
#include "flags.h"
#include "c-family/c-common.h"
#include "c-family/c-pragma.h"
#include "cpplib.h"
void
sparc_target_macros (void)
{
builtin_define_std ("sparc");
if (TARGET_64BIT)
{
cpp_assert (parse_in, "cpu=sparc64");
cpp_assert (parse_in, "machine=sparc64");
}
else
{
cpp_assert (parse_in, "cpu=sparc");
cpp_assert (parse_in, "machine=sparc");
}
if (TARGET_VIS3)
{
cpp_define (parse_in, "__VIS__=0x300");
cpp_define (parse_in, "__VIS=0x300");
}
else if (TARGET_VIS2)
{
cpp_define (parse_in, "__VIS__=0x200");
cpp_define (parse_in, "__VIS=0x200");
}
else if (TARGET_VIS)
{
cpp_define (parse_in, "__VIS__=0x100");
cpp_define (parse_in, "__VIS=0x100");
}
}
| gpl-2.0 |
CyanogenMod/android_kernel_motorola_msm8960dt-common | drivers/video/msm/mipi_mot_notifications.c | 35 | 1302 | /* Copyright (c) 2013, Motorola Mobility, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 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 "mipi_mot.h"
int mmi_panel_register_notifier(struct notifier_block *nb)
{
struct mipi_mot_panel *mot_panel = mipi_mot_get_mot_panel();
return srcu_notifier_chain_register(
&mot_panel->panel_notifier_list, nb);
}
int mmi_panel_unregister_notifier(struct notifier_block *nb)
{
struct mipi_mot_panel *mot_panel = mipi_mot_get_mot_panel();
return srcu_notifier_chain_unregister(
&mot_panel->panel_notifier_list, nb);
}
void mmi_panel_notify(unsigned int state, void *data)
{
struct mipi_mot_panel *mot_panel = mipi_mot_get_mot_panel();
pr_debug("%s (%d) is called\n", __func__, state);
if (!mot_panel->mfd->quickdraw_in_progress)
srcu_notifier_call_chain(&mot_panel->panel_notifier_list, state,
data);
else
pr_debug("%s: skip notifications!\n", __func__);
}
| gpl-2.0 |
rascalmicro/u-boot-rascal | board/esd/voh405/voh405.c | 35 | 10888 | /*
* (C) Copyright 2001-2004
* Stefan Roese, esd gmbh germany, stefan.roese@esd-electronics.com
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <asm/io.h>
#include <asm/processor.h>
#include <command.h>
#include <malloc.h>
/* ------------------------------------------------------------------------- */
#if 0
#define FPGA_DEBUG
#endif
extern int do_reset (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]);
extern void lxt971_no_sleep(void);
/* fpga configuration data - gzip compressed and generated by bin2c */
const unsigned char fpgadata[] =
{
#include "fpgadata.c"
};
/*
* include common fpga code (for esd boards)
*/
#include "../common/fpga.c"
/* logo bitmap data - gzip compressed and generated by bin2c */
unsigned char logo_bmp_320[] =
{
#include "logo_320_240_4bpp.c"
};
unsigned char logo_bmp_640[] =
{
#include "logo_640_480_24bpp.c"
};
/*
* include common lcd code (for esd boards)
*/
#include "../common/lcd.c"
#include "../common/s1d13704_320_240_4bpp.h"
#include "../common/s1d13806_320_240_4bpp.h"
#include "../common/s1d13806_640_480_16bpp.h"
int board_early_init_f (void)
{
/*
* IRQ 0-15 405GP internally generated; active high; level sensitive
* IRQ 16 405GP internally generated; active low; level sensitive
* IRQ 17-24 RESERVED
* IRQ 25 (EXT IRQ 0) CAN0; active low; level sensitive
* IRQ 26 (EXT IRQ 1) SER0 ; active low; level sensitive
* IRQ 27 (EXT IRQ 2) SER1; active low; level sensitive
* IRQ 28 (EXT IRQ 3) FPGA 0; active low; level sensitive
* IRQ 29 (EXT IRQ 4) FPGA 1; active low; level sensitive
* IRQ 30 (EXT IRQ 5) PCI INTA; active low; level sensitive
* IRQ 31 (EXT IRQ 6) COMPACT FLASH; active high; level sensitive
*/
mtdcr(UIC0SR, 0xFFFFFFFF); /* clear all ints */
mtdcr(UIC0ER, 0x00000000); /* disable all ints */
mtdcr(UIC0CR, 0x00000000); /* set all to be non-critical*/
mtdcr(UIC0PR, 0xFFFFFFB5); /* set int polarities */
mtdcr(UIC0TR, 0x10000000); /* set int trigger levels */
mtdcr(UIC0VCR, 0x00000001); /* set vect base=0,INT0 highest priority*/
mtdcr(UIC0SR, 0xFFFFFFFF); /* clear all ints */
/*
* EBC Configuration Register: set ready timeout to 512 ebc-clks -> ca. 15 us
*/
mtebc (EBC0_CFG, 0xa8400000); /* ebc always driven */
return 0;
}
int misc_init_r (void)
{
unsigned char *duart0_mcr = (unsigned char *)((ulong)DUART0_BA + 4);
unsigned char *duart1_mcr = (unsigned char *)((ulong)DUART1_BA + 4);
unsigned short *lcd_contrast =
(unsigned short *)((ulong)CONFIG_SYS_FPGA_BASE_ADDR + CONFIG_SYS_FPGA_CTRL + 4);
unsigned short *lcd_backlight =
(unsigned short *)((ulong)CONFIG_SYS_FPGA_BASE_ADDR + CONFIG_SYS_FPGA_CTRL + 6);
unsigned char *dst;
ulong len = sizeof(fpgadata);
int status;
int index;
int i;
char *str;
dst = malloc(CONFIG_SYS_FPGA_MAX_SIZE);
if (gunzip (dst, CONFIG_SYS_FPGA_MAX_SIZE, (uchar *)fpgadata, &len) != 0) {
printf ("GUNZIP ERROR - must RESET board to recover\n");
do_reset (NULL, 0, 0, NULL);
}
status = fpga_boot(dst, len);
if (status != 0) {
printf("\nFPGA: Booting failed ");
switch (status) {
case ERROR_FPGA_PRG_INIT_LOW:
printf("(Timeout: INIT not low after asserting PROGRAM*)\n ");
break;
case ERROR_FPGA_PRG_INIT_HIGH:
printf("(Timeout: INIT not high after deasserting PROGRAM*)\n ");
break;
case ERROR_FPGA_PRG_DONE:
printf("(Timeout: DONE not high after programming FPGA)\n ");
break;
}
/* display infos on fpgaimage */
index = 15;
for (i=0; i<4; i++) {
len = dst[index];
printf("FPGA: %s\n", &(dst[index+1]));
index += len+3;
}
putc ('\n');
/* delayed reboot */
for (i=20; i>0; i--) {
printf("Rebooting in %2d seconds \r",i);
for (index=0;index<1000;index++)
udelay(1000);
}
putc ('\n');
do_reset(NULL, 0, 0, NULL);
}
puts("FPGA: ");
/* display infos on fpgaimage */
index = 15;
for (i=0; i<4; i++) {
len = dst[index];
printf("%s ", &(dst[index+1]));
index += len+3;
}
putc ('\n');
free(dst);
/*
* Reset FPGA via FPGA_INIT pin
*/
out_be32((void*)GPIO0_TCR, in_be32((void*)GPIO0_TCR) | FPGA_INIT); /* setup FPGA_INIT as output */
out_be32((void*)GPIO0_OR, in_be32((void*)GPIO0_OR) & ~FPGA_INIT); /* reset low */
udelay(1000); /* wait 1ms */
out_be32((void*)GPIO0_OR, in_be32((void*)GPIO0_OR) | FPGA_INIT); /* reset high */
udelay(1000); /* wait 1ms */
/*
* Reset external DUARTs
*/
out_be32((void*)GPIO0_OR, in_be32((void*)GPIO0_OR) | CONFIG_SYS_DUART_RST); /* set reset to high */
udelay(10); /* wait 10us */
out_be32((void*)GPIO0_OR, in_be32((void*)GPIO0_OR) & ~CONFIG_SYS_DUART_RST); /* set reset to low */
udelay(1000); /* wait 1ms */
/*
* Set NAND-FLASH GPIO signals to default
*/
out_be32((void*)GPIO0_OR, in_be32((void*)GPIO0_OR) & ~(CONFIG_SYS_NAND_CLE | CONFIG_SYS_NAND_ALE));
out_be32((void*)GPIO0_OR, in_be32((void*)GPIO0_OR) | CONFIG_SYS_NAND_CE);
/*
* Setup EEPROM write protection
*/
out_be32((void*)GPIO0_OR, in_be32((void*)GPIO0_OR) | CONFIG_SYS_EEPROM_WP);
out_be32((void*)GPIO0_TCR, in_be32((void*)GPIO0_TCR) | CONFIG_SYS_EEPROM_WP);
/*
* Enable interrupts in exar duart mcr[3]
*/
out_8(duart0_mcr, 0x08);
out_8(duart1_mcr, 0x08);
/*
* Init lcd interface and display logo
*/
str = getenv("bd_type");
if (strcmp(str, "voh405_bw") == 0) {
lcd_setup(0, 1);
lcd_init((uchar *)CONFIG_SYS_LCD_SMALL_REG, (uchar *)CONFIG_SYS_LCD_SMALL_MEM,
regs_13704_320_240_4bpp,
sizeof(regs_13704_320_240_4bpp)/sizeof(regs_13704_320_240_4bpp[0]),
logo_bmp_320, sizeof(logo_bmp_320));
} else if (strcmp(str, "voh405_bwbw") == 0) {
lcd_setup(0, 1);
lcd_init((uchar *)CONFIG_SYS_LCD_SMALL_REG, (uchar *)CONFIG_SYS_LCD_SMALL_MEM,
regs_13704_320_240_4bpp,
sizeof(regs_13704_320_240_4bpp)/sizeof(regs_13704_320_240_4bpp[0]),
logo_bmp_320, sizeof(logo_bmp_320));
lcd_setup(1, 1);
lcd_init((uchar *)CONFIG_SYS_LCD_BIG_REG, (uchar *)CONFIG_SYS_LCD_BIG_MEM,
regs_13806_320_240_4bpp,
sizeof(regs_13806_320_240_4bpp)/sizeof(regs_13806_320_240_4bpp[0]),
logo_bmp_320, sizeof(logo_bmp_320));
} else if (strcmp(str, "voh405_bwc") == 0) {
lcd_setup(0, 1);
lcd_init((uchar *)CONFIG_SYS_LCD_SMALL_REG, (uchar *)CONFIG_SYS_LCD_SMALL_MEM,
regs_13704_320_240_4bpp,
sizeof(regs_13704_320_240_4bpp)/sizeof(regs_13704_320_240_4bpp[0]),
logo_bmp_320, sizeof(logo_bmp_320));
lcd_setup(1, 0);
lcd_init((uchar *)CONFIG_SYS_LCD_BIG_REG, (uchar *)CONFIG_SYS_LCD_BIG_MEM,
regs_13806_640_480_16bpp,
sizeof(regs_13806_640_480_16bpp)/sizeof(regs_13806_640_480_16bpp[0]),
logo_bmp_640, sizeof(logo_bmp_640));
} else {
printf("Unsupported bd_type defined (%s) -> No display configured!\n", str);
return 0;
}
/*
* Set invert bit in small lcd controller
*/
out_8((unsigned char *)(CONFIG_SYS_LCD_SMALL_REG + 2),
in_8((unsigned char *)(CONFIG_SYS_LCD_SMALL_REG + 2)) | 0x01);
/*
* Set default contrast voltage on epson vga controller
*/
out_be16(lcd_contrast, 0x4646);
/*
* Enable backlight
*/
out_be16(lcd_backlight, 0xffff);
/*
* Enable external I2C bus
*/
out_be32((void*)GPIO0_TCR, in_be32((void*)GPIO0_TCR) | CONFIG_SYS_IIC_ON);
return (0);
}
/*
* Check Board Identity:
*/
int checkboard (void)
{
char str[64];
int i = getenv_f("serial#", str, sizeof(str));
puts ("Board: ");
if (i == -1) {
puts ("### No HW ID - assuming VOH405");
} else {
puts(str);
}
if (getenv_f("bd_type", str, sizeof(str)) != -1) {
printf(" (%s)", str);
} else {
puts(" (Missing bd_type!)");
}
putc ('\n');
return 0;
}
#ifdef CONFIG_IDE_RESET
#define FPGA_MODE (CONFIG_SYS_FPGA_BASE_ADDR + CONFIG_SYS_FPGA_CTRL)
void ide_set_reset(int on)
{
/*
* Assert or deassert CompactFlash Reset Pin
*/
if (on) { /* assert RESET */
out_be16((void *)FPGA_MODE,
in_be16((void *)FPGA_MODE) & ~CONFIG_SYS_FPGA_CTRL_CF_RESET);
} else { /* release RESET */
out_be16((void *)FPGA_MODE,
in_be16((void *)FPGA_MODE) | CONFIG_SYS_FPGA_CTRL_CF_RESET);
}
}
#endif /* CONFIG_IDE_RESET */
#if defined(CONFIG_RESET_PHY_R)
void reset_phy(void)
{
#ifdef CONFIG_LXT971_NO_SLEEP
/*
* Disable sleep mode in LXT971
*/
lxt971_no_sleep();
#endif
}
#endif
#if defined(CONFIG_SYS_EEPROM_WREN)
/* Input: <dev_addr> I2C address of EEPROM device to enable.
* <state> -1: deliver current state
* 0: disable write
* 1: enable write
* Returns: -1: wrong device address
* 0: dis-/en- able done
* 0/1: current state if <state> was -1.
*/
int eeprom_write_enable (unsigned dev_addr, int state)
{
if (CONFIG_SYS_I2C_EEPROM_ADDR != dev_addr) {
return -1;
} else {
switch (state) {
case 1:
/* Enable write access, clear bit GPIO0. */
out_be32((void*)GPIO0_OR, in_be32((void*)GPIO0_OR) & ~CONFIG_SYS_EEPROM_WP);
state = 0;
break;
case 0:
/* Disable write access, set bit GPIO0. */
out_be32((void*)GPIO0_OR, in_be32((void*)GPIO0_OR) | CONFIG_SYS_EEPROM_WP);
state = 0;
break;
default:
/* Read current status back. */
state = (0 == (in_be32((void*)GPIO0_OR) & CONFIG_SYS_EEPROM_WP));
break;
}
}
return state;
}
int do_eep_wren (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int query = argc == 1;
int state = 0;
if (query) {
/* Query write access state. */
state = eeprom_write_enable (CONFIG_SYS_I2C_EEPROM_ADDR, -1);
if (state < 0) {
puts ("Query of write access state failed.\n");
} else {
printf ("Write access for device 0x%0x is %sabled.\n",
CONFIG_SYS_I2C_EEPROM_ADDR, state ? "en" : "dis");
state = 0;
}
} else {
if ('0' == argv[1][0]) {
/* Disable write access. */
state = eeprom_write_enable (CONFIG_SYS_I2C_EEPROM_ADDR, 0);
} else {
/* Enable write access. */
state = eeprom_write_enable (CONFIG_SYS_I2C_EEPROM_ADDR, 1);
}
if (state < 0) {
puts ("Setup of write access state failed.\n");
}
}
return state;
}
U_BOOT_CMD(eepwren, 2, 0, do_eep_wren,
"Enable / disable / query EEPROM write access",
""
);
#endif /* #if defined(CONFIG_SYS_EEPROM_WREN) */
| gpl-2.0 |
rhcp011235/sgh-t989_kernel | drivers/video/samsung/mdnie.c | 35 | 25175 | /* linux/drivers/video/samsung/mdnie.c
*
* Register interface file for Samsung mDNIe driver
*
* Copyright (c) 2009 Samsung Electronics
* http://www.samsungsemi.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 <mach/gpio.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/mutex.h>
#include <linux/mm.h>
#include <linux/device.h>
#include <linux/backlight.h>
#include <linux/platform_device.h>
#include <linux/mdnie.h>
#ifdef CONFIG_HAS_EARLYSUSPEND
#include <linux/earlysuspend.h>
#endif
#include <linux/delay.h>
#include <linux/lcd.h>
#include <linux/rtc.h>
#include "s3cfb.h"
#include "s3cfb_mdnie.h"
#if defined(CONFIG_CPU_EXYNOS4210)
#if defined(CONFIG_FB_S5P_LD9040) || defined(CONFIG_FB_S5P_NT35560)
#include "mdnie_table_u1.h"
#elif defined(CONFIG_FB_S5P_S6E8AA0)
#include "mdnie_table_q1.h"
#elif defined(CONFIG_FB_S5P_S6E8AB0)
#include "mdnie_table_p8.h"
#elif defined(CONFIG_FB_S5P_S6F1202A)
#include "mdnie_table.h"
#include "mdnie_table_p2_boe.h"
#include "mdnie_table_p2_hydis.h"
#include "mdnie_table_p2_sec.h"
#elif defined(CONFIG_FB_S5P_S6C1372)
#include "mdnie_table_p4.h"
#endif
#include "mdnie_color_tone_4210.h"
#else /* CONFIG_CPU_EXYNOS4210 */
#if defined(CONFIG_FB_S5P_S6E8AA0)
#include "mdnie_table_c1m0.h"
#elif defined(CONFIG_FB_S5P_EA8061) || defined(CONFIG_FB_S5P_S6EVR02)
#include "mdnie_table_t0.h"
#elif defined(CONFIG_FB_S5P_S6E63M0)
#include "mdnie_table_c1m0.h"
#elif defined(CONFIG_FB_S5P_S6C1372)
#include "mdnie_table_p4note.h"
#elif defined(CONFIG_FB_S5P_S6D6AA1)
#include "mdnie_table_gc1.h"
#elif defined(CONFIG_FB_S5P_LMS501XX)
#include "mdnie_table_baffin.h"
#else
#include "mdnie_table_4412.h"
#endif
#include "mdnie_color_tone.h" /* sholud be added for 4212, 4412 */
#endif
#if defined(CONFIG_TDMB) || defined(CONFIG_TARGET_LOCALE_NTT)
#include "mdnie_dmb.h"
#endif
#if defined(CONFIG_FB_MDNIE_PWM)
#define MIN_BRIGHTNESS 0
#define DEFAULT_BRIGHTNESS 150
#if defined(CONFIG_FB_S5P_S6F1202A)
#define MAX_BACKLIGHT_VALUE 1424 /* 1504(94%) -> 1424(89%) */
#define MID_BACKLIGHT_VALUE 544 /* 784(49%) -> 544(34%) */
#define LOW_BACKLIGHT_VALUE 16
#define DIM_BACKLIGHT_VALUE 16
#define CABC_CUTOFF_BACKLIGHT_VALUE 40 /* 2.5% */
#elif defined(CONFIG_FB_S5P_S6C1372)
#define MAX_BACKLIGHT_VALUE 1441 /* 90% */
#define MID_BACKLIGHT_VALUE 784
#define LOW_BACKLIGHT_VALUE 16
#define DIM_BACKLIGHT_VALUE 16
#define CABC_CUTOFF_BACKLIGHT_VALUE 34
#endif
#define MAX_BRIGHTNESS_LEVEL 255
#define MID_BRIGHTNESS_LEVEL 150
#define LOW_BRIGHTNESS_LEVEL 30
#define DIM_BRIGHTNESS_LEVEL 20
#endif
#define SCENARIO_IS_COLOR(scenario) \
((scenario >= COLOR_TONE_1) && (scenario < COLOR_TONE_MAX))
#if defined(CONFIG_TDMB) || defined(CONFIG_TARGET_LOCALE_NTT)
#define SCENARIO_IS_DMB(scenario) \
((scenario >= DMB_NORMAL_MODE) && (scenario < DMB_MODE_MAX))
#define SCENARIO_IS_VALID(scenario) \
((SCENARIO_IS_COLOR(scenario)) || SCENARIO_IS_DMB(scenario) || \
(scenario < SCENARIO_MAX))
#else
#define SCENARIO_IS_VALID(scenario) \
((SCENARIO_IS_COLOR(scenario)) || (scenario < SCENARIO_MAX))
#endif
static char tuning_file_name[50];
struct class *mdnie_class;
struct mdnie_info *g_mdnie;
#ifdef CONFIG_MACH_P4NOTE
static struct mdnie_backlight_value b_value;
#endif
int mdnie_send_sequence(struct mdnie_info *mdnie, const unsigned short *seq)
{
int ret = 0, i = 0;
const unsigned short *wbuf;
if (IS_ERR_OR_NULL(seq)) {
dev_err(mdnie->dev, "mdnie sequence is null\n");
return -EPERM;
}
mutex_lock(&mdnie->dev_lock);
wbuf = seq;
s3c_mdnie_mask();
while (wbuf[i] != END_SEQ) {
mdnie_write(wbuf[i], wbuf[i+1]);
i += 2;
}
s3c_mdnie_unmask();
mutex_unlock(&mdnie->dev_lock);
return ret;
}
void set_mdnie_value(struct mdnie_info *mdnie, u8 force)
{
u8 idx;
if ((!mdnie->enable) && (!force)) {
dev_err(mdnie->dev, "mdnie states is off\n");
return;
}
if (mdnie->scenario == VIDEO_WARM_MODE)
mdnie->tone = TONE_WARM;
else if (mdnie->scenario == VIDEO_COLD_MODE)
mdnie->tone = TONE_COLD;
else
mdnie->tone = TONE_NORMAL;
if (mdnie->tunning) {
dev_info(mdnie->dev, "mdnie tunning mode is enabled\n");
return;
}
mutex_lock(&mdnie->lock);
if (mdnie->negative == NEGATIVE_ON) {
dev_info(mdnie->dev, "NEGATIVE_ON\n");
mdnie_send_sequence(mdnie, negative_table[mdnie->cabc].seq);
goto exit;
}
#if defined(CONFIG_TDMB) || defined(CONFIG_TARGET_LOCALE_NTT)
if (SCENARIO_IS_DMB(mdnie->scenario)) {
idx = mdnie->scenario - DMB_NORMAL_MODE;
mdnie->tone = idx;
mdnie_send_sequence(mdnie, tune_dmb[mdnie->mode].seq);
dev_info(mdnie->dev, "mode=%d, scenario=%d, outdoor=%d, cabc=%d, %s\n",
mdnie->mode, mdnie->scenario, mdnie->outdoor,
mdnie->cabc, tune_dmb[mdnie->mode].name);
goto etc;
}
#endif
if (SCENARIO_IS_COLOR(mdnie->scenario)) {
idx = mdnie->scenario - COLOR_TONE_1;
mdnie_send_sequence(mdnie, color_tone_table[idx].seq);
dev_info(mdnie->dev, "mode=%d, scenario=%d, outdoor=%d, cabc=%d, %s\n",
mdnie->mode, mdnie->scenario, mdnie->outdoor, mdnie->cabc,
color_tone_table[idx].name);
goto exit;
} else if (mdnie->scenario == CAMERA_MODE) {
mdnie_send_sequence(mdnie, camera_table[mdnie->outdoor].seq);
dev_info(mdnie->dev, "%s\n", camera_table[mdnie->outdoor].name);
goto exit;
} else {
mdnie_send_sequence(mdnie, tunning_table[mdnie->cabc][mdnie->mode][mdnie->scenario].seq);
dev_info(mdnie->dev, "mode=%d, scenario=%d, outdoor=%d, cabc=%d, %s\n",
mdnie->mode, mdnie->scenario, mdnie->outdoor, mdnie->cabc,
tunning_table[mdnie->cabc][mdnie->mode][mdnie->scenario].name);
}
#if defined(CONFIG_TDMB) || defined(CONFIG_TARGET_LOCALE_NTT)
etc:
#endif
if (!IS_ERR_OR_NULL(etc_table[mdnie->cabc][mdnie->outdoor][mdnie->tone].seq)) {
mdnie_send_sequence(mdnie, etc_table[mdnie->cabc][mdnie->outdoor][mdnie->tone].seq);
dev_info(mdnie->dev, "%s\n", etc_table[mdnie->cabc][mdnie->outdoor][mdnie->tone].name);
}
exit:
mutex_unlock(&mdnie->lock);
return;
}
#if defined(CONFIG_FB_MDNIE_PWM)
#ifdef CONFIG_MACH_P4NOTE
static int get_backlight_level_from_brightness(unsigned int brightness)
{
unsigned int value;
/* brightness tuning*/
if (brightness >= MID_BRIGHTNESS_LEVEL)
value = (brightness - MID_BRIGHTNESS_LEVEL) * (b_value.max-b_value.mid) / (MAX_BRIGHTNESS_LEVEL-MID_BRIGHTNESS_LEVEL) + b_value.mid;
else if (brightness >= LOW_BRIGHTNESS_LEVEL)
value = (brightness - LOW_BRIGHTNESS_LEVEL) * (b_value.mid-b_value.low) / (MID_BRIGHTNESS_LEVEL-LOW_BRIGHTNESS_LEVEL) + b_value.low;
else if (brightness >= DIM_BRIGHTNESS_LEVEL)
value = (brightness - DIM_BRIGHTNESS_LEVEL) * (b_value.low-b_value.dim) / (LOW_BRIGHTNESS_LEVEL-DIM_BRIGHTNESS_LEVEL) + b_value.dim;
else if (brightness > 0)
value = b_value.dim;
else
return 0;
if (value > 1600)
value = 1600;
if (value < 16)
value = 1;
else
value = value >> 4;
return value;
}
#else
static int get_backlight_level_from_brightness(unsigned int brightness)
{
unsigned int value;
/* brightness tuning*/
if (brightness >= MID_BRIGHTNESS_LEVEL)
value = (brightness - MID_BRIGHTNESS_LEVEL) * (MAX_BACKLIGHT_VALUE-MID_BACKLIGHT_VALUE) / (MAX_BRIGHTNESS_LEVEL-MID_BRIGHTNESS_LEVEL) + MID_BACKLIGHT_VALUE;
else if (brightness >= LOW_BRIGHTNESS_LEVEL)
value = (brightness - LOW_BRIGHTNESS_LEVEL) * (MID_BACKLIGHT_VALUE-LOW_BACKLIGHT_VALUE) / (MID_BRIGHTNESS_LEVEL-LOW_BRIGHTNESS_LEVEL) + LOW_BACKLIGHT_VALUE;
else if (brightness >= DIM_BRIGHTNESS_LEVEL)
value = (brightness - DIM_BRIGHTNESS_LEVEL) * (LOW_BACKLIGHT_VALUE-DIM_BACKLIGHT_VALUE) / (LOW_BRIGHTNESS_LEVEL-DIM_BRIGHTNESS_LEVEL) + DIM_BACKLIGHT_VALUE;
else if (brightness > 0)
value = DIM_BACKLIGHT_VALUE;
else
return 0;
if (value > 1600)
value = 1600;
if (value < 16)
value = 1;
else
value = value >> 4;
return value;
}
#endif
#if defined(CONFIG_CPU_EXYNOS4210)
static void mdnie_pwm_control(struct mdnie_info *mdnie, int value)
{
mutex_lock(&mdnie->dev_lock);
mdnie_write(0x00, 0x0000);
mdnie_write(0xB4, 0xC000 | value);
mdnie_write(0x28, 0x0000);
mutex_unlock(&mdnie->dev_lock);
}
static void mdnie_pwm_control_cabc(struct mdnie_info *mdnie, int value)
{
int reg;
const unsigned char *p_plut;
u16 min_duty;
unsigned idx;
mutex_lock(&mdnie->dev_lock);
idx = tunning_table[mdnie->cabc][mdnie->mode][mdnie->scenario].idx_lut;
p_plut = power_lut[mdnie->power_lut_idx][idx];
min_duty = p_plut[7] * value / 100;
mdnie_write(0x00, 0x0000);
if (min_duty < 4)
reg = 0xC000 | (max(1, (value * p_plut[3] / 100)));
else {
/*PowerLUT*/
mdnie_write(0x76, (p_plut[0] * value / 100) << 8 | (p_plut[1] * value / 100));
mdnie_write(0x77, (p_plut[2] * value / 100) << 8 | (p_plut[3] * value / 100));
mdnie_write(0x78, (p_plut[4] * value / 100) << 8 | (p_plut[5] * value / 100));
mdnie_write(0x79, (p_plut[6] * value / 100) << 8 | (p_plut[7] * value / 100));
mdnie_write(0x7a, (p_plut[8] * value / 100) << 8);
reg = 0x5000 | (value << 4);
}
mdnie_write(0xB4, reg);
mdnie_write(0x28, 0x0000);
mutex_unlock(&mdnie->dev_lock);
}
#elif defined(CONFIG_CPU_EXYNOS4212) || defined(CONFIG_CPU_EXYNOS4412)
static void mdnie_pwm_control(struct mdnie_info *mdnie, int value)
{
mutex_lock(&mdnie->dev_lock);
mdnie_write(0x00, 0x0001);
mdnie_write(0xB6, 0xC000 | value);
mdnie_write(0xff, 0x0000);
mutex_unlock(&mdnie->dev_lock);
}
static void mdnie_pwm_control_cabc(struct mdnie_info *mdnie, int value)
{
int reg;
const unsigned char *p_plut;
u16 min_duty;
unsigned idx;
mutex_lock(&mdnie->dev_lock);
idx = tunning_table[mdnie->cabc][mdnie->mode][mdnie->scenario].idx_lut;
p_plut = power_lut[mdnie->power_lut_idx][idx];
min_duty = p_plut[7] * value / 100;
mdnie_write(0x00, 0x0001);
if (min_duty < 4)
reg = 0xC000 | (max(1, (value * p_plut[3] / 100)));
else {
/*PowerLUT*/
mdnie_write(0x79, (p_plut[0] * value / 100) << 8 | (p_plut[1] * value / 100));
mdnie_write(0x7a, (p_plut[2] * value / 100) << 8 | (p_plut[3] * value / 100));
mdnie_write(0x7b, (p_plut[4] * value / 100) << 8 | (p_plut[5] * value / 100));
mdnie_write(0x7c, (p_plut[6] * value / 100) << 8 | (p_plut[7] * value / 100));
mdnie_write(0x7d, (p_plut[8] * value / 100) << 8);
reg = 0x5000 | (value << 4);
}
mdnie_write(0xB6, reg);
mdnie_write(0xff, 0x0000);
mutex_unlock(&mdnie->dev_lock);
}
#endif
void set_mdnie_pwm_value(struct mdnie_info *mdnie, int value)
{
mdnie_pwm_control(mdnie, value);
}
static int update_brightness(struct mdnie_info *mdnie)
{
unsigned int value;
unsigned int brightness = mdnie->bd->props.brightness;
value = get_backlight_level_from_brightness(brightness);
if (!mdnie->enable) {
dev_err(mdnie->dev, "mdnie states is off\n");
return 0;
}
if (brightness <= CABC_CUTOFF_BACKLIGHT_VALUE) {
mdnie_pwm_control(mdnie, value);
} else {
if ((mdnie->cabc) && (mdnie->scenario != CAMERA_MODE) && !(mdnie->tunning))
mdnie_pwm_control_cabc(mdnie, value);
else
mdnie_pwm_control(mdnie, value);
}
return 0;
}
static int mdnie_set_brightness(struct backlight_device *bd)
{
struct mdnie_info *mdnie = bl_get_data(bd);
int ret = 0;
unsigned int brightness = bd->props.brightness;
if (brightness < MIN_BRIGHTNESS ||
brightness > bd->props.max_brightness) {
dev_err(&bd->dev, "lcd brightness should be %d to %d. now %d\n",
MIN_BRIGHTNESS, bd->props.max_brightness, brightness);
brightness = bd->props.max_brightness;
}
if ((mdnie->enable) && (mdnie->bd_enable)) {
ret = update_brightness(mdnie);
dev_info(&bd->dev, "brightness=%d\n", bd->props.brightness);
if (ret < 0)
return -EINVAL;
}
return ret;
}
static int mdnie_get_brightness(struct backlight_device *bd)
{
return bd->props.brightness;
}
static const struct backlight_ops mdnie_backlight_ops = {
.get_brightness = mdnie_get_brightness,
.update_status = mdnie_set_brightness,
};
#endif
static ssize_t mode_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct mdnie_info *mdnie = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", mdnie->mode);
}
static ssize_t mode_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct mdnie_info *mdnie = dev_get_drvdata(dev);
unsigned int value;
int ret;
ret = strict_strtoul(buf, 0, (unsigned long *)&value);
dev_info(dev, "%s :: value=%d\n", __func__, value);
if (value >= MODE_MAX) {
value = STANDARD;
return -EINVAL;
}
mutex_lock(&mdnie->lock);
mdnie->mode = value;
mutex_unlock(&mdnie->lock);
set_mdnie_value(mdnie, 0);
#if defined(CONFIG_FB_MDNIE_PWM)
if ((mdnie->enable) && (mdnie->bd_enable))
update_brightness(mdnie);
#endif
return count;
}
static ssize_t scenario_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct mdnie_info *mdnie = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", mdnie->scenario);
}
static ssize_t scenario_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct mdnie_info *mdnie = dev_get_drvdata(dev);
unsigned int value;
int ret;
ret = strict_strtoul(buf, 0, (unsigned long *)&value);
dev_info(dev, "%s :: value=%d\n", __func__, value);
if (!SCENARIO_IS_VALID(value))
value = UI_MODE;
#if defined(CONFIG_FB_MDNIE_PWM)
if (value >= SCENARIO_MAX)
value = UI_MODE;
#endif
mutex_lock(&mdnie->lock);
mdnie->scenario = value;
mutex_unlock(&mdnie->lock);
set_mdnie_value(mdnie, 0);
#if defined(CONFIG_FB_MDNIE_PWM)
if ((mdnie->enable) && (mdnie->bd_enable))
update_brightness(mdnie);
#endif
return count;
}
static ssize_t outdoor_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct mdnie_info *mdnie = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", mdnie->outdoor);
}
static ssize_t outdoor_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct mdnie_info *mdnie = dev_get_drvdata(dev);
unsigned int value;
int ret;
ret = strict_strtoul(buf, 0, (unsigned long *)&value);
dev_info(dev, "%s :: value=%d\n", __func__, value);
if (value >= OUTDOOR_MAX)
value = OUTDOOR_OFF;
value = (value) ? OUTDOOR_ON : OUTDOOR_OFF;
mutex_lock(&mdnie->lock);
mdnie->outdoor = value;
mutex_unlock(&mdnie->lock);
set_mdnie_value(mdnie, 0);
return count;
}
#if defined(CONFIG_FB_MDNIE_PWM)
static ssize_t cabc_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct mdnie_info *mdnie = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", mdnie->cabc);
}
static ssize_t cabc_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct mdnie_info *mdnie = dev_get_drvdata(dev);
unsigned int value;
int ret;
ret = strict_strtoul(buf, 0, (unsigned long *)&value);
dev_info(dev, "%s :: value=%d\n", __func__, value);
if (value >= CABC_MAX)
value = CABC_OFF;
value = (value) ? CABC_ON : CABC_OFF;
mutex_lock(&mdnie->lock);
mdnie->cabc = value;
mutex_unlock(&mdnie->lock);
set_mdnie_value(mdnie, 0);
if ((mdnie->enable) && (mdnie->bd_enable))
update_brightness(mdnie);
return count;
}
static ssize_t auto_brightness_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct mdnie_info *mdnie = dev_get_drvdata(dev);
char *pos = buf;
int i;
pos += sprintf(pos, "%d, %d, ", mdnie->auto_brightness, mdnie->power_lut_idx);
for (i = 0; i < 5; i++)
pos += sprintf(pos, "0x%02x, ", power_lut[mdnie->power_lut_idx][0][i]);
pos += sprintf(pos, "\n");
return pos - buf;
}
static ssize_t auto_brightness_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct mdnie_info *mdnie = dev_get_drvdata(dev);
int value;
int rc;
rc = strict_strtoul(buf, (unsigned int)0, (unsigned long *)&value);
if (rc < 0)
return rc;
else {
if (mdnie->auto_brightness != value) {
dev_info(dev, "%s - %d -> %d\n", __func__, mdnie->auto_brightness, value);
mutex_lock(&mdnie->dev_lock);
mdnie->auto_brightness = value;
#if defined(CONFIG_FB_S5P_S6C1372)
mutex_lock(&mdnie->lock);
mdnie->cabc = (value) ? CABC_ON : CABC_OFF;
mutex_unlock(&mdnie->lock);
#endif
if (mdnie->auto_brightness >= 5)
mdnie->power_lut_idx = LUT_LEVEL_OUTDOOR_2;
else if (mdnie->auto_brightness == 4)
mdnie->power_lut_idx = LUT_LEVEL_OUTDOOR_1;
else
mdnie->power_lut_idx = LUT_LEVEL_MANUAL_AND_INDOOR;
mutex_unlock(&mdnie->dev_lock);
set_mdnie_value(mdnie, 0);
if (mdnie->bd_enable)
update_brightness(mdnie);
}
}
return size;
}
static DEVICE_ATTR(auto_brightness, 0644, auto_brightness_show, auto_brightness_store);
#endif
static ssize_t tunning_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
char temp[128];
sprintf(temp, "%s\n", tuning_file_name);
strcat(buf, temp);
return strlen(buf);
}
static ssize_t tunning_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct mdnie_info *mdnie = dev_get_drvdata(dev);
if (!strncmp(buf, "0", 1)) {
mdnie->tunning = FALSE;
dev_info(dev, "%s :: tunning is disabled.\n", __func__);
} else if (!strncmp(buf, "1", 1)) {
mdnie->tunning = TRUE;
dev_info(dev, "%s :: tunning is enabled.\n", __func__);
} else {
if (!mdnie->tunning)
return count;
memset(tuning_file_name, 0, sizeof(tuning_file_name));
strcpy(tuning_file_name, "/sdcard/mdnie/");
strncat(tuning_file_name, buf, count-1);
mdnie_txtbuf_to_parsing(tuning_file_name);
dev_info(dev, "%s :: %s\n", __func__, tuning_file_name);
}
return count;
}
static ssize_t negative_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct mdnie_info *mdnie = dev_get_drvdata(dev);
char *pos = buf;
u32 i;
pos += sprintf(pos, "%d\n", mdnie->negative);
return pos - buf;
}
static ssize_t negative_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct mdnie_info *mdnie = dev_get_drvdata(dev);
unsigned int value;
int ret;
ret = strict_strtoul(buf, 0, (unsigned long *)&value);
dev_info(dev, "%s :: value=%d, by %s\n", __func__, value, current->comm);
if (ret < 0)
return ret;
else {
if (mdnie->negative == value)
return count;
if (value >= NEGATIVE_MAX)
value = NEGATIVE_OFF;
value = (value) ? NEGATIVE_ON : NEGATIVE_OFF;
mutex_lock(&mdnie->lock);
mdnie->negative = value;
mutex_unlock(&mdnie->lock);
set_mdnie_value(mdnie, 0);
}
return count;
}
static struct device_attribute mdnie_attributes[] = {
__ATTR(mode, 0664, mode_show, mode_store),
__ATTR(scenario, 0664, scenario_show, scenario_store),
__ATTR(outdoor, 0664, outdoor_show, outdoor_store),
#if defined(CONFIG_FB_MDNIE_PWM)
__ATTR(cabc, 0664, cabc_show, cabc_store),
#endif
__ATTR(tunning, 0664, tunning_show, tunning_store),
__ATTR(negative, 0664, negative_show, negative_store),
__ATTR_NULL,
};
#ifdef CONFIG_PM
#if defined(CONFIG_HAS_EARLYSUSPEND) && defined(CONFIG_FB_MDNIE_PWM)
void mdnie_early_suspend(struct early_suspend *h)
{
struct mdnie_info *mdnie = container_of(h, struct mdnie_info, early_suspend);
struct lcd_platform_data *pd = NULL;
pd = mdnie->lcd_pd;
dev_info(mdnie->dev, "+%s\n", __func__);
mdnie->bd_enable = FALSE;
if (mdnie->enable)
mdnie_pwm_control(mdnie, 0);
if (!pd)
dev_info(&mdnie->bd->dev, "platform data is NULL.\n");
if (!pd->power_on)
dev_info(&mdnie->bd->dev, "power_on is NULL.\n");
else
pd->power_on(NULL, 0);
dev_info(mdnie->dev, "-%s\n", __func__);
return ;
}
void mdnie_late_resume(struct early_suspend *h)
{
u32 i;
struct mdnie_info *mdnie = container_of(h, struct mdnie_info, early_suspend);
struct lcd_platform_data *pd = NULL;
dev_info(mdnie->dev, "+%s\n", __func__);
pd = mdnie->lcd_pd;
if (mdnie->enable)
mdnie_pwm_control(mdnie, 0);
if (!pd)
dev_info(&mdnie->bd->dev, "platform data is NULL.\n");
if (!pd->power_on)
dev_info(&mdnie->bd->dev, "power_on is NULL.\n");
else
pd->power_on(NULL, 1);
if (mdnie->enable) {
dev_info(&mdnie->bd->dev, "brightness=%d\n", mdnie->bd->props.brightness);
update_brightness(mdnie);
}
mdnie->bd_enable = TRUE;
dev_info(mdnie->dev, "-%s\n", __func__);
return ;
}
#endif
#endif
static int mdnie_probe(struct platform_device *pdev)
{
#if defined(CONFIG_FB_MDNIE_PWM)
struct platform_mdnie_data *pdata = pdev->dev.platform_data;
#endif
struct mdnie_info *mdnie;
int ret = 0;
mdnie_class = class_create(THIS_MODULE, dev_name(&pdev->dev));
if (IS_ERR_OR_NULL(mdnie_class)) {
pr_err("failed to create mdnie class\n");
ret = -EINVAL;
goto error0;
}
mdnie_class->dev_attrs = mdnie_attributes;
mdnie = kzalloc(sizeof(struct mdnie_info), GFP_KERNEL);
if (!mdnie) {
pr_err("failed to allocate mdnie\n");
ret = -ENOMEM;
goto error1;
}
mdnie->dev = device_create(mdnie_class, &pdev->dev, 0, &mdnie, "mdnie");
if (IS_ERR_OR_NULL(mdnie->dev)) {
pr_err("failed to create mdnie device\n");
ret = -EINVAL;
goto error2;
}
#if defined(CONFIG_FB_MDNIE_PWM)
if (!pdata) {
pr_err("no platform data specified\n");
ret = -EINVAL;
goto error2;
}
mdnie->bd = backlight_device_register("panel", mdnie->dev,
mdnie, &mdnie_backlight_ops, NULL);
mdnie->bd->props.max_brightness = MAX_BRIGHTNESS_LEVEL;
mdnie->bd->props.brightness = DEFAULT_BRIGHTNESS;
mdnie->bd_enable = TRUE;
mdnie->lcd_pd = pdata->lcd_pd;
ret = device_create_file(&mdnie->bd->dev, &dev_attr_auto_brightness);
if (ret < 0)
dev_err(&mdnie->bd->dev, "failed to add sysfs entries, %d\n", __LINE__);
#endif
mdnie->scenario = UI_MODE;
mdnie->mode = STANDARD;
mdnie->tone = TONE_NORMAL;
mdnie->outdoor = OUTDOOR_OFF;
#if defined(CONFIG_FB_MDNIE_PWM)
mdnie->cabc = CABC_ON;
mdnie->power_lut_idx = LUT_LEVEL_MANUAL_AND_INDOOR;
mdnie->auto_brightness = 0;
#else
mdnie->cabc = CABC_OFF;
#endif
#if defined(CONFIG_FB_S5P_S6C1372)
mdnie->cabc = CABC_OFF;
#endif
mdnie->enable = TRUE;
mdnie->tunning = FALSE;
mdnie->negative = NEGATIVE_OFF;
mutex_init(&mdnie->lock);
mutex_init(&mdnie->dev_lock);
platform_set_drvdata(pdev, mdnie);
dev_set_drvdata(mdnie->dev, mdnie);
#ifdef CONFIG_HAS_WAKELOCK
#ifdef CONFIG_HAS_EARLYSUSPEND
#if defined(CONFIG_FB_MDNIE_PWM)
mdnie->early_suspend.suspend = mdnie_early_suspend;
mdnie->early_suspend.resume = mdnie_late_resume;
mdnie->early_suspend.level = EARLY_SUSPEND_LEVEL_DISABLE_FB - 1;
register_early_suspend(&mdnie->early_suspend);
#endif
#endif
#endif
#if defined(CONFIG_FB_S5P_S6C1372)
check_lcd_type();
dev_info(mdnie->dev, "lcdtype = %d\n", pdata->display_type);
if (pdata->display_type == 1) {
b_value.max = 1441;
b_value.mid = 784;
b_value.low = 16;
b_value.dim = 16;
} else {
b_value.max = 1216; /* 76% */
b_value.mid = 679; /* 39% */
b_value.low = 16; /* 1% */
b_value.dim = 16; /* 1% */
}
#endif
#if defined(CONFIG_FB_S5P_S6F1202A)
if (pdata->display_type == 0) {
memcpy(tunning_table, tunning_table_hydis, sizeof(tunning_table));
memcpy(etc_table, etc_table_hydis, sizeof(etc_table));
memcpy(camera_table, camera_table_hydis, sizeof(camera_table));
} else if (pdata->display_type == 1) {
memcpy(tunning_table, tunning_table_sec, sizeof(tunning_table));
memcpy(etc_table, etc_table_sec, sizeof(etc_table));
memcpy(camera_table, camera_table_sec, sizeof(camera_table));
} else if (pdata->display_type == 2) {
memcpy(tunning_table, tunning_table_boe, sizeof(tunning_table));
memcpy(etc_table, etc_table_boe, sizeof(etc_table));
memcpy(camera_table, camera_table_boe, sizeof(camera_table));
}
#endif
g_mdnie = mdnie;
set_mdnie_value(mdnie, 0);
dev_info(mdnie->dev, "registered successfully\n");
return 0;
error2:
kfree(mdnie);
error1:
class_destroy(mdnie_class);
error0:
return ret;
}
static int mdnie_remove(struct platform_device *pdev)
{
struct mdnie_info *mdnie = dev_get_drvdata(&pdev->dev);
#if defined(CONFIG_FB_MDNIE_PWM)
backlight_device_unregister(mdnie->bd);
#endif
class_destroy(mdnie_class);
kfree(mdnie);
return 0;
}
static void mdnie_shutdown(struct platform_device *pdev)
{
#if defined(CONFIG_FB_MDNIE_PWM)
struct mdnie_info *mdnie = dev_get_drvdata(&pdev->dev);
struct lcd_platform_data *pd = NULL;
pd = mdnie->lcd_pd;
dev_info(mdnie->dev, "+%s\n", __func__);
mdnie->bd_enable = FALSE;
if (mdnie->enable)
mdnie_pwm_control(mdnie, 0);
if (!pd)
dev_info(&mdnie->bd->dev, "platform data is NULL.\n");
if (!pd->power_on)
dev_info(&mdnie->bd->dev, "power_on is NULL.\n");
else
pd->power_on(NULL, 0);
dev_info(mdnie->dev, "-%s\n", __func__);
#endif
}
static struct platform_driver mdnie_driver = {
.driver = {
.name = "mdnie",
.owner = THIS_MODULE,
},
.probe = mdnie_probe,
.remove = mdnie_remove,
#ifndef CONFIG_HAS_EARLYSUSPEND
.suspend = mdnie_suspend,
.resume = mdnie_resume,
#endif
.shutdown = mdnie_shutdown,
};
static int __init mdnie_init(void)
{
return platform_driver_register(&mdnie_driver);
}
module_init(mdnie_init);
static void __exit mdnie_exit(void)
{
platform_driver_unregister(&mdnie_driver);
}
module_exit(mdnie_exit);
MODULE_DESCRIPTION("mDNIe Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
manabian/linux-lpc | fs/stat.c | 35 | 12225 | /*
* linux/fs/stat.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
#include <linux/export.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <linux/file.h>
#include <linux/highuid.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/pagemap.h>
#include <linux/uaccess.h>
#include <asm/unistd.h>
void generic_fillattr(struct inode *inode, struct kstat *stat)
{
stat->dev = inode->i_sb->s_dev;
stat->ino = inode->i_ino;
stat->mode = inode->i_mode;
stat->nlink = inode->i_nlink;
stat->uid = inode->i_uid;
stat->gid = inode->i_gid;
stat->rdev = inode->i_rdev;
stat->size = i_size_read(inode);
stat->atime = inode->i_atime;
stat->mtime = inode->i_mtime;
stat->ctime = inode->i_ctime;
stat->blksize = (1 << inode->i_blkbits);
stat->blocks = inode->i_blocks;
}
EXPORT_SYMBOL(generic_fillattr);
/**
* vfs_getattr_nosec - getattr without security checks
* @path: file to get attributes from
* @stat: structure to return attributes in
*
* Get attributes without calling security_inode_getattr.
*
* Currently the only caller other than vfs_getattr is internal to the
* filehandle lookup code, which uses only the inode number and returns
* no attributes to any user. Any other code probably wants
* vfs_getattr.
*/
int vfs_getattr_nosec(struct path *path, struct kstat *stat)
{
struct inode *inode = d_backing_inode(path->dentry);
if (inode->i_op->getattr)
return inode->i_op->getattr(path->mnt, path->dentry, stat);
generic_fillattr(inode, stat);
return 0;
}
EXPORT_SYMBOL(vfs_getattr_nosec);
int vfs_getattr(struct path *path, struct kstat *stat)
{
int retval;
retval = security_inode_getattr(path);
if (retval)
return retval;
return vfs_getattr_nosec(path, stat);
}
EXPORT_SYMBOL(vfs_getattr);
int vfs_fstat(unsigned int fd, struct kstat *stat)
{
struct fd f = fdget_raw(fd);
int error = -EBADF;
if (f.file) {
error = vfs_getattr(&f.file->f_path, stat);
fdput(f);
}
return error;
}
EXPORT_SYMBOL(vfs_fstat);
int vfs_fstatat(int dfd, const char __user *filename, struct kstat *stat,
int flag)
{
struct path path;
int error = -EINVAL;
unsigned int lookup_flags = 0;
if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT |
AT_EMPTY_PATH)) != 0)
goto out;
if (!(flag & AT_SYMLINK_NOFOLLOW))
lookup_flags |= LOOKUP_FOLLOW;
if (flag & AT_EMPTY_PATH)
lookup_flags |= LOOKUP_EMPTY;
retry:
error = user_path_at(dfd, filename, lookup_flags, &path);
if (error)
goto out;
error = vfs_getattr(&path, stat);
path_put(&path);
if (retry_estale(error, lookup_flags)) {
lookup_flags |= LOOKUP_REVAL;
goto retry;
}
out:
return error;
}
EXPORT_SYMBOL(vfs_fstatat);
int vfs_stat(const char __user *name, struct kstat *stat)
{
return vfs_fstatat(AT_FDCWD, name, stat, 0);
}
EXPORT_SYMBOL(vfs_stat);
int vfs_lstat(const char __user *name, struct kstat *stat)
{
return vfs_fstatat(AT_FDCWD, name, stat, AT_SYMLINK_NOFOLLOW);
}
EXPORT_SYMBOL(vfs_lstat);
#ifdef __ARCH_WANT_OLD_STAT
/*
* For backward compatibility? Maybe this should be moved
* into arch/i386 instead?
*/
static int cp_old_stat(struct kstat *stat, struct __old_kernel_stat __user * statbuf)
{
static int warncount = 5;
struct __old_kernel_stat tmp;
if (warncount > 0) {
warncount--;
printk(KERN_WARNING "VFS: Warning: %s using old stat() call. Recompile your binary.\n",
current->comm);
} else if (warncount < 0) {
/* it's laughable, but... */
warncount = 0;
}
memset(&tmp, 0, sizeof(struct __old_kernel_stat));
tmp.st_dev = old_encode_dev(stat->dev);
tmp.st_ino = stat->ino;
if (sizeof(tmp.st_ino) < sizeof(stat->ino) && tmp.st_ino != stat->ino)
return -EOVERFLOW;
tmp.st_mode = stat->mode;
tmp.st_nlink = stat->nlink;
if (tmp.st_nlink != stat->nlink)
return -EOVERFLOW;
SET_UID(tmp.st_uid, from_kuid_munged(current_user_ns(), stat->uid));
SET_GID(tmp.st_gid, from_kgid_munged(current_user_ns(), stat->gid));
tmp.st_rdev = old_encode_dev(stat->rdev);
#if BITS_PER_LONG == 32
if (stat->size > MAX_NON_LFS)
return -EOVERFLOW;
#endif
tmp.st_size = stat->size;
tmp.st_atime = stat->atime.tv_sec;
tmp.st_mtime = stat->mtime.tv_sec;
tmp.st_ctime = stat->ctime.tv_sec;
return copy_to_user(statbuf,&tmp,sizeof(tmp)) ? -EFAULT : 0;
}
SYSCALL_DEFINE2(stat, const char __user *, filename,
struct __old_kernel_stat __user *, statbuf)
{
struct kstat stat;
int error;
error = vfs_stat(filename, &stat);
if (error)
return error;
return cp_old_stat(&stat, statbuf);
}
SYSCALL_DEFINE2(lstat, const char __user *, filename,
struct __old_kernel_stat __user *, statbuf)
{
struct kstat stat;
int error;
error = vfs_lstat(filename, &stat);
if (error)
return error;
return cp_old_stat(&stat, statbuf);
}
SYSCALL_DEFINE2(fstat, unsigned int, fd, struct __old_kernel_stat __user *, statbuf)
{
struct kstat stat;
int error = vfs_fstat(fd, &stat);
if (!error)
error = cp_old_stat(&stat, statbuf);
return error;
}
#endif /* __ARCH_WANT_OLD_STAT */
#if BITS_PER_LONG == 32
# define choose_32_64(a,b) a
#else
# define choose_32_64(a,b) b
#endif
#define valid_dev(x) choose_32_64(old_valid_dev(x),true)
#define encode_dev(x) choose_32_64(old_encode_dev,new_encode_dev)(x)
#ifndef INIT_STRUCT_STAT_PADDING
# define INIT_STRUCT_STAT_PADDING(st) memset(&st, 0, sizeof(st))
#endif
static int cp_new_stat(struct kstat *stat, struct stat __user *statbuf)
{
struct stat tmp;
if (!valid_dev(stat->dev) || !valid_dev(stat->rdev))
return -EOVERFLOW;
#if BITS_PER_LONG == 32
if (stat->size > MAX_NON_LFS)
return -EOVERFLOW;
#endif
INIT_STRUCT_STAT_PADDING(tmp);
tmp.st_dev = encode_dev(stat->dev);
tmp.st_ino = stat->ino;
if (sizeof(tmp.st_ino) < sizeof(stat->ino) && tmp.st_ino != stat->ino)
return -EOVERFLOW;
tmp.st_mode = stat->mode;
tmp.st_nlink = stat->nlink;
if (tmp.st_nlink != stat->nlink)
return -EOVERFLOW;
SET_UID(tmp.st_uid, from_kuid_munged(current_user_ns(), stat->uid));
SET_GID(tmp.st_gid, from_kgid_munged(current_user_ns(), stat->gid));
tmp.st_rdev = encode_dev(stat->rdev);
tmp.st_size = stat->size;
tmp.st_atime = stat->atime.tv_sec;
tmp.st_mtime = stat->mtime.tv_sec;
tmp.st_ctime = stat->ctime.tv_sec;
#ifdef STAT_HAVE_NSEC
tmp.st_atime_nsec = stat->atime.tv_nsec;
tmp.st_mtime_nsec = stat->mtime.tv_nsec;
tmp.st_ctime_nsec = stat->ctime.tv_nsec;
#endif
tmp.st_blocks = stat->blocks;
tmp.st_blksize = stat->blksize;
return copy_to_user(statbuf,&tmp,sizeof(tmp)) ? -EFAULT : 0;
}
SYSCALL_DEFINE2(newstat, const char __user *, filename,
struct stat __user *, statbuf)
{
struct kstat stat;
int error = vfs_stat(filename, &stat);
if (error)
return error;
return cp_new_stat(&stat, statbuf);
}
SYSCALL_DEFINE2(newlstat, const char __user *, filename,
struct stat __user *, statbuf)
{
struct kstat stat;
int error;
error = vfs_lstat(filename, &stat);
if (error)
return error;
return cp_new_stat(&stat, statbuf);
}
#if !defined(__ARCH_WANT_STAT64) || defined(__ARCH_WANT_SYS_NEWFSTATAT)
SYSCALL_DEFINE4(newfstatat, int, dfd, const char __user *, filename,
struct stat __user *, statbuf, int, flag)
{
struct kstat stat;
int error;
error = vfs_fstatat(dfd, filename, &stat, flag);
if (error)
return error;
return cp_new_stat(&stat, statbuf);
}
#endif
SYSCALL_DEFINE2(newfstat, unsigned int, fd, struct stat __user *, statbuf)
{
struct kstat stat;
int error = vfs_fstat(fd, &stat);
if (!error)
error = cp_new_stat(&stat, statbuf);
return error;
}
SYSCALL_DEFINE4(readlinkat, int, dfd, const char __user *, pathname,
char __user *, buf, int, bufsiz)
{
struct path path;
int error;
int empty = 0;
unsigned int lookup_flags = LOOKUP_EMPTY;
if (bufsiz <= 0)
return -EINVAL;
retry:
error = user_path_at_empty(dfd, pathname, lookup_flags, &path, &empty);
if (!error) {
struct inode *inode = d_backing_inode(path.dentry);
error = empty ? -ENOENT : -EINVAL;
/*
* AFS mountpoints allow readlink(2) but are not symlinks
*/
if (d_is_symlink(path.dentry) || inode->i_op->readlink) {
error = security_inode_readlink(path.dentry);
if (!error) {
touch_atime(&path);
error = vfs_readlink(path.dentry, buf, bufsiz);
}
}
path_put(&path);
if (retry_estale(error, lookup_flags)) {
lookup_flags |= LOOKUP_REVAL;
goto retry;
}
}
return error;
}
SYSCALL_DEFINE3(readlink, const char __user *, path, char __user *, buf,
int, bufsiz)
{
return sys_readlinkat(AT_FDCWD, path, buf, bufsiz);
}
/* ---------- LFS-64 ----------- */
#if defined(__ARCH_WANT_STAT64) || defined(__ARCH_WANT_COMPAT_STAT64)
#ifndef INIT_STRUCT_STAT64_PADDING
# define INIT_STRUCT_STAT64_PADDING(st) memset(&st, 0, sizeof(st))
#endif
static long cp_new_stat64(struct kstat *stat, struct stat64 __user *statbuf)
{
struct stat64 tmp;
INIT_STRUCT_STAT64_PADDING(tmp);
#ifdef CONFIG_MIPS
/* mips has weird padding, so we don't get 64 bits there */
tmp.st_dev = new_encode_dev(stat->dev);
tmp.st_rdev = new_encode_dev(stat->rdev);
#else
tmp.st_dev = huge_encode_dev(stat->dev);
tmp.st_rdev = huge_encode_dev(stat->rdev);
#endif
tmp.st_ino = stat->ino;
if (sizeof(tmp.st_ino) < sizeof(stat->ino) && tmp.st_ino != stat->ino)
return -EOVERFLOW;
#ifdef STAT64_HAS_BROKEN_ST_INO
tmp.__st_ino = stat->ino;
#endif
tmp.st_mode = stat->mode;
tmp.st_nlink = stat->nlink;
tmp.st_uid = from_kuid_munged(current_user_ns(), stat->uid);
tmp.st_gid = from_kgid_munged(current_user_ns(), stat->gid);
tmp.st_atime = stat->atime.tv_sec;
tmp.st_atime_nsec = stat->atime.tv_nsec;
tmp.st_mtime = stat->mtime.tv_sec;
tmp.st_mtime_nsec = stat->mtime.tv_nsec;
tmp.st_ctime = stat->ctime.tv_sec;
tmp.st_ctime_nsec = stat->ctime.tv_nsec;
tmp.st_size = stat->size;
tmp.st_blocks = stat->blocks;
tmp.st_blksize = stat->blksize;
return copy_to_user(statbuf,&tmp,sizeof(tmp)) ? -EFAULT : 0;
}
SYSCALL_DEFINE2(stat64, const char __user *, filename,
struct stat64 __user *, statbuf)
{
struct kstat stat;
int error = vfs_stat(filename, &stat);
if (!error)
error = cp_new_stat64(&stat, statbuf);
return error;
}
SYSCALL_DEFINE2(lstat64, const char __user *, filename,
struct stat64 __user *, statbuf)
{
struct kstat stat;
int error = vfs_lstat(filename, &stat);
if (!error)
error = cp_new_stat64(&stat, statbuf);
return error;
}
SYSCALL_DEFINE2(fstat64, unsigned long, fd, struct stat64 __user *, statbuf)
{
struct kstat stat;
int error = vfs_fstat(fd, &stat);
if (!error)
error = cp_new_stat64(&stat, statbuf);
return error;
}
SYSCALL_DEFINE4(fstatat64, int, dfd, const char __user *, filename,
struct stat64 __user *, statbuf, int, flag)
{
struct kstat stat;
int error;
error = vfs_fstatat(dfd, filename, &stat, flag);
if (error)
return error;
return cp_new_stat64(&stat, statbuf);
}
#endif /* __ARCH_WANT_STAT64 || __ARCH_WANT_COMPAT_STAT64 */
/* Caller is here responsible for sufficient locking (ie. inode->i_lock) */
void __inode_add_bytes(struct inode *inode, loff_t bytes)
{
inode->i_blocks += bytes >> 9;
bytes &= 511;
inode->i_bytes += bytes;
if (inode->i_bytes >= 512) {
inode->i_blocks++;
inode->i_bytes -= 512;
}
}
void inode_add_bytes(struct inode *inode, loff_t bytes)
{
spin_lock(&inode->i_lock);
__inode_add_bytes(inode, bytes);
spin_unlock(&inode->i_lock);
}
EXPORT_SYMBOL(inode_add_bytes);
void __inode_sub_bytes(struct inode *inode, loff_t bytes)
{
inode->i_blocks -= bytes >> 9;
bytes &= 511;
if (inode->i_bytes < bytes) {
inode->i_blocks--;
inode->i_bytes += 512;
}
inode->i_bytes -= bytes;
}
EXPORT_SYMBOL(__inode_sub_bytes);
void inode_sub_bytes(struct inode *inode, loff_t bytes)
{
spin_lock(&inode->i_lock);
__inode_sub_bytes(inode, bytes);
spin_unlock(&inode->i_lock);
}
EXPORT_SYMBOL(inode_sub_bytes);
loff_t inode_get_bytes(struct inode *inode)
{
loff_t ret;
spin_lock(&inode->i_lock);
ret = (((loff_t)inode->i_blocks) << 9) + inode->i_bytes;
spin_unlock(&inode->i_lock);
return ret;
}
EXPORT_SYMBOL(inode_get_bytes);
void inode_set_bytes(struct inode *inode, loff_t bytes)
{
/* Caller is here responsible for sufficient locking
* (ie. inode->i_lock) */
inode->i_blocks = bytes >> 9;
inode->i_bytes = bytes & 511;
}
EXPORT_SYMBOL(inode_set_bytes);
| gpl-2.0 |
bergwolf/rhel6 | drivers/s390/block/dasd_proc.c | 35 | 10311 | /*
* File...........: linux/drivers/s390/block/dasd_proc.c
* Author(s)......: Holger Smolinski <Holger.Smolinski@de.ibm.com>
* Horst Hummel <Horst.Hummel@de.ibm.com>
* Carsten Otte <Cotte@de.ibm.com>
* Martin Schwidefsky <schwidefsky@de.ibm.com>
* Bugreports.to..: <Linux390@de.ibm.com>
* (C) IBM Corporation, IBM Deutschland Entwicklung GmbH, 1999-2002
*
* /proc interface for the dasd driver.
*
*/
#define KMSG_COMPONENT "dasd"
#include <linux/ctype.h>
#include <linux/string.h>
#include <linux/seq_file.h>
#include <linux/vmalloc.h>
#include <linux/proc_fs.h>
#include <asm/debug.h>
#include <asm/uaccess.h>
/* This is ugly... */
#define PRINTK_HEADER "dasd_proc:"
#include "dasd_int.h"
static struct proc_dir_entry *dasd_proc_root_entry = NULL;
static struct proc_dir_entry *dasd_devices_entry = NULL;
static struct proc_dir_entry *dasd_statistics_entry = NULL;
static int
dasd_devices_show(struct seq_file *m, void *v)
{
struct dasd_device *device;
struct dasd_block *block;
char *substr;
device = dasd_device_from_devindex((unsigned long) v - 1);
if (IS_ERR(device))
return 0;
if (device->block)
block = device->block;
else {
dasd_put_device(device);
return 0;
}
/* Print device number. */
seq_printf(m, "%s", dev_name(&device->cdev->dev));
/* Print discipline string. */
if (device->discipline != NULL)
seq_printf(m, "(%s)", device->discipline->name);
else
seq_printf(m, "(none)");
/* Print kdev. */
if (block->gdp)
seq_printf(m, " at (%3d:%6d)",
MAJOR(disk_devt(block->gdp)),
MINOR(disk_devt(block->gdp)));
else
seq_printf(m, " at (???:??????)");
/* Print device name. */
if (block->gdp)
seq_printf(m, " is %-8s", block->gdp->disk_name);
else
seq_printf(m, " is ????????");
/* Print devices features. */
substr = (device->features & DASD_FEATURE_READONLY) ? "(ro)" : " ";
seq_printf(m, "%4s: ", substr);
/* Print device status information. */
switch (device->state) {
case DASD_STATE_NEW:
seq_printf(m, "new");
break;
case DASD_STATE_KNOWN:
seq_printf(m, "detected");
break;
case DASD_STATE_BASIC:
seq_printf(m, "basic");
break;
case DASD_STATE_UNFMT:
seq_printf(m, "unformatted");
break;
case DASD_STATE_READY:
case DASD_STATE_ONLINE:
seq_printf(m, "active ");
if (dasd_check_blocksize(block->bp_block))
seq_printf(m, "n/f ");
else
seq_printf(m,
"at blocksize: %d, %lld blocks, %lld MB",
block->bp_block, block->blocks,
((block->bp_block >> 9) *
block->blocks) >> 11);
break;
default:
seq_printf(m, "no stat");
break;
}
dasd_put_device(device);
if (dasd_probeonly)
seq_printf(m, "(probeonly)");
seq_printf(m, "\n");
return 0;
}
static void *dasd_devices_start(struct seq_file *m, loff_t *pos)
{
if (*pos >= dasd_max_devindex)
return NULL;
return (void *)((unsigned long) *pos + 1);
}
static void *dasd_devices_next(struct seq_file *m, void *v, loff_t *pos)
{
++*pos;
return dasd_devices_start(m, pos);
}
static void dasd_devices_stop(struct seq_file *m, void *v)
{
}
static const struct seq_operations dasd_devices_seq_ops = {
.start = dasd_devices_start,
.next = dasd_devices_next,
.stop = dasd_devices_stop,
.show = dasd_devices_show,
};
static int dasd_devices_open(struct inode *inode, struct file *file)
{
return seq_open(file, &dasd_devices_seq_ops);
}
static const struct file_operations dasd_devices_file_ops = {
.owner = THIS_MODULE,
.open = dasd_devices_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static int
dasd_calc_metrics(char *page, char **start, off_t off,
int count, int *eof, int len)
{
len = (len > off) ? len - off : 0;
if (len > count)
len = count;
if (len < count)
*eof = 1;
*start = page + off;
return len;
}
#ifdef CONFIG_DASD_PROFILE
static int dasd_stats_all_block_on(void)
{
int i, rc;
struct dasd_device *device;
rc = 0;
for (i = 0; i < dasd_max_devindex; ++i) {
device = dasd_device_from_devindex(i);
if (IS_ERR(device))
continue;
if (device->block)
rc = dasd_profile_on(&device->block->profile);
dasd_put_device(device);
if (rc)
return rc;
}
return 0;
}
static void dasd_stats_all_block_off(void)
{
int i;
struct dasd_device *device;
for (i = 0; i < dasd_max_devindex; ++i) {
device = dasd_device_from_devindex(i);
if (IS_ERR(device))
continue;
if (device->block)
dasd_profile_off(&device->block->profile);
dasd_put_device(device);
}
}
static void dasd_stats_all_block_reset(void)
{
int i;
struct dasd_device *device;
for (i = 0; i < dasd_max_devindex; ++i) {
device = dasd_device_from_devindex(i);
if (IS_ERR(device))
continue;
if (device->block)
dasd_profile_reset(&device->block->profile);
dasd_put_device(device);
}
}
static char *
dasd_statistics_array(char *str, unsigned int *array, int factor)
{
int i;
for (i = 0; i < 32; i++) {
str += sprintf(str, "%7d ", array[i] / factor);
if (i == 15)
str += sprintf(str, "\n");
}
str += sprintf(str,"\n");
return str;
}
#endif /* CONFIG_DASD_PROFILE */
static int
dasd_statistics_read(char *page, char **start, off_t off,
int count, int *eof, void *data)
{
unsigned long len;
#ifdef CONFIG_DASD_PROFILE
struct dasd_profile_info *prof;
char *str;
int factor;
/* check for active profiling */
if (!dasd_global_profile_level) {
len = sprintf(page, "Statistics are off - they might be "
"switched on using 'echo set on > "
"/proc/dasd/statistics'\n");
return dasd_calc_metrics(page, start, off, count, eof, len);
}
prof = &dasd_global_profile_data;
/* prevent couter 'overflow' on output */
for (factor = 1; (prof->dasd_io_reqs / factor) > 9999999;
factor *= 10);
str = page;
str += sprintf(str, "%d dasd I/O requests\n", prof->dasd_io_reqs);
str += sprintf(str, "with %u sectors(512B each)\n",
prof->dasd_io_sects);
str += sprintf(str, "Scale Factor is %d\n", factor);
str += sprintf(str,
" __<4 ___8 __16 __32 __64 _128 "
" _256 _512 __1k __2k __4k __8k "
" _16k _32k _64k 128k\n");
str += sprintf(str,
" _256 _512 __1M __2M __4M __8M "
" _16M _32M _64M 128M 256M 512M "
" __1G __2G __4G " " _>4G\n");
str += sprintf(str, "Histogram of sizes (512B secs)\n");
str = dasd_statistics_array(str, prof->dasd_io_secs, factor);
str += sprintf(str, "Histogram of I/O times (microseconds)\n");
str = dasd_statistics_array(str, prof->dasd_io_times, factor);
str += sprintf(str, "Histogram of I/O times per sector\n");
str = dasd_statistics_array(str, prof->dasd_io_timps, factor);
str += sprintf(str, "Histogram of I/O time till ssch\n");
str = dasd_statistics_array(str, prof->dasd_io_time1, factor);
str += sprintf(str, "Histogram of I/O time between ssch and irq\n");
str = dasd_statistics_array(str, prof->dasd_io_time2, factor);
str += sprintf(str, "Histogram of I/O time between ssch "
"and irq per sector\n");
str = dasd_statistics_array(str, prof->dasd_io_time2ps, factor);
str += sprintf(str, "Histogram of I/O time between irq and end\n");
str = dasd_statistics_array(str, prof->dasd_io_time3, factor);
str += sprintf(str, "# of req in chanq at enqueuing (1..32) \n");
str = dasd_statistics_array(str, prof->dasd_io_nr_req, factor);
len = str - page;
#else
len = sprintf(page, "Statistics are not activated in this kernel\n");
#endif
return dasd_calc_metrics(page, start, off, count, eof, len);
}
static int
dasd_statistics_write(struct file *file, const char __user *user_buf,
unsigned long user_len, void *data)
{
#ifdef CONFIG_DASD_PROFILE
char *buffer, *str;
int rc;
if (user_len > 65536)
user_len = 65536;
buffer = dasd_get_user_string(user_buf, user_len);
if (IS_ERR(buffer))
return PTR_ERR(buffer);
DBF_EVENT(DBF_DEBUG, "/proc/dasd/statictics: '%s'\n", buffer);
/* check for valid verbs */
str = skip_spaces(buffer);
if (strncmp(str, "set", 3) == 0 && isspace(str[3])) {
/* 'set xxx' was given */
str = skip_spaces(str + 4);
if (strcmp(str, "on") == 0) {
/* switch on statistics profiling */
rc = dasd_stats_all_block_on();
if (rc) {
dasd_stats_all_block_off();
goto out_error;
}
dasd_global_profile_reset();
dasd_global_profile_level = DASD_PROFILE_ON;
pr_info("The statistics feature has been switched "
"on\n");
} else if (strcmp(str, "off") == 0) {
/* switch off and reset statistics profiling */
dasd_global_profile_level = DASD_PROFILE_OFF;
dasd_global_profile_reset();
dasd_stats_all_block_off();
pr_info("The statistics feature has been switched "
"off\n");
} else
goto out_parse_error;
} else if (strncmp(str, "reset", 5) == 0) {
/* reset the statistics */
dasd_global_profile_reset();
dasd_stats_all_block_reset();
pr_info("The statistics have been reset\n");
} else
goto out_parse_error;
vfree(buffer);
return user_len;
out_parse_error:
rc = -EINVAL;
pr_warning("%s is not a supported value for /proc/dasd/statistics\n",
str);
out_error:
vfree(buffer);
return rc;
#else
pr_warning("/proc/dasd/statistics: is not activated in this kernel\n");
return user_len;
#endif /* CONFIG_DASD_PROFILE */
}
/*
* Create dasd proc-fs entries.
* In case creation failed, cleanup and return -ENOENT.
*/
int
dasd_proc_init(void)
{
dasd_proc_root_entry = proc_mkdir("dasd", NULL);
if (!dasd_proc_root_entry)
goto out_nodasd;
dasd_devices_entry = proc_create("devices",
S_IFREG | S_IRUGO | S_IWUSR,
dasd_proc_root_entry,
&dasd_devices_file_ops);
if (!dasd_devices_entry)
goto out_nodevices;
dasd_statistics_entry = create_proc_entry("statistics",
S_IFREG | S_IRUGO | S_IWUSR,
dasd_proc_root_entry);
if (!dasd_statistics_entry)
goto out_nostatistics;
dasd_statistics_entry->read_proc = dasd_statistics_read;
dasd_statistics_entry->write_proc = dasd_statistics_write;
return 0;
out_nostatistics:
remove_proc_entry("devices", dasd_proc_root_entry);
out_nodevices:
remove_proc_entry("dasd", NULL);
out_nodasd:
return -ENOENT;
}
void
dasd_proc_exit(void)
{
remove_proc_entry("devices", dasd_proc_root_entry);
remove_proc_entry("statistics", dasd_proc_root_entry);
remove_proc_entry("dasd", NULL);
}
| gpl-2.0 |
locnp13/linux | drivers/gpu/drm/nouveau/nvkm/core/client.c | 547 | 6799 | /*
* Copyright 2012 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include <core/client.h>
#include <core/device.h>
#include <core/handle.h>
#include <core/notify.h>
#include <core/option.h>
#include <nvif/class.h>
#include <nvif/event.h>
#include <nvif/unpack.h>
struct nvkm_client_notify {
struct nvkm_client *client;
struct nvkm_notify n;
u8 version;
u8 size;
union {
struct nvif_notify_rep_v0 v0;
} rep;
};
static int
nvkm_client_notify(struct nvkm_notify *n)
{
struct nvkm_client_notify *notify = container_of(n, typeof(*notify), n);
struct nvkm_client *client = notify->client;
return client->ntfy(¬ify->rep, notify->size, n->data, n->size);
}
int
nvkm_client_notify_put(struct nvkm_client *client, int index)
{
if (index < ARRAY_SIZE(client->notify)) {
if (client->notify[index]) {
nvkm_notify_put(&client->notify[index]->n);
return 0;
}
}
return -ENOENT;
}
int
nvkm_client_notify_get(struct nvkm_client *client, int index)
{
if (index < ARRAY_SIZE(client->notify)) {
if (client->notify[index]) {
nvkm_notify_get(&client->notify[index]->n);
return 0;
}
}
return -ENOENT;
}
int
nvkm_client_notify_del(struct nvkm_client *client, int index)
{
if (index < ARRAY_SIZE(client->notify)) {
if (client->notify[index]) {
nvkm_notify_fini(&client->notify[index]->n);
kfree(client->notify[index]);
client->notify[index] = NULL;
return 0;
}
}
return -ENOENT;
}
int
nvkm_client_notify_new(struct nvkm_object *object,
struct nvkm_event *event, void *data, u32 size)
{
struct nvkm_client *client = nvkm_client(object);
struct nvkm_client_notify *notify;
union {
struct nvif_notify_req_v0 v0;
} *req = data;
u8 index, reply;
int ret;
for (index = 0; index < ARRAY_SIZE(client->notify); index++) {
if (!client->notify[index])
break;
}
if (index == ARRAY_SIZE(client->notify))
return -ENOSPC;
notify = kzalloc(sizeof(*notify), GFP_KERNEL);
if (!notify)
return -ENOMEM;
nv_ioctl(client, "notify new size %d\n", size);
if (nvif_unpack(req->v0, 0, 0, true)) {
nv_ioctl(client, "notify new vers %d reply %d route %02x "
"token %llx\n", req->v0.version,
req->v0.reply, req->v0.route, req->v0.token);
notify->version = req->v0.version;
notify->size = sizeof(notify->rep.v0);
notify->rep.v0.version = req->v0.version;
notify->rep.v0.route = req->v0.route;
notify->rep.v0.token = req->v0.token;
reply = req->v0.reply;
}
if (ret == 0) {
ret = nvkm_notify_init(object, event, nvkm_client_notify,
false, data, size, reply, ¬ify->n);
if (ret == 0) {
client->notify[index] = notify;
notify->client = client;
return index;
}
}
kfree(notify);
return ret;
}
static int
nvkm_client_mthd_devlist(struct nvkm_object *object, void *data, u32 size)
{
union {
struct nv_client_devlist_v0 v0;
} *args = data;
int ret;
nv_ioctl(object, "client devlist size %d\n", size);
if (nvif_unpack(args->v0, 0, 0, true)) {
nv_ioctl(object, "client devlist vers %d count %d\n",
args->v0.version, args->v0.count);
if (size == sizeof(args->v0.device[0]) * args->v0.count) {
ret = nvkm_device_list(args->v0.device, args->v0.count);
if (ret >= 0) {
args->v0.count = ret;
ret = 0;
}
} else {
ret = -EINVAL;
}
}
return ret;
}
static int
nvkm_client_mthd(struct nvkm_object *object, u32 mthd, void *data, u32 size)
{
switch (mthd) {
case NV_CLIENT_DEVLIST:
return nvkm_client_mthd_devlist(object, data, size);
default:
break;
}
return -EINVAL;
}
static void
nvkm_client_dtor(struct nvkm_object *object)
{
struct nvkm_client *client = (void *)object;
int i;
for (i = 0; i < ARRAY_SIZE(client->notify); i++)
nvkm_client_notify_del(client, i);
nvkm_object_ref(NULL, &client->device);
nvkm_handle_destroy(client->root);
nvkm_namedb_destroy(&client->namedb);
}
static struct nvkm_oclass
nvkm_client_oclass = {
.ofuncs = &(struct nvkm_ofuncs) {
.dtor = nvkm_client_dtor,
.mthd = nvkm_client_mthd,
},
};
int
nvkm_client_create_(const char *name, u64 devname, const char *cfg,
const char *dbg, int length, void **pobject)
{
struct nvkm_object *device;
struct nvkm_client *client;
int ret;
device = (void *)nvkm_device_find(devname);
if (!device)
return -ENODEV;
ret = nvkm_namedb_create_(NULL, NULL, &nvkm_client_oclass,
NV_CLIENT_CLASS, NULL,
(1ULL << NVDEV_ENGINE_DEVICE),
length, pobject);
client = *pobject;
if (ret)
return ret;
ret = nvkm_handle_create(nv_object(client), ~0, ~0, nv_object(client),
&client->root);
if (ret)
return ret;
/* prevent init/fini being called, os in in charge of this */
atomic_set(&nv_object(client)->usecount, 2);
nvkm_object_ref(device, &client->device);
snprintf(client->name, sizeof(client->name), "%s", name);
client->debug = nvkm_dbgopt(dbg, "CLIENT");
return 0;
}
int
nvkm_client_init(struct nvkm_client *client)
{
int ret;
nv_debug(client, "init running\n");
ret = nvkm_handle_init(client->root);
nv_debug(client, "init completed with %d\n", ret);
return ret;
}
int
nvkm_client_fini(struct nvkm_client *client, bool suspend)
{
const char *name[2] = { "fini", "suspend" };
int ret, i;
nv_debug(client, "%s running\n", name[suspend]);
nv_debug(client, "%s notify\n", name[suspend]);
for (i = 0; i < ARRAY_SIZE(client->notify); i++)
nvkm_client_notify_put(client, i);
nv_debug(client, "%s object\n", name[suspend]);
ret = nvkm_handle_fini(client->root, suspend);
nv_debug(client, "%s completed with %d\n", name[suspend], ret);
return ret;
}
const char *
nvkm_client_name(void *obj)
{
const char *client_name = "unknown";
struct nvkm_client *client = nvkm_client(obj);
if (client)
client_name = client->name;
return client_name;
}
| gpl-2.0 |
playfulgod/tiamat-8x60-kernel | drivers/xen/balloon.c | 803 | 14919 | /******************************************************************************
* balloon.c
*
* Xen balloon driver - enables returning/claiming memory to/from Xen.
*
* Copyright (c) 2003, B Dragovic
* Copyright (c) 2003-2004, M Williamson, K Fraser
* Copyright (c) 2005 Dan M. Smith, 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; or, when distributed
* separately from the Linux kernel or incorporated into other
* software packages, subject to the following license:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this source file (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <linux/bootmem.h>
#include <linux/pagemap.h>
#include <linux/highmem.h>
#include <linux/mutex.h>
#include <linux/list.h>
#include <linux/sysdev.h>
#include <linux/gfp.h>
#include <asm/page.h>
#include <asm/pgalloc.h>
#include <asm/pgtable.h>
#include <asm/uaccess.h>
#include <asm/tlb.h>
#include <asm/xen/hypervisor.h>
#include <asm/xen/hypercall.h>
#include <xen/xen.h>
#include <xen/interface/xen.h>
#include <xen/interface/memory.h>
#include <xen/xenbus.h>
#include <xen/features.h>
#include <xen/page.h>
#define PAGES2KB(_p) ((_p)<<(PAGE_SHIFT-10))
#define BALLOON_CLASS_NAME "xen_memory"
struct balloon_stats {
/* We aim for 'current allocation' == 'target allocation'. */
unsigned long current_pages;
unsigned long target_pages;
/*
* Drivers may alter the memory reservation independently, but they
* must inform the balloon driver so we avoid hitting the hard limit.
*/
unsigned long driver_pages;
/* Number of pages in high- and low-memory balloons. */
unsigned long balloon_low;
unsigned long balloon_high;
};
static DEFINE_MUTEX(balloon_mutex);
static struct sys_device balloon_sysdev;
static int register_balloon(struct sys_device *sysdev);
/*
* Protects atomic reservation decrease/increase against concurrent increases.
* Also protects non-atomic updates of current_pages and driver_pages, and
* balloon lists.
*/
static DEFINE_SPINLOCK(balloon_lock);
static struct balloon_stats balloon_stats;
/* We increase/decrease in batches which fit in a page */
static unsigned long frame_list[PAGE_SIZE / sizeof(unsigned long)];
#ifdef CONFIG_HIGHMEM
#define inc_totalhigh_pages() (totalhigh_pages++)
#define dec_totalhigh_pages() (totalhigh_pages--)
#else
#define inc_totalhigh_pages() do {} while(0)
#define dec_totalhigh_pages() do {} while(0)
#endif
/* List of ballooned pages, threaded through the mem_map array. */
static LIST_HEAD(ballooned_pages);
/* Main work function, always executed in process context. */
static void balloon_process(struct work_struct *work);
static DECLARE_WORK(balloon_worker, balloon_process);
static struct timer_list balloon_timer;
/* When ballooning out (allocating memory to return to Xen) we don't really
want the kernel to try too hard since that can trigger the oom killer. */
#define GFP_BALLOON \
(GFP_HIGHUSER | __GFP_NOWARN | __GFP_NORETRY | __GFP_NOMEMALLOC)
static void scrub_page(struct page *page)
{
#ifdef CONFIG_XEN_SCRUB_PAGES
clear_highpage(page);
#endif
}
/* balloon_append: add the given page to the balloon. */
static void balloon_append(struct page *page)
{
/* Lowmem is re-populated first, so highmem pages go at list tail. */
if (PageHighMem(page)) {
list_add_tail(&page->lru, &ballooned_pages);
balloon_stats.balloon_high++;
dec_totalhigh_pages();
} else {
list_add(&page->lru, &ballooned_pages);
balloon_stats.balloon_low++;
}
totalram_pages--;
}
/* balloon_retrieve: rescue a page from the balloon, if it is not empty. */
static struct page *balloon_retrieve(void)
{
struct page *page;
if (list_empty(&ballooned_pages))
return NULL;
page = list_entry(ballooned_pages.next, struct page, lru);
list_del(&page->lru);
if (PageHighMem(page)) {
balloon_stats.balloon_high--;
inc_totalhigh_pages();
}
else
balloon_stats.balloon_low--;
totalram_pages++;
return page;
}
static struct page *balloon_first_page(void)
{
if (list_empty(&ballooned_pages))
return NULL;
return list_entry(ballooned_pages.next, struct page, lru);
}
static struct page *balloon_next_page(struct page *page)
{
struct list_head *next = page->lru.next;
if (next == &ballooned_pages)
return NULL;
return list_entry(next, struct page, lru);
}
static void balloon_alarm(unsigned long unused)
{
schedule_work(&balloon_worker);
}
static unsigned long current_target(void)
{
unsigned long target = balloon_stats.target_pages;
target = min(target,
balloon_stats.current_pages +
balloon_stats.balloon_low +
balloon_stats.balloon_high);
return target;
}
static int increase_reservation(unsigned long nr_pages)
{
unsigned long pfn, i, flags;
struct page *page;
long rc;
struct xen_memory_reservation reservation = {
.address_bits = 0,
.extent_order = 0,
.domid = DOMID_SELF
};
if (nr_pages > ARRAY_SIZE(frame_list))
nr_pages = ARRAY_SIZE(frame_list);
spin_lock_irqsave(&balloon_lock, flags);
page = balloon_first_page();
for (i = 0; i < nr_pages; i++) {
BUG_ON(page == NULL);
frame_list[i] = page_to_pfn(page);
page = balloon_next_page(page);
}
set_xen_guest_handle(reservation.extent_start, frame_list);
reservation.nr_extents = nr_pages;
rc = HYPERVISOR_memory_op(XENMEM_populate_physmap, &reservation);
if (rc < 0)
goto out;
for (i = 0; i < rc; i++) {
page = balloon_retrieve();
BUG_ON(page == NULL);
pfn = page_to_pfn(page);
BUG_ON(!xen_feature(XENFEAT_auto_translated_physmap) &&
phys_to_machine_mapping_valid(pfn));
set_phys_to_machine(pfn, frame_list[i]);
/* Link back into the page tables if not highmem. */
if (pfn < max_low_pfn) {
int ret;
ret = HYPERVISOR_update_va_mapping(
(unsigned long)__va(pfn << PAGE_SHIFT),
mfn_pte(frame_list[i], PAGE_KERNEL),
0);
BUG_ON(ret);
}
/* Relinquish the page back to the allocator. */
ClearPageReserved(page);
init_page_count(page);
__free_page(page);
}
balloon_stats.current_pages += rc;
out:
spin_unlock_irqrestore(&balloon_lock, flags);
return rc < 0 ? rc : rc != nr_pages;
}
static int decrease_reservation(unsigned long nr_pages)
{
unsigned long pfn, i, flags;
struct page *page;
int need_sleep = 0;
int ret;
struct xen_memory_reservation reservation = {
.address_bits = 0,
.extent_order = 0,
.domid = DOMID_SELF
};
if (nr_pages > ARRAY_SIZE(frame_list))
nr_pages = ARRAY_SIZE(frame_list);
for (i = 0; i < nr_pages; i++) {
if ((page = alloc_page(GFP_BALLOON)) == NULL) {
nr_pages = i;
need_sleep = 1;
break;
}
pfn = page_to_pfn(page);
frame_list[i] = pfn_to_mfn(pfn);
scrub_page(page);
if (!PageHighMem(page)) {
ret = HYPERVISOR_update_va_mapping(
(unsigned long)__va(pfn << PAGE_SHIFT),
__pte_ma(0), 0);
BUG_ON(ret);
}
}
/* Ensure that ballooned highmem pages don't have kmaps. */
kmap_flush_unused();
flush_tlb_all();
spin_lock_irqsave(&balloon_lock, flags);
/* No more mappings: invalidate P2M and add to balloon. */
for (i = 0; i < nr_pages; i++) {
pfn = mfn_to_pfn(frame_list[i]);
set_phys_to_machine(pfn, INVALID_P2M_ENTRY);
balloon_append(pfn_to_page(pfn));
}
set_xen_guest_handle(reservation.extent_start, frame_list);
reservation.nr_extents = nr_pages;
ret = HYPERVISOR_memory_op(XENMEM_decrease_reservation, &reservation);
BUG_ON(ret != nr_pages);
balloon_stats.current_pages -= nr_pages;
spin_unlock_irqrestore(&balloon_lock, flags);
return need_sleep;
}
/*
* We avoid multiple worker processes conflicting via the balloon mutex.
* We may of course race updates of the target counts (which are protected
* by the balloon lock), or with changes to the Xen hard limit, but we will
* recover from these in time.
*/
static void balloon_process(struct work_struct *work)
{
int need_sleep = 0;
long credit;
mutex_lock(&balloon_mutex);
do {
credit = current_target() - balloon_stats.current_pages;
if (credit > 0)
need_sleep = (increase_reservation(credit) != 0);
if (credit < 0)
need_sleep = (decrease_reservation(-credit) != 0);
#ifndef CONFIG_PREEMPT
if (need_resched())
schedule();
#endif
} while ((credit != 0) && !need_sleep);
/* Schedule more work if there is some still to be done. */
if (current_target() != balloon_stats.current_pages)
mod_timer(&balloon_timer, jiffies + HZ);
mutex_unlock(&balloon_mutex);
}
/* Resets the Xen limit, sets new target, and kicks off processing. */
static void balloon_set_new_target(unsigned long target)
{
/* No need for lock. Not read-modify-write updates. */
balloon_stats.target_pages = target;
schedule_work(&balloon_worker);
}
static struct xenbus_watch target_watch =
{
.node = "memory/target"
};
/* React to a change in the target key */
static void watch_target(struct xenbus_watch *watch,
const char **vec, unsigned int len)
{
unsigned long long new_target;
int err;
err = xenbus_scanf(XBT_NIL, "memory", "target", "%llu", &new_target);
if (err != 1) {
/* This is ok (for domain0 at least) - so just return */
return;
}
/* The given memory/target value is in KiB, so it needs converting to
* pages. PAGE_SHIFT converts bytes to pages, hence PAGE_SHIFT - 10.
*/
balloon_set_new_target(new_target >> (PAGE_SHIFT - 10));
}
static int balloon_init_watcher(struct notifier_block *notifier,
unsigned long event,
void *data)
{
int err;
err = register_xenbus_watch(&target_watch);
if (err)
printk(KERN_ERR "Failed to set balloon watcher\n");
return NOTIFY_DONE;
}
static struct notifier_block xenstore_notifier;
static int __init balloon_init(void)
{
unsigned long pfn;
struct page *page;
if (!xen_pv_domain())
return -ENODEV;
pr_info("xen_balloon: Initialising balloon driver.\n");
balloon_stats.current_pages = min(xen_start_info->nr_pages, max_pfn);
balloon_stats.target_pages = balloon_stats.current_pages;
balloon_stats.balloon_low = 0;
balloon_stats.balloon_high = 0;
balloon_stats.driver_pages = 0UL;
init_timer(&balloon_timer);
balloon_timer.data = 0;
balloon_timer.function = balloon_alarm;
register_balloon(&balloon_sysdev);
/* Initialise the balloon with excess memory space. */
for (pfn = xen_start_info->nr_pages; pfn < max_pfn; pfn++) {
page = pfn_to_page(pfn);
if (!PageReserved(page))
balloon_append(page);
}
target_watch.callback = watch_target;
xenstore_notifier.notifier_call = balloon_init_watcher;
register_xenstore_notifier(&xenstore_notifier);
return 0;
}
subsys_initcall(balloon_init);
static void balloon_exit(void)
{
/* XXX - release balloon here */
return;
}
module_exit(balloon_exit);
#define BALLOON_SHOW(name, format, args...) \
static ssize_t show_##name(struct sys_device *dev, \
struct sysdev_attribute *attr, \
char *buf) \
{ \
return sprintf(buf, format, ##args); \
} \
static SYSDEV_ATTR(name, S_IRUGO, show_##name, NULL)
BALLOON_SHOW(current_kb, "%lu\n", PAGES2KB(balloon_stats.current_pages));
BALLOON_SHOW(low_kb, "%lu\n", PAGES2KB(balloon_stats.balloon_low));
BALLOON_SHOW(high_kb, "%lu\n", PAGES2KB(balloon_stats.balloon_high));
BALLOON_SHOW(driver_kb, "%lu\n", PAGES2KB(balloon_stats.driver_pages));
static ssize_t show_target_kb(struct sys_device *dev, struct sysdev_attribute *attr,
char *buf)
{
return sprintf(buf, "%lu\n", PAGES2KB(balloon_stats.target_pages));
}
static ssize_t store_target_kb(struct sys_device *dev,
struct sysdev_attribute *attr,
const char *buf,
size_t count)
{
char *endchar;
unsigned long long target_bytes;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
target_bytes = simple_strtoull(buf, &endchar, 0) * 1024;
balloon_set_new_target(target_bytes >> PAGE_SHIFT);
return count;
}
static SYSDEV_ATTR(target_kb, S_IRUGO | S_IWUSR,
show_target_kb, store_target_kb);
static ssize_t show_target(struct sys_device *dev, struct sysdev_attribute *attr,
char *buf)
{
return sprintf(buf, "%llu\n",
(unsigned long long)balloon_stats.target_pages
<< PAGE_SHIFT);
}
static ssize_t store_target(struct sys_device *dev,
struct sysdev_attribute *attr,
const char *buf,
size_t count)
{
char *endchar;
unsigned long long target_bytes;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
target_bytes = memparse(buf, &endchar);
balloon_set_new_target(target_bytes >> PAGE_SHIFT);
return count;
}
static SYSDEV_ATTR(target, S_IRUGO | S_IWUSR,
show_target, store_target);
static struct sysdev_attribute *balloon_attrs[] = {
&attr_target_kb,
&attr_target,
};
static struct attribute *balloon_info_attrs[] = {
&attr_current_kb.attr,
&attr_low_kb.attr,
&attr_high_kb.attr,
&attr_driver_kb.attr,
NULL
};
static struct attribute_group balloon_info_group = {
.name = "info",
.attrs = balloon_info_attrs,
};
static struct sysdev_class balloon_sysdev_class = {
.name = BALLOON_CLASS_NAME,
};
static int register_balloon(struct sys_device *sysdev)
{
int i, error;
error = sysdev_class_register(&balloon_sysdev_class);
if (error)
return error;
sysdev->id = 0;
sysdev->cls = &balloon_sysdev_class;
error = sysdev_register(sysdev);
if (error) {
sysdev_class_unregister(&balloon_sysdev_class);
return error;
}
for (i = 0; i < ARRAY_SIZE(balloon_attrs); i++) {
error = sysdev_create_file(sysdev, balloon_attrs[i]);
if (error)
goto fail;
}
error = sysfs_create_group(&sysdev->kobj, &balloon_info_group);
if (error)
goto fail;
return 0;
fail:
while (--i >= 0)
sysdev_remove_file(sysdev, balloon_attrs[i]);
sysdev_unregister(sysdev);
sysdev_class_unregister(&balloon_sysdev_class);
return error;
}
MODULE_LICENSE("GPL");
| gpl-2.0 |
Snuzzo/Vigor-Incredikernel | block/compat_ioctl.c | 803 | 22672 | #include <linux/blkdev.h>
#include <linux/blkpg.h>
#include <linux/blktrace_api.h>
#include <linux/cdrom.h>
#include <linux/compat.h>
#include <linux/elevator.h>
#include <linux/fd.h>
#include <linux/hdreg.h>
#include <linux/slab.h>
#include <linux/syscalls.h>
#include <linux/smp_lock.h>
#include <linux/types.h>
#include <linux/uaccess.h>
static int compat_put_ushort(unsigned long arg, unsigned short val)
{
return put_user(val, (unsigned short __user *)compat_ptr(arg));
}
static int compat_put_int(unsigned long arg, int val)
{
return put_user(val, (compat_int_t __user *)compat_ptr(arg));
}
static int compat_put_uint(unsigned long arg, unsigned int val)
{
return put_user(val, (compat_uint_t __user *)compat_ptr(arg));
}
static int compat_put_long(unsigned long arg, long val)
{
return put_user(val, (compat_long_t __user *)compat_ptr(arg));
}
static int compat_put_ulong(unsigned long arg, compat_ulong_t val)
{
return put_user(val, (compat_ulong_t __user *)compat_ptr(arg));
}
static int compat_put_u64(unsigned long arg, u64 val)
{
return put_user(val, (compat_u64 __user *)compat_ptr(arg));
}
struct compat_hd_geometry {
unsigned char heads;
unsigned char sectors;
unsigned short cylinders;
u32 start;
};
static int compat_hdio_getgeo(struct gendisk *disk, struct block_device *bdev,
struct compat_hd_geometry __user *ugeo)
{
struct hd_geometry geo;
int ret;
if (!ugeo)
return -EINVAL;
if (!disk->fops->getgeo)
return -ENOTTY;
/*
* We need to set the startsect first, the driver may
* want to override it.
*/
geo.start = get_start_sect(bdev);
ret = disk->fops->getgeo(bdev, &geo);
if (ret)
return ret;
ret = copy_to_user(ugeo, &geo, 4);
ret |= __put_user(geo.start, &ugeo->start);
if (ret)
ret = -EFAULT;
return ret;
}
static int compat_hdio_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
mm_segment_t old_fs = get_fs();
unsigned long kval;
unsigned int __user *uvp;
int error;
set_fs(KERNEL_DS);
error = __blkdev_driver_ioctl(bdev, mode,
cmd, (unsigned long)(&kval));
set_fs(old_fs);
if (error == 0) {
uvp = compat_ptr(arg);
if (put_user(kval, uvp))
error = -EFAULT;
}
return error;
}
struct compat_cdrom_read_audio {
union cdrom_addr addr;
u8 addr_format;
compat_int_t nframes;
compat_caddr_t buf;
};
struct compat_cdrom_generic_command {
unsigned char cmd[CDROM_PACKET_SIZE];
compat_caddr_t buffer;
compat_uint_t buflen;
compat_int_t stat;
compat_caddr_t sense;
unsigned char data_direction;
compat_int_t quiet;
compat_int_t timeout;
compat_caddr_t reserved[1];
};
static int compat_cdrom_read_audio(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
struct cdrom_read_audio __user *cdread_audio;
struct compat_cdrom_read_audio __user *cdread_audio32;
__u32 data;
void __user *datap;
cdread_audio = compat_alloc_user_space(sizeof(*cdread_audio));
cdread_audio32 = compat_ptr(arg);
if (copy_in_user(&cdread_audio->addr,
&cdread_audio32->addr,
(sizeof(*cdread_audio32) -
sizeof(compat_caddr_t))))
return -EFAULT;
if (get_user(data, &cdread_audio32->buf))
return -EFAULT;
datap = compat_ptr(data);
if (put_user(datap, &cdread_audio->buf))
return -EFAULT;
return __blkdev_driver_ioctl(bdev, mode, cmd,
(unsigned long)cdread_audio);
}
static int compat_cdrom_generic_command(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
struct cdrom_generic_command __user *cgc;
struct compat_cdrom_generic_command __user *cgc32;
u32 data;
unsigned char dir;
int itmp;
cgc = compat_alloc_user_space(sizeof(*cgc));
cgc32 = compat_ptr(arg);
if (copy_in_user(&cgc->cmd, &cgc32->cmd, sizeof(cgc->cmd)) ||
get_user(data, &cgc32->buffer) ||
put_user(compat_ptr(data), &cgc->buffer) ||
copy_in_user(&cgc->buflen, &cgc32->buflen,
(sizeof(unsigned int) + sizeof(int))) ||
get_user(data, &cgc32->sense) ||
put_user(compat_ptr(data), &cgc->sense) ||
get_user(dir, &cgc32->data_direction) ||
put_user(dir, &cgc->data_direction) ||
get_user(itmp, &cgc32->quiet) ||
put_user(itmp, &cgc->quiet) ||
get_user(itmp, &cgc32->timeout) ||
put_user(itmp, &cgc->timeout) ||
get_user(data, &cgc32->reserved[0]) ||
put_user(compat_ptr(data), &cgc->reserved[0]))
return -EFAULT;
return __blkdev_driver_ioctl(bdev, mode, cmd, (unsigned long)cgc);
}
struct compat_blkpg_ioctl_arg {
compat_int_t op;
compat_int_t flags;
compat_int_t datalen;
compat_caddr_t data;
};
static int compat_blkpg_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, struct compat_blkpg_ioctl_arg __user *ua32)
{
struct blkpg_ioctl_arg __user *a = compat_alloc_user_space(sizeof(*a));
compat_caddr_t udata;
compat_int_t n;
int err;
err = get_user(n, &ua32->op);
err |= put_user(n, &a->op);
err |= get_user(n, &ua32->flags);
err |= put_user(n, &a->flags);
err |= get_user(n, &ua32->datalen);
err |= put_user(n, &a->datalen);
err |= get_user(udata, &ua32->data);
err |= put_user(compat_ptr(udata), &a->data);
if (err)
return err;
return blkdev_ioctl(bdev, mode, cmd, (unsigned long)a);
}
#define BLKBSZGET_32 _IOR(0x12, 112, int)
#define BLKBSZSET_32 _IOW(0x12, 113, int)
#define BLKGETSIZE64_32 _IOR(0x12, 114, int)
struct compat_floppy_struct {
compat_uint_t size;
compat_uint_t sect;
compat_uint_t head;
compat_uint_t track;
compat_uint_t stretch;
unsigned char gap;
unsigned char rate;
unsigned char spec1;
unsigned char fmt_gap;
const compat_caddr_t name;
};
struct compat_floppy_drive_params {
char cmos;
compat_ulong_t max_dtr;
compat_ulong_t hlt;
compat_ulong_t hut;
compat_ulong_t srt;
compat_ulong_t spinup;
compat_ulong_t spindown;
unsigned char spindown_offset;
unsigned char select_delay;
unsigned char rps;
unsigned char tracks;
compat_ulong_t timeout;
unsigned char interleave_sect;
struct floppy_max_errors max_errors;
char flags;
char read_track;
short autodetect[8];
compat_int_t checkfreq;
compat_int_t native_format;
};
struct compat_floppy_drive_struct {
signed char flags;
compat_ulong_t spinup_date;
compat_ulong_t select_date;
compat_ulong_t first_read_date;
short probed_format;
short track;
short maxblock;
short maxtrack;
compat_int_t generation;
compat_int_t keep_data;
compat_int_t fd_ref;
compat_int_t fd_device;
compat_int_t last_checked;
compat_caddr_t dmabuf;
compat_int_t bufblocks;
};
struct compat_floppy_fdc_state {
compat_int_t spec1;
compat_int_t spec2;
compat_int_t dtr;
unsigned char version;
unsigned char dor;
compat_ulong_t address;
unsigned int rawcmd:2;
unsigned int reset:1;
unsigned int need_configure:1;
unsigned int perp_mode:2;
unsigned int has_fifo:1;
unsigned int driver_version;
unsigned char track[4];
};
struct compat_floppy_write_errors {
unsigned int write_errors;
compat_ulong_t first_error_sector;
compat_int_t first_error_generation;
compat_ulong_t last_error_sector;
compat_int_t last_error_generation;
compat_uint_t badness;
};
#define FDSETPRM32 _IOW(2, 0x42, struct compat_floppy_struct)
#define FDDEFPRM32 _IOW(2, 0x43, struct compat_floppy_struct)
#define FDGETPRM32 _IOR(2, 0x04, struct compat_floppy_struct)
#define FDSETDRVPRM32 _IOW(2, 0x90, struct compat_floppy_drive_params)
#define FDGETDRVPRM32 _IOR(2, 0x11, struct compat_floppy_drive_params)
#define FDGETDRVSTAT32 _IOR(2, 0x12, struct compat_floppy_drive_struct)
#define FDPOLLDRVSTAT32 _IOR(2, 0x13, struct compat_floppy_drive_struct)
#define FDGETFDCSTAT32 _IOR(2, 0x15, struct compat_floppy_fdc_state)
#define FDWERRORGET32 _IOR(2, 0x17, struct compat_floppy_write_errors)
static struct {
unsigned int cmd32;
unsigned int cmd;
} fd_ioctl_trans_table[] = {
{ FDSETPRM32, FDSETPRM },
{ FDDEFPRM32, FDDEFPRM },
{ FDGETPRM32, FDGETPRM },
{ FDSETDRVPRM32, FDSETDRVPRM },
{ FDGETDRVPRM32, FDGETDRVPRM },
{ FDGETDRVSTAT32, FDGETDRVSTAT },
{ FDPOLLDRVSTAT32, FDPOLLDRVSTAT },
{ FDGETFDCSTAT32, FDGETFDCSTAT },
{ FDWERRORGET32, FDWERRORGET }
};
#define NR_FD_IOCTL_TRANS ARRAY_SIZE(fd_ioctl_trans_table)
static int compat_fd_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
mm_segment_t old_fs = get_fs();
void *karg = NULL;
unsigned int kcmd = 0;
int i, err;
for (i = 0; i < NR_FD_IOCTL_TRANS; i++)
if (cmd == fd_ioctl_trans_table[i].cmd32) {
kcmd = fd_ioctl_trans_table[i].cmd;
break;
}
if (!kcmd)
return -EINVAL;
switch (cmd) {
case FDSETPRM32:
case FDDEFPRM32:
case FDGETPRM32:
{
compat_uptr_t name;
struct compat_floppy_struct __user *uf;
struct floppy_struct *f;
uf = compat_ptr(arg);
f = karg = kmalloc(sizeof(struct floppy_struct), GFP_KERNEL);
if (!karg)
return -ENOMEM;
if (cmd == FDGETPRM32)
break;
err = __get_user(f->size, &uf->size);
err |= __get_user(f->sect, &uf->sect);
err |= __get_user(f->head, &uf->head);
err |= __get_user(f->track, &uf->track);
err |= __get_user(f->stretch, &uf->stretch);
err |= __get_user(f->gap, &uf->gap);
err |= __get_user(f->rate, &uf->rate);
err |= __get_user(f->spec1, &uf->spec1);
err |= __get_user(f->fmt_gap, &uf->fmt_gap);
err |= __get_user(name, &uf->name);
f->name = compat_ptr(name);
if (err) {
err = -EFAULT;
goto out;
}
break;
}
case FDSETDRVPRM32:
case FDGETDRVPRM32:
{
struct compat_floppy_drive_params __user *uf;
struct floppy_drive_params *f;
uf = compat_ptr(arg);
f = karg = kmalloc(sizeof(struct floppy_drive_params), GFP_KERNEL);
if (!karg)
return -ENOMEM;
if (cmd == FDGETDRVPRM32)
break;
err = __get_user(f->cmos, &uf->cmos);
err |= __get_user(f->max_dtr, &uf->max_dtr);
err |= __get_user(f->hlt, &uf->hlt);
err |= __get_user(f->hut, &uf->hut);
err |= __get_user(f->srt, &uf->srt);
err |= __get_user(f->spinup, &uf->spinup);
err |= __get_user(f->spindown, &uf->spindown);
err |= __get_user(f->spindown_offset, &uf->spindown_offset);
err |= __get_user(f->select_delay, &uf->select_delay);
err |= __get_user(f->rps, &uf->rps);
err |= __get_user(f->tracks, &uf->tracks);
err |= __get_user(f->timeout, &uf->timeout);
err |= __get_user(f->interleave_sect, &uf->interleave_sect);
err |= __copy_from_user(&f->max_errors, &uf->max_errors, sizeof(f->max_errors));
err |= __get_user(f->flags, &uf->flags);
err |= __get_user(f->read_track, &uf->read_track);
err |= __copy_from_user(f->autodetect, uf->autodetect, sizeof(f->autodetect));
err |= __get_user(f->checkfreq, &uf->checkfreq);
err |= __get_user(f->native_format, &uf->native_format);
if (err) {
err = -EFAULT;
goto out;
}
break;
}
case FDGETDRVSTAT32:
case FDPOLLDRVSTAT32:
karg = kmalloc(sizeof(struct floppy_drive_struct), GFP_KERNEL);
if (!karg)
return -ENOMEM;
break;
case FDGETFDCSTAT32:
karg = kmalloc(sizeof(struct floppy_fdc_state), GFP_KERNEL);
if (!karg)
return -ENOMEM;
break;
case FDWERRORGET32:
karg = kmalloc(sizeof(struct floppy_write_errors), GFP_KERNEL);
if (!karg)
return -ENOMEM;
break;
default:
return -EINVAL;
}
set_fs(KERNEL_DS);
err = __blkdev_driver_ioctl(bdev, mode, kcmd, (unsigned long)karg);
set_fs(old_fs);
if (err)
goto out;
switch (cmd) {
case FDGETPRM32:
{
struct floppy_struct *f = karg;
struct compat_floppy_struct __user *uf = compat_ptr(arg);
err = __put_user(f->size, &uf->size);
err |= __put_user(f->sect, &uf->sect);
err |= __put_user(f->head, &uf->head);
err |= __put_user(f->track, &uf->track);
err |= __put_user(f->stretch, &uf->stretch);
err |= __put_user(f->gap, &uf->gap);
err |= __put_user(f->rate, &uf->rate);
err |= __put_user(f->spec1, &uf->spec1);
err |= __put_user(f->fmt_gap, &uf->fmt_gap);
err |= __put_user((u64)f->name, (compat_caddr_t __user *)&uf->name);
break;
}
case FDGETDRVPRM32:
{
struct compat_floppy_drive_params __user *uf;
struct floppy_drive_params *f = karg;
uf = compat_ptr(arg);
err = __put_user(f->cmos, &uf->cmos);
err |= __put_user(f->max_dtr, &uf->max_dtr);
err |= __put_user(f->hlt, &uf->hlt);
err |= __put_user(f->hut, &uf->hut);
err |= __put_user(f->srt, &uf->srt);
err |= __put_user(f->spinup, &uf->spinup);
err |= __put_user(f->spindown, &uf->spindown);
err |= __put_user(f->spindown_offset, &uf->spindown_offset);
err |= __put_user(f->select_delay, &uf->select_delay);
err |= __put_user(f->rps, &uf->rps);
err |= __put_user(f->tracks, &uf->tracks);
err |= __put_user(f->timeout, &uf->timeout);
err |= __put_user(f->interleave_sect, &uf->interleave_sect);
err |= __copy_to_user(&uf->max_errors, &f->max_errors, sizeof(f->max_errors));
err |= __put_user(f->flags, &uf->flags);
err |= __put_user(f->read_track, &uf->read_track);
err |= __copy_to_user(uf->autodetect, f->autodetect, sizeof(f->autodetect));
err |= __put_user(f->checkfreq, &uf->checkfreq);
err |= __put_user(f->native_format, &uf->native_format);
break;
}
case FDGETDRVSTAT32:
case FDPOLLDRVSTAT32:
{
struct compat_floppy_drive_struct __user *uf;
struct floppy_drive_struct *f = karg;
uf = compat_ptr(arg);
err = __put_user(f->flags, &uf->flags);
err |= __put_user(f->spinup_date, &uf->spinup_date);
err |= __put_user(f->select_date, &uf->select_date);
err |= __put_user(f->first_read_date, &uf->first_read_date);
err |= __put_user(f->probed_format, &uf->probed_format);
err |= __put_user(f->track, &uf->track);
err |= __put_user(f->maxblock, &uf->maxblock);
err |= __put_user(f->maxtrack, &uf->maxtrack);
err |= __put_user(f->generation, &uf->generation);
err |= __put_user(f->keep_data, &uf->keep_data);
err |= __put_user(f->fd_ref, &uf->fd_ref);
err |= __put_user(f->fd_device, &uf->fd_device);
err |= __put_user(f->last_checked, &uf->last_checked);
err |= __put_user((u64)f->dmabuf, &uf->dmabuf);
err |= __put_user((u64)f->bufblocks, &uf->bufblocks);
break;
}
case FDGETFDCSTAT32:
{
struct compat_floppy_fdc_state __user *uf;
struct floppy_fdc_state *f = karg;
uf = compat_ptr(arg);
err = __put_user(f->spec1, &uf->spec1);
err |= __put_user(f->spec2, &uf->spec2);
err |= __put_user(f->dtr, &uf->dtr);
err |= __put_user(f->version, &uf->version);
err |= __put_user(f->dor, &uf->dor);
err |= __put_user(f->address, &uf->address);
err |= __copy_to_user((char __user *)&uf->address + sizeof(uf->address),
(char *)&f->address + sizeof(f->address), sizeof(int));
err |= __put_user(f->driver_version, &uf->driver_version);
err |= __copy_to_user(uf->track, f->track, sizeof(f->track));
break;
}
case FDWERRORGET32:
{
struct compat_floppy_write_errors __user *uf;
struct floppy_write_errors *f = karg;
uf = compat_ptr(arg);
err = __put_user(f->write_errors, &uf->write_errors);
err |= __put_user(f->first_error_sector, &uf->first_error_sector);
err |= __put_user(f->first_error_generation, &uf->first_error_generation);
err |= __put_user(f->last_error_sector, &uf->last_error_sector);
err |= __put_user(f->last_error_generation, &uf->last_error_generation);
err |= __put_user(f->badness, &uf->badness);
break;
}
default:
break;
}
if (err)
err = -EFAULT;
out:
kfree(karg);
return err;
}
struct compat_blk_user_trace_setup {
char name[32];
u16 act_mask;
u32 buf_size;
u32 buf_nr;
compat_u64 start_lba;
compat_u64 end_lba;
u32 pid;
};
#define BLKTRACESETUP32 _IOWR(0x12, 115, struct compat_blk_user_trace_setup)
static int compat_blk_trace_setup(struct block_device *bdev, char __user *arg)
{
struct blk_user_trace_setup buts;
struct compat_blk_user_trace_setup cbuts;
struct request_queue *q;
char b[BDEVNAME_SIZE];
int ret;
q = bdev_get_queue(bdev);
if (!q)
return -ENXIO;
if (copy_from_user(&cbuts, arg, sizeof(cbuts)))
return -EFAULT;
bdevname(bdev, b);
buts = (struct blk_user_trace_setup) {
.act_mask = cbuts.act_mask,
.buf_size = cbuts.buf_size,
.buf_nr = cbuts.buf_nr,
.start_lba = cbuts.start_lba,
.end_lba = cbuts.end_lba,
.pid = cbuts.pid,
};
memcpy(&buts.name, &cbuts.name, 32);
mutex_lock(&bdev->bd_mutex);
ret = do_blk_trace_setup(q, b, bdev->bd_dev, bdev, &buts);
mutex_unlock(&bdev->bd_mutex);
if (ret)
return ret;
if (copy_to_user(arg, &buts.name, 32))
return -EFAULT;
return 0;
}
static int compat_blkdev_driver_ioctl(struct block_device *bdev, fmode_t mode,
unsigned cmd, unsigned long arg)
{
switch (cmd) {
case HDIO_GET_UNMASKINTR:
case HDIO_GET_MULTCOUNT:
case HDIO_GET_KEEPSETTINGS:
case HDIO_GET_32BIT:
case HDIO_GET_NOWERR:
case HDIO_GET_DMA:
case HDIO_GET_NICE:
case HDIO_GET_WCACHE:
case HDIO_GET_ACOUSTIC:
case HDIO_GET_ADDRESS:
case HDIO_GET_BUSSTATE:
return compat_hdio_ioctl(bdev, mode, cmd, arg);
case FDSETPRM32:
case FDDEFPRM32:
case FDGETPRM32:
case FDSETDRVPRM32:
case FDGETDRVPRM32:
case FDGETDRVSTAT32:
case FDPOLLDRVSTAT32:
case FDGETFDCSTAT32:
case FDWERRORGET32:
return compat_fd_ioctl(bdev, mode, cmd, arg);
case CDROMREADAUDIO:
return compat_cdrom_read_audio(bdev, mode, cmd, arg);
case CDROM_SEND_PACKET:
return compat_cdrom_generic_command(bdev, mode, cmd, arg);
/*
* No handler required for the ones below, we just need to
* convert arg to a 64 bit pointer.
*/
case BLKSECTSET:
/*
* 0x03 -- HD/IDE ioctl's used by hdparm and friends.
* Some need translations, these do not.
*/
case HDIO_GET_IDENTITY:
case HDIO_DRIVE_TASK:
case HDIO_DRIVE_CMD:
/* 0x330 is reserved -- it used to be HDIO_GETGEO_BIG */
case 0x330:
/* 0x02 -- Floppy ioctls */
case FDMSGON:
case FDMSGOFF:
case FDSETEMSGTRESH:
case FDFLUSH:
case FDWERRORCLR:
case FDSETMAXERRS:
case FDGETMAXERRS:
case FDGETDRVTYP:
case FDEJECT:
case FDCLRPRM:
case FDFMTBEG:
case FDFMTEND:
case FDRESET:
case FDTWADDLE:
case FDFMTTRK:
case FDRAWCMD:
/* CDROM stuff */
case CDROMPAUSE:
case CDROMRESUME:
case CDROMPLAYMSF:
case CDROMPLAYTRKIND:
case CDROMREADTOCHDR:
case CDROMREADTOCENTRY:
case CDROMSTOP:
case CDROMSTART:
case CDROMEJECT:
case CDROMVOLCTRL:
case CDROMSUBCHNL:
case CDROMMULTISESSION:
case CDROM_GET_MCN:
case CDROMRESET:
case CDROMVOLREAD:
case CDROMSEEK:
case CDROMPLAYBLK:
case CDROMCLOSETRAY:
case CDROM_DISC_STATUS:
case CDROM_CHANGER_NSLOTS:
case CDROM_GET_CAPABILITY:
/* Ignore cdrom.h about these next 5 ioctls, they absolutely do
* not take a struct cdrom_read, instead they take a struct cdrom_msf
* which is compatible.
*/
case CDROMREADMODE2:
case CDROMREADMODE1:
case CDROMREADRAW:
case CDROMREADCOOKED:
case CDROMREADALL:
/* DVD ioctls */
case DVD_READ_STRUCT:
case DVD_WRITE_STRUCT:
case DVD_AUTH:
arg = (unsigned long)compat_ptr(arg);
/* These intepret arg as an unsigned long, not as a pointer,
* so we must not do compat_ptr() conversion. */
case HDIO_SET_MULTCOUNT:
case HDIO_SET_UNMASKINTR:
case HDIO_SET_KEEPSETTINGS:
case HDIO_SET_32BIT:
case HDIO_SET_NOWERR:
case HDIO_SET_DMA:
case HDIO_SET_PIO_MODE:
case HDIO_SET_NICE:
case HDIO_SET_WCACHE:
case HDIO_SET_ACOUSTIC:
case HDIO_SET_BUSSTATE:
case HDIO_SET_ADDRESS:
case CDROMEJECT_SW:
case CDROM_SET_OPTIONS:
case CDROM_CLEAR_OPTIONS:
case CDROM_SELECT_SPEED:
case CDROM_SELECT_DISC:
case CDROM_MEDIA_CHANGED:
case CDROM_DRIVE_STATUS:
case CDROM_LOCKDOOR:
case CDROM_DEBUG:
break;
default:
/* unknown ioctl number */
return -ENOIOCTLCMD;
}
return __blkdev_driver_ioctl(bdev, mode, cmd, arg);
}
/* Most of the generic ioctls are handled in the normal fallback path.
This assumes the blkdev's low level compat_ioctl always returns
ENOIOCTLCMD for unknown ioctls. */
long compat_blkdev_ioctl(struct file *file, unsigned cmd, unsigned long arg)
{
int ret = -ENOIOCTLCMD;
struct inode *inode = file->f_mapping->host;
struct block_device *bdev = inode->i_bdev;
struct gendisk *disk = bdev->bd_disk;
fmode_t mode = file->f_mode;
struct backing_dev_info *bdi;
loff_t size;
/*
* O_NDELAY can be altered using fcntl(.., F_SETFL, ..), so we have
* to updated it before every ioctl.
*/
if (file->f_flags & O_NDELAY)
mode |= FMODE_NDELAY;
else
mode &= ~FMODE_NDELAY;
switch (cmd) {
case HDIO_GETGEO:
return compat_hdio_getgeo(disk, bdev, compat_ptr(arg));
case BLKPBSZGET:
return compat_put_uint(arg, bdev_physical_block_size(bdev));
case BLKIOMIN:
return compat_put_uint(arg, bdev_io_min(bdev));
case BLKIOOPT:
return compat_put_uint(arg, bdev_io_opt(bdev));
case BLKALIGNOFF:
return compat_put_int(arg, bdev_alignment_offset(bdev));
case BLKDISCARDZEROES:
return compat_put_uint(arg, bdev_discard_zeroes_data(bdev));
case BLKFLSBUF:
case BLKROSET:
case BLKDISCARD:
/*
* the ones below are implemented in blkdev_locked_ioctl,
* but we call blkdev_ioctl, which gets the lock for us
*/
case BLKRRPART:
return blkdev_ioctl(bdev, mode, cmd,
(unsigned long)compat_ptr(arg));
case BLKBSZSET_32:
return blkdev_ioctl(bdev, mode, BLKBSZSET,
(unsigned long)compat_ptr(arg));
case BLKPG:
return compat_blkpg_ioctl(bdev, mode, cmd, compat_ptr(arg));
case BLKRAGET:
case BLKFRAGET:
if (!arg)
return -EINVAL;
bdi = blk_get_backing_dev_info(bdev);
if (bdi == NULL)
return -ENOTTY;
return compat_put_long(arg,
(bdi->ra_pages * PAGE_CACHE_SIZE) / 512);
case BLKROGET: /* compatible */
return compat_put_int(arg, bdev_read_only(bdev) != 0);
case BLKBSZGET_32: /* get the logical block size (cf. BLKSSZGET) */
return compat_put_int(arg, block_size(bdev));
case BLKSSZGET: /* get block device hardware sector size */
return compat_put_int(arg, bdev_logical_block_size(bdev));
case BLKSECTGET:
return compat_put_ushort(arg,
queue_max_sectors(bdev_get_queue(bdev)));
case BLKRASET: /* compatible, but no compat_ptr (!) */
case BLKFRASET:
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
bdi = blk_get_backing_dev_info(bdev);
if (bdi == NULL)
return -ENOTTY;
bdi->ra_pages = (arg * 512) / PAGE_CACHE_SIZE;
return 0;
case BLKGETSIZE:
size = bdev->bd_inode->i_size;
if ((size >> 9) > ~0UL)
return -EFBIG;
return compat_put_ulong(arg, size >> 9);
case BLKGETSIZE64_32:
return compat_put_u64(arg, bdev->bd_inode->i_size);
case BLKTRACESETUP32:
lock_kernel();
ret = compat_blk_trace_setup(bdev, compat_ptr(arg));
unlock_kernel();
return ret;
case BLKTRACESTART: /* compatible */
case BLKTRACESTOP: /* compatible */
case BLKTRACETEARDOWN: /* compatible */
lock_kernel();
ret = blk_trace_ioctl(bdev, cmd, compat_ptr(arg));
unlock_kernel();
return ret;
default:
if (disk->fops->compat_ioctl)
ret = disk->fops->compat_ioctl(bdev, mode, cmd, arg);
if (ret == -ENOIOCTLCMD)
ret = compat_blkdev_driver_ioctl(bdev, mode, cmd, arg);
return ret;
}
}
| gpl-2.0 |
Kali-/htc-kernel | drivers/staging/rt2860/common/rt_channel.c | 1315 | 29083 | /*
*************************************************************************
* Ralink Tech Inc.
* 5F., No.36, Taiyuan St., Jhubei City,
* Hsinchu County 302,
* Taiwan, R.O.C.
*
* (c) Copyright 2002-2007, Ralink Technology, 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 "../rt_config.h"
struct rt_ch_freq_map CH_HZ_ID_MAP[] = {
{1, 2412}
,
{2, 2417}
,
{3, 2422}
,
{4, 2427}
,
{5, 2432}
,
{6, 2437}
,
{7, 2442}
,
{8, 2447}
,
{9, 2452}
,
{10, 2457}
,
{11, 2462}
,
{12, 2467}
,
{13, 2472}
,
{14, 2484}
,
/* UNII */
{36, 5180}
,
{40, 5200}
,
{44, 5220}
,
{48, 5240}
,
{52, 5260}
,
{56, 5280}
,
{60, 5300}
,
{64, 5320}
,
{149, 5745}
,
{153, 5765}
,
{157, 5785}
,
{161, 5805}
,
{165, 5825}
,
{167, 5835}
,
{169, 5845}
,
{171, 5855}
,
{173, 5865}
,
/* HiperLAN2 */
{100, 5500}
,
{104, 5520}
,
{108, 5540}
,
{112, 5560}
,
{116, 5580}
,
{120, 5600}
,
{124, 5620}
,
{128, 5640}
,
{132, 5660}
,
{136, 5680}
,
{140, 5700}
,
/* Japan MMAC */
{34, 5170}
,
{38, 5190}
,
{42, 5210}
,
{46, 5230}
,
/* Japan */
{184, 4920}
,
{188, 4940}
,
{192, 4960}
,
{196, 4980}
,
{208, 5040}
, /* Japan, means J08 */
{212, 5060}
, /* Japan, means J12 */
{216, 5080}
, /* Japan, means J16 */
};
int CH_HZ_ID_MAP_NUM = (sizeof(CH_HZ_ID_MAP) / sizeof(struct rt_ch_freq_map));
struct rt_ch_region ChRegion[] = {
{ /* Antigua and Berbuda */
"AG",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, BOTH, FALSE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, FALSE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Argentina */
"AR",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{52, 4, 24, BOTH, FALSE}
, /* 5G, ch 52~64 */
{149, 4, 30, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Aruba */
"AW",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, BOTH, FALSE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, FALSE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Australia */
"AU",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, BOTH, FALSE}
, /* 5G, ch 52~64 */
{149, 5, 30, BOTH, FALSE}
, /* 5G, ch 149~165 */
{0}
, /* end */
}
}
,
{ /* Austria */
"AT",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, TRUE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Bahamas */
"BS",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, BOTH, FALSE}
, /* 5G, ch 52~64 */
{149, 5, 30, BOTH, FALSE}
, /* 5G, ch 149~165 */
{0}
, /* end */
}
}
,
{ /* Barbados */
"BB",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, BOTH, FALSE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, FALSE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Bermuda */
"BM",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, BOTH, FALSE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, FALSE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Brazil */
"BR",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, BOTH, FALSE}
, /* 5G, ch 52~64 */
{100, 11, 24, BOTH, FALSE}
, /* 5G, ch 100~140 */
{149, 5, 30, BOTH, FALSE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Belgium */
"BE",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 18, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 18, IDOR, FALSE}
, /* 5G, ch 52~64 */
{0}
, /* end */
}
}
,
{ /* Bulgaria */
"BG",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, ODOR, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Canada */
"CA",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, BOTH, FALSE}
, /* 5G, ch 52~64 */
{149, 5, 30, BOTH, FALSE}
, /* 5G, ch 149~165 */
{0}
, /* end */
}
}
,
{ /* Cayman IsLands */
"KY",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, BOTH, FALSE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, FALSE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Chile */
"CL",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 20, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 20, BOTH, FALSE}
, /* 5G, ch 52~64 */
{149, 5, 20, BOTH, FALSE}
, /* 5G, ch 149~165 */
{0}
, /* end */
}
}
,
{ /* China */
"CN",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{149, 4, 27, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Colombia */
"CO",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 17, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, BOTH, FALSE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, FALSE}
, /* 5G, ch 100~140 */
{149, 5, 30, BOTH, FALSE}
, /* 5G, ch 149~165 */
{0}
, /* end */
}
}
,
{ /* Costa Rica */
"CR",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 17, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, BOTH, FALSE}
, /* 5G, ch 52~64 */
{149, 4, 30, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Cyprus */
"CY",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Czech_Republic */
"CZ",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{0}
, /* end */
}
}
,
{ /* Denmark */
"DK",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Dominican Republic */
"DO",
CE,
{
{1, 0, 20, BOTH, FALSE}
, /* 2.4 G, ch 0 */
{149, 4, 20, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Equador */
"EC",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{100, 11, 27, BOTH, FALSE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* El Salvador */
"SV",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 30, BOTH, TRUE}
, /* 5G, ch 52~64 */
{149, 4, 36, BOTH, TRUE}
, /* 5G, ch 149~165 */
{0}
, /* end */
}
}
,
{ /* Finland */
"FI",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* France */
"FR",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{0}
, /* end */
}
}
,
{ /* Germany */
"DE",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Greece */
"GR",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, ODOR, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Guam */
"GU",
CE,
{
{1, 11, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~11 */
{36, 4, 17, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, BOTH, FALSE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, FALSE}
, /* 5G, ch 100~140 */
{149, 5, 30, BOTH, FALSE}
, /* 5G, ch 149~165 */
{0}
, /* end */
}
}
,
{ /* Guatemala */
"GT",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 17, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, BOTH, FALSE}
, /* 5G, ch 52~64 */
{149, 4, 30, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Haiti */
"HT",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 17, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, BOTH, FALSE}
, /* 5G, ch 52~64 */
{149, 4, 30, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Honduras */
"HN",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{149, 4, 27, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Hong Kong */
"HK",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, FALSE}
, /* 5G, ch 52~64 */
{149, 4, 30, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Hungary */
"HU",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{0}
, /* end */
}
}
,
{ /* Iceland */
"IS",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* India */
"IN",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{149, 4, 24, IDOR, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Indonesia */
"ID",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{149, 4, 27, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Ireland */
"IE",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, ODOR, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Israel */
"IL",
CE,
{
{1, 3, 20, IDOR, FALSE}
, /* 2.4 G, ch 1~3 */
{4, 6, 20, BOTH, FALSE}
, /* 2.4 G, ch 4~9 */
{10, 4, 20, IDOR, FALSE}
, /* 2.4 G, ch 10~13 */
{0}
, /* end */
}
}
,
{ /* Italy */
"IT",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, ODOR, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Japan */
"JP",
JAP,
{
{1, 14, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~14 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{0}
, /* end */
}
}
,
{ /* Jordan */
"JO",
CE,
{
{1, 13, 20, IDOR, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{149, 4, 23, IDOR, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Latvia */
"LV",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Liechtenstein */
"LI",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Lithuania */
"LT",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Luxemburg */
"LU",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Malaysia */
"MY",
CE,
{
{36, 4, 23, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, BOTH, FALSE}
, /* 5G, ch 52~64 */
{149, 5, 20, BOTH, FALSE}
, /* 5G, ch 149~165 */
{0}
, /* end */
}
}
,
{ /* Malta */
"MT",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Marocco */
"MA",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 24, IDOR, FALSE}
, /* 5G, ch 36~48 */
{0}
, /* end */
}
}
,
{ /* Mexico */
"MX",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, BOTH, FALSE}
, /* 5G, ch 52~64 */
{149, 5, 30, IDOR, FALSE}
, /* 5G, ch 149~165 */
{0}
, /* end */
}
}
,
{ /* Netherlands */
"NL",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* New Zealand */
"NZ",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 24, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, BOTH, FALSE}
, /* 5G, ch 52~64 */
{149, 4, 30, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Norway */
"NO",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 24, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 24, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Peru */
"PE",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{149, 4, 27, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Portugal */
"PT",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Poland */
"PL",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Romania */
"RO",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Russia */
"RU",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{149, 4, 20, IDOR, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Saudi Arabia */
"SA",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, BOTH, FALSE}
, /* 5G, ch 52~64 */
{149, 4, 23, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Serbia_and_Montenegro */
"CS",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{0}
, /* end */
}
}
,
{ /* Singapore */
"SG",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, BOTH, FALSE}
, /* 5G, ch 52~64 */
{149, 4, 20, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Slovakia */
"SK",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Slovenia */
"SI",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{0}
, /* end */
}
}
,
{ /* South Africa */
"ZA",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, FALSE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{149, 4, 30, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* South Korea */
"KR",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 20, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 20, BOTH, FALSE}
, /* 5G, ch 52~64 */
{100, 8, 20, BOTH, FALSE}
, /* 5G, ch 100~128 */
{149, 4, 20, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Spain */
"ES",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 17, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Sweden */
"SE",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Switzerland */
"CH",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~13 */
{36, 4, 23, IDOR, TRUE}
, /* 5G, ch 36~48 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{0}
, /* end */
}
}
,
{ /* Taiwan */
"TW",
CE,
{
{1, 11, 30, BOTH, FALSE}
, /* 2.4 G, ch 1~11 */
{52, 4, 23, IDOR, FALSE}
, /* 5G, ch 52~64 */
{0}
, /* end */
}
}
,
{ /* Turkey */
"TR",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~11 */
{36, 4, 23, BOTH, FALSE}
, /* 5G, ch 36~48 */
{52, 4, 23, BOTH, FALSE}
, /* 5G, ch 52~64 */
{0}
, /* end */
}
}
,
{ /* UK */
"GB",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~11 */
{36, 4, 23, IDOR, FALSE}
, /* 5G, ch 52~64 */
{52, 4, 23, IDOR, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{0}
, /* end */
}
}
,
{ /* Ukraine */
"UA",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~11 */
{0}
, /* end */
}
}
,
{ /* United_Arab_Emirates */
"AE",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~11 */
{0}
, /* end */
}
}
,
{ /* United_States */
"US",
CE,
{
{1, 11, 30, BOTH, FALSE}
, /* 2.4 G, ch 1~11 */
{36, 4, 17, IDOR, FALSE}
, /* 5G, ch 52~64 */
{52, 4, 24, BOTH, TRUE}
, /* 5G, ch 52~64 */
{100, 11, 30, BOTH, TRUE}
, /* 5G, ch 100~140 */
{149, 5, 30, BOTH, FALSE}
, /* 5G, ch 149~165 */
{0}
, /* end */
}
}
,
{ /* Venezuela */
"VE",
CE,
{
{1, 13, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~11 */
{149, 4, 27, BOTH, FALSE}
, /* 5G, ch 149~161 */
{0}
, /* end */
}
}
,
{ /* Default */
"",
CE,
{
{1, 11, 20, BOTH, FALSE}
, /* 2.4 G, ch 1~11 */
{36, 4, 20, BOTH, FALSE}
, /* 5G, ch 52~64 */
{52, 4, 20, BOTH, FALSE}
, /* 5G, ch 52~64 */
{100, 11, 20, BOTH, FALSE}
, /* 5G, ch 100~140 */
{149, 5, 20, BOTH, FALSE}
, /* 5G, ch 149~165 */
{0}
, /* end */
}
}
,
};
static struct rt_ch_region *GetChRegion(u8 *CntryCode)
{
int loop = 0;
struct rt_ch_region *pChRegion = NULL;
while (strcmp((char *)ChRegion[loop].CountReg, "") != 0) {
if (strncmp
((char *)ChRegion[loop].CountReg, (char *)CntryCode,
2) == 0) {
pChRegion = &ChRegion[loop];
break;
}
loop++;
}
if (pChRegion == NULL)
pChRegion = &ChRegion[loop];
return pChRegion;
}
static void ChBandCheck(u8 PhyMode, u8 *pChType)
{
switch (PhyMode) {
case PHY_11A:
case PHY_11AN_MIXED:
*pChType = BAND_5G;
break;
case PHY_11ABG_MIXED:
case PHY_11AGN_MIXED:
case PHY_11ABGN_MIXED:
*pChType = BAND_BOTH;
break;
default:
*pChType = BAND_24G;
break;
}
}
static u8 FillChList(struct rt_rtmp_adapter *pAd,
struct rt_ch_desp *pChDesp,
u8 Offset, u8 increment)
{
int i, j, l;
u8 channel;
j = Offset;
for (i = 0; i < pChDesp->NumOfCh; i++) {
channel = pChDesp->FirstChannel + i * increment;
for (l = 0; l < MAX_NUM_OF_CHANNELS; l++) {
if (channel == pAd->TxPower[l].Channel) {
pAd->ChannelList[j].Power =
pAd->TxPower[l].Power;
pAd->ChannelList[j].Power2 =
pAd->TxPower[l].Power2;
break;
}
}
if (l == MAX_NUM_OF_CHANNELS)
continue;
pAd->ChannelList[j].Channel =
pChDesp->FirstChannel + i * increment;
pAd->ChannelList[j].MaxTxPwr = pChDesp->MaxTxPwr;
pAd->ChannelList[j].DfsReq = pChDesp->DfsReq;
j++;
}
pAd->ChannelListNum = j;
return j;
}
static inline void CreateChList(struct rt_rtmp_adapter *pAd,
struct rt_ch_region *pChRegion, u8 Geography)
{
int i;
u8 offset = 0;
struct rt_ch_desp *pChDesp;
u8 ChType;
u8 increment;
if (pChRegion == NULL)
return;
ChBandCheck(pAd->CommonCfg.PhyMode, &ChType);
for (i = 0; i < 10; i++) {
pChDesp = &pChRegion->ChDesp[i];
if (pChDesp->FirstChannel == 0)
break;
if (ChType == BAND_5G) {
if (pChDesp->FirstChannel <= 14)
continue;
} else if (ChType == BAND_24G) {
if (pChDesp->FirstChannel > 14)
continue;
}
if ((pChDesp->Geography == BOTH)
|| (pChDesp->Geography == Geography)) {
if (pChDesp->FirstChannel > 14)
increment = 4;
else
increment = 1;
offset = FillChList(pAd, pChDesp, offset, increment);
}
}
}
void BuildChannelListEx(struct rt_rtmp_adapter *pAd)
{
struct rt_ch_region *pChReg;
pChReg = GetChRegion(pAd->CommonCfg.CountryCode);
CreateChList(pAd, pChReg, pAd->CommonCfg.Geography);
}
void BuildBeaconChList(struct rt_rtmp_adapter *pAd,
u8 *pBuf, unsigned long *pBufLen)
{
int i;
unsigned long TmpLen;
struct rt_ch_region *pChRegion;
struct rt_ch_desp *pChDesp;
u8 ChType;
pChRegion = GetChRegion(pAd->CommonCfg.CountryCode);
if (pChRegion == NULL)
return;
ChBandCheck(pAd->CommonCfg.PhyMode, &ChType);
*pBufLen = 0;
for (i = 0; i < 10; i++) {
pChDesp = &pChRegion->ChDesp[i];
if (pChDesp->FirstChannel == 0)
break;
if (ChType == BAND_5G) {
if (pChDesp->FirstChannel <= 14)
continue;
} else if (ChType == BAND_24G) {
if (pChDesp->FirstChannel > 14)
continue;
}
if ((pChDesp->Geography == BOTH)
|| (pChDesp->Geography == pAd->CommonCfg.Geography)) {
MakeOutgoingFrame(pBuf + *pBufLen, &TmpLen,
1, &pChDesp->FirstChannel,
1, &pChDesp->NumOfCh,
1, &pChDesp->MaxTxPwr, END_OF_ARGS);
*pBufLen += TmpLen;
}
}
}
static BOOLEAN IsValidChannel(struct rt_rtmp_adapter *pAd, u8 channel)
{
int i;
for (i = 0; i < pAd->ChannelListNum; i++) {
if (pAd->ChannelList[i].Channel == channel)
break;
}
if (i == pAd->ChannelListNum)
return FALSE;
else
return TRUE;
}
static u8 GetExtCh(u8 Channel, u8 Direction)
{
char ExtCh;
if (Direction == EXTCHA_ABOVE)
ExtCh = Channel + 4;
else
ExtCh = (Channel - 4) > 0 ? (Channel - 4) : 0;
return ExtCh;
}
void N_ChannelCheck(struct rt_rtmp_adapter *pAd)
{
/*u8 ChannelNum = pAd->ChannelListNum; */
u8 Channel = pAd->CommonCfg.Channel;
if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
&& (pAd->CommonCfg.RegTransmitSetting.field.BW == BW_40)) {
if (Channel > 14) {
if ((Channel == 36) || (Channel == 44)
|| (Channel == 52) || (Channel == 60)
|| (Channel == 100) || (Channel == 108)
|| (Channel == 116) || (Channel == 124)
|| (Channel == 132) || (Channel == 149)
|| (Channel == 157)) {
pAd->CommonCfg.RegTransmitSetting.field.EXTCHA =
EXTCHA_ABOVE;
} else if ((Channel == 40) || (Channel == 48)
|| (Channel == 56) || (Channel == 64)
|| (Channel == 104) || (Channel == 112)
|| (Channel == 120) || (Channel == 128)
|| (Channel == 136) || (Channel == 153)
|| (Channel == 161)) {
pAd->CommonCfg.RegTransmitSetting.field.EXTCHA =
EXTCHA_BELOW;
} else {
pAd->CommonCfg.RegTransmitSetting.field.BW =
BW_20;
}
} else {
do {
u8 ExtCh;
u8 Dir =
pAd->CommonCfg.RegTransmitSetting.field.
EXTCHA;
ExtCh = GetExtCh(Channel, Dir);
if (IsValidChannel(pAd, ExtCh))
break;
Dir =
(Dir ==
EXTCHA_ABOVE) ? EXTCHA_BELOW :
EXTCHA_ABOVE;
ExtCh = GetExtCh(Channel, Dir);
if (IsValidChannel(pAd, ExtCh)) {
pAd->CommonCfg.RegTransmitSetting.field.
EXTCHA = Dir;
break;
}
pAd->CommonCfg.RegTransmitSetting.field.BW =
BW_20;
} while (FALSE);
if (Channel == 14) {
pAd->CommonCfg.RegTransmitSetting.field.BW =
BW_20;
/*pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_NONE; // We didn't set the ExtCh as NONE due to it'll set in RTMPSetHT() */
}
}
}
}
void N_SetCenCh(struct rt_rtmp_adapter *pAd)
{
if (pAd->CommonCfg.RegTransmitSetting.field.BW == BW_40) {
if (pAd->CommonCfg.RegTransmitSetting.field.EXTCHA ==
EXTCHA_ABOVE) {
pAd->CommonCfg.CentralChannel =
pAd->CommonCfg.Channel + 2;
} else {
if (pAd->CommonCfg.Channel == 14)
pAd->CommonCfg.CentralChannel =
pAd->CommonCfg.Channel - 1;
else
pAd->CommonCfg.CentralChannel =
pAd->CommonCfg.Channel - 2;
}
} else {
pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel;
}
}
u8 GetCuntryMaxTxPwr(struct rt_rtmp_adapter *pAd, u8 channel)
{
int i;
for (i = 0; i < pAd->ChannelListNum; i++) {
if (pAd->ChannelList[i].Channel == channel)
break;
}
if (i == pAd->ChannelListNum)
return 0xff;
else
return pAd->ChannelList[i].MaxTxPwr;
}
| gpl-2.0 |
burakgon/E7_Elite_kernel | kernel/arch/arm/mach-msm/platsmp-8625.c | 1827 | 8023 | /* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/jiffies.h>
#include <linux/smp.h>
#include <linux/io.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <asm/hardware/gic.h>
#include <asm/smp_scu.h>
#include <asm/unified.h>
#include <mach/msm_iomap.h>
#include "pm.h"
#include "platsmp.h"
#define CORE_RESET_BASE 0xA8600590
#define MSM_CORE_STATUS_MSK 0x02800000
static DEFINE_PER_CPU(bool, cold_boot_done);
struct per_cpu_data {
unsigned int reset_off;
unsigned int offset;
unsigned int ipc_irq;
void __iomem *reset_core_base;
};
static uint32_t *msm8625_boot_vector;
static struct per_cpu_data cpu_data[CONFIG_NR_CPUS];
static void __iomem *scu_base_addr(void)
{
return MSM_SCU_BASE;
}
static DEFINE_SPINLOCK(boot_lock);
/*
* MP_CORE_IPC will be used to generate interrupt and can be used by either
* of core.
* To bring secondary cores out of GDFS we need to raise the SPI using the
* MP_CORE_IPC.
*/
static void raise_clear_spi(unsigned int cpu, bool set)
{
int value;
value = __raw_readl(MSM_CSR_BASE + 0x54);
if (set)
__raw_writel(value | BIT(cpu), MSM_CSR_BASE + 0x54);
else
__raw_writel(value & ~BIT(cpu), MSM_CSR_BASE + 0x54);
mb();
}
static void clear_pending_spi(unsigned int irq)
{
struct irq_data *d = irq_get_irq_data(irq);
struct irq_chip *c = irq_data_get_irq_chip(d);
c->irq_mask(d);
local_irq_disable();
/* Clear the IRQ from the ENABLE_SET */
gic_clear_irq_pending(irq);
local_irq_enable();
}
void __cpuinit msm8625_platform_secondary_init(unsigned int cpu)
{
WARN_ON(msm_platform_secondary_init(cpu));
/*
* if any interrupts are already enabled for the primary
* core (e.g. timer irq), then they will not have been enabled
* for us: do so
*/
gic_secondary_init(0);
/*
* let the primary processor know we're out of the
* pen, then head off into the C entry point
*/
write_pen_release(-1);
/* clear the IPC pending SPI */
if (per_cpu(power_collapsed, cpu)) {
raise_clear_spi(cpu, false);
clear_pending_spi(cpu_data[cpu].ipc_irq);
per_cpu(power_collapsed, cpu) = 0;
}
/*
* Synchronise with the boot thread.
*/
spin_lock(&boot_lock);
spin_unlock(&boot_lock);
}
static int __cpuinit msm8625_release_secondary(unsigned int cpu)
{
void __iomem *base_ptr;
int value = 0;
unsigned long timeout;
/*
* loop to ensure that the GHS_STATUS_CORE1 bit in the
* MPA5_STATUS_REG(0x3c) is set. The timeout for the while
* loop can be set as 20us as of now
*/
timeout = jiffies + usecs_to_jiffies(20);
while (time_before(jiffies, timeout)) {
value = __raw_readl(MSM_CFG_CTL_BASE + cpu_data[cpu].offset);
if ((value & MSM_CORE_STATUS_MSK) ==
MSM_CORE_STATUS_MSK)
break;
udelay(1);
}
if (!value) {
pr_err("Core %u cannot be brought out of Reset!!!\n", cpu);
return -ENODEV;
}
base_ptr = ioremap_nocache(CORE_RESET_BASE +
cpu_data[cpu].reset_off, SZ_4);
if (!base_ptr)
return -ENODEV;
/* Reset core out of reset */
__raw_writel(0x0, base_ptr);
mb();
cpu_data[cpu].reset_core_base = base_ptr;
return 0;
}
void __iomem *core_reset_base(unsigned int cpu)
{
return cpu_data[cpu].reset_core_base;
}
int __cpuinit msm8625_boot_secondary(unsigned int cpu, struct task_struct *idle)
{
unsigned long timeout;
preset_lpj = loops_per_jiffy;
if (per_cpu(cold_boot_done, cpu) == false) {
if (msm8625_release_secondary(cpu)) {
pr_err("Failed to release core %u\n", cpu);
return -ENODEV;
}
per_cpu(cold_boot_done, cpu) = true;
}
/*
* Set synchronisation state between this boot processor
* and the secondary one
*/
spin_lock(&boot_lock);
/*
* This is really belt and braces; we hold unintended secondary
* CPUs in the holding pen until we're ready for them. However,
* since we haven't sent them a soft interrupt, they shouldn't
* be there.
*/
write_pen_release(cpu);
/*
* Send the secondary CPU a soft interrupt, thereby causing
* the boot monitor to read the system wide flags register,
* and branch to the address found there.
*
* power_collapsed is the flag which will be updated for Powercollapse.
* Once we are out of PC, as secondary cores will be in the state of
* GDFS which needs to be brought out by raising an SPI.
*/
if (per_cpu(power_collapsed, cpu)) {
gic_configure_and_raise(cpu_data[cpu].ipc_irq, cpu);
raise_clear_spi(cpu, true);
} else {
gic_raise_softirq(cpumask_of(cpu), 1);
}
timeout = jiffies + (1 * HZ);
while (time_before(jiffies, timeout)) {
smp_rmb();
if (pen_release == -1)
break;
udelay(10);
}
/*
* now the secondary core is starting up let it run its
* calibrations, then wait for it to finish
*/
spin_unlock(&boot_lock);
return 0;
}
/*
* Initialise the CPU possible map early - this describes the CPUs
* which may be present or become present in the system.
*/
void __init msm8625_smp_init_cpus(void)
{
void __iomem *scu_base = scu_base_addr();
unsigned int i, ncores;
ncores = scu_base ? scu_get_core_count(scu_base) : 1;
for (i = 0; i < ncores; i++)
set_cpu_possible(i, true);
set_smp_cross_call(gic_raise_softirq);
}
static void per_cpu_data(unsigned int cpu, unsigned int off,
unsigned int off1, unsigned int irq)
{
cpu_data[cpu].reset_off = off;
cpu_data[cpu].offset = off1;
cpu_data[cpu].ipc_irq = irq;
}
static void enable_boot_remapper(unsigned long bit, unsigned int off)
{
int value;
/* Enable boot remapper address */
value = __raw_readl(MSM_CFG_CTL_BASE + off);
__raw_writel(value | bit, MSM_CFG_CTL_BASE + off) ;
mb();
}
static void remapper_address(unsigned long phys, unsigned int off)
{
/*
* Write the address of secondary startup into the
* boot remapper register. The secondary CPU branches to this address.
*/
__raw_writel(phys, (MSM_CFG_CTL_BASE + off));
mb();
}
static void __init msm8625_boot_vector_init(uint32_t *boot_vector,
unsigned long entry)
{
if (!boot_vector)
return;
msm8625_boot_vector = boot_vector;
msm8625_boot_vector[0] = 0xE51FF004; /* ldr pc, 4 */
msm8625_boot_vector[1] = entry;
}
void __init msm8625_platform_smp_prepare_cpus(unsigned int max_cpus)
{
int cpu, value;
void __iomem *cpu_ptr;
scu_enable(scu_base_addr());
cpu_ptr = ioremap_nocache(MSM8625_CPU_PHYS, SZ_8);
if (!cpu_ptr) {
pr_err("failed to ioremap for secondary cores\n");
return;
}
msm8625_boot_vector_init(cpu_ptr,
virt_to_phys(msm_secondary_startup));
iounmap(cpu_ptr);
for_each_possible_cpu(cpu) {
switch (cpu) {
case 0:
break;
case 1:
remapper_address(MSM8625_CPU_PHYS, 0x34);
per_cpu_data(cpu, 0x0, 0x3c,
MSM8625_INT_ACSR_MP_CORE_IPC1);
enable_boot_remapper(BIT(26), 0x30);
break;
case 2:
remapper_address((MSM8625_CPU_PHYS >> 16), 0x4C);
per_cpu_data(cpu, 0x8, 0x50,
MSM8625_INT_ACSR_MP_CORE_IPC2);
enable_boot_remapper(BIT(25), 0x48);
break;
case 3:
value = __raw_readl(MSM_CFG_CTL_BASE + 0x4C);
remapper_address(value | MSM8625_CPU_PHYS, 0x4C);
per_cpu_data(cpu, 0xC, 0x50,
MSM8625_INT_ACSR_MP_CORE_IPC3);
enable_boot_remapper(BIT(26), 0x48);
break;
}
}
}
struct smp_operations msm8625_smp_ops __initdata = {
.smp_init_cpus = msm8625_smp_init_cpus,
.smp_prepare_cpus = msm8625_platform_smp_prepare_cpus,
.smp_secondary_init = msm8625_platform_secondary_init,
.smp_boot_secondary = msm8625_boot_secondary,
.cpu_kill = platform_cpu_kill,
.cpu_die = platform_cpu_die,
.cpu_disable = platform_cpu_disable
};
| gpl-2.0 |
usb-bullhead-ubuntu-touch/kernel_msm | drivers/rtc/rtc-starfire.c | 2083 | 1455 | /* rtc-starfire.c: Starfire platform RTC driver.
*
* Copyright (C) 2008 David S. Miller <davem@davemloft.net>
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/rtc.h>
#include <linux/platform_device.h>
#include <asm/oplib.h>
MODULE_AUTHOR("David S. Miller <davem@davemloft.net>");
MODULE_DESCRIPTION("Starfire RTC driver");
MODULE_LICENSE("GPL");
static u32 starfire_get_time(void)
{
static char obp_gettod[32];
static u32 unix_tod;
sprintf(obp_gettod, "h# %08x unix-gettod",
(unsigned int) (long) &unix_tod);
prom_feval(obp_gettod);
return unix_tod;
}
static int starfire_read_time(struct device *dev, struct rtc_time *tm)
{
rtc_time_to_tm(starfire_get_time(), tm);
return rtc_valid_tm(tm);
}
static const struct rtc_class_ops starfire_rtc_ops = {
.read_time = starfire_read_time,
};
static int __init starfire_rtc_probe(struct platform_device *pdev)
{
struct rtc_device *rtc;
rtc = devm_rtc_device_register(&pdev->dev, "starfire",
&starfire_rtc_ops, THIS_MODULE);
if (IS_ERR(rtc))
return PTR_ERR(rtc);
platform_set_drvdata(pdev, rtc);
return 0;
}
static int __exit starfire_rtc_remove(struct platform_device *pdev)
{
return 0;
}
static struct platform_driver starfire_rtc_driver = {
.driver = {
.name = "rtc-starfire",
.owner = THIS_MODULE,
},
.remove = __exit_p(starfire_rtc_remove),
};
module_platform_driver_probe(starfire_rtc_driver, starfire_rtc_probe);
| gpl-2.0 |
AudioGod/DTS-Sound-Integration_CAF-Android-kernel | fs/xfs/xfs_bmap.c | 2083 | 182113 | /*
* Copyright (c) 2000-2006 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_dir2.h"
#include "xfs_mount.h"
#include "xfs_da_btree.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_btree.h"
#include "xfs_mount.h"
#include "xfs_itable.h"
#include "xfs_inode_item.h"
#include "xfs_extfree_item.h"
#include "xfs_alloc.h"
#include "xfs_bmap.h"
#include "xfs_rtalloc.h"
#include "xfs_error.h"
#include "xfs_attr_leaf.h"
#include "xfs_quota.h"
#include "xfs_trans_space.h"
#include "xfs_buf_item.h"
#include "xfs_filestream.h"
#include "xfs_vnodeops.h"
#include "xfs_trace.h"
#include "xfs_symlink.h"
kmem_zone_t *xfs_bmap_free_item_zone;
/*
* Miscellaneous helper functions
*/
/*
* Compute and fill in the value of the maximum depth of a bmap btree
* in this filesystem. Done once, during mount.
*/
void
xfs_bmap_compute_maxlevels(
xfs_mount_t *mp, /* file system mount structure */
int whichfork) /* data or attr fork */
{
int level; /* btree level */
uint maxblocks; /* max blocks at this level */
uint maxleafents; /* max leaf entries possible */
int maxrootrecs; /* max records in root block */
int minleafrecs; /* min records in leaf block */
int minnoderecs; /* min records in node block */
int sz; /* root block size */
/*
* The maximum number of extents in a file, hence the maximum
* number of leaf entries, is controlled by the type of di_nextents
* (a signed 32-bit number, xfs_extnum_t), or by di_anextents
* (a signed 16-bit number, xfs_aextnum_t).
*
* Note that we can no longer assume that if we are in ATTR1 that
* the fork offset of all the inodes will be
* (xfs_default_attroffset(ip) >> 3) because we could have mounted
* with ATTR2 and then mounted back with ATTR1, keeping the
* di_forkoff's fixed but probably at various positions. Therefore,
* for both ATTR1 and ATTR2 we have to assume the worst case scenario
* of a minimum size available.
*/
if (whichfork == XFS_DATA_FORK) {
maxleafents = MAXEXTNUM;
sz = XFS_BMDR_SPACE_CALC(MINDBTPTRS);
} else {
maxleafents = MAXAEXTNUM;
sz = XFS_BMDR_SPACE_CALC(MINABTPTRS);
}
maxrootrecs = xfs_bmdr_maxrecs(mp, sz, 0);
minleafrecs = mp->m_bmap_dmnr[0];
minnoderecs = mp->m_bmap_dmnr[1];
maxblocks = (maxleafents + minleafrecs - 1) / minleafrecs;
for (level = 1; maxblocks > 1; level++) {
if (maxblocks <= maxrootrecs)
maxblocks = 1;
else
maxblocks = (maxblocks + minnoderecs - 1) / minnoderecs;
}
mp->m_bm_maxlevels[whichfork] = level;
}
/*
* Convert the given file system block to a disk block. We have to treat it
* differently based on whether the file is a real time file or not, because the
* bmap code does.
*/
xfs_daddr_t
xfs_fsb_to_db(struct xfs_inode *ip, xfs_fsblock_t fsb)
{
return (XFS_IS_REALTIME_INODE(ip) ? \
(xfs_daddr_t)XFS_FSB_TO_BB((ip)->i_mount, (fsb)) : \
XFS_FSB_TO_DADDR((ip)->i_mount, (fsb)));
}
STATIC int /* error */
xfs_bmbt_lookup_eq(
struct xfs_btree_cur *cur,
xfs_fileoff_t off,
xfs_fsblock_t bno,
xfs_filblks_t len,
int *stat) /* success/failure */
{
cur->bc_rec.b.br_startoff = off;
cur->bc_rec.b.br_startblock = bno;
cur->bc_rec.b.br_blockcount = len;
return xfs_btree_lookup(cur, XFS_LOOKUP_EQ, stat);
}
STATIC int /* error */
xfs_bmbt_lookup_ge(
struct xfs_btree_cur *cur,
xfs_fileoff_t off,
xfs_fsblock_t bno,
xfs_filblks_t len,
int *stat) /* success/failure */
{
cur->bc_rec.b.br_startoff = off;
cur->bc_rec.b.br_startblock = bno;
cur->bc_rec.b.br_blockcount = len;
return xfs_btree_lookup(cur, XFS_LOOKUP_GE, stat);
}
/*
* Check if the inode needs to be converted to btree format.
*/
static inline bool xfs_bmap_needs_btree(struct xfs_inode *ip, int whichfork)
{
return XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_NEXTENTS(ip, whichfork) >
XFS_IFORK_MAXEXT(ip, whichfork);
}
/*
* Check if the inode should be converted to extent format.
*/
static inline bool xfs_bmap_wants_extents(struct xfs_inode *ip, int whichfork)
{
return XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE &&
XFS_IFORK_NEXTENTS(ip, whichfork) <=
XFS_IFORK_MAXEXT(ip, whichfork);
}
/*
* Update the record referred to by cur to the value given
* by [off, bno, len, state].
* This either works (return 0) or gets an EFSCORRUPTED error.
*/
STATIC int
xfs_bmbt_update(
struct xfs_btree_cur *cur,
xfs_fileoff_t off,
xfs_fsblock_t bno,
xfs_filblks_t len,
xfs_exntst_t state)
{
union xfs_btree_rec rec;
xfs_bmbt_disk_set_allf(&rec.bmbt, off, bno, len, state);
return xfs_btree_update(cur, &rec);
}
/*
* Compute the worst-case number of indirect blocks that will be used
* for ip's delayed extent of length "len".
*/
STATIC xfs_filblks_t
xfs_bmap_worst_indlen(
xfs_inode_t *ip, /* incore inode pointer */
xfs_filblks_t len) /* delayed extent length */
{
int level; /* btree level number */
int maxrecs; /* maximum record count at this level */
xfs_mount_t *mp; /* mount structure */
xfs_filblks_t rval; /* return value */
mp = ip->i_mount;
maxrecs = mp->m_bmap_dmxr[0];
for (level = 0, rval = 0;
level < XFS_BM_MAXLEVELS(mp, XFS_DATA_FORK);
level++) {
len += maxrecs - 1;
do_div(len, maxrecs);
rval += len;
if (len == 1)
return rval + XFS_BM_MAXLEVELS(mp, XFS_DATA_FORK) -
level - 1;
if (level == 0)
maxrecs = mp->m_bmap_dmxr[1];
}
return rval;
}
/*
* Calculate the default attribute fork offset for newly created inodes.
*/
uint
xfs_default_attroffset(
struct xfs_inode *ip)
{
struct xfs_mount *mp = ip->i_mount;
uint offset;
if (mp->m_sb.sb_inodesize == 256) {
offset = XFS_LITINO(mp, ip->i_d.di_version) -
XFS_BMDR_SPACE_CALC(MINABTPTRS);
} else {
offset = XFS_BMDR_SPACE_CALC(6 * MINABTPTRS);
}
ASSERT(offset < XFS_LITINO(mp, ip->i_d.di_version));
return offset;
}
/*
* Helper routine to reset inode di_forkoff field when switching
* attribute fork from local to extent format - we reset it where
* possible to make space available for inline data fork extents.
*/
STATIC void
xfs_bmap_forkoff_reset(
xfs_mount_t *mp,
xfs_inode_t *ip,
int whichfork)
{
if (whichfork == XFS_ATTR_FORK &&
ip->i_d.di_format != XFS_DINODE_FMT_DEV &&
ip->i_d.di_format != XFS_DINODE_FMT_UUID &&
ip->i_d.di_format != XFS_DINODE_FMT_BTREE) {
uint dfl_forkoff = xfs_default_attroffset(ip) >> 3;
if (dfl_forkoff > ip->i_d.di_forkoff)
ip->i_d.di_forkoff = dfl_forkoff;
}
}
/*
* Extent tree block counting routines.
*/
/*
* Count leaf blocks given a range of extent records.
*/
STATIC void
xfs_bmap_count_leaves(
xfs_ifork_t *ifp,
xfs_extnum_t idx,
int numrecs,
int *count)
{
int b;
for (b = 0; b < numrecs; b++) {
xfs_bmbt_rec_host_t *frp = xfs_iext_get_ext(ifp, idx + b);
*count += xfs_bmbt_get_blockcount(frp);
}
}
/*
* Count leaf blocks given a range of extent records originally
* in btree format.
*/
STATIC void
xfs_bmap_disk_count_leaves(
struct xfs_mount *mp,
struct xfs_btree_block *block,
int numrecs,
int *count)
{
int b;
xfs_bmbt_rec_t *frp;
for (b = 1; b <= numrecs; b++) {
frp = XFS_BMBT_REC_ADDR(mp, block, b);
*count += xfs_bmbt_disk_get_blockcount(frp);
}
}
/*
* Recursively walks each level of a btree
* to count total fsblocks is use.
*/
STATIC int /* error */
xfs_bmap_count_tree(
xfs_mount_t *mp, /* file system mount point */
xfs_trans_t *tp, /* transaction pointer */
xfs_ifork_t *ifp, /* inode fork pointer */
xfs_fsblock_t blockno, /* file system block number */
int levelin, /* level in btree */
int *count) /* Count of blocks */
{
int error;
xfs_buf_t *bp, *nbp;
int level = levelin;
__be64 *pp;
xfs_fsblock_t bno = blockno;
xfs_fsblock_t nextbno;
struct xfs_btree_block *block, *nextblock;
int numrecs;
error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp, XFS_BMAP_BTREE_REF,
&xfs_bmbt_buf_ops);
if (error)
return error;
*count += 1;
block = XFS_BUF_TO_BLOCK(bp);
if (--level) {
/* Not at node above leaves, count this level of nodes */
nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
while (nextbno != NULLFSBLOCK) {
error = xfs_btree_read_bufl(mp, tp, nextbno, 0, &nbp,
XFS_BMAP_BTREE_REF,
&xfs_bmbt_buf_ops);
if (error)
return error;
*count += 1;
nextblock = XFS_BUF_TO_BLOCK(nbp);
nextbno = be64_to_cpu(nextblock->bb_u.l.bb_rightsib);
xfs_trans_brelse(tp, nbp);
}
/* Dive to the next level */
pp = XFS_BMBT_PTR_ADDR(mp, block, 1, mp->m_bmap_dmxr[1]);
bno = be64_to_cpu(*pp);
if (unlikely((error =
xfs_bmap_count_tree(mp, tp, ifp, bno, level, count)) < 0)) {
xfs_trans_brelse(tp, bp);
XFS_ERROR_REPORT("xfs_bmap_count_tree(1)",
XFS_ERRLEVEL_LOW, mp);
return XFS_ERROR(EFSCORRUPTED);
}
xfs_trans_brelse(tp, bp);
} else {
/* count all level 1 nodes and their leaves */
for (;;) {
nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
numrecs = be16_to_cpu(block->bb_numrecs);
xfs_bmap_disk_count_leaves(mp, block, numrecs, count);
xfs_trans_brelse(tp, bp);
if (nextbno == NULLFSBLOCK)
break;
bno = nextbno;
error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp,
XFS_BMAP_BTREE_REF,
&xfs_bmbt_buf_ops);
if (error)
return error;
*count += 1;
block = XFS_BUF_TO_BLOCK(bp);
}
}
return 0;
}
/*
* Count fsblocks of the given fork.
*/
int /* error */
xfs_bmap_count_blocks(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode */
int whichfork, /* data or attr fork */
int *count) /* out: count of blocks */
{
struct xfs_btree_block *block; /* current btree block */
xfs_fsblock_t bno; /* block # of "block" */
xfs_ifork_t *ifp; /* fork structure */
int level; /* btree level, for checking */
xfs_mount_t *mp; /* file system mount structure */
__be64 *pp; /* pointer to block address */
bno = NULLFSBLOCK;
mp = ip->i_mount;
ifp = XFS_IFORK_PTR(ip, whichfork);
if ( XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS ) {
xfs_bmap_count_leaves(ifp, 0,
ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t),
count);
return 0;
}
/*
* Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out.
*/
block = ifp->if_broot;
level = be16_to_cpu(block->bb_level);
ASSERT(level > 0);
pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, 1, ifp->if_broot_bytes);
bno = be64_to_cpu(*pp);
ASSERT(bno != NULLDFSBNO);
ASSERT(XFS_FSB_TO_AGNO(mp, bno) < mp->m_sb.sb_agcount);
ASSERT(XFS_FSB_TO_AGBNO(mp, bno) < mp->m_sb.sb_agblocks);
if (unlikely(xfs_bmap_count_tree(mp, tp, ifp, bno, level, count) < 0)) {
XFS_ERROR_REPORT("xfs_bmap_count_blocks(2)", XFS_ERRLEVEL_LOW,
mp);
return XFS_ERROR(EFSCORRUPTED);
}
return 0;
}
/*
* Debug/sanity checking code
*/
STATIC int
xfs_bmap_sanity_check(
struct xfs_mount *mp,
struct xfs_buf *bp,
int level)
{
struct xfs_btree_block *block = XFS_BUF_TO_BLOCK(bp);
if (block->bb_magic != cpu_to_be32(XFS_BMAP_CRC_MAGIC) &&
block->bb_magic != cpu_to_be32(XFS_BMAP_MAGIC))
return 0;
if (be16_to_cpu(block->bb_level) != level ||
be16_to_cpu(block->bb_numrecs) == 0 ||
be16_to_cpu(block->bb_numrecs) > mp->m_bmap_dmxr[level != 0])
return 0;
return 1;
}
#ifdef DEBUG
STATIC struct xfs_buf *
xfs_bmap_get_bp(
struct xfs_btree_cur *cur,
xfs_fsblock_t bno)
{
struct xfs_log_item_desc *lidp;
int i;
if (!cur)
return NULL;
for (i = 0; i < XFS_BTREE_MAXLEVELS; i++) {
if (!cur->bc_bufs[i])
break;
if (XFS_BUF_ADDR(cur->bc_bufs[i]) == bno)
return cur->bc_bufs[i];
}
/* Chase down all the log items to see if the bp is there */
list_for_each_entry(lidp, &cur->bc_tp->t_items, lid_trans) {
struct xfs_buf_log_item *bip;
bip = (struct xfs_buf_log_item *)lidp->lid_item;
if (bip->bli_item.li_type == XFS_LI_BUF &&
XFS_BUF_ADDR(bip->bli_buf) == bno)
return bip->bli_buf;
}
return NULL;
}
STATIC void
xfs_check_block(
struct xfs_btree_block *block,
xfs_mount_t *mp,
int root,
short sz)
{
int i, j, dmxr;
__be64 *pp, *thispa; /* pointer to block address */
xfs_bmbt_key_t *prevp, *keyp;
ASSERT(be16_to_cpu(block->bb_level) > 0);
prevp = NULL;
for( i = 1; i <= xfs_btree_get_numrecs(block); i++) {
dmxr = mp->m_bmap_dmxr[0];
keyp = XFS_BMBT_KEY_ADDR(mp, block, i);
if (prevp) {
ASSERT(be64_to_cpu(prevp->br_startoff) <
be64_to_cpu(keyp->br_startoff));
}
prevp = keyp;
/*
* Compare the block numbers to see if there are dups.
*/
if (root)
pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, i, sz);
else
pp = XFS_BMBT_PTR_ADDR(mp, block, i, dmxr);
for (j = i+1; j <= be16_to_cpu(block->bb_numrecs); j++) {
if (root)
thispa = XFS_BMAP_BROOT_PTR_ADDR(mp, block, j, sz);
else
thispa = XFS_BMBT_PTR_ADDR(mp, block, j, dmxr);
if (*thispa == *pp) {
xfs_warn(mp, "%s: thispa(%d) == pp(%d) %Ld",
__func__, j, i,
(unsigned long long)be64_to_cpu(*thispa));
panic("%s: ptrs are equal in node\n",
__func__);
}
}
}
}
/*
* Check that the extents for the inode ip are in the right order in all
* btree leaves.
*/
STATIC void
xfs_bmap_check_leaf_extents(
xfs_btree_cur_t *cur, /* btree cursor or null */
xfs_inode_t *ip, /* incore inode pointer */
int whichfork) /* data or attr fork */
{
struct xfs_btree_block *block; /* current btree block */
xfs_fsblock_t bno; /* block # of "block" */
xfs_buf_t *bp; /* buffer for "block" */
int error; /* error return value */
xfs_extnum_t i=0, j; /* index into the extents list */
xfs_ifork_t *ifp; /* fork structure */
int level; /* btree level, for checking */
xfs_mount_t *mp; /* file system mount structure */
__be64 *pp; /* pointer to block address */
xfs_bmbt_rec_t *ep; /* pointer to current extent */
xfs_bmbt_rec_t last = {0, 0}; /* last extent in prev block */
xfs_bmbt_rec_t *nextp; /* pointer to next extent */
int bp_release = 0;
if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE) {
return;
}
bno = NULLFSBLOCK;
mp = ip->i_mount;
ifp = XFS_IFORK_PTR(ip, whichfork);
block = ifp->if_broot;
/*
* Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out.
*/
level = be16_to_cpu(block->bb_level);
ASSERT(level > 0);
xfs_check_block(block, mp, 1, ifp->if_broot_bytes);
pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, 1, ifp->if_broot_bytes);
bno = be64_to_cpu(*pp);
ASSERT(bno != NULLDFSBNO);
ASSERT(XFS_FSB_TO_AGNO(mp, bno) < mp->m_sb.sb_agcount);
ASSERT(XFS_FSB_TO_AGBNO(mp, bno) < mp->m_sb.sb_agblocks);
/*
* Go down the tree until leaf level is reached, following the first
* pointer (leftmost) at each level.
*/
while (level-- > 0) {
/* See if buf is in cur first */
bp_release = 0;
bp = xfs_bmap_get_bp(cur, XFS_FSB_TO_DADDR(mp, bno));
if (!bp) {
bp_release = 1;
error = xfs_btree_read_bufl(mp, NULL, bno, 0, &bp,
XFS_BMAP_BTREE_REF,
&xfs_bmbt_buf_ops);
if (error)
goto error_norelse;
}
block = XFS_BUF_TO_BLOCK(bp);
XFS_WANT_CORRUPTED_GOTO(
xfs_bmap_sanity_check(mp, bp, level),
error0);
if (level == 0)
break;
/*
* Check this block for basic sanity (increasing keys and
* no duplicate blocks).
*/
xfs_check_block(block, mp, 0, 0);
pp = XFS_BMBT_PTR_ADDR(mp, block, 1, mp->m_bmap_dmxr[1]);
bno = be64_to_cpu(*pp);
XFS_WANT_CORRUPTED_GOTO(XFS_FSB_SANITY_CHECK(mp, bno), error0);
if (bp_release) {
bp_release = 0;
xfs_trans_brelse(NULL, bp);
}
}
/*
* Here with bp and block set to the leftmost leaf node in the tree.
*/
i = 0;
/*
* Loop over all leaf nodes checking that all extents are in the right order.
*/
for (;;) {
xfs_fsblock_t nextbno;
xfs_extnum_t num_recs;
num_recs = xfs_btree_get_numrecs(block);
/*
* Read-ahead the next leaf block, if any.
*/
nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
/*
* Check all the extents to make sure they are OK.
* If we had a previous block, the last entry should
* conform with the first entry in this one.
*/
ep = XFS_BMBT_REC_ADDR(mp, block, 1);
if (i) {
ASSERT(xfs_bmbt_disk_get_startoff(&last) +
xfs_bmbt_disk_get_blockcount(&last) <=
xfs_bmbt_disk_get_startoff(ep));
}
for (j = 1; j < num_recs; j++) {
nextp = XFS_BMBT_REC_ADDR(mp, block, j + 1);
ASSERT(xfs_bmbt_disk_get_startoff(ep) +
xfs_bmbt_disk_get_blockcount(ep) <=
xfs_bmbt_disk_get_startoff(nextp));
ep = nextp;
}
last = *ep;
i += num_recs;
if (bp_release) {
bp_release = 0;
xfs_trans_brelse(NULL, bp);
}
bno = nextbno;
/*
* If we've reached the end, stop.
*/
if (bno == NULLFSBLOCK)
break;
bp_release = 0;
bp = xfs_bmap_get_bp(cur, XFS_FSB_TO_DADDR(mp, bno));
if (!bp) {
bp_release = 1;
error = xfs_btree_read_bufl(mp, NULL, bno, 0, &bp,
XFS_BMAP_BTREE_REF,
&xfs_bmbt_buf_ops);
if (error)
goto error_norelse;
}
block = XFS_BUF_TO_BLOCK(bp);
}
if (bp_release) {
bp_release = 0;
xfs_trans_brelse(NULL, bp);
}
return;
error0:
xfs_warn(mp, "%s: at error0", __func__);
if (bp_release)
xfs_trans_brelse(NULL, bp);
error_norelse:
xfs_warn(mp, "%s: BAD after btree leaves for %d extents",
__func__, i);
panic("%s: CORRUPTED BTREE OR SOMETHING", __func__);
return;
}
/*
* Add bmap trace insert entries for all the contents of the extent records.
*/
void
xfs_bmap_trace_exlist(
xfs_inode_t *ip, /* incore inode pointer */
xfs_extnum_t cnt, /* count of entries in the list */
int whichfork, /* data or attr fork */
unsigned long caller_ip)
{
xfs_extnum_t idx; /* extent record index */
xfs_ifork_t *ifp; /* inode fork pointer */
int state = 0;
if (whichfork == XFS_ATTR_FORK)
state |= BMAP_ATTRFORK;
ifp = XFS_IFORK_PTR(ip, whichfork);
ASSERT(cnt == (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t)));
for (idx = 0; idx < cnt; idx++)
trace_xfs_extlist(ip, idx, whichfork, caller_ip);
}
/*
* Validate that the bmbt_irecs being returned from bmapi are valid
* given the callers original parameters. Specifically check the
* ranges of the returned irecs to ensure that they only extent beyond
* the given parameters if the XFS_BMAPI_ENTIRE flag was set.
*/
STATIC void
xfs_bmap_validate_ret(
xfs_fileoff_t bno,
xfs_filblks_t len,
int flags,
xfs_bmbt_irec_t *mval,
int nmap,
int ret_nmap)
{
int i; /* index to map values */
ASSERT(ret_nmap <= nmap);
for (i = 0; i < ret_nmap; i++) {
ASSERT(mval[i].br_blockcount > 0);
if (!(flags & XFS_BMAPI_ENTIRE)) {
ASSERT(mval[i].br_startoff >= bno);
ASSERT(mval[i].br_blockcount <= len);
ASSERT(mval[i].br_startoff + mval[i].br_blockcount <=
bno + len);
} else {
ASSERT(mval[i].br_startoff < bno + len);
ASSERT(mval[i].br_startoff + mval[i].br_blockcount >
bno);
}
ASSERT(i == 0 ||
mval[i - 1].br_startoff + mval[i - 1].br_blockcount ==
mval[i].br_startoff);
ASSERT(mval[i].br_startblock != DELAYSTARTBLOCK &&
mval[i].br_startblock != HOLESTARTBLOCK);
ASSERT(mval[i].br_state == XFS_EXT_NORM ||
mval[i].br_state == XFS_EXT_UNWRITTEN);
}
}
#else
#define xfs_bmap_check_leaf_extents(cur, ip, whichfork) do { } while (0)
#define xfs_bmap_validate_ret(bno,len,flags,mval,onmap,nmap)
#endif /* DEBUG */
/*
* bmap free list manipulation functions
*/
/*
* Add the extent to the list of extents to be free at transaction end.
* The list is maintained sorted (by block number).
*/
void
xfs_bmap_add_free(
xfs_fsblock_t bno, /* fs block number of extent */
xfs_filblks_t len, /* length of extent */
xfs_bmap_free_t *flist, /* list of extents */
xfs_mount_t *mp) /* mount point structure */
{
xfs_bmap_free_item_t *cur; /* current (next) element */
xfs_bmap_free_item_t *new; /* new element */
xfs_bmap_free_item_t *prev; /* previous element */
#ifdef DEBUG
xfs_agnumber_t agno;
xfs_agblock_t agbno;
ASSERT(bno != NULLFSBLOCK);
ASSERT(len > 0);
ASSERT(len <= MAXEXTLEN);
ASSERT(!isnullstartblock(bno));
agno = XFS_FSB_TO_AGNO(mp, bno);
agbno = XFS_FSB_TO_AGBNO(mp, bno);
ASSERT(agno < mp->m_sb.sb_agcount);
ASSERT(agbno < mp->m_sb.sb_agblocks);
ASSERT(len < mp->m_sb.sb_agblocks);
ASSERT(agbno + len <= mp->m_sb.sb_agblocks);
#endif
ASSERT(xfs_bmap_free_item_zone != NULL);
new = kmem_zone_alloc(xfs_bmap_free_item_zone, KM_SLEEP);
new->xbfi_startblock = bno;
new->xbfi_blockcount = (xfs_extlen_t)len;
for (prev = NULL, cur = flist->xbf_first;
cur != NULL;
prev = cur, cur = cur->xbfi_next) {
if (cur->xbfi_startblock >= bno)
break;
}
if (prev)
prev->xbfi_next = new;
else
flist->xbf_first = new;
new->xbfi_next = cur;
flist->xbf_count++;
}
/*
* Remove the entry "free" from the free item list. Prev points to the
* previous entry, unless "free" is the head of the list.
*/
STATIC void
xfs_bmap_del_free(
xfs_bmap_free_t *flist, /* free item list header */
xfs_bmap_free_item_t *prev, /* previous item on list, if any */
xfs_bmap_free_item_t *free) /* list item to be freed */
{
if (prev)
prev->xbfi_next = free->xbfi_next;
else
flist->xbf_first = free->xbfi_next;
flist->xbf_count--;
kmem_zone_free(xfs_bmap_free_item_zone, free);
}
/*
* Routine to be called at transaction's end by xfs_bmapi, xfs_bunmapi
* caller. Frees all the extents that need freeing, which must be done
* last due to locking considerations. We never free any extents in
* the first transaction.
*
* Return 1 if the given transaction was committed and a new one
* started, and 0 otherwise in the committed parameter.
*/
int /* error */
xfs_bmap_finish(
xfs_trans_t **tp, /* transaction pointer addr */
xfs_bmap_free_t *flist, /* i/o: list extents to free */
int *committed) /* xact committed or not */
{
xfs_efd_log_item_t *efd; /* extent free data */
xfs_efi_log_item_t *efi; /* extent free intention */
int error; /* error return value */
xfs_bmap_free_item_t *free; /* free extent item */
unsigned int logres; /* new log reservation */
unsigned int logcount; /* new log count */
xfs_mount_t *mp; /* filesystem mount structure */
xfs_bmap_free_item_t *next; /* next item on free list */
xfs_trans_t *ntp; /* new transaction pointer */
ASSERT((*tp)->t_flags & XFS_TRANS_PERM_LOG_RES);
if (flist->xbf_count == 0) {
*committed = 0;
return 0;
}
ntp = *tp;
efi = xfs_trans_get_efi(ntp, flist->xbf_count);
for (free = flist->xbf_first; free; free = free->xbfi_next)
xfs_trans_log_efi_extent(ntp, efi, free->xbfi_startblock,
free->xbfi_blockcount);
logres = ntp->t_log_res;
logcount = ntp->t_log_count;
ntp = xfs_trans_dup(*tp);
error = xfs_trans_commit(*tp, 0);
*tp = ntp;
*committed = 1;
/*
* We have a new transaction, so we should return committed=1,
* even though we're returning an error.
*/
if (error)
return error;
/*
* transaction commit worked ok so we can drop the extra ticket
* reference that we gained in xfs_trans_dup()
*/
xfs_log_ticket_put(ntp->t_ticket);
if ((error = xfs_trans_reserve(ntp, 0, logres, 0, XFS_TRANS_PERM_LOG_RES,
logcount)))
return error;
efd = xfs_trans_get_efd(ntp, efi, flist->xbf_count);
for (free = flist->xbf_first; free != NULL; free = next) {
next = free->xbfi_next;
if ((error = xfs_free_extent(ntp, free->xbfi_startblock,
free->xbfi_blockcount))) {
/*
* The bmap free list will be cleaned up at a
* higher level. The EFI will be canceled when
* this transaction is aborted.
* Need to force shutdown here to make sure it
* happens, since this transaction may not be
* dirty yet.
*/
mp = ntp->t_mountp;
if (!XFS_FORCED_SHUTDOWN(mp))
xfs_force_shutdown(mp,
(error == EFSCORRUPTED) ?
SHUTDOWN_CORRUPT_INCORE :
SHUTDOWN_META_IO_ERROR);
return error;
}
xfs_trans_log_efd_extent(ntp, efd, free->xbfi_startblock,
free->xbfi_blockcount);
xfs_bmap_del_free(flist, NULL, free);
}
return 0;
}
/*
* Free up any items left in the list.
*/
void
xfs_bmap_cancel(
xfs_bmap_free_t *flist) /* list of bmap_free_items */
{
xfs_bmap_free_item_t *free; /* free list item */
xfs_bmap_free_item_t *next;
if (flist->xbf_count == 0)
return;
ASSERT(flist->xbf_first != NULL);
for (free = flist->xbf_first; free; free = next) {
next = free->xbfi_next;
xfs_bmap_del_free(flist, NULL, free);
}
ASSERT(flist->xbf_count == 0);
}
/*
* Inode fork format manipulation functions
*/
/*
* Transform a btree format file with only one leaf node, where the
* extents list will fit in the inode, into an extents format file.
* Since the file extents are already in-core, all we have to do is
* give up the space for the btree root and pitch the leaf block.
*/
STATIC int /* error */
xfs_bmap_btree_to_extents(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_btree_cur_t *cur, /* btree cursor */
int *logflagsp, /* inode logging flags */
int whichfork) /* data or attr fork */
{
/* REFERENCED */
struct xfs_btree_block *cblock;/* child btree block */
xfs_fsblock_t cbno; /* child block number */
xfs_buf_t *cbp; /* child block's buffer */
int error; /* error return value */
xfs_ifork_t *ifp; /* inode fork data */
xfs_mount_t *mp; /* mount point structure */
__be64 *pp; /* ptr to block address */
struct xfs_btree_block *rblock;/* root btree block */
mp = ip->i_mount;
ifp = XFS_IFORK_PTR(ip, whichfork);
ASSERT(ifp->if_flags & XFS_IFEXTENTS);
ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE);
rblock = ifp->if_broot;
ASSERT(be16_to_cpu(rblock->bb_level) == 1);
ASSERT(be16_to_cpu(rblock->bb_numrecs) == 1);
ASSERT(xfs_bmbt_maxrecs(mp, ifp->if_broot_bytes, 0) == 1);
pp = XFS_BMAP_BROOT_PTR_ADDR(mp, rblock, 1, ifp->if_broot_bytes);
cbno = be64_to_cpu(*pp);
*logflagsp = 0;
#ifdef DEBUG
if ((error = xfs_btree_check_lptr(cur, cbno, 1)))
return error;
#endif
error = xfs_btree_read_bufl(mp, tp, cbno, 0, &cbp, XFS_BMAP_BTREE_REF,
&xfs_bmbt_buf_ops);
if (error)
return error;
cblock = XFS_BUF_TO_BLOCK(cbp);
if ((error = xfs_btree_check_block(cur, cblock, 0, cbp)))
return error;
xfs_bmap_add_free(cbno, 1, cur->bc_private.b.flist, mp);
ip->i_d.di_nblocks--;
xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_BCOUNT, -1L);
xfs_trans_binval(tp, cbp);
if (cur->bc_bufs[0] == cbp)
cur->bc_bufs[0] = NULL;
xfs_iroot_realloc(ip, -1, whichfork);
ASSERT(ifp->if_broot == NULL);
ASSERT((ifp->if_flags & XFS_IFBROOT) == 0);
XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_EXTENTS);
*logflagsp = XFS_ILOG_CORE | xfs_ilog_fext(whichfork);
return 0;
}
/*
* Convert an extents-format file into a btree-format file.
* The new file will have a root block (in the inode) and a single child block.
*/
STATIC int /* error */
xfs_bmap_extents_to_btree(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_fsblock_t *firstblock, /* first-block-allocated */
xfs_bmap_free_t *flist, /* blocks freed in xaction */
xfs_btree_cur_t **curp, /* cursor returned to caller */
int wasdel, /* converting a delayed alloc */
int *logflagsp, /* inode logging flags */
int whichfork) /* data or attr fork */
{
struct xfs_btree_block *ablock; /* allocated (child) bt block */
xfs_buf_t *abp; /* buffer for ablock */
xfs_alloc_arg_t args; /* allocation arguments */
xfs_bmbt_rec_t *arp; /* child record pointer */
struct xfs_btree_block *block; /* btree root block */
xfs_btree_cur_t *cur; /* bmap btree cursor */
xfs_bmbt_rec_host_t *ep; /* extent record pointer */
int error; /* error return value */
xfs_extnum_t i, cnt; /* extent record index */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_bmbt_key_t *kp; /* root block key pointer */
xfs_mount_t *mp; /* mount structure */
xfs_extnum_t nextents; /* number of file extents */
xfs_bmbt_ptr_t *pp; /* root block address pointer */
mp = ip->i_mount;
ifp = XFS_IFORK_PTR(ip, whichfork);
ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS);
/*
* Make space in the inode incore.
*/
xfs_iroot_realloc(ip, 1, whichfork);
ifp->if_flags |= XFS_IFBROOT;
/*
* Fill in the root.
*/
block = ifp->if_broot;
if (xfs_sb_version_hascrc(&mp->m_sb))
xfs_btree_init_block_int(mp, block, XFS_BUF_DADDR_NULL,
XFS_BMAP_CRC_MAGIC, 1, 1, ip->i_ino,
XFS_BTREE_LONG_PTRS | XFS_BTREE_CRC_BLOCKS);
else
xfs_btree_init_block_int(mp, block, XFS_BUF_DADDR_NULL,
XFS_BMAP_MAGIC, 1, 1, ip->i_ino,
XFS_BTREE_LONG_PTRS);
/*
* Need a cursor. Can't allocate until bb_level is filled in.
*/
cur = xfs_bmbt_init_cursor(mp, tp, ip, whichfork);
cur->bc_private.b.firstblock = *firstblock;
cur->bc_private.b.flist = flist;
cur->bc_private.b.flags = wasdel ? XFS_BTCUR_BPRV_WASDEL : 0;
/*
* Convert to a btree with two levels, one record in root.
*/
XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_BTREE);
memset(&args, 0, sizeof(args));
args.tp = tp;
args.mp = mp;
args.firstblock = *firstblock;
if (*firstblock == NULLFSBLOCK) {
args.type = XFS_ALLOCTYPE_START_BNO;
args.fsbno = XFS_INO_TO_FSB(mp, ip->i_ino);
} else if (flist->xbf_low) {
args.type = XFS_ALLOCTYPE_START_BNO;
args.fsbno = *firstblock;
} else {
args.type = XFS_ALLOCTYPE_NEAR_BNO;
args.fsbno = *firstblock;
}
args.minlen = args.maxlen = args.prod = 1;
args.wasdel = wasdel;
*logflagsp = 0;
if ((error = xfs_alloc_vextent(&args))) {
xfs_iroot_realloc(ip, -1, whichfork);
xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
return error;
}
/*
* Allocation can't fail, the space was reserved.
*/
ASSERT(args.fsbno != NULLFSBLOCK);
ASSERT(*firstblock == NULLFSBLOCK ||
args.agno == XFS_FSB_TO_AGNO(mp, *firstblock) ||
(flist->xbf_low &&
args.agno > XFS_FSB_TO_AGNO(mp, *firstblock)));
*firstblock = cur->bc_private.b.firstblock = args.fsbno;
cur->bc_private.b.allocated++;
ip->i_d.di_nblocks++;
xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_BCOUNT, 1L);
abp = xfs_btree_get_bufl(mp, tp, args.fsbno, 0);
/*
* Fill in the child block.
*/
abp->b_ops = &xfs_bmbt_buf_ops;
ablock = XFS_BUF_TO_BLOCK(abp);
if (xfs_sb_version_hascrc(&mp->m_sb))
xfs_btree_init_block_int(mp, ablock, abp->b_bn,
XFS_BMAP_CRC_MAGIC, 0, 0, ip->i_ino,
XFS_BTREE_LONG_PTRS | XFS_BTREE_CRC_BLOCKS);
else
xfs_btree_init_block_int(mp, ablock, abp->b_bn,
XFS_BMAP_MAGIC, 0, 0, ip->i_ino,
XFS_BTREE_LONG_PTRS);
arp = XFS_BMBT_REC_ADDR(mp, ablock, 1);
nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
for (cnt = i = 0; i < nextents; i++) {
ep = xfs_iext_get_ext(ifp, i);
if (!isnullstartblock(xfs_bmbt_get_startblock(ep))) {
arp->l0 = cpu_to_be64(ep->l0);
arp->l1 = cpu_to_be64(ep->l1);
arp++; cnt++;
}
}
ASSERT(cnt == XFS_IFORK_NEXTENTS(ip, whichfork));
xfs_btree_set_numrecs(ablock, cnt);
/*
* Fill in the root key and pointer.
*/
kp = XFS_BMBT_KEY_ADDR(mp, block, 1);
arp = XFS_BMBT_REC_ADDR(mp, ablock, 1);
kp->br_startoff = cpu_to_be64(xfs_bmbt_disk_get_startoff(arp));
pp = XFS_BMBT_PTR_ADDR(mp, block, 1, xfs_bmbt_get_maxrecs(cur,
be16_to_cpu(block->bb_level)));
*pp = cpu_to_be64(args.fsbno);
/*
* Do all this logging at the end so that
* the root is at the right level.
*/
xfs_btree_log_block(cur, abp, XFS_BB_ALL_BITS);
xfs_btree_log_recs(cur, abp, 1, be16_to_cpu(ablock->bb_numrecs));
ASSERT(*curp == NULL);
*curp = cur;
*logflagsp = XFS_ILOG_CORE | xfs_ilog_fbroot(whichfork);
return 0;
}
/*
* Convert a local file to an extents file.
* This code is out of bounds for data forks of regular files,
* since the file data needs to get logged so things will stay consistent.
* (The bmap-level manipulations are ok, though).
*/
STATIC int /* error */
xfs_bmap_local_to_extents(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_fsblock_t *firstblock, /* first block allocated in xaction */
xfs_extlen_t total, /* total blocks needed by transaction */
int *logflagsp, /* inode logging flags */
int whichfork,
void (*init_fn)(struct xfs_trans *tp,
struct xfs_buf *bp,
struct xfs_inode *ip,
struct xfs_ifork *ifp))
{
int error; /* error return value */
int flags; /* logging flags returned */
xfs_ifork_t *ifp; /* inode fork pointer */
/*
* We don't want to deal with the case of keeping inode data inline yet.
* So sending the data fork of a regular inode is invalid.
*/
ASSERT(!(S_ISREG(ip->i_d.di_mode) && whichfork == XFS_DATA_FORK));
ifp = XFS_IFORK_PTR(ip, whichfork);
ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL);
flags = 0;
error = 0;
if (ifp->if_bytes) {
xfs_alloc_arg_t args; /* allocation arguments */
xfs_buf_t *bp; /* buffer for extent block */
xfs_bmbt_rec_host_t *ep;/* extent record pointer */
ASSERT((ifp->if_flags &
(XFS_IFINLINE|XFS_IFEXTENTS|XFS_IFEXTIREC)) == XFS_IFINLINE);
memset(&args, 0, sizeof(args));
args.tp = tp;
args.mp = ip->i_mount;
args.firstblock = *firstblock;
/*
* Allocate a block. We know we need only one, since the
* file currently fits in an inode.
*/
if (*firstblock == NULLFSBLOCK) {
args.fsbno = XFS_INO_TO_FSB(args.mp, ip->i_ino);
args.type = XFS_ALLOCTYPE_START_BNO;
} else {
args.fsbno = *firstblock;
args.type = XFS_ALLOCTYPE_NEAR_BNO;
}
args.total = total;
args.minlen = args.maxlen = args.prod = 1;
error = xfs_alloc_vextent(&args);
if (error)
goto done;
/* Can't fail, the space was reserved. */
ASSERT(args.fsbno != NULLFSBLOCK);
ASSERT(args.len == 1);
*firstblock = args.fsbno;
bp = xfs_btree_get_bufl(args.mp, tp, args.fsbno, 0);
/* initialise the block and copy the data */
init_fn(tp, bp, ip, ifp);
/* account for the change in fork size and log everything */
xfs_trans_log_buf(tp, bp, 0, ifp->if_bytes - 1);
xfs_bmap_forkoff_reset(args.mp, ip, whichfork);
xfs_idata_realloc(ip, -ifp->if_bytes, whichfork);
xfs_iext_add(ifp, 0, 1);
ep = xfs_iext_get_ext(ifp, 0);
xfs_bmbt_set_allf(ep, 0, args.fsbno, 1, XFS_EXT_NORM);
trace_xfs_bmap_post_update(ip, 0,
whichfork == XFS_ATTR_FORK ? BMAP_ATTRFORK : 0,
_THIS_IP_);
XFS_IFORK_NEXT_SET(ip, whichfork, 1);
ip->i_d.di_nblocks = 1;
xfs_trans_mod_dquot_byino(tp, ip,
XFS_TRANS_DQ_BCOUNT, 1L);
flags |= xfs_ilog_fext(whichfork);
} else {
ASSERT(XFS_IFORK_NEXTENTS(ip, whichfork) == 0);
xfs_bmap_forkoff_reset(ip->i_mount, ip, whichfork);
}
ifp->if_flags &= ~XFS_IFINLINE;
ifp->if_flags |= XFS_IFEXTENTS;
XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_EXTENTS);
flags |= XFS_ILOG_CORE;
done:
*logflagsp = flags;
return error;
}
/*
* Called from xfs_bmap_add_attrfork to handle btree format files.
*/
STATIC int /* error */
xfs_bmap_add_attrfork_btree(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_fsblock_t *firstblock, /* first block allocated */
xfs_bmap_free_t *flist, /* blocks to free at commit */
int *flags) /* inode logging flags */
{
xfs_btree_cur_t *cur; /* btree cursor */
int error; /* error return value */
xfs_mount_t *mp; /* file system mount struct */
int stat; /* newroot status */
mp = ip->i_mount;
if (ip->i_df.if_broot_bytes <= XFS_IFORK_DSIZE(ip))
*flags |= XFS_ILOG_DBROOT;
else {
cur = xfs_bmbt_init_cursor(mp, tp, ip, XFS_DATA_FORK);
cur->bc_private.b.flist = flist;
cur->bc_private.b.firstblock = *firstblock;
if ((error = xfs_bmbt_lookup_ge(cur, 0, 0, 0, &stat)))
goto error0;
/* must be at least one entry */
XFS_WANT_CORRUPTED_GOTO(stat == 1, error0);
if ((error = xfs_btree_new_iroot(cur, flags, &stat)))
goto error0;
if (stat == 0) {
xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
return XFS_ERROR(ENOSPC);
}
*firstblock = cur->bc_private.b.firstblock;
cur->bc_private.b.allocated = 0;
xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
}
return 0;
error0:
xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
return error;
}
/*
* Called from xfs_bmap_add_attrfork to handle extents format files.
*/
STATIC int /* error */
xfs_bmap_add_attrfork_extents(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_fsblock_t *firstblock, /* first block allocated */
xfs_bmap_free_t *flist, /* blocks to free at commit */
int *flags) /* inode logging flags */
{
xfs_btree_cur_t *cur; /* bmap btree cursor */
int error; /* error return value */
if (ip->i_d.di_nextents * sizeof(xfs_bmbt_rec_t) <= XFS_IFORK_DSIZE(ip))
return 0;
cur = NULL;
error = xfs_bmap_extents_to_btree(tp, ip, firstblock, flist, &cur, 0,
flags, XFS_DATA_FORK);
if (cur) {
cur->bc_private.b.allocated = 0;
xfs_btree_del_cursor(cur,
error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
}
return error;
}
/*
* Block initialisation function for local to extent format conversion.
*
* This shouldn't actually be called by anyone, so make sure debug kernels cause
* a noticable failure.
*/
STATIC void
xfs_bmap_local_to_extents_init_fn(
struct xfs_trans *tp,
struct xfs_buf *bp,
struct xfs_inode *ip,
struct xfs_ifork *ifp)
{
ASSERT(0);
bp->b_ops = &xfs_bmbt_buf_ops;
memcpy(bp->b_addr, ifp->if_u1.if_data, ifp->if_bytes);
xfs_trans_buf_set_type(tp, bp, XFS_BLFT_BTREE_BUF);
}
/*
* Called from xfs_bmap_add_attrfork to handle local format files. Each
* different data fork content type needs a different callout to do the
* conversion. Some are basic and only require special block initialisation
* callouts for the data formating, others (directories) are so specialised they
* handle everything themselves.
*
* XXX (dgc): investigate whether directory conversion can use the generic
* formatting callout. It should be possible - it's just a very complex
* formatter.
*/
STATIC int /* error */
xfs_bmap_add_attrfork_local(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_fsblock_t *firstblock, /* first block allocated */
xfs_bmap_free_t *flist, /* blocks to free at commit */
int *flags) /* inode logging flags */
{
xfs_da_args_t dargs; /* args for dir/attr code */
if (ip->i_df.if_bytes <= XFS_IFORK_DSIZE(ip))
return 0;
if (S_ISDIR(ip->i_d.di_mode)) {
memset(&dargs, 0, sizeof(dargs));
dargs.dp = ip;
dargs.firstblock = firstblock;
dargs.flist = flist;
dargs.total = ip->i_mount->m_dirblkfsbs;
dargs.whichfork = XFS_DATA_FORK;
dargs.trans = tp;
return xfs_dir2_sf_to_block(&dargs);
}
if (S_ISLNK(ip->i_d.di_mode))
return xfs_bmap_local_to_extents(tp, ip, firstblock, 1,
flags, XFS_DATA_FORK,
xfs_symlink_local_to_remote);
return xfs_bmap_local_to_extents(tp, ip, firstblock, 1, flags,
XFS_DATA_FORK,
xfs_bmap_local_to_extents_init_fn);
}
/*
* Convert inode from non-attributed to attributed.
* Must not be in a transaction, ip must not be locked.
*/
int /* error code */
xfs_bmap_add_attrfork(
xfs_inode_t *ip, /* incore inode pointer */
int size, /* space new attribute needs */
int rsvd) /* xact may use reserved blks */
{
xfs_fsblock_t firstblock; /* 1st block/ag allocated */
xfs_bmap_free_t flist; /* freed extent records */
xfs_mount_t *mp; /* mount structure */
xfs_trans_t *tp; /* transaction pointer */
int blks; /* space reservation */
int version = 1; /* superblock attr version */
int committed; /* xaction was committed */
int logflags; /* logging flags */
int error; /* error return value */
ASSERT(XFS_IFORK_Q(ip) == 0);
mp = ip->i_mount;
ASSERT(!XFS_NOT_DQATTACHED(mp, ip));
tp = xfs_trans_alloc(mp, XFS_TRANS_ADDAFORK);
blks = XFS_ADDAFORK_SPACE_RES(mp);
if (rsvd)
tp->t_flags |= XFS_TRANS_RESERVE;
if ((error = xfs_trans_reserve(tp, blks, XFS_ADDAFORK_LOG_RES(mp), 0,
XFS_TRANS_PERM_LOG_RES, XFS_ADDAFORK_LOG_COUNT)))
goto error0;
xfs_ilock(ip, XFS_ILOCK_EXCL);
error = xfs_trans_reserve_quota_nblks(tp, ip, blks, 0, rsvd ?
XFS_QMOPT_RES_REGBLKS | XFS_QMOPT_FORCE_RES :
XFS_QMOPT_RES_REGBLKS);
if (error) {
xfs_iunlock(ip, XFS_ILOCK_EXCL);
xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES);
return error;
}
if (XFS_IFORK_Q(ip))
goto error1;
if (ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS) {
/*
* For inodes coming from pre-6.2 filesystems.
*/
ASSERT(ip->i_d.di_aformat == 0);
ip->i_d.di_aformat = XFS_DINODE_FMT_EXTENTS;
}
ASSERT(ip->i_d.di_anextents == 0);
xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
switch (ip->i_d.di_format) {
case XFS_DINODE_FMT_DEV:
ip->i_d.di_forkoff = roundup(sizeof(xfs_dev_t), 8) >> 3;
break;
case XFS_DINODE_FMT_UUID:
ip->i_d.di_forkoff = roundup(sizeof(uuid_t), 8) >> 3;
break;
case XFS_DINODE_FMT_LOCAL:
case XFS_DINODE_FMT_EXTENTS:
case XFS_DINODE_FMT_BTREE:
ip->i_d.di_forkoff = xfs_attr_shortform_bytesfit(ip, size);
if (!ip->i_d.di_forkoff)
ip->i_d.di_forkoff = xfs_default_attroffset(ip) >> 3;
else if (mp->m_flags & XFS_MOUNT_ATTR2)
version = 2;
break;
default:
ASSERT(0);
error = XFS_ERROR(EINVAL);
goto error1;
}
ASSERT(ip->i_afp == NULL);
ip->i_afp = kmem_zone_zalloc(xfs_ifork_zone, KM_SLEEP);
ip->i_afp->if_flags = XFS_IFEXTENTS;
logflags = 0;
xfs_bmap_init(&flist, &firstblock);
switch (ip->i_d.di_format) {
case XFS_DINODE_FMT_LOCAL:
error = xfs_bmap_add_attrfork_local(tp, ip, &firstblock, &flist,
&logflags);
break;
case XFS_DINODE_FMT_EXTENTS:
error = xfs_bmap_add_attrfork_extents(tp, ip, &firstblock,
&flist, &logflags);
break;
case XFS_DINODE_FMT_BTREE:
error = xfs_bmap_add_attrfork_btree(tp, ip, &firstblock, &flist,
&logflags);
break;
default:
error = 0;
break;
}
if (logflags)
xfs_trans_log_inode(tp, ip, logflags);
if (error)
goto error2;
if (!xfs_sb_version_hasattr(&mp->m_sb) ||
(!xfs_sb_version_hasattr2(&mp->m_sb) && version == 2)) {
__int64_t sbfields = 0;
spin_lock(&mp->m_sb_lock);
if (!xfs_sb_version_hasattr(&mp->m_sb)) {
xfs_sb_version_addattr(&mp->m_sb);
sbfields |= XFS_SB_VERSIONNUM;
}
if (!xfs_sb_version_hasattr2(&mp->m_sb) && version == 2) {
xfs_sb_version_addattr2(&mp->m_sb);
sbfields |= (XFS_SB_VERSIONNUM | XFS_SB_FEATURES2);
}
if (sbfields) {
spin_unlock(&mp->m_sb_lock);
xfs_mod_sb(tp, sbfields);
} else
spin_unlock(&mp->m_sb_lock);
}
error = xfs_bmap_finish(&tp, &flist, &committed);
if (error)
goto error2;
return xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
error2:
xfs_bmap_cancel(&flist);
error1:
xfs_iunlock(ip, XFS_ILOCK_EXCL);
error0:
xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES|XFS_TRANS_ABORT);
return error;
}
/*
* Internal and external extent tree search functions.
*/
/*
* Read in the extents to if_extents.
* All inode fields are set up by caller, we just traverse the btree
* and copy the records in. If the file system cannot contain unwritten
* extents, the records are checked for no "state" flags.
*/
int /* error */
xfs_bmap_read_extents(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode */
int whichfork) /* data or attr fork */
{
struct xfs_btree_block *block; /* current btree block */
xfs_fsblock_t bno; /* block # of "block" */
xfs_buf_t *bp; /* buffer for "block" */
int error; /* error return value */
xfs_exntfmt_t exntf; /* XFS_EXTFMT_NOSTATE, if checking */
xfs_extnum_t i, j; /* index into the extents list */
xfs_ifork_t *ifp; /* fork structure */
int level; /* btree level, for checking */
xfs_mount_t *mp; /* file system mount structure */
__be64 *pp; /* pointer to block address */
/* REFERENCED */
xfs_extnum_t room; /* number of entries there's room for */
bno = NULLFSBLOCK;
mp = ip->i_mount;
ifp = XFS_IFORK_PTR(ip, whichfork);
exntf = (whichfork != XFS_DATA_FORK) ? XFS_EXTFMT_NOSTATE :
XFS_EXTFMT_INODE(ip);
block = ifp->if_broot;
/*
* Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out.
*/
level = be16_to_cpu(block->bb_level);
ASSERT(level > 0);
pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, 1, ifp->if_broot_bytes);
bno = be64_to_cpu(*pp);
ASSERT(bno != NULLDFSBNO);
ASSERT(XFS_FSB_TO_AGNO(mp, bno) < mp->m_sb.sb_agcount);
ASSERT(XFS_FSB_TO_AGBNO(mp, bno) < mp->m_sb.sb_agblocks);
/*
* Go down the tree until leaf level is reached, following the first
* pointer (leftmost) at each level.
*/
while (level-- > 0) {
error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp,
XFS_BMAP_BTREE_REF, &xfs_bmbt_buf_ops);
if (error)
return error;
block = XFS_BUF_TO_BLOCK(bp);
XFS_WANT_CORRUPTED_GOTO(
xfs_bmap_sanity_check(mp, bp, level),
error0);
if (level == 0)
break;
pp = XFS_BMBT_PTR_ADDR(mp, block, 1, mp->m_bmap_dmxr[1]);
bno = be64_to_cpu(*pp);
XFS_WANT_CORRUPTED_GOTO(XFS_FSB_SANITY_CHECK(mp, bno), error0);
xfs_trans_brelse(tp, bp);
}
/*
* Here with bp and block set to the leftmost leaf node in the tree.
*/
room = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
i = 0;
/*
* Loop over all leaf nodes. Copy information to the extent records.
*/
for (;;) {
xfs_bmbt_rec_t *frp;
xfs_fsblock_t nextbno;
xfs_extnum_t num_recs;
xfs_extnum_t start;
num_recs = xfs_btree_get_numrecs(block);
if (unlikely(i + num_recs > room)) {
ASSERT(i + num_recs <= room);
xfs_warn(ip->i_mount,
"corrupt dinode %Lu, (btree extents).",
(unsigned long long) ip->i_ino);
XFS_CORRUPTION_ERROR("xfs_bmap_read_extents(1)",
XFS_ERRLEVEL_LOW, ip->i_mount, block);
goto error0;
}
XFS_WANT_CORRUPTED_GOTO(
xfs_bmap_sanity_check(mp, bp, 0),
error0);
/*
* Read-ahead the next leaf block, if any.
*/
nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
if (nextbno != NULLFSBLOCK)
xfs_btree_reada_bufl(mp, nextbno, 1,
&xfs_bmbt_buf_ops);
/*
* Copy records into the extent records.
*/
frp = XFS_BMBT_REC_ADDR(mp, block, 1);
start = i;
for (j = 0; j < num_recs; j++, i++, frp++) {
xfs_bmbt_rec_host_t *trp = xfs_iext_get_ext(ifp, i);
trp->l0 = be64_to_cpu(frp->l0);
trp->l1 = be64_to_cpu(frp->l1);
}
if (exntf == XFS_EXTFMT_NOSTATE) {
/*
* Check all attribute bmap btree records and
* any "older" data bmap btree records for a
* set bit in the "extent flag" position.
*/
if (unlikely(xfs_check_nostate_extents(ifp,
start, num_recs))) {
XFS_ERROR_REPORT("xfs_bmap_read_extents(2)",
XFS_ERRLEVEL_LOW,
ip->i_mount);
goto error0;
}
}
xfs_trans_brelse(tp, bp);
bno = nextbno;
/*
* If we've reached the end, stop.
*/
if (bno == NULLFSBLOCK)
break;
error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp,
XFS_BMAP_BTREE_REF, &xfs_bmbt_buf_ops);
if (error)
return error;
block = XFS_BUF_TO_BLOCK(bp);
}
ASSERT(i == (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t)));
ASSERT(i == XFS_IFORK_NEXTENTS(ip, whichfork));
XFS_BMAP_TRACE_EXLIST(ip, i, whichfork);
return 0;
error0:
xfs_trans_brelse(tp, bp);
return XFS_ERROR(EFSCORRUPTED);
}
/*
* Search the extent records for the entry containing block bno.
* If bno lies in a hole, point to the next entry. If bno lies
* past eof, *eofp will be set, and *prevp will contain the last
* entry (null if none). Else, *lastxp will be set to the index
* of the found entry; *gotp will contain the entry.
*/
STATIC xfs_bmbt_rec_host_t * /* pointer to found extent entry */
xfs_bmap_search_multi_extents(
xfs_ifork_t *ifp, /* inode fork pointer */
xfs_fileoff_t bno, /* block number searched for */
int *eofp, /* out: end of file found */
xfs_extnum_t *lastxp, /* out: last extent index */
xfs_bmbt_irec_t *gotp, /* out: extent entry found */
xfs_bmbt_irec_t *prevp) /* out: previous extent entry found */
{
xfs_bmbt_rec_host_t *ep; /* extent record pointer */
xfs_extnum_t lastx; /* last extent index */
/*
* Initialize the extent entry structure to catch access to
* uninitialized br_startblock field.
*/
gotp->br_startoff = 0xffa5a5a5a5a5a5a5LL;
gotp->br_blockcount = 0xa55a5a5a5a5a5a5aLL;
gotp->br_state = XFS_EXT_INVALID;
#if XFS_BIG_BLKNOS
gotp->br_startblock = 0xffffa5a5a5a5a5a5LL;
#else
gotp->br_startblock = 0xffffa5a5;
#endif
prevp->br_startoff = NULLFILEOFF;
ep = xfs_iext_bno_to_ext(ifp, bno, &lastx);
if (lastx > 0) {
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, lastx - 1), prevp);
}
if (lastx < (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t))) {
xfs_bmbt_get_all(ep, gotp);
*eofp = 0;
} else {
if (lastx > 0) {
*gotp = *prevp;
}
*eofp = 1;
ep = NULL;
}
*lastxp = lastx;
return ep;
}
/*
* Search the extents list for the inode, for the extent containing bno.
* If bno lies in a hole, point to the next entry. If bno lies past eof,
* *eofp will be set, and *prevp will contain the last entry (null if none).
* Else, *lastxp will be set to the index of the found
* entry; *gotp will contain the entry.
*/
STATIC xfs_bmbt_rec_host_t * /* pointer to found extent entry */
xfs_bmap_search_extents(
xfs_inode_t *ip, /* incore inode pointer */
xfs_fileoff_t bno, /* block number searched for */
int fork, /* data or attr fork */
int *eofp, /* out: end of file found */
xfs_extnum_t *lastxp, /* out: last extent index */
xfs_bmbt_irec_t *gotp, /* out: extent entry found */
xfs_bmbt_irec_t *prevp) /* out: previous extent entry found */
{
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_bmbt_rec_host_t *ep; /* extent record pointer */
XFS_STATS_INC(xs_look_exlist);
ifp = XFS_IFORK_PTR(ip, fork);
ep = xfs_bmap_search_multi_extents(ifp, bno, eofp, lastxp, gotp, prevp);
if (unlikely(!(gotp->br_startblock) && (*lastxp != NULLEXTNUM) &&
!(XFS_IS_REALTIME_INODE(ip) && fork == XFS_DATA_FORK))) {
xfs_alert_tag(ip->i_mount, XFS_PTAG_FSBLOCK_ZERO,
"Access to block zero in inode %llu "
"start_block: %llx start_off: %llx "
"blkcnt: %llx extent-state: %x lastx: %x\n",
(unsigned long long)ip->i_ino,
(unsigned long long)gotp->br_startblock,
(unsigned long long)gotp->br_startoff,
(unsigned long long)gotp->br_blockcount,
gotp->br_state, *lastxp);
*lastxp = NULLEXTNUM;
*eofp = 1;
return NULL;
}
return ep;
}
/*
* Returns the file-relative block number of the first unused block(s)
* in the file with at least "len" logically contiguous blocks free.
* This is the lowest-address hole if the file has holes, else the first block
* past the end of file.
* Return 0 if the file is currently local (in-inode).
*/
int /* error */
xfs_bmap_first_unused(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode */
xfs_extlen_t len, /* size of hole to find */
xfs_fileoff_t *first_unused, /* unused block */
int whichfork) /* data or attr fork */
{
int error; /* error return value */
int idx; /* extent record index */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_fileoff_t lastaddr; /* last block number seen */
xfs_fileoff_t lowest; /* lowest useful block */
xfs_fileoff_t max; /* starting useful block */
xfs_fileoff_t off; /* offset for this block */
xfs_extnum_t nextents; /* number of extent entries */
ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE ||
XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS ||
XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL);
if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) {
*first_unused = 0;
return 0;
}
ifp = XFS_IFORK_PTR(ip, whichfork);
if (!(ifp->if_flags & XFS_IFEXTENTS) &&
(error = xfs_iread_extents(tp, ip, whichfork)))
return error;
lowest = *first_unused;
nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
for (idx = 0, lastaddr = 0, max = lowest; idx < nextents; idx++) {
xfs_bmbt_rec_host_t *ep = xfs_iext_get_ext(ifp, idx);
off = xfs_bmbt_get_startoff(ep);
/*
* See if the hole before this extent will work.
*/
if (off >= lowest + len && off - max >= len) {
*first_unused = max;
return 0;
}
lastaddr = off + xfs_bmbt_get_blockcount(ep);
max = XFS_FILEOFF_MAX(lastaddr, lowest);
}
*first_unused = max;
return 0;
}
/*
* Returns the file-relative block number of the last block + 1 before
* last_block (input value) in the file.
* This is not based on i_size, it is based on the extent records.
* Returns 0 for local files, as they do not have extent records.
*/
int /* error */
xfs_bmap_last_before(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode */
xfs_fileoff_t *last_block, /* last block */
int whichfork) /* data or attr fork */
{
xfs_fileoff_t bno; /* input file offset */
int eof; /* hit end of file */
xfs_bmbt_rec_host_t *ep; /* pointer to last extent */
int error; /* error return value */
xfs_bmbt_irec_t got; /* current extent value */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_extnum_t lastx; /* last extent used */
xfs_bmbt_irec_t prev; /* previous extent value */
if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_LOCAL)
return XFS_ERROR(EIO);
if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) {
*last_block = 0;
return 0;
}
ifp = XFS_IFORK_PTR(ip, whichfork);
if (!(ifp->if_flags & XFS_IFEXTENTS) &&
(error = xfs_iread_extents(tp, ip, whichfork)))
return error;
bno = *last_block - 1;
ep = xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got,
&prev);
if (eof || xfs_bmbt_get_startoff(ep) > bno) {
if (prev.br_startoff == NULLFILEOFF)
*last_block = 0;
else
*last_block = prev.br_startoff + prev.br_blockcount;
}
/*
* Otherwise *last_block is already the right answer.
*/
return 0;
}
STATIC int
xfs_bmap_last_extent(
struct xfs_trans *tp,
struct xfs_inode *ip,
int whichfork,
struct xfs_bmbt_irec *rec,
int *is_empty)
{
struct xfs_ifork *ifp = XFS_IFORK_PTR(ip, whichfork);
int error;
int nextents;
if (!(ifp->if_flags & XFS_IFEXTENTS)) {
error = xfs_iread_extents(tp, ip, whichfork);
if (error)
return error;
}
nextents = ifp->if_bytes / sizeof(xfs_bmbt_rec_t);
if (nextents == 0) {
*is_empty = 1;
return 0;
}
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, nextents - 1), rec);
*is_empty = 0;
return 0;
}
/*
* Check the last inode extent to determine whether this allocation will result
* in blocks being allocated at the end of the file. When we allocate new data
* blocks at the end of the file which do not start at the previous data block,
* we will try to align the new blocks at stripe unit boundaries.
*
* Returns 0 in bma->aeof if the file (fork) is empty as any new write will be
* at, or past the EOF.
*/
STATIC int
xfs_bmap_isaeof(
struct xfs_bmalloca *bma,
int whichfork)
{
struct xfs_bmbt_irec rec;
int is_empty;
int error;
bma->aeof = 0;
error = xfs_bmap_last_extent(NULL, bma->ip, whichfork, &rec,
&is_empty);
if (error || is_empty)
return error;
/*
* Check if we are allocation or past the last extent, or at least into
* the last delayed allocated extent.
*/
bma->aeof = bma->offset >= rec.br_startoff + rec.br_blockcount ||
(bma->offset >= rec.br_startoff &&
isnullstartblock(rec.br_startblock));
return 0;
}
/*
* Check if the endoff is outside the last extent. If so the caller will grow
* the allocation to a stripe unit boundary. All offsets are considered outside
* the end of file for an empty fork, so 1 is returned in *eof in that case.
*/
int
xfs_bmap_eof(
struct xfs_inode *ip,
xfs_fileoff_t endoff,
int whichfork,
int *eof)
{
struct xfs_bmbt_irec rec;
int error;
error = xfs_bmap_last_extent(NULL, ip, whichfork, &rec, eof);
if (error || *eof)
return error;
*eof = endoff >= rec.br_startoff + rec.br_blockcount;
return 0;
}
/*
* Returns the file-relative block number of the first block past eof in
* the file. This is not based on i_size, it is based on the extent records.
* Returns 0 for local files, as they do not have extent records.
*/
int
xfs_bmap_last_offset(
struct xfs_trans *tp,
struct xfs_inode *ip,
xfs_fileoff_t *last_block,
int whichfork)
{
struct xfs_bmbt_irec rec;
int is_empty;
int error;
*last_block = 0;
if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL)
return 0;
if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
return XFS_ERROR(EIO);
error = xfs_bmap_last_extent(NULL, ip, whichfork, &rec, &is_empty);
if (error || is_empty)
return error;
*last_block = rec.br_startoff + rec.br_blockcount;
return 0;
}
/*
* Returns whether the selected fork of the inode has exactly one
* block or not. For the data fork we check this matches di_size,
* implying the file's range is 0..bsize-1.
*/
int /* 1=>1 block, 0=>otherwise */
xfs_bmap_one_block(
xfs_inode_t *ip, /* incore inode */
int whichfork) /* data or attr fork */
{
xfs_bmbt_rec_host_t *ep; /* ptr to fork's extent */
xfs_ifork_t *ifp; /* inode fork pointer */
int rval; /* return value */
xfs_bmbt_irec_t s; /* internal version of extent */
#ifndef DEBUG
if (whichfork == XFS_DATA_FORK)
return XFS_ISIZE(ip) == ip->i_mount->m_sb.sb_blocksize;
#endif /* !DEBUG */
if (XFS_IFORK_NEXTENTS(ip, whichfork) != 1)
return 0;
if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
return 0;
ifp = XFS_IFORK_PTR(ip, whichfork);
ASSERT(ifp->if_flags & XFS_IFEXTENTS);
ep = xfs_iext_get_ext(ifp, 0);
xfs_bmbt_get_all(ep, &s);
rval = s.br_startoff == 0 && s.br_blockcount == 1;
if (rval && whichfork == XFS_DATA_FORK)
ASSERT(XFS_ISIZE(ip) == ip->i_mount->m_sb.sb_blocksize);
return rval;
}
/*
* Extent tree manipulation functions used during allocation.
*/
/*
* Convert a delayed allocation to a real allocation.
*/
STATIC int /* error */
xfs_bmap_add_extent_delay_real(
struct xfs_bmalloca *bma)
{
struct xfs_bmbt_irec *new = &bma->got;
int diff; /* temp value */
xfs_bmbt_rec_host_t *ep; /* extent entry for idx */
int error; /* error return value */
int i; /* temp state */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_fileoff_t new_endoff; /* end offset of new entry */
xfs_bmbt_irec_t r[3]; /* neighbor extent entries */
/* left is 0, right is 1, prev is 2 */
int rval=0; /* return value (logging flags) */
int state = 0;/* state bits, accessed thru macros */
xfs_filblks_t da_new; /* new count del alloc blocks used */
xfs_filblks_t da_old; /* old count del alloc blocks used */
xfs_filblks_t temp=0; /* value for da_new calculations */
xfs_filblks_t temp2=0;/* value for da_new calculations */
int tmp_rval; /* partial logging flags */
ifp = XFS_IFORK_PTR(bma->ip, XFS_DATA_FORK);
ASSERT(bma->idx >= 0);
ASSERT(bma->idx <= ifp->if_bytes / sizeof(struct xfs_bmbt_rec));
ASSERT(!isnullstartblock(new->br_startblock));
ASSERT(!bma->cur ||
(bma->cur->bc_private.b.flags & XFS_BTCUR_BPRV_WASDEL));
XFS_STATS_INC(xs_add_exlist);
#define LEFT r[0]
#define RIGHT r[1]
#define PREV r[2]
/*
* Set up a bunch of variables to make the tests simpler.
*/
ep = xfs_iext_get_ext(ifp, bma->idx);
xfs_bmbt_get_all(ep, &PREV);
new_endoff = new->br_startoff + new->br_blockcount;
ASSERT(PREV.br_startoff <= new->br_startoff);
ASSERT(PREV.br_startoff + PREV.br_blockcount >= new_endoff);
da_old = startblockval(PREV.br_startblock);
da_new = 0;
/*
* Set flags determining what part of the previous delayed allocation
* extent is being replaced by a real allocation.
*/
if (PREV.br_startoff == new->br_startoff)
state |= BMAP_LEFT_FILLING;
if (PREV.br_startoff + PREV.br_blockcount == new_endoff)
state |= BMAP_RIGHT_FILLING;
/*
* Check and set flags if this segment has a left neighbor.
* Don't set contiguous if the combined extent would be too large.
*/
if (bma->idx > 0) {
state |= BMAP_LEFT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx - 1), &LEFT);
if (isnullstartblock(LEFT.br_startblock))
state |= BMAP_LEFT_DELAY;
}
if ((state & BMAP_LEFT_VALID) && !(state & BMAP_LEFT_DELAY) &&
LEFT.br_startoff + LEFT.br_blockcount == new->br_startoff &&
LEFT.br_startblock + LEFT.br_blockcount == new->br_startblock &&
LEFT.br_state == new->br_state &&
LEFT.br_blockcount + new->br_blockcount <= MAXEXTLEN)
state |= BMAP_LEFT_CONTIG;
/*
* Check and set flags if this segment has a right neighbor.
* Don't set contiguous if the combined extent would be too large.
* Also check for all-three-contiguous being too large.
*/
if (bma->idx < bma->ip->i_df.if_bytes / (uint)sizeof(xfs_bmbt_rec_t) - 1) {
state |= BMAP_RIGHT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx + 1), &RIGHT);
if (isnullstartblock(RIGHT.br_startblock))
state |= BMAP_RIGHT_DELAY;
}
if ((state & BMAP_RIGHT_VALID) && !(state & BMAP_RIGHT_DELAY) &&
new_endoff == RIGHT.br_startoff &&
new->br_startblock + new->br_blockcount == RIGHT.br_startblock &&
new->br_state == RIGHT.br_state &&
new->br_blockcount + RIGHT.br_blockcount <= MAXEXTLEN &&
((state & (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
BMAP_RIGHT_FILLING)) !=
(BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
BMAP_RIGHT_FILLING) ||
LEFT.br_blockcount + new->br_blockcount + RIGHT.br_blockcount
<= MAXEXTLEN))
state |= BMAP_RIGHT_CONTIG;
error = 0;
/*
* Switch out based on the FILLING and CONTIG state bits.
*/
switch (state & (BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG)) {
case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
/*
* Filling in all of a previously delayed allocation extent.
* The left and right neighbors are both contiguous with new.
*/
bma->idx--;
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx),
LEFT.br_blockcount + PREV.br_blockcount +
RIGHT.br_blockcount);
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_iext_remove(bma->ip, bma->idx + 1, 2, state);
bma->ip->i_d.di_nextents--;
if (bma->cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
error = xfs_bmbt_lookup_eq(bma->cur, RIGHT.br_startoff,
RIGHT.br_startblock,
RIGHT.br_blockcount, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_btree_delete(bma->cur, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_btree_decrement(bma->cur, 0, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, LEFT.br_startoff,
LEFT.br_startblock,
LEFT.br_blockcount +
PREV.br_blockcount +
RIGHT.br_blockcount, LEFT.br_state);
if (error)
goto done;
}
break;
case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
/*
* Filling in all of a previously delayed allocation extent.
* The left neighbor is contiguous, the right is not.
*/
bma->idx--;
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx),
LEFT.br_blockcount + PREV.br_blockcount);
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_iext_remove(bma->ip, bma->idx + 1, 1, state);
if (bma->cur == NULL)
rval = XFS_ILOG_DEXT;
else {
rval = 0;
error = xfs_bmbt_lookup_eq(bma->cur, LEFT.br_startoff,
LEFT.br_startblock, LEFT.br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, LEFT.br_startoff,
LEFT.br_startblock,
LEFT.br_blockcount +
PREV.br_blockcount, LEFT.br_state);
if (error)
goto done;
}
break;
case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
/*
* Filling in all of a previously delayed allocation extent.
* The right neighbor is contiguous, the left is not.
*/
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_startblock(ep, new->br_startblock);
xfs_bmbt_set_blockcount(ep,
PREV.br_blockcount + RIGHT.br_blockcount);
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_iext_remove(bma->ip, bma->idx + 1, 1, state);
if (bma->cur == NULL)
rval = XFS_ILOG_DEXT;
else {
rval = 0;
error = xfs_bmbt_lookup_eq(bma->cur, RIGHT.br_startoff,
RIGHT.br_startblock,
RIGHT.br_blockcount, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, PREV.br_startoff,
new->br_startblock,
PREV.br_blockcount +
RIGHT.br_blockcount, PREV.br_state);
if (error)
goto done;
}
break;
case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING:
/*
* Filling in all of a previously delayed allocation extent.
* Neither the left nor right neighbors are contiguous with
* the new one.
*/
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_startblock(ep, new->br_startblock);
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
bma->ip->i_d.di_nextents++;
if (bma->cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 0, done);
bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
error = xfs_btree_insert(bma->cur, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
break;
case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG:
/*
* Filling in the first part of a previous delayed allocation.
* The left neighbor is contiguous.
*/
trace_xfs_bmap_pre_update(bma->ip, bma->idx - 1, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx - 1),
LEFT.br_blockcount + new->br_blockcount);
xfs_bmbt_set_startoff(ep,
PREV.br_startoff + new->br_blockcount);
trace_xfs_bmap_post_update(bma->ip, bma->idx - 1, state, _THIS_IP_);
temp = PREV.br_blockcount - new->br_blockcount;
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep, temp);
if (bma->cur == NULL)
rval = XFS_ILOG_DEXT;
else {
rval = 0;
error = xfs_bmbt_lookup_eq(bma->cur, LEFT.br_startoff,
LEFT.br_startblock, LEFT.br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, LEFT.br_startoff,
LEFT.br_startblock,
LEFT.br_blockcount +
new->br_blockcount,
LEFT.br_state);
if (error)
goto done;
}
da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
startblockval(PREV.br_startblock));
xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
bma->idx--;
break;
case BMAP_LEFT_FILLING:
/*
* Filling in the first part of a previous delayed allocation.
* The left neighbor is not contiguous.
*/
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_startoff(ep, new_endoff);
temp = PREV.br_blockcount - new->br_blockcount;
xfs_bmbt_set_blockcount(ep, temp);
xfs_iext_insert(bma->ip, bma->idx, 1, new, state);
bma->ip->i_d.di_nextents++;
if (bma->cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 0, done);
bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
error = xfs_btree_insert(bma->cur, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
if (xfs_bmap_needs_btree(bma->ip, XFS_DATA_FORK)) {
error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
bma->firstblock, bma->flist,
&bma->cur, 1, &tmp_rval, XFS_DATA_FORK);
rval |= tmp_rval;
if (error)
goto done;
}
da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
startblockval(PREV.br_startblock) -
(bma->cur ? bma->cur->bc_private.b.allocated : 0));
ep = xfs_iext_get_ext(ifp, bma->idx + 1);
xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
trace_xfs_bmap_post_update(bma->ip, bma->idx + 1, state, _THIS_IP_);
break;
case BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
/*
* Filling in the last part of a previous delayed allocation.
* The right neighbor is contiguous with the new allocation.
*/
temp = PREV.br_blockcount - new->br_blockcount;
trace_xfs_bmap_pre_update(bma->ip, bma->idx + 1, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep, temp);
xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, bma->idx + 1),
new->br_startoff, new->br_startblock,
new->br_blockcount + RIGHT.br_blockcount,
RIGHT.br_state);
trace_xfs_bmap_post_update(bma->ip, bma->idx + 1, state, _THIS_IP_);
if (bma->cur == NULL)
rval = XFS_ILOG_DEXT;
else {
rval = 0;
error = xfs_bmbt_lookup_eq(bma->cur, RIGHT.br_startoff,
RIGHT.br_startblock,
RIGHT.br_blockcount, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, new->br_startoff,
new->br_startblock,
new->br_blockcount +
RIGHT.br_blockcount,
RIGHT.br_state);
if (error)
goto done;
}
da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
startblockval(PREV.br_startblock));
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
bma->idx++;
break;
case BMAP_RIGHT_FILLING:
/*
* Filling in the last part of a previous delayed allocation.
* The right neighbor is not contiguous.
*/
temp = PREV.br_blockcount - new->br_blockcount;
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep, temp);
xfs_iext_insert(bma->ip, bma->idx + 1, 1, new, state);
bma->ip->i_d.di_nextents++;
if (bma->cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 0, done);
bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
error = xfs_btree_insert(bma->cur, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
if (xfs_bmap_needs_btree(bma->ip, XFS_DATA_FORK)) {
error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
bma->firstblock, bma->flist, &bma->cur, 1,
&tmp_rval, XFS_DATA_FORK);
rval |= tmp_rval;
if (error)
goto done;
}
da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
startblockval(PREV.br_startblock) -
(bma->cur ? bma->cur->bc_private.b.allocated : 0));
ep = xfs_iext_get_ext(ifp, bma->idx);
xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
bma->idx++;
break;
case 0:
/*
* Filling in the middle part of a previous delayed allocation.
* Contiguity is impossible here.
* This case is avoided almost all the time.
*
* We start with a delayed allocation:
*
* +ddddddddddddddddddddddddddddddddddddddddddddddddddddddd+
* PREV @ idx
*
* and we are allocating:
* +rrrrrrrrrrrrrrrrr+
* new
*
* and we set it up for insertion as:
* +ddddddddddddddddddd+rrrrrrrrrrrrrrrrr+ddddddddddddddddd+
* new
* PREV @ idx LEFT RIGHT
* inserted at idx + 1
*/
temp = new->br_startoff - PREV.br_startoff;
temp2 = PREV.br_startoff + PREV.br_blockcount - new_endoff;
trace_xfs_bmap_pre_update(bma->ip, bma->idx, 0, _THIS_IP_);
xfs_bmbt_set_blockcount(ep, temp); /* truncate PREV */
LEFT = *new;
RIGHT.br_state = PREV.br_state;
RIGHT.br_startblock = nullstartblock(
(int)xfs_bmap_worst_indlen(bma->ip, temp2));
RIGHT.br_startoff = new_endoff;
RIGHT.br_blockcount = temp2;
/* insert LEFT (r[0]) and RIGHT (r[1]) at the same time */
xfs_iext_insert(bma->ip, bma->idx + 1, 2, &LEFT, state);
bma->ip->i_d.di_nextents++;
if (bma->cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 0, done);
bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
error = xfs_btree_insert(bma->cur, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
if (xfs_bmap_needs_btree(bma->ip, XFS_DATA_FORK)) {
error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
bma->firstblock, bma->flist, &bma->cur,
1, &tmp_rval, XFS_DATA_FORK);
rval |= tmp_rval;
if (error)
goto done;
}
temp = xfs_bmap_worst_indlen(bma->ip, temp);
temp2 = xfs_bmap_worst_indlen(bma->ip, temp2);
diff = (int)(temp + temp2 - startblockval(PREV.br_startblock) -
(bma->cur ? bma->cur->bc_private.b.allocated : 0));
if (diff > 0) {
error = xfs_icsb_modify_counters(bma->ip->i_mount,
XFS_SBS_FDBLOCKS,
-((int64_t)diff), 0);
ASSERT(!error);
if (error)
goto done;
}
ep = xfs_iext_get_ext(ifp, bma->idx);
xfs_bmbt_set_startblock(ep, nullstartblock((int)temp));
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
trace_xfs_bmap_pre_update(bma->ip, bma->idx + 2, state, _THIS_IP_);
xfs_bmbt_set_startblock(xfs_iext_get_ext(ifp, bma->idx + 2),
nullstartblock((int)temp2));
trace_xfs_bmap_post_update(bma->ip, bma->idx + 2, state, _THIS_IP_);
bma->idx++;
da_new = temp + temp2;
break;
case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
case BMAP_LEFT_FILLING | BMAP_RIGHT_CONTIG:
case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
case BMAP_LEFT_CONTIG:
case BMAP_RIGHT_CONTIG:
/*
* These cases are all impossible.
*/
ASSERT(0);
}
/* convert to a btree if necessary */
if (xfs_bmap_needs_btree(bma->ip, XFS_DATA_FORK)) {
int tmp_logflags; /* partial log flag return val */
ASSERT(bma->cur == NULL);
error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
bma->firstblock, bma->flist, &bma->cur,
da_old > 0, &tmp_logflags, XFS_DATA_FORK);
bma->logflags |= tmp_logflags;
if (error)
goto done;
}
/* adjust for changes in reserved delayed indirect blocks */
if (da_old || da_new) {
temp = da_new;
if (bma->cur)
temp += bma->cur->bc_private.b.allocated;
ASSERT(temp <= da_old);
if (temp < da_old)
xfs_icsb_modify_counters(bma->ip->i_mount,
XFS_SBS_FDBLOCKS,
(int64_t)(da_old - temp), 0);
}
/* clear out the allocated field, done with it now in any case. */
if (bma->cur)
bma->cur->bc_private.b.allocated = 0;
xfs_bmap_check_leaf_extents(bma->cur, bma->ip, XFS_DATA_FORK);
done:
bma->logflags |= rval;
return error;
#undef LEFT
#undef RIGHT
#undef PREV
}
/*
* Convert an unwritten allocation to a real allocation or vice versa.
*/
STATIC int /* error */
xfs_bmap_add_extent_unwritten_real(
struct xfs_trans *tp,
xfs_inode_t *ip, /* incore inode pointer */
xfs_extnum_t *idx, /* extent number to update/insert */
xfs_btree_cur_t **curp, /* if *curp is null, not a btree */
xfs_bmbt_irec_t *new, /* new data to add to file extents */
xfs_fsblock_t *first, /* pointer to firstblock variable */
xfs_bmap_free_t *flist, /* list of extents to be freed */
int *logflagsp) /* inode logging flags */
{
xfs_btree_cur_t *cur; /* btree cursor */
xfs_bmbt_rec_host_t *ep; /* extent entry for idx */
int error; /* error return value */
int i; /* temp state */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_fileoff_t new_endoff; /* end offset of new entry */
xfs_exntst_t newext; /* new extent state */
xfs_exntst_t oldext; /* old extent state */
xfs_bmbt_irec_t r[3]; /* neighbor extent entries */
/* left is 0, right is 1, prev is 2 */
int rval=0; /* return value (logging flags) */
int state = 0;/* state bits, accessed thru macros */
*logflagsp = 0;
cur = *curp;
ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
ASSERT(*idx >= 0);
ASSERT(*idx <= ifp->if_bytes / sizeof(struct xfs_bmbt_rec));
ASSERT(!isnullstartblock(new->br_startblock));
XFS_STATS_INC(xs_add_exlist);
#define LEFT r[0]
#define RIGHT r[1]
#define PREV r[2]
/*
* Set up a bunch of variables to make the tests simpler.
*/
error = 0;
ep = xfs_iext_get_ext(ifp, *idx);
xfs_bmbt_get_all(ep, &PREV);
newext = new->br_state;
oldext = (newext == XFS_EXT_UNWRITTEN) ?
XFS_EXT_NORM : XFS_EXT_UNWRITTEN;
ASSERT(PREV.br_state == oldext);
new_endoff = new->br_startoff + new->br_blockcount;
ASSERT(PREV.br_startoff <= new->br_startoff);
ASSERT(PREV.br_startoff + PREV.br_blockcount >= new_endoff);
/*
* Set flags determining what part of the previous oldext allocation
* extent is being replaced by a newext allocation.
*/
if (PREV.br_startoff == new->br_startoff)
state |= BMAP_LEFT_FILLING;
if (PREV.br_startoff + PREV.br_blockcount == new_endoff)
state |= BMAP_RIGHT_FILLING;
/*
* Check and set flags if this segment has a left neighbor.
* Don't set contiguous if the combined extent would be too large.
*/
if (*idx > 0) {
state |= BMAP_LEFT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx - 1), &LEFT);
if (isnullstartblock(LEFT.br_startblock))
state |= BMAP_LEFT_DELAY;
}
if ((state & BMAP_LEFT_VALID) && !(state & BMAP_LEFT_DELAY) &&
LEFT.br_startoff + LEFT.br_blockcount == new->br_startoff &&
LEFT.br_startblock + LEFT.br_blockcount == new->br_startblock &&
LEFT.br_state == newext &&
LEFT.br_blockcount + new->br_blockcount <= MAXEXTLEN)
state |= BMAP_LEFT_CONTIG;
/*
* Check and set flags if this segment has a right neighbor.
* Don't set contiguous if the combined extent would be too large.
* Also check for all-three-contiguous being too large.
*/
if (*idx < ip->i_df.if_bytes / (uint)sizeof(xfs_bmbt_rec_t) - 1) {
state |= BMAP_RIGHT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx + 1), &RIGHT);
if (isnullstartblock(RIGHT.br_startblock))
state |= BMAP_RIGHT_DELAY;
}
if ((state & BMAP_RIGHT_VALID) && !(state & BMAP_RIGHT_DELAY) &&
new_endoff == RIGHT.br_startoff &&
new->br_startblock + new->br_blockcount == RIGHT.br_startblock &&
newext == RIGHT.br_state &&
new->br_blockcount + RIGHT.br_blockcount <= MAXEXTLEN &&
((state & (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
BMAP_RIGHT_FILLING)) !=
(BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
BMAP_RIGHT_FILLING) ||
LEFT.br_blockcount + new->br_blockcount + RIGHT.br_blockcount
<= MAXEXTLEN))
state |= BMAP_RIGHT_CONTIG;
/*
* Switch out based on the FILLING and CONTIG state bits.
*/
switch (state & (BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG)) {
case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
/*
* Setting all of a previous oldext extent to newext.
* The left and right neighbors are both contiguous with new.
*/
--*idx;
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx),
LEFT.br_blockcount + PREV.br_blockcount +
RIGHT.br_blockcount);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
xfs_iext_remove(ip, *idx + 1, 2, state);
ip->i_d.di_nextents -= 2;
if (cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
if ((error = xfs_bmbt_lookup_eq(cur, RIGHT.br_startoff,
RIGHT.br_startblock,
RIGHT.br_blockcount, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_delete(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_decrement(cur, 0, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_delete(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_decrement(cur, 0, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur, LEFT.br_startoff,
LEFT.br_startblock,
LEFT.br_blockcount + PREV.br_blockcount +
RIGHT.br_blockcount, LEFT.br_state)))
goto done;
}
break;
case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
/*
* Setting all of a previous oldext extent to newext.
* The left neighbor is contiguous, the right is not.
*/
--*idx;
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx),
LEFT.br_blockcount + PREV.br_blockcount);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
xfs_iext_remove(ip, *idx + 1, 1, state);
ip->i_d.di_nextents--;
if (cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
PREV.br_startblock, PREV.br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_delete(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_decrement(cur, 0, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur, LEFT.br_startoff,
LEFT.br_startblock,
LEFT.br_blockcount + PREV.br_blockcount,
LEFT.br_state)))
goto done;
}
break;
case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
/*
* Setting all of a previous oldext extent to newext.
* The right neighbor is contiguous, the left is not.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep,
PREV.br_blockcount + RIGHT.br_blockcount);
xfs_bmbt_set_state(ep, newext);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
xfs_iext_remove(ip, *idx + 1, 1, state);
ip->i_d.di_nextents--;
if (cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
if ((error = xfs_bmbt_lookup_eq(cur, RIGHT.br_startoff,
RIGHT.br_startblock,
RIGHT.br_blockcount, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_delete(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_decrement(cur, 0, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur, new->br_startoff,
new->br_startblock,
new->br_blockcount + RIGHT.br_blockcount,
newext)))
goto done;
}
break;
case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING:
/*
* Setting all of a previous oldext extent to newext.
* Neither the left nor right neighbors are contiguous with
* the new one.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_state(ep, newext);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
if (cur == NULL)
rval = XFS_ILOG_DEXT;
else {
rval = 0;
if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
newext)))
goto done;
}
break;
case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG:
/*
* Setting the first part of a previous oldext extent to newext.
* The left neighbor is contiguous.
*/
trace_xfs_bmap_pre_update(ip, *idx - 1, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx - 1),
LEFT.br_blockcount + new->br_blockcount);
xfs_bmbt_set_startoff(ep,
PREV.br_startoff + new->br_blockcount);
trace_xfs_bmap_post_update(ip, *idx - 1, state, _THIS_IP_);
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_startblock(ep,
new->br_startblock + new->br_blockcount);
xfs_bmbt_set_blockcount(ep,
PREV.br_blockcount - new->br_blockcount);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
--*idx;
if (cur == NULL)
rval = XFS_ILOG_DEXT;
else {
rval = 0;
if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
PREV.br_startblock, PREV.br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur,
PREV.br_startoff + new->br_blockcount,
PREV.br_startblock + new->br_blockcount,
PREV.br_blockcount - new->br_blockcount,
oldext)))
goto done;
if ((error = xfs_btree_decrement(cur, 0, &i)))
goto done;
error = xfs_bmbt_update(cur, LEFT.br_startoff,
LEFT.br_startblock,
LEFT.br_blockcount + new->br_blockcount,
LEFT.br_state);
if (error)
goto done;
}
break;
case BMAP_LEFT_FILLING:
/*
* Setting the first part of a previous oldext extent to newext.
* The left neighbor is not contiguous.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
ASSERT(ep && xfs_bmbt_get_state(ep) == oldext);
xfs_bmbt_set_startoff(ep, new_endoff);
xfs_bmbt_set_blockcount(ep,
PREV.br_blockcount - new->br_blockcount);
xfs_bmbt_set_startblock(ep,
new->br_startblock + new->br_blockcount);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
xfs_iext_insert(ip, *idx, 1, new, state);
ip->i_d.di_nextents++;
if (cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
PREV.br_startblock, PREV.br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur,
PREV.br_startoff + new->br_blockcount,
PREV.br_startblock + new->br_blockcount,
PREV.br_blockcount - new->br_blockcount,
oldext)))
goto done;
cur->bc_rec.b = *new;
if ((error = xfs_btree_insert(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
break;
case BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
/*
* Setting the last part of a previous oldext extent to newext.
* The right neighbor is contiguous with the new allocation.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep,
PREV.br_blockcount - new->br_blockcount);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
++*idx;
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, *idx),
new->br_startoff, new->br_startblock,
new->br_blockcount + RIGHT.br_blockcount, newext);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
if (cur == NULL)
rval = XFS_ILOG_DEXT;
else {
rval = 0;
if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
PREV.br_startblock,
PREV.br_blockcount, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur, PREV.br_startoff,
PREV.br_startblock,
PREV.br_blockcount - new->br_blockcount,
oldext)))
goto done;
if ((error = xfs_btree_increment(cur, 0, &i)))
goto done;
if ((error = xfs_bmbt_update(cur, new->br_startoff,
new->br_startblock,
new->br_blockcount + RIGHT.br_blockcount,
newext)))
goto done;
}
break;
case BMAP_RIGHT_FILLING:
/*
* Setting the last part of a previous oldext extent to newext.
* The right neighbor is not contiguous.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep,
PREV.br_blockcount - new->br_blockcount);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
++*idx;
xfs_iext_insert(ip, *idx, 1, new, state);
ip->i_d.di_nextents++;
if (cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
PREV.br_startblock, PREV.br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur, PREV.br_startoff,
PREV.br_startblock,
PREV.br_blockcount - new->br_blockcount,
oldext)))
goto done;
if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 0, done);
cur->bc_rec.b.br_state = XFS_EXT_NORM;
if ((error = xfs_btree_insert(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
break;
case 0:
/*
* Setting the middle part of a previous oldext extent to
* newext. Contiguity is impossible here.
* One extent becomes three extents.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep,
new->br_startoff - PREV.br_startoff);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
r[0] = *new;
r[1].br_startoff = new_endoff;
r[1].br_blockcount =
PREV.br_startoff + PREV.br_blockcount - new_endoff;
r[1].br_startblock = new->br_startblock + new->br_blockcount;
r[1].br_state = oldext;
++*idx;
xfs_iext_insert(ip, *idx, 2, &r[0], state);
ip->i_d.di_nextents += 2;
if (cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
PREV.br_startblock, PREV.br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
/* new right extent - oldext */
if ((error = xfs_bmbt_update(cur, r[1].br_startoff,
r[1].br_startblock, r[1].br_blockcount,
r[1].br_state)))
goto done;
/* new left extent - oldext */
cur->bc_rec.b = PREV;
cur->bc_rec.b.br_blockcount =
new->br_startoff - PREV.br_startoff;
if ((error = xfs_btree_insert(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
/*
* Reset the cursor to the position of the new extent
* we are about to insert as we can't trust it after
* the previous insert.
*/
if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 0, done);
/* new middle extent - newext */
cur->bc_rec.b.br_state = new->br_state;
if ((error = xfs_btree_insert(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
break;
case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
case BMAP_LEFT_FILLING | BMAP_RIGHT_CONTIG:
case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
case BMAP_LEFT_CONTIG:
case BMAP_RIGHT_CONTIG:
/*
* These cases are all impossible.
*/
ASSERT(0);
}
/* convert to a btree if necessary */
if (xfs_bmap_needs_btree(ip, XFS_DATA_FORK)) {
int tmp_logflags; /* partial log flag return val */
ASSERT(cur == NULL);
error = xfs_bmap_extents_to_btree(tp, ip, first, flist, &cur,
0, &tmp_logflags, XFS_DATA_FORK);
*logflagsp |= tmp_logflags;
if (error)
goto done;
}
/* clear out the allocated field, done with it now in any case. */
if (cur) {
cur->bc_private.b.allocated = 0;
*curp = cur;
}
xfs_bmap_check_leaf_extents(*curp, ip, XFS_DATA_FORK);
done:
*logflagsp |= rval;
return error;
#undef LEFT
#undef RIGHT
#undef PREV
}
/*
* Convert a hole to a delayed allocation.
*/
STATIC void
xfs_bmap_add_extent_hole_delay(
xfs_inode_t *ip, /* incore inode pointer */
xfs_extnum_t *idx, /* extent number to update/insert */
xfs_bmbt_irec_t *new) /* new data to add to file extents */
{
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_bmbt_irec_t left; /* left neighbor extent entry */
xfs_filblks_t newlen=0; /* new indirect size */
xfs_filblks_t oldlen=0; /* old indirect size */
xfs_bmbt_irec_t right; /* right neighbor extent entry */
int state; /* state bits, accessed thru macros */
xfs_filblks_t temp=0; /* temp for indirect calculations */
ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
state = 0;
ASSERT(isnullstartblock(new->br_startblock));
/*
* Check and set flags if this segment has a left neighbor
*/
if (*idx > 0) {
state |= BMAP_LEFT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx - 1), &left);
if (isnullstartblock(left.br_startblock))
state |= BMAP_LEFT_DELAY;
}
/*
* Check and set flags if the current (right) segment exists.
* If it doesn't exist, we're converting the hole at end-of-file.
*/
if (*idx < ip->i_df.if_bytes / (uint)sizeof(xfs_bmbt_rec_t)) {
state |= BMAP_RIGHT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx), &right);
if (isnullstartblock(right.br_startblock))
state |= BMAP_RIGHT_DELAY;
}
/*
* Set contiguity flags on the left and right neighbors.
* Don't let extents get too large, even if the pieces are contiguous.
*/
if ((state & BMAP_LEFT_VALID) && (state & BMAP_LEFT_DELAY) &&
left.br_startoff + left.br_blockcount == new->br_startoff &&
left.br_blockcount + new->br_blockcount <= MAXEXTLEN)
state |= BMAP_LEFT_CONTIG;
if ((state & BMAP_RIGHT_VALID) && (state & BMAP_RIGHT_DELAY) &&
new->br_startoff + new->br_blockcount == right.br_startoff &&
new->br_blockcount + right.br_blockcount <= MAXEXTLEN &&
(!(state & BMAP_LEFT_CONTIG) ||
(left.br_blockcount + new->br_blockcount +
right.br_blockcount <= MAXEXTLEN)))
state |= BMAP_RIGHT_CONTIG;
/*
* Switch out based on the contiguity flags.
*/
switch (state & (BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG)) {
case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
/*
* New allocation is contiguous with delayed allocations
* on the left and on the right.
* Merge all three into a single extent record.
*/
--*idx;
temp = left.br_blockcount + new->br_blockcount +
right.br_blockcount;
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx), temp);
oldlen = startblockval(left.br_startblock) +
startblockval(new->br_startblock) +
startblockval(right.br_startblock);
newlen = xfs_bmap_worst_indlen(ip, temp);
xfs_bmbt_set_startblock(xfs_iext_get_ext(ifp, *idx),
nullstartblock((int)newlen));
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
xfs_iext_remove(ip, *idx + 1, 1, state);
break;
case BMAP_LEFT_CONTIG:
/*
* New allocation is contiguous with a delayed allocation
* on the left.
* Merge the new allocation with the left neighbor.
*/
--*idx;
temp = left.br_blockcount + new->br_blockcount;
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx), temp);
oldlen = startblockval(left.br_startblock) +
startblockval(new->br_startblock);
newlen = xfs_bmap_worst_indlen(ip, temp);
xfs_bmbt_set_startblock(xfs_iext_get_ext(ifp, *idx),
nullstartblock((int)newlen));
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
break;
case BMAP_RIGHT_CONTIG:
/*
* New allocation is contiguous with a delayed allocation
* on the right.
* Merge the new allocation with the right neighbor.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
temp = new->br_blockcount + right.br_blockcount;
oldlen = startblockval(new->br_startblock) +
startblockval(right.br_startblock);
newlen = xfs_bmap_worst_indlen(ip, temp);
xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, *idx),
new->br_startoff,
nullstartblock((int)newlen), temp, right.br_state);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
break;
case 0:
/*
* New allocation is not contiguous with another
* delayed allocation.
* Insert a new entry.
*/
oldlen = newlen = 0;
xfs_iext_insert(ip, *idx, 1, new, state);
break;
}
if (oldlen != newlen) {
ASSERT(oldlen > newlen);
xfs_icsb_modify_counters(ip->i_mount, XFS_SBS_FDBLOCKS,
(int64_t)(oldlen - newlen), 0);
/*
* Nothing to do for disk quota accounting here.
*/
}
}
/*
* Convert a hole to a real allocation.
*/
STATIC int /* error */
xfs_bmap_add_extent_hole_real(
struct xfs_bmalloca *bma,
int whichfork)
{
struct xfs_bmbt_irec *new = &bma->got;
int error; /* error return value */
int i; /* temp state */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_bmbt_irec_t left; /* left neighbor extent entry */
xfs_bmbt_irec_t right; /* right neighbor extent entry */
int rval=0; /* return value (logging flags) */
int state; /* state bits, accessed thru macros */
ifp = XFS_IFORK_PTR(bma->ip, whichfork);
ASSERT(bma->idx >= 0);
ASSERT(bma->idx <= ifp->if_bytes / sizeof(struct xfs_bmbt_rec));
ASSERT(!isnullstartblock(new->br_startblock));
ASSERT(!bma->cur ||
!(bma->cur->bc_private.b.flags & XFS_BTCUR_BPRV_WASDEL));
XFS_STATS_INC(xs_add_exlist);
state = 0;
if (whichfork == XFS_ATTR_FORK)
state |= BMAP_ATTRFORK;
/*
* Check and set flags if this segment has a left neighbor.
*/
if (bma->idx > 0) {
state |= BMAP_LEFT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx - 1), &left);
if (isnullstartblock(left.br_startblock))
state |= BMAP_LEFT_DELAY;
}
/*
* Check and set flags if this segment has a current value.
* Not true if we're inserting into the "hole" at eof.
*/
if (bma->idx < ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t)) {
state |= BMAP_RIGHT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx), &right);
if (isnullstartblock(right.br_startblock))
state |= BMAP_RIGHT_DELAY;
}
/*
* We're inserting a real allocation between "left" and "right".
* Set the contiguity flags. Don't let extents get too large.
*/
if ((state & BMAP_LEFT_VALID) && !(state & BMAP_LEFT_DELAY) &&
left.br_startoff + left.br_blockcount == new->br_startoff &&
left.br_startblock + left.br_blockcount == new->br_startblock &&
left.br_state == new->br_state &&
left.br_blockcount + new->br_blockcount <= MAXEXTLEN)
state |= BMAP_LEFT_CONTIG;
if ((state & BMAP_RIGHT_VALID) && !(state & BMAP_RIGHT_DELAY) &&
new->br_startoff + new->br_blockcount == right.br_startoff &&
new->br_startblock + new->br_blockcount == right.br_startblock &&
new->br_state == right.br_state &&
new->br_blockcount + right.br_blockcount <= MAXEXTLEN &&
(!(state & BMAP_LEFT_CONTIG) ||
left.br_blockcount + new->br_blockcount +
right.br_blockcount <= MAXEXTLEN))
state |= BMAP_RIGHT_CONTIG;
error = 0;
/*
* Select which case we're in here, and implement it.
*/
switch (state & (BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG)) {
case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
/*
* New allocation is contiguous with real allocations on the
* left and on the right.
* Merge all three into a single extent record.
*/
--bma->idx;
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx),
left.br_blockcount + new->br_blockcount +
right.br_blockcount);
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_iext_remove(bma->ip, bma->idx + 1, 1, state);
XFS_IFORK_NEXT_SET(bma->ip, whichfork,
XFS_IFORK_NEXTENTS(bma->ip, whichfork) - 1);
if (bma->cur == NULL) {
rval = XFS_ILOG_CORE | xfs_ilog_fext(whichfork);
} else {
rval = XFS_ILOG_CORE;
error = xfs_bmbt_lookup_eq(bma->cur, right.br_startoff,
right.br_startblock, right.br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_btree_delete(bma->cur, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_btree_decrement(bma->cur, 0, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, left.br_startoff,
left.br_startblock,
left.br_blockcount +
new->br_blockcount +
right.br_blockcount,
left.br_state);
if (error)
goto done;
}
break;
case BMAP_LEFT_CONTIG:
/*
* New allocation is contiguous with a real allocation
* on the left.
* Merge the new allocation with the left neighbor.
*/
--bma->idx;
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx),
left.br_blockcount + new->br_blockcount);
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
if (bma->cur == NULL) {
rval = xfs_ilog_fext(whichfork);
} else {
rval = 0;
error = xfs_bmbt_lookup_eq(bma->cur, left.br_startoff,
left.br_startblock, left.br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, left.br_startoff,
left.br_startblock,
left.br_blockcount +
new->br_blockcount,
left.br_state);
if (error)
goto done;
}
break;
case BMAP_RIGHT_CONTIG:
/*
* New allocation is contiguous with a real allocation
* on the right.
* Merge the new allocation with the right neighbor.
*/
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, bma->idx),
new->br_startoff, new->br_startblock,
new->br_blockcount + right.br_blockcount,
right.br_state);
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
if (bma->cur == NULL) {
rval = xfs_ilog_fext(whichfork);
} else {
rval = 0;
error = xfs_bmbt_lookup_eq(bma->cur,
right.br_startoff,
right.br_startblock,
right.br_blockcount, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, new->br_startoff,
new->br_startblock,
new->br_blockcount +
right.br_blockcount,
right.br_state);
if (error)
goto done;
}
break;
case 0:
/*
* New allocation is not contiguous with another
* real allocation.
* Insert a new entry.
*/
xfs_iext_insert(bma->ip, bma->idx, 1, new, state);
XFS_IFORK_NEXT_SET(bma->ip, whichfork,
XFS_IFORK_NEXTENTS(bma->ip, whichfork) + 1);
if (bma->cur == NULL) {
rval = XFS_ILOG_CORE | xfs_ilog_fext(whichfork);
} else {
rval = XFS_ILOG_CORE;
error = xfs_bmbt_lookup_eq(bma->cur,
new->br_startoff,
new->br_startblock,
new->br_blockcount, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 0, done);
bma->cur->bc_rec.b.br_state = new->br_state;
error = xfs_btree_insert(bma->cur, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
break;
}
/* convert to a btree if necessary */
if (xfs_bmap_needs_btree(bma->ip, whichfork)) {
int tmp_logflags; /* partial log flag return val */
ASSERT(bma->cur == NULL);
error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
bma->firstblock, bma->flist, &bma->cur,
0, &tmp_logflags, whichfork);
bma->logflags |= tmp_logflags;
if (error)
goto done;
}
/* clear out the allocated field, done with it now in any case. */
if (bma->cur)
bma->cur->bc_private.b.allocated = 0;
xfs_bmap_check_leaf_extents(bma->cur, bma->ip, whichfork);
done:
bma->logflags |= rval;
return error;
}
/*
* Functions used in the extent read, allocate and remove paths
*/
/*
* Adjust the size of the new extent based on di_extsize and rt extsize.
*/
STATIC int
xfs_bmap_extsize_align(
xfs_mount_t *mp,
xfs_bmbt_irec_t *gotp, /* next extent pointer */
xfs_bmbt_irec_t *prevp, /* previous extent pointer */
xfs_extlen_t extsz, /* align to this extent size */
int rt, /* is this a realtime inode? */
int eof, /* is extent at end-of-file? */
int delay, /* creating delalloc extent? */
int convert, /* overwriting unwritten extent? */
xfs_fileoff_t *offp, /* in/out: aligned offset */
xfs_extlen_t *lenp) /* in/out: aligned length */
{
xfs_fileoff_t orig_off; /* original offset */
xfs_extlen_t orig_alen; /* original length */
xfs_fileoff_t orig_end; /* original off+len */
xfs_fileoff_t nexto; /* next file offset */
xfs_fileoff_t prevo; /* previous file offset */
xfs_fileoff_t align_off; /* temp for offset */
xfs_extlen_t align_alen; /* temp for length */
xfs_extlen_t temp; /* temp for calculations */
if (convert)
return 0;
orig_off = align_off = *offp;
orig_alen = align_alen = *lenp;
orig_end = orig_off + orig_alen;
/*
* If this request overlaps an existing extent, then don't
* attempt to perform any additional alignment.
*/
if (!delay && !eof &&
(orig_off >= gotp->br_startoff) &&
(orig_end <= gotp->br_startoff + gotp->br_blockcount)) {
return 0;
}
/*
* If the file offset is unaligned vs. the extent size
* we need to align it. This will be possible unless
* the file was previously written with a kernel that didn't
* perform this alignment, or if a truncate shot us in the
* foot.
*/
temp = do_mod(orig_off, extsz);
if (temp) {
align_alen += temp;
align_off -= temp;
}
/*
* Same adjustment for the end of the requested area.
*/
if ((temp = (align_alen % extsz))) {
align_alen += extsz - temp;
}
/*
* If the previous block overlaps with this proposed allocation
* then move the start forward without adjusting the length.
*/
if (prevp->br_startoff != NULLFILEOFF) {
if (prevp->br_startblock == HOLESTARTBLOCK)
prevo = prevp->br_startoff;
else
prevo = prevp->br_startoff + prevp->br_blockcount;
} else
prevo = 0;
if (align_off != orig_off && align_off < prevo)
align_off = prevo;
/*
* If the next block overlaps with this proposed allocation
* then move the start back without adjusting the length,
* but not before offset 0.
* This may of course make the start overlap previous block,
* and if we hit the offset 0 limit then the next block
* can still overlap too.
*/
if (!eof && gotp->br_startoff != NULLFILEOFF) {
if ((delay && gotp->br_startblock == HOLESTARTBLOCK) ||
(!delay && gotp->br_startblock == DELAYSTARTBLOCK))
nexto = gotp->br_startoff + gotp->br_blockcount;
else
nexto = gotp->br_startoff;
} else
nexto = NULLFILEOFF;
if (!eof &&
align_off + align_alen != orig_end &&
align_off + align_alen > nexto)
align_off = nexto > align_alen ? nexto - align_alen : 0;
/*
* If we're now overlapping the next or previous extent that
* means we can't fit an extsz piece in this hole. Just move
* the start forward to the first valid spot and set
* the length so we hit the end.
*/
if (align_off != orig_off && align_off < prevo)
align_off = prevo;
if (align_off + align_alen != orig_end &&
align_off + align_alen > nexto &&
nexto != NULLFILEOFF) {
ASSERT(nexto > prevo);
align_alen = nexto - align_off;
}
/*
* If realtime, and the result isn't a multiple of the realtime
* extent size we need to remove blocks until it is.
*/
if (rt && (temp = (align_alen % mp->m_sb.sb_rextsize))) {
/*
* We're not covering the original request, or
* we won't be able to once we fix the length.
*/
if (orig_off < align_off ||
orig_end > align_off + align_alen ||
align_alen - temp < orig_alen)
return XFS_ERROR(EINVAL);
/*
* Try to fix it by moving the start up.
*/
if (align_off + temp <= orig_off) {
align_alen -= temp;
align_off += temp;
}
/*
* Try to fix it by moving the end in.
*/
else if (align_off + align_alen - temp >= orig_end)
align_alen -= temp;
/*
* Set the start to the minimum then trim the length.
*/
else {
align_alen -= orig_off - align_off;
align_off = orig_off;
align_alen -= align_alen % mp->m_sb.sb_rextsize;
}
/*
* Result doesn't cover the request, fail it.
*/
if (orig_off < align_off || orig_end > align_off + align_alen)
return XFS_ERROR(EINVAL);
} else {
ASSERT(orig_off >= align_off);
ASSERT(orig_end <= align_off + align_alen);
}
#ifdef DEBUG
if (!eof && gotp->br_startoff != NULLFILEOFF)
ASSERT(align_off + align_alen <= gotp->br_startoff);
if (prevp->br_startoff != NULLFILEOFF)
ASSERT(align_off >= prevp->br_startoff + prevp->br_blockcount);
#endif
*lenp = align_alen;
*offp = align_off;
return 0;
}
#define XFS_ALLOC_GAP_UNITS 4
STATIC void
xfs_bmap_adjacent(
xfs_bmalloca_t *ap) /* bmap alloc argument struct */
{
xfs_fsblock_t adjust; /* adjustment to block numbers */
xfs_agnumber_t fb_agno; /* ag number of ap->firstblock */
xfs_mount_t *mp; /* mount point structure */
int nullfb; /* true if ap->firstblock isn't set */
int rt; /* true if inode is realtime */
#define ISVALID(x,y) \
(rt ? \
(x) < mp->m_sb.sb_rblocks : \
XFS_FSB_TO_AGNO(mp, x) == XFS_FSB_TO_AGNO(mp, y) && \
XFS_FSB_TO_AGNO(mp, x) < mp->m_sb.sb_agcount && \
XFS_FSB_TO_AGBNO(mp, x) < mp->m_sb.sb_agblocks)
mp = ap->ip->i_mount;
nullfb = *ap->firstblock == NULLFSBLOCK;
rt = XFS_IS_REALTIME_INODE(ap->ip) && ap->userdata;
fb_agno = nullfb ? NULLAGNUMBER : XFS_FSB_TO_AGNO(mp, *ap->firstblock);
/*
* If allocating at eof, and there's a previous real block,
* try to use its last block as our starting point.
*/
if (ap->eof && ap->prev.br_startoff != NULLFILEOFF &&
!isnullstartblock(ap->prev.br_startblock) &&
ISVALID(ap->prev.br_startblock + ap->prev.br_blockcount,
ap->prev.br_startblock)) {
ap->blkno = ap->prev.br_startblock + ap->prev.br_blockcount;
/*
* Adjust for the gap between prevp and us.
*/
adjust = ap->offset -
(ap->prev.br_startoff + ap->prev.br_blockcount);
if (adjust &&
ISVALID(ap->blkno + adjust, ap->prev.br_startblock))
ap->blkno += adjust;
}
/*
* If not at eof, then compare the two neighbor blocks.
* Figure out whether either one gives us a good starting point,
* and pick the better one.
*/
else if (!ap->eof) {
xfs_fsblock_t gotbno; /* right side block number */
xfs_fsblock_t gotdiff=0; /* right side difference */
xfs_fsblock_t prevbno; /* left side block number */
xfs_fsblock_t prevdiff=0; /* left side difference */
/*
* If there's a previous (left) block, select a requested
* start block based on it.
*/
if (ap->prev.br_startoff != NULLFILEOFF &&
!isnullstartblock(ap->prev.br_startblock) &&
(prevbno = ap->prev.br_startblock +
ap->prev.br_blockcount) &&
ISVALID(prevbno, ap->prev.br_startblock)) {
/*
* Calculate gap to end of previous block.
*/
adjust = prevdiff = ap->offset -
(ap->prev.br_startoff +
ap->prev.br_blockcount);
/*
* Figure the startblock based on the previous block's
* end and the gap size.
* Heuristic!
* If the gap is large relative to the piece we're
* allocating, or using it gives us an invalid block
* number, then just use the end of the previous block.
*/
if (prevdiff <= XFS_ALLOC_GAP_UNITS * ap->length &&
ISVALID(prevbno + prevdiff,
ap->prev.br_startblock))
prevbno += adjust;
else
prevdiff += adjust;
/*
* If the firstblock forbids it, can't use it,
* must use default.
*/
if (!rt && !nullfb &&
XFS_FSB_TO_AGNO(mp, prevbno) != fb_agno)
prevbno = NULLFSBLOCK;
}
/*
* No previous block or can't follow it, just default.
*/
else
prevbno = NULLFSBLOCK;
/*
* If there's a following (right) block, select a requested
* start block based on it.
*/
if (!isnullstartblock(ap->got.br_startblock)) {
/*
* Calculate gap to start of next block.
*/
adjust = gotdiff = ap->got.br_startoff - ap->offset;
/*
* Figure the startblock based on the next block's
* start and the gap size.
*/
gotbno = ap->got.br_startblock;
/*
* Heuristic!
* If the gap is large relative to the piece we're
* allocating, or using it gives us an invalid block
* number, then just use the start of the next block
* offset by our length.
*/
if (gotdiff <= XFS_ALLOC_GAP_UNITS * ap->length &&
ISVALID(gotbno - gotdiff, gotbno))
gotbno -= adjust;
else if (ISVALID(gotbno - ap->length, gotbno)) {
gotbno -= ap->length;
gotdiff += adjust - ap->length;
} else
gotdiff += adjust;
/*
* If the firstblock forbids it, can't use it,
* must use default.
*/
if (!rt && !nullfb &&
XFS_FSB_TO_AGNO(mp, gotbno) != fb_agno)
gotbno = NULLFSBLOCK;
}
/*
* No next block, just default.
*/
else
gotbno = NULLFSBLOCK;
/*
* If both valid, pick the better one, else the only good
* one, else ap->blkno is already set (to 0 or the inode block).
*/
if (prevbno != NULLFSBLOCK && gotbno != NULLFSBLOCK)
ap->blkno = prevdiff <= gotdiff ? prevbno : gotbno;
else if (prevbno != NULLFSBLOCK)
ap->blkno = prevbno;
else if (gotbno != NULLFSBLOCK)
ap->blkno = gotbno;
}
#undef ISVALID
}
STATIC int
xfs_bmap_rtalloc(
xfs_bmalloca_t *ap) /* bmap alloc argument struct */
{
xfs_alloctype_t atype = 0; /* type for allocation routines */
int error; /* error return value */
xfs_mount_t *mp; /* mount point structure */
xfs_extlen_t prod = 0; /* product factor for allocators */
xfs_extlen_t ralen = 0; /* realtime allocation length */
xfs_extlen_t align; /* minimum allocation alignment */
xfs_rtblock_t rtb;
mp = ap->ip->i_mount;
align = xfs_get_extsz_hint(ap->ip);
prod = align / mp->m_sb.sb_rextsize;
error = xfs_bmap_extsize_align(mp, &ap->got, &ap->prev,
align, 1, ap->eof, 0,
ap->conv, &ap->offset, &ap->length);
if (error)
return error;
ASSERT(ap->length);
ASSERT(ap->length % mp->m_sb.sb_rextsize == 0);
/*
* If the offset & length are not perfectly aligned
* then kill prod, it will just get us in trouble.
*/
if (do_mod(ap->offset, align) || ap->length % align)
prod = 1;
/*
* Set ralen to be the actual requested length in rtextents.
*/
ralen = ap->length / mp->m_sb.sb_rextsize;
/*
* If the old value was close enough to MAXEXTLEN that
* we rounded up to it, cut it back so it's valid again.
* Note that if it's a really large request (bigger than
* MAXEXTLEN), we don't hear about that number, and can't
* adjust the starting point to match it.
*/
if (ralen * mp->m_sb.sb_rextsize >= MAXEXTLEN)
ralen = MAXEXTLEN / mp->m_sb.sb_rextsize;
/*
* Lock out other modifications to the RT bitmap inode.
*/
xfs_ilock(mp->m_rbmip, XFS_ILOCK_EXCL);
xfs_trans_ijoin(ap->tp, mp->m_rbmip, XFS_ILOCK_EXCL);
/*
* If it's an allocation to an empty file at offset 0,
* pick an extent that will space things out in the rt area.
*/
if (ap->eof && ap->offset == 0) {
xfs_rtblock_t uninitialized_var(rtx); /* realtime extent no */
error = xfs_rtpick_extent(mp, ap->tp, ralen, &rtx);
if (error)
return error;
ap->blkno = rtx * mp->m_sb.sb_rextsize;
} else {
ap->blkno = 0;
}
xfs_bmap_adjacent(ap);
/*
* Realtime allocation, done through xfs_rtallocate_extent.
*/
atype = ap->blkno == 0 ? XFS_ALLOCTYPE_ANY_AG : XFS_ALLOCTYPE_NEAR_BNO;
do_div(ap->blkno, mp->m_sb.sb_rextsize);
rtb = ap->blkno;
ap->length = ralen;
if ((error = xfs_rtallocate_extent(ap->tp, ap->blkno, 1, ap->length,
&ralen, atype, ap->wasdel, prod, &rtb)))
return error;
if (rtb == NULLFSBLOCK && prod > 1 &&
(error = xfs_rtallocate_extent(ap->tp, ap->blkno, 1,
ap->length, &ralen, atype,
ap->wasdel, 1, &rtb)))
return error;
ap->blkno = rtb;
if (ap->blkno != NULLFSBLOCK) {
ap->blkno *= mp->m_sb.sb_rextsize;
ralen *= mp->m_sb.sb_rextsize;
ap->length = ralen;
ap->ip->i_d.di_nblocks += ralen;
xfs_trans_log_inode(ap->tp, ap->ip, XFS_ILOG_CORE);
if (ap->wasdel)
ap->ip->i_delayed_blks -= ralen;
/*
* Adjust the disk quota also. This was reserved
* earlier.
*/
xfs_trans_mod_dquot_byino(ap->tp, ap->ip,
ap->wasdel ? XFS_TRANS_DQ_DELRTBCOUNT :
XFS_TRANS_DQ_RTBCOUNT, (long) ralen);
} else {
ap->length = 0;
}
return 0;
}
STATIC int
xfs_bmap_btalloc_nullfb(
struct xfs_bmalloca *ap,
struct xfs_alloc_arg *args,
xfs_extlen_t *blen)
{
struct xfs_mount *mp = ap->ip->i_mount;
struct xfs_perag *pag;
xfs_agnumber_t ag, startag;
int notinit = 0;
int error;
if (ap->userdata && xfs_inode_is_filestream(ap->ip))
args->type = XFS_ALLOCTYPE_NEAR_BNO;
else
args->type = XFS_ALLOCTYPE_START_BNO;
args->total = ap->total;
/*
* Search for an allocation group with a single extent large enough
* for the request. If one isn't found, then adjust the minimum
* allocation size to the largest space found.
*/
startag = ag = XFS_FSB_TO_AGNO(mp, args->fsbno);
if (startag == NULLAGNUMBER)
startag = ag = 0;
pag = xfs_perag_get(mp, ag);
while (*blen < args->maxlen) {
if (!pag->pagf_init) {
error = xfs_alloc_pagf_init(mp, args->tp, ag,
XFS_ALLOC_FLAG_TRYLOCK);
if (error) {
xfs_perag_put(pag);
return error;
}
}
/*
* See xfs_alloc_fix_freelist...
*/
if (pag->pagf_init) {
xfs_extlen_t longest;
longest = xfs_alloc_longest_free_extent(mp, pag);
if (*blen < longest)
*blen = longest;
} else
notinit = 1;
if (xfs_inode_is_filestream(ap->ip)) {
if (*blen >= args->maxlen)
break;
if (ap->userdata) {
/*
* If startag is an invalid AG, we've
* come here once before and
* xfs_filestream_new_ag picked the
* best currently available.
*
* Don't continue looping, since we
* could loop forever.
*/
if (startag == NULLAGNUMBER)
break;
error = xfs_filestream_new_ag(ap, &ag);
xfs_perag_put(pag);
if (error)
return error;
/* loop again to set 'blen'*/
startag = NULLAGNUMBER;
pag = xfs_perag_get(mp, ag);
continue;
}
}
if (++ag == mp->m_sb.sb_agcount)
ag = 0;
if (ag == startag)
break;
xfs_perag_put(pag);
pag = xfs_perag_get(mp, ag);
}
xfs_perag_put(pag);
/*
* Since the above loop did a BUF_TRYLOCK, it is
* possible that there is space for this request.
*/
if (notinit || *blen < ap->minlen)
args->minlen = ap->minlen;
/*
* If the best seen length is less than the request
* length, use the best as the minimum.
*/
else if (*blen < args->maxlen)
args->minlen = *blen;
/*
* Otherwise we've seen an extent as big as maxlen,
* use that as the minimum.
*/
else
args->minlen = args->maxlen;
/*
* set the failure fallback case to look in the selected
* AG as the stream may have moved.
*/
if (xfs_inode_is_filestream(ap->ip))
ap->blkno = args->fsbno = XFS_AGB_TO_FSB(mp, ag, 0);
return 0;
}
STATIC int
xfs_bmap_btalloc(
xfs_bmalloca_t *ap) /* bmap alloc argument struct */
{
xfs_mount_t *mp; /* mount point structure */
xfs_alloctype_t atype = 0; /* type for allocation routines */
xfs_extlen_t align; /* minimum allocation alignment */
xfs_agnumber_t fb_agno; /* ag number of ap->firstblock */
xfs_agnumber_t ag;
xfs_alloc_arg_t args;
xfs_extlen_t blen;
xfs_extlen_t nextminlen = 0;
int nullfb; /* true if ap->firstblock isn't set */
int isaligned;
int tryagain;
int error;
ASSERT(ap->length);
mp = ap->ip->i_mount;
align = ap->userdata ? xfs_get_extsz_hint(ap->ip) : 0;
if (unlikely(align)) {
error = xfs_bmap_extsize_align(mp, &ap->got, &ap->prev,
align, 0, ap->eof, 0, ap->conv,
&ap->offset, &ap->length);
ASSERT(!error);
ASSERT(ap->length);
}
nullfb = *ap->firstblock == NULLFSBLOCK;
fb_agno = nullfb ? NULLAGNUMBER : XFS_FSB_TO_AGNO(mp, *ap->firstblock);
if (nullfb) {
if (ap->userdata && xfs_inode_is_filestream(ap->ip)) {
ag = xfs_filestream_lookup_ag(ap->ip);
ag = (ag != NULLAGNUMBER) ? ag : 0;
ap->blkno = XFS_AGB_TO_FSB(mp, ag, 0);
} else {
ap->blkno = XFS_INO_TO_FSB(mp, ap->ip->i_ino);
}
} else
ap->blkno = *ap->firstblock;
xfs_bmap_adjacent(ap);
/*
* If allowed, use ap->blkno; otherwise must use firstblock since
* it's in the right allocation group.
*/
if (nullfb || XFS_FSB_TO_AGNO(mp, ap->blkno) == fb_agno)
;
else
ap->blkno = *ap->firstblock;
/*
* Normal allocation, done through xfs_alloc_vextent.
*/
tryagain = isaligned = 0;
memset(&args, 0, sizeof(args));
args.tp = ap->tp;
args.mp = mp;
args.fsbno = ap->blkno;
/* Trim the allocation back to the maximum an AG can fit. */
args.maxlen = MIN(ap->length, XFS_ALLOC_AG_MAX_USABLE(mp));
args.firstblock = *ap->firstblock;
blen = 0;
if (nullfb) {
error = xfs_bmap_btalloc_nullfb(ap, &args, &blen);
if (error)
return error;
} else if (ap->flist->xbf_low) {
if (xfs_inode_is_filestream(ap->ip))
args.type = XFS_ALLOCTYPE_FIRST_AG;
else
args.type = XFS_ALLOCTYPE_START_BNO;
args.total = args.minlen = ap->minlen;
} else {
args.type = XFS_ALLOCTYPE_NEAR_BNO;
args.total = ap->total;
args.minlen = ap->minlen;
}
/* apply extent size hints if obtained earlier */
if (unlikely(align)) {
args.prod = align;
if ((args.mod = (xfs_extlen_t)do_mod(ap->offset, args.prod)))
args.mod = (xfs_extlen_t)(args.prod - args.mod);
} else if (mp->m_sb.sb_blocksize >= PAGE_CACHE_SIZE) {
args.prod = 1;
args.mod = 0;
} else {
args.prod = PAGE_CACHE_SIZE >> mp->m_sb.sb_blocklog;
if ((args.mod = (xfs_extlen_t)(do_mod(ap->offset, args.prod))))
args.mod = (xfs_extlen_t)(args.prod - args.mod);
}
/*
* If we are not low on available data blocks, and the
* underlying logical volume manager is a stripe, and
* the file offset is zero then try to allocate data
* blocks on stripe unit boundary.
* NOTE: ap->aeof is only set if the allocation length
* is >= the stripe unit and the allocation offset is
* at the end of file.
*/
if (!ap->flist->xbf_low && ap->aeof) {
if (!ap->offset) {
args.alignment = mp->m_dalign;
atype = args.type;
isaligned = 1;
/*
* Adjust for alignment
*/
if (blen > args.alignment && blen <= args.maxlen)
args.minlen = blen - args.alignment;
args.minalignslop = 0;
} else {
/*
* First try an exact bno allocation.
* If it fails then do a near or start bno
* allocation with alignment turned on.
*/
atype = args.type;
tryagain = 1;
args.type = XFS_ALLOCTYPE_THIS_BNO;
args.alignment = 1;
/*
* Compute the minlen+alignment for the
* next case. Set slop so that the value
* of minlen+alignment+slop doesn't go up
* between the calls.
*/
if (blen > mp->m_dalign && blen <= args.maxlen)
nextminlen = blen - mp->m_dalign;
else
nextminlen = args.minlen;
if (nextminlen + mp->m_dalign > args.minlen + 1)
args.minalignslop =
nextminlen + mp->m_dalign -
args.minlen - 1;
else
args.minalignslop = 0;
}
} else {
args.alignment = 1;
args.minalignslop = 0;
}
args.minleft = ap->minleft;
args.wasdel = ap->wasdel;
args.isfl = 0;
args.userdata = ap->userdata;
if ((error = xfs_alloc_vextent(&args)))
return error;
if (tryagain && args.fsbno == NULLFSBLOCK) {
/*
* Exact allocation failed. Now try with alignment
* turned on.
*/
args.type = atype;
args.fsbno = ap->blkno;
args.alignment = mp->m_dalign;
args.minlen = nextminlen;
args.minalignslop = 0;
isaligned = 1;
if ((error = xfs_alloc_vextent(&args)))
return error;
}
if (isaligned && args.fsbno == NULLFSBLOCK) {
/*
* allocation failed, so turn off alignment and
* try again.
*/
args.type = atype;
args.fsbno = ap->blkno;
args.alignment = 0;
if ((error = xfs_alloc_vextent(&args)))
return error;
}
if (args.fsbno == NULLFSBLOCK && nullfb &&
args.minlen > ap->minlen) {
args.minlen = ap->minlen;
args.type = XFS_ALLOCTYPE_START_BNO;
args.fsbno = ap->blkno;
if ((error = xfs_alloc_vextent(&args)))
return error;
}
if (args.fsbno == NULLFSBLOCK && nullfb) {
args.fsbno = 0;
args.type = XFS_ALLOCTYPE_FIRST_AG;
args.total = ap->minlen;
args.minleft = 0;
if ((error = xfs_alloc_vextent(&args)))
return error;
ap->flist->xbf_low = 1;
}
if (args.fsbno != NULLFSBLOCK) {
/*
* check the allocation happened at the same or higher AG than
* the first block that was allocated.
*/
ASSERT(*ap->firstblock == NULLFSBLOCK ||
XFS_FSB_TO_AGNO(mp, *ap->firstblock) ==
XFS_FSB_TO_AGNO(mp, args.fsbno) ||
(ap->flist->xbf_low &&
XFS_FSB_TO_AGNO(mp, *ap->firstblock) <
XFS_FSB_TO_AGNO(mp, args.fsbno)));
ap->blkno = args.fsbno;
if (*ap->firstblock == NULLFSBLOCK)
*ap->firstblock = args.fsbno;
ASSERT(nullfb || fb_agno == args.agno ||
(ap->flist->xbf_low && fb_agno < args.agno));
ap->length = args.len;
ap->ip->i_d.di_nblocks += args.len;
xfs_trans_log_inode(ap->tp, ap->ip, XFS_ILOG_CORE);
if (ap->wasdel)
ap->ip->i_delayed_blks -= args.len;
/*
* Adjust the disk quota also. This was reserved
* earlier.
*/
xfs_trans_mod_dquot_byino(ap->tp, ap->ip,
ap->wasdel ? XFS_TRANS_DQ_DELBCOUNT :
XFS_TRANS_DQ_BCOUNT,
(long) args.len);
} else {
ap->blkno = NULLFSBLOCK;
ap->length = 0;
}
return 0;
}
/*
* xfs_bmap_alloc is called by xfs_bmapi to allocate an extent for a file.
* It figures out where to ask the underlying allocator to put the new extent.
*/
STATIC int
xfs_bmap_alloc(
xfs_bmalloca_t *ap) /* bmap alloc argument struct */
{
if (XFS_IS_REALTIME_INODE(ap->ip) && ap->userdata)
return xfs_bmap_rtalloc(ap);
return xfs_bmap_btalloc(ap);
}
/*
* Trim the returned map to the required bounds
*/
STATIC void
xfs_bmapi_trim_map(
struct xfs_bmbt_irec *mval,
struct xfs_bmbt_irec *got,
xfs_fileoff_t *bno,
xfs_filblks_t len,
xfs_fileoff_t obno,
xfs_fileoff_t end,
int n,
int flags)
{
if ((flags & XFS_BMAPI_ENTIRE) ||
got->br_startoff + got->br_blockcount <= obno) {
*mval = *got;
if (isnullstartblock(got->br_startblock))
mval->br_startblock = DELAYSTARTBLOCK;
return;
}
if (obno > *bno)
*bno = obno;
ASSERT((*bno >= obno) || (n == 0));
ASSERT(*bno < end);
mval->br_startoff = *bno;
if (isnullstartblock(got->br_startblock))
mval->br_startblock = DELAYSTARTBLOCK;
else
mval->br_startblock = got->br_startblock +
(*bno - got->br_startoff);
/*
* Return the minimum of what we got and what we asked for for
* the length. We can use the len variable here because it is
* modified below and we could have been there before coming
* here if the first part of the allocation didn't overlap what
* was asked for.
*/
mval->br_blockcount = XFS_FILBLKS_MIN(end - *bno,
got->br_blockcount - (*bno - got->br_startoff));
mval->br_state = got->br_state;
ASSERT(mval->br_blockcount <= len);
return;
}
/*
* Update and validate the extent map to return
*/
STATIC void
xfs_bmapi_update_map(
struct xfs_bmbt_irec **map,
xfs_fileoff_t *bno,
xfs_filblks_t *len,
xfs_fileoff_t obno,
xfs_fileoff_t end,
int *n,
int flags)
{
xfs_bmbt_irec_t *mval = *map;
ASSERT((flags & XFS_BMAPI_ENTIRE) ||
((mval->br_startoff + mval->br_blockcount) <= end));
ASSERT((flags & XFS_BMAPI_ENTIRE) || (mval->br_blockcount <= *len) ||
(mval->br_startoff < obno));
*bno = mval->br_startoff + mval->br_blockcount;
*len = end - *bno;
if (*n > 0 && mval->br_startoff == mval[-1].br_startoff) {
/* update previous map with new information */
ASSERT(mval->br_startblock == mval[-1].br_startblock);
ASSERT(mval->br_blockcount > mval[-1].br_blockcount);
ASSERT(mval->br_state == mval[-1].br_state);
mval[-1].br_blockcount = mval->br_blockcount;
mval[-1].br_state = mval->br_state;
} else if (*n > 0 && mval->br_startblock != DELAYSTARTBLOCK &&
mval[-1].br_startblock != DELAYSTARTBLOCK &&
mval[-1].br_startblock != HOLESTARTBLOCK &&
mval->br_startblock == mval[-1].br_startblock +
mval[-1].br_blockcount &&
((flags & XFS_BMAPI_IGSTATE) ||
mval[-1].br_state == mval->br_state)) {
ASSERT(mval->br_startoff ==
mval[-1].br_startoff + mval[-1].br_blockcount);
mval[-1].br_blockcount += mval->br_blockcount;
} else if (*n > 0 &&
mval->br_startblock == DELAYSTARTBLOCK &&
mval[-1].br_startblock == DELAYSTARTBLOCK &&
mval->br_startoff ==
mval[-1].br_startoff + mval[-1].br_blockcount) {
mval[-1].br_blockcount += mval->br_blockcount;
mval[-1].br_state = mval->br_state;
} else if (!((*n == 0) &&
((mval->br_startoff + mval->br_blockcount) <=
obno))) {
mval++;
(*n)++;
}
*map = mval;
}
/*
* Map file blocks to filesystem blocks without allocation.
*/
int
xfs_bmapi_read(
struct xfs_inode *ip,
xfs_fileoff_t bno,
xfs_filblks_t len,
struct xfs_bmbt_irec *mval,
int *nmap,
int flags)
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_ifork *ifp;
struct xfs_bmbt_irec got;
struct xfs_bmbt_irec prev;
xfs_fileoff_t obno;
xfs_fileoff_t end;
xfs_extnum_t lastx;
int error;
int eof;
int n = 0;
int whichfork = (flags & XFS_BMAPI_ATTRFORK) ?
XFS_ATTR_FORK : XFS_DATA_FORK;
ASSERT(*nmap >= 1);
ASSERT(!(flags & ~(XFS_BMAPI_ATTRFORK|XFS_BMAPI_ENTIRE|
XFS_BMAPI_IGSTATE)));
if (unlikely(XFS_TEST_ERROR(
(XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE),
mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) {
XFS_ERROR_REPORT("xfs_bmapi_read", XFS_ERRLEVEL_LOW, mp);
return XFS_ERROR(EFSCORRUPTED);
}
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
XFS_STATS_INC(xs_blk_mapr);
ifp = XFS_IFORK_PTR(ip, whichfork);
if (!(ifp->if_flags & XFS_IFEXTENTS)) {
error = xfs_iread_extents(NULL, ip, whichfork);
if (error)
return error;
}
xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got, &prev);
end = bno + len;
obno = bno;
while (bno < end && n < *nmap) {
/* Reading past eof, act as though there's a hole up to end. */
if (eof)
got.br_startoff = end;
if (got.br_startoff > bno) {
/* Reading in a hole. */
mval->br_startoff = bno;
mval->br_startblock = HOLESTARTBLOCK;
mval->br_blockcount =
XFS_FILBLKS_MIN(len, got.br_startoff - bno);
mval->br_state = XFS_EXT_NORM;
bno += mval->br_blockcount;
len -= mval->br_blockcount;
mval++;
n++;
continue;
}
/* set up the extent map to return. */
xfs_bmapi_trim_map(mval, &got, &bno, len, obno, end, n, flags);
xfs_bmapi_update_map(&mval, &bno, &len, obno, end, &n, flags);
/* If we're done, stop now. */
if (bno >= end || n >= *nmap)
break;
/* Else go on to the next record. */
if (++lastx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t))
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, lastx), &got);
else
eof = 1;
}
*nmap = n;
return 0;
}
STATIC int
xfs_bmapi_reserve_delalloc(
struct xfs_inode *ip,
xfs_fileoff_t aoff,
xfs_filblks_t len,
struct xfs_bmbt_irec *got,
struct xfs_bmbt_irec *prev,
xfs_extnum_t *lastx,
int eof)
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_ifork *ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
xfs_extlen_t alen;
xfs_extlen_t indlen;
char rt = XFS_IS_REALTIME_INODE(ip);
xfs_extlen_t extsz;
int error;
alen = XFS_FILBLKS_MIN(len, MAXEXTLEN);
if (!eof)
alen = XFS_FILBLKS_MIN(alen, got->br_startoff - aoff);
/* Figure out the extent size, adjust alen */
extsz = xfs_get_extsz_hint(ip);
if (extsz) {
/*
* Make sure we don't exceed a single extent length when we
* align the extent by reducing length we are going to
* allocate by the maximum amount extent size aligment may
* require.
*/
alen = XFS_FILBLKS_MIN(len, MAXEXTLEN - (2 * extsz - 1));
error = xfs_bmap_extsize_align(mp, got, prev, extsz, rt, eof,
1, 0, &aoff, &alen);
ASSERT(!error);
}
if (rt)
extsz = alen / mp->m_sb.sb_rextsize;
/*
* Make a transaction-less quota reservation for delayed allocation
* blocks. This number gets adjusted later. We return if we haven't
* allocated blocks already inside this loop.
*/
error = xfs_trans_reserve_quota_nblks(NULL, ip, (long)alen, 0,
rt ? XFS_QMOPT_RES_RTBLKS : XFS_QMOPT_RES_REGBLKS);
if (error)
return error;
/*
* Split changing sb for alen and indlen since they could be coming
* from different places.
*/
indlen = (xfs_extlen_t)xfs_bmap_worst_indlen(ip, alen);
ASSERT(indlen > 0);
if (rt) {
error = xfs_mod_incore_sb(mp, XFS_SBS_FREXTENTS,
-((int64_t)extsz), 0);
} else {
error = xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS,
-((int64_t)alen), 0);
}
if (error)
goto out_unreserve_quota;
error = xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS,
-((int64_t)indlen), 0);
if (error)
goto out_unreserve_blocks;
ip->i_delayed_blks += alen;
got->br_startoff = aoff;
got->br_startblock = nullstartblock(indlen);
got->br_blockcount = alen;
got->br_state = XFS_EXT_NORM;
xfs_bmap_add_extent_hole_delay(ip, lastx, got);
/*
* Update our extent pointer, given that xfs_bmap_add_extent_hole_delay
* might have merged it into one of the neighbouring ones.
*/
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *lastx), got);
ASSERT(got->br_startoff <= aoff);
ASSERT(got->br_startoff + got->br_blockcount >= aoff + alen);
ASSERT(isnullstartblock(got->br_startblock));
ASSERT(got->br_state == XFS_EXT_NORM);
return 0;
out_unreserve_blocks:
if (rt)
xfs_mod_incore_sb(mp, XFS_SBS_FREXTENTS, extsz, 0);
else
xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS, alen, 0);
out_unreserve_quota:
if (XFS_IS_QUOTA_ON(mp))
xfs_trans_unreserve_quota_nblks(NULL, ip, (long)alen, 0, rt ?
XFS_QMOPT_RES_RTBLKS : XFS_QMOPT_RES_REGBLKS);
return error;
}
/*
* Map file blocks to filesystem blocks, adding delayed allocations as needed.
*/
int
xfs_bmapi_delay(
struct xfs_inode *ip, /* incore inode */
xfs_fileoff_t bno, /* starting file offs. mapped */
xfs_filblks_t len, /* length to map in file */
struct xfs_bmbt_irec *mval, /* output: map values */
int *nmap, /* i/o: mval size/count */
int flags) /* XFS_BMAPI_... */
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_ifork *ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
struct xfs_bmbt_irec got; /* current file extent record */
struct xfs_bmbt_irec prev; /* previous file extent record */
xfs_fileoff_t obno; /* old block number (offset) */
xfs_fileoff_t end; /* end of mapped file region */
xfs_extnum_t lastx; /* last useful extent number */
int eof; /* we've hit the end of extents */
int n = 0; /* current extent index */
int error = 0;
ASSERT(*nmap >= 1);
ASSERT(*nmap <= XFS_BMAP_MAX_NMAP);
ASSERT(!(flags & ~XFS_BMAPI_ENTIRE));
if (unlikely(XFS_TEST_ERROR(
(XFS_IFORK_FORMAT(ip, XFS_DATA_FORK) != XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_FORMAT(ip, XFS_DATA_FORK) != XFS_DINODE_FMT_BTREE),
mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) {
XFS_ERROR_REPORT("xfs_bmapi_delay", XFS_ERRLEVEL_LOW, mp);
return XFS_ERROR(EFSCORRUPTED);
}
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
XFS_STATS_INC(xs_blk_mapw);
if (!(ifp->if_flags & XFS_IFEXTENTS)) {
error = xfs_iread_extents(NULL, ip, XFS_DATA_FORK);
if (error)
return error;
}
xfs_bmap_search_extents(ip, bno, XFS_DATA_FORK, &eof, &lastx, &got, &prev);
end = bno + len;
obno = bno;
while (bno < end && n < *nmap) {
if (eof || got.br_startoff > bno) {
error = xfs_bmapi_reserve_delalloc(ip, bno, len, &got,
&prev, &lastx, eof);
if (error) {
if (n == 0) {
*nmap = 0;
return error;
}
break;
}
}
/* set up the extent map to return. */
xfs_bmapi_trim_map(mval, &got, &bno, len, obno, end, n, flags);
xfs_bmapi_update_map(&mval, &bno, &len, obno, end, &n, flags);
/* If we're done, stop now. */
if (bno >= end || n >= *nmap)
break;
/* Else go on to the next record. */
prev = got;
if (++lastx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t))
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, lastx), &got);
else
eof = 1;
}
*nmap = n;
return 0;
}
STATIC int
__xfs_bmapi_allocate(
struct xfs_bmalloca *bma)
{
struct xfs_mount *mp = bma->ip->i_mount;
int whichfork = (bma->flags & XFS_BMAPI_ATTRFORK) ?
XFS_ATTR_FORK : XFS_DATA_FORK;
struct xfs_ifork *ifp = XFS_IFORK_PTR(bma->ip, whichfork);
int tmp_logflags = 0;
int error;
int rt;
ASSERT(bma->length > 0);
rt = (whichfork == XFS_DATA_FORK) && XFS_IS_REALTIME_INODE(bma->ip);
/*
* For the wasdelay case, we could also just allocate the stuff asked
* for in this bmap call but that wouldn't be as good.
*/
if (bma->wasdel) {
bma->length = (xfs_extlen_t)bma->got.br_blockcount;
bma->offset = bma->got.br_startoff;
if (bma->idx != NULLEXTNUM && bma->idx) {
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx - 1),
&bma->prev);
}
} else {
bma->length = XFS_FILBLKS_MIN(bma->length, MAXEXTLEN);
if (!bma->eof)
bma->length = XFS_FILBLKS_MIN(bma->length,
bma->got.br_startoff - bma->offset);
}
/*
* Indicate if this is the first user data in the file, or just any
* user data.
*/
if (!(bma->flags & XFS_BMAPI_METADATA)) {
bma->userdata = (bma->offset == 0) ?
XFS_ALLOC_INITIAL_USER_DATA : XFS_ALLOC_USERDATA;
}
bma->minlen = (bma->flags & XFS_BMAPI_CONTIG) ? bma->length : 1;
/*
* Only want to do the alignment at the eof if it is userdata and
* allocation length is larger than a stripe unit.
*/
if (mp->m_dalign && bma->length >= mp->m_dalign &&
!(bma->flags & XFS_BMAPI_METADATA) && whichfork == XFS_DATA_FORK) {
error = xfs_bmap_isaeof(bma, whichfork);
if (error)
return error;
}
error = xfs_bmap_alloc(bma);
if (error)
return error;
if (bma->flist->xbf_low)
bma->minleft = 0;
if (bma->cur)
bma->cur->bc_private.b.firstblock = *bma->firstblock;
if (bma->blkno == NULLFSBLOCK)
return 0;
if ((ifp->if_flags & XFS_IFBROOT) && !bma->cur) {
bma->cur = xfs_bmbt_init_cursor(mp, bma->tp, bma->ip, whichfork);
bma->cur->bc_private.b.firstblock = *bma->firstblock;
bma->cur->bc_private.b.flist = bma->flist;
}
/*
* Bump the number of extents we've allocated
* in this call.
*/
bma->nallocs++;
if (bma->cur)
bma->cur->bc_private.b.flags =
bma->wasdel ? XFS_BTCUR_BPRV_WASDEL : 0;
bma->got.br_startoff = bma->offset;
bma->got.br_startblock = bma->blkno;
bma->got.br_blockcount = bma->length;
bma->got.br_state = XFS_EXT_NORM;
/*
* A wasdelay extent has been initialized, so shouldn't be flagged
* as unwritten.
*/
if (!bma->wasdel && (bma->flags & XFS_BMAPI_PREALLOC) &&
xfs_sb_version_hasextflgbit(&mp->m_sb))
bma->got.br_state = XFS_EXT_UNWRITTEN;
if (bma->wasdel)
error = xfs_bmap_add_extent_delay_real(bma);
else
error = xfs_bmap_add_extent_hole_real(bma, whichfork);
bma->logflags |= tmp_logflags;
if (error)
return error;
/*
* Update our extent pointer, given that xfs_bmap_add_extent_delay_real
* or xfs_bmap_add_extent_hole_real might have merged it into one of
* the neighbouring ones.
*/
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx), &bma->got);
ASSERT(bma->got.br_startoff <= bma->offset);
ASSERT(bma->got.br_startoff + bma->got.br_blockcount >=
bma->offset + bma->length);
ASSERT(bma->got.br_state == XFS_EXT_NORM ||
bma->got.br_state == XFS_EXT_UNWRITTEN);
return 0;
}
static void
xfs_bmapi_allocate_worker(
struct work_struct *work)
{
struct xfs_bmalloca *args = container_of(work,
struct xfs_bmalloca, work);
unsigned long pflags;
/* we are in a transaction context here */
current_set_flags_nested(&pflags, PF_FSTRANS);
args->result = __xfs_bmapi_allocate(args);
complete(args->done);
current_restore_flags_nested(&pflags, PF_FSTRANS);
}
/*
* Some allocation requests often come in with little stack to work on. Push
* them off to a worker thread so there is lots of stack to use. Otherwise just
* call directly to avoid the context switch overhead here.
*/
int
xfs_bmapi_allocate(
struct xfs_bmalloca *args)
{
DECLARE_COMPLETION_ONSTACK(done);
if (!args->stack_switch)
return __xfs_bmapi_allocate(args);
args->done = &done;
INIT_WORK_ONSTACK(&args->work, xfs_bmapi_allocate_worker);
queue_work(xfs_alloc_wq, &args->work);
wait_for_completion(&done);
return args->result;
}
STATIC int
xfs_bmapi_convert_unwritten(
struct xfs_bmalloca *bma,
struct xfs_bmbt_irec *mval,
xfs_filblks_t len,
int flags)
{
int whichfork = (flags & XFS_BMAPI_ATTRFORK) ?
XFS_ATTR_FORK : XFS_DATA_FORK;
struct xfs_ifork *ifp = XFS_IFORK_PTR(bma->ip, whichfork);
int tmp_logflags = 0;
int error;
/* check if we need to do unwritten->real conversion */
if (mval->br_state == XFS_EXT_UNWRITTEN &&
(flags & XFS_BMAPI_PREALLOC))
return 0;
/* check if we need to do real->unwritten conversion */
if (mval->br_state == XFS_EXT_NORM &&
(flags & (XFS_BMAPI_PREALLOC | XFS_BMAPI_CONVERT)) !=
(XFS_BMAPI_PREALLOC | XFS_BMAPI_CONVERT))
return 0;
/*
* Modify (by adding) the state flag, if writing.
*/
ASSERT(mval->br_blockcount <= len);
if ((ifp->if_flags & XFS_IFBROOT) && !bma->cur) {
bma->cur = xfs_bmbt_init_cursor(bma->ip->i_mount, bma->tp,
bma->ip, whichfork);
bma->cur->bc_private.b.firstblock = *bma->firstblock;
bma->cur->bc_private.b.flist = bma->flist;
}
mval->br_state = (mval->br_state == XFS_EXT_UNWRITTEN)
? XFS_EXT_NORM : XFS_EXT_UNWRITTEN;
error = xfs_bmap_add_extent_unwritten_real(bma->tp, bma->ip, &bma->idx,
&bma->cur, mval, bma->firstblock, bma->flist,
&tmp_logflags);
bma->logflags |= tmp_logflags;
if (error)
return error;
/*
* Update our extent pointer, given that
* xfs_bmap_add_extent_unwritten_real might have merged it into one
* of the neighbouring ones.
*/
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx), &bma->got);
/*
* We may have combined previously unwritten space with written space,
* so generate another request.
*/
if (mval->br_blockcount < len)
return EAGAIN;
return 0;
}
/*
* Map file blocks to filesystem blocks, and allocate blocks or convert the
* extent state if necessary. Details behaviour is controlled by the flags
* parameter. Only allocates blocks from a single allocation group, to avoid
* locking problems.
*
* The returned value in "firstblock" from the first call in a transaction
* must be remembered and presented to subsequent calls in "firstblock".
* An upper bound for the number of blocks to be allocated is supplied to
* the first call in "total"; if no allocation group has that many free
* blocks then the call will fail (return NULLFSBLOCK in "firstblock").
*/
int
xfs_bmapi_write(
struct xfs_trans *tp, /* transaction pointer */
struct xfs_inode *ip, /* incore inode */
xfs_fileoff_t bno, /* starting file offs. mapped */
xfs_filblks_t len, /* length to map in file */
int flags, /* XFS_BMAPI_... */
xfs_fsblock_t *firstblock, /* first allocated block
controls a.g. for allocs */
xfs_extlen_t total, /* total blocks needed */
struct xfs_bmbt_irec *mval, /* output: map values */
int *nmap, /* i/o: mval size/count */
struct xfs_bmap_free *flist) /* i/o: list extents to free */
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_ifork *ifp;
struct xfs_bmalloca bma = { 0 }; /* args for xfs_bmap_alloc */
xfs_fileoff_t end; /* end of mapped file region */
int eof; /* after the end of extents */
int error; /* error return */
int n; /* current extent index */
xfs_fileoff_t obno; /* old block number (offset) */
int whichfork; /* data or attr fork */
char inhole; /* current location is hole in file */
char wasdelay; /* old extent was delayed */
#ifdef DEBUG
xfs_fileoff_t orig_bno; /* original block number value */
int orig_flags; /* original flags arg value */
xfs_filblks_t orig_len; /* original value of len arg */
struct xfs_bmbt_irec *orig_mval; /* original value of mval */
int orig_nmap; /* original value of *nmap */
orig_bno = bno;
orig_len = len;
orig_flags = flags;
orig_mval = mval;
orig_nmap = *nmap;
#endif
ASSERT(*nmap >= 1);
ASSERT(*nmap <= XFS_BMAP_MAX_NMAP);
ASSERT(!(flags & XFS_BMAPI_IGSTATE));
ASSERT(tp != NULL);
ASSERT(len > 0);
whichfork = (flags & XFS_BMAPI_ATTRFORK) ?
XFS_ATTR_FORK : XFS_DATA_FORK;
if (unlikely(XFS_TEST_ERROR(
(XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_LOCAL),
mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) {
XFS_ERROR_REPORT("xfs_bmapi_write", XFS_ERRLEVEL_LOW, mp);
return XFS_ERROR(EFSCORRUPTED);
}
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
ifp = XFS_IFORK_PTR(ip, whichfork);
XFS_STATS_INC(xs_blk_mapw);
if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) {
/*
* XXX (dgc): This assumes we are only called for inodes that
* contain content neutral data in local format. Anything that
* contains caller-specific data in local format that needs
* transformation to move to a block format needs to do the
* conversion to extent format itself.
*
* Directory data forks and attribute forks handle this
* themselves, but with the addition of metadata verifiers every
* data fork in local format now contains caller specific data
* and as such conversion through this function is likely to be
* broken.
*
* The only likely user of this branch is for remote symlinks,
* but we cannot overwrite the data fork contents of the symlink
* (EEXIST occurs higher up the stack) and so it will never go
* from local format to extent format here. Hence I don't think
* this branch is ever executed intentionally and we should
* consider removing it and asserting that xfs_bmapi_write()
* cannot be called directly on local format forks. i.e. callers
* are completely responsible for local to extent format
* conversion, not xfs_bmapi_write().
*/
error = xfs_bmap_local_to_extents(tp, ip, firstblock, total,
&bma.logflags, whichfork,
xfs_bmap_local_to_extents_init_fn);
if (error)
goto error0;
}
if (*firstblock == NULLFSBLOCK) {
if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE)
bma.minleft = be16_to_cpu(ifp->if_broot->bb_level) + 1;
else
bma.minleft = 1;
} else {
bma.minleft = 0;
}
if (!(ifp->if_flags & XFS_IFEXTENTS)) {
error = xfs_iread_extents(tp, ip, whichfork);
if (error)
goto error0;
}
xfs_bmap_search_extents(ip, bno, whichfork, &eof, &bma.idx, &bma.got,
&bma.prev);
n = 0;
end = bno + len;
obno = bno;
bma.tp = tp;
bma.ip = ip;
bma.total = total;
bma.userdata = 0;
bma.flist = flist;
bma.firstblock = firstblock;
if (flags & XFS_BMAPI_STACK_SWITCH)
bma.stack_switch = 1;
while (bno < end && n < *nmap) {
inhole = eof || bma.got.br_startoff > bno;
wasdelay = !inhole && isnullstartblock(bma.got.br_startblock);
/*
* First, deal with the hole before the allocated space
* that we found, if any.
*/
if (inhole || wasdelay) {
bma.eof = eof;
bma.conv = !!(flags & XFS_BMAPI_CONVERT);
bma.wasdel = wasdelay;
bma.offset = bno;
bma.flags = flags;
/*
* There's a 32/64 bit type mismatch between the
* allocation length request (which can be 64 bits in
* length) and the bma length request, which is
* xfs_extlen_t and therefore 32 bits. Hence we have to
* check for 32-bit overflows and handle them here.
*/
if (len > (xfs_filblks_t)MAXEXTLEN)
bma.length = MAXEXTLEN;
else
bma.length = len;
ASSERT(len > 0);
ASSERT(bma.length > 0);
error = xfs_bmapi_allocate(&bma);
if (error)
goto error0;
if (bma.blkno == NULLFSBLOCK)
break;
}
/* Deal with the allocated space we found. */
xfs_bmapi_trim_map(mval, &bma.got, &bno, len, obno,
end, n, flags);
/* Execute unwritten extent conversion if necessary */
error = xfs_bmapi_convert_unwritten(&bma, mval, len, flags);
if (error == EAGAIN)
continue;
if (error)
goto error0;
/* update the extent map to return */
xfs_bmapi_update_map(&mval, &bno, &len, obno, end, &n, flags);
/*
* If we're done, stop now. Stop when we've allocated
* XFS_BMAP_MAX_NMAP extents no matter what. Otherwise
* the transaction may get too big.
*/
if (bno >= end || n >= *nmap || bma.nallocs >= *nmap)
break;
/* Else go on to the next record. */
bma.prev = bma.got;
if (++bma.idx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t)) {
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma.idx),
&bma.got);
} else
eof = 1;
}
*nmap = n;
/*
* Transform from btree to extents, give it cur.
*/
if (xfs_bmap_wants_extents(ip, whichfork)) {
int tmp_logflags = 0;
ASSERT(bma.cur);
error = xfs_bmap_btree_to_extents(tp, ip, bma.cur,
&tmp_logflags, whichfork);
bma.logflags |= tmp_logflags;
if (error)
goto error0;
}
ASSERT(XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE ||
XFS_IFORK_NEXTENTS(ip, whichfork) >
XFS_IFORK_MAXEXT(ip, whichfork));
error = 0;
error0:
/*
* Log everything. Do this after conversion, there's no point in
* logging the extent records if we've converted to btree format.
*/
if ((bma.logflags & xfs_ilog_fext(whichfork)) &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
bma.logflags &= ~xfs_ilog_fext(whichfork);
else if ((bma.logflags & xfs_ilog_fbroot(whichfork)) &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)
bma.logflags &= ~xfs_ilog_fbroot(whichfork);
/*
* Log whatever the flags say, even if error. Otherwise we might miss
* detecting a case where the data is changed, there's an error,
* and it's not logged so we don't shutdown when we should.
*/
if (bma.logflags)
xfs_trans_log_inode(tp, ip, bma.logflags);
if (bma.cur) {
if (!error) {
ASSERT(*firstblock == NULLFSBLOCK ||
XFS_FSB_TO_AGNO(mp, *firstblock) ==
XFS_FSB_TO_AGNO(mp,
bma.cur->bc_private.b.firstblock) ||
(flist->xbf_low &&
XFS_FSB_TO_AGNO(mp, *firstblock) <
XFS_FSB_TO_AGNO(mp,
bma.cur->bc_private.b.firstblock)));
*firstblock = bma.cur->bc_private.b.firstblock;
}
xfs_btree_del_cursor(bma.cur,
error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
}
if (!error)
xfs_bmap_validate_ret(orig_bno, orig_len, orig_flags, orig_mval,
orig_nmap, *nmap);
return error;
}
/*
* Called by xfs_bmapi to update file extent records and the btree
* after removing space (or undoing a delayed allocation).
*/
STATIC int /* error */
xfs_bmap_del_extent(
xfs_inode_t *ip, /* incore inode pointer */
xfs_trans_t *tp, /* current transaction pointer */
xfs_extnum_t *idx, /* extent number to update/delete */
xfs_bmap_free_t *flist, /* list of extents to be freed */
xfs_btree_cur_t *cur, /* if null, not a btree */
xfs_bmbt_irec_t *del, /* data to remove from extents */
int *logflagsp, /* inode logging flags */
int whichfork) /* data or attr fork */
{
xfs_filblks_t da_new; /* new delay-alloc indirect blocks */
xfs_filblks_t da_old; /* old delay-alloc indirect blocks */
xfs_fsblock_t del_endblock=0; /* first block past del */
xfs_fileoff_t del_endoff; /* first offset past del */
int delay; /* current block is delayed allocated */
int do_fx; /* free extent at end of routine */
xfs_bmbt_rec_host_t *ep; /* current extent entry pointer */
int error; /* error return value */
int flags; /* inode logging flags */
xfs_bmbt_irec_t got; /* current extent entry */
xfs_fileoff_t got_endoff; /* first offset past got */
int i; /* temp state */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_mount_t *mp; /* mount structure */
xfs_filblks_t nblks; /* quota/sb block count */
xfs_bmbt_irec_t new; /* new record to be inserted */
/* REFERENCED */
uint qfield; /* quota field to update */
xfs_filblks_t temp; /* for indirect length calculations */
xfs_filblks_t temp2; /* for indirect length calculations */
int state = 0;
XFS_STATS_INC(xs_del_exlist);
if (whichfork == XFS_ATTR_FORK)
state |= BMAP_ATTRFORK;
mp = ip->i_mount;
ifp = XFS_IFORK_PTR(ip, whichfork);
ASSERT((*idx >= 0) && (*idx < ifp->if_bytes /
(uint)sizeof(xfs_bmbt_rec_t)));
ASSERT(del->br_blockcount > 0);
ep = xfs_iext_get_ext(ifp, *idx);
xfs_bmbt_get_all(ep, &got);
ASSERT(got.br_startoff <= del->br_startoff);
del_endoff = del->br_startoff + del->br_blockcount;
got_endoff = got.br_startoff + got.br_blockcount;
ASSERT(got_endoff >= del_endoff);
delay = isnullstartblock(got.br_startblock);
ASSERT(isnullstartblock(del->br_startblock) == delay);
flags = 0;
qfield = 0;
error = 0;
/*
* If deleting a real allocation, must free up the disk space.
*/
if (!delay) {
flags = XFS_ILOG_CORE;
/*
* Realtime allocation. Free it and record di_nblocks update.
*/
if (whichfork == XFS_DATA_FORK && XFS_IS_REALTIME_INODE(ip)) {
xfs_fsblock_t bno;
xfs_filblks_t len;
ASSERT(do_mod(del->br_blockcount,
mp->m_sb.sb_rextsize) == 0);
ASSERT(do_mod(del->br_startblock,
mp->m_sb.sb_rextsize) == 0);
bno = del->br_startblock;
len = del->br_blockcount;
do_div(bno, mp->m_sb.sb_rextsize);
do_div(len, mp->m_sb.sb_rextsize);
error = xfs_rtfree_extent(tp, bno, (xfs_extlen_t)len);
if (error)
goto done;
do_fx = 0;
nblks = len * mp->m_sb.sb_rextsize;
qfield = XFS_TRANS_DQ_RTBCOUNT;
}
/*
* Ordinary allocation.
*/
else {
do_fx = 1;
nblks = del->br_blockcount;
qfield = XFS_TRANS_DQ_BCOUNT;
}
/*
* Set up del_endblock and cur for later.
*/
del_endblock = del->br_startblock + del->br_blockcount;
if (cur) {
if ((error = xfs_bmbt_lookup_eq(cur, got.br_startoff,
got.br_startblock, got.br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
da_old = da_new = 0;
} else {
da_old = startblockval(got.br_startblock);
da_new = 0;
nblks = 0;
do_fx = 0;
}
/*
* Set flag value to use in switch statement.
* Left-contig is 2, right-contig is 1.
*/
switch (((got.br_startoff == del->br_startoff) << 1) |
(got_endoff == del_endoff)) {
case 3:
/*
* Matches the whole extent. Delete the entry.
*/
xfs_iext_remove(ip, *idx, 1,
whichfork == XFS_ATTR_FORK ? BMAP_ATTRFORK : 0);
--*idx;
if (delay)
break;
XFS_IFORK_NEXT_SET(ip, whichfork,
XFS_IFORK_NEXTENTS(ip, whichfork) - 1);
flags |= XFS_ILOG_CORE;
if (!cur) {
flags |= xfs_ilog_fext(whichfork);
break;
}
if ((error = xfs_btree_delete(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
break;
case 2:
/*
* Deleting the first part of the extent.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_startoff(ep, del_endoff);
temp = got.br_blockcount - del->br_blockcount;
xfs_bmbt_set_blockcount(ep, temp);
if (delay) {
temp = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
da_old);
xfs_bmbt_set_startblock(ep, nullstartblock((int)temp));
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
da_new = temp;
break;
}
xfs_bmbt_set_startblock(ep, del_endblock);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
if (!cur) {
flags |= xfs_ilog_fext(whichfork);
break;
}
if ((error = xfs_bmbt_update(cur, del_endoff, del_endblock,
got.br_blockcount - del->br_blockcount,
got.br_state)))
goto done;
break;
case 1:
/*
* Deleting the last part of the extent.
*/
temp = got.br_blockcount - del->br_blockcount;
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep, temp);
if (delay) {
temp = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
da_old);
xfs_bmbt_set_startblock(ep, nullstartblock((int)temp));
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
da_new = temp;
break;
}
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
if (!cur) {
flags |= xfs_ilog_fext(whichfork);
break;
}
if ((error = xfs_bmbt_update(cur, got.br_startoff,
got.br_startblock,
got.br_blockcount - del->br_blockcount,
got.br_state)))
goto done;
break;
case 0:
/*
* Deleting the middle of the extent.
*/
temp = del->br_startoff - got.br_startoff;
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep, temp);
new.br_startoff = del_endoff;
temp2 = got_endoff - del_endoff;
new.br_blockcount = temp2;
new.br_state = got.br_state;
if (!delay) {
new.br_startblock = del_endblock;
flags |= XFS_ILOG_CORE;
if (cur) {
if ((error = xfs_bmbt_update(cur,
got.br_startoff,
got.br_startblock, temp,
got.br_state)))
goto done;
if ((error = xfs_btree_increment(cur, 0, &i)))
goto done;
cur->bc_rec.b = new;
error = xfs_btree_insert(cur, &i);
if (error && error != ENOSPC)
goto done;
/*
* If get no-space back from btree insert,
* it tried a split, and we have a zero
* block reservation.
* Fix up our state and return the error.
*/
if (error == ENOSPC) {
/*
* Reset the cursor, don't trust
* it after any insert operation.
*/
if ((error = xfs_bmbt_lookup_eq(cur,
got.br_startoff,
got.br_startblock,
temp, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
/*
* Update the btree record back
* to the original value.
*/
if ((error = xfs_bmbt_update(cur,
got.br_startoff,
got.br_startblock,
got.br_blockcount,
got.br_state)))
goto done;
/*
* Reset the extent record back
* to the original value.
*/
xfs_bmbt_set_blockcount(ep,
got.br_blockcount);
flags = 0;
error = XFS_ERROR(ENOSPC);
goto done;
}
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
} else
flags |= xfs_ilog_fext(whichfork);
XFS_IFORK_NEXT_SET(ip, whichfork,
XFS_IFORK_NEXTENTS(ip, whichfork) + 1);
} else {
ASSERT(whichfork == XFS_DATA_FORK);
temp = xfs_bmap_worst_indlen(ip, temp);
xfs_bmbt_set_startblock(ep, nullstartblock((int)temp));
temp2 = xfs_bmap_worst_indlen(ip, temp2);
new.br_startblock = nullstartblock((int)temp2);
da_new = temp + temp2;
while (da_new > da_old) {
if (temp) {
temp--;
da_new--;
xfs_bmbt_set_startblock(ep,
nullstartblock((int)temp));
}
if (da_new == da_old)
break;
if (temp2) {
temp2--;
da_new--;
new.br_startblock =
nullstartblock((int)temp2);
}
}
}
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
xfs_iext_insert(ip, *idx + 1, 1, &new, state);
++*idx;
break;
}
/*
* If we need to, add to list of extents to delete.
*/
if (do_fx)
xfs_bmap_add_free(del->br_startblock, del->br_blockcount, flist,
mp);
/*
* Adjust inode # blocks in the file.
*/
if (nblks)
ip->i_d.di_nblocks -= nblks;
/*
* Adjust quota data.
*/
if (qfield)
xfs_trans_mod_dquot_byino(tp, ip, qfield, (long)-nblks);
/*
* Account for change in delayed indirect blocks.
* Nothing to do for disk quota accounting here.
*/
ASSERT(da_old >= da_new);
if (da_old > da_new) {
xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS,
(int64_t)(da_old - da_new), 0);
}
done:
*logflagsp = flags;
return error;
}
/*
* Unmap (remove) blocks from a file.
* If nexts is nonzero then the number of extents to remove is limited to
* that value. If not all extents in the block range can be removed then
* *done is set.
*/
int /* error */
xfs_bunmapi(
xfs_trans_t *tp, /* transaction pointer */
struct xfs_inode *ip, /* incore inode */
xfs_fileoff_t bno, /* starting offset to unmap */
xfs_filblks_t len, /* length to unmap in file */
int flags, /* misc flags */
xfs_extnum_t nexts, /* number of extents max */
xfs_fsblock_t *firstblock, /* first allocated block
controls a.g. for allocs */
xfs_bmap_free_t *flist, /* i/o: list extents to free */
int *done) /* set if not done yet */
{
xfs_btree_cur_t *cur; /* bmap btree cursor */
xfs_bmbt_irec_t del; /* extent being deleted */
int eof; /* is deleting at eof */
xfs_bmbt_rec_host_t *ep; /* extent record pointer */
int error; /* error return value */
xfs_extnum_t extno; /* extent number in list */
xfs_bmbt_irec_t got; /* current extent record */
xfs_ifork_t *ifp; /* inode fork pointer */
int isrt; /* freeing in rt area */
xfs_extnum_t lastx; /* last extent index used */
int logflags; /* transaction logging flags */
xfs_extlen_t mod; /* rt extent offset */
xfs_mount_t *mp; /* mount structure */
xfs_extnum_t nextents; /* number of file extents */
xfs_bmbt_irec_t prev; /* previous extent record */
xfs_fileoff_t start; /* first file offset deleted */
int tmp_logflags; /* partial logging flags */
int wasdel; /* was a delayed alloc extent */
int whichfork; /* data or attribute fork */
xfs_fsblock_t sum;
trace_xfs_bunmap(ip, bno, len, flags, _RET_IP_);
whichfork = (flags & XFS_BMAPI_ATTRFORK) ?
XFS_ATTR_FORK : XFS_DATA_FORK;
ifp = XFS_IFORK_PTR(ip, whichfork);
if (unlikely(
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)) {
XFS_ERROR_REPORT("xfs_bunmapi", XFS_ERRLEVEL_LOW,
ip->i_mount);
return XFS_ERROR(EFSCORRUPTED);
}
mp = ip->i_mount;
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
ASSERT(len > 0);
ASSERT(nexts >= 0);
if (!(ifp->if_flags & XFS_IFEXTENTS) &&
(error = xfs_iread_extents(tp, ip, whichfork)))
return error;
nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
if (nextents == 0) {
*done = 1;
return 0;
}
XFS_STATS_INC(xs_blk_unmap);
isrt = (whichfork == XFS_DATA_FORK) && XFS_IS_REALTIME_INODE(ip);
start = bno;
bno = start + len - 1;
ep = xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got,
&prev);
/*
* Check to see if the given block number is past the end of the
* file, back up to the last block if so...
*/
if (eof) {
ep = xfs_iext_get_ext(ifp, --lastx);
xfs_bmbt_get_all(ep, &got);
bno = got.br_startoff + got.br_blockcount - 1;
}
logflags = 0;
if (ifp->if_flags & XFS_IFBROOT) {
ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE);
cur = xfs_bmbt_init_cursor(mp, tp, ip, whichfork);
cur->bc_private.b.firstblock = *firstblock;
cur->bc_private.b.flist = flist;
cur->bc_private.b.flags = 0;
} else
cur = NULL;
if (isrt) {
/*
* Synchronize by locking the bitmap inode.
*/
xfs_ilock(mp->m_rbmip, XFS_ILOCK_EXCL);
xfs_trans_ijoin(tp, mp->m_rbmip, XFS_ILOCK_EXCL);
}
extno = 0;
while (bno != (xfs_fileoff_t)-1 && bno >= start && lastx >= 0 &&
(nexts == 0 || extno < nexts)) {
/*
* Is the found extent after a hole in which bno lives?
* Just back up to the previous extent, if so.
*/
if (got.br_startoff > bno) {
if (--lastx < 0)
break;
ep = xfs_iext_get_ext(ifp, lastx);
xfs_bmbt_get_all(ep, &got);
}
/*
* Is the last block of this extent before the range
* we're supposed to delete? If so, we're done.
*/
bno = XFS_FILEOFF_MIN(bno,
got.br_startoff + got.br_blockcount - 1);
if (bno < start)
break;
/*
* Then deal with the (possibly delayed) allocated space
* we found.
*/
ASSERT(ep != NULL);
del = got;
wasdel = isnullstartblock(del.br_startblock);
if (got.br_startoff < start) {
del.br_startoff = start;
del.br_blockcount -= start - got.br_startoff;
if (!wasdel)
del.br_startblock += start - got.br_startoff;
}
if (del.br_startoff + del.br_blockcount > bno + 1)
del.br_blockcount = bno + 1 - del.br_startoff;
sum = del.br_startblock + del.br_blockcount;
if (isrt &&
(mod = do_mod(sum, mp->m_sb.sb_rextsize))) {
/*
* Realtime extent not lined up at the end.
* The extent could have been split into written
* and unwritten pieces, or we could just be
* unmapping part of it. But we can't really
* get rid of part of a realtime extent.
*/
if (del.br_state == XFS_EXT_UNWRITTEN ||
!xfs_sb_version_hasextflgbit(&mp->m_sb)) {
/*
* This piece is unwritten, or we're not
* using unwritten extents. Skip over it.
*/
ASSERT(bno >= mod);
bno -= mod > del.br_blockcount ?
del.br_blockcount : mod;
if (bno < got.br_startoff) {
if (--lastx >= 0)
xfs_bmbt_get_all(xfs_iext_get_ext(
ifp, lastx), &got);
}
continue;
}
/*
* It's written, turn it unwritten.
* This is better than zeroing it.
*/
ASSERT(del.br_state == XFS_EXT_NORM);
ASSERT(xfs_trans_get_block_res(tp) > 0);
/*
* If this spans a realtime extent boundary,
* chop it back to the start of the one we end at.
*/
if (del.br_blockcount > mod) {
del.br_startoff += del.br_blockcount - mod;
del.br_startblock += del.br_blockcount - mod;
del.br_blockcount = mod;
}
del.br_state = XFS_EXT_UNWRITTEN;
error = xfs_bmap_add_extent_unwritten_real(tp, ip,
&lastx, &cur, &del, firstblock, flist,
&logflags);
if (error)
goto error0;
goto nodelete;
}
if (isrt && (mod = do_mod(del.br_startblock, mp->m_sb.sb_rextsize))) {
/*
* Realtime extent is lined up at the end but not
* at the front. We'll get rid of full extents if
* we can.
*/
mod = mp->m_sb.sb_rextsize - mod;
if (del.br_blockcount > mod) {
del.br_blockcount -= mod;
del.br_startoff += mod;
del.br_startblock += mod;
} else if ((del.br_startoff == start &&
(del.br_state == XFS_EXT_UNWRITTEN ||
xfs_trans_get_block_res(tp) == 0)) ||
!xfs_sb_version_hasextflgbit(&mp->m_sb)) {
/*
* Can't make it unwritten. There isn't
* a full extent here so just skip it.
*/
ASSERT(bno >= del.br_blockcount);
bno -= del.br_blockcount;
if (got.br_startoff > bno) {
if (--lastx >= 0) {
ep = xfs_iext_get_ext(ifp,
lastx);
xfs_bmbt_get_all(ep, &got);
}
}
continue;
} else if (del.br_state == XFS_EXT_UNWRITTEN) {
/*
* This one is already unwritten.
* It must have a written left neighbor.
* Unwrite the killed part of that one and
* try again.
*/
ASSERT(lastx > 0);
xfs_bmbt_get_all(xfs_iext_get_ext(ifp,
lastx - 1), &prev);
ASSERT(prev.br_state == XFS_EXT_NORM);
ASSERT(!isnullstartblock(prev.br_startblock));
ASSERT(del.br_startblock ==
prev.br_startblock + prev.br_blockcount);
if (prev.br_startoff < start) {
mod = start - prev.br_startoff;
prev.br_blockcount -= mod;
prev.br_startblock += mod;
prev.br_startoff = start;
}
prev.br_state = XFS_EXT_UNWRITTEN;
lastx--;
error = xfs_bmap_add_extent_unwritten_real(tp,
ip, &lastx, &cur, &prev,
firstblock, flist, &logflags);
if (error)
goto error0;
goto nodelete;
} else {
ASSERT(del.br_state == XFS_EXT_NORM);
del.br_state = XFS_EXT_UNWRITTEN;
error = xfs_bmap_add_extent_unwritten_real(tp,
ip, &lastx, &cur, &del,
firstblock, flist, &logflags);
if (error)
goto error0;
goto nodelete;
}
}
if (wasdel) {
ASSERT(startblockval(del.br_startblock) > 0);
/* Update realtime/data freespace, unreserve quota */
if (isrt) {
xfs_filblks_t rtexts;
rtexts = XFS_FSB_TO_B(mp, del.br_blockcount);
do_div(rtexts, mp->m_sb.sb_rextsize);
xfs_mod_incore_sb(mp, XFS_SBS_FREXTENTS,
(int64_t)rtexts, 0);
(void)xfs_trans_reserve_quota_nblks(NULL,
ip, -((long)del.br_blockcount), 0,
XFS_QMOPT_RES_RTBLKS);
} else {
xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS,
(int64_t)del.br_blockcount, 0);
(void)xfs_trans_reserve_quota_nblks(NULL,
ip, -((long)del.br_blockcount), 0,
XFS_QMOPT_RES_REGBLKS);
}
ip->i_delayed_blks -= del.br_blockcount;
if (cur)
cur->bc_private.b.flags |=
XFS_BTCUR_BPRV_WASDEL;
} else if (cur)
cur->bc_private.b.flags &= ~XFS_BTCUR_BPRV_WASDEL;
/*
* If it's the case where the directory code is running
* with no block reservation, and the deleted block is in
* the middle of its extent, and the resulting insert
* of an extent would cause transformation to btree format,
* then reject it. The calling code will then swap
* blocks around instead.
* We have to do this now, rather than waiting for the
* conversion to btree format, since the transaction
* will be dirty.
*/
if (!wasdel && xfs_trans_get_block_res(tp) == 0 &&
XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_NEXTENTS(ip, whichfork) >= /* Note the >= */
XFS_IFORK_MAXEXT(ip, whichfork) &&
del.br_startoff > got.br_startoff &&
del.br_startoff + del.br_blockcount <
got.br_startoff + got.br_blockcount) {
error = XFS_ERROR(ENOSPC);
goto error0;
}
error = xfs_bmap_del_extent(ip, tp, &lastx, flist, cur, &del,
&tmp_logflags, whichfork);
logflags |= tmp_logflags;
if (error)
goto error0;
bno = del.br_startoff - 1;
nodelete:
/*
* If not done go on to the next (previous) record.
*/
if (bno != (xfs_fileoff_t)-1 && bno >= start) {
if (lastx >= 0) {
ep = xfs_iext_get_ext(ifp, lastx);
if (xfs_bmbt_get_startoff(ep) > bno) {
if (--lastx >= 0)
ep = xfs_iext_get_ext(ifp,
lastx);
}
xfs_bmbt_get_all(ep, &got);
}
extno++;
}
}
*done = bno == (xfs_fileoff_t)-1 || bno < start || lastx < 0;
/*
* Convert to a btree if necessary.
*/
if (xfs_bmap_needs_btree(ip, whichfork)) {
ASSERT(cur == NULL);
error = xfs_bmap_extents_to_btree(tp, ip, firstblock, flist,
&cur, 0, &tmp_logflags, whichfork);
logflags |= tmp_logflags;
if (error)
goto error0;
}
/*
* transform from btree to extents, give it cur
*/
else if (xfs_bmap_wants_extents(ip, whichfork)) {
ASSERT(cur != NULL);
error = xfs_bmap_btree_to_extents(tp, ip, cur, &tmp_logflags,
whichfork);
logflags |= tmp_logflags;
if (error)
goto error0;
}
/*
* transform from extents to local?
*/
error = 0;
error0:
/*
* Log everything. Do this after conversion, there's no point in
* logging the extent records if we've converted to btree format.
*/
if ((logflags & xfs_ilog_fext(whichfork)) &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
logflags &= ~xfs_ilog_fext(whichfork);
else if ((logflags & xfs_ilog_fbroot(whichfork)) &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)
logflags &= ~xfs_ilog_fbroot(whichfork);
/*
* Log inode even in the error case, if the transaction
* is dirty we'll need to shut down the filesystem.
*/
if (logflags)
xfs_trans_log_inode(tp, ip, logflags);
if (cur) {
if (!error) {
*firstblock = cur->bc_private.b.firstblock;
cur->bc_private.b.allocated = 0;
}
xfs_btree_del_cursor(cur,
error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
}
return error;
}
/*
* returns 1 for success, 0 if we failed to map the extent.
*/
STATIC int
xfs_getbmapx_fix_eof_hole(
xfs_inode_t *ip, /* xfs incore inode pointer */
struct getbmapx *out, /* output structure */
int prealloced, /* this is a file with
* preallocated data space */
__int64_t end, /* last block requested */
xfs_fsblock_t startblock)
{
__int64_t fixlen;
xfs_mount_t *mp; /* file system mount point */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_extnum_t lastx; /* last extent pointer */
xfs_fileoff_t fileblock;
if (startblock == HOLESTARTBLOCK) {
mp = ip->i_mount;
out->bmv_block = -1;
fixlen = XFS_FSB_TO_BB(mp, XFS_B_TO_FSB(mp, XFS_ISIZE(ip)));
fixlen -= out->bmv_offset;
if (prealloced && out->bmv_offset + out->bmv_length == end) {
/* Came to hole at EOF. Trim it. */
if (fixlen <= 0)
return 0;
out->bmv_length = fixlen;
}
} else {
if (startblock == DELAYSTARTBLOCK)
out->bmv_block = -2;
else
out->bmv_block = xfs_fsb_to_db(ip, startblock);
fileblock = XFS_BB_TO_FSB(ip->i_mount, out->bmv_offset);
ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
if (xfs_iext_bno_to_ext(ifp, fileblock, &lastx) &&
(lastx == (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t))-1))
out->bmv_oflags |= BMV_OF_LAST;
}
return 1;
}
/*
* Get inode's extents as described in bmv, and format for output.
* Calls formatter to fill the user's buffer until all extents
* are mapped, until the passed-in bmv->bmv_count slots have
* been filled, or until the formatter short-circuits the loop,
* if it is tracking filled-in extents on its own.
*/
int /* error code */
xfs_getbmap(
xfs_inode_t *ip,
struct getbmapx *bmv, /* user bmap structure */
xfs_bmap_format_t formatter, /* format to user */
void *arg) /* formatter arg */
{
__int64_t bmvend; /* last block requested */
int error = 0; /* return value */
__int64_t fixlen; /* length for -1 case */
int i; /* extent number */
int lock; /* lock state */
xfs_bmbt_irec_t *map; /* buffer for user's data */
xfs_mount_t *mp; /* file system mount point */
int nex; /* # of user extents can do */
int nexleft; /* # of user extents left */
int subnex; /* # of bmapi's can do */
int nmap; /* number of map entries */
struct getbmapx *out; /* output structure */
int whichfork; /* data or attr fork */
int prealloced; /* this is a file with
* preallocated data space */
int iflags; /* interface flags */
int bmapi_flags; /* flags for xfs_bmapi */
int cur_ext = 0;
mp = ip->i_mount;
iflags = bmv->bmv_iflags;
whichfork = iflags & BMV_IF_ATTRFORK ? XFS_ATTR_FORK : XFS_DATA_FORK;
if (whichfork == XFS_ATTR_FORK) {
if (XFS_IFORK_Q(ip)) {
if (ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS &&
ip->i_d.di_aformat != XFS_DINODE_FMT_BTREE &&
ip->i_d.di_aformat != XFS_DINODE_FMT_LOCAL)
return XFS_ERROR(EINVAL);
} else if (unlikely(
ip->i_d.di_aformat != 0 &&
ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS)) {
XFS_ERROR_REPORT("xfs_getbmap", XFS_ERRLEVEL_LOW,
ip->i_mount);
return XFS_ERROR(EFSCORRUPTED);
}
prealloced = 0;
fixlen = 1LL << 32;
} else {
if (ip->i_d.di_format != XFS_DINODE_FMT_EXTENTS &&
ip->i_d.di_format != XFS_DINODE_FMT_BTREE &&
ip->i_d.di_format != XFS_DINODE_FMT_LOCAL)
return XFS_ERROR(EINVAL);
if (xfs_get_extsz_hint(ip) ||
ip->i_d.di_flags & (XFS_DIFLAG_PREALLOC|XFS_DIFLAG_APPEND)){
prealloced = 1;
fixlen = mp->m_super->s_maxbytes;
} else {
prealloced = 0;
fixlen = XFS_ISIZE(ip);
}
}
if (bmv->bmv_length == -1) {
fixlen = XFS_FSB_TO_BB(mp, XFS_B_TO_FSB(mp, fixlen));
bmv->bmv_length =
max_t(__int64_t, fixlen - bmv->bmv_offset, 0);
} else if (bmv->bmv_length == 0) {
bmv->bmv_entries = 0;
return 0;
} else if (bmv->bmv_length < 0) {
return XFS_ERROR(EINVAL);
}
nex = bmv->bmv_count - 1;
if (nex <= 0)
return XFS_ERROR(EINVAL);
bmvend = bmv->bmv_offset + bmv->bmv_length;
if (bmv->bmv_count > ULONG_MAX / sizeof(struct getbmapx))
return XFS_ERROR(ENOMEM);
out = kmem_zalloc(bmv->bmv_count * sizeof(struct getbmapx), KM_MAYFAIL);
if (!out) {
out = kmem_zalloc_large(bmv->bmv_count *
sizeof(struct getbmapx));
if (!out)
return XFS_ERROR(ENOMEM);
}
xfs_ilock(ip, XFS_IOLOCK_SHARED);
if (whichfork == XFS_DATA_FORK && !(iflags & BMV_IF_DELALLOC)) {
if (ip->i_delayed_blks || XFS_ISIZE(ip) > ip->i_d.di_size) {
error = -filemap_write_and_wait(VFS_I(ip)->i_mapping);
if (error)
goto out_unlock_iolock;
}
/*
* even after flushing the inode, there can still be delalloc
* blocks on the inode beyond EOF due to speculative
* preallocation. These are not removed until the release
* function is called or the inode is inactivated. Hence we
* cannot assert here that ip->i_delayed_blks == 0.
*/
}
lock = xfs_ilock_map_shared(ip);
/*
* Don't let nex be bigger than the number of extents
* we can have assuming alternating holes and real extents.
*/
if (nex > XFS_IFORK_NEXTENTS(ip, whichfork) * 2 + 1)
nex = XFS_IFORK_NEXTENTS(ip, whichfork) * 2 + 1;
bmapi_flags = xfs_bmapi_aflag(whichfork);
if (!(iflags & BMV_IF_PREALLOC))
bmapi_flags |= XFS_BMAPI_IGSTATE;
/*
* Allocate enough space to handle "subnex" maps at a time.
*/
error = ENOMEM;
subnex = 16;
map = kmem_alloc(subnex * sizeof(*map), KM_MAYFAIL | KM_NOFS);
if (!map)
goto out_unlock_ilock;
bmv->bmv_entries = 0;
if (XFS_IFORK_NEXTENTS(ip, whichfork) == 0 &&
(whichfork == XFS_ATTR_FORK || !(iflags & BMV_IF_DELALLOC))) {
error = 0;
goto out_free_map;
}
nexleft = nex;
do {
nmap = (nexleft > subnex) ? subnex : nexleft;
error = xfs_bmapi_read(ip, XFS_BB_TO_FSBT(mp, bmv->bmv_offset),
XFS_BB_TO_FSB(mp, bmv->bmv_length),
map, &nmap, bmapi_flags);
if (error)
goto out_free_map;
ASSERT(nmap <= subnex);
for (i = 0; i < nmap && nexleft && bmv->bmv_length; i++) {
out[cur_ext].bmv_oflags = 0;
if (map[i].br_state == XFS_EXT_UNWRITTEN)
out[cur_ext].bmv_oflags |= BMV_OF_PREALLOC;
else if (map[i].br_startblock == DELAYSTARTBLOCK)
out[cur_ext].bmv_oflags |= BMV_OF_DELALLOC;
out[cur_ext].bmv_offset =
XFS_FSB_TO_BB(mp, map[i].br_startoff);
out[cur_ext].bmv_length =
XFS_FSB_TO_BB(mp, map[i].br_blockcount);
out[cur_ext].bmv_unused1 = 0;
out[cur_ext].bmv_unused2 = 0;
/*
* delayed allocation extents that start beyond EOF can
* occur due to speculative EOF allocation when the
* delalloc extent is larger than the largest freespace
* extent at conversion time. These extents cannot be
* converted by data writeback, so can exist here even
* if we are not supposed to be finding delalloc
* extents.
*/
if (map[i].br_startblock == DELAYSTARTBLOCK &&
map[i].br_startoff <= XFS_B_TO_FSB(mp, XFS_ISIZE(ip)))
ASSERT((iflags & BMV_IF_DELALLOC) != 0);
if (map[i].br_startblock == HOLESTARTBLOCK &&
whichfork == XFS_ATTR_FORK) {
/* came to the end of attribute fork */
out[cur_ext].bmv_oflags |= BMV_OF_LAST;
goto out_free_map;
}
if (!xfs_getbmapx_fix_eof_hole(ip, &out[cur_ext],
prealloced, bmvend,
map[i].br_startblock))
goto out_free_map;
bmv->bmv_offset =
out[cur_ext].bmv_offset +
out[cur_ext].bmv_length;
bmv->bmv_length =
max_t(__int64_t, 0, bmvend - bmv->bmv_offset);
/*
* In case we don't want to return the hole,
* don't increase cur_ext so that we can reuse
* it in the next loop.
*/
if ((iflags & BMV_IF_NO_HOLES) &&
map[i].br_startblock == HOLESTARTBLOCK) {
memset(&out[cur_ext], 0, sizeof(out[cur_ext]));
continue;
}
nexleft--;
bmv->bmv_entries++;
cur_ext++;
}
} while (nmap && nexleft && bmv->bmv_length);
out_free_map:
kmem_free(map);
out_unlock_ilock:
xfs_iunlock_map_shared(ip, lock);
out_unlock_iolock:
xfs_iunlock(ip, XFS_IOLOCK_SHARED);
for (i = 0; i < cur_ext; i++) {
int full = 0; /* user array is full */
/* format results & advance arg */
error = formatter(&arg, &out[i], &full);
if (error || full)
break;
}
if (is_vmalloc_addr(out))
kmem_free_large(out);
else
kmem_free(out);
return error;
}
/*
* dead simple method of punching delalyed allocation blocks from a range in
* the inode. Walks a block at a time so will be slow, but is only executed in
* rare error cases so the overhead is not critical. This will alays punch out
* both the start and end blocks, even if the ranges only partially overlap
* them, so it is up to the caller to ensure that partial blocks are not
* passed in.
*/
int
xfs_bmap_punch_delalloc_range(
struct xfs_inode *ip,
xfs_fileoff_t start_fsb,
xfs_fileoff_t length)
{
xfs_fileoff_t remaining = length;
int error = 0;
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
do {
int done;
xfs_bmbt_irec_t imap;
int nimaps = 1;
xfs_fsblock_t firstblock;
xfs_bmap_free_t flist;
/*
* Map the range first and check that it is a delalloc extent
* before trying to unmap the range. Otherwise we will be
* trying to remove a real extent (which requires a
* transaction) or a hole, which is probably a bad idea...
*/
error = xfs_bmapi_read(ip, start_fsb, 1, &imap, &nimaps,
XFS_BMAPI_ENTIRE);
if (error) {
/* something screwed, just bail */
if (!XFS_FORCED_SHUTDOWN(ip->i_mount)) {
xfs_alert(ip->i_mount,
"Failed delalloc mapping lookup ino %lld fsb %lld.",
ip->i_ino, start_fsb);
}
break;
}
if (!nimaps) {
/* nothing there */
goto next_block;
}
if (imap.br_startblock != DELAYSTARTBLOCK) {
/* been converted, ignore */
goto next_block;
}
WARN_ON(imap.br_blockcount == 0);
/*
* Note: while we initialise the firstblock/flist pair, they
* should never be used because blocks should never be
* allocated or freed for a delalloc extent and hence we need
* don't cancel or finish them after the xfs_bunmapi() call.
*/
xfs_bmap_init(&flist, &firstblock);
error = xfs_bunmapi(NULL, ip, start_fsb, 1, 0, 1, &firstblock,
&flist, &done);
if (error)
break;
ASSERT(!flist.xbf_count && !flist.xbf_first);
next_block:
start_fsb++;
remaining--;
} while(remaining > 0);
return error;
}
| gpl-2.0 |
Grace5921/Kernel_samsung_a8elte | drivers/spi/spi-mpc512x-psc.c | 2083 | 14278 | /*
* MPC512x PSC in SPI mode driver.
*
* Copyright (C) 2007,2008 Freescale Semiconductor Inc.
* Original port from 52xx driver:
* Hongjun Chen <hong-jun.chen@freescale.com>
*
* Fork of mpc52xx_psc_spi.c:
* Copyright (C) 2006 TOPTICA Photonics AG., Dragos Carp
*
* 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/kernel.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/of_address.h>
#include <linux/of_platform.h>
#include <linux/workqueue.h>
#include <linux/completion.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/spi/spi.h>
#include <linux/fsl_devices.h>
#include <linux/gpio.h>
#include <asm/mpc52xx_psc.h>
struct mpc512x_psc_spi {
void (*cs_control)(struct spi_device *spi, bool on);
u32 sysclk;
/* driver internal data */
struct mpc52xx_psc __iomem *psc;
struct mpc512x_psc_fifo __iomem *fifo;
unsigned int irq;
u8 bits_per_word;
u8 busy;
u32 mclk;
u8 eofbyte;
struct workqueue_struct *workqueue;
struct work_struct work;
struct list_head queue;
spinlock_t lock; /* Message queue lock */
struct completion done;
};
/* controller state */
struct mpc512x_psc_spi_cs {
int bits_per_word;
int speed_hz;
};
/* set clock freq, clock ramp, bits per work
* if t is NULL then reset the values to the default values
*/
static int mpc512x_psc_spi_transfer_setup(struct spi_device *spi,
struct spi_transfer *t)
{
struct mpc512x_psc_spi_cs *cs = spi->controller_state;
cs->speed_hz = (t && t->speed_hz)
? t->speed_hz : spi->max_speed_hz;
cs->bits_per_word = (t && t->bits_per_word)
? t->bits_per_word : spi->bits_per_word;
cs->bits_per_word = ((cs->bits_per_word + 7) / 8) * 8;
return 0;
}
static void mpc512x_psc_spi_activate_cs(struct spi_device *spi)
{
struct mpc512x_psc_spi_cs *cs = spi->controller_state;
struct mpc512x_psc_spi *mps = spi_master_get_devdata(spi->master);
struct mpc52xx_psc __iomem *psc = mps->psc;
u32 sicr;
u32 ccr;
u16 bclkdiv;
sicr = in_be32(&psc->sicr);
/* Set clock phase and polarity */
if (spi->mode & SPI_CPHA)
sicr |= 0x00001000;
else
sicr &= ~0x00001000;
if (spi->mode & SPI_CPOL)
sicr |= 0x00002000;
else
sicr &= ~0x00002000;
if (spi->mode & SPI_LSB_FIRST)
sicr |= 0x10000000;
else
sicr &= ~0x10000000;
out_be32(&psc->sicr, sicr);
ccr = in_be32(&psc->ccr);
ccr &= 0xFF000000;
if (cs->speed_hz)
bclkdiv = (mps->mclk / cs->speed_hz) - 1;
else
bclkdiv = (mps->mclk / 1000000) - 1; /* default 1MHz */
ccr |= (((bclkdiv & 0xff) << 16) | (((bclkdiv >> 8) & 0xff) << 8));
out_be32(&psc->ccr, ccr);
mps->bits_per_word = cs->bits_per_word;
if (mps->cs_control && gpio_is_valid(spi->cs_gpio))
mps->cs_control(spi, (spi->mode & SPI_CS_HIGH) ? 1 : 0);
}
static void mpc512x_psc_spi_deactivate_cs(struct spi_device *spi)
{
struct mpc512x_psc_spi *mps = spi_master_get_devdata(spi->master);
if (mps->cs_control && gpio_is_valid(spi->cs_gpio))
mps->cs_control(spi, (spi->mode & SPI_CS_HIGH) ? 0 : 1);
}
/* extract and scale size field in txsz or rxsz */
#define MPC512x_PSC_FIFO_SZ(sz) ((sz & 0x7ff) << 2);
#define EOFBYTE 1
static int mpc512x_psc_spi_transfer_rxtx(struct spi_device *spi,
struct spi_transfer *t)
{
struct mpc512x_psc_spi *mps = spi_master_get_devdata(spi->master);
struct mpc52xx_psc __iomem *psc = mps->psc;
struct mpc512x_psc_fifo __iomem *fifo = mps->fifo;
size_t len = t->len;
u8 *tx_buf = (u8 *)t->tx_buf;
u8 *rx_buf = (u8 *)t->rx_buf;
if (!tx_buf && !rx_buf && t->len)
return -EINVAL;
/* Zero MR2 */
in_8(&psc->mode);
out_8(&psc->mode, 0x0);
/* enable transmiter/receiver */
out_8(&psc->command, MPC52xx_PSC_TX_ENABLE | MPC52xx_PSC_RX_ENABLE);
while (len) {
int count;
int i;
u8 data;
size_t fifosz;
int rxcount;
/*
* The number of bytes that can be sent at a time
* depends on the fifo size.
*/
fifosz = MPC512x_PSC_FIFO_SZ(in_be32(&fifo->txsz));
count = min(fifosz, len);
for (i = count; i > 0; i--) {
data = tx_buf ? *tx_buf++ : 0;
if (len == EOFBYTE && t->cs_change)
setbits32(&fifo->txcmd, MPC512x_PSC_FIFO_EOF);
out_8(&fifo->txdata_8, data);
len--;
}
INIT_COMPLETION(mps->done);
/* interrupt on tx fifo empty */
out_be32(&fifo->txisr, MPC512x_PSC_FIFO_EMPTY);
out_be32(&fifo->tximr, MPC512x_PSC_FIFO_EMPTY);
wait_for_completion(&mps->done);
mdelay(1);
/* rx fifo should have count bytes in it */
rxcount = in_be32(&fifo->rxcnt);
if (rxcount != count)
mdelay(1);
rxcount = in_be32(&fifo->rxcnt);
if (rxcount != count) {
dev_warn(&spi->dev, "expected %d bytes in rx fifo "
"but got %d\n", count, rxcount);
}
rxcount = min(rxcount, count);
for (i = rxcount; i > 0; i--) {
data = in_8(&fifo->rxdata_8);
if (rx_buf)
*rx_buf++ = data;
}
while (in_be32(&fifo->rxcnt)) {
in_8(&fifo->rxdata_8);
}
}
/* disable transmiter/receiver and fifo interrupt */
out_8(&psc->command, MPC52xx_PSC_TX_DISABLE | MPC52xx_PSC_RX_DISABLE);
out_be32(&fifo->tximr, 0);
return 0;
}
static void mpc512x_psc_spi_work(struct work_struct *work)
{
struct mpc512x_psc_spi *mps = container_of(work,
struct mpc512x_psc_spi,
work);
spin_lock_irq(&mps->lock);
mps->busy = 1;
while (!list_empty(&mps->queue)) {
struct spi_message *m;
struct spi_device *spi;
struct spi_transfer *t = NULL;
unsigned cs_change;
int status;
m = container_of(mps->queue.next, struct spi_message, queue);
list_del_init(&m->queue);
spin_unlock_irq(&mps->lock);
spi = m->spi;
cs_change = 1;
status = 0;
list_for_each_entry(t, &m->transfers, transfer_list) {
if (t->bits_per_word || t->speed_hz) {
status = mpc512x_psc_spi_transfer_setup(spi, t);
if (status < 0)
break;
}
if (cs_change)
mpc512x_psc_spi_activate_cs(spi);
cs_change = t->cs_change;
status = mpc512x_psc_spi_transfer_rxtx(spi, t);
if (status)
break;
m->actual_length += t->len;
if (t->delay_usecs)
udelay(t->delay_usecs);
if (cs_change)
mpc512x_psc_spi_deactivate_cs(spi);
}
m->status = status;
m->complete(m->context);
if (status || !cs_change)
mpc512x_psc_spi_deactivate_cs(spi);
mpc512x_psc_spi_transfer_setup(spi, NULL);
spin_lock_irq(&mps->lock);
}
mps->busy = 0;
spin_unlock_irq(&mps->lock);
}
static int mpc512x_psc_spi_setup(struct spi_device *spi)
{
struct mpc512x_psc_spi *mps = spi_master_get_devdata(spi->master);
struct mpc512x_psc_spi_cs *cs = spi->controller_state;
unsigned long flags;
int ret;
if (spi->bits_per_word % 8)
return -EINVAL;
if (!cs) {
cs = kzalloc(sizeof *cs, GFP_KERNEL);
if (!cs)
return -ENOMEM;
if (gpio_is_valid(spi->cs_gpio)) {
ret = gpio_request(spi->cs_gpio, dev_name(&spi->dev));
if (ret) {
dev_err(&spi->dev, "can't get CS gpio: %d\n",
ret);
kfree(cs);
return ret;
}
gpio_direction_output(spi->cs_gpio,
spi->mode & SPI_CS_HIGH ? 0 : 1);
}
spi->controller_state = cs;
}
cs->bits_per_word = spi->bits_per_word;
cs->speed_hz = spi->max_speed_hz;
spin_lock_irqsave(&mps->lock, flags);
if (!mps->busy)
mpc512x_psc_spi_deactivate_cs(spi);
spin_unlock_irqrestore(&mps->lock, flags);
return 0;
}
static int mpc512x_psc_spi_transfer(struct spi_device *spi,
struct spi_message *m)
{
struct mpc512x_psc_spi *mps = spi_master_get_devdata(spi->master);
unsigned long flags;
m->actual_length = 0;
m->status = -EINPROGRESS;
spin_lock_irqsave(&mps->lock, flags);
list_add_tail(&m->queue, &mps->queue);
queue_work(mps->workqueue, &mps->work);
spin_unlock_irqrestore(&mps->lock, flags);
return 0;
}
static void mpc512x_psc_spi_cleanup(struct spi_device *spi)
{
if (gpio_is_valid(spi->cs_gpio))
gpio_free(spi->cs_gpio);
kfree(spi->controller_state);
}
static int mpc512x_psc_spi_port_config(struct spi_master *master,
struct mpc512x_psc_spi *mps)
{
struct mpc52xx_psc __iomem *psc = mps->psc;
struct mpc512x_psc_fifo __iomem *fifo = mps->fifo;
struct clk *spiclk;
int ret = 0;
char name[32];
u32 sicr;
u32 ccr;
u16 bclkdiv;
sprintf(name, "psc%d_mclk", master->bus_num);
spiclk = clk_get(&master->dev, name);
clk_enable(spiclk);
mps->mclk = clk_get_rate(spiclk);
clk_put(spiclk);
/* Reset the PSC into a known state */
out_8(&psc->command, MPC52xx_PSC_RST_RX);
out_8(&psc->command, MPC52xx_PSC_RST_TX);
out_8(&psc->command, MPC52xx_PSC_TX_DISABLE | MPC52xx_PSC_RX_DISABLE);
/* Disable psc interrupts all useful interrupts are in fifo */
out_be16(&psc->isr_imr.imr, 0);
/* Disable fifo interrupts, will be enabled later */
out_be32(&fifo->tximr, 0);
out_be32(&fifo->rximr, 0);
/* Setup fifo slice address and size */
/*out_be32(&fifo->txsz, 0x0fe00004);*/
/*out_be32(&fifo->rxsz, 0x0ff00004);*/
sicr = 0x01000000 | /* SIM = 0001 -- 8 bit */
0x00800000 | /* GenClk = 1 -- internal clk */
0x00008000 | /* SPI = 1 */
0x00004000 | /* MSTR = 1 -- SPI master */
0x00000800; /* UseEOF = 1 -- SS low until EOF */
out_be32(&psc->sicr, sicr);
ccr = in_be32(&psc->ccr);
ccr &= 0xFF000000;
bclkdiv = (mps->mclk / 1000000) - 1; /* default 1MHz */
ccr |= (((bclkdiv & 0xff) << 16) | (((bclkdiv >> 8) & 0xff) << 8));
out_be32(&psc->ccr, ccr);
/* Set 2ms DTL delay */
out_8(&psc->ctur, 0x00);
out_8(&psc->ctlr, 0x82);
/* we don't use the alarms */
out_be32(&fifo->rxalarm, 0xfff);
out_be32(&fifo->txalarm, 0);
/* Enable FIFO slices for Rx/Tx */
out_be32(&fifo->rxcmd,
MPC512x_PSC_FIFO_ENABLE_SLICE | MPC512x_PSC_FIFO_ENABLE_DMA);
out_be32(&fifo->txcmd,
MPC512x_PSC_FIFO_ENABLE_SLICE | MPC512x_PSC_FIFO_ENABLE_DMA);
mps->bits_per_word = 8;
return ret;
}
static irqreturn_t mpc512x_psc_spi_isr(int irq, void *dev_id)
{
struct mpc512x_psc_spi *mps = (struct mpc512x_psc_spi *)dev_id;
struct mpc512x_psc_fifo __iomem *fifo = mps->fifo;
/* clear interrupt and wake up the work queue */
if (in_be32(&fifo->txisr) &
in_be32(&fifo->tximr) & MPC512x_PSC_FIFO_EMPTY) {
out_be32(&fifo->txisr, MPC512x_PSC_FIFO_EMPTY);
out_be32(&fifo->tximr, 0);
complete(&mps->done);
return IRQ_HANDLED;
}
return IRQ_NONE;
}
static void mpc512x_spi_cs_control(struct spi_device *spi, bool onoff)
{
gpio_set_value(spi->cs_gpio, onoff);
}
/* bus_num is used only for the case dev->platform_data == NULL */
static int mpc512x_psc_spi_do_probe(struct device *dev, u32 regaddr,
u32 size, unsigned int irq,
s16 bus_num)
{
struct fsl_spi_platform_data *pdata = dev->platform_data;
struct mpc512x_psc_spi *mps;
struct spi_master *master;
int ret;
void *tempp;
master = spi_alloc_master(dev, sizeof *mps);
if (master == NULL)
return -ENOMEM;
dev_set_drvdata(dev, master);
mps = spi_master_get_devdata(master);
mps->irq = irq;
if (pdata == NULL) {
mps->cs_control = mpc512x_spi_cs_control;
mps->sysclk = 0;
master->bus_num = bus_num;
} else {
mps->cs_control = pdata->cs_control;
mps->sysclk = pdata->sysclk;
master->bus_num = pdata->bus_num;
master->num_chipselect = pdata->max_chipselect;
}
master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH | SPI_LSB_FIRST;
master->setup = mpc512x_psc_spi_setup;
master->transfer = mpc512x_psc_spi_transfer;
master->cleanup = mpc512x_psc_spi_cleanup;
master->dev.of_node = dev->of_node;
tempp = ioremap(regaddr, size);
if (!tempp) {
dev_err(dev, "could not ioremap I/O port range\n");
ret = -EFAULT;
goto free_master;
}
mps->psc = tempp;
mps->fifo =
(struct mpc512x_psc_fifo *)(tempp + sizeof(struct mpc52xx_psc));
ret = request_irq(mps->irq, mpc512x_psc_spi_isr, IRQF_SHARED,
"mpc512x-psc-spi", mps);
if (ret)
goto free_master;
ret = mpc512x_psc_spi_port_config(master, mps);
if (ret < 0)
goto free_irq;
spin_lock_init(&mps->lock);
init_completion(&mps->done);
INIT_WORK(&mps->work, mpc512x_psc_spi_work);
INIT_LIST_HEAD(&mps->queue);
mps->workqueue =
create_singlethread_workqueue(dev_name(master->dev.parent));
if (mps->workqueue == NULL) {
ret = -EBUSY;
goto free_irq;
}
ret = spi_register_master(master);
if (ret < 0)
goto unreg_master;
return ret;
unreg_master:
destroy_workqueue(mps->workqueue);
free_irq:
free_irq(mps->irq, mps);
free_master:
if (mps->psc)
iounmap(mps->psc);
spi_master_put(master);
return ret;
}
static int mpc512x_psc_spi_do_remove(struct device *dev)
{
struct spi_master *master = spi_master_get(dev_get_drvdata(dev));
struct mpc512x_psc_spi *mps = spi_master_get_devdata(master);
flush_workqueue(mps->workqueue);
destroy_workqueue(mps->workqueue);
spi_unregister_master(master);
free_irq(mps->irq, mps);
if (mps->psc)
iounmap(mps->psc);
spi_master_put(master);
return 0;
}
static int mpc512x_psc_spi_of_probe(struct platform_device *op)
{
const u32 *regaddr_p;
u64 regaddr64, size64;
s16 id = -1;
regaddr_p = of_get_address(op->dev.of_node, 0, &size64, NULL);
if (!regaddr_p) {
dev_err(&op->dev, "Invalid PSC address\n");
return -EINVAL;
}
regaddr64 = of_translate_address(op->dev.of_node, regaddr_p);
/* get PSC id (0..11, used by port_config) */
id = of_alias_get_id(op->dev.of_node, "spi");
if (id < 0) {
dev_err(&op->dev, "no alias id for %s\n",
op->dev.of_node->full_name);
return id;
}
return mpc512x_psc_spi_do_probe(&op->dev, (u32) regaddr64, (u32) size64,
irq_of_parse_and_map(op->dev.of_node, 0), id);
}
static int mpc512x_psc_spi_of_remove(struct platform_device *op)
{
return mpc512x_psc_spi_do_remove(&op->dev);
}
static struct of_device_id mpc512x_psc_spi_of_match[] = {
{ .compatible = "fsl,mpc5121-psc-spi", },
{},
};
MODULE_DEVICE_TABLE(of, mpc512x_psc_spi_of_match);
static struct platform_driver mpc512x_psc_spi_of_driver = {
.probe = mpc512x_psc_spi_of_probe,
.remove = mpc512x_psc_spi_of_remove,
.driver = {
.name = "mpc512x-psc-spi",
.owner = THIS_MODULE,
.of_match_table = mpc512x_psc_spi_of_match,
},
};
module_platform_driver(mpc512x_psc_spi_of_driver);
MODULE_AUTHOR("John Rigby");
MODULE_DESCRIPTION("MPC512x PSC SPI Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
VigorCM9/vigor_aosp_kernel | drivers/pnp/pnpbios/rsparser.c | 3619 | 17095 | /*
* rsparser.c - parses and encodes pnpbios resource data streams
*/
#include <linux/ctype.h>
#include <linux/pnp.h>
#include <linux/string.h>
#ifdef CONFIG_PCI
#include <linux/pci.h>
#else
inline void pcibios_penalize_isa_irq(int irq, int active)
{
}
#endif /* CONFIG_PCI */
#include "../base.h"
#include "pnpbios.h"
/* standard resource tags */
#define SMALL_TAG_PNPVERNO 0x01
#define SMALL_TAG_LOGDEVID 0x02
#define SMALL_TAG_COMPATDEVID 0x03
#define SMALL_TAG_IRQ 0x04
#define SMALL_TAG_DMA 0x05
#define SMALL_TAG_STARTDEP 0x06
#define SMALL_TAG_ENDDEP 0x07
#define SMALL_TAG_PORT 0x08
#define SMALL_TAG_FIXEDPORT 0x09
#define SMALL_TAG_VENDOR 0x0e
#define SMALL_TAG_END 0x0f
#define LARGE_TAG 0x80
#define LARGE_TAG_MEM 0x81
#define LARGE_TAG_ANSISTR 0x82
#define LARGE_TAG_UNICODESTR 0x83
#define LARGE_TAG_VENDOR 0x84
#define LARGE_TAG_MEM32 0x85
#define LARGE_TAG_FIXEDMEM32 0x86
/*
* Resource Data Stream Format:
*
* Allocated Resources (required)
* end tag ->
* Resource Configuration Options (optional)
* end tag ->
* Compitable Device IDs (optional)
* final end tag ->
*/
/*
* Allocated Resources
*/
static void pnpbios_parse_allocated_ioresource(struct pnp_dev *dev,
int start, int len)
{
int flags = 0;
int end = start + len - 1;
if (len <= 0 || end >= 0x10003)
flags |= IORESOURCE_DISABLED;
pnp_add_io_resource(dev, start, end, flags);
}
static void pnpbios_parse_allocated_memresource(struct pnp_dev *dev,
int start, int len)
{
int flags = 0;
int end = start + len - 1;
if (len <= 0)
flags |= IORESOURCE_DISABLED;
pnp_add_mem_resource(dev, start, end, flags);
}
static unsigned char *pnpbios_parse_allocated_resource_data(struct pnp_dev *dev,
unsigned char *p,
unsigned char *end)
{
unsigned int len, tag;
int io, size, mask, i, flags;
if (!p)
return NULL;
pnp_dbg(&dev->dev, "parse allocated resources\n");
pnp_init_resources(dev);
while ((char *)p < (char *)end) {
/* determine the type of tag */
if (p[0] & LARGE_TAG) { /* large tag */
len = (p[2] << 8) | p[1];
tag = p[0];
} else { /* small tag */
len = p[0] & 0x07;
tag = ((p[0] >> 3) & 0x0f);
}
switch (tag) {
case LARGE_TAG_MEM:
if (len != 9)
goto len_err;
io = *(short *)&p[4];
size = *(short *)&p[10];
pnpbios_parse_allocated_memresource(dev, io, size);
break;
case LARGE_TAG_ANSISTR:
/* ignore this for now */
break;
case LARGE_TAG_VENDOR:
/* do nothing */
break;
case LARGE_TAG_MEM32:
if (len != 17)
goto len_err;
io = *(int *)&p[4];
size = *(int *)&p[16];
pnpbios_parse_allocated_memresource(dev, io, size);
break;
case LARGE_TAG_FIXEDMEM32:
if (len != 9)
goto len_err;
io = *(int *)&p[4];
size = *(int *)&p[8];
pnpbios_parse_allocated_memresource(dev, io, size);
break;
case SMALL_TAG_IRQ:
if (len < 2 || len > 3)
goto len_err;
flags = 0;
io = -1;
mask = p[1] + p[2] * 256;
for (i = 0; i < 16; i++, mask = mask >> 1)
if (mask & 0x01)
io = i;
if (io != -1)
pcibios_penalize_isa_irq(io, 1);
else
flags = IORESOURCE_DISABLED;
pnp_add_irq_resource(dev, io, flags);
break;
case SMALL_TAG_DMA:
if (len != 2)
goto len_err;
flags = 0;
io = -1;
mask = p[1];
for (i = 0; i < 8; i++, mask = mask >> 1)
if (mask & 0x01)
io = i;
if (io == -1)
flags = IORESOURCE_DISABLED;
pnp_add_dma_resource(dev, io, flags);
break;
case SMALL_TAG_PORT:
if (len != 7)
goto len_err;
io = p[2] + p[3] * 256;
size = p[7];
pnpbios_parse_allocated_ioresource(dev, io, size);
break;
case SMALL_TAG_VENDOR:
/* do nothing */
break;
case SMALL_TAG_FIXEDPORT:
if (len != 3)
goto len_err;
io = p[1] + p[2] * 256;
size = p[3];
pnpbios_parse_allocated_ioresource(dev, io, size);
break;
case SMALL_TAG_END:
p = p + 2;
return (unsigned char *)p;
break;
default: /* an unknown tag */
len_err:
dev_err(&dev->dev, "unknown tag %#x length %d\n",
tag, len);
break;
}
/* continue to the next tag */
if (p[0] & LARGE_TAG)
p += len + 3;
else
p += len + 1;
}
dev_err(&dev->dev, "no end tag in resource structure\n");
return NULL;
}
/*
* Resource Configuration Options
*/
static __init void pnpbios_parse_mem_option(struct pnp_dev *dev,
unsigned char *p, int size,
unsigned int option_flags)
{
resource_size_t min, max, align, len;
unsigned char flags;
min = ((p[5] << 8) | p[4]) << 8;
max = ((p[7] << 8) | p[6]) << 8;
align = (p[9] << 8) | p[8];
len = ((p[11] << 8) | p[10]) << 8;
flags = p[3];
pnp_register_mem_resource(dev, option_flags, min, max, align, len,
flags);
}
static __init void pnpbios_parse_mem32_option(struct pnp_dev *dev,
unsigned char *p, int size,
unsigned int option_flags)
{
resource_size_t min, max, align, len;
unsigned char flags;
min = (p[7] << 24) | (p[6] << 16) | (p[5] << 8) | p[4];
max = (p[11] << 24) | (p[10] << 16) | (p[9] << 8) | p[8];
align = (p[15] << 24) | (p[14] << 16) | (p[13] << 8) | p[12];
len = (p[19] << 24) | (p[18] << 16) | (p[17] << 8) | p[16];
flags = p[3];
pnp_register_mem_resource(dev, option_flags, min, max, align, len,
flags);
}
static __init void pnpbios_parse_fixed_mem32_option(struct pnp_dev *dev,
unsigned char *p, int size,
unsigned int option_flags)
{
resource_size_t base, len;
unsigned char flags;
base = (p[7] << 24) | (p[6] << 16) | (p[5] << 8) | p[4];
len = (p[11] << 24) | (p[10] << 16) | (p[9] << 8) | p[8];
flags = p[3];
pnp_register_mem_resource(dev, option_flags, base, base, 0, len, flags);
}
static __init void pnpbios_parse_irq_option(struct pnp_dev *dev,
unsigned char *p, int size,
unsigned int option_flags)
{
unsigned long bits;
pnp_irq_mask_t map;
unsigned char flags = IORESOURCE_IRQ_HIGHEDGE;
bits = (p[2] << 8) | p[1];
bitmap_zero(map.bits, PNP_IRQ_NR);
bitmap_copy(map.bits, &bits, 16);
if (size > 2)
flags = p[3];
pnp_register_irq_resource(dev, option_flags, &map, flags);
}
static __init void pnpbios_parse_dma_option(struct pnp_dev *dev,
unsigned char *p, int size,
unsigned int option_flags)
{
pnp_register_dma_resource(dev, option_flags, p[1], p[2]);
}
static __init void pnpbios_parse_port_option(struct pnp_dev *dev,
unsigned char *p, int size,
unsigned int option_flags)
{
resource_size_t min, max, align, len;
unsigned char flags;
min = (p[3] << 8) | p[2];
max = (p[5] << 8) | p[4];
align = p[6];
len = p[7];
flags = p[1] ? IORESOURCE_IO_16BIT_ADDR : 0;
pnp_register_port_resource(dev, option_flags, min, max, align, len,
flags);
}
static __init void pnpbios_parse_fixed_port_option(struct pnp_dev *dev,
unsigned char *p, int size,
unsigned int option_flags)
{
resource_size_t base, len;
base = (p[2] << 8) | p[1];
len = p[3];
pnp_register_port_resource(dev, option_flags, base, base, 0, len,
IORESOURCE_IO_FIXED);
}
static __init unsigned char *
pnpbios_parse_resource_option_data(unsigned char *p, unsigned char *end,
struct pnp_dev *dev)
{
unsigned int len, tag;
int priority;
unsigned int option_flags;
if (!p)
return NULL;
pnp_dbg(&dev->dev, "parse resource options\n");
option_flags = 0;
while ((char *)p < (char *)end) {
/* determine the type of tag */
if (p[0] & LARGE_TAG) { /* large tag */
len = (p[2] << 8) | p[1];
tag = p[0];
} else { /* small tag */
len = p[0] & 0x07;
tag = ((p[0] >> 3) & 0x0f);
}
switch (tag) {
case LARGE_TAG_MEM:
if (len != 9)
goto len_err;
pnpbios_parse_mem_option(dev, p, len, option_flags);
break;
case LARGE_TAG_MEM32:
if (len != 17)
goto len_err;
pnpbios_parse_mem32_option(dev, p, len, option_flags);
break;
case LARGE_TAG_FIXEDMEM32:
if (len != 9)
goto len_err;
pnpbios_parse_fixed_mem32_option(dev, p, len,
option_flags);
break;
case SMALL_TAG_IRQ:
if (len < 2 || len > 3)
goto len_err;
pnpbios_parse_irq_option(dev, p, len, option_flags);
break;
case SMALL_TAG_DMA:
if (len != 2)
goto len_err;
pnpbios_parse_dma_option(dev, p, len, option_flags);
break;
case SMALL_TAG_PORT:
if (len != 7)
goto len_err;
pnpbios_parse_port_option(dev, p, len, option_flags);
break;
case SMALL_TAG_VENDOR:
/* do nothing */
break;
case SMALL_TAG_FIXEDPORT:
if (len != 3)
goto len_err;
pnpbios_parse_fixed_port_option(dev, p, len,
option_flags);
break;
case SMALL_TAG_STARTDEP:
if (len > 1)
goto len_err;
priority = PNP_RES_PRIORITY_ACCEPTABLE;
if (len > 0)
priority = p[1];
option_flags = pnp_new_dependent_set(dev, priority);
break;
case SMALL_TAG_ENDDEP:
if (len != 0)
goto len_err;
option_flags = 0;
break;
case SMALL_TAG_END:
return p + 2;
default: /* an unknown tag */
len_err:
dev_err(&dev->dev, "unknown tag %#x length %d\n",
tag, len);
break;
}
/* continue to the next tag */
if (p[0] & LARGE_TAG)
p += len + 3;
else
p += len + 1;
}
dev_err(&dev->dev, "no end tag in resource structure\n");
return NULL;
}
/*
* Compatible Device IDs
*/
static unsigned char *pnpbios_parse_compatible_ids(unsigned char *p,
unsigned char *end,
struct pnp_dev *dev)
{
int len, tag;
u32 eisa_id;
char id[8];
struct pnp_id *dev_id;
if (!p)
return NULL;
while ((char *)p < (char *)end) {
/* determine the type of tag */
if (p[0] & LARGE_TAG) { /* large tag */
len = (p[2] << 8) | p[1];
tag = p[0];
} else { /* small tag */
len = p[0] & 0x07;
tag = ((p[0] >> 3) & 0x0f);
}
switch (tag) {
case LARGE_TAG_ANSISTR:
strncpy(dev->name, p + 3,
len >= PNP_NAME_LEN ? PNP_NAME_LEN - 2 : len);
dev->name[len >=
PNP_NAME_LEN ? PNP_NAME_LEN - 1 : len] = '\0';
break;
case SMALL_TAG_COMPATDEVID: /* compatible ID */
if (len != 4)
goto len_err;
eisa_id = p[1] | p[2] << 8 | p[3] << 16 | p[4] << 24;
pnp_eisa_id_to_string(eisa_id & PNP_EISA_ID_MASK, id);
dev_id = pnp_add_id(dev, id);
if (!dev_id)
return NULL;
break;
case SMALL_TAG_END:
p = p + 2;
return (unsigned char *)p;
break;
default: /* an unknown tag */
len_err:
dev_err(&dev->dev, "unknown tag %#x length %d\n",
tag, len);
break;
}
/* continue to the next tag */
if (p[0] & LARGE_TAG)
p += len + 3;
else
p += len + 1;
}
dev_err(&dev->dev, "no end tag in resource structure\n");
return NULL;
}
/*
* Allocated Resource Encoding
*/
static void pnpbios_encode_mem(struct pnp_dev *dev, unsigned char *p,
struct resource *res)
{
unsigned long base;
unsigned long len;
if (pnp_resource_enabled(res)) {
base = res->start;
len = res->end - res->start + 1;
} else {
base = 0;
len = 0;
}
p[4] = (base >> 8) & 0xff;
p[5] = ((base >> 8) >> 8) & 0xff;
p[6] = (base >> 8) & 0xff;
p[7] = ((base >> 8) >> 8) & 0xff;
p[10] = (len >> 8) & 0xff;
p[11] = ((len >> 8) >> 8) & 0xff;
pnp_dbg(&dev->dev, " encode mem %#lx-%#lx\n", base, base + len - 1);
}
static void pnpbios_encode_mem32(struct pnp_dev *dev, unsigned char *p,
struct resource *res)
{
unsigned long base;
unsigned long len;
if (pnp_resource_enabled(res)) {
base = res->start;
len = res->end - res->start + 1;
} else {
base = 0;
len = 0;
}
p[4] = base & 0xff;
p[5] = (base >> 8) & 0xff;
p[6] = (base >> 16) & 0xff;
p[7] = (base >> 24) & 0xff;
p[8] = base & 0xff;
p[9] = (base >> 8) & 0xff;
p[10] = (base >> 16) & 0xff;
p[11] = (base >> 24) & 0xff;
p[16] = len & 0xff;
p[17] = (len >> 8) & 0xff;
p[18] = (len >> 16) & 0xff;
p[19] = (len >> 24) & 0xff;
pnp_dbg(&dev->dev, " encode mem32 %#lx-%#lx\n", base, base + len - 1);
}
static void pnpbios_encode_fixed_mem32(struct pnp_dev *dev, unsigned char *p,
struct resource *res)
{
unsigned long base;
unsigned long len;
if (pnp_resource_enabled(res)) {
base = res->start;
len = res->end - res->start + 1;
} else {
base = 0;
len = 0;
}
p[4] = base & 0xff;
p[5] = (base >> 8) & 0xff;
p[6] = (base >> 16) & 0xff;
p[7] = (base >> 24) & 0xff;
p[8] = len & 0xff;
p[9] = (len >> 8) & 0xff;
p[10] = (len >> 16) & 0xff;
p[11] = (len >> 24) & 0xff;
pnp_dbg(&dev->dev, " encode fixed_mem32 %#lx-%#lx\n", base,
base + len - 1);
}
static void pnpbios_encode_irq(struct pnp_dev *dev, unsigned char *p,
struct resource *res)
{
unsigned long map;
if (pnp_resource_enabled(res))
map = 1 << res->start;
else
map = 0;
p[1] = map & 0xff;
p[2] = (map >> 8) & 0xff;
pnp_dbg(&dev->dev, " encode irq mask %#lx\n", map);
}
static void pnpbios_encode_dma(struct pnp_dev *dev, unsigned char *p,
struct resource *res)
{
unsigned long map;
if (pnp_resource_enabled(res))
map = 1 << res->start;
else
map = 0;
p[1] = map & 0xff;
pnp_dbg(&dev->dev, " encode dma mask %#lx\n", map);
}
static void pnpbios_encode_port(struct pnp_dev *dev, unsigned char *p,
struct resource *res)
{
unsigned long base;
unsigned long len;
if (pnp_resource_enabled(res)) {
base = res->start;
len = res->end - res->start + 1;
} else {
base = 0;
len = 0;
}
p[2] = base & 0xff;
p[3] = (base >> 8) & 0xff;
p[4] = base & 0xff;
p[5] = (base >> 8) & 0xff;
p[7] = len & 0xff;
pnp_dbg(&dev->dev, " encode io %#lx-%#lx\n", base, base + len - 1);
}
static void pnpbios_encode_fixed_port(struct pnp_dev *dev, unsigned char *p,
struct resource *res)
{
unsigned long base = res->start;
unsigned long len = res->end - res->start + 1;
if (pnp_resource_enabled(res)) {
base = res->start;
len = res->end - res->start + 1;
} else {
base = 0;
len = 0;
}
p[1] = base & 0xff;
p[2] = (base >> 8) & 0xff;
p[3] = len & 0xff;
pnp_dbg(&dev->dev, " encode fixed_io %#lx-%#lx\n", base,
base + len - 1);
}
static unsigned char *pnpbios_encode_allocated_resource_data(struct pnp_dev
*dev,
unsigned char *p,
unsigned char *end)
{
unsigned int len, tag;
int port = 0, irq = 0, dma = 0, mem = 0;
if (!p)
return NULL;
while ((char *)p < (char *)end) {
/* determine the type of tag */
if (p[0] & LARGE_TAG) { /* large tag */
len = (p[2] << 8) | p[1];
tag = p[0];
} else { /* small tag */
len = p[0] & 0x07;
tag = ((p[0] >> 3) & 0x0f);
}
switch (tag) {
case LARGE_TAG_MEM:
if (len != 9)
goto len_err;
pnpbios_encode_mem(dev, p,
pnp_get_resource(dev, IORESOURCE_MEM, mem));
mem++;
break;
case LARGE_TAG_MEM32:
if (len != 17)
goto len_err;
pnpbios_encode_mem32(dev, p,
pnp_get_resource(dev, IORESOURCE_MEM, mem));
mem++;
break;
case LARGE_TAG_FIXEDMEM32:
if (len != 9)
goto len_err;
pnpbios_encode_fixed_mem32(dev, p,
pnp_get_resource(dev, IORESOURCE_MEM, mem));
mem++;
break;
case SMALL_TAG_IRQ:
if (len < 2 || len > 3)
goto len_err;
pnpbios_encode_irq(dev, p,
pnp_get_resource(dev, IORESOURCE_IRQ, irq));
irq++;
break;
case SMALL_TAG_DMA:
if (len != 2)
goto len_err;
pnpbios_encode_dma(dev, p,
pnp_get_resource(dev, IORESOURCE_DMA, dma));
dma++;
break;
case SMALL_TAG_PORT:
if (len != 7)
goto len_err;
pnpbios_encode_port(dev, p,
pnp_get_resource(dev, IORESOURCE_IO, port));
port++;
break;
case SMALL_TAG_VENDOR:
/* do nothing */
break;
case SMALL_TAG_FIXEDPORT:
if (len != 3)
goto len_err;
pnpbios_encode_fixed_port(dev, p,
pnp_get_resource(dev, IORESOURCE_IO, port));
port++;
break;
case SMALL_TAG_END:
p = p + 2;
return (unsigned char *)p;
break;
default: /* an unknown tag */
len_err:
dev_err(&dev->dev, "unknown tag %#x length %d\n",
tag, len);
break;
}
/* continue to the next tag */
if (p[0] & LARGE_TAG)
p += len + 3;
else
p += len + 1;
}
dev_err(&dev->dev, "no end tag in resource structure\n");
return NULL;
}
/*
* Core Parsing Functions
*/
int __init pnpbios_parse_data_stream(struct pnp_dev *dev,
struct pnp_bios_node *node)
{
unsigned char *p = (char *)node->data;
unsigned char *end = (char *)(node->data + node->size);
p = pnpbios_parse_allocated_resource_data(dev, p, end);
if (!p)
return -EIO;
p = pnpbios_parse_resource_option_data(p, end, dev);
if (!p)
return -EIO;
p = pnpbios_parse_compatible_ids(p, end, dev);
if (!p)
return -EIO;
return 0;
}
int pnpbios_read_resources_from_node(struct pnp_dev *dev,
struct pnp_bios_node *node)
{
unsigned char *p = (char *)node->data;
unsigned char *end = (char *)(node->data + node->size);
p = pnpbios_parse_allocated_resource_data(dev, p, end);
if (!p)
return -EIO;
return 0;
}
int pnpbios_write_resources_to_node(struct pnp_dev *dev,
struct pnp_bios_node *node)
{
unsigned char *p = (char *)node->data;
unsigned char *end = (char *)(node->data + node->size);
p = pnpbios_encode_allocated_resource_data(dev, p, end);
if (!p)
return -EIO;
return 0;
}
| gpl-2.0 |
partner-seco/linux_SBC | drivers/md/dm-path-selector.c | 4643 | 2473 | /*
* Copyright (C) 2003 Sistina Software.
* Copyright (C) 2004 Red Hat, Inc. All rights reserved.
*
* Module Author: Heinz Mauelshagen
*
* This file is released under the GPL.
*
* Path selector registration.
*/
#include <linux/device-mapper.h>
#include "dm-path-selector.h"
#include <linux/slab.h>
struct ps_internal {
struct path_selector_type pst;
struct list_head list;
};
#define pst_to_psi(__pst) container_of((__pst), struct ps_internal, pst)
static LIST_HEAD(_path_selectors);
static DECLARE_RWSEM(_ps_lock);
static struct ps_internal *__find_path_selector_type(const char *name)
{
struct ps_internal *psi;
list_for_each_entry(psi, &_path_selectors, list) {
if (!strcmp(name, psi->pst.name))
return psi;
}
return NULL;
}
static struct ps_internal *get_path_selector(const char *name)
{
struct ps_internal *psi;
down_read(&_ps_lock);
psi = __find_path_selector_type(name);
if (psi && !try_module_get(psi->pst.module))
psi = NULL;
up_read(&_ps_lock);
return psi;
}
struct path_selector_type *dm_get_path_selector(const char *name)
{
struct ps_internal *psi;
if (!name)
return NULL;
psi = get_path_selector(name);
if (!psi) {
request_module("dm-%s", name);
psi = get_path_selector(name);
}
return psi ? &psi->pst : NULL;
}
void dm_put_path_selector(struct path_selector_type *pst)
{
struct ps_internal *psi;
if (!pst)
return;
down_read(&_ps_lock);
psi = __find_path_selector_type(pst->name);
if (!psi)
goto out;
module_put(psi->pst.module);
out:
up_read(&_ps_lock);
}
static struct ps_internal *_alloc_path_selector(struct path_selector_type *pst)
{
struct ps_internal *psi = kzalloc(sizeof(*psi), GFP_KERNEL);
if (psi)
psi->pst = *pst;
return psi;
}
int dm_register_path_selector(struct path_selector_type *pst)
{
int r = 0;
struct ps_internal *psi = _alloc_path_selector(pst);
if (!psi)
return -ENOMEM;
down_write(&_ps_lock);
if (__find_path_selector_type(pst->name)) {
kfree(psi);
r = -EEXIST;
} else
list_add(&psi->list, &_path_selectors);
up_write(&_ps_lock);
return r;
}
int dm_unregister_path_selector(struct path_selector_type *pst)
{
struct ps_internal *psi;
down_write(&_ps_lock);
psi = __find_path_selector_type(pst->name);
if (!psi) {
up_write(&_ps_lock);
return -EINVAL;
}
list_del(&psi->list);
up_write(&_ps_lock);
kfree(psi);
return 0;
}
EXPORT_SYMBOL_GPL(dm_register_path_selector);
EXPORT_SYMBOL_GPL(dm_unregister_path_selector);
| gpl-2.0 |
crpalmer/android_kernel_motorola_msm8974 | drivers/media/video/gspca/mars.c | 4899 | 12647 | /*
* Mars-Semi MR97311A library
* Copyright (C) 2005 <bradlch@hotmail.com>
*
* 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
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define MODULE_NAME "mars"
#include "gspca.h"
#include "jpeg.h"
MODULE_AUTHOR("Michel Xhaard <mxhaard@users.sourceforge.net>");
MODULE_DESCRIPTION("GSPCA/Mars USB Camera Driver");
MODULE_LICENSE("GPL");
/* controls */
enum e_ctrl {
BRIGHTNESS,
COLORS,
GAMMA,
SHARPNESS,
ILLUM_TOP,
ILLUM_BOT,
NCTRLS /* number of controls */
};
/* specific webcam descriptor */
struct sd {
struct gspca_dev gspca_dev; /* !! must be the first item */
struct gspca_ctrl ctrls[NCTRLS];
u8 quality;
#define QUALITY_MIN 40
#define QUALITY_MAX 70
#define QUALITY_DEF 50
u8 jpeg_hdr[JPEG_HDR_SZ];
};
/* V4L2 controls supported by the driver */
static void setbrightness(struct gspca_dev *gspca_dev);
static void setcolors(struct gspca_dev *gspca_dev);
static void setgamma(struct gspca_dev *gspca_dev);
static void setsharpness(struct gspca_dev *gspca_dev);
static int sd_setilluminator1(struct gspca_dev *gspca_dev, __s32 val);
static int sd_setilluminator2(struct gspca_dev *gspca_dev, __s32 val);
static const struct ctrl sd_ctrls[NCTRLS] = {
[BRIGHTNESS] = {
{
.id = V4L2_CID_BRIGHTNESS,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Brightness",
.minimum = 0,
.maximum = 30,
.step = 1,
.default_value = 15,
},
.set_control = setbrightness
},
[COLORS] = {
{
.id = V4L2_CID_SATURATION,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Color",
.minimum = 1,
.maximum = 255,
.step = 1,
.default_value = 200,
},
.set_control = setcolors
},
[GAMMA] = {
{
.id = V4L2_CID_GAMMA,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Gamma",
.minimum = 0,
.maximum = 3,
.step = 1,
.default_value = 1,
},
.set_control = setgamma
},
[SHARPNESS] = {
{
.id = V4L2_CID_SHARPNESS,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Sharpness",
.minimum = 0,
.maximum = 2,
.step = 1,
.default_value = 1,
},
.set_control = setsharpness
},
[ILLUM_TOP] = {
{
.id = V4L2_CID_ILLUMINATORS_1,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Top illuminator",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0,
.flags = V4L2_CTRL_FLAG_UPDATE,
},
.set = sd_setilluminator1
},
[ILLUM_BOT] = {
{
.id = V4L2_CID_ILLUMINATORS_2,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Bottom illuminator",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0,
.flags = V4L2_CTRL_FLAG_UPDATE,
},
.set = sd_setilluminator2
},
};
static const struct v4l2_pix_format vga_mode[] = {
{320, 240, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 2},
{640, 480, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 1},
};
static const __u8 mi_data[0x20] = {
/* 01 02 03 04 05 06 07 08 */
0x48, 0x22, 0x01, 0x47, 0x10, 0x00, 0x00, 0x00,
/* 09 0a 0b 0c 0d 0e 0f 10 */
0x00, 0x01, 0x30, 0x01, 0x30, 0x01, 0x30, 0x01,
/* 11 12 13 14 15 16 17 18 */
0x30, 0x00, 0x04, 0x00, 0x06, 0x01, 0xe2, 0x02,
/* 19 1a 1b 1c 1d 1e 1f 20 */
0x82, 0x00, 0x20, 0x17, 0x80, 0x08, 0x0c, 0x00
};
/* write <len> bytes from gspca_dev->usb_buf */
static void reg_w(struct gspca_dev *gspca_dev,
int len)
{
int alen, ret;
if (gspca_dev->usb_err < 0)
return;
ret = usb_bulk_msg(gspca_dev->dev,
usb_sndbulkpipe(gspca_dev->dev, 4),
gspca_dev->usb_buf,
len,
&alen,
500); /* timeout in milliseconds */
if (ret < 0) {
pr_err("reg write [%02x] error %d\n",
gspca_dev->usb_buf[0], ret);
gspca_dev->usb_err = ret;
}
}
static void mi_w(struct gspca_dev *gspca_dev,
u8 addr,
u8 value)
{
gspca_dev->usb_buf[0] = 0x1f;
gspca_dev->usb_buf[1] = 0; /* control byte */
gspca_dev->usb_buf[2] = addr;
gspca_dev->usb_buf[3] = value;
reg_w(gspca_dev, 4);
}
static void setbrightness(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
gspca_dev->usb_buf[0] = 0x61;
gspca_dev->usb_buf[1] = sd->ctrls[BRIGHTNESS].val;
reg_w(gspca_dev, 2);
}
static void setcolors(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
s16 val;
val = sd->ctrls[COLORS].val;
gspca_dev->usb_buf[0] = 0x5f;
gspca_dev->usb_buf[1] = val << 3;
gspca_dev->usb_buf[2] = ((val >> 2) & 0xf8) | 0x04;
reg_w(gspca_dev, 3);
}
static void setgamma(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
gspca_dev->usb_buf[0] = 0x06;
gspca_dev->usb_buf[1] = sd->ctrls[GAMMA].val * 0x40;
reg_w(gspca_dev, 2);
}
static void setsharpness(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
gspca_dev->usb_buf[0] = 0x67;
gspca_dev->usb_buf[1] = sd->ctrls[SHARPNESS].val * 4 + 3;
reg_w(gspca_dev, 2);
}
static void setilluminators(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
gspca_dev->usb_buf[0] = 0x22;
if (sd->ctrls[ILLUM_TOP].val)
gspca_dev->usb_buf[1] = 0x76;
else if (sd->ctrls[ILLUM_BOT].val)
gspca_dev->usb_buf[1] = 0x7a;
else
gspca_dev->usb_buf[1] = 0x7e;
reg_w(gspca_dev, 2);
}
/* this function is called at probe time */
static int sd_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id)
{
struct sd *sd = (struct sd *) gspca_dev;
struct cam *cam;
cam = &gspca_dev->cam;
cam->cam_mode = vga_mode;
cam->nmodes = ARRAY_SIZE(vga_mode);
cam->ctrls = sd->ctrls;
sd->quality = QUALITY_DEF;
return 0;
}
/* this function is called at probe and resume time */
static int sd_init(struct gspca_dev *gspca_dev)
{
gspca_dev->ctrl_inac = (1 << ILLUM_TOP) | (1 << ILLUM_BOT);
return 0;
}
static int sd_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 *data;
int i;
/* create the JPEG header */
jpeg_define(sd->jpeg_hdr, gspca_dev->height, gspca_dev->width,
0x21); /* JPEG 422 */
jpeg_set_qual(sd->jpeg_hdr, sd->quality);
data = gspca_dev->usb_buf;
data[0] = 0x01; /* address */
data[1] = 0x01;
reg_w(gspca_dev, 2);
/*
Initialize the MR97113 chip register
*/
data[0] = 0x00; /* address */
data[1] = 0x0c | 0x01; /* reg 0 */
data[2] = 0x01; /* reg 1 */
data[3] = gspca_dev->width / 8; /* h_size , reg 2 */
data[4] = gspca_dev->height / 8; /* v_size , reg 3 */
data[5] = 0x30; /* reg 4, MI, PAS5101 :
* 0x30 for 24mhz , 0x28 for 12mhz */
data[6] = 0x02; /* reg 5, H start - was 0x04 */
data[7] = sd->ctrls[GAMMA].val * 0x40; /* reg 0x06: gamma */
data[8] = 0x01; /* reg 7, V start - was 0x03 */
/* if (h_size == 320 ) */
/* data[9]= 0x56; * reg 8, 24MHz, 2:1 scale down */
/* else */
data[9] = 0x52; /* reg 8, 24MHz, no scale down */
/*jfm: from win trace*/
data[10] = 0x18;
reg_w(gspca_dev, 11);
data[0] = 0x23; /* address */
data[1] = 0x09; /* reg 35, append frame header */
reg_w(gspca_dev, 2);
data[0] = 0x3c; /* address */
/* if (gspca_dev->width == 1280) */
/* data[1] = 200; * reg 60, pc-cam frame size
* (unit: 4KB) 800KB */
/* else */
data[1] = 50; /* 50 reg 60, pc-cam frame size
* (unit: 4KB) 200KB */
reg_w(gspca_dev, 2);
/* auto dark-gain */
data[0] = 0x5e; /* address */
data[1] = 0; /* reg 94, Y Gain (auto) */
/*jfm: from win trace*/
/* reg 0x5f/0x60 (LE) = saturation */
/* h (60): xxxx x100
* l (5f): xxxx x000 */
data[2] = sd->ctrls[COLORS].val << 3;
data[3] = ((sd->ctrls[COLORS].val >> 2) & 0xf8) | 0x04;
data[4] = sd->ctrls[BRIGHTNESS].val; /* reg 0x61 = brightness */
data[5] = 0x00;
reg_w(gspca_dev, 6);
data[0] = 0x67;
/*jfm: from win trace*/
data[1] = sd->ctrls[SHARPNESS].val * 4 + 3;
data[2] = 0x14;
reg_w(gspca_dev, 3);
data[0] = 0x69;
data[1] = 0x2f;
data[2] = 0x28;
data[3] = 0x42;
reg_w(gspca_dev, 4);
data[0] = 0x63;
data[1] = 0x07;
reg_w(gspca_dev, 2);
/*jfm: win trace - many writes here to reg 0x64*/
/* initialize the MI sensor */
for (i = 0; i < sizeof mi_data; i++)
mi_w(gspca_dev, i + 1, mi_data[i]);
data[0] = 0x00;
data[1] = 0x4d; /* ISOC transferring enable... */
reg_w(gspca_dev, 2);
gspca_dev->ctrl_inac = 0; /* activate the illuminator controls */
return gspca_dev->usb_err;
}
static void sd_stopN(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
gspca_dev->ctrl_inac = (1 << ILLUM_TOP) | (1 << ILLUM_BOT);
if (sd->ctrls[ILLUM_TOP].val || sd->ctrls[ILLUM_BOT].val) {
sd->ctrls[ILLUM_TOP].val = 0;
sd->ctrls[ILLUM_BOT].val = 0;
setilluminators(gspca_dev);
msleep(20);
}
gspca_dev->usb_buf[0] = 1;
gspca_dev->usb_buf[1] = 0;
reg_w(gspca_dev, 2);
}
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;
int p;
if (len < 6) {
/* gspca_dev->last_packet_type = DISCARD_PACKET; */
return;
}
for (p = 0; p < len - 6; p++) {
if (data[0 + p] == 0xff
&& data[1 + p] == 0xff
&& data[2 + p] == 0x00
&& data[3 + p] == 0xff
&& data[4 + p] == 0x96) {
if (data[5 + p] == 0x64
|| data[5 + p] == 0x65
|| data[5 + p] == 0x66
|| data[5 + p] == 0x67) {
PDEBUG(D_PACK, "sof offset: %d len: %d",
p, len);
gspca_frame_add(gspca_dev, LAST_PACKET,
data, p);
/* put the JPEG header */
gspca_frame_add(gspca_dev, FIRST_PACKET,
sd->jpeg_hdr, JPEG_HDR_SZ);
data += p + 16;
len -= p + 16;
break;
}
}
}
gspca_frame_add(gspca_dev, INTER_PACKET, data, len);
}
static int sd_setilluminator1(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
/* only one illuminator may be on */
sd->ctrls[ILLUM_TOP].val = val;
if (val)
sd->ctrls[ILLUM_BOT].val = 0;
setilluminators(gspca_dev);
return gspca_dev->usb_err;
}
static int sd_setilluminator2(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
/* only one illuminator may be on */
sd->ctrls[ILLUM_BOT].val = val;
if (val)
sd->ctrls[ILLUM_TOP].val = 0;
setilluminators(gspca_dev);
return gspca_dev->usb_err;
}
static int sd_set_jcomp(struct gspca_dev *gspca_dev,
struct v4l2_jpegcompression *jcomp)
{
struct sd *sd = (struct sd *) gspca_dev;
if (jcomp->quality < QUALITY_MIN)
sd->quality = QUALITY_MIN;
else if (jcomp->quality > QUALITY_MAX)
sd->quality = QUALITY_MAX;
else
sd->quality = jcomp->quality;
if (gspca_dev->streaming)
jpeg_set_qual(sd->jpeg_hdr, sd->quality);
return 0;
}
static int sd_get_jcomp(struct gspca_dev *gspca_dev,
struct v4l2_jpegcompression *jcomp)
{
struct sd *sd = (struct sd *) gspca_dev;
memset(jcomp, 0, sizeof *jcomp);
jcomp->quality = sd->quality;
jcomp->jpeg_markers = V4L2_JPEG_MARKER_DHT
| V4L2_JPEG_MARKER_DQT;
return 0;
}
/* sub-driver description */
static const struct sd_desc sd_desc = {
.name = MODULE_NAME,
.ctrls = sd_ctrls,
.nctrls = NCTRLS,
.config = sd_config,
.init = sd_init,
.start = sd_start,
.stopN = sd_stopN,
.pkt_scan = sd_pkt_scan,
.get_jcomp = sd_get_jcomp,
.set_jcomp = sd_set_jcomp,
};
/* -- module initialisation -- */
static const struct usb_device_id device_table[] = {
{USB_DEVICE(0x093a, 0x050f)},
{}
};
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,
#endif
};
module_usb_driver(sd_driver);
| gpl-2.0 |
alexpotter1/QuantumKernel-hammerhead | sound/pci/lx6464es/lx6464es.c | 4899 | 28516 | /* -*- linux-c -*- *
*
* ALSA driver for the digigram lx6464es interface
*
* Copyright (c) 2008, 2009 Tim Blechmann <tim@klingt.org>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <sound/initval.h>
#include <sound/control.h>
#include <sound/info.h>
#include "lx6464es.h"
MODULE_AUTHOR("Tim Blechmann");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("digigram lx6464es");
MODULE_SUPPORTED_DEVICE("{digigram lx6464es{}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for Digigram LX6464ES interface.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for Digigram LX6464ES interface.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable/disable specific Digigram LX6464ES soundcards.");
static const char card_name[] = "LX6464ES";
#define PCI_DEVICE_ID_PLX_LX6464ES PCI_DEVICE_ID_PLX_9056
static DEFINE_PCI_DEVICE_TABLE(snd_lx6464es_ids) = {
{ PCI_DEVICE(PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_LX6464ES),
.subvendor = PCI_VENDOR_ID_DIGIGRAM,
.subdevice = PCI_SUBDEVICE_ID_DIGIGRAM_LX6464ES_SERIAL_SUBSYSTEM
}, /* LX6464ES */
{ PCI_DEVICE(PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_LX6464ES),
.subvendor = PCI_VENDOR_ID_DIGIGRAM,
.subdevice = PCI_SUBDEVICE_ID_DIGIGRAM_LX6464ES_CAE_SERIAL_SUBSYSTEM
}, /* LX6464ES-CAE */
{ 0, },
};
MODULE_DEVICE_TABLE(pci, snd_lx6464es_ids);
/* PGO pour USERo dans le registre pci_0x06/loc_0xEC */
#define CHIPSC_RESET_XILINX (1L<<16)
/* alsa callbacks */
static struct snd_pcm_hardware lx_caps = {
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_SYNC_START),
.formats = (SNDRV_PCM_FMTBIT_S16_LE |
SNDRV_PCM_FMTBIT_S16_BE |
SNDRV_PCM_FMTBIT_S24_3LE |
SNDRV_PCM_FMTBIT_S24_3BE),
.rates = (SNDRV_PCM_RATE_CONTINUOUS |
SNDRV_PCM_RATE_8000_192000),
.rate_min = 8000,
.rate_max = 192000,
.channels_min = 2,
.channels_max = 64,
.buffer_bytes_max = 64*2*3*MICROBLAZE_IBL_MAX*MAX_STREAM_BUFFER,
.period_bytes_min = (2*2*MICROBLAZE_IBL_MIN*2),
.period_bytes_max = (4*64*MICROBLAZE_IBL_MAX*MAX_STREAM_BUFFER),
.periods_min = 2,
.periods_max = MAX_STREAM_BUFFER,
};
static int lx_set_granularity(struct lx6464es *chip, u32 gran);
static int lx_hardware_open(struct lx6464es *chip,
struct snd_pcm_substream *substream)
{
int err = 0;
struct snd_pcm_runtime *runtime = substream->runtime;
int channels = runtime->channels;
int is_capture = (substream->stream == SNDRV_PCM_STREAM_CAPTURE);
snd_pcm_uframes_t period_size = runtime->period_size;
snd_printd(LXP "allocating pipe for %d channels\n", channels);
err = lx_pipe_allocate(chip, 0, is_capture, channels);
if (err < 0) {
snd_printk(KERN_ERR LXP "allocating pipe failed\n");
return err;
}
err = lx_set_granularity(chip, period_size);
if (err < 0) {
snd_printk(KERN_ERR LXP "setting granularity to %ld failed\n",
period_size);
return err;
}
return 0;
}
static int lx_hardware_start(struct lx6464es *chip,
struct snd_pcm_substream *substream)
{
int err = 0;
struct snd_pcm_runtime *runtime = substream->runtime;
int is_capture = (substream->stream == SNDRV_PCM_STREAM_CAPTURE);
snd_printd(LXP "setting stream format\n");
err = lx_stream_set_format(chip, runtime, 0, is_capture);
if (err < 0) {
snd_printk(KERN_ERR LXP "setting stream format failed\n");
return err;
}
snd_printd(LXP "starting pipe\n");
err = lx_pipe_start(chip, 0, is_capture);
if (err < 0) {
snd_printk(KERN_ERR LXP "starting pipe failed\n");
return err;
}
snd_printd(LXP "waiting for pipe to start\n");
err = lx_pipe_wait_for_start(chip, 0, is_capture);
if (err < 0) {
snd_printk(KERN_ERR LXP "waiting for pipe failed\n");
return err;
}
return err;
}
static int lx_hardware_stop(struct lx6464es *chip,
struct snd_pcm_substream *substream)
{
int err = 0;
int is_capture = (substream->stream == SNDRV_PCM_STREAM_CAPTURE);
snd_printd(LXP "pausing pipe\n");
err = lx_pipe_pause(chip, 0, is_capture);
if (err < 0) {
snd_printk(KERN_ERR LXP "pausing pipe failed\n");
return err;
}
snd_printd(LXP "waiting for pipe to become idle\n");
err = lx_pipe_wait_for_idle(chip, 0, is_capture);
if (err < 0) {
snd_printk(KERN_ERR LXP "waiting for pipe failed\n");
return err;
}
snd_printd(LXP "stopping pipe\n");
err = lx_pipe_stop(chip, 0, is_capture);
if (err < 0) {
snd_printk(LXP "stopping pipe failed\n");
return err;
}
return err;
}
static int lx_hardware_close(struct lx6464es *chip,
struct snd_pcm_substream *substream)
{
int err = 0;
int is_capture = (substream->stream == SNDRV_PCM_STREAM_CAPTURE);
snd_printd(LXP "releasing pipe\n");
err = lx_pipe_release(chip, 0, is_capture);
if (err < 0) {
snd_printk(LXP "releasing pipe failed\n");
return err;
}
return err;
}
static int lx_pcm_open(struct snd_pcm_substream *substream)
{
struct lx6464es *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int err = 0;
int board_rate;
snd_printdd("->lx_pcm_open\n");
mutex_lock(&chip->setup_mutex);
/* copy the struct snd_pcm_hardware struct */
runtime->hw = lx_caps;
#if 0
/* buffer-size should better be multiple of period-size */
err = snd_pcm_hw_constraint_integer(runtime,
SNDRV_PCM_HW_PARAM_PERIODS);
if (err < 0) {
snd_printk(KERN_WARNING LXP "could not constrain periods\n");
goto exit;
}
#endif
/* the clock rate cannot be changed */
board_rate = chip->board_sample_rate;
err = snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_RATE,
board_rate, board_rate);
if (err < 0) {
snd_printk(KERN_WARNING LXP "could not constrain periods\n");
goto exit;
}
/* constrain period size */
err = snd_pcm_hw_constraint_minmax(runtime,
SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
MICROBLAZE_IBL_MIN,
MICROBLAZE_IBL_MAX);
if (err < 0) {
snd_printk(KERN_WARNING LXP
"could not constrain period size\n");
goto exit;
}
snd_pcm_hw_constraint_step(runtime, 0,
SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 32);
snd_pcm_set_sync(substream);
err = 0;
exit:
runtime->private_data = chip;
mutex_unlock(&chip->setup_mutex);
snd_printdd("<-lx_pcm_open, %d\n", err);
return err;
}
static int lx_pcm_close(struct snd_pcm_substream *substream)
{
int err = 0;
snd_printdd("->lx_pcm_close\n");
return err;
}
static snd_pcm_uframes_t lx_pcm_stream_pointer(struct snd_pcm_substream
*substream)
{
struct lx6464es *chip = snd_pcm_substream_chip(substream);
snd_pcm_uframes_t pos;
unsigned long flags;
int is_capture = (substream->stream == SNDRV_PCM_STREAM_CAPTURE);
struct lx_stream *lx_stream = is_capture ? &chip->capture_stream :
&chip->playback_stream;
snd_printdd("->lx_pcm_stream_pointer\n");
spin_lock_irqsave(&chip->lock, flags);
pos = lx_stream->frame_pos * substream->runtime->period_size;
spin_unlock_irqrestore(&chip->lock, flags);
snd_printdd(LXP "stream_pointer at %ld\n", pos);
return pos;
}
static int lx_pcm_prepare(struct snd_pcm_substream *substream)
{
struct lx6464es *chip = snd_pcm_substream_chip(substream);
int err = 0;
const int is_capture = (substream->stream == SNDRV_PCM_STREAM_CAPTURE);
snd_printdd("->lx_pcm_prepare\n");
mutex_lock(&chip->setup_mutex);
if (chip->hardware_running[is_capture]) {
err = lx_hardware_stop(chip, substream);
if (err < 0) {
snd_printk(KERN_ERR LXP "failed to stop hardware. "
"Error code %d\n", err);
goto exit;
}
err = lx_hardware_close(chip, substream);
if (err < 0) {
snd_printk(KERN_ERR LXP "failed to close hardware. "
"Error code %d\n", err);
goto exit;
}
}
snd_printd(LXP "opening hardware\n");
err = lx_hardware_open(chip, substream);
if (err < 0) {
snd_printk(KERN_ERR LXP "failed to open hardware. "
"Error code %d\n", err);
goto exit;
}
err = lx_hardware_start(chip, substream);
if (err < 0) {
snd_printk(KERN_ERR LXP "failed to start hardware. "
"Error code %d\n", err);
goto exit;
}
chip->hardware_running[is_capture] = 1;
if (chip->board_sample_rate != substream->runtime->rate) {
if (!err)
chip->board_sample_rate = substream->runtime->rate;
}
exit:
mutex_unlock(&chip->setup_mutex);
return err;
}
static int lx_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params, int is_capture)
{
struct lx6464es *chip = snd_pcm_substream_chip(substream);
int err = 0;
snd_printdd("->lx_pcm_hw_params\n");
mutex_lock(&chip->setup_mutex);
/* set dma buffer */
err = snd_pcm_lib_malloc_pages(substream,
params_buffer_bytes(hw_params));
if (is_capture)
chip->capture_stream.stream = substream;
else
chip->playback_stream.stream = substream;
mutex_unlock(&chip->setup_mutex);
return err;
}
static int lx_pcm_hw_params_playback(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
return lx_pcm_hw_params(substream, hw_params, 0);
}
static int lx_pcm_hw_params_capture(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
return lx_pcm_hw_params(substream, hw_params, 1);
}
static int lx_pcm_hw_free(struct snd_pcm_substream *substream)
{
struct lx6464es *chip = snd_pcm_substream_chip(substream);
int err = 0;
int is_capture = (substream->stream == SNDRV_PCM_STREAM_CAPTURE);
snd_printdd("->lx_pcm_hw_free\n");
mutex_lock(&chip->setup_mutex);
if (chip->hardware_running[is_capture]) {
err = lx_hardware_stop(chip, substream);
if (err < 0) {
snd_printk(KERN_ERR LXP "failed to stop hardware. "
"Error code %d\n", err);
goto exit;
}
err = lx_hardware_close(chip, substream);
if (err < 0) {
snd_printk(KERN_ERR LXP "failed to close hardware. "
"Error code %d\n", err);
goto exit;
}
chip->hardware_running[is_capture] = 0;
}
err = snd_pcm_lib_free_pages(substream);
if (is_capture)
chip->capture_stream.stream = 0;
else
chip->playback_stream.stream = 0;
exit:
mutex_unlock(&chip->setup_mutex);
return err;
}
static void lx_trigger_start(struct lx6464es *chip, struct lx_stream *lx_stream)
{
struct snd_pcm_substream *substream = lx_stream->stream;
const unsigned int is_capture = lx_stream->is_capture;
int err;
const u32 channels = substream->runtime->channels;
const u32 bytes_per_frame = channels * 3;
const u32 period_size = substream->runtime->period_size;
const u32 periods = substream->runtime->periods;
const u32 period_bytes = period_size * bytes_per_frame;
dma_addr_t buf = substream->dma_buffer.addr;
int i;
u32 needed, freed;
u32 size_array[5];
for (i = 0; i != periods; ++i) {
u32 buffer_index = 0;
err = lx_buffer_ask(chip, 0, is_capture, &needed, &freed,
size_array);
snd_printdd(LXP "starting: needed %d, freed %d\n",
needed, freed);
err = lx_buffer_give(chip, 0, is_capture, period_bytes,
lower_32_bits(buf), upper_32_bits(buf),
&buffer_index);
snd_printdd(LXP "starting: buffer index %x on %p (%d bytes)\n",
buffer_index, (void *)buf, period_bytes);
buf += period_bytes;
}
err = lx_buffer_ask(chip, 0, is_capture, &needed, &freed, size_array);
snd_printdd(LXP "starting: needed %d, freed %d\n", needed, freed);
snd_printd(LXP "starting: starting stream\n");
err = lx_stream_start(chip, 0, is_capture);
if (err < 0)
snd_printk(KERN_ERR LXP "couldn't start stream\n");
else
lx_stream->status = LX_STREAM_STATUS_RUNNING;
lx_stream->frame_pos = 0;
}
static void lx_trigger_stop(struct lx6464es *chip, struct lx_stream *lx_stream)
{
const unsigned int is_capture = lx_stream->is_capture;
int err;
snd_printd(LXP "stopping: stopping stream\n");
err = lx_stream_stop(chip, 0, is_capture);
if (err < 0)
snd_printk(KERN_ERR LXP "couldn't stop stream\n");
else
lx_stream->status = LX_STREAM_STATUS_FREE;
}
static void lx_trigger_tasklet_dispatch_stream(struct lx6464es *chip,
struct lx_stream *lx_stream)
{
switch (lx_stream->status) {
case LX_STREAM_STATUS_SCHEDULE_RUN:
lx_trigger_start(chip, lx_stream);
break;
case LX_STREAM_STATUS_SCHEDULE_STOP:
lx_trigger_stop(chip, lx_stream);
break;
default:
break;
}
}
static void lx_trigger_tasklet(unsigned long data)
{
struct lx6464es *chip = (struct lx6464es *)data;
unsigned long flags;
snd_printdd("->lx_trigger_tasklet\n");
spin_lock_irqsave(&chip->lock, flags);
lx_trigger_tasklet_dispatch_stream(chip, &chip->capture_stream);
lx_trigger_tasklet_dispatch_stream(chip, &chip->playback_stream);
spin_unlock_irqrestore(&chip->lock, flags);
}
static int lx_pcm_trigger_dispatch(struct lx6464es *chip,
struct lx_stream *lx_stream, int cmd)
{
int err = 0;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
lx_stream->status = LX_STREAM_STATUS_SCHEDULE_RUN;
break;
case SNDRV_PCM_TRIGGER_STOP:
lx_stream->status = LX_STREAM_STATUS_SCHEDULE_STOP;
break;
default:
err = -EINVAL;
goto exit;
}
tasklet_schedule(&chip->trigger_tasklet);
exit:
return err;
}
static int lx_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct lx6464es *chip = snd_pcm_substream_chip(substream);
const int is_capture = (substream->stream == SNDRV_PCM_STREAM_CAPTURE);
struct lx_stream *stream = is_capture ? &chip->capture_stream :
&chip->playback_stream;
snd_printdd("->lx_pcm_trigger\n");
return lx_pcm_trigger_dispatch(chip, stream, cmd);
}
static int snd_lx6464es_free(struct lx6464es *chip)
{
snd_printdd("->snd_lx6464es_free\n");
lx_irq_disable(chip);
if (chip->irq >= 0)
free_irq(chip->irq, chip);
iounmap(chip->port_dsp_bar);
ioport_unmap(chip->port_plx_remapped);
pci_release_regions(chip->pci);
pci_disable_device(chip->pci);
kfree(chip);
return 0;
}
static int snd_lx6464es_dev_free(struct snd_device *device)
{
return snd_lx6464es_free(device->device_data);
}
/* reset the dsp during initialization */
static int __devinit lx_init_xilinx_reset(struct lx6464es *chip)
{
int i;
u32 plx_reg = lx_plx_reg_read(chip, ePLX_CHIPSC);
snd_printdd("->lx_init_xilinx_reset\n");
/* activate reset of xilinx */
plx_reg &= ~CHIPSC_RESET_XILINX;
lx_plx_reg_write(chip, ePLX_CHIPSC, plx_reg);
msleep(1);
lx_plx_reg_write(chip, ePLX_MBOX3, 0);
msleep(1);
plx_reg |= CHIPSC_RESET_XILINX;
lx_plx_reg_write(chip, ePLX_CHIPSC, plx_reg);
/* deactivate reset of xilinx */
for (i = 0; i != 100; ++i) {
u32 reg_mbox3;
msleep(10);
reg_mbox3 = lx_plx_reg_read(chip, ePLX_MBOX3);
if (reg_mbox3) {
snd_printd(LXP "xilinx reset done\n");
snd_printdd(LXP "xilinx took %d loops\n", i);
break;
}
}
/* todo: add some error handling? */
/* clear mr */
lx_dsp_reg_write(chip, eReg_CSM, 0);
/* le xilinx ES peut ne pas etre encore pret, on attend. */
msleep(600);
return 0;
}
static int __devinit lx_init_xilinx_test(struct lx6464es *chip)
{
u32 reg;
snd_printdd("->lx_init_xilinx_test\n");
/* TEST if we have access to Xilinx/MicroBlaze */
lx_dsp_reg_write(chip, eReg_CSM, 0);
reg = lx_dsp_reg_read(chip, eReg_CSM);
if (reg) {
snd_printk(KERN_ERR LXP "Problem: Reg_CSM %x.\n", reg);
/* PCI9056_SPACE0_REMAP */
lx_plx_reg_write(chip, ePLX_PCICR, 1);
reg = lx_dsp_reg_read(chip, eReg_CSM);
if (reg) {
snd_printk(KERN_ERR LXP "Error: Reg_CSM %x.\n", reg);
return -EAGAIN; /* seems to be appropriate */
}
}
snd_printd(LXP "Xilinx/MicroBlaze access test successful\n");
return 0;
}
/* initialize ethersound */
static int __devinit lx_init_ethersound_config(struct lx6464es *chip)
{
int i;
u32 orig_conf_es = lx_dsp_reg_read(chip, eReg_CONFES);
/* configure 64 io channels */
u32 conf_es = (orig_conf_es & CONFES_READ_PART_MASK) |
(64 << IOCR_INPUTS_OFFSET) |
(64 << IOCR_OUTPUTS_OFFSET) |
(FREQ_RATIO_SINGLE_MODE << FREQ_RATIO_OFFSET);
snd_printdd("->lx_init_ethersound\n");
chip->freq_ratio = FREQ_RATIO_SINGLE_MODE;
/*
* write it to the card !
* this actually kicks the ES xilinx, the first time since poweron.
* the MAC address in the Reg_ADMACESMSB Reg_ADMACESLSB registers
* is not ready before this is done, and the bit 2 in Reg_CSES is set.
* */
lx_dsp_reg_write(chip, eReg_CONFES, conf_es);
for (i = 0; i != 1000; ++i) {
if (lx_dsp_reg_read(chip, eReg_CSES) & 4) {
snd_printd(LXP "ethersound initialized after %dms\n",
i);
goto ethersound_initialized;
}
msleep(1);
}
snd_printk(KERN_WARNING LXP
"ethersound could not be initialized after %dms\n", i);
return -ETIMEDOUT;
ethersound_initialized:
snd_printd(LXP "ethersound initialized\n");
return 0;
}
static int __devinit lx_init_get_version_features(struct lx6464es *chip)
{
u32 dsp_version;
int err;
snd_printdd("->lx_init_get_version_features\n");
err = lx_dsp_get_version(chip, &dsp_version);
if (err == 0) {
u32 freq;
snd_printk(LXP "DSP version: V%02d.%02d #%d\n",
(dsp_version>>16) & 0xff, (dsp_version>>8) & 0xff,
dsp_version & 0xff);
/* later: what firmware version do we expect? */
/* retrieve Play/Rec features */
/* done here because we may have to handle alternate
* DSP files. */
/* later */
/* init the EtherSound sample rate */
err = lx_dsp_get_clock_frequency(chip, &freq);
if (err == 0)
chip->board_sample_rate = freq;
snd_printd(LXP "actual clock frequency %d\n", freq);
} else {
snd_printk(KERN_ERR LXP "DSP corrupted \n");
err = -EAGAIN;
}
return err;
}
static int lx_set_granularity(struct lx6464es *chip, u32 gran)
{
int err = 0;
u32 snapped_gran = MICROBLAZE_IBL_MIN;
snd_printdd("->lx_set_granularity\n");
/* blocksize is a power of 2 */
while ((snapped_gran < gran) &&
(snapped_gran < MICROBLAZE_IBL_MAX)) {
snapped_gran *= 2;
}
if (snapped_gran == chip->pcm_granularity)
return 0;
err = lx_dsp_set_granularity(chip, snapped_gran);
if (err < 0) {
snd_printk(KERN_WARNING LXP "could not set granularity\n");
err = -EAGAIN;
}
if (snapped_gran != gran)
snd_printk(LXP "snapped blocksize to %d\n", snapped_gran);
snd_printd(LXP "set blocksize on board %d\n", snapped_gran);
chip->pcm_granularity = snapped_gran;
return err;
}
/* initialize and test the xilinx dsp chip */
static int __devinit lx_init_dsp(struct lx6464es *chip)
{
int err;
int i;
snd_printdd("->lx_init_dsp\n");
snd_printd(LXP "initialize board\n");
err = lx_init_xilinx_reset(chip);
if (err)
return err;
snd_printd(LXP "testing board\n");
err = lx_init_xilinx_test(chip);
if (err)
return err;
snd_printd(LXP "initialize ethersound configuration\n");
err = lx_init_ethersound_config(chip);
if (err)
return err;
lx_irq_enable(chip);
/** \todo the mac address should be ready by not, but it isn't,
* so we wait for it */
for (i = 0; i != 1000; ++i) {
err = lx_dsp_get_mac(chip);
if (err)
return err;
if (chip->mac_address[0] || chip->mac_address[1] || chip->mac_address[2] ||
chip->mac_address[3] || chip->mac_address[4] || chip->mac_address[5])
goto mac_ready;
msleep(1);
}
return -ETIMEDOUT;
mac_ready:
snd_printd(LXP "mac address ready read after: %dms\n", i);
snd_printk(LXP "mac address: %02X.%02X.%02X.%02X.%02X.%02X\n",
chip->mac_address[0], chip->mac_address[1], chip->mac_address[2],
chip->mac_address[3], chip->mac_address[4], chip->mac_address[5]);
err = lx_init_get_version_features(chip);
if (err)
return err;
lx_set_granularity(chip, MICROBLAZE_IBL_DEFAULT);
chip->playback_mute = 0;
return err;
}
static struct snd_pcm_ops lx_ops_playback = {
.open = lx_pcm_open,
.close = lx_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.prepare = lx_pcm_prepare,
.hw_params = lx_pcm_hw_params_playback,
.hw_free = lx_pcm_hw_free,
.trigger = lx_pcm_trigger,
.pointer = lx_pcm_stream_pointer,
};
static struct snd_pcm_ops lx_ops_capture = {
.open = lx_pcm_open,
.close = lx_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.prepare = lx_pcm_prepare,
.hw_params = lx_pcm_hw_params_capture,
.hw_free = lx_pcm_hw_free,
.trigger = lx_pcm_trigger,
.pointer = lx_pcm_stream_pointer,
};
static int __devinit lx_pcm_create(struct lx6464es *chip)
{
int err;
struct snd_pcm *pcm;
u32 size = 64 * /* channels */
3 * /* 24 bit samples */
MAX_STREAM_BUFFER * /* periods */
MICROBLAZE_IBL_MAX * /* frames per period */
2; /* duplex */
size = PAGE_ALIGN(size);
/* hardcoded device name & channel count */
err = snd_pcm_new(chip->card, (char *)card_name, 0,
1, 1, &pcm);
pcm->private_data = chip;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &lx_ops_playback);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &lx_ops_capture);
pcm->info_flags = 0;
strcpy(pcm->name, card_name);
err = snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci),
size, size);
if (err < 0)
return err;
chip->pcm = pcm;
chip->capture_stream.is_capture = 1;
return 0;
}
static int lx_control_playback_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 1;
return 0;
}
static int lx_control_playback_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct lx6464es *chip = snd_kcontrol_chip(kcontrol);
ucontrol->value.integer.value[0] = chip->playback_mute;
return 0;
}
static int lx_control_playback_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct lx6464es *chip = snd_kcontrol_chip(kcontrol);
int changed = 0;
int current_value = chip->playback_mute;
if (current_value != ucontrol->value.integer.value[0]) {
lx_level_unmute(chip, 0, !current_value);
chip->playback_mute = !current_value;
changed = 1;
}
return changed;
}
static struct snd_kcontrol_new lx_control_playback_switch __devinitdata = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Playback Switch",
.index = 0,
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.private_value = 0,
.info = lx_control_playback_info,
.get = lx_control_playback_get,
.put = lx_control_playback_put
};
static void lx_proc_levels_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
u32 levels[64];
int err;
int i, j;
struct lx6464es *chip = entry->private_data;
snd_iprintf(buffer, "capture levels:\n");
err = lx_level_peaks(chip, 1, 64, levels);
if (err < 0)
return;
for (i = 0; i != 8; ++i) {
for (j = 0; j != 8; ++j)
snd_iprintf(buffer, "%08x ", levels[i*8+j]);
snd_iprintf(buffer, "\n");
}
snd_iprintf(buffer, "\nplayback levels:\n");
err = lx_level_peaks(chip, 0, 64, levels);
if (err < 0)
return;
for (i = 0; i != 8; ++i) {
for (j = 0; j != 8; ++j)
snd_iprintf(buffer, "%08x ", levels[i*8+j]);
snd_iprintf(buffer, "\n");
}
snd_iprintf(buffer, "\n");
}
static int __devinit lx_proc_create(struct snd_card *card, struct lx6464es *chip)
{
struct snd_info_entry *entry;
int err = snd_card_proc_new(card, "levels", &entry);
if (err < 0)
return err;
snd_info_set_text_ops(entry, chip, lx_proc_levels_read);
return 0;
}
static int __devinit snd_lx6464es_create(struct snd_card *card,
struct pci_dev *pci,
struct lx6464es **rchip)
{
struct lx6464es *chip;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_lx6464es_dev_free,
};
snd_printdd("->snd_lx6464es_create\n");
*rchip = NULL;
/* enable PCI device */
err = pci_enable_device(pci);
if (err < 0)
return err;
pci_set_master(pci);
/* check if we can restrict PCI DMA transfers to 32 bits */
err = pci_set_dma_mask(pci, DMA_BIT_MASK(32));
if (err < 0) {
snd_printk(KERN_ERR "architecture does not support "
"32bit PCI busmaster DMA\n");
pci_disable_device(pci);
return -ENXIO;
}
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (chip == NULL) {
err = -ENOMEM;
goto alloc_failed;
}
chip->card = card;
chip->pci = pci;
chip->irq = -1;
/* initialize synchronization structs */
spin_lock_init(&chip->lock);
spin_lock_init(&chip->msg_lock);
mutex_init(&chip->setup_mutex);
tasklet_init(&chip->trigger_tasklet, lx_trigger_tasklet,
(unsigned long)chip);
tasklet_init(&chip->tasklet_capture, lx_tasklet_capture,
(unsigned long)chip);
tasklet_init(&chip->tasklet_playback, lx_tasklet_playback,
(unsigned long)chip);
/* request resources */
err = pci_request_regions(pci, card_name);
if (err < 0)
goto request_regions_failed;
/* plx port */
chip->port_plx = pci_resource_start(pci, 1);
chip->port_plx_remapped = ioport_map(chip->port_plx,
pci_resource_len(pci, 1));
/* dsp port */
chip->port_dsp_bar = pci_ioremap_bar(pci, 2);
err = request_irq(pci->irq, lx_interrupt, IRQF_SHARED,
KBUILD_MODNAME, chip);
if (err) {
snd_printk(KERN_ERR LXP "unable to grab IRQ %d\n", pci->irq);
goto request_irq_failed;
}
chip->irq = pci->irq;
err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
if (err < 0)
goto device_new_failed;
err = lx_init_dsp(chip);
if (err < 0) {
snd_printk(KERN_ERR LXP "error during DSP initialization\n");
return err;
}
err = lx_pcm_create(chip);
if (err < 0)
return err;
err = lx_proc_create(card, chip);
if (err < 0)
return err;
err = snd_ctl_add(card, snd_ctl_new1(&lx_control_playback_switch,
chip));
if (err < 0)
return err;
snd_card_set_dev(card, &pci->dev);
*rchip = chip;
return 0;
device_new_failed:
free_irq(pci->irq, chip);
request_irq_failed:
pci_release_regions(pci);
request_regions_failed:
kfree(chip);
alloc_failed:
pci_disable_device(pci);
return err;
}
static int __devinit snd_lx6464es_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
static int dev;
struct snd_card *card;
struct lx6464es *chip;
int err;
snd_printdd("->snd_lx6464es_probe\n");
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev]) {
dev++;
return -ENOENT;
}
err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
if (err < 0)
return err;
err = snd_lx6464es_create(card, pci, &chip);
if (err < 0) {
snd_printk(KERN_ERR LXP "error during snd_lx6464es_create\n");
goto out_free;
}
strcpy(card->driver, "LX6464ES");
sprintf(card->id, "LX6464ES_%02X%02X%02X",
chip->mac_address[3], chip->mac_address[4], chip->mac_address[5]);
sprintf(card->shortname, "LX6464ES %02X.%02X.%02X.%02X.%02X.%02X",
chip->mac_address[0], chip->mac_address[1], chip->mac_address[2],
chip->mac_address[3], chip->mac_address[4], chip->mac_address[5]);
sprintf(card->longname, "%s at 0x%lx, 0x%p, irq %i",
card->shortname, chip->port_plx,
chip->port_dsp_bar, chip->irq);
err = snd_card_register(card);
if (err < 0)
goto out_free;
snd_printdd(LXP "initialization successful\n");
pci_set_drvdata(pci, card);
dev++;
return 0;
out_free:
snd_card_free(card);
return err;
}
static void __devexit snd_lx6464es_remove(struct pci_dev *pci)
{
snd_card_free(pci_get_drvdata(pci));
pci_set_drvdata(pci, NULL);
}
static struct pci_driver driver = {
.name = KBUILD_MODNAME,
.id_table = snd_lx6464es_ids,
.probe = snd_lx6464es_probe,
.remove = __devexit_p(snd_lx6464es_remove),
};
/* module initialization */
static int __init mod_init(void)
{
return pci_register_driver(&driver);
}
static void __exit mod_exit(void)
{
pci_unregister_driver(&driver);
}
module_init(mod_init);
module_exit(mod_exit);
| gpl-2.0 |
omnirom/android_kernel_lge_msm8974 | drivers/staging/rts5139/rts51x.c | 4899 | 24844 | /* Driver for Realtek RTS51xx USB card reader
*
* Copyright(c) 2009 Realtek Semiconductor Corp. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, 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, see <http://www.gnu.org/licenses/>.
*
* Author:
* wwang (wei_wang@realsil.com.cn)
* No. 450, Shenhu Road, Suzhou Industry Park, Suzhou, China
* Maintainer:
* Edwin Rong (edwin_rong@realsil.com.cn)
* No. 450, Shenhu Road, Suzhou Industry Park, Suzhou, China
*/
#include <linux/blkdev.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/workqueue.h>
#include <linux/errno.h>
#include <linux/freezer.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <linux/utsname.h>
#include <linux/usb.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_devinfo.h>
#include <scsi/scsi_eh.h>
#include <scsi/scsi_host.h>
#include "debug.h"
#include "ms.h"
#include "rts51x.h"
#include "rts51x_chip.h"
#include "rts51x_card.h"
#include "rts51x_scsi.h"
#include "rts51x_transport.h"
#include "rts51x_fop.h"
MODULE_DESCRIPTION(RTS51X_DESC);
MODULE_LICENSE("GPL");
MODULE_VERSION(DRIVER_VERSION);
#ifdef SCSI_SCAN_DELAY
static unsigned int delay_use = 5;
module_param(delay_use, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(delay_use, "seconds to delay before using a new device");
#endif
static int auto_delink_en;
module_param(auto_delink_en, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(auto_delink_en, "enable auto delink");
static int ss_en;
module_param(ss_en, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(ss_en, "enable selective suspend");
static int ss_delay = 50;
module_param(ss_delay, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(ss_delay,
"seconds to delay before entering selective suspend");
static int needs_remote_wakeup;
module_param(needs_remote_wakeup, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(needs_remote_wakeup, "ss state needs remote wakeup supported");
#ifdef SUPPORT_FILE_OP
static const struct file_operations rts51x_fops = {
.owner = THIS_MODULE,
.read = rts51x_read,
.write = rts51x_write,
.unlocked_ioctl = rts51x_ioctl,
.open = rts51x_open,
.release = rts51x_release,
};
/*
* usb class driver info in order to get a minor number from the usb core,
* and to have the device registered with the driver core
*/
static struct usb_class_driver rts51x_class = {
.name = "rts51x%d",
.fops = &rts51x_fops,
.minor_base = 192,
};
#endif
#ifdef CONFIG_PM /* Minimal support for suspend and resume */
static inline void usb_autopm_enable(struct usb_interface *intf)
{
atomic_set(&intf->pm_usage_cnt, 1);
usb_autopm_put_interface(intf);
}
static inline void usb_autopm_disable(struct usb_interface *intf)
{
atomic_set(&intf->pm_usage_cnt, 0);
usb_autopm_get_interface(intf);
}
void rts51x_try_to_enter_ss(struct rts51x_chip *chip)
{
RTS51X_DEBUGP("Ready to enter SS state\n");
usb_autopm_enable(chip->usb->pusb_intf);
}
void rts51x_try_to_exit_ss(struct rts51x_chip *chip)
{
RTS51X_DEBUGP("Exit from SS state\n");
usb_autopm_disable(chip->usb->pusb_intf);
}
int rts51x_suspend(struct usb_interface *iface, pm_message_t message)
{
struct rts51x_chip *chip = usb_get_intfdata(iface);
RTS51X_DEBUGP("%s, message.event = 0x%x\n", __func__, message.event);
/* Wait until no command is running */
mutex_lock(&chip->usb->dev_mutex);
chip->fake_card_ready = chip->card_ready;
rts51x_do_before_power_down(chip);
if (message.event == PM_EVENT_AUTO_SUSPEND) {
RTS51X_DEBUGP("Enter SS state");
chip->resume_from_scsi = 0;
RTS51X_SET_STAT(chip, STAT_SS);
} else {
RTS51X_DEBUGP("Enter SUSPEND state");
RTS51X_SET_STAT(chip, STAT_SUSPEND);
}
/* When runtime PM is working, we'll set a flag to indicate
* whether we should autoresume when a SCSI request arrives. */
mutex_unlock(&chip->usb->dev_mutex);
return 0;
}
int rts51x_resume(struct usb_interface *iface)
{
struct rts51x_chip *chip = usb_get_intfdata(iface);
RTS51X_DEBUGP("%s\n", __func__);
if (!RTS51X_CHK_STAT(chip, STAT_SS) || !chip->resume_from_scsi) {
mutex_lock(&chip->usb->dev_mutex);
if (chip->option.ss_en) {
if (GET_PM_USAGE_CNT(chip) <= 0) {
/* Remote wake up, increase pm_usage_cnt */
RTS51X_DEBUGP("Incr pm_usage_cnt\n");
SET_PM_USAGE_CNT(chip, 1);
}
}
RTS51X_SET_STAT(chip, STAT_RUN);
rts51x_init_chip(chip);
rts51x_init_cards(chip);
mutex_unlock(&chip->usb->dev_mutex);
}
return 0;
}
int rts51x_reset_resume(struct usb_interface *iface)
{
struct rts51x_chip *chip = usb_get_intfdata(iface);
RTS51X_DEBUGP("%s\n", __func__);
mutex_lock(&chip->usb->dev_mutex);
RTS51X_SET_STAT(chip, STAT_RUN);
if (chip->option.ss_en)
SET_PM_USAGE_CNT(chip, 1);
rts51x_init_chip(chip);
rts51x_init_cards(chip);
mutex_unlock(&chip->usb->dev_mutex);
/* FIXME: Notify the subdrivers that they need to reinitialize
* the device */
return 0;
}
#else /* CONFIG_PM */
void rts51x_try_to_enter_ss(struct rts51x_chip *chip)
{
}
void rts51x_try_to_exit_ss(struct rts51x_chip *chip)
{
}
#endif /* CONFIG_PM */
/*
* The next two routines get called just before and just after
* a USB port reset, whether from this driver or a different one.
*/
int rts51x_pre_reset(struct usb_interface *iface)
{
struct rts51x_chip *chip = usb_get_intfdata(iface);
RTS51X_DEBUGP("%s\n", __func__);
/* Make sure no command runs during the reset */
mutex_lock(&chip->usb->dev_mutex);
return 0;
}
int rts51x_post_reset(struct usb_interface *iface)
{
struct rts51x_chip *chip = usb_get_intfdata(iface);
RTS51X_DEBUGP("%s\n", __func__);
/* Report the reset to the SCSI core */
/* usb_stor_report_bus_reset(us); */
/* FIXME: Notify the subdrivers that they need to reinitialize
* the device */
mutex_unlock(&chip->usb->dev_mutex);
return 0;
}
static int rts51x_control_thread(void *__chip)
{
struct rts51x_chip *chip = (struct rts51x_chip *)__chip;
struct Scsi_Host *host = rts51x_to_host(chip);
for (;;) {
if (wait_for_completion_interruptible(&chip->usb->cmnd_ready))
break;
if (test_bit(FLIDX_DISCONNECTING, &chip->usb->dflags)) {
RTS51X_DEBUGP("-- exiting from rts51x-control\n");
break;
}
/* lock the device pointers */
mutex_lock(&(chip->usb->dev_mutex));
/* lock access to the state */
scsi_lock(host);
/* When we are called with no command pending, we're done */
if (chip->srb == NULL) {
scsi_unlock(host);
mutex_unlock(&chip->usb->dev_mutex);
RTS51X_DEBUGP("-- exiting from control thread\n");
break;
}
/* has the command timed out *already* ? */
if (test_bit(FLIDX_TIMED_OUT, &chip->usb->dflags)) {
chip->srb->result = DID_ABORT << 16;
goto SkipForAbort;
}
scsi_unlock(host);
/* reject the command if the direction indicator
* is UNKNOWN
*/
if (chip->srb->sc_data_direction == DMA_BIDIRECTIONAL) {
RTS51X_DEBUGP("UNKNOWN data direction\n");
chip->srb->result = DID_ERROR << 16;
}
/* reject if target != 0 or if LUN is higher than
* the maximum known LUN
*/
else if (chip->srb->device->id) {
RTS51X_DEBUGP("Bad target number (%d:%d)\n",
chip->srb->device->id,
chip->srb->device->lun);
chip->srb->result = DID_BAD_TARGET << 16;
}
else if (chip->srb->device->lun > chip->max_lun) {
RTS51X_DEBUGP("Bad LUN (%d:%d)\n",
chip->srb->device->id,
chip->srb->device->lun);
chip->srb->result = DID_BAD_TARGET << 16;
}
/* we've got a command, let's do it! */
else {
RTS51X_DEBUG(scsi_show_command(chip->srb));
rts51x_invoke_transport(chip->srb, chip);
}
/* lock access to the state */
scsi_lock(host);
/* indicate that the command is done */
if (chip->srb->result != DID_ABORT << 16)
chip->srb->scsi_done(chip->srb);
else
SkipForAbort :
RTS51X_DEBUGP("scsi command aborted\n");
/* If an abort request was received we need to signal that
* the abort has finished. The proper test for this is
* the TIMED_OUT flag, not srb->result == DID_ABORT, because
* the timeout might have occurred after the command had
* already completed with a different result code. */
if (test_bit(FLIDX_TIMED_OUT, &chip->usb->dflags)) {
complete(&(chip->usb->notify));
/* Allow USB transfers to resume */
clear_bit(FLIDX_ABORTING, &chip->usb->dflags);
clear_bit(FLIDX_TIMED_OUT, &chip->usb->dflags);
}
/* finished working on this command */
chip->srb = NULL;
scsi_unlock(host);
/* unlock the device pointers */
mutex_unlock(&chip->usb->dev_mutex);
} /* for (;;) */
complete(&chip->usb->control_exit);
/* Wait until we are told to stop */
/* for (;;) {
set_current_state(TASK_INTERRUPTIBLE);
if (kthread_should_stop())
break;
schedule();
}
__set_current_state(TASK_RUNNING);*/
return 0;
}
static int rts51x_polling_thread(void *__chip)
{
struct rts51x_chip *chip = (struct rts51x_chip *)__chip;
#ifdef SCSI_SCAN_DELAY
/* Wait until SCSI scan finished */
wait_timeout((delay_use + 5) * HZ);
#endif
for (;;) {
wait_timeout(POLLING_INTERVAL);
/* if the device has disconnected, we are free to exit */
if (test_bit(FLIDX_DISCONNECTING, &chip->usb->dflags)) {
RTS51X_DEBUGP("-- exiting from rts51x-polling\n");
break;
}
/* if the device has disconnected, we are free to exit */
/* if (kthread_should_stop()) {
printk(KERN_INFO "Stop polling thread!\n");
break;
} */
#ifdef CONFIG_PM
if (RTS51X_CHK_STAT(chip, STAT_SS) ||
RTS51X_CHK_STAT(chip, STAT_SS_PRE) ||
RTS51X_CHK_STAT(chip, STAT_SUSPEND)) {
continue;
}
if (ss_en) {
if (RTS51X_CHK_STAT(chip, STAT_IDLE)) {
if (chip->ss_counter <
(ss_delay * 1000 / POLLING_INTERVAL)) {
chip->ss_counter++;
} else {
/* Prepare SS state */
RTS51X_SET_STAT(chip, STAT_SS_PRE);
rts51x_try_to_enter_ss(chip);
continue;
}
} else {
chip->ss_counter = 0;
}
}
#endif
mspro_polling_format_status(chip);
/* lock the device pointers */
mutex_lock(&(chip->usb->dev_mutex));
rts51x_polling_func(chip);
/* unlock the device pointers */
mutex_unlock(&chip->usb->dev_mutex);
} /* for (;;) */
complete(&chip->usb->polling_exit);
/* Wait until we are told to stop */
/* for (;;) {
set_current_state(TASK_INTERRUPTIBLE);
if (kthread_should_stop())
break;
schedule();
}
__set_current_state(TASK_RUNNING); */
return 0;
}
#ifdef SCSI_SCAN_DELAY
/* Thread to carry out delayed SCSI-device scanning */
static int rts51x_scan_thread(void *__chip)
{
struct rts51x_chip *chip = (struct rts51x_chip *)__chip;
printk(KERN_DEBUG
"rts51x: device found at %d\n", chip->usb->pusb_dev->devnum);
set_freezable();
/* Wait for the timeout to expire or for a disconnect */
if (delay_use > 0) {
printk(KERN_DEBUG "rts51x: waiting for device "
"to settle before scanning\n");
wait_event_freezable_timeout(chip->usb->delay_wait,
test_bit(FLIDX_DONT_SCAN,
&chip->usb->dflags),
delay_use * HZ);
}
/* If the device is still connected, perform the scanning */
if (!test_bit(FLIDX_DONT_SCAN, &chip->usb->dflags)) {
scsi_scan_host(rts51x_to_host(chip));
printk(KERN_DEBUG "rts51x: device scan complete\n");
/* Should we unbind if no devices were detected? */
}
complete_and_exit(&chip->usb->scanning_done, 0);
}
#endif
/* Associate our private data with the USB device */
static int associate_dev(struct rts51x_chip *chip, struct usb_interface *intf)
{
struct rts51x_usb *rts51x = chip->usb;
#ifdef SUPPORT_FILE_OP
int retval;
#endif
/* Fill in the device-related fields */
rts51x->pusb_dev = interface_to_usbdev(intf);
rts51x->pusb_intf = intf;
rts51x->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
RTS51X_DEBUGP("Vendor: 0x%04x, Product: 0x%04x, Revision: 0x%04x\n",
le16_to_cpu(rts51x->pusb_dev->descriptor.idVendor),
le16_to_cpu(rts51x->pusb_dev->descriptor.idProduct),
le16_to_cpu(rts51x->pusb_dev->descriptor.bcdDevice));
RTS51X_DEBUGP("Interface Subclass: 0x%02x, Protocol: 0x%02x\n",
intf->cur_altsetting->desc.bInterfaceSubClass,
intf->cur_altsetting->desc.bInterfaceProtocol);
/* Store our private data in the interface */
usb_set_intfdata(intf, chip);
#ifdef SUPPORT_FILE_OP
/* we can register the device now, as it is ready */
retval = usb_register_dev(intf, &rts51x_class);
if (retval) {
/* something prevented us from registering this driver */
RTS51X_DEBUGP("Not able to get a minor for this device.");
usb_set_intfdata(intf, NULL);
return -ENOMEM;
}
#endif
/* Allocate the device-related DMA-mapped buffers */
rts51x->cr = usb_buffer_alloc(rts51x->pusb_dev, sizeof(*rts51x->cr),
GFP_KERNEL, &rts51x->cr_dma);
if (!rts51x->cr) {
RTS51X_DEBUGP("usb_ctrlrequest allocation failed\n");
usb_set_intfdata(intf, NULL);
return -ENOMEM;
}
rts51x->iobuf = usb_buffer_alloc(rts51x->pusb_dev, RTS51X_IOBUF_SIZE,
GFP_KERNEL, &rts51x->iobuf_dma);
if (!rts51x->iobuf) {
RTS51X_DEBUGP("I/O buffer allocation failed\n");
usb_set_intfdata(intf, NULL);
return -ENOMEM;
}
return 0;
}
static void rts51x_init_options(struct rts51x_chip *chip)
{
struct rts51x_option *option = &(chip->option);
option->led_blink_speed = 7;
option->mspro_formatter_enable = 1;
option->fpga_sd_sdr104_clk = CLK_100;
option->fpga_sd_sdr50_clk = CLK_100;
option->fpga_sd_ddr50_clk = CLK_100;
option->fpga_sd_hs_clk = CLK_100;
option->fpga_mmc_52m_clk = CLK_80;
option->fpga_ms_hg_clk = CLK_80;
option->fpga_ms_4bit_clk = CLK_80;
option->asic_sd_sdr104_clk = 98;
option->asic_sd_sdr50_clk = 98;
option->asic_sd_ddr50_clk = 98;
option->asic_sd_hs_clk = 97;
option->asic_mmc_52m_clk = 95;
option->asic_ms_hg_clk = 116;
option->asic_ms_4bit_clk = 77;
option->sd_ddr_tx_phase = 0;
option->mmc_ddr_tx_phase = 1;
option->sd_speed_prior = 0;
option->sd_ctl =
SD_PUSH_POINT_AUTO | SD_SAMPLE_POINT_AUTO | SUPPORT_UHS50_MMC44;
option->ss_en = ss_en;
option->ss_delay = ss_delay;
option->needs_remote_wakeup = needs_remote_wakeup;
option->auto_delink_en = auto_delink_en;
option->FT2_fast_mode = 0;
option->pwr_delay = 800;
option->xd_rw_step = 0;
option->D3318_off_delay = 50;
option->delink_delay = 100;
option->rts5129_D3318_off_enable = 0;
option->sd20_pad_drive = 0;
option->reset_or_rw_fail_set_pad_drive = 1;
option->rcc_fail_flag = 0;
option->rcc_bug_fix_en = 1;
option->debounce_num = 2;
option->polling_time = 100;
option->led_toggle_interval = 6;
option->xd_rwn_step = 0;
option->sd_send_status_en = 0;
option->sdr50_tx_phase = 0x01;
option->sdr50_rx_phase = 0x05;
option->ddr50_tx_phase = 0x09;
option->ddr50_rx_phase = 0x06;
option->sdr50_phase_sel = 0;
option->sd30_pad_drive = 1;
option->ms_errreg_fix = 0;
option->reset_mmc_first = 0;
option->speed_mmc = 1;
option->led_always_on = 0;
}
/* Get the pipe settings */
static int get_pipes(struct rts51x_chip *chip)
{
struct rts51x_usb *rts51x = chip->usb;
struct usb_host_interface *altsetting =
rts51x->pusb_intf->cur_altsetting;
int i;
struct usb_endpoint_descriptor *ep;
struct usb_endpoint_descriptor *ep_in = NULL;
struct usb_endpoint_descriptor *ep_out = NULL;
struct usb_endpoint_descriptor *ep_int = NULL;
/*
* Find the first endpoint of each type we need.
* We are expecting a minimum of 2 endpoints - in and out (bulk).
* An optional interrupt-in is OK (necessary for CBI protocol).
* We will ignore any others.
*/
for (i = 0; i < altsetting->desc.bNumEndpoints; i++) {
ep = &altsetting->endpoint[i].desc;
if (usb_endpoint_xfer_bulk(ep)) {
if (usb_endpoint_dir_in(ep)) {
if (!ep_in)
ep_in = ep;
} else {
if (!ep_out)
ep_out = ep;
}
}
else if (usb_endpoint_is_int_in(ep)) {
if (!ep_int)
ep_int = ep;
}
}
if (!ep_in || !ep_out) {
RTS51X_DEBUGP("Endpoint sanity check failed!"
"Rejecting dev.\n");
return -EIO;
}
/* Calculate and store the pipe values */
rts51x->send_ctrl_pipe = usb_sndctrlpipe(rts51x->pusb_dev, 0);
rts51x->recv_ctrl_pipe = usb_rcvctrlpipe(rts51x->pusb_dev, 0);
rts51x->send_bulk_pipe = usb_sndbulkpipe(rts51x->pusb_dev,
usb_endpoint_num(ep_out));
rts51x->recv_bulk_pipe = usb_rcvbulkpipe(rts51x->pusb_dev,
usb_endpoint_num(ep_in));
if (ep_int) {
rts51x->recv_intr_pipe = usb_rcvintpipe(rts51x->pusb_dev,
usb_endpoint_num
(ep_int));
rts51x->ep_bInterval = ep_int->bInterval;
}
return 0;
}
/* Initialize all the dynamic resources we need */
static int rts51x_acquire_resources(struct rts51x_chip *chip)
{
struct rts51x_usb *rts51x = chip->usb;
int retval;
rts51x->current_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!rts51x->current_urb) {
RTS51X_DEBUGP("URB allocation failed\n");
return -ENOMEM;
}
rts51x->intr_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!rts51x->intr_urb) {
RTS51X_DEBUGP("URB allocation failed\n");
return -ENOMEM;
}
chip->cmd_buf = chip->rsp_buf = rts51x->iobuf;
rts51x_init_options(chip);
/* Init rts51xx device */
retval = rts51x_init_chip(chip);
if (retval != STATUS_SUCCESS)
return -EIO;
return 0;
}
/* Release all our dynamic resources */
static void rts51x_release_resources(struct rts51x_chip *chip)
{
RTS51X_DEBUGP("-- %s\n", __func__);
/* Tell the control thread to exit. The SCSI host must
* already have been removed and the DISCONNECTING flag set
* so that we won't accept any more commands.
*/
RTS51X_DEBUGP("-- sending exit command to thread\n");
complete(&chip->usb->cmnd_ready);
if (chip->usb->ctl_thread)
wait_for_completion(&chip->usb->control_exit);
/* kthread_stop(chip->usb->ctl_thread); */
if (chip->usb->polling_thread)
wait_for_completion(&chip->usb->polling_exit);
/* if (chip->usb->polling_thread)
kthread_stop(chip->usb->polling_thread); */
wait_timeout(200);
/* Release rts51xx device here */
rts51x_release_chip(chip);
usb_free_urb(chip->usb->current_urb);
usb_free_urb(chip->usb->intr_urb);
}
/* Dissociate from the USB device */
static void dissociate_dev(struct rts51x_chip *chip)
{
struct rts51x_usb *rts51x = chip->usb;
RTS51X_DEBUGP("-- %s\n", __func__);
/* Free the device-related DMA-mapped buffers */
if (rts51x->cr)
usb_buffer_free(rts51x->pusb_dev, sizeof(*rts51x->cr),
rts51x->cr, rts51x->cr_dma);
if (rts51x->iobuf)
usb_buffer_free(rts51x->pusb_dev, RTS51X_IOBUF_SIZE,
rts51x->iobuf, rts51x->iobuf_dma);
/* Remove our private data from the interface */
usb_set_intfdata(rts51x->pusb_intf, NULL);
#ifdef SUPPORT_FILE_OP
/* give back our minor */
usb_deregister_dev(rts51x->pusb_intf, &rts51x_class);
#endif
kfree(rts51x);
chip->usb = NULL;
}
/* First stage of disconnect processing: stop SCSI scanning,
* remove the host, and stop accepting new commands
*/
static void quiesce_and_remove_host(struct rts51x_chip *chip)
{
struct rts51x_usb *rts51x = chip->usb;
struct Scsi_Host *host = rts51x_to_host(chip);
/* If the device is really gone, cut short reset delays */
if (rts51x->pusb_dev->state == USB_STATE_NOTATTACHED)
set_bit(FLIDX_DISCONNECTING, &rts51x->dflags);
#ifdef SCSI_SCAN_DELAY
/* Prevent SCSI-scanning (if it hasn't started yet)
* and wait for the SCSI-scanning thread to stop.
*/
set_bit(FLIDX_DONT_SCAN, &rts51x->dflags);
wake_up(&rts51x->delay_wait);
wait_for_completion(&rts51x->scanning_done);
#endif
/* Removing the host will perform an orderly shutdown: caches
* synchronized, disks spun down, etc.
*/
scsi_remove_host(host);
/* Prevent any new commands from being accepted and cut short
* reset delays.
*/
scsi_lock(host);
set_bit(FLIDX_DISCONNECTING, &rts51x->dflags);
scsi_unlock(host);
#ifdef SCSI_SCAN_DELAY
wake_up(&rts51x->delay_wait);
#endif
}
/* Second stage of disconnect processing: deallocate all resources */
static void release_everything(struct rts51x_chip *chip)
{
rts51x_release_resources(chip);
dissociate_dev(chip);
/* Drop our reference to the host; the SCSI core will free it
* (and "chip" along with it) when the refcount becomes 0. */
scsi_host_put(rts51x_to_host(chip));
}
static int rts51x_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct Scsi_Host *host;
struct rts51x_chip *chip;
struct rts51x_usb *rts51x;
int result;
struct task_struct *th;
RTS51X_DEBUGP("%s detected\n", RTS51X_NAME);
rts51x = kzalloc(sizeof(struct rts51x_usb), GFP_KERNEL);
if (!rts51x) {
printk(KERN_WARNING RTS51X_TIP
"Unable to allocate rts51x_usb\n");
return -ENOMEM;
}
/*
* Ask the SCSI layer to allocate a host structure, with extra
* space at the end for our private us_data structure.
*/
host = scsi_host_alloc(&rts51x_host_template, sizeof(*chip));
if (!host) {
printk(KERN_WARNING RTS51X_TIP
"Unable to allocate the scsi host\n");
kfree(rts51x);
return -ENOMEM;
}
/*
* Allow 16-byte CDBs and thus > 2TB
*/
host->max_cmd_len = 16;
chip = host_to_rts51x(host);
memset(chip, 0, sizeof(struct rts51x_chip));
chip->vendor_id = id->idVendor;
chip->product_id = id->idProduct;
mutex_init(&(rts51x->dev_mutex));
init_completion(&rts51x->cmnd_ready);
init_completion(&rts51x->control_exit);
init_completion(&rts51x->polling_exit);
init_completion(&(rts51x->notify));
#ifdef SCSI_SCAN_DELAY
init_waitqueue_head(&rts51x->delay_wait);
init_completion(&rts51x->scanning_done);
#endif
chip->usb = rts51x;
/* Associate the us_data structure with the USB device */
result = associate_dev(chip, intf);
if (result)
goto BadDevice;
/* Find the endpoints and calculate pipe values */
result = get_pipes(chip);
if (result)
goto BadDevice;
/* Acquire all the other resources and add the host */
result = rts51x_acquire_resources(chip);
if (result)
goto BadDevice;
/* Start up our control thread */
th = kthread_run(rts51x_control_thread, chip, RTS51X_CTL_THREAD);
if (IS_ERR(th)) {
printk(KERN_WARNING RTS51X_TIP
"Unable to start control thread\n");
result = PTR_ERR(th);
goto BadDevice;
}
rts51x->ctl_thread = th;
result = scsi_add_host(rts51x_to_host(chip), &rts51x->pusb_intf->dev);
if (result) {
printk(KERN_WARNING RTS51X_TIP "Unable to add the scsi host\n");
goto BadDevice;
}
#ifdef SCSI_SCAN_DELAY
/* Start up the thread for delayed SCSI-device scanning */
th = kthread_create(rts51x_scan_thread, chip, RTS51X_SCAN_THREAD);
if (IS_ERR(th)) {
printk(KERN_WARNING RTS51X_TIP
"Unable to start the device-scanning thread\n");
complete(&rts51x->scanning_done);
quiesce_and_remove_host(chip);
result = PTR_ERR(th);
goto BadDevice;
}
wake_up_process(th);
#else
scsi_scan_host(rts51x_to_host(chip));
#endif
/* Start up our polling thread */
th = kthread_run(rts51x_polling_thread, chip, RTS51X_POLLING_THREAD);
if (IS_ERR(th)) {
printk(KERN_WARNING RTS51X_TIP
"Unable to start polling thread\n");
result = PTR_ERR(th);
goto BadDevice;
}
rts51x->polling_thread = th;
#ifdef CONFIG_PM
if (ss_en) {
rts51x->pusb_intf->needs_remote_wakeup = needs_remote_wakeup;
SET_PM_USAGE_CNT(chip, 1);
RTS51X_DEBUGP("pm_usage_cnt = %d\n", GET_PM_USAGE_CNT(chip));
}
#endif
return 0;
/* We come here if there are any problems */
BadDevice:
RTS51X_DEBUGP("rts51x_probe() failed\n");
release_everything(chip);
return result;
}
static void rts51x_disconnect(struct usb_interface *intf)
{
struct rts51x_chip *chip = (struct rts51x_chip *)usb_get_intfdata(intf);
RTS51X_DEBUGP("rts51x_disconnect() called\n");
quiesce_and_remove_host(chip);
release_everything(chip);
}
/***********************************************************************
* Initialization and registration
***********************************************************************/
struct usb_device_id rts5139_usb_ids[] = {
{USB_DEVICE(0x0BDA, 0x0139)},
{USB_DEVICE(0x0BDA, 0x0129)},
{} /* Terminating entry */
};
EXPORT_SYMBOL_GPL(rts5139_usb_ids);
MODULE_DEVICE_TABLE(usb, rts5139_usb_ids);
struct usb_driver rts51x_driver = {
.name = RTS51X_NAME,
.probe = rts51x_probe,
.disconnect = rts51x_disconnect,
.suspend = rts51x_suspend,
.resume = rts51x_resume,
.reset_resume = rts51x_reset_resume,
.pre_reset = rts51x_pre_reset,
.post_reset = rts51x_post_reset,
.id_table = rts5139_usb_ids,
.soft_unbind = 1,
};
module_usb_driver(rts51x_driver);
| gpl-2.0 |
Negamann303/kernel-nk1-negalite-lt02ltespr | drivers/w1/slaves/w1_ds2780.c | 5155 | 4378 | /*
* 1-Wire implementation for the ds2780 chip
*
* Copyright (C) 2010 Indesign, LLC
*
* Author: Clifton Barnes <cabarnes@indesign-llc.com>
*
* Based on w1-ds2760 driver
*
* 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/device.h>
#include <linux/types.h>
#include <linux/platform_device.h>
#include <linux/mutex.h>
#include <linux/idr.h>
#include "../w1.h"
#include "../w1_int.h"
#include "../w1_family.h"
#include "w1_ds2780.h"
static int w1_ds2780_do_io(struct device *dev, char *buf, int addr,
size_t count, int io)
{
struct w1_slave *sl = container_of(dev, struct w1_slave, dev);
if (addr > DS2780_DATA_SIZE || addr < 0)
return 0;
count = min_t(int, count, DS2780_DATA_SIZE - addr);
if (w1_reset_select_slave(sl) == 0) {
if (io) {
w1_write_8(sl->master, W1_DS2780_WRITE_DATA);
w1_write_8(sl->master, addr);
w1_write_block(sl->master, buf, count);
} else {
w1_write_8(sl->master, W1_DS2780_READ_DATA);
w1_write_8(sl->master, addr);
count = w1_read_block(sl->master, buf, count);
}
}
return count;
}
int w1_ds2780_io(struct device *dev, char *buf, int addr, size_t count,
int io)
{
struct w1_slave *sl = container_of(dev, struct w1_slave, dev);
int ret;
if (!dev)
return -ENODEV;
mutex_lock(&sl->master->mutex);
ret = w1_ds2780_do_io(dev, buf, addr, count, io);
mutex_unlock(&sl->master->mutex);
return ret;
}
EXPORT_SYMBOL(w1_ds2780_io);
int w1_ds2780_io_nolock(struct device *dev, char *buf, int addr, size_t count,
int io)
{
int ret;
if (!dev)
return -ENODEV;
ret = w1_ds2780_do_io(dev, buf, addr, count, io);
return ret;
}
EXPORT_SYMBOL(w1_ds2780_io_nolock);
int w1_ds2780_eeprom_cmd(struct device *dev, int addr, int cmd)
{
struct w1_slave *sl = container_of(dev, struct w1_slave, dev);
if (!dev)
return -EINVAL;
mutex_lock(&sl->master->mutex);
if (w1_reset_select_slave(sl) == 0) {
w1_write_8(sl->master, cmd);
w1_write_8(sl->master, addr);
}
mutex_unlock(&sl->master->mutex);
return 0;
}
EXPORT_SYMBOL(w1_ds2780_eeprom_cmd);
static ssize_t w1_ds2780_read_bin(struct file *filp,
struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
return w1_ds2780_io(dev, buf, off, count, 0);
}
static struct bin_attribute w1_ds2780_bin_attr = {
.attr = {
.name = "w1_slave",
.mode = S_IRUGO,
},
.size = DS2780_DATA_SIZE,
.read = w1_ds2780_read_bin,
};
static DEFINE_IDA(bat_ida);
static int w1_ds2780_add_slave(struct w1_slave *sl)
{
int ret;
int id;
struct platform_device *pdev;
id = ida_simple_get(&bat_ida, 0, 0, GFP_KERNEL);
if (id < 0) {
ret = id;
goto noid;
}
pdev = platform_device_alloc("ds2780-battery", id);
if (!pdev) {
ret = -ENOMEM;
goto pdev_alloc_failed;
}
pdev->dev.parent = &sl->dev;
ret = platform_device_add(pdev);
if (ret)
goto pdev_add_failed;
ret = sysfs_create_bin_file(&sl->dev.kobj, &w1_ds2780_bin_attr);
if (ret)
goto bin_attr_failed;
dev_set_drvdata(&sl->dev, pdev);
return 0;
bin_attr_failed:
pdev_add_failed:
platform_device_unregister(pdev);
pdev_alloc_failed:
ida_simple_remove(&bat_ida, id);
noid:
return ret;
}
static void w1_ds2780_remove_slave(struct w1_slave *sl)
{
struct platform_device *pdev = dev_get_drvdata(&sl->dev);
int id = pdev->id;
platform_device_unregister(pdev);
ida_simple_remove(&bat_ida, id);
sysfs_remove_bin_file(&sl->dev.kobj, &w1_ds2780_bin_attr);
}
static struct w1_family_ops w1_ds2780_fops = {
.add_slave = w1_ds2780_add_slave,
.remove_slave = w1_ds2780_remove_slave,
};
static struct w1_family w1_ds2780_family = {
.fid = W1_FAMILY_DS2780,
.fops = &w1_ds2780_fops,
};
static int __init w1_ds2780_init(void)
{
ida_init(&bat_ida);
return w1_register_family(&w1_ds2780_family);
}
static void __exit w1_ds2780_exit(void)
{
w1_unregister_family(&w1_ds2780_family);
ida_destroy(&bat_ida);
}
module_init(w1_ds2780_init);
module_exit(w1_ds2780_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Clifton Barnes <cabarnes@indesign-llc.com>");
MODULE_DESCRIPTION("1-wire Driver for Maxim/Dallas DS2780 Stand-Alone Fuel Gauge IC");
| gpl-2.0 |
rogersb11/Shift | drivers/gpu/drm/nouveau/nv04_graph.c | 5923 | 38059 | /*
* Copyright 2007 Stephane Marchesin
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "drmP.h"
#include "drm.h"
#include "nouveau_drm.h"
#include "nouveau_drv.h"
#include "nouveau_hw.h"
#include "nouveau_util.h"
#include "nouveau_ramht.h"
struct nv04_graph_engine {
struct nouveau_exec_engine base;
};
static uint32_t nv04_graph_ctx_regs[] = {
0x0040053c,
0x00400544,
0x00400540,
0x00400548,
NV04_PGRAPH_CTX_SWITCH1,
NV04_PGRAPH_CTX_SWITCH2,
NV04_PGRAPH_CTX_SWITCH3,
NV04_PGRAPH_CTX_SWITCH4,
NV04_PGRAPH_CTX_CACHE1,
NV04_PGRAPH_CTX_CACHE2,
NV04_PGRAPH_CTX_CACHE3,
NV04_PGRAPH_CTX_CACHE4,
0x00400184,
0x004001a4,
0x004001c4,
0x004001e4,
0x00400188,
0x004001a8,
0x004001c8,
0x004001e8,
0x0040018c,
0x004001ac,
0x004001cc,
0x004001ec,
0x00400190,
0x004001b0,
0x004001d0,
0x004001f0,
0x00400194,
0x004001b4,
0x004001d4,
0x004001f4,
0x00400198,
0x004001b8,
0x004001d8,
0x004001f8,
0x0040019c,
0x004001bc,
0x004001dc,
0x004001fc,
0x00400174,
NV04_PGRAPH_DMA_START_0,
NV04_PGRAPH_DMA_START_1,
NV04_PGRAPH_DMA_LENGTH,
NV04_PGRAPH_DMA_MISC,
NV04_PGRAPH_DMA_PITCH,
NV04_PGRAPH_BOFFSET0,
NV04_PGRAPH_BBASE0,
NV04_PGRAPH_BLIMIT0,
NV04_PGRAPH_BOFFSET1,
NV04_PGRAPH_BBASE1,
NV04_PGRAPH_BLIMIT1,
NV04_PGRAPH_BOFFSET2,
NV04_PGRAPH_BBASE2,
NV04_PGRAPH_BLIMIT2,
NV04_PGRAPH_BOFFSET3,
NV04_PGRAPH_BBASE3,
NV04_PGRAPH_BLIMIT3,
NV04_PGRAPH_BOFFSET4,
NV04_PGRAPH_BBASE4,
NV04_PGRAPH_BLIMIT4,
NV04_PGRAPH_BOFFSET5,
NV04_PGRAPH_BBASE5,
NV04_PGRAPH_BLIMIT5,
NV04_PGRAPH_BPITCH0,
NV04_PGRAPH_BPITCH1,
NV04_PGRAPH_BPITCH2,
NV04_PGRAPH_BPITCH3,
NV04_PGRAPH_BPITCH4,
NV04_PGRAPH_SURFACE,
NV04_PGRAPH_STATE,
NV04_PGRAPH_BSWIZZLE2,
NV04_PGRAPH_BSWIZZLE5,
NV04_PGRAPH_BPIXEL,
NV04_PGRAPH_NOTIFY,
NV04_PGRAPH_PATT_COLOR0,
NV04_PGRAPH_PATT_COLOR1,
NV04_PGRAPH_PATT_COLORRAM+0x00,
NV04_PGRAPH_PATT_COLORRAM+0x04,
NV04_PGRAPH_PATT_COLORRAM+0x08,
NV04_PGRAPH_PATT_COLORRAM+0x0c,
NV04_PGRAPH_PATT_COLORRAM+0x10,
NV04_PGRAPH_PATT_COLORRAM+0x14,
NV04_PGRAPH_PATT_COLORRAM+0x18,
NV04_PGRAPH_PATT_COLORRAM+0x1c,
NV04_PGRAPH_PATT_COLORRAM+0x20,
NV04_PGRAPH_PATT_COLORRAM+0x24,
NV04_PGRAPH_PATT_COLORRAM+0x28,
NV04_PGRAPH_PATT_COLORRAM+0x2c,
NV04_PGRAPH_PATT_COLORRAM+0x30,
NV04_PGRAPH_PATT_COLORRAM+0x34,
NV04_PGRAPH_PATT_COLORRAM+0x38,
NV04_PGRAPH_PATT_COLORRAM+0x3c,
NV04_PGRAPH_PATT_COLORRAM+0x40,
NV04_PGRAPH_PATT_COLORRAM+0x44,
NV04_PGRAPH_PATT_COLORRAM+0x48,
NV04_PGRAPH_PATT_COLORRAM+0x4c,
NV04_PGRAPH_PATT_COLORRAM+0x50,
NV04_PGRAPH_PATT_COLORRAM+0x54,
NV04_PGRAPH_PATT_COLORRAM+0x58,
NV04_PGRAPH_PATT_COLORRAM+0x5c,
NV04_PGRAPH_PATT_COLORRAM+0x60,
NV04_PGRAPH_PATT_COLORRAM+0x64,
NV04_PGRAPH_PATT_COLORRAM+0x68,
NV04_PGRAPH_PATT_COLORRAM+0x6c,
NV04_PGRAPH_PATT_COLORRAM+0x70,
NV04_PGRAPH_PATT_COLORRAM+0x74,
NV04_PGRAPH_PATT_COLORRAM+0x78,
NV04_PGRAPH_PATT_COLORRAM+0x7c,
NV04_PGRAPH_PATT_COLORRAM+0x80,
NV04_PGRAPH_PATT_COLORRAM+0x84,
NV04_PGRAPH_PATT_COLORRAM+0x88,
NV04_PGRAPH_PATT_COLORRAM+0x8c,
NV04_PGRAPH_PATT_COLORRAM+0x90,
NV04_PGRAPH_PATT_COLORRAM+0x94,
NV04_PGRAPH_PATT_COLORRAM+0x98,
NV04_PGRAPH_PATT_COLORRAM+0x9c,
NV04_PGRAPH_PATT_COLORRAM+0xa0,
NV04_PGRAPH_PATT_COLORRAM+0xa4,
NV04_PGRAPH_PATT_COLORRAM+0xa8,
NV04_PGRAPH_PATT_COLORRAM+0xac,
NV04_PGRAPH_PATT_COLORRAM+0xb0,
NV04_PGRAPH_PATT_COLORRAM+0xb4,
NV04_PGRAPH_PATT_COLORRAM+0xb8,
NV04_PGRAPH_PATT_COLORRAM+0xbc,
NV04_PGRAPH_PATT_COLORRAM+0xc0,
NV04_PGRAPH_PATT_COLORRAM+0xc4,
NV04_PGRAPH_PATT_COLORRAM+0xc8,
NV04_PGRAPH_PATT_COLORRAM+0xcc,
NV04_PGRAPH_PATT_COLORRAM+0xd0,
NV04_PGRAPH_PATT_COLORRAM+0xd4,
NV04_PGRAPH_PATT_COLORRAM+0xd8,
NV04_PGRAPH_PATT_COLORRAM+0xdc,
NV04_PGRAPH_PATT_COLORRAM+0xe0,
NV04_PGRAPH_PATT_COLORRAM+0xe4,
NV04_PGRAPH_PATT_COLORRAM+0xe8,
NV04_PGRAPH_PATT_COLORRAM+0xec,
NV04_PGRAPH_PATT_COLORRAM+0xf0,
NV04_PGRAPH_PATT_COLORRAM+0xf4,
NV04_PGRAPH_PATT_COLORRAM+0xf8,
NV04_PGRAPH_PATT_COLORRAM+0xfc,
NV04_PGRAPH_PATTERN,
0x0040080c,
NV04_PGRAPH_PATTERN_SHAPE,
0x00400600,
NV04_PGRAPH_ROP3,
NV04_PGRAPH_CHROMA,
NV04_PGRAPH_BETA_AND,
NV04_PGRAPH_BETA_PREMULT,
NV04_PGRAPH_CONTROL0,
NV04_PGRAPH_CONTROL1,
NV04_PGRAPH_CONTROL2,
NV04_PGRAPH_BLEND,
NV04_PGRAPH_STORED_FMT,
NV04_PGRAPH_SOURCE_COLOR,
0x00400560,
0x00400568,
0x00400564,
0x0040056c,
0x00400400,
0x00400480,
0x00400404,
0x00400484,
0x00400408,
0x00400488,
0x0040040c,
0x0040048c,
0x00400410,
0x00400490,
0x00400414,
0x00400494,
0x00400418,
0x00400498,
0x0040041c,
0x0040049c,
0x00400420,
0x004004a0,
0x00400424,
0x004004a4,
0x00400428,
0x004004a8,
0x0040042c,
0x004004ac,
0x00400430,
0x004004b0,
0x00400434,
0x004004b4,
0x00400438,
0x004004b8,
0x0040043c,
0x004004bc,
0x00400440,
0x004004c0,
0x00400444,
0x004004c4,
0x00400448,
0x004004c8,
0x0040044c,
0x004004cc,
0x00400450,
0x004004d0,
0x00400454,
0x004004d4,
0x00400458,
0x004004d8,
0x0040045c,
0x004004dc,
0x00400460,
0x004004e0,
0x00400464,
0x004004e4,
0x00400468,
0x004004e8,
0x0040046c,
0x004004ec,
0x00400470,
0x004004f0,
0x00400474,
0x004004f4,
0x00400478,
0x004004f8,
0x0040047c,
0x004004fc,
0x00400534,
0x00400538,
0x00400514,
0x00400518,
0x0040051c,
0x00400520,
0x00400524,
0x00400528,
0x0040052c,
0x00400530,
0x00400d00,
0x00400d40,
0x00400d80,
0x00400d04,
0x00400d44,
0x00400d84,
0x00400d08,
0x00400d48,
0x00400d88,
0x00400d0c,
0x00400d4c,
0x00400d8c,
0x00400d10,
0x00400d50,
0x00400d90,
0x00400d14,
0x00400d54,
0x00400d94,
0x00400d18,
0x00400d58,
0x00400d98,
0x00400d1c,
0x00400d5c,
0x00400d9c,
0x00400d20,
0x00400d60,
0x00400da0,
0x00400d24,
0x00400d64,
0x00400da4,
0x00400d28,
0x00400d68,
0x00400da8,
0x00400d2c,
0x00400d6c,
0x00400dac,
0x00400d30,
0x00400d70,
0x00400db0,
0x00400d34,
0x00400d74,
0x00400db4,
0x00400d38,
0x00400d78,
0x00400db8,
0x00400d3c,
0x00400d7c,
0x00400dbc,
0x00400590,
0x00400594,
0x00400598,
0x0040059c,
0x004005a8,
0x004005ac,
0x004005b0,
0x004005b4,
0x004005c0,
0x004005c4,
0x004005c8,
0x004005cc,
0x004005d0,
0x004005d4,
0x004005d8,
0x004005dc,
0x004005e0,
NV04_PGRAPH_PASSTHRU_0,
NV04_PGRAPH_PASSTHRU_1,
NV04_PGRAPH_PASSTHRU_2,
NV04_PGRAPH_DVD_COLORFMT,
NV04_PGRAPH_SCALED_FORMAT,
NV04_PGRAPH_MISC24_0,
NV04_PGRAPH_MISC24_1,
NV04_PGRAPH_MISC24_2,
0x00400500,
0x00400504,
NV04_PGRAPH_VALID1,
NV04_PGRAPH_VALID2,
NV04_PGRAPH_DEBUG_3
};
struct graph_state {
uint32_t nv04[ARRAY_SIZE(nv04_graph_ctx_regs)];
};
static struct nouveau_channel *
nv04_graph_channel(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
int chid = dev_priv->engine.fifo.channels;
if (nv_rd32(dev, NV04_PGRAPH_CTX_CONTROL) & 0x00010000)
chid = nv_rd32(dev, NV04_PGRAPH_CTX_USER) >> 24;
if (chid >= dev_priv->engine.fifo.channels)
return NULL;
return dev_priv->channels.ptr[chid];
}
static uint32_t *ctx_reg(struct graph_state *ctx, uint32_t reg)
{
int i;
for (i = 0; i < ARRAY_SIZE(nv04_graph_ctx_regs); i++) {
if (nv04_graph_ctx_regs[i] == reg)
return &ctx->nv04[i];
}
return NULL;
}
static int
nv04_graph_load_context(struct nouveau_channel *chan)
{
struct graph_state *pgraph_ctx = chan->engctx[NVOBJ_ENGINE_GR];
struct drm_device *dev = chan->dev;
uint32_t tmp;
int i;
for (i = 0; i < ARRAY_SIZE(nv04_graph_ctx_regs); i++)
nv_wr32(dev, nv04_graph_ctx_regs[i], pgraph_ctx->nv04[i]);
nv_wr32(dev, NV04_PGRAPH_CTX_CONTROL, 0x10010100);
tmp = nv_rd32(dev, NV04_PGRAPH_CTX_USER) & 0x00ffffff;
nv_wr32(dev, NV04_PGRAPH_CTX_USER, tmp | chan->id << 24);
tmp = nv_rd32(dev, NV04_PGRAPH_FFINTFC_ST2);
nv_wr32(dev, NV04_PGRAPH_FFINTFC_ST2, tmp & 0x000fffff);
return 0;
}
static int
nv04_graph_unload_context(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_channel *chan = NULL;
struct graph_state *ctx;
uint32_t tmp;
int i;
chan = nv04_graph_channel(dev);
if (!chan)
return 0;
ctx = chan->engctx[NVOBJ_ENGINE_GR];
for (i = 0; i < ARRAY_SIZE(nv04_graph_ctx_regs); i++)
ctx->nv04[i] = nv_rd32(dev, nv04_graph_ctx_regs[i]);
nv_wr32(dev, NV04_PGRAPH_CTX_CONTROL, 0x10000000);
tmp = nv_rd32(dev, NV04_PGRAPH_CTX_USER) & 0x00ffffff;
tmp |= (dev_priv->engine.fifo.channels - 1) << 24;
nv_wr32(dev, NV04_PGRAPH_CTX_USER, tmp);
return 0;
}
static int
nv04_graph_context_new(struct nouveau_channel *chan, int engine)
{
struct graph_state *pgraph_ctx;
NV_DEBUG(chan->dev, "nv04_graph_context_create %d\n", chan->id);
pgraph_ctx = kzalloc(sizeof(*pgraph_ctx), GFP_KERNEL);
if (pgraph_ctx == NULL)
return -ENOMEM;
*ctx_reg(pgraph_ctx, NV04_PGRAPH_DEBUG_3) = 0xfad4ff31;
chan->engctx[engine] = pgraph_ctx;
return 0;
}
static void
nv04_graph_context_del(struct nouveau_channel *chan, int engine)
{
struct drm_device *dev = chan->dev;
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct graph_state *pgraph_ctx = chan->engctx[engine];
unsigned long flags;
spin_lock_irqsave(&dev_priv->context_switch_lock, flags);
nv_mask(dev, NV04_PGRAPH_FIFO, 0x00000001, 0x00000000);
/* Unload the context if it's the currently active one */
if (nv04_graph_channel(dev) == chan)
nv04_graph_unload_context(dev);
nv_mask(dev, NV04_PGRAPH_FIFO, 0x00000001, 0x00000001);
spin_unlock_irqrestore(&dev_priv->context_switch_lock, flags);
/* Free the context resources */
kfree(pgraph_ctx);
chan->engctx[engine] = NULL;
}
int
nv04_graph_object_new(struct nouveau_channel *chan, int engine,
u32 handle, u16 class)
{
struct drm_device *dev = chan->dev;
struct nouveau_gpuobj *obj = NULL;
int ret;
ret = nouveau_gpuobj_new(dev, chan, 16, 16, NVOBJ_FLAG_ZERO_FREE, &obj);
if (ret)
return ret;
obj->engine = 1;
obj->class = class;
#ifdef __BIG_ENDIAN
nv_wo32(obj, 0x00, 0x00080000 | class);
#else
nv_wo32(obj, 0x00, class);
#endif
nv_wo32(obj, 0x04, 0x00000000);
nv_wo32(obj, 0x08, 0x00000000);
nv_wo32(obj, 0x0c, 0x00000000);
ret = nouveau_ramht_insert(chan, handle, obj);
nouveau_gpuobj_ref(NULL, &obj);
return ret;
}
static int
nv04_graph_init(struct drm_device *dev, int engine)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
uint32_t tmp;
nv_wr32(dev, NV03_PMC_ENABLE, nv_rd32(dev, NV03_PMC_ENABLE) &
~NV_PMC_ENABLE_PGRAPH);
nv_wr32(dev, NV03_PMC_ENABLE, nv_rd32(dev, NV03_PMC_ENABLE) |
NV_PMC_ENABLE_PGRAPH);
/* Enable PGRAPH interrupts */
nv_wr32(dev, NV03_PGRAPH_INTR, 0xFFFFFFFF);
nv_wr32(dev, NV03_PGRAPH_INTR_EN, 0xFFFFFFFF);
nv_wr32(dev, NV04_PGRAPH_VALID1, 0);
nv_wr32(dev, NV04_PGRAPH_VALID2, 0);
/*nv_wr32(dev, NV04_PGRAPH_DEBUG_0, 0x000001FF);
nv_wr32(dev, NV04_PGRAPH_DEBUG_0, 0x001FFFFF);*/
nv_wr32(dev, NV04_PGRAPH_DEBUG_0, 0x1231c000);
/*1231C000 blob, 001 haiku*/
/*V_WRITE(NV04_PGRAPH_DEBUG_1, 0xf2d91100);*/
nv_wr32(dev, NV04_PGRAPH_DEBUG_1, 0x72111100);
/*0x72111100 blob , 01 haiku*/
/*nv_wr32(dev, NV04_PGRAPH_DEBUG_2, 0x11d5f870);*/
nv_wr32(dev, NV04_PGRAPH_DEBUG_2, 0x11d5f071);
/*haiku same*/
/*nv_wr32(dev, NV04_PGRAPH_DEBUG_3, 0xfad4ff31);*/
nv_wr32(dev, NV04_PGRAPH_DEBUG_3, 0xf0d4ff31);
/*haiku and blob 10d4*/
nv_wr32(dev, NV04_PGRAPH_STATE , 0xFFFFFFFF);
nv_wr32(dev, NV04_PGRAPH_CTX_CONTROL , 0x10000100);
tmp = nv_rd32(dev, NV04_PGRAPH_CTX_USER) & 0x00ffffff;
tmp |= (dev_priv->engine.fifo.channels - 1) << 24;
nv_wr32(dev, NV04_PGRAPH_CTX_USER, tmp);
/* These don't belong here, they're part of a per-channel context */
nv_wr32(dev, NV04_PGRAPH_PATTERN_SHAPE, 0x00000000);
nv_wr32(dev, NV04_PGRAPH_BETA_AND , 0xFFFFFFFF);
return 0;
}
static int
nv04_graph_fini(struct drm_device *dev, int engine, bool suspend)
{
nv_mask(dev, NV04_PGRAPH_FIFO, 0x00000001, 0x00000000);
if (!nv_wait(dev, NV04_PGRAPH_STATUS, ~0, 0) && suspend) {
nv_mask(dev, NV04_PGRAPH_FIFO, 0x00000001, 0x00000001);
return -EBUSY;
}
nv04_graph_unload_context(dev);
nv_wr32(dev, NV03_PGRAPH_INTR_EN, 0x00000000);
return 0;
}
static int
nv04_graph_mthd_set_ref(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
atomic_set(&chan->fence.last_sequence_irq, data);
return 0;
}
int
nv04_graph_mthd_page_flip(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
struct drm_device *dev = chan->dev;
struct nouveau_page_flip_state s;
if (!nouveau_finish_page_flip(chan, &s))
nv_set_crtc_base(dev, s.crtc,
s.offset + s.y * s.pitch + s.x * s.bpp / 8);
return 0;
}
/*
* Software methods, why they are needed, and how they all work:
*
* NV04 and NV05 keep most of the state in PGRAPH context itself, but some
* 2d engine settings are kept inside the grobjs themselves. The grobjs are
* 3 words long on both. grobj format on NV04 is:
*
* word 0:
* - bits 0-7: class
* - bit 12: color key active
* - bit 13: clip rect active
* - bit 14: if set, destination surface is swizzled and taken from buffer 5
* [set by NV04_SWIZZLED_SURFACE], otherwise it's linear and taken
* from buffer 0 [set by NV04_CONTEXT_SURFACES_2D or
* NV03_CONTEXT_SURFACE_DST].
* - bits 15-17: 2d operation [aka patch config]
* - bit 24: patch valid [enables rendering using this object]
* - bit 25: surf3d valid [for tex_tri and multitex_tri only]
* word 1:
* - bits 0-1: mono format
* - bits 8-13: color format
* - bits 16-31: DMA_NOTIFY instance
* word 2:
* - bits 0-15: DMA_A instance
* - bits 16-31: DMA_B instance
*
* On NV05 it's:
*
* word 0:
* - bits 0-7: class
* - bit 12: color key active
* - bit 13: clip rect active
* - bit 14: if set, destination surface is swizzled and taken from buffer 5
* [set by NV04_SWIZZLED_SURFACE], otherwise it's linear and taken
* from buffer 0 [set by NV04_CONTEXT_SURFACES_2D or
* NV03_CONTEXT_SURFACE_DST].
* - bits 15-17: 2d operation [aka patch config]
* - bits 20-22: dither mode
* - bit 24: patch valid [enables rendering using this object]
* - bit 25: surface_dst/surface_color/surf2d/surf3d valid
* - bit 26: surface_src/surface_zeta valid
* - bit 27: pattern valid
* - bit 28: rop valid
* - bit 29: beta1 valid
* - bit 30: beta4 valid
* word 1:
* - bits 0-1: mono format
* - bits 8-13: color format
* - bits 16-31: DMA_NOTIFY instance
* word 2:
* - bits 0-15: DMA_A instance
* - bits 16-31: DMA_B instance
*
* NV05 will set/unset the relevant valid bits when you poke the relevant
* object-binding methods with object of the proper type, or with the NULL
* type. It'll only allow rendering using the grobj if all needed objects
* are bound. The needed set of objects depends on selected operation: for
* example rop object is needed by ROP_AND, but not by SRCCOPY_AND.
*
* NV04 doesn't have these methods implemented at all, and doesn't have the
* relevant bits in grobj. Instead, it'll allow rendering whenever bit 24
* is set. So we have to emulate them in software, internally keeping the
* same bits as NV05 does. Since grobjs are aligned to 16 bytes on nv04,
* but the last word isn't actually used for anything, we abuse it for this
* purpose.
*
* Actually, NV05 can optionally check bit 24 too, but we disable this since
* there's no use for it.
*
* For unknown reasons, NV04 implements surf3d binding in hardware as an
* exception. Also for unknown reasons, NV04 doesn't implement the clipping
* methods on the surf3d object, so we have to emulate them too.
*/
static void
nv04_graph_set_ctx1(struct nouveau_channel *chan, u32 mask, u32 value)
{
struct drm_device *dev = chan->dev;
u32 instance = (nv_rd32(dev, NV04_PGRAPH_CTX_SWITCH4) & 0xffff) << 4;
int subc = (nv_rd32(dev, NV04_PGRAPH_TRAPPED_ADDR) >> 13) & 0x7;
u32 tmp;
tmp = nv_ri32(dev, instance);
tmp &= ~mask;
tmp |= value;
nv_wi32(dev, instance, tmp);
nv_wr32(dev, NV04_PGRAPH_CTX_SWITCH1, tmp);
nv_wr32(dev, NV04_PGRAPH_CTX_CACHE1 + (subc<<2), tmp);
}
static void
nv04_graph_set_ctx_val(struct nouveau_channel *chan, u32 mask, u32 value)
{
struct drm_device *dev = chan->dev;
u32 instance = (nv_rd32(dev, NV04_PGRAPH_CTX_SWITCH4) & 0xffff) << 4;
u32 tmp, ctx1;
int class, op, valid = 1;
ctx1 = nv_ri32(dev, instance);
class = ctx1 & 0xff;
op = (ctx1 >> 15) & 7;
tmp = nv_ri32(dev, instance + 0xc);
tmp &= ~mask;
tmp |= value;
nv_wi32(dev, instance + 0xc, tmp);
/* check for valid surf2d/surf_dst/surf_color */
if (!(tmp & 0x02000000))
valid = 0;
/* check for valid surf_src/surf_zeta */
if ((class == 0x1f || class == 0x48) && !(tmp & 0x04000000))
valid = 0;
switch (op) {
/* SRCCOPY_AND, SRCCOPY: no extra objects required */
case 0:
case 3:
break;
/* ROP_AND: requires pattern and rop */
case 1:
if (!(tmp & 0x18000000))
valid = 0;
break;
/* BLEND_AND: requires beta1 */
case 2:
if (!(tmp & 0x20000000))
valid = 0;
break;
/* SRCCOPY_PREMULT, BLEND_PREMULT: beta4 required */
case 4:
case 5:
if (!(tmp & 0x40000000))
valid = 0;
break;
}
nv04_graph_set_ctx1(chan, 0x01000000, valid << 24);
}
static int
nv04_graph_mthd_set_operation(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
if (data > 5)
return 1;
/* Old versions of the objects only accept first three operations. */
if (data > 2 && class < 0x40)
return 1;
nv04_graph_set_ctx1(chan, 0x00038000, data << 15);
/* changing operation changes set of objects needed for validation */
nv04_graph_set_ctx_val(chan, 0, 0);
return 0;
}
static int
nv04_graph_mthd_surf3d_clip_h(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
uint32_t min = data & 0xffff, max;
uint32_t w = data >> 16;
if (min & 0x8000)
/* too large */
return 1;
if (w & 0x8000)
/* yes, it accepts negative for some reason. */
w |= 0xffff0000;
max = min + w;
max &= 0x3ffff;
nv_wr32(chan->dev, 0x40053c, min);
nv_wr32(chan->dev, 0x400544, max);
return 0;
}
static int
nv04_graph_mthd_surf3d_clip_v(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
uint32_t min = data & 0xffff, max;
uint32_t w = data >> 16;
if (min & 0x8000)
/* too large */
return 1;
if (w & 0x8000)
/* yes, it accepts negative for some reason. */
w |= 0xffff0000;
max = min + w;
max &= 0x3ffff;
nv_wr32(chan->dev, 0x400540, min);
nv_wr32(chan->dev, 0x400548, max);
return 0;
}
static int
nv04_graph_mthd_bind_surf2d(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
switch (nv_ri32(chan->dev, data << 4) & 0xff) {
case 0x30:
nv04_graph_set_ctx1(chan, 0x00004000, 0);
nv04_graph_set_ctx_val(chan, 0x02000000, 0);
return 0;
case 0x42:
nv04_graph_set_ctx1(chan, 0x00004000, 0);
nv04_graph_set_ctx_val(chan, 0x02000000, 0x02000000);
return 0;
}
return 1;
}
static int
nv04_graph_mthd_bind_surf2d_swzsurf(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
switch (nv_ri32(chan->dev, data << 4) & 0xff) {
case 0x30:
nv04_graph_set_ctx1(chan, 0x00004000, 0);
nv04_graph_set_ctx_val(chan, 0x02000000, 0);
return 0;
case 0x42:
nv04_graph_set_ctx1(chan, 0x00004000, 0);
nv04_graph_set_ctx_val(chan, 0x02000000, 0x02000000);
return 0;
case 0x52:
nv04_graph_set_ctx1(chan, 0x00004000, 0x00004000);
nv04_graph_set_ctx_val(chan, 0x02000000, 0x02000000);
return 0;
}
return 1;
}
static int
nv04_graph_mthd_bind_nv01_patt(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
switch (nv_ri32(chan->dev, data << 4) & 0xff) {
case 0x30:
nv04_graph_set_ctx_val(chan, 0x08000000, 0);
return 0;
case 0x18:
nv04_graph_set_ctx_val(chan, 0x08000000, 0x08000000);
return 0;
}
return 1;
}
static int
nv04_graph_mthd_bind_nv04_patt(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
switch (nv_ri32(chan->dev, data << 4) & 0xff) {
case 0x30:
nv04_graph_set_ctx_val(chan, 0x08000000, 0);
return 0;
case 0x44:
nv04_graph_set_ctx_val(chan, 0x08000000, 0x08000000);
return 0;
}
return 1;
}
static int
nv04_graph_mthd_bind_rop(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
switch (nv_ri32(chan->dev, data << 4) & 0xff) {
case 0x30:
nv04_graph_set_ctx_val(chan, 0x10000000, 0);
return 0;
case 0x43:
nv04_graph_set_ctx_val(chan, 0x10000000, 0x10000000);
return 0;
}
return 1;
}
static int
nv04_graph_mthd_bind_beta1(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
switch (nv_ri32(chan->dev, data << 4) & 0xff) {
case 0x30:
nv04_graph_set_ctx_val(chan, 0x20000000, 0);
return 0;
case 0x12:
nv04_graph_set_ctx_val(chan, 0x20000000, 0x20000000);
return 0;
}
return 1;
}
static int
nv04_graph_mthd_bind_beta4(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
switch (nv_ri32(chan->dev, data << 4) & 0xff) {
case 0x30:
nv04_graph_set_ctx_val(chan, 0x40000000, 0);
return 0;
case 0x72:
nv04_graph_set_ctx_val(chan, 0x40000000, 0x40000000);
return 0;
}
return 1;
}
static int
nv04_graph_mthd_bind_surf_dst(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
switch (nv_ri32(chan->dev, data << 4) & 0xff) {
case 0x30:
nv04_graph_set_ctx_val(chan, 0x02000000, 0);
return 0;
case 0x58:
nv04_graph_set_ctx_val(chan, 0x02000000, 0x02000000);
return 0;
}
return 1;
}
static int
nv04_graph_mthd_bind_surf_src(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
switch (nv_ri32(chan->dev, data << 4) & 0xff) {
case 0x30:
nv04_graph_set_ctx_val(chan, 0x04000000, 0);
return 0;
case 0x59:
nv04_graph_set_ctx_val(chan, 0x04000000, 0x04000000);
return 0;
}
return 1;
}
static int
nv04_graph_mthd_bind_surf_color(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
switch (nv_ri32(chan->dev, data << 4) & 0xff) {
case 0x30:
nv04_graph_set_ctx_val(chan, 0x02000000, 0);
return 0;
case 0x5a:
nv04_graph_set_ctx_val(chan, 0x02000000, 0x02000000);
return 0;
}
return 1;
}
static int
nv04_graph_mthd_bind_surf_zeta(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
switch (nv_ri32(chan->dev, data << 4) & 0xff) {
case 0x30:
nv04_graph_set_ctx_val(chan, 0x04000000, 0);
return 0;
case 0x5b:
nv04_graph_set_ctx_val(chan, 0x04000000, 0x04000000);
return 0;
}
return 1;
}
static int
nv04_graph_mthd_bind_clip(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
switch (nv_ri32(chan->dev, data << 4) & 0xff) {
case 0x30:
nv04_graph_set_ctx1(chan, 0x2000, 0);
return 0;
case 0x19:
nv04_graph_set_ctx1(chan, 0x2000, 0x2000);
return 0;
}
return 1;
}
static int
nv04_graph_mthd_bind_chroma(struct nouveau_channel *chan,
u32 class, u32 mthd, u32 data)
{
switch (nv_ri32(chan->dev, data << 4) & 0xff) {
case 0x30:
nv04_graph_set_ctx1(chan, 0x1000, 0);
return 0;
/* Yes, for some reason even the old versions of objects
* accept 0x57 and not 0x17. Consistency be damned.
*/
case 0x57:
nv04_graph_set_ctx1(chan, 0x1000, 0x1000);
return 0;
}
return 1;
}
static struct nouveau_bitfield nv04_graph_intr[] = {
{ NV_PGRAPH_INTR_NOTIFY, "NOTIFY" },
{}
};
static struct nouveau_bitfield nv04_graph_nstatus[] = {
{ NV04_PGRAPH_NSTATUS_STATE_IN_USE, "STATE_IN_USE" },
{ NV04_PGRAPH_NSTATUS_INVALID_STATE, "INVALID_STATE" },
{ NV04_PGRAPH_NSTATUS_BAD_ARGUMENT, "BAD_ARGUMENT" },
{ NV04_PGRAPH_NSTATUS_PROTECTION_FAULT, "PROTECTION_FAULT" },
{}
};
struct nouveau_bitfield nv04_graph_nsource[] = {
{ NV03_PGRAPH_NSOURCE_NOTIFICATION, "NOTIFICATION" },
{ NV03_PGRAPH_NSOURCE_DATA_ERROR, "DATA_ERROR" },
{ NV03_PGRAPH_NSOURCE_PROTECTION_ERROR, "PROTECTION_ERROR" },
{ NV03_PGRAPH_NSOURCE_RANGE_EXCEPTION, "RANGE_EXCEPTION" },
{ NV03_PGRAPH_NSOURCE_LIMIT_COLOR, "LIMIT_COLOR" },
{ NV03_PGRAPH_NSOURCE_LIMIT_ZETA, "LIMIT_ZETA" },
{ NV03_PGRAPH_NSOURCE_ILLEGAL_MTHD, "ILLEGAL_MTHD" },
{ NV03_PGRAPH_NSOURCE_DMA_R_PROTECTION, "DMA_R_PROTECTION" },
{ NV03_PGRAPH_NSOURCE_DMA_W_PROTECTION, "DMA_W_PROTECTION" },
{ NV03_PGRAPH_NSOURCE_FORMAT_EXCEPTION, "FORMAT_EXCEPTION" },
{ NV03_PGRAPH_NSOURCE_PATCH_EXCEPTION, "PATCH_EXCEPTION" },
{ NV03_PGRAPH_NSOURCE_STATE_INVALID, "STATE_INVALID" },
{ NV03_PGRAPH_NSOURCE_DOUBLE_NOTIFY, "DOUBLE_NOTIFY" },
{ NV03_PGRAPH_NSOURCE_NOTIFY_IN_USE, "NOTIFY_IN_USE" },
{ NV03_PGRAPH_NSOURCE_METHOD_CNT, "METHOD_CNT" },
{ NV03_PGRAPH_NSOURCE_BFR_NOTIFICATION, "BFR_NOTIFICATION" },
{ NV03_PGRAPH_NSOURCE_DMA_VTX_PROTECTION, "DMA_VTX_PROTECTION" },
{ NV03_PGRAPH_NSOURCE_DMA_WIDTH_A, "DMA_WIDTH_A" },
{ NV03_PGRAPH_NSOURCE_DMA_WIDTH_B, "DMA_WIDTH_B" },
{}
};
static void
nv04_graph_context_switch(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_channel *chan = NULL;
int chid;
nouveau_wait_for_idle(dev);
/* If previous context is valid, we need to save it */
nv04_graph_unload_context(dev);
/* Load context for next channel */
chid = dev_priv->engine.fifo.channel_id(dev);
chan = dev_priv->channels.ptr[chid];
if (chan)
nv04_graph_load_context(chan);
}
static void
nv04_graph_isr(struct drm_device *dev)
{
u32 stat;
while ((stat = nv_rd32(dev, NV03_PGRAPH_INTR))) {
u32 nsource = nv_rd32(dev, NV03_PGRAPH_NSOURCE);
u32 nstatus = nv_rd32(dev, NV03_PGRAPH_NSTATUS);
u32 addr = nv_rd32(dev, NV04_PGRAPH_TRAPPED_ADDR);
u32 chid = (addr & 0x0f000000) >> 24;
u32 subc = (addr & 0x0000e000) >> 13;
u32 mthd = (addr & 0x00001ffc);
u32 data = nv_rd32(dev, NV04_PGRAPH_TRAPPED_DATA);
u32 class = nv_rd32(dev, 0x400180 + subc * 4) & 0xff;
u32 show = stat;
if (stat & NV_PGRAPH_INTR_NOTIFY) {
if (nsource & NV03_PGRAPH_NSOURCE_ILLEGAL_MTHD) {
if (!nouveau_gpuobj_mthd_call2(dev, chid, class, mthd, data))
show &= ~NV_PGRAPH_INTR_NOTIFY;
}
}
if (stat & NV_PGRAPH_INTR_CONTEXT_SWITCH) {
nv_wr32(dev, NV03_PGRAPH_INTR, NV_PGRAPH_INTR_CONTEXT_SWITCH);
stat &= ~NV_PGRAPH_INTR_CONTEXT_SWITCH;
show &= ~NV_PGRAPH_INTR_CONTEXT_SWITCH;
nv04_graph_context_switch(dev);
}
nv_wr32(dev, NV03_PGRAPH_INTR, stat);
nv_wr32(dev, NV04_PGRAPH_FIFO, 0x00000001);
if (show && nouveau_ratelimit()) {
NV_INFO(dev, "PGRAPH -");
nouveau_bitfield_print(nv04_graph_intr, show);
printk(" nsource:");
nouveau_bitfield_print(nv04_graph_nsource, nsource);
printk(" nstatus:");
nouveau_bitfield_print(nv04_graph_nstatus, nstatus);
printk("\n");
NV_INFO(dev, "PGRAPH - ch %d/%d class 0x%04x "
"mthd 0x%04x data 0x%08x\n",
chid, subc, class, mthd, data);
}
}
}
static void
nv04_graph_destroy(struct drm_device *dev, int engine)
{
struct nv04_graph_engine *pgraph = nv_engine(dev, engine);
nouveau_irq_unregister(dev, 12);
NVOBJ_ENGINE_DEL(dev, GR);
kfree(pgraph);
}
int
nv04_graph_create(struct drm_device *dev)
{
struct nv04_graph_engine *pgraph;
pgraph = kzalloc(sizeof(*pgraph), GFP_KERNEL);
if (!pgraph)
return -ENOMEM;
pgraph->base.destroy = nv04_graph_destroy;
pgraph->base.init = nv04_graph_init;
pgraph->base.fini = nv04_graph_fini;
pgraph->base.context_new = nv04_graph_context_new;
pgraph->base.context_del = nv04_graph_context_del;
pgraph->base.object_new = nv04_graph_object_new;
NVOBJ_ENGINE_ADD(dev, GR, &pgraph->base);
nouveau_irq_register(dev, 12, nv04_graph_isr);
/* dvd subpicture */
NVOBJ_CLASS(dev, 0x0038, GR);
/* m2mf */
NVOBJ_CLASS(dev, 0x0039, GR);
/* nv03 gdirect */
NVOBJ_CLASS(dev, 0x004b, GR);
NVOBJ_MTHD (dev, 0x004b, 0x0184, nv04_graph_mthd_bind_nv01_patt);
NVOBJ_MTHD (dev, 0x004b, 0x0188, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x004b, 0x018c, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x004b, 0x0190, nv04_graph_mthd_bind_surf_dst);
NVOBJ_MTHD (dev, 0x004b, 0x02fc, nv04_graph_mthd_set_operation);
/* nv04 gdirect */
NVOBJ_CLASS(dev, 0x004a, GR);
NVOBJ_MTHD (dev, 0x004a, 0x0188, nv04_graph_mthd_bind_nv04_patt);
NVOBJ_MTHD (dev, 0x004a, 0x018c, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x004a, 0x0190, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x004a, 0x0194, nv04_graph_mthd_bind_beta4);
NVOBJ_MTHD (dev, 0x004a, 0x0198, nv04_graph_mthd_bind_surf2d);
NVOBJ_MTHD (dev, 0x004a, 0x02fc, nv04_graph_mthd_set_operation);
/* nv01 imageblit */
NVOBJ_CLASS(dev, 0x001f, GR);
NVOBJ_MTHD (dev, 0x001f, 0x0184, nv04_graph_mthd_bind_chroma);
NVOBJ_MTHD (dev, 0x001f, 0x0188, nv04_graph_mthd_bind_clip);
NVOBJ_MTHD (dev, 0x001f, 0x018c, nv04_graph_mthd_bind_nv01_patt);
NVOBJ_MTHD (dev, 0x001f, 0x0190, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x001f, 0x0194, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x001f, 0x0198, nv04_graph_mthd_bind_surf_dst);
NVOBJ_MTHD (dev, 0x001f, 0x019c, nv04_graph_mthd_bind_surf_src);
NVOBJ_MTHD (dev, 0x001f, 0x02fc, nv04_graph_mthd_set_operation);
/* nv04 imageblit */
NVOBJ_CLASS(dev, 0x005f, GR);
NVOBJ_MTHD (dev, 0x005f, 0x0184, nv04_graph_mthd_bind_chroma);
NVOBJ_MTHD (dev, 0x005f, 0x0188, nv04_graph_mthd_bind_clip);
NVOBJ_MTHD (dev, 0x005f, 0x018c, nv04_graph_mthd_bind_nv04_patt);
NVOBJ_MTHD (dev, 0x005f, 0x0190, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x005f, 0x0194, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x005f, 0x0198, nv04_graph_mthd_bind_beta4);
NVOBJ_MTHD (dev, 0x005f, 0x019c, nv04_graph_mthd_bind_surf2d);
NVOBJ_MTHD (dev, 0x005f, 0x02fc, nv04_graph_mthd_set_operation);
/* nv04 iifc */
NVOBJ_CLASS(dev, 0x0060, GR);
NVOBJ_MTHD (dev, 0x0060, 0x0188, nv04_graph_mthd_bind_chroma);
NVOBJ_MTHD (dev, 0x0060, 0x018c, nv04_graph_mthd_bind_clip);
NVOBJ_MTHD (dev, 0x0060, 0x0190, nv04_graph_mthd_bind_nv04_patt);
NVOBJ_MTHD (dev, 0x0060, 0x0194, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x0060, 0x0198, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x0060, 0x019c, nv04_graph_mthd_bind_beta4);
NVOBJ_MTHD (dev, 0x0060, 0x01a0, nv04_graph_mthd_bind_surf2d_swzsurf);
NVOBJ_MTHD (dev, 0x0060, 0x03e4, nv04_graph_mthd_set_operation);
/* nv05 iifc */
NVOBJ_CLASS(dev, 0x0064, GR);
/* nv01 ifc */
NVOBJ_CLASS(dev, 0x0021, GR);
NVOBJ_MTHD (dev, 0x0021, 0x0184, nv04_graph_mthd_bind_chroma);
NVOBJ_MTHD (dev, 0x0021, 0x0188, nv04_graph_mthd_bind_clip);
NVOBJ_MTHD (dev, 0x0021, 0x018c, nv04_graph_mthd_bind_nv01_patt);
NVOBJ_MTHD (dev, 0x0021, 0x0190, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x0021, 0x0194, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x0021, 0x0198, nv04_graph_mthd_bind_surf_dst);
NVOBJ_MTHD (dev, 0x0021, 0x02fc, nv04_graph_mthd_set_operation);
/* nv04 ifc */
NVOBJ_CLASS(dev, 0x0061, GR);
NVOBJ_MTHD (dev, 0x0061, 0x0184, nv04_graph_mthd_bind_chroma);
NVOBJ_MTHD (dev, 0x0061, 0x0188, nv04_graph_mthd_bind_clip);
NVOBJ_MTHD (dev, 0x0061, 0x018c, nv04_graph_mthd_bind_nv04_patt);
NVOBJ_MTHD (dev, 0x0061, 0x0190, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x0061, 0x0194, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x0061, 0x0198, nv04_graph_mthd_bind_beta4);
NVOBJ_MTHD (dev, 0x0061, 0x019c, nv04_graph_mthd_bind_surf2d);
NVOBJ_MTHD (dev, 0x0061, 0x02fc, nv04_graph_mthd_set_operation);
/* nv05 ifc */
NVOBJ_CLASS(dev, 0x0065, GR);
/* nv03 sifc */
NVOBJ_CLASS(dev, 0x0036, GR);
NVOBJ_MTHD (dev, 0x0036, 0x0184, nv04_graph_mthd_bind_chroma);
NVOBJ_MTHD (dev, 0x0036, 0x0188, nv04_graph_mthd_bind_nv01_patt);
NVOBJ_MTHD (dev, 0x0036, 0x018c, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x0036, 0x0190, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x0036, 0x0194, nv04_graph_mthd_bind_surf_dst);
NVOBJ_MTHD (dev, 0x0036, 0x02fc, nv04_graph_mthd_set_operation);
/* nv04 sifc */
NVOBJ_CLASS(dev, 0x0076, GR);
NVOBJ_MTHD (dev, 0x0076, 0x0184, nv04_graph_mthd_bind_chroma);
NVOBJ_MTHD (dev, 0x0076, 0x0188, nv04_graph_mthd_bind_nv04_patt);
NVOBJ_MTHD (dev, 0x0076, 0x018c, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x0076, 0x0190, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x0076, 0x0194, nv04_graph_mthd_bind_beta4);
NVOBJ_MTHD (dev, 0x0076, 0x0198, nv04_graph_mthd_bind_surf2d);
NVOBJ_MTHD (dev, 0x0076, 0x02fc, nv04_graph_mthd_set_operation);
/* nv05 sifc */
NVOBJ_CLASS(dev, 0x0066, GR);
/* nv03 sifm */
NVOBJ_CLASS(dev, 0x0037, GR);
NVOBJ_MTHD (dev, 0x0037, 0x0188, nv04_graph_mthd_bind_nv01_patt);
NVOBJ_MTHD (dev, 0x0037, 0x018c, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x0037, 0x0190, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x0037, 0x0194, nv04_graph_mthd_bind_surf_dst);
NVOBJ_MTHD (dev, 0x0037, 0x0304, nv04_graph_mthd_set_operation);
/* nv04 sifm */
NVOBJ_CLASS(dev, 0x0077, GR);
NVOBJ_MTHD (dev, 0x0077, 0x0188, nv04_graph_mthd_bind_nv04_patt);
NVOBJ_MTHD (dev, 0x0077, 0x018c, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x0077, 0x0190, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x0077, 0x0194, nv04_graph_mthd_bind_beta4);
NVOBJ_MTHD (dev, 0x0077, 0x0198, nv04_graph_mthd_bind_surf2d_swzsurf);
NVOBJ_MTHD (dev, 0x0077, 0x0304, nv04_graph_mthd_set_operation);
/* null */
NVOBJ_CLASS(dev, 0x0030, GR);
/* surf2d */
NVOBJ_CLASS(dev, 0x0042, GR);
/* rop */
NVOBJ_CLASS(dev, 0x0043, GR);
/* beta1 */
NVOBJ_CLASS(dev, 0x0012, GR);
/* beta4 */
NVOBJ_CLASS(dev, 0x0072, GR);
/* cliprect */
NVOBJ_CLASS(dev, 0x0019, GR);
/* nv01 pattern */
NVOBJ_CLASS(dev, 0x0018, GR);
/* nv04 pattern */
NVOBJ_CLASS(dev, 0x0044, GR);
/* swzsurf */
NVOBJ_CLASS(dev, 0x0052, GR);
/* surf3d */
NVOBJ_CLASS(dev, 0x0053, GR);
NVOBJ_MTHD (dev, 0x0053, 0x02f8, nv04_graph_mthd_surf3d_clip_h);
NVOBJ_MTHD (dev, 0x0053, 0x02fc, nv04_graph_mthd_surf3d_clip_v);
/* nv03 tex_tri */
NVOBJ_CLASS(dev, 0x0048, GR);
NVOBJ_MTHD (dev, 0x0048, 0x0188, nv04_graph_mthd_bind_clip);
NVOBJ_MTHD (dev, 0x0048, 0x018c, nv04_graph_mthd_bind_surf_color);
NVOBJ_MTHD (dev, 0x0048, 0x0190, nv04_graph_mthd_bind_surf_zeta);
/* tex_tri */
NVOBJ_CLASS(dev, 0x0054, GR);
/* multitex_tri */
NVOBJ_CLASS(dev, 0x0055, GR);
/* nv01 chroma */
NVOBJ_CLASS(dev, 0x0017, GR);
/* nv04 chroma */
NVOBJ_CLASS(dev, 0x0057, GR);
/* surf_dst */
NVOBJ_CLASS(dev, 0x0058, GR);
/* surf_src */
NVOBJ_CLASS(dev, 0x0059, GR);
/* surf_color */
NVOBJ_CLASS(dev, 0x005a, GR);
/* surf_zeta */
NVOBJ_CLASS(dev, 0x005b, GR);
/* nv01 line */
NVOBJ_CLASS(dev, 0x001c, GR);
NVOBJ_MTHD (dev, 0x001c, 0x0184, nv04_graph_mthd_bind_clip);
NVOBJ_MTHD (dev, 0x001c, 0x0188, nv04_graph_mthd_bind_nv01_patt);
NVOBJ_MTHD (dev, 0x001c, 0x018c, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x001c, 0x0190, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x001c, 0x0194, nv04_graph_mthd_bind_surf_dst);
NVOBJ_MTHD (dev, 0x001c, 0x02fc, nv04_graph_mthd_set_operation);
/* nv04 line */
NVOBJ_CLASS(dev, 0x005c, GR);
NVOBJ_MTHD (dev, 0x005c, 0x0184, nv04_graph_mthd_bind_clip);
NVOBJ_MTHD (dev, 0x005c, 0x0188, nv04_graph_mthd_bind_nv04_patt);
NVOBJ_MTHD (dev, 0x005c, 0x018c, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x005c, 0x0190, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x005c, 0x0194, nv04_graph_mthd_bind_beta4);
NVOBJ_MTHD (dev, 0x005c, 0x0198, nv04_graph_mthd_bind_surf2d);
NVOBJ_MTHD (dev, 0x005c, 0x02fc, nv04_graph_mthd_set_operation);
/* nv01 tri */
NVOBJ_CLASS(dev, 0x001d, GR);
NVOBJ_MTHD (dev, 0x001d, 0x0184, nv04_graph_mthd_bind_clip);
NVOBJ_MTHD (dev, 0x001d, 0x0188, nv04_graph_mthd_bind_nv01_patt);
NVOBJ_MTHD (dev, 0x001d, 0x018c, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x001d, 0x0190, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x001d, 0x0194, nv04_graph_mthd_bind_surf_dst);
NVOBJ_MTHD (dev, 0x001d, 0x02fc, nv04_graph_mthd_set_operation);
/* nv04 tri */
NVOBJ_CLASS(dev, 0x005d, GR);
NVOBJ_MTHD (dev, 0x005d, 0x0184, nv04_graph_mthd_bind_clip);
NVOBJ_MTHD (dev, 0x005d, 0x0188, nv04_graph_mthd_bind_nv04_patt);
NVOBJ_MTHD (dev, 0x005d, 0x018c, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x005d, 0x0190, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x005d, 0x0194, nv04_graph_mthd_bind_beta4);
NVOBJ_MTHD (dev, 0x005d, 0x0198, nv04_graph_mthd_bind_surf2d);
NVOBJ_MTHD (dev, 0x005d, 0x02fc, nv04_graph_mthd_set_operation);
/* nv01 rect */
NVOBJ_CLASS(dev, 0x001e, GR);
NVOBJ_MTHD (dev, 0x001e, 0x0184, nv04_graph_mthd_bind_clip);
NVOBJ_MTHD (dev, 0x001e, 0x0188, nv04_graph_mthd_bind_nv01_patt);
NVOBJ_MTHD (dev, 0x001e, 0x018c, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x001e, 0x0190, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x001e, 0x0194, nv04_graph_mthd_bind_surf_dst);
NVOBJ_MTHD (dev, 0x001e, 0x02fc, nv04_graph_mthd_set_operation);
/* nv04 rect */
NVOBJ_CLASS(dev, 0x005e, GR);
NVOBJ_MTHD (dev, 0x005e, 0x0184, nv04_graph_mthd_bind_clip);
NVOBJ_MTHD (dev, 0x005e, 0x0188, nv04_graph_mthd_bind_nv04_patt);
NVOBJ_MTHD (dev, 0x005e, 0x018c, nv04_graph_mthd_bind_rop);
NVOBJ_MTHD (dev, 0x005e, 0x0190, nv04_graph_mthd_bind_beta1);
NVOBJ_MTHD (dev, 0x005e, 0x0194, nv04_graph_mthd_bind_beta4);
NVOBJ_MTHD (dev, 0x005e, 0x0198, nv04_graph_mthd_bind_surf2d);
NVOBJ_MTHD (dev, 0x005e, 0x02fc, nv04_graph_mthd_set_operation);
/* nvsw */
NVOBJ_CLASS(dev, 0x506e, SW);
NVOBJ_MTHD (dev, 0x506e, 0x0150, nv04_graph_mthd_set_ref);
NVOBJ_MTHD (dev, 0x506e, 0x0500, nv04_graph_mthd_page_flip);
return 0;
}
| gpl-2.0 |
revjunkie/i9505 | drivers/video/geode/gx1fb_core.c | 7971 | 12565 | /*
* drivers/video/geode/gx1fb_core.c
* -- Geode GX1 framebuffer driver
*
* Copyright (C) 2005 Arcom Control Systems Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/pci.h>
#include "geodefb.h"
#include "display_gx1.h"
#include "video_cs5530.h"
static char mode_option[32] = "640x480-16@60";
static int crt_option = 1;
static char panel_option[32] = "";
/* Modes relevant to the GX1 (taken from modedb.c) */
static const struct fb_videomode __devinitdata gx1_modedb[] = {
/* 640x480-60 VESA */
{ NULL, 60, 640, 480, 39682, 48, 16, 33, 10, 96, 2,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 640x480-75 VESA */
{ NULL, 75, 640, 480, 31746, 120, 16, 16, 01, 64, 3,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 640x480-85 VESA */
{ NULL, 85, 640, 480, 27777, 80, 56, 25, 01, 56, 3,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 800x600-60 VESA */
{ NULL, 60, 800, 600, 25000, 88, 40, 23, 01, 128, 4,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 800x600-75 VESA */
{ NULL, 75, 800, 600, 20202, 160, 16, 21, 01, 80, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 800x600-85 VESA */
{ NULL, 85, 800, 600, 17761, 152, 32, 27, 01, 64, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1024x768-60 VESA */
{ NULL, 60, 1024, 768, 15384, 160, 24, 29, 3, 136, 6,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1024x768-75 VESA */
{ NULL, 75, 1024, 768, 12690, 176, 16, 28, 1, 96, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1024x768-85 VESA */
{ NULL, 85, 1024, 768, 10582, 208, 48, 36, 1, 96, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1280x960-60 VESA */
{ NULL, 60, 1280, 960, 9259, 312, 96, 36, 1, 112, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1280x960-85 VESA */
{ NULL, 85, 1280, 960, 6734, 224, 64, 47, 1, 160, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1280x1024-60 VESA */
{ NULL, 60, 1280, 1024, 9259, 248, 48, 38, 1, 112, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1280x1024-75 VESA */
{ NULL, 75, 1280, 1024, 7407, 248, 16, 38, 1, 144, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1280x1024-85 VESA */
{ NULL, 85, 1280, 1024, 6349, 224, 64, 44, 1, 160, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
};
static int gx1_line_delta(int xres, int bpp)
{
int line_delta = xres * (bpp >> 3);
if (line_delta > 2048)
line_delta = 4096;
else if (line_delta > 1024)
line_delta = 2048;
else
line_delta = 1024;
return line_delta;
}
static int gx1fb_check_var(struct fb_var_screeninfo *var, struct fb_info *info)
{
struct geodefb_par *par = info->par;
/* Maximum resolution is 1280x1024. */
if (var->xres > 1280 || var->yres > 1024)
return -EINVAL;
if (par->panel_x && (var->xres > par->panel_x || var->yres > par->panel_y))
return -EINVAL;
/* Only 16 bpp and 8 bpp is supported by the hardware. */
if (var->bits_per_pixel == 16) {
var->red.offset = 11; var->red.length = 5;
var->green.offset = 5; var->green.length = 6;
var->blue.offset = 0; var->blue.length = 5;
var->transp.offset = 0; var->transp.length = 0;
} else if (var->bits_per_pixel == 8) {
var->red.offset = 0; var->red.length = 8;
var->green.offset = 0; var->green.length = 8;
var->blue.offset = 0; var->blue.length = 8;
var->transp.offset = 0; var->transp.length = 0;
} else
return -EINVAL;
/* Enough video memory? */
if (gx1_line_delta(var->xres, var->bits_per_pixel) * var->yres > info->fix.smem_len)
return -EINVAL;
/* FIXME: Check timing parameters here? */
return 0;
}
static int gx1fb_set_par(struct fb_info *info)
{
struct geodefb_par *par = info->par;
if (info->var.bits_per_pixel == 16)
info->fix.visual = FB_VISUAL_TRUECOLOR;
else
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
info->fix.line_length = gx1_line_delta(info->var.xres, info->var.bits_per_pixel);
par->dc_ops->set_mode(info);
return 0;
}
static inline u_int chan_to_field(u_int chan, struct fb_bitfield *bf)
{
chan &= 0xffff;
chan >>= 16 - bf->length;
return chan << bf->offset;
}
static int gx1fb_setcolreg(unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct fb_info *info)
{
struct geodefb_par *par = info->par;
if (info->var.grayscale) {
/* grayscale = 0.30*R + 0.59*G + 0.11*B */
red = green = blue = (red * 77 + green * 151 + blue * 28) >> 8;
}
/* Truecolor has hardware independent palette */
if (info->fix.visual == FB_VISUAL_TRUECOLOR) {
u32 *pal = info->pseudo_palette;
u32 v;
if (regno >= 16)
return -EINVAL;
v = chan_to_field(red, &info->var.red);
v |= chan_to_field(green, &info->var.green);
v |= chan_to_field(blue, &info->var.blue);
pal[regno] = v;
} else {
if (regno >= 256)
return -EINVAL;
par->dc_ops->set_palette_reg(info, regno, red, green, blue);
}
return 0;
}
static int gx1fb_blank(int blank_mode, struct fb_info *info)
{
struct geodefb_par *par = info->par;
return par->vid_ops->blank_display(info, blank_mode);
}
static int __devinit gx1fb_map_video_memory(struct fb_info *info, struct pci_dev *dev)
{
struct geodefb_par *par = info->par;
unsigned gx_base;
int fb_len;
int ret;
gx_base = gx1_gx_base();
if (!gx_base)
return -ENODEV;
ret = pci_enable_device(dev);
if (ret < 0)
return ret;
ret = pci_request_region(dev, 0, "gx1fb (video)");
if (ret < 0)
return ret;
par->vid_regs = pci_ioremap_bar(dev, 0);
if (!par->vid_regs)
return -ENOMEM;
if (!request_mem_region(gx_base + 0x8300, 0x100, "gx1fb (display controller)"))
return -EBUSY;
par->dc_regs = ioremap(gx_base + 0x8300, 0x100);
if (!par->dc_regs)
return -ENOMEM;
if ((fb_len = gx1_frame_buffer_size()) < 0)
return -ENOMEM;
info->fix.smem_start = gx_base + 0x800000;
info->fix.smem_len = fb_len;
info->screen_base = ioremap(info->fix.smem_start, info->fix.smem_len);
if (!info->screen_base)
return -ENOMEM;
dev_info(&dev->dev, "%d Kibyte of video memory at 0x%lx\n",
info->fix.smem_len / 1024, info->fix.smem_start);
return 0;
}
static int parse_panel_option(struct fb_info *info)
{
struct geodefb_par *par = info->par;
if (strcmp(panel_option, "") != 0) {
int x, y;
char *s;
x = simple_strtol(panel_option, &s, 10);
if (!x)
return -EINVAL;
y = simple_strtol(s + 1, NULL, 10);
if (!y)
return -EINVAL;
par->panel_x = x;
par->panel_y = y;
}
return 0;
}
static struct fb_ops gx1fb_ops = {
.owner = THIS_MODULE,
.fb_check_var = gx1fb_check_var,
.fb_set_par = gx1fb_set_par,
.fb_setcolreg = gx1fb_setcolreg,
.fb_blank = gx1fb_blank,
/* No HW acceleration for now. */
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
};
static struct fb_info * __devinit gx1fb_init_fbinfo(struct device *dev)
{
struct geodefb_par *par;
struct fb_info *info;
/* Alloc enough space for the pseudo palette. */
info = framebuffer_alloc(sizeof(struct geodefb_par) + sizeof(u32) * 16, dev);
if (!info)
return NULL;
par = info->par;
strcpy(info->fix.id, "GX1");
info->fix.type = FB_TYPE_PACKED_PIXELS;
info->fix.type_aux = 0;
info->fix.xpanstep = 0;
info->fix.ypanstep = 0;
info->fix.ywrapstep = 0;
info->fix.accel = FB_ACCEL_NONE;
info->var.nonstd = 0;
info->var.activate = FB_ACTIVATE_NOW;
info->var.height = -1;
info->var.width = -1;
info->var.accel_flags = 0;
info->var.vmode = FB_VMODE_NONINTERLACED;
info->fbops = &gx1fb_ops;
info->flags = FBINFO_DEFAULT;
info->node = -1;
info->pseudo_palette = (void *)par + sizeof(struct geodefb_par);
info->var.grayscale = 0;
/* CRT and panel options */
par->enable_crt = crt_option;
if (parse_panel_option(info) < 0)
printk(KERN_WARNING "gx1fb: invalid 'panel' option -- disabling flat panel\n");
if (!par->panel_x)
par->enable_crt = 1; /* fall back to CRT if no panel is specified */
if (fb_alloc_cmap(&info->cmap, 256, 0) < 0) {
framebuffer_release(info);
return NULL;
}
return info;
}
static int __devinit gx1fb_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
struct geodefb_par *par;
struct fb_info *info;
int ret;
info = gx1fb_init_fbinfo(&pdev->dev);
if (!info)
return -ENOMEM;
par = info->par;
/* GX1 display controller and CS5530 video device */
par->dc_ops = &gx1_dc_ops;
par->vid_ops = &cs5530_vid_ops;
if ((ret = gx1fb_map_video_memory(info, pdev)) < 0) {
dev_err(&pdev->dev, "failed to map frame buffer or controller registers\n");
goto err;
}
ret = fb_find_mode(&info->var, info, mode_option,
gx1_modedb, ARRAY_SIZE(gx1_modedb), NULL, 16);
if (ret == 0 || ret == 4) {
dev_err(&pdev->dev, "could not find valid video mode\n");
ret = -EINVAL;
goto err;
}
/* Clear the frame buffer of garbage. */
memset_io(info->screen_base, 0, info->fix.smem_len);
gx1fb_check_var(&info->var, info);
gx1fb_set_par(info);
if (register_framebuffer(info) < 0) {
ret = -EINVAL;
goto err;
}
pci_set_drvdata(pdev, info);
printk(KERN_INFO "fb%d: %s frame buffer device\n", info->node, info->fix.id);
return 0;
err:
if (info->screen_base) {
iounmap(info->screen_base);
pci_release_region(pdev, 0);
}
if (par->vid_regs) {
iounmap(par->vid_regs);
pci_release_region(pdev, 1);
}
if (par->dc_regs) {
iounmap(par->dc_regs);
release_mem_region(gx1_gx_base() + 0x8300, 0x100);
}
if (info) {
fb_dealloc_cmap(&info->cmap);
framebuffer_release(info);
}
return ret;
}
static void __devexit gx1fb_remove(struct pci_dev *pdev)
{
struct fb_info *info = pci_get_drvdata(pdev);
struct geodefb_par *par = info->par;
unregister_framebuffer(info);
iounmap((void __iomem *)info->screen_base);
pci_release_region(pdev, 0);
iounmap(par->vid_regs);
pci_release_region(pdev, 1);
iounmap(par->dc_regs);
release_mem_region(gx1_gx_base() + 0x8300, 0x100);
fb_dealloc_cmap(&info->cmap);
pci_set_drvdata(pdev, NULL);
framebuffer_release(info);
}
#ifndef MODULE
static void __init gx1fb_setup(char *options)
{
char *this_opt;
if (!options || !*options)
return;
while ((this_opt = strsep(&options, ","))) {
if (!*this_opt)
continue;
if (!strncmp(this_opt, "mode:", 5))
strlcpy(mode_option, this_opt + 5, sizeof(mode_option));
else if (!strncmp(this_opt, "crt:", 4))
crt_option = !!simple_strtoul(this_opt + 4, NULL, 0);
else if (!strncmp(this_opt, "panel:", 6))
strlcpy(panel_option, this_opt + 6, sizeof(panel_option));
else
strlcpy(mode_option, this_opt, sizeof(mode_option));
}
}
#endif
static struct pci_device_id gx1fb_id_table[] = {
{ PCI_VENDOR_ID_CYRIX, PCI_DEVICE_ID_CYRIX_5530_VIDEO,
PCI_ANY_ID, PCI_ANY_ID, PCI_BASE_CLASS_DISPLAY << 16,
0xff0000, 0 },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, gx1fb_id_table);
static struct pci_driver gx1fb_driver = {
.name = "gx1fb",
.id_table = gx1fb_id_table,
.probe = gx1fb_probe,
.remove = __devexit_p(gx1fb_remove),
};
static int __init gx1fb_init(void)
{
#ifndef MODULE
char *option = NULL;
if (fb_get_options("gx1fb", &option))
return -ENODEV;
gx1fb_setup(option);
#endif
return pci_register_driver(&gx1fb_driver);
}
static void __devexit gx1fb_cleanup(void)
{
pci_unregister_driver(&gx1fb_driver);
}
module_init(gx1fb_init);
module_exit(gx1fb_cleanup);
module_param_string(mode, mode_option, sizeof(mode_option), 0444);
MODULE_PARM_DESC(mode, "video mode (<x>x<y>[-<bpp>][@<refr>])");
module_param_named(crt, crt_option, int, 0444);
MODULE_PARM_DESC(crt, "enable CRT output. 0 = off, 1 = on (default)");
module_param_string(panel, panel_option, sizeof(panel_option), 0444);
MODULE_PARM_DESC(panel, "size of attached flat panel (<x>x<y>)");
MODULE_DESCRIPTION("framebuffer driver for the AMD Geode GX1");
MODULE_LICENSE("GPL");
| gpl-2.0 |
blacktigersoftware/hummingboard-cuboxi-kernel | drivers/video/geode/gx1fb_core.c | 7971 | 12565 | /*
* drivers/video/geode/gx1fb_core.c
* -- Geode GX1 framebuffer driver
*
* Copyright (C) 2005 Arcom Control Systems Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/pci.h>
#include "geodefb.h"
#include "display_gx1.h"
#include "video_cs5530.h"
static char mode_option[32] = "640x480-16@60";
static int crt_option = 1;
static char panel_option[32] = "";
/* Modes relevant to the GX1 (taken from modedb.c) */
static const struct fb_videomode __devinitdata gx1_modedb[] = {
/* 640x480-60 VESA */
{ NULL, 60, 640, 480, 39682, 48, 16, 33, 10, 96, 2,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 640x480-75 VESA */
{ NULL, 75, 640, 480, 31746, 120, 16, 16, 01, 64, 3,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 640x480-85 VESA */
{ NULL, 85, 640, 480, 27777, 80, 56, 25, 01, 56, 3,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 800x600-60 VESA */
{ NULL, 60, 800, 600, 25000, 88, 40, 23, 01, 128, 4,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 800x600-75 VESA */
{ NULL, 75, 800, 600, 20202, 160, 16, 21, 01, 80, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 800x600-85 VESA */
{ NULL, 85, 800, 600, 17761, 152, 32, 27, 01, 64, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1024x768-60 VESA */
{ NULL, 60, 1024, 768, 15384, 160, 24, 29, 3, 136, 6,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1024x768-75 VESA */
{ NULL, 75, 1024, 768, 12690, 176, 16, 28, 1, 96, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1024x768-85 VESA */
{ NULL, 85, 1024, 768, 10582, 208, 48, 36, 1, 96, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1280x960-60 VESA */
{ NULL, 60, 1280, 960, 9259, 312, 96, 36, 1, 112, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1280x960-85 VESA */
{ NULL, 85, 1280, 960, 6734, 224, 64, 47, 1, 160, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1280x1024-60 VESA */
{ NULL, 60, 1280, 1024, 9259, 248, 48, 38, 1, 112, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1280x1024-75 VESA */
{ NULL, 75, 1280, 1024, 7407, 248, 16, 38, 1, 144, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1280x1024-85 VESA */
{ NULL, 85, 1280, 1024, 6349, 224, 64, 44, 1, 160, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
};
static int gx1_line_delta(int xres, int bpp)
{
int line_delta = xres * (bpp >> 3);
if (line_delta > 2048)
line_delta = 4096;
else if (line_delta > 1024)
line_delta = 2048;
else
line_delta = 1024;
return line_delta;
}
static int gx1fb_check_var(struct fb_var_screeninfo *var, struct fb_info *info)
{
struct geodefb_par *par = info->par;
/* Maximum resolution is 1280x1024. */
if (var->xres > 1280 || var->yres > 1024)
return -EINVAL;
if (par->panel_x && (var->xres > par->panel_x || var->yres > par->panel_y))
return -EINVAL;
/* Only 16 bpp and 8 bpp is supported by the hardware. */
if (var->bits_per_pixel == 16) {
var->red.offset = 11; var->red.length = 5;
var->green.offset = 5; var->green.length = 6;
var->blue.offset = 0; var->blue.length = 5;
var->transp.offset = 0; var->transp.length = 0;
} else if (var->bits_per_pixel == 8) {
var->red.offset = 0; var->red.length = 8;
var->green.offset = 0; var->green.length = 8;
var->blue.offset = 0; var->blue.length = 8;
var->transp.offset = 0; var->transp.length = 0;
} else
return -EINVAL;
/* Enough video memory? */
if (gx1_line_delta(var->xres, var->bits_per_pixel) * var->yres > info->fix.smem_len)
return -EINVAL;
/* FIXME: Check timing parameters here? */
return 0;
}
static int gx1fb_set_par(struct fb_info *info)
{
struct geodefb_par *par = info->par;
if (info->var.bits_per_pixel == 16)
info->fix.visual = FB_VISUAL_TRUECOLOR;
else
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
info->fix.line_length = gx1_line_delta(info->var.xres, info->var.bits_per_pixel);
par->dc_ops->set_mode(info);
return 0;
}
static inline u_int chan_to_field(u_int chan, struct fb_bitfield *bf)
{
chan &= 0xffff;
chan >>= 16 - bf->length;
return chan << bf->offset;
}
static int gx1fb_setcolreg(unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct fb_info *info)
{
struct geodefb_par *par = info->par;
if (info->var.grayscale) {
/* grayscale = 0.30*R + 0.59*G + 0.11*B */
red = green = blue = (red * 77 + green * 151 + blue * 28) >> 8;
}
/* Truecolor has hardware independent palette */
if (info->fix.visual == FB_VISUAL_TRUECOLOR) {
u32 *pal = info->pseudo_palette;
u32 v;
if (regno >= 16)
return -EINVAL;
v = chan_to_field(red, &info->var.red);
v |= chan_to_field(green, &info->var.green);
v |= chan_to_field(blue, &info->var.blue);
pal[regno] = v;
} else {
if (regno >= 256)
return -EINVAL;
par->dc_ops->set_palette_reg(info, regno, red, green, blue);
}
return 0;
}
static int gx1fb_blank(int blank_mode, struct fb_info *info)
{
struct geodefb_par *par = info->par;
return par->vid_ops->blank_display(info, blank_mode);
}
static int __devinit gx1fb_map_video_memory(struct fb_info *info, struct pci_dev *dev)
{
struct geodefb_par *par = info->par;
unsigned gx_base;
int fb_len;
int ret;
gx_base = gx1_gx_base();
if (!gx_base)
return -ENODEV;
ret = pci_enable_device(dev);
if (ret < 0)
return ret;
ret = pci_request_region(dev, 0, "gx1fb (video)");
if (ret < 0)
return ret;
par->vid_regs = pci_ioremap_bar(dev, 0);
if (!par->vid_regs)
return -ENOMEM;
if (!request_mem_region(gx_base + 0x8300, 0x100, "gx1fb (display controller)"))
return -EBUSY;
par->dc_regs = ioremap(gx_base + 0x8300, 0x100);
if (!par->dc_regs)
return -ENOMEM;
if ((fb_len = gx1_frame_buffer_size()) < 0)
return -ENOMEM;
info->fix.smem_start = gx_base + 0x800000;
info->fix.smem_len = fb_len;
info->screen_base = ioremap(info->fix.smem_start, info->fix.smem_len);
if (!info->screen_base)
return -ENOMEM;
dev_info(&dev->dev, "%d Kibyte of video memory at 0x%lx\n",
info->fix.smem_len / 1024, info->fix.smem_start);
return 0;
}
static int parse_panel_option(struct fb_info *info)
{
struct geodefb_par *par = info->par;
if (strcmp(panel_option, "") != 0) {
int x, y;
char *s;
x = simple_strtol(panel_option, &s, 10);
if (!x)
return -EINVAL;
y = simple_strtol(s + 1, NULL, 10);
if (!y)
return -EINVAL;
par->panel_x = x;
par->panel_y = y;
}
return 0;
}
static struct fb_ops gx1fb_ops = {
.owner = THIS_MODULE,
.fb_check_var = gx1fb_check_var,
.fb_set_par = gx1fb_set_par,
.fb_setcolreg = gx1fb_setcolreg,
.fb_blank = gx1fb_blank,
/* No HW acceleration for now. */
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
};
static struct fb_info * __devinit gx1fb_init_fbinfo(struct device *dev)
{
struct geodefb_par *par;
struct fb_info *info;
/* Alloc enough space for the pseudo palette. */
info = framebuffer_alloc(sizeof(struct geodefb_par) + sizeof(u32) * 16, dev);
if (!info)
return NULL;
par = info->par;
strcpy(info->fix.id, "GX1");
info->fix.type = FB_TYPE_PACKED_PIXELS;
info->fix.type_aux = 0;
info->fix.xpanstep = 0;
info->fix.ypanstep = 0;
info->fix.ywrapstep = 0;
info->fix.accel = FB_ACCEL_NONE;
info->var.nonstd = 0;
info->var.activate = FB_ACTIVATE_NOW;
info->var.height = -1;
info->var.width = -1;
info->var.accel_flags = 0;
info->var.vmode = FB_VMODE_NONINTERLACED;
info->fbops = &gx1fb_ops;
info->flags = FBINFO_DEFAULT;
info->node = -1;
info->pseudo_palette = (void *)par + sizeof(struct geodefb_par);
info->var.grayscale = 0;
/* CRT and panel options */
par->enable_crt = crt_option;
if (parse_panel_option(info) < 0)
printk(KERN_WARNING "gx1fb: invalid 'panel' option -- disabling flat panel\n");
if (!par->panel_x)
par->enable_crt = 1; /* fall back to CRT if no panel is specified */
if (fb_alloc_cmap(&info->cmap, 256, 0) < 0) {
framebuffer_release(info);
return NULL;
}
return info;
}
static int __devinit gx1fb_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
struct geodefb_par *par;
struct fb_info *info;
int ret;
info = gx1fb_init_fbinfo(&pdev->dev);
if (!info)
return -ENOMEM;
par = info->par;
/* GX1 display controller and CS5530 video device */
par->dc_ops = &gx1_dc_ops;
par->vid_ops = &cs5530_vid_ops;
if ((ret = gx1fb_map_video_memory(info, pdev)) < 0) {
dev_err(&pdev->dev, "failed to map frame buffer or controller registers\n");
goto err;
}
ret = fb_find_mode(&info->var, info, mode_option,
gx1_modedb, ARRAY_SIZE(gx1_modedb), NULL, 16);
if (ret == 0 || ret == 4) {
dev_err(&pdev->dev, "could not find valid video mode\n");
ret = -EINVAL;
goto err;
}
/* Clear the frame buffer of garbage. */
memset_io(info->screen_base, 0, info->fix.smem_len);
gx1fb_check_var(&info->var, info);
gx1fb_set_par(info);
if (register_framebuffer(info) < 0) {
ret = -EINVAL;
goto err;
}
pci_set_drvdata(pdev, info);
printk(KERN_INFO "fb%d: %s frame buffer device\n", info->node, info->fix.id);
return 0;
err:
if (info->screen_base) {
iounmap(info->screen_base);
pci_release_region(pdev, 0);
}
if (par->vid_regs) {
iounmap(par->vid_regs);
pci_release_region(pdev, 1);
}
if (par->dc_regs) {
iounmap(par->dc_regs);
release_mem_region(gx1_gx_base() + 0x8300, 0x100);
}
if (info) {
fb_dealloc_cmap(&info->cmap);
framebuffer_release(info);
}
return ret;
}
static void __devexit gx1fb_remove(struct pci_dev *pdev)
{
struct fb_info *info = pci_get_drvdata(pdev);
struct geodefb_par *par = info->par;
unregister_framebuffer(info);
iounmap((void __iomem *)info->screen_base);
pci_release_region(pdev, 0);
iounmap(par->vid_regs);
pci_release_region(pdev, 1);
iounmap(par->dc_regs);
release_mem_region(gx1_gx_base() + 0x8300, 0x100);
fb_dealloc_cmap(&info->cmap);
pci_set_drvdata(pdev, NULL);
framebuffer_release(info);
}
#ifndef MODULE
static void __init gx1fb_setup(char *options)
{
char *this_opt;
if (!options || !*options)
return;
while ((this_opt = strsep(&options, ","))) {
if (!*this_opt)
continue;
if (!strncmp(this_opt, "mode:", 5))
strlcpy(mode_option, this_opt + 5, sizeof(mode_option));
else if (!strncmp(this_opt, "crt:", 4))
crt_option = !!simple_strtoul(this_opt + 4, NULL, 0);
else if (!strncmp(this_opt, "panel:", 6))
strlcpy(panel_option, this_opt + 6, sizeof(panel_option));
else
strlcpy(mode_option, this_opt, sizeof(mode_option));
}
}
#endif
static struct pci_device_id gx1fb_id_table[] = {
{ PCI_VENDOR_ID_CYRIX, PCI_DEVICE_ID_CYRIX_5530_VIDEO,
PCI_ANY_ID, PCI_ANY_ID, PCI_BASE_CLASS_DISPLAY << 16,
0xff0000, 0 },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, gx1fb_id_table);
static struct pci_driver gx1fb_driver = {
.name = "gx1fb",
.id_table = gx1fb_id_table,
.probe = gx1fb_probe,
.remove = __devexit_p(gx1fb_remove),
};
static int __init gx1fb_init(void)
{
#ifndef MODULE
char *option = NULL;
if (fb_get_options("gx1fb", &option))
return -ENODEV;
gx1fb_setup(option);
#endif
return pci_register_driver(&gx1fb_driver);
}
static void __devexit gx1fb_cleanup(void)
{
pci_unregister_driver(&gx1fb_driver);
}
module_init(gx1fb_init);
module_exit(gx1fb_cleanup);
module_param_string(mode, mode_option, sizeof(mode_option), 0444);
MODULE_PARM_DESC(mode, "video mode (<x>x<y>[-<bpp>][@<refr>])");
module_param_named(crt, crt_option, int, 0444);
MODULE_PARM_DESC(crt, "enable CRT output. 0 = off, 1 = on (default)");
module_param_string(panel, panel_option, sizeof(panel_option), 0444);
MODULE_PARM_DESC(panel, "size of attached flat panel (<x>x<y>)");
MODULE_DESCRIPTION("framebuffer driver for the AMD Geode GX1");
MODULE_LICENSE("GPL");
| gpl-2.0 |
tecno789/kernel_lge_msm8226_g2m | drivers/pcmcia/i82365.c | 8227 | 38302 | /*======================================================================
Device driver for Intel 82365 and compatible PC Card controllers.
i82365.c 1.265 1999/11/10 18:36:21
The contents of this file are subject to the Mozilla Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
The initial developer of the original code is David A. Hinds
<dahinds@users.sourceforge.net>. Portions created by David A. Hinds
are Copyright (C) 1999 David A. Hinds. All Rights Reserved.
Alternatively, the contents of this file may be used under the
terms of the GNU General Public License version 2 (the "GPL"), in which
case the provisions of the GPL are applicable instead of the
above. If you wish to allow the use of your version of this file
only under the terms of the GPL and not to allow others to use
your version of this file under the MPL, indicate your decision
by deleting the provisions above and replace them with the notice
and other provisions required by the GPL. If you do not delete
the provisions above, a recipient may use your version of this
file under either the MPL or the GPL.
======================================================================*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/workqueue.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/bitops.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <pcmcia/ss.h>
#include <linux/isapnp.h>
/* ISA-bus controllers */
#include "i82365.h"
#include "cirrus.h"
#include "vg468.h"
#include "ricoh.h"
static irqreturn_t i365_count_irq(int, void *);
static inline int _check_irq(int irq, int flags)
{
if (request_irq(irq, i365_count_irq, flags, "x", i365_count_irq) != 0)
return -1;
free_irq(irq, i365_count_irq);
return 0;
}
/*====================================================================*/
/* Parameters that can be set with 'insmod' */
/* Default base address for i82365sl and other ISA chips */
static unsigned long i365_base = 0x3e0;
/* Should we probe at 0x3e2 for an extra ISA controller? */
static int extra_sockets = 0;
/* Specify a socket number to ignore */
static int ignore = -1;
/* Bit map or list of interrupts to choose from */
static u_int irq_mask = 0xffff;
static int irq_list[16];
static unsigned int irq_list_count;
/* The card status change interrupt -- 0 means autoselect */
static int cs_irq = 0;
/* Probe for safe interrupts? */
static int do_scan = 1;
/* Poll status interval -- 0 means default to interrupt */
static int poll_interval = 0;
/* External clock time, in nanoseconds. 120 ns = 8.33 MHz */
static int cycle_time = 120;
/* Cirrus options */
static int has_dma = -1;
static int has_led = -1;
static int has_ring = -1;
static int dynamic_mode = 0;
static int freq_bypass = -1;
static int setup_time = -1;
static int cmd_time = -1;
static int recov_time = -1;
/* Vadem options */
static int async_clock = -1;
static int cable_mode = -1;
static int wakeup = 0;
module_param(i365_base, ulong, 0444);
module_param(ignore, int, 0444);
module_param(extra_sockets, int, 0444);
module_param(irq_mask, int, 0444);
module_param_array(irq_list, int, &irq_list_count, 0444);
module_param(cs_irq, int, 0444);
module_param(async_clock, int, 0444);
module_param(cable_mode, int, 0444);
module_param(wakeup, int, 0444);
module_param(do_scan, int, 0444);
module_param(poll_interval, int, 0444);
module_param(cycle_time, int, 0444);
module_param(has_dma, int, 0444);
module_param(has_led, int, 0444);
module_param(has_ring, int, 0444);
module_param(dynamic_mode, int, 0444);
module_param(freq_bypass, int, 0444);
module_param(setup_time, int, 0444);
module_param(cmd_time, int, 0444);
module_param(recov_time, int, 0444);
/*====================================================================*/
typedef struct cirrus_state_t {
u_char misc1, misc2;
u_char timer[6];
} cirrus_state_t;
typedef struct vg46x_state_t {
u_char ctl, ema;
} vg46x_state_t;
struct i82365_socket {
u_short type, flags;
struct pcmcia_socket socket;
unsigned int number;
unsigned int ioaddr;
u_short psock;
u_char cs_irq, intr;
union {
cirrus_state_t cirrus;
vg46x_state_t vg46x;
} state;
};
/* Where we keep track of our sockets... */
static int sockets = 0;
static struct i82365_socket socket[8] = {
{ 0, }, /* ... */
};
/* Default ISA interrupt mask */
#define I365_MASK 0xdeb8 /* irq 15,14,12,11,10,9,7,5,4,3 */
static int grab_irq;
static DEFINE_SPINLOCK(isa_lock);
#define ISA_LOCK(n, f) spin_lock_irqsave(&isa_lock, f)
#define ISA_UNLOCK(n, f) spin_unlock_irqrestore(&isa_lock, f)
static struct timer_list poll_timer;
/*====================================================================*/
/* These definitions must match the pcic table! */
typedef enum pcic_id {
IS_I82365A, IS_I82365B, IS_I82365DF,
IS_IBM, IS_RF5Cx96, IS_VLSI, IS_VG468, IS_VG469,
IS_PD6710, IS_PD672X, IS_VT83C469,
} pcic_id;
/* Flags for classifying groups of controllers */
#define IS_VADEM 0x0001
#define IS_CIRRUS 0x0002
#define IS_VIA 0x0010
#define IS_UNKNOWN 0x0400
#define IS_VG_PWR 0x0800
#define IS_DF_PWR 0x1000
#define IS_REGISTERED 0x2000
#define IS_ALIVE 0x8000
typedef struct pcic_t {
char *name;
u_short flags;
} pcic_t;
static pcic_t pcic[] = {
{ "Intel i82365sl A step", 0 },
{ "Intel i82365sl B step", 0 },
{ "Intel i82365sl DF", IS_DF_PWR },
{ "IBM Clone", 0 },
{ "Ricoh RF5C296/396", 0 },
{ "VLSI 82C146", 0 },
{ "Vadem VG-468", IS_VADEM },
{ "Vadem VG-469", IS_VADEM|IS_VG_PWR },
{ "Cirrus PD6710", IS_CIRRUS },
{ "Cirrus PD672x", IS_CIRRUS },
{ "VIA VT83C469", IS_CIRRUS|IS_VIA },
};
#define PCIC_COUNT (sizeof(pcic)/sizeof(pcic_t))
/*====================================================================*/
static DEFINE_SPINLOCK(bus_lock);
static u_char i365_get(u_short sock, u_short reg)
{
unsigned long flags;
spin_lock_irqsave(&bus_lock,flags);
{
unsigned int port = socket[sock].ioaddr;
u_char val;
reg = I365_REG(socket[sock].psock, reg);
outb(reg, port); val = inb(port+1);
spin_unlock_irqrestore(&bus_lock,flags);
return val;
}
}
static void i365_set(u_short sock, u_short reg, u_char data)
{
unsigned long flags;
spin_lock_irqsave(&bus_lock,flags);
{
unsigned int port = socket[sock].ioaddr;
u_char val = I365_REG(socket[sock].psock, reg);
outb(val, port); outb(data, port+1);
spin_unlock_irqrestore(&bus_lock,flags);
}
}
static void i365_bset(u_short sock, u_short reg, u_char mask)
{
u_char d = i365_get(sock, reg);
d |= mask;
i365_set(sock, reg, d);
}
static void i365_bclr(u_short sock, u_short reg, u_char mask)
{
u_char d = i365_get(sock, reg);
d &= ~mask;
i365_set(sock, reg, d);
}
static void i365_bflip(u_short sock, u_short reg, u_char mask, int b)
{
u_char d = i365_get(sock, reg);
if (b)
d |= mask;
else
d &= ~mask;
i365_set(sock, reg, d);
}
static u_short i365_get_pair(u_short sock, u_short reg)
{
u_short a, b;
a = i365_get(sock, reg);
b = i365_get(sock, reg+1);
return (a + (b<<8));
}
static void i365_set_pair(u_short sock, u_short reg, u_short data)
{
i365_set(sock, reg, data & 0xff);
i365_set(sock, reg+1, data >> 8);
}
/*======================================================================
Code to save and restore global state information for Cirrus
PD67xx controllers, and to set and report global configuration
options.
The VIA controllers also use these routines, as they are mostly
Cirrus lookalikes, without the timing registers.
======================================================================*/
#define flip(v,b,f) (v = ((f)<0) ? v : ((f) ? ((v)|(b)) : ((v)&(~b))))
static void cirrus_get_state(u_short s)
{
int i;
cirrus_state_t *p = &socket[s].state.cirrus;
p->misc1 = i365_get(s, PD67_MISC_CTL_1);
p->misc1 &= (PD67_MC1_MEDIA_ENA | PD67_MC1_INPACK_ENA);
p->misc2 = i365_get(s, PD67_MISC_CTL_2);
for (i = 0; i < 6; i++)
p->timer[i] = i365_get(s, PD67_TIME_SETUP(0)+i);
}
static void cirrus_set_state(u_short s)
{
int i;
u_char misc;
cirrus_state_t *p = &socket[s].state.cirrus;
misc = i365_get(s, PD67_MISC_CTL_2);
i365_set(s, PD67_MISC_CTL_2, p->misc2);
if (misc & PD67_MC2_SUSPEND) mdelay(50);
misc = i365_get(s, PD67_MISC_CTL_1);
misc &= ~(PD67_MC1_MEDIA_ENA | PD67_MC1_INPACK_ENA);
i365_set(s, PD67_MISC_CTL_1, misc | p->misc1);
for (i = 0; i < 6; i++)
i365_set(s, PD67_TIME_SETUP(0)+i, p->timer[i]);
}
static u_int __init cirrus_set_opts(u_short s, char *buf)
{
struct i82365_socket *t = &socket[s];
cirrus_state_t *p = &socket[s].state.cirrus;
u_int mask = 0xffff;
if (has_ring == -1) has_ring = 1;
flip(p->misc2, PD67_MC2_IRQ15_RI, has_ring);
flip(p->misc2, PD67_MC2_DYNAMIC_MODE, dynamic_mode);
flip(p->misc2, PD67_MC2_FREQ_BYPASS, freq_bypass);
if (p->misc2 & PD67_MC2_IRQ15_RI)
strcat(buf, " [ring]");
if (p->misc2 & PD67_MC2_DYNAMIC_MODE)
strcat(buf, " [dyn mode]");
if (p->misc2 & PD67_MC2_FREQ_BYPASS)
strcat(buf, " [freq bypass]");
if (p->misc1 & PD67_MC1_INPACK_ENA)
strcat(buf, " [inpack]");
if (p->misc2 & PD67_MC2_IRQ15_RI)
mask &= ~0x8000;
if (has_led > 0) {
strcat(buf, " [led]");
mask &= ~0x1000;
}
if (has_dma > 0) {
strcat(buf, " [dma]");
mask &= ~0x0600;
}
if (!(t->flags & IS_VIA)) {
if (setup_time >= 0)
p->timer[0] = p->timer[3] = setup_time;
if (cmd_time > 0) {
p->timer[1] = cmd_time;
p->timer[4] = cmd_time*2+4;
}
if (p->timer[1] == 0) {
p->timer[1] = 6; p->timer[4] = 16;
if (p->timer[0] == 0)
p->timer[0] = p->timer[3] = 1;
}
if (recov_time >= 0)
p->timer[2] = p->timer[5] = recov_time;
buf += strlen(buf);
sprintf(buf, " [%d/%d/%d] [%d/%d/%d]", p->timer[0], p->timer[1],
p->timer[2], p->timer[3], p->timer[4], p->timer[5]);
}
return mask;
}
/*======================================================================
Code to save and restore global state information for Vadem VG468
and VG469 controllers, and to set and report global configuration
options.
======================================================================*/
static void vg46x_get_state(u_short s)
{
vg46x_state_t *p = &socket[s].state.vg46x;
p->ctl = i365_get(s, VG468_CTL);
if (socket[s].type == IS_VG469)
p->ema = i365_get(s, VG469_EXT_MODE);
}
static void vg46x_set_state(u_short s)
{
vg46x_state_t *p = &socket[s].state.vg46x;
i365_set(s, VG468_CTL, p->ctl);
if (socket[s].type == IS_VG469)
i365_set(s, VG469_EXT_MODE, p->ema);
}
static u_int __init vg46x_set_opts(u_short s, char *buf)
{
vg46x_state_t *p = &socket[s].state.vg46x;
flip(p->ctl, VG468_CTL_ASYNC, async_clock);
flip(p->ema, VG469_MODE_CABLE, cable_mode);
if (p->ctl & VG468_CTL_ASYNC)
strcat(buf, " [async]");
if (p->ctl & VG468_CTL_INPACK)
strcat(buf, " [inpack]");
if (socket[s].type == IS_VG469) {
u_char vsel = i365_get(s, VG469_VSELECT);
if (vsel & VG469_VSEL_EXT_STAT) {
strcat(buf, " [ext mode]");
if (vsel & VG469_VSEL_EXT_BUS)
strcat(buf, " [isa buf]");
}
if (p->ema & VG469_MODE_CABLE)
strcat(buf, " [cable]");
if (p->ema & VG469_MODE_COMPAT)
strcat(buf, " [c step]");
}
return 0xffff;
}
/*======================================================================
Generic routines to get and set controller options
======================================================================*/
static void get_bridge_state(u_short s)
{
struct i82365_socket *t = &socket[s];
if (t->flags & IS_CIRRUS)
cirrus_get_state(s);
else if (t->flags & IS_VADEM)
vg46x_get_state(s);
}
static void set_bridge_state(u_short s)
{
struct i82365_socket *t = &socket[s];
if (t->flags & IS_CIRRUS)
cirrus_set_state(s);
else {
i365_set(s, I365_GBLCTL, 0x00);
i365_set(s, I365_GENCTL, 0x00);
}
i365_bflip(s, I365_INTCTL, I365_INTR_ENA, t->intr);
if (t->flags & IS_VADEM)
vg46x_set_state(s);
}
static u_int __init set_bridge_opts(u_short s, u_short ns)
{
u_short i;
u_int m = 0xffff;
char buf[128];
for (i = s; i < s+ns; i++) {
if (socket[i].flags & IS_ALIVE) {
printk(KERN_INFO " host opts [%d]: already alive!\n", i);
continue;
}
buf[0] = '\0';
get_bridge_state(i);
if (socket[i].flags & IS_CIRRUS)
m = cirrus_set_opts(i, buf);
else if (socket[i].flags & IS_VADEM)
m = vg46x_set_opts(i, buf);
set_bridge_state(i);
printk(KERN_INFO " host opts [%d]:%s\n", i,
(*buf) ? buf : " none");
}
return m;
}
/*======================================================================
Interrupt testing code, for ISA and PCI interrupts
======================================================================*/
static volatile u_int irq_hits;
static u_short irq_sock;
static irqreturn_t i365_count_irq(int irq, void *dev)
{
i365_get(irq_sock, I365_CSC);
irq_hits++;
pr_debug("i82365: -> hit on irq %d\n", irq);
return IRQ_HANDLED;
}
static u_int __init test_irq(u_short sock, int irq)
{
pr_debug("i82365: testing ISA irq %d\n", irq);
if (request_irq(irq, i365_count_irq, IRQF_PROBE_SHARED, "scan",
i365_count_irq) != 0)
return 1;
irq_hits = 0; irq_sock = sock;
msleep(10);
if (irq_hits) {
free_irq(irq, i365_count_irq);
pr_debug("i82365: spurious hit!\n");
return 1;
}
/* Generate one interrupt */
i365_set(sock, I365_CSCINT, I365_CSC_DETECT | (irq << 4));
i365_bset(sock, I365_GENCTL, I365_CTL_SW_IRQ);
udelay(1000);
free_irq(irq, i365_count_irq);
/* mask all interrupts */
i365_set(sock, I365_CSCINT, 0);
pr_debug("i82365: hits = %d\n", irq_hits);
return (irq_hits != 1);
}
static u_int __init isa_scan(u_short sock, u_int mask0)
{
u_int mask1 = 0;
int i;
#ifdef __alpha__
#define PIC 0x4d0
/* Don't probe level-triggered interrupts -- reserved for PCI */
mask0 &= ~(inb(PIC) | (inb(PIC+1) << 8));
#endif
if (do_scan) {
set_bridge_state(sock);
i365_set(sock, I365_CSCINT, 0);
for (i = 0; i < 16; i++)
if ((mask0 & (1 << i)) && (test_irq(sock, i) == 0))
mask1 |= (1 << i);
for (i = 0; i < 16; i++)
if ((mask1 & (1 << i)) && (test_irq(sock, i) != 0))
mask1 ^= (1 << i);
}
printk(KERN_INFO " ISA irqs (");
if (mask1) {
printk("scanned");
} else {
/* Fallback: just find interrupts that aren't in use */
for (i = 0; i < 16; i++)
if ((mask0 & (1 << i)) && (_check_irq(i, IRQF_PROBE_SHARED) == 0))
mask1 |= (1 << i);
printk("default");
/* If scan failed, default to polled status */
if (!cs_irq && (poll_interval == 0)) poll_interval = HZ;
}
printk(") = ");
for (i = 0; i < 16; i++)
if (mask1 & (1<<i))
printk("%s%d", ((mask1 & ((1<<i)-1)) ? "," : ""), i);
if (mask1 == 0) printk("none!");
return mask1;
}
/*====================================================================*/
/* Time conversion functions */
static int to_cycles(int ns)
{
return ns/cycle_time;
}
/*====================================================================*/
static int __init identify(unsigned int port, u_short sock)
{
u_char val;
int type = -1;
/* Use the next free entry in the socket table */
socket[sockets].ioaddr = port;
socket[sockets].psock = sock;
/* Wake up a sleepy Cirrus controller */
if (wakeup) {
i365_bclr(sockets, PD67_MISC_CTL_2, PD67_MC2_SUSPEND);
/* Pause at least 50 ms */
mdelay(50);
}
if ((val = i365_get(sockets, I365_IDENT)) & 0x70)
return -1;
switch (val) {
case 0x82:
type = IS_I82365A; break;
case 0x83:
type = IS_I82365B; break;
case 0x84:
type = IS_I82365DF; break;
case 0x88: case 0x89: case 0x8a:
type = IS_IBM; break;
}
/* Check for Vadem VG-468 chips */
outb(0x0e, port);
outb(0x37, port);
i365_bset(sockets, VG468_MISC, VG468_MISC_VADEMREV);
val = i365_get(sockets, I365_IDENT);
if (val & I365_IDENT_VADEM) {
i365_bclr(sockets, VG468_MISC, VG468_MISC_VADEMREV);
type = ((val & 7) >= 4) ? IS_VG469 : IS_VG468;
}
/* Check for Ricoh chips */
val = i365_get(sockets, RF5C_CHIP_ID);
if ((val == RF5C_CHIP_RF5C296) || (val == RF5C_CHIP_RF5C396))
type = IS_RF5Cx96;
/* Check for Cirrus CL-PD67xx chips */
i365_set(sockets, PD67_CHIP_INFO, 0);
val = i365_get(sockets, PD67_CHIP_INFO);
if ((val & PD67_INFO_CHIP_ID) == PD67_INFO_CHIP_ID) {
val = i365_get(sockets, PD67_CHIP_INFO);
if ((val & PD67_INFO_CHIP_ID) == 0) {
type = (val & PD67_INFO_SLOTS) ? IS_PD672X : IS_PD6710;
i365_set(sockets, PD67_EXT_INDEX, 0xe5);
if (i365_get(sockets, PD67_EXT_INDEX) != 0xe5)
type = IS_VT83C469;
}
}
return type;
} /* identify */
/*======================================================================
See if a card is present, powered up, in IO mode, and already
bound to a (non PC Card) Linux driver. We leave these alone.
We make an exception for cards that seem to be serial devices.
======================================================================*/
static int __init is_alive(u_short sock)
{
u_char stat;
unsigned int start, stop;
stat = i365_get(sock, I365_STATUS);
start = i365_get_pair(sock, I365_IO(0)+I365_W_START);
stop = i365_get_pair(sock, I365_IO(0)+I365_W_STOP);
if ((stat & I365_CS_DETECT) && (stat & I365_CS_POWERON) &&
(i365_get(sock, I365_INTCTL) & I365_PC_IOCARD) &&
(i365_get(sock, I365_ADDRWIN) & I365_ENA_IO(0)) &&
((start & 0xfeef) != 0x02e8)) {
if (!request_region(start, stop-start+1, "i82365"))
return 1;
release_region(start, stop-start+1);
}
return 0;
}
/*====================================================================*/
static void __init add_socket(unsigned int port, int psock, int type)
{
socket[sockets].ioaddr = port;
socket[sockets].psock = psock;
socket[sockets].type = type;
socket[sockets].flags = pcic[type].flags;
if (is_alive(sockets))
socket[sockets].flags |= IS_ALIVE;
sockets++;
}
static void __init add_pcic(int ns, int type)
{
u_int mask = 0, i, base;
int isa_irq = 0;
struct i82365_socket *t = &socket[sockets-ns];
base = sockets-ns;
if (base == 0) printk("\n");
printk(KERN_INFO " %s", pcic[type].name);
printk(" ISA-to-PCMCIA at port %#x ofs 0x%02x",
t->ioaddr, t->psock*0x40);
printk(", %d socket%s\n", ns, ((ns > 1) ? "s" : ""));
/* Set host options, build basic interrupt mask */
if (irq_list_count == 0)
mask = irq_mask;
else
for (i = mask = 0; i < irq_list_count; i++)
mask |= (1<<irq_list[i]);
mask &= I365_MASK & set_bridge_opts(base, ns);
/* Scan for ISA interrupts */
mask = isa_scan(base, mask);
/* Poll if only two interrupts available */
if (!poll_interval) {
u_int tmp = (mask & 0xff20);
tmp = tmp & (tmp-1);
if ((tmp & (tmp-1)) == 0)
poll_interval = HZ;
}
/* Only try an ISA cs_irq if this is the first controller */
if (!grab_irq && (cs_irq || !poll_interval)) {
/* Avoid irq 12 unless it is explicitly requested */
u_int cs_mask = mask & ((cs_irq) ? (1<<cs_irq) : ~(1<<12));
for (cs_irq = 15; cs_irq > 0; cs_irq--)
if ((cs_mask & (1 << cs_irq)) &&
(_check_irq(cs_irq, IRQF_PROBE_SHARED) == 0))
break;
if (cs_irq) {
grab_irq = 1;
isa_irq = cs_irq;
printk(" status change on irq %d\n", cs_irq);
}
}
if (!isa_irq) {
if (poll_interval == 0)
poll_interval = HZ;
printk(" polling interval = %d ms\n",
poll_interval * 1000 / HZ);
}
/* Update socket interrupt information, capabilities */
for (i = 0; i < ns; i++) {
t[i].socket.features |= SS_CAP_PCCARD;
t[i].socket.map_size = 0x1000;
t[i].socket.irq_mask = mask;
t[i].cs_irq = isa_irq;
}
} /* add_pcic */
/*====================================================================*/
#ifdef CONFIG_PNP
static struct isapnp_device_id id_table[] __initdata = {
{ ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('P', 'N', 'P'),
ISAPNP_FUNCTION(0x0e00), (unsigned long) "Intel 82365-Compatible" },
{ ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('P', 'N', 'P'),
ISAPNP_FUNCTION(0x0e01), (unsigned long) "Cirrus Logic CL-PD6720" },
{ ISAPNP_ANY_ID, ISAPNP_ANY_ID, ISAPNP_VENDOR('P', 'N', 'P'),
ISAPNP_FUNCTION(0x0e02), (unsigned long) "VLSI VL82C146" },
{ 0 }
};
MODULE_DEVICE_TABLE(isapnp, id_table);
static struct pnp_dev *i82365_pnpdev;
#endif
static void __init isa_probe(void)
{
int i, j, sock, k, ns, id;
unsigned int port;
#ifdef CONFIG_PNP
struct isapnp_device_id *devid;
struct pnp_dev *dev;
for (devid = id_table; devid->vendor; devid++) {
if ((dev = pnp_find_dev(NULL, devid->vendor, devid->function, NULL))) {
if (pnp_device_attach(dev) < 0)
continue;
if (pnp_activate_dev(dev) < 0) {
printk("activate failed\n");
pnp_device_detach(dev);
break;
}
if (!pnp_port_valid(dev, 0)) {
printk("invalid resources ?\n");
pnp_device_detach(dev);
break;
}
i365_base = pnp_port_start(dev, 0);
i82365_pnpdev = dev;
break;
}
}
#endif
if (!request_region(i365_base, 2, "i82365")) {
if (sockets == 0)
printk("port conflict at %#lx\n", i365_base);
return;
}
id = identify(i365_base, 0);
if ((id == IS_I82365DF) && (identify(i365_base, 1) != id)) {
for (i = 0; i < 4; i++) {
if (i == ignore) continue;
port = i365_base + ((i & 1) << 2) + ((i & 2) << 1);
sock = (i & 1) << 1;
if (identify(port, sock) == IS_I82365DF) {
add_socket(port, sock, IS_VLSI);
add_pcic(1, IS_VLSI);
}
}
} else {
for (i = 0; i < 8; i += 2) {
if (sockets && !extra_sockets && (i == 4))
break;
port = i365_base + 2*(i>>2);
sock = (i & 3);
id = identify(port, sock);
if (id < 0) continue;
for (j = ns = 0; j < 2; j++) {
/* Does the socket exist? */
if ((ignore == i+j) || (identify(port, sock+j) < 0))
continue;
/* Check for bad socket decode */
for (k = 0; k <= sockets; k++)
i365_set(k, I365_MEM(0)+I365_W_OFF, k);
for (k = 0; k <= sockets; k++)
if (i365_get(k, I365_MEM(0)+I365_W_OFF) != k)
break;
if (k <= sockets) break;
add_socket(port, sock+j, id); ns++;
}
if (ns != 0) add_pcic(ns, id);
}
}
}
/*====================================================================*/
static irqreturn_t pcic_interrupt(int irq, void *dev)
{
int i, j, csc;
u_int events, active;
u_long flags = 0;
int handled = 0;
pr_debug("pcic_interrupt(%d)\n", irq);
for (j = 0; j < 20; j++) {
active = 0;
for (i = 0; i < sockets; i++) {
if (socket[i].cs_irq != irq)
continue;
handled = 1;
ISA_LOCK(i, flags);
csc = i365_get(i, I365_CSC);
if ((csc == 0) || (i365_get(i, I365_IDENT) & 0x70)) {
ISA_UNLOCK(i, flags);
continue;
}
events = (csc & I365_CSC_DETECT) ? SS_DETECT : 0;
if (i365_get(i, I365_INTCTL) & I365_PC_IOCARD)
events |= (csc & I365_CSC_STSCHG) ? SS_STSCHG : 0;
else {
events |= (csc & I365_CSC_BVD1) ? SS_BATDEAD : 0;
events |= (csc & I365_CSC_BVD2) ? SS_BATWARN : 0;
events |= (csc & I365_CSC_READY) ? SS_READY : 0;
}
ISA_UNLOCK(i, flags);
pr_debug("socket %d event 0x%02x\n", i, events);
if (events)
pcmcia_parse_events(&socket[i].socket, events);
active |= events;
}
if (!active) break;
}
if (j == 20)
printk(KERN_NOTICE "i82365: infinite loop in interrupt handler\n");
pr_debug("pcic_interrupt done\n");
return IRQ_RETVAL(handled);
} /* pcic_interrupt */
static void pcic_interrupt_wrapper(u_long data)
{
pcic_interrupt(0, NULL);
poll_timer.expires = jiffies + poll_interval;
add_timer(&poll_timer);
}
/*====================================================================*/
static int i365_get_status(u_short sock, u_int *value)
{
u_int status;
status = i365_get(sock, I365_STATUS);
*value = ((status & I365_CS_DETECT) == I365_CS_DETECT)
? SS_DETECT : 0;
if (i365_get(sock, I365_INTCTL) & I365_PC_IOCARD)
*value |= (status & I365_CS_STSCHG) ? 0 : SS_STSCHG;
else {
*value |= (status & I365_CS_BVD1) ? 0 : SS_BATDEAD;
*value |= (status & I365_CS_BVD2) ? 0 : SS_BATWARN;
}
*value |= (status & I365_CS_WRPROT) ? SS_WRPROT : 0;
*value |= (status & I365_CS_READY) ? SS_READY : 0;
*value |= (status & I365_CS_POWERON) ? SS_POWERON : 0;
if (socket[sock].type == IS_VG469) {
status = i365_get(sock, VG469_VSENSE);
if (socket[sock].psock & 1) {
*value |= (status & VG469_VSENSE_B_VS1) ? 0 : SS_3VCARD;
*value |= (status & VG469_VSENSE_B_VS2) ? 0 : SS_XVCARD;
} else {
*value |= (status & VG469_VSENSE_A_VS1) ? 0 : SS_3VCARD;
*value |= (status & VG469_VSENSE_A_VS2) ? 0 : SS_XVCARD;
}
}
pr_debug("GetStatus(%d) = %#4.4x\n", sock, *value);
return 0;
} /* i365_get_status */
/*====================================================================*/
static int i365_set_socket(u_short sock, socket_state_t *state)
{
struct i82365_socket *t = &socket[sock];
u_char reg;
pr_debug("SetSocket(%d, flags %#3.3x, Vcc %d, Vpp %d, "
"io_irq %d, csc_mask %#2.2x)\n", sock, state->flags,
state->Vcc, state->Vpp, state->io_irq, state->csc_mask);
/* First set global controller options */
set_bridge_state(sock);
/* IO card, RESET flag, IO interrupt */
reg = t->intr;
reg |= state->io_irq;
reg |= (state->flags & SS_RESET) ? 0 : I365_PC_RESET;
reg |= (state->flags & SS_IOCARD) ? I365_PC_IOCARD : 0;
i365_set(sock, I365_INTCTL, reg);
reg = I365_PWR_NORESET;
if (state->flags & SS_PWR_AUTO) reg |= I365_PWR_AUTO;
if (state->flags & SS_OUTPUT_ENA) reg |= I365_PWR_OUT;
if (t->flags & IS_CIRRUS) {
if (state->Vpp != 0) {
if (state->Vpp == 120)
reg |= I365_VPP1_12V;
else if (state->Vpp == state->Vcc)
reg |= I365_VPP1_5V;
else return -EINVAL;
}
if (state->Vcc != 0) {
reg |= I365_VCC_5V;
if (state->Vcc == 33)
i365_bset(sock, PD67_MISC_CTL_1, PD67_MC1_VCC_3V);
else if (state->Vcc == 50)
i365_bclr(sock, PD67_MISC_CTL_1, PD67_MC1_VCC_3V);
else return -EINVAL;
}
} else if (t->flags & IS_VG_PWR) {
if (state->Vpp != 0) {
if (state->Vpp == 120)
reg |= I365_VPP1_12V;
else if (state->Vpp == state->Vcc)
reg |= I365_VPP1_5V;
else return -EINVAL;
}
if (state->Vcc != 0) {
reg |= I365_VCC_5V;
if (state->Vcc == 33)
i365_bset(sock, VG469_VSELECT, VG469_VSEL_VCC);
else if (state->Vcc == 50)
i365_bclr(sock, VG469_VSELECT, VG469_VSEL_VCC);
else return -EINVAL;
}
} else if (t->flags & IS_DF_PWR) {
switch (state->Vcc) {
case 0: break;
case 33: reg |= I365_VCC_3V; break;
case 50: reg |= I365_VCC_5V; break;
default: return -EINVAL;
}
switch (state->Vpp) {
case 0: break;
case 50: reg |= I365_VPP1_5V; break;
case 120: reg |= I365_VPP1_12V; break;
default: return -EINVAL;
}
} else {
switch (state->Vcc) {
case 0: break;
case 50: reg |= I365_VCC_5V; break;
default: return -EINVAL;
}
switch (state->Vpp) {
case 0: break;
case 50: reg |= I365_VPP1_5V | I365_VPP2_5V; break;
case 120: reg |= I365_VPP1_12V | I365_VPP2_12V; break;
default: return -EINVAL;
}
}
if (reg != i365_get(sock, I365_POWER))
i365_set(sock, I365_POWER, reg);
/* Chipset-specific functions */
if (t->flags & IS_CIRRUS) {
/* Speaker control */
i365_bflip(sock, PD67_MISC_CTL_1, PD67_MC1_SPKR_ENA,
state->flags & SS_SPKR_ENA);
}
/* Card status change interrupt mask */
reg = t->cs_irq << 4;
if (state->csc_mask & SS_DETECT) reg |= I365_CSC_DETECT;
if (state->flags & SS_IOCARD) {
if (state->csc_mask & SS_STSCHG) reg |= I365_CSC_STSCHG;
} else {
if (state->csc_mask & SS_BATDEAD) reg |= I365_CSC_BVD1;
if (state->csc_mask & SS_BATWARN) reg |= I365_CSC_BVD2;
if (state->csc_mask & SS_READY) reg |= I365_CSC_READY;
}
i365_set(sock, I365_CSCINT, reg);
i365_get(sock, I365_CSC);
return 0;
} /* i365_set_socket */
/*====================================================================*/
static int i365_set_io_map(u_short sock, struct pccard_io_map *io)
{
u_char map, ioctl;
pr_debug("SetIOMap(%d, %d, %#2.2x, %d ns, "
"%#llx-%#llx)\n", sock, io->map, io->flags, io->speed,
(unsigned long long)io->start, (unsigned long long)io->stop);
map = io->map;
if ((map > 1) || (io->start > 0xffff) || (io->stop > 0xffff) ||
(io->stop < io->start)) return -EINVAL;
/* Turn off the window before changing anything */
if (i365_get(sock, I365_ADDRWIN) & I365_ENA_IO(map))
i365_bclr(sock, I365_ADDRWIN, I365_ENA_IO(map));
i365_set_pair(sock, I365_IO(map)+I365_W_START, io->start);
i365_set_pair(sock, I365_IO(map)+I365_W_STOP, io->stop);
ioctl = i365_get(sock, I365_IOCTL) & ~I365_IOCTL_MASK(map);
if (io->speed) ioctl |= I365_IOCTL_WAIT(map);
if (io->flags & MAP_0WS) ioctl |= I365_IOCTL_0WS(map);
if (io->flags & MAP_16BIT) ioctl |= I365_IOCTL_16BIT(map);
if (io->flags & MAP_AUTOSZ) ioctl |= I365_IOCTL_IOCS16(map);
i365_set(sock, I365_IOCTL, ioctl);
/* Turn on the window if necessary */
if (io->flags & MAP_ACTIVE)
i365_bset(sock, I365_ADDRWIN, I365_ENA_IO(map));
return 0;
} /* i365_set_io_map */
/*====================================================================*/
static int i365_set_mem_map(u_short sock, struct pccard_mem_map *mem)
{
u_short base, i;
u_char map;
pr_debug("SetMemMap(%d, %d, %#2.2x, %d ns, %#llx-%#llx, "
"%#x)\n", sock, mem->map, mem->flags, mem->speed,
(unsigned long long)mem->res->start,
(unsigned long long)mem->res->end, mem->card_start);
map = mem->map;
if ((map > 4) || (mem->card_start > 0x3ffffff) ||
(mem->res->start > mem->res->end) || (mem->speed > 1000))
return -EINVAL;
if ((mem->res->start > 0xffffff) || (mem->res->end > 0xffffff))
return -EINVAL;
/* Turn off the window before changing anything */
if (i365_get(sock, I365_ADDRWIN) & I365_ENA_MEM(map))
i365_bclr(sock, I365_ADDRWIN, I365_ENA_MEM(map));
base = I365_MEM(map);
i = (mem->res->start >> 12) & 0x0fff;
if (mem->flags & MAP_16BIT) i |= I365_MEM_16BIT;
if (mem->flags & MAP_0WS) i |= I365_MEM_0WS;
i365_set_pair(sock, base+I365_W_START, i);
i = (mem->res->end >> 12) & 0x0fff;
switch (to_cycles(mem->speed)) {
case 0: break;
case 1: i |= I365_MEM_WS0; break;
case 2: i |= I365_MEM_WS1; break;
default: i |= I365_MEM_WS1 | I365_MEM_WS0; break;
}
i365_set_pair(sock, base+I365_W_STOP, i);
i = ((mem->card_start - mem->res->start) >> 12) & 0x3fff;
if (mem->flags & MAP_WRPROT) i |= I365_MEM_WRPROT;
if (mem->flags & MAP_ATTRIB) i |= I365_MEM_REG;
i365_set_pair(sock, base+I365_W_OFF, i);
/* Turn on the window if necessary */
if (mem->flags & MAP_ACTIVE)
i365_bset(sock, I365_ADDRWIN, I365_ENA_MEM(map));
return 0;
} /* i365_set_mem_map */
#if 0 /* driver model ordering issue */
/*======================================================================
Routines for accessing socket information and register dumps via
/sys/class/pcmcia_socket/...
======================================================================*/
static ssize_t show_info(struct class_device *class_dev, char *buf)
{
struct i82365_socket *s = container_of(class_dev, struct i82365_socket, socket.dev);
return sprintf(buf, "type: %s\npsock: %d\n",
pcic[s->type].name, s->psock);
}
static ssize_t show_exca(struct class_device *class_dev, char *buf)
{
struct i82365_socket *s = container_of(class_dev, struct i82365_socket, socket.dev);
unsigned short sock;
int i;
ssize_t ret = 0;
unsigned long flags = 0;
sock = s->number;
ISA_LOCK(sock, flags);
for (i = 0; i < 0x40; i += 4) {
ret += sprintf(buf, "%02x %02x %02x %02x%s",
i365_get(sock,i), i365_get(sock,i+1),
i365_get(sock,i+2), i365_get(sock,i+3),
((i % 16) == 12) ? "\n" : " ");
buf += ret;
}
ISA_UNLOCK(sock, flags);
return ret;
}
static CLASS_DEVICE_ATTR(exca, S_IRUGO, show_exca, NULL);
static CLASS_DEVICE_ATTR(info, S_IRUGO, show_info, NULL);
#endif
/*====================================================================*/
/* this is horribly ugly... proper locking needs to be done here at
* some time... */
#define LOCKED(x) do { \
int retval; \
unsigned long flags; \
spin_lock_irqsave(&isa_lock, flags); \
retval = x; \
spin_unlock_irqrestore(&isa_lock, flags); \
return retval; \
} while (0)
static int pcic_get_status(struct pcmcia_socket *s, u_int *value)
{
unsigned int sock = container_of(s, struct i82365_socket, socket)->number;
if (socket[sock].flags & IS_ALIVE) {
*value = 0;
return -EINVAL;
}
LOCKED(i365_get_status(sock, value));
}
static int pcic_set_socket(struct pcmcia_socket *s, socket_state_t *state)
{
unsigned int sock = container_of(s, struct i82365_socket, socket)->number;
if (socket[sock].flags & IS_ALIVE)
return -EINVAL;
LOCKED(i365_set_socket(sock, state));
}
static int pcic_set_io_map(struct pcmcia_socket *s, struct pccard_io_map *io)
{
unsigned int sock = container_of(s, struct i82365_socket, socket)->number;
if (socket[sock].flags & IS_ALIVE)
return -EINVAL;
LOCKED(i365_set_io_map(sock, io));
}
static int pcic_set_mem_map(struct pcmcia_socket *s, struct pccard_mem_map *mem)
{
unsigned int sock = container_of(s, struct i82365_socket, socket)->number;
if (socket[sock].flags & IS_ALIVE)
return -EINVAL;
LOCKED(i365_set_mem_map(sock, mem));
}
static int pcic_init(struct pcmcia_socket *s)
{
int i;
struct resource res = { .start = 0, .end = 0x1000 };
pccard_io_map io = { 0, 0, 0, 0, 1 };
pccard_mem_map mem = { .res = &res, };
for (i = 0; i < 2; i++) {
io.map = i;
pcic_set_io_map(s, &io);
}
for (i = 0; i < 5; i++) {
mem.map = i;
pcic_set_mem_map(s, &mem);
}
return 0;
}
static struct pccard_operations pcic_operations = {
.init = pcic_init,
.get_status = pcic_get_status,
.set_socket = pcic_set_socket,
.set_io_map = pcic_set_io_map,
.set_mem_map = pcic_set_mem_map,
};
/*====================================================================*/
static struct platform_driver i82365_driver = {
.driver = {
.name = "i82365",
.owner = THIS_MODULE,
},
};
static struct platform_device *i82365_device;
static int __init init_i82365(void)
{
int i, ret;
ret = platform_driver_register(&i82365_driver);
if (ret)
goto err_out;
i82365_device = platform_device_alloc("i82365", 0);
if (i82365_device) {
ret = platform_device_add(i82365_device);
if (ret)
platform_device_put(i82365_device);
} else
ret = -ENOMEM;
if (ret)
goto err_driver_unregister;
printk(KERN_INFO "Intel ISA PCIC probe: ");
sockets = 0;
isa_probe();
if (sockets == 0) {
printk("not found.\n");
ret = -ENODEV;
goto err_dev_unregister;
}
/* Set up interrupt handler(s) */
if (grab_irq != 0)
ret = request_irq(cs_irq, pcic_interrupt, 0, "i82365", pcic_interrupt);
if (ret)
goto err_socket_release;
/* register sockets with the pcmcia core */
for (i = 0; i < sockets; i++) {
socket[i].socket.dev.parent = &i82365_device->dev;
socket[i].socket.ops = &pcic_operations;
socket[i].socket.resource_ops = &pccard_nonstatic_ops;
socket[i].socket.owner = THIS_MODULE;
socket[i].number = i;
ret = pcmcia_register_socket(&socket[i].socket);
if (!ret)
socket[i].flags |= IS_REGISTERED;
#if 0 /* driver model ordering issue */
class_device_create_file(&socket[i].socket.dev,
&class_device_attr_info);
class_device_create_file(&socket[i].socket.dev,
&class_device_attr_exca);
#endif
}
/* Finally, schedule a polling interrupt */
if (poll_interval != 0) {
poll_timer.function = pcic_interrupt_wrapper;
poll_timer.data = 0;
init_timer(&poll_timer);
poll_timer.expires = jiffies + poll_interval;
add_timer(&poll_timer);
}
return 0;
err_socket_release:
for (i = 0; i < sockets; i++) {
/* Turn off all interrupt sources! */
i365_set(i, I365_CSCINT, 0);
release_region(socket[i].ioaddr, 2);
}
err_dev_unregister:
platform_device_unregister(i82365_device);
release_region(i365_base, 2);
#ifdef CONFIG_PNP
if (i82365_pnpdev)
pnp_disable_dev(i82365_pnpdev);
#endif
err_driver_unregister:
platform_driver_unregister(&i82365_driver);
err_out:
return ret;
} /* init_i82365 */
static void __exit exit_i82365(void)
{
int i;
for (i = 0; i < sockets; i++) {
if (socket[i].flags & IS_REGISTERED)
pcmcia_unregister_socket(&socket[i].socket);
}
platform_device_unregister(i82365_device);
if (poll_interval != 0)
del_timer_sync(&poll_timer);
if (grab_irq != 0)
free_irq(cs_irq, pcic_interrupt);
for (i = 0; i < sockets; i++) {
/* Turn off all interrupt sources! */
i365_set(i, I365_CSCINT, 0);
release_region(socket[i].ioaddr, 2);
}
release_region(i365_base, 2);
#ifdef CONFIG_PNP
if (i82365_pnpdev)
pnp_disable_dev(i82365_pnpdev);
#endif
platform_driver_unregister(&i82365_driver);
} /* exit_i82365 */
module_init(init_i82365);
module_exit(exit_i82365);
MODULE_LICENSE("Dual MPL/GPL");
/*====================================================================*/
| gpl-2.0 |
drewx2/caf-kernel | tools/power/cpupower/debug/i386/dump_psb.c | 9763 | 3668 | /*
* dump_psb. (c) 2004, Dave Jones, Red Hat Inc.
* Licensed under the GPL v2.
*/
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define _GNU_SOURCE
#include <getopt.h>
#include <sys/mman.h>
#define LEN (0x100000 - 0xc0000)
#define OFFSET (0xc0000)
#ifndef __packed
#define __packed __attribute((packed))
#endif
static long relevant;
static const int fid_to_mult[32] = {
110, 115, 120, 125, 50, 55, 60, 65,
70, 75, 80, 85, 90, 95, 100, 105,
30, 190, 40, 200, 130, 135, 140, 210,
150, 225, 160, 165, 170, 180, -1, -1,
};
static const int vid_to_voltage[32] = {
2000, 1950, 1900, 1850, 1800, 1750, 1700, 1650,
1600, 1550, 1500, 1450, 1400, 1350, 1300, 0,
1275, 1250, 1225, 1200, 1175, 1150, 1125, 1100,
1075, 1050, 1024, 1000, 975, 950, 925, 0,
};
struct psb_header {
char signature[10];
u_char version;
u_char flags;
u_short settlingtime;
u_char res1;
u_char numpst;
} __packed;
struct pst_header {
u_int32_t cpuid;
u_char fsb;
u_char maxfid;
u_char startvid;
u_char numpstates;
} __packed;
static u_int fsb;
static u_int sgtc;
static int
decode_pst(char *p, int npstates)
{
int i;
int freq, fid, vid;
for (i = 0; i < npstates; ++i) {
fid = *p++;
vid = *p++;
freq = 100 * fid_to_mult[fid] * fsb;
printf(" %2d %8dkHz FID %02x (%2d.%01d) VID %02x (%4dmV)\n",
i,
freq,
fid, fid_to_mult[fid]/10, fid_to_mult[fid]%10,
vid, vid_to_voltage[vid]);
}
return 0;
}
static
void decode_psb(char *p, int numpst)
{
int i;
struct psb_header *psb;
struct pst_header *pst;
psb = (struct psb_header*) p;
if (psb->version != 0x12)
return;
printf("PSB version: %hhx flags: %hhx settling time %hhuus res1 %hhx num pst %hhu\n",
psb->version,
psb->flags,
psb->settlingtime,
psb->res1,
psb->numpst);
sgtc = psb->settlingtime * 100;
if (sgtc < 10000)
sgtc = 10000;
p = ((char *) psb) + sizeof(struct psb_header);
if (numpst < 0)
numpst = psb->numpst;
else
printf("Overriding number of pst :%d\n", numpst);
for (i = 0; i < numpst; i++) {
pst = (struct pst_header*) p;
if (relevant != 0) {
if (relevant!= pst->cpuid)
goto next_one;
}
printf(" PST %d cpuid %.3x fsb %hhu mfid %hhx svid %hhx numberstates %hhu\n",
i+1,
pst->cpuid,
pst->fsb,
pst->maxfid,
pst->startvid,
pst->numpstates);
fsb = pst->fsb;
decode_pst(p + sizeof(struct pst_header), pst->numpstates);
next_one:
p += sizeof(struct pst_header) + 2*pst->numpstates;
}
}
static struct option info_opts[] = {
{.name = "numpst", .has_arg=no_argument, .flag=NULL, .val='n'},
};
void print_help(void)
{
printf ("Usage: dump_psb [options]\n");
printf ("Options:\n");
printf (" -n, --numpst Set number of PST tables to scan\n");
printf (" -r, --relevant Only display PSTs relevant to cpuid N\n");
}
int
main(int argc, char *argv[])
{
int fd;
int numpst=-1;
int ret=0, cont=1;
char *mem = NULL;
char *p;
do {
ret = getopt_long(argc, argv, "hr:n:", info_opts, NULL);
switch (ret){
case '?':
case 'h':
print_help();
cont = 0;
break;
case 'r':
relevant = strtol(optarg, NULL, 16);
break;
case 'n':
numpst = strtol(optarg, NULL, 10);
break;
case -1:
cont = 0;
break;
}
} while(cont);
fd = open("/dev/mem", O_RDONLY);
if (fd < 0) {
printf ("Couldn't open /dev/mem. Are you root?\n");
exit(1);
}
mem = mmap(mem, 0x100000 - 0xc0000, PROT_READ, MAP_SHARED, fd, 0xc0000);
close(fd);
for (p = mem; p - mem < LEN; p+=16) {
if (memcmp(p, "AMDK7PNOW!", 10) == 0) {
decode_psb(p, numpst);
break;
}
}
munmap(mem, LEN);
return 0;
}
| gpl-2.0 |
CyanHacker-Lollipop/kernel_sony_msm8974 | arch/mips/lib/iomap.c | 12579 | 4626 | /*
* Implement the default iomap interfaces
*
* (C) Copyright 2004 Linus Torvalds
* (C) Copyright 2006 Ralf Baechle <ralf@linux-mips.org>
* (C) Copyright 2007 MIPS Technologies, Inc.
* written by Ralf Baechle <ralf@linux-mips.org>
*/
#include <linux/module.h>
#include <asm/io.h>
/*
* Read/write from/to an (offsettable) iomem cookie. It might be a PIO
* access or a MMIO access, these functions don't care. The info is
* encoded in the hardware mapping set up by the mapping functions
* (or the cookie itself, depending on implementation and hw).
*
* The generic routines don't assume any hardware mappings, and just
* encode the PIO/MMIO as part of the cookie. They coldly assume that
* the MMIO IO mappings are not in the low address range.
*
* Architectures for which this is not true can't use this generic
* implementation and should do their own copy.
*/
#define PIO_MASK 0x0ffffUL
unsigned int ioread8(void __iomem *addr)
{
return readb(addr);
}
EXPORT_SYMBOL(ioread8);
unsigned int ioread16(void __iomem *addr)
{
return readw(addr);
}
EXPORT_SYMBOL(ioread16);
unsigned int ioread16be(void __iomem *addr)
{
return be16_to_cpu(__raw_readw(addr));
}
EXPORT_SYMBOL(ioread16be);
unsigned int ioread32(void __iomem *addr)
{
return readl(addr);
}
EXPORT_SYMBOL(ioread32);
unsigned int ioread32be(void __iomem *addr)
{
return be32_to_cpu(__raw_readl(addr));
}
EXPORT_SYMBOL(ioread32be);
void iowrite8(u8 val, void __iomem *addr)
{
writeb(val, addr);
}
EXPORT_SYMBOL(iowrite8);
void iowrite16(u16 val, void __iomem *addr)
{
writew(val, addr);
}
EXPORT_SYMBOL(iowrite16);
void iowrite16be(u16 val, void __iomem *addr)
{
__raw_writew(cpu_to_be16(val), addr);
}
EXPORT_SYMBOL(iowrite16be);
void iowrite32(u32 val, void __iomem *addr)
{
writel(val, addr);
}
EXPORT_SYMBOL(iowrite32);
void iowrite32be(u32 val, void __iomem *addr)
{
__raw_writel(cpu_to_be32(val), addr);
}
EXPORT_SYMBOL(iowrite32be);
/*
* These are the "repeat MMIO read/write" functions.
* Note the "__raw" accesses, since we don't want to
* convert to CPU byte order. We write in "IO byte
* order" (we also don't have IO barriers).
*/
static inline void mmio_insb(void __iomem *addr, u8 *dst, int count)
{
while (--count >= 0) {
u8 data = __raw_readb(addr);
*dst = data;
dst++;
}
}
static inline void mmio_insw(void __iomem *addr, u16 *dst, int count)
{
while (--count >= 0) {
u16 data = __raw_readw(addr);
*dst = data;
dst++;
}
}
static inline void mmio_insl(void __iomem *addr, u32 *dst, int count)
{
while (--count >= 0) {
u32 data = __raw_readl(addr);
*dst = data;
dst++;
}
}
static inline void mmio_outsb(void __iomem *addr, const u8 *src, int count)
{
while (--count >= 0) {
__raw_writeb(*src, addr);
src++;
}
}
static inline void mmio_outsw(void __iomem *addr, const u16 *src, int count)
{
while (--count >= 0) {
__raw_writew(*src, addr);
src++;
}
}
static inline void mmio_outsl(void __iomem *addr, const u32 *src, int count)
{
while (--count >= 0) {
__raw_writel(*src, addr);
src++;
}
}
void ioread8_rep(void __iomem *addr, void *dst, unsigned long count)
{
mmio_insb(addr, dst, count);
}
EXPORT_SYMBOL(ioread8_rep);
void ioread16_rep(void __iomem *addr, void *dst, unsigned long count)
{
mmio_insw(addr, dst, count);
}
EXPORT_SYMBOL(ioread16_rep);
void ioread32_rep(void __iomem *addr, void *dst, unsigned long count)
{
mmio_insl(addr, dst, count);
}
EXPORT_SYMBOL(ioread32_rep);
void iowrite8_rep(void __iomem *addr, const void *src, unsigned long count)
{
mmio_outsb(addr, src, count);
}
EXPORT_SYMBOL(iowrite8_rep);
void iowrite16_rep(void __iomem *addr, const void *src, unsigned long count)
{
mmio_outsw(addr, src, count);
}
EXPORT_SYMBOL(iowrite16_rep);
void iowrite32_rep(void __iomem *addr, const void *src, unsigned long count)
{
mmio_outsl(addr, src, count);
}
EXPORT_SYMBOL(iowrite32_rep);
/*
* Create a virtual mapping cookie for an IO port range
*
* This uses the same mapping are as the in/out family which has to be setup
* by the platform initialization code.
*
* Just to make matters somewhat more interesting on MIPS systems with
* multiple host bridge each will have it's own ioport address space.
*/
static void __iomem *ioport_map_legacy(unsigned long port, unsigned int nr)
{
return (void __iomem *) (mips_io_port_base + port);
}
void __iomem *ioport_map(unsigned long port, unsigned int nr)
{
if (port > PIO_MASK)
return NULL;
return ioport_map_legacy(port, nr);
}
EXPORT_SYMBOL(ioport_map);
void ioport_unmap(void __iomem *addr)
{
/* Nothing to do */
}
EXPORT_SYMBOL(ioport_unmap);
| gpl-2.0 |
rkollataj/linux-can-next | drivers/gpu/drm/amd/powerplay/smumgr/iceland_smc.c | 36 | 88449 | /*
* Copyright 2015 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
*/
#include "iceland_smc.h"
#include "smu7_dyn_defaults.h"
#include "smu7_hwmgr.h"
#include "hardwaremanager.h"
#include "ppatomctrl.h"
#include "pp_debug.h"
#include "cgs_common.h"
#include "atombios.h"
#include "pppcielanes.h"
#include "pp_endian.h"
#include "smu7_ppsmc.h"
#include "smu71_discrete.h"
#include "smu/smu_7_1_1_d.h"
#include "smu/smu_7_1_1_sh_mask.h"
#include "gmc/gmc_8_1_d.h"
#include "gmc/gmc_8_1_sh_mask.h"
#include "bif/bif_5_0_d.h"
#include "bif/bif_5_0_sh_mask.h"
#include "dce/dce_10_0_d.h"
#include "dce/dce_10_0_sh_mask.h"
#include "processpptables.h"
#include "iceland_smumgr.h"
#define VOLTAGE_SCALE 4
#define POWERTUNE_DEFAULT_SET_MAX 1
#define VOLTAGE_VID_OFFSET_SCALE1 625
#define VOLTAGE_VID_OFFSET_SCALE2 100
#define MC_CG_ARB_FREQ_F1 0x0b
#define VDDC_VDDCI_DELTA 200
#define DEVICE_ID_VI_ICELAND_M_6900 0x6900
#define DEVICE_ID_VI_ICELAND_M_6901 0x6901
#define DEVICE_ID_VI_ICELAND_M_6902 0x6902
#define DEVICE_ID_VI_ICELAND_M_6903 0x6903
static const struct iceland_pt_defaults defaults_iceland = {
/*
* sviLoadLIneEn, SviLoadLineVddC, TDC_VDDC_ThrottleReleaseLimitPerc,
* TDC_MAWt, TdcWaterfallCtl, DTEAmbientTempBase, DisplayCac, BAPM_TEMP_GRADIENT
*/
1, 0xF, 0xFD, 0x19, 5, 45, 0, 0xB0000,
{ 0x79, 0x253, 0x25D, 0xAE, 0x72, 0x80, 0x83, 0x86, 0x6F, 0xC8, 0xC9, 0xC9, 0x2F, 0x4D, 0x61 },
{ 0x17C, 0x172, 0x180, 0x1BC, 0x1B3, 0x1BD, 0x206, 0x200, 0x203, 0x25D, 0x25A, 0x255, 0x2C3, 0x2C5, 0x2B4 }
};
/* 35W - XT, XTL */
static const struct iceland_pt_defaults defaults_icelandxt = {
/*
* sviLoadLIneEn, SviLoadLineVddC,
* TDC_VDDC_ThrottleReleaseLimitPerc, TDC_MAWt,
* TdcWaterfallCtl, DTEAmbientTempBase, DisplayCac,
* BAPM_TEMP_GRADIENT
*/
1, 0xF, 0xFD, 0x19, 5, 45, 0, 0x0,
{ 0xA7, 0x0, 0x0, 0xB5, 0x0, 0x0, 0x9F, 0x0, 0x0, 0xD6, 0x0, 0x0, 0xD7, 0x0, 0x0},
{ 0x1EA, 0x0, 0x0, 0x224, 0x0, 0x0, 0x25E, 0x0, 0x0, 0x28E, 0x0, 0x0, 0x2AB, 0x0, 0x0}
};
/* 25W - PRO, LE */
static const struct iceland_pt_defaults defaults_icelandpro = {
/*
* sviLoadLIneEn, SviLoadLineVddC,
* TDC_VDDC_ThrottleReleaseLimitPerc, TDC_MAWt,
* TdcWaterfallCtl, DTEAmbientTempBase, DisplayCac,
* BAPM_TEMP_GRADIENT
*/
1, 0xF, 0xFD, 0x19, 5, 45, 0, 0x0,
{ 0xB7, 0x0, 0x0, 0xC3, 0x0, 0x0, 0xB5, 0x0, 0x0, 0xEA, 0x0, 0x0, 0xE6, 0x0, 0x0},
{ 0x1EA, 0x0, 0x0, 0x224, 0x0, 0x0, 0x25E, 0x0, 0x0, 0x28E, 0x0, 0x0, 0x2AB, 0x0, 0x0}
};
static void iceland_initialize_power_tune_defaults(struct pp_hwmgr *hwmgr)
{
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
struct cgs_system_info sys_info = {0};
uint32_t dev_id;
sys_info.size = sizeof(struct cgs_system_info);
sys_info.info_id = CGS_SYSTEM_INFO_PCIE_DEV;
cgs_query_system_info(hwmgr->device, &sys_info);
dev_id = (uint32_t)sys_info.value;
switch (dev_id) {
case DEVICE_ID_VI_ICELAND_M_6900:
case DEVICE_ID_VI_ICELAND_M_6903:
smu_data->power_tune_defaults = &defaults_icelandxt;
break;
case DEVICE_ID_VI_ICELAND_M_6901:
case DEVICE_ID_VI_ICELAND_M_6902:
smu_data->power_tune_defaults = &defaults_icelandpro;
break;
default:
smu_data->power_tune_defaults = &defaults_iceland;
pr_warning("Unknown V.I. Device ID.\n");
break;
}
return;
}
static int iceland_populate_svi_load_line(struct pp_hwmgr *hwmgr)
{
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
const struct iceland_pt_defaults *defaults = smu_data->power_tune_defaults;
smu_data->power_tune_table.SviLoadLineEn = defaults->svi_load_line_en;
smu_data->power_tune_table.SviLoadLineVddC = defaults->svi_load_line_vddc;
smu_data->power_tune_table.SviLoadLineTrimVddC = 3;
smu_data->power_tune_table.SviLoadLineOffsetVddC = 0;
return 0;
}
static int iceland_populate_tdc_limit(struct pp_hwmgr *hwmgr)
{
uint16_t tdc_limit;
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
const struct iceland_pt_defaults *defaults = smu_data->power_tune_defaults;
tdc_limit = (uint16_t)(hwmgr->dyn_state.cac_dtp_table->usTDC * 256);
smu_data->power_tune_table.TDC_VDDC_PkgLimit =
CONVERT_FROM_HOST_TO_SMC_US(tdc_limit);
smu_data->power_tune_table.TDC_VDDC_ThrottleReleaseLimitPerc =
defaults->tdc_vddc_throttle_release_limit_perc;
smu_data->power_tune_table.TDC_MAWt = defaults->tdc_mawt;
return 0;
}
static int iceland_populate_dw8(struct pp_hwmgr *hwmgr, uint32_t fuse_table_offset)
{
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
const struct iceland_pt_defaults *defaults = smu_data->power_tune_defaults;
uint32_t temp;
if (smu7_read_smc_sram_dword(hwmgr->smumgr,
fuse_table_offset +
offsetof(SMU71_Discrete_PmFuses, TdcWaterfallCtl),
(uint32_t *)&temp, SMC_RAM_END))
PP_ASSERT_WITH_CODE(false,
"Attempt to read PmFuses.DW6 (SviLoadLineEn) from SMC Failed!",
return -EINVAL);
else
smu_data->power_tune_table.TdcWaterfallCtl = defaults->tdc_waterfall_ctl;
return 0;
}
static int iceland_populate_temperature_scaler(struct pp_hwmgr *hwmgr)
{
return 0;
}
static int iceland_populate_gnb_lpml(struct pp_hwmgr *hwmgr)
{
int i;
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
/* Currently not used. Set all to zero. */
for (i = 0; i < 8; i++)
smu_data->power_tune_table.GnbLPML[i] = 0;
return 0;
}
static int iceland_min_max_vgnb_lpml_id_from_bapm_vddc(struct pp_hwmgr *hwmgr)
{
return 0;
}
static int iceland_populate_bapm_vddc_base_leakage_sidd(struct pp_hwmgr *hwmgr)
{
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
uint16_t HiSidd = smu_data->power_tune_table.BapmVddCBaseLeakageHiSidd;
uint16_t LoSidd = smu_data->power_tune_table.BapmVddCBaseLeakageLoSidd;
struct phm_cac_tdp_table *cac_table = hwmgr->dyn_state.cac_dtp_table;
HiSidd = (uint16_t)(cac_table->usHighCACLeakage / 100 * 256);
LoSidd = (uint16_t)(cac_table->usLowCACLeakage / 100 * 256);
smu_data->power_tune_table.BapmVddCBaseLeakageHiSidd =
CONVERT_FROM_HOST_TO_SMC_US(HiSidd);
smu_data->power_tune_table.BapmVddCBaseLeakageLoSidd =
CONVERT_FROM_HOST_TO_SMC_US(LoSidd);
return 0;
}
static int iceland_populate_bapm_vddc_vid_sidd(struct pp_hwmgr *hwmgr)
{
int i;
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
uint8_t *hi_vid = smu_data->power_tune_table.BapmVddCVidHiSidd;
uint8_t *lo_vid = smu_data->power_tune_table.BapmVddCVidLoSidd;
PP_ASSERT_WITH_CODE(NULL != hwmgr->dyn_state.cac_leakage_table,
"The CAC Leakage table does not exist!", return -EINVAL);
PP_ASSERT_WITH_CODE(hwmgr->dyn_state.cac_leakage_table->count <= 8,
"There should never be more than 8 entries for BapmVddcVid!!!", return -EINVAL);
PP_ASSERT_WITH_CODE(hwmgr->dyn_state.cac_leakage_table->count == hwmgr->dyn_state.vddc_dependency_on_sclk->count,
"CACLeakageTable->count and VddcDependencyOnSCLk->count not equal", return -EINVAL);
if (phm_cap_enabled(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_EVV)) {
for (i = 0; (uint32_t) i < hwmgr->dyn_state.cac_leakage_table->count; i++) {
lo_vid[i] = convert_to_vid(hwmgr->dyn_state.cac_leakage_table->entries[i].Vddc1);
hi_vid[i] = convert_to_vid(hwmgr->dyn_state.cac_leakage_table->entries[i].Vddc2);
}
} else {
PP_ASSERT_WITH_CODE(false, "Iceland should always support EVV", return -EINVAL);
}
return 0;
}
static int iceland_populate_vddc_vid(struct pp_hwmgr *hwmgr)
{
int i;
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
uint8_t *vid = smu_data->power_tune_table.VddCVid;
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
PP_ASSERT_WITH_CODE(data->vddc_voltage_table.count <= 8,
"There should never be more than 8 entries for VddcVid!!!",
return -EINVAL);
for (i = 0; i < (int)data->vddc_voltage_table.count; i++) {
vid[i] = convert_to_vid(data->vddc_voltage_table.entries[i].value);
}
return 0;
}
static int iceland_populate_pm_fuses(struct pp_hwmgr *hwmgr)
{
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
uint32_t pm_fuse_table_offset;
if (phm_cap_enabled(hwmgr->platform_descriptor.platformCaps,
PHM_PlatformCaps_PowerContainment)) {
if (smu7_read_smc_sram_dword(hwmgr->smumgr,
SMU71_FIRMWARE_HEADER_LOCATION +
offsetof(SMU71_Firmware_Header, PmFuseTable),
&pm_fuse_table_offset, SMC_RAM_END))
PP_ASSERT_WITH_CODE(false,
"Attempt to get pm_fuse_table_offset Failed!",
return -EINVAL);
/* DW0 - DW3 */
if (iceland_populate_bapm_vddc_vid_sidd(hwmgr))
PP_ASSERT_WITH_CODE(false,
"Attempt to populate bapm vddc vid Failed!",
return -EINVAL);
/* DW4 - DW5 */
if (iceland_populate_vddc_vid(hwmgr))
PP_ASSERT_WITH_CODE(false,
"Attempt to populate vddc vid Failed!",
return -EINVAL);
/* DW6 */
if (iceland_populate_svi_load_line(hwmgr))
PP_ASSERT_WITH_CODE(false,
"Attempt to populate SviLoadLine Failed!",
return -EINVAL);
/* DW7 */
if (iceland_populate_tdc_limit(hwmgr))
PP_ASSERT_WITH_CODE(false,
"Attempt to populate TDCLimit Failed!", return -EINVAL);
/* DW8 */
if (iceland_populate_dw8(hwmgr, pm_fuse_table_offset))
PP_ASSERT_WITH_CODE(false,
"Attempt to populate TdcWaterfallCtl, "
"LPMLTemperature Min and Max Failed!",
return -EINVAL);
/* DW9-DW12 */
if (0 != iceland_populate_temperature_scaler(hwmgr))
PP_ASSERT_WITH_CODE(false,
"Attempt to populate LPMLTemperatureScaler Failed!",
return -EINVAL);
/* DW13-DW16 */
if (iceland_populate_gnb_lpml(hwmgr))
PP_ASSERT_WITH_CODE(false,
"Attempt to populate GnbLPML Failed!",
return -EINVAL);
/* DW17 */
if (iceland_min_max_vgnb_lpml_id_from_bapm_vddc(hwmgr))
PP_ASSERT_WITH_CODE(false,
"Attempt to populate GnbLPML Min and Max Vid Failed!",
return -EINVAL);
/* DW18 */
if (iceland_populate_bapm_vddc_base_leakage_sidd(hwmgr))
PP_ASSERT_WITH_CODE(false,
"Attempt to populate BapmVddCBaseLeakage Hi and Lo Sidd Failed!",
return -EINVAL);
if (smu7_copy_bytes_to_smc(hwmgr->smumgr, pm_fuse_table_offset,
(uint8_t *)&smu_data->power_tune_table,
sizeof(struct SMU71_Discrete_PmFuses), SMC_RAM_END))
PP_ASSERT_WITH_CODE(false,
"Attempt to download PmFuseTable Failed!",
return -EINVAL);
}
return 0;
}
static int iceland_get_dependecy_volt_by_clk(struct pp_hwmgr *hwmgr,
struct phm_clock_voltage_dependency_table *allowed_clock_voltage_table,
uint32_t clock, uint32_t *vol)
{
uint32_t i = 0;
/* clock - voltage dependency table is empty table */
if (allowed_clock_voltage_table->count == 0)
return -EINVAL;
for (i = 0; i < allowed_clock_voltage_table->count; i++) {
/* find first sclk bigger than request */
if (allowed_clock_voltage_table->entries[i].clk >= clock) {
*vol = allowed_clock_voltage_table->entries[i].v;
return 0;
}
}
/* sclk is bigger than max sclk in the dependence table */
*vol = allowed_clock_voltage_table->entries[i - 1].v;
return 0;
}
static int iceland_get_std_voltage_value_sidd(struct pp_hwmgr *hwmgr,
pp_atomctrl_voltage_table_entry *tab, uint16_t *hi,
uint16_t *lo)
{
uint16_t v_index;
bool vol_found = false;
*hi = tab->value * VOLTAGE_SCALE;
*lo = tab->value * VOLTAGE_SCALE;
/* SCLK/VDDC Dependency Table has to exist. */
PP_ASSERT_WITH_CODE(NULL != hwmgr->dyn_state.vddc_dependency_on_sclk,
"The SCLK/VDDC Dependency Table does not exist.\n",
return -EINVAL);
if (NULL == hwmgr->dyn_state.cac_leakage_table) {
pr_warning("CAC Leakage Table does not exist, using vddc.\n");
return 0;
}
/*
* Since voltage in the sclk/vddc dependency table is not
* necessarily in ascending order because of ELB voltage
* patching, loop through entire list to find exact voltage.
*/
for (v_index = 0; (uint32_t)v_index < hwmgr->dyn_state.vddc_dependency_on_sclk->count; v_index++) {
if (tab->value == hwmgr->dyn_state.vddc_dependency_on_sclk->entries[v_index].v) {
vol_found = true;
if ((uint32_t)v_index < hwmgr->dyn_state.cac_leakage_table->count) {
*lo = hwmgr->dyn_state.cac_leakage_table->entries[v_index].Vddc * VOLTAGE_SCALE;
*hi = (uint16_t)(hwmgr->dyn_state.cac_leakage_table->entries[v_index].Leakage * VOLTAGE_SCALE);
} else {
pr_warning("Index from SCLK/VDDC Dependency Table exceeds the CAC Leakage Table index, using maximum index from CAC table.\n");
*lo = hwmgr->dyn_state.cac_leakage_table->entries[hwmgr->dyn_state.cac_leakage_table->count - 1].Vddc * VOLTAGE_SCALE;
*hi = (uint16_t)(hwmgr->dyn_state.cac_leakage_table->entries[hwmgr->dyn_state.cac_leakage_table->count - 1].Leakage * VOLTAGE_SCALE);
}
break;
}
}
/*
* If voltage is not found in the first pass, loop again to
* find the best match, equal or higher value.
*/
if (!vol_found) {
for (v_index = 0; (uint32_t)v_index < hwmgr->dyn_state.vddc_dependency_on_sclk->count; v_index++) {
if (tab->value <= hwmgr->dyn_state.vddc_dependency_on_sclk->entries[v_index].v) {
vol_found = true;
if ((uint32_t)v_index < hwmgr->dyn_state.cac_leakage_table->count) {
*lo = hwmgr->dyn_state.cac_leakage_table->entries[v_index].Vddc * VOLTAGE_SCALE;
*hi = (uint16_t)(hwmgr->dyn_state.cac_leakage_table->entries[v_index].Leakage) * VOLTAGE_SCALE;
} else {
pr_warning("Index from SCLK/VDDC Dependency Table exceeds the CAC Leakage Table index in second look up, using maximum index from CAC table.");
*lo = hwmgr->dyn_state.cac_leakage_table->entries[hwmgr->dyn_state.cac_leakage_table->count - 1].Vddc * VOLTAGE_SCALE;
*hi = (uint16_t)(hwmgr->dyn_state.cac_leakage_table->entries[hwmgr->dyn_state.cac_leakage_table->count - 1].Leakage * VOLTAGE_SCALE);
}
break;
}
}
if (!vol_found)
pr_warning("Unable to get std_vddc from SCLK/VDDC Dependency Table, using vddc.\n");
}
return 0;
}
static int iceland_populate_smc_voltage_table(struct pp_hwmgr *hwmgr,
pp_atomctrl_voltage_table_entry *tab,
SMU71_Discrete_VoltageLevel *smc_voltage_tab)
{
int result;
result = iceland_get_std_voltage_value_sidd(hwmgr, tab,
&smc_voltage_tab->StdVoltageHiSidd,
&smc_voltage_tab->StdVoltageLoSidd);
if (0 != result) {
smc_voltage_tab->StdVoltageHiSidd = tab->value * VOLTAGE_SCALE;
smc_voltage_tab->StdVoltageLoSidd = tab->value * VOLTAGE_SCALE;
}
smc_voltage_tab->Voltage = PP_HOST_TO_SMC_US(tab->value * VOLTAGE_SCALE);
CONVERT_FROM_HOST_TO_SMC_US(smc_voltage_tab->StdVoltageHiSidd);
CONVERT_FROM_HOST_TO_SMC_US(smc_voltage_tab->StdVoltageHiSidd);
return 0;
}
static int iceland_populate_smc_vddc_table(struct pp_hwmgr *hwmgr,
SMU71_Discrete_DpmTable *table)
{
unsigned int count;
int result;
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
table->VddcLevelCount = data->vddc_voltage_table.count;
for (count = 0; count < table->VddcLevelCount; count++) {
result = iceland_populate_smc_voltage_table(hwmgr,
&(data->vddc_voltage_table.entries[count]),
&(table->VddcLevel[count]));
PP_ASSERT_WITH_CODE(0 == result, "do not populate SMC VDDC voltage table", return -EINVAL);
/* GPIO voltage control */
if (SMU7_VOLTAGE_CONTROL_BY_GPIO == data->voltage_control)
table->VddcLevel[count].Smio |= data->vddc_voltage_table.entries[count].smio_low;
else if (SMU7_VOLTAGE_CONTROL_BY_SVID2 == data->voltage_control)
table->VddcLevel[count].Smio = 0;
}
CONVERT_FROM_HOST_TO_SMC_UL(table->VddcLevelCount);
return 0;
}
static int iceland_populate_smc_vdd_ci_table(struct pp_hwmgr *hwmgr,
SMU71_Discrete_DpmTable *table)
{
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
uint32_t count;
int result;
table->VddciLevelCount = data->vddci_voltage_table.count;
for (count = 0; count < table->VddciLevelCount; count++) {
result = iceland_populate_smc_voltage_table(hwmgr,
&(data->vddci_voltage_table.entries[count]),
&(table->VddciLevel[count]));
PP_ASSERT_WITH_CODE(result == 0, "do not populate SMC VDDCI voltage table", return -EINVAL);
if (SMU7_VOLTAGE_CONTROL_BY_GPIO == data->vddci_control)
table->VddciLevel[count].Smio |= data->vddci_voltage_table.entries[count].smio_low;
else
table->VddciLevel[count].Smio |= 0;
}
CONVERT_FROM_HOST_TO_SMC_UL(table->VddciLevelCount);
return 0;
}
static int iceland_populate_smc_mvdd_table(struct pp_hwmgr *hwmgr,
SMU71_Discrete_DpmTable *table)
{
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
uint32_t count;
int result;
table->MvddLevelCount = data->mvdd_voltage_table.count;
for (count = 0; count < table->VddciLevelCount; count++) {
result = iceland_populate_smc_voltage_table(hwmgr,
&(data->mvdd_voltage_table.entries[count]),
&table->MvddLevel[count]);
PP_ASSERT_WITH_CODE(result == 0, "do not populate SMC mvdd voltage table", return -EINVAL);
if (SMU7_VOLTAGE_CONTROL_BY_GPIO == data->mvdd_control)
table->MvddLevel[count].Smio |= data->mvdd_voltage_table.entries[count].smio_low;
else
table->MvddLevel[count].Smio |= 0;
}
CONVERT_FROM_HOST_TO_SMC_UL(table->MvddLevelCount);
return 0;
}
static int iceland_populate_smc_voltage_tables(struct pp_hwmgr *hwmgr,
SMU71_Discrete_DpmTable *table)
{
int result;
result = iceland_populate_smc_vddc_table(hwmgr, table);
PP_ASSERT_WITH_CODE(0 == result,
"can not populate VDDC voltage table to SMC", return -EINVAL);
result = iceland_populate_smc_vdd_ci_table(hwmgr, table);
PP_ASSERT_WITH_CODE(0 == result,
"can not populate VDDCI voltage table to SMC", return -EINVAL);
result = iceland_populate_smc_mvdd_table(hwmgr, table);
PP_ASSERT_WITH_CODE(0 == result,
"can not populate MVDD voltage table to SMC", return -EINVAL);
return 0;
}
static int iceland_populate_ulv_level(struct pp_hwmgr *hwmgr,
struct SMU71_Discrete_Ulv *state)
{
uint32_t voltage_response_time, ulv_voltage;
int result;
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
state->CcPwrDynRm = 0;
state->CcPwrDynRm1 = 0;
result = pp_tables_get_response_times(hwmgr, &voltage_response_time, &ulv_voltage);
PP_ASSERT_WITH_CODE((0 == result), "can not get ULV voltage value", return result;);
if (ulv_voltage == 0) {
data->ulv_supported = false;
return 0;
}
if (data->voltage_control != SMU7_VOLTAGE_CONTROL_BY_SVID2) {
/* use minimum voltage if ulv voltage in pptable is bigger than minimum voltage */
if (ulv_voltage > hwmgr->dyn_state.vddc_dependency_on_sclk->entries[0].v)
state->VddcOffset = 0;
else
/* used in SMIO Mode. not implemented for now. this is backup only for CI. */
state->VddcOffset = (uint16_t)(hwmgr->dyn_state.vddc_dependency_on_sclk->entries[0].v - ulv_voltage);
} else {
/* use minimum voltage if ulv voltage in pptable is bigger than minimum voltage */
if (ulv_voltage > hwmgr->dyn_state.vddc_dependency_on_sclk->entries[0].v)
state->VddcOffsetVid = 0;
else /* used in SVI2 Mode */
state->VddcOffsetVid = (uint8_t)(
(hwmgr->dyn_state.vddc_dependency_on_sclk->entries[0].v - ulv_voltage)
* VOLTAGE_VID_OFFSET_SCALE2
/ VOLTAGE_VID_OFFSET_SCALE1);
}
state->VddcPhase = 1;
CONVERT_FROM_HOST_TO_SMC_UL(state->CcPwrDynRm);
CONVERT_FROM_HOST_TO_SMC_UL(state->CcPwrDynRm1);
CONVERT_FROM_HOST_TO_SMC_US(state->VddcOffset);
return 0;
}
static int iceland_populate_ulv_state(struct pp_hwmgr *hwmgr,
SMU71_Discrete_Ulv *ulv_level)
{
return iceland_populate_ulv_level(hwmgr, ulv_level);
}
static int iceland_populate_smc_link_level(struct pp_hwmgr *hwmgr, SMU71_Discrete_DpmTable *table)
{
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
struct smu7_dpm_table *dpm_table = &data->dpm_table;
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
uint32_t i;
/* Index (dpm_table->pcie_speed_table.count) is reserved for PCIE boot level. */
for (i = 0; i <= dpm_table->pcie_speed_table.count; i++) {
table->LinkLevel[i].PcieGenSpeed =
(uint8_t)dpm_table->pcie_speed_table.dpm_levels[i].value;
table->LinkLevel[i].PcieLaneCount =
(uint8_t)encode_pcie_lane_width(dpm_table->pcie_speed_table.dpm_levels[i].param1);
table->LinkLevel[i].EnabledForActivity =
1;
table->LinkLevel[i].SPC =
(uint8_t)(data->pcie_spc_cap & 0xff);
table->LinkLevel[i].DownThreshold =
PP_HOST_TO_SMC_UL(5);
table->LinkLevel[i].UpThreshold =
PP_HOST_TO_SMC_UL(30);
}
smu_data->smc_state_table.LinkLevelCount =
(uint8_t)dpm_table->pcie_speed_table.count;
data->dpm_level_enable_mask.pcie_dpm_enable_mask =
phm_get_dpm_level_enable_mask_value(&dpm_table->pcie_speed_table);
return 0;
}
/**
* Calculates the SCLK dividers using the provided engine clock
*
* @param hwmgr the address of the hardware manager
* @param engine_clock the engine clock to use to populate the structure
* @param sclk the SMC SCLK structure to be populated
*/
static int iceland_calculate_sclk_params(struct pp_hwmgr *hwmgr,
uint32_t engine_clock, SMU71_Discrete_GraphicsLevel *sclk)
{
const struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
pp_atomctrl_clock_dividers_vi dividers;
uint32_t spll_func_cntl = data->clock_registers.vCG_SPLL_FUNC_CNTL;
uint32_t spll_func_cntl_3 = data->clock_registers.vCG_SPLL_FUNC_CNTL_3;
uint32_t spll_func_cntl_4 = data->clock_registers.vCG_SPLL_FUNC_CNTL_4;
uint32_t cg_spll_spread_spectrum = data->clock_registers.vCG_SPLL_SPREAD_SPECTRUM;
uint32_t cg_spll_spread_spectrum_2 = data->clock_registers.vCG_SPLL_SPREAD_SPECTRUM_2;
uint32_t reference_clock;
uint32_t reference_divider;
uint32_t fbdiv;
int result;
/* get the engine clock dividers for this clock value*/
result = atomctrl_get_engine_pll_dividers_vi(hwmgr, engine_clock, ÷rs);
PP_ASSERT_WITH_CODE(result == 0,
"Error retrieving Engine Clock dividers from VBIOS.", return result);
/* To get FBDIV we need to multiply this by 16384 and divide it by Fref.*/
reference_clock = atomctrl_get_reference_clock(hwmgr);
reference_divider = 1 + dividers.uc_pll_ref_div;
/* low 14 bits is fraction and high 12 bits is divider*/
fbdiv = dividers.ul_fb_div.ul_fb_divider & 0x3FFFFFF;
/* SPLL_FUNC_CNTL setup*/
spll_func_cntl = PHM_SET_FIELD(spll_func_cntl,
CG_SPLL_FUNC_CNTL, SPLL_REF_DIV, dividers.uc_pll_ref_div);
spll_func_cntl = PHM_SET_FIELD(spll_func_cntl,
CG_SPLL_FUNC_CNTL, SPLL_PDIV_A, dividers.uc_pll_post_div);
/* SPLL_FUNC_CNTL_3 setup*/
spll_func_cntl_3 = PHM_SET_FIELD(spll_func_cntl_3,
CG_SPLL_FUNC_CNTL_3, SPLL_FB_DIV, fbdiv);
/* set to use fractional accumulation*/
spll_func_cntl_3 = PHM_SET_FIELD(spll_func_cntl_3,
CG_SPLL_FUNC_CNTL_3, SPLL_DITHEN, 1);
if (phm_cap_enabled(hwmgr->platform_descriptor.platformCaps,
PHM_PlatformCaps_EngineSpreadSpectrumSupport)) {
pp_atomctrl_internal_ss_info ss_info;
uint32_t vcoFreq = engine_clock * dividers.uc_pll_post_div;
if (0 == atomctrl_get_engine_clock_spread_spectrum(hwmgr, vcoFreq, &ss_info)) {
/*
* ss_info.speed_spectrum_percentage -- in unit of 0.01%
* ss_info.speed_spectrum_rate -- in unit of khz
*/
/* clks = reference_clock * 10 / (REFDIV + 1) / speed_spectrum_rate / 2 */
uint32_t clkS = reference_clock * 5 / (reference_divider * ss_info.speed_spectrum_rate);
/* clkv = 2 * D * fbdiv / NS */
uint32_t clkV = 4 * ss_info.speed_spectrum_percentage * fbdiv / (clkS * 10000);
cg_spll_spread_spectrum =
PHM_SET_FIELD(cg_spll_spread_spectrum, CG_SPLL_SPREAD_SPECTRUM, CLKS, clkS);
cg_spll_spread_spectrum =
PHM_SET_FIELD(cg_spll_spread_spectrum, CG_SPLL_SPREAD_SPECTRUM, SSEN, 1);
cg_spll_spread_spectrum_2 =
PHM_SET_FIELD(cg_spll_spread_spectrum_2, CG_SPLL_SPREAD_SPECTRUM_2, CLKV, clkV);
}
}
sclk->SclkFrequency = engine_clock;
sclk->CgSpllFuncCntl3 = spll_func_cntl_3;
sclk->CgSpllFuncCntl4 = spll_func_cntl_4;
sclk->SpllSpreadSpectrum = cg_spll_spread_spectrum;
sclk->SpllSpreadSpectrum2 = cg_spll_spread_spectrum_2;
sclk->SclkDid = (uint8_t)dividers.pll_post_divider;
return 0;
}
static int iceland_populate_phase_value_based_on_sclk(struct pp_hwmgr *hwmgr,
const struct phm_phase_shedding_limits_table *pl,
uint32_t sclk, uint32_t *p_shed)
{
unsigned int i;
/* use the minimum phase shedding */
*p_shed = 1;
for (i = 0; i < pl->count; i++) {
if (sclk < pl->entries[i].Sclk) {
*p_shed = i;
break;
}
}
return 0;
}
/**
* Populates single SMC SCLK structure using the provided engine clock
*
* @param hwmgr the address of the hardware manager
* @param engine_clock the engine clock to use to populate the structure
* @param sclk the SMC SCLK structure to be populated
*/
static int iceland_populate_single_graphic_level(struct pp_hwmgr *hwmgr,
uint32_t engine_clock,
uint16_t sclk_activity_level_threshold,
SMU71_Discrete_GraphicsLevel *graphic_level)
{
int result;
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
result = iceland_calculate_sclk_params(hwmgr, engine_clock, graphic_level);
/* populate graphics levels*/
result = iceland_get_dependecy_volt_by_clk(hwmgr,
hwmgr->dyn_state.vddc_dependency_on_sclk, engine_clock,
&graphic_level->MinVddc);
PP_ASSERT_WITH_CODE((0 == result),
"can not find VDDC voltage value for VDDC \
engine clock dependency table", return result);
/* SCLK frequency in units of 10KHz*/
graphic_level->SclkFrequency = engine_clock;
graphic_level->MinVddcPhases = 1;
if (data->vddc_phase_shed_control)
iceland_populate_phase_value_based_on_sclk(hwmgr,
hwmgr->dyn_state.vddc_phase_shed_limits_table,
engine_clock,
&graphic_level->MinVddcPhases);
/* Indicates maximum activity level for this performance level. 50% for now*/
graphic_level->ActivityLevel = sclk_activity_level_threshold;
graphic_level->CcPwrDynRm = 0;
graphic_level->CcPwrDynRm1 = 0;
/* this level can be used if activity is high enough.*/
graphic_level->EnabledForActivity = 0;
/* this level can be used for throttling.*/
graphic_level->EnabledForThrottle = 1;
graphic_level->UpHyst = 0;
graphic_level->DownHyst = 100;
graphic_level->VoltageDownHyst = 0;
graphic_level->PowerThrottle = 0;
data->display_timing.min_clock_in_sr =
hwmgr->display_config.min_core_set_clock_in_sr;
if (phm_cap_enabled(hwmgr->platform_descriptor.platformCaps,
PHM_PlatformCaps_SclkDeepSleep))
graphic_level->DeepSleepDivId =
smu7_get_sleep_divider_id_from_clock(engine_clock,
data->display_timing.min_clock_in_sr);
/* Default to slow, highest DPM level will be set to PPSMC_DISPLAY_WATERMARK_LOW later.*/
graphic_level->DisplayWatermark = PPSMC_DISPLAY_WATERMARK_LOW;
if (0 == result) {
graphic_level->MinVddc = PP_HOST_TO_SMC_UL(graphic_level->MinVddc * VOLTAGE_SCALE);
CONVERT_FROM_HOST_TO_SMC_UL(graphic_level->MinVddcPhases);
CONVERT_FROM_HOST_TO_SMC_UL(graphic_level->SclkFrequency);
CONVERT_FROM_HOST_TO_SMC_US(graphic_level->ActivityLevel);
CONVERT_FROM_HOST_TO_SMC_UL(graphic_level->CgSpllFuncCntl3);
CONVERT_FROM_HOST_TO_SMC_UL(graphic_level->CgSpllFuncCntl4);
CONVERT_FROM_HOST_TO_SMC_UL(graphic_level->SpllSpreadSpectrum);
CONVERT_FROM_HOST_TO_SMC_UL(graphic_level->SpllSpreadSpectrum2);
CONVERT_FROM_HOST_TO_SMC_UL(graphic_level->CcPwrDynRm);
CONVERT_FROM_HOST_TO_SMC_UL(graphic_level->CcPwrDynRm1);
}
return result;
}
/**
* Populates all SMC SCLK levels' structure based on the trimmed allowed dpm engine clock states
*
* @param hwmgr the address of the hardware manager
*/
int iceland_populate_all_graphic_levels(struct pp_hwmgr *hwmgr)
{
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
struct smu7_dpm_table *dpm_table = &data->dpm_table;
uint32_t level_array_adress = smu_data->smu7_data.dpm_table_start +
offsetof(SMU71_Discrete_DpmTable, GraphicsLevel);
uint32_t level_array_size = sizeof(SMU71_Discrete_GraphicsLevel) *
SMU71_MAX_LEVELS_GRAPHICS;
SMU71_Discrete_GraphicsLevel *levels = smu_data->smc_state_table.GraphicsLevel;
uint32_t i;
uint8_t highest_pcie_level_enabled = 0;
uint8_t lowest_pcie_level_enabled = 0, mid_pcie_level_enabled = 0;
uint8_t count = 0;
int result = 0;
memset(levels, 0x00, level_array_size);
for (i = 0; i < dpm_table->sclk_table.count; i++) {
result = iceland_populate_single_graphic_level(hwmgr,
dpm_table->sclk_table.dpm_levels[i].value,
(uint16_t)smu_data->activity_target[i],
&(smu_data->smc_state_table.GraphicsLevel[i]));
if (result != 0)
return result;
/* Making sure only DPM level 0-1 have Deep Sleep Div ID populated. */
if (i > 1)
smu_data->smc_state_table.GraphicsLevel[i].DeepSleepDivId = 0;
}
/* Only enable level 0 for now. */
smu_data->smc_state_table.GraphicsLevel[0].EnabledForActivity = 1;
/* set highest level watermark to high */
if (dpm_table->sclk_table.count > 1)
smu_data->smc_state_table.GraphicsLevel[dpm_table->sclk_table.count-1].DisplayWatermark =
PPSMC_DISPLAY_WATERMARK_HIGH;
smu_data->smc_state_table.GraphicsDpmLevelCount =
(uint8_t)dpm_table->sclk_table.count;
data->dpm_level_enable_mask.sclk_dpm_enable_mask =
phm_get_dpm_level_enable_mask_value(&dpm_table->sclk_table);
while ((data->dpm_level_enable_mask.pcie_dpm_enable_mask &
(1 << (highest_pcie_level_enabled + 1))) != 0) {
highest_pcie_level_enabled++;
}
while ((data->dpm_level_enable_mask.pcie_dpm_enable_mask &
(1 << lowest_pcie_level_enabled)) == 0) {
lowest_pcie_level_enabled++;
}
while ((count < highest_pcie_level_enabled) &&
((data->dpm_level_enable_mask.pcie_dpm_enable_mask &
(1 << (lowest_pcie_level_enabled + 1 + count))) == 0)) {
count++;
}
mid_pcie_level_enabled = (lowest_pcie_level_enabled+1+count) < highest_pcie_level_enabled ?
(lowest_pcie_level_enabled+1+count) : highest_pcie_level_enabled;
/* set pcieDpmLevel to highest_pcie_level_enabled*/
for (i = 2; i < dpm_table->sclk_table.count; i++) {
smu_data->smc_state_table.GraphicsLevel[i].pcieDpmLevel = highest_pcie_level_enabled;
}
/* set pcieDpmLevel to lowest_pcie_level_enabled*/
smu_data->smc_state_table.GraphicsLevel[0].pcieDpmLevel = lowest_pcie_level_enabled;
/* set pcieDpmLevel to mid_pcie_level_enabled*/
smu_data->smc_state_table.GraphicsLevel[1].pcieDpmLevel = mid_pcie_level_enabled;
/* level count will send to smc once at init smc table and never change*/
result = smu7_copy_bytes_to_smc(hwmgr->smumgr, level_array_adress,
(uint8_t *)levels, (uint32_t)level_array_size,
SMC_RAM_END);
return result;
}
/**
* Populates the SMC MCLK structure using the provided memory clock
*
* @param hwmgr the address of the hardware manager
* @param memory_clock the memory clock to use to populate the structure
* @param sclk the SMC SCLK structure to be populated
*/
static int iceland_calculate_mclk_params(
struct pp_hwmgr *hwmgr,
uint32_t memory_clock,
SMU71_Discrete_MemoryLevel *mclk,
bool strobe_mode,
bool dllStateOn
)
{
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
uint32_t dll_cntl = data->clock_registers.vDLL_CNTL;
uint32_t mclk_pwrmgt_cntl = data->clock_registers.vMCLK_PWRMGT_CNTL;
uint32_t mpll_ad_func_cntl = data->clock_registers.vMPLL_AD_FUNC_CNTL;
uint32_t mpll_dq_func_cntl = data->clock_registers.vMPLL_DQ_FUNC_CNTL;
uint32_t mpll_func_cntl = data->clock_registers.vMPLL_FUNC_CNTL;
uint32_t mpll_func_cntl_1 = data->clock_registers.vMPLL_FUNC_CNTL_1;
uint32_t mpll_func_cntl_2 = data->clock_registers.vMPLL_FUNC_CNTL_2;
uint32_t mpll_ss1 = data->clock_registers.vMPLL_SS1;
uint32_t mpll_ss2 = data->clock_registers.vMPLL_SS2;
pp_atomctrl_memory_clock_param mpll_param;
int result;
result = atomctrl_get_memory_pll_dividers_si(hwmgr,
memory_clock, &mpll_param, strobe_mode);
PP_ASSERT_WITH_CODE(0 == result,
"Error retrieving Memory Clock Parameters from VBIOS.", return result);
/* MPLL_FUNC_CNTL setup*/
mpll_func_cntl = PHM_SET_FIELD(mpll_func_cntl, MPLL_FUNC_CNTL, BWCTRL, mpll_param.bw_ctrl);
/* MPLL_FUNC_CNTL_1 setup*/
mpll_func_cntl_1 = PHM_SET_FIELD(mpll_func_cntl_1,
MPLL_FUNC_CNTL_1, CLKF, mpll_param.mpll_fb_divider.cl_kf);
mpll_func_cntl_1 = PHM_SET_FIELD(mpll_func_cntl_1,
MPLL_FUNC_CNTL_1, CLKFRAC, mpll_param.mpll_fb_divider.clk_frac);
mpll_func_cntl_1 = PHM_SET_FIELD(mpll_func_cntl_1,
MPLL_FUNC_CNTL_1, VCO_MODE, mpll_param.vco_mode);
/* MPLL_AD_FUNC_CNTL setup*/
mpll_ad_func_cntl = PHM_SET_FIELD(mpll_ad_func_cntl,
MPLL_AD_FUNC_CNTL, YCLK_POST_DIV, mpll_param.mpll_post_divider);
if (data->is_memory_gddr5) {
/* MPLL_DQ_FUNC_CNTL setup*/
mpll_dq_func_cntl = PHM_SET_FIELD(mpll_dq_func_cntl,
MPLL_DQ_FUNC_CNTL, YCLK_SEL, mpll_param.yclk_sel);
mpll_dq_func_cntl = PHM_SET_FIELD(mpll_dq_func_cntl,
MPLL_DQ_FUNC_CNTL, YCLK_POST_DIV, mpll_param.mpll_post_divider);
}
if (phm_cap_enabled(hwmgr->platform_descriptor.platformCaps,
PHM_PlatformCaps_MemorySpreadSpectrumSupport)) {
/*
************************************
Fref = Reference Frequency
NF = Feedback divider ratio
NR = Reference divider ratio
Fnom = Nominal VCO output frequency = Fref * NF / NR
Fs = Spreading Rate
D = Percentage down-spread / 2
Fint = Reference input frequency to PFD = Fref / NR
NS = Spreading rate divider ratio = int(Fint / (2 * Fs))
CLKS = NS - 1 = ISS_STEP_NUM[11:0]
NV = D * Fs / Fnom * 4 * ((Fnom/Fref * NR) ^ 2)
CLKV = 65536 * NV = ISS_STEP_SIZE[25:0]
*************************************
*/
pp_atomctrl_internal_ss_info ss_info;
uint32_t freq_nom;
uint32_t tmp;
uint32_t reference_clock = atomctrl_get_mpll_reference_clock(hwmgr);
/* for GDDR5 for all modes and DDR3 */
if (1 == mpll_param.qdr)
freq_nom = memory_clock * 4 * (1 << mpll_param.mpll_post_divider);
else
freq_nom = memory_clock * 2 * (1 << mpll_param.mpll_post_divider);
/* tmp = (freq_nom / reference_clock * reference_divider) ^ 2 Note: S.I. reference_divider = 1*/
tmp = (freq_nom / reference_clock);
tmp = tmp * tmp;
if (0 == atomctrl_get_memory_clock_spread_spectrum(hwmgr, freq_nom, &ss_info)) {
/* ss_info.speed_spectrum_percentage -- in unit of 0.01% */
/* ss.Info.speed_spectrum_rate -- in unit of khz */
/* CLKS = reference_clock / (2 * speed_spectrum_rate * reference_divider) * 10 */
/* = reference_clock * 5 / speed_spectrum_rate */
uint32_t clks = reference_clock * 5 / ss_info.speed_spectrum_rate;
/* CLKV = 65536 * speed_spectrum_percentage / 2 * spreadSpecrumRate / freq_nom * 4 / 100000 * ((freq_nom / reference_clock) ^ 2) */
/* = 131 * speed_spectrum_percentage * speed_spectrum_rate / 100 * ((freq_nom / reference_clock) ^ 2) / freq_nom */
uint32_t clkv =
(uint32_t)((((131 * ss_info.speed_spectrum_percentage *
ss_info.speed_spectrum_rate) / 100) * tmp) / freq_nom);
mpll_ss1 = PHM_SET_FIELD(mpll_ss1, MPLL_SS1, CLKV, clkv);
mpll_ss2 = PHM_SET_FIELD(mpll_ss2, MPLL_SS2, CLKS, clks);
}
}
/* MCLK_PWRMGT_CNTL setup */
mclk_pwrmgt_cntl = PHM_SET_FIELD(mclk_pwrmgt_cntl,
MCLK_PWRMGT_CNTL, DLL_SPEED, mpll_param.dll_speed);
mclk_pwrmgt_cntl = PHM_SET_FIELD(mclk_pwrmgt_cntl,
MCLK_PWRMGT_CNTL, MRDCK0_PDNB, dllStateOn);
mclk_pwrmgt_cntl = PHM_SET_FIELD(mclk_pwrmgt_cntl,
MCLK_PWRMGT_CNTL, MRDCK1_PDNB, dllStateOn);
/* Save the result data to outpupt memory level structure */
mclk->MclkFrequency = memory_clock;
mclk->MpllFuncCntl = mpll_func_cntl;
mclk->MpllFuncCntl_1 = mpll_func_cntl_1;
mclk->MpllFuncCntl_2 = mpll_func_cntl_2;
mclk->MpllAdFuncCntl = mpll_ad_func_cntl;
mclk->MpllDqFuncCntl = mpll_dq_func_cntl;
mclk->MclkPwrmgtCntl = mclk_pwrmgt_cntl;
mclk->DllCntl = dll_cntl;
mclk->MpllSs1 = mpll_ss1;
mclk->MpllSs2 = mpll_ss2;
return 0;
}
static uint8_t iceland_get_mclk_frequency_ratio(uint32_t memory_clock,
bool strobe_mode)
{
uint8_t mc_para_index;
if (strobe_mode) {
if (memory_clock < 12500) {
mc_para_index = 0x00;
} else if (memory_clock > 47500) {
mc_para_index = 0x0f;
} else {
mc_para_index = (uint8_t)((memory_clock - 10000) / 2500);
}
} else {
if (memory_clock < 65000) {
mc_para_index = 0x00;
} else if (memory_clock > 135000) {
mc_para_index = 0x0f;
} else {
mc_para_index = (uint8_t)((memory_clock - 60000) / 5000);
}
}
return mc_para_index;
}
static uint8_t iceland_get_ddr3_mclk_frequency_ratio(uint32_t memory_clock)
{
uint8_t mc_para_index;
if (memory_clock < 10000) {
mc_para_index = 0;
} else if (memory_clock >= 80000) {
mc_para_index = 0x0f;
} else {
mc_para_index = (uint8_t)((memory_clock - 10000) / 5000 + 1);
}
return mc_para_index;
}
static int iceland_populate_phase_value_based_on_mclk(struct pp_hwmgr *hwmgr, const struct phm_phase_shedding_limits_table *pl,
uint32_t memory_clock, uint32_t *p_shed)
{
unsigned int i;
*p_shed = 1;
for (i = 0; i < pl->count; i++) {
if (memory_clock < pl->entries[i].Mclk) {
*p_shed = i;
break;
}
}
return 0;
}
static int iceland_populate_single_memory_level(
struct pp_hwmgr *hwmgr,
uint32_t memory_clock,
SMU71_Discrete_MemoryLevel *memory_level
)
{
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
int result = 0;
bool dll_state_on;
struct cgs_display_info info = {0};
uint32_t mclk_edc_wr_enable_threshold = 40000;
uint32_t mclk_edc_enable_threshold = 40000;
uint32_t mclk_strobe_mode_threshold = 40000;
if (hwmgr->dyn_state.vddc_dependency_on_mclk != NULL) {
result = iceland_get_dependecy_volt_by_clk(hwmgr,
hwmgr->dyn_state.vddc_dependency_on_mclk, memory_clock, &memory_level->MinVddc);
PP_ASSERT_WITH_CODE((0 == result),
"can not find MinVddc voltage value from memory VDDC voltage dependency table", return result);
}
if (data->vddci_control == SMU7_VOLTAGE_CONTROL_NONE) {
memory_level->MinVddci = memory_level->MinVddc;
} else if (NULL != hwmgr->dyn_state.vddci_dependency_on_mclk) {
result = iceland_get_dependecy_volt_by_clk(hwmgr,
hwmgr->dyn_state.vddci_dependency_on_mclk,
memory_clock,
&memory_level->MinVddci);
PP_ASSERT_WITH_CODE((0 == result),
"can not find MinVddci voltage value from memory VDDCI voltage dependency table", return result);
}
memory_level->MinVddcPhases = 1;
if (data->vddc_phase_shed_control) {
iceland_populate_phase_value_based_on_mclk(hwmgr, hwmgr->dyn_state.vddc_phase_shed_limits_table,
memory_clock, &memory_level->MinVddcPhases);
}
memory_level->EnabledForThrottle = 1;
memory_level->EnabledForActivity = 0;
memory_level->UpHyst = 0;
memory_level->DownHyst = 100;
memory_level->VoltageDownHyst = 0;
/* Indicates maximum activity level for this performance level.*/
memory_level->ActivityLevel = (uint16_t)data->mclk_activity_target;
memory_level->StutterEnable = 0;
memory_level->StrobeEnable = 0;
memory_level->EdcReadEnable = 0;
memory_level->EdcWriteEnable = 0;
memory_level->RttEnable = 0;
/* default set to low watermark. Highest level will be set to high later.*/
memory_level->DisplayWatermark = PPSMC_DISPLAY_WATERMARK_LOW;
cgs_get_active_displays_info(hwmgr->device, &info);
data->display_timing.num_existing_displays = info.display_count;
/* stutter mode not support on iceland */
/* decide strobe mode*/
memory_level->StrobeEnable = (mclk_strobe_mode_threshold != 0) &&
(memory_clock <= mclk_strobe_mode_threshold);
/* decide EDC mode and memory clock ratio*/
if (data->is_memory_gddr5) {
memory_level->StrobeRatio = iceland_get_mclk_frequency_ratio(memory_clock,
memory_level->StrobeEnable);
if ((mclk_edc_enable_threshold != 0) &&
(memory_clock > mclk_edc_enable_threshold)) {
memory_level->EdcReadEnable = 1;
}
if ((mclk_edc_wr_enable_threshold != 0) &&
(memory_clock > mclk_edc_wr_enable_threshold)) {
memory_level->EdcWriteEnable = 1;
}
if (memory_level->StrobeEnable) {
if (iceland_get_mclk_frequency_ratio(memory_clock, 1) >=
((cgs_read_register(hwmgr->device, mmMC_SEQ_MISC7) >> 16) & 0xf))
dll_state_on = ((cgs_read_register(hwmgr->device, mmMC_SEQ_MISC5) >> 1) & 0x1) ? 1 : 0;
else
dll_state_on = ((cgs_read_register(hwmgr->device, mmMC_SEQ_MISC6) >> 1) & 0x1) ? 1 : 0;
} else
dll_state_on = data->dll_default_on;
} else {
memory_level->StrobeRatio =
iceland_get_ddr3_mclk_frequency_ratio(memory_clock);
dll_state_on = ((cgs_read_register(hwmgr->device, mmMC_SEQ_MISC5) >> 1) & 0x1) ? 1 : 0;
}
result = iceland_calculate_mclk_params(hwmgr,
memory_clock, memory_level, memory_level->StrobeEnable, dll_state_on);
if (0 == result) {
memory_level->MinVddc = PP_HOST_TO_SMC_UL(memory_level->MinVddc * VOLTAGE_SCALE);
CONVERT_FROM_HOST_TO_SMC_UL(memory_level->MinVddcPhases);
memory_level->MinVddci = PP_HOST_TO_SMC_UL(memory_level->MinVddci * VOLTAGE_SCALE);
memory_level->MinMvdd = PP_HOST_TO_SMC_UL(memory_level->MinMvdd * VOLTAGE_SCALE);
/* MCLK frequency in units of 10KHz*/
CONVERT_FROM_HOST_TO_SMC_UL(memory_level->MclkFrequency);
/* Indicates maximum activity level for this performance level.*/
CONVERT_FROM_HOST_TO_SMC_US(memory_level->ActivityLevel);
CONVERT_FROM_HOST_TO_SMC_UL(memory_level->MpllFuncCntl);
CONVERT_FROM_HOST_TO_SMC_UL(memory_level->MpllFuncCntl_1);
CONVERT_FROM_HOST_TO_SMC_UL(memory_level->MpllFuncCntl_2);
CONVERT_FROM_HOST_TO_SMC_UL(memory_level->MpllAdFuncCntl);
CONVERT_FROM_HOST_TO_SMC_UL(memory_level->MpllDqFuncCntl);
CONVERT_FROM_HOST_TO_SMC_UL(memory_level->MclkPwrmgtCntl);
CONVERT_FROM_HOST_TO_SMC_UL(memory_level->DllCntl);
CONVERT_FROM_HOST_TO_SMC_UL(memory_level->MpllSs1);
CONVERT_FROM_HOST_TO_SMC_UL(memory_level->MpllSs2);
}
return result;
}
/**
* Populates all SMC MCLK levels' structure based on the trimmed allowed dpm memory clock states
*
* @param hwmgr the address of the hardware manager
*/
int iceland_populate_all_memory_levels(struct pp_hwmgr *hwmgr)
{
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
struct smu7_dpm_table *dpm_table = &data->dpm_table;
int result;
/* populate MCLK dpm table to SMU7 */
uint32_t level_array_adress = smu_data->smu7_data.dpm_table_start + offsetof(SMU71_Discrete_DpmTable, MemoryLevel);
uint32_t level_array_size = sizeof(SMU71_Discrete_MemoryLevel) * SMU71_MAX_LEVELS_MEMORY;
SMU71_Discrete_MemoryLevel *levels = smu_data->smc_state_table.MemoryLevel;
uint32_t i;
memset(levels, 0x00, level_array_size);
for (i = 0; i < dpm_table->mclk_table.count; i++) {
PP_ASSERT_WITH_CODE((0 != dpm_table->mclk_table.dpm_levels[i].value),
"can not populate memory level as memory clock is zero", return -EINVAL);
result = iceland_populate_single_memory_level(hwmgr, dpm_table->mclk_table.dpm_levels[i].value,
&(smu_data->smc_state_table.MemoryLevel[i]));
if (0 != result) {
return result;
}
}
/* Only enable level 0 for now.*/
smu_data->smc_state_table.MemoryLevel[0].EnabledForActivity = 1;
/*
* in order to prevent MC activity from stutter mode to push DPM up.
* the UVD change complements this by putting the MCLK in a higher state
* by default such that we are not effected by up threshold or and MCLK DPM latency.
*/
smu_data->smc_state_table.MemoryLevel[0].ActivityLevel = 0x1F;
CONVERT_FROM_HOST_TO_SMC_US(smu_data->smc_state_table.MemoryLevel[0].ActivityLevel);
smu_data->smc_state_table.MemoryDpmLevelCount = (uint8_t)dpm_table->mclk_table.count;
data->dpm_level_enable_mask.mclk_dpm_enable_mask = phm_get_dpm_level_enable_mask_value(&dpm_table->mclk_table);
/* set highest level watermark to high*/
smu_data->smc_state_table.MemoryLevel[dpm_table->mclk_table.count-1].DisplayWatermark = PPSMC_DISPLAY_WATERMARK_HIGH;
/* level count will send to smc once at init smc table and never change*/
result = smu7_copy_bytes_to_smc(hwmgr->smumgr,
level_array_adress, (uint8_t *)levels, (uint32_t)level_array_size,
SMC_RAM_END);
return result;
}
static int iceland_populate_mvdd_value(struct pp_hwmgr *hwmgr, uint32_t mclk,
SMU71_Discrete_VoltageLevel *voltage)
{
const struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
uint32_t i = 0;
if (SMU7_VOLTAGE_CONTROL_NONE != data->mvdd_control) {
/* find mvdd value which clock is more than request */
for (i = 0; i < hwmgr->dyn_state.mvdd_dependency_on_mclk->count; i++) {
if (mclk <= hwmgr->dyn_state.mvdd_dependency_on_mclk->entries[i].clk) {
/* Always round to higher voltage. */
voltage->Voltage = data->mvdd_voltage_table.entries[i].value;
break;
}
}
PP_ASSERT_WITH_CODE(i < hwmgr->dyn_state.mvdd_dependency_on_mclk->count,
"MVDD Voltage is outside the supported range.", return -EINVAL);
} else {
return -EINVAL;
}
return 0;
}
static int iceland_populate_smc_acpi_level(struct pp_hwmgr *hwmgr,
SMU71_Discrete_DpmTable *table)
{
int result = 0;
const struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
struct pp_atomctrl_clock_dividers_vi dividers;
uint32_t vddc_phase_shed_control = 0;
SMU71_Discrete_VoltageLevel voltage_level;
uint32_t spll_func_cntl = data->clock_registers.vCG_SPLL_FUNC_CNTL;
uint32_t spll_func_cntl_2 = data->clock_registers.vCG_SPLL_FUNC_CNTL_2;
uint32_t dll_cntl = data->clock_registers.vDLL_CNTL;
uint32_t mclk_pwrmgt_cntl = data->clock_registers.vMCLK_PWRMGT_CNTL;
/* The ACPI state should not do DPM on DC (or ever).*/
table->ACPILevel.Flags &= ~PPSMC_SWSTATE_FLAG_DC;
if (data->acpi_vddc)
table->ACPILevel.MinVddc = PP_HOST_TO_SMC_UL(data->acpi_vddc * VOLTAGE_SCALE);
else
table->ACPILevel.MinVddc = PP_HOST_TO_SMC_UL(data->min_vddc_in_pptable * VOLTAGE_SCALE);
table->ACPILevel.MinVddcPhases = vddc_phase_shed_control ? 0 : 1;
/* assign zero for now*/
table->ACPILevel.SclkFrequency = atomctrl_get_reference_clock(hwmgr);
/* get the engine clock dividers for this clock value*/
result = atomctrl_get_engine_pll_dividers_vi(hwmgr,
table->ACPILevel.SclkFrequency, ÷rs);
PP_ASSERT_WITH_CODE(result == 0,
"Error retrieving Engine Clock dividers from VBIOS.", return result);
/* divider ID for required SCLK*/
table->ACPILevel.SclkDid = (uint8_t)dividers.pll_post_divider;
table->ACPILevel.DisplayWatermark = PPSMC_DISPLAY_WATERMARK_LOW;
table->ACPILevel.DeepSleepDivId = 0;
spll_func_cntl = PHM_SET_FIELD(spll_func_cntl,
CG_SPLL_FUNC_CNTL, SPLL_PWRON, 0);
spll_func_cntl = PHM_SET_FIELD(spll_func_cntl,
CG_SPLL_FUNC_CNTL, SPLL_RESET, 1);
spll_func_cntl_2 = PHM_SET_FIELD(spll_func_cntl_2,
CG_SPLL_FUNC_CNTL_2, SCLK_MUX_SEL, 4);
table->ACPILevel.CgSpllFuncCntl = spll_func_cntl;
table->ACPILevel.CgSpllFuncCntl2 = spll_func_cntl_2;
table->ACPILevel.CgSpllFuncCntl3 = data->clock_registers.vCG_SPLL_FUNC_CNTL_3;
table->ACPILevel.CgSpllFuncCntl4 = data->clock_registers.vCG_SPLL_FUNC_CNTL_4;
table->ACPILevel.SpllSpreadSpectrum = data->clock_registers.vCG_SPLL_SPREAD_SPECTRUM;
table->ACPILevel.SpllSpreadSpectrum2 = data->clock_registers.vCG_SPLL_SPREAD_SPECTRUM_2;
table->ACPILevel.CcPwrDynRm = 0;
table->ACPILevel.CcPwrDynRm1 = 0;
/* For various features to be enabled/disabled while this level is active.*/
CONVERT_FROM_HOST_TO_SMC_UL(table->ACPILevel.Flags);
/* SCLK frequency in units of 10KHz*/
CONVERT_FROM_HOST_TO_SMC_UL(table->ACPILevel.SclkFrequency);
CONVERT_FROM_HOST_TO_SMC_UL(table->ACPILevel.CgSpllFuncCntl);
CONVERT_FROM_HOST_TO_SMC_UL(table->ACPILevel.CgSpllFuncCntl2);
CONVERT_FROM_HOST_TO_SMC_UL(table->ACPILevel.CgSpllFuncCntl3);
CONVERT_FROM_HOST_TO_SMC_UL(table->ACPILevel.CgSpllFuncCntl4);
CONVERT_FROM_HOST_TO_SMC_UL(table->ACPILevel.SpllSpreadSpectrum);
CONVERT_FROM_HOST_TO_SMC_UL(table->ACPILevel.SpllSpreadSpectrum2);
CONVERT_FROM_HOST_TO_SMC_UL(table->ACPILevel.CcPwrDynRm);
CONVERT_FROM_HOST_TO_SMC_UL(table->ACPILevel.CcPwrDynRm1);
/* table->MemoryACPILevel.MinVddcPhases = table->ACPILevel.MinVddcPhases;*/
table->MemoryACPILevel.MinVddc = table->ACPILevel.MinVddc;
table->MemoryACPILevel.MinVddcPhases = table->ACPILevel.MinVddcPhases;
if (SMU7_VOLTAGE_CONTROL_NONE == data->vddci_control)
table->MemoryACPILevel.MinVddci = table->MemoryACPILevel.MinVddc;
else {
if (data->acpi_vddci != 0)
table->MemoryACPILevel.MinVddci = PP_HOST_TO_SMC_UL(data->acpi_vddci * VOLTAGE_SCALE);
else
table->MemoryACPILevel.MinVddci = PP_HOST_TO_SMC_UL(data->min_vddci_in_pptable * VOLTAGE_SCALE);
}
if (0 == iceland_populate_mvdd_value(hwmgr, 0, &voltage_level))
table->MemoryACPILevel.MinMvdd =
PP_HOST_TO_SMC_UL(voltage_level.Voltage * VOLTAGE_SCALE);
else
table->MemoryACPILevel.MinMvdd = 0;
/* Force reset on DLL*/
mclk_pwrmgt_cntl = PHM_SET_FIELD(mclk_pwrmgt_cntl,
MCLK_PWRMGT_CNTL, MRDCK0_RESET, 0x1);
mclk_pwrmgt_cntl = PHM_SET_FIELD(mclk_pwrmgt_cntl,
MCLK_PWRMGT_CNTL, MRDCK1_RESET, 0x1);
/* Disable DLL in ACPIState*/
mclk_pwrmgt_cntl = PHM_SET_FIELD(mclk_pwrmgt_cntl,
MCLK_PWRMGT_CNTL, MRDCK0_PDNB, 0);
mclk_pwrmgt_cntl = PHM_SET_FIELD(mclk_pwrmgt_cntl,
MCLK_PWRMGT_CNTL, MRDCK1_PDNB, 0);
/* Enable DLL bypass signal*/
dll_cntl = PHM_SET_FIELD(dll_cntl,
DLL_CNTL, MRDCK0_BYPASS, 0);
dll_cntl = PHM_SET_FIELD(dll_cntl,
DLL_CNTL, MRDCK1_BYPASS, 0);
table->MemoryACPILevel.DllCntl =
PP_HOST_TO_SMC_UL(dll_cntl);
table->MemoryACPILevel.MclkPwrmgtCntl =
PP_HOST_TO_SMC_UL(mclk_pwrmgt_cntl);
table->MemoryACPILevel.MpllAdFuncCntl =
PP_HOST_TO_SMC_UL(data->clock_registers.vMPLL_AD_FUNC_CNTL);
table->MemoryACPILevel.MpllDqFuncCntl =
PP_HOST_TO_SMC_UL(data->clock_registers.vMPLL_DQ_FUNC_CNTL);
table->MemoryACPILevel.MpllFuncCntl =
PP_HOST_TO_SMC_UL(data->clock_registers.vMPLL_FUNC_CNTL);
table->MemoryACPILevel.MpllFuncCntl_1 =
PP_HOST_TO_SMC_UL(data->clock_registers.vMPLL_FUNC_CNTL_1);
table->MemoryACPILevel.MpllFuncCntl_2 =
PP_HOST_TO_SMC_UL(data->clock_registers.vMPLL_FUNC_CNTL_2);
table->MemoryACPILevel.MpllSs1 =
PP_HOST_TO_SMC_UL(data->clock_registers.vMPLL_SS1);
table->MemoryACPILevel.MpllSs2 =
PP_HOST_TO_SMC_UL(data->clock_registers.vMPLL_SS2);
table->MemoryACPILevel.EnabledForThrottle = 0;
table->MemoryACPILevel.EnabledForActivity = 0;
table->MemoryACPILevel.UpHyst = 0;
table->MemoryACPILevel.DownHyst = 100;
table->MemoryACPILevel.VoltageDownHyst = 0;
/* Indicates maximum activity level for this performance level.*/
table->MemoryACPILevel.ActivityLevel = PP_HOST_TO_SMC_US((uint16_t)data->mclk_activity_target);
table->MemoryACPILevel.StutterEnable = 0;
table->MemoryACPILevel.StrobeEnable = 0;
table->MemoryACPILevel.EdcReadEnable = 0;
table->MemoryACPILevel.EdcWriteEnable = 0;
table->MemoryACPILevel.RttEnable = 0;
return result;
}
static int iceland_populate_smc_uvd_level(struct pp_hwmgr *hwmgr,
SMU71_Discrete_DpmTable *table)
{
return 0;
}
static int iceland_populate_smc_vce_level(struct pp_hwmgr *hwmgr,
SMU71_Discrete_DpmTable *table)
{
return 0;
}
static int iceland_populate_smc_acp_level(struct pp_hwmgr *hwmgr,
SMU71_Discrete_DpmTable *table)
{
return 0;
}
static int iceland_populate_smc_samu_level(struct pp_hwmgr *hwmgr,
SMU71_Discrete_DpmTable *table)
{
return 0;
}
static int iceland_populate_memory_timing_parameters(
struct pp_hwmgr *hwmgr,
uint32_t engine_clock,
uint32_t memory_clock,
struct SMU71_Discrete_MCArbDramTimingTableEntry *arb_regs
)
{
uint32_t dramTiming;
uint32_t dramTiming2;
uint32_t burstTime;
int result;
result = atomctrl_set_engine_dram_timings_rv770(hwmgr,
engine_clock, memory_clock);
PP_ASSERT_WITH_CODE(result == 0,
"Error calling VBIOS to set DRAM_TIMING.", return result);
dramTiming = cgs_read_register(hwmgr->device, mmMC_ARB_DRAM_TIMING);
dramTiming2 = cgs_read_register(hwmgr->device, mmMC_ARB_DRAM_TIMING2);
burstTime = PHM_READ_FIELD(hwmgr->device, MC_ARB_BURST_TIME, STATE0);
arb_regs->McArbDramTiming = PP_HOST_TO_SMC_UL(dramTiming);
arb_regs->McArbDramTiming2 = PP_HOST_TO_SMC_UL(dramTiming2);
arb_regs->McArbBurstTime = (uint8_t)burstTime;
return 0;
}
/**
* Setup parameters for the MC ARB.
*
* @param hwmgr the address of the powerplay hardware manager.
* @return always 0
* This function is to be called from the SetPowerState table.
*/
static int iceland_program_memory_timing_parameters(struct pp_hwmgr *hwmgr)
{
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
int result = 0;
SMU71_Discrete_MCArbDramTimingTable arb_regs;
uint32_t i, j;
memset(&arb_regs, 0x00, sizeof(SMU71_Discrete_MCArbDramTimingTable));
for (i = 0; i < data->dpm_table.sclk_table.count; i++) {
for (j = 0; j < data->dpm_table.mclk_table.count; j++) {
result = iceland_populate_memory_timing_parameters
(hwmgr, data->dpm_table.sclk_table.dpm_levels[i].value,
data->dpm_table.mclk_table.dpm_levels[j].value,
&arb_regs.entries[i][j]);
if (0 != result) {
break;
}
}
}
if (0 == result) {
result = smu7_copy_bytes_to_smc(
hwmgr->smumgr,
smu_data->smu7_data.arb_table_start,
(uint8_t *)&arb_regs,
sizeof(SMU71_Discrete_MCArbDramTimingTable),
SMC_RAM_END
);
}
return result;
}
static int iceland_populate_smc_boot_level(struct pp_hwmgr *hwmgr,
SMU71_Discrete_DpmTable *table)
{
int result = 0;
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
table->GraphicsBootLevel = 0;
table->MemoryBootLevel = 0;
/* find boot level from dpm table*/
result = phm_find_boot_level(&(data->dpm_table.sclk_table),
data->vbios_boot_state.sclk_bootup_value,
(uint32_t *)&(smu_data->smc_state_table.GraphicsBootLevel));
if (0 != result) {
smu_data->smc_state_table.GraphicsBootLevel = 0;
printk(KERN_ERR "[ powerplay ] VBIOS did not find boot engine clock value \
in dependency table. Using Graphics DPM level 0!");
result = 0;
}
result = phm_find_boot_level(&(data->dpm_table.mclk_table),
data->vbios_boot_state.mclk_bootup_value,
(uint32_t *)&(smu_data->smc_state_table.MemoryBootLevel));
if (0 != result) {
smu_data->smc_state_table.MemoryBootLevel = 0;
printk(KERN_ERR "[ powerplay ] VBIOS did not find boot engine clock value \
in dependency table. Using Memory DPM level 0!");
result = 0;
}
table->BootVddc = data->vbios_boot_state.vddc_bootup_value;
if (SMU7_VOLTAGE_CONTROL_NONE == data->vddci_control)
table->BootVddci = table->BootVddc;
else
table->BootVddci = data->vbios_boot_state.vddci_bootup_value;
table->BootMVdd = data->vbios_boot_state.mvdd_bootup_value;
return result;
}
static int iceland_populate_mc_reg_address(struct pp_smumgr *smumgr,
SMU71_Discrete_MCRegisters *mc_reg_table)
{
const struct iceland_smumgr *smu_data = (struct iceland_smumgr *)smumgr->backend;
uint32_t i, j;
for (i = 0, j = 0; j < smu_data->mc_reg_table.last; j++) {
if (smu_data->mc_reg_table.validflag & 1<<j) {
PP_ASSERT_WITH_CODE(i < SMU71_DISCRETE_MC_REGISTER_ARRAY_SIZE,
"Index of mc_reg_table->address[] array out of boundary", return -EINVAL);
mc_reg_table->address[i].s0 =
PP_HOST_TO_SMC_US(smu_data->mc_reg_table.mc_reg_address[j].s0);
mc_reg_table->address[i].s1 =
PP_HOST_TO_SMC_US(smu_data->mc_reg_table.mc_reg_address[j].s1);
i++;
}
}
mc_reg_table->last = (uint8_t)i;
return 0;
}
/*convert register values from driver to SMC format */
static void iceland_convert_mc_registers(
const struct iceland_mc_reg_entry *entry,
SMU71_Discrete_MCRegisterSet *data,
uint32_t num_entries, uint32_t valid_flag)
{
uint32_t i, j;
for (i = 0, j = 0; j < num_entries; j++) {
if (valid_flag & 1<<j) {
data->value[i] = PP_HOST_TO_SMC_UL(entry->mc_data[j]);
i++;
}
}
}
static int iceland_convert_mc_reg_table_entry_to_smc(
struct pp_smumgr *smumgr,
const uint32_t memory_clock,
SMU71_Discrete_MCRegisterSet *mc_reg_table_data
)
{
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(smumgr->backend);
uint32_t i = 0;
for (i = 0; i < smu_data->mc_reg_table.num_entries; i++) {
if (memory_clock <=
smu_data->mc_reg_table.mc_reg_table_entry[i].mclk_max) {
break;
}
}
if ((i == smu_data->mc_reg_table.num_entries) && (i > 0))
--i;
iceland_convert_mc_registers(&smu_data->mc_reg_table.mc_reg_table_entry[i],
mc_reg_table_data, smu_data->mc_reg_table.last,
smu_data->mc_reg_table.validflag);
return 0;
}
static int iceland_convert_mc_reg_table_to_smc(struct pp_hwmgr *hwmgr,
SMU71_Discrete_MCRegisters *mc_regs)
{
int result = 0;
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
int res;
uint32_t i;
for (i = 0; i < data->dpm_table.mclk_table.count; i++) {
res = iceland_convert_mc_reg_table_entry_to_smc(
hwmgr->smumgr,
data->dpm_table.mclk_table.dpm_levels[i].value,
&mc_regs->data[i]
);
if (0 != res)
result = res;
}
return result;
}
static int iceland_update_and_upload_mc_reg_table(struct pp_hwmgr *hwmgr)
{
struct pp_smumgr *smumgr = hwmgr->smumgr;
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(smumgr->backend);
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
uint32_t address;
int32_t result;
if (0 == (data->need_update_smu7_dpm_table & DPMTABLE_OD_UPDATE_MCLK))
return 0;
memset(&smu_data->mc_regs, 0, sizeof(SMU71_Discrete_MCRegisters));
result = iceland_convert_mc_reg_table_to_smc(hwmgr, &(smu_data->mc_regs));
if (result != 0)
return result;
address = smu_data->smu7_data.mc_reg_table_start + (uint32_t)offsetof(SMU71_Discrete_MCRegisters, data[0]);
return smu7_copy_bytes_to_smc(hwmgr->smumgr, address,
(uint8_t *)&smu_data->mc_regs.data[0],
sizeof(SMU71_Discrete_MCRegisterSet) * data->dpm_table.mclk_table.count,
SMC_RAM_END);
}
static int iceland_populate_initial_mc_reg_table(struct pp_hwmgr *hwmgr)
{
int result;
struct pp_smumgr *smumgr = hwmgr->smumgr;
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(smumgr->backend);
memset(&smu_data->mc_regs, 0x00, sizeof(SMU71_Discrete_MCRegisters));
result = iceland_populate_mc_reg_address(smumgr, &(smu_data->mc_regs));
PP_ASSERT_WITH_CODE(0 == result,
"Failed to initialize MCRegTable for the MC register addresses!", return result;);
result = iceland_convert_mc_reg_table_to_smc(hwmgr, &smu_data->mc_regs);
PP_ASSERT_WITH_CODE(0 == result,
"Failed to initialize MCRegTable for driver state!", return result;);
return smu7_copy_bytes_to_smc(smumgr, smu_data->smu7_data.mc_reg_table_start,
(uint8_t *)&smu_data->mc_regs, sizeof(SMU71_Discrete_MCRegisters), SMC_RAM_END);
}
static int iceland_populate_smc_initial_state(struct pp_hwmgr *hwmgr)
{
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
uint8_t count, level;
count = (uint8_t)(hwmgr->dyn_state.vddc_dependency_on_sclk->count);
for (level = 0; level < count; level++) {
if (hwmgr->dyn_state.vddc_dependency_on_sclk->entries[level].clk
>= data->vbios_boot_state.sclk_bootup_value) {
smu_data->smc_state_table.GraphicsBootLevel = level;
break;
}
}
count = (uint8_t)(hwmgr->dyn_state.vddc_dependency_on_mclk->count);
for (level = 0; level < count; level++) {
if (hwmgr->dyn_state.vddc_dependency_on_mclk->entries[level].clk
>= data->vbios_boot_state.mclk_bootup_value) {
smu_data->smc_state_table.MemoryBootLevel = level;
break;
}
}
return 0;
}
static int iceland_populate_bapm_parameters_in_dpm_table(struct pp_hwmgr *hwmgr)
{
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
const struct iceland_pt_defaults *defaults = smu_data->power_tune_defaults;
SMU71_Discrete_DpmTable *dpm_table = &(smu_data->smc_state_table);
struct phm_cac_tdp_table *cac_dtp_table = hwmgr->dyn_state.cac_dtp_table;
struct phm_ppm_table *ppm = hwmgr->dyn_state.ppm_parameter_table;
const uint16_t *def1, *def2;
int i, j, k;
/*
* TDP number of fraction bits are changed from 8 to 7 for Iceland
* as requested by SMC team
*/
dpm_table->DefaultTdp = PP_HOST_TO_SMC_US((uint16_t)(cac_dtp_table->usTDP * 256));
dpm_table->TargetTdp = PP_HOST_TO_SMC_US((uint16_t)(cac_dtp_table->usConfigurableTDP * 256));
dpm_table->DTETjOffset = 0;
dpm_table->GpuTjMax = (uint8_t)(data->thermal_temp_setting.temperature_high / PP_TEMPERATURE_UNITS_PER_CENTIGRADES);
dpm_table->GpuTjHyst = 8;
dpm_table->DTEAmbientTempBase = defaults->dte_ambient_temp_base;
/* The following are for new Iceland Multi-input fan/thermal control */
if (NULL != ppm) {
dpm_table->PPM_PkgPwrLimit = (uint16_t)ppm->dgpu_tdp * 256 / 1000;
dpm_table->PPM_TemperatureLimit = (uint16_t)ppm->tj_max * 256;
} else {
dpm_table->PPM_PkgPwrLimit = 0;
dpm_table->PPM_TemperatureLimit = 0;
}
CONVERT_FROM_HOST_TO_SMC_US(dpm_table->PPM_PkgPwrLimit);
CONVERT_FROM_HOST_TO_SMC_US(dpm_table->PPM_TemperatureLimit);
dpm_table->BAPM_TEMP_GRADIENT = PP_HOST_TO_SMC_UL(defaults->bamp_temp_gradient);
def1 = defaults->bapmti_r;
def2 = defaults->bapmti_rc;
for (i = 0; i < SMU71_DTE_ITERATIONS; i++) {
for (j = 0; j < SMU71_DTE_SOURCES; j++) {
for (k = 0; k < SMU71_DTE_SINKS; k++) {
dpm_table->BAPMTI_R[i][j][k] = PP_HOST_TO_SMC_US(*def1);
dpm_table->BAPMTI_RC[i][j][k] = PP_HOST_TO_SMC_US(*def2);
def1++;
def2++;
}
}
}
return 0;
}
static int iceland_populate_smc_svi2_config(struct pp_hwmgr *hwmgr,
SMU71_Discrete_DpmTable *tab)
{
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
if (SMU7_VOLTAGE_CONTROL_BY_SVID2 == data->voltage_control)
tab->SVI2Enable |= VDDC_ON_SVI2;
if (SMU7_VOLTAGE_CONTROL_BY_SVID2 == data->vddci_control)
tab->SVI2Enable |= VDDCI_ON_SVI2;
else
tab->MergedVddci = 1;
if (SMU7_VOLTAGE_CONTROL_BY_SVID2 == data->mvdd_control)
tab->SVI2Enable |= MVDD_ON_SVI2;
PP_ASSERT_WITH_CODE(tab->SVI2Enable != (VDDC_ON_SVI2 | VDDCI_ON_SVI2 | MVDD_ON_SVI2) &&
(tab->SVI2Enable & VDDC_ON_SVI2), "SVI2 domain configuration is incorrect!", return -EINVAL);
return 0;
}
/**
* Initializes the SMC table and uploads it
*
* @param hwmgr the address of the powerplay hardware manager.
* @param pInput the pointer to input data (PowerState)
* @return always 0
*/
int iceland_init_smc_table(struct pp_hwmgr *hwmgr)
{
int result;
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
SMU71_Discrete_DpmTable *table = &(smu_data->smc_state_table);
iceland_initialize_power_tune_defaults(hwmgr);
memset(&(smu_data->smc_state_table), 0x00, sizeof(smu_data->smc_state_table));
if (SMU7_VOLTAGE_CONTROL_NONE != data->voltage_control) {
iceland_populate_smc_voltage_tables(hwmgr, table);
}
if (phm_cap_enabled(hwmgr->platform_descriptor.platformCaps,
PHM_PlatformCaps_AutomaticDCTransition))
table->SystemFlags |= PPSMC_SYSTEMFLAG_GPIO_DC;
if (phm_cap_enabled(hwmgr->platform_descriptor.platformCaps,
PHM_PlatformCaps_StepVddc))
table->SystemFlags |= PPSMC_SYSTEMFLAG_STEPVDDC;
if (data->is_memory_gddr5)
table->SystemFlags |= PPSMC_SYSTEMFLAG_GDDR5;
if (data->ulv_supported) {
result = iceland_populate_ulv_state(hwmgr, &(smu_data->ulv_setting));
PP_ASSERT_WITH_CODE(0 == result,
"Failed to initialize ULV state!", return result;);
cgs_write_ind_register(hwmgr->device, CGS_IND_REG__SMC,
ixCG_ULV_PARAMETER, 0x40035);
}
result = iceland_populate_smc_link_level(hwmgr, table);
PP_ASSERT_WITH_CODE(0 == result,
"Failed to initialize Link Level!", return result;);
result = iceland_populate_all_graphic_levels(hwmgr);
PP_ASSERT_WITH_CODE(0 == result,
"Failed to initialize Graphics Level!", return result;);
result = iceland_populate_all_memory_levels(hwmgr);
PP_ASSERT_WITH_CODE(0 == result,
"Failed to initialize Memory Level!", return result;);
result = iceland_populate_smc_acpi_level(hwmgr, table);
PP_ASSERT_WITH_CODE(0 == result,
"Failed to initialize ACPI Level!", return result;);
result = iceland_populate_smc_vce_level(hwmgr, table);
PP_ASSERT_WITH_CODE(0 == result,
"Failed to initialize VCE Level!", return result;);
result = iceland_populate_smc_acp_level(hwmgr, table);
PP_ASSERT_WITH_CODE(0 == result,
"Failed to initialize ACP Level!", return result;);
result = iceland_populate_smc_samu_level(hwmgr, table);
PP_ASSERT_WITH_CODE(0 == result,
"Failed to initialize SAMU Level!", return result;);
/* Since only the initial state is completely set up at this point (the other states are just copies of the boot state) we only */
/* need to populate the ARB settings for the initial state. */
result = iceland_program_memory_timing_parameters(hwmgr);
PP_ASSERT_WITH_CODE(0 == result,
"Failed to Write ARB settings for the initial state.", return result;);
result = iceland_populate_smc_uvd_level(hwmgr, table);
PP_ASSERT_WITH_CODE(0 == result,
"Failed to initialize UVD Level!", return result;);
table->GraphicsBootLevel = 0;
table->MemoryBootLevel = 0;
result = iceland_populate_smc_boot_level(hwmgr, table);
PP_ASSERT_WITH_CODE(0 == result,
"Failed to initialize Boot Level!", return result;);
result = iceland_populate_smc_initial_state(hwmgr);
PP_ASSERT_WITH_CODE(0 == result, "Failed to initialize Boot State!", return result);
result = iceland_populate_bapm_parameters_in_dpm_table(hwmgr);
PP_ASSERT_WITH_CODE(0 == result, "Failed to populate BAPM Parameters!", return result);
table->GraphicsVoltageChangeEnable = 1;
table->GraphicsThermThrottleEnable = 1;
table->GraphicsInterval = 1;
table->VoltageInterval = 1;
table->ThermalInterval = 1;
table->TemperatureLimitHigh =
(data->thermal_temp_setting.temperature_high *
SMU7_Q88_FORMAT_CONVERSION_UNIT) / PP_TEMPERATURE_UNITS_PER_CENTIGRADES;
table->TemperatureLimitLow =
(data->thermal_temp_setting.temperature_low *
SMU7_Q88_FORMAT_CONVERSION_UNIT) / PP_TEMPERATURE_UNITS_PER_CENTIGRADES;
table->MemoryVoltageChangeEnable = 1;
table->MemoryInterval = 1;
table->VoltageResponseTime = 0;
table->PhaseResponseTime = 0;
table->MemoryThermThrottleEnable = 1;
table->PCIeBootLinkLevel = 0;
table->PCIeGenInterval = 1;
result = iceland_populate_smc_svi2_config(hwmgr, table);
PP_ASSERT_WITH_CODE(0 == result,
"Failed to populate SVI2 setting!", return result);
table->ThermGpio = 17;
table->SclkStepSize = 0x4000;
CONVERT_FROM_HOST_TO_SMC_UL(table->SystemFlags);
CONVERT_FROM_HOST_TO_SMC_UL(table->SmioMaskVddcVid);
CONVERT_FROM_HOST_TO_SMC_UL(table->SmioMaskVddcPhase);
CONVERT_FROM_HOST_TO_SMC_UL(table->SmioMaskVddciVid);
CONVERT_FROM_HOST_TO_SMC_UL(table->SmioMaskMvddVid);
CONVERT_FROM_HOST_TO_SMC_UL(table->SclkStepSize);
CONVERT_FROM_HOST_TO_SMC_US(table->TemperatureLimitHigh);
CONVERT_FROM_HOST_TO_SMC_US(table->TemperatureLimitLow);
CONVERT_FROM_HOST_TO_SMC_US(table->VoltageResponseTime);
CONVERT_FROM_HOST_TO_SMC_US(table->PhaseResponseTime);
table->BootVddc = PP_HOST_TO_SMC_US(table->BootVddc * VOLTAGE_SCALE);
table->BootVddci = PP_HOST_TO_SMC_US(table->BootVddci * VOLTAGE_SCALE);
table->BootMVdd = PP_HOST_TO_SMC_US(table->BootMVdd * VOLTAGE_SCALE);
/* Upload all dpm data to SMC memory.(dpm level, dpm level count etc) */
result = smu7_copy_bytes_to_smc(hwmgr->smumgr, smu_data->smu7_data.dpm_table_start +
offsetof(SMU71_Discrete_DpmTable, SystemFlags),
(uint8_t *)&(table->SystemFlags),
sizeof(SMU71_Discrete_DpmTable)-3 * sizeof(SMU71_PIDController),
SMC_RAM_END);
PP_ASSERT_WITH_CODE(0 == result,
"Failed to upload dpm data to SMC memory!", return result;);
/* Upload all ulv setting to SMC memory.(dpm level, dpm level count etc) */
result = smu7_copy_bytes_to_smc(hwmgr->smumgr,
smu_data->smu7_data.ulv_setting_starts,
(uint8_t *)&(smu_data->ulv_setting),
sizeof(SMU71_Discrete_Ulv),
SMC_RAM_END);
result = iceland_populate_initial_mc_reg_table(hwmgr);
PP_ASSERT_WITH_CODE((0 == result),
"Failed to populate initialize MC Reg table!", return result);
result = iceland_populate_pm_fuses(hwmgr);
PP_ASSERT_WITH_CODE(0 == result,
"Failed to populate PM fuses to SMC memory!", return result);
return 0;
}
/**
* Set up the fan table to control the fan using the SMC.
* @param hwmgr the address of the powerplay hardware manager.
* @param pInput the pointer to input data
* @param pOutput the pointer to output data
* @param pStorage the pointer to temporary storage
* @param Result the last failure code
* @return result from set temperature range routine
*/
int iceland_thermal_setup_fan_table(struct pp_hwmgr *hwmgr)
{
struct smu7_smumgr *smu7_data = (struct smu7_smumgr *)(hwmgr->smumgr->backend);
SMU71_Discrete_FanTable fan_table = { FDO_MODE_HARDWARE };
uint32_t duty100;
uint32_t t_diff1, t_diff2, pwm_diff1, pwm_diff2;
uint16_t fdo_min, slope1, slope2;
uint32_t reference_clock;
int res;
uint64_t tmp64;
if (!phm_cap_enabled(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_MicrocodeFanControl))
return 0;
if (hwmgr->thermal_controller.fanInfo.bNoFan) {
phm_cap_unset(hwmgr->platform_descriptor.platformCaps,
PHM_PlatformCaps_MicrocodeFanControl);
return 0;
}
if (0 == smu7_data->fan_table_start) {
phm_cap_unset(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_MicrocodeFanControl);
return 0;
}
duty100 = PHM_READ_VFPF_INDIRECT_FIELD(hwmgr->device, CGS_IND_REG__SMC, CG_FDO_CTRL1, FMAX_DUTY100);
if (0 == duty100) {
phm_cap_unset(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_MicrocodeFanControl);
return 0;
}
tmp64 = hwmgr->thermal_controller.advanceFanControlParameters.usPWMMin * duty100;
do_div(tmp64, 10000);
fdo_min = (uint16_t)tmp64;
t_diff1 = hwmgr->thermal_controller.advanceFanControlParameters.usTMed - hwmgr->thermal_controller.advanceFanControlParameters.usTMin;
t_diff2 = hwmgr->thermal_controller.advanceFanControlParameters.usTHigh - hwmgr->thermal_controller.advanceFanControlParameters.usTMed;
pwm_diff1 = hwmgr->thermal_controller.advanceFanControlParameters.usPWMMed - hwmgr->thermal_controller.advanceFanControlParameters.usPWMMin;
pwm_diff2 = hwmgr->thermal_controller.advanceFanControlParameters.usPWMHigh - hwmgr->thermal_controller.advanceFanControlParameters.usPWMMed;
slope1 = (uint16_t)((50 + ((16 * duty100 * pwm_diff1) / t_diff1)) / 100);
slope2 = (uint16_t)((50 + ((16 * duty100 * pwm_diff2) / t_diff2)) / 100);
fan_table.TempMin = cpu_to_be16((50 + hwmgr->thermal_controller.advanceFanControlParameters.usTMin) / 100);
fan_table.TempMed = cpu_to_be16((50 + hwmgr->thermal_controller.advanceFanControlParameters.usTMed) / 100);
fan_table.TempMax = cpu_to_be16((50 + hwmgr->thermal_controller.advanceFanControlParameters.usTMax) / 100);
fan_table.Slope1 = cpu_to_be16(slope1);
fan_table.Slope2 = cpu_to_be16(slope2);
fan_table.FdoMin = cpu_to_be16(fdo_min);
fan_table.HystDown = cpu_to_be16(hwmgr->thermal_controller.advanceFanControlParameters.ucTHyst);
fan_table.HystUp = cpu_to_be16(1);
fan_table.HystSlope = cpu_to_be16(1);
fan_table.TempRespLim = cpu_to_be16(5);
reference_clock = smu7_get_xclk(hwmgr);
fan_table.RefreshPeriod = cpu_to_be32((hwmgr->thermal_controller.advanceFanControlParameters.ulCycleDelay * reference_clock) / 1600);
fan_table.FdoMax = cpu_to_be16((uint16_t)duty100);
fan_table.TempSrc = (uint8_t)PHM_READ_VFPF_INDIRECT_FIELD(hwmgr->device, CGS_IND_REG__SMC, CG_MULT_THERMAL_CTRL, TEMP_SEL);
/* fan_table.FanControl_GL_Flag = 1; */
res = smu7_copy_bytes_to_smc(hwmgr->smumgr, smu7_data->fan_table_start, (uint8_t *)&fan_table, (uint32_t)sizeof(fan_table), SMC_RAM_END);
return 0;
}
static int iceland_program_mem_timing_parameters(struct pp_hwmgr *hwmgr)
{
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
if (data->need_update_smu7_dpm_table &
(DPMTABLE_OD_UPDATE_SCLK + DPMTABLE_OD_UPDATE_MCLK))
return iceland_program_memory_timing_parameters(hwmgr);
return 0;
}
int iceland_update_sclk_threshold(struct pp_hwmgr *hwmgr)
{
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
int result = 0;
uint32_t low_sclk_interrupt_threshold = 0;
if (phm_cap_enabled(hwmgr->platform_descriptor.platformCaps,
PHM_PlatformCaps_SclkThrottleLowNotification)
&& (hwmgr->gfx_arbiter.sclk_threshold !=
data->low_sclk_interrupt_threshold)) {
data->low_sclk_interrupt_threshold =
hwmgr->gfx_arbiter.sclk_threshold;
low_sclk_interrupt_threshold =
data->low_sclk_interrupt_threshold;
CONVERT_FROM_HOST_TO_SMC_UL(low_sclk_interrupt_threshold);
result = smu7_copy_bytes_to_smc(
hwmgr->smumgr,
smu_data->smu7_data.dpm_table_start +
offsetof(SMU71_Discrete_DpmTable,
LowSclkInterruptThreshold),
(uint8_t *)&low_sclk_interrupt_threshold,
sizeof(uint32_t),
SMC_RAM_END);
}
result = iceland_update_and_upload_mc_reg_table(hwmgr);
PP_ASSERT_WITH_CODE((0 == result), "Failed to upload MC reg table!", return result);
result = iceland_program_mem_timing_parameters(hwmgr);
PP_ASSERT_WITH_CODE((result == 0),
"Failed to program memory timing parameters!",
);
return result;
}
uint32_t iceland_get_offsetof(uint32_t type, uint32_t member)
{
switch (type) {
case SMU_SoftRegisters:
switch (member) {
case HandshakeDisables:
return offsetof(SMU71_SoftRegisters, HandshakeDisables);
case VoltageChangeTimeout:
return offsetof(SMU71_SoftRegisters, VoltageChangeTimeout);
case AverageGraphicsActivity:
return offsetof(SMU71_SoftRegisters, AverageGraphicsActivity);
case PreVBlankGap:
return offsetof(SMU71_SoftRegisters, PreVBlankGap);
case VBlankTimeout:
return offsetof(SMU71_SoftRegisters, VBlankTimeout);
case UcodeLoadStatus:
return offsetof(SMU71_SoftRegisters, UcodeLoadStatus);
}
case SMU_Discrete_DpmTable:
switch (member) {
case LowSclkInterruptThreshold:
return offsetof(SMU71_Discrete_DpmTable, LowSclkInterruptThreshold);
}
}
printk(KERN_WARNING "can't get the offset of type %x member %x\n", type, member);
return 0;
}
uint32_t iceland_get_mac_definition(uint32_t value)
{
switch (value) {
case SMU_MAX_LEVELS_GRAPHICS:
return SMU71_MAX_LEVELS_GRAPHICS;
case SMU_MAX_LEVELS_MEMORY:
return SMU71_MAX_LEVELS_MEMORY;
case SMU_MAX_LEVELS_LINK:
return SMU71_MAX_LEVELS_LINK;
case SMU_MAX_ENTRIES_SMIO:
return SMU71_MAX_ENTRIES_SMIO;
case SMU_MAX_LEVELS_VDDC:
return SMU71_MAX_LEVELS_VDDC;
case SMU_MAX_LEVELS_VDDCI:
return SMU71_MAX_LEVELS_VDDCI;
case SMU_MAX_LEVELS_MVDD:
return SMU71_MAX_LEVELS_MVDD;
}
printk(KERN_WARNING "can't get the mac of %x\n", value);
return 0;
}
/**
* Get the location of various tables inside the FW image.
*
* @param hwmgr the address of the powerplay hardware manager.
* @return always 0
*/
int iceland_process_firmware_header(struct pp_hwmgr *hwmgr)
{
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
struct smu7_smumgr *smu7_data = (struct smu7_smumgr *)(hwmgr->smumgr->backend);
uint32_t tmp;
int result;
bool error = false;
result = smu7_read_smc_sram_dword(hwmgr->smumgr,
SMU71_FIRMWARE_HEADER_LOCATION +
offsetof(SMU71_Firmware_Header, DpmTable),
&tmp, SMC_RAM_END);
if (0 == result) {
smu7_data->dpm_table_start = tmp;
}
error |= (0 != result);
result = smu7_read_smc_sram_dword(hwmgr->smumgr,
SMU71_FIRMWARE_HEADER_LOCATION +
offsetof(SMU71_Firmware_Header, SoftRegisters),
&tmp, SMC_RAM_END);
if (0 == result) {
data->soft_regs_start = tmp;
smu7_data->soft_regs_start = tmp;
}
error |= (0 != result);
result = smu7_read_smc_sram_dword(hwmgr->smumgr,
SMU71_FIRMWARE_HEADER_LOCATION +
offsetof(SMU71_Firmware_Header, mcRegisterTable),
&tmp, SMC_RAM_END);
if (0 == result) {
smu7_data->mc_reg_table_start = tmp;
}
result = smu7_read_smc_sram_dword(hwmgr->smumgr,
SMU71_FIRMWARE_HEADER_LOCATION +
offsetof(SMU71_Firmware_Header, FanTable),
&tmp, SMC_RAM_END);
if (0 == result) {
smu7_data->fan_table_start = tmp;
}
error |= (0 != result);
result = smu7_read_smc_sram_dword(hwmgr->smumgr,
SMU71_FIRMWARE_HEADER_LOCATION +
offsetof(SMU71_Firmware_Header, mcArbDramTimingTable),
&tmp, SMC_RAM_END);
if (0 == result) {
smu7_data->arb_table_start = tmp;
}
error |= (0 != result);
result = smu7_read_smc_sram_dword(hwmgr->smumgr,
SMU71_FIRMWARE_HEADER_LOCATION +
offsetof(SMU71_Firmware_Header, Version),
&tmp, SMC_RAM_END);
if (0 == result) {
hwmgr->microcode_version_info.SMC = tmp;
}
error |= (0 != result);
result = smu7_read_smc_sram_dword(hwmgr->smumgr,
SMU71_FIRMWARE_HEADER_LOCATION +
offsetof(SMU71_Firmware_Header, UlvSettings),
&tmp, SMC_RAM_END);
if (0 == result) {
smu7_data->ulv_setting_starts = tmp;
}
error |= (0 != result);
return error ? 1 : 0;
}
/*---------------------------MC----------------------------*/
static uint8_t iceland_get_memory_modile_index(struct pp_hwmgr *hwmgr)
{
return (uint8_t) (0xFF & (cgs_read_register(hwmgr->device, mmBIOS_SCRATCH_4) >> 16));
}
static bool iceland_check_s0_mc_reg_index(uint16_t in_reg, uint16_t *out_reg)
{
bool result = true;
switch (in_reg) {
case mmMC_SEQ_RAS_TIMING:
*out_reg = mmMC_SEQ_RAS_TIMING_LP;
break;
case mmMC_SEQ_DLL_STBY:
*out_reg = mmMC_SEQ_DLL_STBY_LP;
break;
case mmMC_SEQ_G5PDX_CMD0:
*out_reg = mmMC_SEQ_G5PDX_CMD0_LP;
break;
case mmMC_SEQ_G5PDX_CMD1:
*out_reg = mmMC_SEQ_G5PDX_CMD1_LP;
break;
case mmMC_SEQ_G5PDX_CTRL:
*out_reg = mmMC_SEQ_G5PDX_CTRL_LP;
break;
case mmMC_SEQ_CAS_TIMING:
*out_reg = mmMC_SEQ_CAS_TIMING_LP;
break;
case mmMC_SEQ_MISC_TIMING:
*out_reg = mmMC_SEQ_MISC_TIMING_LP;
break;
case mmMC_SEQ_MISC_TIMING2:
*out_reg = mmMC_SEQ_MISC_TIMING2_LP;
break;
case mmMC_SEQ_PMG_DVS_CMD:
*out_reg = mmMC_SEQ_PMG_DVS_CMD_LP;
break;
case mmMC_SEQ_PMG_DVS_CTL:
*out_reg = mmMC_SEQ_PMG_DVS_CTL_LP;
break;
case mmMC_SEQ_RD_CTL_D0:
*out_reg = mmMC_SEQ_RD_CTL_D0_LP;
break;
case mmMC_SEQ_RD_CTL_D1:
*out_reg = mmMC_SEQ_RD_CTL_D1_LP;
break;
case mmMC_SEQ_WR_CTL_D0:
*out_reg = mmMC_SEQ_WR_CTL_D0_LP;
break;
case mmMC_SEQ_WR_CTL_D1:
*out_reg = mmMC_SEQ_WR_CTL_D1_LP;
break;
case mmMC_PMG_CMD_EMRS:
*out_reg = mmMC_SEQ_PMG_CMD_EMRS_LP;
break;
case mmMC_PMG_CMD_MRS:
*out_reg = mmMC_SEQ_PMG_CMD_MRS_LP;
break;
case mmMC_PMG_CMD_MRS1:
*out_reg = mmMC_SEQ_PMG_CMD_MRS1_LP;
break;
case mmMC_SEQ_PMG_TIMING:
*out_reg = mmMC_SEQ_PMG_TIMING_LP;
break;
case mmMC_PMG_CMD_MRS2:
*out_reg = mmMC_SEQ_PMG_CMD_MRS2_LP;
break;
case mmMC_SEQ_WR_CTL_2:
*out_reg = mmMC_SEQ_WR_CTL_2_LP;
break;
default:
result = false;
break;
}
return result;
}
static int iceland_set_s0_mc_reg_index(struct iceland_mc_reg_table *table)
{
uint32_t i;
uint16_t address;
for (i = 0; i < table->last; i++) {
table->mc_reg_address[i].s0 =
iceland_check_s0_mc_reg_index(table->mc_reg_address[i].s1, &address)
? address : table->mc_reg_address[i].s1;
}
return 0;
}
static int iceland_copy_vbios_smc_reg_table(const pp_atomctrl_mc_reg_table *table,
struct iceland_mc_reg_table *ni_table)
{
uint8_t i, j;
PP_ASSERT_WITH_CODE((table->last <= SMU71_DISCRETE_MC_REGISTER_ARRAY_SIZE),
"Invalid VramInfo table.", return -EINVAL);
PP_ASSERT_WITH_CODE((table->num_entries <= MAX_AC_TIMING_ENTRIES),
"Invalid VramInfo table.", return -EINVAL);
for (i = 0; i < table->last; i++) {
ni_table->mc_reg_address[i].s1 = table->mc_reg_address[i].s1;
}
ni_table->last = table->last;
for (i = 0; i < table->num_entries; i++) {
ni_table->mc_reg_table_entry[i].mclk_max =
table->mc_reg_table_entry[i].mclk_max;
for (j = 0; j < table->last; j++) {
ni_table->mc_reg_table_entry[i].mc_data[j] =
table->mc_reg_table_entry[i].mc_data[j];
}
}
ni_table->num_entries = table->num_entries;
return 0;
}
/**
* VBIOS omits some information to reduce size, we need to recover them here.
* 1. when we see mmMC_SEQ_MISC1, bit[31:16] EMRS1, need to be write to mmMC_PMG_CMD_EMRS /_LP[15:0].
* Bit[15:0] MRS, need to be update mmMC_PMG_CMD_MRS/_LP[15:0]
* 2. when we see mmMC_SEQ_RESERVE_M, bit[15:0] EMRS2, need to be write to mmMC_PMG_CMD_MRS1/_LP[15:0].
* 3. need to set these data for each clock range
*
* @param hwmgr the address of the powerplay hardware manager.
* @param table the address of MCRegTable
* @return always 0
*/
static int iceland_set_mc_special_registers(struct pp_hwmgr *hwmgr,
struct iceland_mc_reg_table *table)
{
uint8_t i, j, k;
uint32_t temp_reg;
struct smu7_hwmgr *data = (struct smu7_hwmgr *)(hwmgr->backend);
for (i = 0, j = table->last; i < table->last; i++) {
PP_ASSERT_WITH_CODE((j < SMU71_DISCRETE_MC_REGISTER_ARRAY_SIZE),
"Invalid VramInfo table.", return -EINVAL);
switch (table->mc_reg_address[i].s1) {
case mmMC_SEQ_MISC1:
temp_reg = cgs_read_register(hwmgr->device, mmMC_PMG_CMD_EMRS);
table->mc_reg_address[j].s1 = mmMC_PMG_CMD_EMRS;
table->mc_reg_address[j].s0 = mmMC_SEQ_PMG_CMD_EMRS_LP;
for (k = 0; k < table->num_entries; k++) {
table->mc_reg_table_entry[k].mc_data[j] =
((temp_reg & 0xffff0000)) |
((table->mc_reg_table_entry[k].mc_data[i] & 0xffff0000) >> 16);
}
j++;
PP_ASSERT_WITH_CODE((j < SMU71_DISCRETE_MC_REGISTER_ARRAY_SIZE),
"Invalid VramInfo table.", return -EINVAL);
temp_reg = cgs_read_register(hwmgr->device, mmMC_PMG_CMD_MRS);
table->mc_reg_address[j].s1 = mmMC_PMG_CMD_MRS;
table->mc_reg_address[j].s0 = mmMC_SEQ_PMG_CMD_MRS_LP;
for (k = 0; k < table->num_entries; k++) {
table->mc_reg_table_entry[k].mc_data[j] =
(temp_reg & 0xffff0000) |
(table->mc_reg_table_entry[k].mc_data[i] & 0x0000ffff);
if (!data->is_memory_gddr5) {
table->mc_reg_table_entry[k].mc_data[j] |= 0x100;
}
}
j++;
PP_ASSERT_WITH_CODE((j <= SMU71_DISCRETE_MC_REGISTER_ARRAY_SIZE),
"Invalid VramInfo table.", return -EINVAL);
if (!data->is_memory_gddr5 && j < SMU71_DISCRETE_MC_REGISTER_ARRAY_SIZE) {
table->mc_reg_address[j].s1 = mmMC_PMG_AUTO_CMD;
table->mc_reg_address[j].s0 = mmMC_PMG_AUTO_CMD;
for (k = 0; k < table->num_entries; k++) {
table->mc_reg_table_entry[k].mc_data[j] =
(table->mc_reg_table_entry[k].mc_data[i] & 0xffff0000) >> 16;
}
j++;
PP_ASSERT_WITH_CODE((j <= SMU71_DISCRETE_MC_REGISTER_ARRAY_SIZE),
"Invalid VramInfo table.", return -EINVAL);
}
break;
case mmMC_SEQ_RESERVE_M:
temp_reg = cgs_read_register(hwmgr->device, mmMC_PMG_CMD_MRS1);
table->mc_reg_address[j].s1 = mmMC_PMG_CMD_MRS1;
table->mc_reg_address[j].s0 = mmMC_SEQ_PMG_CMD_MRS1_LP;
for (k = 0; k < table->num_entries; k++) {
table->mc_reg_table_entry[k].mc_data[j] =
(temp_reg & 0xffff0000) |
(table->mc_reg_table_entry[k].mc_data[i] & 0x0000ffff);
}
j++;
PP_ASSERT_WITH_CODE((j <= SMU71_DISCRETE_MC_REGISTER_ARRAY_SIZE),
"Invalid VramInfo table.", return -EINVAL);
break;
default:
break;
}
}
table->last = j;
return 0;
}
static int iceland_set_valid_flag(struct iceland_mc_reg_table *table)
{
uint8_t i, j;
for (i = 0; i < table->last; i++) {
for (j = 1; j < table->num_entries; j++) {
if (table->mc_reg_table_entry[j-1].mc_data[i] !=
table->mc_reg_table_entry[j].mc_data[i]) {
table->validflag |= (1<<i);
break;
}
}
}
return 0;
}
int iceland_initialize_mc_reg_table(struct pp_hwmgr *hwmgr)
{
int result;
struct iceland_smumgr *smu_data = (struct iceland_smumgr *)(hwmgr->smumgr->backend);
pp_atomctrl_mc_reg_table *table;
struct iceland_mc_reg_table *ni_table = &smu_data->mc_reg_table;
uint8_t module_index = iceland_get_memory_modile_index(hwmgr);
table = kzalloc(sizeof(pp_atomctrl_mc_reg_table), GFP_KERNEL);
if (NULL == table)
return -ENOMEM;
/* Program additional LP registers that are no longer programmed by VBIOS */
cgs_write_register(hwmgr->device, mmMC_SEQ_RAS_TIMING_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_RAS_TIMING));
cgs_write_register(hwmgr->device, mmMC_SEQ_CAS_TIMING_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_CAS_TIMING));
cgs_write_register(hwmgr->device, mmMC_SEQ_DLL_STBY_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_DLL_STBY));
cgs_write_register(hwmgr->device, mmMC_SEQ_G5PDX_CMD0_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_G5PDX_CMD0));
cgs_write_register(hwmgr->device, mmMC_SEQ_G5PDX_CMD1_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_G5PDX_CMD1));
cgs_write_register(hwmgr->device, mmMC_SEQ_G5PDX_CTRL_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_G5PDX_CTRL));
cgs_write_register(hwmgr->device, mmMC_SEQ_PMG_DVS_CMD_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_PMG_DVS_CMD));
cgs_write_register(hwmgr->device, mmMC_SEQ_PMG_DVS_CTL_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_PMG_DVS_CTL));
cgs_write_register(hwmgr->device, mmMC_SEQ_MISC_TIMING_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_MISC_TIMING));
cgs_write_register(hwmgr->device, mmMC_SEQ_MISC_TIMING2_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_MISC_TIMING2));
cgs_write_register(hwmgr->device, mmMC_SEQ_PMG_CMD_EMRS_LP, cgs_read_register(hwmgr->device, mmMC_PMG_CMD_EMRS));
cgs_write_register(hwmgr->device, mmMC_SEQ_PMG_CMD_MRS_LP, cgs_read_register(hwmgr->device, mmMC_PMG_CMD_MRS));
cgs_write_register(hwmgr->device, mmMC_SEQ_PMG_CMD_MRS1_LP, cgs_read_register(hwmgr->device, mmMC_PMG_CMD_MRS1));
cgs_write_register(hwmgr->device, mmMC_SEQ_WR_CTL_D0_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_WR_CTL_D0));
cgs_write_register(hwmgr->device, mmMC_SEQ_WR_CTL_D1_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_WR_CTL_D1));
cgs_write_register(hwmgr->device, mmMC_SEQ_RD_CTL_D0_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_RD_CTL_D0));
cgs_write_register(hwmgr->device, mmMC_SEQ_RD_CTL_D1_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_RD_CTL_D1));
cgs_write_register(hwmgr->device, mmMC_SEQ_PMG_TIMING_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_PMG_TIMING));
cgs_write_register(hwmgr->device, mmMC_SEQ_PMG_CMD_MRS2_LP, cgs_read_register(hwmgr->device, mmMC_PMG_CMD_MRS2));
cgs_write_register(hwmgr->device, mmMC_SEQ_WR_CTL_2_LP, cgs_read_register(hwmgr->device, mmMC_SEQ_WR_CTL_2));
memset(table, 0x00, sizeof(pp_atomctrl_mc_reg_table));
result = atomctrl_initialize_mc_reg_table(hwmgr, module_index, table);
if (0 == result)
result = iceland_copy_vbios_smc_reg_table(table, ni_table);
if (0 == result) {
iceland_set_s0_mc_reg_index(ni_table);
result = iceland_set_mc_special_registers(hwmgr, ni_table);
}
if (0 == result)
iceland_set_valid_flag(ni_table);
kfree(table);
return result;
}
bool iceland_is_dpm_running(struct pp_hwmgr *hwmgr)
{
return (1 == PHM_READ_INDIRECT_FIELD(hwmgr->device,
CGS_IND_REG__SMC, FEATURE_STATUS, VOLTAGE_CONTROLLER_ON))
? true : false;
}
| gpl-2.0 |
mk01/linux-fslc | arch/mips/lantiq/xway/reset.c | 292 | 9917 | /*
* 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.
*
* Copyright (C) 2010 John Crispin <john@phrozen.org>
* Copyright (C) 2013-2015 Lantiq Beteiligungs-GmbH & Co.KG
*/
#include <linux/init.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/pm.h>
#include <linux/export.h>
#include <linux/delay.h>
#include <linux/of_address.h>
#include <linux/of_platform.h>
#include <linux/reset-controller.h>
#include <asm/reboot.h>
#include <lantiq_soc.h>
#include "../prom.h"
/* reset request register */
#define RCU_RST_REQ 0x0010
/* reset status register */
#define RCU_RST_STAT 0x0014
/* vr9 gphy registers */
#define RCU_GFS_ADD0_XRX200 0x0020
#define RCU_GFS_ADD1_XRX200 0x0068
/* xRX300 gphy registers */
#define RCU_GFS_ADD0_XRX300 0x0020
#define RCU_GFS_ADD1_XRX300 0x0058
#define RCU_GFS_ADD2_XRX300 0x00AC
/* xRX330 gphy registers */
#define RCU_GFS_ADD0_XRX330 0x0020
#define RCU_GFS_ADD1_XRX330 0x0058
#define RCU_GFS_ADD2_XRX330 0x00AC
#define RCU_GFS_ADD3_XRX330 0x0264
/* xbar BE flag */
#define RCU_AHB_ENDIAN 0x004C
#define RCU_VR9_BE_AHB1S 0x00000008
/* reboot bit */
#define RCU_RD_GPHY0_XRX200 BIT(31)
#define RCU_RD_SRST BIT(30)
#define RCU_RD_GPHY1_XRX200 BIT(29)
/* xRX300 bits */
#define RCU_RD_GPHY0_XRX300 BIT(31)
#define RCU_RD_GPHY1_XRX300 BIT(29)
#define RCU_RD_GPHY2_XRX300 BIT(28)
/* xRX330 bits */
#define RCU_RD_GPHY0_XRX330 BIT(31)
#define RCU_RD_GPHY1_XRX330 BIT(29)
#define RCU_RD_GPHY2_XRX330 BIT(28)
#define RCU_RD_GPHY3_XRX330 BIT(10)
/* reset cause */
#define RCU_STAT_SHIFT 26
/* boot selection */
#define RCU_BOOT_SEL(x) ((x >> 18) & 0x7)
#define RCU_BOOT_SEL_XRX200(x) (((x >> 17) & 0xf) | ((x >> 8) & 0x10))
/* dwc2 USB configuration registers */
#define RCU_USB1CFG 0x0018
#define RCU_USB2CFG 0x0034
/* USB DMA endianness bits */
#define RCU_USBCFG_HDSEL_BIT BIT(11)
#define RCU_USBCFG_HOST_END_BIT BIT(10)
#define RCU_USBCFG_SLV_END_BIT BIT(9)
/* USB reset bits */
#define RCU_USBRESET 0x0010
#define USBRESET_BIT BIT(4)
#define RCU_USBRESET2 0x0048
#define USB1RESET_BIT BIT(4)
#define USB2RESET_BIT BIT(5)
#define RCU_CFG1A 0x0038
#define RCU_CFG1B 0x003C
/* USB PMU devices */
#define PMU_AHBM BIT(15)
#define PMU_USB0 BIT(6)
#define PMU_USB1 BIT(27)
/* USB PHY PMU devices */
#define PMU_USB0_P BIT(0)
#define PMU_USB1_P BIT(26)
/* remapped base addr of the reset control unit */
static void __iomem *ltq_rcu_membase;
static struct device_node *ltq_rcu_np;
static DEFINE_SPINLOCK(ltq_rcu_lock);
static void ltq_rcu_w32(uint32_t val, uint32_t reg_off)
{
ltq_w32(val, ltq_rcu_membase + reg_off);
}
static uint32_t ltq_rcu_r32(uint32_t reg_off)
{
return ltq_r32(ltq_rcu_membase + reg_off);
}
static void ltq_rcu_w32_mask(uint32_t clr, uint32_t set, uint32_t reg_off)
{
unsigned long flags;
spin_lock_irqsave(<q_rcu_lock, flags);
ltq_rcu_w32((ltq_rcu_r32(reg_off) & ~(clr)) | (set), reg_off);
spin_unlock_irqrestore(<q_rcu_lock, flags);
}
/* This function is used by the watchdog driver */
int ltq_reset_cause(void)
{
u32 val = ltq_rcu_r32(RCU_RST_STAT);
return val >> RCU_STAT_SHIFT;
}
EXPORT_SYMBOL_GPL(ltq_reset_cause);
/* allow platform code to find out what source we booted from */
unsigned char ltq_boot_select(void)
{
u32 val = ltq_rcu_r32(RCU_RST_STAT);
if (of_device_is_compatible(ltq_rcu_np, "lantiq,rcu-xrx200"))
return RCU_BOOT_SEL_XRX200(val);
return RCU_BOOT_SEL(val);
}
struct ltq_gphy_reset {
u32 rd;
u32 addr;
};
/* reset / boot a gphy */
static struct ltq_gphy_reset xrx200_gphy[] = {
{RCU_RD_GPHY0_XRX200, RCU_GFS_ADD0_XRX200},
{RCU_RD_GPHY1_XRX200, RCU_GFS_ADD1_XRX200},
};
/* reset / boot a gphy */
static struct ltq_gphy_reset xrx300_gphy[] = {
{RCU_RD_GPHY0_XRX300, RCU_GFS_ADD0_XRX300},
{RCU_RD_GPHY1_XRX300, RCU_GFS_ADD1_XRX300},
{RCU_RD_GPHY2_XRX300, RCU_GFS_ADD2_XRX300},
};
/* reset / boot a gphy */
static struct ltq_gphy_reset xrx330_gphy[] = {
{RCU_RD_GPHY0_XRX330, RCU_GFS_ADD0_XRX330},
{RCU_RD_GPHY1_XRX330, RCU_GFS_ADD1_XRX330},
{RCU_RD_GPHY2_XRX330, RCU_GFS_ADD2_XRX330},
{RCU_RD_GPHY3_XRX330, RCU_GFS_ADD3_XRX330},
};
static void xrx200_gphy_boot_addr(struct ltq_gphy_reset *phy_regs,
dma_addr_t dev_addr)
{
ltq_rcu_w32_mask(0, phy_regs->rd, RCU_RST_REQ);
ltq_rcu_w32(dev_addr, phy_regs->addr);
ltq_rcu_w32_mask(phy_regs->rd, 0, RCU_RST_REQ);
}
/* reset and boot a gphy. these phys only exist on xrx200 SoC */
int xrx200_gphy_boot(struct device *dev, unsigned int id, dma_addr_t dev_addr)
{
struct clk *clk;
if (!of_device_is_compatible(ltq_rcu_np, "lantiq,rcu-xrx200")) {
dev_err(dev, "this SoC has no GPHY\n");
return -EINVAL;
}
if (of_machine_is_compatible("lantiq,vr9")) {
clk = clk_get_sys("1f203000.rcu", "gphy");
if (IS_ERR(clk))
return PTR_ERR(clk);
clk_enable(clk);
}
dev_info(dev, "booting GPHY%u firmware at %X\n", id, dev_addr);
if (of_machine_is_compatible("lantiq,vr9")) {
if (id >= ARRAY_SIZE(xrx200_gphy)) {
dev_err(dev, "%u is an invalid gphy id\n", id);
return -EINVAL;
}
xrx200_gphy_boot_addr(&xrx200_gphy[id], dev_addr);
} else if (of_machine_is_compatible("lantiq,ar10")) {
if (id >= ARRAY_SIZE(xrx300_gphy)) {
dev_err(dev, "%u is an invalid gphy id\n", id);
return -EINVAL;
}
xrx200_gphy_boot_addr(&xrx300_gphy[id], dev_addr);
} else if (of_machine_is_compatible("lantiq,grx390")) {
if (id >= ARRAY_SIZE(xrx330_gphy)) {
dev_err(dev, "%u is an invalid gphy id\n", id);
return -EINVAL;
}
xrx200_gphy_boot_addr(&xrx330_gphy[id], dev_addr);
}
return 0;
}
/* reset a io domain for u micro seconds */
void ltq_reset_once(unsigned int module, ulong u)
{
ltq_rcu_w32(ltq_rcu_r32(RCU_RST_REQ) | module, RCU_RST_REQ);
udelay(u);
ltq_rcu_w32(ltq_rcu_r32(RCU_RST_REQ) & ~module, RCU_RST_REQ);
}
static int ltq_assert_device(struct reset_controller_dev *rcdev,
unsigned long id)
{
u32 val;
if (id < 8)
return -1;
val = ltq_rcu_r32(RCU_RST_REQ);
val |= BIT(id);
ltq_rcu_w32(val, RCU_RST_REQ);
return 0;
}
static int ltq_deassert_device(struct reset_controller_dev *rcdev,
unsigned long id)
{
u32 val;
if (id < 8)
return -1;
val = ltq_rcu_r32(RCU_RST_REQ);
val &= ~BIT(id);
ltq_rcu_w32(val, RCU_RST_REQ);
return 0;
}
static int ltq_reset_device(struct reset_controller_dev *rcdev,
unsigned long id)
{
ltq_assert_device(rcdev, id);
return ltq_deassert_device(rcdev, id);
}
static const struct reset_control_ops reset_ops = {
.reset = ltq_reset_device,
.assert = ltq_assert_device,
.deassert = ltq_deassert_device,
};
static struct reset_controller_dev reset_dev = {
.ops = &reset_ops,
.owner = THIS_MODULE,
.nr_resets = 32,
.of_reset_n_cells = 1,
};
void ltq_rst_init(void)
{
reset_dev.of_node = of_find_compatible_node(NULL, NULL,
"lantiq,xway-reset");
if (!reset_dev.of_node)
pr_err("Failed to find reset controller node");
else
reset_controller_register(&reset_dev);
}
static void ltq_machine_restart(char *command)
{
u32 val = ltq_rcu_r32(RCU_RST_REQ);
if (of_device_is_compatible(ltq_rcu_np, "lantiq,rcu-xrx200"))
val |= RCU_RD_GPHY1_XRX200 | RCU_RD_GPHY0_XRX200;
val |= RCU_RD_SRST;
local_irq_disable();
ltq_rcu_w32(val, RCU_RST_REQ);
unreachable();
}
static void ltq_machine_halt(void)
{
local_irq_disable();
unreachable();
}
static void ltq_machine_power_off(void)
{
local_irq_disable();
unreachable();
}
static void ltq_usb_init(void)
{
/* Power for USB cores 1 & 2 */
ltq_pmu_enable(PMU_AHBM);
ltq_pmu_enable(PMU_USB0);
ltq_pmu_enable(PMU_USB1);
ltq_rcu_w32(ltq_rcu_r32(RCU_CFG1A) | BIT(0), RCU_CFG1A);
ltq_rcu_w32(ltq_rcu_r32(RCU_CFG1B) | BIT(0), RCU_CFG1B);
/* Enable USB PHY power for cores 1 & 2 */
ltq_pmu_enable(PMU_USB0_P);
ltq_pmu_enable(PMU_USB1_P);
/* Configure cores to host mode */
ltq_rcu_w32(ltq_rcu_r32(RCU_USB1CFG) & ~RCU_USBCFG_HDSEL_BIT,
RCU_USB1CFG);
ltq_rcu_w32(ltq_rcu_r32(RCU_USB2CFG) & ~RCU_USBCFG_HDSEL_BIT,
RCU_USB2CFG);
/* Select DMA endianness (Host-endian: big-endian) */
ltq_rcu_w32((ltq_rcu_r32(RCU_USB1CFG) & ~RCU_USBCFG_SLV_END_BIT)
| RCU_USBCFG_HOST_END_BIT, RCU_USB1CFG);
ltq_rcu_w32(ltq_rcu_r32((RCU_USB2CFG) & ~RCU_USBCFG_SLV_END_BIT)
| RCU_USBCFG_HOST_END_BIT, RCU_USB2CFG);
/* Hard reset USB state machines */
ltq_rcu_w32(ltq_rcu_r32(RCU_USBRESET) | USBRESET_BIT, RCU_USBRESET);
udelay(50 * 1000);
ltq_rcu_w32(ltq_rcu_r32(RCU_USBRESET) & ~USBRESET_BIT, RCU_USBRESET);
/* Soft reset USB state machines */
ltq_rcu_w32(ltq_rcu_r32(RCU_USBRESET2)
| USB1RESET_BIT | USB2RESET_BIT, RCU_USBRESET2);
udelay(50 * 1000);
ltq_rcu_w32(ltq_rcu_r32(RCU_USBRESET2)
& ~(USB1RESET_BIT | USB2RESET_BIT), RCU_USBRESET2);
}
static int __init mips_reboot_setup(void)
{
struct resource res;
ltq_rcu_np = of_find_compatible_node(NULL, NULL, "lantiq,rcu-xway");
if (!ltq_rcu_np)
ltq_rcu_np = of_find_compatible_node(NULL, NULL,
"lantiq,rcu-xrx200");
/* check if all the reset register range is available */
if (!ltq_rcu_np)
panic("Failed to load reset resources from devicetree");
if (of_address_to_resource(ltq_rcu_np, 0, &res))
panic("Failed to get rcu memory range");
if (!request_mem_region(res.start, resource_size(&res), res.name))
pr_err("Failed to request rcu memory");
ltq_rcu_membase = ioremap_nocache(res.start, resource_size(&res));
if (!ltq_rcu_membase)
panic("Failed to remap core memory");
if (of_machine_is_compatible("lantiq,ar9") ||
of_machine_is_compatible("lantiq,vr9"))
ltq_usb_init();
if (of_machine_is_compatible("lantiq,vr9"))
ltq_rcu_w32(ltq_rcu_r32(RCU_AHB_ENDIAN) | RCU_VR9_BE_AHB1S,
RCU_AHB_ENDIAN);
_machine_restart = ltq_machine_restart;
_machine_halt = ltq_machine_halt;
pm_power_off = ltq_machine_power_off;
return 0;
}
arch_initcall(mips_reboot_setup);
| gpl-2.0 |
ajs-sun/linux | drivers/net/wireless/rtlwifi/rtl8723be/sw.c | 292 | 13247 | /******************************************************************************
*
* Copyright(c) 2009-2014 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.
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#include "../wifi.h"
#include "../core.h"
#include "../pci.h"
#include "reg.h"
#include "def.h"
#include "phy.h"
#include "../rtl8723com/phy_common.h"
#include "dm.h"
#include "../rtl8723com/dm_common.h"
#include "hw.h"
#include "fw.h"
#include "../rtl8723com/fw_common.h"
#include "sw.h"
#include "trx.h"
#include "led.h"
#include "table.h"
#include "../btcoexist/rtl_btc.h"
#include <linux/vmalloc.h>
#include <linux/module.h>
static void rtl8723be_init_aspm_vars(struct ieee80211_hw *hw)
{
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
/*close ASPM for AMD defaultly */
rtlpci->const_amdpci_aspm = 0;
/* ASPM PS mode.
* 0 - Disable ASPM,
* 1 - Enable ASPM without Clock Req,
* 2 - Enable ASPM with Clock Req,
* 3 - Alwyas Enable ASPM with Clock Req,
* 4 - Always Enable ASPM without Clock Req.
* set defult to RTL8192CE:3 RTL8192E:2
*/
rtlpci->const_pci_aspm = 3;
/*Setting for PCI-E device */
rtlpci->const_devicepci_aspm_setting = 0x03;
/*Setting for PCI-E bridge */
rtlpci->const_hostpci_aspm_setting = 0x02;
/* In Hw/Sw Radio Off situation.
* 0 - Default,
* 1 - From ASPM setting without low Mac Pwr,
* 2 - From ASPM setting with low Mac Pwr,
* 3 - Bus D3
* set default to RTL8192CE:0 RTL8192SE:2
*/
rtlpci->const_hwsw_rfoff_d3 = 0;
/* This setting works for those device with
* backdoor ASPM setting such as EPHY setting.
* 0 - Not support ASPM,
* 1 - Support ASPM,
* 2 - According to chipset.
*/
rtlpci->const_support_pciaspm = 1;
}
int rtl8723be_init_sw_vars(struct ieee80211_hw *hw)
{
int err = 0;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
rtl8723be_bt_reg_init(hw);
rtlpci->msi_support = rtlpriv->cfg->mod_params->msi_support;
rtlpriv->btcoexist.btc_ops = rtl_btc_get_ops_pointer();
rtlpriv->dm.dm_initialgain_enable = 1;
rtlpriv->dm.dm_flag = 0;
rtlpriv->dm.disable_framebursting = 0;
rtlpriv->dm.thermalvalue = 0;
rtlpci->transmit_config = CFENDFORM | BIT(15) | BIT(24) | BIT(25);
rtlpriv->phy.lck_inprogress = false;
mac->ht_enable = true;
/* compatible 5G band 88ce just 2.4G band & smsp */
rtlpriv->rtlhal.current_bandtype = BAND_ON_2_4G;
rtlpriv->rtlhal.bandset = BAND_ON_2_4G;
rtlpriv->rtlhal.macphymode = SINGLEMAC_SINGLEPHY;
rtlpci->receive_config = (RCR_APPFCS |
RCR_APP_MIC |
RCR_APP_ICV |
RCR_APP_PHYST_RXFF |
RCR_HTC_LOC_CTRL |
RCR_AMF |
RCR_ACF |
RCR_ADF |
RCR_AICV |
RCR_AB |
RCR_AM |
RCR_APM |
0);
rtlpci->irq_mask[0] = (u32) (IMR_PSTIMEOUT |
IMR_HSISR_IND_ON_INT |
IMR_C2HCMD |
IMR_HIGHDOK |
IMR_MGNTDOK |
IMR_BKDOK |
IMR_BEDOK |
IMR_VIDOK |
IMR_VODOK |
IMR_RDU |
IMR_ROK |
0);
rtlpci->irq_mask[1] = (u32)(IMR_RXFOVW | 0);
rtlpci->sys_irq_mask = (u32)(HSIMR_PDN_INT_EN |
HSIMR_RON_INT_EN |
0);
/* for debug level */
rtlpriv->dbg.global_debuglevel = rtlpriv->cfg->mod_params->debug;
/* for LPS & IPS */
rtlpriv->psc.inactiveps = rtlpriv->cfg->mod_params->inactiveps;
rtlpriv->psc.swctrl_lps = rtlpriv->cfg->mod_params->swctrl_lps;
rtlpriv->psc.fwctrl_lps = rtlpriv->cfg->mod_params->fwctrl_lps;
rtlpci->msi_support = rtlpriv->cfg->mod_params->msi_support;
if (rtlpriv->cfg->mod_params->disable_watchdog)
pr_info("watchdog disabled\n");
rtlpriv->psc.reg_fwctrl_lps = 3;
rtlpriv->psc.reg_max_lps_awakeintvl = 5;
/* for ASPM, you can close aspm through
* set const_support_pciaspm = 0
*/
rtl8723be_init_aspm_vars(hw);
if (rtlpriv->psc.reg_fwctrl_lps == 1)
rtlpriv->psc.fwctrl_psmode = FW_PS_MIN_MODE;
else if (rtlpriv->psc.reg_fwctrl_lps == 2)
rtlpriv->psc.fwctrl_psmode = FW_PS_MAX_MODE;
else if (rtlpriv->psc.reg_fwctrl_lps == 3)
rtlpriv->psc.fwctrl_psmode = FW_PS_DTIM_MODE;
/*low power: Disable 32k */
rtlpriv->psc.low_power_enable = false;
rtlpriv->rtlhal.earlymode_enable = false;
/* for firmware buf */
rtlpriv->rtlhal.pfirmware = vzalloc(0x8000);
if (!rtlpriv->rtlhal.pfirmware) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Can't alloc buffer for fw.\n");
return 1;
}
rtlpriv->max_fw_size = 0x8000;
pr_info("Using firmware %s\n", rtlpriv->cfg->fw_name);
err = request_firmware_nowait(THIS_MODULE, 1, rtlpriv->cfg->fw_name,
rtlpriv->io.dev, GFP_KERNEL, hw,
rtl_fw_cb);
if (err) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Failed to request firmware!\n");
return 1;
}
return 0;
}
void rtl8723be_deinit_sw_vars(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
if (rtlpriv->rtlhal.pfirmware) {
vfree(rtlpriv->rtlhal.pfirmware);
rtlpriv->rtlhal.pfirmware = NULL;
}
}
/* get bt coexist status */
bool rtl8723be_get_btc_status(void)
{
return true;
}
static bool is_fw_header(struct rtl8723e_firmware_header *hdr)
{
return (hdr->signature & 0xfff0) == 0x5300;
}
static struct rtl_hal_ops rtl8723be_hal_ops = {
.init_sw_vars = rtl8723be_init_sw_vars,
.deinit_sw_vars = rtl8723be_deinit_sw_vars,
.read_eeprom_info = rtl8723be_read_eeprom_info,
.interrupt_recognized = rtl8723be_interrupt_recognized,
.hw_init = rtl8723be_hw_init,
.hw_disable = rtl8723be_card_disable,
.hw_suspend = rtl8723be_suspend,
.hw_resume = rtl8723be_resume,
.enable_interrupt = rtl8723be_enable_interrupt,
.disable_interrupt = rtl8723be_disable_interrupt,
.set_network_type = rtl8723be_set_network_type,
.set_chk_bssid = rtl8723be_set_check_bssid,
.set_qos = rtl8723be_set_qos,
.set_bcn_reg = rtl8723be_set_beacon_related_registers,
.set_bcn_intv = rtl8723be_set_beacon_interval,
.update_interrupt_mask = rtl8723be_update_interrupt_mask,
.get_hw_reg = rtl8723be_get_hw_reg,
.set_hw_reg = rtl8723be_set_hw_reg,
.update_rate_tbl = rtl8723be_update_hal_rate_tbl,
.fill_tx_desc = rtl8723be_tx_fill_desc,
.fill_tx_cmddesc = rtl8723be_tx_fill_cmddesc,
.query_rx_desc = rtl8723be_rx_query_desc,
.set_channel_access = rtl8723be_update_channel_access_setting,
.radio_onoff_checking = rtl8723be_gpio_radio_on_off_checking,
.set_bw_mode = rtl8723be_phy_set_bw_mode,
.switch_channel = rtl8723be_phy_sw_chnl,
.dm_watchdog = rtl8723be_dm_watchdog,
.scan_operation_backup = rtl8723be_phy_scan_operation_backup,
.set_rf_power_state = rtl8723be_phy_set_rf_power_state,
.led_control = rtl8723be_led_control,
.set_desc = rtl8723be_set_desc,
.get_desc = rtl8723be_get_desc,
.is_tx_desc_closed = rtl8723be_is_tx_desc_closed,
.tx_polling = rtl8723be_tx_polling,
.enable_hw_sec = rtl8723be_enable_hw_security_config,
.set_key = rtl8723be_set_key,
.init_sw_leds = rtl8723be_init_sw_leds,
.get_bbreg = rtl8723_phy_query_bb_reg,
.set_bbreg = rtl8723_phy_set_bb_reg,
.get_rfreg = rtl8723be_phy_query_rf_reg,
.set_rfreg = rtl8723be_phy_set_rf_reg,
.fill_h2c_cmd = rtl8723be_fill_h2c_cmd,
.get_btc_status = rtl8723be_get_btc_status,
.rx_command_packet = rtl8723be_rx_command_packet,
.is_fw_header = is_fw_header,
};
static struct rtl_mod_params rtl8723be_mod_params = {
.sw_crypto = false,
.inactiveps = true,
.swctrl_lps = false,
.fwctrl_lps = true,
};
static struct rtl_hal_cfg rtl8723be_hal_cfg = {
.bar_id = 2,
.write_readback = true,
.name = "rtl8723be_pci",
.fw_name = "rtlwifi/rtl8723befw.bin",
.ops = &rtl8723be_hal_ops,
.mod_params = &rtl8723be_mod_params,
.maps[SYS_ISO_CTRL] = REG_SYS_ISO_CTRL,
.maps[SYS_FUNC_EN] = REG_SYS_FUNC_EN,
.maps[SYS_CLK] = REG_SYS_CLKR,
.maps[MAC_RCR_AM] = AM,
.maps[MAC_RCR_AB] = AB,
.maps[MAC_RCR_ACRC32] = ACRC32,
.maps[MAC_RCR_ACF] = ACF,
.maps[MAC_RCR_AAP] = AAP,
.maps[MAC_HIMR] = REG_HIMR,
.maps[MAC_HIMRE] = REG_HIMRE,
.maps[MAC_HSISR] = REG_HSISR,
.maps[EFUSE_ACCESS] = REG_EFUSE_ACCESS,
.maps[EFUSE_TEST] = REG_EFUSE_TEST,
.maps[EFUSE_CTRL] = REG_EFUSE_CTRL,
.maps[EFUSE_CLK] = 0,
.maps[EFUSE_CLK_CTRL] = REG_EFUSE_CTRL,
.maps[EFUSE_PWC_EV12V] = PWC_EV12V,
.maps[EFUSE_FEN_ELDR] = FEN_ELDR,
.maps[EFUSE_LOADER_CLK_EN] = LOADER_CLK_EN,
.maps[EFUSE_ANA8M] = ANA8M,
.maps[EFUSE_HWSET_MAX_SIZE] = HWSET_MAX_SIZE,
.maps[EFUSE_MAX_SECTION_MAP] = EFUSE_MAX_SECTION,
.maps[EFUSE_REAL_CONTENT_SIZE] = EFUSE_REAL_CONTENT_LEN,
.maps[EFUSE_OOB_PROTECT_BYTES_LEN] = EFUSE_OOB_PROTECT_BYTES,
.maps[RWCAM] = REG_CAMCMD,
.maps[WCAMI] = REG_CAMWRITE,
.maps[RCAMO] = REG_CAMREAD,
.maps[CAMDBG] = REG_CAMDBG,
.maps[SECR] = REG_SECCFG,
.maps[SEC_CAM_NONE] = CAM_NONE,
.maps[SEC_CAM_WEP40] = CAM_WEP40,
.maps[SEC_CAM_TKIP] = CAM_TKIP,
.maps[SEC_CAM_AES] = CAM_AES,
.maps[SEC_CAM_WEP104] = CAM_WEP104,
.maps[RTL_IMR_BCNDMAINT6] = IMR_BCNDMAINT6,
.maps[RTL_IMR_BCNDMAINT5] = IMR_BCNDMAINT5,
.maps[RTL_IMR_BCNDMAINT4] = IMR_BCNDMAINT4,
.maps[RTL_IMR_BCNDMAINT3] = IMR_BCNDMAINT3,
.maps[RTL_IMR_BCNDMAINT2] = IMR_BCNDMAINT2,
.maps[RTL_IMR_BCNDMAINT1] = IMR_BCNDMAINT1,
/* .maps[RTL_IMR_BCNDOK8] = IMR_BCNDOK8, */ /*need check*/
.maps[RTL_IMR_BCNDOK7] = IMR_BCNDOK7,
.maps[RTL_IMR_BCNDOK6] = IMR_BCNDOK6,
.maps[RTL_IMR_BCNDOK5] = IMR_BCNDOK5,
.maps[RTL_IMR_BCNDOK4] = IMR_BCNDOK4,
.maps[RTL_IMR_BCNDOK3] = IMR_BCNDOK3,
.maps[RTL_IMR_BCNDOK2] = IMR_BCNDOK2,
.maps[RTL_IMR_BCNDOK1] = IMR_BCNDOK1,
/* .maps[RTL_IMR_TIMEOUT2] = IMR_TIMEOUT2,*/
/* .maps[RTL_IMR_TIMEOUT1] = IMR_TIMEOUT1,*/
.maps[RTL_IMR_TXFOVW] = IMR_TXFOVW,
.maps[RTL_IMR_PSTIMEOUT] = IMR_PSTIMEOUT,
.maps[RTL_IMR_BCNINT] = IMR_BCNDMAINT0,
.maps[RTL_IMR_RXFOVW] = IMR_RXFOVW,
.maps[RTL_IMR_RDU] = IMR_RDU,
.maps[RTL_IMR_ATIMEND] = IMR_ATIMEND,
.maps[RTL_IMR_BDOK] = IMR_BCNDOK0,
.maps[RTL_IMR_MGNTDOK] = IMR_MGNTDOK,
.maps[RTL_IMR_TBDER] = IMR_TBDER,
.maps[RTL_IMR_HIGHDOK] = IMR_HIGHDOK,
.maps[RTL_IMR_TBDOK] = IMR_TBDOK,
.maps[RTL_IMR_BKDOK] = IMR_BKDOK,
.maps[RTL_IMR_BEDOK] = IMR_BEDOK,
.maps[RTL_IMR_VIDOK] = IMR_VIDOK,
.maps[RTL_IMR_VODOK] = IMR_VODOK,
.maps[RTL_IMR_ROK] = IMR_ROK,
.maps[RTL_IMR_HSISR_IND] = IMR_HSISR_IND_ON_INT,
.maps[RTL_IBSS_INT_MASKS] = (IMR_BCNDMAINT0 | IMR_TBDOK | IMR_TBDER),
.maps[RTL_RC_CCK_RATE1M] = DESC92C_RATE1M,
.maps[RTL_RC_CCK_RATE2M] = DESC92C_RATE2M,
.maps[RTL_RC_CCK_RATE5_5M] = DESC92C_RATE5_5M,
.maps[RTL_RC_CCK_RATE11M] = DESC92C_RATE11M,
.maps[RTL_RC_OFDM_RATE6M] = DESC92C_RATE6M,
.maps[RTL_RC_OFDM_RATE9M] = DESC92C_RATE9M,
.maps[RTL_RC_OFDM_RATE12M] = DESC92C_RATE12M,
.maps[RTL_RC_OFDM_RATE18M] = DESC92C_RATE18M,
.maps[RTL_RC_OFDM_RATE24M] = DESC92C_RATE24M,
.maps[RTL_RC_OFDM_RATE36M] = DESC92C_RATE36M,
.maps[RTL_RC_OFDM_RATE48M] = DESC92C_RATE48M,
.maps[RTL_RC_OFDM_RATE54M] = DESC92C_RATE54M,
.maps[RTL_RC_HT_RATEMCS7] = DESC92C_RATEMCS7,
.maps[RTL_RC_HT_RATEMCS15] = DESC92C_RATEMCS15,
};
static struct pci_device_id rtl8723be_pci_ids[] = {
{RTL_PCI_DEVICE(PCI_VENDOR_ID_REALTEK, 0xB723, rtl8723be_hal_cfg)},
{},
};
MODULE_DEVICE_TABLE(pci, rtl8723be_pci_ids);
MODULE_AUTHOR("PageHe <page_he@realsil.com.cn>");
MODULE_AUTHOR("Realtek WlanFAE <wlanfae@realtek.com>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Realtek 8723BE 802.11n PCI wireless");
MODULE_FIRMWARE("rtlwifi/rtl8723befw.bin");
module_param_named(swenc, rtl8723be_mod_params.sw_crypto, bool, 0444);
module_param_named(debug, rtl8723be_mod_params.debug, int, 0444);
module_param_named(ips, rtl8723be_mod_params.inactiveps, bool, 0444);
module_param_named(swlps, rtl8723be_mod_params.swctrl_lps, bool, 0444);
module_param_named(fwlps, rtl8723be_mod_params.fwctrl_lps, bool, 0444);
module_param_named(disable_watchdog, rtl8723be_mod_params.disable_watchdog,
bool, 0444);
MODULE_PARM_DESC(swenc, "using hardware crypto (default 0 [hardware])\n");
MODULE_PARM_DESC(ips, "using no link power save (default 1 is open)\n");
MODULE_PARM_DESC(fwlps, "using linked fw control power save (default 1 is open)\n");
MODULE_PARM_DESC(msi, "Set to 1 to use MSI interrupts mode (default 0)\n");
MODULE_PARM_DESC(debug, "Set debug level (0-5) (default 0)");
MODULE_PARM_DESC(disable_watchdog, "Set to 1 to disable the watchdog (default 0)\n");
static SIMPLE_DEV_PM_OPS(rtlwifi_pm_ops, rtl_pci_suspend, rtl_pci_resume);
static struct pci_driver rtl8723be_driver = {
.name = KBUILD_MODNAME,
.id_table = rtl8723be_pci_ids,
.probe = rtl_pci_probe,
.remove = rtl_pci_disconnect,
.driver.pm = &rtlwifi_pm_ops,
};
module_pci_driver(rtl8723be_driver);
| gpl-2.0 |
widz4rd/WIDzard_Kernel_E250_KK | sound/soc/codecs/ymu831/mcdebuglog.c | 292 | 43816 | /****************************************************************************
*
* Copyright(c) 2012 Yamaha Corporation. All rights reserved.
*
* Module : mcdebuglog.c
*
* Description : MC Driver debug log
*
* Version : 1.0.0 2012.12.13
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
****************************************************************************/
#include "mcdebuglog.h"
#include "mcresctrl.h"
#if MCDRV_DEBUG_LEVEL
#include "mcdefs.h"
#include "mcdevprof.h"
#include "mcservice.h"
#include "mcmachdep.h"
#define CHAR char
static CHAR gsbLogString[8192];
static CHAR gsbLFCode[] = "\n";
static const CHAR gsbCmdName[][20] = {
"init",
"term",
"read_reg",
"write_reg",
"get_clocksw",
"set_clocksw",
"get_path",
"set_path",
"get_volume",
"set_volume",
"get_digitalio",
"set_digitalio",
"get_digitalio_path",
"set_digitalio_path",
"get_swap",
"set_swap",
"set_dsp",
"get_dsp",
"get_dsp_data",
"set_dsp_data",
"register_dsp_cb",
"get_dsp_transition",
"irq",
"get_hsdet",
"set_hsdet",
"config_gp",
"mask_gp",
"getset_gp"
};
static void OutputRegDump(void);
static void GetRegDump(CHAR *psbLogString,
UINT8 bSlaveAddr,
UINT8 bADRAddr,
UINT8 bWINDOWAddr,
UINT8 bRegType);
static void MakeInitInfoLog(const struct MCDRV_INIT_INFO *pvPrm1);
static void MakeRegInfoLog(const struct MCDRV_REG_INFO *pvPrm1);
static void MakeClockSwInfoLog(const struct MCDRV_CLOCKSW_INFO *pvPrm1);
static void MakePathInfoLog(const struct MCDRV_PATH_INFO *pvPrm1);
static void MakeVolInfoLog(const struct MCDRV_VOL_INFO *pvPrm1);
static void MakeDIOInfoLog(const struct MCDRV_DIO_INFO *pvPrm1);
static void MakeDIOPathInfoLog(const struct MCDRV_DIOPATH_INFO *pvPrm1);
static void MakeSwapInfoLog(const struct MCDRV_SWAP_INFO *pvPrm1);
static void MakeDspLog(const UINT8 *pvPrm1, UINT32 dPrm);
static void MakeDspPrmLog(const struct MCDRV_DSP_PARAM *pvPrm1,
const void *pvPrm2,
UINT32 dPrm);
static void MakeHSDETInfoLog(const struct MCDRV_HSDET_INFO *pvPrm1);
static void MakeGPModeLog(const struct MCDRV_GP_MODE *pvPrm1);
static void MakeGPMaskLog(const UINT8 *pvPrm1);
static void MakeGetSetGPLog(const UINT8 *pvPrm1);
/****************************************************************************
* McDebugLog_CmdIn
*
* Description:
* Output Function entrance log.
* Arguments:
* dCmd Command ID
* pvPrm1 pointer to parameter
* pvPrm2 pointer to parameter
* dPrm parameter
* Return:
* none
*
****************************************************************************/
void McDebugLog_CmdIn(
UINT32 dCmd,
const void *pvPrm1,
const void *pvPrm2,
UINT32 dPrm
)
{
CHAR sbStr[80];
UINT8 bLevel = MCDRV_DEBUG_LEVEL;
if (dCmd >= sizeof(gsbCmdName)/sizeof(gsbCmdName[0])) {
;
return;
}
strcpy(gsbLogString, gsbCmdName[dCmd]);
strcat(gsbLogString, " In");
if (bLevel < 2) {
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
return;
}
switch (dCmd) {
case MCDRV_INIT:
MakeInitInfoLog((struct MCDRV_INIT_INFO *)pvPrm1);
break;
case MCDRV_READ_REG:
case MCDRV_WRITE_REG:
MakeRegInfoLog((struct MCDRV_REG_INFO *)pvPrm1);
break;
case MCDRV_SET_CLOCKSW:
MakeClockSwInfoLog((struct MCDRV_CLOCKSW_INFO *)pvPrm1);
break;
case MCDRV_SET_PATH:
MakePathInfoLog((struct MCDRV_PATH_INFO *)pvPrm1);
break;
case MCDRV_SET_VOLUME:
MakeVolInfoLog((struct MCDRV_VOL_INFO *)pvPrm1);
break;
case MCDRV_SET_DIGITALIO:
MakeDIOInfoLog((struct MCDRV_DIO_INFO *)pvPrm1);
sprintf(sbStr, " dPrm=%08lX", dPrm);
strcat(gsbLogString, sbStr);
break;
case MCDRV_SET_DIGITALIO_PATH:
MakeDIOPathInfoLog((struct MCDRV_DIOPATH_INFO *)pvPrm1);
sprintf(sbStr, " dPrm=%08lX", dPrm);
strcat(gsbLogString, sbStr);
break;
case MCDRV_SET_SWAP:
MakeSwapInfoLog((struct MCDRV_SWAP_INFO *)pvPrm1);
sprintf(sbStr, " dPrm=%08lX", dPrm);
strcat(gsbLogString, sbStr);
break;
case MCDRV_SET_DSP:
MakeDspLog((UINT8 *)pvPrm1, dPrm);
break;
case MCDRV_GET_DSP:
sprintf(sbStr, " dType=%08lX",
((struct MCDRV_DSP_PARAM *)pvPrm1)->dType);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " dInfo=%08lX",
((struct MCDRV_DSP_PARAM *)pvPrm1)->dInfo);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " pvPrm2=%p", pvPrm2);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " dPrm=%08lX", dPrm);
strcat(gsbLogString, sbStr);
break;
case MCDRV_GET_DSP_DATA:
sprintf(sbStr, " pvPrm1=%p", pvPrm2);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " dPrm=%08lX", dPrm);
strcat(gsbLogString, sbStr);
break;
case MCDRV_SET_DSP_DATA:
MakeDspLog((UINT8 *)pvPrm1, dPrm);
sprintf(sbStr, " dPrm=%08lX", dPrm);
strcat(gsbLogString, sbStr);
break;
case MCDRV_GET_DSP_TRANSITION:
sprintf(sbStr, " dPrm=%08lX", dPrm);
strcat(gsbLogString, sbStr);
break;
case MCDRV_REGISTER_DSP_CB:
sprintf(sbStr, " dPrm=%p", pvPrm1);
strcat(gsbLogString, sbStr);
break;
case MCDRV_SET_HSDET:
MakeHSDETInfoLog((struct MCDRV_HSDET_INFO *)pvPrm1);
sprintf(sbStr, " dPrm=%08lX", dPrm);
strcat(gsbLogString, sbStr);
break;
case MCDRV_CONFIG_GP:
MakeGPModeLog((struct MCDRV_GP_MODE *)pvPrm1);
break;
case MCDRV_MASK_GP:
MakeGPMaskLog((UINT8 *)pvPrm1);
sprintf(sbStr, " dPrm=%08lX", dPrm);
strcat(gsbLogString, sbStr);
break;
case MCDRV_GETSET_GP:
MakeGetSetGPLog((UINT8 *)pvPrm1);
sprintf(sbStr, " dPrm=%08lX", dPrm);
strcat(gsbLogString, sbStr);
break;
default:
break;
}
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
}
/****************************************************************************
* McDebugLog_CmdOut
*
* Description:
* Output Function exit log.
* Arguments:
* dCmd Command ID
* psdRet retrun value
* pvPrm1 pointer to parameter
* pvPrm2 pointer to parameter
* dPrm parameter
* Return:
* none
*
****************************************************************************/
void McDebugLog_CmdOut(
UINT32 dCmd,
const SINT32 *psdRet,
const void *pvPrm1,
const void *pvPrm2,
UINT32 dPrm
)
{
CHAR sbStr[80];
UINT8 bLevel = MCDRV_DEBUG_LEVEL;
if (dCmd >= sizeof(gsbCmdName)/sizeof(gsbCmdName[0])) {
;
return;
}
strcpy(gsbLogString, gsbCmdName[dCmd]);
strcat(gsbLogString, " Out");
if (psdRet != NULL) {
sprintf(sbStr, " ret=%ld", *psdRet);
strcat(gsbLogString, sbStr);
}
if (bLevel < 2) {
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
return;
}
switch (dCmd) {
case MCDRV_READ_REG:
MakeRegInfoLog((struct MCDRV_REG_INFO *)pvPrm1);
break;
case MCDRV_GET_CLOCKSW:
MakeClockSwInfoLog((struct MCDRV_CLOCKSW_INFO *)pvPrm1);
break;
case MCDRV_GET_PATH:
MakePathInfoLog((struct MCDRV_PATH_INFO *)pvPrm1);
break;
case MCDRV_GET_VOLUME:
MakeVolInfoLog((struct MCDRV_VOL_INFO *)pvPrm1);
break;
case MCDRV_GET_DIGITALIO:
MakeDIOInfoLog((struct MCDRV_DIO_INFO *)pvPrm1);
break;
case MCDRV_GET_DIGITALIO_PATH:
MakeDIOPathInfoLog((struct MCDRV_DIOPATH_INFO *)pvPrm1);
break;
case MCDRV_GET_SWAP:
MakeSwapInfoLog((struct MCDRV_SWAP_INFO *)pvPrm1);
break;
case MCDRV_GET_DSP:
MakeDspPrmLog((struct MCDRV_DSP_PARAM *)pvPrm1, pvPrm2, dPrm);
break;
case MCDRV_GET_DSP_DATA:
MakeDspLog((UINT8 *)pvPrm1, dPrm);
break;
case MCDRV_GET_HSDET:
MakeHSDETInfoLog((struct MCDRV_HSDET_INFO *)pvPrm1);
break;
case MCDRV_GETSET_GP:
MakeGetSetGPLog((UINT8 *)pvPrm1);
break;
default:
break;
}
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
if (bLevel < 3) {
;
return;
}
OutputRegDump();
}
/****************************************************************************
* McDebugLog_FuncIn
*
* Description:
* Output Function entrance log.
* Arguments:
* pbFuncName function name
* Return:
* none
*
****************************************************************************/
void McDebugLog_FuncIn(
void *pvFuncName
)
{
strcpy(gsbLogString, (CHAR *)pvFuncName);
strcat(gsbLogString, " In");
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
}
/****************************************************************************
* McDebugLog_FuncOut
*
* Description:
* Output Function exit log.
* Arguments:
* pbFuncName function name
* psdRet retrun value
* Return:
* none
*
****************************************************************************/
void McDebugLog_FuncOut(
void *pvFuncName,
const SINT32 *psdRet
)
{
CHAR sbStr[80];
strcpy(gsbLogString, (CHAR *)pvFuncName);
strcat(gsbLogString, " Out");
if (psdRet != NULL) {
sprintf(sbStr, " ret=%ld", *psdRet);
strcat(gsbLogString, sbStr);
}
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
}
/****************************************************************************
* OutputRegDump
*
* Description:
* Output Register dump.
* Arguments:
* none
* Return:
* none
*
****************************************************************************/
static void OutputRegDump
(
void
)
{
UINT16 i;
CHAR sbStr[10];
UINT8 bSlaveAddr_dig, bSlaveAddr_ana;
struct MCDRV_REG_INFO sRegInfo;
bSlaveAddr_dig = McDevProf_GetSlaveAddr(eMCDRV_SLAVE_ADDR_DIG);
bSlaveAddr_ana = McDevProf_GetSlaveAddr(eMCDRV_SLAVE_ADDR_ANA);
/* IF_REG */
sRegInfo.bRegType = MCDRV_REGTYPE_IF;
strcpy(gsbLogString, "IF_REG:");
for (i = 0; i < 256UL; i++) {
sRegInfo.bAddress = (UINT8)i;
if ((McResCtrl_GetRegAccess(&sRegInfo)
& eMCDRV_CAN_READ) != 0) {
sprintf(sbStr, "[%d]=%02X",
i, McSrv_ReadReg(bSlaveAddr_dig, i));
strcat(gsbLogString, sbStr);
if (i < 255UL) {
;
strcat(gsbLogString, " ");
}
}
}
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
/* A_REG */
strcpy(gsbLogString, "A_REG:");
GetRegDump(gsbLogString, bSlaveAddr_dig,
MCI_A_REG_A, MCI_A_REG_D, MCDRV_REGTYPE_A);
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
/* MA_REG */
strcpy(gsbLogString, "MA_REG:");
GetRegDump(gsbLogString, bSlaveAddr_dig,
MCI_MA_REG_A, MCI_MA_REG_D, MCDRV_REGTYPE_MA);
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
/* MB_REG */
strcpy(gsbLogString, "MB_REG:");
GetRegDump(gsbLogString, bSlaveAddr_dig,
MCI_MB_REG_A, MCI_MB_REG_D, MCDRV_REGTYPE_MB);
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
/* B_REG */
strcpy(gsbLogString, "B_REG:");
GetRegDump(gsbLogString, bSlaveAddr_dig,
MCI_B_REG_A, MCI_B_REG_D, MCDRV_REGTYPE_B);
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
/* E_REG */
strcpy(gsbLogString, "E_REG:");
GetRegDump(gsbLogString, bSlaveAddr_dig,
MCI_E_REG_A, MCI_E_REG_D, MCDRV_REGTYPE_E);
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
/* C_REG */
strcpy(gsbLogString, "C_REG:");
GetRegDump(gsbLogString, bSlaveAddr_dig,
MCI_C_REG_A, MCI_C_REG_D, MCDRV_REGTYPE_C);
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
/* F_REG */
strcpy(gsbLogString, "F_REG:");
GetRegDump(gsbLogString, bSlaveAddr_dig,
MCI_F_REG_A, MCI_F_REG_D, MCDRV_REGTYPE_F);
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
/* ANA_REG */
strcpy(gsbLogString, "ANA_REG:");
GetRegDump(gsbLogString, bSlaveAddr_ana,
MCI_ANA_REG_A, MCI_ANA_REG_D, MCDRV_REGTYPE_ANA);
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
/* CD_REG */
strcpy(gsbLogString, "CD_REG:");
GetRegDump(gsbLogString, bSlaveAddr_ana,
MCI_CD_REG_A, MCI_CD_REG_D, MCDRV_REGTYPE_CD);
strcat(gsbLogString, gsbLFCode);
machdep_DebugPrint((UINT8 *)(void *)gsbLogString);
}
/****************************************************************************
* GetRegDump
*
* Description:
* Get Register dump string.
* Arguments:
* psbLogString string buffer
* bSlaveAddr Slave address
* bADRAddr ADR address
* bWINDOWAddr WINDOW address
* bRegType register type
* Return:
* none
*
****************************************************************************/
static void GetRegDump
(
CHAR *psbLogString,
UINT8 bSlaveAddr,
UINT8 bADRAddr,
UINT8 bWINDOWAddr,
UINT8 bRegType
)
{
UINT16 i;
CHAR sbStr[10];
UINT8 abData[2];
struct MCDRV_REG_INFO sRegInfo;
abData[0] = bADRAddr<<1;
sRegInfo.bRegType = bRegType;
for (i = 0; i < 256UL; i++) {
sRegInfo.bAddress = (UINT8)i;
if ((McResCtrl_GetRegAccess(&sRegInfo)
& eMCDRV_CAN_READ) != 0) {
abData[1] = (UINT8)i;
McSrv_WriteReg(bSlaveAddr, abData, 2);
sprintf(sbStr, "[%d]=%02X",
i, McSrv_ReadReg(bSlaveAddr, bWINDOWAddr));
strcat(psbLogString, sbStr);
if (i < 255UL) {
;
strcat(psbLogString, " ");
}
}
}
}
/****************************************************************************
* MakeInitInfoLog
*
* Description:
* Make Init Parameter log.
* Arguments:
* pvPrm1 pointer to parameter
* Return:
* none
*
****************************************************************************/
static void MakeInitInfoLog
(
const struct MCDRV_INIT_INFO *pvPrm1
)
{
CHAR sbStr[80];
int i;
if (pvPrm1 == NULL) {
strcat(gsbLogString, " param=NULL");
return;
}
sprintf(sbStr, " bCkSel=%02X", pvPrm1->bCkSel);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bCkInput=%02X", pvPrm1->bCkInput);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bPllModeA=%02X", pvPrm1->bPllModeA);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bPllPrevDivA=%02X", pvPrm1->bPllPrevDivA);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " wPllFbDivA=%04X", pvPrm1->wPllFbDivA);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " wPllFracA=%04X", pvPrm1->wPllFracA);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bPllFreqA=%02X", pvPrm1->bPllFreqA);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bPllModeB=%02X", pvPrm1->bPllModeB);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bPllPrevDivB=%02X", pvPrm1->bPllPrevDivB);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " wPllFbDivB=%04X", pvPrm1->wPllFbDivB);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " wPllFracB=%04X", pvPrm1->wPllFracB);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bPllFreqB=%02X", pvPrm1->bPllFreqB);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bHsdetClk=%02X", pvPrm1->bHsdetClk);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bDio0SdoHiz=%02X", pvPrm1->bDio0SdoHiz);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bDio1SdoHiz=%02X", pvPrm1->bDio1SdoHiz);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bDio2SdoHiz=%02X", pvPrm1->bDio2SdoHiz);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bDio0ClkHiz=%02X", pvPrm1->bDio0ClkHiz);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bDio1ClkHiz=%02X", pvPrm1->bDio1ClkHiz);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bDio2ClkHiz=%02X", pvPrm1->bDio2ClkHiz);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bDio0PcmHiz=%02X", pvPrm1->bDio0PcmHiz);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bDio1PcmHiz=%02X", pvPrm1->bDio1PcmHiz);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bDio2PcmHiz=%02X", pvPrm1->bDio2PcmHiz);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bPa0Func=%02X", pvPrm1->bPa0Func);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bPa1Func=%02X", pvPrm1->bPa1Func);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bPa2Func=%02X", pvPrm1->bPa2Func);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bPowerMode=%02X", pvPrm1->bPowerMode);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bMbSel1=%02X", pvPrm1->bMbSel1);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bMbSel2=%02X", pvPrm1->bMbSel2);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bMbSel3=%02X", pvPrm1->bMbSel3);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bMbSel4=%02X", pvPrm1->bMbSel4);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bMbsDisch=%02X", pvPrm1->bMbsDisch);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bNonClip=%02X", pvPrm1->bNonClip);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bLineIn1Dif=%02X", pvPrm1->bLineIn1Dif);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bLineOut1Dif=%02X", pvPrm1->bLineOut1Dif);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bLineOut2Dif=%02X", pvPrm1->bLineOut2Dif);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bMic1Sng=%02X", pvPrm1->bMic1Sng);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bMic2Sng=%02X", pvPrm1->bMic2Sng);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bMic3Sng=%02X", pvPrm1->bMic3Sng);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bMic4Sng=%02X", pvPrm1->bMic4Sng);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bZcLineOut1=%02X", pvPrm1->bZcLineOut1);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bZcLineOut2=%02X", pvPrm1->bZcLineOut2);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bZcRc=%02X", pvPrm1->bZcRc);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bZcSp=%02X", pvPrm1->bZcSp);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bZcHp=%02X", pvPrm1->bZcHp);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bSvolLineOut1=%02X", pvPrm1->bSvolLineOut1);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bSvolLineOut2=%02X", pvPrm1->bSvolLineOut2);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bSvolRc=%02X", pvPrm1->bSvolRc);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bSvolSp=%02X", pvPrm1->bSvolSp);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bSvolHp=%02X", pvPrm1->bSvolHp);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bRcHiz=%02X", pvPrm1->bRcHiz);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bSpHiz=%02X", pvPrm1->bSpHiz);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bHpHiz=%02X", pvPrm1->bHpHiz);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bLineOut1Hiz=%02X", pvPrm1->bLineOut1Hiz);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bLineOut2Hiz=%02X", pvPrm1->bLineOut2Hiz);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bCpMod=%02X", pvPrm1->bCpMod);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bRbSel=%02X", pvPrm1->bRbSel);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bPlugSel=%02X", pvPrm1->bPlugSel);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bGndDet=%02X", pvPrm1->bGndDet);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bPpdRc=%02X", pvPrm1->bPpdRc);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bPpdSp=%02X", pvPrm1->bPpdSp);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " =bPpdHp%02X", pvPrm1->bPpdHp);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bPpdLineOut1=%02X", pvPrm1->bPpdLineOut1);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bPpdLineOut2=%02X", pvPrm1->bPpdLineOut2);
strcat(gsbLogString, sbStr);
for (i = 0; i < 20; i++) {
sprintf(sbStr, " dWaitTime[%02d]=%lu",
i, pvPrm1->sWaitTime.dWaitTime[i]);
strcat(gsbLogString, sbStr);
}
for (i = 0; i < 20; i++) {
sprintf(sbStr, " dPollInterval[%02d]=%lu",
i, pvPrm1->sWaitTime.dPollInterval[i]);
strcat(gsbLogString, sbStr);
}
for (i = 0; i < 20; i++) {
sprintf(sbStr, " dPollTimeOut[%02d]=%lu",
i, pvPrm1->sWaitTime.dPollTimeOut[i]);
strcat(gsbLogString, sbStr);
}
}
/****************************************************************************
* MakeRegInfoLog
*
* Description:
* Make Reg Info Parameter log.
* Arguments:
* pvPrm1 pointer to parameter
* Return:
* none
*
****************************************************************************/
static void MakeRegInfoLog
(
const struct MCDRV_REG_INFO *pvPrm1
)
{
CHAR sbStr[80];
if (pvPrm1 == NULL) {
strcat(gsbLogString, " param=NULL");
return;
}
sprintf(sbStr, " bRegType=%02X", pvPrm1->bRegType);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bAddress=%02X", pvPrm1->bAddress);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " bData=%02X", pvPrm1->bData);
strcat(gsbLogString, sbStr);
}
/****************************************************************************
* MakeClockSwInfoLog
*
* Description:
* Make Clock Switch Info Parameter log.
* Arguments:
* pvPrm1 pointer to parameter
* Return:
* none
*
****************************************************************************/
static void MakeClockSwInfoLog
(
const struct MCDRV_CLOCKSW_INFO *pvPrm1
)
{
CHAR sbStr[80];
if (pvPrm1 == NULL) {
strcat(gsbLogString, " param=NULL");
return;
}
sprintf(sbStr, " bClkSrc=%02X", pvPrm1->bClkSrc);
strcat(gsbLogString, sbStr);
}
/****************************************************************************
* MakePathInfoLog
*
* Description:
* Make Path Info Parameter log.
* Arguments:
* pvPrm1 pointer to parameter
* Return:
* none
*
****************************************************************************/
static void MakePathInfoLog
(
const struct MCDRV_PATH_INFO *pvPrm1
)
{
UINT8 bCh;
CHAR sbStr[80];
if (pvPrm1 == NULL) {
strcat(gsbLogString, " param=NULL");
return;
}
for (bCh = 0; bCh < MUSICOUT_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asMusicOut[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asMusicOut[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < EXTOUT_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asExtOut[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asExtOut[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < HIFIOUT_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asHifiOut[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asHifiOut[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < VBOXMIXIN_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asVboxMixIn[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asVboxMixIn[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < AE_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asAe0[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asAe0[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < AE_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asAe1[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asAe1[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < AE_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asAe2[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asAe2[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < AE_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asAe3[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asAe3[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < DAC0_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asDac0[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asDac0[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < DAC1_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asDac1[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asDac1[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < VOICEOUT_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asVoiceOut[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asVoiceOut[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < VBOXIOIN_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asVboxIoIn[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asVboxIoIn[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < VBOXHOSTIN_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asVboxHostIn[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asVboxHostIn[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < HOSTOUT_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asHostOut[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asHostOut[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < ADIF0_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asAdif0[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asAdif0[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < ADIF1_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asAdif1[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asAdif1[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < ADIF2_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asAdif2[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asAdif2[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < ADC0_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asAdc0[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asAdc0[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < ADC1_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asAdc1[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asAdc1[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < SP_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asSp[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asSp[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < HP_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asHp[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asHp[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < RC_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asRc[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asRc[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < LOUT1_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asLout1[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asLout1[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < LOUT2_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asLout2[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asLout2[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < BIAS_PATH_CHANNELS; bCh++) {
sprintf(sbStr, " asBias[%d].dSrcOnOff=%08lX",
bCh, pvPrm1->asBias[bCh].dSrcOnOff);
strcat(gsbLogString, sbStr);
}
}
/****************************************************************************
* MakeVolInfoLog
*
* Description:
* Make Volume Info Parameter log.
* Arguments:
* pvPrm1 pointer to parameter
* Return:
* none
*
****************************************************************************/
static void MakeVolInfoLog
(
const struct MCDRV_VOL_INFO *pvPrm1
)
{
UINT8 bCh;
CHAR sbStr[80];
if (pvPrm1 == NULL) {
strcat(gsbLogString, " param=NULL");
return;
}
for (bCh = 0; bCh < MUSICIN_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswD_MusicIn[%d]=%04X",
bCh, (UINT16)pvPrm1->aswD_MusicIn[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < EXTIN_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswD_ExtIn[%d]=%04X",
bCh, (UINT16)pvPrm1->aswD_ExtIn[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < VOICEIN_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswD_VoiceIn[%d]=%04X",
bCh, (UINT16)pvPrm1->aswD_VoiceIn[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < REFIN_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswD_RefIn[%d]=%04X",
bCh, (UINT16)pvPrm1->aswD_RefIn[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < ADIF0IN_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswD_Adif0In[%d]=%04X",
bCh, (UINT16)pvPrm1->aswD_Adif0In[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < ADIF1IN_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswD_Adif1In[%d]=%04X",
bCh, (UINT16)pvPrm1->aswD_Adif1In[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < ADIF2IN_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswD_Adif2In[%d]=%04X",
bCh, (UINT16)pvPrm1->aswD_Adif2In[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < MUSICOUT_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswD_MusicOut[%d]=%04X",
bCh, (UINT16)pvPrm1->aswD_MusicOut[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < EXTOUT_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswD_ExtOut[%d]=%04X",
bCh, (UINT16)pvPrm1->aswD_ExtOut[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < VOICEOUT_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswD_VoiceOut[%d]=%04X",
bCh, (UINT16)pvPrm1->aswD_VoiceOut[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < REFOUT_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswD_RefOut[%d]=%04X",
bCh, (UINT16)pvPrm1->aswD_RefOut[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < DAC0OUT_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswD_Dac0Out[%d]=%04X",
bCh, (UINT16)pvPrm1->aswD_Dac0Out[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < DAC1OUT_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswD_Dac1Out[%d]=%04X",
bCh, (UINT16)pvPrm1->aswD_Dac1Out[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < DPATH_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswD_DpathDa[%d]=%04X",
bCh, (UINT16)pvPrm1->aswD_DpathDa[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < DPATH_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswD_DpathAd[%d]=%04X",
bCh, (UINT16)pvPrm1->aswD_DpathAd[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < LINEIN1_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswA_LineIn1[%d]=%04X",
bCh, (UINT16)pvPrm1->aswA_LineIn1[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < MIC1_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswA_Mic1[%d]=%04X",
bCh, (UINT16)pvPrm1->aswA_Mic1[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < MIC2_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswA_Mic2[%d]=%04X",
bCh, (UINT16)pvPrm1->aswA_Mic2[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < MIC3_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswA_Mic3[%d]=%04X",
bCh, (UINT16)pvPrm1->aswA_Mic3[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < MIC4_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswA_Mic4[%d]=%04X",
bCh, (UINT16)pvPrm1->aswA_Mic4[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < HP_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswA_Hp[%d]=%04X",
bCh, (UINT16)pvPrm1->aswA_Hp[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < SP_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswA_Sp[%d]=%04X",
bCh, (UINT16)pvPrm1->aswA_Sp[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < RC_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswA_Rc[%d]=%04X",
bCh, (UINT16)pvPrm1->aswA_Rc[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < LINEOUT1_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswA_LineOut1[%d]=%04X",
bCh, (UINT16)pvPrm1->aswA_LineOut1[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < LINEOUT2_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswA_LineOut2[%d]=%04X",
bCh, (UINT16)pvPrm1->aswA_LineOut2[bCh]);
strcat(gsbLogString, sbStr);
}
for (bCh = 0; bCh < HPDET_VOL_CHANNELS; bCh++) {
sprintf(sbStr, " aswA_HpDet[%d]=%04X",
bCh, (UINT16)pvPrm1->aswA_HpDet[bCh]);
strcat(gsbLogString, sbStr);
}
}
/****************************************************************************
* MakeDIOInfoLog
*
* Description:
* Make Digital I/O Info Parameter log.
* Arguments:
* pvPrm1 pointer to parameter
* Return:
* none
*
****************************************************************************/
static void MakeDIOInfoLog
(
const struct MCDRV_DIO_INFO *pvPrm1
)
{
CHAR sbStr[80];
UINT8 bPort;
if (pvPrm1 == NULL) {
strcat(gsbLogString, " param=NULL");
return;
}
for (bPort = 0; bPort < 4; bPort++) {
sprintf(sbStr, " asPortInfo[%d].sDioCommon.bMasterSlave=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDioCommon.bMasterSlave);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDioCommon.bAutoFs=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDioCommon.bAutoFs);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDioCommon.bFs=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDioCommon.bFs);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDioCommon.bBckFs=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDioCommon.bBckFs);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDioCommon.bInterface=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDioCommon.bInterface);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDioCommon.bBckInvert=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDioCommon.bBckInvert);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDioCommon.bSrcThru=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDioCommon.bSrcThru);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDioCommon.bPcmHizTim=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDioCommon.bPcmHizTim);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDioCommon.bPcmFrame=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDioCommon.bPcmFrame);
strcat(gsbLogString, sbStr);
sprintf(sbStr,
" asPortInfo[%d].sDioCommon.bPcmHighPeriod=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDioCommon.bPcmHighPeriod);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDir.sDaFormat.bBitSel=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDir.sDaFormat.bBitSel);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDir.sDaFormat.bMode=%02X",
bPort, pvPrm1->asPortInfo[bPort].sDir.sDaFormat.bMode);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDir.sPcmFormat.bMono=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDir.sPcmFormat.bMono);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDir.sPcmFormat.bOrder=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDir.sPcmFormat.bOrder);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDir.sPcmFormat.bLaw=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDir.sPcmFormat.bLaw);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDir.sPcmFormat.bBitSel=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDir.sPcmFormat.bBitSel);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDit.bStMode=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDit.bStMode);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDit.bEdge=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDit.bEdge);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDit.sDaFormat.bBitSel=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDit.sDaFormat.bBitSel);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDit.sDaFormat.bMode=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDit.sDaFormat.bMode);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDit.sPcmFormat.bMono=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDit.sPcmFormat.bMono);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDit.sPcmFormat.bOrder=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDit.sPcmFormat.bOrder);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDit.sPcmFormat.bLaw=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDit.sPcmFormat.bLaw);
strcat(gsbLogString, sbStr);
sprintf(sbStr, " asPortInfo[%d].sDit.sPcmFormat.bBitSel=%02X",
bPort,
pvPrm1->asPortInfo[bPort].sDit.sPcmFormat.bBitSel);
strcat(gsbLogString, sbStr);
}
}
/****************************************************************************
* MakeDIOPathInfoLog
*
* Description:
* Make Digital I/O path Info Parameter log.
* Arguments:
* pvPrm1 pointer to parameter
* Return:
* none
*
****************************************************************************/
static void MakeDIOPathInfoLog
(
const struct MCDRV_DIOPATH_INFO *pvPrm1
)
{
CHAR sbStr[80];
UINT8 bPort;
if (pvPrm1 == NULL) {
strcat(gsbLogString, " param=NULL");
return;
}
for (bPort = 0; bPort < 4; bPort++) {
sprintf(sbStr, " abPhysPort[%d]=%02X",
bPort, pvPrm1->abPhysPort[bPort]);
strcat(gsbLogString, sbStr);
}
sprintf(sbStr, " bMusicCh=%02X", pvPrm1->bMusicCh);
strcat(gsbLogString, sbStr);
for (bPort = 0; bPort < 3; bPort++) {
sprintf(sbStr, " abMusicRSlot[%d]=%02X",
bPort, pvPrm1->abMusicRSlot[bPort]);
strcat(gsbLogString, sbStr);
}
for (bPort = 0; bPort < 3; bPort++) {
sprintf(sbStr, " abMusicTSlot[%d]=%02X",
bPort, pvPrm1->abMusicTSlot[bPort]);
strcat(gsbLogString, sbStr);
}
}
/****************************************************************************
* MakeSwapInfoLog
*
* Description:
* Make Swap Info Parameter log.
* Arguments:
* pvPrm1 pointer to parameter
* Return:
* none
*
****************************************************************************/
static void MakeSwapInfoLog
(
const struct MCDRV_SWAP_INFO *pvPrm1
)
{
CHAR sbStr[80];
if (pvPrm1 == NULL) {
strcat(gsbLogString, " param=NULL");
return;
}
sprintf(sbStr, " bAdif0=%02X", pvPrm1->bAdif0);
sprintf(sbStr, " bAdif1=%02X", pvPrm1->bAdif1);
sprintf(sbStr, " bAdif2=%02X", pvPrm1->bAdif2);
sprintf(sbStr, " bDac0=%02X", pvPrm1->bDac0);
sprintf(sbStr, " bDac1=%02X", pvPrm1->bDac1);
sprintf(sbStr, " bMusicIn0=%02X", pvPrm1->bMusicIn0);
sprintf(sbStr, " bMusicIn1=%02X", pvPrm1->bMusicIn1);
sprintf(sbStr, " bMusicIn2=%02X", pvPrm1->bMusicIn2);
sprintf(sbStr, " bExtIn=%02X", pvPrm1->bExtIn);
sprintf(sbStr, " bVoiceIn=%02X", pvPrm1->bVoiceIn);
sprintf(sbStr, " bHifiIn=%02X", pvPrm1->bHifiIn);
sprintf(sbStr, " bMusicOut0=%02X", pvPrm1->bMusicOut0);
sprintf(sbStr, " bMusicOut1=%02X", pvPrm1->bMusicOut1);
sprintf(sbStr, " bMusicOut2=%02X", pvPrm1->bMusicOut2);
sprintf(sbStr, " bExtOut=%02X", pvPrm1->bExtOut);
sprintf(sbStr, " bVoiceOut=%02X", pvPrm1->bVoiceOut);
sprintf(sbStr, " bHifiOut=%02X", pvPrm1->bHifiOut);
strcat(gsbLogString, sbStr);
}
/****************************************************************************
* MakeDspLog
*
* Description:
* Make DSP Parameter log.
* Arguments:
* pvPrm1 pointer to parameter
* Return:
* none
*
****************************************************************************/
static void MakeDspLog(
const UINT8 *pvPrm1,
UINT32 dPrm
)
{
CHAR sbStr[80];
UINT32 i;
if (pvPrm1 == NULL) {
strcat(gsbLogString, " param=NULL");
return;
}
sprintf(sbStr, " param=");
strcat(gsbLogString, sbStr);
for (i = 0; i < dPrm; i++) {
sprintf(sbStr, " %d", pvPrm1[i]);
strcat(gsbLogString, sbStr);
}
}
/****************************************************************************
* MakeDspPrmLog
*
* Description:
* Make DSP Param Parameter log.
* Arguments:
* pvPrm1 pointer to parameter
* Return:
* none
*
****************************************************************************/
static void MakeDspPrmLog
(
const struct MCDRV_DSP_PARAM *pvPrm1,
const void *pvPrm2,
UINT32 dPrm
)
{
CHAR sbStr[80];
UINT32 i;
if (pvPrm1 == NULL) {
strcat(gsbLogString, " pvPrm1=NULL");
return;
}
if (pvPrm2 == NULL) {
strcat(gsbLogString, " pvPrm2=NULL");
return;
}
if ((pvPrm1->dType == MCDRV_DSP_PARAM_CDSP_INPOS)
|| (pvPrm1->dType == MCDRV_DSP_PARAM_CDSP_OUTPOS)
|| (pvPrm1->dType == MCDRV_DSP_PARAM_CDSP_DFIFO_REMAIN)
|| (pvPrm1->dType == MCDRV_DSP_PARAM_CDSP_RFIFO_REMAIN)) {
sprintf(sbStr, " param=%ld", *((UINT32 *)pvPrm2));
strcat(gsbLogString, sbStr);
} else {
sprintf(sbStr, " param=");
strcat(gsbLogString, sbStr);
for (i = 0; i < dPrm; i++) {
sprintf(sbStr, " %d", ((UINT8 *)pvPrm2)[i]);
strcat(gsbLogString, sbStr);
}
}
}
/****************************************************************************
* MakeHSDETInfoLog
*
* Description:
* Make HSDET Info Parameter log.
* Arguments:
* pvPrm1 pointer to parameter
* Return:
* none
*
****************************************************************************/
static void MakeHSDETInfoLog
(
const struct MCDRV_HSDET_INFO *pvPrm1
)
{
CHAR sbStr[80];
if (pvPrm1 == NULL) {
strcat(gsbLogString, " param=NULL");
return;
}
sprintf(sbStr, " bEnPlugDet=%02X", pvPrm1->bEnPlugDet);
sprintf(sbStr, " bEnPlugDetDb=%02X", pvPrm1->bEnPlugDetDb);
sprintf(sbStr, " bEnDlyKeyOff=%02X", pvPrm1->bEnDlyKeyOff);
sprintf(sbStr, " bEnDlyKeyOn=%02X", pvPrm1->bEnDlyKeyOn);
sprintf(sbStr, " bEnMicDet=%02X", pvPrm1->bEnMicDet);
sprintf(sbStr, " bEnKeyOff=%02X", pvPrm1->bEnKeyOff);
sprintf(sbStr, " bEnKeyOn=%02X", pvPrm1->bEnKeyOn);
sprintf(sbStr, " bHsDetDbnc=%02X", pvPrm1->bHsDetDbnc);
sprintf(sbStr, " bKeyOffMtim=%02X", pvPrm1->bKeyOffMtim);
sprintf(sbStr, " bKeyOnMtim=%02X", pvPrm1->bKeyOnMtim);
sprintf(sbStr, " bKey0OffDlyTim=%02X", pvPrm1->bKey0OffDlyTim);
sprintf(sbStr, " bKey1OffDlyTim=%02X", pvPrm1->bKey1OffDlyTim);
sprintf(sbStr, " bKey2OffDlyTim=%02X", pvPrm1->bKey2OffDlyTim);
sprintf(sbStr, " bKey0OnDlyTim=%02X", pvPrm1->bKey0OnDlyTim);
sprintf(sbStr, " bKey1OnDlyTim=%02X", pvPrm1->bKey1OnDlyTim);
sprintf(sbStr, " bKey2OnDlyTim=%02X", pvPrm1->bKey2OnDlyTim);
sprintf(sbStr, " bKey0OnDlyTim2=%02X", pvPrm1->bKey0OnDlyTim2);
sprintf(sbStr, " bKey1OnDlyTim2=%02X", pvPrm1->bKey1OnDlyTim2);
sprintf(sbStr, " bKey2OnDlyTim2=%02X", pvPrm1->bKey2OnDlyTim2);
sprintf(sbStr, " bIrqType=%02X", pvPrm1->bIrqType);
sprintf(sbStr, " bDetInInv=%02X", pvPrm1->bDetInInv);
sprintf(sbStr, " bHsDetMode=%02X", pvPrm1->bHsDetMode);
sprintf(sbStr, " bSperiod=%02X", pvPrm1->bSperiod);
sprintf(sbStr, " bLperiod=%02X", pvPrm1->bLperiod);
sprintf(sbStr, " bDbncNumPlug=%02X", pvPrm1->bDbncNumPlug);
sprintf(sbStr, " bDbncNumMic=%02X", pvPrm1->bDbncNumMic);
sprintf(sbStr, " bDbncNumKey=%02X", pvPrm1->bDbncNumKey);
sprintf(sbStr, " bSgnlPeriod=%02X", pvPrm1->bSgnlPeriod);
sprintf(sbStr, " bSgnlNum=%02X", pvPrm1->bSgnlNum);
sprintf(sbStr, " bSgnlPeak=%02X", pvPrm1->bSgnlPeak);
sprintf(sbStr, " bImpSel=%02X", pvPrm1->bImpSel);
sprintf(sbStr, " bDlyIrqStop=%02X", pvPrm1->bDlyIrqStop);
sprintf(sbStr, " cbfunc=%p", pvPrm1->cbfunc);
strcat(gsbLogString, sbStr);
}
/****************************************************************************
* MakeGPModeLog
*
* Description:
* Make GPIO mode Info Parameter log.
* Arguments:
* pvPrm1 pointer to parameter
* Return:
* none
*
****************************************************************************/
static void MakeGPModeLog
(
const struct MCDRV_GP_MODE *pvPrm1
)
{
CHAR sbStr[80];
UINT8 bPadNo;
if (pvPrm1 == NULL) {
strcat(gsbLogString, " param=NULL");
return;
}
for (bPadNo = 0; bPadNo < 3; bPadNo++) {
sprintf(sbStr, " abGpDdr[%d]=%02X",
bPadNo, pvPrm1->abGpDdr[bPadNo]);
strcat(gsbLogString, sbStr);
}
for (bPadNo = 0; bPadNo < 3; bPadNo++) {
sprintf(sbStr, " abGpHost[%d]=%02X",
bPadNo, pvPrm1->abGpHost[bPadNo]);
strcat(gsbLogString, sbStr);
}
for (bPadNo = 0; bPadNo < 3; bPadNo++) {
sprintf(sbStr, " abGpInvert[%d]=%02X",
bPadNo, pvPrm1->abGpInvert[bPadNo]);
strcat(gsbLogString, sbStr);
}
}
/****************************************************************************
* MakeGPMaskLog
*
* Description:
* Make GPIO Mask Info Parameter log.
* Arguments:
* pvPrm1 pointer to parameter
* Return:
* none
*
****************************************************************************/
static void MakeGPMaskLog
(
const UINT8 *pvPrm1
)
{
CHAR sbStr[80];
if (pvPrm1 == NULL) {
strcat(gsbLogString, " param=NULL");
return;
}
sprintf(sbStr, " mask=%02X", *pvPrm1);
strcat(gsbLogString, sbStr);
}
/****************************************************************************
* MakeGetSetGPLog
*
* Description:
* Make Get/Set GPIO Info Parameter log.
* Arguments:
* pvPrm1 pointer to parameter
* Return:
* none
*
****************************************************************************/
static void MakeGetSetGPLog
(
const UINT8 *pvPrm1
)
{
CHAR sbStr[80];
if (pvPrm1 == NULL) {
strcat(gsbLogString, " param=NULL");
return;
}
sprintf(sbStr, " HiLow=%02X", *pvPrm1);
strcat(gsbLogString, sbStr);
}
#endif /* MCDRV_DEBUG_LEVEL */
| gpl-2.0 |
Klozz/TheXperienceProject_Motorola_Kernel_msm8226_falcon | drivers/hid/hid-lg4ff.c | 1316 | 15134 | /*
* Force feedback support for Logitech Speed Force Wireless
*
* http://wiibrew.org/wiki/Logitech_USB_steering_wheel
*
* Copyright (c) 2010 Simon Wood <simon@mungewell.org>
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/input.h>
#include <linux/usb.h>
#include <linux/hid.h>
#include "usbhid/usbhid.h"
#include "hid-lg.h"
#include "hid-ids.h"
#define DFGT_REV_MAJ 0x13
#define DFGT_REV_MIN 0x22
#define DFP_REV_MAJ 0x11
#define DFP_REV_MIN 0x06
#define FFEX_REV_MAJ 0x21
#define FFEX_REV_MIN 0x00
#define G25_REV_MAJ 0x12
#define G25_REV_MIN 0x22
#define G27_REV_MAJ 0x12
#define G27_REV_MIN 0x38
#define to_hid_device(pdev) container_of(pdev, struct hid_device, dev)
static void hid_lg4ff_set_range_dfp(struct hid_device *hid, u16 range);
static void hid_lg4ff_set_range_g25(struct hid_device *hid, u16 range);
static ssize_t lg4ff_range_show(struct device *dev, struct device_attribute *attr, char *buf);
static ssize_t lg4ff_range_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count);
static DEVICE_ATTR(range, S_IRWXU | S_IRWXG | S_IRWXO, lg4ff_range_show, lg4ff_range_store);
static bool list_inited;
struct lg4ff_device_entry {
char *device_id; /* Use name in respective kobject structure's address as the ID */
__u16 range;
__u16 min_range;
__u16 max_range;
__u8 leds;
struct list_head list;
void (*set_range)(struct hid_device *hid, u16 range);
};
static struct lg4ff_device_entry device_list;
static const signed short lg4ff_wheel_effects[] = {
FF_CONSTANT,
FF_AUTOCENTER,
-1
};
struct lg4ff_wheel {
const __u32 product_id;
const signed short *ff_effects;
const __u16 min_range;
const __u16 max_range;
void (*set_range)(struct hid_device *hid, u16 range);
};
static const struct lg4ff_wheel lg4ff_devices[] = {
{USB_DEVICE_ID_LOGITECH_WHEEL, lg4ff_wheel_effects, 40, 270, NULL},
{USB_DEVICE_ID_LOGITECH_MOMO_WHEEL, lg4ff_wheel_effects, 40, 270, NULL},
{USB_DEVICE_ID_LOGITECH_DFP_WHEEL, lg4ff_wheel_effects, 40, 900, hid_lg4ff_set_range_dfp},
{USB_DEVICE_ID_LOGITECH_G25_WHEEL, lg4ff_wheel_effects, 40, 900, hid_lg4ff_set_range_g25},
{USB_DEVICE_ID_LOGITECH_DFGT_WHEEL, lg4ff_wheel_effects, 40, 900, hid_lg4ff_set_range_g25},
{USB_DEVICE_ID_LOGITECH_G27_WHEEL, lg4ff_wheel_effects, 40, 900, hid_lg4ff_set_range_g25},
{USB_DEVICE_ID_LOGITECH_MOMO_WHEEL2, lg4ff_wheel_effects, 40, 270, NULL},
{USB_DEVICE_ID_LOGITECH_WII_WHEEL, lg4ff_wheel_effects, 40, 270, NULL}
};
struct lg4ff_native_cmd {
const __u8 cmd_num; /* Number of commands to send */
const __u8 cmd[];
};
struct lg4ff_usb_revision {
const __u16 rev_maj;
const __u16 rev_min;
const struct lg4ff_native_cmd *command;
};
static const struct lg4ff_native_cmd native_dfp = {
1,
{0xf8, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00}
};
static const struct lg4ff_native_cmd native_dfgt = {
2,
{0xf8, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1st command */
0xf8, 0x09, 0x03, 0x01, 0x00, 0x00, 0x00} /* 2nd command */
};
static const struct lg4ff_native_cmd native_g25 = {
1,
{0xf8, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00}
};
static const struct lg4ff_native_cmd native_g27 = {
2,
{0xf8, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1st command */
0xf8, 0x09, 0x04, 0x01, 0x00, 0x00, 0x00} /* 2nd command */
};
static const struct lg4ff_usb_revision lg4ff_revs[] = {
{DFGT_REV_MAJ, DFGT_REV_MIN, &native_dfgt}, /* Driving Force GT */
{DFP_REV_MAJ, DFP_REV_MIN, &native_dfp}, /* Driving Force Pro */
{G25_REV_MAJ, G25_REV_MIN, &native_g25}, /* G25 */
{G27_REV_MAJ, G27_REV_MIN, &native_g27}, /* G27 */
};
static int hid_lg4ff_play(struct input_dev *dev, void *data, struct ff_effect *effect)
{
struct hid_device *hid = input_get_drvdata(dev);
struct list_head *report_list = &hid->report_enum[HID_OUTPUT_REPORT].report_list;
struct hid_report *report = list_entry(report_list->next, struct hid_report, list);
int x;
#define CLAMP(x) if (x < 0) x = 0; if (x > 0xff) x = 0xff
switch (effect->type) {
case FF_CONSTANT:
x = effect->u.ramp.start_level + 0x80; /* 0x80 is no force */
CLAMP(x);
report->field[0]->value[0] = 0x11; /* Slot 1 */
report->field[0]->value[1] = 0x08;
report->field[0]->value[2] = x;
report->field[0]->value[3] = 0x80;
report->field[0]->value[4] = 0x00;
report->field[0]->value[5] = 0x00;
report->field[0]->value[6] = 0x00;
usbhid_submit_report(hid, report, USB_DIR_OUT);
break;
}
return 0;
}
/* Sends default autocentering command compatible with
* all wheels except Formula Force EX */
static void hid_lg4ff_set_autocenter_default(struct input_dev *dev, u16 magnitude)
{
struct hid_device *hid = input_get_drvdata(dev);
struct list_head *report_list = &hid->report_enum[HID_OUTPUT_REPORT].report_list;
struct hid_report *report = list_entry(report_list->next, struct hid_report, list);
report->field[0]->value[0] = 0xfe;
report->field[0]->value[1] = 0x0d;
report->field[0]->value[2] = magnitude >> 13;
report->field[0]->value[3] = magnitude >> 13;
report->field[0]->value[4] = magnitude >> 8;
report->field[0]->value[5] = 0x00;
report->field[0]->value[6] = 0x00;
usbhid_submit_report(hid, report, USB_DIR_OUT);
}
/* Sends autocentering command compatible with Formula Force EX */
static void hid_lg4ff_set_autocenter_ffex(struct input_dev *dev, u16 magnitude)
{
struct hid_device *hid = input_get_drvdata(dev);
struct list_head *report_list = &hid->report_enum[HID_OUTPUT_REPORT].report_list;
struct hid_report *report = list_entry(report_list->next, struct hid_report, list);
magnitude = magnitude * 90 / 65535;
report->field[0]->value[0] = 0xfe;
report->field[0]->value[1] = 0x03;
report->field[0]->value[2] = magnitude >> 14;
report->field[0]->value[3] = magnitude >> 14;
report->field[0]->value[4] = magnitude;
report->field[0]->value[5] = 0x00;
report->field[0]->value[6] = 0x00;
usbhid_submit_report(hid, report, USB_DIR_OUT);
}
/* Sends command to set range compatible with G25/G27/Driving Force GT */
static void hid_lg4ff_set_range_g25(struct hid_device *hid, u16 range)
{
struct list_head *report_list = &hid->report_enum[HID_OUTPUT_REPORT].report_list;
struct hid_report *report = list_entry(report_list->next, struct hid_report, list);
dbg_hid("G25/G27/DFGT: setting range to %u\n", range);
report->field[0]->value[0] = 0xf8;
report->field[0]->value[1] = 0x81;
report->field[0]->value[2] = range & 0x00ff;
report->field[0]->value[3] = (range & 0xff00) >> 8;
report->field[0]->value[4] = 0x00;
report->field[0]->value[5] = 0x00;
report->field[0]->value[6] = 0x00;
usbhid_submit_report(hid, report, USB_DIR_OUT);
}
/* Sends commands to set range compatible with Driving Force Pro wheel */
static void hid_lg4ff_set_range_dfp(struct hid_device *hid, __u16 range)
{
struct list_head *report_list = &hid->report_enum[HID_OUTPUT_REPORT].report_list;
struct hid_report *report = list_entry(report_list->next, struct hid_report, list);
int start_left, start_right, full_range;
dbg_hid("Driving Force Pro: setting range to %u\n", range);
/* Prepare "coarse" limit command */
report->field[0]->value[0] = 0xf8;
report->field[0]->value[1] = 0x00; /* Set later */
report->field[0]->value[2] = 0x00;
report->field[0]->value[3] = 0x00;
report->field[0]->value[4] = 0x00;
report->field[0]->value[5] = 0x00;
report->field[0]->value[6] = 0x00;
if (range > 200) {
report->field[0]->value[1] = 0x03;
full_range = 900;
} else {
report->field[0]->value[1] = 0x02;
full_range = 200;
}
usbhid_submit_report(hid, report, USB_DIR_OUT);
/* Prepare "fine" limit command */
report->field[0]->value[0] = 0x81;
report->field[0]->value[1] = 0x0b;
report->field[0]->value[2] = 0x00;
report->field[0]->value[3] = 0x00;
report->field[0]->value[4] = 0x00;
report->field[0]->value[5] = 0x00;
report->field[0]->value[6] = 0x00;
if (range == 200 || range == 900) { /* Do not apply any fine limit */
usbhid_submit_report(hid, report, USB_DIR_OUT);
return;
}
/* Construct fine limit command */
start_left = (((full_range - range + 1) * 2047) / full_range);
start_right = 0xfff - start_left;
report->field[0]->value[2] = start_left >> 4;
report->field[0]->value[3] = start_right >> 4;
report->field[0]->value[4] = 0xff;
report->field[0]->value[5] = (start_right & 0xe) << 4 | (start_left & 0xe);
report->field[0]->value[6] = 0xff;
usbhid_submit_report(hid, report, USB_DIR_OUT);
}
static void hid_lg4ff_switch_native(struct hid_device *hid, const struct lg4ff_native_cmd *cmd)
{
struct list_head *report_list = &hid->report_enum[HID_OUTPUT_REPORT].report_list;
struct hid_report *report = list_entry(report_list->next, struct hid_report, list);
__u8 i, j;
j = 0;
while (j < 7*cmd->cmd_num) {
for (i = 0; i < 7; i++)
report->field[0]->value[i] = cmd->cmd[j++];
usbhid_submit_report(hid, report, USB_DIR_OUT);
}
}
/* Read current range and display it in terminal */
static ssize_t lg4ff_range_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct lg4ff_device_entry *uninitialized_var(entry);
struct list_head *h;
struct hid_device *hid = to_hid_device(dev);
size_t count;
list_for_each(h, &device_list.list) {
entry = list_entry(h, struct lg4ff_device_entry, list);
if (strcmp(entry->device_id, (&hid->dev)->kobj.name) == 0)
break;
}
if (h == &device_list.list) {
dbg_hid("Device not found!");
return 0;
}
count = scnprintf(buf, PAGE_SIZE, "%u\n", entry->range);
return count;
}
/* Set range to user specified value, call appropriate function
* according to the type of the wheel */
static ssize_t lg4ff_range_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
struct lg4ff_device_entry *uninitialized_var(entry);
struct list_head *h;
struct hid_device *hid = to_hid_device(dev);
__u16 range = simple_strtoul(buf, NULL, 10);
list_for_each(h, &device_list.list) {
entry = list_entry(h, struct lg4ff_device_entry, list);
if (strcmp(entry->device_id, (&hid->dev)->kobj.name) == 0)
break;
}
if (h == &device_list.list) {
dbg_hid("Device not found!");
return count;
}
if (range == 0)
range = entry->max_range;
/* Check if the wheel supports range setting
* and that the range is within limits for the wheel */
if (entry->set_range != NULL && range >= entry->min_range && range <= entry->max_range) {
entry->set_range(hid, range);
entry->range = range;
}
return count;
}
int lg4ff_init(struct hid_device *hid)
{
struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list);
struct input_dev *dev = hidinput->input;
struct lg4ff_device_entry *entry;
struct usb_device_descriptor *udesc;
int error, i, j;
__u16 bcdDevice, rev_maj, rev_min;
/* Check that the report looks ok */
if (!hid_validate_values(hid, HID_OUTPUT_REPORT, 0, 0, 7))
return -1;
/* Check what wheel has been connected */
for (i = 0; i < ARRAY_SIZE(lg4ff_devices); i++) {
if (hid->product == lg4ff_devices[i].product_id) {
dbg_hid("Found compatible device, product ID %04X\n", lg4ff_devices[i].product_id);
break;
}
}
if (i == ARRAY_SIZE(lg4ff_devices)) {
hid_err(hid, "Device is not supported by lg4ff driver. If you think it should be, consider reporting a bug to"
"LKML, Simon Wood <simon@mungewell.org> or Michal Maly <madcatxster@gmail.com>\n");
return -1;
}
/* Attempt to switch wheel to native mode when applicable */
udesc = &(hid_to_usb_dev(hid)->descriptor);
if (!udesc) {
hid_err(hid, "NULL USB device descriptor\n");
return -1;
}
bcdDevice = le16_to_cpu(udesc->bcdDevice);
rev_maj = bcdDevice >> 8;
rev_min = bcdDevice & 0xff;
if (lg4ff_devices[i].product_id == USB_DEVICE_ID_LOGITECH_WHEEL) {
dbg_hid("Generic wheel detected, can it do native?\n");
dbg_hid("USB revision: %2x.%02x\n", rev_maj, rev_min);
for (j = 0; j < ARRAY_SIZE(lg4ff_revs); j++) {
if (lg4ff_revs[j].rev_maj == rev_maj && lg4ff_revs[j].rev_min == rev_min) {
hid_lg4ff_switch_native(hid, lg4ff_revs[j].command);
hid_info(hid, "Switched to native mode\n");
}
}
}
/* Set supported force feedback capabilities */
for (j = 0; lg4ff_devices[i].ff_effects[j] >= 0; j++)
set_bit(lg4ff_devices[i].ff_effects[j], dev->ffbit);
error = input_ff_create_memless(dev, NULL, hid_lg4ff_play);
if (error)
return error;
/* Check if autocentering is available and
* set the centering force to zero by default */
if (test_bit(FF_AUTOCENTER, dev->ffbit)) {
if(rev_maj == FFEX_REV_MAJ && rev_min == FFEX_REV_MIN) /* Formula Force EX expects different autocentering command */
dev->ff->set_autocenter = hid_lg4ff_set_autocenter_ffex;
else
dev->ff->set_autocenter = hid_lg4ff_set_autocenter_default;
dev->ff->set_autocenter(dev, 0);
}
/* Initialize device_list if this is the first device to handle by lg4ff */
if (!list_inited) {
INIT_LIST_HEAD(&device_list.list);
list_inited = 1;
}
/* Add the device to device_list */
entry = kzalloc(sizeof(struct lg4ff_device_entry), GFP_KERNEL);
if (!entry) {
hid_err(hid, "Cannot add device, insufficient memory.\n");
return -ENOMEM;
}
entry->device_id = kstrdup((&hid->dev)->kobj.name, GFP_KERNEL);
if (!entry->device_id) {
hid_err(hid, "Cannot set device_id, insufficient memory.\n");
kfree(entry);
return -ENOMEM;
}
entry->min_range = lg4ff_devices[i].min_range;
entry->max_range = lg4ff_devices[i].max_range;
entry->set_range = lg4ff_devices[i].set_range;
list_add(&entry->list, &device_list.list);
/* Create sysfs interface */
error = device_create_file(&hid->dev, &dev_attr_range);
if (error)
return error;
dbg_hid("sysfs interface created\n");
/* Set the maximum range to start with */
entry->range = entry->max_range;
if (entry->set_range != NULL)
entry->set_range(hid, entry->range);
hid_info(hid, "Force feedback for Logitech Speed Force Wireless by Simon Wood <simon@mungewell.org>\n");
return 0;
}
int lg4ff_deinit(struct hid_device *hid)
{
bool found = 0;
struct lg4ff_device_entry *entry;
struct list_head *h, *g;
list_for_each_safe(h, g, &device_list.list) {
entry = list_entry(h, struct lg4ff_device_entry, list);
if (strcmp(entry->device_id, (&hid->dev)->kobj.name) == 0) {
list_del(h);
kfree(entry->device_id);
kfree(entry);
found = 1;
break;
}
}
if (!found) {
dbg_hid("Device entry not found!\n");
return -1;
}
device_remove_file(&hid->dev, &dev_attr_range);
dbg_hid("Device successfully unregistered\n");
return 0;
}
| gpl-2.0 |
Lukas1212/htc7x30-3.0 | sound/usb/misc/ua101.c | 1828 | 38342 | /*
* Edirol UA-101/UA-1000 driver
* Copyright (c) Clemens Ladisch <clemens@ladisch.de>
*
* This driver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2.
*
* This driver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this driver. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/usb/audio.h>
#include <sound/core.h>
#include <sound/initval.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include "../usbaudio.h"
#include "../midi.h"
MODULE_DESCRIPTION("Edirol UA-101/1000 driver");
MODULE_AUTHOR("Clemens Ladisch <clemens@ladisch.de>");
MODULE_LICENSE("GPL v2");
MODULE_SUPPORTED_DEVICE("{{Edirol,UA-101},{Edirol,UA-1000}}");
/*
* Should not be lower than the minimum scheduling delay of the host
* controller. Some Intel controllers need more than one frame; as long as
* that driver doesn't tell us about this, use 1.5 frames just to be sure.
*/
#define MIN_QUEUE_LENGTH 12
/* Somewhat random. */
#define MAX_QUEUE_LENGTH 30
/*
* This magic value optimizes memory usage efficiency for the UA-101's packet
* sizes at all sample rates, taking into account the stupid cache pool sizes
* that usb_alloc_coherent() uses.
*/
#define DEFAULT_QUEUE_LENGTH 21
#define MAX_PACKET_SIZE 672 /* hardware specific */
#define MAX_MEMORY_BUFFERS DIV_ROUND_UP(MAX_QUEUE_LENGTH, \
PAGE_SIZE / MAX_PACKET_SIZE)
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
static unsigned int queue_length = 21;
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "card index");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "enable card");
module_param(queue_length, uint, 0644);
MODULE_PARM_DESC(queue_length, "USB queue length in microframes, "
__stringify(MIN_QUEUE_LENGTH)"-"__stringify(MAX_QUEUE_LENGTH));
enum {
INTF_PLAYBACK,
INTF_CAPTURE,
INTF_MIDI,
INTF_COUNT
};
/* bits in struct ua101::states */
enum {
USB_CAPTURE_RUNNING,
USB_PLAYBACK_RUNNING,
ALSA_CAPTURE_OPEN,
ALSA_PLAYBACK_OPEN,
ALSA_CAPTURE_RUNNING,
ALSA_PLAYBACK_RUNNING,
CAPTURE_URB_COMPLETED,
PLAYBACK_URB_COMPLETED,
DISCONNECTED,
};
struct ua101 {
struct usb_device *dev;
struct snd_card *card;
struct usb_interface *intf[INTF_COUNT];
int card_index;
struct snd_pcm *pcm;
struct list_head midi_list;
u64 format_bit;
unsigned int rate;
unsigned int packets_per_second;
spinlock_t lock;
struct mutex mutex;
unsigned long states;
/* FIFO to synchronize playback rate to capture rate */
unsigned int rate_feedback_start;
unsigned int rate_feedback_count;
u8 rate_feedback[MAX_QUEUE_LENGTH];
struct list_head ready_playback_urbs;
struct tasklet_struct playback_tasklet;
wait_queue_head_t alsa_capture_wait;
wait_queue_head_t rate_feedback_wait;
wait_queue_head_t alsa_playback_wait;
struct ua101_stream {
struct snd_pcm_substream *substream;
unsigned int usb_pipe;
unsigned int channels;
unsigned int frame_bytes;
unsigned int max_packet_bytes;
unsigned int period_pos;
unsigned int buffer_pos;
unsigned int queue_length;
struct ua101_urb {
struct urb urb;
struct usb_iso_packet_descriptor iso_frame_desc[1];
struct list_head ready_list;
} *urbs[MAX_QUEUE_LENGTH];
struct {
unsigned int size;
void *addr;
dma_addr_t dma;
} buffers[MAX_MEMORY_BUFFERS];
} capture, playback;
};
static DEFINE_MUTEX(devices_mutex);
static unsigned int devices_used;
static struct usb_driver ua101_driver;
static void abort_alsa_playback(struct ua101 *ua);
static void abort_alsa_capture(struct ua101 *ua);
static const char *usb_error_string(int err)
{
switch (err) {
case -ENODEV:
return "no device";
case -ENOENT:
return "endpoint not enabled";
case -EPIPE:
return "endpoint stalled";
case -ENOSPC:
return "not enough bandwidth";
case -ESHUTDOWN:
return "device disabled";
case -EHOSTUNREACH:
return "device suspended";
case -EINVAL:
case -EAGAIN:
case -EFBIG:
case -EMSGSIZE:
return "internal error";
default:
return "unknown error";
}
}
static void abort_usb_capture(struct ua101 *ua)
{
if (test_and_clear_bit(USB_CAPTURE_RUNNING, &ua->states)) {
wake_up(&ua->alsa_capture_wait);
wake_up(&ua->rate_feedback_wait);
}
}
static void abort_usb_playback(struct ua101 *ua)
{
if (test_and_clear_bit(USB_PLAYBACK_RUNNING, &ua->states))
wake_up(&ua->alsa_playback_wait);
}
static void playback_urb_complete(struct urb *usb_urb)
{
struct ua101_urb *urb = (struct ua101_urb *)usb_urb;
struct ua101 *ua = urb->urb.context;
unsigned long flags;
if (unlikely(urb->urb.status == -ENOENT || /* unlinked */
urb->urb.status == -ENODEV || /* device removed */
urb->urb.status == -ECONNRESET || /* unlinked */
urb->urb.status == -ESHUTDOWN)) { /* device disabled */
abort_usb_playback(ua);
abort_alsa_playback(ua);
return;
}
if (test_bit(USB_PLAYBACK_RUNNING, &ua->states)) {
/* append URB to FIFO */
spin_lock_irqsave(&ua->lock, flags);
list_add_tail(&urb->ready_list, &ua->ready_playback_urbs);
if (ua->rate_feedback_count > 0)
tasklet_schedule(&ua->playback_tasklet);
ua->playback.substream->runtime->delay -=
urb->urb.iso_frame_desc[0].length /
ua->playback.frame_bytes;
spin_unlock_irqrestore(&ua->lock, flags);
}
}
static void first_playback_urb_complete(struct urb *urb)
{
struct ua101 *ua = urb->context;
urb->complete = playback_urb_complete;
playback_urb_complete(urb);
set_bit(PLAYBACK_URB_COMPLETED, &ua->states);
wake_up(&ua->alsa_playback_wait);
}
/* copy data from the ALSA ring buffer into the URB buffer */
static bool copy_playback_data(struct ua101_stream *stream, struct urb *urb,
unsigned int frames)
{
struct snd_pcm_runtime *runtime;
unsigned int frame_bytes, frames1;
const u8 *source;
runtime = stream->substream->runtime;
frame_bytes = stream->frame_bytes;
source = runtime->dma_area + stream->buffer_pos * frame_bytes;
if (stream->buffer_pos + frames <= runtime->buffer_size) {
memcpy(urb->transfer_buffer, source, frames * frame_bytes);
} else {
/* wrap around at end of ring buffer */
frames1 = runtime->buffer_size - stream->buffer_pos;
memcpy(urb->transfer_buffer, source, frames1 * frame_bytes);
memcpy(urb->transfer_buffer + frames1 * frame_bytes,
runtime->dma_area, (frames - frames1) * frame_bytes);
}
stream->buffer_pos += frames;
if (stream->buffer_pos >= runtime->buffer_size)
stream->buffer_pos -= runtime->buffer_size;
stream->period_pos += frames;
if (stream->period_pos >= runtime->period_size) {
stream->period_pos -= runtime->period_size;
return true;
}
return false;
}
static inline void add_with_wraparound(struct ua101 *ua,
unsigned int *value, unsigned int add)
{
*value += add;
if (*value >= ua->playback.queue_length)
*value -= ua->playback.queue_length;
}
static void playback_tasklet(unsigned long data)
{
struct ua101 *ua = (void *)data;
unsigned long flags;
unsigned int frames;
struct ua101_urb *urb;
bool do_period_elapsed = false;
int err;
if (unlikely(!test_bit(USB_PLAYBACK_RUNNING, &ua->states)))
return;
/*
* Synchronizing the playback rate to the capture rate is done by using
* the same sequence of packet sizes for both streams.
* Submitting a playback URB therefore requires both a ready URB and
* the size of the corresponding capture packet, i.e., both playback
* and capture URBs must have been completed. Since the USB core does
* not guarantee that playback and capture complete callbacks are
* called alternately, we use two FIFOs for packet sizes and read URBs;
* submitting playback URBs is possible as long as both FIFOs are
* nonempty.
*/
spin_lock_irqsave(&ua->lock, flags);
while (ua->rate_feedback_count > 0 &&
!list_empty(&ua->ready_playback_urbs)) {
/* take packet size out of FIFO */
frames = ua->rate_feedback[ua->rate_feedback_start];
add_with_wraparound(ua, &ua->rate_feedback_start, 1);
ua->rate_feedback_count--;
/* take URB out of FIFO */
urb = list_first_entry(&ua->ready_playback_urbs,
struct ua101_urb, ready_list);
list_del(&urb->ready_list);
/* fill packet with data or silence */
urb->urb.iso_frame_desc[0].length =
frames * ua->playback.frame_bytes;
if (test_bit(ALSA_PLAYBACK_RUNNING, &ua->states))
do_period_elapsed |= copy_playback_data(&ua->playback,
&urb->urb,
frames);
else
memset(urb->urb.transfer_buffer, 0,
urb->urb.iso_frame_desc[0].length);
/* and off you go ... */
err = usb_submit_urb(&urb->urb, GFP_ATOMIC);
if (unlikely(err < 0)) {
spin_unlock_irqrestore(&ua->lock, flags);
abort_usb_playback(ua);
abort_alsa_playback(ua);
dev_err(&ua->dev->dev, "USB request error %d: %s\n",
err, usb_error_string(err));
return;
}
ua->playback.substream->runtime->delay += frames;
}
spin_unlock_irqrestore(&ua->lock, flags);
if (do_period_elapsed)
snd_pcm_period_elapsed(ua->playback.substream);
}
/* copy data from the URB buffer into the ALSA ring buffer */
static bool copy_capture_data(struct ua101_stream *stream, struct urb *urb,
unsigned int frames)
{
struct snd_pcm_runtime *runtime;
unsigned int frame_bytes, frames1;
u8 *dest;
runtime = stream->substream->runtime;
frame_bytes = stream->frame_bytes;
dest = runtime->dma_area + stream->buffer_pos * frame_bytes;
if (stream->buffer_pos + frames <= runtime->buffer_size) {
memcpy(dest, urb->transfer_buffer, frames * frame_bytes);
} else {
/* wrap around at end of ring buffer */
frames1 = runtime->buffer_size - stream->buffer_pos;
memcpy(dest, urb->transfer_buffer, frames1 * frame_bytes);
memcpy(runtime->dma_area,
urb->transfer_buffer + frames1 * frame_bytes,
(frames - frames1) * frame_bytes);
}
stream->buffer_pos += frames;
if (stream->buffer_pos >= runtime->buffer_size)
stream->buffer_pos -= runtime->buffer_size;
stream->period_pos += frames;
if (stream->period_pos >= runtime->period_size) {
stream->period_pos -= runtime->period_size;
return true;
}
return false;
}
static void capture_urb_complete(struct urb *urb)
{
struct ua101 *ua = urb->context;
struct ua101_stream *stream = &ua->capture;
unsigned long flags;
unsigned int frames, write_ptr;
bool do_period_elapsed;
int err;
if (unlikely(urb->status == -ENOENT || /* unlinked */
urb->status == -ENODEV || /* device removed */
urb->status == -ECONNRESET || /* unlinked */
urb->status == -ESHUTDOWN)) /* device disabled */
goto stream_stopped;
if (urb->status >= 0 && urb->iso_frame_desc[0].status >= 0)
frames = urb->iso_frame_desc[0].actual_length /
stream->frame_bytes;
else
frames = 0;
spin_lock_irqsave(&ua->lock, flags);
if (frames > 0 && test_bit(ALSA_CAPTURE_RUNNING, &ua->states))
do_period_elapsed = copy_capture_data(stream, urb, frames);
else
do_period_elapsed = false;
if (test_bit(USB_CAPTURE_RUNNING, &ua->states)) {
err = usb_submit_urb(urb, GFP_ATOMIC);
if (unlikely(err < 0)) {
spin_unlock_irqrestore(&ua->lock, flags);
dev_err(&ua->dev->dev, "USB request error %d: %s\n",
err, usb_error_string(err));
goto stream_stopped;
}
/* append packet size to FIFO */
write_ptr = ua->rate_feedback_start;
add_with_wraparound(ua, &write_ptr, ua->rate_feedback_count);
ua->rate_feedback[write_ptr] = frames;
if (ua->rate_feedback_count < ua->playback.queue_length) {
ua->rate_feedback_count++;
if (ua->rate_feedback_count ==
ua->playback.queue_length)
wake_up(&ua->rate_feedback_wait);
} else {
/*
* Ring buffer overflow; this happens when the playback
* stream is not running. Throw away the oldest entry,
* so that the playback stream, when it starts, sees
* the most recent packet sizes.
*/
add_with_wraparound(ua, &ua->rate_feedback_start, 1);
}
if (test_bit(USB_PLAYBACK_RUNNING, &ua->states) &&
!list_empty(&ua->ready_playback_urbs))
tasklet_schedule(&ua->playback_tasklet);
}
spin_unlock_irqrestore(&ua->lock, flags);
if (do_period_elapsed)
snd_pcm_period_elapsed(stream->substream);
return;
stream_stopped:
abort_usb_playback(ua);
abort_usb_capture(ua);
abort_alsa_playback(ua);
abort_alsa_capture(ua);
}
static void first_capture_urb_complete(struct urb *urb)
{
struct ua101 *ua = urb->context;
urb->complete = capture_urb_complete;
capture_urb_complete(urb);
set_bit(CAPTURE_URB_COMPLETED, &ua->states);
wake_up(&ua->alsa_capture_wait);
}
static int submit_stream_urbs(struct ua101 *ua, struct ua101_stream *stream)
{
unsigned int i;
for (i = 0; i < stream->queue_length; ++i) {
int err = usb_submit_urb(&stream->urbs[i]->urb, GFP_KERNEL);
if (err < 0) {
dev_err(&ua->dev->dev, "USB request error %d: %s\n",
err, usb_error_string(err));
return err;
}
}
return 0;
}
static void kill_stream_urbs(struct ua101_stream *stream)
{
unsigned int i;
for (i = 0; i < stream->queue_length; ++i)
if (stream->urbs[i])
usb_kill_urb(&stream->urbs[i]->urb);
}
static int enable_iso_interface(struct ua101 *ua, unsigned int intf_index)
{
struct usb_host_interface *alts;
alts = ua->intf[intf_index]->cur_altsetting;
if (alts->desc.bAlternateSetting != 1) {
int err = usb_set_interface(ua->dev,
alts->desc.bInterfaceNumber, 1);
if (err < 0) {
dev_err(&ua->dev->dev,
"cannot initialize interface; error %d: %s\n",
err, usb_error_string(err));
return err;
}
}
return 0;
}
static void disable_iso_interface(struct ua101 *ua, unsigned int intf_index)
{
struct usb_host_interface *alts;
if (!ua->intf[intf_index])
return;
alts = ua->intf[intf_index]->cur_altsetting;
if (alts->desc.bAlternateSetting != 0) {
int err = usb_set_interface(ua->dev,
alts->desc.bInterfaceNumber, 0);
if (err < 0 && !test_bit(DISCONNECTED, &ua->states))
dev_warn(&ua->dev->dev,
"interface reset failed; error %d: %s\n",
err, usb_error_string(err));
}
}
static void stop_usb_capture(struct ua101 *ua)
{
clear_bit(USB_CAPTURE_RUNNING, &ua->states);
kill_stream_urbs(&ua->capture);
disable_iso_interface(ua, INTF_CAPTURE);
}
static int start_usb_capture(struct ua101 *ua)
{
int err;
if (test_bit(DISCONNECTED, &ua->states))
return -ENODEV;
if (test_bit(USB_CAPTURE_RUNNING, &ua->states))
return 0;
kill_stream_urbs(&ua->capture);
err = enable_iso_interface(ua, INTF_CAPTURE);
if (err < 0)
return err;
clear_bit(CAPTURE_URB_COMPLETED, &ua->states);
ua->capture.urbs[0]->urb.complete = first_capture_urb_complete;
ua->rate_feedback_start = 0;
ua->rate_feedback_count = 0;
set_bit(USB_CAPTURE_RUNNING, &ua->states);
err = submit_stream_urbs(ua, &ua->capture);
if (err < 0)
stop_usb_capture(ua);
return err;
}
static void stop_usb_playback(struct ua101 *ua)
{
clear_bit(USB_PLAYBACK_RUNNING, &ua->states);
kill_stream_urbs(&ua->playback);
tasklet_kill(&ua->playback_tasklet);
disable_iso_interface(ua, INTF_PLAYBACK);
}
static int start_usb_playback(struct ua101 *ua)
{
unsigned int i, frames;
struct urb *urb;
int err = 0;
if (test_bit(DISCONNECTED, &ua->states))
return -ENODEV;
if (test_bit(USB_PLAYBACK_RUNNING, &ua->states))
return 0;
kill_stream_urbs(&ua->playback);
tasklet_kill(&ua->playback_tasklet);
err = enable_iso_interface(ua, INTF_PLAYBACK);
if (err < 0)
return err;
clear_bit(PLAYBACK_URB_COMPLETED, &ua->states);
ua->playback.urbs[0]->urb.complete =
first_playback_urb_complete;
spin_lock_irq(&ua->lock);
INIT_LIST_HEAD(&ua->ready_playback_urbs);
spin_unlock_irq(&ua->lock);
/*
* We submit the initial URBs all at once, so we have to wait for the
* packet size FIFO to be full.
*/
wait_event(ua->rate_feedback_wait,
ua->rate_feedback_count >= ua->playback.queue_length ||
!test_bit(USB_CAPTURE_RUNNING, &ua->states) ||
test_bit(DISCONNECTED, &ua->states));
if (test_bit(DISCONNECTED, &ua->states)) {
stop_usb_playback(ua);
return -ENODEV;
}
if (!test_bit(USB_CAPTURE_RUNNING, &ua->states)) {
stop_usb_playback(ua);
return -EIO;
}
for (i = 0; i < ua->playback.queue_length; ++i) {
/* all initial URBs contain silence */
spin_lock_irq(&ua->lock);
frames = ua->rate_feedback[ua->rate_feedback_start];
add_with_wraparound(ua, &ua->rate_feedback_start, 1);
ua->rate_feedback_count--;
spin_unlock_irq(&ua->lock);
urb = &ua->playback.urbs[i]->urb;
urb->iso_frame_desc[0].length =
frames * ua->playback.frame_bytes;
memset(urb->transfer_buffer, 0,
urb->iso_frame_desc[0].length);
}
set_bit(USB_PLAYBACK_RUNNING, &ua->states);
err = submit_stream_urbs(ua, &ua->playback);
if (err < 0)
stop_usb_playback(ua);
return err;
}
static void abort_alsa_capture(struct ua101 *ua)
{
if (test_bit(ALSA_CAPTURE_RUNNING, &ua->states))
snd_pcm_stop(ua->capture.substream, SNDRV_PCM_STATE_XRUN);
}
static void abort_alsa_playback(struct ua101 *ua)
{
if (test_bit(ALSA_PLAYBACK_RUNNING, &ua->states))
snd_pcm_stop(ua->playback.substream, SNDRV_PCM_STATE_XRUN);
}
static int set_stream_hw(struct ua101 *ua, struct snd_pcm_substream *substream,
unsigned int channels)
{
int err;
substream->runtime->hw.info =
SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_BATCH |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_FIFO_IN_FRAMES;
substream->runtime->hw.formats = ua->format_bit;
substream->runtime->hw.rates = snd_pcm_rate_to_rate_bit(ua->rate);
substream->runtime->hw.rate_min = ua->rate;
substream->runtime->hw.rate_max = ua->rate;
substream->runtime->hw.channels_min = channels;
substream->runtime->hw.channels_max = channels;
substream->runtime->hw.buffer_bytes_max = 45000 * 1024;
substream->runtime->hw.period_bytes_min = 1;
substream->runtime->hw.period_bytes_max = UINT_MAX;
substream->runtime->hw.periods_min = 2;
substream->runtime->hw.periods_max = UINT_MAX;
err = snd_pcm_hw_constraint_minmax(substream->runtime,
SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1500000 / ua->packets_per_second,
8192000);
if (err < 0)
return err;
err = snd_pcm_hw_constraint_msbits(substream->runtime, 0, 32, 24);
return err;
}
static int capture_pcm_open(struct snd_pcm_substream *substream)
{
struct ua101 *ua = substream->private_data;
int err;
ua->capture.substream = substream;
err = set_stream_hw(ua, substream, ua->capture.channels);
if (err < 0)
return err;
substream->runtime->hw.fifo_size =
DIV_ROUND_CLOSEST(ua->rate, ua->packets_per_second);
substream->runtime->delay = substream->runtime->hw.fifo_size;
mutex_lock(&ua->mutex);
err = start_usb_capture(ua);
if (err >= 0)
set_bit(ALSA_CAPTURE_OPEN, &ua->states);
mutex_unlock(&ua->mutex);
return err;
}
static int playback_pcm_open(struct snd_pcm_substream *substream)
{
struct ua101 *ua = substream->private_data;
int err;
ua->playback.substream = substream;
err = set_stream_hw(ua, substream, ua->playback.channels);
if (err < 0)
return err;
substream->runtime->hw.fifo_size =
DIV_ROUND_CLOSEST(ua->rate * ua->playback.queue_length,
ua->packets_per_second);
mutex_lock(&ua->mutex);
err = start_usb_capture(ua);
if (err < 0)
goto error;
err = start_usb_playback(ua);
if (err < 0) {
if (!test_bit(ALSA_CAPTURE_OPEN, &ua->states))
stop_usb_capture(ua);
goto error;
}
set_bit(ALSA_PLAYBACK_OPEN, &ua->states);
error:
mutex_unlock(&ua->mutex);
return err;
}
static int capture_pcm_close(struct snd_pcm_substream *substream)
{
struct ua101 *ua = substream->private_data;
mutex_lock(&ua->mutex);
clear_bit(ALSA_CAPTURE_OPEN, &ua->states);
if (!test_bit(ALSA_PLAYBACK_OPEN, &ua->states))
stop_usb_capture(ua);
mutex_unlock(&ua->mutex);
return 0;
}
static int playback_pcm_close(struct snd_pcm_substream *substream)
{
struct ua101 *ua = substream->private_data;
mutex_lock(&ua->mutex);
stop_usb_playback(ua);
clear_bit(ALSA_PLAYBACK_OPEN, &ua->states);
if (!test_bit(ALSA_CAPTURE_OPEN, &ua->states))
stop_usb_capture(ua);
mutex_unlock(&ua->mutex);
return 0;
}
static int capture_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct ua101 *ua = substream->private_data;
int err;
mutex_lock(&ua->mutex);
err = start_usb_capture(ua);
mutex_unlock(&ua->mutex);
if (err < 0)
return err;
return snd_pcm_lib_alloc_vmalloc_buffer(substream,
params_buffer_bytes(hw_params));
}
static int playback_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct ua101 *ua = substream->private_data;
int err;
mutex_lock(&ua->mutex);
err = start_usb_capture(ua);
if (err >= 0)
err = start_usb_playback(ua);
mutex_unlock(&ua->mutex);
if (err < 0)
return err;
return snd_pcm_lib_alloc_vmalloc_buffer(substream,
params_buffer_bytes(hw_params));
}
static int ua101_pcm_hw_free(struct snd_pcm_substream *substream)
{
return snd_pcm_lib_free_vmalloc_buffer(substream);
}
static int capture_pcm_prepare(struct snd_pcm_substream *substream)
{
struct ua101 *ua = substream->private_data;
int err;
mutex_lock(&ua->mutex);
err = start_usb_capture(ua);
mutex_unlock(&ua->mutex);
if (err < 0)
return err;
/*
* The EHCI driver schedules the first packet of an iso stream at 10 ms
* in the future, i.e., no data is actually captured for that long.
* Take the wait here so that the stream is known to be actually
* running when the start trigger has been called.
*/
wait_event(ua->alsa_capture_wait,
test_bit(CAPTURE_URB_COMPLETED, &ua->states) ||
!test_bit(USB_CAPTURE_RUNNING, &ua->states));
if (test_bit(DISCONNECTED, &ua->states))
return -ENODEV;
if (!test_bit(USB_CAPTURE_RUNNING, &ua->states))
return -EIO;
ua->capture.period_pos = 0;
ua->capture.buffer_pos = 0;
return 0;
}
static int playback_pcm_prepare(struct snd_pcm_substream *substream)
{
struct ua101 *ua = substream->private_data;
int err;
mutex_lock(&ua->mutex);
err = start_usb_capture(ua);
if (err >= 0)
err = start_usb_playback(ua);
mutex_unlock(&ua->mutex);
if (err < 0)
return err;
/* see the comment in capture_pcm_prepare() */
wait_event(ua->alsa_playback_wait,
test_bit(PLAYBACK_URB_COMPLETED, &ua->states) ||
!test_bit(USB_PLAYBACK_RUNNING, &ua->states));
if (test_bit(DISCONNECTED, &ua->states))
return -ENODEV;
if (!test_bit(USB_PLAYBACK_RUNNING, &ua->states))
return -EIO;
substream->runtime->delay = 0;
ua->playback.period_pos = 0;
ua->playback.buffer_pos = 0;
return 0;
}
static int capture_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct ua101 *ua = substream->private_data;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
if (!test_bit(USB_CAPTURE_RUNNING, &ua->states))
return -EIO;
set_bit(ALSA_CAPTURE_RUNNING, &ua->states);
return 0;
case SNDRV_PCM_TRIGGER_STOP:
clear_bit(ALSA_CAPTURE_RUNNING, &ua->states);
return 0;
default:
return -EINVAL;
}
}
static int playback_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct ua101 *ua = substream->private_data;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
if (!test_bit(USB_PLAYBACK_RUNNING, &ua->states))
return -EIO;
set_bit(ALSA_PLAYBACK_RUNNING, &ua->states);
return 0;
case SNDRV_PCM_TRIGGER_STOP:
clear_bit(ALSA_PLAYBACK_RUNNING, &ua->states);
return 0;
default:
return -EINVAL;
}
}
static inline snd_pcm_uframes_t ua101_pcm_pointer(struct ua101 *ua,
struct ua101_stream *stream)
{
unsigned long flags;
unsigned int pos;
spin_lock_irqsave(&ua->lock, flags);
pos = stream->buffer_pos;
spin_unlock_irqrestore(&ua->lock, flags);
return pos;
}
static snd_pcm_uframes_t capture_pcm_pointer(struct snd_pcm_substream *subs)
{
struct ua101 *ua = subs->private_data;
return ua101_pcm_pointer(ua, &ua->capture);
}
static snd_pcm_uframes_t playback_pcm_pointer(struct snd_pcm_substream *subs)
{
struct ua101 *ua = subs->private_data;
return ua101_pcm_pointer(ua, &ua->playback);
}
static struct snd_pcm_ops capture_pcm_ops = {
.open = capture_pcm_open,
.close = capture_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = capture_pcm_hw_params,
.hw_free = ua101_pcm_hw_free,
.prepare = capture_pcm_prepare,
.trigger = capture_pcm_trigger,
.pointer = capture_pcm_pointer,
.page = snd_pcm_lib_get_vmalloc_page,
.mmap = snd_pcm_lib_mmap_vmalloc,
};
static struct snd_pcm_ops playback_pcm_ops = {
.open = playback_pcm_open,
.close = playback_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = playback_pcm_hw_params,
.hw_free = ua101_pcm_hw_free,
.prepare = playback_pcm_prepare,
.trigger = playback_pcm_trigger,
.pointer = playback_pcm_pointer,
.page = snd_pcm_lib_get_vmalloc_page,
.mmap = snd_pcm_lib_mmap_vmalloc,
};
static const struct uac_format_type_i_discrete_descriptor *
find_format_descriptor(struct usb_interface *interface)
{
struct usb_host_interface *alt;
u8 *extra;
int extralen;
if (interface->num_altsetting != 2) {
dev_err(&interface->dev, "invalid num_altsetting\n");
return NULL;
}
alt = &interface->altsetting[0];
if (alt->desc.bNumEndpoints != 0) {
dev_err(&interface->dev, "invalid bNumEndpoints\n");
return NULL;
}
alt = &interface->altsetting[1];
if (alt->desc.bNumEndpoints != 1) {
dev_err(&interface->dev, "invalid bNumEndpoints\n");
return NULL;
}
extra = alt->extra;
extralen = alt->extralen;
while (extralen >= sizeof(struct usb_descriptor_header)) {
struct uac_format_type_i_discrete_descriptor *desc;
desc = (struct uac_format_type_i_discrete_descriptor *)extra;
if (desc->bLength > extralen) {
dev_err(&interface->dev, "descriptor overflow\n");
return NULL;
}
if (desc->bLength == UAC_FORMAT_TYPE_I_DISCRETE_DESC_SIZE(1) &&
desc->bDescriptorType == USB_DT_CS_INTERFACE &&
desc->bDescriptorSubtype == UAC_FORMAT_TYPE) {
if (desc->bFormatType != UAC_FORMAT_TYPE_I_PCM ||
desc->bSamFreqType != 1) {
dev_err(&interface->dev,
"invalid format type\n");
return NULL;
}
return desc;
}
extralen -= desc->bLength;
extra += desc->bLength;
}
dev_err(&interface->dev, "sample format descriptor not found\n");
return NULL;
}
static int detect_usb_format(struct ua101 *ua)
{
const struct uac_format_type_i_discrete_descriptor *fmt_capture;
const struct uac_format_type_i_discrete_descriptor *fmt_playback;
const struct usb_endpoint_descriptor *epd;
unsigned int rate2;
fmt_capture = find_format_descriptor(ua->intf[INTF_CAPTURE]);
fmt_playback = find_format_descriptor(ua->intf[INTF_PLAYBACK]);
if (!fmt_capture || !fmt_playback)
return -ENXIO;
switch (fmt_capture->bSubframeSize) {
case 3:
ua->format_bit = SNDRV_PCM_FMTBIT_S24_3LE;
break;
case 4:
ua->format_bit = SNDRV_PCM_FMTBIT_S32_LE;
break;
default:
dev_err(&ua->dev->dev, "sample width is not 24 or 32 bits\n");
return -ENXIO;
}
if (fmt_capture->bSubframeSize != fmt_playback->bSubframeSize) {
dev_err(&ua->dev->dev,
"playback/capture sample widths do not match\n");
return -ENXIO;
}
if (fmt_capture->bBitResolution != 24 ||
fmt_playback->bBitResolution != 24) {
dev_err(&ua->dev->dev, "sample width is not 24 bits\n");
return -ENXIO;
}
ua->rate = combine_triple(fmt_capture->tSamFreq[0]);
rate2 = combine_triple(fmt_playback->tSamFreq[0]);
if (ua->rate != rate2) {
dev_err(&ua->dev->dev,
"playback/capture rates do not match: %u/%u\n",
rate2, ua->rate);
return -ENXIO;
}
switch (ua->dev->speed) {
case USB_SPEED_FULL:
ua->packets_per_second = 1000;
break;
case USB_SPEED_HIGH:
ua->packets_per_second = 8000;
break;
default:
dev_err(&ua->dev->dev, "unknown device speed\n");
return -ENXIO;
}
ua->capture.channels = fmt_capture->bNrChannels;
ua->playback.channels = fmt_playback->bNrChannels;
ua->capture.frame_bytes =
fmt_capture->bSubframeSize * ua->capture.channels;
ua->playback.frame_bytes =
fmt_playback->bSubframeSize * ua->playback.channels;
epd = &ua->intf[INTF_CAPTURE]->altsetting[1].endpoint[0].desc;
if (!usb_endpoint_is_isoc_in(epd)) {
dev_err(&ua->dev->dev, "invalid capture endpoint\n");
return -ENXIO;
}
ua->capture.usb_pipe = usb_rcvisocpipe(ua->dev, usb_endpoint_num(epd));
ua->capture.max_packet_bytes = le16_to_cpu(epd->wMaxPacketSize);
epd = &ua->intf[INTF_PLAYBACK]->altsetting[1].endpoint[0].desc;
if (!usb_endpoint_is_isoc_out(epd)) {
dev_err(&ua->dev->dev, "invalid playback endpoint\n");
return -ENXIO;
}
ua->playback.usb_pipe = usb_sndisocpipe(ua->dev, usb_endpoint_num(epd));
ua->playback.max_packet_bytes = le16_to_cpu(epd->wMaxPacketSize);
return 0;
}
static int alloc_stream_buffers(struct ua101 *ua, struct ua101_stream *stream)
{
unsigned int remaining_packets, packets, packets_per_page, i;
size_t size;
stream->queue_length = queue_length;
stream->queue_length = max(stream->queue_length,
(unsigned int)MIN_QUEUE_LENGTH);
stream->queue_length = min(stream->queue_length,
(unsigned int)MAX_QUEUE_LENGTH);
/*
* The cache pool sizes used by usb_alloc_coherent() (128, 512, 2048) are
* quite bad when used with the packet sizes of this device (e.g. 280,
* 520, 624). Therefore, we allocate and subdivide entire pages, using
* a smaller buffer only for the last chunk.
*/
remaining_packets = stream->queue_length;
packets_per_page = PAGE_SIZE / stream->max_packet_bytes;
for (i = 0; i < ARRAY_SIZE(stream->buffers); ++i) {
packets = min(remaining_packets, packets_per_page);
size = packets * stream->max_packet_bytes;
stream->buffers[i].addr =
usb_alloc_coherent(ua->dev, size, GFP_KERNEL,
&stream->buffers[i].dma);
if (!stream->buffers[i].addr)
return -ENOMEM;
stream->buffers[i].size = size;
remaining_packets -= packets;
if (!remaining_packets)
break;
}
if (remaining_packets) {
dev_err(&ua->dev->dev, "too many packets\n");
return -ENXIO;
}
return 0;
}
static void free_stream_buffers(struct ua101 *ua, struct ua101_stream *stream)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(stream->buffers); ++i)
usb_free_coherent(ua->dev,
stream->buffers[i].size,
stream->buffers[i].addr,
stream->buffers[i].dma);
}
static int alloc_stream_urbs(struct ua101 *ua, struct ua101_stream *stream,
void (*urb_complete)(struct urb *))
{
unsigned max_packet_size = stream->max_packet_bytes;
struct ua101_urb *urb;
unsigned int b, u = 0;
for (b = 0; b < ARRAY_SIZE(stream->buffers); ++b) {
unsigned int size = stream->buffers[b].size;
u8 *addr = stream->buffers[b].addr;
dma_addr_t dma = stream->buffers[b].dma;
while (size >= max_packet_size) {
if (u >= stream->queue_length)
goto bufsize_error;
urb = kmalloc(sizeof(*urb), GFP_KERNEL);
if (!urb)
return -ENOMEM;
usb_init_urb(&urb->urb);
urb->urb.dev = ua->dev;
urb->urb.pipe = stream->usb_pipe;
urb->urb.transfer_flags = URB_ISO_ASAP |
URB_NO_TRANSFER_DMA_MAP;
urb->urb.transfer_buffer = addr;
urb->urb.transfer_dma = dma;
urb->urb.transfer_buffer_length = max_packet_size;
urb->urb.number_of_packets = 1;
urb->urb.interval = 1;
urb->urb.context = ua;
urb->urb.complete = urb_complete;
urb->urb.iso_frame_desc[0].offset = 0;
urb->urb.iso_frame_desc[0].length = max_packet_size;
stream->urbs[u++] = urb;
size -= max_packet_size;
addr += max_packet_size;
dma += max_packet_size;
}
}
if (u == stream->queue_length)
return 0;
bufsize_error:
dev_err(&ua->dev->dev, "internal buffer size error\n");
return -ENXIO;
}
static void free_stream_urbs(struct ua101_stream *stream)
{
unsigned int i;
for (i = 0; i < stream->queue_length; ++i) {
kfree(stream->urbs[i]);
stream->urbs[i] = NULL;
}
}
static void free_usb_related_resources(struct ua101 *ua,
struct usb_interface *interface)
{
unsigned int i;
struct usb_interface *intf;
mutex_lock(&ua->mutex);
free_stream_urbs(&ua->capture);
free_stream_urbs(&ua->playback);
mutex_unlock(&ua->mutex);
free_stream_buffers(ua, &ua->capture);
free_stream_buffers(ua, &ua->playback);
for (i = 0; i < ARRAY_SIZE(ua->intf); ++i) {
mutex_lock(&ua->mutex);
intf = ua->intf[i];
ua->intf[i] = NULL;
mutex_unlock(&ua->mutex);
if (intf) {
usb_set_intfdata(intf, NULL);
if (intf != interface)
usb_driver_release_interface(&ua101_driver,
intf);
}
}
}
static void ua101_card_free(struct snd_card *card)
{
struct ua101 *ua = card->private_data;
mutex_destroy(&ua->mutex);
}
static int ua101_probe(struct usb_interface *interface,
const struct usb_device_id *usb_id)
{
static const struct snd_usb_midi_endpoint_info midi_ep = {
.out_cables = 0x0001,
.in_cables = 0x0001
};
static const struct snd_usb_audio_quirk midi_quirk = {
.type = QUIRK_MIDI_FIXED_ENDPOINT,
.data = &midi_ep
};
static const int intf_numbers[2][3] = {
{ /* UA-101 */
[INTF_PLAYBACK] = 0,
[INTF_CAPTURE] = 1,
[INTF_MIDI] = 2,
},
{ /* UA-1000 */
[INTF_CAPTURE] = 1,
[INTF_PLAYBACK] = 2,
[INTF_MIDI] = 3,
},
};
struct snd_card *card;
struct ua101 *ua;
unsigned int card_index, i;
int is_ua1000;
const char *name;
char usb_path[32];
int err;
is_ua1000 = usb_id->idProduct == 0x0044;
if (interface->altsetting->desc.bInterfaceNumber !=
intf_numbers[is_ua1000][0])
return -ENODEV;
mutex_lock(&devices_mutex);
for (card_index = 0; card_index < SNDRV_CARDS; ++card_index)
if (enable[card_index] && !(devices_used & (1 << card_index)))
break;
if (card_index >= SNDRV_CARDS) {
mutex_unlock(&devices_mutex);
return -ENOENT;
}
err = snd_card_create(index[card_index], id[card_index], THIS_MODULE,
sizeof(*ua), &card);
if (err < 0) {
mutex_unlock(&devices_mutex);
return err;
}
card->private_free = ua101_card_free;
ua = card->private_data;
ua->dev = interface_to_usbdev(interface);
ua->card = card;
ua->card_index = card_index;
INIT_LIST_HEAD(&ua->midi_list);
spin_lock_init(&ua->lock);
mutex_init(&ua->mutex);
INIT_LIST_HEAD(&ua->ready_playback_urbs);
tasklet_init(&ua->playback_tasklet,
playback_tasklet, (unsigned long)ua);
init_waitqueue_head(&ua->alsa_capture_wait);
init_waitqueue_head(&ua->rate_feedback_wait);
init_waitqueue_head(&ua->alsa_playback_wait);
ua->intf[0] = interface;
for (i = 1; i < ARRAY_SIZE(ua->intf); ++i) {
ua->intf[i] = usb_ifnum_to_if(ua->dev,
intf_numbers[is_ua1000][i]);
if (!ua->intf[i]) {
dev_err(&ua->dev->dev, "interface %u not found\n",
intf_numbers[is_ua1000][i]);
err = -ENXIO;
goto probe_error;
}
err = usb_driver_claim_interface(&ua101_driver,
ua->intf[i], ua);
if (err < 0) {
ua->intf[i] = NULL;
err = -EBUSY;
goto probe_error;
}
}
snd_card_set_dev(card, &interface->dev);
err = detect_usb_format(ua);
if (err < 0)
goto probe_error;
name = usb_id->idProduct == 0x0044 ? "UA-1000" : "UA-101";
strcpy(card->driver, "UA-101");
strcpy(card->shortname, name);
usb_make_path(ua->dev, usb_path, sizeof(usb_path));
snprintf(ua->card->longname, sizeof(ua->card->longname),
"EDIROL %s (serial %s), %u Hz at %s, %s speed", name,
ua->dev->serial ? ua->dev->serial : "?", ua->rate, usb_path,
ua->dev->speed == USB_SPEED_HIGH ? "high" : "full");
err = alloc_stream_buffers(ua, &ua->capture);
if (err < 0)
goto probe_error;
err = alloc_stream_buffers(ua, &ua->playback);
if (err < 0)
goto probe_error;
err = alloc_stream_urbs(ua, &ua->capture, capture_urb_complete);
if (err < 0)
goto probe_error;
err = alloc_stream_urbs(ua, &ua->playback, playback_urb_complete);
if (err < 0)
goto probe_error;
err = snd_pcm_new(card, name, 0, 1, 1, &ua->pcm);
if (err < 0)
goto probe_error;
ua->pcm->private_data = ua;
strcpy(ua->pcm->name, name);
snd_pcm_set_ops(ua->pcm, SNDRV_PCM_STREAM_PLAYBACK, &playback_pcm_ops);
snd_pcm_set_ops(ua->pcm, SNDRV_PCM_STREAM_CAPTURE, &capture_pcm_ops);
err = snd_usbmidi_create(card, ua->intf[INTF_MIDI],
&ua->midi_list, &midi_quirk);
if (err < 0)
goto probe_error;
err = snd_card_register(card);
if (err < 0)
goto probe_error;
usb_set_intfdata(interface, ua);
devices_used |= 1 << card_index;
mutex_unlock(&devices_mutex);
return 0;
probe_error:
free_usb_related_resources(ua, interface);
snd_card_free(card);
mutex_unlock(&devices_mutex);
return err;
}
static void ua101_disconnect(struct usb_interface *interface)
{
struct ua101 *ua = usb_get_intfdata(interface);
struct list_head *midi;
if (!ua)
return;
mutex_lock(&devices_mutex);
set_bit(DISCONNECTED, &ua->states);
wake_up(&ua->rate_feedback_wait);
/* make sure that userspace cannot create new requests */
snd_card_disconnect(ua->card);
/* make sure that there are no pending USB requests */
__list_for_each(midi, &ua->midi_list)
snd_usbmidi_disconnect(midi);
abort_alsa_playback(ua);
abort_alsa_capture(ua);
mutex_lock(&ua->mutex);
stop_usb_playback(ua);
stop_usb_capture(ua);
mutex_unlock(&ua->mutex);
free_usb_related_resources(ua, interface);
devices_used &= ~(1 << ua->card_index);
snd_card_free_when_closed(ua->card);
mutex_unlock(&devices_mutex);
}
static struct usb_device_id ua101_ids[] = {
{ USB_DEVICE(0x0582, 0x0044) }, /* UA-1000 high speed */
{ USB_DEVICE(0x0582, 0x007d) }, /* UA-101 high speed */
{ USB_DEVICE(0x0582, 0x008d) }, /* UA-101 full speed */
{ }
};
MODULE_DEVICE_TABLE(usb, ua101_ids);
static struct usb_driver ua101_driver = {
.name = "snd-ua101",
.id_table = ua101_ids,
.probe = ua101_probe,
.disconnect = ua101_disconnect,
#if 0
.suspend = ua101_suspend,
.resume = ua101_resume,
#endif
};
static int __init alsa_card_ua101_init(void)
{
return usb_register(&ua101_driver);
}
static void __exit alsa_card_ua101_exit(void)
{
usb_deregister(&ua101_driver);
mutex_destroy(&devices_mutex);
}
module_init(alsa_card_ua101_init);
module_exit(alsa_card_ua101_exit);
| gpl-2.0 |
fortunave3gxx/android_kernel_samsung_fortuna-common | arch/arm/mach-orion5x/ts78xx-setup.c | 2340 | 15419 | /*
* arch/arm/mach-orion5x/ts78xx-setup.c
*
* Maintainer: Alexander Clouter <alex@digriz.org.uk>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/sysfs.h>
#include <linux/platform_device.h>
#include <linux/mv643xx_eth.h>
#include <linux/ata_platform.h>
#include <linux/m48t86.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include <linux/timeriomem-rng.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/orion5x.h>
#include "common.h"
#include "mpp.h"
#include "ts78xx-fpga.h"
/*****************************************************************************
* TS-78xx Info
****************************************************************************/
/*
* FPGA - lives where the PCI bus would be at ORION5X_PCI_MEM_PHYS_BASE
*/
#define TS78XX_FPGA_REGS_PHYS_BASE 0xe8000000
#define TS78XX_FPGA_REGS_VIRT_BASE IOMEM(0xff900000)
#define TS78XX_FPGA_REGS_SIZE SZ_1M
static struct ts78xx_fpga_data ts78xx_fpga = {
.id = 0,
.state = 1,
/* .supports = ... - populated by ts78xx_fpga_supports() */
};
/*****************************************************************************
* I/O Address Mapping
****************************************************************************/
static struct map_desc ts78xx_io_desc[] __initdata = {
{
.virtual = (unsigned long)TS78XX_FPGA_REGS_VIRT_BASE,
.pfn = __phys_to_pfn(TS78XX_FPGA_REGS_PHYS_BASE),
.length = TS78XX_FPGA_REGS_SIZE,
.type = MT_DEVICE,
},
};
void __init ts78xx_map_io(void)
{
orion5x_map_io();
iotable_init(ts78xx_io_desc, ARRAY_SIZE(ts78xx_io_desc));
}
/*****************************************************************************
* Ethernet
****************************************************************************/
static struct mv643xx_eth_platform_data ts78xx_eth_data = {
.phy_addr = MV643XX_ETH_PHY_ADDR(0),
};
/*****************************************************************************
* SATA
****************************************************************************/
static struct mv_sata_platform_data ts78xx_sata_data = {
.n_ports = 2,
};
/*****************************************************************************
* RTC M48T86 - nicked^Wborrowed from arch/arm/mach-ep93xx/ts72xx.c
****************************************************************************/
#define TS_RTC_CTRL (TS78XX_FPGA_REGS_VIRT_BASE + 0x808)
#define TS_RTC_DATA (TS78XX_FPGA_REGS_VIRT_BASE + 0x80c)
static unsigned char ts78xx_ts_rtc_readbyte(unsigned long addr)
{
writeb(addr, TS_RTC_CTRL);
return readb(TS_RTC_DATA);
}
static void ts78xx_ts_rtc_writebyte(unsigned char value, unsigned long addr)
{
writeb(addr, TS_RTC_CTRL);
writeb(value, TS_RTC_DATA);
}
static struct m48t86_ops ts78xx_ts_rtc_ops = {
.readbyte = ts78xx_ts_rtc_readbyte,
.writebyte = ts78xx_ts_rtc_writebyte,
};
static struct platform_device ts78xx_ts_rtc_device = {
.name = "rtc-m48t86",
.id = -1,
.dev = {
.platform_data = &ts78xx_ts_rtc_ops,
},
.num_resources = 0,
};
/*
* TS uses some of the user storage space on the RTC chip so see if it is
* present; as it's an optional feature at purchase time and not all boards
* will have it present
*
* I've used the method TS use in their rtc7800.c example for the detection
*
* TODO: track down a guinea pig without an RTC to see if we can work out a
* better RTC detection routine
*/
static int ts78xx_ts_rtc_load(void)
{
int rc;
unsigned char tmp_rtc0, tmp_rtc1;
tmp_rtc0 = ts78xx_ts_rtc_readbyte(126);
tmp_rtc1 = ts78xx_ts_rtc_readbyte(127);
ts78xx_ts_rtc_writebyte(0x00, 126);
ts78xx_ts_rtc_writebyte(0x55, 127);
if (ts78xx_ts_rtc_readbyte(127) == 0x55) {
ts78xx_ts_rtc_writebyte(0xaa, 127);
if (ts78xx_ts_rtc_readbyte(127) == 0xaa
&& ts78xx_ts_rtc_readbyte(126) == 0x00) {
ts78xx_ts_rtc_writebyte(tmp_rtc0, 126);
ts78xx_ts_rtc_writebyte(tmp_rtc1, 127);
if (ts78xx_fpga.supports.ts_rtc.init == 0) {
rc = platform_device_register(&ts78xx_ts_rtc_device);
if (!rc)
ts78xx_fpga.supports.ts_rtc.init = 1;
} else
rc = platform_device_add(&ts78xx_ts_rtc_device);
if (rc)
pr_info("RTC could not be registered: %d\n",
rc);
return rc;
}
}
pr_info("RTC not found\n");
return -ENODEV;
};
static void ts78xx_ts_rtc_unload(void)
{
platform_device_del(&ts78xx_ts_rtc_device);
}
/*****************************************************************************
* NAND Flash
****************************************************************************/
#define TS_NAND_CTRL (TS78XX_FPGA_REGS_VIRT_BASE + 0x800) /* VIRT */
#define TS_NAND_DATA (TS78XX_FPGA_REGS_PHYS_BASE + 0x804) /* PHYS */
/*
* hardware specific access to control-lines
*
* ctrl:
* NAND_NCE: bit 0 -> bit 2
* NAND_CLE: bit 1 -> bit 1
* NAND_ALE: bit 2 -> bit 0
*/
static void ts78xx_ts_nand_cmd_ctrl(struct mtd_info *mtd, int cmd,
unsigned int ctrl)
{
struct nand_chip *this = mtd->priv;
if (ctrl & NAND_CTRL_CHANGE) {
unsigned char bits;
bits = (ctrl & NAND_NCE) << 2;
bits |= ctrl & NAND_CLE;
bits |= (ctrl & NAND_ALE) >> 2;
writeb((readb(TS_NAND_CTRL) & ~0x7) | bits, TS_NAND_CTRL);
}
if (cmd != NAND_CMD_NONE)
writeb(cmd, this->IO_ADDR_W);
}
static int ts78xx_ts_nand_dev_ready(struct mtd_info *mtd)
{
return readb(TS_NAND_CTRL) & 0x20;
}
static void ts78xx_ts_nand_write_buf(struct mtd_info *mtd,
const uint8_t *buf, int len)
{
struct nand_chip *chip = mtd->priv;
void __iomem *io_base = chip->IO_ADDR_W;
unsigned long off = ((unsigned long)buf & 3);
int sz;
if (off) {
sz = min_t(int, 4 - off, len);
writesb(io_base, buf, sz);
buf += sz;
len -= sz;
}
sz = len >> 2;
if (sz) {
u32 *buf32 = (u32 *)buf;
writesl(io_base, buf32, sz);
buf += sz << 2;
len -= sz << 2;
}
if (len)
writesb(io_base, buf, len);
}
static void ts78xx_ts_nand_read_buf(struct mtd_info *mtd,
uint8_t *buf, int len)
{
struct nand_chip *chip = mtd->priv;
void __iomem *io_base = chip->IO_ADDR_R;
unsigned long off = ((unsigned long)buf & 3);
int sz;
if (off) {
sz = min_t(int, 4 - off, len);
readsb(io_base, buf, sz);
buf += sz;
len -= sz;
}
sz = len >> 2;
if (sz) {
u32 *buf32 = (u32 *)buf;
readsl(io_base, buf32, sz);
buf += sz << 2;
len -= sz << 2;
}
if (len)
readsb(io_base, buf, len);
}
static struct mtd_partition ts78xx_ts_nand_parts[] = {
{
.name = "mbr",
.offset = 0,
.size = SZ_128K,
.mask_flags = MTD_WRITEABLE,
}, {
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = SZ_4M,
}, {
.name = "initrd",
.offset = MTDPART_OFS_APPEND,
.size = SZ_4M,
}, {
.name = "rootfs",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
}
};
static struct platform_nand_data ts78xx_ts_nand_data = {
.chip = {
.nr_chips = 1,
.partitions = ts78xx_ts_nand_parts,
.nr_partitions = ARRAY_SIZE(ts78xx_ts_nand_parts),
.chip_delay = 15,
.bbt_options = NAND_BBT_USE_FLASH,
},
.ctrl = {
/*
* The HW ECC offloading functions, used to give about a 9%
* performance increase for 'dd if=/dev/mtdblockX' and 5% for
* nanddump. This all however was changed by git commit
* e6cf5df1838c28bb060ac45b5585e48e71bbc740 so now there is
* no performance advantage to be had so we no longer bother
*/
.cmd_ctrl = ts78xx_ts_nand_cmd_ctrl,
.dev_ready = ts78xx_ts_nand_dev_ready,
.write_buf = ts78xx_ts_nand_write_buf,
.read_buf = ts78xx_ts_nand_read_buf,
},
};
static struct resource ts78xx_ts_nand_resources
= DEFINE_RES_MEM(TS_NAND_DATA, 4);
static struct platform_device ts78xx_ts_nand_device = {
.name = "gen_nand",
.id = -1,
.dev = {
.platform_data = &ts78xx_ts_nand_data,
},
.resource = &ts78xx_ts_nand_resources,
.num_resources = 1,
};
static int ts78xx_ts_nand_load(void)
{
int rc;
if (ts78xx_fpga.supports.ts_nand.init == 0) {
rc = platform_device_register(&ts78xx_ts_nand_device);
if (!rc)
ts78xx_fpga.supports.ts_nand.init = 1;
} else
rc = platform_device_add(&ts78xx_ts_nand_device);
if (rc)
pr_info("NAND could not be registered: %d\n", rc);
return rc;
};
static void ts78xx_ts_nand_unload(void)
{
platform_device_del(&ts78xx_ts_nand_device);
}
/*****************************************************************************
* HW RNG
****************************************************************************/
#define TS_RNG_DATA (TS78XX_FPGA_REGS_PHYS_BASE | 0x044)
static struct resource ts78xx_ts_rng_resource
= DEFINE_RES_MEM(TS_RNG_DATA, 4);
static struct timeriomem_rng_data ts78xx_ts_rng_data = {
.period = 1000000, /* one second */
};
static struct platform_device ts78xx_ts_rng_device = {
.name = "timeriomem_rng",
.id = -1,
.dev = {
.platform_data = &ts78xx_ts_rng_data,
},
.resource = &ts78xx_ts_rng_resource,
.num_resources = 1,
};
static int ts78xx_ts_rng_load(void)
{
int rc;
if (ts78xx_fpga.supports.ts_rng.init == 0) {
rc = platform_device_register(&ts78xx_ts_rng_device);
if (!rc)
ts78xx_fpga.supports.ts_rng.init = 1;
} else
rc = platform_device_add(&ts78xx_ts_rng_device);
if (rc)
pr_info("RNG could not be registered: %d\n", rc);
return rc;
};
static void ts78xx_ts_rng_unload(void)
{
platform_device_del(&ts78xx_ts_rng_device);
}
/*****************************************************************************
* FPGA 'hotplug' support code
****************************************************************************/
static void ts78xx_fpga_devices_zero_init(void)
{
ts78xx_fpga.supports.ts_rtc.init = 0;
ts78xx_fpga.supports.ts_nand.init = 0;
ts78xx_fpga.supports.ts_rng.init = 0;
}
static void ts78xx_fpga_supports(void)
{
/* TODO: put this 'table' into ts78xx-fpga.h */
switch (ts78xx_fpga.id) {
case TS7800_REV_1:
case TS7800_REV_2:
case TS7800_REV_3:
case TS7800_REV_4:
case TS7800_REV_5:
case TS7800_REV_6:
case TS7800_REV_7:
case TS7800_REV_8:
case TS7800_REV_9:
ts78xx_fpga.supports.ts_rtc.present = 1;
ts78xx_fpga.supports.ts_nand.present = 1;
ts78xx_fpga.supports.ts_rng.present = 1;
break;
default:
/* enable devices if magic matches */
switch ((ts78xx_fpga.id >> 8) & 0xffffff) {
case TS7800_FPGA_MAGIC:
pr_warning("unrecognised FPGA revision 0x%.2x\n",
ts78xx_fpga.id & 0xff);
ts78xx_fpga.supports.ts_rtc.present = 1;
ts78xx_fpga.supports.ts_nand.present = 1;
ts78xx_fpga.supports.ts_rng.present = 1;
break;
default:
ts78xx_fpga.supports.ts_rtc.present = 0;
ts78xx_fpga.supports.ts_nand.present = 0;
ts78xx_fpga.supports.ts_rng.present = 0;
}
}
}
static int ts78xx_fpga_load_devices(void)
{
int tmp, ret = 0;
if (ts78xx_fpga.supports.ts_rtc.present == 1) {
tmp = ts78xx_ts_rtc_load();
if (tmp)
ts78xx_fpga.supports.ts_rtc.present = 0;
ret |= tmp;
}
if (ts78xx_fpga.supports.ts_nand.present == 1) {
tmp = ts78xx_ts_nand_load();
if (tmp)
ts78xx_fpga.supports.ts_nand.present = 0;
ret |= tmp;
}
if (ts78xx_fpga.supports.ts_rng.present == 1) {
tmp = ts78xx_ts_rng_load();
if (tmp)
ts78xx_fpga.supports.ts_rng.present = 0;
ret |= tmp;
}
return ret;
}
static int ts78xx_fpga_unload_devices(void)
{
int ret = 0;
if (ts78xx_fpga.supports.ts_rtc.present == 1)
ts78xx_ts_rtc_unload();
if (ts78xx_fpga.supports.ts_nand.present == 1)
ts78xx_ts_nand_unload();
if (ts78xx_fpga.supports.ts_rng.present == 1)
ts78xx_ts_rng_unload();
return ret;
}
static int ts78xx_fpga_load(void)
{
ts78xx_fpga.id = readl(TS78XX_FPGA_REGS_VIRT_BASE);
pr_info("FPGA magic=0x%.6x, rev=0x%.2x\n",
(ts78xx_fpga.id >> 8) & 0xffffff,
ts78xx_fpga.id & 0xff);
ts78xx_fpga_supports();
if (ts78xx_fpga_load_devices()) {
ts78xx_fpga.state = -1;
return -EBUSY;
}
return 0;
};
static int ts78xx_fpga_unload(void)
{
unsigned int fpga_id;
fpga_id = readl(TS78XX_FPGA_REGS_VIRT_BASE);
/*
* There does not seem to be a feasible way to block access to the GPIO
* pins from userspace (/dev/mem). This if clause should hopefully warn
* those foolish enough not to follow 'policy' :)
*
* UrJTAG SVN since r1381 can be used to reprogram the FPGA
*/
if (ts78xx_fpga.id != fpga_id) {
pr_err("FPGA magic/rev mismatch\n"
"TS-78xx FPGA: was 0x%.6x/%.2x but now 0x%.6x/%.2x\n",
(ts78xx_fpga.id >> 8) & 0xffffff, ts78xx_fpga.id & 0xff,
(fpga_id >> 8) & 0xffffff, fpga_id & 0xff);
ts78xx_fpga.state = -1;
return -EBUSY;
}
if (ts78xx_fpga_unload_devices()) {
ts78xx_fpga.state = -1;
return -EBUSY;
}
return 0;
};
static ssize_t ts78xx_fpga_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
if (ts78xx_fpga.state < 0)
return sprintf(buf, "borked\n");
return sprintf(buf, "%s\n", (ts78xx_fpga.state) ? "online" : "offline");
}
static ssize_t ts78xx_fpga_store(struct kobject *kobj,
struct kobj_attribute *attr, const char *buf, size_t n)
{
int value, ret;
if (ts78xx_fpga.state < 0) {
pr_err("FPGA borked, you must powercycle ASAP\n");
return -EBUSY;
}
if (strncmp(buf, "online", sizeof("online") - 1) == 0)
value = 1;
else if (strncmp(buf, "offline", sizeof("offline") - 1) == 0)
value = 0;
else
return -EINVAL;
if (ts78xx_fpga.state == value)
return n;
ret = (ts78xx_fpga.state == 0)
? ts78xx_fpga_load()
: ts78xx_fpga_unload();
if (!(ret < 0))
ts78xx_fpga.state = value;
return n;
}
static struct kobj_attribute ts78xx_fpga_attr =
__ATTR(ts78xx_fpga, 0644, ts78xx_fpga_show, ts78xx_fpga_store);
/*****************************************************************************
* General Setup
****************************************************************************/
static unsigned int ts78xx_mpp_modes[] __initdata = {
MPP0_UNUSED,
MPP1_GPIO, /* JTAG Clock */
MPP2_GPIO, /* JTAG Data In */
MPP3_GPIO, /* Lat ECP2 256 FPGA - PB2B */
MPP4_GPIO, /* JTAG Data Out */
MPP5_GPIO, /* JTAG TMS */
MPP6_GPIO, /* Lat ECP2 256 FPGA - PB31A_CLK4+ */
MPP7_GPIO, /* Lat ECP2 256 FPGA - PB22B */
MPP8_UNUSED,
MPP9_UNUSED,
MPP10_UNUSED,
MPP11_UNUSED,
MPP12_UNUSED,
MPP13_UNUSED,
MPP14_UNUSED,
MPP15_UNUSED,
MPP16_UART,
MPP17_UART,
MPP18_UART,
MPP19_UART,
/*
* MPP[20] PCI Clock Out 1
* MPP[21] PCI Clock Out 0
* MPP[22] Unused
* MPP[23] Unused
* MPP[24] Unused
* MPP[25] Unused
*/
0,
};
static void __init ts78xx_init(void)
{
int ret;
/*
* Setup basic Orion functions. Need to be called early.
*/
orion5x_init();
orion5x_mpp_conf(ts78xx_mpp_modes);
/*
* Configure peripherals.
*/
orion5x_ehci0_init();
orion5x_ehci1_init();
orion5x_eth_init(&ts78xx_eth_data);
orion5x_sata_init(&ts78xx_sata_data);
orion5x_uart0_init();
orion5x_uart1_init();
orion5x_xor_init();
/* FPGA init */
ts78xx_fpga_devices_zero_init();
ret = ts78xx_fpga_load();
ret = sysfs_create_file(firmware_kobj, &ts78xx_fpga_attr.attr);
if (ret)
pr_err("sysfs_create_file failed: %d\n", ret);
}
MACHINE_START(TS78XX, "Technologic Systems TS-78xx SBC")
/* Maintainer: Alexander Clouter <alex@digriz.org.uk> */
.atag_offset = 0x100,
.init_machine = ts78xx_init,
.map_io = ts78xx_map_io,
.init_early = orion5x_init_early,
.init_irq = orion5x_init_irq,
.init_time = orion5x_timer_init,
.restart = orion5x_restart,
MACHINE_END
| gpl-2.0 |
gallagth/keecker_kernel | drivers/char/tpm/tpm_nsc.c | 3620 | 10298 | /*
* Copyright (C) 2004 IBM Corporation
*
* Authors:
* Leendert van Doorn <leendert@watson.ibm.com>
* Dave Safford <safford@watson.ibm.com>
* Reiner Sailer <sailer@watson.ibm.com>
* Kylene Hall <kjhall@us.ibm.com>
*
* Maintained by: <tpmdd-devel@lists.sourceforge.net>
*
* Device driver for TCG/TCPA TPM (trusted platform module).
* Specifications at www.trustedcomputinggroup.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2 of the
* License.
*
*/
#include <linux/platform_device.h>
#include <linux/slab.h>
#include "tpm.h"
/* National definitions */
enum tpm_nsc_addr{
TPM_NSC_IRQ = 0x07,
TPM_NSC_BASE0_HI = 0x60,
TPM_NSC_BASE0_LO = 0x61,
TPM_NSC_BASE1_HI = 0x62,
TPM_NSC_BASE1_LO = 0x63
};
enum tpm_nsc_index {
NSC_LDN_INDEX = 0x07,
NSC_SID_INDEX = 0x20,
NSC_LDC_INDEX = 0x30,
NSC_DIO_INDEX = 0x60,
NSC_CIO_INDEX = 0x62,
NSC_IRQ_INDEX = 0x70,
NSC_ITS_INDEX = 0x71
};
enum tpm_nsc_status_loc {
NSC_STATUS = 0x01,
NSC_COMMAND = 0x01,
NSC_DATA = 0x00
};
/* status bits */
enum tpm_nsc_status {
NSC_STATUS_OBF = 0x01, /* output buffer full */
NSC_STATUS_IBF = 0x02, /* input buffer full */
NSC_STATUS_F0 = 0x04, /* F0 */
NSC_STATUS_A2 = 0x08, /* A2 */
NSC_STATUS_RDY = 0x10, /* ready to receive command */
NSC_STATUS_IBR = 0x20 /* ready to receive data */
};
/* command bits */
enum tpm_nsc_cmd_mode {
NSC_COMMAND_NORMAL = 0x01, /* normal mode */
NSC_COMMAND_EOC = 0x03,
NSC_COMMAND_CANCEL = 0x22
};
/*
* Wait for a certain status to appear
*/
static int wait_for_stat(struct tpm_chip *chip, u8 mask, u8 val, u8 * data)
{
unsigned long stop;
/* status immediately available check */
*data = inb(chip->vendor.base + NSC_STATUS);
if ((*data & mask) == val)
return 0;
/* wait for status */
stop = jiffies + 10 * HZ;
do {
msleep(TPM_TIMEOUT);
*data = inb(chip->vendor.base + 1);
if ((*data & mask) == val)
return 0;
}
while (time_before(jiffies, stop));
return -EBUSY;
}
static int nsc_wait_for_ready(struct tpm_chip *chip)
{
int status;
unsigned long stop;
/* status immediately available check */
status = inb(chip->vendor.base + NSC_STATUS);
if (status & NSC_STATUS_OBF)
status = inb(chip->vendor.base + NSC_DATA);
if (status & NSC_STATUS_RDY)
return 0;
/* wait for status */
stop = jiffies + 100;
do {
msleep(TPM_TIMEOUT);
status = inb(chip->vendor.base + NSC_STATUS);
if (status & NSC_STATUS_OBF)
status = inb(chip->vendor.base + NSC_DATA);
if (status & NSC_STATUS_RDY)
return 0;
}
while (time_before(jiffies, stop));
dev_info(chip->dev, "wait for ready failed\n");
return -EBUSY;
}
static int tpm_nsc_recv(struct tpm_chip *chip, u8 * buf, size_t count)
{
u8 *buffer = buf;
u8 data, *p;
u32 size;
__be32 *native_size;
if (count < 6)
return -EIO;
if (wait_for_stat(chip, NSC_STATUS_F0, NSC_STATUS_F0, &data) < 0) {
dev_err(chip->dev, "F0 timeout\n");
return -EIO;
}
if ((data =
inb(chip->vendor.base + NSC_DATA)) != NSC_COMMAND_NORMAL) {
dev_err(chip->dev, "not in normal mode (0x%x)\n",
data);
return -EIO;
}
/* read the whole packet */
for (p = buffer; p < &buffer[count]; p++) {
if (wait_for_stat
(chip, NSC_STATUS_OBF, NSC_STATUS_OBF, &data) < 0) {
dev_err(chip->dev,
"OBF timeout (while reading data)\n");
return -EIO;
}
if (data & NSC_STATUS_F0)
break;
*p = inb(chip->vendor.base + NSC_DATA);
}
if ((data & NSC_STATUS_F0) == 0 &&
(wait_for_stat(chip, NSC_STATUS_F0, NSC_STATUS_F0, &data) < 0)) {
dev_err(chip->dev, "F0 not set\n");
return -EIO;
}
if ((data = inb(chip->vendor.base + NSC_DATA)) != NSC_COMMAND_EOC) {
dev_err(chip->dev,
"expected end of command(0x%x)\n", data);
return -EIO;
}
native_size = (__force __be32 *) (buf + 2);
size = be32_to_cpu(*native_size);
if (count < size)
return -EIO;
return size;
}
static int tpm_nsc_send(struct tpm_chip *chip, u8 * buf, size_t count)
{
u8 data;
int i;
/*
* If we hit the chip with back to back commands it locks up
* and never set IBF. Hitting it with this "hammer" seems to
* fix it. Not sure why this is needed, we followed the flow
* chart in the manual to the letter.
*/
outb(NSC_COMMAND_CANCEL, chip->vendor.base + NSC_COMMAND);
if (nsc_wait_for_ready(chip) != 0)
return -EIO;
if (wait_for_stat(chip, NSC_STATUS_IBF, 0, &data) < 0) {
dev_err(chip->dev, "IBF timeout\n");
return -EIO;
}
outb(NSC_COMMAND_NORMAL, chip->vendor.base + NSC_COMMAND);
if (wait_for_stat(chip, NSC_STATUS_IBR, NSC_STATUS_IBR, &data) < 0) {
dev_err(chip->dev, "IBR timeout\n");
return -EIO;
}
for (i = 0; i < count; i++) {
if (wait_for_stat(chip, NSC_STATUS_IBF, 0, &data) < 0) {
dev_err(chip->dev,
"IBF timeout (while writing data)\n");
return -EIO;
}
outb(buf[i], chip->vendor.base + NSC_DATA);
}
if (wait_for_stat(chip, NSC_STATUS_IBF, 0, &data) < 0) {
dev_err(chip->dev, "IBF timeout\n");
return -EIO;
}
outb(NSC_COMMAND_EOC, chip->vendor.base + NSC_COMMAND);
return count;
}
static void tpm_nsc_cancel(struct tpm_chip *chip)
{
outb(NSC_COMMAND_CANCEL, chip->vendor.base + NSC_COMMAND);
}
static u8 tpm_nsc_status(struct tpm_chip *chip)
{
return inb(chip->vendor.base + NSC_STATUS);
}
static const struct file_operations nsc_ops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.open = tpm_open,
.read = tpm_read,
.write = tpm_write,
.release = tpm_release,
};
static DEVICE_ATTR(pubek, S_IRUGO, tpm_show_pubek, NULL);
static DEVICE_ATTR(pcrs, S_IRUGO, tpm_show_pcrs, NULL);
static DEVICE_ATTR(caps, S_IRUGO, tpm_show_caps, NULL);
static DEVICE_ATTR(cancel, S_IWUSR|S_IWGRP, NULL, tpm_store_cancel);
static struct attribute * nsc_attrs[] = {
&dev_attr_pubek.attr,
&dev_attr_pcrs.attr,
&dev_attr_caps.attr,
&dev_attr_cancel.attr,
NULL,
};
static struct attribute_group nsc_attr_grp = { .attrs = nsc_attrs };
static const struct tpm_vendor_specific tpm_nsc = {
.recv = tpm_nsc_recv,
.send = tpm_nsc_send,
.cancel = tpm_nsc_cancel,
.status = tpm_nsc_status,
.req_complete_mask = NSC_STATUS_OBF,
.req_complete_val = NSC_STATUS_OBF,
.req_canceled = NSC_STATUS_RDY,
.attr_group = &nsc_attr_grp,
.miscdev = { .fops = &nsc_ops, },
};
static struct platform_device *pdev = NULL;
static void tpm_nsc_remove(struct device *dev)
{
struct tpm_chip *chip = dev_get_drvdata(dev);
if ( chip ) {
release_region(chip->vendor.base, 2);
tpm_remove_hardware(chip->dev);
}
}
static int tpm_nsc_suspend(struct platform_device *dev, pm_message_t msg)
{
return tpm_pm_suspend(&dev->dev, msg);
}
static int tpm_nsc_resume(struct platform_device *dev)
{
return tpm_pm_resume(&dev->dev);
}
static struct platform_driver nsc_drv = {
.suspend = tpm_nsc_suspend,
.resume = tpm_nsc_resume,
.driver = {
.name = "tpm_nsc",
.owner = THIS_MODULE,
},
};
static int __init init_nsc(void)
{
int rc = 0;
int lo, hi, err;
int nscAddrBase = TPM_ADDR;
struct tpm_chip *chip;
unsigned long base;
/* verify that it is a National part (SID) */
if (tpm_read_index(TPM_ADDR, NSC_SID_INDEX) != 0xEF) {
nscAddrBase = (tpm_read_index(TPM_SUPERIO_ADDR, 0x2C)<<8)|
(tpm_read_index(TPM_SUPERIO_ADDR, 0x2B)&0xFE);
if (tpm_read_index(nscAddrBase, NSC_SID_INDEX) != 0xF6)
return -ENODEV;
}
err = platform_driver_register(&nsc_drv);
if (err)
return err;
hi = tpm_read_index(nscAddrBase, TPM_NSC_BASE0_HI);
lo = tpm_read_index(nscAddrBase, TPM_NSC_BASE0_LO);
base = (hi<<8) | lo;
/* enable the DPM module */
tpm_write_index(nscAddrBase, NSC_LDC_INDEX, 0x01);
pdev = platform_device_alloc("tpm_nscl0", -1);
if (!pdev) {
rc = -ENOMEM;
goto err_unreg_drv;
}
pdev->num_resources = 0;
pdev->dev.driver = &nsc_drv.driver;
pdev->dev.release = tpm_nsc_remove;
if ((rc = platform_device_register(pdev)) < 0)
goto err_free_dev;
if (request_region(base, 2, "tpm_nsc0") == NULL ) {
rc = -EBUSY;
goto err_unreg_dev;
}
if (!(chip = tpm_register_hardware(&pdev->dev, &tpm_nsc))) {
rc = -ENODEV;
goto err_rel_reg;
}
dev_dbg(&pdev->dev, "NSC TPM detected\n");
dev_dbg(&pdev->dev,
"NSC LDN 0x%x, SID 0x%x, SRID 0x%x\n",
tpm_read_index(nscAddrBase,0x07), tpm_read_index(nscAddrBase,0x20),
tpm_read_index(nscAddrBase,0x27));
dev_dbg(&pdev->dev,
"NSC SIOCF1 0x%x SIOCF5 0x%x SIOCF6 0x%x SIOCF8 0x%x\n",
tpm_read_index(nscAddrBase,0x21), tpm_read_index(nscAddrBase,0x25),
tpm_read_index(nscAddrBase,0x26), tpm_read_index(nscAddrBase,0x28));
dev_dbg(&pdev->dev, "NSC IO Base0 0x%x\n",
(tpm_read_index(nscAddrBase,0x60) << 8) | tpm_read_index(nscAddrBase,0x61));
dev_dbg(&pdev->dev, "NSC IO Base1 0x%x\n",
(tpm_read_index(nscAddrBase,0x62) << 8) | tpm_read_index(nscAddrBase,0x63));
dev_dbg(&pdev->dev, "NSC Interrupt number and wakeup 0x%x\n",
tpm_read_index(nscAddrBase,0x70));
dev_dbg(&pdev->dev, "NSC IRQ type select 0x%x\n",
tpm_read_index(nscAddrBase,0x71));
dev_dbg(&pdev->dev,
"NSC DMA channel select0 0x%x, select1 0x%x\n",
tpm_read_index(nscAddrBase,0x74), tpm_read_index(nscAddrBase,0x75));
dev_dbg(&pdev->dev,
"NSC Config "
"0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\n",
tpm_read_index(nscAddrBase,0xF0), tpm_read_index(nscAddrBase,0xF1),
tpm_read_index(nscAddrBase,0xF2), tpm_read_index(nscAddrBase,0xF3),
tpm_read_index(nscAddrBase,0xF4), tpm_read_index(nscAddrBase,0xF5),
tpm_read_index(nscAddrBase,0xF6), tpm_read_index(nscAddrBase,0xF7),
tpm_read_index(nscAddrBase,0xF8), tpm_read_index(nscAddrBase,0xF9));
dev_info(&pdev->dev,
"NSC TPM revision %d\n",
tpm_read_index(nscAddrBase, 0x27) & 0x1F);
chip->vendor.base = base;
return 0;
err_rel_reg:
release_region(base, 2);
err_unreg_dev:
platform_device_unregister(pdev);
err_free_dev:
kfree(pdev);
err_unreg_drv:
platform_driver_unregister(&nsc_drv);
return rc;
}
static void __exit cleanup_nsc(void)
{
if (pdev) {
tpm_nsc_remove(&pdev->dev);
platform_device_unregister(pdev);
kfree(pdev);
pdev = NULL;
}
platform_driver_unregister(&nsc_drv);
}
module_init(init_nsc);
module_exit(cleanup_nsc);
MODULE_AUTHOR("Leendert van Doorn (leendert@watson.ibm.com)");
MODULE_DESCRIPTION("TPM Driver");
MODULE_VERSION("2.0");
MODULE_LICENSE("GPL");
| gpl-2.0 |
TEAM-Gummy/kernel_oppo_msm8974 | drivers/gpu/drm/drm_mm.c | 3876 | 19335 | /**************************************************************************
*
* Copyright 2006 Tungsten Graphics, Inc., Bismarck, ND., USA.
* 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, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS, AUTHORS 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.
*
*
**************************************************************************/
/*
* Generic simple memory manager implementation. Intended to be used as a base
* class implementation for more advanced memory managers.
*
* Note that the algorithm used is quite simple and there might be substantial
* performance gains if a smarter free list is implemented. Currently it is just an
* unordered stack of free regions. This could easily be improved if an RB-tree
* is used instead. At least if we expect heavy fragmentation.
*
* Aligned allocations can also see improvement.
*
* Authors:
* Thomas Hellström <thomas-at-tungstengraphics-dot-com>
*/
#include "drmP.h"
#include "drm_mm.h"
#include <linux/slab.h>
#include <linux/seq_file.h>
#include <linux/export.h>
#define MM_UNUSED_TARGET 4
static struct drm_mm_node *drm_mm_kmalloc(struct drm_mm *mm, int atomic)
{
struct drm_mm_node *child;
if (atomic)
child = kzalloc(sizeof(*child), GFP_ATOMIC);
else
child = kzalloc(sizeof(*child), GFP_KERNEL);
if (unlikely(child == NULL)) {
spin_lock(&mm->unused_lock);
if (list_empty(&mm->unused_nodes))
child = NULL;
else {
child =
list_entry(mm->unused_nodes.next,
struct drm_mm_node, node_list);
list_del(&child->node_list);
--mm->num_unused;
}
spin_unlock(&mm->unused_lock);
}
return child;
}
/* drm_mm_pre_get() - pre allocate drm_mm_node structure
* drm_mm: memory manager struct we are pre-allocating for
*
* Returns 0 on success or -ENOMEM if allocation fails.
*/
int drm_mm_pre_get(struct drm_mm *mm)
{
struct drm_mm_node *node;
spin_lock(&mm->unused_lock);
while (mm->num_unused < MM_UNUSED_TARGET) {
spin_unlock(&mm->unused_lock);
node = kzalloc(sizeof(*node), GFP_KERNEL);
spin_lock(&mm->unused_lock);
if (unlikely(node == NULL)) {
int ret = (mm->num_unused < 2) ? -ENOMEM : 0;
spin_unlock(&mm->unused_lock);
return ret;
}
++mm->num_unused;
list_add_tail(&node->node_list, &mm->unused_nodes);
}
spin_unlock(&mm->unused_lock);
return 0;
}
EXPORT_SYMBOL(drm_mm_pre_get);
static inline unsigned long drm_mm_hole_node_start(struct drm_mm_node *hole_node)
{
return hole_node->start + hole_node->size;
}
static inline unsigned long drm_mm_hole_node_end(struct drm_mm_node *hole_node)
{
struct drm_mm_node *next_node =
list_entry(hole_node->node_list.next, struct drm_mm_node,
node_list);
return next_node->start;
}
static void drm_mm_insert_helper(struct drm_mm_node *hole_node,
struct drm_mm_node *node,
unsigned long size, unsigned alignment)
{
struct drm_mm *mm = hole_node->mm;
unsigned long tmp = 0, wasted = 0;
unsigned long hole_start = drm_mm_hole_node_start(hole_node);
unsigned long hole_end = drm_mm_hole_node_end(hole_node);
BUG_ON(!hole_node->hole_follows || node->allocated);
if (alignment)
tmp = hole_start % alignment;
if (!tmp) {
hole_node->hole_follows = 0;
list_del_init(&hole_node->hole_stack);
} else
wasted = alignment - tmp;
node->start = hole_start + wasted;
node->size = size;
node->mm = mm;
node->allocated = 1;
INIT_LIST_HEAD(&node->hole_stack);
list_add(&node->node_list, &hole_node->node_list);
BUG_ON(node->start + node->size > hole_end);
if (node->start + node->size < hole_end) {
list_add(&node->hole_stack, &mm->hole_stack);
node->hole_follows = 1;
} else {
node->hole_follows = 0;
}
}
struct drm_mm_node *drm_mm_get_block_generic(struct drm_mm_node *hole_node,
unsigned long size,
unsigned alignment,
int atomic)
{
struct drm_mm_node *node;
node = drm_mm_kmalloc(hole_node->mm, atomic);
if (unlikely(node == NULL))
return NULL;
drm_mm_insert_helper(hole_node, node, size, alignment);
return node;
}
EXPORT_SYMBOL(drm_mm_get_block_generic);
/**
* Search for free space and insert a preallocated memory node. Returns
* -ENOSPC if no suitable free area is available. The preallocated memory node
* must be cleared.
*/
int drm_mm_insert_node(struct drm_mm *mm, struct drm_mm_node *node,
unsigned long size, unsigned alignment)
{
struct drm_mm_node *hole_node;
hole_node = drm_mm_search_free(mm, size, alignment, 0);
if (!hole_node)
return -ENOSPC;
drm_mm_insert_helper(hole_node, node, size, alignment);
return 0;
}
EXPORT_SYMBOL(drm_mm_insert_node);
static void drm_mm_insert_helper_range(struct drm_mm_node *hole_node,
struct drm_mm_node *node,
unsigned long size, unsigned alignment,
unsigned long start, unsigned long end)
{
struct drm_mm *mm = hole_node->mm;
unsigned long tmp = 0, wasted = 0;
unsigned long hole_start = drm_mm_hole_node_start(hole_node);
unsigned long hole_end = drm_mm_hole_node_end(hole_node);
BUG_ON(!hole_node->hole_follows || node->allocated);
if (hole_start < start)
wasted += start - hole_start;
if (alignment)
tmp = (hole_start + wasted) % alignment;
if (tmp)
wasted += alignment - tmp;
if (!wasted) {
hole_node->hole_follows = 0;
list_del_init(&hole_node->hole_stack);
}
node->start = hole_start + wasted;
node->size = size;
node->mm = mm;
node->allocated = 1;
INIT_LIST_HEAD(&node->hole_stack);
list_add(&node->node_list, &hole_node->node_list);
BUG_ON(node->start + node->size > hole_end);
BUG_ON(node->start + node->size > end);
if (node->start + node->size < hole_end) {
list_add(&node->hole_stack, &mm->hole_stack);
node->hole_follows = 1;
} else {
node->hole_follows = 0;
}
}
struct drm_mm_node *drm_mm_get_block_range_generic(struct drm_mm_node *hole_node,
unsigned long size,
unsigned alignment,
unsigned long start,
unsigned long end,
int atomic)
{
struct drm_mm_node *node;
node = drm_mm_kmalloc(hole_node->mm, atomic);
if (unlikely(node == NULL))
return NULL;
drm_mm_insert_helper_range(hole_node, node, size, alignment,
start, end);
return node;
}
EXPORT_SYMBOL(drm_mm_get_block_range_generic);
/**
* Search for free space and insert a preallocated memory node. Returns
* -ENOSPC if no suitable free area is available. This is for range
* restricted allocations. The preallocated memory node must be cleared.
*/
int drm_mm_insert_node_in_range(struct drm_mm *mm, struct drm_mm_node *node,
unsigned long size, unsigned alignment,
unsigned long start, unsigned long end)
{
struct drm_mm_node *hole_node;
hole_node = drm_mm_search_free_in_range(mm, size, alignment,
start, end, 0);
if (!hole_node)
return -ENOSPC;
drm_mm_insert_helper_range(hole_node, node, size, alignment,
start, end);
return 0;
}
EXPORT_SYMBOL(drm_mm_insert_node_in_range);
/**
* Remove a memory node from the allocator.
*/
void drm_mm_remove_node(struct drm_mm_node *node)
{
struct drm_mm *mm = node->mm;
struct drm_mm_node *prev_node;
BUG_ON(node->scanned_block || node->scanned_prev_free
|| node->scanned_next_free);
prev_node =
list_entry(node->node_list.prev, struct drm_mm_node, node_list);
if (node->hole_follows) {
BUG_ON(drm_mm_hole_node_start(node)
== drm_mm_hole_node_end(node));
list_del(&node->hole_stack);
} else
BUG_ON(drm_mm_hole_node_start(node)
!= drm_mm_hole_node_end(node));
if (!prev_node->hole_follows) {
prev_node->hole_follows = 1;
list_add(&prev_node->hole_stack, &mm->hole_stack);
} else
list_move(&prev_node->hole_stack, &mm->hole_stack);
list_del(&node->node_list);
node->allocated = 0;
}
EXPORT_SYMBOL(drm_mm_remove_node);
/*
* Remove a memory node from the allocator and free the allocated struct
* drm_mm_node. Only to be used on a struct drm_mm_node obtained by one of the
* drm_mm_get_block functions.
*/
void drm_mm_put_block(struct drm_mm_node *node)
{
struct drm_mm *mm = node->mm;
drm_mm_remove_node(node);
spin_lock(&mm->unused_lock);
if (mm->num_unused < MM_UNUSED_TARGET) {
list_add(&node->node_list, &mm->unused_nodes);
++mm->num_unused;
} else
kfree(node);
spin_unlock(&mm->unused_lock);
}
EXPORT_SYMBOL(drm_mm_put_block);
static int check_free_hole(unsigned long start, unsigned long end,
unsigned long size, unsigned alignment)
{
unsigned wasted = 0;
if (end - start < size)
return 0;
if (alignment) {
unsigned tmp = start % alignment;
if (tmp)
wasted = alignment - tmp;
}
if (end >= start + size + wasted) {
return 1;
}
return 0;
}
struct drm_mm_node *drm_mm_search_free(const struct drm_mm *mm,
unsigned long size,
unsigned alignment, int best_match)
{
struct drm_mm_node *entry;
struct drm_mm_node *best;
unsigned long best_size;
BUG_ON(mm->scanned_blocks);
best = NULL;
best_size = ~0UL;
list_for_each_entry(entry, &mm->hole_stack, hole_stack) {
BUG_ON(!entry->hole_follows);
if (!check_free_hole(drm_mm_hole_node_start(entry),
drm_mm_hole_node_end(entry),
size, alignment))
continue;
if (!best_match)
return entry;
if (entry->size < best_size) {
best = entry;
best_size = entry->size;
}
}
return best;
}
EXPORT_SYMBOL(drm_mm_search_free);
struct drm_mm_node *drm_mm_search_free_in_range(const struct drm_mm *mm,
unsigned long size,
unsigned alignment,
unsigned long start,
unsigned long end,
int best_match)
{
struct drm_mm_node *entry;
struct drm_mm_node *best;
unsigned long best_size;
BUG_ON(mm->scanned_blocks);
best = NULL;
best_size = ~0UL;
list_for_each_entry(entry, &mm->hole_stack, hole_stack) {
unsigned long adj_start = drm_mm_hole_node_start(entry) < start ?
start : drm_mm_hole_node_start(entry);
unsigned long adj_end = drm_mm_hole_node_end(entry) > end ?
end : drm_mm_hole_node_end(entry);
BUG_ON(!entry->hole_follows);
if (!check_free_hole(adj_start, adj_end, size, alignment))
continue;
if (!best_match)
return entry;
if (entry->size < best_size) {
best = entry;
best_size = entry->size;
}
}
return best;
}
EXPORT_SYMBOL(drm_mm_search_free_in_range);
/**
* Moves an allocation. To be used with embedded struct drm_mm_node.
*/
void drm_mm_replace_node(struct drm_mm_node *old, struct drm_mm_node *new)
{
list_replace(&old->node_list, &new->node_list);
list_replace(&old->hole_stack, &new->hole_stack);
new->hole_follows = old->hole_follows;
new->mm = old->mm;
new->start = old->start;
new->size = old->size;
old->allocated = 0;
new->allocated = 1;
}
EXPORT_SYMBOL(drm_mm_replace_node);
/**
* Initializa lru scanning.
*
* This simply sets up the scanning routines with the parameters for the desired
* hole.
*
* Warning: As long as the scan list is non-empty, no other operations than
* adding/removing nodes to/from the scan list are allowed.
*/
void drm_mm_init_scan(struct drm_mm *mm, unsigned long size,
unsigned alignment)
{
mm->scan_alignment = alignment;
mm->scan_size = size;
mm->scanned_blocks = 0;
mm->scan_hit_start = 0;
mm->scan_hit_size = 0;
mm->scan_check_range = 0;
mm->prev_scanned_node = NULL;
}
EXPORT_SYMBOL(drm_mm_init_scan);
/**
* Initializa lru scanning.
*
* This simply sets up the scanning routines with the parameters for the desired
* hole. This version is for range-restricted scans.
*
* Warning: As long as the scan list is non-empty, no other operations than
* adding/removing nodes to/from the scan list are allowed.
*/
void drm_mm_init_scan_with_range(struct drm_mm *mm, unsigned long size,
unsigned alignment,
unsigned long start,
unsigned long end)
{
mm->scan_alignment = alignment;
mm->scan_size = size;
mm->scanned_blocks = 0;
mm->scan_hit_start = 0;
mm->scan_hit_size = 0;
mm->scan_start = start;
mm->scan_end = end;
mm->scan_check_range = 1;
mm->prev_scanned_node = NULL;
}
EXPORT_SYMBOL(drm_mm_init_scan_with_range);
/**
* Add a node to the scan list that might be freed to make space for the desired
* hole.
*
* Returns non-zero, if a hole has been found, zero otherwise.
*/
int drm_mm_scan_add_block(struct drm_mm_node *node)
{
struct drm_mm *mm = node->mm;
struct drm_mm_node *prev_node;
unsigned long hole_start, hole_end;
unsigned long adj_start;
unsigned long adj_end;
mm->scanned_blocks++;
BUG_ON(node->scanned_block);
node->scanned_block = 1;
prev_node = list_entry(node->node_list.prev, struct drm_mm_node,
node_list);
node->scanned_preceeds_hole = prev_node->hole_follows;
prev_node->hole_follows = 1;
list_del(&node->node_list);
node->node_list.prev = &prev_node->node_list;
node->node_list.next = &mm->prev_scanned_node->node_list;
mm->prev_scanned_node = node;
hole_start = drm_mm_hole_node_start(prev_node);
hole_end = drm_mm_hole_node_end(prev_node);
if (mm->scan_check_range) {
adj_start = hole_start < mm->scan_start ?
mm->scan_start : hole_start;
adj_end = hole_end > mm->scan_end ?
mm->scan_end : hole_end;
} else {
adj_start = hole_start;
adj_end = hole_end;
}
if (check_free_hole(adj_start , adj_end,
mm->scan_size, mm->scan_alignment)) {
mm->scan_hit_start = hole_start;
mm->scan_hit_size = hole_end;
return 1;
}
return 0;
}
EXPORT_SYMBOL(drm_mm_scan_add_block);
/**
* Remove a node from the scan list.
*
* Nodes _must_ be removed in the exact same order from the scan list as they
* have been added, otherwise the internal state of the memory manager will be
* corrupted.
*
* When the scan list is empty, the selected memory nodes can be freed. An
* immediately following drm_mm_search_free with best_match = 0 will then return
* the just freed block (because its at the top of the free_stack list).
*
* Returns one if this block should be evicted, zero otherwise. Will always
* return zero when no hole has been found.
*/
int drm_mm_scan_remove_block(struct drm_mm_node *node)
{
struct drm_mm *mm = node->mm;
struct drm_mm_node *prev_node;
mm->scanned_blocks--;
BUG_ON(!node->scanned_block);
node->scanned_block = 0;
prev_node = list_entry(node->node_list.prev, struct drm_mm_node,
node_list);
prev_node->hole_follows = node->scanned_preceeds_hole;
INIT_LIST_HEAD(&node->node_list);
list_add(&node->node_list, &prev_node->node_list);
/* Only need to check for containement because start&size for the
* complete resulting free block (not just the desired part) is
* stored. */
if (node->start >= mm->scan_hit_start &&
node->start + node->size
<= mm->scan_hit_start + mm->scan_hit_size) {
return 1;
}
return 0;
}
EXPORT_SYMBOL(drm_mm_scan_remove_block);
int drm_mm_clean(struct drm_mm * mm)
{
struct list_head *head = &mm->head_node.node_list;
return (head->next->next == head);
}
EXPORT_SYMBOL(drm_mm_clean);
int drm_mm_init(struct drm_mm * mm, unsigned long start, unsigned long size)
{
INIT_LIST_HEAD(&mm->hole_stack);
INIT_LIST_HEAD(&mm->unused_nodes);
mm->num_unused = 0;
mm->scanned_blocks = 0;
spin_lock_init(&mm->unused_lock);
/* Clever trick to avoid a special case in the free hole tracking. */
INIT_LIST_HEAD(&mm->head_node.node_list);
INIT_LIST_HEAD(&mm->head_node.hole_stack);
mm->head_node.hole_follows = 1;
mm->head_node.scanned_block = 0;
mm->head_node.scanned_prev_free = 0;
mm->head_node.scanned_next_free = 0;
mm->head_node.mm = mm;
mm->head_node.start = start + size;
mm->head_node.size = start - mm->head_node.start;
list_add_tail(&mm->head_node.hole_stack, &mm->hole_stack);
return 0;
}
EXPORT_SYMBOL(drm_mm_init);
void drm_mm_takedown(struct drm_mm * mm)
{
struct drm_mm_node *entry, *next;
if (!list_empty(&mm->head_node.node_list)) {
DRM_ERROR("Memory manager not clean. Delaying takedown\n");
return;
}
spin_lock(&mm->unused_lock);
list_for_each_entry_safe(entry, next, &mm->unused_nodes, node_list) {
list_del(&entry->node_list);
kfree(entry);
--mm->num_unused;
}
spin_unlock(&mm->unused_lock);
BUG_ON(mm->num_unused != 0);
}
EXPORT_SYMBOL(drm_mm_takedown);
void drm_mm_debug_table(struct drm_mm *mm, const char *prefix)
{
struct drm_mm_node *entry;
unsigned long total_used = 0, total_free = 0, total = 0;
unsigned long hole_start, hole_end, hole_size;
hole_start = drm_mm_hole_node_start(&mm->head_node);
hole_end = drm_mm_hole_node_end(&mm->head_node);
hole_size = hole_end - hole_start;
if (hole_size)
printk(KERN_DEBUG "%s 0x%08lx-0x%08lx: %8lu: free\n",
prefix, hole_start, hole_end,
hole_size);
total_free += hole_size;
drm_mm_for_each_node(entry, mm) {
printk(KERN_DEBUG "%s 0x%08lx-0x%08lx: %8lu: used\n",
prefix, entry->start, entry->start + entry->size,
entry->size);
total_used += entry->size;
if (entry->hole_follows) {
hole_start = drm_mm_hole_node_start(entry);
hole_end = drm_mm_hole_node_end(entry);
hole_size = hole_end - hole_start;
printk(KERN_DEBUG "%s 0x%08lx-0x%08lx: %8lu: free\n",
prefix, hole_start, hole_end,
hole_size);
total_free += hole_size;
}
}
total = total_free + total_used;
printk(KERN_DEBUG "%s total: %lu, used %lu free %lu\n", prefix, total,
total_used, total_free);
}
EXPORT_SYMBOL(drm_mm_debug_table);
#if defined(CONFIG_DEBUG_FS)
int drm_mm_dump_table(struct seq_file *m, struct drm_mm *mm)
{
struct drm_mm_node *entry;
unsigned long total_used = 0, total_free = 0, total = 0;
unsigned long hole_start, hole_end, hole_size;
hole_start = drm_mm_hole_node_start(&mm->head_node);
hole_end = drm_mm_hole_node_end(&mm->head_node);
hole_size = hole_end - hole_start;
if (hole_size)
seq_printf(m, "0x%08lx-0x%08lx: 0x%08lx: free\n",
hole_start, hole_end, hole_size);
total_free += hole_size;
drm_mm_for_each_node(entry, mm) {
seq_printf(m, "0x%08lx-0x%08lx: 0x%08lx: used\n",
entry->start, entry->start + entry->size,
entry->size);
total_used += entry->size;
if (entry->hole_follows) {
hole_start = drm_mm_hole_node_start(entry);
hole_end = drm_mm_hole_node_end(entry);
hole_size = hole_end - hole_start;
seq_printf(m, "0x%08lx-0x%08lx: 0x%08lx: free\n",
hole_start, hole_end, hole_size);
total_free += hole_size;
}
}
total = total_free + total_used;
seq_printf(m, "total: %lu, used %lu free %lu\n", total, total_used, total_free);
return 0;
}
EXPORT_SYMBOL(drm_mm_dump_table);
#endif
| gpl-2.0 |
MattCrystal/ballin-robot | net/netfilter/xt_RATEEST.c | 5668 | 4722 | /*
* (C) 2007 Patrick McHardy <kaber@trash.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/gen_stats.h>
#include <linux/jhash.h>
#include <linux/rtnetlink.h>
#include <linux/random.h>
#include <linux/slab.h>
#include <net/gen_stats.h>
#include <net/netlink.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter/xt_RATEEST.h>
#include <net/netfilter/xt_rateest.h>
static DEFINE_MUTEX(xt_rateest_mutex);
#define RATEEST_HSIZE 16
static struct hlist_head rateest_hash[RATEEST_HSIZE] __read_mostly;
static unsigned int jhash_rnd __read_mostly;
static bool rnd_inited __read_mostly;
static unsigned int xt_rateest_hash(const char *name)
{
return jhash(name, FIELD_SIZEOF(struct xt_rateest, name), jhash_rnd) &
(RATEEST_HSIZE - 1);
}
static void xt_rateest_hash_insert(struct xt_rateest *est)
{
unsigned int h;
h = xt_rateest_hash(est->name);
hlist_add_head(&est->list, &rateest_hash[h]);
}
struct xt_rateest *xt_rateest_lookup(const char *name)
{
struct xt_rateest *est;
struct hlist_node *n;
unsigned int h;
h = xt_rateest_hash(name);
mutex_lock(&xt_rateest_mutex);
hlist_for_each_entry(est, n, &rateest_hash[h], list) {
if (strcmp(est->name, name) == 0) {
est->refcnt++;
mutex_unlock(&xt_rateest_mutex);
return est;
}
}
mutex_unlock(&xt_rateest_mutex);
return NULL;
}
EXPORT_SYMBOL_GPL(xt_rateest_lookup);
void xt_rateest_put(struct xt_rateest *est)
{
mutex_lock(&xt_rateest_mutex);
if (--est->refcnt == 0) {
hlist_del(&est->list);
gen_kill_estimator(&est->bstats, &est->rstats);
/*
* gen_estimator est_timer() might access est->lock or bstats,
* wait a RCU grace period before freeing 'est'
*/
kfree_rcu(est, rcu);
}
mutex_unlock(&xt_rateest_mutex);
}
EXPORT_SYMBOL_GPL(xt_rateest_put);
static unsigned int
xt_rateest_tg(struct sk_buff *skb, const struct xt_action_param *par)
{
const struct xt_rateest_target_info *info = par->targinfo;
struct gnet_stats_basic_packed *stats = &info->est->bstats;
spin_lock_bh(&info->est->lock);
stats->bytes += skb->len;
stats->packets++;
spin_unlock_bh(&info->est->lock);
return XT_CONTINUE;
}
static int xt_rateest_tg_checkentry(const struct xt_tgchk_param *par)
{
struct xt_rateest_target_info *info = par->targinfo;
struct xt_rateest *est;
struct {
struct nlattr opt;
struct gnet_estimator est;
} cfg;
int ret;
if (unlikely(!rnd_inited)) {
get_random_bytes(&jhash_rnd, sizeof(jhash_rnd));
rnd_inited = true;
}
est = xt_rateest_lookup(info->name);
if (est) {
/*
* If estimator parameters are specified, they must match the
* existing estimator.
*/
if ((!info->interval && !info->ewma_log) ||
(info->interval != est->params.interval ||
info->ewma_log != est->params.ewma_log)) {
xt_rateest_put(est);
return -EINVAL;
}
info->est = est;
return 0;
}
ret = -ENOMEM;
est = kzalloc(sizeof(*est), GFP_KERNEL);
if (!est)
goto err1;
strlcpy(est->name, info->name, sizeof(est->name));
spin_lock_init(&est->lock);
est->refcnt = 1;
est->params.interval = info->interval;
est->params.ewma_log = info->ewma_log;
cfg.opt.nla_len = nla_attr_size(sizeof(cfg.est));
cfg.opt.nla_type = TCA_STATS_RATE_EST;
cfg.est.interval = info->interval;
cfg.est.ewma_log = info->ewma_log;
ret = gen_new_estimator(&est->bstats, &est->rstats,
&est->lock, &cfg.opt);
if (ret < 0)
goto err2;
info->est = est;
xt_rateest_hash_insert(est);
return 0;
err2:
kfree(est);
err1:
return ret;
}
static void xt_rateest_tg_destroy(const struct xt_tgdtor_param *par)
{
struct xt_rateest_target_info *info = par->targinfo;
xt_rateest_put(info->est);
}
static struct xt_target xt_rateest_tg_reg __read_mostly = {
.name = "RATEEST",
.revision = 0,
.family = NFPROTO_UNSPEC,
.target = xt_rateest_tg,
.checkentry = xt_rateest_tg_checkentry,
.destroy = xt_rateest_tg_destroy,
.targetsize = sizeof(struct xt_rateest_target_info),
.me = THIS_MODULE,
};
static int __init xt_rateest_tg_init(void)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(rateest_hash); i++)
INIT_HLIST_HEAD(&rateest_hash[i]);
return xt_register_target(&xt_rateest_tg_reg);
}
static void __exit xt_rateest_tg_fini(void)
{
xt_unregister_target(&xt_rateest_tg_reg);
}
MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Xtables: packet rate estimator");
MODULE_ALIAS("ipt_RATEEST");
MODULE_ALIAS("ip6t_RATEEST");
module_init(xt_rateest_tg_init);
module_exit(xt_rateest_tg_fini);
| gpl-2.0 |
RikuAzhurlar/demonslayerkernel_lge_msm8226 | arch/sh/kernel/cpu/sh4/softfloat.c | 14628 | 22912 | /*
* Floating point emulation support for subnormalised numbers on SH4
* architecture This file is derived from the SoftFloat IEC/IEEE
* Floating-point Arithmetic Package, Release 2 the original license of
* which is reproduced below.
*
* ========================================================================
*
* This C source file is part of the SoftFloat IEC/IEEE Floating-point
* Arithmetic Package, Release 2.
*
* Written by John R. Hauser. This work was made possible in part by the
* International Computer Science Institute, located at Suite 600, 1947 Center
* Street, Berkeley, California 94704. Funding was partially provided by the
* National Science Foundation under grant MIP-9311980. The original version
* of this code was written as part of a project to build a fixed-point vector
* processor in collaboration with the University of California at Berkeley,
* overseen by Profs. Nelson Morgan and John Wawrzynek. More information
* is available through the web page `http://HTTP.CS.Berkeley.EDU/~jhauser/
* arithmetic/softfloat.html'.
*
* THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE. Although reasonable effort
* has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT
* TIMES RESULT IN INCORRECT BEHAVIOR. USE OF THIS SOFTWARE IS RESTRICTED TO
* PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY
* AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE.
*
* Derivative works are acceptable, even for commercial purposes, so long as
* (1) they include prominent notice that the work is derivative, and (2) they
* include prominent notice akin to these three paragraphs for those parts of
* this code that are retained.
*
* ========================================================================
*
* SH4 modifications by Ismail Dhaoui <ismail.dhaoui@st.com>
* and Kamel Khelifi <kamel.khelifi@st.com>
*/
#include <linux/kernel.h>
#include <cpu/fpu.h>
#include <asm/div64.h>
#define LIT64( a ) a##LL
typedef char flag;
typedef unsigned char uint8;
typedef signed char int8;
typedef int uint16;
typedef int int16;
typedef unsigned int uint32;
typedef signed int int32;
typedef unsigned long long int bits64;
typedef signed long long int sbits64;
typedef unsigned char bits8;
typedef signed char sbits8;
typedef unsigned short int bits16;
typedef signed short int sbits16;
typedef unsigned int bits32;
typedef signed int sbits32;
typedef unsigned long long int uint64;
typedef signed long long int int64;
typedef unsigned long int float32;
typedef unsigned long long float64;
extern void float_raise(unsigned int flags); /* in fpu.c */
extern int float_rounding_mode(void); /* in fpu.c */
bits64 extractFloat64Frac(float64 a);
flag extractFloat64Sign(float64 a);
int16 extractFloat64Exp(float64 a);
int16 extractFloat32Exp(float32 a);
flag extractFloat32Sign(float32 a);
bits32 extractFloat32Frac(float32 a);
float64 packFloat64(flag zSign, int16 zExp, bits64 zSig);
void shift64RightJamming(bits64 a, int16 count, bits64 * zPtr);
float32 packFloat32(flag zSign, int16 zExp, bits32 zSig);
void shift32RightJamming(bits32 a, int16 count, bits32 * zPtr);
float64 float64_sub(float64 a, float64 b);
float32 float32_sub(float32 a, float32 b);
float32 float32_add(float32 a, float32 b);
float64 float64_add(float64 a, float64 b);
float64 float64_div(float64 a, float64 b);
float32 float32_div(float32 a, float32 b);
float32 float32_mul(float32 a, float32 b);
float64 float64_mul(float64 a, float64 b);
float32 float64_to_float32(float64 a);
void add128(bits64 a0, bits64 a1, bits64 b0, bits64 b1, bits64 * z0Ptr,
bits64 * z1Ptr);
void sub128(bits64 a0, bits64 a1, bits64 b0, bits64 b1, bits64 * z0Ptr,
bits64 * z1Ptr);
void mul64To128(bits64 a, bits64 b, bits64 * z0Ptr, bits64 * z1Ptr);
static int8 countLeadingZeros32(bits32 a);
static int8 countLeadingZeros64(bits64 a);
static float64 normalizeRoundAndPackFloat64(flag zSign, int16 zExp,
bits64 zSig);
static float64 subFloat64Sigs(float64 a, float64 b, flag zSign);
static float64 addFloat64Sigs(float64 a, float64 b, flag zSign);
static float32 roundAndPackFloat32(flag zSign, int16 zExp, bits32 zSig);
static float32 normalizeRoundAndPackFloat32(flag zSign, int16 zExp,
bits32 zSig);
static float64 roundAndPackFloat64(flag zSign, int16 zExp, bits64 zSig);
static float32 subFloat32Sigs(float32 a, float32 b, flag zSign);
static float32 addFloat32Sigs(float32 a, float32 b, flag zSign);
static void normalizeFloat64Subnormal(bits64 aSig, int16 * zExpPtr,
bits64 * zSigPtr);
static bits64 estimateDiv128To64(bits64 a0, bits64 a1, bits64 b);
static void normalizeFloat32Subnormal(bits32 aSig, int16 * zExpPtr,
bits32 * zSigPtr);
bits64 extractFloat64Frac(float64 a)
{
return a & LIT64(0x000FFFFFFFFFFFFF);
}
flag extractFloat64Sign(float64 a)
{
return a >> 63;
}
int16 extractFloat64Exp(float64 a)
{
return (a >> 52) & 0x7FF;
}
int16 extractFloat32Exp(float32 a)
{
return (a >> 23) & 0xFF;
}
flag extractFloat32Sign(float32 a)
{
return a >> 31;
}
bits32 extractFloat32Frac(float32 a)
{
return a & 0x007FFFFF;
}
float64 packFloat64(flag zSign, int16 zExp, bits64 zSig)
{
return (((bits64) zSign) << 63) + (((bits64) zExp) << 52) + zSig;
}
void shift64RightJamming(bits64 a, int16 count, bits64 * zPtr)
{
bits64 z;
if (count == 0) {
z = a;
} else if (count < 64) {
z = (a >> count) | ((a << ((-count) & 63)) != 0);
} else {
z = (a != 0);
}
*zPtr = z;
}
static int8 countLeadingZeros32(bits32 a)
{
static const int8 countLeadingZerosHigh[] = {
8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
int8 shiftCount;
shiftCount = 0;
if (a < 0x10000) {
shiftCount += 16;
a <<= 16;
}
if (a < 0x1000000) {
shiftCount += 8;
a <<= 8;
}
shiftCount += countLeadingZerosHigh[a >> 24];
return shiftCount;
}
static int8 countLeadingZeros64(bits64 a)
{
int8 shiftCount;
shiftCount = 0;
if (a < ((bits64) 1) << 32) {
shiftCount += 32;
} else {
a >>= 32;
}
shiftCount += countLeadingZeros32(a);
return shiftCount;
}
static float64 normalizeRoundAndPackFloat64(flag zSign, int16 zExp, bits64 zSig)
{
int8 shiftCount;
shiftCount = countLeadingZeros64(zSig) - 1;
return roundAndPackFloat64(zSign, zExp - shiftCount,
zSig << shiftCount);
}
static float64 subFloat64Sigs(float64 a, float64 b, flag zSign)
{
int16 aExp, bExp, zExp;
bits64 aSig, bSig, zSig;
int16 expDiff;
aSig = extractFloat64Frac(a);
aExp = extractFloat64Exp(a);
bSig = extractFloat64Frac(b);
bExp = extractFloat64Exp(b);
expDiff = aExp - bExp;
aSig <<= 10;
bSig <<= 10;
if (0 < expDiff)
goto aExpBigger;
if (expDiff < 0)
goto bExpBigger;
if (aExp == 0) {
aExp = 1;
bExp = 1;
}
if (bSig < aSig)
goto aBigger;
if (aSig < bSig)
goto bBigger;
return packFloat64(float_rounding_mode() == FPSCR_RM_ZERO, 0, 0);
bExpBigger:
if (bExp == 0x7FF) {
return packFloat64(zSign ^ 1, 0x7FF, 0);
}
if (aExp == 0) {
++expDiff;
} else {
aSig |= LIT64(0x4000000000000000);
}
shift64RightJamming(aSig, -expDiff, &aSig);
bSig |= LIT64(0x4000000000000000);
bBigger:
zSig = bSig - aSig;
zExp = bExp;
zSign ^= 1;
goto normalizeRoundAndPack;
aExpBigger:
if (aExp == 0x7FF) {
return a;
}
if (bExp == 0) {
--expDiff;
} else {
bSig |= LIT64(0x4000000000000000);
}
shift64RightJamming(bSig, expDiff, &bSig);
aSig |= LIT64(0x4000000000000000);
aBigger:
zSig = aSig - bSig;
zExp = aExp;
normalizeRoundAndPack:
--zExp;
return normalizeRoundAndPackFloat64(zSign, zExp, zSig);
}
static float64 addFloat64Sigs(float64 a, float64 b, flag zSign)
{
int16 aExp, bExp, zExp;
bits64 aSig, bSig, zSig;
int16 expDiff;
aSig = extractFloat64Frac(a);
aExp = extractFloat64Exp(a);
bSig = extractFloat64Frac(b);
bExp = extractFloat64Exp(b);
expDiff = aExp - bExp;
aSig <<= 9;
bSig <<= 9;
if (0 < expDiff) {
if (aExp == 0x7FF) {
return a;
}
if (bExp == 0) {
--expDiff;
} else {
bSig |= LIT64(0x2000000000000000);
}
shift64RightJamming(bSig, expDiff, &bSig);
zExp = aExp;
} else if (expDiff < 0) {
if (bExp == 0x7FF) {
return packFloat64(zSign, 0x7FF, 0);
}
if (aExp == 0) {
++expDiff;
} else {
aSig |= LIT64(0x2000000000000000);
}
shift64RightJamming(aSig, -expDiff, &aSig);
zExp = bExp;
} else {
if (aExp == 0x7FF) {
return a;
}
if (aExp == 0)
return packFloat64(zSign, 0, (aSig + bSig) >> 9);
zSig = LIT64(0x4000000000000000) + aSig + bSig;
zExp = aExp;
goto roundAndPack;
}
aSig |= LIT64(0x2000000000000000);
zSig = (aSig + bSig) << 1;
--zExp;
if ((sbits64) zSig < 0) {
zSig = aSig + bSig;
++zExp;
}
roundAndPack:
return roundAndPackFloat64(zSign, zExp, zSig);
}
float32 packFloat32(flag zSign, int16 zExp, bits32 zSig)
{
return (((bits32) zSign) << 31) + (((bits32) zExp) << 23) + zSig;
}
void shift32RightJamming(bits32 a, int16 count, bits32 * zPtr)
{
bits32 z;
if (count == 0) {
z = a;
} else if (count < 32) {
z = (a >> count) | ((a << ((-count) & 31)) != 0);
} else {
z = (a != 0);
}
*zPtr = z;
}
static float32 roundAndPackFloat32(flag zSign, int16 zExp, bits32 zSig)
{
flag roundNearestEven;
int8 roundIncrement, roundBits;
flag isTiny;
/* SH4 has only 2 rounding modes - round to nearest and round to zero */
roundNearestEven = (float_rounding_mode() == FPSCR_RM_NEAREST);
roundIncrement = 0x40;
if (!roundNearestEven) {
roundIncrement = 0;
}
roundBits = zSig & 0x7F;
if (0xFD <= (bits16) zExp) {
if ((0xFD < zExp)
|| ((zExp == 0xFD)
&& ((sbits32) (zSig + roundIncrement) < 0))
) {
float_raise(FPSCR_CAUSE_OVERFLOW | FPSCR_CAUSE_INEXACT);
return packFloat32(zSign, 0xFF,
0) - (roundIncrement == 0);
}
if (zExp < 0) {
isTiny = (zExp < -1)
|| (zSig + roundIncrement < 0x80000000);
shift32RightJamming(zSig, -zExp, &zSig);
zExp = 0;
roundBits = zSig & 0x7F;
if (isTiny && roundBits)
float_raise(FPSCR_CAUSE_UNDERFLOW);
}
}
if (roundBits)
float_raise(FPSCR_CAUSE_INEXACT);
zSig = (zSig + roundIncrement) >> 7;
zSig &= ~(((roundBits ^ 0x40) == 0) & roundNearestEven);
if (zSig == 0)
zExp = 0;
return packFloat32(zSign, zExp, zSig);
}
static float32 normalizeRoundAndPackFloat32(flag zSign, int16 zExp, bits32 zSig)
{
int8 shiftCount;
shiftCount = countLeadingZeros32(zSig) - 1;
return roundAndPackFloat32(zSign, zExp - shiftCount,
zSig << shiftCount);
}
static float64 roundAndPackFloat64(flag zSign, int16 zExp, bits64 zSig)
{
flag roundNearestEven;
int16 roundIncrement, roundBits;
flag isTiny;
/* SH4 has only 2 rounding modes - round to nearest and round to zero */
roundNearestEven = (float_rounding_mode() == FPSCR_RM_NEAREST);
roundIncrement = 0x200;
if (!roundNearestEven) {
roundIncrement = 0;
}
roundBits = zSig & 0x3FF;
if (0x7FD <= (bits16) zExp) {
if ((0x7FD < zExp)
|| ((zExp == 0x7FD)
&& ((sbits64) (zSig + roundIncrement) < 0))
) {
float_raise(FPSCR_CAUSE_OVERFLOW | FPSCR_CAUSE_INEXACT);
return packFloat64(zSign, 0x7FF,
0) - (roundIncrement == 0);
}
if (zExp < 0) {
isTiny = (zExp < -1)
|| (zSig + roundIncrement <
LIT64(0x8000000000000000));
shift64RightJamming(zSig, -zExp, &zSig);
zExp = 0;
roundBits = zSig & 0x3FF;
if (isTiny && roundBits)
float_raise(FPSCR_CAUSE_UNDERFLOW);
}
}
if (roundBits)
float_raise(FPSCR_CAUSE_INEXACT);
zSig = (zSig + roundIncrement) >> 10;
zSig &= ~(((roundBits ^ 0x200) == 0) & roundNearestEven);
if (zSig == 0)
zExp = 0;
return packFloat64(zSign, zExp, zSig);
}
static float32 subFloat32Sigs(float32 a, float32 b, flag zSign)
{
int16 aExp, bExp, zExp;
bits32 aSig, bSig, zSig;
int16 expDiff;
aSig = extractFloat32Frac(a);
aExp = extractFloat32Exp(a);
bSig = extractFloat32Frac(b);
bExp = extractFloat32Exp(b);
expDiff = aExp - bExp;
aSig <<= 7;
bSig <<= 7;
if (0 < expDiff)
goto aExpBigger;
if (expDiff < 0)
goto bExpBigger;
if (aExp == 0) {
aExp = 1;
bExp = 1;
}
if (bSig < aSig)
goto aBigger;
if (aSig < bSig)
goto bBigger;
return packFloat32(float_rounding_mode() == FPSCR_RM_ZERO, 0, 0);
bExpBigger:
if (bExp == 0xFF) {
return packFloat32(zSign ^ 1, 0xFF, 0);
}
if (aExp == 0) {
++expDiff;
} else {
aSig |= 0x40000000;
}
shift32RightJamming(aSig, -expDiff, &aSig);
bSig |= 0x40000000;
bBigger:
zSig = bSig - aSig;
zExp = bExp;
zSign ^= 1;
goto normalizeRoundAndPack;
aExpBigger:
if (aExp == 0xFF) {
return a;
}
if (bExp == 0) {
--expDiff;
} else {
bSig |= 0x40000000;
}
shift32RightJamming(bSig, expDiff, &bSig);
aSig |= 0x40000000;
aBigger:
zSig = aSig - bSig;
zExp = aExp;
normalizeRoundAndPack:
--zExp;
return normalizeRoundAndPackFloat32(zSign, zExp, zSig);
}
static float32 addFloat32Sigs(float32 a, float32 b, flag zSign)
{
int16 aExp, bExp, zExp;
bits32 aSig, bSig, zSig;
int16 expDiff;
aSig = extractFloat32Frac(a);
aExp = extractFloat32Exp(a);
bSig = extractFloat32Frac(b);
bExp = extractFloat32Exp(b);
expDiff = aExp - bExp;
aSig <<= 6;
bSig <<= 6;
if (0 < expDiff) {
if (aExp == 0xFF) {
return a;
}
if (bExp == 0) {
--expDiff;
} else {
bSig |= 0x20000000;
}
shift32RightJamming(bSig, expDiff, &bSig);
zExp = aExp;
} else if (expDiff < 0) {
if (bExp == 0xFF) {
return packFloat32(zSign, 0xFF, 0);
}
if (aExp == 0) {
++expDiff;
} else {
aSig |= 0x20000000;
}
shift32RightJamming(aSig, -expDiff, &aSig);
zExp = bExp;
} else {
if (aExp == 0xFF) {
return a;
}
if (aExp == 0)
return packFloat32(zSign, 0, (aSig + bSig) >> 6);
zSig = 0x40000000 + aSig + bSig;
zExp = aExp;
goto roundAndPack;
}
aSig |= 0x20000000;
zSig = (aSig + bSig) << 1;
--zExp;
if ((sbits32) zSig < 0) {
zSig = aSig + bSig;
++zExp;
}
roundAndPack:
return roundAndPackFloat32(zSign, zExp, zSig);
}
float64 float64_sub(float64 a, float64 b)
{
flag aSign, bSign;
aSign = extractFloat64Sign(a);
bSign = extractFloat64Sign(b);
if (aSign == bSign) {
return subFloat64Sigs(a, b, aSign);
} else {
return addFloat64Sigs(a, b, aSign);
}
}
float32 float32_sub(float32 a, float32 b)
{
flag aSign, bSign;
aSign = extractFloat32Sign(a);
bSign = extractFloat32Sign(b);
if (aSign == bSign) {
return subFloat32Sigs(a, b, aSign);
} else {
return addFloat32Sigs(a, b, aSign);
}
}
float32 float32_add(float32 a, float32 b)
{
flag aSign, bSign;
aSign = extractFloat32Sign(a);
bSign = extractFloat32Sign(b);
if (aSign == bSign) {
return addFloat32Sigs(a, b, aSign);
} else {
return subFloat32Sigs(a, b, aSign);
}
}
float64 float64_add(float64 a, float64 b)
{
flag aSign, bSign;
aSign = extractFloat64Sign(a);
bSign = extractFloat64Sign(b);
if (aSign == bSign) {
return addFloat64Sigs(a, b, aSign);
} else {
return subFloat64Sigs(a, b, aSign);
}
}
static void
normalizeFloat64Subnormal(bits64 aSig, int16 * zExpPtr, bits64 * zSigPtr)
{
int8 shiftCount;
shiftCount = countLeadingZeros64(aSig) - 11;
*zSigPtr = aSig << shiftCount;
*zExpPtr = 1 - shiftCount;
}
void add128(bits64 a0, bits64 a1, bits64 b0, bits64 b1, bits64 * z0Ptr,
bits64 * z1Ptr)
{
bits64 z1;
z1 = a1 + b1;
*z1Ptr = z1;
*z0Ptr = a0 + b0 + (z1 < a1);
}
void
sub128(bits64 a0, bits64 a1, bits64 b0, bits64 b1, bits64 * z0Ptr,
bits64 * z1Ptr)
{
*z1Ptr = a1 - b1;
*z0Ptr = a0 - b0 - (a1 < b1);
}
static bits64 estimateDiv128To64(bits64 a0, bits64 a1, bits64 b)
{
bits64 b0, b1;
bits64 rem0, rem1, term0, term1;
bits64 z, tmp;
if (b <= a0)
return LIT64(0xFFFFFFFFFFFFFFFF);
b0 = b >> 32;
tmp = a0;
do_div(tmp, b0);
z = (b0 << 32 <= a0) ? LIT64(0xFFFFFFFF00000000) : tmp << 32;
mul64To128(b, z, &term0, &term1);
sub128(a0, a1, term0, term1, &rem0, &rem1);
while (((sbits64) rem0) < 0) {
z -= LIT64(0x100000000);
b1 = b << 32;
add128(rem0, rem1, b0, b1, &rem0, &rem1);
}
rem0 = (rem0 << 32) | (rem1 >> 32);
tmp = rem0;
do_div(tmp, b0);
z |= (b0 << 32 <= rem0) ? 0xFFFFFFFF : tmp;
return z;
}
void mul64To128(bits64 a, bits64 b, bits64 * z0Ptr, bits64 * z1Ptr)
{
bits32 aHigh, aLow, bHigh, bLow;
bits64 z0, zMiddleA, zMiddleB, z1;
aLow = a;
aHigh = a >> 32;
bLow = b;
bHigh = b >> 32;
z1 = ((bits64) aLow) * bLow;
zMiddleA = ((bits64) aLow) * bHigh;
zMiddleB = ((bits64) aHigh) * bLow;
z0 = ((bits64) aHigh) * bHigh;
zMiddleA += zMiddleB;
z0 += (((bits64) (zMiddleA < zMiddleB)) << 32) + (zMiddleA >> 32);
zMiddleA <<= 32;
z1 += zMiddleA;
z0 += (z1 < zMiddleA);
*z1Ptr = z1;
*z0Ptr = z0;
}
static void normalizeFloat32Subnormal(bits32 aSig, int16 * zExpPtr,
bits32 * zSigPtr)
{
int8 shiftCount;
shiftCount = countLeadingZeros32(aSig) - 8;
*zSigPtr = aSig << shiftCount;
*zExpPtr = 1 - shiftCount;
}
float64 float64_div(float64 a, float64 b)
{
flag aSign, bSign, zSign;
int16 aExp, bExp, zExp;
bits64 aSig, bSig, zSig;
bits64 rem0, rem1;
bits64 term0, term1;
aSig = extractFloat64Frac(a);
aExp = extractFloat64Exp(a);
aSign = extractFloat64Sign(a);
bSig = extractFloat64Frac(b);
bExp = extractFloat64Exp(b);
bSign = extractFloat64Sign(b);
zSign = aSign ^ bSign;
if (aExp == 0x7FF) {
if (bExp == 0x7FF) {
}
return packFloat64(zSign, 0x7FF, 0);
}
if (bExp == 0x7FF) {
return packFloat64(zSign, 0, 0);
}
if (bExp == 0) {
if (bSig == 0) {
if ((aExp | aSig) == 0) {
float_raise(FPSCR_CAUSE_INVALID);
}
return packFloat64(zSign, 0x7FF, 0);
}
normalizeFloat64Subnormal(bSig, &bExp, &bSig);
}
if (aExp == 0) {
if (aSig == 0)
return packFloat64(zSign, 0, 0);
normalizeFloat64Subnormal(aSig, &aExp, &aSig);
}
zExp = aExp - bExp + 0x3FD;
aSig = (aSig | LIT64(0x0010000000000000)) << 10;
bSig = (bSig | LIT64(0x0010000000000000)) << 11;
if (bSig <= (aSig + aSig)) {
aSig >>= 1;
++zExp;
}
zSig = estimateDiv128To64(aSig, 0, bSig);
if ((zSig & 0x1FF) <= 2) {
mul64To128(bSig, zSig, &term0, &term1);
sub128(aSig, 0, term0, term1, &rem0, &rem1);
while ((sbits64) rem0 < 0) {
--zSig;
add128(rem0, rem1, 0, bSig, &rem0, &rem1);
}
zSig |= (rem1 != 0);
}
return roundAndPackFloat64(zSign, zExp, zSig);
}
float32 float32_div(float32 a, float32 b)
{
flag aSign, bSign, zSign;
int16 aExp, bExp, zExp;
bits32 aSig, bSig;
uint64_t zSig;
aSig = extractFloat32Frac(a);
aExp = extractFloat32Exp(a);
aSign = extractFloat32Sign(a);
bSig = extractFloat32Frac(b);
bExp = extractFloat32Exp(b);
bSign = extractFloat32Sign(b);
zSign = aSign ^ bSign;
if (aExp == 0xFF) {
if (bExp == 0xFF) {
}
return packFloat32(zSign, 0xFF, 0);
}
if (bExp == 0xFF) {
return packFloat32(zSign, 0, 0);
}
if (bExp == 0) {
if (bSig == 0) {
return packFloat32(zSign, 0xFF, 0);
}
normalizeFloat32Subnormal(bSig, &bExp, &bSig);
}
if (aExp == 0) {
if (aSig == 0)
return packFloat32(zSign, 0, 0);
normalizeFloat32Subnormal(aSig, &aExp, &aSig);
}
zExp = aExp - bExp + 0x7D;
aSig = (aSig | 0x00800000) << 7;
bSig = (bSig | 0x00800000) << 8;
if (bSig <= (aSig + aSig)) {
aSig >>= 1;
++zExp;
}
zSig = (((bits64) aSig) << 32);
do_div(zSig, bSig);
if ((zSig & 0x3F) == 0) {
zSig |= (((bits64) bSig) * zSig != ((bits64) aSig) << 32);
}
return roundAndPackFloat32(zSign, zExp, (bits32)zSig);
}
float32 float32_mul(float32 a, float32 b)
{
char aSign, bSign, zSign;
int aExp, bExp, zExp;
unsigned int aSig, bSig;
unsigned long long zSig64;
unsigned int zSig;
aSig = extractFloat32Frac(a);
aExp = extractFloat32Exp(a);
aSign = extractFloat32Sign(a);
bSig = extractFloat32Frac(b);
bExp = extractFloat32Exp(b);
bSign = extractFloat32Sign(b);
zSign = aSign ^ bSign;
if (aExp == 0) {
if (aSig == 0)
return packFloat32(zSign, 0, 0);
normalizeFloat32Subnormal(aSig, &aExp, &aSig);
}
if (bExp == 0) {
if (bSig == 0)
return packFloat32(zSign, 0, 0);
normalizeFloat32Subnormal(bSig, &bExp, &bSig);
}
if ((bExp == 0xff && bSig == 0) || (aExp == 0xff && aSig == 0))
return roundAndPackFloat32(zSign, 0xff, 0);
zExp = aExp + bExp - 0x7F;
aSig = (aSig | 0x00800000) << 7;
bSig = (bSig | 0x00800000) << 8;
shift64RightJamming(((unsigned long long)aSig) * bSig, 32, &zSig64);
zSig = zSig64;
if (0 <= (signed int)(zSig << 1)) {
zSig <<= 1;
--zExp;
}
return roundAndPackFloat32(zSign, zExp, zSig);
}
float64 float64_mul(float64 a, float64 b)
{
char aSign, bSign, zSign;
int aExp, bExp, zExp;
unsigned long long int aSig, bSig, zSig0, zSig1;
aSig = extractFloat64Frac(a);
aExp = extractFloat64Exp(a);
aSign = extractFloat64Sign(a);
bSig = extractFloat64Frac(b);
bExp = extractFloat64Exp(b);
bSign = extractFloat64Sign(b);
zSign = aSign ^ bSign;
if (aExp == 0) {
if (aSig == 0)
return packFloat64(zSign, 0, 0);
normalizeFloat64Subnormal(aSig, &aExp, &aSig);
}
if (bExp == 0) {
if (bSig == 0)
return packFloat64(zSign, 0, 0);
normalizeFloat64Subnormal(bSig, &bExp, &bSig);
}
if ((aExp == 0x7ff && aSig == 0) || (bExp == 0x7ff && bSig == 0))
return roundAndPackFloat64(zSign, 0x7ff, 0);
zExp = aExp + bExp - 0x3FF;
aSig = (aSig | 0x0010000000000000LL) << 10;
bSig = (bSig | 0x0010000000000000LL) << 11;
mul64To128(aSig, bSig, &zSig0, &zSig1);
zSig0 |= (zSig1 != 0);
if (0 <= (signed long long int)(zSig0 << 1)) {
zSig0 <<= 1;
--zExp;
}
return roundAndPackFloat64(zSign, zExp, zSig0);
}
/*
* -------------------------------------------------------------------------------
* Returns the result of converting the double-precision floating-point value
* `a' to the single-precision floating-point format. The conversion is
* performed according to the IEC/IEEE Standard for Binary Floating-point
* Arithmetic.
* -------------------------------------------------------------------------------
* */
float32 float64_to_float32(float64 a)
{
flag aSign;
int16 aExp;
bits64 aSig;
bits32 zSig;
aSig = extractFloat64Frac( a );
aExp = extractFloat64Exp( a );
aSign = extractFloat64Sign( a );
shift64RightJamming( aSig, 22, &aSig );
zSig = aSig;
if ( aExp || zSig ) {
zSig |= 0x40000000;
aExp -= 0x381;
}
return roundAndPackFloat32(aSign, aExp, zSig);
}
| gpl-2.0 |
bigzz/s3c-u-boot-1.1.6 | rtc/ds1374.c | 37 | 7188 | /*
* (C) Copyright 2001, 2002, 2003
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
* Keith Outwater, keith_outwater@mvis.com`
* Steven Scholz, steven.scholz@imc-berlin.de
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
/*
* Date & Time support (no alarms) for Dallas Semiconductor (now Maxim)
* DS1374 Real Time Clock (RTC).
*
* based on ds1337.c
*/
#include <common.h>
#include <command.h>
#include <rtc.h>
#include <i2c.h>
#if (defined(CONFIG_RTC_DS1374)) && (CONFIG_COMMANDS & CFG_CMD_DATE)
/*---------------------------------------------------------------------*/
#undef DEBUG_RTC
#define DEBUG_RTC
#ifdef DEBUG_RTC
#define DEBUGR(fmt,args...) printf(fmt ,##args)
#else
#define DEBUGR(fmt,args...)
#endif
/*---------------------------------------------------------------------*/
#ifndef CFG_I2C_RTC_ADDR
# define CFG_I2C_RTC_ADDR 0x68
#endif
#if defined(CONFIG_RTC_DS1374) && (CFG_I2C_SPEED > 400000)
# error The DS1374 is specified up to 400kHz in fast mode!
#endif
/*
* RTC register addresses
*/
#define RTC_TOD_CNT_BYTE0_ADDR 0x00 /* TimeOfDay */
#define RTC_TOD_CNT_BYTE1_ADDR 0x01
#define RTC_TOD_CNT_BYTE2_ADDR 0x02
#define RTC_TOD_CNT_BYTE3_ADDR 0x03
#define RTC_WD_ALM_CNT_BYTE0_ADDR 0x04
#define RTC_WD_ALM_CNT_BYTE1_ADDR 0x05
#define RTC_WD_ALM_CNT_BYTE2_ADDR 0x06
#define RTC_CTL_ADDR 0x07 /* RTC-CoNTrol-register */
#define RTC_SR_ADDR 0x08 /* RTC-StatusRegister */
#define RTC_TCS_DS_ADDR 0x09 /* RTC-TrickleChargeSelect DiodeSelect-register */
#define RTC_CTL_BIT_AIE (1<<0) /* Bit 0 - Alarm Interrupt enable */
#define RTC_CTL_BIT_RS1 (1<<1) /* Bit 1/2 - Rate Select square wave output */
#define RTC_CTL_BIT_RS2 (1<<2) /* Bit 2/2 - Rate Select square wave output */
#define RTC_CTL_BIT_WDSTR (1<<3) /* Bit 3 - Watchdog Reset Steering */
#define RTC_CTL_BIT_BBSQW (1<<4) /* Bit 4 - Battery-Backed Square-Wave */
#define RTC_CTL_BIT_WD_ALM (1<<5) /* Bit 5 - Watchdoc/Alarm Counter Select */
#define RTC_CTL_BIT_WACE (1<<6) /* Bit 6 - Watchdog/Alarm Counter Enable WACE*/
#define RTC_CTL_BIT_EN_OSC (1<<7) /* Bit 7 - Enable Oscilator */
#define RTC_SR_BIT_AF 0x01 /* Bit 0 = Alarm Flag */
#define RTC_SR_BIT_OSF 0x80 /* Bit 7 - Osc Stop Flag */
typedef unsigned char boolean_t;
#ifndef TRUE
#define TRUE ((boolean_t)(0==0))
#endif
#ifndef FALSE
#define FALSE (!TRUE)
#endif
const char RtcTodAddr[] = {
RTC_TOD_CNT_BYTE0_ADDR,
RTC_TOD_CNT_BYTE1_ADDR,
RTC_TOD_CNT_BYTE2_ADDR,
RTC_TOD_CNT_BYTE3_ADDR
};
static uchar rtc_read (uchar reg);
static void rtc_write (uchar reg, uchar val, boolean_t set);
static void rtc_write_raw (uchar reg, uchar val);
/*
* Get the current time from the RTC
*/
void rtc_get (struct rtc_time *tm){
unsigned long time1, time2;
unsigned int limit;
unsigned char tmp;
unsigned int i;
/*
* Since the reads are being performed one byte at a time,
* there is a chance that a carry will occur during the read.
* To detect this, 2 reads are performed and compared.
*/
limit = 10;
do {
i = 4;
time1 = 0;
while (i--) {
tmp = rtc_read(RtcTodAddr[i]);
time1 = (time1 << 8) | (tmp & 0xff);
}
i = 4;
time2 = 0;
while (i--) {
tmp = rtc_read(RtcTodAddr[i]);
time2 = (time2 << 8) | (tmp & 0xff);
}
} while ((time1 != time2) && limit--);
if (time1 != time2) {
printf("can't get consistent time from rtc chip\n");
}
DEBUGR ("Get RTC s since 1.1.1970: %d\n", time1);
to_tm(time1, tm); /* To Gregorian Date */
if (rtc_read(RTC_SR_ADDR) & RTC_SR_BIT_OSF)
printf ("### Warning: RTC oscillator has stopped\n");
DEBUGR ("Get DATE: %4d-%02d-%02d (wday=%d) TIME: %2d:%02d:%02d\n",
tm->tm_year, tm->tm_mon, tm->tm_mday, tm->tm_wday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
}
/*
* Set the RTC
*/
void rtc_set (struct rtc_time *tmp){
unsigned long time;
unsigned i;
DEBUGR ("Set DATE: %4d-%02d-%02d (wday=%d) TIME: %2d:%02d:%02d\n",
tmp->tm_year, tmp->tm_mon, tmp->tm_mday, tmp->tm_wday,
tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
if (tmp->tm_year < 1970 || tmp->tm_year > 2069)
printf("WARNING: year should be between 1970 and 2069!\n");
time = mktime(tmp->tm_year, tmp->tm_mon,
tmp->tm_mday, tmp->tm_hour,
tmp->tm_min, tmp->tm_sec);
DEBUGR ("Set RTC s since 1.1.1970: %d (0x%02x)\n", time, time);
/* write to RTC_TOD_CNT_BYTEn_ADDR */
for (i = 0; i <= 3; i++) {
rtc_write_raw(RtcTodAddr[i], (unsigned char)(time & 0xff));
time = time >> 8;
}
/* Start clock */
rtc_write(RTC_CTL_ADDR, RTC_CTL_BIT_EN_OSC, FALSE);
}
/*
* Reset the RTC. We setting the date back to 1970-01-01.
* We also enable the oscillator output on the SQW/OUT pin and program
* it for 32,768 Hz output. Note that according to the datasheet, turning
* on the square wave output increases the current drain on the backup
* battery to something between 480nA and 800nA.
*/
void rtc_reset (void){
struct rtc_time tmp;
/* clear status flags */
rtc_write (RTC_SR_ADDR, (RTC_SR_BIT_AF|RTC_SR_BIT_OSF), FALSE); /* clearing OSF and AF */
/* Initialise DS1374 oriented to MPC8349E-ADS */
rtc_write (RTC_CTL_ADDR, (RTC_CTL_BIT_EN_OSC
|RTC_CTL_BIT_WACE
|RTC_CTL_BIT_AIE), FALSE);/* start osc, disable WACE, clear AIE
- set to 0 */
rtc_write (RTC_CTL_ADDR, (RTC_CTL_BIT_WD_ALM
|RTC_CTL_BIT_WDSTR
|RTC_CTL_BIT_RS1
|RTC_CTL_BIT_RS2
|RTC_CTL_BIT_BBSQW), TRUE);/* disable WD/ALM, WDSTR set to INT-pin,
set BBSQW and SQW to 32k
- set to 1 */
tmp.tm_year = 1970;
tmp.tm_mon = 1;
tmp.tm_mday= 1;
tmp.tm_hour = 0;
tmp.tm_min = 0;
tmp.tm_sec = 0;
rtc_set(&tmp);
printf("RTC: %4d-%02d-%02d %2d:%02d:%02d UTC\n",
tmp.tm_year, tmp.tm_mon, tmp.tm_mday,
tmp.tm_hour, tmp.tm_min, tmp.tm_sec);
rtc_write(RTC_WD_ALM_CNT_BYTE2_ADDR,0xAC, TRUE);
rtc_write(RTC_WD_ALM_CNT_BYTE1_ADDR,0xDE, TRUE);
rtc_write(RTC_WD_ALM_CNT_BYTE2_ADDR,0xAD, TRUE);
}
/*
* Helper functions
*/
static uchar rtc_read (uchar reg)
{
return (i2c_reg_read (CFG_I2C_RTC_ADDR, reg));
}
static void rtc_write (uchar reg, uchar val, boolean_t set)
{
if (set == TRUE) {
val |= i2c_reg_read (CFG_I2C_RTC_ADDR, reg);
i2c_reg_write (CFG_I2C_RTC_ADDR, reg, val);
} else {
val = i2c_reg_read (CFG_I2C_RTC_ADDR, reg) & ~val;
i2c_reg_write (CFG_I2C_RTC_ADDR, reg, val);
}
}
static void rtc_write_raw (uchar reg, uchar val)
{
i2c_reg_write (CFG_I2C_RTC_ADDR, reg, val);
}
#endif /* (CONFIG_RTC_DS1374) && (CFG_COMMANDS & CFG_CMD_DATE) */
| gpl-2.0 |
Ca1ne/Enoch213 | arch/arm/mach-msm/subsystem_restart.c | 37 | 22397 | /* Copyright (c) 2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#define pr_fmt(fmt) "subsys-restart: %s(): " fmt, __func__
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/uaccess.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/proc_fs.h>
#include <linux/delay.h>
#include <linux/list.h>
#include <linux/io.h>
#include <linux/kthread.h>
#include <linux/time.h>
#include <asm/current.h>
#include <mach/peripheral-loader.h>
#include <mach/scm.h>
#include <mach/socinfo.h>
#include <mach/subsystem_notif.h>
#include <mach/subsystem_restart.h>
#include "smd_private.h"
#include <mach/restart.h>
#include <mach/board_htc.h>
#include <mach/msm_smsm.h>
#include <mach/pm.h>
struct subsys_soc_restart_order {
const char * const *subsystem_list;
int count;
struct mutex shutdown_lock;
struct mutex powerup_lock;
struct subsys_data *subsys_ptrs[];
};
struct restart_thread_data {
struct subsys_data *subsys;
int coupled;
};
struct restart_log {
struct timeval time;
struct subsys_data *subsys;
struct list_head list;
};
static int restart_level;
static int enable_ramdumps;
static wait_queue_head_t subsystem_restart_wq;
static char subsystem_restart_reason[256];
static int modem_restart_count = 0;
static int riva_restart_count = 0;
static int lpass_restart_count = 0;
static enum {
SUBSYSTEM_RESTART_STATE_NONE,
SUBSYSTEM_RESTART_STATE_ACTION,
} subsystem_restart_state;
static LIST_HEAD(restart_log_list);
static LIST_HEAD(subsystem_list);
static DEFINE_MUTEX(subsystem_list_lock);
static DEFINE_MUTEX(soc_order_reg_lock);
static DEFINE_MUTEX(restart_log_mutex);
/* SOC specific restart orders go here */
#define DEFINE_SINGLE_RESTART_ORDER(name, order) \
static struct subsys_soc_restart_order __##name = { \
.subsystem_list = order, \
.count = ARRAY_SIZE(order), \
.subsys_ptrs = {[ARRAY_SIZE(order)] = NULL} \
}; \
static struct subsys_soc_restart_order *name[] = { \
&__##name, \
}
/* MSM 8x60 restart ordering info */
static const char * const _order_8x60_all[] = {
"external_modem", "modem", "lpass"
};
DEFINE_SINGLE_RESTART_ORDER(orders_8x60_all, _order_8x60_all);
static const char * const _order_8x60_modems[] = {"external_modem", "modem"};
DEFINE_SINGLE_RESTART_ORDER(orders_8x60_modems, _order_8x60_modems);
/* MSM 8960 restart ordering info */
static const char * const order_8960[] = {"modem", "lpass"};
static struct subsys_soc_restart_order restart_orders_8960_one = {
.subsystem_list = order_8960,
.count = ARRAY_SIZE(order_8960),
.subsys_ptrs = {[ARRAY_SIZE(order_8960)] = NULL}
};
static struct subsys_soc_restart_order *restart_orders_8960[] = {
&restart_orders_8960_one,
};
/* These will be assigned to one of the sets above after
* runtime SoC identification.
*/
static struct subsys_soc_restart_order **restart_orders;
static int n_restart_orders;
module_param(enable_ramdumps, int, S_IRUGO | S_IWUSR);
static struct subsys_soc_restart_order *_update_restart_order(
struct subsys_data *subsys);
int get_restart_level()
{
return restart_level;
}
EXPORT_SYMBOL(get_restart_level);
int ssr_have_set_restart_reason;
void ssr_set_restart_reason(char *reason)
{
set_ramdump_reason(reason);
ssr_have_set_restart_reason = 1;
}
EXPORT_SYMBOL(ssr_set_restart_reason);
static void restart_level_changed(void)
{
struct subsys_data *subsys;
if (cpu_is_msm8x60() && restart_level == RESET_SUBSYS_COUPLED) {
restart_orders = orders_8x60_all;
n_restart_orders = ARRAY_SIZE(orders_8x60_all);
}
if (cpu_is_msm8x60() && restart_level == RESET_SUBSYS_MIXED) {
restart_orders = orders_8x60_modems;
n_restart_orders = ARRAY_SIZE(orders_8x60_modems);
}
mutex_lock(&subsystem_list_lock);
list_for_each_entry(subsys, &subsystem_list, list)
subsys->restart_order = _update_restart_order(subsys);
mutex_unlock(&subsystem_list_lock);
}
static int restart_level_set(const char *val, struct kernel_param *kp)
{
int ret;
int old_val = restart_level;
if (cpu_is_msm9615()) {
pr_err("Only Phase 1 subsystem restart is supported\n");
return -EINVAL;
}
ret = param_set_int(val, kp);
if (ret)
return ret;
switch (restart_level) {
case RESET_SOC:
case RESET_SUBSYS_COUPLED:
case RESET_SUBSYS_INDEPENDENT:
pr_info("Phase %d behavior activated.\n", restart_level);
break;
case RESET_SUBSYS_MIXED:
pr_info("Phase 2+ behavior activated.\n");
break;
case RESET_NONE:
pr_info("Subsystem restart deactivated\n");
break;
default:
restart_level = old_val;
return -EINVAL;
break;
}
if (restart_level != old_val)
restart_level_changed();
return 0;
}
module_param_call(restart_level, restart_level_set, param_get_int,
&restart_level, 0644);
static struct subsys_data *_find_subsystem(const char *subsys_name)
{
struct subsys_data *subsys;
mutex_lock(&subsystem_list_lock);
list_for_each_entry(subsys, &subsystem_list, list)
if (!strncmp(subsys->name, subsys_name,
SUBSYS_NAME_MAX_LENGTH)) {
mutex_unlock(&subsystem_list_lock);
return subsys;
}
mutex_unlock(&subsystem_list_lock);
return NULL;
}
static struct subsys_soc_restart_order *_update_restart_order(
struct subsys_data *subsys)
{
int i, j;
if (!subsys)
return NULL;
if (!subsys->name)
return NULL;
mutex_lock(&soc_order_reg_lock);
for (j = 0; j < n_restart_orders; j++) {
for (i = 0; i < restart_orders[j]->count; i++)
if (!strncmp(restart_orders[j]->subsystem_list[i],
subsys->name, SUBSYS_NAME_MAX_LENGTH)) {
restart_orders[j]->subsys_ptrs[i] =
subsys;
mutex_unlock(&soc_order_reg_lock);
return restart_orders[j];
}
}
mutex_unlock(&soc_order_reg_lock);
return NULL;
}
static void _send_notification_to_order(struct subsys_data
**restart_list, int count,
enum subsys_notif_type notif_type)
{
int i;
for (i = 0; i < count; i++)
if (restart_list[i])
subsys_notif_queue_notification(
restart_list[i]->notif_handle, notif_type);
}
static int max_restarts;
module_param(max_restarts, int, 0644);
static long max_history_time = 3600;
module_param(max_history_time, long, 0644);
static void do_epoch_check(struct subsys_data *subsys)
{
int n = 0;
struct timeval *time_first = NULL, *curr_time;
struct restart_log *r_log, *temp;
static int max_restarts_check;
static long max_history_time_check;
mutex_lock(&restart_log_mutex);
max_restarts_check = max_restarts;
max_history_time_check = max_history_time;
/* Check if epoch checking is enabled */
if (!max_restarts_check)
goto out;
r_log = kmalloc(sizeof(struct restart_log), GFP_KERNEL);
if (!r_log)
goto out;
r_log->subsys = subsys;
do_gettimeofday(&r_log->time);
curr_time = &r_log->time;
INIT_LIST_HEAD(&r_log->list);
list_add_tail(&r_log->list, &restart_log_list);
list_for_each_entry_safe(r_log, temp, &restart_log_list, list) {
if ((curr_time->tv_sec - r_log->time.tv_sec) >
max_history_time_check) {
pr_debug("Deleted node with restart_time = %ld\n",
r_log->time.tv_sec);
list_del(&r_log->list);
kfree(r_log);
continue;
}
if (!n) {
time_first = &r_log->time;
pr_debug("Time_first: %ld\n", time_first->tv_sec);
}
n++;
pr_debug("Restart_time: %ld\n", r_log->time.tv_sec);
}
if (time_first && n >= max_restarts_check) {
if ((curr_time->tv_sec - time_first->tv_sec) <
max_history_time_check)
panic("Subsystems have crashed %d times in less than "
"%ld seconds!", max_restarts_check,
max_history_time_check);
}
out:
mutex_unlock(&restart_log_mutex);
}
static int subsystem_restart_thread(void *data)
{
struct restart_thread_data *r_work = data;
struct subsys_data **restart_list;
struct subsys_data *subsys = r_work->subsys;
struct subsys_soc_restart_order *soc_restart_order = NULL;
struct mutex *powerup_lock;
struct mutex *shutdown_lock;
int i;
int restart_list_count = 0;
if (r_work->coupled)
soc_restart_order = subsys->restart_order;
/* It's OK to not take the registration lock at this point.
* This is because the subsystem list inside the relevant
* restart order is not being traversed.
*/
if (!soc_restart_order) {
restart_list = subsys->single_restart_list;
restart_list_count = 1;
powerup_lock = &subsys->powerup_lock;
shutdown_lock = &subsys->shutdown_lock;
} else {
restart_list = soc_restart_order->subsys_ptrs;
restart_list_count = soc_restart_order->count;
powerup_lock = &soc_restart_order->powerup_lock;
shutdown_lock = &soc_restart_order->shutdown_lock;
}
pr_debug("[%p]: Attempting to get shutdown lock!\n", current);
/* Try to acquire shutdown_lock. If this fails, these subsystems are
* already being restarted - return.
*/
if (!mutex_trylock(shutdown_lock)) {
kfree(data);
do_exit(0);
}
pr_debug("[%p]: Attempting to get powerup lock!\n", current);
/* Now that we've acquired the shutdown lock, either we're the first to
* restart these subsystems or some other thread is doing the powerup
* sequence for these subsystems. In the latter case, panic and bail
* out, since a subsystem died in its powerup sequence.
*/
if (!mutex_trylock(powerup_lock))
panic("%s[%p]: Subsystem died during powerup!",
__func__, current);
do_epoch_check(subsys);
/* Now it is necessary to take the registration lock. This is because
* the subsystem list in the SoC restart order will be traversed
* and it shouldn't be changed until _this_ restart sequence completes.
*/
mutex_lock(&soc_order_reg_lock);
pr_debug("[%p]: Starting restart sequence for %s\n", current,
r_work->subsys->name);
_send_notification_to_order(restart_list,
restart_list_count,
SUBSYS_BEFORE_SHUTDOWN);
for (i = 0; i < restart_list_count; i++) {
if (!restart_list[i])
continue;
pr_info("[%p]: Shutting down %s\n", current,
restart_list[i]->name);
if (restart_list[i]->shutdown(subsys) < 0)
panic("subsys-restart: %s[%p]: Failed to shutdown %s!",
__func__, current, restart_list[i]->name);
}
_send_notification_to_order(restart_list, restart_list_count,
SUBSYS_AFTER_SHUTDOWN);
/* Now that we've finished shutting down these subsystems, release the
* shutdown lock. If a subsystem restart request comes in for a
* subsystem in _this_ restart order after the unlock below, and
* before the powerup lock is released, panic and bail out.
*/
mutex_unlock(shutdown_lock);
/* Collect ram dumps for all subsystems in order here */
for (i = 0; i < restart_list_count; i++) {
if (!restart_list[i])
continue;
if (restart_list[i]->ramdump)
if (restart_list[i]->ramdump(enable_ramdumps,
subsys) < 0)
pr_warn("%s[%p]: Ramdump failed.\n",
restart_list[i]->name, current);
}
_send_notification_to_order(restart_list,
restart_list_count,
SUBSYS_BEFORE_POWERUP);
for (i = restart_list_count - 1; i >= 0; i--) {
if (!restart_list[i])
continue;
pr_info("[%p]: Powering up %s\n", current,
restart_list[i]->name);
/* QCA debug + */
if (strcmp(restart_list[i]->name, "riva")==0) {
pr_info("[WLAN][%p]: delay 1 seconds calling power up callback %s\n", current,
restart_list[i]->name);
mdelay(1000);
}
/* QCA debug - */
if (restart_list[i]->powerup(subsys) < 0)
panic("%s[%p]: Failed to powerup %s!", __func__,
current, restart_list[i]->name);
/* QCA debug + */
if (strcmp(restart_list[i]->name, "riva")==0) {
pr_info("[WLAN][%p]: Powering up finished. delay 1 seconds %s\n", current,
restart_list[i]->name);
mdelay(1000);
}
/* QCA debug - */
}
_send_notification_to_order(restart_list,
restart_list_count,
SUBSYS_AFTER_POWERUP);
pr_info("[%p]: Restart sequence for %s completed.\n",
current, r_work->subsys->name);
mutex_unlock(powerup_lock);
mutex_unlock(&soc_order_reg_lock);
pr_debug("[%p]: Released powerup lock!\n", current);
kfree(data);
do_exit(0);
}
static void show_subsystem_restart_count(const char *subsys_name)
{
if(!strncmp(subsys_name, "modem", SUBSYS_NAME_MAX_LENGTH))
pr_info("Restarting %s [level=%d], modem_restart_count = %d!\n", subsys_name,
restart_level, ++modem_restart_count);
else if(!strncmp(subsys_name, "riva", SUBSYS_NAME_MAX_LENGTH))
pr_info("Restarting %s [level=%d], riva_restart_count = %d!\n", subsys_name,
restart_level, ++riva_restart_count);
else if(!strncmp(subsys_name, "lpass", SUBSYS_NAME_MAX_LENGTH))
pr_info("Restarting %s [level=%d], lpass_restart_count = %d!\n", subsys_name,
restart_level, ++lpass_restart_count);
else
pr_info("Restarting %s [level=%d]!\n", subsys_name,
restart_level);
}
int subsystem_restart(const char *subsys_name)
{
struct subsys_data *subsys;
struct task_struct *tsk;
struct restart_thread_data *data = NULL;
char restart_reason[256];
if (!subsys_name) {
pr_err("Invalid subsystem name.\n");
return -EINVAL;
}
pr_info("Restart sequence requested for %s, restart_level = %d.\n",
subsys_name, restart_level);
/* List of subsystems is protected by a lock. New subsystems can
* still come in.
*/
subsys = _find_subsystem(subsys_name);
if (!subsys) {
pr_warn("Unregistered subsystem %s!\n", subsys_name);
return -EINVAL;
}
if (restart_level != RESET_SOC && restart_level != RESET_NONE) {
/* Check independent SSR enable status here */
#if defined(CONFIG_MSM_SSR_INDEPENDENT)
if ((!subsys->enable_ssr) ||
((get_radio_flag() & 0x8) && (!(get_kernel_flag() & KERNEL_FLAG_ENABLE_SSR_MODEM)) && (!strncmp(subsys_name, "modem", SUBSYS_NAME_MAX_LENGTH))) ||
(get_restart_reason() == RESTART_REASON_RIL_FATAL)) {
#else
if (!subsys->enable_ssr) {
#endif
restart_level = RESET_SOC;
pr_warn("%s: %s did not enable SSR, reset SOC instead.\n",
__func__, subsys_name);
} else {
data = kzalloc(sizeof(struct restart_thread_data), GFP_KERNEL);
if (!data) {
restart_level = RESET_SOC;
pr_warn("Failed to alloc restart data. Resetting.\n");
} else {
if (restart_level == RESET_SUBSYS_COUPLED ||
restart_level == RESET_SUBSYS_MIXED)
data->coupled = 1;
else
data->coupled = 0;
data->subsys = subsys;
}
}
}
switch (restart_level) {
case RESET_SUBSYS_COUPLED:
case RESET_SUBSYS_MIXED:
case RESET_SUBSYS_INDEPENDENT:
show_subsystem_restart_count(subsys_name);
if (!strncmp(subsys_name, "modem",
SUBSYS_NAME_MAX_LENGTH)) {
/* If fatal was called by modem, check for reset reason in
* shared memory and overwrite any current reset reason
* if modem has provided a reset reason.
*/
smd_diag_ssr(subsystem_restart_reason);
}
else
{
/* Only print "<subsystem name> fatal" when no reset
* reason has been set by any subsystem.
*/
sprintf(subsystem_restart_reason, "%s fatal", subsys_name);
pr_info("%s: %s\n", __func__, subsystem_restart_reason);
}
subsystem_restart_state = SUBSYSTEM_RESTART_STATE_ACTION;
wake_up(&subsystem_restart_wq);
/* Let the kthread handle the actual restarting. Using a
* workqueue will not work since all restart requests are
* serialized and it prevents the short circuiting of
* restart requests for subsystems already in a restart
* sequence.
*/
tsk = kthread_run(subsystem_restart_thread, data,
"subsystem_restart_thread");
if (IS_ERR(tsk))
panic("%s: Unable to create thread to restart %s",
__func__, subsys->name);
break;
case RESET_SOC:
/* If fatal was called by modem, check for reset reason in
* shared memory and overwrite any current reset reason
* if modem has provided a reset reason.
*/
if (!strncmp(subsys_name, "modem",
SUBSYS_NAME_MAX_LENGTH)) {
smd_diag();
}
/* Only print "<subsystem name> fatal" when no reset
* reason has been set by any subsystem.
*/
if (!ssr_have_set_restart_reason) {
sprintf(restart_reason, "%s fatal", subsys_name);
ssr_set_restart_reason(restart_reason);
}
panic("subsys-restart: Resetting the SoC - %s crashed.",
subsys->name);
break;
case RESET_NONE:
pr_info("%s: restart_level set to RESET_NONE, skip reset.\n",
__func__);
break;
default:
panic("subsys-restart: Unknown restart level!\n");
break;
}
return 0;
}
EXPORT_SYMBOL(subsystem_restart);
int ssr_register_subsystem(struct subsys_data *subsys)
{
if (!subsys)
goto err;
if (!subsys->name)
goto err;
if (!subsys->powerup || !subsys->shutdown)
goto err;
subsys->notif_handle = subsys_notif_add_subsys(subsys->name);
subsys->restart_order = _update_restart_order(subsys);
subsys->single_restart_list[0] = subsys;
mutex_init(&subsys->shutdown_lock);
mutex_init(&subsys->powerup_lock);
mutex_lock(&subsystem_list_lock);
list_add(&subsys->list, &subsystem_list);
mutex_unlock(&subsystem_list_lock);
return 0;
err:
return -EINVAL;
}
EXPORT_SYMBOL(ssr_register_subsystem);
static int ssr_panic_handler(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct subsys_data *subsys;
list_for_each_entry(subsys, &subsystem_list, list)
if (subsys->crash_shutdown)
subsys->crash_shutdown(subsys);
return NOTIFY_DONE;
}
static struct notifier_block panic_nb = {
.notifier_call = ssr_panic_handler,
};
static int __init ssr_init_soc_restart_orders(void)
{
int i;
atomic_notifier_chain_register(&panic_notifier_list,
&panic_nb);
if (cpu_is_msm8x60()) {
for (i = 0; i < ARRAY_SIZE(orders_8x60_all); i++) {
mutex_init(&orders_8x60_all[i]->powerup_lock);
mutex_init(&orders_8x60_all[i]->shutdown_lock);
}
for (i = 0; i < ARRAY_SIZE(orders_8x60_modems); i++) {
mutex_init(&orders_8x60_modems[i]->powerup_lock);
mutex_init(&orders_8x60_modems[i]->shutdown_lock);
}
restart_orders = orders_8x60_all;
n_restart_orders = ARRAY_SIZE(orders_8x60_all);
}
if (cpu_is_msm8960() || cpu_is_msm8930() || cpu_is_msm9615()) {
restart_orders = restart_orders_8960;
n_restart_orders = ARRAY_SIZE(restart_orders_8960);
}
if (restart_orders == NULL || n_restart_orders < 1) {
WARN_ON(1);
return -EINVAL;
}
return 0;
}
static ssize_t subsystem_restart_reason_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
char *s = buf;
int ret;
ret = wait_event_interruptible(subsystem_restart_wq,
subsystem_restart_state != SUBSYSTEM_RESTART_STATE_NONE);
printk(KERN_INFO "%s: state = %d", __func__, subsystem_restart_state);
if (ret && subsystem_restart_state == SUBSYSTEM_RESTART_STATE_NONE)
return ret;
else
{
subsystem_restart_state = SUBSYSTEM_RESTART_STATE_NONE;
s += sprintf(buf, subsystem_restart_reason);
}
printk(KERN_INFO "%s: state = %d, buf = %s", __func__, subsystem_restart_state, buf);
return s - buf;
}
static ssize_t subsystem_restart_modem_trigger_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
char *s = buf;
int ret = 0;
if (get_kernel_flag() & KERNEL_FLAG_ENABLE_SSR_MODEM)
{
pr_info("%s: trigger modem restart\n", __func__);
ret = smsm_change_state_ssr(SMSM_APPS_STATE, 0, SMSM_RESET, KERNEL_FLAG_ENABLE_SSR_MODEM);
if(ret == 0)
pr_info("%s: set smsm state SMSM_RESET success\n", __func__);
else
{
pr_info("%s: set smsm state SMSM_RESET faild => ret = %d\n", __func__, ret);
s += sprintf(buf, "Failed");
return s - buf;
}
s += sprintf(buf, "Success");
}
else
{
pr_info("%s: kernel_flag = 0x%X\n", __func__, (int)get_kernel_flag());
s += sprintf(buf, "Please check whether kernel flag 6 is 0x800");
}
return s - buf;
}
static ssize_t subsystem_restart_wcnss_trigger_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
char *s = buf;
int ret = 0;
if (get_kernel_flag() & KERNEL_FLAG_ENABLE_SSR_WCNSS)
{
pr_info("%s: trigger wcnss restart\n", __func__);
ret = smsm_change_state_ssr(SMSM_APPS_STATE, 0, SMSM_RESET, KERNEL_FLAG_ENABLE_SSR_WCNSS);
if(ret == 0)
pr_info("%s: set smsm state SMSM_RESET success\n", __func__);
else
{
pr_info("%s: set smsm state SMSM_RESET faild => ret = %d\n", __func__, ret);
s += sprintf(buf, "Failed");
return s - buf;
}
s += sprintf(buf, "Success");
}
else
{
pr_info("%s: kernel_flag = 0x%X\n", __func__, (int)get_kernel_flag());
s += sprintf(buf, "Please check whether kernel flag 6 is 0x1000");
}
return s - buf;
}
#define subsystem_restart_ro_attr(_name) \
static struct kobj_attribute _name##_attr = { \
.attr = { \
.name = __stringify(_name), \
.mode = 0444, \
}, \
.show = _name##_show, \
.store = NULL, \
}
subsystem_restart_ro_attr(subsystem_restart_reason);
subsystem_restart_ro_attr(subsystem_restart_modem_trigger);
subsystem_restart_ro_attr(subsystem_restart_wcnss_trigger);
static struct attribute *g[] = {
&subsystem_restart_reason_attr.attr,
&subsystem_restart_modem_trigger_attr.attr,
&subsystem_restart_wcnss_trigger_attr.attr,
NULL,
};
static struct attribute_group attr_group = {
.attrs = g,
};
static int __init subsys_restart_init(void)
{
int ret = 0;
struct kobject *properties_kobj;
ssr_have_set_restart_reason = 0;
#if defined(CONFIG_MSM_SSR_INDEPENDENT)
if (board_mfg_mode() == 0)
restart_level = RESET_SUBSYS_INDEPENDENT;
else
restart_level = RESET_SOC;
#else
restart_level = RESET_SOC;
#endif
if (get_kernel_flag() & (KERNEL_FLAG_ENABLE_SSR_MODEM | KERNEL_FLAG_ENABLE_SSR_WCNSS))
restart_level = RESET_SUBSYS_INDEPENDENT;
pr_info("%s: restart_level set to %d, board_mfg_mode %d\n", __func__, restart_level, board_mfg_mode());
init_waitqueue_head(&subsystem_restart_wq);
subsystem_restart_state = SUBSYSTEM_RESTART_STATE_NONE;
properties_kobj = kobject_create_and_add("subsystem_restart_properties", NULL);
if (properties_kobj) {
ret = sysfs_create_group(properties_kobj, &attr_group);
if (ret) {
pr_err("subsys_restart_init: sysfs_create_group failed\n");
return ret;
}
}
ret = ssr_init_soc_restart_orders();
return ret;
}
arch_initcall(subsys_restart_init);
MODULE_DESCRIPTION("Subsystem Restart Driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
azbesthu/freya | memcheck/tests/origin6-fp.c | 37 | 2550 |
/* Test of origin tracking through floating point code and in the case
where there are large amounts of uninitialised data floating
around. This program creates 3 matrices of 2300x2300 doubles,
makes one value in them undefined, does arithmetic, and tests the
result, which is then undefined.
This also tests the secondary otag cache (ocacheL2), since the
amount of uninitialised data is somewhat over 43MB and it appears
that quite a lot of non-zero-otag lines are pushed into ocacheL2.
This program needs to be compiled with -O.
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "../memcheck.h"
double** alloc_square_array ( int nArr )
{
int i;
double** vec;
assert(nArr >= 1);
vec = malloc(nArr * sizeof(double*));
assert(vec);
for (i = 0; i < nArr; i++) {
vec[i] = malloc(nArr * sizeof(double));
assert(vec);
}
return vec;
}
double** do3x3smooth ( double** arr, int nArr )
{
int i, j;
double** out;
assert(nArr >= 3);
out = alloc_square_array(nArr - 2);
assert(out);
for (i = 1; i < nArr-1; i++) {
for (j = 1; j < nArr-1; j++) {
double s = arr[i-1][j-1] + arr[i-1][j ] + arr[i-1][j+1]
+ arr[i ][j-1] + arr[i ][j ] + arr[i ][j+1]
+ arr[i+1][j-1] + arr[i+1][j ] + arr[i+1][j+1];
out[i-1][j-1] = s / 9.0;
}
}
return out;
}
double sum ( double** arr, int nArr )
{
int i, j;
double s = 0.0;
assert(nArr >= 1);
for (i = 0; i < nArr; i++) {
for (j = 0; j < nArr; j++) {
s += arr[i][j];
}
}
return s;
}
void setup_arr ( /*OUT*/double** arr, int nArr )
{
int i, j;
assert(nArr >= 1);
for (i = 0; i < nArr; i++) {
for (j = 0; j < nArr; j++) {
arr[i][j] = (double)(i * j);
if (i == nArr/2 && j == nArr/2) {
unsigned char* p = (unsigned char*)&arr[i][j];
VALGRIND_MAKE_MEM_UNDEFINED(p, 1);
}
}
}
}
int main ( void )
{
int nArr = 2300;
int ri;
double r, **arr, **arr2, **arr3;
arr = alloc_square_array(nArr);
setup_arr( arr, nArr );
arr2 = do3x3smooth( arr, nArr );
arr3 = do3x3smooth( arr2, nArr-2 );
r = sum( arr3, nArr-4 );
/* Convert answer to int before testing it, so as to
guarantee there's only one conditional branch. */
if (0) fprintf(stderr, "r = %g\n", r );
r /= 10000.0;
ri = (int)r;
if (0) fprintf(stderr, "ri = %d\n", ri);
if (ri == 696565111) {
fprintf(stderr, "Test succeeded.\n");
} else {
fprintf(stderr, "Test FAILED !\n");
assert(0);
}
return 0;
}
| gpl-2.0 |
novic/AniDroid-Kernel-N7000 | drivers/media/video/exynos/gsc/gsc-regs.c | 37 | 16187 | /* linux/drivers/media/video/exynos/gsc/gsc-regs.c
*
* Copyright (c) 2011 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* Samsung EXYNOS5 SoC series G-scaler 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, either version 2 of the License,
* or (at your option) any later version.
*/
#include <linux/io.h>
#include <linux/delay.h>
#include <mach/map.h>
#include "gsc-core.h"
void gsc_hw_set_sw_reset(struct gsc_dev *dev)
{
u32 cfg = 0;
cfg |= GSC_SW_RESET_SRESET;
writel(cfg, dev->regs + GSC_SW_RESET);
}
void gsc_disp_fifo_sw_reset(struct gsc_dev *dev)
{
u32 cfg = readl(SYSREG_DISP1BLK_CFG);
/* DISPBLK1 FIFO S/W reset sequence
set FIFORST_DISP1 as 0 then, set FIFORST_DISP1 as 1 again */
cfg &= ~FIFORST_DISP1;
writel(cfg, SYSREG_DISP1BLK_CFG);
cfg |= FIFORST_DISP1;
writel(cfg, SYSREG_DISP1BLK_CFG);
}
void gsc_pixelasync_sw_reset(struct gsc_dev *dev)
{
u32 cfg = readl(SYSREG_GSCBLK_CFG0);
/* GSCBLK Pixel asyncy FIFO S/W reset sequence
set PXLASYNC_SW_RESET as 0 then, set PXLASYNC_SW_RESET as 1 again */
cfg &= ~GSC_PXLASYNC_RST(dev->id);
writel(cfg, SYSREG_GSCBLK_CFG0);
cfg |= GSC_PXLASYNC_RST(dev->id);
writel(cfg, SYSREG_GSCBLK_CFG0);
}
int gsc_wait_reset(struct gsc_dev *dev)
{
unsigned long timeo = jiffies + 10; /* timeout of 50ms */
u32 cfg;
while (time_before(jiffies, timeo)) {
cfg = readl(dev->regs + GSC_SW_RESET);
if (!cfg)
return 0;
usleep_range(10, 20);
}
gsc_dbg("wait time : %d ms", jiffies_to_msecs(jiffies - timeo + 20));
return -EBUSY;
}
int gsc_wait_operating(struct gsc_dev *dev)
{
unsigned long timeo = jiffies + 10; /* timeout of 50ms */
u32 cfg;
while (time_before(jiffies, timeo)) {
cfg = readl(dev->regs + GSC_ENABLE);
if ((cfg & GSC_ENABLE_OP_STATUS) == GSC_ENABLE_OP_STATUS)
return 0;
usleep_range(10, 20);
}
gsc_dbg("wait time : %d ms", jiffies_to_msecs(jiffies - timeo + 20));
return -EBUSY;
}
int gsc_wait_stop(struct gsc_dev *dev)
{
unsigned long timeo = jiffies + 10; /* timeout of 50ms */
u32 cfg;
while (time_before(jiffies, timeo)) {
cfg = readl(dev->regs + GSC_ENABLE);
if (!(cfg & GSC_ENABLE_OP_STATUS))
return 0;
usleep_range(10, 20);
}
gsc_dbg("wait time : %d ms", jiffies_to_msecs(jiffies - timeo + 20));
return -EBUSY;
}
void gsc_hw_set_one_frm_mode(struct gsc_dev *dev, bool mask)
{
u32 cfg;
cfg = readl(dev->regs + GSC_ENABLE);
if (mask)
cfg |= GSC_ENABLE_ON_CLEAR;
else
cfg &= ~GSC_ENABLE_ON_CLEAR;
writel(cfg, dev->regs + GSC_ENABLE);
}
int gsc_hw_get_input_buf_mask_status(struct gsc_dev *dev)
{
u32 cfg, status, bits = 0;
cfg = readl(dev->regs + GSC_IN_BASE_ADDR_Y_MASK);
status = cfg & GSC_IN_BASE_ADDR_MASK;
while (status) {
status = status & (status - 1);
bits++;
}
return bits;
}
int gsc_hw_get_done_input_buf_index(struct gsc_dev *dev)
{
u32 cfg, curr_index, i;
cfg = readl(dev->regs + GSC_IN_BASE_ADDR_Y_MASK);
curr_index = GSC_IN_CURR_GET_INDEX(cfg);
for (i = curr_index; i > 1; i--) {
if (cfg ^ (1 << (i - 2)))
return i - 2;
}
for (i = dev->variant->in_buf_cnt; i > curr_index; i--) {
if (cfg ^ (1 << (i -1)))
return i - 1;
}
return curr_index - 1;
}
int gsc_hw_get_done_output_buf_index(struct gsc_dev *dev)
{
u32 cfg, curr_index, done_buf_index;
unsigned long state_mask;
u32 reqbufs_cnt = dev->cap.reqbufs_cnt;
cfg = readl(dev->regs + GSC_OUT_BASE_ADDR_Y_MASK);
curr_index = GSC_OUT_CURR_GET_INDEX(cfg);
gsc_dbg("curr_index : %d", curr_index);
state_mask = cfg & GSC_OUT_BASE_ADDR_MASK;
done_buf_index = (curr_index == 0) ? reqbufs_cnt - 1: curr_index - 1;
do {
/* Test done_buf_index whether masking or not */
if (test_bit(done_buf_index, &state_mask))
done_buf_index = (done_buf_index == 0) ?
reqbufs_cnt - 1 : done_buf_index - 1;
else
return done_buf_index;
} while (done_buf_index != curr_index);
return -EBUSY;
}
void gsc_hw_set_frm_done_irq_mask(struct gsc_dev *dev, bool mask)
{
u32 cfg;
cfg = readl(dev->regs + GSC_IRQ);
if (mask)
cfg |= GSC_IRQ_FRMDONE_MASK;
else
cfg &= ~GSC_IRQ_FRMDONE_MASK;
writel(cfg, dev->regs + GSC_IRQ);
}
void gsc_hw_set_overflow_irq_mask(struct gsc_dev *dev, bool mask)
{
u32 cfg;
cfg = readl(dev->regs + GSC_IRQ);
if (mask)
cfg |= GSC_IRQ_OR_MASK;
else
cfg &= ~GSC_IRQ_OR_MASK;
writel(cfg, dev->regs + GSC_IRQ);
}
void gsc_hw_set_gsc_irq_enable(struct gsc_dev *dev, bool mask)
{
u32 cfg;
cfg = readl(dev->regs + GSC_IRQ);
if (mask)
cfg |= GSC_IRQ_ENABLE;
else
cfg &= ~GSC_IRQ_ENABLE;
writel(cfg, dev->regs + GSC_IRQ);
}
void gsc_hw_set_input_buf_mask_all(struct gsc_dev *dev)
{
u32 cfg;
cfg = readl(dev->regs + GSC_IN_BASE_ADDR_Y_MASK);
cfg |= GSC_IN_BASE_ADDR_MASK;
cfg |= GSC_IN_BASE_ADDR_PINGPONG(dev->variant->in_buf_cnt);
writel(cfg, dev->regs + GSC_IN_BASE_ADDR_Y_MASK);
writel(cfg, dev->regs + GSC_IN_BASE_ADDR_CB_MASK);
writel(cfg, dev->regs + GSC_IN_BASE_ADDR_CR_MASK);
}
void gsc_hw_set_output_buf_mask_all(struct gsc_dev *dev)
{
u32 cfg;
cfg = readl(dev->regs + GSC_OUT_BASE_ADDR_Y_MASK);
cfg |= GSC_OUT_BASE_ADDR_MASK;
cfg |= GSC_OUT_BASE_ADDR_PINGPONG(dev->variant->out_buf_cnt);
writel(cfg, dev->regs + GSC_OUT_BASE_ADDR_Y_MASK);
writel(cfg, dev->regs + GSC_OUT_BASE_ADDR_CB_MASK);
writel(cfg, dev->regs + GSC_OUT_BASE_ADDR_CR_MASK);
}
void gsc_hw_set_input_buf_masking(struct gsc_dev *dev, u32 shift,
bool enable)
{
u32 cfg = readl(dev->regs + GSC_IN_BASE_ADDR_Y_MASK);
u32 mask = 1 << shift;
cfg &= (~mask);
cfg |= enable << shift;
writel(cfg, dev->regs + GSC_IN_BASE_ADDR_Y_MASK);
writel(cfg, dev->regs + GSC_IN_BASE_ADDR_CB_MASK);
writel(cfg, dev->regs + GSC_IN_BASE_ADDR_CR_MASK);
}
void gsc_hw_set_output_buf_masking(struct gsc_dev *dev, u32 shift,
bool enable)
{
u32 cfg = readl(dev->regs + GSC_OUT_BASE_ADDR_Y_MASK);
u32 mask = 1 << shift;
cfg &= (~mask);
cfg |= enable << shift;
writel(cfg, dev->regs + GSC_OUT_BASE_ADDR_Y_MASK);
writel(cfg, dev->regs + GSC_OUT_BASE_ADDR_CB_MASK);
writel(cfg, dev->regs + GSC_OUT_BASE_ADDR_CR_MASK);
}
int gsc_hw_get_nr_unmask_bits(struct gsc_dev *dev)
{
u32 bits = 0;
u32 mask_bits = readl(dev->regs + GSC_OUT_BASE_ADDR_Y_MASK);
mask_bits &= GSC_OUT_BASE_ADDR_MASK;
while(mask_bits) {
mask_bits = mask_bits & (mask_bits - 1);
bits++;
}
bits = 16 - bits;
return bits;
}
void gsc_hw_set_input_addr(struct gsc_dev *dev, struct gsc_addr *addr,
int index)
{
gsc_dbg("src_buf[%d]: 0x%X, cb: 0x%X, cr: 0x%X", index,
addr->y, addr->cb, addr->cr);
writel(addr->y, dev->regs + GSC_IN_BASE_ADDR_Y(index));
writel(addr->cb, dev->regs + GSC_IN_BASE_ADDR_CB(index));
writel(addr->cr, dev->regs + GSC_IN_BASE_ADDR_CR(index));
}
void gsc_hw_set_output_addr(struct gsc_dev *dev,
struct gsc_addr *addr, int index)
{
gsc_dbg("dst_buf[%d]: 0x%X, cb: 0x%X, cr: 0x%X",
index, addr->y, addr->cb, addr->cr);
writel(addr->y, dev->regs + GSC_OUT_BASE_ADDR_Y(index));
writel(addr->cb, dev->regs + GSC_OUT_BASE_ADDR_CB(index));
writel(addr->cr, dev->regs + GSC_OUT_BASE_ADDR_CR(index));
}
void gsc_hw_set_input_path(struct gsc_ctx *ctx)
{
struct gsc_dev *dev = ctx->gsc_dev;
u32 cfg = readl(dev->regs + GSC_IN_CON);
cfg &= ~(GSC_IN_PATH_MASK | GSC_IN_LOCAL_SEL_MASK);
if (ctx->in_path == GSC_DMA) {
cfg |= GSC_IN_PATH_MEMORY;
} else {
cfg |= GSC_IN_PATH_LOCAL;
if (ctx->in_path == GSC_WRITEBACK) {
cfg |= GSC_IN_LOCAL_FIMD_WB;
} else {
struct v4l2_subdev *sd = dev->pipeline.sensor;
struct gsc_sensor_info *s_info =
v4l2_get_subdev_hostdata(sd);
if (s_info->pdata->cam_port == CAM_PORT_A)
cfg |= GSC_IN_LOCAL_CAM0;
else
cfg |= GSC_IN_LOCAL_CAM1;
}
}
writel(cfg, dev->regs + GSC_IN_CON);
}
void gsc_hw_set_in_size(struct gsc_ctx *ctx)
{
struct gsc_dev *dev = ctx->gsc_dev;
struct gsc_frame *frame = &ctx->s_frame;
u32 cfg;
/* Set input pixel offset */
cfg = GSC_SRCIMG_OFFSET_X(frame->crop.left);
cfg |= GSC_SRCIMG_OFFSET_Y(frame->crop.top);
writel(cfg, dev->regs + GSC_SRCIMG_OFFSET);
/* Set input original size */
cfg = GSC_SRCIMG_WIDTH(frame->f_width);
cfg |= GSC_SRCIMG_HEIGHT(frame->f_height);
writel(cfg, dev->regs + GSC_SRCIMG_SIZE);
/* Set input cropped size */
cfg = GSC_CROPPED_WIDTH(frame->crop.width);
cfg |= GSC_CROPPED_HEIGHT(frame->crop.height);
writel(cfg, dev->regs + GSC_CROPPED_SIZE);
}
void gsc_hw_set_in_image_rgb(struct gsc_ctx *ctx)
{
struct gsc_dev *dev = ctx->gsc_dev;
struct gsc_frame *frame = &ctx->s_frame;
u32 cfg;
cfg = readl(dev->regs + GSC_IN_CON);
if (ctx->gsc_ctrls.csc_eq->val) {
if (ctx->gsc_ctrls.csc_range->val)
cfg |= GSC_IN_RGB_HD_WIDE;
else
cfg |= GSC_IN_RGB_HD_NARROW;
} else {
if (ctx->gsc_ctrls.csc_range->val)
cfg |= GSC_IN_RGB_SD_WIDE;
else
cfg |= GSC_IN_RGB_SD_NARROW;
}
if (frame->fmt->pixelformat == V4L2_PIX_FMT_RGB565X)
cfg |= GSC_IN_RGB565;
else if (frame->fmt->pixelformat == V4L2_PIX_FMT_RGB32)
cfg |= GSC_IN_XRGB8888;
writel(cfg, dev->regs + GSC_IN_CON);
}
void gsc_hw_set_in_image_format(struct gsc_ctx *ctx)
{
struct gsc_dev *dev = ctx->gsc_dev;
struct gsc_frame *frame = &ctx->s_frame;
u32 i, depth = 0;
u32 cfg;
cfg = readl(dev->regs + GSC_IN_CON);
cfg &= ~(GSC_IN_RGB_TYPE_MASK | GSC_IN_YUV422_1P_ORDER_MASK |
GSC_IN_CHROMA_ORDER_MASK | GSC_IN_FORMAT_MASK |
GSC_IN_TILE_TYPE_MASK | GSC_IN_TILE_MODE);
writel(cfg, dev->regs + GSC_IN_CON);
if (is_rgb(frame->fmt->color)) {
gsc_hw_set_in_image_rgb(ctx);
return;
}
for (i = 0; i < frame->fmt->num_planes; i++)
depth += frame->fmt->depth[i];
switch (frame->fmt->nr_comp) {
case 1:
cfg |= GSC_IN_YUV422_1P;
if (frame->fmt->yorder == GSC_LSB_Y)
cfg |= GSC_IN_YUV422_1P_ORDER_LSB_Y;
else
cfg |= GSC_IN_YUV422_1P_OEDER_LSB_C;
if (frame->fmt->corder == GSC_CBCR)
cfg |= GSC_IN_CHROMA_ORDER_CBCR;
else
cfg |= GSC_IN_CHROMA_ORDER_CRCB;
break;
case 2:
if (depth == 12)
cfg |= GSC_IN_YUV420_2P;
else
cfg |= GSC_IN_YUV422_2P;
if (frame->fmt->corder == GSC_CBCR)
cfg |= GSC_IN_CHROMA_ORDER_CBCR;
else
cfg |= GSC_IN_CHROMA_ORDER_CRCB;
break;
case 3:
if (depth == 12)
cfg |= GSC_IN_YUV420_3P;
else
cfg |= GSC_IN_YUV422_3P;
break;
};
if(is_tiled(frame->fmt))
cfg |= GSC_IN_TILE_C_16x8 | GSC_IN_TILE_MODE;
writel(cfg, dev->regs + GSC_IN_CON);
}
void gsc_hw_set_output_path(struct gsc_ctx *ctx)
{
struct gsc_dev *dev = ctx->gsc_dev;
u32 cfg = readl(dev->regs + GSC_OUT_CON);
cfg &= ~GSC_OUT_PATH_MASK;
if (ctx->out_path == GSC_DMA) {
cfg |= GSC_OUT_PATH_MEMORY;
} else {
cfg |= GSC_OUT_PATH_LOCAL;
}
writel(cfg, dev->regs + GSC_OUT_CON);
}
void gsc_hw_set_out_size(struct gsc_ctx *ctx)
{
struct gsc_dev *dev = ctx->gsc_dev;
struct gsc_frame *frame = &ctx->d_frame;
u32 cfg;
/* Set output original size */
if (ctx->out_path == GSC_DMA) {
cfg = GSC_DSTIMG_OFFSET_X(frame->crop.left);
cfg |= GSC_DSTIMG_OFFSET_Y(frame->crop.top);
writel(cfg, dev->regs + GSC_DSTIMG_OFFSET);
cfg = GSC_DSTIMG_WIDTH(frame->f_width);
cfg |= GSC_DSTIMG_HEIGHT(frame->f_height);
writel(cfg, dev->regs + GSC_DSTIMG_SIZE);
}
/* Set output scaled size */
if (ctx->gsc_ctrls.rotate->val == 90 ||
ctx->gsc_ctrls.rotate->val == 270) {
cfg = GSC_SCALED_WIDTH(frame->crop.height);
cfg |= GSC_SCALED_HEIGHT(frame->crop.width);
} else {
cfg = GSC_SCALED_WIDTH(frame->crop.width);
cfg |= GSC_SCALED_HEIGHT(frame->crop.height);
}
writel(cfg, dev->regs + GSC_SCALED_SIZE);
}
void gsc_hw_set_out_image_rgb(struct gsc_ctx *ctx)
{
struct gsc_dev *dev = ctx->gsc_dev;
struct gsc_frame *frame = &ctx->d_frame;
u32 cfg;
cfg = readl(dev->regs + GSC_OUT_CON);
if (ctx->gsc_ctrls.csc_eq->val) {
if (ctx->gsc_ctrls.csc_range->val)
cfg |= GSC_OUT_RGB_HD_WIDE;
else
cfg |= GSC_OUT_RGB_HD_NARROW;
} else {
if (ctx->gsc_ctrls.csc_range->val)
cfg |= GSC_OUT_RGB_SD_WIDE;
else
cfg |= GSC_OUT_RGB_SD_NARROW;
}
if (frame->fmt->pixelformat == V4L2_PIX_FMT_RGB565X)
cfg |= GSC_OUT_RGB565;
else if (frame->fmt->pixelformat == V4L2_PIX_FMT_RGB32)
cfg |= GSC_OUT_XRGB8888;
writel(cfg, dev->regs + GSC_OUT_CON);
}
void gsc_hw_set_out_image_format(struct gsc_ctx *ctx)
{
struct gsc_dev *dev = ctx->gsc_dev;
struct gsc_frame *frame = &ctx->d_frame;
u32 i, depth = 0;
u32 cfg;
cfg = readl(dev->regs + GSC_OUT_CON);
cfg &= ~(GSC_OUT_RGB_TYPE_MASK | GSC_OUT_YUV422_1P_ORDER_MASK |
GSC_OUT_CHROMA_ORDER_MASK | GSC_OUT_FORMAT_MASK |
GSC_OUT_TILE_TYPE_MASK | GSC_OUT_TILE_MODE);
writel(cfg, dev->regs + GSC_OUT_CON);
if (is_rgb(frame->fmt->color)) {
gsc_hw_set_out_image_rgb(ctx);
return;
}
if (ctx->out_path != GSC_DMA) {
cfg |= GSC_OUT_YUV444;
goto end_set;
}
for (i = 0; i < frame->fmt->num_planes; i++)
depth += frame->fmt->depth[i];
switch (frame->fmt->nr_comp) {
case 1:
cfg |= GSC_OUT_YUV422_1P;
if (frame->fmt->yorder == GSC_LSB_Y)
cfg |= GSC_OUT_YUV422_1P_ORDER_LSB_Y;
else
cfg |= GSC_OUT_YUV422_1P_OEDER_LSB_C;
if (frame->fmt->corder == GSC_CBCR)
cfg |= GSC_OUT_CHROMA_ORDER_CBCR;
else
cfg |= GSC_OUT_CHROMA_ORDER_CRCB;
break;
case 2:
if (depth == 12)
cfg |= GSC_OUT_YUV420_2P;
else
cfg |= GSC_OUT_YUV422_2P;
if (frame->fmt->corder == GSC_CBCR)
cfg |= GSC_OUT_CHROMA_ORDER_CBCR;
else
cfg |= GSC_OUT_CHROMA_ORDER_CRCB;
break;
case 3:
cfg |= GSC_OUT_YUV420_3P;
break;
};
if(is_tiled(frame->fmt))
cfg |= GSC_OUT_TILE_C_16x8 | GSC_OUT_TILE_MODE;
end_set:
writel(cfg, dev->regs + GSC_OUT_CON);
}
void gsc_hw_set_prescaler(struct gsc_ctx *ctx)
{
struct gsc_dev *dev = ctx->gsc_dev;
struct gsc_scaler *sc = &ctx->scaler;
u32 cfg;
cfg = GSC_PRESC_SHFACTOR(sc->pre_shfactor);
cfg |= GSC_PRESC_H_RATIO(sc->pre_hratio);
cfg |= GSC_PRESC_V_RATIO(sc->pre_vratio);
writel(cfg, dev->regs + GSC_PRE_SCALE_RATIO);
}
void gsc_hw_set_mainscaler(struct gsc_ctx *ctx)
{
struct gsc_dev *dev = ctx->gsc_dev;
struct gsc_scaler *sc = &ctx->scaler;
u32 cfg;
cfg = GSC_MAIN_H_RATIO_VALUE(sc->main_hratio);
writel(cfg, dev->regs + GSC_MAIN_H_RATIO);
cfg = GSC_MAIN_V_RATIO_VALUE(sc->main_vratio);
writel(cfg, dev->regs + GSC_MAIN_V_RATIO);
}
void gsc_hw_set_rotation(struct gsc_ctx *ctx)
{
struct gsc_dev *dev = ctx->gsc_dev;
u32 cfg;
cfg = readl(dev->regs + GSC_IN_CON);
cfg &= ~GSC_IN_ROT_MASK;
switch (ctx->gsc_ctrls.rotate->val) {
case 270:
cfg |= GSC_IN_ROT_270;
break;
case 180:
cfg |= GSC_IN_ROT_180;
break;
case 90:
if (ctx->gsc_ctrls.hflip->val)
cfg |= GSC_IN_ROT_90_XFLIP;
else if (ctx->gsc_ctrls.vflip->val)
cfg |= GSC_IN_ROT_90_YFLIP;
else
cfg |= GSC_IN_ROT_90;
break;
case 0:
if (ctx->gsc_ctrls.hflip->val)
cfg |= GSC_IN_ROT_XFLIP;
else if (ctx->gsc_ctrls.vflip->val)
cfg |= GSC_IN_ROT_YFLIP;
}
writel(cfg, dev->regs + GSC_IN_CON);
}
void gsc_hw_set_global_alpha(struct gsc_ctx *ctx)
{
struct gsc_dev *dev = ctx->gsc_dev;
struct gsc_frame *frame = &ctx->d_frame;
u32 cfg;
cfg = readl(dev->regs + GSC_OUT_CON);
cfg &= ~GSC_OUT_GLOBAL_ALPHA_MASK;
if (!is_rgb(frame->fmt->color)) {
gsc_dbg("Not a RGB format");
return;
}
cfg |= GSC_OUT_GLOBAL_ALPHA(ctx->gsc_ctrls.global_alpha->val);
writel(cfg, dev->regs + GSC_OUT_CON);
}
void gsc_hw_set_sfr_update(struct gsc_ctx *ctx)
{
struct gsc_dev *dev = ctx->gsc_dev;
u32 cfg;
cfg = readl(dev->regs + GSC_ENABLE);
cfg |= GSC_ENABLE_SFR_UPDATE;
writel(cfg, dev->regs + GSC_ENABLE);
}
void gsc_hw_set_local_dst(int id, bool on)
{
u32 cfg = readl(SYSREG_GSCBLK_CFG0);
if (on)
cfg |= GSC_OUT_DST_SEL(id);
else
cfg &= ~(GSC_OUT_DST_SEL(id));
writel(cfg, SYSREG_GSCBLK_CFG0);
}
void gsc_hw_set_sysreg_writeback(struct gsc_ctx *ctx)
{
struct gsc_dev *dev = ctx->gsc_dev;
u32 cfg = readl(SYSREG_GSCBLK_CFG1);
cfg |= GSC_BLK_DISP1WB_DEST(dev->id);
cfg |= GSC_BLK_GSCL_WB_IN_SRC_SEL(dev->id);
cfg |= GSC_BLK_SW_RESET_WB_DEST(dev->id);
writel(cfg, SYSREG_GSCBLK_CFG1);
}
void gsc_hw_set_sysreg_camif(bool on)
{
u32 cfg = readl(SYSREG_GSCBLK_CFG0);
if (on)
cfg |= GSC_PXLASYNC_CAMIF_TOP;
else
cfg &= ~(GSC_PXLASYNC_CAMIF_TOP);
writel(cfg, SYSREG_GSCBLK_CFG0);
}
| gpl-2.0 |
viaembedded/vab1000-uboot-bsp | arch/arm/cpu/arm926ejs/armada100/timer.c | 37 | 5493 | /*
* (C) Copyright 2010
* Marvell Semiconductor <www.marvell.com>
* Written-by: Prafulla Wadaskar <prafulla@marvell.com>
* Contributor: Mahavir Jain <mjain@marvell.com>
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
#include <common.h>
#include <asm/arch/cpu.h>
#include <asm/arch/armada100.h>
/*
* Timer registers
* Refer Section A.6 in Datasheet
*/
struct armd1tmr_registers {
u32 clk_ctrl; /* Timer clk control reg */
u32 match[9]; /* Timer match registers */
u32 count[3]; /* Timer count registers */
u32 status[3];
u32 ie[3];
u32 preload[3]; /* Timer preload value */
u32 preload_ctrl[3];
u32 wdt_match_en;
u32 wdt_match_r;
u32 wdt_val;
u32 wdt_sts;
u32 icr[3];
u32 wdt_icr;
u32 cer; /* Timer count enable reg */
u32 cmr;
u32 ilr[3];
u32 wcr;
u32 wfar;
u32 wsar;
u32 cvwr;
};
#define TIMER 0 /* Use TIMER 0 */
/* Each timer has 3 match registers */
#define MATCH_CMP(x) ((3 * TIMER) + x)
#define TIMER_LOAD_VAL 0xffffffff
#define COUNT_RD_REQ 0x1
DECLARE_GLOBAL_DATA_PTR;
/* Using gd->arch.tbu from timestamp and gd->arch.tbl for lastdec */
/* For preventing risk of instability in reading counter value,
* first set read request to register cvwr and then read same
* register after it captures counter value.
*/
ulong read_timer(void)
{
struct armd1tmr_registers *armd1timers =
(struct armd1tmr_registers *) ARMD1_TIMER_BASE;
volatile int loop=100;
writel(COUNT_RD_REQ, &armd1timers->cvwr);
while (loop--);
return(readl(&armd1timers->cvwr));
}
ulong get_timer_masked(void)
{
ulong now = read_timer();
if (now >= gd->arch.tbl) {
/* normal mode */
gd->arch.tbu += now - gd->arch.tbl;
} else {
/* we have an overflow ... */
gd->arch.tbu += now + TIMER_LOAD_VAL - gd->arch.tbl;
}
gd->arch.tbl = now;
return gd->arch.tbu;
}
ulong get_timer(ulong base)
{
return ((get_timer_masked() / (CONFIG_SYS_HZ_CLOCK / 1000)) -
base);
}
void __udelay(unsigned long usec)
{
ulong delayticks;
ulong endtime;
delayticks = (usec * (CONFIG_SYS_HZ_CLOCK / 1000000));
endtime = get_timer_masked() + delayticks;
while (get_timer_masked() < endtime);
}
/*
* init the Timer
*/
int timer_init(void)
{
struct armd1apb1_registers *apb1clkres =
(struct armd1apb1_registers *) ARMD1_APBC1_BASE;
struct armd1tmr_registers *armd1timers =
(struct armd1tmr_registers *) ARMD1_TIMER_BASE;
/* Enable Timer clock at 3.25 MHZ */
writel(APBC_APBCLK | APBC_FNCLK | APBC_FNCLKSEL(3), &apb1clkres->timers);
/* load value into timer */
writel(0x0, &armd1timers->clk_ctrl);
/* Use Timer 0 Match Resiger 0 */
writel(TIMER_LOAD_VAL, &armd1timers->match[MATCH_CMP(0)]);
/* Preload value is 0 */
writel(0x0, &armd1timers->preload[TIMER]);
/* Enable match comparator 0 for Timer 0 */
writel(0x1, &armd1timers->preload_ctrl[TIMER]);
/* Enable timer 0 */
writel(0x1, &armd1timers->cer);
/* init the gd->arch.tbu and gd->arch.tbl value */
gd->arch.tbl = read_timer();
gd->arch.tbu = 0;
return 0;
}
#define MPMU_APRR_WDTR (1<<4)
#define TMR_WFAR 0xbaba /* WDT Register First key */
#define TMP_WSAR 0xeb10 /* WDT Register Second key */
/*
* This function uses internal Watchdog Timer
* based reset mechanism.
* Steps to write watchdog registers (protected access)
* 1. Write key value to TMR_WFAR reg.
* 2. Write key value to TMP_WSAR reg.
* 3. Perform write operation.
*/
void reset_cpu (unsigned long ignored)
{
struct armd1mpmu_registers *mpmu =
(struct armd1mpmu_registers *) ARMD1_MPMU_BASE;
struct armd1tmr_registers *armd1timers =
(struct armd1tmr_registers *) ARMD1_TIMER_BASE;
u32 val;
/* negate hardware reset to the WDT after system reset */
val = readl(&mpmu->aprr);
val = val | MPMU_APRR_WDTR;
writel(val, &mpmu->aprr);
/* reset/enable WDT clock */
writel(APBC_APBCLK | APBC_FNCLK | APBC_RST, &mpmu->wdtpcr);
readl(&mpmu->wdtpcr);
writel(APBC_APBCLK | APBC_FNCLK, &mpmu->wdtpcr);
readl(&mpmu->wdtpcr);
/* clear previous WDT status */
writel(TMR_WFAR, &armd1timers->wfar);
writel(TMP_WSAR, &armd1timers->wsar);
writel(0, &armd1timers->wdt_sts);
/* set match counter */
writel(TMR_WFAR, &armd1timers->wfar);
writel(TMP_WSAR, &armd1timers->wsar);
writel(0xf, &armd1timers->wdt_match_r);
/* enable WDT reset */
writel(TMR_WFAR, &armd1timers->wfar);
writel(TMP_WSAR, &armd1timers->wsar);
writel(0x3, &armd1timers->wdt_match_en);
while(1);
}
/*
* This function is derived from PowerPC code (read timebase as long long).
* On ARM it just returns the timer value.
*/
unsigned long long get_ticks(void)
{
return get_timer(0);
}
/*
* This function is derived from PowerPC code (timebase clock frequency).
* On ARM it returns the number of timer ticks per second.
*/
ulong get_tbclk (void)
{
return (ulong)CONFIG_SYS_HZ;
}
| gpl-2.0 |
slade87/semc_mimmi_kernel_492 | drivers/media/video/msm/vx6953.c | 37 | 50352 | /* 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/delay.h>
#include <linux/types.h>
#include <linux/i2c.h>
#include <linux/uaccess.h>
#include <linux/miscdevice.h>
#include <media/msm_camera.h>
#include <mach/gpio.h>
#include <mach/camera.h>
#include "vx6953.h"
/*=============================================================
SENSOR REGISTER DEFINES
==============================================================*/
#define REG_GROUPED_PARAMETER_HOLD 0x0104
#define GROUPED_PARAMETER_HOLD_OFF 0x00
#define GROUPED_PARAMETER_HOLD 0x01
#define REG_MODE_SELECT 0x0100
#define MODE_SELECT_STANDBY_MODE 0x00
#define MODE_SELECT_STREAM 0x01
/* Integration Time */
#define REG_COARSE_INTEGRATION_TIME_HI 0x0202
#define REG_COARSE_INTEGRATION_TIME_LO 0x0203
/* Gain */
#define REG_ANALOGUE_GAIN_CODE_GLOBAL_HI 0x0204
#define REG_ANALOGUE_GAIN_CODE_GLOBAL_LO 0x0205
/* Digital Gain */
#define REG_DIGITAL_GAIN_GREEN_R_HI 0x020E
#define REG_DIGITAL_GAIN_GREEN_R_LO 0x020F
#define REG_DIGITAL_GAIN_RED_HI 0x0210
#define REG_DIGITAL_GAIN_RED_LO 0x0211
#define REG_DIGITAL_GAIN_BLUE_HI 0x0212
#define REG_DIGITAL_GAIN_BLUE_LO 0x0213
#define REG_DIGITAL_GAIN_GREEN_B_HI 0x0214
#define REG_DIGITAL_GAIN_GREEN_B_LO 0x0215
/* output bits setting */
#define REG_0x0112 0x0112
#define REG_0x0113 0x0113
/* PLL registers */
#define REG_VT_PIX_CLK_DIV 0x0301
#define REG_PRE_PLL_CLK_DIV 0x0305
#define REG_PLL_MULTIPLIER 0x0307
#define REG_OP_PIX_CLK_DIV 0x0309
#define REG_0x034c 0x034c
#define REG_0x034d 0x034d
#define REG_0x034e 0x034e
#define REG_0x034f 0x034f
#define REG_0x0387 0x0387
#define REG_0x0383 0x0383
#define REG_FRAME_LENGTH_LINES_HI 0x0340
#define REG_FRAME_LENGTH_LINES_LO 0x0341
#define REG_LINE_LENGTH_PCK_HI 0x0342
#define REG_LINE_LENGTH_PCK_LO 0x0343
#define REG_0x3030 0x3030
#define REG_0x0111 0x0111
#define REG_0x0b00 0x0b00
#define REG_0x3001 0x3001
#define REG_0x3004 0x3004
#define REG_0x3007 0x3007
#define REG_0x301a 0x301a
#define REG_0x3101 0x3101
#define REG_0x3364 0x3364
#define REG_0x3365 0x3365
#define REG_0x0b83 0x0b83
#define REG_0x0b84 0x0b84
#define REG_0x0b8a 0x0b8a
#define REG_0x3005 0x3005
#define REG_0x3036 0x3036
#define REG_0x3041 0x3041
#define REG_0x0b80 0x0b80
#define REG_0x0900 0x0900
#define REG_0x0901 0x0901
#define REG_0x0902 0x0902
#define REG_0x3016 0x3016
#define REG_0x301d 0x301d
#define REG_0x317e 0x317e
#define REG_0x317f 0x317f
#define REG_0x3400 0x3400
#define REG_0x303a 0x303a
#define REG_0x1716 0x1716
#define REG_0x1717 0x1717
#define REG_0x1718 0x1718
#define REG_0x1719 0x1719
#define REG_0x3011 0x3011
#define REG_0x3035 0x3035
#define REG_0x3045 0x3045
/* Test Pattern */
#define REG_TEST_PATTERN_MODE 0x0601
/*============================================================================
TYPE DECLARATIONS
============================================================================*/
/* 16bit address - 8 bit context register structure */
#define VX6953_STM5M0EDOF_OFFSET 9
#define Q8 0x00000100
#define VX6953_STM5M0EDOF_MAX_SNAPSHOT_EXPOSURE_LINE_COUNT 2922
#define VX6953_STM5M0EDOF_DEFAULT_MASTER_CLK_RATE 24000000
#define VX6953_STM5M0EDOF_OP_PIXEL_CLOCK_RATE 79800000
#define VX6953_STM5M0EDOF_VT_PIXEL_CLOCK_RATE 88670000
/* Full Size */
#define VX6953_FULL_SIZE_WIDTH 2608
#define VX6953_FULL_SIZE_HEIGHT 1960
#define VX6953_FULL_SIZE_DUMMY_PIXELS 1
#define VX6953_FULL_SIZE_DUMMY_LINES 0
/* Quarter Size */
#define VX6953_QTR_SIZE_WIDTH 1304
#define VX6953_QTR_SIZE_HEIGHT 980
#define VX6953_QTR_SIZE_DUMMY_PIXELS 1
#define VX6953_QTR_SIZE_DUMMY_LINES 0
/* Blanking as measured on the scope */
/* Full Size */
#define VX6953_HRZ_FULL_BLK_PIXELS 348
#define VX6953_VER_FULL_BLK_LINES 40
/* Quarter Size */
#define VX6953_HRZ_QTR_BLK_PIXELS 1628
#define VX6953_VER_QTR_BLK_LINES 28
#define MAX_LINE_LENGTH_PCK 8190
#define VX6953_REVISION_NUMBER 0x10/*revision number for Cut2.0*/
/* FIXME: Changes from here */
struct vx6953_work_t {
struct work_struct work;
};
static struct vx6953_work_t *vx6953_sensorw;
static struct i2c_client *vx6953_client;
struct vx6953_ctrl_t {
const struct msm_camera_sensor_info *sensordata;
uint32_t sensormode;
uint32_t fps_divider; /* init to 1 * 0x00000400 */
uint32_t pict_fps_divider; /* init to 1 * 0x00000400 */
uint16_t fps;
int16_t curr_lens_pos;
uint16_t curr_step_pos;
uint16_t my_reg_gain;
uint32_t my_reg_line_count;
uint16_t total_lines_per_frame;
enum vx6953_resolution_t prev_res;
enum vx6953_resolution_t pict_res;
enum vx6953_resolution_t curr_res;
enum vx6953_test_mode_t set_test;
enum sensor_revision_t sensor_type;
enum edof_mode_t edof_mode;
unsigned short imgaddr;
};
static uint8_t vx6953_stm5m0edof_delay_msecs_stdby;
static uint16_t vx6953_stm5m0edof_delay_msecs_stream = 20;
static struct vx6953_ctrl_t *vx6953_ctrl;
static DECLARE_WAIT_QUEUE_HEAD(vx6953_wait_queue);
DEFINE_MUTEX(vx6953_mut);
static struct vx6953_i2c_reg_conf patch_tbl[] = {
{0xFB94, 0}, /*intialise Data Xfer Status reg*/
{0xFB95, 0}, /*gain 1 (0x00)*/
{0xFB96, 0}, /*gain 1.07 (0x10)*/
{0xFB97, 0}, /*gain 1.14 (0x20)*/
{0xFB98, 0}, /*gain 1.23 (0x30)*/
{0xFB99, 0}, /*gain 1.33 (0x40)*/
{0xFB9A, 0}, /*gain 1.45 (0x50)*/
{0xFB9B, 0}, /*gain 1.6 (0x60)*/
{0xFB9C, 0}, /*gain 1.78 (0x70)*/
{0xFB9D, 2}, /*gain 2 (0x80)*/
{0xFB9E, 2}, /*gain 2.29 (0x90)*/
{0xFB9F, 3}, /*gain 2.67 (0xA0)*/
{0xFBA0, 3}, /*gain 3.2 (0xB0)*/
{0xFBA1, 4}, /*gain 4 (0xC0)*/
{0xFBA2, 7}, /*gain 5.33 (0xD0)*/
{0xFBA3, 10}, /*gain 8 (0xE0)*/
{0xFBA4, 11}, /*gain 9.14 (0xE4)*/
{0xFBA5, 13}, /*gain 10.67 (0xE8)*/
{0xFBA6, 15}, /*gain 12.8 (0xEC)*/
{0xFBA7, 19}, /*gain 16 (0xF0)*/
{0xF800, 0x12},
{0xF801, 0x06},
{0xF802, 0xf7},
{0xF803, 0x90},
{0xF804, 0x02},
{0xF805, 0x05},
{0xF806, 0xe0},
{0xF807, 0xff},
{0xF808, 0x65},
{0xF809, 0x7d},
{0xF80A, 0x70},
{0xF80B, 0x03},
{0xF80C, 0x02},
{0xF80D, 0xf9},
{0xF80E, 0x1c},
{0xF80F, 0x8f},
{0xF810, 0x7d},
{0xF811, 0xe4},
{0xF812, 0xf5},
{0xF813, 0x7a},
{0xF814, 0x75},
{0xF815, 0x78},
{0xF816, 0x30},
{0xF817, 0x75},
{0xF818, 0x79},
{0xF819, 0x53},
{0xF81A, 0x85},
{0xF81B, 0x79},
{0xF81C, 0x82},
{0xF81D, 0x85},
{0xF81E, 0x78},
{0xF81F, 0x83},
{0xF820, 0xe0},
{0xF821, 0xc3},
{0xF822, 0x95},
{0xF823, 0x7b},
{0xF824, 0xf0},
{0xF825, 0x74},
{0xF826, 0x02},
{0xF827, 0x25},
{0xF828, 0x79},
{0xF829, 0xf5},
{0xF82A, 0x79},
{0xF82B, 0xe4},
{0xF82C, 0x35},
{0xF82D, 0x78},
{0xF82E, 0xf5},
{0xF82F, 0x78},
{0xF830, 0x05},
{0xF831, 0x7a},
{0xF832, 0xe5},
{0xF833, 0x7a},
{0xF834, 0xb4},
{0xF835, 0x08},
{0xF836, 0xe3},
{0xF837, 0xe5},
{0xF838, 0x7d},
{0xF839, 0x70},
{0xF83A, 0x04},
{0xF83B, 0xff},
{0xF83C, 0x02},
{0xF83D, 0xf8},
{0xF83E, 0xe4},
{0xF83F, 0xe5},
{0xF840, 0x7d},
{0xF841, 0xb4},
{0xF842, 0x10},
{0xF843, 0x05},
{0xF844, 0x7f},
{0xF845, 0x01},
{0xF846, 0x02},
{0xF847, 0xf8},
{0xF848, 0xe4},
{0xF849, 0xe5},
{0xF84A, 0x7d},
{0xF84B, 0xb4},
{0xF84C, 0x20},
{0xF84D, 0x05},
{0xF84E, 0x7f},
{0xF84F, 0x02},
{0xF850, 0x02},
{0xF851, 0xf8},
{0xF852, 0xe4},
{0xF853, 0xe5},
{0xF854, 0x7d},
{0xF855, 0xb4},
{0xF856, 0x30},
{0xF857, 0x05},
{0xF858, 0x7f},
{0xF859, 0x03},
{0xF85A, 0x02},
{0xF85B, 0xf8},
{0xF85C, 0xe4},
{0xF85D, 0xe5},
{0xF85E, 0x7d},
{0xF85F, 0xb4},
{0xF860, 0x40},
{0xF861, 0x04},
{0xF862, 0x7f},
{0xF863, 0x04},
{0xF864, 0x80},
{0xF865, 0x7e},
{0xF866, 0xe5},
{0xF867, 0x7d},
{0xF868, 0xb4},
{0xF869, 0x50},
{0xF86A, 0x04},
{0xF86B, 0x7f},
{0xF86C, 0x05},
{0xF86D, 0x80},
{0xF86E, 0x75},
{0xF86F, 0xe5},
{0xF870, 0x7d},
{0xF871, 0xb4},
{0xF872, 0x60},
{0xF873, 0x04},
{0xF874, 0x7f},
{0xF875, 0x06},
{0xF876, 0x80},
{0xF877, 0x6c},
{0xF878, 0xe5},
{0xF879, 0x7d},
{0xF87A, 0xb4},
{0xF87B, 0x70},
{0xF87C, 0x04},
{0xF87D, 0x7f},
{0xF87E, 0x07},
{0xF87F, 0x80},
{0xF880, 0x63},
{0xF881, 0xe5},
{0xF882, 0x7d},
{0xF883, 0xb4},
{0xF884, 0x80},
{0xF885, 0x04},
{0xF886, 0x7f},
{0xF887, 0x08},
{0xF888, 0x80},
{0xF889, 0x5a},
{0xF88A, 0xe5},
{0xF88B, 0x7d},
{0xF88C, 0xb4},
{0xF88D, 0x90},
{0xF88E, 0x04},
{0xF88F, 0x7f},
{0xF890, 0x09},
{0xF891, 0x80},
{0xF892, 0x51},
{0xF893, 0xe5},
{0xF894, 0x7d},
{0xF895, 0xb4},
{0xF896, 0xa0},
{0xF897, 0x04},
{0xF898, 0x7f},
{0xF899, 0x0a},
{0xF89A, 0x80},
{0xF89B, 0x48},
{0xF89C, 0xe5},
{0xF89D, 0x7d},
{0xF89E, 0xb4},
{0xF89F, 0xb0},
{0xF8A0, 0x04},
{0xF8A1, 0x7f},
{0xF8A2, 0x0b},
{0xF8A3, 0x80},
{0xF8A4, 0x3f},
{0xF8A5, 0xe5},
{0xF8A6, 0x7d},
{0xF8A7, 0xb4},
{0xF8A8, 0xc0},
{0xF8A9, 0x04},
{0xF8AA, 0x7f},
{0xF8AB, 0x0c},
{0xF8AC, 0x80},
{0xF8AD, 0x36},
{0xF8AE, 0xe5},
{0xF8AF, 0x7d},
{0xF8B0, 0xb4},
{0xF8B1, 0xd0},
{0xF8B2, 0x04},
{0xF8B3, 0x7f},
{0xF8B4, 0x0d},
{0xF8B5, 0x80},
{0xF8B6, 0x2d},
{0xF8B7, 0xe5},
{0xF8B8, 0x7d},
{0xF8B9, 0xb4},
{0xF8BA, 0xe0},
{0xF8BB, 0x04},
{0xF8BC, 0x7f},
{0xF8BD, 0x0e},
{0xF8BE, 0x80},
{0xF8BF, 0x24},
{0xF8C0, 0xe5},
{0xF8C1, 0x7d},
{0xF8C2, 0xb4},
{0xF8C3, 0xe4},
{0xF8C4, 0x04},
{0xF8C5, 0x7f},
{0xF8C6, 0x0f},
{0xF8C7, 0x80},
{0xF8C8, 0x1b},
{0xF8C9, 0xe5},
{0xF8CA, 0x7d},
{0xF8CB, 0xb4},
{0xF8CC, 0xe8},
{0xF8CD, 0x04},
{0xF8CE, 0x7f},
{0xF8CF, 0x10},
{0xF8D0, 0x80},
{0xF8D1, 0x12},
{0xF8D2, 0xe5},
{0xF8D3, 0x7d},
{0xF8D4, 0xb4},
{0xF8D5, 0xec},
{0xF8D6, 0x04},
{0xF8D7, 0x7f},
{0xF8D8, 0x11},
{0xF8D9, 0x80},
{0xF8DA, 0x09},
{0xF8DB, 0xe5},
{0xF8DC, 0x7d},
{0xF8DD, 0x7f},
{0xF8DE, 0x00},
{0xF8DF, 0xb4},
{0xF8E0, 0xf0},
{0xF8E1, 0x02},
{0xF8E2, 0x7f},
{0xF8E3, 0x12},
{0xF8E4, 0x8f},
{0xF8E5, 0x7c},
{0xF8E6, 0xef},
{0xF8E7, 0x24},
{0xF8E8, 0x95},
{0xF8E9, 0xff},
{0xF8EA, 0xe4},
{0xF8EB, 0x34},
{0xF8EC, 0xfb},
{0xF8ED, 0x8f},
{0xF8EE, 0x82},
{0xF8EF, 0xf5},
{0xF8F0, 0x83},
{0xF8F1, 0xe4},
{0xF8F2, 0x93},
{0xF8F3, 0xf5},
{0xF8F4, 0x7c},
{0xF8F5, 0xf5},
{0xF8F6, 0x7b},
{0xF8F7, 0xe4},
{0xF8F8, 0xf5},
{0xF8F9, 0x7a},
{0xF8FA, 0x75},
{0xF8FB, 0x78},
{0xF8FC, 0x30},
{0xF8FD, 0x75},
{0xF8FE, 0x79},
{0xF8FF, 0x53},
{0xF900, 0x85},
{0xF901, 0x79},
{0xF902, 0x82},
{0xF903, 0x85},
{0xF904, 0x78},
{0xF905, 0x83},
{0xF906, 0xe0},
{0xF907, 0x25},
{0xF908, 0x7c},
{0xF909, 0xf0},
{0xF90A, 0x74},
{0xF90B, 0x02},
{0xF90C, 0x25},
{0xF90D, 0x79},
{0xF90E, 0xf5},
{0xF90F, 0x79},
{0xF910, 0xe4},
{0xF911, 0x35},
{0xF912, 0x78},
{0xF913, 0xf5},
{0xF914, 0x78},
{0xF915, 0x05},
{0xF916, 0x7a},
{0xF917, 0xe5},
{0xF918, 0x7a},
{0xF919, 0xb4},
{0xF91A, 0x08},
{0xF91B, 0xe4},
{0xF91C, 0x02},
{0xF91D, 0x18},
{0xF91E, 0x32},
{0xF91F, 0x22},
{0xF920, 0xf0},
{0xF921, 0x90},
{0xF922, 0xa0},
{0xF923, 0xf8},
{0xF924, 0xe0},
{0xF925, 0x70},
{0xF926, 0x02},
{0xF927, 0xa3},
{0xF928, 0xe0},
{0xF929, 0x70},
{0xF92A, 0x0a},
{0xF92B, 0x90},
{0xF92C, 0xa1},
{0xF92D, 0x10},
{0xF92E, 0xe0},
{0xF92F, 0xfe},
{0xF930, 0xa3},
{0xF931, 0xe0},
{0xF932, 0xff},
{0xF933, 0x80},
{0xF934, 0x04},
{0xF935, 0x7e},
{0xF936, 0x00},
{0xF937, 0x7f},
{0xF938, 0x00},
{0xF939, 0x8e},
{0xF93A, 0x7e},
{0xF93B, 0x8f},
{0xF93C, 0x7f},
{0xF93D, 0x90},
{0xF93E, 0x36},
{0xF93F, 0x0d},
{0xF940, 0xe0},
{0xF941, 0x44},
{0xF942, 0x02},
{0xF943, 0xf0},
{0xF944, 0x90},
{0xF945, 0x36},
{0xF946, 0x0e},
{0xF947, 0xe5},
{0xF948, 0x7e},
{0xF949, 0xf0},
{0xF94A, 0xa3},
{0xF94B, 0xe5},
{0xF94C, 0x7f},
{0xF94D, 0xf0},
{0xF94E, 0xe5},
{0xF94F, 0x3a},
{0xF950, 0x60},
{0xF951, 0x0c},
{0xF952, 0x90},
{0xF953, 0x36},
{0xF954, 0x09},
{0xF955, 0xe0},
{0xF956, 0x70},
{0xF957, 0x06},
{0xF958, 0x90},
{0xF959, 0x36},
{0xF95A, 0x08},
{0xF95B, 0xf0},
{0xF95C, 0xf5},
{0xF95D, 0x3a},
{0xF95E, 0x02},
{0xF95F, 0x03},
{0xF960, 0x94},
{0xF961, 0x22},
{0xF962, 0x78},
{0xF963, 0x07},
{0xF964, 0xe6},
{0xF965, 0xd3},
{0xF966, 0x94},
{0xF967, 0x00},
{0xF968, 0x40},
{0xF969, 0x16},
{0xF96A, 0x16},
{0xF96B, 0xe6},
{0xF96C, 0x90},
{0xF96D, 0x30},
{0xF96E, 0xa1},
{0xF96F, 0xf0},
{0xF970, 0x90},
{0xF971, 0x43},
{0xF972, 0x83},
{0xF973, 0xe0},
{0xF974, 0xb4},
{0xF975, 0x01},
{0xF976, 0x0f},
{0xF977, 0x90},
{0xF978, 0x43},
{0xF979, 0x87},
{0xF97A, 0xe0},
{0xF97B, 0xb4},
{0xF97C, 0x01},
{0xF97D, 0x08},
{0xF97E, 0x80},
{0xF97F, 0x00},
{0xF980, 0x90},
{0xF981, 0x30},
{0xF982, 0xa0},
{0xF983, 0x74},
{0xF984, 0x01},
{0xF985, 0xf0},
{0xF986, 0x22},
{0xF987, 0xf0},
{0xF988, 0x90},
{0xF989, 0x35},
{0xF98A, 0xba},
{0xF98B, 0xe0},
{0xF98C, 0xb4},
{0xF98D, 0x0a},
{0xF98E, 0x0d},
{0xF98F, 0xa3},
{0xF990, 0xe0},
{0xF991, 0xb4},
{0xF992, 0x01},
{0xF993, 0x08},
{0xF994, 0x90},
{0xF995, 0xfb},
{0xF996, 0x94},
{0xF997, 0xe0},
{0xF998, 0x90},
{0xF999, 0x35},
{0xF99A, 0xb8},
{0xF99B, 0xf0},
{0xF99C, 0xd0},
{0xF99D, 0xd0},
{0xF99E, 0xd0},
{0xF99F, 0x82},
{0xF9A0, 0xd0},
{0xF9A1, 0x83},
{0xF9A2, 0xd0},
{0xF9A3, 0xe0},
{0xF9A4, 0x32},
{0xF9A5, 0x22},
{0xF9A6, 0xe5},
{0xF9A7, 0x7f},
{0xF9A8, 0x45},
{0xF9A9, 0x7e},
{0xF9AA, 0x60},
{0xF9AB, 0x15},
{0xF9AC, 0x90},
{0xF9AD, 0x01},
{0xF9AE, 0x00},
{0xF9AF, 0xe0},
{0xF9B0, 0x70},
{0xF9B1, 0x0f},
{0xF9B2, 0x90},
{0xF9B3, 0xa0},
{0xF9B4, 0xf8},
{0xF9B5, 0xe5},
{0xF9B6, 0x7e},
{0xF9B7, 0xf0},
{0xF9B8, 0xa3},
{0xF9B9, 0xe5},
{0xF9BA, 0x7f},
{0xF9BB, 0xf0},
{0xF9BC, 0xe4},
{0xF9BD, 0xf5},
{0xF9BE, 0x7e},
{0xF9BF, 0xf5},
{0xF9C0, 0x7f},
{0xF9C1, 0x22},
{0xF9C2, 0x02},
{0xF9C3, 0x0e},
{0xF9C4, 0x79},
{0xF9C5, 0x22},
/* Offsets:*/
{0x35C6, 0x00},/* FIDDLEDARKCAL*/
{0x35C7, 0x00},
{0x35C8, 0x01},/* STOREDISTANCEATSTOPSTREAMING*/
{0x35C9, 0x20},
{0x35CA, 0x01},/*BRUCEFIX*/
{0x35CB, 0x62},
{0x35CC, 0x01},/*FIXDATAXFERSTATUSREG*/
{0x35CD, 0x87},
{0x35CE, 0x01},/*FOCUSDISTANCEUPDATE*/
{0x35CF, 0xA6},
{0x35D0, 0x01},/*SKIPEDOFRESET*/
{0x35D1, 0xC2},
{0x35D2, 0x00},
{0x35D3, 0xFB},
{0x35D4, 0x00},
{0x35D5, 0x94},
{0x35D6, 0x00},
{0x35D7, 0xFB},
{0x35D8, 0x00},
{0x35D9, 0x94},
{0x35DA, 0x00},
{0x35DB, 0xFB},
{0x35DC, 0x00},
{0x35DD, 0x94},
{0x35DE, 0x00},
{0x35DF, 0xFB},
{0x35E0, 0x00},
{0x35E1, 0x94},
{0x35E6, 0x18},/* FIDDLEDARKCAL*/
{0x35E7, 0x2F},
{0x35E8, 0x03},/* STOREDISTANCEATSTOPSTREAMING*/
{0x35E9, 0x93},
{0x35EA, 0x18},/* BRUCEFIX*/
{0x35EB, 0x99},
{0x35EC, 0x00},/* FIXDATAXFERSTATUSREG*/
{0x35ED, 0xA3},
{0x35EE, 0x21},/* FOCUSDISTANCEUPDATE*/
{0x35EF, 0x5B},
{0x35F0, 0x0E},/* SKIPEDOFRESET*/
{0x35F1, 0x74},
{0x35F2, 0x04},
{0x35F3, 0x64},
{0x35F4, 0x04},
{0x35F5, 0x65},
{0x35F6, 0x04},
{0x35F7, 0x7B},
{0x35F8, 0x04},
{0x35F9, 0x7C},
{0x35FA, 0x04},
{0x35FB, 0xDD},
{0x35FC, 0x04},
{0x35FD, 0xDE},
{0x35FE, 0x04},
{0x35FF, 0xEF},
{0x3600, 0x04},
{0x3601, 0xF0},
/*Jump/Data:*/
{0x35C2, 0x3F},/* Jump Reg*/
{0x35C3, 0xFF},/* Jump Reg*/
{0x35C4, 0x3F},/* Data Reg*/
{0x35C5, 0xC0},/* Data Reg*/
{0x35C0, 0x01},/* Enable*/
};
/*=============================================================*/
static int vx6953_i2c_rxdata(unsigned short saddr,
unsigned char *rxdata, int length)
{
struct i2c_msg msgs[] = {
{
.addr = saddr,
.flags = 0,
.len = 2,
.buf = rxdata,
},
{
.addr = saddr,
.flags = I2C_M_RD,
.len = 2,
.buf = rxdata,
},
};
if (i2c_transfer(vx6953_client->adapter, msgs, 2) < 0) {
CDBG("vx6953_i2c_rxdata failed!\n");
return -EIO;
}
return 0;
}
static int32_t vx6953_i2c_txdata(unsigned short saddr,
unsigned char *txdata, int length)
{
struct i2c_msg msg[] = {
{
.addr = saddr,
.flags = 0,
.len = length,
.buf = txdata,
},
};
if (i2c_transfer(vx6953_client->adapter, msg, 1) < 0) {
CDBG("vx6953_i2c_txdata faild 0x%x\n", vx6953_client->addr);
return -EIO;
}
return 0;
}
static int32_t vx6953_i2c_read(unsigned short raddr,
unsigned short *rdata, int rlen)
{
int32_t rc = 0;
unsigned char buf[2];
if (!rdata)
return -EIO;
memset(buf, 0, sizeof(buf));
buf[0] = (raddr & 0xFF00) >> 8;
buf[1] = (raddr & 0x00FF);
rc = vx6953_i2c_rxdata(vx6953_client->addr>>1, buf, rlen);
if (rc < 0) {
CDBG("vx6953_i2c_read 0x%x failed!\n", raddr);
return rc;
}
*rdata = (rlen == 2 ? buf[0] << 8 | buf[1] : buf[0]);
return rc;
}
static int32_t vx6953_i2c_write_b_sensor(unsigned short waddr, uint8_t bdata)
{
int32_t rc = -EFAULT;
unsigned char buf[3];
memset(buf, 0, sizeof(buf));
buf[0] = (waddr & 0xFF00) >> 8;
buf[1] = (waddr & 0x00FF);
buf[2] = bdata;
CDBG("i2c_write_b addr = 0x%x, val = 0x%x\n", waddr, bdata);
rc = vx6953_i2c_txdata(vx6953_client->addr>>1, buf, 3);
if (rc < 0) {
CDBG("i2c_write_b failed, addr = 0x%x, val = 0x%x!\n",
waddr, bdata);
}
udelay(250);
return rc;
}
static int32_t vx6953_i2c_write_seq_sensor(unsigned short waddr,
uint8_t *bdata, uint16_t len)
{
int32_t rc = -EFAULT;
unsigned char buf[len+2];
int i;
memset(buf, 0, sizeof(buf));
buf[0] = (waddr & 0xFF00) >> 8;
buf[1] = (waddr & 0x00FF);
for (i = 2; i < len+2; i++)
buf[i] = *bdata++;
rc = vx6953_i2c_txdata(vx6953_client->addr>>1, buf, len+2);
if (rc < 0) {
CDBG("i2c_write_b failed, addr = 0x%x, val = 0x%x!\n",
waddr, bdata[0]);
}
mdelay(1);
return rc;
}
static int32_t vx6953_i2c_write_w_table(struct vx6953_i2c_reg_conf const
*reg_conf_tbl, int num)
{
int i;
int32_t rc = -EIO;
for (i = 0; i < num; i++) {
rc = vx6953_i2c_write_b_sensor(reg_conf_tbl->waddr,
reg_conf_tbl->wdata);
if (rc < 0)
break;
reg_conf_tbl++;
}
return rc;
}
static void vx6953_get_pict_fps(uint16_t fps, uint16_t *pfps)
{
/* input fps is preview fps in Q8 format */
uint16_t preview_frame_length_lines, snapshot_frame_length_lines;
uint16_t preview_line_length_pck, snapshot_line_length_pck;
uint32_t divider, d1, d2;
/* Total frame_length_lines and line_length_pck for preview */
preview_frame_length_lines = VX6953_QTR_SIZE_HEIGHT +
VX6953_VER_QTR_BLK_LINES;
preview_line_length_pck = VX6953_QTR_SIZE_WIDTH +
VX6953_HRZ_QTR_BLK_PIXELS;
/* Total frame_length_lines and line_length_pck for snapshot */
snapshot_frame_length_lines = VX6953_FULL_SIZE_HEIGHT +
VX6953_VER_FULL_BLK_LINES;
snapshot_line_length_pck = VX6953_FULL_SIZE_WIDTH +
VX6953_HRZ_FULL_BLK_PIXELS;
d1 = preview_frame_length_lines * 0x00000400/
snapshot_frame_length_lines;
d2 = preview_line_length_pck * 0x00000400/
snapshot_line_length_pck;
divider = d1 * d2 / 0x400;
/*Verify PCLK settings and frame sizes.*/
*pfps = (uint16_t) (fps * divider / 0x400);
/* 2 is the ratio of no.of snapshot channels
to number of preview channels */
}
static uint16_t vx6953_get_prev_lines_pf(void)
{
if (vx6953_ctrl->prev_res == QTR_SIZE)
return VX6953_QTR_SIZE_HEIGHT + VX6953_VER_QTR_BLK_LINES;
else
return VX6953_FULL_SIZE_HEIGHT + VX6953_VER_FULL_BLK_LINES;
}
static uint16_t vx6953_get_prev_pixels_pl(void)
{
if (vx6953_ctrl->prev_res == QTR_SIZE)
return VX6953_QTR_SIZE_WIDTH + VX6953_HRZ_QTR_BLK_PIXELS;
else
return VX6953_FULL_SIZE_WIDTH + VX6953_HRZ_FULL_BLK_PIXELS;
}
static uint16_t vx6953_get_pict_lines_pf(void)
{
if (vx6953_ctrl->pict_res == QTR_SIZE)
return VX6953_QTR_SIZE_HEIGHT +
VX6953_VER_QTR_BLK_LINES;
else
return VX6953_FULL_SIZE_HEIGHT +
VX6953_VER_FULL_BLK_LINES;
}
static uint16_t vx6953_get_pict_pixels_pl(void)
{
if (vx6953_ctrl->pict_res == QTR_SIZE)
return VX6953_QTR_SIZE_WIDTH +
VX6953_HRZ_QTR_BLK_PIXELS;
else
return VX6953_FULL_SIZE_WIDTH +
VX6953_HRZ_FULL_BLK_PIXELS;
}
static uint32_t vx6953_get_pict_max_exp_lc(void)
{
if (vx6953_ctrl->pict_res == QTR_SIZE)
return (VX6953_QTR_SIZE_HEIGHT +
VX6953_VER_QTR_BLK_LINES)*24;
else
return (VX6953_FULL_SIZE_HEIGHT +
VX6953_VER_FULL_BLK_LINES)*24;
}
static int32_t vx6953_set_fps(struct fps_cfg *fps)
{
uint16_t total_lines_per_frame;
int32_t rc = 0;
total_lines_per_frame = (uint16_t)((VX6953_QTR_SIZE_HEIGHT +
VX6953_VER_QTR_BLK_LINES) * vx6953_ctrl->fps_divider/0x400);
if (vx6953_i2c_write_b_sensor(REG_FRAME_LENGTH_LINES_HI,
((total_lines_per_frame & 0xFF00) >> 8)) < 0)
return rc;
if (vx6953_i2c_write_b_sensor(REG_FRAME_LENGTH_LINES_LO,
(total_lines_per_frame & 0x00FF)) < 0)
return rc;
return rc;
}
static int32_t vx6953_write_exp_gain(uint16_t gain, uint32_t line)
{
static uint16_t stored_line_length_ratio = 1*Q8;
static uint16_t stored_gain = 0x0;
static uint16_t stored_line = 0x0;
uint16_t line_length_pck, frame_length_lines;
uint8_t gain_hi, gain_lo;
uint8_t intg_time_hi, intg_time_lo;
uint8_t line_length_pck_hi = 0, line_length_pck_lo = 0;
uint16_t line_length_ratio = 1 * Q8;
int32_t rc = 0;
if (gain != stored_gain || line != stored_line) {
if (vx6953_ctrl->sensormode != SENSOR_SNAPSHOT_MODE) {
frame_length_lines = VX6953_QTR_SIZE_HEIGHT +
VX6953_VER_QTR_BLK_LINES;
line_length_pck = VX6953_QTR_SIZE_WIDTH +
VX6953_HRZ_QTR_BLK_PIXELS;
if (line > (frame_length_lines -
VX6953_STM5M0EDOF_OFFSET)) {
vx6953_ctrl->fps = (uint16_t) (30 * Q8 *
(frame_length_lines - VX6953_STM5M0EDOF_OFFSET)/
line);
} else {
vx6953_ctrl->fps = (uint16_t) (30 * Q8);
}
} else {
frame_length_lines = VX6953_FULL_SIZE_HEIGHT +
VX6953_VER_FULL_BLK_LINES;
line_length_pck = VX6953_FULL_SIZE_WIDTH +
VX6953_HRZ_FULL_BLK_PIXELS;
}
/* calculate line_length_ratio */
if ((frame_length_lines - VX6953_STM5M0EDOF_OFFSET) < line) {
line_length_ratio = (line*Q8) /
(frame_length_lines - VX6953_STM5M0EDOF_OFFSET);
line = frame_length_lines - VX6953_STM5M0EDOF_OFFSET;
} else {
line_length_ratio = 1*Q8;
}
vx6953_i2c_write_b_sensor(REG_GROUPED_PARAMETER_HOLD,
GROUPED_PARAMETER_HOLD);
if (line_length_ratio != stored_line_length_ratio) {
line_length_pck = (line_length_pck >
MAX_LINE_LENGTH_PCK) ?
MAX_LINE_LENGTH_PCK : line_length_pck;
line_length_pck = (uint16_t) (line_length_pck *
line_length_ratio/Q8);
line_length_pck_hi = (uint8_t) ((line_length_pck &
0xFF00) >> 8);
line_length_pck_lo = (uint8_t) (line_length_pck &
0x00FF);
vx6953_i2c_write_b_sensor(REG_LINE_LENGTH_PCK_HI,
line_length_pck_hi);
vx6953_i2c_write_b_sensor(REG_LINE_LENGTH_PCK_LO,
line_length_pck_lo);
stored_line_length_ratio = line_length_ratio;
}
/* update analogue gain registers */
gain_hi = (uint8_t) ((gain & 0xFF00) >> 8);
gain_lo = (uint8_t) (gain & 0x00FF);
vx6953_i2c_write_b_sensor(REG_ANALOGUE_GAIN_CODE_GLOBAL_LO,
gain_lo);
vx6953_i2c_write_b_sensor(REG_DIGITAL_GAIN_GREEN_R_LO, gain_hi);
vx6953_i2c_write_b_sensor(REG_DIGITAL_GAIN_RED_LO, gain_hi);
vx6953_i2c_write_b_sensor(REG_DIGITAL_GAIN_BLUE_LO, gain_hi);
vx6953_i2c_write_b_sensor(REG_DIGITAL_GAIN_GREEN_B_LO, gain_hi);
CDBG("%s, gain_hi 0x%x, gain_lo 0x%x\n", __func__,
gain_hi, gain_lo);
/* update line count registers */
intg_time_hi = (uint8_t) (((uint16_t)line & 0xFF00) >> 8);
intg_time_lo = (uint8_t) ((uint16_t)line & 0x00FF);
vx6953_i2c_write_b_sensor(REG_COARSE_INTEGRATION_TIME_HI,
intg_time_hi);
vx6953_i2c_write_b_sensor(REG_COARSE_INTEGRATION_TIME_LO,
intg_time_lo);
vx6953_i2c_write_b_sensor(REG_GROUPED_PARAMETER_HOLD,
GROUPED_PARAMETER_HOLD_OFF);
stored_gain = gain;
stored_line = line;
}
return rc;
}
static int32_t vx6953_set_pict_exp_gain(uint16_t gain, uint32_t line)
{
int32_t rc = 0;
rc = vx6953_write_exp_gain(gain, line);
return rc;
} /* endof vx6953_set_pict_exp_gain*/
static int32_t vx6953_move_focus(int direction,
int32_t num_steps)
{
return 0;
}
static int32_t vx6953_set_default_focus(uint8_t af_step)
{
return 0;
}
static int32_t vx6953_test(enum vx6953_test_mode_t mo)
{
int32_t rc = 0;
if (mo == TEST_OFF)
return rc;
else {
/* REG_0x30D8[4] is TESBYPEN: 0: Normal Operation,
1: Bypass Signal Processing
REG_0x30D8[5] is EBDMASK: 0:
Output Embedded data, 1: No output embedded data */
if (vx6953_i2c_write_b_sensor(REG_TEST_PATTERN_MODE,
(uint8_t) mo) < 0) {
return rc;
}
}
return rc;
}
static int vx6953_enable_edof(enum edof_mode_t edof_mode)
{
int rc = 0;
if (edof_mode == VX6953_EDOF_ESTIMATION) {
/* EDof Estimation mode for preview */
if (vx6953_i2c_write_b_sensor(REG_0x0b80, 0x02) < 0)
return rc;
CDBG("VX6953_EDOF_ESTIMATION");
} else if (edof_mode == VX6953_EDOF_APPLICATION) {
/* EDof Application mode for Capture */
if (vx6953_i2c_write_b_sensor(REG_0x0b80, 0x01) < 0)
return rc;
CDBG("VX6953_EDOF_APPLICATION");
} else {
/* EDOF disabled */
if (vx6953_i2c_write_b_sensor(REG_0x0b80, 0x00) < 0)
return rc;
CDBG("VX6953_EDOF_DISABLE");
}
return rc;
}
static int32_t vx6953_patch_for_cut2(void)
{
int32_t rc = 0;
rc = vx6953_i2c_write_w_table(patch_tbl,
ARRAY_SIZE(patch_tbl));
if (rc < 0)
return rc;
return rc;
}
static int32_t vx6953_sensor_setting(int update_type, int rt)
{
int32_t rc = 0;
unsigned short frame_cnt;
switch (update_type) {
case REG_INIT:
if (rt == RES_PREVIEW || rt == RES_CAPTURE) {
struct vx6953_i2c_reg_conf init_tbl[] = {
{REG_0x0112,
vx6953_regs.reg_pat_init[0].reg_0x0112},
{REG_0x0113,
vx6953_regs.reg_pat_init[0].reg_0x0113},
{REG_VT_PIX_CLK_DIV,
vx6953_regs.reg_pat_init[0].
vt_pix_clk_div},
{REG_PRE_PLL_CLK_DIV,
vx6953_regs.reg_pat_init[0].
pre_pll_clk_div},
{REG_PLL_MULTIPLIER,
vx6953_regs.reg_pat_init[0].
pll_multiplier},
{REG_OP_PIX_CLK_DIV,
vx6953_regs.reg_pat_init[0].
op_pix_clk_div},
{REG_COARSE_INTEGRATION_TIME_HI,
vx6953_regs.reg_pat[rt].
coarse_integration_time_hi},
{REG_COARSE_INTEGRATION_TIME_LO,
vx6953_regs.reg_pat[rt].
coarse_integration_time_lo},
{REG_ANALOGUE_GAIN_CODE_GLOBAL_LO,
vx6953_regs.reg_pat[rt].
analogue_gain_code_global},
{REG_0x3030,
vx6953_regs.reg_pat_init[0].reg_0x3030},
/* 953 specific registers */
{REG_0x0111,
vx6953_regs.reg_pat_init[0].reg_0x0111},
{REG_0x0b00,
vx6953_regs.reg_pat_init[0].reg_0x0b00},
{REG_0x3001,
vx6953_regs.reg_pat_init[0].reg_0x3001},
{REG_0x3004,
vx6953_regs.reg_pat_init[0].reg_0x3004},
{REG_0x3007,
vx6953_regs.reg_pat_init[0].reg_0x3007},
{REG_0x3016,
vx6953_regs.reg_pat_init[0].reg_0x3016},
{REG_0x301d,
vx6953_regs.reg_pat_init[0].reg_0x301d},
{REG_0x317e,
vx6953_regs.reg_pat_init[0].reg_0x317e},
{REG_0x317f,
vx6953_regs.reg_pat_init[0].reg_0x317f},
{REG_0x3400,
vx6953_regs.reg_pat_init[0].reg_0x3400},
/* DEFCOR settings */
/*Single Defect Correction Weight DISABLE*/
{0x0b06,
vx6953_regs.reg_pat_init[0].reg_0x0b06},
/*Single_defect_correct_weight = auto*/
{0x0b07,
vx6953_regs.reg_pat_init[0].reg_0x0b07},
/*Dynamic couplet correction ENABLED*/
{0x0b08,
vx6953_regs.reg_pat_init[0].reg_0x0b08},
/*Dynamic couplet correction weight*/
{0x0b09,
vx6953_regs.reg_pat_init[0].reg_0x0b09},
/* Clock Setup */
/* Tell sensor ext clk is 24MHz*/
{0x0136,
vx6953_regs.reg_pat_init[0].reg_0x0136},
{0x0137,
vx6953_regs.reg_pat_init[0].reg_0x0137},
/* The white balance gains must be written
to the sensor every frame. */
/* Edof */
{REG_0x0b83,
vx6953_regs.reg_pat_init[0].reg_0x0b83},
{REG_0x0b84,
vx6953_regs.reg_pat_init[0].reg_0x0b84},
{0x0b85,
vx6953_regs.reg_pat_init[0].reg_0x0b85},
{0x0b88,
vx6953_regs.reg_pat_init[0].reg_0x0b88},
{0x0b89,
vx6953_regs.reg_pat_init[0].reg_0x0b89},
{REG_0x0b8a,
vx6953_regs.reg_pat_init[0].reg_0x0b8a},
/* Mode specific regieters */
{REG_FRAME_LENGTH_LINES_HI,
vx6953_regs.reg_pat[rt].
frame_length_lines_hi},
{REG_FRAME_LENGTH_LINES_LO,
vx6953_regs.reg_pat[rt].
frame_length_lines_lo},
{REG_LINE_LENGTH_PCK_HI,
vx6953_regs.reg_pat[rt].
line_length_pck_hi},
{REG_LINE_LENGTH_PCK_LO,
vx6953_regs.reg_pat[rt].
line_length_pck_lo},
{REG_0x3005,
vx6953_regs.reg_pat[rt].reg_0x3005},
{0x3010,
vx6953_regs.reg_pat[rt].reg_0x3010},
{REG_0x3011,
vx6953_regs.reg_pat[rt].reg_0x3011},
{REG_0x301a,
vx6953_regs.reg_pat[rt].reg_0x301a},
{REG_0x3035,
vx6953_regs.reg_pat[rt].reg_0x3035},
{REG_0x3036,
vx6953_regs.reg_pat[rt].reg_0x3036},
{REG_0x3041,
vx6953_regs.reg_pat[rt].reg_0x3041},
{0x3042,
vx6953_regs.reg_pat[rt].reg_0x3042},
{REG_0x3045,
vx6953_regs.reg_pat[rt].reg_0x3045},
/*EDOF: Estimation settings for Preview mode
Application settings for capture mode
(standard settings - Not tuned) */
{REG_0x0b80,
vx6953_regs.reg_pat[rt].reg_0x0b80},
{REG_0x0900,
vx6953_regs.reg_pat[rt].reg_0x0900},
{REG_0x0901,
vx6953_regs.reg_pat[rt].reg_0x0901},
{REG_0x0902,
vx6953_regs.reg_pat[rt].reg_0x0902},
{REG_0x0383,
vx6953_regs.reg_pat[rt].reg_0x0383},
{REG_0x0387,
vx6953_regs.reg_pat[rt].reg_0x0387},
/* Change output size / frame rate */
{REG_0x034c,
vx6953_regs.reg_pat[rt].reg_0x034c},
{REG_0x034d,
vx6953_regs.reg_pat[rt].reg_0x034d},
{REG_0x034e,
vx6953_regs.reg_pat[rt].reg_0x034e},
{REG_0x034f,
vx6953_regs.reg_pat[rt].reg_0x034f},
{REG_0x1716,
vx6953_regs.reg_pat[rt].reg_0x1716},
{REG_0x1717,
vx6953_regs.reg_pat[rt].reg_0x1717},
{REG_0x1718,
vx6953_regs.reg_pat[rt].reg_0x1718},
{REG_0x1719,
vx6953_regs.reg_pat[rt].reg_0x1719},
};
/* reset fps_divider */
vx6953_ctrl->fps = 30 * Q8;
/* stop streaming */
if (vx6953_i2c_write_b_sensor(REG_MODE_SELECT,
MODE_SELECT_STANDBY_MODE) < 0)
return rc;
/*vx6953_stm5m0edof_delay_msecs_stdby*/
mdelay(vx6953_stm5m0edof_delay_msecs_stdby);
vx6953_patch_for_cut2();
rc = vx6953_i2c_write_w_table(&init_tbl[0],
ARRAY_SIZE(init_tbl));
if (rc < 0)
return rc;
/* Start sensor streaming */
if (vx6953_i2c_write_b_sensor(REG_MODE_SELECT,
MODE_SELECT_STREAM) < 0)
return rc;
mdelay(vx6953_stm5m0edof_delay_msecs_stream);
if (vx6953_i2c_read(0x0005, &frame_cnt, 1) < 0)
return rc;
while (frame_cnt == 0xFF) {
if (vx6953_i2c_read(0x0005, &frame_cnt, 1) < 0)
return rc;
CDBG("frame_cnt=%d", frame_cnt);
}
}
return rc;
case UPDATE_PERIODIC:
if (rt == RES_PREVIEW || rt == RES_CAPTURE) {
struct vx6953_i2c_reg_conf mode_tbl[] = {
{REG_VT_PIX_CLK_DIV,
vx6953_regs.reg_pat_init[0].vt_pix_clk_div},
{REG_PRE_PLL_CLK_DIV,
vx6953_regs.reg_pat_init[0].pre_pll_clk_div},
{REG_PLL_MULTIPLIER,
vx6953_regs.reg_pat_init[0].pll_multiplier},
{REG_OP_PIX_CLK_DIV,
vx6953_regs.reg_pat_init[0].op_pix_clk_div},
/* Mode specific regieters */
{REG_FRAME_LENGTH_LINES_HI,
vx6953_regs.reg_pat[rt].frame_length_lines_hi},
{REG_FRAME_LENGTH_LINES_LO,
vx6953_regs.reg_pat[rt].frame_length_lines_lo},
{REG_LINE_LENGTH_PCK_HI,
vx6953_regs.reg_pat[rt].line_length_pck_hi},
{REG_LINE_LENGTH_PCK_LO,
vx6953_regs.reg_pat[rt].line_length_pck_lo},
{REG_0x3005, vx6953_regs.reg_pat[rt].reg_0x3005},
{0x3010, vx6953_regs.reg_pat[rt].reg_0x3010},
{REG_0x3011, vx6953_regs.reg_pat[rt].reg_0x3011},
{REG_0x301a, vx6953_regs.reg_pat[rt].reg_0x301a},
{REG_0x3035, vx6953_regs.reg_pat[rt].reg_0x3035},
{REG_0x3036, vx6953_regs.reg_pat[rt].reg_0x3036},
{REG_0x3041, vx6953_regs.reg_pat[rt].reg_0x3041},
{0x3042, vx6953_regs.reg_pat[rt].reg_0x3042},
{REG_0x3045, vx6953_regs.reg_pat[rt].reg_0x3045},
/*EDOF: Estimation settings for Preview mode
Application settings for capture
mode(standard settings - Not tuned) */
{REG_0x0b80, vx6953_regs.reg_pat[rt].reg_0x0b80},
{REG_0x0900, vx6953_regs.reg_pat[rt].reg_0x0900},
{REG_0x0901, vx6953_regs.reg_pat[rt].reg_0x0901},
{REG_0x0902, vx6953_regs.reg_pat[rt].reg_0x0902},
{REG_0x0383, vx6953_regs.reg_pat[rt].reg_0x0383},
{REG_0x0387, vx6953_regs.reg_pat[rt].reg_0x0387},
/* Change output size / frame rate */
{REG_0x034c, vx6953_regs.reg_pat[rt].reg_0x034c},
{REG_0x034d, vx6953_regs.reg_pat[rt].reg_0x034d},
{REG_0x034e, vx6953_regs.reg_pat[rt].reg_0x034e},
{REG_0x034f, vx6953_regs.reg_pat[rt].reg_0x034f},
/*{0x200, vx6953_regs.reg_pat[rt].reg_0x0200},
{0x201, vx6953_regs.reg_pat[rt].reg_0x0201},*/
{REG_0x1716, vx6953_regs.reg_pat[rt].reg_0x1716},
{REG_0x1717, vx6953_regs.reg_pat[rt].reg_0x1717},
{REG_0x1718, vx6953_regs.reg_pat[rt].reg_0x1718},
{REG_0x1719, vx6953_regs.reg_pat[rt].reg_0x1719},
};
/* stop streaming */
mdelay(5);
if (vx6953_i2c_write_b_sensor(REG_MODE_SELECT,
MODE_SELECT_STANDBY_MODE) < 0)
return rc;
/*vx6953_stm5m0edof_delay_msecs_stdby*/
mdelay(vx6953_stm5m0edof_delay_msecs_stdby);
rc = vx6953_i2c_write_w_table(&mode_tbl[0],
ARRAY_SIZE(mode_tbl));
if (rc < 0)
return rc;
/* Start sensor streaming */
if (vx6953_i2c_write_b_sensor(REG_MODE_SELECT,
MODE_SELECT_STREAM) < 0)
return rc;
mdelay(vx6953_stm5m0edof_delay_msecs_stream);
if (vx6953_i2c_read(0x0005, &frame_cnt, 1) < 0)
return rc;
while (frame_cnt == 0xFF) {
if (vx6953_i2c_read(0x0005, &frame_cnt, 1) < 0)
return rc;
CDBG("frame_cnt=%d", frame_cnt);
}
}
return rc;
default:
return rc;
}
return rc;
}
static int32_t vx6953_video_config(int mode)
{
int32_t rc = 0;
int rt;
/* change sensor resolution if needed */
if (vx6953_ctrl->curr_res != vx6953_ctrl->prev_res) {
if (vx6953_ctrl->prev_res == QTR_SIZE) {
rt = RES_PREVIEW;
vx6953_stm5m0edof_delay_msecs_stdby =
((2 * 1000 * Q8 * vx6953_ctrl->fps_divider) /
vx6953_ctrl->fps) + 1;
} else {
rt = RES_CAPTURE;
vx6953_stm5m0edof_delay_msecs_stdby =
((1000 * Q8 * vx6953_ctrl->fps_divider) /
vx6953_ctrl->fps) + 1;
}
if (vx6953_sensor_setting(UPDATE_PERIODIC, rt) < 0)
return rc;
}
if (vx6953_ctrl->set_test) {
if (vx6953_test(vx6953_ctrl->set_test) < 0)
return rc;
}
vx6953_ctrl->edof_mode = VX6953_EDOF_ESTIMATION;
rc = vx6953_enable_edof(vx6953_ctrl->edof_mode);
if (rc < 0)
return rc;
vx6953_ctrl->curr_res = vx6953_ctrl->prev_res;
vx6953_ctrl->sensormode = mode;
return rc;
}
static int32_t vx6953_snapshot_config(int mode)
{
int32_t rc = 0;
int rt;
/*change sensor resolution if needed */
if (vx6953_ctrl->curr_res != vx6953_ctrl->pict_res) {
if (vx6953_ctrl->pict_res == QTR_SIZE) {
rt = RES_PREVIEW;
vx6953_stm5m0edof_delay_msecs_stdby =
((2 * 1000 * Q8 * vx6953_ctrl->fps_divider)/
vx6953_ctrl->fps) + 1;
} else {
rt = RES_CAPTURE;
vx6953_stm5m0edof_delay_msecs_stdby =
((1000 * Q8 * vx6953_ctrl->fps_divider)/
vx6953_ctrl->fps) + 1;
}
if (vx6953_sensor_setting(UPDATE_PERIODIC, rt) < 0)
return rc;
}
vx6953_ctrl->edof_mode = VX6953_EDOF_APPLICATION;
if (vx6953_enable_edof(vx6953_ctrl->edof_mode) < 0)
return rc;
vx6953_ctrl->curr_res = vx6953_ctrl->pict_res;
vx6953_ctrl->sensormode = mode;
return rc;
} /*end of vx6953_snapshot_config*/
static int32_t vx6953_raw_snapshot_config(int mode)
{
int32_t rc = 0;
int rt;
/* change sensor resolution if needed */
if (vx6953_ctrl->curr_res != vx6953_ctrl->pict_res) {
if (vx6953_ctrl->pict_res == QTR_SIZE) {
rt = RES_PREVIEW;
vx6953_stm5m0edof_delay_msecs_stdby =
((2 * 1000 * Q8 *
vx6953_ctrl->fps_divider) /
vx6953_ctrl->fps) + 1;
} else {
rt = RES_CAPTURE;
vx6953_stm5m0edof_delay_msecs_stdby =
((1000 * Q8 * vx6953_ctrl->fps_divider)/
vx6953_ctrl->fps) + 1;
}
if (vx6953_sensor_setting(UPDATE_PERIODIC, rt) < 0)
return rc;
}
vx6953_ctrl->edof_mode = VX6953_EDOF_APPLICATION;
if (vx6953_enable_edof(vx6953_ctrl->edof_mode) < 0)
return rc;
vx6953_ctrl->curr_res = vx6953_ctrl->pict_res;
vx6953_ctrl->sensormode = mode;
return rc;
} /*end of vx6953_raw_snapshot_config*/
static int32_t vx6953_set_sensor_mode(int mode,
int res)
{
int32_t rc = 0;
switch (mode) {
case SENSOR_PREVIEW_MODE:
rc = vx6953_video_config(mode);
break;
case SENSOR_SNAPSHOT_MODE:
rc = vx6953_snapshot_config(mode);
break;
case SENSOR_RAW_SNAPSHOT_MODE:
rc = vx6953_raw_snapshot_config(mode);
break;
default:
rc = -EINVAL;
break;
}
return rc;
}
static int32_t vx6953_power_down(void)
{
return 0;
}
static int vx6953_probe_init_done(const struct msm_camera_sensor_info *data)
{
gpio_direction_output(data->sensor_reset, 0);
gpio_free(data->sensor_reset);
return 0;
}
static int vx6953_probe_init_sensor(const struct msm_camera_sensor_info *data)
{
int32_t rc = 0;
unsigned short chipidl, chipidh;
CDBG("%s: %d\n", __func__, __LINE__);
rc = gpio_request(data->sensor_reset, "vx6953");
CDBG(" vx6953_probe_init_sensor \n");
if (!rc) {
CDBG("sensor_reset = %d\n", rc);
CDBG(" vx6953_probe_init_sensor 1\n");
gpio_direction_output(data->sensor_reset, 0);
mdelay(50);
CDBG(" vx6953_probe_init_sensor 1\n");
gpio_direction_output(data->sensor_reset, 1);
mdelay(13);
} else {
CDBG(" vx6953_probe_init_sensor 2\n");
goto init_probe_done;
}
mdelay(20);
CDBG(" vx6953_probe_init_sensor is called \n");
/* 3. Read sensor Model ID: */
rc = vx6953_i2c_read(0x0000, &chipidh, 1);
if (rc < 0) {
CDBG(" vx6953_probe_init_sensor 3 \n");
goto init_probe_fail;
}
rc = vx6953_i2c_read(0x0001, &chipidl, 1);
if (rc < 0) {
CDBG(" vx6953_probe_init_sensor4 \n");
goto init_probe_fail;
}
CDBG("vx6953 model_id = 0x%x 0x%x\n", chipidh, chipidl);
/* 4. Compare sensor ID to VX6953 ID: */
if (chipidh != 0x03 || chipidl != 0xB9) {
rc = -ENODEV;
CDBG("vx6953_probe_init_sensor fail chip id doesnot match\n");
goto init_probe_fail;
}
goto init_probe_done;
init_probe_fail:
CDBG(" vx6953_probe_init_sensor fails\n");
vx6953_probe_init_done(data);
init_probe_done:
CDBG(" vx6953_probe_init_sensor finishes\n");
return rc;
}
/* camsensor_iu060f_vx6953_reset */
int vx6953_sensor_open_init(const struct msm_camera_sensor_info *data)
{
unsigned short revision_number;
int32_t rc = 0;
struct msm_camera_csi_params *vx6953_csi_params =
kzalloc(sizeof(struct msm_camera_csi_params), GFP_KERNEL);
CDBG("%s: %d\n", __func__, __LINE__);
CDBG("Calling vx6953_sensor_open_init\n");
vx6953_ctrl = kzalloc(sizeof(struct vx6953_ctrl_t), GFP_KERNEL);
if (!vx6953_ctrl) {
CDBG("vx6953_init failed!\n");
rc = -ENOMEM;
goto init_done;
}
vx6953_ctrl->fps_divider = 1 * 0x00000100;
vx6953_ctrl->pict_fps_divider = 1 * 0x00000100;
vx6953_ctrl->set_test = TEST_OFF;
vx6953_ctrl->prev_res = QTR_SIZE;
vx6953_ctrl->pict_res = FULL_SIZE;
vx6953_ctrl->curr_res = INVALID_SIZE;
vx6953_ctrl->sensor_type = VX6953_STM5M0EDOF_CUT_2;
vx6953_ctrl->edof_mode = VX6953_EDOF_ESTIMATION;
if (data)
vx6953_ctrl->sensordata = data;
if (rc < 0) {
CDBG("Calling vx6953_sensor_open_init fail1\n");
return rc;
}
CDBG("%s: %d\n", __func__, __LINE__);
/* enable mclk first */
msm_camio_clk_rate_set(VX6953_STM5M0EDOF_DEFAULT_MASTER_CLK_RATE);
mdelay(20);
CDBG("%s: %d\n", __func__, __LINE__);
rc = vx6953_probe_init_sensor(data);
if (rc < 0) {
CDBG("Calling vx6953_sensor_open_init fail3\n");
goto init_fail;
}
if (rc < 0) {
CDBG("Calling vx6953_sensor_open_init fail5\n");
return rc;
}
if (vx6953_i2c_read(0x0002, &revision_number, 1) < 0)
return rc;
CDBG("sensor revision number major = 0x%x\n", revision_number);
if (vx6953_i2c_read(0x0018, &revision_number, 1) < 0)
return rc;
CDBG("sensor revision number = 0x%x\n", revision_number);
if (revision_number == VX6953_REVISION_NUMBER) {
vx6953_ctrl->sensor_type = VX6953_STM5M0EDOF_CUT_2;
CDBG("VX6953 EDof Cut 2.0 sensor\n ");
} else {/* Cut1.0 reads 0x00 for register 0x0018*/
vx6953_ctrl->sensor_type = VX6953_STM5M0EDOF_CUT_1;
CDBG("VX6953 EDof Cut 1.0 sensor \n");
}
/* config mipi csi controller */
CDBG("vx6953_sensor_open_init: config csi controller \n");
vx6953_csi_params->data_format = CSI_8BIT;
vx6953_csi_params->lane_cnt = 1;
vx6953_csi_params->lane_assign = 0xe4;
vx6953_csi_params->dpcm_scheme = 0;
vx6953_csi_params->settle_cnt = 7;
rc = msm_camio_csi_config(vx6953_csi_params);
if (rc < 0)
CDBG(" config csi controller failed \n");
if (vx6953_ctrl->prev_res == QTR_SIZE) {
if (vx6953_sensor_setting(REG_INIT, RES_PREVIEW) < 0)
return rc;
} else {
if (vx6953_sensor_setting(REG_INIT, RES_CAPTURE) < 0)
return rc;
}
vx6953_ctrl->fps = 30*Q8;
if (rc < 0)
goto init_fail;
else
goto init_done;
init_fail:
CDBG(" init_fail \n");
vx6953_probe_init_done(data);
kfree(vx6953_ctrl);
init_done:
CDBG("init_done \n");
return rc;
} /*endof vx6953_sensor_open_init*/
static int vx6953_init_client(struct i2c_client *client)
{
/* Initialize the MSM_CAMI2C Chip */
init_waitqueue_head(&vx6953_wait_queue);
return 0;
}
static const struct i2c_device_id vx6953_i2c_id[] = {
{"vx6953", 0},
{ }
};
static int vx6953_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int rc = 0;
CDBG("vx6953_probe called!\n");
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
CDBG("i2c_check_functionality failed\n");
goto probe_failure;
}
vx6953_sensorw = kzalloc(sizeof(struct vx6953_work_t), GFP_KERNEL);
if (!vx6953_sensorw) {
CDBG("kzalloc failed.\n");
rc = -ENOMEM;
goto probe_failure;
}
i2c_set_clientdata(client, vx6953_sensorw);
vx6953_init_client(client);
vx6953_client = client;
mdelay(50);
CDBG("vx6953_probe successed! rc = %d\n", rc);
return 0;
probe_failure:
CDBG("vx6953_probe failed! rc = %d\n", rc);
return rc;
}
static int vx6953_send_wb_info(struct wb_info_cfg *wb)
{
unsigned short read_data;
uint8_t temp[8];
int rc = 0;
int i = 0;
/* red_gain */
temp[2] = wb->red_gain >> 8;
temp[3] = wb->red_gain & 0xFF;
/* green_gain */
temp[0] = wb->green_gain >> 8;
temp[1] = wb->green_gain & 0xFF;
temp[6] = temp[0];
temp[7] = temp[1];
/* blue_gain */
temp[4] = wb->blue_gain >> 8;
temp[5] = wb->blue_gain & 0xFF;
rc = vx6953_i2c_write_seq_sensor(0x0B8E, &temp[0], 8);
for (i = 0; i < 6; i++) {
rc = vx6953_i2c_read(0x0B8E + i, &read_data, 1);
CDBG("%s addr 0x%x val %d \n", __func__, 0x0B8E + i, read_data);
}
rc = vx6953_i2c_read(0x0B82, &read_data, 1);
CDBG("%s addr 0x%x val %d \n", __func__, 0x0B82, read_data);
if (rc < 0)
return rc;
return rc;
} /*end of vx6953_snapshot_config*/
static int __exit vx6953_remove(struct i2c_client *client)
{
struct vx6953_work_t_t *sensorw = i2c_get_clientdata(client);
free_irq(client->irq, sensorw);
vx6953_client = NULL;
kfree(sensorw);
return 0;
}
static struct i2c_driver vx6953_i2c_driver = {
.id_table = vx6953_i2c_id,
.probe = vx6953_i2c_probe,
.remove = __exit_p(vx6953_i2c_remove),
.driver = {
.name = "vx6953",
},
};
int vx6953_sensor_config(void __user *argp)
{
struct sensor_cfg_data cdata;
long rc = 0;
if (copy_from_user(&cdata,
(void *)argp,
sizeof(struct sensor_cfg_data)))
return -EFAULT;
mutex_lock(&vx6953_mut);
CDBG("vx6953_sensor_config: cfgtype = %d\n",
cdata.cfgtype);
switch (cdata.cfgtype) {
case CFG_GET_PICT_FPS:
vx6953_get_pict_fps(
cdata.cfg.gfps.prevfps,
&(cdata.cfg.gfps.pictfps));
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_GET_PREV_L_PF:
cdata.cfg.prevl_pf =
vx6953_get_prev_lines_pf();
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_GET_PREV_P_PL:
cdata.cfg.prevp_pl =
vx6953_get_prev_pixels_pl();
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_GET_PICT_L_PF:
cdata.cfg.pictl_pf =
vx6953_get_pict_lines_pf();
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_GET_PICT_P_PL:
cdata.cfg.pictp_pl =
vx6953_get_pict_pixels_pl();
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_GET_PICT_MAX_EXP_LC:
cdata.cfg.pict_max_exp_lc =
vx6953_get_pict_max_exp_lc();
if (copy_to_user((void *)argp,
&cdata,
sizeof(struct sensor_cfg_data)))
rc = -EFAULT;
break;
case CFG_SET_FPS:
case CFG_SET_PICT_FPS:
rc = vx6953_set_fps(&(cdata.cfg.fps));
break;
case CFG_SET_EXP_GAIN:
rc =
vx6953_write_exp_gain(
cdata.cfg.exp_gain.gain,
cdata.cfg.exp_gain.line);
break;
case CFG_SET_PICT_EXP_GAIN:
rc =
vx6953_set_pict_exp_gain(
cdata.cfg.exp_gain.gain,
cdata.cfg.exp_gain.line);
break;
case CFG_SET_MODE:
rc = vx6953_set_sensor_mode(cdata.mode,
cdata.rs);
break;
case CFG_PWR_DOWN:
rc = vx6953_power_down();
break;
case CFG_MOVE_FOCUS:
rc =
vx6953_move_focus(
cdata.cfg.focus.dir,
cdata.cfg.focus.steps);
break;
case CFG_SET_DEFAULT_FOCUS:
rc =
vx6953_set_default_focus(
cdata.cfg.focus.steps);
break;
case CFG_SET_EFFECT:
rc = vx6953_set_default_focus(
cdata.cfg.effect);
break;
case CFG_SEND_WB_INFO:
rc = vx6953_send_wb_info(
&(cdata.cfg.wb_info));
break;
default:
rc = -EFAULT;
break;
}
mutex_unlock(&vx6953_mut);
return rc;
}
static int vx6953_sensor_release(void)
{
int rc = -EBADF;
mutex_lock(&vx6953_mut);
vx6953_power_down();
gpio_direction_output(vx6953_ctrl->sensordata->sensor_reset,
0);
gpio_free(vx6953_ctrl->sensordata->sensor_reset);
kfree(vx6953_ctrl);
vx6953_ctrl = NULL;
CDBG("vx6953_release completed\n");
mutex_unlock(&vx6953_mut);
return rc;
}
static int vx6953_sensor_probe(const struct msm_camera_sensor_info *info,
struct msm_sensor_ctrl *s)
{
int rc = 0;
rc = i2c_add_driver(&vx6953_i2c_driver);
if (rc < 0 || vx6953_client == NULL) {
rc = -ENOTSUPP;
goto probe_fail;
}
msm_camio_clk_rate_set(24000000);
rc = vx6953_probe_init_sensor(info);
if (rc < 0)
goto probe_fail;
s->s_init = vx6953_sensor_open_init;
s->s_release = vx6953_sensor_release;
s->s_config = vx6953_sensor_config;
vx6953_probe_init_done(info);
return rc;
probe_fail:
CDBG("vx6953_sensor_probe: SENSOR PROBE FAILS!\n");
return rc;
}
static int __vx6953_probe(struct platform_device *pdev)
{
return msm_camera_drv_start(pdev, vx6953_sensor_probe);
}
static struct platform_driver msm_camera_driver = {
.probe = __vx6953_probe,
.driver = {
.name = "msm_camera_vx6953",
.owner = THIS_MODULE,
},
};
static int __init vx6953_init(void)
{
return platform_driver_register(&msm_camera_driver);
}
module_init(vx6953_init);
void vx6953_exit(void)
{
i2c_del_driver(&vx6953_i2c_driver);
}
| gpl-2.0 |
Vangreen/android_kernel_lge_msm8926 | fs/nilfs2/inode.c | 549 | 29260 | /*
* inode.c - NILFS inode operations.
*
* Copyright (C) 2005-2008 Nippon Telegraph and Telephone Corporation.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Written by Ryusuke Konishi <ryusuke@osrg.net>
*
*/
#include <linux/buffer_head.h>
#include <linux/gfp.h>
#include <linux/mpage.h>
#include <linux/writeback.h>
#include <linux/uio.h>
#include "nilfs.h"
#include "btnode.h"
#include "segment.h"
#include "page.h"
#include "mdt.h"
#include "cpfile.h"
#include "ifile.h"
struct nilfs_iget_args {
u64 ino;
__u64 cno;
struct nilfs_root *root;
int for_gc;
};
void nilfs_inode_add_blocks(struct inode *inode, int n)
{
struct nilfs_root *root = NILFS_I(inode)->i_root;
inode_add_bytes(inode, (1 << inode->i_blkbits) * n);
if (root)
atomic_add(n, &root->blocks_count);
}
void nilfs_inode_sub_blocks(struct inode *inode, int n)
{
struct nilfs_root *root = NILFS_I(inode)->i_root;
inode_sub_bytes(inode, (1 << inode->i_blkbits) * n);
if (root)
atomic_sub(n, &root->blocks_count);
}
/**
* nilfs_get_block() - get a file block on the filesystem (callback function)
* @inode - inode struct of the target file
* @blkoff - file block number
* @bh_result - buffer head to be mapped on
* @create - indicate whether allocating the block or not when it has not
* been allocated yet.
*
* This function does not issue actual read request of the specified data
* block. It is done by VFS.
*/
int nilfs_get_block(struct inode *inode, sector_t blkoff,
struct buffer_head *bh_result, int create)
{
struct nilfs_inode_info *ii = NILFS_I(inode);
struct the_nilfs *nilfs = inode->i_sb->s_fs_info;
__u64 blknum = 0;
int err = 0, ret;
unsigned maxblocks = bh_result->b_size >> inode->i_blkbits;
down_read(&NILFS_MDT(nilfs->ns_dat)->mi_sem);
ret = nilfs_bmap_lookup_contig(ii->i_bmap, blkoff, &blknum, maxblocks);
up_read(&NILFS_MDT(nilfs->ns_dat)->mi_sem);
if (ret >= 0) { /* found */
map_bh(bh_result, inode->i_sb, blknum);
if (ret > 0)
bh_result->b_size = (ret << inode->i_blkbits);
goto out;
}
/* data block was not found */
if (ret == -ENOENT && create) {
struct nilfs_transaction_info ti;
bh_result->b_blocknr = 0;
err = nilfs_transaction_begin(inode->i_sb, &ti, 1);
if (unlikely(err))
goto out;
err = nilfs_bmap_insert(ii->i_bmap, (unsigned long)blkoff,
(unsigned long)bh_result);
if (unlikely(err != 0)) {
if (err == -EEXIST) {
/*
* The get_block() function could be called
* from multiple callers for an inode.
* However, the page having this block must
* be locked in this case.
*/
printk(KERN_WARNING
"nilfs_get_block: a race condition "
"while inserting a data block. "
"(inode number=%lu, file block "
"offset=%llu)\n",
inode->i_ino,
(unsigned long long)blkoff);
err = 0;
}
nilfs_transaction_abort(inode->i_sb);
goto out;
}
nilfs_mark_inode_dirty(inode);
nilfs_transaction_commit(inode->i_sb); /* never fails */
/* Error handling should be detailed */
set_buffer_new(bh_result);
set_buffer_delay(bh_result);
map_bh(bh_result, inode->i_sb, 0); /* dbn must be changed
to proper value */
} else if (ret == -ENOENT) {
/* not found is not error (e.g. hole); must return without
the mapped state flag. */
;
} else {
err = ret;
}
out:
return err;
}
/**
* nilfs_readpage() - implement readpage() method of nilfs_aops {}
* address_space_operations.
* @file - file struct of the file to be read
* @page - the page to be read
*/
static int nilfs_readpage(struct file *file, struct page *page)
{
return mpage_readpage(page, nilfs_get_block);
}
/**
* nilfs_readpages() - implement readpages() method of nilfs_aops {}
* address_space_operations.
* @file - file struct of the file to be read
* @mapping - address_space struct used for reading multiple pages
* @pages - the pages to be read
* @nr_pages - number of pages to be read
*/
static int nilfs_readpages(struct file *file, struct address_space *mapping,
struct list_head *pages, unsigned nr_pages)
{
return mpage_readpages(mapping, pages, nr_pages, nilfs_get_block);
}
static int nilfs_writepages(struct address_space *mapping,
struct writeback_control *wbc)
{
struct inode *inode = mapping->host;
int err = 0;
if (wbc->sync_mode == WB_SYNC_ALL)
err = nilfs_construct_dsync_segment(inode->i_sb, inode,
wbc->range_start,
wbc->range_end);
return err;
}
static int nilfs_writepage(struct page *page, struct writeback_control *wbc)
{
struct inode *inode = page->mapping->host;
int err;
redirty_page_for_writepage(wbc, page);
unlock_page(page);
if (wbc->sync_mode == WB_SYNC_ALL) {
err = nilfs_construct_segment(inode->i_sb);
if (unlikely(err))
return err;
} else if (wbc->for_reclaim)
nilfs_flush_segment(inode->i_sb, inode->i_ino);
return 0;
}
static int nilfs_set_page_dirty(struct page *page)
{
int ret = __set_page_dirty_nobuffers(page);
if (page_has_buffers(page)) {
struct inode *inode = page->mapping->host;
unsigned nr_dirty = 0;
struct buffer_head *bh, *head;
/*
* This page is locked by callers, and no other thread
* concurrently marks its buffers dirty since they are
* only dirtied through routines in fs/buffer.c in
* which call sites of mark_buffer_dirty are protected
* by page lock.
*/
bh = head = page_buffers(page);
do {
/* Do not mark hole blocks dirty */
if (buffer_dirty(bh) || !buffer_mapped(bh))
continue;
set_buffer_dirty(bh);
nr_dirty++;
} while (bh = bh->b_this_page, bh != head);
if (nr_dirty)
nilfs_set_file_dirty(inode, nr_dirty);
}
return ret;
}
static int nilfs_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
struct inode *inode = mapping->host;
int err = nilfs_transaction_begin(inode->i_sb, NULL, 1);
if (unlikely(err))
return err;
err = block_write_begin(mapping, pos, len, flags, pagep,
nilfs_get_block);
if (unlikely(err)) {
loff_t isize = mapping->host->i_size;
if (pos + len > isize)
vmtruncate(mapping->host, isize);
nilfs_transaction_abort(inode->i_sb);
}
return err;
}
static int nilfs_write_end(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
struct inode *inode = mapping->host;
unsigned start = pos & (PAGE_CACHE_SIZE - 1);
unsigned nr_dirty;
int err;
nr_dirty = nilfs_page_count_clean_buffers(page, start,
start + copied);
copied = generic_write_end(file, mapping, pos, len, copied, page,
fsdata);
nilfs_set_file_dirty(inode, nr_dirty);
err = nilfs_transaction_commit(inode->i_sb);
return err ? : copied;
}
static ssize_t
nilfs_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
loff_t offset, unsigned long nr_segs)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
ssize_t size;
if (rw == WRITE)
return 0;
/* Needs synchronization with the cleaner */
size = blockdev_direct_IO(rw, iocb, inode, iov, offset, nr_segs,
nilfs_get_block);
/*
* In case of error extending write may have instantiated a few
* blocks outside i_size. Trim these off again.
*/
if (unlikely((rw & WRITE) && size < 0)) {
loff_t isize = i_size_read(inode);
loff_t end = offset + iov_length(iov, nr_segs);
if (end > isize)
vmtruncate(inode, isize);
}
return size;
}
const struct address_space_operations nilfs_aops = {
.writepage = nilfs_writepage,
.readpage = nilfs_readpage,
.writepages = nilfs_writepages,
.set_page_dirty = nilfs_set_page_dirty,
.readpages = nilfs_readpages,
.write_begin = nilfs_write_begin,
.write_end = nilfs_write_end,
/* .releasepage = nilfs_releasepage, */
.invalidatepage = block_invalidatepage,
.direct_IO = nilfs_direct_IO,
.is_partially_uptodate = block_is_partially_uptodate,
};
struct inode *nilfs_new_inode(struct inode *dir, umode_t mode)
{
struct super_block *sb = dir->i_sb;
struct the_nilfs *nilfs = sb->s_fs_info;
struct inode *inode;
struct nilfs_inode_info *ii;
struct nilfs_root *root;
int err = -ENOMEM;
ino_t ino;
inode = new_inode(sb);
if (unlikely(!inode))
goto failed;
mapping_set_gfp_mask(inode->i_mapping,
mapping_gfp_mask(inode->i_mapping) & ~__GFP_FS);
root = NILFS_I(dir)->i_root;
ii = NILFS_I(inode);
ii->i_state = 1 << NILFS_I_NEW;
ii->i_root = root;
err = nilfs_ifile_create_inode(root->ifile, &ino, &ii->i_bh);
if (unlikely(err))
goto failed_ifile_create_inode;
/* reference count of i_bh inherits from nilfs_mdt_read_block() */
atomic_inc(&root->inodes_count);
inode_init_owner(inode, dir, mode);
inode->i_ino = ino;
inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
if (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)) {
err = nilfs_bmap_read(ii->i_bmap, NULL);
if (err < 0)
goto failed_bmap;
set_bit(NILFS_I_BMAP, &ii->i_state);
/* No lock is needed; iget() ensures it. */
}
ii->i_flags = nilfs_mask_flags(
mode, NILFS_I(dir)->i_flags & NILFS_FL_INHERITED);
/* ii->i_file_acl = 0; */
/* ii->i_dir_acl = 0; */
ii->i_dir_start_lookup = 0;
nilfs_set_inode_flags(inode);
spin_lock(&nilfs->ns_next_gen_lock);
inode->i_generation = nilfs->ns_next_generation++;
spin_unlock(&nilfs->ns_next_gen_lock);
insert_inode_hash(inode);
err = nilfs_init_acl(inode, dir);
if (unlikely(err))
goto failed_acl; /* never occur. When supporting
nilfs_init_acl(), proper cancellation of
above jobs should be considered */
return inode;
failed_acl:
failed_bmap:
clear_nlink(inode);
iput(inode); /* raw_inode will be deleted through
generic_delete_inode() */
goto failed;
failed_ifile_create_inode:
make_bad_inode(inode);
iput(inode); /* if i_nlink == 1, generic_forget_inode() will be
called */
failed:
return ERR_PTR(err);
}
void nilfs_set_inode_flags(struct inode *inode)
{
unsigned int flags = NILFS_I(inode)->i_flags;
inode->i_flags &= ~(S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME |
S_DIRSYNC);
if (flags & FS_SYNC_FL)
inode->i_flags |= S_SYNC;
if (flags & FS_APPEND_FL)
inode->i_flags |= S_APPEND;
if (flags & FS_IMMUTABLE_FL)
inode->i_flags |= S_IMMUTABLE;
if (flags & FS_NOATIME_FL)
inode->i_flags |= S_NOATIME;
if (flags & FS_DIRSYNC_FL)
inode->i_flags |= S_DIRSYNC;
mapping_set_gfp_mask(inode->i_mapping,
mapping_gfp_mask(inode->i_mapping) & ~__GFP_FS);
}
int nilfs_read_inode_common(struct inode *inode,
struct nilfs_inode *raw_inode)
{
struct nilfs_inode_info *ii = NILFS_I(inode);
int err;
inode->i_mode = le16_to_cpu(raw_inode->i_mode);
inode->i_uid = (uid_t)le32_to_cpu(raw_inode->i_uid);
inode->i_gid = (gid_t)le32_to_cpu(raw_inode->i_gid);
set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
inode->i_size = le64_to_cpu(raw_inode->i_size);
inode->i_atime.tv_sec = le64_to_cpu(raw_inode->i_mtime);
inode->i_ctime.tv_sec = le64_to_cpu(raw_inode->i_ctime);
inode->i_mtime.tv_sec = le64_to_cpu(raw_inode->i_mtime);
inode->i_atime.tv_nsec = le32_to_cpu(raw_inode->i_mtime_nsec);
inode->i_ctime.tv_nsec = le32_to_cpu(raw_inode->i_ctime_nsec);
inode->i_mtime.tv_nsec = le32_to_cpu(raw_inode->i_mtime_nsec);
if (inode->i_nlink == 0 && inode->i_mode == 0)
return -EINVAL; /* this inode is deleted */
inode->i_blocks = le64_to_cpu(raw_inode->i_blocks);
ii->i_flags = le32_to_cpu(raw_inode->i_flags);
#if 0
ii->i_file_acl = le32_to_cpu(raw_inode->i_file_acl);
ii->i_dir_acl = S_ISREG(inode->i_mode) ?
0 : le32_to_cpu(raw_inode->i_dir_acl);
#endif
ii->i_dir_start_lookup = 0;
inode->i_generation = le32_to_cpu(raw_inode->i_generation);
if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
S_ISLNK(inode->i_mode)) {
err = nilfs_bmap_read(ii->i_bmap, raw_inode);
if (err < 0)
return err;
set_bit(NILFS_I_BMAP, &ii->i_state);
/* No lock is needed; iget() ensures it. */
}
return 0;
}
static int __nilfs_read_inode(struct super_block *sb,
struct nilfs_root *root, unsigned long ino,
struct inode *inode)
{
struct the_nilfs *nilfs = sb->s_fs_info;
struct buffer_head *bh;
struct nilfs_inode *raw_inode;
int err;
down_read(&NILFS_MDT(nilfs->ns_dat)->mi_sem);
err = nilfs_ifile_get_inode_block(root->ifile, ino, &bh);
if (unlikely(err))
goto bad_inode;
raw_inode = nilfs_ifile_map_inode(root->ifile, ino, bh);
err = nilfs_read_inode_common(inode, raw_inode);
if (err)
goto failed_unmap;
if (S_ISREG(inode->i_mode)) {
inode->i_op = &nilfs_file_inode_operations;
inode->i_fop = &nilfs_file_operations;
inode->i_mapping->a_ops = &nilfs_aops;
} else if (S_ISDIR(inode->i_mode)) {
inode->i_op = &nilfs_dir_inode_operations;
inode->i_fop = &nilfs_dir_operations;
inode->i_mapping->a_ops = &nilfs_aops;
} else if (S_ISLNK(inode->i_mode)) {
inode->i_op = &nilfs_symlink_inode_operations;
inode->i_mapping->a_ops = &nilfs_aops;
} else {
inode->i_op = &nilfs_special_inode_operations;
init_special_inode(
inode, inode->i_mode,
huge_decode_dev(le64_to_cpu(raw_inode->i_device_code)));
}
nilfs_ifile_unmap_inode(root->ifile, ino, bh);
brelse(bh);
up_read(&NILFS_MDT(nilfs->ns_dat)->mi_sem);
nilfs_set_inode_flags(inode);
return 0;
failed_unmap:
nilfs_ifile_unmap_inode(root->ifile, ino, bh);
brelse(bh);
bad_inode:
up_read(&NILFS_MDT(nilfs->ns_dat)->mi_sem);
return err;
}
static int nilfs_iget_test(struct inode *inode, void *opaque)
{
struct nilfs_iget_args *args = opaque;
struct nilfs_inode_info *ii;
if (args->ino != inode->i_ino || args->root != NILFS_I(inode)->i_root)
return 0;
ii = NILFS_I(inode);
if (!test_bit(NILFS_I_GCINODE, &ii->i_state))
return !args->for_gc;
return args->for_gc && args->cno == ii->i_cno;
}
static int nilfs_iget_set(struct inode *inode, void *opaque)
{
struct nilfs_iget_args *args = opaque;
inode->i_ino = args->ino;
if (args->for_gc) {
NILFS_I(inode)->i_state = 1 << NILFS_I_GCINODE;
NILFS_I(inode)->i_cno = args->cno;
NILFS_I(inode)->i_root = NULL;
} else {
if (args->root && args->ino == NILFS_ROOT_INO)
nilfs_get_root(args->root);
NILFS_I(inode)->i_root = args->root;
}
return 0;
}
struct inode *nilfs_ilookup(struct super_block *sb, struct nilfs_root *root,
unsigned long ino)
{
struct nilfs_iget_args args = {
.ino = ino, .root = root, .cno = 0, .for_gc = 0
};
return ilookup5(sb, ino, nilfs_iget_test, &args);
}
struct inode *nilfs_iget_locked(struct super_block *sb, struct nilfs_root *root,
unsigned long ino)
{
struct nilfs_iget_args args = {
.ino = ino, .root = root, .cno = 0, .for_gc = 0
};
return iget5_locked(sb, ino, nilfs_iget_test, nilfs_iget_set, &args);
}
struct inode *nilfs_iget(struct super_block *sb, struct nilfs_root *root,
unsigned long ino)
{
struct inode *inode;
int err;
inode = nilfs_iget_locked(sb, root, ino);
if (unlikely(!inode))
return ERR_PTR(-ENOMEM);
if (!(inode->i_state & I_NEW))
return inode;
err = __nilfs_read_inode(sb, root, ino, inode);
if (unlikely(err)) {
iget_failed(inode);
return ERR_PTR(err);
}
unlock_new_inode(inode);
return inode;
}
struct inode *nilfs_iget_for_gc(struct super_block *sb, unsigned long ino,
__u64 cno)
{
struct nilfs_iget_args args = {
.ino = ino, .root = NULL, .cno = cno, .for_gc = 1
};
struct inode *inode;
int err;
inode = iget5_locked(sb, ino, nilfs_iget_test, nilfs_iget_set, &args);
if (unlikely(!inode))
return ERR_PTR(-ENOMEM);
if (!(inode->i_state & I_NEW))
return inode;
err = nilfs_init_gcinode(inode);
if (unlikely(err)) {
iget_failed(inode);
return ERR_PTR(err);
}
unlock_new_inode(inode);
return inode;
}
void nilfs_write_inode_common(struct inode *inode,
struct nilfs_inode *raw_inode, int has_bmap)
{
struct nilfs_inode_info *ii = NILFS_I(inode);
raw_inode->i_mode = cpu_to_le16(inode->i_mode);
raw_inode->i_uid = cpu_to_le32(inode->i_uid);
raw_inode->i_gid = cpu_to_le32(inode->i_gid);
raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
raw_inode->i_size = cpu_to_le64(inode->i_size);
raw_inode->i_ctime = cpu_to_le64(inode->i_ctime.tv_sec);
raw_inode->i_mtime = cpu_to_le64(inode->i_mtime.tv_sec);
raw_inode->i_ctime_nsec = cpu_to_le32(inode->i_ctime.tv_nsec);
raw_inode->i_mtime_nsec = cpu_to_le32(inode->i_mtime.tv_nsec);
raw_inode->i_blocks = cpu_to_le64(inode->i_blocks);
raw_inode->i_flags = cpu_to_le32(ii->i_flags);
raw_inode->i_generation = cpu_to_le32(inode->i_generation);
if (NILFS_ROOT_METADATA_FILE(inode->i_ino)) {
struct the_nilfs *nilfs = inode->i_sb->s_fs_info;
/* zero-fill unused portion in the case of super root block */
raw_inode->i_xattr = 0;
raw_inode->i_pad = 0;
memset((void *)raw_inode + sizeof(*raw_inode), 0,
nilfs->ns_inode_size - sizeof(*raw_inode));
}
if (has_bmap)
nilfs_bmap_write(ii->i_bmap, raw_inode);
else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode))
raw_inode->i_device_code =
cpu_to_le64(huge_encode_dev(inode->i_rdev));
/* When extending inode, nilfs->ns_inode_size should be checked
for substitutions of appended fields */
}
void nilfs_update_inode(struct inode *inode, struct buffer_head *ibh)
{
ino_t ino = inode->i_ino;
struct nilfs_inode_info *ii = NILFS_I(inode);
struct inode *ifile = ii->i_root->ifile;
struct nilfs_inode *raw_inode;
raw_inode = nilfs_ifile_map_inode(ifile, ino, ibh);
if (test_and_clear_bit(NILFS_I_NEW, &ii->i_state))
memset(raw_inode, 0, NILFS_MDT(ifile)->mi_entry_size);
set_bit(NILFS_I_INODE_DIRTY, &ii->i_state);
nilfs_write_inode_common(inode, raw_inode, 0);
/* XXX: call with has_bmap = 0 is a workaround to avoid
deadlock of bmap. This delays update of i_bmap to just
before writing */
nilfs_ifile_unmap_inode(ifile, ino, ibh);
}
#define NILFS_MAX_TRUNCATE_BLOCKS 16384 /* 64MB for 4KB block */
static void nilfs_truncate_bmap(struct nilfs_inode_info *ii,
unsigned long from)
{
unsigned long b;
int ret;
if (!test_bit(NILFS_I_BMAP, &ii->i_state))
return;
repeat:
ret = nilfs_bmap_last_key(ii->i_bmap, &b);
if (ret == -ENOENT)
return;
else if (ret < 0)
goto failed;
if (b < from)
return;
b -= min_t(unsigned long, NILFS_MAX_TRUNCATE_BLOCKS, b - from);
ret = nilfs_bmap_truncate(ii->i_bmap, b);
nilfs_relax_pressure_in_lock(ii->vfs_inode.i_sb);
if (!ret || (ret == -ENOMEM &&
nilfs_bmap_truncate(ii->i_bmap, b) == 0))
goto repeat;
failed:
nilfs_warning(ii->vfs_inode.i_sb, __func__,
"failed to truncate bmap (ino=%lu, err=%d)",
ii->vfs_inode.i_ino, ret);
}
void nilfs_truncate(struct inode *inode)
{
unsigned long blkoff;
unsigned int blocksize;
struct nilfs_transaction_info ti;
struct super_block *sb = inode->i_sb;
struct nilfs_inode_info *ii = NILFS_I(inode);
if (!test_bit(NILFS_I_BMAP, &ii->i_state))
return;
if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
return;
blocksize = sb->s_blocksize;
blkoff = (inode->i_size + blocksize - 1) >> sb->s_blocksize_bits;
nilfs_transaction_begin(sb, &ti, 0); /* never fails */
block_truncate_page(inode->i_mapping, inode->i_size, nilfs_get_block);
nilfs_truncate_bmap(ii, blkoff);
inode->i_mtime = inode->i_ctime = CURRENT_TIME;
if (IS_SYNC(inode))
nilfs_set_transaction_flag(NILFS_TI_SYNC);
nilfs_mark_inode_dirty(inode);
nilfs_set_file_dirty(inode, 0);
nilfs_transaction_commit(sb);
/* May construct a logical segment and may fail in sync mode.
But truncate has no return value. */
}
static void nilfs_clear_inode(struct inode *inode)
{
struct nilfs_inode_info *ii = NILFS_I(inode);
struct nilfs_mdt_info *mdi = NILFS_MDT(inode);
/*
* Free resources allocated in nilfs_read_inode(), here.
*/
BUG_ON(!list_empty(&ii->i_dirty));
brelse(ii->i_bh);
ii->i_bh = NULL;
if (mdi && mdi->mi_palloc_cache)
nilfs_palloc_destroy_cache(inode);
if (test_bit(NILFS_I_BMAP, &ii->i_state))
nilfs_bmap_clear(ii->i_bmap);
nilfs_btnode_cache_clear(&ii->i_btnode_cache);
if (ii->i_root && inode->i_ino == NILFS_ROOT_INO)
nilfs_put_root(ii->i_root);
}
void nilfs_evict_inode(struct inode *inode)
{
struct nilfs_transaction_info ti;
struct super_block *sb = inode->i_sb;
struct nilfs_inode_info *ii = NILFS_I(inode);
int ret;
if (inode->i_nlink || !ii->i_root || unlikely(is_bad_inode(inode))) {
if (inode->i_data.nrpages)
truncate_inode_pages(&inode->i_data, 0);
end_writeback(inode);
nilfs_clear_inode(inode);
return;
}
nilfs_transaction_begin(sb, &ti, 0); /* never fails */
if (inode->i_data.nrpages)
truncate_inode_pages(&inode->i_data, 0);
/* TODO: some of the following operations may fail. */
nilfs_truncate_bmap(ii, 0);
nilfs_mark_inode_dirty(inode);
end_writeback(inode);
ret = nilfs_ifile_delete_inode(ii->i_root->ifile, inode->i_ino);
if (!ret)
atomic_dec(&ii->i_root->inodes_count);
nilfs_clear_inode(inode);
if (IS_SYNC(inode))
nilfs_set_transaction_flag(NILFS_TI_SYNC);
nilfs_transaction_commit(sb);
/* May construct a logical segment and may fail in sync mode.
But delete_inode has no return value. */
}
int nilfs_setattr(struct dentry *dentry, struct iattr *iattr)
{
struct nilfs_transaction_info ti;
struct inode *inode = dentry->d_inode;
struct super_block *sb = inode->i_sb;
int err;
err = inode_change_ok(inode, iattr);
if (err)
return err;
err = nilfs_transaction_begin(sb, &ti, 0);
if (unlikely(err))
return err;
if ((iattr->ia_valid & ATTR_SIZE) &&
iattr->ia_size != i_size_read(inode)) {
inode_dio_wait(inode);
err = vmtruncate(inode, iattr->ia_size);
if (unlikely(err))
goto out_err;
}
setattr_copy(inode, iattr);
mark_inode_dirty(inode);
if (iattr->ia_valid & ATTR_MODE) {
err = nilfs_acl_chmod(inode);
if (unlikely(err))
goto out_err;
}
return nilfs_transaction_commit(sb);
out_err:
nilfs_transaction_abort(sb);
return err;
}
int nilfs_permission(struct inode *inode, int mask)
{
struct nilfs_root *root = NILFS_I(inode)->i_root;
if ((mask & MAY_WRITE) && root &&
root->cno != NILFS_CPTREE_CURRENT_CNO)
return -EROFS; /* snapshot is not writable */
return generic_permission(inode, mask);
}
int nilfs_load_inode_block(struct inode *inode, struct buffer_head **pbh)
{
struct the_nilfs *nilfs = inode->i_sb->s_fs_info;
struct nilfs_inode_info *ii = NILFS_I(inode);
int err;
spin_lock(&nilfs->ns_inode_lock);
if (ii->i_bh == NULL) {
spin_unlock(&nilfs->ns_inode_lock);
err = nilfs_ifile_get_inode_block(ii->i_root->ifile,
inode->i_ino, pbh);
if (unlikely(err))
return err;
spin_lock(&nilfs->ns_inode_lock);
if (ii->i_bh == NULL)
ii->i_bh = *pbh;
else {
brelse(*pbh);
*pbh = ii->i_bh;
}
} else
*pbh = ii->i_bh;
get_bh(*pbh);
spin_unlock(&nilfs->ns_inode_lock);
return 0;
}
int nilfs_inode_dirty(struct inode *inode)
{
struct nilfs_inode_info *ii = NILFS_I(inode);
struct the_nilfs *nilfs = inode->i_sb->s_fs_info;
int ret = 0;
if (!list_empty(&ii->i_dirty)) {
spin_lock(&nilfs->ns_inode_lock);
ret = test_bit(NILFS_I_DIRTY, &ii->i_state) ||
test_bit(NILFS_I_BUSY, &ii->i_state);
spin_unlock(&nilfs->ns_inode_lock);
}
return ret;
}
int nilfs_set_file_dirty(struct inode *inode, unsigned nr_dirty)
{
struct nilfs_inode_info *ii = NILFS_I(inode);
struct the_nilfs *nilfs = inode->i_sb->s_fs_info;
atomic_add(nr_dirty, &nilfs->ns_ndirtyblks);
if (test_and_set_bit(NILFS_I_DIRTY, &ii->i_state))
return 0;
spin_lock(&nilfs->ns_inode_lock);
if (!test_bit(NILFS_I_QUEUED, &ii->i_state) &&
!test_bit(NILFS_I_BUSY, &ii->i_state)) {
/* Because this routine may race with nilfs_dispose_list(),
we have to check NILFS_I_QUEUED here, too. */
if (list_empty(&ii->i_dirty) && igrab(inode) == NULL) {
/* This will happen when somebody is freeing
this inode. */
nilfs_warning(inode->i_sb, __func__,
"cannot get inode (ino=%lu)\n",
inode->i_ino);
spin_unlock(&nilfs->ns_inode_lock);
return -EINVAL; /* NILFS_I_DIRTY may remain for
freeing inode */
}
list_move_tail(&ii->i_dirty, &nilfs->ns_dirty_files);
set_bit(NILFS_I_QUEUED, &ii->i_state);
}
spin_unlock(&nilfs->ns_inode_lock);
return 0;
}
int nilfs_mark_inode_dirty(struct inode *inode)
{
struct buffer_head *ibh;
int err;
err = nilfs_load_inode_block(inode, &ibh);
if (unlikely(err)) {
nilfs_warning(inode->i_sb, __func__,
"failed to reget inode block.\n");
return err;
}
nilfs_update_inode(inode, ibh);
mark_buffer_dirty(ibh);
nilfs_mdt_mark_dirty(NILFS_I(inode)->i_root->ifile);
brelse(ibh);
return 0;
}
/**
* nilfs_dirty_inode - reflect changes on given inode to an inode block.
* @inode: inode of the file to be registered.
*
* nilfs_dirty_inode() loads a inode block containing the specified
* @inode and copies data from a nilfs_inode to a corresponding inode
* entry in the inode block. This operation is excluded from the segment
* construction. This function can be called both as a single operation
* and as a part of indivisible file operations.
*/
void nilfs_dirty_inode(struct inode *inode, int flags)
{
struct nilfs_transaction_info ti;
struct nilfs_mdt_info *mdi = NILFS_MDT(inode);
if (is_bad_inode(inode)) {
nilfs_warning(inode->i_sb, __func__,
"tried to mark bad_inode dirty. ignored.\n");
dump_stack();
return;
}
if (mdi) {
nilfs_mdt_mark_dirty(inode);
return;
}
nilfs_transaction_begin(inode->i_sb, &ti, 0);
nilfs_mark_inode_dirty(inode);
nilfs_transaction_commit(inode->i_sb); /* never fails */
}
int nilfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
__u64 start, __u64 len)
{
struct the_nilfs *nilfs = inode->i_sb->s_fs_info;
__u64 logical = 0, phys = 0, size = 0;
__u32 flags = 0;
loff_t isize;
sector_t blkoff, end_blkoff;
sector_t delalloc_blkoff;
unsigned long delalloc_blklen;
unsigned int blkbits = inode->i_blkbits;
int ret, n;
ret = fiemap_check_flags(fieinfo, FIEMAP_FLAG_SYNC);
if (ret)
return ret;
mutex_lock(&inode->i_mutex);
isize = i_size_read(inode);
blkoff = start >> blkbits;
end_blkoff = (start + len - 1) >> blkbits;
delalloc_blklen = nilfs_find_uncommitted_extent(inode, blkoff,
&delalloc_blkoff);
do {
__u64 blkphy;
unsigned int maxblocks;
if (delalloc_blklen && blkoff == delalloc_blkoff) {
if (size) {
/* End of the current extent */
ret = fiemap_fill_next_extent(
fieinfo, logical, phys, size, flags);
if (ret)
break;
}
if (blkoff > end_blkoff)
break;
flags = FIEMAP_EXTENT_MERGED | FIEMAP_EXTENT_DELALLOC;
logical = blkoff << blkbits;
phys = 0;
size = delalloc_blklen << blkbits;
blkoff = delalloc_blkoff + delalloc_blklen;
delalloc_blklen = nilfs_find_uncommitted_extent(
inode, blkoff, &delalloc_blkoff);
continue;
}
/*
* Limit the number of blocks that we look up so as
* not to get into the next delayed allocation extent.
*/
maxblocks = INT_MAX;
if (delalloc_blklen)
maxblocks = min_t(sector_t, delalloc_blkoff - blkoff,
maxblocks);
blkphy = 0;
down_read(&NILFS_MDT(nilfs->ns_dat)->mi_sem);
n = nilfs_bmap_lookup_contig(
NILFS_I(inode)->i_bmap, blkoff, &blkphy, maxblocks);
up_read(&NILFS_MDT(nilfs->ns_dat)->mi_sem);
if (n < 0) {
int past_eof;
if (unlikely(n != -ENOENT))
break; /* error */
/* HOLE */
blkoff++;
past_eof = ((blkoff << blkbits) >= isize);
if (size) {
/* End of the current extent */
if (past_eof)
flags |= FIEMAP_EXTENT_LAST;
ret = fiemap_fill_next_extent(
fieinfo, logical, phys, size, flags);
if (ret)
break;
size = 0;
}
if (blkoff > end_blkoff || past_eof)
break;
} else {
if (size) {
if (phys && blkphy << blkbits == phys + size) {
/* The current extent goes on */
size += n << blkbits;
} else {
/* Terminate the current extent */
ret = fiemap_fill_next_extent(
fieinfo, logical, phys, size,
flags);
if (ret || blkoff > end_blkoff)
break;
/* Start another extent */
flags = FIEMAP_EXTENT_MERGED;
logical = blkoff << blkbits;
phys = blkphy << blkbits;
size = n << blkbits;
}
} else {
/* Start a new extent */
flags = FIEMAP_EXTENT_MERGED;
logical = blkoff << blkbits;
phys = blkphy << blkbits;
size = n << blkbits;
}
blkoff += n;
}
cond_resched();
} while (true);
/* If ret is 1 then we just hit the end of the extent array */
if (ret == 1)
ret = 0;
mutex_unlock(&inode->i_mutex);
return ret;
}
| gpl-2.0 |
abenagiel/android_kernel_fih_msm7x30 | arch/s390/kernel/setup.c | 805 | 23071 | /*
* arch/s390/kernel/setup.c
*
* S390 version
* Copyright (C) IBM Corp. 1999,2010
* Author(s): Hartmut Penner (hp@de.ibm.com),
* Martin Schwidefsky (schwidefsky@de.ibm.com)
*
* Derived from "arch/i386/kernel/setup.c"
* Copyright (C) 1995, Linus Torvalds
*/
/*
* This file handles the architecture-dependent parts of initialization
*/
#define KMSG_COMPONENT "setup"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/stddef.h>
#include <linux/unistd.h>
#include <linux/ptrace.h>
#include <linux/user.h>
#include <linux/tty.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/initrd.h>
#include <linux/bootmem.h>
#include <linux/root_dev.h>
#include <linux/console.h>
#include <linux/kernel_stat.h>
#include <linux/device.h>
#include <linux/notifier.h>
#include <linux/pfn.h>
#include <linux/ctype.h>
#include <linux/reboot.h>
#include <linux/topology.h>
#include <linux/ftrace.h>
#include <asm/ipl.h>
#include <asm/uaccess.h>
#include <asm/system.h>
#include <asm/smp.h>
#include <asm/mmu_context.h>
#include <asm/cpcmd.h>
#include <asm/lowcore.h>
#include <asm/irq.h>
#include <asm/page.h>
#include <asm/ptrace.h>
#include <asm/sections.h>
#include <asm/ebcdic.h>
#include <asm/compat.h>
#include <asm/kvm_virtio.h>
long psw_kernel_bits = (PSW_BASE_BITS | PSW_MASK_DAT | PSW_ASC_PRIMARY |
PSW_MASK_MCHECK | PSW_DEFAULT_KEY);
long psw_user_bits = (PSW_BASE_BITS | PSW_MASK_DAT | PSW_ASC_HOME |
PSW_MASK_IO | PSW_MASK_EXT | PSW_MASK_MCHECK |
PSW_MASK_PSTATE | PSW_DEFAULT_KEY);
/*
* User copy operations.
*/
struct uaccess_ops uaccess;
EXPORT_SYMBOL(uaccess);
/*
* Machine setup..
*/
unsigned int console_mode = 0;
EXPORT_SYMBOL(console_mode);
unsigned int console_devno = -1;
EXPORT_SYMBOL(console_devno);
unsigned int console_irq = -1;
EXPORT_SYMBOL(console_irq);
unsigned long elf_hwcap = 0;
char elf_platform[ELF_PLATFORM_SIZE];
struct mem_chunk __initdata memory_chunk[MEMORY_CHUNKS];
int __initdata memory_end_set;
unsigned long __initdata memory_end;
/* An array with a pointer to the lowcore of every CPU. */
struct _lowcore *lowcore_ptr[NR_CPUS];
EXPORT_SYMBOL(lowcore_ptr);
/*
* This is set up by the setup-routine at boot-time
* for S390 need to find out, what we have to setup
* using address 0x10400 ...
*/
#include <asm/setup.h>
static struct resource code_resource = {
.name = "Kernel code",
.flags = IORESOURCE_BUSY | IORESOURCE_MEM,
};
static struct resource data_resource = {
.name = "Kernel data",
.flags = IORESOURCE_BUSY | IORESOURCE_MEM,
};
/*
* condev= and conmode= setup parameter.
*/
static int __init condev_setup(char *str)
{
int vdev;
vdev = simple_strtoul(str, &str, 0);
if (vdev >= 0 && vdev < 65536) {
console_devno = vdev;
console_irq = -1;
}
return 1;
}
__setup("condev=", condev_setup);
static void __init set_preferred_console(void)
{
if (MACHINE_IS_KVM)
add_preferred_console("hvc", 0, NULL);
else if (CONSOLE_IS_3215 || CONSOLE_IS_SCLP)
add_preferred_console("ttyS", 0, NULL);
else if (CONSOLE_IS_3270)
add_preferred_console("tty3270", 0, NULL);
}
static int __init conmode_setup(char *str)
{
#if defined(CONFIG_SCLP_CONSOLE) || defined(CONFIG_SCLP_VT220_CONSOLE)
if (strncmp(str, "hwc", 4) == 0 || strncmp(str, "sclp", 5) == 0)
SET_CONSOLE_SCLP;
#endif
#if defined(CONFIG_TN3215_CONSOLE)
if (strncmp(str, "3215", 5) == 0)
SET_CONSOLE_3215;
#endif
#if defined(CONFIG_TN3270_CONSOLE)
if (strncmp(str, "3270", 5) == 0)
SET_CONSOLE_3270;
#endif
set_preferred_console();
return 1;
}
__setup("conmode=", conmode_setup);
static void __init conmode_default(void)
{
char query_buffer[1024];
char *ptr;
if (MACHINE_IS_VM) {
cpcmd("QUERY CONSOLE", query_buffer, 1024, NULL);
console_devno = simple_strtoul(query_buffer + 5, NULL, 16);
ptr = strstr(query_buffer, "SUBCHANNEL =");
console_irq = simple_strtoul(ptr + 13, NULL, 16);
cpcmd("QUERY TERM", query_buffer, 1024, NULL);
ptr = strstr(query_buffer, "CONMODE");
/*
* Set the conmode to 3215 so that the device recognition
* will set the cu_type of the console to 3215. If the
* conmode is 3270 and we don't set it back then both
* 3215 and the 3270 driver will try to access the console
* device (3215 as console and 3270 as normal tty).
*/
cpcmd("TERM CONMODE 3215", NULL, 0, NULL);
if (ptr == NULL) {
#if defined(CONFIG_SCLP_CONSOLE) || defined(CONFIG_SCLP_VT220_CONSOLE)
SET_CONSOLE_SCLP;
#endif
return;
}
if (strncmp(ptr + 8, "3270", 4) == 0) {
#if defined(CONFIG_TN3270_CONSOLE)
SET_CONSOLE_3270;
#elif defined(CONFIG_TN3215_CONSOLE)
SET_CONSOLE_3215;
#elif defined(CONFIG_SCLP_CONSOLE) || defined(CONFIG_SCLP_VT220_CONSOLE)
SET_CONSOLE_SCLP;
#endif
} else if (strncmp(ptr + 8, "3215", 4) == 0) {
#if defined(CONFIG_TN3215_CONSOLE)
SET_CONSOLE_3215;
#elif defined(CONFIG_TN3270_CONSOLE)
SET_CONSOLE_3270;
#elif defined(CONFIG_SCLP_CONSOLE) || defined(CONFIG_SCLP_VT220_CONSOLE)
SET_CONSOLE_SCLP;
#endif
}
} else {
#if defined(CONFIG_SCLP_CONSOLE) || defined(CONFIG_SCLP_VT220_CONSOLE)
SET_CONSOLE_SCLP;
#endif
}
}
#ifdef CONFIG_ZFCPDUMP
static void __init setup_zfcpdump(unsigned int console_devno)
{
static char str[41];
if (ipl_info.type != IPL_TYPE_FCP_DUMP)
return;
if (console_devno != -1)
sprintf(str, " cio_ignore=all,!0.0.%04x,!0.0.%04x",
ipl_info.data.fcp.dev_id.devno, console_devno);
else
sprintf(str, " cio_ignore=all,!0.0.%04x",
ipl_info.data.fcp.dev_id.devno);
strcat(boot_command_line, str);
console_loglevel = 2;
}
#else
static inline void setup_zfcpdump(unsigned int console_devno) {}
#endif /* CONFIG_ZFCPDUMP */
/*
* Reboot, halt and power_off stubs. They just call _machine_restart,
* _machine_halt or _machine_power_off.
*/
void machine_restart(char *command)
{
if ((!in_interrupt() && !in_atomic()) || oops_in_progress)
/*
* Only unblank the console if we are called in enabled
* context or a bust_spinlocks cleared the way for us.
*/
console_unblank();
_machine_restart(command);
}
void machine_halt(void)
{
if (!in_interrupt() || oops_in_progress)
/*
* Only unblank the console if we are called in enabled
* context or a bust_spinlocks cleared the way for us.
*/
console_unblank();
_machine_halt();
}
void machine_power_off(void)
{
if (!in_interrupt() || oops_in_progress)
/*
* Only unblank the console if we are called in enabled
* context or a bust_spinlocks cleared the way for us.
*/
console_unblank();
_machine_power_off();
}
/*
* Dummy power off function.
*/
void (*pm_power_off)(void) = machine_power_off;
static int __init early_parse_mem(char *p)
{
memory_end = memparse(p, &p);
memory_end_set = 1;
return 0;
}
early_param("mem", early_parse_mem);
unsigned int user_mode = HOME_SPACE_MODE;
EXPORT_SYMBOL_GPL(user_mode);
static int set_amode_and_uaccess(unsigned long user_amode,
unsigned long user32_amode)
{
psw_user_bits = PSW_BASE_BITS | PSW_MASK_DAT | user_amode |
PSW_MASK_IO | PSW_MASK_EXT | PSW_MASK_MCHECK |
PSW_MASK_PSTATE | PSW_DEFAULT_KEY;
#ifdef CONFIG_COMPAT
psw_user32_bits = PSW_BASE32_BITS | PSW_MASK_DAT | user_amode |
PSW_MASK_IO | PSW_MASK_EXT | PSW_MASK_MCHECK |
PSW_MASK_PSTATE | PSW_DEFAULT_KEY;
psw32_user_bits = PSW32_BASE_BITS | PSW32_MASK_DAT | user32_amode |
PSW32_MASK_IO | PSW32_MASK_EXT | PSW32_MASK_MCHECK |
PSW32_MASK_PSTATE;
#endif
psw_kernel_bits = PSW_BASE_BITS | PSW_MASK_DAT | PSW_ASC_HOME |
PSW_MASK_MCHECK | PSW_DEFAULT_KEY;
if (MACHINE_HAS_MVCOS) {
memcpy(&uaccess, &uaccess_mvcos_switch, sizeof(uaccess));
return 1;
} else {
memcpy(&uaccess, &uaccess_pt, sizeof(uaccess));
return 0;
}
}
/*
* Switch kernel/user addressing modes?
*/
static int __init early_parse_switch_amode(char *p)
{
if (user_mode != SECONDARY_SPACE_MODE)
user_mode = PRIMARY_SPACE_MODE;
return 0;
}
early_param("switch_amode", early_parse_switch_amode);
static int __init early_parse_user_mode(char *p)
{
if (p && strcmp(p, "primary") == 0)
user_mode = PRIMARY_SPACE_MODE;
#ifdef CONFIG_S390_EXEC_PROTECT
else if (p && strcmp(p, "secondary") == 0)
user_mode = SECONDARY_SPACE_MODE;
#endif
else if (!p || strcmp(p, "home") == 0)
user_mode = HOME_SPACE_MODE;
else
return 1;
return 0;
}
early_param("user_mode", early_parse_user_mode);
#ifdef CONFIG_S390_EXEC_PROTECT
/*
* Enable execute protection?
*/
static int __init early_parse_noexec(char *p)
{
if (!strncmp(p, "off", 3))
return 0;
user_mode = SECONDARY_SPACE_MODE;
return 0;
}
early_param("noexec", early_parse_noexec);
#endif /* CONFIG_S390_EXEC_PROTECT */
static void setup_addressing_mode(void)
{
if (user_mode == SECONDARY_SPACE_MODE) {
if (set_amode_and_uaccess(PSW_ASC_SECONDARY,
PSW32_ASC_SECONDARY))
pr_info("Execute protection active, "
"mvcos available\n");
else
pr_info("Execute protection active, "
"mvcos not available\n");
} else if (user_mode == PRIMARY_SPACE_MODE) {
if (set_amode_and_uaccess(PSW_ASC_PRIMARY, PSW32_ASC_PRIMARY))
pr_info("Address spaces switched, "
"mvcos available\n");
else
pr_info("Address spaces switched, "
"mvcos not available\n");
}
}
static void __init
setup_lowcore(void)
{
struct _lowcore *lc;
/*
* Setup lowcore for boot cpu
*/
BUILD_BUG_ON(sizeof(struct _lowcore) != LC_PAGES * 4096);
lc = __alloc_bootmem_low(LC_PAGES * PAGE_SIZE, LC_PAGES * PAGE_SIZE, 0);
lc->restart_psw.mask = PSW_BASE_BITS | PSW_DEFAULT_KEY;
lc->restart_psw.addr =
PSW_ADDR_AMODE | (unsigned long) restart_int_handler;
if (user_mode != HOME_SPACE_MODE)
lc->restart_psw.mask |= PSW_ASC_HOME;
lc->external_new_psw.mask = psw_kernel_bits;
lc->external_new_psw.addr =
PSW_ADDR_AMODE | (unsigned long) ext_int_handler;
lc->svc_new_psw.mask = psw_kernel_bits | PSW_MASK_IO | PSW_MASK_EXT;
lc->svc_new_psw.addr = PSW_ADDR_AMODE | (unsigned long) system_call;
lc->program_new_psw.mask = psw_kernel_bits;
lc->program_new_psw.addr =
PSW_ADDR_AMODE | (unsigned long)pgm_check_handler;
lc->mcck_new_psw.mask =
psw_kernel_bits & ~PSW_MASK_MCHECK & ~PSW_MASK_DAT;
lc->mcck_new_psw.addr =
PSW_ADDR_AMODE | (unsigned long) mcck_int_handler;
lc->io_new_psw.mask = psw_kernel_bits;
lc->io_new_psw.addr = PSW_ADDR_AMODE | (unsigned long) io_int_handler;
lc->clock_comparator = -1ULL;
lc->kernel_stack = ((unsigned long) &init_thread_union) + THREAD_SIZE;
lc->async_stack = (unsigned long)
__alloc_bootmem(ASYNC_SIZE, ASYNC_SIZE, 0) + ASYNC_SIZE;
lc->panic_stack = (unsigned long)
__alloc_bootmem(PAGE_SIZE, PAGE_SIZE, 0) + PAGE_SIZE;
lc->current_task = (unsigned long) init_thread_union.thread_info.task;
lc->thread_info = (unsigned long) &init_thread_union;
lc->machine_flags = S390_lowcore.machine_flags;
#ifndef CONFIG_64BIT
if (MACHINE_HAS_IEEE) {
lc->extended_save_area_addr = (__u32)
__alloc_bootmem_low(PAGE_SIZE, PAGE_SIZE, 0);
/* enable extended save area */
__ctl_set_bit(14, 29);
}
#else
lc->cmf_hpp = -1ULL;
lc->vdso_per_cpu_data = (unsigned long) &lc->paste[0];
#endif
lc->sync_enter_timer = S390_lowcore.sync_enter_timer;
lc->async_enter_timer = S390_lowcore.async_enter_timer;
lc->exit_timer = S390_lowcore.exit_timer;
lc->user_timer = S390_lowcore.user_timer;
lc->system_timer = S390_lowcore.system_timer;
lc->steal_timer = S390_lowcore.steal_timer;
lc->last_update_timer = S390_lowcore.last_update_timer;
lc->last_update_clock = S390_lowcore.last_update_clock;
lc->ftrace_func = S390_lowcore.ftrace_func;
set_prefix((u32)(unsigned long) lc);
lowcore_ptr[0] = lc;
}
static void __init
setup_resources(void)
{
struct resource *res, *sub_res;
int i;
code_resource.start = (unsigned long) &_text;
code_resource.end = (unsigned long) &_etext - 1;
data_resource.start = (unsigned long) &_etext;
data_resource.end = (unsigned long) &_edata - 1;
for (i = 0; i < MEMORY_CHUNKS; i++) {
if (!memory_chunk[i].size)
continue;
res = alloc_bootmem_low(sizeof(struct resource));
res->flags = IORESOURCE_BUSY | IORESOURCE_MEM;
switch (memory_chunk[i].type) {
case CHUNK_READ_WRITE:
res->name = "System RAM";
break;
case CHUNK_READ_ONLY:
res->name = "System ROM";
res->flags |= IORESOURCE_READONLY;
break;
default:
res->name = "reserved";
}
res->start = memory_chunk[i].addr;
res->end = memory_chunk[i].addr + memory_chunk[i].size - 1;
request_resource(&iomem_resource, res);
if (code_resource.start >= res->start &&
code_resource.start <= res->end &&
code_resource.end > res->end) {
sub_res = alloc_bootmem_low(sizeof(struct resource));
memcpy(sub_res, &code_resource,
sizeof(struct resource));
sub_res->end = res->end;
code_resource.start = res->end + 1;
request_resource(res, sub_res);
}
if (code_resource.start >= res->start &&
code_resource.start <= res->end &&
code_resource.end <= res->end)
request_resource(res, &code_resource);
if (data_resource.start >= res->start &&
data_resource.start <= res->end &&
data_resource.end > res->end) {
sub_res = alloc_bootmem_low(sizeof(struct resource));
memcpy(sub_res, &data_resource,
sizeof(struct resource));
sub_res->end = res->end;
data_resource.start = res->end + 1;
request_resource(res, sub_res);
}
if (data_resource.start >= res->start &&
data_resource.start <= res->end &&
data_resource.end <= res->end)
request_resource(res, &data_resource);
}
}
unsigned long real_memory_size;
EXPORT_SYMBOL_GPL(real_memory_size);
static void __init setup_memory_end(void)
{
unsigned long memory_size;
unsigned long max_mem;
int i;
#ifdef CONFIG_ZFCPDUMP
if (ipl_info.type == IPL_TYPE_FCP_DUMP) {
memory_end = ZFCPDUMP_HSA_SIZE;
memory_end_set = 1;
}
#endif
memory_size = 0;
memory_end &= PAGE_MASK;
max_mem = memory_end ? min(VMEM_MAX_PHYS, memory_end) : VMEM_MAX_PHYS;
memory_end = min(max_mem, memory_end);
/*
* Make sure all chunks are MAX_ORDER aligned so we don't need the
* extra checks that HOLES_IN_ZONE would require.
*/
for (i = 0; i < MEMORY_CHUNKS; i++) {
unsigned long start, end;
struct mem_chunk *chunk;
unsigned long align;
chunk = &memory_chunk[i];
align = 1UL << (MAX_ORDER + PAGE_SHIFT - 1);
start = (chunk->addr + align - 1) & ~(align - 1);
end = (chunk->addr + chunk->size) & ~(align - 1);
if (start >= end)
memset(chunk, 0, sizeof(*chunk));
else {
chunk->addr = start;
chunk->size = end - start;
}
}
for (i = 0; i < MEMORY_CHUNKS; i++) {
struct mem_chunk *chunk = &memory_chunk[i];
real_memory_size = max(real_memory_size,
chunk->addr + chunk->size);
if (chunk->addr >= max_mem) {
memset(chunk, 0, sizeof(*chunk));
continue;
}
if (chunk->addr + chunk->size > max_mem)
chunk->size = max_mem - chunk->addr;
memory_size = max(memory_size, chunk->addr + chunk->size);
}
if (!memory_end)
memory_end = memory_size;
}
static void __init
setup_memory(void)
{
unsigned long bootmap_size;
unsigned long start_pfn, end_pfn;
int i;
/*
* partially used pages are not usable - thus
* we are rounding upwards:
*/
start_pfn = PFN_UP(__pa(&_end));
end_pfn = max_pfn = PFN_DOWN(memory_end);
#ifdef CONFIG_BLK_DEV_INITRD
/*
* Move the initrd in case the bitmap of the bootmem allocater
* would overwrite it.
*/
if (INITRD_START && INITRD_SIZE) {
unsigned long bmap_size;
unsigned long start;
bmap_size = bootmem_bootmap_pages(end_pfn - start_pfn + 1);
bmap_size = PFN_PHYS(bmap_size);
if (PFN_PHYS(start_pfn) + bmap_size > INITRD_START) {
start = PFN_PHYS(start_pfn) + bmap_size + PAGE_SIZE;
if (start + INITRD_SIZE > memory_end) {
pr_err("initrd extends beyond end of "
"memory (0x%08lx > 0x%08lx) "
"disabling initrd\n",
start + INITRD_SIZE, memory_end);
INITRD_START = INITRD_SIZE = 0;
} else {
pr_info("Moving initrd (0x%08lx -> "
"0x%08lx, size: %ld)\n",
INITRD_START, start, INITRD_SIZE);
memmove((void *) start, (void *) INITRD_START,
INITRD_SIZE);
INITRD_START = start;
}
}
}
#endif
/*
* Initialize the boot-time allocator
*/
bootmap_size = init_bootmem(start_pfn, end_pfn);
/*
* Register RAM areas with the bootmem allocator.
*/
for (i = 0; i < MEMORY_CHUNKS && memory_chunk[i].size > 0; i++) {
unsigned long start_chunk, end_chunk, pfn;
if (memory_chunk[i].type != CHUNK_READ_WRITE)
continue;
start_chunk = PFN_DOWN(memory_chunk[i].addr);
end_chunk = start_chunk + PFN_DOWN(memory_chunk[i].size);
end_chunk = min(end_chunk, end_pfn);
if (start_chunk >= end_chunk)
continue;
add_active_range(0, start_chunk, end_chunk);
pfn = max(start_chunk, start_pfn);
for (; pfn < end_chunk; pfn++)
page_set_storage_key(PFN_PHYS(pfn), PAGE_DEFAULT_KEY);
}
psw_set_key(PAGE_DEFAULT_KEY);
free_bootmem_with_active_regions(0, max_pfn);
/*
* Reserve memory used for lowcore/command line/kernel image.
*/
reserve_bootmem(0, (unsigned long)_ehead, BOOTMEM_DEFAULT);
reserve_bootmem((unsigned long)_stext,
PFN_PHYS(start_pfn) - (unsigned long)_stext,
BOOTMEM_DEFAULT);
/*
* Reserve the bootmem bitmap itself as well. We do this in two
* steps (first step was init_bootmem()) because this catches
* the (very unlikely) case of us accidentally initializing the
* bootmem allocator with an invalid RAM area.
*/
reserve_bootmem(start_pfn << PAGE_SHIFT, bootmap_size,
BOOTMEM_DEFAULT);
#ifdef CONFIG_BLK_DEV_INITRD
if (INITRD_START && INITRD_SIZE) {
if (INITRD_START + INITRD_SIZE <= memory_end) {
reserve_bootmem(INITRD_START, INITRD_SIZE,
BOOTMEM_DEFAULT);
initrd_start = INITRD_START;
initrd_end = initrd_start + INITRD_SIZE;
} else {
pr_err("initrd extends beyond end of "
"memory (0x%08lx > 0x%08lx) "
"disabling initrd\n",
initrd_start + INITRD_SIZE, memory_end);
initrd_start = initrd_end = 0;
}
}
#endif
}
/*
* Setup hardware capabilities.
*/
static void __init setup_hwcaps(void)
{
static const int stfl_bits[6] = { 0, 2, 7, 17, 19, 21 };
unsigned long long facility_list_extended;
unsigned int facility_list;
struct cpuid cpu_id;
int i;
facility_list = stfl();
/*
* The store facility list bits numbers as found in the principles
* of operation are numbered with bit 1UL<<31 as number 0 to
* bit 1UL<<0 as number 31.
* Bit 0: instructions named N3, "backported" to esa-mode
* Bit 2: z/Architecture mode is active
* Bit 7: the store-facility-list-extended facility is installed
* Bit 17: the message-security assist is installed
* Bit 19: the long-displacement facility is installed
* Bit 21: the extended-immediate facility is installed
* Bit 22: extended-translation facility 3 is installed
* Bit 30: extended-translation facility 3 enhancement facility
* These get translated to:
* HWCAP_S390_ESAN3 bit 0, HWCAP_S390_ZARCH bit 1,
* HWCAP_S390_STFLE bit 2, HWCAP_S390_MSA bit 3,
* HWCAP_S390_LDISP bit 4, HWCAP_S390_EIMM bit 5 and
* HWCAP_S390_ETF3EH bit 8 (22 && 30).
*/
for (i = 0; i < 6; i++)
if (facility_list & (1UL << (31 - stfl_bits[i])))
elf_hwcap |= 1UL << i;
if ((facility_list & (1UL << (31 - 22)))
&& (facility_list & (1UL << (31 - 30))))
elf_hwcap |= HWCAP_S390_ETF3EH;
/*
* Check for additional facilities with store-facility-list-extended.
* stfle stores doublewords (8 byte) with bit 1ULL<<63 as bit 0
* and 1ULL<<0 as bit 63. Bits 0-31 contain the same information
* as stored by stfl, bits 32-xxx contain additional facilities.
* How many facility words are stored depends on the number of
* doublewords passed to the instruction. The additional facilites
* are:
* Bit 42: decimal floating point facility is installed
* Bit 44: perform floating point operation facility is installed
* translated to:
* HWCAP_S390_DFP bit 6 (42 && 44).
*/
if ((elf_hwcap & (1UL << 2)) &&
__stfle(&facility_list_extended, 1) > 0) {
if ((facility_list_extended & (1ULL << (63 - 42)))
&& (facility_list_extended & (1ULL << (63 - 44))))
elf_hwcap |= HWCAP_S390_DFP;
}
/*
* Huge page support HWCAP_S390_HPAGE is bit 7.
*/
if (MACHINE_HAS_HPAGE)
elf_hwcap |= HWCAP_S390_HPAGE;
/*
* 64-bit register support for 31-bit processes
* HWCAP_S390_HIGH_GPRS is bit 9.
*/
elf_hwcap |= HWCAP_S390_HIGH_GPRS;
get_cpu_id(&cpu_id);
switch (cpu_id.machine) {
case 0x9672:
#if !defined(CONFIG_64BIT)
default: /* Use "g5" as default for 31 bit kernels. */
#endif
strcpy(elf_platform, "g5");
break;
case 0x2064:
case 0x2066:
#if defined(CONFIG_64BIT)
default: /* Use "z900" as default for 64 bit kernels. */
#endif
strcpy(elf_platform, "z900");
break;
case 0x2084:
case 0x2086:
strcpy(elf_platform, "z990");
break;
case 0x2094:
case 0x2096:
strcpy(elf_platform, "z9-109");
break;
case 0x2097:
case 0x2098:
strcpy(elf_platform, "z10");
break;
}
}
/*
* Setup function called from init/main.c just after the banner
* was printed.
*/
void __init
setup_arch(char **cmdline_p)
{
/*
* print what head.S has found out about the machine
*/
#ifndef CONFIG_64BIT
if (MACHINE_IS_VM)
pr_info("Linux is running as a z/VM "
"guest operating system in 31-bit mode\n");
else if (MACHINE_IS_LPAR)
pr_info("Linux is running natively in 31-bit mode\n");
if (MACHINE_HAS_IEEE)
pr_info("The hardware system has IEEE compatible "
"floating point units\n");
else
pr_info("The hardware system has no IEEE compatible "
"floating point units\n");
#else /* CONFIG_64BIT */
if (MACHINE_IS_VM)
pr_info("Linux is running as a z/VM "
"guest operating system in 64-bit mode\n");
else if (MACHINE_IS_KVM)
pr_info("Linux is running under KVM in 64-bit mode\n");
else if (MACHINE_IS_LPAR)
pr_info("Linux is running natively in 64-bit mode\n");
#endif /* CONFIG_64BIT */
/* Have one command line that is parsed and saved in /proc/cmdline */
/* boot_command_line has been already set up in early.c */
*cmdline_p = boot_command_line;
ROOT_DEV = Root_RAM0;
init_mm.start_code = PAGE_OFFSET;
init_mm.end_code = (unsigned long) &_etext;
init_mm.end_data = (unsigned long) &_edata;
init_mm.brk = (unsigned long) &_end;
if (MACHINE_HAS_MVCOS)
memcpy(&uaccess, &uaccess_mvcos, sizeof(uaccess));
else
memcpy(&uaccess, &uaccess_std, sizeof(uaccess));
parse_early_param();
setup_ipl();
setup_memory_end();
setup_addressing_mode();
setup_memory();
setup_resources();
setup_lowcore();
cpu_init();
s390_init_cpu_topology();
/*
* Setup capabilities (ELF_HWCAP & ELF_PLATFORM).
*/
setup_hwcaps();
/*
* Create kernel page tables and switch to virtual addressing.
*/
paging_init();
/* Setup default console */
conmode_default();
set_preferred_console();
/* Setup zfcpdump support */
setup_zfcpdump(console_devno);
}
| gpl-2.0 |
teamblueridge/SuperSickKernel | tools/perf/util/sort.c | 1573 | 8542 | #include "sort.h"
#include "hist.h"
regex_t parent_regex;
const char default_parent_pattern[] = "^sys_|^do_page_fault";
const char *parent_pattern = default_parent_pattern;
const char default_sort_order[] = "comm,dso,symbol";
const char *sort_order = default_sort_order;
int sort__need_collapse = 0;
int sort__has_parent = 0;
enum sort_type sort__first_dimension;
char * field_sep;
LIST_HEAD(hist_entry__sort_list);
static int hist_entry__thread_snprintf(struct hist_entry *self, char *bf,
size_t size, unsigned int width);
static int hist_entry__comm_snprintf(struct hist_entry *self, char *bf,
size_t size, unsigned int width);
static int hist_entry__dso_snprintf(struct hist_entry *self, char *bf,
size_t size, unsigned int width);
static int hist_entry__sym_snprintf(struct hist_entry *self, char *bf,
size_t size, unsigned int width);
static int hist_entry__parent_snprintf(struct hist_entry *self, char *bf,
size_t size, unsigned int width);
static int hist_entry__cpu_snprintf(struct hist_entry *self, char *bf,
size_t size, unsigned int width);
struct sort_entry sort_thread = {
.se_header = "Command: Pid",
.se_cmp = sort__thread_cmp,
.se_snprintf = hist_entry__thread_snprintf,
.se_width_idx = HISTC_THREAD,
};
struct sort_entry sort_comm = {
.se_header = "Command",
.se_cmp = sort__comm_cmp,
.se_collapse = sort__comm_collapse,
.se_snprintf = hist_entry__comm_snprintf,
.se_width_idx = HISTC_COMM,
};
struct sort_entry sort_dso = {
.se_header = "Shared Object",
.se_cmp = sort__dso_cmp,
.se_snprintf = hist_entry__dso_snprintf,
.se_width_idx = HISTC_DSO,
};
struct sort_entry sort_sym = {
.se_header = "Symbol",
.se_cmp = sort__sym_cmp,
.se_snprintf = hist_entry__sym_snprintf,
.se_width_idx = HISTC_SYMBOL,
};
struct sort_entry sort_parent = {
.se_header = "Parent symbol",
.se_cmp = sort__parent_cmp,
.se_snprintf = hist_entry__parent_snprintf,
.se_width_idx = HISTC_PARENT,
};
struct sort_entry sort_cpu = {
.se_header = "CPU",
.se_cmp = sort__cpu_cmp,
.se_snprintf = hist_entry__cpu_snprintf,
.se_width_idx = HISTC_CPU,
};
struct sort_dimension {
const char *name;
struct sort_entry *entry;
int taken;
};
static struct sort_dimension sort_dimensions[] = {
{ .name = "pid", .entry = &sort_thread, },
{ .name = "comm", .entry = &sort_comm, },
{ .name = "dso", .entry = &sort_dso, },
{ .name = "symbol", .entry = &sort_sym, },
{ .name = "parent", .entry = &sort_parent, },
{ .name = "cpu", .entry = &sort_cpu, },
};
int64_t cmp_null(void *l, void *r)
{
if (!l && !r)
return 0;
else if (!l)
return -1;
else
return 1;
}
/* --sort pid */
int64_t
sort__thread_cmp(struct hist_entry *left, struct hist_entry *right)
{
return right->thread->pid - left->thread->pid;
}
static int repsep_snprintf(char *bf, size_t size, const char *fmt, ...)
{
int n;
va_list ap;
va_start(ap, fmt);
n = vsnprintf(bf, size, fmt, ap);
if (field_sep && n > 0) {
char *sep = bf;
while (1) {
sep = strchr(sep, *field_sep);
if (sep == NULL)
break;
*sep = '.';
}
}
va_end(ap);
if (n >= (int)size)
return size - 1;
return n;
}
static int hist_entry__thread_snprintf(struct hist_entry *self, char *bf,
size_t size, unsigned int width)
{
return repsep_snprintf(bf, size, "%*s:%5d", width,
self->thread->comm ?: "", self->thread->pid);
}
static int hist_entry__comm_snprintf(struct hist_entry *self, char *bf,
size_t size, unsigned int width)
{
return repsep_snprintf(bf, size, "%*s", width, self->thread->comm);
}
/* --sort dso */
int64_t
sort__dso_cmp(struct hist_entry *left, struct hist_entry *right)
{
struct dso *dso_l = left->ms.map ? left->ms.map->dso : NULL;
struct dso *dso_r = right->ms.map ? right->ms.map->dso : NULL;
const char *dso_name_l, *dso_name_r;
if (!dso_l || !dso_r)
return cmp_null(dso_l, dso_r);
if (verbose) {
dso_name_l = dso_l->long_name;
dso_name_r = dso_r->long_name;
} else {
dso_name_l = dso_l->short_name;
dso_name_r = dso_r->short_name;
}
return strcmp(dso_name_l, dso_name_r);
}
static int hist_entry__dso_snprintf(struct hist_entry *self, char *bf,
size_t size, unsigned int width)
{
if (self->ms.map && self->ms.map->dso) {
const char *dso_name = !verbose ? self->ms.map->dso->short_name :
self->ms.map->dso->long_name;
return repsep_snprintf(bf, size, "%-*s", width, dso_name);
}
return repsep_snprintf(bf, size, "%-*s", width, "[unknown]");
}
/* --sort symbol */
int64_t
sort__sym_cmp(struct hist_entry *left, struct hist_entry *right)
{
u64 ip_l, ip_r;
if (left->ms.sym == right->ms.sym)
return 0;
ip_l = left->ms.sym ? left->ms.sym->start : left->ip;
ip_r = right->ms.sym ? right->ms.sym->start : right->ip;
return (int64_t)(ip_r - ip_l);
}
static int hist_entry__sym_snprintf(struct hist_entry *self, char *bf,
size_t size, unsigned int width __used)
{
size_t ret = 0;
if (verbose) {
char o = self->ms.map ? dso__symtab_origin(self->ms.map->dso) : '!';
ret += repsep_snprintf(bf, size, "%-#*llx %c ",
BITS_PER_LONG / 4, self->ip, o);
}
ret += repsep_snprintf(bf + ret, size - ret, "[%c] ", self->level);
if (self->ms.sym)
ret += repsep_snprintf(bf + ret, size - ret, "%s",
self->ms.sym->name);
else
ret += repsep_snprintf(bf + ret, size - ret, "%-#*llx",
BITS_PER_LONG / 4, self->ip);
return ret;
}
/* --sort comm */
int64_t
sort__comm_cmp(struct hist_entry *left, struct hist_entry *right)
{
return right->thread->pid - left->thread->pid;
}
int64_t
sort__comm_collapse(struct hist_entry *left, struct hist_entry *right)
{
char *comm_l = left->thread->comm;
char *comm_r = right->thread->comm;
if (!comm_l || !comm_r)
return cmp_null(comm_l, comm_r);
return strcmp(comm_l, comm_r);
}
/* --sort parent */
int64_t
sort__parent_cmp(struct hist_entry *left, struct hist_entry *right)
{
struct symbol *sym_l = left->parent;
struct symbol *sym_r = right->parent;
if (!sym_l || !sym_r)
return cmp_null(sym_l, sym_r);
return strcmp(sym_l->name, sym_r->name);
}
static int hist_entry__parent_snprintf(struct hist_entry *self, char *bf,
size_t size, unsigned int width)
{
return repsep_snprintf(bf, size, "%-*s", width,
self->parent ? self->parent->name : "[other]");
}
/* --sort cpu */
int64_t
sort__cpu_cmp(struct hist_entry *left, struct hist_entry *right)
{
return right->cpu - left->cpu;
}
static int hist_entry__cpu_snprintf(struct hist_entry *self, char *bf,
size_t size, unsigned int width)
{
return repsep_snprintf(bf, size, "%-*d", width, self->cpu);
}
int sort_dimension__add(const char *tok)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(sort_dimensions); i++) {
struct sort_dimension *sd = &sort_dimensions[i];
if (sd->taken)
continue;
if (strncasecmp(tok, sd->name, strlen(tok)))
continue;
if (sd->entry->se_collapse)
sort__need_collapse = 1;
if (sd->entry == &sort_parent) {
int ret = regcomp(&parent_regex, parent_pattern, REG_EXTENDED);
if (ret) {
char err[BUFSIZ];
regerror(ret, &parent_regex, err, sizeof(err));
pr_err("Invalid regex: %s\n%s", parent_pattern, err);
return -EINVAL;
}
sort__has_parent = 1;
}
if (list_empty(&hist_entry__sort_list)) {
if (!strcmp(sd->name, "pid"))
sort__first_dimension = SORT_PID;
else if (!strcmp(sd->name, "comm"))
sort__first_dimension = SORT_COMM;
else if (!strcmp(sd->name, "dso"))
sort__first_dimension = SORT_DSO;
else if (!strcmp(sd->name, "symbol"))
sort__first_dimension = SORT_SYM;
else if (!strcmp(sd->name, "parent"))
sort__first_dimension = SORT_PARENT;
else if (!strcmp(sd->name, "cpu"))
sort__first_dimension = SORT_CPU;
}
list_add_tail(&sd->entry->list, &hist_entry__sort_list);
sd->taken = 1;
return 0;
}
return -ESRCH;
}
void setup_sorting(const char * const usagestr[], const struct option *opts)
{
char *tmp, *tok, *str = strdup(sort_order);
for (tok = strtok_r(str, ", ", &tmp);
tok; tok = strtok_r(NULL, ", ", &tmp)) {
if (sort_dimension__add(tok) < 0) {
error("Unknown --sort key: `%s'", tok);
usage_with_options(usagestr, opts);
}
}
free(str);
}
void sort_entry__setup_elide(struct sort_entry *self, struct strlist *list,
const char *list_name, FILE *fp)
{
if (list && strlist__nr_entries(list) == 1) {
if (fp != NULL)
fprintf(fp, "# %s: %s\n", list_name,
strlist__entry(list, 0)->s);
self->elide = true;
}
}
| gpl-2.0 |
AirOne70/android_kernel_asus_grouper | drivers/usb/serial/siemens_mpi.c | 3365 | 2072 | /*
* Siemens USB-MPI Serial USB driver
*
* Copyright (C) 2005 Thomas Hergenhahn <thomas.hergenhahn@suse.de>
* Copyright (C) 2005,2008 Greg Kroah-Hartman <gregkh@suse.de>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/tty.h>
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
/* Version Information */
#define DRIVER_VERSION "Version 0.1 09/26/2005"
#define DRIVER_AUTHOR "Thomas Hergenhahn@web.de http://libnodave.sf.net"
#define DRIVER_DESC "Driver for Siemens USB/MPI adapter"
static const struct usb_device_id id_table[] = {
/* Vendor and product id for 6ES7-972-0CB20-0XA0 */
{ USB_DEVICE(0x908, 0x0004) },
{ },
};
MODULE_DEVICE_TABLE(usb, id_table);
static struct usb_driver siemens_usb_mpi_driver = {
.name = "siemens_mpi",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = id_table,
};
static struct usb_serial_driver siemens_usb_mpi_device = {
.driver = {
.owner = THIS_MODULE,
.name = "siemens_mpi",
},
.id_table = id_table,
.usb_driver = &siemens_usb_mpi_driver,
.num_ports = 1,
};
static int __init siemens_usb_mpi_init(void)
{
int retval;
retval = usb_serial_register(&siemens_usb_mpi_device);
if (retval)
goto failed_usb_serial_register;
retval = usb_register(&siemens_usb_mpi_driver);
if (retval)
goto failed_usb_register;
printk(KERN_INFO DRIVER_DESC "\n");
printk(KERN_INFO DRIVER_VERSION " " DRIVER_AUTHOR "\n");
return retval;
failed_usb_register:
usb_serial_deregister(&siemens_usb_mpi_device);
failed_usb_serial_register:
return retval;
}
static void __exit siemens_usb_mpi_exit(void)
{
usb_deregister(&siemens_usb_mpi_driver);
usb_serial_deregister(&siemens_usb_mpi_device);
}
module_init(siemens_usb_mpi_init);
module_exit(siemens_usb_mpi_exit);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
Josemurillo/frokTinkel | src/server/scripts/EasternKingdoms/SunwellPlateau/boss_muru.cpp | 38 | 19651 | /*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Boss_Muru
SD%Complete: 80
SDComment: all sounds, black hole effect triggers to often (46228)
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "sunwell_plateau.h"
// Muru & Entropius's spells
enum Spells
{
SPELL_ENRAGE = 26662,
// Muru's spells
SPELL_NEGATIVE_ENERGY = 46009, //(this trigger 46008)
SPELL_DARKNESS = 45999,
SPELL_OPEN_ALL_PORTALS = 46177,
SPELL_OPEN_PORTAL = 45977,
SPELL_OPEN_PORTAL_2 = 45976,
SPELL_SUMMON_BERSERKER = 46037,
SPELL_SUMNON_FURY_MAGE = 46038,
SPELL_SUMMON_VOID_SENTINEL = 45988,
SPELL_SUMMON_ENTROPIUS = 46217,
// Entropius's spells
SPELL_DARKNESS_E = 46269,
SPELL_BLACKHOLE = 46282,
SPELL_NEGATIVE_ENERGY_E = 46284,
SPELL_ENTROPIUS_SPAWN = 46223,
// Shadowsword Berserker's spells
SPELL_FLURRY = 46160,
SPELL_DUAL_WIELD = 29651,
// Shadowsword Fury Mage's spells
SPELL_FEL_FIREBALL = 46101,
SPELL_SPELL_FURY = 46102,
// Void Sentinel's spells
SPELL_SHADOW_PULSE = 46087,
SPELL_VOID_BLAST = 46161,
// Void Spawn's spells
SPELL_SHADOW_BOLT_VOLLEY = 46082,
//Dark Fiend Spells
SPELL_DARKFIEND_AOE = 45944,
SPELL_DARKFIEND_VISUAL = 45936,
SPELL_DARKFIEND_SKIN = 45934,
//Black Hole Spells
SPELL_BLACKHOLE_SPAWN = 46242,
SPELL_BLACKHOLE_GROW = 46228
};
enum BossTimers{
TIMER_DARKNESS = 0,
TIMER_HUMANOIDES = 1,
TIMER_PHASE = 2,
TIMER_SENTINEL = 3
};
float DarkFiends[8][4] =
{
{1819.9f, 609.80f, 69.74f, 1.94f},
{1829.39f, 617.89f, 69.73f, 2.61f},
{1801.98f, 633.62f, 69.74f, 5.71f},
{1830.88f, 629.99f, 69.73f, 3.52f},
{1800.38f, 621.41f, 69.74f, 0.22f},
{1808.3f, 612.45f, 69.73f, 1.02f},
{1823.9f, 639.69f, 69.74f, 4.12f},
{1811.85f, 640.46f, 69.73f, 4.97f}
};
float Humanoides[6][5] =
{
{CREATURE_FURY_MAGE, 1780.16f, 666.83f, 71.19f, 5.21f},
{CREATURE_FURY_MAGE, 1847.93f, 600.30f, 71.30f, 2.57f},
{CREATURE_BERSERKER, 1779.97f, 660.64f, 71.19f, 5.28f},
{CREATURE_BERSERKER, 1786.2f, 661.01f, 71.19f, 4.51f},
{CREATURE_BERSERKER, 1845.17f, 602.63f, 71.28f, 2.43f},
{CREATURE_BERSERKER, 1842.91f, 599.93f, 71.23f, 2.44f}
};
uint32 EnrageTimer = 600000;
class boss_entropius : public CreatureScript
{
public:
boss_entropius() : CreatureScript("boss_entropius") { }
CreatureAI* GetAI(Creature* creature) const
{
return new boss_entropiusAI (creature);
}
struct boss_entropiusAI : public ScriptedAI
{
boss_entropiusAI(Creature* creature) : ScriptedAI(creature), Summons(me)
{
instance = creature->GetInstanceScript();
}
InstanceScript* instance;
SummonList Summons;
uint32 BlackHoleSummonTimer;
void Reset()
{
BlackHoleSummonTimer = 15000;
DoCastAOE(SPELL_NEGATIVE_ENERGY_E, false);
Summons.DespawnAll();
if (instance)
instance->SetData(DATA_MURU_EVENT, NOT_STARTED);
}
void EnterCombat(Unit* /*who*/)
{
DoCastAOE(SPELL_NEGATIVE_ENERGY_E, true);
DoCast(me, SPELL_ENTROPIUS_SPAWN, false);
if (instance)
instance->SetData(DATA_MURU_EVENT, IN_PROGRESS);
}
void JustSummoned(Creature* summoned)
{
switch (summoned->GetEntry())
{
case CREATURE_DARK_FIENDS:
summoned->CastSpell(summoned, SPELL_DARKFIEND_VISUAL, false);
break;
case CREATURE_DARKNESS:
summoned->AddUnitState(UNIT_STATE_STUNNED);
float x, y, z, o;
summoned->GetHomePosition(x, y, z, o);
me->SummonCreature(CREATURE_DARK_FIENDS, x, y, z, o, TEMPSUMMON_CORPSE_DESPAWN, 0);
break;
}
summoned->AI()->AttackStart(SelectTarget(SELECT_TARGET_RANDOM, 0, 50, true));
Summons.Summon(summoned);
}
void JustDied(Unit* /*killer*/)
{
Summons.DespawnAll();
if (instance)
instance->SetData(DATA_MURU_EVENT, DONE);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
if (EnrageTimer < diff && !me->HasAura(SPELL_ENRAGE, 0))
{
DoCast(me, SPELL_ENRAGE, false);
} else EnrageTimer -= diff;
if (BlackHoleSummonTimer <= diff)
{
Unit* random = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true);
if (!random)
return;
DoCast(random, SPELL_DARKNESS_E, false);
random = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true);
if (!random)
return;
random->CastSpell(random, SPELL_BLACKHOLE, false);
BlackHoleSummonTimer = 15000;
} else BlackHoleSummonTimer -= diff;
DoMeleeAttackIfReady();
}
};
};
class boss_muru : public CreatureScript
{
public:
boss_muru() : CreatureScript("boss_muru") { }
CreatureAI* GetAI(Creature* creature) const
{
return new boss_muruAI (creature);
}
struct boss_muruAI : public Scripted_NoMovementAI
{
boss_muruAI(Creature* creature) : Scripted_NoMovementAI(creature), Summons(me)
{
instance = creature->GetInstanceScript();
}
InstanceScript* instance;
SummonList Summons;
uint8 Phase;
uint32 Timer[4];
bool DarkFiend;
void Reset()
{
DarkFiend = false;
Phase = 1;
EnrageTimer = 600000;
Timer[TIMER_DARKNESS] = 45000;
Timer[TIMER_HUMANOIDES] = 10000;
Timer[TIMER_PHASE] = 2000;
Timer[TIMER_SENTINEL] = 31500;
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->SetVisible(true);
Summons.DespawnAll();
if (instance)
instance->SetData(DATA_MURU_EVENT, NOT_STARTED);
}
void EnterCombat(Unit* /*who*/)
{
DoCastAOE(SPELL_NEGATIVE_ENERGY, false);
if (instance)
instance->SetData(DATA_MURU_EVENT, IN_PROGRESS);
}
void DamageTaken(Unit* /*done_by*/, uint32 &damage)
{
if (damage > me->GetHealth() && Phase == 1)
{
damage = 0;
Phase = 2;
me->RemoveAllAuras();
DoCast(me, SPELL_OPEN_ALL_PORTALS, false);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
}
if (Phase > 1 && Phase < 4)
damage = 0;
}
void JustSummoned(Creature* summoned)
{
switch (summoned->GetEntry())
{
case BOSS_ENTROPIUS:
me->SetVisible(false);
break;
case CREATURE_DARK_FIENDS:
summoned->CastSpell(summoned, SPELL_DARKFIEND_VISUAL, false);
break;
}
summoned->AI()->AttackStart(SelectTarget(SELECT_TARGET_RANDOM, 0, 50, true));
Summons.Summon(summoned);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
if (Phase == 3)
{
if (Timer[TIMER_PHASE] <= diff)
{
if (!instance)
return;
switch (instance->GetData(DATA_MURU_EVENT))
{
case NOT_STARTED:
Reset();
break;
case DONE:
Phase = 4;
me->DisappearAndDie();
break;
}
Timer[TIMER_PHASE] = 3000;
} else Timer[TIMER_PHASE] -= diff;
return;
}
if (EnrageTimer < diff && !me->HasAura(SPELL_ENRAGE, 0))
{
DoCast(me, SPELL_ENRAGE, false);
} else EnrageTimer -= diff;
for (uint8 i = 0; i < 4; ++i)
{
if (Timer[i] <= diff)
{
switch (i)
{
case TIMER_DARKNESS:
if (!DarkFiend)
{
DoCastAOE(SPELL_DARKNESS, false);
Timer[TIMER_DARKNESS] = 3000;
DarkFiend = true;
}
else
{
DarkFiend = false;
for (uint8 j = 0; j < 8; ++j)
me->SummonCreature(CREATURE_DARK_FIENDS, DarkFiends[j][0], DarkFiends[j][1], DarkFiends[j][2], DarkFiends[j][3], TEMPSUMMON_CORPSE_DESPAWN, 0);
Timer[TIMER_DARKNESS] = 42000;
}
break;
case TIMER_HUMANOIDES:
for (uint8 j = 0; j < 6; ++j)
me->SummonCreature(uint32(Humanoides[j][0]), Humanoides[j][1], Humanoides[j][2], Humanoides[j][3], Humanoides[j][4], TEMPSUMMON_CORPSE_DESPAWN, 0);
Timer[TIMER_HUMANOIDES] = 60000;
break;
case TIMER_PHASE:
me->RemoveAllAuras();
DoCast(me, SPELL_SUMMON_ENTROPIUS, false);
Timer[TIMER_PHASE] = 3000;
Phase = 3;
return;
case TIMER_SENTINEL:
DoCastAOE(SPELL_OPEN_PORTAL_2, false);
Timer[TIMER_SENTINEL] = 30000;
break;
}
break;
}
}
//Timer
for (uint8 i = 0; i < 4; ++i)
{
if (i != TIMER_PHASE)Timer[i] -= diff;
else if (Phase == 2) Timer[i] -= diff;
}
}
};
};
class npc_muru_portal : public CreatureScript
{
public:
npc_muru_portal() : CreatureScript("npc_muru_portal") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_muru_portalAI (creature);
}
struct npc_muru_portalAI : public Scripted_NoMovementAI
{
npc_muru_portalAI(Creature* creature) : Scripted_NoMovementAI(creature), Summons(me)
{
instance = creature->GetInstanceScript();
}
InstanceScript* instance;
SummonList Summons;
bool SummonSentinel;
bool InAction;
uint32 SummonTimer;
void Reset()
{
SummonTimer = 5000;
InAction = false;
SummonSentinel = false;
me->AddUnitState(UNIT_STATE_STUNNED);
Summons.DespawnAll();
}
void JustSummoned(Creature* summoned)
{
if (instance)
if (Player* Target = Unit::GetPlayer(*me, instance->GetData64(DATA_PLAYER_GUID)))
summoned->AI()->AttackStart(Target);
Summons.Summon(summoned);
}
void SpellHit(Unit* /*caster*/, const SpellInfo* Spell)
{
float x, y, z, o;
me->GetHomePosition(x, y, z, o);
DoTeleportTo(x, y, z);
InAction = true;
switch (Spell->Id)
{
case SPELL_OPEN_ALL_PORTALS:
DoCastAOE(SPELL_OPEN_PORTAL, false);
break;
case SPELL_OPEN_PORTAL_2:
DoCastAOE(SPELL_OPEN_PORTAL, false);
SummonSentinel = true;
break;
}
}
void UpdateAI(const uint32 diff)
{
if (!SummonSentinel)
{
if (InAction && instance && instance->GetData(DATA_MURU_EVENT) == NOT_STARTED)
Reset();
return;
}
if (SummonTimer <= diff)
{
DoCastAOE(SPELL_SUMMON_VOID_SENTINEL, false);
SummonTimer = 5000;
SummonSentinel = false;
} else SummonTimer -= diff;
}
};
};
class npc_dark_fiend : public CreatureScript
{
public:
npc_dark_fiend() : CreatureScript("npc_dark_fiend") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_dark_fiendAI (creature);
}
struct npc_dark_fiendAI : public ScriptedAI
{
npc_dark_fiendAI(Creature* creature) : ScriptedAI(creature) {}
uint32 WaitTimer;
bool InAction;
void Reset()
{
WaitTimer = 2000;
InAction = false;
me->AddUnitState(UNIT_STATE_STUNNED);
}
void SpellHit(Unit* /*caster*/, const SpellInfo* Spell)
{
for (uint8 i = 0; i < 3; ++i)
if (Spell->Effects[i].Effect == 38)
me->DisappearAndDie();
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
if (WaitTimer <= diff)
{
if (!InAction)
{
me->ClearUnitState(UNIT_STATE_STUNNED);
DoCastAOE(SPELL_DARKFIEND_SKIN, false);
AttackStart(SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true));
InAction = true;
WaitTimer = 500;
}
else
{
if (me->IsWithinDist(me->getVictim(), 5))
{
DoCastAOE(SPELL_DARKFIEND_AOE, false);
me->DisappearAndDie();
}
WaitTimer = 500;
}
} else WaitTimer -= diff;
}
};
};
class npc_void_sentinel : public CreatureScript
{
public:
npc_void_sentinel() : CreatureScript("npc_void_sentinel") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_void_sentinelAI (creature);
}
struct npc_void_sentinelAI : public ScriptedAI
{
npc_void_sentinelAI(Creature* creature) : ScriptedAI(creature){}
uint32 PulseTimer;
uint32 VoidBlastTimer;
void Reset()
{
PulseTimer = 3000;
VoidBlastTimer = 45000; //is this a correct timer?
float x, y, z, o;
me->GetHomePosition(x, y, z, o);
DoTeleportTo(x, y, 71);
}
void JustDied(Unit* /*killer*/)
{
for (uint8 i = 0; i < 8; ++i)
me->SummonCreature(CREATURE_VOID_SPAWN, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), float(rand()%6), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 180000);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
if (PulseTimer <= diff)
{
DoCastAOE(SPELL_SHADOW_PULSE, true);
PulseTimer = 3000;
} else PulseTimer -= diff;
if (VoidBlastTimer <= diff)
{
DoCast(me->getVictim(), SPELL_VOID_BLAST, false);
VoidBlastTimer = 45000;
} else VoidBlastTimer -= diff;
DoMeleeAttackIfReady();
}
};
};
class npc_blackhole : public CreatureScript
{
public:
npc_blackhole() : CreatureScript("npc_blackhole") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_blackholeAI (creature);
}
struct npc_blackholeAI : public ScriptedAI
{
npc_blackholeAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
InstanceScript* instance;
uint32 DespawnTimer;
uint32 SpellTimer;
uint8 Phase;
uint8 NeedForAHack;
void Reset()
{
DespawnTimer = 15000;
SpellTimer = 5000;
Phase = 0;
me->AddUnitState(UNIT_STATE_STUNNED);
DoCastAOE(SPELL_BLACKHOLE_SPAWN, true);
}
void UpdateAI(const uint32 diff)
{
if (SpellTimer <= diff)
{
Unit* Victim = Unit::GetUnit(*me, instance ? instance->GetData64(DATA_PLAYER_GUID) : 0);
switch (NeedForAHack)
{
case 0:
me->ClearUnitState(UNIT_STATE_STUNNED);
DoCastAOE(SPELL_BLACKHOLE_GROW, false);
if (Victim)
AttackStart(Victim);
SpellTimer = 700;
NeedForAHack = 2;
break;
case 1:
me->AddAura(SPELL_BLACKHOLE_GROW, me);
NeedForAHack = 2;
SpellTimer = 600;
break;
case 2:
SpellTimer = 400;
NeedForAHack = 3;
me->RemoveAura(SPELL_BLACKHOLE_GROW, 1);
break;
case 3:
SpellTimer = urand(400, 900);
NeedForAHack = 1;
if (Unit* Temp = me->getVictim())
{
if (Temp->GetPositionZ() > 73 && Victim)
AttackStart(Victim);
} else
return;
}
} else SpellTimer -= diff;
if (DespawnTimer <= diff)
me->DisappearAndDie();
else DespawnTimer -= diff;
}
};
};
void AddSC_boss_muru()
{
new boss_muru();
new boss_entropius();
new npc_muru_portal();
new npc_dark_fiend();
new npc_void_sentinel();
new npc_blackhole();
}
| gpl-2.0 |
bjzhang/xen | tools/libxc/xc_linux.c | 38 | 2100 | /******************************************************************************
*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xc_private.h"
/* Optionally flush file to disk and discard page cache */
void discard_file_cache(xc_interface *xch, int fd, int flush)
{
off_t cur = 0;
int saved_errno = errno;
if ( flush && (fsync(fd) < 0) )
{
/*PERROR("Failed to flush file: %s", strerror(errno));*/
goto out;
}
/*
* Calculate last page boundary of amount written so far
* unless we are flushing in which case entire cache
* is discarded.
*/
if ( !flush )
{
if ( (cur = lseek(fd, 0, SEEK_CUR)) == (off_t)-1 )
cur = 0;
cur &= ~(XC_PAGE_SIZE-1);
}
/* Discard from the buffer cache. */
if ( posix_fadvise64(fd, 0, cur, POSIX_FADV_DONTNEED) < 0 )
{
/*PERROR("Failed to discard cache: %s", strerror(errno));*/
goto out;
}
out:
errno = saved_errno;
}
void *xc_memalign(xc_interface *xch, size_t alignment, size_t size)
{
int ret;
void *ptr;
ret = posix_memalign(&ptr, alignment, size);
if (ret != 0 || !ptr)
return NULL;
return ptr;
}
/*
* Local variables:
* mode: C
* c-file-style: "BSD"
* c-basic-offset: 4
* tab-width: 4
* indent-tabs-mode: nil
* End:
*/
| gpl-2.0 |
dragonpt/Kernel_3.4.67_KK_Wiko_DarkMoon | fs/yaffs2/yaffs_vfs.c | 38 | 70825 | /*
* YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
*
* Copyright (C) 2002-2010 Aleph One Ltd.
* for Toby Churchill Ltd and Brightstar Engineering
*
* Created by Charles Manning <charles@aleph1.co.uk>
* Acknowledgements:
* Luc van OostenRyck for numerous patches.
* Nick Bane for numerous patches.
* Nick Bane for 2.5/2.6 integration.
* Andras Toth for mknod rdev issue.
* Michael Fischer for finding the problem with inode inconsistency.
* Some code bodily lifted from JFFS
*
* 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 is the file system front-end to YAFFS that hooks it up to
* the VFS.
*
* Special notes:
* >> 2.4: sb->u.generic_sbp points to the struct yaffs_dev associated with
* this superblock
* >> 2.6: sb->s_fs_info points to the struct yaffs_dev associated with this
* superblock
* >> inode->u.generic_ip points to the associated struct yaffs_obj.
*/
/*
* NB There are two variants of Linux VFS glue code. This variant supports
* a single version and should not include any multi-version code.
*/
#include <linux/version.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/proc_fs.h>
//#include <linux/smp_lock.h>
#include <linux/pagemap.h>
#include <linux/mtd/mtd.h>
#include <linux/interrupt.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/namei.h>
#include <linux/exportfs.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/freezer.h>
#include <asm/div64.h>
#include <linux/statfs.h>
#define UnlockPage(p) unlock_page(p)
#define Page_Uptodate(page) test_bit(PG_uptodate, &(page)->flags)
#define yaffs_devname(sb, buf) bdevname(sb->s_bdev, buf)
#define YPROC_ROOT NULL
#define Y_INIT_TIMER(a) init_timer_on_stack(a)
#define WRITE_SIZE_STR "writesize"
#define WRITE_SIZE(mtd) ((mtd)->writesize)
static uint32_t YCALCBLOCKS(uint64_t partition_size, uint32_t block_size)
{
uint64_t result = partition_size;
do_div(result, block_size);
return (uint32_t) result;
}
#include <linux/uaccess.h>
#include <linux/mtd/mtd.h>
#include "yportenv.h"
#include "yaffs_trace.h"
#include "yaffs_guts.h"
#include "yaffs_attribs.h"
#include "yaffs_linux.h"
#include "yaffs_mtdif.h"
#include "yaffs_mtdif1.h"
#include "yaffs_mtdif2.h"
unsigned int yaffs_trace_mask = YAFFS_TRACE_BAD_BLOCKS | YAFFS_TRACE_ALWAYS | YAFFS_TRACE_ERROR;
unsigned int yaffs_wr_attempts = YAFFS_WR_ATTEMPTS;
unsigned int yaffs_auto_checkpoint = 1;
unsigned int yaffs_gc_control = 1;
unsigned int yaffs_bg_enable = 1;
/* Module Parameters */
module_param(yaffs_trace_mask, uint, 0644);
module_param(yaffs_wr_attempts, uint, 0644);
module_param(yaffs_auto_checkpoint, uint, 0644);
module_param(yaffs_gc_control, uint, 0644);
module_param(yaffs_bg_enable, uint, 0644);
#define yaffs_inode_to_obj_lv(iptr) ((iptr)->i_private)
#define yaffs_inode_to_obj(iptr) ((struct yaffs_obj *)(yaffs_inode_to_obj_lv(iptr)))
#define yaffs_dentry_to_obj(dptr) yaffs_inode_to_obj((dptr)->d_inode)
#define yaffs_super_to_dev(sb) ((struct yaffs_dev *)sb->s_fs_info)
#define update_dir_time(dir) do {\
(dir)->i_ctime = (dir)->i_mtime = CURRENT_TIME; \
} while(0)
static unsigned yaffs_gc_control_callback(struct yaffs_dev *dev)
{
return yaffs_gc_control;
}
static void yaffs_gross_lock(struct yaffs_dev *dev)
{
yaffs_trace(YAFFS_TRACE_LOCK, "yaffs locking %p", current);
mutex_lock(&(yaffs_dev_to_lc(dev)->gross_lock));
yaffs_trace(YAFFS_TRACE_LOCK, "yaffs locked %p", current);
}
static void yaffs_gross_unlock(struct yaffs_dev *dev)
{
yaffs_trace(YAFFS_TRACE_LOCK, "yaffs unlocking %p", current);
mutex_unlock(&(yaffs_dev_to_lc(dev)->gross_lock));
}
static void yaffs_fill_inode_from_obj(struct inode *inode,
struct yaffs_obj *obj);
static struct inode *yaffs_iget(struct super_block *sb, unsigned long ino)
{
struct inode *inode;
struct yaffs_obj *obj;
struct yaffs_dev *dev = yaffs_super_to_dev(sb);
gfp_t gfp_mask;
yaffs_trace(YAFFS_TRACE_OS, "yaffs_iget for %lu", ino);
inode = iget_locked(sb, ino);
if (!inode)
return ERR_PTR(-ENOMEM);
gfp_mask = mapping_gfp_mask(inode->i_mapping);
gfp_mask &= ~__GFP_HIGHMEM;
mapping_set_gfp_mask(inode->i_mapping, gfp_mask);
if (!(inode->i_state & I_NEW))
return inode;
/* NB This is called as a side effect of other functions, but
* we had to release the lock to prevent deadlocks, so
* need to lock again.
*/
yaffs_gross_lock(dev);
obj = yaffs_find_by_number(dev, inode->i_ino);
yaffs_fill_inode_from_obj(inode, obj);
yaffs_gross_unlock(dev);
unlock_new_inode(inode);
return inode;
}
struct inode *yaffs_get_inode(struct super_block *sb, int mode, int dev,
struct yaffs_obj *obj)
{
struct inode *inode;
if (!sb) {
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_get_inode for NULL super_block!!");
return NULL;
}
if (!obj) {
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_get_inode for NULL object!!");
return NULL;
}
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_get_inode for object %d",
obj->obj_id);
inode = yaffs_iget(sb, obj->obj_id);
if (IS_ERR(inode))
return NULL;
/* NB Side effect: iget calls back to yaffs_read_inode(). */
/* iget also increments the inode's i_count */
/* NB You can't be holding gross_lock or deadlock will happen! */
return inode;
}
static int yaffs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode,
dev_t rdev)
{
struct inode *inode;
struct yaffs_obj *obj = NULL;
struct yaffs_dev *dev;
struct yaffs_obj *parent = yaffs_inode_to_obj(dir);
int error = -ENOSPC;
uid_t uid = current->cred->fsuid;
gid_t gid =
(dir->i_mode & S_ISGID) ? dir->i_gid : current->cred->fsgid;
if ((dir->i_mode & S_ISGID) && S_ISDIR(mode))
mode |= S_ISGID;
if (parent) {
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_mknod: parent object %d type %d",
parent->obj_id, parent->variant_type);
} else {
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_mknod: could not get parent object");
return -EPERM;
}
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_mknod: making oject for %s, mode %x dev %x",
dentry->d_name.name, mode, rdev);
dev = parent->my_dev;
yaffs_gross_lock(dev);
switch (mode & S_IFMT) {
default:
/* Special (socket, fifo, device...) */
yaffs_trace(YAFFS_TRACE_OS, "yaffs_mknod: making special");
obj =
yaffs_create_special(parent, dentry->d_name.name, mode, uid,
gid, old_encode_dev(rdev));
break;
case S_IFREG: /* file */
yaffs_trace(YAFFS_TRACE_OS, "yaffs_mknod: making file");
obj = yaffs_create_file(parent, dentry->d_name.name, mode, uid,
gid);
break;
case S_IFDIR: /* directory */
yaffs_trace(YAFFS_TRACE_OS, "yaffs_mknod: making directory");
obj = yaffs_create_dir(parent, dentry->d_name.name, mode,
uid, gid);
break;
case S_IFLNK: /* symlink */
yaffs_trace(YAFFS_TRACE_OS, "yaffs_mknod: making symlink");
obj = NULL; /* Do we ever get here? */
break;
}
/* Can not call yaffs_get_inode() with gross lock held */
yaffs_gross_unlock(dev);
if (obj) {
inode = yaffs_get_inode(dir->i_sb, mode, rdev, obj);
d_instantiate(dentry, inode);
update_dir_time(dir);
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_mknod created object %d count = %d",
obj->obj_id, atomic_read(&inode->i_count));
error = 0;
yaffs_fill_inode_from_obj(dir, parent);
} else {
yaffs_trace(YAFFS_TRACE_OS, "yaffs_mknod failed making object");
error = -ENOMEM;
}
return error;
}
static int yaffs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
{
return yaffs_mknod(dir, dentry, mode | S_IFDIR, 0);
}
static int yaffs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
struct nameidata *n)
{
return yaffs_mknod(dir, dentry, mode | S_IFREG, 0);
}
static int yaffs_link(struct dentry *old_dentry, struct inode *dir,
struct dentry *dentry)
{
struct inode *inode = old_dentry->d_inode;
struct yaffs_obj *obj = NULL;
struct yaffs_obj *link = NULL;
struct yaffs_dev *dev;
yaffs_trace(YAFFS_TRACE_OS, "yaffs_link");
obj = yaffs_inode_to_obj(inode);
dev = obj->my_dev;
yaffs_gross_lock(dev);
if (!S_ISDIR(inode->i_mode)) /* Don't link directories */
link =
yaffs_link_obj(yaffs_inode_to_obj(dir), dentry->d_name.name,
obj);
if (link) {
old_dentry->d_inode->__i_nlink = yaffs_get_obj_link_count(obj);
d_instantiate(dentry, old_dentry->d_inode);
atomic_inc(&old_dentry->d_inode->i_count);
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_link link count %d i_count %d",
old_dentry->d_inode->__i_nlink,
atomic_read(&old_dentry->d_inode->i_count));
}
yaffs_gross_unlock(dev);
if (link) {
update_dir_time(dir);
return 0;
}
return -EPERM;
}
static int yaffs_symlink(struct inode *dir, struct dentry *dentry,
const char *symname)
{
struct yaffs_obj *obj;
struct yaffs_dev *dev;
uid_t uid = current->cred->fsuid;
gid_t gid =
(dir->i_mode & S_ISGID) ? dir->i_gid : current->cred->fsgid;
yaffs_trace(YAFFS_TRACE_OS, "yaffs_symlink");
dev = yaffs_inode_to_obj(dir)->my_dev;
yaffs_gross_lock(dev);
obj = yaffs_create_symlink(yaffs_inode_to_obj(dir), dentry->d_name.name,
S_IFLNK | S_IRWXUGO, uid, gid, symname);
yaffs_gross_unlock(dev);
if (obj) {
struct inode *inode;
inode = yaffs_get_inode(dir->i_sb, obj->yst_mode, 0, obj);
d_instantiate(dentry, inode);
update_dir_time(dir);
yaffs_trace(YAFFS_TRACE_OS, "symlink created OK");
return 0;
} else {
yaffs_trace(YAFFS_TRACE_OS, "symlink not created");
}
return -ENOMEM;
}
static struct dentry *yaffs_lookup(struct inode *dir, struct dentry *dentry,
struct nameidata *n)
{
struct yaffs_obj *obj;
struct inode *inode = NULL;
struct yaffs_dev *dev = yaffs_inode_to_obj(dir)->my_dev;
if (current != yaffs_dev_to_lc(dev)->readdir_process)
yaffs_gross_lock(dev);
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_lookup for %d:%s",
yaffs_inode_to_obj(dir)->obj_id, dentry->d_name.name);
obj = yaffs_find_by_name(yaffs_inode_to_obj(dir), dentry->d_name.name);
obj = yaffs_get_equivalent_obj(obj); /* in case it was a hardlink */
/* Can't hold gross lock when calling yaffs_get_inode() */
if (current != yaffs_dev_to_lc(dev)->readdir_process)
yaffs_gross_unlock(dev);
if (obj) {
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_lookup found %d", obj->obj_id);
inode = yaffs_get_inode(dir->i_sb, obj->yst_mode, 0, obj);
if (inode) {
yaffs_trace(YAFFS_TRACE_OS, "yaffs_loookup dentry");
d_add(dentry, inode);
/* return dentry; */
return NULL;
}
} else {
yaffs_trace(YAFFS_TRACE_OS, "yaffs_lookup not found");
}
d_add(dentry, inode);
return NULL;
}
static int yaffs_unlink(struct inode *dir, struct dentry *dentry)
{
int ret_val;
struct yaffs_dev *dev;
struct yaffs_obj *obj;
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_unlink %d:%s",
(int)(dir->i_ino), dentry->d_name.name);
obj = yaffs_inode_to_obj(dir);
dev = obj->my_dev;
yaffs_gross_lock(dev);
ret_val = yaffs_unlinker(obj, dentry->d_name.name);
if (ret_val == YAFFS_OK) {
dentry->d_inode->__i_nlink--;
dir->i_version++;
yaffs_gross_unlock(dev);
mark_inode_dirty(dentry->d_inode);
update_dir_time(dir);
return 0;
}
yaffs_gross_unlock(dev);
return -ENOTEMPTY;
}
static int yaffs_sync_object(struct file *file,loff_t start,loff_t end, int datasync)
{
struct yaffs_obj *obj;
struct yaffs_dev *dev;
struct dentry *dentry = file->f_path.dentry;
obj = yaffs_dentry_to_obj(dentry);
dev = obj->my_dev;
yaffs_trace(YAFFS_TRACE_OS | YAFFS_TRACE_SYNC, "yaffs_sync_object");
yaffs_gross_lock(dev);
yaffs_flush_file(obj, 1, datasync);
yaffs_gross_unlock(dev);
return 0;
}
/*
* The VFS layer already does all the dentry stuff for rename.
*
* NB: POSIX says you can rename an object over an old object of the same name
*/
static int yaffs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
struct yaffs_dev *dev;
int ret_val = YAFFS_FAIL;
struct yaffs_obj *target;
yaffs_trace(YAFFS_TRACE_OS, "yaffs_rename");
dev = yaffs_inode_to_obj(old_dir)->my_dev;
yaffs_gross_lock(dev);
/* Check if the target is an existing directory that is not empty. */
target = yaffs_find_by_name(yaffs_inode_to_obj(new_dir),
new_dentry->d_name.name);
if (target && target->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY &&
!list_empty(&target->variant.dir_variant.children)) {
yaffs_trace(YAFFS_TRACE_OS, "target is non-empty dir");
ret_val = YAFFS_FAIL;
} else {
/* Now does unlinking internally using shadowing mechanism */
yaffs_trace(YAFFS_TRACE_OS, "calling yaffs_rename_obj");
ret_val = yaffs_rename_obj(yaffs_inode_to_obj(old_dir),
old_dentry->d_name.name,
yaffs_inode_to_obj(new_dir),
new_dentry->d_name.name);
}
yaffs_gross_unlock(dev);
if (ret_val == YAFFS_OK) {
if (target) {
new_dentry->d_inode->__i_nlink--;
mark_inode_dirty(new_dentry->d_inode);
}
update_dir_time(old_dir);
if (old_dir != new_dir)
update_dir_time(new_dir);
return 0;
} else {
return -ENOTEMPTY;
}
}
static int yaffs_setattr(struct dentry *dentry, struct iattr *attr)
{
struct inode *inode = dentry->d_inode;
int error = 0;
struct yaffs_dev *dev;
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_setattr of object %d",
yaffs_inode_to_obj(inode)->obj_id);
/* Fail if a requested resize >= 2GB */
if (attr->ia_valid & ATTR_SIZE && (attr->ia_size >> 32)){
printk("[yaffs_setattr] length %llx beyond 4GB\n",attr->ia_size);
error = -EINVAL;
}
if (error == 0)
error = inode_change_ok(inode, attr);
if (error == 0) {
int result;
if (!error) {
setattr_copy(inode, attr);
yaffs_trace(YAFFS_TRACE_OS, "inode_setattr called");
if (attr->ia_valid & ATTR_SIZE) {
truncate_setsize(inode, attr->ia_size);
inode->i_blocks = (inode->i_size + 511) >> 9;
}
}
dev = yaffs_inode_to_obj(inode)->my_dev;
if (attr->ia_valid & ATTR_SIZE) {
yaffs_trace(YAFFS_TRACE_OS, "resize to %d(%x)",
(int)(attr->ia_size),
(int)(attr->ia_size));
}
yaffs_gross_lock(dev);
result = yaffs_set_attribs(yaffs_inode_to_obj(inode), attr);
if (result == YAFFS_OK) {
error = 0;
} else {
error = -EPERM;
}
yaffs_gross_unlock(dev);
}
yaffs_trace(YAFFS_TRACE_OS, "yaffs_setattr done returning %d", error);
return error;
}
#ifdef CONFIG_YAFFS_XATTR
static int yaffs_setxattr(struct dentry *dentry, const char *name,
const void *value, size_t size, int flags)
{
struct inode *inode = dentry->d_inode;
int error = 0;
struct yaffs_dev *dev;
struct yaffs_obj *obj = yaffs_inode_to_obj(inode);
yaffs_trace(YAFFS_TRACE_OS, "yaffs_setxattr of object %d", obj->obj_id);
if (error == 0) {
int result;
dev = obj->my_dev;
yaffs_gross_lock(dev);
result = yaffs_set_xattrib(obj, name, value, size, flags);
if (result == YAFFS_OK)
error = 0;
else if (result < 0)
error = result;
yaffs_gross_unlock(dev);
}
yaffs_trace(YAFFS_TRACE_OS, "yaffs_setxattr done returning %d", error);
return error;
}
static ssize_t yaffs_getxattr(struct dentry * dentry, const char *name, void *buff,
size_t size)
{
struct inode *inode = dentry->d_inode;
int error = 0;
struct yaffs_dev *dev;
struct yaffs_obj *obj = yaffs_inode_to_obj(inode);
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_getxattr \"%s\" from object %d",
name, obj->obj_id);
if (error == 0) {
dev = obj->my_dev;
yaffs_gross_lock(dev);
error = yaffs_get_xattrib(obj, name, buff, size);
yaffs_gross_unlock(dev);
}
yaffs_trace(YAFFS_TRACE_OS, "yaffs_getxattr done returning %d", error);
return error;
}
static int yaffs_removexattr(struct dentry *dentry, const char *name)
{
struct inode *inode = dentry->d_inode;
int error = 0;
struct yaffs_dev *dev;
struct yaffs_obj *obj = yaffs_inode_to_obj(inode);
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_removexattr of object %d", obj->obj_id);
if (error == 0) {
int result;
dev = obj->my_dev;
yaffs_gross_lock(dev);
result = yaffs_remove_xattrib(obj, name);
if (result == YAFFS_OK)
error = 0;
else if (result < 0)
error = result;
yaffs_gross_unlock(dev);
}
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_removexattr done returning %d", error);
return error;
}
static ssize_t yaffs_listxattr(struct dentry * dentry, char *buff, size_t size)
{
struct inode *inode = dentry->d_inode;
int error = 0;
struct yaffs_dev *dev;
struct yaffs_obj *obj = yaffs_inode_to_obj(inode);
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_listxattr of object %d", obj->obj_id);
if (error == 0) {
dev = obj->my_dev;
yaffs_gross_lock(dev);
error = yaffs_list_xattrib(obj, buff, size);
yaffs_gross_unlock(dev);
}
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_listxattr done returning %d", error);
return error;
}
#endif
static const struct inode_operations yaffs_dir_inode_operations = {
.create = yaffs_create,
.lookup = yaffs_lookup,
.link = yaffs_link,
.unlink = yaffs_unlink,
.symlink = yaffs_symlink,
.mkdir = yaffs_mkdir,
.rmdir = yaffs_unlink,
.mknod = yaffs_mknod,
.rename = yaffs_rename,
.setattr = yaffs_setattr,
#ifdef CONFIG_YAFFS_XATTR
.setxattr = yaffs_setxattr,
.getxattr = yaffs_getxattr,
.listxattr = yaffs_listxattr,
.removexattr = yaffs_removexattr,
#endif
};
/*-----------------------------------------------------------------*/
/* Directory search context allows us to unlock access to yaffs during
* filldir without causing problems with the directory being modified.
* This is similar to the tried and tested mechanism used in yaffs direct.
*
* A search context iterates along a doubly linked list of siblings in the
* directory. If the iterating object is deleted then this would corrupt
* the list iteration, likely causing a crash. The search context avoids
* this by using the remove_obj_fn to move the search context to the
* next object before the object is deleted.
*
* Many readdirs (and thus seach conexts) may be alive simulateously so
* each struct yaffs_dev has a list of these.
*
* A seach context lives for the duration of a readdir.
*
* All these functions must be called while yaffs is locked.
*/
struct yaffs_search_context {
struct yaffs_dev *dev;
struct yaffs_obj *dir_obj;
struct yaffs_obj *next_return;
struct list_head others;
};
/*
* yaffs_new_search() creates a new search context, initialises it and
* adds it to the device's search context list.
*
* Called at start of readdir.
*/
static struct yaffs_search_context *yaffs_new_search(struct yaffs_obj *dir)
{
struct yaffs_dev *dev = dir->my_dev;
struct yaffs_search_context *sc =
kmalloc(sizeof(struct yaffs_search_context), GFP_NOFS);
if (sc) {
sc->dir_obj = dir;
sc->dev = dev;
if (list_empty(&sc->dir_obj->variant.dir_variant.children))
sc->next_return = NULL;
else
sc->next_return =
list_entry(dir->variant.dir_variant.children.next,
struct yaffs_obj, siblings);
INIT_LIST_HEAD(&sc->others);
list_add(&sc->others, &(yaffs_dev_to_lc(dev)->search_contexts));
}
return sc;
}
/*
* yaffs_search_end() disposes of a search context and cleans up.
*/
static void yaffs_search_end(struct yaffs_search_context *sc)
{
if (sc) {
list_del(&sc->others);
kfree(sc);
}
}
/*
* yaffs_search_advance() moves a search context to the next object.
* Called when the search iterates or when an object removal causes
* the search context to be moved to the next object.
*/
static void yaffs_search_advance(struct yaffs_search_context *sc)
{
if (!sc)
return;
if (sc->next_return == NULL ||
list_empty(&sc->dir_obj->variant.dir_variant.children))
sc->next_return = NULL;
else {
struct list_head *next = sc->next_return->siblings.next;
if (next == &sc->dir_obj->variant.dir_variant.children)
sc->next_return = NULL; /* end of list */
else
sc->next_return =
list_entry(next, struct yaffs_obj, siblings);
}
}
/*
* yaffs_remove_obj_callback() is called when an object is unlinked.
* We check open search contexts and advance any which are currently
* on the object being iterated.
*/
static void yaffs_remove_obj_callback(struct yaffs_obj *obj)
{
struct list_head *i;
struct yaffs_search_context *sc;
struct list_head *search_contexts =
&(yaffs_dev_to_lc(obj->my_dev)->search_contexts);
/* Iterate through the directory search contexts.
* If any are currently on the object being removed, then advance
* the search context to the next object to prevent a hanging pointer.
*/
list_for_each(i, search_contexts) {
if (i) {
sc = list_entry(i, struct yaffs_search_context, others);
if (sc->next_return == obj)
yaffs_search_advance(sc);
}
}
}
static int yaffs_readdir(struct file *f, void *dirent, filldir_t filldir)
{
struct yaffs_obj *obj;
struct yaffs_dev *dev;
struct yaffs_search_context *sc;
struct inode *inode = f->f_dentry->d_inode;
unsigned long offset, curoffs;
struct yaffs_obj *l;
int ret_val = 0;
char name[YAFFS_MAX_NAME_LENGTH + 1];
obj = yaffs_dentry_to_obj(f->f_dentry);
dev = obj->my_dev;
yaffs_gross_lock(dev);
yaffs_dev_to_lc(dev)->readdir_process = current;
offset = f->f_pos;
sc = yaffs_new_search(obj);
if (!sc) {
ret_val = -ENOMEM;
goto out;
}
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_readdir: starting at %d", (int)offset);
if (offset == 0) {
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_readdir: entry . ino %d",
(int)inode->i_ino);
yaffs_gross_unlock(dev);
if (filldir(dirent, ".", 1, offset, inode->i_ino, DT_DIR) < 0) {
yaffs_gross_lock(dev);
goto out;
}
yaffs_gross_lock(dev);
offset++;
f->f_pos++;
}
if (offset == 1) {
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_readdir: entry .. ino %d",
(int)f->f_dentry->d_parent->d_inode->i_ino);
yaffs_gross_unlock(dev);
if (filldir(dirent, "..", 2, offset,
f->f_dentry->d_parent->d_inode->i_ino,
DT_DIR) < 0) {
yaffs_gross_lock(dev);
goto out;
}
yaffs_gross_lock(dev);
offset++;
f->f_pos++;
}
curoffs = 1;
/* If the directory has changed since the open or last call to
readdir, rewind to after the 2 canned entries. */
if (f->f_version != inode->i_version) {
offset = 2;
f->f_pos = offset;
f->f_version = inode->i_version;
}
while (sc->next_return) {
curoffs++;
l = sc->next_return;
if (curoffs >= offset) {
int this_inode = yaffs_get_obj_inode(l);
int this_type = yaffs_get_obj_type(l);
yaffs_get_obj_name(l, name, YAFFS_MAX_NAME_LENGTH + 1);
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_readdir: %s inode %d",
name, yaffs_get_obj_inode(l));
yaffs_gross_unlock(dev);
if (filldir(dirent,
name,
strlen(name),
offset, this_inode, this_type) < 0) {
yaffs_gross_lock(dev);
goto out;
}
yaffs_gross_lock(dev);
offset++;
f->f_pos++;
}
yaffs_search_advance(sc);
}
out:
yaffs_search_end(sc);
yaffs_dev_to_lc(dev)->readdir_process = NULL;
yaffs_gross_unlock(dev);
return ret_val;
}
static const struct file_operations yaffs_dir_operations = {
.read = generic_read_dir,
.readdir = yaffs_readdir,
.fsync = yaffs_sync_object,
.llseek = generic_file_llseek,
};
static int yaffs_file_flush(struct file *file, fl_owner_t id)
{
struct yaffs_obj *obj = yaffs_dentry_to_obj(file->f_dentry);
struct yaffs_dev *dev = obj->my_dev;
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_file_flush object %d (%s)",
obj->obj_id, obj->dirty ? "dirty" : "clean");
yaffs_gross_lock(dev);
yaffs_flush_file(obj, 1, 0);
yaffs_gross_unlock(dev);
return 0;
}
static const struct file_operations yaffs_file_operations = {
.read = do_sync_read,
.write = do_sync_write,
.aio_read = generic_file_aio_read,
.aio_write = generic_file_aio_write,
.mmap = generic_file_mmap,
.flush = yaffs_file_flush,
.fsync = yaffs_sync_object,
.splice_read = generic_file_splice_read,
.splice_write = generic_file_splice_write,
.llseek = generic_file_llseek,
};
/* ExportFS support */
static struct inode *yaffs2_nfs_get_inode(struct super_block *sb, uint64_t ino,
uint32_t generation)
{
return yaffs_iget(sb, ino);
}
static struct dentry *yaffs2_fh_to_dentry(struct super_block *sb,
struct fid *fid, int fh_len,
int fh_type)
{
return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
yaffs2_nfs_get_inode);
}
static struct dentry *yaffs2_fh_to_parent(struct super_block *sb,
struct fid *fid, int fh_len,
int fh_type)
{
return generic_fh_to_parent(sb, fid, fh_len, fh_type,
yaffs2_nfs_get_inode);
}
struct dentry *yaffs2_get_parent(struct dentry *dentry)
{
struct super_block *sb = dentry->d_inode->i_sb;
struct dentry *parent = ERR_PTR(-ENOENT);
struct inode *inode;
unsigned long parent_ino;
struct yaffs_obj *d_obj;
struct yaffs_obj *parent_obj;
d_obj = yaffs_inode_to_obj(dentry->d_inode);
if (d_obj) {
parent_obj = d_obj->parent;
if (parent_obj) {
parent_ino = yaffs_get_obj_inode(parent_obj);
inode = yaffs_iget(sb, parent_ino);
if (IS_ERR(inode)) {
parent = ERR_CAST(inode);
} else {
parent = d_obtain_alias(inode);
if (!IS_ERR(parent)) {
parent = ERR_PTR(-ENOMEM);
iput(inode);
}
}
}
}
return parent;
}
/* Just declare a zero structure as a NULL value implies
* using the default functions of exportfs.
*/
static struct export_operations yaffs_export_ops = {
.fh_to_dentry = yaffs2_fh_to_dentry,
.fh_to_parent = yaffs2_fh_to_parent,
.get_parent = yaffs2_get_parent,
};
/*-----------------------------------------------------------------*/
static int yaffs_readlink(struct dentry *dentry, char __user * buffer,
int buflen)
{
unsigned char *alias;
int ret;
struct yaffs_dev *dev = yaffs_dentry_to_obj(dentry)->my_dev;
yaffs_gross_lock(dev);
alias = yaffs_get_symlink_alias(yaffs_dentry_to_obj(dentry));
yaffs_gross_unlock(dev);
if (!alias)
return -ENOMEM;
ret = vfs_readlink(dentry, buffer, buflen, alias);
kfree(alias);
return ret;
}
static void *yaffs_follow_link(struct dentry *dentry, struct nameidata *nd)
{
unsigned char *alias;
void *ret;
struct yaffs_dev *dev = yaffs_dentry_to_obj(dentry)->my_dev;
yaffs_gross_lock(dev);
alias = yaffs_get_symlink_alias(yaffs_dentry_to_obj(dentry));
yaffs_gross_unlock(dev);
if (!alias) {
ret = ERR_PTR(-ENOMEM);
goto out;
}
nd_set_link(nd, alias);
ret = (void *)alias;
out:
return ret;
}
void yaffs_put_link(struct dentry *dentry, struct nameidata *nd, void *alias)
{
kfree(alias);
}
static void yaffs_unstitch_obj(struct inode *inode, struct yaffs_obj *obj)
{
/* Clear the association between the inode and
* the struct yaffs_obj.
*/
obj->my_inode = NULL;
yaffs_inode_to_obj_lv(inode) = NULL;
/* If the object freeing was deferred, then the real
* free happens now.
* This should fix the inode inconsistency problem.
*/
yaffs_handle_defered_free(obj);
}
/* yaffs_evict_inode combines into one operation what was previously done in
* yaffs_clear_inode() and yaffs_delete_inode()
*
*/
static void yaffs_evict_inode(struct inode *inode)
{
struct yaffs_obj *obj;
struct yaffs_dev *dev;
int deleteme = 0;
obj = yaffs_inode_to_obj(inode);
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_evict_inode: ino %d, count %d %s",
(int)inode->i_ino,
atomic_read(&inode->i_count),
obj ? "object exists" : "null object");
if (!inode->__i_nlink && !is_bad_inode(inode))
deleteme = 1;
truncate_inode_pages(&inode->i_data, 0);
end_writeback(inode);
if (deleteme && obj) {
dev = obj->my_dev;
yaffs_gross_lock(dev);
yaffs_del_obj(obj);
yaffs_gross_unlock(dev);
}
if (obj) {
dev = obj->my_dev;
yaffs_gross_lock(dev);
yaffs_unstitch_obj(inode, obj);
yaffs_gross_unlock(dev);
}
}
static void yaffs_touch_super(struct yaffs_dev *dev)
{
struct super_block *sb = yaffs_dev_to_lc(dev)->super;
yaffs_trace(YAFFS_TRACE_OS, "yaffs_touch_super() sb = %p", sb);
if (sb)
sb->s_dirt = 1;
}
static int yaffs_readpage_nolock(struct file *f, struct page *pg)
{
/* Lifted from jffs2 */
struct yaffs_obj *obj;
unsigned char *pg_buf;
int ret;
struct yaffs_dev *dev;
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_readpage_nolock at %08x, size %08x",
(unsigned)(pg->index << PAGE_CACHE_SHIFT),
(unsigned)PAGE_CACHE_SIZE);
obj = yaffs_dentry_to_obj(f->f_dentry);
dev = obj->my_dev;
BUG_ON(!PageLocked(pg));
pg_buf = kmap(pg);
/* FIXME: Can kmap fail? */
yaffs_gross_lock(dev);
ret = yaffs_file_rd(obj, pg_buf,
pg->index << PAGE_CACHE_SHIFT, PAGE_CACHE_SIZE);
yaffs_gross_unlock(dev);
if (ret >= 0)
ret = 0;
if (ret) {
ClearPageUptodate(pg);
SetPageError(pg);
} else {
SetPageUptodate(pg);
ClearPageError(pg);
}
flush_dcache_page(pg);
kunmap(pg);
yaffs_trace(YAFFS_TRACE_OS, "yaffs_readpage_nolock done");
return ret;
}
static int yaffs_readpage_unlock(struct file *f, struct page *pg)
{
int ret = yaffs_readpage_nolock(f, pg);
UnlockPage(pg);
return ret;
}
static int yaffs_readpage(struct file *f, struct page *pg)
{
int ret;
yaffs_trace(YAFFS_TRACE_OS, "yaffs_readpage");
ret = yaffs_readpage_unlock(f, pg);
yaffs_trace(YAFFS_TRACE_OS, "yaffs_readpage done");
return ret;
}
/* writepage inspired by/stolen from smbfs */
static int yaffs_writepage(struct page *page, struct writeback_control *wbc)
{
struct yaffs_dev *dev;
struct address_space *mapping = page->mapping;
struct inode *inode;
unsigned long end_index;
char *buffer;
struct yaffs_obj *obj;
int n_written = 0;
unsigned n_bytes;
loff_t i_size;
if (!mapping)
BUG();
inode = mapping->host;
if (!inode)
BUG();
i_size = i_size_read(inode);
end_index = i_size >> PAGE_CACHE_SHIFT;
if (page->index < end_index)
n_bytes = PAGE_CACHE_SIZE;
else {
n_bytes = i_size & (PAGE_CACHE_SIZE - 1);
if (page->index > end_index || !n_bytes) {
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_writepage at %08x, inode size = %08x!!!",
(unsigned)(page->index << PAGE_CACHE_SHIFT),
(unsigned)inode->i_size);
yaffs_trace(YAFFS_TRACE_OS,
" -> don't care!!");
zero_user_segment(page, 0, PAGE_CACHE_SIZE);
set_page_writeback(page);
unlock_page(page);
end_page_writeback(page);
return 0;
}
}
if (n_bytes != PAGE_CACHE_SIZE)
zero_user_segment(page, n_bytes, PAGE_CACHE_SIZE);
get_page(page);
buffer = kmap(page);
obj = yaffs_inode_to_obj(inode);
dev = obj->my_dev;
yaffs_gross_lock(dev);
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_writepage at %08x, size %08x",
(unsigned)(page->index << PAGE_CACHE_SHIFT), n_bytes);
yaffs_trace(YAFFS_TRACE_OS,
"writepag0: obj = %05x, ino = %05x",
(int)obj->variant.file_variant.file_size, (int)inode->i_size);
n_written = yaffs_wr_file(obj, buffer,
page->index << PAGE_CACHE_SHIFT, n_bytes, 0);
yaffs_touch_super(dev);
yaffs_trace(YAFFS_TRACE_OS,
"writepag1: obj = %05x, ino = %05x",
(int)obj->variant.file_variant.file_size, (int)inode->i_size);
yaffs_gross_unlock(dev);
kunmap(page);
set_page_writeback(page);
unlock_page(page);
end_page_writeback(page);
put_page(page);
return (n_written == n_bytes) ? 0 : -ENOSPC;
}
/* Space holding and freeing is done to ensure we have space available for
* write_begin/end.
* For now we just assume few parallel writes and check against a small
* number.
* Todo: need to do this with a counter to handle parallel reads better.
*/
static ssize_t yaffs_hold_space(struct file *f)
{
struct yaffs_obj *obj;
struct yaffs_dev *dev;
int n_free_chunks;
obj = yaffs_dentry_to_obj(f->f_dentry);
dev = obj->my_dev;
yaffs_gross_lock(dev);
n_free_chunks = yaffs_get_n_free_chunks(dev);
yaffs_gross_unlock(dev);
return (n_free_chunks > 20) ? 1 : 0;
}
static void yaffs_release_space(struct file *f)
{
struct yaffs_obj *obj;
struct yaffs_dev *dev;
obj = yaffs_dentry_to_obj(f->f_dentry);
dev = obj->my_dev;
yaffs_gross_lock(dev);
yaffs_gross_unlock(dev);
}
static int yaffs_write_begin(struct file *filp, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
struct page *pg = NULL;
pgoff_t index = pos >> PAGE_CACHE_SHIFT;
int ret = 0;
int space_held = 0;
/* Get a page */
pg = grab_cache_page_write_begin(mapping, index, flags);
*pagep = pg;
if (!pg) {
ret = -ENOMEM;
goto out;
}
yaffs_trace(YAFFS_TRACE_OS,
"start yaffs_write_begin index %d(%x) uptodate %d",
(int)index, (int)index, Page_Uptodate(pg) ? 1 : 0);
/* Get fs space */
space_held = yaffs_hold_space(filp);
if (!space_held) {
ret = -ENOSPC;
goto out;
}
/* Update page if required */
if (!Page_Uptodate(pg))
ret = yaffs_readpage_nolock(filp, pg);
if (ret)
goto out;
/* Happy path return */
yaffs_trace(YAFFS_TRACE_OS, "end yaffs_write_begin - ok");
return 0;
out:
yaffs_trace(YAFFS_TRACE_OS,
"end yaffs_write_begin fail returning %d", ret);
if (space_held)
yaffs_release_space(filp);
if (pg) {
unlock_page(pg);
page_cache_release(pg);
}
return ret;
}
static ssize_t yaffs_file_write(struct file *f, const char *buf, size_t n,
loff_t * pos)
{
struct yaffs_obj *obj;
int n_written, ipos;
struct inode *inode;
struct yaffs_dev *dev;
obj = yaffs_dentry_to_obj(f->f_dentry);
dev = obj->my_dev;
yaffs_gross_lock(dev);
inode = f->f_dentry->d_inode;
if (!S_ISBLK(inode->i_mode) && f->f_flags & O_APPEND)
ipos = inode->i_size;
else
ipos = *pos;
if (!obj)
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_file_write: hey obj is null!");
else
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_file_write about to write writing %u(%x) bytes to object %d at %d(%x)",
(unsigned)n, (unsigned)n, obj->obj_id, ipos, ipos);
n_written = yaffs_wr_file(obj, buf, ipos, n, 0);
yaffs_touch_super(dev);
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_file_write: %d(%x) bytes written",
(unsigned)n, (unsigned)n);
if (n_written > 0) {
ipos += n_written;
*pos = ipos;
if (ipos > inode->i_size) {
inode->i_size = ipos;
inode->i_blocks = (ipos + 511) >> 9;
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_file_write size updated to %d bytes, %d blocks",
ipos, (int)(inode->i_blocks));
}
}
yaffs_gross_unlock(dev);
return (n_written == 0) && (n > 0) ? -ENOSPC : n_written;
}
static int yaffs_write_end(struct file *filp, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *pg, void *fsdadata)
{
int ret = 0;
void *addr, *kva;
uint32_t offset_into_page = pos & (PAGE_CACHE_SIZE - 1);
kva = kmap(pg);
addr = kva + offset_into_page;
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_write_end addr %p pos %x n_bytes %d",
addr, (unsigned)pos, copied);
ret = yaffs_file_write(filp, addr, copied, &pos);
if (ret != copied) {
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_write_end not same size ret %d copied %d",
ret, copied);
SetPageError(pg);
}
kunmap(pg);
yaffs_release_space(filp);
unlock_page(pg);
page_cache_release(pg);
return ret;
}
static int yaffs_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct yaffs_dev *dev = yaffs_dentry_to_obj(dentry)->my_dev;
struct super_block *sb = dentry->d_sb;
yaffs_trace(YAFFS_TRACE_OS, "yaffs_statfs");
yaffs_gross_lock(dev);
buf->f_type = YAFFS_MAGIC;
buf->f_bsize = sb->s_blocksize;
buf->f_namelen = 255;
if (dev->data_bytes_per_chunk & (dev->data_bytes_per_chunk - 1)) {
/* Do this if chunk size is not a power of 2 */
uint64_t bytes_in_dev;
uint64_t bytes_free;
bytes_in_dev =
((uint64_t)
((dev->param.end_block - dev->param.start_block +
1))) * ((uint64_t) (dev->param.chunks_per_block *
dev->data_bytes_per_chunk));
do_div(bytes_in_dev, sb->s_blocksize); /* bytes_in_dev becomes the number of blocks */
buf->f_blocks = bytes_in_dev;
bytes_free = ((uint64_t) (yaffs_get_n_free_chunks(dev))) *
((uint64_t) (dev->data_bytes_per_chunk));
do_div(bytes_free, sb->s_blocksize);
buf->f_bfree = bytes_free;
} else if (sb->s_blocksize > dev->data_bytes_per_chunk) {
buf->f_blocks =
(dev->param.end_block - dev->param.start_block + 1) *
dev->param.chunks_per_block /
(sb->s_blocksize / dev->data_bytes_per_chunk);
buf->f_bfree =
yaffs_get_n_free_chunks(dev) /
(sb->s_blocksize / dev->data_bytes_per_chunk);
} else {
buf->f_blocks =
(dev->param.end_block - dev->param.start_block + 1) *
dev->param.chunks_per_block *
(dev->data_bytes_per_chunk / sb->s_blocksize);
buf->f_bfree =
yaffs_get_n_free_chunks(dev) *
(dev->data_bytes_per_chunk / sb->s_blocksize);
}
buf->f_files = 0;
buf->f_ffree = 0;
buf->f_bavail = buf->f_bfree;
yaffs_gross_unlock(dev);
return 0;
}
static void yaffs_flush_inodes(struct super_block *sb)
{
struct inode *iptr;
struct yaffs_obj *obj;
list_for_each_entry(iptr, &sb->s_inodes, i_sb_list) {
obj = yaffs_inode_to_obj(iptr);
if (obj) {
yaffs_trace(YAFFS_TRACE_OS,
"flushing obj %d", obj->obj_id);
yaffs_flush_file(obj, 1, 0);
}
}
}
static void yaffs_flush_super(struct super_block *sb, int do_checkpoint)
{
struct yaffs_dev *dev = yaffs_super_to_dev(sb);
if (!dev)
return;
yaffs_flush_inodes(sb);
yaffs_update_dirty_dirs(dev);
yaffs_flush_whole_cache(dev);
if (do_checkpoint)
yaffs_checkpoint_save(dev);
}
static unsigned yaffs_bg_gc_urgency(struct yaffs_dev *dev)
{
unsigned erased_chunks =
dev->n_erased_blocks * dev->param.chunks_per_block;
struct yaffs_linux_context *context = yaffs_dev_to_lc(dev);
unsigned scattered = 0; /* Free chunks not in an erased block */
if (erased_chunks < dev->n_free_chunks)
scattered = (dev->n_free_chunks - erased_chunks);
if (!context->bg_running)
return 0;
else if (scattered < (dev->param.chunks_per_block * 2))
return 0;
else if (erased_chunks > dev->n_free_chunks / 2)
return 0;
else if (erased_chunks > dev->n_free_chunks / 4)
return 1;
else
return 2;
}
static int yaffs_do_sync_fs(struct super_block *sb, int request_checkpoint)
{
struct yaffs_dev *dev = yaffs_super_to_dev(sb);
unsigned int oneshot_checkpoint = (yaffs_auto_checkpoint & 4);
unsigned gc_urgent = yaffs_bg_gc_urgency(dev);
int do_checkpoint;
yaffs_trace(YAFFS_TRACE_OS | YAFFS_TRACE_SYNC | YAFFS_TRACE_BACKGROUND,
"yaffs_do_sync_fs: gc-urgency %d %s %s%s",
gc_urgent,
sb->s_dirt ? "dirty" : "clean",
request_checkpoint ? "checkpoint requested" : "no checkpoint",
oneshot_checkpoint ? " one-shot" : "");
yaffs_gross_lock(dev);
do_checkpoint = ((request_checkpoint && !gc_urgent) ||
oneshot_checkpoint) && !dev->is_checkpointed;
if (sb->s_dirt || do_checkpoint) {
yaffs_flush_super(sb, !dev->is_checkpointed && do_checkpoint);
sb->s_dirt = 0;
if (oneshot_checkpoint)
yaffs_auto_checkpoint &= ~4;
}
yaffs_gross_unlock(dev);
return 0;
}
/*
* yaffs background thread functions .
* yaffs_bg_thread_fn() the thread function
* yaffs_bg_start() launches the background thread.
* yaffs_bg_stop() cleans up the background thread.
*
* NB:
* The thread should only run after the yaffs is initialised
* The thread should be stopped before yaffs is unmounted.
* The thread should not do any writing while the fs is in read only.
*/
void yaffs_background_waker(unsigned long data)
{
wake_up_process((struct task_struct *)data);
}
static int yaffs_bg_thread_fn(void *data)
{
struct yaffs_dev *dev = (struct yaffs_dev *)data;
struct yaffs_linux_context *context = yaffs_dev_to_lc(dev);
unsigned long now = jiffies;
unsigned long next_dir_update = now;
unsigned long next_gc = now;
unsigned long expires;
unsigned int urgency;
int gc_result;
struct timer_list timer;
yaffs_trace(YAFFS_TRACE_BACKGROUND,
"yaffs_background starting for dev %p", (void *)dev);
set_freezable();
while (context->bg_running) {
yaffs_trace(YAFFS_TRACE_BACKGROUND, "yaffs_background");
if (kthread_should_stop())
break;
if (try_to_freeze())
continue;
yaffs_gross_lock(dev);
now = jiffies;
if (time_after(now, next_dir_update) && yaffs_bg_enable) {
yaffs_update_dirty_dirs(dev);
next_dir_update = now + HZ;
}
if (time_after(now, next_gc) && yaffs_bg_enable) {
if (!dev->is_checkpointed) {
urgency = yaffs_bg_gc_urgency(dev);
gc_result = yaffs_bg_gc(dev, urgency);
if (urgency > 1)
next_gc = now + HZ / 20 + 1;
else if (urgency > 0)
next_gc = now + HZ / 10 + 1;
else
next_gc = now + HZ * 2;
} else {
/*
* gc not running so set to next_dir_update
* to cut down on wake ups
*/
next_gc = next_dir_update;
}
}
yaffs_gross_unlock(dev);
expires = next_dir_update;
if (time_before(next_gc, expires))
expires = next_gc;
if (time_before(expires, now))
expires = now + HZ;
Y_INIT_TIMER(&timer);
timer.expires = expires + 1;
timer.data = (unsigned long)current;
timer.function = yaffs_background_waker;
set_current_state(TASK_INTERRUPTIBLE);
add_timer(&timer);
schedule();
del_timer_sync(&timer);
}
return 0;
}
static int yaffs_bg_start(struct yaffs_dev *dev)
{
int retval = 0;
struct yaffs_linux_context *context = yaffs_dev_to_lc(dev);
if (dev->read_only)
return -1;
context->bg_running = 1;
context->bg_thread = kthread_run(yaffs_bg_thread_fn,
(void *)dev, "yaffs-bg-%d",
context->mount_id);
if (IS_ERR(context->bg_thread)) {
retval = PTR_ERR(context->bg_thread);
context->bg_thread = NULL;
context->bg_running = 0;
}
return retval;
}
static void yaffs_bg_stop(struct yaffs_dev *dev)
{
struct yaffs_linux_context *ctxt = yaffs_dev_to_lc(dev);
ctxt->bg_running = 0;
if (ctxt->bg_thread) {
kthread_stop(ctxt->bg_thread);
ctxt->bg_thread = NULL;
}
}
static void yaffs_write_super(struct super_block *sb)
{
unsigned request_checkpoint = (yaffs_auto_checkpoint >= 2);
yaffs_trace(YAFFS_TRACE_OS | YAFFS_TRACE_SYNC | YAFFS_TRACE_BACKGROUND,
"yaffs_write_super%s",
request_checkpoint ? " checkpt" : "");
yaffs_do_sync_fs(sb, request_checkpoint);
}
static int yaffs_sync_fs(struct super_block *sb, int wait)
{
unsigned request_checkpoint = (yaffs_auto_checkpoint >= 1);
yaffs_trace(YAFFS_TRACE_OS | YAFFS_TRACE_SYNC,
"yaffs_sync_fs%s", request_checkpoint ? " checkpt" : "");
yaffs_do_sync_fs(sb, request_checkpoint);
return 0;
}
static LIST_HEAD(yaffs_context_list);
struct mutex yaffs_context_lock;
struct yaffs_options {
int inband_tags;
int skip_checkpoint_read;
int skip_checkpoint_write;
int no_cache;
int tags_ecc_on;
int tags_ecc_overridden;
int lazy_loading_enabled;
int lazy_loading_overridden;
int empty_lost_and_found;
int empty_lost_and_found_overridden;
};
#define MAX_OPT_LEN 30
static int yaffs_parse_options(struct yaffs_options *options,
const char *options_str)
{
char cur_opt[MAX_OPT_LEN + 1];
int p;
int error = 0;
/* Parse through the options which is a comma seperated list */
while (options_str && *options_str && !error) {
memset(cur_opt, 0, MAX_OPT_LEN + 1);
p = 0;
while (*options_str == ',')
options_str++;
while (*options_str && *options_str != ',') {
if (p < MAX_OPT_LEN) {
cur_opt[p] = *options_str;
p++;
}
options_str++;
}
if (!strcmp(cur_opt, "inband-tags")) {
options->inband_tags = 1;
} else if (!strcmp(cur_opt, "tags-ecc-off")) {
options->tags_ecc_on = 0;
options->tags_ecc_overridden = 1;
} else if (!strcmp(cur_opt, "tags-ecc-on")) {
options->tags_ecc_on = 1;
options->tags_ecc_overridden = 1;
} else if (!strcmp(cur_opt, "lazy-loading-off")) {
options->lazy_loading_enabled = 0;
options->lazy_loading_overridden = 1;
} else if (!strcmp(cur_opt, "lazy-loading-on")) {
options->lazy_loading_enabled = 1;
options->lazy_loading_overridden = 1;
} else if (!strcmp(cur_opt, "empty-lost-and-found-off")) {
options->empty_lost_and_found = 0;
options->empty_lost_and_found_overridden = 1;
} else if (!strcmp(cur_opt, "empty-lost-and-found-on")) {
options->empty_lost_and_found = 1;
options->empty_lost_and_found_overridden = 1;
} else if (!strcmp(cur_opt, "no-cache")) {
options->no_cache = 1;
} else if (!strcmp(cur_opt, "no-checkpoint-read")) {
options->skip_checkpoint_read = 1;
} else if (!strcmp(cur_opt, "no-checkpoint-write")) {
options->skip_checkpoint_write = 1;
} else if (!strcmp(cur_opt, "no-checkpoint")) {
options->skip_checkpoint_read = 1;
options->skip_checkpoint_write = 1;
} else {
printk(KERN_INFO "yaffs: Bad mount option \"%s\"\n",
cur_opt);
error = 1;
}
}
return error;
}
static struct address_space_operations yaffs_file_address_operations = {
.readpage = yaffs_readpage,
.writepage = yaffs_writepage,
.write_begin = yaffs_write_begin,
.write_end = yaffs_write_end,
};
static const struct inode_operations yaffs_file_inode_operations = {
.setattr = yaffs_setattr,
#ifdef CONFIG_YAFFS_XATTR
.setxattr = yaffs_setxattr,
.getxattr = yaffs_getxattr,
.listxattr = yaffs_listxattr,
.removexattr = yaffs_removexattr,
#endif
};
static const struct inode_operations yaffs_symlink_inode_operations = {
.readlink = yaffs_readlink,
.follow_link = yaffs_follow_link,
.put_link = yaffs_put_link,
.setattr = yaffs_setattr,
#ifdef CONFIG_YAFFS_XATTR
.setxattr = yaffs_setxattr,
.getxattr = yaffs_getxattr,
.listxattr = yaffs_listxattr,
.removexattr = yaffs_removexattr,
#endif
};
static void yaffs_fill_inode_from_obj(struct inode *inode,
struct yaffs_obj *obj)
{
if (inode && obj) {
/* Check mode against the variant type and attempt to repair if broken. */
u32 mode = obj->yst_mode;
switch (obj->variant_type) {
case YAFFS_OBJECT_TYPE_FILE:
if (!S_ISREG(mode)) {
obj->yst_mode &= ~S_IFMT;
obj->yst_mode |= S_IFREG;
}
break;
case YAFFS_OBJECT_TYPE_SYMLINK:
if (!S_ISLNK(mode)) {
obj->yst_mode &= ~S_IFMT;
obj->yst_mode |= S_IFLNK;
}
break;
case YAFFS_OBJECT_TYPE_DIRECTORY:
if (!S_ISDIR(mode)) {
obj->yst_mode &= ~S_IFMT;
obj->yst_mode |= S_IFDIR;
}
break;
case YAFFS_OBJECT_TYPE_UNKNOWN:
case YAFFS_OBJECT_TYPE_HARDLINK:
case YAFFS_OBJECT_TYPE_SPECIAL:
default:
/* TODO? */
break;
}
inode->i_flags |= S_NOATIME;
inode->i_ino = obj->obj_id;
inode->i_mode = obj->yst_mode;
inode->i_uid = obj->yst_uid;
inode->i_gid = obj->yst_gid;
inode->i_rdev = old_decode_dev(obj->yst_rdev);
inode->i_atime.tv_sec = (time_t) (obj->yst_atime);
inode->i_atime.tv_nsec = 0;
inode->i_mtime.tv_sec = (time_t) obj->yst_mtime;
inode->i_mtime.tv_nsec = 0;
inode->i_ctime.tv_sec = (time_t) obj->yst_ctime;
inode->i_ctime.tv_nsec = 0;
inode->i_size = yaffs_get_obj_length(obj);
inode->i_blocks = (inode->i_size + 511) >> 9;
inode->__i_nlink = yaffs_get_obj_link_count(obj);
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_fill_inode mode %x uid %d gid %d size %d count %d",
inode->i_mode, inode->i_uid, inode->i_gid,
(int)inode->i_size, atomic_read(&inode->i_count));
switch (obj->yst_mode & S_IFMT) {
default: /* fifo, device or socket */
init_special_inode(inode, obj->yst_mode,
old_decode_dev(obj->yst_rdev));
break;
case S_IFREG: /* file */
inode->i_op = &yaffs_file_inode_operations;
inode->i_fop = &yaffs_file_operations;
inode->i_mapping->a_ops =
&yaffs_file_address_operations;
break;
case S_IFDIR: /* directory */
inode->i_op = &yaffs_dir_inode_operations;
inode->i_fop = &yaffs_dir_operations;
break;
case S_IFLNK: /* symlink */
inode->i_op = &yaffs_symlink_inode_operations;
break;
}
yaffs_inode_to_obj_lv(inode) = obj;
obj->my_inode = inode;
} else {
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_fill_inode invalid parameters");
}
}
static void yaffs_put_super(struct super_block *sb)
{
struct yaffs_dev *dev = yaffs_super_to_dev(sb);
yaffs_trace(YAFFS_TRACE_OS, "yaffs_put_super");
yaffs_trace(YAFFS_TRACE_OS | YAFFS_TRACE_BACKGROUND,
"Shutting down yaffs background thread");
yaffs_bg_stop(dev);
yaffs_trace(YAFFS_TRACE_OS | YAFFS_TRACE_BACKGROUND,
"yaffs background thread shut down");
yaffs_gross_lock(dev);
yaffs_flush_super(sb, 1);
if (yaffs_dev_to_lc(dev)->put_super_fn)
yaffs_dev_to_lc(dev)->put_super_fn(sb);
yaffs_deinitialise(dev);
yaffs_gross_unlock(dev);
mutex_lock(&yaffs_context_lock);
list_del_init(&(yaffs_dev_to_lc(dev)->context_list));
mutex_unlock(&yaffs_context_lock);
if (yaffs_dev_to_lc(dev)->spare_buffer) {
kfree(yaffs_dev_to_lc(dev)->spare_buffer);
yaffs_dev_to_lc(dev)->spare_buffer = NULL;
}
kfree(dev);
}
static void yaffs_mtd_put_super(struct super_block *sb)
{
struct mtd_info *mtd = yaffs_dev_to_mtd(yaffs_super_to_dev(sb));
mtd_sync(mtd);
put_mtd_device(mtd);
}
static const struct super_operations yaffs_super_ops = {
.statfs = yaffs_statfs,
.put_super = yaffs_put_super,
.evict_inode = yaffs_evict_inode,
.sync_fs = yaffs_sync_fs,
.write_super = yaffs_write_super,
};
static struct super_block *yaffs_internal_read_super(int yaffs_version,
struct super_block *sb,
void *data, int silent)
{
int n_blocks;
struct inode *inode = NULL;
struct dentry *root;
struct yaffs_dev *dev = 0;
char devname_buf[BDEVNAME_SIZE + 1];
struct mtd_info *mtd;
int err;
char *data_str = (char *)data;
struct yaffs_linux_context *context = NULL;
struct yaffs_param *param;
int yaffs_mvg_test_debug_mode = 0;
int read_only = 0;
struct yaffs_options options;
unsigned mount_id;
int found;
struct yaffs_linux_context *context_iterator;
struct list_head *l;
sb->s_magic = YAFFS_MAGIC;
sb->s_op = &yaffs_super_ops;
sb->s_flags |= MS_NOATIME;
read_only = ((sb->s_flags & MS_RDONLY) != 0);
sb->s_export_op = &yaffs_export_ops;
if (!sb)
printk(KERN_INFO "yaffs: sb is NULL\n");
else if (!sb->s_dev)
printk(KERN_INFO "yaffs: sb->s_dev is NULL\n");
else if (!yaffs_devname(sb, devname_buf))
printk(KERN_INFO "yaffs: devname is NULL\n");
else
printk(KERN_INFO "yaffs: dev is %d name is \"%s\" %s\n",
sb->s_dev,
yaffs_devname(sb, devname_buf), read_only ? "ro" : "rw");
if (!data_str)
data_str = "";
printk(KERN_INFO "yaffs: passed flags \"%s\"\n", data_str);
memset(&options, 0, sizeof(options));
if (yaffs_parse_options(&options, data_str)) {
/* Option parsing failed */
return NULL;
}
sb->s_blocksize = PAGE_CACHE_SIZE;
sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
printk("[yaffs_read_super]sb maxbytes %llx",sb->s_maxbytes);
sb->s_maxbytes = 1LL<<32;
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_read_super: Using yaffs%d", yaffs_version);
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_read_super: block size %d", (int)(sb->s_blocksize));
#ifdef YAFFS_MVG_TEST_DEBUG_LOG
yaffs_mvg_test_debug_mode |= 0x1;
#endif
#ifdef YAFFS_MVG_TEST_DUMP_SCAN_SEQ //dump seq num in yaffs2_ScanBackwards
yaffs_mvg_test_debug_mode |= 0x2;
#endif
#ifdef YAFFS_MVG_TEST_ERASECHEKFF //when erase block,check if or not the block becomes 0xff
yaffs_mvg_test_debug_mode |= 0x4;
#endif
#ifdef YAFFS_MVG_TEST_DEBUG_WRITECHECK //check 0xff ,before write every chunk .
yaffs_mvg_test_debug_mode |= 0x8;
#endif
#ifdef YAFFS_MVG_TEST_DEBUG_WRITEHECK_FIXERROR //fixerror when chunk is not ,before write every chunk .
yaffs_mvg_test_debug_mode |= 0x10;
#endif
yaffs_trace(YAFFS_TRACE_ALWAYS,
"Attempting MTD mount of %u.%u,\"%s\" debug_mode:0x%x\n",
MAJOR(sb->s_dev), MINOR(sb->s_dev),
yaffs_devname(sb, devname_buf),yaffs_mvg_test_debug_mode);
/* Check it's an mtd device..... */
if (MAJOR(sb->s_dev) != MTD_BLOCK_MAJOR)
return NULL; /* This isn't an mtd device */
/* Get the device */
mtd = get_mtd_device(NULL, MINOR(sb->s_dev));
if (!mtd) {
yaffs_trace(YAFFS_TRACE_ALWAYS,
"MTD device #%u doesn't appear to exist",
MINOR(sb->s_dev));
return NULL;
}
/* Check it's NAND */
if (mtd->type != MTD_NANDFLASH) {
yaffs_trace(YAFFS_TRACE_ALWAYS,
"MTD device is not NAND it's type %d",
mtd->type);
return NULL;
}
yaffs_trace(YAFFS_TRACE_OS, " erase %p", mtd->_erase);
yaffs_trace(YAFFS_TRACE_OS, " read %p", mtd->_read);
yaffs_trace(YAFFS_TRACE_OS, " write %p", mtd->_write);
yaffs_trace(YAFFS_TRACE_OS, " readoob %p", mtd->_read_oob);
yaffs_trace(YAFFS_TRACE_OS, " writeoob %p", mtd->_write_oob);
yaffs_trace(YAFFS_TRACE_OS, " block_isbad %p", mtd->_block_isbad);
yaffs_trace(YAFFS_TRACE_OS, " block_markbad %p", mtd->_block_markbad);
yaffs_trace(YAFFS_TRACE_OS, " %s %d", WRITE_SIZE_STR, WRITE_SIZE(mtd));
yaffs_trace(YAFFS_TRACE_OS, " oobsize %d", mtd->oobsize);
yaffs_trace(YAFFS_TRACE_OS, " erasesize %d", mtd->erasesize);
yaffs_trace(YAFFS_TRACE_OS, " size %lld", mtd->size);
#ifdef CONFIG_YAFFS_AUTO_YAFFS2
if (yaffs_version == 1 && WRITE_SIZE(mtd) >= 2048) {
yaffs_trace(YAFFS_TRACE_ALWAYS, "auto selecting yaffs2");
yaffs_version = 2;
}
/* Added NCB 26/5/2006 for completeness */
if (yaffs_version == 2 && !options.inband_tags
&& WRITE_SIZE(mtd) == 512) {
yaffs_trace(YAFFS_TRACE_ALWAYS, "auto selecting yaffs1");
yaffs_version = 1;
}
#endif
if (yaffs_version == 2) {
/* Check for version 2 style functions */
if (!mtd->_erase ||
!mtd->_block_isbad ||
!mtd->_block_markbad ||
!mtd->_read ||
!mtd->_write || !mtd->_read_oob || !mtd->_write_oob) {
yaffs_trace(YAFFS_TRACE_ALWAYS,
"MTD device does not support required functions");
return NULL;
}
if ((WRITE_SIZE(mtd) < YAFFS_MIN_YAFFS2_CHUNK_SIZE ||
mtd->oobsize < YAFFS_MIN_YAFFS2_SPARE_SIZE) &&
!options.inband_tags) {
yaffs_trace(YAFFS_TRACE_ALWAYS,
"MTD device does not have the right page sizes");
return NULL;
}
} else {
/* Check for V1 style functions */
if (!mtd->_erase ||
!mtd->_read ||
!mtd->_write || !mtd->_read_oob || !mtd->_write_oob) {
yaffs_trace(YAFFS_TRACE_ALWAYS,
"MTD device does not support required functions");
return NULL;
}
if (WRITE_SIZE(mtd) < YAFFS_BYTES_PER_CHUNK ||
mtd->oobsize != YAFFS_BYTES_PER_SPARE) {
yaffs_trace(YAFFS_TRACE_ALWAYS,
"MTD device does not support have the right page sizes");
return NULL;
}
}
/* OK, so if we got here, we have an MTD that's NAND and looks
* like it has the right capabilities
* Set the struct yaffs_dev up for mtd
*/
if (!read_only && !(mtd->flags & MTD_WRITEABLE)) {
read_only = 1;
printk(KERN_INFO
"yaffs: mtd is read only, setting superblock read only");
sb->s_flags |= MS_RDONLY;
}
dev = kmalloc(sizeof(struct yaffs_dev), GFP_KERNEL);
context = kmalloc(sizeof(struct yaffs_linux_context), GFP_KERNEL);
if (!dev || !context) {
if (dev)
kfree(dev);
if (context)
kfree(context);
dev = NULL;
context = NULL;
}
if (!dev) {
/* Deep shit could not allocate device structure */
yaffs_trace(YAFFS_TRACE_ALWAYS,
"yaffs_read_super failed trying to allocate yaffs_dev");
return NULL;
}
memset(dev, 0, sizeof(struct yaffs_dev));
param = &(dev->param);
memset(context, 0, sizeof(struct yaffs_linux_context));
dev->os_context = context;
INIT_LIST_HEAD(&(context->context_list));
context->dev = dev;
context->super = sb;
dev->read_only = read_only;
sb->s_fs_info = dev;
dev->driver_context = mtd;
param->name = mtd->name;
/* Set up the memory size parameters.... */
n_blocks =
YCALCBLOCKS(mtd->size,
(YAFFS_CHUNKS_PER_BLOCK * YAFFS_BYTES_PER_CHUNK));
param->start_block = 0;
param->end_block = n_blocks - 1;
param->chunks_per_block = YAFFS_CHUNKS_PER_BLOCK;
param->total_bytes_per_chunk = YAFFS_BYTES_PER_CHUNK;
param->n_reserved_blocks = 5;
param->n_caches = (options.no_cache) ? 0 : 10;
param->inband_tags = options.inband_tags;
#ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
param->disable_lazy_load = 1;
#endif
#ifdef CONFIG_YAFFS_XATTR
param->enable_xattr = 1;
#endif
if (options.lazy_loading_overridden)
param->disable_lazy_load = !options.lazy_loading_enabled;
#ifdef CONFIG_YAFFS_DISABLE_TAGS_ECC
param->no_tags_ecc = 1;
#endif
#ifdef CONFIG_YAFFS_DISABLE_BACKGROUND
#else
param->defered_dir_update = 1;
#endif
if (options.tags_ecc_overridden)
param->no_tags_ecc = !options.tags_ecc_on;
#ifdef CONFIG_YAFFS_EMPTY_LOST_AND_FOUND
param->empty_lost_n_found = 1;
#endif
#ifdef CONFIG_YAFFS_DISABLE_BLOCK_REFRESHING
param->refresh_period = 0;
#else
param->refresh_period = 500;
#endif
#ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
param->always_check_erased = 1;
#endif
if (options.empty_lost_and_found_overridden)
param->empty_lost_n_found = options.empty_lost_and_found;
/* ... and the functions. */
if (yaffs_version == 2) {
param->write_chunk_tags_fn = nandmtd2_write_chunk_tags;
param->read_chunk_tags_fn = nandmtd2_read_chunk_tags;
param->bad_block_fn = nandmtd2_mark_block_bad;
param->query_block_fn = nandmtd2_query_block;
yaffs_dev_to_lc(dev)->spare_buffer =
kmalloc(mtd->oobsize, GFP_NOFS);
param->is_yaffs2 = 1;
param->total_bytes_per_chunk = mtd->writesize;
param->chunks_per_block = mtd->erasesize / mtd->writesize;
n_blocks = YCALCBLOCKS(mtd->size, mtd->erasesize);
param->start_block = 0;
param->end_block = n_blocks - 1;
} else {
/* use the MTD interface in yaffs_mtdif1.c */
param->write_chunk_tags_fn = nandmtd1_write_chunk_tags;
param->read_chunk_tags_fn = nandmtd1_read_chunk_tags;
param->bad_block_fn = nandmtd1_mark_block_bad;
param->query_block_fn = nandmtd1_query_block;
param->is_yaffs2 = 0;
}
/* ... and common functions */
param->erase_fn = nandmtd_erase_block;
param->initialise_flash_fn = nandmtd_initialise;
yaffs_dev_to_lc(dev)->put_super_fn = yaffs_mtd_put_super;
param->sb_dirty_fn = yaffs_touch_super;
param->gc_control = yaffs_gc_control_callback;
yaffs_dev_to_lc(dev)->super = sb;
#ifndef CONFIG_YAFFS_DOES_ECC
param->use_nand_ecc = 1;
#endif
param->skip_checkpt_rd = options.skip_checkpoint_read;
param->skip_checkpt_wr = options.skip_checkpoint_write;
mutex_lock(&yaffs_context_lock);
/* Get a mount id */
found = 0;
for (mount_id = 0; !found; mount_id++) {
found = 1;
list_for_each(l, &yaffs_context_list) {
context_iterator =
list_entry(l, struct yaffs_linux_context,
context_list);
if (context_iterator->mount_id == mount_id)
found = 0;
}
}
context->mount_id = mount_id;
list_add_tail(&(yaffs_dev_to_lc(dev)->context_list),
&yaffs_context_list);
mutex_unlock(&yaffs_context_lock);
/* Directory search handling... */
INIT_LIST_HEAD(&(yaffs_dev_to_lc(dev)->search_contexts));
param->remove_obj_fn = yaffs_remove_obj_callback;
mutex_init(&(yaffs_dev_to_lc(dev)->gross_lock));
yaffs_gross_lock(dev);
err = yaffs_guts_initialise(dev);
yaffs_trace(YAFFS_TRACE_OS,
"yaffs_read_super: guts initialised %s",
(err == YAFFS_OK) ? "OK" : "FAILED");
if (err == YAFFS_OK)
yaffs_bg_start(dev);
if (!context->bg_thread)
param->defered_dir_update = 0;
/* Release lock before yaffs_get_inode() */
yaffs_gross_unlock(dev);
/* Create root inode */
if (err == YAFFS_OK)
inode = yaffs_get_inode(sb, S_IFDIR | 0755, 0, yaffs_root(dev));
if (!inode)
return NULL;
inode->i_op = &yaffs_dir_inode_operations;
inode->i_fop = &yaffs_dir_operations;
yaffs_trace(YAFFS_TRACE_OS, "yaffs_read_super: got root inode");
root = d_make_root(inode);
yaffs_trace(YAFFS_TRACE_OS, "yaffs_read_super: d_alloc_root done");
if (!root) {
iput(inode);
return NULL;
}
sb->s_root = root;
sb->s_dirt = !dev->is_checkpointed;
yaffs_trace(YAFFS_TRACE_ALWAYS,
"yaffs_read_super: is_checkpointed %d",
dev->is_checkpointed);
yaffs_trace(YAFFS_TRACE_OS, "yaffs_read_super: done");
return sb;
}
static int yaffs_internal_read_super_mtd(struct super_block *sb, void *data,
int silent)
{
return yaffs_internal_read_super(1, sb, data, silent) ? 0 : -EINVAL;
}
static struct dentry *yaffs_read_super(struct file_system_type *fs,
int flags, const char *dev_name,
void *data)
{
return mount_bdev(fs, flags, dev_name, data,
yaffs_internal_read_super_mtd);
}
static struct file_system_type yaffs_fs_type = {
.owner = THIS_MODULE,
.name = "yaffs",
.mount = yaffs_read_super,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
#ifdef CONFIG_YAFFS_YAFFS2
static int yaffs2_internal_read_super_mtd(struct super_block *sb, void *data,
int silent)
{
return yaffs_internal_read_super(2, sb, data, silent) ? 0 : -EINVAL;
}
static struct dentry *yaffs2_read_super(struct file_system_type *fs,
int flags, const char *dev_name, void *data)
{
return mount_bdev(fs, flags, dev_name, data,
yaffs2_internal_read_super_mtd);
}
static struct file_system_type yaffs2_fs_type = {
.owner = THIS_MODULE,
.name = "yaffs2",
.mount = yaffs2_read_super,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
#endif /* CONFIG_YAFFS_YAFFS2 */
static struct proc_dir_entry *my_proc_entry;
static char *yaffs_dump_dev_part0(char *buf, struct yaffs_dev *dev)
{
struct yaffs_param *param = &dev->param;
buf += sprintf(buf, "start_block........... %d\n", param->start_block);
buf += sprintf(buf, "end_block............. %d\n", param->end_block);
buf += sprintf(buf, "total_bytes_per_chunk. %d\n",
param->total_bytes_per_chunk);
buf += sprintf(buf, "use_nand_ecc.......... %d\n",
param->use_nand_ecc);
buf += sprintf(buf, "no_tags_ecc........... %d\n", param->no_tags_ecc);
buf += sprintf(buf, "is_yaffs2............. %d\n", param->is_yaffs2);
buf += sprintf(buf, "inband_tags........... %d\n", param->inband_tags);
buf += sprintf(buf, "empty_lost_n_found.... %d\n",
param->empty_lost_n_found);
buf += sprintf(buf, "disable_lazy_load..... %d\n",
param->disable_lazy_load);
buf += sprintf(buf, "refresh_period........ %d\n",
param->refresh_period);
buf += sprintf(buf, "n_caches.............. %d\n", param->n_caches);
buf += sprintf(buf, "n_reserved_blocks..... %d\n",
param->n_reserved_blocks);
buf += sprintf(buf, "always_check_erased... %d\n",
param->always_check_erased);
return buf;
}
static char *yaffs_dump_dev_part1(char *buf, struct yaffs_dev *dev)
{
buf +=
sprintf(buf, "data_bytes_per_chunk.. %d\n",
dev->data_bytes_per_chunk);
buf += sprintf(buf, "chunk_grp_bits........ %d\n", dev->chunk_grp_bits);
buf += sprintf(buf, "chunk_grp_size........ %d\n", dev->chunk_grp_size);
buf +=
sprintf(buf, "n_erased_blocks....... %d\n", dev->n_erased_blocks);
buf +=
sprintf(buf, "blocks_in_checkpt..... %d\n", dev->blocks_in_checkpt);
buf += sprintf(buf, "\n");
buf += sprintf(buf, "n_tnodes.............. %d\n", dev->n_tnodes);
buf += sprintf(buf, "n_obj................. %d\n", dev->n_obj);
buf += sprintf(buf, "n_free_chunks......... %d\n", dev->n_free_chunks);
buf += sprintf(buf, "\n");
buf += sprintf(buf, "n_page_writes......... %u\n", dev->n_page_writes);
buf += sprintf(buf, "n_page_reads.......... %u\n", dev->n_page_reads);
buf += sprintf(buf, "n_erasures............ %u\n", dev->n_erasures);
buf += sprintf(buf, "n_gc_copies........... %u\n", dev->n_gc_copies);
buf += sprintf(buf, "all_gcs............... %u\n", dev->all_gcs);
buf +=
sprintf(buf, "passive_gc_count...... %u\n", dev->passive_gc_count);
buf +=
sprintf(buf, "oldest_dirty_gc_count. %u\n",
dev->oldest_dirty_gc_count);
buf += sprintf(buf, "n_gc_blocks........... %u\n", dev->n_gc_blocks);
buf += sprintf(buf, "bg_gcs................ %u\n", dev->bg_gcs);
buf +=
sprintf(buf, "n_retired_writes...... %u\n", dev->n_retired_writes);
buf +=
sprintf(buf, "n_retired_blocks...... %u\n", dev->n_retired_blocks);
buf += sprintf(buf, "n_ecc_fixed........... %u\n", dev->n_ecc_fixed);
buf += sprintf(buf, "n_ecc_unfixed......... %u\n", dev->n_ecc_unfixed);
buf +=
sprintf(buf, "n_tags_ecc_fixed...... %u\n", dev->n_tags_ecc_fixed);
buf +=
sprintf(buf, "n_tags_ecc_unfixed.... %u\n",
dev->n_tags_ecc_unfixed);
buf += sprintf(buf, "cache_hits............ %u\n", dev->cache_hits);
buf +=
sprintf(buf, "n_deleted_files....... %u\n", dev->n_deleted_files);
buf +=
sprintf(buf, "n_unlinked_files...... %u\n", dev->n_unlinked_files);
buf += sprintf(buf, "refresh_count......... %u\n", dev->refresh_count);
buf += sprintf(buf, "n_bg_deletions........ %u\n", dev->n_bg_deletions);
return buf;
}
static int yaffs_proc_read(char *page,
char **start,
off_t offset, int count, int *eof, void *data)
{
struct list_head *item;
char *buf = page;
int step = offset;
int n = 0;
/* Get proc_file_read() to step 'offset' by one on each sucessive call.
* We use 'offset' (*ppos) to indicate where we are in dev_list.
* This also assumes the user has posted a read buffer large
* enough to hold the complete output; but that's life in /proc.
*/
*(int *)start = 1;
/* Print header first */
if (step == 0)
buf += sprintf(buf, "YAFFS built:" __DATE__ " " __TIME__ "\n");
else if (step == 1)
buf += sprintf(buf, "\n");
else {
step -= 2;
mutex_lock(&yaffs_context_lock);
/* Locate and print the Nth entry. Order N-squared but N is small. */
list_for_each(item, &yaffs_context_list) {
struct yaffs_linux_context *dc =
list_entry(item, struct yaffs_linux_context,
context_list);
struct yaffs_dev *dev = dc->dev;
if (n < (step & ~1)) {
n += 2;
continue;
}
if ((step & 1) == 0) {
buf +=
sprintf(buf, "\nDevice %d \"%s\"\n", n,
dev->param.name);
buf = yaffs_dump_dev_part0(buf, dev);
} else {
buf = yaffs_dump_dev_part1(buf, dev);
}
break;
}
mutex_unlock(&yaffs_context_lock);
}
return buf - page < count ? buf - page : count;
}
/**
* Set the verbosity of the warnings and error messages.
*
* Note that the names can only be a..z or _ with the current code.
*/
static struct {
char *mask_name;
unsigned mask_bitfield;
} mask_flags[] = {
{"allocate", YAFFS_TRACE_ALLOCATE},
{"always", YAFFS_TRACE_ALWAYS},
{"background", YAFFS_TRACE_BACKGROUND},
{"bad_blocks", YAFFS_TRACE_BAD_BLOCKS},
{"buffers", YAFFS_TRACE_BUFFERS},
{"bug", YAFFS_TRACE_BUG},
{"checkpt", YAFFS_TRACE_CHECKPOINT},
{"deletion", YAFFS_TRACE_DELETION},
{"erase", YAFFS_TRACE_ERASE},
{"error", YAFFS_TRACE_ERROR},
{"gc_detail", YAFFS_TRACE_GC_DETAIL},
{"gc", YAFFS_TRACE_GC},
{"lock", YAFFS_TRACE_LOCK},
{"mtd", YAFFS_TRACE_MTD},
{"nandaccess", YAFFS_TRACE_NANDACCESS},
{"os", YAFFS_TRACE_OS},
{"scan_debug", YAFFS_TRACE_SCAN_DEBUG},
{"scan", YAFFS_TRACE_SCAN},
{"mount", YAFFS_TRACE_MOUNT},
{"tracing", YAFFS_TRACE_TRACING},
{"sync", YAFFS_TRACE_SYNC},
{"write", YAFFS_TRACE_WRITE},
{"verify", YAFFS_TRACE_VERIFY},
{"verify_nand", YAFFS_TRACE_VERIFY_NAND},
{"verify_full", YAFFS_TRACE_VERIFY_FULL},
{"verify_all", YAFFS_TRACE_VERIFY_ALL},
{"all", 0xffffffff},
{"none", 0},
{NULL, 0},
};
#define MAX_MASK_NAME_LENGTH 40
static int yaffs_proc_write_trace_options(struct file *file, const char *buf,
unsigned long count, void *data)
{
unsigned rg = 0, mask_bitfield;
char *end;
char *mask_name;
const char *x;
char substring[MAX_MASK_NAME_LENGTH + 1];
int i;
int done = 0;
int add, len = 0;
int pos = 0;
rg = yaffs_trace_mask;
while (!done && (pos < count)) {
done = 1;
while ((pos < count) && isspace(buf[pos]))
pos++;
switch (buf[pos]) {
case '+':
case '-':
case '=':
add = buf[pos];
pos++;
break;
default:
add = ' ';
break;
}
mask_name = NULL;
mask_bitfield = simple_strtoul(buf + pos, &end, 0);
if (end > buf + pos) {
mask_name = "numeral";
len = end - (buf + pos);
pos += len;
done = 0;
} else {
for (x = buf + pos, i = 0;
(*x == '_' || (*x >= 'a' && *x <= 'z')) &&
i < MAX_MASK_NAME_LENGTH; x++, i++, pos++)
substring[i] = *x;
substring[i] = '\0';
for (i = 0; mask_flags[i].mask_name != NULL; i++) {
if (strcmp(substring, mask_flags[i].mask_name)
== 0) {
mask_name = mask_flags[i].mask_name;
mask_bitfield =
mask_flags[i].mask_bitfield;
done = 0;
break;
}
}
}
if (mask_name != NULL) {
done = 0;
switch (add) {
case '-':
rg &= ~mask_bitfield;
break;
case '+':
rg |= mask_bitfield;
break;
case '=':
rg = mask_bitfield;
break;
default:
rg |= mask_bitfield;
break;
}
}
}
yaffs_trace_mask = rg | YAFFS_TRACE_ALWAYS;
printk(KERN_DEBUG "new trace = 0x%08X\n", yaffs_trace_mask);
if (rg & YAFFS_TRACE_ALWAYS) {
for (i = 0; mask_flags[i].mask_name != NULL; i++) {
char flag;
flag = ((rg & mask_flags[i].mask_bitfield) ==
mask_flags[i].mask_bitfield) ? '+' : '-';
printk(KERN_DEBUG "%c%s\n", flag,
mask_flags[i].mask_name);
}
}
return count;
}
static int yaffs_proc_write(struct file *file, const char *buf,
unsigned long count, void *data)
{
return yaffs_proc_write_trace_options(file, buf, count, data);
}
/* Stuff to handle installation of file systems */
struct file_system_to_install {
struct file_system_type *fst;
int installed;
};
static struct file_system_to_install fs_to_install[] = {
{&yaffs_fs_type, 0},
{&yaffs2_fs_type, 0},
{NULL, 0}
};
static int __init init_yaffs_fs(void)
{
int error = 0;
struct file_system_to_install *fsinst;
yaffs_trace(YAFFS_TRACE_ALWAYS,
"yaffs built " __DATE__ " " __TIME__ " Installing.");
#ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
yaffs_trace(YAFFS_TRACE_ALWAYS,
"\n\nYAFFS-WARNING CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED selected.\n\n\n");
#endif
mutex_init(&yaffs_context_lock);
/* Install the proc_fs entries */
my_proc_entry = create_proc_entry("yaffs",
S_IRUGO | S_IFREG, YPROC_ROOT);
if (my_proc_entry) {
my_proc_entry->write_proc = yaffs_proc_write;
my_proc_entry->read_proc = yaffs_proc_read;
my_proc_entry->data = NULL;
} else {
return -ENOMEM;
}
/* Now add the file system entries */
fsinst = fs_to_install;
while (fsinst->fst && !error) {
error = register_filesystem(fsinst->fst);
if (!error)
fsinst->installed = 1;
fsinst++;
}
/* Any errors? uninstall */
if (error) {
fsinst = fs_to_install;
while (fsinst->fst) {
if (fsinst->installed) {
unregister_filesystem(fsinst->fst);
fsinst->installed = 0;
}
fsinst++;
}
}
return error;
}
static void __exit exit_yaffs_fs(void)
{
struct file_system_to_install *fsinst;
yaffs_trace(YAFFS_TRACE_ALWAYS,
"yaffs built " __DATE__ " " __TIME__ " removing.");
remove_proc_entry("yaffs", YPROC_ROOT);
fsinst = fs_to_install;
while (fsinst->fst) {
if (fsinst->installed) {
unregister_filesystem(fsinst->fst);
fsinst->installed = 0;
}
fsinst++;
}
}
module_init(init_yaffs_fs)
module_exit(exit_yaffs_fs)
MODULE_DESCRIPTION("YAFFS2 - a NAND specific flash file system");
MODULE_AUTHOR("Charles Manning, Aleph One Ltd., 2002-2010");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Mouseomics/R | src/extra/graphapp/events.c | 38 | 29425 | /*
* GraphApp - Cross-Platform Graphics Programming Library.
*
* File: events.c -- winprocs and timers are contained here.
* Platform: Windows Version: 2.35 Date: 1998/04/04
*
* Version: 1.00 Changes: Original version by Lachlan Patrick.
* Version: 2.00 Changes: New class system implemented.
* Version: 2.20 Changes: Non-native buttons supported.
* Version: 2.22 Changes: 32-bit fix by Wim Rijnders.
* Version: 2.35 Changes: New delayed deletion technique.
*/
/* Copyright (C) 1993-1998 Lachlan Patrick
This file is part of GraphApp, a cross-platform C graphics library.
GraphApp is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License.
GraphApp is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY.
See the file COPYLIB.TXT for details.
*/
/* Copyright (C) 2004, 2009 The R Foundation
Copyright (C) 2013 The R Core Team
Changes for R, Chris Jackson, 2004
Handle find-and-replace modeless dialogs
Menu shortcut keys re-enabled
Handle WM_CONTEXTMENU events for right-clicking on a (rich) edit control
Handle mouse wheel scrolling
Remove assumption that current->dest is non-NULL
Add waitevent() function
*/
#include "internal.h"
/*
* Library variables.
*/
static timerfn do_timer = NULL;
static void *timer_data = NULL;
static MSG msg;
PROTECTED int keystate = 0; /* state of shift, ctrl and alt keys */
/* a user-timer and a mouse-down timer function can be started */
static UINT timer_id = 0;
static UINT mouse_timer_id = 0;
/* buttons and xy are used to record the state of the mouse */
static int buttons = 0;
static point xy;
static long mouse_msec = 0;
TIMERPROC app_timer_proc;
WNDPROC app_control_proc;
static object frontwindow = NULL; /* the window receiving events */
static UINT uFindReplaceMsg; // message identifier for FINDMSGSTRING
/* Surrogate Pairs MACRO */
#define SURROGATE_PAIRS_HI_MIN ((uint16_t)0xd800)
#define SURROGATE_PAIRS_HI_MAX ((uint16_t)0xdbff)
#define SURROGATE_PAIRS_LO_MIN ((uint16_t)0xdc00)
#define SURROGATE_PAIRS_LO_MAX ((uint16_t)0xdfff)
#define SURROGATE_PAIRS_BIT_SZ ((uint32_t)10)
#define SURROGATE_PAIRS_MASK (((uint16_t)1 << SURROGATE_PAIRS_BIT_SZ)-1)
#define IsSurrogatePairsHi(_h) (SURROGATE_PAIRS_HI_MIN == \
((uint16_t)(_h) &~ (uint16_t)SURROGATE_PAIRS_MASK ))
#define IsSurrogatePairsLo(_l) (SURROGATE_PAIRS_LO_MIN == \
((uint16_t)(_l) &~ (uint16_t)SURROGATE_PAIRS_MASK ))
/*
* Call the relevent mouse handler function.
*/
static void handle_mouse(object obj, HWND hwnd, UINT message,
int param, int x, int y)
{
menu m;
POINT wp;
HWND hw;
int dble = 1;
xy.x = x;
xy.y = y;
buttons = 0;
if (!obj) return;
if (param & MK_LBUTTON)
buttons |= LeftButton;
if (param & MK_MBUTTON)
buttons |= MiddleButton;
if (param & MK_RBUTTON)
buttons |= RightButton;
/* dispatch the mouse event to the relevent handler */
if (obj && obj->drawstate && obj->drawstate->crsr)
SetCursor((HCURSOR)obj->drawstate->crsr->handle);
switch (message)
{
case WM_MOUSEMOVE:
if (obj->call) {
if (buttons) {
if (obj->call->mousedrag)
obj->call->mousedrag(obj, buttons, xy);
}
else if (obj->call->mousemove)
obj->call->mousemove(obj, buttons, xy);
}
break;
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN:
dble = 0;
setmousetimer(mouse_msec); /* restart timer */
/* fall through to next case */
case WM_LBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
case WM_MBUTTONDBLCLK:
if (dble) buttons |= DblClick;
if ((obj->flags & ChildWindow) && (obj->kind != LabelObject))
SetFocus(hwnd);
if (obj->flags & TrackMouse)
SetCapture(hwnd);
if (buttons == RightButton) {
m = obj->popup; hw = hwnd;
if (!m) {
m = obj->parent->popup;
hw = (HWND) obj->parent->handle;
}
if (m) {
wp.x = x; wp.y = y;
ClientToScreen(hw, (LPPOINT) &wp);
if (m->action) m->action(m);
TrackPopupMenu(m->handle,
TPM_LEFTALIGN|
TPM_LEFTBUTTON|TPM_RIGHTBUTTON,
wp.x,wp.y,
0,
obj->handle,
NULL);
break;
}
}
if (obj->call && obj->call->mousedown)
obj->call->mousedown(obj, buttons, xy);
break;
case WM_LBUTTONUP:
case WM_RBUTTONUP:
case WM_MBUTTONUP:
if ((obj->flags & TrackMouse) && (buttons == 0))
ReleaseCapture();
if (obj->call && obj->call->mouseup)
obj->call->mouseup(obj, buttons, xy);
break;
}
}
/*
* Some WM_KEYDOWN VK_* messages call the keyaction associated
* with a window.
*/
static void handle_virtual_keydown(object obj, int param)
{
if ((! obj->call) || (! obj->call->keyaction))
return;
/* translate arrow key combinations into Unicode arrow symbols */
if ((param >= VK_LEFT) && (param <= VK_DOWN)) {
param += (LEFT - VK_LEFT);
}
/* translate functions keys into Unicode circled numbers */
else if ((param >= VK_F1) && (param <= VK_F10)) {
param += (F1 - VK_F1);
}
/* translate other keyboard keys into Unicode 'equivalents' */
else switch (param) {
case VK_PRIOR: param = PGUP; break;
case VK_NEXT: param = PGDN; break;
case VK_END: param = END; break;
case VK_HOME: param = HOME; break;
case VK_INSERT: param = INS; break;
case VK_DELETE: param = DEL; break;
default: return; /* do nothing */
}
drawto(obj);
obj->call->keyaction(obj, param);
}
static void handle_keydown(int param)
{
if (param == VK_SHIFT)
keystate |= ShiftKey;
else if (param == VK_CONTROL)
keystate |= CtrlKey;
else if (param == VK_MENU)
keystate |= AltKey;
}
static void handle_keyup(int param)
{
if (param == VK_SHIFT)
keystate &= ~ShiftKey;
else if (param == VK_CONTROL)
keystate &= ~CtrlKey;
else if (param == VK_MENU)
keystate &= ~AltKey;
}
/*
* Handle char messages.
*/
static void handle_char(object obj, int ch)
{
if (obj->call && obj->call->keydown) {
if (ch == '\r') /* carriage return becomes newline */
ch = '\n';
drawto(obj);
obj->call->keydown(obj, ch);
}
}
static int showMDIToolbar = 1;
void toolbar_show(void)
{
showMDIToolbar = 1;
SendMessage(hwndFrame,WM_PAINT, (WPARAM) 0, (LPARAM) 0);
}
void toolbar_hide(void)
{
showMDIToolbar = 0;
SendMessage(hwndFrame,WM_PAINT, (WPARAM) 0, (LPARAM) 0);
}
static void handle_mdiframesize(void)
{
HWND tool=NULL ,status=NULL;
RECT rFrame,rToolbar;
int fw, fh, th=0, sh=0;
GetClientRect(hwndFrame,&rFrame);
fw = rFrame.right-rFrame.left;
fh = rFrame.bottom-rFrame.top;
if (showMDIToolbar && MDIToolbar) {
tool = (HWND)MDIToolbar->handle;
GetWindowRect(tool,&rToolbar);
th = rToolbar.bottom-rToolbar.top;
}
if (MDIStatus) {
status = (HWND)MDIStatus;
GetWindowRect(status,&rToolbar);
sh = rToolbar.bottom-rToolbar.top;
}
MoveWindow(hwndClient,0,th+1,fw,fh-sh-th-1,TRUE);
if (tool) {
MoveWindow(tool,1,0,fw-2,th,TRUE);
show(MDIToolbar);
}
if (status) {
MoveWindow(status,1,fh-sh,fw-2,sh,TRUE);
}
SetFocus((HWND)SendMessage(hwndClient,
WM_MDIGETACTIVE,(WPARAM)0,(LPARAM) 0));
}
/*
* The window is being resized for some reason.
*/
static void handle_resize(object obj)
{
if (obj->call && obj->call->resize) {
drawto(obj);
obj->call->resize(obj,
rect(0,0,obj->rect.width,obj->rect.height));
}
deletion_traversal(); /* We may be called again before
returning to doevent */
}
/*
* The window is being redrawn for some reason.
*/
static void handle_redraw(object obj, HWND hwnd)
{
PAINTSTRUCT ps;
if (obj==MDIFrame)
handle_mdiframesize();
del_context(obj);
add_context(obj, BeginPaint(hwnd, &ps), NULL);
if (ps.fErase)
clear(obj);
draw(obj);
EndPaint(hwnd, &ps);
remove_context(obj);
dc = 0;
}
/*
* Hide an application window, or call close() function if possible.
*/
static void handle_close(object obj)
{
if (obj->call && obj->call->close) {
drawto(obj);
obj->call->close(obj);
} else {
hide(obj);
}
}
static void handle_destroy(object obj)
{
/*
drawto(obj);
del_object(obj);
*/
}
static void handle_focus(object obj, int gained_focus)
{
if (gained_focus) {
obj->state |= Focus;
if (obj->caretwidth < 0) {
setcaret(obj, 0,0, -obj->caretwidth, obj->caretheight);
showcaret(obj, 1);
}
} else {
obj->state &= ~Focus;
if (obj->caretwidth > 0) {
setcaret(obj, 0,0, -obj->caretwidth, obj->caretheight);
showcaret(obj, 0);
}
}
if ((! USE_NATIVE_BUTTONS) && (obj->kind == ButtonObject))
InvalidateRect(obj->handle, NULL, 0);
if (obj->call && obj->call->focus)
obj->call->focus(obj);
}
/*
* Handle scrollbars. Designed to also work with normal window
* scrollbars.
*/
static void handle_scroll(object obj, HWND hwnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
int size_shown = 10;
int max_value = 100;
int where = 0;
int prev = 0;
int which = 0;
/* we need to look at the recorded values */
max_value = obj->max;
size_shown = obj->size;
if (obj->kind != WindowObject) which = SB_CTL;
else if (message == WM_VSCROLL) which = SB_VERT;
else if (message == WM_HSCROLL) {
which = SB_HORZ;
max_value = obj->xmax;
size_shown = obj->xsize;
}
prev = where = GetScrollPos(hwnd, which);
/* next we look at wParam to see what happened */
switch(LOWORD(wParam))
{
case SB_PAGEDOWN: where += (size_shown-1);
/* fall through to next case */
case SB_LINEDOWN: where = min(max_value, where+1);
break;
case SB_PAGEUP: where -= (size_shown-1);
/* fall through to next case */
case SB_LINEUP: where = max(0, where-1);
break;
case SB_TOP: where = 0;
break;
case SB_BOTTOM: where = max_value;
break;
case SB_THUMBPOSITION:
case SB_THUMBTRACK:
#ifdef WIN32
{
/* The message only contains a 16 bit position. We need to query to get 32 bits. */
SCROLLINFO si;
si.cbSize = sizeof(SCROLLINFO);
si.fMask = SIF_TRACKPOS;
if (GetScrollInfo(hwnd, which, &si))
where = si.nTrackPos;
else
where = HIWORD(wParam); /* Just in case this mask is not supported. Not sure when it arrived... */
}
#else
where = LOWORD(lParam);
#endif
break;
default: break;
}
/* check if something happened */
if (prev == where)
return;
/* now we reset the scrollbar's values */
SetScrollPos(hwnd, which, where, 1);
if (message == WM_HSCROLL) {
where = -(where+1);
}
setvalue(obj, where);
activatecontrol(obj);
}
/*
* Perform some brush manipulation to handle background colours
* in native checkboxes and radio buttons.
*/
#if USE_NATIVE_TOGGLES
#ifdef WM_CTLCOLOR
static void handle_colour(HDC dc, object obj)
{
rgb fg, bg;
COLORREF wincolour;
if (obj->drawstate)
fg = obj->drawstate->hue;
else
fg = obj->fg;
wincolour = RGB((fg&Red)>>16,(fg&Green)>>8,(fg&Blue));
SetTextColor(dc, wincolour);
bg = obj->bg;
wincolour = RGB((bg&Red)>>16,(bg&Green)>>8,(bg&Blue));
SetBkColor(dc, wincolour);
fix_brush(dc, obj, obj->bgbrush);
}
#endif
#endif
static char dfilename[MAX_PATH + 1];
static void handle_drop(object obj, HANDLE dropstruct)
{
if (obj->call && obj->call->drop) {
int len = DragQueryFile(dropstruct, 0, NULL, 0);
if (len > MAX_PATH) {
DragFinish(dropstruct);
return;
}
DragQueryFile(dropstruct, 0, dfilename, MAX_PATH);
DragFinish(dropstruct);
obj->call->drop(obj, dfilename);
}
}
/* Handle a right-click context menu in non-window objects such as text areas */
static void handle_context_menu(object obj, HWND hwnd, int x, int y)
{
menu m = obj->popup;
HWND hw = hwnd;
POINT wp;
if (!m) {
m = obj->parent->popup;
hw = (HWND) obj->parent->handle;
}
if (m) {
wp.x = x; wp.y = y;
if (m->action) m->action(m);
TrackPopupMenu(m->handle,
TPM_LEFTALIGN|TPM_LEFTBUTTON|TPM_RIGHTBUTTON,
wp.x, wp.y, 0, hw, NULL);
}
}
/*
* Shared window procedure code. The pass variable is initially zero.
* It can be set to non-zero in this procedure if we wish to pass
* the event to the default Windows winprocs.
*/
static long handle_message(HWND hwnd, UINT message,
WPARAM wParam, LONG lParam, int *pass)
{
object obj;
WPARAM upDown;
static unsigned short altnpad = 0;
/* Find the library object associated with the hwnd. */
obj = find_by_handle(hwnd);
if (! obj) { /* Not a library object ... */
*pass = 1; /* ... so pass the event. */
return 0;
}
frontwindow = obj; /* Needed for auto-mousedowns. */
/* Handle mouse messages. */
if ((message >= WM_MOUSEMOVE) && (message <= WM_MBUTTONDBLCLK))
{
handle_mouse(obj, hwnd, message, LOWORD(wParam),
LOWORD(lParam), HIWORD(lParam));
return 0;
}
/* Handle other messages. */
switch (message)
{
case WM_MOUSEWHEEL: /* convert MOUSEWHEEL messages to VSCROLL. Scroll by pairs of lines */
upDown = (short)HIWORD(wParam) > 0 ? SB_LINEUP : SB_LINEDOWN;
PostMessage(hwnd, WM_VSCROLL, upDown, 0);
PostMessage(hwnd, WM_VSCROLL, upDown, 0);
break;
case WM_SYSKEYDOWN:
if(obj->flags & UseUnicode)
if(VK_NUMPAD0 <= LOWORD(wParam) && LOWORD(wParam) <= VK_NUMPAD9) {
altnpad *= 10;
altnpad += LOWORD(wParam) & 0xf;
}
break;
case WM_KEYDOWN: /* record state of shift and control keys */
handle_keydown(LOWORD(wParam));
handle_virtual_keydown(obj, LOWORD(wParam));
if(obj->flags & UseUnicode) {
BYTE sta[256];
wchar_t wcs[3];
HKL dwhkl;
static wchar_t deadkey = L'\0';
dwhkl = GetKeyboardLayout((DWORD) 0);
GetKeyboardState(sta);
if(ToUnicodeEx(wParam, lParam, sta,
wcs, /* 3 */ sizeof(wcs)/sizeof(wchar_t),
0, dwhkl) == 1) {
if(deadkey != L'\0') {
wchar_t wcs_in[3];
wchar_t wcs_out[3];
wcs_in[0] = wcs[0];
wcs_in[1] = deadkey;
wcs_in[2] = L'\0';
/* from accent char to unicode */
if (FoldStringW(MAP_PRECOMPOSED, wcs_in, 3, wcs_out, 3))
handle_char(obj, wcs_out[0]);
/* deadchar convert failure to skip. */
} else
handle_char(obj, wcs[0]);
deadkey = L'\0';
} else {
switch(wcs[0]) {
case 0x5e: /* circumflex */
deadkey = 0x302; break;
case 0x60: /* grave accent */
deadkey = 0x300; break;
case 0xa8: /* diaeresis */
deadkey = 0x308; break;
case 0xb4: /* acute accent */
deadkey = 0x301; break;
case 0xb8: /* cedilla */
deadkey = 0x327; break;
default:
deadkey = wcs[0];
break;
}
}
}
break;
case WM_KEYUP: /* record state of shift and control keys */
if(obj->flags & UseUnicode)
if(LOWORD(wParam) == VK_MENU && altnpad) {
handle_char(obj, altnpad);
altnpad = 0;
}
handle_keyup(LOWORD(wParam));
break;
case WM_CHAR: /* SBCS Only */
if(obj->flags & UseUnicode) return 0;
else {
handle_char(obj, LOWORD(wParam));
return 0;
}
case WM_IME_COMPOSITION: /* DBCS Only */
if (lParam & GCS_RESULTSTR) { /* is fixed multibyte string */
HIMC himc = ImmGetContext(hwnd);
wchar_t buf[80];
wchar_t *p;
int i;
int len;
if(obj->flags & UseUnicode) {
/* len is byte */
len = ImmGetCompositionStringW(himc, GCS_RESULTSTR, NULL,0);
if(NULL == (p=( len > sizeof(buf)-1) ? calloc(len,sizeof(char)) : buf)) {
len = sizeof(buf);
p = buf;
}
ImmGetCompositionStringW(himc,GCS_RESULTSTR, p, len);
ImmReleaseContext(hwnd,himc);
/* Surrogate Pairs Block */
for(i = 0; i < (len/sizeof(wchar_t)); i++)
if(IsSurrogatePairsHi(p[i]) &&
i+1 < (len/sizeof(wchar_t)) &&
IsSurrogatePairsLo(p[i+1]) ) {
handle_char(obj, L'?');
handle_char(obj, L'?');
i++;
} else handle_char(obj, p[i]);
if(p != buf) free(p);
return 0;
}
}
break;
case WM_SETFOCUS:
handle_focus(obj, 1);
break;
case WM_KILLFOCUS:
handle_focus(obj, 0);
break;
case WM_PAINT:
handle_redraw(obj, hwnd);
return 0;
case WM_INITMENUPOPUP:
if (HIWORD(lParam)) /* true if system menu */
return 0; /* else fall through */
case WM_INITMENU:
adjust_menu(wParam);
break;
case WM_MOVE:
obj->rect.x = LOWORD(lParam);
obj->rect.y = HIWORD(lParam);
break;
case WM_SIZE:
obj->rect.width = LOWORD(lParam);
obj->rect.height = HIWORD(lParam);
handle_resize(obj);
break;
case WM_ACTIVATE:
/* Keep track of which window is in front. */
if (LOWORD(wParam) != WA_INACTIVE)
move_to_front(obj);
break;
case WM_QUERYENDSESSION:
handle_close(obj);
return 1L; /* ensure Windows can terminate */
case WM_CLOSE:
handle_close(obj);
return 0;
case WM_DESTROY:
handle_destroy(obj);
break;
/*case WM_SYSCOMMAND:*/
case WM_COMMAND:
if (LOWORD(wParam) >= MinDocID)
break; /* MDI Client window will handle it */
else if (LOWORD(wParam) >= MinChildID) {
#ifdef WIN32
handle_control((HWND) (intptr_t) lParam, HIWORD(wParam));
#else
handle_control((HWND) LOWORD(lParam), HIWORD(lParam));
#endif /* WIN32 */
}
else if ((LOWORD(wParam) >= MinMenuID) && menus_active)
handle_menu_id(LOWORD(wParam));
break;
case WM_VSCROLL:
case WM_HSCROLL:
#ifdef WIN32
if (lParam != 0) { /* scrollbar object */
hwnd = (HWND) (intptr_t) lParam;
#else
if (HIWORD(lParam) != 0) { /* scrollbar object */
hwnd = (HWND) HIWORD(lParam);
#endif /* WIN32 */
obj = find_by_handle(hwnd);
if (! obj)
return 0;
}
handle_scroll(obj, hwnd, message, wParam, lParam);
return 0;
#if USE_NATIVE_TOGGLES
#ifdef WM_CTLCOLOR
case WM_CTLCOLOR:
#ifdef WIN32
hwnd = (HWND) lParam;
#else
hwnd = (HWND) LOWORD(lParam);
#endif /* WIN32 */
obj = find_by_handle(hwnd);
if (! obj)
break;
if ((obj->kind != CheckboxObject) && (obj->kind != RadioObject))
break;
handle_colour((HDC) wParam, obj);
return (LRESULT) obj->bgbrush;
#endif
#endif
case WM_IME_STARTCOMPOSITION:
if(obj->call && obj->call->im) {
HIMC himc ;
LOGFONT lf;
font f;
COMPOSITIONFORM cf;
himc = ImmGetContext(hwnd);
obj->call->im(obj, &f, (void *) &cf.ptCurrentPos);
GetObject(f->handle, sizeof(LOGFONT), &lf);
ImmSetCompositionFont(himc, &lf);
cf.dwStyle = CFS_POINT;
ImmSetCompositionWindow(himc, &cf);
ImmReleaseContext(hwnd, himc);
}
break;
case WM_DROPFILES:
handle_drop(obj, (HANDLE) wParam);
}
/* If we got this far the event must be passed along
* to the default Windows event handling procedures. */
*pass = 1;
return 0;
}
/*
* Window procedures call a generic window handling routine.
* We need three window procedures since the different calls
* tell us which default window procedure to pass the messages
* to if we don't wish to handle a message.
* If we were to use only one window procedure, we would have to
* have a way of determining which is the default window proc
* for a window from just knowing the hwnd (which may or may not
* belong to us).
*/
LRESULT WINAPI
app_win_proc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
long result;
int pass = 0;
result = handle_message(hwnd, message, wParam, lParam, &pass);
if (pass)
result = DefWindowProc(hwnd, message, wParam, lParam);
return result;
}
LRESULT WINAPI
app_doc_proc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
long result;
int pass = 0;
object obj;
if ((message==WM_MDIACTIVATE) && ((HWND)lParam==hwnd)) {
if (MDIToolbar) hide(MDIToolbar);
obj = find_by_handle(hwnd);
MDIToolbar = (obj) ? obj->toolbar : NULL;
handle_mdiframesize();
if (obj && obj->menubar) {
menu mdi = (obj->menubar)->menubar;
SendMessage(hwndClient, WM_MDISETMENU,
(WPARAM)obj->menubar->handle,
(LPARAM)(mdi?(mdi->handle):0));
DrawMenuBar(hwndFrame);
}
if (obj) updatestatus(obj->status);
RedrawWindow(hwndFrame,NULL,NULL,
RDW_UPDATENOW|RDW_ALLCHILDREN);
SetFocus(hwnd);
return 1;
}
result = handle_message(hwnd, message, wParam, lParam, &pass);
if (pass)
result = DefMDIChildProc(hwnd, message, wParam, lParam);
return result;
}
LRESULT WINAPI
app_work_proc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
long result;
int pass = 0;
result = handle_message(hwnd, message, wParam, lParam, &pass);
if (pass)
result = DefFrameProc(hwnd, hwndClient, message, wParam, lParam);
return result;
}
/*
* To handle controls correctly, we replace each control's event
* handling procedure with our own when we create it. We handle
* certain events ourselves, and pass the rest to the default
* routines.
* Things we do here include: allowing the TAB key to change
* input focus to the next control; for one-line text fields
* pressing return causes the event to be sent to the parent window.
*/
/* Send a char to an object, or its parent if it has no handler. */
static void send_char(object obj, int ch)
{
while (obj) {
if ((obj->call) && (obj->call->keydown))
break;
obj = obj->parent;
}
if (! obj)
return;
if (ch == '\r')
ch = '\n';
drawto(obj);
obj->call->keydown(obj, ch);
keystate = 0;
}
long WINAPI
app_control_procedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int prevent_activation = 0;
int key;
long result;
object obj, next;
/* Find the library object associated with the hwnd. */
obj = find_by_handle(hwnd);
key = LOWORD(wParam);
if (! obj) /* Not a library object ... */
return 0; /* ... so do nothing. */
if (! obj->winproc)
return 0; /* Nowhere to send events! */
next = find_valid_sibling(obj->next);
if (message == WM_KEYDOWN)
handle_keydown(key);
else if (message == WM_KEYUP)
handle_keyup(key);
switch (message)
{
case WM_KEYDOWN:
if (obj->kind == TextboxObject) {
handle_virtual_keydown(obj, key); /* call user's virtual key handler */
if ((key == VK_TAB) && (keystate & CtrlKey)) {
SetFocus(next->handle);
return 0;
}
break;
}
if (key == VK_TAB) {
SetFocus(next->handle);
return 0;
}
else if ((key == VK_RETURN) || (key == VK_ESCAPE)) {
send_char(obj, key);
return 0;
}
break;
case WM_CHAR:
switch (obj->kind) {
case TextboxObject:
send_char(obj, key); /* call user's key handler */
break;
case LabelObject:
case ButtonObject: case CheckboxObject:
case RadioObject: case ScrollbarObject:
case ListboxObject: case MultilistObject:
case DroplistObject: case DropfieldObject:
if (key != ' ') {
send_char(obj, key);
return 0;
}
case FieldObject:
if (key == '\t')
return 0;
if ((key == '\n') || (key == ESC))
return 0;
break;
}
break;
case WM_SETFOCUS:
if (obj->kind == RadioObject) {
/* Temporarily disable the control manually.
* We do this to work around the way Windows
* sends WM_COMMAND messages to radio buttons
* when we use TAB to set focus to them. */
#if USE_NATIVE_TOGGLES
if (isenabled(obj)) {
obj->state &= ~Enabled;
prevent_activation = 1;
}
#endif
}
else if (obj->kind == FieldObject) {
#ifdef WIN32
sendmessage(hwnd, EM_SETSEL, 32767, 32767);
#else
sendmessage(hwnd, EM_SETSEL, 0, MAKELONG(32767,32767));
#endif /* WIN32 */
}
break;
case WM_CONTEXTMENU:
handle_context_menu(obj, hwnd, LOWORD(lParam), HIWORD(lParam)); /* Handles right-click menus in, for example, edit controls */
break;
}
if (message == uFindReplaceMsg) {
handle_findreplace(hwnd, (LPFINDREPLACE) lParam);
return 0;
}
result = CallWindowProc((obj->winproc), hwnd, message, wParam, lParam);
/* Re-activate the control if necessary. */
if (prevent_activation)
obj->state |= Enabled;
return result;
}
/*
* Timer functions use a timer procedure not associated with a window.
* We use this one procedure to handle both timer events and mouse-down
* timer events. The mouse-down timer happens when the user has held
* a mouse button down for longer than mouse_msec milliseconds, and
* it causes the last mouse event to repeat.
*/
UINT WINAPI
app_timer_procedure(HWND hwnd, UINT message, UINT tid, DWORD time)
{
object obj;
UINT id = LOWORD(tid);
if ((id == 0) || (message != WM_TIMER))
return 0;
if (id == mouse_timer_id) {
obj = frontwindow;
if ((buttons == 0) || (! obj) || (! obj->call)
|| (! obj->call->mouserepeat))
setmousetimer(0);
else
obj->call->mouserepeat(obj, buttons, xy);
}
else if (id == timer_id) {
if (do_timer)
do_timer(timer_data);
}
return 0;
}
/*
* Set the timer function.
*/
void settimerfn(timerfn timeout, void *data)
{
do_timer = timeout;
timer_data = data;
}
/*
* Start the timer with a period of msec milliseconds.
*/
int settimer(unsigned msec)
{
if (timer_id != 0) {
KillTimer(0, timer_id);
timer_id = 0;
}
if (msec == 0)
timer_id = 0;
else {
timer_id = SetTimer(0, 0, (UINT) msec, app_timer_proc);
if (timer_id == 0)
return 0;
}
return 1;
}
/*
* Start the mouse-down timer with a period of msec milliseconds.
*
* Notes: setmousetimer() starts the mouse-down auto-repeat timer.
* The timer will not do anything unless the user holds down a
* mouse button for longer than msec milliseconds, in which case
* it will call the mouserepeat function associated with which ever
* window is currently active.
* Also, an interval of zero should stop the timer without
* destroying the previous interval recorded in mouse_msec.
*/
int setmousetimer(unsigned msec)
{
if (mouse_timer_id != 0) {
KillTimer(0, mouse_timer_id);
mouse_timer_id = 0;
}
if (msec == 0) {
mouse_timer_id = 0;
return 1;
}
else {
mouse_timer_id = SetTimer(0, 0, (UINT) msec, app_timer_proc);
if (mouse_timer_id == 0)
return 0;
}
mouse_msec = msec;
return 1;
}
/*
* Delay execution for a given number of milliseconds.
* This is a blocking function which should be used sparingly.
*/
void delay(unsigned msec)
{
unsigned long now;
unsigned long stop;
stop = msec;
now = GetTickCount();
stop += now;
while(now < stop)
now = GetTickCount();
}
/*
* Report current time in milliseconds since initialisation of
* the graphics interface. Not reliable for timing events.
*/
long currenttime(void)
{
return GetTickCount();
}
/*
* Intercept menu keys, since we don't always have accelerator tables.
* Return 1 if doing something which should not go to the winproc, else 0.
*/
static int TranslateMenuKeys(MSG *msg)
{
int key = LOWORD(msg->wParam);
/* Translate F10 from syskey to normal keydown message. */
if ((key == VK_F10) && (msg->message == WM_SYSKEYDOWN))
msg->message = WM_KEYDOWN;
/* Check for menu control keys. */
/* disabled for R 0.9.1 to 1.9.1.
Added proper AltGr fix for 2.5.0 */
if ((GetKeyState(VK_CONTROL) & 0x8000)
&& (msg->message == WM_KEYDOWN)
&& !(GetKeyState(VK_RMENU) & 0x8000))
{
/* ctrl-letter or ctrl-number is a menu key */
if (((key >= 'A') && (key <= 'Z')) ||
((key >= '0') && (key <= '9')))
{
if (menus_active && handle_menu_key(key))
return 1;
}
}
return 0; /* 0 = pass to TranslateMessage and DispatchMessage */
}
/*
* Return zero if there are no messages, non-zero otherwise.
*/
int peekevent(void)
{
return PeekMessage(&msg, 0, 0, 0, PM_NOREMOVE);
}
/*
* Wait for the next message
*/
void waitevent(void)
{
if (!peekevent()) WaitMessage();
}
/*
* Handle one event.
*/
int doevent(void)
{
int result = PeekMessage(&msg, 0, 0, 0, PM_REMOVE);
HWND modeless = get_modeless();
if (result)
{
/* del_all_contexts();*/
if (TranslateMenuKeys(&msg))
return result;
if ((hwndClient) &&
TranslateMDISysAccel(hwndClient, &msg))
return result;
if ((hwndFrame) && (hAccel) &&
TranslateAccelerator(hwndFrame, hAccel, &msg))
return result;
if ((modeless) && IsDialogMessage(modeless, &msg))
return result;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
deletion_traversal();
if ((active_windows <= 0) || (msg.message == WM_QUIT))
return 0;
else
return 1;
}
/*
* Handle events until the program has finished receiving events,
* or until there are no windows open to receive events.
*/
void gamainloop(void)
{
while (doevent())
continue;
}
/*
* Finish all pending graphics requests.
*/
void drawall(void)
{
/* Do nothing here. */
}
/*
* Initialise the timer and make some instance 'thunks' for
* the event callbacks.
*/
PROTECTED
void init_events(void)
{
uFindReplaceMsg = RegisterWindowMessage(FINDMSGSTRING);
app_timer_proc = (TIMERPROC) MakeProcInstance((FARPROC) app_timer_procedure,
this_instance);
setmousetimer(100); /* start 1/10 second mouse-down auto-repeat */
app_control_proc = (WNDPROC) MakeProcInstance((FARPROC) app_control_procedure,
this_instance);
}
/*
* Stop all timers and release the memory requirements of
* the proc instance 'thunks'.
*/
PROTECTED
void finish_events(void)
{
settimer(0);
setmousetimer(0);
}
| gpl-2.0 |
wakashige/TrinityCore | src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp | 38 | 29604 | /*
* Copyright (C) 2008-2015 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "InstanceScript.h"
#include "naxxramas.h"
DoorData const doorData[] =
{
{ GO_ROOM_ANUBREKHAN, BOSS_ANUBREKHAN, DOOR_TYPE_ROOM, BOUNDARY_S },
{ GO_PASSAGE_ANUBREKHAN, BOSS_ANUBREKHAN, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_PASSAGE_FAERLINA, BOSS_FAERLINA, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_ROOM_MAEXXNA, BOSS_FAERLINA, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_ROOM_MAEXXNA, BOSS_MAEXXNA, DOOR_TYPE_ROOM, BOUNDARY_SW },
{ GO_ROOM_NOTH, BOSS_NOTH, DOOR_TYPE_ROOM, BOUNDARY_N },
{ GO_PASSAGE_NOTH, BOSS_NOTH, DOOR_TYPE_PASSAGE, BOUNDARY_E },
{ GO_ROOM_HEIGAN, BOSS_NOTH, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_ROOM_HEIGAN, BOSS_HEIGAN, DOOR_TYPE_ROOM, BOUNDARY_N },
{ GO_PASSAGE_HEIGAN, BOSS_HEIGAN, DOOR_TYPE_PASSAGE, BOUNDARY_E },
{ GO_ROOM_LOATHEB, BOSS_HEIGAN, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_ROOM_LOATHEB, BOSS_LOATHEB, DOOR_TYPE_ROOM, BOUNDARY_W },
{ GO_ROOM_GROBBULUS, BOSS_PATCHWERK, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_ROOM_GROBBULUS, BOSS_GROBBULUS, DOOR_TYPE_ROOM, BOUNDARY_NONE },
{ GO_PASSAGE_GLUTH, BOSS_GLUTH, DOOR_TYPE_PASSAGE, BOUNDARY_NW },
{ GO_ROOM_THADDIUS, BOSS_GLUTH, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_ROOM_THADDIUS, BOSS_THADDIUS, DOOR_TYPE_ROOM, BOUNDARY_NONE },
{ GO_ROOM_GOTHIK, BOSS_RAZUVIOUS, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_ROOM_GOTHIK, BOSS_GOTHIK, DOOR_TYPE_ROOM, BOUNDARY_N },
{ GO_PASSAGE_GOTHIK, BOSS_GOTHIK, DOOR_TYPE_PASSAGE, BOUNDARY_S },
{ GO_ROOM_HORSEMEN, BOSS_GOTHIK, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_GOTHIK_GATE, BOSS_GOTHIK, DOOR_TYPE_ROOM, BOUNDARY_NONE },
{ GO_ROOM_HORSEMEN, BOSS_HORSEMEN, DOOR_TYPE_ROOM, BOUNDARY_NE },
{ GO_PASSAGE_SAPPHIRON, BOSS_SAPPHIRON, DOOR_TYPE_PASSAGE, BOUNDARY_W },
{ GO_ROOM_KELTHUZAD, BOSS_KELTHUZAD, DOOR_TYPE_ROOM, BOUNDARY_S },
{ GO_ARAC_EYE_RAMP, BOSS_MAEXXNA, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_ARAC_EYE_RAMP_BOSS, BOSS_MAEXXNA, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_PLAG_EYE_RAMP, BOSS_LOATHEB, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_PLAG_EYE_RAMP_BOSS, BOSS_LOATHEB, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_MILI_EYE_RAMP, BOSS_HORSEMEN, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_MILI_EYE_RAMP_BOSS, BOSS_HORSEMEN, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_CONS_EYE_RAMP, BOSS_THADDIUS, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ GO_CONS_EYE_RAMP_BOSS, BOSS_THADDIUS, DOOR_TYPE_PASSAGE, BOUNDARY_NONE },
{ 0, 0, DOOR_TYPE_ROOM, BOUNDARY_NONE }
};
MinionData const minionData[] =
{
{ NPC_FOLLOWER_WORSHIPPER, BOSS_FAERLINA },
{ NPC_DK_UNDERSTUDY, BOSS_RAZUVIOUS },
{ NPC_SIR, BOSS_HORSEMEN },
{ NPC_THANE, BOSS_HORSEMEN },
{ NPC_LADY, BOSS_HORSEMEN },
{ NPC_BARON, BOSS_HORSEMEN },
{ 0, 0, }
};
ObjectData const objectData[] =
{
{ GO_NAXX_PORTAL_ARACHNID, DATA_NAXX_PORTAL_ARACHNID },
{ GO_NAXX_PORTAL_CONSTRUCT, DATA_NAXX_PORTAL_CONSTRUCT },
{ GO_NAXX_PORTAL_PLAGUE, DATA_NAXX_PORTAL_PLAGUE },
{ GO_NAXX_PORTAL_MILITARY, DATA_NAXX_PORTAL_MILITARY },
{ 0, 0, }
};
float const HeiganPos[2] = { 2796.0f, -3707.0f };
float const HeiganEruptionSlope[3] =
{
(-3685.0f - HeiganPos[1]) / (2724.0f - HeiganPos[0]),
(-3647.0f - HeiganPos[1]) / (2749.0f - HeiganPos[0]),
(-3637.0f - HeiganPos[1]) / (2771.0f - HeiganPos[0])
};
// 0 H x
// 1 ^
// 2 |
// 3 y<--o
inline uint32 GetEruptionSection(float x, float y)
{
y -= HeiganPos[1];
if (y < 1.0f)
return 0;
x -= HeiganPos[0];
if (x > -1.0f)
return 3;
float slope = y/x;
for (uint32 i = 0; i < 3; ++i)
if (slope > HeiganEruptionSlope[i])
return i;
return 3;
}
class instance_naxxramas : public InstanceMapScript
{
public:
instance_naxxramas() : InstanceMapScript("instance_naxxramas", 533) { }
struct instance_naxxramas_InstanceMapScript : public InstanceScript
{
instance_naxxramas_InstanceMapScript(Map* map) : InstanceScript(map)
{
SetHeaders(DataHeader);
SetBossNumber(EncounterCount);
LoadDoorData(doorData);
LoadMinionData(minionData);
LoadObjectData(nullptr, objectData);
minHorsemenDiedTime = 0;
maxHorsemenDiedTime = 0;
AbominationCount = 0;
CurrentWingTaunt = SAY_KELTHUZAD_FIRST_WING_TAUNT;
playerDied = 0;
}
void OnCreatureCreate(Creature* creature) override
{
switch (creature->GetEntry())
{
case NPC_FAERLINA:
FaerlinaGUID = creature->GetGUID();
break;
case NPC_THANE:
ThaneGUID = creature->GetGUID();
break;
case NPC_LADY:
LadyGUID = creature->GetGUID();
break;
case NPC_BARON:
BaronGUID = creature->GetGUID();
break;
case NPC_SIR:
SirGUID = creature->GetGUID();
break;
case NPC_THADDIUS:
ThaddiusGUID = creature->GetGUID();
break;
case NPC_HEIGAN:
HeiganGUID = creature->GetGUID();
break;
case NPC_FEUGEN:
FeugenGUID = creature->GetGUID();
break;
case NPC_STALAGG:
StalaggGUID = creature->GetGUID();
break;
case NPC_SAPPHIRON:
SapphironGUID = creature->GetGUID();
break;
case NPC_KEL_THUZAD:
KelthuzadGUID = creature->GetGUID();
break;
case NPC_LICH_KING:
LichKingGUID = creature->GetGUID();
break;
default:
break;
}
AddMinion(creature, true);
}
void OnCreatureRemove(Creature* creature) override
{
AddMinion(creature, false);
}
void OnGameObjectCreate(GameObject* go) override
{
if (go->GetGOInfo()->displayId == 6785 || go->GetGOInfo()->displayId == 1287)
{
uint32 section = GetEruptionSection(go->GetPositionX(), go->GetPositionY());
HeiganEruptionGUID[section].insert(go->GetGUID());
return;
}
switch (go->GetEntry())
{
case GO_GOTHIK_GATE:
GothikGateGUID = go->GetGUID();
break;
case GO_HORSEMEN_CHEST:
case GO_HORSEMEN_CHEST_HERO:
HorsemenChestGUID = go->GetGUID();
break;
case GO_KELTHUZAD_PORTAL01:
PortalsGUID[0] = go->GetGUID();
break;
case GO_KELTHUZAD_PORTAL02:
PortalsGUID[1] = go->GetGUID();
break;
case GO_KELTHUZAD_PORTAL03:
PortalsGUID[2] = go->GetGUID();
break;
case GO_KELTHUZAD_PORTAL04:
PortalsGUID[3] = go->GetGUID();
break;
case GO_KELTHUZAD_TRIGGER:
KelthuzadTriggerGUID = go->GetGUID();
break;
case GO_ROOM_KELTHUZAD:
KelthuzadDoorGUID = go->GetGUID();
break;
case GO_NAXX_PORTAL_ARACHNID:
if (GetBossState(BOSS_MAEXXNA) == DONE)
go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
break;
case GO_NAXX_PORTAL_CONSTRUCT:
if (GetBossState(BOSS_THADDIUS) == DONE)
go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
break;
case GO_NAXX_PORTAL_PLAGUE:
if (GetBossState(BOSS_LOATHEB) == DONE)
go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
break;
case GO_NAXX_PORTAL_MILITARY:
if (GetBossState(BOSS_HORSEMEN) == DONE)
go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
break;
default:
break;
}
InstanceScript::OnGameObjectCreate(go);
}
void OnGameObjectRemove(GameObject* go) override
{
if (go->GetGOInfo()->displayId == 6785 || go->GetGOInfo()->displayId == 1287)
{
uint32 section = GetEruptionSection(go->GetPositionX(), go->GetPositionY());
HeiganEruptionGUID[section].erase(go->GetGUID());
return;
}
switch (go->GetEntry())
{
case GO_BIRTH:
if (!SapphironGUID.IsEmpty())
{
if (Creature* sapphiron = instance->GetCreature(SapphironGUID))
sapphiron->AI()->DoAction(DATA_SAPPHIRON_BIRTH);
return;
}
break;
default:
break;
}
InstanceScript::OnGameObjectRemove(go);
}
void OnUnitDeath(Unit* unit) override
{
if (unit->GetTypeId() == TYPEID_PLAYER && IsEncounterInProgress())
{
playerDied = 1;
SaveToDB();
}
if (Creature* creature = unit->ToCreature())
if (creature->GetEntry() == NPC_BIGGLESWORTH)
{
// Loads Kel'Thuzad's grid. We need this as he must be active in order for his texts to work.
instance->LoadGrid(3749.67f, -5114.06f);
if (Creature* kelthuzad = instance->GetCreature(KelthuzadGUID))
kelthuzad->AI()->Talk(SAY_KELTHUZAD_CAT_DIED);
}
}
void SetData(uint32 id, uint32 value) override
{
switch (id)
{
case DATA_HEIGAN_ERUPT:
HeiganErupt(value);
break;
case DATA_GOTHIK_GATE:
if (GameObject* gate = instance->GetGameObject(GothikGateGUID))
gate->SetGoState(GOState(value));
break;
case DATA_HORSEMEN0:
case DATA_HORSEMEN1:
case DATA_HORSEMEN2:
case DATA_HORSEMEN3:
if (value == NOT_STARTED)
{
minHorsemenDiedTime = 0;
maxHorsemenDiedTime = 0;
}
else if (value == DONE)
{
time_t now = time(NULL);
if (minHorsemenDiedTime == 0)
minHorsemenDiedTime = now;
maxHorsemenDiedTime = now;
}
break;
case DATA_ABOMINATION_KILLED:
AbominationCount = value;
break;
}
}
uint32 GetData(uint32 id) const override
{
switch (id)
{
case DATA_ABOMINATION_KILLED:
return AbominationCount;
default:
break;
}
return 0;
}
ObjectGuid GetGuidData(uint32 id) const override
{
switch (id)
{
case DATA_FAERLINA:
return FaerlinaGUID;
case DATA_THANE:
return ThaneGUID;
case DATA_LADY:
return LadyGUID;
case DATA_BARON:
return BaronGUID;
case DATA_SIR:
return SirGUID;
case DATA_THADDIUS:
return ThaddiusGUID;
case DATA_HEIGAN:
return HeiganGUID;
case DATA_FEUGEN:
return FeugenGUID;
case DATA_STALAGG:
return StalaggGUID;
case DATA_KELTHUZAD:
return KelthuzadGUID;
case DATA_KELTHUZAD_PORTAL01:
return PortalsGUID[0];
case DATA_KELTHUZAD_PORTAL02:
return PortalsGUID[1];
case DATA_KELTHUZAD_PORTAL03:
return PortalsGUID[2];
case DATA_KELTHUZAD_PORTAL04:
return PortalsGUID[3];
case DATA_KELTHUZAD_TRIGGER:
return KelthuzadTriggerGUID;
case DATA_LICH_KING:
return LichKingGUID;
}
return ObjectGuid::Empty;
}
bool SetBossState(uint32 id, EncounterState state) override
{
if (!InstanceScript::SetBossState(id, state))
return false;
switch (id)
{
case BOSS_MAEXXNA:
if (state == DONE)
{
if (GameObject* teleporter = GetGameObject(DATA_NAXX_PORTAL_ARACHNID))
teleporter->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
events.ScheduleEvent(EVENT_KELTHUZAD_WING_TAUNT, 6000);
}
break;
case BOSS_LOATHEB:
if (state == DONE)
{
if (GameObject* teleporter = GetGameObject(DATA_NAXX_PORTAL_PLAGUE))
teleporter->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
events.ScheduleEvent(EVENT_KELTHUZAD_WING_TAUNT, 6000);
}
break;
case BOSS_THADDIUS:
if (state == DONE)
{
if (GameObject* teleporter = GetGameObject(DATA_NAXX_PORTAL_CONSTRUCT))
teleporter->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
events.ScheduleEvent(EVENT_KELTHUZAD_WING_TAUNT, 6000);
}
break;
case BOSS_GOTHIK:
if (state == DONE)
events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_KORTHAZZ, 10000);
break;
case BOSS_HORSEMEN:
if (state == DONE)
{
if (GameObject* horsemenChest = instance->GetGameObject(HorsemenChestGUID))
{
horsemenChest->SetRespawnTime(horsemenChest->GetRespawnDelay());
horsemenChest->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
}
if (GameObject* teleporter = GetGameObject(DATA_NAXX_PORTAL_MILITARY))
teleporter->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
events.ScheduleEvent(EVENT_KELTHUZAD_WING_TAUNT, 6000);
}
break;
case BOSS_SAPPHIRON:
if (state == DONE)
events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD, 6000);
break;
default:
break;
}
return true;
}
void Update(uint32 diff) override
{
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_DIALOGUE_GOTHIK_KORTHAZZ:
if (Creature* korthazz = instance->GetCreature(ThaneGUID))
korthazz->AI()->Talk(SAY_DIALOGUE_GOTHIK_HORSEMAN);
events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_ZELIEK, 5000);
break;
case EVENT_DIALOGUE_GOTHIK_ZELIEK:
if (Creature* zeliek = instance->GetCreature(SirGUID))
zeliek->AI()->Talk(SAY_DIALOGUE_GOTHIK_HORSEMAN);
events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_BLAUMEUX, 6000);
break;
case EVENT_DIALOGUE_GOTHIK_BLAUMEUX:
if (Creature* blaumeux = instance->GetCreature(LadyGUID))
blaumeux->AI()->Talk(SAY_DIALOGUE_GOTHIK_HORSEMAN);
events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_RIVENDARE, 6000);
break;
case EVENT_DIALOGUE_GOTHIK_RIVENDARE:
if (Creature* rivendare = instance->GetCreature(BaronGUID))
rivendare->AI()->Talk(SAY_DIALOGUE_GOTHIK_HORSEMAN);
events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_BLAUMEUX2, 6000);
break;
case EVENT_DIALOGUE_GOTHIK_BLAUMEUX2:
if (Creature* blaumeux = instance->GetCreature(LadyGUID))
blaumeux->AI()->Talk(SAY_DIALOGUE_GOTHIK_HORSEMAN2);
events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_ZELIEK2, 6000);
break;
case EVENT_DIALOGUE_GOTHIK_ZELIEK2:
if (Creature* zeliek = instance->GetCreature(SirGUID))
zeliek->AI()->Talk(SAY_DIALOGUE_GOTHIK_HORSEMAN2);
events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_KORTHAZZ2, 6000);
break;
case EVENT_DIALOGUE_GOTHIK_KORTHAZZ2:
if (Creature* korthazz = instance->GetCreature(ThaneGUID))
korthazz->AI()->Talk(SAY_DIALOGUE_GOTHIK_HORSEMAN2);
events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_RIVENDARE2, 6000);
break;
case EVENT_DIALOGUE_GOTHIK_RIVENDARE2:
if (Creature* rivendare = instance->GetCreature(BaronGUID))
rivendare->AI()->Talk(SAY_DIALOGUE_GOTHIK_HORSEMAN2);
break;
case EVENT_KELTHUZAD_WING_TAUNT:
// Loads Kel'Thuzad's grid. We need this as he must be active in order for his texts to work.
instance->LoadGrid(3749.67f, -5114.06f);
if (Creature* kelthuzad = instance->GetCreature(KelthuzadGUID))
kelthuzad->AI()->Talk(CurrentWingTaunt);
++CurrentWingTaunt;
break;
case EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD:
if (Creature* kelthuzad = instance->GetCreature(KelthuzadGUID))
kelthuzad->AI()->Talk(SAY_DIALOGUE_SAPPHIRON_KELTHUZAD);
HandleGameObject(KelthuzadDoorGUID, false);
events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_LICHKING, 6000);
break;
case EVENT_DIALOGUE_SAPPHIRON_LICHKING:
if (Creature* lichKing = instance->GetCreature(LichKingGUID))
lichKing->AI()->Talk(SAY_DIALOGUE_SAPPHIRON_LICH_KING);
events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD2, 16000);
break;
case EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD2:
if (Creature* kelthuzad = instance->GetCreature(KelthuzadGUID))
kelthuzad->AI()->Talk(SAY_DIALOGUE_SAPPHIRON_KELTHUZAD2);
events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_LICHKING2, 9000);
break;
case EVENT_DIALOGUE_SAPPHIRON_LICHKING2:
if (Creature* lichKing = instance->GetCreature(LichKingGUID))
lichKing->AI()->Talk(SAY_DIALOGUE_SAPPHIRON_LICH_KING2);
events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD3, 12000);
break;
case EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD3:
if (Creature* kelthuzad = instance->GetCreature(KelthuzadGUID))
kelthuzad->AI()->Talk(SAY_DIALOGUE_SAPPHIRON_KELTHUZAD3);
events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD4, 6000);
break;
case EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD4:
if (Creature* kelthuzad = instance->GetCreature(KelthuzadGUID))
kelthuzad->AI()->Talk(SAY_DIALOGUE_SAPPHIRON_KELTHUZAD4);
HandleGameObject(KelthuzadDoorGUID, true);
break;
default:
break;
}
}
}
void HeiganErupt(uint32 section)
{
for (uint32 i = 0; i < 4; ++i)
{
if (i == section)
continue;
for (ObjectGuid guid : HeiganEruptionGUID[i])
{
if (GameObject* heiganEruption = instance->GetGameObject(guid))
{
heiganEruption->SendCustomAnim(heiganEruption->GetGoAnimProgress());
heiganEruption->CastSpell(NULL, SPELL_ERUPTION);
}
}
}
}
// This Function is called in CheckAchievementCriteriaMeet and CheckAchievementCriteriaMeet is called before SetBossState(bossId, DONE),
// so to check if all bosses are done the checker must exclude 1 boss, the last done, if there is at most 1 encouter in progress when is
// called this function then all bosses are done. The one boss that check is the boss that calls this function, so it is dead.
bool AreAllEncoutersDone()
{
uint32 numBossAlive = 0;
for (uint32 i = 0; i < EncounterCount; ++i)
if (GetBossState(i) != DONE)
numBossAlive++;
if (numBossAlive > 1)
return false;
return true;
}
bool CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target = NULL*/, uint32 /*miscvalue1 = 0*/) override
{
switch (criteria_id)
{
case 7600: // Criteria for achievement 2176: And They Would All Go Down Together 15sec of each other 10-man
if (Difficulty(instance->GetSpawnMode()) == DIFFICULTY_10_N && (maxHorsemenDiedTime - minHorsemenDiedTime) < 15)
return true;
return false;
case 7601: // Criteria for achievement 2177: And They Would All Go Down Together 15sec of each other 25-man
if (Difficulty(instance->GetSpawnMode()) == DIFFICULTY_25_N && (maxHorsemenDiedTime - minHorsemenDiedTime) < 15)
return true;
return false;
// Difficulty checks are done on DB.
// Criteria for achievement 2186: The Immortal (25-man)
case 13233: // The Four Horsemen
case 13234: // Maexxna
case 13235: // Thaddius
case 13236: // Loatheb
case 7616: // Kel'Thuzad
// Criteria for achievement 2187: The Undying (10-man)
case 13237: // The Four Horsemen
case 13238: // Maexxna
case 13239: // Loatheb
case 13240: // Thaddius
case 7617: // Kel'Thuzad
if (AreAllEncoutersDone() && !playerDied)
return true;
return false;
}
return false;
}
protected:
/* The Arachnid Quarter */
// Grand Widow Faerlina
ObjectGuid FaerlinaGUID;
/* The Plague Quarter */
// Heigan the Unclean
GuidSet HeiganEruptionGUID[4];
ObjectGuid HeiganGUID;
/* The Military Quarter */
// Gothik the Harvester
ObjectGuid GothikGateGUID;
// The Four Horsemen
ObjectGuid ThaneGUID;
ObjectGuid LadyGUID;
ObjectGuid BaronGUID;
ObjectGuid SirGUID;
ObjectGuid HorsemenChestGUID;
time_t minHorsemenDiedTime;
time_t maxHorsemenDiedTime;
/* The Construct Quarter */
// Thaddius
ObjectGuid ThaddiusGUID;
ObjectGuid FeugenGUID;
ObjectGuid StalaggGUID;
/* Frostwyrm Lair */
// Sapphiron
ObjectGuid SapphironGUID;
// Kel'Thuzad
ObjectGuid KelthuzadGUID;
ObjectGuid KelthuzadTriggerGUID;
ObjectGuid PortalsGUID[4];
ObjectGuid KelthuzadDoorGUID;
ObjectGuid LichKingGUID;
uint8 AbominationCount;
uint8 CurrentWingTaunt;
/* The Immortal / The Undying */
uint32 playerDied;
EventMap events;
};
InstanceScript* GetInstanceScript(InstanceMap* map) const override
{
return new instance_naxxramas_InstanceMapScript(map);
}
};
void AddSC_instance_naxxramas()
{
new instance_naxxramas();
}
| gpl-2.0 |
mipltd/imx6merlin-linux-3.14.28 | drivers/pwm/pwm-tiehrpwm.c | 294 | 16674 | /*
* EHRPWM PWM driver
*
* Copyright (C) 2012 Texas Instruments, Inc. - http://www.ti.com/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pwm.h>
#include <linux/io.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/pm_runtime.h>
#include <linux/of_device.h>
#include "pwm-tipwmss.h"
/* EHRPWM registers and bits definitions */
/* Time base module registers */
#define TBCTL 0x00
#define TBPRD 0x0A
#define TBCTL_RUN_MASK (BIT(15) | BIT(14))
#define TBCTL_STOP_NEXT 0
#define TBCTL_STOP_ON_CYCLE BIT(14)
#define TBCTL_FREE_RUN (BIT(15) | BIT(14))
#define TBCTL_PRDLD_MASK BIT(3)
#define TBCTL_PRDLD_SHDW 0
#define TBCTL_PRDLD_IMDT BIT(3)
#define TBCTL_CLKDIV_MASK (BIT(12) | BIT(11) | BIT(10) | BIT(9) | \
BIT(8) | BIT(7))
#define TBCTL_CTRMODE_MASK (BIT(1) | BIT(0))
#define TBCTL_CTRMODE_UP 0
#define TBCTL_CTRMODE_DOWN BIT(0)
#define TBCTL_CTRMODE_UPDOWN BIT(1)
#define TBCTL_CTRMODE_FREEZE (BIT(1) | BIT(0))
#define TBCTL_HSPCLKDIV_SHIFT 7
#define TBCTL_CLKDIV_SHIFT 10
#define CLKDIV_MAX 7
#define HSPCLKDIV_MAX 7
#define PERIOD_MAX 0xFFFF
/* compare module registers */
#define CMPA 0x12
#define CMPB 0x14
/* Action qualifier module registers */
#define AQCTLA 0x16
#define AQCTLB 0x18
#define AQSFRC 0x1A
#define AQCSFRC 0x1C
#define AQCTL_CBU_MASK (BIT(9) | BIT(8))
#define AQCTL_CBU_FRCLOW BIT(8)
#define AQCTL_CBU_FRCHIGH BIT(9)
#define AQCTL_CBU_FRCTOGGLE (BIT(9) | BIT(8))
#define AQCTL_CAU_MASK (BIT(5) | BIT(4))
#define AQCTL_CAU_FRCLOW BIT(4)
#define AQCTL_CAU_FRCHIGH BIT(5)
#define AQCTL_CAU_FRCTOGGLE (BIT(5) | BIT(4))
#define AQCTL_PRD_MASK (BIT(3) | BIT(2))
#define AQCTL_PRD_FRCLOW BIT(2)
#define AQCTL_PRD_FRCHIGH BIT(3)
#define AQCTL_PRD_FRCTOGGLE (BIT(3) | BIT(2))
#define AQCTL_ZRO_MASK (BIT(1) | BIT(0))
#define AQCTL_ZRO_FRCLOW BIT(0)
#define AQCTL_ZRO_FRCHIGH BIT(1)
#define AQCTL_ZRO_FRCTOGGLE (BIT(1) | BIT(0))
#define AQCTL_CHANA_POLNORMAL (AQCTL_CAU_FRCLOW | AQCTL_PRD_FRCHIGH | \
AQCTL_ZRO_FRCHIGH)
#define AQCTL_CHANA_POLINVERSED (AQCTL_CAU_FRCHIGH | AQCTL_PRD_FRCLOW | \
AQCTL_ZRO_FRCLOW)
#define AQCTL_CHANB_POLNORMAL (AQCTL_CBU_FRCLOW | AQCTL_PRD_FRCHIGH | \
AQCTL_ZRO_FRCHIGH)
#define AQCTL_CHANB_POLINVERSED (AQCTL_CBU_FRCHIGH | AQCTL_PRD_FRCLOW | \
AQCTL_ZRO_FRCLOW)
#define AQSFRC_RLDCSF_MASK (BIT(7) | BIT(6))
#define AQSFRC_RLDCSF_ZRO 0
#define AQSFRC_RLDCSF_PRD BIT(6)
#define AQSFRC_RLDCSF_ZROPRD BIT(7)
#define AQSFRC_RLDCSF_IMDT (BIT(7) | BIT(6))
#define AQCSFRC_CSFB_MASK (BIT(3) | BIT(2))
#define AQCSFRC_CSFB_FRCDIS 0
#define AQCSFRC_CSFB_FRCLOW BIT(2)
#define AQCSFRC_CSFB_FRCHIGH BIT(3)
#define AQCSFRC_CSFB_DISSWFRC (BIT(3) | BIT(2))
#define AQCSFRC_CSFA_MASK (BIT(1) | BIT(0))
#define AQCSFRC_CSFA_FRCDIS 0
#define AQCSFRC_CSFA_FRCLOW BIT(0)
#define AQCSFRC_CSFA_FRCHIGH BIT(1)
#define AQCSFRC_CSFA_DISSWFRC (BIT(1) | BIT(0))
#define NUM_PWM_CHANNEL 2 /* EHRPWM channels */
struct ehrpwm_context {
u16 tbctl;
u16 tbprd;
u16 cmpa;
u16 cmpb;
u16 aqctla;
u16 aqctlb;
u16 aqsfrc;
u16 aqcsfrc;
};
struct ehrpwm_pwm_chip {
struct pwm_chip chip;
unsigned int clk_rate;
void __iomem *mmio_base;
unsigned long period_cycles[NUM_PWM_CHANNEL];
enum pwm_polarity polarity[NUM_PWM_CHANNEL];
struct clk *tbclk;
struct ehrpwm_context ctx;
};
static inline struct ehrpwm_pwm_chip *to_ehrpwm_pwm_chip(struct pwm_chip *chip)
{
return container_of(chip, struct ehrpwm_pwm_chip, chip);
}
static u16 ehrpwm_read(void __iomem *base, int offset)
{
return readw(base + offset);
}
static void ehrpwm_write(void __iomem *base, int offset, unsigned int val)
{
writew(val & 0xFFFF, base + offset);
}
static void ehrpwm_modify(void __iomem *base, int offset,
unsigned short mask, unsigned short val)
{
unsigned short regval;
regval = readw(base + offset);
regval &= ~mask;
regval |= val & mask;
writew(regval, base + offset);
}
/**
* set_prescale_div - Set up the prescaler divider function
* @rqst_prescaler: prescaler value min
* @prescale_div: prescaler value set
* @tb_clk_div: Time Base Control prescaler bits
*/
static int set_prescale_div(unsigned long rqst_prescaler,
unsigned short *prescale_div, unsigned short *tb_clk_div)
{
unsigned int clkdiv, hspclkdiv;
for (clkdiv = 0; clkdiv <= CLKDIV_MAX; clkdiv++) {
for (hspclkdiv = 0; hspclkdiv <= HSPCLKDIV_MAX; hspclkdiv++) {
/*
* calculations for prescaler value :
* prescale_div = HSPCLKDIVIDER * CLKDIVIDER.
* HSPCLKDIVIDER = 2 ** hspclkdiv
* CLKDIVIDER = (1), if clkdiv == 0 *OR*
* (2 * clkdiv), if clkdiv != 0
*
* Configure prescale_div value such that period
* register value is less than 65535.
*/
*prescale_div = (1 << clkdiv) *
(hspclkdiv ? (hspclkdiv * 2) : 1);
if (*prescale_div > rqst_prescaler) {
*tb_clk_div = (clkdiv << TBCTL_CLKDIV_SHIFT) |
(hspclkdiv << TBCTL_HSPCLKDIV_SHIFT);
return 0;
}
}
}
return 1;
}
static void configure_polarity(struct ehrpwm_pwm_chip *pc, int chan)
{
int aqctl_reg;
unsigned short aqctl_val, aqctl_mask;
/*
* Configure PWM output to HIGH/LOW level on counter
* reaches compare register value and LOW/HIGH level
* on counter value reaches period register value and
* zero value on counter
*/
if (chan == 1) {
aqctl_reg = AQCTLB;
aqctl_mask = AQCTL_CBU_MASK;
if (pc->polarity[chan] == PWM_POLARITY_INVERSED)
aqctl_val = AQCTL_CHANB_POLINVERSED;
else
aqctl_val = AQCTL_CHANB_POLNORMAL;
} else {
aqctl_reg = AQCTLA;
aqctl_mask = AQCTL_CAU_MASK;
if (pc->polarity[chan] == PWM_POLARITY_INVERSED)
aqctl_val = AQCTL_CHANA_POLINVERSED;
else
aqctl_val = AQCTL_CHANA_POLNORMAL;
}
aqctl_mask |= AQCTL_PRD_MASK | AQCTL_ZRO_MASK;
ehrpwm_modify(pc->mmio_base, aqctl_reg, aqctl_mask, aqctl_val);
}
/*
* period_ns = 10^9 * (ps_divval * period_cycles) / PWM_CLK_RATE
* duty_ns = 10^9 * (ps_divval * duty_cycles) / PWM_CLK_RATE
*/
static int ehrpwm_pwm_config(struct pwm_chip *chip, struct pwm_device *pwm,
int duty_ns, int period_ns)
{
struct ehrpwm_pwm_chip *pc = to_ehrpwm_pwm_chip(chip);
unsigned long long c;
unsigned long period_cycles, duty_cycles;
unsigned short ps_divval, tb_divval;
int i, cmp_reg;
if (period_ns > NSEC_PER_SEC)
return -ERANGE;
c = pc->clk_rate;
c = c * period_ns;
do_div(c, NSEC_PER_SEC);
period_cycles = (unsigned long)c;
if (period_cycles < 1) {
period_cycles = 1;
duty_cycles = 1;
} else {
c = pc->clk_rate;
c = c * duty_ns;
do_div(c, NSEC_PER_SEC);
duty_cycles = (unsigned long)c;
}
/*
* Period values should be same for multiple PWM channels as IP uses
* same period register for multiple channels.
*/
for (i = 0; i < NUM_PWM_CHANNEL; i++) {
if (pc->period_cycles[i] &&
(pc->period_cycles[i] != period_cycles)) {
/*
* Allow channel to reconfigure period if no other
* channels being configured.
*/
if (i == pwm->hwpwm)
continue;
dev_err(chip->dev, "Period value conflicts with channel %d\n",
i);
return -EINVAL;
}
}
pc->period_cycles[pwm->hwpwm] = period_cycles;
/* Configure clock prescaler to support Low frequency PWM wave */
if (set_prescale_div(period_cycles/PERIOD_MAX, &ps_divval,
&tb_divval)) {
dev_err(chip->dev, "Unsupported values\n");
return -EINVAL;
}
pm_runtime_get_sync(chip->dev);
/* Update clock prescaler values */
ehrpwm_modify(pc->mmio_base, TBCTL, TBCTL_CLKDIV_MASK, tb_divval);
/* Update period & duty cycle with presacler division */
period_cycles = period_cycles / ps_divval;
duty_cycles = duty_cycles / ps_divval;
/* Configure shadow loading on Period register */
ehrpwm_modify(pc->mmio_base, TBCTL, TBCTL_PRDLD_MASK, TBCTL_PRDLD_SHDW);
ehrpwm_write(pc->mmio_base, TBPRD, period_cycles);
/* Configure ehrpwm counter for up-count mode */
ehrpwm_modify(pc->mmio_base, TBCTL, TBCTL_CTRMODE_MASK,
TBCTL_CTRMODE_UP);
if (pwm->hwpwm == 1)
/* Channel 1 configured with compare B register */
cmp_reg = CMPB;
else
/* Channel 0 configured with compare A register */
cmp_reg = CMPA;
ehrpwm_write(pc->mmio_base, cmp_reg, duty_cycles);
pm_runtime_put_sync(chip->dev);
return 0;
}
static int ehrpwm_pwm_set_polarity(struct pwm_chip *chip,
struct pwm_device *pwm, enum pwm_polarity polarity)
{
struct ehrpwm_pwm_chip *pc = to_ehrpwm_pwm_chip(chip);
/* Configuration of polarity in hardware delayed, do at enable */
pc->polarity[pwm->hwpwm] = polarity;
return 0;
}
static int ehrpwm_pwm_enable(struct pwm_chip *chip, struct pwm_device *pwm)
{
struct ehrpwm_pwm_chip *pc = to_ehrpwm_pwm_chip(chip);
unsigned short aqcsfrc_val, aqcsfrc_mask;
int ret;
/* Leave clock enabled on enabling PWM */
pm_runtime_get_sync(chip->dev);
/* Disabling Action Qualifier on PWM output */
if (pwm->hwpwm) {
aqcsfrc_val = AQCSFRC_CSFB_FRCDIS;
aqcsfrc_mask = AQCSFRC_CSFB_MASK;
} else {
aqcsfrc_val = AQCSFRC_CSFA_FRCDIS;
aqcsfrc_mask = AQCSFRC_CSFA_MASK;
}
/* Changes to shadow mode */
ehrpwm_modify(pc->mmio_base, AQSFRC, AQSFRC_RLDCSF_MASK,
AQSFRC_RLDCSF_ZRO);
ehrpwm_modify(pc->mmio_base, AQCSFRC, aqcsfrc_mask, aqcsfrc_val);
/* Channels polarity can be configured from action qualifier module */
configure_polarity(pc, pwm->hwpwm);
/* Enable TBCLK before enabling PWM device */
ret = clk_enable(pc->tbclk);
if (ret) {
dev_err(chip->dev, "Failed to enable TBCLK for %s\n",
dev_name(pc->chip.dev));
return ret;
}
/* Enable time counter for free_run */
ehrpwm_modify(pc->mmio_base, TBCTL, TBCTL_RUN_MASK, TBCTL_FREE_RUN);
return 0;
}
static void ehrpwm_pwm_disable(struct pwm_chip *chip, struct pwm_device *pwm)
{
struct ehrpwm_pwm_chip *pc = to_ehrpwm_pwm_chip(chip);
unsigned short aqcsfrc_val, aqcsfrc_mask;
/* Action Qualifier puts PWM output low forcefully */
if (pwm->hwpwm) {
aqcsfrc_val = AQCSFRC_CSFB_FRCLOW;
aqcsfrc_mask = AQCSFRC_CSFB_MASK;
} else {
aqcsfrc_val = AQCSFRC_CSFA_FRCLOW;
aqcsfrc_mask = AQCSFRC_CSFA_MASK;
}
/*
* Changes to immediate action on Action Qualifier. This puts
* Action Qualifier control on PWM output from next TBCLK
*/
ehrpwm_modify(pc->mmio_base, AQSFRC, AQSFRC_RLDCSF_MASK,
AQSFRC_RLDCSF_IMDT);
ehrpwm_modify(pc->mmio_base, AQCSFRC, aqcsfrc_mask, aqcsfrc_val);
/* Disabling TBCLK on PWM disable */
clk_disable(pc->tbclk);
/* Stop Time base counter */
ehrpwm_modify(pc->mmio_base, TBCTL, TBCTL_RUN_MASK, TBCTL_STOP_NEXT);
/* Disable clock on PWM disable */
pm_runtime_put_sync(chip->dev);
}
static void ehrpwm_pwm_free(struct pwm_chip *chip, struct pwm_device *pwm)
{
struct ehrpwm_pwm_chip *pc = to_ehrpwm_pwm_chip(chip);
if (test_bit(PWMF_ENABLED, &pwm->flags)) {
dev_warn(chip->dev, "Removing PWM device without disabling\n");
pm_runtime_put_sync(chip->dev);
}
/* set period value to zero on free */
pc->period_cycles[pwm->hwpwm] = 0;
}
static const struct pwm_ops ehrpwm_pwm_ops = {
.free = ehrpwm_pwm_free,
.config = ehrpwm_pwm_config,
.set_polarity = ehrpwm_pwm_set_polarity,
.enable = ehrpwm_pwm_enable,
.disable = ehrpwm_pwm_disable,
.owner = THIS_MODULE,
};
static const struct of_device_id ehrpwm_of_match[] = {
{ .compatible = "ti,am33xx-ehrpwm" },
{},
};
MODULE_DEVICE_TABLE(of, ehrpwm_of_match);
static int ehrpwm_pwm_probe(struct platform_device *pdev)
{
int ret;
struct resource *r;
struct clk *clk;
struct ehrpwm_pwm_chip *pc;
u16 status;
pc = devm_kzalloc(&pdev->dev, sizeof(*pc), GFP_KERNEL);
if (!pc) {
dev_err(&pdev->dev, "failed to allocate memory\n");
return -ENOMEM;
}
clk = devm_clk_get(&pdev->dev, "fck");
if (IS_ERR(clk)) {
dev_err(&pdev->dev, "failed to get clock\n");
return PTR_ERR(clk);
}
pc->clk_rate = clk_get_rate(clk);
if (!pc->clk_rate) {
dev_err(&pdev->dev, "failed to get clock rate\n");
return -EINVAL;
}
pc->chip.dev = &pdev->dev;
pc->chip.ops = &ehrpwm_pwm_ops;
pc->chip.of_xlate = of_pwm_xlate_with_flags;
pc->chip.of_pwm_n_cells = 3;
pc->chip.base = -1;
pc->chip.npwm = NUM_PWM_CHANNEL;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
pc->mmio_base = devm_ioremap_resource(&pdev->dev, r);
if (IS_ERR(pc->mmio_base))
return PTR_ERR(pc->mmio_base);
/* Acquire tbclk for Time Base EHRPWM submodule */
pc->tbclk = devm_clk_get(&pdev->dev, "tbclk");
if (IS_ERR(pc->tbclk)) {
dev_err(&pdev->dev, "Failed to get tbclk\n");
return PTR_ERR(pc->tbclk);
}
ret = clk_prepare(pc->tbclk);
if (ret < 0) {
dev_err(&pdev->dev, "clk_prepare() failed: %d\n", ret);
return ret;
}
ret = pwmchip_add(&pc->chip);
if (ret < 0) {
dev_err(&pdev->dev, "pwmchip_add() failed: %d\n", ret);
return ret;
}
pm_runtime_enable(&pdev->dev);
pm_runtime_get_sync(&pdev->dev);
status = pwmss_submodule_state_change(pdev->dev.parent,
PWMSS_EPWMCLK_EN);
if (!(status & PWMSS_EPWMCLK_EN_ACK)) {
dev_err(&pdev->dev, "PWMSS config space clock enable failed\n");
ret = -EINVAL;
goto pwmss_clk_failure;
}
pm_runtime_put_sync(&pdev->dev);
platform_set_drvdata(pdev, pc);
return 0;
pwmss_clk_failure:
pm_runtime_put_sync(&pdev->dev);
pm_runtime_disable(&pdev->dev);
pwmchip_remove(&pc->chip);
clk_unprepare(pc->tbclk);
return ret;
}
static int ehrpwm_pwm_remove(struct platform_device *pdev)
{
struct ehrpwm_pwm_chip *pc = platform_get_drvdata(pdev);
clk_unprepare(pc->tbclk);
pm_runtime_get_sync(&pdev->dev);
/*
* Due to hardware misbehaviour, acknowledge of the stop_req
* is missing. Hence checking of the status bit skipped.
*/
pwmss_submodule_state_change(pdev->dev.parent, PWMSS_EPWMCLK_STOP_REQ);
pm_runtime_put_sync(&pdev->dev);
pm_runtime_put_sync(&pdev->dev);
pm_runtime_disable(&pdev->dev);
return pwmchip_remove(&pc->chip);
}
static void ehrpwm_pwm_save_context(struct ehrpwm_pwm_chip *pc)
{
pm_runtime_get_sync(pc->chip.dev);
pc->ctx.tbctl = ehrpwm_read(pc->mmio_base, TBCTL);
pc->ctx.tbprd = ehrpwm_read(pc->mmio_base, TBPRD);
pc->ctx.cmpa = ehrpwm_read(pc->mmio_base, CMPA);
pc->ctx.cmpb = ehrpwm_read(pc->mmio_base, CMPB);
pc->ctx.aqctla = ehrpwm_read(pc->mmio_base, AQCTLA);
pc->ctx.aqctlb = ehrpwm_read(pc->mmio_base, AQCTLB);
pc->ctx.aqsfrc = ehrpwm_read(pc->mmio_base, AQSFRC);
pc->ctx.aqcsfrc = ehrpwm_read(pc->mmio_base, AQCSFRC);
pm_runtime_put_sync(pc->chip.dev);
}
static void ehrpwm_pwm_restore_context(struct ehrpwm_pwm_chip *pc)
{
ehrpwm_write(pc->mmio_base, TBPRD, pc->ctx.tbprd);
ehrpwm_write(pc->mmio_base, CMPA, pc->ctx.cmpa);
ehrpwm_write(pc->mmio_base, CMPB, pc->ctx.cmpb);
ehrpwm_write(pc->mmio_base, AQCTLA, pc->ctx.aqctla);
ehrpwm_write(pc->mmio_base, AQCTLB, pc->ctx.aqctlb);
ehrpwm_write(pc->mmio_base, AQSFRC, pc->ctx.aqsfrc);
ehrpwm_write(pc->mmio_base, AQCSFRC, pc->ctx.aqcsfrc);
ehrpwm_write(pc->mmio_base, TBCTL, pc->ctx.tbctl);
}
#ifdef CONFIG_PM_SLEEP
static int ehrpwm_pwm_suspend(struct device *dev)
{
struct ehrpwm_pwm_chip *pc = dev_get_drvdata(dev);
int i;
ehrpwm_pwm_save_context(pc);
for (i = 0; i < pc->chip.npwm; i++) {
struct pwm_device *pwm = &pc->chip.pwms[i];
if (!test_bit(PWMF_ENABLED, &pwm->flags))
continue;
/* Disable explicitly if PWM is running */
pm_runtime_put_sync(dev);
}
return 0;
}
static int ehrpwm_pwm_resume(struct device *dev)
{
struct ehrpwm_pwm_chip *pc = dev_get_drvdata(dev);
int i;
for (i = 0; i < pc->chip.npwm; i++) {
struct pwm_device *pwm = &pc->chip.pwms[i];
if (!test_bit(PWMF_ENABLED, &pwm->flags))
continue;
/* Enable explicitly if PWM was running */
pm_runtime_get_sync(dev);
}
ehrpwm_pwm_restore_context(pc);
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(ehrpwm_pwm_pm_ops, ehrpwm_pwm_suspend,
ehrpwm_pwm_resume);
static struct platform_driver ehrpwm_pwm_driver = {
.driver = {
.name = "ehrpwm",
.owner = THIS_MODULE,
.of_match_table = ehrpwm_of_match,
.pm = &ehrpwm_pwm_pm_ops,
},
.probe = ehrpwm_pwm_probe,
.remove = ehrpwm_pwm_remove,
};
module_platform_driver(ehrpwm_pwm_driver);
MODULE_DESCRIPTION("EHRPWM PWM driver");
MODULE_AUTHOR("Texas Instruments");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ghanashyamprabhu/linux | net/atm/clip.c | 1062 | 22826 | /* net/atm/clip.c - RFC1577 Classical IP over ATM */
/* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */
#define pr_fmt(fmt) KBUILD_MODNAME ":%s: " fmt, __func__
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/kernel.h> /* for UINT_MAX */
#include <linux/module.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/wait.h>
#include <linux/timer.h>
#include <linux/if_arp.h> /* for some manifest constants */
#include <linux/notifier.h>
#include <linux/atm.h>
#include <linux/atmdev.h>
#include <linux/atmclip.h>
#include <linux/atmarp.h>
#include <linux/capability.h>
#include <linux/ip.h> /* for net/route.h */
#include <linux/in.h> /* for struct sockaddr_in */
#include <linux/if.h> /* for IFF_UP */
#include <linux/inetdevice.h>
#include <linux/bitops.h>
#include <linux/poison.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/rcupdate.h>
#include <linux/jhash.h>
#include <linux/slab.h>
#include <net/route.h> /* for struct rtable and routing */
#include <net/icmp.h> /* icmp_send */
#include <net/arp.h>
#include <linux/param.h> /* for HZ */
#include <linux/uaccess.h>
#include <asm/byteorder.h> /* for htons etc. */
#include <linux/atomic.h>
#include "common.h"
#include "resources.h"
#include <net/atmclip.h>
static struct net_device *clip_devs;
static struct atm_vcc *atmarpd;
static struct timer_list idle_timer;
static const struct neigh_ops clip_neigh_ops;
static int to_atmarpd(enum atmarp_ctrl_type type, int itf, __be32 ip)
{
struct sock *sk;
struct atmarp_ctrl *ctrl;
struct sk_buff *skb;
pr_debug("(%d)\n", type);
if (!atmarpd)
return -EUNATCH;
skb = alloc_skb(sizeof(struct atmarp_ctrl), GFP_ATOMIC);
if (!skb)
return -ENOMEM;
ctrl = (struct atmarp_ctrl *)skb_put(skb, sizeof(struct atmarp_ctrl));
ctrl->type = type;
ctrl->itf_num = itf;
ctrl->ip = ip;
atm_force_charge(atmarpd, skb->truesize);
sk = sk_atm(atmarpd);
skb_queue_tail(&sk->sk_receive_queue, skb);
sk->sk_data_ready(sk);
return 0;
}
static void link_vcc(struct clip_vcc *clip_vcc, struct atmarp_entry *entry)
{
pr_debug("%p to entry %p (neigh %p)\n", clip_vcc, entry, entry->neigh);
clip_vcc->entry = entry;
clip_vcc->xoff = 0; /* @@@ may overrun buffer by one packet */
clip_vcc->next = entry->vccs;
entry->vccs = clip_vcc;
entry->neigh->used = jiffies;
}
static void unlink_clip_vcc(struct clip_vcc *clip_vcc)
{
struct atmarp_entry *entry = clip_vcc->entry;
struct clip_vcc **walk;
if (!entry) {
pr_crit("!clip_vcc->entry (clip_vcc %p)\n", clip_vcc);
return;
}
netif_tx_lock_bh(entry->neigh->dev); /* block clip_start_xmit() */
entry->neigh->used = jiffies;
for (walk = &entry->vccs; *walk; walk = &(*walk)->next)
if (*walk == clip_vcc) {
int error;
*walk = clip_vcc->next; /* atomic */
clip_vcc->entry = NULL;
if (clip_vcc->xoff)
netif_wake_queue(entry->neigh->dev);
if (entry->vccs)
goto out;
entry->expires = jiffies - 1;
/* force resolution or expiration */
error = neigh_update(entry->neigh, NULL, NUD_NONE,
NEIGH_UPDATE_F_ADMIN);
if (error)
pr_crit("neigh_update failed with %d\n", error);
goto out;
}
pr_crit("ATMARP: failed (entry %p, vcc 0x%p)\n", entry, clip_vcc);
out:
netif_tx_unlock_bh(entry->neigh->dev);
}
/* The neighbour entry n->lock is held. */
static int neigh_check_cb(struct neighbour *n)
{
struct atmarp_entry *entry = neighbour_priv(n);
struct clip_vcc *cv;
if (n->ops != &clip_neigh_ops)
return 0;
for (cv = entry->vccs; cv; cv = cv->next) {
unsigned long exp = cv->last_use + cv->idle_timeout;
if (cv->idle_timeout && time_after(jiffies, exp)) {
pr_debug("releasing vcc %p->%p of entry %p\n",
cv, cv->vcc, entry);
vcc_release_async(cv->vcc, -ETIMEDOUT);
}
}
if (entry->vccs || time_before(jiffies, entry->expires))
return 0;
if (atomic_read(&n->refcnt) > 1) {
struct sk_buff *skb;
pr_debug("destruction postponed with ref %d\n",
atomic_read(&n->refcnt));
while ((skb = skb_dequeue(&n->arp_queue)) != NULL)
dev_kfree_skb(skb);
return 0;
}
pr_debug("expired neigh %p\n", n);
return 1;
}
static void idle_timer_check(unsigned long dummy)
{
write_lock(&arp_tbl.lock);
__neigh_for_each_release(&arp_tbl, neigh_check_cb);
mod_timer(&idle_timer, jiffies + CLIP_CHECK_INTERVAL * HZ);
write_unlock(&arp_tbl.lock);
}
static int clip_arp_rcv(struct sk_buff *skb)
{
struct atm_vcc *vcc;
pr_debug("\n");
vcc = ATM_SKB(skb)->vcc;
if (!vcc || !atm_charge(vcc, skb->truesize)) {
dev_kfree_skb_any(skb);
return 0;
}
pr_debug("pushing to %p\n", vcc);
pr_debug("using %p\n", CLIP_VCC(vcc)->old_push);
CLIP_VCC(vcc)->old_push(vcc, skb);
return 0;
}
static const unsigned char llc_oui[] = {
0xaa, /* DSAP: non-ISO */
0xaa, /* SSAP: non-ISO */
0x03, /* Ctrl: Unnumbered Information Command PDU */
0x00, /* OUI: EtherType */
0x00,
0x00
};
static void clip_push(struct atm_vcc *vcc, struct sk_buff *skb)
{
struct clip_vcc *clip_vcc = CLIP_VCC(vcc);
pr_debug("\n");
if (!clip_devs) {
atm_return(vcc, skb->truesize);
kfree_skb(skb);
return;
}
if (!skb) {
pr_debug("removing VCC %p\n", clip_vcc);
if (clip_vcc->entry)
unlink_clip_vcc(clip_vcc);
clip_vcc->old_push(vcc, NULL); /* pass on the bad news */
kfree(clip_vcc);
return;
}
atm_return(vcc, skb->truesize);
skb->dev = clip_vcc->entry ? clip_vcc->entry->neigh->dev : clip_devs;
/* clip_vcc->entry == NULL if we don't have an IP address yet */
if (!skb->dev) {
dev_kfree_skb_any(skb);
return;
}
ATM_SKB(skb)->vcc = vcc;
skb_reset_mac_header(skb);
if (!clip_vcc->encap ||
skb->len < RFC1483LLC_LEN ||
memcmp(skb->data, llc_oui, sizeof(llc_oui)))
skb->protocol = htons(ETH_P_IP);
else {
skb->protocol = ((__be16 *)skb->data)[3];
skb_pull(skb, RFC1483LLC_LEN);
if (skb->protocol == htons(ETH_P_ARP)) {
skb->dev->stats.rx_packets++;
skb->dev->stats.rx_bytes += skb->len;
clip_arp_rcv(skb);
return;
}
}
clip_vcc->last_use = jiffies;
skb->dev->stats.rx_packets++;
skb->dev->stats.rx_bytes += skb->len;
memset(ATM_SKB(skb), 0, sizeof(struct atm_skb_data));
netif_rx(skb);
}
/*
* Note: these spinlocks _must_not_ block on non-SMP. The only goal is that
* clip_pop is atomic with respect to the critical section in clip_start_xmit.
*/
static void clip_pop(struct atm_vcc *vcc, struct sk_buff *skb)
{
struct clip_vcc *clip_vcc = CLIP_VCC(vcc);
struct net_device *dev = skb->dev;
int old;
unsigned long flags;
pr_debug("(vcc %p)\n", vcc);
clip_vcc->old_pop(vcc, skb);
/* skb->dev == NULL in outbound ARP packets */
if (!dev)
return;
spin_lock_irqsave(&PRIV(dev)->xoff_lock, flags);
if (atm_may_send(vcc, 0)) {
old = xchg(&clip_vcc->xoff, 0);
if (old)
netif_wake_queue(dev);
}
spin_unlock_irqrestore(&PRIV(dev)->xoff_lock, flags);
}
static void clip_neigh_solicit(struct neighbour *neigh, struct sk_buff *skb)
{
__be32 *ip = (__be32 *) neigh->primary_key;
pr_debug("(neigh %p, skb %p)\n", neigh, skb);
to_atmarpd(act_need, PRIV(neigh->dev)->number, *ip);
}
static void clip_neigh_error(struct neighbour *neigh, struct sk_buff *skb)
{
#ifndef CONFIG_ATM_CLIP_NO_ICMP
icmp_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_UNREACH, 0);
#endif
kfree_skb(skb);
}
static const struct neigh_ops clip_neigh_ops = {
.family = AF_INET,
.solicit = clip_neigh_solicit,
.error_report = clip_neigh_error,
.output = neigh_direct_output,
.connected_output = neigh_direct_output,
};
static int clip_constructor(struct neighbour *neigh)
{
struct atmarp_entry *entry = neighbour_priv(neigh);
if (neigh->tbl->family != AF_INET)
return -EINVAL;
if (neigh->type != RTN_UNICAST)
return -EINVAL;
neigh->nud_state = NUD_NONE;
neigh->ops = &clip_neigh_ops;
neigh->output = neigh->ops->output;
entry->neigh = neigh;
entry->vccs = NULL;
entry->expires = jiffies - 1;
return 0;
}
/* @@@ copy bh locking from arp.c -- need to bh-enable atm code before */
/*
* We play with the resolve flag: 0 and 1 have the usual meaning, but -1 means
* to allocate the neighbour entry but not to ask atmarpd for resolution. Also,
* don't increment the usage count. This is used to create entries in
* clip_setentry.
*/
static int clip_encap(struct atm_vcc *vcc, int mode)
{
CLIP_VCC(vcc)->encap = mode;
return 0;
}
static netdev_tx_t clip_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct clip_priv *clip_priv = PRIV(dev);
struct dst_entry *dst = skb_dst(skb);
struct atmarp_entry *entry;
struct neighbour *n;
struct atm_vcc *vcc;
struct rtable *rt;
__be32 *daddr;
int old;
unsigned long flags;
pr_debug("(skb %p)\n", skb);
if (!dst) {
pr_err("skb_dst(skb) == NULL\n");
dev_kfree_skb(skb);
dev->stats.tx_dropped++;
return NETDEV_TX_OK;
}
rt = (struct rtable *) dst;
if (rt->rt_gateway)
daddr = &rt->rt_gateway;
else
daddr = &ip_hdr(skb)->daddr;
n = dst_neigh_lookup(dst, daddr);
if (!n) {
pr_err("NO NEIGHBOUR !\n");
dev_kfree_skb(skb);
dev->stats.tx_dropped++;
return NETDEV_TX_OK;
}
entry = neighbour_priv(n);
if (!entry->vccs) {
if (time_after(jiffies, entry->expires)) {
/* should be resolved */
entry->expires = jiffies + ATMARP_RETRY_DELAY * HZ;
to_atmarpd(act_need, PRIV(dev)->number, *((__be32 *)n->primary_key));
}
if (entry->neigh->arp_queue.qlen < ATMARP_MAX_UNRES_PACKETS)
skb_queue_tail(&entry->neigh->arp_queue, skb);
else {
dev_kfree_skb(skb);
dev->stats.tx_dropped++;
}
goto out_release_neigh;
}
pr_debug("neigh %p, vccs %p\n", entry, entry->vccs);
ATM_SKB(skb)->vcc = vcc = entry->vccs->vcc;
pr_debug("using neighbour %p, vcc %p\n", n, vcc);
if (entry->vccs->encap) {
void *here;
here = skb_push(skb, RFC1483LLC_LEN);
memcpy(here, llc_oui, sizeof(llc_oui));
((__be16 *) here)[3] = skb->protocol;
}
atomic_add(skb->truesize, &sk_atm(vcc)->sk_wmem_alloc);
ATM_SKB(skb)->atm_options = vcc->atm_options;
entry->vccs->last_use = jiffies;
pr_debug("atm_skb(%p)->vcc(%p)->dev(%p)\n", skb, vcc, vcc->dev);
old = xchg(&entry->vccs->xoff, 1); /* assume XOFF ... */
if (old) {
pr_warn("XOFF->XOFF transition\n");
goto out_release_neigh;
}
dev->stats.tx_packets++;
dev->stats.tx_bytes += skb->len;
vcc->send(vcc, skb);
if (atm_may_send(vcc, 0)) {
entry->vccs->xoff = 0;
goto out_release_neigh;
}
spin_lock_irqsave(&clip_priv->xoff_lock, flags);
netif_stop_queue(dev); /* XOFF -> throttle immediately */
barrier();
if (!entry->vccs->xoff)
netif_start_queue(dev);
/* Oh, we just raced with clip_pop. netif_start_queue should be
good enough, because nothing should really be asleep because
of the brief netif_stop_queue. If this isn't true or if it
changes, use netif_wake_queue instead. */
spin_unlock_irqrestore(&clip_priv->xoff_lock, flags);
out_release_neigh:
neigh_release(n);
return NETDEV_TX_OK;
}
static int clip_mkip(struct atm_vcc *vcc, int timeout)
{
struct clip_vcc *clip_vcc;
if (!vcc->push)
return -EBADFD;
clip_vcc = kmalloc(sizeof(struct clip_vcc), GFP_KERNEL);
if (!clip_vcc)
return -ENOMEM;
pr_debug("%p vcc %p\n", clip_vcc, vcc);
clip_vcc->vcc = vcc;
vcc->user_back = clip_vcc;
set_bit(ATM_VF_IS_CLIP, &vcc->flags);
clip_vcc->entry = NULL;
clip_vcc->xoff = 0;
clip_vcc->encap = 1;
clip_vcc->last_use = jiffies;
clip_vcc->idle_timeout = timeout * HZ;
clip_vcc->old_push = vcc->push;
clip_vcc->old_pop = vcc->pop;
vcc->push = clip_push;
vcc->pop = clip_pop;
/* re-process everything received between connection setup and MKIP */
vcc_process_recv_queue(vcc);
return 0;
}
static int clip_setentry(struct atm_vcc *vcc, __be32 ip)
{
struct neighbour *neigh;
struct atmarp_entry *entry;
int error;
struct clip_vcc *clip_vcc;
struct rtable *rt;
if (vcc->push != clip_push) {
pr_warn("non-CLIP VCC\n");
return -EBADF;
}
clip_vcc = CLIP_VCC(vcc);
if (!ip) {
if (!clip_vcc->entry) {
pr_err("hiding hidden ATMARP entry\n");
return 0;
}
pr_debug("remove\n");
unlink_clip_vcc(clip_vcc);
return 0;
}
rt = ip_route_output(&init_net, ip, 0, 1, 0);
if (IS_ERR(rt))
return PTR_ERR(rt);
neigh = __neigh_lookup(&arp_tbl, &ip, rt->dst.dev, 1);
ip_rt_put(rt);
if (!neigh)
return -ENOMEM;
entry = neighbour_priv(neigh);
if (entry != clip_vcc->entry) {
if (!clip_vcc->entry)
pr_debug("add\n");
else {
pr_debug("update\n");
unlink_clip_vcc(clip_vcc);
}
link_vcc(clip_vcc, entry);
}
error = neigh_update(neigh, llc_oui, NUD_PERMANENT,
NEIGH_UPDATE_F_OVERRIDE | NEIGH_UPDATE_F_ADMIN);
neigh_release(neigh);
return error;
}
static const struct net_device_ops clip_netdev_ops = {
.ndo_start_xmit = clip_start_xmit,
.ndo_neigh_construct = clip_constructor,
};
static void clip_setup(struct net_device *dev)
{
dev->netdev_ops = &clip_netdev_ops;
dev->type = ARPHRD_ATM;
dev->neigh_priv_len = sizeof(struct atmarp_entry);
dev->hard_header_len = RFC1483LLC_LEN;
dev->mtu = RFC1626_MTU;
dev->tx_queue_len = 100; /* "normal" queue (packets) */
/* When using a "real" qdisc, the qdisc determines the queue */
/* length. tx_queue_len is only used for the default case, */
/* without any more elaborate queuing. 100 is a reasonable */
/* compromise between decent burst-tolerance and protection */
/* against memory hogs. */
netif_keep_dst(dev);
}
static int clip_create(int number)
{
struct net_device *dev;
struct clip_priv *clip_priv;
int error;
if (number != -1) {
for (dev = clip_devs; dev; dev = PRIV(dev)->next)
if (PRIV(dev)->number == number)
return -EEXIST;
} else {
number = 0;
for (dev = clip_devs; dev; dev = PRIV(dev)->next)
if (PRIV(dev)->number >= number)
number = PRIV(dev)->number + 1;
}
dev = alloc_netdev(sizeof(struct clip_priv), "", NET_NAME_UNKNOWN,
clip_setup);
if (!dev)
return -ENOMEM;
clip_priv = PRIV(dev);
sprintf(dev->name, "atm%d", number);
spin_lock_init(&clip_priv->xoff_lock);
clip_priv->number = number;
error = register_netdev(dev);
if (error) {
free_netdev(dev);
return error;
}
clip_priv->next = clip_devs;
clip_devs = dev;
pr_debug("registered (net:%s)\n", dev->name);
return number;
}
static int clip_device_event(struct notifier_block *this, unsigned long event,
void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
if (!net_eq(dev_net(dev), &init_net))
return NOTIFY_DONE;
if (event == NETDEV_UNREGISTER)
return NOTIFY_DONE;
/* ignore non-CLIP devices */
if (dev->type != ARPHRD_ATM || dev->netdev_ops != &clip_netdev_ops)
return NOTIFY_DONE;
switch (event) {
case NETDEV_UP:
pr_debug("NETDEV_UP\n");
to_atmarpd(act_up, PRIV(dev)->number, 0);
break;
case NETDEV_GOING_DOWN:
pr_debug("NETDEV_DOWN\n");
to_atmarpd(act_down, PRIV(dev)->number, 0);
break;
case NETDEV_CHANGE:
case NETDEV_CHANGEMTU:
pr_debug("NETDEV_CHANGE*\n");
to_atmarpd(act_change, PRIV(dev)->number, 0);
break;
}
return NOTIFY_DONE;
}
static int clip_inet_event(struct notifier_block *this, unsigned long event,
void *ifa)
{
struct in_device *in_dev;
struct netdev_notifier_info info;
in_dev = ((struct in_ifaddr *)ifa)->ifa_dev;
/*
* Transitions are of the down-change-up type, so it's sufficient to
* handle the change on up.
*/
if (event != NETDEV_UP)
return NOTIFY_DONE;
netdev_notifier_info_init(&info, in_dev->dev);
return clip_device_event(this, NETDEV_CHANGE, &info);
}
static struct notifier_block clip_dev_notifier = {
.notifier_call = clip_device_event,
};
static struct notifier_block clip_inet_notifier = {
.notifier_call = clip_inet_event,
};
static void atmarpd_close(struct atm_vcc *vcc)
{
pr_debug("\n");
rtnl_lock();
atmarpd = NULL;
skb_queue_purge(&sk_atm(vcc)->sk_receive_queue);
rtnl_unlock();
pr_debug("(done)\n");
module_put(THIS_MODULE);
}
static struct atmdev_ops atmarpd_dev_ops = {
.close = atmarpd_close
};
static struct atm_dev atmarpd_dev = {
.ops = &atmarpd_dev_ops,
.type = "arpd",
.number = 999,
.lock = __SPIN_LOCK_UNLOCKED(atmarpd_dev.lock)
};
static int atm_init_atmarp(struct atm_vcc *vcc)
{
rtnl_lock();
if (atmarpd) {
rtnl_unlock();
return -EADDRINUSE;
}
mod_timer(&idle_timer, jiffies + CLIP_CHECK_INTERVAL * HZ);
atmarpd = vcc;
set_bit(ATM_VF_META, &vcc->flags);
set_bit(ATM_VF_READY, &vcc->flags);
/* allow replies and avoid getting closed if signaling dies */
vcc->dev = &atmarpd_dev;
vcc_insert_socket(sk_atm(vcc));
vcc->push = NULL;
vcc->pop = NULL; /* crash */
vcc->push_oam = NULL; /* crash */
rtnl_unlock();
return 0;
}
static int clip_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct atm_vcc *vcc = ATM_SD(sock);
int err = 0;
switch (cmd) {
case SIOCMKCLIP:
case ATMARPD_CTRL:
case ATMARP_MKIP:
case ATMARP_SETENTRY:
case ATMARP_ENCAP:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
break;
default:
return -ENOIOCTLCMD;
}
switch (cmd) {
case SIOCMKCLIP:
err = clip_create(arg);
break;
case ATMARPD_CTRL:
err = atm_init_atmarp(vcc);
if (!err) {
sock->state = SS_CONNECTED;
__module_get(THIS_MODULE);
}
break;
case ATMARP_MKIP:
err = clip_mkip(vcc, arg);
break;
case ATMARP_SETENTRY:
err = clip_setentry(vcc, (__force __be32)arg);
break;
case ATMARP_ENCAP:
err = clip_encap(vcc, arg);
break;
}
return err;
}
static struct atm_ioctl clip_ioctl_ops = {
.owner = THIS_MODULE,
.ioctl = clip_ioctl,
};
#ifdef CONFIG_PROC_FS
static void svc_addr(struct seq_file *seq, struct sockaddr_atmsvc *addr)
{
static int code[] = { 1, 2, 10, 6, 1, 0 };
static int e164[] = { 1, 8, 4, 6, 1, 0 };
if (*addr->sas_addr.pub) {
seq_printf(seq, "%s", addr->sas_addr.pub);
if (*addr->sas_addr.prv)
seq_putc(seq, '+');
} else if (!*addr->sas_addr.prv) {
seq_printf(seq, "%s", "(none)");
return;
}
if (*addr->sas_addr.prv) {
unsigned char *prv = addr->sas_addr.prv;
int *fields;
int i, j;
fields = *prv == ATM_AFI_E164 ? e164 : code;
for (i = 0; fields[i]; i++) {
for (j = fields[i]; j; j--)
seq_printf(seq, "%02X", *prv++);
if (fields[i + 1])
seq_putc(seq, '.');
}
}
}
/* This means the neighbour entry has no attached VCC objects. */
#define SEQ_NO_VCC_TOKEN ((void *) 2)
static void atmarp_info(struct seq_file *seq, struct neighbour *n,
struct atmarp_entry *entry, struct clip_vcc *clip_vcc)
{
struct net_device *dev = n->dev;
unsigned long exp;
char buf[17];
int svc, llc, off;
svc = ((clip_vcc == SEQ_NO_VCC_TOKEN) ||
(sk_atm(clip_vcc->vcc)->sk_family == AF_ATMSVC));
llc = ((clip_vcc == SEQ_NO_VCC_TOKEN) || clip_vcc->encap);
if (clip_vcc == SEQ_NO_VCC_TOKEN)
exp = entry->neigh->used;
else
exp = clip_vcc->last_use;
exp = (jiffies - exp) / HZ;
seq_printf(seq, "%-6s%-4s%-4s%5ld ",
dev->name, svc ? "SVC" : "PVC", llc ? "LLC" : "NULL", exp);
off = scnprintf(buf, sizeof(buf) - 1, "%pI4", n->primary_key);
while (off < 16)
buf[off++] = ' ';
buf[off] = '\0';
seq_printf(seq, "%s", buf);
if (clip_vcc == SEQ_NO_VCC_TOKEN) {
if (time_before(jiffies, entry->expires))
seq_printf(seq, "(resolving)\n");
else
seq_printf(seq, "(expired, ref %d)\n",
atomic_read(&entry->neigh->refcnt));
} else if (!svc) {
seq_printf(seq, "%d.%d.%d\n",
clip_vcc->vcc->dev->number,
clip_vcc->vcc->vpi, clip_vcc->vcc->vci);
} else {
svc_addr(seq, &clip_vcc->vcc->remote);
seq_putc(seq, '\n');
}
}
struct clip_seq_state {
/* This member must be first. */
struct neigh_seq_state ns;
/* Local to clip specific iteration. */
struct clip_vcc *vcc;
};
static struct clip_vcc *clip_seq_next_vcc(struct atmarp_entry *e,
struct clip_vcc *curr)
{
if (!curr) {
curr = e->vccs;
if (!curr)
return SEQ_NO_VCC_TOKEN;
return curr;
}
if (curr == SEQ_NO_VCC_TOKEN)
return NULL;
curr = curr->next;
return curr;
}
static void *clip_seq_vcc_walk(struct clip_seq_state *state,
struct atmarp_entry *e, loff_t * pos)
{
struct clip_vcc *vcc = state->vcc;
vcc = clip_seq_next_vcc(e, vcc);
if (vcc && pos != NULL) {
while (*pos) {
vcc = clip_seq_next_vcc(e, vcc);
if (!vcc)
break;
--(*pos);
}
}
state->vcc = vcc;
return vcc;
}
static void *clip_seq_sub_iter(struct neigh_seq_state *_state,
struct neighbour *n, loff_t * pos)
{
struct clip_seq_state *state = (struct clip_seq_state *)_state;
if (n->dev->type != ARPHRD_ATM)
return NULL;
return clip_seq_vcc_walk(state, neighbour_priv(n), pos);
}
static void *clip_seq_start(struct seq_file *seq, loff_t * pos)
{
struct clip_seq_state *state = seq->private;
state->ns.neigh_sub_iter = clip_seq_sub_iter;
return neigh_seq_start(seq, pos, &arp_tbl, NEIGH_SEQ_NEIGH_ONLY);
}
static int clip_seq_show(struct seq_file *seq, void *v)
{
static char atm_arp_banner[] =
"IPitf TypeEncp Idle IP address ATM address\n";
if (v == SEQ_START_TOKEN) {
seq_puts(seq, atm_arp_banner);
} else {
struct clip_seq_state *state = seq->private;
struct clip_vcc *vcc = state->vcc;
struct neighbour *n = v;
atmarp_info(seq, n, neighbour_priv(n), vcc);
}
return 0;
}
static const struct seq_operations arp_seq_ops = {
.start = clip_seq_start,
.next = neigh_seq_next,
.stop = neigh_seq_stop,
.show = clip_seq_show,
};
static int arp_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &arp_seq_ops,
sizeof(struct clip_seq_state));
}
static const struct file_operations arp_seq_fops = {
.open = arp_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
.owner = THIS_MODULE
};
#endif
static void atm_clip_exit_noproc(void);
static int __init atm_clip_init(void)
{
register_atm_ioctl(&clip_ioctl_ops);
register_netdevice_notifier(&clip_dev_notifier);
register_inetaddr_notifier(&clip_inet_notifier);
setup_timer(&idle_timer, idle_timer_check, 0);
#ifdef CONFIG_PROC_FS
{
struct proc_dir_entry *p;
p = proc_create("arp", S_IRUGO, atm_proc_root, &arp_seq_fops);
if (!p) {
pr_err("Unable to initialize /proc/net/atm/arp\n");
atm_clip_exit_noproc();
return -ENOMEM;
}
}
#endif
return 0;
}
static void atm_clip_exit_noproc(void)
{
struct net_device *dev, *next;
unregister_inetaddr_notifier(&clip_inet_notifier);
unregister_netdevice_notifier(&clip_dev_notifier);
deregister_atm_ioctl(&clip_ioctl_ops);
/* First, stop the idle timer, so it stops banging
* on the table.
*/
del_timer_sync(&idle_timer);
dev = clip_devs;
while (dev) {
next = PRIV(dev)->next;
unregister_netdev(dev);
free_netdev(dev);
dev = next;
}
}
static void __exit atm_clip_exit(void)
{
remove_proc_entry("arp", atm_proc_root);
atm_clip_exit_noproc();
}
module_init(atm_clip_init);
module_exit(atm_clip_exit);
MODULE_AUTHOR("Werner Almesberger");
MODULE_DESCRIPTION("Classical/IP over ATM interface");
MODULE_LICENSE("GPL");
| gpl-2.0 |
jooojub/SPC | lib/test-kstrtox.c | 1062 | 17796 | #include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#define for_each_test(i, test) \
for (i = 0; i < ARRAY_SIZE(test); i++)
struct test_fail {
const char *str;
unsigned int base;
};
#define DEFINE_TEST_FAIL(test) \
const struct test_fail test[] __initconst
#define DECLARE_TEST_OK(type, test_type) \
test_type { \
const char *str; \
unsigned int base; \
type expected_res; \
}
#define DEFINE_TEST_OK(type, test) \
const type test[] __initconst
#define TEST_FAIL(fn, type, fmt, test) \
{ \
unsigned int i; \
\
for_each_test(i, test) { \
const struct test_fail *t = &test[i]; \
type tmp; \
int rv; \
\
tmp = 0; \
rv = fn(t->str, t->base, &tmp); \
if (rv >= 0) { \
WARN(1, "str '%s', base %u, expected -E, got %d/" fmt "\n", \
t->str, t->base, rv, tmp); \
continue; \
} \
} \
}
#define TEST_OK(fn, type, fmt, test) \
{ \
unsigned int i; \
\
for_each_test(i, test) { \
const typeof(test[0]) *t = &test[i]; \
type res; \
int rv; \
\
rv = fn(t->str, t->base, &res); \
if (rv != 0) { \
WARN(1, "str '%s', base %u, expected 0/" fmt ", got %d\n", \
t->str, t->base, t->expected_res, rv); \
continue; \
} \
if (res != t->expected_res) { \
WARN(1, "str '%s', base %u, expected " fmt ", got " fmt "\n", \
t->str, t->base, t->expected_res, res); \
continue; \
} \
} \
}
static void __init test_kstrtoull_ok(void)
{
DECLARE_TEST_OK(unsigned long long, struct test_ull);
static DEFINE_TEST_OK(struct test_ull, test_ull_ok) = {
{"0", 10, 0ULL},
{"1", 10, 1ULL},
{"127", 10, 127ULL},
{"128", 10, 128ULL},
{"129", 10, 129ULL},
{"255", 10, 255ULL},
{"256", 10, 256ULL},
{"257", 10, 257ULL},
{"32767", 10, 32767ULL},
{"32768", 10, 32768ULL},
{"32769", 10, 32769ULL},
{"65535", 10, 65535ULL},
{"65536", 10, 65536ULL},
{"65537", 10, 65537ULL},
{"2147483647", 10, 2147483647ULL},
{"2147483648", 10, 2147483648ULL},
{"2147483649", 10, 2147483649ULL},
{"4294967295", 10, 4294967295ULL},
{"4294967296", 10, 4294967296ULL},
{"4294967297", 10, 4294967297ULL},
{"9223372036854775807", 10, 9223372036854775807ULL},
{"9223372036854775808", 10, 9223372036854775808ULL},
{"9223372036854775809", 10, 9223372036854775809ULL},
{"18446744073709551614", 10, 18446744073709551614ULL},
{"18446744073709551615", 10, 18446744073709551615ULL},
{"00", 8, 00ULL},
{"01", 8, 01ULL},
{"0177", 8, 0177ULL},
{"0200", 8, 0200ULL},
{"0201", 8, 0201ULL},
{"0377", 8, 0377ULL},
{"0400", 8, 0400ULL},
{"0401", 8, 0401ULL},
{"077777", 8, 077777ULL},
{"0100000", 8, 0100000ULL},
{"0100001", 8, 0100001ULL},
{"0177777", 8, 0177777ULL},
{"0200000", 8, 0200000ULL},
{"0200001", 8, 0200001ULL},
{"017777777777", 8, 017777777777ULL},
{"020000000000", 8, 020000000000ULL},
{"020000000001", 8, 020000000001ULL},
{"037777777777", 8, 037777777777ULL},
{"040000000000", 8, 040000000000ULL},
{"040000000001", 8, 040000000001ULL},
{"0777777777777777777777", 8, 0777777777777777777777ULL},
{"01000000000000000000000", 8, 01000000000000000000000ULL},
{"01000000000000000000001", 8, 01000000000000000000001ULL},
{"01777777777777777777776", 8, 01777777777777777777776ULL},
{"01777777777777777777777", 8, 01777777777777777777777ULL},
{"0x0", 16, 0x0ULL},
{"0x1", 16, 0x1ULL},
{"0x7f", 16, 0x7fULL},
{"0x80", 16, 0x80ULL},
{"0x81", 16, 0x81ULL},
{"0xff", 16, 0xffULL},
{"0x100", 16, 0x100ULL},
{"0x101", 16, 0x101ULL},
{"0x7fff", 16, 0x7fffULL},
{"0x8000", 16, 0x8000ULL},
{"0x8001", 16, 0x8001ULL},
{"0xffff", 16, 0xffffULL},
{"0x10000", 16, 0x10000ULL},
{"0x10001", 16, 0x10001ULL},
{"0x7fffffff", 16, 0x7fffffffULL},
{"0x80000000", 16, 0x80000000ULL},
{"0x80000001", 16, 0x80000001ULL},
{"0xffffffff", 16, 0xffffffffULL},
{"0x100000000", 16, 0x100000000ULL},
{"0x100000001", 16, 0x100000001ULL},
{"0x7fffffffffffffff", 16, 0x7fffffffffffffffULL},
{"0x8000000000000000", 16, 0x8000000000000000ULL},
{"0x8000000000000001", 16, 0x8000000000000001ULL},
{"0xfffffffffffffffe", 16, 0xfffffffffffffffeULL},
{"0xffffffffffffffff", 16, 0xffffffffffffffffULL},
{"0\n", 0, 0ULL},
};
TEST_OK(kstrtoull, unsigned long long, "%llu", test_ull_ok);
}
static void __init test_kstrtoull_fail(void)
{
static DEFINE_TEST_FAIL(test_ull_fail) = {
{"", 0},
{"", 8},
{"", 10},
{"", 16},
{"\n", 0},
{"\n", 8},
{"\n", 10},
{"\n", 16},
{"\n0", 0},
{"\n0", 8},
{"\n0", 10},
{"\n0", 16},
{"+", 0},
{"+", 8},
{"+", 10},
{"+", 16},
{"-", 0},
{"-", 8},
{"-", 10},
{"-", 16},
{"0x", 0},
{"0x", 16},
{"0X", 0},
{"0X", 16},
{"0 ", 0},
{"1+", 0},
{"1-", 0},
{" 2", 0},
/* base autodetection */
{"0x0z", 0},
{"0z", 0},
{"a", 0},
/* digit >= base */
{"2", 2},
{"8", 8},
{"a", 10},
{"A", 10},
{"g", 16},
{"G", 16},
/* overflow */
{"10000000000000000000000000000000000000000000000000000000000000000", 2},
{"2000000000000000000000", 8},
{"18446744073709551616", 10},
{"10000000000000000", 16},
/* negative */
{"-0", 0},
{"-0", 8},
{"-0", 10},
{"-0", 16},
{"-1", 0},
{"-1", 8},
{"-1", 10},
{"-1", 16},
/* sign is first character if any */
{"-+1", 0},
{"-+1", 8},
{"-+1", 10},
{"-+1", 16},
/* nothing after \n */
{"0\n0", 0},
{"0\n0", 8},
{"0\n0", 10},
{"0\n0", 16},
{"0\n+", 0},
{"0\n+", 8},
{"0\n+", 10},
{"0\n+", 16},
{"0\n-", 0},
{"0\n-", 8},
{"0\n-", 10},
{"0\n-", 16},
{"0\n ", 0},
{"0\n ", 8},
{"0\n ", 10},
{"0\n ", 16},
};
TEST_FAIL(kstrtoull, unsigned long long, "%llu", test_ull_fail);
}
static void __init test_kstrtoll_ok(void)
{
DECLARE_TEST_OK(long long, struct test_ll);
static DEFINE_TEST_OK(struct test_ll, test_ll_ok) = {
{"0", 10, 0LL},
{"1", 10, 1LL},
{"127", 10, 127LL},
{"128", 10, 128LL},
{"129", 10, 129LL},
{"255", 10, 255LL},
{"256", 10, 256LL},
{"257", 10, 257LL},
{"32767", 10, 32767LL},
{"32768", 10, 32768LL},
{"32769", 10, 32769LL},
{"65535", 10, 65535LL},
{"65536", 10, 65536LL},
{"65537", 10, 65537LL},
{"2147483647", 10, 2147483647LL},
{"2147483648", 10, 2147483648LL},
{"2147483649", 10, 2147483649LL},
{"4294967295", 10, 4294967295LL},
{"4294967296", 10, 4294967296LL},
{"4294967297", 10, 4294967297LL},
{"9223372036854775807", 10, 9223372036854775807LL},
{"-1", 10, -1LL},
{"-2", 10, -2LL},
{"-9223372036854775808", 10, LLONG_MIN},
};
TEST_OK(kstrtoll, long long, "%lld", test_ll_ok);
}
static void __init test_kstrtoll_fail(void)
{
static DEFINE_TEST_FAIL(test_ll_fail) = {
{"9223372036854775808", 10},
{"9223372036854775809", 10},
{"18446744073709551614", 10},
{"18446744073709551615", 10},
{"-9223372036854775809", 10},
{"-18446744073709551614", 10},
{"-18446744073709551615", 10},
/* negative zero isn't an integer in Linux */
{"-0", 0},
{"-0", 8},
{"-0", 10},
{"-0", 16},
/* sign is first character if any */
{"-+1", 0},
{"-+1", 8},
{"-+1", 10},
{"-+1", 16},
};
TEST_FAIL(kstrtoll, long long, "%lld", test_ll_fail);
}
static void __init test_kstrtou64_ok(void)
{
DECLARE_TEST_OK(u64, struct test_u64);
static DEFINE_TEST_OK(struct test_u64, test_u64_ok) = {
{"0", 10, 0},
{"1", 10, 1},
{"126", 10, 126},
{"127", 10, 127},
{"128", 10, 128},
{"129", 10, 129},
{"254", 10, 254},
{"255", 10, 255},
{"256", 10, 256},
{"257", 10, 257},
{"32766", 10, 32766},
{"32767", 10, 32767},
{"32768", 10, 32768},
{"32769", 10, 32769},
{"65534", 10, 65534},
{"65535", 10, 65535},
{"65536", 10, 65536},
{"65537", 10, 65537},
{"2147483646", 10, 2147483646},
{"2147483647", 10, 2147483647},
{"2147483648", 10, 2147483648ULL},
{"2147483649", 10, 2147483649ULL},
{"4294967294", 10, 4294967294ULL},
{"4294967295", 10, 4294967295ULL},
{"4294967296", 10, 4294967296ULL},
{"4294967297", 10, 4294967297ULL},
{"9223372036854775806", 10, 9223372036854775806ULL},
{"9223372036854775807", 10, 9223372036854775807ULL},
{"9223372036854775808", 10, 9223372036854775808ULL},
{"9223372036854775809", 10, 9223372036854775809ULL},
{"18446744073709551614", 10, 18446744073709551614ULL},
{"18446744073709551615", 10, 18446744073709551615ULL},
};
TEST_OK(kstrtou64, u64, "%llu", test_u64_ok);
}
static void __init test_kstrtou64_fail(void)
{
static DEFINE_TEST_FAIL(test_u64_fail) = {
{"-2", 10},
{"-1", 10},
{"18446744073709551616", 10},
{"18446744073709551617", 10},
};
TEST_FAIL(kstrtou64, u64, "%llu", test_u64_fail);
}
static void __init test_kstrtos64_ok(void)
{
DECLARE_TEST_OK(s64, struct test_s64);
static DEFINE_TEST_OK(struct test_s64, test_s64_ok) = {
{"-128", 10, -128},
{"-127", 10, -127},
{"-1", 10, -1},
{"0", 10, 0},
{"1", 10, 1},
{"126", 10, 126},
{"127", 10, 127},
{"128", 10, 128},
{"129", 10, 129},
{"254", 10, 254},
{"255", 10, 255},
{"256", 10, 256},
{"257", 10, 257},
{"32766", 10, 32766},
{"32767", 10, 32767},
{"32768", 10, 32768},
{"32769", 10, 32769},
{"65534", 10, 65534},
{"65535", 10, 65535},
{"65536", 10, 65536},
{"65537", 10, 65537},
{"2147483646", 10, 2147483646},
{"2147483647", 10, 2147483647},
{"2147483648", 10, 2147483648LL},
{"2147483649", 10, 2147483649LL},
{"4294967294", 10, 4294967294LL},
{"4294967295", 10, 4294967295LL},
{"4294967296", 10, 4294967296LL},
{"4294967297", 10, 4294967297LL},
{"9223372036854775806", 10, 9223372036854775806LL},
{"9223372036854775807", 10, 9223372036854775807LL},
};
TEST_OK(kstrtos64, s64, "%lld", test_s64_ok);
}
static void __init test_kstrtos64_fail(void)
{
static DEFINE_TEST_FAIL(test_s64_fail) = {
{"9223372036854775808", 10},
{"9223372036854775809", 10},
{"18446744073709551614", 10},
{"18446744073709551615", 10},
{"18446744073709551616", 10},
{"18446744073709551617", 10},
};
TEST_FAIL(kstrtos64, s64, "%lld", test_s64_fail);
}
static void __init test_kstrtou32_ok(void)
{
DECLARE_TEST_OK(u32, struct test_u32);
static DEFINE_TEST_OK(struct test_u32, test_u32_ok) = {
{"0", 10, 0},
{"1", 10, 1},
{"126", 10, 126},
{"127", 10, 127},
{"128", 10, 128},
{"129", 10, 129},
{"254", 10, 254},
{"255", 10, 255},
{"256", 10, 256},
{"257", 10, 257},
{"32766", 10, 32766},
{"32767", 10, 32767},
{"32768", 10, 32768},
{"32769", 10, 32769},
{"65534", 10, 65534},
{"65535", 10, 65535},
{"65536", 10, 65536},
{"65537", 10, 65537},
{"2147483646", 10, 2147483646},
{"2147483647", 10, 2147483647},
{"2147483648", 10, 2147483648U},
{"2147483649", 10, 2147483649U},
{"4294967294", 10, 4294967294U},
{"4294967295", 10, 4294967295U},
};
TEST_OK(kstrtou32, u32, "%u", test_u32_ok);
}
static void __init test_kstrtou32_fail(void)
{
static DEFINE_TEST_FAIL(test_u32_fail) = {
{"-2", 10},
{"-1", 10},
{"4294967296", 10},
{"4294967297", 10},
{"9223372036854775806", 10},
{"9223372036854775807", 10},
{"9223372036854775808", 10},
{"9223372036854775809", 10},
{"18446744073709551614", 10},
{"18446744073709551615", 10},
{"18446744073709551616", 10},
{"18446744073709551617", 10},
};
TEST_FAIL(kstrtou32, u32, "%u", test_u32_fail);
}
static void __init test_kstrtos32_ok(void)
{
DECLARE_TEST_OK(s32, struct test_s32);
static DEFINE_TEST_OK(struct test_s32, test_s32_ok) = {
{"-128", 10, -128},
{"-127", 10, -127},
{"-1", 10, -1},
{"0", 10, 0},
{"1", 10, 1},
{"126", 10, 126},
{"127", 10, 127},
{"128", 10, 128},
{"129", 10, 129},
{"254", 10, 254},
{"255", 10, 255},
{"256", 10, 256},
{"257", 10, 257},
{"32766", 10, 32766},
{"32767", 10, 32767},
{"32768", 10, 32768},
{"32769", 10, 32769},
{"65534", 10, 65534},
{"65535", 10, 65535},
{"65536", 10, 65536},
{"65537", 10, 65537},
{"2147483646", 10, 2147483646},
{"2147483647", 10, 2147483647},
};
TEST_OK(kstrtos32, s32, "%d", test_s32_ok);
}
static void __init test_kstrtos32_fail(void)
{
static DEFINE_TEST_FAIL(test_s32_fail) = {
{"2147483648", 10},
{"2147483649", 10},
{"4294967294", 10},
{"4294967295", 10},
{"4294967296", 10},
{"4294967297", 10},
{"9223372036854775806", 10},
{"9223372036854775807", 10},
{"9223372036854775808", 10},
{"9223372036854775809", 10},
{"18446744073709551614", 10},
{"18446744073709551615", 10},
{"18446744073709551616", 10},
{"18446744073709551617", 10},
};
TEST_FAIL(kstrtos32, s32, "%d", test_s32_fail);
}
static void __init test_kstrtou16_ok(void)
{
DECLARE_TEST_OK(u16, struct test_u16);
static DEFINE_TEST_OK(struct test_u16, test_u16_ok) = {
{"0", 10, 0},
{"1", 10, 1},
{"126", 10, 126},
{"127", 10, 127},
{"128", 10, 128},
{"129", 10, 129},
{"254", 10, 254},
{"255", 10, 255},
{"256", 10, 256},
{"257", 10, 257},
{"32766", 10, 32766},
{"32767", 10, 32767},
{"32768", 10, 32768},
{"32769", 10, 32769},
{"65534", 10, 65534},
{"65535", 10, 65535},
};
TEST_OK(kstrtou16, u16, "%hu", test_u16_ok);
}
static void __init test_kstrtou16_fail(void)
{
static DEFINE_TEST_FAIL(test_u16_fail) = {
{"-2", 10},
{"-1", 10},
{"65536", 10},
{"65537", 10},
{"2147483646", 10},
{"2147483647", 10},
{"2147483648", 10},
{"2147483649", 10},
{"4294967294", 10},
{"4294967295", 10},
{"4294967296", 10},
{"4294967297", 10},
{"9223372036854775806", 10},
{"9223372036854775807", 10},
{"9223372036854775808", 10},
{"9223372036854775809", 10},
{"18446744073709551614", 10},
{"18446744073709551615", 10},
{"18446744073709551616", 10},
{"18446744073709551617", 10},
};
TEST_FAIL(kstrtou16, u16, "%hu", test_u16_fail);
}
static void __init test_kstrtos16_ok(void)
{
DECLARE_TEST_OK(s16, struct test_s16);
static DEFINE_TEST_OK(struct test_s16, test_s16_ok) = {
{"-130", 10, -130},
{"-129", 10, -129},
{"-128", 10, -128},
{"-127", 10, -127},
{"-1", 10, -1},
{"0", 10, 0},
{"1", 10, 1},
{"126", 10, 126},
{"127", 10, 127},
{"128", 10, 128},
{"129", 10, 129},
{"254", 10, 254},
{"255", 10, 255},
{"256", 10, 256},
{"257", 10, 257},
{"32766", 10, 32766},
{"32767", 10, 32767},
};
TEST_OK(kstrtos16, s16, "%hd", test_s16_ok);
}
static void __init test_kstrtos16_fail(void)
{
static DEFINE_TEST_FAIL(test_s16_fail) = {
{"32768", 10},
{"32769", 10},
{"65534", 10},
{"65535", 10},
{"65536", 10},
{"65537", 10},
{"2147483646", 10},
{"2147483647", 10},
{"2147483648", 10},
{"2147483649", 10},
{"4294967294", 10},
{"4294967295", 10},
{"4294967296", 10},
{"4294967297", 10},
{"9223372036854775806", 10},
{"9223372036854775807", 10},
{"9223372036854775808", 10},
{"9223372036854775809", 10},
{"18446744073709551614", 10},
{"18446744073709551615", 10},
{"18446744073709551616", 10},
{"18446744073709551617", 10},
};
TEST_FAIL(kstrtos16, s16, "%hd", test_s16_fail);
}
static void __init test_kstrtou8_ok(void)
{
DECLARE_TEST_OK(u8, struct test_u8);
static DEFINE_TEST_OK(struct test_u8, test_u8_ok) = {
{"0", 10, 0},
{"1", 10, 1},
{"126", 10, 126},
{"127", 10, 127},
{"128", 10, 128},
{"129", 10, 129},
{"254", 10, 254},
{"255", 10, 255},
};
TEST_OK(kstrtou8, u8, "%hhu", test_u8_ok);
}
static void __init test_kstrtou8_fail(void)
{
static DEFINE_TEST_FAIL(test_u8_fail) = {
{"-2", 10},
{"-1", 10},
{"256", 10},
{"257", 10},
{"32766", 10},
{"32767", 10},
{"32768", 10},
{"32769", 10},
{"65534", 10},
{"65535", 10},
{"65536", 10},
{"65537", 10},
{"2147483646", 10},
{"2147483647", 10},
{"2147483648", 10},
{"2147483649", 10},
{"4294967294", 10},
{"4294967295", 10},
{"4294967296", 10},
{"4294967297", 10},
{"9223372036854775806", 10},
{"9223372036854775807", 10},
{"9223372036854775808", 10},
{"9223372036854775809", 10},
{"18446744073709551614", 10},
{"18446744073709551615", 10},
{"18446744073709551616", 10},
{"18446744073709551617", 10},
};
TEST_FAIL(kstrtou8, u8, "%hhu", test_u8_fail);
}
static void __init test_kstrtos8_ok(void)
{
DECLARE_TEST_OK(s8, struct test_s8);
static DEFINE_TEST_OK(struct test_s8, test_s8_ok) = {
{"-128", 10, -128},
{"-127", 10, -127},
{"-1", 10, -1},
{"0", 10, 0},
{"1", 10, 1},
{"126", 10, 126},
{"127", 10, 127},
};
TEST_OK(kstrtos8, s8, "%hhd", test_s8_ok);
}
static void __init test_kstrtos8_fail(void)
{
static DEFINE_TEST_FAIL(test_s8_fail) = {
{"-130", 10},
{"-129", 10},
{"128", 10},
{"129", 10},
{"254", 10},
{"255", 10},
{"256", 10},
{"257", 10},
{"32766", 10},
{"32767", 10},
{"32768", 10},
{"32769", 10},
{"65534", 10},
{"65535", 10},
{"65536", 10},
{"65537", 10},
{"2147483646", 10},
{"2147483647", 10},
{"2147483648", 10},
{"2147483649", 10},
{"4294967294", 10},
{"4294967295", 10},
{"4294967296", 10},
{"4294967297", 10},
{"9223372036854775806", 10},
{"9223372036854775807", 10},
{"9223372036854775808", 10},
{"9223372036854775809", 10},
{"18446744073709551614", 10},
{"18446744073709551615", 10},
{"18446744073709551616", 10},
{"18446744073709551617", 10},
};
TEST_FAIL(kstrtos8, s8, "%hhd", test_s8_fail);
}
static int __init test_kstrtox_init(void)
{
test_kstrtoull_ok();
test_kstrtoull_fail();
test_kstrtoll_ok();
test_kstrtoll_fail();
test_kstrtou64_ok();
test_kstrtou64_fail();
test_kstrtos64_ok();
test_kstrtos64_fail();
test_kstrtou32_ok();
test_kstrtou32_fail();
test_kstrtos32_ok();
test_kstrtos32_fail();
test_kstrtou16_ok();
test_kstrtou16_fail();
test_kstrtos16_ok();
test_kstrtos16_fail();
test_kstrtou8_ok();
test_kstrtou8_fail();
test_kstrtos8_ok();
test_kstrtos8_fail();
return -EINVAL;
}
module_init(test_kstrtox_init);
MODULE_LICENSE("Dual BSD/GPL");
| gpl-2.0 |
faux123/android_kernel_sony_msm8974ab | net/rxrpc/af_rxrpc.c | 1830 | 20967 | /* AF_RXRPC implementation
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public 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/net.h>
#include <linux/slab.h>
#include <linux/skbuff.h>
#include <linux/poll.h>
#include <linux/proc_fs.h>
#include <linux/key-type.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/af_rxrpc.h>
#include "ar-internal.h"
MODULE_DESCRIPTION("RxRPC network protocol");
MODULE_AUTHOR("Red Hat, Inc.");
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_RXRPC);
unsigned rxrpc_debug; // = RXRPC_DEBUG_KPROTO;
module_param_named(debug, rxrpc_debug, uint, S_IWUSR | S_IRUGO);
MODULE_PARM_DESC(debug, "RxRPC debugging mask");
static int sysctl_rxrpc_max_qlen __read_mostly = 10;
static struct proto rxrpc_proto;
static const struct proto_ops rxrpc_rpc_ops;
/* local epoch for detecting local-end reset */
__be32 rxrpc_epoch;
/* current debugging ID */
atomic_t rxrpc_debug_id;
/* count of skbs currently in use */
atomic_t rxrpc_n_skbs;
struct workqueue_struct *rxrpc_workqueue;
static void rxrpc_sock_destructor(struct sock *);
/*
* see if an RxRPC socket is currently writable
*/
static inline int rxrpc_writable(struct sock *sk)
{
return atomic_read(&sk->sk_wmem_alloc) < (size_t) sk->sk_sndbuf;
}
/*
* wait for write bufferage to become available
*/
static void rxrpc_write_space(struct sock *sk)
{
_enter("%p", sk);
rcu_read_lock();
if (rxrpc_writable(sk)) {
struct socket_wq *wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible(&wq->wait);
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
}
rcu_read_unlock();
}
/*
* validate an RxRPC address
*/
static int rxrpc_validate_address(struct rxrpc_sock *rx,
struct sockaddr_rxrpc *srx,
int len)
{
if (len < sizeof(struct sockaddr_rxrpc))
return -EINVAL;
if (srx->srx_family != AF_RXRPC)
return -EAFNOSUPPORT;
if (srx->transport_type != SOCK_DGRAM)
return -ESOCKTNOSUPPORT;
len -= offsetof(struct sockaddr_rxrpc, transport);
if (srx->transport_len < sizeof(sa_family_t) ||
srx->transport_len > len)
return -EINVAL;
if (srx->transport.family != rx->proto)
return -EAFNOSUPPORT;
switch (srx->transport.family) {
case AF_INET:
_debug("INET: %x @ %pI4",
ntohs(srx->transport.sin.sin_port),
&srx->transport.sin.sin_addr);
if (srx->transport_len > 8)
memset((void *)&srx->transport + 8, 0,
srx->transport_len - 8);
break;
case AF_INET6:
default:
return -EAFNOSUPPORT;
}
return 0;
}
/*
* bind a local address to an RxRPC socket
*/
static int rxrpc_bind(struct socket *sock, struct sockaddr *saddr, int len)
{
struct sockaddr_rxrpc *srx = (struct sockaddr_rxrpc *) saddr;
struct sock *sk = sock->sk;
struct rxrpc_local *local;
struct rxrpc_sock *rx = rxrpc_sk(sk), *prx;
__be16 service_id;
int ret;
_enter("%p,%p,%d", rx, saddr, len);
ret = rxrpc_validate_address(rx, srx, len);
if (ret < 0)
goto error;
lock_sock(&rx->sk);
if (rx->sk.sk_state != RXRPC_UNCONNECTED) {
ret = -EINVAL;
goto error_unlock;
}
memcpy(&rx->srx, srx, sizeof(rx->srx));
/* find a local transport endpoint if we don't have one already */
local = rxrpc_lookup_local(&rx->srx);
if (IS_ERR(local)) {
ret = PTR_ERR(local);
goto error_unlock;
}
rx->local = local;
if (srx->srx_service) {
service_id = htons(srx->srx_service);
write_lock_bh(&local->services_lock);
list_for_each_entry(prx, &local->services, listen_link) {
if (prx->service_id == service_id)
goto service_in_use;
}
rx->service_id = service_id;
list_add_tail(&rx->listen_link, &local->services);
write_unlock_bh(&local->services_lock);
rx->sk.sk_state = RXRPC_SERVER_BOUND;
} else {
rx->sk.sk_state = RXRPC_CLIENT_BOUND;
}
release_sock(&rx->sk);
_leave(" = 0");
return 0;
service_in_use:
ret = -EADDRINUSE;
write_unlock_bh(&local->services_lock);
error_unlock:
release_sock(&rx->sk);
error:
_leave(" = %d", ret);
return ret;
}
/*
* set the number of pending calls permitted on a listening socket
*/
static int rxrpc_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
struct rxrpc_sock *rx = rxrpc_sk(sk);
int ret;
_enter("%p,%d", rx, backlog);
lock_sock(&rx->sk);
switch (rx->sk.sk_state) {
case RXRPC_UNCONNECTED:
ret = -EADDRNOTAVAIL;
break;
case RXRPC_CLIENT_BOUND:
case RXRPC_CLIENT_CONNECTED:
default:
ret = -EBUSY;
break;
case RXRPC_SERVER_BOUND:
ASSERT(rx->local != NULL);
sk->sk_max_ack_backlog = backlog;
rx->sk.sk_state = RXRPC_SERVER_LISTENING;
ret = 0;
break;
}
release_sock(&rx->sk);
_leave(" = %d", ret);
return ret;
}
/*
* find a transport by address
*/
static struct rxrpc_transport *rxrpc_name_to_transport(struct socket *sock,
struct sockaddr *addr,
int addr_len, int flags,
gfp_t gfp)
{
struct sockaddr_rxrpc *srx = (struct sockaddr_rxrpc *) addr;
struct rxrpc_transport *trans;
struct rxrpc_sock *rx = rxrpc_sk(sock->sk);
struct rxrpc_peer *peer;
_enter("%p,%p,%d,%d", rx, addr, addr_len, flags);
ASSERT(rx->local != NULL);
ASSERT(rx->sk.sk_state > RXRPC_UNCONNECTED);
if (rx->srx.transport_type != srx->transport_type)
return ERR_PTR(-ESOCKTNOSUPPORT);
if (rx->srx.transport.family != srx->transport.family)
return ERR_PTR(-EAFNOSUPPORT);
/* find a remote transport endpoint from the local one */
peer = rxrpc_get_peer(srx, gfp);
if (IS_ERR(peer))
return ERR_CAST(peer);
/* find a transport */
trans = rxrpc_get_transport(rx->local, peer, gfp);
rxrpc_put_peer(peer);
_leave(" = %p", trans);
return trans;
}
/**
* rxrpc_kernel_begin_call - Allow a kernel service to begin a call
* @sock: The socket on which to make the call
* @srx: The address of the peer to contact (defaults to socket setting)
* @key: The security context to use (defaults to socket setting)
* @user_call_ID: The ID to use
*
* Allow a kernel service to begin a call on the nominated socket. This just
* sets up all the internal tracking structures and allocates connection and
* call IDs as appropriate. The call to be used is returned.
*
* The default socket destination address and security may be overridden by
* supplying @srx and @key.
*/
struct rxrpc_call *rxrpc_kernel_begin_call(struct socket *sock,
struct sockaddr_rxrpc *srx,
struct key *key,
unsigned long user_call_ID,
gfp_t gfp)
{
struct rxrpc_conn_bundle *bundle;
struct rxrpc_transport *trans;
struct rxrpc_call *call;
struct rxrpc_sock *rx = rxrpc_sk(sock->sk);
__be16 service_id;
_enter(",,%x,%lx", key_serial(key), user_call_ID);
lock_sock(&rx->sk);
if (srx) {
trans = rxrpc_name_to_transport(sock, (struct sockaddr *) srx,
sizeof(*srx), 0, gfp);
if (IS_ERR(trans)) {
call = ERR_CAST(trans);
trans = NULL;
goto out_notrans;
}
} else {
trans = rx->trans;
if (!trans) {
call = ERR_PTR(-ENOTCONN);
goto out_notrans;
}
atomic_inc(&trans->usage);
}
service_id = rx->service_id;
if (srx)
service_id = htons(srx->srx_service);
if (!key)
key = rx->key;
if (key && !key->payload.data)
key = NULL; /* a no-security key */
bundle = rxrpc_get_bundle(rx, trans, key, service_id, gfp);
if (IS_ERR(bundle)) {
call = ERR_CAST(bundle);
goto out;
}
call = rxrpc_get_client_call(rx, trans, bundle, user_call_ID, true,
gfp);
rxrpc_put_bundle(trans, bundle);
out:
rxrpc_put_transport(trans);
out_notrans:
release_sock(&rx->sk);
_leave(" = %p", call);
return call;
}
EXPORT_SYMBOL(rxrpc_kernel_begin_call);
/**
* rxrpc_kernel_end_call - Allow a kernel service to end a call it was using
* @call: The call to end
*
* Allow a kernel service to end a call it was using. The call must be
* complete before this is called (the call should be aborted if necessary).
*/
void rxrpc_kernel_end_call(struct rxrpc_call *call)
{
_enter("%d{%d}", call->debug_id, atomic_read(&call->usage));
rxrpc_remove_user_ID(call->socket, call);
rxrpc_put_call(call);
}
EXPORT_SYMBOL(rxrpc_kernel_end_call);
/**
* rxrpc_kernel_intercept_rx_messages - Intercept received RxRPC messages
* @sock: The socket to intercept received messages on
* @interceptor: The function to pass the messages to
*
* Allow a kernel service to intercept messages heading for the Rx queue on an
* RxRPC socket. They get passed to the specified function instead.
* @interceptor should free the socket buffers it is given. @interceptor is
* called with the socket receive queue spinlock held and softirqs disabled -
* this ensures that the messages will be delivered in the right order.
*/
void rxrpc_kernel_intercept_rx_messages(struct socket *sock,
rxrpc_interceptor_t interceptor)
{
struct rxrpc_sock *rx = rxrpc_sk(sock->sk);
_enter("");
rx->interceptor = interceptor;
}
EXPORT_SYMBOL(rxrpc_kernel_intercept_rx_messages);
/*
* connect an RxRPC socket
* - this just targets it at a specific destination; no actual connection
* negotiation takes place
*/
static int rxrpc_connect(struct socket *sock, struct sockaddr *addr,
int addr_len, int flags)
{
struct sockaddr_rxrpc *srx = (struct sockaddr_rxrpc *) addr;
struct sock *sk = sock->sk;
struct rxrpc_transport *trans;
struct rxrpc_local *local;
struct rxrpc_sock *rx = rxrpc_sk(sk);
int ret;
_enter("%p,%p,%d,%d", rx, addr, addr_len, flags);
ret = rxrpc_validate_address(rx, srx, addr_len);
if (ret < 0) {
_leave(" = %d [bad addr]", ret);
return ret;
}
lock_sock(&rx->sk);
switch (rx->sk.sk_state) {
case RXRPC_UNCONNECTED:
/* find a local transport endpoint if we don't have one already */
ASSERTCMP(rx->local, ==, NULL);
rx->srx.srx_family = AF_RXRPC;
rx->srx.srx_service = 0;
rx->srx.transport_type = srx->transport_type;
rx->srx.transport_len = sizeof(sa_family_t);
rx->srx.transport.family = srx->transport.family;
local = rxrpc_lookup_local(&rx->srx);
if (IS_ERR(local)) {
release_sock(&rx->sk);
return PTR_ERR(local);
}
rx->local = local;
rx->sk.sk_state = RXRPC_CLIENT_BOUND;
case RXRPC_CLIENT_BOUND:
break;
case RXRPC_CLIENT_CONNECTED:
release_sock(&rx->sk);
return -EISCONN;
default:
release_sock(&rx->sk);
return -EBUSY; /* server sockets can't connect as well */
}
trans = rxrpc_name_to_transport(sock, addr, addr_len, flags,
GFP_KERNEL);
if (IS_ERR(trans)) {
release_sock(&rx->sk);
_leave(" = %ld", PTR_ERR(trans));
return PTR_ERR(trans);
}
rx->trans = trans;
rx->service_id = htons(srx->srx_service);
rx->sk.sk_state = RXRPC_CLIENT_CONNECTED;
release_sock(&rx->sk);
return 0;
}
/*
* send a message through an RxRPC socket
* - in a client this does a number of things:
* - finds/sets up a connection for the security specified (if any)
* - initiates a call (ID in control data)
* - ends the request phase of a call (if MSG_MORE is not set)
* - sends a call data packet
* - may send an abort (abort code in control data)
*/
static int rxrpc_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t len)
{
struct rxrpc_transport *trans;
struct rxrpc_sock *rx = rxrpc_sk(sock->sk);
int ret;
_enter(",{%d},,%zu", rx->sk.sk_state, len);
if (m->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
if (m->msg_name) {
ret = rxrpc_validate_address(rx, m->msg_name, m->msg_namelen);
if (ret < 0) {
_leave(" = %d [bad addr]", ret);
return ret;
}
}
trans = NULL;
lock_sock(&rx->sk);
if (m->msg_name) {
ret = -EISCONN;
trans = rxrpc_name_to_transport(sock, m->msg_name,
m->msg_namelen, 0, GFP_KERNEL);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
trans = NULL;
goto out;
}
} else {
trans = rx->trans;
if (trans)
atomic_inc(&trans->usage);
}
switch (rx->sk.sk_state) {
case RXRPC_SERVER_LISTENING:
if (!m->msg_name) {
ret = rxrpc_server_sendmsg(iocb, rx, m, len);
break;
}
case RXRPC_SERVER_BOUND:
case RXRPC_CLIENT_BOUND:
if (!m->msg_name) {
ret = -ENOTCONN;
break;
}
case RXRPC_CLIENT_CONNECTED:
ret = rxrpc_client_sendmsg(iocb, rx, trans, m, len);
break;
default:
ret = -ENOTCONN;
break;
}
out:
release_sock(&rx->sk);
if (trans)
rxrpc_put_transport(trans);
_leave(" = %d", ret);
return ret;
}
/*
* set RxRPC socket options
*/
static int rxrpc_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct rxrpc_sock *rx = rxrpc_sk(sock->sk);
unsigned min_sec_level;
int ret;
_enter(",%d,%d,,%d", level, optname, optlen);
lock_sock(&rx->sk);
ret = -EOPNOTSUPP;
if (level == SOL_RXRPC) {
switch (optname) {
case RXRPC_EXCLUSIVE_CONNECTION:
ret = -EINVAL;
if (optlen != 0)
goto error;
ret = -EISCONN;
if (rx->sk.sk_state != RXRPC_UNCONNECTED)
goto error;
set_bit(RXRPC_SOCK_EXCLUSIVE_CONN, &rx->flags);
goto success;
case RXRPC_SECURITY_KEY:
ret = -EINVAL;
if (rx->key)
goto error;
ret = -EISCONN;
if (rx->sk.sk_state != RXRPC_UNCONNECTED)
goto error;
ret = rxrpc_request_key(rx, optval, optlen);
goto error;
case RXRPC_SECURITY_KEYRING:
ret = -EINVAL;
if (rx->key)
goto error;
ret = -EISCONN;
if (rx->sk.sk_state != RXRPC_UNCONNECTED)
goto error;
ret = rxrpc_server_keyring(rx, optval, optlen);
goto error;
case RXRPC_MIN_SECURITY_LEVEL:
ret = -EINVAL;
if (optlen != sizeof(unsigned))
goto error;
ret = -EISCONN;
if (rx->sk.sk_state != RXRPC_UNCONNECTED)
goto error;
ret = get_user(min_sec_level,
(unsigned __user *) optval);
if (ret < 0)
goto error;
ret = -EINVAL;
if (min_sec_level > RXRPC_SECURITY_MAX)
goto error;
rx->min_sec_level = min_sec_level;
goto success;
default:
break;
}
}
success:
ret = 0;
error:
release_sock(&rx->sk);
return ret;
}
/*
* permit an RxRPC socket to be polled
*/
static unsigned int rxrpc_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
unsigned int mask;
struct sock *sk = sock->sk;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* the socket is readable if there are any messages waiting on the Rx
* queue */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* the socket is writable if there is space to add new data to the
* socket; there is no guarantee that any particular call in progress
* on the socket may have space in the Tx ACK window */
if (rxrpc_writable(sk))
mask |= POLLOUT | POLLWRNORM;
return mask;
}
/*
* create an RxRPC socket
*/
static int rxrpc_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct rxrpc_sock *rx;
struct sock *sk;
_enter("%p,%d", sock, protocol);
if (!net_eq(net, &init_net))
return -EAFNOSUPPORT;
/* we support transport protocol UDP only */
if (protocol != PF_INET)
return -EPROTONOSUPPORT;
if (sock->type != SOCK_DGRAM)
return -ESOCKTNOSUPPORT;
sock->ops = &rxrpc_rpc_ops;
sock->state = SS_UNCONNECTED;
sk = sk_alloc(net, PF_RXRPC, GFP_KERNEL, &rxrpc_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sk->sk_state = RXRPC_UNCONNECTED;
sk->sk_write_space = rxrpc_write_space;
sk->sk_max_ack_backlog = sysctl_rxrpc_max_qlen;
sk->sk_destruct = rxrpc_sock_destructor;
rx = rxrpc_sk(sk);
rx->proto = protocol;
rx->calls = RB_ROOT;
INIT_LIST_HEAD(&rx->listen_link);
INIT_LIST_HEAD(&rx->secureq);
INIT_LIST_HEAD(&rx->acceptq);
rwlock_init(&rx->call_lock);
memset(&rx->srx, 0, sizeof(rx->srx));
_leave(" = 0 [%p]", rx);
return 0;
}
/*
* RxRPC socket destructor
*/
static void rxrpc_sock_destructor(struct sock *sk)
{
_enter("%p", sk);
rxrpc_purge_queue(&sk->sk_receive_queue);
WARN_ON(atomic_read(&sk->sk_wmem_alloc));
WARN_ON(!sk_unhashed(sk));
WARN_ON(sk->sk_socket);
if (!sock_flag(sk, SOCK_DEAD)) {
WARN(1, "Attempt to release alive rxrpc socket: %p\n", sk);
return;
}
}
/*
* release an RxRPC socket
*/
static int rxrpc_release_sock(struct sock *sk)
{
struct rxrpc_sock *rx = rxrpc_sk(sk);
_enter("%p{%d,%d}", sk, sk->sk_state, atomic_read(&sk->sk_refcnt));
/* declare the socket closed for business */
sock_orphan(sk);
sk->sk_shutdown = SHUTDOWN_MASK;
spin_lock_bh(&sk->sk_receive_queue.lock);
sk->sk_state = RXRPC_CLOSE;
spin_unlock_bh(&sk->sk_receive_queue.lock);
ASSERTCMP(rx->listen_link.next, !=, LIST_POISON1);
if (!list_empty(&rx->listen_link)) {
write_lock_bh(&rx->local->services_lock);
list_del(&rx->listen_link);
write_unlock_bh(&rx->local->services_lock);
}
/* try to flush out this socket */
rxrpc_release_calls_on_socket(rx);
flush_workqueue(rxrpc_workqueue);
rxrpc_purge_queue(&sk->sk_receive_queue);
if (rx->conn) {
rxrpc_put_connection(rx->conn);
rx->conn = NULL;
}
if (rx->bundle) {
rxrpc_put_bundle(rx->trans, rx->bundle);
rx->bundle = NULL;
}
if (rx->trans) {
rxrpc_put_transport(rx->trans);
rx->trans = NULL;
}
if (rx->local) {
rxrpc_put_local(rx->local);
rx->local = NULL;
}
key_put(rx->key);
rx->key = NULL;
key_put(rx->securities);
rx->securities = NULL;
sock_put(sk);
_leave(" = 0");
return 0;
}
/*
* release an RxRPC BSD socket on close() or equivalent
*/
static int rxrpc_release(struct socket *sock)
{
struct sock *sk = sock->sk;
_enter("%p{%p}", sock, sk);
if (!sk)
return 0;
sock->sk = NULL;
return rxrpc_release_sock(sk);
}
/*
* RxRPC network protocol
*/
static const struct proto_ops rxrpc_rpc_ops = {
.family = PF_UNIX,
.owner = THIS_MODULE,
.release = rxrpc_release,
.bind = rxrpc_bind,
.connect = rxrpc_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = sock_no_getname,
.poll = rxrpc_poll,
.ioctl = sock_no_ioctl,
.listen = rxrpc_listen,
.shutdown = sock_no_shutdown,
.setsockopt = rxrpc_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = rxrpc_sendmsg,
.recvmsg = rxrpc_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static struct proto rxrpc_proto = {
.name = "RXRPC",
.owner = THIS_MODULE,
.obj_size = sizeof(struct rxrpc_sock),
.max_header = sizeof(struct rxrpc_header),
};
static const struct net_proto_family rxrpc_family_ops = {
.family = PF_RXRPC,
.create = rxrpc_create,
.owner = THIS_MODULE,
};
/*
* initialise and register the RxRPC protocol
*/
static int __init af_rxrpc_init(void)
{
struct sk_buff *dummy_skb;
int ret = -1;
BUILD_BUG_ON(sizeof(struct rxrpc_skb_priv) > sizeof(dummy_skb->cb));
rxrpc_epoch = htonl(get_seconds());
ret = -ENOMEM;
rxrpc_call_jar = kmem_cache_create(
"rxrpc_call_jar", sizeof(struct rxrpc_call), 0,
SLAB_HWCACHE_ALIGN, NULL);
if (!rxrpc_call_jar) {
printk(KERN_NOTICE "RxRPC: Failed to allocate call jar\n");
goto error_call_jar;
}
rxrpc_workqueue = alloc_workqueue("krxrpcd", 0, 1);
if (!rxrpc_workqueue) {
printk(KERN_NOTICE "RxRPC: Failed to allocate work queue\n");
goto error_work_queue;
}
ret = proto_register(&rxrpc_proto, 1);
if (ret < 0) {
printk(KERN_CRIT "RxRPC: Cannot register protocol\n");
goto error_proto;
}
ret = sock_register(&rxrpc_family_ops);
if (ret < 0) {
printk(KERN_CRIT "RxRPC: Cannot register socket family\n");
goto error_sock;
}
ret = register_key_type(&key_type_rxrpc);
if (ret < 0) {
printk(KERN_CRIT "RxRPC: Cannot register client key type\n");
goto error_key_type;
}
ret = register_key_type(&key_type_rxrpc_s);
if (ret < 0) {
printk(KERN_CRIT "RxRPC: Cannot register server key type\n");
goto error_key_type_s;
}
#ifdef CONFIG_PROC_FS
proc_net_fops_create(&init_net, "rxrpc_calls", 0, &rxrpc_call_seq_fops);
proc_net_fops_create(&init_net, "rxrpc_conns", 0, &rxrpc_connection_seq_fops);
#endif
return 0;
error_key_type_s:
unregister_key_type(&key_type_rxrpc);
error_key_type:
sock_unregister(PF_RXRPC);
error_sock:
proto_unregister(&rxrpc_proto);
error_proto:
destroy_workqueue(rxrpc_workqueue);
error_work_queue:
kmem_cache_destroy(rxrpc_call_jar);
error_call_jar:
return ret;
}
/*
* unregister the RxRPC protocol
*/
static void __exit af_rxrpc_exit(void)
{
_enter("");
unregister_key_type(&key_type_rxrpc_s);
unregister_key_type(&key_type_rxrpc);
sock_unregister(PF_RXRPC);
proto_unregister(&rxrpc_proto);
rxrpc_destroy_all_calls();
rxrpc_destroy_all_connections();
rxrpc_destroy_all_transports();
rxrpc_destroy_all_peers();
rxrpc_destroy_all_locals();
ASSERTCMP(atomic_read(&rxrpc_n_skbs), ==, 0);
_debug("flush scheduled work");
flush_workqueue(rxrpc_workqueue);
proc_net_remove(&init_net, "rxrpc_conns");
proc_net_remove(&init_net, "rxrpc_calls");
destroy_workqueue(rxrpc_workqueue);
kmem_cache_destroy(rxrpc_call_jar);
_leave("");
}
module_init(af_rxrpc_init);
module_exit(af_rxrpc_exit);
| gpl-2.0 |
AndroidGX/SimpleGX-MM-6.0_H815_20i | drivers/rtc/rtc-isl12022.c | 2086 | 7358 | /*
* An I2C driver for the Intersil ISL 12022
*
* Author: Roman Fietze <roman.fietze@telemotive.de>
*
* Based on the Philips PCF8563 RTC
* by Alessandro Zummo <a.zummo@towertech.it>.
*
* 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/i2c.h>
#include <linux/bcd.h>
#include <linux/rtc.h>
#include <linux/slab.h>
#include <linux/module.h>
#define DRV_VERSION "0.1"
/* ISL register offsets */
#define ISL12022_REG_SC 0x00
#define ISL12022_REG_MN 0x01
#define ISL12022_REG_HR 0x02
#define ISL12022_REG_DT 0x03
#define ISL12022_REG_MO 0x04
#define ISL12022_REG_YR 0x05
#define ISL12022_REG_DW 0x06
#define ISL12022_REG_SR 0x07
#define ISL12022_REG_INT 0x08
/* ISL register bits */
#define ISL12022_HR_MIL (1 << 7) /* military or 24 hour time */
#define ISL12022_SR_LBAT85 (1 << 2)
#define ISL12022_SR_LBAT75 (1 << 1)
#define ISL12022_INT_WRTC (1 << 6)
static struct i2c_driver isl12022_driver;
struct isl12022 {
struct rtc_device *rtc;
bool write_enabled; /* true if write enable is set */
};
static int isl12022_read_regs(struct i2c_client *client, uint8_t reg,
uint8_t *data, size_t n)
{
struct i2c_msg msgs[] = {
{
.addr = client->addr,
.flags = 0,
.len = 1,
.buf = data
}, /* setup read ptr */
{
.addr = client->addr,
.flags = I2C_M_RD,
.len = n,
.buf = data
}
};
int ret;
data[0] = reg;
ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
if (ret != ARRAY_SIZE(msgs)) {
dev_err(&client->dev, "%s: read error, ret=%d\n",
__func__, ret);
return -EIO;
}
return 0;
}
static int isl12022_write_reg(struct i2c_client *client,
uint8_t reg, uint8_t val)
{
uint8_t data[2] = { reg, val };
int err;
err = i2c_master_send(client, data, sizeof(data));
if (err != sizeof(data)) {
dev_err(&client->dev,
"%s: err=%d addr=%02x, data=%02x\n",
__func__, err, data[0], data[1]);
return -EIO;
}
return 0;
}
/*
* In the routines that deal directly with the isl12022 hardware, we use
* rtc_time -- month 0-11, hour 0-23, yr = calendar year-epoch.
*/
static int isl12022_get_datetime(struct i2c_client *client, struct rtc_time *tm)
{
uint8_t buf[ISL12022_REG_INT + 1];
int ret;
ret = isl12022_read_regs(client, ISL12022_REG_SC, buf, sizeof(buf));
if (ret)
return ret;
if (buf[ISL12022_REG_SR] & (ISL12022_SR_LBAT85 | ISL12022_SR_LBAT75)) {
dev_warn(&client->dev,
"voltage dropped below %u%%, "
"date and time is not reliable.\n",
buf[ISL12022_REG_SR] & ISL12022_SR_LBAT85 ? 85 : 75);
}
dev_dbg(&client->dev,
"%s: raw data is sec=%02x, min=%02x, hr=%02x, "
"mday=%02x, mon=%02x, year=%02x, wday=%02x, "
"sr=%02x, int=%02x",
__func__,
buf[ISL12022_REG_SC],
buf[ISL12022_REG_MN],
buf[ISL12022_REG_HR],
buf[ISL12022_REG_DT],
buf[ISL12022_REG_MO],
buf[ISL12022_REG_YR],
buf[ISL12022_REG_DW],
buf[ISL12022_REG_SR],
buf[ISL12022_REG_INT]);
tm->tm_sec = bcd2bin(buf[ISL12022_REG_SC] & 0x7F);
tm->tm_min = bcd2bin(buf[ISL12022_REG_MN] & 0x7F);
tm->tm_hour = bcd2bin(buf[ISL12022_REG_HR] & 0x3F);
tm->tm_mday = bcd2bin(buf[ISL12022_REG_DT] & 0x3F);
tm->tm_wday = buf[ISL12022_REG_DW] & 0x07;
tm->tm_mon = bcd2bin(buf[ISL12022_REG_MO] & 0x1F) - 1;
tm->tm_year = bcd2bin(buf[ISL12022_REG_YR]) + 100;
dev_dbg(&client->dev, "%s: secs=%d, mins=%d, hours=%d, "
"mday=%d, mon=%d, year=%d, wday=%d\n",
__func__,
tm->tm_sec, tm->tm_min, tm->tm_hour,
tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday);
/* The clock can give out invalid datetime, but we cannot return
* -EINVAL otherwise hwclock will refuse to set the time on bootup. */
if (rtc_valid_tm(tm) < 0)
dev_err(&client->dev, "retrieved date and time is invalid.\n");
return 0;
}
static int isl12022_set_datetime(struct i2c_client *client, struct rtc_time *tm)
{
struct isl12022 *isl12022 = i2c_get_clientdata(client);
size_t i;
int ret;
uint8_t buf[ISL12022_REG_DW + 1];
dev_dbg(&client->dev, "%s: secs=%d, mins=%d, hours=%d, "
"mday=%d, mon=%d, year=%d, wday=%d\n",
__func__,
tm->tm_sec, tm->tm_min, tm->tm_hour,
tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday);
if (!isl12022->write_enabled) {
ret = isl12022_read_regs(client, ISL12022_REG_INT, buf, 1);
if (ret)
return ret;
/* Check if WRTC (write rtc enable) is set factory default is
* 0 (not set) */
if (!(buf[0] & ISL12022_INT_WRTC)) {
dev_info(&client->dev,
"init write enable and 24 hour format\n");
/* Set the write enable bit. */
ret = isl12022_write_reg(client,
ISL12022_REG_INT,
buf[0] | ISL12022_INT_WRTC);
if (ret)
return ret;
/* Write to any RTC register to start RTC, we use the
* HR register, setting the MIL bit to use the 24 hour
* format. */
ret = isl12022_read_regs(client, ISL12022_REG_HR,
buf, 1);
if (ret)
return ret;
ret = isl12022_write_reg(client,
ISL12022_REG_HR,
buf[0] | ISL12022_HR_MIL);
if (ret)
return ret;
}
isl12022->write_enabled = 1;
}
/* hours, minutes and seconds */
buf[ISL12022_REG_SC] = bin2bcd(tm->tm_sec);
buf[ISL12022_REG_MN] = bin2bcd(tm->tm_min);
buf[ISL12022_REG_HR] = bin2bcd(tm->tm_hour) | ISL12022_HR_MIL;
buf[ISL12022_REG_DT] = bin2bcd(tm->tm_mday);
/* month, 1 - 12 */
buf[ISL12022_REG_MO] = bin2bcd(tm->tm_mon + 1);
/* year and century */
buf[ISL12022_REG_YR] = bin2bcd(tm->tm_year % 100);
buf[ISL12022_REG_DW] = tm->tm_wday & 0x07;
/* write register's data */
for (i = 0; i < ARRAY_SIZE(buf); i++) {
ret = isl12022_write_reg(client, ISL12022_REG_SC + i,
buf[ISL12022_REG_SC + i]);
if (ret)
return -EIO;
}
return 0;
}
static int isl12022_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
return isl12022_get_datetime(to_i2c_client(dev), tm);
}
static int isl12022_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
return isl12022_set_datetime(to_i2c_client(dev), tm);
}
static const struct rtc_class_ops isl12022_rtc_ops = {
.read_time = isl12022_rtc_read_time,
.set_time = isl12022_rtc_set_time,
};
static int isl12022_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct isl12022 *isl12022;
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C))
return -ENODEV;
isl12022 = devm_kzalloc(&client->dev, sizeof(struct isl12022),
GFP_KERNEL);
if (!isl12022)
return -ENOMEM;
dev_dbg(&client->dev, "chip found, driver version " DRV_VERSION "\n");
i2c_set_clientdata(client, isl12022);
isl12022->rtc = devm_rtc_device_register(&client->dev,
isl12022_driver.driver.name,
&isl12022_rtc_ops, THIS_MODULE);
if (IS_ERR(isl12022->rtc))
return PTR_ERR(isl12022->rtc);
return 0;
}
static int isl12022_remove(struct i2c_client *client)
{
return 0;
}
static const struct i2c_device_id isl12022_id[] = {
{ "isl12022", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, isl12022_id);
static struct i2c_driver isl12022_driver = {
.driver = {
.name = "rtc-isl12022",
},
.probe = isl12022_probe,
.remove = isl12022_remove,
.id_table = isl12022_id,
};
module_i2c_driver(isl12022_driver);
MODULE_AUTHOR("roman.fietze@telemotive.de");
MODULE_DESCRIPTION("ISL 12022 RTC driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
| gpl-2.0 |
fortunaFiWn/android_kernel_samsung_fortunave3g | drivers/rtc/rtc-x1205.c | 2086 | 16319 | /*
* An i2c driver for the Xicor/Intersil X1205 RTC
* Copyright 2004 Karen Spearel
* Copyright 2005 Alessandro Zummo
*
* please send all reports to:
* Karen Spearel <kas111 at gmail dot com>
* Alessandro Zummo <a.zummo@towertech.it>
*
* based on a lot of other RTC drivers.
*
* Information and datasheet:
* http://www.intersil.com/cda/deviceinfo/0,1477,X1205,00.html
*
* 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/i2c.h>
#include <linux/bcd.h>
#include <linux/rtc.h>
#include <linux/delay.h>
#include <linux/module.h>
#define DRV_VERSION "1.0.8"
/* offsets into CCR area */
#define CCR_SEC 0
#define CCR_MIN 1
#define CCR_HOUR 2
#define CCR_MDAY 3
#define CCR_MONTH 4
#define CCR_YEAR 5
#define CCR_WDAY 6
#define CCR_Y2K 7
#define X1205_REG_SR 0x3F /* status register */
#define X1205_REG_Y2K 0x37
#define X1205_REG_DW 0x36
#define X1205_REG_YR 0x35
#define X1205_REG_MO 0x34
#define X1205_REG_DT 0x33
#define X1205_REG_HR 0x32
#define X1205_REG_MN 0x31
#define X1205_REG_SC 0x30
#define X1205_REG_DTR 0x13
#define X1205_REG_ATR 0x12
#define X1205_REG_INT 0x11
#define X1205_REG_0 0x10
#define X1205_REG_Y2K1 0x0F
#define X1205_REG_DWA1 0x0E
#define X1205_REG_YRA1 0x0D
#define X1205_REG_MOA1 0x0C
#define X1205_REG_DTA1 0x0B
#define X1205_REG_HRA1 0x0A
#define X1205_REG_MNA1 0x09
#define X1205_REG_SCA1 0x08
#define X1205_REG_Y2K0 0x07
#define X1205_REG_DWA0 0x06
#define X1205_REG_YRA0 0x05
#define X1205_REG_MOA0 0x04
#define X1205_REG_DTA0 0x03
#define X1205_REG_HRA0 0x02
#define X1205_REG_MNA0 0x01
#define X1205_REG_SCA0 0x00
#define X1205_CCR_BASE 0x30 /* Base address of CCR */
#define X1205_ALM0_BASE 0x00 /* Base address of ALARM0 */
#define X1205_SR_RTCF 0x01 /* Clock failure */
#define X1205_SR_WEL 0x02 /* Write Enable Latch */
#define X1205_SR_RWEL 0x04 /* Register Write Enable */
#define X1205_SR_AL0 0x20 /* Alarm 0 match */
#define X1205_DTR_DTR0 0x01
#define X1205_DTR_DTR1 0x02
#define X1205_DTR_DTR2 0x04
#define X1205_HR_MIL 0x80 /* Set in ccr.hour for 24 hr mode */
#define X1205_INT_AL0E 0x20 /* Alarm 0 enable */
static struct i2c_driver x1205_driver;
/*
* In the routines that deal directly with the x1205 hardware, we use
* rtc_time -- month 0-11, hour 0-23, yr = calendar year-epoch
* Epoch is initialized as 2000. Time is set to UTC.
*/
static int x1205_get_datetime(struct i2c_client *client, struct rtc_time *tm,
unsigned char reg_base)
{
unsigned char dt_addr[2] = { 0, reg_base };
unsigned char buf[8];
int i;
struct i2c_msg msgs[] = {
{/* setup read ptr */
.addr = client->addr,
.len = 2,
.buf = dt_addr
},
{/* read date */
.addr = client->addr,
.flags = I2C_M_RD,
.len = 8,
.buf = buf
},
};
/* read date registers */
if (i2c_transfer(client->adapter, &msgs[0], 2) != 2) {
dev_err(&client->dev, "%s: read error\n", __func__);
return -EIO;
}
dev_dbg(&client->dev,
"%s: raw read data - sec=%02x, min=%02x, hr=%02x, "
"mday=%02x, mon=%02x, year=%02x, wday=%02x, y2k=%02x\n",
__func__,
buf[0], buf[1], buf[2], buf[3],
buf[4], buf[5], buf[6], buf[7]);
/* Mask out the enable bits if these are alarm registers */
if (reg_base < X1205_CCR_BASE)
for (i = 0; i <= 4; i++)
buf[i] &= 0x7F;
tm->tm_sec = bcd2bin(buf[CCR_SEC]);
tm->tm_min = bcd2bin(buf[CCR_MIN]);
tm->tm_hour = bcd2bin(buf[CCR_HOUR] & 0x3F); /* hr is 0-23 */
tm->tm_mday = bcd2bin(buf[CCR_MDAY]);
tm->tm_mon = bcd2bin(buf[CCR_MONTH]) - 1; /* mon is 0-11 */
tm->tm_year = bcd2bin(buf[CCR_YEAR])
+ (bcd2bin(buf[CCR_Y2K]) * 100) - 1900;
tm->tm_wday = buf[CCR_WDAY];
dev_dbg(&client->dev, "%s: tm is secs=%d, mins=%d, hours=%d, "
"mday=%d, mon=%d, year=%d, wday=%d\n",
__func__,
tm->tm_sec, tm->tm_min, tm->tm_hour,
tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday);
return 0;
}
static int x1205_get_status(struct i2c_client *client, unsigned char *sr)
{
static unsigned char sr_addr[2] = { 0, X1205_REG_SR };
struct i2c_msg msgs[] = {
{ /* setup read ptr */
.addr = client->addr,
.len = 2,
.buf = sr_addr
},
{ /* read status */
.addr = client->addr,
.flags = I2C_M_RD,
.len = 1,
.buf = sr
},
};
/* read status register */
if (i2c_transfer(client->adapter, &msgs[0], 2) != 2) {
dev_err(&client->dev, "%s: read error\n", __func__);
return -EIO;
}
return 0;
}
static int x1205_set_datetime(struct i2c_client *client, struct rtc_time *tm,
u8 reg_base, unsigned char alm_enable)
{
int i, xfer;
unsigned char rdata[10] = { 0, reg_base };
unsigned char *buf = rdata + 2;
static const unsigned char wel[3] = { 0, X1205_REG_SR,
X1205_SR_WEL };
static const unsigned char rwel[3] = { 0, X1205_REG_SR,
X1205_SR_WEL | X1205_SR_RWEL };
static const unsigned char diswe[3] = { 0, X1205_REG_SR, 0 };
dev_dbg(&client->dev,
"%s: sec=%d min=%d hour=%d mday=%d mon=%d year=%d wday=%d\n",
__func__, tm->tm_sec, tm->tm_min, tm->tm_hour, tm->tm_mday,
tm->tm_mon, tm->tm_year, tm->tm_wday);
buf[CCR_SEC] = bin2bcd(tm->tm_sec);
buf[CCR_MIN] = bin2bcd(tm->tm_min);
/* set hour and 24hr bit */
buf[CCR_HOUR] = bin2bcd(tm->tm_hour) | X1205_HR_MIL;
buf[CCR_MDAY] = bin2bcd(tm->tm_mday);
/* month, 1 - 12 */
buf[CCR_MONTH] = bin2bcd(tm->tm_mon + 1);
/* year, since the rtc epoch*/
buf[CCR_YEAR] = bin2bcd(tm->tm_year % 100);
buf[CCR_WDAY] = tm->tm_wday & 0x07;
buf[CCR_Y2K] = bin2bcd((tm->tm_year + 1900) / 100);
/* If writing alarm registers, set compare bits on registers 0-4 */
if (reg_base < X1205_CCR_BASE)
for (i = 0; i <= 4; i++)
buf[i] |= 0x80;
/* this sequence is required to unlock the chip */
if ((xfer = i2c_master_send(client, wel, 3)) != 3) {
dev_err(&client->dev, "%s: wel - %d\n", __func__, xfer);
return -EIO;
}
if ((xfer = i2c_master_send(client, rwel, 3)) != 3) {
dev_err(&client->dev, "%s: rwel - %d\n", __func__, xfer);
return -EIO;
}
xfer = i2c_master_send(client, rdata, sizeof(rdata));
if (xfer != sizeof(rdata)) {
dev_err(&client->dev,
"%s: result=%d addr=%02x, data=%02x\n",
__func__,
xfer, rdata[1], rdata[2]);
return -EIO;
}
/* If we wrote to the nonvolatile region, wait 10msec for write cycle*/
if (reg_base < X1205_CCR_BASE) {
unsigned char al0e[3] = { 0, X1205_REG_INT, 0 };
msleep(10);
/* ...and set or clear the AL0E bit in the INT register */
/* Need to set RWEL again as the write has cleared it */
xfer = i2c_master_send(client, rwel, 3);
if (xfer != 3) {
dev_err(&client->dev,
"%s: aloe rwel - %d\n",
__func__,
xfer);
return -EIO;
}
if (alm_enable)
al0e[2] = X1205_INT_AL0E;
xfer = i2c_master_send(client, al0e, 3);
if (xfer != 3) {
dev_err(&client->dev,
"%s: al0e - %d\n",
__func__,
xfer);
return -EIO;
}
/* and wait 10msec again for this write to complete */
msleep(10);
}
/* disable further writes */
if ((xfer = i2c_master_send(client, diswe, 3)) != 3) {
dev_err(&client->dev, "%s: diswe - %d\n", __func__, xfer);
return -EIO;
}
return 0;
}
static int x1205_fix_osc(struct i2c_client *client)
{
int err;
struct rtc_time tm;
memset(&tm, 0, sizeof(tm));
err = x1205_set_datetime(client, &tm, X1205_CCR_BASE, 0);
if (err < 0)
dev_err(&client->dev, "unable to restart the oscillator\n");
return err;
}
static int x1205_get_dtrim(struct i2c_client *client, int *trim)
{
unsigned char dtr;
static unsigned char dtr_addr[2] = { 0, X1205_REG_DTR };
struct i2c_msg msgs[] = {
{ /* setup read ptr */
.addr = client->addr,
.len = 2,
.buf = dtr_addr
},
{ /* read dtr */
.addr = client->addr,
.flags = I2C_M_RD,
.len = 1,
.buf = &dtr
},
};
/* read dtr register */
if (i2c_transfer(client->adapter, &msgs[0], 2) != 2) {
dev_err(&client->dev, "%s: read error\n", __func__);
return -EIO;
}
dev_dbg(&client->dev, "%s: raw dtr=%x\n", __func__, dtr);
*trim = 0;
if (dtr & X1205_DTR_DTR0)
*trim += 20;
if (dtr & X1205_DTR_DTR1)
*trim += 10;
if (dtr & X1205_DTR_DTR2)
*trim = -*trim;
return 0;
}
static int x1205_get_atrim(struct i2c_client *client, int *trim)
{
s8 atr;
static unsigned char atr_addr[2] = { 0, X1205_REG_ATR };
struct i2c_msg msgs[] = {
{/* setup read ptr */
.addr = client->addr,
.len = 2,
.buf = atr_addr
},
{/* read atr */
.addr = client->addr,
.flags = I2C_M_RD,
.len = 1,
.buf = &atr
},
};
/* read atr register */
if (i2c_transfer(client->adapter, &msgs[0], 2) != 2) {
dev_err(&client->dev, "%s: read error\n", __func__);
return -EIO;
}
dev_dbg(&client->dev, "%s: raw atr=%x\n", __func__, atr);
/* atr is a two's complement value on 6 bits,
* perform sign extension. The formula is
* Catr = (atr * 0.25pF) + 11.00pF.
*/
if (atr & 0x20)
atr |= 0xC0;
dev_dbg(&client->dev, "%s: raw atr=%x (%d)\n", __func__, atr, atr);
*trim = (atr * 250) + 11000;
dev_dbg(&client->dev, "%s: real=%d\n", __func__, *trim);
return 0;
}
struct x1205_limit
{
unsigned char reg, mask, min, max;
};
static int x1205_validate_client(struct i2c_client *client)
{
int i, xfer;
/* Probe array. We will read the register at the specified
* address and check if the given bits are zero.
*/
static const unsigned char probe_zero_pattern[] = {
/* register, mask */
X1205_REG_SR, 0x18,
X1205_REG_DTR, 0xF8,
X1205_REG_ATR, 0xC0,
X1205_REG_INT, 0x18,
X1205_REG_0, 0xFF,
};
static const struct x1205_limit probe_limits_pattern[] = {
/* register, mask, min, max */
{ X1205_REG_Y2K, 0xFF, 19, 20 },
{ X1205_REG_DW, 0xFF, 0, 6 },
{ X1205_REG_YR, 0xFF, 0, 99 },
{ X1205_REG_MO, 0xFF, 0, 12 },
{ X1205_REG_DT, 0xFF, 0, 31 },
{ X1205_REG_HR, 0x7F, 0, 23 },
{ X1205_REG_MN, 0xFF, 0, 59 },
{ X1205_REG_SC, 0xFF, 0, 59 },
{ X1205_REG_Y2K1, 0xFF, 19, 20 },
{ X1205_REG_Y2K0, 0xFF, 19, 20 },
};
/* check that registers have bits a 0 where expected */
for (i = 0; i < ARRAY_SIZE(probe_zero_pattern); i += 2) {
unsigned char buf;
unsigned char addr[2] = { 0, probe_zero_pattern[i] };
struct i2c_msg msgs[2] = {
{
.addr = client->addr,
.len = 2,
.buf = addr
},
{
.addr = client->addr,
.flags = I2C_M_RD,
.len = 1,
.buf = &buf
},
};
if ((xfer = i2c_transfer(client->adapter, msgs, 2)) != 2) {
dev_err(&client->dev,
"%s: could not read register %x\n",
__func__, probe_zero_pattern[i]);
return -EIO;
}
if ((buf & probe_zero_pattern[i+1]) != 0) {
dev_err(&client->dev,
"%s: register=%02x, zero pattern=%d, value=%x\n",
__func__, probe_zero_pattern[i], i, buf);
return -ENODEV;
}
}
/* check limits (only registers with bcd values) */
for (i = 0; i < ARRAY_SIZE(probe_limits_pattern); i++) {
unsigned char reg, value;
unsigned char addr[2] = { 0, probe_limits_pattern[i].reg };
struct i2c_msg msgs[2] = {
{
.addr = client->addr,
.len = 2,
.buf = addr
},
{
.addr = client->addr,
.flags = I2C_M_RD,
.len = 1,
.buf = ®
},
};
if ((xfer = i2c_transfer(client->adapter, msgs, 2)) != 2) {
dev_err(&client->dev,
"%s: could not read register %x\n",
__func__, probe_limits_pattern[i].reg);
return -EIO;
}
value = bcd2bin(reg & probe_limits_pattern[i].mask);
if (value > probe_limits_pattern[i].max ||
value < probe_limits_pattern[i].min) {
dev_dbg(&client->dev,
"%s: register=%x, lim pattern=%d, value=%d\n",
__func__, probe_limits_pattern[i].reg,
i, value);
return -ENODEV;
}
}
return 0;
}
static int x1205_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
int err;
unsigned char intreg, status;
static unsigned char int_addr[2] = { 0, X1205_REG_INT };
struct i2c_client *client = to_i2c_client(dev);
struct i2c_msg msgs[] = {
{ /* setup read ptr */
.addr = client->addr,
.len = 2,
.buf = int_addr
},
{/* read INT register */
.addr = client->addr,
.flags = I2C_M_RD,
.len = 1,
.buf = &intreg
},
};
/* read interrupt register and status register */
if (i2c_transfer(client->adapter, &msgs[0], 2) != 2) {
dev_err(&client->dev, "%s: read error\n", __func__);
return -EIO;
}
err = x1205_get_status(client, &status);
if (err == 0) {
alrm->pending = (status & X1205_SR_AL0) ? 1 : 0;
alrm->enabled = (intreg & X1205_INT_AL0E) ? 1 : 0;
err = x1205_get_datetime(client, &alrm->time, X1205_ALM0_BASE);
}
return err;
}
static int x1205_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
return x1205_set_datetime(to_i2c_client(dev),
&alrm->time, X1205_ALM0_BASE, alrm->enabled);
}
static int x1205_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
return x1205_get_datetime(to_i2c_client(dev),
tm, X1205_CCR_BASE);
}
static int x1205_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
return x1205_set_datetime(to_i2c_client(dev),
tm, X1205_CCR_BASE, 0);
}
static int x1205_rtc_proc(struct device *dev, struct seq_file *seq)
{
int err, dtrim, atrim;
if ((err = x1205_get_dtrim(to_i2c_client(dev), &dtrim)) == 0)
seq_printf(seq, "digital_trim\t: %d ppm\n", dtrim);
if ((err = x1205_get_atrim(to_i2c_client(dev), &atrim)) == 0)
seq_printf(seq, "analog_trim\t: %d.%02d pF\n",
atrim / 1000, atrim % 1000);
return 0;
}
static const struct rtc_class_ops x1205_rtc_ops = {
.proc = x1205_rtc_proc,
.read_time = x1205_rtc_read_time,
.set_time = x1205_rtc_set_time,
.read_alarm = x1205_rtc_read_alarm,
.set_alarm = x1205_rtc_set_alarm,
};
static ssize_t x1205_sysfs_show_atrim(struct device *dev,
struct device_attribute *attr, char *buf)
{
int err, atrim;
err = x1205_get_atrim(to_i2c_client(dev), &atrim);
if (err)
return err;
return sprintf(buf, "%d.%02d pF\n", atrim / 1000, atrim % 1000);
}
static DEVICE_ATTR(atrim, S_IRUGO, x1205_sysfs_show_atrim, NULL);
static ssize_t x1205_sysfs_show_dtrim(struct device *dev,
struct device_attribute *attr, char *buf)
{
int err, dtrim;
err = x1205_get_dtrim(to_i2c_client(dev), &dtrim);
if (err)
return err;
return sprintf(buf, "%d ppm\n", dtrim);
}
static DEVICE_ATTR(dtrim, S_IRUGO, x1205_sysfs_show_dtrim, NULL);
static int x1205_sysfs_register(struct device *dev)
{
int err;
err = device_create_file(dev, &dev_attr_atrim);
if (err)
return err;
err = device_create_file(dev, &dev_attr_dtrim);
if (err)
device_remove_file(dev, &dev_attr_atrim);
return err;
}
static void x1205_sysfs_unregister(struct device *dev)
{
device_remove_file(dev, &dev_attr_atrim);
device_remove_file(dev, &dev_attr_dtrim);
}
static int x1205_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int err = 0;
unsigned char sr;
struct rtc_device *rtc;
dev_dbg(&client->dev, "%s\n", __func__);
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C))
return -ENODEV;
if (x1205_validate_client(client) < 0)
return -ENODEV;
dev_info(&client->dev, "chip found, driver version " DRV_VERSION "\n");
rtc = devm_rtc_device_register(&client->dev, x1205_driver.driver.name,
&x1205_rtc_ops, THIS_MODULE);
if (IS_ERR(rtc))
return PTR_ERR(rtc);
i2c_set_clientdata(client, rtc);
/* Check for power failures and eventually enable the osc */
if ((err = x1205_get_status(client, &sr)) == 0) {
if (sr & X1205_SR_RTCF) {
dev_err(&client->dev,
"power failure detected, "
"please set the clock\n");
udelay(50);
x1205_fix_osc(client);
}
}
else
dev_err(&client->dev, "couldn't read status\n");
err = x1205_sysfs_register(&client->dev);
if (err)
return err;
return 0;
}
static int x1205_remove(struct i2c_client *client)
{
x1205_sysfs_unregister(&client->dev);
return 0;
}
static const struct i2c_device_id x1205_id[] = {
{ "x1205", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, x1205_id);
static struct i2c_driver x1205_driver = {
.driver = {
.name = "rtc-x1205",
},
.probe = x1205_probe,
.remove = x1205_remove,
.id_table = x1205_id,
};
module_i2c_driver(x1205_driver);
MODULE_AUTHOR(
"Karen Spearel <kas111 at gmail dot com>, "
"Alessandro Zummo <a.zummo@towertech.it>");
MODULE_DESCRIPTION("Xicor/Intersil X1205 RTC driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
| gpl-2.0 |
cybernet/rhel7-kernel | kernel/drivers/mmc/host/android-goldfish.c | 2086 | 14076 | /*
* Copyright 2007, Google Inc.
* Copyright 2012, Intel Inc.
*
* based on omap.c driver, which was
* Copyright (C) 2004 Nokia Corporation
* Written by Tuukka Tikkanen and Juha Yrjölä <juha.yrjola@nokia.com>
* Misc hacks here and there by Tony Lindgren <tony@atomide.com>
* Other hacks (DMA, SD, etc) by David Brownell
*
* 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/platform_device.h>
#include <linux/major.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/hdreg.h>
#include <linux/kdev_t.h>
#include <linux/blkdev.h>
#include <linux/mutex.h>
#include <linux/scatterlist.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/sdio.h>
#include <linux/mmc/host.h>
#include <linux/mmc/card.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/dma-mapping.h>
#include <linux/delay.h>
#include <linux/spinlock.h>
#include <linux/timer.h>
#include <linux/clk.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/scatterlist.h>
#include <asm/types.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#define DRIVER_NAME "goldfish_mmc"
#define BUFFER_SIZE 16384
#define GOLDFISH_MMC_READ(host, addr) (readl(host->reg_base + addr))
#define GOLDFISH_MMC_WRITE(host, addr, x) (writel(x, host->reg_base + addr))
enum {
/* status register */
MMC_INT_STATUS = 0x00,
/* set this to enable IRQ */
MMC_INT_ENABLE = 0x04,
/* set this to specify buffer address */
MMC_SET_BUFFER = 0x08,
/* MMC command number */
MMC_CMD = 0x0C,
/* MMC argument */
MMC_ARG = 0x10,
/* MMC response (or R2 bits 0 - 31) */
MMC_RESP_0 = 0x14,
/* MMC R2 response bits 32 - 63 */
MMC_RESP_1 = 0x18,
/* MMC R2 response bits 64 - 95 */
MMC_RESP_2 = 0x1C,
/* MMC R2 response bits 96 - 127 */
MMC_RESP_3 = 0x20,
MMC_BLOCK_LENGTH = 0x24,
MMC_BLOCK_COUNT = 0x28,
/* MMC state flags */
MMC_STATE = 0x2C,
/* MMC_INT_STATUS bits */
MMC_STAT_END_OF_CMD = 1U << 0,
MMC_STAT_END_OF_DATA = 1U << 1,
MMC_STAT_STATE_CHANGE = 1U << 2,
MMC_STAT_CMD_TIMEOUT = 1U << 3,
/* MMC_STATE bits */
MMC_STATE_INSERTED = 1U << 0,
MMC_STATE_READ_ONLY = 1U << 1,
};
/*
* Command types
*/
#define OMAP_MMC_CMDTYPE_BC 0
#define OMAP_MMC_CMDTYPE_BCR 1
#define OMAP_MMC_CMDTYPE_AC 2
#define OMAP_MMC_CMDTYPE_ADTC 3
struct goldfish_mmc_host {
struct mmc_request *mrq;
struct mmc_command *cmd;
struct mmc_data *data;
struct mmc_host *mmc;
struct device *dev;
unsigned char id; /* 16xx chips have 2 MMC blocks */
void __iomem *virt_base;
unsigned int phys_base;
int irq;
unsigned char bus_mode;
unsigned char hw_bus_mode;
unsigned int sg_len;
unsigned dma_done:1;
unsigned dma_in_use:1;
void __iomem *reg_base;
};
static inline int
goldfish_mmc_cover_is_open(struct goldfish_mmc_host *host)
{
return 0;
}
static ssize_t
goldfish_mmc_show_cover_switch(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct goldfish_mmc_host *host = dev_get_drvdata(dev);
return sprintf(buf, "%s\n", goldfish_mmc_cover_is_open(host) ? "open" :
"closed");
}
static DEVICE_ATTR(cover_switch, S_IRUGO, goldfish_mmc_show_cover_switch, NULL);
static void
goldfish_mmc_start_command(struct goldfish_mmc_host *host, struct mmc_command *cmd)
{
u32 cmdreg;
u32 resptype;
u32 cmdtype;
host->cmd = cmd;
resptype = 0;
cmdtype = 0;
/* Our hardware needs to know exact type */
switch (mmc_resp_type(cmd)) {
case MMC_RSP_NONE:
break;
case MMC_RSP_R1:
case MMC_RSP_R1B:
/* resp 1, 1b, 6, 7 */
resptype = 1;
break;
case MMC_RSP_R2:
resptype = 2;
break;
case MMC_RSP_R3:
resptype = 3;
break;
default:
dev_err(mmc_dev(host->mmc),
"Invalid response type: %04x\n", mmc_resp_type(cmd));
break;
}
if (mmc_cmd_type(cmd) == MMC_CMD_ADTC)
cmdtype = OMAP_MMC_CMDTYPE_ADTC;
else if (mmc_cmd_type(cmd) == MMC_CMD_BC)
cmdtype = OMAP_MMC_CMDTYPE_BC;
else if (mmc_cmd_type(cmd) == MMC_CMD_BCR)
cmdtype = OMAP_MMC_CMDTYPE_BCR;
else
cmdtype = OMAP_MMC_CMDTYPE_AC;
cmdreg = cmd->opcode | (resptype << 8) | (cmdtype << 12);
if (host->bus_mode == MMC_BUSMODE_OPENDRAIN)
cmdreg |= 1 << 6;
if (cmd->flags & MMC_RSP_BUSY)
cmdreg |= 1 << 11;
if (host->data && !(host->data->flags & MMC_DATA_WRITE))
cmdreg |= 1 << 15;
GOLDFISH_MMC_WRITE(host, MMC_ARG, cmd->arg);
GOLDFISH_MMC_WRITE(host, MMC_CMD, cmdreg);
}
static void goldfish_mmc_xfer_done(struct goldfish_mmc_host *host,
struct mmc_data *data)
{
if (host->dma_in_use) {
enum dma_data_direction dma_data_dir;
if (data->flags & MMC_DATA_WRITE)
dma_data_dir = DMA_TO_DEVICE;
else
dma_data_dir = DMA_FROM_DEVICE;
if (dma_data_dir == DMA_FROM_DEVICE) {
/*
* We don't really have DMA, so we need
* to copy from our platform driver buffer
*/
uint8_t *dest = (uint8_t *)sg_virt(data->sg);
memcpy(dest, host->virt_base, data->sg->length);
}
host->data->bytes_xfered += data->sg->length;
dma_unmap_sg(mmc_dev(host->mmc), data->sg, host->sg_len,
dma_data_dir);
}
host->data = NULL;
host->sg_len = 0;
/*
* NOTE: MMC layer will sometimes poll-wait CMD13 next, issuing
* dozens of requests until the card finishes writing data.
* It'd be cheaper to just wait till an EOFB interrupt arrives...
*/
if (!data->stop) {
host->mrq = NULL;
mmc_request_done(host->mmc, data->mrq);
return;
}
goldfish_mmc_start_command(host, data->stop);
}
static void goldfish_mmc_end_of_data(struct goldfish_mmc_host *host,
struct mmc_data *data)
{
if (!host->dma_in_use) {
goldfish_mmc_xfer_done(host, data);
return;
}
if (host->dma_done)
goldfish_mmc_xfer_done(host, data);
}
static void goldfish_mmc_cmd_done(struct goldfish_mmc_host *host,
struct mmc_command *cmd)
{
host->cmd = NULL;
if (cmd->flags & MMC_RSP_PRESENT) {
if (cmd->flags & MMC_RSP_136) {
/* response type 2 */
cmd->resp[3] =
GOLDFISH_MMC_READ(host, MMC_RESP_0);
cmd->resp[2] =
GOLDFISH_MMC_READ(host, MMC_RESP_1);
cmd->resp[1] =
GOLDFISH_MMC_READ(host, MMC_RESP_2);
cmd->resp[0] =
GOLDFISH_MMC_READ(host, MMC_RESP_3);
} else {
/* response types 1, 1b, 3, 4, 5, 6 */
cmd->resp[0] =
GOLDFISH_MMC_READ(host, MMC_RESP_0);
}
}
if (host->data == NULL || cmd->error) {
host->mrq = NULL;
mmc_request_done(host->mmc, cmd->mrq);
}
}
static irqreturn_t goldfish_mmc_irq(int irq, void *dev_id)
{
struct goldfish_mmc_host *host = (struct goldfish_mmc_host *)dev_id;
u16 status;
int end_command = 0;
int end_transfer = 0;
int transfer_error = 0;
int state_changed = 0;
int cmd_timeout = 0;
while ((status = GOLDFISH_MMC_READ(host, MMC_INT_STATUS)) != 0) {
GOLDFISH_MMC_WRITE(host, MMC_INT_STATUS, status);
if (status & MMC_STAT_END_OF_CMD)
end_command = 1;
if (status & MMC_STAT_END_OF_DATA)
end_transfer = 1;
if (status & MMC_STAT_STATE_CHANGE)
state_changed = 1;
if (status & MMC_STAT_CMD_TIMEOUT) {
end_command = 0;
cmd_timeout = 1;
}
}
if (cmd_timeout) {
struct mmc_request *mrq = host->mrq;
mrq->cmd->error = -ETIMEDOUT;
host->mrq = NULL;
mmc_request_done(host->mmc, mrq);
}
if (end_command)
goldfish_mmc_cmd_done(host, host->cmd);
if (transfer_error)
goldfish_mmc_xfer_done(host, host->data);
else if (end_transfer) {
host->dma_done = 1;
goldfish_mmc_end_of_data(host, host->data);
} else if (host->data != NULL) {
/*
* WORKAROUND -- after porting this driver from 2.6 to 3.4,
* during device initialization, cases where host->data is
* non-null but end_transfer is false would occur. Doing
* nothing in such cases results in no further interrupts,
* and initialization failure.
* TODO -- find the real cause.
*/
host->dma_done = 1;
goldfish_mmc_end_of_data(host, host->data);
}
if (state_changed) {
u32 state = GOLDFISH_MMC_READ(host, MMC_STATE);
pr_info("%s: Card detect now %d\n", __func__,
(state & MMC_STATE_INSERTED));
mmc_detect_change(host->mmc, 0);
}
if (!end_command && !end_transfer &&
!transfer_error && !state_changed && !cmd_timeout) {
status = GOLDFISH_MMC_READ(host, MMC_INT_STATUS);
dev_info(mmc_dev(host->mmc),"spurious irq 0x%04x\n", status);
if (status != 0) {
GOLDFISH_MMC_WRITE(host, MMC_INT_STATUS, status);
GOLDFISH_MMC_WRITE(host, MMC_INT_ENABLE, 0);
}
}
return IRQ_HANDLED;
}
static void goldfish_mmc_prepare_data(struct goldfish_mmc_host *host,
struct mmc_request *req)
{
struct mmc_data *data = req->data;
int block_size;
unsigned sg_len;
enum dma_data_direction dma_data_dir;
host->data = data;
if (data == NULL) {
GOLDFISH_MMC_WRITE(host, MMC_BLOCK_LENGTH, 0);
GOLDFISH_MMC_WRITE(host, MMC_BLOCK_COUNT, 0);
host->dma_in_use = 0;
return;
}
block_size = data->blksz;
GOLDFISH_MMC_WRITE(host, MMC_BLOCK_COUNT, data->blocks - 1);
GOLDFISH_MMC_WRITE(host, MMC_BLOCK_LENGTH, block_size - 1);
/*
* Cope with calling layer confusion; it issues "single
* block" writes using multi-block scatterlists.
*/
sg_len = (data->blocks == 1) ? 1 : data->sg_len;
if (data->flags & MMC_DATA_WRITE)
dma_data_dir = DMA_TO_DEVICE;
else
dma_data_dir = DMA_FROM_DEVICE;
host->sg_len = dma_map_sg(mmc_dev(host->mmc), data->sg,
sg_len, dma_data_dir);
host->dma_done = 0;
host->dma_in_use = 1;
if (dma_data_dir == DMA_TO_DEVICE) {
/*
* We don't really have DMA, so we need to copy to our
* platform driver buffer
*/
const uint8_t *src = (uint8_t *)sg_virt(data->sg);
memcpy(host->virt_base, src, data->sg->length);
}
}
static void goldfish_mmc_request(struct mmc_host *mmc, struct mmc_request *req)
{
struct goldfish_mmc_host *host = mmc_priv(mmc);
WARN_ON(host->mrq != NULL);
host->mrq = req;
goldfish_mmc_prepare_data(host, req);
goldfish_mmc_start_command(host, req->cmd);
/*
* This is to avoid accidentally being detected as an SDIO card
* in mmc_attach_sdio().
*/
if (req->cmd->opcode == SD_IO_SEND_OP_COND &&
req->cmd->flags == (MMC_RSP_SPI_R4 | MMC_RSP_R4 | MMC_CMD_BCR))
req->cmd->error = -EINVAL;
}
static void goldfish_mmc_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct goldfish_mmc_host *host = mmc_priv(mmc);
host->bus_mode = ios->bus_mode;
host->hw_bus_mode = host->bus_mode;
}
static int goldfish_mmc_get_ro(struct mmc_host *mmc)
{
uint32_t state;
struct goldfish_mmc_host *host = mmc_priv(mmc);
state = GOLDFISH_MMC_READ(host, MMC_STATE);
return ((state & MMC_STATE_READ_ONLY) != 0);
}
static const struct mmc_host_ops goldfish_mmc_ops = {
.request = goldfish_mmc_request,
.set_ios = goldfish_mmc_set_ios,
.get_ro = goldfish_mmc_get_ro,
};
static int goldfish_mmc_probe(struct platform_device *pdev)
{
struct mmc_host *mmc;
struct goldfish_mmc_host *host = NULL;
struct resource *res;
int ret = 0;
int irq;
dma_addr_t buf_addr;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
irq = platform_get_irq(pdev, 0);
if (res == NULL || irq < 0)
return -ENXIO;
mmc = mmc_alloc_host(sizeof(struct goldfish_mmc_host), &pdev->dev);
if (mmc == NULL) {
ret = -ENOMEM;
goto err_alloc_host_failed;
}
host = mmc_priv(mmc);
host->mmc = mmc;
pr_err("mmc: Mapping %lX to %lX\n", (long)res->start, (long)res->end);
host->reg_base = ioremap(res->start, resource_size(res));
if (host->reg_base == NULL) {
ret = -ENOMEM;
goto ioremap_failed;
}
host->virt_base = dma_alloc_coherent(&pdev->dev, BUFFER_SIZE,
&buf_addr, GFP_KERNEL);
if (host->virt_base == 0) {
ret = -ENOMEM;
goto dma_alloc_failed;
}
host->phys_base = buf_addr;
host->id = pdev->id;
host->irq = irq;
mmc->ops = &goldfish_mmc_ops;
mmc->f_min = 400000;
mmc->f_max = 24000000;
mmc->ocr_avail = MMC_VDD_32_33 | MMC_VDD_33_34;
mmc->caps = MMC_CAP_4_BIT_DATA;
/* Use scatterlist DMA to reduce per-transfer costs.
* NOTE max_seg_size assumption that small blocks aren't
* normally used (except e.g. for reading SD registers).
*/
mmc->max_segs = 32;
mmc->max_blk_size = 2048; /* MMC_BLOCK_LENGTH is 11 bits (+1) */
mmc->max_blk_count = 2048; /* MMC_BLOCK_COUNT is 11 bits (+1) */
mmc->max_req_size = BUFFER_SIZE;
mmc->max_seg_size = mmc->max_req_size;
ret = request_irq(host->irq, goldfish_mmc_irq, 0, DRIVER_NAME, host);
if (ret) {
dev_err(&pdev->dev, "Failed IRQ Adding goldfish MMC\n");
goto err_request_irq_failed;
}
host->dev = &pdev->dev;
platform_set_drvdata(pdev, host);
ret = device_create_file(&pdev->dev, &dev_attr_cover_switch);
if (ret)
dev_warn(mmc_dev(host->mmc),
"Unable to create sysfs attributes\n");
GOLDFISH_MMC_WRITE(host, MMC_SET_BUFFER, host->phys_base);
GOLDFISH_MMC_WRITE(host, MMC_INT_ENABLE,
MMC_STAT_END_OF_CMD | MMC_STAT_END_OF_DATA |
MMC_STAT_STATE_CHANGE | MMC_STAT_CMD_TIMEOUT);
mmc_add_host(mmc);
return 0;
err_request_irq_failed:
dma_free_coherent(&pdev->dev, BUFFER_SIZE, host->virt_base,
host->phys_base);
dma_alloc_failed:
iounmap(host->reg_base);
ioremap_failed:
mmc_free_host(host->mmc);
err_alloc_host_failed:
return ret;
}
static int goldfish_mmc_remove(struct platform_device *pdev)
{
struct goldfish_mmc_host *host = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
BUG_ON(host == NULL);
mmc_remove_host(host->mmc);
free_irq(host->irq, host);
dma_free_coherent(&pdev->dev, BUFFER_SIZE, host->virt_base, host->phys_base);
iounmap(host->reg_base);
mmc_free_host(host->mmc);
return 0;
}
static struct platform_driver goldfish_mmc_driver = {
.probe = goldfish_mmc_probe,
.remove = goldfish_mmc_remove,
.driver = {
.name = DRIVER_NAME,
},
};
module_platform_driver(goldfish_mmc_driver);
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
Benzonat0r/android_kernel_samsung_golden | drivers/net/wireless/bcm4329/dhd_custom_gpio.c | 2854 | 7134 | /*
* Customer code to add GPIO control during WLAN start/stop
* Copyright (C) 1999-2010, Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that
* you also meet, for each linked independent module, the terms and conditions of
* the license of that module. An independent module is a module which is not
* derived from this software. The special exception does not apply to any
* modifications of the software.
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
* $Id: dhd_custom_gpio.c,v 1.1.4.8.4.4 2011/01/20 20:23:09 Exp $
*/
#include <typedefs.h>
#include <linuxver.h>
#include <osl.h>
#include <bcmutils.h>
#include <dngl_stats.h>
#include <dhd.h>
#include <wlioctl.h>
#include <wl_iw.h>
#define WL_ERROR(x) printf x
#define WL_TRACE(x)
#ifdef CUSTOMER_HW
extern void bcm_wlan_power_off(int);
extern void bcm_wlan_power_on(int);
#endif /* CUSTOMER_HW */
#ifdef CUSTOMER_HW2
int wifi_set_carddetect(int on);
int wifi_set_power(int on, unsigned long msec);
int wifi_get_irq_number(unsigned long *irq_flags_ptr);
int wifi_get_mac_addr(unsigned char *buf);
void *wifi_get_country_code(char *ccode);
#endif
#if defined(OOB_INTR_ONLY)
#if defined(BCMLXSDMMC)
extern int sdioh_mmc_irq(int irq);
#endif /* (BCMLXSDMMC) */
#ifdef CUSTOMER_HW3
#include <mach/gpio.h>
#endif
/* Customer specific Host GPIO defintion */
static int dhd_oob_gpio_num = -1; /* GG 19 */
module_param(dhd_oob_gpio_num, int, 0644);
MODULE_PARM_DESC(dhd_oob_gpio_num, "DHD oob gpio number");
int dhd_customer_oob_irq_map(unsigned long *irq_flags_ptr)
{
int host_oob_irq = 0;
#ifdef CUSTOMER_HW2
host_oob_irq = wifi_get_irq_number(irq_flags_ptr);
#else /* for NOT CUSTOMER_HW2 */
#if defined(CUSTOM_OOB_GPIO_NUM)
if (dhd_oob_gpio_num < 0) {
dhd_oob_gpio_num = CUSTOM_OOB_GPIO_NUM;
}
#endif
if (dhd_oob_gpio_num < 0) {
WL_ERROR(("%s: ERROR customer specific Host GPIO is NOT defined \n",
__FUNCTION__));
return (dhd_oob_gpio_num);
}
WL_ERROR(("%s: customer specific Host GPIO number is (%d)\n",
__FUNCTION__, dhd_oob_gpio_num));
#if defined CUSTOMER_HW
host_oob_irq = MSM_GPIO_TO_INT(dhd_oob_gpio_num);
#elif defined CUSTOMER_HW3
gpio_request(dhd_oob_gpio_num, "oob irq");
host_oob_irq = gpio_to_irq(dhd_oob_gpio_num);
gpio_direction_input(dhd_oob_gpio_num);
#endif /* CUSTOMER_HW */
#endif /* CUSTOMER_HW2 */
return (host_oob_irq);
}
#endif /* defined(OOB_INTR_ONLY) */
/* Customer function to control hw specific wlan gpios */
void
dhd_customer_gpio_wlan_ctrl(int onoff)
{
switch (onoff) {
case WLAN_RESET_OFF:
WL_TRACE(("%s: call customer specific GPIO to insert WLAN RESET\n",
__FUNCTION__));
#ifdef CUSTOMER_HW
bcm_wlan_power_off(2);
#endif /* CUSTOMER_HW */
#ifdef CUSTOMER_HW2
wifi_set_power(0, 0);
#endif
WL_ERROR(("=========== WLAN placed in RESET ========\n"));
break;
case WLAN_RESET_ON:
WL_TRACE(("%s: callc customer specific GPIO to remove WLAN RESET\n",
__FUNCTION__));
#ifdef CUSTOMER_HW
bcm_wlan_power_on(2);
#endif /* CUSTOMER_HW */
#ifdef CUSTOMER_HW2
wifi_set_power(1, 0);
#endif
WL_ERROR(("=========== WLAN going back to live ========\n"));
break;
case WLAN_POWER_OFF:
WL_TRACE(("%s: call customer specific GPIO to turn off WL_REG_ON\n",
__FUNCTION__));
#ifdef CUSTOMER_HW
bcm_wlan_power_off(1);
#endif /* CUSTOMER_HW */
break;
case WLAN_POWER_ON:
WL_TRACE(("%s: call customer specific GPIO to turn on WL_REG_ON\n",
__FUNCTION__));
#ifdef CUSTOMER_HW
bcm_wlan_power_on(1);
/* Lets customer power to get stable */
OSL_DELAY(50);
#endif /* CUSTOMER_HW */
break;
}
}
#ifdef GET_CUSTOM_MAC_ENABLE
/* Function to get custom MAC address */
int
dhd_custom_get_mac_address(unsigned char *buf)
{
int ret = 0;
WL_TRACE(("%s Enter\n", __FUNCTION__));
if (!buf)
return -EINVAL;
/* Customer access to MAC address stored outside of DHD driver */
#ifdef CUSTOMER_HW2
ret = wifi_get_mac_addr(buf);
#endif
#ifdef EXAMPLE_GET_MAC
/* EXAMPLE code */
{
struct ether_addr ea_example = {{0x00, 0x11, 0x22, 0x33, 0x44, 0xFF}};
bcopy((char *)&ea_example, buf, sizeof(struct ether_addr));
}
#endif /* EXAMPLE_GET_MAC */
return ret;
}
#endif /* GET_CUSTOM_MAC_ENABLE */
/* Customized Locale table : OPTIONAL feature */
const struct cntry_locales_custom translate_custom_table[] = {
/* Table should be filled out based on custom platform regulatory requirement */
#ifdef EXAMPLE_TABLE
{"", "XY", 4}, /* universal */
{"US", "US", 69}, /* input ISO "US" to : US regrev 69 */
{"CA", "US", 69}, /* input ISO "CA" to : US regrev 69 */
{"EU", "EU", 5}, /* European union countries */
{"AT", "EU", 5},
{"BE", "EU", 5},
{"BG", "EU", 5},
{"CY", "EU", 5},
{"CZ", "EU", 5},
{"DK", "EU", 5},
{"EE", "EU", 5},
{"FI", "EU", 5},
{"FR", "EU", 5},
{"DE", "EU", 5},
{"GR", "EU", 5},
{"HU", "EU", 5},
{"IE", "EU", 5},
{"IT", "EU", 5},
{"LV", "EU", 5},
{"LI", "EU", 5},
{"LT", "EU", 5},
{"LU", "EU", 5},
{"MT", "EU", 5},
{"NL", "EU", 5},
{"PL", "EU", 5},
{"PT", "EU", 5},
{"RO", "EU", 5},
{"SK", "EU", 5},
{"SI", "EU", 5},
{"ES", "EU", 5},
{"SE", "EU", 5},
{"GB", "EU", 5}, /* input ISO "GB" to : EU regrev 05 */
{"IL", "IL", 0},
{"CH", "CH", 0},
{"TR", "TR", 0},
{"NO", "NO", 0},
{"KR", "XY", 3},
{"AU", "XY", 3},
{"CN", "XY", 3}, /* input ISO "CN" to : XY regrev 03 */
{"TW", "XY", 3},
{"AR", "XY", 3},
{"MX", "XY", 3}
#endif /* EXAMPLE_TABLE */
};
/* Customized Locale convertor
* input : ISO 3166-1 country abbreviation
* output: customized cspec
*/
void get_customized_country_code(char *country_iso_code, wl_country_t *cspec)
{
#ifdef CUSTOMER_HW2
struct cntry_locales_custom *cloc_ptr;
if (!cspec)
return;
cloc_ptr = wifi_get_country_code(country_iso_code);
if (cloc_ptr) {
strlcpy(cspec->ccode, cloc_ptr->custom_locale, WLC_CNTRY_BUF_SZ);
cspec->rev = cloc_ptr->custom_locale_rev;
}
return;
#else
int size, i;
size = ARRAYSIZE(translate_custom_table);
if (cspec == 0)
return;
if (size == 0)
return;
for (i = 0; i < size; i++) {
if (strcmp(country_iso_code, translate_custom_table[i].iso_abbrev) == 0) {
memcpy(cspec->ccode, translate_custom_table[i].custom_locale, WLC_CNTRY_BUF_SZ);
cspec->rev = translate_custom_table[i].custom_locale_rev;
return;
}
}
memcpy(cspec->ccode, translate_custom_table[0].custom_locale, WLC_CNTRY_BUF_SZ);
cspec->rev = translate_custom_table[0].custom_locale_rev;
return;
#endif
}
| gpl-2.0 |
javelinanddart/android_kernel_lge_hamerhead | drivers/mfd/mfd-core.c | 2854 | 5651 | /*
* drivers/mfd/mfd-core.c
*
* core MFD support
* Copyright (c) 2006 Ian Molton
* Copyright (c) 2007,2008 Dmitry Baryshkov
*
* 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/platform_device.h>
#include <linux/acpi.h>
#include <linux/mfd/core.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h>
#include <linux/module.h>
int mfd_cell_enable(struct platform_device *pdev)
{
const struct mfd_cell *cell = mfd_get_cell(pdev);
int err = 0;
/* only call enable hook if the cell wasn't previously enabled */
if (atomic_inc_return(cell->usage_count) == 1)
err = cell->enable(pdev);
/* if the enable hook failed, decrement counter to allow retries */
if (err)
atomic_dec(cell->usage_count);
return err;
}
EXPORT_SYMBOL(mfd_cell_enable);
int mfd_cell_disable(struct platform_device *pdev)
{
const struct mfd_cell *cell = mfd_get_cell(pdev);
int err = 0;
/* only disable if no other clients are using it */
if (atomic_dec_return(cell->usage_count) == 0)
err = cell->disable(pdev);
/* if the disable hook failed, increment to allow retries */
if (err)
atomic_inc(cell->usage_count);
/* sanity check; did someone call disable too many times? */
WARN_ON(atomic_read(cell->usage_count) < 0);
return err;
}
EXPORT_SYMBOL(mfd_cell_disable);
static int mfd_platform_add_cell(struct platform_device *pdev,
const struct mfd_cell *cell)
{
if (!cell)
return 0;
pdev->mfd_cell = kmemdup(cell, sizeof(*cell), GFP_KERNEL);
if (!pdev->mfd_cell)
return -ENOMEM;
return 0;
}
static int mfd_add_device(struct device *parent, int id,
const struct mfd_cell *cell,
struct resource *mem_base,
int irq_base)
{
struct resource *res;
struct platform_device *pdev;
int ret = -ENOMEM;
int r;
pdev = platform_device_alloc(cell->name, id + cell->id);
if (!pdev)
goto fail_alloc;
res = kzalloc(sizeof(*res) * cell->num_resources, GFP_KERNEL);
if (!res)
goto fail_device;
pdev->dev.parent = parent;
if (cell->pdata_size) {
ret = platform_device_add_data(pdev,
cell->platform_data, cell->pdata_size);
if (ret)
goto fail_res;
}
ret = mfd_platform_add_cell(pdev, cell);
if (ret)
goto fail_res;
for (r = 0; r < cell->num_resources; r++) {
res[r].name = cell->resources[r].name;
res[r].flags = cell->resources[r].flags;
/* Find out base to use */
if ((cell->resources[r].flags & IORESOURCE_MEM) && mem_base) {
res[r].parent = mem_base;
res[r].start = mem_base->start +
cell->resources[r].start;
res[r].end = mem_base->start +
cell->resources[r].end;
} else if (cell->resources[r].flags & IORESOURCE_IRQ) {
res[r].start = irq_base +
cell->resources[r].start;
res[r].end = irq_base +
cell->resources[r].end;
} else {
res[r].parent = cell->resources[r].parent;
res[r].start = cell->resources[r].start;
res[r].end = cell->resources[r].end;
}
if (!cell->ignore_resource_conflicts) {
ret = acpi_check_resource_conflict(&res[r]);
if (ret)
goto fail_res;
}
}
ret = platform_device_add_resources(pdev, res, cell->num_resources);
if (ret)
goto fail_res;
ret = platform_device_add(pdev);
if (ret)
goto fail_res;
if (cell->pm_runtime_no_callbacks)
pm_runtime_no_callbacks(&pdev->dev);
kfree(res);
return 0;
fail_res:
kfree(res);
fail_device:
platform_device_put(pdev);
fail_alloc:
return ret;
}
int mfd_add_devices(struct device *parent, int id,
struct mfd_cell *cells, int n_devs,
struct resource *mem_base,
int irq_base)
{
int i;
int ret = 0;
atomic_t *cnts;
/* initialize reference counting for all cells */
cnts = kcalloc(n_devs, sizeof(*cnts), GFP_KERNEL);
if (!cnts)
return -ENOMEM;
for (i = 0; i < n_devs; i++) {
atomic_set(&cnts[i], 0);
cells[i].usage_count = &cnts[i];
ret = mfd_add_device(parent, id, cells + i, mem_base, irq_base);
if (ret)
break;
}
if (ret)
mfd_remove_devices(parent);
return ret;
}
EXPORT_SYMBOL(mfd_add_devices);
static int mfd_remove_devices_fn(struct device *dev, void *c)
{
struct platform_device *pdev = to_platform_device(dev);
const struct mfd_cell *cell = mfd_get_cell(pdev);
atomic_t **usage_count = c;
/* find the base address of usage_count pointers (for freeing) */
if (!*usage_count || (cell->usage_count < *usage_count))
*usage_count = cell->usage_count;
platform_device_unregister(pdev);
return 0;
}
void mfd_remove_devices(struct device *parent)
{
atomic_t *cnts = NULL;
device_for_each_child(parent, &cnts, mfd_remove_devices_fn);
kfree(cnts);
}
EXPORT_SYMBOL(mfd_remove_devices);
int mfd_clone_cell(const char *cell, const char **clones, size_t n_clones)
{
struct mfd_cell cell_entry;
struct device *dev;
struct platform_device *pdev;
int i;
/* fetch the parent cell's device (should already be registered!) */
dev = bus_find_device_by_name(&platform_bus_type, NULL, cell);
if (!dev) {
printk(KERN_ERR "failed to find device for cell %s\n", cell);
return -ENODEV;
}
pdev = to_platform_device(dev);
memcpy(&cell_entry, mfd_get_cell(pdev), sizeof(cell_entry));
WARN_ON(!cell_entry.enable);
for (i = 0; i < n_clones; i++) {
cell_entry.name = clones[i];
/* don't give up if a single call fails; just report error */
if (mfd_add_device(pdev->dev.parent, -1, &cell_entry, NULL, 0))
dev_err(dev, "failed to create platform device '%s'\n",
clones[i]);
}
return 0;
}
EXPORT_SYMBOL(mfd_clone_cell);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Ian Molton, Dmitry Baryshkov");
| gpl-2.0 |
PRJosh/kernel_motorola_msm8916 | fs/nilfs2/sufile.c | 2854 | 25173 | /*
* sufile.c - NILFS segment usage file.
*
* Copyright (C) 2006-2008 Nippon Telegraph and Telephone Corporation.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Written by Koji Sato <koji@osrg.net>.
* Revised by Ryusuke Konishi <ryusuke@osrg.net>.
*/
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/buffer_head.h>
#include <linux/errno.h>
#include <linux/nilfs2_fs.h>
#include "mdt.h"
#include "sufile.h"
/**
* struct nilfs_sufile_info - on-memory private data of sufile
* @mi: on-memory private data of metadata file
* @ncleansegs: number of clean segments
* @allocmin: lower limit of allocatable segment range
* @allocmax: upper limit of allocatable segment range
*/
struct nilfs_sufile_info {
struct nilfs_mdt_info mi;
unsigned long ncleansegs;/* number of clean segments */
__u64 allocmin; /* lower limit of allocatable segment range */
__u64 allocmax; /* upper limit of allocatable segment range */
};
static inline struct nilfs_sufile_info *NILFS_SUI(struct inode *sufile)
{
return (struct nilfs_sufile_info *)NILFS_MDT(sufile);
}
static inline unsigned long
nilfs_sufile_segment_usages_per_block(const struct inode *sufile)
{
return NILFS_MDT(sufile)->mi_entries_per_block;
}
static unsigned long
nilfs_sufile_get_blkoff(const struct inode *sufile, __u64 segnum)
{
__u64 t = segnum + NILFS_MDT(sufile)->mi_first_entry_offset;
do_div(t, nilfs_sufile_segment_usages_per_block(sufile));
return (unsigned long)t;
}
static unsigned long
nilfs_sufile_get_offset(const struct inode *sufile, __u64 segnum)
{
__u64 t = segnum + NILFS_MDT(sufile)->mi_first_entry_offset;
return do_div(t, nilfs_sufile_segment_usages_per_block(sufile));
}
static unsigned long
nilfs_sufile_segment_usages_in_block(const struct inode *sufile, __u64 curr,
__u64 max)
{
return min_t(unsigned long,
nilfs_sufile_segment_usages_per_block(sufile) -
nilfs_sufile_get_offset(sufile, curr),
max - curr + 1);
}
static struct nilfs_segment_usage *
nilfs_sufile_block_get_segment_usage(const struct inode *sufile, __u64 segnum,
struct buffer_head *bh, void *kaddr)
{
return kaddr + bh_offset(bh) +
nilfs_sufile_get_offset(sufile, segnum) *
NILFS_MDT(sufile)->mi_entry_size;
}
static inline int nilfs_sufile_get_header_block(struct inode *sufile,
struct buffer_head **bhp)
{
return nilfs_mdt_get_block(sufile, 0, 0, NULL, bhp);
}
static inline int
nilfs_sufile_get_segment_usage_block(struct inode *sufile, __u64 segnum,
int create, struct buffer_head **bhp)
{
return nilfs_mdt_get_block(sufile,
nilfs_sufile_get_blkoff(sufile, segnum),
create, NULL, bhp);
}
static int nilfs_sufile_delete_segment_usage_block(struct inode *sufile,
__u64 segnum)
{
return nilfs_mdt_delete_block(sufile,
nilfs_sufile_get_blkoff(sufile, segnum));
}
static void nilfs_sufile_mod_counter(struct buffer_head *header_bh,
u64 ncleanadd, u64 ndirtyadd)
{
struct nilfs_sufile_header *header;
void *kaddr;
kaddr = kmap_atomic(header_bh->b_page);
header = kaddr + bh_offset(header_bh);
le64_add_cpu(&header->sh_ncleansegs, ncleanadd);
le64_add_cpu(&header->sh_ndirtysegs, ndirtyadd);
kunmap_atomic(kaddr);
mark_buffer_dirty(header_bh);
}
/**
* nilfs_sufile_get_ncleansegs - return the number of clean segments
* @sufile: inode of segment usage file
*/
unsigned long nilfs_sufile_get_ncleansegs(struct inode *sufile)
{
return NILFS_SUI(sufile)->ncleansegs;
}
/**
* nilfs_sufile_updatev - modify multiple segment usages at a time
* @sufile: inode of segment usage file
* @segnumv: array of segment numbers
* @nsegs: size of @segnumv array
* @create: creation flag
* @ndone: place to store number of modified segments on @segnumv
* @dofunc: primitive operation for the update
*
* Description: nilfs_sufile_updatev() repeatedly calls @dofunc
* against the given array of segments. The @dofunc is called with
* buffers of a header block and the sufile block in which the target
* segment usage entry is contained. If @ndone is given, the number
* of successfully modified segments from the head is stored in the
* place @ndone points to.
*
* Return Value: On success, zero is returned. On error, one of the
* following negative error codes is returned.
*
* %-EIO - I/O error.
*
* %-ENOMEM - Insufficient amount of memory available.
*
* %-ENOENT - Given segment usage is in hole block (may be returned if
* @create is zero)
*
* %-EINVAL - Invalid segment usage number
*/
int nilfs_sufile_updatev(struct inode *sufile, __u64 *segnumv, size_t nsegs,
int create, size_t *ndone,
void (*dofunc)(struct inode *, __u64,
struct buffer_head *,
struct buffer_head *))
{
struct buffer_head *header_bh, *bh;
unsigned long blkoff, prev_blkoff;
__u64 *seg;
size_t nerr = 0, n = 0;
int ret = 0;
if (unlikely(nsegs == 0))
goto out;
down_write(&NILFS_MDT(sufile)->mi_sem);
for (seg = segnumv; seg < segnumv + nsegs; seg++) {
if (unlikely(*seg >= nilfs_sufile_get_nsegments(sufile))) {
printk(KERN_WARNING
"%s: invalid segment number: %llu\n", __func__,
(unsigned long long)*seg);
nerr++;
}
}
if (nerr > 0) {
ret = -EINVAL;
goto out_sem;
}
ret = nilfs_sufile_get_header_block(sufile, &header_bh);
if (ret < 0)
goto out_sem;
seg = segnumv;
blkoff = nilfs_sufile_get_blkoff(sufile, *seg);
ret = nilfs_mdt_get_block(sufile, blkoff, create, NULL, &bh);
if (ret < 0)
goto out_header;
for (;;) {
dofunc(sufile, *seg, header_bh, bh);
if (++seg >= segnumv + nsegs)
break;
prev_blkoff = blkoff;
blkoff = nilfs_sufile_get_blkoff(sufile, *seg);
if (blkoff == prev_blkoff)
continue;
/* get different block */
brelse(bh);
ret = nilfs_mdt_get_block(sufile, blkoff, create, NULL, &bh);
if (unlikely(ret < 0))
goto out_header;
}
brelse(bh);
out_header:
n = seg - segnumv;
brelse(header_bh);
out_sem:
up_write(&NILFS_MDT(sufile)->mi_sem);
out:
if (ndone)
*ndone = n;
return ret;
}
int nilfs_sufile_update(struct inode *sufile, __u64 segnum, int create,
void (*dofunc)(struct inode *, __u64,
struct buffer_head *,
struct buffer_head *))
{
struct buffer_head *header_bh, *bh;
int ret;
if (unlikely(segnum >= nilfs_sufile_get_nsegments(sufile))) {
printk(KERN_WARNING "%s: invalid segment number: %llu\n",
__func__, (unsigned long long)segnum);
return -EINVAL;
}
down_write(&NILFS_MDT(sufile)->mi_sem);
ret = nilfs_sufile_get_header_block(sufile, &header_bh);
if (ret < 0)
goto out_sem;
ret = nilfs_sufile_get_segment_usage_block(sufile, segnum, create, &bh);
if (!ret) {
dofunc(sufile, segnum, header_bh, bh);
brelse(bh);
}
brelse(header_bh);
out_sem:
up_write(&NILFS_MDT(sufile)->mi_sem);
return ret;
}
/**
* nilfs_sufile_set_alloc_range - limit range of segment to be allocated
* @sufile: inode of segment usage file
* @start: minimum segment number of allocatable region (inclusive)
* @end: maximum segment number of allocatable region (inclusive)
*
* Return Value: On success, 0 is returned. On error, one of the
* following negative error codes is returned.
*
* %-ERANGE - invalid segment region
*/
int nilfs_sufile_set_alloc_range(struct inode *sufile, __u64 start, __u64 end)
{
struct nilfs_sufile_info *sui = NILFS_SUI(sufile);
__u64 nsegs;
int ret = -ERANGE;
down_write(&NILFS_MDT(sufile)->mi_sem);
nsegs = nilfs_sufile_get_nsegments(sufile);
if (start <= end && end < nsegs) {
sui->allocmin = start;
sui->allocmax = end;
ret = 0;
}
up_write(&NILFS_MDT(sufile)->mi_sem);
return ret;
}
/**
* nilfs_sufile_alloc - allocate a segment
* @sufile: inode of segment usage file
* @segnump: pointer to segment number
*
* Description: nilfs_sufile_alloc() allocates a clean segment.
*
* Return Value: On success, 0 is returned and the segment number of the
* allocated segment is stored in the place pointed by @segnump. On error, one
* of the following negative error codes is returned.
*
* %-EIO - I/O error.
*
* %-ENOMEM - Insufficient amount of memory available.
*
* %-ENOSPC - No clean segment left.
*/
int nilfs_sufile_alloc(struct inode *sufile, __u64 *segnump)
{
struct buffer_head *header_bh, *su_bh;
struct nilfs_sufile_header *header;
struct nilfs_segment_usage *su;
struct nilfs_sufile_info *sui = NILFS_SUI(sufile);
size_t susz = NILFS_MDT(sufile)->mi_entry_size;
__u64 segnum, maxsegnum, last_alloc;
void *kaddr;
unsigned long nsegments, ncleansegs, nsus, cnt;
int ret, j;
down_write(&NILFS_MDT(sufile)->mi_sem);
ret = nilfs_sufile_get_header_block(sufile, &header_bh);
if (ret < 0)
goto out_sem;
kaddr = kmap_atomic(header_bh->b_page);
header = kaddr + bh_offset(header_bh);
ncleansegs = le64_to_cpu(header->sh_ncleansegs);
last_alloc = le64_to_cpu(header->sh_last_alloc);
kunmap_atomic(kaddr);
nsegments = nilfs_sufile_get_nsegments(sufile);
maxsegnum = sui->allocmax;
segnum = last_alloc + 1;
if (segnum < sui->allocmin || segnum > sui->allocmax)
segnum = sui->allocmin;
for (cnt = 0; cnt < nsegments; cnt += nsus) {
if (segnum > maxsegnum) {
if (cnt < sui->allocmax - sui->allocmin + 1) {
/*
* wrap around in the limited region.
* if allocation started from
* sui->allocmin, this never happens.
*/
segnum = sui->allocmin;
maxsegnum = last_alloc;
} else if (segnum > sui->allocmin &&
sui->allocmax + 1 < nsegments) {
segnum = sui->allocmax + 1;
maxsegnum = nsegments - 1;
} else if (sui->allocmin > 0) {
segnum = 0;
maxsegnum = sui->allocmin - 1;
} else {
break; /* never happens */
}
}
ret = nilfs_sufile_get_segment_usage_block(sufile, segnum, 1,
&su_bh);
if (ret < 0)
goto out_header;
kaddr = kmap_atomic(su_bh->b_page);
su = nilfs_sufile_block_get_segment_usage(
sufile, segnum, su_bh, kaddr);
nsus = nilfs_sufile_segment_usages_in_block(
sufile, segnum, maxsegnum);
for (j = 0; j < nsus; j++, su = (void *)su + susz, segnum++) {
if (!nilfs_segment_usage_clean(su))
continue;
/* found a clean segment */
nilfs_segment_usage_set_dirty(su);
kunmap_atomic(kaddr);
kaddr = kmap_atomic(header_bh->b_page);
header = kaddr + bh_offset(header_bh);
le64_add_cpu(&header->sh_ncleansegs, -1);
le64_add_cpu(&header->sh_ndirtysegs, 1);
header->sh_last_alloc = cpu_to_le64(segnum);
kunmap_atomic(kaddr);
sui->ncleansegs--;
mark_buffer_dirty(header_bh);
mark_buffer_dirty(su_bh);
nilfs_mdt_mark_dirty(sufile);
brelse(su_bh);
*segnump = segnum;
goto out_header;
}
kunmap_atomic(kaddr);
brelse(su_bh);
}
/* no segments left */
ret = -ENOSPC;
out_header:
brelse(header_bh);
out_sem:
up_write(&NILFS_MDT(sufile)->mi_sem);
return ret;
}
void nilfs_sufile_do_cancel_free(struct inode *sufile, __u64 segnum,
struct buffer_head *header_bh,
struct buffer_head *su_bh)
{
struct nilfs_segment_usage *su;
void *kaddr;
kaddr = kmap_atomic(su_bh->b_page);
su = nilfs_sufile_block_get_segment_usage(sufile, segnum, su_bh, kaddr);
if (unlikely(!nilfs_segment_usage_clean(su))) {
printk(KERN_WARNING "%s: segment %llu must be clean\n",
__func__, (unsigned long long)segnum);
kunmap_atomic(kaddr);
return;
}
nilfs_segment_usage_set_dirty(su);
kunmap_atomic(kaddr);
nilfs_sufile_mod_counter(header_bh, -1, 1);
NILFS_SUI(sufile)->ncleansegs--;
mark_buffer_dirty(su_bh);
nilfs_mdt_mark_dirty(sufile);
}
void nilfs_sufile_do_scrap(struct inode *sufile, __u64 segnum,
struct buffer_head *header_bh,
struct buffer_head *su_bh)
{
struct nilfs_segment_usage *su;
void *kaddr;
int clean, dirty;
kaddr = kmap_atomic(su_bh->b_page);
su = nilfs_sufile_block_get_segment_usage(sufile, segnum, su_bh, kaddr);
if (su->su_flags == cpu_to_le32(1UL << NILFS_SEGMENT_USAGE_DIRTY) &&
su->su_nblocks == cpu_to_le32(0)) {
kunmap_atomic(kaddr);
return;
}
clean = nilfs_segment_usage_clean(su);
dirty = nilfs_segment_usage_dirty(su);
/* make the segment garbage */
su->su_lastmod = cpu_to_le64(0);
su->su_nblocks = cpu_to_le32(0);
su->su_flags = cpu_to_le32(1UL << NILFS_SEGMENT_USAGE_DIRTY);
kunmap_atomic(kaddr);
nilfs_sufile_mod_counter(header_bh, clean ? (u64)-1 : 0, dirty ? 0 : 1);
NILFS_SUI(sufile)->ncleansegs -= clean;
mark_buffer_dirty(su_bh);
nilfs_mdt_mark_dirty(sufile);
}
void nilfs_sufile_do_free(struct inode *sufile, __u64 segnum,
struct buffer_head *header_bh,
struct buffer_head *su_bh)
{
struct nilfs_segment_usage *su;
void *kaddr;
int sudirty;
kaddr = kmap_atomic(su_bh->b_page);
su = nilfs_sufile_block_get_segment_usage(sufile, segnum, su_bh, kaddr);
if (nilfs_segment_usage_clean(su)) {
printk(KERN_WARNING "%s: segment %llu is already clean\n",
__func__, (unsigned long long)segnum);
kunmap_atomic(kaddr);
return;
}
WARN_ON(nilfs_segment_usage_error(su));
WARN_ON(!nilfs_segment_usage_dirty(su));
sudirty = nilfs_segment_usage_dirty(su);
nilfs_segment_usage_set_clean(su);
kunmap_atomic(kaddr);
mark_buffer_dirty(su_bh);
nilfs_sufile_mod_counter(header_bh, 1, sudirty ? (u64)-1 : 0);
NILFS_SUI(sufile)->ncleansegs++;
nilfs_mdt_mark_dirty(sufile);
}
/**
* nilfs_sufile_mark_dirty - mark the buffer having a segment usage dirty
* @sufile: inode of segment usage file
* @segnum: segment number
*/
int nilfs_sufile_mark_dirty(struct inode *sufile, __u64 segnum)
{
struct buffer_head *bh;
int ret;
ret = nilfs_sufile_get_segment_usage_block(sufile, segnum, 0, &bh);
if (!ret) {
mark_buffer_dirty(bh);
nilfs_mdt_mark_dirty(sufile);
brelse(bh);
}
return ret;
}
/**
* nilfs_sufile_set_segment_usage - set usage of a segment
* @sufile: inode of segment usage file
* @segnum: segment number
* @nblocks: number of live blocks in the segment
* @modtime: modification time (option)
*/
int nilfs_sufile_set_segment_usage(struct inode *sufile, __u64 segnum,
unsigned long nblocks, time_t modtime)
{
struct buffer_head *bh;
struct nilfs_segment_usage *su;
void *kaddr;
int ret;
down_write(&NILFS_MDT(sufile)->mi_sem);
ret = nilfs_sufile_get_segment_usage_block(sufile, segnum, 0, &bh);
if (ret < 0)
goto out_sem;
kaddr = kmap_atomic(bh->b_page);
su = nilfs_sufile_block_get_segment_usage(sufile, segnum, bh, kaddr);
WARN_ON(nilfs_segment_usage_error(su));
if (modtime)
su->su_lastmod = cpu_to_le64(modtime);
su->su_nblocks = cpu_to_le32(nblocks);
kunmap_atomic(kaddr);
mark_buffer_dirty(bh);
nilfs_mdt_mark_dirty(sufile);
brelse(bh);
out_sem:
up_write(&NILFS_MDT(sufile)->mi_sem);
return ret;
}
/**
* nilfs_sufile_get_stat - get segment usage statistics
* @sufile: inode of segment usage file
* @stat: pointer to a structure of segment usage statistics
*
* Description: nilfs_sufile_get_stat() returns information about segment
* usage.
*
* Return Value: On success, 0 is returned, and segment usage information is
* stored in the place pointed by @stat. On error, one of the following
* negative error codes is returned.
*
* %-EIO - I/O error.
*
* %-ENOMEM - Insufficient amount of memory available.
*/
int nilfs_sufile_get_stat(struct inode *sufile, struct nilfs_sustat *sustat)
{
struct buffer_head *header_bh;
struct nilfs_sufile_header *header;
struct the_nilfs *nilfs = sufile->i_sb->s_fs_info;
void *kaddr;
int ret;
down_read(&NILFS_MDT(sufile)->mi_sem);
ret = nilfs_sufile_get_header_block(sufile, &header_bh);
if (ret < 0)
goto out_sem;
kaddr = kmap_atomic(header_bh->b_page);
header = kaddr + bh_offset(header_bh);
sustat->ss_nsegs = nilfs_sufile_get_nsegments(sufile);
sustat->ss_ncleansegs = le64_to_cpu(header->sh_ncleansegs);
sustat->ss_ndirtysegs = le64_to_cpu(header->sh_ndirtysegs);
sustat->ss_ctime = nilfs->ns_ctime;
sustat->ss_nongc_ctime = nilfs->ns_nongc_ctime;
spin_lock(&nilfs->ns_last_segment_lock);
sustat->ss_prot_seq = nilfs->ns_prot_seq;
spin_unlock(&nilfs->ns_last_segment_lock);
kunmap_atomic(kaddr);
brelse(header_bh);
out_sem:
up_read(&NILFS_MDT(sufile)->mi_sem);
return ret;
}
void nilfs_sufile_do_set_error(struct inode *sufile, __u64 segnum,
struct buffer_head *header_bh,
struct buffer_head *su_bh)
{
struct nilfs_segment_usage *su;
void *kaddr;
int suclean;
kaddr = kmap_atomic(su_bh->b_page);
su = nilfs_sufile_block_get_segment_usage(sufile, segnum, su_bh, kaddr);
if (nilfs_segment_usage_error(su)) {
kunmap_atomic(kaddr);
return;
}
suclean = nilfs_segment_usage_clean(su);
nilfs_segment_usage_set_error(su);
kunmap_atomic(kaddr);
if (suclean) {
nilfs_sufile_mod_counter(header_bh, -1, 0);
NILFS_SUI(sufile)->ncleansegs--;
}
mark_buffer_dirty(su_bh);
nilfs_mdt_mark_dirty(sufile);
}
/**
* nilfs_sufile_truncate_range - truncate range of segment array
* @sufile: inode of segment usage file
* @start: start segment number (inclusive)
* @end: end segment number (inclusive)
*
* Return Value: On success, 0 is returned. On error, one of the
* following negative error codes is returned.
*
* %-EIO - I/O error.
*
* %-ENOMEM - Insufficient amount of memory available.
*
* %-EINVAL - Invalid number of segments specified
*
* %-EBUSY - Dirty or active segments are present in the range
*/
static int nilfs_sufile_truncate_range(struct inode *sufile,
__u64 start, __u64 end)
{
struct the_nilfs *nilfs = sufile->i_sb->s_fs_info;
struct buffer_head *header_bh;
struct buffer_head *su_bh;
struct nilfs_segment_usage *su, *su2;
size_t susz = NILFS_MDT(sufile)->mi_entry_size;
unsigned long segusages_per_block;
unsigned long nsegs, ncleaned;
__u64 segnum;
void *kaddr;
ssize_t n, nc;
int ret;
int j;
nsegs = nilfs_sufile_get_nsegments(sufile);
ret = -EINVAL;
if (start > end || start >= nsegs)
goto out;
ret = nilfs_sufile_get_header_block(sufile, &header_bh);
if (ret < 0)
goto out;
segusages_per_block = nilfs_sufile_segment_usages_per_block(sufile);
ncleaned = 0;
for (segnum = start; segnum <= end; segnum += n) {
n = min_t(unsigned long,
segusages_per_block -
nilfs_sufile_get_offset(sufile, segnum),
end - segnum + 1);
ret = nilfs_sufile_get_segment_usage_block(sufile, segnum, 0,
&su_bh);
if (ret < 0) {
if (ret != -ENOENT)
goto out_header;
/* hole */
continue;
}
kaddr = kmap_atomic(su_bh->b_page);
su = nilfs_sufile_block_get_segment_usage(
sufile, segnum, su_bh, kaddr);
su2 = su;
for (j = 0; j < n; j++, su = (void *)su + susz) {
if ((le32_to_cpu(su->su_flags) &
~(1UL << NILFS_SEGMENT_USAGE_ERROR)) ||
nilfs_segment_is_active(nilfs, segnum + j)) {
ret = -EBUSY;
kunmap_atomic(kaddr);
brelse(su_bh);
goto out_header;
}
}
nc = 0;
for (su = su2, j = 0; j < n; j++, su = (void *)su + susz) {
if (nilfs_segment_usage_error(su)) {
nilfs_segment_usage_set_clean(su);
nc++;
}
}
kunmap_atomic(kaddr);
if (nc > 0) {
mark_buffer_dirty(su_bh);
ncleaned += nc;
}
brelse(su_bh);
if (n == segusages_per_block) {
/* make hole */
nilfs_sufile_delete_segment_usage_block(sufile, segnum);
}
}
ret = 0;
out_header:
if (ncleaned > 0) {
NILFS_SUI(sufile)->ncleansegs += ncleaned;
nilfs_sufile_mod_counter(header_bh, ncleaned, 0);
nilfs_mdt_mark_dirty(sufile);
}
brelse(header_bh);
out:
return ret;
}
/**
* nilfs_sufile_resize - resize segment array
* @sufile: inode of segment usage file
* @newnsegs: new number of segments
*
* Return Value: On success, 0 is returned. On error, one of the
* following negative error codes is returned.
*
* %-EIO - I/O error.
*
* %-ENOMEM - Insufficient amount of memory available.
*
* %-ENOSPC - Enough free space is not left for shrinking
*
* %-EBUSY - Dirty or active segments exist in the region to be truncated
*/
int nilfs_sufile_resize(struct inode *sufile, __u64 newnsegs)
{
struct the_nilfs *nilfs = sufile->i_sb->s_fs_info;
struct buffer_head *header_bh;
struct nilfs_sufile_header *header;
struct nilfs_sufile_info *sui = NILFS_SUI(sufile);
void *kaddr;
unsigned long nsegs, nrsvsegs;
int ret = 0;
down_write(&NILFS_MDT(sufile)->mi_sem);
nsegs = nilfs_sufile_get_nsegments(sufile);
if (nsegs == newnsegs)
goto out;
ret = -ENOSPC;
nrsvsegs = nilfs_nrsvsegs(nilfs, newnsegs);
if (newnsegs < nsegs && nsegs - newnsegs + nrsvsegs > sui->ncleansegs)
goto out;
ret = nilfs_sufile_get_header_block(sufile, &header_bh);
if (ret < 0)
goto out;
if (newnsegs > nsegs) {
sui->ncleansegs += newnsegs - nsegs;
} else /* newnsegs < nsegs */ {
ret = nilfs_sufile_truncate_range(sufile, newnsegs, nsegs - 1);
if (ret < 0)
goto out_header;
sui->ncleansegs -= nsegs - newnsegs;
}
kaddr = kmap_atomic(header_bh->b_page);
header = kaddr + bh_offset(header_bh);
header->sh_ncleansegs = cpu_to_le64(sui->ncleansegs);
kunmap_atomic(kaddr);
mark_buffer_dirty(header_bh);
nilfs_mdt_mark_dirty(sufile);
nilfs_set_nsegments(nilfs, newnsegs);
out_header:
brelse(header_bh);
out:
up_write(&NILFS_MDT(sufile)->mi_sem);
return ret;
}
/**
* nilfs_sufile_get_suinfo -
* @sufile: inode of segment usage file
* @segnum: segment number to start looking
* @buf: array of suinfo
* @sisz: byte size of suinfo
* @nsi: size of suinfo array
*
* Description:
*
* Return Value: On success, 0 is returned and .... On error, one of the
* following negative error codes is returned.
*
* %-EIO - I/O error.
*
* %-ENOMEM - Insufficient amount of memory available.
*/
ssize_t nilfs_sufile_get_suinfo(struct inode *sufile, __u64 segnum, void *buf,
unsigned sisz, size_t nsi)
{
struct buffer_head *su_bh;
struct nilfs_segment_usage *su;
struct nilfs_suinfo *si = buf;
size_t susz = NILFS_MDT(sufile)->mi_entry_size;
struct the_nilfs *nilfs = sufile->i_sb->s_fs_info;
void *kaddr;
unsigned long nsegs, segusages_per_block;
ssize_t n;
int ret, i, j;
down_read(&NILFS_MDT(sufile)->mi_sem);
segusages_per_block = nilfs_sufile_segment_usages_per_block(sufile);
nsegs = min_t(unsigned long,
nilfs_sufile_get_nsegments(sufile) - segnum,
nsi);
for (i = 0; i < nsegs; i += n, segnum += n) {
n = min_t(unsigned long,
segusages_per_block -
nilfs_sufile_get_offset(sufile, segnum),
nsegs - i);
ret = nilfs_sufile_get_segment_usage_block(sufile, segnum, 0,
&su_bh);
if (ret < 0) {
if (ret != -ENOENT)
goto out;
/* hole */
memset(si, 0, sisz * n);
si = (void *)si + sisz * n;
continue;
}
kaddr = kmap_atomic(su_bh->b_page);
su = nilfs_sufile_block_get_segment_usage(
sufile, segnum, su_bh, kaddr);
for (j = 0; j < n;
j++, su = (void *)su + susz, si = (void *)si + sisz) {
si->sui_lastmod = le64_to_cpu(su->su_lastmod);
si->sui_nblocks = le32_to_cpu(su->su_nblocks);
si->sui_flags = le32_to_cpu(su->su_flags) &
~(1UL << NILFS_SEGMENT_USAGE_ACTIVE);
if (nilfs_segment_is_active(nilfs, segnum + j))
si->sui_flags |=
(1UL << NILFS_SEGMENT_USAGE_ACTIVE);
}
kunmap_atomic(kaddr);
brelse(su_bh);
}
ret = nsegs;
out:
up_read(&NILFS_MDT(sufile)->mi_sem);
return ret;
}
/**
* nilfs_sufile_read - read or get sufile inode
* @sb: super block instance
* @susize: size of a segment usage entry
* @raw_inode: on-disk sufile inode
* @inodep: buffer to store the inode
*/
int nilfs_sufile_read(struct super_block *sb, size_t susize,
struct nilfs_inode *raw_inode, struct inode **inodep)
{
struct inode *sufile;
struct nilfs_sufile_info *sui;
struct buffer_head *header_bh;
struct nilfs_sufile_header *header;
void *kaddr;
int err;
sufile = nilfs_iget_locked(sb, NULL, NILFS_SUFILE_INO);
if (unlikely(!sufile))
return -ENOMEM;
if (!(sufile->i_state & I_NEW))
goto out;
err = nilfs_mdt_init(sufile, NILFS_MDT_GFP, sizeof(*sui));
if (err)
goto failed;
nilfs_mdt_set_entry_size(sufile, susize,
sizeof(struct nilfs_sufile_header));
err = nilfs_read_inode_common(sufile, raw_inode);
if (err)
goto failed;
err = nilfs_sufile_get_header_block(sufile, &header_bh);
if (err)
goto failed;
sui = NILFS_SUI(sufile);
kaddr = kmap_atomic(header_bh->b_page);
header = kaddr + bh_offset(header_bh);
sui->ncleansegs = le64_to_cpu(header->sh_ncleansegs);
kunmap_atomic(kaddr);
brelse(header_bh);
sui->allocmax = nilfs_sufile_get_nsegments(sufile) - 1;
sui->allocmin = 0;
unlock_new_inode(sufile);
out:
*inodep = sufile;
return 0;
failed:
iget_failed(sufile);
return err;
}
| gpl-2.0 |
x414e54/gt-n8000-kernel | drivers/net/arcnet/arc-rimi.c | 3622 | 10924 | /*
* Linux ARCnet driver - "RIM I" (entirely mem-mapped) cards
*
* Written 1994-1999 by Avery Pennarun.
* Written 1999-2000 by Martin Mares <mj@ucw.cz>.
* Derived from skeleton.c by Donald Becker.
*
* Special thanks to Contemporary Controls, Inc. (www.ccontrols.com)
* for sponsoring the further development of this driver.
*
* **********************
*
* The original copyright of skeleton.c was as follows:
*
* skeleton.c Written 1993 by Donald Becker.
* Copyright 1993 United States Government as represented by the
* Director, National Security Agency. This software may only be used
* and distributed according to the terms of the GNU General Public License as
* modified by SRC, incorporated herein by reference.
*
* **********************
*
* For more details, see drivers/net/arcnet.c
*
* **********************
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/bootmem.h>
#include <linux/init.h>
#include <asm/io.h>
#include <linux/arcdevice.h>
#define VERSION "arcnet: RIM I (entirely mem-mapped) support\n"
/* Internal function declarations */
static int arcrimi_probe(struct net_device *dev);
static int arcrimi_found(struct net_device *dev);
static void arcrimi_command(struct net_device *dev, int command);
static int arcrimi_status(struct net_device *dev);
static void arcrimi_setmask(struct net_device *dev, int mask);
static int arcrimi_reset(struct net_device *dev, int really_reset);
static void arcrimi_copy_to_card(struct net_device *dev, int bufnum, int offset,
void *buf, int count);
static void arcrimi_copy_from_card(struct net_device *dev, int bufnum, int offset,
void *buf, int count);
/* Handy defines for ARCnet specific stuff */
/* Amount of I/O memory used by the card */
#define BUFFER_SIZE (512)
#define MIRROR_SIZE (BUFFER_SIZE*4)
/* COM 9026 controller chip --> ARCnet register addresses */
#define _INTMASK (ioaddr+0) /* writable */
#define _STATUS (ioaddr+0) /* readable */
#define _COMMAND (ioaddr+1) /* writable, returns random vals on read (?) */
#define _RESET (ioaddr+8) /* software reset (on read) */
#define _MEMDATA (ioaddr+12) /* Data port for IO-mapped memory */
#define _ADDR_HI (ioaddr+15) /* Control registers for said */
#define _ADDR_LO (ioaddr+14)
#define _CONFIG (ioaddr+2) /* Configuration register */
#undef ASTATUS
#undef ACOMMAND
#undef AINTMASK
#define ASTATUS() readb(_STATUS)
#define ACOMMAND(cmd) writeb((cmd),_COMMAND)
#define AINTMASK(msk) writeb((msk),_INTMASK)
#define SETCONF() writeb(lp->config,_CONFIG)
/*
* We cannot probe for a RIM I card; one reason is I don't know how to reset
* them. In fact, we can't even get their node ID automatically. So, we
* need to be passed a specific shmem address, IRQ, and node ID.
*/
static int __init arcrimi_probe(struct net_device *dev)
{
BUGLVL(D_NORMAL) printk(VERSION);
BUGLVL(D_NORMAL) printk("E-mail me if you actually test the RIM I driver, please!\n");
BUGMSG(D_NORMAL, "Given: node %02Xh, shmem %lXh, irq %d\n",
dev->dev_addr[0], dev->mem_start, dev->irq);
if (dev->mem_start <= 0 || dev->irq <= 0) {
BUGMSG(D_NORMAL, "No autoprobe for RIM I; you "
"must specify the shmem and irq!\n");
return -ENODEV;
}
if (dev->dev_addr[0] == 0) {
BUGMSG(D_NORMAL, "You need to specify your card's station "
"ID!\n");
return -ENODEV;
}
/*
* Grab the memory region at mem_start for MIRROR_SIZE bytes.
* Later in arcrimi_found() the real size will be determined
* and this reserve will be released and the correct size
* will be taken.
*/
if (!request_mem_region(dev->mem_start, MIRROR_SIZE, "arcnet (90xx)")) {
BUGMSG(D_NORMAL, "Card memory already allocated\n");
return -ENODEV;
}
return arcrimi_found(dev);
}
static int check_mirror(unsigned long addr, size_t size)
{
void __iomem *p;
int res = -1;
if (!request_mem_region(addr, size, "arcnet (90xx)"))
return -1;
p = ioremap(addr, size);
if (p) {
if (readb(p) == TESTvalue)
res = 1;
else
res = 0;
iounmap(p);
}
release_mem_region(addr, size);
return res;
}
/*
* Set up the struct net_device associated with this card. Called after
* probing succeeds.
*/
static int __init arcrimi_found(struct net_device *dev)
{
struct arcnet_local *lp;
unsigned long first_mirror, last_mirror, shmem;
void __iomem *p;
int mirror_size;
int err;
p = ioremap(dev->mem_start, MIRROR_SIZE);
if (!p) {
release_mem_region(dev->mem_start, MIRROR_SIZE);
BUGMSG(D_NORMAL, "Can't ioremap\n");
return -ENODEV;
}
/* reserve the irq */
if (request_irq(dev->irq, arcnet_interrupt, 0, "arcnet (RIM I)", dev)) {
iounmap(p);
release_mem_region(dev->mem_start, MIRROR_SIZE);
BUGMSG(D_NORMAL, "Can't get IRQ %d!\n", dev->irq);
return -ENODEV;
}
shmem = dev->mem_start;
writeb(TESTvalue, p);
writeb(dev->dev_addr[0], p + 1); /* actually the node ID */
/* find the real shared memory start/end points, including mirrors */
/* guess the actual size of one "memory mirror" - the number of
* bytes between copies of the shared memory. On most cards, it's
* 2k (or there are no mirrors at all) but on some, it's 4k.
*/
mirror_size = MIRROR_SIZE;
if (readb(p) == TESTvalue &&
check_mirror(shmem - MIRROR_SIZE, MIRROR_SIZE) == 0 &&
check_mirror(shmem - 2 * MIRROR_SIZE, MIRROR_SIZE) == 1)
mirror_size = 2 * MIRROR_SIZE;
first_mirror = shmem - mirror_size;
while (check_mirror(first_mirror, mirror_size) == 1)
first_mirror -= mirror_size;
first_mirror += mirror_size;
last_mirror = shmem + mirror_size;
while (check_mirror(last_mirror, mirror_size) == 1)
last_mirror += mirror_size;
last_mirror -= mirror_size;
dev->mem_start = first_mirror;
dev->mem_end = last_mirror + MIRROR_SIZE - 1;
/* initialize the rest of the device structure. */
lp = netdev_priv(dev);
lp->card_name = "RIM I";
lp->hw.command = arcrimi_command;
lp->hw.status = arcrimi_status;
lp->hw.intmask = arcrimi_setmask;
lp->hw.reset = arcrimi_reset;
lp->hw.owner = THIS_MODULE;
lp->hw.copy_to_card = arcrimi_copy_to_card;
lp->hw.copy_from_card = arcrimi_copy_from_card;
/*
* re-reserve the memory region - arcrimi_probe() alloced this reqion
* but didn't know the real size. Free that region and then re-get
* with the correct size. There is a VERY slim chance this could
* fail.
*/
iounmap(p);
release_mem_region(shmem, MIRROR_SIZE);
if (!request_mem_region(dev->mem_start,
dev->mem_end - dev->mem_start + 1,
"arcnet (90xx)")) {
BUGMSG(D_NORMAL, "Card memory already allocated\n");
goto err_free_irq;
}
lp->mem_start = ioremap(dev->mem_start, dev->mem_end - dev->mem_start + 1);
if (!lp->mem_start) {
BUGMSG(D_NORMAL, "Can't remap device memory!\n");
goto err_release_mem;
}
/* get and check the station ID from offset 1 in shmem */
dev->dev_addr[0] = readb(lp->mem_start + 1);
BUGMSG(D_NORMAL, "ARCnet RIM I: station %02Xh found at IRQ %d, "
"ShMem %lXh (%ld*%d bytes).\n",
dev->dev_addr[0],
dev->irq, dev->mem_start,
(dev->mem_end - dev->mem_start + 1) / mirror_size, mirror_size);
err = register_netdev(dev);
if (err)
goto err_unmap;
return 0;
err_unmap:
iounmap(lp->mem_start);
err_release_mem:
release_mem_region(dev->mem_start, dev->mem_end - dev->mem_start + 1);
err_free_irq:
free_irq(dev->irq, dev);
return -EIO;
}
/*
* Do a hardware reset on the card, and set up necessary registers.
*
* This should be called as little as possible, because it disrupts the
* token on the network (causes a RECON) and requires a significant delay.
*
* However, it does make sure the card is in a defined state.
*/
static int arcrimi_reset(struct net_device *dev, int really_reset)
{
struct arcnet_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->mem_start + 0x800;
BUGMSG(D_INIT, "Resetting %s (status=%02Xh)\n", dev->name, ASTATUS());
if (really_reset) {
writeb(TESTvalue, ioaddr - 0x800); /* fake reset */
return 0;
}
ACOMMAND(CFLAGScmd | RESETclear); /* clear flags & end reset */
ACOMMAND(CFLAGScmd | CONFIGclear);
/* enable extended (512-byte) packets */
ACOMMAND(CONFIGcmd | EXTconf);
/* done! return success. */
return 0;
}
static void arcrimi_setmask(struct net_device *dev, int mask)
{
struct arcnet_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->mem_start + 0x800;
AINTMASK(mask);
}
static int arcrimi_status(struct net_device *dev)
{
struct arcnet_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->mem_start + 0x800;
return ASTATUS();
}
static void arcrimi_command(struct net_device *dev, int cmd)
{
struct arcnet_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->mem_start + 0x800;
ACOMMAND(cmd);
}
static void arcrimi_copy_to_card(struct net_device *dev, int bufnum, int offset,
void *buf, int count)
{
struct arcnet_local *lp = netdev_priv(dev);
void __iomem *memaddr = lp->mem_start + 0x800 + bufnum * 512 + offset;
TIME("memcpy_toio", count, memcpy_toio(memaddr, buf, count));
}
static void arcrimi_copy_from_card(struct net_device *dev, int bufnum, int offset,
void *buf, int count)
{
struct arcnet_local *lp = netdev_priv(dev);
void __iomem *memaddr = lp->mem_start + 0x800 + bufnum * 512 + offset;
TIME("memcpy_fromio", count, memcpy_fromio(buf, memaddr, count));
}
static int node;
static int io; /* use the insmod io= irq= node= options */
static int irq;
static char device[9]; /* use eg. device=arc1 to change name */
module_param(node, int, 0);
module_param(io, int, 0);
module_param(irq, int, 0);
module_param_string(device, device, sizeof(device), 0);
MODULE_LICENSE("GPL");
static struct net_device *my_dev;
static int __init arc_rimi_init(void)
{
struct net_device *dev;
dev = alloc_arcdev(device);
if (!dev)
return -ENOMEM;
if (node && node != 0xff)
dev->dev_addr[0] = node;
dev->mem_start = io;
dev->irq = irq;
if (dev->irq == 2)
dev->irq = 9;
if (arcrimi_probe(dev)) {
free_netdev(dev);
return -EIO;
}
my_dev = dev;
return 0;
}
static void __exit arc_rimi_exit(void)
{
struct net_device *dev = my_dev;
struct arcnet_local *lp = netdev_priv(dev);
unregister_netdev(dev);
iounmap(lp->mem_start);
release_mem_region(dev->mem_start, dev->mem_end - dev->mem_start + 1);
free_irq(dev->irq, dev);
free_netdev(dev);
}
#ifndef MODULE
static int __init arcrimi_setup(char *s)
{
int ints[8];
s = get_options(s, 8, ints);
if (!ints[0])
return 1;
switch (ints[0]) {
default: /* ERROR */
printk("arcrimi: Too many arguments.\n");
case 3: /* Node ID */
node = ints[3];
case 2: /* IRQ */
irq = ints[2];
case 1: /* IO address */
io = ints[1];
}
if (*s)
snprintf(device, sizeof(device), "%s", s);
return 1;
}
__setup("arcrimi=", arcrimi_setup);
#endif /* MODULE */
module_init(arc_rimi_init)
module_exit(arc_rimi_exit)
| gpl-2.0 |
The-Covenant/android_kernel_samsung_i317 | drivers/input/tablet/gtco.c | 4134 | 26943 | /* -*- linux-c -*-
GTCO digitizer USB driver
Use the err() and dbg() macros from usb.h for system logging
TO CHECK: Is pressure done right on report 5?
Copyright (C) 2006 GTCO CalComp
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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation, and that the name of GTCO-CalComp not be used in advertising
or publicity pertaining to distribution of the software without specific,
written prior permission. GTCO-CalComp makes no representations about the
suitability of this software for any purpose. It is provided "as is"
without express or implied warranty.
GTCO-CALCOMP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL GTCO-CALCOMP BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTIONS, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
GTCO CalComp, Inc.
7125 Riverwood Drive
Columbia, MD 21046
Jeremy Roberson jroberson@gtcocalcomp.com
Scott Hill shill@gtcocalcomp.com
*/
/*#define DEBUG*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/usb.h>
#include <asm/uaccess.h>
#include <asm/unaligned.h>
#include <asm/byteorder.h>
#include <linux/usb/input.h>
/* Version with a Major number of 2 is for kernel inclusion only. */
#define GTCO_VERSION "2.00.0006"
/* MACROS */
#define VENDOR_ID_GTCO 0x078C
#define PID_400 0x400
#define PID_401 0x401
#define PID_1000 0x1000
#define PID_1001 0x1001
#define PID_1002 0x1002
/* Max size of a single report */
#define REPORT_MAX_SIZE 10
/* Bitmask whether pen is in range */
#define MASK_INRANGE 0x20
#define MASK_BUTTON 0x01F
#define PATHLENGTH 64
/* DATA STRUCTURES */
/* Device table */
static const struct usb_device_id gtco_usbid_table[] = {
{ USB_DEVICE(VENDOR_ID_GTCO, PID_400) },
{ USB_DEVICE(VENDOR_ID_GTCO, PID_401) },
{ USB_DEVICE(VENDOR_ID_GTCO, PID_1000) },
{ USB_DEVICE(VENDOR_ID_GTCO, PID_1001) },
{ USB_DEVICE(VENDOR_ID_GTCO, PID_1002) },
{ }
};
MODULE_DEVICE_TABLE (usb, gtco_usbid_table);
/* Structure to hold all of our device specific stuff */
struct gtco {
struct input_dev *inputdevice; /* input device struct pointer */
struct usb_device *usbdev; /* the usb device for this device */
struct urb *urbinfo; /* urb for incoming reports */
dma_addr_t buf_dma; /* dma addr of the data buffer*/
unsigned char * buffer; /* databuffer for reports */
char usbpath[PATHLENGTH];
int openCount;
/* Information pulled from Report Descriptor */
u32 usage;
u32 min_X;
u32 max_X;
u32 min_Y;
u32 max_Y;
s8 mintilt_X;
s8 maxtilt_X;
s8 mintilt_Y;
s8 maxtilt_Y;
u32 maxpressure;
u32 minpressure;
};
/* Code for parsing the HID REPORT DESCRIPTOR */
/* From HID1.11 spec */
struct hid_descriptor
{
struct usb_descriptor_header header;
__le16 bcdHID;
u8 bCountryCode;
u8 bNumDescriptors;
u8 bDescriptorType;
__le16 wDescriptorLength;
} __attribute__ ((packed));
#define HID_DESCRIPTOR_SIZE 9
#define HID_DEVICE_TYPE 33
#define REPORT_DEVICE_TYPE 34
#define PREF_TAG(x) ((x)>>4)
#define PREF_TYPE(x) ((x>>2)&0x03)
#define PREF_SIZE(x) ((x)&0x03)
#define TYPE_MAIN 0
#define TYPE_GLOBAL 1
#define TYPE_LOCAL 2
#define TYPE_RESERVED 3
#define TAG_MAIN_INPUT 0x8
#define TAG_MAIN_OUTPUT 0x9
#define TAG_MAIN_FEATURE 0xB
#define TAG_MAIN_COL_START 0xA
#define TAG_MAIN_COL_END 0xC
#define TAG_GLOB_USAGE 0
#define TAG_GLOB_LOG_MIN 1
#define TAG_GLOB_LOG_MAX 2
#define TAG_GLOB_PHYS_MIN 3
#define TAG_GLOB_PHYS_MAX 4
#define TAG_GLOB_UNIT_EXP 5
#define TAG_GLOB_UNIT 6
#define TAG_GLOB_REPORT_SZ 7
#define TAG_GLOB_REPORT_ID 8
#define TAG_GLOB_REPORT_CNT 9
#define TAG_GLOB_PUSH 10
#define TAG_GLOB_POP 11
#define TAG_GLOB_MAX 12
#define DIGITIZER_USAGE_TIP_PRESSURE 0x30
#define DIGITIZER_USAGE_TILT_X 0x3D
#define DIGITIZER_USAGE_TILT_Y 0x3E
/*
* This is an abbreviated parser for the HID Report Descriptor. We
* know what devices we are talking to, so this is by no means meant
* to be generic. We can make some safe assumptions:
*
* - We know there are no LONG tags, all short
* - We know that we have no MAIN Feature and MAIN Output items
* - We know what the IRQ reports are supposed to look like.
*
* The main purpose of this is to use the HID report desc to figure
* out the mins and maxs of the fields in the IRQ reports. The IRQ
* reports for 400/401 change slightly if the max X is bigger than 64K.
*
*/
static void parse_hid_report_descriptor(struct gtco *device, char * report,
int length)
{
int x, i = 0;
/* Tag primitive vars */
__u8 prefix;
__u8 size;
__u8 tag;
__u8 type;
__u8 data = 0;
__u16 data16 = 0;
__u32 data32 = 0;
/* For parsing logic */
int inputnum = 0;
__u32 usage = 0;
/* Global Values, indexed by TAG */
__u32 globalval[TAG_GLOB_MAX];
__u32 oldval[TAG_GLOB_MAX];
/* Debug stuff */
char maintype = 'x';
char globtype[12];
int indent = 0;
char indentstr[10] = "";
dbg("======>>>>>>PARSE<<<<<<======");
/* Walk this report and pull out the info we need */
while (i < length) {
prefix = report[i];
/* Skip over prefix */
i++;
/* Determine data size and save the data in the proper variable */
size = PREF_SIZE(prefix);
switch (size) {
case 1:
data = report[i];
break;
case 2:
data16 = get_unaligned_le16(&report[i]);
break;
case 3:
size = 4;
data32 = get_unaligned_le32(&report[i]);
break;
}
/* Skip size of data */
i += size;
/* What we do depends on the tag type */
tag = PREF_TAG(prefix);
type = PREF_TYPE(prefix);
switch (type) {
case TYPE_MAIN:
strcpy(globtype, "");
switch (tag) {
case TAG_MAIN_INPUT:
/*
* The INPUT MAIN tag signifies this is
* information from a report. We need to
* figure out what it is and store the
* min/max values
*/
maintype = 'I';
if (data == 2)
strcpy(globtype, "Variable");
else if (data == 3)
strcpy(globtype, "Var|Const");
dbg("::::: Saving Report: %d input #%d Max: 0x%X(%d) Min:0x%X(%d) of %d bits",
globalval[TAG_GLOB_REPORT_ID], inputnum,
globalval[TAG_GLOB_LOG_MAX], globalval[TAG_GLOB_LOG_MAX],
globalval[TAG_GLOB_LOG_MIN], globalval[TAG_GLOB_LOG_MIN],
globalval[TAG_GLOB_REPORT_SZ] * globalval[TAG_GLOB_REPORT_CNT]);
/*
We can assume that the first two input items
are always the X and Y coordinates. After
that, we look for everything else by
local usage value
*/
switch (inputnum) {
case 0: /* X coord */
dbg("GER: X Usage: 0x%x", usage);
if (device->max_X == 0) {
device->max_X = globalval[TAG_GLOB_LOG_MAX];
device->min_X = globalval[TAG_GLOB_LOG_MIN];
}
break;
case 1: /* Y coord */
dbg("GER: Y Usage: 0x%x", usage);
if (device->max_Y == 0) {
device->max_Y = globalval[TAG_GLOB_LOG_MAX];
device->min_Y = globalval[TAG_GLOB_LOG_MIN];
}
break;
default:
/* Tilt X */
if (usage == DIGITIZER_USAGE_TILT_X) {
if (device->maxtilt_X == 0) {
device->maxtilt_X = globalval[TAG_GLOB_LOG_MAX];
device->mintilt_X = globalval[TAG_GLOB_LOG_MIN];
}
}
/* Tilt Y */
if (usage == DIGITIZER_USAGE_TILT_Y) {
if (device->maxtilt_Y == 0) {
device->maxtilt_Y = globalval[TAG_GLOB_LOG_MAX];
device->mintilt_Y = globalval[TAG_GLOB_LOG_MIN];
}
}
/* Pressure */
if (usage == DIGITIZER_USAGE_TIP_PRESSURE) {
if (device->maxpressure == 0) {
device->maxpressure = globalval[TAG_GLOB_LOG_MAX];
device->minpressure = globalval[TAG_GLOB_LOG_MIN];
}
}
break;
}
inputnum++;
break;
case TAG_MAIN_OUTPUT:
maintype = 'O';
break;
case TAG_MAIN_FEATURE:
maintype = 'F';
break;
case TAG_MAIN_COL_START:
maintype = 'S';
if (data == 0) {
dbg("======>>>>>> Physical");
strcpy(globtype, "Physical");
} else
dbg("======>>>>>>");
/* Indent the debug output */
indent++;
for (x = 0; x < indent; x++)
indentstr[x] = '-';
indentstr[x] = 0;
/* Save global tags */
for (x = 0; x < TAG_GLOB_MAX; x++)
oldval[x] = globalval[x];
break;
case TAG_MAIN_COL_END:
dbg("<<<<<<======");
maintype = 'E';
indent--;
for (x = 0; x < indent; x++)
indentstr[x] = '-';
indentstr[x] = 0;
/* Copy global tags back */
for (x = 0; x < TAG_GLOB_MAX; x++)
globalval[x] = oldval[x];
break;
}
switch (size) {
case 1:
dbg("%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x",
indentstr, tag, maintype, size, globtype, data);
break;
case 2:
dbg("%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x",
indentstr, tag, maintype, size, globtype, data16);
break;
case 4:
dbg("%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x",
indentstr, tag, maintype, size, globtype, data32);
break;
}
break;
case TYPE_GLOBAL:
switch (tag) {
case TAG_GLOB_USAGE:
/*
* First time we hit the global usage tag,
* it should tell us the type of device
*/
if (device->usage == 0)
device->usage = data;
strcpy(globtype, "USAGE");
break;
case TAG_GLOB_LOG_MIN:
strcpy(globtype, "LOG_MIN");
break;
case TAG_GLOB_LOG_MAX:
strcpy(globtype, "LOG_MAX");
break;
case TAG_GLOB_PHYS_MIN:
strcpy(globtype, "PHYS_MIN");
break;
case TAG_GLOB_PHYS_MAX:
strcpy(globtype, "PHYS_MAX");
break;
case TAG_GLOB_UNIT_EXP:
strcpy(globtype, "EXP");
break;
case TAG_GLOB_UNIT:
strcpy(globtype, "UNIT");
break;
case TAG_GLOB_REPORT_SZ:
strcpy(globtype, "REPORT_SZ");
break;
case TAG_GLOB_REPORT_ID:
strcpy(globtype, "REPORT_ID");
/* New report, restart numbering */
inputnum = 0;
break;
case TAG_GLOB_REPORT_CNT:
strcpy(globtype, "REPORT_CNT");
break;
case TAG_GLOB_PUSH:
strcpy(globtype, "PUSH");
break;
case TAG_GLOB_POP:
strcpy(globtype, "POP");
break;
}
/* Check to make sure we have a good tag number
so we don't overflow array */
if (tag < TAG_GLOB_MAX) {
switch (size) {
case 1:
dbg("%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x",
indentstr, globtype, tag, size, data);
globalval[tag] = data;
break;
case 2:
dbg("%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x",
indentstr, globtype, tag, size, data16);
globalval[tag] = data16;
break;
case 4:
dbg("%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x",
indentstr, globtype, tag, size, data32);
globalval[tag] = data32;
break;
}
} else {
dbg("%sGLOBALTAG: ILLEGAL TAG:%d SIZE: %d ",
indentstr, tag, size);
}
break;
case TYPE_LOCAL:
switch (tag) {
case TAG_GLOB_USAGE:
strcpy(globtype, "USAGE");
/* Always 1 byte */
usage = data;
break;
case TAG_GLOB_LOG_MIN:
strcpy(globtype, "MIN");
break;
case TAG_GLOB_LOG_MAX:
strcpy(globtype, "MAX");
break;
default:
strcpy(globtype, "UNKNOWN");
break;
}
switch (size) {
case 1:
dbg("%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x",
indentstr, tag, globtype, size, data);
break;
case 2:
dbg("%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x",
indentstr, tag, globtype, size, data16);
break;
case 4:
dbg("%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x",
indentstr, tag, globtype, size, data32);
break;
}
break;
}
}
}
/* INPUT DRIVER Routines */
/*
* Called when opening the input device. This will submit the URB to
* the usb system so we start getting reports
*/
static int gtco_input_open(struct input_dev *inputdev)
{
struct gtco *device = input_get_drvdata(inputdev);
device->urbinfo->dev = device->usbdev;
if (usb_submit_urb(device->urbinfo, GFP_KERNEL))
return -EIO;
return 0;
}
/*
* Called when closing the input device. This will unlink the URB
*/
static void gtco_input_close(struct input_dev *inputdev)
{
struct gtco *device = input_get_drvdata(inputdev);
usb_kill_urb(device->urbinfo);
}
/*
* Setup input device capabilities. Tell the input system what this
* device is capable of generating.
*
* This information is based on what is read from the HID report and
* placed in the struct gtco structure
*
*/
static void gtco_setup_caps(struct input_dev *inputdev)
{
struct gtco *device = input_get_drvdata(inputdev);
/* Which events */
inputdev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS) |
BIT_MASK(EV_MSC);
/* Misc event menu block */
inputdev->mscbit[0] = BIT_MASK(MSC_SCAN) | BIT_MASK(MSC_SERIAL) |
BIT_MASK(MSC_RAW);
/* Absolute values based on HID report info */
input_set_abs_params(inputdev, ABS_X, device->min_X, device->max_X,
0, 0);
input_set_abs_params(inputdev, ABS_Y, device->min_Y, device->max_Y,
0, 0);
/* Proximity */
input_set_abs_params(inputdev, ABS_DISTANCE, 0, 1, 0, 0);
/* Tilt & pressure */
input_set_abs_params(inputdev, ABS_TILT_X, device->mintilt_X,
device->maxtilt_X, 0, 0);
input_set_abs_params(inputdev, ABS_TILT_Y, device->mintilt_Y,
device->maxtilt_Y, 0, 0);
input_set_abs_params(inputdev, ABS_PRESSURE, device->minpressure,
device->maxpressure, 0, 0);
/* Transducer */
input_set_abs_params(inputdev, ABS_MISC, 0, 0xFF, 0, 0);
}
/* USB Routines */
/*
* URB callback routine. Called when we get IRQ reports from the
* digitizer.
*
* This bridges the USB and input device worlds. It generates events
* on the input device based on the USB reports.
*/
static void gtco_urb_callback(struct urb *urbinfo)
{
struct gtco *device = urbinfo->context;
struct input_dev *inputdev;
int rc;
u32 val = 0;
s8 valsigned = 0;
char le_buffer[2];
inputdev = device->inputdevice;
/* Was callback OK? */
if (urbinfo->status == -ECONNRESET ||
urbinfo->status == -ENOENT ||
urbinfo->status == -ESHUTDOWN) {
/* Shutdown is occurring. Return and don't queue up any more */
return;
}
if (urbinfo->status != 0) {
/*
* Some unknown error. Hopefully temporary. Just go and
* requeue an URB
*/
goto resubmit;
}
/*
* Good URB, now process
*/
/* PID dependent when we interpret the report */
if (inputdev->id.product == PID_1000 ||
inputdev->id.product == PID_1001 ||
inputdev->id.product == PID_1002) {
/*
* Switch on the report ID
* Conveniently, the reports have more information, the higher
* the report number. We can just fall through the case
* statements if we start with the highest number report
*/
switch (device->buffer[0]) {
case 5:
/* Pressure is 9 bits */
val = ((u16)(device->buffer[8]) << 1);
val |= (u16)(device->buffer[7] >> 7);
input_report_abs(inputdev, ABS_PRESSURE,
device->buffer[8]);
/* Mask out the Y tilt value used for pressure */
device->buffer[7] = (u8)((device->buffer[7]) & 0x7F);
/* Fall thru */
case 4:
/* Tilt */
/* Sign extend these 7 bit numbers. */
if (device->buffer[6] & 0x40)
device->buffer[6] |= 0x80;
if (device->buffer[7] & 0x40)
device->buffer[7] |= 0x80;
valsigned = (device->buffer[6]);
input_report_abs(inputdev, ABS_TILT_X, (s32)valsigned);
valsigned = (device->buffer[7]);
input_report_abs(inputdev, ABS_TILT_Y, (s32)valsigned);
/* Fall thru */
case 2:
case 3:
/* Convert buttons, only 5 bits possible */
val = (device->buffer[5]) & MASK_BUTTON;
/* We don't apply any meaning to the bitmask,
just report */
input_event(inputdev, EV_MSC, MSC_SERIAL, val);
/* Fall thru */
case 1:
/* All reports have X and Y coords in the same place */
val = get_unaligned_le16(&device->buffer[1]);
input_report_abs(inputdev, ABS_X, val);
val = get_unaligned_le16(&device->buffer[3]);
input_report_abs(inputdev, ABS_Y, val);
/* Ditto for proximity bit */
val = device->buffer[5] & MASK_INRANGE ? 1 : 0;
input_report_abs(inputdev, ABS_DISTANCE, val);
/* Report 1 is an exception to how we handle buttons */
/* Buttons are an index, not a bitmask */
if (device->buffer[0] == 1) {
/*
* Convert buttons, 5 bit index
* Report value of index set as one,
* the rest as 0
*/
val = device->buffer[5] & MASK_BUTTON;
dbg("======>>>>>>REPORT 1: val 0x%X(%d)",
val, val);
/*
* We don't apply any meaning to the button
* index, just report it
*/
input_event(inputdev, EV_MSC, MSC_SERIAL, val);
}
break;
case 7:
/* Menu blocks */
input_event(inputdev, EV_MSC, MSC_SCAN,
device->buffer[1]);
break;
}
}
/* Other pid class */
if (inputdev->id.product == PID_400 ||
inputdev->id.product == PID_401) {
/* Report 2 */
if (device->buffer[0] == 2) {
/* Menu blocks */
input_event(inputdev, EV_MSC, MSC_SCAN, device->buffer[1]);
}
/* Report 1 */
if (device->buffer[0] == 1) {
char buttonbyte;
/* IF X max > 64K, we still a bit from the y report */
if (device->max_X > 0x10000) {
val = (u16)(((u16)(device->buffer[2] << 8)) | (u8)device->buffer[1]);
val |= (u32)(((u8)device->buffer[3] & 0x1) << 16);
input_report_abs(inputdev, ABS_X, val);
le_buffer[0] = (u8)((u8)(device->buffer[3]) >> 1);
le_buffer[0] |= (u8)((device->buffer[3] & 0x1) << 7);
le_buffer[1] = (u8)(device->buffer[4] >> 1);
le_buffer[1] |= (u8)((device->buffer[5] & 0x1) << 7);
val = get_unaligned_le16(le_buffer);
input_report_abs(inputdev, ABS_Y, val);
/*
* Shift the button byte right by one to
* make it look like the standard report
*/
buttonbyte = device->buffer[5] >> 1;
} else {
val = get_unaligned_le16(&device->buffer[1]);
input_report_abs(inputdev, ABS_X, val);
val = get_unaligned_le16(&device->buffer[3]);
input_report_abs(inputdev, ABS_Y, val);
buttonbyte = device->buffer[5];
}
/* BUTTONS and PROXIMITY */
val = buttonbyte & MASK_INRANGE ? 1 : 0;
input_report_abs(inputdev, ABS_DISTANCE, val);
/* Convert buttons, only 4 bits possible */
val = buttonbyte & 0x0F;
#ifdef USE_BUTTONS
for (i = 0; i < 5; i++)
input_report_key(inputdev, BTN_DIGI + i, val & (1 << i));
#else
/* We don't apply any meaning to the bitmask, just report */
input_event(inputdev, EV_MSC, MSC_SERIAL, val);
#endif
/* TRANSDUCER */
input_report_abs(inputdev, ABS_MISC, device->buffer[6]);
}
}
/* Everybody gets report ID's */
input_event(inputdev, EV_MSC, MSC_RAW, device->buffer[0]);
/* Sync it up */
input_sync(inputdev);
resubmit:
rc = usb_submit_urb(urbinfo, GFP_ATOMIC);
if (rc != 0)
err("usb_submit_urb failed rc=0x%x", rc);
}
/*
* The probe routine. This is called when the kernel find the matching USB
* vendor/product. We do the following:
*
* - Allocate mem for a local structure to manage the device
* - Request a HID Report Descriptor from the device and parse it to
* find out the device parameters
* - Create an input device and assign it attributes
* - Allocate an URB so the device can talk to us when the input
* queue is open
*/
static int gtco_probe(struct usb_interface *usbinterface,
const struct usb_device_id *id)
{
struct gtco *gtco;
struct input_dev *input_dev;
struct hid_descriptor *hid_desc;
char *report;
int result = 0, retry;
int error;
struct usb_endpoint_descriptor *endpoint;
/* Allocate memory for device structure */
gtco = kzalloc(sizeof(struct gtco), GFP_KERNEL);
input_dev = input_allocate_device();
if (!gtco || !input_dev) {
err("No more memory");
error = -ENOMEM;
goto err_free_devs;
}
/* Set pointer to the input device */
gtco->inputdevice = input_dev;
/* Save interface information */
gtco->usbdev = usb_get_dev(interface_to_usbdev(usbinterface));
/* Allocate some data for incoming reports */
gtco->buffer = usb_alloc_coherent(gtco->usbdev, REPORT_MAX_SIZE,
GFP_KERNEL, >co->buf_dma);
if (!gtco->buffer) {
err("No more memory for us buffers");
error = -ENOMEM;
goto err_free_devs;
}
/* Allocate URB for reports */
gtco->urbinfo = usb_alloc_urb(0, GFP_KERNEL);
if (!gtco->urbinfo) {
err("Failed to allocate URB");
error = -ENOMEM;
goto err_free_buf;
}
/*
* The endpoint is always altsetting 0, we know this since we know
* this device only has one interrupt endpoint
*/
endpoint = &usbinterface->altsetting[0].endpoint[0].desc;
/* Some debug */
dbg("gtco # interfaces: %d", usbinterface->num_altsetting);
dbg("num endpoints: %d", usbinterface->cur_altsetting->desc.bNumEndpoints);
dbg("interface class: %d", usbinterface->cur_altsetting->desc.bInterfaceClass);
dbg("endpoint: attribute:0x%x type:0x%x", endpoint->bmAttributes, endpoint->bDescriptorType);
if (usb_endpoint_xfer_int(endpoint))
dbg("endpoint: we have interrupt endpoint\n");
dbg("endpoint extra len:%d ", usbinterface->altsetting[0].extralen);
/*
* Find the HID descriptor so we can find out the size of the
* HID report descriptor
*/
if (usb_get_extra_descriptor(usbinterface->cur_altsetting,
HID_DEVICE_TYPE, &hid_desc) != 0){
err("Can't retrieve exta USB descriptor to get hid report descriptor length");
error = -EIO;
goto err_free_urb;
}
dbg("Extra descriptor success: type:%d len:%d",
hid_desc->bDescriptorType, hid_desc->wDescriptorLength);
report = kzalloc(le16_to_cpu(hid_desc->wDescriptorLength), GFP_KERNEL);
if (!report) {
err("No more memory for report");
error = -ENOMEM;
goto err_free_urb;
}
/* Couple of tries to get reply */
for (retry = 0; retry < 3; retry++) {
result = usb_control_msg(gtco->usbdev,
usb_rcvctrlpipe(gtco->usbdev, 0),
USB_REQ_GET_DESCRIPTOR,
USB_RECIP_INTERFACE | USB_DIR_IN,
REPORT_DEVICE_TYPE << 8,
0, /* interface */
report,
le16_to_cpu(hid_desc->wDescriptorLength),
5000); /* 5 secs */
dbg("usb_control_msg result: %d", result);
if (result == le16_to_cpu(hid_desc->wDescriptorLength)) {
parse_hid_report_descriptor(gtco, report, result);
break;
}
}
kfree(report);
/* If we didn't get the report, fail */
if (result != le16_to_cpu(hid_desc->wDescriptorLength)) {
err("Failed to get HID Report Descriptor of size: %d",
hid_desc->wDescriptorLength);
error = -EIO;
goto err_free_urb;
}
/* Create a device file node */
usb_make_path(gtco->usbdev, gtco->usbpath, sizeof(gtco->usbpath));
strlcat(gtco->usbpath, "/input0", sizeof(gtco->usbpath));
/* Set Input device functions */
input_dev->open = gtco_input_open;
input_dev->close = gtco_input_close;
/* Set input device information */
input_dev->name = "GTCO_CalComp";
input_dev->phys = gtco->usbpath;
input_set_drvdata(input_dev, gtco);
/* Now set up all the input device capabilities */
gtco_setup_caps(input_dev);
/* Set input device required ID information */
usb_to_input_id(gtco->usbdev, &input_dev->id);
input_dev->dev.parent = &usbinterface->dev;
/* Setup the URB, it will be posted later on open of input device */
endpoint = &usbinterface->altsetting[0].endpoint[0].desc;
usb_fill_int_urb(gtco->urbinfo,
gtco->usbdev,
usb_rcvintpipe(gtco->usbdev,
endpoint->bEndpointAddress),
gtco->buffer,
REPORT_MAX_SIZE,
gtco_urb_callback,
gtco,
endpoint->bInterval);
gtco->urbinfo->transfer_dma = gtco->buf_dma;
gtco->urbinfo->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
/* Save gtco pointer in USB interface gtco */
usb_set_intfdata(usbinterface, gtco);
/* All done, now register the input device */
error = input_register_device(input_dev);
if (error)
goto err_free_urb;
return 0;
err_free_urb:
usb_free_urb(gtco->urbinfo);
err_free_buf:
usb_free_coherent(gtco->usbdev, REPORT_MAX_SIZE,
gtco->buffer, gtco->buf_dma);
err_free_devs:
input_free_device(input_dev);
kfree(gtco);
return error;
}
/*
* This function is a standard USB function called when the USB device
* is disconnected. We will get rid of the URV, de-register the input
* device, and free up allocated memory
*/
static void gtco_disconnect(struct usb_interface *interface)
{
/* Grab private device ptr */
struct gtco *gtco = usb_get_intfdata(interface);
/* Now reverse all the registration stuff */
if (gtco) {
input_unregister_device(gtco->inputdevice);
usb_kill_urb(gtco->urbinfo);
usb_free_urb(gtco->urbinfo);
usb_free_coherent(gtco->usbdev, REPORT_MAX_SIZE,
gtco->buffer, gtco->buf_dma);
kfree(gtco);
}
dev_info(&interface->dev, "gtco driver disconnected\n");
}
/* STANDARD MODULE LOAD ROUTINES */
static struct usb_driver gtco_driverinfo_table = {
.name = "gtco",
.id_table = gtco_usbid_table,
.probe = gtco_probe,
.disconnect = gtco_disconnect,
};
/*
* Register this module with the USB subsystem
*/
static int __init gtco_init(void)
{
int error;
error = usb_register(>co_driverinfo_table);
if (error) {
err("usb_register() failed rc=0x%x", error);
return error;
}
printk("GTCO usb driver version: %s", GTCO_VERSION);
return 0;
}
/*
* Deregister this module with the USB subsystem
*/
static void __exit gtco_exit(void)
{
usb_deregister(>co_driverinfo_table);
}
module_init(gtco_init);
module_exit(gtco_exit);
MODULE_DESCRIPTION("GTCO digitizer USB driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
kenkit/htc-kernel-saga | drivers/char/agp/sis-agp.c | 4134 | 11465 | /*
* SiS AGPGART routines.
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/agp_backend.h>
#include <linux/delay.h>
#include "agp.h"
#define SIS_ATTBASE 0x90
#define SIS_APSIZE 0x94
#define SIS_TLBCNTRL 0x97
#define SIS_TLBFLUSH 0x98
#define PCI_DEVICE_ID_SI_662 0x0662
#define PCI_DEVICE_ID_SI_671 0x0671
static int __devinitdata agp_sis_force_delay = 0;
static int __devinitdata agp_sis_agp_spec = -1;
static int sis_fetch_size(void)
{
u8 temp_size;
int i;
struct aper_size_info_8 *values;
pci_read_config_byte(agp_bridge->dev, SIS_APSIZE, &temp_size);
values = A_SIZE_8(agp_bridge->driver->aperture_sizes);
for (i = 0; i < agp_bridge->driver->num_aperture_sizes; i++) {
if ((temp_size == values[i].size_value) ||
((temp_size & ~(0x07)) ==
(values[i].size_value & ~(0x07)))) {
agp_bridge->previous_size =
agp_bridge->current_size = (void *) (values + i);
agp_bridge->aperture_size_idx = i;
return values[i].size;
}
}
return 0;
}
static void sis_tlbflush(struct agp_memory *mem)
{
pci_write_config_byte(agp_bridge->dev, SIS_TLBFLUSH, 0x02);
}
static int sis_configure(void)
{
u32 temp;
struct aper_size_info_8 *current_size;
current_size = A_SIZE_8(agp_bridge->current_size);
pci_write_config_byte(agp_bridge->dev, SIS_TLBCNTRL, 0x05);
pci_read_config_dword(agp_bridge->dev, AGP_APBASE, &temp);
agp_bridge->gart_bus_addr = (temp & PCI_BASE_ADDRESS_MEM_MASK);
pci_write_config_dword(agp_bridge->dev, SIS_ATTBASE,
agp_bridge->gatt_bus_addr);
pci_write_config_byte(agp_bridge->dev, SIS_APSIZE,
current_size->size_value);
return 0;
}
static void sis_cleanup(void)
{
struct aper_size_info_8 *previous_size;
previous_size = A_SIZE_8(agp_bridge->previous_size);
pci_write_config_byte(agp_bridge->dev, SIS_APSIZE,
(previous_size->size_value & ~(0x03)));
}
static void sis_delayed_enable(struct agp_bridge_data *bridge, u32 mode)
{
struct pci_dev *device = NULL;
u32 command;
int rate;
dev_info(&agp_bridge->dev->dev, "AGP %d.%d bridge\n",
agp_bridge->major_version, agp_bridge->minor_version);
pci_read_config_dword(agp_bridge->dev, agp_bridge->capndx + PCI_AGP_STATUS, &command);
command = agp_collect_device_status(bridge, mode, command);
command |= AGPSTAT_AGP_ENABLE;
rate = (command & 0x7) << 2;
for_each_pci_dev(device) {
u8 agp = pci_find_capability(device, PCI_CAP_ID_AGP);
if (!agp)
continue;
dev_info(&agp_bridge->dev->dev, "putting AGP V3 device at %s into %dx mode\n",
pci_name(device), rate);
pci_write_config_dword(device, agp + PCI_AGP_COMMAND, command);
/*
* Weird: on some sis chipsets any rate change in the target
* command register triggers a 5ms screwup during which the master
* cannot be configured
*/
if (device->device == bridge->dev->device) {
dev_info(&agp_bridge->dev->dev, "SiS delay workaround: giving bridge time to recover\n");
msleep(10);
}
}
}
static const struct aper_size_info_8 sis_generic_sizes[7] =
{
{256, 65536, 6, 99},
{128, 32768, 5, 83},
{64, 16384, 4, 67},
{32, 8192, 3, 51},
{16, 4096, 2, 35},
{8, 2048, 1, 19},
{4, 1024, 0, 3}
};
static struct agp_bridge_driver sis_driver = {
.owner = THIS_MODULE,
.aperture_sizes = sis_generic_sizes,
.size_type = U8_APER_SIZE,
.num_aperture_sizes = 7,
.needs_scratch_page = true,
.configure = sis_configure,
.fetch_size = sis_fetch_size,
.cleanup = sis_cleanup,
.tlb_flush = sis_tlbflush,
.mask_memory = agp_generic_mask_memory,
.masks = NULL,
.agp_enable = agp_generic_enable,
.cache_flush = global_cache_flush,
.create_gatt_table = agp_generic_create_gatt_table,
.free_gatt_table = agp_generic_free_gatt_table,
.insert_memory = agp_generic_insert_memory,
.remove_memory = agp_generic_remove_memory,
.alloc_by_type = agp_generic_alloc_by_type,
.free_by_type = agp_generic_free_by_type,
.agp_alloc_page = agp_generic_alloc_page,
.agp_alloc_pages = agp_generic_alloc_pages,
.agp_destroy_page = agp_generic_destroy_page,
.agp_destroy_pages = agp_generic_destroy_pages,
.agp_type_to_mask_type = agp_generic_type_to_mask_type,
};
// chipsets that require the 'delay hack'
static int sis_broken_chipsets[] __devinitdata = {
PCI_DEVICE_ID_SI_648,
PCI_DEVICE_ID_SI_746,
0 // terminator
};
static void __devinit sis_get_driver(struct agp_bridge_data *bridge)
{
int i;
for (i=0; sis_broken_chipsets[i]!=0; ++i)
if (bridge->dev->device==sis_broken_chipsets[i])
break;
if (sis_broken_chipsets[i] || agp_sis_force_delay)
sis_driver.agp_enable=sis_delayed_enable;
// sis chipsets that indicate less than agp3.5
// are not actually fully agp3 compliant
if ((agp_bridge->major_version == 3 && agp_bridge->minor_version >= 5
&& agp_sis_agp_spec!=0) || agp_sis_agp_spec==1) {
sis_driver.aperture_sizes = agp3_generic_sizes;
sis_driver.size_type = U16_APER_SIZE;
sis_driver.num_aperture_sizes = AGP_GENERIC_SIZES_ENTRIES;
sis_driver.configure = agp3_generic_configure;
sis_driver.fetch_size = agp3_generic_fetch_size;
sis_driver.cleanup = agp3_generic_cleanup;
sis_driver.tlb_flush = agp3_generic_tlbflush;
}
}
static int __devinit agp_sis_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct agp_bridge_data *bridge;
u8 cap_ptr;
cap_ptr = pci_find_capability(pdev, PCI_CAP_ID_AGP);
if (!cap_ptr)
return -ENODEV;
dev_info(&pdev->dev, "SiS chipset [%04x/%04x]\n",
pdev->vendor, pdev->device);
bridge = agp_alloc_bridge();
if (!bridge)
return -ENOMEM;
bridge->driver = &sis_driver;
bridge->dev = pdev;
bridge->capndx = cap_ptr;
get_agp_version(bridge);
/* Fill in the mode register */
pci_read_config_dword(pdev, bridge->capndx+PCI_AGP_STATUS, &bridge->mode);
sis_get_driver(bridge);
pci_set_drvdata(pdev, bridge);
return agp_add_bridge(bridge);
}
static void __devexit agp_sis_remove(struct pci_dev *pdev)
{
struct agp_bridge_data *bridge = pci_get_drvdata(pdev);
agp_remove_bridge(bridge);
agp_put_bridge(bridge);
}
#ifdef CONFIG_PM
static int agp_sis_suspend(struct pci_dev *pdev, pm_message_t state)
{
pci_save_state(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
}
static int agp_sis_resume(struct pci_dev *pdev)
{
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
return sis_driver.configure();
}
#endif /* CONFIG_PM */
static struct pci_device_id agp_sis_pci_table[] = {
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_5591,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_530,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_540,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_550,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_620,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_630,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_635,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_645,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_646,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_648,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_650,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_651,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_655,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_661,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_662,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_671,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_730,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_735,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_740,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_741,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_745,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_746,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{ }
};
MODULE_DEVICE_TABLE(pci, agp_sis_pci_table);
static struct pci_driver agp_sis_pci_driver = {
.name = "agpgart-sis",
.id_table = agp_sis_pci_table,
.probe = agp_sis_probe,
.remove = agp_sis_remove,
#ifdef CONFIG_PM
.suspend = agp_sis_suspend,
.resume = agp_sis_resume,
#endif
};
static int __init agp_sis_init(void)
{
if (agp_off)
return -EINVAL;
return pci_register_driver(&agp_sis_pci_driver);
}
static void __exit agp_sis_cleanup(void)
{
pci_unregister_driver(&agp_sis_pci_driver);
}
module_init(agp_sis_init);
module_exit(agp_sis_cleanup);
module_param(agp_sis_force_delay, bool, 0);
MODULE_PARM_DESC(agp_sis_force_delay,"forces sis delay hack");
module_param(agp_sis_agp_spec, int, 0);
MODULE_PARM_DESC(agp_sis_agp_spec,"0=force sis init, 1=force generic agp3 init, default: autodetect");
MODULE_LICENSE("GPL and additional rights");
| gpl-2.0 |
fronti90/kernel_lge_geefhd | drivers/media/video/s5p-fimc/fimc-core.c | 4646 | 50345 | /*
* Samsung S5P/EXYNOS4 SoC series camera interface (video postprocessor) driver
*
* Copyright (C) 2010-2011 Samsung Electronics Co., Ltd.
* Contact: Sylwester Nawrocki, <s.nawrocki@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License 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/kernel.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/bug.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/list.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <media/v4l2-ioctl.h>
#include <media/videobuf2-core.h>
#include <media/videobuf2-dma-contig.h>
#include "fimc-core.h"
#include "fimc-mdevice.h"
static char *fimc_clocks[MAX_FIMC_CLOCKS] = {
"sclk_fimc", "fimc"
};
static struct fimc_fmt fimc_formats[] = {
{
.name = "RGB565",
.fourcc = V4L2_PIX_FMT_RGB565,
.depth = { 16 },
.color = S5P_FIMC_RGB565,
.memplanes = 1,
.colplanes = 1,
.flags = FMT_FLAGS_M2M,
}, {
.name = "BGR666",
.fourcc = V4L2_PIX_FMT_BGR666,
.depth = { 32 },
.color = S5P_FIMC_RGB666,
.memplanes = 1,
.colplanes = 1,
.flags = FMT_FLAGS_M2M,
}, {
.name = "ARGB8888, 32 bpp",
.fourcc = V4L2_PIX_FMT_RGB32,
.depth = { 32 },
.color = S5P_FIMC_RGB888,
.memplanes = 1,
.colplanes = 1,
.flags = FMT_FLAGS_M2M | FMT_HAS_ALPHA,
}, {
.name = "ARGB1555",
.fourcc = V4L2_PIX_FMT_RGB555,
.depth = { 16 },
.color = S5P_FIMC_RGB555,
.memplanes = 1,
.colplanes = 1,
.flags = FMT_FLAGS_M2M_OUT | FMT_HAS_ALPHA,
}, {
.name = "ARGB4444",
.fourcc = V4L2_PIX_FMT_RGB444,
.depth = { 16 },
.color = S5P_FIMC_RGB444,
.memplanes = 1,
.colplanes = 1,
.flags = FMT_FLAGS_M2M_OUT | FMT_HAS_ALPHA,
}, {
.name = "YUV 4:2:2 packed, YCbYCr",
.fourcc = V4L2_PIX_FMT_YUYV,
.depth = { 16 },
.color = S5P_FIMC_YCBYCR422,
.memplanes = 1,
.colplanes = 1,
.mbus_code = V4L2_MBUS_FMT_YUYV8_2X8,
.flags = FMT_FLAGS_M2M | FMT_FLAGS_CAM,
}, {
.name = "YUV 4:2:2 packed, CbYCrY",
.fourcc = V4L2_PIX_FMT_UYVY,
.depth = { 16 },
.color = S5P_FIMC_CBYCRY422,
.memplanes = 1,
.colplanes = 1,
.mbus_code = V4L2_MBUS_FMT_UYVY8_2X8,
.flags = FMT_FLAGS_M2M | FMT_FLAGS_CAM,
}, {
.name = "YUV 4:2:2 packed, CrYCbY",
.fourcc = V4L2_PIX_FMT_VYUY,
.depth = { 16 },
.color = S5P_FIMC_CRYCBY422,
.memplanes = 1,
.colplanes = 1,
.mbus_code = V4L2_MBUS_FMT_VYUY8_2X8,
.flags = FMT_FLAGS_M2M | FMT_FLAGS_CAM,
}, {
.name = "YUV 4:2:2 packed, YCrYCb",
.fourcc = V4L2_PIX_FMT_YVYU,
.depth = { 16 },
.color = S5P_FIMC_YCRYCB422,
.memplanes = 1,
.colplanes = 1,
.mbus_code = V4L2_MBUS_FMT_YVYU8_2X8,
.flags = FMT_FLAGS_M2M | FMT_FLAGS_CAM,
}, {
.name = "YUV 4:2:2 planar, Y/Cb/Cr",
.fourcc = V4L2_PIX_FMT_YUV422P,
.depth = { 12 },
.color = S5P_FIMC_YCBYCR422,
.memplanes = 1,
.colplanes = 3,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:2 planar, Y/CbCr",
.fourcc = V4L2_PIX_FMT_NV16,
.depth = { 16 },
.color = S5P_FIMC_YCBYCR422,
.memplanes = 1,
.colplanes = 2,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:2 planar, Y/CrCb",
.fourcc = V4L2_PIX_FMT_NV61,
.depth = { 16 },
.color = S5P_FIMC_YCRYCB422,
.memplanes = 1,
.colplanes = 2,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:0 planar, YCbCr",
.fourcc = V4L2_PIX_FMT_YUV420,
.depth = { 12 },
.color = S5P_FIMC_YCBCR420,
.memplanes = 1,
.colplanes = 3,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:0 planar, Y/CbCr",
.fourcc = V4L2_PIX_FMT_NV12,
.depth = { 12 },
.color = S5P_FIMC_YCBCR420,
.memplanes = 1,
.colplanes = 2,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:0 non-contiguous 2-planar, Y/CbCr",
.fourcc = V4L2_PIX_FMT_NV12M,
.color = S5P_FIMC_YCBCR420,
.depth = { 8, 4 },
.memplanes = 2,
.colplanes = 2,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:0 non-contiguous 3-planar, Y/Cb/Cr",
.fourcc = V4L2_PIX_FMT_YUV420M,
.color = S5P_FIMC_YCBCR420,
.depth = { 8, 2, 2 },
.memplanes = 3,
.colplanes = 3,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:0 non-contiguous 2-planar, Y/CbCr, tiled",
.fourcc = V4L2_PIX_FMT_NV12MT,
.color = S5P_FIMC_YCBCR420,
.depth = { 8, 4 },
.memplanes = 2,
.colplanes = 2,
.flags = FMT_FLAGS_M2M,
}, {
.name = "JPEG encoded data",
.fourcc = V4L2_PIX_FMT_JPEG,
.color = S5P_FIMC_JPEG,
.depth = { 8 },
.memplanes = 1,
.colplanes = 1,
.mbus_code = V4L2_MBUS_FMT_JPEG_1X8,
.flags = FMT_FLAGS_CAM,
},
};
static unsigned int get_m2m_fmt_flags(unsigned int stream_type)
{
if (stream_type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
return FMT_FLAGS_M2M_IN;
else
return FMT_FLAGS_M2M_OUT;
}
int fimc_check_scaler_ratio(struct fimc_ctx *ctx, int sw, int sh,
int dw, int dh, int rotation)
{
if (rotation == 90 || rotation == 270)
swap(dw, dh);
if (!ctx->scaler.enabled)
return (sw == dw && sh == dh) ? 0 : -EINVAL;
if ((sw >= SCALER_MAX_HRATIO * dw) || (sh >= SCALER_MAX_VRATIO * dh))
return -EINVAL;
return 0;
}
static int fimc_get_scaler_factor(u32 src, u32 tar, u32 *ratio, u32 *shift)
{
u32 sh = 6;
if (src >= 64 * tar)
return -EINVAL;
while (sh--) {
u32 tmp = 1 << sh;
if (src >= tar * tmp) {
*shift = sh, *ratio = tmp;
return 0;
}
}
*shift = 0, *ratio = 1;
return 0;
}
int fimc_set_scaler_info(struct fimc_ctx *ctx)
{
struct samsung_fimc_variant *variant = ctx->fimc_dev->variant;
struct device *dev = &ctx->fimc_dev->pdev->dev;
struct fimc_scaler *sc = &ctx->scaler;
struct fimc_frame *s_frame = &ctx->s_frame;
struct fimc_frame *d_frame = &ctx->d_frame;
int tx, ty, sx, sy;
int ret;
if (ctx->rotation == 90 || ctx->rotation == 270) {
ty = d_frame->width;
tx = d_frame->height;
} else {
tx = d_frame->width;
ty = d_frame->height;
}
if (tx <= 0 || ty <= 0) {
dev_err(dev, "Invalid target size: %dx%d", tx, ty);
return -EINVAL;
}
sx = s_frame->width;
sy = s_frame->height;
if (sx <= 0 || sy <= 0) {
dev_err(dev, "Invalid source size: %dx%d", sx, sy);
return -EINVAL;
}
sc->real_width = sx;
sc->real_height = sy;
ret = fimc_get_scaler_factor(sx, tx, &sc->pre_hratio, &sc->hfactor);
if (ret)
return ret;
ret = fimc_get_scaler_factor(sy, ty, &sc->pre_vratio, &sc->vfactor);
if (ret)
return ret;
sc->pre_dst_width = sx / sc->pre_hratio;
sc->pre_dst_height = sy / sc->pre_vratio;
if (variant->has_mainscaler_ext) {
sc->main_hratio = (sx << 14) / (tx << sc->hfactor);
sc->main_vratio = (sy << 14) / (ty << sc->vfactor);
} else {
sc->main_hratio = (sx << 8) / (tx << sc->hfactor);
sc->main_vratio = (sy << 8) / (ty << sc->vfactor);
}
sc->scaleup_h = (tx >= sx) ? 1 : 0;
sc->scaleup_v = (ty >= sy) ? 1 : 0;
/* check to see if input and output size/format differ */
if (s_frame->fmt->color == d_frame->fmt->color
&& s_frame->width == d_frame->width
&& s_frame->height == d_frame->height)
sc->copy_mode = 1;
else
sc->copy_mode = 0;
return 0;
}
static void fimc_m2m_job_finish(struct fimc_ctx *ctx, int vb_state)
{
struct vb2_buffer *src_vb, *dst_vb;
if (!ctx || !ctx->m2m_ctx)
return;
src_vb = v4l2_m2m_src_buf_remove(ctx->m2m_ctx);
dst_vb = v4l2_m2m_dst_buf_remove(ctx->m2m_ctx);
if (src_vb && dst_vb) {
v4l2_m2m_buf_done(src_vb, vb_state);
v4l2_m2m_buf_done(dst_vb, vb_state);
v4l2_m2m_job_finish(ctx->fimc_dev->m2m.m2m_dev,
ctx->m2m_ctx);
}
}
/* Complete the transaction which has been scheduled for execution. */
static int fimc_m2m_shutdown(struct fimc_ctx *ctx)
{
struct fimc_dev *fimc = ctx->fimc_dev;
int ret;
if (!fimc_m2m_pending(fimc))
return 0;
fimc_ctx_state_lock_set(FIMC_CTX_SHUT, ctx);
ret = wait_event_timeout(fimc->irq_queue,
!fimc_ctx_state_is_set(FIMC_CTX_SHUT, ctx),
FIMC_SHUTDOWN_TIMEOUT);
return ret == 0 ? -ETIMEDOUT : ret;
}
static int start_streaming(struct vb2_queue *q, unsigned int count)
{
struct fimc_ctx *ctx = q->drv_priv;
int ret;
ret = pm_runtime_get_sync(&ctx->fimc_dev->pdev->dev);
return ret > 0 ? 0 : ret;
}
static int stop_streaming(struct vb2_queue *q)
{
struct fimc_ctx *ctx = q->drv_priv;
int ret;
ret = fimc_m2m_shutdown(ctx);
if (ret == -ETIMEDOUT)
fimc_m2m_job_finish(ctx, VB2_BUF_STATE_ERROR);
pm_runtime_put(&ctx->fimc_dev->pdev->dev);
return 0;
}
void fimc_capture_irq_handler(struct fimc_dev *fimc, bool final)
{
struct fimc_vid_cap *cap = &fimc->vid_cap;
struct fimc_vid_buffer *v_buf;
struct timeval *tv;
struct timespec ts;
if (test_and_clear_bit(ST_CAPT_SHUT, &fimc->state)) {
wake_up(&fimc->irq_queue);
return;
}
if (!list_empty(&cap->active_buf_q) &&
test_bit(ST_CAPT_RUN, &fimc->state) && final) {
ktime_get_real_ts(&ts);
v_buf = fimc_active_queue_pop(cap);
tv = &v_buf->vb.v4l2_buf.timestamp;
tv->tv_sec = ts.tv_sec;
tv->tv_usec = ts.tv_nsec / NSEC_PER_USEC;
v_buf->vb.v4l2_buf.sequence = cap->frame_count++;
vb2_buffer_done(&v_buf->vb, VB2_BUF_STATE_DONE);
}
if (!list_empty(&cap->pending_buf_q)) {
v_buf = fimc_pending_queue_pop(cap);
fimc_hw_set_output_addr(fimc, &v_buf->paddr, cap->buf_index);
v_buf->index = cap->buf_index;
/* Move the buffer to the capture active queue */
fimc_active_queue_add(cap, v_buf);
dbg("next frame: %d, done frame: %d",
fimc_hw_get_frame_index(fimc), v_buf->index);
if (++cap->buf_index >= FIMC_MAX_OUT_BUFS)
cap->buf_index = 0;
}
if (cap->active_buf_cnt == 0) {
if (final)
clear_bit(ST_CAPT_RUN, &fimc->state);
if (++cap->buf_index >= FIMC_MAX_OUT_BUFS)
cap->buf_index = 0;
} else {
set_bit(ST_CAPT_RUN, &fimc->state);
}
fimc_capture_config_update(cap->ctx);
dbg("frame: %d, active_buf_cnt: %d",
fimc_hw_get_frame_index(fimc), cap->active_buf_cnt);
}
static irqreturn_t fimc_irq_handler(int irq, void *priv)
{
struct fimc_dev *fimc = priv;
struct fimc_vid_cap *cap = &fimc->vid_cap;
struct fimc_ctx *ctx;
fimc_hw_clear_irq(fimc);
spin_lock(&fimc->slock);
if (test_and_clear_bit(ST_M2M_PEND, &fimc->state)) {
if (test_and_clear_bit(ST_M2M_SUSPENDING, &fimc->state)) {
set_bit(ST_M2M_SUSPENDED, &fimc->state);
wake_up(&fimc->irq_queue);
goto out;
}
ctx = v4l2_m2m_get_curr_priv(fimc->m2m.m2m_dev);
if (ctx != NULL) {
spin_unlock(&fimc->slock);
fimc_m2m_job_finish(ctx, VB2_BUF_STATE_DONE);
spin_lock(&ctx->slock);
if (ctx->state & FIMC_CTX_SHUT) {
ctx->state &= ~FIMC_CTX_SHUT;
wake_up(&fimc->irq_queue);
}
spin_unlock(&ctx->slock);
}
return IRQ_HANDLED;
} else if (test_bit(ST_CAPT_PEND, &fimc->state)) {
fimc_capture_irq_handler(fimc,
!test_bit(ST_CAPT_JPEG, &fimc->state));
if (cap->active_buf_cnt == 1) {
fimc_deactivate_capture(fimc);
clear_bit(ST_CAPT_STREAM, &fimc->state);
}
}
out:
spin_unlock(&fimc->slock);
return IRQ_HANDLED;
}
/* The color format (colplanes, memplanes) must be already configured. */
int fimc_prepare_addr(struct fimc_ctx *ctx, struct vb2_buffer *vb,
struct fimc_frame *frame, struct fimc_addr *paddr)
{
int ret = 0;
u32 pix_size;
if (vb == NULL || frame == NULL)
return -EINVAL;
pix_size = frame->width * frame->height;
dbg("memplanes= %d, colplanes= %d, pix_size= %d",
frame->fmt->memplanes, frame->fmt->colplanes, pix_size);
paddr->y = vb2_dma_contig_plane_dma_addr(vb, 0);
if (frame->fmt->memplanes == 1) {
switch (frame->fmt->colplanes) {
case 1:
paddr->cb = 0;
paddr->cr = 0;
break;
case 2:
/* decompose Y into Y/Cb */
paddr->cb = (u32)(paddr->y + pix_size);
paddr->cr = 0;
break;
case 3:
paddr->cb = (u32)(paddr->y + pix_size);
/* decompose Y into Y/Cb/Cr */
if (S5P_FIMC_YCBCR420 == frame->fmt->color)
paddr->cr = (u32)(paddr->cb
+ (pix_size >> 2));
else /* 422 */
paddr->cr = (u32)(paddr->cb
+ (pix_size >> 1));
break;
default:
return -EINVAL;
}
} else {
if (frame->fmt->memplanes >= 2)
paddr->cb = vb2_dma_contig_plane_dma_addr(vb, 1);
if (frame->fmt->memplanes == 3)
paddr->cr = vb2_dma_contig_plane_dma_addr(vb, 2);
}
dbg("PHYS_ADDR: y= 0x%X cb= 0x%X cr= 0x%X ret= %d",
paddr->y, paddr->cb, paddr->cr, ret);
return ret;
}
/* Set order for 1 and 2 plane YCBCR 4:2:2 formats. */
void fimc_set_yuv_order(struct fimc_ctx *ctx)
{
/* The one only mode supported in SoC. */
ctx->in_order_2p = S5P_FIMC_LSB_CRCB;
ctx->out_order_2p = S5P_FIMC_LSB_CRCB;
/* Set order for 1 plane input formats. */
switch (ctx->s_frame.fmt->color) {
case S5P_FIMC_YCRYCB422:
ctx->in_order_1p = S5P_MSCTRL_ORDER422_CBYCRY;
break;
case S5P_FIMC_CBYCRY422:
ctx->in_order_1p = S5P_MSCTRL_ORDER422_YCRYCB;
break;
case S5P_FIMC_CRYCBY422:
ctx->in_order_1p = S5P_MSCTRL_ORDER422_YCBYCR;
break;
case S5P_FIMC_YCBYCR422:
default:
ctx->in_order_1p = S5P_MSCTRL_ORDER422_CRYCBY;
break;
}
dbg("ctx->in_order_1p= %d", ctx->in_order_1p);
switch (ctx->d_frame.fmt->color) {
case S5P_FIMC_YCRYCB422:
ctx->out_order_1p = S5P_CIOCTRL_ORDER422_CBYCRY;
break;
case S5P_FIMC_CBYCRY422:
ctx->out_order_1p = S5P_CIOCTRL_ORDER422_YCRYCB;
break;
case S5P_FIMC_CRYCBY422:
ctx->out_order_1p = S5P_CIOCTRL_ORDER422_YCBYCR;
break;
case S5P_FIMC_YCBYCR422:
default:
ctx->out_order_1p = S5P_CIOCTRL_ORDER422_CRYCBY;
break;
}
dbg("ctx->out_order_1p= %d", ctx->out_order_1p);
}
void fimc_prepare_dma_offset(struct fimc_ctx *ctx, struct fimc_frame *f)
{
struct samsung_fimc_variant *variant = ctx->fimc_dev->variant;
u32 i, depth = 0;
for (i = 0; i < f->fmt->colplanes; i++)
depth += f->fmt->depth[i];
f->dma_offset.y_h = f->offs_h;
if (!variant->pix_hoff)
f->dma_offset.y_h *= (depth >> 3);
f->dma_offset.y_v = f->offs_v;
f->dma_offset.cb_h = f->offs_h;
f->dma_offset.cb_v = f->offs_v;
f->dma_offset.cr_h = f->offs_h;
f->dma_offset.cr_v = f->offs_v;
if (!variant->pix_hoff) {
if (f->fmt->colplanes == 3) {
f->dma_offset.cb_h >>= 1;
f->dma_offset.cr_h >>= 1;
}
if (f->fmt->color == S5P_FIMC_YCBCR420) {
f->dma_offset.cb_v >>= 1;
f->dma_offset.cr_v >>= 1;
}
}
dbg("in_offset: color= %d, y_h= %d, y_v= %d",
f->fmt->color, f->dma_offset.y_h, f->dma_offset.y_v);
}
/**
* fimc_prepare_config - check dimensions, operation and color mode
* and pre-calculate offset and the scaling coefficients.
*
* @ctx: hardware context information
* @flags: flags indicating which parameters to check/update
*
* Return: 0 if dimensions are valid or non zero otherwise.
*/
int fimc_prepare_config(struct fimc_ctx *ctx, u32 flags)
{
struct fimc_frame *s_frame, *d_frame;
struct vb2_buffer *vb = NULL;
int ret = 0;
s_frame = &ctx->s_frame;
d_frame = &ctx->d_frame;
if (flags & FIMC_PARAMS) {
/* Prepare the DMA offset ratios for scaler. */
fimc_prepare_dma_offset(ctx, &ctx->s_frame);
fimc_prepare_dma_offset(ctx, &ctx->d_frame);
if (s_frame->height > (SCALER_MAX_VRATIO * d_frame->height) ||
s_frame->width > (SCALER_MAX_HRATIO * d_frame->width)) {
err("out of scaler range");
return -EINVAL;
}
fimc_set_yuv_order(ctx);
}
if (flags & FIMC_SRC_ADDR) {
vb = v4l2_m2m_next_src_buf(ctx->m2m_ctx);
ret = fimc_prepare_addr(ctx, vb, s_frame, &s_frame->paddr);
if (ret)
return ret;
}
if (flags & FIMC_DST_ADDR) {
vb = v4l2_m2m_next_dst_buf(ctx->m2m_ctx);
ret = fimc_prepare_addr(ctx, vb, d_frame, &d_frame->paddr);
}
return ret;
}
static void fimc_dma_run(void *priv)
{
struct fimc_ctx *ctx = priv;
struct fimc_dev *fimc;
unsigned long flags;
u32 ret;
if (WARN(!ctx, "null hardware context\n"))
return;
fimc = ctx->fimc_dev;
spin_lock_irqsave(&fimc->slock, flags);
set_bit(ST_M2M_PEND, &fimc->state);
spin_lock(&ctx->slock);
ctx->state |= (FIMC_SRC_ADDR | FIMC_DST_ADDR);
ret = fimc_prepare_config(ctx, ctx->state);
if (ret)
goto dma_unlock;
/* Reconfigure hardware if the context has changed. */
if (fimc->m2m.ctx != ctx) {
ctx->state |= FIMC_PARAMS;
fimc->m2m.ctx = ctx;
}
fimc_hw_set_input_addr(fimc, &ctx->s_frame.paddr);
if (ctx->state & FIMC_PARAMS) {
fimc_hw_set_input_path(ctx);
fimc_hw_set_in_dma(ctx);
ret = fimc_set_scaler_info(ctx);
if (ret) {
spin_unlock(&fimc->slock);
goto dma_unlock;
}
fimc_hw_set_prescaler(ctx);
fimc_hw_set_mainscaler(ctx);
fimc_hw_set_target_format(ctx);
fimc_hw_set_rotation(ctx);
fimc_hw_set_effect(ctx, false);
}
fimc_hw_set_output_path(ctx);
if (ctx->state & (FIMC_DST_ADDR | FIMC_PARAMS))
fimc_hw_set_output_addr(fimc, &ctx->d_frame.paddr, -1);
if (ctx->state & FIMC_PARAMS) {
fimc_hw_set_out_dma(ctx);
if (fimc->variant->has_alpha)
fimc_hw_set_rgb_alpha(ctx);
}
fimc_activate_capture(ctx);
ctx->state &= (FIMC_CTX_M2M | FIMC_CTX_CAP |
FIMC_SRC_FMT | FIMC_DST_FMT);
fimc_hw_activate_input_dma(fimc, true);
dma_unlock:
spin_unlock(&ctx->slock);
spin_unlock_irqrestore(&fimc->slock, flags);
}
static void fimc_job_abort(void *priv)
{
fimc_m2m_shutdown(priv);
}
static int fimc_queue_setup(struct vb2_queue *vq, const struct v4l2_format *fmt,
unsigned int *num_buffers, unsigned int *num_planes,
unsigned int sizes[], void *allocators[])
{
struct fimc_ctx *ctx = vb2_get_drv_priv(vq);
struct fimc_frame *f;
int i;
f = ctx_get_frame(ctx, vq->type);
if (IS_ERR(f))
return PTR_ERR(f);
/*
* Return number of non-contigous planes (plane buffers)
* depending on the configured color format.
*/
if (!f->fmt)
return -EINVAL;
*num_planes = f->fmt->memplanes;
for (i = 0; i < f->fmt->memplanes; i++) {
sizes[i] = (f->f_width * f->f_height * f->fmt->depth[i]) / 8;
allocators[i] = ctx->fimc_dev->alloc_ctx;
}
return 0;
}
static int fimc_buf_prepare(struct vb2_buffer *vb)
{
struct fimc_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
struct fimc_frame *frame;
int i;
frame = ctx_get_frame(ctx, vb->vb2_queue->type);
if (IS_ERR(frame))
return PTR_ERR(frame);
for (i = 0; i < frame->fmt->memplanes; i++)
vb2_set_plane_payload(vb, i, frame->payload[i]);
return 0;
}
static void fimc_buf_queue(struct vb2_buffer *vb)
{
struct fimc_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
dbg("ctx: %p, ctx->state: 0x%x", ctx, ctx->state);
if (ctx->m2m_ctx)
v4l2_m2m_buf_queue(ctx->m2m_ctx, vb);
}
static void fimc_lock(struct vb2_queue *vq)
{
struct fimc_ctx *ctx = vb2_get_drv_priv(vq);
mutex_lock(&ctx->fimc_dev->lock);
}
static void fimc_unlock(struct vb2_queue *vq)
{
struct fimc_ctx *ctx = vb2_get_drv_priv(vq);
mutex_unlock(&ctx->fimc_dev->lock);
}
static struct vb2_ops fimc_qops = {
.queue_setup = fimc_queue_setup,
.buf_prepare = fimc_buf_prepare,
.buf_queue = fimc_buf_queue,
.wait_prepare = fimc_unlock,
.wait_finish = fimc_lock,
.stop_streaming = stop_streaming,
.start_streaming = start_streaming,
};
/*
* V4L2 controls handling
*/
#define ctrl_to_ctx(__ctrl) \
container_of((__ctrl)->handler, struct fimc_ctx, ctrl_handler)
static int __fimc_s_ctrl(struct fimc_ctx *ctx, struct v4l2_ctrl *ctrl)
{
struct fimc_dev *fimc = ctx->fimc_dev;
struct samsung_fimc_variant *variant = fimc->variant;
unsigned int flags = FIMC_DST_FMT | FIMC_SRC_FMT;
int ret = 0;
if (ctrl->flags & V4L2_CTRL_FLAG_INACTIVE)
return 0;
switch (ctrl->id) {
case V4L2_CID_HFLIP:
ctx->hflip = ctrl->val;
break;
case V4L2_CID_VFLIP:
ctx->vflip = ctrl->val;
break;
case V4L2_CID_ROTATE:
if (fimc_capture_pending(fimc) ||
(ctx->state & flags) == flags) {
ret = fimc_check_scaler_ratio(ctx, ctx->s_frame.width,
ctx->s_frame.height, ctx->d_frame.width,
ctx->d_frame.height, ctrl->val);
if (ret)
return -EINVAL;
}
if ((ctrl->val == 90 || ctrl->val == 270) &&
!variant->has_out_rot)
return -EINVAL;
ctx->rotation = ctrl->val;
break;
case V4L2_CID_ALPHA_COMPONENT:
ctx->d_frame.alpha = ctrl->val;
break;
}
ctx->state |= FIMC_PARAMS;
set_bit(ST_CAPT_APPLY_CFG, &fimc->state);
return 0;
}
static int fimc_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct fimc_ctx *ctx = ctrl_to_ctx(ctrl);
unsigned long flags;
int ret;
spin_lock_irqsave(&ctx->slock, flags);
ret = __fimc_s_ctrl(ctx, ctrl);
spin_unlock_irqrestore(&ctx->slock, flags);
return ret;
}
static const struct v4l2_ctrl_ops fimc_ctrl_ops = {
.s_ctrl = fimc_s_ctrl,
};
int fimc_ctrls_create(struct fimc_ctx *ctx)
{
struct samsung_fimc_variant *variant = ctx->fimc_dev->variant;
unsigned int max_alpha = fimc_get_alpha_mask(ctx->d_frame.fmt);
if (ctx->ctrls_rdy)
return 0;
v4l2_ctrl_handler_init(&ctx->ctrl_handler, 4);
ctx->ctrl_rotate = v4l2_ctrl_new_std(&ctx->ctrl_handler, &fimc_ctrl_ops,
V4L2_CID_ROTATE, 0, 270, 90, 0);
ctx->ctrl_hflip = v4l2_ctrl_new_std(&ctx->ctrl_handler, &fimc_ctrl_ops,
V4L2_CID_HFLIP, 0, 1, 1, 0);
ctx->ctrl_vflip = v4l2_ctrl_new_std(&ctx->ctrl_handler, &fimc_ctrl_ops,
V4L2_CID_VFLIP, 0, 1, 1, 0);
if (variant->has_alpha)
ctx->ctrl_alpha = v4l2_ctrl_new_std(&ctx->ctrl_handler,
&fimc_ctrl_ops, V4L2_CID_ALPHA_COMPONENT,
0, max_alpha, 1, 0);
else
ctx->ctrl_alpha = NULL;
ctx->ctrls_rdy = ctx->ctrl_handler.error == 0;
return ctx->ctrl_handler.error;
}
void fimc_ctrls_delete(struct fimc_ctx *ctx)
{
if (ctx->ctrls_rdy) {
v4l2_ctrl_handler_free(&ctx->ctrl_handler);
ctx->ctrls_rdy = false;
ctx->ctrl_alpha = NULL;
}
}
void fimc_ctrls_activate(struct fimc_ctx *ctx, bool active)
{
unsigned int has_alpha = ctx->d_frame.fmt->flags & FMT_HAS_ALPHA;
if (!ctx->ctrls_rdy)
return;
mutex_lock(&ctx->ctrl_handler.lock);
v4l2_ctrl_activate(ctx->ctrl_rotate, active);
v4l2_ctrl_activate(ctx->ctrl_hflip, active);
v4l2_ctrl_activate(ctx->ctrl_vflip, active);
if (ctx->ctrl_alpha)
v4l2_ctrl_activate(ctx->ctrl_alpha, active && has_alpha);
if (active) {
ctx->rotation = ctx->ctrl_rotate->val;
ctx->hflip = ctx->ctrl_hflip->val;
ctx->vflip = ctx->ctrl_vflip->val;
} else {
ctx->rotation = 0;
ctx->hflip = 0;
ctx->vflip = 0;
}
mutex_unlock(&ctx->ctrl_handler.lock);
}
/* Update maximum value of the alpha color control */
void fimc_alpha_ctrl_update(struct fimc_ctx *ctx)
{
struct fimc_dev *fimc = ctx->fimc_dev;
struct v4l2_ctrl *ctrl = ctx->ctrl_alpha;
if (ctrl == NULL || !fimc->variant->has_alpha)
return;
v4l2_ctrl_lock(ctrl);
ctrl->maximum = fimc_get_alpha_mask(ctx->d_frame.fmt);
if (ctrl->cur.val > ctrl->maximum)
ctrl->cur.val = ctrl->maximum;
v4l2_ctrl_unlock(ctrl);
}
/*
* V4L2 ioctl handlers
*/
static int fimc_m2m_querycap(struct file *file, void *fh,
struct v4l2_capability *cap)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
struct fimc_dev *fimc = ctx->fimc_dev;
strncpy(cap->driver, fimc->pdev->name, sizeof(cap->driver) - 1);
strncpy(cap->card, fimc->pdev->name, sizeof(cap->card) - 1);
cap->bus_info[0] = 0;
cap->capabilities = V4L2_CAP_STREAMING |
V4L2_CAP_VIDEO_CAPTURE_MPLANE | V4L2_CAP_VIDEO_OUTPUT_MPLANE;
return 0;
}
static int fimc_m2m_enum_fmt_mplane(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
struct fimc_fmt *fmt;
fmt = fimc_find_format(NULL, NULL, get_m2m_fmt_flags(f->type),
f->index);
if (!fmt)
return -EINVAL;
strncpy(f->description, fmt->name, sizeof(f->description) - 1);
f->pixelformat = fmt->fourcc;
return 0;
}
int fimc_fill_format(struct fimc_frame *frame, struct v4l2_format *f)
{
struct v4l2_pix_format_mplane *pixm = &f->fmt.pix_mp;
int i;
pixm->width = frame->o_width;
pixm->height = frame->o_height;
pixm->field = V4L2_FIELD_NONE;
pixm->pixelformat = frame->fmt->fourcc;
pixm->colorspace = V4L2_COLORSPACE_JPEG;
pixm->num_planes = frame->fmt->memplanes;
for (i = 0; i < pixm->num_planes; ++i) {
int bpl = frame->f_width;
if (frame->fmt->colplanes == 1) /* packed formats */
bpl = (bpl * frame->fmt->depth[0]) / 8;
pixm->plane_fmt[i].bytesperline = bpl;
pixm->plane_fmt[i].sizeimage = (frame->o_width *
frame->o_height * frame->fmt->depth[i]) / 8;
}
return 0;
}
void fimc_fill_frame(struct fimc_frame *frame, struct v4l2_format *f)
{
struct v4l2_pix_format_mplane *pixm = &f->fmt.pix_mp;
frame->f_width = pixm->plane_fmt[0].bytesperline;
if (frame->fmt->colplanes == 1)
frame->f_width = (frame->f_width * 8) / frame->fmt->depth[0];
frame->f_height = pixm->height;
frame->width = pixm->width;
frame->height = pixm->height;
frame->o_width = pixm->width;
frame->o_height = pixm->height;
frame->offs_h = 0;
frame->offs_v = 0;
}
/**
* fimc_adjust_mplane_format - adjust bytesperline/sizeimage for each plane
* @fmt: fimc pixel format description (input)
* @width: requested pixel width
* @height: requested pixel height
* @pix: multi-plane format to adjust
*/
void fimc_adjust_mplane_format(struct fimc_fmt *fmt, u32 width, u32 height,
struct v4l2_pix_format_mplane *pix)
{
u32 bytesperline = 0;
int i;
pix->colorspace = V4L2_COLORSPACE_JPEG;
pix->field = V4L2_FIELD_NONE;
pix->num_planes = fmt->memplanes;
pix->pixelformat = fmt->fourcc;
pix->height = height;
pix->width = width;
for (i = 0; i < pix->num_planes; ++i) {
u32 bpl = pix->plane_fmt[i].bytesperline;
u32 *sizeimage = &pix->plane_fmt[i].sizeimage;
if (fmt->colplanes > 1 && (bpl == 0 || bpl < pix->width))
bpl = pix->width; /* Planar */
if (fmt->colplanes == 1 && /* Packed */
(bpl == 0 || ((bpl * 8) / fmt->depth[i]) < pix->width))
bpl = (pix->width * fmt->depth[0]) / 8;
if (i == 0) /* Same bytesperline for each plane. */
bytesperline = bpl;
pix->plane_fmt[i].bytesperline = bytesperline;
*sizeimage = (pix->width * pix->height * fmt->depth[i]) / 8;
}
}
static int fimc_m2m_g_fmt_mplane(struct file *file, void *fh,
struct v4l2_format *f)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
struct fimc_frame *frame = ctx_get_frame(ctx, f->type);
if (IS_ERR(frame))
return PTR_ERR(frame);
return fimc_fill_format(frame, f);
}
/**
* fimc_find_format - lookup fimc color format by fourcc or media bus format
* @pixelformat: fourcc to match, ignored if null
* @mbus_code: media bus code to match, ignored if null
* @mask: the color flags to match
* @index: offset in the fimc_formats array, ignored if negative
*/
struct fimc_fmt *fimc_find_format(const u32 *pixelformat, const u32 *mbus_code,
unsigned int mask, int index)
{
struct fimc_fmt *fmt, *def_fmt = NULL;
unsigned int i;
int id = 0;
if (index >= (int)ARRAY_SIZE(fimc_formats))
return NULL;
for (i = 0; i < ARRAY_SIZE(fimc_formats); ++i) {
fmt = &fimc_formats[i];
if (!(fmt->flags & mask))
continue;
if (pixelformat && fmt->fourcc == *pixelformat)
return fmt;
if (mbus_code && fmt->mbus_code == *mbus_code)
return fmt;
if (index == id)
def_fmt = fmt;
id++;
}
return def_fmt;
}
static int fimc_try_fmt_mplane(struct fimc_ctx *ctx, struct v4l2_format *f)
{
struct fimc_dev *fimc = ctx->fimc_dev;
struct samsung_fimc_variant *variant = fimc->variant;
struct v4l2_pix_format_mplane *pix = &f->fmt.pix_mp;
struct fimc_fmt *fmt;
u32 max_w, mod_x, mod_y;
if (!IS_M2M(f->type))
return -EINVAL;
dbg("w: %d, h: %d", pix->width, pix->height);
fmt = fimc_find_format(&pix->pixelformat, NULL,
get_m2m_fmt_flags(f->type), 0);
if (WARN(fmt == NULL, "Pixel format lookup failed"))
return -EINVAL;
if (pix->field == V4L2_FIELD_ANY)
pix->field = V4L2_FIELD_NONE;
else if (pix->field != V4L2_FIELD_NONE)
return -EINVAL;
if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
max_w = variant->pix_limit->scaler_dis_w;
mod_x = ffs(variant->min_inp_pixsize) - 1;
} else {
max_w = variant->pix_limit->out_rot_dis_w;
mod_x = ffs(variant->min_out_pixsize) - 1;
}
if (tiled_fmt(fmt)) {
mod_x = 6; /* 64 x 32 pixels tile */
mod_y = 5;
} else {
if (variant->min_vsize_align == 1)
mod_y = fimc_fmt_is_rgb(fmt->color) ? 0 : 1;
else
mod_y = ffs(variant->min_vsize_align) - 1;
}
v4l_bound_align_image(&pix->width, 16, max_w, mod_x,
&pix->height, 8, variant->pix_limit->scaler_dis_w, mod_y, 0);
fimc_adjust_mplane_format(fmt, pix->width, pix->height, &f->fmt.pix_mp);
return 0;
}
static int fimc_m2m_try_fmt_mplane(struct file *file, void *fh,
struct v4l2_format *f)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
return fimc_try_fmt_mplane(ctx, f);
}
static int fimc_m2m_s_fmt_mplane(struct file *file, void *fh,
struct v4l2_format *f)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
struct fimc_dev *fimc = ctx->fimc_dev;
struct vb2_queue *vq;
struct fimc_frame *frame;
struct v4l2_pix_format_mplane *pix;
int i, ret = 0;
ret = fimc_try_fmt_mplane(ctx, f);
if (ret)
return ret;
vq = v4l2_m2m_get_vq(ctx->m2m_ctx, f->type);
if (vb2_is_busy(vq)) {
v4l2_err(fimc->m2m.vfd, "queue (%d) busy\n", f->type);
return -EBUSY;
}
if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
frame = &ctx->s_frame;
else
frame = &ctx->d_frame;
pix = &f->fmt.pix_mp;
frame->fmt = fimc_find_format(&pix->pixelformat, NULL,
get_m2m_fmt_flags(f->type), 0);
if (!frame->fmt)
return -EINVAL;
/* Update RGB Alpha control state and value range */
fimc_alpha_ctrl_update(ctx);
for (i = 0; i < frame->fmt->colplanes; i++) {
frame->payload[i] =
(pix->width * pix->height * frame->fmt->depth[i]) / 8;
}
fimc_fill_frame(frame, f);
ctx->scaler.enabled = 1;
if (f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
fimc_ctx_state_lock_set(FIMC_PARAMS | FIMC_DST_FMT, ctx);
else
fimc_ctx_state_lock_set(FIMC_PARAMS | FIMC_SRC_FMT, ctx);
dbg("f_w: %d, f_h: %d", frame->f_width, frame->f_height);
return 0;
}
static int fimc_m2m_reqbufs(struct file *file, void *fh,
struct v4l2_requestbuffers *reqbufs)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
return v4l2_m2m_reqbufs(file, ctx->m2m_ctx, reqbufs);
}
static int fimc_m2m_querybuf(struct file *file, void *fh,
struct v4l2_buffer *buf)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
return v4l2_m2m_querybuf(file, ctx->m2m_ctx, buf);
}
static int fimc_m2m_qbuf(struct file *file, void *fh,
struct v4l2_buffer *buf)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
return v4l2_m2m_qbuf(file, ctx->m2m_ctx, buf);
}
static int fimc_m2m_dqbuf(struct file *file, void *fh,
struct v4l2_buffer *buf)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
return v4l2_m2m_dqbuf(file, ctx->m2m_ctx, buf);
}
static int fimc_m2m_streamon(struct file *file, void *fh,
enum v4l2_buf_type type)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
/* The source and target color format need to be set */
if (V4L2_TYPE_IS_OUTPUT(type)) {
if (!fimc_ctx_state_is_set(FIMC_SRC_FMT, ctx))
return -EINVAL;
} else if (!fimc_ctx_state_is_set(FIMC_DST_FMT, ctx)) {
return -EINVAL;
}
return v4l2_m2m_streamon(file, ctx->m2m_ctx, type);
}
static int fimc_m2m_streamoff(struct file *file, void *fh,
enum v4l2_buf_type type)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
return v4l2_m2m_streamoff(file, ctx->m2m_ctx, type);
}
static int fimc_m2m_cropcap(struct file *file, void *fh,
struct v4l2_cropcap *cr)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
struct fimc_frame *frame;
frame = ctx_get_frame(ctx, cr->type);
if (IS_ERR(frame))
return PTR_ERR(frame);
cr->bounds.left = 0;
cr->bounds.top = 0;
cr->bounds.width = frame->o_width;
cr->bounds.height = frame->o_height;
cr->defrect = cr->bounds;
return 0;
}
static int fimc_m2m_g_crop(struct file *file, void *fh, struct v4l2_crop *cr)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
struct fimc_frame *frame;
frame = ctx_get_frame(ctx, cr->type);
if (IS_ERR(frame))
return PTR_ERR(frame);
cr->c.left = frame->offs_h;
cr->c.top = frame->offs_v;
cr->c.width = frame->width;
cr->c.height = frame->height;
return 0;
}
static int fimc_m2m_try_crop(struct fimc_ctx *ctx, struct v4l2_crop *cr)
{
struct fimc_dev *fimc = ctx->fimc_dev;
struct fimc_frame *f;
u32 min_size, halign, depth = 0;
int i;
if (cr->c.top < 0 || cr->c.left < 0) {
v4l2_err(fimc->m2m.vfd,
"doesn't support negative values for top & left\n");
return -EINVAL;
}
if (cr->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
f = &ctx->d_frame;
else if (cr->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
f = &ctx->s_frame;
else
return -EINVAL;
min_size = (f == &ctx->s_frame) ?
fimc->variant->min_inp_pixsize : fimc->variant->min_out_pixsize;
/* Get pixel alignment constraints. */
if (fimc->variant->min_vsize_align == 1)
halign = fimc_fmt_is_rgb(f->fmt->color) ? 0 : 1;
else
halign = ffs(fimc->variant->min_vsize_align) - 1;
for (i = 0; i < f->fmt->colplanes; i++)
depth += f->fmt->depth[i];
v4l_bound_align_image(&cr->c.width, min_size, f->o_width,
ffs(min_size) - 1,
&cr->c.height, min_size, f->o_height,
halign, 64/(ALIGN(depth, 8)));
/* adjust left/top if cropping rectangle is out of bounds */
if (cr->c.left + cr->c.width > f->o_width)
cr->c.left = f->o_width - cr->c.width;
if (cr->c.top + cr->c.height > f->o_height)
cr->c.top = f->o_height - cr->c.height;
cr->c.left = round_down(cr->c.left, min_size);
cr->c.top = round_down(cr->c.top, fimc->variant->hor_offs_align);
dbg("l:%d, t:%d, w:%d, h:%d, f_w: %d, f_h: %d",
cr->c.left, cr->c.top, cr->c.width, cr->c.height,
f->f_width, f->f_height);
return 0;
}
static int fimc_m2m_s_crop(struct file *file, void *fh, struct v4l2_crop *cr)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
struct fimc_dev *fimc = ctx->fimc_dev;
struct fimc_frame *f;
int ret;
ret = fimc_m2m_try_crop(ctx, cr);
if (ret)
return ret;
f = (cr->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) ?
&ctx->s_frame : &ctx->d_frame;
/* Check to see if scaling ratio is within supported range */
if (fimc_ctx_state_is_set(FIMC_DST_FMT | FIMC_SRC_FMT, ctx)) {
if (cr->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
ret = fimc_check_scaler_ratio(ctx, cr->c.width,
cr->c.height, ctx->d_frame.width,
ctx->d_frame.height, ctx->rotation);
} else {
ret = fimc_check_scaler_ratio(ctx, ctx->s_frame.width,
ctx->s_frame.height, cr->c.width,
cr->c.height, ctx->rotation);
}
if (ret) {
v4l2_err(fimc->m2m.vfd, "Out of scaler range\n");
return -EINVAL;
}
}
f->offs_h = cr->c.left;
f->offs_v = cr->c.top;
f->width = cr->c.width;
f->height = cr->c.height;
fimc_ctx_state_lock_set(FIMC_PARAMS, ctx);
return 0;
}
static const struct v4l2_ioctl_ops fimc_m2m_ioctl_ops = {
.vidioc_querycap = fimc_m2m_querycap,
.vidioc_enum_fmt_vid_cap_mplane = fimc_m2m_enum_fmt_mplane,
.vidioc_enum_fmt_vid_out_mplane = fimc_m2m_enum_fmt_mplane,
.vidioc_g_fmt_vid_cap_mplane = fimc_m2m_g_fmt_mplane,
.vidioc_g_fmt_vid_out_mplane = fimc_m2m_g_fmt_mplane,
.vidioc_try_fmt_vid_cap_mplane = fimc_m2m_try_fmt_mplane,
.vidioc_try_fmt_vid_out_mplane = fimc_m2m_try_fmt_mplane,
.vidioc_s_fmt_vid_cap_mplane = fimc_m2m_s_fmt_mplane,
.vidioc_s_fmt_vid_out_mplane = fimc_m2m_s_fmt_mplane,
.vidioc_reqbufs = fimc_m2m_reqbufs,
.vidioc_querybuf = fimc_m2m_querybuf,
.vidioc_qbuf = fimc_m2m_qbuf,
.vidioc_dqbuf = fimc_m2m_dqbuf,
.vidioc_streamon = fimc_m2m_streamon,
.vidioc_streamoff = fimc_m2m_streamoff,
.vidioc_g_crop = fimc_m2m_g_crop,
.vidioc_s_crop = fimc_m2m_s_crop,
.vidioc_cropcap = fimc_m2m_cropcap
};
static int queue_init(void *priv, struct vb2_queue *src_vq,
struct vb2_queue *dst_vq)
{
struct fimc_ctx *ctx = priv;
int ret;
memset(src_vq, 0, sizeof(*src_vq));
src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
src_vq->io_modes = VB2_MMAP | VB2_USERPTR;
src_vq->drv_priv = ctx;
src_vq->ops = &fimc_qops;
src_vq->mem_ops = &vb2_dma_contig_memops;
src_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
ret = vb2_queue_init(src_vq);
if (ret)
return ret;
memset(dst_vq, 0, sizeof(*dst_vq));
dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
dst_vq->io_modes = VB2_MMAP | VB2_USERPTR;
dst_vq->drv_priv = ctx;
dst_vq->ops = &fimc_qops;
dst_vq->mem_ops = &vb2_dma_contig_memops;
dst_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
return vb2_queue_init(dst_vq);
}
static int fimc_m2m_open(struct file *file)
{
struct fimc_dev *fimc = video_drvdata(file);
struct fimc_ctx *ctx;
int ret;
dbg("pid: %d, state: 0x%lx, refcnt: %d",
task_pid_nr(current), fimc->state, fimc->vid_cap.refcnt);
/*
* Return if the corresponding video capture node
* is already opened.
*/
if (fimc->vid_cap.refcnt > 0)
return -EBUSY;
ctx = kzalloc(sizeof *ctx, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
v4l2_fh_init(&ctx->fh, fimc->m2m.vfd);
ctx->fimc_dev = fimc;
/* Default color format */
ctx->s_frame.fmt = &fimc_formats[0];
ctx->d_frame.fmt = &fimc_formats[0];
ret = fimc_ctrls_create(ctx);
if (ret)
goto error_fh;
/* Use separate control handler per file handle */
ctx->fh.ctrl_handler = &ctx->ctrl_handler;
file->private_data = &ctx->fh;
v4l2_fh_add(&ctx->fh);
/* Setup the device context for memory-to-memory mode */
ctx->state = FIMC_CTX_M2M;
ctx->flags = 0;
ctx->in_path = FIMC_DMA;
ctx->out_path = FIMC_DMA;
spin_lock_init(&ctx->slock);
ctx->m2m_ctx = v4l2_m2m_ctx_init(fimc->m2m.m2m_dev, ctx, queue_init);
if (IS_ERR(ctx->m2m_ctx)) {
ret = PTR_ERR(ctx->m2m_ctx);
goto error_c;
}
if (fimc->m2m.refcnt++ == 0)
set_bit(ST_M2M_RUN, &fimc->state);
return 0;
error_c:
fimc_ctrls_delete(ctx);
error_fh:
v4l2_fh_del(&ctx->fh);
v4l2_fh_exit(&ctx->fh);
kfree(ctx);
return ret;
}
static int fimc_m2m_release(struct file *file)
{
struct fimc_ctx *ctx = fh_to_ctx(file->private_data);
struct fimc_dev *fimc = ctx->fimc_dev;
dbg("pid: %d, state: 0x%lx, refcnt= %d",
task_pid_nr(current), fimc->state, fimc->m2m.refcnt);
v4l2_m2m_ctx_release(ctx->m2m_ctx);
fimc_ctrls_delete(ctx);
v4l2_fh_del(&ctx->fh);
v4l2_fh_exit(&ctx->fh);
if (--fimc->m2m.refcnt <= 0)
clear_bit(ST_M2M_RUN, &fimc->state);
kfree(ctx);
return 0;
}
static unsigned int fimc_m2m_poll(struct file *file,
struct poll_table_struct *wait)
{
struct fimc_ctx *ctx = fh_to_ctx(file->private_data);
return v4l2_m2m_poll(file, ctx->m2m_ctx, wait);
}
static int fimc_m2m_mmap(struct file *file, struct vm_area_struct *vma)
{
struct fimc_ctx *ctx = fh_to_ctx(file->private_data);
return v4l2_m2m_mmap(file, ctx->m2m_ctx, vma);
}
static const struct v4l2_file_operations fimc_m2m_fops = {
.owner = THIS_MODULE,
.open = fimc_m2m_open,
.release = fimc_m2m_release,
.poll = fimc_m2m_poll,
.unlocked_ioctl = video_ioctl2,
.mmap = fimc_m2m_mmap,
};
static struct v4l2_m2m_ops m2m_ops = {
.device_run = fimc_dma_run,
.job_abort = fimc_job_abort,
};
int fimc_register_m2m_device(struct fimc_dev *fimc,
struct v4l2_device *v4l2_dev)
{
struct video_device *vfd;
struct platform_device *pdev;
int ret = 0;
if (!fimc)
return -ENODEV;
pdev = fimc->pdev;
fimc->v4l2_dev = v4l2_dev;
vfd = video_device_alloc();
if (!vfd) {
v4l2_err(v4l2_dev, "Failed to allocate video device\n");
return -ENOMEM;
}
vfd->fops = &fimc_m2m_fops;
vfd->ioctl_ops = &fimc_m2m_ioctl_ops;
vfd->v4l2_dev = v4l2_dev;
vfd->minor = -1;
vfd->release = video_device_release;
vfd->lock = &fimc->lock;
snprintf(vfd->name, sizeof(vfd->name), "%s.m2m", dev_name(&pdev->dev));
video_set_drvdata(vfd, fimc);
fimc->m2m.vfd = vfd;
fimc->m2m.m2m_dev = v4l2_m2m_init(&m2m_ops);
if (IS_ERR(fimc->m2m.m2m_dev)) {
v4l2_err(v4l2_dev, "failed to initialize v4l2-m2m device\n");
ret = PTR_ERR(fimc->m2m.m2m_dev);
goto err_init;
}
ret = media_entity_init(&vfd->entity, 0, NULL, 0);
if (!ret)
return 0;
v4l2_m2m_release(fimc->m2m.m2m_dev);
err_init:
video_device_release(fimc->m2m.vfd);
return ret;
}
void fimc_unregister_m2m_device(struct fimc_dev *fimc)
{
if (!fimc)
return;
if (fimc->m2m.m2m_dev)
v4l2_m2m_release(fimc->m2m.m2m_dev);
if (fimc->m2m.vfd) {
media_entity_cleanup(&fimc->m2m.vfd->entity);
/* Can also be called if video device wasn't registered */
video_unregister_device(fimc->m2m.vfd);
}
}
static void fimc_clk_put(struct fimc_dev *fimc)
{
int i;
for (i = 0; i < fimc->num_clocks; i++) {
if (IS_ERR_OR_NULL(fimc->clock[i]))
continue;
clk_unprepare(fimc->clock[i]);
clk_put(fimc->clock[i]);
fimc->clock[i] = NULL;
}
}
static int fimc_clk_get(struct fimc_dev *fimc)
{
int i, ret;
for (i = 0; i < fimc->num_clocks; i++) {
fimc->clock[i] = clk_get(&fimc->pdev->dev, fimc_clocks[i]);
if (IS_ERR(fimc->clock[i]))
goto err;
ret = clk_prepare(fimc->clock[i]);
if (ret < 0) {
clk_put(fimc->clock[i]);
fimc->clock[i] = NULL;
goto err;
}
}
return 0;
err:
fimc_clk_put(fimc);
dev_err(&fimc->pdev->dev, "failed to get clock: %s\n",
fimc_clocks[i]);
return -ENXIO;
}
static int fimc_m2m_suspend(struct fimc_dev *fimc)
{
unsigned long flags;
int timeout;
spin_lock_irqsave(&fimc->slock, flags);
if (!fimc_m2m_pending(fimc)) {
spin_unlock_irqrestore(&fimc->slock, flags);
return 0;
}
clear_bit(ST_M2M_SUSPENDED, &fimc->state);
set_bit(ST_M2M_SUSPENDING, &fimc->state);
spin_unlock_irqrestore(&fimc->slock, flags);
timeout = wait_event_timeout(fimc->irq_queue,
test_bit(ST_M2M_SUSPENDED, &fimc->state),
FIMC_SHUTDOWN_TIMEOUT);
clear_bit(ST_M2M_SUSPENDING, &fimc->state);
return timeout == 0 ? -EAGAIN : 0;
}
static int fimc_m2m_resume(struct fimc_dev *fimc)
{
unsigned long flags;
spin_lock_irqsave(&fimc->slock, flags);
/* Clear for full H/W setup in first run after resume */
fimc->m2m.ctx = NULL;
spin_unlock_irqrestore(&fimc->slock, flags);
if (test_and_clear_bit(ST_M2M_SUSPENDED, &fimc->state))
fimc_m2m_job_finish(fimc->m2m.ctx,
VB2_BUF_STATE_ERROR);
return 0;
}
static int fimc_probe(struct platform_device *pdev)
{
struct fimc_dev *fimc;
struct resource *res;
struct samsung_fimc_driverdata *drv_data;
struct s5p_platform_fimc *pdata;
int ret = 0;
drv_data = (struct samsung_fimc_driverdata *)
platform_get_device_id(pdev)->driver_data;
if (pdev->id >= drv_data->num_entities) {
dev_err(&pdev->dev, "Invalid platform device id: %d\n",
pdev->id);
return -EINVAL;
}
fimc = devm_kzalloc(&pdev->dev, sizeof(*fimc), GFP_KERNEL);
if (!fimc)
return -ENOMEM;
fimc->id = pdev->id;
fimc->variant = drv_data->variant[fimc->id];
fimc->pdev = pdev;
pdata = pdev->dev.platform_data;
fimc->pdata = pdata;
init_waitqueue_head(&fimc->irq_queue);
spin_lock_init(&fimc->slock);
mutex_init(&fimc->lock);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
fimc->regs = devm_request_and_ioremap(&pdev->dev, res);
if (fimc->regs == NULL) {
dev_err(&pdev->dev, "Failed to obtain io memory\n");
return -ENOENT;
}
res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (res == NULL) {
dev_err(&pdev->dev, "Failed to get IRQ resource\n");
return -ENXIO;
}
fimc->irq = res->start;
fimc->num_clocks = MAX_FIMC_CLOCKS;
ret = fimc_clk_get(fimc);
if (ret)
return ret;
clk_set_rate(fimc->clock[CLK_BUS], drv_data->lclk_frequency);
clk_enable(fimc->clock[CLK_BUS]);
platform_set_drvdata(pdev, fimc);
ret = devm_request_irq(&pdev->dev, fimc->irq, fimc_irq_handler,
0, pdev->name, fimc);
if (ret) {
dev_err(&pdev->dev, "failed to install irq (%d)\n", ret);
goto err_clk;
}
pm_runtime_enable(&pdev->dev);
ret = pm_runtime_get_sync(&pdev->dev);
if (ret < 0)
goto err_clk;
/* Initialize contiguous memory allocator */
fimc->alloc_ctx = vb2_dma_contig_init_ctx(&pdev->dev);
if (IS_ERR(fimc->alloc_ctx)) {
ret = PTR_ERR(fimc->alloc_ctx);
goto err_pm;
}
dev_dbg(&pdev->dev, "FIMC.%d registered successfully\n", fimc->id);
pm_runtime_put(&pdev->dev);
return 0;
err_pm:
pm_runtime_put(&pdev->dev);
err_clk:
fimc_clk_put(fimc);
return ret;
}
static int fimc_runtime_resume(struct device *dev)
{
struct fimc_dev *fimc = dev_get_drvdata(dev);
dbg("fimc%d: state: 0x%lx", fimc->id, fimc->state);
/* Enable clocks and perform basic initalization */
clk_enable(fimc->clock[CLK_GATE]);
fimc_hw_reset(fimc);
/* Resume the capture or mem-to-mem device */
if (fimc_capture_busy(fimc))
return fimc_capture_resume(fimc);
return fimc_m2m_resume(fimc);
}
static int fimc_runtime_suspend(struct device *dev)
{
struct fimc_dev *fimc = dev_get_drvdata(dev);
int ret = 0;
if (fimc_capture_busy(fimc))
ret = fimc_capture_suspend(fimc);
else
ret = fimc_m2m_suspend(fimc);
if (!ret)
clk_disable(fimc->clock[CLK_GATE]);
dbg("fimc%d: state: 0x%lx", fimc->id, fimc->state);
return ret;
}
#ifdef CONFIG_PM_SLEEP
static int fimc_resume(struct device *dev)
{
struct fimc_dev *fimc = dev_get_drvdata(dev);
unsigned long flags;
dbg("fimc%d: state: 0x%lx", fimc->id, fimc->state);
/* Do not resume if the device was idle before system suspend */
spin_lock_irqsave(&fimc->slock, flags);
if (!test_and_clear_bit(ST_LPM, &fimc->state) ||
(!fimc_m2m_active(fimc) && !fimc_capture_busy(fimc))) {
spin_unlock_irqrestore(&fimc->slock, flags);
return 0;
}
fimc_hw_reset(fimc);
spin_unlock_irqrestore(&fimc->slock, flags);
if (fimc_capture_busy(fimc))
return fimc_capture_resume(fimc);
return fimc_m2m_resume(fimc);
}
static int fimc_suspend(struct device *dev)
{
struct fimc_dev *fimc = dev_get_drvdata(dev);
dbg("fimc%d: state: 0x%lx", fimc->id, fimc->state);
if (test_and_set_bit(ST_LPM, &fimc->state))
return 0;
if (fimc_capture_busy(fimc))
return fimc_capture_suspend(fimc);
return fimc_m2m_suspend(fimc);
}
#endif /* CONFIG_PM_SLEEP */
static int __devexit fimc_remove(struct platform_device *pdev)
{
struct fimc_dev *fimc = platform_get_drvdata(pdev);
pm_runtime_disable(&pdev->dev);
pm_runtime_set_suspended(&pdev->dev);
vb2_dma_contig_cleanup_ctx(fimc->alloc_ctx);
clk_disable(fimc->clock[CLK_BUS]);
fimc_clk_put(fimc);
dev_info(&pdev->dev, "driver unloaded\n");
return 0;
}
/* Image pixel limits, similar across several FIMC HW revisions. */
static struct fimc_pix_limit s5p_pix_limit[4] = {
[0] = {
.scaler_en_w = 3264,
.scaler_dis_w = 8192,
.in_rot_en_h = 1920,
.in_rot_dis_w = 8192,
.out_rot_en_w = 1920,
.out_rot_dis_w = 4224,
},
[1] = {
.scaler_en_w = 4224,
.scaler_dis_w = 8192,
.in_rot_en_h = 1920,
.in_rot_dis_w = 8192,
.out_rot_en_w = 1920,
.out_rot_dis_w = 4224,
},
[2] = {
.scaler_en_w = 1920,
.scaler_dis_w = 8192,
.in_rot_en_h = 1280,
.in_rot_dis_w = 8192,
.out_rot_en_w = 1280,
.out_rot_dis_w = 1920,
},
[3] = {
.scaler_en_w = 1920,
.scaler_dis_w = 8192,
.in_rot_en_h = 1366,
.in_rot_dis_w = 8192,
.out_rot_en_w = 1366,
.out_rot_dis_w = 1920,
},
};
static struct samsung_fimc_variant fimc0_variant_s5p = {
.has_inp_rot = 1,
.has_out_rot = 1,
.has_cam_if = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 8,
.min_vsize_align = 16,
.out_buf_count = 4,
.pix_limit = &s5p_pix_limit[0],
};
static struct samsung_fimc_variant fimc2_variant_s5p = {
.has_cam_if = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 8,
.min_vsize_align = 16,
.out_buf_count = 4,
.pix_limit = &s5p_pix_limit[1],
};
static struct samsung_fimc_variant fimc0_variant_s5pv210 = {
.pix_hoff = 1,
.has_inp_rot = 1,
.has_out_rot = 1,
.has_cam_if = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 8,
.min_vsize_align = 16,
.out_buf_count = 4,
.pix_limit = &s5p_pix_limit[1],
};
static struct samsung_fimc_variant fimc1_variant_s5pv210 = {
.pix_hoff = 1,
.has_inp_rot = 1,
.has_out_rot = 1,
.has_cam_if = 1,
.has_mainscaler_ext = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 1,
.min_vsize_align = 1,
.out_buf_count = 4,
.pix_limit = &s5p_pix_limit[2],
};
static struct samsung_fimc_variant fimc2_variant_s5pv210 = {
.has_cam_if = 1,
.pix_hoff = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 8,
.min_vsize_align = 16,
.out_buf_count = 4,
.pix_limit = &s5p_pix_limit[2],
};
static struct samsung_fimc_variant fimc0_variant_exynos4 = {
.pix_hoff = 1,
.has_inp_rot = 1,
.has_out_rot = 1,
.has_cam_if = 1,
.has_cistatus2 = 1,
.has_mainscaler_ext = 1,
.has_alpha = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 2,
.min_vsize_align = 1,
.out_buf_count = 32,
.pix_limit = &s5p_pix_limit[1],
};
static struct samsung_fimc_variant fimc3_variant_exynos4 = {
.pix_hoff = 1,
.has_cam_if = 1,
.has_cistatus2 = 1,
.has_mainscaler_ext = 1,
.has_alpha = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 2,
.min_vsize_align = 1,
.out_buf_count = 32,
.pix_limit = &s5p_pix_limit[3],
};
/* S5PC100 */
static struct samsung_fimc_driverdata fimc_drvdata_s5p = {
.variant = {
[0] = &fimc0_variant_s5p,
[1] = &fimc0_variant_s5p,
[2] = &fimc2_variant_s5p,
},
.num_entities = 3,
.lclk_frequency = 133000000UL,
};
/* S5PV210, S5PC110 */
static struct samsung_fimc_driverdata fimc_drvdata_s5pv210 = {
.variant = {
[0] = &fimc0_variant_s5pv210,
[1] = &fimc1_variant_s5pv210,
[2] = &fimc2_variant_s5pv210,
},
.num_entities = 3,
.lclk_frequency = 166000000UL,
};
/* S5PV310, S5PC210 */
static struct samsung_fimc_driverdata fimc_drvdata_exynos4 = {
.variant = {
[0] = &fimc0_variant_exynos4,
[1] = &fimc0_variant_exynos4,
[2] = &fimc0_variant_exynos4,
[3] = &fimc3_variant_exynos4,
},
.num_entities = 4,
.lclk_frequency = 166000000UL,
};
static struct platform_device_id fimc_driver_ids[] = {
{
.name = "s5p-fimc",
.driver_data = (unsigned long)&fimc_drvdata_s5p,
}, {
.name = "s5pv210-fimc",
.driver_data = (unsigned long)&fimc_drvdata_s5pv210,
}, {
.name = "exynos4-fimc",
.driver_data = (unsigned long)&fimc_drvdata_exynos4,
},
{},
};
MODULE_DEVICE_TABLE(platform, fimc_driver_ids);
static const struct dev_pm_ops fimc_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(fimc_suspend, fimc_resume)
SET_RUNTIME_PM_OPS(fimc_runtime_suspend, fimc_runtime_resume, NULL)
};
static struct platform_driver fimc_driver = {
.probe = fimc_probe,
.remove = __devexit_p(fimc_remove),
.id_table = fimc_driver_ids,
.driver = {
.name = FIMC_MODULE_NAME,
.owner = THIS_MODULE,
.pm = &fimc_pm_ops,
}
};
int __init fimc_register_driver(void)
{
return platform_driver_probe(&fimc_driver, fimc_probe);
}
void __exit fimc_unregister_driver(void)
{
platform_driver_unregister(&fimc_driver);
}
| gpl-2.0 |
robcore/machinex_kernel | drivers/media/video/s5p-fimc/fimc-core.c | 4646 | 50345 | /*
* Samsung S5P/EXYNOS4 SoC series camera interface (video postprocessor) driver
*
* Copyright (C) 2010-2011 Samsung Electronics Co., Ltd.
* Contact: Sylwester Nawrocki, <s.nawrocki@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License 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/kernel.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/bug.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/list.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <media/v4l2-ioctl.h>
#include <media/videobuf2-core.h>
#include <media/videobuf2-dma-contig.h>
#include "fimc-core.h"
#include "fimc-mdevice.h"
static char *fimc_clocks[MAX_FIMC_CLOCKS] = {
"sclk_fimc", "fimc"
};
static struct fimc_fmt fimc_formats[] = {
{
.name = "RGB565",
.fourcc = V4L2_PIX_FMT_RGB565,
.depth = { 16 },
.color = S5P_FIMC_RGB565,
.memplanes = 1,
.colplanes = 1,
.flags = FMT_FLAGS_M2M,
}, {
.name = "BGR666",
.fourcc = V4L2_PIX_FMT_BGR666,
.depth = { 32 },
.color = S5P_FIMC_RGB666,
.memplanes = 1,
.colplanes = 1,
.flags = FMT_FLAGS_M2M,
}, {
.name = "ARGB8888, 32 bpp",
.fourcc = V4L2_PIX_FMT_RGB32,
.depth = { 32 },
.color = S5P_FIMC_RGB888,
.memplanes = 1,
.colplanes = 1,
.flags = FMT_FLAGS_M2M | FMT_HAS_ALPHA,
}, {
.name = "ARGB1555",
.fourcc = V4L2_PIX_FMT_RGB555,
.depth = { 16 },
.color = S5P_FIMC_RGB555,
.memplanes = 1,
.colplanes = 1,
.flags = FMT_FLAGS_M2M_OUT | FMT_HAS_ALPHA,
}, {
.name = "ARGB4444",
.fourcc = V4L2_PIX_FMT_RGB444,
.depth = { 16 },
.color = S5P_FIMC_RGB444,
.memplanes = 1,
.colplanes = 1,
.flags = FMT_FLAGS_M2M_OUT | FMT_HAS_ALPHA,
}, {
.name = "YUV 4:2:2 packed, YCbYCr",
.fourcc = V4L2_PIX_FMT_YUYV,
.depth = { 16 },
.color = S5P_FIMC_YCBYCR422,
.memplanes = 1,
.colplanes = 1,
.mbus_code = V4L2_MBUS_FMT_YUYV8_2X8,
.flags = FMT_FLAGS_M2M | FMT_FLAGS_CAM,
}, {
.name = "YUV 4:2:2 packed, CbYCrY",
.fourcc = V4L2_PIX_FMT_UYVY,
.depth = { 16 },
.color = S5P_FIMC_CBYCRY422,
.memplanes = 1,
.colplanes = 1,
.mbus_code = V4L2_MBUS_FMT_UYVY8_2X8,
.flags = FMT_FLAGS_M2M | FMT_FLAGS_CAM,
}, {
.name = "YUV 4:2:2 packed, CrYCbY",
.fourcc = V4L2_PIX_FMT_VYUY,
.depth = { 16 },
.color = S5P_FIMC_CRYCBY422,
.memplanes = 1,
.colplanes = 1,
.mbus_code = V4L2_MBUS_FMT_VYUY8_2X8,
.flags = FMT_FLAGS_M2M | FMT_FLAGS_CAM,
}, {
.name = "YUV 4:2:2 packed, YCrYCb",
.fourcc = V4L2_PIX_FMT_YVYU,
.depth = { 16 },
.color = S5P_FIMC_YCRYCB422,
.memplanes = 1,
.colplanes = 1,
.mbus_code = V4L2_MBUS_FMT_YVYU8_2X8,
.flags = FMT_FLAGS_M2M | FMT_FLAGS_CAM,
}, {
.name = "YUV 4:2:2 planar, Y/Cb/Cr",
.fourcc = V4L2_PIX_FMT_YUV422P,
.depth = { 12 },
.color = S5P_FIMC_YCBYCR422,
.memplanes = 1,
.colplanes = 3,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:2 planar, Y/CbCr",
.fourcc = V4L2_PIX_FMT_NV16,
.depth = { 16 },
.color = S5P_FIMC_YCBYCR422,
.memplanes = 1,
.colplanes = 2,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:2 planar, Y/CrCb",
.fourcc = V4L2_PIX_FMT_NV61,
.depth = { 16 },
.color = S5P_FIMC_YCRYCB422,
.memplanes = 1,
.colplanes = 2,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:0 planar, YCbCr",
.fourcc = V4L2_PIX_FMT_YUV420,
.depth = { 12 },
.color = S5P_FIMC_YCBCR420,
.memplanes = 1,
.colplanes = 3,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:0 planar, Y/CbCr",
.fourcc = V4L2_PIX_FMT_NV12,
.depth = { 12 },
.color = S5P_FIMC_YCBCR420,
.memplanes = 1,
.colplanes = 2,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:0 non-contiguous 2-planar, Y/CbCr",
.fourcc = V4L2_PIX_FMT_NV12M,
.color = S5P_FIMC_YCBCR420,
.depth = { 8, 4 },
.memplanes = 2,
.colplanes = 2,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:0 non-contiguous 3-planar, Y/Cb/Cr",
.fourcc = V4L2_PIX_FMT_YUV420M,
.color = S5P_FIMC_YCBCR420,
.depth = { 8, 2, 2 },
.memplanes = 3,
.colplanes = 3,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:0 non-contiguous 2-planar, Y/CbCr, tiled",
.fourcc = V4L2_PIX_FMT_NV12MT,
.color = S5P_FIMC_YCBCR420,
.depth = { 8, 4 },
.memplanes = 2,
.colplanes = 2,
.flags = FMT_FLAGS_M2M,
}, {
.name = "JPEG encoded data",
.fourcc = V4L2_PIX_FMT_JPEG,
.color = S5P_FIMC_JPEG,
.depth = { 8 },
.memplanes = 1,
.colplanes = 1,
.mbus_code = V4L2_MBUS_FMT_JPEG_1X8,
.flags = FMT_FLAGS_CAM,
},
};
static unsigned int get_m2m_fmt_flags(unsigned int stream_type)
{
if (stream_type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
return FMT_FLAGS_M2M_IN;
else
return FMT_FLAGS_M2M_OUT;
}
int fimc_check_scaler_ratio(struct fimc_ctx *ctx, int sw, int sh,
int dw, int dh, int rotation)
{
if (rotation == 90 || rotation == 270)
swap(dw, dh);
if (!ctx->scaler.enabled)
return (sw == dw && sh == dh) ? 0 : -EINVAL;
if ((sw >= SCALER_MAX_HRATIO * dw) || (sh >= SCALER_MAX_VRATIO * dh))
return -EINVAL;
return 0;
}
static int fimc_get_scaler_factor(u32 src, u32 tar, u32 *ratio, u32 *shift)
{
u32 sh = 6;
if (src >= 64 * tar)
return -EINVAL;
while (sh--) {
u32 tmp = 1 << sh;
if (src >= tar * tmp) {
*shift = sh, *ratio = tmp;
return 0;
}
}
*shift = 0, *ratio = 1;
return 0;
}
int fimc_set_scaler_info(struct fimc_ctx *ctx)
{
struct samsung_fimc_variant *variant = ctx->fimc_dev->variant;
struct device *dev = &ctx->fimc_dev->pdev->dev;
struct fimc_scaler *sc = &ctx->scaler;
struct fimc_frame *s_frame = &ctx->s_frame;
struct fimc_frame *d_frame = &ctx->d_frame;
int tx, ty, sx, sy;
int ret;
if (ctx->rotation == 90 || ctx->rotation == 270) {
ty = d_frame->width;
tx = d_frame->height;
} else {
tx = d_frame->width;
ty = d_frame->height;
}
if (tx <= 0 || ty <= 0) {
dev_err(dev, "Invalid target size: %dx%d", tx, ty);
return -EINVAL;
}
sx = s_frame->width;
sy = s_frame->height;
if (sx <= 0 || sy <= 0) {
dev_err(dev, "Invalid source size: %dx%d", sx, sy);
return -EINVAL;
}
sc->real_width = sx;
sc->real_height = sy;
ret = fimc_get_scaler_factor(sx, tx, &sc->pre_hratio, &sc->hfactor);
if (ret)
return ret;
ret = fimc_get_scaler_factor(sy, ty, &sc->pre_vratio, &sc->vfactor);
if (ret)
return ret;
sc->pre_dst_width = sx / sc->pre_hratio;
sc->pre_dst_height = sy / sc->pre_vratio;
if (variant->has_mainscaler_ext) {
sc->main_hratio = (sx << 14) / (tx << sc->hfactor);
sc->main_vratio = (sy << 14) / (ty << sc->vfactor);
} else {
sc->main_hratio = (sx << 8) / (tx << sc->hfactor);
sc->main_vratio = (sy << 8) / (ty << sc->vfactor);
}
sc->scaleup_h = (tx >= sx) ? 1 : 0;
sc->scaleup_v = (ty >= sy) ? 1 : 0;
/* check to see if input and output size/format differ */
if (s_frame->fmt->color == d_frame->fmt->color
&& s_frame->width == d_frame->width
&& s_frame->height == d_frame->height)
sc->copy_mode = 1;
else
sc->copy_mode = 0;
return 0;
}
static void fimc_m2m_job_finish(struct fimc_ctx *ctx, int vb_state)
{
struct vb2_buffer *src_vb, *dst_vb;
if (!ctx || !ctx->m2m_ctx)
return;
src_vb = v4l2_m2m_src_buf_remove(ctx->m2m_ctx);
dst_vb = v4l2_m2m_dst_buf_remove(ctx->m2m_ctx);
if (src_vb && dst_vb) {
v4l2_m2m_buf_done(src_vb, vb_state);
v4l2_m2m_buf_done(dst_vb, vb_state);
v4l2_m2m_job_finish(ctx->fimc_dev->m2m.m2m_dev,
ctx->m2m_ctx);
}
}
/* Complete the transaction which has been scheduled for execution. */
static int fimc_m2m_shutdown(struct fimc_ctx *ctx)
{
struct fimc_dev *fimc = ctx->fimc_dev;
int ret;
if (!fimc_m2m_pending(fimc))
return 0;
fimc_ctx_state_lock_set(FIMC_CTX_SHUT, ctx);
ret = wait_event_timeout(fimc->irq_queue,
!fimc_ctx_state_is_set(FIMC_CTX_SHUT, ctx),
FIMC_SHUTDOWN_TIMEOUT);
return ret == 0 ? -ETIMEDOUT : ret;
}
static int start_streaming(struct vb2_queue *q, unsigned int count)
{
struct fimc_ctx *ctx = q->drv_priv;
int ret;
ret = pm_runtime_get_sync(&ctx->fimc_dev->pdev->dev);
return ret > 0 ? 0 : ret;
}
static int stop_streaming(struct vb2_queue *q)
{
struct fimc_ctx *ctx = q->drv_priv;
int ret;
ret = fimc_m2m_shutdown(ctx);
if (ret == -ETIMEDOUT)
fimc_m2m_job_finish(ctx, VB2_BUF_STATE_ERROR);
pm_runtime_put(&ctx->fimc_dev->pdev->dev);
return 0;
}
void fimc_capture_irq_handler(struct fimc_dev *fimc, bool final)
{
struct fimc_vid_cap *cap = &fimc->vid_cap;
struct fimc_vid_buffer *v_buf;
struct timeval *tv;
struct timespec ts;
if (test_and_clear_bit(ST_CAPT_SHUT, &fimc->state)) {
wake_up(&fimc->irq_queue);
return;
}
if (!list_empty(&cap->active_buf_q) &&
test_bit(ST_CAPT_RUN, &fimc->state) && final) {
ktime_get_real_ts(&ts);
v_buf = fimc_active_queue_pop(cap);
tv = &v_buf->vb.v4l2_buf.timestamp;
tv->tv_sec = ts.tv_sec;
tv->tv_usec = ts.tv_nsec / NSEC_PER_USEC;
v_buf->vb.v4l2_buf.sequence = cap->frame_count++;
vb2_buffer_done(&v_buf->vb, VB2_BUF_STATE_DONE);
}
if (!list_empty(&cap->pending_buf_q)) {
v_buf = fimc_pending_queue_pop(cap);
fimc_hw_set_output_addr(fimc, &v_buf->paddr, cap->buf_index);
v_buf->index = cap->buf_index;
/* Move the buffer to the capture active queue */
fimc_active_queue_add(cap, v_buf);
dbg("next frame: %d, done frame: %d",
fimc_hw_get_frame_index(fimc), v_buf->index);
if (++cap->buf_index >= FIMC_MAX_OUT_BUFS)
cap->buf_index = 0;
}
if (cap->active_buf_cnt == 0) {
if (final)
clear_bit(ST_CAPT_RUN, &fimc->state);
if (++cap->buf_index >= FIMC_MAX_OUT_BUFS)
cap->buf_index = 0;
} else {
set_bit(ST_CAPT_RUN, &fimc->state);
}
fimc_capture_config_update(cap->ctx);
dbg("frame: %d, active_buf_cnt: %d",
fimc_hw_get_frame_index(fimc), cap->active_buf_cnt);
}
static irqreturn_t fimc_irq_handler(int irq, void *priv)
{
struct fimc_dev *fimc = priv;
struct fimc_vid_cap *cap = &fimc->vid_cap;
struct fimc_ctx *ctx;
fimc_hw_clear_irq(fimc);
spin_lock(&fimc->slock);
if (test_and_clear_bit(ST_M2M_PEND, &fimc->state)) {
if (test_and_clear_bit(ST_M2M_SUSPENDING, &fimc->state)) {
set_bit(ST_M2M_SUSPENDED, &fimc->state);
wake_up(&fimc->irq_queue);
goto out;
}
ctx = v4l2_m2m_get_curr_priv(fimc->m2m.m2m_dev);
if (ctx != NULL) {
spin_unlock(&fimc->slock);
fimc_m2m_job_finish(ctx, VB2_BUF_STATE_DONE);
spin_lock(&ctx->slock);
if (ctx->state & FIMC_CTX_SHUT) {
ctx->state &= ~FIMC_CTX_SHUT;
wake_up(&fimc->irq_queue);
}
spin_unlock(&ctx->slock);
}
return IRQ_HANDLED;
} else if (test_bit(ST_CAPT_PEND, &fimc->state)) {
fimc_capture_irq_handler(fimc,
!test_bit(ST_CAPT_JPEG, &fimc->state));
if (cap->active_buf_cnt == 1) {
fimc_deactivate_capture(fimc);
clear_bit(ST_CAPT_STREAM, &fimc->state);
}
}
out:
spin_unlock(&fimc->slock);
return IRQ_HANDLED;
}
/* The color format (colplanes, memplanes) must be already configured. */
int fimc_prepare_addr(struct fimc_ctx *ctx, struct vb2_buffer *vb,
struct fimc_frame *frame, struct fimc_addr *paddr)
{
int ret = 0;
u32 pix_size;
if (vb == NULL || frame == NULL)
return -EINVAL;
pix_size = frame->width * frame->height;
dbg("memplanes= %d, colplanes= %d, pix_size= %d",
frame->fmt->memplanes, frame->fmt->colplanes, pix_size);
paddr->y = vb2_dma_contig_plane_dma_addr(vb, 0);
if (frame->fmt->memplanes == 1) {
switch (frame->fmt->colplanes) {
case 1:
paddr->cb = 0;
paddr->cr = 0;
break;
case 2:
/* decompose Y into Y/Cb */
paddr->cb = (u32)(paddr->y + pix_size);
paddr->cr = 0;
break;
case 3:
paddr->cb = (u32)(paddr->y + pix_size);
/* decompose Y into Y/Cb/Cr */
if (S5P_FIMC_YCBCR420 == frame->fmt->color)
paddr->cr = (u32)(paddr->cb
+ (pix_size >> 2));
else /* 422 */
paddr->cr = (u32)(paddr->cb
+ (pix_size >> 1));
break;
default:
return -EINVAL;
}
} else {
if (frame->fmt->memplanes >= 2)
paddr->cb = vb2_dma_contig_plane_dma_addr(vb, 1);
if (frame->fmt->memplanes == 3)
paddr->cr = vb2_dma_contig_plane_dma_addr(vb, 2);
}
dbg("PHYS_ADDR: y= 0x%X cb= 0x%X cr= 0x%X ret= %d",
paddr->y, paddr->cb, paddr->cr, ret);
return ret;
}
/* Set order for 1 and 2 plane YCBCR 4:2:2 formats. */
void fimc_set_yuv_order(struct fimc_ctx *ctx)
{
/* The one only mode supported in SoC. */
ctx->in_order_2p = S5P_FIMC_LSB_CRCB;
ctx->out_order_2p = S5P_FIMC_LSB_CRCB;
/* Set order for 1 plane input formats. */
switch (ctx->s_frame.fmt->color) {
case S5P_FIMC_YCRYCB422:
ctx->in_order_1p = S5P_MSCTRL_ORDER422_CBYCRY;
break;
case S5P_FIMC_CBYCRY422:
ctx->in_order_1p = S5P_MSCTRL_ORDER422_YCRYCB;
break;
case S5P_FIMC_CRYCBY422:
ctx->in_order_1p = S5P_MSCTRL_ORDER422_YCBYCR;
break;
case S5P_FIMC_YCBYCR422:
default:
ctx->in_order_1p = S5P_MSCTRL_ORDER422_CRYCBY;
break;
}
dbg("ctx->in_order_1p= %d", ctx->in_order_1p);
switch (ctx->d_frame.fmt->color) {
case S5P_FIMC_YCRYCB422:
ctx->out_order_1p = S5P_CIOCTRL_ORDER422_CBYCRY;
break;
case S5P_FIMC_CBYCRY422:
ctx->out_order_1p = S5P_CIOCTRL_ORDER422_YCRYCB;
break;
case S5P_FIMC_CRYCBY422:
ctx->out_order_1p = S5P_CIOCTRL_ORDER422_YCBYCR;
break;
case S5P_FIMC_YCBYCR422:
default:
ctx->out_order_1p = S5P_CIOCTRL_ORDER422_CRYCBY;
break;
}
dbg("ctx->out_order_1p= %d", ctx->out_order_1p);
}
void fimc_prepare_dma_offset(struct fimc_ctx *ctx, struct fimc_frame *f)
{
struct samsung_fimc_variant *variant = ctx->fimc_dev->variant;
u32 i, depth = 0;
for (i = 0; i < f->fmt->colplanes; i++)
depth += f->fmt->depth[i];
f->dma_offset.y_h = f->offs_h;
if (!variant->pix_hoff)
f->dma_offset.y_h *= (depth >> 3);
f->dma_offset.y_v = f->offs_v;
f->dma_offset.cb_h = f->offs_h;
f->dma_offset.cb_v = f->offs_v;
f->dma_offset.cr_h = f->offs_h;
f->dma_offset.cr_v = f->offs_v;
if (!variant->pix_hoff) {
if (f->fmt->colplanes == 3) {
f->dma_offset.cb_h >>= 1;
f->dma_offset.cr_h >>= 1;
}
if (f->fmt->color == S5P_FIMC_YCBCR420) {
f->dma_offset.cb_v >>= 1;
f->dma_offset.cr_v >>= 1;
}
}
dbg("in_offset: color= %d, y_h= %d, y_v= %d",
f->fmt->color, f->dma_offset.y_h, f->dma_offset.y_v);
}
/**
* fimc_prepare_config - check dimensions, operation and color mode
* and pre-calculate offset and the scaling coefficients.
*
* @ctx: hardware context information
* @flags: flags indicating which parameters to check/update
*
* Return: 0 if dimensions are valid or non zero otherwise.
*/
int fimc_prepare_config(struct fimc_ctx *ctx, u32 flags)
{
struct fimc_frame *s_frame, *d_frame;
struct vb2_buffer *vb = NULL;
int ret = 0;
s_frame = &ctx->s_frame;
d_frame = &ctx->d_frame;
if (flags & FIMC_PARAMS) {
/* Prepare the DMA offset ratios for scaler. */
fimc_prepare_dma_offset(ctx, &ctx->s_frame);
fimc_prepare_dma_offset(ctx, &ctx->d_frame);
if (s_frame->height > (SCALER_MAX_VRATIO * d_frame->height) ||
s_frame->width > (SCALER_MAX_HRATIO * d_frame->width)) {
err("out of scaler range");
return -EINVAL;
}
fimc_set_yuv_order(ctx);
}
if (flags & FIMC_SRC_ADDR) {
vb = v4l2_m2m_next_src_buf(ctx->m2m_ctx);
ret = fimc_prepare_addr(ctx, vb, s_frame, &s_frame->paddr);
if (ret)
return ret;
}
if (flags & FIMC_DST_ADDR) {
vb = v4l2_m2m_next_dst_buf(ctx->m2m_ctx);
ret = fimc_prepare_addr(ctx, vb, d_frame, &d_frame->paddr);
}
return ret;
}
static void fimc_dma_run(void *priv)
{
struct fimc_ctx *ctx = priv;
struct fimc_dev *fimc;
unsigned long flags;
u32 ret;
if (WARN(!ctx, "null hardware context\n"))
return;
fimc = ctx->fimc_dev;
spin_lock_irqsave(&fimc->slock, flags);
set_bit(ST_M2M_PEND, &fimc->state);
spin_lock(&ctx->slock);
ctx->state |= (FIMC_SRC_ADDR | FIMC_DST_ADDR);
ret = fimc_prepare_config(ctx, ctx->state);
if (ret)
goto dma_unlock;
/* Reconfigure hardware if the context has changed. */
if (fimc->m2m.ctx != ctx) {
ctx->state |= FIMC_PARAMS;
fimc->m2m.ctx = ctx;
}
fimc_hw_set_input_addr(fimc, &ctx->s_frame.paddr);
if (ctx->state & FIMC_PARAMS) {
fimc_hw_set_input_path(ctx);
fimc_hw_set_in_dma(ctx);
ret = fimc_set_scaler_info(ctx);
if (ret) {
spin_unlock(&fimc->slock);
goto dma_unlock;
}
fimc_hw_set_prescaler(ctx);
fimc_hw_set_mainscaler(ctx);
fimc_hw_set_target_format(ctx);
fimc_hw_set_rotation(ctx);
fimc_hw_set_effect(ctx, false);
}
fimc_hw_set_output_path(ctx);
if (ctx->state & (FIMC_DST_ADDR | FIMC_PARAMS))
fimc_hw_set_output_addr(fimc, &ctx->d_frame.paddr, -1);
if (ctx->state & FIMC_PARAMS) {
fimc_hw_set_out_dma(ctx);
if (fimc->variant->has_alpha)
fimc_hw_set_rgb_alpha(ctx);
}
fimc_activate_capture(ctx);
ctx->state &= (FIMC_CTX_M2M | FIMC_CTX_CAP |
FIMC_SRC_FMT | FIMC_DST_FMT);
fimc_hw_activate_input_dma(fimc, true);
dma_unlock:
spin_unlock(&ctx->slock);
spin_unlock_irqrestore(&fimc->slock, flags);
}
static void fimc_job_abort(void *priv)
{
fimc_m2m_shutdown(priv);
}
static int fimc_queue_setup(struct vb2_queue *vq, const struct v4l2_format *fmt,
unsigned int *num_buffers, unsigned int *num_planes,
unsigned int sizes[], void *allocators[])
{
struct fimc_ctx *ctx = vb2_get_drv_priv(vq);
struct fimc_frame *f;
int i;
f = ctx_get_frame(ctx, vq->type);
if (IS_ERR(f))
return PTR_ERR(f);
/*
* Return number of non-contigous planes (plane buffers)
* depending on the configured color format.
*/
if (!f->fmt)
return -EINVAL;
*num_planes = f->fmt->memplanes;
for (i = 0; i < f->fmt->memplanes; i++) {
sizes[i] = (f->f_width * f->f_height * f->fmt->depth[i]) / 8;
allocators[i] = ctx->fimc_dev->alloc_ctx;
}
return 0;
}
static int fimc_buf_prepare(struct vb2_buffer *vb)
{
struct fimc_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
struct fimc_frame *frame;
int i;
frame = ctx_get_frame(ctx, vb->vb2_queue->type);
if (IS_ERR(frame))
return PTR_ERR(frame);
for (i = 0; i < frame->fmt->memplanes; i++)
vb2_set_plane_payload(vb, i, frame->payload[i]);
return 0;
}
static void fimc_buf_queue(struct vb2_buffer *vb)
{
struct fimc_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
dbg("ctx: %p, ctx->state: 0x%x", ctx, ctx->state);
if (ctx->m2m_ctx)
v4l2_m2m_buf_queue(ctx->m2m_ctx, vb);
}
static void fimc_lock(struct vb2_queue *vq)
{
struct fimc_ctx *ctx = vb2_get_drv_priv(vq);
mutex_lock(&ctx->fimc_dev->lock);
}
static void fimc_unlock(struct vb2_queue *vq)
{
struct fimc_ctx *ctx = vb2_get_drv_priv(vq);
mutex_unlock(&ctx->fimc_dev->lock);
}
static struct vb2_ops fimc_qops = {
.queue_setup = fimc_queue_setup,
.buf_prepare = fimc_buf_prepare,
.buf_queue = fimc_buf_queue,
.wait_prepare = fimc_unlock,
.wait_finish = fimc_lock,
.stop_streaming = stop_streaming,
.start_streaming = start_streaming,
};
/*
* V4L2 controls handling
*/
#define ctrl_to_ctx(__ctrl) \
container_of((__ctrl)->handler, struct fimc_ctx, ctrl_handler)
static int __fimc_s_ctrl(struct fimc_ctx *ctx, struct v4l2_ctrl *ctrl)
{
struct fimc_dev *fimc = ctx->fimc_dev;
struct samsung_fimc_variant *variant = fimc->variant;
unsigned int flags = FIMC_DST_FMT | FIMC_SRC_FMT;
int ret = 0;
if (ctrl->flags & V4L2_CTRL_FLAG_INACTIVE)
return 0;
switch (ctrl->id) {
case V4L2_CID_HFLIP:
ctx->hflip = ctrl->val;
break;
case V4L2_CID_VFLIP:
ctx->vflip = ctrl->val;
break;
case V4L2_CID_ROTATE:
if (fimc_capture_pending(fimc) ||
(ctx->state & flags) == flags) {
ret = fimc_check_scaler_ratio(ctx, ctx->s_frame.width,
ctx->s_frame.height, ctx->d_frame.width,
ctx->d_frame.height, ctrl->val);
if (ret)
return -EINVAL;
}
if ((ctrl->val == 90 || ctrl->val == 270) &&
!variant->has_out_rot)
return -EINVAL;
ctx->rotation = ctrl->val;
break;
case V4L2_CID_ALPHA_COMPONENT:
ctx->d_frame.alpha = ctrl->val;
break;
}
ctx->state |= FIMC_PARAMS;
set_bit(ST_CAPT_APPLY_CFG, &fimc->state);
return 0;
}
static int fimc_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct fimc_ctx *ctx = ctrl_to_ctx(ctrl);
unsigned long flags;
int ret;
spin_lock_irqsave(&ctx->slock, flags);
ret = __fimc_s_ctrl(ctx, ctrl);
spin_unlock_irqrestore(&ctx->slock, flags);
return ret;
}
static const struct v4l2_ctrl_ops fimc_ctrl_ops = {
.s_ctrl = fimc_s_ctrl,
};
int fimc_ctrls_create(struct fimc_ctx *ctx)
{
struct samsung_fimc_variant *variant = ctx->fimc_dev->variant;
unsigned int max_alpha = fimc_get_alpha_mask(ctx->d_frame.fmt);
if (ctx->ctrls_rdy)
return 0;
v4l2_ctrl_handler_init(&ctx->ctrl_handler, 4);
ctx->ctrl_rotate = v4l2_ctrl_new_std(&ctx->ctrl_handler, &fimc_ctrl_ops,
V4L2_CID_ROTATE, 0, 270, 90, 0);
ctx->ctrl_hflip = v4l2_ctrl_new_std(&ctx->ctrl_handler, &fimc_ctrl_ops,
V4L2_CID_HFLIP, 0, 1, 1, 0);
ctx->ctrl_vflip = v4l2_ctrl_new_std(&ctx->ctrl_handler, &fimc_ctrl_ops,
V4L2_CID_VFLIP, 0, 1, 1, 0);
if (variant->has_alpha)
ctx->ctrl_alpha = v4l2_ctrl_new_std(&ctx->ctrl_handler,
&fimc_ctrl_ops, V4L2_CID_ALPHA_COMPONENT,
0, max_alpha, 1, 0);
else
ctx->ctrl_alpha = NULL;
ctx->ctrls_rdy = ctx->ctrl_handler.error == 0;
return ctx->ctrl_handler.error;
}
void fimc_ctrls_delete(struct fimc_ctx *ctx)
{
if (ctx->ctrls_rdy) {
v4l2_ctrl_handler_free(&ctx->ctrl_handler);
ctx->ctrls_rdy = false;
ctx->ctrl_alpha = NULL;
}
}
void fimc_ctrls_activate(struct fimc_ctx *ctx, bool active)
{
unsigned int has_alpha = ctx->d_frame.fmt->flags & FMT_HAS_ALPHA;
if (!ctx->ctrls_rdy)
return;
mutex_lock(&ctx->ctrl_handler.lock);
v4l2_ctrl_activate(ctx->ctrl_rotate, active);
v4l2_ctrl_activate(ctx->ctrl_hflip, active);
v4l2_ctrl_activate(ctx->ctrl_vflip, active);
if (ctx->ctrl_alpha)
v4l2_ctrl_activate(ctx->ctrl_alpha, active && has_alpha);
if (active) {
ctx->rotation = ctx->ctrl_rotate->val;
ctx->hflip = ctx->ctrl_hflip->val;
ctx->vflip = ctx->ctrl_vflip->val;
} else {
ctx->rotation = 0;
ctx->hflip = 0;
ctx->vflip = 0;
}
mutex_unlock(&ctx->ctrl_handler.lock);
}
/* Update maximum value of the alpha color control */
void fimc_alpha_ctrl_update(struct fimc_ctx *ctx)
{
struct fimc_dev *fimc = ctx->fimc_dev;
struct v4l2_ctrl *ctrl = ctx->ctrl_alpha;
if (ctrl == NULL || !fimc->variant->has_alpha)
return;
v4l2_ctrl_lock(ctrl);
ctrl->maximum = fimc_get_alpha_mask(ctx->d_frame.fmt);
if (ctrl->cur.val > ctrl->maximum)
ctrl->cur.val = ctrl->maximum;
v4l2_ctrl_unlock(ctrl);
}
/*
* V4L2 ioctl handlers
*/
static int fimc_m2m_querycap(struct file *file, void *fh,
struct v4l2_capability *cap)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
struct fimc_dev *fimc = ctx->fimc_dev;
strncpy(cap->driver, fimc->pdev->name, sizeof(cap->driver) - 1);
strncpy(cap->card, fimc->pdev->name, sizeof(cap->card) - 1);
cap->bus_info[0] = 0;
cap->capabilities = V4L2_CAP_STREAMING |
V4L2_CAP_VIDEO_CAPTURE_MPLANE | V4L2_CAP_VIDEO_OUTPUT_MPLANE;
return 0;
}
static int fimc_m2m_enum_fmt_mplane(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
struct fimc_fmt *fmt;
fmt = fimc_find_format(NULL, NULL, get_m2m_fmt_flags(f->type),
f->index);
if (!fmt)
return -EINVAL;
strncpy(f->description, fmt->name, sizeof(f->description) - 1);
f->pixelformat = fmt->fourcc;
return 0;
}
int fimc_fill_format(struct fimc_frame *frame, struct v4l2_format *f)
{
struct v4l2_pix_format_mplane *pixm = &f->fmt.pix_mp;
int i;
pixm->width = frame->o_width;
pixm->height = frame->o_height;
pixm->field = V4L2_FIELD_NONE;
pixm->pixelformat = frame->fmt->fourcc;
pixm->colorspace = V4L2_COLORSPACE_JPEG;
pixm->num_planes = frame->fmt->memplanes;
for (i = 0; i < pixm->num_planes; ++i) {
int bpl = frame->f_width;
if (frame->fmt->colplanes == 1) /* packed formats */
bpl = (bpl * frame->fmt->depth[0]) / 8;
pixm->plane_fmt[i].bytesperline = bpl;
pixm->plane_fmt[i].sizeimage = (frame->o_width *
frame->o_height * frame->fmt->depth[i]) / 8;
}
return 0;
}
void fimc_fill_frame(struct fimc_frame *frame, struct v4l2_format *f)
{
struct v4l2_pix_format_mplane *pixm = &f->fmt.pix_mp;
frame->f_width = pixm->plane_fmt[0].bytesperline;
if (frame->fmt->colplanes == 1)
frame->f_width = (frame->f_width * 8) / frame->fmt->depth[0];
frame->f_height = pixm->height;
frame->width = pixm->width;
frame->height = pixm->height;
frame->o_width = pixm->width;
frame->o_height = pixm->height;
frame->offs_h = 0;
frame->offs_v = 0;
}
/**
* fimc_adjust_mplane_format - adjust bytesperline/sizeimage for each plane
* @fmt: fimc pixel format description (input)
* @width: requested pixel width
* @height: requested pixel height
* @pix: multi-plane format to adjust
*/
void fimc_adjust_mplane_format(struct fimc_fmt *fmt, u32 width, u32 height,
struct v4l2_pix_format_mplane *pix)
{
u32 bytesperline = 0;
int i;
pix->colorspace = V4L2_COLORSPACE_JPEG;
pix->field = V4L2_FIELD_NONE;
pix->num_planes = fmt->memplanes;
pix->pixelformat = fmt->fourcc;
pix->height = height;
pix->width = width;
for (i = 0; i < pix->num_planes; ++i) {
u32 bpl = pix->plane_fmt[i].bytesperline;
u32 *sizeimage = &pix->plane_fmt[i].sizeimage;
if (fmt->colplanes > 1 && (bpl == 0 || bpl < pix->width))
bpl = pix->width; /* Planar */
if (fmt->colplanes == 1 && /* Packed */
(bpl == 0 || ((bpl * 8) / fmt->depth[i]) < pix->width))
bpl = (pix->width * fmt->depth[0]) / 8;
if (i == 0) /* Same bytesperline for each plane. */
bytesperline = bpl;
pix->plane_fmt[i].bytesperline = bytesperline;
*sizeimage = (pix->width * pix->height * fmt->depth[i]) / 8;
}
}
static int fimc_m2m_g_fmt_mplane(struct file *file, void *fh,
struct v4l2_format *f)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
struct fimc_frame *frame = ctx_get_frame(ctx, f->type);
if (IS_ERR(frame))
return PTR_ERR(frame);
return fimc_fill_format(frame, f);
}
/**
* fimc_find_format - lookup fimc color format by fourcc or media bus format
* @pixelformat: fourcc to match, ignored if null
* @mbus_code: media bus code to match, ignored if null
* @mask: the color flags to match
* @index: offset in the fimc_formats array, ignored if negative
*/
struct fimc_fmt *fimc_find_format(const u32 *pixelformat, const u32 *mbus_code,
unsigned int mask, int index)
{
struct fimc_fmt *fmt, *def_fmt = NULL;
unsigned int i;
int id = 0;
if (index >= (int)ARRAY_SIZE(fimc_formats))
return NULL;
for (i = 0; i < ARRAY_SIZE(fimc_formats); ++i) {
fmt = &fimc_formats[i];
if (!(fmt->flags & mask))
continue;
if (pixelformat && fmt->fourcc == *pixelformat)
return fmt;
if (mbus_code && fmt->mbus_code == *mbus_code)
return fmt;
if (index == id)
def_fmt = fmt;
id++;
}
return def_fmt;
}
static int fimc_try_fmt_mplane(struct fimc_ctx *ctx, struct v4l2_format *f)
{
struct fimc_dev *fimc = ctx->fimc_dev;
struct samsung_fimc_variant *variant = fimc->variant;
struct v4l2_pix_format_mplane *pix = &f->fmt.pix_mp;
struct fimc_fmt *fmt;
u32 max_w, mod_x, mod_y;
if (!IS_M2M(f->type))
return -EINVAL;
dbg("w: %d, h: %d", pix->width, pix->height);
fmt = fimc_find_format(&pix->pixelformat, NULL,
get_m2m_fmt_flags(f->type), 0);
if (WARN(fmt == NULL, "Pixel format lookup failed"))
return -EINVAL;
if (pix->field == V4L2_FIELD_ANY)
pix->field = V4L2_FIELD_NONE;
else if (pix->field != V4L2_FIELD_NONE)
return -EINVAL;
if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
max_w = variant->pix_limit->scaler_dis_w;
mod_x = ffs(variant->min_inp_pixsize) - 1;
} else {
max_w = variant->pix_limit->out_rot_dis_w;
mod_x = ffs(variant->min_out_pixsize) - 1;
}
if (tiled_fmt(fmt)) {
mod_x = 6; /* 64 x 32 pixels tile */
mod_y = 5;
} else {
if (variant->min_vsize_align == 1)
mod_y = fimc_fmt_is_rgb(fmt->color) ? 0 : 1;
else
mod_y = ffs(variant->min_vsize_align) - 1;
}
v4l_bound_align_image(&pix->width, 16, max_w, mod_x,
&pix->height, 8, variant->pix_limit->scaler_dis_w, mod_y, 0);
fimc_adjust_mplane_format(fmt, pix->width, pix->height, &f->fmt.pix_mp);
return 0;
}
static int fimc_m2m_try_fmt_mplane(struct file *file, void *fh,
struct v4l2_format *f)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
return fimc_try_fmt_mplane(ctx, f);
}
static int fimc_m2m_s_fmt_mplane(struct file *file, void *fh,
struct v4l2_format *f)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
struct fimc_dev *fimc = ctx->fimc_dev;
struct vb2_queue *vq;
struct fimc_frame *frame;
struct v4l2_pix_format_mplane *pix;
int i, ret = 0;
ret = fimc_try_fmt_mplane(ctx, f);
if (ret)
return ret;
vq = v4l2_m2m_get_vq(ctx->m2m_ctx, f->type);
if (vb2_is_busy(vq)) {
v4l2_err(fimc->m2m.vfd, "queue (%d) busy\n", f->type);
return -EBUSY;
}
if (f->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
frame = &ctx->s_frame;
else
frame = &ctx->d_frame;
pix = &f->fmt.pix_mp;
frame->fmt = fimc_find_format(&pix->pixelformat, NULL,
get_m2m_fmt_flags(f->type), 0);
if (!frame->fmt)
return -EINVAL;
/* Update RGB Alpha control state and value range */
fimc_alpha_ctrl_update(ctx);
for (i = 0; i < frame->fmt->colplanes; i++) {
frame->payload[i] =
(pix->width * pix->height * frame->fmt->depth[i]) / 8;
}
fimc_fill_frame(frame, f);
ctx->scaler.enabled = 1;
if (f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
fimc_ctx_state_lock_set(FIMC_PARAMS | FIMC_DST_FMT, ctx);
else
fimc_ctx_state_lock_set(FIMC_PARAMS | FIMC_SRC_FMT, ctx);
dbg("f_w: %d, f_h: %d", frame->f_width, frame->f_height);
return 0;
}
static int fimc_m2m_reqbufs(struct file *file, void *fh,
struct v4l2_requestbuffers *reqbufs)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
return v4l2_m2m_reqbufs(file, ctx->m2m_ctx, reqbufs);
}
static int fimc_m2m_querybuf(struct file *file, void *fh,
struct v4l2_buffer *buf)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
return v4l2_m2m_querybuf(file, ctx->m2m_ctx, buf);
}
static int fimc_m2m_qbuf(struct file *file, void *fh,
struct v4l2_buffer *buf)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
return v4l2_m2m_qbuf(file, ctx->m2m_ctx, buf);
}
static int fimc_m2m_dqbuf(struct file *file, void *fh,
struct v4l2_buffer *buf)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
return v4l2_m2m_dqbuf(file, ctx->m2m_ctx, buf);
}
static int fimc_m2m_streamon(struct file *file, void *fh,
enum v4l2_buf_type type)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
/* The source and target color format need to be set */
if (V4L2_TYPE_IS_OUTPUT(type)) {
if (!fimc_ctx_state_is_set(FIMC_SRC_FMT, ctx))
return -EINVAL;
} else if (!fimc_ctx_state_is_set(FIMC_DST_FMT, ctx)) {
return -EINVAL;
}
return v4l2_m2m_streamon(file, ctx->m2m_ctx, type);
}
static int fimc_m2m_streamoff(struct file *file, void *fh,
enum v4l2_buf_type type)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
return v4l2_m2m_streamoff(file, ctx->m2m_ctx, type);
}
static int fimc_m2m_cropcap(struct file *file, void *fh,
struct v4l2_cropcap *cr)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
struct fimc_frame *frame;
frame = ctx_get_frame(ctx, cr->type);
if (IS_ERR(frame))
return PTR_ERR(frame);
cr->bounds.left = 0;
cr->bounds.top = 0;
cr->bounds.width = frame->o_width;
cr->bounds.height = frame->o_height;
cr->defrect = cr->bounds;
return 0;
}
static int fimc_m2m_g_crop(struct file *file, void *fh, struct v4l2_crop *cr)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
struct fimc_frame *frame;
frame = ctx_get_frame(ctx, cr->type);
if (IS_ERR(frame))
return PTR_ERR(frame);
cr->c.left = frame->offs_h;
cr->c.top = frame->offs_v;
cr->c.width = frame->width;
cr->c.height = frame->height;
return 0;
}
static int fimc_m2m_try_crop(struct fimc_ctx *ctx, struct v4l2_crop *cr)
{
struct fimc_dev *fimc = ctx->fimc_dev;
struct fimc_frame *f;
u32 min_size, halign, depth = 0;
int i;
if (cr->c.top < 0 || cr->c.left < 0) {
v4l2_err(fimc->m2m.vfd,
"doesn't support negative values for top & left\n");
return -EINVAL;
}
if (cr->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
f = &ctx->d_frame;
else if (cr->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)
f = &ctx->s_frame;
else
return -EINVAL;
min_size = (f == &ctx->s_frame) ?
fimc->variant->min_inp_pixsize : fimc->variant->min_out_pixsize;
/* Get pixel alignment constraints. */
if (fimc->variant->min_vsize_align == 1)
halign = fimc_fmt_is_rgb(f->fmt->color) ? 0 : 1;
else
halign = ffs(fimc->variant->min_vsize_align) - 1;
for (i = 0; i < f->fmt->colplanes; i++)
depth += f->fmt->depth[i];
v4l_bound_align_image(&cr->c.width, min_size, f->o_width,
ffs(min_size) - 1,
&cr->c.height, min_size, f->o_height,
halign, 64/(ALIGN(depth, 8)));
/* adjust left/top if cropping rectangle is out of bounds */
if (cr->c.left + cr->c.width > f->o_width)
cr->c.left = f->o_width - cr->c.width;
if (cr->c.top + cr->c.height > f->o_height)
cr->c.top = f->o_height - cr->c.height;
cr->c.left = round_down(cr->c.left, min_size);
cr->c.top = round_down(cr->c.top, fimc->variant->hor_offs_align);
dbg("l:%d, t:%d, w:%d, h:%d, f_w: %d, f_h: %d",
cr->c.left, cr->c.top, cr->c.width, cr->c.height,
f->f_width, f->f_height);
return 0;
}
static int fimc_m2m_s_crop(struct file *file, void *fh, struct v4l2_crop *cr)
{
struct fimc_ctx *ctx = fh_to_ctx(fh);
struct fimc_dev *fimc = ctx->fimc_dev;
struct fimc_frame *f;
int ret;
ret = fimc_m2m_try_crop(ctx, cr);
if (ret)
return ret;
f = (cr->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) ?
&ctx->s_frame : &ctx->d_frame;
/* Check to see if scaling ratio is within supported range */
if (fimc_ctx_state_is_set(FIMC_DST_FMT | FIMC_SRC_FMT, ctx)) {
if (cr->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
ret = fimc_check_scaler_ratio(ctx, cr->c.width,
cr->c.height, ctx->d_frame.width,
ctx->d_frame.height, ctx->rotation);
} else {
ret = fimc_check_scaler_ratio(ctx, ctx->s_frame.width,
ctx->s_frame.height, cr->c.width,
cr->c.height, ctx->rotation);
}
if (ret) {
v4l2_err(fimc->m2m.vfd, "Out of scaler range\n");
return -EINVAL;
}
}
f->offs_h = cr->c.left;
f->offs_v = cr->c.top;
f->width = cr->c.width;
f->height = cr->c.height;
fimc_ctx_state_lock_set(FIMC_PARAMS, ctx);
return 0;
}
static const struct v4l2_ioctl_ops fimc_m2m_ioctl_ops = {
.vidioc_querycap = fimc_m2m_querycap,
.vidioc_enum_fmt_vid_cap_mplane = fimc_m2m_enum_fmt_mplane,
.vidioc_enum_fmt_vid_out_mplane = fimc_m2m_enum_fmt_mplane,
.vidioc_g_fmt_vid_cap_mplane = fimc_m2m_g_fmt_mplane,
.vidioc_g_fmt_vid_out_mplane = fimc_m2m_g_fmt_mplane,
.vidioc_try_fmt_vid_cap_mplane = fimc_m2m_try_fmt_mplane,
.vidioc_try_fmt_vid_out_mplane = fimc_m2m_try_fmt_mplane,
.vidioc_s_fmt_vid_cap_mplane = fimc_m2m_s_fmt_mplane,
.vidioc_s_fmt_vid_out_mplane = fimc_m2m_s_fmt_mplane,
.vidioc_reqbufs = fimc_m2m_reqbufs,
.vidioc_querybuf = fimc_m2m_querybuf,
.vidioc_qbuf = fimc_m2m_qbuf,
.vidioc_dqbuf = fimc_m2m_dqbuf,
.vidioc_streamon = fimc_m2m_streamon,
.vidioc_streamoff = fimc_m2m_streamoff,
.vidioc_g_crop = fimc_m2m_g_crop,
.vidioc_s_crop = fimc_m2m_s_crop,
.vidioc_cropcap = fimc_m2m_cropcap
};
static int queue_init(void *priv, struct vb2_queue *src_vq,
struct vb2_queue *dst_vq)
{
struct fimc_ctx *ctx = priv;
int ret;
memset(src_vq, 0, sizeof(*src_vq));
src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
src_vq->io_modes = VB2_MMAP | VB2_USERPTR;
src_vq->drv_priv = ctx;
src_vq->ops = &fimc_qops;
src_vq->mem_ops = &vb2_dma_contig_memops;
src_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
ret = vb2_queue_init(src_vq);
if (ret)
return ret;
memset(dst_vq, 0, sizeof(*dst_vq));
dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
dst_vq->io_modes = VB2_MMAP | VB2_USERPTR;
dst_vq->drv_priv = ctx;
dst_vq->ops = &fimc_qops;
dst_vq->mem_ops = &vb2_dma_contig_memops;
dst_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
return vb2_queue_init(dst_vq);
}
static int fimc_m2m_open(struct file *file)
{
struct fimc_dev *fimc = video_drvdata(file);
struct fimc_ctx *ctx;
int ret;
dbg("pid: %d, state: 0x%lx, refcnt: %d",
task_pid_nr(current), fimc->state, fimc->vid_cap.refcnt);
/*
* Return if the corresponding video capture node
* is already opened.
*/
if (fimc->vid_cap.refcnt > 0)
return -EBUSY;
ctx = kzalloc(sizeof *ctx, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
v4l2_fh_init(&ctx->fh, fimc->m2m.vfd);
ctx->fimc_dev = fimc;
/* Default color format */
ctx->s_frame.fmt = &fimc_formats[0];
ctx->d_frame.fmt = &fimc_formats[0];
ret = fimc_ctrls_create(ctx);
if (ret)
goto error_fh;
/* Use separate control handler per file handle */
ctx->fh.ctrl_handler = &ctx->ctrl_handler;
file->private_data = &ctx->fh;
v4l2_fh_add(&ctx->fh);
/* Setup the device context for memory-to-memory mode */
ctx->state = FIMC_CTX_M2M;
ctx->flags = 0;
ctx->in_path = FIMC_DMA;
ctx->out_path = FIMC_DMA;
spin_lock_init(&ctx->slock);
ctx->m2m_ctx = v4l2_m2m_ctx_init(fimc->m2m.m2m_dev, ctx, queue_init);
if (IS_ERR(ctx->m2m_ctx)) {
ret = PTR_ERR(ctx->m2m_ctx);
goto error_c;
}
if (fimc->m2m.refcnt++ == 0)
set_bit(ST_M2M_RUN, &fimc->state);
return 0;
error_c:
fimc_ctrls_delete(ctx);
error_fh:
v4l2_fh_del(&ctx->fh);
v4l2_fh_exit(&ctx->fh);
kfree(ctx);
return ret;
}
static int fimc_m2m_release(struct file *file)
{
struct fimc_ctx *ctx = fh_to_ctx(file->private_data);
struct fimc_dev *fimc = ctx->fimc_dev;
dbg("pid: %d, state: 0x%lx, refcnt= %d",
task_pid_nr(current), fimc->state, fimc->m2m.refcnt);
v4l2_m2m_ctx_release(ctx->m2m_ctx);
fimc_ctrls_delete(ctx);
v4l2_fh_del(&ctx->fh);
v4l2_fh_exit(&ctx->fh);
if (--fimc->m2m.refcnt <= 0)
clear_bit(ST_M2M_RUN, &fimc->state);
kfree(ctx);
return 0;
}
static unsigned int fimc_m2m_poll(struct file *file,
struct poll_table_struct *wait)
{
struct fimc_ctx *ctx = fh_to_ctx(file->private_data);
return v4l2_m2m_poll(file, ctx->m2m_ctx, wait);
}
static int fimc_m2m_mmap(struct file *file, struct vm_area_struct *vma)
{
struct fimc_ctx *ctx = fh_to_ctx(file->private_data);
return v4l2_m2m_mmap(file, ctx->m2m_ctx, vma);
}
static const struct v4l2_file_operations fimc_m2m_fops = {
.owner = THIS_MODULE,
.open = fimc_m2m_open,
.release = fimc_m2m_release,
.poll = fimc_m2m_poll,
.unlocked_ioctl = video_ioctl2,
.mmap = fimc_m2m_mmap,
};
static struct v4l2_m2m_ops m2m_ops = {
.device_run = fimc_dma_run,
.job_abort = fimc_job_abort,
};
int fimc_register_m2m_device(struct fimc_dev *fimc,
struct v4l2_device *v4l2_dev)
{
struct video_device *vfd;
struct platform_device *pdev;
int ret = 0;
if (!fimc)
return -ENODEV;
pdev = fimc->pdev;
fimc->v4l2_dev = v4l2_dev;
vfd = video_device_alloc();
if (!vfd) {
v4l2_err(v4l2_dev, "Failed to allocate video device\n");
return -ENOMEM;
}
vfd->fops = &fimc_m2m_fops;
vfd->ioctl_ops = &fimc_m2m_ioctl_ops;
vfd->v4l2_dev = v4l2_dev;
vfd->minor = -1;
vfd->release = video_device_release;
vfd->lock = &fimc->lock;
snprintf(vfd->name, sizeof(vfd->name), "%s.m2m", dev_name(&pdev->dev));
video_set_drvdata(vfd, fimc);
fimc->m2m.vfd = vfd;
fimc->m2m.m2m_dev = v4l2_m2m_init(&m2m_ops);
if (IS_ERR(fimc->m2m.m2m_dev)) {
v4l2_err(v4l2_dev, "failed to initialize v4l2-m2m device\n");
ret = PTR_ERR(fimc->m2m.m2m_dev);
goto err_init;
}
ret = media_entity_init(&vfd->entity, 0, NULL, 0);
if (!ret)
return 0;
v4l2_m2m_release(fimc->m2m.m2m_dev);
err_init:
video_device_release(fimc->m2m.vfd);
return ret;
}
void fimc_unregister_m2m_device(struct fimc_dev *fimc)
{
if (!fimc)
return;
if (fimc->m2m.m2m_dev)
v4l2_m2m_release(fimc->m2m.m2m_dev);
if (fimc->m2m.vfd) {
media_entity_cleanup(&fimc->m2m.vfd->entity);
/* Can also be called if video device wasn't registered */
video_unregister_device(fimc->m2m.vfd);
}
}
static void fimc_clk_put(struct fimc_dev *fimc)
{
int i;
for (i = 0; i < fimc->num_clocks; i++) {
if (IS_ERR_OR_NULL(fimc->clock[i]))
continue;
clk_unprepare(fimc->clock[i]);
clk_put(fimc->clock[i]);
fimc->clock[i] = NULL;
}
}
static int fimc_clk_get(struct fimc_dev *fimc)
{
int i, ret;
for (i = 0; i < fimc->num_clocks; i++) {
fimc->clock[i] = clk_get(&fimc->pdev->dev, fimc_clocks[i]);
if (IS_ERR(fimc->clock[i]))
goto err;
ret = clk_prepare(fimc->clock[i]);
if (ret < 0) {
clk_put(fimc->clock[i]);
fimc->clock[i] = NULL;
goto err;
}
}
return 0;
err:
fimc_clk_put(fimc);
dev_err(&fimc->pdev->dev, "failed to get clock: %s\n",
fimc_clocks[i]);
return -ENXIO;
}
static int fimc_m2m_suspend(struct fimc_dev *fimc)
{
unsigned long flags;
int timeout;
spin_lock_irqsave(&fimc->slock, flags);
if (!fimc_m2m_pending(fimc)) {
spin_unlock_irqrestore(&fimc->slock, flags);
return 0;
}
clear_bit(ST_M2M_SUSPENDED, &fimc->state);
set_bit(ST_M2M_SUSPENDING, &fimc->state);
spin_unlock_irqrestore(&fimc->slock, flags);
timeout = wait_event_timeout(fimc->irq_queue,
test_bit(ST_M2M_SUSPENDED, &fimc->state),
FIMC_SHUTDOWN_TIMEOUT);
clear_bit(ST_M2M_SUSPENDING, &fimc->state);
return timeout == 0 ? -EAGAIN : 0;
}
static int fimc_m2m_resume(struct fimc_dev *fimc)
{
unsigned long flags;
spin_lock_irqsave(&fimc->slock, flags);
/* Clear for full H/W setup in first run after resume */
fimc->m2m.ctx = NULL;
spin_unlock_irqrestore(&fimc->slock, flags);
if (test_and_clear_bit(ST_M2M_SUSPENDED, &fimc->state))
fimc_m2m_job_finish(fimc->m2m.ctx,
VB2_BUF_STATE_ERROR);
return 0;
}
static int fimc_probe(struct platform_device *pdev)
{
struct fimc_dev *fimc;
struct resource *res;
struct samsung_fimc_driverdata *drv_data;
struct s5p_platform_fimc *pdata;
int ret = 0;
drv_data = (struct samsung_fimc_driverdata *)
platform_get_device_id(pdev)->driver_data;
if (pdev->id >= drv_data->num_entities) {
dev_err(&pdev->dev, "Invalid platform device id: %d\n",
pdev->id);
return -EINVAL;
}
fimc = devm_kzalloc(&pdev->dev, sizeof(*fimc), GFP_KERNEL);
if (!fimc)
return -ENOMEM;
fimc->id = pdev->id;
fimc->variant = drv_data->variant[fimc->id];
fimc->pdev = pdev;
pdata = pdev->dev.platform_data;
fimc->pdata = pdata;
init_waitqueue_head(&fimc->irq_queue);
spin_lock_init(&fimc->slock);
mutex_init(&fimc->lock);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
fimc->regs = devm_request_and_ioremap(&pdev->dev, res);
if (fimc->regs == NULL) {
dev_err(&pdev->dev, "Failed to obtain io memory\n");
return -ENOENT;
}
res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (res == NULL) {
dev_err(&pdev->dev, "Failed to get IRQ resource\n");
return -ENXIO;
}
fimc->irq = res->start;
fimc->num_clocks = MAX_FIMC_CLOCKS;
ret = fimc_clk_get(fimc);
if (ret)
return ret;
clk_set_rate(fimc->clock[CLK_BUS], drv_data->lclk_frequency);
clk_enable(fimc->clock[CLK_BUS]);
platform_set_drvdata(pdev, fimc);
ret = devm_request_irq(&pdev->dev, fimc->irq, fimc_irq_handler,
0, pdev->name, fimc);
if (ret) {
dev_err(&pdev->dev, "failed to install irq (%d)\n", ret);
goto err_clk;
}
pm_runtime_enable(&pdev->dev);
ret = pm_runtime_get_sync(&pdev->dev);
if (ret < 0)
goto err_clk;
/* Initialize contiguous memory allocator */
fimc->alloc_ctx = vb2_dma_contig_init_ctx(&pdev->dev);
if (IS_ERR(fimc->alloc_ctx)) {
ret = PTR_ERR(fimc->alloc_ctx);
goto err_pm;
}
dev_dbg(&pdev->dev, "FIMC.%d registered successfully\n", fimc->id);
pm_runtime_put(&pdev->dev);
return 0;
err_pm:
pm_runtime_put(&pdev->dev);
err_clk:
fimc_clk_put(fimc);
return ret;
}
static int fimc_runtime_resume(struct device *dev)
{
struct fimc_dev *fimc = dev_get_drvdata(dev);
dbg("fimc%d: state: 0x%lx", fimc->id, fimc->state);
/* Enable clocks and perform basic initalization */
clk_enable(fimc->clock[CLK_GATE]);
fimc_hw_reset(fimc);
/* Resume the capture or mem-to-mem device */
if (fimc_capture_busy(fimc))
return fimc_capture_resume(fimc);
return fimc_m2m_resume(fimc);
}
static int fimc_runtime_suspend(struct device *dev)
{
struct fimc_dev *fimc = dev_get_drvdata(dev);
int ret = 0;
if (fimc_capture_busy(fimc))
ret = fimc_capture_suspend(fimc);
else
ret = fimc_m2m_suspend(fimc);
if (!ret)
clk_disable(fimc->clock[CLK_GATE]);
dbg("fimc%d: state: 0x%lx", fimc->id, fimc->state);
return ret;
}
#ifdef CONFIG_PM_SLEEP
static int fimc_resume(struct device *dev)
{
struct fimc_dev *fimc = dev_get_drvdata(dev);
unsigned long flags;
dbg("fimc%d: state: 0x%lx", fimc->id, fimc->state);
/* Do not resume if the device was idle before system suspend */
spin_lock_irqsave(&fimc->slock, flags);
if (!test_and_clear_bit(ST_LPM, &fimc->state) ||
(!fimc_m2m_active(fimc) && !fimc_capture_busy(fimc))) {
spin_unlock_irqrestore(&fimc->slock, flags);
return 0;
}
fimc_hw_reset(fimc);
spin_unlock_irqrestore(&fimc->slock, flags);
if (fimc_capture_busy(fimc))
return fimc_capture_resume(fimc);
return fimc_m2m_resume(fimc);
}
static int fimc_suspend(struct device *dev)
{
struct fimc_dev *fimc = dev_get_drvdata(dev);
dbg("fimc%d: state: 0x%lx", fimc->id, fimc->state);
if (test_and_set_bit(ST_LPM, &fimc->state))
return 0;
if (fimc_capture_busy(fimc))
return fimc_capture_suspend(fimc);
return fimc_m2m_suspend(fimc);
}
#endif /* CONFIG_PM_SLEEP */
static int __devexit fimc_remove(struct platform_device *pdev)
{
struct fimc_dev *fimc = platform_get_drvdata(pdev);
pm_runtime_disable(&pdev->dev);
pm_runtime_set_suspended(&pdev->dev);
vb2_dma_contig_cleanup_ctx(fimc->alloc_ctx);
clk_disable(fimc->clock[CLK_BUS]);
fimc_clk_put(fimc);
dev_info(&pdev->dev, "driver unloaded\n");
return 0;
}
/* Image pixel limits, similar across several FIMC HW revisions. */
static struct fimc_pix_limit s5p_pix_limit[4] = {
[0] = {
.scaler_en_w = 3264,
.scaler_dis_w = 8192,
.in_rot_en_h = 1920,
.in_rot_dis_w = 8192,
.out_rot_en_w = 1920,
.out_rot_dis_w = 4224,
},
[1] = {
.scaler_en_w = 4224,
.scaler_dis_w = 8192,
.in_rot_en_h = 1920,
.in_rot_dis_w = 8192,
.out_rot_en_w = 1920,
.out_rot_dis_w = 4224,
},
[2] = {
.scaler_en_w = 1920,
.scaler_dis_w = 8192,
.in_rot_en_h = 1280,
.in_rot_dis_w = 8192,
.out_rot_en_w = 1280,
.out_rot_dis_w = 1920,
},
[3] = {
.scaler_en_w = 1920,
.scaler_dis_w = 8192,
.in_rot_en_h = 1366,
.in_rot_dis_w = 8192,
.out_rot_en_w = 1366,
.out_rot_dis_w = 1920,
},
};
static struct samsung_fimc_variant fimc0_variant_s5p = {
.has_inp_rot = 1,
.has_out_rot = 1,
.has_cam_if = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 8,
.min_vsize_align = 16,
.out_buf_count = 4,
.pix_limit = &s5p_pix_limit[0],
};
static struct samsung_fimc_variant fimc2_variant_s5p = {
.has_cam_if = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 8,
.min_vsize_align = 16,
.out_buf_count = 4,
.pix_limit = &s5p_pix_limit[1],
};
static struct samsung_fimc_variant fimc0_variant_s5pv210 = {
.pix_hoff = 1,
.has_inp_rot = 1,
.has_out_rot = 1,
.has_cam_if = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 8,
.min_vsize_align = 16,
.out_buf_count = 4,
.pix_limit = &s5p_pix_limit[1],
};
static struct samsung_fimc_variant fimc1_variant_s5pv210 = {
.pix_hoff = 1,
.has_inp_rot = 1,
.has_out_rot = 1,
.has_cam_if = 1,
.has_mainscaler_ext = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 1,
.min_vsize_align = 1,
.out_buf_count = 4,
.pix_limit = &s5p_pix_limit[2],
};
static struct samsung_fimc_variant fimc2_variant_s5pv210 = {
.has_cam_if = 1,
.pix_hoff = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 8,
.min_vsize_align = 16,
.out_buf_count = 4,
.pix_limit = &s5p_pix_limit[2],
};
static struct samsung_fimc_variant fimc0_variant_exynos4 = {
.pix_hoff = 1,
.has_inp_rot = 1,
.has_out_rot = 1,
.has_cam_if = 1,
.has_cistatus2 = 1,
.has_mainscaler_ext = 1,
.has_alpha = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 2,
.min_vsize_align = 1,
.out_buf_count = 32,
.pix_limit = &s5p_pix_limit[1],
};
static struct samsung_fimc_variant fimc3_variant_exynos4 = {
.pix_hoff = 1,
.has_cam_if = 1,
.has_cistatus2 = 1,
.has_mainscaler_ext = 1,
.has_alpha = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 2,
.min_vsize_align = 1,
.out_buf_count = 32,
.pix_limit = &s5p_pix_limit[3],
};
/* S5PC100 */
static struct samsung_fimc_driverdata fimc_drvdata_s5p = {
.variant = {
[0] = &fimc0_variant_s5p,
[1] = &fimc0_variant_s5p,
[2] = &fimc2_variant_s5p,
},
.num_entities = 3,
.lclk_frequency = 133000000UL,
};
/* S5PV210, S5PC110 */
static struct samsung_fimc_driverdata fimc_drvdata_s5pv210 = {
.variant = {
[0] = &fimc0_variant_s5pv210,
[1] = &fimc1_variant_s5pv210,
[2] = &fimc2_variant_s5pv210,
},
.num_entities = 3,
.lclk_frequency = 166000000UL,
};
/* S5PV310, S5PC210 */
static struct samsung_fimc_driverdata fimc_drvdata_exynos4 = {
.variant = {
[0] = &fimc0_variant_exynos4,
[1] = &fimc0_variant_exynos4,
[2] = &fimc0_variant_exynos4,
[3] = &fimc3_variant_exynos4,
},
.num_entities = 4,
.lclk_frequency = 166000000UL,
};
static struct platform_device_id fimc_driver_ids[] = {
{
.name = "s5p-fimc",
.driver_data = (unsigned long)&fimc_drvdata_s5p,
}, {
.name = "s5pv210-fimc",
.driver_data = (unsigned long)&fimc_drvdata_s5pv210,
}, {
.name = "exynos4-fimc",
.driver_data = (unsigned long)&fimc_drvdata_exynos4,
},
{},
};
MODULE_DEVICE_TABLE(platform, fimc_driver_ids);
static const struct dev_pm_ops fimc_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(fimc_suspend, fimc_resume)
SET_RUNTIME_PM_OPS(fimc_runtime_suspend, fimc_runtime_resume, NULL)
};
static struct platform_driver fimc_driver = {
.probe = fimc_probe,
.remove = __devexit_p(fimc_remove),
.id_table = fimc_driver_ids,
.driver = {
.name = FIMC_MODULE_NAME,
.owner = THIS_MODULE,
.pm = &fimc_pm_ops,
}
};
int __init fimc_register_driver(void)
{
return platform_driver_probe(&fimc_driver, fimc_probe);
}
void __exit fimc_unregister_driver(void)
{
platform_driver_unregister(&fimc_driver);
}
| gpl-2.0 |
houst0nn/android_kernel_lge_geeb | drivers/media/video/cx25821/cx25821-medusa-video.c | 4902 | 21305 | /*
* Driver for the Conexant CX25821 PCIe bridge
*
* Copyright (C) 2009 Conexant Systems Inc.
* Authors <shu.lin@conexant.com>, <hiep.huynh@conexant.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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include "cx25821.h"
#include "cx25821-medusa-video.h"
#include "cx25821-biffuncs.h"
/*
* medusa_enable_bluefield_output()
*
* Enable the generation of blue filed output if no video
*
*/
static void medusa_enable_bluefield_output(struct cx25821_dev *dev, int channel,
int enable)
{
int ret_val = 1;
u32 value = 0;
u32 tmp = 0;
int out_ctrl = OUT_CTRL1;
int out_ctrl_ns = OUT_CTRL_NS;
switch (channel) {
default:
case VDEC_A:
break;
case VDEC_B:
out_ctrl = VDEC_B_OUT_CTRL1;
out_ctrl_ns = VDEC_B_OUT_CTRL_NS;
break;
case VDEC_C:
out_ctrl = VDEC_C_OUT_CTRL1;
out_ctrl_ns = VDEC_C_OUT_CTRL_NS;
break;
case VDEC_D:
out_ctrl = VDEC_D_OUT_CTRL1;
out_ctrl_ns = VDEC_D_OUT_CTRL_NS;
break;
case VDEC_E:
out_ctrl = VDEC_E_OUT_CTRL1;
out_ctrl_ns = VDEC_E_OUT_CTRL_NS;
return;
case VDEC_F:
out_ctrl = VDEC_F_OUT_CTRL1;
out_ctrl_ns = VDEC_F_OUT_CTRL_NS;
return;
case VDEC_G:
out_ctrl = VDEC_G_OUT_CTRL1;
out_ctrl_ns = VDEC_G_OUT_CTRL_NS;
return;
case VDEC_H:
out_ctrl = VDEC_H_OUT_CTRL1;
out_ctrl_ns = VDEC_H_OUT_CTRL_NS;
return;
}
value = cx25821_i2c_read(&dev->i2c_bus[0], out_ctrl, &tmp);
value &= 0xFFFFFF7F; /* clear BLUE_FIELD_EN */
if (enable)
value |= 0x00000080; /* set BLUE_FIELD_EN */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0], out_ctrl, value);
value = cx25821_i2c_read(&dev->i2c_bus[0], out_ctrl_ns, &tmp);
value &= 0xFFFFFF7F;
if (enable)
value |= 0x00000080; /* set BLUE_FIELD_EN */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0], out_ctrl_ns, value);
}
static int medusa_initialize_ntsc(struct cx25821_dev *dev)
{
int ret_val = 0;
int i = 0;
u32 value = 0;
u32 tmp = 0;
mutex_lock(&dev->lock);
for (i = 0; i < MAX_DECODERS; i++) {
/* set video format NTSC-M */
value = cx25821_i2c_read(&dev->i2c_bus[0],
MODE_CTRL + (0x200 * i), &tmp);
value &= 0xFFFFFFF0;
/* enable the fast locking mode bit[16] */
value |= 0x10001;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
MODE_CTRL + (0x200 * i), value);
/* resolution NTSC 720x480 */
value = cx25821_i2c_read(&dev->i2c_bus[0],
HORIZ_TIM_CTRL + (0x200 * i), &tmp);
value &= 0x00C00C00;
value |= 0x612D0074;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
HORIZ_TIM_CTRL + (0x200 * i), value);
value = cx25821_i2c_read(&dev->i2c_bus[0],
VERT_TIM_CTRL + (0x200 * i), &tmp);
value &= 0x00C00C00;
value |= 0x1C1E001A; /* vblank_cnt + 2 to get camera ID */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
VERT_TIM_CTRL + (0x200 * i), value);
/* chroma subcarrier step size */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
SC_STEP_SIZE + (0x200 * i), 0x43E00000);
/* enable VIP optional active */
value = cx25821_i2c_read(&dev->i2c_bus[0],
OUT_CTRL_NS + (0x200 * i), &tmp);
value &= 0xFFFBFFFF;
value |= 0x00040000;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
OUT_CTRL_NS + (0x200 * i), value);
/* enable VIP optional active (VIP_OPT_AL) for direct output. */
value = cx25821_i2c_read(&dev->i2c_bus[0],
OUT_CTRL1 + (0x200 * i), &tmp);
value &= 0xFFFBFFFF;
value |= 0x00040000;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
OUT_CTRL1 + (0x200 * i), value);
/*
* clear VPRES_VERT_EN bit, fixes the chroma run away problem
* when the input switching rate < 16 fields
*/
value = cx25821_i2c_read(&dev->i2c_bus[0],
MISC_TIM_CTRL + (0x200 * i), &tmp);
/* disable special play detection */
value = setBitAtPos(value, 14);
value = clearBitAtPos(value, 15);
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
MISC_TIM_CTRL + (0x200 * i), value);
/* set vbi_gate_en to 0 */
value = cx25821_i2c_read(&dev->i2c_bus[0],
DFE_CTRL1 + (0x200 * i), &tmp);
value = clearBitAtPos(value, 29);
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DFE_CTRL1 + (0x200 * i), value);
/* Enable the generation of blue field output if no video */
medusa_enable_bluefield_output(dev, i, 1);
}
for (i = 0; i < MAX_ENCODERS; i++) {
/* NTSC hclock */
value = cx25821_i2c_read(&dev->i2c_bus[0],
DENC_A_REG_1 + (0x100 * i), &tmp);
value &= 0xF000FC00;
value |= 0x06B402D0;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DENC_A_REG_1 + (0x100 * i), value);
/* burst begin and burst end */
value = cx25821_i2c_read(&dev->i2c_bus[0],
DENC_A_REG_2 + (0x100 * i), &tmp);
value &= 0xFF000000;
value |= 0x007E9054;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DENC_A_REG_2 + (0x100 * i), value);
value = cx25821_i2c_read(&dev->i2c_bus[0],
DENC_A_REG_3 + (0x100 * i), &tmp);
value &= 0xFC00FE00;
value |= 0x00EC00F0;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DENC_A_REG_3 + (0x100 * i), value);
/* set NTSC vblank, no phase alternation, 7.5 IRE pedestal */
value = cx25821_i2c_read(&dev->i2c_bus[0],
DENC_A_REG_4 + (0x100 * i), &tmp);
value &= 0x00FCFFFF;
value |= 0x13020000;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DENC_A_REG_4 + (0x100 * i), value);
value = cx25821_i2c_read(&dev->i2c_bus[0],
DENC_A_REG_5 + (0x100 * i), &tmp);
value &= 0xFFFF0000;
value |= 0x0000E575;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DENC_A_REG_5 + (0x100 * i), value);
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DENC_A_REG_6 + (0x100 * i), 0x009A89C1);
/* Subcarrier Increment */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DENC_A_REG_7 + (0x100 * i), 0x21F07C1F);
}
/* set picture resolutions */
/* 0 - 720 */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0], HSCALE_CTRL, 0x0);
/* 0 - 480 */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0], VSCALE_CTRL, 0x0);
/* set Bypass input format to NTSC 525 lines */
value = cx25821_i2c_read(&dev->i2c_bus[0], BYP_AB_CTRL, &tmp);
value |= 0x00080200;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0], BYP_AB_CTRL, value);
mutex_unlock(&dev->lock);
return ret_val;
}
static int medusa_PALCombInit(struct cx25821_dev *dev, int dec)
{
int ret_val = -1;
u32 value = 0, tmp = 0;
/* Setup for 2D threshold */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
COMB_2D_HFS_CFG + (0x200 * dec), 0x20002861);
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
COMB_2D_HFD_CFG + (0x200 * dec), 0x20002861);
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
COMB_2D_LF_CFG + (0x200 * dec), 0x200A1023);
/* Setup flat chroma and luma thresholds */
value = cx25821_i2c_read(&dev->i2c_bus[0],
COMB_FLAT_THRESH_CTRL + (0x200 * dec), &tmp);
value &= 0x06230000;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
COMB_FLAT_THRESH_CTRL + (0x200 * dec), value);
/* set comb 2D blend */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
COMB_2D_BLEND + (0x200 * dec), 0x210F0F0F);
/* COMB MISC CONTROL */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
COMB_MISC_CTRL + (0x200 * dec), 0x41120A7F);
return ret_val;
}
static int medusa_initialize_pal(struct cx25821_dev *dev)
{
int ret_val = 0;
int i = 0;
u32 value = 0;
u32 tmp = 0;
mutex_lock(&dev->lock);
for (i = 0; i < MAX_DECODERS; i++) {
/* set video format PAL-BDGHI */
value = cx25821_i2c_read(&dev->i2c_bus[0],
MODE_CTRL + (0x200 * i), &tmp);
value &= 0xFFFFFFF0;
/* enable the fast locking mode bit[16] */
value |= 0x10004;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
MODE_CTRL + (0x200 * i), value);
/* resolution PAL 720x576 */
value = cx25821_i2c_read(&dev->i2c_bus[0],
HORIZ_TIM_CTRL + (0x200 * i), &tmp);
value &= 0x00C00C00;
value |= 0x632D007D;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
HORIZ_TIM_CTRL + (0x200 * i), value);
/* vblank656_cnt=x26, vactive_cnt=240h, vblank_cnt=x24 */
value = cx25821_i2c_read(&dev->i2c_bus[0],
VERT_TIM_CTRL + (0x200 * i), &tmp);
value &= 0x00C00C00;
value |= 0x28240026; /* vblank_cnt + 2 to get camera ID */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
VERT_TIM_CTRL + (0x200 * i), value);
/* chroma subcarrier step size */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
SC_STEP_SIZE + (0x200 * i), 0x5411E2D0);
/* enable VIP optional active */
value = cx25821_i2c_read(&dev->i2c_bus[0],
OUT_CTRL_NS + (0x200 * i), &tmp);
value &= 0xFFFBFFFF;
value |= 0x00040000;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
OUT_CTRL_NS + (0x200 * i), value);
/* enable VIP optional active (VIP_OPT_AL) for direct output. */
value = cx25821_i2c_read(&dev->i2c_bus[0],
OUT_CTRL1 + (0x200 * i), &tmp);
value &= 0xFFFBFFFF;
value |= 0x00040000;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
OUT_CTRL1 + (0x200 * i), value);
/*
* clear VPRES_VERT_EN bit, fixes the chroma run away problem
* when the input switching rate < 16 fields
*/
value = cx25821_i2c_read(&dev->i2c_bus[0],
MISC_TIM_CTRL + (0x200 * i), &tmp);
/* disable special play detection */
value = setBitAtPos(value, 14);
value = clearBitAtPos(value, 15);
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
MISC_TIM_CTRL + (0x200 * i), value);
/* set vbi_gate_en to 0 */
value = cx25821_i2c_read(&dev->i2c_bus[0],
DFE_CTRL1 + (0x200 * i), &tmp);
value = clearBitAtPos(value, 29);
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DFE_CTRL1 + (0x200 * i), value);
medusa_PALCombInit(dev, i);
/* Enable the generation of blue field output if no video */
medusa_enable_bluefield_output(dev, i, 1);
}
for (i = 0; i < MAX_ENCODERS; i++) {
/* PAL hclock */
value = cx25821_i2c_read(&dev->i2c_bus[0],
DENC_A_REG_1 + (0x100 * i), &tmp);
value &= 0xF000FC00;
value |= 0x06C002D0;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DENC_A_REG_1 + (0x100 * i), value);
/* burst begin and burst end */
value = cx25821_i2c_read(&dev->i2c_bus[0],
DENC_A_REG_2 + (0x100 * i), &tmp);
value &= 0xFF000000;
value |= 0x007E9754;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DENC_A_REG_2 + (0x100 * i), value);
/* hblank and vactive */
value = cx25821_i2c_read(&dev->i2c_bus[0],
DENC_A_REG_3 + (0x100 * i), &tmp);
value &= 0xFC00FE00;
value |= 0x00FC0120;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DENC_A_REG_3 + (0x100 * i), value);
/* set PAL vblank, phase alternation, 0 IRE pedestal */
value = cx25821_i2c_read(&dev->i2c_bus[0],
DENC_A_REG_4 + (0x100 * i), &tmp);
value &= 0x00FCFFFF;
value |= 0x14010000;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DENC_A_REG_4 + (0x100 * i), value);
value = cx25821_i2c_read(&dev->i2c_bus[0],
DENC_A_REG_5 + (0x100 * i), &tmp);
value &= 0xFFFF0000;
value |= 0x0000F078;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DENC_A_REG_5 + (0x100 * i), value);
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DENC_A_REG_6 + (0x100 * i), 0x00A493CF);
/* Subcarrier Increment */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
DENC_A_REG_7 + (0x100 * i), 0x2A098ACB);
}
/* set picture resolutions */
/* 0 - 720 */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0], HSCALE_CTRL, 0x0);
/* 0 - 576 */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0], VSCALE_CTRL, 0x0);
/* set Bypass input format to PAL 625 lines */
value = cx25821_i2c_read(&dev->i2c_bus[0], BYP_AB_CTRL, &tmp);
value &= 0xFFF7FDFF;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0], BYP_AB_CTRL, value);
mutex_unlock(&dev->lock);
return ret_val;
}
int medusa_set_videostandard(struct cx25821_dev *dev)
{
int status = STATUS_SUCCESS;
u32 value = 0, tmp = 0;
if (dev->tvnorm & V4L2_STD_PAL_BG || dev->tvnorm & V4L2_STD_PAL_DK)
status = medusa_initialize_pal(dev);
else
status = medusa_initialize_ntsc(dev);
/* Enable DENC_A output */
value = cx25821_i2c_read(&dev->i2c_bus[0], DENC_A_REG_4, &tmp);
value = setBitAtPos(value, 4);
status = cx25821_i2c_write(&dev->i2c_bus[0], DENC_A_REG_4, value);
/* Enable DENC_B output */
value = cx25821_i2c_read(&dev->i2c_bus[0], DENC_B_REG_4, &tmp);
value = setBitAtPos(value, 4);
status = cx25821_i2c_write(&dev->i2c_bus[0], DENC_B_REG_4, value);
return status;
}
void medusa_set_resolution(struct cx25821_dev *dev, int width,
int decoder_select)
{
int decoder = 0;
int decoder_count = 0;
int ret_val = 0;
u32 hscale = 0x0;
u32 vscale = 0x0;
const int MAX_WIDTH = 720;
mutex_lock(&dev->lock);
/* validate the width */
if (width > MAX_WIDTH) {
pr_info("%s(): width %d > MAX_WIDTH %d ! resetting to MAX_WIDTH\n",
__func__, width, MAX_WIDTH);
width = MAX_WIDTH;
}
if (decoder_select <= 7 && decoder_select >= 0) {
decoder = decoder_select;
decoder_count = decoder_select + 1;
} else {
decoder = 0;
decoder_count = _num_decoders;
}
switch (width) {
case 320:
hscale = 0x13E34B;
vscale = 0x0;
break;
case 352:
hscale = 0x10A273;
vscale = 0x0;
break;
case 176:
hscale = 0x3115B2;
vscale = 0x1E00;
break;
case 160:
hscale = 0x378D84;
vscale = 0x1E00;
break;
default: /* 720 */
hscale = 0x0;
vscale = 0x0;
break;
}
for (; decoder < decoder_count; decoder++) {
/* write scaling values for each decoder */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
HSCALE_CTRL + (0x200 * decoder), hscale);
ret_val = cx25821_i2c_write(&dev->i2c_bus[0],
VSCALE_CTRL + (0x200 * decoder), vscale);
}
mutex_unlock(&dev->lock);
}
static void medusa_set_decoderduration(struct cx25821_dev *dev, int decoder,
int duration)
{
int ret_val = 0;
u32 fld_cnt = 0;
u32 tmp = 0;
u32 disp_cnt_reg = DISP_AB_CNT;
mutex_lock(&dev->lock);
/* no support */
if (decoder < VDEC_A && decoder > VDEC_H) {
mutex_unlock(&dev->lock);
return;
}
switch (decoder) {
default:
break;
case VDEC_C:
case VDEC_D:
disp_cnt_reg = DISP_CD_CNT;
break;
case VDEC_E:
case VDEC_F:
disp_cnt_reg = DISP_EF_CNT;
break;
case VDEC_G:
case VDEC_H:
disp_cnt_reg = DISP_GH_CNT;
break;
}
_display_field_cnt[decoder] = duration;
/* update hardware */
fld_cnt = cx25821_i2c_read(&dev->i2c_bus[0], disp_cnt_reg, &tmp);
if (!(decoder % 2)) { /* EVEN decoder */
fld_cnt &= 0xFFFF0000;
fld_cnt |= duration;
} else {
fld_cnt &= 0x0000FFFF;
fld_cnt |= ((u32) duration) << 16;
}
ret_val = cx25821_i2c_write(&dev->i2c_bus[0], disp_cnt_reg, fld_cnt);
mutex_unlock(&dev->lock);
}
/* Map to Medusa register setting */
static int mapM(int srcMin, int srcMax, int srcVal, int dstMin, int dstMax,
int *dstVal)
{
int numerator;
int denominator;
int quotient;
if ((srcMin == srcMax) || (srcVal < srcMin) || (srcVal > srcMax))
return -1;
/*
* This is the overall expression used:
* *dstVal =
* (srcVal - srcMin)*(dstMax - dstMin) / (srcMax - srcMin) + dstMin;
* but we need to account for rounding so below we use the modulus
* operator to find the remainder and increment if necessary.
*/
numerator = (srcVal - srcMin) * (dstMax - dstMin);
denominator = srcMax - srcMin;
quotient = numerator / denominator;
if (2 * (numerator % denominator) >= denominator)
quotient++;
*dstVal = quotient + dstMin;
return 0;
}
static unsigned long convert_to_twos(long numeric, unsigned long bits_len)
{
unsigned char temp;
if (numeric >= 0)
return numeric;
else {
temp = ~(abs(numeric) & 0xFF);
temp += 1;
return temp;
}
}
int medusa_set_brightness(struct cx25821_dev *dev, int brightness, int decoder)
{
int ret_val = 0;
int value = 0;
u32 val = 0, tmp = 0;
mutex_lock(&dev->lock);
if ((brightness > VIDEO_PROCAMP_MAX) ||
(brightness < VIDEO_PROCAMP_MIN)) {
mutex_unlock(&dev->lock);
return -1;
}
ret_val = mapM(VIDEO_PROCAMP_MIN, VIDEO_PROCAMP_MAX, brightness,
SIGNED_BYTE_MIN, SIGNED_BYTE_MAX, &value);
value = convert_to_twos(value, 8);
val = cx25821_i2c_read(&dev->i2c_bus[0],
VDEC_A_BRITE_CTRL + (0x200 * decoder), &tmp);
val &= 0xFFFFFF00;
ret_val |= cx25821_i2c_write(&dev->i2c_bus[0],
VDEC_A_BRITE_CTRL + (0x200 * decoder), val | value);
mutex_unlock(&dev->lock);
return ret_val;
}
int medusa_set_contrast(struct cx25821_dev *dev, int contrast, int decoder)
{
int ret_val = 0;
int value = 0;
u32 val = 0, tmp = 0;
mutex_lock(&dev->lock);
if ((contrast > VIDEO_PROCAMP_MAX) || (contrast < VIDEO_PROCAMP_MIN)) {
mutex_unlock(&dev->lock);
return -1;
}
ret_val = mapM(VIDEO_PROCAMP_MIN, VIDEO_PROCAMP_MAX, contrast,
UNSIGNED_BYTE_MIN, UNSIGNED_BYTE_MAX, &value);
val = cx25821_i2c_read(&dev->i2c_bus[0],
VDEC_A_CNTRST_CTRL + (0x200 * decoder), &tmp);
val &= 0xFFFFFF00;
ret_val |= cx25821_i2c_write(&dev->i2c_bus[0],
VDEC_A_CNTRST_CTRL + (0x200 * decoder), val | value);
mutex_unlock(&dev->lock);
return ret_val;
}
int medusa_set_hue(struct cx25821_dev *dev, int hue, int decoder)
{
int ret_val = 0;
int value = 0;
u32 val = 0, tmp = 0;
mutex_lock(&dev->lock);
if ((hue > VIDEO_PROCAMP_MAX) || (hue < VIDEO_PROCAMP_MIN)) {
mutex_unlock(&dev->lock);
return -1;
}
ret_val = mapM(VIDEO_PROCAMP_MIN, VIDEO_PROCAMP_MAX, hue,
SIGNED_BYTE_MIN, SIGNED_BYTE_MAX, &value);
value = convert_to_twos(value, 8);
val = cx25821_i2c_read(&dev->i2c_bus[0],
VDEC_A_HUE_CTRL + (0x200 * decoder), &tmp);
val &= 0xFFFFFF00;
ret_val |= cx25821_i2c_write(&dev->i2c_bus[0],
VDEC_A_HUE_CTRL + (0x200 * decoder), val | value);
mutex_unlock(&dev->lock);
return ret_val;
}
int medusa_set_saturation(struct cx25821_dev *dev, int saturation, int decoder)
{
int ret_val = 0;
int value = 0;
u32 val = 0, tmp = 0;
mutex_lock(&dev->lock);
if ((saturation > VIDEO_PROCAMP_MAX) ||
(saturation < VIDEO_PROCAMP_MIN)) {
mutex_unlock(&dev->lock);
return -1;
}
ret_val = mapM(VIDEO_PROCAMP_MIN, VIDEO_PROCAMP_MAX, saturation,
UNSIGNED_BYTE_MIN, UNSIGNED_BYTE_MAX, &value);
val = cx25821_i2c_read(&dev->i2c_bus[0],
VDEC_A_USAT_CTRL + (0x200 * decoder), &tmp);
val &= 0xFFFFFF00;
ret_val |= cx25821_i2c_write(&dev->i2c_bus[0],
VDEC_A_USAT_CTRL + (0x200 * decoder), val | value);
val = cx25821_i2c_read(&dev->i2c_bus[0],
VDEC_A_VSAT_CTRL + (0x200 * decoder), &tmp);
val &= 0xFFFFFF00;
ret_val |= cx25821_i2c_write(&dev->i2c_bus[0],
VDEC_A_VSAT_CTRL + (0x200 * decoder), val | value);
mutex_unlock(&dev->lock);
return ret_val;
}
/* Program the display sequence and monitor output. */
int medusa_video_init(struct cx25821_dev *dev)
{
u32 value = 0, tmp = 0;
int ret_val = 0;
int i = 0;
mutex_lock(&dev->lock);
_num_decoders = dev->_max_num_decoders;
/* disable Auto source selection on all video decoders */
value = cx25821_i2c_read(&dev->i2c_bus[0], MON_A_CTRL, &tmp);
value &= 0xFFFFF0FF;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0], MON_A_CTRL, value);
if (ret_val < 0)
goto error;
/* Turn off Master source switch enable */
value = cx25821_i2c_read(&dev->i2c_bus[0], MON_A_CTRL, &tmp);
value &= 0xFFFFFFDF;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0], MON_A_CTRL, value);
if (ret_val < 0)
goto error;
mutex_unlock(&dev->lock);
for (i = 0; i < _num_decoders; i++)
medusa_set_decoderduration(dev, i, _display_field_cnt[i]);
mutex_lock(&dev->lock);
/* Select monitor as DENC A input, power up the DAC */
value = cx25821_i2c_read(&dev->i2c_bus[0], DENC_AB_CTRL, &tmp);
value &= 0xFF70FF70;
value |= 0x00090008; /* set en_active */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0], DENC_AB_CTRL, value);
if (ret_val < 0)
goto error;
/* enable input is VIP/656 */
value = cx25821_i2c_read(&dev->i2c_bus[0], BYP_AB_CTRL, &tmp);
value |= 0x00040100; /* enable VIP */
ret_val = cx25821_i2c_write(&dev->i2c_bus[0], BYP_AB_CTRL, value);
if (ret_val < 0)
goto error;
/* select AFE clock to output mode */
value = cx25821_i2c_read(&dev->i2c_bus[0], AFE_AB_DIAG_CTRL, &tmp);
value &= 0x83FFFFFF;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0], AFE_AB_DIAG_CTRL,
value | 0x10000000);
if (ret_val < 0)
goto error;
/* Turn on all of the data out and control output pins. */
value = cx25821_i2c_read(&dev->i2c_bus[0], PIN_OE_CTRL, &tmp);
value &= 0xFEF0FE00;
if (_num_decoders == MAX_DECODERS) {
/*
* Note: The octal board does not support control pins(bit16-19)
* These bits are ignored in the octal board.
*
* disable VDEC A-C port, default to Mobilygen Interface
*/
value |= 0x010001F8;
} else {
/* disable VDEC A-C port, default to Mobilygen Interface */
value |= 0x010F0108;
}
value |= 7;
ret_val = cx25821_i2c_write(&dev->i2c_bus[0], PIN_OE_CTRL, value);
if (ret_val < 0)
goto error;
mutex_unlock(&dev->lock);
ret_val = medusa_set_videostandard(dev);
return ret_val;
error:
mutex_unlock(&dev->lock);
return ret_val;
}
| gpl-2.0 |
NoelMacwan/SXDNickiMallow | drivers/media/video/c-qcam.c | 4902 | 21425 | /*
* Video4Linux Colour QuickCam driver
* Copyright 1997-2000 Philip Blundell <philb@gnu.org>
*
* Module parameters:
*
* parport=auto -- probe all parports (default)
* parport=0 -- parport0 becomes qcam1
* parport=2,0,1 -- parports 2,0,1 are tried in that order
*
* probe=0 -- do no probing, assume camera is present
* probe=1 -- use IEEE-1284 autoprobe data only (default)
* probe=2 -- probe aggressively for cameras
*
* force_rgb=1 -- force data format to RGB (default is BGR)
*
* The parport parameter controls which parports will be scanned.
* Scanning all parports causes some printers to print a garbage page.
* -- March 14, 1999 Billy Donahue <billy@escape.com>
*
* Fixed data format to BGR, added force_rgb parameter. Added missing
* parport_unregister_driver() on module removal.
* -- May 28, 2000 Claudio Matsuoka <claudio@conectiva.com>
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/parport.h>
#include <linux/sched.h>
#include <linux/mutex.h>
#include <linux/jiffies.h>
#include <linux/videodev2.h>
#include <asm/uaccess.h>
#include <media/v4l2-device.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
struct qcam {
struct v4l2_device v4l2_dev;
struct video_device vdev;
struct pardevice *pdev;
struct parport *pport;
int width, height;
int ccd_width, ccd_height;
int mode;
int contrast, brightness, whitebal;
int top, left;
unsigned int bidirectional;
struct mutex lock;
};
/* cameras maximum */
#define MAX_CAMS 4
/* The three possible QuickCam modes */
#define QC_MILLIONS 0x18
#define QC_BILLIONS 0x10
#define QC_THOUSANDS 0x08 /* with VIDEC compression (not supported) */
/* The three possible decimations */
#define QC_DECIMATION_1 0
#define QC_DECIMATION_2 2
#define QC_DECIMATION_4 4
#define BANNER "Colour QuickCam for Video4Linux v0.06"
static int parport[MAX_CAMS] = { [1 ... MAX_CAMS-1] = -1 };
static int probe = 2;
static bool force_rgb;
static int video_nr = -1;
/* FIXME: parport=auto would never have worked, surely? --RR */
MODULE_PARM_DESC(parport, "parport=<auto|n[,n]...> for port detection method\n"
"probe=<0|1|2> for camera detection method\n"
"force_rgb=<0|1> for RGB data format (default BGR)");
module_param_array(parport, int, NULL, 0);
module_param(probe, int, 0);
module_param(force_rgb, bool, 0);
module_param(video_nr, int, 0);
static struct qcam *qcams[MAX_CAMS];
static unsigned int num_cams;
static inline void qcam_set_ack(struct qcam *qcam, unsigned int i)
{
/* note: the QC specs refer to the PCAck pin by voltage, not
software level. PC ports have builtin inverters. */
parport_frob_control(qcam->pport, 8, i ? 8 : 0);
}
static inline unsigned int qcam_ready1(struct qcam *qcam)
{
return (parport_read_status(qcam->pport) & 0x8) ? 1 : 0;
}
static inline unsigned int qcam_ready2(struct qcam *qcam)
{
return (parport_read_data(qcam->pport) & 0x1) ? 1 : 0;
}
static unsigned int qcam_await_ready1(struct qcam *qcam, int value)
{
struct v4l2_device *v4l2_dev = &qcam->v4l2_dev;
unsigned long oldjiffies = jiffies;
unsigned int i;
for (oldjiffies = jiffies;
time_before(jiffies, oldjiffies + msecs_to_jiffies(40));)
if (qcam_ready1(qcam) == value)
return 0;
/* If the camera didn't respond within 1/25 second, poll slowly
for a while. */
for (i = 0; i < 50; i++) {
if (qcam_ready1(qcam) == value)
return 0;
msleep_interruptible(100);
}
/* Probably somebody pulled the plug out. Not much we can do. */
v4l2_err(v4l2_dev, "ready1 timeout (%d) %x %x\n", value,
parport_read_status(qcam->pport),
parport_read_control(qcam->pport));
return 1;
}
static unsigned int qcam_await_ready2(struct qcam *qcam, int value)
{
struct v4l2_device *v4l2_dev = &qcam->v4l2_dev;
unsigned long oldjiffies = jiffies;
unsigned int i;
for (oldjiffies = jiffies;
time_before(jiffies, oldjiffies + msecs_to_jiffies(40));)
if (qcam_ready2(qcam) == value)
return 0;
/* If the camera didn't respond within 1/25 second, poll slowly
for a while. */
for (i = 0; i < 50; i++) {
if (qcam_ready2(qcam) == value)
return 0;
msleep_interruptible(100);
}
/* Probably somebody pulled the plug out. Not much we can do. */
v4l2_err(v4l2_dev, "ready2 timeout (%d) %x %x %x\n", value,
parport_read_status(qcam->pport),
parport_read_control(qcam->pport),
parport_read_data(qcam->pport));
return 1;
}
static int qcam_read_data(struct qcam *qcam)
{
unsigned int idata;
qcam_set_ack(qcam, 0);
if (qcam_await_ready1(qcam, 1))
return -1;
idata = parport_read_status(qcam->pport) & 0xf0;
qcam_set_ack(qcam, 1);
if (qcam_await_ready1(qcam, 0))
return -1;
idata |= parport_read_status(qcam->pport) >> 4;
return idata;
}
static int qcam_write_data(struct qcam *qcam, unsigned int data)
{
struct v4l2_device *v4l2_dev = &qcam->v4l2_dev;
unsigned int idata;
parport_write_data(qcam->pport, data);
idata = qcam_read_data(qcam);
if (data != idata) {
v4l2_warn(v4l2_dev, "sent %x but received %x\n", data,
idata);
return 1;
}
return 0;
}
static inline int qcam_set(struct qcam *qcam, unsigned int cmd, unsigned int data)
{
if (qcam_write_data(qcam, cmd))
return -1;
if (qcam_write_data(qcam, data))
return -1;
return 0;
}
static inline int qcam_get(struct qcam *qcam, unsigned int cmd)
{
if (qcam_write_data(qcam, cmd))
return -1;
return qcam_read_data(qcam);
}
static int qc_detect(struct qcam *qcam)
{
unsigned int stat, ostat, i, count = 0;
/* The probe routine below is not very reliable. The IEEE-1284
probe takes precedence. */
/* XXX Currently parport provides no way to distinguish between
"the IEEE probe was not done" and "the probe was done, but
no device was found". Fix this one day. */
if (qcam->pport->probe_info[0].class == PARPORT_CLASS_MEDIA
&& qcam->pport->probe_info[0].model
&& !strcmp(qcam->pdev->port->probe_info[0].model,
"Color QuickCam 2.0")) {
printk(KERN_DEBUG "QuickCam: Found by IEEE1284 probe.\n");
return 1;
}
if (probe < 2)
return 0;
parport_write_control(qcam->pport, 0xc);
/* look for a heartbeat */
ostat = stat = parport_read_status(qcam->pport);
for (i = 0; i < 250; i++) {
mdelay(1);
stat = parport_read_status(qcam->pport);
if (ostat != stat) {
if (++count >= 3)
return 1;
ostat = stat;
}
}
/* Reset the camera and try again */
parport_write_control(qcam->pport, 0xc);
parport_write_control(qcam->pport, 0x8);
mdelay(1);
parport_write_control(qcam->pport, 0xc);
mdelay(1);
count = 0;
ostat = stat = parport_read_status(qcam->pport);
for (i = 0; i < 250; i++) {
mdelay(1);
stat = parport_read_status(qcam->pport);
if (ostat != stat) {
if (++count >= 3)
return 1;
ostat = stat;
}
}
/* no (or flatline) camera, give up */
return 0;
}
static void qc_reset(struct qcam *qcam)
{
parport_write_control(qcam->pport, 0xc);
parport_write_control(qcam->pport, 0x8);
mdelay(1);
parport_write_control(qcam->pport, 0xc);
mdelay(1);
}
/* Reset the QuickCam and program for brightness, contrast,
* white-balance, and resolution. */
static void qc_setup(struct qcam *qcam)
{
qc_reset(qcam);
/* Set the brightness. */
qcam_set(qcam, 11, qcam->brightness);
/* Set the height and width. These refer to the actual
CCD area *before* applying the selected decimation. */
qcam_set(qcam, 17, qcam->ccd_height);
qcam_set(qcam, 19, qcam->ccd_width / 2);
/* Set top and left. */
qcam_set(qcam, 0xd, qcam->top);
qcam_set(qcam, 0xf, qcam->left);
/* Set contrast and white balance. */
qcam_set(qcam, 0x19, qcam->contrast);
qcam_set(qcam, 0x1f, qcam->whitebal);
/* Set the speed. */
qcam_set(qcam, 45, 2);
}
/* Read some bytes from the camera and put them in the buffer.
nbytes should be a multiple of 3, because bidirectional mode gives
us three bytes at a time. */
static unsigned int qcam_read_bytes(struct qcam *qcam, unsigned char *buf, unsigned int nbytes)
{
unsigned int bytes = 0;
qcam_set_ack(qcam, 0);
if (qcam->bidirectional) {
/* It's a bidirectional port */
while (bytes < nbytes) {
unsigned int lo1, hi1, lo2, hi2;
unsigned char r, g, b;
if (qcam_await_ready2(qcam, 1))
return bytes;
lo1 = parport_read_data(qcam->pport) >> 1;
hi1 = ((parport_read_status(qcam->pport) >> 3) & 0x1f) ^ 0x10;
qcam_set_ack(qcam, 1);
if (qcam_await_ready2(qcam, 0))
return bytes;
lo2 = parport_read_data(qcam->pport) >> 1;
hi2 = ((parport_read_status(qcam->pport) >> 3) & 0x1f) ^ 0x10;
qcam_set_ack(qcam, 0);
r = lo1 | ((hi1 & 1) << 7);
g = ((hi1 & 0x1e) << 3) | ((hi2 & 0x1e) >> 1);
b = lo2 | ((hi2 & 1) << 7);
if (force_rgb) {
buf[bytes++] = r;
buf[bytes++] = g;
buf[bytes++] = b;
} else {
buf[bytes++] = b;
buf[bytes++] = g;
buf[bytes++] = r;
}
}
} else {
/* It's a unidirectional port */
int i = 0, n = bytes;
unsigned char rgb[3];
while (bytes < nbytes) {
unsigned int hi, lo;
if (qcam_await_ready1(qcam, 1))
return bytes;
hi = (parport_read_status(qcam->pport) & 0xf0);
qcam_set_ack(qcam, 1);
if (qcam_await_ready1(qcam, 0))
return bytes;
lo = (parport_read_status(qcam->pport) & 0xf0);
qcam_set_ack(qcam, 0);
/* flip some bits */
rgb[(i = bytes++ % 3)] = (hi | (lo >> 4)) ^ 0x88;
if (i >= 2) {
get_fragment:
if (force_rgb) {
buf[n++] = rgb[0];
buf[n++] = rgb[1];
buf[n++] = rgb[2];
} else {
buf[n++] = rgb[2];
buf[n++] = rgb[1];
buf[n++] = rgb[0];
}
}
}
if (i) {
i = 0;
goto get_fragment;
}
}
return bytes;
}
#define BUFSZ 150
static long qc_capture(struct qcam *qcam, char __user *buf, unsigned long len)
{
struct v4l2_device *v4l2_dev = &qcam->v4l2_dev;
unsigned lines, pixelsperline, bitsperxfer;
unsigned int is_bi_dir = qcam->bidirectional;
size_t wantlen, outptr = 0;
char tmpbuf[BUFSZ];
if (!access_ok(VERIFY_WRITE, buf, len))
return -EFAULT;
/* Wait for camera to become ready */
for (;;) {
int i = qcam_get(qcam, 41);
if (i == -1) {
qc_setup(qcam);
return -EIO;
}
if ((i & 0x80) == 0)
break;
schedule();
}
if (qcam_set(qcam, 7, (qcam->mode | (is_bi_dir ? 1 : 0)) + 1))
return -EIO;
lines = qcam->height;
pixelsperline = qcam->width;
bitsperxfer = (is_bi_dir) ? 24 : 8;
if (is_bi_dir) {
/* Turn the port around */
parport_data_reverse(qcam->pport);
mdelay(3);
qcam_set_ack(qcam, 0);
if (qcam_await_ready1(qcam, 1)) {
qc_setup(qcam);
return -EIO;
}
qcam_set_ack(qcam, 1);
if (qcam_await_ready1(qcam, 0)) {
qc_setup(qcam);
return -EIO;
}
}
wantlen = lines * pixelsperline * 24 / 8;
while (wantlen) {
size_t t, s;
s = (wantlen > BUFSZ) ? BUFSZ : wantlen;
t = qcam_read_bytes(qcam, tmpbuf, s);
if (outptr < len) {
size_t sz = len - outptr;
if (sz > t)
sz = t;
if (__copy_to_user(buf + outptr, tmpbuf, sz))
break;
outptr += sz;
}
wantlen -= t;
if (t < s)
break;
cond_resched();
}
len = outptr;
if (wantlen) {
v4l2_err(v4l2_dev, "short read.\n");
if (is_bi_dir)
parport_data_forward(qcam->pport);
qc_setup(qcam);
return len;
}
if (is_bi_dir) {
int l;
do {
l = qcam_read_bytes(qcam, tmpbuf, 3);
cond_resched();
} while (l && (tmpbuf[0] == 0x7e || tmpbuf[1] == 0x7e || tmpbuf[2] == 0x7e));
if (force_rgb) {
if (tmpbuf[0] != 0xe || tmpbuf[1] != 0x0 || tmpbuf[2] != 0xf)
v4l2_err(v4l2_dev, "bad EOF\n");
} else {
if (tmpbuf[0] != 0xf || tmpbuf[1] != 0x0 || tmpbuf[2] != 0xe)
v4l2_err(v4l2_dev, "bad EOF\n");
}
qcam_set_ack(qcam, 0);
if (qcam_await_ready1(qcam, 1)) {
v4l2_err(v4l2_dev, "no ack after EOF\n");
parport_data_forward(qcam->pport);
qc_setup(qcam);
return len;
}
parport_data_forward(qcam->pport);
mdelay(3);
qcam_set_ack(qcam, 1);
if (qcam_await_ready1(qcam, 0)) {
v4l2_err(v4l2_dev, "no ack to port turnaround\n");
qc_setup(qcam);
return len;
}
} else {
int l;
do {
l = qcam_read_bytes(qcam, tmpbuf, 1);
cond_resched();
} while (l && tmpbuf[0] == 0x7e);
l = qcam_read_bytes(qcam, tmpbuf + 1, 2);
if (force_rgb) {
if (tmpbuf[0] != 0xe || tmpbuf[1] != 0x0 || tmpbuf[2] != 0xf)
v4l2_err(v4l2_dev, "bad EOF\n");
} else {
if (tmpbuf[0] != 0xf || tmpbuf[1] != 0x0 || tmpbuf[2] != 0xe)
v4l2_err(v4l2_dev, "bad EOF\n");
}
}
qcam_write_data(qcam, 0);
return len;
}
/*
* Video4linux interfacing
*/
static int qcam_querycap(struct file *file, void *priv,
struct v4l2_capability *vcap)
{
struct qcam *qcam = video_drvdata(file);
strlcpy(vcap->driver, qcam->v4l2_dev.name, sizeof(vcap->driver));
strlcpy(vcap->card, "Color Quickcam", sizeof(vcap->card));
strlcpy(vcap->bus_info, "parport", sizeof(vcap->bus_info));
vcap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE;
return 0;
}
static int qcam_enum_input(struct file *file, void *fh, struct v4l2_input *vin)
{
if (vin->index > 0)
return -EINVAL;
strlcpy(vin->name, "Camera", sizeof(vin->name));
vin->type = V4L2_INPUT_TYPE_CAMERA;
vin->audioset = 0;
vin->tuner = 0;
vin->std = 0;
vin->status = 0;
return 0;
}
static int qcam_g_input(struct file *file, void *fh, unsigned int *inp)
{
*inp = 0;
return 0;
}
static int qcam_s_input(struct file *file, void *fh, unsigned int inp)
{
return (inp > 0) ? -EINVAL : 0;
}
static int qcam_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
switch (qc->id) {
case V4L2_CID_BRIGHTNESS:
return v4l2_ctrl_query_fill(qc, 0, 255, 1, 240);
case V4L2_CID_CONTRAST:
return v4l2_ctrl_query_fill(qc, 0, 255, 1, 192);
case V4L2_CID_GAMMA:
return v4l2_ctrl_query_fill(qc, 0, 255, 1, 128);
}
return -EINVAL;
}
static int qcam_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct qcam *qcam = video_drvdata(file);
int ret = 0;
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
ctrl->value = qcam->brightness;
break;
case V4L2_CID_CONTRAST:
ctrl->value = qcam->contrast;
break;
case V4L2_CID_GAMMA:
ctrl->value = qcam->whitebal;
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static int qcam_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct qcam *qcam = video_drvdata(file);
int ret = 0;
mutex_lock(&qcam->lock);
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
qcam->brightness = ctrl->value;
break;
case V4L2_CID_CONTRAST:
qcam->contrast = ctrl->value;
break;
case V4L2_CID_GAMMA:
qcam->whitebal = ctrl->value;
break;
default:
ret = -EINVAL;
break;
}
if (ret == 0) {
parport_claim_or_block(qcam->pdev);
qc_setup(qcam);
parport_release(qcam->pdev);
}
mutex_unlock(&qcam->lock);
return ret;
}
static int qcam_g_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct qcam *qcam = video_drvdata(file);
struct v4l2_pix_format *pix = &fmt->fmt.pix;
pix->width = qcam->width;
pix->height = qcam->height;
pix->pixelformat = V4L2_PIX_FMT_RGB24;
pix->field = V4L2_FIELD_NONE;
pix->bytesperline = 3 * qcam->width;
pix->sizeimage = 3 * qcam->width * qcam->height;
/* Just a guess */
pix->colorspace = V4L2_COLORSPACE_SRGB;
return 0;
}
static int qcam_try_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct v4l2_pix_format *pix = &fmt->fmt.pix;
if (pix->height < 60 || pix->width < 80) {
pix->height = 60;
pix->width = 80;
} else if (pix->height < 120 || pix->width < 160) {
pix->height = 120;
pix->width = 160;
} else {
pix->height = 240;
pix->width = 320;
}
pix->pixelformat = V4L2_PIX_FMT_RGB24;
pix->field = V4L2_FIELD_NONE;
pix->bytesperline = 3 * pix->width;
pix->sizeimage = 3 * pix->width * pix->height;
/* Just a guess */
pix->colorspace = V4L2_COLORSPACE_SRGB;
return 0;
}
static int qcam_s_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct qcam *qcam = video_drvdata(file);
struct v4l2_pix_format *pix = &fmt->fmt.pix;
int ret = qcam_try_fmt_vid_cap(file, fh, fmt);
if (ret)
return ret;
switch (pix->height) {
case 60:
qcam->mode = QC_DECIMATION_4;
break;
case 120:
qcam->mode = QC_DECIMATION_2;
break;
default:
qcam->mode = QC_DECIMATION_1;
break;
}
mutex_lock(&qcam->lock);
qcam->mode |= QC_MILLIONS;
qcam->height = pix->height;
qcam->width = pix->width;
parport_claim_or_block(qcam->pdev);
qc_setup(qcam);
parport_release(qcam->pdev);
mutex_unlock(&qcam->lock);
return 0;
}
static int qcam_enum_fmt_vid_cap(struct file *file, void *fh, struct v4l2_fmtdesc *fmt)
{
static struct v4l2_fmtdesc formats[] = {
{ 0, 0, 0,
"RGB 8:8:8", V4L2_PIX_FMT_RGB24,
{ 0, 0, 0, 0 }
},
};
enum v4l2_buf_type type = fmt->type;
if (fmt->index > 0)
return -EINVAL;
*fmt = formats[fmt->index];
fmt->type = type;
return 0;
}
static ssize_t qcam_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct qcam *qcam = video_drvdata(file);
int len;
mutex_lock(&qcam->lock);
parport_claim_or_block(qcam->pdev);
/* Probably should have a semaphore against multiple users */
len = qc_capture(qcam, buf, count);
parport_release(qcam->pdev);
mutex_unlock(&qcam->lock);
return len;
}
static const struct v4l2_file_operations qcam_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = video_ioctl2,
.read = qcam_read,
};
static const struct v4l2_ioctl_ops qcam_ioctl_ops = {
.vidioc_querycap = qcam_querycap,
.vidioc_g_input = qcam_g_input,
.vidioc_s_input = qcam_s_input,
.vidioc_enum_input = qcam_enum_input,
.vidioc_queryctrl = qcam_queryctrl,
.vidioc_g_ctrl = qcam_g_ctrl,
.vidioc_s_ctrl = qcam_s_ctrl,
.vidioc_enum_fmt_vid_cap = qcam_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = qcam_g_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = qcam_s_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = qcam_try_fmt_vid_cap,
};
/* Initialize the QuickCam driver control structure. */
static struct qcam *qcam_init(struct parport *port)
{
struct qcam *qcam;
struct v4l2_device *v4l2_dev;
qcam = kzalloc(sizeof(*qcam), GFP_KERNEL);
if (qcam == NULL)
return NULL;
v4l2_dev = &qcam->v4l2_dev;
strlcpy(v4l2_dev->name, "c-qcam", sizeof(v4l2_dev->name));
if (v4l2_device_register(NULL, v4l2_dev) < 0) {
v4l2_err(v4l2_dev, "Could not register v4l2_device\n");
kfree(qcam);
return NULL;
}
qcam->pport = port;
qcam->pdev = parport_register_device(port, "c-qcam", NULL, NULL,
NULL, 0, NULL);
qcam->bidirectional = (qcam->pport->modes & PARPORT_MODE_TRISTATE) ? 1 : 0;
if (qcam->pdev == NULL) {
v4l2_err(v4l2_dev, "couldn't register for %s.\n", port->name);
kfree(qcam);
return NULL;
}
strlcpy(qcam->vdev.name, "Colour QuickCam", sizeof(qcam->vdev.name));
qcam->vdev.v4l2_dev = v4l2_dev;
qcam->vdev.fops = &qcam_fops;
qcam->vdev.ioctl_ops = &qcam_ioctl_ops;
qcam->vdev.release = video_device_release_empty;
video_set_drvdata(&qcam->vdev, qcam);
mutex_init(&qcam->lock);
qcam->width = qcam->ccd_width = 320;
qcam->height = qcam->ccd_height = 240;
qcam->mode = QC_MILLIONS | QC_DECIMATION_1;
qcam->contrast = 192;
qcam->brightness = 240;
qcam->whitebal = 128;
qcam->top = 1;
qcam->left = 14;
return qcam;
}
static int init_cqcam(struct parport *port)
{
struct qcam *qcam;
struct v4l2_device *v4l2_dev;
if (parport[0] != -1) {
/* The user gave specific instructions */
int i, found = 0;
for (i = 0; i < MAX_CAMS && parport[i] != -1; i++) {
if (parport[0] == port->number)
found = 1;
}
if (!found)
return -ENODEV;
}
if (num_cams == MAX_CAMS)
return -ENOSPC;
qcam = qcam_init(port);
if (qcam == NULL)
return -ENODEV;
v4l2_dev = &qcam->v4l2_dev;
parport_claim_or_block(qcam->pdev);
qc_reset(qcam);
if (probe && qc_detect(qcam) == 0) {
parport_release(qcam->pdev);
parport_unregister_device(qcam->pdev);
kfree(qcam);
return -ENODEV;
}
qc_setup(qcam);
parport_release(qcam->pdev);
if (video_register_device(&qcam->vdev, VFL_TYPE_GRABBER, video_nr) < 0) {
v4l2_err(v4l2_dev, "Unable to register Colour QuickCam on %s\n",
qcam->pport->name);
parport_unregister_device(qcam->pdev);
kfree(qcam);
return -ENODEV;
}
v4l2_info(v4l2_dev, "%s: Colour QuickCam found on %s\n",
video_device_node_name(&qcam->vdev), qcam->pport->name);
qcams[num_cams++] = qcam;
return 0;
}
static void close_cqcam(struct qcam *qcam)
{
video_unregister_device(&qcam->vdev);
parport_unregister_device(qcam->pdev);
kfree(qcam);
}
static void cq_attach(struct parport *port)
{
init_cqcam(port);
}
static void cq_detach(struct parport *port)
{
/* Write this some day. */
}
static struct parport_driver cqcam_driver = {
.name = "cqcam",
.attach = cq_attach,
.detach = cq_detach,
};
static int __init cqcam_init(void)
{
printk(KERN_INFO BANNER "\n");
return parport_register_driver(&cqcam_driver);
}
static void __exit cqcam_cleanup(void)
{
unsigned int i;
for (i = 0; i < num_cams; i++)
close_cqcam(qcams[i]);
parport_unregister_driver(&cqcam_driver);
}
MODULE_AUTHOR("Philip Blundell <philb@gnu.org>");
MODULE_DESCRIPTION(BANNER);
MODULE_LICENSE("GPL");
MODULE_VERSION("0.0.4");
module_init(cqcam_init);
module_exit(cqcam_cleanup);
| gpl-2.0 |
MI2S/android_kernel_xiaomi_aries | drivers/media/video/c-qcam.c | 4902 | 21425 | /*
* Video4Linux Colour QuickCam driver
* Copyright 1997-2000 Philip Blundell <philb@gnu.org>
*
* Module parameters:
*
* parport=auto -- probe all parports (default)
* parport=0 -- parport0 becomes qcam1
* parport=2,0,1 -- parports 2,0,1 are tried in that order
*
* probe=0 -- do no probing, assume camera is present
* probe=1 -- use IEEE-1284 autoprobe data only (default)
* probe=2 -- probe aggressively for cameras
*
* force_rgb=1 -- force data format to RGB (default is BGR)
*
* The parport parameter controls which parports will be scanned.
* Scanning all parports causes some printers to print a garbage page.
* -- March 14, 1999 Billy Donahue <billy@escape.com>
*
* Fixed data format to BGR, added force_rgb parameter. Added missing
* parport_unregister_driver() on module removal.
* -- May 28, 2000 Claudio Matsuoka <claudio@conectiva.com>
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/parport.h>
#include <linux/sched.h>
#include <linux/mutex.h>
#include <linux/jiffies.h>
#include <linux/videodev2.h>
#include <asm/uaccess.h>
#include <media/v4l2-device.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
struct qcam {
struct v4l2_device v4l2_dev;
struct video_device vdev;
struct pardevice *pdev;
struct parport *pport;
int width, height;
int ccd_width, ccd_height;
int mode;
int contrast, brightness, whitebal;
int top, left;
unsigned int bidirectional;
struct mutex lock;
};
/* cameras maximum */
#define MAX_CAMS 4
/* The three possible QuickCam modes */
#define QC_MILLIONS 0x18
#define QC_BILLIONS 0x10
#define QC_THOUSANDS 0x08 /* with VIDEC compression (not supported) */
/* The three possible decimations */
#define QC_DECIMATION_1 0
#define QC_DECIMATION_2 2
#define QC_DECIMATION_4 4
#define BANNER "Colour QuickCam for Video4Linux v0.06"
static int parport[MAX_CAMS] = { [1 ... MAX_CAMS-1] = -1 };
static int probe = 2;
static bool force_rgb;
static int video_nr = -1;
/* FIXME: parport=auto would never have worked, surely? --RR */
MODULE_PARM_DESC(parport, "parport=<auto|n[,n]...> for port detection method\n"
"probe=<0|1|2> for camera detection method\n"
"force_rgb=<0|1> for RGB data format (default BGR)");
module_param_array(parport, int, NULL, 0);
module_param(probe, int, 0);
module_param(force_rgb, bool, 0);
module_param(video_nr, int, 0);
static struct qcam *qcams[MAX_CAMS];
static unsigned int num_cams;
static inline void qcam_set_ack(struct qcam *qcam, unsigned int i)
{
/* note: the QC specs refer to the PCAck pin by voltage, not
software level. PC ports have builtin inverters. */
parport_frob_control(qcam->pport, 8, i ? 8 : 0);
}
static inline unsigned int qcam_ready1(struct qcam *qcam)
{
return (parport_read_status(qcam->pport) & 0x8) ? 1 : 0;
}
static inline unsigned int qcam_ready2(struct qcam *qcam)
{
return (parport_read_data(qcam->pport) & 0x1) ? 1 : 0;
}
static unsigned int qcam_await_ready1(struct qcam *qcam, int value)
{
struct v4l2_device *v4l2_dev = &qcam->v4l2_dev;
unsigned long oldjiffies = jiffies;
unsigned int i;
for (oldjiffies = jiffies;
time_before(jiffies, oldjiffies + msecs_to_jiffies(40));)
if (qcam_ready1(qcam) == value)
return 0;
/* If the camera didn't respond within 1/25 second, poll slowly
for a while. */
for (i = 0; i < 50; i++) {
if (qcam_ready1(qcam) == value)
return 0;
msleep_interruptible(100);
}
/* Probably somebody pulled the plug out. Not much we can do. */
v4l2_err(v4l2_dev, "ready1 timeout (%d) %x %x\n", value,
parport_read_status(qcam->pport),
parport_read_control(qcam->pport));
return 1;
}
static unsigned int qcam_await_ready2(struct qcam *qcam, int value)
{
struct v4l2_device *v4l2_dev = &qcam->v4l2_dev;
unsigned long oldjiffies = jiffies;
unsigned int i;
for (oldjiffies = jiffies;
time_before(jiffies, oldjiffies + msecs_to_jiffies(40));)
if (qcam_ready2(qcam) == value)
return 0;
/* If the camera didn't respond within 1/25 second, poll slowly
for a while. */
for (i = 0; i < 50; i++) {
if (qcam_ready2(qcam) == value)
return 0;
msleep_interruptible(100);
}
/* Probably somebody pulled the plug out. Not much we can do. */
v4l2_err(v4l2_dev, "ready2 timeout (%d) %x %x %x\n", value,
parport_read_status(qcam->pport),
parport_read_control(qcam->pport),
parport_read_data(qcam->pport));
return 1;
}
static int qcam_read_data(struct qcam *qcam)
{
unsigned int idata;
qcam_set_ack(qcam, 0);
if (qcam_await_ready1(qcam, 1))
return -1;
idata = parport_read_status(qcam->pport) & 0xf0;
qcam_set_ack(qcam, 1);
if (qcam_await_ready1(qcam, 0))
return -1;
idata |= parport_read_status(qcam->pport) >> 4;
return idata;
}
static int qcam_write_data(struct qcam *qcam, unsigned int data)
{
struct v4l2_device *v4l2_dev = &qcam->v4l2_dev;
unsigned int idata;
parport_write_data(qcam->pport, data);
idata = qcam_read_data(qcam);
if (data != idata) {
v4l2_warn(v4l2_dev, "sent %x but received %x\n", data,
idata);
return 1;
}
return 0;
}
static inline int qcam_set(struct qcam *qcam, unsigned int cmd, unsigned int data)
{
if (qcam_write_data(qcam, cmd))
return -1;
if (qcam_write_data(qcam, data))
return -1;
return 0;
}
static inline int qcam_get(struct qcam *qcam, unsigned int cmd)
{
if (qcam_write_data(qcam, cmd))
return -1;
return qcam_read_data(qcam);
}
static int qc_detect(struct qcam *qcam)
{
unsigned int stat, ostat, i, count = 0;
/* The probe routine below is not very reliable. The IEEE-1284
probe takes precedence. */
/* XXX Currently parport provides no way to distinguish between
"the IEEE probe was not done" and "the probe was done, but
no device was found". Fix this one day. */
if (qcam->pport->probe_info[0].class == PARPORT_CLASS_MEDIA
&& qcam->pport->probe_info[0].model
&& !strcmp(qcam->pdev->port->probe_info[0].model,
"Color QuickCam 2.0")) {
printk(KERN_DEBUG "QuickCam: Found by IEEE1284 probe.\n");
return 1;
}
if (probe < 2)
return 0;
parport_write_control(qcam->pport, 0xc);
/* look for a heartbeat */
ostat = stat = parport_read_status(qcam->pport);
for (i = 0; i < 250; i++) {
mdelay(1);
stat = parport_read_status(qcam->pport);
if (ostat != stat) {
if (++count >= 3)
return 1;
ostat = stat;
}
}
/* Reset the camera and try again */
parport_write_control(qcam->pport, 0xc);
parport_write_control(qcam->pport, 0x8);
mdelay(1);
parport_write_control(qcam->pport, 0xc);
mdelay(1);
count = 0;
ostat = stat = parport_read_status(qcam->pport);
for (i = 0; i < 250; i++) {
mdelay(1);
stat = parport_read_status(qcam->pport);
if (ostat != stat) {
if (++count >= 3)
return 1;
ostat = stat;
}
}
/* no (or flatline) camera, give up */
return 0;
}
static void qc_reset(struct qcam *qcam)
{
parport_write_control(qcam->pport, 0xc);
parport_write_control(qcam->pport, 0x8);
mdelay(1);
parport_write_control(qcam->pport, 0xc);
mdelay(1);
}
/* Reset the QuickCam and program for brightness, contrast,
* white-balance, and resolution. */
static void qc_setup(struct qcam *qcam)
{
qc_reset(qcam);
/* Set the brightness. */
qcam_set(qcam, 11, qcam->brightness);
/* Set the height and width. These refer to the actual
CCD area *before* applying the selected decimation. */
qcam_set(qcam, 17, qcam->ccd_height);
qcam_set(qcam, 19, qcam->ccd_width / 2);
/* Set top and left. */
qcam_set(qcam, 0xd, qcam->top);
qcam_set(qcam, 0xf, qcam->left);
/* Set contrast and white balance. */
qcam_set(qcam, 0x19, qcam->contrast);
qcam_set(qcam, 0x1f, qcam->whitebal);
/* Set the speed. */
qcam_set(qcam, 45, 2);
}
/* Read some bytes from the camera and put them in the buffer.
nbytes should be a multiple of 3, because bidirectional mode gives
us three bytes at a time. */
static unsigned int qcam_read_bytes(struct qcam *qcam, unsigned char *buf, unsigned int nbytes)
{
unsigned int bytes = 0;
qcam_set_ack(qcam, 0);
if (qcam->bidirectional) {
/* It's a bidirectional port */
while (bytes < nbytes) {
unsigned int lo1, hi1, lo2, hi2;
unsigned char r, g, b;
if (qcam_await_ready2(qcam, 1))
return bytes;
lo1 = parport_read_data(qcam->pport) >> 1;
hi1 = ((parport_read_status(qcam->pport) >> 3) & 0x1f) ^ 0x10;
qcam_set_ack(qcam, 1);
if (qcam_await_ready2(qcam, 0))
return bytes;
lo2 = parport_read_data(qcam->pport) >> 1;
hi2 = ((parport_read_status(qcam->pport) >> 3) & 0x1f) ^ 0x10;
qcam_set_ack(qcam, 0);
r = lo1 | ((hi1 & 1) << 7);
g = ((hi1 & 0x1e) << 3) | ((hi2 & 0x1e) >> 1);
b = lo2 | ((hi2 & 1) << 7);
if (force_rgb) {
buf[bytes++] = r;
buf[bytes++] = g;
buf[bytes++] = b;
} else {
buf[bytes++] = b;
buf[bytes++] = g;
buf[bytes++] = r;
}
}
} else {
/* It's a unidirectional port */
int i = 0, n = bytes;
unsigned char rgb[3];
while (bytes < nbytes) {
unsigned int hi, lo;
if (qcam_await_ready1(qcam, 1))
return bytes;
hi = (parport_read_status(qcam->pport) & 0xf0);
qcam_set_ack(qcam, 1);
if (qcam_await_ready1(qcam, 0))
return bytes;
lo = (parport_read_status(qcam->pport) & 0xf0);
qcam_set_ack(qcam, 0);
/* flip some bits */
rgb[(i = bytes++ % 3)] = (hi | (lo >> 4)) ^ 0x88;
if (i >= 2) {
get_fragment:
if (force_rgb) {
buf[n++] = rgb[0];
buf[n++] = rgb[1];
buf[n++] = rgb[2];
} else {
buf[n++] = rgb[2];
buf[n++] = rgb[1];
buf[n++] = rgb[0];
}
}
}
if (i) {
i = 0;
goto get_fragment;
}
}
return bytes;
}
#define BUFSZ 150
static long qc_capture(struct qcam *qcam, char __user *buf, unsigned long len)
{
struct v4l2_device *v4l2_dev = &qcam->v4l2_dev;
unsigned lines, pixelsperline, bitsperxfer;
unsigned int is_bi_dir = qcam->bidirectional;
size_t wantlen, outptr = 0;
char tmpbuf[BUFSZ];
if (!access_ok(VERIFY_WRITE, buf, len))
return -EFAULT;
/* Wait for camera to become ready */
for (;;) {
int i = qcam_get(qcam, 41);
if (i == -1) {
qc_setup(qcam);
return -EIO;
}
if ((i & 0x80) == 0)
break;
schedule();
}
if (qcam_set(qcam, 7, (qcam->mode | (is_bi_dir ? 1 : 0)) + 1))
return -EIO;
lines = qcam->height;
pixelsperline = qcam->width;
bitsperxfer = (is_bi_dir) ? 24 : 8;
if (is_bi_dir) {
/* Turn the port around */
parport_data_reverse(qcam->pport);
mdelay(3);
qcam_set_ack(qcam, 0);
if (qcam_await_ready1(qcam, 1)) {
qc_setup(qcam);
return -EIO;
}
qcam_set_ack(qcam, 1);
if (qcam_await_ready1(qcam, 0)) {
qc_setup(qcam);
return -EIO;
}
}
wantlen = lines * pixelsperline * 24 / 8;
while (wantlen) {
size_t t, s;
s = (wantlen > BUFSZ) ? BUFSZ : wantlen;
t = qcam_read_bytes(qcam, tmpbuf, s);
if (outptr < len) {
size_t sz = len - outptr;
if (sz > t)
sz = t;
if (__copy_to_user(buf + outptr, tmpbuf, sz))
break;
outptr += sz;
}
wantlen -= t;
if (t < s)
break;
cond_resched();
}
len = outptr;
if (wantlen) {
v4l2_err(v4l2_dev, "short read.\n");
if (is_bi_dir)
parport_data_forward(qcam->pport);
qc_setup(qcam);
return len;
}
if (is_bi_dir) {
int l;
do {
l = qcam_read_bytes(qcam, tmpbuf, 3);
cond_resched();
} while (l && (tmpbuf[0] == 0x7e || tmpbuf[1] == 0x7e || tmpbuf[2] == 0x7e));
if (force_rgb) {
if (tmpbuf[0] != 0xe || tmpbuf[1] != 0x0 || tmpbuf[2] != 0xf)
v4l2_err(v4l2_dev, "bad EOF\n");
} else {
if (tmpbuf[0] != 0xf || tmpbuf[1] != 0x0 || tmpbuf[2] != 0xe)
v4l2_err(v4l2_dev, "bad EOF\n");
}
qcam_set_ack(qcam, 0);
if (qcam_await_ready1(qcam, 1)) {
v4l2_err(v4l2_dev, "no ack after EOF\n");
parport_data_forward(qcam->pport);
qc_setup(qcam);
return len;
}
parport_data_forward(qcam->pport);
mdelay(3);
qcam_set_ack(qcam, 1);
if (qcam_await_ready1(qcam, 0)) {
v4l2_err(v4l2_dev, "no ack to port turnaround\n");
qc_setup(qcam);
return len;
}
} else {
int l;
do {
l = qcam_read_bytes(qcam, tmpbuf, 1);
cond_resched();
} while (l && tmpbuf[0] == 0x7e);
l = qcam_read_bytes(qcam, tmpbuf + 1, 2);
if (force_rgb) {
if (tmpbuf[0] != 0xe || tmpbuf[1] != 0x0 || tmpbuf[2] != 0xf)
v4l2_err(v4l2_dev, "bad EOF\n");
} else {
if (tmpbuf[0] != 0xf || tmpbuf[1] != 0x0 || tmpbuf[2] != 0xe)
v4l2_err(v4l2_dev, "bad EOF\n");
}
}
qcam_write_data(qcam, 0);
return len;
}
/*
* Video4linux interfacing
*/
static int qcam_querycap(struct file *file, void *priv,
struct v4l2_capability *vcap)
{
struct qcam *qcam = video_drvdata(file);
strlcpy(vcap->driver, qcam->v4l2_dev.name, sizeof(vcap->driver));
strlcpy(vcap->card, "Color Quickcam", sizeof(vcap->card));
strlcpy(vcap->bus_info, "parport", sizeof(vcap->bus_info));
vcap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE;
return 0;
}
static int qcam_enum_input(struct file *file, void *fh, struct v4l2_input *vin)
{
if (vin->index > 0)
return -EINVAL;
strlcpy(vin->name, "Camera", sizeof(vin->name));
vin->type = V4L2_INPUT_TYPE_CAMERA;
vin->audioset = 0;
vin->tuner = 0;
vin->std = 0;
vin->status = 0;
return 0;
}
static int qcam_g_input(struct file *file, void *fh, unsigned int *inp)
{
*inp = 0;
return 0;
}
static int qcam_s_input(struct file *file, void *fh, unsigned int inp)
{
return (inp > 0) ? -EINVAL : 0;
}
static int qcam_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
switch (qc->id) {
case V4L2_CID_BRIGHTNESS:
return v4l2_ctrl_query_fill(qc, 0, 255, 1, 240);
case V4L2_CID_CONTRAST:
return v4l2_ctrl_query_fill(qc, 0, 255, 1, 192);
case V4L2_CID_GAMMA:
return v4l2_ctrl_query_fill(qc, 0, 255, 1, 128);
}
return -EINVAL;
}
static int qcam_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct qcam *qcam = video_drvdata(file);
int ret = 0;
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
ctrl->value = qcam->brightness;
break;
case V4L2_CID_CONTRAST:
ctrl->value = qcam->contrast;
break;
case V4L2_CID_GAMMA:
ctrl->value = qcam->whitebal;
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static int qcam_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct qcam *qcam = video_drvdata(file);
int ret = 0;
mutex_lock(&qcam->lock);
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
qcam->brightness = ctrl->value;
break;
case V4L2_CID_CONTRAST:
qcam->contrast = ctrl->value;
break;
case V4L2_CID_GAMMA:
qcam->whitebal = ctrl->value;
break;
default:
ret = -EINVAL;
break;
}
if (ret == 0) {
parport_claim_or_block(qcam->pdev);
qc_setup(qcam);
parport_release(qcam->pdev);
}
mutex_unlock(&qcam->lock);
return ret;
}
static int qcam_g_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct qcam *qcam = video_drvdata(file);
struct v4l2_pix_format *pix = &fmt->fmt.pix;
pix->width = qcam->width;
pix->height = qcam->height;
pix->pixelformat = V4L2_PIX_FMT_RGB24;
pix->field = V4L2_FIELD_NONE;
pix->bytesperline = 3 * qcam->width;
pix->sizeimage = 3 * qcam->width * qcam->height;
/* Just a guess */
pix->colorspace = V4L2_COLORSPACE_SRGB;
return 0;
}
static int qcam_try_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct v4l2_pix_format *pix = &fmt->fmt.pix;
if (pix->height < 60 || pix->width < 80) {
pix->height = 60;
pix->width = 80;
} else if (pix->height < 120 || pix->width < 160) {
pix->height = 120;
pix->width = 160;
} else {
pix->height = 240;
pix->width = 320;
}
pix->pixelformat = V4L2_PIX_FMT_RGB24;
pix->field = V4L2_FIELD_NONE;
pix->bytesperline = 3 * pix->width;
pix->sizeimage = 3 * pix->width * pix->height;
/* Just a guess */
pix->colorspace = V4L2_COLORSPACE_SRGB;
return 0;
}
static int qcam_s_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct qcam *qcam = video_drvdata(file);
struct v4l2_pix_format *pix = &fmt->fmt.pix;
int ret = qcam_try_fmt_vid_cap(file, fh, fmt);
if (ret)
return ret;
switch (pix->height) {
case 60:
qcam->mode = QC_DECIMATION_4;
break;
case 120:
qcam->mode = QC_DECIMATION_2;
break;
default:
qcam->mode = QC_DECIMATION_1;
break;
}
mutex_lock(&qcam->lock);
qcam->mode |= QC_MILLIONS;
qcam->height = pix->height;
qcam->width = pix->width;
parport_claim_or_block(qcam->pdev);
qc_setup(qcam);
parport_release(qcam->pdev);
mutex_unlock(&qcam->lock);
return 0;
}
static int qcam_enum_fmt_vid_cap(struct file *file, void *fh, struct v4l2_fmtdesc *fmt)
{
static struct v4l2_fmtdesc formats[] = {
{ 0, 0, 0,
"RGB 8:8:8", V4L2_PIX_FMT_RGB24,
{ 0, 0, 0, 0 }
},
};
enum v4l2_buf_type type = fmt->type;
if (fmt->index > 0)
return -EINVAL;
*fmt = formats[fmt->index];
fmt->type = type;
return 0;
}
static ssize_t qcam_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct qcam *qcam = video_drvdata(file);
int len;
mutex_lock(&qcam->lock);
parport_claim_or_block(qcam->pdev);
/* Probably should have a semaphore against multiple users */
len = qc_capture(qcam, buf, count);
parport_release(qcam->pdev);
mutex_unlock(&qcam->lock);
return len;
}
static const struct v4l2_file_operations qcam_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = video_ioctl2,
.read = qcam_read,
};
static const struct v4l2_ioctl_ops qcam_ioctl_ops = {
.vidioc_querycap = qcam_querycap,
.vidioc_g_input = qcam_g_input,
.vidioc_s_input = qcam_s_input,
.vidioc_enum_input = qcam_enum_input,
.vidioc_queryctrl = qcam_queryctrl,
.vidioc_g_ctrl = qcam_g_ctrl,
.vidioc_s_ctrl = qcam_s_ctrl,
.vidioc_enum_fmt_vid_cap = qcam_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = qcam_g_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = qcam_s_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = qcam_try_fmt_vid_cap,
};
/* Initialize the QuickCam driver control structure. */
static struct qcam *qcam_init(struct parport *port)
{
struct qcam *qcam;
struct v4l2_device *v4l2_dev;
qcam = kzalloc(sizeof(*qcam), GFP_KERNEL);
if (qcam == NULL)
return NULL;
v4l2_dev = &qcam->v4l2_dev;
strlcpy(v4l2_dev->name, "c-qcam", sizeof(v4l2_dev->name));
if (v4l2_device_register(NULL, v4l2_dev) < 0) {
v4l2_err(v4l2_dev, "Could not register v4l2_device\n");
kfree(qcam);
return NULL;
}
qcam->pport = port;
qcam->pdev = parport_register_device(port, "c-qcam", NULL, NULL,
NULL, 0, NULL);
qcam->bidirectional = (qcam->pport->modes & PARPORT_MODE_TRISTATE) ? 1 : 0;
if (qcam->pdev == NULL) {
v4l2_err(v4l2_dev, "couldn't register for %s.\n", port->name);
kfree(qcam);
return NULL;
}
strlcpy(qcam->vdev.name, "Colour QuickCam", sizeof(qcam->vdev.name));
qcam->vdev.v4l2_dev = v4l2_dev;
qcam->vdev.fops = &qcam_fops;
qcam->vdev.ioctl_ops = &qcam_ioctl_ops;
qcam->vdev.release = video_device_release_empty;
video_set_drvdata(&qcam->vdev, qcam);
mutex_init(&qcam->lock);
qcam->width = qcam->ccd_width = 320;
qcam->height = qcam->ccd_height = 240;
qcam->mode = QC_MILLIONS | QC_DECIMATION_1;
qcam->contrast = 192;
qcam->brightness = 240;
qcam->whitebal = 128;
qcam->top = 1;
qcam->left = 14;
return qcam;
}
static int init_cqcam(struct parport *port)
{
struct qcam *qcam;
struct v4l2_device *v4l2_dev;
if (parport[0] != -1) {
/* The user gave specific instructions */
int i, found = 0;
for (i = 0; i < MAX_CAMS && parport[i] != -1; i++) {
if (parport[0] == port->number)
found = 1;
}
if (!found)
return -ENODEV;
}
if (num_cams == MAX_CAMS)
return -ENOSPC;
qcam = qcam_init(port);
if (qcam == NULL)
return -ENODEV;
v4l2_dev = &qcam->v4l2_dev;
parport_claim_or_block(qcam->pdev);
qc_reset(qcam);
if (probe && qc_detect(qcam) == 0) {
parport_release(qcam->pdev);
parport_unregister_device(qcam->pdev);
kfree(qcam);
return -ENODEV;
}
qc_setup(qcam);
parport_release(qcam->pdev);
if (video_register_device(&qcam->vdev, VFL_TYPE_GRABBER, video_nr) < 0) {
v4l2_err(v4l2_dev, "Unable to register Colour QuickCam on %s\n",
qcam->pport->name);
parport_unregister_device(qcam->pdev);
kfree(qcam);
return -ENODEV;
}
v4l2_info(v4l2_dev, "%s: Colour QuickCam found on %s\n",
video_device_node_name(&qcam->vdev), qcam->pport->name);
qcams[num_cams++] = qcam;
return 0;
}
static void close_cqcam(struct qcam *qcam)
{
video_unregister_device(&qcam->vdev);
parport_unregister_device(qcam->pdev);
kfree(qcam);
}
static void cq_attach(struct parport *port)
{
init_cqcam(port);
}
static void cq_detach(struct parport *port)
{
/* Write this some day. */
}
static struct parport_driver cqcam_driver = {
.name = "cqcam",
.attach = cq_attach,
.detach = cq_detach,
};
static int __init cqcam_init(void)
{
printk(KERN_INFO BANNER "\n");
return parport_register_driver(&cqcam_driver);
}
static void __exit cqcam_cleanup(void)
{
unsigned int i;
for (i = 0; i < num_cams; i++)
close_cqcam(qcams[i]);
parport_unregister_driver(&cqcam_driver);
}
MODULE_AUTHOR("Philip Blundell <philb@gnu.org>");
MODULE_DESCRIPTION(BANNER);
MODULE_LICENSE("GPL");
MODULE_VERSION("0.0.4");
module_init(cqcam_init);
module_exit(cqcam_cleanup);
| gpl-2.0 |
Metallium-Devices/android_kernel_google_msm | drivers/media/video/cx25821/cx25821-video-upstream-ch2.c | 4902 | 21526 | /*
* Driver for the Conexant CX25821 PCIe bridge
*
* Copyright (C) 2009 Conexant Systems Inc.
* Authors <hiep.huynh@conexant.com>, <shu.lin@conexant.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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include "cx25821-video.h"
#include "cx25821-video-upstream-ch2.h"
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/syscalls.h>
#include <linux/file.h>
#include <linux/fcntl.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
MODULE_DESCRIPTION("v4l2 driver module for cx25821 based TV cards");
MODULE_AUTHOR("Hiep Huynh <hiep.huynh@conexant.com>");
MODULE_LICENSE("GPL");
static int _intr_msk = FLD_VID_SRC_RISC1 | FLD_VID_SRC_UF | FLD_VID_SRC_SYNC |
FLD_VID_SRC_OPC_ERR;
static __le32 *cx25821_update_riscprogram_ch2(struct cx25821_dev *dev,
__le32 *rp, unsigned int offset,
unsigned int bpl, u32 sync_line,
unsigned int lines,
int fifo_enable, int field_type)
{
unsigned int line, i;
int dist_betwn_starts = bpl * 2;
*(rp++) = cpu_to_le32(RISC_RESYNC | sync_line);
if (USE_RISC_NOOP_VIDEO) {
for (i = 0; i < NUM_NO_OPS; i++)
*(rp++) = cpu_to_le32(RISC_NOOP);
}
/* scan lines */
for (line = 0; line < lines; line++) {
*(rp++) = cpu_to_le32(RISC_READ | RISC_SOL | RISC_EOL | bpl);
*(rp++) = cpu_to_le32(dev->_data_buf_phys_addr_ch2 + offset);
*(rp++) = cpu_to_le32(0); /* bits 63-32 */
if ((lines <= NTSC_FIELD_HEIGHT) ||
(line < (NTSC_FIELD_HEIGHT - 1)) || !(dev->_isNTSC_ch2)) {
offset += dist_betwn_starts;
}
}
return rp;
}
static __le32 *cx25821_risc_field_upstream_ch2(struct cx25821_dev *dev,
__le32 *rp,
dma_addr_t databuf_phys_addr,
unsigned int offset,
u32 sync_line, unsigned int bpl,
unsigned int lines,
int fifo_enable, int field_type)
{
unsigned int line, i;
struct sram_channel *sram_ch =
dev->channels[dev->_channel2_upstream_select].sram_channels;
int dist_betwn_starts = bpl * 2;
/* sync instruction */
if (sync_line != NO_SYNC_LINE)
*(rp++) = cpu_to_le32(RISC_RESYNC | sync_line);
if (USE_RISC_NOOP_VIDEO) {
for (i = 0; i < NUM_NO_OPS; i++)
*(rp++) = cpu_to_le32(RISC_NOOP);
}
/* scan lines */
for (line = 0; line < lines; line++) {
*(rp++) = cpu_to_le32(RISC_READ | RISC_SOL | RISC_EOL | bpl);
*(rp++) = cpu_to_le32(databuf_phys_addr + offset);
*(rp++) = cpu_to_le32(0); /* bits 63-32 */
if ((lines <= NTSC_FIELD_HEIGHT) ||
(line < (NTSC_FIELD_HEIGHT - 1)) || !(dev->_isNTSC_ch2)) {
offset += dist_betwn_starts;
}
/*
check if we need to enable the FIFO after the first 4 lines
For the upstream video channel, the risc engine will enable
the FIFO.
*/
if (fifo_enable && line == 3) {
*(rp++) = RISC_WRITECR;
*(rp++) = sram_ch->dma_ctl;
*(rp++) = FLD_VID_FIFO_EN;
*(rp++) = 0x00000001;
}
}
return rp;
}
int cx25821_risc_buffer_upstream_ch2(struct cx25821_dev *dev,
struct pci_dev *pci,
unsigned int top_offset, unsigned int bpl,
unsigned int lines)
{
__le32 *rp;
int fifo_enable = 0;
int singlefield_lines = lines >> 1; /*get line count for single field */
int odd_num_lines = singlefield_lines;
int frame = 0;
int frame_size = 0;
int databuf_offset = 0;
int risc_program_size = 0;
int risc_flag = RISC_CNT_RESET;
unsigned int bottom_offset = bpl;
dma_addr_t risc_phys_jump_addr;
if (dev->_isNTSC_ch2) {
odd_num_lines = singlefield_lines + 1;
risc_program_size = FRAME1_VID_PROG_SIZE;
if (bpl == Y411_LINE_SZ)
frame_size = FRAME_SIZE_NTSC_Y411;
else
frame_size = FRAME_SIZE_NTSC_Y422;
} else {
risc_program_size = PAL_VID_PROG_SIZE;
if (bpl == Y411_LINE_SZ)
frame_size = FRAME_SIZE_PAL_Y411;
else
frame_size = FRAME_SIZE_PAL_Y422;
}
/* Virtual address of Risc buffer program */
rp = dev->_dma_virt_addr_ch2;
for (frame = 0; frame < NUM_FRAMES; frame++) {
databuf_offset = frame_size * frame;
if (UNSET != top_offset) {
fifo_enable = (frame == 0) ? FIFO_ENABLE : FIFO_DISABLE;
rp = cx25821_risc_field_upstream_ch2(dev, rp,
dev->_data_buf_phys_addr_ch2 + databuf_offset,
top_offset, 0, bpl, odd_num_lines, fifo_enable,
ODD_FIELD);
}
fifo_enable = FIFO_DISABLE;
/* Even field */
rp = cx25821_risc_field_upstream_ch2(dev, rp,
dev->_data_buf_phys_addr_ch2 + databuf_offset,
bottom_offset, 0x200, bpl, singlefield_lines,
fifo_enable, EVEN_FIELD);
if (frame == 0) {
risc_flag = RISC_CNT_RESET;
risc_phys_jump_addr = dev->_dma_phys_start_addr_ch2 +
risc_program_size;
} else {
risc_flag = RISC_CNT_INC;
risc_phys_jump_addr = dev->_dma_phys_start_addr_ch2;
}
/*
* Loop to 2ndFrameRISC or to Start of
* Risc program & generate IRQ
*/
*(rp++) = cpu_to_le32(RISC_JUMP | RISC_IRQ1 | risc_flag);
*(rp++) = cpu_to_le32(risc_phys_jump_addr);
*(rp++) = cpu_to_le32(0);
}
return 0;
}
void cx25821_stop_upstream_video_ch2(struct cx25821_dev *dev)
{
struct sram_channel *sram_ch =
dev->channels[VID_UPSTREAM_SRAM_CHANNEL_J].sram_channels;
u32 tmp = 0;
if (!dev->_is_running_ch2) {
pr_info("No video file is currently running so return!\n");
return;
}
/* Disable RISC interrupts */
tmp = cx_read(sram_ch->int_msk);
cx_write(sram_ch->int_msk, tmp & ~_intr_msk);
/* Turn OFF risc and fifo */
tmp = cx_read(sram_ch->dma_ctl);
cx_write(sram_ch->dma_ctl, tmp & ~(FLD_VID_FIFO_EN | FLD_VID_RISC_EN));
/* Clear data buffer memory */
if (dev->_data_buf_virt_addr_ch2)
memset(dev->_data_buf_virt_addr_ch2, 0,
dev->_data_buf_size_ch2);
dev->_is_running_ch2 = 0;
dev->_is_first_frame_ch2 = 0;
dev->_frame_count_ch2 = 0;
dev->_file_status_ch2 = END_OF_FILE;
kfree(dev->_irq_queues_ch2);
dev->_irq_queues_ch2 = NULL;
kfree(dev->_filename_ch2);
tmp = cx_read(VID_CH_MODE_SEL);
cx_write(VID_CH_MODE_SEL, tmp & 0xFFFFFE00);
}
void cx25821_free_mem_upstream_ch2(struct cx25821_dev *dev)
{
if (dev->_is_running_ch2)
cx25821_stop_upstream_video_ch2(dev);
if (dev->_dma_virt_addr_ch2) {
pci_free_consistent(dev->pci, dev->_risc_size_ch2,
dev->_dma_virt_addr_ch2,
dev->_dma_phys_addr_ch2);
dev->_dma_virt_addr_ch2 = NULL;
}
if (dev->_data_buf_virt_addr_ch2) {
pci_free_consistent(dev->pci, dev->_data_buf_size_ch2,
dev->_data_buf_virt_addr_ch2,
dev->_data_buf_phys_addr_ch2);
dev->_data_buf_virt_addr_ch2 = NULL;
}
}
int cx25821_get_frame_ch2(struct cx25821_dev *dev, struct sram_channel *sram_ch)
{
struct file *myfile;
int frame_index_temp = dev->_frame_index_ch2;
int i = 0;
int line_size = (dev->_pixel_format_ch2 == PIXEL_FRMT_411) ?
Y411_LINE_SZ : Y422_LINE_SZ;
int frame_size = 0;
int frame_offset = 0;
ssize_t vfs_read_retval = 0;
char mybuf[line_size];
loff_t file_offset;
loff_t pos;
mm_segment_t old_fs;
if (dev->_file_status_ch2 == END_OF_FILE)
return 0;
if (dev->_isNTSC_ch2) {
frame_size = (line_size == Y411_LINE_SZ) ?
FRAME_SIZE_NTSC_Y411 : FRAME_SIZE_NTSC_Y422;
} else {
frame_size = (line_size == Y411_LINE_SZ) ?
FRAME_SIZE_PAL_Y411 : FRAME_SIZE_PAL_Y422;
}
frame_offset = (frame_index_temp > 0) ? frame_size : 0;
file_offset = dev->_frame_count_ch2 * frame_size;
myfile = filp_open(dev->_filename_ch2, O_RDONLY | O_LARGEFILE, 0);
if (IS_ERR(myfile)) {
const int open_errno = -PTR_ERR(myfile);
pr_err("%s(): ERROR opening file(%s) with errno = %d!\n",
__func__, dev->_filename_ch2, open_errno);
return PTR_ERR(myfile);
} else {
if (!(myfile->f_op)) {
pr_err("%s(): File has no file operations registered!\n",
__func__);
filp_close(myfile, NULL);
return -EIO;
}
if (!myfile->f_op->read) {
pr_err("%s(): File has no READ operations registered!\n",
__func__);
filp_close(myfile, NULL);
return -EIO;
}
pos = myfile->f_pos;
old_fs = get_fs();
set_fs(KERNEL_DS);
for (i = 0; i < dev->_lines_count_ch2; i++) {
pos = file_offset;
vfs_read_retval = vfs_read(myfile, mybuf, line_size,
&pos);
if (vfs_read_retval > 0 && vfs_read_retval == line_size
&& dev->_data_buf_virt_addr_ch2 != NULL) {
memcpy((void *)(dev->_data_buf_virt_addr_ch2 +
frame_offset / 4), mybuf,
vfs_read_retval);
}
file_offset += vfs_read_retval;
frame_offset += vfs_read_retval;
if (vfs_read_retval < line_size) {
pr_info("Done: exit %s() since no more bytes to read from Video file\n",
__func__);
break;
}
}
if (i > 0)
dev->_frame_count_ch2++;
dev->_file_status_ch2 = (vfs_read_retval == line_size) ?
IN_PROGRESS : END_OF_FILE;
set_fs(old_fs);
filp_close(myfile, NULL);
}
return 0;
}
static void cx25821_vidups_handler_ch2(struct work_struct *work)
{
struct cx25821_dev *dev = container_of(work, struct cx25821_dev,
_irq_work_entry_ch2);
if (!dev) {
pr_err("ERROR %s(): since container_of(work_struct) FAILED!\n",
__func__);
return;
}
cx25821_get_frame_ch2(dev, dev->channels[dev->
_channel2_upstream_select].sram_channels);
}
int cx25821_openfile_ch2(struct cx25821_dev *dev, struct sram_channel *sram_ch)
{
struct file *myfile;
int i = 0, j = 0;
int line_size = (dev->_pixel_format_ch2 == PIXEL_FRMT_411) ?
Y411_LINE_SZ : Y422_LINE_SZ;
ssize_t vfs_read_retval = 0;
char mybuf[line_size];
loff_t pos;
loff_t offset = (unsigned long)0;
mm_segment_t old_fs;
myfile = filp_open(dev->_filename_ch2, O_RDONLY | O_LARGEFILE, 0);
if (IS_ERR(myfile)) {
const int open_errno = -PTR_ERR(myfile);
pr_err("%s(): ERROR opening file(%s) with errno = %d!\n",
__func__, dev->_filename_ch2, open_errno);
return PTR_ERR(myfile);
} else {
if (!(myfile->f_op)) {
pr_err("%s(): File has no file operations registered!\n",
__func__);
filp_close(myfile, NULL);
return -EIO;
}
if (!myfile->f_op->read) {
pr_err("%s(): File has no READ operations registered! Returning\n",
__func__);
filp_close(myfile, NULL);
return -EIO;
}
pos = myfile->f_pos;
old_fs = get_fs();
set_fs(KERNEL_DS);
for (j = 0; j < NUM_FRAMES; j++) {
for (i = 0; i < dev->_lines_count_ch2; i++) {
pos = offset;
vfs_read_retval = vfs_read(myfile, mybuf,
line_size, &pos);
if (vfs_read_retval > 0 &&
vfs_read_retval == line_size &&
dev->_data_buf_virt_addr_ch2 != NULL) {
memcpy((void *)(dev->
_data_buf_virt_addr_ch2
+ offset / 4), mybuf,
vfs_read_retval);
}
offset += vfs_read_retval;
if (vfs_read_retval < line_size) {
pr_info("Done: exit %s() since no more bytes to read from Video file\n",
__func__);
break;
}
}
if (i > 0)
dev->_frame_count_ch2++;
if (vfs_read_retval < line_size)
break;
}
dev->_file_status_ch2 = (vfs_read_retval == line_size) ?
IN_PROGRESS : END_OF_FILE;
set_fs(old_fs);
myfile->f_pos = 0;
filp_close(myfile, NULL);
}
return 0;
}
static int cx25821_upstream_buffer_prepare_ch2(struct cx25821_dev *dev,
struct sram_channel *sram_ch,
int bpl)
{
int ret = 0;
dma_addr_t dma_addr;
dma_addr_t data_dma_addr;
if (dev->_dma_virt_addr_ch2 != NULL) {
pci_free_consistent(dev->pci, dev->upstream_riscbuf_size_ch2,
dev->_dma_virt_addr_ch2,
dev->_dma_phys_addr_ch2);
}
dev->_dma_virt_addr_ch2 = pci_alloc_consistent(dev->pci,
dev->upstream_riscbuf_size_ch2, &dma_addr);
dev->_dma_virt_start_addr_ch2 = dev->_dma_virt_addr_ch2;
dev->_dma_phys_start_addr_ch2 = dma_addr;
dev->_dma_phys_addr_ch2 = dma_addr;
dev->_risc_size_ch2 = dev->upstream_riscbuf_size_ch2;
if (!dev->_dma_virt_addr_ch2) {
pr_err("FAILED to allocate memory for Risc buffer! Returning\n");
return -ENOMEM;
}
/* Iniitize at this address until n bytes to 0 */
memset(dev->_dma_virt_addr_ch2, 0, dev->_risc_size_ch2);
if (dev->_data_buf_virt_addr_ch2 != NULL) {
pci_free_consistent(dev->pci, dev->upstream_databuf_size_ch2,
dev->_data_buf_virt_addr_ch2,
dev->_data_buf_phys_addr_ch2);
}
/* For Video Data buffer allocation */
dev->_data_buf_virt_addr_ch2 = pci_alloc_consistent(dev->pci,
dev->upstream_databuf_size_ch2, &data_dma_addr);
dev->_data_buf_phys_addr_ch2 = data_dma_addr;
dev->_data_buf_size_ch2 = dev->upstream_databuf_size_ch2;
if (!dev->_data_buf_virt_addr_ch2) {
pr_err("FAILED to allocate memory for data buffer! Returning\n");
return -ENOMEM;
}
/* Initialize at this address until n bytes to 0 */
memset(dev->_data_buf_virt_addr_ch2, 0, dev->_data_buf_size_ch2);
ret = cx25821_openfile_ch2(dev, sram_ch);
if (ret < 0)
return ret;
/* Creating RISC programs */
ret = cx25821_risc_buffer_upstream_ch2(dev, dev->pci, 0, bpl,
dev->_lines_count_ch2);
if (ret < 0) {
pr_info("Failed creating Video Upstream Risc programs!\n");
goto error;
}
return 0;
error:
return ret;
}
int cx25821_video_upstream_irq_ch2(struct cx25821_dev *dev, int chan_num,
u32 status)
{
u32 int_msk_tmp;
struct sram_channel *channel = dev->channels[chan_num].sram_channels;
int singlefield_lines = NTSC_FIELD_HEIGHT;
int line_size_in_bytes = Y422_LINE_SZ;
int odd_risc_prog_size = 0;
dma_addr_t risc_phys_jump_addr;
__le32 *rp;
if (status & FLD_VID_SRC_RISC1) {
/* We should only process one program per call */
u32 prog_cnt = cx_read(channel->gpcnt);
/*
* Since we've identified our IRQ, clear our bits from the
* interrupt mask and interrupt status registers
*/
int_msk_tmp = cx_read(channel->int_msk);
cx_write(channel->int_msk, int_msk_tmp & ~_intr_msk);
cx_write(channel->int_stat, _intr_msk);
spin_lock(&dev->slock);
dev->_frame_index_ch2 = prog_cnt;
queue_work(dev->_irq_queues_ch2, &dev->_irq_work_entry_ch2);
if (dev->_is_first_frame_ch2) {
dev->_is_first_frame_ch2 = 0;
if (dev->_isNTSC_ch2) {
singlefield_lines += 1;
odd_risc_prog_size = ODD_FLD_NTSC_PROG_SIZE;
} else {
singlefield_lines = PAL_FIELD_HEIGHT;
odd_risc_prog_size = ODD_FLD_PAL_PROG_SIZE;
}
if (dev->_dma_virt_start_addr_ch2 != NULL) {
if (dev->_pixel_format_ch2 == PIXEL_FRMT_411)
line_size_in_bytes = Y411_LINE_SZ;
else
line_size_in_bytes = Y422_LINE_SZ;
risc_phys_jump_addr =
dev->_dma_phys_start_addr_ch2 +
odd_risc_prog_size;
rp = cx25821_update_riscprogram_ch2(dev,
dev->_dma_virt_start_addr_ch2,
TOP_OFFSET, line_size_in_bytes,
0x0, singlefield_lines,
FIFO_DISABLE, ODD_FIELD);
/* Jump to Even Risc program of 1st Frame */
*(rp++) = cpu_to_le32(RISC_JUMP);
*(rp++) = cpu_to_le32(risc_phys_jump_addr);
*(rp++) = cpu_to_le32(0);
}
}
spin_unlock(&dev->slock);
}
if (dev->_file_status_ch2 == END_OF_FILE) {
pr_info("EOF Channel 2 Framecount = %d\n",
dev->_frame_count_ch2);
return -1;
}
/* ElSE, set the interrupt mask register, re-enable irq. */
int_msk_tmp = cx_read(channel->int_msk);
cx_write(channel->int_msk, int_msk_tmp |= _intr_msk);
return 0;
}
static irqreturn_t cx25821_upstream_irq_ch2(int irq, void *dev_id)
{
struct cx25821_dev *dev = dev_id;
u32 msk_stat, vid_status;
int handled = 0;
int channel_num = 0;
struct sram_channel *sram_ch;
if (!dev)
return -1;
channel_num = VID_UPSTREAM_SRAM_CHANNEL_J;
sram_ch = dev->channels[channel_num].sram_channels;
msk_stat = cx_read(sram_ch->int_mstat);
vid_status = cx_read(sram_ch->int_stat);
/* Only deal with our interrupt */
if (vid_status)
handled = cx25821_video_upstream_irq_ch2(dev, channel_num,
vid_status);
if (handled < 0)
cx25821_stop_upstream_video_ch2(dev);
else
handled += handled;
return IRQ_RETVAL(handled);
}
static void cx25821_set_pixelengine_ch2(struct cx25821_dev *dev,
struct sram_channel *ch, int pix_format)
{
int width = WIDTH_D1;
int height = dev->_lines_count_ch2;
int num_lines, odd_num_lines;
u32 value;
int vip_mode = PIXEL_ENGINE_VIP1;
value = ((pix_format & 0x3) << 12) | (vip_mode & 0x7);
value &= 0xFFFFFFEF;
value |= dev->_isNTSC_ch2 ? 0 : 0x10;
cx_write(ch->vid_fmt_ctl, value);
/*
* set number of active pixels in each line. Default is 720
* pixels in both NTSC and PAL format
*/
cx_write(ch->vid_active_ctl1, width);
num_lines = (height / 2) & 0x3FF;
odd_num_lines = num_lines;
if (dev->_isNTSC_ch2)
odd_num_lines += 1;
value = (num_lines << 16) | odd_num_lines;
/* set number of active lines in field 0 (top) and field 1 (bottom) */
cx_write(ch->vid_active_ctl2, value);
cx_write(ch->vid_cdt_size, VID_CDT_SIZE >> 3);
}
int cx25821_start_video_dma_upstream_ch2(struct cx25821_dev *dev,
struct sram_channel *sram_ch)
{
u32 tmp = 0;
int err = 0;
/*
* 656/VIP SRC Upstream Channel I & J and 7 - Host Bus Interface
* for channel A-C
*/
tmp = cx_read(VID_CH_MODE_SEL);
cx_write(VID_CH_MODE_SEL, tmp | 0x1B0001FF);
/*
* Set the physical start address of the RISC program in the initial
* program counter(IPC) member of the cmds.
*/
cx_write(sram_ch->cmds_start + 0, dev->_dma_phys_addr_ch2);
cx_write(sram_ch->cmds_start + 4, 0); /* Risc IPC High 64 bits 63-32 */
/* reset counter */
cx_write(sram_ch->gpcnt_ctl, 3);
/* Clear our bits from the interrupt status register. */
cx_write(sram_ch->int_stat, _intr_msk);
/* Set the interrupt mask register, enable irq. */
cx_set(PCI_INT_MSK, cx_read(PCI_INT_MSK) | (1 << sram_ch->irq_bit));
tmp = cx_read(sram_ch->int_msk);
cx_write(sram_ch->int_msk, tmp |= _intr_msk);
err = request_irq(dev->pci->irq, cx25821_upstream_irq_ch2,
IRQF_SHARED, dev->name, dev);
if (err < 0) {
pr_err("%s: can't get upstream IRQ %d\n",
dev->name, dev->pci->irq);
goto fail_irq;
}
/* Start the DMA engine */
tmp = cx_read(sram_ch->dma_ctl);
cx_set(sram_ch->dma_ctl, tmp | FLD_VID_RISC_EN);
dev->_is_running_ch2 = 1;
dev->_is_first_frame_ch2 = 1;
return 0;
fail_irq:
cx25821_dev_unregister(dev);
return err;
}
int cx25821_vidupstream_init_ch2(struct cx25821_dev *dev, int channel_select,
int pixel_format)
{
struct sram_channel *sram_ch;
u32 tmp;
int retval = 0;
int err = 0;
int data_frame_size = 0;
int risc_buffer_size = 0;
int str_length = 0;
if (dev->_is_running_ch2) {
pr_info("Video Channel is still running so return!\n");
return 0;
}
dev->_channel2_upstream_select = channel_select;
sram_ch = dev->channels[channel_select].sram_channels;
INIT_WORK(&dev->_irq_work_entry_ch2, cx25821_vidups_handler_ch2);
dev->_irq_queues_ch2 =
create_singlethread_workqueue("cx25821_workqueue2");
if (!dev->_irq_queues_ch2) {
pr_err("create_singlethread_workqueue() for Video FAILED!\n");
return -ENOMEM;
}
/*
* 656/VIP SRC Upstream Channel I & J and 7 -
* Host Bus Interface for channel A-C
*/
tmp = cx_read(VID_CH_MODE_SEL);
cx_write(VID_CH_MODE_SEL, tmp | 0x1B0001FF);
dev->_is_running_ch2 = 0;
dev->_frame_count_ch2 = 0;
dev->_file_status_ch2 = RESET_STATUS;
dev->_lines_count_ch2 = dev->_isNTSC_ch2 ? 480 : 576;
dev->_pixel_format_ch2 = pixel_format;
dev->_line_size_ch2 = (dev->_pixel_format_ch2 == PIXEL_FRMT_422) ?
(WIDTH_D1 * 2) : (WIDTH_D1 * 3) / 2;
data_frame_size = dev->_isNTSC_ch2 ? NTSC_DATA_BUF_SZ : PAL_DATA_BUF_SZ;
risc_buffer_size = dev->_isNTSC_ch2 ?
NTSC_RISC_BUF_SIZE : PAL_RISC_BUF_SIZE;
if (dev->input_filename_ch2) {
str_length = strlen(dev->input_filename_ch2);
dev->_filename_ch2 = kmemdup(dev->input_filename_ch2,
str_length + 1, GFP_KERNEL);
if (!dev->_filename_ch2)
goto error;
} else {
str_length = strlen(dev->_defaultname_ch2);
dev->_filename_ch2 = kmemdup(dev->_defaultname_ch2,
str_length + 1, GFP_KERNEL);
if (!dev->_filename_ch2)
goto error;
}
/* Default if filename is empty string */
if (strcmp(dev->input_filename_ch2, "") == 0) {
if (dev->_isNTSC_ch2) {
dev->_filename_ch2 = (dev->_pixel_format_ch2 ==
PIXEL_FRMT_411) ? "/root/vid411.yuv" :
"/root/vidtest.yuv";
} else {
dev->_filename_ch2 = (dev->_pixel_format_ch2 ==
PIXEL_FRMT_411) ? "/root/pal411.yuv" :
"/root/pal422.yuv";
}
}
retval = cx25821_sram_channel_setup_upstream(dev, sram_ch,
dev->_line_size_ch2, 0);
/* setup fifo + format */
cx25821_set_pixelengine_ch2(dev, sram_ch, dev->_pixel_format_ch2);
dev->upstream_riscbuf_size_ch2 = risc_buffer_size * 2;
dev->upstream_databuf_size_ch2 = data_frame_size * 2;
/* Allocating buffers and prepare RISC program */
retval = cx25821_upstream_buffer_prepare_ch2(dev, sram_ch,
dev->_line_size_ch2);
if (retval < 0) {
pr_err("%s: Failed to set up Video upstream buffers!\n",
dev->name);
goto error;
}
cx25821_start_video_dma_upstream_ch2(dev, sram_ch);
return 0;
error:
cx25821_dev_unregister(dev);
return err;
}
| gpl-2.0 |
NXTnet/android_kernel_samsung_msm8916-caf | sound/pci/oxygen/oxygen_io.c | 7718 | 7738 | /*
* C-Media CMI8788 driver - helper functions
*
* Copyright (c) Clemens Ladisch <clemens@ladisch.de>
*
*
* This driver is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2.
*
* This driver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this driver; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/export.h>
#include <sound/core.h>
#include <sound/mpu401.h>
#include <asm/io.h>
#include "oxygen.h"
u8 oxygen_read8(struct oxygen *chip, unsigned int reg)
{
return inb(chip->addr + reg);
}
EXPORT_SYMBOL(oxygen_read8);
u16 oxygen_read16(struct oxygen *chip, unsigned int reg)
{
return inw(chip->addr + reg);
}
EXPORT_SYMBOL(oxygen_read16);
u32 oxygen_read32(struct oxygen *chip, unsigned int reg)
{
return inl(chip->addr + reg);
}
EXPORT_SYMBOL(oxygen_read32);
void oxygen_write8(struct oxygen *chip, unsigned int reg, u8 value)
{
outb(value, chip->addr + reg);
chip->saved_registers._8[reg] = value;
}
EXPORT_SYMBOL(oxygen_write8);
void oxygen_write16(struct oxygen *chip, unsigned int reg, u16 value)
{
outw(value, chip->addr + reg);
chip->saved_registers._16[reg / 2] = cpu_to_le16(value);
}
EXPORT_SYMBOL(oxygen_write16);
void oxygen_write32(struct oxygen *chip, unsigned int reg, u32 value)
{
outl(value, chip->addr + reg);
chip->saved_registers._32[reg / 4] = cpu_to_le32(value);
}
EXPORT_SYMBOL(oxygen_write32);
void oxygen_write8_masked(struct oxygen *chip, unsigned int reg,
u8 value, u8 mask)
{
u8 tmp = inb(chip->addr + reg);
tmp &= ~mask;
tmp |= value & mask;
outb(tmp, chip->addr + reg);
chip->saved_registers._8[reg] = tmp;
}
EXPORT_SYMBOL(oxygen_write8_masked);
void oxygen_write16_masked(struct oxygen *chip, unsigned int reg,
u16 value, u16 mask)
{
u16 tmp = inw(chip->addr + reg);
tmp &= ~mask;
tmp |= value & mask;
outw(tmp, chip->addr + reg);
chip->saved_registers._16[reg / 2] = cpu_to_le16(tmp);
}
EXPORT_SYMBOL(oxygen_write16_masked);
void oxygen_write32_masked(struct oxygen *chip, unsigned int reg,
u32 value, u32 mask)
{
u32 tmp = inl(chip->addr + reg);
tmp &= ~mask;
tmp |= value & mask;
outl(tmp, chip->addr + reg);
chip->saved_registers._32[reg / 4] = cpu_to_le32(tmp);
}
EXPORT_SYMBOL(oxygen_write32_masked);
static int oxygen_ac97_wait(struct oxygen *chip, unsigned int mask)
{
u8 status = 0;
/*
* Reading the status register also clears the bits, so we have to save
* the read bits in status.
*/
wait_event_timeout(chip->ac97_waitqueue,
({ status |= oxygen_read8(chip, OXYGEN_AC97_INTERRUPT_STATUS);
status & mask; }),
msecs_to_jiffies(1) + 1);
/*
* Check even after a timeout because this function should not require
* the AC'97 interrupt to be enabled.
*/
status |= oxygen_read8(chip, OXYGEN_AC97_INTERRUPT_STATUS);
return status & mask ? 0 : -EIO;
}
/*
* About 10% of AC'97 register reads or writes fail to complete, but even those
* where the controller indicates completion aren't guaranteed to have actually
* happened.
*
* It's hard to assign blame to either the controller or the codec because both
* were made by C-Media ...
*/
void oxygen_write_ac97(struct oxygen *chip, unsigned int codec,
unsigned int index, u16 data)
{
unsigned int count, succeeded;
u32 reg;
reg = data;
reg |= index << OXYGEN_AC97_REG_ADDR_SHIFT;
reg |= OXYGEN_AC97_REG_DIR_WRITE;
reg |= codec << OXYGEN_AC97_REG_CODEC_SHIFT;
succeeded = 0;
for (count = 5; count > 0; --count) {
udelay(5);
oxygen_write32(chip, OXYGEN_AC97_REGS, reg);
/* require two "completed" writes, just to be sure */
if (oxygen_ac97_wait(chip, OXYGEN_AC97_INT_WRITE_DONE) >= 0 &&
++succeeded >= 2) {
chip->saved_ac97_registers[codec][index / 2] = data;
return;
}
}
snd_printk(KERN_ERR "AC'97 write timeout\n");
}
EXPORT_SYMBOL(oxygen_write_ac97);
u16 oxygen_read_ac97(struct oxygen *chip, unsigned int codec,
unsigned int index)
{
unsigned int count;
unsigned int last_read = UINT_MAX;
u32 reg;
reg = index << OXYGEN_AC97_REG_ADDR_SHIFT;
reg |= OXYGEN_AC97_REG_DIR_READ;
reg |= codec << OXYGEN_AC97_REG_CODEC_SHIFT;
for (count = 5; count > 0; --count) {
udelay(5);
oxygen_write32(chip, OXYGEN_AC97_REGS, reg);
udelay(10);
if (oxygen_ac97_wait(chip, OXYGEN_AC97_INT_READ_DONE) >= 0) {
u16 value = oxygen_read16(chip, OXYGEN_AC97_REGS);
/* we require two consecutive reads of the same value */
if (value == last_read)
return value;
last_read = value;
/*
* Invert the register value bits to make sure that two
* consecutive unsuccessful reads do not return the same
* value.
*/
reg ^= 0xffff;
}
}
snd_printk(KERN_ERR "AC'97 read timeout on codec %u\n", codec);
return 0;
}
EXPORT_SYMBOL(oxygen_read_ac97);
void oxygen_write_ac97_masked(struct oxygen *chip, unsigned int codec,
unsigned int index, u16 data, u16 mask)
{
u16 value = oxygen_read_ac97(chip, codec, index);
value &= ~mask;
value |= data & mask;
oxygen_write_ac97(chip, codec, index, value);
}
EXPORT_SYMBOL(oxygen_write_ac97_masked);
void oxygen_write_spi(struct oxygen *chip, u8 control, unsigned int data)
{
unsigned int count;
/* should not need more than 30.72 us (24 * 1.28 us) */
count = 10;
while ((oxygen_read8(chip, OXYGEN_SPI_CONTROL) & OXYGEN_SPI_BUSY)
&& count > 0) {
udelay(4);
--count;
}
oxygen_write8(chip, OXYGEN_SPI_DATA1, data);
oxygen_write8(chip, OXYGEN_SPI_DATA2, data >> 8);
if (control & OXYGEN_SPI_DATA_LENGTH_3)
oxygen_write8(chip, OXYGEN_SPI_DATA3, data >> 16);
oxygen_write8(chip, OXYGEN_SPI_CONTROL, control);
}
EXPORT_SYMBOL(oxygen_write_spi);
void oxygen_write_i2c(struct oxygen *chip, u8 device, u8 map, u8 data)
{
/* should not need more than about 300 us */
msleep(1);
oxygen_write8(chip, OXYGEN_2WIRE_MAP, map);
oxygen_write8(chip, OXYGEN_2WIRE_DATA, data);
oxygen_write8(chip, OXYGEN_2WIRE_CONTROL,
device | OXYGEN_2WIRE_DIR_WRITE);
}
EXPORT_SYMBOL(oxygen_write_i2c);
static void _write_uart(struct oxygen *chip, unsigned int port, u8 data)
{
if (oxygen_read8(chip, OXYGEN_MPU401 + 1) & MPU401_TX_FULL)
msleep(1);
oxygen_write8(chip, OXYGEN_MPU401 + port, data);
}
void oxygen_reset_uart(struct oxygen *chip)
{
_write_uart(chip, 1, MPU401_RESET);
msleep(1); /* wait for ACK */
_write_uart(chip, 1, MPU401_ENTER_UART);
}
EXPORT_SYMBOL(oxygen_reset_uart);
void oxygen_write_uart(struct oxygen *chip, u8 data)
{
_write_uart(chip, 0, data);
}
EXPORT_SYMBOL(oxygen_write_uart);
u16 oxygen_read_eeprom(struct oxygen *chip, unsigned int index)
{
unsigned int timeout;
oxygen_write8(chip, OXYGEN_EEPROM_CONTROL,
index | OXYGEN_EEPROM_DIR_READ);
for (timeout = 0; timeout < 100; ++timeout) {
udelay(1);
if (!(oxygen_read8(chip, OXYGEN_EEPROM_STATUS)
& OXYGEN_EEPROM_BUSY))
break;
}
return oxygen_read16(chip, OXYGEN_EEPROM_DATA);
}
void oxygen_write_eeprom(struct oxygen *chip, unsigned int index, u16 value)
{
unsigned int timeout;
oxygen_write16(chip, OXYGEN_EEPROM_DATA, value);
oxygen_write8(chip, OXYGEN_EEPROM_CONTROL,
index | OXYGEN_EEPROM_DIR_WRITE);
for (timeout = 0; timeout < 10; ++timeout) {
msleep(1);
if (!(oxygen_read8(chip, OXYGEN_EEPROM_STATUS)
& OXYGEN_EEPROM_BUSY))
return;
}
snd_printk(KERN_ERR "EEPROM write timeout\n");
}
| gpl-2.0 |
firstred/surfacepro3-kernel | drivers/md/dm-queue-length.c | 9254 | 5520 | /*
* Copyright (C) 2004-2005 IBM Corp. All Rights Reserved.
* Copyright (C) 2006-2009 NEC Corporation.
*
* dm-queue-length.c
*
* Module Author: Stefan Bader, IBM
* Modified by: Kiyoshi Ueda, NEC
*
* This file is released under the GPL.
*
* queue-length path selector - choose a path with the least number of
* in-flight I/Os.
*/
#include "dm.h"
#include "dm-path-selector.h"
#include <linux/slab.h>
#include <linux/ctype.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/atomic.h>
#define DM_MSG_PREFIX "multipath queue-length"
#define QL_MIN_IO 128
#define QL_VERSION "0.1.0"
struct selector {
struct list_head valid_paths;
struct list_head failed_paths;
};
struct path_info {
struct list_head list;
struct dm_path *path;
unsigned repeat_count;
atomic_t qlen; /* the number of in-flight I/Os */
};
static struct selector *alloc_selector(void)
{
struct selector *s = kmalloc(sizeof(*s), GFP_KERNEL);
if (s) {
INIT_LIST_HEAD(&s->valid_paths);
INIT_LIST_HEAD(&s->failed_paths);
}
return s;
}
static int ql_create(struct path_selector *ps, unsigned argc, char **argv)
{
struct selector *s = alloc_selector();
if (!s)
return -ENOMEM;
ps->context = s;
return 0;
}
static void ql_free_paths(struct list_head *paths)
{
struct path_info *pi, *next;
list_for_each_entry_safe(pi, next, paths, list) {
list_del(&pi->list);
kfree(pi);
}
}
static void ql_destroy(struct path_selector *ps)
{
struct selector *s = ps->context;
ql_free_paths(&s->valid_paths);
ql_free_paths(&s->failed_paths);
kfree(s);
ps->context = NULL;
}
static int ql_status(struct path_selector *ps, struct dm_path *path,
status_type_t type, char *result, unsigned maxlen)
{
unsigned sz = 0;
struct path_info *pi;
/* When called with NULL path, return selector status/args. */
if (!path)
DMEMIT("0 ");
else {
pi = path->pscontext;
switch (type) {
case STATUSTYPE_INFO:
DMEMIT("%d ", atomic_read(&pi->qlen));
break;
case STATUSTYPE_TABLE:
DMEMIT("%u ", pi->repeat_count);
break;
}
}
return sz;
}
static int ql_add_path(struct path_selector *ps, struct dm_path *path,
int argc, char **argv, char **error)
{
struct selector *s = ps->context;
struct path_info *pi;
unsigned repeat_count = QL_MIN_IO;
char dummy;
/*
* Arguments: [<repeat_count>]
* <repeat_count>: The number of I/Os before switching path.
* If not given, default (QL_MIN_IO) is used.
*/
if (argc > 1) {
*error = "queue-length ps: incorrect number of arguments";
return -EINVAL;
}
if ((argc == 1) && (sscanf(argv[0], "%u%c", &repeat_count, &dummy) != 1)) {
*error = "queue-length ps: invalid repeat count";
return -EINVAL;
}
/* Allocate the path information structure */
pi = kmalloc(sizeof(*pi), GFP_KERNEL);
if (!pi) {
*error = "queue-length ps: Error allocating path information";
return -ENOMEM;
}
pi->path = path;
pi->repeat_count = repeat_count;
atomic_set(&pi->qlen, 0);
path->pscontext = pi;
list_add_tail(&pi->list, &s->valid_paths);
return 0;
}
static void ql_fail_path(struct path_selector *ps, struct dm_path *path)
{
struct selector *s = ps->context;
struct path_info *pi = path->pscontext;
list_move(&pi->list, &s->failed_paths);
}
static int ql_reinstate_path(struct path_selector *ps, struct dm_path *path)
{
struct selector *s = ps->context;
struct path_info *pi = path->pscontext;
list_move_tail(&pi->list, &s->valid_paths);
return 0;
}
/*
* Select a path having the minimum number of in-flight I/Os
*/
static struct dm_path *ql_select_path(struct path_selector *ps,
unsigned *repeat_count, size_t nr_bytes)
{
struct selector *s = ps->context;
struct path_info *pi = NULL, *best = NULL;
if (list_empty(&s->valid_paths))
return NULL;
/* Change preferred (first in list) path to evenly balance. */
list_move_tail(s->valid_paths.next, &s->valid_paths);
list_for_each_entry(pi, &s->valid_paths, list) {
if (!best ||
(atomic_read(&pi->qlen) < atomic_read(&best->qlen)))
best = pi;
if (!atomic_read(&best->qlen))
break;
}
if (!best)
return NULL;
*repeat_count = best->repeat_count;
return best->path;
}
static int ql_start_io(struct path_selector *ps, struct dm_path *path,
size_t nr_bytes)
{
struct path_info *pi = path->pscontext;
atomic_inc(&pi->qlen);
return 0;
}
static int ql_end_io(struct path_selector *ps, struct dm_path *path,
size_t nr_bytes)
{
struct path_info *pi = path->pscontext;
atomic_dec(&pi->qlen);
return 0;
}
static struct path_selector_type ql_ps = {
.name = "queue-length",
.module = THIS_MODULE,
.table_args = 1,
.info_args = 1,
.create = ql_create,
.destroy = ql_destroy,
.status = ql_status,
.add_path = ql_add_path,
.fail_path = ql_fail_path,
.reinstate_path = ql_reinstate_path,
.select_path = ql_select_path,
.start_io = ql_start_io,
.end_io = ql_end_io,
};
static int __init dm_ql_init(void)
{
int r = dm_register_path_selector(&ql_ps);
if (r < 0)
DMERR("register failed %d", r);
DMINFO("version " QL_VERSION " loaded");
return r;
}
static void __exit dm_ql_exit(void)
{
int r = dm_unregister_path_selector(&ql_ps);
if (r < 0)
DMERR("unregister failed %d", r);
}
module_init(dm_ql_init);
module_exit(dm_ql_exit);
MODULE_AUTHOR("Stefan Bader <Stefan.Bader at de.ibm.com>");
MODULE_DESCRIPTION(
"(C) Copyright IBM Corp. 2004,2005 All Rights Reserved.\n"
DM_NAME " path selector to balance the number of in-flight I/Os"
);
MODULE_LICENSE("GPL");
| gpl-2.0 |
MuddyPlump/android_kernel_motorola_msm8226 | fs/compat_binfmt_elf.c | 9254 | 3540 | /*
* 32-bit compatibility support for ELF format executables and core dumps.
*
* Copyright (C) 2007 Red Hat, Inc. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License v.2.
*
* Red Hat Author: Roland McGrath.
*
* This file is used in a 64-bit kernel that wants to support 32-bit ELF.
* asm/elf.h is responsible for defining the compat_* and COMPAT_* macros
* used below, with definitions appropriate for 32-bit ABI compatibility.
*
* We use macros to rename the ABI types and machine-dependent
* functions used in binfmt_elf.c to compat versions.
*/
#include <linux/elfcore-compat.h>
#include <linux/time.h>
/*
* Rename the basic ELF layout types to refer to the 32-bit class of files.
*/
#undef ELF_CLASS
#define ELF_CLASS ELFCLASS32
#undef elfhdr
#undef elf_phdr
#undef elf_shdr
#undef elf_note
#undef elf_addr_t
#define elfhdr elf32_hdr
#define elf_phdr elf32_phdr
#define elf_shdr elf32_shdr
#define elf_note elf32_note
#define elf_addr_t Elf32_Addr
/*
* The machine-dependent core note format types are defined in elfcore-compat.h,
* which requires asm/elf.h to define compat_elf_gregset_t et al.
*/
#define elf_prstatus compat_elf_prstatus
#define elf_prpsinfo compat_elf_prpsinfo
/*
* Compat version of cputime_to_compat_timeval, perhaps this
* should be an inline in <linux/compat.h>.
*/
static void cputime_to_compat_timeval(const cputime_t cputime,
struct compat_timeval *value)
{
struct timeval tv;
cputime_to_timeval(cputime, &tv);
value->tv_sec = tv.tv_sec;
value->tv_usec = tv.tv_usec;
}
#undef cputime_to_timeval
#define cputime_to_timeval cputime_to_compat_timeval
/*
* To use this file, asm/elf.h must define compat_elf_check_arch.
* The other following macros can be defined if the compat versions
* differ from the native ones, or omitted when they match.
*/
#undef ELF_ARCH
#undef elf_check_arch
#define elf_check_arch compat_elf_check_arch
#ifdef COMPAT_ELF_PLATFORM
#undef ELF_PLATFORM
#define ELF_PLATFORM COMPAT_ELF_PLATFORM
#endif
#ifdef COMPAT_ELF_HWCAP
#undef ELF_HWCAP
#define ELF_HWCAP COMPAT_ELF_HWCAP
#endif
#ifdef COMPAT_ARCH_DLINFO
#undef ARCH_DLINFO
#define ARCH_DLINFO COMPAT_ARCH_DLINFO
#endif
#ifdef COMPAT_ELF_ET_DYN_BASE
#undef ELF_ET_DYN_BASE
#define ELF_ET_DYN_BASE COMPAT_ELF_ET_DYN_BASE
#endif
#ifdef COMPAT_ELF_EXEC_PAGESIZE
#undef ELF_EXEC_PAGESIZE
#define ELF_EXEC_PAGESIZE COMPAT_ELF_EXEC_PAGESIZE
#endif
#ifdef COMPAT_ELF_PLAT_INIT
#undef ELF_PLAT_INIT
#define ELF_PLAT_INIT COMPAT_ELF_PLAT_INIT
#endif
#ifdef COMPAT_SET_PERSONALITY
#undef SET_PERSONALITY
#define SET_PERSONALITY COMPAT_SET_PERSONALITY
#endif
#ifdef compat_start_thread
#undef start_thread
#define start_thread compat_start_thread
#endif
#ifdef compat_arch_setup_additional_pages
#undef ARCH_HAS_SETUP_ADDITIONAL_PAGES
#define ARCH_HAS_SETUP_ADDITIONAL_PAGES 1
#undef arch_setup_additional_pages
#define arch_setup_additional_pages compat_arch_setup_additional_pages
#endif
/*
* Rename a few of the symbols that binfmt_elf.c will define.
* These are all local so the names don't really matter, but it
* might make some debugging less confusing not to duplicate them.
*/
#define elf_format compat_elf_format
#define init_elf_binfmt init_compat_elf_binfmt
#define exit_elf_binfmt exit_compat_elf_binfmt
/*
* We share all the actual code with the native (64-bit) version.
*/
#include "binfmt_elf.c"
| gpl-2.0 |
aznrice/l-preview | drivers/gpu/drm/gma500/mdfld_tmd_vid.c | 10278 | 7236 | /*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Authors:
* Jim Liu <jim.liu@intel.com>
* Jackie Li<yaodong.li@intel.com>
* Gideon Eaton <eaton.
* Scott Rowe <scott.m.rowe@intel.com>
*/
#include "mdfld_dsi_dpi.h"
#include "mdfld_dsi_pkg_sender.h"
static struct drm_display_mode *tmd_vid_get_config_mode(struct drm_device *dev)
{
struct drm_display_mode *mode;
struct drm_psb_private *dev_priv = dev->dev_private;
struct oaktrail_timing_info *ti = &dev_priv->gct_data.DTD;
bool use_gct = false; /*Disable GCT for now*/
mode = kzalloc(sizeof(*mode), GFP_KERNEL);
if (!mode)
return NULL;
if (use_gct) {
mode->hdisplay = (ti->hactive_hi << 8) | ti->hactive_lo;
mode->vdisplay = (ti->vactive_hi << 8) | ti->vactive_lo;
mode->hsync_start = mode->hdisplay + \
((ti->hsync_offset_hi << 8) | \
ti->hsync_offset_lo);
mode->hsync_end = mode->hsync_start + \
((ti->hsync_pulse_width_hi << 8) | \
ti->hsync_pulse_width_lo);
mode->htotal = mode->hdisplay + ((ti->hblank_hi << 8) | \
ti->hblank_lo);
mode->vsync_start = \
mode->vdisplay + ((ti->vsync_offset_hi << 8) | \
ti->vsync_offset_lo);
mode->vsync_end = \
mode->vsync_start + ((ti->vsync_pulse_width_hi << 8) | \
ti->vsync_pulse_width_lo);
mode->vtotal = mode->vdisplay + \
((ti->vblank_hi << 8) | ti->vblank_lo);
mode->clock = ti->pixel_clock * 10;
dev_dbg(dev->dev, "hdisplay is %d\n", mode->hdisplay);
dev_dbg(dev->dev, "vdisplay is %d\n", mode->vdisplay);
dev_dbg(dev->dev, "HSS is %d\n", mode->hsync_start);
dev_dbg(dev->dev, "HSE is %d\n", mode->hsync_end);
dev_dbg(dev->dev, "htotal is %d\n", mode->htotal);
dev_dbg(dev->dev, "VSS is %d\n", mode->vsync_start);
dev_dbg(dev->dev, "VSE is %d\n", mode->vsync_end);
dev_dbg(dev->dev, "vtotal is %d\n", mode->vtotal);
dev_dbg(dev->dev, "clock is %d\n", mode->clock);
} else {
mode->hdisplay = 480;
mode->vdisplay = 854;
mode->hsync_start = 487;
mode->hsync_end = 490;
mode->htotal = 499;
mode->vsync_start = 861;
mode->vsync_end = 865;
mode->vtotal = 873;
mode->clock = 33264;
}
drm_mode_set_name(mode);
drm_mode_set_crtcinfo(mode, 0);
mode->type |= DRM_MODE_TYPE_PREFERRED;
return mode;
}
static int tmd_vid_get_panel_info(struct drm_device *dev,
int pipe,
struct panel_info *pi)
{
if (!dev || !pi)
return -EINVAL;
pi->width_mm = TMD_PANEL_WIDTH;
pi->height_mm = TMD_PANEL_HEIGHT;
return 0;
}
/* ************************************************************************* *\
* FUNCTION: mdfld_init_TMD_MIPI
*
* DESCRIPTION: This function is called only by mrst_dsi_mode_set and
* restore_display_registers. since this function does not
* acquire the mutex, it is important that the calling function
* does!
\* ************************************************************************* */
/* FIXME: make the below data u8 instead of u32; note byte order! */
static u32 tmd_cmd_mcap_off[] = {0x000000b2};
static u32 tmd_cmd_enable_lane_switch[] = {0x000101ef};
static u32 tmd_cmd_set_lane_num[] = {0x006360ef};
static u32 tmd_cmd_pushing_clock0[] = {0x00cc2fef};
static u32 tmd_cmd_pushing_clock1[] = {0x00dd6eef};
static u32 tmd_cmd_set_mode[] = {0x000000b3};
static u32 tmd_cmd_set_sync_pulse_mode[] = {0x000961ef};
static u32 tmd_cmd_set_column[] = {0x0100002a, 0x000000df};
static u32 tmd_cmd_set_page[] = {0x0300002b, 0x00000055};
static u32 tmd_cmd_set_video_mode[] = {0x00000153};
/*no auto_bl,need add in furture*/
static u32 tmd_cmd_enable_backlight[] = {0x00005ab4};
static u32 tmd_cmd_set_backlight_dimming[] = {0x00000ebd};
static void mdfld_dsi_tmd_drv_ic_init(struct mdfld_dsi_config *dsi_config,
int pipe)
{
struct mdfld_dsi_pkg_sender *sender
= mdfld_dsi_get_pkg_sender(dsi_config);
DRM_INFO("Enter mdfld init TMD MIPI display.\n");
if (!sender) {
DRM_ERROR("Cannot get sender\n");
return;
}
if (dsi_config->dvr_ic_inited)
return;
msleep(3);
/* FIXME: make the below data u8 instead of u32; note byte order! */
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_mcap_off,
sizeof(tmd_cmd_mcap_off), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_enable_lane_switch,
sizeof(tmd_cmd_enable_lane_switch), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_set_lane_num,
sizeof(tmd_cmd_set_lane_num), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_pushing_clock0,
sizeof(tmd_cmd_pushing_clock0), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_pushing_clock1,
sizeof(tmd_cmd_pushing_clock1), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_set_mode,
sizeof(tmd_cmd_set_mode), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_set_sync_pulse_mode,
sizeof(tmd_cmd_set_sync_pulse_mode), false);
mdfld_dsi_send_mcs_long(sender, (u8 *) tmd_cmd_set_column,
sizeof(tmd_cmd_set_column), false);
mdfld_dsi_send_mcs_long(sender, (u8 *) tmd_cmd_set_page,
sizeof(tmd_cmd_set_page), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_set_video_mode,
sizeof(tmd_cmd_set_video_mode), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_enable_backlight,
sizeof(tmd_cmd_enable_backlight), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_set_backlight_dimming,
sizeof(tmd_cmd_set_backlight_dimming), false);
dsi_config->dvr_ic_inited = 1;
}
/*TPO DPI encoder helper funcs*/
static const struct drm_encoder_helper_funcs
mdfld_tpo_dpi_encoder_helper_funcs = {
.dpms = mdfld_dsi_dpi_dpms,
.mode_fixup = mdfld_dsi_dpi_mode_fixup,
.prepare = mdfld_dsi_dpi_prepare,
.mode_set = mdfld_dsi_dpi_mode_set,
.commit = mdfld_dsi_dpi_commit,
};
/*TPO DPI encoder funcs*/
static const struct drm_encoder_funcs mdfld_tpo_dpi_encoder_funcs = {
.destroy = drm_encoder_cleanup,
};
const struct panel_funcs mdfld_tmd_vid_funcs = {
.encoder_funcs = &mdfld_tpo_dpi_encoder_funcs,
.encoder_helper_funcs = &mdfld_tpo_dpi_encoder_helper_funcs,
.get_config_mode = &tmd_vid_get_config_mode,
.get_panel_info = tmd_vid_get_panel_info,
.reset = mdfld_dsi_panel_reset,
.drv_ic_init = mdfld_dsi_tmd_drv_ic_init,
};
| gpl-2.0 |
lbule/ALPS.L0.MP6.V3.18_LCSH6795_LWT_L_KERNEL | arch/sh/kernel/cpu/sh5/probe.c | 10534 | 2215 | /*
* arch/sh/kernel/cpu/sh5/probe.c
*
* CPU Subtype Probing for SH-5.
*
* Copyright (C) 2000, 2001 Paolo Alberelli
* Copyright (C) 2003 - 2007 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/init.h>
#include <linux/io.h>
#include <linux/string.h>
#include <asm/processor.h>
#include <asm/cache.h>
#include <asm/tlb.h>
void __cpuinit cpu_probe(void)
{
unsigned long long cir;
/*
* Do peeks in real mode to avoid having to set up a mapping for
* the WPC registers. On SH5-101 cut2, such a mapping would be
* exposed to an address translation erratum which would make it
* hard to set up correctly.
*/
cir = peek_real_address_q(0x0d000008);
if ((cir & 0xffff) == 0x5103)
boot_cpu_data.type = CPU_SH5_103;
else if (((cir >> 32) & 0xffff) == 0x51e2)
/* CPU.VCR aliased at CIR address on SH5-101 */
boot_cpu_data.type = CPU_SH5_101;
boot_cpu_data.family = CPU_FAMILY_SH5;
/*
* First, setup some sane values for the I-cache.
*/
boot_cpu_data.icache.ways = 4;
boot_cpu_data.icache.sets = 256;
boot_cpu_data.icache.linesz = L1_CACHE_BYTES;
boot_cpu_data.icache.way_incr = (1 << 13);
boot_cpu_data.icache.entry_shift = 5;
boot_cpu_data.icache.way_size = boot_cpu_data.icache.sets *
boot_cpu_data.icache.linesz;
boot_cpu_data.icache.entry_mask = 0x1fe0;
boot_cpu_data.icache.flags = 0;
/*
* Next, setup some sane values for the D-cache.
*
* On the SH5, these are pretty consistent with the I-cache settings,
* so we just copy over the existing definitions.. these can be fixed
* up later, especially if we add runtime CPU probing.
*
* Though in the meantime it saves us from having to duplicate all of
* the above definitions..
*/
boot_cpu_data.dcache = boot_cpu_data.icache;
/*
* Setup any cache-related flags here
*/
#if defined(CONFIG_CACHE_WRITETHROUGH)
set_bit(SH_CACHE_MODE_WT, &(boot_cpu_data.dcache.flags));
#elif defined(CONFIG_CACHE_WRITEBACK)
set_bit(SH_CACHE_MODE_WB, &(boot_cpu_data.dcache.flags));
#endif
/* Setup some I/D TLB defaults */
sh64_tlb_init();
}
| gpl-2.0 |
MaxiCM-Test/android_kernel_lge_msm8226 | arch/powerpc/boot/serial.c | 12326 | 3633 | /*
* Generic serial console support
*
* Author: Mark A. Greer <mgreer@mvista.com>
*
* Code in serial_edit_cmdline() copied from <file:arch/ppc/boot/simple/misc.c>
* and was written by Matt Porter <mporter@kernel.crashing.org>.
*
* 2001,2006 (c) MontaVista Software, Inc. This file is licensed under
* the terms of the GNU General Public License version 2. This program
* is licensed "as is" without any warranty of any kind, whether express
* or implied.
*/
#include <stdarg.h>
#include <stddef.h>
#include "types.h"
#include "string.h"
#include "stdio.h"
#include "io.h"
#include "ops.h"
static int serial_open(void)
{
struct serial_console_data *scdp = console_ops.data;
return scdp->open();
}
static void serial_write(const char *buf, int len)
{
struct serial_console_data *scdp = console_ops.data;
while (*buf != '\0')
scdp->putc(*buf++);
}
static void serial_edit_cmdline(char *buf, int len)
{
int timer = 0, count;
char ch, *cp;
struct serial_console_data *scdp = console_ops.data;
cp = buf;
count = strlen(buf);
cp = &buf[count];
count++;
while (timer++ < 5*1000) {
if (scdp->tstc()) {
while (((ch = scdp->getc()) != '\n') && (ch != '\r')) {
/* Test for backspace/delete */
if ((ch == '\b') || (ch == '\177')) {
if (cp != buf) {
cp--;
count--;
printf("\b \b");
}
/* Test for ^x/^u (and wipe the line) */
} else if ((ch == '\030') || (ch == '\025')) {
while (cp != buf) {
cp--;
count--;
printf("\b \b");
}
} else if (count < len) {
*cp++ = ch;
count++;
scdp->putc(ch);
}
}
break; /* Exit 'timer' loop */
}
udelay(1000); /* 1 msec */
}
*cp = 0;
}
static void serial_close(void)
{
struct serial_console_data *scdp = console_ops.data;
if (scdp->close)
scdp->close();
}
static void *serial_get_stdout_devp(void)
{
void *devp;
char devtype[MAX_PROP_LEN];
char path[MAX_PATH_LEN];
devp = finddevice("/chosen");
if (devp == NULL)
goto err_out;
if (getprop(devp, "linux,stdout-path", path, MAX_PATH_LEN) > 0) {
devp = finddevice(path);
if (devp == NULL)
goto err_out;
if ((getprop(devp, "device_type", devtype, sizeof(devtype)) > 0)
&& !strcmp(devtype, "serial"))
return devp;
}
err_out:
return NULL;
}
static struct serial_console_data serial_cd;
/* Node's "compatible" property determines which serial driver to use */
int serial_console_init(void)
{
void *devp;
int rc = -1;
devp = serial_get_stdout_devp();
if (devp == NULL)
goto err_out;
if (dt_is_compatible(devp, "ns16550") ||
dt_is_compatible(devp, "pnpPNP,501"))
rc = ns16550_console_init(devp, &serial_cd);
else if (dt_is_compatible(devp, "marvell,mv64360-mpsc"))
rc = mpsc_console_init(devp, &serial_cd);
else if (dt_is_compatible(devp, "fsl,cpm1-scc-uart") ||
dt_is_compatible(devp, "fsl,cpm1-smc-uart") ||
dt_is_compatible(devp, "fsl,cpm2-scc-uart") ||
dt_is_compatible(devp, "fsl,cpm2-smc-uart"))
rc = cpm_console_init(devp, &serial_cd);
else if (dt_is_compatible(devp, "fsl,mpc5200-psc-uart"))
rc = mpc5200_psc_console_init(devp, &serial_cd);
else if (dt_is_compatible(devp, "xlnx,opb-uartlite-1.00.b") ||
dt_is_compatible(devp, "xlnx,xps-uartlite-1.00.a"))
rc = uartlite_console_init(devp, &serial_cd);
/* Add other serial console driver calls here */
if (!rc) {
console_ops.open = serial_open;
console_ops.write = serial_write;
console_ops.close = serial_close;
console_ops.data = &serial_cd;
if (serial_cd.getc)
console_ops.edit_cmdline = serial_edit_cmdline;
return 0;
}
err_out:
return -1;
}
| gpl-2.0 |
janrinze/loox7xxport.loox2-6-22 | fs/adfs/super.c | 39 | 11910 | /*
* linux/fs/adfs/super.c
*
* Copyright (C) 1997-1999 Russell King
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/adfs_fs.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/stat.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/buffer_head.h>
#include <linux/vfs.h>
#include <linux/parser.h>
#include <linux/bitops.h>
#include <asm/uaccess.h>
#include <asm/system.h>
#include <stdarg.h>
#include "adfs.h"
#include "dir_f.h"
#include "dir_fplus.h"
void __adfs_error(struct super_block *sb, const char *function, const char *fmt, ...)
{
char error_buf[128];
va_list args;
va_start(args, fmt);
vsnprintf(error_buf, sizeof(error_buf), fmt, args);
va_end(args);
printk(KERN_CRIT "ADFS-fs error (device %s)%s%s: %s\n",
sb->s_id, function ? ": " : "",
function ? function : "", error_buf);
}
static int adfs_checkdiscrecord(struct adfs_discrecord *dr)
{
int i;
/* sector size must be 256, 512 or 1024 bytes */
if (dr->log2secsize != 8 &&
dr->log2secsize != 9 &&
dr->log2secsize != 10)
return 1;
/* idlen must be at least log2secsize + 3 */
if (dr->idlen < dr->log2secsize + 3)
return 1;
/* we cannot have such a large disc that we
* are unable to represent sector offsets in
* 32 bits. This works out at 2.0 TB.
*/
if (le32_to_cpu(dr->disc_size_high) >> dr->log2secsize)
return 1;
/* idlen must be no greater than 19 v2 [1.0] */
if (dr->idlen > 19)
return 1;
/* reserved bytes should be zero */
for (i = 0; i < sizeof(dr->unused52); i++)
if (dr->unused52[i] != 0)
return 1;
return 0;
}
static unsigned char adfs_calczonecheck(struct super_block *sb, unsigned char *map)
{
unsigned int v0, v1, v2, v3;
int i;
v0 = v1 = v2 = v3 = 0;
for (i = sb->s_blocksize - 4; i; i -= 4) {
v0 += map[i] + (v3 >> 8);
v3 &= 0xff;
v1 += map[i + 1] + (v0 >> 8);
v0 &= 0xff;
v2 += map[i + 2] + (v1 >> 8);
v1 &= 0xff;
v3 += map[i + 3] + (v2 >> 8);
v2 &= 0xff;
}
v0 += v3 >> 8;
v1 += map[1] + (v0 >> 8);
v2 += map[2] + (v1 >> 8);
v3 += map[3] + (v2 >> 8);
return v0 ^ v1 ^ v2 ^ v3;
}
static int adfs_checkmap(struct super_block *sb, struct adfs_discmap *dm)
{
unsigned char crosscheck = 0, zonecheck = 1;
int i;
for (i = 0; i < ADFS_SB(sb)->s_map_size; i++) {
unsigned char *map;
map = dm[i].dm_bh->b_data;
if (adfs_calczonecheck(sb, map) != map[0]) {
adfs_error(sb, "zone %d fails zonecheck", i);
zonecheck = 0;
}
crosscheck ^= map[3];
}
if (crosscheck != 0xff)
adfs_error(sb, "crosscheck != 0xff");
return crosscheck == 0xff && zonecheck;
}
static void adfs_put_super(struct super_block *sb)
{
int i;
struct adfs_sb_info *asb = ADFS_SB(sb);
for (i = 0; i < asb->s_map_size; i++)
brelse(asb->s_map[i].dm_bh);
kfree(asb->s_map);
kfree(asb);
sb->s_fs_info = NULL;
}
enum {Opt_uid, Opt_gid, Opt_ownmask, Opt_othmask, Opt_err};
static match_table_t tokens = {
{Opt_uid, "uid=%u"},
{Opt_gid, "gid=%u"},
{Opt_ownmask, "ownmask=%o"},
{Opt_othmask, "othmask=%o"},
{Opt_err, NULL}
};
static int parse_options(struct super_block *sb, char *options)
{
char *p;
struct adfs_sb_info *asb = ADFS_SB(sb);
int option;
if (!options)
return 0;
while ((p = strsep(&options, ",")) != NULL) {
substring_t args[MAX_OPT_ARGS];
int token;
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case Opt_uid:
if (match_int(args, &option))
return -EINVAL;
asb->s_uid = option;
break;
case Opt_gid:
if (match_int(args, &option))
return -EINVAL;
asb->s_gid = option;
break;
case Opt_ownmask:
if (match_octal(args, &option))
return -EINVAL;
asb->s_owner_mask = option;
break;
case Opt_othmask:
if (match_octal(args, &option))
return -EINVAL;
asb->s_other_mask = option;
break;
default:
printk("ADFS-fs: unrecognised mount option \"%s\" "
"or missing value\n", p);
return -EINVAL;
}
}
return 0;
}
static int adfs_remount(struct super_block *sb, int *flags, char *data)
{
*flags |= MS_NODIRATIME;
return parse_options(sb, data);
}
static int adfs_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct adfs_sb_info *asb = ADFS_SB(dentry->d_sb);
buf->f_type = ADFS_SUPER_MAGIC;
buf->f_namelen = asb->s_namelen;
buf->f_bsize = dentry->d_sb->s_blocksize;
buf->f_blocks = asb->s_size;
buf->f_files = asb->s_ids_per_zone * asb->s_map_size;
buf->f_bavail =
buf->f_bfree = adfs_map_free(dentry->d_sb);
buf->f_ffree = (long)(buf->f_bfree * buf->f_files) / (long)buf->f_blocks;
return 0;
}
static struct kmem_cache *adfs_inode_cachep;
static struct inode *adfs_alloc_inode(struct super_block *sb)
{
struct adfs_inode_info *ei;
ei = (struct adfs_inode_info *)kmem_cache_alloc(adfs_inode_cachep, GFP_KERNEL);
if (!ei)
return NULL;
return &ei->vfs_inode;
}
static void adfs_destroy_inode(struct inode *inode)
{
kmem_cache_free(adfs_inode_cachep, ADFS_I(inode));
}
static void init_once(void * foo, struct kmem_cache * cachep, unsigned long flags)
{
struct adfs_inode_info *ei = (struct adfs_inode_info *) foo;
inode_init_once(&ei->vfs_inode);
}
static int init_inodecache(void)
{
adfs_inode_cachep = kmem_cache_create("adfs_inode_cache",
sizeof(struct adfs_inode_info),
0, (SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD),
init_once, NULL);
if (adfs_inode_cachep == NULL)
return -ENOMEM;
return 0;
}
static void destroy_inodecache(void)
{
kmem_cache_destroy(adfs_inode_cachep);
}
static const struct super_operations adfs_sops = {
.alloc_inode = adfs_alloc_inode,
.destroy_inode = adfs_destroy_inode,
.write_inode = adfs_write_inode,
.put_super = adfs_put_super,
.statfs = adfs_statfs,
.remount_fs = adfs_remount,
};
static struct adfs_discmap *adfs_read_map(struct super_block *sb, struct adfs_discrecord *dr)
{
struct adfs_discmap *dm;
unsigned int map_addr, zone_size, nzones;
int i, zone;
struct adfs_sb_info *asb = ADFS_SB(sb);
nzones = asb->s_map_size;
zone_size = (8 << dr->log2secsize) - le16_to_cpu(dr->zone_spare);
map_addr = (nzones >> 1) * zone_size -
((nzones > 1) ? ADFS_DR_SIZE_BITS : 0);
map_addr = signed_asl(map_addr, asb->s_map2blk);
asb->s_ids_per_zone = zone_size / (asb->s_idlen + 1);
dm = kmalloc(nzones * sizeof(*dm), GFP_KERNEL);
if (dm == NULL) {
adfs_error(sb, "not enough memory");
return NULL;
}
for (zone = 0; zone < nzones; zone++, map_addr++) {
dm[zone].dm_startbit = 0;
dm[zone].dm_endbit = zone_size;
dm[zone].dm_startblk = zone * zone_size - ADFS_DR_SIZE_BITS;
dm[zone].dm_bh = sb_bread(sb, map_addr);
if (!dm[zone].dm_bh) {
adfs_error(sb, "unable to read map");
goto error_free;
}
}
/* adjust the limits for the first and last map zones */
i = zone - 1;
dm[0].dm_startblk = 0;
dm[0].dm_startbit = ADFS_DR_SIZE_BITS;
dm[i].dm_endbit = (le32_to_cpu(dr->disc_size_high) << (32 - dr->log2bpmb)) +
(le32_to_cpu(dr->disc_size) >> dr->log2bpmb) +
(ADFS_DR_SIZE_BITS - i * zone_size);
if (adfs_checkmap(sb, dm))
return dm;
adfs_error(sb, "map corrupted");
error_free:
while (--zone >= 0)
brelse(dm[zone].dm_bh);
kfree(dm);
return NULL;
}
static inline unsigned long adfs_discsize(struct adfs_discrecord *dr, int block_bits)
{
unsigned long discsize;
discsize = le32_to_cpu(dr->disc_size_high) << (32 - block_bits);
discsize |= le32_to_cpu(dr->disc_size) >> block_bits;
return discsize;
}
static int adfs_fill_super(struct super_block *sb, void *data, int silent)
{
struct adfs_discrecord *dr;
struct buffer_head *bh;
struct object_info root_obj;
unsigned char *b_data;
struct adfs_sb_info *asb;
struct inode *root;
sb->s_flags |= MS_NODIRATIME;
asb = kzalloc(sizeof(*asb), GFP_KERNEL);
if (!asb)
return -ENOMEM;
sb->s_fs_info = asb;
/* set default options */
asb->s_uid = 0;
asb->s_gid = 0;
asb->s_owner_mask = S_IRWXU;
asb->s_other_mask = S_IRWXG | S_IRWXO;
if (parse_options(sb, data))
goto error;
sb_set_blocksize(sb, BLOCK_SIZE);
if (!(bh = sb_bread(sb, ADFS_DISCRECORD / BLOCK_SIZE))) {
adfs_error(sb, "unable to read superblock");
goto error;
}
b_data = bh->b_data + (ADFS_DISCRECORD % BLOCK_SIZE);
if (adfs_checkbblk(b_data)) {
if (!silent)
printk("VFS: Can't find an adfs filesystem on dev "
"%s.\n", sb->s_id);
goto error_free_bh;
}
dr = (struct adfs_discrecord *)(b_data + ADFS_DR_OFFSET);
/*
* Do some sanity checks on the ADFS disc record
*/
if (adfs_checkdiscrecord(dr)) {
if (!silent)
printk("VPS: Can't find an adfs filesystem on dev "
"%s.\n", sb->s_id);
goto error_free_bh;
}
brelse(bh);
if (sb_set_blocksize(sb, 1 << dr->log2secsize)) {
bh = sb_bread(sb, ADFS_DISCRECORD / sb->s_blocksize);
if (!bh) {
adfs_error(sb, "couldn't read superblock on "
"2nd try.");
goto error;
}
b_data = bh->b_data + (ADFS_DISCRECORD % sb->s_blocksize);
if (adfs_checkbblk(b_data)) {
adfs_error(sb, "disc record mismatch, very weird!");
goto error_free_bh;
}
dr = (struct adfs_discrecord *)(b_data + ADFS_DR_OFFSET);
} else {
if (!silent)
printk(KERN_ERR "VFS: Unsupported blocksize on dev "
"%s.\n", sb->s_id);
goto error;
}
/*
* blocksize on this device should now be set to the ADFS log2secsize
*/
sb->s_magic = ADFS_SUPER_MAGIC;
asb->s_idlen = dr->idlen;
asb->s_map_size = dr->nzones | (dr->nzones_high << 8);
asb->s_map2blk = dr->log2bpmb - dr->log2secsize;
asb->s_size = adfs_discsize(dr, sb->s_blocksize_bits);
asb->s_version = dr->format_version;
asb->s_log2sharesize = dr->log2sharesize;
asb->s_map = adfs_read_map(sb, dr);
if (!asb->s_map)
goto error_free_bh;
brelse(bh);
/*
* set up enough so that we can read an inode
*/
sb->s_op = &adfs_sops;
dr = (struct adfs_discrecord *)(asb->s_map[0].dm_bh->b_data + 4);
root_obj.parent_id = root_obj.file_id = le32_to_cpu(dr->root);
root_obj.name_len = 0;
root_obj.loadaddr = 0;
root_obj.execaddr = 0;
root_obj.size = ADFS_NEWDIR_SIZE;
root_obj.attr = ADFS_NDA_DIRECTORY | ADFS_NDA_OWNER_READ |
ADFS_NDA_OWNER_WRITE | ADFS_NDA_PUBLIC_READ;
/*
* If this is a F+ disk with variable length directories,
* get the root_size from the disc record.
*/
if (asb->s_version) {
root_obj.size = le32_to_cpu(dr->root_size);
asb->s_dir = &adfs_fplus_dir_ops;
asb->s_namelen = ADFS_FPLUS_NAME_LEN;
} else {
asb->s_dir = &adfs_f_dir_ops;
asb->s_namelen = ADFS_F_NAME_LEN;
}
root = adfs_iget(sb, &root_obj);
sb->s_root = d_alloc_root(root);
if (!sb->s_root) {
int i;
iput(root);
for (i = 0; i < asb->s_map_size; i++)
brelse(asb->s_map[i].dm_bh);
kfree(asb->s_map);
adfs_error(sb, "get root inode failed\n");
goto error;
} else
sb->s_root->d_op = &adfs_dentry_operations;
return 0;
error_free_bh:
brelse(bh);
error:
sb->s_fs_info = NULL;
kfree(asb);
return -EINVAL;
}
static int adfs_get_sb(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data, struct vfsmount *mnt)
{
return get_sb_bdev(fs_type, flags, dev_name, data, adfs_fill_super,
mnt);
}
static struct file_system_type adfs_fs_type = {
.owner = THIS_MODULE,
.name = "adfs",
.get_sb = adfs_get_sb,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
static int __init init_adfs_fs(void)
{
int err = init_inodecache();
if (err)
goto out1;
err = register_filesystem(&adfs_fs_type);
if (err)
goto out;
return 0;
out:
destroy_inodecache();
out1:
return err;
}
static void __exit exit_adfs_fs(void)
{
unregister_filesystem(&adfs_fs_type);
destroy_inodecache();
}
module_init(init_adfs_fs)
module_exit(exit_adfs_fs)
| gpl-2.0 |
dnh34/proj1 | kernel/utsname.c | 39 | 1448 | /*
* Copyright (C) 2004 IBM Corporation
*
* Author: Serge Hallyn <serue@us.ibm.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2 of the
* License.
*/
#include <linux/module.h>
#include <linux/uts.h>
#include <linux/utsname.h>
#include <linux/version.h>
/*
* Clone a new ns copying an original utsname, setting refcount to 1
* @old_ns: namespace to clone
* Return NULL on error (failure to kmalloc), new ns otherwise
*/
static struct uts_namespace *clone_uts_ns(struct uts_namespace *old_ns)
{
struct uts_namespace *ns;
ns = kmalloc(sizeof(struct uts_namespace), GFP_KERNEL);
if (ns) {
memcpy(&ns->name, &old_ns->name, sizeof(ns->name));
kref_init(&ns->kref);
}
return ns;
}
/*
* Copy task tsk's utsname namespace, or clone it if flags
* specifies CLONE_NEWUTS. In latter case, changes to the
* utsname of this process won't be seen by parent, and vice
* versa.
*/
struct uts_namespace *copy_utsname(int flags, struct uts_namespace *old_ns)
{
struct uts_namespace *new_ns;
BUG_ON(!old_ns);
get_uts_ns(old_ns);
if (!(flags & CLONE_NEWUTS))
return old_ns;
new_ns = clone_uts_ns(old_ns);
put_uts_ns(old_ns);
return new_ns;
}
void free_uts_ns(struct kref *kref)
{
struct uts_namespace *ns;
ns = container_of(kref, struct uts_namespace, kref);
kfree(ns);
}
| gpl-2.0 |
Dronevery/JetsonTK1-kernel | arch/m68knommu/platform/5307/vectors.c | 39 | 2264 | /***************************************************************************/
/*
* linux/arch/m68knommu/platform/5307/vectors.c
*
* Copyright (C) 1999-2003, Greg Ungerer <gerg@snapgear.com>
*/
/***************************************************************************/
#include <linux/config.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/param.h>
#include <linux/init.h>
#include <linux/unistd.h>
#include <linux/delay.h>
#include <asm/irq.h>
#include <asm/dma.h>
#include <asm/traps.h>
#include <asm/machdep.h>
#include <asm/coldfire.h>
#include <asm/mcftimer.h>
#include <asm/mcfsim.h>
#include <asm/mcfdma.h>
#include <asm/mcfwdebug.h>
/***************************************************************************/
#ifdef TRAP_DBG_INTERRUPT
asmlinkage void dbginterrupt_c(struct frame *fp)
{
extern void dump(struct pt_regs *fp);
printk(KERN_DEBUG "%s(%d): BUS ERROR TRAP\n", __FILE__, __LINE__);
dump((struct pt_regs *) fp);
asm("halt");
}
#endif
/***************************************************************************/
extern e_vector *_ramvec;
void set_evector(int vecnum, void (*handler)(void))
{
if (vecnum >= 0 && vecnum <= 255)
_ramvec[vecnum] = handler;
}
/***************************************************************************/
/* Assembler routines */
asmlinkage void buserr(void);
asmlinkage void trap(void);
asmlinkage void system_call(void);
asmlinkage void inthandler(void);
void __init coldfire_trap_init(void)
{
int i;
/*
* There is a common trap handler and common interrupt
* handler that handle almost every vector. We treat
* the system call and bus error special, they get their
* own first level handlers.
*/
for (i = 3; (i <= 23); i++)
_ramvec[i] = trap;
for (i = 33; (i <= 63); i++)
_ramvec[i] = trap;
for (i = 24; (i <= 31); i++)
_ramvec[i] = inthandler;
for (i = 64; (i < 255); i++)
_ramvec[i] = inthandler;
_ramvec[255] = 0;
_ramvec[2] = buserr;
_ramvec[32] = system_call;
#ifdef TRAP_DBG_INTERRUPT
_ramvec[12] = dbginterrupt;
#endif
}
/***************************************************************************/
void coldfire_reset(void)
{
HARD_RESET_NOW();
}
/***************************************************************************/
| gpl-2.0 |
bftg/binutils-2.25 | gas/config/tc-tilepro.c | 39 | 44477 | /* tc-tilepro.c -- Assemble for a TILEPro chip.
Copyright (C) 2011-2014 Free Software Foundation, Inc.
This file is part of GAS, the GNU Assembler.
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. */
#include "as.h"
#include "struc-symbol.h"
#include "subsegs.h"
#include "elf/tilepro.h"
#include "opcode/tilepro.h"
#include "dwarf2dbg.h"
#include "dw2gencfi.h"
#include "safe-ctype.h"
/* Special registers. */
#define TREG_IDN0 57
#define TREG_IDN1 58
#define TREG_UDN0 59
#define TREG_UDN1 60
#define TREG_UDN2 61
#define TREG_UDN3 62
#define TREG_ZERO 63
/* Generic assembler global variables which must be defined by all
targets. */
/* Characters which always start a comment. */
const char comment_chars[] = "#";
/* Characters which start a comment at the beginning of a line. */
const char line_comment_chars[] = "#";
/* Characters which may be used to separate multiple commands on a
single line. */
const char line_separator_chars[] = ";";
/* Characters which are used to indicate an exponent in a floating
point number. */
const char EXP_CHARS[] = "eE";
/* Characters which mean that a number is a floating point constant,
as in 0d1.0. */
const char FLT_CHARS[] = "rRsSfFdDxXpP";
const char *md_shortopts = "VQ:";
struct option md_longopts[] =
{
{NULL, no_argument, NULL, 0}
};
size_t md_longopts_size = sizeof (md_longopts);
int
md_parse_option (int c, char *arg ATTRIBUTE_UNUSED)
{
switch (c)
{
/* -Qy, -Qn: SVR4 arguments controlling whether a .comment section
should be emitted or not. FIXME: Not implemented. */
case 'Q':
break;
/* -V: SVR4 argument to print version ID. */
case 'V':
print_version_id ();
break;
default:
return 0;
}
return 1;
}
void
md_show_usage (FILE *stream)
{
fprintf (stream, _("\
-Q ignored\n\
-V print assembler version number\n"));
}
/* Extra expression types. */
#define O_lo16 O_md1
#define O_hi16 O_md2
#define O_ha16 O_md3
#define O_got O_md4
#define O_got_lo16 O_md5
#define O_got_hi16 O_md6
#define O_got_ha16 O_md7
#define O_plt O_md8
#define O_tls_gd O_md9
#define O_tls_gd_lo16 O_md10
#define O_tls_gd_hi16 O_md11
#define O_tls_gd_ha16 O_md12
#define O_tls_ie O_md13
#define O_tls_ie_lo16 O_md14
#define O_tls_ie_hi16 O_md15
#define O_tls_ie_ha16 O_md16
#define O_tls_le O_md17
#define O_tls_le_lo16 O_md18
#define O_tls_le_hi16 O_md19
#define O_tls_le_ha16 O_md20
#define O_tls_gd_call O_md21
#define O_tls_gd_add O_md22
#define O_tls_ie_load O_md23
static struct hash_control *special_operator_hash;
/* Hash tables for instruction mnemonic lookup. */
static struct hash_control *op_hash;
/* Hash table for spr lookup. */
static struct hash_control *spr_hash;
/* True temporarily while parsing an SPR expression. This changes the
* namespace to include SPR names. */
static int parsing_spr;
/* Are we currently inside `{ ... }'? */
static int inside_bundle;
struct tilepro_instruction
{
const struct tilepro_opcode *opcode;
tilepro_pipeline pipe;
expressionS operand_values[TILEPRO_MAX_OPERANDS];
};
/* This keeps track of the current bundle being built up. */
static struct tilepro_instruction
current_bundle[TILEPRO_MAX_INSTRUCTIONS_PER_BUNDLE];
/* Index in current_bundle for the next instruction to parse. */
static int current_bundle_index;
/* Allow 'r63' in addition to 'zero', etc. Normally we disallow this as
'zero' is not a real register, so using it accidentally would be a
nasty bug. For other registers, such as 'sp', code using multiple names
for the same physical register is excessively confusing.
The '.require_canonical_reg_names' pseudo-op turns this error on,
and the '.no_require_canonical_reg_names' pseudo-op turns this off.
By default the error is on. */
static int require_canonical_reg_names;
/* Allow bundles that do undefined or suspicious things like write
two different values to the same register at the same time.
The '.no_allow_suspicious_bundles' pseudo-op turns this error on,
and the '.allow_suspicious_bundles' pseudo-op turns this off. */
static int allow_suspicious_bundles;
/* A hash table of main processor registers, mapping each register name
to its index.
Furthermore, if the register number is greater than the number
of registers for that processor, the user used an illegal alias
for that register (e.g. r63 instead of zero), so we should generate
a warning. The attempted register number can be found by clearing
NONCANONICAL_REG_NAME_FLAG. */
static struct hash_control *main_reg_hash;
/* We cannot unambiguously store a 0 in a hash table and look it up,
so we OR in this flag to every canonical register. */
#define CANONICAL_REG_NAME_FLAG 0x1000
/* By default we disallow register aliases like r63, but we record
them in the hash table in case the .no_require_canonical_reg_names
directive is used. Noncanonical names have this value added to them. */
#define NONCANONICAL_REG_NAME_FLAG 0x2000
/* Discards flags for register hash table entries and returns the
reg number. */
#define EXTRACT_REGNO(p) ((p) & 63)
/* This function is called once, at assembler startup time. It should
set up all the tables, etc., that the MD part of the assembler will
need. */
void
md_begin (void)
{
const struct tilepro_opcode *op;
int i;
/* Guarantee text section is aligned. */
bfd_set_section_alignment (stdoutput, text_section,
TILEPRO_LOG2_BUNDLE_ALIGNMENT_IN_BYTES);
require_canonical_reg_names = 1;
allow_suspicious_bundles = 0;
current_bundle_index = 0;
inside_bundle = 0;
/* Initialize special operator hash table. */
special_operator_hash = hash_new ();
#define INSERT_SPECIAL_OP(name) \
hash_insert (special_operator_hash, #name, (void *)O_##name)
INSERT_SPECIAL_OP(lo16);
INSERT_SPECIAL_OP(hi16);
INSERT_SPECIAL_OP(ha16);
INSERT_SPECIAL_OP(got);
INSERT_SPECIAL_OP(got_lo16);
INSERT_SPECIAL_OP(got_hi16);
INSERT_SPECIAL_OP(got_ha16);
INSERT_SPECIAL_OP(plt);
INSERT_SPECIAL_OP(tls_gd);
INSERT_SPECIAL_OP(tls_gd_lo16);
INSERT_SPECIAL_OP(tls_gd_hi16);
INSERT_SPECIAL_OP(tls_gd_ha16);
INSERT_SPECIAL_OP(tls_ie);
INSERT_SPECIAL_OP(tls_ie_lo16);
INSERT_SPECIAL_OP(tls_ie_hi16);
INSERT_SPECIAL_OP(tls_ie_ha16);
INSERT_SPECIAL_OP(tls_le);
INSERT_SPECIAL_OP(tls_le_lo16);
INSERT_SPECIAL_OP(tls_le_hi16);
INSERT_SPECIAL_OP(tls_le_ha16);
INSERT_SPECIAL_OP(tls_gd_call);
INSERT_SPECIAL_OP(tls_gd_add);
INSERT_SPECIAL_OP(tls_ie_load);
#undef INSERT_SPECIAL_OP
/* Initialize op_hash hash table. */
op_hash = hash_new ();
for (op = &tilepro_opcodes[0]; op->name != NULL; op++)
{
const char *hash_err = hash_insert (op_hash, op->name, (void *)op);
if (hash_err != NULL)
{
as_fatal (_("Internal Error: Can't hash %s: %s"),
op->name, hash_err);
}
}
/* Initialize the spr hash table. */
parsing_spr = 0;
spr_hash = hash_new ();
for (i = 0; i < tilepro_num_sprs; i++)
hash_insert (spr_hash, tilepro_sprs[i].name,
(void *) &tilepro_sprs[i]);
/* Set up the main_reg_hash table. We use this instead of
* creating a symbol in the register section to avoid ambiguities
* with labels that have the same names as registers. */
main_reg_hash = hash_new ();
for (i = 0; i < TILEPRO_NUM_REGISTERS; i++)
{
char buf[64];
hash_insert (main_reg_hash, tilepro_register_names[i],
(void *) (long)(i | CANONICAL_REG_NAME_FLAG));
/* See if we should insert a noncanonical alias, like r63. */
sprintf (buf, "r%d", i);
if (strcmp (buf, tilepro_register_names[i]) != 0)
hash_insert (main_reg_hash, xstrdup (buf),
(void *) (long)(i | NONCANONICAL_REG_NAME_FLAG));
}
/* Insert obsolete backwards-compatibility register names. */
hash_insert (main_reg_hash, "io0",
(void *) (long) (TREG_IDN0 | CANONICAL_REG_NAME_FLAG));
hash_insert (main_reg_hash, "io1",
(void *) (long) (TREG_IDN1 | CANONICAL_REG_NAME_FLAG));
hash_insert (main_reg_hash, "us0",
(void *) (long) (TREG_UDN0 | CANONICAL_REG_NAME_FLAG));
hash_insert (main_reg_hash, "us1",
(void *) (long) (TREG_UDN1 | CANONICAL_REG_NAME_FLAG));
hash_insert (main_reg_hash, "us2",
(void *) (long) (TREG_UDN2 | CANONICAL_REG_NAME_FLAG));
hash_insert (main_reg_hash, "us3",
(void *) (long) (TREG_UDN3 | CANONICAL_REG_NAME_FLAG));
}
#define BUNDLE_TEMPLATE_MASK(p0, p1, p2) \
((p0) | ((p1) << 8) | ((p2) << 16))
#define BUNDLE_TEMPLATE(p0, p1, p2) \
{ { (p0), (p1), (p2) }, \
BUNDLE_TEMPLATE_MASK(1 << (p0), 1 << (p1), (1 << (p2))) \
}
#define NO_PIPELINE TILEPRO_NUM_PIPELINE_ENCODINGS
struct bundle_template
{
tilepro_pipeline pipe[TILEPRO_MAX_INSTRUCTIONS_PER_BUNDLE];
unsigned int pipe_mask;
};
static const struct bundle_template bundle_templates[] =
{
/* In Y format we must always have something in Y2, since it has
* no fnop, so this conveys that Y2 must always be used. */
BUNDLE_TEMPLATE(TILEPRO_PIPELINE_Y0, TILEPRO_PIPELINE_Y2, NO_PIPELINE),
BUNDLE_TEMPLATE(TILEPRO_PIPELINE_Y1, TILEPRO_PIPELINE_Y2, NO_PIPELINE),
BUNDLE_TEMPLATE(TILEPRO_PIPELINE_Y2, TILEPRO_PIPELINE_Y0, NO_PIPELINE),
BUNDLE_TEMPLATE(TILEPRO_PIPELINE_Y2, TILEPRO_PIPELINE_Y1, NO_PIPELINE),
/* Y format has three instructions. */
BUNDLE_TEMPLATE(TILEPRO_PIPELINE_Y0, TILEPRO_PIPELINE_Y1, TILEPRO_PIPELINE_Y2),
BUNDLE_TEMPLATE(TILEPRO_PIPELINE_Y0, TILEPRO_PIPELINE_Y2, TILEPRO_PIPELINE_Y1),
BUNDLE_TEMPLATE(TILEPRO_PIPELINE_Y1, TILEPRO_PIPELINE_Y0, TILEPRO_PIPELINE_Y2),
BUNDLE_TEMPLATE(TILEPRO_PIPELINE_Y1, TILEPRO_PIPELINE_Y2, TILEPRO_PIPELINE_Y0),
BUNDLE_TEMPLATE(TILEPRO_PIPELINE_Y2, TILEPRO_PIPELINE_Y0, TILEPRO_PIPELINE_Y1),
BUNDLE_TEMPLATE(TILEPRO_PIPELINE_Y2, TILEPRO_PIPELINE_Y1, TILEPRO_PIPELINE_Y0),
/* X format has only two instructions. */
BUNDLE_TEMPLATE(TILEPRO_PIPELINE_X0, TILEPRO_PIPELINE_X1, NO_PIPELINE),
BUNDLE_TEMPLATE(TILEPRO_PIPELINE_X1, TILEPRO_PIPELINE_X0, NO_PIPELINE)
};
static void
prepend_nop_to_bundle (tilepro_mnemonic mnemonic)
{
memmove (¤t_bundle[1], ¤t_bundle[0],
current_bundle_index * sizeof current_bundle[0]);
current_bundle[0].opcode = &tilepro_opcodes[mnemonic];
++current_bundle_index;
}
static tilepro_bundle_bits
insert_operand (tilepro_bundle_bits bits,
const struct tilepro_operand *operand,
int operand_value,
char *file,
unsigned lineno)
{
/* Range-check the immediate. */
int num_bits = operand->num_bits;
operand_value >>= operand->rightshift;
if (bfd_check_overflow (operand->is_signed
? complain_overflow_signed
: complain_overflow_unsigned,
num_bits,
0,
bfd_arch_bits_per_address (stdoutput),
operand_value)
!= bfd_reloc_ok)
{
offsetT min, max;
if (operand->is_signed)
{
min = -(1 << (num_bits - 1));
max = (1 << (num_bits - 1)) - 1;
}
else
{
min = 0;
max = (1 << num_bits) - 1;
}
as_bad_value_out_of_range (_("operand"), operand_value, min, max,
file, lineno);
}
/* Write out the bits for the immediate. */
return bits | operand->insert (operand_value);
}
static int
apply_special_operator (operatorT op, int num)
{
switch (op)
{
case O_lo16:
return (signed short)num;
case O_hi16:
return (signed short)(num >> 16);
case O_ha16:
return (signed short)((num + 0x8000) >> 16);
default:
abort ();
}
}
static tilepro_bundle_bits
emit_tilepro_instruction (tilepro_bundle_bits bits,
int num_operands,
const unsigned char *operands,
expressionS *operand_values,
char *bundle_start)
{
int i;
for (i = 0; i < num_operands; i++)
{
const struct tilepro_operand *operand =
&tilepro_operands[operands[i]];
expressionS *operand_exp = &operand_values[i];
int is_pc_relative = operand->is_pc_relative;
if (operand_exp->X_op == O_register
|| (operand_exp->X_op == O_constant && !is_pc_relative))
{
/* We know what the bits are right now, so insert them. */
bits = insert_operand (bits, operand, operand_exp->X_add_number,
NULL, 0);
}
else
{
bfd_reloc_code_real_type reloc = operand->default_reloc;
expressionS subexp;
int die = 0, use_subexp = 0, require_symbol = 0;
fixS *fixP;
/* Take an expression like hi16(x) and turn it into x with
a different reloc type. */
switch (operand_exp->X_op)
{
#define HANDLE_OP16(suffix) \
switch (reloc) \
{ \
case BFD_RELOC_TILEPRO_IMM16_X0: \
reloc = BFD_RELOC_TILEPRO_IMM16_X0_##suffix; \
break; \
case BFD_RELOC_TILEPRO_IMM16_X1: \
reloc = BFD_RELOC_TILEPRO_IMM16_X1_##suffix; \
break; \
default: \
die = 1; \
break; \
} \
use_subexp = 1
case O_lo16:
HANDLE_OP16 (LO);
break;
case O_hi16:
HANDLE_OP16 (HI);
break;
case O_ha16:
HANDLE_OP16 (HA);
break;
case O_got:
HANDLE_OP16 (GOT);
require_symbol = 1;
break;
case O_got_lo16:
HANDLE_OP16 (GOT_LO);
require_symbol = 1;
break;
case O_got_hi16:
HANDLE_OP16 (GOT_HI);
require_symbol = 1;
break;
case O_got_ha16:
HANDLE_OP16 (GOT_HA);
require_symbol = 1;
break;
case O_tls_gd:
HANDLE_OP16 (TLS_GD);
require_symbol = 1;
break;
case O_tls_gd_lo16:
HANDLE_OP16 (TLS_GD_LO);
require_symbol = 1;
break;
case O_tls_gd_hi16:
HANDLE_OP16 (TLS_GD_HI);
require_symbol = 1;
break;
case O_tls_gd_ha16:
HANDLE_OP16 (TLS_GD_HA);
require_symbol = 1;
break;
case O_tls_ie:
HANDLE_OP16 (TLS_IE);
require_symbol = 1;
break;
case O_tls_ie_lo16:
HANDLE_OP16 (TLS_IE_LO);
require_symbol = 1;
break;
case O_tls_ie_hi16:
HANDLE_OP16 (TLS_IE_HI);
require_symbol = 1;
break;
case O_tls_ie_ha16:
HANDLE_OP16 (TLS_IE_HA);
require_symbol = 1;
break;
case O_tls_le:
HANDLE_OP16 (TLS_LE);
require_symbol = 1;
break;
case O_tls_le_lo16:
HANDLE_OP16 (TLS_LE_LO);
require_symbol = 1;
break;
case O_tls_le_hi16:
HANDLE_OP16 (TLS_LE_HI);
require_symbol = 1;
break;
case O_tls_le_ha16:
HANDLE_OP16 (TLS_LE_HA);
require_symbol = 1;
break;
#undef HANDLE_OP16
case O_plt:
switch (reloc)
{
case BFD_RELOC_TILEPRO_JOFFLONG_X1:
reloc = BFD_RELOC_TILEPRO_JOFFLONG_X1_PLT;
break;
default:
die = 1;
break;
}
use_subexp = 1;
require_symbol = 1;
break;
case O_tls_gd_call:
switch (reloc)
{
case BFD_RELOC_TILEPRO_JOFFLONG_X1:
reloc = BFD_RELOC_TILEPRO_TLS_GD_CALL;
break;
default:
die = 1;
break;
}
use_subexp = 1;
require_symbol = 1;
break;
case O_tls_gd_add:
switch (reloc)
{
case BFD_RELOC_TILEPRO_IMM8_X0:
reloc = BFD_RELOC_TILEPRO_IMM8_X0_TLS_GD_ADD;
break;
case BFD_RELOC_TILEPRO_IMM8_X1:
reloc = BFD_RELOC_TILEPRO_IMM8_X1_TLS_GD_ADD;
break;
case BFD_RELOC_TILEPRO_IMM8_Y0:
reloc = BFD_RELOC_TILEPRO_IMM8_Y0_TLS_GD_ADD;
break;
case BFD_RELOC_TILEPRO_IMM8_Y1:
reloc = BFD_RELOC_TILEPRO_IMM8_Y1_TLS_GD_ADD;
break;
default:
die = 1;
break;
}
use_subexp = 1;
require_symbol = 1;
break;
case O_tls_ie_load:
switch (reloc)
{
case BFD_RELOC_TILEPRO_IMM8_X1:
reloc = BFD_RELOC_TILEPRO_TLS_IE_LOAD;
break;
default:
die = 1;
break;
}
use_subexp = 1;
require_symbol = 1;
break;
default:
/* Do nothing. */
break;
}
if (die)
{
as_bad (_("Invalid operator for operand."));
}
else if (use_subexp)
{
/* Now that we've changed the reloc, change ha16(x) into x,
etc. */
if (!operand_exp->X_add_symbol->sy_flags.sy_local_symbol
&& operand_exp->X_add_symbol->sy_value.X_md)
{
/* HACK: We used X_md to mark this symbol as a fake wrapper
around a real expression. To unwrap it, we just grab its
value here. */
operand_exp = &operand_exp->X_add_symbol->sy_value;
if (require_symbol)
{
/* Look at the expression, and reject it if it's not a
plain symbol. */
if (operand_exp->X_op != O_symbol
|| operand_exp->X_add_number != 0)
as_bad (_("Operator may only be applied to symbols."));
}
}
else
{
/* The value of this expression is an actual symbol, so
turn that into an expression. */
memset (&subexp, 0, sizeof subexp);
subexp.X_op = O_symbol;
subexp.X_add_symbol = operand_exp->X_add_symbol;
operand_exp = &subexp;
}
}
/* Create a fixup to handle this later. */
fixP = fix_new_exp (frag_now,
bundle_start - frag_now->fr_literal,
(operand->num_bits + 7) >> 3,
operand_exp,
is_pc_relative,
reloc);
fixP->tc_fix_data = operand;
/* Don't do overflow checking if we are applying a function like
ha16. */
fixP->fx_no_overflow |= use_subexp;
}
}
return bits;
}
/* Detects and complains if two instructions in current_bundle write
to the same register, either implicitly or explicitly, or if a
read-only register is written. */
static void
check_illegal_reg_writes (void)
{
BFD_HOST_U_64_BIT all_regs_written = 0;
int j;
for (j = 0; j < current_bundle_index; j++)
{
const struct tilepro_instruction *instr = ¤t_bundle[j];
int k;
BFD_HOST_U_64_BIT regs =
((BFD_HOST_U_64_BIT)1) << instr->opcode->implicitly_written_register;
BFD_HOST_U_64_BIT conflict;
for (k = 0; k < instr->opcode->num_operands; k++)
{
const struct tilepro_operand *operand =
&tilepro_operands[instr->opcode->operands[instr->pipe][k]];
if (operand->is_dest_reg)
{
int regno = instr->operand_values[k].X_add_number;
BFD_HOST_U_64_BIT mask = ((BFD_HOST_U_64_BIT)1) << regno;
if ((mask & ( (((BFD_HOST_U_64_BIT)1) << TREG_IDN1)
| (((BFD_HOST_U_64_BIT)1) << TREG_UDN1)
| (((BFD_HOST_U_64_BIT)1) << TREG_UDN2)
| (((BFD_HOST_U_64_BIT)1) << TREG_UDN3))) != 0
&& !allow_suspicious_bundles)
{
as_bad (_("Writes to register '%s' are not allowed."),
tilepro_register_names[regno]);
}
regs |= mask;
}
}
/* Writing to the zero register doesn't count. */
regs &= ~(((BFD_HOST_U_64_BIT)1) << TREG_ZERO);
conflict = all_regs_written & regs;
if (conflict != 0 && !allow_suspicious_bundles)
{
/* Find which register caused the conflict. */
const char *conflicting_reg_name = "???";
int i;
for (i = 0; i < TILEPRO_NUM_REGISTERS; i++)
{
if (((conflict >> i) & 1) != 0)
{
conflicting_reg_name = tilepro_register_names[i];
break;
}
}
as_bad (_("Two instructions in the same bundle both write "
"to register %s, which is not allowed."),
conflicting_reg_name);
}
all_regs_written |= regs;
}
}
static void
tilepro_flush_bundle (void)
{
unsigned i;
int j, addr_mod;
unsigned compatible_pipes;
const struct bundle_template *match;
char *f;
inside_bundle = 0;
switch (current_bundle_index)
{
case 0:
/* No instructions. */
return;
case 1:
if (current_bundle[0].opcode->can_bundle)
{
/* Simplify later logic by adding an explicit fnop. */
prepend_nop_to_bundle (TILEPRO_OPC_FNOP);
}
else
{
/* This instruction cannot be bundled with anything else.
Prepend an explicit 'nop', rather than an 'fnop', because
fnops can be replaced by later binary-processing tools
while nops cannot. */
prepend_nop_to_bundle (TILEPRO_OPC_NOP);
}
break;
default:
if (!allow_suspicious_bundles)
{
/* Make sure all instructions can be bundled with other
instructions. */
const struct tilepro_opcode *cannot_bundle = NULL;
bfd_boolean seen_non_nop = FALSE;
for (j = 0; j < current_bundle_index; j++)
{
const struct tilepro_opcode *op = current_bundle[j].opcode;
if (!op->can_bundle && cannot_bundle == NULL)
cannot_bundle = op;
else if (op->mnemonic != TILEPRO_OPC_NOP
&& op->mnemonic != TILEPRO_OPC_INFO
&& op->mnemonic != TILEPRO_OPC_INFOL)
seen_non_nop = TRUE;
}
if (cannot_bundle != NULL && seen_non_nop)
{
current_bundle_index = 0;
as_bad (_("'%s' may not be bundled with other instructions."),
cannot_bundle->name);
return;
}
}
break;
}
compatible_pipes =
BUNDLE_TEMPLATE_MASK(current_bundle[0].opcode->pipes,
current_bundle[1].opcode->pipes,
(current_bundle_index == 3
? current_bundle[2].opcode->pipes
: (1 << NO_PIPELINE)));
/* Find a template that works, if any. */
match = NULL;
for (i = 0; i < sizeof bundle_templates / sizeof bundle_templates[0]; i++)
{
const struct bundle_template *b = &bundle_templates[i];
if ((b->pipe_mask & compatible_pipes) == b->pipe_mask)
{
match = b;
break;
}
}
if (match == NULL)
{
current_bundle_index = 0;
as_bad (_("Invalid combination of instructions for bundle."));
return;
}
/* If the section seems to have no alignment set yet, go ahead and
make it large enough to hold code. */
if (bfd_get_section_alignment (stdoutput, now_seg) == 0)
bfd_set_section_alignment (stdoutput, now_seg,
TILEPRO_LOG2_BUNDLE_ALIGNMENT_IN_BYTES);
for (j = 0; j < current_bundle_index; j++)
current_bundle[j].pipe = match->pipe[j];
if (current_bundle_index == 2 && !tilepro_is_x_pipeline(match->pipe[0]))
{
/* We are in Y mode with only two instructions, so add an FNOP. */
prepend_nop_to_bundle (TILEPRO_OPC_FNOP);
/* Figure out what pipe the fnop must be in via arithmetic.
* p0 + p1 + p2 must sum to the sum of TILEPRO_PIPELINE_Y[012]. */
current_bundle[0].pipe =
(tilepro_pipeline)((TILEPRO_PIPELINE_Y0
+ TILEPRO_PIPELINE_Y1
+ TILEPRO_PIPELINE_Y2) -
(current_bundle[1].pipe + current_bundle[2].pipe));
}
check_illegal_reg_writes ();
f = frag_more (TILEPRO_BUNDLE_SIZE_IN_BYTES);
/* Check to see if this bundle is at an offset that is a multiple of 8-bytes
from the start of the frag. */
addr_mod = frag_now_fix () & (TILEPRO_BUNDLE_ALIGNMENT_IN_BYTES - 1);
if (frag_now->has_code && frag_now->insn_addr != addr_mod)
as_bad (_("instruction address is not a multiple of 8"));
frag_now->insn_addr = addr_mod;
frag_now->has_code = 1;
tilepro_bundle_bits bits = 0;
for (j = 0; j < current_bundle_index; j++)
{
struct tilepro_instruction *instr = ¤t_bundle[j];
tilepro_pipeline pipeline = instr->pipe;
const struct tilepro_opcode *opcode = instr->opcode;
bits |= emit_tilepro_instruction (opcode->fixed_bit_values[pipeline],
opcode->num_operands,
&opcode->operands[pipeline][0],
instr->operand_values,
f);
}
number_to_chars_littleendian (f, (unsigned int)bits, 4);
number_to_chars_littleendian (f + 4, (unsigned int)(bits >> 32), 4);
current_bundle_index = 0;
/* Emit DWARF2 debugging information. */
dwarf2_emit_insn (TILEPRO_BUNDLE_SIZE_IN_BYTES);
}
/* Extend the expression parser to handle hi16(label), etc.
as well as SPR names when in the context of parsing an SPR. */
int
tilepro_parse_name (char *name, expressionS *e, char *nextcharP)
{
operatorT op = O_illegal;
if (parsing_spr)
{
void *val = hash_find (spr_hash, name);
if (val == NULL)
return 0;
memset (e, 0, sizeof *e);
e->X_op = O_constant;
e->X_add_number = ((const struct tilepro_spr *)val)->number;
return 1;
}
if (*nextcharP != '(')
{
/* hi16, etc. not followed by a paren is just a label with that
name. */
return 0;
}
else
{
/* Look up the operator in our table. */
void *val = hash_find (special_operator_hash, name);
if (val == 0)
return 0;
op = (operatorT)(long)val;
}
/* Restore old '(' and skip it. */
*input_line_pointer = '(';
++input_line_pointer;
expression (e);
if (*input_line_pointer != ')')
{
as_bad (_("Missing ')'"));
*nextcharP = *input_line_pointer;
return 0;
}
/* Skip ')'. */
++input_line_pointer;
if (e->X_op == O_register || e->X_op == O_absent)
{
as_bad (_("Invalid expression."));
e->X_op = O_constant;
e->X_add_number = 0;
}
else
{
/* Wrap subexpression with a unary operator. */
symbolS *sym = make_expr_symbol (e);
if (sym != e->X_add_symbol)
{
/* HACK: mark this symbol as a temporary wrapper around a proper
expression, so we can unwrap it later once we have communicated
the relocation type. */
sym->sy_value.X_md = 1;
}
memset (e, 0, sizeof *e);
e->X_op = op;
e->X_add_symbol = sym;
e->X_add_number = 0;
}
*nextcharP = *input_line_pointer;
return 1;
}
/* Parses an expression which must be a register name. */
static void
parse_reg_expression (expressionS* expression)
{
/* Zero everything to make sure we don't miss any flags. */
memset (expression, 0, sizeof *expression);
char* regname = input_line_pointer;
char terminating_char = get_symbol_end ();
void* pval = hash_find (main_reg_hash, regname);
if (pval == NULL)
as_bad (_("Expected register, got '%s'."), regname);
int regno_and_flags = (int)(size_t)pval;
int regno = EXTRACT_REGNO(regno_and_flags);
if ((regno_and_flags & NONCANONICAL_REG_NAME_FLAG)
&& require_canonical_reg_names)
as_warn (_("Found use of non-canonical register name %s; "
"use %s instead."),
regname, tilepro_register_names[regno]);
/* Restore the old character following the register name. */
*input_line_pointer = terminating_char;
/* Fill in the expression fields to indicate it's a register. */
expression->X_op = O_register;
expression->X_add_number = regno;
}
/* Parses and type-checks comma-separated operands in input_line_pointer. */
static void
parse_operands (const char *opcode_name,
const unsigned char *operands,
int num_operands,
expressionS *operand_values)
{
int i;
memset (operand_values, 0, num_operands * sizeof operand_values[0]);
SKIP_WHITESPACE ();
for (i = 0; i < num_operands; i++)
{
tilepro_operand_type type = tilepro_operands[operands[i]].type;
SKIP_WHITESPACE ();
if (type == TILEPRO_OP_TYPE_REGISTER)
{
parse_reg_expression (&operand_values[i]);
}
else if (*input_line_pointer == '}')
{
operand_values[i].X_op = O_absent;
}
else if (type == TILEPRO_OP_TYPE_SPR)
{
/* Modify the expression parser to add SPRs to the namespace. */
parsing_spr = 1;
expression (&operand_values[i]);
parsing_spr = 0;
}
else
{
expression (&operand_values[i]);
}
SKIP_WHITESPACE ();
if (i + 1 < num_operands)
{
int separator = (unsigned char)*input_line_pointer++;
if (is_end_of_line[separator] || (separator == '}'))
{
as_bad (_("Too few operands to '%s'."), opcode_name);
return;
}
else if (separator != ',')
{
as_bad (_("Unexpected character '%c' after operand %d to %s."),
(char)separator, i + 1, opcode_name);
return;
}
}
/* Arbitrarily use the first valid pipe to get the operand type,
since they are all the same. */
switch (tilepro_operands[operands[i]].type)
{
case TILEPRO_OP_TYPE_REGISTER:
/* Handled in parse_reg_expression already. */
break;
case TILEPRO_OP_TYPE_SPR:
/* Fall through */
case TILEPRO_OP_TYPE_IMMEDIATE:
/* Fall through */
case TILEPRO_OP_TYPE_ADDRESS:
if ( operand_values[i].X_op == O_register
|| operand_values[i].X_op == O_illegal
|| operand_values[i].X_op == O_absent)
as_bad (_("Expected immediate expression"));
break;
default:
abort ();
}
}
if (!is_end_of_line[(unsigned char)*input_line_pointer])
{
switch (*input_line_pointer)
{
case '}':
if (!inside_bundle)
as_bad (_("Found '}' when not bundling."));
++input_line_pointer;
inside_bundle = 0;
demand_empty_rest_of_line ();
break;
case ',':
as_bad (_("Too many operands"));
break;
default:
/* Use default error for unrecognized garbage. */
demand_empty_rest_of_line ();
break;
}
}
}
/* This is the guts of the machine-dependent assembler. STR points to a
machine dependent instruction. This function is supposed to emit
the frags/bytes it assembles to. */
void
md_assemble (char *str)
{
char old_char;
size_t opname_len;
char *old_input_line_pointer;
const struct tilepro_opcode *op;
int first_pipe;
/* Split off the opcode and look it up. */
opname_len = strcspn (str, " {}");
old_char = str[opname_len];
str[opname_len] = '\0';
op = hash_find(op_hash, str);
str[opname_len] = old_char;
if (op == NULL)
{
as_bad (_("Unknown opcode `%.*s'."), (int)opname_len, str);
return;
}
/* Prepare to parse the operands. */
old_input_line_pointer = input_line_pointer;
input_line_pointer = str + opname_len;
SKIP_WHITESPACE ();
if (current_bundle_index == TILEPRO_MAX_INSTRUCTIONS_PER_BUNDLE)
{
as_bad (_("Too many instructions for bundle."));
tilepro_flush_bundle ();
}
/* Make sure we have room for the upcoming bundle before we
create any fixups. Otherwise if we have to switch to a new
frag the fixup dot_value fields will be wrong. */
frag_grow (TILEPRO_BUNDLE_SIZE_IN_BYTES);
/* Find a valid pipe for this opcode. */
for (first_pipe = 0; (op->pipes & (1 << first_pipe)) == 0; first_pipe++)
;
/* Call the function that assembles this instruction. */
current_bundle[current_bundle_index].opcode = op;
parse_operands (op->name,
&op->operands[first_pipe][0],
op->num_operands,
current_bundle[current_bundle_index].operand_values);
++current_bundle_index;
/* Restore the saved value of input_line_pointer. */
input_line_pointer = old_input_line_pointer;
/* If we weren't inside curly braces, go ahead and emit
this lone instruction as a bundle right now. */
if (!inside_bundle)
tilepro_flush_bundle ();
}
static void
s_require_canonical_reg_names (int require)
{
demand_empty_rest_of_line ();
require_canonical_reg_names = require;
}
static void
s_allow_suspicious_bundles (int allow)
{
demand_empty_rest_of_line ();
allow_suspicious_bundles = allow;
}
const pseudo_typeS md_pseudo_table[] =
{
{"align", s_align_bytes, 0}, /* Defaulting is invalid (0). */
{"word", cons, 4},
{"require_canonical_reg_names", s_require_canonical_reg_names, 1 },
{"no_require_canonical_reg_names", s_require_canonical_reg_names, 0 },
{"allow_suspicious_bundles", s_allow_suspicious_bundles, 1 },
{"no_allow_suspicious_bundles", s_allow_suspicious_bundles, 0 },
{ NULL, 0, 0 }
};
/* Equal to MAX_PRECISION in atof-ieee.c */
#define MAX_LITTLENUMS 6
/* Turn the string pointed to by litP into a floating point constant
of type TYPE, and emit the appropriate bytes. The number of
LITTLENUMS emitted is stored in *SIZEP. An error message is
returned, or NULL on OK. */
char *
md_atof (int type, char *litP, int *sizeP)
{
int prec;
LITTLENUM_TYPE words[MAX_LITTLENUMS];
LITTLENUM_TYPE *wordP;
char *t;
switch (type)
{
case 'f':
case 'F':
prec = 2;
break;
case 'd':
case 'D':
prec = 4;
break;
default:
*sizeP = 0;
return _("Bad call to md_atof ()");
}
t = atof_ieee (input_line_pointer, type, words);
if (t)
input_line_pointer = t;
*sizeP = prec * sizeof (LITTLENUM_TYPE);
/* This loops outputs the LITTLENUMs in REVERSE order; in accord with
the bigendian 386. */
for (wordP = words + prec - 1; prec--;)
{
md_number_to_chars (litP, (valueT) (*wordP--), sizeof (LITTLENUM_TYPE));
litP += sizeof (LITTLENUM_TYPE);
}
return 0;
}
/* We have no need to default values of symbols. */
symbolS *
md_undefined_symbol (char *name ATTRIBUTE_UNUSED)
{
return NULL;
}
void
tilepro_cons_fix_new (fragS *frag,
int where,
int nbytes,
expressionS *exp)
{
expressionS subexp;
bfd_reloc_code_real_type reloc = BFD_RELOC_NONE;
int no_overflow = 0;
fixS *fixP;
/* See if it's one of our special functions. */
switch (exp->X_op)
{
case O_lo16:
reloc = BFD_RELOC_LO16;
no_overflow = 1;
break;
case O_hi16:
reloc = BFD_RELOC_HI16;
no_overflow = 1;
break;
case O_ha16:
reloc = BFD_RELOC_HI16_S;
no_overflow = 1;
break;
default:
/* Do nothing. */
break;
}
if (reloc != BFD_RELOC_NONE)
{
if (nbytes != 2)
{
as_bad (_("This operator only produces two byte values."));
nbytes = 2;
}
memset (&subexp, 0, sizeof subexp);
subexp.X_op = O_symbol;
subexp.X_add_symbol = exp->X_add_symbol;
exp = &subexp;
}
else
{
switch (nbytes)
{
case 1:
reloc = BFD_RELOC_8;
break;
case 2:
reloc = BFD_RELOC_16;
break;
case 4:
reloc = BFD_RELOC_32;
break;
case 8:
reloc = BFD_RELOC_64;
break;
default:
as_bad (_("unsupported BFD relocation size %d"), nbytes);
reloc = BFD_RELOC_32;
break;
}
}
fixP = fix_new_exp (frag, where, nbytes, exp, 0, reloc);
fixP->tc_fix_data = NULL;
fixP->fx_no_overflow |= no_overflow;
}
void
md_apply_fix (fixS *fixP, valueT * valP, segT seg ATTRIBUTE_UNUSED)
{
const struct tilepro_operand *operand;
valueT value = *valP;
char *p;
/* Leave these for the linker. */
if (fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
|| fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
return;
if (fixP->fx_subsy != (symbolS *) NULL)
{
/* We can't actually support subtracting a symbol. */
as_bad_where (fixP->fx_file, fixP->fx_line, _("expression too complex"));
}
/* Correct relocation types for pc-relativeness. */
switch (fixP->fx_r_type)
{
#define FIX_PCREL(rtype) \
case rtype: \
if (fixP->fx_pcrel) \
fixP->fx_r_type = rtype##_PCREL; \
break; \
\
case rtype##_PCREL: \
if (!fixP->fx_pcrel) \
fixP->fx_r_type = rtype; \
break
FIX_PCREL (BFD_RELOC_8);
FIX_PCREL (BFD_RELOC_16);
FIX_PCREL (BFD_RELOC_32);
FIX_PCREL (BFD_RELOC_TILEPRO_IMM16_X0);
FIX_PCREL (BFD_RELOC_TILEPRO_IMM16_X1);
FIX_PCREL (BFD_RELOC_TILEPRO_IMM16_X0_LO);
FIX_PCREL (BFD_RELOC_TILEPRO_IMM16_X1_LO);
FIX_PCREL (BFD_RELOC_TILEPRO_IMM16_X0_HI);
FIX_PCREL (BFD_RELOC_TILEPRO_IMM16_X1_HI);
FIX_PCREL (BFD_RELOC_TILEPRO_IMM16_X0_HA);
FIX_PCREL (BFD_RELOC_TILEPRO_IMM16_X1_HA);
#undef FIX_PCREL
default:
/* Do nothing */
break;
}
if (fixP->fx_addsy != NULL)
{
#ifdef OBJ_ELF
switch (fixP->fx_r_type)
{
case BFD_RELOC_TILEPRO_IMM8_X0_TLS_GD_ADD:
case BFD_RELOC_TILEPRO_IMM8_X1_TLS_GD_ADD:
case BFD_RELOC_TILEPRO_IMM8_Y0_TLS_GD_ADD:
case BFD_RELOC_TILEPRO_IMM8_Y1_TLS_GD_ADD:
case BFD_RELOC_TILEPRO_IMM16_X0_TLS_GD:
case BFD_RELOC_TILEPRO_IMM16_X1_TLS_GD:
case BFD_RELOC_TILEPRO_IMM16_X0_TLS_GD_LO:
case BFD_RELOC_TILEPRO_IMM16_X1_TLS_GD_LO:
case BFD_RELOC_TILEPRO_IMM16_X0_TLS_GD_HI:
case BFD_RELOC_TILEPRO_IMM16_X1_TLS_GD_HI:
case BFD_RELOC_TILEPRO_IMM16_X0_TLS_GD_HA:
case BFD_RELOC_TILEPRO_IMM16_X1_TLS_GD_HA:
case BFD_RELOC_TILEPRO_IMM16_X0_TLS_IE:
case BFD_RELOC_TILEPRO_IMM16_X1_TLS_IE:
case BFD_RELOC_TILEPRO_IMM16_X0_TLS_IE_LO:
case BFD_RELOC_TILEPRO_IMM16_X1_TLS_IE_LO:
case BFD_RELOC_TILEPRO_IMM16_X0_TLS_IE_HI:
case BFD_RELOC_TILEPRO_IMM16_X1_TLS_IE_HI:
case BFD_RELOC_TILEPRO_IMM16_X0_TLS_IE_HA:
case BFD_RELOC_TILEPRO_IMM16_X1_TLS_IE_HA:
case BFD_RELOC_TILEPRO_IMM16_X0_TLS_LE:
case BFD_RELOC_TILEPRO_IMM16_X1_TLS_LE:
case BFD_RELOC_TILEPRO_IMM16_X0_TLS_LE_LO:
case BFD_RELOC_TILEPRO_IMM16_X1_TLS_LE_LO:
case BFD_RELOC_TILEPRO_IMM16_X0_TLS_LE_HI:
case BFD_RELOC_TILEPRO_IMM16_X1_TLS_LE_HI:
case BFD_RELOC_TILEPRO_IMM16_X0_TLS_LE_HA:
case BFD_RELOC_TILEPRO_IMM16_X1_TLS_LE_HA:
case BFD_RELOC_TILEPRO_TLS_GD_CALL:
case BFD_RELOC_TILEPRO_TLS_IE_LOAD:
case BFD_RELOC_TILEPRO_TLS_DTPMOD32:
case BFD_RELOC_TILEPRO_TLS_DTPOFF32:
case BFD_RELOC_TILEPRO_TLS_TPOFF32:
S_SET_THREAD_LOCAL (fixP->fx_addsy);
break;
default:
/* Do nothing */
break;
}
#endif
return;
}
/* Apply lo16, hi16, ha16, etc. munging. */
switch (fixP->fx_r_type)
{
case BFD_RELOC_LO16:
case BFD_RELOC_TILEPRO_IMM16_X0_LO:
case BFD_RELOC_TILEPRO_IMM16_X1_LO:
case BFD_RELOC_TILEPRO_IMM16_X0_LO_PCREL:
case BFD_RELOC_TILEPRO_IMM16_X1_LO_PCREL:
*valP = value = apply_special_operator (O_lo16, value);
break;
case BFD_RELOC_HI16:
case BFD_RELOC_TILEPRO_IMM16_X0_HI:
case BFD_RELOC_TILEPRO_IMM16_X1_HI:
case BFD_RELOC_TILEPRO_IMM16_X0_HI_PCREL:
case BFD_RELOC_TILEPRO_IMM16_X1_HI_PCREL:
*valP = value = apply_special_operator (O_hi16, value);
break;
case BFD_RELOC_HI16_S:
case BFD_RELOC_TILEPRO_IMM16_X0_HA:
case BFD_RELOC_TILEPRO_IMM16_X1_HA:
case BFD_RELOC_TILEPRO_IMM16_X0_HA_PCREL:
case BFD_RELOC_TILEPRO_IMM16_X1_HA_PCREL:
*valP = value = apply_special_operator (O_ha16, value);
break;
default:
/* Do nothing */
break;
}
p = fixP->fx_frag->fr_literal + fixP->fx_where;
operand = fixP->tc_fix_data;
if (operand != NULL)
{
/* It's an instruction operand. */
tilepro_bundle_bits bits =
insert_operand (0, operand, value, fixP->fx_file, fixP->fx_line);
/* Note that we might either be writing out bits for a bundle or a
static network instruction, which are different sizes, so it's
important to stop touching memory once we run out of bits. ORing in
values is OK since we know the existing bits for this operand are
zero. */
for (; bits != 0; bits >>= 8)
*p++ |= (char)bits;
}
else
{
/* Some other kind of relocation. */
switch (fixP->fx_r_type)
{
case BFD_RELOC_8:
case BFD_RELOC_8_PCREL:
md_number_to_chars (p, value, 1);
break;
case BFD_RELOC_16:
case BFD_RELOC_16_PCREL:
md_number_to_chars (p, value, 2);
break;
case BFD_RELOC_32:
case BFD_RELOC_32_PCREL:
md_number_to_chars (p, value, 4);
break;
default:
/* Leave it for the linker. */
return;
}
}
fixP->fx_done = 1;
}
/* Generate the BFD reloc to be stuck in the object file from the
fixup used internally in the assembler. */
arelent *
tc_gen_reloc (asection *sec ATTRIBUTE_UNUSED, fixS *fixp)
{
arelent *reloc;
reloc = (arelent *) xmalloc (sizeof (arelent));
reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
*reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
/* Make sure none of our internal relocations make it this far.
They'd better have been fully resolved by this point. */
gas_assert ((int) fixp->fx_r_type > 0);
reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
if (reloc->howto == NULL)
{
as_bad_where (fixp->fx_file, fixp->fx_line,
_("cannot represent `%s' relocation in object file"),
bfd_get_reloc_code_name (fixp->fx_r_type));
return NULL;
}
if (!fixp->fx_pcrel != !reloc->howto->pc_relative)
{
as_fatal (_("internal error? cannot generate `%s' relocation (%d, %d)"),
bfd_get_reloc_code_name (fixp->fx_r_type),
fixp->fx_pcrel, reloc->howto->pc_relative);
}
gas_assert (!fixp->fx_pcrel == !reloc->howto->pc_relative);
reloc->addend = fixp->fx_offset;
return reloc;
}
/* The location from which a PC relative jump should be calculated,
given a PC relative reloc. */
long
md_pcrel_from (fixS *fixP)
{
return fixP->fx_frag->fr_address + fixP->fx_where;
}
/* Return 1 if it's OK to adjust a reloc by replacing the symbol with
a section symbol plus some offset. */
int
tilepro_fix_adjustable (fixS *fix)
{
/* Prevent all adjustments to global symbols */
if (S_IS_EXTERNAL (fix->fx_addsy) || S_IS_WEAK (fix->fx_addsy))
return 0;
return 1;
}
int
tilepro_unrecognized_line (int ch)
{
switch (ch)
{
case '{':
if (inside_bundle)
{
as_bad (_("Found '{' when already bundling."));
}
else
{
inside_bundle = 1;
current_bundle_index = 0;
}
return 1;
case '}':
if (!inside_bundle)
{
as_bad (_("Found '}' when not bundling."));
}
else
{
tilepro_flush_bundle ();
}
/* Allow '{' to follow on the same line. We also allow ";;", but that
happens automatically because ';' is an end of line marker. */
SKIP_WHITESPACE ();
if (input_line_pointer[0] == '{')
{
input_line_pointer++;
return tilepro_unrecognized_line ('{');
}
demand_empty_rest_of_line ();
return 1;
default:
break;
}
/* Not a valid line. */
return 0;
}
/* This is called from HANDLE_ALIGN in write.c. Fill in the contents
of an rs_align_code fragment. */
void
tilepro_handle_align (fragS *fragp)
{
int bytes, fix;
char *p;
if (fragp->fr_type != rs_align_code)
return;
bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
p = fragp->fr_literal + fragp->fr_fix;
fix = 0;
/* Determine the bits for NOP. */
const struct tilepro_opcode *nop_opcode =
&tilepro_opcodes[TILEPRO_OPC_NOP];
tilepro_bundle_bits nop =
( nop_opcode->fixed_bit_values[TILEPRO_PIPELINE_X0]
| nop_opcode->fixed_bit_values[TILEPRO_PIPELINE_X1]);
if ((bytes & (TILEPRO_BUNDLE_SIZE_IN_BYTES - 1)) != 0)
{
fix = bytes & (TILEPRO_BUNDLE_SIZE_IN_BYTES - 1);
memset (p, 0, fix);
p += fix;
bytes -= fix;
}
number_to_chars_littleendian (p, (unsigned int)nop, 4);
number_to_chars_littleendian (p + 4, (unsigned int)(nop >> 32), 4);
fragp->fr_fix += fix;
fragp->fr_var = TILEPRO_BUNDLE_SIZE_IN_BYTES;
}
/* Standard calling conventions leave the CFA at SP on entry. */
void
tilepro_cfi_frame_initial_instructions (void)
{
cfi_add_CFA_def_cfa_register (54);
}
int
tc_tilepro_regname_to_dw2regnum (char *regname)
{
int i;
for (i = 0; i < TILEPRO_NUM_REGISTERS; i++)
{
if (!strcmp (regname, tilepro_register_names[i]))
return i;
}
return -1;
}
| gpl-2.0 |
alysher/mangos-cata-pb | dep/ACE_wrappers/ace/Malloc_T.cpp | 295 | 40897 | // $Id: Malloc_T.cpp 91809 2010-09-17 07:20:41Z johnnyw $
#ifndef ACE_MALLOC_T_CPP
#define ACE_MALLOC_T_CPP
#include "ace/Malloc_T.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#if !defined (__ACE_INLINE__)
#include "ace/Malloc_T.inl"
#endif /* __ACE_INLINE__ */
#include "ace/ACE.h"
#include "ace/OS_NS_string.h"
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
template <class T, class ACE_LOCK>
ACE_Cached_Allocator<T, ACE_LOCK>::ACE_Cached_Allocator (size_t n_chunks)
: pool_ (0),
free_list_ (ACE_PURE_FREE_LIST)
{
// To maintain alignment requirements, make sure that each element
// inserted into the free list is aligned properly for the platform.
// Since the memory is allocated as a char[], the compiler won't help.
// To make sure enough room is allocated, round up the size so that
// each element starts aligned.
//
// NOTE - this would probably be easier by defining pool_ as a pointer
// to T and allocating an array of them (the compiler would probably
// take care of the alignment for us), but then the ACE_NEW below would
// require a default constructor on T - a requirement that is not in
// previous versions of ACE
size_t chunk_size = sizeof (T);
chunk_size = ACE_MALLOC_ROUNDUP (chunk_size, ACE_MALLOC_ALIGN);
ACE_NEW (this->pool_,
char[n_chunks * chunk_size]);
for (size_t c = 0;
c < n_chunks;
c++)
{
void* placement = this->pool_ + c * chunk_size;
this->free_list_.add (new (placement) ACE_Cached_Mem_Pool_Node<T>);
}
// Put into free list using placement contructor, no real memory
// allocation in the above <new>.
}
template <class T, class ACE_LOCK>
ACE_Cached_Allocator<T, ACE_LOCK>::~ACE_Cached_Allocator (void)
{
delete [] this->pool_;
}
template <class T, class ACE_LOCK> void *
ACE_Cached_Allocator<T, ACE_LOCK>::malloc (size_t nbytes)
{
// Check if size requested fits within pre-determined size.
if (nbytes > sizeof (T))
return 0;
// addr() call is really not absolutely necessary because of the way
// ACE_Cached_Mem_Pool_Node's internal structure arranged.
return this->free_list_.remove ()->addr ();
}
template <class T, class ACE_LOCK> void *
ACE_Cached_Allocator<T, ACE_LOCK>::calloc (size_t nbytes,
char initial_value)
{
// Check if size requested fits within pre-determined size.
if (nbytes > sizeof (T))
return 0;
// addr() call is really not absolutely necessary because of the way
// ACE_Cached_Mem_Pool_Node's internal structure arranged.
void *ptr = this->free_list_.remove ()->addr ();
if (ptr != 0)
ACE_OS::memset (ptr, initial_value, sizeof (T));
return ptr;
}
template <class T, class ACE_LOCK> void *
ACE_Cached_Allocator<T, ACE_LOCK>::calloc (size_t,
size_t,
char)
{
ACE_NOTSUP_RETURN (0);
}
template <class T, class ACE_LOCK> void
ACE_Cached_Allocator<T, ACE_LOCK>::free (void * ptr)
{
if (ptr != 0)
this->free_list_.add ((ACE_Cached_Mem_Pool_Node<T> *) ptr) ;
}
template <class ACE_LOCK>
ACE_Dynamic_Cached_Allocator<ACE_LOCK>::ACE_Dynamic_Cached_Allocator
(size_t n_chunks, size_t chunk_size)
: pool_ (0),
free_list_ (ACE_PURE_FREE_LIST),
chunk_size_(chunk_size)
{
chunk_size = ACE_MALLOC_ROUNDUP (chunk_size, ACE_MALLOC_ALIGN);
ACE_NEW (this->pool_, char[n_chunks * chunk_size_]);
for (size_t c = 0;
c < n_chunks;
c++)
{
void* placement = this->pool_ + c * chunk_size_;
this->free_list_.add (new (placement) ACE_Cached_Mem_Pool_Node<char>);
}
// Put into free list using placement contructor, no real memory
// allocation in the above <new>.
}
template <class ACE_LOCK>
ACE_Dynamic_Cached_Allocator<ACE_LOCK>::~ACE_Dynamic_Cached_Allocator (void)
{
delete [] this->pool_;
this->pool_ = 0;
chunk_size_ = 0;
}
template <class ACE_LOCK> void *
ACE_Dynamic_Cached_Allocator<ACE_LOCK>::malloc (size_t nbytes)
{
// Check if size requested fits within pre-determined size.
if (nbytes > chunk_size_)
return 0;
// addr() call is really not absolutely necessary because of the way
// ACE_Cached_Mem_Pool_Node's internal structure arranged.
return this->free_list_.remove ()->addr ();
}
template <class ACE_LOCK> void *
ACE_Dynamic_Cached_Allocator<ACE_LOCK>::calloc (size_t nbytes,
char initial_value)
{
// Check if size requested fits within pre-determined size.
if (nbytes > chunk_size_)
return 0;
// addr() call is really not absolutely necessary because of the way
// ACE_Cached_Mem_Pool_Node's internal structure arranged.
void *ptr = this->free_list_.remove ()->addr ();
if (ptr != 0)
ACE_OS::memset (ptr, initial_value, chunk_size_);
return ptr;
}
template <class ACE_LOCK> void *
ACE_Dynamic_Cached_Allocator<ACE_LOCK>::calloc (size_t, size_t, char)
{
ACE_NOTSUP_RETURN (0);
}
template <class ACE_LOCK> void
ACE_Dynamic_Cached_Allocator<ACE_LOCK>::free (void * ptr)
{
if (ptr != 0)
this->free_list_.add ((ACE_Cached_Mem_Pool_Node<char> *) ptr);
}
ACE_ALLOC_HOOK_DEFINE (ACE_Malloc_T)
template <class MALLOC> void *
ACE_Allocator_Adapter<MALLOC>::malloc (size_t nbytes)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::malloc");
return this->allocator_.malloc (nbytes);
}
template <class MALLOC> void *
ACE_Allocator_Adapter<MALLOC>::calloc (size_t nbytes,
char initial_value)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::calloc");
return this->allocator_.calloc (nbytes, initial_value);
}
template <class MALLOC> void *
ACE_Allocator_Adapter<MALLOC>::calloc (size_t n_elem,
size_t elem_size,
char initial_value)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::calloc");
return this->allocator_.calloc (n_elem, elem_size, initial_value);
}
template <class MALLOC> MALLOC &
ACE_Allocator_Adapter<MALLOC>::alloc (void)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::allocator");
return this->allocator_;
}
template <class MALLOC> void
ACE_Allocator_Adapter<MALLOC>::free (void *ptr)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::free");
this->allocator_.free (ptr);
}
template <class MALLOC> int
ACE_Allocator_Adapter<MALLOC>::remove (void)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::remove");
return this->allocator_.remove ();
}
template <class MALLOC> int
ACE_Allocator_Adapter<MALLOC>::trybind (const char *name,
void *&pointer)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::trybind");
return this->allocator_.trybind (name, pointer);
}
template <class MALLOC> int
ACE_Allocator_Adapter<MALLOC>::bind (const char *name,
void *pointer,
int duplicates)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::bind");
return this->allocator_.bind (name, pointer, duplicates);
}
template <class MALLOC> int
ACE_Allocator_Adapter<MALLOC>::find (const char *name,
void *&pointer)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::find");
return this->allocator_.find (name, pointer);
}
template <class MALLOC> int
ACE_Allocator_Adapter<MALLOC>::find (const char *name)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::find");
return this->allocator_.find (name);
}
template <class MALLOC> int
ACE_Allocator_Adapter<MALLOC>::unbind (const char *name, void *&pointer)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::unbind");
return this->allocator_.unbind (name, pointer);
}
template <class MALLOC> int
ACE_Allocator_Adapter<MALLOC>::unbind (const char *name)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::unbind");
return this->allocator_.unbind (name);
}
template <class MALLOC> int
ACE_Allocator_Adapter<MALLOC>::sync (ssize_t len, int flags)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::sync");
return this->allocator_.sync (len, flags);
}
template <class MALLOC> int
ACE_Allocator_Adapter<MALLOC>::sync (void *addr, size_t len, int flags)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::sync");
return this->allocator_.sync (addr, len, flags);
}
template <class MALLOC> int
ACE_Allocator_Adapter<MALLOC>::protect (ssize_t len, int flags)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::protect");
return this->allocator_.protect (len, flags);
}
template <class MALLOC> int
ACE_Allocator_Adapter<MALLOC>::protect (void *addr, size_t len, int flags)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::protect");
return this->allocator_.protect (addr, len, flags);
}
template <class MALLOC>
ACE_Allocator_Adapter<MALLOC>::ACE_Allocator_Adapter (const char *pool_name)
: allocator_ (ACE_TEXT_CHAR_TO_TCHAR (pool_name))
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::ACE_Allocator_Adapter");
}
template <class MALLOC>
ACE_Allocator_Adapter<MALLOC>::ACE_Allocator_Adapter (
const char *pool_name,
const char *lock_name,
MEMORY_POOL_OPTIONS options)
: allocator_ (ACE_TEXT_CHAR_TO_TCHAR (pool_name),
ACE_TEXT_CHAR_TO_TCHAR (lock_name),
options)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::ACE_Allocator_Adapter");
}
#if defined (ACE_HAS_WCHAR)
template <class MALLOC>
ACE_Allocator_Adapter<MALLOC>::ACE_Allocator_Adapter (const wchar_t *pool_name)
: allocator_ (ACE_TEXT_WCHAR_TO_TCHAR (pool_name))
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::ACE_Allocator_Adapter");
}
template <class MALLOC>
ACE_Allocator_Adapter<MALLOC>::ACE_Allocator_Adapter (
const wchar_t *pool_name,
const wchar_t *lock_name,
MEMORY_POOL_OPTIONS options)
: allocator_ (ACE_TEXT_WCHAR_TO_TCHAR (pool_name),
ACE_TEXT_WCHAR_TO_TCHAR (lock_name),
options)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::ACE_Allocator_Adapter");
}
#endif /* ACE_HAS_WCHAR */
template <class MALLOC>
ACE_Allocator_Adapter<MALLOC>::~ACE_Allocator_Adapter (void)
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::~ACE_Allocator_Adapter");
}
#if defined (ACE_HAS_MALLOC_STATS)
template <class MALLOC> void
ACE_Allocator_Adapter<MALLOC>::print_stats (void) const
{
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::print_stats");
this->allocator_.print_stats ();
}
#endif /* ACE_HAS_MALLOC_STATS */
template <class MALLOC> void
ACE_Allocator_Adapter<MALLOC>::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Allocator_Adapter<MALLOC>::dump");
this->allocator_.dump ();
#endif /* ACE_HAS_DUMP */
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> void
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::dump");
ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
this->memory_pool_.dump ();
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("cb_ptr_ = %@\n"), this->cb_ptr_));
this->cb_ptr_->dump ();
#if defined (ACE_HAS_MALLOC_STATS)
if (this->cb_ptr_ != 0)
this->cb_ptr_->malloc_stats_.dump ();
#endif /* ACE_HAS_MALLOC_STATS */
ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
#if defined (ACE_HAS_MALLOC_STATS)
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> void
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::print_stats (void) const
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::print_stats");
ACE_GUARD (ACE_LOCK, ace_mon, *this->lock_);
if (this->cb_ptr_ == 0)
return;
this->cb_ptr_->malloc_stats_.dump ();
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("(%P|%t) contents of freelist:\n")));
for (MALLOC_HEADER *currp = this->cb_ptr_->freep_->next_block_;
;
currp = currp->next_block_)
{
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("(%P|%t) ptr = %@, MALLOC_HEADER units = %d, byte units = %d\n"),
currp,
currp->size_,
currp->size_ * sizeof (MALLOC_HEADER)));
if (currp == this->cb_ptr_->freep_)
break;
}
}
#endif /* ACE_HAS_MALLOC_STATS */
// Put <ptr> in the free list (locked version).
template<ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> void
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::free (void *ptr)
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::free");
ACE_GUARD (ACE_LOCK, ace_mon, *this->lock_);
this->shared_free (ptr);
}
// This function is called by the ACE_Malloc_T constructor to initialize
// the memory pool. The first time in it allocates room for the
// control block (as well as a chunk of memory, depending on
// rounding...). Depending on the type of <MEM_POOL> (i.e., shared
// vs. local) subsequent calls from other processes will only
// initialize the control block pointer.
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::open (void)
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::open");
ACE_GUARD_RETURN (ACE_LOCK, ace_mon, *this->lock_, -1);
size_t rounded_bytes = 0;
int first_time = 0;
this->cb_ptr_ = (ACE_CB *)
this->memory_pool_.init_acquire (sizeof *this->cb_ptr_,
rounded_bytes,
first_time);
if (this->cb_ptr_ == 0)
ACE_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("(%P|%t) %p\n"),
ACE_TEXT ("init_acquire failed")),
-1);
else if (first_time)
{
// ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) first time in, control block = %@\n"), this->cb_ptr_));
MALLOC_HEADER::init_ptr (&this->cb_ptr_->freep_,
&this->cb_ptr_->base_,
this->cb_ptr_);
MALLOC_HEADER::init_ptr (&this->cb_ptr_->freep_->next_block_,
this->cb_ptr_->freep_,
this->cb_ptr_);
NAME_NODE::init_ptr (&this->cb_ptr_->name_head_,
0,
this->cb_ptr_);
this->cb_ptr_->freep_->size_ = 0;
this->cb_ptr_->ref_counter_ = 1;
if (rounded_bytes > (sizeof *this->cb_ptr_ + sizeof (MALLOC_HEADER)))
{
// If we've got any extra space at the end of the control
// block, then skip past the dummy <MALLOC_HEADER> to
// point at the first free block.
MALLOC_HEADER *p = ((MALLOC_HEADER *) (this->cb_ptr_->freep_)) + 1;
MALLOC_HEADER::init_ptr (&p->next_block_,
0,
this->cb_ptr_);
// Why aC++ in 64-bit mode can't grok this, I have no
// idea... but it ends up with an extra bit set which makes
// size_ really big without this hack.
#if defined (__hpux) && defined (__LP64__)
size_t hpux11_hack = (rounded_bytes - sizeof *this->cb_ptr_)
/ sizeof (MALLOC_HEADER);
p->size_ = hpux11_hack;
#else
p->size_ = (rounded_bytes - sizeof *this->cb_ptr_)
/ sizeof (MALLOC_HEADER);
#endif /* (__hpux) && defined (__LP64__) */
ACE_MALLOC_STATS (++this->cb_ptr_->malloc_stats_.nchunks_);
ACE_MALLOC_STATS (++this->cb_ptr_->malloc_stats_.nblocks_);
ACE_MALLOC_STATS (++this->cb_ptr_->malloc_stats_.ninuse_);
// Insert the newly allocated chunk of memory into the free
// list. Add "1" to skip over the <MALLOC_HEADER> when
// freeing the pointer.
this->shared_free (p + 1);
}
}
else
++this->cb_ptr_->ref_counter_;
return 0;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB>
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::ACE_Malloc_T (const ACE_TCHAR *pool_name)
: cb_ptr_ (0),
memory_pool_ (pool_name),
bad_flag_ (0)
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::ACE_Malloc_T");
this->lock_ = ACE_Malloc_Lock_Adapter_T<ACE_LOCK> ()(pool_name);
if (this->lock_ == 0)
return;
this->delete_lock_ = true;
this->bad_flag_ = this->open ();
if (this->bad_flag_ == -1)
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("%p\n"),
ACE_TEXT ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::ACE_Malloc_T")));
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB>
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::ACE_Malloc_T (const ACE_TCHAR *pool_name,
const ACE_TCHAR *lock_name,
const ACE_MEM_POOL_OPTIONS *options)
: cb_ptr_ (0),
memory_pool_ (pool_name, options),
bad_flag_ (0)
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::ACE_Malloc_T");
// Use pool_name for lock_name if lock_name not passed.
const ACE_TCHAR *name = lock_name ? lock_name : pool_name;
this->lock_ = ACE_Malloc_Lock_Adapter_T<ACE_LOCK> ()(name);
if (this->lock_ == 0)
return;
this->delete_lock_ = true;
this->bad_flag_ = this->open ();
if (this->bad_flag_ == -1)
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("%p\n"),
ACE_TEXT ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::ACE_Malloc_T")));
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB>
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::ACE_Malloc_T (const ACE_TCHAR *pool_name,
const ACE_MEM_POOL_OPTIONS *options,
ACE_LOCK *lock)
: cb_ptr_ (0),
memory_pool_ (pool_name, options),
lock_ (lock),
delete_lock_ (false),
bad_flag_ (0)
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::ACE_Malloc_T");
if (lock == 0)
{
this->bad_flag_ = -1;
errno = EINVAL;
return;
}
this->bad_flag_ = this->open ();
if (this->bad_flag_ == -1)
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("%p\n"),
ACE_TEXT ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::ACE_Malloc_T")));
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB>
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::~ACE_Malloc_T (void)
{
ACE_TRACE ("ACE_Malloc_T<MEM_POOL>::~ACE_Malloc_T<MEM_POOL>");
if (this->delete_lock_)
{
delete this->lock_;
this->lock_ = 0;
}
}
// Clean up the resources allocated by ACE_Malloc_T.
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::remove (void)
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::remove");
// ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) destroying ACE_Malloc_T\n")));
#if defined (ACE_HAS_MALLOC_STATS)
this->print_stats ();
#endif /* ACE_HAS_MALLOC_STATS */
// Remove the ACE_LOCK.
if (this->delete_lock_)
this->lock_->remove ();
// Give the memory pool a chance to release its resources.
int const result = this->memory_pool_.release ();
// Reset this->cb_ptr_ as it is no longer valid.
// There's also no need to keep the reference counter as the
// underlying memory pool has been destroyed.
// Also notice that we are leaving the decision of removing
// the pool to users so they can map to the same mmap file
// again.
this->cb_ptr_ = 0;
return result;
}
// General-purpose memory allocator. Assumes caller holds the locks.
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> void *
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::shared_malloc (size_t nbytes)
{
#if !defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS)
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::shared_malloc");
#endif /* !ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */
if (this->cb_ptr_ == 0)
return 0;
// Round up request to a multiple of the MALLOC_HEADER size.
size_t const nunits =
(nbytes + sizeof (MALLOC_HEADER) - 1) / sizeof (MALLOC_HEADER)
+ 1; // Add one for the <MALLOC_HEADER> itself.
MALLOC_HEADER *prevp = 0;
MALLOC_HEADER *currp = 0;
ACE_SEH_TRY
{
// Begin the search starting at the place in the freelist where the
// last block was found.
prevp = this->cb_ptr_->freep_;
currp = prevp->next_block_;
}
#if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS)
ACE_SEH_EXCEPT (this->memory_pool_.seh_selector (GetExceptionInformation ()))
{
currp = prevp->next_block_;
}
#endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */
// Search the freelist to locate a block of the appropriate size.
while (1)
// *Warning* Do not use "continue" within this while-loop.
{
ACE_SEH_TRY
{
if (currp->size_ >= nunits) // Big enough
{
ACE_MALLOC_STATS (++this->cb_ptr_->malloc_stats_.ninuse_);
if (currp->size_ == nunits)
// Exact size, just update the pointers.
prevp->next_block_ = currp->next_block_;
else
{
// Remaining chunk is larger than requested block, so
// allocate at tail end.
ACE_MALLOC_STATS (++this->cb_ptr_->malloc_stats_.nblocks_);
currp->size_ -= nunits;
currp += currp->size_;
MALLOC_HEADER::init_ptr (&currp->next_block_,
0,
this->cb_ptr_);
currp->size_ = nunits;
}
this->cb_ptr_->freep_ = prevp;
// Skip over the MALLOC_HEADER when returning pointer.
return currp + 1;
}
else if (currp == this->cb_ptr_->freep_)
{
// We've wrapped around freelist without finding a
// block. Therefore, we need to ask the memory pool for
// a new chunk of bytes.
size_t chunk_bytes = 0;
currp = (MALLOC_HEADER *)
this->memory_pool_.acquire (nunits * sizeof (MALLOC_HEADER),
chunk_bytes);
void *remap_addr = this->memory_pool_.base_addr ();
if (remap_addr != 0)
this->cb_ptr_ = (ACE_CB *) remap_addr;
if (currp != 0)
{
ACE_MALLOC_STATS (++this->cb_ptr_->malloc_stats_.nblocks_);
ACE_MALLOC_STATS (++this->cb_ptr_->malloc_stats_.nchunks_);
ACE_MALLOC_STATS (++this->cb_ptr_->malloc_stats_.ninuse_);
MALLOC_HEADER::init_ptr (&currp->next_block_,
0,
this->cb_ptr_);
// Compute the chunk size in MALLOC_HEADER units.
currp->size_ = chunk_bytes / sizeof (MALLOC_HEADER);
// Insert the newly allocated chunk of memory into the
// free list. Add "1" to skip over the
// <MALLOC_HEADER> when freeing the pointer since
// the first thing <free> does is decrement by this
// amount.
this->shared_free (currp + 1);
currp = this->cb_ptr_->freep_;
}
else
return 0;
// Shouldn't do this here because of errors with the wchar ver
// This is because ACE_ERROR_RETURN converts the __FILE__ to
// wchar before printing out. The compiler will complain
// about this since a destructor would present in a SEH block
//ACE_ERROR_RETURN ((LM_ERROR,
// ACE_TEXT ("(%P|%t) %p\n"),
// ACE_TEXT ("malloc")),
// 0);
}
prevp = currp;
currp = currp->next_block_;
}
ACE_SEH_EXCEPT (this->memory_pool_.seh_selector (GetExceptionInformation ()))
{
}
}
ACE_NOTREACHED (return 0;)
}
// General-purpose memory allocator.
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> void *
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::malloc (size_t nbytes)
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::malloc");
ACE_GUARD_RETURN (ACE_LOCK, ace_mon, *this->lock_, 0);
return this->shared_malloc (nbytes);
}
// General-purpose memory allocator.
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> void *
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::calloc (size_t nbytes,
char initial_value)
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::calloc");
void *ptr = this->malloc (nbytes);
if (ptr != 0)
ACE_OS::memset (ptr, initial_value, nbytes);
return ptr;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> void *
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::calloc (size_t n_elem,
size_t elem_size,
char initial_value)
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::calloc");
return this->calloc (n_elem * elem_size, initial_value);
}
// Put block AP in the free list (must be called with locks held!)
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> void
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::shared_free (void *ap)
{
#if !defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS)
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::shared_free");
#endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */
if (ap == 0 || this->cb_ptr_ == 0)
return;
// Adjust AP to point to the block MALLOC_HEADER
MALLOC_HEADER *blockp = ((MALLOC_HEADER *) ap) - 1;
MALLOC_HEADER *currp = this->cb_ptr_->freep_;
// Search until we find the location where the blocks belongs. Note
// that addresses are kept in sorted order.
ACE_SEH_TRY
{
for (;
blockp <= currp
|| blockp >= (MALLOC_HEADER *) currp->next_block_;
currp = currp->next_block_)
{
if (currp >= (MALLOC_HEADER *) currp->next_block_
&& (blockp > currp
|| blockp < (MALLOC_HEADER *) currp->next_block_))
// Freed block at the start or the end of the memory pool.
break;
}
// Join to upper neighbor.
if ((blockp + blockp->size_) == currp->next_block_)
{
ACE_MALLOC_STATS (--this->cb_ptr_->malloc_stats_.nblocks_);
blockp->size_ += currp->next_block_->size_;
blockp->next_block_ = currp->next_block_->next_block_;
}
else
blockp->next_block_ = currp->next_block_;
// Join to lower neighbor.
if ((currp + currp->size_) == blockp)
{
ACE_MALLOC_STATS (--this->cb_ptr_->malloc_stats_.nblocks_);
currp->size_ += blockp->size_;
currp->next_block_ = blockp->next_block_;
}
else
currp->next_block_ = blockp;
ACE_MALLOC_STATS (--this->cb_ptr_->malloc_stats_.ninuse_);
this->cb_ptr_->freep_ = currp;
}
ACE_SEH_EXCEPT (this->memory_pool_.seh_selector (GetExceptionInformation ()))
{
}
}
// No locks held here, caller must acquire/release lock.
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> void*
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::shared_find (const char *name)
{
#if !defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS)
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::shared_find");
#endif /* !ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */
if (this->cb_ptr_ == 0)
return 0;
ACE_SEH_TRY
{
for (NAME_NODE *node = this->cb_ptr_->name_head_;
node != 0;
node = node->next_)
if (ACE_OS::strcmp (node->name (),
name) == 0)
return node;
}
ACE_SEH_EXCEPT (this->memory_pool_.seh_selector (GetExceptionInformation ()))
{
}
return 0;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::shared_bind (const char *name,
void *pointer)
{
if (this->cb_ptr_ == 0)
return -1;
// Combine the two allocations into one to avoid overhead...
NAME_NODE *new_node = 0;
ACE_ALLOCATOR_RETURN (new_node,
(NAME_NODE *)
this->shared_malloc (sizeof (NAME_NODE) +
ACE_OS::strlen (name) + 1),
-1);
char *name_ptr = (char *) (new_node + 1);
// Use operator placement new to insert <new_node> at the head of
// the linked list of <NAME_NODE>s.
NAME_NODE *result =
new (new_node) NAME_NODE (name,
name_ptr,
reinterpret_cast<char *> (pointer),
this->cb_ptr_->name_head_);
this->cb_ptr_->name_head_ = result;
return 0;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::trybind (const char *name,
void *&pointer)
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::trybind");
ACE_WRITE_GUARD_RETURN (ACE_LOCK, ace_mon, *this->lock_, -1);
NAME_NODE *node = (NAME_NODE *) this->shared_find (name);
if (node == 0)
// Didn't find it, so insert it.
return this->shared_bind (name, pointer);
// Found it, so return a copy of the current entry.
pointer = (char *) node->pointer_;
return 1;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::bind (const char *name,
void *pointer,
int duplicates)
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::bind");
ACE_WRITE_GUARD_RETURN (ACE_LOCK, ace_mon, *this->lock_, -1);
if (duplicates == 0 && this->shared_find (name) != 0)
// If we're not allowing duplicates, then if the name is already
// present, return 1.
return 1;
// If we get this far, either we're allowing duplicates or we didn't
// find the name yet.
return this->shared_bind (name, pointer);
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::find (const char *name,
void *&pointer)
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::find");
ACE_READ_GUARD_RETURN (ACE_LOCK, ace_mon, *this->lock_, -1);
NAME_NODE *node = (NAME_NODE *) this->shared_find (name);
if (node == 0)
return -1;
pointer = (char *) node->pointer_;
return 0;
}
// Returns a count of the number of available chunks that can hold
// <size> byte allocations. Function can be used to determine if you
// have reached a water mark. This implies a fixed amount of allocated
// memory.
//
// @param size - the chunk size of that you would like a count of
// @return function returns the number of chunks of the given size
// that would fit in the currently allocated memory
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> ssize_t
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::avail_chunks (size_t size) const
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::avail_chunks");
ACE_READ_GUARD_RETURN (ACE_LOCK, ace_mon, *this->lock_, -1);
if (this->cb_ptr_ == 0)
return -1;
size_t count = 0;
// Avoid dividing by 0...
size = size == 0 ? 1 : size;
MALLOC_HEADER *currp = this->cb_ptr_->freep_;
// Calculate how many will fit in this block.
do {
size_t avail_size = currp->size_ == 0 ? 0 : currp->size_ - 1;
if (avail_size * sizeof (MALLOC_HEADER) >= size)
count += avail_size * sizeof (MALLOC_HEADER) / size;
currp = currp->next_block_;
}
while (currp != this->cb_ptr_->freep_);
return count;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::find (const char *name)
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::find");
ACE_READ_GUARD_RETURN (ACE_LOCK, ace_mon, *this->lock_, -1);
return this->shared_find (name) == 0 ? -1 : 0;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::unbind (const char *name, void *&pointer)
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::unbind");
ACE_WRITE_GUARD_RETURN (ACE_LOCK, ace_mon, *this->lock_, -1);
if (this->cb_ptr_ == 0)
return -1;
NAME_NODE *prev = 0;
for (NAME_NODE *curr = this->cb_ptr_->name_head_;
curr != 0;
curr = curr->next_)
{
if (ACE_OS::strcmp (curr->name (), name) == 0)
{
pointer = (char *) curr->pointer_;
if (prev == 0)
this->cb_ptr_->name_head_ = curr->next_;
else
prev->next_ = curr->next_;
if (curr->next_)
curr->next_->prev_ = prev;
// This will free up both the node and the name due to our
// clever trick in <bind>!
this->shared_free (curr);
return 0;
}
prev = curr;
}
// Didn't find it, so fail.
return -1;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::unbind (const char *name)
{
ACE_TRACE ("ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::unbind");
void *temp = 0;
return this->unbind (name, temp);
}
/*****************************************************************************/
template <class ACE_LOCK> ACE_LOCK *
ACE_Malloc_Lock_Adapter_T<ACE_LOCK>::operator () (const ACE_TCHAR *name)
{
ACE_LOCK *p = 0;
if (name == 0)
ACE_NEW_RETURN (p, ACE_LOCK (name), 0);
else
ACE_NEW_RETURN (p, ACE_LOCK (ACE::basename (name,
ACE_DIRECTORY_SEPARATOR_CHAR)),
0);
return p;
}
/*****************************************************************************/
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> void
ACE_Malloc_LIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Malloc_LIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::dump");
ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
this->curr_->dump ();
this->guard_.dump ();
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("name_ = %C\n"), this->name_));
ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB>
ACE_Malloc_LIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::ACE_Malloc_LIFO_Iterator_T (ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB> &malloc,
const char *name)
: malloc_ (malloc),
curr_ (0),
guard_ (*malloc_.lock_),
name_ (name != 0 ? ACE_OS::strdup (name) : 0)
{
ACE_TRACE ("ACE_Malloc_LIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::ACE_Malloc_LIFO_Iterator_T");
// Cheap trick to make code simple.
// @@ Doug, this looks like trouble...
NAME_NODE temp;
this->curr_ = &temp;
this->curr_->next_ = malloc_.cb_ptr_->name_head_;
this->advance ();
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB>
ACE_Malloc_LIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::~ACE_Malloc_LIFO_Iterator_T (void)
{
ACE_OS::free ((void *) this->name_);
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_LIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::next (void *&next_entry,
const char *&name)
{
ACE_TRACE ("ACE_Malloc_LIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::next");
if (this->curr_ != 0)
{
next_entry = (char *) this->curr_->pointer_;
name = this->curr_->name ();
return 1;
}
else
return 0;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_LIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::next (void *&next_entry)
{
ACE_TRACE ("ACE_Malloc_LIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::next");
if (this->curr_ != 0)
{
next_entry = this->curr_->pointer_;
return 1;
}
else
return 0;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_LIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::done (void) const
{
ACE_TRACE ("ACE_Malloc_LIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::done");
return this->curr_ == 0;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_LIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::advance (void)
{
ACE_TRACE ("ACE_Malloc_LIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::advance");
this->curr_ = this->curr_->next_;
if (this->name_ == 0)
return this->curr_ != 0;
while (this->curr_ != 0
&& ACE_OS::strcmp (this->name_,
this->curr_->name ()) != 0)
this->curr_ = this->curr_->next_;
return this->curr_ != 0;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> void
ACE_Malloc_FIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Malloc_FIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::dump");
ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
this->curr_->dump ();
this->guard_.dump ();
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("name_ = %s\n"), this->name_));
ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB>
ACE_Malloc_FIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::ACE_Malloc_FIFO_Iterator_T (ACE_Malloc_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB> &malloc,
const char *name)
: malloc_ (malloc),
curr_ (0),
guard_ (*malloc_.lock_),
name_ (name != 0 ? ACE_OS::strdup (name) : 0)
{
ACE_TRACE ("ACE_Malloc_FIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::ACE_Malloc_FIFO_Iterator");
// Cheap trick to make code simple.
// @@ Doug, this looks like trouble...
NAME_NODE temp;
this->curr_ = &temp;
this->curr_->next_ = malloc_.cb_ptr_->name_head_;
this->curr_->prev_ = 0;
// Go to the first element that was inserted.
this->start ();
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB>
ACE_Malloc_FIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::~ACE_Malloc_FIFO_Iterator_T (void)
{
ACE_OS::free ((void *) this->name_);
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_FIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::next (void *&next_entry,
const char *&name)
{
ACE_TRACE ("ACE_Malloc_FIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::next");
if (this->curr_ != 0)
{
next_entry = (char *) this->curr_->pointer_;
name = this->curr_->name ();
return 1;
}
else
return 0;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_FIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::next (void *&next_entry)
{
ACE_TRACE ("ACE_Malloc_FIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::next");
if (this->curr_ != 0)
{
next_entry = this->curr_->pointer_;
return 1;
}
else
return 0;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_FIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::done (void) const
{
ACE_TRACE ("ACE_Malloc_FIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::done");
return this->curr_ == 0;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_FIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::advance (void)
{
ACE_TRACE ("ACE_Malloc_FIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::advance");
this->curr_ = this->curr_->prev_;
if (this->name_ == 0)
return this->curr_ != 0;
while (this->curr_ != 0
&& ACE_OS::strcmp (this->name_,
this->curr_->name ()) != 0)
this->curr_ = this->curr_->prev_;
return this->curr_ != 0;
}
template <ACE_MEM_POOL_1, class ACE_LOCK, class ACE_CB> int
ACE_Malloc_FIFO_Iterator_T<ACE_MEM_POOL_2, ACE_LOCK, ACE_CB>::start (void)
{
this->curr_ = this->curr_->next_;
NAME_NODE *prev = 0;
// Locate the element that was inserted first.
// @@ We could optimize this by making the list a circular list or
// storing an extra pointer.
while (this->curr_ != 0)
{
prev = this->curr_;
this->curr_ = this->curr_->next_;
}
this->curr_ = prev;
return this->curr_ != 0;
}
ACE_END_VERSIONED_NAMESPACE_DECL
#endif /* ACE_MALLOC_T_CPP */
| gpl-2.0 |
sudosurootdev/binutils | intl/dcngettext.c | 551 | 1916 | /* Implementation of the dcngettext(3) function.
Copyright (C) 1995-1999, 2000, 2001, 2002 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published
by the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301,
USA. */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "gettextP.h"
#ifdef _LIBC
# include <libintl.h>
#else
# include "libgnuintl.h"
#endif
/* @@ end of prolog @@ */
/* Names for the libintl functions are a problem. They must not clash
with existing names and they should follow ANSI C. But this source
code is also used in GNU C Library where the names have a __
prefix. So we have to make a difference here. */
#ifdef _LIBC
# define DCNGETTEXT __dcngettext
# define DCIGETTEXT __dcigettext
#else
# define DCNGETTEXT libintl_dcngettext
# define DCIGETTEXT libintl_dcigettext
#endif
/* Look up MSGID in the DOMAINNAME message catalog for the current CATEGORY
locale. */
char *
DCNGETTEXT (domainname, msgid1, msgid2, n, category)
const char *domainname;
const char *msgid1;
const char *msgid2;
unsigned long int n;
int category;
{
return DCIGETTEXT (domainname, msgid1, msgid2, 1, n, category);
}
#ifdef _LIBC
/* Alias for function name in GNU C Library. */
weak_alias (__dcngettext, dcngettext);
#endif
| gpl-2.0 |
cryptickid/android_kernel_oneplus_msm8974 | drivers/staging/prima/CORE/SAP/src/sapFsm.c | 551 | 58755 | /*
* Copyright (c) 2012-2013 The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/*
* This file was originally distributed by Qualcomm Atheros, Inc.
* under proprietary terms before Copyright ownership was assigned
* to the Linux Foundation.
*/
/*===========================================================================
s a p F s m . C
OVERVIEW:
This software unit holds the implementation of the WLAN SAP Finite
State Machine modules
DEPENDENCIES:
Are listed for each API below.
Copyright (c) 2010 QUALCOMM Incorporated.
All Rights Reserved.
Qualcomm Confidential and Proprietary
===========================================================================*/
/*===========================================================================
EDIT HISTORY FOR FILE
This section contains comments describing changes made to the module.
Notice that changes are listed in reverse chronological order.
when who what, where, why
---------- --- --------------------------------------------------------
2010-03-15 Created module
===========================================================================*/
/*----------------------------------------------------------------------------
* Include Files
* -------------------------------------------------------------------------*/
#include "sapInternal.h"
// Pick up the SME API definitions
#include "sme_Api.h"
// Pick up the PMC API definitions
#include "pmcApi.h"
#include "wlan_nv.h"
/*----------------------------------------------------------------------------
* Preprocessor Definitions and Constants
* -------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
* Type Declarations
* -------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
* Global Data Definitions
* -------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
* External declarations for global context
* -------------------------------------------------------------------------*/
#ifdef FEATURE_WLAN_CH_AVOID
extern safeChannelType safeChannels[];
#endif /* FEATURE_WLAN_CH_AVOID */
/*----------------------------------------------------------------------------
* Static Variable Definitions
* -------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
* Static Function Declarations and Definitions
* -------------------------------------------------------------------------*/
#ifdef SOFTAP_CHANNEL_RANGE
static VOS_STATUS sapGetChannelList(ptSapContext sapContext, v_U8_t **channelList,
v_U8_t *numberOfChannels);
#endif
/*----------------------------------------------------------------------------
* Externalized Function Definitions
* -------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
* Function Declarations and Documentation
* -------------------------------------------------------------------------*/
/*==========================================================================
FUNCTION sapEventInit
DESCRIPTION
Function for initializing sWLAN_SAPEvent structure
DEPENDENCIES
NA.
PARAMETERS
IN
sapEvent : State machine event
RETURN VALUE
None
SIDE EFFECTS
============================================================================*/
static inline void sapEventInit(ptWLAN_SAPEvent sapEvent)
{
sapEvent->event = eSAP_MAC_SCAN_COMPLETE;
sapEvent->params = 0;
sapEvent->u1 = 0;
sapEvent->u2 = 0;
}
/*==========================================================================
FUNCTION sapGotoChannelSel
DESCRIPTION
Function for initiating scan request for SME
DEPENDENCIES
NA.
PARAMETERS
IN
sapContext : Sap Context value
sapEvent : State machine event
RETURN VALUE
The VOS_STATUS code associated with performing the operation
VOS_STATUS_SUCCESS: Success
SIDE EFFECTS
============================================================================*/
VOS_STATUS
sapGotoChannelSel
(
ptSapContext sapContext,
ptWLAN_SAPEvent sapEvent
)
{
/* Initiate a SCAN request */
eHalStatus halStatus;
tCsrScanRequest scanRequest;/* To be initialised if scan is required */
v_U32_t scanRequestID = 0;
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
#ifdef SOFTAP_CHANNEL_RANGE
v_U8_t *channelList = NULL;
v_U8_t numOfChannels = 0 ;
#endif
tHalHandle hHal;
tANI_U8 channel;
hHal = (tHalHandle)vos_get_context( VOS_MODULE_ID_SME, sapContext->pvosGCtx);
if (NULL == hHal)
{
/* we have a serious problem */
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_FATAL,
"In %s, invalid hHal", __func__);
return VOS_STATUS_E_FAULT;
}
/*If STA-AP concurrency is enabled take the concurrent connected channel first. In other cases wpa_supplicant should take care */
if (vos_get_concurrency_mode() == VOS_STA_SAP)
{
channel = sme_GetConcurrentOperationChannel(hHal);
if (channel)
{ /*if a valid channel is returned then use concurrent channel.
Else take whatever comes from configuartion*/
sapContext->channel = channel;
sme_SelectCBMode(hHal,
sapConvertSapPhyModeToCsrPhyMode(sapContext->csrRoamProfile.phyMode),
channel);
}
}
if (sapContext->channel == AUTO_CHANNEL_SELECT)
{
vos_mem_zero(&scanRequest, sizeof(scanRequest));
/* Set scanType to Passive scan */
scanRequest.scanType = eSIR_PASSIVE_SCAN;
/* Set min and max channel time to zero */
scanRequest.minChnTime = 0;
scanRequest.maxChnTime = 0;
/* Set BSSType to default type */
scanRequest.BSSType = eCSR_BSS_TYPE_ANY;
#ifndef SOFTAP_CHANNEL_RANGE
/*Scan all the channels */
scanRequest.ChannelInfo.numOfChannels = 0;
scanRequest.ChannelInfo.ChannelList = NULL;
scanRequest.requestType = eCSR_SCAN_REQUEST_FULL_SCAN;//eCSR_SCAN_REQUEST_11D_SCAN;
#else
sapGetChannelList(sapContext, &channelList, &numOfChannels);
/*Scan the channels in the list*/
scanRequest.ChannelInfo.numOfChannels = numOfChannels;
scanRequest.ChannelInfo.ChannelList = channelList;
scanRequest.requestType = eCSR_SCAN_SOFTAP_CHANNEL_RANGE;
sapContext->numofChannel = numOfChannels;
sapContext->channelList = channelList;
#endif
/* Set requestType to Full scan */
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, calling sme_ScanRequest", __func__);
halStatus = sme_ScanRequest(hHal,
0,//Not used in csrScanRequest
&scanRequest,
&scanRequestID,//, when ID == 0 11D scan/active scan with callback, min-maxChntime set in csrScanRequest()?
&WLANSAP_ScanCallback,//csrScanCompleteCallback callback,
sapContext);//void * pContext scanRequestID filled up
if (eHAL_STATUS_SUCCESS != halStatus)
{
VOS_TRACE(VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR, "%s:sme_ScanRequest fail %d!!!", __func__, halStatus);
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "SoftAP Configuring for default channel, Ch= %d", sapContext->channel);
/* In case of error, switch to default channel */
sapContext->channel = SAP_DEFAULT_CHANNEL;
#ifdef SOFTAP_CHANNEL_RANGE
if(sapContext->channelList != NULL)
{
sapContext->channel = sapContext->channelList[0];
vos_mem_free(sapContext->channelList);
sapContext->channelList = NULL;
}
#endif
/* Fill in the event structure */
sapEventInit(sapEvent);
/* Handle event */
vosStatus = sapFsm(sapContext, sapEvent);
}
else
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, return from sme_ScanRequest, scanRequestID=%d, Ch= %d",
__func__, scanRequestID, sapContext->channel);
}
}
else
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, for configured channel, Ch= %d", __func__, sapContext->channel);
/* Fill in the event structure */
// Eventhough scan was not done, means a user set channel was chosen
sapEventInit(sapEvent);
/* Handle event */
vosStatus = sapFsm(sapContext, sapEvent);
}
/* If scan failed, get default channel and advance state machine as success with default channel */
/* Have to wait for the call back to be called to get the channel cannot advance state machine here as said above */
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, before exiting sapGotoChannelSel channel=%d", __func__, sapContext->channel);
return VOS_STATUS_SUCCESS;
}// sapGotoChannelSel
/*==========================================================================
FUNCTION sapGotoStarting
DESCRIPTION
Function for initiating start bss request for SME
DEPENDENCIES
NA.
PARAMETERS
IN
sapContext : Sap Context value
sapEvent : State machine event
bssType : Type of bss to start, INRA AP
status : Return the SAP status here
RETURN VALUE
The VOS_STATUS code associated with performing the operation
VOS_STATUS_SUCCESS: Success
SIDE EFFECTS
============================================================================*/
VOS_STATUS
sapGotoStarting
(
ptSapContext sapContext,
ptWLAN_SAPEvent sapEvent,
eCsrRoamBssType bssType
)
{
/* tHalHandle */
tHalHandle hHal = VOS_GET_HAL_CB(sapContext->pvosGCtx);
eHalStatus halStatus;
/*- - - - - - - - TODO:once configs from hdd available - - - - - - - - -*/
char key_material[32]={ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1,};
sapContext->key_type = 0x05;
sapContext->key_length = 32;
vos_mem_copy(sapContext->key_material, key_material, sizeof(key_material)); /* Need a key size define */
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s", __func__);
if (NULL == hHal)
{
/* we have a serious problem */
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_FATAL,
"In %s, invalid hHal", __func__);
return VOS_STATUS_E_FAULT;
}
//TODO: What shall we do if failure????
halStatus = pmcRequestFullPower( hHal,
WLANSAP_pmcFullPwrReqCB,
sapContext,
eSME_REASON_OTHER);
/* Open SME Session for Softap */
halStatus = sme_OpenSession(hHal,
&WLANSAP_RoamCallback,
sapContext,
sapContext->self_mac_addr,
&sapContext->sessionId);
if(eHAL_STATUS_SUCCESS != halStatus )
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR, "Error: In %s calling sme_RoamConnect status = %d", __func__, halStatus);
return VOS_STATUS_E_FAILURE;
}
return VOS_STATUS_SUCCESS;
}// sapGotoStarting
/*==========================================================================
FUNCTION sapGotoDisconnecting
DESCRIPTION
Processing of SAP FSM Disconnecting state
DEPENDENCIES
NA.
PARAMETERS
IN
sapContext : Sap Context value
status : Return the SAP status here
RETURN VALUE
The VOS_STATUS code associated with performing the operation
VOS_STATUS_SUCCESS: Success
SIDE EFFECTS
============================================================================*/
VOS_STATUS
sapGotoDisconnecting
(
ptSapContext sapContext
)
{
eHalStatus halStatus;
tHalHandle hHal;
hHal = VOS_GET_HAL_CB(sapContext->pvosGCtx);
if (NULL == hHal)
{
/* we have a serious problem */
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"In %s, invalid hHal", __func__);
return VOS_STATUS_E_FAULT;
}
sapFreeRoamProfile(&sapContext->csrRoamProfile);
halStatus = sme_RoamStopBss(hHal, sapContext->sessionId);
if(eHAL_STATUS_SUCCESS != halStatus )
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR, "Error: In %s calling sme_RoamStopBss status = %d", __func__, halStatus);
return VOS_STATUS_E_FAILURE;
}
return VOS_STATUS_SUCCESS;
}
static eHalStatus sapRoamSessionCloseCallback(void *pContext)
{
ptSapContext sapContext = (ptSapContext)pContext;
return sapSignalHDDevent(sapContext, NULL,
eSAP_STOP_BSS_EVENT, (v_PVOID_t) eSAP_STATUS_SUCCESS);
}
/*==========================================================================
FUNCTION sapGotoDisconnected
DESCRIPTION
Function for setting the SAP FSM to Disconnection state
DEPENDENCIES
NA.
PARAMETERS
IN
sapContext : Sap Context value
sapEvent : State machine event
status : Return the SAP status here
RETURN VALUE
The VOS_STATUS code associated with performing the operation
VOS_STATUS_SUCCESS: Success
SIDE EFFECTS
============================================================================*/
VOS_STATUS
sapGotoDisconnected
(
ptSapContext sapContext
)
{
VOS_STATUS vosStatus = VOS_STATUS_E_FAILURE;
tWLAN_SAPEvent sapEvent;
// Processing has to be coded
// Clean up stations from TL etc as AP BSS is shut down then set event
sapEvent.event = eSAP_MAC_READY_FOR_CONNECTIONS;// hardcoded
sapEvent.params = 0;
sapEvent.u1 = 0;
sapEvent.u2 = 0;
/* Handle event */
vosStatus = sapFsm(sapContext, &sapEvent);
return vosStatus;
}
/*==========================================================================
FUNCTION sapSignalHDDevent
DESCRIPTION
Function for HDD to send the event notification using callback
DEPENDENCIES
NA.
PARAMETERS
IN
sapContext : Sap Context value
pCsrRoamInfo : Pointer to CSR roam information
sapHddevent : SAP HDD event
context : to pass the element for future support
RETURN VALUE
The VOS_STATUS code associated with performing the operation
VOS_STATUS_SUCCESS: Success
SIDE EFFECTS
============================================================================*/
VOS_STATUS
sapSignalHDDevent
(
ptSapContext sapContext, /* sapContext value */
tCsrRoamInfo *pCsrRoamInfo,
eSapHddEvent sapHddevent,
void *context
)
{
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
tSap_Event sapApAppEvent; /* This now encodes ALL event types */
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
/* Format the Start BSS Complete event to return... */
if (NULL == sapContext->pfnSapEventCallback)
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR, "%s: HDD Event"
" callaback invalid", __func__);
return VOS_STATUS_E_INVAL;
}
switch (sapHddevent)
{
case eSAP_STA_ASSOC_IND:
// TODO - Indicate the assoc request indication to OS
sapApAppEvent.sapHddEventCode = eSAP_STA_ASSOC_IND;
vos_mem_copy( &sapApAppEvent.sapevt.sapAssocIndication.staMac, pCsrRoamInfo->peerMac,sizeof(tSirMacAddr));
sapApAppEvent.sapevt.sapAssocIndication.staId = pCsrRoamInfo->staId;
sapApAppEvent.sapevt.sapAssocIndication.status = 0;
// Required for indicating the frames to upper layer
sapApAppEvent.sapevt.sapAssocIndication.beaconLength = pCsrRoamInfo->beaconLength;
sapApAppEvent.sapevt.sapAssocIndication.beaconPtr = pCsrRoamInfo->beaconPtr;
sapApAppEvent.sapevt.sapAssocIndication.assocReqLength = pCsrRoamInfo->assocReqLength;
sapApAppEvent.sapevt.sapAssocIndication.assocReqPtr = pCsrRoamInfo->assocReqPtr;
sapApAppEvent.sapevt.sapAssocIndication.fWmmEnabled = pCsrRoamInfo->wmmEnabledSta;
if ( pCsrRoamInfo->u.pConnectedProfile != NULL )
{
sapApAppEvent.sapevt.sapAssocIndication.negotiatedAuthType = pCsrRoamInfo->u.pConnectedProfile->AuthType;
sapApAppEvent.sapevt.sapAssocIndication.negotiatedUCEncryptionType = pCsrRoamInfo->u.pConnectedProfile->EncryptionType;
sapApAppEvent.sapevt.sapAssocIndication.negotiatedMCEncryptionType = pCsrRoamInfo->u.pConnectedProfile->mcEncryptionType;
sapApAppEvent.sapevt.sapAssocIndication.fAuthRequired = pCsrRoamInfo->fAuthRequired;
}
break;
case eSAP_START_BSS_EVENT:
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, SAP event callback event = %s",
__func__, "eSAP_START_BSS_EVENT");
sapApAppEvent.sapHddEventCode = eSAP_START_BSS_EVENT;
sapApAppEvent.sapevt.sapStartBssCompleteEvent.status = (eSapStatus )context;
if(pCsrRoamInfo != NULL ){
sapApAppEvent.sapevt.sapStartBssCompleteEvent.staId = pCsrRoamInfo->staId;
}
else
sapApAppEvent.sapevt.sapStartBssCompleteEvent.staId = 0;
sapApAppEvent.sapevt.sapStartBssCompleteEvent.operatingChannel = (v_U8_t)sapContext->channel;
break;
case eSAP_STOP_BSS_EVENT:
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, SAP event callback event = %s",
__func__, "eSAP_STOP_BSS_EVENT");
sapApAppEvent.sapHddEventCode = eSAP_STOP_BSS_EVENT;
sapApAppEvent.sapevt.sapStopBssCompleteEvent.status = (eSapStatus )context;
break;
case eSAP_STA_ASSOC_EVENT:
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, SAP event callback event = %s",
__func__, "eSAP_STA_ASSOC_EVENT");
if (pCsrRoamInfo->fReassocReq)
sapApAppEvent.sapHddEventCode = eSAP_STA_REASSOC_EVENT;
else
sapApAppEvent.sapHddEventCode = eSAP_STA_ASSOC_EVENT;
//TODO: Need to fill the SET KEY information and pass to HDD
vos_mem_copy( &sapApAppEvent.sapevt.sapStationAssocReassocCompleteEvent.staMac,
pCsrRoamInfo->peerMac,sizeof(tSirMacAddr));
sapApAppEvent.sapevt.sapStationAssocReassocCompleteEvent.staId = pCsrRoamInfo->staId ;
sapApAppEvent.sapevt.sapStationAssocReassocCompleteEvent.statusCode = pCsrRoamInfo->statusCode;
sapApAppEvent.sapevt.sapStationAssocReassocCompleteEvent.iesLen = pCsrRoamInfo->rsnIELen;
vos_mem_copy(sapApAppEvent.sapevt.sapStationAssocReassocCompleteEvent.ies, pCsrRoamInfo->prsnIE,
pCsrRoamInfo->rsnIELen);
if(pCsrRoamInfo->addIELen)
{
v_U8_t len = sapApAppEvent.sapevt.sapStationAssocReassocCompleteEvent.iesLen;
sapApAppEvent.sapevt.sapStationAssocReassocCompleteEvent.iesLen
+= pCsrRoamInfo->addIELen;
vos_mem_copy(&sapApAppEvent.sapevt.sapStationAssocReassocCompleteEvent.ies[len], pCsrRoamInfo->paddIE,
pCsrRoamInfo->addIELen);
}
sapApAppEvent.sapevt.sapStationAssocReassocCompleteEvent.wmmEnabled = pCsrRoamInfo->wmmEnabledSta;
sapApAppEvent.sapevt.sapStationAssocReassocCompleteEvent.status = (eSapStatus )context;
//TODO: Need to fill sapAuthType
//sapApAppEvent.sapevt.sapStationAssocReassocCompleteEvent.SapAuthType = pCsrRoamInfo->pProfile->negotiatedAuthType;
break;
}
case eSAP_STA_DISASSOC_EVENT:
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, SAP event callback event = %s",
__func__, "eSAP_STA_DISASSOC_EVENT");
sapApAppEvent.sapHddEventCode = eSAP_STA_DISASSOC_EVENT;
vos_mem_copy( &sapApAppEvent.sapevt.sapStationDisassocCompleteEvent.staMac,
pCsrRoamInfo->peerMac, sizeof(tSirMacAddr));
sapApAppEvent.sapevt.sapStationDisassocCompleteEvent.staId = pCsrRoamInfo->staId;
if (pCsrRoamInfo->reasonCode == eCSR_ROAM_RESULT_FORCED)
sapApAppEvent.sapevt.sapStationDisassocCompleteEvent.reason = eSAP_USR_INITATED_DISASSOC;
else
sapApAppEvent.sapevt.sapStationDisassocCompleteEvent.reason = eSAP_MAC_INITATED_DISASSOC;
sapApAppEvent.sapevt.sapStationDisassocCompleteEvent.statusCode = pCsrRoamInfo->statusCode;
sapApAppEvent.sapevt.sapStationDisassocCompleteEvent.status = (eSapStatus )context;
break;
case eSAP_STA_SET_KEY_EVENT:
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, SAP event callback event = %s",
__func__, "eSAP_STA_SET_KEY_EVENT");
sapApAppEvent.sapHddEventCode = eSAP_STA_SET_KEY_EVENT;
sapApAppEvent.sapevt.sapStationSetKeyCompleteEvent.status = (eSapStatus )context;
vos_mem_copy(&sapApAppEvent.sapevt.sapStationSetKeyCompleteEvent.peerMacAddr,
pCsrRoamInfo->peerMac,sizeof(tSirMacAddr));
break;
case eSAP_STA_DEL_KEY_EVENT :
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, SAP event callback event = %s",
__func__, "eSAP_STA_DEL_KEY_EVENT");
sapApAppEvent.sapHddEventCode = eSAP_STA_DEL_KEY_EVENT;
sapApAppEvent.sapevt.sapStationDeleteKeyCompleteEvent.status = (eSapStatus )context;
//TODO: Should we need to send the key information
//sapApAppEvent.sapevt.sapStationDeleteKeyCompleteEvent.keyId = ;
break;
case eSAP_STA_MIC_FAILURE_EVENT :
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, SAP event callback event = %s",
__func__, "eSAP_STA_MIC_FAILURE_EVENT");
sapApAppEvent.sapHddEventCode = eSAP_STA_MIC_FAILURE_EVENT;
vos_mem_copy( &sapApAppEvent.sapevt.sapStationMICFailureEvent.srcMacAddr,
pCsrRoamInfo->u.pMICFailureInfo->srcMacAddr,
sizeof(tSirMacAddr));
vos_mem_copy( &sapApAppEvent.sapevt.sapStationMICFailureEvent.staMac,
pCsrRoamInfo->u.pMICFailureInfo->taMacAddr,
sizeof(tSirMacAddr));
vos_mem_copy( &sapApAppEvent.sapevt.sapStationMICFailureEvent.dstMacAddr,
pCsrRoamInfo->u.pMICFailureInfo->dstMacAddr,
sizeof(tSirMacAddr));
sapApAppEvent.sapevt.sapStationMICFailureEvent.multicast = pCsrRoamInfo->u.pMICFailureInfo->multicast;
sapApAppEvent.sapevt.sapStationMICFailureEvent.IV1 = pCsrRoamInfo->u.pMICFailureInfo->IV1;
sapApAppEvent.sapevt.sapStationMICFailureEvent.keyId = pCsrRoamInfo->u.pMICFailureInfo->keyId;
vos_mem_copy( sapApAppEvent.sapevt.sapStationMICFailureEvent.TSC,
pCsrRoamInfo->u.pMICFailureInfo->TSC,
SIR_CIPHER_SEQ_CTR_SIZE);
break;
case eSAP_ASSOC_STA_CALLBACK_EVENT:
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, SAP event callback event = %s",
__func__, "eSAP_ASSOC_STA_CALLBACK_EVENT");
break;
case eSAP_WPS_PBC_PROBE_REQ_EVENT:
sapApAppEvent.sapHddEventCode = eSAP_WPS_PBC_PROBE_REQ_EVENT;
vos_mem_copy( &sapApAppEvent.sapevt.sapPBCProbeReqEvent.WPSPBCProbeReq,
pCsrRoamInfo->u.pWPSPBCProbeReq,
sizeof(tSirWPSPBCProbeReq));
break;
case eSAP_INDICATE_MGMT_FRAME:
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"In %s, SAP event callback event = %s",
__func__, "eSAP_INDICATE_MGMT_FRAME");
sapApAppEvent.sapHddEventCode = eSAP_INDICATE_MGMT_FRAME;
sapApAppEvent.sapevt.sapManagementFrameInfo.nFrameLength
= pCsrRoamInfo->nFrameLength;
sapApAppEvent.sapevt.sapManagementFrameInfo.pbFrames
= pCsrRoamInfo->pbFrames;
sapApAppEvent.sapevt.sapManagementFrameInfo.frameType
= pCsrRoamInfo->frameType;
sapApAppEvent.sapevt.sapManagementFrameInfo.rxChan
= pCsrRoamInfo->rxChan;
break;
case eSAP_REMAIN_CHAN_READY:
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"In %s, SAP event callback event = %s",
__func__, "eSAP_REMAIN_CHAN_READY");
sapApAppEvent.sapHddEventCode = eSAP_REMAIN_CHAN_READY;
break;
case eSAP_SEND_ACTION_CNF:
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"In %s, SAP event callback event = %s",
__func__, "eSAP_SEND_ACTION_CNF");
sapApAppEvent.sapHddEventCode = eSAP_SEND_ACTION_CNF;
sapApAppEvent.sapevt.sapActionCnf.actionSendSuccess = (eSapStatus)context;
break;
case eSAP_DISCONNECT_ALL_P2P_CLIENT:
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"In %s, SAP event callback event = %s",
__func__, "eSAP_DISCONNECT_ALL_P2P_CLIENT");
sapApAppEvent.sapHddEventCode = eSAP_DISCONNECT_ALL_P2P_CLIENT;
sapApAppEvent.sapevt.sapActionCnf.actionSendSuccess = (eSapStatus)context;
break;
case eSAP_MAC_TRIG_STOP_BSS_EVENT :
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"In %s, SAP event callback event = %s",
__func__, "eSAP_MAC_TRIG_STOP_BSS_EVENT");
sapApAppEvent.sapHddEventCode = eSAP_MAC_TRIG_STOP_BSS_EVENT;
sapApAppEvent.sapevt.sapActionCnf.actionSendSuccess = (eSapStatus)context;
break;
case eSAP_UNKNOWN_STA_JOIN:
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"In %s, SAP event callback event = %s",
__func__, "eSAP_UNKNOWN_STA_JOIN");
sapApAppEvent.sapHddEventCode = eSAP_UNKNOWN_STA_JOIN;
vos_mem_copy((v_PVOID_t)sapApAppEvent.sapevt.sapUnknownSTAJoin.macaddr.bytes,
(v_PVOID_t)context, sizeof(v_MACADDR_t));
break;
case eSAP_MAX_ASSOC_EXCEEDED:
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"In %s, SAP event callback event = %s",
__func__, "eSAP_MAX_ASSOC_EXCEEDED");
sapApAppEvent.sapHddEventCode = eSAP_MAX_ASSOC_EXCEEDED;
vos_mem_copy((v_PVOID_t)sapApAppEvent.sapevt.sapMaxAssocExceeded.macaddr.bytes,
(v_PVOID_t)pCsrRoamInfo->peerMac, sizeof(v_MACADDR_t));
break;
default:
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR, "In %s, SAP Unknown callback event = %d",
__func__,sapHddevent);
break;
}
vosStatus = (*sapContext->pfnSapEventCallback)
(
&sapApAppEvent,
sapContext->pUsrContext//userdataforcallback - hdd opaque handle
);
return vosStatus;
} /* sapSignalApAppStartBssEvent */
/*==========================================================================
FUNCTION sapFsm
DESCRIPTION
SAP State machine entry function
DEPENDENCIES
NA.
PARAMETERS
IN
sapContext : Sap Context value
sapEvent : State machine event
status : Return the SAP status here
RETURN VALUE
The VOS_STATUS code associated with performing the operation
VOS_STATUS_SUCCESS: Success
SIDE EFFECTS
============================================================================*/
VOS_STATUS
sapFsm
(
ptSapContext sapContext, /* sapContext value */
ptWLAN_SAPEvent sapEvent /* State machine event */
)
{
/* Retrieve the phy link state machine structure
* from the sapContext value
*/
eSapFsmStates_t stateVar = sapContext->sapsMachine; /*state var that keeps track of state machine*/
tCsrRoamInfo *roamInfo = (tCsrRoamInfo *)(sapEvent->params);
v_U32_t msg = sapEvent->event; /* State machine input event message */
VOS_STATUS vosStatus = VOS_STATUS_E_FAILURE;
switch (stateVar)
{
case eSAP_DISCONNECTED:
if ((msg == eSAP_HDD_START_INFRA_BSS))
{
/* Transition from eSAP_DISCONNECTED to eSAP_CH_SELECT (both without substates) */
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, new from state %s => %s",
__func__, "eSAP_DISCONNECTED", "eSAP_CH_SELECT");
/* There can be one SAP Session for softap */
if (sapContext->isSapSessionOpen == eSAP_TRUE)
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_FATAL,
"%s:SME Session is already opened\n",__func__);
return VOS_STATUS_E_EXISTS;
}
sapContext->sessionId = 0xff;
/* Set SAP device role */
sapContext->sapsMachine = eSAP_CH_SELECT;
/* Perform sme_ScanRequest */
vosStatus = sapGotoChannelSel(sapContext, sapEvent);
/* Transition from eSAP_DISCONNECTED to eSAP_CH_SELECT (both without substates) */
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, from state %s => %s",
__func__, "eSAP_DISCONNECTED", "eSAP_CH_SELECT");
}
else
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR, "In %s, in state %s, event msg %d",
__func__, "eSAP_DISCONNECTED", msg);
}
break;
case eSAP_CH_SELECT:
if (msg == eSAP_MAC_SCAN_COMPLETE)
{
/* Transition from eSAP_CH_SELECT to eSAP_STARTING (both without substates) */
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, from state %s => %s",
__func__, "eSAP_CH_SELECT", "eSAP_STARTING");
// Channel selected. Now can sapGotoStarting
sapContext->sapsMachine = eSAP_STARTING;
// Specify the channel
sapContext->csrRoamProfile.ChannelInfo.numOfChannels = 1;
sapContext->csrRoamProfile.ChannelInfo.ChannelList = &sapContext->csrRoamProfile.operationChannel;
sapContext->csrRoamProfile.operationChannel = (tANI_U8)sapContext->channel;
vosStatus = sapGotoStarting( sapContext, sapEvent, eCSR_BSS_TYPE_INFRA_AP);
/* Transition from eSAP_CH_SELECT to eSAP_STARTING (both without substates) */
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, from state %s => %s",
__func__, "eSAP_CH_SELECT", "eSAP_STARTING");
}
else
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR, "In %s, in state %s, invalid event msg %d",
__func__, "eSAP_CH_SELECT", msg);
}
break;
case eSAP_STARTING:
if (msg == eSAP_MAC_START_BSS_SUCCESS )
{
/* Transition from eSAP_STARTING to eSAP_STARTED (both without substates) */
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, from state channel = %d %s => %s",
__func__,sapContext->channel, "eSAP_STARTING", "eSAP_STARTED");
sapContext->sapsMachine = eSAP_STARTED;
/*Action code for transition */
vosStatus = sapSignalHDDevent( sapContext, roamInfo, eSAP_START_BSS_EVENT, (v_PVOID_t)eSAP_STATUS_SUCCESS);
/* Transition from eSAP_STARTING to eSAP_STARTED (both without substates) */
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, from state %s => %s",
__func__, "eSAP_STARTING", "eSAP_STARTED");
}
else if (msg == eSAP_MAC_START_FAILS)
{
/*Transition from STARTING to DISCONNECTED (both without substates)*/
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR, "In %s, from state %s => %s",
__func__, "eSAP_STARTING", "eSAP_DISCONNECTED");
/*Action code for transition */
vosStatus = sapSignalHDDevent( sapContext, NULL, eSAP_START_BSS_EVENT,(v_PVOID_t) eSAP_STATUS_FAILURE);
vosStatus = sapGotoDisconnected(sapContext);
/*Advance outer statevar */
sapContext->sapsMachine = eSAP_DISCONNECTED;
}
else if (msg == eSAP_HDD_STOP_INFRA_BSS)
{
/*Transition from eSAP_STARTING to eSAP_DISCONNECTING (both without substates)*/
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, from state %s => %s",
__func__, "eSAP_STARTING", "eSAP_DISCONNECTING");
/*Advance outer statevar */
sapContext->sapsMachine = eSAP_DISCONNECTED;
vosStatus = sapSignalHDDevent( sapContext, NULL, eSAP_START_BSS_EVENT, (v_PVOID_t)eSAP_STATUS_FAILURE);
vosStatus = sapGotoDisconnected(sapContext);
/* Close the SME session*/
if (eSAP_TRUE == sapContext->isSapSessionOpen)
{
tHalHandle hHal = VOS_GET_HAL_CB(sapContext->pvosGCtx);
if (NULL == hHal)
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"In %s, NULL hHal in state %s, msg %d",
__func__, "eSAP_STARTING", msg);
}
else if (eHAL_STATUS_SUCCESS ==
sme_CloseSession(hHal,
sapContext->sessionId, NULL, NULL))
{
sapContext->isSapSessionOpen = eSAP_FALSE;
}
}
}
else
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"In %s, in state %s, invalid event msg %d",
__func__, "eSAP_STARTING", msg);
/* Intentionally left blank */
}
break;
case eSAP_STARTED:
if (msg == eSAP_HDD_STOP_INFRA_BSS)
{
/* Transition from eSAP_STARTED to eSAP_DISCONNECTING (both without substates) */
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, from state %s => %s",
__func__, "eSAP_STARTED", "eSAP_DISCONNECTING");
sapContext->sapsMachine = eSAP_DISCONNECTING;
vosStatus = sapGotoDisconnecting(sapContext);
}
else
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR, "In %s, in state %s, invalid event msg %d",
__func__, "eSAP_STARTED", msg);
}
break;
case eSAP_DISCONNECTING:
if (msg == eSAP_MAC_READY_FOR_CONNECTIONS)
{
/* Transition from eSAP_DISCONNECTING to eSAP_DISCONNECTED (both without substates) */
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH, "In %s, from state %s => %s",
__func__, "eSAP_DISCONNECTING", "eSAP_DISCONNECTED");
sapContext->sapsMachine = eSAP_DISCONNECTED;
/* Close the SME session*/
if (eSAP_TRUE == sapContext->isSapSessionOpen)
{
tHalHandle hHal = VOS_GET_HAL_CB(sapContext->pvosGCtx);
if (NULL == hHal)
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"In %s, NULL hHal in state %s, msg %d",
__func__, "eSAP_DISCONNECTING", msg);
}
else
{
sapContext->isSapSessionOpen = eSAP_FALSE;
if (!HAL_STATUS_SUCCESS(
sme_CloseSession(hHal,
sapContext->sessionId,
sapRoamSessionCloseCallback, sapContext)))
{
vosStatus = sapSignalHDDevent(sapContext, NULL,
eSAP_STOP_BSS_EVENT,
(v_PVOID_t) eSAP_STATUS_SUCCESS);
}
}
}
}
if (msg == eSAP_CHANNEL_SELECTION_FAILED)
{
/* Set SAP device role */
sapContext->sapsMachine = eSAP_CH_SELECT;
/* Perform sme_ScanRequest */
vosStatus = sapGotoChannelSel(sapContext, sapEvent);
}
else
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"In %s, in state %s, invalid event msg %d",
__func__, "eSAP_DISCONNECTING", msg);
}
break;
}
return vosStatus;
}// sapFsm
eSapStatus
sapconvertToCsrProfile(tsap_Config_t *pconfig_params, eCsrRoamBssType bssType, tCsrRoamProfile *profile)
{
//Create Roam profile for SoftAP to connect
profile->BSSType = eCSR_BSS_TYPE_INFRA_AP;
profile->SSIDs.numOfSSIDs = 1;
profile->csrPersona = pconfig_params->persona;
vos_mem_zero(profile->SSIDs.SSIDList[0].SSID.ssId,
sizeof(profile->SSIDs.SSIDList[0].SSID.ssId));
//Flag to not broadcast the SSID information
profile->SSIDs.SSIDList[0].ssidHidden = pconfig_params->SSIDinfo.ssidHidden;
profile->SSIDs.SSIDList[0].SSID.length = pconfig_params->SSIDinfo.ssid.length;
vos_mem_copy(&profile->SSIDs.SSIDList[0].SSID.ssId, pconfig_params->SSIDinfo.ssid.ssId,
sizeof(pconfig_params->SSIDinfo.ssid.ssId));
profile->negotiatedAuthType = eCSR_AUTH_TYPE_OPEN_SYSTEM;
if (pconfig_params->authType == eSAP_OPEN_SYSTEM)
{
profile->negotiatedAuthType = eCSR_AUTH_TYPE_OPEN_SYSTEM;
}
else if (pconfig_params->authType == eSAP_SHARED_KEY)
{
profile->negotiatedAuthType = eCSR_AUTH_TYPE_SHARED_KEY;
}
else
{
profile->negotiatedAuthType = eCSR_AUTH_TYPE_AUTOSWITCH;
}
profile->AuthType.numEntries = 1;
profile->AuthType.authType[0] = eCSR_AUTH_TYPE_OPEN_SYSTEM;
//Always set the Encryption Type
profile->EncryptionType.numEntries = 1;
profile->EncryptionType.encryptionType[0] = pconfig_params->RSNEncryptType;
profile->mcEncryptionType.numEntries = 1;
profile->mcEncryptionType.encryptionType[0] = pconfig_params->mcRSNEncryptType;
if (pconfig_params->privacy & eSAP_SHARED_KEY)
{
profile->AuthType.authType[0] = eCSR_AUTH_TYPE_SHARED_KEY;
}
profile->privacy = pconfig_params->privacy;
profile->fwdWPSPBCProbeReq = pconfig_params->fwdWPSPBCProbeReq;
if (pconfig_params->authType == eSAP_SHARED_KEY)
{
profile->csr80211AuthType = eSIR_SHARED_KEY;
}
else if (pconfig_params->authType == eSAP_OPEN_SYSTEM)
{
profile->csr80211AuthType = eSIR_OPEN_SYSTEM;
}
else
{
profile->csr80211AuthType = eSIR_AUTO_SWITCH;
}
//Initialize we are not going to use it
profile->pWPAReqIE = NULL;
profile->nWPAReqIELength = 0;
//set the RSN/WPA IE
profile->pRSNReqIE = NULL;
profile->nRSNReqIELength = pconfig_params->RSNWPAReqIELength;
if (pconfig_params->RSNWPAReqIELength)
{
profile->pRSNReqIE = vos_mem_malloc(pconfig_params->RSNWPAReqIELength);
if( NULL == profile->pRSNReqIE )
{
VOS_TRACE(VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR, " %s Fail to alloc memory", __func__);
return eSAP_STATUS_FAILURE;
}
vos_mem_copy(profile->pRSNReqIE, pconfig_params->pRSNWPAReqIE, pconfig_params->RSNWPAReqIELength);
profile->nRSNReqIELength = pconfig_params->RSNWPAReqIELength;
}
// Turn off CB mode
profile->CBMode = eCSR_CB_OFF;
//set the phyMode to accept anything
//Best means everything because it covers all the things we support
profile->phyMode = pconfig_params->SapHw_mode; /*eCSR_DOT11_MODE_BEST*/
//Configure beaconInterval
profile->beaconInterval = (tANI_U16)pconfig_params->beacon_int;
// set DTIM period
profile->dtimPeriod = pconfig_params->dtim_period;
//set Uapsd enable bit
profile->ApUapsdEnable = pconfig_params->UapsdEnable;
//Enable protection parameters
profile->protEnabled = pconfig_params->protEnabled;
profile->obssProtEnabled = pconfig_params->obssProtEnabled;
profile->cfg_protection = pconfig_params->ht_capab;
//country code
if (pconfig_params->countryCode[0])
vos_mem_copy(profile->countryCode, pconfig_params->countryCode, WNI_CFG_COUNTRY_CODE_LEN);
profile->ieee80211d = pconfig_params->ieee80211d;
//wps config info
profile->wps_state = pconfig_params->wps_state;
#ifdef WLAN_FEATURE_11W
// MFP capable/required
profile->MFPCapable = pconfig_params->mfpCapable ? 1 : 0;
profile->MFPRequired = pconfig_params->mfpRequired ? 1 : 0;
#endif
return eSAP_STATUS_SUCCESS; /* Success. */
}
/**
* FUNCTION: sapConvertSapPhyModeToCsrPhyMode
* Called internally by SAP
*/
eCsrPhyMode sapConvertSapPhyModeToCsrPhyMode( eSapPhyMode sapPhyMode )
{
switch (sapPhyMode)
{
case (eSAP_DOT11_MODE_abg):
return eCSR_DOT11_MODE_abg;
case (eSAP_DOT11_MODE_11b):
return eCSR_DOT11_MODE_11b;
case (eSAP_DOT11_MODE_11g):
return eCSR_DOT11_MODE_11g;
case (eSAP_DOT11_MODE_11n):
return eCSR_DOT11_MODE_11n;
case (eSAP_DOT11_MODE_11g_ONLY):
return eCSR_DOT11_MODE_11g_ONLY;
case (eSAP_DOT11_MODE_11n_ONLY):
return eCSR_DOT11_MODE_11n_ONLY;
case (eSAP_DOT11_MODE_11b_ONLY):
return eCSR_DOT11_MODE_11b_ONLY;
#ifdef WLAN_FEATURE_11AC
case (eSAP_DOT11_MODE_11ac_ONLY):
return eCSR_DOT11_MODE_11ac_ONLY;
case (eSAP_DOT11_MODE_11ac):
return eCSR_DOT11_MODE_11ac;
#endif
case (eSAP_DOT11_MODE_11a):
return eCSR_DOT11_MODE_11a;
default:
return eCSR_DOT11_MODE_AUTO;
}
}
void sapFreeRoamProfile(tCsrRoamProfile *profile)
{
if(profile->pRSNReqIE)
{
vos_mem_free(profile->pRSNReqIE);
profile->pRSNReqIE = NULL;
}
}
void
sapSortMacList(v_MACADDR_t *macList, v_U8_t size)
{
v_U8_t outer, inner;
v_MACADDR_t temp;
v_SINT_t nRes = -1;
if ((NULL == macList) || (size >= MAX_ACL_MAC_ADDRESS))
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"In %s, either buffer is NULL or size = %d is more."
,__func__, size);
return;
}
for(outer = 0; outer < size; outer++)
{
for(inner = 0; inner < size - 1; inner++)
{
nRes = vos_mem_compare2((macList + inner)->bytes, (macList + inner + 1)->bytes, sizeof(v_MACADDR_t));
if (nRes > 0)
{
vos_mem_copy(temp.bytes, (macList + inner + 1)->bytes, sizeof(v_MACADDR_t));
vos_mem_copy((macList + inner + 1)->bytes, (macList + inner)->bytes, sizeof(v_MACADDR_t));
vos_mem_copy((macList + inner)->bytes, temp.bytes, sizeof(v_MACADDR_t));
}
}
}
}
eSapBool
sapSearchMacList(v_MACADDR_t *macList, v_U8_t num_mac, v_U8_t *peerMac, v_U8_t *index)
{
v_SINT_t nRes = -1;
v_S7_t nStart = 0, nEnd, nMiddle;
nEnd = num_mac - 1;
while (nStart <= nEnd)
{
nMiddle = (nStart + nEnd) / 2;
nRes = vos_mem_compare2(&macList[nMiddle], peerMac, sizeof(v_MACADDR_t));
if (0 == nRes)
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"search SUCC");
// "index equals NULL" means the caller does not need the
// index value of the peerMac being searched
if (index != NULL)
{
*index = (v_U8_t) nMiddle;
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"index %d", *index);
}
return eSAP_TRUE;
}
if (nRes < 0)
nStart = nMiddle + 1;
else
nEnd = nMiddle - 1;
}
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"search not succ");
return eSAP_FALSE;
}
void
sapAddMacToACL(v_MACADDR_t *macList, v_U8_t *size, v_U8_t *peerMac)
{
v_SINT_t nRes = -1;
int i;
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,"add acl entered");
if ((NULL == macList) || (*size >= MAX_ACL_MAC_ADDRESS))
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"In %s, either buffer is NULL or size %d is incorrect."
, __func__, *size);
return;
}
for (i=((*size)-1); i>=0; i--)
{
nRes = vos_mem_compare2(&macList[i], peerMac, sizeof(v_MACADDR_t));
if (nRes > 0)
{
/* Move alphabetically greater mac addresses one index down to allow for insertion
of new mac in sorted order */
vos_mem_copy((macList+i+1)->bytes,(macList+i)->bytes, sizeof(v_MACADDR_t));
}
else
{
break;
}
}
//This should also take care of if the element is the first to be added in the list
vos_mem_copy((macList+i+1)->bytes, peerMac, sizeof(v_MACADDR_t));
// increment the list size
(*size)++;
}
void
sapRemoveMacFromACL(v_MACADDR_t *macList, v_U8_t *size, v_U8_t index)
{
int i;
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,"remove acl entered");
/* return if the list passed is empty. Ideally this should never happen since this funcn is always
called after sapSearchMacList to get the index of the mac addr to be removed and this will
only get called if the search is successful. Still no harm in having the check */
if ((macList==NULL) || (*size == 0) || (*size > MAX_ACL_MAC_ADDRESS))
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"In %s, either buffer is NULL or size %d is incorrect."
, __func__, *size);
return;
}
for (i=index; i<((*size)-1); i++)
{
/* Move mac addresses starting from "index" passed one index up to delete the void
created by deletion of a mac address in ACL */
vos_mem_copy((macList+i)->bytes,(macList+i+1)->bytes, sizeof(v_MACADDR_t));
}
// The last space should be made empty since all mac addesses moved one step up
vos_mem_zero((macList+(*size)-1)->bytes, sizeof(v_MACADDR_t));
//reduce the list size by 1
(*size)--;
}
void sapPrintACL(v_MACADDR_t *macList, v_U8_t size)
{
int i;
v_BYTE_t *macArray;
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,"print acl entered");
if ((NULL == macList) || (size == 0) || (size >= MAX_ACL_MAC_ADDRESS))
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"In %s, either buffer is NULL or size %d is incorrect."
, __func__, size);
return;
}
for (i=0; i<size; i++)
{
macArray = (macList+i)->bytes;
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"** ACL entry %i - "MAC_ADDRESS_STR, i,
MAC_ADDR_ARRAY(macArray));
}
return;
}
VOS_STATUS
sapIsPeerMacAllowed(ptSapContext sapContext, v_U8_t *peerMac)
{
if (eSAP_ALLOW_ALL == sapContext->eSapMacAddrAclMode)
return VOS_STATUS_SUCCESS;
if (sapSearchMacList(sapContext->acceptMacList, sapContext->nAcceptMac, peerMac, NULL))
return VOS_STATUS_SUCCESS;
if (sapSearchMacList(sapContext->denyMacList, sapContext->nDenyMac, peerMac, NULL))
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"In %s, Peer "MAC_ADDRESS_STR" in deny list",
__func__, MAC_ADDR_ARRAY(peerMac));
return VOS_STATUS_E_FAILURE;
}
// A new station CAN associate, unless in deny list. Less stringent mode
if (eSAP_ACCEPT_UNLESS_DENIED == sapContext->eSapMacAddrAclMode)
return VOS_STATUS_SUCCESS;
// A new station CANNOT associate, unless in accept list. More stringent mode
if (eSAP_DENY_UNLESS_ACCEPTED == sapContext->eSapMacAddrAclMode)
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"In %s, Peer "MAC_ADDRESS_STR" denied, Mac filter mode is eSAP_DENY_UNLESS_ACCEPTED",
__func__, MAC_ADDR_ARRAY(peerMac));
return VOS_STATUS_E_FAILURE;
}
/* The new STA is neither in accept list nor in deny list. In this case, deny the association
* but send a wifi event notification indicating the mac address being denied
*/
if (eSAP_SUPPORT_ACCEPT_AND_DENY == sapContext->eSapMacAddrAclMode)
{
sapSignalHDDevent(sapContext, NULL, eSAP_UNKNOWN_STA_JOIN, (v_PVOID_t)peerMac);
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO_HIGH,
"In %s, Peer "MAC_ADDRESS_STR" denied, Mac filter mode is eSAP_SUPPORT_ACCEPT_AND_DENY",
__func__, MAC_ADDR_ARRAY(peerMac));
return VOS_STATUS_E_FAILURE;
}
return VOS_STATUS_SUCCESS;
}
#ifdef SOFTAP_CHANNEL_RANGE
static VOS_STATUS sapGetChannelList(ptSapContext sapContext,
v_U8_t **channelList, v_U8_t *numberOfChannels)
{
v_U32_t startChannelNum;
v_U32_t endChannelNum;
v_U32_t operatingBand;
v_U8_t loopCount;
v_U8_t *list;
v_U8_t channelCount;
v_U8_t bandStartChannel;
v_U8_t bandEndChannel ;
v_U32_t enableLTECoex;
tHalHandle hHal = VOS_GET_HAL_CB(sapContext->pvosGCtx);
#ifdef FEATURE_WLAN_CH_AVOID
v_U8_t i;
#endif
if (NULL == hHal)
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"Invalid HAL pointer from pvosGCtx on sapGetChannelList");
*numberOfChannels = 0;
*channelList = NULL;
return VOS_STATUS_E_FAULT;
}
if ( eCSR_BAND_ALL == sapContext->scanBandPreference)
{
ccmCfgGetInt(hHal, WNI_CFG_SAP_CHANNEL_SELECT_START_CHANNEL, &startChannelNum);
ccmCfgGetInt(hHal, WNI_CFG_SAP_CHANNEL_SELECT_END_CHANNEL, &endChannelNum);
ccmCfgGetInt(hHal, WNI_CFG_SAP_CHANNEL_SELECT_OPERATING_BAND, &operatingBand);
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO,
"%s:sapGetChannelList: startChannel %d,EndChannel %d,Operatingband:%d",
__func__,startChannelNum,endChannelNum,operatingBand);
switch(operatingBand)
{
case eSAP_RF_SUBBAND_2_4_GHZ:
bandStartChannel = RF_CHAN_1;
bandEndChannel = RF_CHAN_14;
break;
case eSAP_RF_SUBBAND_5_LOW_GHZ:
bandStartChannel = RF_CHAN_36;
bandEndChannel = RF_CHAN_64;
break;
case eSAP_RF_SUBBAND_5_MID_GHZ:
bandStartChannel = RF_CHAN_100;
bandEndChannel = RF_CHAN_140;
break;
case eSAP_RF_SUBBAND_5_HIGH_GHZ:
bandStartChannel = RF_CHAN_149;
bandEndChannel = RF_CHAN_165;
break;
case eSAP_RF_SUBBAND_5_ALL_GHZ:
bandStartChannel = RF_CHAN_36;
bandEndChannel = RF_CHAN_165;
break;
default:
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"sapGetChannelList:OperatingBand not valid ");
/* assume 2.4 GHz */
bandStartChannel = RF_CHAN_1;
bandEndChannel = RF_CHAN_14;
break;
}
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO,
"%s: expanded startChannel %d,EndChannel %d,Operatingband:%d",
__func__,startChannelNum,endChannelNum,operatingBand);
}
else
{
if ( sapContext->allBandScanned == eSAP_FALSE )
{
//first band scan
sapContext->currentPreferredBand = sapContext->scanBandPreference;
}
else
{
//scan next band
if ( eCSR_BAND_24 == sapContext->scanBandPreference )
sapContext->currentPreferredBand = eCSR_BAND_5G;
else
sapContext->currentPreferredBand = eCSR_BAND_24;
}
switch(sapContext->currentPreferredBand)
{
case eCSR_BAND_24:
bandStartChannel = RF_CHAN_1;
bandEndChannel = RF_CHAN_14;
startChannelNum = 1;
endChannelNum = 14;
break;
case eCSR_BAND_5G:
bandStartChannel = RF_CHAN_36;
bandEndChannel = RF_CHAN_165;
startChannelNum = 36;
endChannelNum = 165;
break;
default:
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"sapGetChannelList:bandPreference not valid ");
/* assume 2.4 GHz */
bandStartChannel = RF_CHAN_1;
bandEndChannel = RF_CHAN_14;
startChannelNum = 1;
endChannelNum = 14;
break;
}
}
ccmCfgGetInt(hHal, WNI_CFG_ENABLE_LTE_COEX, &enableLTECoex);
/*Check if LTE coex is enabled and 2.4GHz is selected*/
if (enableLTECoex && (bandStartChannel == RF_CHAN_1)
&& (bandEndChannel == RF_CHAN_14))
{
/*Set 2.4GHz upper limit to channel 9 for LTE COEX*/
bandEndChannel = RF_CHAN_9;
}
/* Allocate the max number of channel supported */
list = (v_U8_t *)vos_mem_malloc(NUM_5GHZ_CHANNELS);
if (NULL == list)
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"%s: Unable to allocate channel list", __func__);
*numberOfChannels = 0;
*channelList = NULL;
return VOS_STATUS_E_RESOURCES;
}
/*Search for the Active channels in the given range */
channelCount = 0;
for( loopCount = bandStartChannel; loopCount <= bandEndChannel; loopCount++ )
{
if((startChannelNum <= rfChannels[loopCount].channelNum)&&
(endChannelNum >= rfChannels[loopCount].channelNum ))
{
if( regChannels[loopCount].enabled )
{
#ifdef FEATURE_WLAN_CH_AVOID
for( i = 0; i < NUM_20MHZ_RF_CHANNELS; i++ )
{
if( (safeChannels[i].channelNumber ==
rfChannels[loopCount].channelNum) )
{
/* Check if channel is safe */
if(VOS_TRUE == safeChannels[i].isSafe)
{
#endif
list[channelCount] =
rfChannels[loopCount].channelNum;
channelCount++;
#ifdef FEATURE_WLAN_CH_AVOID
}
break;
}
}
#endif
}
}
}
if (0 == channelCount)
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ERROR,
"sapGetChannelList:No active channels present in the given range for the current region");
/*LTE COEX: channel range outside the restricted 2.4GHz band limits*/
if (enableLTECoex && (startChannelNum > bandEndChannel))
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_FATAL,
"sapGetChannelList:SAP cannot be started as LTE COEX restricted 2.4GHz limits");
}
}
/* return the channel list and number of channels to scan*/
*numberOfChannels = channelCount;
if(channelCount != 0)
{
*channelList = list;
}
else
{
*channelList = NULL;
vos_mem_free(list);
}
for (loopCount = 0; loopCount <channelCount; loopCount ++ )
{
VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_DEBUG,
"%s: channel number: %d",
__func__,list[loopCount]);
}
return VOS_STATUS_SUCCESS;
}
#endif
| gpl-2.0 |
pgielda/linux-2.6-olinuxino | drivers/serial/max3100.c | 807 | 21762 | /*
*
* Copyright (C) 2008 Christian Pellegrin <chripell@evolware.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.
*
*
* Notes: the MAX3100 doesn't provide an interrupt on CTS so we have
* to use polling for flow control. TX empty IRQ is unusable, since
* writing conf clears FIFO buffer and we cannot have this interrupt
* always asking us for attention.
*
* Example platform data:
static struct plat_max3100 max3100_plat_data = {
.loopback = 0,
.crystal = 0,
.poll_time = 100,
};
static struct spi_board_info spi_board_info[] = {
{
.modalias = "max3100",
.platform_data = &max3100_plat_data,
.irq = IRQ_EINT12,
.max_speed_hz = 5*1000*1000,
.chip_select = 0,
},
};
* The initial minor number is 209 in the low-density serial port:
* mknod /dev/ttyMAX0 c 204 209
*/
#define MAX3100_MAJOR 204
#define MAX3100_MINOR 209
/* 4 MAX3100s should be enough for everyone */
#define MAX_MAX3100 4
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/serial_core.h>
#include <linux/serial.h>
#include <linux/spi/spi.h>
#include <linux/freezer.h>
#include <linux/serial_max3100.h>
#define MAX3100_C (1<<14)
#define MAX3100_D (0<<14)
#define MAX3100_W (1<<15)
#define MAX3100_RX (0<<15)
#define MAX3100_WC (MAX3100_W | MAX3100_C)
#define MAX3100_RC (MAX3100_RX | MAX3100_C)
#define MAX3100_WD (MAX3100_W | MAX3100_D)
#define MAX3100_RD (MAX3100_RX | MAX3100_D)
#define MAX3100_CMD (3 << 14)
#define MAX3100_T (1<<14)
#define MAX3100_R (1<<15)
#define MAX3100_FEN (1<<13)
#define MAX3100_SHDN (1<<12)
#define MAX3100_TM (1<<11)
#define MAX3100_RM (1<<10)
#define MAX3100_PM (1<<9)
#define MAX3100_RAM (1<<8)
#define MAX3100_IR (1<<7)
#define MAX3100_ST (1<<6)
#define MAX3100_PE (1<<5)
#define MAX3100_L (1<<4)
#define MAX3100_BAUD (0xf)
#define MAX3100_TE (1<<10)
#define MAX3100_RAFE (1<<10)
#define MAX3100_RTS (1<<9)
#define MAX3100_CTS (1<<9)
#define MAX3100_PT (1<<8)
#define MAX3100_DATA (0xff)
#define MAX3100_RT (MAX3100_R | MAX3100_T)
#define MAX3100_RTC (MAX3100_RT | MAX3100_CTS | MAX3100_RAFE)
/* the following simulate a status reg for ignore_status_mask */
#define MAX3100_STATUS_PE 1
#define MAX3100_STATUS_FE 2
#define MAX3100_STATUS_OE 4
struct max3100_port {
struct uart_port port;
struct spi_device *spi;
int cts; /* last CTS received for flow ctrl */
int tx_empty; /* last TX empty bit */
spinlock_t conf_lock; /* shared data */
int conf_commit; /* need to make changes */
int conf; /* configuration for the MAX31000
* (bits 0-7, bits 8-11 are irqs) */
int rts_commit; /* need to change rts */
int rts; /* rts status */
int baud; /* current baud rate */
int parity; /* keeps track if we should send parity */
#define MAX3100_PARITY_ON 1
#define MAX3100_PARITY_ODD 2
#define MAX3100_7BIT 4
int rx_enabled; /* if we should rx chars */
int irq; /* irq assigned to the max3100 */
int minor; /* minor number */
int crystal; /* 1 if 3.6864Mhz crystal 0 for 1.8432 */
int loopback; /* 1 if we are in loopback mode */
/* for handling irqs: need workqueue since we do spi_sync */
struct workqueue_struct *workqueue;
struct work_struct work;
/* set to 1 to make the workhandler exit as soon as possible */
int force_end_work;
/* need to know we are suspending to avoid deadlock on workqueue */
int suspending;
/* hook for suspending MAX3100 via dedicated pin */
void (*max3100_hw_suspend) (int suspend);
/* poll time (in ms) for ctrl lines */
int poll_time;
/* and its timer */
struct timer_list timer;
};
static struct max3100_port *max3100s[MAX_MAX3100]; /* the chips */
static DEFINE_MUTEX(max3100s_lock); /* race on probe */
static int max3100_do_parity(struct max3100_port *s, u16 c)
{
int parity;
if (s->parity & MAX3100_PARITY_ODD)
parity = 1;
else
parity = 0;
if (s->parity & MAX3100_7BIT)
c &= 0x7f;
else
c &= 0xff;
parity = parity ^ (hweight8(c) & 1);
return parity;
}
static int max3100_check_parity(struct max3100_port *s, u16 c)
{
return max3100_do_parity(s, c) == ((c >> 8) & 1);
}
static void max3100_calc_parity(struct max3100_port *s, u16 *c)
{
if (s->parity & MAX3100_7BIT)
*c &= 0x7f;
else
*c &= 0xff;
if (s->parity & MAX3100_PARITY_ON)
*c |= max3100_do_parity(s, *c) << 8;
}
static void max3100_work(struct work_struct *w);
static void max3100_dowork(struct max3100_port *s)
{
if (!s->force_end_work && !work_pending(&s->work) &&
!freezing(current) && !s->suspending)
queue_work(s->workqueue, &s->work);
}
static void max3100_timeout(unsigned long data)
{
struct max3100_port *s = (struct max3100_port *)data;
if (s->port.state) {
max3100_dowork(s);
mod_timer(&s->timer, jiffies + s->poll_time);
}
}
static int max3100_sr(struct max3100_port *s, u16 tx, u16 *rx)
{
struct spi_message message;
u16 etx, erx;
int status;
struct spi_transfer tran = {
.tx_buf = &etx,
.rx_buf = &erx,
.len = 2,
};
etx = cpu_to_be16(tx);
spi_message_init(&message);
spi_message_add_tail(&tran, &message);
status = spi_sync(s->spi, &message);
if (status) {
dev_warn(&s->spi->dev, "error while calling spi_sync\n");
return -EIO;
}
*rx = be16_to_cpu(erx);
s->tx_empty = (*rx & MAX3100_T) > 0;
dev_dbg(&s->spi->dev, "%04x - %04x\n", tx, *rx);
return 0;
}
static int max3100_handlerx(struct max3100_port *s, u16 rx)
{
unsigned int ch, flg, status = 0;
int ret = 0, cts;
if (rx & MAX3100_R && s->rx_enabled) {
dev_dbg(&s->spi->dev, "%s\n", __func__);
ch = rx & (s->parity & MAX3100_7BIT ? 0x7f : 0xff);
if (rx & MAX3100_RAFE) {
s->port.icount.frame++;
flg = TTY_FRAME;
status |= MAX3100_STATUS_FE;
} else {
if (s->parity & MAX3100_PARITY_ON) {
if (max3100_check_parity(s, rx)) {
s->port.icount.rx++;
flg = TTY_NORMAL;
} else {
s->port.icount.parity++;
flg = TTY_PARITY;
status |= MAX3100_STATUS_PE;
}
} else {
s->port.icount.rx++;
flg = TTY_NORMAL;
}
}
uart_insert_char(&s->port, status, MAX3100_STATUS_OE, ch, flg);
ret = 1;
}
cts = (rx & MAX3100_CTS) > 0;
if (s->cts != cts) {
s->cts = cts;
uart_handle_cts_change(&s->port, cts ? TIOCM_CTS : 0);
}
return ret;
}
static void max3100_work(struct work_struct *w)
{
struct max3100_port *s = container_of(w, struct max3100_port, work);
int rxchars;
u16 tx, rx;
int conf, cconf, rts, crts;
struct circ_buf *xmit = &s->port.state->xmit;
dev_dbg(&s->spi->dev, "%s\n", __func__);
rxchars = 0;
do {
spin_lock(&s->conf_lock);
conf = s->conf;
cconf = s->conf_commit;
s->conf_commit = 0;
rts = s->rts;
crts = s->rts_commit;
s->rts_commit = 0;
spin_unlock(&s->conf_lock);
if (cconf)
max3100_sr(s, MAX3100_WC | conf, &rx);
if (crts) {
max3100_sr(s, MAX3100_WD | MAX3100_TE |
(s->rts ? MAX3100_RTS : 0), &rx);
rxchars += max3100_handlerx(s, rx);
}
max3100_sr(s, MAX3100_RD, &rx);
rxchars += max3100_handlerx(s, rx);
if (rx & MAX3100_T) {
tx = 0xffff;
if (s->port.x_char) {
tx = s->port.x_char;
s->port.icount.tx++;
s->port.x_char = 0;
} else if (!uart_circ_empty(xmit) &&
!uart_tx_stopped(&s->port)) {
tx = xmit->buf[xmit->tail];
xmit->tail = (xmit->tail + 1) &
(UART_XMIT_SIZE - 1);
s->port.icount.tx++;
}
if (tx != 0xffff) {
max3100_calc_parity(s, &tx);
tx |= MAX3100_WD | (s->rts ? MAX3100_RTS : 0);
max3100_sr(s, tx, &rx);
rxchars += max3100_handlerx(s, rx);
}
}
if (rxchars > 16 && s->port.state->port.tty != NULL) {
tty_flip_buffer_push(s->port.state->port.tty);
rxchars = 0;
}
if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
uart_write_wakeup(&s->port);
} while (!s->force_end_work &&
!freezing(current) &&
((rx & MAX3100_R) ||
(!uart_circ_empty(xmit) &&
!uart_tx_stopped(&s->port))));
if (rxchars > 0 && s->port.state->port.tty != NULL)
tty_flip_buffer_push(s->port.state->port.tty);
}
static irqreturn_t max3100_irq(int irqno, void *dev_id)
{
struct max3100_port *s = dev_id;
dev_dbg(&s->spi->dev, "%s\n", __func__);
max3100_dowork(s);
return IRQ_HANDLED;
}
static void max3100_enable_ms(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
if (s->poll_time > 0)
mod_timer(&s->timer, jiffies);
dev_dbg(&s->spi->dev, "%s\n", __func__);
}
static void max3100_start_tx(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
max3100_dowork(s);
}
static void max3100_stop_rx(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
s->rx_enabled = 0;
spin_lock(&s->conf_lock);
s->conf &= ~MAX3100_RM;
s->conf_commit = 1;
spin_unlock(&s->conf_lock);
max3100_dowork(s);
}
static unsigned int max3100_tx_empty(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
/* may not be truly up-to-date */
max3100_dowork(s);
return s->tx_empty;
}
static unsigned int max3100_get_mctrl(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
/* may not be truly up-to-date */
max3100_dowork(s);
/* always assert DCD and DSR since these lines are not wired */
return (s->cts ? TIOCM_CTS : 0) | TIOCM_DSR | TIOCM_CAR;
}
static void max3100_set_mctrl(struct uart_port *port, unsigned int mctrl)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
int rts;
dev_dbg(&s->spi->dev, "%s\n", __func__);
rts = (mctrl & TIOCM_RTS) > 0;
spin_lock(&s->conf_lock);
if (s->rts != rts) {
s->rts = rts;
s->rts_commit = 1;
max3100_dowork(s);
}
spin_unlock(&s->conf_lock);
}
static void
max3100_set_termios(struct uart_port *port, struct ktermios *termios,
struct ktermios *old)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
int baud = 0;
unsigned cflag;
u32 param_new, param_mask, parity = 0;
struct tty_struct *tty = s->port.state->port.tty;
dev_dbg(&s->spi->dev, "%s\n", __func__);
if (!tty)
return;
cflag = termios->c_cflag;
param_new = 0;
param_mask = 0;
baud = tty_get_baud_rate(tty);
param_new = s->conf & MAX3100_BAUD;
switch (baud) {
case 300:
if (s->crystal)
baud = s->baud;
else
param_new = 15;
break;
case 600:
param_new = 14 + s->crystal;
break;
case 1200:
param_new = 13 + s->crystal;
break;
case 2400:
param_new = 12 + s->crystal;
break;
case 4800:
param_new = 11 + s->crystal;
break;
case 9600:
param_new = 10 + s->crystal;
break;
case 19200:
param_new = 9 + s->crystal;
break;
case 38400:
param_new = 8 + s->crystal;
break;
case 57600:
param_new = 1 + s->crystal;
break;
case 115200:
param_new = 0 + s->crystal;
break;
case 230400:
if (s->crystal)
param_new = 0;
else
baud = s->baud;
break;
default:
baud = s->baud;
}
tty_encode_baud_rate(tty, baud, baud);
s->baud = baud;
param_mask |= MAX3100_BAUD;
if ((cflag & CSIZE) == CS8) {
param_new &= ~MAX3100_L;
parity &= ~MAX3100_7BIT;
} else {
param_new |= MAX3100_L;
parity |= MAX3100_7BIT;
cflag = (cflag & ~CSIZE) | CS7;
}
param_mask |= MAX3100_L;
if (cflag & CSTOPB)
param_new |= MAX3100_ST;
else
param_new &= ~MAX3100_ST;
param_mask |= MAX3100_ST;
if (cflag & PARENB) {
param_new |= MAX3100_PE;
parity |= MAX3100_PARITY_ON;
} else {
param_new &= ~MAX3100_PE;
parity &= ~MAX3100_PARITY_ON;
}
param_mask |= MAX3100_PE;
if (cflag & PARODD)
parity |= MAX3100_PARITY_ODD;
else
parity &= ~MAX3100_PARITY_ODD;
/* mask termios capabilities we don't support */
cflag &= ~CMSPAR;
termios->c_cflag = cflag;
s->port.ignore_status_mask = 0;
if (termios->c_iflag & IGNPAR)
s->port.ignore_status_mask |=
MAX3100_STATUS_PE | MAX3100_STATUS_FE |
MAX3100_STATUS_OE;
/* we are sending char from a workqueue so enable */
s->port.state->port.tty->low_latency = 1;
if (s->poll_time > 0)
del_timer_sync(&s->timer);
uart_update_timeout(port, termios->c_cflag, baud);
spin_lock(&s->conf_lock);
s->conf = (s->conf & ~param_mask) | (param_new & param_mask);
s->conf_commit = 1;
s->parity = parity;
spin_unlock(&s->conf_lock);
max3100_dowork(s);
if (UART_ENABLE_MS(&s->port, termios->c_cflag))
max3100_enable_ms(&s->port);
}
static void max3100_shutdown(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
if (s->suspending)
return;
s->force_end_work = 1;
if (s->poll_time > 0)
del_timer_sync(&s->timer);
if (s->workqueue) {
flush_workqueue(s->workqueue);
destroy_workqueue(s->workqueue);
s->workqueue = NULL;
}
if (s->irq)
free_irq(s->irq, s);
/* set shutdown mode to save power */
if (s->max3100_hw_suspend)
s->max3100_hw_suspend(1);
else {
u16 tx, rx;
tx = MAX3100_WC | MAX3100_SHDN;
max3100_sr(s, tx, &rx);
}
}
static int max3100_startup(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
char b[12];
dev_dbg(&s->spi->dev, "%s\n", __func__);
s->conf = MAX3100_RM;
s->baud = s->crystal ? 230400 : 115200;
s->rx_enabled = 1;
if (s->suspending)
return 0;
s->force_end_work = 0;
s->parity = 0;
s->rts = 0;
sprintf(b, "max3100-%d", s->minor);
s->workqueue = create_freezeable_workqueue(b);
if (!s->workqueue) {
dev_warn(&s->spi->dev, "cannot create workqueue\n");
return -EBUSY;
}
INIT_WORK(&s->work, max3100_work);
if (request_irq(s->irq, max3100_irq,
IRQF_TRIGGER_FALLING, "max3100", s) < 0) {
dev_warn(&s->spi->dev, "cannot allocate irq %d\n", s->irq);
s->irq = 0;
destroy_workqueue(s->workqueue);
s->workqueue = NULL;
return -EBUSY;
}
if (s->loopback) {
u16 tx, rx;
tx = 0x4001;
max3100_sr(s, tx, &rx);
}
if (s->max3100_hw_suspend)
s->max3100_hw_suspend(0);
s->conf_commit = 1;
max3100_dowork(s);
/* wait for clock to settle */
msleep(50);
max3100_enable_ms(&s->port);
return 0;
}
static const char *max3100_type(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
return s->port.type == PORT_MAX3100 ? "MAX3100" : NULL;
}
static void max3100_release_port(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
}
static void max3100_config_port(struct uart_port *port, int flags)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
if (flags & UART_CONFIG_TYPE)
s->port.type = PORT_MAX3100;
}
static int max3100_verify_port(struct uart_port *port,
struct serial_struct *ser)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
int ret = -EINVAL;
dev_dbg(&s->spi->dev, "%s\n", __func__);
if (ser->type == PORT_UNKNOWN || ser->type == PORT_MAX3100)
ret = 0;
return ret;
}
static void max3100_stop_tx(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
}
static int max3100_request_port(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
return 0;
}
static void max3100_break_ctl(struct uart_port *port, int break_state)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
}
static struct uart_ops max3100_ops = {
.tx_empty = max3100_tx_empty,
.set_mctrl = max3100_set_mctrl,
.get_mctrl = max3100_get_mctrl,
.stop_tx = max3100_stop_tx,
.start_tx = max3100_start_tx,
.stop_rx = max3100_stop_rx,
.enable_ms = max3100_enable_ms,
.break_ctl = max3100_break_ctl,
.startup = max3100_startup,
.shutdown = max3100_shutdown,
.set_termios = max3100_set_termios,
.type = max3100_type,
.release_port = max3100_release_port,
.request_port = max3100_request_port,
.config_port = max3100_config_port,
.verify_port = max3100_verify_port,
};
static struct uart_driver max3100_uart_driver = {
.owner = THIS_MODULE,
.driver_name = "ttyMAX",
.dev_name = "ttyMAX",
.major = MAX3100_MAJOR,
.minor = MAX3100_MINOR,
.nr = MAX_MAX3100,
};
static int uart_driver_registered;
static int __devinit max3100_probe(struct spi_device *spi)
{
int i, retval;
struct plat_max3100 *pdata;
u16 tx, rx;
mutex_lock(&max3100s_lock);
if (!uart_driver_registered) {
uart_driver_registered = 1;
retval = uart_register_driver(&max3100_uart_driver);
if (retval) {
printk(KERN_ERR "Couldn't register max3100 uart driver\n");
mutex_unlock(&max3100s_lock);
return retval;
}
}
for (i = 0; i < MAX_MAX3100; i++)
if (!max3100s[i])
break;
if (i == MAX_MAX3100) {
dev_warn(&spi->dev, "too many MAX3100 chips\n");
mutex_unlock(&max3100s_lock);
return -ENOMEM;
}
max3100s[i] = kzalloc(sizeof(struct max3100_port), GFP_KERNEL);
if (!max3100s[i]) {
dev_warn(&spi->dev,
"kmalloc for max3100 structure %d failed!\n", i);
mutex_unlock(&max3100s_lock);
return -ENOMEM;
}
max3100s[i]->spi = spi;
max3100s[i]->irq = spi->irq;
spin_lock_init(&max3100s[i]->conf_lock);
dev_set_drvdata(&spi->dev, max3100s[i]);
pdata = spi->dev.platform_data;
max3100s[i]->crystal = pdata->crystal;
max3100s[i]->loopback = pdata->loopback;
max3100s[i]->poll_time = pdata->poll_time * HZ / 1000;
if (pdata->poll_time > 0 && max3100s[i]->poll_time == 0)
max3100s[i]->poll_time = 1;
max3100s[i]->max3100_hw_suspend = pdata->max3100_hw_suspend;
max3100s[i]->minor = i;
init_timer(&max3100s[i]->timer);
max3100s[i]->timer.function = max3100_timeout;
max3100s[i]->timer.data = (unsigned long) max3100s[i];
dev_dbg(&spi->dev, "%s: adding port %d\n", __func__, i);
max3100s[i]->port.irq = max3100s[i]->irq;
max3100s[i]->port.uartclk = max3100s[i]->crystal ? 3686400 : 1843200;
max3100s[i]->port.fifosize = 16;
max3100s[i]->port.ops = &max3100_ops;
max3100s[i]->port.flags = UPF_SKIP_TEST | UPF_BOOT_AUTOCONF;
max3100s[i]->port.line = i;
max3100s[i]->port.type = PORT_MAX3100;
max3100s[i]->port.dev = &spi->dev;
retval = uart_add_one_port(&max3100_uart_driver, &max3100s[i]->port);
if (retval < 0)
dev_warn(&spi->dev,
"uart_add_one_port failed for line %d with error %d\n",
i, retval);
/* set shutdown mode to save power. Will be woken-up on open */
if (max3100s[i]->max3100_hw_suspend)
max3100s[i]->max3100_hw_suspend(1);
else {
tx = MAX3100_WC | MAX3100_SHDN;
max3100_sr(max3100s[i], tx, &rx);
}
mutex_unlock(&max3100s_lock);
return 0;
}
static int __devexit max3100_remove(struct spi_device *spi)
{
struct max3100_port *s = dev_get_drvdata(&spi->dev);
int i;
mutex_lock(&max3100s_lock);
/* find out the index for the chip we are removing */
for (i = 0; i < MAX_MAX3100; i++)
if (max3100s[i] == s)
break;
dev_dbg(&spi->dev, "%s: removing port %d\n", __func__, i);
uart_remove_one_port(&max3100_uart_driver, &max3100s[i]->port);
kfree(max3100s[i]);
max3100s[i] = NULL;
/* check if this is the last chip we have */
for (i = 0; i < MAX_MAX3100; i++)
if (max3100s[i]) {
mutex_unlock(&max3100s_lock);
return 0;
}
pr_debug("removing max3100 driver\n");
uart_unregister_driver(&max3100_uart_driver);
mutex_unlock(&max3100s_lock);
return 0;
}
#ifdef CONFIG_PM
static int max3100_suspend(struct spi_device *spi, pm_message_t state)
{
struct max3100_port *s = dev_get_drvdata(&spi->dev);
dev_dbg(&s->spi->dev, "%s\n", __func__);
disable_irq(s->irq);
s->suspending = 1;
uart_suspend_port(&max3100_uart_driver, &s->port);
if (s->max3100_hw_suspend)
s->max3100_hw_suspend(1);
else {
/* no HW suspend, so do SW one */
u16 tx, rx;
tx = MAX3100_WC | MAX3100_SHDN;
max3100_sr(s, tx, &rx);
}
return 0;
}
static int max3100_resume(struct spi_device *spi)
{
struct max3100_port *s = dev_get_drvdata(&spi->dev);
dev_dbg(&s->spi->dev, "%s\n", __func__);
if (s->max3100_hw_suspend)
s->max3100_hw_suspend(0);
uart_resume_port(&max3100_uart_driver, &s->port);
s->suspending = 0;
enable_irq(s->irq);
s->conf_commit = 1;
if (s->workqueue)
max3100_dowork(s);
return 0;
}
#else
#define max3100_suspend NULL
#define max3100_resume NULL
#endif
static struct spi_driver max3100_driver = {
.driver = {
.name = "max3100",
.bus = &spi_bus_type,
.owner = THIS_MODULE,
},
.probe = max3100_probe,
.remove = __devexit_p(max3100_remove),
.suspend = max3100_suspend,
.resume = max3100_resume,
};
static int __init max3100_init(void)
{
return spi_register_driver(&max3100_driver);
}
module_init(max3100_init);
static void __exit max3100_exit(void)
{
spi_unregister_driver(&max3100_driver);
}
module_exit(max3100_exit);
MODULE_DESCRIPTION("MAX3100 driver");
MODULE_AUTHOR("Christian Pellegrin <chripell@evolware.org>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("spi:max3100");
| gpl-2.0 |
satyamrockstar2013/linux | drivers/regulator/arizona-micsupp.c | 1063 | 8129 | /*
* arizona-micsupp.c -- Microphone supply for Arizona devices
*
* Copyright 2012 Wolfson Microelectronics PLC.
*
* Author: Mark Brown <broonie@opensource.wolfsonmicro.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License 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/moduleparam.h>
#include <linux/init.h>
#include <linux/bitops.h>
#include <linux/err.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/regulator/driver.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/of_regulator.h>
#include <linux/gpio.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <sound/soc.h>
#include <linux/mfd/arizona/core.h>
#include <linux/mfd/arizona/pdata.h>
#include <linux/mfd/arizona/registers.h>
struct arizona_micsupp {
struct regulator_dev *regulator;
struct arizona *arizona;
struct regulator_consumer_supply supply;
struct regulator_init_data init_data;
struct work_struct check_cp_work;
};
static void arizona_micsupp_check_cp(struct work_struct *work)
{
struct arizona_micsupp *micsupp =
container_of(work, struct arizona_micsupp, check_cp_work);
struct snd_soc_dapm_context *dapm = micsupp->arizona->dapm;
struct arizona *arizona = micsupp->arizona;
struct regmap *regmap = arizona->regmap;
unsigned int reg;
int ret;
ret = regmap_read(regmap, ARIZONA_MIC_CHARGE_PUMP_1, ®);
if (ret != 0) {
dev_err(arizona->dev, "Failed to read CP state: %d\n", ret);
return;
}
if (dapm) {
if ((reg & (ARIZONA_CPMIC_ENA | ARIZONA_CPMIC_BYPASS)) ==
ARIZONA_CPMIC_ENA)
snd_soc_dapm_force_enable_pin(dapm, "MICSUPP");
else
snd_soc_dapm_disable_pin(dapm, "MICSUPP");
snd_soc_dapm_sync(dapm);
}
}
static int arizona_micsupp_enable(struct regulator_dev *rdev)
{
struct arizona_micsupp *micsupp = rdev_get_drvdata(rdev);
int ret;
ret = regulator_enable_regmap(rdev);
if (ret == 0)
schedule_work(&micsupp->check_cp_work);
return ret;
}
static int arizona_micsupp_disable(struct regulator_dev *rdev)
{
struct arizona_micsupp *micsupp = rdev_get_drvdata(rdev);
int ret;
ret = regulator_disable_regmap(rdev);
if (ret == 0)
schedule_work(&micsupp->check_cp_work);
return ret;
}
static int arizona_micsupp_set_bypass(struct regulator_dev *rdev, bool ena)
{
struct arizona_micsupp *micsupp = rdev_get_drvdata(rdev);
int ret;
ret = regulator_set_bypass_regmap(rdev, ena);
if (ret == 0)
schedule_work(&micsupp->check_cp_work);
return ret;
}
static struct regulator_ops arizona_micsupp_ops = {
.enable = arizona_micsupp_enable,
.disable = arizona_micsupp_disable,
.is_enabled = regulator_is_enabled_regmap,
.list_voltage = regulator_list_voltage_linear_range,
.map_voltage = regulator_map_voltage_linear_range,
.get_voltage_sel = regulator_get_voltage_sel_regmap,
.set_voltage_sel = regulator_set_voltage_sel_regmap,
.get_bypass = regulator_get_bypass_regmap,
.set_bypass = arizona_micsupp_set_bypass,
};
static const struct regulator_linear_range arizona_micsupp_ranges[] = {
REGULATOR_LINEAR_RANGE(1700000, 0, 0x1e, 50000),
REGULATOR_LINEAR_RANGE(3300000, 0x1f, 0x1f, 0),
};
static const struct regulator_desc arizona_micsupp = {
.name = "MICVDD",
.supply_name = "CPVDD",
.type = REGULATOR_VOLTAGE,
.n_voltages = 32,
.ops = &arizona_micsupp_ops,
.vsel_reg = ARIZONA_LDO2_CONTROL_1,
.vsel_mask = ARIZONA_LDO2_VSEL_MASK,
.enable_reg = ARIZONA_MIC_CHARGE_PUMP_1,
.enable_mask = ARIZONA_CPMIC_ENA,
.bypass_reg = ARIZONA_MIC_CHARGE_PUMP_1,
.bypass_mask = ARIZONA_CPMIC_BYPASS,
.linear_ranges = arizona_micsupp_ranges,
.n_linear_ranges = ARRAY_SIZE(arizona_micsupp_ranges),
.enable_time = 3000,
.owner = THIS_MODULE,
};
static const struct regulator_linear_range arizona_micsupp_ext_ranges[] = {
REGULATOR_LINEAR_RANGE(900000, 0, 0x14, 25000),
REGULATOR_LINEAR_RANGE(1500000, 0x15, 0x27, 100000),
};
static const struct regulator_desc arizona_micsupp_ext = {
.name = "MICVDD",
.supply_name = "CPVDD",
.type = REGULATOR_VOLTAGE,
.n_voltages = 40,
.ops = &arizona_micsupp_ops,
.vsel_reg = ARIZONA_LDO2_CONTROL_1,
.vsel_mask = ARIZONA_LDO2_VSEL_MASK,
.enable_reg = ARIZONA_MIC_CHARGE_PUMP_1,
.enable_mask = ARIZONA_CPMIC_ENA,
.bypass_reg = ARIZONA_MIC_CHARGE_PUMP_1,
.bypass_mask = ARIZONA_CPMIC_BYPASS,
.linear_ranges = arizona_micsupp_ext_ranges,
.n_linear_ranges = ARRAY_SIZE(arizona_micsupp_ext_ranges),
.enable_time = 3000,
.owner = THIS_MODULE,
};
static const struct regulator_init_data arizona_micsupp_default = {
.constraints = {
.valid_ops_mask = REGULATOR_CHANGE_STATUS |
REGULATOR_CHANGE_VOLTAGE |
REGULATOR_CHANGE_BYPASS,
.min_uV = 1700000,
.max_uV = 3300000,
},
.num_consumer_supplies = 1,
};
static const struct regulator_init_data arizona_micsupp_ext_default = {
.constraints = {
.valid_ops_mask = REGULATOR_CHANGE_STATUS |
REGULATOR_CHANGE_VOLTAGE |
REGULATOR_CHANGE_BYPASS,
.min_uV = 900000,
.max_uV = 3300000,
},
.num_consumer_supplies = 1,
};
static int arizona_micsupp_of_get_pdata(struct arizona *arizona,
struct regulator_config *config,
const struct regulator_desc *desc)
{
struct arizona_pdata *pdata = &arizona->pdata;
struct arizona_micsupp *micsupp = config->driver_data;
struct device_node *np;
struct regulator_init_data *init_data;
np = of_get_child_by_name(arizona->dev->of_node, "micvdd");
if (np) {
config->of_node = np;
init_data = of_get_regulator_init_data(arizona->dev, np, desc);
if (init_data) {
init_data->consumer_supplies = &micsupp->supply;
init_data->num_consumer_supplies = 1;
pdata->micvdd = init_data;
}
}
return 0;
}
static int arizona_micsupp_probe(struct platform_device *pdev)
{
struct arizona *arizona = dev_get_drvdata(pdev->dev.parent);
const struct regulator_desc *desc;
struct regulator_config config = { };
struct arizona_micsupp *micsupp;
int ret;
micsupp = devm_kzalloc(&pdev->dev, sizeof(*micsupp), GFP_KERNEL);
if (!micsupp)
return -ENOMEM;
micsupp->arizona = arizona;
INIT_WORK(&micsupp->check_cp_work, arizona_micsupp_check_cp);
/*
* Since the chip usually supplies itself we provide some
* default init_data for it. This will be overridden with
* platform data if provided.
*/
switch (arizona->type) {
case WM5110:
case WM8280:
desc = &arizona_micsupp_ext;
micsupp->init_data = arizona_micsupp_ext_default;
break;
default:
desc = &arizona_micsupp;
micsupp->init_data = arizona_micsupp_default;
break;
}
micsupp->init_data.consumer_supplies = &micsupp->supply;
micsupp->supply.supply = "MICVDD";
micsupp->supply.dev_name = dev_name(arizona->dev);
config.dev = arizona->dev;
config.driver_data = micsupp;
config.regmap = arizona->regmap;
if (IS_ENABLED(CONFIG_OF)) {
if (!dev_get_platdata(arizona->dev)) {
ret = arizona_micsupp_of_get_pdata(arizona, &config,
desc);
if (ret < 0)
return ret;
}
}
if (arizona->pdata.micvdd)
config.init_data = arizona->pdata.micvdd;
else
config.init_data = &micsupp->init_data;
/* Default to regulated mode until the API supports bypass */
regmap_update_bits(arizona->regmap, ARIZONA_MIC_CHARGE_PUMP_1,
ARIZONA_CPMIC_BYPASS, 0);
micsupp->regulator = devm_regulator_register(&pdev->dev,
desc,
&config);
of_node_put(config.of_node);
if (IS_ERR(micsupp->regulator)) {
ret = PTR_ERR(micsupp->regulator);
dev_err(arizona->dev, "Failed to register mic supply: %d\n",
ret);
return ret;
}
platform_set_drvdata(pdev, micsupp);
return 0;
}
static struct platform_driver arizona_micsupp_driver = {
.probe = arizona_micsupp_probe,
.driver = {
.name = "arizona-micsupp",
},
};
module_platform_driver(arizona_micsupp_driver);
/* Module information */
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");
MODULE_DESCRIPTION("Arizona microphone supply driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:arizona-micsupp");
| gpl-2.0 |
revjunkie/kernel | drivers/media/usb/dvb-usb-v2/it913x.c | 2087 | 20888 | /*
* DVB USB compliant linux driver for ITE IT9135 and IT9137
*
* Copyright (C) 2011 Malcolm Priestley (tvboxspy@gmail.com)
* IT9135 (C) ITE Tech Inc.
* IT9137 (C) ITE Tech Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License Version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*
* see Documentation/dvb/README.dvb-usb for more information
* see Documentation/dvb/it9137.txt for firmware information
*
*/
#define DVB_USB_LOG_PREFIX "it913x"
#include <linux/usb.h>
#include <linux/usb/input.h>
#include <media/rc-core.h>
#include "dvb_usb.h"
#include "it913x-fe.h"
/* debug */
static int dvb_usb_it913x_debug;
#define it_debug(var, level, args...) \
do { if ((var & level)) pr_debug(DVB_USB_LOG_PREFIX": " args); \
} while (0)
#define deb_info(level, args...) it_debug(dvb_usb_it913x_debug, level, args)
#define info(args...) pr_info(DVB_USB_LOG_PREFIX": " args)
module_param_named(debug, dvb_usb_it913x_debug, int, 0644);
MODULE_PARM_DESC(debug, "set debugging level (1=info (or-able)).");
static int dvb_usb_it913x_firmware;
module_param_named(firmware, dvb_usb_it913x_firmware, int, 0644);
MODULE_PARM_DESC(firmware, "set firmware 0=auto"\
"1=IT9137 2=IT9135 V1 3=IT9135 V2");
#define FW_IT9137 "dvb-usb-it9137-01.fw"
#define FW_IT9135_V1 "dvb-usb-it9135-01.fw"
#define FW_IT9135_V2 "dvb-usb-it9135-02.fw"
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
struct it913x_state {
struct ite_config it913x_config;
u8 pid_filter_onoff;
bool proprietary_ir;
int cmd_counter;
};
static u16 check_sum(u8 *p, u8 len)
{
u16 sum = 0;
u8 i = 1;
while (i < len)
sum += (i++ & 1) ? (*p++) << 8 : *p++;
return ~sum;
}
static int it913x_io(struct dvb_usb_device *d, u8 mode, u8 pro,
u8 cmd, u32 reg, u8 addr, u8 *data, u8 len)
{
struct it913x_state *st = d->priv;
int ret = 0, i, buf_size = 1;
u8 *buff;
u8 rlen;
u16 chk_sum;
buff = kzalloc(256, GFP_KERNEL);
if (!buff) {
info("USB Buffer Failed");
return -ENOMEM;
}
buff[buf_size++] = pro;
buff[buf_size++] = cmd;
buff[buf_size++] = st->cmd_counter;
switch (mode) {
case READ_LONG:
case WRITE_LONG:
buff[buf_size++] = len;
buff[buf_size++] = 2;
buff[buf_size++] = (reg >> 24);
buff[buf_size++] = (reg >> 16) & 0xff;
buff[buf_size++] = (reg >> 8) & 0xff;
buff[buf_size++] = reg & 0xff;
break;
case READ_SHORT:
buff[buf_size++] = addr;
break;
case WRITE_SHORT:
buff[buf_size++] = len;
buff[buf_size++] = addr;
buff[buf_size++] = (reg >> 8) & 0xff;
buff[buf_size++] = reg & 0xff;
break;
case READ_DATA:
case WRITE_DATA:
break;
case WRITE_CMD:
mode = 7;
break;
default:
kfree(buff);
return -EINVAL;
}
if (mode & 1) {
for (i = 0; i < len ; i++)
buff[buf_size++] = data[i];
}
chk_sum = check_sum(&buff[1], buf_size);
buff[buf_size++] = chk_sum >> 8;
buff[0] = buf_size;
buff[buf_size++] = (chk_sum & 0xff);
ret = dvb_usbv2_generic_rw(d, buff, buf_size, buff, (mode & 1) ?
5 : len + 5);
if (ret < 0)
goto error;
rlen = (mode & 0x1) ? 0x1 : len;
if (mode & 1)
ret = buff[2];
else
memcpy(data, &buff[3], rlen);
st->cmd_counter++;
error: kfree(buff);
return ret;
}
static int it913x_wr_reg(struct dvb_usb_device *d, u8 pro, u32 reg , u8 data)
{
int ret;
u8 b[1];
b[0] = data;
ret = it913x_io(d, WRITE_LONG, pro,
CMD_DEMOD_WRITE, reg, 0, b, sizeof(b));
return ret;
}
static int it913x_read_reg(struct dvb_usb_device *d, u32 reg)
{
int ret;
u8 data[1];
ret = it913x_io(d, READ_LONG, DEV_0,
CMD_DEMOD_READ, reg, 0, &data[0], sizeof(data));
return (ret < 0) ? ret : data[0];
}
static int it913x_query(struct dvb_usb_device *d, u8 pro)
{
struct it913x_state *st = d->priv;
int ret, i;
u8 data[4];
u8 ver;
for (i = 0; i < 5; i++) {
ret = it913x_io(d, READ_LONG, pro, CMD_DEMOD_READ,
0x1222, 0, &data[0], 3);
ver = data[0];
if (ver > 0 && ver < 3)
break;
msleep(100);
}
if (ver < 1 || ver > 2) {
info("Failed to identify chip version applying 1");
st->it913x_config.chip_ver = 0x1;
st->it913x_config.chip_type = 0x9135;
return 0;
}
st->it913x_config.chip_ver = ver;
st->it913x_config.chip_type = (u16)(data[2] << 8) + data[1];
info("Chip Version=%02x Chip Type=%04x", st->it913x_config.chip_ver,
st->it913x_config.chip_type);
ret = it913x_io(d, READ_SHORT, pro,
CMD_QUERYINFO, 0, 0x1, &data[0], 4);
st->it913x_config.firmware = (data[0] << 24) | (data[1] << 16) |
(data[2] << 8) | data[3];
return ret;
}
static int it913x_pid_filter_ctrl(struct dvb_usb_adapter *adap, int onoff)
{
struct dvb_usb_device *d = adap_to_d(adap);
struct it913x_state *st = adap_to_priv(adap);
int ret;
u8 pro = (adap->id == 0) ? DEV_0_DMOD : DEV_1_DMOD;
mutex_lock(&d->i2c_mutex);
deb_info(1, "PID_C (%02x)", onoff);
st->pid_filter_onoff = adap->pid_filtering;
ret = it913x_wr_reg(d, pro, PID_EN, st->pid_filter_onoff);
mutex_unlock(&d->i2c_mutex);
return ret;
}
static int it913x_pid_filter(struct dvb_usb_adapter *adap,
int index, u16 pid, int onoff)
{
struct dvb_usb_device *d = adap_to_d(adap);
struct it913x_state *st = adap_to_priv(adap);
int ret;
u8 pro = (adap->id == 0) ? DEV_0_DMOD : DEV_1_DMOD;
mutex_lock(&d->i2c_mutex);
deb_info(1, "PID_F (%02x)", onoff);
ret = it913x_wr_reg(d, pro, PID_LSB, (u8)(pid & 0xff));
ret |= it913x_wr_reg(d, pro, PID_MSB, (u8)(pid >> 8));
ret |= it913x_wr_reg(d, pro, PID_INX_EN, (u8)onoff);
ret |= it913x_wr_reg(d, pro, PID_INX, (u8)(index & 0x1f));
if (d->udev->speed == USB_SPEED_HIGH && pid == 0x2000) {
ret |= it913x_wr_reg(d , pro, PID_EN, !onoff);
st->pid_filter_onoff = !onoff;
} else
st->pid_filter_onoff =
adap->pid_filtering;
mutex_unlock(&d->i2c_mutex);
return 0;
}
static int it913x_return_status(struct dvb_usb_device *d)
{
struct it913x_state *st = d->priv;
int ret = it913x_query(d, DEV_0);
if (st->it913x_config.firmware > 0)
info("Firmware Version %d", st->it913x_config.firmware);
return ret;
}
static int it913x_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msg[],
int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adap);
static u8 data[256];
int ret;
u32 reg;
u8 pro;
mutex_lock(&d->i2c_mutex);
deb_info(2, "num of messages %d address %02x", num, msg[0].addr);
pro = (msg[0].addr & 0x2) ? DEV_0_DMOD : 0x0;
pro |= (msg[0].addr & 0x20) ? DEV_1 : DEV_0;
memcpy(data, msg[0].buf, msg[0].len);
reg = (data[0] << 24) + (data[1] << 16) +
(data[2] << 8) + data[3];
if (num == 2) {
ret = it913x_io(d, READ_LONG, pro,
CMD_DEMOD_READ, reg, 0, data, msg[1].len);
memcpy(msg[1].buf, data, msg[1].len);
} else
ret = it913x_io(d, WRITE_LONG, pro, CMD_DEMOD_WRITE,
reg, 0, &data[4], msg[0].len - 4);
mutex_unlock(&d->i2c_mutex);
return ret;
}
static u32 it913x_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
static struct i2c_algorithm it913x_i2c_algo = {
.master_xfer = it913x_i2c_xfer,
.functionality = it913x_i2c_func,
};
/* Callbacks for DVB USB */
#if IS_ENABLED(CONFIG_RC_CORE)
static int it913x_rc_query(struct dvb_usb_device *d)
{
u8 ibuf[4];
int ret;
u32 key;
/* Avoid conflict with frontends*/
mutex_lock(&d->i2c_mutex);
ret = it913x_io(d, READ_LONG, PRO_LINK, CMD_IR_GET,
0, 0, &ibuf[0], sizeof(ibuf));
if ((ibuf[2] + ibuf[3]) == 0xff) {
key = ibuf[2];
key += ibuf[0] << 16;
key += ibuf[1] << 8;
deb_info(1, "NEC Extended Key =%08x", key);
if (d->rc_dev != NULL)
rc_keydown(d->rc_dev, key, 0);
}
mutex_unlock(&d->i2c_mutex);
return ret;
}
static int it913x_get_rc_config(struct dvb_usb_device *d, struct dvb_usb_rc *rc)
{
struct it913x_state *st = d->priv;
if (st->proprietary_ir == false) {
rc->map_name = NULL;
return 0;
}
rc->allowed_protos = RC_BIT_NEC;
rc->query = it913x_rc_query;
rc->interval = 250;
return 0;
}
#else
#define it913x_get_rc_config NULL
#endif
/* Firmware sets raw */
static const char fw_it9135_v1[] = FW_IT9135_V1;
static const char fw_it9135_v2[] = FW_IT9135_V2;
static const char fw_it9137[] = FW_IT9137;
static void ite_get_firmware_name(struct dvb_usb_device *d,
const char **name)
{
struct it913x_state *st = d->priv;
int sw;
/* auto switch */
if (le16_to_cpu(d->udev->descriptor.idVendor) == USB_VID_KWORLD_2)
sw = IT9137_FW;
else if (st->it913x_config.chip_ver == 1)
sw = IT9135_V1_FW;
else
sw = IT9135_V2_FW;
/* force switch */
if (dvb_usb_it913x_firmware != IT9135_AUTO)
sw = dvb_usb_it913x_firmware;
switch (sw) {
case IT9135_V1_FW:
st->it913x_config.firmware_ver = 1;
st->it913x_config.adc_x2 = 1;
st->it913x_config.read_slevel = false;
*name = fw_it9135_v1;
break;
case IT9135_V2_FW:
st->it913x_config.firmware_ver = 1;
st->it913x_config.adc_x2 = 1;
st->it913x_config.read_slevel = false;
*name = fw_it9135_v2;
switch (st->it913x_config.tuner_id_0) {
case IT9135_61:
case IT9135_62:
break;
default:
info("Unknown tuner ID applying default 0x60");
case IT9135_60:
st->it913x_config.tuner_id_0 = IT9135_60;
}
break;
case IT9137_FW:
default:
st->it913x_config.firmware_ver = 0;
st->it913x_config.adc_x2 = 0;
st->it913x_config.read_slevel = true;
*name = fw_it9137;
}
return;
}
#define TS_MPEG_PKT_SIZE 188
#define EP_LOW 21
#define TS_BUFFER_SIZE_PID (EP_LOW*TS_MPEG_PKT_SIZE)
#define EP_HIGH 348
#define TS_BUFFER_SIZE_MAX (EP_HIGH*TS_MPEG_PKT_SIZE)
static int it913x_get_stream_config(struct dvb_frontend *fe, u8 *ts_type,
struct usb_data_stream_properties *stream)
{
struct dvb_usb_adapter *adap = fe_to_adap(fe);
if (adap->pid_filtering)
stream->u.bulk.buffersize = TS_BUFFER_SIZE_PID;
else
stream->u.bulk.buffersize = TS_BUFFER_SIZE_MAX;
return 0;
}
static int it913x_select_config(struct dvb_usb_device *d)
{
struct it913x_state *st = d->priv;
int ret, reg;
ret = it913x_return_status(d);
if (ret < 0)
return ret;
if (st->it913x_config.chip_ver == 0x02
&& st->it913x_config.chip_type == 0x9135)
reg = it913x_read_reg(d, 0x461d);
else
reg = it913x_read_reg(d, 0x461b);
if (reg < 0)
return reg;
if (reg == 0) {
st->it913x_config.dual_mode = 0;
st->it913x_config.tuner_id_0 = IT9135_38;
st->proprietary_ir = true;
} else {
/* TS mode */
reg = it913x_read_reg(d, 0x49c5);
if (reg < 0)
return reg;
st->it913x_config.dual_mode = reg;
/* IR mode type */
reg = it913x_read_reg(d, 0x49ac);
if (reg < 0)
return reg;
if (reg == 5) {
info("Remote propriety (raw) mode");
st->proprietary_ir = true;
} else if (reg == 1) {
info("Remote HID mode NOT SUPPORTED");
st->proprietary_ir = false;
}
/* Tuner_id */
reg = it913x_read_reg(d, 0x49d0);
if (reg < 0)
return reg;
st->it913x_config.tuner_id_0 = reg;
}
info("Dual mode=%x Tuner Type=%x", st->it913x_config.dual_mode,
st->it913x_config.tuner_id_0);
return ret;
}
static int it913x_streaming_ctrl(struct dvb_frontend *fe, int onoff)
{
struct dvb_usb_adapter *adap = fe_to_adap(fe);
struct dvb_usb_device *d = adap_to_d(adap);
struct it913x_state *st = fe_to_priv(fe);
int ret = 0;
u8 pro = (adap->id == 0) ? DEV_0_DMOD : DEV_1_DMOD;
deb_info(1, "STM (%02x)", onoff);
if (!onoff) {
mutex_lock(&d->i2c_mutex);
ret = it913x_wr_reg(d, pro, PID_RST, 0x1);
mutex_unlock(&d->i2c_mutex);
st->pid_filter_onoff =
adap->pid_filtering;
}
return ret;
}
static int it913x_identify_state(struct dvb_usb_device *d, const char **name)
{
struct it913x_state *st = d->priv;
int ret;
u8 reg;
/* Read and select config */
ret = it913x_select_config(d);
if (ret < 0)
return ret;
ite_get_firmware_name(d, name);
if (st->it913x_config.firmware > 0)
return WARM;
if (st->it913x_config.dual_mode) {
st->it913x_config.tuner_id_1 = it913x_read_reg(d, 0x49e0);
ret = it913x_wr_reg(d, DEV_0, GPIOH1_EN, 0x1);
ret |= it913x_wr_reg(d, DEV_0, GPIOH1_ON, 0x1);
ret |= it913x_wr_reg(d, DEV_0, GPIOH1_O, 0x1);
msleep(50);
ret |= it913x_wr_reg(d, DEV_0, GPIOH1_O, 0x0);
msleep(50);
reg = it913x_read_reg(d, GPIOH1_O);
if (reg == 0) {
ret |= it913x_wr_reg(d, DEV_0, GPIOH1_O, 0x1);
ret |= it913x_return_status(d);
if (ret != 0)
ret = it913x_wr_reg(d, DEV_0,
GPIOH1_O, 0x0);
}
}
reg = it913x_read_reg(d, IO_MUX_POWER_CLK);
if (st->it913x_config.dual_mode) {
ret |= it913x_wr_reg(d, DEV_0, 0x4bfb, CHIP2_I2C_ADDR);
if (st->it913x_config.firmware_ver == 1)
ret |= it913x_wr_reg(d, DEV_0, 0xcfff, 0x1);
else
ret |= it913x_wr_reg(d, DEV_0, CLK_O_EN, 0x1);
} else {
ret |= it913x_wr_reg(d, DEV_0, 0x4bfb, 0x0);
if (st->it913x_config.firmware_ver == 1)
ret |= it913x_wr_reg(d, DEV_0, 0xcfff, 0x0);
else
ret |= it913x_wr_reg(d, DEV_0, CLK_O_EN, 0x0);
}
ret |= it913x_wr_reg(d, DEV_0, I2C_CLK, I2C_CLK_100);
return (ret < 0) ? ret : COLD;
}
static int it913x_download_firmware(struct dvb_usb_device *d,
const struct firmware *fw)
{
struct it913x_state *st = d->priv;
int ret = 0, i = 0, pos = 0;
u8 packet_size, min_pkt;
u8 *fw_data;
ret = it913x_wr_reg(d, DEV_0, I2C_CLK, I2C_CLK_100);
info("FRM Starting Firmware Download");
/* Multi firmware loader */
/* This uses scatter write firmware headers */
/* The firmware must start with 03 XX 00 */
/* and be the extact firmware length */
if (st->it913x_config.chip_ver == 2)
min_pkt = 0x11;
else
min_pkt = 0x19;
while (i <= fw->size) {
if (((fw->data[i] == 0x3) && (fw->data[i + 2] == 0x0))
|| (i == fw->size)) {
packet_size = i - pos;
if ((packet_size > min_pkt) || (i == fw->size)) {
fw_data = (u8 *)(fw->data + pos);
pos += packet_size;
if (packet_size > 0) {
ret = it913x_io(d, WRITE_DATA,
DEV_0, CMD_SCATTER_WRITE, 0,
0, fw_data, packet_size);
if (ret < 0)
break;
}
udelay(1000);
}
}
i++;
}
if (ret < 0)
info("FRM Firmware Download Failed (%d)" , ret);
else
info("FRM Firmware Download Completed - Resetting Device");
msleep(30);
ret = it913x_io(d, WRITE_CMD, DEV_0, CMD_BOOT, 0, 0, NULL, 0);
if (ret < 0)
info("FRM Device not responding to reboot");
ret = it913x_return_status(d);
if (st->it913x_config.firmware == 0) {
info("FRM Failed to reboot device");
return -ENODEV;
}
msleep(30);
ret = it913x_wr_reg(d, DEV_0, I2C_CLK, I2C_CLK_400);
msleep(30);
/* Tuner function */
if (st->it913x_config.dual_mode)
ret |= it913x_wr_reg(d, DEV_0_DMOD , 0xec4c, 0xa0);
else
ret |= it913x_wr_reg(d, DEV_0_DMOD , 0xec4c, 0x68);
if ((st->it913x_config.chip_ver == 1) &&
(st->it913x_config.chip_type == 0x9135)) {
ret |= it913x_wr_reg(d, DEV_0, PADODPU, 0x0);
ret |= it913x_wr_reg(d, DEV_0, AGC_O_D, 0x0);
if (st->it913x_config.dual_mode) {
ret |= it913x_wr_reg(d, DEV_1, PADODPU, 0x0);
ret |= it913x_wr_reg(d, DEV_1, AGC_O_D, 0x0);
}
}
return (ret < 0) ? -ENODEV : 0;
}
static int it913x_name(struct dvb_usb_adapter *adap)
{
struct dvb_usb_device *d = adap_to_d(adap);
const char *desc = d->name;
char *fe_name[] = {"_1", "_2", "_3", "_4"};
char *name = adap->fe[0]->ops.info.name;
strlcpy(name, desc, 128);
strlcat(name, fe_name[adap->id], 128);
return 0;
}
static int it913x_frontend_attach(struct dvb_usb_adapter *adap)
{
struct dvb_usb_device *d = adap_to_d(adap);
struct it913x_state *st = d->priv;
int ret = 0;
u8 adap_addr = I2C_BASE_ADDR + (adap->id << 5);
u16 ep_size = (adap->pid_filtering) ? TS_BUFFER_SIZE_PID / 4 :
TS_BUFFER_SIZE_MAX / 4;
u8 pkt_size = 0x80;
if (d->udev->speed != USB_SPEED_HIGH)
pkt_size = 0x10;
st->it913x_config.adf = it913x_read_reg(d, IO_MUX_POWER_CLK);
adap->fe[0] = dvb_attach(it913x_fe_attach,
&d->i2c_adap, adap_addr, &st->it913x_config);
if (adap->id == 0 && adap->fe[0]) {
it913x_wr_reg(d, DEV_0_DMOD, MP2_SW_RST, 0x1);
it913x_wr_reg(d, DEV_0_DMOD, MP2IF2_SW_RST, 0x1);
it913x_wr_reg(d, DEV_0, EP0_TX_EN, 0x0f);
it913x_wr_reg(d, DEV_0, EP0_TX_NAK, 0x1b);
if (st->proprietary_ir == false) /* Enable endpoint 3 */
it913x_wr_reg(d, DEV_0, EP0_TX_EN, 0x3f);
else
it913x_wr_reg(d, DEV_0, EP0_TX_EN, 0x2f);
it913x_wr_reg(d, DEV_0, EP4_TX_LEN_LSB,
ep_size & 0xff);
it913x_wr_reg(d, DEV_0, EP4_TX_LEN_MSB, ep_size >> 8);
ret = it913x_wr_reg(d, DEV_0, EP4_MAX_PKT, pkt_size);
} else if (adap->id == 1 && adap->fe[0]) {
if (st->proprietary_ir == false)
it913x_wr_reg(d, DEV_0, EP0_TX_EN, 0x7f);
else
it913x_wr_reg(d, DEV_0, EP0_TX_EN, 0x6f);
it913x_wr_reg(d, DEV_0, EP5_TX_LEN_LSB,
ep_size & 0xff);
it913x_wr_reg(d, DEV_0, EP5_TX_LEN_MSB, ep_size >> 8);
it913x_wr_reg(d, DEV_0, EP5_MAX_PKT, pkt_size);
it913x_wr_reg(d, DEV_0_DMOD, MP2IF2_EN, 0x1);
it913x_wr_reg(d, DEV_1_DMOD, MP2IF_SERIAL, 0x1);
it913x_wr_reg(d, DEV_1, TOP_HOSTB_SER_MODE, 0x1);
it913x_wr_reg(d, DEV_0_DMOD, TSIS_ENABLE, 0x1);
it913x_wr_reg(d, DEV_0_DMOD, MP2_SW_RST, 0x0);
it913x_wr_reg(d, DEV_0_DMOD, MP2IF2_SW_RST, 0x0);
it913x_wr_reg(d, DEV_0_DMOD, MP2IF2_HALF_PSB, 0x0);
it913x_wr_reg(d, DEV_0_DMOD, MP2IF_STOP_EN, 0x1);
it913x_wr_reg(d, DEV_1_DMOD, MPEG_FULL_SPEED, 0x0);
ret = it913x_wr_reg(d, DEV_1_DMOD, MP2IF_STOP_EN, 0x0);
} else
return -ENODEV;
ret |= it913x_name(adap);
return ret;
}
/* DVB USB Driver */
static int it913x_get_adapter_count(struct dvb_usb_device *d)
{
struct it913x_state *st = d->priv;
if (st->it913x_config.dual_mode)
return 2;
return 1;
}
static struct dvb_usb_device_properties it913x_properties = {
.driver_name = KBUILD_MODNAME,
.owner = THIS_MODULE,
.bInterfaceNumber = 0,
.generic_bulk_ctrl_endpoint = 0x02,
.generic_bulk_ctrl_endpoint_response = 0x81,
.adapter_nr = adapter_nr,
.size_of_priv = sizeof(struct it913x_state),
.identify_state = it913x_identify_state,
.i2c_algo = &it913x_i2c_algo,
.download_firmware = it913x_download_firmware,
.frontend_attach = it913x_frontend_attach,
.get_rc_config = it913x_get_rc_config,
.get_stream_config = it913x_get_stream_config,
.get_adapter_count = it913x_get_adapter_count,
.streaming_ctrl = it913x_streaming_ctrl,
.adapter = {
{
.caps = DVB_USB_ADAP_HAS_PID_FILTER|
DVB_USB_ADAP_PID_FILTER_CAN_BE_TURNED_OFF,
.pid_filter_count = 32,
.pid_filter = it913x_pid_filter,
.pid_filter_ctrl = it913x_pid_filter_ctrl,
.stream =
DVB_USB_STREAM_BULK(0x84, 10, TS_BUFFER_SIZE_MAX),
},
{
.caps = DVB_USB_ADAP_HAS_PID_FILTER|
DVB_USB_ADAP_PID_FILTER_CAN_BE_TURNED_OFF,
.pid_filter_count = 32,
.pid_filter = it913x_pid_filter,
.pid_filter_ctrl = it913x_pid_filter_ctrl,
.stream =
DVB_USB_STREAM_BULK(0x85, 10, TS_BUFFER_SIZE_MAX),
}
}
};
static const struct usb_device_id it913x_id_table[] = {
{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_KWORLD_UB499_2T_T09,
&it913x_properties, "Kworld UB499-2T T09(IT9137)",
RC_MAP_IT913X_V1) },
{ DVB_USB_DEVICE(USB_VID_ITETECH, USB_PID_ITETECH_IT9135,
&it913x_properties, "ITE 9135 Generic",
RC_MAP_IT913X_V1) },
{ DVB_USB_DEVICE(USB_VID_KWORLD_2, USB_PID_SVEON_STV22_IT9137,
&it913x_properties, "Sveon STV22 Dual DVB-T HDTV(IT9137)",
RC_MAP_IT913X_V1) },
{ DVB_USB_DEVICE(USB_VID_ITETECH, USB_PID_ITETECH_IT9135_9005,
&it913x_properties, "ITE 9135(9005) Generic",
RC_MAP_IT913X_V2) },
{ DVB_USB_DEVICE(USB_VID_ITETECH, USB_PID_ITETECH_IT9135_9006,
&it913x_properties, "ITE 9135(9006) Generic",
RC_MAP_IT913X_V1) },
{ DVB_USB_DEVICE(USB_VID_AVERMEDIA, USB_PID_AVERMEDIA_A835B_1835,
&it913x_properties, "Avermedia A835B(1835)",
RC_MAP_IT913X_V2) },
{ DVB_USB_DEVICE(USB_VID_AVERMEDIA, USB_PID_AVERMEDIA_A835B_2835,
&it913x_properties, "Avermedia A835B(2835)",
RC_MAP_IT913X_V2) },
{ DVB_USB_DEVICE(USB_VID_AVERMEDIA, USB_PID_AVERMEDIA_A835B_3835,
&it913x_properties, "Avermedia A835B(3835)",
RC_MAP_IT913X_V2) },
{ DVB_USB_DEVICE(USB_VID_AVERMEDIA, USB_PID_AVERMEDIA_A835B_4835,
&it913x_properties, "Avermedia A835B(4835)",
RC_MAP_IT913X_V2) },
{} /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, it913x_id_table);
static struct usb_driver it913x_driver = {
.name = KBUILD_MODNAME,
.probe = dvb_usbv2_probe,
.disconnect = dvb_usbv2_disconnect,
.suspend = dvb_usbv2_suspend,
.resume = dvb_usbv2_resume,
.id_table = it913x_id_table,
};
module_usb_driver(it913x_driver);
MODULE_AUTHOR("Malcolm Priestley <tvboxspy@gmail.com>");
MODULE_DESCRIPTION("it913x USB 2 Driver");
MODULE_VERSION("1.33");
MODULE_LICENSE("GPL");
MODULE_FIRMWARE(FW_IT9135_V1);
MODULE_FIRMWARE(FW_IT9135_V2);
MODULE_FIRMWARE(FW_IT9137);
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.