repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
MassStash/m8whl_sense | arch/arm/mach-s3c24xx/mach-vr1000.c | 4734 | 9025 | /* linux/arch/arm/mach-s3c2410/mach-vr1000.c
*
* Copyright (c) 2003-2008 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
*
* Machine support for Thorcom VR1000 board. Designed for Thorcom by
* Simtec Electronics, http://www.simtec.co.uk/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/gpio.h>
#include <linux/dm9000.h>
#include <linux/i2c.h>
#include <linux/serial.h>
#include <linux/tty.h>
#include <linux/serial_8250.h>
#include <linux/serial_reg.h>
#include <linux/io.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/bast-map.h>
#include <mach/vr1000-map.h>
#include <mach/vr1000-irq.h>
#include <mach/vr1000-cpld.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <plat/regs-serial.h>
#include <mach/regs-gpio.h>
#include <mach/leds-gpio.h>
#include <plat/clock.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/iic.h>
#include <plat/audio-simtec.h>
#include "simtec.h"
#include "common.h"
/* macros for virtual address mods for the io space entries */
#define VA_C5(item) ((unsigned long)(item) + BAST_VAM_CS5)
#define VA_C4(item) ((unsigned long)(item) + BAST_VAM_CS4)
#define VA_C3(item) ((unsigned long)(item) + BAST_VAM_CS3)
#define VA_C2(item) ((unsigned long)(item) + BAST_VAM_CS2)
/* macros to modify the physical addresses for io space */
#define PA_CS2(item) (__phys_to_pfn((item) + S3C2410_CS2))
#define PA_CS3(item) (__phys_to_pfn((item) + S3C2410_CS3))
#define PA_CS4(item) (__phys_to_pfn((item) + S3C2410_CS4))
#define PA_CS5(item) (__phys_to_pfn((item) + S3C2410_CS5))
static struct map_desc vr1000_iodesc[] __initdata = {
/* ISA IO areas */
{
.virtual = (u32)S3C24XX_VA_ISA_BYTE,
.pfn = PA_CS2(BAST_PA_ISAIO),
.length = SZ_16M,
.type = MT_DEVICE,
}, {
.virtual = (u32)S3C24XX_VA_ISA_WORD,
.pfn = PA_CS3(BAST_PA_ISAIO),
.length = SZ_16M,
.type = MT_DEVICE,
},
/* CPLD control registers, and external interrupt controls */
{
.virtual = (u32)VR1000_VA_CTRL1,
.pfn = __phys_to_pfn(VR1000_PA_CTRL1),
.length = SZ_1M,
.type = MT_DEVICE,
}, {
.virtual = (u32)VR1000_VA_CTRL2,
.pfn = __phys_to_pfn(VR1000_PA_CTRL2),
.length = SZ_1M,
.type = MT_DEVICE,
}, {
.virtual = (u32)VR1000_VA_CTRL3,
.pfn = __phys_to_pfn(VR1000_PA_CTRL3),
.length = SZ_1M,
.type = MT_DEVICE,
}, {
.virtual = (u32)VR1000_VA_CTRL4,
.pfn = __phys_to_pfn(VR1000_PA_CTRL4),
.length = SZ_1M,
.type = MT_DEVICE,
},
};
#define UCON S3C2410_UCON_DEFAULT | S3C2410_UCON_UCLK
#define ULCON S3C2410_LCON_CS8 | S3C2410_LCON_PNONE | S3C2410_LCON_STOPB
#define UFCON S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE
static struct s3c2410_uartcfg vr1000_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
/* port 2 is not actually used */
[2] = {
.hwport = 2,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
}
};
/* definitions for the vr1000 extra 16550 serial ports */
#define VR1000_BAUDBASE (3692307)
#define VR1000_SERIAL_MAPBASE(x) (VR1000_PA_SERIAL + 0x80 + ((x) << 5))
static struct plat_serial8250_port serial_platform_data[] = {
[0] = {
.mapbase = VR1000_SERIAL_MAPBASE(0),
.irq = IRQ_VR1000_SERIAL + 0,
.flags = UPF_BOOT_AUTOCONF | UPF_IOREMAP,
.iotype = UPIO_MEM,
.regshift = 0,
.uartclk = VR1000_BAUDBASE,
},
[1] = {
.mapbase = VR1000_SERIAL_MAPBASE(1),
.irq = IRQ_VR1000_SERIAL + 1,
.flags = UPF_BOOT_AUTOCONF | UPF_IOREMAP,
.iotype = UPIO_MEM,
.regshift = 0,
.uartclk = VR1000_BAUDBASE,
},
[2] = {
.mapbase = VR1000_SERIAL_MAPBASE(2),
.irq = IRQ_VR1000_SERIAL + 2,
.flags = UPF_BOOT_AUTOCONF | UPF_IOREMAP,
.iotype = UPIO_MEM,
.regshift = 0,
.uartclk = VR1000_BAUDBASE,
},
[3] = {
.mapbase = VR1000_SERIAL_MAPBASE(3),
.irq = IRQ_VR1000_SERIAL + 3,
.flags = UPF_BOOT_AUTOCONF | UPF_IOREMAP,
.iotype = UPIO_MEM,
.regshift = 0,
.uartclk = VR1000_BAUDBASE,
},
{ },
};
static struct platform_device serial_device = {
.name = "serial8250",
.id = PLAT8250_DEV_PLATFORM,
.dev = {
.platform_data = serial_platform_data,
},
};
/* DM9000 ethernet devices */
static struct resource vr1000_dm9k0_resource[] = {
[0] = {
.start = S3C2410_CS5 + VR1000_PA_DM9000,
.end = S3C2410_CS5 + VR1000_PA_DM9000 + 3,
.flags = IORESOURCE_MEM
},
[1] = {
.start = S3C2410_CS5 + VR1000_PA_DM9000 + 0x40,
.end = S3C2410_CS5 + VR1000_PA_DM9000 + 0x7f,
.flags = IORESOURCE_MEM
},
[2] = {
.start = IRQ_VR1000_DM9000A,
.end = IRQ_VR1000_DM9000A,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL,
}
};
static struct resource vr1000_dm9k1_resource[] = {
[0] = {
.start = S3C2410_CS5 + VR1000_PA_DM9000 + 0x80,
.end = S3C2410_CS5 + VR1000_PA_DM9000 + 0x83,
.flags = IORESOURCE_MEM
},
[1] = {
.start = S3C2410_CS5 + VR1000_PA_DM9000 + 0xC0,
.end = S3C2410_CS5 + VR1000_PA_DM9000 + 0xFF,
.flags = IORESOURCE_MEM
},
[2] = {
.start = IRQ_VR1000_DM9000N,
.end = IRQ_VR1000_DM9000N,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL,
}
};
/* for the moment we limit ourselves to 16bit IO until some
* better IO routines can be written and tested
*/
static struct dm9000_plat_data vr1000_dm9k_platdata = {
.flags = DM9000_PLATF_16BITONLY,
};
static struct platform_device vr1000_dm9k0 = {
.name = "dm9000",
.id = 0,
.num_resources = ARRAY_SIZE(vr1000_dm9k0_resource),
.resource = vr1000_dm9k0_resource,
.dev = {
.platform_data = &vr1000_dm9k_platdata,
}
};
static struct platform_device vr1000_dm9k1 = {
.name = "dm9000",
.id = 1,
.num_resources = ARRAY_SIZE(vr1000_dm9k1_resource),
.resource = vr1000_dm9k1_resource,
.dev = {
.platform_data = &vr1000_dm9k_platdata,
}
};
/* LEDS */
static struct s3c24xx_led_platdata vr1000_led1_pdata = {
.name = "led1",
.gpio = S3C2410_GPB(0),
.def_trigger = "",
};
static struct s3c24xx_led_platdata vr1000_led2_pdata = {
.name = "led2",
.gpio = S3C2410_GPB(1),
.def_trigger = "",
};
static struct s3c24xx_led_platdata vr1000_led3_pdata = {
.name = "led3",
.gpio = S3C2410_GPB(2),
.def_trigger = "",
};
static struct platform_device vr1000_led1 = {
.name = "s3c24xx_led",
.id = 1,
.dev = {
.platform_data = &vr1000_led1_pdata,
},
};
static struct platform_device vr1000_led2 = {
.name = "s3c24xx_led",
.id = 2,
.dev = {
.platform_data = &vr1000_led2_pdata,
},
};
static struct platform_device vr1000_led3 = {
.name = "s3c24xx_led",
.id = 3,
.dev = {
.platform_data = &vr1000_led3_pdata,
},
};
/* I2C devices. */
static struct i2c_board_info vr1000_i2c_devs[] __initdata = {
{
I2C_BOARD_INFO("tlv320aic23", 0x1a),
}, {
I2C_BOARD_INFO("tmp101", 0x48),
}, {
I2C_BOARD_INFO("m41st87", 0x68),
},
};
/* devices for this board */
static struct platform_device *vr1000_devices[] __initdata = {
&s3c_device_ohci,
&s3c_device_lcd,
&s3c_device_wdt,
&s3c_device_i2c0,
&s3c_device_adc,
&serial_device,
&vr1000_dm9k0,
&vr1000_dm9k1,
&vr1000_led1,
&vr1000_led2,
&vr1000_led3,
};
static struct clk *vr1000_clocks[] __initdata = {
&s3c24xx_dclk0,
&s3c24xx_dclk1,
&s3c24xx_clkout0,
&s3c24xx_clkout1,
&s3c24xx_uclk,
};
static void vr1000_power_off(void)
{
gpio_direction_output(S3C2410_GPB(9), 1);
}
static void __init vr1000_map_io(void)
{
/* initialise clock sources */
s3c24xx_dclk0.parent = &clk_upll;
s3c24xx_dclk0.rate = 12*1000*1000;
s3c24xx_dclk1.parent = NULL;
s3c24xx_dclk1.rate = 3692307;
s3c24xx_clkout0.parent = &s3c24xx_dclk0;
s3c24xx_clkout1.parent = &s3c24xx_dclk1;
s3c24xx_uclk.parent = &s3c24xx_clkout1;
s3c24xx_register_clocks(vr1000_clocks, ARRAY_SIZE(vr1000_clocks));
pm_power_off = vr1000_power_off;
s3c24xx_init_io(vr1000_iodesc, ARRAY_SIZE(vr1000_iodesc));
s3c24xx_init_clocks(0);
s3c24xx_init_uarts(vr1000_uartcfgs, ARRAY_SIZE(vr1000_uartcfgs));
}
static void __init vr1000_init(void)
{
s3c_i2c0_set_platdata(NULL);
platform_add_devices(vr1000_devices, ARRAY_SIZE(vr1000_devices));
i2c_register_board_info(0, vr1000_i2c_devs,
ARRAY_SIZE(vr1000_i2c_devs));
nor_simtec_init();
simtec_audio_add(NULL, true, NULL);
WARN_ON(gpio_request(S3C2410_GPB(9), "power off"));
}
MACHINE_START(VR1000, "Thorcom-VR1000")
/* Maintainer: Ben Dooks <ben@simtec.co.uk> */
.atag_offset = 0x100,
.map_io = vr1000_map_io,
.init_machine = vr1000_init,
.init_irq = s3c24xx_init_irq,
.timer = &s3c24xx_timer,
.restart = s3c2410_restart,
MACHINE_END
| gpl-2.0 |
Emptying/android_kernel_a890 | lib/hexdump.c | 4734 | 7158 | /*
* lib/hexdump.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation. See README and COPYING for
* more details.
*/
#include <linux/types.h>
#include <linux/ctype.h>
#include <linux/kernel.h>
#include <linux/export.h>
const char hex_asc[] = "0123456789abcdef";
EXPORT_SYMBOL(hex_asc);
/**
* hex_to_bin - convert a hex digit to its real value
* @ch: ascii character represents hex digit
*
* hex_to_bin() converts one hex digit to its actual value or -1 in case of bad
* input.
*/
int hex_to_bin(char ch)
{
if ((ch >= '0') && (ch <= '9'))
return ch - '0';
ch = tolower(ch);
if ((ch >= 'a') && (ch <= 'f'))
return ch - 'a' + 10;
return -1;
}
EXPORT_SYMBOL(hex_to_bin);
/**
* hex2bin - convert an ascii hexadecimal string to its binary representation
* @dst: binary result
* @src: ascii hexadecimal string
* @count: result length
*
* Return 0 on success, -1 in case of bad input.
*/
int hex2bin(u8 *dst, const char *src, size_t count)
{
while (count--) {
int hi = hex_to_bin(*src++);
int lo = hex_to_bin(*src++);
if ((hi < 0) || (lo < 0))
return -1;
*dst++ = (hi << 4) | lo;
}
return 0;
}
EXPORT_SYMBOL(hex2bin);
/**
* hex_dump_to_buffer - convert a blob of data to "hex ASCII" in memory
* @buf: data blob to dump
* @len: number of bytes in the @buf
* @rowsize: number of bytes to print per line; must be 16 or 32
* @groupsize: number of bytes to print at a time (1, 2, 4, 8; default = 1)
* @linebuf: where to put the converted data
* @linebuflen: total size of @linebuf, including space for terminating NUL
* @ascii: include ASCII after the hex output
*
* hex_dump_to_buffer() works on one "line" of output at a time, i.e.,
* 16 or 32 bytes of input data converted to hex + ASCII output.
*
* Given a buffer of u8 data, hex_dump_to_buffer() converts the input data
* to a hex + ASCII dump at the supplied memory location.
* The converted output is always NUL-terminated.
*
* E.g.:
* hex_dump_to_buffer(frame->data, frame->len, 16, 1,
* linebuf, sizeof(linebuf), true);
*
* example output buffer:
* 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f @ABCDEFGHIJKLMNO
*/
void hex_dump_to_buffer(const void *buf, size_t len, int rowsize,
int groupsize, char *linebuf, size_t linebuflen,
bool ascii)
{
const u8 *ptr = buf;
u8 ch;
int j, lx = 0;
int ascii_column;
if (rowsize != 16 && rowsize != 32)
rowsize = 16;
if (!len)
goto nil;
if (len > rowsize) /* limit to one line at a time */
len = rowsize;
if ((len % groupsize) != 0) /* no mixed size output */
groupsize = 1;
switch (groupsize) {
case 8: {
const u64 *ptr8 = buf;
int ngroups = len / groupsize;
for (j = 0; j < ngroups; j++)
lx += scnprintf(linebuf + lx, linebuflen - lx,
"%s%16.16llx", j ? " " : "",
(unsigned long long)*(ptr8 + j));
ascii_column = 17 * ngroups + 2;
break;
}
case 4: {
const u32 *ptr4 = buf;
int ngroups = len / groupsize;
for (j = 0; j < ngroups; j++)
lx += scnprintf(linebuf + lx, linebuflen - lx,
"%s%8.8x", j ? " " : "", *(ptr4 + j));
ascii_column = 9 * ngroups + 2;
break;
}
case 2: {
const u16 *ptr2 = buf;
int ngroups = len / groupsize;
for (j = 0; j < ngroups; j++)
lx += scnprintf(linebuf + lx, linebuflen - lx,
"%s%4.4x", j ? " " : "", *(ptr2 + j));
ascii_column = 5 * ngroups + 2;
break;
}
default:
for (j = 0; (j < len) && (lx + 3) <= linebuflen; j++) {
ch = ptr[j];
linebuf[lx++] = hex_asc_hi(ch);
linebuf[lx++] = hex_asc_lo(ch);
linebuf[lx++] = ' ';
}
if (j)
lx--;
ascii_column = 3 * rowsize + 2;
break;
}
if (!ascii)
goto nil;
while (lx < (linebuflen - 1) && lx < (ascii_column - 1))
linebuf[lx++] = ' ';
for (j = 0; (j < len) && (lx + 2) < linebuflen; j++) {
ch = ptr[j];
linebuf[lx++] = (isascii(ch) && isprint(ch)) ? ch : '.';
}
nil:
linebuf[lx++] = '\0';
}
EXPORT_SYMBOL(hex_dump_to_buffer);
#ifdef CONFIG_PRINTK
/**
* print_hex_dump - print a text hex dump to syslog for a binary blob of data
* @level: kernel log level (e.g. KERN_DEBUG)
* @prefix_str: string to prefix each line with;
* caller supplies trailing spaces for alignment if desired
* @prefix_type: controls whether prefix of an offset, address, or none
* is printed (%DUMP_PREFIX_OFFSET, %DUMP_PREFIX_ADDRESS, %DUMP_PREFIX_NONE)
* @rowsize: number of bytes to print per line; must be 16 or 32
* @groupsize: number of bytes to print at a time (1, 2, 4, 8; default = 1)
* @buf: data blob to dump
* @len: number of bytes in the @buf
* @ascii: include ASCII after the hex output
*
* Given a buffer of u8 data, print_hex_dump() prints a hex + ASCII dump
* to the kernel log at the specified kernel log level, with an optional
* leading prefix.
*
* print_hex_dump() works on one "line" of output at a time, i.e.,
* 16 or 32 bytes of input data converted to hex + ASCII output.
* print_hex_dump() iterates over the entire input @buf, breaking it into
* "line size" chunks to format and print.
*
* E.g.:
* print_hex_dump(KERN_DEBUG, "raw data: ", DUMP_PREFIX_ADDRESS,
* 16, 1, frame->data, frame->len, true);
*
* Example output using %DUMP_PREFIX_OFFSET and 1-byte mode:
* 0009ab42: 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f @ABCDEFGHIJKLMNO
* Example output using %DUMP_PREFIX_ADDRESS and 4-byte mode:
* ffffffff88089af0: 73727170 77767574 7b7a7978 7f7e7d7c pqrstuvwxyz{|}~.
*/
void print_hex_dump(const char *level, const char *prefix_str, int prefix_type,
int rowsize, int groupsize,
const void *buf, size_t len, bool ascii)
{
const u8 *ptr = buf;
int i, linelen, remaining = len;
unsigned char linebuf[32 * 3 + 2 + 32 + 1];
if (rowsize != 16 && rowsize != 32)
rowsize = 16;
for (i = 0; i < len; i += rowsize) {
linelen = min(remaining, rowsize);
remaining -= rowsize;
hex_dump_to_buffer(ptr + i, linelen, rowsize, groupsize,
linebuf, sizeof(linebuf), ascii);
switch (prefix_type) {
case DUMP_PREFIX_ADDRESS:
printk("%s%s%p: %s\n",
level, prefix_str, ptr + i, linebuf);
break;
case DUMP_PREFIX_OFFSET:
printk("%s%s%.8x: %s\n", level, prefix_str, i, linebuf);
break;
default:
printk("%s%s%s\n", level, prefix_str, linebuf);
break;
}
}
}
EXPORT_SYMBOL(print_hex_dump);
/**
* print_hex_dump_bytes - shorthand form of print_hex_dump() with default params
* @prefix_str: string to prefix each line with;
* caller supplies trailing spaces for alignment if desired
* @prefix_type: controls whether prefix of an offset, address, or none
* is printed (%DUMP_PREFIX_OFFSET, %DUMP_PREFIX_ADDRESS, %DUMP_PREFIX_NONE)
* @buf: data blob to dump
* @len: number of bytes in the @buf
*
* Calls print_hex_dump(), with log level of KERN_DEBUG,
* rowsize of 16, groupsize of 1, and ASCII output included.
*/
void print_hex_dump_bytes(const char *prefix_str, int prefix_type,
const void *buf, size_t len)
{
print_hex_dump(KERN_DEBUG, prefix_str, prefix_type, 16, 1,
buf, len, true);
}
EXPORT_SYMBOL(print_hex_dump_bytes);
#endif
| gpl-2.0 |
cleaton/liquid-chocolate | drivers/isdn/mISDN/dsp_hwec.c | 4990 | 3049 | /*
* dsp_hwec.c:
* builtin mISDN dsp pipeline element for enabling the hw echocanceller
*
* Copyright (C) 2007, Nadi Sarrar
*
* Nadi Sarrar <nadi@beronet.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
*/
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/mISDNdsp.h>
#include <linux/mISDNif.h>
#include "core.h"
#include "dsp.h"
#include "dsp_hwec.h"
static struct mISDN_dsp_element_arg args[] = {
{ "deftaps", "128", "Set the number of taps of cancellation." },
};
static struct mISDN_dsp_element dsp_hwec_p = {
.name = "hwec",
.new = NULL,
.free = NULL,
.process_tx = NULL,
.process_rx = NULL,
.num_args = ARRAY_SIZE(args),
.args = args,
};
struct mISDN_dsp_element *dsp_hwec = &dsp_hwec_p;
void dsp_hwec_enable(struct dsp *dsp, const char *arg)
{
int deftaps = 128,
len;
struct mISDN_ctrl_req cq;
if (!dsp) {
printk(KERN_ERR "%s: failed to enable hwec: dsp is NULL\n",
__func__);
return;
}
if (!arg)
goto _do;
len = strlen(arg);
if (!len)
goto _do;
{
char _dup[len + 1];
char *dup, *tok, *name, *val;
int tmp;
strcpy(_dup, arg);
dup = _dup;
while ((tok = strsep(&dup, ","))) {
if (!strlen(tok))
continue;
name = strsep(&tok, "=");
val = tok;
if (!val)
continue;
if (!strcmp(name, "deftaps")) {
if (sscanf(val, "%d", &tmp) == 1)
deftaps = tmp;
}
}
}
_do:
printk(KERN_DEBUG "%s: enabling hwec with deftaps=%d\n",
__func__, deftaps);
memset(&cq, 0, sizeof(cq));
cq.op = MISDN_CTRL_HFC_ECHOCAN_ON;
cq.p1 = deftaps;
if (!dsp->ch.peer->ctrl(&dsp->ch, CONTROL_CHANNEL, &cq)) {
printk(KERN_DEBUG "%s: CONTROL_CHANNEL failed\n",
__func__);
return;
}
}
void dsp_hwec_disable(struct dsp *dsp)
{
struct mISDN_ctrl_req cq;
if (!dsp) {
printk(KERN_ERR "%s: failed to disable hwec: dsp is NULL\n",
__func__);
return;
}
printk(KERN_DEBUG "%s: disabling hwec\n", __func__);
memset(&cq, 0, sizeof(cq));
cq.op = MISDN_CTRL_HFC_ECHOCAN_OFF;
if (!dsp->ch.peer->ctrl(&dsp->ch, CONTROL_CHANNEL, &cq)) {
printk(KERN_DEBUG "%s: CONTROL_CHANNEL failed\n",
__func__);
return;
}
}
int dsp_hwec_init(void)
{
mISDN_dsp_element_register(dsp_hwec);
return 0;
}
void dsp_hwec_exit(void)
{
mISDN_dsp_element_unregister(dsp_hwec);
}
| gpl-2.0 |
Validus-Lollipop/android_kernel_motorola_msm8960dt-common | drivers/ata/pata_radisys.c | 5502 | 6962 | /*
* pata_radisys.c - Intel PATA/SATA controllers
*
* (C) 2006 Red Hat <alan@lxorguk.ukuu.org.uk>
*
* Some parts based on ata_piix.c by Jeff Garzik and others.
*
* A PIIX relative, this device has a single ATA channel and no
* slave timings, SITRE or PPE. In that sense it is a close relative
* of the original PIIX. It does however support UDMA 33/66 per channel
* although no other modes/timings. Also lacking is 32bit I/O on the ATA
* port.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#include <linux/ata.h>
#define DRV_NAME "pata_radisys"
#define DRV_VERSION "0.4.4"
/**
* radisys_set_piomode - Initialize host controller PATA PIO timings
* @ap: ATA port
* @adev: Device whose timings we are configuring
*
* Set PIO mode for device, in host controller PCI config space.
*
* LOCKING:
* None (inherited from caller).
*/
static void radisys_set_piomode (struct ata_port *ap, struct ata_device *adev)
{
unsigned int pio = adev->pio_mode - XFER_PIO_0;
struct pci_dev *dev = to_pci_dev(ap->host->dev);
u16 idetm_data;
int control = 0;
/*
* See Intel Document 298600-004 for the timing programing rules
* for PIIX/ICH. Note that the early PIIX does not have the slave
* timing port at 0x44. The Radisys is a relative of the PIIX
* but not the same so be careful.
*/
static const /* ISP RTC */
u8 timings[][2] = { { 0, 0 }, /* Check me */
{ 0, 0 },
{ 1, 1 },
{ 2, 2 },
{ 3, 3 }, };
if (pio > 0)
control |= 1; /* TIME1 enable */
if (ata_pio_need_iordy(adev))
control |= 2; /* IE IORDY */
pci_read_config_word(dev, 0x40, &idetm_data);
/* Enable IE and TIME as appropriate. Clear the other
drive timing bits */
idetm_data &= 0xCCCC;
idetm_data |= (control << (4 * adev->devno));
idetm_data |= (timings[pio][0] << 12) |
(timings[pio][1] << 8);
pci_write_config_word(dev, 0x40, idetm_data);
/* Track which port is configured */
ap->private_data = adev;
}
/**
* radisys_set_dmamode - Initialize host controller PATA DMA timings
* @ap: Port whose timings we are configuring
* @adev: Device to program
*
* Set MWDMA mode for device, in host controller PCI config space.
*
* LOCKING:
* None (inherited from caller).
*/
static void radisys_set_dmamode (struct ata_port *ap, struct ata_device *adev)
{
struct pci_dev *dev = to_pci_dev(ap->host->dev);
u16 idetm_data;
u8 udma_enable;
static const /* ISP RTC */
u8 timings[][2] = { { 0, 0 },
{ 0, 0 },
{ 1, 1 },
{ 2, 2 },
{ 3, 3 }, };
/*
* MWDMA is driven by the PIO timings. We must also enable
* IORDY unconditionally.
*/
pci_read_config_word(dev, 0x40, &idetm_data);
pci_read_config_byte(dev, 0x48, &udma_enable);
if (adev->dma_mode < XFER_UDMA_0) {
unsigned int mwdma = adev->dma_mode - XFER_MW_DMA_0;
const unsigned int needed_pio[3] = {
XFER_PIO_0, XFER_PIO_3, XFER_PIO_4
};
int pio = needed_pio[mwdma] - XFER_PIO_0;
int control = 3; /* IORDY|TIME0 */
/* If the drive MWDMA is faster than it can do PIO then
we must force PIO0 for PIO cycles. */
if (adev->pio_mode < needed_pio[mwdma])
control = 1;
/* Mask out the relevant control and timing bits we will load. Also
clear the other drive TIME register as a precaution */
idetm_data &= 0xCCCC;
idetm_data |= control << (4 * adev->devno);
idetm_data |= (timings[pio][0] << 12) | (timings[pio][1] << 8);
udma_enable &= ~(1 << adev->devno);
} else {
u8 udma_mode;
/* UDMA66 on: UDMA 33 and 66 are switchable via register 0x4A */
pci_read_config_byte(dev, 0x4A, &udma_mode);
if (adev->xfer_mode == XFER_UDMA_2)
udma_mode &= ~(2 << (adev->devno * 4));
else /* UDMA 4 */
udma_mode |= (2 << (adev->devno * 4));
pci_write_config_byte(dev, 0x4A, udma_mode);
udma_enable |= (1 << adev->devno);
}
pci_write_config_word(dev, 0x40, idetm_data);
pci_write_config_byte(dev, 0x48, udma_enable);
/* Track which port is configured */
ap->private_data = adev;
}
/**
* radisys_qc_issue - command issue
* @qc: command pending
*
* Called when the libata layer is about to issue a command. We wrap
* this interface so that we can load the correct ATA timings if
* necessary. Our logic also clears TIME0/TIME1 for the other device so
* that, even if we get this wrong, cycles to the other device will
* be made PIO0.
*/
static unsigned int radisys_qc_issue(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_device *adev = qc->dev;
if (adev != ap->private_data) {
/* UDMA timing is not shared */
if (adev->dma_mode < XFER_UDMA_0) {
if (adev->dma_mode)
radisys_set_dmamode(ap, adev);
else if (adev->pio_mode)
radisys_set_piomode(ap, adev);
}
}
return ata_bmdma_qc_issue(qc);
}
static struct scsi_host_template radisys_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
static struct ata_port_operations radisys_pata_ops = {
.inherits = &ata_bmdma_port_ops,
.qc_issue = radisys_qc_issue,
.cable_detect = ata_cable_unknown,
.set_piomode = radisys_set_piomode,
.set_dmamode = radisys_set_dmamode,
};
/**
* radisys_init_one - Register PIIX ATA PCI device with kernel services
* @pdev: PCI device to register
* @ent: Entry in radisys_pci_tbl matching with @pdev
*
* Called from kernel PCI layer. We probe for combined mode (sigh),
* and then hand over control to libata, for it to do the rest.
*
* LOCKING:
* Inherited from PCI layer (may sleep).
*
* RETURNS:
* Zero on success, or -ERRNO value.
*/
static int radisys_init_one (struct pci_dev *pdev, const struct pci_device_id *ent)
{
static const struct ata_port_info info = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA12_ONLY,
.udma_mask = ATA_UDMA24_ONLY,
.port_ops = &radisys_pata_ops,
};
const struct ata_port_info *ppi[] = { &info, NULL };
ata_print_version_once(&pdev->dev, DRV_VERSION);
return ata_pci_bmdma_init_one(pdev, ppi, &radisys_sht, NULL, 0);
}
static const struct pci_device_id radisys_pci_tbl[] = {
{ PCI_VDEVICE(RADISYS, 0x8201), },
{ } /* terminate list */
};
static struct pci_driver radisys_pci_driver = {
.name = DRV_NAME,
.id_table = radisys_pci_tbl,
.probe = radisys_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM
.suspend = ata_pci_device_suspend,
.resume = ata_pci_device_resume,
#endif
};
static int __init radisys_init(void)
{
return pci_register_driver(&radisys_pci_driver);
}
static void __exit radisys_exit(void)
{
pci_unregister_driver(&radisys_pci_driver);
}
module_init(radisys_init);
module_exit(radisys_exit);
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("SCSI low-level driver for Radisys R82600 controllers");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, radisys_pci_tbl);
MODULE_VERSION(DRV_VERSION);
| gpl-2.0 |
loiz/android_kernel_samsung_hllte | drivers/ata/pata_acpi.c | 5502 | 6978 | /*
* ACPI PATA driver
*
* (c) 2007 Red Hat
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/gfp.h>
#include <scsi/scsi_host.h>
#include <acpi/acpi_bus.h>
#include <linux/libata.h>
#include <linux/ata.h>
#define DRV_NAME "pata_acpi"
#define DRV_VERSION "0.2.3"
struct pata_acpi {
struct ata_acpi_gtm gtm;
void *last;
unsigned long mask[2];
};
/**
* pacpi_pre_reset - check for 40/80 pin
* @ap: Port
* @deadline: deadline jiffies for the operation
*
* Perform the PATA port setup we need.
*/
static int pacpi_pre_reset(struct ata_link *link, unsigned long deadline)
{
struct ata_port *ap = link->ap;
struct pata_acpi *acpi = ap->private_data;
if (ap->acpi_handle == NULL || ata_acpi_gtm(ap, &acpi->gtm) < 0)
return -ENODEV;
return ata_sff_prereset(link, deadline);
}
/**
* pacpi_cable_detect - cable type detection
* @ap: port to detect
*
* Perform device specific cable detection
*/
static int pacpi_cable_detect(struct ata_port *ap)
{
struct pata_acpi *acpi = ap->private_data;
if ((acpi->mask[0] | acpi->mask[1]) & (0xF8 << ATA_SHIFT_UDMA))
return ATA_CBL_PATA80;
else
return ATA_CBL_PATA40;
}
/**
* pacpi_discover_modes - filter non ACPI modes
* @adev: ATA device
* @mask: proposed modes
*
* Try the modes available and see which ones the ACPI method will
* set up sensibly. From this we get a mask of ACPI modes we can use
*/
static unsigned long pacpi_discover_modes(struct ata_port *ap, struct ata_device *adev)
{
struct pata_acpi *acpi = ap->private_data;
struct ata_acpi_gtm probe;
unsigned int xfer_mask;
probe = acpi->gtm;
ata_acpi_gtm(ap, &probe);
xfer_mask = ata_acpi_gtm_xfermask(adev, &probe);
if (xfer_mask & (0xF8 << ATA_SHIFT_UDMA))
ap->cbl = ATA_CBL_PATA80;
return xfer_mask;
}
/**
* pacpi_mode_filter - mode filter for ACPI
* @adev: device
* @mask: mask of valid modes
*
* Filter the valid mode list according to our own specific rules, in
* this case the list of discovered valid modes obtained by ACPI probing
*/
static unsigned long pacpi_mode_filter(struct ata_device *adev, unsigned long mask)
{
struct pata_acpi *acpi = adev->link->ap->private_data;
return mask & acpi->mask[adev->devno];
}
/**
* pacpi_set_piomode - set initial PIO mode data
* @ap: ATA interface
* @adev: ATA device
*/
static void pacpi_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
int unit = adev->devno;
struct pata_acpi *acpi = ap->private_data;
const struct ata_timing *t;
if (!(acpi->gtm.flags & 0x10))
unit = 0;
/* Now stuff the nS values into the structure */
t = ata_timing_find_mode(adev->pio_mode);
acpi->gtm.drive[unit].pio = t->cycle;
ata_acpi_stm(ap, &acpi->gtm);
/* See what mode we actually got */
ata_acpi_gtm(ap, &acpi->gtm);
}
/**
* pacpi_set_dmamode - set initial DMA mode data
* @ap: ATA interface
* @adev: ATA device
*/
static void pacpi_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
int unit = adev->devno;
struct pata_acpi *acpi = ap->private_data;
const struct ata_timing *t;
if (!(acpi->gtm.flags & 0x10))
unit = 0;
/* Now stuff the nS values into the structure */
t = ata_timing_find_mode(adev->dma_mode);
if (adev->dma_mode >= XFER_UDMA_0) {
acpi->gtm.drive[unit].dma = t->udma;
acpi->gtm.flags |= (1 << (2 * unit));
} else {
acpi->gtm.drive[unit].dma = t->cycle;
acpi->gtm.flags &= ~(1 << (2 * unit));
}
ata_acpi_stm(ap, &acpi->gtm);
/* See what mode we actually got */
ata_acpi_gtm(ap, &acpi->gtm);
}
/**
* pacpi_qc_issue - command issue
* @qc: command pending
*
* Called when the libata layer is about to issue a command. We wrap
* this interface so that we can load the correct ATA timings if
* necessary.
*/
static unsigned int pacpi_qc_issue(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_device *adev = qc->dev;
struct pata_acpi *acpi = ap->private_data;
if (acpi->gtm.flags & 0x10)
return ata_bmdma_qc_issue(qc);
if (adev != acpi->last) {
pacpi_set_piomode(ap, adev);
if (ata_dma_enabled(adev))
pacpi_set_dmamode(ap, adev);
acpi->last = adev;
}
return ata_bmdma_qc_issue(qc);
}
/**
* pacpi_port_start - port setup
* @ap: ATA port being set up
*
* Use the port_start hook to maintain private control structures
*/
static int pacpi_port_start(struct ata_port *ap)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
struct pata_acpi *acpi;
if (ap->acpi_handle == NULL)
return -ENODEV;
acpi = ap->private_data = devm_kzalloc(&pdev->dev, sizeof(struct pata_acpi), GFP_KERNEL);
if (ap->private_data == NULL)
return -ENOMEM;
acpi->mask[0] = pacpi_discover_modes(ap, &ap->link.device[0]);
acpi->mask[1] = pacpi_discover_modes(ap, &ap->link.device[1]);
return ata_bmdma_port_start(ap);
}
static struct scsi_host_template pacpi_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
static struct ata_port_operations pacpi_ops = {
.inherits = &ata_bmdma_port_ops,
.qc_issue = pacpi_qc_issue,
.cable_detect = pacpi_cable_detect,
.mode_filter = pacpi_mode_filter,
.set_piomode = pacpi_set_piomode,
.set_dmamode = pacpi_set_dmamode,
.prereset = pacpi_pre_reset,
.port_start = pacpi_port_start,
};
/**
* pacpi_init_one - Register ACPI ATA PCI device with kernel services
* @pdev: PCI device to register
* @ent: Entry in pacpi_pci_tbl matching with @pdev
*
* Called from kernel PCI layer.
*
* LOCKING:
* Inherited from PCI layer (may sleep).
*
* RETURNS:
* Zero on success, or -ERRNO value.
*/
static int pacpi_init_one (struct pci_dev *pdev, const struct pci_device_id *id)
{
static const struct ata_port_info info = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA6,
.port_ops = &pacpi_ops,
};
const struct ata_port_info *ppi[] = { &info, NULL };
if (pdev->vendor == PCI_VENDOR_ID_ATI) {
int rc = pcim_enable_device(pdev);
if (rc < 0)
return rc;
pcim_pin_device(pdev);
}
return ata_pci_bmdma_init_one(pdev, ppi, &pacpi_sht, NULL, 0);
}
static const struct pci_device_id pacpi_pci_tbl[] = {
{ PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_STORAGE_IDE << 8, 0xFFFFFF00UL, 1},
{ } /* terminate list */
};
static struct pci_driver pacpi_pci_driver = {
.name = DRV_NAME,
.id_table = pacpi_pci_tbl,
.probe = pacpi_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM
.suspend = ata_pci_device_suspend,
.resume = ata_pci_device_resume,
#endif
};
static int __init pacpi_init(void)
{
return pci_register_driver(&pacpi_pci_driver);
}
static void __exit pacpi_exit(void)
{
pci_unregister_driver(&pacpi_pci_driver);
}
module_init(pacpi_init);
module_exit(pacpi_exit);
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("SCSI low-level driver for ATA in ACPI mode");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, pacpi_pci_tbl);
MODULE_VERSION(DRV_VERSION);
| gpl-2.0 |
mgbotoe/GT-I8552-kernel-source | drivers/ata/pata_netcell.c | 5502 | 2870 | /*
* pata_netcell.c - Netcell PATA driver
*
* (c) 2006 Red Hat
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#include <linux/ata.h>
#define DRV_NAME "pata_netcell"
#define DRV_VERSION "0.1.7"
/* No PIO or DMA methods needed for this device */
static unsigned int netcell_read_id(struct ata_device *adev,
struct ata_taskfile *tf, u16 *id)
{
unsigned int err_mask = ata_do_dev_read_id(adev, tf, id);
/* Firmware forgets to mark words 85-87 valid */
if (err_mask == 0)
id[ATA_ID_CSF_DEFAULT] |= 0x4000;
return err_mask;
}
static struct scsi_host_template netcell_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
static struct ata_port_operations netcell_ops = {
.inherits = &ata_bmdma_port_ops,
.cable_detect = ata_cable_80wire,
.read_id = netcell_read_id,
};
/**
* netcell_init_one - Register Netcell ATA PCI device with kernel services
* @pdev: PCI device to register
* @ent: Entry in netcell_pci_tbl matching with @pdev
*
* Called from kernel PCI layer.
*
* LOCKING:
* Inherited from PCI layer (may sleep).
*
* RETURNS:
* Zero on success, or -ERRNO value.
*/
static int netcell_init_one (struct pci_dev *pdev, const struct pci_device_id *ent)
{
static const struct ata_port_info info = {
.flags = ATA_FLAG_SLAVE_POSS,
/* Actually we don't really care about these as the
firmware deals with it */
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5, /* UDMA 133 */
.port_ops = &netcell_ops,
};
const struct ata_port_info *port_info[] = { &info, NULL };
int rc;
ata_print_version_once(&pdev->dev, DRV_VERSION);
rc = pcim_enable_device(pdev);
if (rc)
return rc;
/* Any chip specific setup/optimisation/messages here */
ata_pci_bmdma_clear_simplex(pdev);
/* And let the library code do the work */
return ata_pci_bmdma_init_one(pdev, port_info, &netcell_sht, NULL, 0);
}
static const struct pci_device_id netcell_pci_tbl[] = {
{ PCI_VDEVICE(NETCELL, PCI_DEVICE_ID_REVOLUTION), },
{ } /* terminate list */
};
static struct pci_driver netcell_pci_driver = {
.name = DRV_NAME,
.id_table = netcell_pci_tbl,
.probe = netcell_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM
.suspend = ata_pci_device_suspend,
.resume = ata_pci_device_resume,
#endif
};
static int __init netcell_init(void)
{
return pci_register_driver(&netcell_pci_driver);
}
static void __exit netcell_exit(void)
{
pci_unregister_driver(&netcell_pci_driver);
}
module_init(netcell_init);
module_exit(netcell_exit);
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("SCSI low-level driver for Netcell PATA RAID");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, netcell_pci_tbl);
MODULE_VERSION(DRV_VERSION);
| gpl-2.0 |
Vegaviet-DevTeam/Kernel_N4_N910SLK | net/ipv4/xfrm4_mode_beet.c | 9342 | 3780 | /*
* xfrm4_mode_beet.c - BEET mode encapsulation for IPv4.
*
* Copyright (c) 2006 Diego Beltrami <diego.beltrami@gmail.com>
* Miika Komu <miika@iki.fi>
* Herbert Xu <herbert@gondor.apana.org.au>
* Abhinav Pathak <abhinav.pathak@hiit.fi>
* Jeff Ahrenholz <ahrenholz@gmail.com>
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/stringify.h>
#include <net/dst.h>
#include <net/ip.h>
#include <net/xfrm.h>
static void xfrm4_beet_make_header(struct sk_buff *skb)
{
struct iphdr *iph = ip_hdr(skb);
iph->ihl = 5;
iph->version = 4;
iph->protocol = XFRM_MODE_SKB_CB(skb)->protocol;
iph->tos = XFRM_MODE_SKB_CB(skb)->tos;
iph->id = XFRM_MODE_SKB_CB(skb)->id;
iph->frag_off = XFRM_MODE_SKB_CB(skb)->frag_off;
iph->ttl = XFRM_MODE_SKB_CB(skb)->ttl;
}
/* Add encapsulation header.
*
* The top IP header will be constructed per draft-nikander-esp-beet-mode-06.txt.
*/
static int xfrm4_beet_output(struct xfrm_state *x, struct sk_buff *skb)
{
struct ip_beet_phdr *ph;
struct iphdr *top_iph;
int hdrlen, optlen;
hdrlen = 0;
optlen = XFRM_MODE_SKB_CB(skb)->optlen;
if (unlikely(optlen))
hdrlen += IPV4_BEET_PHMAXLEN - (optlen & 4);
skb_set_network_header(skb, -x->props.header_len -
hdrlen + (XFRM_MODE_SKB_CB(skb)->ihl - sizeof(*top_iph)));
if (x->sel.family != AF_INET6)
skb->network_header += IPV4_BEET_PHMAXLEN;
skb->mac_header = skb->network_header +
offsetof(struct iphdr, protocol);
skb->transport_header = skb->network_header + sizeof(*top_iph);
xfrm4_beet_make_header(skb);
ph = (struct ip_beet_phdr *)
__skb_pull(skb, XFRM_MODE_SKB_CB(skb)->ihl - hdrlen);
top_iph = ip_hdr(skb);
if (unlikely(optlen)) {
BUG_ON(optlen < 0);
ph->padlen = 4 - (optlen & 4);
ph->hdrlen = optlen / 8;
ph->nexthdr = top_iph->protocol;
if (ph->padlen)
memset(ph + 1, IPOPT_NOP, ph->padlen);
top_iph->protocol = IPPROTO_BEETPH;
top_iph->ihl = sizeof(struct iphdr) / 4;
}
top_iph->saddr = x->props.saddr.a4;
top_iph->daddr = x->id.daddr.a4;
return 0;
}
static int xfrm4_beet_input(struct xfrm_state *x, struct sk_buff *skb)
{
struct iphdr *iph;
int optlen = 0;
int err = -EINVAL;
if (unlikely(XFRM_MODE_SKB_CB(skb)->protocol == IPPROTO_BEETPH)) {
struct ip_beet_phdr *ph;
int phlen;
if (!pskb_may_pull(skb, sizeof(*ph)))
goto out;
ph = (struct ip_beet_phdr *)skb->data;
phlen = sizeof(*ph) + ph->padlen;
optlen = ph->hdrlen * 8 + (IPV4_BEET_PHMAXLEN - phlen);
if (optlen < 0 || optlen & 3 || optlen > 250)
goto out;
XFRM_MODE_SKB_CB(skb)->protocol = ph->nexthdr;
if (!pskb_may_pull(skb, phlen))
goto out;
__skb_pull(skb, phlen);
}
skb_push(skb, sizeof(*iph));
skb_reset_network_header(skb);
skb_mac_header_rebuild(skb);
xfrm4_beet_make_header(skb);
iph = ip_hdr(skb);
iph->ihl += optlen / 4;
iph->tot_len = htons(skb->len);
iph->daddr = x->sel.daddr.a4;
iph->saddr = x->sel.saddr.a4;
iph->check = 0;
iph->check = ip_fast_csum(skb_network_header(skb), iph->ihl);
err = 0;
out:
return err;
}
static struct xfrm_mode xfrm4_beet_mode = {
.input2 = xfrm4_beet_input,
.input = xfrm_prepare_input,
.output2 = xfrm4_beet_output,
.output = xfrm4_prepare_output,
.owner = THIS_MODULE,
.encap = XFRM_MODE_BEET,
.flags = XFRM_MODE_FLAG_TUNNEL,
};
static int __init xfrm4_beet_init(void)
{
return xfrm_register_mode(&xfrm4_beet_mode, AF_INET);
}
static void __exit xfrm4_beet_exit(void)
{
int err;
err = xfrm_unregister_mode(&xfrm4_beet_mode, AF_INET);
BUG_ON(err);
}
module_init(xfrm4_beet_init);
module_exit(xfrm4_beet_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_XFRM_MODE(AF_INET, XFRM_MODE_BEET);
| gpl-2.0 |
Al3XKOoL/tmp | arch/mips/math-emu/dp_fint.c | 10366 | 1906 | /* IEEE754 floating point arithmetic
* double precision: common utilities
*/
/*
* MIPS floating point support
* Copyright (C) 1994-2000 Algorithmics Ltd.
*
* ########################################################################
*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*
* ########################################################################
*/
#include "ieee754dp.h"
ieee754dp ieee754dp_fint(int x)
{
u64 xm;
int xe;
int xs;
CLEARCX;
if (x == 0)
return ieee754dp_zero(0);
if (x == 1 || x == -1)
return ieee754dp_one(x < 0);
if (x == 10 || x == -10)
return ieee754dp_ten(x < 0);
xs = (x < 0);
if (xs) {
if (x == (1 << 31))
xm = ((unsigned) 1 << 31); /* max neg can't be safely negated */
else
xm = -x;
} else {
xm = x;
}
#if 1
/* normalize - result can never be inexact or overflow */
xe = DP_MBITS;
while ((xm >> DP_MBITS) == 0) {
xm <<= 1;
xe--;
}
return builddp(xs, xe + DP_EBIAS, xm & ~DP_HIDDEN_BIT);
#else
/* normalize */
xe = DP_MBITS + 3;
while ((xm >> (DP_MBITS + 3)) == 0) {
xm <<= 1;
xe--;
}
DPNORMRET1(xs, xe, xm, "fint", x);
#endif
}
ieee754dp ieee754dp_funs(unsigned int u)
{
if ((int) u < 0)
return ieee754dp_add(ieee754dp_1e31(),
ieee754dp_fint(u & ~(1 << 31)));
return ieee754dp_fint(u);
}
| gpl-2.0 |
AOSPERIA/android_kernel_sony | arch/um/drivers/stderr_console.c | 14206 | 1683 | #include <linux/kernel.h>
#include <linux/init.h>
#include <linux/console.h>
#include "chan_user.h"
/* ----------------------------------------------------------------------------- */
/* trivial console driver -- simply dump everything to stderr */
/*
* Don't register by default -- as this registers very early in the
* boot process it becomes the default console.
*
* Initialized at init time.
*/
static int use_stderr_console = 0;
static void stderr_console_write(struct console *console, const char *string,
unsigned len)
{
generic_write(2 /* stderr */, string, len, NULL);
}
static struct console stderr_console = {
.name = "stderr",
.write = stderr_console_write,
.flags = CON_PRINTBUFFER,
};
static int __init stderr_console_init(void)
{
if (use_stderr_console)
register_console(&stderr_console);
return 0;
}
console_initcall(stderr_console_init);
static int stderr_setup(char *str)
{
if (!str)
return 0;
use_stderr_console = simple_strtoul(str,&str,0);
return 1;
}
__setup("stderr=", stderr_setup);
/* The previous behavior of not unregistering led to /dev/console being
* impossible to open. My FC5 filesystem started having init die, and the
* system panicing because of this. Unregistering causes the real
* console to become the default console, and /dev/console can then be
* opened. Making this an initcall makes this happen late enough that
* there is no added value in dumping everything to stderr, and the
* normal console is good enough to show you all available output.
*/
static int __init unregister_stderr(void)
{
unregister_console(&stderr_console);
return 0;
}
__initcall(unregister_stderr);
| gpl-2.0 |
vishnuavula/ntb | drivers/of/address.c | 127 | 25416 |
#include <linux/device.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/module.h>
#include <linux/of_address.h>
#include <linux/pci_regs.h>
#include <linux/sizes.h>
#include <linux/slab.h>
#include <linux/string.h>
/* Max address size we deal with */
#define OF_MAX_ADDR_CELLS 4
#define OF_CHECK_ADDR_COUNT(na) ((na) > 0 && (na) <= OF_MAX_ADDR_CELLS)
#define OF_CHECK_COUNTS(na, ns) (OF_CHECK_ADDR_COUNT(na) && (ns) > 0)
static struct of_bus *of_match_bus(struct device_node *np);
static int __of_address_to_resource(struct device_node *dev,
const __be32 *addrp, u64 size, unsigned int flags,
const char *name, struct resource *r);
/* Debug utility */
#ifdef DEBUG
static void of_dump_addr(const char *s, const __be32 *addr, int na)
{
printk(KERN_DEBUG "%s", s);
while (na--)
printk(" %08x", be32_to_cpu(*(addr++)));
printk("\n");
}
#else
static void of_dump_addr(const char *s, const __be32 *addr, int na) { }
#endif
/* Callbacks for bus specific translators */
struct of_bus {
const char *name;
const char *addresses;
int (*match)(struct device_node *parent);
void (*count_cells)(struct device_node *child,
int *addrc, int *sizec);
u64 (*map)(__be32 *addr, const __be32 *range,
int na, int ns, int pna);
int (*translate)(__be32 *addr, u64 offset, int na);
unsigned int (*get_flags)(const __be32 *addr);
};
/*
* Default translator (generic bus)
*/
static void of_bus_default_count_cells(struct device_node *dev,
int *addrc, int *sizec)
{
if (addrc)
*addrc = of_n_addr_cells(dev);
if (sizec)
*sizec = of_n_size_cells(dev);
}
static u64 of_bus_default_map(__be32 *addr, const __be32 *range,
int na, int ns, int pna)
{
u64 cp, s, da;
cp = of_read_number(range, na);
s = of_read_number(range + na + pna, ns);
da = of_read_number(addr, na);
pr_debug("OF: default map, cp=%llx, s=%llx, da=%llx\n",
(unsigned long long)cp, (unsigned long long)s,
(unsigned long long)da);
if (da < cp || da >= (cp + s))
return OF_BAD_ADDR;
return da - cp;
}
static int of_bus_default_translate(__be32 *addr, u64 offset, int na)
{
u64 a = of_read_number(addr, na);
memset(addr, 0, na * 4);
a += offset;
if (na > 1)
addr[na - 2] = cpu_to_be32(a >> 32);
addr[na - 1] = cpu_to_be32(a & 0xffffffffu);
return 0;
}
static unsigned int of_bus_default_get_flags(const __be32 *addr)
{
return IORESOURCE_MEM;
}
#ifdef CONFIG_OF_ADDRESS_PCI
/*
* PCI bus specific translator
*/
static int of_bus_pci_match(struct device_node *np)
{
/*
* "pciex" is PCI Express
* "vci" is for the /chaos bridge on 1st-gen PCI powermacs
* "ht" is hypertransport
*/
return !strcmp(np->type, "pci") || !strcmp(np->type, "pciex") ||
!strcmp(np->type, "vci") || !strcmp(np->type, "ht");
}
static void of_bus_pci_count_cells(struct device_node *np,
int *addrc, int *sizec)
{
if (addrc)
*addrc = 3;
if (sizec)
*sizec = 2;
}
static unsigned int of_bus_pci_get_flags(const __be32 *addr)
{
unsigned int flags = 0;
u32 w = be32_to_cpup(addr);
switch((w >> 24) & 0x03) {
case 0x01:
flags |= IORESOURCE_IO;
break;
case 0x02: /* 32 bits */
case 0x03: /* 64 bits */
flags |= IORESOURCE_MEM;
break;
}
if (w & 0x40000000)
flags |= IORESOURCE_PREFETCH;
return flags;
}
static u64 of_bus_pci_map(__be32 *addr, const __be32 *range, int na, int ns,
int pna)
{
u64 cp, s, da;
unsigned int af, rf;
af = of_bus_pci_get_flags(addr);
rf = of_bus_pci_get_flags(range);
/* Check address type match */
if ((af ^ rf) & (IORESOURCE_MEM | IORESOURCE_IO))
return OF_BAD_ADDR;
/* Read address values, skipping high cell */
cp = of_read_number(range + 1, na - 1);
s = of_read_number(range + na + pna, ns);
da = of_read_number(addr + 1, na - 1);
pr_debug("OF: PCI map, cp=%llx, s=%llx, da=%llx\n",
(unsigned long long)cp, (unsigned long long)s,
(unsigned long long)da);
if (da < cp || da >= (cp + s))
return OF_BAD_ADDR;
return da - cp;
}
static int of_bus_pci_translate(__be32 *addr, u64 offset, int na)
{
return of_bus_default_translate(addr + 1, offset, na - 1);
}
#endif /* CONFIG_OF_ADDRESS_PCI */
#ifdef CONFIG_PCI
const __be32 *of_get_pci_address(struct device_node *dev, int bar_no, u64 *size,
unsigned int *flags)
{
const __be32 *prop;
unsigned int psize;
struct device_node *parent;
struct of_bus *bus;
int onesize, i, na, ns;
/* Get parent & match bus type */
parent = of_get_parent(dev);
if (parent == NULL)
return NULL;
bus = of_match_bus(parent);
if (strcmp(bus->name, "pci")) {
of_node_put(parent);
return NULL;
}
bus->count_cells(dev, &na, &ns);
of_node_put(parent);
if (!OF_CHECK_ADDR_COUNT(na))
return NULL;
/* Get "reg" or "assigned-addresses" property */
prop = of_get_property(dev, bus->addresses, &psize);
if (prop == NULL)
return NULL;
psize /= 4;
onesize = na + ns;
for (i = 0; psize >= onesize; psize -= onesize, prop += onesize, i++) {
u32 val = be32_to_cpu(prop[0]);
if ((val & 0xff) == ((bar_no * 4) + PCI_BASE_ADDRESS_0)) {
if (size)
*size = of_read_number(prop + na, ns);
if (flags)
*flags = bus->get_flags(prop);
return prop;
}
}
return NULL;
}
EXPORT_SYMBOL(of_get_pci_address);
int of_pci_address_to_resource(struct device_node *dev, int bar,
struct resource *r)
{
const __be32 *addrp;
u64 size;
unsigned int flags;
addrp = of_get_pci_address(dev, bar, &size, &flags);
if (addrp == NULL)
return -EINVAL;
return __of_address_to_resource(dev, addrp, size, flags, NULL, r);
}
EXPORT_SYMBOL_GPL(of_pci_address_to_resource);
int of_pci_range_parser_init(struct of_pci_range_parser *parser,
struct device_node *node)
{
const int na = 3, ns = 2;
int rlen;
parser->node = node;
parser->pna = of_n_addr_cells(node);
parser->np = parser->pna + na + ns;
parser->range = of_get_property(node, "ranges", &rlen);
if (parser->range == NULL)
return -ENOENT;
parser->end = parser->range + rlen / sizeof(__be32);
return 0;
}
EXPORT_SYMBOL_GPL(of_pci_range_parser_init);
struct of_pci_range *of_pci_range_parser_one(struct of_pci_range_parser *parser,
struct of_pci_range *range)
{
const int na = 3, ns = 2;
if (!range)
return NULL;
if (!parser->range || parser->range + parser->np > parser->end)
return NULL;
range->pci_space = parser->range[0];
range->flags = of_bus_pci_get_flags(parser->range);
range->pci_addr = of_read_number(parser->range + 1, ns);
range->cpu_addr = of_translate_address(parser->node,
parser->range + na);
range->size = of_read_number(parser->range + parser->pna + na, ns);
parser->range += parser->np;
/* Now consume following elements while they are contiguous */
while (parser->range + parser->np <= parser->end) {
u32 flags, pci_space;
u64 pci_addr, cpu_addr, size;
pci_space = be32_to_cpup(parser->range);
flags = of_bus_pci_get_flags(parser->range);
pci_addr = of_read_number(parser->range + 1, ns);
cpu_addr = of_translate_address(parser->node,
parser->range + na);
size = of_read_number(parser->range + parser->pna + na, ns);
if (flags != range->flags)
break;
if (pci_addr != range->pci_addr + range->size ||
cpu_addr != range->cpu_addr + range->size)
break;
range->size += size;
parser->range += parser->np;
}
return range;
}
EXPORT_SYMBOL_GPL(of_pci_range_parser_one);
/*
* of_pci_range_to_resource - Create a resource from an of_pci_range
* @range: the PCI range that describes the resource
* @np: device node where the range belongs to
* @res: pointer to a valid resource that will be updated to
* reflect the values contained in the range.
*
* Returns EINVAL if the range cannot be converted to resource.
*
* Note that if the range is an IO range, the resource will be converted
* using pci_address_to_pio() which can fail if it is called too early or
* if the range cannot be matched to any host bridge IO space (our case here).
* To guard against that we try to register the IO range first.
* If that fails we know that pci_address_to_pio() will do too.
*/
int of_pci_range_to_resource(struct of_pci_range *range,
struct device_node *np, struct resource *res)
{
int err;
res->flags = range->flags;
res->parent = res->child = res->sibling = NULL;
res->name = np->full_name;
if (res->flags & IORESOURCE_IO) {
unsigned long port;
err = pci_register_io_range(range->cpu_addr, range->size);
if (err)
goto invalid_range;
port = pci_address_to_pio(range->cpu_addr);
if (port == (unsigned long)-1) {
err = -EINVAL;
goto invalid_range;
}
res->start = port;
} else {
res->start = range->cpu_addr;
}
res->end = res->start + range->size - 1;
return 0;
invalid_range:
res->start = (resource_size_t)OF_BAD_ADDR;
res->end = (resource_size_t)OF_BAD_ADDR;
return err;
}
#endif /* CONFIG_PCI */
/*
* ISA bus specific translator
*/
static int of_bus_isa_match(struct device_node *np)
{
return !strcmp(np->name, "isa");
}
static void of_bus_isa_count_cells(struct device_node *child,
int *addrc, int *sizec)
{
if (addrc)
*addrc = 2;
if (sizec)
*sizec = 1;
}
static u64 of_bus_isa_map(__be32 *addr, const __be32 *range, int na, int ns,
int pna)
{
u64 cp, s, da;
/* Check address type match */
if ((addr[0] ^ range[0]) & cpu_to_be32(1))
return OF_BAD_ADDR;
/* Read address values, skipping high cell */
cp = of_read_number(range + 1, na - 1);
s = of_read_number(range + na + pna, ns);
da = of_read_number(addr + 1, na - 1);
pr_debug("OF: ISA map, cp=%llx, s=%llx, da=%llx\n",
(unsigned long long)cp, (unsigned long long)s,
(unsigned long long)da);
if (da < cp || da >= (cp + s))
return OF_BAD_ADDR;
return da - cp;
}
static int of_bus_isa_translate(__be32 *addr, u64 offset, int na)
{
return of_bus_default_translate(addr + 1, offset, na - 1);
}
static unsigned int of_bus_isa_get_flags(const __be32 *addr)
{
unsigned int flags = 0;
u32 w = be32_to_cpup(addr);
if (w & 1)
flags |= IORESOURCE_IO;
else
flags |= IORESOURCE_MEM;
return flags;
}
/*
* Array of bus specific translators
*/
static struct of_bus of_busses[] = {
#ifdef CONFIG_OF_ADDRESS_PCI
/* PCI */
{
.name = "pci",
.addresses = "assigned-addresses",
.match = of_bus_pci_match,
.count_cells = of_bus_pci_count_cells,
.map = of_bus_pci_map,
.translate = of_bus_pci_translate,
.get_flags = of_bus_pci_get_flags,
},
#endif /* CONFIG_OF_ADDRESS_PCI */
/* ISA */
{
.name = "isa",
.addresses = "reg",
.match = of_bus_isa_match,
.count_cells = of_bus_isa_count_cells,
.map = of_bus_isa_map,
.translate = of_bus_isa_translate,
.get_flags = of_bus_isa_get_flags,
},
/* Default */
{
.name = "default",
.addresses = "reg",
.match = NULL,
.count_cells = of_bus_default_count_cells,
.map = of_bus_default_map,
.translate = of_bus_default_translate,
.get_flags = of_bus_default_get_flags,
},
};
static struct of_bus *of_match_bus(struct device_node *np)
{
int i;
for (i = 0; i < ARRAY_SIZE(of_busses); i++)
if (!of_busses[i].match || of_busses[i].match(np))
return &of_busses[i];
BUG();
return NULL;
}
static int of_empty_ranges_quirk(void)
{
if (IS_ENABLED(CONFIG_PPC)) {
/* To save cycles, we cache the result */
static int quirk_state = -1;
if (quirk_state < 0)
quirk_state =
of_machine_is_compatible("Power Macintosh") ||
of_machine_is_compatible("MacRISC");
return quirk_state;
}
return false;
}
static int of_translate_one(struct device_node *parent, struct of_bus *bus,
struct of_bus *pbus, __be32 *addr,
int na, int ns, int pna, const char *rprop)
{
const __be32 *ranges;
unsigned int rlen;
int rone;
u64 offset = OF_BAD_ADDR;
/* Normally, an absence of a "ranges" property means we are
* crossing a non-translatable boundary, and thus the addresses
* below the current not cannot be converted to CPU physical ones.
* Unfortunately, while this is very clear in the spec, it's not
* what Apple understood, and they do have things like /uni-n or
* /ht nodes with no "ranges" property and a lot of perfectly
* useable mapped devices below them. Thus we treat the absence of
* "ranges" as equivalent to an empty "ranges" property which means
* a 1:1 translation at that level. It's up to the caller not to try
* to translate addresses that aren't supposed to be translated in
* the first place. --BenH.
*
* As far as we know, this damage only exists on Apple machines, so
* This code is only enabled on powerpc. --gcl
*/
ranges = of_get_property(parent, rprop, &rlen);
if (ranges == NULL && !of_empty_ranges_quirk()) {
pr_debug("OF: no ranges; cannot translate\n");
return 1;
}
if (ranges == NULL || rlen == 0) {
offset = of_read_number(addr, na);
memset(addr, 0, pna * 4);
pr_debug("OF: empty ranges; 1:1 translation\n");
goto finish;
}
pr_debug("OF: walking ranges...\n");
/* Now walk through the ranges */
rlen /= 4;
rone = na + pna + ns;
for (; rlen >= rone; rlen -= rone, ranges += rone) {
offset = bus->map(addr, ranges, na, ns, pna);
if (offset != OF_BAD_ADDR)
break;
}
if (offset == OF_BAD_ADDR) {
pr_debug("OF: not found !\n");
return 1;
}
memcpy(addr, ranges + na, 4 * pna);
finish:
of_dump_addr("OF: parent translation for:", addr, pna);
pr_debug("OF: with offset: %llx\n", (unsigned long long)offset);
/* Translate it into parent bus space */
return pbus->translate(addr, offset, pna);
}
/*
* Translate an address from the device-tree into a CPU physical address,
* this walks up the tree and applies the various bus mappings on the
* way.
*
* Note: We consider that crossing any level with #size-cells == 0 to mean
* that translation is impossible (that is we are not dealing with a value
* that can be mapped to a cpu physical address). This is not really specified
* that way, but this is traditionally the way IBM at least do things
*/
static u64 __of_translate_address(struct device_node *dev,
const __be32 *in_addr, const char *rprop)
{
struct device_node *parent = NULL;
struct of_bus *bus, *pbus;
__be32 addr[OF_MAX_ADDR_CELLS];
int na, ns, pna, pns;
u64 result = OF_BAD_ADDR;
pr_debug("OF: ** translation for device %s **\n", of_node_full_name(dev));
/* Increase refcount at current level */
of_node_get(dev);
/* Get parent & match bus type */
parent = of_get_parent(dev);
if (parent == NULL)
goto bail;
bus = of_match_bus(parent);
/* Count address cells & copy address locally */
bus->count_cells(dev, &na, &ns);
if (!OF_CHECK_COUNTS(na, ns)) {
pr_debug("OF: Bad cell count for %s\n", of_node_full_name(dev));
goto bail;
}
memcpy(addr, in_addr, na * 4);
pr_debug("OF: bus is %s (na=%d, ns=%d) on %s\n",
bus->name, na, ns, of_node_full_name(parent));
of_dump_addr("OF: translating address:", addr, na);
/* Translate */
for (;;) {
/* Switch to parent bus */
of_node_put(dev);
dev = parent;
parent = of_get_parent(dev);
/* If root, we have finished */
if (parent == NULL) {
pr_debug("OF: reached root node\n");
result = of_read_number(addr, na);
break;
}
/* Get new parent bus and counts */
pbus = of_match_bus(parent);
pbus->count_cells(dev, &pna, &pns);
if (!OF_CHECK_COUNTS(pna, pns)) {
printk(KERN_ERR "prom_parse: Bad cell count for %s\n",
of_node_full_name(dev));
break;
}
pr_debug("OF: parent bus is %s (na=%d, ns=%d) on %s\n",
pbus->name, pna, pns, of_node_full_name(parent));
/* Apply bus translation */
if (of_translate_one(dev, bus, pbus, addr, na, ns, pna, rprop))
break;
/* Complete the move up one level */
na = pna;
ns = pns;
bus = pbus;
of_dump_addr("OF: one level translation:", addr, na);
}
bail:
of_node_put(parent);
of_node_put(dev);
return result;
}
u64 of_translate_address(struct device_node *dev, const __be32 *in_addr)
{
return __of_translate_address(dev, in_addr, "ranges");
}
EXPORT_SYMBOL(of_translate_address);
u64 of_translate_dma_address(struct device_node *dev, const __be32 *in_addr)
{
return __of_translate_address(dev, in_addr, "dma-ranges");
}
EXPORT_SYMBOL(of_translate_dma_address);
const __be32 *of_get_address(struct device_node *dev, int index, u64 *size,
unsigned int *flags)
{
const __be32 *prop;
unsigned int psize;
struct device_node *parent;
struct of_bus *bus;
int onesize, i, na, ns;
/* Get parent & match bus type */
parent = of_get_parent(dev);
if (parent == NULL)
return NULL;
bus = of_match_bus(parent);
bus->count_cells(dev, &na, &ns);
of_node_put(parent);
if (!OF_CHECK_ADDR_COUNT(na))
return NULL;
/* Get "reg" or "assigned-addresses" property */
prop = of_get_property(dev, bus->addresses, &psize);
if (prop == NULL)
return NULL;
psize /= 4;
onesize = na + ns;
for (i = 0; psize >= onesize; psize -= onesize, prop += onesize, i++)
if (i == index) {
if (size)
*size = of_read_number(prop + na, ns);
if (flags)
*flags = bus->get_flags(prop);
return prop;
}
return NULL;
}
EXPORT_SYMBOL(of_get_address);
#ifdef PCI_IOBASE
struct io_range {
struct list_head list;
phys_addr_t start;
resource_size_t size;
};
static LIST_HEAD(io_range_list);
static DEFINE_SPINLOCK(io_range_lock);
#endif
/*
* Record the PCI IO range (expressed as CPU physical address + size).
* Return a negative value if an error has occured, zero otherwise
*/
int __weak pci_register_io_range(phys_addr_t addr, resource_size_t size)
{
int err = 0;
#ifdef PCI_IOBASE
struct io_range *range;
resource_size_t allocated_size = 0;
/* check if the range hasn't been previously recorded */
spin_lock(&io_range_lock);
list_for_each_entry(range, &io_range_list, list) {
if (addr >= range->start && addr + size <= range->start + size) {
/* range already registered, bail out */
goto end_register;
}
allocated_size += range->size;
}
/* range not registed yet, check for available space */
if (allocated_size + size - 1 > IO_SPACE_LIMIT) {
/* if it's too big check if 64K space can be reserved */
if (allocated_size + SZ_64K - 1 > IO_SPACE_LIMIT) {
err = -E2BIG;
goto end_register;
}
size = SZ_64K;
pr_warn("Requested IO range too big, new size set to 64K\n");
}
/* add the range to the list */
range = kzalloc(sizeof(*range), GFP_KERNEL);
if (!range) {
err = -ENOMEM;
goto end_register;
}
range->start = addr;
range->size = size;
list_add_tail(&range->list, &io_range_list);
end_register:
spin_unlock(&io_range_lock);
#endif
return err;
}
phys_addr_t pci_pio_to_address(unsigned long pio)
{
phys_addr_t address = (phys_addr_t)OF_BAD_ADDR;
#ifdef PCI_IOBASE
struct io_range *range;
resource_size_t allocated_size = 0;
if (pio > IO_SPACE_LIMIT)
return address;
spin_lock(&io_range_lock);
list_for_each_entry(range, &io_range_list, list) {
if (pio >= allocated_size && pio < allocated_size + range->size) {
address = range->start + pio - allocated_size;
break;
}
allocated_size += range->size;
}
spin_unlock(&io_range_lock);
#endif
return address;
}
unsigned long __weak pci_address_to_pio(phys_addr_t address)
{
#ifdef PCI_IOBASE
struct io_range *res;
resource_size_t offset = 0;
unsigned long addr = -1;
spin_lock(&io_range_lock);
list_for_each_entry(res, &io_range_list, list) {
if (address >= res->start && address < res->start + res->size) {
addr = res->start - address + offset;
break;
}
offset += res->size;
}
spin_unlock(&io_range_lock);
return addr;
#else
if (address > IO_SPACE_LIMIT)
return (unsigned long)-1;
return (unsigned long) address;
#endif
}
static int __of_address_to_resource(struct device_node *dev,
const __be32 *addrp, u64 size, unsigned int flags,
const char *name, struct resource *r)
{
u64 taddr;
if ((flags & (IORESOURCE_IO | IORESOURCE_MEM)) == 0)
return -EINVAL;
taddr = of_translate_address(dev, addrp);
if (taddr == OF_BAD_ADDR)
return -EINVAL;
memset(r, 0, sizeof(struct resource));
if (flags & IORESOURCE_IO) {
unsigned long port;
port = pci_address_to_pio(taddr);
if (port == (unsigned long)-1)
return -EINVAL;
r->start = port;
r->end = port + size - 1;
} else {
r->start = taddr;
r->end = taddr + size - 1;
}
r->flags = flags;
r->name = name ? name : dev->full_name;
return 0;
}
/**
* of_address_to_resource - Translate device tree address and return as resource
*
* Note that if your address is a PIO address, the conversion will fail if
* the physical address can't be internally converted to an IO token with
* pci_address_to_pio(), that is because it's either called to early or it
* can't be matched to any host bridge IO space
*/
int of_address_to_resource(struct device_node *dev, int index,
struct resource *r)
{
const __be32 *addrp;
u64 size;
unsigned int flags;
const char *name = NULL;
addrp = of_get_address(dev, index, &size, &flags);
if (addrp == NULL)
return -EINVAL;
/* Get optional "reg-names" property to add a name to a resource */
of_property_read_string_index(dev, "reg-names", index, &name);
return __of_address_to_resource(dev, addrp, size, flags, name, r);
}
EXPORT_SYMBOL_GPL(of_address_to_resource);
struct device_node *of_find_matching_node_by_address(struct device_node *from,
const struct of_device_id *matches,
u64 base_address)
{
struct device_node *dn = of_find_matching_node(from, matches);
struct resource res;
while (dn) {
if (of_address_to_resource(dn, 0, &res))
continue;
if (res.start == base_address)
return dn;
dn = of_find_matching_node(dn, matches);
}
return NULL;
}
/**
* of_iomap - Maps the memory mapped IO for a given device_node
* @device: the device whose io range will be mapped
* @index: index of the io range
*
* Returns a pointer to the mapped memory
*/
void __iomem *of_iomap(struct device_node *np, int index)
{
struct resource res;
if (of_address_to_resource(np, index, &res))
return NULL;
return ioremap(res.start, resource_size(&res));
}
EXPORT_SYMBOL(of_iomap);
/*
* of_io_request_and_map - Requests a resource and maps the memory mapped IO
* for a given device_node
* @device: the device whose io range will be mapped
* @index: index of the io range
* @name: name of the resource
*
* Returns a pointer to the requested and mapped memory or an ERR_PTR() encoded
* error code on failure. Usage example:
*
* base = of_io_request_and_map(node, 0, "foo");
* if (IS_ERR(base))
* return PTR_ERR(base);
*/
void __iomem *of_io_request_and_map(struct device_node *np, int index,
const char *name)
{
struct resource res;
void __iomem *mem;
if (of_address_to_resource(np, index, &res))
return IOMEM_ERR_PTR(-EINVAL);
if (!request_mem_region(res.start, resource_size(&res), name))
return IOMEM_ERR_PTR(-EBUSY);
mem = ioremap(res.start, resource_size(&res));
if (!mem) {
release_mem_region(res.start, resource_size(&res));
return IOMEM_ERR_PTR(-ENOMEM);
}
return mem;
}
EXPORT_SYMBOL(of_io_request_and_map);
/**
* of_dma_get_range - Get DMA range info
* @np: device node to get DMA range info
* @dma_addr: pointer to store initial DMA address of DMA range
* @paddr: pointer to store initial CPU address of DMA range
* @size: pointer to store size of DMA range
*
* Look in bottom up direction for the first "dma-ranges" property
* and parse it.
* dma-ranges format:
* DMA addr (dma_addr) : naddr cells
* CPU addr (phys_addr_t) : pna cells
* size : nsize cells
*
* It returns -ENODEV if "dma-ranges" property was not found
* for this device in DT.
*/
int of_dma_get_range(struct device_node *np, u64 *dma_addr, u64 *paddr, u64 *size)
{
struct device_node *node = of_node_get(np);
const __be32 *ranges = NULL;
int len, naddr, nsize, pna;
int ret = 0;
u64 dmaaddr;
if (!node)
return -EINVAL;
while (1) {
naddr = of_n_addr_cells(node);
nsize = of_n_size_cells(node);
node = of_get_next_parent(node);
if (!node)
break;
ranges = of_get_property(node, "dma-ranges", &len);
/* Ignore empty ranges, they imply no translation required */
if (ranges && len > 0)
break;
/*
* At least empty ranges has to be defined for parent node if
* DMA is supported
*/
if (!ranges)
break;
}
if (!ranges) {
pr_debug("%s: no dma-ranges found for node(%s)\n",
__func__, np->full_name);
ret = -ENODEV;
goto out;
}
len /= sizeof(u32);
pna = of_n_addr_cells(node);
/* dma-ranges format:
* DMA addr : naddr cells
* CPU addr : pna cells
* size : nsize cells
*/
dmaaddr = of_read_number(ranges, naddr);
*paddr = of_translate_dma_address(np, ranges);
if (*paddr == OF_BAD_ADDR) {
pr_err("%s: translation of DMA address(%pad) to CPU address failed node(%s)\n",
__func__, dma_addr, np->full_name);
ret = -EINVAL;
goto out;
}
*dma_addr = dmaaddr;
*size = of_read_number(ranges + naddr + pna, nsize);
pr_debug("dma_addr(%llx) cpu_addr(%llx) size(%llx)\n",
*dma_addr, *paddr, *size);
out:
of_node_put(node);
return ret;
}
EXPORT_SYMBOL_GPL(of_dma_get_range);
/**
* of_dma_is_coherent - Check if device is coherent
* @np: device node
*
* It returns true if "dma-coherent" property was found
* for this device in DT.
*/
bool of_dma_is_coherent(struct device_node *np)
{
struct device_node *node = of_node_get(np);
while (node) {
if (of_property_read_bool(node, "dma-coherent")) {
of_node_put(node);
return true;
}
node = of_get_next_parent(node);
}
of_node_put(node);
return false;
}
EXPORT_SYMBOL_GPL(of_dma_is_coherent);
| gpl-2.0 |
Shelnutt2/android_kernel_lge_f180k | drivers/usb/gadget/u_bam_data.c | 127 | 7283 | /* Copyright (c) 2012, 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.
*/
#ifdef pr_fmt
#undef pr_fmt
#endif
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <linux/bitops.h>
#include <linux/usb/gadget.h>
#include <mach/bam_dmux.h>
#include <mach/usb_gadget_xport.h>
#include <mach/usb_bam.h>
#define BAM2BAM_DATA_N_PORTS 1
static struct workqueue_struct *bam_data_wq;
static int n_bam2bam_data_ports;
#define SPS_PARAMS_SPS_MODE BIT(5)
#define SPS_PARAMS_TBE BIT(6)
#define MSM_VENDOR_ID BIT(16)
struct data_port {
struct usb_function func;
struct usb_ep *in;
struct usb_ep *out;
};
struct bam_data_ch_info {
unsigned long flags;
unsigned id;
struct bam_data_port *port;
struct work_struct write_tobam_w;
struct usb_request *rx_req;
struct usb_request *tx_req;
u32 src_pipe_idx;
u32 dst_pipe_idx;
u8 connection_idx;
};
struct bam_data_port {
unsigned port_num;
struct data_port *port_usb;
struct bam_data_ch_info data_ch;
struct work_struct connect_w;
struct work_struct disconnect_w;
};
struct bam_data_port *bam2bam_data_ports[BAM2BAM_DATA_N_PORTS];
/*------------data_path----------------------------*/
static void bam_data_endless_rx_complete(struct usb_ep *ep,
struct usb_request *req)
{
int status = req->status;
pr_info("status: %d\n", status);
}
static void bam_data_endless_tx_complete(struct usb_ep *ep,
struct usb_request *req)
{
int status = req->status;
pr_info("status: %d\n", status);
}
static void bam_data_start_endless_rx(struct bam_data_port *port)
{
struct bam_data_ch_info *d = &port->data_ch;
int status;
status = usb_ep_queue(port->port_usb->out, d->rx_req, GFP_ATOMIC);
if (status)
pr_err("error enqueuing transfer, %d\n", status);
}
static void bam_data_start_endless_tx(struct bam_data_port *port)
{
struct bam_data_ch_info *d = &port->data_ch;
int status;
status = usb_ep_queue(port->port_usb->in, d->tx_req, GFP_ATOMIC);
if (status)
pr_err("error enqueuing transfer, %d\n", status);
}
static void bam2bam_data_disconnect_work(struct work_struct *w)
{
struct bam_data_port *port =
container_of(w, struct bam_data_port, disconnect_w);
pr_info("Enter");
/* disable endpoints */
if (!port->port_usb || !port->port_usb->out || !port->port_usb->in) {
pr_err("port_usb->out/in == NULL. Exit");
return;
}
usb_ep_disable(port->port_usb->out);
usb_ep_disable(port->port_usb->in);
port->port_usb->in->driver_data = NULL;
port->port_usb->out->driver_data = NULL;
port->port_usb = 0;
pr_info("Exit");
}
static void bam2bam_data_connect_work(struct work_struct *w)
{
struct bam_data_port *port = container_of(w, struct bam_data_port,
connect_w);
struct bam_data_ch_info *d = &port->data_ch;
u32 sps_params;
int ret;
pr_info("Enter");
ret = usb_bam_connect(d->connection_idx, &d->src_pipe_idx,
&d->dst_pipe_idx);
d->src_pipe_idx = 11;
d->dst_pipe_idx = 10;
if (ret) {
pr_err("usb_bam_connect failed: err:%d\n", ret);
return;
}
if (!port->port_usb) {
pr_err("port_usb is NULL");
return;
}
if (!port->port_usb->out) {
pr_err("port_usb->out (bulk out ep) is NULL");
return;
}
d->rx_req = usb_ep_alloc_request(port->port_usb->out, GFP_KERNEL);
if (!d->rx_req)
return;
d->rx_req->context = port;
d->rx_req->complete = bam_data_endless_rx_complete;
d->rx_req->length = 0;
sps_params = (SPS_PARAMS_SPS_MODE | d->src_pipe_idx |
MSM_VENDOR_ID) & ~SPS_PARAMS_TBE;
d->rx_req->udc_priv = sps_params;
d->tx_req = usb_ep_alloc_request(port->port_usb->in, GFP_KERNEL);
if (!d->tx_req)
return;
d->tx_req->context = port;
d->tx_req->complete = bam_data_endless_tx_complete;
d->tx_req->length = 0;
sps_params = (SPS_PARAMS_SPS_MODE | d->dst_pipe_idx |
MSM_VENDOR_ID) & ~SPS_PARAMS_TBE;
d->tx_req->udc_priv = sps_params;
/* queue in & out requests */
bam_data_start_endless_rx(port);
bam_data_start_endless_tx(port);
pr_info("Done\n");
}
static void bam2bam_data_port_free(int portno)
{
kfree(bam2bam_data_ports[portno]);
bam2bam_data_ports[portno] = NULL;
}
static int bam2bam_data_port_alloc(int portno)
{
struct bam_data_port *port = NULL;
struct bam_data_ch_info *d = NULL;
port = kzalloc(sizeof(struct bam_data_port), GFP_KERNEL);
if (!port)
return -ENOMEM;
port->port_num = portno;
INIT_WORK(&port->connect_w, bam2bam_data_connect_work);
INIT_WORK(&port->disconnect_w, bam2bam_data_disconnect_work);
/* data ch */
d = &port->data_ch;
d->port = port;
bam2bam_data_ports[portno] = port;
pr_info("port:%p portno:%d\n", port, portno);
return 0;
}
void bam_data_disconnect(struct data_port *gr, u8 port_num)
{
struct bam_data_port *port;
struct bam_data_ch_info *d;
pr_info("dev:%p port#%d\n", gr, port_num);
if (port_num >= n_bam2bam_data_ports) {
pr_err("invalid bam2bam portno#%d\n", port_num);
return;
}
if (!gr) {
pr_err("mbim data port is null\n");
return;
}
port = bam2bam_data_ports[port_num];
d = &port->data_ch;
port->port_usb = gr;
queue_work(bam_data_wq, &port->disconnect_w);
}
int bam_data_connect(struct data_port *gr, u8 port_num,
u8 connection_idx)
{
struct bam_data_port *port;
struct bam_data_ch_info *d;
int ret;
pr_info("dev:%p port#%d\n", gr, port_num);
if (port_num >= n_bam2bam_data_ports) {
pr_err("invalid portno#%d\n", port_num);
return -ENODEV;
}
if (!gr) {
pr_err("mbim data port is null\n");
return -ENODEV;
}
port = bam2bam_data_ports[port_num];
d = &port->data_ch;
ret = usb_ep_enable(gr->in);
if (ret) {
pr_err("usb_ep_enable failed eptype:IN ep:%p", gr->in);
return ret;
}
gr->in->driver_data = port;
ret = usb_ep_enable(gr->out);
if (ret) {
pr_err("usb_ep_enable failed eptype:OUT ep:%p", gr->out);
gr->in->driver_data = 0;
return ret;
}
gr->out->driver_data = port;
port->port_usb = gr;
d->connection_idx = connection_idx;
queue_work(bam_data_wq, &port->connect_w);
return 0;
}
int bam_data_setup(unsigned int no_bam2bam_port)
{
int i;
int ret;
pr_info("requested %d BAM2BAM ports", no_bam2bam_port);
if (!no_bam2bam_port || no_bam2bam_port > BAM2BAM_DATA_N_PORTS) {
pr_err("Invalid num of ports count:%d\n", no_bam2bam_port);
return -EINVAL;
}
bam_data_wq = alloc_workqueue("k_bam_data",
WQ_UNBOUND | WQ_MEM_RECLAIM, 1);
if (!bam_data_wq) {
pr_err("Failed to create workqueue\n");
return -ENOMEM;
}
for (i = 0; i < no_bam2bam_port; i++) {
n_bam2bam_data_ports++;
ret = bam2bam_data_port_alloc(i);
if (ret) {
n_bam2bam_data_ports--;
pr_err("Failed to alloc port:%d\n", i);
goto free_bam_ports;
}
}
return 0;
free_bam_ports:
for (i = 0; i < n_bam2bam_data_ports; i++)
bam2bam_data_port_free(i);
destroy_workqueue(bam_data_wq);
return ret;
}
| gpl-2.0 |
wejoncy/linux-digilent | arch/mips/pmc-sierra/yosemite/ht.c | 127 | 11983 | /*
* Copyright 2003 PMC-Sierra
* Author: Manish Lachwani (lachwani@pmc-sierra.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <asm/pci.h>
#include <asm/io.h>
#include <linux/init.h>
#include <asm/titan_dep.h>
#ifdef CONFIG_HYPERTRANSPORT
/*
* This function check if the Hypertransport Link Initialization completed. If
* it did, then proceed further with scanning bus #2
*/
static __inline__ int check_titan_htlink(void)
{
u32 val;
val = *(volatile uint32_t *)(RM9000x2_HTLINK_REG);
if (val & 0x00000020)
/* HT Link Initialization completed */
return 1;
else
return 0;
}
static int titan_ht_config_read_dword(struct pci_dev *device,
int offset, u32* val)
{
int dev, bus, func;
uint32_t address_reg, data_reg;
uint32_t address;
bus = device->bus->number;
dev = PCI_SLOT(device->devfn);
func = PCI_FUNC(device->devfn);
/* XXX Need to change the Bus # */
if (bus > 2)
address = (bus << 16) | (dev << 11) | (func << 8) | (offset & 0xfc) |
0x80000000 | 0x1;
else
address = (dev << 11) | (func << 8) | (offset & 0xfc) | 0x80000000;
address_reg = RM9000x2_OCD_HTCFGA;
data_reg = RM9000x2_OCD_HTCFGD;
RM9K_WRITE(address_reg, address);
RM9K_READ(data_reg, val);
return PCIBIOS_SUCCESSFUL;
}
static int titan_ht_config_read_word(struct pci_dev *device,
int offset, u16* val)
{
int dev, bus, func;
uint32_t address_reg, data_reg;
uint32_t address;
bus = device->bus->number;
dev = PCI_SLOT(device->devfn);
func = PCI_FUNC(device->devfn);
/* XXX Need to change the Bus # */
if (bus > 2)
address = (bus << 16) | (dev << 11) | (func << 8) | (offset & 0xfc) |
0x80000000 | 0x1;
else
address = (dev << 11) | (func << 8) | (offset & 0xfc) | 0x80000000;
address_reg = RM9000x2_OCD_HTCFGA;
data_reg = RM9000x2_OCD_HTCFGD;
if ((offset & 0x3) == 0)
offset = 0x2;
else
offset = 0x0;
RM9K_WRITE(address_reg, address);
RM9K_READ_16(data_reg + offset, val);
return PCIBIOS_SUCCESSFUL;
}
u32 longswap(unsigned long l)
{
unsigned char b1, b2, b3, b4;
b1 = l&255;
b2 = (l>>8)&255;
b3 = (l>>16)&255;
b4 = (l>>24)&255;
return ((b1<<24) + (b2<<16) + (b3<<8) + b4);
}
static int titan_ht_config_read_byte(struct pci_dev *device,
int offset, u8* val)
{
int dev, bus, func;
uint32_t address_reg, data_reg;
uint32_t address;
int offset1;
bus = device->bus->number;
dev = PCI_SLOT(device->devfn);
func = PCI_FUNC(device->devfn);
/* XXX Need to change the Bus # */
if (bus > 2)
address = (bus << 16) | (dev << 11) | (func << 8) | (offset & 0xfc) |
0x80000000 | 0x1;
else
address = (dev << 11) | (func << 8) | (offset & 0xfc) | 0x80000000;
address_reg = RM9000x2_OCD_HTCFGA;
data_reg = RM9000x2_OCD_HTCFGD;
RM9K_WRITE(address_reg, address);
if ((offset & 0x3) == 0) {
offset1 = 0x3;
}
if ((offset & 0x3) == 1) {
offset1 = 0x2;
}
if ((offset & 0x3) == 2) {
offset1 = 0x1;
}
if ((offset & 0x3) == 3) {
offset1 = 0x0;
}
RM9K_READ_8(data_reg + offset1, val);
return PCIBIOS_SUCCESSFUL;
}
static int titan_ht_config_write_dword(struct pci_dev *device,
int offset, u8 val)
{
int dev, bus, func;
uint32_t address_reg, data_reg;
uint32_t address;
bus = device->bus->number;
dev = PCI_SLOT(device->devfn);
func = PCI_FUNC(device->devfn);
/* XXX Need to change the Bus # */
if (bus > 2)
address = (bus << 16) | (dev << 11) | (func << 8) | (offset & 0xfc) |
0x80000000 | 0x1;
else
address = (dev << 11) | (func << 8) | (offset & 0xfc) | 0x80000000;
address_reg = RM9000x2_OCD_HTCFGA;
data_reg = RM9000x2_OCD_HTCFGD;
RM9K_WRITE(address_reg, address);
RM9K_WRITE(data_reg, val);
return PCIBIOS_SUCCESSFUL;
}
static int titan_ht_config_write_word(struct pci_dev *device,
int offset, u8 val)
{
int dev, bus, func;
uint32_t address_reg, data_reg;
uint32_t address;
bus = device->bus->number;
dev = PCI_SLOT(device->devfn);
func = PCI_FUNC(device->devfn);
/* XXX Need to change the Bus # */
if (bus > 2)
address = (bus << 16) | (dev << 11) | (func << 8) | (offset & 0xfc) |
0x80000000 | 0x1;
else
address = (dev << 11) | (func << 8) | (offset & 0xfc) | 0x80000000;
address_reg = RM9000x2_OCD_HTCFGA;
data_reg = RM9000x2_OCD_HTCFGD;
if ((offset & 0x3) == 0)
offset = 0x2;
else
offset = 0x0;
RM9K_WRITE(address_reg, address);
RM9K_WRITE_16(data_reg + offset, val);
return PCIBIOS_SUCCESSFUL;
}
static int titan_ht_config_write_byte(struct pci_dev *device,
int offset, u8 val)
{
int dev, bus, func;
uint32_t address_reg, data_reg;
uint32_t address;
int offset1;
bus = device->bus->number;
dev = PCI_SLOT(device->devfn);
func = PCI_FUNC(device->devfn);
/* XXX Need to change the Bus # */
if (bus > 2)
address = (bus << 16) | (dev << 11) | (func << 8) | (offset & 0xfc) |
0x80000000 | 0x1;
else
address = (dev << 11) | (func << 8) | (offset & 0xfc) | 0x80000000;
address_reg = RM9000x2_OCD_HTCFGA;
data_reg = RM9000x2_OCD_HTCFGD;
RM9K_WRITE(address_reg, address);
if ((offset & 0x3) == 0) {
offset1 = 0x3;
}
if ((offset & 0x3) == 1) {
offset1 = 0x2;
}
if ((offset & 0x3) == 2) {
offset1 = 0x1;
}
if ((offset & 0x3) == 3) {
offset1 = 0x0;
}
RM9K_WRITE_8(data_reg + offset1, val);
return PCIBIOS_SUCCESSFUL;
}
static void titan_pcibios_set_master(struct pci_dev *dev)
{
u16 cmd;
int bus = dev->bus->number;
if (check_titan_htlink())
titan_ht_config_read_word(dev, PCI_COMMAND, &cmd);
cmd |= PCI_COMMAND_MASTER;
if (check_titan_htlink())
titan_ht_config_write_word(dev, PCI_COMMAND, cmd);
}
int pcibios_enable_resources(struct pci_dev *dev)
{
u16 cmd, old_cmd;
u8 tmp1;
int idx;
struct resource *r;
int bus = dev->bus->number;
if (check_titan_htlink())
titan_ht_config_read_word(dev, PCI_COMMAND, &cmd);
old_cmd = cmd;
for (idx = 0; idx < 6; idx++) {
r = &dev->resource[idx];
if (!r->start && r->end) {
printk(KERN_ERR
"PCI: Device %s not available because of "
"resource collisions\n", pci_name(dev));
return -EINVAL;
}
if (r->flags & IORESOURCE_IO)
cmd |= PCI_COMMAND_IO;
if (r->flags & IORESOURCE_MEM)
cmd |= PCI_COMMAND_MEMORY;
}
if (cmd != old_cmd) {
if (check_titan_htlink())
titan_ht_config_write_word(dev, PCI_COMMAND, cmd);
}
if (check_titan_htlink())
titan_ht_config_read_byte(dev, PCI_CACHE_LINE_SIZE, &tmp1);
if (tmp1 != 8) {
printk(KERN_WARNING "PCI setting cache line size to 8 from "
"%d\n", tmp1);
}
if (check_titan_htlink())
titan_ht_config_write_byte(dev, PCI_CACHE_LINE_SIZE, 8);
if (check_titan_htlink())
titan_ht_config_read_byte(dev, PCI_LATENCY_TIMER, &tmp1);
if (tmp1 < 32 || tmp1 == 0xff) {
printk(KERN_WARNING "PCI setting latency timer to 32 from %d\n",
tmp1);
}
if (check_titan_htlink())
titan_ht_config_write_byte(dev, PCI_LATENCY_TIMER, 32);
return 0;
}
int pcibios_enable_device(struct pci_dev *dev, int mask)
{
return pcibios_enable_resources(dev);
}
resource_size_t pcibios_align_resource(void *data, const struct resource *res,
resource_size_t size, resource_size_t align)
{
struct pci_dev *dev = data;
resource_size_t start = res->start;
if (res->flags & IORESOURCE_IO) {
/* We need to avoid collisions with `mirrored' VGA ports
and other strange ISA hardware, so we always want the
addresses kilobyte aligned. */
if (size > 0x100) {
printk(KERN_ERR "PCI: I/O Region %s/%d too large"
" (%ld bytes)\n", pci_name(dev),
dev->resource - res, size);
}
start = (start + 1024 - 1) & ~(1024 - 1);
}
return start;
}
struct pci_ops titan_pci_ops = {
titan_ht_config_read_byte,
titan_ht_config_read_word,
titan_ht_config_read_dword,
titan_ht_config_write_byte,
titan_ht_config_write_word,
titan_ht_config_write_dword
};
void __init pcibios_fixup_bus(struct pci_bus *c)
{
titan_ht_pcibios_fixup_bus(c);
}
void __init pcibios_init(void)
{
/* Reset PCI I/O and PCI MEM values */
/* XXX Need to add the proper values here */
ioport_resource.start = 0xe0000000;
ioport_resource.end = 0xe0000000 + 0x20000000 - 1;
iomem_resource.start = 0xc0000000;
iomem_resource.end = 0xc0000000 + 0x20000000 - 1;
/* XXX Need to add bus values */
pci_scan_bus(2, &titan_pci_ops, NULL);
pci_scan_bus(3, &titan_pci_ops, NULL);
}
unsigned __init int pcibios_assign_all_busses(void)
{
/* We want to use the PCI bus detection done by PMON */
return 0;
}
#endif /* CONFIG_HYPERTRANSPORT */
| gpl-2.0 |
NamanArora/dx_kernel | net/ipv6/ip6_flowlabel.c | 383 | 17034 | /*
* ip6_flowlabel.c IPv6 flowlabel manager.
*
* 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.
*
* Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
*/
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/in6.h>
#include <linux/route.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/ipv6.h>
#include <net/ndisc.h>
#include <net/protocol.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#include <net/rawv6.h>
#include <net/icmp.h>
#include <net/transp_v6.h>
#include <asm/uaccess.h>
#define FL_MIN_LINGER 6
#define FL_MAX_LINGER 60
#define FL_MAX_PER_SOCK 32
#define FL_MAX_SIZE 4096
#define FL_HASH_MASK 255
#define FL_HASH(l) (ntohl(l)&FL_HASH_MASK)
static atomic_t fl_size = ATOMIC_INIT(0);
static struct ip6_flowlabel *fl_ht[FL_HASH_MASK+1];
static void ip6_fl_gc(unsigned long dummy);
static DEFINE_TIMER(ip6_fl_gc_timer, ip6_fl_gc, 0, 0);
static DEFINE_RWLOCK(ip6_fl_lock);
static DEFINE_RWLOCK(ip6_sk_fl_lock);
static inline struct ip6_flowlabel *__fl_lookup(struct net *net, __be32 label)
{
struct ip6_flowlabel *fl;
for (fl=fl_ht[FL_HASH(label)]; fl; fl = fl->next) {
if (fl->label == label && net_eq(fl->fl_net, net))
return fl;
}
return NULL;
}
static struct ip6_flowlabel *fl_lookup(struct net *net, __be32 label)
{
struct ip6_flowlabel *fl;
read_lock_bh(&ip6_fl_lock);
fl = __fl_lookup(net, label);
if (fl)
atomic_inc(&fl->users);
read_unlock_bh(&ip6_fl_lock);
return fl;
}
static void fl_free(struct ip6_flowlabel *fl)
{
if (fl) {
release_net(fl->fl_net);
kfree(fl->opt);
}
kfree(fl);
}
static void fl_release(struct ip6_flowlabel *fl)
{
write_lock_bh(&ip6_fl_lock);
fl->lastuse = jiffies;
if (atomic_dec_and_test(&fl->users)) {
unsigned long ttd = fl->lastuse + fl->linger;
if (time_after(ttd, fl->expires))
fl->expires = ttd;
ttd = fl->expires;
if (fl->opt && fl->share == IPV6_FL_S_EXCL) {
struct ipv6_txoptions *opt = fl->opt;
fl->opt = NULL;
kfree(opt);
}
if (!timer_pending(&ip6_fl_gc_timer) ||
time_after(ip6_fl_gc_timer.expires, ttd))
mod_timer(&ip6_fl_gc_timer, ttd);
}
write_unlock_bh(&ip6_fl_lock);
}
static void ip6_fl_gc(unsigned long dummy)
{
int i;
unsigned long now = jiffies;
unsigned long sched = 0;
write_lock(&ip6_fl_lock);
for (i=0; i<=FL_HASH_MASK; i++) {
struct ip6_flowlabel *fl, **flp;
flp = &fl_ht[i];
while ((fl=*flp) != NULL) {
if (atomic_read(&fl->users) == 0) {
unsigned long ttd = fl->lastuse + fl->linger;
if (time_after(ttd, fl->expires))
fl->expires = ttd;
ttd = fl->expires;
if (time_after_eq(now, ttd)) {
*flp = fl->next;
fl_free(fl);
atomic_dec(&fl_size);
continue;
}
if (!sched || time_before(ttd, sched))
sched = ttd;
}
flp = &fl->next;
}
}
if (!sched && atomic_read(&fl_size))
sched = now + FL_MAX_LINGER;
if (sched) {
mod_timer(&ip6_fl_gc_timer, sched);
}
write_unlock(&ip6_fl_lock);
}
static void __net_exit ip6_fl_purge(struct net *net)
{
int i;
write_lock(&ip6_fl_lock);
for (i = 0; i <= FL_HASH_MASK; i++) {
struct ip6_flowlabel *fl, **flp;
flp = &fl_ht[i];
while ((fl = *flp) != NULL) {
if (net_eq(fl->fl_net, net) &&
atomic_read(&fl->users) == 0) {
*flp = fl->next;
fl_free(fl);
atomic_dec(&fl_size);
continue;
}
flp = &fl->next;
}
}
write_unlock(&ip6_fl_lock);
}
static struct ip6_flowlabel *fl_intern(struct net *net,
struct ip6_flowlabel *fl, __be32 label)
{
struct ip6_flowlabel *lfl;
fl->label = label & IPV6_FLOWLABEL_MASK;
write_lock_bh(&ip6_fl_lock);
if (label == 0) {
for (;;) {
fl->label = htonl(net_random())&IPV6_FLOWLABEL_MASK;
if (fl->label) {
lfl = __fl_lookup(net, fl->label);
if (lfl == NULL)
break;
}
}
} else {
lfl = __fl_lookup(net, fl->label);
if (lfl != NULL) {
atomic_inc(&lfl->users);
write_unlock_bh(&ip6_fl_lock);
return lfl;
}
}
fl->lastuse = jiffies;
fl->next = fl_ht[FL_HASH(fl->label)];
fl_ht[FL_HASH(fl->label)] = fl;
atomic_inc(&fl_size);
write_unlock_bh(&ip6_fl_lock);
return NULL;
}
struct ip6_flowlabel * fl6_sock_lookup(struct sock *sk, __be32 label)
{
struct ipv6_fl_socklist *sfl;
struct ipv6_pinfo *np = inet6_sk(sk);
label &= IPV6_FLOWLABEL_MASK;
read_lock_bh(&ip6_sk_fl_lock);
for (sfl=np->ipv6_fl_list; sfl; sfl = sfl->next) {
struct ip6_flowlabel *fl = sfl->fl;
if (fl->label == label) {
fl->lastuse = jiffies;
atomic_inc(&fl->users);
read_unlock_bh(&ip6_sk_fl_lock);
return fl;
}
}
read_unlock_bh(&ip6_sk_fl_lock);
return NULL;
}
EXPORT_SYMBOL_GPL(fl6_sock_lookup);
void fl6_free_socklist(struct sock *sk)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6_fl_socklist *sfl;
while ((sfl = np->ipv6_fl_list) != NULL) {
np->ipv6_fl_list = sfl->next;
fl_release(sfl->fl);
kfree(sfl);
}
}
struct ipv6_txoptions *fl6_merge_options(struct ipv6_txoptions * opt_space,
struct ip6_flowlabel * fl,
struct ipv6_txoptions * fopt)
{
struct ipv6_txoptions * fl_opt = fl->opt;
if (fopt == NULL || fopt->opt_flen == 0)
return fl_opt;
if (fl_opt != NULL) {
opt_space->hopopt = fl_opt->hopopt;
opt_space->dst0opt = fl_opt->dst0opt;
opt_space->srcrt = fl_opt->srcrt;
opt_space->opt_nflen = fl_opt->opt_nflen;
} else {
if (fopt->opt_nflen == 0)
return fopt;
opt_space->hopopt = NULL;
opt_space->dst0opt = NULL;
opt_space->srcrt = NULL;
opt_space->opt_nflen = 0;
}
opt_space->dst1opt = fopt->dst1opt;
opt_space->opt_flen = fopt->opt_flen;
return opt_space;
}
static unsigned long check_linger(unsigned long ttl)
{
if (ttl < FL_MIN_LINGER)
return FL_MIN_LINGER*HZ;
if (ttl > FL_MAX_LINGER && !capable(CAP_NET_ADMIN))
return 0;
return ttl*HZ;
}
static int fl6_renew(struct ip6_flowlabel *fl, unsigned long linger, unsigned long expires)
{
linger = check_linger(linger);
if (!linger)
return -EPERM;
expires = check_linger(expires);
if (!expires)
return -EPERM;
fl->lastuse = jiffies;
if (time_before(fl->linger, linger))
fl->linger = linger;
if (time_before(expires, fl->linger))
expires = fl->linger;
if (time_before(fl->expires, fl->lastuse + expires))
fl->expires = fl->lastuse + expires;
return 0;
}
static struct ip6_flowlabel *
fl_create(struct net *net, struct sock *sk, struct in6_flowlabel_req *freq,
char __user *optval, int optlen, int *err_p)
{
struct ip6_flowlabel *fl = NULL;
int olen;
int addr_type;
int err;
olen = optlen - CMSG_ALIGN(sizeof(*freq));
err = -EINVAL;
if (olen > 64 * 1024)
goto done;
err = -ENOMEM;
fl = kzalloc(sizeof(*fl), GFP_KERNEL);
if (fl == NULL)
goto done;
if (olen > 0) {
struct msghdr msg;
struct flowi6 flowi6;
int junk;
err = -ENOMEM;
fl->opt = kmalloc(sizeof(*fl->opt) + olen, GFP_KERNEL);
if (fl->opt == NULL)
goto done;
memset(fl->opt, 0, sizeof(*fl->opt));
fl->opt->tot_len = sizeof(*fl->opt) + olen;
err = -EFAULT;
if (copy_from_user(fl->opt+1, optval+CMSG_ALIGN(sizeof(*freq)), olen))
goto done;
msg.msg_controllen = olen;
msg.msg_control = (void*)(fl->opt+1);
memset(&flowi6, 0, sizeof(flowi6));
err = datagram_send_ctl(net, sk, &msg, &flowi6, fl->opt, &junk,
&junk, &junk);
if (err)
goto done;
err = -EINVAL;
if (fl->opt->opt_flen)
goto done;
if (fl->opt->opt_nflen == 0) {
kfree(fl->opt);
fl->opt = NULL;
}
}
fl->fl_net = hold_net(net);
fl->expires = jiffies;
err = fl6_renew(fl, freq->flr_linger, freq->flr_expires);
if (err)
goto done;
fl->share = freq->flr_share;
addr_type = ipv6_addr_type(&freq->flr_dst);
if ((addr_type & IPV6_ADDR_MAPPED) ||
addr_type == IPV6_ADDR_ANY) {
err = -EINVAL;
goto done;
}
fl->dst = freq->flr_dst;
atomic_set(&fl->users, 1);
switch (fl->share) {
case IPV6_FL_S_EXCL:
case IPV6_FL_S_ANY:
break;
case IPV6_FL_S_PROCESS:
fl->owner = current->pid;
break;
case IPV6_FL_S_USER:
fl->owner = current_euid();
break;
default:
err = -EINVAL;
goto done;
}
return fl;
done:
fl_free(fl);
*err_p = err;
return NULL;
}
static int mem_check(struct sock *sk)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6_fl_socklist *sfl;
int room = FL_MAX_SIZE - atomic_read(&fl_size);
int count = 0;
if (room > FL_MAX_SIZE - FL_MAX_PER_SOCK)
return 0;
for (sfl = np->ipv6_fl_list; sfl; sfl = sfl->next)
count++;
if (room <= 0 ||
((count >= FL_MAX_PER_SOCK ||
(count > 0 && room < FL_MAX_SIZE/2) || room < FL_MAX_SIZE/4) &&
!capable(CAP_NET_ADMIN)))
return -ENOBUFS;
return 0;
}
static int ipv6_hdr_cmp(struct ipv6_opt_hdr *h1, struct ipv6_opt_hdr *h2)
{
if (h1 == h2)
return 0;
if (h1 == NULL || h2 == NULL)
return 1;
if (h1->hdrlen != h2->hdrlen)
return 1;
return memcmp(h1+1, h2+1, ((h1->hdrlen+1)<<3) - sizeof(*h1));
}
static int ipv6_opt_cmp(struct ipv6_txoptions *o1, struct ipv6_txoptions *o2)
{
if (o1 == o2)
return 0;
if (o1 == NULL || o2 == NULL)
return 1;
if (o1->opt_nflen != o2->opt_nflen)
return 1;
if (ipv6_hdr_cmp(o1->hopopt, o2->hopopt))
return 1;
if (ipv6_hdr_cmp(o1->dst0opt, o2->dst0opt))
return 1;
if (ipv6_hdr_cmp((struct ipv6_opt_hdr *)o1->srcrt, (struct ipv6_opt_hdr *)o2->srcrt))
return 1;
return 0;
}
static inline void fl_link(struct ipv6_pinfo *np, struct ipv6_fl_socklist *sfl,
struct ip6_flowlabel *fl)
{
write_lock_bh(&ip6_sk_fl_lock);
sfl->fl = fl;
sfl->next = np->ipv6_fl_list;
np->ipv6_fl_list = sfl;
write_unlock_bh(&ip6_sk_fl_lock);
}
int ipv6_flowlabel_opt(struct sock *sk, char __user *optval, int optlen)
{
int uninitialized_var(err);
struct net *net = sock_net(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct in6_flowlabel_req freq;
struct ipv6_fl_socklist *sfl1=NULL;
struct ipv6_fl_socklist *sfl, **sflp;
struct ip6_flowlabel *fl, *fl1 = NULL;
if (optlen < sizeof(freq))
return -EINVAL;
if (copy_from_user(&freq, optval, sizeof(freq)))
return -EFAULT;
switch (freq.flr_action) {
case IPV6_FL_A_PUT:
write_lock_bh(&ip6_sk_fl_lock);
for (sflp = &np->ipv6_fl_list; (sfl=*sflp)!=NULL; sflp = &sfl->next) {
if (sfl->fl->label == freq.flr_label) {
if (freq.flr_label == (np->flow_label&IPV6_FLOWLABEL_MASK))
np->flow_label &= ~IPV6_FLOWLABEL_MASK;
*sflp = sfl->next;
write_unlock_bh(&ip6_sk_fl_lock);
fl_release(sfl->fl);
kfree(sfl);
return 0;
}
}
write_unlock_bh(&ip6_sk_fl_lock);
return -ESRCH;
case IPV6_FL_A_RENEW:
read_lock_bh(&ip6_sk_fl_lock);
for (sfl = np->ipv6_fl_list; sfl; sfl = sfl->next) {
if (sfl->fl->label == freq.flr_label) {
err = fl6_renew(sfl->fl, freq.flr_linger, freq.flr_expires);
read_unlock_bh(&ip6_sk_fl_lock);
return err;
}
}
read_unlock_bh(&ip6_sk_fl_lock);
if (freq.flr_share == IPV6_FL_S_NONE && capable(CAP_NET_ADMIN)) {
fl = fl_lookup(net, freq.flr_label);
if (fl) {
err = fl6_renew(fl, freq.flr_linger, freq.flr_expires);
fl_release(fl);
return err;
}
}
return -ESRCH;
case IPV6_FL_A_GET:
if (freq.flr_label & ~IPV6_FLOWLABEL_MASK)
return -EINVAL;
fl = fl_create(net, sk, &freq, optval, optlen, &err);
if (fl == NULL)
return err;
sfl1 = kmalloc(sizeof(*sfl1), GFP_KERNEL);
if (freq.flr_label) {
err = -EEXIST;
read_lock_bh(&ip6_sk_fl_lock);
for (sfl = np->ipv6_fl_list; sfl; sfl = sfl->next) {
if (sfl->fl->label == freq.flr_label) {
if (freq.flr_flags&IPV6_FL_F_EXCL) {
read_unlock_bh(&ip6_sk_fl_lock);
goto done;
}
fl1 = sfl->fl;
atomic_inc(&fl1->users);
break;
}
}
read_unlock_bh(&ip6_sk_fl_lock);
if (fl1 == NULL)
fl1 = fl_lookup(net, freq.flr_label);
if (fl1) {
recheck:
err = -EEXIST;
if (freq.flr_flags&IPV6_FL_F_EXCL)
goto release;
err = -EPERM;
if (fl1->share == IPV6_FL_S_EXCL ||
fl1->share != fl->share ||
fl1->owner != fl->owner)
goto release;
err = -EINVAL;
if (!ipv6_addr_equal(&fl1->dst, &fl->dst) ||
ipv6_opt_cmp(fl1->opt, fl->opt))
goto release;
err = -ENOMEM;
if (sfl1 == NULL)
goto release;
if (fl->linger > fl1->linger)
fl1->linger = fl->linger;
if ((long)(fl->expires - fl1->expires) > 0)
fl1->expires = fl->expires;
fl_link(np, sfl1, fl1);
fl_free(fl);
return 0;
release:
fl_release(fl1);
goto done;
}
}
err = -ENOENT;
if (!(freq.flr_flags&IPV6_FL_F_CREATE))
goto done;
err = -ENOMEM;
if (sfl1 == NULL || (err = mem_check(sk)) != 0)
goto done;
fl1 = fl_intern(net, fl, freq.flr_label);
if (fl1 != NULL)
goto recheck;
if (!freq.flr_label) {
if (copy_to_user(&((struct in6_flowlabel_req __user *) optval)->flr_label,
&fl->label, sizeof(fl->label))) {
}
}
fl_link(np, sfl1, fl);
return 0;
default:
return -EINVAL;
}
done:
fl_free(fl);
kfree(sfl1);
return err;
}
#ifdef CONFIG_PROC_FS
struct ip6fl_iter_state {
struct seq_net_private p;
int bucket;
};
#define ip6fl_seq_private(seq) ((struct ip6fl_iter_state *)(seq)->private)
static struct ip6_flowlabel *ip6fl_get_first(struct seq_file *seq)
{
struct ip6_flowlabel *fl = NULL;
struct ip6fl_iter_state *state = ip6fl_seq_private(seq);
struct net *net = seq_file_net(seq);
for (state->bucket = 0; state->bucket <= FL_HASH_MASK; ++state->bucket) {
fl = fl_ht[state->bucket];
while (fl && !net_eq(fl->fl_net, net))
fl = fl->next;
if (fl)
break;
}
return fl;
}
static struct ip6_flowlabel *ip6fl_get_next(struct seq_file *seq, struct ip6_flowlabel *fl)
{
struct ip6fl_iter_state *state = ip6fl_seq_private(seq);
struct net *net = seq_file_net(seq);
fl = fl->next;
try_again:
while (fl && !net_eq(fl->fl_net, net))
fl = fl->next;
while (!fl) {
if (++state->bucket <= FL_HASH_MASK) {
fl = fl_ht[state->bucket];
goto try_again;
} else
break;
}
return fl;
}
static struct ip6_flowlabel *ip6fl_get_idx(struct seq_file *seq, loff_t pos)
{
struct ip6_flowlabel *fl = ip6fl_get_first(seq);
if (fl)
while (pos && (fl = ip6fl_get_next(seq, fl)) != NULL)
--pos;
return pos ? NULL : fl;
}
static void *ip6fl_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(ip6_fl_lock)
{
read_lock_bh(&ip6_fl_lock);
return *pos ? ip6fl_get_idx(seq, *pos - 1) : SEQ_START_TOKEN;
}
static void *ip6fl_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct ip6_flowlabel *fl;
if (v == SEQ_START_TOKEN)
fl = ip6fl_get_first(seq);
else
fl = ip6fl_get_next(seq, v);
++*pos;
return fl;
}
static void ip6fl_seq_stop(struct seq_file *seq, void *v)
__releases(ip6_fl_lock)
{
read_unlock_bh(&ip6_fl_lock);
}
static int ip6fl_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_printf(seq, "%-5s %-1s %-6s %-6s %-6s %-8s %-32s %s\n",
"Label", "S", "Owner", "Users", "Linger", "Expires", "Dst", "Opt");
else {
struct ip6_flowlabel *fl = v;
seq_printf(seq,
"%05X %-1d %-6d %-6d %-6ld %-8ld %pi6 %-4d\n",
(unsigned)ntohl(fl->label),
fl->share,
(unsigned)fl->owner,
atomic_read(&fl->users),
fl->linger/HZ,
(long)(fl->expires - jiffies)/HZ,
&fl->dst,
fl->opt ? fl->opt->opt_nflen : 0);
}
return 0;
}
static const struct seq_operations ip6fl_seq_ops = {
.start = ip6fl_seq_start,
.next = ip6fl_seq_next,
.stop = ip6fl_seq_stop,
.show = ip6fl_seq_show,
};
static int ip6fl_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &ip6fl_seq_ops,
sizeof(struct ip6fl_iter_state));
}
static const struct file_operations ip6fl_seq_fops = {
.owner = THIS_MODULE,
.open = ip6fl_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static int __net_init ip6_flowlabel_proc_init(struct net *net)
{
if (!proc_net_fops_create(net, "ip6_flowlabel",
S_IRUGO, &ip6fl_seq_fops))
return -ENOMEM;
return 0;
}
static void __net_exit ip6_flowlabel_proc_fini(struct net *net)
{
proc_net_remove(net, "ip6_flowlabel");
}
#else
static inline int ip6_flowlabel_proc_init(struct net *net)
{
return 0;
}
static inline void ip6_flowlabel_proc_fini(struct net *net)
{
}
#endif
static void __net_exit ip6_flowlabel_net_exit(struct net *net)
{
ip6_fl_purge(net);
ip6_flowlabel_proc_fini(net);
}
static struct pernet_operations ip6_flowlabel_net_ops = {
.init = ip6_flowlabel_proc_init,
.exit = ip6_flowlabel_net_exit,
};
int ip6_flowlabel_init(void)
{
return register_pernet_subsys(&ip6_flowlabel_net_ops);
}
void ip6_flowlabel_cleanup(void)
{
del_timer(&ip6_fl_gc_timer);
unregister_pernet_subsys(&ip6_flowlabel_net_ops);
}
| gpl-2.0 |
calonso-conabio/linux | drivers/net/ethernet/mellanox/mlx4/resource_tracker.c | 383 | 128858 | /*
* Copyright (c) 2004, 2005 Topspin Communications. All rights reserved.
* Copyright (c) 2005, 2006, 2007, 2008 Mellanox Technologies.
* All rights reserved.
* Copyright (c) 2005, 2006, 2007 Cisco Systems, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/sched.h>
#include <linux/pci.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/mlx4/cmd.h>
#include <linux/mlx4/qp.h>
#include <linux/if_ether.h>
#include <linux/etherdevice.h>
#include "mlx4.h"
#include "fw.h"
#include "mlx4_stats.h"
#define MLX4_MAC_VALID (1ull << 63)
#define MLX4_PF_COUNTERS_PER_PORT 2
#define MLX4_VF_COUNTERS_PER_PORT 1
struct mac_res {
struct list_head list;
u64 mac;
int ref_count;
u8 smac_index;
u8 port;
};
struct vlan_res {
struct list_head list;
u16 vlan;
int ref_count;
int vlan_index;
u8 port;
};
struct res_common {
struct list_head list;
struct rb_node node;
u64 res_id;
int owner;
int state;
int from_state;
int to_state;
int removing;
};
enum {
RES_ANY_BUSY = 1
};
struct res_gid {
struct list_head list;
u8 gid[16];
enum mlx4_protocol prot;
enum mlx4_steer_type steer;
u64 reg_id;
};
enum res_qp_states {
RES_QP_BUSY = RES_ANY_BUSY,
/* QP number was allocated */
RES_QP_RESERVED,
/* ICM memory for QP context was mapped */
RES_QP_MAPPED,
/* QP is in hw ownership */
RES_QP_HW
};
struct res_qp {
struct res_common com;
struct res_mtt *mtt;
struct res_cq *rcq;
struct res_cq *scq;
struct res_srq *srq;
struct list_head mcg_list;
spinlock_t mcg_spl;
int local_qpn;
atomic_t ref_count;
u32 qpc_flags;
/* saved qp params before VST enforcement in order to restore on VGT */
u8 sched_queue;
__be32 param3;
u8 vlan_control;
u8 fvl_rx;
u8 pri_path_fl;
u8 vlan_index;
u8 feup;
};
enum res_mtt_states {
RES_MTT_BUSY = RES_ANY_BUSY,
RES_MTT_ALLOCATED,
};
static inline const char *mtt_states_str(enum res_mtt_states state)
{
switch (state) {
case RES_MTT_BUSY: return "RES_MTT_BUSY";
case RES_MTT_ALLOCATED: return "RES_MTT_ALLOCATED";
default: return "Unknown";
}
}
struct res_mtt {
struct res_common com;
int order;
atomic_t ref_count;
};
enum res_mpt_states {
RES_MPT_BUSY = RES_ANY_BUSY,
RES_MPT_RESERVED,
RES_MPT_MAPPED,
RES_MPT_HW,
};
struct res_mpt {
struct res_common com;
struct res_mtt *mtt;
int key;
};
enum res_eq_states {
RES_EQ_BUSY = RES_ANY_BUSY,
RES_EQ_RESERVED,
RES_EQ_HW,
};
struct res_eq {
struct res_common com;
struct res_mtt *mtt;
};
enum res_cq_states {
RES_CQ_BUSY = RES_ANY_BUSY,
RES_CQ_ALLOCATED,
RES_CQ_HW,
};
struct res_cq {
struct res_common com;
struct res_mtt *mtt;
atomic_t ref_count;
};
enum res_srq_states {
RES_SRQ_BUSY = RES_ANY_BUSY,
RES_SRQ_ALLOCATED,
RES_SRQ_HW,
};
struct res_srq {
struct res_common com;
struct res_mtt *mtt;
struct res_cq *cq;
atomic_t ref_count;
};
enum res_counter_states {
RES_COUNTER_BUSY = RES_ANY_BUSY,
RES_COUNTER_ALLOCATED,
};
struct res_counter {
struct res_common com;
int port;
};
enum res_xrcdn_states {
RES_XRCD_BUSY = RES_ANY_BUSY,
RES_XRCD_ALLOCATED,
};
struct res_xrcdn {
struct res_common com;
int port;
};
enum res_fs_rule_states {
RES_FS_RULE_BUSY = RES_ANY_BUSY,
RES_FS_RULE_ALLOCATED,
};
struct res_fs_rule {
struct res_common com;
int qpn;
};
static void *res_tracker_lookup(struct rb_root *root, u64 res_id)
{
struct rb_node *node = root->rb_node;
while (node) {
struct res_common *res = container_of(node, struct res_common,
node);
if (res_id < res->res_id)
node = node->rb_left;
else if (res_id > res->res_id)
node = node->rb_right;
else
return res;
}
return NULL;
}
static int res_tracker_insert(struct rb_root *root, struct res_common *res)
{
struct rb_node **new = &(root->rb_node), *parent = NULL;
/* Figure out where to put new node */
while (*new) {
struct res_common *this = container_of(*new, struct res_common,
node);
parent = *new;
if (res->res_id < this->res_id)
new = &((*new)->rb_left);
else if (res->res_id > this->res_id)
new = &((*new)->rb_right);
else
return -EEXIST;
}
/* Add new node and rebalance tree. */
rb_link_node(&res->node, parent, new);
rb_insert_color(&res->node, root);
return 0;
}
enum qp_transition {
QP_TRANS_INIT2RTR,
QP_TRANS_RTR2RTS,
QP_TRANS_RTS2RTS,
QP_TRANS_SQERR2RTS,
QP_TRANS_SQD2SQD,
QP_TRANS_SQD2RTS
};
/* For Debug uses */
static const char *resource_str(enum mlx4_resource rt)
{
switch (rt) {
case RES_QP: return "RES_QP";
case RES_CQ: return "RES_CQ";
case RES_SRQ: return "RES_SRQ";
case RES_MPT: return "RES_MPT";
case RES_MTT: return "RES_MTT";
case RES_MAC: return "RES_MAC";
case RES_VLAN: return "RES_VLAN";
case RES_EQ: return "RES_EQ";
case RES_COUNTER: return "RES_COUNTER";
case RES_FS_RULE: return "RES_FS_RULE";
case RES_XRCD: return "RES_XRCD";
default: return "Unknown resource type !!!";
};
}
static void rem_slave_vlans(struct mlx4_dev *dev, int slave);
static inline int mlx4_grant_resource(struct mlx4_dev *dev, int slave,
enum mlx4_resource res_type, int count,
int port)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct resource_allocator *res_alloc =
&priv->mfunc.master.res_tracker.res_alloc[res_type];
int err = -EINVAL;
int allocated, free, reserved, guaranteed, from_free;
int from_rsvd;
if (slave > dev->persist->num_vfs)
return -EINVAL;
spin_lock(&res_alloc->alloc_lock);
allocated = (port > 0) ?
res_alloc->allocated[(port - 1) *
(dev->persist->num_vfs + 1) + slave] :
res_alloc->allocated[slave];
free = (port > 0) ? res_alloc->res_port_free[port - 1] :
res_alloc->res_free;
reserved = (port > 0) ? res_alloc->res_port_rsvd[port - 1] :
res_alloc->res_reserved;
guaranteed = res_alloc->guaranteed[slave];
if (allocated + count > res_alloc->quota[slave]) {
mlx4_warn(dev, "VF %d port %d res %s: quota exceeded, count %d alloc %d quota %d\n",
slave, port, resource_str(res_type), count,
allocated, res_alloc->quota[slave]);
goto out;
}
if (allocated + count <= guaranteed) {
err = 0;
from_rsvd = count;
} else {
/* portion may need to be obtained from free area */
if (guaranteed - allocated > 0)
from_free = count - (guaranteed - allocated);
else
from_free = count;
from_rsvd = count - from_free;
if (free - from_free >= reserved)
err = 0;
else
mlx4_warn(dev, "VF %d port %d res %s: free pool empty, free %d from_free %d rsvd %d\n",
slave, port, resource_str(res_type), free,
from_free, reserved);
}
if (!err) {
/* grant the request */
if (port > 0) {
res_alloc->allocated[(port - 1) *
(dev->persist->num_vfs + 1) + slave] += count;
res_alloc->res_port_free[port - 1] -= count;
res_alloc->res_port_rsvd[port - 1] -= from_rsvd;
} else {
res_alloc->allocated[slave] += count;
res_alloc->res_free -= count;
res_alloc->res_reserved -= from_rsvd;
}
}
out:
spin_unlock(&res_alloc->alloc_lock);
return err;
}
static inline void mlx4_release_resource(struct mlx4_dev *dev, int slave,
enum mlx4_resource res_type, int count,
int port)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct resource_allocator *res_alloc =
&priv->mfunc.master.res_tracker.res_alloc[res_type];
int allocated, guaranteed, from_rsvd;
if (slave > dev->persist->num_vfs)
return;
spin_lock(&res_alloc->alloc_lock);
allocated = (port > 0) ?
res_alloc->allocated[(port - 1) *
(dev->persist->num_vfs + 1) + slave] :
res_alloc->allocated[slave];
guaranteed = res_alloc->guaranteed[slave];
if (allocated - count >= guaranteed) {
from_rsvd = 0;
} else {
/* portion may need to be returned to reserved area */
if (allocated - guaranteed > 0)
from_rsvd = count - (allocated - guaranteed);
else
from_rsvd = count;
}
if (port > 0) {
res_alloc->allocated[(port - 1) *
(dev->persist->num_vfs + 1) + slave] -= count;
res_alloc->res_port_free[port - 1] += count;
res_alloc->res_port_rsvd[port - 1] += from_rsvd;
} else {
res_alloc->allocated[slave] -= count;
res_alloc->res_free += count;
res_alloc->res_reserved += from_rsvd;
}
spin_unlock(&res_alloc->alloc_lock);
return;
}
static inline void initialize_res_quotas(struct mlx4_dev *dev,
struct resource_allocator *res_alloc,
enum mlx4_resource res_type,
int vf, int num_instances)
{
res_alloc->guaranteed[vf] = num_instances /
(2 * (dev->persist->num_vfs + 1));
res_alloc->quota[vf] = (num_instances / 2) + res_alloc->guaranteed[vf];
if (vf == mlx4_master_func_num(dev)) {
res_alloc->res_free = num_instances;
if (res_type == RES_MTT) {
/* reserved mtts will be taken out of the PF allocation */
res_alloc->res_free += dev->caps.reserved_mtts;
res_alloc->guaranteed[vf] += dev->caps.reserved_mtts;
res_alloc->quota[vf] += dev->caps.reserved_mtts;
}
}
}
void mlx4_init_quotas(struct mlx4_dev *dev)
{
struct mlx4_priv *priv = mlx4_priv(dev);
int pf;
/* quotas for VFs are initialized in mlx4_slave_cap */
if (mlx4_is_slave(dev))
return;
if (!mlx4_is_mfunc(dev)) {
dev->quotas.qp = dev->caps.num_qps - dev->caps.reserved_qps -
mlx4_num_reserved_sqps(dev);
dev->quotas.cq = dev->caps.num_cqs - dev->caps.reserved_cqs;
dev->quotas.srq = dev->caps.num_srqs - dev->caps.reserved_srqs;
dev->quotas.mtt = dev->caps.num_mtts - dev->caps.reserved_mtts;
dev->quotas.mpt = dev->caps.num_mpts - dev->caps.reserved_mrws;
return;
}
pf = mlx4_master_func_num(dev);
dev->quotas.qp =
priv->mfunc.master.res_tracker.res_alloc[RES_QP].quota[pf];
dev->quotas.cq =
priv->mfunc.master.res_tracker.res_alloc[RES_CQ].quota[pf];
dev->quotas.srq =
priv->mfunc.master.res_tracker.res_alloc[RES_SRQ].quota[pf];
dev->quotas.mtt =
priv->mfunc.master.res_tracker.res_alloc[RES_MTT].quota[pf];
dev->quotas.mpt =
priv->mfunc.master.res_tracker.res_alloc[RES_MPT].quota[pf];
}
static int get_max_gauranteed_vfs_counter(struct mlx4_dev *dev)
{
/* reduce the sink counter */
return (dev->caps.max_counters - 1 -
(MLX4_PF_COUNTERS_PER_PORT * MLX4_MAX_PORTS))
/ MLX4_MAX_PORTS;
}
int mlx4_init_resource_tracker(struct mlx4_dev *dev)
{
struct mlx4_priv *priv = mlx4_priv(dev);
int i, j;
int t;
int max_vfs_guarantee_counter = get_max_gauranteed_vfs_counter(dev);
priv->mfunc.master.res_tracker.slave_list =
kzalloc(dev->num_slaves * sizeof(struct slave_list),
GFP_KERNEL);
if (!priv->mfunc.master.res_tracker.slave_list)
return -ENOMEM;
for (i = 0 ; i < dev->num_slaves; i++) {
for (t = 0; t < MLX4_NUM_OF_RESOURCE_TYPE; ++t)
INIT_LIST_HEAD(&priv->mfunc.master.res_tracker.
slave_list[i].res_list[t]);
mutex_init(&priv->mfunc.master.res_tracker.slave_list[i].mutex);
}
mlx4_dbg(dev, "Started init_resource_tracker: %ld slaves\n",
dev->num_slaves);
for (i = 0 ; i < MLX4_NUM_OF_RESOURCE_TYPE; i++)
priv->mfunc.master.res_tracker.res_tree[i] = RB_ROOT;
for (i = 0; i < MLX4_NUM_OF_RESOURCE_TYPE; i++) {
struct resource_allocator *res_alloc =
&priv->mfunc.master.res_tracker.res_alloc[i];
res_alloc->quota = kmalloc((dev->persist->num_vfs + 1) *
sizeof(int), GFP_KERNEL);
res_alloc->guaranteed = kmalloc((dev->persist->num_vfs + 1) *
sizeof(int), GFP_KERNEL);
if (i == RES_MAC || i == RES_VLAN)
res_alloc->allocated = kzalloc(MLX4_MAX_PORTS *
(dev->persist->num_vfs
+ 1) *
sizeof(int), GFP_KERNEL);
else
res_alloc->allocated = kzalloc((dev->persist->
num_vfs + 1) *
sizeof(int), GFP_KERNEL);
/* Reduce the sink counter */
if (i == RES_COUNTER)
res_alloc->res_free = dev->caps.max_counters - 1;
if (!res_alloc->quota || !res_alloc->guaranteed ||
!res_alloc->allocated)
goto no_mem_err;
spin_lock_init(&res_alloc->alloc_lock);
for (t = 0; t < dev->persist->num_vfs + 1; t++) {
struct mlx4_active_ports actv_ports =
mlx4_get_active_ports(dev, t);
switch (i) {
case RES_QP:
initialize_res_quotas(dev, res_alloc, RES_QP,
t, dev->caps.num_qps -
dev->caps.reserved_qps -
mlx4_num_reserved_sqps(dev));
break;
case RES_CQ:
initialize_res_quotas(dev, res_alloc, RES_CQ,
t, dev->caps.num_cqs -
dev->caps.reserved_cqs);
break;
case RES_SRQ:
initialize_res_quotas(dev, res_alloc, RES_SRQ,
t, dev->caps.num_srqs -
dev->caps.reserved_srqs);
break;
case RES_MPT:
initialize_res_quotas(dev, res_alloc, RES_MPT,
t, dev->caps.num_mpts -
dev->caps.reserved_mrws);
break;
case RES_MTT:
initialize_res_quotas(dev, res_alloc, RES_MTT,
t, dev->caps.num_mtts -
dev->caps.reserved_mtts);
break;
case RES_MAC:
if (t == mlx4_master_func_num(dev)) {
int max_vfs_pport = 0;
/* Calculate the max vfs per port for */
/* both ports. */
for (j = 0; j < dev->caps.num_ports;
j++) {
struct mlx4_slaves_pport slaves_pport =
mlx4_phys_to_slaves_pport(dev, j + 1);
unsigned current_slaves =
bitmap_weight(slaves_pport.slaves,
dev->caps.num_ports) - 1;
if (max_vfs_pport < current_slaves)
max_vfs_pport =
current_slaves;
}
res_alloc->quota[t] =
MLX4_MAX_MAC_NUM -
2 * max_vfs_pport;
res_alloc->guaranteed[t] = 2;
for (j = 0; j < MLX4_MAX_PORTS; j++)
res_alloc->res_port_free[j] =
MLX4_MAX_MAC_NUM;
} else {
res_alloc->quota[t] = MLX4_MAX_MAC_NUM;
res_alloc->guaranteed[t] = 2;
}
break;
case RES_VLAN:
if (t == mlx4_master_func_num(dev)) {
res_alloc->quota[t] = MLX4_MAX_VLAN_NUM;
res_alloc->guaranteed[t] = MLX4_MAX_VLAN_NUM / 2;
for (j = 0; j < MLX4_MAX_PORTS; j++)
res_alloc->res_port_free[j] =
res_alloc->quota[t];
} else {
res_alloc->quota[t] = MLX4_MAX_VLAN_NUM / 2;
res_alloc->guaranteed[t] = 0;
}
break;
case RES_COUNTER:
res_alloc->quota[t] = dev->caps.max_counters;
if (t == mlx4_master_func_num(dev))
res_alloc->guaranteed[t] =
MLX4_PF_COUNTERS_PER_PORT *
MLX4_MAX_PORTS;
else if (t <= max_vfs_guarantee_counter)
res_alloc->guaranteed[t] =
MLX4_VF_COUNTERS_PER_PORT *
MLX4_MAX_PORTS;
else
res_alloc->guaranteed[t] = 0;
res_alloc->res_free -= res_alloc->guaranteed[t];
break;
default:
break;
}
if (i == RES_MAC || i == RES_VLAN) {
for (j = 0; j < dev->caps.num_ports; j++)
if (test_bit(j, actv_ports.ports))
res_alloc->res_port_rsvd[j] +=
res_alloc->guaranteed[t];
} else {
res_alloc->res_reserved += res_alloc->guaranteed[t];
}
}
}
spin_lock_init(&priv->mfunc.master.res_tracker.lock);
return 0;
no_mem_err:
for (i = 0; i < MLX4_NUM_OF_RESOURCE_TYPE; i++) {
kfree(priv->mfunc.master.res_tracker.res_alloc[i].allocated);
priv->mfunc.master.res_tracker.res_alloc[i].allocated = NULL;
kfree(priv->mfunc.master.res_tracker.res_alloc[i].guaranteed);
priv->mfunc.master.res_tracker.res_alloc[i].guaranteed = NULL;
kfree(priv->mfunc.master.res_tracker.res_alloc[i].quota);
priv->mfunc.master.res_tracker.res_alloc[i].quota = NULL;
}
return -ENOMEM;
}
void mlx4_free_resource_tracker(struct mlx4_dev *dev,
enum mlx4_res_tracker_free_type type)
{
struct mlx4_priv *priv = mlx4_priv(dev);
int i;
if (priv->mfunc.master.res_tracker.slave_list) {
if (type != RES_TR_FREE_STRUCTS_ONLY) {
for (i = 0; i < dev->num_slaves; i++) {
if (type == RES_TR_FREE_ALL ||
dev->caps.function != i)
mlx4_delete_all_resources_for_slave(dev, i);
}
/* free master's vlans */
i = dev->caps.function;
mlx4_reset_roce_gids(dev, i);
mutex_lock(&priv->mfunc.master.res_tracker.slave_list[i].mutex);
rem_slave_vlans(dev, i);
mutex_unlock(&priv->mfunc.master.res_tracker.slave_list[i].mutex);
}
if (type != RES_TR_FREE_SLAVES_ONLY) {
for (i = 0; i < MLX4_NUM_OF_RESOURCE_TYPE; i++) {
kfree(priv->mfunc.master.res_tracker.res_alloc[i].allocated);
priv->mfunc.master.res_tracker.res_alloc[i].allocated = NULL;
kfree(priv->mfunc.master.res_tracker.res_alloc[i].guaranteed);
priv->mfunc.master.res_tracker.res_alloc[i].guaranteed = NULL;
kfree(priv->mfunc.master.res_tracker.res_alloc[i].quota);
priv->mfunc.master.res_tracker.res_alloc[i].quota = NULL;
}
kfree(priv->mfunc.master.res_tracker.slave_list);
priv->mfunc.master.res_tracker.slave_list = NULL;
}
}
}
static void update_pkey_index(struct mlx4_dev *dev, int slave,
struct mlx4_cmd_mailbox *inbox)
{
u8 sched = *(u8 *)(inbox->buf + 64);
u8 orig_index = *(u8 *)(inbox->buf + 35);
u8 new_index;
struct mlx4_priv *priv = mlx4_priv(dev);
int port;
port = (sched >> 6 & 1) + 1;
new_index = priv->virt2phys_pkey[slave][port - 1][orig_index];
*(u8 *)(inbox->buf + 35) = new_index;
}
static void update_gid(struct mlx4_dev *dev, struct mlx4_cmd_mailbox *inbox,
u8 slave)
{
struct mlx4_qp_context *qp_ctx = inbox->buf + 8;
enum mlx4_qp_optpar optpar = be32_to_cpu(*(__be32 *) inbox->buf);
u32 ts = (be32_to_cpu(qp_ctx->flags) >> 16) & 0xff;
int port;
if (MLX4_QP_ST_UD == ts) {
port = (qp_ctx->pri_path.sched_queue >> 6 & 1) + 1;
if (mlx4_is_eth(dev, port))
qp_ctx->pri_path.mgid_index =
mlx4_get_base_gid_ix(dev, slave, port) | 0x80;
else
qp_ctx->pri_path.mgid_index = slave | 0x80;
} else if (MLX4_QP_ST_RC == ts || MLX4_QP_ST_XRC == ts || MLX4_QP_ST_UC == ts) {
if (optpar & MLX4_QP_OPTPAR_PRIMARY_ADDR_PATH) {
port = (qp_ctx->pri_path.sched_queue >> 6 & 1) + 1;
if (mlx4_is_eth(dev, port)) {
qp_ctx->pri_path.mgid_index +=
mlx4_get_base_gid_ix(dev, slave, port);
qp_ctx->pri_path.mgid_index &= 0x7f;
} else {
qp_ctx->pri_path.mgid_index = slave & 0x7F;
}
}
if (optpar & MLX4_QP_OPTPAR_ALT_ADDR_PATH) {
port = (qp_ctx->alt_path.sched_queue >> 6 & 1) + 1;
if (mlx4_is_eth(dev, port)) {
qp_ctx->alt_path.mgid_index +=
mlx4_get_base_gid_ix(dev, slave, port);
qp_ctx->alt_path.mgid_index &= 0x7f;
} else {
qp_ctx->alt_path.mgid_index = slave & 0x7F;
}
}
}
}
static int handle_counter(struct mlx4_dev *dev, struct mlx4_qp_context *qpc,
u8 slave, int port);
static int update_vport_qp_param(struct mlx4_dev *dev,
struct mlx4_cmd_mailbox *inbox,
u8 slave, u32 qpn)
{
struct mlx4_qp_context *qpc = inbox->buf + 8;
struct mlx4_vport_oper_state *vp_oper;
struct mlx4_priv *priv;
u32 qp_type;
int port, err = 0;
port = (qpc->pri_path.sched_queue & 0x40) ? 2 : 1;
priv = mlx4_priv(dev);
vp_oper = &priv->mfunc.master.vf_oper[slave].vport[port];
qp_type = (be32_to_cpu(qpc->flags) >> 16) & 0xff;
err = handle_counter(dev, qpc, slave, port);
if (err)
goto out;
if (MLX4_VGT != vp_oper->state.default_vlan) {
/* the reserved QPs (special, proxy, tunnel)
* do not operate over vlans
*/
if (mlx4_is_qp_reserved(dev, qpn))
return 0;
/* force strip vlan by clear vsd, MLX QP refers to Raw Ethernet */
if (qp_type == MLX4_QP_ST_UD ||
(qp_type == MLX4_QP_ST_MLX && mlx4_is_eth(dev, port))) {
if (dev->caps.bmme_flags & MLX4_BMME_FLAG_VSD_INIT2RTR) {
*(__be32 *)inbox->buf =
cpu_to_be32(be32_to_cpu(*(__be32 *)inbox->buf) |
MLX4_QP_OPTPAR_VLAN_STRIPPING);
qpc->param3 &= ~cpu_to_be32(MLX4_STRIP_VLAN);
} else {
struct mlx4_update_qp_params params = {.flags = 0};
err = mlx4_update_qp(dev, qpn, MLX4_UPDATE_QP_VSD, ¶ms);
if (err)
goto out;
}
}
if (vp_oper->state.link_state == IFLA_VF_LINK_STATE_DISABLE &&
dev->caps.flags2 & MLX4_DEV_CAP_FLAG2_UPDATE_QP) {
qpc->pri_path.vlan_control =
MLX4_VLAN_CTRL_ETH_TX_BLOCK_TAGGED |
MLX4_VLAN_CTRL_ETH_TX_BLOCK_PRIO_TAGGED |
MLX4_VLAN_CTRL_ETH_TX_BLOCK_UNTAGGED |
MLX4_VLAN_CTRL_ETH_RX_BLOCK_PRIO_TAGGED |
MLX4_VLAN_CTRL_ETH_RX_BLOCK_UNTAGGED |
MLX4_VLAN_CTRL_ETH_RX_BLOCK_TAGGED;
} else if (0 != vp_oper->state.default_vlan) {
qpc->pri_path.vlan_control =
MLX4_VLAN_CTRL_ETH_TX_BLOCK_TAGGED |
MLX4_VLAN_CTRL_ETH_RX_BLOCK_PRIO_TAGGED |
MLX4_VLAN_CTRL_ETH_RX_BLOCK_UNTAGGED;
} else { /* priority tagged */
qpc->pri_path.vlan_control =
MLX4_VLAN_CTRL_ETH_TX_BLOCK_TAGGED |
MLX4_VLAN_CTRL_ETH_RX_BLOCK_TAGGED;
}
qpc->pri_path.fvl_rx |= MLX4_FVL_RX_FORCE_ETH_VLAN;
qpc->pri_path.vlan_index = vp_oper->vlan_idx;
qpc->pri_path.fl |= MLX4_FL_CV | MLX4_FL_ETH_HIDE_CQE_VLAN;
qpc->pri_path.feup |= MLX4_FEUP_FORCE_ETH_UP | MLX4_FVL_FORCE_ETH_VLAN;
qpc->pri_path.sched_queue &= 0xC7;
qpc->pri_path.sched_queue |= (vp_oper->state.default_qos) << 3;
qpc->qos_vport = vp_oper->state.qos_vport;
}
if (vp_oper->state.spoofchk) {
qpc->pri_path.feup |= MLX4_FSM_FORCE_ETH_SRC_MAC;
qpc->pri_path.grh_mylmc = (0x80 & qpc->pri_path.grh_mylmc) + vp_oper->mac_idx;
}
out:
return err;
}
static int mpt_mask(struct mlx4_dev *dev)
{
return dev->caps.num_mpts - 1;
}
static void *find_res(struct mlx4_dev *dev, u64 res_id,
enum mlx4_resource type)
{
struct mlx4_priv *priv = mlx4_priv(dev);
return res_tracker_lookup(&priv->mfunc.master.res_tracker.res_tree[type],
res_id);
}
static int get_res(struct mlx4_dev *dev, int slave, u64 res_id,
enum mlx4_resource type,
void *res)
{
struct res_common *r;
int err = 0;
spin_lock_irq(mlx4_tlock(dev));
r = find_res(dev, res_id, type);
if (!r) {
err = -ENONET;
goto exit;
}
if (r->state == RES_ANY_BUSY) {
err = -EBUSY;
goto exit;
}
if (r->owner != slave) {
err = -EPERM;
goto exit;
}
r->from_state = r->state;
r->state = RES_ANY_BUSY;
if (res)
*((struct res_common **)res) = r;
exit:
spin_unlock_irq(mlx4_tlock(dev));
return err;
}
int mlx4_get_slave_from_resource_id(struct mlx4_dev *dev,
enum mlx4_resource type,
u64 res_id, int *slave)
{
struct res_common *r;
int err = -ENOENT;
int id = res_id;
if (type == RES_QP)
id &= 0x7fffff;
spin_lock(mlx4_tlock(dev));
r = find_res(dev, id, type);
if (r) {
*slave = r->owner;
err = 0;
}
spin_unlock(mlx4_tlock(dev));
return err;
}
static void put_res(struct mlx4_dev *dev, int slave, u64 res_id,
enum mlx4_resource type)
{
struct res_common *r;
spin_lock_irq(mlx4_tlock(dev));
r = find_res(dev, res_id, type);
if (r)
r->state = r->from_state;
spin_unlock_irq(mlx4_tlock(dev));
}
static int counter_alloc_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param, int port);
static int handle_existing_counter(struct mlx4_dev *dev, u8 slave, int port,
int counter_index)
{
struct res_common *r;
struct res_counter *counter;
int ret = 0;
if (counter_index == MLX4_SINK_COUNTER_INDEX(dev))
return ret;
spin_lock_irq(mlx4_tlock(dev));
r = find_res(dev, counter_index, RES_COUNTER);
if (!r || r->owner != slave)
ret = -EINVAL;
counter = container_of(r, struct res_counter, com);
if (!counter->port)
counter->port = port;
spin_unlock_irq(mlx4_tlock(dev));
return ret;
}
static int handle_unexisting_counter(struct mlx4_dev *dev,
struct mlx4_qp_context *qpc, u8 slave,
int port)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct res_common *tmp;
struct res_counter *counter;
u64 counter_idx = MLX4_SINK_COUNTER_INDEX(dev);
int err = 0;
spin_lock_irq(mlx4_tlock(dev));
list_for_each_entry(tmp,
&tracker->slave_list[slave].res_list[RES_COUNTER],
list) {
counter = container_of(tmp, struct res_counter, com);
if (port == counter->port) {
qpc->pri_path.counter_index = counter->com.res_id;
spin_unlock_irq(mlx4_tlock(dev));
return 0;
}
}
spin_unlock_irq(mlx4_tlock(dev));
/* No existing counter, need to allocate a new counter */
err = counter_alloc_res(dev, slave, RES_OP_RESERVE, 0, 0, &counter_idx,
port);
if (err == -ENOENT) {
err = 0;
} else if (err && err != -ENOSPC) {
mlx4_err(dev, "%s: failed to create new counter for slave %d err %d\n",
__func__, slave, err);
} else {
qpc->pri_path.counter_index = counter_idx;
mlx4_dbg(dev, "%s: alloc new counter for slave %d index %d\n",
__func__, slave, qpc->pri_path.counter_index);
err = 0;
}
return err;
}
static int handle_counter(struct mlx4_dev *dev, struct mlx4_qp_context *qpc,
u8 slave, int port)
{
if (qpc->pri_path.counter_index != MLX4_SINK_COUNTER_INDEX(dev))
return handle_existing_counter(dev, slave, port,
qpc->pri_path.counter_index);
return handle_unexisting_counter(dev, qpc, slave, port);
}
static struct res_common *alloc_qp_tr(int id)
{
struct res_qp *ret;
ret = kzalloc(sizeof *ret, GFP_KERNEL);
if (!ret)
return NULL;
ret->com.res_id = id;
ret->com.state = RES_QP_RESERVED;
ret->local_qpn = id;
INIT_LIST_HEAD(&ret->mcg_list);
spin_lock_init(&ret->mcg_spl);
atomic_set(&ret->ref_count, 0);
return &ret->com;
}
static struct res_common *alloc_mtt_tr(int id, int order)
{
struct res_mtt *ret;
ret = kzalloc(sizeof *ret, GFP_KERNEL);
if (!ret)
return NULL;
ret->com.res_id = id;
ret->order = order;
ret->com.state = RES_MTT_ALLOCATED;
atomic_set(&ret->ref_count, 0);
return &ret->com;
}
static struct res_common *alloc_mpt_tr(int id, int key)
{
struct res_mpt *ret;
ret = kzalloc(sizeof *ret, GFP_KERNEL);
if (!ret)
return NULL;
ret->com.res_id = id;
ret->com.state = RES_MPT_RESERVED;
ret->key = key;
return &ret->com;
}
static struct res_common *alloc_eq_tr(int id)
{
struct res_eq *ret;
ret = kzalloc(sizeof *ret, GFP_KERNEL);
if (!ret)
return NULL;
ret->com.res_id = id;
ret->com.state = RES_EQ_RESERVED;
return &ret->com;
}
static struct res_common *alloc_cq_tr(int id)
{
struct res_cq *ret;
ret = kzalloc(sizeof *ret, GFP_KERNEL);
if (!ret)
return NULL;
ret->com.res_id = id;
ret->com.state = RES_CQ_ALLOCATED;
atomic_set(&ret->ref_count, 0);
return &ret->com;
}
static struct res_common *alloc_srq_tr(int id)
{
struct res_srq *ret;
ret = kzalloc(sizeof *ret, GFP_KERNEL);
if (!ret)
return NULL;
ret->com.res_id = id;
ret->com.state = RES_SRQ_ALLOCATED;
atomic_set(&ret->ref_count, 0);
return &ret->com;
}
static struct res_common *alloc_counter_tr(int id, int port)
{
struct res_counter *ret;
ret = kzalloc(sizeof *ret, GFP_KERNEL);
if (!ret)
return NULL;
ret->com.res_id = id;
ret->com.state = RES_COUNTER_ALLOCATED;
ret->port = port;
return &ret->com;
}
static struct res_common *alloc_xrcdn_tr(int id)
{
struct res_xrcdn *ret;
ret = kzalloc(sizeof *ret, GFP_KERNEL);
if (!ret)
return NULL;
ret->com.res_id = id;
ret->com.state = RES_XRCD_ALLOCATED;
return &ret->com;
}
static struct res_common *alloc_fs_rule_tr(u64 id, int qpn)
{
struct res_fs_rule *ret;
ret = kzalloc(sizeof *ret, GFP_KERNEL);
if (!ret)
return NULL;
ret->com.res_id = id;
ret->com.state = RES_FS_RULE_ALLOCATED;
ret->qpn = qpn;
return &ret->com;
}
static struct res_common *alloc_tr(u64 id, enum mlx4_resource type, int slave,
int extra)
{
struct res_common *ret;
switch (type) {
case RES_QP:
ret = alloc_qp_tr(id);
break;
case RES_MPT:
ret = alloc_mpt_tr(id, extra);
break;
case RES_MTT:
ret = alloc_mtt_tr(id, extra);
break;
case RES_EQ:
ret = alloc_eq_tr(id);
break;
case RES_CQ:
ret = alloc_cq_tr(id);
break;
case RES_SRQ:
ret = alloc_srq_tr(id);
break;
case RES_MAC:
pr_err("implementation missing\n");
return NULL;
case RES_COUNTER:
ret = alloc_counter_tr(id, extra);
break;
case RES_XRCD:
ret = alloc_xrcdn_tr(id);
break;
case RES_FS_RULE:
ret = alloc_fs_rule_tr(id, extra);
break;
default:
return NULL;
}
if (ret)
ret->owner = slave;
return ret;
}
int mlx4_calc_vf_counters(struct mlx4_dev *dev, int slave, int port,
struct mlx4_counter *data)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct res_common *tmp;
struct res_counter *counter;
int *counters_arr;
int i = 0, err = 0;
memset(data, 0, sizeof(*data));
counters_arr = kmalloc_array(dev->caps.max_counters,
sizeof(*counters_arr), GFP_KERNEL);
if (!counters_arr)
return -ENOMEM;
spin_lock_irq(mlx4_tlock(dev));
list_for_each_entry(tmp,
&tracker->slave_list[slave].res_list[RES_COUNTER],
list) {
counter = container_of(tmp, struct res_counter, com);
if (counter->port == port) {
counters_arr[i] = (int)tmp->res_id;
i++;
}
}
spin_unlock_irq(mlx4_tlock(dev));
counters_arr[i] = -1;
i = 0;
while (counters_arr[i] != -1) {
err = mlx4_get_counter_stats(dev, counters_arr[i], data,
0);
if (err) {
memset(data, 0, sizeof(*data));
goto table_changed;
}
i++;
}
table_changed:
kfree(counters_arr);
return 0;
}
static int add_res_range(struct mlx4_dev *dev, int slave, u64 base, int count,
enum mlx4_resource type, int extra)
{
int i;
int err;
struct mlx4_priv *priv = mlx4_priv(dev);
struct res_common **res_arr;
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct rb_root *root = &tracker->res_tree[type];
res_arr = kzalloc(count * sizeof *res_arr, GFP_KERNEL);
if (!res_arr)
return -ENOMEM;
for (i = 0; i < count; ++i) {
res_arr[i] = alloc_tr(base + i, type, slave, extra);
if (!res_arr[i]) {
for (--i; i >= 0; --i)
kfree(res_arr[i]);
kfree(res_arr);
return -ENOMEM;
}
}
spin_lock_irq(mlx4_tlock(dev));
for (i = 0; i < count; ++i) {
if (find_res(dev, base + i, type)) {
err = -EEXIST;
goto undo;
}
err = res_tracker_insert(root, res_arr[i]);
if (err)
goto undo;
list_add_tail(&res_arr[i]->list,
&tracker->slave_list[slave].res_list[type]);
}
spin_unlock_irq(mlx4_tlock(dev));
kfree(res_arr);
return 0;
undo:
for (--i; i >= base; --i)
rb_erase(&res_arr[i]->node, root);
spin_unlock_irq(mlx4_tlock(dev));
for (i = 0; i < count; ++i)
kfree(res_arr[i]);
kfree(res_arr);
return err;
}
static int remove_qp_ok(struct res_qp *res)
{
if (res->com.state == RES_QP_BUSY || atomic_read(&res->ref_count) ||
!list_empty(&res->mcg_list)) {
pr_err("resource tracker: fail to remove qp, state %d, ref_count %d\n",
res->com.state, atomic_read(&res->ref_count));
return -EBUSY;
} else if (res->com.state != RES_QP_RESERVED) {
return -EPERM;
}
return 0;
}
static int remove_mtt_ok(struct res_mtt *res, int order)
{
if (res->com.state == RES_MTT_BUSY ||
atomic_read(&res->ref_count)) {
pr_devel("%s-%d: state %s, ref_count %d\n",
__func__, __LINE__,
mtt_states_str(res->com.state),
atomic_read(&res->ref_count));
return -EBUSY;
} else if (res->com.state != RES_MTT_ALLOCATED)
return -EPERM;
else if (res->order != order)
return -EINVAL;
return 0;
}
static int remove_mpt_ok(struct res_mpt *res)
{
if (res->com.state == RES_MPT_BUSY)
return -EBUSY;
else if (res->com.state != RES_MPT_RESERVED)
return -EPERM;
return 0;
}
static int remove_eq_ok(struct res_eq *res)
{
if (res->com.state == RES_MPT_BUSY)
return -EBUSY;
else if (res->com.state != RES_MPT_RESERVED)
return -EPERM;
return 0;
}
static int remove_counter_ok(struct res_counter *res)
{
if (res->com.state == RES_COUNTER_BUSY)
return -EBUSY;
else if (res->com.state != RES_COUNTER_ALLOCATED)
return -EPERM;
return 0;
}
static int remove_xrcdn_ok(struct res_xrcdn *res)
{
if (res->com.state == RES_XRCD_BUSY)
return -EBUSY;
else if (res->com.state != RES_XRCD_ALLOCATED)
return -EPERM;
return 0;
}
static int remove_fs_rule_ok(struct res_fs_rule *res)
{
if (res->com.state == RES_FS_RULE_BUSY)
return -EBUSY;
else if (res->com.state != RES_FS_RULE_ALLOCATED)
return -EPERM;
return 0;
}
static int remove_cq_ok(struct res_cq *res)
{
if (res->com.state == RES_CQ_BUSY)
return -EBUSY;
else if (res->com.state != RES_CQ_ALLOCATED)
return -EPERM;
return 0;
}
static int remove_srq_ok(struct res_srq *res)
{
if (res->com.state == RES_SRQ_BUSY)
return -EBUSY;
else if (res->com.state != RES_SRQ_ALLOCATED)
return -EPERM;
return 0;
}
static int remove_ok(struct res_common *res, enum mlx4_resource type, int extra)
{
switch (type) {
case RES_QP:
return remove_qp_ok((struct res_qp *)res);
case RES_CQ:
return remove_cq_ok((struct res_cq *)res);
case RES_SRQ:
return remove_srq_ok((struct res_srq *)res);
case RES_MPT:
return remove_mpt_ok((struct res_mpt *)res);
case RES_MTT:
return remove_mtt_ok((struct res_mtt *)res, extra);
case RES_MAC:
return -ENOSYS;
case RES_EQ:
return remove_eq_ok((struct res_eq *)res);
case RES_COUNTER:
return remove_counter_ok((struct res_counter *)res);
case RES_XRCD:
return remove_xrcdn_ok((struct res_xrcdn *)res);
case RES_FS_RULE:
return remove_fs_rule_ok((struct res_fs_rule *)res);
default:
return -EINVAL;
}
}
static int rem_res_range(struct mlx4_dev *dev, int slave, u64 base, int count,
enum mlx4_resource type, int extra)
{
u64 i;
int err;
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct res_common *r;
spin_lock_irq(mlx4_tlock(dev));
for (i = base; i < base + count; ++i) {
r = res_tracker_lookup(&tracker->res_tree[type], i);
if (!r) {
err = -ENOENT;
goto out;
}
if (r->owner != slave) {
err = -EPERM;
goto out;
}
err = remove_ok(r, type, extra);
if (err)
goto out;
}
for (i = base; i < base + count; ++i) {
r = res_tracker_lookup(&tracker->res_tree[type], i);
rb_erase(&r->node, &tracker->res_tree[type]);
list_del(&r->list);
kfree(r);
}
err = 0;
out:
spin_unlock_irq(mlx4_tlock(dev));
return err;
}
static int qp_res_start_move_to(struct mlx4_dev *dev, int slave, int qpn,
enum res_qp_states state, struct res_qp **qp,
int alloc)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct res_qp *r;
int err = 0;
spin_lock_irq(mlx4_tlock(dev));
r = res_tracker_lookup(&tracker->res_tree[RES_QP], qpn);
if (!r)
err = -ENOENT;
else if (r->com.owner != slave)
err = -EPERM;
else {
switch (state) {
case RES_QP_BUSY:
mlx4_dbg(dev, "%s: failed RES_QP, 0x%llx\n",
__func__, r->com.res_id);
err = -EBUSY;
break;
case RES_QP_RESERVED:
if (r->com.state == RES_QP_MAPPED && !alloc)
break;
mlx4_dbg(dev, "failed RES_QP, 0x%llx\n", r->com.res_id);
err = -EINVAL;
break;
case RES_QP_MAPPED:
if ((r->com.state == RES_QP_RESERVED && alloc) ||
r->com.state == RES_QP_HW)
break;
else {
mlx4_dbg(dev, "failed RES_QP, 0x%llx\n",
r->com.res_id);
err = -EINVAL;
}
break;
case RES_QP_HW:
if (r->com.state != RES_QP_MAPPED)
err = -EINVAL;
break;
default:
err = -EINVAL;
}
if (!err) {
r->com.from_state = r->com.state;
r->com.to_state = state;
r->com.state = RES_QP_BUSY;
if (qp)
*qp = r;
}
}
spin_unlock_irq(mlx4_tlock(dev));
return err;
}
static int mr_res_start_move_to(struct mlx4_dev *dev, int slave, int index,
enum res_mpt_states state, struct res_mpt **mpt)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct res_mpt *r;
int err = 0;
spin_lock_irq(mlx4_tlock(dev));
r = res_tracker_lookup(&tracker->res_tree[RES_MPT], index);
if (!r)
err = -ENOENT;
else if (r->com.owner != slave)
err = -EPERM;
else {
switch (state) {
case RES_MPT_BUSY:
err = -EINVAL;
break;
case RES_MPT_RESERVED:
if (r->com.state != RES_MPT_MAPPED)
err = -EINVAL;
break;
case RES_MPT_MAPPED:
if (r->com.state != RES_MPT_RESERVED &&
r->com.state != RES_MPT_HW)
err = -EINVAL;
break;
case RES_MPT_HW:
if (r->com.state != RES_MPT_MAPPED)
err = -EINVAL;
break;
default:
err = -EINVAL;
}
if (!err) {
r->com.from_state = r->com.state;
r->com.to_state = state;
r->com.state = RES_MPT_BUSY;
if (mpt)
*mpt = r;
}
}
spin_unlock_irq(mlx4_tlock(dev));
return err;
}
static int eq_res_start_move_to(struct mlx4_dev *dev, int slave, int index,
enum res_eq_states state, struct res_eq **eq)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct res_eq *r;
int err = 0;
spin_lock_irq(mlx4_tlock(dev));
r = res_tracker_lookup(&tracker->res_tree[RES_EQ], index);
if (!r)
err = -ENOENT;
else if (r->com.owner != slave)
err = -EPERM;
else {
switch (state) {
case RES_EQ_BUSY:
err = -EINVAL;
break;
case RES_EQ_RESERVED:
if (r->com.state != RES_EQ_HW)
err = -EINVAL;
break;
case RES_EQ_HW:
if (r->com.state != RES_EQ_RESERVED)
err = -EINVAL;
break;
default:
err = -EINVAL;
}
if (!err) {
r->com.from_state = r->com.state;
r->com.to_state = state;
r->com.state = RES_EQ_BUSY;
if (eq)
*eq = r;
}
}
spin_unlock_irq(mlx4_tlock(dev));
return err;
}
static int cq_res_start_move_to(struct mlx4_dev *dev, int slave, int cqn,
enum res_cq_states state, struct res_cq **cq)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct res_cq *r;
int err;
spin_lock_irq(mlx4_tlock(dev));
r = res_tracker_lookup(&tracker->res_tree[RES_CQ], cqn);
if (!r) {
err = -ENOENT;
} else if (r->com.owner != slave) {
err = -EPERM;
} else if (state == RES_CQ_ALLOCATED) {
if (r->com.state != RES_CQ_HW)
err = -EINVAL;
else if (atomic_read(&r->ref_count))
err = -EBUSY;
else
err = 0;
} else if (state != RES_CQ_HW || r->com.state != RES_CQ_ALLOCATED) {
err = -EINVAL;
} else {
err = 0;
}
if (!err) {
r->com.from_state = r->com.state;
r->com.to_state = state;
r->com.state = RES_CQ_BUSY;
if (cq)
*cq = r;
}
spin_unlock_irq(mlx4_tlock(dev));
return err;
}
static int srq_res_start_move_to(struct mlx4_dev *dev, int slave, int index,
enum res_srq_states state, struct res_srq **srq)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct res_srq *r;
int err = 0;
spin_lock_irq(mlx4_tlock(dev));
r = res_tracker_lookup(&tracker->res_tree[RES_SRQ], index);
if (!r) {
err = -ENOENT;
} else if (r->com.owner != slave) {
err = -EPERM;
} else if (state == RES_SRQ_ALLOCATED) {
if (r->com.state != RES_SRQ_HW)
err = -EINVAL;
else if (atomic_read(&r->ref_count))
err = -EBUSY;
} else if (state != RES_SRQ_HW || r->com.state != RES_SRQ_ALLOCATED) {
err = -EINVAL;
}
if (!err) {
r->com.from_state = r->com.state;
r->com.to_state = state;
r->com.state = RES_SRQ_BUSY;
if (srq)
*srq = r;
}
spin_unlock_irq(mlx4_tlock(dev));
return err;
}
static void res_abort_move(struct mlx4_dev *dev, int slave,
enum mlx4_resource type, int id)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct res_common *r;
spin_lock_irq(mlx4_tlock(dev));
r = res_tracker_lookup(&tracker->res_tree[type], id);
if (r && (r->owner == slave))
r->state = r->from_state;
spin_unlock_irq(mlx4_tlock(dev));
}
static void res_end_move(struct mlx4_dev *dev, int slave,
enum mlx4_resource type, int id)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct res_common *r;
spin_lock_irq(mlx4_tlock(dev));
r = res_tracker_lookup(&tracker->res_tree[type], id);
if (r && (r->owner == slave))
r->state = r->to_state;
spin_unlock_irq(mlx4_tlock(dev));
}
static int valid_reserved(struct mlx4_dev *dev, int slave, int qpn)
{
return mlx4_is_qp_reserved(dev, qpn) &&
(mlx4_is_master(dev) || mlx4_is_guest_proxy(dev, slave, qpn));
}
static int fw_reserved(struct mlx4_dev *dev, int qpn)
{
return qpn < dev->caps.reserved_qps_cnt[MLX4_QP_REGION_FW];
}
static int qp_alloc_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param)
{
int err;
int count;
int align;
int base;
int qpn;
u8 flags;
switch (op) {
case RES_OP_RESERVE:
count = get_param_l(&in_param) & 0xffffff;
/* Turn off all unsupported QP allocation flags that the
* slave tries to set.
*/
flags = (get_param_l(&in_param) >> 24) & dev->caps.alloc_res_qp_mask;
align = get_param_h(&in_param);
err = mlx4_grant_resource(dev, slave, RES_QP, count, 0);
if (err)
return err;
err = __mlx4_qp_reserve_range(dev, count, align, &base, flags);
if (err) {
mlx4_release_resource(dev, slave, RES_QP, count, 0);
return err;
}
err = add_res_range(dev, slave, base, count, RES_QP, 0);
if (err) {
mlx4_release_resource(dev, slave, RES_QP, count, 0);
__mlx4_qp_release_range(dev, base, count);
return err;
}
set_param_l(out_param, base);
break;
case RES_OP_MAP_ICM:
qpn = get_param_l(&in_param) & 0x7fffff;
if (valid_reserved(dev, slave, qpn)) {
err = add_res_range(dev, slave, qpn, 1, RES_QP, 0);
if (err)
return err;
}
err = qp_res_start_move_to(dev, slave, qpn, RES_QP_MAPPED,
NULL, 1);
if (err)
return err;
if (!fw_reserved(dev, qpn)) {
err = __mlx4_qp_alloc_icm(dev, qpn, GFP_KERNEL);
if (err) {
res_abort_move(dev, slave, RES_QP, qpn);
return err;
}
}
res_end_move(dev, slave, RES_QP, qpn);
break;
default:
err = -EINVAL;
break;
}
return err;
}
static int mtt_alloc_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param)
{
int err = -EINVAL;
int base;
int order;
if (op != RES_OP_RESERVE_AND_MAP)
return err;
order = get_param_l(&in_param);
err = mlx4_grant_resource(dev, slave, RES_MTT, 1 << order, 0);
if (err)
return err;
base = __mlx4_alloc_mtt_range(dev, order);
if (base == -1) {
mlx4_release_resource(dev, slave, RES_MTT, 1 << order, 0);
return -ENOMEM;
}
err = add_res_range(dev, slave, base, 1, RES_MTT, order);
if (err) {
mlx4_release_resource(dev, slave, RES_MTT, 1 << order, 0);
__mlx4_free_mtt_range(dev, base, order);
} else {
set_param_l(out_param, base);
}
return err;
}
static int mpt_alloc_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param)
{
int err = -EINVAL;
int index;
int id;
struct res_mpt *mpt;
switch (op) {
case RES_OP_RESERVE:
err = mlx4_grant_resource(dev, slave, RES_MPT, 1, 0);
if (err)
break;
index = __mlx4_mpt_reserve(dev);
if (index == -1) {
mlx4_release_resource(dev, slave, RES_MPT, 1, 0);
break;
}
id = index & mpt_mask(dev);
err = add_res_range(dev, slave, id, 1, RES_MPT, index);
if (err) {
mlx4_release_resource(dev, slave, RES_MPT, 1, 0);
__mlx4_mpt_release(dev, index);
break;
}
set_param_l(out_param, index);
break;
case RES_OP_MAP_ICM:
index = get_param_l(&in_param);
id = index & mpt_mask(dev);
err = mr_res_start_move_to(dev, slave, id,
RES_MPT_MAPPED, &mpt);
if (err)
return err;
err = __mlx4_mpt_alloc_icm(dev, mpt->key, GFP_KERNEL);
if (err) {
res_abort_move(dev, slave, RES_MPT, id);
return err;
}
res_end_move(dev, slave, RES_MPT, id);
break;
}
return err;
}
static int cq_alloc_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param)
{
int cqn;
int err;
switch (op) {
case RES_OP_RESERVE_AND_MAP:
err = mlx4_grant_resource(dev, slave, RES_CQ, 1, 0);
if (err)
break;
err = __mlx4_cq_alloc_icm(dev, &cqn);
if (err) {
mlx4_release_resource(dev, slave, RES_CQ, 1, 0);
break;
}
err = add_res_range(dev, slave, cqn, 1, RES_CQ, 0);
if (err) {
mlx4_release_resource(dev, slave, RES_CQ, 1, 0);
__mlx4_cq_free_icm(dev, cqn);
break;
}
set_param_l(out_param, cqn);
break;
default:
err = -EINVAL;
}
return err;
}
static int srq_alloc_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param)
{
int srqn;
int err;
switch (op) {
case RES_OP_RESERVE_AND_MAP:
err = mlx4_grant_resource(dev, slave, RES_SRQ, 1, 0);
if (err)
break;
err = __mlx4_srq_alloc_icm(dev, &srqn);
if (err) {
mlx4_release_resource(dev, slave, RES_SRQ, 1, 0);
break;
}
err = add_res_range(dev, slave, srqn, 1, RES_SRQ, 0);
if (err) {
mlx4_release_resource(dev, slave, RES_SRQ, 1, 0);
__mlx4_srq_free_icm(dev, srqn);
break;
}
set_param_l(out_param, srqn);
break;
default:
err = -EINVAL;
}
return err;
}
static int mac_find_smac_ix_in_slave(struct mlx4_dev *dev, int slave, int port,
u8 smac_index, u64 *mac)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct list_head *mac_list =
&tracker->slave_list[slave].res_list[RES_MAC];
struct mac_res *res, *tmp;
list_for_each_entry_safe(res, tmp, mac_list, list) {
if (res->smac_index == smac_index && res->port == (u8) port) {
*mac = res->mac;
return 0;
}
}
return -ENOENT;
}
static int mac_add_to_slave(struct mlx4_dev *dev, int slave, u64 mac, int port, u8 smac_index)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct list_head *mac_list =
&tracker->slave_list[slave].res_list[RES_MAC];
struct mac_res *res, *tmp;
list_for_each_entry_safe(res, tmp, mac_list, list) {
if (res->mac == mac && res->port == (u8) port) {
/* mac found. update ref count */
++res->ref_count;
return 0;
}
}
if (mlx4_grant_resource(dev, slave, RES_MAC, 1, port))
return -EINVAL;
res = kzalloc(sizeof *res, GFP_KERNEL);
if (!res) {
mlx4_release_resource(dev, slave, RES_MAC, 1, port);
return -ENOMEM;
}
res->mac = mac;
res->port = (u8) port;
res->smac_index = smac_index;
res->ref_count = 1;
list_add_tail(&res->list,
&tracker->slave_list[slave].res_list[RES_MAC]);
return 0;
}
static void mac_del_from_slave(struct mlx4_dev *dev, int slave, u64 mac,
int port)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct list_head *mac_list =
&tracker->slave_list[slave].res_list[RES_MAC];
struct mac_res *res, *tmp;
list_for_each_entry_safe(res, tmp, mac_list, list) {
if (res->mac == mac && res->port == (u8) port) {
if (!--res->ref_count) {
list_del(&res->list);
mlx4_release_resource(dev, slave, RES_MAC, 1, port);
kfree(res);
}
break;
}
}
}
static void rem_slave_macs(struct mlx4_dev *dev, int slave)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct list_head *mac_list =
&tracker->slave_list[slave].res_list[RES_MAC];
struct mac_res *res, *tmp;
int i;
list_for_each_entry_safe(res, tmp, mac_list, list) {
list_del(&res->list);
/* dereference the mac the num times the slave referenced it */
for (i = 0; i < res->ref_count; i++)
__mlx4_unregister_mac(dev, res->port, res->mac);
mlx4_release_resource(dev, slave, RES_MAC, 1, res->port);
kfree(res);
}
}
static int mac_alloc_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param, int in_port)
{
int err = -EINVAL;
int port;
u64 mac;
u8 smac_index;
if (op != RES_OP_RESERVE_AND_MAP)
return err;
port = !in_port ? get_param_l(out_param) : in_port;
port = mlx4_slave_convert_port(
dev, slave, port);
if (port < 0)
return -EINVAL;
mac = in_param;
err = __mlx4_register_mac(dev, port, mac);
if (err >= 0) {
smac_index = err;
set_param_l(out_param, err);
err = 0;
}
if (!err) {
err = mac_add_to_slave(dev, slave, mac, port, smac_index);
if (err)
__mlx4_unregister_mac(dev, port, mac);
}
return err;
}
static int vlan_add_to_slave(struct mlx4_dev *dev, int slave, u16 vlan,
int port, int vlan_index)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct list_head *vlan_list =
&tracker->slave_list[slave].res_list[RES_VLAN];
struct vlan_res *res, *tmp;
list_for_each_entry_safe(res, tmp, vlan_list, list) {
if (res->vlan == vlan && res->port == (u8) port) {
/* vlan found. update ref count */
++res->ref_count;
return 0;
}
}
if (mlx4_grant_resource(dev, slave, RES_VLAN, 1, port))
return -EINVAL;
res = kzalloc(sizeof(*res), GFP_KERNEL);
if (!res) {
mlx4_release_resource(dev, slave, RES_VLAN, 1, port);
return -ENOMEM;
}
res->vlan = vlan;
res->port = (u8) port;
res->vlan_index = vlan_index;
res->ref_count = 1;
list_add_tail(&res->list,
&tracker->slave_list[slave].res_list[RES_VLAN]);
return 0;
}
static void vlan_del_from_slave(struct mlx4_dev *dev, int slave, u16 vlan,
int port)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct list_head *vlan_list =
&tracker->slave_list[slave].res_list[RES_VLAN];
struct vlan_res *res, *tmp;
list_for_each_entry_safe(res, tmp, vlan_list, list) {
if (res->vlan == vlan && res->port == (u8) port) {
if (!--res->ref_count) {
list_del(&res->list);
mlx4_release_resource(dev, slave, RES_VLAN,
1, port);
kfree(res);
}
break;
}
}
}
static void rem_slave_vlans(struct mlx4_dev *dev, int slave)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct list_head *vlan_list =
&tracker->slave_list[slave].res_list[RES_VLAN];
struct vlan_res *res, *tmp;
int i;
list_for_each_entry_safe(res, tmp, vlan_list, list) {
list_del(&res->list);
/* dereference the vlan the num times the slave referenced it */
for (i = 0; i < res->ref_count; i++)
__mlx4_unregister_vlan(dev, res->port, res->vlan);
mlx4_release_resource(dev, slave, RES_VLAN, 1, res->port);
kfree(res);
}
}
static int vlan_alloc_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param, int in_port)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_slave_state *slave_state = priv->mfunc.master.slave_state;
int err;
u16 vlan;
int vlan_index;
int port;
port = !in_port ? get_param_l(out_param) : in_port;
if (!port || op != RES_OP_RESERVE_AND_MAP)
return -EINVAL;
port = mlx4_slave_convert_port(
dev, slave, port);
if (port < 0)
return -EINVAL;
/* upstream kernels had NOP for reg/unreg vlan. Continue this. */
if (!in_port && port > 0 && port <= dev->caps.num_ports) {
slave_state[slave].old_vlan_api = true;
return 0;
}
vlan = (u16) in_param;
err = __mlx4_register_vlan(dev, port, vlan, &vlan_index);
if (!err) {
set_param_l(out_param, (u32) vlan_index);
err = vlan_add_to_slave(dev, slave, vlan, port, vlan_index);
if (err)
__mlx4_unregister_vlan(dev, port, vlan);
}
return err;
}
static int counter_alloc_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param, int port)
{
u32 index;
int err;
if (op != RES_OP_RESERVE)
return -EINVAL;
err = mlx4_grant_resource(dev, slave, RES_COUNTER, 1, 0);
if (err)
return err;
err = __mlx4_counter_alloc(dev, &index);
if (err) {
mlx4_release_resource(dev, slave, RES_COUNTER, 1, 0);
return err;
}
err = add_res_range(dev, slave, index, 1, RES_COUNTER, port);
if (err) {
__mlx4_counter_free(dev, index);
mlx4_release_resource(dev, slave, RES_COUNTER, 1, 0);
} else {
set_param_l(out_param, index);
}
return err;
}
static int xrcdn_alloc_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param)
{
u32 xrcdn;
int err;
if (op != RES_OP_RESERVE)
return -EINVAL;
err = __mlx4_xrcd_alloc(dev, &xrcdn);
if (err)
return err;
err = add_res_range(dev, slave, xrcdn, 1, RES_XRCD, 0);
if (err)
__mlx4_xrcd_free(dev, xrcdn);
else
set_param_l(out_param, xrcdn);
return err;
}
int mlx4_ALLOC_RES_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
int alop = vhcr->op_modifier;
switch (vhcr->in_modifier & 0xFF) {
case RES_QP:
err = qp_alloc_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param);
break;
case RES_MTT:
err = mtt_alloc_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param);
break;
case RES_MPT:
err = mpt_alloc_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param);
break;
case RES_CQ:
err = cq_alloc_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param);
break;
case RES_SRQ:
err = srq_alloc_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param);
break;
case RES_MAC:
err = mac_alloc_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param,
(vhcr->in_modifier >> 8) & 0xFF);
break;
case RES_VLAN:
err = vlan_alloc_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param,
(vhcr->in_modifier >> 8) & 0xFF);
break;
case RES_COUNTER:
err = counter_alloc_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param, 0);
break;
case RES_XRCD:
err = xrcdn_alloc_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param);
break;
default:
err = -EINVAL;
break;
}
return err;
}
static int qp_free_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param)
{
int err;
int count;
int base;
int qpn;
switch (op) {
case RES_OP_RESERVE:
base = get_param_l(&in_param) & 0x7fffff;
count = get_param_h(&in_param);
err = rem_res_range(dev, slave, base, count, RES_QP, 0);
if (err)
break;
mlx4_release_resource(dev, slave, RES_QP, count, 0);
__mlx4_qp_release_range(dev, base, count);
break;
case RES_OP_MAP_ICM:
qpn = get_param_l(&in_param) & 0x7fffff;
err = qp_res_start_move_to(dev, slave, qpn, RES_QP_RESERVED,
NULL, 0);
if (err)
return err;
if (!fw_reserved(dev, qpn))
__mlx4_qp_free_icm(dev, qpn);
res_end_move(dev, slave, RES_QP, qpn);
if (valid_reserved(dev, slave, qpn))
err = rem_res_range(dev, slave, qpn, 1, RES_QP, 0);
break;
default:
err = -EINVAL;
break;
}
return err;
}
static int mtt_free_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param)
{
int err = -EINVAL;
int base;
int order;
if (op != RES_OP_RESERVE_AND_MAP)
return err;
base = get_param_l(&in_param);
order = get_param_h(&in_param);
err = rem_res_range(dev, slave, base, 1, RES_MTT, order);
if (!err) {
mlx4_release_resource(dev, slave, RES_MTT, 1 << order, 0);
__mlx4_free_mtt_range(dev, base, order);
}
return err;
}
static int mpt_free_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param)
{
int err = -EINVAL;
int index;
int id;
struct res_mpt *mpt;
switch (op) {
case RES_OP_RESERVE:
index = get_param_l(&in_param);
id = index & mpt_mask(dev);
err = get_res(dev, slave, id, RES_MPT, &mpt);
if (err)
break;
index = mpt->key;
put_res(dev, slave, id, RES_MPT);
err = rem_res_range(dev, slave, id, 1, RES_MPT, 0);
if (err)
break;
mlx4_release_resource(dev, slave, RES_MPT, 1, 0);
__mlx4_mpt_release(dev, index);
break;
case RES_OP_MAP_ICM:
index = get_param_l(&in_param);
id = index & mpt_mask(dev);
err = mr_res_start_move_to(dev, slave, id,
RES_MPT_RESERVED, &mpt);
if (err)
return err;
__mlx4_mpt_free_icm(dev, mpt->key);
res_end_move(dev, slave, RES_MPT, id);
return err;
break;
default:
err = -EINVAL;
break;
}
return err;
}
static int cq_free_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param)
{
int cqn;
int err;
switch (op) {
case RES_OP_RESERVE_AND_MAP:
cqn = get_param_l(&in_param);
err = rem_res_range(dev, slave, cqn, 1, RES_CQ, 0);
if (err)
break;
mlx4_release_resource(dev, slave, RES_CQ, 1, 0);
__mlx4_cq_free_icm(dev, cqn);
break;
default:
err = -EINVAL;
break;
}
return err;
}
static int srq_free_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param)
{
int srqn;
int err;
switch (op) {
case RES_OP_RESERVE_AND_MAP:
srqn = get_param_l(&in_param);
err = rem_res_range(dev, slave, srqn, 1, RES_SRQ, 0);
if (err)
break;
mlx4_release_resource(dev, slave, RES_SRQ, 1, 0);
__mlx4_srq_free_icm(dev, srqn);
break;
default:
err = -EINVAL;
break;
}
return err;
}
static int mac_free_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param, int in_port)
{
int port;
int err = 0;
switch (op) {
case RES_OP_RESERVE_AND_MAP:
port = !in_port ? get_param_l(out_param) : in_port;
port = mlx4_slave_convert_port(
dev, slave, port);
if (port < 0)
return -EINVAL;
mac_del_from_slave(dev, slave, in_param, port);
__mlx4_unregister_mac(dev, port, in_param);
break;
default:
err = -EINVAL;
break;
}
return err;
}
static int vlan_free_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param, int port)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_slave_state *slave_state = priv->mfunc.master.slave_state;
int err = 0;
port = mlx4_slave_convert_port(
dev, slave, port);
if (port < 0)
return -EINVAL;
switch (op) {
case RES_OP_RESERVE_AND_MAP:
if (slave_state[slave].old_vlan_api)
return 0;
if (!port)
return -EINVAL;
vlan_del_from_slave(dev, slave, in_param, port);
__mlx4_unregister_vlan(dev, port, in_param);
break;
default:
err = -EINVAL;
break;
}
return err;
}
static int counter_free_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param)
{
int index;
int err;
if (op != RES_OP_RESERVE)
return -EINVAL;
index = get_param_l(&in_param);
if (index == MLX4_SINK_COUNTER_INDEX(dev))
return 0;
err = rem_res_range(dev, slave, index, 1, RES_COUNTER, 0);
if (err)
return err;
__mlx4_counter_free(dev, index);
mlx4_release_resource(dev, slave, RES_COUNTER, 1, 0);
return err;
}
static int xrcdn_free_res(struct mlx4_dev *dev, int slave, int op, int cmd,
u64 in_param, u64 *out_param)
{
int xrcdn;
int err;
if (op != RES_OP_RESERVE)
return -EINVAL;
xrcdn = get_param_l(&in_param);
err = rem_res_range(dev, slave, xrcdn, 1, RES_XRCD, 0);
if (err)
return err;
__mlx4_xrcd_free(dev, xrcdn);
return err;
}
int mlx4_FREE_RES_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err = -EINVAL;
int alop = vhcr->op_modifier;
switch (vhcr->in_modifier & 0xFF) {
case RES_QP:
err = qp_free_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param);
break;
case RES_MTT:
err = mtt_free_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param);
break;
case RES_MPT:
err = mpt_free_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param);
break;
case RES_CQ:
err = cq_free_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param);
break;
case RES_SRQ:
err = srq_free_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param);
break;
case RES_MAC:
err = mac_free_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param,
(vhcr->in_modifier >> 8) & 0xFF);
break;
case RES_VLAN:
err = vlan_free_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param,
(vhcr->in_modifier >> 8) & 0xFF);
break;
case RES_COUNTER:
err = counter_free_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param);
break;
case RES_XRCD:
err = xrcdn_free_res(dev, slave, vhcr->op_modifier, alop,
vhcr->in_param, &vhcr->out_param);
default:
break;
}
return err;
}
/* ugly but other choices are uglier */
static int mr_phys_mpt(struct mlx4_mpt_entry *mpt)
{
return (be32_to_cpu(mpt->flags) >> 9) & 1;
}
static int mr_get_mtt_addr(struct mlx4_mpt_entry *mpt)
{
return (int)be64_to_cpu(mpt->mtt_addr) & 0xfffffff8;
}
static int mr_get_mtt_size(struct mlx4_mpt_entry *mpt)
{
return be32_to_cpu(mpt->mtt_sz);
}
static u32 mr_get_pd(struct mlx4_mpt_entry *mpt)
{
return be32_to_cpu(mpt->pd_flags) & 0x00ffffff;
}
static int mr_is_fmr(struct mlx4_mpt_entry *mpt)
{
return be32_to_cpu(mpt->pd_flags) & MLX4_MPT_PD_FLAG_FAST_REG;
}
static int mr_is_bind_enabled(struct mlx4_mpt_entry *mpt)
{
return be32_to_cpu(mpt->flags) & MLX4_MPT_FLAG_BIND_ENABLE;
}
static int mr_is_region(struct mlx4_mpt_entry *mpt)
{
return be32_to_cpu(mpt->flags) & MLX4_MPT_FLAG_REGION;
}
static int qp_get_mtt_addr(struct mlx4_qp_context *qpc)
{
return be32_to_cpu(qpc->mtt_base_addr_l) & 0xfffffff8;
}
static int srq_get_mtt_addr(struct mlx4_srq_context *srqc)
{
return be32_to_cpu(srqc->mtt_base_addr_l) & 0xfffffff8;
}
static int qp_get_mtt_size(struct mlx4_qp_context *qpc)
{
int page_shift = (qpc->log_page_size & 0x3f) + 12;
int log_sq_size = (qpc->sq_size_stride >> 3) & 0xf;
int log_sq_sride = qpc->sq_size_stride & 7;
int log_rq_size = (qpc->rq_size_stride >> 3) & 0xf;
int log_rq_stride = qpc->rq_size_stride & 7;
int srq = (be32_to_cpu(qpc->srqn) >> 24) & 1;
int rss = (be32_to_cpu(qpc->flags) >> 13) & 1;
u32 ts = (be32_to_cpu(qpc->flags) >> 16) & 0xff;
int xrc = (ts == MLX4_QP_ST_XRC) ? 1 : 0;
int sq_size;
int rq_size;
int total_pages;
int total_mem;
int page_offset = (be32_to_cpu(qpc->params2) >> 6) & 0x3f;
sq_size = 1 << (log_sq_size + log_sq_sride + 4);
rq_size = (srq|rss|xrc) ? 0 : (1 << (log_rq_size + log_rq_stride + 4));
total_mem = sq_size + rq_size;
total_pages =
roundup_pow_of_two((total_mem + (page_offset << 6)) >>
page_shift);
return total_pages;
}
static int check_mtt_range(struct mlx4_dev *dev, int slave, int start,
int size, struct res_mtt *mtt)
{
int res_start = mtt->com.res_id;
int res_size = (1 << mtt->order);
if (start < res_start || start + size > res_start + res_size)
return -EPERM;
return 0;
}
int mlx4_SW2HW_MPT_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
int index = vhcr->in_modifier;
struct res_mtt *mtt;
struct res_mpt *mpt;
int mtt_base = mr_get_mtt_addr(inbox->buf) / dev->caps.mtt_entry_sz;
int phys;
int id;
u32 pd;
int pd_slave;
id = index & mpt_mask(dev);
err = mr_res_start_move_to(dev, slave, id, RES_MPT_HW, &mpt);
if (err)
return err;
/* Disable memory windows for VFs. */
if (!mr_is_region(inbox->buf)) {
err = -EPERM;
goto ex_abort;
}
/* Make sure that the PD bits related to the slave id are zeros. */
pd = mr_get_pd(inbox->buf);
pd_slave = (pd >> 17) & 0x7f;
if (pd_slave != 0 && --pd_slave != slave) {
err = -EPERM;
goto ex_abort;
}
if (mr_is_fmr(inbox->buf)) {
/* FMR and Bind Enable are forbidden in slave devices. */
if (mr_is_bind_enabled(inbox->buf)) {
err = -EPERM;
goto ex_abort;
}
/* FMR and Memory Windows are also forbidden. */
if (!mr_is_region(inbox->buf)) {
err = -EPERM;
goto ex_abort;
}
}
phys = mr_phys_mpt(inbox->buf);
if (!phys) {
err = get_res(dev, slave, mtt_base, RES_MTT, &mtt);
if (err)
goto ex_abort;
err = check_mtt_range(dev, slave, mtt_base,
mr_get_mtt_size(inbox->buf), mtt);
if (err)
goto ex_put;
mpt->mtt = mtt;
}
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
if (err)
goto ex_put;
if (!phys) {
atomic_inc(&mtt->ref_count);
put_res(dev, slave, mtt->com.res_id, RES_MTT);
}
res_end_move(dev, slave, RES_MPT, id);
return 0;
ex_put:
if (!phys)
put_res(dev, slave, mtt->com.res_id, RES_MTT);
ex_abort:
res_abort_move(dev, slave, RES_MPT, id);
return err;
}
int mlx4_HW2SW_MPT_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
int index = vhcr->in_modifier;
struct res_mpt *mpt;
int id;
id = index & mpt_mask(dev);
err = mr_res_start_move_to(dev, slave, id, RES_MPT_MAPPED, &mpt);
if (err)
return err;
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
if (err)
goto ex_abort;
if (mpt->mtt)
atomic_dec(&mpt->mtt->ref_count);
res_end_move(dev, slave, RES_MPT, id);
return 0;
ex_abort:
res_abort_move(dev, slave, RES_MPT, id);
return err;
}
int mlx4_QUERY_MPT_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
int index = vhcr->in_modifier;
struct res_mpt *mpt;
int id;
id = index & mpt_mask(dev);
err = get_res(dev, slave, id, RES_MPT, &mpt);
if (err)
return err;
if (mpt->com.from_state == RES_MPT_MAPPED) {
/* In order to allow rereg in SRIOV, we need to alter the MPT entry. To do
* that, the VF must read the MPT. But since the MPT entry memory is not
* in the VF's virtual memory space, it must use QUERY_MPT to obtain the
* entry contents. To guarantee that the MPT cannot be changed, the driver
* must perform HW2SW_MPT before this query and return the MPT entry to HW
* ownership fofollowing the change. The change here allows the VF to
* perform QUERY_MPT also when the entry is in SW ownership.
*/
struct mlx4_mpt_entry *mpt_entry = mlx4_table_find(
&mlx4_priv(dev)->mr_table.dmpt_table,
mpt->key, NULL);
if (NULL == mpt_entry || NULL == outbox->buf) {
err = -EINVAL;
goto out;
}
memcpy(outbox->buf, mpt_entry, sizeof(*mpt_entry));
err = 0;
} else if (mpt->com.from_state == RES_MPT_HW) {
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
} else {
err = -EBUSY;
goto out;
}
out:
put_res(dev, slave, id, RES_MPT);
return err;
}
static int qp_get_rcqn(struct mlx4_qp_context *qpc)
{
return be32_to_cpu(qpc->cqn_recv) & 0xffffff;
}
static int qp_get_scqn(struct mlx4_qp_context *qpc)
{
return be32_to_cpu(qpc->cqn_send) & 0xffffff;
}
static u32 qp_get_srqn(struct mlx4_qp_context *qpc)
{
return be32_to_cpu(qpc->srqn) & 0x1ffffff;
}
static void adjust_proxy_tun_qkey(struct mlx4_dev *dev, struct mlx4_vhcr *vhcr,
struct mlx4_qp_context *context)
{
u32 qpn = vhcr->in_modifier & 0xffffff;
u32 qkey = 0;
if (mlx4_get_parav_qkey(dev, qpn, &qkey))
return;
/* adjust qkey in qp context */
context->qkey = cpu_to_be32(qkey);
}
static int adjust_qp_sched_queue(struct mlx4_dev *dev, int slave,
struct mlx4_qp_context *qpc,
struct mlx4_cmd_mailbox *inbox);
int mlx4_RST2INIT_QP_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
int qpn = vhcr->in_modifier & 0x7fffff;
struct res_mtt *mtt;
struct res_qp *qp;
struct mlx4_qp_context *qpc = inbox->buf + 8;
int mtt_base = qp_get_mtt_addr(qpc) / dev->caps.mtt_entry_sz;
int mtt_size = qp_get_mtt_size(qpc);
struct res_cq *rcq;
struct res_cq *scq;
int rcqn = qp_get_rcqn(qpc);
int scqn = qp_get_scqn(qpc);
u32 srqn = qp_get_srqn(qpc) & 0xffffff;
int use_srq = (qp_get_srqn(qpc) >> 24) & 1;
struct res_srq *srq;
int local_qpn = be32_to_cpu(qpc->local_qpn) & 0xffffff;
err = adjust_qp_sched_queue(dev, slave, qpc, inbox);
if (err)
return err;
err = qp_res_start_move_to(dev, slave, qpn, RES_QP_HW, &qp, 0);
if (err)
return err;
qp->local_qpn = local_qpn;
qp->sched_queue = 0;
qp->param3 = 0;
qp->vlan_control = 0;
qp->fvl_rx = 0;
qp->pri_path_fl = 0;
qp->vlan_index = 0;
qp->feup = 0;
qp->qpc_flags = be32_to_cpu(qpc->flags);
err = get_res(dev, slave, mtt_base, RES_MTT, &mtt);
if (err)
goto ex_abort;
err = check_mtt_range(dev, slave, mtt_base, mtt_size, mtt);
if (err)
goto ex_put_mtt;
err = get_res(dev, slave, rcqn, RES_CQ, &rcq);
if (err)
goto ex_put_mtt;
if (scqn != rcqn) {
err = get_res(dev, slave, scqn, RES_CQ, &scq);
if (err)
goto ex_put_rcq;
} else
scq = rcq;
if (use_srq) {
err = get_res(dev, slave, srqn, RES_SRQ, &srq);
if (err)
goto ex_put_scq;
}
adjust_proxy_tun_qkey(dev, vhcr, qpc);
update_pkey_index(dev, slave, inbox);
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
if (err)
goto ex_put_srq;
atomic_inc(&mtt->ref_count);
qp->mtt = mtt;
atomic_inc(&rcq->ref_count);
qp->rcq = rcq;
atomic_inc(&scq->ref_count);
qp->scq = scq;
if (scqn != rcqn)
put_res(dev, slave, scqn, RES_CQ);
if (use_srq) {
atomic_inc(&srq->ref_count);
put_res(dev, slave, srqn, RES_SRQ);
qp->srq = srq;
}
put_res(dev, slave, rcqn, RES_CQ);
put_res(dev, slave, mtt_base, RES_MTT);
res_end_move(dev, slave, RES_QP, qpn);
return 0;
ex_put_srq:
if (use_srq)
put_res(dev, slave, srqn, RES_SRQ);
ex_put_scq:
if (scqn != rcqn)
put_res(dev, slave, scqn, RES_CQ);
ex_put_rcq:
put_res(dev, slave, rcqn, RES_CQ);
ex_put_mtt:
put_res(dev, slave, mtt_base, RES_MTT);
ex_abort:
res_abort_move(dev, slave, RES_QP, qpn);
return err;
}
static int eq_get_mtt_addr(struct mlx4_eq_context *eqc)
{
return be32_to_cpu(eqc->mtt_base_addr_l) & 0xfffffff8;
}
static int eq_get_mtt_size(struct mlx4_eq_context *eqc)
{
int log_eq_size = eqc->log_eq_size & 0x1f;
int page_shift = (eqc->log_page_size & 0x3f) + 12;
if (log_eq_size + 5 < page_shift)
return 1;
return 1 << (log_eq_size + 5 - page_shift);
}
static int cq_get_mtt_addr(struct mlx4_cq_context *cqc)
{
return be32_to_cpu(cqc->mtt_base_addr_l) & 0xfffffff8;
}
static int cq_get_mtt_size(struct mlx4_cq_context *cqc)
{
int log_cq_size = (be32_to_cpu(cqc->logsize_usrpage) >> 24) & 0x1f;
int page_shift = (cqc->log_page_size & 0x3f) + 12;
if (log_cq_size + 5 < page_shift)
return 1;
return 1 << (log_cq_size + 5 - page_shift);
}
int mlx4_SW2HW_EQ_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
int eqn = vhcr->in_modifier;
int res_id = (slave << 10) | eqn;
struct mlx4_eq_context *eqc = inbox->buf;
int mtt_base = eq_get_mtt_addr(eqc) / dev->caps.mtt_entry_sz;
int mtt_size = eq_get_mtt_size(eqc);
struct res_eq *eq;
struct res_mtt *mtt;
err = add_res_range(dev, slave, res_id, 1, RES_EQ, 0);
if (err)
return err;
err = eq_res_start_move_to(dev, slave, res_id, RES_EQ_HW, &eq);
if (err)
goto out_add;
err = get_res(dev, slave, mtt_base, RES_MTT, &mtt);
if (err)
goto out_move;
err = check_mtt_range(dev, slave, mtt_base, mtt_size, mtt);
if (err)
goto out_put;
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
if (err)
goto out_put;
atomic_inc(&mtt->ref_count);
eq->mtt = mtt;
put_res(dev, slave, mtt->com.res_id, RES_MTT);
res_end_move(dev, slave, RES_EQ, res_id);
return 0;
out_put:
put_res(dev, slave, mtt->com.res_id, RES_MTT);
out_move:
res_abort_move(dev, slave, RES_EQ, res_id);
out_add:
rem_res_range(dev, slave, res_id, 1, RES_EQ, 0);
return err;
}
int mlx4_CONFIG_DEV_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
u8 get = vhcr->op_modifier;
if (get != 1)
return -EPERM;
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
return err;
}
static int get_containing_mtt(struct mlx4_dev *dev, int slave, int start,
int len, struct res_mtt **res)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct res_mtt *mtt;
int err = -EINVAL;
spin_lock_irq(mlx4_tlock(dev));
list_for_each_entry(mtt, &tracker->slave_list[slave].res_list[RES_MTT],
com.list) {
if (!check_mtt_range(dev, slave, start, len, mtt)) {
*res = mtt;
mtt->com.from_state = mtt->com.state;
mtt->com.state = RES_MTT_BUSY;
err = 0;
break;
}
}
spin_unlock_irq(mlx4_tlock(dev));
return err;
}
static int verify_qp_parameters(struct mlx4_dev *dev,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
enum qp_transition transition, u8 slave)
{
u32 qp_type;
u32 qpn;
struct mlx4_qp_context *qp_ctx;
enum mlx4_qp_optpar optpar;
int port;
int num_gids;
qp_ctx = inbox->buf + 8;
qp_type = (be32_to_cpu(qp_ctx->flags) >> 16) & 0xff;
optpar = be32_to_cpu(*(__be32 *) inbox->buf);
if (slave != mlx4_master_func_num(dev)) {
qp_ctx->params2 &= ~MLX4_QP_BIT_FPP;
/* setting QP rate-limit is disallowed for VFs */
if (qp_ctx->rate_limit_params)
return -EPERM;
}
switch (qp_type) {
case MLX4_QP_ST_RC:
case MLX4_QP_ST_XRC:
case MLX4_QP_ST_UC:
switch (transition) {
case QP_TRANS_INIT2RTR:
case QP_TRANS_RTR2RTS:
case QP_TRANS_RTS2RTS:
case QP_TRANS_SQD2SQD:
case QP_TRANS_SQD2RTS:
if (slave != mlx4_master_func_num(dev))
if (optpar & MLX4_QP_OPTPAR_PRIMARY_ADDR_PATH) {
port = (qp_ctx->pri_path.sched_queue >> 6 & 1) + 1;
if (dev->caps.port_mask[port] != MLX4_PORT_TYPE_IB)
num_gids = mlx4_get_slave_num_gids(dev, slave, port);
else
num_gids = 1;
if (qp_ctx->pri_path.mgid_index >= num_gids)
return -EINVAL;
}
if (optpar & MLX4_QP_OPTPAR_ALT_ADDR_PATH) {
port = (qp_ctx->alt_path.sched_queue >> 6 & 1) + 1;
if (dev->caps.port_mask[port] != MLX4_PORT_TYPE_IB)
num_gids = mlx4_get_slave_num_gids(dev, slave, port);
else
num_gids = 1;
if (qp_ctx->alt_path.mgid_index >= num_gids)
return -EINVAL;
}
break;
default:
break;
}
break;
case MLX4_QP_ST_MLX:
qpn = vhcr->in_modifier & 0x7fffff;
port = (qp_ctx->pri_path.sched_queue >> 6 & 1) + 1;
if (transition == QP_TRANS_INIT2RTR &&
slave != mlx4_master_func_num(dev) &&
mlx4_is_qp_reserved(dev, qpn) &&
!mlx4_vf_smi_enabled(dev, slave, port)) {
/* only enabled VFs may create MLX proxy QPs */
mlx4_err(dev, "%s: unprivileged slave %d attempting to create an MLX proxy special QP on port %d\n",
__func__, slave, port);
return -EPERM;
}
break;
default:
break;
}
return 0;
}
int mlx4_WRITE_MTT_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
struct mlx4_mtt mtt;
__be64 *page_list = inbox->buf;
u64 *pg_list = (u64 *)page_list;
int i;
struct res_mtt *rmtt = NULL;
int start = be64_to_cpu(page_list[0]);
int npages = vhcr->in_modifier;
int err;
err = get_containing_mtt(dev, slave, start, npages, &rmtt);
if (err)
return err;
/* Call the SW implementation of write_mtt:
* - Prepare a dummy mtt struct
* - Translate inbox contents to simple addresses in host endianness */
mtt.offset = 0; /* TBD this is broken but I don't handle it since
we don't really use it */
mtt.order = 0;
mtt.page_shift = 0;
for (i = 0; i < npages; ++i)
pg_list[i + 2] = (be64_to_cpu(page_list[i + 2]) & ~1ULL);
err = __mlx4_write_mtt(dev, &mtt, be64_to_cpu(page_list[0]), npages,
((u64 *)page_list + 2));
if (rmtt)
put_res(dev, slave, rmtt->com.res_id, RES_MTT);
return err;
}
int mlx4_HW2SW_EQ_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int eqn = vhcr->in_modifier;
int res_id = eqn | (slave << 10);
struct res_eq *eq;
int err;
err = eq_res_start_move_to(dev, slave, res_id, RES_EQ_RESERVED, &eq);
if (err)
return err;
err = get_res(dev, slave, eq->mtt->com.res_id, RES_MTT, NULL);
if (err)
goto ex_abort;
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
if (err)
goto ex_put;
atomic_dec(&eq->mtt->ref_count);
put_res(dev, slave, eq->mtt->com.res_id, RES_MTT);
res_end_move(dev, slave, RES_EQ, res_id);
rem_res_range(dev, slave, res_id, 1, RES_EQ, 0);
return 0;
ex_put:
put_res(dev, slave, eq->mtt->com.res_id, RES_MTT);
ex_abort:
res_abort_move(dev, slave, RES_EQ, res_id);
return err;
}
int mlx4_GEN_EQE(struct mlx4_dev *dev, int slave, struct mlx4_eqe *eqe)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_slave_event_eq_info *event_eq;
struct mlx4_cmd_mailbox *mailbox;
u32 in_modifier = 0;
int err;
int res_id;
struct res_eq *req;
if (!priv->mfunc.master.slave_state)
return -EINVAL;
/* check for slave valid, slave not PF, and slave active */
if (slave < 0 || slave > dev->persist->num_vfs ||
slave == dev->caps.function ||
!priv->mfunc.master.slave_state[slave].active)
return 0;
event_eq = &priv->mfunc.master.slave_state[slave].event_eq[eqe->type];
/* Create the event only if the slave is registered */
if (event_eq->eqn < 0)
return 0;
mutex_lock(&priv->mfunc.master.gen_eqe_mutex[slave]);
res_id = (slave << 10) | event_eq->eqn;
err = get_res(dev, slave, res_id, RES_EQ, &req);
if (err)
goto unlock;
if (req->com.from_state != RES_EQ_HW) {
err = -EINVAL;
goto put;
}
mailbox = mlx4_alloc_cmd_mailbox(dev);
if (IS_ERR(mailbox)) {
err = PTR_ERR(mailbox);
goto put;
}
if (eqe->type == MLX4_EVENT_TYPE_CMD) {
++event_eq->token;
eqe->event.cmd.token = cpu_to_be16(event_eq->token);
}
memcpy(mailbox->buf, (u8 *) eqe, 28);
in_modifier = (slave & 0xff) | ((event_eq->eqn & 0x3ff) << 16);
err = mlx4_cmd(dev, mailbox->dma, in_modifier, 0,
MLX4_CMD_GEN_EQE, MLX4_CMD_TIME_CLASS_B,
MLX4_CMD_NATIVE);
put_res(dev, slave, res_id, RES_EQ);
mutex_unlock(&priv->mfunc.master.gen_eqe_mutex[slave]);
mlx4_free_cmd_mailbox(dev, mailbox);
return err;
put:
put_res(dev, slave, res_id, RES_EQ);
unlock:
mutex_unlock(&priv->mfunc.master.gen_eqe_mutex[slave]);
return err;
}
int mlx4_QUERY_EQ_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int eqn = vhcr->in_modifier;
int res_id = eqn | (slave << 10);
struct res_eq *eq;
int err;
err = get_res(dev, slave, res_id, RES_EQ, &eq);
if (err)
return err;
if (eq->com.from_state != RES_EQ_HW) {
err = -EINVAL;
goto ex_put;
}
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
ex_put:
put_res(dev, slave, res_id, RES_EQ);
return err;
}
int mlx4_SW2HW_CQ_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
int cqn = vhcr->in_modifier;
struct mlx4_cq_context *cqc = inbox->buf;
int mtt_base = cq_get_mtt_addr(cqc) / dev->caps.mtt_entry_sz;
struct res_cq *cq = NULL;
struct res_mtt *mtt;
err = cq_res_start_move_to(dev, slave, cqn, RES_CQ_HW, &cq);
if (err)
return err;
err = get_res(dev, slave, mtt_base, RES_MTT, &mtt);
if (err)
goto out_move;
err = check_mtt_range(dev, slave, mtt_base, cq_get_mtt_size(cqc), mtt);
if (err)
goto out_put;
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
if (err)
goto out_put;
atomic_inc(&mtt->ref_count);
cq->mtt = mtt;
put_res(dev, slave, mtt->com.res_id, RES_MTT);
res_end_move(dev, slave, RES_CQ, cqn);
return 0;
out_put:
put_res(dev, slave, mtt->com.res_id, RES_MTT);
out_move:
res_abort_move(dev, slave, RES_CQ, cqn);
return err;
}
int mlx4_HW2SW_CQ_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
int cqn = vhcr->in_modifier;
struct res_cq *cq = NULL;
err = cq_res_start_move_to(dev, slave, cqn, RES_CQ_ALLOCATED, &cq);
if (err)
return err;
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
if (err)
goto out_move;
atomic_dec(&cq->mtt->ref_count);
res_end_move(dev, slave, RES_CQ, cqn);
return 0;
out_move:
res_abort_move(dev, slave, RES_CQ, cqn);
return err;
}
int mlx4_QUERY_CQ_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int cqn = vhcr->in_modifier;
struct res_cq *cq;
int err;
err = get_res(dev, slave, cqn, RES_CQ, &cq);
if (err)
return err;
if (cq->com.from_state != RES_CQ_HW)
goto ex_put;
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
ex_put:
put_res(dev, slave, cqn, RES_CQ);
return err;
}
static int handle_resize(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd,
struct res_cq *cq)
{
int err;
struct res_mtt *orig_mtt;
struct res_mtt *mtt;
struct mlx4_cq_context *cqc = inbox->buf;
int mtt_base = cq_get_mtt_addr(cqc) / dev->caps.mtt_entry_sz;
err = get_res(dev, slave, cq->mtt->com.res_id, RES_MTT, &orig_mtt);
if (err)
return err;
if (orig_mtt != cq->mtt) {
err = -EINVAL;
goto ex_put;
}
err = get_res(dev, slave, mtt_base, RES_MTT, &mtt);
if (err)
goto ex_put;
err = check_mtt_range(dev, slave, mtt_base, cq_get_mtt_size(cqc), mtt);
if (err)
goto ex_put1;
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
if (err)
goto ex_put1;
atomic_dec(&orig_mtt->ref_count);
put_res(dev, slave, orig_mtt->com.res_id, RES_MTT);
atomic_inc(&mtt->ref_count);
cq->mtt = mtt;
put_res(dev, slave, mtt->com.res_id, RES_MTT);
return 0;
ex_put1:
put_res(dev, slave, mtt->com.res_id, RES_MTT);
ex_put:
put_res(dev, slave, orig_mtt->com.res_id, RES_MTT);
return err;
}
int mlx4_MODIFY_CQ_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int cqn = vhcr->in_modifier;
struct res_cq *cq;
int err;
err = get_res(dev, slave, cqn, RES_CQ, &cq);
if (err)
return err;
if (cq->com.from_state != RES_CQ_HW)
goto ex_put;
if (vhcr->op_modifier == 0) {
err = handle_resize(dev, slave, vhcr, inbox, outbox, cmd, cq);
goto ex_put;
}
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
ex_put:
put_res(dev, slave, cqn, RES_CQ);
return err;
}
static int srq_get_mtt_size(struct mlx4_srq_context *srqc)
{
int log_srq_size = (be32_to_cpu(srqc->state_logsize_srqn) >> 24) & 0xf;
int log_rq_stride = srqc->logstride & 7;
int page_shift = (srqc->log_page_size & 0x3f) + 12;
if (log_srq_size + log_rq_stride + 4 < page_shift)
return 1;
return 1 << (log_srq_size + log_rq_stride + 4 - page_shift);
}
int mlx4_SW2HW_SRQ_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
int srqn = vhcr->in_modifier;
struct res_mtt *mtt;
struct res_srq *srq = NULL;
struct mlx4_srq_context *srqc = inbox->buf;
int mtt_base = srq_get_mtt_addr(srqc) / dev->caps.mtt_entry_sz;
if (srqn != (be32_to_cpu(srqc->state_logsize_srqn) & 0xffffff))
return -EINVAL;
err = srq_res_start_move_to(dev, slave, srqn, RES_SRQ_HW, &srq);
if (err)
return err;
err = get_res(dev, slave, mtt_base, RES_MTT, &mtt);
if (err)
goto ex_abort;
err = check_mtt_range(dev, slave, mtt_base, srq_get_mtt_size(srqc),
mtt);
if (err)
goto ex_put_mtt;
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
if (err)
goto ex_put_mtt;
atomic_inc(&mtt->ref_count);
srq->mtt = mtt;
put_res(dev, slave, mtt->com.res_id, RES_MTT);
res_end_move(dev, slave, RES_SRQ, srqn);
return 0;
ex_put_mtt:
put_res(dev, slave, mtt->com.res_id, RES_MTT);
ex_abort:
res_abort_move(dev, slave, RES_SRQ, srqn);
return err;
}
int mlx4_HW2SW_SRQ_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
int srqn = vhcr->in_modifier;
struct res_srq *srq = NULL;
err = srq_res_start_move_to(dev, slave, srqn, RES_SRQ_ALLOCATED, &srq);
if (err)
return err;
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
if (err)
goto ex_abort;
atomic_dec(&srq->mtt->ref_count);
if (srq->cq)
atomic_dec(&srq->cq->ref_count);
res_end_move(dev, slave, RES_SRQ, srqn);
return 0;
ex_abort:
res_abort_move(dev, slave, RES_SRQ, srqn);
return err;
}
int mlx4_QUERY_SRQ_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
int srqn = vhcr->in_modifier;
struct res_srq *srq;
err = get_res(dev, slave, srqn, RES_SRQ, &srq);
if (err)
return err;
if (srq->com.from_state != RES_SRQ_HW) {
err = -EBUSY;
goto out;
}
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
out:
put_res(dev, slave, srqn, RES_SRQ);
return err;
}
int mlx4_ARM_SRQ_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
int srqn = vhcr->in_modifier;
struct res_srq *srq;
err = get_res(dev, slave, srqn, RES_SRQ, &srq);
if (err)
return err;
if (srq->com.from_state != RES_SRQ_HW) {
err = -EBUSY;
goto out;
}
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
out:
put_res(dev, slave, srqn, RES_SRQ);
return err;
}
int mlx4_GEN_QP_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
int qpn = vhcr->in_modifier & 0x7fffff;
struct res_qp *qp;
err = get_res(dev, slave, qpn, RES_QP, &qp);
if (err)
return err;
if (qp->com.from_state != RES_QP_HW) {
err = -EBUSY;
goto out;
}
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
out:
put_res(dev, slave, qpn, RES_QP);
return err;
}
int mlx4_INIT2INIT_QP_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
struct mlx4_qp_context *context = inbox->buf + 8;
adjust_proxy_tun_qkey(dev, vhcr, context);
update_pkey_index(dev, slave, inbox);
return mlx4_GEN_QP_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
}
static int adjust_qp_sched_queue(struct mlx4_dev *dev, int slave,
struct mlx4_qp_context *qpc,
struct mlx4_cmd_mailbox *inbox)
{
enum mlx4_qp_optpar optpar = be32_to_cpu(*(__be32 *)inbox->buf);
u8 pri_sched_queue;
int port = mlx4_slave_convert_port(
dev, slave, (qpc->pri_path.sched_queue >> 6 & 1) + 1) - 1;
if (port < 0)
return -EINVAL;
pri_sched_queue = (qpc->pri_path.sched_queue & ~(1 << 6)) |
((port & 1) << 6);
if (optpar & (MLX4_QP_OPTPAR_PRIMARY_ADDR_PATH | MLX4_QP_OPTPAR_SCHED_QUEUE) ||
qpc->pri_path.sched_queue || mlx4_is_eth(dev, port + 1)) {
qpc->pri_path.sched_queue = pri_sched_queue;
}
if (optpar & MLX4_QP_OPTPAR_ALT_ADDR_PATH) {
port = mlx4_slave_convert_port(
dev, slave, (qpc->alt_path.sched_queue >> 6 & 1)
+ 1) - 1;
if (port < 0)
return -EINVAL;
qpc->alt_path.sched_queue =
(qpc->alt_path.sched_queue & ~(1 << 6)) |
(port & 1) << 6;
}
return 0;
}
static int roce_verify_mac(struct mlx4_dev *dev, int slave,
struct mlx4_qp_context *qpc,
struct mlx4_cmd_mailbox *inbox)
{
u64 mac;
int port;
u32 ts = (be32_to_cpu(qpc->flags) >> 16) & 0xff;
u8 sched = *(u8 *)(inbox->buf + 64);
u8 smac_ix;
port = (sched >> 6 & 1) + 1;
if (mlx4_is_eth(dev, port) && (ts != MLX4_QP_ST_MLX)) {
smac_ix = qpc->pri_path.grh_mylmc & 0x7f;
if (mac_find_smac_ix_in_slave(dev, slave, port, smac_ix, &mac))
return -ENOENT;
}
return 0;
}
int mlx4_INIT2RTR_QP_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
struct mlx4_qp_context *qpc = inbox->buf + 8;
int qpn = vhcr->in_modifier & 0x7fffff;
struct res_qp *qp;
u8 orig_sched_queue;
__be32 orig_param3 = qpc->param3;
u8 orig_vlan_control = qpc->pri_path.vlan_control;
u8 orig_fvl_rx = qpc->pri_path.fvl_rx;
u8 orig_pri_path_fl = qpc->pri_path.fl;
u8 orig_vlan_index = qpc->pri_path.vlan_index;
u8 orig_feup = qpc->pri_path.feup;
err = adjust_qp_sched_queue(dev, slave, qpc, inbox);
if (err)
return err;
err = verify_qp_parameters(dev, vhcr, inbox, QP_TRANS_INIT2RTR, slave);
if (err)
return err;
if (roce_verify_mac(dev, slave, qpc, inbox))
return -EINVAL;
update_pkey_index(dev, slave, inbox);
update_gid(dev, inbox, (u8)slave);
adjust_proxy_tun_qkey(dev, vhcr, qpc);
orig_sched_queue = qpc->pri_path.sched_queue;
err = update_vport_qp_param(dev, inbox, slave, qpn);
if (err)
return err;
err = get_res(dev, slave, qpn, RES_QP, &qp);
if (err)
return err;
if (qp->com.from_state != RES_QP_HW) {
err = -EBUSY;
goto out;
}
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
out:
/* if no error, save sched queue value passed in by VF. This is
* essentially the QOS value provided by the VF. This will be useful
* if we allow dynamic changes from VST back to VGT
*/
if (!err) {
qp->sched_queue = orig_sched_queue;
qp->param3 = orig_param3;
qp->vlan_control = orig_vlan_control;
qp->fvl_rx = orig_fvl_rx;
qp->pri_path_fl = orig_pri_path_fl;
qp->vlan_index = orig_vlan_index;
qp->feup = orig_feup;
}
put_res(dev, slave, qpn, RES_QP);
return err;
}
int mlx4_RTR2RTS_QP_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
struct mlx4_qp_context *context = inbox->buf + 8;
err = adjust_qp_sched_queue(dev, slave, context, inbox);
if (err)
return err;
err = verify_qp_parameters(dev, vhcr, inbox, QP_TRANS_RTR2RTS, slave);
if (err)
return err;
update_pkey_index(dev, slave, inbox);
update_gid(dev, inbox, (u8)slave);
adjust_proxy_tun_qkey(dev, vhcr, context);
return mlx4_GEN_QP_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
}
int mlx4_RTS2RTS_QP_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
struct mlx4_qp_context *context = inbox->buf + 8;
err = adjust_qp_sched_queue(dev, slave, context, inbox);
if (err)
return err;
err = verify_qp_parameters(dev, vhcr, inbox, QP_TRANS_RTS2RTS, slave);
if (err)
return err;
update_pkey_index(dev, slave, inbox);
update_gid(dev, inbox, (u8)slave);
adjust_proxy_tun_qkey(dev, vhcr, context);
return mlx4_GEN_QP_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
}
int mlx4_SQERR2RTS_QP_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
struct mlx4_qp_context *context = inbox->buf + 8;
int err = adjust_qp_sched_queue(dev, slave, context, inbox);
if (err)
return err;
adjust_proxy_tun_qkey(dev, vhcr, context);
return mlx4_GEN_QP_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
}
int mlx4_SQD2SQD_QP_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
struct mlx4_qp_context *context = inbox->buf + 8;
err = adjust_qp_sched_queue(dev, slave, context, inbox);
if (err)
return err;
err = verify_qp_parameters(dev, vhcr, inbox, QP_TRANS_SQD2SQD, slave);
if (err)
return err;
adjust_proxy_tun_qkey(dev, vhcr, context);
update_gid(dev, inbox, (u8)slave);
update_pkey_index(dev, slave, inbox);
return mlx4_GEN_QP_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
}
int mlx4_SQD2RTS_QP_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
struct mlx4_qp_context *context = inbox->buf + 8;
err = adjust_qp_sched_queue(dev, slave, context, inbox);
if (err)
return err;
err = verify_qp_parameters(dev, vhcr, inbox, QP_TRANS_SQD2RTS, slave);
if (err)
return err;
adjust_proxy_tun_qkey(dev, vhcr, context);
update_gid(dev, inbox, (u8)slave);
update_pkey_index(dev, slave, inbox);
return mlx4_GEN_QP_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
}
int mlx4_2RST_QP_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
int qpn = vhcr->in_modifier & 0x7fffff;
struct res_qp *qp;
err = qp_res_start_move_to(dev, slave, qpn, RES_QP_MAPPED, &qp, 0);
if (err)
return err;
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
if (err)
goto ex_abort;
atomic_dec(&qp->mtt->ref_count);
atomic_dec(&qp->rcq->ref_count);
atomic_dec(&qp->scq->ref_count);
if (qp->srq)
atomic_dec(&qp->srq->ref_count);
res_end_move(dev, slave, RES_QP, qpn);
return 0;
ex_abort:
res_abort_move(dev, slave, RES_QP, qpn);
return err;
}
static struct res_gid *find_gid(struct mlx4_dev *dev, int slave,
struct res_qp *rqp, u8 *gid)
{
struct res_gid *res;
list_for_each_entry(res, &rqp->mcg_list, list) {
if (!memcmp(res->gid, gid, 16))
return res;
}
return NULL;
}
static int add_mcg_res(struct mlx4_dev *dev, int slave, struct res_qp *rqp,
u8 *gid, enum mlx4_protocol prot,
enum mlx4_steer_type steer, u64 reg_id)
{
struct res_gid *res;
int err;
res = kzalloc(sizeof *res, GFP_KERNEL);
if (!res)
return -ENOMEM;
spin_lock_irq(&rqp->mcg_spl);
if (find_gid(dev, slave, rqp, gid)) {
kfree(res);
err = -EEXIST;
} else {
memcpy(res->gid, gid, 16);
res->prot = prot;
res->steer = steer;
res->reg_id = reg_id;
list_add_tail(&res->list, &rqp->mcg_list);
err = 0;
}
spin_unlock_irq(&rqp->mcg_spl);
return err;
}
static int rem_mcg_res(struct mlx4_dev *dev, int slave, struct res_qp *rqp,
u8 *gid, enum mlx4_protocol prot,
enum mlx4_steer_type steer, u64 *reg_id)
{
struct res_gid *res;
int err;
spin_lock_irq(&rqp->mcg_spl);
res = find_gid(dev, slave, rqp, gid);
if (!res || res->prot != prot || res->steer != steer)
err = -EINVAL;
else {
*reg_id = res->reg_id;
list_del(&res->list);
kfree(res);
err = 0;
}
spin_unlock_irq(&rqp->mcg_spl);
return err;
}
static int qp_attach(struct mlx4_dev *dev, int slave, struct mlx4_qp *qp,
u8 gid[16], int block_loopback, enum mlx4_protocol prot,
enum mlx4_steer_type type, u64 *reg_id)
{
switch (dev->caps.steering_mode) {
case MLX4_STEERING_MODE_DEVICE_MANAGED: {
int port = mlx4_slave_convert_port(dev, slave, gid[5]);
if (port < 0)
return port;
return mlx4_trans_to_dmfs_attach(dev, qp, gid, port,
block_loopback, prot,
reg_id);
}
case MLX4_STEERING_MODE_B0:
if (prot == MLX4_PROT_ETH) {
int port = mlx4_slave_convert_port(dev, slave, gid[5]);
if (port < 0)
return port;
gid[5] = port;
}
return mlx4_qp_attach_common(dev, qp, gid,
block_loopback, prot, type);
default:
return -EINVAL;
}
}
static int qp_detach(struct mlx4_dev *dev, struct mlx4_qp *qp,
u8 gid[16], enum mlx4_protocol prot,
enum mlx4_steer_type type, u64 reg_id)
{
switch (dev->caps.steering_mode) {
case MLX4_STEERING_MODE_DEVICE_MANAGED:
return mlx4_flow_detach(dev, reg_id);
case MLX4_STEERING_MODE_B0:
return mlx4_qp_detach_common(dev, qp, gid, prot, type);
default:
return -EINVAL;
}
}
static int mlx4_adjust_port(struct mlx4_dev *dev, int slave,
u8 *gid, enum mlx4_protocol prot)
{
int real_port;
if (prot != MLX4_PROT_ETH)
return 0;
if (dev->caps.steering_mode == MLX4_STEERING_MODE_B0 ||
dev->caps.steering_mode == MLX4_STEERING_MODE_DEVICE_MANAGED) {
real_port = mlx4_slave_convert_port(dev, slave, gid[5]);
if (real_port < 0)
return -EINVAL;
gid[5] = real_port;
}
return 0;
}
int mlx4_QP_ATTACH_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
struct mlx4_qp qp; /* dummy for calling attach/detach */
u8 *gid = inbox->buf;
enum mlx4_protocol prot = (vhcr->in_modifier >> 28) & 0x7;
int err;
int qpn;
struct res_qp *rqp;
u64 reg_id = 0;
int attach = vhcr->op_modifier;
int block_loopback = vhcr->in_modifier >> 31;
u8 steer_type_mask = 2;
enum mlx4_steer_type type = (gid[7] & steer_type_mask) >> 1;
qpn = vhcr->in_modifier & 0xffffff;
err = get_res(dev, slave, qpn, RES_QP, &rqp);
if (err)
return err;
qp.qpn = qpn;
if (attach) {
err = qp_attach(dev, slave, &qp, gid, block_loopback, prot,
type, ®_id);
if (err) {
pr_err("Fail to attach rule to qp 0x%x\n", qpn);
goto ex_put;
}
err = add_mcg_res(dev, slave, rqp, gid, prot, type, reg_id);
if (err)
goto ex_detach;
} else {
err = mlx4_adjust_port(dev, slave, gid, prot);
if (err)
goto ex_put;
err = rem_mcg_res(dev, slave, rqp, gid, prot, type, ®_id);
if (err)
goto ex_put;
err = qp_detach(dev, &qp, gid, prot, type, reg_id);
if (err)
pr_err("Fail to detach rule from qp 0x%x reg_id = 0x%llx\n",
qpn, reg_id);
}
put_res(dev, slave, qpn, RES_QP);
return err;
ex_detach:
qp_detach(dev, &qp, gid, prot, type, reg_id);
ex_put:
put_res(dev, slave, qpn, RES_QP);
return err;
}
/*
* MAC validation for Flow Steering rules.
* VF can attach rules only with a mac address which is assigned to it.
*/
static int validate_eth_header_mac(int slave, struct _rule_hw *eth_header,
struct list_head *rlist)
{
struct mac_res *res, *tmp;
__be64 be_mac;
/* make sure it isn't multicast or broadcast mac*/
if (!is_multicast_ether_addr(eth_header->eth.dst_mac) &&
!is_broadcast_ether_addr(eth_header->eth.dst_mac)) {
list_for_each_entry_safe(res, tmp, rlist, list) {
be_mac = cpu_to_be64(res->mac << 16);
if (ether_addr_equal((u8 *)&be_mac, eth_header->eth.dst_mac))
return 0;
}
pr_err("MAC %pM doesn't belong to VF %d, Steering rule rejected\n",
eth_header->eth.dst_mac, slave);
return -EINVAL;
}
return 0;
}
static void handle_eth_header_mcast_prio(struct mlx4_net_trans_rule_hw_ctrl *ctrl,
struct _rule_hw *eth_header)
{
if (is_multicast_ether_addr(eth_header->eth.dst_mac) ||
is_broadcast_ether_addr(eth_header->eth.dst_mac)) {
struct mlx4_net_trans_rule_hw_eth *eth =
(struct mlx4_net_trans_rule_hw_eth *)eth_header;
struct _rule_hw *next_rule = (struct _rule_hw *)(eth + 1);
bool last_rule = next_rule->size == 0 && next_rule->id == 0 &&
next_rule->rsvd == 0;
if (last_rule)
ctrl->prio = cpu_to_be16(MLX4_DOMAIN_NIC);
}
}
/*
* In case of missing eth header, append eth header with a MAC address
* assigned to the VF.
*/
static int add_eth_header(struct mlx4_dev *dev, int slave,
struct mlx4_cmd_mailbox *inbox,
struct list_head *rlist, int header_id)
{
struct mac_res *res, *tmp;
u8 port;
struct mlx4_net_trans_rule_hw_ctrl *ctrl;
struct mlx4_net_trans_rule_hw_eth *eth_header;
struct mlx4_net_trans_rule_hw_ipv4 *ip_header;
struct mlx4_net_trans_rule_hw_tcp_udp *l4_header;
__be64 be_mac = 0;
__be64 mac_msk = cpu_to_be64(MLX4_MAC_MASK << 16);
ctrl = (struct mlx4_net_trans_rule_hw_ctrl *)inbox->buf;
port = ctrl->port;
eth_header = (struct mlx4_net_trans_rule_hw_eth *)(ctrl + 1);
/* Clear a space in the inbox for eth header */
switch (header_id) {
case MLX4_NET_TRANS_RULE_ID_IPV4:
ip_header =
(struct mlx4_net_trans_rule_hw_ipv4 *)(eth_header + 1);
memmove(ip_header, eth_header,
sizeof(*ip_header) + sizeof(*l4_header));
break;
case MLX4_NET_TRANS_RULE_ID_TCP:
case MLX4_NET_TRANS_RULE_ID_UDP:
l4_header = (struct mlx4_net_trans_rule_hw_tcp_udp *)
(eth_header + 1);
memmove(l4_header, eth_header, sizeof(*l4_header));
break;
default:
return -EINVAL;
}
list_for_each_entry_safe(res, tmp, rlist, list) {
if (port == res->port) {
be_mac = cpu_to_be64(res->mac << 16);
break;
}
}
if (!be_mac) {
pr_err("Failed adding eth header to FS rule, Can't find matching MAC for port %d\n",
port);
return -EINVAL;
}
memset(eth_header, 0, sizeof(*eth_header));
eth_header->size = sizeof(*eth_header) >> 2;
eth_header->id = cpu_to_be16(__sw_id_hw[MLX4_NET_TRANS_RULE_ID_ETH]);
memcpy(eth_header->dst_mac, &be_mac, ETH_ALEN);
memcpy(eth_header->dst_mac_msk, &mac_msk, ETH_ALEN);
return 0;
}
#define MLX4_UPD_QP_PATH_MASK_SUPPORTED (1ULL << MLX4_UPD_QP_PATH_MASK_MAC_INDEX)
int mlx4_UPDATE_QP_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd_info)
{
int err;
u32 qpn = vhcr->in_modifier & 0xffffff;
struct res_qp *rqp;
u64 mac;
unsigned port;
u64 pri_addr_path_mask;
struct mlx4_update_qp_context *cmd;
int smac_index;
cmd = (struct mlx4_update_qp_context *)inbox->buf;
pri_addr_path_mask = be64_to_cpu(cmd->primary_addr_path_mask);
if (cmd->qp_mask || cmd->secondary_addr_path_mask ||
(pri_addr_path_mask & ~MLX4_UPD_QP_PATH_MASK_SUPPORTED))
return -EPERM;
/* Just change the smac for the QP */
err = get_res(dev, slave, qpn, RES_QP, &rqp);
if (err) {
mlx4_err(dev, "Updating qpn 0x%x for slave %d rejected\n", qpn, slave);
return err;
}
port = (rqp->sched_queue >> 6 & 1) + 1;
if (pri_addr_path_mask & (1ULL << MLX4_UPD_QP_PATH_MASK_MAC_INDEX)) {
smac_index = cmd->qp_context.pri_path.grh_mylmc;
err = mac_find_smac_ix_in_slave(dev, slave, port,
smac_index, &mac);
if (err) {
mlx4_err(dev, "Failed to update qpn 0x%x, MAC is invalid. smac_ix: %d\n",
qpn, smac_index);
goto err_mac;
}
}
err = mlx4_cmd(dev, inbox->dma,
vhcr->in_modifier, 0,
MLX4_CMD_UPDATE_QP, MLX4_CMD_TIME_CLASS_A,
MLX4_CMD_NATIVE);
if (err) {
mlx4_err(dev, "Failed to update qpn on qpn 0x%x, command failed\n", qpn);
goto err_mac;
}
err_mac:
put_res(dev, slave, qpn, RES_QP);
return err;
}
int mlx4_QP_FLOW_STEERING_ATTACH_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct list_head *rlist = &tracker->slave_list[slave].res_list[RES_MAC];
int err;
int qpn;
struct res_qp *rqp;
struct mlx4_net_trans_rule_hw_ctrl *ctrl;
struct _rule_hw *rule_header;
int header_id;
if (dev->caps.steering_mode !=
MLX4_STEERING_MODE_DEVICE_MANAGED)
return -EOPNOTSUPP;
ctrl = (struct mlx4_net_trans_rule_hw_ctrl *)inbox->buf;
ctrl->port = mlx4_slave_convert_port(dev, slave, ctrl->port);
if (ctrl->port <= 0)
return -EINVAL;
qpn = be32_to_cpu(ctrl->qpn) & 0xffffff;
err = get_res(dev, slave, qpn, RES_QP, &rqp);
if (err) {
pr_err("Steering rule with qpn 0x%x rejected\n", qpn);
return err;
}
rule_header = (struct _rule_hw *)(ctrl + 1);
header_id = map_hw_to_sw_id(be16_to_cpu(rule_header->id));
if (header_id == MLX4_NET_TRANS_RULE_ID_ETH)
handle_eth_header_mcast_prio(ctrl, rule_header);
if (slave == dev->caps.function)
goto execute;
switch (header_id) {
case MLX4_NET_TRANS_RULE_ID_ETH:
if (validate_eth_header_mac(slave, rule_header, rlist)) {
err = -EINVAL;
goto err_put;
}
break;
case MLX4_NET_TRANS_RULE_ID_IB:
break;
case MLX4_NET_TRANS_RULE_ID_IPV4:
case MLX4_NET_TRANS_RULE_ID_TCP:
case MLX4_NET_TRANS_RULE_ID_UDP:
pr_warn("Can't attach FS rule without L2 headers, adding L2 header\n");
if (add_eth_header(dev, slave, inbox, rlist, header_id)) {
err = -EINVAL;
goto err_put;
}
vhcr->in_modifier +=
sizeof(struct mlx4_net_trans_rule_hw_eth) >> 2;
break;
default:
pr_err("Corrupted mailbox\n");
err = -EINVAL;
goto err_put;
}
execute:
err = mlx4_cmd_imm(dev, inbox->dma, &vhcr->out_param,
vhcr->in_modifier, 0,
MLX4_QP_FLOW_STEERING_ATTACH, MLX4_CMD_TIME_CLASS_A,
MLX4_CMD_NATIVE);
if (err)
goto err_put;
err = add_res_range(dev, slave, vhcr->out_param, 1, RES_FS_RULE, qpn);
if (err) {
mlx4_err(dev, "Fail to add flow steering resources\n");
/* detach rule*/
mlx4_cmd(dev, vhcr->out_param, 0, 0,
MLX4_QP_FLOW_STEERING_DETACH, MLX4_CMD_TIME_CLASS_A,
MLX4_CMD_NATIVE);
goto err_put;
}
atomic_inc(&rqp->ref_count);
err_put:
put_res(dev, slave, qpn, RES_QP);
return err;
}
int mlx4_QP_FLOW_STEERING_DETACH_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
struct res_qp *rqp;
struct res_fs_rule *rrule;
if (dev->caps.steering_mode !=
MLX4_STEERING_MODE_DEVICE_MANAGED)
return -EOPNOTSUPP;
err = get_res(dev, slave, vhcr->in_param, RES_FS_RULE, &rrule);
if (err)
return err;
/* Release the rule form busy state before removal */
put_res(dev, slave, vhcr->in_param, RES_FS_RULE);
err = get_res(dev, slave, rrule->qpn, RES_QP, &rqp);
if (err)
return err;
err = rem_res_range(dev, slave, vhcr->in_param, 1, RES_FS_RULE, 0);
if (err) {
mlx4_err(dev, "Fail to remove flow steering resources\n");
goto out;
}
err = mlx4_cmd(dev, vhcr->in_param, 0, 0,
MLX4_QP_FLOW_STEERING_DETACH, MLX4_CMD_TIME_CLASS_A,
MLX4_CMD_NATIVE);
if (!err)
atomic_dec(&rqp->ref_count);
out:
put_res(dev, slave, rrule->qpn, RES_QP);
return err;
}
enum {
BUSY_MAX_RETRIES = 10
};
int mlx4_QUERY_IF_STAT_wrapper(struct mlx4_dev *dev, int slave,
struct mlx4_vhcr *vhcr,
struct mlx4_cmd_mailbox *inbox,
struct mlx4_cmd_mailbox *outbox,
struct mlx4_cmd_info *cmd)
{
int err;
int index = vhcr->in_modifier & 0xffff;
err = get_res(dev, slave, index, RES_COUNTER, NULL);
if (err)
return err;
err = mlx4_DMA_wrapper(dev, slave, vhcr, inbox, outbox, cmd);
put_res(dev, slave, index, RES_COUNTER);
return err;
}
static void detach_qp(struct mlx4_dev *dev, int slave, struct res_qp *rqp)
{
struct res_gid *rgid;
struct res_gid *tmp;
struct mlx4_qp qp; /* dummy for calling attach/detach */
list_for_each_entry_safe(rgid, tmp, &rqp->mcg_list, list) {
switch (dev->caps.steering_mode) {
case MLX4_STEERING_MODE_DEVICE_MANAGED:
mlx4_flow_detach(dev, rgid->reg_id);
break;
case MLX4_STEERING_MODE_B0:
qp.qpn = rqp->local_qpn;
(void) mlx4_qp_detach_common(dev, &qp, rgid->gid,
rgid->prot, rgid->steer);
break;
}
list_del(&rgid->list);
kfree(rgid);
}
}
static int _move_all_busy(struct mlx4_dev *dev, int slave,
enum mlx4_resource type, int print)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker =
&priv->mfunc.master.res_tracker;
struct list_head *rlist = &tracker->slave_list[slave].res_list[type];
struct res_common *r;
struct res_common *tmp;
int busy;
busy = 0;
spin_lock_irq(mlx4_tlock(dev));
list_for_each_entry_safe(r, tmp, rlist, list) {
if (r->owner == slave) {
if (!r->removing) {
if (r->state == RES_ANY_BUSY) {
if (print)
mlx4_dbg(dev,
"%s id 0x%llx is busy\n",
resource_str(type),
r->res_id);
++busy;
} else {
r->from_state = r->state;
r->state = RES_ANY_BUSY;
r->removing = 1;
}
}
}
}
spin_unlock_irq(mlx4_tlock(dev));
return busy;
}
static int move_all_busy(struct mlx4_dev *dev, int slave,
enum mlx4_resource type)
{
unsigned long begin;
int busy;
begin = jiffies;
do {
busy = _move_all_busy(dev, slave, type, 0);
if (time_after(jiffies, begin + 5 * HZ))
break;
if (busy)
cond_resched();
} while (busy);
if (busy)
busy = _move_all_busy(dev, slave, type, 1);
return busy;
}
static void rem_slave_qps(struct mlx4_dev *dev, int slave)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct list_head *qp_list =
&tracker->slave_list[slave].res_list[RES_QP];
struct res_qp *qp;
struct res_qp *tmp;
int state;
u64 in_param;
int qpn;
int err;
err = move_all_busy(dev, slave, RES_QP);
if (err)
mlx4_warn(dev, "rem_slave_qps: Could not move all qps to busy for slave %d\n",
slave);
spin_lock_irq(mlx4_tlock(dev));
list_for_each_entry_safe(qp, tmp, qp_list, com.list) {
spin_unlock_irq(mlx4_tlock(dev));
if (qp->com.owner == slave) {
qpn = qp->com.res_id;
detach_qp(dev, slave, qp);
state = qp->com.from_state;
while (state != 0) {
switch (state) {
case RES_QP_RESERVED:
spin_lock_irq(mlx4_tlock(dev));
rb_erase(&qp->com.node,
&tracker->res_tree[RES_QP]);
list_del(&qp->com.list);
spin_unlock_irq(mlx4_tlock(dev));
if (!valid_reserved(dev, slave, qpn)) {
__mlx4_qp_release_range(dev, qpn, 1);
mlx4_release_resource(dev, slave,
RES_QP, 1, 0);
}
kfree(qp);
state = 0;
break;
case RES_QP_MAPPED:
if (!valid_reserved(dev, slave, qpn))
__mlx4_qp_free_icm(dev, qpn);
state = RES_QP_RESERVED;
break;
case RES_QP_HW:
in_param = slave;
err = mlx4_cmd(dev, in_param,
qp->local_qpn, 2,
MLX4_CMD_2RST_QP,
MLX4_CMD_TIME_CLASS_A,
MLX4_CMD_NATIVE);
if (err)
mlx4_dbg(dev, "rem_slave_qps: failed to move slave %d qpn %d to reset\n",
slave, qp->local_qpn);
atomic_dec(&qp->rcq->ref_count);
atomic_dec(&qp->scq->ref_count);
atomic_dec(&qp->mtt->ref_count);
if (qp->srq)
atomic_dec(&qp->srq->ref_count);
state = RES_QP_MAPPED;
break;
default:
state = 0;
}
}
}
spin_lock_irq(mlx4_tlock(dev));
}
spin_unlock_irq(mlx4_tlock(dev));
}
static void rem_slave_srqs(struct mlx4_dev *dev, int slave)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct list_head *srq_list =
&tracker->slave_list[slave].res_list[RES_SRQ];
struct res_srq *srq;
struct res_srq *tmp;
int state;
u64 in_param;
LIST_HEAD(tlist);
int srqn;
int err;
err = move_all_busy(dev, slave, RES_SRQ);
if (err)
mlx4_warn(dev, "rem_slave_srqs: Could not move all srqs - too busy for slave %d\n",
slave);
spin_lock_irq(mlx4_tlock(dev));
list_for_each_entry_safe(srq, tmp, srq_list, com.list) {
spin_unlock_irq(mlx4_tlock(dev));
if (srq->com.owner == slave) {
srqn = srq->com.res_id;
state = srq->com.from_state;
while (state != 0) {
switch (state) {
case RES_SRQ_ALLOCATED:
__mlx4_srq_free_icm(dev, srqn);
spin_lock_irq(mlx4_tlock(dev));
rb_erase(&srq->com.node,
&tracker->res_tree[RES_SRQ]);
list_del(&srq->com.list);
spin_unlock_irq(mlx4_tlock(dev));
mlx4_release_resource(dev, slave,
RES_SRQ, 1, 0);
kfree(srq);
state = 0;
break;
case RES_SRQ_HW:
in_param = slave;
err = mlx4_cmd(dev, in_param, srqn, 1,
MLX4_CMD_HW2SW_SRQ,
MLX4_CMD_TIME_CLASS_A,
MLX4_CMD_NATIVE);
if (err)
mlx4_dbg(dev, "rem_slave_srqs: failed to move slave %d srq %d to SW ownership\n",
slave, srqn);
atomic_dec(&srq->mtt->ref_count);
if (srq->cq)
atomic_dec(&srq->cq->ref_count);
state = RES_SRQ_ALLOCATED;
break;
default:
state = 0;
}
}
}
spin_lock_irq(mlx4_tlock(dev));
}
spin_unlock_irq(mlx4_tlock(dev));
}
static void rem_slave_cqs(struct mlx4_dev *dev, int slave)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct list_head *cq_list =
&tracker->slave_list[slave].res_list[RES_CQ];
struct res_cq *cq;
struct res_cq *tmp;
int state;
u64 in_param;
LIST_HEAD(tlist);
int cqn;
int err;
err = move_all_busy(dev, slave, RES_CQ);
if (err)
mlx4_warn(dev, "rem_slave_cqs: Could not move all cqs - too busy for slave %d\n",
slave);
spin_lock_irq(mlx4_tlock(dev));
list_for_each_entry_safe(cq, tmp, cq_list, com.list) {
spin_unlock_irq(mlx4_tlock(dev));
if (cq->com.owner == slave && !atomic_read(&cq->ref_count)) {
cqn = cq->com.res_id;
state = cq->com.from_state;
while (state != 0) {
switch (state) {
case RES_CQ_ALLOCATED:
__mlx4_cq_free_icm(dev, cqn);
spin_lock_irq(mlx4_tlock(dev));
rb_erase(&cq->com.node,
&tracker->res_tree[RES_CQ]);
list_del(&cq->com.list);
spin_unlock_irq(mlx4_tlock(dev));
mlx4_release_resource(dev, slave,
RES_CQ, 1, 0);
kfree(cq);
state = 0;
break;
case RES_CQ_HW:
in_param = slave;
err = mlx4_cmd(dev, in_param, cqn, 1,
MLX4_CMD_HW2SW_CQ,
MLX4_CMD_TIME_CLASS_A,
MLX4_CMD_NATIVE);
if (err)
mlx4_dbg(dev, "rem_slave_cqs: failed to move slave %d cq %d to SW ownership\n",
slave, cqn);
atomic_dec(&cq->mtt->ref_count);
state = RES_CQ_ALLOCATED;
break;
default:
state = 0;
}
}
}
spin_lock_irq(mlx4_tlock(dev));
}
spin_unlock_irq(mlx4_tlock(dev));
}
static void rem_slave_mrs(struct mlx4_dev *dev, int slave)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct list_head *mpt_list =
&tracker->slave_list[slave].res_list[RES_MPT];
struct res_mpt *mpt;
struct res_mpt *tmp;
int state;
u64 in_param;
LIST_HEAD(tlist);
int mptn;
int err;
err = move_all_busy(dev, slave, RES_MPT);
if (err)
mlx4_warn(dev, "rem_slave_mrs: Could not move all mpts - too busy for slave %d\n",
slave);
spin_lock_irq(mlx4_tlock(dev));
list_for_each_entry_safe(mpt, tmp, mpt_list, com.list) {
spin_unlock_irq(mlx4_tlock(dev));
if (mpt->com.owner == slave) {
mptn = mpt->com.res_id;
state = mpt->com.from_state;
while (state != 0) {
switch (state) {
case RES_MPT_RESERVED:
__mlx4_mpt_release(dev, mpt->key);
spin_lock_irq(mlx4_tlock(dev));
rb_erase(&mpt->com.node,
&tracker->res_tree[RES_MPT]);
list_del(&mpt->com.list);
spin_unlock_irq(mlx4_tlock(dev));
mlx4_release_resource(dev, slave,
RES_MPT, 1, 0);
kfree(mpt);
state = 0;
break;
case RES_MPT_MAPPED:
__mlx4_mpt_free_icm(dev, mpt->key);
state = RES_MPT_RESERVED;
break;
case RES_MPT_HW:
in_param = slave;
err = mlx4_cmd(dev, in_param, mptn, 0,
MLX4_CMD_HW2SW_MPT,
MLX4_CMD_TIME_CLASS_A,
MLX4_CMD_NATIVE);
if (err)
mlx4_dbg(dev, "rem_slave_mrs: failed to move slave %d mpt %d to SW ownership\n",
slave, mptn);
if (mpt->mtt)
atomic_dec(&mpt->mtt->ref_count);
state = RES_MPT_MAPPED;
break;
default:
state = 0;
}
}
}
spin_lock_irq(mlx4_tlock(dev));
}
spin_unlock_irq(mlx4_tlock(dev));
}
static void rem_slave_mtts(struct mlx4_dev *dev, int slave)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker =
&priv->mfunc.master.res_tracker;
struct list_head *mtt_list =
&tracker->slave_list[slave].res_list[RES_MTT];
struct res_mtt *mtt;
struct res_mtt *tmp;
int state;
LIST_HEAD(tlist);
int base;
int err;
err = move_all_busy(dev, slave, RES_MTT);
if (err)
mlx4_warn(dev, "rem_slave_mtts: Could not move all mtts - too busy for slave %d\n",
slave);
spin_lock_irq(mlx4_tlock(dev));
list_for_each_entry_safe(mtt, tmp, mtt_list, com.list) {
spin_unlock_irq(mlx4_tlock(dev));
if (mtt->com.owner == slave) {
base = mtt->com.res_id;
state = mtt->com.from_state;
while (state != 0) {
switch (state) {
case RES_MTT_ALLOCATED:
__mlx4_free_mtt_range(dev, base,
mtt->order);
spin_lock_irq(mlx4_tlock(dev));
rb_erase(&mtt->com.node,
&tracker->res_tree[RES_MTT]);
list_del(&mtt->com.list);
spin_unlock_irq(mlx4_tlock(dev));
mlx4_release_resource(dev, slave, RES_MTT,
1 << mtt->order, 0);
kfree(mtt);
state = 0;
break;
default:
state = 0;
}
}
}
spin_lock_irq(mlx4_tlock(dev));
}
spin_unlock_irq(mlx4_tlock(dev));
}
static void rem_slave_fs_rule(struct mlx4_dev *dev, int slave)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker =
&priv->mfunc.master.res_tracker;
struct list_head *fs_rule_list =
&tracker->slave_list[slave].res_list[RES_FS_RULE];
struct res_fs_rule *fs_rule;
struct res_fs_rule *tmp;
int state;
u64 base;
int err;
err = move_all_busy(dev, slave, RES_FS_RULE);
if (err)
mlx4_warn(dev, "rem_slave_fs_rule: Could not move all mtts to busy for slave %d\n",
slave);
spin_lock_irq(mlx4_tlock(dev));
list_for_each_entry_safe(fs_rule, tmp, fs_rule_list, com.list) {
spin_unlock_irq(mlx4_tlock(dev));
if (fs_rule->com.owner == slave) {
base = fs_rule->com.res_id;
state = fs_rule->com.from_state;
while (state != 0) {
switch (state) {
case RES_FS_RULE_ALLOCATED:
/* detach rule */
err = mlx4_cmd(dev, base, 0, 0,
MLX4_QP_FLOW_STEERING_DETACH,
MLX4_CMD_TIME_CLASS_A,
MLX4_CMD_NATIVE);
spin_lock_irq(mlx4_tlock(dev));
rb_erase(&fs_rule->com.node,
&tracker->res_tree[RES_FS_RULE]);
list_del(&fs_rule->com.list);
spin_unlock_irq(mlx4_tlock(dev));
kfree(fs_rule);
state = 0;
break;
default:
state = 0;
}
}
}
spin_lock_irq(mlx4_tlock(dev));
}
spin_unlock_irq(mlx4_tlock(dev));
}
static void rem_slave_eqs(struct mlx4_dev *dev, int slave)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct list_head *eq_list =
&tracker->slave_list[slave].res_list[RES_EQ];
struct res_eq *eq;
struct res_eq *tmp;
int err;
int state;
LIST_HEAD(tlist);
int eqn;
err = move_all_busy(dev, slave, RES_EQ);
if (err)
mlx4_warn(dev, "rem_slave_eqs: Could not move all eqs - too busy for slave %d\n",
slave);
spin_lock_irq(mlx4_tlock(dev));
list_for_each_entry_safe(eq, tmp, eq_list, com.list) {
spin_unlock_irq(mlx4_tlock(dev));
if (eq->com.owner == slave) {
eqn = eq->com.res_id;
state = eq->com.from_state;
while (state != 0) {
switch (state) {
case RES_EQ_RESERVED:
spin_lock_irq(mlx4_tlock(dev));
rb_erase(&eq->com.node,
&tracker->res_tree[RES_EQ]);
list_del(&eq->com.list);
spin_unlock_irq(mlx4_tlock(dev));
kfree(eq);
state = 0;
break;
case RES_EQ_HW:
err = mlx4_cmd(dev, slave, eqn & 0x3ff,
1, MLX4_CMD_HW2SW_EQ,
MLX4_CMD_TIME_CLASS_A,
MLX4_CMD_NATIVE);
if (err)
mlx4_dbg(dev, "rem_slave_eqs: failed to move slave %d eqs %d to SW ownership\n",
slave, eqn & 0x3ff);
atomic_dec(&eq->mtt->ref_count);
state = RES_EQ_RESERVED;
break;
default:
state = 0;
}
}
}
spin_lock_irq(mlx4_tlock(dev));
}
spin_unlock_irq(mlx4_tlock(dev));
}
static void rem_slave_counters(struct mlx4_dev *dev, int slave)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct list_head *counter_list =
&tracker->slave_list[slave].res_list[RES_COUNTER];
struct res_counter *counter;
struct res_counter *tmp;
int err;
int index;
err = move_all_busy(dev, slave, RES_COUNTER);
if (err)
mlx4_warn(dev, "rem_slave_counters: Could not move all counters - too busy for slave %d\n",
slave);
spin_lock_irq(mlx4_tlock(dev));
list_for_each_entry_safe(counter, tmp, counter_list, com.list) {
if (counter->com.owner == slave) {
index = counter->com.res_id;
rb_erase(&counter->com.node,
&tracker->res_tree[RES_COUNTER]);
list_del(&counter->com.list);
kfree(counter);
__mlx4_counter_free(dev, index);
mlx4_release_resource(dev, slave, RES_COUNTER, 1, 0);
}
}
spin_unlock_irq(mlx4_tlock(dev));
}
static void rem_slave_xrcdns(struct mlx4_dev *dev, int slave)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource_tracker *tracker = &priv->mfunc.master.res_tracker;
struct list_head *xrcdn_list =
&tracker->slave_list[slave].res_list[RES_XRCD];
struct res_xrcdn *xrcd;
struct res_xrcdn *tmp;
int err;
int xrcdn;
err = move_all_busy(dev, slave, RES_XRCD);
if (err)
mlx4_warn(dev, "rem_slave_xrcdns: Could not move all xrcdns - too busy for slave %d\n",
slave);
spin_lock_irq(mlx4_tlock(dev));
list_for_each_entry_safe(xrcd, tmp, xrcdn_list, com.list) {
if (xrcd->com.owner == slave) {
xrcdn = xrcd->com.res_id;
rb_erase(&xrcd->com.node, &tracker->res_tree[RES_XRCD]);
list_del(&xrcd->com.list);
kfree(xrcd);
__mlx4_xrcd_free(dev, xrcdn);
}
}
spin_unlock_irq(mlx4_tlock(dev));
}
void mlx4_delete_all_resources_for_slave(struct mlx4_dev *dev, int slave)
{
struct mlx4_priv *priv = mlx4_priv(dev);
mlx4_reset_roce_gids(dev, slave);
mutex_lock(&priv->mfunc.master.res_tracker.slave_list[slave].mutex);
rem_slave_vlans(dev, slave);
rem_slave_macs(dev, slave);
rem_slave_fs_rule(dev, slave);
rem_slave_qps(dev, slave);
rem_slave_srqs(dev, slave);
rem_slave_cqs(dev, slave);
rem_slave_mrs(dev, slave);
rem_slave_eqs(dev, slave);
rem_slave_mtts(dev, slave);
rem_slave_counters(dev, slave);
rem_slave_xrcdns(dev, slave);
mutex_unlock(&priv->mfunc.master.res_tracker.slave_list[slave].mutex);
}
void mlx4_vf_immed_vlan_work_handler(struct work_struct *_work)
{
struct mlx4_vf_immed_vlan_work *work =
container_of(_work, struct mlx4_vf_immed_vlan_work, work);
struct mlx4_cmd_mailbox *mailbox;
struct mlx4_update_qp_context *upd_context;
struct mlx4_dev *dev = &work->priv->dev;
struct mlx4_resource_tracker *tracker =
&work->priv->mfunc.master.res_tracker;
struct list_head *qp_list =
&tracker->slave_list[work->slave].res_list[RES_QP];
struct res_qp *qp;
struct res_qp *tmp;
u64 qp_path_mask_vlan_ctrl =
((1ULL << MLX4_UPD_QP_PATH_MASK_ETH_TX_BLOCK_UNTAGGED) |
(1ULL << MLX4_UPD_QP_PATH_MASK_ETH_TX_BLOCK_1P) |
(1ULL << MLX4_UPD_QP_PATH_MASK_ETH_TX_BLOCK_TAGGED) |
(1ULL << MLX4_UPD_QP_PATH_MASK_ETH_RX_BLOCK_UNTAGGED) |
(1ULL << MLX4_UPD_QP_PATH_MASK_ETH_RX_BLOCK_1P) |
(1ULL << MLX4_UPD_QP_PATH_MASK_ETH_RX_BLOCK_TAGGED));
u64 qp_path_mask = ((1ULL << MLX4_UPD_QP_PATH_MASK_VLAN_INDEX) |
(1ULL << MLX4_UPD_QP_PATH_MASK_FVL) |
(1ULL << MLX4_UPD_QP_PATH_MASK_CV) |
(1ULL << MLX4_UPD_QP_PATH_MASK_ETH_HIDE_CQE_VLAN) |
(1ULL << MLX4_UPD_QP_PATH_MASK_FEUP) |
(1ULL << MLX4_UPD_QP_PATH_MASK_FVL_RX) |
(1ULL << MLX4_UPD_QP_PATH_MASK_SCHED_QUEUE));
int err;
int port, errors = 0;
u8 vlan_control;
if (mlx4_is_slave(dev)) {
mlx4_warn(dev, "Trying to update-qp in slave %d\n",
work->slave);
goto out;
}
mailbox = mlx4_alloc_cmd_mailbox(dev);
if (IS_ERR(mailbox))
goto out;
if (work->flags & MLX4_VF_IMMED_VLAN_FLAG_LINK_DISABLE) /* block all */
vlan_control = MLX4_VLAN_CTRL_ETH_TX_BLOCK_TAGGED |
MLX4_VLAN_CTRL_ETH_TX_BLOCK_PRIO_TAGGED |
MLX4_VLAN_CTRL_ETH_TX_BLOCK_UNTAGGED |
MLX4_VLAN_CTRL_ETH_RX_BLOCK_PRIO_TAGGED |
MLX4_VLAN_CTRL_ETH_RX_BLOCK_UNTAGGED |
MLX4_VLAN_CTRL_ETH_RX_BLOCK_TAGGED;
else if (!work->vlan_id)
vlan_control = MLX4_VLAN_CTRL_ETH_TX_BLOCK_TAGGED |
MLX4_VLAN_CTRL_ETH_RX_BLOCK_TAGGED;
else
vlan_control = MLX4_VLAN_CTRL_ETH_TX_BLOCK_TAGGED |
MLX4_VLAN_CTRL_ETH_RX_BLOCK_PRIO_TAGGED |
MLX4_VLAN_CTRL_ETH_RX_BLOCK_UNTAGGED;
upd_context = mailbox->buf;
upd_context->qp_mask = cpu_to_be64(1ULL << MLX4_UPD_QP_MASK_VSD);
spin_lock_irq(mlx4_tlock(dev));
list_for_each_entry_safe(qp, tmp, qp_list, com.list) {
spin_unlock_irq(mlx4_tlock(dev));
if (qp->com.owner == work->slave) {
if (qp->com.from_state != RES_QP_HW ||
!qp->sched_queue || /* no INIT2RTR trans yet */
mlx4_is_qp_reserved(dev, qp->local_qpn) ||
qp->qpc_flags & (1 << MLX4_RSS_QPC_FLAG_OFFSET)) {
spin_lock_irq(mlx4_tlock(dev));
continue;
}
port = (qp->sched_queue >> 6 & 1) + 1;
if (port != work->port) {
spin_lock_irq(mlx4_tlock(dev));
continue;
}
if (MLX4_QP_ST_RC == ((qp->qpc_flags >> 16) & 0xff))
upd_context->primary_addr_path_mask = cpu_to_be64(qp_path_mask);
else
upd_context->primary_addr_path_mask =
cpu_to_be64(qp_path_mask | qp_path_mask_vlan_ctrl);
if (work->vlan_id == MLX4_VGT) {
upd_context->qp_context.param3 = qp->param3;
upd_context->qp_context.pri_path.vlan_control = qp->vlan_control;
upd_context->qp_context.pri_path.fvl_rx = qp->fvl_rx;
upd_context->qp_context.pri_path.vlan_index = qp->vlan_index;
upd_context->qp_context.pri_path.fl = qp->pri_path_fl;
upd_context->qp_context.pri_path.feup = qp->feup;
upd_context->qp_context.pri_path.sched_queue =
qp->sched_queue;
} else {
upd_context->qp_context.param3 = qp->param3 & ~cpu_to_be32(MLX4_STRIP_VLAN);
upd_context->qp_context.pri_path.vlan_control = vlan_control;
upd_context->qp_context.pri_path.vlan_index = work->vlan_ix;
upd_context->qp_context.pri_path.fvl_rx =
qp->fvl_rx | MLX4_FVL_RX_FORCE_ETH_VLAN;
upd_context->qp_context.pri_path.fl =
qp->pri_path_fl | MLX4_FL_CV | MLX4_FL_ETH_HIDE_CQE_VLAN;
upd_context->qp_context.pri_path.feup =
qp->feup | MLX4_FEUP_FORCE_ETH_UP | MLX4_FVL_FORCE_ETH_VLAN;
upd_context->qp_context.pri_path.sched_queue =
qp->sched_queue & 0xC7;
upd_context->qp_context.pri_path.sched_queue |=
((work->qos & 0x7) << 3);
upd_context->qp_mask |=
cpu_to_be64(1ULL <<
MLX4_UPD_QP_MASK_QOS_VPP);
upd_context->qp_context.qos_vport =
work->qos_vport;
}
err = mlx4_cmd(dev, mailbox->dma,
qp->local_qpn & 0xffffff,
0, MLX4_CMD_UPDATE_QP,
MLX4_CMD_TIME_CLASS_C, MLX4_CMD_NATIVE);
if (err) {
mlx4_info(dev, "UPDATE_QP failed for slave %d, port %d, qpn %d (%d)\n",
work->slave, port, qp->local_qpn, err);
errors++;
}
}
spin_lock_irq(mlx4_tlock(dev));
}
spin_unlock_irq(mlx4_tlock(dev));
mlx4_free_cmd_mailbox(dev, mailbox);
if (errors)
mlx4_err(dev, "%d UPDATE_QP failures for slave %d, port %d\n",
errors, work->slave, work->port);
/* unregister previous vlan_id if needed and we had no errors
* while updating the QPs
*/
if (work->flags & MLX4_VF_IMMED_VLAN_FLAG_VLAN && !errors &&
NO_INDX != work->orig_vlan_ix)
__mlx4_unregister_vlan(&work->priv->dev, work->port,
work->orig_vlan_id);
out:
kfree(work);
return;
}
| gpl-2.0 |
lp0/linux | kernel/gcov/gcc_4_7.c | 639 | 13709 | /*
* This code provides functions to handle gcc's profiling data format
* introduced with gcc 4.7.
*
* This file is based heavily on gcc_3_4.c file.
*
* For a better understanding, refer to gcc source:
* gcc/gcov-io.h
* libgcc/libgcov.c
*
* Uses gcc-internal data definitions.
*/
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/seq_file.h>
#include <linux/vmalloc.h>
#include "gcov.h"
#if __GNUC__ == 5 && __GNUC_MINOR__ >= 1
#define GCOV_COUNTERS 10
#elif __GNUC__ == 4 && __GNUC_MINOR__ >= 9
#define GCOV_COUNTERS 9
#else
#define GCOV_COUNTERS 8
#endif
#define GCOV_TAG_FUNCTION_LENGTH 3
static struct gcov_info *gcov_info_head;
/**
* struct gcov_ctr_info - information about counters for a single function
* @num: number of counter values for this type
* @values: array of counter values for this type
*
* This data is generated by gcc during compilation and doesn't change
* at run-time with the exception of the values array.
*/
struct gcov_ctr_info {
unsigned int num;
gcov_type *values;
};
/**
* struct gcov_fn_info - profiling meta data per function
* @key: comdat key
* @ident: unique ident of function
* @lineno_checksum: function lineo_checksum
* @cfg_checksum: function cfg checksum
* @ctrs: instrumented counters
*
* This data is generated by gcc during compilation and doesn't change
* at run-time.
*
* Information about a single function. This uses the trailing array
* idiom. The number of counters is determined from the merge pointer
* array in gcov_info. The key is used to detect which of a set of
* comdat functions was selected -- it points to the gcov_info object
* of the object file containing the selected comdat function.
*/
struct gcov_fn_info {
const struct gcov_info *key;
unsigned int ident;
unsigned int lineno_checksum;
unsigned int cfg_checksum;
struct gcov_ctr_info ctrs[0];
};
/**
* struct gcov_info - profiling data per object file
* @version: gcov version magic indicating the gcc version used for compilation
* @next: list head for a singly-linked list
* @stamp: uniquifying time stamp
* @filename: name of the associated gcov data file
* @merge: merge functions (null for unused counter type)
* @n_functions: number of instrumented functions
* @functions: pointer to pointers to function information
*
* This data is generated by gcc during compilation and doesn't change
* at run-time with the exception of the next pointer.
*/
struct gcov_info {
unsigned int version;
struct gcov_info *next;
unsigned int stamp;
const char *filename;
void (*merge[GCOV_COUNTERS])(gcov_type *, unsigned int);
unsigned int n_functions;
struct gcov_fn_info **functions;
};
/**
* gcov_info_filename - return info filename
* @info: profiling data set
*/
const char *gcov_info_filename(struct gcov_info *info)
{
return info->filename;
}
/**
* gcov_info_version - return info version
* @info: profiling data set
*/
unsigned int gcov_info_version(struct gcov_info *info)
{
return info->version;
}
/**
* gcov_info_next - return next profiling data set
* @info: profiling data set
*
* Returns next gcov_info following @info or first gcov_info in the chain if
* @info is %NULL.
*/
struct gcov_info *gcov_info_next(struct gcov_info *info)
{
if (!info)
return gcov_info_head;
return info->next;
}
/**
* gcov_info_link - link/add profiling data set to the list
* @info: profiling data set
*/
void gcov_info_link(struct gcov_info *info)
{
info->next = gcov_info_head;
gcov_info_head = info;
}
/**
* gcov_info_unlink - unlink/remove profiling data set from the list
* @prev: previous profiling data set
* @info: profiling data set
*/
void gcov_info_unlink(struct gcov_info *prev, struct gcov_info *info)
{
if (prev)
prev->next = info->next;
else
gcov_info_head = info->next;
}
/* Symbolic links to be created for each profiling data file. */
const struct gcov_link gcov_link[] = {
{ OBJ_TREE, "gcno" }, /* Link to .gcno file in $(objtree). */
{ 0, NULL},
};
/*
* Determine whether a counter is active. Doesn't change at run-time.
*/
static int counter_active(struct gcov_info *info, unsigned int type)
{
return info->merge[type] ? 1 : 0;
}
/* Determine number of active counters. Based on gcc magic. */
static unsigned int num_counter_active(struct gcov_info *info)
{
unsigned int i;
unsigned int result = 0;
for (i = 0; i < GCOV_COUNTERS; i++) {
if (counter_active(info, i))
result++;
}
return result;
}
/**
* gcov_info_reset - reset profiling data to zero
* @info: profiling data set
*/
void gcov_info_reset(struct gcov_info *info)
{
struct gcov_ctr_info *ci_ptr;
unsigned int fi_idx;
unsigned int ct_idx;
for (fi_idx = 0; fi_idx < info->n_functions; fi_idx++) {
ci_ptr = info->functions[fi_idx]->ctrs;
for (ct_idx = 0; ct_idx < GCOV_COUNTERS; ct_idx++) {
if (!counter_active(info, ct_idx))
continue;
memset(ci_ptr->values, 0,
sizeof(gcov_type) * ci_ptr->num);
ci_ptr++;
}
}
}
/**
* gcov_info_is_compatible - check if profiling data can be added
* @info1: first profiling data set
* @info2: second profiling data set
*
* Returns non-zero if profiling data can be added, zero otherwise.
*/
int gcov_info_is_compatible(struct gcov_info *info1, struct gcov_info *info2)
{
return (info1->stamp == info2->stamp);
}
/**
* gcov_info_add - add up profiling data
* @dest: profiling data set to which data is added
* @source: profiling data set which is added
*
* Adds profiling counts of @source to @dest.
*/
void gcov_info_add(struct gcov_info *dst, struct gcov_info *src)
{
struct gcov_ctr_info *dci_ptr;
struct gcov_ctr_info *sci_ptr;
unsigned int fi_idx;
unsigned int ct_idx;
unsigned int val_idx;
for (fi_idx = 0; fi_idx < src->n_functions; fi_idx++) {
dci_ptr = dst->functions[fi_idx]->ctrs;
sci_ptr = src->functions[fi_idx]->ctrs;
for (ct_idx = 0; ct_idx < GCOV_COUNTERS; ct_idx++) {
if (!counter_active(src, ct_idx))
continue;
for (val_idx = 0; val_idx < sci_ptr->num; val_idx++)
dci_ptr->values[val_idx] +=
sci_ptr->values[val_idx];
dci_ptr++;
sci_ptr++;
}
}
}
/**
* gcov_info_dup - duplicate profiling data set
* @info: profiling data set to duplicate
*
* Return newly allocated duplicate on success, %NULL on error.
*/
struct gcov_info *gcov_info_dup(struct gcov_info *info)
{
struct gcov_info *dup;
struct gcov_ctr_info *dci_ptr; /* dst counter info */
struct gcov_ctr_info *sci_ptr; /* src counter info */
unsigned int active;
unsigned int fi_idx; /* function info idx */
unsigned int ct_idx; /* counter type idx */
size_t fi_size; /* function info size */
size_t cv_size; /* counter values size */
dup = kmemdup(info, sizeof(*dup), GFP_KERNEL);
if (!dup)
return NULL;
dup->next = NULL;
dup->filename = NULL;
dup->functions = NULL;
dup->filename = kstrdup(info->filename, GFP_KERNEL);
if (!dup->filename)
goto err_free;
dup->functions = kcalloc(info->n_functions,
sizeof(struct gcov_fn_info *), GFP_KERNEL);
if (!dup->functions)
goto err_free;
active = num_counter_active(info);
fi_size = sizeof(struct gcov_fn_info);
fi_size += sizeof(struct gcov_ctr_info) * active;
for (fi_idx = 0; fi_idx < info->n_functions; fi_idx++) {
dup->functions[fi_idx] = kzalloc(fi_size, GFP_KERNEL);
if (!dup->functions[fi_idx])
goto err_free;
*(dup->functions[fi_idx]) = *(info->functions[fi_idx]);
sci_ptr = info->functions[fi_idx]->ctrs;
dci_ptr = dup->functions[fi_idx]->ctrs;
for (ct_idx = 0; ct_idx < active; ct_idx++) {
cv_size = sizeof(gcov_type) * sci_ptr->num;
dci_ptr->values = vmalloc(cv_size);
if (!dci_ptr->values)
goto err_free;
dci_ptr->num = sci_ptr->num;
memcpy(dci_ptr->values, sci_ptr->values, cv_size);
sci_ptr++;
dci_ptr++;
}
}
return dup;
err_free:
gcov_info_free(dup);
return NULL;
}
/**
* gcov_info_free - release memory for profiling data set duplicate
* @info: profiling data set duplicate to free
*/
void gcov_info_free(struct gcov_info *info)
{
unsigned int active;
unsigned int fi_idx;
unsigned int ct_idx;
struct gcov_ctr_info *ci_ptr;
if (!info->functions)
goto free_info;
active = num_counter_active(info);
for (fi_idx = 0; fi_idx < info->n_functions; fi_idx++) {
if (!info->functions[fi_idx])
continue;
ci_ptr = info->functions[fi_idx]->ctrs;
for (ct_idx = 0; ct_idx < active; ct_idx++, ci_ptr++)
vfree(ci_ptr->values);
kfree(info->functions[fi_idx]);
}
free_info:
kfree(info->functions);
kfree(info->filename);
kfree(info);
}
#define ITER_STRIDE PAGE_SIZE
/**
* struct gcov_iterator - specifies current file position in logical records
* @info: associated profiling data
* @buffer: buffer containing file data
* @size: size of buffer
* @pos: current position in file
*/
struct gcov_iterator {
struct gcov_info *info;
void *buffer;
size_t size;
loff_t pos;
};
/**
* store_gcov_u32 - store 32 bit number in gcov format to buffer
* @buffer: target buffer or NULL
* @off: offset into the buffer
* @v: value to be stored
*
* Number format defined by gcc: numbers are recorded in the 32 bit
* unsigned binary form of the endianness of the machine generating the
* file. Returns the number of bytes stored. If @buffer is %NULL, doesn't
* store anything.
*/
static size_t store_gcov_u32(void *buffer, size_t off, u32 v)
{
u32 *data;
if (buffer) {
data = buffer + off;
*data = v;
}
return sizeof(*data);
}
/**
* store_gcov_u64 - store 64 bit number in gcov format to buffer
* @buffer: target buffer or NULL
* @off: offset into the buffer
* @v: value to be stored
*
* Number format defined by gcc: numbers are recorded in the 32 bit
* unsigned binary form of the endianness of the machine generating the
* file. 64 bit numbers are stored as two 32 bit numbers, the low part
* first. Returns the number of bytes stored. If @buffer is %NULL, doesn't store
* anything.
*/
static size_t store_gcov_u64(void *buffer, size_t off, u64 v)
{
u32 *data;
if (buffer) {
data = buffer + off;
data[0] = (v & 0xffffffffUL);
data[1] = (v >> 32);
}
return sizeof(*data) * 2;
}
/**
* convert_to_gcda - convert profiling data set to gcda file format
* @buffer: the buffer to store file data or %NULL if no data should be stored
* @info: profiling data set to be converted
*
* Returns the number of bytes that were/would have been stored into the buffer.
*/
static size_t convert_to_gcda(char *buffer, struct gcov_info *info)
{
struct gcov_fn_info *fi_ptr;
struct gcov_ctr_info *ci_ptr;
unsigned int fi_idx;
unsigned int ct_idx;
unsigned int cv_idx;
size_t pos = 0;
/* File header. */
pos += store_gcov_u32(buffer, pos, GCOV_DATA_MAGIC);
pos += store_gcov_u32(buffer, pos, info->version);
pos += store_gcov_u32(buffer, pos, info->stamp);
for (fi_idx = 0; fi_idx < info->n_functions; fi_idx++) {
fi_ptr = info->functions[fi_idx];
/* Function record. */
pos += store_gcov_u32(buffer, pos, GCOV_TAG_FUNCTION);
pos += store_gcov_u32(buffer, pos, GCOV_TAG_FUNCTION_LENGTH);
pos += store_gcov_u32(buffer, pos, fi_ptr->ident);
pos += store_gcov_u32(buffer, pos, fi_ptr->lineno_checksum);
pos += store_gcov_u32(buffer, pos, fi_ptr->cfg_checksum);
ci_ptr = fi_ptr->ctrs;
for (ct_idx = 0; ct_idx < GCOV_COUNTERS; ct_idx++) {
if (!counter_active(info, ct_idx))
continue;
/* Counter record. */
pos += store_gcov_u32(buffer, pos,
GCOV_TAG_FOR_COUNTER(ct_idx));
pos += store_gcov_u32(buffer, pos, ci_ptr->num * 2);
for (cv_idx = 0; cv_idx < ci_ptr->num; cv_idx++) {
pos += store_gcov_u64(buffer, pos,
ci_ptr->values[cv_idx]);
}
ci_ptr++;
}
}
return pos;
}
/**
* gcov_iter_new - allocate and initialize profiling data iterator
* @info: profiling data set to be iterated
*
* Return file iterator on success, %NULL otherwise.
*/
struct gcov_iterator *gcov_iter_new(struct gcov_info *info)
{
struct gcov_iterator *iter;
iter = kzalloc(sizeof(struct gcov_iterator), GFP_KERNEL);
if (!iter)
goto err_free;
iter->info = info;
/* Dry-run to get the actual buffer size. */
iter->size = convert_to_gcda(NULL, info);
iter->buffer = vmalloc(iter->size);
if (!iter->buffer)
goto err_free;
convert_to_gcda(iter->buffer, info);
return iter;
err_free:
kfree(iter);
return NULL;
}
/**
* gcov_iter_get_info - return profiling data set for given file iterator
* @iter: file iterator
*/
void gcov_iter_free(struct gcov_iterator *iter)
{
vfree(iter->buffer);
kfree(iter);
}
/**
* gcov_iter_get_info - return profiling data set for given file iterator
* @iter: file iterator
*/
struct gcov_info *gcov_iter_get_info(struct gcov_iterator *iter)
{
return iter->info;
}
/**
* gcov_iter_start - reset file iterator to starting position
* @iter: file iterator
*/
void gcov_iter_start(struct gcov_iterator *iter)
{
iter->pos = 0;
}
/**
* gcov_iter_next - advance file iterator to next logical record
* @iter: file iterator
*
* Return zero if new position is valid, non-zero if iterator has reached end.
*/
int gcov_iter_next(struct gcov_iterator *iter)
{
if (iter->pos < iter->size)
iter->pos += ITER_STRIDE;
if (iter->pos >= iter->size)
return -EINVAL;
return 0;
}
/**
* gcov_iter_write - write data for current pos to seq_file
* @iter: file iterator
* @seq: seq_file handle
*
* Return zero on success, non-zero otherwise.
*/
int gcov_iter_write(struct gcov_iterator *iter, struct seq_file *seq)
{
size_t len;
if (iter->pos >= iter->size)
return -EINVAL;
len = ITER_STRIDE;
if (iter->pos + len > iter->size)
len = iter->size - iter->pos;
seq_write(seq, iter->buffer + iter->pos, len);
return 0;
}
| gpl-2.0 |
Entropy512/linux_kernel_galaxyplayer | drivers/net/wireless/orinoco/scan.c | 895 | 5440 | /* Helpers for managing scan queues
*
* See copyright notice in main.c
*/
#include <linux/gfp.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/ieee80211.h>
#include <net/cfg80211.h>
#include "hermes.h"
#include "orinoco.h"
#include "main.h"
#include "scan.h"
#define ZERO_DBM_OFFSET 0x95
#define MAX_SIGNAL_LEVEL 0x8A
#define MIN_SIGNAL_LEVEL 0x2F
#define SIGNAL_TO_DBM(x) \
(clamp_t(s32, (x), MIN_SIGNAL_LEVEL, MAX_SIGNAL_LEVEL) \
- ZERO_DBM_OFFSET)
#define SIGNAL_TO_MBM(x) (SIGNAL_TO_DBM(x) * 100)
static int symbol_build_supp_rates(u8 *buf, const __le16 *rates)
{
int i;
u8 rate;
buf[0] = WLAN_EID_SUPP_RATES;
for (i = 0; i < 5; i++) {
rate = le16_to_cpu(rates[i]);
/* NULL terminated */
if (rate == 0x0)
break;
buf[i + 2] = rate;
}
buf[1] = i;
return i + 2;
}
static int prism_build_supp_rates(u8 *buf, const u8 *rates)
{
int i;
buf[0] = WLAN_EID_SUPP_RATES;
for (i = 0; i < 8; i++) {
/* NULL terminated */
if (rates[i] == 0x0)
break;
buf[i + 2] = rates[i];
}
buf[1] = i;
/* We might still have another 2 rates, which need to go in
* extended supported rates */
if (i == 8 && rates[i] > 0) {
buf[10] = WLAN_EID_EXT_SUPP_RATES;
for (; i < 10; i++) {
/* NULL terminated */
if (rates[i] == 0x0)
break;
buf[i + 2] = rates[i];
}
buf[11] = i - 8;
}
return (i < 8) ? i + 2 : i + 4;
}
static void orinoco_add_hostscan_result(struct orinoco_private *priv,
const union hermes_scan_info *bss)
{
struct wiphy *wiphy = priv_to_wiphy(priv);
struct ieee80211_channel *channel;
u8 *ie;
u8 ie_buf[46];
u64 timestamp;
s32 signal;
u16 capability;
u16 beacon_interval;
int ie_len;
int freq;
int len;
len = le16_to_cpu(bss->a.essid_len);
/* Reconstruct SSID and bitrate IEs to pass up */
ie_buf[0] = WLAN_EID_SSID;
ie_buf[1] = len;
memcpy(&ie_buf[2], bss->a.essid, len);
ie = ie_buf + len + 2;
ie_len = ie_buf[1] + 2;
switch (priv->firmware_type) {
case FIRMWARE_TYPE_SYMBOL:
ie_len += symbol_build_supp_rates(ie, bss->s.rates);
break;
case FIRMWARE_TYPE_INTERSIL:
ie_len += prism_build_supp_rates(ie, bss->p.rates);
break;
case FIRMWARE_TYPE_AGERE:
default:
break;
}
freq = ieee80211_dsss_chan_to_freq(le16_to_cpu(bss->a.channel));
channel = ieee80211_get_channel(wiphy, freq);
timestamp = 0;
capability = le16_to_cpu(bss->a.capabilities);
beacon_interval = le16_to_cpu(bss->a.beacon_interv);
signal = SIGNAL_TO_MBM(le16_to_cpu(bss->a.level));
cfg80211_inform_bss(wiphy, channel, bss->a.bssid, timestamp,
capability, beacon_interval, ie_buf, ie_len,
signal, GFP_KERNEL);
}
void orinoco_add_extscan_result(struct orinoco_private *priv,
struct agere_ext_scan_info *bss,
size_t len)
{
struct wiphy *wiphy = priv_to_wiphy(priv);
struct ieee80211_channel *channel;
const u8 *ie;
u64 timestamp;
s32 signal;
u16 capability;
u16 beacon_interval;
size_t ie_len;
int chan, freq;
ie_len = len - sizeof(*bss);
ie = cfg80211_find_ie(WLAN_EID_DS_PARAMS, bss->data, ie_len);
chan = ie ? ie[2] : 0;
freq = ieee80211_dsss_chan_to_freq(chan);
channel = ieee80211_get_channel(wiphy, freq);
timestamp = le64_to_cpu(bss->timestamp);
capability = le16_to_cpu(bss->capabilities);
beacon_interval = le16_to_cpu(bss->beacon_interval);
ie = bss->data;
signal = SIGNAL_TO_MBM(bss->level);
cfg80211_inform_bss(wiphy, channel, bss->bssid, timestamp,
capability, beacon_interval, ie, ie_len,
signal, GFP_KERNEL);
}
void orinoco_add_hostscan_results(struct orinoco_private *priv,
unsigned char *buf,
size_t len)
{
int offset; /* In the scan data */
size_t atom_len;
bool abort = false;
switch (priv->firmware_type) {
case FIRMWARE_TYPE_AGERE:
atom_len = sizeof(struct agere_scan_apinfo);
offset = 0;
break;
case FIRMWARE_TYPE_SYMBOL:
/* Lack of documentation necessitates this hack.
* Different firmwares have 68 or 76 byte long atoms.
* We try modulo first. If the length divides by both,
* we check what would be the channel in the second
* frame for a 68-byte atom. 76-byte atoms have 0 there.
* Valid channel cannot be 0. */
if (len % 76)
atom_len = 68;
else if (len % 68)
atom_len = 76;
else if (len >= 1292 && buf[68] == 0)
atom_len = 76;
else
atom_len = 68;
offset = 0;
break;
case FIRMWARE_TYPE_INTERSIL:
offset = 4;
if (priv->has_hostscan) {
atom_len = le16_to_cpup((__le16 *)buf);
/* Sanity check for atom_len */
if (atom_len < sizeof(struct prism2_scan_apinfo)) {
printk(KERN_ERR "%s: Invalid atom_len in scan "
"data: %zu\n", priv->ndev->name,
atom_len);
abort = true;
goto scan_abort;
}
} else
atom_len = offsetof(struct prism2_scan_apinfo, atim);
break;
default:
abort = true;
goto scan_abort;
}
/* Check that we got an whole number of atoms */
if ((len - offset) % atom_len) {
printk(KERN_ERR "%s: Unexpected scan data length %zu, "
"atom_len %zu, offset %d\n", priv->ndev->name, len,
atom_len, offset);
abort = true;
goto scan_abort;
}
/* Process the entries one by one */
for (; offset + atom_len <= len; offset += atom_len) {
union hermes_scan_info *atom;
atom = (union hermes_scan_info *) (buf + offset);
orinoco_add_hostscan_result(priv, atom);
}
scan_abort:
if (priv->scan_request) {
cfg80211_scan_done(priv->scan_request, abort);
priv->scan_request = NULL;
}
}
| gpl-2.0 |
perillamint/linux-COSE341 | drivers/staging/iio/accel/sca3000_ring.c | 895 | 9492 | /*
* sca3000_ring.c -- support VTI sca3000 series accelerometers via SPI
*
* 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) 2009 Jonathan Cameron <jic23@cam.ac.uk>
*
*/
#include <linux/interrupt.h>
#include <linux/gpio.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/spi/spi.h>
#include <linux/sysfs.h>
#include "../iio.h"
#include "../sysfs.h"
#include "../ring_generic.h"
#include "../ring_hw.h"
#include "accel.h"
#include "sca3000.h"
/* RFC / future work
*
* The internal ring buffer doesn't actually change what it holds depending
* on which signals are enabled etc, merely whether you can read them.
* As such the scan mode selection is somewhat different than for a software
* ring buffer and changing it actually covers any data already in the buffer.
* Currently scan elements aren't configured so it doesn't matter.
*/
/**
* sca3000_rip_hw_rb() - main ring access function, pulls data from ring
* @r: the ring
* @count: number of samples to try and pull
* @data: output the actual samples pulled from the hw ring
* @dead_offset: cheating a bit here: Set to 1 so as to allow for the
* leading byte used in bus comms.
*
* Currently does not provide timestamps. As the hardware doesn't add them they
* can only be inferred aproximately from ring buffer events such as 50% full
* and knowledge of when buffer was last emptied. This is left to userspace.
**/
static int sca3000_rip_hw_rb(struct iio_ring_buffer *r,
size_t count, u8 **data, int *dead_offset)
{
struct iio_hw_ring_buffer *hw_ring = iio_to_hw_ring_buf(r);
struct iio_dev *indio_dev = hw_ring->private;
struct sca3000_state *st = indio_dev->dev_data;
u8 *rx;
int ret, num_available, num_read = 0;
int bytes_per_sample = 1;
if (st->bpse == 11)
bytes_per_sample = 2;
mutex_lock(&st->lock);
/* Check how much data is available:
* RFC: Implement an ioctl to not bother checking whether there
* is enough data in the ring? Afterall, if we are responding
* to an interrupt we have a minimum content guaranteed so it
* seems slight silly to waste time checking it is there.
*/
ret = sca3000_read_data(st,
SCA3000_REG_ADDR_BUF_COUNT,
&rx, 1);
if (ret)
goto error_ret;
else
num_available = rx[1];
/* num_available is the total number of samples available
* i.e. number of time points * number of channels.
*/
kfree(rx);
if (count > num_available * bytes_per_sample)
num_read = num_available*bytes_per_sample;
else
num_read = count - (count % (bytes_per_sample));
/* Avoid the read request byte */
*dead_offset = 1;
ret = sca3000_read_data(st,
SCA3000_REG_ADDR_RING_OUT,
data, num_read);
error_ret:
mutex_unlock(&st->lock);
return ret ? ret : num_read;
}
/* This is only valid with all 3 elements enabled */
static int sca3000_ring_get_length(struct iio_ring_buffer *r)
{
return 64;
}
/* only valid if resolution is kept at 11bits */
static int sca3000_ring_get_bpd(struct iio_ring_buffer *r)
{
return 6;
}
static void sca3000_ring_release(struct device *dev)
{
struct iio_ring_buffer *r = to_iio_ring_buffer(dev);
kfree(iio_to_hw_ring_buf(r));
}
static IIO_RING_ENABLE_ATTR;
static IIO_RING_BPS_ATTR;
static IIO_RING_LENGTH_ATTR;
/**
* sca3000_show_ring_bpse() -sysfs function to query bits per sample from ring
* @dev: ring buffer device
* @attr: this device attribute
* @buf: buffer to write to
**/
static ssize_t sca3000_show_ring_bpse(struct device *dev,
struct device_attribute *attr,
char *buf)
{
int len = 0, ret;
u8 *rx;
struct iio_ring_buffer *r = dev_get_drvdata(dev);
struct sca3000_state *st = r->indio_dev->dev_data;
mutex_lock(&st->lock);
ret = sca3000_read_data(st, SCA3000_REG_ADDR_MODE, &rx, 1);
if (ret)
goto error_ret;
len = sprintf(buf, "%d\n", (rx[1] & SCA3000_RING_BUF_8BIT) ? 8 : 11);
kfree(rx);
error_ret:
mutex_unlock(&st->lock);
return ret ? ret : len;
}
/**
* sca3000_store_ring_bpse() - bits per scan element
* @dev: ring buffer device
* @attr: attribute called from
* @buf: input from userspace
* @len: length of input
**/
static ssize_t sca3000_store_ring_bpse(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_ring_buffer *r = dev_get_drvdata(dev);
struct sca3000_state *st = r->indio_dev->dev_data;
int ret;
u8 *rx;
long val;
ret = strict_strtol(buf, 10, &val);
if (ret)
return ret;
mutex_lock(&st->lock);
ret = sca3000_read_data(st, SCA3000_REG_ADDR_MODE, &rx, 1);
if (!ret)
switch (val) {
case 8:
ret = sca3000_write_reg(st, SCA3000_REG_ADDR_MODE,
rx[1] | SCA3000_RING_BUF_8BIT);
st->bpse = 8;
break;
case 11:
ret = sca3000_write_reg(st, SCA3000_REG_ADDR_MODE,
rx[1] & ~SCA3000_RING_BUF_8BIT);
st->bpse = 11;
break;
default:
ret = -EINVAL;
break;
}
mutex_unlock(&st->lock);
return ret ? ret : len;
}
static IIO_SCAN_EL_C(accel_x, 0, 0, 0, NULL);
static IIO_SCAN_EL_C(accel_y, 1, 0, 0, NULL);
static IIO_SCAN_EL_C(accel_z, 2, 0, 0, NULL);
static IIO_CONST_ATTR(accel_precision_available, "8 11");
static IIO_DEVICE_ATTR(accel_precision,
S_IRUGO | S_IWUSR,
sca3000_show_ring_bpse,
sca3000_store_ring_bpse,
0);
static struct attribute *sca3000_scan_el_attrs[] = {
&iio_scan_el_accel_x.dev_attr.attr,
&iio_scan_el_accel_y.dev_attr.attr,
&iio_scan_el_accel_z.dev_attr.attr,
&iio_const_attr_accel_precision_available.dev_attr.attr,
&iio_dev_attr_accel_precision.dev_attr.attr,
NULL
};
static struct attribute_group sca3000_scan_el_group = {
.attrs = sca3000_scan_el_attrs,
.name = "scan_elements",
};
/*
* Ring buffer attributes
* This device is a bit unusual in that the sampling frequency and bpse
* only apply to the ring buffer. At all times full rate and accuracy
* is available via direct reading from registers.
*/
static struct attribute *sca3000_ring_attributes[] = {
&dev_attr_length.attr,
&dev_attr_bps.attr,
&dev_attr_ring_enable.attr,
NULL,
};
static struct attribute_group sca3000_ring_attr = {
.attrs = sca3000_ring_attributes,
};
static const struct attribute_group *sca3000_ring_attr_groups[] = {
&sca3000_ring_attr,
NULL
};
static struct device_type sca3000_ring_type = {
.release = sca3000_ring_release,
.groups = sca3000_ring_attr_groups,
};
static struct iio_ring_buffer *sca3000_rb_allocate(struct iio_dev *indio_dev)
{
struct iio_ring_buffer *buf;
struct iio_hw_ring_buffer *ring;
ring = kzalloc(sizeof *ring, GFP_KERNEL);
if (!ring)
return NULL;
ring->private = indio_dev;
buf = &ring->buf;
iio_ring_buffer_init(buf, indio_dev);
buf->dev.type = &sca3000_ring_type;
device_initialize(&buf->dev);
buf->dev.parent = &indio_dev->dev;
dev_set_drvdata(&buf->dev, (void *)buf);
return buf;
}
static inline void sca3000_rb_free(struct iio_ring_buffer *r)
{
if (r)
iio_put_ring_buffer(r);
}
int sca3000_configure_ring(struct iio_dev *indio_dev)
{
indio_dev->scan_el_attrs = &sca3000_scan_el_group;
indio_dev->ring = sca3000_rb_allocate(indio_dev);
if (indio_dev->ring == NULL)
return -ENOMEM;
indio_dev->modes |= INDIO_RING_HARDWARE_BUFFER;
indio_dev->ring->access.rip_lots = &sca3000_rip_hw_rb;
indio_dev->ring->access.get_length = &sca3000_ring_get_length;
indio_dev->ring->access.get_bpd = &sca3000_ring_get_bpd;
return 0;
}
void sca3000_unconfigure_ring(struct iio_dev *indio_dev)
{
sca3000_rb_free(indio_dev->ring);
}
static inline
int __sca3000_hw_ring_state_set(struct iio_dev *indio_dev, bool state)
{
struct sca3000_state *st = indio_dev->dev_data;
int ret;
u8 *rx;
mutex_lock(&st->lock);
ret = sca3000_read_data(st, SCA3000_REG_ADDR_MODE, &rx, 1);
if (ret)
goto error_ret;
if (state) {
printk(KERN_INFO "supposedly enabling ring buffer\n");
ret = sca3000_write_reg(st,
SCA3000_REG_ADDR_MODE,
(rx[1] | SCA3000_RING_BUF_ENABLE));
} else
ret = sca3000_write_reg(st,
SCA3000_REG_ADDR_MODE,
(rx[1] & ~SCA3000_RING_BUF_ENABLE));
kfree(rx);
error_ret:
mutex_unlock(&st->lock);
return ret;
}
/**
* sca3000_hw_ring_preenable() hw ring buffer preenable function
*
* Very simple enable function as the chip will allows normal reads
* during ring buffer operation so as long as it is indeed running
* before we notify the core, the precise ordering does not matter.
**/
static int sca3000_hw_ring_preenable(struct iio_dev *indio_dev)
{
return __sca3000_hw_ring_state_set(indio_dev, 1);
}
static int sca3000_hw_ring_postdisable(struct iio_dev *indio_dev)
{
return __sca3000_hw_ring_state_set(indio_dev, 0);
}
void sca3000_register_ring_funcs(struct iio_dev *indio_dev)
{
indio_dev->ring->preenable = &sca3000_hw_ring_preenable;
indio_dev->ring->postdisable = &sca3000_hw_ring_postdisable;
}
/**
* sca3000_ring_int_process() ring specific interrupt handling.
*
* This is only split from the main interrupt handler so as to
* reduce the amount of code if the ring buffer is not enabled.
**/
void sca3000_ring_int_process(u8 val, struct iio_ring_buffer *ring)
{
if (val & SCA3000_INT_STATUS_THREE_QUARTERS)
iio_push_or_escallate_ring_event(ring,
IIO_EVENT_CODE_RING_75_FULL,
0);
else if (val & SCA3000_INT_STATUS_HALF)
iio_push_ring_event(ring,
IIO_EVENT_CODE_RING_50_FULL, 0);
}
| gpl-2.0 |
Tigrouzen/Samsung_Wave_Kernel_SD_NAND | arch/arm/mach-at91/at91sam9260_devices.c | 895 | 33090 | /*
* arch/arm/mach-at91/at91sam9260_devices.c
*
* Copyright (C) 2006 Atmel
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
*/
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <linux/dma-mapping.h>
#include <linux/platform_device.h>
#include <linux/i2c-gpio.h>
#include <mach/board.h>
#include <mach/gpio.h>
#include <mach/cpu.h>
#include <mach/at91sam9260.h>
#include <mach/at91sam9260_matrix.h>
#include <mach/at91sam9_smc.h>
#include "generic.h"
/* --------------------------------------------------------------------
* USB Host
* -------------------------------------------------------------------- */
#if defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE)
static u64 ohci_dmamask = DMA_BIT_MASK(32);
static struct at91_usbh_data usbh_data;
static struct resource usbh_resources[] = {
[0] = {
.start = AT91SAM9260_UHP_BASE,
.end = AT91SAM9260_UHP_BASE + SZ_1M - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_UHP,
.end = AT91SAM9260_ID_UHP,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91_usbh_device = {
.name = "at91_ohci",
.id = -1,
.dev = {
.dma_mask = &ohci_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &usbh_data,
},
.resource = usbh_resources,
.num_resources = ARRAY_SIZE(usbh_resources),
};
void __init at91_add_device_usbh(struct at91_usbh_data *data)
{
if (!data)
return;
usbh_data = *data;
platform_device_register(&at91_usbh_device);
}
#else
void __init at91_add_device_usbh(struct at91_usbh_data *data) {}
#endif
/* --------------------------------------------------------------------
* USB Device (Gadget)
* -------------------------------------------------------------------- */
#ifdef CONFIG_USB_GADGET_AT91
static struct at91_udc_data udc_data;
static struct resource udc_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_UDP,
.end = AT91SAM9260_BASE_UDP + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_UDP,
.end = AT91SAM9260_ID_UDP,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91_udc_device = {
.name = "at91_udc",
.id = -1,
.dev = {
.platform_data = &udc_data,
},
.resource = udc_resources,
.num_resources = ARRAY_SIZE(udc_resources),
};
void __init at91_add_device_udc(struct at91_udc_data *data)
{
if (!data)
return;
if (data->vbus_pin) {
at91_set_gpio_input(data->vbus_pin, 0);
at91_set_deglitch(data->vbus_pin, 1);
}
/* Pullup pin is handled internally by USB device peripheral */
udc_data = *data;
platform_device_register(&at91_udc_device);
}
#else
void __init at91_add_device_udc(struct at91_udc_data *data) {}
#endif
/* --------------------------------------------------------------------
* Ethernet
* -------------------------------------------------------------------- */
#if defined(CONFIG_MACB) || defined(CONFIG_MACB_MODULE)
static u64 eth_dmamask = DMA_BIT_MASK(32);
static struct at91_eth_data eth_data;
static struct resource eth_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_EMAC,
.end = AT91SAM9260_BASE_EMAC + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_EMAC,
.end = AT91SAM9260_ID_EMAC,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9260_eth_device = {
.name = "macb",
.id = -1,
.dev = {
.dma_mask = ð_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = ð_data,
},
.resource = eth_resources,
.num_resources = ARRAY_SIZE(eth_resources),
};
void __init at91_add_device_eth(struct at91_eth_data *data)
{
if (!data)
return;
if (data->phy_irq_pin) {
at91_set_gpio_input(data->phy_irq_pin, 0);
at91_set_deglitch(data->phy_irq_pin, 1);
}
/* Pins used for MII and RMII */
at91_set_A_periph(AT91_PIN_PA19, 0); /* ETXCK_EREFCK */
at91_set_A_periph(AT91_PIN_PA17, 0); /* ERXDV */
at91_set_A_periph(AT91_PIN_PA14, 0); /* ERX0 */
at91_set_A_periph(AT91_PIN_PA15, 0); /* ERX1 */
at91_set_A_periph(AT91_PIN_PA18, 0); /* ERXER */
at91_set_A_periph(AT91_PIN_PA16, 0); /* ETXEN */
at91_set_A_periph(AT91_PIN_PA12, 0); /* ETX0 */
at91_set_A_periph(AT91_PIN_PA13, 0); /* ETX1 */
at91_set_A_periph(AT91_PIN_PA21, 0); /* EMDIO */
at91_set_A_periph(AT91_PIN_PA20, 0); /* EMDC */
if (!data->is_rmii) {
at91_set_B_periph(AT91_PIN_PA28, 0); /* ECRS */
at91_set_B_periph(AT91_PIN_PA29, 0); /* ECOL */
at91_set_B_periph(AT91_PIN_PA25, 0); /* ERX2 */
at91_set_B_periph(AT91_PIN_PA26, 0); /* ERX3 */
at91_set_B_periph(AT91_PIN_PA27, 0); /* ERXCK */
at91_set_B_periph(AT91_PIN_PA23, 0); /* ETX2 */
at91_set_B_periph(AT91_PIN_PA24, 0); /* ETX3 */
at91_set_B_periph(AT91_PIN_PA22, 0); /* ETXER */
}
eth_data = *data;
platform_device_register(&at91sam9260_eth_device);
}
#else
void __init at91_add_device_eth(struct at91_eth_data *data) {}
#endif
/* --------------------------------------------------------------------
* MMC / SD
* -------------------------------------------------------------------- */
#if defined(CONFIG_MMC_AT91) || defined(CONFIG_MMC_AT91_MODULE)
static u64 mmc_dmamask = DMA_BIT_MASK(32);
static struct at91_mmc_data mmc_data;
static struct resource mmc_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_MCI,
.end = AT91SAM9260_BASE_MCI + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_MCI,
.end = AT91SAM9260_ID_MCI,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9260_mmc_device = {
.name = "at91_mci",
.id = -1,
.dev = {
.dma_mask = &mmc_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &mmc_data,
},
.resource = mmc_resources,
.num_resources = ARRAY_SIZE(mmc_resources),
};
void __init at91_add_device_mmc(short mmc_id, struct at91_mmc_data *data)
{
if (!data)
return;
/* input/irq */
if (data->det_pin) {
at91_set_gpio_input(data->det_pin, 1);
at91_set_deglitch(data->det_pin, 1);
}
if (data->wp_pin)
at91_set_gpio_input(data->wp_pin, 1);
if (data->vcc_pin)
at91_set_gpio_output(data->vcc_pin, 0);
/* CLK */
at91_set_A_periph(AT91_PIN_PA8, 0);
if (data->slot_b) {
/* CMD */
at91_set_B_periph(AT91_PIN_PA1, 1);
/* DAT0, maybe DAT1..DAT3 */
at91_set_B_periph(AT91_PIN_PA0, 1);
if (data->wire4) {
at91_set_B_periph(AT91_PIN_PA5, 1);
at91_set_B_periph(AT91_PIN_PA4, 1);
at91_set_B_periph(AT91_PIN_PA3, 1);
}
} else {
/* CMD */
at91_set_A_periph(AT91_PIN_PA7, 1);
/* DAT0, maybe DAT1..DAT3 */
at91_set_A_periph(AT91_PIN_PA6, 1);
if (data->wire4) {
at91_set_A_periph(AT91_PIN_PA9, 1);
at91_set_A_periph(AT91_PIN_PA10, 1);
at91_set_A_periph(AT91_PIN_PA11, 1);
}
}
mmc_data = *data;
platform_device_register(&at91sam9260_mmc_device);
}
#else
void __init at91_add_device_mmc(short mmc_id, struct at91_mmc_data *data) {}
#endif
/* --------------------------------------------------------------------
* MMC / SD Slot for Atmel MCI Driver
* -------------------------------------------------------------------- */
#if defined(CONFIG_MMC_ATMELMCI) || defined(CONFIG_MMC_ATMELMCI_MODULE)
static u64 mmc_dmamask = DMA_BIT_MASK(32);
static struct mci_platform_data mmc_data;
static struct resource mmc_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_MCI,
.end = AT91SAM9260_BASE_MCI + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_MCI,
.end = AT91SAM9260_ID_MCI,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9260_mmc_device = {
.name = "atmel_mci",
.id = -1,
.dev = {
.dma_mask = &mmc_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &mmc_data,
},
.resource = mmc_resources,
.num_resources = ARRAY_SIZE(mmc_resources),
};
void __init at91_add_device_mci(short mmc_id, struct mci_platform_data *data)
{
unsigned int i;
unsigned int slot_count = 0;
if (!data)
return;
for (i = 0; i < ATMEL_MCI_MAX_NR_SLOTS; i++) {
if (data->slot[i].bus_width) {
/* input/irq */
if (data->slot[i].detect_pin) {
at91_set_gpio_input(data->slot[i].detect_pin, 1);
at91_set_deglitch(data->slot[i].detect_pin, 1);
}
if (data->slot[i].wp_pin)
at91_set_gpio_input(data->slot[i].wp_pin, 1);
switch (i) {
case 0:
/* CMD */
at91_set_A_periph(AT91_PIN_PA7, 1);
/* DAT0, maybe DAT1..DAT3 */
at91_set_A_periph(AT91_PIN_PA6, 1);
if (data->slot[i].bus_width == 4) {
at91_set_A_periph(AT91_PIN_PA9, 1);
at91_set_A_periph(AT91_PIN_PA10, 1);
at91_set_A_periph(AT91_PIN_PA11, 1);
}
slot_count++;
break;
case 1:
/* CMD */
at91_set_B_periph(AT91_PIN_PA1, 1);
/* DAT0, maybe DAT1..DAT3 */
at91_set_B_periph(AT91_PIN_PA0, 1);
if (data->slot[i].bus_width == 4) {
at91_set_B_periph(AT91_PIN_PA5, 1);
at91_set_B_periph(AT91_PIN_PA4, 1);
at91_set_B_periph(AT91_PIN_PA3, 1);
}
slot_count++;
break;
default:
printk(KERN_ERR
"AT91: SD/MMC slot %d not available\n", i);
break;
}
}
}
if (slot_count) {
/* CLK */
at91_set_A_periph(AT91_PIN_PA8, 0);
mmc_data = *data;
platform_device_register(&at91sam9260_mmc_device);
}
}
#else
void __init at91_add_device_mci(short mmc_id, struct mci_platform_data *data) {}
#endif
/* --------------------------------------------------------------------
* NAND / SmartMedia
* -------------------------------------------------------------------- */
#if defined(CONFIG_MTD_NAND_ATMEL) || defined(CONFIG_MTD_NAND_ATMEL_MODULE)
static struct atmel_nand_data nand_data;
#define NAND_BASE AT91_CHIPSELECT_3
static struct resource nand_resources[] = {
[0] = {
.start = NAND_BASE,
.end = NAND_BASE + SZ_256M - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91_BASE_SYS + AT91_ECC,
.end = AT91_BASE_SYS + AT91_ECC + SZ_512 - 1,
.flags = IORESOURCE_MEM,
}
};
static struct platform_device at91sam9260_nand_device = {
.name = "atmel_nand",
.id = -1,
.dev = {
.platform_data = &nand_data,
},
.resource = nand_resources,
.num_resources = ARRAY_SIZE(nand_resources),
};
void __init at91_add_device_nand(struct atmel_nand_data *data)
{
unsigned long csa;
if (!data)
return;
csa = at91_sys_read(AT91_MATRIX_EBICSA);
at91_sys_write(AT91_MATRIX_EBICSA, csa | AT91_MATRIX_CS3A_SMC_SMARTMEDIA);
/* enable pin */
if (data->enable_pin)
at91_set_gpio_output(data->enable_pin, 1);
/* ready/busy pin */
if (data->rdy_pin)
at91_set_gpio_input(data->rdy_pin, 1);
/* card detect pin */
if (data->det_pin)
at91_set_gpio_input(data->det_pin, 1);
nand_data = *data;
platform_device_register(&at91sam9260_nand_device);
}
#else
void __init at91_add_device_nand(struct atmel_nand_data *data) {}
#endif
/* --------------------------------------------------------------------
* TWI (i2c)
* -------------------------------------------------------------------- */
/*
* Prefer the GPIO code since the TWI controller isn't robust
* (gets overruns and underruns under load) and can only issue
* repeated STARTs in one scenario (the driver doesn't yet handle them).
*/
#if defined(CONFIG_I2C_GPIO) || defined(CONFIG_I2C_GPIO_MODULE)
static struct i2c_gpio_platform_data pdata = {
.sda_pin = AT91_PIN_PA23,
.sda_is_open_drain = 1,
.scl_pin = AT91_PIN_PA24,
.scl_is_open_drain = 1,
.udelay = 2, /* ~100 kHz */
};
static struct platform_device at91sam9260_twi_device = {
.name = "i2c-gpio",
.id = 0,
.dev.platform_data = &pdata,
};
void __init at91_add_device_i2c(struct i2c_board_info *devices, int nr_devices)
{
at91_set_GPIO_periph(AT91_PIN_PA23, 1); /* TWD (SDA) */
at91_set_multi_drive(AT91_PIN_PA23, 1);
at91_set_GPIO_periph(AT91_PIN_PA24, 1); /* TWCK (SCL) */
at91_set_multi_drive(AT91_PIN_PA24, 1);
i2c_register_board_info(0, devices, nr_devices);
platform_device_register(&at91sam9260_twi_device);
}
#elif defined(CONFIG_I2C_AT91) || defined(CONFIG_I2C_AT91_MODULE)
static struct resource twi_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_TWI,
.end = AT91SAM9260_BASE_TWI + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_TWI,
.end = AT91SAM9260_ID_TWI,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9260_twi_device = {
.name = "at91_i2c",
.id = -1,
.resource = twi_resources,
.num_resources = ARRAY_SIZE(twi_resources),
};
void __init at91_add_device_i2c(struct i2c_board_info *devices, int nr_devices)
{
/* pins used for TWI interface */
at91_set_A_periph(AT91_PIN_PA23, 0); /* TWD */
at91_set_multi_drive(AT91_PIN_PA23, 1);
at91_set_A_periph(AT91_PIN_PA24, 0); /* TWCK */
at91_set_multi_drive(AT91_PIN_PA24, 1);
i2c_register_board_info(0, devices, nr_devices);
platform_device_register(&at91sam9260_twi_device);
}
#else
void __init at91_add_device_i2c(struct i2c_board_info *devices, int nr_devices) {}
#endif
/* --------------------------------------------------------------------
* SPI
* -------------------------------------------------------------------- */
#if defined(CONFIG_SPI_ATMEL) || defined(CONFIG_SPI_ATMEL_MODULE)
static u64 spi_dmamask = DMA_BIT_MASK(32);
static struct resource spi0_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_SPI0,
.end = AT91SAM9260_BASE_SPI0 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_SPI0,
.end = AT91SAM9260_ID_SPI0,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9260_spi0_device = {
.name = "atmel_spi",
.id = 0,
.dev = {
.dma_mask = &spi_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
.resource = spi0_resources,
.num_resources = ARRAY_SIZE(spi0_resources),
};
static const unsigned spi0_standard_cs[4] = { AT91_PIN_PA3, AT91_PIN_PC11, AT91_PIN_PC16, AT91_PIN_PC17 };
static struct resource spi1_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_SPI1,
.end = AT91SAM9260_BASE_SPI1 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_SPI1,
.end = AT91SAM9260_ID_SPI1,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9260_spi1_device = {
.name = "atmel_spi",
.id = 1,
.dev = {
.dma_mask = &spi_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
.resource = spi1_resources,
.num_resources = ARRAY_SIZE(spi1_resources),
};
static const unsigned spi1_standard_cs[4] = { AT91_PIN_PB3, AT91_PIN_PC5, AT91_PIN_PC4, AT91_PIN_PC3 };
void __init at91_add_device_spi(struct spi_board_info *devices, int nr_devices)
{
int i;
unsigned long cs_pin;
short enable_spi0 = 0;
short enable_spi1 = 0;
/* Choose SPI chip-selects */
for (i = 0; i < nr_devices; i++) {
if (devices[i].controller_data)
cs_pin = (unsigned long) devices[i].controller_data;
else if (devices[i].bus_num == 0)
cs_pin = spi0_standard_cs[devices[i].chip_select];
else
cs_pin = spi1_standard_cs[devices[i].chip_select];
if (devices[i].bus_num == 0)
enable_spi0 = 1;
else
enable_spi1 = 1;
/* enable chip-select pin */
at91_set_gpio_output(cs_pin, 1);
/* pass chip-select pin to driver */
devices[i].controller_data = (void *) cs_pin;
}
spi_register_board_info(devices, nr_devices);
/* Configure SPI bus(es) */
if (enable_spi0) {
at91_set_A_periph(AT91_PIN_PA0, 0); /* SPI0_MISO */
at91_set_A_periph(AT91_PIN_PA1, 0); /* SPI0_MOSI */
at91_set_A_periph(AT91_PIN_PA2, 0); /* SPI1_SPCK */
platform_device_register(&at91sam9260_spi0_device);
}
if (enable_spi1) {
at91_set_A_periph(AT91_PIN_PB0, 0); /* SPI1_MISO */
at91_set_A_periph(AT91_PIN_PB1, 0); /* SPI1_MOSI */
at91_set_A_periph(AT91_PIN_PB2, 0); /* SPI1_SPCK */
platform_device_register(&at91sam9260_spi1_device);
}
}
#else
void __init at91_add_device_spi(struct spi_board_info *devices, int nr_devices) {}
#endif
/* --------------------------------------------------------------------
* Timer/Counter blocks
* -------------------------------------------------------------------- */
#ifdef CONFIG_ATMEL_TCLIB
static struct resource tcb0_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_TCB0,
.end = AT91SAM9260_BASE_TCB0 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_TC0,
.end = AT91SAM9260_ID_TC0,
.flags = IORESOURCE_IRQ,
},
[2] = {
.start = AT91SAM9260_ID_TC1,
.end = AT91SAM9260_ID_TC1,
.flags = IORESOURCE_IRQ,
},
[3] = {
.start = AT91SAM9260_ID_TC2,
.end = AT91SAM9260_ID_TC2,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9260_tcb0_device = {
.name = "atmel_tcb",
.id = 0,
.resource = tcb0_resources,
.num_resources = ARRAY_SIZE(tcb0_resources),
};
static struct resource tcb1_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_TCB1,
.end = AT91SAM9260_BASE_TCB1 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_TC3,
.end = AT91SAM9260_ID_TC3,
.flags = IORESOURCE_IRQ,
},
[2] = {
.start = AT91SAM9260_ID_TC4,
.end = AT91SAM9260_ID_TC4,
.flags = IORESOURCE_IRQ,
},
[3] = {
.start = AT91SAM9260_ID_TC5,
.end = AT91SAM9260_ID_TC5,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9260_tcb1_device = {
.name = "atmel_tcb",
.id = 1,
.resource = tcb1_resources,
.num_resources = ARRAY_SIZE(tcb1_resources),
};
static void __init at91_add_device_tc(void)
{
platform_device_register(&at91sam9260_tcb0_device);
platform_device_register(&at91sam9260_tcb1_device);
}
#else
static void __init at91_add_device_tc(void) { }
#endif
/* --------------------------------------------------------------------
* RTT
* -------------------------------------------------------------------- */
static struct resource rtt_resources[] = {
{
.start = AT91_BASE_SYS + AT91_RTT,
.end = AT91_BASE_SYS + AT91_RTT + SZ_16 - 1,
.flags = IORESOURCE_MEM,
}
};
static struct platform_device at91sam9260_rtt_device = {
.name = "at91_rtt",
.id = 0,
.resource = rtt_resources,
.num_resources = ARRAY_SIZE(rtt_resources),
};
static void __init at91_add_device_rtt(void)
{
platform_device_register(&at91sam9260_rtt_device);
}
/* --------------------------------------------------------------------
* Watchdog
* -------------------------------------------------------------------- */
#if defined(CONFIG_AT91SAM9X_WATCHDOG) || defined(CONFIG_AT91SAM9X_WATCHDOG_MODULE)
static struct platform_device at91sam9260_wdt_device = {
.name = "at91_wdt",
.id = -1,
.num_resources = 0,
};
static void __init at91_add_device_watchdog(void)
{
platform_device_register(&at91sam9260_wdt_device);
}
#else
static void __init at91_add_device_watchdog(void) {}
#endif
/* --------------------------------------------------------------------
* SSC -- Synchronous Serial Controller
* -------------------------------------------------------------------- */
#if defined(CONFIG_ATMEL_SSC) || defined(CONFIG_ATMEL_SSC_MODULE)
static u64 ssc_dmamask = DMA_BIT_MASK(32);
static struct resource ssc_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_SSC,
.end = AT91SAM9260_BASE_SSC + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_SSC,
.end = AT91SAM9260_ID_SSC,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9260_ssc_device = {
.name = "ssc",
.id = 0,
.dev = {
.dma_mask = &ssc_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
.resource = ssc_resources,
.num_resources = ARRAY_SIZE(ssc_resources),
};
static inline void configure_ssc_pins(unsigned pins)
{
if (pins & ATMEL_SSC_TF)
at91_set_A_periph(AT91_PIN_PB17, 1);
if (pins & ATMEL_SSC_TK)
at91_set_A_periph(AT91_PIN_PB16, 1);
if (pins & ATMEL_SSC_TD)
at91_set_A_periph(AT91_PIN_PB18, 1);
if (pins & ATMEL_SSC_RD)
at91_set_A_periph(AT91_PIN_PB19, 1);
if (pins & ATMEL_SSC_RK)
at91_set_A_periph(AT91_PIN_PB20, 1);
if (pins & ATMEL_SSC_RF)
at91_set_A_periph(AT91_PIN_PB21, 1);
}
/*
* SSC controllers are accessed through library code, instead of any
* kind of all-singing/all-dancing driver. For example one could be
* used by a particular I2S audio codec's driver, while another one
* on the same system might be used by a custom data capture driver.
*/
void __init at91_add_device_ssc(unsigned id, unsigned pins)
{
struct platform_device *pdev;
/*
* NOTE: caller is responsible for passing information matching
* "pins" to whatever will be using each particular controller.
*/
switch (id) {
case AT91SAM9260_ID_SSC:
pdev = &at91sam9260_ssc_device;
configure_ssc_pins(pins);
break;
default:
return;
}
platform_device_register(pdev);
}
#else
void __init at91_add_device_ssc(unsigned id, unsigned pins) {}
#endif
/* --------------------------------------------------------------------
* UART
* -------------------------------------------------------------------- */
#if defined(CONFIG_SERIAL_ATMEL)
static struct resource dbgu_resources[] = {
[0] = {
.start = AT91_VA_BASE_SYS + AT91_DBGU,
.end = AT91_VA_BASE_SYS + AT91_DBGU + SZ_512 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91_ID_SYS,
.end = AT91_ID_SYS,
.flags = IORESOURCE_IRQ,
},
};
static struct atmel_uart_data dbgu_data = {
.use_dma_tx = 0,
.use_dma_rx = 0, /* DBGU not capable of receive DMA */
.regs = (void __iomem *)(AT91_VA_BASE_SYS + AT91_DBGU),
};
static u64 dbgu_dmamask = DMA_BIT_MASK(32);
static struct platform_device at91sam9260_dbgu_device = {
.name = "atmel_usart",
.id = 0,
.dev = {
.dma_mask = &dbgu_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &dbgu_data,
},
.resource = dbgu_resources,
.num_resources = ARRAY_SIZE(dbgu_resources),
};
static inline void configure_dbgu_pins(void)
{
at91_set_A_periph(AT91_PIN_PB14, 0); /* DRXD */
at91_set_A_periph(AT91_PIN_PB15, 1); /* DTXD */
}
static struct resource uart0_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_US0,
.end = AT91SAM9260_BASE_US0 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_US0,
.end = AT91SAM9260_ID_US0,
.flags = IORESOURCE_IRQ,
},
};
static struct atmel_uart_data uart0_data = {
.use_dma_tx = 1,
.use_dma_rx = 1,
};
static u64 uart0_dmamask = DMA_BIT_MASK(32);
static struct platform_device at91sam9260_uart0_device = {
.name = "atmel_usart",
.id = 1,
.dev = {
.dma_mask = &uart0_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &uart0_data,
},
.resource = uart0_resources,
.num_resources = ARRAY_SIZE(uart0_resources),
};
static inline void configure_usart0_pins(unsigned pins)
{
at91_set_A_periph(AT91_PIN_PB4, 1); /* TXD0 */
at91_set_A_periph(AT91_PIN_PB5, 0); /* RXD0 */
if (pins & ATMEL_UART_RTS)
at91_set_A_periph(AT91_PIN_PB26, 0); /* RTS0 */
if (pins & ATMEL_UART_CTS)
at91_set_A_periph(AT91_PIN_PB27, 0); /* CTS0 */
if (pins & ATMEL_UART_DTR)
at91_set_A_periph(AT91_PIN_PB24, 0); /* DTR0 */
if (pins & ATMEL_UART_DSR)
at91_set_A_periph(AT91_PIN_PB22, 0); /* DSR0 */
if (pins & ATMEL_UART_DCD)
at91_set_A_periph(AT91_PIN_PB23, 0); /* DCD0 */
if (pins & ATMEL_UART_RI)
at91_set_A_periph(AT91_PIN_PB25, 0); /* RI0 */
}
static struct resource uart1_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_US1,
.end = AT91SAM9260_BASE_US1 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_US1,
.end = AT91SAM9260_ID_US1,
.flags = IORESOURCE_IRQ,
},
};
static struct atmel_uart_data uart1_data = {
.use_dma_tx = 1,
.use_dma_rx = 1,
};
static u64 uart1_dmamask = DMA_BIT_MASK(32);
static struct platform_device at91sam9260_uart1_device = {
.name = "atmel_usart",
.id = 2,
.dev = {
.dma_mask = &uart1_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &uart1_data,
},
.resource = uart1_resources,
.num_resources = ARRAY_SIZE(uart1_resources),
};
static inline void configure_usart1_pins(unsigned pins)
{
at91_set_A_periph(AT91_PIN_PB6, 1); /* TXD1 */
at91_set_A_periph(AT91_PIN_PB7, 0); /* RXD1 */
if (pins & ATMEL_UART_RTS)
at91_set_A_periph(AT91_PIN_PB28, 0); /* RTS1 */
if (pins & ATMEL_UART_CTS)
at91_set_A_periph(AT91_PIN_PB29, 0); /* CTS1 */
}
static struct resource uart2_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_US2,
.end = AT91SAM9260_BASE_US2 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_US2,
.end = AT91SAM9260_ID_US2,
.flags = IORESOURCE_IRQ,
},
};
static struct atmel_uart_data uart2_data = {
.use_dma_tx = 1,
.use_dma_rx = 1,
};
static u64 uart2_dmamask = DMA_BIT_MASK(32);
static struct platform_device at91sam9260_uart2_device = {
.name = "atmel_usart",
.id = 3,
.dev = {
.dma_mask = &uart2_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &uart2_data,
},
.resource = uart2_resources,
.num_resources = ARRAY_SIZE(uart2_resources),
};
static inline void configure_usart2_pins(unsigned pins)
{
at91_set_A_periph(AT91_PIN_PB8, 1); /* TXD2 */
at91_set_A_periph(AT91_PIN_PB9, 0); /* RXD2 */
if (pins & ATMEL_UART_RTS)
at91_set_A_periph(AT91_PIN_PA4, 0); /* RTS2 */
if (pins & ATMEL_UART_CTS)
at91_set_A_periph(AT91_PIN_PA5, 0); /* CTS2 */
}
static struct resource uart3_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_US3,
.end = AT91SAM9260_BASE_US3 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_US3,
.end = AT91SAM9260_ID_US3,
.flags = IORESOURCE_IRQ,
},
};
static struct atmel_uart_data uart3_data = {
.use_dma_tx = 1,
.use_dma_rx = 1,
};
static u64 uart3_dmamask = DMA_BIT_MASK(32);
static struct platform_device at91sam9260_uart3_device = {
.name = "atmel_usart",
.id = 4,
.dev = {
.dma_mask = &uart3_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &uart3_data,
},
.resource = uart3_resources,
.num_resources = ARRAY_SIZE(uart3_resources),
};
static inline void configure_usart3_pins(unsigned pins)
{
at91_set_A_periph(AT91_PIN_PB10, 1); /* TXD3 */
at91_set_A_periph(AT91_PIN_PB11, 0); /* RXD3 */
if (pins & ATMEL_UART_RTS)
at91_set_B_periph(AT91_PIN_PC8, 0); /* RTS3 */
if (pins & ATMEL_UART_CTS)
at91_set_B_periph(AT91_PIN_PC10, 0); /* CTS3 */
}
static struct resource uart4_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_US4,
.end = AT91SAM9260_BASE_US4 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_US4,
.end = AT91SAM9260_ID_US4,
.flags = IORESOURCE_IRQ,
},
};
static struct atmel_uart_data uart4_data = {
.use_dma_tx = 1,
.use_dma_rx = 1,
};
static u64 uart4_dmamask = DMA_BIT_MASK(32);
static struct platform_device at91sam9260_uart4_device = {
.name = "atmel_usart",
.id = 5,
.dev = {
.dma_mask = &uart4_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &uart4_data,
},
.resource = uart4_resources,
.num_resources = ARRAY_SIZE(uart4_resources),
};
static inline void configure_usart4_pins(void)
{
at91_set_B_periph(AT91_PIN_PA31, 1); /* TXD4 */
at91_set_B_periph(AT91_PIN_PA30, 0); /* RXD4 */
}
static struct resource uart5_resources[] = {
[0] = {
.start = AT91SAM9260_BASE_US5,
.end = AT91SAM9260_BASE_US5 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9260_ID_US5,
.end = AT91SAM9260_ID_US5,
.flags = IORESOURCE_IRQ,
},
};
static struct atmel_uart_data uart5_data = {
.use_dma_tx = 1,
.use_dma_rx = 1,
};
static u64 uart5_dmamask = DMA_BIT_MASK(32);
static struct platform_device at91sam9260_uart5_device = {
.name = "atmel_usart",
.id = 6,
.dev = {
.dma_mask = &uart5_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &uart5_data,
},
.resource = uart5_resources,
.num_resources = ARRAY_SIZE(uart5_resources),
};
static inline void configure_usart5_pins(void)
{
at91_set_A_periph(AT91_PIN_PB12, 1); /* TXD5 */
at91_set_A_periph(AT91_PIN_PB13, 0); /* RXD5 */
}
static struct platform_device *__initdata at91_uarts[ATMEL_MAX_UART]; /* the UARTs to use */
struct platform_device *atmel_default_console_device; /* the serial console device */
void __init at91_register_uart(unsigned id, unsigned portnr, unsigned pins)
{
struct platform_device *pdev;
struct atmel_uart_data *pdata;
switch (id) {
case 0: /* DBGU */
pdev = &at91sam9260_dbgu_device;
configure_dbgu_pins();
break;
case AT91SAM9260_ID_US0:
pdev = &at91sam9260_uart0_device;
configure_usart0_pins(pins);
break;
case AT91SAM9260_ID_US1:
pdev = &at91sam9260_uart1_device;
configure_usart1_pins(pins);
break;
case AT91SAM9260_ID_US2:
pdev = &at91sam9260_uart2_device;
configure_usart2_pins(pins);
break;
case AT91SAM9260_ID_US3:
pdev = &at91sam9260_uart3_device;
configure_usart3_pins(pins);
break;
case AT91SAM9260_ID_US4:
pdev = &at91sam9260_uart4_device;
configure_usart4_pins();
break;
case AT91SAM9260_ID_US5:
pdev = &at91sam9260_uart5_device;
configure_usart5_pins();
break;
default:
return;
}
pdata = pdev->dev.platform_data;
pdata->num = portnr; /* update to mapped ID */
if (portnr < ATMEL_MAX_UART)
at91_uarts[portnr] = pdev;
}
void __init at91_set_serial_console(unsigned portnr)
{
if (portnr < ATMEL_MAX_UART) {
atmel_default_console_device = at91_uarts[portnr];
at91sam9260_set_console_clock(at91_uarts[portnr]->id);
}
}
void __init at91_add_device_serial(void)
{
int i;
for (i = 0; i < ATMEL_MAX_UART; i++) {
if (at91_uarts[i])
platform_device_register(at91_uarts[i]);
}
if (!atmel_default_console_device)
printk(KERN_INFO "AT91: No default serial console defined.\n");
}
#else
void __init at91_register_uart(unsigned id, unsigned portnr, unsigned pins) {}
void __init at91_set_serial_console(unsigned portnr) {}
void __init at91_add_device_serial(void) {}
#endif
/* --------------------------------------------------------------------
* CF/IDE
* -------------------------------------------------------------------- */
#if defined(CONFIG_BLK_DEV_IDE_AT91) || defined(CONFIG_BLK_DEV_IDE_AT91_MODULE) || \
defined(CONFIG_PATA_AT91) || defined(CONFIG_PATA_AT91_MODULE) || \
defined(CONFIG_AT91_CF) || defined(CONFIG_AT91_CF_MODULE)
static struct at91_cf_data cf0_data;
static struct resource cf0_resources[] = {
[0] = {
.start = AT91_CHIPSELECT_4,
.end = AT91_CHIPSELECT_4 + SZ_256M - 1,
.flags = IORESOURCE_MEM,
}
};
static struct platform_device cf0_device = {
.id = 0,
.dev = {
.platform_data = &cf0_data,
},
.resource = cf0_resources,
.num_resources = ARRAY_SIZE(cf0_resources),
};
static struct at91_cf_data cf1_data;
static struct resource cf1_resources[] = {
[0] = {
.start = AT91_CHIPSELECT_5,
.end = AT91_CHIPSELECT_5 + SZ_256M - 1,
.flags = IORESOURCE_MEM,
}
};
static struct platform_device cf1_device = {
.id = 1,
.dev = {
.platform_data = &cf1_data,
},
.resource = cf1_resources,
.num_resources = ARRAY_SIZE(cf1_resources),
};
void __init at91_add_device_cf(struct at91_cf_data *data)
{
struct platform_device *pdev;
unsigned long csa;
if (!data)
return;
csa = at91_sys_read(AT91_MATRIX_EBICSA);
switch (data->chipselect) {
case 4:
at91_set_multi_drive(AT91_PIN_PC8, 0);
at91_set_A_periph(AT91_PIN_PC8, 0);
csa |= AT91_MATRIX_CS4A_SMC_CF1;
cf0_data = *data;
pdev = &cf0_device;
break;
case 5:
at91_set_multi_drive(AT91_PIN_PC9, 0);
at91_set_A_periph(AT91_PIN_PC9, 0);
csa |= AT91_MATRIX_CS5A_SMC_CF2;
cf1_data = *data;
pdev = &cf1_device;
break;
default:
printk(KERN_ERR "AT91 CF: bad chip-select requested (%u)\n",
data->chipselect);
return;
}
at91_sys_write(AT91_MATRIX_EBICSA, csa);
if (data->rst_pin) {
at91_set_multi_drive(data->rst_pin, 0);
at91_set_gpio_output(data->rst_pin, 1);
}
if (data->irq_pin) {
at91_set_gpio_input(data->irq_pin, 0);
at91_set_deglitch(data->irq_pin, 1);
}
if (data->det_pin) {
at91_set_gpio_input(data->det_pin, 0);
at91_set_deglitch(data->det_pin, 1);
}
at91_set_B_periph(AT91_PIN_PC6, 0); /* CFCE1 */
at91_set_B_periph(AT91_PIN_PC7, 0); /* CFCE2 */
at91_set_A_periph(AT91_PIN_PC10, 0); /* CFRNW */
at91_set_A_periph(AT91_PIN_PC15, 1); /* NWAIT */
if (data->flags & AT91_CF_TRUE_IDE)
#if defined(CONFIG_PATA_AT91) || defined(CONFIG_PATA_AT91_MODULE)
pdev->name = "pata_at91";
#elif defined(CONFIG_BLK_DEV_IDE_AT91) || defined(CONFIG_BLK_DEV_IDE_AT91_MODULE)
pdev->name = "at91_ide";
#else
#warning "board requires AT91_CF_TRUE_IDE: enable either at91_ide or pata_at91"
#endif
else
pdev->name = "at91_cf";
platform_device_register(pdev);
}
#else
void __init at91_add_device_cf(struct at91_cf_data * data) {}
#endif
/* -------------------------------------------------------------------- */
/*
* These devices are always present and don't need any board-specific
* setup.
*/
static int __init at91_add_standard_devices(void)
{
at91_add_device_rtt();
at91_add_device_watchdog();
at91_add_device_tc();
return 0;
}
arch_initcall(at91_add_standard_devices);
| gpl-2.0 |
pacificIT/Kernel_Unico | fs/btrfs/volumes.c | 1663 | 94410 | /*
* Copyright (C) 2007 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include <linux/sched.h>
#include <linux/bio.h>
#include <linux/slab.h>
#include <linux/buffer_head.h>
#include <linux/blkdev.h>
#include <linux/random.h>
#include <linux/iocontext.h>
#include <linux/capability.h>
#include <asm/div64.h>
#include "compat.h"
#include "ctree.h"
#include "extent_map.h"
#include "disk-io.h"
#include "transaction.h"
#include "print-tree.h"
#include "volumes.h"
#include "async-thread.h"
static int init_first_rw_device(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_device *device);
static int btrfs_relocate_sys_chunks(struct btrfs_root *root);
static DEFINE_MUTEX(uuid_mutex);
static LIST_HEAD(fs_uuids);
static void lock_chunks(struct btrfs_root *root)
{
mutex_lock(&root->fs_info->chunk_mutex);
}
static void unlock_chunks(struct btrfs_root *root)
{
mutex_unlock(&root->fs_info->chunk_mutex);
}
static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
{
struct btrfs_device *device;
WARN_ON(fs_devices->opened);
while (!list_empty(&fs_devices->devices)) {
device = list_entry(fs_devices->devices.next,
struct btrfs_device, dev_list);
list_del(&device->dev_list);
kfree(device->name);
kfree(device);
}
kfree(fs_devices);
}
int btrfs_cleanup_fs_uuids(void)
{
struct btrfs_fs_devices *fs_devices;
while (!list_empty(&fs_uuids)) {
fs_devices = list_entry(fs_uuids.next,
struct btrfs_fs_devices, list);
list_del(&fs_devices->list);
free_fs_devices(fs_devices);
}
return 0;
}
static noinline struct btrfs_device *__find_device(struct list_head *head,
u64 devid, u8 *uuid)
{
struct btrfs_device *dev;
list_for_each_entry(dev, head, dev_list) {
if (dev->devid == devid &&
(!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
return dev;
}
}
return NULL;
}
static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
{
struct btrfs_fs_devices *fs_devices;
list_for_each_entry(fs_devices, &fs_uuids, list) {
if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
return fs_devices;
}
return NULL;
}
static void requeue_list(struct btrfs_pending_bios *pending_bios,
struct bio *head, struct bio *tail)
{
struct bio *old_head;
old_head = pending_bios->head;
pending_bios->head = head;
if (pending_bios->tail)
tail->bi_next = old_head;
else
pending_bios->tail = tail;
}
/*
* we try to collect pending bios for a device so we don't get a large
* number of procs sending bios down to the same device. This greatly
* improves the schedulers ability to collect and merge the bios.
*
* But, it also turns into a long list of bios to process and that is sure
* to eventually make the worker thread block. The solution here is to
* make some progress and then put this work struct back at the end of
* the list if the block device is congested. This way, multiple devices
* can make progress from a single worker thread.
*/
static noinline int run_scheduled_bios(struct btrfs_device *device)
{
struct bio *pending;
struct backing_dev_info *bdi;
struct btrfs_fs_info *fs_info;
struct btrfs_pending_bios *pending_bios;
struct bio *tail;
struct bio *cur;
int again = 0;
unsigned long num_run;
unsigned long batch_run = 0;
unsigned long limit;
unsigned long last_waited = 0;
int force_reg = 0;
struct blk_plug plug;
/*
* this function runs all the bios we've collected for
* a particular device. We don't want to wander off to
* another device without first sending all of these down.
* So, setup a plug here and finish it off before we return
*/
blk_start_plug(&plug);
bdi = blk_get_backing_dev_info(device->bdev);
fs_info = device->dev_root->fs_info;
limit = btrfs_async_submit_limit(fs_info);
limit = limit * 2 / 3;
loop:
spin_lock(&device->io_lock);
loop_lock:
num_run = 0;
/* take all the bios off the list at once and process them
* later on (without the lock held). But, remember the
* tail and other pointers so the bios can be properly reinserted
* into the list if we hit congestion
*/
if (!force_reg && device->pending_sync_bios.head) {
pending_bios = &device->pending_sync_bios;
force_reg = 1;
} else {
pending_bios = &device->pending_bios;
force_reg = 0;
}
pending = pending_bios->head;
tail = pending_bios->tail;
WARN_ON(pending && !tail);
/*
* if pending was null this time around, no bios need processing
* at all and we can stop. Otherwise it'll loop back up again
* and do an additional check so no bios are missed.
*
* device->running_pending is used to synchronize with the
* schedule_bio code.
*/
if (device->pending_sync_bios.head == NULL &&
device->pending_bios.head == NULL) {
again = 0;
device->running_pending = 0;
} else {
again = 1;
device->running_pending = 1;
}
pending_bios->head = NULL;
pending_bios->tail = NULL;
spin_unlock(&device->io_lock);
while (pending) {
rmb();
/* we want to work on both lists, but do more bios on the
* sync list than the regular list
*/
if ((num_run > 32 &&
pending_bios != &device->pending_sync_bios &&
device->pending_sync_bios.head) ||
(num_run > 64 && pending_bios == &device->pending_sync_bios &&
device->pending_bios.head)) {
spin_lock(&device->io_lock);
requeue_list(pending_bios, pending, tail);
goto loop_lock;
}
cur = pending;
pending = pending->bi_next;
cur->bi_next = NULL;
atomic_dec(&fs_info->nr_async_bios);
if (atomic_read(&fs_info->nr_async_bios) < limit &&
waitqueue_active(&fs_info->async_submit_wait))
wake_up(&fs_info->async_submit_wait);
BUG_ON(atomic_read(&cur->bi_cnt) == 0);
submit_bio(cur->bi_rw, cur);
num_run++;
batch_run++;
if (need_resched())
cond_resched();
/*
* we made progress, there is more work to do and the bdi
* is now congested. Back off and let other work structs
* run instead
*/
if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
fs_info->fs_devices->open_devices > 1) {
struct io_context *ioc;
ioc = current->io_context;
/*
* the main goal here is that we don't want to
* block if we're going to be able to submit
* more requests without blocking.
*
* This code does two great things, it pokes into
* the elevator code from a filesystem _and_
* it makes assumptions about how batching works.
*/
if (ioc && ioc->nr_batch_requests > 0 &&
time_before(jiffies, ioc->last_waited + HZ/50UL) &&
(last_waited == 0 ||
ioc->last_waited == last_waited)) {
/*
* we want to go through our batch of
* requests and stop. So, we copy out
* the ioc->last_waited time and test
* against it before looping
*/
last_waited = ioc->last_waited;
if (need_resched())
cond_resched();
continue;
}
spin_lock(&device->io_lock);
requeue_list(pending_bios, pending, tail);
device->running_pending = 1;
spin_unlock(&device->io_lock);
btrfs_requeue_work(&device->work);
goto done;
}
}
cond_resched();
if (again)
goto loop;
spin_lock(&device->io_lock);
if (device->pending_bios.head || device->pending_sync_bios.head)
goto loop_lock;
spin_unlock(&device->io_lock);
done:
blk_finish_plug(&plug);
return 0;
}
static void pending_bios_fn(struct btrfs_work *work)
{
struct btrfs_device *device;
device = container_of(work, struct btrfs_device, work);
run_scheduled_bios(device);
}
static noinline int device_list_add(const char *path,
struct btrfs_super_block *disk_super,
u64 devid, struct btrfs_fs_devices **fs_devices_ret)
{
struct btrfs_device *device;
struct btrfs_fs_devices *fs_devices;
u64 found_transid = btrfs_super_generation(disk_super);
char *name;
fs_devices = find_fsid(disk_super->fsid);
if (!fs_devices) {
fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
if (!fs_devices)
return -ENOMEM;
INIT_LIST_HEAD(&fs_devices->devices);
INIT_LIST_HEAD(&fs_devices->alloc_list);
list_add(&fs_devices->list, &fs_uuids);
memcpy(fs_devices->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
fs_devices->latest_devid = devid;
fs_devices->latest_trans = found_transid;
mutex_init(&fs_devices->device_list_mutex);
device = NULL;
} else {
device = __find_device(&fs_devices->devices, devid,
disk_super->dev_item.uuid);
}
if (!device) {
if (fs_devices->opened)
return -EBUSY;
device = kzalloc(sizeof(*device), GFP_NOFS);
if (!device) {
/* we can safely leave the fs_devices entry around */
return -ENOMEM;
}
device->devid = devid;
device->work.func = pending_bios_fn;
memcpy(device->uuid, disk_super->dev_item.uuid,
BTRFS_UUID_SIZE);
spin_lock_init(&device->io_lock);
device->name = kstrdup(path, GFP_NOFS);
if (!device->name) {
kfree(device);
return -ENOMEM;
}
INIT_LIST_HEAD(&device->dev_alloc_list);
mutex_lock(&fs_devices->device_list_mutex);
list_add_rcu(&device->dev_list, &fs_devices->devices);
mutex_unlock(&fs_devices->device_list_mutex);
device->fs_devices = fs_devices;
fs_devices->num_devices++;
} else if (!device->name || strcmp(device->name, path)) {
name = kstrdup(path, GFP_NOFS);
if (!name)
return -ENOMEM;
kfree(device->name);
device->name = name;
if (device->missing) {
fs_devices->missing_devices--;
device->missing = 0;
}
}
if (found_transid > fs_devices->latest_trans) {
fs_devices->latest_devid = devid;
fs_devices->latest_trans = found_transid;
}
*fs_devices_ret = fs_devices;
return 0;
}
static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
{
struct btrfs_fs_devices *fs_devices;
struct btrfs_device *device;
struct btrfs_device *orig_dev;
fs_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
if (!fs_devices)
return ERR_PTR(-ENOMEM);
INIT_LIST_HEAD(&fs_devices->devices);
INIT_LIST_HEAD(&fs_devices->alloc_list);
INIT_LIST_HEAD(&fs_devices->list);
mutex_init(&fs_devices->device_list_mutex);
fs_devices->latest_devid = orig->latest_devid;
fs_devices->latest_trans = orig->latest_trans;
memcpy(fs_devices->fsid, orig->fsid, sizeof(fs_devices->fsid));
/* We have held the volume lock, it is safe to get the devices. */
list_for_each_entry(orig_dev, &orig->devices, dev_list) {
device = kzalloc(sizeof(*device), GFP_NOFS);
if (!device)
goto error;
device->name = kstrdup(orig_dev->name, GFP_NOFS);
if (!device->name) {
kfree(device);
goto error;
}
device->devid = orig_dev->devid;
device->work.func = pending_bios_fn;
memcpy(device->uuid, orig_dev->uuid, sizeof(device->uuid));
spin_lock_init(&device->io_lock);
INIT_LIST_HEAD(&device->dev_list);
INIT_LIST_HEAD(&device->dev_alloc_list);
list_add(&device->dev_list, &fs_devices->devices);
device->fs_devices = fs_devices;
fs_devices->num_devices++;
}
return fs_devices;
error:
free_fs_devices(fs_devices);
return ERR_PTR(-ENOMEM);
}
int btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices)
{
struct btrfs_device *device, *next;
mutex_lock(&uuid_mutex);
again:
/* This is the initialized path, it is safe to release the devices. */
list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
if (device->in_fs_metadata)
continue;
if (device->bdev) {
blkdev_put(device->bdev, device->mode);
device->bdev = NULL;
fs_devices->open_devices--;
}
if (device->writeable) {
list_del_init(&device->dev_alloc_list);
device->writeable = 0;
fs_devices->rw_devices--;
}
list_del_init(&device->dev_list);
fs_devices->num_devices--;
kfree(device->name);
kfree(device);
}
if (fs_devices->seed) {
fs_devices = fs_devices->seed;
goto again;
}
mutex_unlock(&uuid_mutex);
return 0;
}
static void __free_device(struct work_struct *work)
{
struct btrfs_device *device;
device = container_of(work, struct btrfs_device, rcu_work);
if (device->bdev)
blkdev_put(device->bdev, device->mode);
kfree(device->name);
kfree(device);
}
static void free_device(struct rcu_head *head)
{
struct btrfs_device *device;
device = container_of(head, struct btrfs_device, rcu);
INIT_WORK(&device->rcu_work, __free_device);
schedule_work(&device->rcu_work);
}
static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
{
struct btrfs_device *device;
if (--fs_devices->opened > 0)
return 0;
mutex_lock(&fs_devices->device_list_mutex);
list_for_each_entry(device, &fs_devices->devices, dev_list) {
struct btrfs_device *new_device;
if (device->bdev)
fs_devices->open_devices--;
if (device->writeable) {
list_del_init(&device->dev_alloc_list);
fs_devices->rw_devices--;
}
if (device->can_discard)
fs_devices->num_can_discard--;
new_device = kmalloc(sizeof(*new_device), GFP_NOFS);
BUG_ON(!new_device);
memcpy(new_device, device, sizeof(*new_device));
new_device->name = kstrdup(device->name, GFP_NOFS);
BUG_ON(device->name && !new_device->name);
new_device->bdev = NULL;
new_device->writeable = 0;
new_device->in_fs_metadata = 0;
new_device->can_discard = 0;
list_replace_rcu(&device->dev_list, &new_device->dev_list);
call_rcu(&device->rcu, free_device);
}
mutex_unlock(&fs_devices->device_list_mutex);
WARN_ON(fs_devices->open_devices);
WARN_ON(fs_devices->rw_devices);
fs_devices->opened = 0;
fs_devices->seeding = 0;
return 0;
}
int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
{
struct btrfs_fs_devices *seed_devices = NULL;
int ret;
mutex_lock(&uuid_mutex);
ret = __btrfs_close_devices(fs_devices);
if (!fs_devices->opened) {
seed_devices = fs_devices->seed;
fs_devices->seed = NULL;
}
mutex_unlock(&uuid_mutex);
while (seed_devices) {
fs_devices = seed_devices;
seed_devices = fs_devices->seed;
__btrfs_close_devices(fs_devices);
free_fs_devices(fs_devices);
}
return ret;
}
static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
fmode_t flags, void *holder)
{
struct request_queue *q;
struct block_device *bdev;
struct list_head *head = &fs_devices->devices;
struct btrfs_device *device;
struct block_device *latest_bdev = NULL;
struct buffer_head *bh;
struct btrfs_super_block *disk_super;
u64 latest_devid = 0;
u64 latest_transid = 0;
u64 devid;
int seeding = 1;
int ret = 0;
flags |= FMODE_EXCL;
list_for_each_entry(device, head, dev_list) {
if (device->bdev)
continue;
if (!device->name)
continue;
bdev = blkdev_get_by_path(device->name, flags, holder);
if (IS_ERR(bdev)) {
printk(KERN_INFO "open %s failed\n", device->name);
goto error;
}
set_blocksize(bdev, 4096);
bh = btrfs_read_dev_super(bdev);
if (!bh) {
ret = -EINVAL;
goto error_close;
}
disk_super = (struct btrfs_super_block *)bh->b_data;
devid = btrfs_stack_device_id(&disk_super->dev_item);
if (devid != device->devid)
goto error_brelse;
if (memcmp(device->uuid, disk_super->dev_item.uuid,
BTRFS_UUID_SIZE))
goto error_brelse;
device->generation = btrfs_super_generation(disk_super);
if (!latest_transid || device->generation > latest_transid) {
latest_devid = devid;
latest_transid = device->generation;
latest_bdev = bdev;
}
if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
device->writeable = 0;
} else {
device->writeable = !bdev_read_only(bdev);
seeding = 0;
}
q = bdev_get_queue(bdev);
if (blk_queue_discard(q)) {
device->can_discard = 1;
fs_devices->num_can_discard++;
}
device->bdev = bdev;
device->in_fs_metadata = 0;
device->mode = flags;
if (!blk_queue_nonrot(bdev_get_queue(bdev)))
fs_devices->rotating = 1;
fs_devices->open_devices++;
if (device->writeable) {
fs_devices->rw_devices++;
list_add(&device->dev_alloc_list,
&fs_devices->alloc_list);
}
brelse(bh);
continue;
error_brelse:
brelse(bh);
error_close:
blkdev_put(bdev, flags);
error:
continue;
}
if (fs_devices->open_devices == 0) {
ret = -EIO;
goto out;
}
fs_devices->seeding = seeding;
fs_devices->opened = 1;
fs_devices->latest_bdev = latest_bdev;
fs_devices->latest_devid = latest_devid;
fs_devices->latest_trans = latest_transid;
fs_devices->total_rw_bytes = 0;
out:
return ret;
}
int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
fmode_t flags, void *holder)
{
int ret;
mutex_lock(&uuid_mutex);
if (fs_devices->opened) {
fs_devices->opened++;
ret = 0;
} else {
ret = __btrfs_open_devices(fs_devices, flags, holder);
}
mutex_unlock(&uuid_mutex);
return ret;
}
int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
struct btrfs_fs_devices **fs_devices_ret)
{
struct btrfs_super_block *disk_super;
struct block_device *bdev;
struct buffer_head *bh;
int ret;
u64 devid;
u64 transid;
mutex_lock(&uuid_mutex);
flags |= FMODE_EXCL;
bdev = blkdev_get_by_path(path, flags, holder);
if (IS_ERR(bdev)) {
ret = PTR_ERR(bdev);
goto error;
}
ret = set_blocksize(bdev, 4096);
if (ret)
goto error_close;
bh = btrfs_read_dev_super(bdev);
if (!bh) {
ret = -EINVAL;
goto error_close;
}
disk_super = (struct btrfs_super_block *)bh->b_data;
devid = btrfs_stack_device_id(&disk_super->dev_item);
transid = btrfs_super_generation(disk_super);
if (disk_super->label[0])
printk(KERN_INFO "device label %s ", disk_super->label);
else
printk(KERN_INFO "device fsid %pU ", disk_super->fsid);
printk(KERN_CONT "devid %llu transid %llu %s\n",
(unsigned long long)devid, (unsigned long long)transid, path);
ret = device_list_add(path, disk_super, devid, fs_devices_ret);
brelse(bh);
error_close:
blkdev_put(bdev, flags);
error:
mutex_unlock(&uuid_mutex);
return ret;
}
/* helper to account the used device space in the range */
int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
u64 end, u64 *length)
{
struct btrfs_key key;
struct btrfs_root *root = device->dev_root;
struct btrfs_dev_extent *dev_extent;
struct btrfs_path *path;
u64 extent_end;
int ret;
int slot;
struct extent_buffer *l;
*length = 0;
if (start >= device->total_bytes)
return 0;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
path->reada = 2;
key.objectid = device->devid;
key.offset = start;
key.type = BTRFS_DEV_EXTENT_KEY;
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
goto out;
if (ret > 0) {
ret = btrfs_previous_item(root, path, key.objectid, key.type);
if (ret < 0)
goto out;
}
while (1) {
l = path->nodes[0];
slot = path->slots[0];
if (slot >= btrfs_header_nritems(l)) {
ret = btrfs_next_leaf(root, path);
if (ret == 0)
continue;
if (ret < 0)
goto out;
break;
}
btrfs_item_key_to_cpu(l, &key, slot);
if (key.objectid < device->devid)
goto next;
if (key.objectid > device->devid)
break;
if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
goto next;
dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
extent_end = key.offset + btrfs_dev_extent_length(l,
dev_extent);
if (key.offset <= start && extent_end > end) {
*length = end - start + 1;
break;
} else if (key.offset <= start && extent_end > start)
*length += extent_end - start;
else if (key.offset > start && extent_end <= end)
*length += extent_end - key.offset;
else if (key.offset > start && key.offset <= end) {
*length += end - key.offset + 1;
break;
} else if (key.offset > end)
break;
next:
path->slots[0]++;
}
ret = 0;
out:
btrfs_free_path(path);
return ret;
}
/*
* find_free_dev_extent - find free space in the specified device
* @trans: transaction handler
* @device: the device which we search the free space in
* @num_bytes: the size of the free space that we need
* @start: store the start of the free space.
* @len: the size of the free space. that we find, or the size of the max
* free space if we don't find suitable free space
*
* this uses a pretty simple search, the expectation is that it is
* called very infrequently and that a given device has a small number
* of extents
*
* @start is used to store the start of the free space if we find. But if we
* don't find suitable free space, it will be used to store the start position
* of the max free space.
*
* @len is used to store the size of the free space that we find.
* But if we don't find suitable free space, it is used to store the size of
* the max free space.
*/
int find_free_dev_extent(struct btrfs_trans_handle *trans,
struct btrfs_device *device, u64 num_bytes,
u64 *start, u64 *len)
{
struct btrfs_key key;
struct btrfs_root *root = device->dev_root;
struct btrfs_dev_extent *dev_extent;
struct btrfs_path *path;
u64 hole_size;
u64 max_hole_start;
u64 max_hole_size;
u64 extent_end;
u64 search_start;
u64 search_end = device->total_bytes;
int ret;
int slot;
struct extent_buffer *l;
/* FIXME use last free of some kind */
/* we don't want to overwrite the superblock on the drive,
* so we make sure to start at an offset of at least 1MB
*/
search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
max_hole_start = search_start;
max_hole_size = 0;
if (search_start >= search_end) {
ret = -ENOSPC;
goto error;
}
path = btrfs_alloc_path();
if (!path) {
ret = -ENOMEM;
goto error;
}
path->reada = 2;
key.objectid = device->devid;
key.offset = search_start;
key.type = BTRFS_DEV_EXTENT_KEY;
ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
if (ret < 0)
goto out;
if (ret > 0) {
ret = btrfs_previous_item(root, path, key.objectid, key.type);
if (ret < 0)
goto out;
}
while (1) {
l = path->nodes[0];
slot = path->slots[0];
if (slot >= btrfs_header_nritems(l)) {
ret = btrfs_next_leaf(root, path);
if (ret == 0)
continue;
if (ret < 0)
goto out;
break;
}
btrfs_item_key_to_cpu(l, &key, slot);
if (key.objectid < device->devid)
goto next;
if (key.objectid > device->devid)
break;
if (btrfs_key_type(&key) != BTRFS_DEV_EXTENT_KEY)
goto next;
if (key.offset > search_start) {
hole_size = key.offset - search_start;
if (hole_size > max_hole_size) {
max_hole_start = search_start;
max_hole_size = hole_size;
}
/*
* If this free space is greater than which we need,
* it must be the max free space that we have found
* until now, so max_hole_start must point to the start
* of this free space and the length of this free space
* is stored in max_hole_size. Thus, we return
* max_hole_start and max_hole_size and go back to the
* caller.
*/
if (hole_size >= num_bytes) {
ret = 0;
goto out;
}
}
dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
extent_end = key.offset + btrfs_dev_extent_length(l,
dev_extent);
if (extent_end > search_start)
search_start = extent_end;
next:
path->slots[0]++;
cond_resched();
}
hole_size = search_end- search_start;
if (hole_size > max_hole_size) {
max_hole_start = search_start;
max_hole_size = hole_size;
}
/* See above. */
if (hole_size < num_bytes)
ret = -ENOSPC;
else
ret = 0;
out:
btrfs_free_path(path);
error:
*start = max_hole_start;
if (len)
*len = max_hole_size;
return ret;
}
static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
struct btrfs_device *device,
u64 start)
{
int ret;
struct btrfs_path *path;
struct btrfs_root *root = device->dev_root;
struct btrfs_key key;
struct btrfs_key found_key;
struct extent_buffer *leaf = NULL;
struct btrfs_dev_extent *extent = NULL;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
key.objectid = device->devid;
key.offset = start;
key.type = BTRFS_DEV_EXTENT_KEY;
ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
if (ret > 0) {
ret = btrfs_previous_item(root, path, key.objectid,
BTRFS_DEV_EXTENT_KEY);
if (ret)
goto out;
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
extent = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_dev_extent);
BUG_ON(found_key.offset > start || found_key.offset +
btrfs_dev_extent_length(leaf, extent) < start);
} else if (ret == 0) {
leaf = path->nodes[0];
extent = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_dev_extent);
}
BUG_ON(ret);
if (device->bytes_used > 0)
device->bytes_used -= btrfs_dev_extent_length(leaf, extent);
ret = btrfs_del_item(trans, root, path);
out:
btrfs_free_path(path);
return ret;
}
int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
struct btrfs_device *device,
u64 chunk_tree, u64 chunk_objectid,
u64 chunk_offset, u64 start, u64 num_bytes)
{
int ret;
struct btrfs_path *path;
struct btrfs_root *root = device->dev_root;
struct btrfs_dev_extent *extent;
struct extent_buffer *leaf;
struct btrfs_key key;
WARN_ON(!device->in_fs_metadata);
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
key.objectid = device->devid;
key.offset = start;
key.type = BTRFS_DEV_EXTENT_KEY;
ret = btrfs_insert_empty_item(trans, root, path, &key,
sizeof(*extent));
BUG_ON(ret);
leaf = path->nodes[0];
extent = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_dev_extent);
btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
(unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
BTRFS_UUID_SIZE);
btrfs_set_dev_extent_length(leaf, extent, num_bytes);
btrfs_mark_buffer_dirty(leaf);
btrfs_free_path(path);
return ret;
}
static noinline int find_next_chunk(struct btrfs_root *root,
u64 objectid, u64 *offset)
{
struct btrfs_path *path;
int ret;
struct btrfs_key key;
struct btrfs_chunk *chunk;
struct btrfs_key found_key;
path = btrfs_alloc_path();
BUG_ON(!path);
key.objectid = objectid;
key.offset = (u64)-1;
key.type = BTRFS_CHUNK_ITEM_KEY;
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
goto error;
BUG_ON(ret == 0);
ret = btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY);
if (ret) {
*offset = 0;
} else {
btrfs_item_key_to_cpu(path->nodes[0], &found_key,
path->slots[0]);
if (found_key.objectid != objectid)
*offset = 0;
else {
chunk = btrfs_item_ptr(path->nodes[0], path->slots[0],
struct btrfs_chunk);
*offset = found_key.offset +
btrfs_chunk_length(path->nodes[0], chunk);
}
}
ret = 0;
error:
btrfs_free_path(path);
return ret;
}
static noinline int find_next_devid(struct btrfs_root *root, u64 *objectid)
{
int ret;
struct btrfs_key key;
struct btrfs_key found_key;
struct btrfs_path *path;
root = root->fs_info->chunk_root;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
key.type = BTRFS_DEV_ITEM_KEY;
key.offset = (u64)-1;
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
goto error;
BUG_ON(ret == 0);
ret = btrfs_previous_item(root, path, BTRFS_DEV_ITEMS_OBJECTID,
BTRFS_DEV_ITEM_KEY);
if (ret) {
*objectid = 1;
} else {
btrfs_item_key_to_cpu(path->nodes[0], &found_key,
path->slots[0]);
*objectid = found_key.offset + 1;
}
ret = 0;
error:
btrfs_free_path(path);
return ret;
}
/*
* the device information is stored in the chunk root
* the btrfs_device struct should be fully filled in
*/
int btrfs_add_device(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_device *device)
{
int ret;
struct btrfs_path *path;
struct btrfs_dev_item *dev_item;
struct extent_buffer *leaf;
struct btrfs_key key;
unsigned long ptr;
root = root->fs_info->chunk_root;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
key.type = BTRFS_DEV_ITEM_KEY;
key.offset = device->devid;
ret = btrfs_insert_empty_item(trans, root, path, &key,
sizeof(*dev_item));
if (ret)
goto out;
leaf = path->nodes[0];
dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
btrfs_set_device_id(leaf, dev_item, device->devid);
btrfs_set_device_generation(leaf, dev_item, 0);
btrfs_set_device_type(leaf, dev_item, device->type);
btrfs_set_device_io_align(leaf, dev_item, device->io_align);
btrfs_set_device_io_width(leaf, dev_item, device->io_width);
btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
btrfs_set_device_total_bytes(leaf, dev_item, device->total_bytes);
btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
btrfs_set_device_group(leaf, dev_item, 0);
btrfs_set_device_seek_speed(leaf, dev_item, 0);
btrfs_set_device_bandwidth(leaf, dev_item, 0);
btrfs_set_device_start_offset(leaf, dev_item, 0);
ptr = (unsigned long)btrfs_device_uuid(dev_item);
write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
ptr = (unsigned long)btrfs_device_fsid(dev_item);
write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
btrfs_mark_buffer_dirty(leaf);
ret = 0;
out:
btrfs_free_path(path);
return ret;
}
static int btrfs_rm_dev_item(struct btrfs_root *root,
struct btrfs_device *device)
{
int ret;
struct btrfs_path *path;
struct btrfs_key key;
struct btrfs_trans_handle *trans;
root = root->fs_info->chunk_root;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
trans = btrfs_start_transaction(root, 0);
if (IS_ERR(trans)) {
btrfs_free_path(path);
return PTR_ERR(trans);
}
key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
key.type = BTRFS_DEV_ITEM_KEY;
key.offset = device->devid;
lock_chunks(root);
ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
if (ret < 0)
goto out;
if (ret > 0) {
ret = -ENOENT;
goto out;
}
ret = btrfs_del_item(trans, root, path);
if (ret)
goto out;
out:
btrfs_free_path(path);
unlock_chunks(root);
btrfs_commit_transaction(trans, root);
return ret;
}
int btrfs_rm_device(struct btrfs_root *root, char *device_path)
{
struct btrfs_device *device;
struct btrfs_device *next_device;
struct block_device *bdev;
struct buffer_head *bh = NULL;
struct btrfs_super_block *disk_super;
struct btrfs_fs_devices *cur_devices;
u64 all_avail;
u64 devid;
u64 num_devices;
u8 *dev_uuid;
int ret = 0;
bool clear_super = false;
mutex_lock(&uuid_mutex);
mutex_lock(&root->fs_info->volume_mutex);
all_avail = root->fs_info->avail_data_alloc_bits |
root->fs_info->avail_system_alloc_bits |
root->fs_info->avail_metadata_alloc_bits;
if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) &&
root->fs_info->fs_devices->num_devices <= 4) {
printk(KERN_ERR "btrfs: unable to go below four devices "
"on raid10\n");
ret = -EINVAL;
goto out;
}
if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) &&
root->fs_info->fs_devices->num_devices <= 2) {
printk(KERN_ERR "btrfs: unable to go below two "
"devices on raid1\n");
ret = -EINVAL;
goto out;
}
if (strcmp(device_path, "missing") == 0) {
struct list_head *devices;
struct btrfs_device *tmp;
device = NULL;
devices = &root->fs_info->fs_devices->devices;
/*
* It is safe to read the devices since the volume_mutex
* is held.
*/
list_for_each_entry(tmp, devices, dev_list) {
if (tmp->in_fs_metadata && !tmp->bdev) {
device = tmp;
break;
}
}
bdev = NULL;
bh = NULL;
disk_super = NULL;
if (!device) {
printk(KERN_ERR "btrfs: no missing devices found to "
"remove\n");
goto out;
}
} else {
bdev = blkdev_get_by_path(device_path, FMODE_READ | FMODE_EXCL,
root->fs_info->bdev_holder);
if (IS_ERR(bdev)) {
ret = PTR_ERR(bdev);
goto out;
}
set_blocksize(bdev, 4096);
bh = btrfs_read_dev_super(bdev);
if (!bh) {
ret = -EINVAL;
goto error_close;
}
disk_super = (struct btrfs_super_block *)bh->b_data;
devid = btrfs_stack_device_id(&disk_super->dev_item);
dev_uuid = disk_super->dev_item.uuid;
device = btrfs_find_device(root, devid, dev_uuid,
disk_super->fsid);
if (!device) {
ret = -ENOENT;
goto error_brelse;
}
}
if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
printk(KERN_ERR "btrfs: unable to remove the only writeable "
"device\n");
ret = -EINVAL;
goto error_brelse;
}
if (device->writeable) {
lock_chunks(root);
list_del_init(&device->dev_alloc_list);
unlock_chunks(root);
root->fs_info->fs_devices->rw_devices--;
clear_super = true;
}
ret = btrfs_shrink_device(device, 0);
if (ret)
goto error_undo;
ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
if (ret)
goto error_undo;
device->in_fs_metadata = 0;
btrfs_scrub_cancel_dev(root, device);
/*
* the device list mutex makes sure that we don't change
* the device list while someone else is writing out all
* the device supers.
*/
cur_devices = device->fs_devices;
mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
list_del_rcu(&device->dev_list);
device->fs_devices->num_devices--;
if (device->missing)
root->fs_info->fs_devices->missing_devices--;
next_device = list_entry(root->fs_info->fs_devices->devices.next,
struct btrfs_device, dev_list);
if (device->bdev == root->fs_info->sb->s_bdev)
root->fs_info->sb->s_bdev = next_device->bdev;
if (device->bdev == root->fs_info->fs_devices->latest_bdev)
root->fs_info->fs_devices->latest_bdev = next_device->bdev;
if (device->bdev)
device->fs_devices->open_devices--;
call_rcu(&device->rcu, free_device);
mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
num_devices = btrfs_super_num_devices(&root->fs_info->super_copy) - 1;
btrfs_set_super_num_devices(&root->fs_info->super_copy, num_devices);
if (cur_devices->open_devices == 0) {
struct btrfs_fs_devices *fs_devices;
fs_devices = root->fs_info->fs_devices;
while (fs_devices) {
if (fs_devices->seed == cur_devices)
break;
fs_devices = fs_devices->seed;
}
fs_devices->seed = cur_devices->seed;
cur_devices->seed = NULL;
lock_chunks(root);
__btrfs_close_devices(cur_devices);
unlock_chunks(root);
free_fs_devices(cur_devices);
}
/*
* at this point, the device is zero sized. We want to
* remove it from the devices list and zero out the old super
*/
if (clear_super) {
/* make sure this device isn't detected as part of
* the FS anymore
*/
memset(&disk_super->magic, 0, sizeof(disk_super->magic));
set_buffer_dirty(bh);
sync_dirty_buffer(bh);
}
ret = 0;
error_brelse:
brelse(bh);
error_close:
if (bdev)
blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
out:
mutex_unlock(&root->fs_info->volume_mutex);
mutex_unlock(&uuid_mutex);
return ret;
error_undo:
if (device->writeable) {
lock_chunks(root);
list_add(&device->dev_alloc_list,
&root->fs_info->fs_devices->alloc_list);
unlock_chunks(root);
root->fs_info->fs_devices->rw_devices++;
}
goto error_brelse;
}
/*
* does all the dirty work required for changing file system's UUID.
*/
static int btrfs_prepare_sprout(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
struct btrfs_fs_devices *old_devices;
struct btrfs_fs_devices *seed_devices;
struct btrfs_super_block *disk_super = &root->fs_info->super_copy;
struct btrfs_device *device;
u64 super_flags;
BUG_ON(!mutex_is_locked(&uuid_mutex));
if (!fs_devices->seeding)
return -EINVAL;
seed_devices = kzalloc(sizeof(*fs_devices), GFP_NOFS);
if (!seed_devices)
return -ENOMEM;
old_devices = clone_fs_devices(fs_devices);
if (IS_ERR(old_devices)) {
kfree(seed_devices);
return PTR_ERR(old_devices);
}
list_add(&old_devices->list, &fs_uuids);
memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
seed_devices->opened = 1;
INIT_LIST_HEAD(&seed_devices->devices);
INIT_LIST_HEAD(&seed_devices->alloc_list);
mutex_init(&seed_devices->device_list_mutex);
mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
synchronize_rcu);
mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
list_for_each_entry(device, &seed_devices->devices, dev_list) {
device->fs_devices = seed_devices;
}
fs_devices->seeding = 0;
fs_devices->num_devices = 0;
fs_devices->open_devices = 0;
fs_devices->seed = seed_devices;
generate_random_uuid(fs_devices->fsid);
memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
super_flags = btrfs_super_flags(disk_super) &
~BTRFS_SUPER_FLAG_SEEDING;
btrfs_set_super_flags(disk_super, super_flags);
return 0;
}
/*
* strore the expected generation for seed devices in device items.
*/
static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
struct btrfs_path *path;
struct extent_buffer *leaf;
struct btrfs_dev_item *dev_item;
struct btrfs_device *device;
struct btrfs_key key;
u8 fs_uuid[BTRFS_UUID_SIZE];
u8 dev_uuid[BTRFS_UUID_SIZE];
u64 devid;
int ret;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
root = root->fs_info->chunk_root;
key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
key.offset = 0;
key.type = BTRFS_DEV_ITEM_KEY;
while (1) {
ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
if (ret < 0)
goto error;
leaf = path->nodes[0];
next_slot:
if (path->slots[0] >= btrfs_header_nritems(leaf)) {
ret = btrfs_next_leaf(root, path);
if (ret > 0)
break;
if (ret < 0)
goto error;
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
btrfs_release_path(path);
continue;
}
btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
key.type != BTRFS_DEV_ITEM_KEY)
break;
dev_item = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_dev_item);
devid = btrfs_device_id(leaf, dev_item);
read_extent_buffer(leaf, dev_uuid,
(unsigned long)btrfs_device_uuid(dev_item),
BTRFS_UUID_SIZE);
read_extent_buffer(leaf, fs_uuid,
(unsigned long)btrfs_device_fsid(dev_item),
BTRFS_UUID_SIZE);
device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
BUG_ON(!device);
if (device->fs_devices->seeding) {
btrfs_set_device_generation(leaf, dev_item,
device->generation);
btrfs_mark_buffer_dirty(leaf);
}
path->slots[0]++;
goto next_slot;
}
ret = 0;
error:
btrfs_free_path(path);
return ret;
}
int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
{
struct request_queue *q;
struct btrfs_trans_handle *trans;
struct btrfs_device *device;
struct block_device *bdev;
struct list_head *devices;
struct super_block *sb = root->fs_info->sb;
u64 total_bytes;
int seeding_dev = 0;
int ret = 0;
if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
return -EINVAL;
bdev = blkdev_get_by_path(device_path, FMODE_EXCL,
root->fs_info->bdev_holder);
if (IS_ERR(bdev))
return PTR_ERR(bdev);
if (root->fs_info->fs_devices->seeding) {
seeding_dev = 1;
down_write(&sb->s_umount);
mutex_lock(&uuid_mutex);
}
filemap_write_and_wait(bdev->bd_inode->i_mapping);
mutex_lock(&root->fs_info->volume_mutex);
devices = &root->fs_info->fs_devices->devices;
/*
* we have the volume lock, so we don't need the extra
* device list mutex while reading the list here.
*/
list_for_each_entry(device, devices, dev_list) {
if (device->bdev == bdev) {
ret = -EEXIST;
goto error;
}
}
device = kzalloc(sizeof(*device), GFP_NOFS);
if (!device) {
/* we can safely leave the fs_devices entry around */
ret = -ENOMEM;
goto error;
}
device->name = kstrdup(device_path, GFP_NOFS);
if (!device->name) {
kfree(device);
ret = -ENOMEM;
goto error;
}
ret = find_next_devid(root, &device->devid);
if (ret) {
kfree(device->name);
kfree(device);
goto error;
}
trans = btrfs_start_transaction(root, 0);
if (IS_ERR(trans)) {
kfree(device->name);
kfree(device);
ret = PTR_ERR(trans);
goto error;
}
lock_chunks(root);
q = bdev_get_queue(bdev);
if (blk_queue_discard(q))
device->can_discard = 1;
device->writeable = 1;
device->work.func = pending_bios_fn;
generate_random_uuid(device->uuid);
spin_lock_init(&device->io_lock);
device->generation = trans->transid;
device->io_width = root->sectorsize;
device->io_align = root->sectorsize;
device->sector_size = root->sectorsize;
device->total_bytes = i_size_read(bdev->bd_inode);
device->disk_total_bytes = device->total_bytes;
device->dev_root = root->fs_info->dev_root;
device->bdev = bdev;
device->in_fs_metadata = 1;
device->mode = FMODE_EXCL;
set_blocksize(device->bdev, 4096);
if (seeding_dev) {
sb->s_flags &= ~MS_RDONLY;
ret = btrfs_prepare_sprout(trans, root);
BUG_ON(ret);
}
device->fs_devices = root->fs_info->fs_devices;
/*
* we don't want write_supers to jump in here with our device
* half setup
*/
mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
list_add(&device->dev_alloc_list,
&root->fs_info->fs_devices->alloc_list);
root->fs_info->fs_devices->num_devices++;
root->fs_info->fs_devices->open_devices++;
root->fs_info->fs_devices->rw_devices++;
if (device->can_discard)
root->fs_info->fs_devices->num_can_discard++;
root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
if (!blk_queue_nonrot(bdev_get_queue(bdev)))
root->fs_info->fs_devices->rotating = 1;
total_bytes = btrfs_super_total_bytes(&root->fs_info->super_copy);
btrfs_set_super_total_bytes(&root->fs_info->super_copy,
total_bytes + device->total_bytes);
total_bytes = btrfs_super_num_devices(&root->fs_info->super_copy);
btrfs_set_super_num_devices(&root->fs_info->super_copy,
total_bytes + 1);
mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
if (seeding_dev) {
ret = init_first_rw_device(trans, root, device);
BUG_ON(ret);
ret = btrfs_finish_sprout(trans, root);
BUG_ON(ret);
} else {
ret = btrfs_add_device(trans, root, device);
}
/*
* we've got more storage, clear any full flags on the space
* infos
*/
btrfs_clear_space_info_full(root->fs_info);
unlock_chunks(root);
btrfs_commit_transaction(trans, root);
if (seeding_dev) {
mutex_unlock(&uuid_mutex);
up_write(&sb->s_umount);
ret = btrfs_relocate_sys_chunks(root);
BUG_ON(ret);
}
out:
mutex_unlock(&root->fs_info->volume_mutex);
return ret;
error:
blkdev_put(bdev, FMODE_EXCL);
if (seeding_dev) {
mutex_unlock(&uuid_mutex);
up_write(&sb->s_umount);
}
goto out;
}
static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
struct btrfs_device *device)
{
int ret;
struct btrfs_path *path;
struct btrfs_root *root;
struct btrfs_dev_item *dev_item;
struct extent_buffer *leaf;
struct btrfs_key key;
root = device->dev_root->fs_info->chunk_root;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
key.type = BTRFS_DEV_ITEM_KEY;
key.offset = device->devid;
ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
if (ret < 0)
goto out;
if (ret > 0) {
ret = -ENOENT;
goto out;
}
leaf = path->nodes[0];
dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
btrfs_set_device_id(leaf, dev_item, device->devid);
btrfs_set_device_type(leaf, dev_item, device->type);
btrfs_set_device_io_align(leaf, dev_item, device->io_align);
btrfs_set_device_io_width(leaf, dev_item, device->io_width);
btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
btrfs_set_device_total_bytes(leaf, dev_item, device->disk_total_bytes);
btrfs_set_device_bytes_used(leaf, dev_item, device->bytes_used);
btrfs_mark_buffer_dirty(leaf);
out:
btrfs_free_path(path);
return ret;
}
static int __btrfs_grow_device(struct btrfs_trans_handle *trans,
struct btrfs_device *device, u64 new_size)
{
struct btrfs_super_block *super_copy =
&device->dev_root->fs_info->super_copy;
u64 old_total = btrfs_super_total_bytes(super_copy);
u64 diff = new_size - device->total_bytes;
if (!device->writeable)
return -EACCES;
if (new_size <= device->total_bytes)
return -EINVAL;
btrfs_set_super_total_bytes(super_copy, old_total + diff);
device->fs_devices->total_rw_bytes += diff;
device->total_bytes = new_size;
device->disk_total_bytes = new_size;
btrfs_clear_space_info_full(device->dev_root->fs_info);
return btrfs_update_device(trans, device);
}
int btrfs_grow_device(struct btrfs_trans_handle *trans,
struct btrfs_device *device, u64 new_size)
{
int ret;
lock_chunks(device->dev_root);
ret = __btrfs_grow_device(trans, device, new_size);
unlock_chunks(device->dev_root);
return ret;
}
static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
u64 chunk_tree, u64 chunk_objectid,
u64 chunk_offset)
{
int ret;
struct btrfs_path *path;
struct btrfs_key key;
root = root->fs_info->chunk_root;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
key.objectid = chunk_objectid;
key.offset = chunk_offset;
key.type = BTRFS_CHUNK_ITEM_KEY;
ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
BUG_ON(ret);
ret = btrfs_del_item(trans, root, path);
btrfs_free_path(path);
return ret;
}
static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
chunk_offset)
{
struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
struct btrfs_disk_key *disk_key;
struct btrfs_chunk *chunk;
u8 *ptr;
int ret = 0;
u32 num_stripes;
u32 array_size;
u32 len = 0;
u32 cur;
struct btrfs_key key;
array_size = btrfs_super_sys_array_size(super_copy);
ptr = super_copy->sys_chunk_array;
cur = 0;
while (cur < array_size) {
disk_key = (struct btrfs_disk_key *)ptr;
btrfs_disk_key_to_cpu(&key, disk_key);
len = sizeof(*disk_key);
if (key.type == BTRFS_CHUNK_ITEM_KEY) {
chunk = (struct btrfs_chunk *)(ptr + len);
num_stripes = btrfs_stack_chunk_num_stripes(chunk);
len += btrfs_chunk_item_size(num_stripes);
} else {
ret = -EIO;
break;
}
if (key.objectid == chunk_objectid &&
key.offset == chunk_offset) {
memmove(ptr, ptr + len, array_size - (cur + len));
array_size -= len;
btrfs_set_super_sys_array_size(super_copy, array_size);
} else {
ptr += len;
cur += len;
}
}
return ret;
}
static int btrfs_relocate_chunk(struct btrfs_root *root,
u64 chunk_tree, u64 chunk_objectid,
u64 chunk_offset)
{
struct extent_map_tree *em_tree;
struct btrfs_root *extent_root;
struct btrfs_trans_handle *trans;
struct extent_map *em;
struct map_lookup *map;
int ret;
int i;
root = root->fs_info->chunk_root;
extent_root = root->fs_info->extent_root;
em_tree = &root->fs_info->mapping_tree.map_tree;
ret = btrfs_can_relocate(extent_root, chunk_offset);
if (ret)
return -ENOSPC;
/* step one, relocate all the extents inside this chunk */
ret = btrfs_relocate_block_group(extent_root, chunk_offset);
if (ret)
return ret;
trans = btrfs_start_transaction(root, 0);
BUG_ON(IS_ERR(trans));
lock_chunks(root);
/*
* step two, delete the device extents and the
* chunk tree entries
*/
read_lock(&em_tree->lock);
em = lookup_extent_mapping(em_tree, chunk_offset, 1);
read_unlock(&em_tree->lock);
BUG_ON(em->start > chunk_offset ||
em->start + em->len < chunk_offset);
map = (struct map_lookup *)em->bdev;
for (i = 0; i < map->num_stripes; i++) {
ret = btrfs_free_dev_extent(trans, map->stripes[i].dev,
map->stripes[i].physical);
BUG_ON(ret);
if (map->stripes[i].dev) {
ret = btrfs_update_device(trans, map->stripes[i].dev);
BUG_ON(ret);
}
}
ret = btrfs_free_chunk(trans, root, chunk_tree, chunk_objectid,
chunk_offset);
BUG_ON(ret);
trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
BUG_ON(ret);
}
ret = btrfs_remove_block_group(trans, extent_root, chunk_offset);
BUG_ON(ret);
write_lock(&em_tree->lock);
remove_extent_mapping(em_tree, em);
write_unlock(&em_tree->lock);
kfree(map);
em->bdev = NULL;
/* once for the tree */
free_extent_map(em);
/* once for us */
free_extent_map(em);
unlock_chunks(root);
btrfs_end_transaction(trans, root);
return 0;
}
static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
{
struct btrfs_root *chunk_root = root->fs_info->chunk_root;
struct btrfs_path *path;
struct extent_buffer *leaf;
struct btrfs_chunk *chunk;
struct btrfs_key key;
struct btrfs_key found_key;
u64 chunk_tree = chunk_root->root_key.objectid;
u64 chunk_type;
bool retried = false;
int failed = 0;
int ret;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
again:
key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
key.offset = (u64)-1;
key.type = BTRFS_CHUNK_ITEM_KEY;
while (1) {
ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
if (ret < 0)
goto error;
BUG_ON(ret == 0);
ret = btrfs_previous_item(chunk_root, path, key.objectid,
key.type);
if (ret < 0)
goto error;
if (ret > 0)
break;
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
chunk = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_chunk);
chunk_type = btrfs_chunk_type(leaf, chunk);
btrfs_release_path(path);
if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
ret = btrfs_relocate_chunk(chunk_root, chunk_tree,
found_key.objectid,
found_key.offset);
if (ret == -ENOSPC)
failed++;
else if (ret)
BUG();
}
if (found_key.offset == 0)
break;
key.offset = found_key.offset - 1;
}
ret = 0;
if (failed && !retried) {
failed = 0;
retried = true;
goto again;
} else if (failed && retried) {
WARN_ON(1);
ret = -ENOSPC;
}
error:
btrfs_free_path(path);
return ret;
}
static u64 div_factor(u64 num, int factor)
{
if (factor == 10)
return num;
num *= factor;
do_div(num, 10);
return num;
}
int btrfs_balance(struct btrfs_root *dev_root)
{
int ret;
struct list_head *devices = &dev_root->fs_info->fs_devices->devices;
struct btrfs_device *device;
u64 old_size;
u64 size_to_free;
struct btrfs_path *path;
struct btrfs_key key;
struct btrfs_root *chunk_root = dev_root->fs_info->chunk_root;
struct btrfs_trans_handle *trans;
struct btrfs_key found_key;
if (dev_root->fs_info->sb->s_flags & MS_RDONLY)
return -EROFS;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
mutex_lock(&dev_root->fs_info->volume_mutex);
dev_root = dev_root->fs_info->dev_root;
/* step one make some room on all the devices */
list_for_each_entry(device, devices, dev_list) {
old_size = device->total_bytes;
size_to_free = div_factor(old_size, 1);
size_to_free = min(size_to_free, (u64)1 * 1024 * 1024);
if (!device->writeable ||
device->total_bytes - device->bytes_used > size_to_free)
continue;
ret = btrfs_shrink_device(device, old_size - size_to_free);
if (ret == -ENOSPC)
break;
BUG_ON(ret);
trans = btrfs_start_transaction(dev_root, 0);
BUG_ON(IS_ERR(trans));
ret = btrfs_grow_device(trans, device, old_size);
BUG_ON(ret);
btrfs_end_transaction(trans, dev_root);
}
/* step two, relocate all the chunks */
path = btrfs_alloc_path();
BUG_ON(!path);
key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
key.offset = (u64)-1;
key.type = BTRFS_CHUNK_ITEM_KEY;
while (1) {
ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
if (ret < 0)
goto error;
/*
* this shouldn't happen, it means the last relocate
* failed
*/
if (ret == 0)
break;
ret = btrfs_previous_item(chunk_root, path, 0,
BTRFS_CHUNK_ITEM_KEY);
if (ret)
break;
btrfs_item_key_to_cpu(path->nodes[0], &found_key,
path->slots[0]);
if (found_key.objectid != key.objectid)
break;
/* chunk zero is special */
if (found_key.offset == 0)
break;
btrfs_release_path(path);
ret = btrfs_relocate_chunk(chunk_root,
chunk_root->root_key.objectid,
found_key.objectid,
found_key.offset);
if (ret && ret != -ENOSPC)
goto error;
key.offset = found_key.offset - 1;
}
ret = 0;
error:
btrfs_free_path(path);
mutex_unlock(&dev_root->fs_info->volume_mutex);
return ret;
}
/*
* shrinking a device means finding all of the device extents past
* the new size, and then following the back refs to the chunks.
* The chunk relocation code actually frees the device extent
*/
int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = device->dev_root;
struct btrfs_dev_extent *dev_extent = NULL;
struct btrfs_path *path;
u64 length;
u64 chunk_tree;
u64 chunk_objectid;
u64 chunk_offset;
int ret;
int slot;
int failed = 0;
bool retried = false;
struct extent_buffer *l;
struct btrfs_key key;
struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
u64 old_total = btrfs_super_total_bytes(super_copy);
u64 old_size = device->total_bytes;
u64 diff = device->total_bytes - new_size;
if (new_size >= device->total_bytes)
return -EINVAL;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
path->reada = 2;
lock_chunks(root);
device->total_bytes = new_size;
if (device->writeable)
device->fs_devices->total_rw_bytes -= diff;
unlock_chunks(root);
again:
key.objectid = device->devid;
key.offset = (u64)-1;
key.type = BTRFS_DEV_EXTENT_KEY;
while (1) {
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
goto done;
ret = btrfs_previous_item(root, path, 0, key.type);
if (ret < 0)
goto done;
if (ret) {
ret = 0;
btrfs_release_path(path);
break;
}
l = path->nodes[0];
slot = path->slots[0];
btrfs_item_key_to_cpu(l, &key, path->slots[0]);
if (key.objectid != device->devid) {
btrfs_release_path(path);
break;
}
dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
length = btrfs_dev_extent_length(l, dev_extent);
if (key.offset + length <= new_size) {
btrfs_release_path(path);
break;
}
chunk_tree = btrfs_dev_extent_chunk_tree(l, dev_extent);
chunk_objectid = btrfs_dev_extent_chunk_objectid(l, dev_extent);
chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
btrfs_release_path(path);
ret = btrfs_relocate_chunk(root, chunk_tree, chunk_objectid,
chunk_offset);
if (ret && ret != -ENOSPC)
goto done;
if (ret == -ENOSPC)
failed++;
key.offset -= 1;
}
if (failed && !retried) {
failed = 0;
retried = true;
goto again;
} else if (failed && retried) {
ret = -ENOSPC;
lock_chunks(root);
device->total_bytes = old_size;
if (device->writeable)
device->fs_devices->total_rw_bytes += diff;
unlock_chunks(root);
goto done;
}
/* Shrinking succeeded, else we would be at "done". */
trans = btrfs_start_transaction(root, 0);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
goto done;
}
lock_chunks(root);
device->disk_total_bytes = new_size;
/* Now btrfs_update_device() will change the on-disk size. */
ret = btrfs_update_device(trans, device);
if (ret) {
unlock_chunks(root);
btrfs_end_transaction(trans, root);
goto done;
}
WARN_ON(diff > old_total);
btrfs_set_super_total_bytes(super_copy, old_total - diff);
unlock_chunks(root);
btrfs_end_transaction(trans, root);
done:
btrfs_free_path(path);
return ret;
}
static int btrfs_add_system_chunk(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_key *key,
struct btrfs_chunk *chunk, int item_size)
{
struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
struct btrfs_disk_key disk_key;
u32 array_size;
u8 *ptr;
array_size = btrfs_super_sys_array_size(super_copy);
if (array_size + item_size > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
return -EFBIG;
ptr = super_copy->sys_chunk_array + array_size;
btrfs_cpu_key_to_disk(&disk_key, key);
memcpy(ptr, &disk_key, sizeof(disk_key));
ptr += sizeof(disk_key);
memcpy(ptr, chunk, item_size);
item_size += sizeof(disk_key);
btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
return 0;
}
/*
* sort the devices in descending order by max_avail, total_avail
*/
static int btrfs_cmp_device_info(const void *a, const void *b)
{
const struct btrfs_device_info *di_a = a;
const struct btrfs_device_info *di_b = b;
if (di_a->max_avail > di_b->max_avail)
return -1;
if (di_a->max_avail < di_b->max_avail)
return 1;
if (di_a->total_avail > di_b->total_avail)
return -1;
if (di_a->total_avail < di_b->total_avail)
return 1;
return 0;
}
static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
struct btrfs_root *extent_root,
struct map_lookup **map_ret,
u64 *num_bytes_out, u64 *stripe_size_out,
u64 start, u64 type)
{
struct btrfs_fs_info *info = extent_root->fs_info;
struct btrfs_fs_devices *fs_devices = info->fs_devices;
struct list_head *cur;
struct map_lookup *map = NULL;
struct extent_map_tree *em_tree;
struct extent_map *em;
struct btrfs_device_info *devices_info = NULL;
u64 total_avail;
int num_stripes; /* total number of stripes to allocate */
int sub_stripes; /* sub_stripes info for map */
int dev_stripes; /* stripes per dev */
int devs_max; /* max devs to use */
int devs_min; /* min devs needed */
int devs_increment; /* ndevs has to be a multiple of this */
int ncopies; /* how many copies to data has */
int ret;
u64 max_stripe_size;
u64 max_chunk_size;
u64 stripe_size;
u64 num_bytes;
int ndevs;
int i;
int j;
if ((type & BTRFS_BLOCK_GROUP_RAID1) &&
(type & BTRFS_BLOCK_GROUP_DUP)) {
WARN_ON(1);
type &= ~BTRFS_BLOCK_GROUP_DUP;
}
if (list_empty(&fs_devices->alloc_list))
return -ENOSPC;
sub_stripes = 1;
dev_stripes = 1;
devs_increment = 1;
ncopies = 1;
devs_max = 0; /* 0 == as many as possible */
devs_min = 1;
/*
* define the properties of each RAID type.
* FIXME: move this to a global table and use it in all RAID
* calculation code
*/
if (type & (BTRFS_BLOCK_GROUP_DUP)) {
dev_stripes = 2;
ncopies = 2;
devs_max = 1;
} else if (type & (BTRFS_BLOCK_GROUP_RAID0)) {
devs_min = 2;
} else if (type & (BTRFS_BLOCK_GROUP_RAID1)) {
devs_increment = 2;
ncopies = 2;
devs_max = 2;
devs_min = 2;
} else if (type & (BTRFS_BLOCK_GROUP_RAID10)) {
sub_stripes = 2;
devs_increment = 2;
ncopies = 2;
devs_min = 4;
} else {
devs_max = 1;
}
if (type & BTRFS_BLOCK_GROUP_DATA) {
max_stripe_size = 1024 * 1024 * 1024;
max_chunk_size = 10 * max_stripe_size;
} else if (type & BTRFS_BLOCK_GROUP_METADATA) {
max_stripe_size = 256 * 1024 * 1024;
max_chunk_size = max_stripe_size;
} else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
max_stripe_size = 8 * 1024 * 1024;
max_chunk_size = 2 * max_stripe_size;
} else {
printk(KERN_ERR "btrfs: invalid chunk type 0x%llx requested\n",
type);
BUG_ON(1);
}
/* we don't want a chunk larger than 10% of writeable space */
max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
max_chunk_size);
devices_info = kzalloc(sizeof(*devices_info) * fs_devices->rw_devices,
GFP_NOFS);
if (!devices_info)
return -ENOMEM;
cur = fs_devices->alloc_list.next;
/*
* in the first pass through the devices list, we gather information
* about the available holes on each device.
*/
ndevs = 0;
while (cur != &fs_devices->alloc_list) {
struct btrfs_device *device;
u64 max_avail;
u64 dev_offset;
device = list_entry(cur, struct btrfs_device, dev_alloc_list);
cur = cur->next;
if (!device->writeable) {
printk(KERN_ERR
"btrfs: read-only device in alloc_list\n");
WARN_ON(1);
continue;
}
if (!device->in_fs_metadata)
continue;
if (device->total_bytes > device->bytes_used)
total_avail = device->total_bytes - device->bytes_used;
else
total_avail = 0;
/* avail is off by max(alloc_start, 1MB), but that is the same
* for all devices, so it doesn't hurt the sorting later on
*/
ret = find_free_dev_extent(trans, device,
max_stripe_size * dev_stripes,
&dev_offset, &max_avail);
if (ret && ret != -ENOSPC)
goto error;
if (ret == 0)
max_avail = max_stripe_size * dev_stripes;
if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
continue;
devices_info[ndevs].dev_offset = dev_offset;
devices_info[ndevs].max_avail = max_avail;
devices_info[ndevs].total_avail = total_avail;
devices_info[ndevs].dev = device;
++ndevs;
}
/*
* now sort the devices by hole size / available space
*/
sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
btrfs_cmp_device_info, NULL);
/* round down to number of usable stripes */
ndevs -= ndevs % devs_increment;
if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
ret = -ENOSPC;
goto error;
}
if (devs_max && ndevs > devs_max)
ndevs = devs_max;
/*
* the primary goal is to maximize the number of stripes, so use as many
* devices as possible, even if the stripes are not maximum sized.
*/
stripe_size = devices_info[ndevs-1].max_avail;
num_stripes = ndevs * dev_stripes;
if (stripe_size * num_stripes > max_chunk_size * ncopies) {
stripe_size = max_chunk_size * ncopies;
do_div(stripe_size, num_stripes);
}
do_div(stripe_size, dev_stripes);
do_div(stripe_size, BTRFS_STRIPE_LEN);
stripe_size *= BTRFS_STRIPE_LEN;
map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
if (!map) {
ret = -ENOMEM;
goto error;
}
map->num_stripes = num_stripes;
for (i = 0; i < ndevs; ++i) {
for (j = 0; j < dev_stripes; ++j) {
int s = i * dev_stripes + j;
map->stripes[s].dev = devices_info[i].dev;
map->stripes[s].physical = devices_info[i].dev_offset +
j * stripe_size;
}
}
map->sector_size = extent_root->sectorsize;
map->stripe_len = BTRFS_STRIPE_LEN;
map->io_align = BTRFS_STRIPE_LEN;
map->io_width = BTRFS_STRIPE_LEN;
map->type = type;
map->sub_stripes = sub_stripes;
*map_ret = map;
num_bytes = stripe_size * (num_stripes / ncopies);
*stripe_size_out = stripe_size;
*num_bytes_out = num_bytes;
trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
em = alloc_extent_map();
if (!em) {
ret = -ENOMEM;
goto error;
}
em->bdev = (struct block_device *)map;
em->start = start;
em->len = num_bytes;
em->block_start = 0;
em->block_len = em->len;
em_tree = &extent_root->fs_info->mapping_tree.map_tree;
write_lock(&em_tree->lock);
ret = add_extent_mapping(em_tree, em);
write_unlock(&em_tree->lock);
BUG_ON(ret);
free_extent_map(em);
ret = btrfs_make_block_group(trans, extent_root, 0, type,
BTRFS_FIRST_CHUNK_TREE_OBJECTID,
start, num_bytes);
BUG_ON(ret);
for (i = 0; i < map->num_stripes; ++i) {
struct btrfs_device *device;
u64 dev_offset;
device = map->stripes[i].dev;
dev_offset = map->stripes[i].physical;
ret = btrfs_alloc_dev_extent(trans, device,
info->chunk_root->root_key.objectid,
BTRFS_FIRST_CHUNK_TREE_OBJECTID,
start, dev_offset, stripe_size);
BUG_ON(ret);
}
kfree(devices_info);
return 0;
error:
kfree(map);
kfree(devices_info);
return ret;
}
static int __finish_chunk_alloc(struct btrfs_trans_handle *trans,
struct btrfs_root *extent_root,
struct map_lookup *map, u64 chunk_offset,
u64 chunk_size, u64 stripe_size)
{
u64 dev_offset;
struct btrfs_key key;
struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
struct btrfs_device *device;
struct btrfs_chunk *chunk;
struct btrfs_stripe *stripe;
size_t item_size = btrfs_chunk_item_size(map->num_stripes);
int index = 0;
int ret;
chunk = kzalloc(item_size, GFP_NOFS);
if (!chunk)
return -ENOMEM;
index = 0;
while (index < map->num_stripes) {
device = map->stripes[index].dev;
device->bytes_used += stripe_size;
ret = btrfs_update_device(trans, device);
BUG_ON(ret);
index++;
}
index = 0;
stripe = &chunk->stripe;
while (index < map->num_stripes) {
device = map->stripes[index].dev;
dev_offset = map->stripes[index].physical;
btrfs_set_stack_stripe_devid(stripe, device->devid);
btrfs_set_stack_stripe_offset(stripe, dev_offset);
memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
stripe++;
index++;
}
btrfs_set_stack_chunk_length(chunk, chunk_size);
btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
btrfs_set_stack_chunk_type(chunk, map->type);
btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
key.type = BTRFS_CHUNK_ITEM_KEY;
key.offset = chunk_offset;
ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
BUG_ON(ret);
if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
ret = btrfs_add_system_chunk(trans, chunk_root, &key, chunk,
item_size);
BUG_ON(ret);
}
kfree(chunk);
return 0;
}
/*
* Chunk allocation falls into two parts. The first part does works
* that make the new allocated chunk useable, but not do any operation
* that modifies the chunk tree. The second part does the works that
* require modifying the chunk tree. This division is important for the
* bootstrap process of adding storage to a seed btrfs.
*/
int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
struct btrfs_root *extent_root, u64 type)
{
u64 chunk_offset;
u64 chunk_size;
u64 stripe_size;
struct map_lookup *map;
struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
int ret;
ret = find_next_chunk(chunk_root, BTRFS_FIRST_CHUNK_TREE_OBJECTID,
&chunk_offset);
if (ret)
return ret;
ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
&stripe_size, chunk_offset, type);
if (ret)
return ret;
ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
chunk_size, stripe_size);
BUG_ON(ret);
return 0;
}
static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct btrfs_device *device)
{
u64 chunk_offset;
u64 sys_chunk_offset;
u64 chunk_size;
u64 sys_chunk_size;
u64 stripe_size;
u64 sys_stripe_size;
u64 alloc_profile;
struct map_lookup *map;
struct map_lookup *sys_map;
struct btrfs_fs_info *fs_info = root->fs_info;
struct btrfs_root *extent_root = fs_info->extent_root;
int ret;
ret = find_next_chunk(fs_info->chunk_root,
BTRFS_FIRST_CHUNK_TREE_OBJECTID, &chunk_offset);
BUG_ON(ret);
alloc_profile = BTRFS_BLOCK_GROUP_METADATA |
(fs_info->metadata_alloc_profile &
fs_info->avail_metadata_alloc_bits);
alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
ret = __btrfs_alloc_chunk(trans, extent_root, &map, &chunk_size,
&stripe_size, chunk_offset, alloc_profile);
BUG_ON(ret);
sys_chunk_offset = chunk_offset + chunk_size;
alloc_profile = BTRFS_BLOCK_GROUP_SYSTEM |
(fs_info->system_alloc_profile &
fs_info->avail_system_alloc_bits);
alloc_profile = btrfs_reduce_alloc_profile(root, alloc_profile);
ret = __btrfs_alloc_chunk(trans, extent_root, &sys_map,
&sys_chunk_size, &sys_stripe_size,
sys_chunk_offset, alloc_profile);
BUG_ON(ret);
ret = btrfs_add_device(trans, fs_info->chunk_root, device);
BUG_ON(ret);
/*
* Modifying chunk tree needs allocating new blocks from both
* system block group and metadata block group. So we only can
* do operations require modifying the chunk tree after both
* block groups were created.
*/
ret = __finish_chunk_alloc(trans, extent_root, map, chunk_offset,
chunk_size, stripe_size);
BUG_ON(ret);
ret = __finish_chunk_alloc(trans, extent_root, sys_map,
sys_chunk_offset, sys_chunk_size,
sys_stripe_size);
BUG_ON(ret);
return 0;
}
int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
{
struct extent_map *em;
struct map_lookup *map;
struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
int readonly = 0;
int i;
read_lock(&map_tree->map_tree.lock);
em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
read_unlock(&map_tree->map_tree.lock);
if (!em)
return 1;
if (btrfs_test_opt(root, DEGRADED)) {
free_extent_map(em);
return 0;
}
map = (struct map_lookup *)em->bdev;
for (i = 0; i < map->num_stripes; i++) {
if (!map->stripes[i].dev->writeable) {
readonly = 1;
break;
}
}
free_extent_map(em);
return readonly;
}
void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
{
extent_map_tree_init(&tree->map_tree);
}
void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
{
struct extent_map *em;
while (1) {
write_lock(&tree->map_tree.lock);
em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
if (em)
remove_extent_mapping(&tree->map_tree, em);
write_unlock(&tree->map_tree.lock);
if (!em)
break;
kfree(em->bdev);
/* once for us */
free_extent_map(em);
/* once for the tree */
free_extent_map(em);
}
}
int btrfs_num_copies(struct btrfs_mapping_tree *map_tree, u64 logical, u64 len)
{
struct extent_map *em;
struct map_lookup *map;
struct extent_map_tree *em_tree = &map_tree->map_tree;
int ret;
read_lock(&em_tree->lock);
em = lookup_extent_mapping(em_tree, logical, len);
read_unlock(&em_tree->lock);
BUG_ON(!em);
BUG_ON(em->start > logical || em->start + em->len < logical);
map = (struct map_lookup *)em->bdev;
if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
ret = map->num_stripes;
else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
ret = map->sub_stripes;
else
ret = 1;
free_extent_map(em);
return ret;
}
static int find_live_mirror(struct map_lookup *map, int first, int num,
int optimal)
{
int i;
if (map->stripes[optimal].dev->bdev)
return optimal;
for (i = first; i < first + num; i++) {
if (map->stripes[i].dev->bdev)
return i;
}
/* we couldn't find one that doesn't fail. Just return something
* and the io error handling code will clean up eventually
*/
return optimal;
}
static int __btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
u64 logical, u64 *length,
struct btrfs_multi_bio **multi_ret,
int mirror_num)
{
struct extent_map *em;
struct map_lookup *map;
struct extent_map_tree *em_tree = &map_tree->map_tree;
u64 offset;
u64 stripe_offset;
u64 stripe_end_offset;
u64 stripe_nr;
u64 stripe_nr_orig;
u64 stripe_nr_end;
int stripes_allocated = 8;
int stripes_required = 1;
int stripe_index;
int i;
int num_stripes;
int max_errors = 0;
struct btrfs_multi_bio *multi = NULL;
if (multi_ret && !(rw & (REQ_WRITE | REQ_DISCARD)))
stripes_allocated = 1;
again:
if (multi_ret) {
multi = kzalloc(btrfs_multi_bio_size(stripes_allocated),
GFP_NOFS);
if (!multi)
return -ENOMEM;
atomic_set(&multi->error, 0);
}
read_lock(&em_tree->lock);
em = lookup_extent_mapping(em_tree, logical, *length);
read_unlock(&em_tree->lock);
if (!em) {
printk(KERN_CRIT "unable to find logical %llu len %llu\n",
(unsigned long long)logical,
(unsigned long long)*length);
BUG();
}
BUG_ON(em->start > logical || em->start + em->len < logical);
map = (struct map_lookup *)em->bdev;
offset = logical - em->start;
if (mirror_num > map->num_stripes)
mirror_num = 0;
/* if our multi bio struct is too small, back off and try again */
if (rw & REQ_WRITE) {
if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
BTRFS_BLOCK_GROUP_DUP)) {
stripes_required = map->num_stripes;
max_errors = 1;
} else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
stripes_required = map->sub_stripes;
max_errors = 1;
}
}
if (rw & REQ_DISCARD) {
if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
BTRFS_BLOCK_GROUP_RAID1 |
BTRFS_BLOCK_GROUP_DUP |
BTRFS_BLOCK_GROUP_RAID10)) {
stripes_required = map->num_stripes;
}
}
if (multi_ret && (rw & (REQ_WRITE | REQ_DISCARD)) &&
stripes_allocated < stripes_required) {
stripes_allocated = map->num_stripes;
free_extent_map(em);
kfree(multi);
goto again;
}
stripe_nr = offset;
/*
* stripe_nr counts the total number of stripes we have to stride
* to get to this block
*/
do_div(stripe_nr, map->stripe_len);
stripe_offset = stripe_nr * map->stripe_len;
BUG_ON(offset < stripe_offset);
/* stripe_offset is the offset of this block in its stripe*/
stripe_offset = offset - stripe_offset;
if (rw & REQ_DISCARD)
*length = min_t(u64, em->len - offset, *length);
else if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
BTRFS_BLOCK_GROUP_RAID1 |
BTRFS_BLOCK_GROUP_RAID10 |
BTRFS_BLOCK_GROUP_DUP)) {
/* we limit the length of each bio to what fits in a stripe */
*length = min_t(u64, em->len - offset,
map->stripe_len - stripe_offset);
} else {
*length = em->len - offset;
}
if (!multi_ret)
goto out;
num_stripes = 1;
stripe_index = 0;
stripe_nr_orig = stripe_nr;
stripe_nr_end = (offset + *length + map->stripe_len - 1) &
(~(map->stripe_len - 1));
do_div(stripe_nr_end, map->stripe_len);
stripe_end_offset = stripe_nr_end * map->stripe_len -
(offset + *length);
if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
if (rw & REQ_DISCARD)
num_stripes = min_t(u64, map->num_stripes,
stripe_nr_end - stripe_nr_orig);
stripe_index = do_div(stripe_nr, map->num_stripes);
} else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
if (rw & (REQ_WRITE | REQ_DISCARD))
num_stripes = map->num_stripes;
else if (mirror_num)
stripe_index = mirror_num - 1;
else {
stripe_index = find_live_mirror(map, 0,
map->num_stripes,
current->pid % map->num_stripes);
}
} else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
if (rw & (REQ_WRITE | REQ_DISCARD))
num_stripes = map->num_stripes;
else if (mirror_num)
stripe_index = mirror_num - 1;
} else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
int factor = map->num_stripes / map->sub_stripes;
stripe_index = do_div(stripe_nr, factor);
stripe_index *= map->sub_stripes;
if (rw & REQ_WRITE)
num_stripes = map->sub_stripes;
else if (rw & REQ_DISCARD)
num_stripes = min_t(u64, map->sub_stripes *
(stripe_nr_end - stripe_nr_orig),
map->num_stripes);
else if (mirror_num)
stripe_index += mirror_num - 1;
else {
stripe_index = find_live_mirror(map, stripe_index,
map->sub_stripes, stripe_index +
current->pid % map->sub_stripes);
}
} else {
/*
* after this do_div call, stripe_nr is the number of stripes
* on this device we have to walk to find the data, and
* stripe_index is the number of our device in the stripe array
*/
stripe_index = do_div(stripe_nr, map->num_stripes);
}
BUG_ON(stripe_index >= map->num_stripes);
if (rw & REQ_DISCARD) {
for (i = 0; i < num_stripes; i++) {
multi->stripes[i].physical =
map->stripes[stripe_index].physical +
stripe_offset + stripe_nr * map->stripe_len;
multi->stripes[i].dev = map->stripes[stripe_index].dev;
if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
u64 stripes;
u32 last_stripe = 0;
int j;
div_u64_rem(stripe_nr_end - 1,
map->num_stripes,
&last_stripe);
for (j = 0; j < map->num_stripes; j++) {
u32 test;
div_u64_rem(stripe_nr_end - 1 - j,
map->num_stripes, &test);
if (test == stripe_index)
break;
}
stripes = stripe_nr_end - 1 - j;
do_div(stripes, map->num_stripes);
multi->stripes[i].length = map->stripe_len *
(stripes - stripe_nr + 1);
if (i == 0) {
multi->stripes[i].length -=
stripe_offset;
stripe_offset = 0;
}
if (stripe_index == last_stripe)
multi->stripes[i].length -=
stripe_end_offset;
} else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
u64 stripes;
int j;
int factor = map->num_stripes /
map->sub_stripes;
u32 last_stripe = 0;
div_u64_rem(stripe_nr_end - 1,
factor, &last_stripe);
last_stripe *= map->sub_stripes;
for (j = 0; j < factor; j++) {
u32 test;
div_u64_rem(stripe_nr_end - 1 - j,
factor, &test);
if (test ==
stripe_index / map->sub_stripes)
break;
}
stripes = stripe_nr_end - 1 - j;
do_div(stripes, factor);
multi->stripes[i].length = map->stripe_len *
(stripes - stripe_nr + 1);
if (i < map->sub_stripes) {
multi->stripes[i].length -=
stripe_offset;
if (i == map->sub_stripes - 1)
stripe_offset = 0;
}
if (stripe_index >= last_stripe &&
stripe_index <= (last_stripe +
map->sub_stripes - 1)) {
multi->stripes[i].length -=
stripe_end_offset;
}
} else
multi->stripes[i].length = *length;
stripe_index++;
if (stripe_index == map->num_stripes) {
/* This could only happen for RAID0/10 */
stripe_index = 0;
stripe_nr++;
}
}
} else {
for (i = 0; i < num_stripes; i++) {
multi->stripes[i].physical =
map->stripes[stripe_index].physical +
stripe_offset +
stripe_nr * map->stripe_len;
multi->stripes[i].dev =
map->stripes[stripe_index].dev;
stripe_index++;
}
}
if (multi_ret) {
*multi_ret = multi;
multi->num_stripes = num_stripes;
multi->max_errors = max_errors;
}
out:
free_extent_map(em);
return 0;
}
int btrfs_map_block(struct btrfs_mapping_tree *map_tree, int rw,
u64 logical, u64 *length,
struct btrfs_multi_bio **multi_ret, int mirror_num)
{
return __btrfs_map_block(map_tree, rw, logical, length, multi_ret,
mirror_num);
}
int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
u64 chunk_start, u64 physical, u64 devid,
u64 **logical, int *naddrs, int *stripe_len)
{
struct extent_map_tree *em_tree = &map_tree->map_tree;
struct extent_map *em;
struct map_lookup *map;
u64 *buf;
u64 bytenr;
u64 length;
u64 stripe_nr;
int i, j, nr = 0;
read_lock(&em_tree->lock);
em = lookup_extent_mapping(em_tree, chunk_start, 1);
read_unlock(&em_tree->lock);
BUG_ON(!em || em->start != chunk_start);
map = (struct map_lookup *)em->bdev;
length = em->len;
if (map->type & BTRFS_BLOCK_GROUP_RAID10)
do_div(length, map->num_stripes / map->sub_stripes);
else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
do_div(length, map->num_stripes);
buf = kzalloc(sizeof(u64) * map->num_stripes, GFP_NOFS);
BUG_ON(!buf);
for (i = 0; i < map->num_stripes; i++) {
if (devid && map->stripes[i].dev->devid != devid)
continue;
if (map->stripes[i].physical > physical ||
map->stripes[i].physical + length <= physical)
continue;
stripe_nr = physical - map->stripes[i].physical;
do_div(stripe_nr, map->stripe_len);
if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
stripe_nr = stripe_nr * map->num_stripes + i;
do_div(stripe_nr, map->sub_stripes);
} else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
stripe_nr = stripe_nr * map->num_stripes + i;
}
bytenr = chunk_start + stripe_nr * map->stripe_len;
WARN_ON(nr >= map->num_stripes);
for (j = 0; j < nr; j++) {
if (buf[j] == bytenr)
break;
}
if (j == nr) {
WARN_ON(nr >= map->num_stripes);
buf[nr++] = bytenr;
}
}
*logical = buf;
*naddrs = nr;
*stripe_len = map->stripe_len;
free_extent_map(em);
return 0;
}
static void end_bio_multi_stripe(struct bio *bio, int err)
{
struct btrfs_multi_bio *multi = bio->bi_private;
int is_orig_bio = 0;
if (err)
atomic_inc(&multi->error);
if (bio == multi->orig_bio)
is_orig_bio = 1;
if (atomic_dec_and_test(&multi->stripes_pending)) {
if (!is_orig_bio) {
bio_put(bio);
bio = multi->orig_bio;
}
bio->bi_private = multi->private;
bio->bi_end_io = multi->end_io;
/* only send an error to the higher layers if it is
* beyond the tolerance of the multi-bio
*/
if (atomic_read(&multi->error) > multi->max_errors) {
err = -EIO;
} else if (err) {
/*
* this bio is actually up to date, we didn't
* go over the max number of errors
*/
set_bit(BIO_UPTODATE, &bio->bi_flags);
err = 0;
}
kfree(multi);
bio_endio(bio, err);
} else if (!is_orig_bio) {
bio_put(bio);
}
}
struct async_sched {
struct bio *bio;
int rw;
struct btrfs_fs_info *info;
struct btrfs_work work;
};
/*
* see run_scheduled_bios for a description of why bios are collected for
* async submit.
*
* This will add one bio to the pending list for a device and make sure
* the work struct is scheduled.
*/
static noinline int schedule_bio(struct btrfs_root *root,
struct btrfs_device *device,
int rw, struct bio *bio)
{
int should_queue = 1;
struct btrfs_pending_bios *pending_bios;
/* don't bother with additional async steps for reads, right now */
if (!(rw & REQ_WRITE)) {
bio_get(bio);
submit_bio(rw, bio);
bio_put(bio);
return 0;
}
/*
* nr_async_bios allows us to reliably return congestion to the
* higher layers. Otherwise, the async bio makes it appear we have
* made progress against dirty pages when we've really just put it
* on a queue for later
*/
atomic_inc(&root->fs_info->nr_async_bios);
WARN_ON(bio->bi_next);
bio->bi_next = NULL;
bio->bi_rw |= rw;
spin_lock(&device->io_lock);
if (bio->bi_rw & REQ_SYNC)
pending_bios = &device->pending_sync_bios;
else
pending_bios = &device->pending_bios;
if (pending_bios->tail)
pending_bios->tail->bi_next = bio;
pending_bios->tail = bio;
if (!pending_bios->head)
pending_bios->head = bio;
if (device->running_pending)
should_queue = 0;
spin_unlock(&device->io_lock);
if (should_queue)
btrfs_queue_worker(&root->fs_info->submit_workers,
&device->work);
return 0;
}
int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
int mirror_num, int async_submit)
{
struct btrfs_mapping_tree *map_tree;
struct btrfs_device *dev;
struct bio *first_bio = bio;
u64 logical = (u64)bio->bi_sector << 9;
u64 length = 0;
u64 map_length;
struct btrfs_multi_bio *multi = NULL;
int ret;
int dev_nr = 0;
int total_devs = 1;
length = bio->bi_size;
map_tree = &root->fs_info->mapping_tree;
map_length = length;
ret = btrfs_map_block(map_tree, rw, logical, &map_length, &multi,
mirror_num);
BUG_ON(ret);
total_devs = multi->num_stripes;
if (map_length < length) {
printk(KERN_CRIT "mapping failed logical %llu bio len %llu "
"len %llu\n", (unsigned long long)logical,
(unsigned long long)length,
(unsigned long long)map_length);
BUG();
}
multi->end_io = first_bio->bi_end_io;
multi->private = first_bio->bi_private;
multi->orig_bio = first_bio;
atomic_set(&multi->stripes_pending, multi->num_stripes);
while (dev_nr < total_devs) {
if (total_devs > 1) {
if (dev_nr < total_devs - 1) {
bio = bio_clone(first_bio, GFP_NOFS);
BUG_ON(!bio);
} else {
bio = first_bio;
}
bio->bi_private = multi;
bio->bi_end_io = end_bio_multi_stripe;
}
bio->bi_sector = multi->stripes[dev_nr].physical >> 9;
dev = multi->stripes[dev_nr].dev;
if (dev && dev->bdev && (rw != WRITE || dev->writeable)) {
bio->bi_bdev = dev->bdev;
if (async_submit)
schedule_bio(root, dev, rw, bio);
else
submit_bio(rw, bio);
} else {
bio->bi_bdev = root->fs_info->fs_devices->latest_bdev;
bio->bi_sector = logical >> 9;
bio_endio(bio, -EIO);
}
dev_nr++;
}
if (total_devs == 1)
kfree(multi);
return 0;
}
struct btrfs_device *btrfs_find_device(struct btrfs_root *root, u64 devid,
u8 *uuid, u8 *fsid)
{
struct btrfs_device *device;
struct btrfs_fs_devices *cur_devices;
cur_devices = root->fs_info->fs_devices;
while (cur_devices) {
if (!fsid ||
!memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
device = __find_device(&cur_devices->devices,
devid, uuid);
if (device)
return device;
}
cur_devices = cur_devices->seed;
}
return NULL;
}
static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
u64 devid, u8 *dev_uuid)
{
struct btrfs_device *device;
struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
device = kzalloc(sizeof(*device), GFP_NOFS);
if (!device)
return NULL;
list_add(&device->dev_list,
&fs_devices->devices);
device->dev_root = root->fs_info->dev_root;
device->devid = devid;
device->work.func = pending_bios_fn;
device->fs_devices = fs_devices;
device->missing = 1;
fs_devices->num_devices++;
fs_devices->missing_devices++;
spin_lock_init(&device->io_lock);
INIT_LIST_HEAD(&device->dev_alloc_list);
memcpy(device->uuid, dev_uuid, BTRFS_UUID_SIZE);
return device;
}
static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
struct extent_buffer *leaf,
struct btrfs_chunk *chunk)
{
struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
struct map_lookup *map;
struct extent_map *em;
u64 logical;
u64 length;
u64 devid;
u8 uuid[BTRFS_UUID_SIZE];
int num_stripes;
int ret;
int i;
logical = key->offset;
length = btrfs_chunk_length(leaf, chunk);
read_lock(&map_tree->map_tree.lock);
em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
read_unlock(&map_tree->map_tree.lock);
/* already mapped? */
if (em && em->start <= logical && em->start + em->len > logical) {
free_extent_map(em);
return 0;
} else if (em) {
free_extent_map(em);
}
em = alloc_extent_map();
if (!em)
return -ENOMEM;
num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
if (!map) {
free_extent_map(em);
return -ENOMEM;
}
em->bdev = (struct block_device *)map;
em->start = logical;
em->len = length;
em->block_start = 0;
em->block_len = em->len;
map->num_stripes = num_stripes;
map->io_width = btrfs_chunk_io_width(leaf, chunk);
map->io_align = btrfs_chunk_io_align(leaf, chunk);
map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
map->type = btrfs_chunk_type(leaf, chunk);
map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
for (i = 0; i < num_stripes; i++) {
map->stripes[i].physical =
btrfs_stripe_offset_nr(leaf, chunk, i);
devid = btrfs_stripe_devid_nr(leaf, chunk, i);
read_extent_buffer(leaf, uuid, (unsigned long)
btrfs_stripe_dev_uuid_nr(chunk, i),
BTRFS_UUID_SIZE);
map->stripes[i].dev = btrfs_find_device(root, devid, uuid,
NULL);
if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
kfree(map);
free_extent_map(em);
return -EIO;
}
if (!map->stripes[i].dev) {
map->stripes[i].dev =
add_missing_dev(root, devid, uuid);
if (!map->stripes[i].dev) {
kfree(map);
free_extent_map(em);
return -EIO;
}
}
map->stripes[i].dev->in_fs_metadata = 1;
}
write_lock(&map_tree->map_tree.lock);
ret = add_extent_mapping(&map_tree->map_tree, em);
write_unlock(&map_tree->map_tree.lock);
BUG_ON(ret);
free_extent_map(em);
return 0;
}
static int fill_device_from_item(struct extent_buffer *leaf,
struct btrfs_dev_item *dev_item,
struct btrfs_device *device)
{
unsigned long ptr;
device->devid = btrfs_device_id(leaf, dev_item);
device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
device->total_bytes = device->disk_total_bytes;
device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
device->type = btrfs_device_type(leaf, dev_item);
device->io_align = btrfs_device_io_align(leaf, dev_item);
device->io_width = btrfs_device_io_width(leaf, dev_item);
device->sector_size = btrfs_device_sector_size(leaf, dev_item);
ptr = (unsigned long)btrfs_device_uuid(dev_item);
read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
return 0;
}
static int open_seed_devices(struct btrfs_root *root, u8 *fsid)
{
struct btrfs_fs_devices *fs_devices;
int ret;
mutex_lock(&uuid_mutex);
fs_devices = root->fs_info->fs_devices->seed;
while (fs_devices) {
if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
ret = 0;
goto out;
}
fs_devices = fs_devices->seed;
}
fs_devices = find_fsid(fsid);
if (!fs_devices) {
ret = -ENOENT;
goto out;
}
fs_devices = clone_fs_devices(fs_devices);
if (IS_ERR(fs_devices)) {
ret = PTR_ERR(fs_devices);
goto out;
}
ret = __btrfs_open_devices(fs_devices, FMODE_READ,
root->fs_info->bdev_holder);
if (ret)
goto out;
if (!fs_devices->seeding) {
__btrfs_close_devices(fs_devices);
free_fs_devices(fs_devices);
ret = -EINVAL;
goto out;
}
fs_devices->seed = root->fs_info->fs_devices->seed;
root->fs_info->fs_devices->seed = fs_devices;
out:
mutex_unlock(&uuid_mutex);
return ret;
}
static int read_one_dev(struct btrfs_root *root,
struct extent_buffer *leaf,
struct btrfs_dev_item *dev_item)
{
struct btrfs_device *device;
u64 devid;
int ret;
u8 fs_uuid[BTRFS_UUID_SIZE];
u8 dev_uuid[BTRFS_UUID_SIZE];
devid = btrfs_device_id(leaf, dev_item);
read_extent_buffer(leaf, dev_uuid,
(unsigned long)btrfs_device_uuid(dev_item),
BTRFS_UUID_SIZE);
read_extent_buffer(leaf, fs_uuid,
(unsigned long)btrfs_device_fsid(dev_item),
BTRFS_UUID_SIZE);
if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
ret = open_seed_devices(root, fs_uuid);
if (ret && !btrfs_test_opt(root, DEGRADED))
return ret;
}
device = btrfs_find_device(root, devid, dev_uuid, fs_uuid);
if (!device || !device->bdev) {
if (!btrfs_test_opt(root, DEGRADED))
return -EIO;
if (!device) {
printk(KERN_WARNING "warning devid %llu missing\n",
(unsigned long long)devid);
device = add_missing_dev(root, devid, dev_uuid);
if (!device)
return -ENOMEM;
} else if (!device->missing) {
/*
* this happens when a device that was properly setup
* in the device info lists suddenly goes bad.
* device->bdev is NULL, and so we have to set
* device->missing to one here
*/
root->fs_info->fs_devices->missing_devices++;
device->missing = 1;
}
}
if (device->fs_devices != root->fs_info->fs_devices) {
BUG_ON(device->writeable);
if (device->generation !=
btrfs_device_generation(leaf, dev_item))
return -EINVAL;
}
fill_device_from_item(leaf, dev_item, device);
device->dev_root = root->fs_info->dev_root;
device->in_fs_metadata = 1;
if (device->writeable)
device->fs_devices->total_rw_bytes += device->total_bytes;
ret = 0;
return ret;
}
int btrfs_read_sys_array(struct btrfs_root *root)
{
struct btrfs_super_block *super_copy = &root->fs_info->super_copy;
struct extent_buffer *sb;
struct btrfs_disk_key *disk_key;
struct btrfs_chunk *chunk;
u8 *ptr;
unsigned long sb_ptr;
int ret = 0;
u32 num_stripes;
u32 array_size;
u32 len = 0;
u32 cur;
struct btrfs_key key;
sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET,
BTRFS_SUPER_INFO_SIZE);
if (!sb)
return -ENOMEM;
btrfs_set_buffer_uptodate(sb);
btrfs_set_buffer_lockdep_class(sb, 0);
write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
array_size = btrfs_super_sys_array_size(super_copy);
ptr = super_copy->sys_chunk_array;
sb_ptr = offsetof(struct btrfs_super_block, sys_chunk_array);
cur = 0;
while (cur < array_size) {
disk_key = (struct btrfs_disk_key *)ptr;
btrfs_disk_key_to_cpu(&key, disk_key);
len = sizeof(*disk_key); ptr += len;
sb_ptr += len;
cur += len;
if (key.type == BTRFS_CHUNK_ITEM_KEY) {
chunk = (struct btrfs_chunk *)sb_ptr;
ret = read_one_chunk(root, &key, sb, chunk);
if (ret)
break;
num_stripes = btrfs_chunk_num_stripes(sb, chunk);
len = btrfs_chunk_item_size(num_stripes);
} else {
ret = -EIO;
break;
}
ptr += len;
sb_ptr += len;
cur += len;
}
free_extent_buffer(sb);
return ret;
}
int btrfs_read_chunk_tree(struct btrfs_root *root)
{
struct btrfs_path *path;
struct extent_buffer *leaf;
struct btrfs_key key;
struct btrfs_key found_key;
int ret;
int slot;
root = root->fs_info->chunk_root;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
/* first we search for all of the device items, and then we
* read in all of the chunk items. This way we can create chunk
* mappings that reference all of the devices that are afound
*/
key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
key.offset = 0;
key.type = 0;
again:
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
goto error;
while (1) {
leaf = path->nodes[0];
slot = path->slots[0];
if (slot >= btrfs_header_nritems(leaf)) {
ret = btrfs_next_leaf(root, path);
if (ret == 0)
continue;
if (ret < 0)
goto error;
break;
}
btrfs_item_key_to_cpu(leaf, &found_key, slot);
if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
if (found_key.objectid != BTRFS_DEV_ITEMS_OBJECTID)
break;
if (found_key.type == BTRFS_DEV_ITEM_KEY) {
struct btrfs_dev_item *dev_item;
dev_item = btrfs_item_ptr(leaf, slot,
struct btrfs_dev_item);
ret = read_one_dev(root, leaf, dev_item);
if (ret)
goto error;
}
} else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
struct btrfs_chunk *chunk;
chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
ret = read_one_chunk(root, &found_key, leaf, chunk);
if (ret)
goto error;
}
path->slots[0]++;
}
if (key.objectid == BTRFS_DEV_ITEMS_OBJECTID) {
key.objectid = 0;
btrfs_release_path(path);
goto again;
}
ret = 0;
error:
btrfs_free_path(path);
return ret;
}
| gpl-2.0 |
stratosk/semaphore | drivers/media/dvb/ttpci/budget-core.c | 1663 | 17319 | /*
* budget-core.c: driver for the SAA7146 based Budget DVB cards
*
* Compiled from various sources by Michael Hunold <michael@mihu.de>
*
* Copyright (C) 2002 Ralph Metzler <rjkm@metzlerbros.de>
*
* Copyright (C) 1999-2002 Ralph Metzler
* & Marcus Metzler for convergence integrated media GmbH
*
* 26feb2004 Support for FS Activy Card (Grundig tuner) by
* Michael Dreher <michael@5dot1.de>,
* Oliver Endriss <o.endriss@gmx.de>,
* Andreas 'randy' Weinberger
*
* 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.
* Or, point your browser to http://www.gnu.org/copyleft/gpl.html
*
*
* the project's page is at http://www.linuxtv.org/dvb/
*/
#include "budget.h"
#include "ttpci-eeprom.h"
#define TS_WIDTH (2 * TS_SIZE)
#define TS_WIDTH_ACTIVY TS_SIZE
#define TS_WIDTH_DVBC TS_SIZE
#define TS_HEIGHT_MASK 0xf00
#define TS_HEIGHT_MASK_ACTIVY 0xc00
#define TS_HEIGHT_MASK_DVBC 0xe00
#define TS_MIN_BUFSIZE_K 188
#define TS_MAX_BUFSIZE_K 1410
#define TS_MAX_BUFSIZE_K_ACTIVY 564
#define TS_MAX_BUFSIZE_K_DVBC 1316
#define BUFFER_WARNING_WAIT (30*HZ)
int budget_debug;
static int dma_buffer_size = TS_MIN_BUFSIZE_K;
module_param_named(debug, budget_debug, int, 0644);
module_param_named(bufsize, dma_buffer_size, int, 0444);
MODULE_PARM_DESC(debug, "Turn on/off budget debugging (default:off).");
MODULE_PARM_DESC(bufsize, "DMA buffer size in KB, default: 188, min: 188, max: 1410 (Activy: 564)");
/****************************************************************************
* TT budget / WinTV Nova
****************************************************************************/
static int stop_ts_capture(struct budget *budget)
{
dprintk(2, "budget: %p\n", budget);
saa7146_write(budget->dev, MC1, MASK_20); // DMA3 off
SAA7146_IER_DISABLE(budget->dev, MASK_10);
return 0;
}
static int start_ts_capture(struct budget *budget)
{
struct saa7146_dev *dev = budget->dev;
dprintk(2, "budget: %p\n", budget);
if (!budget->feeding || !budget->fe_synced)
return 0;
saa7146_write(dev, MC1, MASK_20); // DMA3 off
memset(budget->grabbing, 0x00, budget->buffer_size);
saa7146_write(dev, PCI_BT_V1, 0x001c0000 | (saa7146_read(dev, PCI_BT_V1) & ~0x001f0000));
budget->ttbp = 0;
/*
* Signal path on the Activy:
*
* tuner -> SAA7146 port A -> SAA7146 BRS -> SAA7146 DMA3 -> memory
*
* Since the tuner feeds 204 bytes packets into the SAA7146,
* DMA3 is configured to strip the trailing 16 FEC bytes:
* Pitch: 188, NumBytes3: 188, NumLines3: 1024
*/
switch(budget->card->type) {
case BUDGET_FS_ACTIVY:
saa7146_write(dev, DD1_INIT, 0x04000000);
saa7146_write(dev, MC2, (MASK_09 | MASK_25));
saa7146_write(dev, BRS_CTRL, 0x00000000);
break;
case BUDGET_PATCH:
saa7146_write(dev, DD1_INIT, 0x00000200);
saa7146_write(dev, MC2, (MASK_10 | MASK_26));
saa7146_write(dev, BRS_CTRL, 0x60000000);
break;
case BUDGET_CIN1200C_MK3:
case BUDGET_KNC1C_MK3:
case BUDGET_KNC1CP_MK3:
if (budget->video_port == BUDGET_VIDEO_PORTA) {
saa7146_write(dev, DD1_INIT, 0x06000200);
saa7146_write(dev, MC2, (MASK_09 | MASK_25 | MASK_10 | MASK_26));
saa7146_write(dev, BRS_CTRL, 0x00000000);
} else {
saa7146_write(dev, DD1_INIT, 0x00000600);
saa7146_write(dev, MC2, (MASK_09 | MASK_25 | MASK_10 | MASK_26));
saa7146_write(dev, BRS_CTRL, 0x60000000);
}
break;
default:
if (budget->video_port == BUDGET_VIDEO_PORTA) {
saa7146_write(dev, DD1_INIT, 0x06000200);
saa7146_write(dev, MC2, (MASK_09 | MASK_25 | MASK_10 | MASK_26));
saa7146_write(dev, BRS_CTRL, 0x00000000);
} else {
saa7146_write(dev, DD1_INIT, 0x02000600);
saa7146_write(dev, MC2, (MASK_09 | MASK_25 | MASK_10 | MASK_26));
saa7146_write(dev, BRS_CTRL, 0x60000000);
}
}
saa7146_write(dev, MC2, (MASK_08 | MASK_24));
mdelay(10);
saa7146_write(dev, BASE_ODD3, 0);
if (budget->buffer_size > budget->buffer_height * budget->buffer_width) {
// using odd/even buffers
saa7146_write(dev, BASE_EVEN3, budget->buffer_height * budget->buffer_width);
} else {
// using a single buffer
saa7146_write(dev, BASE_EVEN3, 0);
}
saa7146_write(dev, PROT_ADDR3, budget->buffer_size);
saa7146_write(dev, BASE_PAGE3, budget->pt.dma | ME1 | 0x90);
saa7146_write(dev, PITCH3, budget->buffer_width);
saa7146_write(dev, NUM_LINE_BYTE3,
(budget->buffer_height << 16) | budget->buffer_width);
saa7146_write(dev, MC2, (MASK_04 | MASK_20));
SAA7146_ISR_CLEAR(budget->dev, MASK_10); /* VPE */
SAA7146_IER_ENABLE(budget->dev, MASK_10); /* VPE */
saa7146_write(dev, MC1, (MASK_04 | MASK_20)); /* DMA3 on */
return 0;
}
static int budget_read_fe_status(struct dvb_frontend *fe, fe_status_t *status)
{
struct budget *budget = (struct budget *) fe->dvb->priv;
int synced;
int ret;
if (budget->read_fe_status)
ret = budget->read_fe_status(fe, status);
else
ret = -EINVAL;
if (!ret) {
synced = (*status & FE_HAS_LOCK);
if (synced != budget->fe_synced) {
budget->fe_synced = synced;
spin_lock(&budget->feedlock);
if (synced)
start_ts_capture(budget);
else
stop_ts_capture(budget);
spin_unlock(&budget->feedlock);
}
}
return ret;
}
static void vpeirq(unsigned long data)
{
struct budget *budget = (struct budget *) data;
u8 *mem = (u8 *) (budget->grabbing);
u32 olddma = budget->ttbp;
u32 newdma = saa7146_read(budget->dev, PCI_VDP3);
u32 count;
/* Ensure streamed PCI data is synced to CPU */
pci_dma_sync_sg_for_cpu(budget->dev->pci, budget->pt.slist, budget->pt.nents, PCI_DMA_FROMDEVICE);
/* nearest lower position divisible by 188 */
newdma -= newdma % 188;
if (newdma >= budget->buffer_size)
return;
budget->ttbp = newdma;
if (budget->feeding == 0 || newdma == olddma)
return;
if (newdma > olddma) { /* no wraparound, dump olddma..newdma */
count = newdma - olddma;
dvb_dmx_swfilter_packets(&budget->demux, mem + olddma, count / 188);
} else { /* wraparound, dump olddma..buflen and 0..newdma */
count = budget->buffer_size - olddma;
dvb_dmx_swfilter_packets(&budget->demux, mem + olddma, count / 188);
count += newdma;
dvb_dmx_swfilter_packets(&budget->demux, mem, newdma / 188);
}
if (count > budget->buffer_warning_threshold)
budget->buffer_warnings++;
if (budget->buffer_warnings && time_after(jiffies, budget->buffer_warning_time)) {
printk("%s %s: used %d times >80%% of buffer (%u bytes now)\n",
budget->dev->name, __func__, budget->buffer_warnings, count);
budget->buffer_warning_time = jiffies + BUFFER_WARNING_WAIT;
budget->buffer_warnings = 0;
}
}
int ttpci_budget_debiread(struct budget *budget, u32 config, int addr, int count,
int uselocks, int nobusyloop)
{
struct saa7146_dev *saa = budget->dev;
int result = 0;
unsigned long flags = 0;
if (count > 4 || count <= 0)
return 0;
if (uselocks)
spin_lock_irqsave(&budget->debilock, flags);
if ((result = saa7146_wait_for_debi_done(saa, nobusyloop)) < 0) {
if (uselocks)
spin_unlock_irqrestore(&budget->debilock, flags);
return result;
}
saa7146_write(saa, DEBI_COMMAND, (count << 17) | 0x10000 | (addr & 0xffff));
saa7146_write(saa, DEBI_CONFIG, config);
saa7146_write(saa, DEBI_PAGE, 0);
saa7146_write(saa, MC2, (2 << 16) | 2);
if ((result = saa7146_wait_for_debi_done(saa, nobusyloop)) < 0) {
if (uselocks)
spin_unlock_irqrestore(&budget->debilock, flags);
return result;
}
result = saa7146_read(saa, DEBI_AD);
result &= (0xffffffffUL >> ((4 - count) * 8));
if (uselocks)
spin_unlock_irqrestore(&budget->debilock, flags);
return result;
}
int ttpci_budget_debiwrite(struct budget *budget, u32 config, int addr,
int count, u32 value, int uselocks, int nobusyloop)
{
struct saa7146_dev *saa = budget->dev;
unsigned long flags = 0;
int result;
if (count > 4 || count <= 0)
return 0;
if (uselocks)
spin_lock_irqsave(&budget->debilock, flags);
if ((result = saa7146_wait_for_debi_done(saa, nobusyloop)) < 0) {
if (uselocks)
spin_unlock_irqrestore(&budget->debilock, flags);
return result;
}
saa7146_write(saa, DEBI_COMMAND, (count << 17) | 0x00000 | (addr & 0xffff));
saa7146_write(saa, DEBI_CONFIG, config);
saa7146_write(saa, DEBI_PAGE, 0);
saa7146_write(saa, DEBI_AD, value);
saa7146_write(saa, MC2, (2 << 16) | 2);
if ((result = saa7146_wait_for_debi_done(saa, nobusyloop)) < 0) {
if (uselocks)
spin_unlock_irqrestore(&budget->debilock, flags);
return result;
}
if (uselocks)
spin_unlock_irqrestore(&budget->debilock, flags);
return 0;
}
/****************************************************************************
* DVB API SECTION
****************************************************************************/
static int budget_start_feed(struct dvb_demux_feed *feed)
{
struct dvb_demux *demux = feed->demux;
struct budget *budget = (struct budget *) demux->priv;
int status = 0;
dprintk(2, "budget: %p\n", budget);
if (!demux->dmx.frontend)
return -EINVAL;
spin_lock(&budget->feedlock);
feed->pusi_seen = 0; /* have a clean section start */
if (budget->feeding++ == 0)
status = start_ts_capture(budget);
spin_unlock(&budget->feedlock);
return status;
}
static int budget_stop_feed(struct dvb_demux_feed *feed)
{
struct dvb_demux *demux = feed->demux;
struct budget *budget = (struct budget *) demux->priv;
int status = 0;
dprintk(2, "budget: %p\n", budget);
spin_lock(&budget->feedlock);
if (--budget->feeding == 0)
status = stop_ts_capture(budget);
spin_unlock(&budget->feedlock);
return status;
}
static int budget_register(struct budget *budget)
{
struct dvb_demux *dvbdemux = &budget->demux;
int ret;
dprintk(2, "budget: %p\n", budget);
dvbdemux->priv = (void *) budget;
dvbdemux->filternum = 256;
dvbdemux->feednum = 256;
dvbdemux->start_feed = budget_start_feed;
dvbdemux->stop_feed = budget_stop_feed;
dvbdemux->write_to_decoder = NULL;
dvbdemux->dmx.capabilities = (DMX_TS_FILTERING | DMX_SECTION_FILTERING |
DMX_MEMORY_BASED_FILTERING);
dvb_dmx_init(&budget->demux);
budget->dmxdev.filternum = 256;
budget->dmxdev.demux = &dvbdemux->dmx;
budget->dmxdev.capabilities = 0;
dvb_dmxdev_init(&budget->dmxdev, &budget->dvb_adapter);
budget->hw_frontend.source = DMX_FRONTEND_0;
ret = dvbdemux->dmx.add_frontend(&dvbdemux->dmx, &budget->hw_frontend);
if (ret < 0)
return ret;
budget->mem_frontend.source = DMX_MEMORY_FE;
ret = dvbdemux->dmx.add_frontend(&dvbdemux->dmx, &budget->mem_frontend);
if (ret < 0)
return ret;
ret = dvbdemux->dmx.connect_frontend(&dvbdemux->dmx, &budget->hw_frontend);
if (ret < 0)
return ret;
dvb_net_init(&budget->dvb_adapter, &budget->dvb_net, &dvbdemux->dmx);
return 0;
}
static void budget_unregister(struct budget *budget)
{
struct dvb_demux *dvbdemux = &budget->demux;
dprintk(2, "budget: %p\n", budget);
dvb_net_release(&budget->dvb_net);
dvbdemux->dmx.close(&dvbdemux->dmx);
dvbdemux->dmx.remove_frontend(&dvbdemux->dmx, &budget->hw_frontend);
dvbdemux->dmx.remove_frontend(&dvbdemux->dmx, &budget->mem_frontend);
dvb_dmxdev_release(&budget->dmxdev);
dvb_dmx_release(&budget->demux);
}
int ttpci_budget_init(struct budget *budget, struct saa7146_dev *dev,
struct saa7146_pci_extension_data *info,
struct module *owner, short *adapter_nums)
{
int ret = 0;
struct budget_info *bi = info->ext_priv;
int max_bufsize;
int height_mask;
memset(budget, 0, sizeof(struct budget));
dprintk(2, "dev: %p, budget: %p\n", dev, budget);
budget->card = bi;
budget->dev = (struct saa7146_dev *) dev;
switch(budget->card->type) {
case BUDGET_FS_ACTIVY:
budget->buffer_width = TS_WIDTH_ACTIVY;
max_bufsize = TS_MAX_BUFSIZE_K_ACTIVY;
height_mask = TS_HEIGHT_MASK_ACTIVY;
break;
case BUDGET_KNC1C:
case BUDGET_KNC1CP:
case BUDGET_CIN1200C:
case BUDGET_KNC1C_MK3:
case BUDGET_KNC1CP_MK3:
case BUDGET_CIN1200C_MK3:
budget->buffer_width = TS_WIDTH_DVBC;
max_bufsize = TS_MAX_BUFSIZE_K_DVBC;
height_mask = TS_HEIGHT_MASK_DVBC;
break;
default:
budget->buffer_width = TS_WIDTH;
max_bufsize = TS_MAX_BUFSIZE_K;
height_mask = TS_HEIGHT_MASK;
}
if (dma_buffer_size < TS_MIN_BUFSIZE_K)
dma_buffer_size = TS_MIN_BUFSIZE_K;
else if (dma_buffer_size > max_bufsize)
dma_buffer_size = max_bufsize;
budget->buffer_height = dma_buffer_size * 1024 / budget->buffer_width;
if (budget->buffer_height > 0xfff) {
budget->buffer_height /= 2;
budget->buffer_height &= height_mask;
budget->buffer_size = 2 * budget->buffer_height * budget->buffer_width;
} else {
budget->buffer_height &= height_mask;
budget->buffer_size = budget->buffer_height * budget->buffer_width;
}
budget->buffer_warning_threshold = budget->buffer_size * 80/100;
budget->buffer_warnings = 0;
budget->buffer_warning_time = jiffies;
dprintk(2, "%s: buffer type = %s, width = %d, height = %d\n",
budget->dev->name,
budget->buffer_size > budget->buffer_width * budget->buffer_height ? "odd/even" : "single",
budget->buffer_width, budget->buffer_height);
printk("%s: dma buffer size %u\n", budget->dev->name, budget->buffer_size);
ret = dvb_register_adapter(&budget->dvb_adapter, budget->card->name,
owner, &budget->dev->pci->dev, adapter_nums);
if (ret < 0)
return ret;
/* set dd1 stream a & b */
saa7146_write(dev, DD1_STREAM_B, 0x00000000);
saa7146_write(dev, MC2, (MASK_09 | MASK_25));
saa7146_write(dev, MC2, (MASK_10 | MASK_26));
saa7146_write(dev, DD1_INIT, 0x02000000);
saa7146_write(dev, MC2, (MASK_09 | MASK_25 | MASK_10 | MASK_26));
if (bi->type != BUDGET_FS_ACTIVY)
budget->video_port = BUDGET_VIDEO_PORTB;
else
budget->video_port = BUDGET_VIDEO_PORTA;
spin_lock_init(&budget->feedlock);
spin_lock_init(&budget->debilock);
/* the Siemens DVB needs this if you want to have the i2c chips
get recognized before the main driver is loaded */
if (bi->type != BUDGET_FS_ACTIVY)
saa7146_write(dev, GPIO_CTRL, 0x500000); /* GPIO 3 = 1 */
budget->i2c_adap.class = I2C_CLASS_TV_DIGITAL;
strlcpy(budget->i2c_adap.name, budget->card->name, sizeof(budget->i2c_adap.name));
saa7146_i2c_adapter_prepare(dev, &budget->i2c_adap, SAA7146_I2C_BUS_BIT_RATE_120);
strcpy(budget->i2c_adap.name, budget->card->name);
if (i2c_add_adapter(&budget->i2c_adap) < 0) {
ret = -ENOMEM;
goto err_dvb_unregister;
}
ttpci_eeprom_parse_mac(&budget->i2c_adap, budget->dvb_adapter.proposed_mac);
budget->grabbing = saa7146_vmalloc_build_pgtable(dev->pci, budget->buffer_size, &budget->pt);
if (NULL == budget->grabbing) {
ret = -ENOMEM;
goto err_del_i2c;
}
saa7146_write(dev, PCI_BT_V1, 0x001c0000);
/* upload all */
saa7146_write(dev, GPIO_CTRL, 0x000000);
tasklet_init(&budget->vpe_tasklet, vpeirq, (unsigned long) budget);
/* frontend power on */
if (bi->type != BUDGET_FS_ACTIVY)
saa7146_setgpio(dev, 2, SAA7146_GPIO_OUTHI);
if ((ret = budget_register(budget)) == 0)
return 0; /* Everything OK */
/* An error occurred, cleanup resources */
saa7146_vfree_destroy_pgtable(dev->pci, budget->grabbing, &budget->pt);
err_del_i2c:
i2c_del_adapter(&budget->i2c_adap);
err_dvb_unregister:
dvb_unregister_adapter(&budget->dvb_adapter);
return ret;
}
void ttpci_budget_init_hooks(struct budget *budget)
{
if (budget->dvb_frontend && !budget->read_fe_status) {
budget->read_fe_status = budget->dvb_frontend->ops.read_status;
budget->dvb_frontend->ops.read_status = budget_read_fe_status;
}
}
int ttpci_budget_deinit(struct budget *budget)
{
struct saa7146_dev *dev = budget->dev;
dprintk(2, "budget: %p\n", budget);
budget_unregister(budget);
tasklet_kill(&budget->vpe_tasklet);
saa7146_vfree_destroy_pgtable(dev->pci, budget->grabbing, &budget->pt);
i2c_del_adapter(&budget->i2c_adap);
dvb_unregister_adapter(&budget->dvb_adapter);
return 0;
}
void ttpci_budget_irq10_handler(struct saa7146_dev *dev, u32 * isr)
{
struct budget *budget = (struct budget *) dev->ext_priv;
dprintk(8, "dev: %p, budget: %p\n", dev, budget);
if (*isr & MASK_10)
tasklet_schedule(&budget->vpe_tasklet);
}
void ttpci_budget_set_video_port(struct saa7146_dev *dev, int video_port)
{
struct budget *budget = (struct budget *) dev->ext_priv;
spin_lock(&budget->feedlock);
budget->video_port = video_port;
if (budget->feeding) {
stop_ts_capture(budget);
start_ts_capture(budget);
}
spin_unlock(&budget->feedlock);
}
EXPORT_SYMBOL_GPL(ttpci_budget_debiread);
EXPORT_SYMBOL_GPL(ttpci_budget_debiwrite);
EXPORT_SYMBOL_GPL(ttpci_budget_init);
EXPORT_SYMBOL_GPL(ttpci_budget_init_hooks);
EXPORT_SYMBOL_GPL(ttpci_budget_deinit);
EXPORT_SYMBOL_GPL(ttpci_budget_irq10_handler);
EXPORT_SYMBOL_GPL(ttpci_budget_set_video_port);
EXPORT_SYMBOL_GPL(budget_debug);
MODULE_LICENSE("GPL");
| gpl-2.0 |
Ryuinferno/Blazing_Kernel_t1 | drivers/gpu/drm/ttm/ttm_bo_util.c | 1919 | 16872 | /**************************************************************************
*
* Copyright (c) 2007-2009 VMware, Inc., Palo Alto, CA., 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.
*
**************************************************************************/
/*
* Authors: Thomas Hellstrom <thellstrom-at-vmware-dot-com>
*/
#include "ttm/ttm_bo_driver.h"
#include "ttm/ttm_placement.h"
#include <linux/io.h>
#include <linux/highmem.h>
#include <linux/wait.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/module.h>
void ttm_bo_free_old_node(struct ttm_buffer_object *bo)
{
ttm_bo_mem_put(bo, &bo->mem);
}
int ttm_bo_move_ttm(struct ttm_buffer_object *bo,
bool evict, bool no_wait_reserve,
bool no_wait_gpu, struct ttm_mem_reg *new_mem)
{
struct ttm_tt *ttm = bo->ttm;
struct ttm_mem_reg *old_mem = &bo->mem;
int ret;
if (old_mem->mem_type != TTM_PL_SYSTEM) {
ttm_tt_unbind(ttm);
ttm_bo_free_old_node(bo);
ttm_flag_masked(&old_mem->placement, TTM_PL_FLAG_SYSTEM,
TTM_PL_MASK_MEM);
old_mem->mem_type = TTM_PL_SYSTEM;
}
ret = ttm_tt_set_placement_caching(ttm, new_mem->placement);
if (unlikely(ret != 0))
return ret;
if (new_mem->mem_type != TTM_PL_SYSTEM) {
ret = ttm_tt_bind(ttm, new_mem);
if (unlikely(ret != 0))
return ret;
}
*old_mem = *new_mem;
new_mem->mm_node = NULL;
return 0;
}
EXPORT_SYMBOL(ttm_bo_move_ttm);
int ttm_mem_io_lock(struct ttm_mem_type_manager *man, bool interruptible)
{
if (likely(man->io_reserve_fastpath))
return 0;
if (interruptible)
return mutex_lock_interruptible(&man->io_reserve_mutex);
mutex_lock(&man->io_reserve_mutex);
return 0;
}
void ttm_mem_io_unlock(struct ttm_mem_type_manager *man)
{
if (likely(man->io_reserve_fastpath))
return;
mutex_unlock(&man->io_reserve_mutex);
}
static int ttm_mem_io_evict(struct ttm_mem_type_manager *man)
{
struct ttm_buffer_object *bo;
if (!man->use_io_reserve_lru || list_empty(&man->io_reserve_lru))
return -EAGAIN;
bo = list_first_entry(&man->io_reserve_lru,
struct ttm_buffer_object,
io_reserve_lru);
list_del_init(&bo->io_reserve_lru);
ttm_bo_unmap_virtual_locked(bo);
return 0;
}
static int ttm_mem_io_reserve(struct ttm_bo_device *bdev,
struct ttm_mem_reg *mem)
{
struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
int ret = 0;
if (!bdev->driver->io_mem_reserve)
return 0;
if (likely(man->io_reserve_fastpath))
return bdev->driver->io_mem_reserve(bdev, mem);
if (bdev->driver->io_mem_reserve &&
mem->bus.io_reserved_count++ == 0) {
retry:
ret = bdev->driver->io_mem_reserve(bdev, mem);
if (ret == -EAGAIN) {
ret = ttm_mem_io_evict(man);
if (ret == 0)
goto retry;
}
}
return ret;
}
static void ttm_mem_io_free(struct ttm_bo_device *bdev,
struct ttm_mem_reg *mem)
{
struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
if (likely(man->io_reserve_fastpath))
return;
if (bdev->driver->io_mem_reserve &&
--mem->bus.io_reserved_count == 0 &&
bdev->driver->io_mem_free)
bdev->driver->io_mem_free(bdev, mem);
}
int ttm_mem_io_reserve_vm(struct ttm_buffer_object *bo)
{
struct ttm_mem_reg *mem = &bo->mem;
int ret;
if (!mem->bus.io_reserved_vm) {
struct ttm_mem_type_manager *man =
&bo->bdev->man[mem->mem_type];
ret = ttm_mem_io_reserve(bo->bdev, mem);
if (unlikely(ret != 0))
return ret;
mem->bus.io_reserved_vm = true;
if (man->use_io_reserve_lru)
list_add_tail(&bo->io_reserve_lru,
&man->io_reserve_lru);
}
return 0;
}
void ttm_mem_io_free_vm(struct ttm_buffer_object *bo)
{
struct ttm_mem_reg *mem = &bo->mem;
if (mem->bus.io_reserved_vm) {
mem->bus.io_reserved_vm = false;
list_del_init(&bo->io_reserve_lru);
ttm_mem_io_free(bo->bdev, mem);
}
}
int ttm_mem_reg_ioremap(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem,
void **virtual)
{
struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
int ret;
void *addr;
*virtual = NULL;
(void) ttm_mem_io_lock(man, false);
ret = ttm_mem_io_reserve(bdev, mem);
ttm_mem_io_unlock(man);
if (ret || !mem->bus.is_iomem)
return ret;
if (mem->bus.addr) {
addr = mem->bus.addr;
} else {
if (mem->placement & TTM_PL_FLAG_WC)
addr = ioremap_wc(mem->bus.base + mem->bus.offset, mem->bus.size);
else
addr = ioremap_nocache(mem->bus.base + mem->bus.offset, mem->bus.size);
if (!addr) {
(void) ttm_mem_io_lock(man, false);
ttm_mem_io_free(bdev, mem);
ttm_mem_io_unlock(man);
return -ENOMEM;
}
}
*virtual = addr;
return 0;
}
void ttm_mem_reg_iounmap(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem,
void *virtual)
{
struct ttm_mem_type_manager *man;
man = &bdev->man[mem->mem_type];
if (virtual && mem->bus.addr == NULL)
iounmap(virtual);
(void) ttm_mem_io_lock(man, false);
ttm_mem_io_free(bdev, mem);
ttm_mem_io_unlock(man);
}
static int ttm_copy_io_page(void *dst, void *src, unsigned long page)
{
uint32_t *dstP =
(uint32_t *) ((unsigned long)dst + (page << PAGE_SHIFT));
uint32_t *srcP =
(uint32_t *) ((unsigned long)src + (page << PAGE_SHIFT));
int i;
for (i = 0; i < PAGE_SIZE / sizeof(uint32_t); ++i)
iowrite32(ioread32(srcP++), dstP++);
return 0;
}
static int ttm_copy_io_ttm_page(struct ttm_tt *ttm, void *src,
unsigned long page,
pgprot_t prot)
{
struct page *d = ttm_tt_get_page(ttm, page);
void *dst;
if (!d)
return -ENOMEM;
src = (void *)((unsigned long)src + (page << PAGE_SHIFT));
#ifdef CONFIG_X86
dst = kmap_atomic_prot(d, prot);
#else
if (pgprot_val(prot) != pgprot_val(PAGE_KERNEL))
dst = vmap(&d, 1, 0, prot);
else
dst = kmap(d);
#endif
if (!dst)
return -ENOMEM;
memcpy_fromio(dst, src, PAGE_SIZE);
#ifdef CONFIG_X86
kunmap_atomic(dst);
#else
if (pgprot_val(prot) != pgprot_val(PAGE_KERNEL))
vunmap(dst);
else
kunmap(d);
#endif
return 0;
}
static int ttm_copy_ttm_io_page(struct ttm_tt *ttm, void *dst,
unsigned long page,
pgprot_t prot)
{
struct page *s = ttm_tt_get_page(ttm, page);
void *src;
if (!s)
return -ENOMEM;
dst = (void *)((unsigned long)dst + (page << PAGE_SHIFT));
#ifdef CONFIG_X86
src = kmap_atomic_prot(s, prot);
#else
if (pgprot_val(prot) != pgprot_val(PAGE_KERNEL))
src = vmap(&s, 1, 0, prot);
else
src = kmap(s);
#endif
if (!src)
return -ENOMEM;
memcpy_toio(dst, src, PAGE_SIZE);
#ifdef CONFIG_X86
kunmap_atomic(src);
#else
if (pgprot_val(prot) != pgprot_val(PAGE_KERNEL))
vunmap(src);
else
kunmap(s);
#endif
return 0;
}
int ttm_bo_move_memcpy(struct ttm_buffer_object *bo,
bool evict, bool no_wait_reserve, bool no_wait_gpu,
struct ttm_mem_reg *new_mem)
{
struct ttm_bo_device *bdev = bo->bdev;
struct ttm_mem_type_manager *man = &bdev->man[new_mem->mem_type];
struct ttm_tt *ttm = bo->ttm;
struct ttm_mem_reg *old_mem = &bo->mem;
struct ttm_mem_reg old_copy;
void *old_iomap;
void *new_iomap;
int ret;
unsigned long i;
unsigned long page;
unsigned long add = 0;
int dir;
ret = ttm_mem_reg_ioremap(bdev, old_mem, &old_iomap);
if (ret)
return ret;
ret = ttm_mem_reg_ioremap(bdev, new_mem, &new_iomap);
if (ret)
goto out;
if (old_iomap == NULL && new_iomap == NULL)
goto out2;
if (old_iomap == NULL && ttm == NULL)
goto out2;
add = 0;
dir = 1;
if ((old_mem->mem_type == new_mem->mem_type) &&
(new_mem->start < old_mem->start + old_mem->size)) {
dir = -1;
add = new_mem->num_pages - 1;
}
for (i = 0; i < new_mem->num_pages; ++i) {
page = i * dir + add;
if (old_iomap == NULL) {
pgprot_t prot = ttm_io_prot(old_mem->placement,
PAGE_KERNEL);
ret = ttm_copy_ttm_io_page(ttm, new_iomap, page,
prot);
} else if (new_iomap == NULL) {
pgprot_t prot = ttm_io_prot(new_mem->placement,
PAGE_KERNEL);
ret = ttm_copy_io_ttm_page(ttm, old_iomap, page,
prot);
} else
ret = ttm_copy_io_page(new_iomap, old_iomap, page);
if (ret)
goto out1;
}
mb();
out2:
old_copy = *old_mem;
*old_mem = *new_mem;
new_mem->mm_node = NULL;
if ((man->flags & TTM_MEMTYPE_FLAG_FIXED) && (ttm != NULL)) {
ttm_tt_unbind(ttm);
ttm_tt_destroy(ttm);
bo->ttm = NULL;
}
out1:
ttm_mem_reg_iounmap(bdev, old_mem, new_iomap);
out:
ttm_mem_reg_iounmap(bdev, &old_copy, old_iomap);
ttm_bo_mem_put(bo, &old_copy);
return ret;
}
EXPORT_SYMBOL(ttm_bo_move_memcpy);
static void ttm_transfered_destroy(struct ttm_buffer_object *bo)
{
kfree(bo);
}
/**
* ttm_buffer_object_transfer
*
* @bo: A pointer to a struct ttm_buffer_object.
* @new_obj: A pointer to a pointer to a newly created ttm_buffer_object,
* holding the data of @bo with the old placement.
*
* This is a utility function that may be called after an accelerated move
* has been scheduled. A new buffer object is created as a placeholder for
* the old data while it's being copied. When that buffer object is idle,
* it can be destroyed, releasing the space of the old placement.
* Returns:
* !0: Failure.
*/
static int ttm_buffer_object_transfer(struct ttm_buffer_object *bo,
struct ttm_buffer_object **new_obj)
{
struct ttm_buffer_object *fbo;
struct ttm_bo_device *bdev = bo->bdev;
struct ttm_bo_driver *driver = bdev->driver;
fbo = kzalloc(sizeof(*fbo), GFP_KERNEL);
if (!fbo)
return -ENOMEM;
*fbo = *bo;
/**
* Fix up members that we shouldn't copy directly:
* TODO: Explicit member copy would probably be better here.
*/
init_waitqueue_head(&fbo->event_queue);
INIT_LIST_HEAD(&fbo->ddestroy);
INIT_LIST_HEAD(&fbo->lru);
INIT_LIST_HEAD(&fbo->swap);
INIT_LIST_HEAD(&fbo->io_reserve_lru);
fbo->vm_node = NULL;
atomic_set(&fbo->cpu_writers, 0);
fbo->sync_obj = driver->sync_obj_ref(bo->sync_obj);
kref_init(&fbo->list_kref);
kref_init(&fbo->kref);
fbo->destroy = &ttm_transfered_destroy;
*new_obj = fbo;
return 0;
}
pgprot_t ttm_io_prot(uint32_t caching_flags, pgprot_t tmp)
{
#if defined(__i386__) || defined(__x86_64__)
if (caching_flags & TTM_PL_FLAG_WC)
tmp = pgprot_writecombine(tmp);
else if (boot_cpu_data.x86 > 3)
tmp = pgprot_noncached(tmp);
#elif defined(__powerpc__)
if (!(caching_flags & TTM_PL_FLAG_CACHED)) {
pgprot_val(tmp) |= _PAGE_NO_CACHE;
if (caching_flags & TTM_PL_FLAG_UNCACHED)
pgprot_val(tmp) |= _PAGE_GUARDED;
}
#endif
#if defined(__ia64__)
if (caching_flags & TTM_PL_FLAG_WC)
tmp = pgprot_writecombine(tmp);
else
tmp = pgprot_noncached(tmp);
#endif
#if defined(__sparc__)
if (!(caching_flags & TTM_PL_FLAG_CACHED))
tmp = pgprot_noncached(tmp);
#endif
return tmp;
}
EXPORT_SYMBOL(ttm_io_prot);
static int ttm_bo_ioremap(struct ttm_buffer_object *bo,
unsigned long offset,
unsigned long size,
struct ttm_bo_kmap_obj *map)
{
struct ttm_mem_reg *mem = &bo->mem;
if (bo->mem.bus.addr) {
map->bo_kmap_type = ttm_bo_map_premapped;
map->virtual = (void *)(((u8 *)bo->mem.bus.addr) + offset);
} else {
map->bo_kmap_type = ttm_bo_map_iomap;
if (mem->placement & TTM_PL_FLAG_WC)
map->virtual = ioremap_wc(bo->mem.bus.base + bo->mem.bus.offset + offset,
size);
else
map->virtual = ioremap_nocache(bo->mem.bus.base + bo->mem.bus.offset + offset,
size);
}
return (!map->virtual) ? -ENOMEM : 0;
}
static int ttm_bo_kmap_ttm(struct ttm_buffer_object *bo,
unsigned long start_page,
unsigned long num_pages,
struct ttm_bo_kmap_obj *map)
{
struct ttm_mem_reg *mem = &bo->mem; pgprot_t prot;
struct ttm_tt *ttm = bo->ttm;
struct page *d;
int i;
BUG_ON(!ttm);
if (num_pages == 1 && (mem->placement & TTM_PL_FLAG_CACHED)) {
/*
* We're mapping a single page, and the desired
* page protection is consistent with the bo.
*/
map->bo_kmap_type = ttm_bo_map_kmap;
map->page = ttm_tt_get_page(ttm, start_page);
map->virtual = kmap(map->page);
} else {
/*
* Populate the part we're mapping;
*/
for (i = start_page; i < start_page + num_pages; ++i) {
d = ttm_tt_get_page(ttm, i);
if (!d)
return -ENOMEM;
}
/*
* We need to use vmap to get the desired page protection
* or to make the buffer object look contiguous.
*/
prot = (mem->placement & TTM_PL_FLAG_CACHED) ?
PAGE_KERNEL :
ttm_io_prot(mem->placement, PAGE_KERNEL);
map->bo_kmap_type = ttm_bo_map_vmap;
map->virtual = vmap(ttm->pages + start_page, num_pages,
0, prot);
}
return (!map->virtual) ? -ENOMEM : 0;
}
int ttm_bo_kmap(struct ttm_buffer_object *bo,
unsigned long start_page, unsigned long num_pages,
struct ttm_bo_kmap_obj *map)
{
struct ttm_mem_type_manager *man =
&bo->bdev->man[bo->mem.mem_type];
unsigned long offset, size;
int ret;
BUG_ON(!list_empty(&bo->swap));
map->virtual = NULL;
map->bo = bo;
if (num_pages > bo->num_pages)
return -EINVAL;
if (start_page > bo->num_pages)
return -EINVAL;
#if 0
if (num_pages > 1 && !DRM_SUSER(DRM_CURPROC))
return -EPERM;
#endif
(void) ttm_mem_io_lock(man, false);
ret = ttm_mem_io_reserve(bo->bdev, &bo->mem);
ttm_mem_io_unlock(man);
if (ret)
return ret;
if (!bo->mem.bus.is_iomem) {
return ttm_bo_kmap_ttm(bo, start_page, num_pages, map);
} else {
offset = start_page << PAGE_SHIFT;
size = num_pages << PAGE_SHIFT;
return ttm_bo_ioremap(bo, offset, size, map);
}
}
EXPORT_SYMBOL(ttm_bo_kmap);
void ttm_bo_kunmap(struct ttm_bo_kmap_obj *map)
{
struct ttm_buffer_object *bo = map->bo;
struct ttm_mem_type_manager *man =
&bo->bdev->man[bo->mem.mem_type];
if (!map->virtual)
return;
switch (map->bo_kmap_type) {
case ttm_bo_map_iomap:
iounmap(map->virtual);
break;
case ttm_bo_map_vmap:
vunmap(map->virtual);
break;
case ttm_bo_map_kmap:
kunmap(map->page);
break;
case ttm_bo_map_premapped:
break;
default:
BUG();
}
(void) ttm_mem_io_lock(man, false);
ttm_mem_io_free(map->bo->bdev, &map->bo->mem);
ttm_mem_io_unlock(man);
map->virtual = NULL;
map->page = NULL;
}
EXPORT_SYMBOL(ttm_bo_kunmap);
int ttm_bo_move_accel_cleanup(struct ttm_buffer_object *bo,
void *sync_obj,
void *sync_obj_arg,
bool evict, bool no_wait_reserve,
bool no_wait_gpu,
struct ttm_mem_reg *new_mem)
{
struct ttm_bo_device *bdev = bo->bdev;
struct ttm_bo_driver *driver = bdev->driver;
struct ttm_mem_type_manager *man = &bdev->man[new_mem->mem_type];
struct ttm_mem_reg *old_mem = &bo->mem;
int ret;
struct ttm_buffer_object *ghost_obj;
void *tmp_obj = NULL;
spin_lock(&bdev->fence_lock);
if (bo->sync_obj) {
tmp_obj = bo->sync_obj;
bo->sync_obj = NULL;
}
bo->sync_obj = driver->sync_obj_ref(sync_obj);
bo->sync_obj_arg = sync_obj_arg;
if (evict) {
ret = ttm_bo_wait(bo, false, false, false);
spin_unlock(&bdev->fence_lock);
if (tmp_obj)
driver->sync_obj_unref(&tmp_obj);
if (ret)
return ret;
if ((man->flags & TTM_MEMTYPE_FLAG_FIXED) &&
(bo->ttm != NULL)) {
ttm_tt_unbind(bo->ttm);
ttm_tt_destroy(bo->ttm);
bo->ttm = NULL;
}
ttm_bo_free_old_node(bo);
} else {
/**
* This should help pipeline ordinary buffer moves.
*
* Hang old buffer memory on a new buffer object,
* and leave it to be released when the GPU
* operation has completed.
*/
set_bit(TTM_BO_PRIV_FLAG_MOVING, &bo->priv_flags);
spin_unlock(&bdev->fence_lock);
if (tmp_obj)
driver->sync_obj_unref(&tmp_obj);
ret = ttm_buffer_object_transfer(bo, &ghost_obj);
if (ret)
return ret;
/**
* If we're not moving to fixed memory, the TTM object
* needs to stay alive. Otherwhise hang it on the ghost
* bo to be unbound and destroyed.
*/
if (!(man->flags & TTM_MEMTYPE_FLAG_FIXED))
ghost_obj->ttm = NULL;
else
bo->ttm = NULL;
ttm_bo_unreserve(ghost_obj);
ttm_bo_unref(&ghost_obj);
}
*old_mem = *new_mem;
new_mem->mm_node = NULL;
return 0;
}
EXPORT_SYMBOL(ttm_bo_move_accel_cleanup);
| gpl-2.0 |
CalcProgrammer1/ubuntu-kernel-quincyatt | drivers/infiniband/hw/cxgb4/resource.c | 2687 | 12609 | /*
* Copyright (c) 2009-2010 Chelsio, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/* Crude resource management */
#include <linux/kernel.h>
#include <linux/random.h>
#include <linux/slab.h>
#include <linux/kfifo.h>
#include <linux/spinlock.h>
#include <linux/errno.h>
#include <linux/genalloc.h>
#include "iw_cxgb4.h"
#define RANDOM_SIZE 16
static int __c4iw_init_resource_fifo(struct kfifo *fifo,
spinlock_t *fifo_lock,
u32 nr, u32 skip_low,
u32 skip_high,
int random)
{
u32 i, j, entry = 0, idx;
u32 random_bytes;
u32 rarray[16];
spin_lock_init(fifo_lock);
if (kfifo_alloc(fifo, nr * sizeof(u32), GFP_KERNEL))
return -ENOMEM;
for (i = 0; i < skip_low + skip_high; i++)
kfifo_in(fifo, (unsigned char *) &entry, sizeof(u32));
if (random) {
j = 0;
random_bytes = random32();
for (i = 0; i < RANDOM_SIZE; i++)
rarray[i] = i + skip_low;
for (i = skip_low + RANDOM_SIZE; i < nr - skip_high; i++) {
if (j >= RANDOM_SIZE) {
j = 0;
random_bytes = random32();
}
idx = (random_bytes >> (j * 2)) & 0xF;
kfifo_in(fifo,
(unsigned char *) &rarray[idx],
sizeof(u32));
rarray[idx] = i;
j++;
}
for (i = 0; i < RANDOM_SIZE; i++)
kfifo_in(fifo,
(unsigned char *) &rarray[i],
sizeof(u32));
} else
for (i = skip_low; i < nr - skip_high; i++)
kfifo_in(fifo, (unsigned char *) &i, sizeof(u32));
for (i = 0; i < skip_low + skip_high; i++)
if (kfifo_out_locked(fifo, (unsigned char *) &entry,
sizeof(u32), fifo_lock))
break;
return 0;
}
static int c4iw_init_resource_fifo(struct kfifo *fifo, spinlock_t * fifo_lock,
u32 nr, u32 skip_low, u32 skip_high)
{
return __c4iw_init_resource_fifo(fifo, fifo_lock, nr, skip_low,
skip_high, 0);
}
static int c4iw_init_resource_fifo_random(struct kfifo *fifo,
spinlock_t *fifo_lock,
u32 nr, u32 skip_low, u32 skip_high)
{
return __c4iw_init_resource_fifo(fifo, fifo_lock, nr, skip_low,
skip_high, 1);
}
static int c4iw_init_qid_fifo(struct c4iw_rdev *rdev)
{
u32 i;
spin_lock_init(&rdev->resource.qid_fifo_lock);
if (kfifo_alloc(&rdev->resource.qid_fifo, rdev->lldi.vr->qp.size *
sizeof(u32), GFP_KERNEL))
return -ENOMEM;
for (i = rdev->lldi.vr->qp.start;
i < rdev->lldi.vr->qp.start + rdev->lldi.vr->qp.size; i++)
if (!(i & rdev->qpmask))
kfifo_in(&rdev->resource.qid_fifo,
(unsigned char *) &i, sizeof(u32));
return 0;
}
/* nr_* must be power of 2 */
int c4iw_init_resource(struct c4iw_rdev *rdev, u32 nr_tpt, u32 nr_pdid)
{
int err = 0;
err = c4iw_init_resource_fifo_random(&rdev->resource.tpt_fifo,
&rdev->resource.tpt_fifo_lock,
nr_tpt, 1, 0);
if (err)
goto tpt_err;
err = c4iw_init_qid_fifo(rdev);
if (err)
goto qid_err;
err = c4iw_init_resource_fifo(&rdev->resource.pdid_fifo,
&rdev->resource.pdid_fifo_lock,
nr_pdid, 1, 0);
if (err)
goto pdid_err;
return 0;
pdid_err:
kfifo_free(&rdev->resource.qid_fifo);
qid_err:
kfifo_free(&rdev->resource.tpt_fifo);
tpt_err:
return -ENOMEM;
}
/*
* returns 0 if no resource available
*/
u32 c4iw_get_resource(struct kfifo *fifo, spinlock_t *lock)
{
u32 entry;
if (kfifo_out_locked(fifo, (unsigned char *) &entry, sizeof(u32), lock))
return entry;
else
return 0;
}
void c4iw_put_resource(struct kfifo *fifo, u32 entry, spinlock_t *lock)
{
PDBG("%s entry 0x%x\n", __func__, entry);
kfifo_in_locked(fifo, (unsigned char *) &entry, sizeof(u32), lock);
}
u32 c4iw_get_cqid(struct c4iw_rdev *rdev, struct c4iw_dev_ucontext *uctx)
{
struct c4iw_qid_list *entry;
u32 qid;
int i;
mutex_lock(&uctx->lock);
if (!list_empty(&uctx->cqids)) {
entry = list_entry(uctx->cqids.next, struct c4iw_qid_list,
entry);
list_del(&entry->entry);
qid = entry->qid;
kfree(entry);
} else {
qid = c4iw_get_resource(&rdev->resource.qid_fifo,
&rdev->resource.qid_fifo_lock);
if (!qid)
goto out;
for (i = qid+1; i & rdev->qpmask; i++) {
entry = kmalloc(sizeof *entry, GFP_KERNEL);
if (!entry)
goto out;
entry->qid = i;
list_add_tail(&entry->entry, &uctx->cqids);
}
/*
* now put the same ids on the qp list since they all
* map to the same db/gts page.
*/
entry = kmalloc(sizeof *entry, GFP_KERNEL);
if (!entry)
goto out;
entry->qid = qid;
list_add_tail(&entry->entry, &uctx->qpids);
for (i = qid+1; i & rdev->qpmask; i++) {
entry = kmalloc(sizeof *entry, GFP_KERNEL);
if (!entry)
goto out;
entry->qid = i;
list_add_tail(&entry->entry, &uctx->qpids);
}
}
out:
mutex_unlock(&uctx->lock);
PDBG("%s qid 0x%x\n", __func__, qid);
return qid;
}
void c4iw_put_cqid(struct c4iw_rdev *rdev, u32 qid,
struct c4iw_dev_ucontext *uctx)
{
struct c4iw_qid_list *entry;
entry = kmalloc(sizeof *entry, GFP_KERNEL);
if (!entry)
return;
PDBG("%s qid 0x%x\n", __func__, qid);
entry->qid = qid;
mutex_lock(&uctx->lock);
list_add_tail(&entry->entry, &uctx->cqids);
mutex_unlock(&uctx->lock);
}
u32 c4iw_get_qpid(struct c4iw_rdev *rdev, struct c4iw_dev_ucontext *uctx)
{
struct c4iw_qid_list *entry;
u32 qid;
int i;
mutex_lock(&uctx->lock);
if (!list_empty(&uctx->qpids)) {
entry = list_entry(uctx->qpids.next, struct c4iw_qid_list,
entry);
list_del(&entry->entry);
qid = entry->qid;
kfree(entry);
} else {
qid = c4iw_get_resource(&rdev->resource.qid_fifo,
&rdev->resource.qid_fifo_lock);
if (!qid)
goto out;
for (i = qid+1; i & rdev->qpmask; i++) {
entry = kmalloc(sizeof *entry, GFP_KERNEL);
if (!entry)
goto out;
entry->qid = i;
list_add_tail(&entry->entry, &uctx->qpids);
}
/*
* now put the same ids on the cq list since they all
* map to the same db/gts page.
*/
entry = kmalloc(sizeof *entry, GFP_KERNEL);
if (!entry)
goto out;
entry->qid = qid;
list_add_tail(&entry->entry, &uctx->cqids);
for (i = qid; i & rdev->qpmask; i++) {
entry = kmalloc(sizeof *entry, GFP_KERNEL);
if (!entry)
goto out;
entry->qid = i;
list_add_tail(&entry->entry, &uctx->cqids);
}
}
out:
mutex_unlock(&uctx->lock);
PDBG("%s qid 0x%x\n", __func__, qid);
return qid;
}
void c4iw_put_qpid(struct c4iw_rdev *rdev, u32 qid,
struct c4iw_dev_ucontext *uctx)
{
struct c4iw_qid_list *entry;
entry = kmalloc(sizeof *entry, GFP_KERNEL);
if (!entry)
return;
PDBG("%s qid 0x%x\n", __func__, qid);
entry->qid = qid;
mutex_lock(&uctx->lock);
list_add_tail(&entry->entry, &uctx->qpids);
mutex_unlock(&uctx->lock);
}
void c4iw_destroy_resource(struct c4iw_resource *rscp)
{
kfifo_free(&rscp->tpt_fifo);
kfifo_free(&rscp->qid_fifo);
kfifo_free(&rscp->pdid_fifo);
}
/*
* PBL Memory Manager. Uses Linux generic allocator.
*/
#define MIN_PBL_SHIFT 8 /* 256B == min PBL size (32 entries) */
u32 c4iw_pblpool_alloc(struct c4iw_rdev *rdev, int size)
{
unsigned long addr = gen_pool_alloc(rdev->pbl_pool, size);
PDBG("%s addr 0x%x size %d\n", __func__, (u32)addr, size);
if (!addr && printk_ratelimit())
printk(KERN_WARNING MOD "%s: Out of PBL memory\n",
pci_name(rdev->lldi.pdev));
return (u32)addr;
}
void c4iw_pblpool_free(struct c4iw_rdev *rdev, u32 addr, int size)
{
PDBG("%s addr 0x%x size %d\n", __func__, addr, size);
gen_pool_free(rdev->pbl_pool, (unsigned long)addr, size);
}
int c4iw_pblpool_create(struct c4iw_rdev *rdev)
{
unsigned pbl_start, pbl_chunk, pbl_top;
rdev->pbl_pool = gen_pool_create(MIN_PBL_SHIFT, -1);
if (!rdev->pbl_pool)
return -ENOMEM;
pbl_start = rdev->lldi.vr->pbl.start;
pbl_chunk = rdev->lldi.vr->pbl.size;
pbl_top = pbl_start + pbl_chunk;
while (pbl_start < pbl_top) {
pbl_chunk = min(pbl_top - pbl_start + 1, pbl_chunk);
if (gen_pool_add(rdev->pbl_pool, pbl_start, pbl_chunk, -1)) {
PDBG("%s failed to add PBL chunk (%x/%x)\n",
__func__, pbl_start, pbl_chunk);
if (pbl_chunk <= 1024 << MIN_PBL_SHIFT) {
printk(KERN_WARNING MOD
"Failed to add all PBL chunks (%x/%x)\n",
pbl_start,
pbl_top - pbl_start);
return 0;
}
pbl_chunk >>= 1;
} else {
PDBG("%s added PBL chunk (%x/%x)\n",
__func__, pbl_start, pbl_chunk);
pbl_start += pbl_chunk;
}
}
return 0;
}
void c4iw_pblpool_destroy(struct c4iw_rdev *rdev)
{
gen_pool_destroy(rdev->pbl_pool);
}
/*
* RQT Memory Manager. Uses Linux generic allocator.
*/
#define MIN_RQT_SHIFT 10 /* 1KB == min RQT size (16 entries) */
u32 c4iw_rqtpool_alloc(struct c4iw_rdev *rdev, int size)
{
unsigned long addr = gen_pool_alloc(rdev->rqt_pool, size << 6);
PDBG("%s addr 0x%x size %d\n", __func__, (u32)addr, size << 6);
if (!addr && printk_ratelimit())
printk(KERN_WARNING MOD "%s: Out of RQT memory\n",
pci_name(rdev->lldi.pdev));
return (u32)addr;
}
void c4iw_rqtpool_free(struct c4iw_rdev *rdev, u32 addr, int size)
{
PDBG("%s addr 0x%x size %d\n", __func__, addr, size << 6);
gen_pool_free(rdev->rqt_pool, (unsigned long)addr, size << 6);
}
int c4iw_rqtpool_create(struct c4iw_rdev *rdev)
{
unsigned rqt_start, rqt_chunk, rqt_top;
rdev->rqt_pool = gen_pool_create(MIN_RQT_SHIFT, -1);
if (!rdev->rqt_pool)
return -ENOMEM;
rqt_start = rdev->lldi.vr->rq.start;
rqt_chunk = rdev->lldi.vr->rq.size;
rqt_top = rqt_start + rqt_chunk;
while (rqt_start < rqt_top) {
rqt_chunk = min(rqt_top - rqt_start + 1, rqt_chunk);
if (gen_pool_add(rdev->rqt_pool, rqt_start, rqt_chunk, -1)) {
PDBG("%s failed to add RQT chunk (%x/%x)\n",
__func__, rqt_start, rqt_chunk);
if (rqt_chunk <= 1024 << MIN_RQT_SHIFT) {
printk(KERN_WARNING MOD
"Failed to add all RQT chunks (%x/%x)\n",
rqt_start, rqt_top - rqt_start);
return 0;
}
rqt_chunk >>= 1;
} else {
PDBG("%s added RQT chunk (%x/%x)\n",
__func__, rqt_start, rqt_chunk);
rqt_start += rqt_chunk;
}
}
return 0;
}
void c4iw_rqtpool_destroy(struct c4iw_rdev *rdev)
{
gen_pool_destroy(rdev->rqt_pool);
}
/*
* On-Chip QP Memory.
*/
#define MIN_OCQP_SHIFT 12 /* 4KB == min ocqp size */
u32 c4iw_ocqp_pool_alloc(struct c4iw_rdev *rdev, int size)
{
unsigned long addr = gen_pool_alloc(rdev->ocqp_pool, size);
PDBG("%s addr 0x%x size %d\n", __func__, (u32)addr, size);
return (u32)addr;
}
void c4iw_ocqp_pool_free(struct c4iw_rdev *rdev, u32 addr, int size)
{
PDBG("%s addr 0x%x size %d\n", __func__, addr, size);
gen_pool_free(rdev->ocqp_pool, (unsigned long)addr, size);
}
int c4iw_ocqp_pool_create(struct c4iw_rdev *rdev)
{
unsigned start, chunk, top;
rdev->ocqp_pool = gen_pool_create(MIN_OCQP_SHIFT, -1);
if (!rdev->ocqp_pool)
return -ENOMEM;
start = rdev->lldi.vr->ocq.start;
chunk = rdev->lldi.vr->ocq.size;
top = start + chunk;
while (start < top) {
chunk = min(top - start + 1, chunk);
if (gen_pool_add(rdev->ocqp_pool, start, chunk, -1)) {
PDBG("%s failed to add OCQP chunk (%x/%x)\n",
__func__, start, chunk);
if (chunk <= 1024 << MIN_OCQP_SHIFT) {
printk(KERN_WARNING MOD
"Failed to add all OCQP chunks (%x/%x)\n",
start, top - start);
return 0;
}
chunk >>= 1;
} else {
PDBG("%s added OCQP chunk (%x/%x)\n",
__func__, start, chunk);
start += chunk;
}
}
return 0;
}
void c4iw_ocqp_pool_destroy(struct c4iw_rdev *rdev)
{
gen_pool_destroy(rdev->ocqp_pool);
}
| gpl-2.0 |
yatto/xteam31 | drivers/media/radio/radio-rtrack2.c | 2687 | 7785 | /* RadioTrack II driver for Linux radio support (C) 1998 Ben Pfaff
*
* Based on RadioTrack I/RadioReveal (C) 1997 M. Kirkwood
* Converted to new API by Alan Cox <alan@lxorguk.ukuu.org.uk>
* Various bugfixes and enhancements by Russell Kroll <rkroll@exploits.org>
*
* TODO: Allow for more than one of these foolish entities :-)
*
* Converted to V4L2 API by Mauro Carvalho Chehab <mchehab@infradead.org>
*/
#include <linux/module.h> /* Modules */
#include <linux/init.h> /* Initdata */
#include <linux/ioport.h> /* request_region */
#include <linux/delay.h> /* udelay */
#include <linux/videodev2.h> /* kernel radio structs */
#include <linux/mutex.h>
#include <linux/version.h> /* for KERNEL_VERSION MACRO */
#include <linux/io.h> /* outb, outb_p */
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
MODULE_AUTHOR("Ben Pfaff");
MODULE_DESCRIPTION("A driver for the RadioTrack II radio card.");
MODULE_LICENSE("GPL");
#ifndef CONFIG_RADIO_RTRACK2_PORT
#define CONFIG_RADIO_RTRACK2_PORT -1
#endif
static int io = CONFIG_RADIO_RTRACK2_PORT;
static int radio_nr = -1;
module_param(io, int, 0);
MODULE_PARM_DESC(io, "I/O address of the RadioTrack card (0x20c or 0x30c)");
module_param(radio_nr, int, 0);
#define RADIO_VERSION KERNEL_VERSION(0, 0, 2)
struct rtrack2
{
struct v4l2_device v4l2_dev;
struct video_device vdev;
int io;
unsigned long curfreq;
int muted;
struct mutex lock;
};
static struct rtrack2 rtrack2_card;
/* local things */
static void rt_mute(struct rtrack2 *dev)
{
if (dev->muted)
return;
mutex_lock(&dev->lock);
outb(1, dev->io);
mutex_unlock(&dev->lock);
dev->muted = 1;
}
static void rt_unmute(struct rtrack2 *dev)
{
if(dev->muted == 0)
return;
mutex_lock(&dev->lock);
outb(0, dev->io);
mutex_unlock(&dev->lock);
dev->muted = 0;
}
static void zero(struct rtrack2 *dev)
{
outb_p(1, dev->io);
outb_p(3, dev->io);
outb_p(1, dev->io);
}
static void one(struct rtrack2 *dev)
{
outb_p(5, dev->io);
outb_p(7, dev->io);
outb_p(5, dev->io);
}
static int rt_setfreq(struct rtrack2 *dev, unsigned long freq)
{
int i;
mutex_lock(&dev->lock);
dev->curfreq = freq;
freq = freq / 200 + 856;
outb_p(0xc8, dev->io);
outb_p(0xc9, dev->io);
outb_p(0xc9, dev->io);
for (i = 0; i < 10; i++)
zero(dev);
for (i = 14; i >= 0; i--)
if (freq & (1 << i))
one(dev);
else
zero(dev);
outb_p(0xc8, dev->io);
if (!dev->muted)
outb_p(0, dev->io);
mutex_unlock(&dev->lock);
return 0;
}
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *v)
{
strlcpy(v->driver, "radio-rtrack2", sizeof(v->driver));
strlcpy(v->card, "RadioTrack II", sizeof(v->card));
strlcpy(v->bus_info, "ISA", sizeof(v->bus_info));
v->version = RADIO_VERSION;
v->capabilities = V4L2_CAP_TUNER | V4L2_CAP_RADIO;
return 0;
}
static int vidioc_s_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
return v->index ? -EINVAL : 0;
}
static int rt_getsigstr(struct rtrack2 *dev)
{
int sig = 1;
mutex_lock(&dev->lock);
if (inb(dev->io) & 2) /* bit set = no signal present */
sig = 0;
mutex_unlock(&dev->lock);
return sig;
}
static int vidioc_g_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
struct rtrack2 *rt = video_drvdata(file);
if (v->index > 0)
return -EINVAL;
strlcpy(v->name, "FM", sizeof(v->name));
v->type = V4L2_TUNER_RADIO;
v->rangelow = 88 * 16000;
v->rangehigh = 108 * 16000;
v->rxsubchans = V4L2_TUNER_SUB_MONO;
v->capability = V4L2_TUNER_CAP_LOW;
v->audmode = V4L2_TUNER_MODE_MONO;
v->signal = 0xFFFF * rt_getsigstr(rt);
return 0;
}
static int vidioc_s_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct rtrack2 *rt = video_drvdata(file);
if (f->tuner != 0 || f->type != V4L2_TUNER_RADIO)
return -EINVAL;
rt_setfreq(rt, f->frequency);
return 0;
}
static int vidioc_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct rtrack2 *rt = video_drvdata(file);
if (f->tuner != 0)
return -EINVAL;
f->type = V4L2_TUNER_RADIO;
f->frequency = rt->curfreq;
return 0;
}
static int vidioc_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
switch (qc->id) {
case V4L2_CID_AUDIO_MUTE:
return v4l2_ctrl_query_fill(qc, 0, 1, 1, 1);
case V4L2_CID_AUDIO_VOLUME:
return v4l2_ctrl_query_fill(qc, 0, 65535, 65535, 65535);
}
return -EINVAL;
}
static int vidioc_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct rtrack2 *rt = video_drvdata(file);
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
ctrl->value = rt->muted;
return 0;
case V4L2_CID_AUDIO_VOLUME:
if (rt->muted)
ctrl->value = 0;
else
ctrl->value = 65535;
return 0;
}
return -EINVAL;
}
static int vidioc_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct rtrack2 *rt = video_drvdata(file);
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
if (ctrl->value)
rt_mute(rt);
else
rt_unmute(rt);
return 0;
case V4L2_CID_AUDIO_VOLUME:
if (ctrl->value)
rt_unmute(rt);
else
rt_mute(rt);
return 0;
}
return -EINVAL;
}
static int vidioc_g_input(struct file *filp, void *priv, unsigned int *i)
{
*i = 0;
return 0;
}
static int vidioc_s_input(struct file *filp, void *priv, unsigned int i)
{
return i ? -EINVAL : 0;
}
static int vidioc_g_audio(struct file *file, void *priv,
struct v4l2_audio *a)
{
a->index = 0;
strlcpy(a->name, "Radio", sizeof(a->name));
a->capability = V4L2_AUDCAP_STEREO;
return 0;
}
static int vidioc_s_audio(struct file *file, void *priv,
struct v4l2_audio *a)
{
return a->index ? -EINVAL : 0;
}
static const struct v4l2_file_operations rtrack2_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = video_ioctl2,
};
static const struct v4l2_ioctl_ops rtrack2_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_g_tuner = vidioc_g_tuner,
.vidioc_s_tuner = vidioc_s_tuner,
.vidioc_g_frequency = vidioc_g_frequency,
.vidioc_s_frequency = vidioc_s_frequency,
.vidioc_queryctrl = vidioc_queryctrl,
.vidioc_g_ctrl = vidioc_g_ctrl,
.vidioc_s_ctrl = vidioc_s_ctrl,
.vidioc_g_audio = vidioc_g_audio,
.vidioc_s_audio = vidioc_s_audio,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
};
static int __init rtrack2_init(void)
{
struct rtrack2 *dev = &rtrack2_card;
struct v4l2_device *v4l2_dev = &dev->v4l2_dev;
int res;
strlcpy(v4l2_dev->name, "rtrack2", sizeof(v4l2_dev->name));
dev->io = io;
if (dev->io == -1) {
v4l2_err(v4l2_dev, "You must set an I/O address with io=0x20c or io=0x30c\n");
return -EINVAL;
}
if (!request_region(dev->io, 4, "rtrack2")) {
v4l2_err(v4l2_dev, "port 0x%x already in use\n", dev->io);
return -EBUSY;
}
res = v4l2_device_register(NULL, v4l2_dev);
if (res < 0) {
release_region(dev->io, 4);
v4l2_err(v4l2_dev, "Could not register v4l2_device\n");
return res;
}
strlcpy(dev->vdev.name, v4l2_dev->name, sizeof(dev->vdev.name));
dev->vdev.v4l2_dev = v4l2_dev;
dev->vdev.fops = &rtrack2_fops;
dev->vdev.ioctl_ops = &rtrack2_ioctl_ops;
dev->vdev.release = video_device_release_empty;
video_set_drvdata(&dev->vdev, dev);
/* mute card - prevents noisy bootups */
outb(1, dev->io);
dev->muted = 1;
mutex_init(&dev->lock);
if (video_register_device(&dev->vdev, VFL_TYPE_RADIO, radio_nr) < 0) {
v4l2_device_unregister(v4l2_dev);
release_region(dev->io, 4);
return -EINVAL;
}
v4l2_info(v4l2_dev, "AIMSlab Radiotrack II card driver.\n");
return 0;
}
static void __exit rtrack2_exit(void)
{
struct rtrack2 *dev = &rtrack2_card;
video_unregister_device(&dev->vdev);
v4l2_device_unregister(&dev->v4l2_dev);
release_region(dev->io, 4);
}
module_init(rtrack2_init);
module_exit(rtrack2_exit);
| gpl-2.0 |
VanirAOSP/kernel_lge_g3 | arch/h8300/kernel/traps.c | 4735 | 4038 | /*
* linux/arch/h8300/boot/traps.c -- general exception handling code
* H8/300 support Yoshinori Sato <ysato@users.sourceforge.jp>
*
* Cloned from Linux/m68k.
*
* No original Copyright holder listed,
* Probable original (C) Roman Zippel (assigned DJD, 1999)
*
* Copyright 1999-2000 D. Jeff Dionne, <jeff@rt-control.com>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive
* for more details.
*/
#include <linux/types.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/bug.h>
#include <asm/irq.h>
#include <asm/traps.h>
#include <asm/page.h>
static DEFINE_SPINLOCK(die_lock);
/*
* this must be called very early as the kernel might
* use some instruction that are emulated on the 060
*/
void __init base_trap_init(void)
{
}
void __init trap_init (void)
{
}
asmlinkage void set_esp0 (unsigned long ssp)
{
current->thread.esp0 = ssp;
}
/*
* Generic dumping code. Used for panic and debug.
*/
static void dump(struct pt_regs *fp)
{
unsigned long *sp;
unsigned char *tp;
int i;
printk("\nCURRENT PROCESS:\n\n");
printk("COMM=%s PID=%d\n", current->comm, current->pid);
if (current->mm) {
printk("TEXT=%08x-%08x DATA=%08x-%08x BSS=%08x-%08x\n",
(int) current->mm->start_code,
(int) current->mm->end_code,
(int) current->mm->start_data,
(int) current->mm->end_data,
(int) current->mm->end_data,
(int) current->mm->brk);
printk("USER-STACK=%08x KERNEL-STACK=%08lx\n\n",
(int) current->mm->start_stack,
(int) PAGE_SIZE+(unsigned long)current);
}
show_regs(fp);
printk("\nCODE:");
tp = ((unsigned char *) fp->pc) - 0x20;
for (sp = (unsigned long *) tp, i = 0; (i < 0x40); i += 4) {
if ((i % 0x10) == 0)
printk("\n%08x: ", (int) (tp + i));
printk("%08x ", (int) *sp++);
}
printk("\n");
printk("\nKERNEL STACK:");
tp = ((unsigned char *) fp) - 0x40;
for (sp = (unsigned long *) tp, i = 0; (i < 0xc0); i += 4) {
if ((i % 0x10) == 0)
printk("\n%08x: ", (int) (tp + i));
printk("%08x ", (int) *sp++);
}
printk("\n");
if (STACK_MAGIC != *(unsigned long *)((unsigned long)current+PAGE_SIZE))
printk("(Possibly corrupted stack page??)\n");
printk("\n\n");
}
void die(const char *str, struct pt_regs *fp, unsigned long err)
{
static int diecount;
oops_enter();
console_verbose();
spin_lock_irq(&die_lock);
report_bug(fp->pc, fp);
printk(KERN_EMERG "%s: %04lx [#%d] ", str, err & 0xffff, ++diecount);
dump(fp);
spin_unlock_irq(&die_lock);
do_exit(SIGSEGV);
}
extern char _start, _etext;
#define check_kernel_text(addr) \
((addr >= (unsigned long)(&_start)) && \
(addr < (unsigned long)(&_etext)))
static int kstack_depth_to_print = 24;
void show_stack(struct task_struct *task, unsigned long *esp)
{
unsigned long *stack, addr;
int i;
if (esp == NULL)
esp = (unsigned long *) &esp;
stack = esp;
printk("Stack from %08lx:", (unsigned long)stack);
for (i = 0; i < kstack_depth_to_print; i++) {
if (((unsigned long)stack & (THREAD_SIZE - 1)) == 0)
break;
if (i % 8 == 0)
printk("\n ");
printk(" %08lx", *stack++);
}
printk("\nCall Trace:");
i = 0;
stack = esp;
while (((unsigned long)stack & (THREAD_SIZE - 1)) != 0) {
addr = *stack++;
/*
* If the address is either in the text segment of the
* kernel, or in the region which contains vmalloc'ed
* memory, it *may* be the address of a calling
* routine; if so, print it so that someone tracing
* down the cause of the crash will be able to figure
* out the call path that was taken.
*/
if (check_kernel_text(addr)) {
if (i % 4 == 0)
printk("\n ");
printk(" [<%08lx>]", addr);
i++;
}
}
printk("\n");
}
void show_trace_task(struct task_struct *tsk)
{
show_stack(tsk,(unsigned long *)tsk->thread.esp0);
}
void dump_stack(void)
{
show_stack(NULL,NULL);
}
EXPORT_SYMBOL(dump_stack);
| gpl-2.0 |
XMelancholy/android_kernel_sony_u8500 | arch/arm/mach-omap1/irq.c | 4735 | 7337 | /*
* linux/arch/arm/mach-omap1/irq.c
*
* Interrupt handler for all OMAP boards
*
* Copyright (C) 2004 Nokia Corporation
* Written by Tony Lindgren <tony@atomide.com>
* Major cleanups by Juha Yrjölä <juha.yrjola@nokia.com>
*
* Completely re-written to support various OMAP chips with bank specific
* interrupt handlers.
*
* Some snippets of the code taken from the older OMAP interrupt handler
* Copyright (C) 2001 RidgeRun, Inc. Greg Lonnon <glonnon@ridgerun.com>
*
* GPIO interrupt handler moved to gpio.c by Juha Yrjola
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <asm/irq.h>
#include <asm/mach/irq.h>
#include <plat/cpu.h>
#include <mach/hardware.h>
#define IRQ_BANK(irq) ((irq) >> 5)
#define IRQ_BIT(irq) ((irq) & 0x1f)
struct omap_irq_bank {
unsigned long base_reg;
unsigned long trigger_map;
unsigned long wake_enable;
};
u32 omap_irq_flags;
static unsigned int irq_bank_count;
static struct omap_irq_bank *irq_banks;
static inline unsigned int irq_bank_readl(int bank, int offset)
{
return omap_readl(irq_banks[bank].base_reg + offset);
}
static inline void irq_bank_writel(unsigned long value, int bank, int offset)
{
omap_writel(value, irq_banks[bank].base_reg + offset);
}
static void omap_ack_irq(struct irq_data *d)
{
if (d->irq > 31)
omap_writel(0x1, OMAP_IH2_BASE + IRQ_CONTROL_REG_OFFSET);
omap_writel(0x1, OMAP_IH1_BASE + IRQ_CONTROL_REG_OFFSET);
}
static void omap_mask_irq(struct irq_data *d)
{
int bank = IRQ_BANK(d->irq);
u32 l;
l = omap_readl(irq_banks[bank].base_reg + IRQ_MIR_REG_OFFSET);
l |= 1 << IRQ_BIT(d->irq);
omap_writel(l, irq_banks[bank].base_reg + IRQ_MIR_REG_OFFSET);
}
static void omap_unmask_irq(struct irq_data *d)
{
int bank = IRQ_BANK(d->irq);
u32 l;
l = omap_readl(irq_banks[bank].base_reg + IRQ_MIR_REG_OFFSET);
l &= ~(1 << IRQ_BIT(d->irq));
omap_writel(l, irq_banks[bank].base_reg + IRQ_MIR_REG_OFFSET);
}
static void omap_mask_ack_irq(struct irq_data *d)
{
omap_mask_irq(d);
omap_ack_irq(d);
}
static int omap_wake_irq(struct irq_data *d, unsigned int enable)
{
int bank = IRQ_BANK(d->irq);
if (enable)
irq_banks[bank].wake_enable |= IRQ_BIT(d->irq);
else
irq_banks[bank].wake_enable &= ~IRQ_BIT(d->irq);
return 0;
}
/*
* Allows tuning the IRQ type and priority
*
* NOTE: There is currently no OMAP fiq handler for Linux. Read the
* mailing list threads on FIQ handlers if you are planning to
* add a FIQ handler for OMAP.
*/
static void omap_irq_set_cfg(int irq, int fiq, int priority, int trigger)
{
signed int bank;
unsigned long val, offset;
bank = IRQ_BANK(irq);
/* FIQ is only available on bank 0 interrupts */
fiq = bank ? 0 : (fiq & 0x1);
val = fiq | ((priority & 0x1f) << 2) | ((trigger & 0x1) << 1);
offset = IRQ_ILR0_REG_OFFSET + IRQ_BIT(irq) * 0x4;
irq_bank_writel(val, bank, offset);
}
#if defined (CONFIG_ARCH_OMAP730) || defined (CONFIG_ARCH_OMAP850)
static struct omap_irq_bank omap7xx_irq_banks[] = {
{ .base_reg = OMAP_IH1_BASE, .trigger_map = 0xb3f8e22f },
{ .base_reg = OMAP_IH2_BASE, .trigger_map = 0xfdb9c1f2 },
{ .base_reg = OMAP_IH2_BASE + 0x100, .trigger_map = 0x800040f3 },
};
#endif
#ifdef CONFIG_ARCH_OMAP15XX
static struct omap_irq_bank omap1510_irq_banks[] = {
{ .base_reg = OMAP_IH1_BASE, .trigger_map = 0xb3febfff },
{ .base_reg = OMAP_IH2_BASE, .trigger_map = 0xffbfffed },
};
static struct omap_irq_bank omap310_irq_banks[] = {
{ .base_reg = OMAP_IH1_BASE, .trigger_map = 0xb3faefc3 },
{ .base_reg = OMAP_IH2_BASE, .trigger_map = 0x65b3c061 },
};
#endif
#if defined(CONFIG_ARCH_OMAP16XX)
static struct omap_irq_bank omap1610_irq_banks[] = {
{ .base_reg = OMAP_IH1_BASE, .trigger_map = 0xb3fefe8f },
{ .base_reg = OMAP_IH2_BASE, .trigger_map = 0xfdb7c1fd },
{ .base_reg = OMAP_IH2_BASE + 0x100, .trigger_map = 0xffffb7ff },
{ .base_reg = OMAP_IH2_BASE + 0x200, .trigger_map = 0xffffffff },
};
#endif
static struct irq_chip omap_irq_chip = {
.name = "MPU",
.irq_ack = omap_mask_ack_irq,
.irq_mask = omap_mask_irq,
.irq_unmask = omap_unmask_irq,
.irq_set_wake = omap_wake_irq,
};
void __init omap1_init_irq(void)
{
int i, j;
#if defined(CONFIG_ARCH_OMAP730) || defined(CONFIG_ARCH_OMAP850)
if (cpu_is_omap7xx()) {
omap_irq_flags = INT_7XX_IH2_IRQ;
irq_banks = omap7xx_irq_banks;
irq_bank_count = ARRAY_SIZE(omap7xx_irq_banks);
}
#endif
#ifdef CONFIG_ARCH_OMAP15XX
if (cpu_is_omap1510()) {
omap_irq_flags = INT_1510_IH2_IRQ;
irq_banks = omap1510_irq_banks;
irq_bank_count = ARRAY_SIZE(omap1510_irq_banks);
}
if (cpu_is_omap310()) {
omap_irq_flags = INT_1510_IH2_IRQ;
irq_banks = omap310_irq_banks;
irq_bank_count = ARRAY_SIZE(omap310_irq_banks);
}
#endif
#if defined(CONFIG_ARCH_OMAP16XX)
if (cpu_is_omap16xx()) {
omap_irq_flags = INT_1510_IH2_IRQ;
irq_banks = omap1610_irq_banks;
irq_bank_count = ARRAY_SIZE(omap1610_irq_banks);
}
#endif
printk("Total of %i interrupts in %i interrupt banks\n",
irq_bank_count * 32, irq_bank_count);
/* Mask and clear all interrupts */
for (i = 0; i < irq_bank_count; i++) {
irq_bank_writel(~0x0, i, IRQ_MIR_REG_OFFSET);
irq_bank_writel(0x0, i, IRQ_ITR_REG_OFFSET);
}
/* Clear any pending interrupts */
irq_bank_writel(0x03, 0, IRQ_CONTROL_REG_OFFSET);
irq_bank_writel(0x03, 1, IRQ_CONTROL_REG_OFFSET);
/* Enable interrupts in global mask */
if (cpu_is_omap7xx())
irq_bank_writel(0x0, 0, IRQ_GMR_REG_OFFSET);
/* Install the interrupt handlers for each bank */
for (i = 0; i < irq_bank_count; i++) {
for (j = i * 32; j < (i + 1) * 32; j++) {
int irq_trigger;
irq_trigger = irq_banks[i].trigger_map >> IRQ_BIT(j);
omap_irq_set_cfg(j, 0, 0, irq_trigger);
irq_set_chip_and_handler(j, &omap_irq_chip,
handle_level_irq);
set_irq_flags(j, IRQF_VALID);
}
}
/* Unmask level 2 handler */
if (cpu_is_omap7xx())
omap_unmask_irq(irq_get_irq_data(INT_7XX_IH2_IRQ));
else if (cpu_is_omap15xx())
omap_unmask_irq(irq_get_irq_data(INT_1510_IH2_IRQ));
else if (cpu_is_omap16xx())
omap_unmask_irq(irq_get_irq_data(INT_1610_IH2_IRQ));
}
| gpl-2.0 |
imang/gcore_kernel | drivers/media/video/vs6624.c | 4991 | 21056 | /*
* vs6624.c ST VS6624 CMOS image sensor driver
*
* Copyright (c) 2011 Analog Devices 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.
*/
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/videodev2.h>
#include <media/v4l2-chip-ident.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-device.h>
#include <media/v4l2-mediabus.h>
#include "vs6624_regs.h"
#define VGA_WIDTH 640
#define VGA_HEIGHT 480
#define QVGA_WIDTH 320
#define QVGA_HEIGHT 240
#define QQVGA_WIDTH 160
#define QQVGA_HEIGHT 120
#define CIF_WIDTH 352
#define CIF_HEIGHT 288
#define QCIF_WIDTH 176
#define QCIF_HEIGHT 144
#define QQCIF_WIDTH 88
#define QQCIF_HEIGHT 72
#define MAX_FRAME_RATE 30
struct vs6624 {
struct v4l2_subdev sd;
struct v4l2_ctrl_handler hdl;
struct v4l2_fract frame_rate;
struct v4l2_mbus_framefmt fmt;
unsigned ce_pin;
};
static const struct vs6624_format {
enum v4l2_mbus_pixelcode mbus_code;
enum v4l2_colorspace colorspace;
} vs6624_formats[] = {
{
.mbus_code = V4L2_MBUS_FMT_UYVY8_2X8,
.colorspace = V4L2_COLORSPACE_JPEG,
},
{
.mbus_code = V4L2_MBUS_FMT_YUYV8_2X8,
.colorspace = V4L2_COLORSPACE_JPEG,
},
{
.mbus_code = V4L2_MBUS_FMT_RGB565_2X8_LE,
.colorspace = V4L2_COLORSPACE_SRGB,
},
};
static struct v4l2_mbus_framefmt vs6624_default_fmt = {
.width = VGA_WIDTH,
.height = VGA_HEIGHT,
.code = V4L2_MBUS_FMT_UYVY8_2X8,
.field = V4L2_FIELD_NONE,
.colorspace = V4L2_COLORSPACE_JPEG,
};
static const u16 vs6624_p1[] = {
0x8104, 0x03,
0x8105, 0x01,
0xc900, 0x03,
0xc904, 0x47,
0xc905, 0x10,
0xc906, 0x80,
0xc907, 0x3a,
0x903a, 0x02,
0x903b, 0x47,
0x903c, 0x15,
0xc908, 0x31,
0xc909, 0xdc,
0xc90a, 0x80,
0xc90b, 0x44,
0x9044, 0x02,
0x9045, 0x31,
0x9046, 0xe2,
0xc90c, 0x07,
0xc90d, 0xe0,
0xc90e, 0x80,
0xc90f, 0x47,
0x9047, 0x90,
0x9048, 0x83,
0x9049, 0x81,
0x904a, 0xe0,
0x904b, 0x60,
0x904c, 0x08,
0x904d, 0x90,
0x904e, 0xc0,
0x904f, 0x43,
0x9050, 0x74,
0x9051, 0x01,
0x9052, 0xf0,
0x9053, 0x80,
0x9054, 0x05,
0x9055, 0xE4,
0x9056, 0x90,
0x9057, 0xc0,
0x9058, 0x43,
0x9059, 0xf0,
0x905a, 0x02,
0x905b, 0x07,
0x905c, 0xec,
0xc910, 0x5d,
0xc911, 0xca,
0xc912, 0x80,
0xc913, 0x5d,
0x905d, 0xa3,
0x905e, 0x04,
0x905f, 0xf0,
0x9060, 0xa3,
0x9061, 0x04,
0x9062, 0xf0,
0x9063, 0x22,
0xc914, 0x72,
0xc915, 0x92,
0xc916, 0x80,
0xc917, 0x64,
0x9064, 0x74,
0x9065, 0x01,
0x9066, 0x02,
0x9067, 0x72,
0x9068, 0x95,
0xc918, 0x47,
0xc919, 0xf2,
0xc91a, 0x81,
0xc91b, 0x69,
0x9169, 0x74,
0x916a, 0x02,
0x916b, 0xf0,
0x916c, 0xec,
0x916d, 0xb4,
0x916e, 0x10,
0x916f, 0x0a,
0x9170, 0x90,
0x9171, 0x80,
0x9172, 0x16,
0x9173, 0xe0,
0x9174, 0x70,
0x9175, 0x04,
0x9176, 0x90,
0x9177, 0xd3,
0x9178, 0xc4,
0x9179, 0xf0,
0x917a, 0x22,
0xc91c, 0x0a,
0xc91d, 0xbe,
0xc91e, 0x80,
0xc91f, 0x73,
0x9073, 0xfc,
0x9074, 0xa3,
0x9075, 0xe0,
0x9076, 0xf5,
0x9077, 0x82,
0x9078, 0x8c,
0x9079, 0x83,
0x907a, 0xa3,
0x907b, 0xa3,
0x907c, 0xe0,
0x907d, 0xfc,
0x907e, 0xa3,
0x907f, 0xe0,
0x9080, 0xc3,
0x9081, 0x9f,
0x9082, 0xff,
0x9083, 0xec,
0x9084, 0x9e,
0x9085, 0xfe,
0x9086, 0x02,
0x9087, 0x0a,
0x9088, 0xea,
0xc920, 0x47,
0xc921, 0x38,
0xc922, 0x80,
0xc923, 0x89,
0x9089, 0xec,
0x908a, 0xd3,
0x908b, 0x94,
0x908c, 0x20,
0x908d, 0x40,
0x908e, 0x01,
0x908f, 0x1c,
0x9090, 0x90,
0x9091, 0xd3,
0x9092, 0xd4,
0x9093, 0xec,
0x9094, 0xf0,
0x9095, 0x02,
0x9096, 0x47,
0x9097, 0x3d,
0xc924, 0x45,
0xc925, 0xca,
0xc926, 0x80,
0xc927, 0x98,
0x9098, 0x12,
0x9099, 0x77,
0x909a, 0xd6,
0x909b, 0x02,
0x909c, 0x45,
0x909d, 0xcd,
0xc928, 0x20,
0xc929, 0xd5,
0xc92a, 0x80,
0xc92b, 0x9e,
0x909e, 0x90,
0x909f, 0x82,
0x90a0, 0x18,
0x90a1, 0xe0,
0x90a2, 0xb4,
0x90a3, 0x03,
0x90a4, 0x0e,
0x90a5, 0x90,
0x90a6, 0x83,
0x90a7, 0xbf,
0x90a8, 0xe0,
0x90a9, 0x60,
0x90aa, 0x08,
0x90ab, 0x90,
0x90ac, 0x81,
0x90ad, 0xfc,
0x90ae, 0xe0,
0x90af, 0xff,
0x90b0, 0xc3,
0x90b1, 0x13,
0x90b2, 0xf0,
0x90b3, 0x90,
0x90b4, 0x81,
0x90b5, 0xfc,
0x90b6, 0xe0,
0x90b7, 0xff,
0x90b8, 0x02,
0x90b9, 0x20,
0x90ba, 0xda,
0xc92c, 0x70,
0xc92d, 0xbc,
0xc92e, 0x80,
0xc92f, 0xbb,
0x90bb, 0x90,
0x90bc, 0x82,
0x90bd, 0x18,
0x90be, 0xe0,
0x90bf, 0xb4,
0x90c0, 0x03,
0x90c1, 0x06,
0x90c2, 0x90,
0x90c3, 0xc1,
0x90c4, 0x06,
0x90c5, 0x74,
0x90c6, 0x05,
0x90c7, 0xf0,
0x90c8, 0x90,
0x90c9, 0xd3,
0x90ca, 0xa0,
0x90cb, 0x02,
0x90cc, 0x70,
0x90cd, 0xbf,
0xc930, 0x72,
0xc931, 0x21,
0xc932, 0x81,
0xc933, 0x3b,
0x913b, 0x7d,
0x913c, 0x02,
0x913d, 0x7f,
0x913e, 0x7b,
0x913f, 0x02,
0x9140, 0x72,
0x9141, 0x25,
0xc934, 0x28,
0xc935, 0xae,
0xc936, 0x80,
0xc937, 0xd2,
0x90d2, 0xf0,
0x90d3, 0x90,
0x90d4, 0xd2,
0x90d5, 0x0a,
0x90d6, 0x02,
0x90d7, 0x28,
0x90d8, 0xb4,
0xc938, 0x28,
0xc939, 0xb1,
0xc93a, 0x80,
0xc93b, 0xd9,
0x90d9, 0x90,
0x90da, 0x83,
0x90db, 0xba,
0x90dc, 0xe0,
0x90dd, 0xff,
0x90de, 0x90,
0x90df, 0xd2,
0x90e0, 0x08,
0x90e1, 0xe0,
0x90e2, 0xe4,
0x90e3, 0xef,
0x90e4, 0xf0,
0x90e5, 0xa3,
0x90e6, 0xe0,
0x90e7, 0x74,
0x90e8, 0xff,
0x90e9, 0xf0,
0x90ea, 0x90,
0x90eb, 0xd2,
0x90ec, 0x0a,
0x90ed, 0x02,
0x90ee, 0x28,
0x90ef, 0xb4,
0xc93c, 0x29,
0xc93d, 0x79,
0xc93e, 0x80,
0xc93f, 0xf0,
0x90f0, 0xf0,
0x90f1, 0x90,
0x90f2, 0xd2,
0x90f3, 0x0e,
0x90f4, 0x02,
0x90f5, 0x29,
0x90f6, 0x7f,
0xc940, 0x29,
0xc941, 0x7c,
0xc942, 0x80,
0xc943, 0xf7,
0x90f7, 0x90,
0x90f8, 0x83,
0x90f9, 0xba,
0x90fa, 0xe0,
0x90fb, 0xff,
0x90fc, 0x90,
0x90fd, 0xd2,
0x90fe, 0x0c,
0x90ff, 0xe0,
0x9100, 0xe4,
0x9101, 0xef,
0x9102, 0xf0,
0x9103, 0xa3,
0x9104, 0xe0,
0x9105, 0x74,
0x9106, 0xff,
0x9107, 0xf0,
0x9108, 0x90,
0x9109, 0xd2,
0x910a, 0x0e,
0x910b, 0x02,
0x910c, 0x29,
0x910d, 0x7f,
0xc944, 0x2a,
0xc945, 0x42,
0xc946, 0x81,
0xc947, 0x0e,
0x910e, 0xf0,
0x910f, 0x90,
0x9110, 0xd2,
0x9111, 0x12,
0x9112, 0x02,
0x9113, 0x2a,
0x9114, 0x48,
0xc948, 0x2a,
0xc949, 0x45,
0xc94a, 0x81,
0xc94b, 0x15,
0x9115, 0x90,
0x9116, 0x83,
0x9117, 0xba,
0x9118, 0xe0,
0x9119, 0xff,
0x911a, 0x90,
0x911b, 0xd2,
0x911c, 0x10,
0x911d, 0xe0,
0x911e, 0xe4,
0x911f, 0xef,
0x9120, 0xf0,
0x9121, 0xa3,
0x9122, 0xe0,
0x9123, 0x74,
0x9124, 0xff,
0x9125, 0xf0,
0x9126, 0x90,
0x9127, 0xd2,
0x9128, 0x12,
0x9129, 0x02,
0x912a, 0x2a,
0x912b, 0x48,
0xc900, 0x01,
0x0000, 0x00,
};
static const u16 vs6624_p2[] = {
0x806f, 0x01,
0x058c, 0x01,
0x0000, 0x00,
};
static const u16 vs6624_run_setup[] = {
0x1d18, 0x00, /* Enableconstrainedwhitebalance */
VS6624_PEAK_MIN_OUT_G_MSB, 0x3c, /* Damper PeakGain Output MSB */
VS6624_PEAK_MIN_OUT_G_LSB, 0x66, /* Damper PeakGain Output LSB */
VS6624_CM_LOW_THR_MSB, 0x65, /* Damper Low MSB */
VS6624_CM_LOW_THR_LSB, 0xd1, /* Damper Low LSB */
VS6624_CM_HIGH_THR_MSB, 0x66, /* Damper High MSB */
VS6624_CM_HIGH_THR_LSB, 0x62, /* Damper High LSB */
VS6624_CM_MIN_OUT_MSB, 0x00, /* Damper Min output MSB */
VS6624_CM_MIN_OUT_LSB, 0x00, /* Damper Min output LSB */
VS6624_NORA_DISABLE, 0x00, /* Nora fDisable */
VS6624_NORA_USAGE, 0x04, /* Nora usage */
VS6624_NORA_LOW_THR_MSB, 0x63, /* Damper Low MSB Changed 0x63 to 0x65 */
VS6624_NORA_LOW_THR_LSB, 0xd1, /* Damper Low LSB */
VS6624_NORA_HIGH_THR_MSB, 0x68, /* Damper High MSB */
VS6624_NORA_HIGH_THR_LSB, 0xdd, /* Damper High LSB */
VS6624_NORA_MIN_OUT_MSB, 0x3a, /* Damper Min output MSB */
VS6624_NORA_MIN_OUT_LSB, 0x00, /* Damper Min output LSB */
VS6624_F2B_DISABLE, 0x00, /* Disable */
0x1d8a, 0x30, /* MAXWeightHigh */
0x1d91, 0x62, /* fpDamperLowThresholdHigh MSB */
0x1d92, 0x4a, /* fpDamperLowThresholdHigh LSB */
0x1d95, 0x65, /* fpDamperHighThresholdHigh MSB */
0x1d96, 0x0e, /* fpDamperHighThresholdHigh LSB */
0x1da1, 0x3a, /* fpMinimumDamperOutputLow MSB */
0x1da2, 0xb8, /* fpMinimumDamperOutputLow LSB */
0x1e08, 0x06, /* MAXWeightLow */
0x1e0a, 0x0a, /* MAXWeightHigh */
0x1601, 0x3a, /* Red A MSB */
0x1602, 0x14, /* Red A LSB */
0x1605, 0x3b, /* Blue A MSB */
0x1606, 0x85, /* BLue A LSB */
0x1609, 0x3b, /* RED B MSB */
0x160a, 0x85, /* RED B LSB */
0x160d, 0x3a, /* Blue B MSB */
0x160e, 0x14, /* Blue B LSB */
0x1611, 0x30, /* Max Distance from Locus MSB */
0x1612, 0x8f, /* Max Distance from Locus MSB */
0x1614, 0x01, /* Enable constrainer */
0x0000, 0x00,
};
static const u16 vs6624_default[] = {
VS6624_CONTRAST0, 0x84,
VS6624_SATURATION0, 0x75,
VS6624_GAMMA0, 0x11,
VS6624_CONTRAST1, 0x84,
VS6624_SATURATION1, 0x75,
VS6624_GAMMA1, 0x11,
VS6624_MAN_RG, 0x80,
VS6624_MAN_GG, 0x80,
VS6624_MAN_BG, 0x80,
VS6624_WB_MODE, 0x1,
VS6624_EXPO_COMPENSATION, 0xfe,
VS6624_EXPO_METER, 0x0,
VS6624_LIGHT_FREQ, 0x64,
VS6624_PEAK_GAIN, 0xe,
VS6624_PEAK_LOW_THR, 0x28,
VS6624_HMIRROR0, 0x0,
VS6624_VFLIP0, 0x0,
VS6624_ZOOM_HSTEP0_MSB, 0x0,
VS6624_ZOOM_HSTEP0_LSB, 0x1,
VS6624_ZOOM_VSTEP0_MSB, 0x0,
VS6624_ZOOM_VSTEP0_LSB, 0x1,
VS6624_PAN_HSTEP0_MSB, 0x0,
VS6624_PAN_HSTEP0_LSB, 0xf,
VS6624_PAN_VSTEP0_MSB, 0x0,
VS6624_PAN_VSTEP0_LSB, 0xf,
VS6624_SENSOR_MODE, 0x1,
VS6624_SYNC_CODE_SETUP, 0x21,
VS6624_DISABLE_FR_DAMPER, 0x0,
VS6624_FR_DEN, 0x1,
VS6624_FR_NUM_LSB, 0xf,
VS6624_INIT_PIPE_SETUP, 0x0,
VS6624_IMG_FMT0, 0x0,
VS6624_YUV_SETUP, 0x1,
VS6624_IMAGE_SIZE0, 0x2,
0x0000, 0x00,
};
static inline struct vs6624 *to_vs6624(struct v4l2_subdev *sd)
{
return container_of(sd, struct vs6624, sd);
}
static inline struct v4l2_subdev *to_sd(struct v4l2_ctrl *ctrl)
{
return &container_of(ctrl->handler, struct vs6624, hdl)->sd;
}
static int vs6624_read(struct v4l2_subdev *sd, u16 index)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
u8 buf[2];
buf[0] = index >> 8;
buf[1] = index;
i2c_master_send(client, buf, 2);
i2c_master_recv(client, buf, 1);
return buf[0];
}
static int vs6624_write(struct v4l2_subdev *sd, u16 index,
u8 value)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
u8 buf[3];
buf[0] = index >> 8;
buf[1] = index;
buf[2] = value;
return i2c_master_send(client, buf, 3);
}
static int vs6624_writeregs(struct v4l2_subdev *sd, const u16 *regs)
{
u16 reg;
u8 data;
while (*regs != 0x00) {
reg = *regs++;
data = *regs++;
vs6624_write(sd, reg, data);
}
return 0;
}
static int vs6624_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct v4l2_subdev *sd = to_sd(ctrl);
switch (ctrl->id) {
case V4L2_CID_CONTRAST:
vs6624_write(sd, VS6624_CONTRAST0, ctrl->val);
break;
case V4L2_CID_SATURATION:
vs6624_write(sd, VS6624_SATURATION0, ctrl->val);
break;
case V4L2_CID_HFLIP:
vs6624_write(sd, VS6624_HMIRROR0, ctrl->val);
break;
case V4L2_CID_VFLIP:
vs6624_write(sd, VS6624_VFLIP0, ctrl->val);
break;
default:
return -EINVAL;
}
return 0;
}
static int vs6624_enum_mbus_fmt(struct v4l2_subdev *sd, unsigned index,
enum v4l2_mbus_pixelcode *code)
{
if (index >= ARRAY_SIZE(vs6624_formats))
return -EINVAL;
*code = vs6624_formats[index].mbus_code;
return 0;
}
static int vs6624_try_mbus_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *fmt)
{
int index;
for (index = 0; index < ARRAY_SIZE(vs6624_formats); index++)
if (vs6624_formats[index].mbus_code == fmt->code)
break;
if (index >= ARRAY_SIZE(vs6624_formats)) {
/* default to first format */
index = 0;
fmt->code = vs6624_formats[0].mbus_code;
}
/* sensor mode is VGA */
if (fmt->width > VGA_WIDTH)
fmt->width = VGA_WIDTH;
if (fmt->height > VGA_HEIGHT)
fmt->height = VGA_HEIGHT;
fmt->width = fmt->width & (~3);
fmt->height = fmt->height & (~3);
fmt->field = V4L2_FIELD_NONE;
fmt->colorspace = vs6624_formats[index].colorspace;
return 0;
}
static int vs6624_s_mbus_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *fmt)
{
struct vs6624 *sensor = to_vs6624(sd);
int ret;
ret = vs6624_try_mbus_fmt(sd, fmt);
if (ret)
return ret;
/* set image format */
switch (fmt->code) {
case V4L2_MBUS_FMT_UYVY8_2X8:
vs6624_write(sd, VS6624_IMG_FMT0, 0x0);
vs6624_write(sd, VS6624_YUV_SETUP, 0x1);
break;
case V4L2_MBUS_FMT_YUYV8_2X8:
vs6624_write(sd, VS6624_IMG_FMT0, 0x0);
vs6624_write(sd, VS6624_YUV_SETUP, 0x3);
break;
case V4L2_MBUS_FMT_RGB565_2X8_LE:
vs6624_write(sd, VS6624_IMG_FMT0, 0x4);
vs6624_write(sd, VS6624_RGB_SETUP, 0x0);
break;
default:
return -EINVAL;
}
/* set image size */
if ((fmt->width == VGA_WIDTH) && (fmt->height == VGA_HEIGHT))
vs6624_write(sd, VS6624_IMAGE_SIZE0, 0x2);
else if ((fmt->width == QVGA_WIDTH) && (fmt->height == QVGA_HEIGHT))
vs6624_write(sd, VS6624_IMAGE_SIZE0, 0x4);
else if ((fmt->width == QQVGA_WIDTH) && (fmt->height == QQVGA_HEIGHT))
vs6624_write(sd, VS6624_IMAGE_SIZE0, 0x6);
else if ((fmt->width == CIF_WIDTH) && (fmt->height == CIF_HEIGHT))
vs6624_write(sd, VS6624_IMAGE_SIZE0, 0x3);
else if ((fmt->width == QCIF_WIDTH) && (fmt->height == QCIF_HEIGHT))
vs6624_write(sd, VS6624_IMAGE_SIZE0, 0x5);
else if ((fmt->width == QQCIF_WIDTH) && (fmt->height == QQCIF_HEIGHT))
vs6624_write(sd, VS6624_IMAGE_SIZE0, 0x7);
else {
vs6624_write(sd, VS6624_IMAGE_SIZE0, 0x8);
vs6624_write(sd, VS6624_MAN_HSIZE0_MSB, fmt->width >> 8);
vs6624_write(sd, VS6624_MAN_HSIZE0_LSB, fmt->width & 0xFF);
vs6624_write(sd, VS6624_MAN_VSIZE0_MSB, fmt->height >> 8);
vs6624_write(sd, VS6624_MAN_VSIZE0_LSB, fmt->height & 0xFF);
vs6624_write(sd, VS6624_CROP_CTRL0, 0x1);
}
sensor->fmt = *fmt;
return 0;
}
static int vs6624_g_mbus_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *fmt)
{
struct vs6624 *sensor = to_vs6624(sd);
*fmt = sensor->fmt;
return 0;
}
static int vs6624_g_parm(struct v4l2_subdev *sd, struct v4l2_streamparm *parms)
{
struct vs6624 *sensor = to_vs6624(sd);
struct v4l2_captureparm *cp = &parms->parm.capture;
if (parms->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
memset(cp, 0, sizeof(*cp));
cp->capability = V4L2_CAP_TIMEPERFRAME;
cp->timeperframe.numerator = sensor->frame_rate.denominator;
cp->timeperframe.denominator = sensor->frame_rate.numerator;
return 0;
}
static int vs6624_s_parm(struct v4l2_subdev *sd, struct v4l2_streamparm *parms)
{
struct vs6624 *sensor = to_vs6624(sd);
struct v4l2_captureparm *cp = &parms->parm.capture;
struct v4l2_fract *tpf = &cp->timeperframe;
if (parms->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
if (cp->extendedmode != 0)
return -EINVAL;
if (tpf->numerator == 0 || tpf->denominator == 0
|| (tpf->denominator > tpf->numerator * MAX_FRAME_RATE)) {
/* reset to max frame rate */
tpf->numerator = 1;
tpf->denominator = MAX_FRAME_RATE;
}
sensor->frame_rate.numerator = tpf->denominator;
sensor->frame_rate.denominator = tpf->numerator;
vs6624_write(sd, VS6624_DISABLE_FR_DAMPER, 0x0);
vs6624_write(sd, VS6624_FR_NUM_MSB,
sensor->frame_rate.numerator >> 8);
vs6624_write(sd, VS6624_FR_NUM_LSB,
sensor->frame_rate.numerator & 0xFF);
vs6624_write(sd, VS6624_FR_DEN,
sensor->frame_rate.denominator & 0xFF);
return 0;
}
static int vs6624_s_stream(struct v4l2_subdev *sd, int enable)
{
if (enable)
vs6624_write(sd, VS6624_USER_CMD, 0x2);
else
vs6624_write(sd, VS6624_USER_CMD, 0x4);
udelay(100);
return 0;
}
static int vs6624_g_chip_ident(struct v4l2_subdev *sd,
struct v4l2_dbg_chip_ident *chip)
{
int rev;
struct i2c_client *client = v4l2_get_subdevdata(sd);
rev = (vs6624_read(sd, VS6624_FW_VSN_MAJOR) << 8)
| vs6624_read(sd, VS6624_FW_VSN_MINOR);
return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_VS6624, rev);
}
#ifdef CONFIG_VIDEO_ADV_DEBUG
static int vs6624_g_register(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
if (!v4l2_chip_match_i2c_client(client, ®->match))
return -EINVAL;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
reg->val = vs6624_read(sd, reg->reg & 0xffff);
reg->size = 1;
return 0;
}
static int vs6624_s_register(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
if (!v4l2_chip_match_i2c_client(client, ®->match))
return -EINVAL;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
vs6624_write(sd, reg->reg & 0xffff, reg->val & 0xff);
return 0;
}
#endif
static const struct v4l2_ctrl_ops vs6624_ctrl_ops = {
.s_ctrl = vs6624_s_ctrl,
};
static const struct v4l2_subdev_core_ops vs6624_core_ops = {
.g_chip_ident = vs6624_g_chip_ident,
#ifdef CONFIG_VIDEO_ADV_DEBUG
.g_register = vs6624_g_register,
.s_register = vs6624_s_register,
#endif
};
static const struct v4l2_subdev_video_ops vs6624_video_ops = {
.enum_mbus_fmt = vs6624_enum_mbus_fmt,
.try_mbus_fmt = vs6624_try_mbus_fmt,
.s_mbus_fmt = vs6624_s_mbus_fmt,
.g_mbus_fmt = vs6624_g_mbus_fmt,
.s_parm = vs6624_s_parm,
.g_parm = vs6624_g_parm,
.s_stream = vs6624_s_stream,
};
static const struct v4l2_subdev_ops vs6624_ops = {
.core = &vs6624_core_ops,
.video = &vs6624_video_ops,
};
static int __devinit vs6624_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct vs6624 *sensor;
struct v4l2_subdev *sd;
struct v4l2_ctrl_handler *hdl;
const unsigned *ce;
int ret;
/* Check if the adapter supports the needed features */
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C))
return -EIO;
ce = client->dev.platform_data;
if (ce == NULL)
return -EINVAL;
ret = gpio_request(*ce, "VS6624 Chip Enable");
if (ret) {
v4l_err(client, "failed to request GPIO %d\n", *ce);
return ret;
}
gpio_direction_output(*ce, 1);
/* wait 100ms before any further i2c writes are performed */
mdelay(100);
sensor = kzalloc(sizeof(*sensor), GFP_KERNEL);
if (sensor == NULL) {
gpio_free(*ce);
return -ENOMEM;
}
sd = &sensor->sd;
v4l2_i2c_subdev_init(sd, client, &vs6624_ops);
vs6624_writeregs(sd, vs6624_p1);
vs6624_write(sd, VS6624_MICRO_EN, 0x2);
vs6624_write(sd, VS6624_DIO_EN, 0x1);
mdelay(10);
vs6624_writeregs(sd, vs6624_p2);
vs6624_writeregs(sd, vs6624_default);
vs6624_write(sd, VS6624_HSYNC_SETUP, 0xF);
vs6624_writeregs(sd, vs6624_run_setup);
/* set frame rate */
sensor->frame_rate.numerator = MAX_FRAME_RATE;
sensor->frame_rate.denominator = 1;
vs6624_write(sd, VS6624_DISABLE_FR_DAMPER, 0x0);
vs6624_write(sd, VS6624_FR_NUM_MSB,
sensor->frame_rate.numerator >> 8);
vs6624_write(sd, VS6624_FR_NUM_LSB,
sensor->frame_rate.numerator & 0xFF);
vs6624_write(sd, VS6624_FR_DEN,
sensor->frame_rate.denominator & 0xFF);
sensor->fmt = vs6624_default_fmt;
sensor->ce_pin = *ce;
v4l_info(client, "chip found @ 0x%02x (%s)\n",
client->addr << 1, client->adapter->name);
hdl = &sensor->hdl;
v4l2_ctrl_handler_init(hdl, 4);
v4l2_ctrl_new_std(hdl, &vs6624_ctrl_ops,
V4L2_CID_CONTRAST, 0, 0xFF, 1, 0x87);
v4l2_ctrl_new_std(hdl, &vs6624_ctrl_ops,
V4L2_CID_SATURATION, 0, 0xFF, 1, 0x78);
v4l2_ctrl_new_std(hdl, &vs6624_ctrl_ops,
V4L2_CID_HFLIP, 0, 1, 1, 0);
v4l2_ctrl_new_std(hdl, &vs6624_ctrl_ops,
V4L2_CID_VFLIP, 0, 1, 1, 0);
/* hook the control handler into the driver */
sd->ctrl_handler = hdl;
if (hdl->error) {
int err = hdl->error;
v4l2_ctrl_handler_free(hdl);
kfree(sensor);
gpio_free(*ce);
return err;
}
/* initialize the hardware to the default control values */
ret = v4l2_ctrl_handler_setup(hdl);
if (ret) {
v4l2_ctrl_handler_free(hdl);
kfree(sensor);
gpio_free(*ce);
}
return ret;
}
static int __devexit vs6624_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
struct vs6624 *sensor = to_vs6624(sd);
v4l2_device_unregister_subdev(sd);
v4l2_ctrl_handler_free(sd->ctrl_handler);
gpio_free(sensor->ce_pin);
kfree(sensor);
return 0;
}
static const struct i2c_device_id vs6624_id[] = {
{"vs6624", 0},
{},
};
MODULE_DEVICE_TABLE(i2c, vs6624_id);
static struct i2c_driver vs6624_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "vs6624",
},
.probe = vs6624_probe,
.remove = __devexit_p(vs6624_remove),
.id_table = vs6624_id,
};
static __init int vs6624_init(void)
{
return i2c_add_driver(&vs6624_driver);
}
static __exit void vs6624_exit(void)
{
i2c_del_driver(&vs6624_driver);
}
module_init(vs6624_init);
module_exit(vs6624_exit);
MODULE_DESCRIPTION("VS6624 sensor driver");
MODULE_AUTHOR("Scott Jiang <Scott.Jiang.Linux@gmail.com>");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
NormandyEGY/android_kernel_nokia_normandy | drivers/power/ds2760_battery.c | 4991 | 18472 | /*
* Driver for batteries with DS2760 chips inside.
*
* Copyright © 2007 Anton Vorontsov
* 2004-2007 Matt Reimer
* 2004 Szabolcs Gyurko
*
* Use consistent with the GNU GPL is permitted,
* provided that this copyright notice is
* preserved in its entirety in all copies and derived works.
*
* Author: Anton Vorontsov <cbou@mail.ru>
* February 2007
*
* Matt Reimer <mreimer@vpop.net>
* April 2004, 2005, 2007
*
* Szabolcs Gyurko <szabolcs.gyurko@tlt.hu>
* September 2004
*/
#include <linux/module.h>
#include <linux/param.h>
#include <linux/jiffies.h>
#include <linux/workqueue.h>
#include <linux/pm.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include "../w1/w1.h"
#include "../w1/slaves/w1_ds2760.h"
struct ds2760_device_info {
struct device *dev;
/* DS2760 data, valid after calling ds2760_battery_read_status() */
unsigned long update_time; /* jiffies when data read */
char raw[DS2760_DATA_SIZE]; /* raw DS2760 data */
int voltage_raw; /* units of 4.88 mV */
int voltage_uV; /* units of µV */
int current_raw; /* units of 0.625 mA */
int current_uA; /* units of µA */
int accum_current_raw; /* units of 0.25 mAh */
int accum_current_uAh; /* units of µAh */
int temp_raw; /* units of 0.125 °C */
int temp_C; /* units of 0.1 °C */
int rated_capacity; /* units of µAh */
int rem_capacity; /* percentage */
int full_active_uAh; /* units of µAh */
int empty_uAh; /* units of µAh */
int life_sec; /* units of seconds */
int charge_status; /* POWER_SUPPLY_STATUS_* */
int full_counter;
struct power_supply bat;
struct device *w1_dev;
struct workqueue_struct *monitor_wqueue;
struct delayed_work monitor_work;
struct delayed_work set_charged_work;
};
static unsigned int cache_time = 1000;
module_param(cache_time, uint, 0644);
MODULE_PARM_DESC(cache_time, "cache time in milliseconds");
static bool pmod_enabled;
module_param(pmod_enabled, bool, 0644);
MODULE_PARM_DESC(pmod_enabled, "PMOD enable bit");
static unsigned int rated_capacity;
module_param(rated_capacity, uint, 0644);
MODULE_PARM_DESC(rated_capacity, "rated battery capacity, 10*mAh or index");
static unsigned int current_accum;
module_param(current_accum, uint, 0644);
MODULE_PARM_DESC(current_accum, "current accumulator value");
/* Some batteries have their rated capacity stored a N * 10 mAh, while
* others use an index into this table. */
static int rated_capacities[] = {
0,
920, /* Samsung */
920, /* BYD */
920, /* Lishen */
920, /* NEC */
1440, /* Samsung */
1440, /* BYD */
#ifdef CONFIG_MACH_H4700
1800, /* HP iPAQ hx4700 3.7V 1800mAh (359113-001) */
#else
1440, /* Lishen */
#endif
1440, /* NEC */
2880, /* Samsung */
2880, /* BYD */
2880, /* Lishen */
2880, /* NEC */
#ifdef CONFIG_MACH_H4700
0,
3600, /* HP iPAQ hx4700 3.7V 3600mAh (359114-001) */
#endif
};
/* array is level at temps 0°C, 10°C, 20°C, 30°C, 40°C
* temp is in Celsius */
static int battery_interpolate(int array[], int temp)
{
int index, dt;
if (temp <= 0)
return array[0];
if (temp >= 40)
return array[4];
index = temp / 10;
dt = temp % 10;
return array[index] + (((array[index + 1] - array[index]) * dt) / 10);
}
static int ds2760_battery_read_status(struct ds2760_device_info *di)
{
int ret, i, start, count, scale[5];
if (di->update_time && time_before(jiffies, di->update_time +
msecs_to_jiffies(cache_time)))
return 0;
/* The first time we read the entire contents of SRAM/EEPROM,
* but after that we just read the interesting bits that change. */
if (di->update_time == 0) {
start = 0;
count = DS2760_DATA_SIZE;
} else {
start = DS2760_VOLTAGE_MSB;
count = DS2760_TEMP_LSB - start + 1;
}
ret = w1_ds2760_read(di->w1_dev, di->raw + start, start, count);
if (ret != count) {
dev_warn(di->dev, "call to w1_ds2760_read failed (0x%p)\n",
di->w1_dev);
return 1;
}
di->update_time = jiffies;
/* DS2760 reports voltage in units of 4.88mV, but the battery class
* reports in units of uV, so convert by multiplying by 4880. */
di->voltage_raw = (di->raw[DS2760_VOLTAGE_MSB] << 3) |
(di->raw[DS2760_VOLTAGE_LSB] >> 5);
di->voltage_uV = di->voltage_raw * 4880;
/* DS2760 reports current in signed units of 0.625mA, but the battery
* class reports in units of µA, so convert by multiplying by 625. */
di->current_raw =
(((signed char)di->raw[DS2760_CURRENT_MSB]) << 5) |
(di->raw[DS2760_CURRENT_LSB] >> 3);
di->current_uA = di->current_raw * 625;
/* DS2760 reports accumulated current in signed units of 0.25mAh. */
di->accum_current_raw =
(((signed char)di->raw[DS2760_CURRENT_ACCUM_MSB]) << 8) |
di->raw[DS2760_CURRENT_ACCUM_LSB];
di->accum_current_uAh = di->accum_current_raw * 250;
/* DS2760 reports temperature in signed units of 0.125°C, but the
* battery class reports in units of 1/10 °C, so we convert by
* multiplying by .125 * 10 = 1.25. */
di->temp_raw = (((signed char)di->raw[DS2760_TEMP_MSB]) << 3) |
(di->raw[DS2760_TEMP_LSB] >> 5);
di->temp_C = di->temp_raw + (di->temp_raw / 4);
/* At least some battery monitors (e.g. HP iPAQ) store the battery's
* maximum rated capacity. */
if (di->raw[DS2760_RATED_CAPACITY] < ARRAY_SIZE(rated_capacities))
di->rated_capacity = rated_capacities[
(unsigned int)di->raw[DS2760_RATED_CAPACITY]];
else
di->rated_capacity = di->raw[DS2760_RATED_CAPACITY] * 10;
di->rated_capacity *= 1000; /* convert to µAh */
/* Calculate the full level at the present temperature. */
di->full_active_uAh = di->raw[DS2760_ACTIVE_FULL] << 8 |
di->raw[DS2760_ACTIVE_FULL + 1];
/* If the full_active_uAh value is not given, fall back to the rated
* capacity. This is likely to happen when chips are not part of the
* battery pack and is therefore not bootstrapped. */
if (di->full_active_uAh == 0)
di->full_active_uAh = di->rated_capacity / 1000L;
scale[0] = di->full_active_uAh;
for (i = 1; i < 5; i++)
scale[i] = scale[i - 1] + di->raw[DS2760_ACTIVE_FULL + 1 + i];
di->full_active_uAh = battery_interpolate(scale, di->temp_C / 10);
di->full_active_uAh *= 1000; /* convert to µAh */
/* Calculate the empty level at the present temperature. */
scale[4] = di->raw[DS2760_ACTIVE_EMPTY + 4];
for (i = 3; i >= 0; i--)
scale[i] = scale[i + 1] + di->raw[DS2760_ACTIVE_EMPTY + i];
di->empty_uAh = battery_interpolate(scale, di->temp_C / 10);
di->empty_uAh *= 1000; /* convert to µAh */
if (di->full_active_uAh == di->empty_uAh)
di->rem_capacity = 0;
else
/* From Maxim Application Note 131: remaining capacity =
* ((ICA - Empty Value) / (Full Value - Empty Value)) x 100% */
di->rem_capacity = ((di->accum_current_uAh - di->empty_uAh) * 100L) /
(di->full_active_uAh - di->empty_uAh);
if (di->rem_capacity < 0)
di->rem_capacity = 0;
if (di->rem_capacity > 100)
di->rem_capacity = 100;
if (di->current_uA < -100L)
di->life_sec = -((di->accum_current_uAh - di->empty_uAh) * 36L)
/ (di->current_uA / 100L);
else
di->life_sec = 0;
return 0;
}
static void ds2760_battery_set_current_accum(struct ds2760_device_info *di,
unsigned int acr_val)
{
unsigned char acr[2];
/* acr is in units of 0.25 mAh */
acr_val *= 4L;
acr_val /= 1000;
acr[0] = acr_val >> 8;
acr[1] = acr_val & 0xff;
if (w1_ds2760_write(di->w1_dev, acr, DS2760_CURRENT_ACCUM_MSB, 2) < 2)
dev_warn(di->dev, "ACR write failed\n");
}
static void ds2760_battery_update_status(struct ds2760_device_info *di)
{
int old_charge_status = di->charge_status;
ds2760_battery_read_status(di);
if (di->charge_status == POWER_SUPPLY_STATUS_UNKNOWN)
di->full_counter = 0;
if (power_supply_am_i_supplied(&di->bat)) {
if (di->current_uA > 10000) {
di->charge_status = POWER_SUPPLY_STATUS_CHARGING;
di->full_counter = 0;
} else if (di->current_uA < -5000) {
if (di->charge_status != POWER_SUPPLY_STATUS_NOT_CHARGING)
dev_notice(di->dev, "not enough power to "
"charge\n");
di->charge_status = POWER_SUPPLY_STATUS_NOT_CHARGING;
di->full_counter = 0;
} else if (di->current_uA < 10000 &&
di->charge_status != POWER_SUPPLY_STATUS_FULL) {
/* Don't consider the battery to be full unless
* we've seen the current < 10 mA at least two
* consecutive times. */
di->full_counter++;
if (di->full_counter < 2) {
di->charge_status = POWER_SUPPLY_STATUS_CHARGING;
} else {
di->charge_status = POWER_SUPPLY_STATUS_FULL;
ds2760_battery_set_current_accum(di,
di->full_active_uAh);
}
}
} else {
di->charge_status = POWER_SUPPLY_STATUS_DISCHARGING;
di->full_counter = 0;
}
if (di->charge_status != old_charge_status)
power_supply_changed(&di->bat);
}
static void ds2760_battery_write_status(struct ds2760_device_info *di,
char status)
{
if (status == di->raw[DS2760_STATUS_REG])
return;
w1_ds2760_write(di->w1_dev, &status, DS2760_STATUS_WRITE_REG, 1);
w1_ds2760_store_eeprom(di->w1_dev, DS2760_EEPROM_BLOCK1);
w1_ds2760_recall_eeprom(di->w1_dev, DS2760_EEPROM_BLOCK1);
}
static void ds2760_battery_write_rated_capacity(struct ds2760_device_info *di,
unsigned char rated_capacity)
{
if (rated_capacity == di->raw[DS2760_RATED_CAPACITY])
return;
w1_ds2760_write(di->w1_dev, &rated_capacity, DS2760_RATED_CAPACITY, 1);
w1_ds2760_store_eeprom(di->w1_dev, DS2760_EEPROM_BLOCK1);
w1_ds2760_recall_eeprom(di->w1_dev, DS2760_EEPROM_BLOCK1);
}
static void ds2760_battery_write_active_full(struct ds2760_device_info *di,
int active_full)
{
unsigned char tmp[2] = {
active_full >> 8,
active_full & 0xff
};
if (tmp[0] == di->raw[DS2760_ACTIVE_FULL] &&
tmp[1] == di->raw[DS2760_ACTIVE_FULL + 1])
return;
w1_ds2760_write(di->w1_dev, tmp, DS2760_ACTIVE_FULL, sizeof(tmp));
w1_ds2760_store_eeprom(di->w1_dev, DS2760_EEPROM_BLOCK0);
w1_ds2760_recall_eeprom(di->w1_dev, DS2760_EEPROM_BLOCK0);
/* Write to the di->raw[] buffer directly - the DS2760_ACTIVE_FULL
* values won't be read back by ds2760_battery_read_status() */
di->raw[DS2760_ACTIVE_FULL] = tmp[0];
di->raw[DS2760_ACTIVE_FULL + 1] = tmp[1];
}
static void ds2760_battery_work(struct work_struct *work)
{
struct ds2760_device_info *di = container_of(work,
struct ds2760_device_info, monitor_work.work);
const int interval = HZ * 60;
dev_dbg(di->dev, "%s\n", __func__);
ds2760_battery_update_status(di);
queue_delayed_work(di->monitor_wqueue, &di->monitor_work, interval);
}
#define to_ds2760_device_info(x) container_of((x), struct ds2760_device_info, \
bat);
static void ds2760_battery_external_power_changed(struct power_supply *psy)
{
struct ds2760_device_info *di = to_ds2760_device_info(psy);
dev_dbg(di->dev, "%s\n", __func__);
cancel_delayed_work(&di->monitor_work);
queue_delayed_work(di->monitor_wqueue, &di->monitor_work, HZ/10);
}
static void ds2760_battery_set_charged_work(struct work_struct *work)
{
char bias;
struct ds2760_device_info *di = container_of(work,
struct ds2760_device_info, set_charged_work.work);
dev_dbg(di->dev, "%s\n", __func__);
ds2760_battery_read_status(di);
/* When we get notified by external circuitry that the battery is
* considered fully charged now, we know that there is no current
* flow any more. However, the ds2760's internal current meter is
* too inaccurate to rely on - spec say something ~15% failure.
* Hence, we use the current offset bias register to compensate
* that error.
*/
if (!power_supply_am_i_supplied(&di->bat))
return;
bias = (signed char) di->current_raw +
(signed char) di->raw[DS2760_CURRENT_OFFSET_BIAS];
dev_dbg(di->dev, "%s: bias = %d\n", __func__, bias);
w1_ds2760_write(di->w1_dev, &bias, DS2760_CURRENT_OFFSET_BIAS, 1);
w1_ds2760_store_eeprom(di->w1_dev, DS2760_EEPROM_BLOCK1);
w1_ds2760_recall_eeprom(di->w1_dev, DS2760_EEPROM_BLOCK1);
/* Write to the di->raw[] buffer directly - the CURRENT_OFFSET_BIAS
* value won't be read back by ds2760_battery_read_status() */
di->raw[DS2760_CURRENT_OFFSET_BIAS] = bias;
}
static void ds2760_battery_set_charged(struct power_supply *psy)
{
struct ds2760_device_info *di = to_ds2760_device_info(psy);
/* postpone the actual work by 20 secs. This is for debouncing GPIO
* signals and to let the current value settle. See AN4188. */
cancel_delayed_work(&di->set_charged_work);
queue_delayed_work(di->monitor_wqueue, &di->set_charged_work, HZ * 20);
}
static int ds2760_battery_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct ds2760_device_info *di = to_ds2760_device_info(psy);
switch (psp) {
case POWER_SUPPLY_PROP_STATUS:
val->intval = di->charge_status;
return 0;
default:
break;
}
ds2760_battery_read_status(di);
switch (psp) {
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
val->intval = di->voltage_uV;
break;
case POWER_SUPPLY_PROP_CURRENT_NOW:
val->intval = di->current_uA;
break;
case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
val->intval = di->rated_capacity;
break;
case POWER_SUPPLY_PROP_CHARGE_FULL:
val->intval = di->full_active_uAh;
break;
case POWER_SUPPLY_PROP_CHARGE_EMPTY:
val->intval = di->empty_uAh;
break;
case POWER_SUPPLY_PROP_CHARGE_NOW:
val->intval = di->accum_current_uAh;
break;
case POWER_SUPPLY_PROP_TEMP:
val->intval = di->temp_C;
break;
case POWER_SUPPLY_PROP_TIME_TO_EMPTY_NOW:
val->intval = di->life_sec;
break;
case POWER_SUPPLY_PROP_CAPACITY:
val->intval = di->rem_capacity;
break;
default:
return -EINVAL;
}
return 0;
}
static int ds2760_battery_set_property(struct power_supply *psy,
enum power_supply_property psp,
const union power_supply_propval *val)
{
struct ds2760_device_info *di = to_ds2760_device_info(psy);
switch (psp) {
case POWER_SUPPLY_PROP_CHARGE_FULL:
/* the interface counts in uAh, convert the value */
ds2760_battery_write_active_full(di, val->intval / 1000L);
break;
case POWER_SUPPLY_PROP_CHARGE_NOW:
/* ds2760_battery_set_current_accum() does the conversion */
ds2760_battery_set_current_accum(di, val->intval);
break;
default:
return -EPERM;
}
return 0;
}
static int ds2760_battery_property_is_writeable(struct power_supply *psy,
enum power_supply_property psp)
{
switch (psp) {
case POWER_SUPPLY_PROP_CHARGE_FULL:
case POWER_SUPPLY_PROP_CHARGE_NOW:
return 1;
default:
break;
}
return 0;
}
static enum power_supply_property ds2760_battery_props[] = {
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_CURRENT_NOW,
POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
POWER_SUPPLY_PROP_CHARGE_FULL,
POWER_SUPPLY_PROP_CHARGE_EMPTY,
POWER_SUPPLY_PROP_CHARGE_NOW,
POWER_SUPPLY_PROP_TEMP,
POWER_SUPPLY_PROP_TIME_TO_EMPTY_NOW,
POWER_SUPPLY_PROP_CAPACITY,
};
static int ds2760_battery_probe(struct platform_device *pdev)
{
char status;
int retval = 0;
struct ds2760_device_info *di;
di = kzalloc(sizeof(*di), GFP_KERNEL);
if (!di) {
retval = -ENOMEM;
goto di_alloc_failed;
}
platform_set_drvdata(pdev, di);
di->dev = &pdev->dev;
di->w1_dev = pdev->dev.parent;
di->bat.name = dev_name(&pdev->dev);
di->bat.type = POWER_SUPPLY_TYPE_BATTERY;
di->bat.properties = ds2760_battery_props;
di->bat.num_properties = ARRAY_SIZE(ds2760_battery_props);
di->bat.get_property = ds2760_battery_get_property;
di->bat.set_property = ds2760_battery_set_property;
di->bat.property_is_writeable =
ds2760_battery_property_is_writeable;
di->bat.set_charged = ds2760_battery_set_charged;
di->bat.external_power_changed =
ds2760_battery_external_power_changed;
di->charge_status = POWER_SUPPLY_STATUS_UNKNOWN;
/* enable sleep mode feature */
ds2760_battery_read_status(di);
status = di->raw[DS2760_STATUS_REG];
if (pmod_enabled)
status |= DS2760_STATUS_PMOD;
else
status &= ~DS2760_STATUS_PMOD;
ds2760_battery_write_status(di, status);
/* set rated capacity from module param */
if (rated_capacity)
ds2760_battery_write_rated_capacity(di, rated_capacity);
/* set current accumulator if given as parameter.
* this should only be done for bootstrapping the value */
if (current_accum)
ds2760_battery_set_current_accum(di, current_accum);
retval = power_supply_register(&pdev->dev, &di->bat);
if (retval) {
dev_err(di->dev, "failed to register battery\n");
goto batt_failed;
}
INIT_DELAYED_WORK(&di->monitor_work, ds2760_battery_work);
INIT_DELAYED_WORK(&di->set_charged_work,
ds2760_battery_set_charged_work);
di->monitor_wqueue = create_singlethread_workqueue(dev_name(&pdev->dev));
if (!di->monitor_wqueue) {
retval = -ESRCH;
goto workqueue_failed;
}
queue_delayed_work(di->monitor_wqueue, &di->monitor_work, HZ * 1);
goto success;
workqueue_failed:
power_supply_unregister(&di->bat);
batt_failed:
kfree(di);
di_alloc_failed:
success:
return retval;
}
static int ds2760_battery_remove(struct platform_device *pdev)
{
struct ds2760_device_info *di = platform_get_drvdata(pdev);
cancel_delayed_work_sync(&di->monitor_work);
cancel_delayed_work_sync(&di->set_charged_work);
destroy_workqueue(di->monitor_wqueue);
power_supply_unregister(&di->bat);
kfree(di);
return 0;
}
#ifdef CONFIG_PM
static int ds2760_battery_suspend(struct platform_device *pdev,
pm_message_t state)
{
struct ds2760_device_info *di = platform_get_drvdata(pdev);
di->charge_status = POWER_SUPPLY_STATUS_UNKNOWN;
return 0;
}
static int ds2760_battery_resume(struct platform_device *pdev)
{
struct ds2760_device_info *di = platform_get_drvdata(pdev);
di->charge_status = POWER_SUPPLY_STATUS_UNKNOWN;
power_supply_changed(&di->bat);
cancel_delayed_work(&di->monitor_work);
queue_delayed_work(di->monitor_wqueue, &di->monitor_work, HZ);
return 0;
}
#else
#define ds2760_battery_suspend NULL
#define ds2760_battery_resume NULL
#endif /* CONFIG_PM */
MODULE_ALIAS("platform:ds2760-battery");
static struct platform_driver ds2760_battery_driver = {
.driver = {
.name = "ds2760-battery",
},
.probe = ds2760_battery_probe,
.remove = ds2760_battery_remove,
.suspend = ds2760_battery_suspend,
.resume = ds2760_battery_resume,
};
module_platform_driver(ds2760_battery_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Szabolcs Gyurko <szabolcs.gyurko@tlt.hu>, "
"Matt Reimer <mreimer@vpop.net>, "
"Anton Vorontsov <cbou@mail.ru>");
MODULE_DESCRIPTION("ds2760 battery driver");
| gpl-2.0 |
CyanogenMod/android_kernel_lge_ls970 | drivers/media/video/bt8xx/bttv-input.c | 5247 | 14049 | /*
*
* Copyright (c) 2003 Gerd Knorr
* Copyright (c) 2003 Pavel Machek
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/slab.h>
#include "bttv.h"
#include "bttvp.h"
static int ir_debug;
module_param(ir_debug, int, 0644);
static int ir_rc5_remote_gap = 885;
module_param(ir_rc5_remote_gap, int, 0644);
#undef dprintk
#define dprintk(fmt, ...) \
do { \
if (ir_debug >= 1) \
pr_info(fmt, ##__VA_ARGS__); \
} while (0)
#define DEVNAME "bttv-input"
#define MODULE_NAME "bttv"
/* ---------------------------------------------------------------------- */
static void ir_handle_key(struct bttv *btv)
{
struct bttv_ir *ir = btv->remote;
u32 gpio,data;
/* read gpio value */
gpio = bttv_gpio_read(&btv->c);
if (ir->polling) {
if (ir->last_gpio == gpio)
return;
ir->last_gpio = gpio;
}
/* extract data */
data = ir_extract_bits(gpio, ir->mask_keycode);
dprintk("irq gpio=0x%x code=%d | %s%s%s\n",
gpio, data,
ir->polling ? "poll" : "irq",
(gpio & ir->mask_keydown) ? " down" : "",
(gpio & ir->mask_keyup) ? " up" : "");
if ((ir->mask_keydown && (gpio & ir->mask_keydown)) ||
(ir->mask_keyup && !(gpio & ir->mask_keyup))) {
rc_keydown_notimeout(ir->dev, data, 0);
} else {
/* HACK: Probably, ir->mask_keydown is missing
for this board */
if (btv->c.type == BTTV_BOARD_WINFAST2000)
rc_keydown_notimeout(ir->dev, data, 0);
rc_keyup(ir->dev);
}
}
static void ir_enltv_handle_key(struct bttv *btv)
{
struct bttv_ir *ir = btv->remote;
u32 gpio, data, keyup;
/* read gpio value */
gpio = bttv_gpio_read(&btv->c);
/* extract data */
data = ir_extract_bits(gpio, ir->mask_keycode);
/* Check if it is keyup */
keyup = (gpio & ir->mask_keyup) ? 1 << 31 : 0;
if ((ir->last_gpio & 0x7f) != data) {
dprintk("gpio=0x%x code=%d | %s\n",
gpio, data,
(gpio & ir->mask_keyup) ? " up" : "up/down");
rc_keydown_notimeout(ir->dev, data, 0);
if (keyup)
rc_keyup(ir->dev);
} else {
if ((ir->last_gpio & 1 << 31) == keyup)
return;
dprintk("(cnt) gpio=0x%x code=%d | %s\n",
gpio, data,
(gpio & ir->mask_keyup) ? " up" : "down");
if (keyup)
rc_keyup(ir->dev);
else
rc_keydown_notimeout(ir->dev, data, 0);
}
ir->last_gpio = data | keyup;
}
static int bttv_rc5_irq(struct bttv *btv);
void bttv_input_irq(struct bttv *btv)
{
struct bttv_ir *ir = btv->remote;
if (ir->rc5_gpio)
bttv_rc5_irq(btv);
else if (!ir->polling)
ir_handle_key(btv);
}
static void bttv_input_timer(unsigned long data)
{
struct bttv *btv = (struct bttv*)data;
struct bttv_ir *ir = btv->remote;
if (btv->c.type == BTTV_BOARD_ENLTV_FM_2)
ir_enltv_handle_key(btv);
else
ir_handle_key(btv);
mod_timer(&ir->timer, jiffies + msecs_to_jiffies(ir->polling));
}
/*
* FIXME: Nebula digi uses the legacy way to decode RC5, instead of relying
* on the rc-core way. As we need to be sure that both IRQ transitions are
* properly triggered, Better to touch it only with this hardware for
* testing.
*/
#define RC5_START(x) (((x) >> 12) & 3)
#define RC5_TOGGLE(x) (((x) >> 11) & 1)
#define RC5_ADDR(x) (((x) >> 6) & 31)
#define RC5_INSTR(x) ((x) & 63)
/* decode raw bit pattern to RC5 code */
static u32 bttv_rc5_decode(unsigned int code)
{
unsigned int org_code = code;
unsigned int pair;
unsigned int rc5 = 0;
int i;
for (i = 0; i < 14; ++i) {
pair = code & 0x3;
code >>= 2;
rc5 <<= 1;
switch (pair) {
case 0:
case 2:
break;
case 1:
rc5 |= 1;
break;
case 3:
dprintk("rc5_decode(%x) bad code\n",
org_code);
return 0;
}
}
dprintk("code=%x, rc5=%x, start=%x, toggle=%x, address=%x, "
"instr=%x\n", rc5, org_code, RC5_START(rc5),
RC5_TOGGLE(rc5), RC5_ADDR(rc5), RC5_INSTR(rc5));
return rc5;
}
static void bttv_rc5_timer_end(unsigned long data)
{
struct bttv_ir *ir = (struct bttv_ir *)data;
struct timeval tv;
u32 gap;
u32 rc5 = 0;
/* get time */
do_gettimeofday(&tv);
/* avoid overflow with gap >1s */
if (tv.tv_sec - ir->base_time.tv_sec > 1) {
gap = 200000;
} else {
gap = 1000000 * (tv.tv_sec - ir->base_time.tv_sec) +
tv.tv_usec - ir->base_time.tv_usec;
}
/* signal we're ready to start a new code */
ir->active = false;
/* Allow some timer jitter (RC5 is ~24ms anyway so this is ok) */
if (gap < 28000) {
dprintk("spurious timer_end\n");
return;
}
if (ir->last_bit < 20) {
/* ignore spurious codes (caused by light/other remotes) */
dprintk("short code: %x\n", ir->code);
} else {
ir->code = (ir->code << ir->shift_by) | 1;
rc5 = bttv_rc5_decode(ir->code);
/* two start bits? */
if (RC5_START(rc5) != ir->start) {
pr_info(DEVNAME ":"
" rc5 start bits invalid: %u\n", RC5_START(rc5));
/* right address? */
} else if (RC5_ADDR(rc5) == ir->addr) {
u32 toggle = RC5_TOGGLE(rc5);
u32 instr = RC5_INSTR(rc5);
/* Good code */
rc_keydown(ir->dev, instr, toggle);
dprintk("instruction %x, toggle %x\n",
instr, toggle);
}
}
}
static int bttv_rc5_irq(struct bttv *btv)
{
struct bttv_ir *ir = btv->remote;
struct timeval tv;
u32 gpio;
u32 gap;
unsigned long current_jiffies;
/* read gpio port */
gpio = bttv_gpio_read(&btv->c);
/* get time of bit */
current_jiffies = jiffies;
do_gettimeofday(&tv);
/* avoid overflow with gap >1s */
if (tv.tv_sec - ir->base_time.tv_sec > 1) {
gap = 200000;
} else {
gap = 1000000 * (tv.tv_sec - ir->base_time.tv_sec) +
tv.tv_usec - ir->base_time.tv_usec;
}
dprintk("RC5 IRQ: gap %d us for %s\n",
gap, (gpio & 0x20) ? "mark" : "space");
/* remote IRQ? */
if (!(gpio & 0x20))
return 0;
/* active code => add bit */
if (ir->active) {
/* only if in the code (otherwise spurious IRQ or timer
late) */
if (ir->last_bit < 28) {
ir->last_bit = (gap - ir_rc5_remote_gap / 2) /
ir_rc5_remote_gap;
ir->code |= 1 << ir->last_bit;
}
/* starting new code */
} else {
ir->active = true;
ir->code = 0;
ir->base_time = tv;
ir->last_bit = 0;
mod_timer(&ir->timer, current_jiffies + msecs_to_jiffies(30));
}
/* toggle GPIO pin 4 to reset the irq */
bttv_gpio_write(&btv->c, gpio & ~(1 << 4));
bttv_gpio_write(&btv->c, gpio | (1 << 4));
return 1;
}
/* ---------------------------------------------------------------------- */
static void bttv_ir_start(struct bttv *btv, struct bttv_ir *ir)
{
if (ir->polling) {
setup_timer(&ir->timer, bttv_input_timer, (unsigned long)btv);
ir->timer.expires = jiffies + msecs_to_jiffies(1000);
add_timer(&ir->timer);
} else if (ir->rc5_gpio) {
/* set timer_end for code completion */
setup_timer(&ir->timer, bttv_rc5_timer_end, (unsigned long)ir);
ir->shift_by = 1;
ir->start = 3;
ir->addr = 0x0;
ir->rc5_remote_gap = ir_rc5_remote_gap;
}
}
static void bttv_ir_stop(struct bttv *btv)
{
if (btv->remote->polling)
del_timer_sync(&btv->remote->timer);
if (btv->remote->rc5_gpio) {
u32 gpio;
del_timer_sync(&btv->remote->timer);
gpio = bttv_gpio_read(&btv->c);
bttv_gpio_write(&btv->c, gpio & ~(1 << 4));
}
}
/*
* Get_key functions used by I2C remotes
*/
static int get_key_pv951(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
unsigned char b;
/* poll IR chip */
if (1 != i2c_master_recv(ir->c, &b, 1)) {
dprintk("read error\n");
return -EIO;
}
/* ignore 0xaa */
if (b==0xaa)
return 0;
dprintk("key %02x\n", b);
/*
* NOTE:
* lirc_i2c maps the pv951 code as:
* addr = 0x61D6
* cmd = bit_reverse (b)
* So, it seems that this device uses NEC extended
* I decided to not fix the table, due to two reasons:
* 1) Without the actual device, this is only a guess;
* 2) As the addr is not reported via I2C, nor can be changed,
* the device is bound to the vendor-provided RC.
*/
*ir_key = b;
*ir_raw = b;
return 1;
}
/* Instantiate the I2C IR receiver device, if present */
void __devinit init_bttv_i2c_ir(struct bttv *btv)
{
const unsigned short addr_list[] = {
0x1a, 0x18, 0x64, 0x30, 0x71,
I2C_CLIENT_END
};
struct i2c_board_info info;
if (0 != btv->i2c_rc)
return;
memset(&info, 0, sizeof(struct i2c_board_info));
memset(&btv->init_data, 0, sizeof(btv->init_data));
strlcpy(info.type, "ir_video", I2C_NAME_SIZE);
switch (btv->c.type) {
case BTTV_BOARD_PV951:
btv->init_data.name = "PV951";
btv->init_data.get_key = get_key_pv951;
btv->init_data.ir_codes = RC_MAP_PV951;
info.addr = 0x4b;
break;
default:
/*
* The external IR receiver is at i2c address 0x34 (0x35 for
* reads). Future Hauppauge cards will have an internal
* receiver at 0x30 (0x31 for reads). In theory, both can be
* fitted, and Hauppauge suggest an external overrides an
* internal.
* That's why we probe 0x1a (~0x34) first. CB
*/
i2c_new_probed_device(&btv->c.i2c_adap, &info, addr_list, NULL);
return;
}
if (btv->init_data.name)
info.platform_data = &btv->init_data;
i2c_new_device(&btv->c.i2c_adap, &info);
return;
}
int __devexit fini_bttv_i2c(struct bttv *btv)
{
if (0 != btv->i2c_rc)
return 0;
return i2c_del_adapter(&btv->c.i2c_adap);
}
int bttv_input_init(struct bttv *btv)
{
struct bttv_ir *ir;
char *ir_codes = NULL;
struct rc_dev *rc;
int err = -ENOMEM;
if (!btv->has_remote)
return -ENODEV;
ir = kzalloc(sizeof(*ir),GFP_KERNEL);
rc = rc_allocate_device();
if (!ir || !rc)
goto err_out_free;
/* detect & configure */
switch (btv->c.type) {
case BTTV_BOARD_AVERMEDIA:
case BTTV_BOARD_AVPHONE98:
case BTTV_BOARD_AVERMEDIA98:
ir_codes = RC_MAP_AVERMEDIA;
ir->mask_keycode = 0xf88000;
ir->mask_keydown = 0x010000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_AVDVBT_761:
case BTTV_BOARD_AVDVBT_771:
ir_codes = RC_MAP_AVERMEDIA_DVBT;
ir->mask_keycode = 0x0f00c0;
ir->mask_keydown = 0x000020;
ir->polling = 50; // ms
break;
case BTTV_BOARD_PXELVWPLTVPAK:
ir_codes = RC_MAP_PIXELVIEW;
ir->mask_keycode = 0x003e00;
ir->mask_keyup = 0x010000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_PV_M4900:
case BTTV_BOARD_PV_BT878P_9B:
case BTTV_BOARD_PV_BT878P_PLUS:
ir_codes = RC_MAP_PIXELVIEW;
ir->mask_keycode = 0x001f00;
ir->mask_keyup = 0x008000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_WINFAST2000:
ir_codes = RC_MAP_WINFAST;
ir->mask_keycode = 0x1f8;
break;
case BTTV_BOARD_MAGICTVIEW061:
case BTTV_BOARD_MAGICTVIEW063:
ir_codes = RC_MAP_WINFAST;
ir->mask_keycode = 0x0008e000;
ir->mask_keydown = 0x00200000;
break;
case BTTV_BOARD_APAC_VIEWCOMP:
ir_codes = RC_MAP_APAC_VIEWCOMP;
ir->mask_keycode = 0x001f00;
ir->mask_keyup = 0x008000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_ASKEY_CPH03X:
case BTTV_BOARD_CONCEPTRONIC_CTVFMI2:
case BTTV_BOARD_CONTVFMI:
ir_codes = RC_MAP_PIXELVIEW;
ir->mask_keycode = 0x001F00;
ir->mask_keyup = 0x006000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_NEBULA_DIGITV:
ir_codes = RC_MAP_NEBULA;
ir->rc5_gpio = true;
break;
case BTTV_BOARD_MACHTV_MAGICTV:
ir_codes = RC_MAP_APAC_VIEWCOMP;
ir->mask_keycode = 0x001F00;
ir->mask_keyup = 0x004000;
ir->polling = 50; /* ms */
break;
case BTTV_BOARD_KOZUMI_KTV_01C:
ir_codes = RC_MAP_PCTV_SEDNA;
ir->mask_keycode = 0x001f00;
ir->mask_keyup = 0x006000;
ir->polling = 50; /* ms */
break;
case BTTV_BOARD_ENLTV_FM_2:
ir_codes = RC_MAP_ENCORE_ENLTV2;
ir->mask_keycode = 0x00fd00;
ir->mask_keyup = 0x000080;
ir->polling = 1; /* ms */
ir->last_gpio = ir_extract_bits(bttv_gpio_read(&btv->c),
ir->mask_keycode);
break;
}
if (NULL == ir_codes) {
dprintk("Ooops: IR config error [card=%d]\n", btv->c.type);
err = -ENODEV;
goto err_out_free;
}
if (ir->rc5_gpio) {
u32 gpio;
/* enable remote irq */
bttv_gpio_inout(&btv->c, (1 << 4), 1 << 4);
gpio = bttv_gpio_read(&btv->c);
bttv_gpio_write(&btv->c, gpio & ~(1 << 4));
bttv_gpio_write(&btv->c, gpio | (1 << 4));
} else {
/* init hardware-specific stuff */
bttv_gpio_inout(&btv->c, ir->mask_keycode | ir->mask_keydown, 0);
}
/* init input device */
ir->dev = rc;
snprintf(ir->name, sizeof(ir->name), "bttv IR (card=%d)",
btv->c.type);
snprintf(ir->phys, sizeof(ir->phys), "pci-%s/ir0",
pci_name(btv->c.pci));
rc->input_name = ir->name;
rc->input_phys = ir->phys;
rc->input_id.bustype = BUS_PCI;
rc->input_id.version = 1;
if (btv->c.pci->subsystem_vendor) {
rc->input_id.vendor = btv->c.pci->subsystem_vendor;
rc->input_id.product = btv->c.pci->subsystem_device;
} else {
rc->input_id.vendor = btv->c.pci->vendor;
rc->input_id.product = btv->c.pci->device;
}
rc->dev.parent = &btv->c.pci->dev;
rc->map_name = ir_codes;
rc->driver_name = MODULE_NAME;
btv->remote = ir;
bttv_ir_start(btv, ir);
/* all done */
err = rc_register_device(rc);
if (err)
goto err_out_stop;
return 0;
err_out_stop:
bttv_ir_stop(btv);
btv->remote = NULL;
err_out_free:
rc_free_device(rc);
kfree(ir);
return err;
}
void bttv_input_fini(struct bttv *btv)
{
if (btv->remote == NULL)
return;
bttv_ir_stop(btv);
rc_unregister_device(btv->remote->dev);
kfree(btv->remote);
btv->remote = NULL;
}
| gpl-2.0 |
srisurya95/android_kernel_motorola_msm8226 | drivers/usb/image/microtek.c | 7551 | 23425 | /* Driver for Microtek Scanmaker X6 USB scanner, and possibly others.
*
* (C) Copyright 2000 John Fremlin <vii@penguinpowered.com>
* (C) Copyright 2000 Oliver Neukum <Oliver.Neukum@lrz.uni-muenchen.de>
*
* Parts shamelessly stolen from usb-storage and copyright by their
* authors. Thanks to Matt Dharm for giving us permission!
*
* This driver implements a SCSI host controller driver and a USB
* device driver. To avoid confusion, all the USB related stuff is
* prefixed by mts_usb_ and all the SCSI stuff by mts_scsi_.
*
* Microtek (www.microtek.com) did not release the specifications for
* their USB protocol to us, so we had to reverse engineer them. We
* don't know for which models they are valid.
*
* The X6 USB has three bulk endpoints, one output (0x1) down which
* commands and outgoing data are sent, and two input: 0x82 from which
* normal data is read from the scanner (in packets of maximum 32
* bytes) and from which the status byte is read, and 0x83 from which
* the results of a scan (or preview) are read in up to 64 * 1024 byte
* chunks by the Windows driver. We don't know how much it is possible
* to read at a time from 0x83.
*
* It seems possible to read (with URB transfers) everything from 0x82
* in one go, without bothering to read in 32 byte chunks.
*
* There seems to be an optimisation of a further READ implicit if
* you simply read from 0x83.
*
* Guessed protocol:
*
* Send raw SCSI command to EP 0x1
*
* If there is data to receive:
* If the command was READ datatype=image:
* Read a lot of data from EP 0x83
* Else:
* Read data from EP 0x82
* Else:
* If there is data to transmit:
* Write it to EP 0x1
*
* Read status byte from EP 0x82
*
* References:
*
* The SCSI command set for the scanner is available from
* ftp://ftp.microtek.com/microtek/devpack/
*
* Microtek NV sent us a more up to date version of the document. If
* you want it, just send mail.
*
* Status:
*
* Untested with multiple scanners.
* Untested on SMP.
* Untested on a bigendian machine.
*
* History:
*
* 20000417 starting history
* 20000417 fixed load oops
* 20000417 fixed unload oops
* 20000419 fixed READ IMAGE detection
* 20000424 started conversion to use URBs
* 20000502 handled short transfers as errors
* 20000513 rename and organisation of functions (john)
* 20000513 added IDs for all products supported by Windows driver (john)
* 20000514 Rewrote mts_scsi_queuecommand to use URBs (john)
* 20000514 Version 0.0.8j
* 20000514 Fix reporting of non-existent devices to SCSI layer (john)
* 20000514 Added MTS_DEBUG_INT (john)
* 20000514 Changed "usb-microtek" to "microtek" for consistency (john)
* 20000514 Stupid bug fixes (john)
* 20000514 Version 0.0.9j
* 20000515 Put transfer context and URB in mts_desc (john)
* 20000515 Added prelim turn off debugging support (john)
* 20000515 Version 0.0.10j
* 20000515 Fixed up URB allocation (clear URB on alloc) (john)
* 20000515 Version 0.0.11j
* 20000516 Removed unnecessary spinlock in mts_transfer_context (john)
* 20000516 Removed unnecessary up on instance lock in mts_remove_nolock (john)
* 20000516 Implemented (badly) scsi_abort (john)
* 20000516 Version 0.0.12j
* 20000517 Hopefully removed mts_remove_nolock quasideadlock (john)
* 20000517 Added mts_debug_dump to print ll USB info (john)
* 20000518 Tweaks and documentation updates (john)
* 20000518 Version 0.0.13j
* 20000518 Cleaned up abort handling (john)
* 20000523 Removed scsi_command and various scsi_..._resets (john)
* 20000523 Added unlink URB on scsi_abort, now OHCI supports it (john)
* 20000523 Fixed last tiresome compile warning (john)
* 20000523 Version 0.0.14j (though version 0.1 has come out?)
* 20000602 Added primitive reset
* 20000602 Version 0.2.0
* 20000603 various cosmetic changes
* 20000603 Version 0.2.1
* 20000620 minor cosmetic changes
* 20000620 Version 0.2.2
* 20000822 Hopefully fixed deadlock in mts_remove_nolock()
* 20000822 Fixed minor race in mts_transfer_cleanup()
* 20000822 Fixed deadlock on submission error in queuecommand
* 20000822 Version 0.2.3
* 20000913 Reduced module size if debugging is off
* 20000913 Version 0.2.4
* 20010210 New abort logic
* 20010210 Version 0.3.0
* 20010217 Merged scatter/gather
* 20010218 Version 0.4.0
* 20010218 Cosmetic fixes
* 20010218 Version 0.4.1
* 20010306 Abort while using scatter/gather
* 20010306 Version 0.4.2
* 20010311 Remove all timeouts and tidy up generally (john)
* 20010320 check return value of scsi_register()
* 20010320 Version 0.4.3
* 20010408 Identify version on module load.
* 20011003 Fix multiple requests
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/random.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/usb.h>
#include <linux/proc_fs.h>
#include <linux/atomic.h>
#include <linux/blkdev.h>
#include "../../scsi/scsi.h"
#include <scsi/scsi_host.h>
#include "microtek.h"
/*
* Version Information
*/
#define DRIVER_VERSION "v0.4.3"
#define DRIVER_AUTHOR "John Fremlin <vii@penguinpowered.com>, Oliver Neukum <Oliver.Neukum@lrz.uni-muenchen.de>"
#define DRIVER_DESC "Microtek Scanmaker X6 USB scanner driver"
/* Should we do debugging? */
//#define MTS_DO_DEBUG
/* USB layer driver interface */
static int mts_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id);
static void mts_usb_disconnect(struct usb_interface *intf);
static const struct usb_device_id mts_usb_ids[];
static struct usb_driver mts_usb_driver = {
.name = "microtekX6",
.probe = mts_usb_probe,
.disconnect = mts_usb_disconnect,
.id_table = mts_usb_ids,
};
/* Internal driver stuff */
#define MTS_VERSION "0.4.3"
#define MTS_NAME "microtek usb (rev " MTS_VERSION "): "
#define MTS_WARNING(x...) \
printk( KERN_WARNING MTS_NAME x )
#define MTS_ERROR(x...) \
printk( KERN_ERR MTS_NAME x )
#define MTS_INT_ERROR(x...) \
MTS_ERROR(x)
#define MTS_MESSAGE(x...) \
printk( KERN_INFO MTS_NAME x )
#if defined MTS_DO_DEBUG
#define MTS_DEBUG(x...) \
printk( KERN_DEBUG MTS_NAME x )
#define MTS_DEBUG_GOT_HERE() \
MTS_DEBUG("got to %s:%d (%s)\n", __FILE__, (int)__LINE__, __func__ )
#define MTS_DEBUG_INT() \
do { MTS_DEBUG_GOT_HERE(); \
MTS_DEBUG("transfer = 0x%x context = 0x%x\n",(int)transfer,(int)context ); \
MTS_DEBUG("status = 0x%x data-length = 0x%x sent = 0x%x\n",transfer->status,(int)context->data_length, (int)transfer->actual_length ); \
mts_debug_dump(context->instance);\
} while(0)
#else
#define MTS_NUL_STATEMENT do { } while(0)
#define MTS_DEBUG(x...) MTS_NUL_STATEMENT
#define MTS_DEBUG_GOT_HERE() MTS_NUL_STATEMENT
#define MTS_DEBUG_INT() MTS_NUL_STATEMENT
#endif
#define MTS_INT_INIT()\
struct mts_transfer_context* context = (struct mts_transfer_context*)transfer->context; \
MTS_DEBUG_INT();\
#ifdef MTS_DO_DEBUG
static inline void mts_debug_dump(struct mts_desc* desc) {
MTS_DEBUG("desc at 0x%x: toggle = %02x%02x\n",
(int)desc,
(int)desc->usb_dev->toggle[1],(int)desc->usb_dev->toggle[0]
);
MTS_DEBUG("ep_out=%x ep_response=%x ep_image=%x\n",
usb_sndbulkpipe(desc->usb_dev,desc->ep_out),
usb_rcvbulkpipe(desc->usb_dev,desc->ep_response),
usb_rcvbulkpipe(desc->usb_dev,desc->ep_image)
);
}
static inline void mts_show_command(struct scsi_cmnd *srb)
{
char *what = NULL;
switch (srb->cmnd[0]) {
case TEST_UNIT_READY: what = "TEST_UNIT_READY"; break;
case REZERO_UNIT: what = "REZERO_UNIT"; break;
case REQUEST_SENSE: what = "REQUEST_SENSE"; break;
case FORMAT_UNIT: what = "FORMAT_UNIT"; break;
case READ_BLOCK_LIMITS: what = "READ_BLOCK_LIMITS"; break;
case REASSIGN_BLOCKS: what = "REASSIGN_BLOCKS"; break;
case READ_6: what = "READ_6"; break;
case WRITE_6: what = "WRITE_6"; break;
case SEEK_6: what = "SEEK_6"; break;
case READ_REVERSE: what = "READ_REVERSE"; break;
case WRITE_FILEMARKS: what = "WRITE_FILEMARKS"; break;
case SPACE: what = "SPACE"; break;
case INQUIRY: what = "INQUIRY"; break;
case RECOVER_BUFFERED_DATA: what = "RECOVER_BUFFERED_DATA"; break;
case MODE_SELECT: what = "MODE_SELECT"; break;
case RESERVE: what = "RESERVE"; break;
case RELEASE: what = "RELEASE"; break;
case COPY: what = "COPY"; break;
case ERASE: what = "ERASE"; break;
case MODE_SENSE: what = "MODE_SENSE"; break;
case START_STOP: what = "START_STOP"; break;
case RECEIVE_DIAGNOSTIC: what = "RECEIVE_DIAGNOSTIC"; break;
case SEND_DIAGNOSTIC: what = "SEND_DIAGNOSTIC"; break;
case ALLOW_MEDIUM_REMOVAL: what = "ALLOW_MEDIUM_REMOVAL"; break;
case SET_WINDOW: what = "SET_WINDOW"; break;
case READ_CAPACITY: what = "READ_CAPACITY"; break;
case READ_10: what = "READ_10"; break;
case WRITE_10: what = "WRITE_10"; break;
case SEEK_10: what = "SEEK_10"; break;
case WRITE_VERIFY: what = "WRITE_VERIFY"; break;
case VERIFY: what = "VERIFY"; break;
case SEARCH_HIGH: what = "SEARCH_HIGH"; break;
case SEARCH_EQUAL: what = "SEARCH_EQUAL"; break;
case SEARCH_LOW: what = "SEARCH_LOW"; break;
case SET_LIMITS: what = "SET_LIMITS"; break;
case READ_POSITION: what = "READ_POSITION"; break;
case SYNCHRONIZE_CACHE: what = "SYNCHRONIZE_CACHE"; break;
case LOCK_UNLOCK_CACHE: what = "LOCK_UNLOCK_CACHE"; break;
case READ_DEFECT_DATA: what = "READ_DEFECT_DATA"; break;
case MEDIUM_SCAN: what = "MEDIUM_SCAN"; break;
case COMPARE: what = "COMPARE"; break;
case COPY_VERIFY: what = "COPY_VERIFY"; break;
case WRITE_BUFFER: what = "WRITE_BUFFER"; break;
case READ_BUFFER: what = "READ_BUFFER"; break;
case UPDATE_BLOCK: what = "UPDATE_BLOCK"; break;
case READ_LONG: what = "READ_LONG"; break;
case WRITE_LONG: what = "WRITE_LONG"; break;
case CHANGE_DEFINITION: what = "CHANGE_DEFINITION"; break;
case WRITE_SAME: what = "WRITE_SAME"; break;
case READ_TOC: what = "READ_TOC"; break;
case LOG_SELECT: what = "LOG_SELECT"; break;
case LOG_SENSE: what = "LOG_SENSE"; break;
case MODE_SELECT_10: what = "MODE_SELECT_10"; break;
case MODE_SENSE_10: what = "MODE_SENSE_10"; break;
case MOVE_MEDIUM: what = "MOVE_MEDIUM"; break;
case READ_12: what = "READ_12"; break;
case WRITE_12: what = "WRITE_12"; break;
case WRITE_VERIFY_12: what = "WRITE_VERIFY_12"; break;
case SEARCH_HIGH_12: what = "SEARCH_HIGH_12"; break;
case SEARCH_EQUAL_12: what = "SEARCH_EQUAL_12"; break;
case SEARCH_LOW_12: what = "SEARCH_LOW_12"; break;
case READ_ELEMENT_STATUS: what = "READ_ELEMENT_STATUS"; break;
case SEND_VOLUME_TAG: what = "SEND_VOLUME_TAG"; break;
case WRITE_LONG_2: what = "WRITE_LONG_2"; break;
default:
MTS_DEBUG("can't decode command\n");
goto out;
break;
}
MTS_DEBUG( "Command %s (%d bytes)\n", what, srb->cmd_len);
out:
MTS_DEBUG( " %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
srb->cmnd[0], srb->cmnd[1], srb->cmnd[2], srb->cmnd[3], srb->cmnd[4], srb->cmnd[5],
srb->cmnd[6], srb->cmnd[7], srb->cmnd[8], srb->cmnd[9]);
}
#else
static inline void mts_show_command(struct scsi_cmnd * dummy)
{
}
static inline void mts_debug_dump(struct mts_desc* dummy)
{
}
#endif
static inline void mts_urb_abort(struct mts_desc* desc) {
MTS_DEBUG_GOT_HERE();
mts_debug_dump(desc);
usb_kill_urb( desc->urb );
}
static int mts_slave_alloc (struct scsi_device *s)
{
s->inquiry_len = 0x24;
return 0;
}
static int mts_slave_configure (struct scsi_device *s)
{
blk_queue_dma_alignment(s->request_queue, (512 - 1));
return 0;
}
static int mts_scsi_abort(struct scsi_cmnd *srb)
{
struct mts_desc* desc = (struct mts_desc*)(srb->device->host->hostdata[0]);
MTS_DEBUG_GOT_HERE();
mts_urb_abort(desc);
return FAILED;
}
static int mts_scsi_host_reset(struct scsi_cmnd *srb)
{
struct mts_desc* desc = (struct mts_desc*)(srb->device->host->hostdata[0]);
int result;
MTS_DEBUG_GOT_HERE();
mts_debug_dump(desc);
result = usb_lock_device_for_reset(desc->usb_dev, desc->usb_intf);
if (result == 0) {
result = usb_reset_device(desc->usb_dev);
usb_unlock_device(desc->usb_dev);
}
return result ? FAILED : SUCCESS;
}
static int
mts_scsi_queuecommand(struct Scsi_Host *shost, struct scsi_cmnd *srb);
static void mts_transfer_cleanup( struct urb *transfer );
static void mts_do_sg(struct urb * transfer);
static inline
void mts_int_submit_urb (struct urb* transfer,
int pipe,
void* data,
unsigned length,
usb_complete_t callback )
/* Interrupt context! */
/* Holding transfer->context->lock! */
{
int res;
MTS_INT_INIT();
usb_fill_bulk_urb(transfer,
context->instance->usb_dev,
pipe,
data,
length,
callback,
context
);
res = usb_submit_urb( transfer, GFP_ATOMIC );
if ( unlikely(res) ) {
MTS_INT_ERROR( "could not submit URB! Error was %d\n",(int)res );
context->srb->result = DID_ERROR << 16;
mts_transfer_cleanup(transfer);
}
}
static void mts_transfer_cleanup( struct urb *transfer )
/* Interrupt context! */
{
MTS_INT_INIT();
if ( likely(context->final_callback != NULL) )
context->final_callback(context->srb);
}
static void mts_transfer_done( struct urb *transfer )
{
MTS_INT_INIT();
context->srb->result &= MTS_SCSI_ERR_MASK;
context->srb->result |= (unsigned)(*context->scsi_status)<<1;
mts_transfer_cleanup(transfer);
}
static void mts_get_status( struct urb *transfer )
/* Interrupt context! */
{
MTS_INT_INIT();
mts_int_submit_urb(transfer,
usb_rcvbulkpipe(context->instance->usb_dev,
context->instance->ep_response),
context->scsi_status,
1,
mts_transfer_done );
}
static void mts_data_done( struct urb* transfer )
/* Interrupt context! */
{
int status = transfer->status;
MTS_INT_INIT();
if ( context->data_length != transfer->actual_length ) {
scsi_set_resid(context->srb, context->data_length -
transfer->actual_length);
} else if ( unlikely(status) ) {
context->srb->result = (status == -ENOENT ? DID_ABORT : DID_ERROR)<<16;
}
mts_get_status(transfer);
}
static void mts_command_done( struct urb *transfer )
/* Interrupt context! */
{
int status = transfer->status;
MTS_INT_INIT();
if ( unlikely(status) ) {
if (status == -ENOENT) {
/* We are being killed */
MTS_DEBUG_GOT_HERE();
context->srb->result = DID_ABORT<<16;
} else {
/* A genuine error has occurred */
MTS_DEBUG_GOT_HERE();
context->srb->result = DID_ERROR<<16;
}
mts_transfer_cleanup(transfer);
return;
}
if (context->srb->cmnd[0] == REQUEST_SENSE) {
mts_int_submit_urb(transfer,
context->data_pipe,
context->srb->sense_buffer,
context->data_length,
mts_data_done);
} else { if ( context->data ) {
mts_int_submit_urb(transfer,
context->data_pipe,
context->data,
context->data_length,
scsi_sg_count(context->srb) > 1 ?
mts_do_sg : mts_data_done);
} else {
mts_get_status(transfer);
}
}
}
static void mts_do_sg (struct urb* transfer)
{
struct scatterlist * sg;
int status = transfer->status;
MTS_INT_INIT();
MTS_DEBUG("Processing fragment %d of %d\n", context->fragment,
scsi_sg_count(context->srb));
if (unlikely(status)) {
context->srb->result = (status == -ENOENT ? DID_ABORT : DID_ERROR)<<16;
mts_transfer_cleanup(transfer);
}
sg = scsi_sglist(context->srb);
context->fragment++;
mts_int_submit_urb(transfer,
context->data_pipe,
sg_virt(&sg[context->fragment]),
sg[context->fragment].length,
context->fragment + 1 == scsi_sg_count(context->srb) ?
mts_data_done : mts_do_sg);
}
static const u8 mts_read_image_sig[] = { 0x28, 00, 00, 00 };
static const u8 mts_read_image_sig_len = 4;
static const unsigned char mts_direction[256/8] = {
0x28, 0x81, 0x14, 0x14, 0x20, 0x01, 0x90, 0x77,
0x0C, 0x20, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
#define MTS_DIRECTION_IS_IN(x) ((mts_direction[x>>3] >> (x & 7)) & 1)
static void
mts_build_transfer_context(struct scsi_cmnd *srb, struct mts_desc* desc)
{
int pipe;
struct scatterlist * sg;
MTS_DEBUG_GOT_HERE();
desc->context.instance = desc;
desc->context.srb = srb;
desc->context.fragment = 0;
if (!scsi_bufflen(srb)) {
desc->context.data = NULL;
desc->context.data_length = 0;
return;
} else {
sg = scsi_sglist(srb);
desc->context.data = sg_virt(&sg[0]);
desc->context.data_length = sg[0].length;
}
/* can't rely on srb->sc_data_direction */
/* Brutally ripped from usb-storage */
if ( !memcmp( srb->cmnd, mts_read_image_sig, mts_read_image_sig_len )
) { pipe = usb_rcvbulkpipe(desc->usb_dev,desc->ep_image);
MTS_DEBUG( "transferring from desc->ep_image == %d\n",
(int)desc->ep_image );
} else if ( MTS_DIRECTION_IS_IN(srb->cmnd[0]) ) {
pipe = usb_rcvbulkpipe(desc->usb_dev,desc->ep_response);
MTS_DEBUG( "transferring from desc->ep_response == %d\n",
(int)desc->ep_response);
} else {
MTS_DEBUG("transferring to desc->ep_out == %d\n",
(int)desc->ep_out);
pipe = usb_sndbulkpipe(desc->usb_dev,desc->ep_out);
}
desc->context.data_pipe = pipe;
}
static int
mts_scsi_queuecommand_lck(struct scsi_cmnd *srb, mts_scsi_cmnd_callback callback)
{
struct mts_desc* desc = (struct mts_desc*)(srb->device->host->hostdata[0]);
int err = 0;
int res;
MTS_DEBUG_GOT_HERE();
mts_show_command(srb);
mts_debug_dump(desc);
if ( srb->device->lun || srb->device->id || srb->device->channel ) {
MTS_DEBUG("Command to LUN=%d ID=%d CHANNEL=%d from SCSI layer\n",(int)srb->device->lun,(int)srb->device->id, (int)srb->device->channel );
MTS_DEBUG("this device doesn't exist\n");
srb->result = DID_BAD_TARGET << 16;
if(likely(callback != NULL))
callback(srb);
goto out;
}
usb_fill_bulk_urb(desc->urb,
desc->usb_dev,
usb_sndbulkpipe(desc->usb_dev,desc->ep_out),
srb->cmnd,
srb->cmd_len,
mts_command_done,
&desc->context
);
mts_build_transfer_context( srb, desc );
desc->context.final_callback = callback;
/* here we need ATOMIC as we are called with the iolock */
res=usb_submit_urb(desc->urb, GFP_ATOMIC);
if(unlikely(res)){
MTS_ERROR("error %d submitting URB\n",(int)res);
srb->result = DID_ERROR << 16;
if(likely(callback != NULL))
callback(srb);
}
out:
return err;
}
static DEF_SCSI_QCMD(mts_scsi_queuecommand)
static struct scsi_host_template mts_scsi_host_template = {
.module = THIS_MODULE,
.name = "microtekX6",
.proc_name = "microtekX6",
.queuecommand = mts_scsi_queuecommand,
.eh_abort_handler = mts_scsi_abort,
.eh_host_reset_handler = mts_scsi_host_reset,
.sg_tablesize = SG_ALL,
.can_queue = 1,
.this_id = -1,
.cmd_per_lun = 1,
.use_clustering = 1,
.emulated = 1,
.slave_alloc = mts_slave_alloc,
.slave_configure = mts_slave_configure,
.max_sectors= 256, /* 128 K */
};
/* The entries of microtek_table must correspond, line-by-line to
the entries of mts_supported_products[]. */
static const struct usb_device_id mts_usb_ids[] =
{
{ USB_DEVICE(0x4ce, 0x0300) },
{ USB_DEVICE(0x5da, 0x0094) },
{ USB_DEVICE(0x5da, 0x0099) },
{ USB_DEVICE(0x5da, 0x009a) },
{ USB_DEVICE(0x5da, 0x00a0) },
{ USB_DEVICE(0x5da, 0x00a3) },
{ USB_DEVICE(0x5da, 0x80a3) },
{ USB_DEVICE(0x5da, 0x80ac) },
{ USB_DEVICE(0x5da, 0x00b6) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, mts_usb_ids);
static int mts_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
int i;
int ep_out = -1;
int ep_in_set[3]; /* this will break if we have more than three endpoints
which is why we check */
int *ep_in_current = ep_in_set;
int err_retval = -ENOMEM;
struct mts_desc * new_desc;
struct usb_device *dev = interface_to_usbdev (intf);
/* the current altsetting on the interface we're probing */
struct usb_host_interface *altsetting;
MTS_DEBUG_GOT_HERE();
MTS_DEBUG( "usb-device descriptor at %x\n", (int)dev );
MTS_DEBUG( "product id = 0x%x, vendor id = 0x%x\n",
le16_to_cpu(dev->descriptor.idProduct),
le16_to_cpu(dev->descriptor.idVendor) );
MTS_DEBUG_GOT_HERE();
/* the current altsetting on the interface we're probing */
altsetting = intf->cur_altsetting;
/* Check if the config is sane */
if ( altsetting->desc.bNumEndpoints != MTS_EP_TOTAL ) {
MTS_WARNING( "expecting %d got %d endpoints! Bailing out.\n",
(int)MTS_EP_TOTAL, (int)altsetting->desc.bNumEndpoints );
return -ENODEV;
}
for( i = 0; i < altsetting->desc.bNumEndpoints; i++ ) {
if ((altsetting->endpoint[i].desc.bmAttributes &
USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_BULK) {
MTS_WARNING( "can only deal with bulk endpoints; endpoint %d is not bulk.\n",
(int)altsetting->endpoint[i].desc.bEndpointAddress );
} else {
if (altsetting->endpoint[i].desc.bEndpointAddress &
USB_DIR_IN)
*ep_in_current++
= altsetting->endpoint[i].desc.bEndpointAddress &
USB_ENDPOINT_NUMBER_MASK;
else {
if ( ep_out != -1 ) {
MTS_WARNING( "can only deal with one output endpoints. Bailing out." );
return -ENODEV;
}
ep_out = altsetting->endpoint[i].desc.bEndpointAddress &
USB_ENDPOINT_NUMBER_MASK;
}
}
}
if ( ep_out == -1 ) {
MTS_WARNING( "couldn't find an output bulk endpoint. Bailing out.\n" );
return -ENODEV;
}
new_desc = kzalloc(sizeof(struct mts_desc), GFP_KERNEL);
if (!new_desc)
goto out;
new_desc->urb = usb_alloc_urb(0, GFP_KERNEL);
if (!new_desc->urb)
goto out_kfree;
new_desc->context.scsi_status = kmalloc(1, GFP_KERNEL);
if (!new_desc->context.scsi_status)
goto out_free_urb;
new_desc->usb_dev = dev;
new_desc->usb_intf = intf;
/* endpoints */
new_desc->ep_out = ep_out;
new_desc->ep_response = ep_in_set[0];
new_desc->ep_image = ep_in_set[1];
if ( new_desc->ep_out != MTS_EP_OUT )
MTS_WARNING( "will this work? Command EP is not usually %d\n",
(int)new_desc->ep_out );
if ( new_desc->ep_response != MTS_EP_RESPONSE )
MTS_WARNING( "will this work? Response EP is not usually %d\n",
(int)new_desc->ep_response );
if ( new_desc->ep_image != MTS_EP_IMAGE )
MTS_WARNING( "will this work? Image data EP is not usually %d\n",
(int)new_desc->ep_image );
new_desc->host = scsi_host_alloc(&mts_scsi_host_template,
sizeof(new_desc));
if (!new_desc->host)
goto out_kfree2;
new_desc->host->hostdata[0] = (unsigned long)new_desc;
if (scsi_add_host(new_desc->host, &dev->dev)) {
err_retval = -EIO;
goto out_host_put;
}
scsi_scan_host(new_desc->host);
usb_set_intfdata(intf, new_desc);
return 0;
out_host_put:
scsi_host_put(new_desc->host);
out_kfree2:
kfree(new_desc->context.scsi_status);
out_free_urb:
usb_free_urb(new_desc->urb);
out_kfree:
kfree(new_desc);
out:
return err_retval;
}
static void mts_usb_disconnect (struct usb_interface *intf)
{
struct mts_desc *desc = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
usb_kill_urb(desc->urb);
scsi_remove_host(desc->host);
scsi_host_put(desc->host);
usb_free_urb(desc->urb);
kfree(desc->context.scsi_status);
kfree(desc);
}
module_usb_driver(mts_usb_driver);
MODULE_AUTHOR( DRIVER_AUTHOR );
MODULE_DESCRIPTION( DRIVER_DESC );
MODULE_LICENSE("GPL");
| gpl-2.0 |
shinkumara/sprout_shinkumara_kernel | arch/microblaze/kernel/cpu/cpuinfo-static.c | 7551 | 5155 | /*
* Copyright (C) 2007-2009 Michal Simek <monstr@monstr.eu>
* Copyright (C) 2007-2009 PetaLogix
* Copyright (C) 2007 John Williams <john.williams@petalogix.com>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/string.h>
#include <asm/cpuinfo.h>
#include <asm/pvr.h>
static const char family_string[] = CONFIG_XILINX_MICROBLAZE0_FAMILY;
static const char cpu_ver_string[] = CONFIG_XILINX_MICROBLAZE0_HW_VER;
#define err_printk(x) \
early_printk("ERROR: Microblaze " x "-different for kernel and DTS\n");
void __init set_cpuinfo_static(struct cpuinfo *ci, struct device_node *cpu)
{
int i = 0;
ci->use_instr =
(fcpu(cpu, "xlnx,use-barrel") ? PVR0_USE_BARREL_MASK : 0) |
(fcpu(cpu, "xlnx,use-msr-instr") ? PVR2_USE_MSR_INSTR : 0) |
(fcpu(cpu, "xlnx,use-pcmp-instr") ? PVR2_USE_PCMP_INSTR : 0) |
(fcpu(cpu, "xlnx,use-div") ? PVR0_USE_DIV_MASK : 0);
if (CONFIG_XILINX_MICROBLAZE0_USE_BARREL)
i |= PVR0_USE_BARREL_MASK;
if (CONFIG_XILINX_MICROBLAZE0_USE_MSR_INSTR)
i |= PVR2_USE_MSR_INSTR;
if (CONFIG_XILINX_MICROBLAZE0_USE_PCMP_INSTR)
i |= PVR2_USE_PCMP_INSTR;
if (CONFIG_XILINX_MICROBLAZE0_USE_DIV)
i |= PVR0_USE_DIV_MASK;
if (ci->use_instr != i)
err_printk("BARREL, MSR, PCMP or DIV");
ci->use_mult = fcpu(cpu, "xlnx,use-hw-mul");
if (ci->use_mult != CONFIG_XILINX_MICROBLAZE0_USE_HW_MUL)
err_printk("HW_MUL");
ci->use_mult =
(ci->use_mult > 1 ?
(PVR2_USE_MUL64_MASK | PVR0_USE_HW_MUL_MASK) :
(ci->use_mult == 1 ? PVR0_USE_HW_MUL_MASK : 0));
ci->use_fpu = fcpu(cpu, "xlnx,use-fpu");
if (ci->use_fpu != CONFIG_XILINX_MICROBLAZE0_USE_FPU)
err_printk("HW_FPU");
ci->use_fpu = (ci->use_fpu > 1 ?
(PVR2_USE_FPU2_MASK | PVR0_USE_FPU_MASK) :
(ci->use_fpu == 1 ? PVR0_USE_FPU_MASK : 0));
ci->use_exc =
(fcpu(cpu, "xlnx,unaligned-exceptions") ?
PVR2_UNALIGNED_EXC_MASK : 0) |
(fcpu(cpu, "xlnx,ill-opcode-exception") ?
PVR2_ILL_OPCODE_EXC_MASK : 0) |
(fcpu(cpu, "xlnx,iopb-bus-exception") ?
PVR2_IOPB_BUS_EXC_MASK : 0) |
(fcpu(cpu, "xlnx,dopb-bus-exception") ?
PVR2_DOPB_BUS_EXC_MASK : 0) |
(fcpu(cpu, "xlnx,div-zero-exception") ?
PVR2_DIV_ZERO_EXC_MASK : 0) |
(fcpu(cpu, "xlnx,fpu-exception") ? PVR2_FPU_EXC_MASK : 0) |
(fcpu(cpu, "xlnx,fsl-exception") ? PVR2_USE_EXTEND_FSL : 0);
ci->use_icache = fcpu(cpu, "xlnx,use-icache");
ci->icache_tagbits = fcpu(cpu, "xlnx,addr-tag-bits");
ci->icache_write = fcpu(cpu, "xlnx,allow-icache-wr");
ci->icache_line_length = fcpu(cpu, "xlnx,icache-line-len") << 2;
if (!ci->icache_line_length) {
if (fcpu(cpu, "xlnx,icache-use-fsl"))
ci->icache_line_length = 4 << 2;
else
ci->icache_line_length = 1 << 2;
}
ci->icache_size = fcpu(cpu, "i-cache-size");
ci->icache_base = fcpu(cpu, "i-cache-baseaddr");
ci->icache_high = fcpu(cpu, "i-cache-highaddr");
ci->use_dcache = fcpu(cpu, "xlnx,use-dcache");
ci->dcache_tagbits = fcpu(cpu, "xlnx,dcache-addr-tag");
ci->dcache_write = fcpu(cpu, "xlnx,allow-dcache-wr");
ci->dcache_line_length = fcpu(cpu, "xlnx,dcache-line-len") << 2;
if (!ci->dcache_line_length) {
if (fcpu(cpu, "xlnx,dcache-use-fsl"))
ci->dcache_line_length = 4 << 2;
else
ci->dcache_line_length = 1 << 2;
}
ci->dcache_size = fcpu(cpu, "d-cache-size");
ci->dcache_base = fcpu(cpu, "d-cache-baseaddr");
ci->dcache_high = fcpu(cpu, "d-cache-highaddr");
ci->dcache_wb = fcpu(cpu, "xlnx,dcache-use-writeback");
ci->use_dopb = fcpu(cpu, "xlnx,d-opb");
ci->use_iopb = fcpu(cpu, "xlnx,i-opb");
ci->use_dlmb = fcpu(cpu, "xlnx,d-lmb");
ci->use_ilmb = fcpu(cpu, "xlnx,i-lmb");
ci->num_fsl = fcpu(cpu, "xlnx,fsl-links");
ci->irq_edge = fcpu(cpu, "xlnx,interrupt-is-edge");
ci->irq_positive = fcpu(cpu, "xlnx,edge-is-positive");
ci->area_optimised = 0;
ci->hw_debug = fcpu(cpu, "xlnx,debug-enabled");
ci->num_pc_brk = fcpu(cpu, "xlnx,number-of-pc-brk");
ci->num_rd_brk = fcpu(cpu, "xlnx,number-of-rd-addr-brk");
ci->num_wr_brk = fcpu(cpu, "xlnx,number-of-wr-addr-brk");
ci->cpu_clock_freq = fcpu(cpu, "timebase-frequency");
ci->pvr_user1 = fcpu(cpu, "xlnx,pvr-user1");
ci->pvr_user2 = fcpu(cpu, "xlnx,pvr-user2");
ci->mmu = fcpu(cpu, "xlnx,use-mmu");
ci->mmu_privins = fcpu(cpu, "xlnx,mmu-privileged-instr");
ci->endian = fcpu(cpu, "xlnx,endianness");
ci->ver_code = 0;
ci->fpga_family_code = 0;
/* Do various fixups based on CPU version and FPGA family strings */
/* Resolved the CPU version code */
for (i = 0; cpu_ver_lookup[i].s != NULL; i++) {
if (strcmp(cpu_ver_lookup[i].s, cpu_ver_string) == 0)
ci->ver_code = cpu_ver_lookup[i].k;
}
/* Resolved the fpga family code */
for (i = 0; family_string_lookup[i].s != NULL; i++) {
if (strcmp(family_string_lookup[i].s, family_string) == 0)
ci->fpga_family_code = family_string_lookup[i].k;
}
/* FIXME - mb3 and spartan2 do not exist in PVR */
/* This is mb3 and on a non Spartan2 */
if (ci->ver_code == 0x20 && ci->fpga_family_code != 0xf0)
/* Hardware Multiplier in use */
ci->use_mult = 1;
}
| gpl-2.0 |
BanBxda/Linux-3.0.X | tools/perf/util/path.c | 8319 | 3344 | /*
* I'm tired of doing "vsnprintf()" etc just to open a
* file, so here's a "return static buffer with printf"
* interface for paths.
*
* It's obviously not thread-safe. Sue me. But it's quite
* useful for doing things like
*
* f = open(mkpath("%s/%s.perf", base, name), O_RDONLY);
*
* which is what it's designed for.
*/
#include "cache.h"
static char bad_path[] = "/bad-path/";
/*
* Two hacks:
*/
static const char *get_perf_dir(void)
{
return ".";
}
#ifdef NO_STRLCPY
size_t strlcpy(char *dest, const char *src, size_t size)
{
size_t ret = strlen(src);
if (size) {
size_t len = (ret >= size) ? size - 1 : ret;
memcpy(dest, src, len);
dest[len] = '\0';
}
return ret;
}
#endif
static char *get_pathname(void)
{
static char pathname_array[4][PATH_MAX];
static int idx;
return pathname_array[3 & ++idx];
}
static char *cleanup_path(char *path)
{
/* Clean it up */
if (!memcmp(path, "./", 2)) {
path += 2;
while (*path == '/')
path++;
}
return path;
}
static char *perf_vsnpath(char *buf, size_t n, const char *fmt, va_list args)
{
const char *perf_dir = get_perf_dir();
size_t len;
len = strlen(perf_dir);
if (n < len + 1)
goto bad;
memcpy(buf, perf_dir, len);
if (len && !is_dir_sep(perf_dir[len-1]))
buf[len++] = '/';
len += vsnprintf(buf + len, n - len, fmt, args);
if (len >= n)
goto bad;
return cleanup_path(buf);
bad:
strlcpy(buf, bad_path, n);
return buf;
}
char *perf_pathdup(const char *fmt, ...)
{
char path[PATH_MAX];
va_list args;
va_start(args, fmt);
(void)perf_vsnpath(path, sizeof(path), fmt, args);
va_end(args);
return xstrdup(path);
}
char *mkpath(const char *fmt, ...)
{
va_list args;
unsigned len;
char *pathname = get_pathname();
va_start(args, fmt);
len = vsnprintf(pathname, PATH_MAX, fmt, args);
va_end(args);
if (len >= PATH_MAX)
return bad_path;
return cleanup_path(pathname);
}
char *perf_path(const char *fmt, ...)
{
const char *perf_dir = get_perf_dir();
char *pathname = get_pathname();
va_list args;
unsigned len;
len = strlen(perf_dir);
if (len > PATH_MAX-100)
return bad_path;
memcpy(pathname, perf_dir, len);
if (len && perf_dir[len-1] != '/')
pathname[len++] = '/';
va_start(args, fmt);
len += vsnprintf(pathname + len, PATH_MAX - len, fmt, args);
va_end(args);
if (len >= PATH_MAX)
return bad_path;
return cleanup_path(pathname);
}
/* strip arbitrary amount of directory separators at end of path */
static inline int chomp_trailing_dir_sep(const char *path, int len)
{
while (len && is_dir_sep(path[len - 1]))
len--;
return len;
}
/*
* If path ends with suffix (complete path components), returns the
* part before suffix (sans trailing directory separators).
* Otherwise returns NULL.
*/
char *strip_path_suffix(const char *path, const char *suffix)
{
int path_len = strlen(path), suffix_len = strlen(suffix);
while (suffix_len) {
if (!path_len)
return NULL;
if (is_dir_sep(path[path_len - 1])) {
if (!is_dir_sep(suffix[suffix_len - 1]))
return NULL;
path_len = chomp_trailing_dir_sep(path, path_len);
suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
}
else if (path[--path_len] != suffix[--suffix_len])
return NULL;
}
if (path_len && !is_dir_sep(path[path_len - 1]))
return NULL;
return strndup(path, chomp_trailing_dir_sep(path, path_len));
}
| gpl-2.0 |
nimengyu2/ti-a8-linux-04.06.00.07 | drivers/edac/mv64x60_edac.c | 9087 | 22846 | /*
* Marvell MV64x60 Memory Controller kernel module for PPC platforms
*
* Author: Dave Jiang <djiang@mvista.com>
*
* 2006-2007 (c) MontaVista Software, Inc. This file is licensed under
* the terms of the GNU General Public License version 2. This program
* is licensed "as is" without any warranty of any kind, whether express
* or implied.
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/edac.h>
#include <linux/gfp.h>
#include "edac_core.h"
#include "edac_module.h"
#include "mv64x60_edac.h"
static const char *mv64x60_ctl_name = "MV64x60";
static int edac_dev_idx;
static int edac_pci_idx;
static int edac_mc_idx;
/*********************** PCI err device **********************************/
#ifdef CONFIG_PCI
static void mv64x60_pci_check(struct edac_pci_ctl_info *pci)
{
struct mv64x60_pci_pdata *pdata = pci->pvt_info;
u32 cause;
cause = in_le32(pdata->pci_vbase + MV64X60_PCI_ERROR_CAUSE);
if (!cause)
return;
printk(KERN_ERR "Error in PCI %d Interface\n", pdata->pci_hose);
printk(KERN_ERR "Cause register: 0x%08x\n", cause);
printk(KERN_ERR "Address Low: 0x%08x\n",
in_le32(pdata->pci_vbase + MV64X60_PCI_ERROR_ADDR_LO));
printk(KERN_ERR "Address High: 0x%08x\n",
in_le32(pdata->pci_vbase + MV64X60_PCI_ERROR_ADDR_HI));
printk(KERN_ERR "Attribute: 0x%08x\n",
in_le32(pdata->pci_vbase + MV64X60_PCI_ERROR_ATTR));
printk(KERN_ERR "Command: 0x%08x\n",
in_le32(pdata->pci_vbase + MV64X60_PCI_ERROR_CMD));
out_le32(pdata->pci_vbase + MV64X60_PCI_ERROR_CAUSE, ~cause);
if (cause & MV64X60_PCI_PE_MASK)
edac_pci_handle_pe(pci, pci->ctl_name);
if (!(cause & MV64X60_PCI_PE_MASK))
edac_pci_handle_npe(pci, pci->ctl_name);
}
static irqreturn_t mv64x60_pci_isr(int irq, void *dev_id)
{
struct edac_pci_ctl_info *pci = dev_id;
struct mv64x60_pci_pdata *pdata = pci->pvt_info;
u32 val;
val = in_le32(pdata->pci_vbase + MV64X60_PCI_ERROR_CAUSE);
if (!val)
return IRQ_NONE;
mv64x60_pci_check(pci);
return IRQ_HANDLED;
}
/*
* Bit 0 of MV64x60_PCIx_ERR_MASK does not exist on the 64360 and because of
* errata FEr-#11 and FEr-##16 for the 64460, it should be 0 on that chip as
* well. IOW, don't set bit 0.
*/
/* Erratum FEr PCI-#16: clear bit 0 of PCI SERRn Mask reg. */
static int __init mv64x60_pci_fixup(struct platform_device *pdev)
{
struct resource *r;
void __iomem *pci_serr;
r = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!r) {
printk(KERN_ERR "%s: Unable to get resource for "
"PCI err regs\n", __func__);
return -ENOENT;
}
pci_serr = ioremap(r->start, resource_size(r));
if (!pci_serr)
return -ENOMEM;
out_le32(pci_serr, in_le32(pci_serr) & ~0x1);
iounmap(pci_serr);
return 0;
}
static int __devinit mv64x60_pci_err_probe(struct platform_device *pdev)
{
struct edac_pci_ctl_info *pci;
struct mv64x60_pci_pdata *pdata;
struct resource *r;
int res = 0;
if (!devres_open_group(&pdev->dev, mv64x60_pci_err_probe, GFP_KERNEL))
return -ENOMEM;
pci = edac_pci_alloc_ctl_info(sizeof(*pdata), "mv64x60_pci_err");
if (!pci)
return -ENOMEM;
pdata = pci->pvt_info;
pdata->pci_hose = pdev->id;
pdata->name = "mpc85xx_pci_err";
pdata->irq = NO_IRQ;
platform_set_drvdata(pdev, pci);
pci->dev = &pdev->dev;
pci->dev_name = dev_name(&pdev->dev);
pci->mod_name = EDAC_MOD_STR;
pci->ctl_name = pdata->name;
if (edac_op_state == EDAC_OPSTATE_POLL)
pci->edac_check = mv64x60_pci_check;
pdata->edac_idx = edac_pci_idx++;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!r) {
printk(KERN_ERR "%s: Unable to get resource for "
"PCI err regs\n", __func__);
res = -ENOENT;
goto err;
}
if (!devm_request_mem_region(&pdev->dev,
r->start,
resource_size(r),
pdata->name)) {
printk(KERN_ERR "%s: Error while requesting mem region\n",
__func__);
res = -EBUSY;
goto err;
}
pdata->pci_vbase = devm_ioremap(&pdev->dev,
r->start,
resource_size(r));
if (!pdata->pci_vbase) {
printk(KERN_ERR "%s: Unable to setup PCI err regs\n", __func__);
res = -ENOMEM;
goto err;
}
res = mv64x60_pci_fixup(pdev);
if (res < 0) {
printk(KERN_ERR "%s: PCI fixup failed\n", __func__);
goto err;
}
out_le32(pdata->pci_vbase + MV64X60_PCI_ERROR_CAUSE, 0);
out_le32(pdata->pci_vbase + MV64X60_PCI_ERROR_MASK, 0);
out_le32(pdata->pci_vbase + MV64X60_PCI_ERROR_MASK,
MV64X60_PCIx_ERR_MASK_VAL);
if (edac_pci_add_device(pci, pdata->edac_idx) > 0) {
debugf3("%s(): failed edac_pci_add_device()\n", __func__);
goto err;
}
if (edac_op_state == EDAC_OPSTATE_INT) {
pdata->irq = platform_get_irq(pdev, 0);
res = devm_request_irq(&pdev->dev,
pdata->irq,
mv64x60_pci_isr,
IRQF_DISABLED,
"[EDAC] PCI err",
pci);
if (res < 0) {
printk(KERN_ERR "%s: Unable to request irq %d for "
"MV64x60 PCI ERR\n", __func__, pdata->irq);
res = -ENODEV;
goto err2;
}
printk(KERN_INFO EDAC_MOD_STR " acquired irq %d for PCI Err\n",
pdata->irq);
}
devres_remove_group(&pdev->dev, mv64x60_pci_err_probe);
/* get this far and it's successful */
debugf3("%s(): success\n", __func__);
return 0;
err2:
edac_pci_del_device(&pdev->dev);
err:
edac_pci_free_ctl_info(pci);
devres_release_group(&pdev->dev, mv64x60_pci_err_probe);
return res;
}
static int mv64x60_pci_err_remove(struct platform_device *pdev)
{
struct edac_pci_ctl_info *pci = platform_get_drvdata(pdev);
debugf0("%s()\n", __func__);
edac_pci_del_device(&pdev->dev);
edac_pci_free_ctl_info(pci);
return 0;
}
static struct platform_driver mv64x60_pci_err_driver = {
.probe = mv64x60_pci_err_probe,
.remove = __devexit_p(mv64x60_pci_err_remove),
.driver = {
.name = "mv64x60_pci_err",
}
};
#endif /* CONFIG_PCI */
/*********************** SRAM err device **********************************/
static void mv64x60_sram_check(struct edac_device_ctl_info *edac_dev)
{
struct mv64x60_sram_pdata *pdata = edac_dev->pvt_info;
u32 cause;
cause = in_le32(pdata->sram_vbase + MV64X60_SRAM_ERR_CAUSE);
if (!cause)
return;
printk(KERN_ERR "Error in internal SRAM\n");
printk(KERN_ERR "Cause register: 0x%08x\n", cause);
printk(KERN_ERR "Address Low: 0x%08x\n",
in_le32(pdata->sram_vbase + MV64X60_SRAM_ERR_ADDR_LO));
printk(KERN_ERR "Address High: 0x%08x\n",
in_le32(pdata->sram_vbase + MV64X60_SRAM_ERR_ADDR_HI));
printk(KERN_ERR "Data Low: 0x%08x\n",
in_le32(pdata->sram_vbase + MV64X60_SRAM_ERR_DATA_LO));
printk(KERN_ERR "Data High: 0x%08x\n",
in_le32(pdata->sram_vbase + MV64X60_SRAM_ERR_DATA_HI));
printk(KERN_ERR "Parity: 0x%08x\n",
in_le32(pdata->sram_vbase + MV64X60_SRAM_ERR_PARITY));
out_le32(pdata->sram_vbase + MV64X60_SRAM_ERR_CAUSE, 0);
edac_device_handle_ue(edac_dev, 0, 0, edac_dev->ctl_name);
}
static irqreturn_t mv64x60_sram_isr(int irq, void *dev_id)
{
struct edac_device_ctl_info *edac_dev = dev_id;
struct mv64x60_sram_pdata *pdata = edac_dev->pvt_info;
u32 cause;
cause = in_le32(pdata->sram_vbase + MV64X60_SRAM_ERR_CAUSE);
if (!cause)
return IRQ_NONE;
mv64x60_sram_check(edac_dev);
return IRQ_HANDLED;
}
static int __devinit mv64x60_sram_err_probe(struct platform_device *pdev)
{
struct edac_device_ctl_info *edac_dev;
struct mv64x60_sram_pdata *pdata;
struct resource *r;
int res = 0;
if (!devres_open_group(&pdev->dev, mv64x60_sram_err_probe, GFP_KERNEL))
return -ENOMEM;
edac_dev = edac_device_alloc_ctl_info(sizeof(*pdata),
"sram", 1, NULL, 0, 0, NULL, 0,
edac_dev_idx);
if (!edac_dev) {
devres_release_group(&pdev->dev, mv64x60_sram_err_probe);
return -ENOMEM;
}
pdata = edac_dev->pvt_info;
pdata->name = "mv64x60_sram_err";
pdata->irq = NO_IRQ;
edac_dev->dev = &pdev->dev;
platform_set_drvdata(pdev, edac_dev);
edac_dev->dev_name = dev_name(&pdev->dev);
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!r) {
printk(KERN_ERR "%s: Unable to get resource for "
"SRAM err regs\n", __func__);
res = -ENOENT;
goto err;
}
if (!devm_request_mem_region(&pdev->dev,
r->start,
resource_size(r),
pdata->name)) {
printk(KERN_ERR "%s: Error while request mem region\n",
__func__);
res = -EBUSY;
goto err;
}
pdata->sram_vbase = devm_ioremap(&pdev->dev,
r->start,
resource_size(r));
if (!pdata->sram_vbase) {
printk(KERN_ERR "%s: Unable to setup SRAM err regs\n",
__func__);
res = -ENOMEM;
goto err;
}
/* setup SRAM err registers */
out_le32(pdata->sram_vbase + MV64X60_SRAM_ERR_CAUSE, 0);
edac_dev->mod_name = EDAC_MOD_STR;
edac_dev->ctl_name = pdata->name;
if (edac_op_state == EDAC_OPSTATE_POLL)
edac_dev->edac_check = mv64x60_sram_check;
pdata->edac_idx = edac_dev_idx++;
if (edac_device_add_device(edac_dev) > 0) {
debugf3("%s(): failed edac_device_add_device()\n", __func__);
goto err;
}
if (edac_op_state == EDAC_OPSTATE_INT) {
pdata->irq = platform_get_irq(pdev, 0);
res = devm_request_irq(&pdev->dev,
pdata->irq,
mv64x60_sram_isr,
IRQF_DISABLED,
"[EDAC] SRAM err",
edac_dev);
if (res < 0) {
printk(KERN_ERR
"%s: Unable to request irq %d for "
"MV64x60 SRAM ERR\n", __func__, pdata->irq);
res = -ENODEV;
goto err2;
}
printk(KERN_INFO EDAC_MOD_STR " acquired irq %d for SRAM Err\n",
pdata->irq);
}
devres_remove_group(&pdev->dev, mv64x60_sram_err_probe);
/* get this far and it's successful */
debugf3("%s(): success\n", __func__);
return 0;
err2:
edac_device_del_device(&pdev->dev);
err:
devres_release_group(&pdev->dev, mv64x60_sram_err_probe);
edac_device_free_ctl_info(edac_dev);
return res;
}
static int mv64x60_sram_err_remove(struct platform_device *pdev)
{
struct edac_device_ctl_info *edac_dev = platform_get_drvdata(pdev);
debugf0("%s()\n", __func__);
edac_device_del_device(&pdev->dev);
edac_device_free_ctl_info(edac_dev);
return 0;
}
static struct platform_driver mv64x60_sram_err_driver = {
.probe = mv64x60_sram_err_probe,
.remove = mv64x60_sram_err_remove,
.driver = {
.name = "mv64x60_sram_err",
}
};
/*********************** CPU err device **********************************/
static void mv64x60_cpu_check(struct edac_device_ctl_info *edac_dev)
{
struct mv64x60_cpu_pdata *pdata = edac_dev->pvt_info;
u32 cause;
cause = in_le32(pdata->cpu_vbase[1] + MV64x60_CPU_ERR_CAUSE) &
MV64x60_CPU_CAUSE_MASK;
if (!cause)
return;
printk(KERN_ERR "Error on CPU interface\n");
printk(KERN_ERR "Cause register: 0x%08x\n", cause);
printk(KERN_ERR "Address Low: 0x%08x\n",
in_le32(pdata->cpu_vbase[0] + MV64x60_CPU_ERR_ADDR_LO));
printk(KERN_ERR "Address High: 0x%08x\n",
in_le32(pdata->cpu_vbase[0] + MV64x60_CPU_ERR_ADDR_HI));
printk(KERN_ERR "Data Low: 0x%08x\n",
in_le32(pdata->cpu_vbase[1] + MV64x60_CPU_ERR_DATA_LO));
printk(KERN_ERR "Data High: 0x%08x\n",
in_le32(pdata->cpu_vbase[1] + MV64x60_CPU_ERR_DATA_HI));
printk(KERN_ERR "Parity: 0x%08x\n",
in_le32(pdata->cpu_vbase[1] + MV64x60_CPU_ERR_PARITY));
out_le32(pdata->cpu_vbase[1] + MV64x60_CPU_ERR_CAUSE, 0);
edac_device_handle_ue(edac_dev, 0, 0, edac_dev->ctl_name);
}
static irqreturn_t mv64x60_cpu_isr(int irq, void *dev_id)
{
struct edac_device_ctl_info *edac_dev = dev_id;
struct mv64x60_cpu_pdata *pdata = edac_dev->pvt_info;
u32 cause;
cause = in_le32(pdata->cpu_vbase[1] + MV64x60_CPU_ERR_CAUSE) &
MV64x60_CPU_CAUSE_MASK;
if (!cause)
return IRQ_NONE;
mv64x60_cpu_check(edac_dev);
return IRQ_HANDLED;
}
static int __devinit mv64x60_cpu_err_probe(struct platform_device *pdev)
{
struct edac_device_ctl_info *edac_dev;
struct resource *r;
struct mv64x60_cpu_pdata *pdata;
int res = 0;
if (!devres_open_group(&pdev->dev, mv64x60_cpu_err_probe, GFP_KERNEL))
return -ENOMEM;
edac_dev = edac_device_alloc_ctl_info(sizeof(*pdata),
"cpu", 1, NULL, 0, 0, NULL, 0,
edac_dev_idx);
if (!edac_dev) {
devres_release_group(&pdev->dev, mv64x60_cpu_err_probe);
return -ENOMEM;
}
pdata = edac_dev->pvt_info;
pdata->name = "mv64x60_cpu_err";
pdata->irq = NO_IRQ;
edac_dev->dev = &pdev->dev;
platform_set_drvdata(pdev, edac_dev);
edac_dev->dev_name = dev_name(&pdev->dev);
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!r) {
printk(KERN_ERR "%s: Unable to get resource for "
"CPU err regs\n", __func__);
res = -ENOENT;
goto err;
}
if (!devm_request_mem_region(&pdev->dev,
r->start,
resource_size(r),
pdata->name)) {
printk(KERN_ERR "%s: Error while requesting mem region\n",
__func__);
res = -EBUSY;
goto err;
}
pdata->cpu_vbase[0] = devm_ioremap(&pdev->dev,
r->start,
resource_size(r));
if (!pdata->cpu_vbase[0]) {
printk(KERN_ERR "%s: Unable to setup CPU err regs\n", __func__);
res = -ENOMEM;
goto err;
}
r = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!r) {
printk(KERN_ERR "%s: Unable to get resource for "
"CPU err regs\n", __func__);
res = -ENOENT;
goto err;
}
if (!devm_request_mem_region(&pdev->dev,
r->start,
resource_size(r),
pdata->name)) {
printk(KERN_ERR "%s: Error while requesting mem region\n",
__func__);
res = -EBUSY;
goto err;
}
pdata->cpu_vbase[1] = devm_ioremap(&pdev->dev,
r->start,
resource_size(r));
if (!pdata->cpu_vbase[1]) {
printk(KERN_ERR "%s: Unable to setup CPU err regs\n", __func__);
res = -ENOMEM;
goto err;
}
/* setup CPU err registers */
out_le32(pdata->cpu_vbase[1] + MV64x60_CPU_ERR_CAUSE, 0);
out_le32(pdata->cpu_vbase[1] + MV64x60_CPU_ERR_MASK, 0);
out_le32(pdata->cpu_vbase[1] + MV64x60_CPU_ERR_MASK, 0x000000ff);
edac_dev->mod_name = EDAC_MOD_STR;
edac_dev->ctl_name = pdata->name;
if (edac_op_state == EDAC_OPSTATE_POLL)
edac_dev->edac_check = mv64x60_cpu_check;
pdata->edac_idx = edac_dev_idx++;
if (edac_device_add_device(edac_dev) > 0) {
debugf3("%s(): failed edac_device_add_device()\n", __func__);
goto err;
}
if (edac_op_state == EDAC_OPSTATE_INT) {
pdata->irq = platform_get_irq(pdev, 0);
res = devm_request_irq(&pdev->dev,
pdata->irq,
mv64x60_cpu_isr,
IRQF_DISABLED,
"[EDAC] CPU err",
edac_dev);
if (res < 0) {
printk(KERN_ERR
"%s: Unable to request irq %d for MV64x60 "
"CPU ERR\n", __func__, pdata->irq);
res = -ENODEV;
goto err2;
}
printk(KERN_INFO EDAC_MOD_STR
" acquired irq %d for CPU Err\n", pdata->irq);
}
devres_remove_group(&pdev->dev, mv64x60_cpu_err_probe);
/* get this far and it's successful */
debugf3("%s(): success\n", __func__);
return 0;
err2:
edac_device_del_device(&pdev->dev);
err:
devres_release_group(&pdev->dev, mv64x60_cpu_err_probe);
edac_device_free_ctl_info(edac_dev);
return res;
}
static int mv64x60_cpu_err_remove(struct platform_device *pdev)
{
struct edac_device_ctl_info *edac_dev = platform_get_drvdata(pdev);
debugf0("%s()\n", __func__);
edac_device_del_device(&pdev->dev);
edac_device_free_ctl_info(edac_dev);
return 0;
}
static struct platform_driver mv64x60_cpu_err_driver = {
.probe = mv64x60_cpu_err_probe,
.remove = mv64x60_cpu_err_remove,
.driver = {
.name = "mv64x60_cpu_err",
}
};
/*********************** DRAM err device **********************************/
static void mv64x60_mc_check(struct mem_ctl_info *mci)
{
struct mv64x60_mc_pdata *pdata = mci->pvt_info;
u32 reg;
u32 err_addr;
u32 sdram_ecc;
u32 comp_ecc;
u32 syndrome;
reg = in_le32(pdata->mc_vbase + MV64X60_SDRAM_ERR_ADDR);
if (!reg)
return;
err_addr = reg & ~0x3;
sdram_ecc = in_le32(pdata->mc_vbase + MV64X60_SDRAM_ERR_ECC_RCVD);
comp_ecc = in_le32(pdata->mc_vbase + MV64X60_SDRAM_ERR_ECC_CALC);
syndrome = sdram_ecc ^ comp_ecc;
/* first bit clear in ECC Err Reg, 1 bit error, correctable by HW */
if (!(reg & 0x1))
edac_mc_handle_ce(mci, err_addr >> PAGE_SHIFT,
err_addr & PAGE_MASK, syndrome, 0, 0,
mci->ctl_name);
else /* 2 bit error, UE */
edac_mc_handle_ue(mci, err_addr >> PAGE_SHIFT,
err_addr & PAGE_MASK, 0, mci->ctl_name);
/* clear the error */
out_le32(pdata->mc_vbase + MV64X60_SDRAM_ERR_ADDR, 0);
}
static irqreturn_t mv64x60_mc_isr(int irq, void *dev_id)
{
struct mem_ctl_info *mci = dev_id;
struct mv64x60_mc_pdata *pdata = mci->pvt_info;
u32 reg;
reg = in_le32(pdata->mc_vbase + MV64X60_SDRAM_ERR_ADDR);
if (!reg)
return IRQ_NONE;
/* writing 0's to the ECC err addr in check function clears irq */
mv64x60_mc_check(mci);
return IRQ_HANDLED;
}
static void get_total_mem(struct mv64x60_mc_pdata *pdata)
{
struct device_node *np = NULL;
const unsigned int *reg;
np = of_find_node_by_type(NULL, "memory");
if (!np)
return;
reg = of_get_property(np, "reg", NULL);
pdata->total_mem = reg[1];
}
static void mv64x60_init_csrows(struct mem_ctl_info *mci,
struct mv64x60_mc_pdata *pdata)
{
struct csrow_info *csrow;
u32 devtype;
u32 ctl;
get_total_mem(pdata);
ctl = in_le32(pdata->mc_vbase + MV64X60_SDRAM_CONFIG);
csrow = &mci->csrows[0];
csrow->first_page = 0;
csrow->nr_pages = pdata->total_mem >> PAGE_SHIFT;
csrow->last_page = csrow->first_page + csrow->nr_pages - 1;
csrow->grain = 8;
csrow->mtype = (ctl & MV64X60_SDRAM_REGISTERED) ? MEM_RDDR : MEM_DDR;
devtype = (ctl >> 20) & 0x3;
switch (devtype) {
case 0x0:
csrow->dtype = DEV_X32;
break;
case 0x2: /* could be X8 too, but no way to tell */
csrow->dtype = DEV_X16;
break;
case 0x3:
csrow->dtype = DEV_X4;
break;
default:
csrow->dtype = DEV_UNKNOWN;
break;
}
csrow->edac_mode = EDAC_SECDED;
}
static int __devinit mv64x60_mc_err_probe(struct platform_device *pdev)
{
struct mem_ctl_info *mci;
struct mv64x60_mc_pdata *pdata;
struct resource *r;
u32 ctl;
int res = 0;
if (!devres_open_group(&pdev->dev, mv64x60_mc_err_probe, GFP_KERNEL))
return -ENOMEM;
mci = edac_mc_alloc(sizeof(struct mv64x60_mc_pdata), 1, 1, edac_mc_idx);
if (!mci) {
printk(KERN_ERR "%s: No memory for CPU err\n", __func__);
devres_release_group(&pdev->dev, mv64x60_mc_err_probe);
return -ENOMEM;
}
pdata = mci->pvt_info;
mci->dev = &pdev->dev;
platform_set_drvdata(pdev, mci);
pdata->name = "mv64x60_mc_err";
pdata->irq = NO_IRQ;
mci->dev_name = dev_name(&pdev->dev);
pdata->edac_idx = edac_mc_idx++;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!r) {
printk(KERN_ERR "%s: Unable to get resource for "
"MC err regs\n", __func__);
res = -ENOENT;
goto err;
}
if (!devm_request_mem_region(&pdev->dev,
r->start,
resource_size(r),
pdata->name)) {
printk(KERN_ERR "%s: Error while requesting mem region\n",
__func__);
res = -EBUSY;
goto err;
}
pdata->mc_vbase = devm_ioremap(&pdev->dev,
r->start,
resource_size(r));
if (!pdata->mc_vbase) {
printk(KERN_ERR "%s: Unable to setup MC err regs\n", __func__);
res = -ENOMEM;
goto err;
}
ctl = in_le32(pdata->mc_vbase + MV64X60_SDRAM_CONFIG);
if (!(ctl & MV64X60_SDRAM_ECC)) {
/* Non-ECC RAM? */
printk(KERN_WARNING "%s: No ECC DIMMs discovered\n", __func__);
res = -ENODEV;
goto err2;
}
debugf3("%s(): init mci\n", __func__);
mci->mtype_cap = MEM_FLAG_RDDR | MEM_FLAG_DDR;
mci->edac_ctl_cap = EDAC_FLAG_NONE | EDAC_FLAG_SECDED;
mci->edac_cap = EDAC_FLAG_SECDED;
mci->mod_name = EDAC_MOD_STR;
mci->mod_ver = MV64x60_REVISION;
mci->ctl_name = mv64x60_ctl_name;
if (edac_op_state == EDAC_OPSTATE_POLL)
mci->edac_check = mv64x60_mc_check;
mci->ctl_page_to_phys = NULL;
mci->scrub_mode = SCRUB_SW_SRC;
mv64x60_init_csrows(mci, pdata);
/* setup MC registers */
out_le32(pdata->mc_vbase + MV64X60_SDRAM_ERR_ADDR, 0);
ctl = in_le32(pdata->mc_vbase + MV64X60_SDRAM_ERR_ECC_CNTL);
ctl = (ctl & 0xff00ffff) | 0x10000;
out_le32(pdata->mc_vbase + MV64X60_SDRAM_ERR_ECC_CNTL, ctl);
if (edac_mc_add_mc(mci)) {
debugf3("%s(): failed edac_mc_add_mc()\n", __func__);
goto err;
}
if (edac_op_state == EDAC_OPSTATE_INT) {
/* acquire interrupt that reports errors */
pdata->irq = platform_get_irq(pdev, 0);
res = devm_request_irq(&pdev->dev,
pdata->irq,
mv64x60_mc_isr,
IRQF_DISABLED,
"[EDAC] MC err",
mci);
if (res < 0) {
printk(KERN_ERR "%s: Unable to request irq %d for "
"MV64x60 DRAM ERR\n", __func__, pdata->irq);
res = -ENODEV;
goto err2;
}
printk(KERN_INFO EDAC_MOD_STR " acquired irq %d for MC Err\n",
pdata->irq);
}
/* get this far and it's successful */
debugf3("%s(): success\n", __func__);
return 0;
err2:
edac_mc_del_mc(&pdev->dev);
err:
devres_release_group(&pdev->dev, mv64x60_mc_err_probe);
edac_mc_free(mci);
return res;
}
static int mv64x60_mc_err_remove(struct platform_device *pdev)
{
struct mem_ctl_info *mci = platform_get_drvdata(pdev);
debugf0("%s()\n", __func__);
edac_mc_del_mc(&pdev->dev);
edac_mc_free(mci);
return 0;
}
static struct platform_driver mv64x60_mc_err_driver = {
.probe = mv64x60_mc_err_probe,
.remove = mv64x60_mc_err_remove,
.driver = {
.name = "mv64x60_mc_err",
}
};
static int __init mv64x60_edac_init(void)
{
int ret = 0;
printk(KERN_INFO "Marvell MV64x60 EDAC driver " MV64x60_REVISION "\n");
printk(KERN_INFO "\t(C) 2006-2007 MontaVista Software\n");
/* make sure error reporting method is sane */
switch (edac_op_state) {
case EDAC_OPSTATE_POLL:
case EDAC_OPSTATE_INT:
break;
default:
edac_op_state = EDAC_OPSTATE_INT;
break;
}
ret = platform_driver_register(&mv64x60_mc_err_driver);
if (ret)
printk(KERN_WARNING EDAC_MOD_STR "MC err failed to register\n");
ret = platform_driver_register(&mv64x60_cpu_err_driver);
if (ret)
printk(KERN_WARNING EDAC_MOD_STR
"CPU err failed to register\n");
ret = platform_driver_register(&mv64x60_sram_err_driver);
if (ret)
printk(KERN_WARNING EDAC_MOD_STR
"SRAM err failed to register\n");
#ifdef CONFIG_PCI
ret = platform_driver_register(&mv64x60_pci_err_driver);
if (ret)
printk(KERN_WARNING EDAC_MOD_STR
"PCI err failed to register\n");
#endif
return ret;
}
module_init(mv64x60_edac_init);
static void __exit mv64x60_edac_exit(void)
{
#ifdef CONFIG_PCI
platform_driver_unregister(&mv64x60_pci_err_driver);
#endif
platform_driver_unregister(&mv64x60_sram_err_driver);
platform_driver_unregister(&mv64x60_cpu_err_driver);
platform_driver_unregister(&mv64x60_mc_err_driver);
}
module_exit(mv64x60_edac_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Montavista Software, Inc.");
module_param(edac_op_state, int, 0444);
MODULE_PARM_DESC(edac_op_state,
"EDAC Error Reporting state: 0=Poll, 2=Interrupt");
| gpl-2.0 |
sjurbren/modem-ipc | drivers/infiniband/hw/ipath/ipath_wc_x86_64.c | 13439 | 6209 | /*
* Copyright (c) 2006, 2007 QLogic Corporation. All rights reserved.
* Copyright (c) 2003, 2004, 2005, 2006 PathScale, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* This file is conditionally built on x86_64 only. Otherwise weak symbol
* versions of the functions exported from here are used.
*/
#include <linux/pci.h>
#include <asm/mtrr.h>
#include <asm/processor.h>
#include "ipath_kernel.h"
/**
* ipath_enable_wc - enable write combining for MMIO writes to the device
* @dd: infinipath device
*
* This routine is x86_64-specific; it twiddles the CPU's MTRRs to enable
* write combining.
*/
int ipath_enable_wc(struct ipath_devdata *dd)
{
int ret = 0;
u64 pioaddr, piolen;
unsigned bits;
const unsigned long addr = pci_resource_start(dd->pcidev, 0);
const size_t len = pci_resource_len(dd->pcidev, 0);
/*
* Set the PIO buffers to be WCCOMB, so we get HT bursts to the
* chip. Linux (possibly the hardware) requires it to be on a power
* of 2 address matching the length (which has to be a power of 2).
* For rev1, that means the base address, for rev2, it will be just
* the PIO buffers themselves.
* For chips with two sets of buffers, the calculations are
* somewhat more complicated; we need to sum, and the piobufbase
* register has both offsets, 2K in low 32 bits, 4K in high 32 bits.
* The buffers are still packed, so a single range covers both.
*/
if (dd->ipath_piobcnt2k && dd->ipath_piobcnt4k) { /* 2 sizes */
unsigned long pio2kbase, pio4kbase;
pio2kbase = dd->ipath_piobufbase & 0xffffffffUL;
pio4kbase = (dd->ipath_piobufbase >> 32) & 0xffffffffUL;
if (pio2kbase < pio4kbase) { /* all, for now */
pioaddr = addr + pio2kbase;
piolen = pio4kbase - pio2kbase +
dd->ipath_piobcnt4k * dd->ipath_4kalign;
} else {
pioaddr = addr + pio4kbase;
piolen = pio2kbase - pio4kbase +
dd->ipath_piobcnt2k * dd->ipath_palign;
}
} else { /* single buffer size (2K, currently) */
pioaddr = addr + dd->ipath_piobufbase;
piolen = dd->ipath_piobcnt2k * dd->ipath_palign +
dd->ipath_piobcnt4k * dd->ipath_4kalign;
}
for (bits = 0; !(piolen & (1ULL << bits)); bits++)
/* do nothing */ ;
if (piolen != (1ULL << bits)) {
piolen >>= bits;
while (piolen >>= 1)
bits++;
piolen = 1ULL << (bits + 1);
}
if (pioaddr & (piolen - 1)) {
u64 atmp;
ipath_dbg("pioaddr %llx not on right boundary for size "
"%llx, fixing\n",
(unsigned long long) pioaddr,
(unsigned long long) piolen);
atmp = pioaddr & ~(piolen - 1);
if (atmp < addr || (atmp + piolen) > (addr + len)) {
ipath_dev_err(dd, "No way to align address/size "
"(%llx/%llx), no WC mtrr\n",
(unsigned long long) atmp,
(unsigned long long) piolen << 1);
ret = -ENODEV;
} else {
ipath_dbg("changing WC base from %llx to %llx, "
"len from %llx to %llx\n",
(unsigned long long) pioaddr,
(unsigned long long) atmp,
(unsigned long long) piolen,
(unsigned long long) piolen << 1);
pioaddr = atmp;
piolen <<= 1;
}
}
if (!ret) {
int cookie;
ipath_cdbg(VERBOSE, "Setting mtrr for chip to WC "
"(addr %llx, len=0x%llx)\n",
(unsigned long long) pioaddr,
(unsigned long long) piolen);
cookie = mtrr_add(pioaddr, piolen, MTRR_TYPE_WRCOMB, 0);
if (cookie < 0) {
{
dev_info(&dd->pcidev->dev,
"mtrr_add() WC for PIO bufs "
"failed (%d)\n",
cookie);
ret = -EINVAL;
}
} else {
ipath_cdbg(VERBOSE, "Set mtrr for chip to WC, "
"cookie is %d\n", cookie);
dd->ipath_wc_cookie = cookie;
dd->ipath_wc_base = (unsigned long) pioaddr;
dd->ipath_wc_len = (unsigned long) piolen;
}
}
return ret;
}
/**
* ipath_disable_wc - disable write combining for MMIO writes to the device
* @dd: infinipath device
*/
void ipath_disable_wc(struct ipath_devdata *dd)
{
if (dd->ipath_wc_cookie) {
int r;
ipath_cdbg(VERBOSE, "undoing WCCOMB on pio buffers\n");
r = mtrr_del(dd->ipath_wc_cookie, dd->ipath_wc_base,
dd->ipath_wc_len);
if (r < 0)
dev_info(&dd->pcidev->dev,
"mtrr_del(%lx, %lx, %lx) failed: %d\n",
dd->ipath_wc_cookie, dd->ipath_wc_base,
dd->ipath_wc_len, r);
dd->ipath_wc_cookie = 0; /* even on failure */
}
}
/**
* ipath_unordered_wc - indicate whether write combining is ordered
*
* Because our performance depends on our ability to do write combining mmio
* writes in the most efficient way, we need to know if we are on an Intel
* or AMD x86_64 processor. AMD x86_64 processors flush WC buffers out in
* the order completed, and so no special flushing is required to get
* correct ordering. Intel processors, however, will flush write buffers
* out in "random" orders, and so explicit ordering is needed at times.
*/
int ipath_unordered_wc(void)
{
return boot_cpu_data.x86_vendor != X86_VENDOR_AMD;
}
| gpl-2.0 |
mdeejay/android_kernel_mako | arch/powerpc/xmon/ppc-dis.c | 13695 | 5571 | /* ppc-dis.c -- Disassemble PowerPC instructions
Copyright 1994, 1995, 2000, 2001, 2002, 2003, 2004, 2005, 2006
Free Software Foundation, Inc.
Written by Ian Lance Taylor, Cygnus Support
This file is part of GDB, GAS, and the GNU binutils.
GDB, GAS, and the GNU binutils are free software; you can redistribute
them and/or modify them under the terms of the GNU General Public
License as published by the Free Software Foundation; either version
2, or (at your option) any later version.
GDB, GAS, and the GNU binutils are distributed in the hope that they
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 file; see the file COPYING. If not, write to the Free
Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */
#include <asm/cputable.h>
#include "nonstdio.h"
#include "ansidecl.h"
#include "ppc.h"
#include "dis-asm.h"
/* Print a PowerPC or POWER instruction. */
int
print_insn_powerpc (unsigned long insn, unsigned long memaddr)
{
const struct powerpc_opcode *opcode;
const struct powerpc_opcode *opcode_end;
unsigned long op;
int dialect;
dialect = PPC_OPCODE_PPC | PPC_OPCODE_CLASSIC | PPC_OPCODE_COMMON
| PPC_OPCODE_64 | PPC_OPCODE_POWER4 | PPC_OPCODE_ALTIVEC;
if (cpu_has_feature(CPU_FTRS_POWER5))
dialect |= PPC_OPCODE_POWER5;
if (cpu_has_feature(CPU_FTRS_CELL))
dialect |= PPC_OPCODE_CELL | PPC_OPCODE_ALTIVEC;
if (cpu_has_feature(CPU_FTRS_POWER6))
dialect |= PPC_OPCODE_POWER5 | PPC_OPCODE_POWER6 | PPC_OPCODE_ALTIVEC;
/* Get the major opcode of the instruction. */
op = PPC_OP (insn);
/* Find the first match in the opcode table. We could speed this up
a bit by doing a binary search on the major opcode. */
opcode_end = powerpc_opcodes + powerpc_num_opcodes;
again:
for (opcode = powerpc_opcodes; opcode < opcode_end; opcode++)
{
unsigned long table_op;
const unsigned char *opindex;
const struct powerpc_operand *operand;
int invalid;
int need_comma;
int need_paren;
table_op = PPC_OP (opcode->opcode);
if (op < table_op)
break;
if (op > table_op)
continue;
if ((insn & opcode->mask) != opcode->opcode
|| (opcode->flags & dialect) == 0)
continue;
/* Make two passes over the operands. First see if any of them
have extraction functions, and, if they do, make sure the
instruction is valid. */
invalid = 0;
for (opindex = opcode->operands; *opindex != 0; opindex++)
{
operand = powerpc_operands + *opindex;
if (operand->extract)
(*operand->extract) (insn, dialect, &invalid);
}
if (invalid)
continue;
/* The instruction is valid. */
printf("%s", opcode->name);
if (opcode->operands[0] != 0)
printf("\t");
/* Now extract and print the operands. */
need_comma = 0;
need_paren = 0;
for (opindex = opcode->operands; *opindex != 0; opindex++)
{
long value;
operand = powerpc_operands + *opindex;
/* Operands that are marked FAKE are simply ignored. We
already made sure that the extract function considered
the instruction to be valid. */
if ((operand->flags & PPC_OPERAND_FAKE) != 0)
continue;
/* Extract the value from the instruction. */
if (operand->extract)
value = (*operand->extract) (insn, dialect, &invalid);
else
{
value = (insn >> operand->shift) & ((1 << operand->bits) - 1);
if ((operand->flags & PPC_OPERAND_SIGNED) != 0
&& (value & (1 << (operand->bits - 1))) != 0)
value -= 1 << operand->bits;
}
/* If the operand is optional, and the value is zero, don't
print anything. */
if ((operand->flags & PPC_OPERAND_OPTIONAL) != 0
&& (operand->flags & PPC_OPERAND_NEXT) == 0
&& value == 0)
continue;
if (need_comma)
{
printf(",");
need_comma = 0;
}
/* Print the operand as directed by the flags. */
if ((operand->flags & PPC_OPERAND_GPR) != 0
|| ((operand->flags & PPC_OPERAND_GPR_0) != 0 && value != 0))
printf("r%ld", value);
else if ((operand->flags & PPC_OPERAND_FPR) != 0)
printf("f%ld", value);
else if ((operand->flags & PPC_OPERAND_VR) != 0)
printf("v%ld", value);
else if ((operand->flags & PPC_OPERAND_RELATIVE) != 0)
print_address (memaddr + value);
else if ((operand->flags & PPC_OPERAND_ABSOLUTE) != 0)
print_address (value & 0xffffffff);
else if ((operand->flags & PPC_OPERAND_CR) == 0
|| (dialect & PPC_OPCODE_PPC) == 0)
printf("%ld", value);
else
{
if (operand->bits == 3)
printf("cr%ld", value);
else
{
static const char *cbnames[4] = { "lt", "gt", "eq", "so" };
int cr;
int cc;
cr = value >> 2;
if (cr != 0)
printf("4*cr%d+", cr);
cc = value & 3;
printf("%s", cbnames[cc]);
}
}
if (need_paren)
{
printf(")");
need_paren = 0;
}
if ((operand->flags & PPC_OPERAND_PARENS) == 0)
need_comma = 1;
else
{
printf("(");
need_paren = 1;
}
}
/* We have found and printed an instruction; return. */
return 4;
}
if ((dialect & PPC_OPCODE_ANY) != 0)
{
dialect = ~PPC_OPCODE_ANY;
goto again;
}
/* We could not find a match. */
printf(".long 0x%lx", insn);
return 4;
}
| gpl-2.0 |
Foxda-Tech/polaris-kernel | arch/arm/mach-pxa/csb701.c | 14207 | 1321 | #include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <linux/leds.h>
#include <asm/mach-types.h>
static struct gpio_keys_button csb701_buttons[] = {
{
.code = 0x7,
.gpio = 1,
.active_low = 1,
.desc = "SW2",
.type = EV_SW,
.wakeup = 1,
},
};
static struct gpio_keys_platform_data csb701_gpio_keys_data = {
.buttons = csb701_buttons,
.nbuttons = ARRAY_SIZE(csb701_buttons),
};
static struct gpio_led csb701_leds[] = {
{
.name = "csb701:yellow:heartbeat",
.default_trigger = "heartbeat",
.gpio = 11,
.active_low = 1,
},
};
static struct platform_device csb701_gpio_keys = {
.name = "gpio-keys",
.id = -1,
.dev.platform_data = &csb701_gpio_keys_data,
};
static struct gpio_led_platform_data csb701_leds_gpio_data = {
.leds = csb701_leds,
.num_leds = ARRAY_SIZE(csb701_leds),
};
static struct platform_device csb701_leds_gpio = {
.name = "leds-gpio",
.id = -1,
.dev.platform_data = &csb701_leds_gpio_data,
};
static struct platform_device *devices[] __initdata = {
&csb701_gpio_keys,
&csb701_leds_gpio,
};
static int __init csb701_init(void)
{
if (!machine_is_csb726())
return -ENODEV;
return platform_add_devices(devices, ARRAY_SIZE(devices));
}
module_init(csb701_init);
| gpl-2.0 |
ProjectX-Android/kernel_htc_msm8974 | drivers/htc_debug/stability/htc_report_meminfo.c | 128 | 4509 | #include <linux/mm_types.h>
#include <linux/mm.h>
#include <linux/seq_file.h>
#include <linux/swap.h>
#include <linux/fs.h>
#include <linux/msm_kgsl.h>
#include <htc_debug/stability/htc_report_meminfo.h>
static atomic_long_t meminfo_stat[NR_MEMINFO_STAT_ITEMS] =
{[0 ... NR_MEMINFO_STAT_ITEMS - 1] = ATOMIC_LONG_INIT(0)};
const char * const meminfo_stat_text[] = {
[NR_KMALLOC_PAGES] = "Kmalloc",
[NR_VMALLOC_PAGES] = "VmallocAlloc",
[NR_DMA_PAGES] = "DmaAlloc",
[NR_IOMMU_PAGETABLES_PAGES] = "IommuPgd",
[NR_DRIVER_ALLOC_PAGES] = "DriverAlloc",
[NR_HASHTABLES_PAGES] = "HashTables",
[NR_MEMPOOL_ALLOC_PAGES] = "MemPoolAlloc",
};
static atomic_long_t cached_mapped_stat = ATOMIC_LONG_INIT(0);
static atomic_long_t kgsl_mapped_stat = ATOMIC_LONG_INIT(0);
void kmalloc_count(struct page *page, int to_alloc)
{
if (unlikely(!page))
return;
if (to_alloc) {
int order = compound_order(page);
SetPageKmalloc(page);
add_meminfo_total_pages(NR_KMALLOC_PAGES, 1 << order);
} else if (PageKmalloc(page)) {
int order = compound_order(page);
ClearPageKmalloc(page);
sub_meminfo_total_pages(NR_KMALLOC_PAGES, 1 << order);
}
}
struct super_block;
extern int sb_is_blkdev_sb(struct super_block *sb);
static inline int page_is_cached(struct page *page)
{
return page_mapping(page) && !PageSwapCache(page) &&
page->mapping->host && page->mapping->host->i_sb &&
!sb_is_blkdev_sb(page->mapping->host->i_sb);
}
void mapped_count(struct page *page, int to_map)
{
if (unlikely(!page))
return;
if (PageKgsl(page)) {
if (to_map)
atomic_long_inc(&kgsl_mapped_stat);
else
atomic_long_dec(&kgsl_mapped_stat);
} else if (page_is_cached(page)) {
if (to_map)
atomic_long_inc(&cached_mapped_stat);
else
atomic_long_dec(&cached_mapped_stat);
}
}
static unsigned long driver_alloc_total_pages(void)
{
long total = 0UL;
int i;
for (i = NR_DRIVER_ALLOC_BASE; i < NR_MEMINFO_STAT_ITEMS; i++)
total += atomic_long_read(&meminfo_stat[i]);
if (total < 0)
total = 0;
return (unsigned long) total;
}
static inline unsigned long cached_pages(struct sysinfo *i)
{
long cached = global_page_state(NR_FILE_PAGES) -
total_swapcache_pages - i->bufferram;
if (cached < 0)
cached = 0;
return cached;
}
unsigned long cached_unmapped_pages(struct sysinfo *i)
{
long cached_unmapped = (long)cached_pages(i) -
atomic_long_read(&cached_mapped_stat);
if (cached_unmapped < 0)
cached_unmapped = 0;
return cached_unmapped;
}
unsigned long kgsl_unmapped_pages(void)
{
long kgsl_alloc = kgsl_get_alloc_size(false) >> PAGE_SHIFT;
long kgsl_unmapped = kgsl_alloc -
atomic_long_read(&kgsl_mapped_stat);
if (kgsl_unmapped < 0)
kgsl_unmapped = 0;
return kgsl_unmapped;
}
unsigned long meminfo_total_pages(enum meminfo_stat_item item)
{
long total = atomic_long_read(&meminfo_stat[item]);
if (item == NR_DRIVER_ALLOC_PAGES)
return driver_alloc_total_pages();
if (total < 0)
total = 0;
return (unsigned long) total;
}
void inc_meminfo_total_pages(enum meminfo_stat_item item)
{
atomic_long_inc(&meminfo_stat[item]);
}
void dec_meminfo_total_pages(enum meminfo_stat_item item)
{
atomic_long_dec(&meminfo_stat[item]);
}
void add_meminfo_total_pages(enum meminfo_stat_item item, int delta)
{
atomic_long_add(delta, &meminfo_stat[item]);
}
void sub_meminfo_total_pages(enum meminfo_stat_item item, int delta)
{
atomic_long_sub(delta, &meminfo_stat[item]);
}
void report_meminfo_item(struct seq_file *m, enum meminfo_stat_item item)
{
unsigned long total = meminfo_total_pages(item);
char buf[32];
snprintf(buf, 32, "%s:", meminfo_stat_text[item]);
#define K(x) ((x) << (PAGE_SHIFT - 10))
seq_printf(m, "%-16s%8lu kB\n", buf, K(total));
#undef K
}
static void report_unmapped(struct seq_file *m, struct sysinfo *sysinfo)
{
unsigned long cached_unmapped = cached_unmapped_pages(sysinfo);
unsigned long kgsl_unmapped = kgsl_unmapped_pages();
#define K(x) ((x) << (PAGE_SHIFT - 10))
seq_printf(m, "%-16s%8lu kB\n", "CachedUnmapped: ", K(cached_unmapped));
seq_printf(m, "%-16s%8lu kB\n", "KgslUnmapped: ", K(kgsl_unmapped));
#undef K
}
void report_meminfo(struct seq_file *m, struct sysinfo *sysinfo)
{
int i;
for (i = 0; i <= NR_DRIVER_ALLOC_PAGES; i++) {
if (i == NR_VMALLOC_PAGES)
continue;
report_meminfo_item(m, i);
}
report_unmapped(m, sysinfo);
#define K(x) ((x) << (PAGE_SHIFT - 10))
seq_printf(m, "%-16s%8lu kB\n", "Ftrace: ", K(ftrace_total_pages()));
#undef K
}
| gpl-2.0 |
malvira/uboot | api/api_net.c | 128 | 2401 | /*
* (C) Copyright 2007 Semihalf
*
* Written by: Rafal Jaworowski <raj@semihalf.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 <config.h>
#include <common.h>
#include <net.h>
#include <linux/types.h>
#include <api_public.h>
DECLARE_GLOBAL_DATA_PTR;
#define DEBUG
#undef DEBUG
#ifdef DEBUG
#define debugf(fmt, args...) do { printf("%s(): ", __func__); printf(fmt, ##args); } while (0)
#else
#define debugf(fmt, args...)
#endif
#define errf(fmt, args...) do { printf("ERROR @ %s(): ", __func__); printf(fmt, ##args); } while (0)
static int dev_valid_net(void *cookie)
{
return ((void *)eth_get_dev() == cookie) ? 1 : 0;
}
int dev_open_net(void *cookie)
{
if (!dev_valid_net(cookie))
return API_ENODEV;
if (eth_init(gd->bd) < 0)
return API_EIO;
return 0;
}
int dev_close_net(void *cookie)
{
if (!dev_valid_net(cookie))
return API_ENODEV;
eth_halt();
return 0;
}
/*
* There can only be one active eth interface at a time - use what is
* currently set to eth_current
*/
int dev_enum_net(struct device_info *di)
{
struct eth_device *eth_current = eth_get_dev();
di->type = DEV_TYP_NET;
di->cookie = (void *)eth_current;
if (di->cookie == NULL)
return 0;
memcpy(di->di_net.hwaddr, eth_current->enetaddr, 6);
debugf("device found, returning cookie 0x%08x\n",
(u_int32_t)di->cookie);
return 1;
}
int dev_write_net(void *cookie, void *buf, int len)
{
/* XXX verify that cookie points to a valid net device??? */
return eth_send(buf, len);
}
int dev_read_net(void *cookie, void *buf, int len)
{
/* XXX verify that cookie points to a valid net device??? */
return eth_receive(buf, len);
}
| gpl-2.0 |
cosmicexplorer/linux | drivers/infiniband/hw/mlx5/qp.c | 128 | 83927 | /*
* Copyright (c) 2013-2015, Mellanox Technologies. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/module.h>
#include <rdma/ib_umem.h>
#include "mlx5_ib.h"
#include "user.h"
/* not supported currently */
static int wq_signature;
enum {
MLX5_IB_ACK_REQ_FREQ = 8,
};
enum {
MLX5_IB_DEFAULT_SCHED_QUEUE = 0x83,
MLX5_IB_DEFAULT_QP0_SCHED_QUEUE = 0x3f,
MLX5_IB_LINK_TYPE_IB = 0,
MLX5_IB_LINK_TYPE_ETH = 1
};
enum {
MLX5_IB_SQ_STRIDE = 6,
MLX5_IB_CACHE_LINE_SIZE = 64,
};
static const u32 mlx5_ib_opcode[] = {
[IB_WR_SEND] = MLX5_OPCODE_SEND,
[IB_WR_SEND_WITH_IMM] = MLX5_OPCODE_SEND_IMM,
[IB_WR_RDMA_WRITE] = MLX5_OPCODE_RDMA_WRITE,
[IB_WR_RDMA_WRITE_WITH_IMM] = MLX5_OPCODE_RDMA_WRITE_IMM,
[IB_WR_RDMA_READ] = MLX5_OPCODE_RDMA_READ,
[IB_WR_ATOMIC_CMP_AND_SWP] = MLX5_OPCODE_ATOMIC_CS,
[IB_WR_ATOMIC_FETCH_AND_ADD] = MLX5_OPCODE_ATOMIC_FA,
[IB_WR_SEND_WITH_INV] = MLX5_OPCODE_SEND_INVAL,
[IB_WR_LOCAL_INV] = MLX5_OPCODE_UMR,
[IB_WR_FAST_REG_MR] = MLX5_OPCODE_UMR,
[IB_WR_MASKED_ATOMIC_CMP_AND_SWP] = MLX5_OPCODE_ATOMIC_MASKED_CS,
[IB_WR_MASKED_ATOMIC_FETCH_AND_ADD] = MLX5_OPCODE_ATOMIC_MASKED_FA,
[MLX5_IB_WR_UMR] = MLX5_OPCODE_UMR,
};
static int is_qp0(enum ib_qp_type qp_type)
{
return qp_type == IB_QPT_SMI;
}
static int is_sqp(enum ib_qp_type qp_type)
{
return is_qp0(qp_type) || is_qp1(qp_type);
}
static void *get_wqe(struct mlx5_ib_qp *qp, int offset)
{
return mlx5_buf_offset(&qp->buf, offset);
}
static void *get_recv_wqe(struct mlx5_ib_qp *qp, int n)
{
return get_wqe(qp, qp->rq.offset + (n << qp->rq.wqe_shift));
}
void *mlx5_get_send_wqe(struct mlx5_ib_qp *qp, int n)
{
return get_wqe(qp, qp->sq.offset + (n << MLX5_IB_SQ_STRIDE));
}
/**
* mlx5_ib_read_user_wqe() - Copy a user-space WQE to kernel space.
*
* @qp: QP to copy from.
* @send: copy from the send queue when non-zero, use the receive queue
* otherwise.
* @wqe_index: index to start copying from. For send work queues, the
* wqe_index is in units of MLX5_SEND_WQE_BB.
* For receive work queue, it is the number of work queue
* element in the queue.
* @buffer: destination buffer.
* @length: maximum number of bytes to copy.
*
* Copies at least a single WQE, but may copy more data.
*
* Return: the number of bytes copied, or an error code.
*/
int mlx5_ib_read_user_wqe(struct mlx5_ib_qp *qp, int send, int wqe_index,
void *buffer, u32 length)
{
struct ib_device *ibdev = qp->ibqp.device;
struct mlx5_ib_dev *dev = to_mdev(ibdev);
struct mlx5_ib_wq *wq = send ? &qp->sq : &qp->rq;
size_t offset;
size_t wq_end;
struct ib_umem *umem = qp->umem;
u32 first_copy_length;
int wqe_length;
int ret;
if (wq->wqe_cnt == 0) {
mlx5_ib_dbg(dev, "mlx5_ib_read_user_wqe for a QP with wqe_cnt == 0. qp_type: 0x%x\n",
qp->ibqp.qp_type);
return -EINVAL;
}
offset = wq->offset + ((wqe_index % wq->wqe_cnt) << wq->wqe_shift);
wq_end = wq->offset + (wq->wqe_cnt << wq->wqe_shift);
if (send && length < sizeof(struct mlx5_wqe_ctrl_seg))
return -EINVAL;
if (offset > umem->length ||
(send && offset + sizeof(struct mlx5_wqe_ctrl_seg) > umem->length))
return -EINVAL;
first_copy_length = min_t(u32, offset + length, wq_end) - offset;
ret = ib_umem_copy_from(buffer, umem, offset, first_copy_length);
if (ret)
return ret;
if (send) {
struct mlx5_wqe_ctrl_seg *ctrl = buffer;
int ds = be32_to_cpu(ctrl->qpn_ds) & MLX5_WQE_CTRL_DS_MASK;
wqe_length = ds * MLX5_WQE_DS_UNITS;
} else {
wqe_length = 1 << wq->wqe_shift;
}
if (wqe_length <= first_copy_length)
return first_copy_length;
ret = ib_umem_copy_from(buffer + first_copy_length, umem, wq->offset,
wqe_length - first_copy_length);
if (ret)
return ret;
return wqe_length;
}
static void mlx5_ib_qp_event(struct mlx5_core_qp *qp, int type)
{
struct ib_qp *ibqp = &to_mibqp(qp)->ibqp;
struct ib_event event;
if (type == MLX5_EVENT_TYPE_PATH_MIG)
to_mibqp(qp)->port = to_mibqp(qp)->alt_port;
if (ibqp->event_handler) {
event.device = ibqp->device;
event.element.qp = ibqp;
switch (type) {
case MLX5_EVENT_TYPE_PATH_MIG:
event.event = IB_EVENT_PATH_MIG;
break;
case MLX5_EVENT_TYPE_COMM_EST:
event.event = IB_EVENT_COMM_EST;
break;
case MLX5_EVENT_TYPE_SQ_DRAINED:
event.event = IB_EVENT_SQ_DRAINED;
break;
case MLX5_EVENT_TYPE_SRQ_LAST_WQE:
event.event = IB_EVENT_QP_LAST_WQE_REACHED;
break;
case MLX5_EVENT_TYPE_WQ_CATAS_ERROR:
event.event = IB_EVENT_QP_FATAL;
break;
case MLX5_EVENT_TYPE_PATH_MIG_FAILED:
event.event = IB_EVENT_PATH_MIG_ERR;
break;
case MLX5_EVENT_TYPE_WQ_INVAL_REQ_ERROR:
event.event = IB_EVENT_QP_REQ_ERR;
break;
case MLX5_EVENT_TYPE_WQ_ACCESS_ERROR:
event.event = IB_EVENT_QP_ACCESS_ERR;
break;
default:
pr_warn("mlx5_ib: Unexpected event type %d on QP %06x\n", type, qp->qpn);
return;
}
ibqp->event_handler(&event, ibqp->qp_context);
}
}
static int set_rq_size(struct mlx5_ib_dev *dev, struct ib_qp_cap *cap,
int has_rq, struct mlx5_ib_qp *qp, struct mlx5_ib_create_qp *ucmd)
{
int wqe_size;
int wq_size;
/* Sanity check RQ size before proceeding */
if (cap->max_recv_wr > (1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz)))
return -EINVAL;
if (!has_rq) {
qp->rq.max_gs = 0;
qp->rq.wqe_cnt = 0;
qp->rq.wqe_shift = 0;
} else {
if (ucmd) {
qp->rq.wqe_cnt = ucmd->rq_wqe_count;
qp->rq.wqe_shift = ucmd->rq_wqe_shift;
qp->rq.max_gs = (1 << qp->rq.wqe_shift) / sizeof(struct mlx5_wqe_data_seg) - qp->wq_sig;
qp->rq.max_post = qp->rq.wqe_cnt;
} else {
wqe_size = qp->wq_sig ? sizeof(struct mlx5_wqe_signature_seg) : 0;
wqe_size += cap->max_recv_sge * sizeof(struct mlx5_wqe_data_seg);
wqe_size = roundup_pow_of_two(wqe_size);
wq_size = roundup_pow_of_two(cap->max_recv_wr) * wqe_size;
wq_size = max_t(int, wq_size, MLX5_SEND_WQE_BB);
qp->rq.wqe_cnt = wq_size / wqe_size;
if (wqe_size > MLX5_CAP_GEN(dev->mdev, max_wqe_sz_rq)) {
mlx5_ib_dbg(dev, "wqe_size %d, max %d\n",
wqe_size,
MLX5_CAP_GEN(dev->mdev,
max_wqe_sz_rq));
return -EINVAL;
}
qp->rq.wqe_shift = ilog2(wqe_size);
qp->rq.max_gs = (1 << qp->rq.wqe_shift) / sizeof(struct mlx5_wqe_data_seg) - qp->wq_sig;
qp->rq.max_post = qp->rq.wqe_cnt;
}
}
return 0;
}
static int sq_overhead(enum ib_qp_type qp_type)
{
int size = 0;
switch (qp_type) {
case IB_QPT_XRC_INI:
size += sizeof(struct mlx5_wqe_xrc_seg);
/* fall through */
case IB_QPT_RC:
size += sizeof(struct mlx5_wqe_ctrl_seg) +
sizeof(struct mlx5_wqe_atomic_seg) +
sizeof(struct mlx5_wqe_raddr_seg);
break;
case IB_QPT_XRC_TGT:
return 0;
case IB_QPT_UC:
size += sizeof(struct mlx5_wqe_ctrl_seg) +
sizeof(struct mlx5_wqe_raddr_seg) +
sizeof(struct mlx5_wqe_umr_ctrl_seg) +
sizeof(struct mlx5_mkey_seg);
break;
case IB_QPT_UD:
case IB_QPT_SMI:
case IB_QPT_GSI:
size += sizeof(struct mlx5_wqe_ctrl_seg) +
sizeof(struct mlx5_wqe_datagram_seg);
break;
case MLX5_IB_QPT_REG_UMR:
size += sizeof(struct mlx5_wqe_ctrl_seg) +
sizeof(struct mlx5_wqe_umr_ctrl_seg) +
sizeof(struct mlx5_mkey_seg);
break;
default:
return -EINVAL;
}
return size;
}
static int calc_send_wqe(struct ib_qp_init_attr *attr)
{
int inl_size = 0;
int size;
size = sq_overhead(attr->qp_type);
if (size < 0)
return size;
if (attr->cap.max_inline_data) {
inl_size = size + sizeof(struct mlx5_wqe_inline_seg) +
attr->cap.max_inline_data;
}
size += attr->cap.max_send_sge * sizeof(struct mlx5_wqe_data_seg);
if (attr->create_flags & IB_QP_CREATE_SIGNATURE_EN &&
ALIGN(max_t(int, inl_size, size), MLX5_SEND_WQE_BB) < MLX5_SIG_WQE_SIZE)
return MLX5_SIG_WQE_SIZE;
else
return ALIGN(max_t(int, inl_size, size), MLX5_SEND_WQE_BB);
}
static int calc_sq_size(struct mlx5_ib_dev *dev, struct ib_qp_init_attr *attr,
struct mlx5_ib_qp *qp)
{
int wqe_size;
int wq_size;
if (!attr->cap.max_send_wr)
return 0;
wqe_size = calc_send_wqe(attr);
mlx5_ib_dbg(dev, "wqe_size %d\n", wqe_size);
if (wqe_size < 0)
return wqe_size;
if (wqe_size > MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq)) {
mlx5_ib_dbg(dev, "wqe_size(%d) > max_sq_desc_sz(%d)\n",
wqe_size, MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq));
return -EINVAL;
}
qp->max_inline_data = wqe_size - sq_overhead(attr->qp_type) -
sizeof(struct mlx5_wqe_inline_seg);
attr->cap.max_inline_data = qp->max_inline_data;
if (attr->create_flags & IB_QP_CREATE_SIGNATURE_EN)
qp->signature_en = true;
wq_size = roundup_pow_of_two(attr->cap.max_send_wr * wqe_size);
qp->sq.wqe_cnt = wq_size / MLX5_SEND_WQE_BB;
if (qp->sq.wqe_cnt > (1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz))) {
mlx5_ib_dbg(dev, "wqe count(%d) exceeds limits(%d)\n",
qp->sq.wqe_cnt,
1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz));
return -ENOMEM;
}
qp->sq.wqe_shift = ilog2(MLX5_SEND_WQE_BB);
qp->sq.max_gs = attr->cap.max_send_sge;
qp->sq.max_post = wq_size / wqe_size;
attr->cap.max_send_wr = qp->sq.max_post;
return wq_size;
}
static int set_user_buf_size(struct mlx5_ib_dev *dev,
struct mlx5_ib_qp *qp,
struct mlx5_ib_create_qp *ucmd)
{
int desc_sz = 1 << qp->sq.wqe_shift;
if (desc_sz > MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq)) {
mlx5_ib_warn(dev, "desc_sz %d, max_sq_desc_sz %d\n",
desc_sz, MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq));
return -EINVAL;
}
if (ucmd->sq_wqe_count && ((1 << ilog2(ucmd->sq_wqe_count)) != ucmd->sq_wqe_count)) {
mlx5_ib_warn(dev, "sq_wqe_count %d, sq_wqe_count %d\n",
ucmd->sq_wqe_count, ucmd->sq_wqe_count);
return -EINVAL;
}
qp->sq.wqe_cnt = ucmd->sq_wqe_count;
if (qp->sq.wqe_cnt > (1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz))) {
mlx5_ib_warn(dev, "wqe_cnt %d, max_wqes %d\n",
qp->sq.wqe_cnt,
1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz));
return -EINVAL;
}
qp->buf_size = (qp->rq.wqe_cnt << qp->rq.wqe_shift) +
(qp->sq.wqe_cnt << 6);
return 0;
}
static int qp_has_rq(struct ib_qp_init_attr *attr)
{
if (attr->qp_type == IB_QPT_XRC_INI ||
attr->qp_type == IB_QPT_XRC_TGT || attr->srq ||
attr->qp_type == MLX5_IB_QPT_REG_UMR ||
!attr->cap.max_recv_wr)
return 0;
return 1;
}
static int first_med_uuar(void)
{
return 1;
}
static int next_uuar(int n)
{
n++;
while (((n % 4) & 2))
n++;
return n;
}
static int num_med_uuar(struct mlx5_uuar_info *uuari)
{
int n;
n = uuari->num_uars * MLX5_NON_FP_BF_REGS_PER_PAGE -
uuari->num_low_latency_uuars - 1;
return n >= 0 ? n : 0;
}
static int max_uuari(struct mlx5_uuar_info *uuari)
{
return uuari->num_uars * 4;
}
static int first_hi_uuar(struct mlx5_uuar_info *uuari)
{
int med;
int i;
int t;
med = num_med_uuar(uuari);
for (t = 0, i = first_med_uuar();; i = next_uuar(i)) {
t++;
if (t == med)
return next_uuar(i);
}
return 0;
}
static int alloc_high_class_uuar(struct mlx5_uuar_info *uuari)
{
int i;
for (i = first_hi_uuar(uuari); i < max_uuari(uuari); i = next_uuar(i)) {
if (!test_bit(i, uuari->bitmap)) {
set_bit(i, uuari->bitmap);
uuari->count[i]++;
return i;
}
}
return -ENOMEM;
}
static int alloc_med_class_uuar(struct mlx5_uuar_info *uuari)
{
int minidx = first_med_uuar();
int i;
for (i = first_med_uuar(); i < first_hi_uuar(uuari); i = next_uuar(i)) {
if (uuari->count[i] < uuari->count[minidx])
minidx = i;
}
uuari->count[minidx]++;
return minidx;
}
static int alloc_uuar(struct mlx5_uuar_info *uuari,
enum mlx5_ib_latency_class lat)
{
int uuarn = -EINVAL;
mutex_lock(&uuari->lock);
switch (lat) {
case MLX5_IB_LATENCY_CLASS_LOW:
uuarn = 0;
uuari->count[uuarn]++;
break;
case MLX5_IB_LATENCY_CLASS_MEDIUM:
if (uuari->ver < 2)
uuarn = -ENOMEM;
else
uuarn = alloc_med_class_uuar(uuari);
break;
case MLX5_IB_LATENCY_CLASS_HIGH:
if (uuari->ver < 2)
uuarn = -ENOMEM;
else
uuarn = alloc_high_class_uuar(uuari);
break;
case MLX5_IB_LATENCY_CLASS_FAST_PATH:
uuarn = 2;
break;
}
mutex_unlock(&uuari->lock);
return uuarn;
}
static void free_med_class_uuar(struct mlx5_uuar_info *uuari, int uuarn)
{
clear_bit(uuarn, uuari->bitmap);
--uuari->count[uuarn];
}
static void free_high_class_uuar(struct mlx5_uuar_info *uuari, int uuarn)
{
clear_bit(uuarn, uuari->bitmap);
--uuari->count[uuarn];
}
static void free_uuar(struct mlx5_uuar_info *uuari, int uuarn)
{
int nuuars = uuari->num_uars * MLX5_BF_REGS_PER_PAGE;
int high_uuar = nuuars - uuari->num_low_latency_uuars;
mutex_lock(&uuari->lock);
if (uuarn == 0) {
--uuari->count[uuarn];
goto out;
}
if (uuarn < high_uuar) {
free_med_class_uuar(uuari, uuarn);
goto out;
}
free_high_class_uuar(uuari, uuarn);
out:
mutex_unlock(&uuari->lock);
}
static enum mlx5_qp_state to_mlx5_state(enum ib_qp_state state)
{
switch (state) {
case IB_QPS_RESET: return MLX5_QP_STATE_RST;
case IB_QPS_INIT: return MLX5_QP_STATE_INIT;
case IB_QPS_RTR: return MLX5_QP_STATE_RTR;
case IB_QPS_RTS: return MLX5_QP_STATE_RTS;
case IB_QPS_SQD: return MLX5_QP_STATE_SQD;
case IB_QPS_SQE: return MLX5_QP_STATE_SQER;
case IB_QPS_ERR: return MLX5_QP_STATE_ERR;
default: return -1;
}
}
static int to_mlx5_st(enum ib_qp_type type)
{
switch (type) {
case IB_QPT_RC: return MLX5_QP_ST_RC;
case IB_QPT_UC: return MLX5_QP_ST_UC;
case IB_QPT_UD: return MLX5_QP_ST_UD;
case MLX5_IB_QPT_REG_UMR: return MLX5_QP_ST_REG_UMR;
case IB_QPT_XRC_INI:
case IB_QPT_XRC_TGT: return MLX5_QP_ST_XRC;
case IB_QPT_SMI: return MLX5_QP_ST_QP0;
case IB_QPT_GSI: return MLX5_QP_ST_QP1;
case IB_QPT_RAW_IPV6: return MLX5_QP_ST_RAW_IPV6;
case IB_QPT_RAW_ETHERTYPE: return MLX5_QP_ST_RAW_ETHERTYPE;
case IB_QPT_RAW_PACKET:
case IB_QPT_MAX:
default: return -EINVAL;
}
}
static int uuarn_to_uar_index(struct mlx5_uuar_info *uuari, int uuarn)
{
return uuari->uars[uuarn / MLX5_BF_REGS_PER_PAGE].index;
}
static int create_user_qp(struct mlx5_ib_dev *dev, struct ib_pd *pd,
struct mlx5_ib_qp *qp, struct ib_udata *udata,
struct mlx5_create_qp_mbox_in **in,
struct mlx5_ib_create_qp_resp *resp, int *inlen)
{
struct mlx5_ib_ucontext *context;
struct mlx5_ib_create_qp ucmd;
int page_shift = 0;
int uar_index;
int npages;
u32 offset = 0;
int uuarn;
int ncont = 0;
int err;
err = ib_copy_from_udata(&ucmd, udata, sizeof(ucmd));
if (err) {
mlx5_ib_dbg(dev, "copy failed\n");
return err;
}
context = to_mucontext(pd->uobject->context);
/*
* TBD: should come from the verbs when we have the API
*/
uuarn = alloc_uuar(&context->uuari, MLX5_IB_LATENCY_CLASS_HIGH);
if (uuarn < 0) {
mlx5_ib_dbg(dev, "failed to allocate low latency UUAR\n");
mlx5_ib_dbg(dev, "reverting to medium latency\n");
uuarn = alloc_uuar(&context->uuari, MLX5_IB_LATENCY_CLASS_MEDIUM);
if (uuarn < 0) {
mlx5_ib_dbg(dev, "failed to allocate medium latency UUAR\n");
mlx5_ib_dbg(dev, "reverting to high latency\n");
uuarn = alloc_uuar(&context->uuari, MLX5_IB_LATENCY_CLASS_LOW);
if (uuarn < 0) {
mlx5_ib_warn(dev, "uuar allocation failed\n");
return uuarn;
}
}
}
uar_index = uuarn_to_uar_index(&context->uuari, uuarn);
mlx5_ib_dbg(dev, "uuarn 0x%x, uar_index 0x%x\n", uuarn, uar_index);
qp->rq.offset = 0;
qp->sq.wqe_shift = ilog2(MLX5_SEND_WQE_BB);
qp->sq.offset = qp->rq.wqe_cnt << qp->rq.wqe_shift;
err = set_user_buf_size(dev, qp, &ucmd);
if (err)
goto err_uuar;
if (ucmd.buf_addr && qp->buf_size) {
qp->umem = ib_umem_get(pd->uobject->context, ucmd.buf_addr,
qp->buf_size, 0, 0);
if (IS_ERR(qp->umem)) {
mlx5_ib_dbg(dev, "umem_get failed\n");
err = PTR_ERR(qp->umem);
goto err_uuar;
}
} else {
qp->umem = NULL;
}
if (qp->umem) {
mlx5_ib_cont_pages(qp->umem, ucmd.buf_addr, &npages, &page_shift,
&ncont, NULL);
err = mlx5_ib_get_buf_offset(ucmd.buf_addr, page_shift, &offset);
if (err) {
mlx5_ib_warn(dev, "bad offset\n");
goto err_umem;
}
mlx5_ib_dbg(dev, "addr 0x%llx, size %d, npages %d, page_shift %d, ncont %d, offset %d\n",
ucmd.buf_addr, qp->buf_size, npages, page_shift, ncont, offset);
}
*inlen = sizeof(**in) + sizeof(*(*in)->pas) * ncont;
*in = mlx5_vzalloc(*inlen);
if (!*in) {
err = -ENOMEM;
goto err_umem;
}
if (qp->umem)
mlx5_ib_populate_pas(dev, qp->umem, page_shift, (*in)->pas, 0);
(*in)->ctx.log_pg_sz_remote_qpn =
cpu_to_be32((page_shift - MLX5_ADAPTER_PAGE_SHIFT) << 24);
(*in)->ctx.params2 = cpu_to_be32(offset << 6);
(*in)->ctx.qp_counter_set_usr_page = cpu_to_be32(uar_index);
resp->uuar_index = uuarn;
qp->uuarn = uuarn;
err = mlx5_ib_db_map_user(context, ucmd.db_addr, &qp->db);
if (err) {
mlx5_ib_dbg(dev, "map failed\n");
goto err_free;
}
err = ib_copy_to_udata(udata, resp, sizeof(*resp));
if (err) {
mlx5_ib_dbg(dev, "copy failed\n");
goto err_unmap;
}
qp->create_type = MLX5_QP_USER;
return 0;
err_unmap:
mlx5_ib_db_unmap_user(context, &qp->db);
err_free:
kvfree(*in);
err_umem:
if (qp->umem)
ib_umem_release(qp->umem);
err_uuar:
free_uuar(&context->uuari, uuarn);
return err;
}
static void destroy_qp_user(struct ib_pd *pd, struct mlx5_ib_qp *qp)
{
struct mlx5_ib_ucontext *context;
context = to_mucontext(pd->uobject->context);
mlx5_ib_db_unmap_user(context, &qp->db);
if (qp->umem)
ib_umem_release(qp->umem);
free_uuar(&context->uuari, qp->uuarn);
}
static int create_kernel_qp(struct mlx5_ib_dev *dev,
struct ib_qp_init_attr *init_attr,
struct mlx5_ib_qp *qp,
struct mlx5_create_qp_mbox_in **in, int *inlen)
{
enum mlx5_ib_latency_class lc = MLX5_IB_LATENCY_CLASS_LOW;
struct mlx5_uuar_info *uuari;
int uar_index;
int uuarn;
int err;
uuari = &dev->mdev->priv.uuari;
if (init_attr->create_flags & ~(IB_QP_CREATE_SIGNATURE_EN | IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK))
return -EINVAL;
if (init_attr->qp_type == MLX5_IB_QPT_REG_UMR)
lc = MLX5_IB_LATENCY_CLASS_FAST_PATH;
uuarn = alloc_uuar(uuari, lc);
if (uuarn < 0) {
mlx5_ib_dbg(dev, "\n");
return -ENOMEM;
}
qp->bf = &uuari->bfs[uuarn];
uar_index = qp->bf->uar->index;
err = calc_sq_size(dev, init_attr, qp);
if (err < 0) {
mlx5_ib_dbg(dev, "err %d\n", err);
goto err_uuar;
}
qp->rq.offset = 0;
qp->sq.offset = qp->rq.wqe_cnt << qp->rq.wqe_shift;
qp->buf_size = err + (qp->rq.wqe_cnt << qp->rq.wqe_shift);
err = mlx5_buf_alloc(dev->mdev, qp->buf_size, &qp->buf);
if (err) {
mlx5_ib_dbg(dev, "err %d\n", err);
goto err_uuar;
}
qp->sq.qend = mlx5_get_send_wqe(qp, qp->sq.wqe_cnt);
*inlen = sizeof(**in) + sizeof(*(*in)->pas) * qp->buf.npages;
*in = mlx5_vzalloc(*inlen);
if (!*in) {
err = -ENOMEM;
goto err_buf;
}
(*in)->ctx.qp_counter_set_usr_page = cpu_to_be32(uar_index);
(*in)->ctx.log_pg_sz_remote_qpn =
cpu_to_be32((qp->buf.page_shift - MLX5_ADAPTER_PAGE_SHIFT) << 24);
/* Set "fast registration enabled" for all kernel QPs */
(*in)->ctx.params1 |= cpu_to_be32(1 << 11);
(*in)->ctx.sq_crq_size |= cpu_to_be16(1 << 4);
mlx5_fill_page_array(&qp->buf, (*in)->pas);
err = mlx5_db_alloc(dev->mdev, &qp->db);
if (err) {
mlx5_ib_dbg(dev, "err %d\n", err);
goto err_free;
}
qp->sq.wrid = kmalloc(qp->sq.wqe_cnt * sizeof(*qp->sq.wrid), GFP_KERNEL);
qp->sq.wr_data = kmalloc(qp->sq.wqe_cnt * sizeof(*qp->sq.wr_data), GFP_KERNEL);
qp->rq.wrid = kmalloc(qp->rq.wqe_cnt * sizeof(*qp->rq.wrid), GFP_KERNEL);
qp->sq.w_list = kmalloc(qp->sq.wqe_cnt * sizeof(*qp->sq.w_list), GFP_KERNEL);
qp->sq.wqe_head = kmalloc(qp->sq.wqe_cnt * sizeof(*qp->sq.wqe_head), GFP_KERNEL);
if (!qp->sq.wrid || !qp->sq.wr_data || !qp->rq.wrid ||
!qp->sq.w_list || !qp->sq.wqe_head) {
err = -ENOMEM;
goto err_wrid;
}
qp->create_type = MLX5_QP_KERNEL;
return 0;
err_wrid:
mlx5_db_free(dev->mdev, &qp->db);
kfree(qp->sq.wqe_head);
kfree(qp->sq.w_list);
kfree(qp->sq.wrid);
kfree(qp->sq.wr_data);
kfree(qp->rq.wrid);
err_free:
kvfree(*in);
err_buf:
mlx5_buf_free(dev->mdev, &qp->buf);
err_uuar:
free_uuar(&dev->mdev->priv.uuari, uuarn);
return err;
}
static void destroy_qp_kernel(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp)
{
mlx5_db_free(dev->mdev, &qp->db);
kfree(qp->sq.wqe_head);
kfree(qp->sq.w_list);
kfree(qp->sq.wrid);
kfree(qp->sq.wr_data);
kfree(qp->rq.wrid);
mlx5_buf_free(dev->mdev, &qp->buf);
free_uuar(&dev->mdev->priv.uuari, qp->bf->uuarn);
}
static __be32 get_rx_type(struct mlx5_ib_qp *qp, struct ib_qp_init_attr *attr)
{
if (attr->srq || (attr->qp_type == IB_QPT_XRC_TGT) ||
(attr->qp_type == IB_QPT_XRC_INI))
return cpu_to_be32(MLX5_SRQ_RQ);
else if (!qp->has_rq)
return cpu_to_be32(MLX5_ZERO_LEN_RQ);
else
return cpu_to_be32(MLX5_NON_ZERO_RQ);
}
static int is_connected(enum ib_qp_type qp_type)
{
if (qp_type == IB_QPT_RC || qp_type == IB_QPT_UC)
return 1;
return 0;
}
static int create_qp_common(struct mlx5_ib_dev *dev, struct ib_pd *pd,
struct ib_qp_init_attr *init_attr,
struct ib_udata *udata, struct mlx5_ib_qp *qp)
{
struct mlx5_ib_resources *devr = &dev->devr;
struct mlx5_core_dev *mdev = dev->mdev;
struct mlx5_ib_create_qp_resp resp;
struct mlx5_create_qp_mbox_in *in;
struct mlx5_ib_create_qp ucmd;
int inlen = sizeof(*in);
int err;
mlx5_ib_odp_create_qp(qp);
mutex_init(&qp->mutex);
spin_lock_init(&qp->sq.lock);
spin_lock_init(&qp->rq.lock);
if (init_attr->create_flags & IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK) {
if (!MLX5_CAP_GEN(mdev, block_lb_mc)) {
mlx5_ib_dbg(dev, "block multicast loopback isn't supported\n");
return -EINVAL;
} else {
qp->flags |= MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK;
}
}
if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR)
qp->sq_signal_bits = MLX5_WQE_CTRL_CQ_UPDATE;
if (pd && pd->uobject) {
if (ib_copy_from_udata(&ucmd, udata, sizeof(ucmd))) {
mlx5_ib_dbg(dev, "copy failed\n");
return -EFAULT;
}
qp->wq_sig = !!(ucmd.flags & MLX5_QP_FLAG_SIGNATURE);
qp->scat_cqe = !!(ucmd.flags & MLX5_QP_FLAG_SCATTER_CQE);
} else {
qp->wq_sig = !!wq_signature;
}
qp->has_rq = qp_has_rq(init_attr);
err = set_rq_size(dev, &init_attr->cap, qp->has_rq,
qp, (pd && pd->uobject) ? &ucmd : NULL);
if (err) {
mlx5_ib_dbg(dev, "err %d\n", err);
return err;
}
if (pd) {
if (pd->uobject) {
__u32 max_wqes =
1 << MLX5_CAP_GEN(mdev, log_max_qp_sz);
mlx5_ib_dbg(dev, "requested sq_wqe_count (%d)\n", ucmd.sq_wqe_count);
if (ucmd.rq_wqe_shift != qp->rq.wqe_shift ||
ucmd.rq_wqe_count != qp->rq.wqe_cnt) {
mlx5_ib_dbg(dev, "invalid rq params\n");
return -EINVAL;
}
if (ucmd.sq_wqe_count > max_wqes) {
mlx5_ib_dbg(dev, "requested sq_wqe_count (%d) > max allowed (%d)\n",
ucmd.sq_wqe_count, max_wqes);
return -EINVAL;
}
err = create_user_qp(dev, pd, qp, udata, &in, &resp, &inlen);
if (err)
mlx5_ib_dbg(dev, "err %d\n", err);
} else {
err = create_kernel_qp(dev, init_attr, qp, &in, &inlen);
if (err)
mlx5_ib_dbg(dev, "err %d\n", err);
else
qp->pa_lkey = to_mpd(pd)->pa_lkey;
}
if (err)
return err;
} else {
in = mlx5_vzalloc(sizeof(*in));
if (!in)
return -ENOMEM;
qp->create_type = MLX5_QP_EMPTY;
}
if (is_sqp(init_attr->qp_type))
qp->port = init_attr->port_num;
in->ctx.flags = cpu_to_be32(to_mlx5_st(init_attr->qp_type) << 16 |
MLX5_QP_PM_MIGRATED << 11);
if (init_attr->qp_type != MLX5_IB_QPT_REG_UMR)
in->ctx.flags_pd = cpu_to_be32(to_mpd(pd ? pd : devr->p0)->pdn);
else
in->ctx.flags_pd = cpu_to_be32(MLX5_QP_LAT_SENSITIVE);
if (qp->wq_sig)
in->ctx.flags_pd |= cpu_to_be32(MLX5_QP_ENABLE_SIG);
if (qp->flags & MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK)
in->ctx.flags_pd |= cpu_to_be32(MLX5_QP_BLOCK_MCAST);
if (qp->scat_cqe && is_connected(init_attr->qp_type)) {
int rcqe_sz;
int scqe_sz;
rcqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->recv_cq);
scqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->send_cq);
if (rcqe_sz == 128)
in->ctx.cs_res = MLX5_RES_SCAT_DATA64_CQE;
else
in->ctx.cs_res = MLX5_RES_SCAT_DATA32_CQE;
if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) {
if (scqe_sz == 128)
in->ctx.cs_req = MLX5_REQ_SCAT_DATA64_CQE;
else
in->ctx.cs_req = MLX5_REQ_SCAT_DATA32_CQE;
}
}
if (qp->rq.wqe_cnt) {
in->ctx.rq_size_stride = (qp->rq.wqe_shift - 4);
in->ctx.rq_size_stride |= ilog2(qp->rq.wqe_cnt) << 3;
}
in->ctx.rq_type_srqn = get_rx_type(qp, init_attr);
if (qp->sq.wqe_cnt)
in->ctx.sq_crq_size |= cpu_to_be16(ilog2(qp->sq.wqe_cnt) << 11);
else
in->ctx.sq_crq_size |= cpu_to_be16(0x8000);
/* Set default resources */
switch (init_attr->qp_type) {
case IB_QPT_XRC_TGT:
in->ctx.cqn_recv = cpu_to_be32(to_mcq(devr->c0)->mcq.cqn);
in->ctx.cqn_send = cpu_to_be32(to_mcq(devr->c0)->mcq.cqn);
in->ctx.rq_type_srqn |= cpu_to_be32(to_msrq(devr->s0)->msrq.srqn);
in->ctx.xrcd = cpu_to_be32(to_mxrcd(init_attr->xrcd)->xrcdn);
break;
case IB_QPT_XRC_INI:
in->ctx.cqn_recv = cpu_to_be32(to_mcq(devr->c0)->mcq.cqn);
in->ctx.xrcd = cpu_to_be32(to_mxrcd(devr->x1)->xrcdn);
in->ctx.rq_type_srqn |= cpu_to_be32(to_msrq(devr->s0)->msrq.srqn);
break;
default:
if (init_attr->srq) {
in->ctx.xrcd = cpu_to_be32(to_mxrcd(devr->x0)->xrcdn);
in->ctx.rq_type_srqn |= cpu_to_be32(to_msrq(init_attr->srq)->msrq.srqn);
} else {
in->ctx.xrcd = cpu_to_be32(to_mxrcd(devr->x1)->xrcdn);
in->ctx.rq_type_srqn |=
cpu_to_be32(to_msrq(devr->s1)->msrq.srqn);
}
}
if (init_attr->send_cq)
in->ctx.cqn_send = cpu_to_be32(to_mcq(init_attr->send_cq)->mcq.cqn);
if (init_attr->recv_cq)
in->ctx.cqn_recv = cpu_to_be32(to_mcq(init_attr->recv_cq)->mcq.cqn);
in->ctx.db_rec_addr = cpu_to_be64(qp->db.dma);
err = mlx5_core_create_qp(dev->mdev, &qp->mqp, in, inlen);
if (err) {
mlx5_ib_dbg(dev, "create qp failed\n");
goto err_create;
}
kvfree(in);
/* Hardware wants QPN written in big-endian order (after
* shifting) for send doorbell. Precompute this value to save
* a little bit when posting sends.
*/
qp->doorbell_qpn = swab32(qp->mqp.qpn << 8);
qp->mqp.event = mlx5_ib_qp_event;
return 0;
err_create:
if (qp->create_type == MLX5_QP_USER)
destroy_qp_user(pd, qp);
else if (qp->create_type == MLX5_QP_KERNEL)
destroy_qp_kernel(dev, qp);
kvfree(in);
return err;
}
static void mlx5_ib_lock_cqs(struct mlx5_ib_cq *send_cq, struct mlx5_ib_cq *recv_cq)
__acquires(&send_cq->lock) __acquires(&recv_cq->lock)
{
if (send_cq) {
if (recv_cq) {
if (send_cq->mcq.cqn < recv_cq->mcq.cqn) {
spin_lock_irq(&send_cq->lock);
spin_lock_nested(&recv_cq->lock,
SINGLE_DEPTH_NESTING);
} else if (send_cq->mcq.cqn == recv_cq->mcq.cqn) {
spin_lock_irq(&send_cq->lock);
__acquire(&recv_cq->lock);
} else {
spin_lock_irq(&recv_cq->lock);
spin_lock_nested(&send_cq->lock,
SINGLE_DEPTH_NESTING);
}
} else {
spin_lock_irq(&send_cq->lock);
__acquire(&recv_cq->lock);
}
} else if (recv_cq) {
spin_lock_irq(&recv_cq->lock);
__acquire(&send_cq->lock);
} else {
__acquire(&send_cq->lock);
__acquire(&recv_cq->lock);
}
}
static void mlx5_ib_unlock_cqs(struct mlx5_ib_cq *send_cq, struct mlx5_ib_cq *recv_cq)
__releases(&send_cq->lock) __releases(&recv_cq->lock)
{
if (send_cq) {
if (recv_cq) {
if (send_cq->mcq.cqn < recv_cq->mcq.cqn) {
spin_unlock(&recv_cq->lock);
spin_unlock_irq(&send_cq->lock);
} else if (send_cq->mcq.cqn == recv_cq->mcq.cqn) {
__release(&recv_cq->lock);
spin_unlock_irq(&send_cq->lock);
} else {
spin_unlock(&send_cq->lock);
spin_unlock_irq(&recv_cq->lock);
}
} else {
__release(&recv_cq->lock);
spin_unlock_irq(&send_cq->lock);
}
} else if (recv_cq) {
__release(&send_cq->lock);
spin_unlock_irq(&recv_cq->lock);
} else {
__release(&recv_cq->lock);
__release(&send_cq->lock);
}
}
static struct mlx5_ib_pd *get_pd(struct mlx5_ib_qp *qp)
{
return to_mpd(qp->ibqp.pd);
}
static void get_cqs(struct mlx5_ib_qp *qp,
struct mlx5_ib_cq **send_cq, struct mlx5_ib_cq **recv_cq)
{
switch (qp->ibqp.qp_type) {
case IB_QPT_XRC_TGT:
*send_cq = NULL;
*recv_cq = NULL;
break;
case MLX5_IB_QPT_REG_UMR:
case IB_QPT_XRC_INI:
*send_cq = to_mcq(qp->ibqp.send_cq);
*recv_cq = NULL;
break;
case IB_QPT_SMI:
case IB_QPT_GSI:
case IB_QPT_RC:
case IB_QPT_UC:
case IB_QPT_UD:
case IB_QPT_RAW_IPV6:
case IB_QPT_RAW_ETHERTYPE:
*send_cq = to_mcq(qp->ibqp.send_cq);
*recv_cq = to_mcq(qp->ibqp.recv_cq);
break;
case IB_QPT_RAW_PACKET:
case IB_QPT_MAX:
default:
*send_cq = NULL;
*recv_cq = NULL;
break;
}
}
static void destroy_qp_common(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp)
{
struct mlx5_ib_cq *send_cq, *recv_cq;
struct mlx5_modify_qp_mbox_in *in;
int err;
in = kzalloc(sizeof(*in), GFP_KERNEL);
if (!in)
return;
if (qp->state != IB_QPS_RESET) {
mlx5_ib_qp_disable_pagefaults(qp);
if (mlx5_core_qp_modify(dev->mdev, to_mlx5_state(qp->state),
MLX5_QP_STATE_RST, in, 0, &qp->mqp))
mlx5_ib_warn(dev, "mlx5_ib: modify QP %06x to RESET failed\n",
qp->mqp.qpn);
}
get_cqs(qp, &send_cq, &recv_cq);
if (qp->create_type == MLX5_QP_KERNEL) {
mlx5_ib_lock_cqs(send_cq, recv_cq);
__mlx5_ib_cq_clean(recv_cq, qp->mqp.qpn,
qp->ibqp.srq ? to_msrq(qp->ibqp.srq) : NULL);
if (send_cq != recv_cq)
__mlx5_ib_cq_clean(send_cq, qp->mqp.qpn, NULL);
mlx5_ib_unlock_cqs(send_cq, recv_cq);
}
err = mlx5_core_destroy_qp(dev->mdev, &qp->mqp);
if (err)
mlx5_ib_warn(dev, "failed to destroy QP 0x%x\n", qp->mqp.qpn);
kfree(in);
if (qp->create_type == MLX5_QP_KERNEL)
destroy_qp_kernel(dev, qp);
else if (qp->create_type == MLX5_QP_USER)
destroy_qp_user(&get_pd(qp)->ibpd, qp);
}
static const char *ib_qp_type_str(enum ib_qp_type type)
{
switch (type) {
case IB_QPT_SMI:
return "IB_QPT_SMI";
case IB_QPT_GSI:
return "IB_QPT_GSI";
case IB_QPT_RC:
return "IB_QPT_RC";
case IB_QPT_UC:
return "IB_QPT_UC";
case IB_QPT_UD:
return "IB_QPT_UD";
case IB_QPT_RAW_IPV6:
return "IB_QPT_RAW_IPV6";
case IB_QPT_RAW_ETHERTYPE:
return "IB_QPT_RAW_ETHERTYPE";
case IB_QPT_XRC_INI:
return "IB_QPT_XRC_INI";
case IB_QPT_XRC_TGT:
return "IB_QPT_XRC_TGT";
case IB_QPT_RAW_PACKET:
return "IB_QPT_RAW_PACKET";
case MLX5_IB_QPT_REG_UMR:
return "MLX5_IB_QPT_REG_UMR";
case IB_QPT_MAX:
default:
return "Invalid QP type";
}
}
struct ib_qp *mlx5_ib_create_qp(struct ib_pd *pd,
struct ib_qp_init_attr *init_attr,
struct ib_udata *udata)
{
struct mlx5_ib_dev *dev;
struct mlx5_ib_qp *qp;
u16 xrcdn = 0;
int err;
if (pd) {
dev = to_mdev(pd->device);
} else {
/* being cautious here */
if (init_attr->qp_type != IB_QPT_XRC_TGT &&
init_attr->qp_type != MLX5_IB_QPT_REG_UMR) {
pr_warn("%s: no PD for transport %s\n", __func__,
ib_qp_type_str(init_attr->qp_type));
return ERR_PTR(-EINVAL);
}
dev = to_mdev(to_mxrcd(init_attr->xrcd)->ibxrcd.device);
}
switch (init_attr->qp_type) {
case IB_QPT_XRC_TGT:
case IB_QPT_XRC_INI:
if (!MLX5_CAP_GEN(dev->mdev, xrc)) {
mlx5_ib_dbg(dev, "XRC not supported\n");
return ERR_PTR(-ENOSYS);
}
init_attr->recv_cq = NULL;
if (init_attr->qp_type == IB_QPT_XRC_TGT) {
xrcdn = to_mxrcd(init_attr->xrcd)->xrcdn;
init_attr->send_cq = NULL;
}
/* fall through */
case IB_QPT_RC:
case IB_QPT_UC:
case IB_QPT_UD:
case IB_QPT_SMI:
case IB_QPT_GSI:
case MLX5_IB_QPT_REG_UMR:
qp = kzalloc(sizeof(*qp), GFP_KERNEL);
if (!qp)
return ERR_PTR(-ENOMEM);
err = create_qp_common(dev, pd, init_attr, udata, qp);
if (err) {
mlx5_ib_dbg(dev, "create_qp_common failed\n");
kfree(qp);
return ERR_PTR(err);
}
if (is_qp0(init_attr->qp_type))
qp->ibqp.qp_num = 0;
else if (is_qp1(init_attr->qp_type))
qp->ibqp.qp_num = 1;
else
qp->ibqp.qp_num = qp->mqp.qpn;
mlx5_ib_dbg(dev, "ib qpnum 0x%x, mlx qpn 0x%x, rcqn 0x%x, scqn 0x%x\n",
qp->ibqp.qp_num, qp->mqp.qpn, to_mcq(init_attr->recv_cq)->mcq.cqn,
to_mcq(init_attr->send_cq)->mcq.cqn);
qp->xrcdn = xrcdn;
break;
case IB_QPT_RAW_IPV6:
case IB_QPT_RAW_ETHERTYPE:
case IB_QPT_RAW_PACKET:
case IB_QPT_MAX:
default:
mlx5_ib_dbg(dev, "unsupported qp type %d\n",
init_attr->qp_type);
/* Don't support raw QPs */
return ERR_PTR(-EINVAL);
}
return &qp->ibqp;
}
int mlx5_ib_destroy_qp(struct ib_qp *qp)
{
struct mlx5_ib_dev *dev = to_mdev(qp->device);
struct mlx5_ib_qp *mqp = to_mqp(qp);
destroy_qp_common(dev, mqp);
kfree(mqp);
return 0;
}
static __be32 to_mlx5_access_flags(struct mlx5_ib_qp *qp, const struct ib_qp_attr *attr,
int attr_mask)
{
u32 hw_access_flags = 0;
u8 dest_rd_atomic;
u32 access_flags;
if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC)
dest_rd_atomic = attr->max_dest_rd_atomic;
else
dest_rd_atomic = qp->resp_depth;
if (attr_mask & IB_QP_ACCESS_FLAGS)
access_flags = attr->qp_access_flags;
else
access_flags = qp->atomic_rd_en;
if (!dest_rd_atomic)
access_flags &= IB_ACCESS_REMOTE_WRITE;
if (access_flags & IB_ACCESS_REMOTE_READ)
hw_access_flags |= MLX5_QP_BIT_RRE;
if (access_flags & IB_ACCESS_REMOTE_ATOMIC)
hw_access_flags |= (MLX5_QP_BIT_RAE | MLX5_ATOMIC_MODE_CX);
if (access_flags & IB_ACCESS_REMOTE_WRITE)
hw_access_flags |= MLX5_QP_BIT_RWE;
return cpu_to_be32(hw_access_flags);
}
enum {
MLX5_PATH_FLAG_FL = 1 << 0,
MLX5_PATH_FLAG_FREE_AR = 1 << 1,
MLX5_PATH_FLAG_COUNTER = 1 << 2,
};
static int ib_rate_to_mlx5(struct mlx5_ib_dev *dev, u8 rate)
{
if (rate == IB_RATE_PORT_CURRENT) {
return 0;
} else if (rate < IB_RATE_2_5_GBPS || rate > IB_RATE_300_GBPS) {
return -EINVAL;
} else {
while (rate != IB_RATE_2_5_GBPS &&
!(1 << (rate + MLX5_STAT_RATE_OFFSET) &
MLX5_CAP_GEN(dev->mdev, stat_rate_support)))
--rate;
}
return rate + MLX5_STAT_RATE_OFFSET;
}
static int mlx5_set_path(struct mlx5_ib_dev *dev, const struct ib_ah_attr *ah,
struct mlx5_qp_path *path, u8 port, int attr_mask,
u32 path_flags, const struct ib_qp_attr *attr)
{
int err;
path->fl = (path_flags & MLX5_PATH_FLAG_FL) ? 0x80 : 0;
path->free_ar = (path_flags & MLX5_PATH_FLAG_FREE_AR) ? 0x80 : 0;
if (attr_mask & IB_QP_PKEY_INDEX)
path->pkey_index = attr->pkey_index;
path->grh_mlid = ah->src_path_bits & 0x7f;
path->rlid = cpu_to_be16(ah->dlid);
if (ah->ah_flags & IB_AH_GRH) {
if (ah->grh.sgid_index >=
dev->mdev->port_caps[port - 1].gid_table_len) {
pr_err("sgid_index (%u) too large. max is %d\n",
ah->grh.sgid_index,
dev->mdev->port_caps[port - 1].gid_table_len);
return -EINVAL;
}
path->grh_mlid |= 1 << 7;
path->mgid_index = ah->grh.sgid_index;
path->hop_limit = ah->grh.hop_limit;
path->tclass_flowlabel =
cpu_to_be32((ah->grh.traffic_class << 20) |
(ah->grh.flow_label));
memcpy(path->rgid, ah->grh.dgid.raw, 16);
}
err = ib_rate_to_mlx5(dev, ah->static_rate);
if (err < 0)
return err;
path->static_rate = err;
path->port = port;
if (attr_mask & IB_QP_TIMEOUT)
path->ackto_lt = attr->timeout << 3;
path->sl = ah->sl & 0xf;
return 0;
}
static enum mlx5_qp_optpar opt_mask[MLX5_QP_NUM_STATE][MLX5_QP_NUM_STATE][MLX5_QP_ST_MAX] = {
[MLX5_QP_STATE_INIT] = {
[MLX5_QP_STATE_INIT] = {
[MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_RRE |
MLX5_QP_OPTPAR_RAE |
MLX5_QP_OPTPAR_RWE |
MLX5_QP_OPTPAR_PKEY_INDEX |
MLX5_QP_OPTPAR_PRI_PORT,
[MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_RWE |
MLX5_QP_OPTPAR_PKEY_INDEX |
MLX5_QP_OPTPAR_PRI_PORT,
[MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_PKEY_INDEX |
MLX5_QP_OPTPAR_Q_KEY |
MLX5_QP_OPTPAR_PRI_PORT,
},
[MLX5_QP_STATE_RTR] = {
[MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH |
MLX5_QP_OPTPAR_RRE |
MLX5_QP_OPTPAR_RAE |
MLX5_QP_OPTPAR_RWE |
MLX5_QP_OPTPAR_PKEY_INDEX,
[MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH |
MLX5_QP_OPTPAR_RWE |
MLX5_QP_OPTPAR_PKEY_INDEX,
[MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_PKEY_INDEX |
MLX5_QP_OPTPAR_Q_KEY,
[MLX5_QP_ST_MLX] = MLX5_QP_OPTPAR_PKEY_INDEX |
MLX5_QP_OPTPAR_Q_KEY,
[MLX5_QP_ST_XRC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH |
MLX5_QP_OPTPAR_RRE |
MLX5_QP_OPTPAR_RAE |
MLX5_QP_OPTPAR_RWE |
MLX5_QP_OPTPAR_PKEY_INDEX,
},
},
[MLX5_QP_STATE_RTR] = {
[MLX5_QP_STATE_RTS] = {
[MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH |
MLX5_QP_OPTPAR_RRE |
MLX5_QP_OPTPAR_RAE |
MLX5_QP_OPTPAR_RWE |
MLX5_QP_OPTPAR_PM_STATE |
MLX5_QP_OPTPAR_RNR_TIMEOUT,
[MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH |
MLX5_QP_OPTPAR_RWE |
MLX5_QP_OPTPAR_PM_STATE,
[MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_Q_KEY,
},
},
[MLX5_QP_STATE_RTS] = {
[MLX5_QP_STATE_RTS] = {
[MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_RRE |
MLX5_QP_OPTPAR_RAE |
MLX5_QP_OPTPAR_RWE |
MLX5_QP_OPTPAR_RNR_TIMEOUT |
MLX5_QP_OPTPAR_PM_STATE |
MLX5_QP_OPTPAR_ALT_ADDR_PATH,
[MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_RWE |
MLX5_QP_OPTPAR_PM_STATE |
MLX5_QP_OPTPAR_ALT_ADDR_PATH,
[MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_Q_KEY |
MLX5_QP_OPTPAR_SRQN |
MLX5_QP_OPTPAR_CQN_RCV,
},
},
[MLX5_QP_STATE_SQER] = {
[MLX5_QP_STATE_RTS] = {
[MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_Q_KEY,
[MLX5_QP_ST_MLX] = MLX5_QP_OPTPAR_Q_KEY,
[MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_RWE,
[MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_RNR_TIMEOUT |
MLX5_QP_OPTPAR_RWE |
MLX5_QP_OPTPAR_RAE |
MLX5_QP_OPTPAR_RRE,
},
},
};
static int ib_nr_to_mlx5_nr(int ib_mask)
{
switch (ib_mask) {
case IB_QP_STATE:
return 0;
case IB_QP_CUR_STATE:
return 0;
case IB_QP_EN_SQD_ASYNC_NOTIFY:
return 0;
case IB_QP_ACCESS_FLAGS:
return MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_RRE |
MLX5_QP_OPTPAR_RAE;
case IB_QP_PKEY_INDEX:
return MLX5_QP_OPTPAR_PKEY_INDEX;
case IB_QP_PORT:
return MLX5_QP_OPTPAR_PRI_PORT;
case IB_QP_QKEY:
return MLX5_QP_OPTPAR_Q_KEY;
case IB_QP_AV:
return MLX5_QP_OPTPAR_PRIMARY_ADDR_PATH |
MLX5_QP_OPTPAR_PRI_PORT;
case IB_QP_PATH_MTU:
return 0;
case IB_QP_TIMEOUT:
return MLX5_QP_OPTPAR_ACK_TIMEOUT;
case IB_QP_RETRY_CNT:
return MLX5_QP_OPTPAR_RETRY_COUNT;
case IB_QP_RNR_RETRY:
return MLX5_QP_OPTPAR_RNR_RETRY;
case IB_QP_RQ_PSN:
return 0;
case IB_QP_MAX_QP_RD_ATOMIC:
return MLX5_QP_OPTPAR_SRA_MAX;
case IB_QP_ALT_PATH:
return MLX5_QP_OPTPAR_ALT_ADDR_PATH;
case IB_QP_MIN_RNR_TIMER:
return MLX5_QP_OPTPAR_RNR_TIMEOUT;
case IB_QP_SQ_PSN:
return 0;
case IB_QP_MAX_DEST_RD_ATOMIC:
return MLX5_QP_OPTPAR_RRA_MAX | MLX5_QP_OPTPAR_RWE |
MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE;
case IB_QP_PATH_MIG_STATE:
return MLX5_QP_OPTPAR_PM_STATE;
case IB_QP_CAP:
return 0;
case IB_QP_DEST_QPN:
return 0;
}
return 0;
}
static int ib_mask_to_mlx5_opt(int ib_mask)
{
int result = 0;
int i;
for (i = 0; i < 8 * sizeof(int); i++) {
if ((1 << i) & ib_mask)
result |= ib_nr_to_mlx5_nr(1 << i);
}
return result;
}
static int __mlx5_ib_modify_qp(struct ib_qp *ibqp,
const struct ib_qp_attr *attr, int attr_mask,
enum ib_qp_state cur_state, enum ib_qp_state new_state)
{
struct mlx5_ib_dev *dev = to_mdev(ibqp->device);
struct mlx5_ib_qp *qp = to_mqp(ibqp);
struct mlx5_ib_cq *send_cq, *recv_cq;
struct mlx5_qp_context *context;
struct mlx5_modify_qp_mbox_in *in;
struct mlx5_ib_pd *pd;
enum mlx5_qp_state mlx5_cur, mlx5_new;
enum mlx5_qp_optpar optpar;
int sqd_event;
int mlx5_st;
int err;
in = kzalloc(sizeof(*in), GFP_KERNEL);
if (!in)
return -ENOMEM;
context = &in->ctx;
err = to_mlx5_st(ibqp->qp_type);
if (err < 0)
goto out;
context->flags = cpu_to_be32(err << 16);
if (!(attr_mask & IB_QP_PATH_MIG_STATE)) {
context->flags |= cpu_to_be32(MLX5_QP_PM_MIGRATED << 11);
} else {
switch (attr->path_mig_state) {
case IB_MIG_MIGRATED:
context->flags |= cpu_to_be32(MLX5_QP_PM_MIGRATED << 11);
break;
case IB_MIG_REARM:
context->flags |= cpu_to_be32(MLX5_QP_PM_REARM << 11);
break;
case IB_MIG_ARMED:
context->flags |= cpu_to_be32(MLX5_QP_PM_ARMED << 11);
break;
}
}
if (ibqp->qp_type == IB_QPT_GSI || ibqp->qp_type == IB_QPT_SMI) {
context->mtu_msgmax = (IB_MTU_256 << 5) | 8;
} else if (ibqp->qp_type == IB_QPT_UD ||
ibqp->qp_type == MLX5_IB_QPT_REG_UMR) {
context->mtu_msgmax = (IB_MTU_4096 << 5) | 12;
} else if (attr_mask & IB_QP_PATH_MTU) {
if (attr->path_mtu < IB_MTU_256 ||
attr->path_mtu > IB_MTU_4096) {
mlx5_ib_warn(dev, "invalid mtu %d\n", attr->path_mtu);
err = -EINVAL;
goto out;
}
context->mtu_msgmax = (attr->path_mtu << 5) |
(u8)MLX5_CAP_GEN(dev->mdev, log_max_msg);
}
if (attr_mask & IB_QP_DEST_QPN)
context->log_pg_sz_remote_qpn = cpu_to_be32(attr->dest_qp_num);
if (attr_mask & IB_QP_PKEY_INDEX)
context->pri_path.pkey_index = attr->pkey_index;
/* todo implement counter_index functionality */
if (is_sqp(ibqp->qp_type))
context->pri_path.port = qp->port;
if (attr_mask & IB_QP_PORT)
context->pri_path.port = attr->port_num;
if (attr_mask & IB_QP_AV) {
err = mlx5_set_path(dev, &attr->ah_attr, &context->pri_path,
attr_mask & IB_QP_PORT ? attr->port_num : qp->port,
attr_mask, 0, attr);
if (err)
goto out;
}
if (attr_mask & IB_QP_TIMEOUT)
context->pri_path.ackto_lt |= attr->timeout << 3;
if (attr_mask & IB_QP_ALT_PATH) {
err = mlx5_set_path(dev, &attr->alt_ah_attr, &context->alt_path,
attr->alt_port_num, attr_mask, 0, attr);
if (err)
goto out;
}
pd = get_pd(qp);
get_cqs(qp, &send_cq, &recv_cq);
context->flags_pd = cpu_to_be32(pd ? pd->pdn : to_mpd(dev->devr.p0)->pdn);
context->cqn_send = send_cq ? cpu_to_be32(send_cq->mcq.cqn) : 0;
context->cqn_recv = recv_cq ? cpu_to_be32(recv_cq->mcq.cqn) : 0;
context->params1 = cpu_to_be32(MLX5_IB_ACK_REQ_FREQ << 28);
if (attr_mask & IB_QP_RNR_RETRY)
context->params1 |= cpu_to_be32(attr->rnr_retry << 13);
if (attr_mask & IB_QP_RETRY_CNT)
context->params1 |= cpu_to_be32(attr->retry_cnt << 16);
if (attr_mask & IB_QP_MAX_QP_RD_ATOMIC) {
if (attr->max_rd_atomic)
context->params1 |=
cpu_to_be32(fls(attr->max_rd_atomic - 1) << 21);
}
if (attr_mask & IB_QP_SQ_PSN)
context->next_send_psn = cpu_to_be32(attr->sq_psn);
if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC) {
if (attr->max_dest_rd_atomic)
context->params2 |=
cpu_to_be32(fls(attr->max_dest_rd_atomic - 1) << 21);
}
if (attr_mask & (IB_QP_ACCESS_FLAGS | IB_QP_MAX_DEST_RD_ATOMIC))
context->params2 |= to_mlx5_access_flags(qp, attr, attr_mask);
if (attr_mask & IB_QP_MIN_RNR_TIMER)
context->rnr_nextrecvpsn |= cpu_to_be32(attr->min_rnr_timer << 24);
if (attr_mask & IB_QP_RQ_PSN)
context->rnr_nextrecvpsn |= cpu_to_be32(attr->rq_psn);
if (attr_mask & IB_QP_QKEY)
context->qkey = cpu_to_be32(attr->qkey);
if (qp->rq.wqe_cnt && cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT)
context->db_rec_addr = cpu_to_be64(qp->db.dma);
if (cur_state == IB_QPS_RTS && new_state == IB_QPS_SQD &&
attr_mask & IB_QP_EN_SQD_ASYNC_NOTIFY && attr->en_sqd_async_notify)
sqd_event = 1;
else
sqd_event = 0;
if (!ibqp->uobject && cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT)
context->sq_crq_size |= cpu_to_be16(1 << 4);
mlx5_cur = to_mlx5_state(cur_state);
mlx5_new = to_mlx5_state(new_state);
mlx5_st = to_mlx5_st(ibqp->qp_type);
if (mlx5_st < 0)
goto out;
/* If moving to a reset or error state, we must disable page faults on
* this QP and flush all current page faults. Otherwise a stale page
* fault may attempt to work on this QP after it is reset and moved
* again to RTS, and may cause the driver and the device to get out of
* sync. */
if (cur_state != IB_QPS_RESET && cur_state != IB_QPS_ERR &&
(new_state == IB_QPS_RESET || new_state == IB_QPS_ERR))
mlx5_ib_qp_disable_pagefaults(qp);
optpar = ib_mask_to_mlx5_opt(attr_mask);
optpar &= opt_mask[mlx5_cur][mlx5_new][mlx5_st];
in->optparam = cpu_to_be32(optpar);
err = mlx5_core_qp_modify(dev->mdev, to_mlx5_state(cur_state),
to_mlx5_state(new_state), in, sqd_event,
&qp->mqp);
if (err)
goto out;
if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT)
mlx5_ib_qp_enable_pagefaults(qp);
qp->state = new_state;
if (attr_mask & IB_QP_ACCESS_FLAGS)
qp->atomic_rd_en = attr->qp_access_flags;
if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC)
qp->resp_depth = attr->max_dest_rd_atomic;
if (attr_mask & IB_QP_PORT)
qp->port = attr->port_num;
if (attr_mask & IB_QP_ALT_PATH)
qp->alt_port = attr->alt_port_num;
/*
* If we moved a kernel QP to RESET, clean up all old CQ
* entries and reinitialize the QP.
*/
if (new_state == IB_QPS_RESET && !ibqp->uobject) {
mlx5_ib_cq_clean(recv_cq, qp->mqp.qpn,
ibqp->srq ? to_msrq(ibqp->srq) : NULL);
if (send_cq != recv_cq)
mlx5_ib_cq_clean(send_cq, qp->mqp.qpn, NULL);
qp->rq.head = 0;
qp->rq.tail = 0;
qp->sq.head = 0;
qp->sq.tail = 0;
qp->sq.cur_post = 0;
qp->sq.last_poll = 0;
qp->db.db[MLX5_RCV_DBR] = 0;
qp->db.db[MLX5_SND_DBR] = 0;
}
out:
kfree(in);
return err;
}
int mlx5_ib_modify_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr,
int attr_mask, struct ib_udata *udata)
{
struct mlx5_ib_dev *dev = to_mdev(ibqp->device);
struct mlx5_ib_qp *qp = to_mqp(ibqp);
enum ib_qp_state cur_state, new_state;
int err = -EINVAL;
int port;
mutex_lock(&qp->mutex);
cur_state = attr_mask & IB_QP_CUR_STATE ? attr->cur_qp_state : qp->state;
new_state = attr_mask & IB_QP_STATE ? attr->qp_state : cur_state;
if (ibqp->qp_type != MLX5_IB_QPT_REG_UMR &&
!ib_modify_qp_is_ok(cur_state, new_state, ibqp->qp_type, attr_mask,
IB_LINK_LAYER_UNSPECIFIED))
goto out;
if ((attr_mask & IB_QP_PORT) &&
(attr->port_num == 0 ||
attr->port_num > MLX5_CAP_GEN(dev->mdev, num_ports)))
goto out;
if (attr_mask & IB_QP_PKEY_INDEX) {
port = attr_mask & IB_QP_PORT ? attr->port_num : qp->port;
if (attr->pkey_index >=
dev->mdev->port_caps[port - 1].pkey_table_len)
goto out;
}
if (attr_mask & IB_QP_MAX_QP_RD_ATOMIC &&
attr->max_rd_atomic >
(1 << MLX5_CAP_GEN(dev->mdev, log_max_ra_res_qp)))
goto out;
if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC &&
attr->max_dest_rd_atomic >
(1 << MLX5_CAP_GEN(dev->mdev, log_max_ra_req_qp)))
goto out;
if (cur_state == new_state && cur_state == IB_QPS_RESET) {
err = 0;
goto out;
}
err = __mlx5_ib_modify_qp(ibqp, attr, attr_mask, cur_state, new_state);
out:
mutex_unlock(&qp->mutex);
return err;
}
static int mlx5_wq_overflow(struct mlx5_ib_wq *wq, int nreq, struct ib_cq *ib_cq)
{
struct mlx5_ib_cq *cq;
unsigned cur;
cur = wq->head - wq->tail;
if (likely(cur + nreq < wq->max_post))
return 0;
cq = to_mcq(ib_cq);
spin_lock(&cq->lock);
cur = wq->head - wq->tail;
spin_unlock(&cq->lock);
return cur + nreq >= wq->max_post;
}
static __always_inline void set_raddr_seg(struct mlx5_wqe_raddr_seg *rseg,
u64 remote_addr, u32 rkey)
{
rseg->raddr = cpu_to_be64(remote_addr);
rseg->rkey = cpu_to_be32(rkey);
rseg->reserved = 0;
}
static void set_datagram_seg(struct mlx5_wqe_datagram_seg *dseg,
struct ib_send_wr *wr)
{
memcpy(&dseg->av, &to_mah(wr->wr.ud.ah)->av, sizeof(struct mlx5_av));
dseg->av.dqp_dct = cpu_to_be32(wr->wr.ud.remote_qpn | MLX5_EXTENDED_UD_AV);
dseg->av.key.qkey.qkey = cpu_to_be32(wr->wr.ud.remote_qkey);
}
static void set_data_ptr_seg(struct mlx5_wqe_data_seg *dseg, struct ib_sge *sg)
{
dseg->byte_count = cpu_to_be32(sg->length);
dseg->lkey = cpu_to_be32(sg->lkey);
dseg->addr = cpu_to_be64(sg->addr);
}
static __be16 get_klm_octo(int npages)
{
return cpu_to_be16(ALIGN(npages, 8) / 2);
}
static __be64 frwr_mkey_mask(void)
{
u64 result;
result = MLX5_MKEY_MASK_LEN |
MLX5_MKEY_MASK_PAGE_SIZE |
MLX5_MKEY_MASK_START_ADDR |
MLX5_MKEY_MASK_EN_RINVAL |
MLX5_MKEY_MASK_KEY |
MLX5_MKEY_MASK_LR |
MLX5_MKEY_MASK_LW |
MLX5_MKEY_MASK_RR |
MLX5_MKEY_MASK_RW |
MLX5_MKEY_MASK_A |
MLX5_MKEY_MASK_SMALL_FENCE |
MLX5_MKEY_MASK_FREE;
return cpu_to_be64(result);
}
static __be64 sig_mkey_mask(void)
{
u64 result;
result = MLX5_MKEY_MASK_LEN |
MLX5_MKEY_MASK_PAGE_SIZE |
MLX5_MKEY_MASK_START_ADDR |
MLX5_MKEY_MASK_EN_SIGERR |
MLX5_MKEY_MASK_EN_RINVAL |
MLX5_MKEY_MASK_KEY |
MLX5_MKEY_MASK_LR |
MLX5_MKEY_MASK_LW |
MLX5_MKEY_MASK_RR |
MLX5_MKEY_MASK_RW |
MLX5_MKEY_MASK_SMALL_FENCE |
MLX5_MKEY_MASK_FREE |
MLX5_MKEY_MASK_BSF_EN;
return cpu_to_be64(result);
}
static void set_frwr_umr_segment(struct mlx5_wqe_umr_ctrl_seg *umr,
struct ib_send_wr *wr, int li)
{
memset(umr, 0, sizeof(*umr));
if (li) {
umr->mkey_mask = cpu_to_be64(MLX5_MKEY_MASK_FREE);
umr->flags = 1 << 7;
return;
}
umr->flags = (1 << 5); /* fail if not free */
umr->klm_octowords = get_klm_octo(wr->wr.fast_reg.page_list_len);
umr->mkey_mask = frwr_mkey_mask();
}
static __be64 get_umr_reg_mr_mask(void)
{
u64 result;
result = MLX5_MKEY_MASK_LEN |
MLX5_MKEY_MASK_PAGE_SIZE |
MLX5_MKEY_MASK_START_ADDR |
MLX5_MKEY_MASK_PD |
MLX5_MKEY_MASK_LR |
MLX5_MKEY_MASK_LW |
MLX5_MKEY_MASK_KEY |
MLX5_MKEY_MASK_RR |
MLX5_MKEY_MASK_RW |
MLX5_MKEY_MASK_A |
MLX5_MKEY_MASK_FREE;
return cpu_to_be64(result);
}
static __be64 get_umr_unreg_mr_mask(void)
{
u64 result;
result = MLX5_MKEY_MASK_FREE;
return cpu_to_be64(result);
}
static __be64 get_umr_update_mtt_mask(void)
{
u64 result;
result = MLX5_MKEY_MASK_FREE;
return cpu_to_be64(result);
}
static void set_reg_umr_segment(struct mlx5_wqe_umr_ctrl_seg *umr,
struct ib_send_wr *wr)
{
struct mlx5_umr_wr *umrwr = (struct mlx5_umr_wr *)&wr->wr.fast_reg;
memset(umr, 0, sizeof(*umr));
if (wr->send_flags & MLX5_IB_SEND_UMR_FAIL_IF_FREE)
umr->flags = MLX5_UMR_CHECK_FREE; /* fail if free */
else
umr->flags = MLX5_UMR_CHECK_NOT_FREE; /* fail if not free */
if (!(wr->send_flags & MLX5_IB_SEND_UMR_UNREG)) {
umr->klm_octowords = get_klm_octo(umrwr->npages);
if (wr->send_flags & MLX5_IB_SEND_UMR_UPDATE_MTT) {
umr->mkey_mask = get_umr_update_mtt_mask();
umr->bsf_octowords = get_klm_octo(umrwr->target.offset);
umr->flags |= MLX5_UMR_TRANSLATION_OFFSET_EN;
} else {
umr->mkey_mask = get_umr_reg_mr_mask();
}
} else {
umr->mkey_mask = get_umr_unreg_mr_mask();
}
if (!wr->num_sge)
umr->flags |= MLX5_UMR_INLINE;
}
static u8 get_umr_flags(int acc)
{
return (acc & IB_ACCESS_REMOTE_ATOMIC ? MLX5_PERM_ATOMIC : 0) |
(acc & IB_ACCESS_REMOTE_WRITE ? MLX5_PERM_REMOTE_WRITE : 0) |
(acc & IB_ACCESS_REMOTE_READ ? MLX5_PERM_REMOTE_READ : 0) |
(acc & IB_ACCESS_LOCAL_WRITE ? MLX5_PERM_LOCAL_WRITE : 0) |
MLX5_PERM_LOCAL_READ | MLX5_PERM_UMR_EN;
}
static void set_mkey_segment(struct mlx5_mkey_seg *seg, struct ib_send_wr *wr,
int li, int *writ)
{
memset(seg, 0, sizeof(*seg));
if (li) {
seg->status = MLX5_MKEY_STATUS_FREE;
return;
}
seg->flags = get_umr_flags(wr->wr.fast_reg.access_flags) |
MLX5_ACCESS_MODE_MTT;
*writ = seg->flags & (MLX5_PERM_LOCAL_WRITE | IB_ACCESS_REMOTE_WRITE);
seg->qpn_mkey7_0 = cpu_to_be32((wr->wr.fast_reg.rkey & 0xff) | 0xffffff00);
seg->flags_pd = cpu_to_be32(MLX5_MKEY_REMOTE_INVAL);
seg->start_addr = cpu_to_be64(wr->wr.fast_reg.iova_start);
seg->len = cpu_to_be64(wr->wr.fast_reg.length);
seg->xlt_oct_size = cpu_to_be32((wr->wr.fast_reg.page_list_len + 1) / 2);
seg->log2_page_size = wr->wr.fast_reg.page_shift;
}
static void set_reg_mkey_segment(struct mlx5_mkey_seg *seg, struct ib_send_wr *wr)
{
struct mlx5_umr_wr *umrwr = (struct mlx5_umr_wr *)&wr->wr.fast_reg;
memset(seg, 0, sizeof(*seg));
if (wr->send_flags & MLX5_IB_SEND_UMR_UNREG) {
seg->status = MLX5_MKEY_STATUS_FREE;
return;
}
seg->flags = convert_access(umrwr->access_flags);
if (!(wr->send_flags & MLX5_IB_SEND_UMR_UPDATE_MTT)) {
seg->flags_pd = cpu_to_be32(to_mpd(umrwr->pd)->pdn);
seg->start_addr = cpu_to_be64(umrwr->target.virt_addr);
}
seg->len = cpu_to_be64(umrwr->length);
seg->log2_page_size = umrwr->page_shift;
seg->qpn_mkey7_0 = cpu_to_be32(0xffffff00 |
mlx5_mkey_variant(umrwr->mkey));
}
static void set_frwr_pages(struct mlx5_wqe_data_seg *dseg,
struct ib_send_wr *wr,
struct mlx5_core_dev *mdev,
struct mlx5_ib_pd *pd,
int writ)
{
struct mlx5_ib_fast_reg_page_list *mfrpl = to_mfrpl(wr->wr.fast_reg.page_list);
u64 *page_list = wr->wr.fast_reg.page_list->page_list;
u64 perm = MLX5_EN_RD | (writ ? MLX5_EN_WR : 0);
int i;
for (i = 0; i < wr->wr.fast_reg.page_list_len; i++)
mfrpl->mapped_page_list[i] = cpu_to_be64(page_list[i] | perm);
dseg->addr = cpu_to_be64(mfrpl->map);
dseg->byte_count = cpu_to_be32(ALIGN(sizeof(u64) * wr->wr.fast_reg.page_list_len, 64));
dseg->lkey = cpu_to_be32(pd->pa_lkey);
}
static __be32 send_ieth(struct ib_send_wr *wr)
{
switch (wr->opcode) {
case IB_WR_SEND_WITH_IMM:
case IB_WR_RDMA_WRITE_WITH_IMM:
return wr->ex.imm_data;
case IB_WR_SEND_WITH_INV:
return cpu_to_be32(wr->ex.invalidate_rkey);
default:
return 0;
}
}
static u8 calc_sig(void *wqe, int size)
{
u8 *p = wqe;
u8 res = 0;
int i;
for (i = 0; i < size; i++)
res ^= p[i];
return ~res;
}
static u8 wq_sig(void *wqe)
{
return calc_sig(wqe, (*((u8 *)wqe + 8) & 0x3f) << 4);
}
static int set_data_inl_seg(struct mlx5_ib_qp *qp, struct ib_send_wr *wr,
void *wqe, int *sz)
{
struct mlx5_wqe_inline_seg *seg;
void *qend = qp->sq.qend;
void *addr;
int inl = 0;
int copy;
int len;
int i;
seg = wqe;
wqe += sizeof(*seg);
for (i = 0; i < wr->num_sge; i++) {
addr = (void *)(unsigned long)(wr->sg_list[i].addr);
len = wr->sg_list[i].length;
inl += len;
if (unlikely(inl > qp->max_inline_data))
return -ENOMEM;
if (unlikely(wqe + len > qend)) {
copy = qend - wqe;
memcpy(wqe, addr, copy);
addr += copy;
len -= copy;
wqe = mlx5_get_send_wqe(qp, 0);
}
memcpy(wqe, addr, len);
wqe += len;
}
seg->byte_count = cpu_to_be32(inl | MLX5_INLINE_SEG);
*sz = ALIGN(inl + sizeof(seg->byte_count), 16) / 16;
return 0;
}
static u16 prot_field_size(enum ib_signature_type type)
{
switch (type) {
case IB_SIG_TYPE_T10_DIF:
return MLX5_DIF_SIZE;
default:
return 0;
}
}
static u8 bs_selector(int block_size)
{
switch (block_size) {
case 512: return 0x1;
case 520: return 0x2;
case 4096: return 0x3;
case 4160: return 0x4;
case 1073741824: return 0x5;
default: return 0;
}
}
static void mlx5_fill_inl_bsf(struct ib_sig_domain *domain,
struct mlx5_bsf_inl *inl)
{
/* Valid inline section and allow BSF refresh */
inl->vld_refresh = cpu_to_be16(MLX5_BSF_INL_VALID |
MLX5_BSF_REFRESH_DIF);
inl->dif_apptag = cpu_to_be16(domain->sig.dif.app_tag);
inl->dif_reftag = cpu_to_be32(domain->sig.dif.ref_tag);
/* repeating block */
inl->rp_inv_seed = MLX5_BSF_REPEAT_BLOCK;
inl->sig_type = domain->sig.dif.bg_type == IB_T10DIF_CRC ?
MLX5_DIF_CRC : MLX5_DIF_IPCS;
if (domain->sig.dif.ref_remap)
inl->dif_inc_ref_guard_check |= MLX5_BSF_INC_REFTAG;
if (domain->sig.dif.app_escape) {
if (domain->sig.dif.ref_escape)
inl->dif_inc_ref_guard_check |= MLX5_BSF_APPREF_ESCAPE;
else
inl->dif_inc_ref_guard_check |= MLX5_BSF_APPTAG_ESCAPE;
}
inl->dif_app_bitmask_check =
cpu_to_be16(domain->sig.dif.apptag_check_mask);
}
static int mlx5_set_bsf(struct ib_mr *sig_mr,
struct ib_sig_attrs *sig_attrs,
struct mlx5_bsf *bsf, u32 data_size)
{
struct mlx5_core_sig_ctx *msig = to_mmr(sig_mr)->sig;
struct mlx5_bsf_basic *basic = &bsf->basic;
struct ib_sig_domain *mem = &sig_attrs->mem;
struct ib_sig_domain *wire = &sig_attrs->wire;
memset(bsf, 0, sizeof(*bsf));
/* Basic + Extended + Inline */
basic->bsf_size_sbs = 1 << 7;
/* Input domain check byte mask */
basic->check_byte_mask = sig_attrs->check_mask;
basic->raw_data_size = cpu_to_be32(data_size);
/* Memory domain */
switch (sig_attrs->mem.sig_type) {
case IB_SIG_TYPE_NONE:
break;
case IB_SIG_TYPE_T10_DIF:
basic->mem.bs_selector = bs_selector(mem->sig.dif.pi_interval);
basic->m_bfs_psv = cpu_to_be32(msig->psv_memory.psv_idx);
mlx5_fill_inl_bsf(mem, &bsf->m_inl);
break;
default:
return -EINVAL;
}
/* Wire domain */
switch (sig_attrs->wire.sig_type) {
case IB_SIG_TYPE_NONE:
break;
case IB_SIG_TYPE_T10_DIF:
if (mem->sig.dif.pi_interval == wire->sig.dif.pi_interval &&
mem->sig_type == wire->sig_type) {
/* Same block structure */
basic->bsf_size_sbs |= 1 << 4;
if (mem->sig.dif.bg_type == wire->sig.dif.bg_type)
basic->wire.copy_byte_mask |= MLX5_CPY_GRD_MASK;
if (mem->sig.dif.app_tag == wire->sig.dif.app_tag)
basic->wire.copy_byte_mask |= MLX5_CPY_APP_MASK;
if (mem->sig.dif.ref_tag == wire->sig.dif.ref_tag)
basic->wire.copy_byte_mask |= MLX5_CPY_REF_MASK;
} else
basic->wire.bs_selector = bs_selector(wire->sig.dif.pi_interval);
basic->w_bfs_psv = cpu_to_be32(msig->psv_wire.psv_idx);
mlx5_fill_inl_bsf(wire, &bsf->w_inl);
break;
default:
return -EINVAL;
}
return 0;
}
static int set_sig_data_segment(struct ib_send_wr *wr, struct mlx5_ib_qp *qp,
void **seg, int *size)
{
struct ib_sig_attrs *sig_attrs = wr->wr.sig_handover.sig_attrs;
struct ib_mr *sig_mr = wr->wr.sig_handover.sig_mr;
struct mlx5_bsf *bsf;
u32 data_len = wr->sg_list->length;
u32 data_key = wr->sg_list->lkey;
u64 data_va = wr->sg_list->addr;
int ret;
int wqe_size;
if (!wr->wr.sig_handover.prot ||
(data_key == wr->wr.sig_handover.prot->lkey &&
data_va == wr->wr.sig_handover.prot->addr &&
data_len == wr->wr.sig_handover.prot->length)) {
/**
* Source domain doesn't contain signature information
* or data and protection are interleaved in memory.
* So need construct:
* ------------------
* | data_klm |
* ------------------
* | BSF |
* ------------------
**/
struct mlx5_klm *data_klm = *seg;
data_klm->bcount = cpu_to_be32(data_len);
data_klm->key = cpu_to_be32(data_key);
data_klm->va = cpu_to_be64(data_va);
wqe_size = ALIGN(sizeof(*data_klm), 64);
} else {
/**
* Source domain contains signature information
* So need construct a strided block format:
* ---------------------------
* | stride_block_ctrl |
* ---------------------------
* | data_klm |
* ---------------------------
* | prot_klm |
* ---------------------------
* | BSF |
* ---------------------------
**/
struct mlx5_stride_block_ctrl_seg *sblock_ctrl;
struct mlx5_stride_block_entry *data_sentry;
struct mlx5_stride_block_entry *prot_sentry;
u32 prot_key = wr->wr.sig_handover.prot->lkey;
u64 prot_va = wr->wr.sig_handover.prot->addr;
u16 block_size = sig_attrs->mem.sig.dif.pi_interval;
int prot_size;
sblock_ctrl = *seg;
data_sentry = (void *)sblock_ctrl + sizeof(*sblock_ctrl);
prot_sentry = (void *)data_sentry + sizeof(*data_sentry);
prot_size = prot_field_size(sig_attrs->mem.sig_type);
if (!prot_size) {
pr_err("Bad block size given: %u\n", block_size);
return -EINVAL;
}
sblock_ctrl->bcount_per_cycle = cpu_to_be32(block_size +
prot_size);
sblock_ctrl->op = cpu_to_be32(MLX5_STRIDE_BLOCK_OP);
sblock_ctrl->repeat_count = cpu_to_be32(data_len / block_size);
sblock_ctrl->num_entries = cpu_to_be16(2);
data_sentry->bcount = cpu_to_be16(block_size);
data_sentry->key = cpu_to_be32(data_key);
data_sentry->va = cpu_to_be64(data_va);
data_sentry->stride = cpu_to_be16(block_size);
prot_sentry->bcount = cpu_to_be16(prot_size);
prot_sentry->key = cpu_to_be32(prot_key);
prot_sentry->va = cpu_to_be64(prot_va);
prot_sentry->stride = cpu_to_be16(prot_size);
wqe_size = ALIGN(sizeof(*sblock_ctrl) + sizeof(*data_sentry) +
sizeof(*prot_sentry), 64);
}
*seg += wqe_size;
*size += wqe_size / 16;
if (unlikely((*seg == qp->sq.qend)))
*seg = mlx5_get_send_wqe(qp, 0);
bsf = *seg;
ret = mlx5_set_bsf(sig_mr, sig_attrs, bsf, data_len);
if (ret)
return -EINVAL;
*seg += sizeof(*bsf);
*size += sizeof(*bsf) / 16;
if (unlikely((*seg == qp->sq.qend)))
*seg = mlx5_get_send_wqe(qp, 0);
return 0;
}
static void set_sig_mkey_segment(struct mlx5_mkey_seg *seg,
struct ib_send_wr *wr, u32 nelements,
u32 length, u32 pdn)
{
struct ib_mr *sig_mr = wr->wr.sig_handover.sig_mr;
u32 sig_key = sig_mr->rkey;
u8 sigerr = to_mmr(sig_mr)->sig->sigerr_count & 1;
memset(seg, 0, sizeof(*seg));
seg->flags = get_umr_flags(wr->wr.sig_handover.access_flags) |
MLX5_ACCESS_MODE_KLM;
seg->qpn_mkey7_0 = cpu_to_be32((sig_key & 0xff) | 0xffffff00);
seg->flags_pd = cpu_to_be32(MLX5_MKEY_REMOTE_INVAL | sigerr << 26 |
MLX5_MKEY_BSF_EN | pdn);
seg->len = cpu_to_be64(length);
seg->xlt_oct_size = cpu_to_be32(be16_to_cpu(get_klm_octo(nelements)));
seg->bsfs_octo_size = cpu_to_be32(MLX5_MKEY_BSF_OCTO_SIZE);
}
static void set_sig_umr_segment(struct mlx5_wqe_umr_ctrl_seg *umr,
struct ib_send_wr *wr, u32 nelements)
{
memset(umr, 0, sizeof(*umr));
umr->flags = MLX5_FLAGS_INLINE | MLX5_FLAGS_CHECK_FREE;
umr->klm_octowords = get_klm_octo(nelements);
umr->bsf_octowords = cpu_to_be16(MLX5_MKEY_BSF_OCTO_SIZE);
umr->mkey_mask = sig_mkey_mask();
}
static int set_sig_umr_wr(struct ib_send_wr *wr, struct mlx5_ib_qp *qp,
void **seg, int *size)
{
struct mlx5_ib_mr *sig_mr = to_mmr(wr->wr.sig_handover.sig_mr);
u32 pdn = get_pd(qp)->pdn;
u32 klm_oct_size;
int region_len, ret;
if (unlikely(wr->num_sge != 1) ||
unlikely(wr->wr.sig_handover.access_flags &
IB_ACCESS_REMOTE_ATOMIC) ||
unlikely(!sig_mr->sig) || unlikely(!qp->signature_en) ||
unlikely(!sig_mr->sig->sig_status_checked))
return -EINVAL;
/* length of the protected region, data + protection */
region_len = wr->sg_list->length;
if (wr->wr.sig_handover.prot &&
(wr->wr.sig_handover.prot->lkey != wr->sg_list->lkey ||
wr->wr.sig_handover.prot->addr != wr->sg_list->addr ||
wr->wr.sig_handover.prot->length != wr->sg_list->length))
region_len += wr->wr.sig_handover.prot->length;
/**
* KLM octoword size - if protection was provided
* then we use strided block format (3 octowords),
* else we use single KLM (1 octoword)
**/
klm_oct_size = wr->wr.sig_handover.prot ? 3 : 1;
set_sig_umr_segment(*seg, wr, klm_oct_size);
*seg += sizeof(struct mlx5_wqe_umr_ctrl_seg);
*size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16;
if (unlikely((*seg == qp->sq.qend)))
*seg = mlx5_get_send_wqe(qp, 0);
set_sig_mkey_segment(*seg, wr, klm_oct_size, region_len, pdn);
*seg += sizeof(struct mlx5_mkey_seg);
*size += sizeof(struct mlx5_mkey_seg) / 16;
if (unlikely((*seg == qp->sq.qend)))
*seg = mlx5_get_send_wqe(qp, 0);
ret = set_sig_data_segment(wr, qp, seg, size);
if (ret)
return ret;
sig_mr->sig->sig_status_checked = false;
return 0;
}
static int set_psv_wr(struct ib_sig_domain *domain,
u32 psv_idx, void **seg, int *size)
{
struct mlx5_seg_set_psv *psv_seg = *seg;
memset(psv_seg, 0, sizeof(*psv_seg));
psv_seg->psv_num = cpu_to_be32(psv_idx);
switch (domain->sig_type) {
case IB_SIG_TYPE_NONE:
break;
case IB_SIG_TYPE_T10_DIF:
psv_seg->transient_sig = cpu_to_be32(domain->sig.dif.bg << 16 |
domain->sig.dif.app_tag);
psv_seg->ref_tag = cpu_to_be32(domain->sig.dif.ref_tag);
break;
default:
pr_err("Bad signature type given.\n");
return 1;
}
*seg += sizeof(*psv_seg);
*size += sizeof(*psv_seg) / 16;
return 0;
}
static int set_frwr_li_wr(void **seg, struct ib_send_wr *wr, int *size,
struct mlx5_core_dev *mdev, struct mlx5_ib_pd *pd, struct mlx5_ib_qp *qp)
{
int writ = 0;
int li;
li = wr->opcode == IB_WR_LOCAL_INV ? 1 : 0;
if (unlikely(wr->send_flags & IB_SEND_INLINE))
return -EINVAL;
set_frwr_umr_segment(*seg, wr, li);
*seg += sizeof(struct mlx5_wqe_umr_ctrl_seg);
*size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16;
if (unlikely((*seg == qp->sq.qend)))
*seg = mlx5_get_send_wqe(qp, 0);
set_mkey_segment(*seg, wr, li, &writ);
*seg += sizeof(struct mlx5_mkey_seg);
*size += sizeof(struct mlx5_mkey_seg) / 16;
if (unlikely((*seg == qp->sq.qend)))
*seg = mlx5_get_send_wqe(qp, 0);
if (!li) {
if (unlikely(wr->wr.fast_reg.page_list_len >
wr->wr.fast_reg.page_list->max_page_list_len))
return -ENOMEM;
set_frwr_pages(*seg, wr, mdev, pd, writ);
*seg += sizeof(struct mlx5_wqe_data_seg);
*size += (sizeof(struct mlx5_wqe_data_seg) / 16);
}
return 0;
}
static void dump_wqe(struct mlx5_ib_qp *qp, int idx, int size_16)
{
__be32 *p = NULL;
int tidx = idx;
int i, j;
pr_debug("dump wqe at %p\n", mlx5_get_send_wqe(qp, tidx));
for (i = 0, j = 0; i < size_16 * 4; i += 4, j += 4) {
if ((i & 0xf) == 0) {
void *buf = mlx5_get_send_wqe(qp, tidx);
tidx = (tidx + 1) & (qp->sq.wqe_cnt - 1);
p = buf;
j = 0;
}
pr_debug("%08x %08x %08x %08x\n", be32_to_cpu(p[j]),
be32_to_cpu(p[j + 1]), be32_to_cpu(p[j + 2]),
be32_to_cpu(p[j + 3]));
}
}
static void mlx5_bf_copy(u64 __iomem *dst, u64 *src,
unsigned bytecnt, struct mlx5_ib_qp *qp)
{
while (bytecnt > 0) {
__iowrite64_copy(dst++, src++, 8);
__iowrite64_copy(dst++, src++, 8);
__iowrite64_copy(dst++, src++, 8);
__iowrite64_copy(dst++, src++, 8);
__iowrite64_copy(dst++, src++, 8);
__iowrite64_copy(dst++, src++, 8);
__iowrite64_copy(dst++, src++, 8);
__iowrite64_copy(dst++, src++, 8);
bytecnt -= 64;
if (unlikely(src == qp->sq.qend))
src = mlx5_get_send_wqe(qp, 0);
}
}
static u8 get_fence(u8 fence, struct ib_send_wr *wr)
{
if (unlikely(wr->opcode == IB_WR_LOCAL_INV &&
wr->send_flags & IB_SEND_FENCE))
return MLX5_FENCE_MODE_STRONG_ORDERING;
if (unlikely(fence)) {
if (wr->send_flags & IB_SEND_FENCE)
return MLX5_FENCE_MODE_SMALL_AND_FENCE;
else
return fence;
} else {
return 0;
}
}
static int begin_wqe(struct mlx5_ib_qp *qp, void **seg,
struct mlx5_wqe_ctrl_seg **ctrl,
struct ib_send_wr *wr, unsigned *idx,
int *size, int nreq)
{
int err = 0;
if (unlikely(mlx5_wq_overflow(&qp->sq, nreq, qp->ibqp.send_cq))) {
err = -ENOMEM;
return err;
}
*idx = qp->sq.cur_post & (qp->sq.wqe_cnt - 1);
*seg = mlx5_get_send_wqe(qp, *idx);
*ctrl = *seg;
*(uint32_t *)(*seg + 8) = 0;
(*ctrl)->imm = send_ieth(wr);
(*ctrl)->fm_ce_se = qp->sq_signal_bits |
(wr->send_flags & IB_SEND_SIGNALED ?
MLX5_WQE_CTRL_CQ_UPDATE : 0) |
(wr->send_flags & IB_SEND_SOLICITED ?
MLX5_WQE_CTRL_SOLICITED : 0);
*seg += sizeof(**ctrl);
*size = sizeof(**ctrl) / 16;
return err;
}
static void finish_wqe(struct mlx5_ib_qp *qp,
struct mlx5_wqe_ctrl_seg *ctrl,
u8 size, unsigned idx, u64 wr_id,
int nreq, u8 fence, u8 next_fence,
u32 mlx5_opcode)
{
u8 opmod = 0;
ctrl->opmod_idx_opcode = cpu_to_be32(((u32)(qp->sq.cur_post) << 8) |
mlx5_opcode | ((u32)opmod << 24));
ctrl->qpn_ds = cpu_to_be32(size | (qp->mqp.qpn << 8));
ctrl->fm_ce_se |= fence;
qp->fm_cache = next_fence;
if (unlikely(qp->wq_sig))
ctrl->signature = wq_sig(ctrl);
qp->sq.wrid[idx] = wr_id;
qp->sq.w_list[idx].opcode = mlx5_opcode;
qp->sq.wqe_head[idx] = qp->sq.head + nreq;
qp->sq.cur_post += DIV_ROUND_UP(size * 16, MLX5_SEND_WQE_BB);
qp->sq.w_list[idx].next = qp->sq.cur_post;
}
int mlx5_ib_post_send(struct ib_qp *ibqp, struct ib_send_wr *wr,
struct ib_send_wr **bad_wr)
{
struct mlx5_wqe_ctrl_seg *ctrl = NULL; /* compiler warning */
struct mlx5_ib_dev *dev = to_mdev(ibqp->device);
struct mlx5_core_dev *mdev = dev->mdev;
struct mlx5_ib_qp *qp = to_mqp(ibqp);
struct mlx5_ib_mr *mr;
struct mlx5_wqe_data_seg *dpseg;
struct mlx5_wqe_xrc_seg *xrc;
struct mlx5_bf *bf = qp->bf;
int uninitialized_var(size);
void *qend = qp->sq.qend;
unsigned long flags;
unsigned idx;
int err = 0;
int inl = 0;
int num_sge;
void *seg;
int nreq;
int i;
u8 next_fence = 0;
u8 fence;
spin_lock_irqsave(&qp->sq.lock, flags);
for (nreq = 0; wr; nreq++, wr = wr->next) {
if (unlikely(wr->opcode >= ARRAY_SIZE(mlx5_ib_opcode))) {
mlx5_ib_warn(dev, "\n");
err = -EINVAL;
*bad_wr = wr;
goto out;
}
fence = qp->fm_cache;
num_sge = wr->num_sge;
if (unlikely(num_sge > qp->sq.max_gs)) {
mlx5_ib_warn(dev, "\n");
err = -ENOMEM;
*bad_wr = wr;
goto out;
}
err = begin_wqe(qp, &seg, &ctrl, wr, &idx, &size, nreq);
if (err) {
mlx5_ib_warn(dev, "\n");
err = -ENOMEM;
*bad_wr = wr;
goto out;
}
switch (ibqp->qp_type) {
case IB_QPT_XRC_INI:
xrc = seg;
xrc->xrc_srqn = htonl(wr->xrc_remote_srq_num);
seg += sizeof(*xrc);
size += sizeof(*xrc) / 16;
/* fall through */
case IB_QPT_RC:
switch (wr->opcode) {
case IB_WR_RDMA_READ:
case IB_WR_RDMA_WRITE:
case IB_WR_RDMA_WRITE_WITH_IMM:
set_raddr_seg(seg, wr->wr.rdma.remote_addr,
wr->wr.rdma.rkey);
seg += sizeof(struct mlx5_wqe_raddr_seg);
size += sizeof(struct mlx5_wqe_raddr_seg) / 16;
break;
case IB_WR_ATOMIC_CMP_AND_SWP:
case IB_WR_ATOMIC_FETCH_AND_ADD:
case IB_WR_MASKED_ATOMIC_CMP_AND_SWP:
mlx5_ib_warn(dev, "Atomic operations are not supported yet\n");
err = -ENOSYS;
*bad_wr = wr;
goto out;
case IB_WR_LOCAL_INV:
next_fence = MLX5_FENCE_MODE_INITIATOR_SMALL;
qp->sq.wr_data[idx] = IB_WR_LOCAL_INV;
ctrl->imm = cpu_to_be32(wr->ex.invalidate_rkey);
err = set_frwr_li_wr(&seg, wr, &size, mdev, to_mpd(ibqp->pd), qp);
if (err) {
mlx5_ib_warn(dev, "\n");
*bad_wr = wr;
goto out;
}
num_sge = 0;
break;
case IB_WR_FAST_REG_MR:
next_fence = MLX5_FENCE_MODE_INITIATOR_SMALL;
qp->sq.wr_data[idx] = IB_WR_FAST_REG_MR;
ctrl->imm = cpu_to_be32(wr->wr.fast_reg.rkey);
err = set_frwr_li_wr(&seg, wr, &size, mdev, to_mpd(ibqp->pd), qp);
if (err) {
mlx5_ib_warn(dev, "\n");
*bad_wr = wr;
goto out;
}
num_sge = 0;
break;
case IB_WR_REG_SIG_MR:
qp->sq.wr_data[idx] = IB_WR_REG_SIG_MR;
mr = to_mmr(wr->wr.sig_handover.sig_mr);
ctrl->imm = cpu_to_be32(mr->ibmr.rkey);
err = set_sig_umr_wr(wr, qp, &seg, &size);
if (err) {
mlx5_ib_warn(dev, "\n");
*bad_wr = wr;
goto out;
}
finish_wqe(qp, ctrl, size, idx, wr->wr_id,
nreq, get_fence(fence, wr),
next_fence, MLX5_OPCODE_UMR);
/*
* SET_PSV WQEs are not signaled and solicited
* on error
*/
wr->send_flags &= ~IB_SEND_SIGNALED;
wr->send_flags |= IB_SEND_SOLICITED;
err = begin_wqe(qp, &seg, &ctrl, wr,
&idx, &size, nreq);
if (err) {
mlx5_ib_warn(dev, "\n");
err = -ENOMEM;
*bad_wr = wr;
goto out;
}
err = set_psv_wr(&wr->wr.sig_handover.sig_attrs->mem,
mr->sig->psv_memory.psv_idx, &seg,
&size);
if (err) {
mlx5_ib_warn(dev, "\n");
*bad_wr = wr;
goto out;
}
finish_wqe(qp, ctrl, size, idx, wr->wr_id,
nreq, get_fence(fence, wr),
next_fence, MLX5_OPCODE_SET_PSV);
err = begin_wqe(qp, &seg, &ctrl, wr,
&idx, &size, nreq);
if (err) {
mlx5_ib_warn(dev, "\n");
err = -ENOMEM;
*bad_wr = wr;
goto out;
}
next_fence = MLX5_FENCE_MODE_INITIATOR_SMALL;
err = set_psv_wr(&wr->wr.sig_handover.sig_attrs->wire,
mr->sig->psv_wire.psv_idx, &seg,
&size);
if (err) {
mlx5_ib_warn(dev, "\n");
*bad_wr = wr;
goto out;
}
finish_wqe(qp, ctrl, size, idx, wr->wr_id,
nreq, get_fence(fence, wr),
next_fence, MLX5_OPCODE_SET_PSV);
num_sge = 0;
goto skip_psv;
default:
break;
}
break;
case IB_QPT_UC:
switch (wr->opcode) {
case IB_WR_RDMA_WRITE:
case IB_WR_RDMA_WRITE_WITH_IMM:
set_raddr_seg(seg, wr->wr.rdma.remote_addr,
wr->wr.rdma.rkey);
seg += sizeof(struct mlx5_wqe_raddr_seg);
size += sizeof(struct mlx5_wqe_raddr_seg) / 16;
break;
default:
break;
}
break;
case IB_QPT_UD:
case IB_QPT_SMI:
case IB_QPT_GSI:
set_datagram_seg(seg, wr);
seg += sizeof(struct mlx5_wqe_datagram_seg);
size += sizeof(struct mlx5_wqe_datagram_seg) / 16;
if (unlikely((seg == qend)))
seg = mlx5_get_send_wqe(qp, 0);
break;
case MLX5_IB_QPT_REG_UMR:
if (wr->opcode != MLX5_IB_WR_UMR) {
err = -EINVAL;
mlx5_ib_warn(dev, "bad opcode\n");
goto out;
}
qp->sq.wr_data[idx] = MLX5_IB_WR_UMR;
ctrl->imm = cpu_to_be32(wr->wr.fast_reg.rkey);
set_reg_umr_segment(seg, wr);
seg += sizeof(struct mlx5_wqe_umr_ctrl_seg);
size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16;
if (unlikely((seg == qend)))
seg = mlx5_get_send_wqe(qp, 0);
set_reg_mkey_segment(seg, wr);
seg += sizeof(struct mlx5_mkey_seg);
size += sizeof(struct mlx5_mkey_seg) / 16;
if (unlikely((seg == qend)))
seg = mlx5_get_send_wqe(qp, 0);
break;
default:
break;
}
if (wr->send_flags & IB_SEND_INLINE && num_sge) {
int uninitialized_var(sz);
err = set_data_inl_seg(qp, wr, seg, &sz);
if (unlikely(err)) {
mlx5_ib_warn(dev, "\n");
*bad_wr = wr;
goto out;
}
inl = 1;
size += sz;
} else {
dpseg = seg;
for (i = 0; i < num_sge; i++) {
if (unlikely(dpseg == qend)) {
seg = mlx5_get_send_wqe(qp, 0);
dpseg = seg;
}
if (likely(wr->sg_list[i].length)) {
set_data_ptr_seg(dpseg, wr->sg_list + i);
size += sizeof(struct mlx5_wqe_data_seg) / 16;
dpseg++;
}
}
}
finish_wqe(qp, ctrl, size, idx, wr->wr_id, nreq,
get_fence(fence, wr), next_fence,
mlx5_ib_opcode[wr->opcode]);
skip_psv:
if (0)
dump_wqe(qp, idx, size);
}
out:
if (likely(nreq)) {
qp->sq.head += nreq;
/* Make sure that descriptors are written before
* updating doorbell record and ringing the doorbell
*/
wmb();
qp->db.db[MLX5_SND_DBR] = cpu_to_be32(qp->sq.cur_post);
/* Make sure doorbell record is visible to the HCA before
* we hit doorbell */
wmb();
if (bf->need_lock)
spin_lock(&bf->lock);
else
__acquire(&bf->lock);
/* TBD enable WC */
if (0 && nreq == 1 && bf->uuarn && inl && size > 1 && size <= bf->buf_size / 16) {
mlx5_bf_copy(bf->reg + bf->offset, (u64 *)ctrl, ALIGN(size * 16, 64), qp);
/* wc_wmb(); */
} else {
mlx5_write64((__be32 *)ctrl, bf->regreg + bf->offset,
MLX5_GET_DOORBELL_LOCK(&bf->lock32));
/* Make sure doorbells don't leak out of SQ spinlock
* and reach the HCA out of order.
*/
mmiowb();
}
bf->offset ^= bf->buf_size;
if (bf->need_lock)
spin_unlock(&bf->lock);
else
__release(&bf->lock);
}
spin_unlock_irqrestore(&qp->sq.lock, flags);
return err;
}
static void set_sig_seg(struct mlx5_rwqe_sig *sig, int size)
{
sig->signature = calc_sig(sig, size);
}
int mlx5_ib_post_recv(struct ib_qp *ibqp, struct ib_recv_wr *wr,
struct ib_recv_wr **bad_wr)
{
struct mlx5_ib_qp *qp = to_mqp(ibqp);
struct mlx5_wqe_data_seg *scat;
struct mlx5_rwqe_sig *sig;
unsigned long flags;
int err = 0;
int nreq;
int ind;
int i;
spin_lock_irqsave(&qp->rq.lock, flags);
ind = qp->rq.head & (qp->rq.wqe_cnt - 1);
for (nreq = 0; wr; nreq++, wr = wr->next) {
if (mlx5_wq_overflow(&qp->rq, nreq, qp->ibqp.recv_cq)) {
err = -ENOMEM;
*bad_wr = wr;
goto out;
}
if (unlikely(wr->num_sge > qp->rq.max_gs)) {
err = -EINVAL;
*bad_wr = wr;
goto out;
}
scat = get_recv_wqe(qp, ind);
if (qp->wq_sig)
scat++;
for (i = 0; i < wr->num_sge; i++)
set_data_ptr_seg(scat + i, wr->sg_list + i);
if (i < qp->rq.max_gs) {
scat[i].byte_count = 0;
scat[i].lkey = cpu_to_be32(MLX5_INVALID_LKEY);
scat[i].addr = 0;
}
if (qp->wq_sig) {
sig = (struct mlx5_rwqe_sig *)scat;
set_sig_seg(sig, (qp->rq.max_gs + 1) << 2);
}
qp->rq.wrid[ind] = wr->wr_id;
ind = (ind + 1) & (qp->rq.wqe_cnt - 1);
}
out:
if (likely(nreq)) {
qp->rq.head += nreq;
/* Make sure that descriptors are written before
* doorbell record.
*/
wmb();
*qp->db.db = cpu_to_be32(qp->rq.head & 0xffff);
}
spin_unlock_irqrestore(&qp->rq.lock, flags);
return err;
}
static inline enum ib_qp_state to_ib_qp_state(enum mlx5_qp_state mlx5_state)
{
switch (mlx5_state) {
case MLX5_QP_STATE_RST: return IB_QPS_RESET;
case MLX5_QP_STATE_INIT: return IB_QPS_INIT;
case MLX5_QP_STATE_RTR: return IB_QPS_RTR;
case MLX5_QP_STATE_RTS: return IB_QPS_RTS;
case MLX5_QP_STATE_SQ_DRAINING:
case MLX5_QP_STATE_SQD: return IB_QPS_SQD;
case MLX5_QP_STATE_SQER: return IB_QPS_SQE;
case MLX5_QP_STATE_ERR: return IB_QPS_ERR;
default: return -1;
}
}
static inline enum ib_mig_state to_ib_mig_state(int mlx5_mig_state)
{
switch (mlx5_mig_state) {
case MLX5_QP_PM_ARMED: return IB_MIG_ARMED;
case MLX5_QP_PM_REARM: return IB_MIG_REARM;
case MLX5_QP_PM_MIGRATED: return IB_MIG_MIGRATED;
default: return -1;
}
}
static int to_ib_qp_access_flags(int mlx5_flags)
{
int ib_flags = 0;
if (mlx5_flags & MLX5_QP_BIT_RRE)
ib_flags |= IB_ACCESS_REMOTE_READ;
if (mlx5_flags & MLX5_QP_BIT_RWE)
ib_flags |= IB_ACCESS_REMOTE_WRITE;
if (mlx5_flags & MLX5_QP_BIT_RAE)
ib_flags |= IB_ACCESS_REMOTE_ATOMIC;
return ib_flags;
}
static void to_ib_ah_attr(struct mlx5_ib_dev *ibdev, struct ib_ah_attr *ib_ah_attr,
struct mlx5_qp_path *path)
{
struct mlx5_core_dev *dev = ibdev->mdev;
memset(ib_ah_attr, 0, sizeof(*ib_ah_attr));
ib_ah_attr->port_num = path->port;
if (ib_ah_attr->port_num == 0 ||
ib_ah_attr->port_num > MLX5_CAP_GEN(dev, num_ports))
return;
ib_ah_attr->sl = path->sl & 0xf;
ib_ah_attr->dlid = be16_to_cpu(path->rlid);
ib_ah_attr->src_path_bits = path->grh_mlid & 0x7f;
ib_ah_attr->static_rate = path->static_rate ? path->static_rate - 5 : 0;
ib_ah_attr->ah_flags = (path->grh_mlid & (1 << 7)) ? IB_AH_GRH : 0;
if (ib_ah_attr->ah_flags) {
ib_ah_attr->grh.sgid_index = path->mgid_index;
ib_ah_attr->grh.hop_limit = path->hop_limit;
ib_ah_attr->grh.traffic_class =
(be32_to_cpu(path->tclass_flowlabel) >> 20) & 0xff;
ib_ah_attr->grh.flow_label =
be32_to_cpu(path->tclass_flowlabel) & 0xfffff;
memcpy(ib_ah_attr->grh.dgid.raw,
path->rgid, sizeof(ib_ah_attr->grh.dgid.raw));
}
}
int mlx5_ib_query_qp(struct ib_qp *ibqp, struct ib_qp_attr *qp_attr, int qp_attr_mask,
struct ib_qp_init_attr *qp_init_attr)
{
struct mlx5_ib_dev *dev = to_mdev(ibqp->device);
struct mlx5_ib_qp *qp = to_mqp(ibqp);
struct mlx5_query_qp_mbox_out *outb;
struct mlx5_qp_context *context;
int mlx5_state;
int err = 0;
#ifdef CONFIG_INFINIBAND_ON_DEMAND_PAGING
/*
* Wait for any outstanding page faults, in case the user frees memory
* based upon this query's result.
*/
flush_workqueue(mlx5_ib_page_fault_wq);
#endif
mutex_lock(&qp->mutex);
outb = kzalloc(sizeof(*outb), GFP_KERNEL);
if (!outb) {
err = -ENOMEM;
goto out;
}
context = &outb->ctx;
err = mlx5_core_qp_query(dev->mdev, &qp->mqp, outb, sizeof(*outb));
if (err)
goto out_free;
mlx5_state = be32_to_cpu(context->flags) >> 28;
qp->state = to_ib_qp_state(mlx5_state);
qp_attr->qp_state = qp->state;
qp_attr->path_mtu = context->mtu_msgmax >> 5;
qp_attr->path_mig_state =
to_ib_mig_state((be32_to_cpu(context->flags) >> 11) & 0x3);
qp_attr->qkey = be32_to_cpu(context->qkey);
qp_attr->rq_psn = be32_to_cpu(context->rnr_nextrecvpsn) & 0xffffff;
qp_attr->sq_psn = be32_to_cpu(context->next_send_psn) & 0xffffff;
qp_attr->dest_qp_num = be32_to_cpu(context->log_pg_sz_remote_qpn) & 0xffffff;
qp_attr->qp_access_flags =
to_ib_qp_access_flags(be32_to_cpu(context->params2));
if (qp->ibqp.qp_type == IB_QPT_RC || qp->ibqp.qp_type == IB_QPT_UC) {
to_ib_ah_attr(dev, &qp_attr->ah_attr, &context->pri_path);
to_ib_ah_attr(dev, &qp_attr->alt_ah_attr, &context->alt_path);
qp_attr->alt_pkey_index = context->alt_path.pkey_index & 0x7f;
qp_attr->alt_port_num = qp_attr->alt_ah_attr.port_num;
}
qp_attr->pkey_index = context->pri_path.pkey_index & 0x7f;
qp_attr->port_num = context->pri_path.port;
/* qp_attr->en_sqd_async_notify is only applicable in modify qp */
qp_attr->sq_draining = mlx5_state == MLX5_QP_STATE_SQ_DRAINING;
qp_attr->max_rd_atomic = 1 << ((be32_to_cpu(context->params1) >> 21) & 0x7);
qp_attr->max_dest_rd_atomic =
1 << ((be32_to_cpu(context->params2) >> 21) & 0x7);
qp_attr->min_rnr_timer =
(be32_to_cpu(context->rnr_nextrecvpsn) >> 24) & 0x1f;
qp_attr->timeout = context->pri_path.ackto_lt >> 3;
qp_attr->retry_cnt = (be32_to_cpu(context->params1) >> 16) & 0x7;
qp_attr->rnr_retry = (be32_to_cpu(context->params1) >> 13) & 0x7;
qp_attr->alt_timeout = context->alt_path.ackto_lt >> 3;
qp_attr->cur_qp_state = qp_attr->qp_state;
qp_attr->cap.max_recv_wr = qp->rq.wqe_cnt;
qp_attr->cap.max_recv_sge = qp->rq.max_gs;
if (!ibqp->uobject) {
qp_attr->cap.max_send_wr = qp->sq.wqe_cnt;
qp_attr->cap.max_send_sge = qp->sq.max_gs;
} else {
qp_attr->cap.max_send_wr = 0;
qp_attr->cap.max_send_sge = 0;
}
/* We don't support inline sends for kernel QPs (yet), and we
* don't know what userspace's value should be.
*/
qp_attr->cap.max_inline_data = 0;
qp_init_attr->cap = qp_attr->cap;
qp_init_attr->create_flags = 0;
if (qp->flags & MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK)
qp_init_attr->create_flags |= IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK;
qp_init_attr->sq_sig_type = qp->sq_signal_bits & MLX5_WQE_CTRL_CQ_UPDATE ?
IB_SIGNAL_ALL_WR : IB_SIGNAL_REQ_WR;
out_free:
kfree(outb);
out:
mutex_unlock(&qp->mutex);
return err;
}
struct ib_xrcd *mlx5_ib_alloc_xrcd(struct ib_device *ibdev,
struct ib_ucontext *context,
struct ib_udata *udata)
{
struct mlx5_ib_dev *dev = to_mdev(ibdev);
struct mlx5_ib_xrcd *xrcd;
int err;
if (!MLX5_CAP_GEN(dev->mdev, xrc))
return ERR_PTR(-ENOSYS);
xrcd = kmalloc(sizeof(*xrcd), GFP_KERNEL);
if (!xrcd)
return ERR_PTR(-ENOMEM);
err = mlx5_core_xrcd_alloc(dev->mdev, &xrcd->xrcdn);
if (err) {
kfree(xrcd);
return ERR_PTR(-ENOMEM);
}
return &xrcd->ibxrcd;
}
int mlx5_ib_dealloc_xrcd(struct ib_xrcd *xrcd)
{
struct mlx5_ib_dev *dev = to_mdev(xrcd->device);
u32 xrcdn = to_mxrcd(xrcd)->xrcdn;
int err;
err = mlx5_core_xrcd_dealloc(dev->mdev, xrcdn);
if (err) {
mlx5_ib_warn(dev, "failed to dealloc xrcdn 0x%x\n", xrcdn);
return err;
}
kfree(xrcd);
return 0;
}
| gpl-2.0 |
Kris89/mooc_os_lab | labcodes/lab5/libs/printfmt.c | 384 | 9877 | #include <defs.h>
#include <x86.h>
#include <error.h>
#include <stdio.h>
#include <string.h>
/* *
* Space or zero padding and a field width are supported for the numeric
* formats only.
*
* The special format %e takes an integer error code
* and prints a string describing the error.
* The integer may be positive or negative,
* so that -E_NO_MEM and E_NO_MEM are equivalent.
* */
static const char * const error_string[MAXERROR + 1] = {
[0] NULL,
[E_UNSPECIFIED] "unspecified error",
[E_BAD_PROC] "bad process",
[E_INVAL] "invalid parameter",
[E_NO_MEM] "out of memory",
[E_NO_FREE_PROC] "out of processes",
[E_FAULT] "segmentation fault",
[E_INVAL_ELF] "invalid elf file",
[E_KILLED] "process is killed",
[E_PANIC] "panic failure",
};
/* *
* printnum - print a number (base <= 16) in reverse order
* @putch: specified putch function, print a single character
* @putdat: used by @putch function
* @num: the number will be printed
* @base: base for print, must be in [1, 16]
* @width: maximum number of digits, if the actual width is less than @width, use @padc instead
* @padc: character that padded on the left if the actual width is less than @width
* */
static void
printnum(void (*putch)(int, void*), void *putdat,
unsigned long long num, unsigned base, int width, int padc) {
unsigned long long result = num;
unsigned mod = do_div(result, base);
// first recursively print all preceding (more significant) digits
if (num >= base) {
printnum(putch, putdat, result, base, width - 1, padc);
} else {
// print any needed pad characters before first digit
while (-- width > 0)
putch(padc, putdat);
}
// then print this (the least significant) digit
putch("0123456789abcdef"[mod], putdat);
}
/* *
* getuint - get an unsigned int of various possible sizes from a varargs list
* @ap: a varargs list pointer
* @lflag: determines the size of the vararg that @ap points to
* */
static unsigned long long
getuint(va_list *ap, int lflag) {
if (lflag >= 2) {
return va_arg(*ap, unsigned long long);
}
else if (lflag) {
return va_arg(*ap, unsigned long);
}
else {
return va_arg(*ap, unsigned int);
}
}
/* *
* getint - same as getuint but signed, we can't use getuint because of sign extension
* @ap: a varargs list pointer
* @lflag: determines the size of the vararg that @ap points to
* */
static long long
getint(va_list *ap, int lflag) {
if (lflag >= 2) {
return va_arg(*ap, long long);
}
else if (lflag) {
return va_arg(*ap, long);
}
else {
return va_arg(*ap, int);
}
}
/* *
* printfmt - format a string and print it by using putch
* @putch: specified putch function, print a single character
* @putdat: used by @putch function
* @fmt: the format string to use
* */
void
printfmt(void (*putch)(int, void*), void *putdat, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vprintfmt(putch, putdat, fmt, ap);
va_end(ap);
}
/* *
* vprintfmt - format a string and print it by using putch, it's called with a va_list
* instead of a variable number of arguments
* @putch: specified putch function, print a single character
* @putdat: used by @putch function
* @fmt: the format string to use
* @ap: arguments for the format string
*
* Call this function if you are already dealing with a va_list.
* Or you probably want printfmt() instead.
* */
void
vprintfmt(void (*putch)(int, void*), void *putdat, const char *fmt, va_list ap) {
register const char *p;
register int ch, err;
unsigned long long num;
int base, width, precision, lflag, altflag;
while (1) {
while ((ch = *(unsigned char *)fmt ++) != '%') {
if (ch == '\0') {
return;
}
putch(ch, putdat);
}
// Process a %-escape sequence
char padc = ' ';
width = precision = -1;
lflag = altflag = 0;
reswitch:
switch (ch = *(unsigned char *)fmt ++) {
// flag to pad on the right
case '-':
padc = '-';
goto reswitch;
// flag to pad with 0's instead of spaces
case '0':
padc = '0';
goto reswitch;
// width field
case '1' ... '9':
for (precision = 0; ; ++ fmt) {
precision = precision * 10 + ch - '0';
ch = *fmt;
if (ch < '0' || ch > '9') {
break;
}
}
goto process_precision;
case '*':
precision = va_arg(ap, int);
goto process_precision;
case '.':
if (width < 0)
width = 0;
goto reswitch;
case '#':
altflag = 1;
goto reswitch;
process_precision:
if (width < 0)
width = precision, precision = -1;
goto reswitch;
// long flag (doubled for long long)
case 'l':
lflag ++;
goto reswitch;
// character
case 'c':
putch(va_arg(ap, int), putdat);
break;
// error message
case 'e':
err = va_arg(ap, int);
if (err < 0) {
err = -err;
}
if (err > MAXERROR || (p = error_string[err]) == NULL) {
printfmt(putch, putdat, "error %d", err);
}
else {
printfmt(putch, putdat, "%s", p);
}
break;
// string
case 's':
if ((p = va_arg(ap, char *)) == NULL) {
p = "(null)";
}
if (width > 0 && padc != '-') {
for (width -= strnlen(p, precision); width > 0; width --) {
putch(padc, putdat);
}
}
for (; (ch = *p ++) != '\0' && (precision < 0 || -- precision >= 0); width --) {
if (altflag && (ch < ' ' || ch > '~')) {
putch('?', putdat);
}
else {
putch(ch, putdat);
}
}
for (; width > 0; width --) {
putch(' ', putdat);
}
break;
// (signed) decimal
case 'd':
num = getint(&ap, lflag);
if ((long long)num < 0) {
putch('-', putdat);
num = -(long long)num;
}
base = 10;
goto number;
// unsigned decimal
case 'u':
num = getuint(&ap, lflag);
base = 10;
goto number;
// (unsigned) octal
case 'o':
num = getuint(&ap, lflag);
base = 8;
goto number;
// pointer
case 'p':
putch('0', putdat);
putch('x', putdat);
num = (unsigned long long)(uintptr_t)va_arg(ap, void *);
base = 16;
goto number;
// (unsigned) hexadecimal
case 'x':
num = getuint(&ap, lflag);
base = 16;
number:
printnum(putch, putdat, num, base, width, padc);
break;
// escaped '%' character
case '%':
putch(ch, putdat);
break;
// unrecognized escape sequence - just print it literally
default:
putch('%', putdat);
for (fmt --; fmt[-1] != '%'; fmt --)
/* do nothing */;
break;
}
}
}
/* sprintbuf is used to save enough information of a buffer */
struct sprintbuf {
char *buf; // address pointer points to the first unused memory
char *ebuf; // points the end of the buffer
int cnt; // the number of characters that have been placed in this buffer
};
/* *
* sprintputch - 'print' a single character in a buffer
* @ch: the character will be printed
* @b: the buffer to place the character @ch
* */
static void
sprintputch(int ch, struct sprintbuf *b) {
b->cnt ++;
if (b->buf < b->ebuf) {
*b->buf ++ = ch;
}
}
/* *
* snprintf - format a string and place it in a buffer
* @str: the buffer to place the result into
* @size: the size of buffer, including the trailing null space
* @fmt: the format string to use
* */
int
snprintf(char *str, size_t size, const char *fmt, ...) {
va_list ap;
int cnt;
va_start(ap, fmt);
cnt = vsnprintf(str, size, fmt, ap);
va_end(ap);
return cnt;
}
/* *
* vsnprintf - format a string and place it in a buffer, it's called with a va_list
* instead of a variable number of arguments
* @str: the buffer to place the result into
* @size: the size of buffer, including the trailing null space
* @fmt: the format string to use
* @ap: arguments for the format string
*
* The return value is the number of characters which would be generated for the
* given input, excluding the trailing '\0'.
*
* Call this function if you are already dealing with a va_list.
* Or you probably want snprintf() instead.
* */
int
vsnprintf(char *str, size_t size, const char *fmt, va_list ap) {
struct sprintbuf b = {str, str + size - 1, 0};
if (str == NULL || b.buf > b.ebuf) {
return -E_INVAL;
}
// print the string to the buffer
vprintfmt((void*)sprintputch, &b, fmt, ap);
// null terminate the buffer
*b.buf = '\0';
return b.cnt;
}
| gpl-2.0 |
jdheiner/SGH-T769_Kernel_ICS | drivers/media/tdmb/fc8050/fc8050_spi.c | 384 | 8083 | /*****************************************************************************
Copyright(c) 2009 FCI Inc. All Rights Reserved
File name : fc8050_spi.c
Description : fc8050 host interface
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
History :
----------------------------------------------------------------------
2009/08/29 jason initial
*******************************************************************************/
#include <linux/input.h>
#include <linux/spi/spi.h>
#include "fci_types.h"
#include "fc8050_regs.h"
#include "fci_oal.h"
#include "fc8050_spi.h"
#include "tdmb.h"
#define DRIVER_NAME "fc8050_spi"
#define HPIC_READ 0x01 /* read command */
#define HPIC_WRITE 0x02 /* write command */
#define HPIC_AINC 0x04 /* address increment */
#define HPIC_BMODE 0x00 /* byte mode */
#define HPIC_WMODE 0x10 /* word mode */
#define HPIC_LMODE 0x20 /* long mode */
#define HPIC_ENDIAN 0x00 /* little endian */
#define HPIC_CLEAR 0x80 /* currently not used */
#define CHIPID 0
#if (CHIPID == 0)
#define SPI_CMD_WRITE 0x0
#define SPI_CMD_READ 0x1
#define SPI_CMD_BURST_WRITE 0x2
#define SPI_CMD_BURST_READ 0x3
#else
#define SPI_CMD_WRITE 0x4
#define SPI_CMD_READ 0x5
#define SPI_CMD_BURST_WRITE 0x6
#define SPI_CMD_BURST_READ 0x7
#endif
struct spi_device *fc8050_spi;
static u8 tx_data[32] __cacheline_aligned;
static DEFINE_MUTEX(lock);
int fc8050_spi_write_then_read(
struct spi_device *spi
, u8 *txbuf
, u16 tx_length
, u8 *rxbuf
, u16 rx_length)
{
s32 res;
struct spi_message message;
struct spi_transfer x;
spi_message_init(&message);
memset(&x, 0, sizeof x);
spi_message_add_tail(&x, &message);
x.tx_buf = txbuf;
x.rx_buf = txbuf;
x.len = tx_length + rx_length;
res = spi_sync(spi, &message);
memcpy(rxbuf, x.rx_buf + tx_length, rx_length);
return res;
}
int fc8050_spi_write_then_burstread(
struct spi_device *spi
, u8 *txbuf
, u16 tx_length
, u8 *rxbuf
, u16 rx_length)
{
s32 res;
struct spi_message message;
struct spi_transfer x;
spi_message_init(&message);
memset(&x, 0, sizeof x);
spi_message_add_tail(&x, &message);
x.tx_buf = txbuf;
x.rx_buf = rxbuf;
x.len = tx_length + rx_length;
res = spi_sync(spi, &message);
return res;
}
static int spi_bulkread(HANDLE hDevice, u8 addr, u8 *data, u16 length)
{
s32 ret;
tx_data[0] = SPI_CMD_BURST_READ;
tx_data[1] = addr;
fc8050_spi = tdmb_get_spi_handle();
ret = fc8050_spi_write_then_read(
fc8050_spi, &tx_data[0], 2, &data[0], length);
if (ret) {
print_log(0, "fc8050_spi_bulkread fail : %d\n", ret);
return BBM_NOK;
}
return BBM_OK;
}
static int spi_bulkwrite(HANDLE hDevice, u8 addr, u8 *data, u16 length)
{
s32 ret;
s32 i;
tx_data[0] = SPI_CMD_BURST_WRITE;
tx_data[1] = addr;
for (i = 0; i < length; i++)
tx_data[2+i] = data[i];
fc8050_spi = tdmb_get_spi_handle();
ret = fc8050_spi_write_then_read(
fc8050_spi, &tx_data[0], length+2, NULL, 0);
if (ret) {
print_log(0, "fc8050_spi_bulkwrite fail : %d\n", ret);
return BBM_NOK;
}
return BBM_OK;
}
static int spi_dataread(HANDLE hDevice, u8 addr, u8 *data, u16 length)
{
s32 ret = 0;
tx_data[0] = SPI_CMD_BURST_READ;
tx_data[1] = addr;
fc8050_spi = tdmb_get_spi_handle();
ret = fc8050_spi_write_then_burstread(
fc8050_spi, &tx_data[0], 2, &data[0], length);
if (ret) {
print_log(0, "fc8050_spi_dataread fail : %d\n", ret);
return BBM_NOK;
}
return BBM_OK;
}
int fc8050_spi_init(HANDLE hDevice, u16 param1, u16 param2)
{
return BBM_OK;
}
int fc8050_spi_byteread(HANDLE hDevice, u16 addr, u8 *data)
{
int res;
u8 command = HPIC_READ | HPIC_BMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkread(hDevice, BBM_DATA_REG, data, 1);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_wordread(HANDLE hDevice, u16 addr, u16 *data)
{
int res;
u8 command = HPIC_READ | HPIC_AINC | HPIC_BMODE | HPIC_ENDIAN;
if (BBM_SCI_DATA <= addr && BBM_SCI_SYNCRX >= addr)
command = HPIC_READ | HPIC_WMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkread(hDevice, BBM_DATA_REG, (u8 *)data, 2);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_longread(HANDLE hDevice, u16 addr, u32 *data)
{
int res;
u8 command = HPIC_READ | HPIC_AINC | HPIC_BMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkread(hDevice, BBM_DATA_REG, (u8 *)data, 4);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_bulkread(HANDLE hDevice, u16 addr, u8 *data, u16 length)
{
int res;
u8 command = HPIC_READ | HPIC_AINC | HPIC_BMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkread(hDevice, BBM_DATA_REG, data, length);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_bytewrite(HANDLE hDevice, u16 addr, u8 data)
{
int res;
u8 command = HPIC_WRITE | HPIC_BMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkwrite(hDevice, BBM_DATA_REG, (u8 *)&data, 1);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_wordwrite(HANDLE hDevice, u16 addr, u16 data)
{
int res;
u8 command = HPIC_WRITE | HPIC_AINC | HPIC_BMODE | HPIC_ENDIAN;
if (BBM_SCI_DATA <= addr && BBM_SCI_SYNCRX >= addr)
command = HPIC_WRITE | HPIC_WMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkwrite(hDevice, BBM_DATA_REG, (u8 *)&data, 2);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_longwrite(HANDLE hDevice, u16 addr, u32 data)
{
int res;
u8 command = HPIC_WRITE | HPIC_AINC | HPIC_BMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkwrite(hDevice, BBM_DATA_REG, (u8 *)&data, 4);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_bulkwrite(HANDLE hDevice, u16 addr, u8 *data, u16 length)
{
int res;
u8 command = HPIC_WRITE | HPIC_AINC | HPIC_BMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkwrite(hDevice, BBM_DATA_REG, data, length);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_dataread(HANDLE hDevice, u16 addr, u8 *data, u16 length)
{
int res;
u8 command = HPIC_READ | HPIC_BMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_dataread(hDevice, BBM_DATA_REG, data, length);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_deinit(HANDLE hDevice)
{
print_log(NULL, "fc8050_spi_deinit\n");
return BBM_OK;
}
| gpl-2.0 |
exactassembly/linux-stable | drivers/mfd/tps6586x.c | 896 | 16020 | /*
* Core driver for TI TPS6586x PMIC family
*
* Copyright (c) 2010 CompuLab Ltd.
* Mike Rapoport <mike@compulab.co.il>
*
* Based on da903x.c.
* Copyright (C) 2008 Compulab, Ltd.
* Mike Rapoport <mike@compulab.co.il>
* Copyright (C) 2006-2008 Marvell International Ltd.
* Eric Miao <eric.miao@marvell.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/irqdomain.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <linux/regmap.h>
#include <linux/of.h>
#include <linux/mfd/core.h>
#include <linux/mfd/tps6586x.h>
#define TPS6586X_SUPPLYENE 0x14
#define EXITSLREQ_BIT BIT(1)
#define SLEEP_MODE_BIT BIT(3)
/* interrupt control registers */
#define TPS6586X_INT_ACK1 0xb5
#define TPS6586X_INT_ACK2 0xb6
#define TPS6586X_INT_ACK3 0xb7
#define TPS6586X_INT_ACK4 0xb8
/* interrupt mask registers */
#define TPS6586X_INT_MASK1 0xb0
#define TPS6586X_INT_MASK2 0xb1
#define TPS6586X_INT_MASK3 0xb2
#define TPS6586X_INT_MASK4 0xb3
#define TPS6586X_INT_MASK5 0xb4
/* device id */
#define TPS6586X_VERSIONCRC 0xcd
/* Maximum register */
#define TPS6586X_MAX_REGISTER (TPS6586X_VERSIONCRC + 1)
struct tps6586x_irq_data {
u8 mask_reg;
u8 mask_mask;
};
#define TPS6586X_IRQ(_reg, _mask) \
{ \
.mask_reg = (_reg) - TPS6586X_INT_MASK1, \
.mask_mask = (_mask), \
}
static const struct tps6586x_irq_data tps6586x_irqs[] = {
[TPS6586X_INT_PLDO_0] = TPS6586X_IRQ(TPS6586X_INT_MASK1, 1 << 0),
[TPS6586X_INT_PLDO_1] = TPS6586X_IRQ(TPS6586X_INT_MASK1, 1 << 1),
[TPS6586X_INT_PLDO_2] = TPS6586X_IRQ(TPS6586X_INT_MASK1, 1 << 2),
[TPS6586X_INT_PLDO_3] = TPS6586X_IRQ(TPS6586X_INT_MASK1, 1 << 3),
[TPS6586X_INT_PLDO_4] = TPS6586X_IRQ(TPS6586X_INT_MASK1, 1 << 4),
[TPS6586X_INT_PLDO_5] = TPS6586X_IRQ(TPS6586X_INT_MASK1, 1 << 5),
[TPS6586X_INT_PLDO_6] = TPS6586X_IRQ(TPS6586X_INT_MASK1, 1 << 6),
[TPS6586X_INT_PLDO_7] = TPS6586X_IRQ(TPS6586X_INT_MASK1, 1 << 7),
[TPS6586X_INT_COMP_DET] = TPS6586X_IRQ(TPS6586X_INT_MASK4, 1 << 0),
[TPS6586X_INT_ADC] = TPS6586X_IRQ(TPS6586X_INT_MASK2, 1 << 1),
[TPS6586X_INT_PLDO_8] = TPS6586X_IRQ(TPS6586X_INT_MASK2, 1 << 2),
[TPS6586X_INT_PLDO_9] = TPS6586X_IRQ(TPS6586X_INT_MASK2, 1 << 3),
[TPS6586X_INT_PSM_0] = TPS6586X_IRQ(TPS6586X_INT_MASK2, 1 << 4),
[TPS6586X_INT_PSM_1] = TPS6586X_IRQ(TPS6586X_INT_MASK2, 1 << 5),
[TPS6586X_INT_PSM_2] = TPS6586X_IRQ(TPS6586X_INT_MASK2, 1 << 6),
[TPS6586X_INT_PSM_3] = TPS6586X_IRQ(TPS6586X_INT_MASK2, 1 << 7),
[TPS6586X_INT_RTC_ALM1] = TPS6586X_IRQ(TPS6586X_INT_MASK5, 1 << 4),
[TPS6586X_INT_ACUSB_OVP] = TPS6586X_IRQ(TPS6586X_INT_MASK5, 0x03),
[TPS6586X_INT_USB_DET] = TPS6586X_IRQ(TPS6586X_INT_MASK5, 1 << 2),
[TPS6586X_INT_AC_DET] = TPS6586X_IRQ(TPS6586X_INT_MASK5, 1 << 3),
[TPS6586X_INT_BAT_DET] = TPS6586X_IRQ(TPS6586X_INT_MASK3, 1 << 0),
[TPS6586X_INT_CHG_STAT] = TPS6586X_IRQ(TPS6586X_INT_MASK4, 0xfc),
[TPS6586X_INT_CHG_TEMP] = TPS6586X_IRQ(TPS6586X_INT_MASK3, 0x06),
[TPS6586X_INT_PP] = TPS6586X_IRQ(TPS6586X_INT_MASK3, 0xf0),
[TPS6586X_INT_RESUME] = TPS6586X_IRQ(TPS6586X_INT_MASK5, 1 << 5),
[TPS6586X_INT_LOW_SYS] = TPS6586X_IRQ(TPS6586X_INT_MASK5, 1 << 6),
[TPS6586X_INT_RTC_ALM2] = TPS6586X_IRQ(TPS6586X_INT_MASK4, 1 << 1),
};
static struct resource tps6586x_rtc_resources[] = {
{
.start = TPS6586X_INT_RTC_ALM1,
.end = TPS6586X_INT_RTC_ALM1,
.flags = IORESOURCE_IRQ,
},
};
static const struct mfd_cell tps6586x_cell[] = {
{
.name = "tps6586x-gpio",
},
{
.name = "tps6586x-regulator",
},
{
.name = "tps6586x-rtc",
.num_resources = ARRAY_SIZE(tps6586x_rtc_resources),
.resources = &tps6586x_rtc_resources[0],
},
{
.name = "tps6586x-onkey",
},
};
struct tps6586x {
struct device *dev;
struct i2c_client *client;
struct regmap *regmap;
int version;
int irq;
struct irq_chip irq_chip;
struct mutex irq_lock;
int irq_base;
u32 irq_en;
u8 mask_reg[5];
struct irq_domain *irq_domain;
};
static inline struct tps6586x *dev_to_tps6586x(struct device *dev)
{
return i2c_get_clientdata(to_i2c_client(dev));
}
int tps6586x_write(struct device *dev, int reg, uint8_t val)
{
struct tps6586x *tps6586x = dev_to_tps6586x(dev);
return regmap_write(tps6586x->regmap, reg, val);
}
EXPORT_SYMBOL_GPL(tps6586x_write);
int tps6586x_writes(struct device *dev, int reg, int len, uint8_t *val)
{
struct tps6586x *tps6586x = dev_to_tps6586x(dev);
return regmap_bulk_write(tps6586x->regmap, reg, val, len);
}
EXPORT_SYMBOL_GPL(tps6586x_writes);
int tps6586x_read(struct device *dev, int reg, uint8_t *val)
{
struct tps6586x *tps6586x = dev_to_tps6586x(dev);
unsigned int rval;
int ret;
ret = regmap_read(tps6586x->regmap, reg, &rval);
if (!ret)
*val = rval;
return ret;
}
EXPORT_SYMBOL_GPL(tps6586x_read);
int tps6586x_reads(struct device *dev, int reg, int len, uint8_t *val)
{
struct tps6586x *tps6586x = dev_to_tps6586x(dev);
return regmap_bulk_read(tps6586x->regmap, reg, val, len);
}
EXPORT_SYMBOL_GPL(tps6586x_reads);
int tps6586x_set_bits(struct device *dev, int reg, uint8_t bit_mask)
{
struct tps6586x *tps6586x = dev_to_tps6586x(dev);
return regmap_update_bits(tps6586x->regmap, reg, bit_mask, bit_mask);
}
EXPORT_SYMBOL_GPL(tps6586x_set_bits);
int tps6586x_clr_bits(struct device *dev, int reg, uint8_t bit_mask)
{
struct tps6586x *tps6586x = dev_to_tps6586x(dev);
return regmap_update_bits(tps6586x->regmap, reg, bit_mask, 0);
}
EXPORT_SYMBOL_GPL(tps6586x_clr_bits);
int tps6586x_update(struct device *dev, int reg, uint8_t val, uint8_t mask)
{
struct tps6586x *tps6586x = dev_to_tps6586x(dev);
return regmap_update_bits(tps6586x->regmap, reg, mask, val);
}
EXPORT_SYMBOL_GPL(tps6586x_update);
int tps6586x_irq_get_virq(struct device *dev, int irq)
{
struct tps6586x *tps6586x = dev_to_tps6586x(dev);
return irq_create_mapping(tps6586x->irq_domain, irq);
}
EXPORT_SYMBOL_GPL(tps6586x_irq_get_virq);
int tps6586x_get_version(struct device *dev)
{
struct tps6586x *tps6586x = dev_get_drvdata(dev);
return tps6586x->version;
}
EXPORT_SYMBOL_GPL(tps6586x_get_version);
static int __remove_subdev(struct device *dev, void *unused)
{
platform_device_unregister(to_platform_device(dev));
return 0;
}
static int tps6586x_remove_subdevs(struct tps6586x *tps6586x)
{
return device_for_each_child(tps6586x->dev, NULL, __remove_subdev);
}
static void tps6586x_irq_lock(struct irq_data *data)
{
struct tps6586x *tps6586x = irq_data_get_irq_chip_data(data);
mutex_lock(&tps6586x->irq_lock);
}
static void tps6586x_irq_enable(struct irq_data *irq_data)
{
struct tps6586x *tps6586x = irq_data_get_irq_chip_data(irq_data);
unsigned int __irq = irq_data->hwirq;
const struct tps6586x_irq_data *data = &tps6586x_irqs[__irq];
tps6586x->mask_reg[data->mask_reg] &= ~data->mask_mask;
tps6586x->irq_en |= (1 << __irq);
}
static void tps6586x_irq_disable(struct irq_data *irq_data)
{
struct tps6586x *tps6586x = irq_data_get_irq_chip_data(irq_data);
unsigned int __irq = irq_data->hwirq;
const struct tps6586x_irq_data *data = &tps6586x_irqs[__irq];
tps6586x->mask_reg[data->mask_reg] |= data->mask_mask;
tps6586x->irq_en &= ~(1 << __irq);
}
static void tps6586x_irq_sync_unlock(struct irq_data *data)
{
struct tps6586x *tps6586x = irq_data_get_irq_chip_data(data);
int i;
for (i = 0; i < ARRAY_SIZE(tps6586x->mask_reg); i++) {
int ret;
ret = tps6586x_write(tps6586x->dev,
TPS6586X_INT_MASK1 + i,
tps6586x->mask_reg[i]);
WARN_ON(ret);
}
mutex_unlock(&tps6586x->irq_lock);
}
#ifdef CONFIG_PM_SLEEP
static int tps6586x_irq_set_wake(struct irq_data *irq_data, unsigned int on)
{
struct tps6586x *tps6586x = irq_data_get_irq_chip_data(irq_data);
return irq_set_irq_wake(tps6586x->irq, on);
}
#else
#define tps6586x_irq_set_wake NULL
#endif
static struct irq_chip tps6586x_irq_chip = {
.name = "tps6586x",
.irq_bus_lock = tps6586x_irq_lock,
.irq_bus_sync_unlock = tps6586x_irq_sync_unlock,
.irq_disable = tps6586x_irq_disable,
.irq_enable = tps6586x_irq_enable,
.irq_set_wake = tps6586x_irq_set_wake,
};
static int tps6586x_irq_map(struct irq_domain *h, unsigned int virq,
irq_hw_number_t hw)
{
struct tps6586x *tps6586x = h->host_data;
irq_set_chip_data(virq, tps6586x);
irq_set_chip_and_handler(virq, &tps6586x_irq_chip, handle_simple_irq);
irq_set_nested_thread(virq, 1);
/* ARM needs us to explicitly flag the IRQ as valid
* and will set them noprobe when we do so. */
#ifdef CONFIG_ARM
set_irq_flags(virq, IRQF_VALID);
#else
irq_set_noprobe(virq);
#endif
return 0;
}
static struct irq_domain_ops tps6586x_domain_ops = {
.map = tps6586x_irq_map,
.xlate = irq_domain_xlate_twocell,
};
static irqreturn_t tps6586x_irq(int irq, void *data)
{
struct tps6586x *tps6586x = data;
u32 acks;
int ret = 0;
ret = tps6586x_reads(tps6586x->dev, TPS6586X_INT_ACK1,
sizeof(acks), (uint8_t *)&acks);
if (ret < 0) {
dev_err(tps6586x->dev, "failed to read interrupt status\n");
return IRQ_NONE;
}
acks = le32_to_cpu(acks);
while (acks) {
int i = __ffs(acks);
if (tps6586x->irq_en & (1 << i))
handle_nested_irq(
irq_find_mapping(tps6586x->irq_domain, i));
acks &= ~(1 << i);
}
return IRQ_HANDLED;
}
static int tps6586x_irq_init(struct tps6586x *tps6586x, int irq,
int irq_base)
{
int i, ret;
u8 tmp[4];
int new_irq_base;
int irq_num = ARRAY_SIZE(tps6586x_irqs);
tps6586x->irq = irq;
mutex_init(&tps6586x->irq_lock);
for (i = 0; i < 5; i++) {
tps6586x->mask_reg[i] = 0xff;
tps6586x_write(tps6586x->dev, TPS6586X_INT_MASK1 + i, 0xff);
}
tps6586x_reads(tps6586x->dev, TPS6586X_INT_ACK1, sizeof(tmp), tmp);
if (irq_base > 0) {
new_irq_base = irq_alloc_descs(irq_base, 0, irq_num, -1);
if (new_irq_base < 0) {
dev_err(tps6586x->dev,
"Failed to alloc IRQs: %d\n", new_irq_base);
return new_irq_base;
}
} else {
new_irq_base = 0;
}
tps6586x->irq_domain = irq_domain_add_simple(tps6586x->dev->of_node,
irq_num, new_irq_base, &tps6586x_domain_ops,
tps6586x);
if (!tps6586x->irq_domain) {
dev_err(tps6586x->dev, "Failed to create IRQ domain\n");
return -ENOMEM;
}
ret = request_threaded_irq(irq, NULL, tps6586x_irq, IRQF_ONESHOT,
"tps6586x", tps6586x);
if (!ret)
device_init_wakeup(tps6586x->dev, 1);
return ret;
}
static int tps6586x_add_subdevs(struct tps6586x *tps6586x,
struct tps6586x_platform_data *pdata)
{
struct tps6586x_subdev_info *subdev;
struct platform_device *pdev;
int i, ret = 0;
for (i = 0; i < pdata->num_subdevs; i++) {
subdev = &pdata->subdevs[i];
pdev = platform_device_alloc(subdev->name, subdev->id);
if (!pdev) {
ret = -ENOMEM;
goto failed;
}
pdev->dev.parent = tps6586x->dev;
pdev->dev.platform_data = subdev->platform_data;
pdev->dev.of_node = subdev->of_node;
ret = platform_device_add(pdev);
if (ret) {
platform_device_put(pdev);
goto failed;
}
}
return 0;
failed:
tps6586x_remove_subdevs(tps6586x);
return ret;
}
#ifdef CONFIG_OF
static struct tps6586x_platform_data *tps6586x_parse_dt(struct i2c_client *client)
{
struct device_node *np = client->dev.of_node;
struct tps6586x_platform_data *pdata;
pdata = devm_kzalloc(&client->dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata) {
dev_err(&client->dev, "Memory allocation failed\n");
return NULL;
}
pdata->num_subdevs = 0;
pdata->subdevs = NULL;
pdata->gpio_base = -1;
pdata->irq_base = -1;
pdata->pm_off = of_property_read_bool(np, "ti,system-power-controller");
return pdata;
}
static const struct of_device_id tps6586x_of_match[] = {
{ .compatible = "ti,tps6586x", },
{ },
};
#else
static struct tps6586x_platform_data *tps6586x_parse_dt(struct i2c_client *client)
{
return NULL;
}
#endif
static bool is_volatile_reg(struct device *dev, unsigned int reg)
{
/* Cache all interrupt mask register */
if ((reg >= TPS6586X_INT_MASK1) && (reg <= TPS6586X_INT_MASK5))
return false;
return true;
}
static const struct regmap_config tps6586x_regmap_config = {
.reg_bits = 8,
.val_bits = 8,
.max_register = TPS6586X_MAX_REGISTER - 1,
.volatile_reg = is_volatile_reg,
.cache_type = REGCACHE_RBTREE,
};
static struct device *tps6586x_dev;
static void tps6586x_power_off(void)
{
if (tps6586x_clr_bits(tps6586x_dev, TPS6586X_SUPPLYENE, EXITSLREQ_BIT))
return;
tps6586x_set_bits(tps6586x_dev, TPS6586X_SUPPLYENE, SLEEP_MODE_BIT);
}
static void tps6586x_print_version(struct i2c_client *client, int version)
{
const char *name;
switch (version) {
case TPS658621A:
name = "TPS658621A";
break;
case TPS658621CD:
name = "TPS658621C/D";
break;
case TPS658623:
name = "TPS658623";
break;
case TPS658640:
case TPS658640v2:
name = "TPS658640";
break;
case TPS658643:
name = "TPS658643";
break;
default:
name = "TPS6586X";
break;
}
dev_info(&client->dev, "Found %s, VERSIONCRC is %02x\n", name, version);
}
static int tps6586x_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct tps6586x_platform_data *pdata = dev_get_platdata(&client->dev);
struct tps6586x *tps6586x;
int ret;
int version;
if (!pdata && client->dev.of_node)
pdata = tps6586x_parse_dt(client);
if (!pdata) {
dev_err(&client->dev, "tps6586x requires platform data\n");
return -ENOTSUPP;
}
version = i2c_smbus_read_byte_data(client, TPS6586X_VERSIONCRC);
if (version < 0) {
dev_err(&client->dev, "Chip ID read failed: %d\n", version);
return -EIO;
}
tps6586x = devm_kzalloc(&client->dev, sizeof(*tps6586x), GFP_KERNEL);
if (!tps6586x)
return -ENOMEM;
tps6586x->version = version;
tps6586x_print_version(client, tps6586x->version);
tps6586x->client = client;
tps6586x->dev = &client->dev;
i2c_set_clientdata(client, tps6586x);
tps6586x->regmap = devm_regmap_init_i2c(client,
&tps6586x_regmap_config);
if (IS_ERR(tps6586x->regmap)) {
ret = PTR_ERR(tps6586x->regmap);
dev_err(&client->dev, "regmap init failed: %d\n", ret);
return ret;
}
if (client->irq) {
ret = tps6586x_irq_init(tps6586x, client->irq,
pdata->irq_base);
if (ret) {
dev_err(&client->dev, "IRQ init failed: %d\n", ret);
return ret;
}
}
ret = mfd_add_devices(tps6586x->dev, -1,
tps6586x_cell, ARRAY_SIZE(tps6586x_cell),
NULL, 0, tps6586x->irq_domain);
if (ret < 0) {
dev_err(&client->dev, "mfd_add_devices failed: %d\n", ret);
goto err_mfd_add;
}
ret = tps6586x_add_subdevs(tps6586x, pdata);
if (ret) {
dev_err(&client->dev, "add devices failed: %d\n", ret);
goto err_add_devs;
}
if (pdata->pm_off && !pm_power_off) {
tps6586x_dev = &client->dev;
pm_power_off = tps6586x_power_off;
}
return 0;
err_add_devs:
mfd_remove_devices(tps6586x->dev);
err_mfd_add:
if (client->irq)
free_irq(client->irq, tps6586x);
return ret;
}
static int tps6586x_i2c_remove(struct i2c_client *client)
{
struct tps6586x *tps6586x = i2c_get_clientdata(client);
tps6586x_remove_subdevs(tps6586x);
mfd_remove_devices(tps6586x->dev);
if (client->irq)
free_irq(client->irq, tps6586x);
return 0;
}
static const struct i2c_device_id tps6586x_id_table[] = {
{ "tps6586x", 0 },
{ },
};
MODULE_DEVICE_TABLE(i2c, tps6586x_id_table);
static struct i2c_driver tps6586x_driver = {
.driver = {
.name = "tps6586x",
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(tps6586x_of_match),
},
.probe = tps6586x_i2c_probe,
.remove = tps6586x_i2c_remove,
.id_table = tps6586x_id_table,
};
static int __init tps6586x_init(void)
{
return i2c_add_driver(&tps6586x_driver);
}
subsys_initcall(tps6586x_init);
static void __exit tps6586x_exit(void)
{
i2c_del_driver(&tps6586x_driver);
}
module_exit(tps6586x_exit);
MODULE_DESCRIPTION("TPS6586X core driver");
MODULE_AUTHOR("Mike Rapoport <mike@compulab.co.il>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
androidarmv6/android_kernel_zte_msm7x27 | drivers/hwmon/w83791d.c | 1152 | 51461 | /*
w83791d.c - Part of lm_sensors, Linux kernel modules for hardware
monitoring
Copyright (C) 2006-2007 Charles Spirakis <bezaur@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Supports following chips:
Chip #vin #fanin #pwm #temp wchipid vendid i2c ISA
w83791d 10 5 5 3 0x71 0x5ca3 yes no
The w83791d chip appears to be part way between the 83781d and the
83792d. Thus, this file is derived from both the w83792d.c and
w83781d.c files.
The w83791g chip is the same as the w83791d but lead-free.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-vid.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#define NUMBER_OF_VIN 10
#define NUMBER_OF_FANIN 5
#define NUMBER_OF_TEMPIN 3
#define NUMBER_OF_PWM 5
/* Addresses to scan */
static const unsigned short normal_i2c[] = { 0x2c, 0x2d, 0x2e, 0x2f,
I2C_CLIENT_END };
/* Insmod parameters */
static unsigned short force_subclients[4];
module_param_array(force_subclients, short, NULL, 0);
MODULE_PARM_DESC(force_subclients, "List of subclient addresses: "
"{bus, clientaddr, subclientaddr1, subclientaddr2}");
static int reset;
module_param(reset, bool, 0);
MODULE_PARM_DESC(reset, "Set to one to force a hardware chip reset");
static int init;
module_param(init, bool, 0);
MODULE_PARM_DESC(init, "Set to one to force extra software initialization");
/* The W83791D registers */
static const u8 W83791D_REG_IN[NUMBER_OF_VIN] = {
0x20, /* VCOREA in DataSheet */
0x21, /* VINR0 in DataSheet */
0x22, /* +3.3VIN in DataSheet */
0x23, /* VDD5V in DataSheet */
0x24, /* +12VIN in DataSheet */
0x25, /* -12VIN in DataSheet */
0x26, /* -5VIN in DataSheet */
0xB0, /* 5VSB in DataSheet */
0xB1, /* VBAT in DataSheet */
0xB2 /* VINR1 in DataSheet */
};
static const u8 W83791D_REG_IN_MAX[NUMBER_OF_VIN] = {
0x2B, /* VCOREA High Limit in DataSheet */
0x2D, /* VINR0 High Limit in DataSheet */
0x2F, /* +3.3VIN High Limit in DataSheet */
0x31, /* VDD5V High Limit in DataSheet */
0x33, /* +12VIN High Limit in DataSheet */
0x35, /* -12VIN High Limit in DataSheet */
0x37, /* -5VIN High Limit in DataSheet */
0xB4, /* 5VSB High Limit in DataSheet */
0xB6, /* VBAT High Limit in DataSheet */
0xB8 /* VINR1 High Limit in DataSheet */
};
static const u8 W83791D_REG_IN_MIN[NUMBER_OF_VIN] = {
0x2C, /* VCOREA Low Limit in DataSheet */
0x2E, /* VINR0 Low Limit in DataSheet */
0x30, /* +3.3VIN Low Limit in DataSheet */
0x32, /* VDD5V Low Limit in DataSheet */
0x34, /* +12VIN Low Limit in DataSheet */
0x36, /* -12VIN Low Limit in DataSheet */
0x38, /* -5VIN Low Limit in DataSheet */
0xB5, /* 5VSB Low Limit in DataSheet */
0xB7, /* VBAT Low Limit in DataSheet */
0xB9 /* VINR1 Low Limit in DataSheet */
};
static const u8 W83791D_REG_FAN[NUMBER_OF_FANIN] = {
0x28, /* FAN 1 Count in DataSheet */
0x29, /* FAN 2 Count in DataSheet */
0x2A, /* FAN 3 Count in DataSheet */
0xBA, /* FAN 4 Count in DataSheet */
0xBB, /* FAN 5 Count in DataSheet */
};
static const u8 W83791D_REG_FAN_MIN[NUMBER_OF_FANIN] = {
0x3B, /* FAN 1 Count Low Limit in DataSheet */
0x3C, /* FAN 2 Count Low Limit in DataSheet */
0x3D, /* FAN 3 Count Low Limit in DataSheet */
0xBC, /* FAN 4 Count Low Limit in DataSheet */
0xBD, /* FAN 5 Count Low Limit in DataSheet */
};
static const u8 W83791D_REG_PWM[NUMBER_OF_PWM] = {
0x81, /* PWM 1 duty cycle register in DataSheet */
0x83, /* PWM 2 duty cycle register in DataSheet */
0x94, /* PWM 3 duty cycle register in DataSheet */
0xA0, /* PWM 4 duty cycle register in DataSheet */
0xA1, /* PWM 5 duty cycle register in DataSheet */
};
static const u8 W83791D_REG_TEMP_TARGET[3] = {
0x85, /* PWM 1 target temperature for temp 1 */
0x86, /* PWM 2 target temperature for temp 2 */
0x96, /* PWM 3 target temperature for temp 3 */
};
static const u8 W83791D_REG_TEMP_TOL[2] = {
0x87, /* PWM 1/2 temperature tolerance */
0x97, /* PWM 3 temperature tolerance */
};
static const u8 W83791D_REG_FAN_CFG[2] = {
0x84, /* FAN 1/2 configuration */
0x95, /* FAN 3 configuration */
};
static const u8 W83791D_REG_FAN_DIV[3] = {
0x47, /* contains FAN1 and FAN2 Divisor */
0x4b, /* contains FAN3 Divisor */
0x5C, /* contains FAN4 and FAN5 Divisor */
};
#define W83791D_REG_BANK 0x4E
#define W83791D_REG_TEMP2_CONFIG 0xC2
#define W83791D_REG_TEMP3_CONFIG 0xCA
static const u8 W83791D_REG_TEMP1[3] = {
0x27, /* TEMP 1 in DataSheet */
0x39, /* TEMP 1 Over in DataSheet */
0x3A, /* TEMP 1 Hyst in DataSheet */
};
static const u8 W83791D_REG_TEMP_ADD[2][6] = {
{0xC0, /* TEMP 2 in DataSheet */
0xC1, /* TEMP 2(0.5 deg) in DataSheet */
0xC5, /* TEMP 2 Over High part in DataSheet */
0xC6, /* TEMP 2 Over Low part in DataSheet */
0xC3, /* TEMP 2 Thyst High part in DataSheet */
0xC4}, /* TEMP 2 Thyst Low part in DataSheet */
{0xC8, /* TEMP 3 in DataSheet */
0xC9, /* TEMP 3(0.5 deg) in DataSheet */
0xCD, /* TEMP 3 Over High part in DataSheet */
0xCE, /* TEMP 3 Over Low part in DataSheet */
0xCB, /* TEMP 3 Thyst High part in DataSheet */
0xCC} /* TEMP 3 Thyst Low part in DataSheet */
};
#define W83791D_REG_BEEP_CONFIG 0x4D
static const u8 W83791D_REG_BEEP_CTRL[3] = {
0x56, /* BEEP Control Register 1 */
0x57, /* BEEP Control Register 2 */
0xA3, /* BEEP Control Register 3 */
};
#define W83791D_REG_GPIO 0x15
#define W83791D_REG_CONFIG 0x40
#define W83791D_REG_VID_FANDIV 0x47
#define W83791D_REG_DID_VID4 0x49
#define W83791D_REG_WCHIPID 0x58
#define W83791D_REG_CHIPMAN 0x4F
#define W83791D_REG_PIN 0x4B
#define W83791D_REG_I2C_SUBADDR 0x4A
#define W83791D_REG_ALARM1 0xA9 /* realtime status register1 */
#define W83791D_REG_ALARM2 0xAA /* realtime status register2 */
#define W83791D_REG_ALARM3 0xAB /* realtime status register3 */
#define W83791D_REG_VBAT 0x5D
#define W83791D_REG_I2C_ADDR 0x48
/* The SMBus locks itself. The Winbond W83791D has a bank select register
(index 0x4e), but the driver only accesses registers in bank 0. Since
we don't switch banks, we don't need any special code to handle
locking access between bank switches */
static inline int w83791d_read(struct i2c_client *client, u8 reg)
{
return i2c_smbus_read_byte_data(client, reg);
}
static inline int w83791d_write(struct i2c_client *client, u8 reg, u8 value)
{
return i2c_smbus_write_byte_data(client, reg, value);
}
/* The analog voltage inputs have 16mV LSB. Since the sysfs output is
in mV as would be measured on the chip input pin, need to just
multiply/divide by 16 to translate from/to register values. */
#define IN_TO_REG(val) (SENSORS_LIMIT((((val) + 8) / 16), 0, 255))
#define IN_FROM_REG(val) ((val) * 16)
static u8 fan_to_reg(long rpm, int div)
{
if (rpm == 0)
return 255;
rpm = SENSORS_LIMIT(rpm, 1, 1000000);
return SENSORS_LIMIT((1350000 + rpm * div / 2) / (rpm * div), 1, 254);
}
#define FAN_FROM_REG(val,div) ((val) == 0 ? -1 : \
((val) == 255 ? 0 : \
1350000 / ((val) * (div))))
/* for temp1 which is 8-bit resolution, LSB = 1 degree Celsius */
#define TEMP1_FROM_REG(val) ((val) * 1000)
#define TEMP1_TO_REG(val) ((val) <= -128000 ? -128 : \
(val) >= 127000 ? 127 : \
(val) < 0 ? ((val) - 500) / 1000 : \
((val) + 500) / 1000)
/* for temp2 and temp3 which are 9-bit resolution, LSB = 0.5 degree Celsius
Assumes the top 8 bits are the integral amount and the bottom 8 bits
are the fractional amount. Since we only have 0.5 degree resolution,
the bottom 7 bits will always be zero */
#define TEMP23_FROM_REG(val) ((val) / 128 * 500)
#define TEMP23_TO_REG(val) ((val) <= -128000 ? 0x8000 : \
(val) >= 127500 ? 0x7F80 : \
(val) < 0 ? ((val) - 250) / 500 * 128 : \
((val) + 250) / 500 * 128)
/* for thermal cruise target temp, 7-bits, LSB = 1 degree Celsius */
#define TARGET_TEMP_TO_REG(val) ((val) < 0 ? 0 : \
(val) >= 127000 ? 127 : \
((val) + 500) / 1000)
/* for thermal cruise temp tolerance, 4-bits, LSB = 1 degree Celsius */
#define TOL_TEMP_TO_REG(val) ((val) < 0 ? 0 : \
(val) >= 15000 ? 15 : \
((val) + 500) / 1000)
#define BEEP_MASK_TO_REG(val) ((val) & 0xffffff)
#define BEEP_MASK_FROM_REG(val) ((val) & 0xffffff)
#define DIV_FROM_REG(val) (1 << (val))
static u8 div_to_reg(int nr, long val)
{
int i;
/* fan divisors max out at 128 */
val = SENSORS_LIMIT(val, 1, 128) >> 1;
for (i = 0; i < 7; i++) {
if (val == 0)
break;
val >>= 1;
}
return (u8) i;
}
struct w83791d_data {
struct device *hwmon_dev;
struct mutex update_lock;
char valid; /* !=0 if following fields are valid */
unsigned long last_updated; /* In jiffies */
/* array of 2 pointers to subclients */
struct i2c_client *lm75[2];
/* volts */
u8 in[NUMBER_OF_VIN]; /* Register value */
u8 in_max[NUMBER_OF_VIN]; /* Register value */
u8 in_min[NUMBER_OF_VIN]; /* Register value */
/* fans */
u8 fan[NUMBER_OF_FANIN]; /* Register value */
u8 fan_min[NUMBER_OF_FANIN]; /* Register value */
u8 fan_div[NUMBER_OF_FANIN]; /* Register encoding, shifted right */
/* Temperature sensors */
s8 temp1[3]; /* current, over, thyst */
s16 temp_add[2][3]; /* fixed point value. Top 8 bits are the
integral part, bottom 8 bits are the
fractional part. We only use the top
9 bits as the resolution is only
to the 0.5 degree C...
two sensors with three values
(cur, over, hyst) */
/* PWMs */
u8 pwm[5]; /* pwm duty cycle */
u8 pwm_enable[3]; /* pwm enable status for fan 1-3
(fan 4-5 only support manual mode) */
u8 temp_target[3]; /* pwm 1-3 target temperature */
u8 temp_tolerance[3]; /* pwm 1-3 temperature tolerance */
/* Misc */
u32 alarms; /* realtime status register encoding,combined */
u8 beep_enable; /* Global beep enable */
u32 beep_mask; /* Mask off specific beeps */
u8 vid; /* Register encoding, combined */
u8 vrm; /* hwmon-vid */
};
static int w83791d_probe(struct i2c_client *client,
const struct i2c_device_id *id);
static int w83791d_detect(struct i2c_client *client,
struct i2c_board_info *info);
static int w83791d_remove(struct i2c_client *client);
static int w83791d_read(struct i2c_client *client, u8 register);
static int w83791d_write(struct i2c_client *client, u8 register, u8 value);
static struct w83791d_data *w83791d_update_device(struct device *dev);
#ifdef DEBUG
static void w83791d_print_debug(struct w83791d_data *data, struct device *dev);
#endif
static void w83791d_init_client(struct i2c_client *client);
static const struct i2c_device_id w83791d_id[] = {
{ "w83791d", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, w83791d_id);
static struct i2c_driver w83791d_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "w83791d",
},
.probe = w83791d_probe,
.remove = w83791d_remove,
.id_table = w83791d_id,
.detect = w83791d_detect,
.address_list = normal_i2c,
};
/* following are the sysfs callback functions */
#define show_in_reg(reg) \
static ssize_t show_##reg(struct device *dev, struct device_attribute *attr, \
char *buf) \
{ \
struct sensor_device_attribute *sensor_attr = \
to_sensor_dev_attr(attr); \
struct w83791d_data *data = w83791d_update_device(dev); \
int nr = sensor_attr->index; \
return sprintf(buf,"%d\n", IN_FROM_REG(data->reg[nr])); \
}
show_in_reg(in);
show_in_reg(in_min);
show_in_reg(in_max);
#define store_in_reg(REG, reg) \
static ssize_t store_in_##reg(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count) \
{ \
struct sensor_device_attribute *sensor_attr = \
to_sensor_dev_attr(attr); \
struct i2c_client *client = to_i2c_client(dev); \
struct w83791d_data *data = i2c_get_clientdata(client); \
unsigned long val = simple_strtoul(buf, NULL, 10); \
int nr = sensor_attr->index; \
\
mutex_lock(&data->update_lock); \
data->in_##reg[nr] = IN_TO_REG(val); \
w83791d_write(client, W83791D_REG_IN_##REG[nr], data->in_##reg[nr]); \
mutex_unlock(&data->update_lock); \
\
return count; \
}
store_in_reg(MIN, min);
store_in_reg(MAX, max);
static struct sensor_device_attribute sda_in_input[] = {
SENSOR_ATTR(in0_input, S_IRUGO, show_in, NULL, 0),
SENSOR_ATTR(in1_input, S_IRUGO, show_in, NULL, 1),
SENSOR_ATTR(in2_input, S_IRUGO, show_in, NULL, 2),
SENSOR_ATTR(in3_input, S_IRUGO, show_in, NULL, 3),
SENSOR_ATTR(in4_input, S_IRUGO, show_in, NULL, 4),
SENSOR_ATTR(in5_input, S_IRUGO, show_in, NULL, 5),
SENSOR_ATTR(in6_input, S_IRUGO, show_in, NULL, 6),
SENSOR_ATTR(in7_input, S_IRUGO, show_in, NULL, 7),
SENSOR_ATTR(in8_input, S_IRUGO, show_in, NULL, 8),
SENSOR_ATTR(in9_input, S_IRUGO, show_in, NULL, 9),
};
static struct sensor_device_attribute sda_in_min[] = {
SENSOR_ATTR(in0_min, S_IWUSR | S_IRUGO, show_in_min, store_in_min, 0),
SENSOR_ATTR(in1_min, S_IWUSR | S_IRUGO, show_in_min, store_in_min, 1),
SENSOR_ATTR(in2_min, S_IWUSR | S_IRUGO, show_in_min, store_in_min, 2),
SENSOR_ATTR(in3_min, S_IWUSR | S_IRUGO, show_in_min, store_in_min, 3),
SENSOR_ATTR(in4_min, S_IWUSR | S_IRUGO, show_in_min, store_in_min, 4),
SENSOR_ATTR(in5_min, S_IWUSR | S_IRUGO, show_in_min, store_in_min, 5),
SENSOR_ATTR(in6_min, S_IWUSR | S_IRUGO, show_in_min, store_in_min, 6),
SENSOR_ATTR(in7_min, S_IWUSR | S_IRUGO, show_in_min, store_in_min, 7),
SENSOR_ATTR(in8_min, S_IWUSR | S_IRUGO, show_in_min, store_in_min, 8),
SENSOR_ATTR(in9_min, S_IWUSR | S_IRUGO, show_in_min, store_in_min, 9),
};
static struct sensor_device_attribute sda_in_max[] = {
SENSOR_ATTR(in0_max, S_IWUSR | S_IRUGO, show_in_max, store_in_max, 0),
SENSOR_ATTR(in1_max, S_IWUSR | S_IRUGO, show_in_max, store_in_max, 1),
SENSOR_ATTR(in2_max, S_IWUSR | S_IRUGO, show_in_max, store_in_max, 2),
SENSOR_ATTR(in3_max, S_IWUSR | S_IRUGO, show_in_max, store_in_max, 3),
SENSOR_ATTR(in4_max, S_IWUSR | S_IRUGO, show_in_max, store_in_max, 4),
SENSOR_ATTR(in5_max, S_IWUSR | S_IRUGO, show_in_max, store_in_max, 5),
SENSOR_ATTR(in6_max, S_IWUSR | S_IRUGO, show_in_max, store_in_max, 6),
SENSOR_ATTR(in7_max, S_IWUSR | S_IRUGO, show_in_max, store_in_max, 7),
SENSOR_ATTR(in8_max, S_IWUSR | S_IRUGO, show_in_max, store_in_max, 8),
SENSOR_ATTR(in9_max, S_IWUSR | S_IRUGO, show_in_max, store_in_max, 9),
};
static ssize_t show_beep(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr =
to_sensor_dev_attr(attr);
struct w83791d_data *data = w83791d_update_device(dev);
int bitnr = sensor_attr->index;
return sprintf(buf, "%d\n", (data->beep_mask >> bitnr) & 1);
}
static ssize_t store_beep(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr =
to_sensor_dev_attr(attr);
struct i2c_client *client = to_i2c_client(dev);
struct w83791d_data *data = i2c_get_clientdata(client);
int bitnr = sensor_attr->index;
int bytenr = bitnr / 8;
long val = simple_strtol(buf, NULL, 10) ? 1 : 0;
mutex_lock(&data->update_lock);
data->beep_mask &= ~(0xff << (bytenr * 8));
data->beep_mask |= w83791d_read(client, W83791D_REG_BEEP_CTRL[bytenr])
<< (bytenr * 8);
data->beep_mask &= ~(1 << bitnr);
data->beep_mask |= val << bitnr;
w83791d_write(client, W83791D_REG_BEEP_CTRL[bytenr],
(data->beep_mask >> (bytenr * 8)) & 0xff);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_alarm(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr =
to_sensor_dev_attr(attr);
struct w83791d_data *data = w83791d_update_device(dev);
int bitnr = sensor_attr->index;
return sprintf(buf, "%d\n", (data->alarms >> bitnr) & 1);
}
/* Note: The bitmask for the beep enable/disable is different than
the bitmask for the alarm. */
static struct sensor_device_attribute sda_in_beep[] = {
SENSOR_ATTR(in0_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 0),
SENSOR_ATTR(in1_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 13),
SENSOR_ATTR(in2_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 2),
SENSOR_ATTR(in3_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 3),
SENSOR_ATTR(in4_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 8),
SENSOR_ATTR(in5_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 9),
SENSOR_ATTR(in6_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 10),
SENSOR_ATTR(in7_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 16),
SENSOR_ATTR(in8_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 17),
SENSOR_ATTR(in9_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 14),
};
static struct sensor_device_attribute sda_in_alarm[] = {
SENSOR_ATTR(in0_alarm, S_IRUGO, show_alarm, NULL, 0),
SENSOR_ATTR(in1_alarm, S_IRUGO, show_alarm, NULL, 1),
SENSOR_ATTR(in2_alarm, S_IRUGO, show_alarm, NULL, 2),
SENSOR_ATTR(in3_alarm, S_IRUGO, show_alarm, NULL, 3),
SENSOR_ATTR(in4_alarm, S_IRUGO, show_alarm, NULL, 8),
SENSOR_ATTR(in5_alarm, S_IRUGO, show_alarm, NULL, 9),
SENSOR_ATTR(in6_alarm, S_IRUGO, show_alarm, NULL, 10),
SENSOR_ATTR(in7_alarm, S_IRUGO, show_alarm, NULL, 19),
SENSOR_ATTR(in8_alarm, S_IRUGO, show_alarm, NULL, 20),
SENSOR_ATTR(in9_alarm, S_IRUGO, show_alarm, NULL, 14),
};
#define show_fan_reg(reg) \
static ssize_t show_##reg(struct device *dev, struct device_attribute *attr, \
char *buf) \
{ \
struct sensor_device_attribute *sensor_attr = \
to_sensor_dev_attr(attr); \
struct w83791d_data *data = w83791d_update_device(dev); \
int nr = sensor_attr->index; \
return sprintf(buf,"%d\n", \
FAN_FROM_REG(data->reg[nr], DIV_FROM_REG(data->fan_div[nr]))); \
}
show_fan_reg(fan);
show_fan_reg(fan_min);
static ssize_t store_fan_min(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
struct i2c_client *client = to_i2c_client(dev);
struct w83791d_data *data = i2c_get_clientdata(client);
unsigned long val = simple_strtoul(buf, NULL, 10);
int nr = sensor_attr->index;
mutex_lock(&data->update_lock);
data->fan_min[nr] = fan_to_reg(val, DIV_FROM_REG(data->fan_div[nr]));
w83791d_write(client, W83791D_REG_FAN_MIN[nr], data->fan_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_fan_div(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct w83791d_data *data = w83791d_update_device(dev);
return sprintf(buf, "%u\n", DIV_FROM_REG(data->fan_div[nr]));
}
/* Note: we save and restore the fan minimum here, because its value is
determined in part by the fan divisor. This follows the principle of
least suprise; the user doesn't expect the fan minimum to change just
because the divisor changed. */
static ssize_t store_fan_div(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
struct i2c_client *client = to_i2c_client(dev);
struct w83791d_data *data = i2c_get_clientdata(client);
int nr = sensor_attr->index;
unsigned long min;
u8 tmp_fan_div;
u8 fan_div_reg;
u8 vbat_reg;
int indx = 0;
u8 keep_mask = 0;
u8 new_shift = 0;
/* Save fan_min */
min = FAN_FROM_REG(data->fan_min[nr], DIV_FROM_REG(data->fan_div[nr]));
mutex_lock(&data->update_lock);
data->fan_div[nr] = div_to_reg(nr, simple_strtoul(buf, NULL, 10));
switch (nr) {
case 0:
indx = 0;
keep_mask = 0xcf;
new_shift = 4;
break;
case 1:
indx = 0;
keep_mask = 0x3f;
new_shift = 6;
break;
case 2:
indx = 1;
keep_mask = 0x3f;
new_shift = 6;
break;
case 3:
indx = 2;
keep_mask = 0xf8;
new_shift = 0;
break;
case 4:
indx = 2;
keep_mask = 0x8f;
new_shift = 4;
break;
#ifdef DEBUG
default:
dev_warn(dev, "store_fan_div: Unexpected nr seen: %d\n", nr);
count = -EINVAL;
goto err_exit;
#endif
}
fan_div_reg = w83791d_read(client, W83791D_REG_FAN_DIV[indx])
& keep_mask;
tmp_fan_div = (data->fan_div[nr] << new_shift) & ~keep_mask;
w83791d_write(client, W83791D_REG_FAN_DIV[indx],
fan_div_reg | tmp_fan_div);
/* Bit 2 of fans 0-2 is stored in the vbat register (bits 5-7) */
if (nr < 3) {
keep_mask = ~(1 << (nr + 5));
vbat_reg = w83791d_read(client, W83791D_REG_VBAT)
& keep_mask;
tmp_fan_div = (data->fan_div[nr] << (3 + nr)) & ~keep_mask;
w83791d_write(client, W83791D_REG_VBAT,
vbat_reg | tmp_fan_div);
}
/* Restore fan_min */
data->fan_min[nr] = fan_to_reg(min, DIV_FROM_REG(data->fan_div[nr]));
w83791d_write(client, W83791D_REG_FAN_MIN[nr], data->fan_min[nr]);
#ifdef DEBUG
err_exit:
#endif
mutex_unlock(&data->update_lock);
return count;
}
static struct sensor_device_attribute sda_fan_input[] = {
SENSOR_ATTR(fan1_input, S_IRUGO, show_fan, NULL, 0),
SENSOR_ATTR(fan2_input, S_IRUGO, show_fan, NULL, 1),
SENSOR_ATTR(fan3_input, S_IRUGO, show_fan, NULL, 2),
SENSOR_ATTR(fan4_input, S_IRUGO, show_fan, NULL, 3),
SENSOR_ATTR(fan5_input, S_IRUGO, show_fan, NULL, 4),
};
static struct sensor_device_attribute sda_fan_min[] = {
SENSOR_ATTR(fan1_min, S_IWUSR | S_IRUGO,
show_fan_min, store_fan_min, 0),
SENSOR_ATTR(fan2_min, S_IWUSR | S_IRUGO,
show_fan_min, store_fan_min, 1),
SENSOR_ATTR(fan3_min, S_IWUSR | S_IRUGO,
show_fan_min, store_fan_min, 2),
SENSOR_ATTR(fan4_min, S_IWUSR | S_IRUGO,
show_fan_min, store_fan_min, 3),
SENSOR_ATTR(fan5_min, S_IWUSR | S_IRUGO,
show_fan_min, store_fan_min, 4),
};
static struct sensor_device_attribute sda_fan_div[] = {
SENSOR_ATTR(fan1_div, S_IWUSR | S_IRUGO,
show_fan_div, store_fan_div, 0),
SENSOR_ATTR(fan2_div, S_IWUSR | S_IRUGO,
show_fan_div, store_fan_div, 1),
SENSOR_ATTR(fan3_div, S_IWUSR | S_IRUGO,
show_fan_div, store_fan_div, 2),
SENSOR_ATTR(fan4_div, S_IWUSR | S_IRUGO,
show_fan_div, store_fan_div, 3),
SENSOR_ATTR(fan5_div, S_IWUSR | S_IRUGO,
show_fan_div, store_fan_div, 4),
};
static struct sensor_device_attribute sda_fan_beep[] = {
SENSOR_ATTR(fan1_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 6),
SENSOR_ATTR(fan2_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 7),
SENSOR_ATTR(fan3_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 11),
SENSOR_ATTR(fan4_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 21),
SENSOR_ATTR(fan5_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 22),
};
static struct sensor_device_attribute sda_fan_alarm[] = {
SENSOR_ATTR(fan1_alarm, S_IRUGO, show_alarm, NULL, 6),
SENSOR_ATTR(fan2_alarm, S_IRUGO, show_alarm, NULL, 7),
SENSOR_ATTR(fan3_alarm, S_IRUGO, show_alarm, NULL, 11),
SENSOR_ATTR(fan4_alarm, S_IRUGO, show_alarm, NULL, 21),
SENSOR_ATTR(fan5_alarm, S_IRUGO, show_alarm, NULL, 22),
};
/* read/write PWMs */
static ssize_t show_pwm(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct w83791d_data *data = w83791d_update_device(dev);
return sprintf(buf, "%u\n", data->pwm[nr]);
}
static ssize_t store_pwm(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
struct i2c_client *client = to_i2c_client(dev);
struct w83791d_data *data = i2c_get_clientdata(client);
int nr = sensor_attr->index;
unsigned long val;
if (strict_strtoul(buf, 10, &val))
return -EINVAL;
mutex_lock(&data->update_lock);
data->pwm[nr] = SENSORS_LIMIT(val, 0, 255);
w83791d_write(client, W83791D_REG_PWM[nr], data->pwm[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static struct sensor_device_attribute sda_pwm[] = {
SENSOR_ATTR(pwm1, S_IWUSR | S_IRUGO,
show_pwm, store_pwm, 0),
SENSOR_ATTR(pwm2, S_IWUSR | S_IRUGO,
show_pwm, store_pwm, 1),
SENSOR_ATTR(pwm3, S_IWUSR | S_IRUGO,
show_pwm, store_pwm, 2),
SENSOR_ATTR(pwm4, S_IWUSR | S_IRUGO,
show_pwm, store_pwm, 3),
SENSOR_ATTR(pwm5, S_IWUSR | S_IRUGO,
show_pwm, store_pwm, 4),
};
static ssize_t show_pwmenable(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
int nr = sensor_attr->index;
struct w83791d_data *data = w83791d_update_device(dev);
return sprintf(buf, "%u\n", data->pwm_enable[nr] + 1);
}
static ssize_t store_pwmenable(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
struct i2c_client *client = to_i2c_client(dev);
struct w83791d_data *data = i2c_get_clientdata(client);
int nr = sensor_attr->index;
unsigned long val;
u8 reg_cfg_tmp;
u8 reg_idx = 0;
u8 val_shift = 0;
u8 keep_mask = 0;
int ret = strict_strtoul(buf, 10, &val);
if (ret || val < 1 || val > 3)
return -EINVAL;
mutex_lock(&data->update_lock);
data->pwm_enable[nr] = val - 1;
switch (nr) {
case 0:
reg_idx = 0;
val_shift = 2;
keep_mask = 0xf3;
break;
case 1:
reg_idx = 0;
val_shift = 4;
keep_mask = 0xcf;
break;
case 2:
reg_idx = 1;
val_shift = 2;
keep_mask = 0xf3;
break;
}
reg_cfg_tmp = w83791d_read(client, W83791D_REG_FAN_CFG[reg_idx]);
reg_cfg_tmp = (reg_cfg_tmp & keep_mask) |
data->pwm_enable[nr] << val_shift;
w83791d_write(client, W83791D_REG_FAN_CFG[reg_idx], reg_cfg_tmp);
mutex_unlock(&data->update_lock);
return count;
}
static struct sensor_device_attribute sda_pwmenable[] = {
SENSOR_ATTR(pwm1_enable, S_IWUSR | S_IRUGO,
show_pwmenable, store_pwmenable, 0),
SENSOR_ATTR(pwm2_enable, S_IWUSR | S_IRUGO,
show_pwmenable, store_pwmenable, 1),
SENSOR_ATTR(pwm3_enable, S_IWUSR | S_IRUGO,
show_pwmenable, store_pwmenable, 2),
};
/* For Smart Fan I / Thermal Cruise */
static ssize_t show_temp_target(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
struct w83791d_data *data = w83791d_update_device(dev);
int nr = sensor_attr->index;
return sprintf(buf, "%d\n", TEMP1_FROM_REG(data->temp_target[nr]));
}
static ssize_t store_temp_target(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
struct i2c_client *client = to_i2c_client(dev);
struct w83791d_data *data = i2c_get_clientdata(client);
int nr = sensor_attr->index;
unsigned long val;
u8 target_mask;
if (strict_strtoul(buf, 10, &val))
return -EINVAL;
mutex_lock(&data->update_lock);
data->temp_target[nr] = TARGET_TEMP_TO_REG(val);
target_mask = w83791d_read(client,
W83791D_REG_TEMP_TARGET[nr]) & 0x80;
w83791d_write(client, W83791D_REG_TEMP_TARGET[nr],
data->temp_target[nr] | target_mask);
mutex_unlock(&data->update_lock);
return count;
}
static struct sensor_device_attribute sda_temp_target[] = {
SENSOR_ATTR(temp1_target, S_IWUSR | S_IRUGO,
show_temp_target, store_temp_target, 0),
SENSOR_ATTR(temp2_target, S_IWUSR | S_IRUGO,
show_temp_target, store_temp_target, 1),
SENSOR_ATTR(temp3_target, S_IWUSR | S_IRUGO,
show_temp_target, store_temp_target, 2),
};
static ssize_t show_temp_tolerance(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
struct w83791d_data *data = w83791d_update_device(dev);
int nr = sensor_attr->index;
return sprintf(buf, "%d\n", TEMP1_FROM_REG(data->temp_tolerance[nr]));
}
static ssize_t store_temp_tolerance(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct sensor_device_attribute *sensor_attr = to_sensor_dev_attr(attr);
struct i2c_client *client = to_i2c_client(dev);
struct w83791d_data *data = i2c_get_clientdata(client);
int nr = sensor_attr->index;
unsigned long val;
u8 target_mask;
u8 reg_idx = 0;
u8 val_shift = 0;
u8 keep_mask = 0;
if (strict_strtoul(buf, 10, &val))
return -EINVAL;
switch (nr) {
case 0:
reg_idx = 0;
val_shift = 0;
keep_mask = 0xf0;
break;
case 1:
reg_idx = 0;
val_shift = 4;
keep_mask = 0x0f;
break;
case 2:
reg_idx = 1;
val_shift = 0;
keep_mask = 0xf0;
break;
}
mutex_lock(&data->update_lock);
data->temp_tolerance[nr] = TOL_TEMP_TO_REG(val);
target_mask = w83791d_read(client,
W83791D_REG_TEMP_TOL[reg_idx]) & keep_mask;
w83791d_write(client, W83791D_REG_TEMP_TOL[reg_idx],
(data->temp_tolerance[nr] << val_shift) | target_mask);
mutex_unlock(&data->update_lock);
return count;
}
static struct sensor_device_attribute sda_temp_tolerance[] = {
SENSOR_ATTR(temp1_tolerance, S_IWUSR | S_IRUGO,
show_temp_tolerance, store_temp_tolerance, 0),
SENSOR_ATTR(temp2_tolerance, S_IWUSR | S_IRUGO,
show_temp_tolerance, store_temp_tolerance, 1),
SENSOR_ATTR(temp3_tolerance, S_IWUSR | S_IRUGO,
show_temp_tolerance, store_temp_tolerance, 2),
};
/* read/write the temperature1, includes measured value and limits */
static ssize_t show_temp1(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct w83791d_data *data = w83791d_update_device(dev);
return sprintf(buf, "%d\n", TEMP1_FROM_REG(data->temp1[attr->index]));
}
static ssize_t store_temp1(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct i2c_client *client = to_i2c_client(dev);
struct w83791d_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
int nr = attr->index;
mutex_lock(&data->update_lock);
data->temp1[nr] = TEMP1_TO_REG(val);
w83791d_write(client, W83791D_REG_TEMP1[nr], data->temp1[nr]);
mutex_unlock(&data->update_lock);
return count;
}
/* read/write temperature2-3, includes measured value and limits */
static ssize_t show_temp23(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
struct w83791d_data *data = w83791d_update_device(dev);
int nr = attr->nr;
int index = attr->index;
return sprintf(buf, "%d\n", TEMP23_FROM_REG(data->temp_add[nr][index]));
}
static ssize_t store_temp23(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct sensor_device_attribute_2 *attr = to_sensor_dev_attr_2(devattr);
struct i2c_client *client = to_i2c_client(dev);
struct w83791d_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
int nr = attr->nr;
int index = attr->index;
mutex_lock(&data->update_lock);
data->temp_add[nr][index] = TEMP23_TO_REG(val);
w83791d_write(client, W83791D_REG_TEMP_ADD[nr][index * 2],
data->temp_add[nr][index] >> 8);
w83791d_write(client, W83791D_REG_TEMP_ADD[nr][index * 2 + 1],
data->temp_add[nr][index] & 0x80);
mutex_unlock(&data->update_lock);
return count;
}
static struct sensor_device_attribute_2 sda_temp_input[] = {
SENSOR_ATTR_2(temp1_input, S_IRUGO, show_temp1, NULL, 0, 0),
SENSOR_ATTR_2(temp2_input, S_IRUGO, show_temp23, NULL, 0, 0),
SENSOR_ATTR_2(temp3_input, S_IRUGO, show_temp23, NULL, 1, 0),
};
static struct sensor_device_attribute_2 sda_temp_max[] = {
SENSOR_ATTR_2(temp1_max, S_IRUGO | S_IWUSR,
show_temp1, store_temp1, 0, 1),
SENSOR_ATTR_2(temp2_max, S_IRUGO | S_IWUSR,
show_temp23, store_temp23, 0, 1),
SENSOR_ATTR_2(temp3_max, S_IRUGO | S_IWUSR,
show_temp23, store_temp23, 1, 1),
};
static struct sensor_device_attribute_2 sda_temp_max_hyst[] = {
SENSOR_ATTR_2(temp1_max_hyst, S_IRUGO | S_IWUSR,
show_temp1, store_temp1, 0, 2),
SENSOR_ATTR_2(temp2_max_hyst, S_IRUGO | S_IWUSR,
show_temp23, store_temp23, 0, 2),
SENSOR_ATTR_2(temp3_max_hyst, S_IRUGO | S_IWUSR,
show_temp23, store_temp23, 1, 2),
};
/* Note: The bitmask for the beep enable/disable is different than
the bitmask for the alarm. */
static struct sensor_device_attribute sda_temp_beep[] = {
SENSOR_ATTR(temp1_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 4),
SENSOR_ATTR(temp2_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 5),
SENSOR_ATTR(temp3_beep, S_IWUSR | S_IRUGO, show_beep, store_beep, 1),
};
static struct sensor_device_attribute sda_temp_alarm[] = {
SENSOR_ATTR(temp1_alarm, S_IRUGO, show_alarm, NULL, 4),
SENSOR_ATTR(temp2_alarm, S_IRUGO, show_alarm, NULL, 5),
SENSOR_ATTR(temp3_alarm, S_IRUGO, show_alarm, NULL, 13),
};
/* get reatime status of all sensors items: voltage, temp, fan */
static ssize_t show_alarms_reg(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct w83791d_data *data = w83791d_update_device(dev);
return sprintf(buf, "%u\n", data->alarms);
}
static DEVICE_ATTR(alarms, S_IRUGO, show_alarms_reg, NULL);
/* Beep control */
#define GLOBAL_BEEP_ENABLE_SHIFT 15
#define GLOBAL_BEEP_ENABLE_MASK (1 << GLOBAL_BEEP_ENABLE_SHIFT)
static ssize_t show_beep_enable(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct w83791d_data *data = w83791d_update_device(dev);
return sprintf(buf, "%d\n", data->beep_enable);
}
static ssize_t show_beep_mask(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct w83791d_data *data = w83791d_update_device(dev);
return sprintf(buf, "%d\n", BEEP_MASK_FROM_REG(data->beep_mask));
}
static ssize_t store_beep_mask(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct w83791d_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
int i;
mutex_lock(&data->update_lock);
/* The beep_enable state overrides any enabling request from
the masks */
data->beep_mask = BEEP_MASK_TO_REG(val) & ~GLOBAL_BEEP_ENABLE_MASK;
data->beep_mask |= (data->beep_enable << GLOBAL_BEEP_ENABLE_SHIFT);
val = data->beep_mask;
for (i = 0; i < 3; i++) {
w83791d_write(client, W83791D_REG_BEEP_CTRL[i], (val & 0xff));
val >>= 8;
}
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t store_beep_enable(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct w83791d_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
mutex_lock(&data->update_lock);
data->beep_enable = val ? 1 : 0;
/* Keep the full mask value in sync with the current enable */
data->beep_mask &= ~GLOBAL_BEEP_ENABLE_MASK;
data->beep_mask |= (data->beep_enable << GLOBAL_BEEP_ENABLE_SHIFT);
/* The global control is in the second beep control register
so only need to update that register */
val = (data->beep_mask >> 8) & 0xff;
w83791d_write(client, W83791D_REG_BEEP_CTRL[1], val);
mutex_unlock(&data->update_lock);
return count;
}
static struct sensor_device_attribute sda_beep_ctrl[] = {
SENSOR_ATTR(beep_enable, S_IRUGO | S_IWUSR,
show_beep_enable, store_beep_enable, 0),
SENSOR_ATTR(beep_mask, S_IRUGO | S_IWUSR,
show_beep_mask, store_beep_mask, 1)
};
/* cpu voltage regulation information */
static ssize_t show_vid_reg(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct w83791d_data *data = w83791d_update_device(dev);
return sprintf(buf, "%d\n", vid_from_reg(data->vid, data->vrm));
}
static DEVICE_ATTR(cpu0_vid, S_IRUGO, show_vid_reg, NULL);
static ssize_t show_vrm_reg(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct w83791d_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", data->vrm);
}
static ssize_t store_vrm_reg(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct w83791d_data *data = dev_get_drvdata(dev);
/* No lock needed as vrm is internal to the driver
(not read from a chip register) and so is not
updated in w83791d_update_device() */
data->vrm = simple_strtoul(buf, NULL, 10);
return count;
}
static DEVICE_ATTR(vrm, S_IRUGO | S_IWUSR, show_vrm_reg, store_vrm_reg);
#define IN_UNIT_ATTRS(X) \
&sda_in_input[X].dev_attr.attr, \
&sda_in_min[X].dev_attr.attr, \
&sda_in_max[X].dev_attr.attr, \
&sda_in_beep[X].dev_attr.attr, \
&sda_in_alarm[X].dev_attr.attr
#define FAN_UNIT_ATTRS(X) \
&sda_fan_input[X].dev_attr.attr, \
&sda_fan_min[X].dev_attr.attr, \
&sda_fan_div[X].dev_attr.attr, \
&sda_fan_beep[X].dev_attr.attr, \
&sda_fan_alarm[X].dev_attr.attr
#define TEMP_UNIT_ATTRS(X) \
&sda_temp_input[X].dev_attr.attr, \
&sda_temp_max[X].dev_attr.attr, \
&sda_temp_max_hyst[X].dev_attr.attr, \
&sda_temp_beep[X].dev_attr.attr, \
&sda_temp_alarm[X].dev_attr.attr
static struct attribute *w83791d_attributes[] = {
IN_UNIT_ATTRS(0),
IN_UNIT_ATTRS(1),
IN_UNIT_ATTRS(2),
IN_UNIT_ATTRS(3),
IN_UNIT_ATTRS(4),
IN_UNIT_ATTRS(5),
IN_UNIT_ATTRS(6),
IN_UNIT_ATTRS(7),
IN_UNIT_ATTRS(8),
IN_UNIT_ATTRS(9),
FAN_UNIT_ATTRS(0),
FAN_UNIT_ATTRS(1),
FAN_UNIT_ATTRS(2),
TEMP_UNIT_ATTRS(0),
TEMP_UNIT_ATTRS(1),
TEMP_UNIT_ATTRS(2),
&dev_attr_alarms.attr,
&sda_beep_ctrl[0].dev_attr.attr,
&sda_beep_ctrl[1].dev_attr.attr,
&dev_attr_cpu0_vid.attr,
&dev_attr_vrm.attr,
&sda_pwm[0].dev_attr.attr,
&sda_pwm[1].dev_attr.attr,
&sda_pwm[2].dev_attr.attr,
&sda_pwmenable[0].dev_attr.attr,
&sda_pwmenable[1].dev_attr.attr,
&sda_pwmenable[2].dev_attr.attr,
&sda_temp_target[0].dev_attr.attr,
&sda_temp_target[1].dev_attr.attr,
&sda_temp_target[2].dev_attr.attr,
&sda_temp_tolerance[0].dev_attr.attr,
&sda_temp_tolerance[1].dev_attr.attr,
&sda_temp_tolerance[2].dev_attr.attr,
NULL
};
static const struct attribute_group w83791d_group = {
.attrs = w83791d_attributes,
};
/* Separate group of attributes for fan/pwm 4-5. Their pins can also be
in use for GPIO in which case their sysfs-interface should not be made
available */
static struct attribute *w83791d_attributes_fanpwm45[] = {
FAN_UNIT_ATTRS(3),
FAN_UNIT_ATTRS(4),
&sda_pwm[3].dev_attr.attr,
&sda_pwm[4].dev_attr.attr,
NULL
};
static const struct attribute_group w83791d_group_fanpwm45 = {
.attrs = w83791d_attributes_fanpwm45,
};
static int w83791d_detect_subclients(struct i2c_client *client)
{
struct i2c_adapter *adapter = client->adapter;
struct w83791d_data *data = i2c_get_clientdata(client);
int address = client->addr;
int i, id, err;
u8 val;
id = i2c_adapter_id(adapter);
if (force_subclients[0] == id && force_subclients[1] == address) {
for (i = 2; i <= 3; i++) {
if (force_subclients[i] < 0x48 ||
force_subclients[i] > 0x4f) {
dev_err(&client->dev,
"invalid subclient "
"address %d; must be 0x48-0x4f\n",
force_subclients[i]);
err = -ENODEV;
goto error_sc_0;
}
}
w83791d_write(client, W83791D_REG_I2C_SUBADDR,
(force_subclients[2] & 0x07) |
((force_subclients[3] & 0x07) << 4));
}
val = w83791d_read(client, W83791D_REG_I2C_SUBADDR);
if (!(val & 0x08)) {
data->lm75[0] = i2c_new_dummy(adapter, 0x48 + (val & 0x7));
}
if (!(val & 0x80)) {
if ((data->lm75[0] != NULL) &&
((val & 0x7) == ((val >> 4) & 0x7))) {
dev_err(&client->dev,
"duplicate addresses 0x%x, "
"use force_subclient\n",
data->lm75[0]->addr);
err = -ENODEV;
goto error_sc_1;
}
data->lm75[1] = i2c_new_dummy(adapter,
0x48 + ((val >> 4) & 0x7));
}
return 0;
/* Undo inits in case of errors */
error_sc_1:
if (data->lm75[0] != NULL)
i2c_unregister_device(data->lm75[0]);
error_sc_0:
return err;
}
/* Return 0 if detection is successful, -ENODEV otherwise */
static int w83791d_detect(struct i2c_client *client,
struct i2c_board_info *info)
{
struct i2c_adapter *adapter = client->adapter;
int val1, val2;
unsigned short address = client->addr;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) {
return -ENODEV;
}
if (w83791d_read(client, W83791D_REG_CONFIG) & 0x80)
return -ENODEV;
val1 = w83791d_read(client, W83791D_REG_BANK);
val2 = w83791d_read(client, W83791D_REG_CHIPMAN);
/* Check for Winbond ID if in bank 0 */
if (!(val1 & 0x07)) {
if ((!(val1 & 0x80) && val2 != 0xa3) ||
( (val1 & 0x80) && val2 != 0x5c)) {
return -ENODEV;
}
}
/* If Winbond chip, address of chip and W83791D_REG_I2C_ADDR
should match */
if (w83791d_read(client, W83791D_REG_I2C_ADDR) != address)
return -ENODEV;
/* We want bank 0 and Vendor ID high byte */
val1 = w83791d_read(client, W83791D_REG_BANK) & 0x78;
w83791d_write(client, W83791D_REG_BANK, val1 | 0x80);
/* Verify it is a Winbond w83791d */
val1 = w83791d_read(client, W83791D_REG_WCHIPID);
val2 = w83791d_read(client, W83791D_REG_CHIPMAN);
if (val1 != 0x71 || val2 != 0x5c)
return -ENODEV;
strlcpy(info->type, "w83791d", I2C_NAME_SIZE);
return 0;
}
static int w83791d_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct w83791d_data *data;
struct device *dev = &client->dev;
int i, err;
u8 has_fanpwm45;
#ifdef DEBUG
int val1;
val1 = w83791d_read(client, W83791D_REG_DID_VID4);
dev_dbg(dev, "Device ID version: %d.%d (0x%02x)\n",
(val1 >> 5) & 0x07, (val1 >> 1) & 0x0f, val1);
#endif
data = kzalloc(sizeof(struct w83791d_data), GFP_KERNEL);
if (!data) {
err = -ENOMEM;
goto error0;
}
i2c_set_clientdata(client, data);
mutex_init(&data->update_lock);
err = w83791d_detect_subclients(client);
if (err)
goto error1;
/* Initialize the chip */
w83791d_init_client(client);
/* If the fan_div is changed, make sure there is a rational
fan_min in place */
for (i = 0; i < NUMBER_OF_FANIN; i++) {
data->fan_min[i] = w83791d_read(client, W83791D_REG_FAN_MIN[i]);
}
/* Register sysfs hooks */
if ((err = sysfs_create_group(&client->dev.kobj, &w83791d_group)))
goto error3;
/* Check if pins of fan/pwm 4-5 are in use as GPIO */
has_fanpwm45 = w83791d_read(client, W83791D_REG_GPIO) & 0x10;
if (has_fanpwm45) {
err = sysfs_create_group(&client->dev.kobj,
&w83791d_group_fanpwm45);
if (err)
goto error4;
}
/* Everything is ready, now register the working device */
data->hwmon_dev = hwmon_device_register(dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto error5;
}
return 0;
error5:
if (has_fanpwm45)
sysfs_remove_group(&client->dev.kobj, &w83791d_group_fanpwm45);
error4:
sysfs_remove_group(&client->dev.kobj, &w83791d_group);
error3:
if (data->lm75[0] != NULL)
i2c_unregister_device(data->lm75[0]);
if (data->lm75[1] != NULL)
i2c_unregister_device(data->lm75[1]);
error1:
kfree(data);
error0:
return err;
}
static int w83791d_remove(struct i2c_client *client)
{
struct w83791d_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&client->dev.kobj, &w83791d_group);
if (data->lm75[0] != NULL)
i2c_unregister_device(data->lm75[0]);
if (data->lm75[1] != NULL)
i2c_unregister_device(data->lm75[1]);
kfree(data);
return 0;
}
static void w83791d_init_client(struct i2c_client *client)
{
struct w83791d_data *data = i2c_get_clientdata(client);
u8 tmp;
u8 old_beep;
/* The difference between reset and init is that reset
does a hard reset of the chip via index 0x40, bit 7,
but init simply forces certain registers to have "sane"
values. The hope is that the BIOS has done the right
thing (which is why the default is reset=0, init=0),
but if not, reset is the hard hammer and init
is the soft mallet both of which are trying to whack
things into place...
NOTE: The data sheet makes a distinction between
"power on defaults" and "reset by MR". As far as I can tell,
the hard reset puts everything into a power-on state so I'm
not sure what "reset by MR" means or how it can happen.
*/
if (reset || init) {
/* keep some BIOS settings when we... */
old_beep = w83791d_read(client, W83791D_REG_BEEP_CONFIG);
if (reset) {
/* ... reset the chip and ... */
w83791d_write(client, W83791D_REG_CONFIG, 0x80);
}
/* ... disable power-on abnormal beep */
w83791d_write(client, W83791D_REG_BEEP_CONFIG, old_beep | 0x80);
/* disable the global beep (not done by hard reset) */
tmp = w83791d_read(client, W83791D_REG_BEEP_CTRL[1]);
w83791d_write(client, W83791D_REG_BEEP_CTRL[1], tmp & 0xef);
if (init) {
/* Make sure monitoring is turned on for add-ons */
tmp = w83791d_read(client, W83791D_REG_TEMP2_CONFIG);
if (tmp & 1) {
w83791d_write(client, W83791D_REG_TEMP2_CONFIG,
tmp & 0xfe);
}
tmp = w83791d_read(client, W83791D_REG_TEMP3_CONFIG);
if (tmp & 1) {
w83791d_write(client, W83791D_REG_TEMP3_CONFIG,
tmp & 0xfe);
}
/* Start monitoring */
tmp = w83791d_read(client, W83791D_REG_CONFIG) & 0xf7;
w83791d_write(client, W83791D_REG_CONFIG, tmp | 0x01);
}
}
data->vrm = vid_which_vrm();
}
static struct w83791d_data *w83791d_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct w83791d_data *data = i2c_get_clientdata(client);
int i, j;
u8 reg_array_tmp[3];
u8 vbat_reg;
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + (HZ * 3))
|| !data->valid) {
dev_dbg(dev, "Starting w83791d device update\n");
/* Update the voltages measured value and limits */
for (i = 0; i < NUMBER_OF_VIN; i++) {
data->in[i] = w83791d_read(client,
W83791D_REG_IN[i]);
data->in_max[i] = w83791d_read(client,
W83791D_REG_IN_MAX[i]);
data->in_min[i] = w83791d_read(client,
W83791D_REG_IN_MIN[i]);
}
/* Update the fan counts and limits */
for (i = 0; i < NUMBER_OF_FANIN; i++) {
/* Update the Fan measured value and limits */
data->fan[i] = w83791d_read(client,
W83791D_REG_FAN[i]);
data->fan_min[i] = w83791d_read(client,
W83791D_REG_FAN_MIN[i]);
}
/* Update the fan divisor */
for (i = 0; i < 3; i++) {
reg_array_tmp[i] = w83791d_read(client,
W83791D_REG_FAN_DIV[i]);
}
data->fan_div[0] = (reg_array_tmp[0] >> 4) & 0x03;
data->fan_div[1] = (reg_array_tmp[0] >> 6) & 0x03;
data->fan_div[2] = (reg_array_tmp[1] >> 6) & 0x03;
data->fan_div[3] = reg_array_tmp[2] & 0x07;
data->fan_div[4] = (reg_array_tmp[2] >> 4) & 0x07;
/* The fan divisor for fans 0-2 get bit 2 from
bits 5-7 respectively of vbat register */
vbat_reg = w83791d_read(client, W83791D_REG_VBAT);
for (i = 0; i < 3; i++)
data->fan_div[i] |= (vbat_reg >> (3 + i)) & 0x04;
/* Update PWM duty cycle */
for (i = 0; i < NUMBER_OF_PWM; i++) {
data->pwm[i] = w83791d_read(client,
W83791D_REG_PWM[i]);
}
/* Update PWM enable status */
for (i = 0; i < 2; i++) {
reg_array_tmp[i] = w83791d_read(client,
W83791D_REG_FAN_CFG[i]);
}
data->pwm_enable[0] = (reg_array_tmp[0] >> 2) & 0x03;
data->pwm_enable[1] = (reg_array_tmp[0] >> 4) & 0x03;
data->pwm_enable[2] = (reg_array_tmp[1] >> 2) & 0x03;
/* Update PWM target temperature */
for (i = 0; i < 3; i++) {
data->temp_target[i] = w83791d_read(client,
W83791D_REG_TEMP_TARGET[i]) & 0x7f;
}
/* Update PWM temperature tolerance */
for (i = 0; i < 2; i++) {
reg_array_tmp[i] = w83791d_read(client,
W83791D_REG_TEMP_TOL[i]);
}
data->temp_tolerance[0] = reg_array_tmp[0] & 0x0f;
data->temp_tolerance[1] = (reg_array_tmp[0] >> 4) & 0x0f;
data->temp_tolerance[2] = reg_array_tmp[1] & 0x0f;
/* Update the first temperature sensor */
for (i = 0; i < 3; i++) {
data->temp1[i] = w83791d_read(client,
W83791D_REG_TEMP1[i]);
}
/* Update the rest of the temperature sensors */
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
data->temp_add[i][j] =
(w83791d_read(client,
W83791D_REG_TEMP_ADD[i][j * 2]) << 8) |
w83791d_read(client,
W83791D_REG_TEMP_ADD[i][j * 2 + 1]);
}
}
/* Update the realtime status */
data->alarms =
w83791d_read(client, W83791D_REG_ALARM1) +
(w83791d_read(client, W83791D_REG_ALARM2) << 8) +
(w83791d_read(client, W83791D_REG_ALARM3) << 16);
/* Update the beep configuration information */
data->beep_mask =
w83791d_read(client, W83791D_REG_BEEP_CTRL[0]) +
(w83791d_read(client, W83791D_REG_BEEP_CTRL[1]) << 8) +
(w83791d_read(client, W83791D_REG_BEEP_CTRL[2]) << 16);
/* Extract global beep enable flag */
data->beep_enable =
(data->beep_mask >> GLOBAL_BEEP_ENABLE_SHIFT) & 0x01;
/* Update the cpu voltage information */
i = w83791d_read(client, W83791D_REG_VID_FANDIV);
data->vid = i & 0x0f;
data->vid |= (w83791d_read(client, W83791D_REG_DID_VID4) & 0x01)
<< 4;
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
#ifdef DEBUG
w83791d_print_debug(data, dev);
#endif
return data;
}
#ifdef DEBUG
static void w83791d_print_debug(struct w83791d_data *data, struct device *dev)
{
int i = 0, j = 0;
dev_dbg(dev, "======Start of w83791d debug values======\n");
dev_dbg(dev, "%d set of Voltages: ===>\n", NUMBER_OF_VIN);
for (i = 0; i < NUMBER_OF_VIN; i++) {
dev_dbg(dev, "vin[%d] is: 0x%02x\n", i, data->in[i]);
dev_dbg(dev, "vin[%d] min is: 0x%02x\n", i, data->in_min[i]);
dev_dbg(dev, "vin[%d] max is: 0x%02x\n", i, data->in_max[i]);
}
dev_dbg(dev, "%d set of Fan Counts/Divisors: ===>\n", NUMBER_OF_FANIN);
for (i = 0; i < NUMBER_OF_FANIN; i++) {
dev_dbg(dev, "fan[%d] is: 0x%02x\n", i, data->fan[i]);
dev_dbg(dev, "fan[%d] min is: 0x%02x\n", i, data->fan_min[i]);
dev_dbg(dev, "fan_div[%d] is: 0x%02x\n", i, data->fan_div[i]);
}
/* temperature math is signed, but only print out the
bits that matter */
dev_dbg(dev, "%d set of Temperatures: ===>\n", NUMBER_OF_TEMPIN);
for (i = 0; i < 3; i++) {
dev_dbg(dev, "temp1[%d] is: 0x%02x\n", i, (u8) data->temp1[i]);
}
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
dev_dbg(dev, "temp_add[%d][%d] is: 0x%04x\n", i, j,
(u16) data->temp_add[i][j]);
}
}
dev_dbg(dev, "Misc Information: ===>\n");
dev_dbg(dev, "alarm is: 0x%08x\n", data->alarms);
dev_dbg(dev, "beep_mask is: 0x%08x\n", data->beep_mask);
dev_dbg(dev, "beep_enable is: %d\n", data->beep_enable);
dev_dbg(dev, "vid is: 0x%02x\n", data->vid);
dev_dbg(dev, "vrm is: 0x%02x\n", data->vrm);
dev_dbg(dev, "=======End of w83791d debug values========\n");
dev_dbg(dev, "\n");
}
#endif
static int __init sensors_w83791d_init(void)
{
return i2c_add_driver(&w83791d_driver);
}
static void __exit sensors_w83791d_exit(void)
{
i2c_del_driver(&w83791d_driver);
}
MODULE_AUTHOR("Charles Spirakis <bezaur@gmail.com>");
MODULE_DESCRIPTION("W83791D driver");
MODULE_LICENSE("GPL");
module_init(sensors_w83791d_init);
module_exit(sensors_w83791d_exit);
| gpl-2.0 |
yank555-lu/TF101G_V9.2.2.6 | drivers/media/rc/keymaps/rc-dntv-live-dvb-t.c | 2944 | 2052 | /* dntv-live-dvb-t.h - Keytable for dntv_live_dvb_t Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Mauro Carvalho Chehab <mchehab@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 <media/rc-map.h>
/* DigitalNow DNTV Live DVB-T Remote */
static struct rc_map_table dntv_live_dvb_t[] = {
{ 0x00, KEY_ESC }, /* 'go up a level?' */
/* Keys 0 to 9 */
{ 0x0a, KEY_0 },
{ 0x01, KEY_1 },
{ 0x02, KEY_2 },
{ 0x03, KEY_3 },
{ 0x04, KEY_4 },
{ 0x05, KEY_5 },
{ 0x06, KEY_6 },
{ 0x07, KEY_7 },
{ 0x08, KEY_8 },
{ 0x09, KEY_9 },
{ 0x0b, KEY_TUNER }, /* tv/fm */
{ 0x0c, KEY_SEARCH }, /* scan */
{ 0x0d, KEY_STOP },
{ 0x0e, KEY_PAUSE },
{ 0x0f, KEY_VIDEO }, /* source */
{ 0x10, KEY_MUTE },
{ 0x11, KEY_REWIND }, /* backward << */
{ 0x12, KEY_POWER },
{ 0x13, KEY_CAMERA }, /* snap */
{ 0x14, KEY_AUDIO }, /* stereo */
{ 0x15, KEY_CLEAR }, /* reset */
{ 0x16, KEY_PLAY },
{ 0x17, KEY_ENTER },
{ 0x18, KEY_ZOOM }, /* full screen */
{ 0x19, KEY_FASTFORWARD }, /* forward >> */
{ 0x1a, KEY_CHANNELUP },
{ 0x1b, KEY_VOLUMEUP },
{ 0x1c, KEY_INFO }, /* preview */
{ 0x1d, KEY_RECORD }, /* record */
{ 0x1e, KEY_CHANNELDOWN },
{ 0x1f, KEY_VOLUMEDOWN },
};
static struct rc_map_list dntv_live_dvb_t_map = {
.map = {
.scan = dntv_live_dvb_t,
.size = ARRAY_SIZE(dntv_live_dvb_t),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_DNTV_LIVE_DVB_T,
}
};
static int __init init_rc_map_dntv_live_dvb_t(void)
{
return rc_map_register(&dntv_live_dvb_t_map);
}
static void __exit exit_rc_map_dntv_live_dvb_t(void)
{
rc_map_unregister(&dntv_live_dvb_t_map);
}
module_init(init_rc_map_dntv_live_dvb_t)
module_exit(exit_rc_map_dntv_live_dvb_t)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
CyanogenMod/android_kernel_acer_t20-common | drivers/media/rc/keymaps/rc-terratec-slim-2.c | 2944 | 2216 | /*
* TerraTec remote controller keytable
*
* Copyright (C) 2011 Martin Groszhauser <mgroszhauser@gmail.com>
* Copyright (C) 2011 Antti Palosaari <crope@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <media/rc-map.h>
/*
* TerraTec slim remote, 6 rows, 3 columns.
* Keytable from Martin Groszhauser <mgroszhauser@gmail.com>
*/
static struct rc_map_table terratec_slim_2[] = {
{ 0x8001, KEY_MUTE }, /* MUTE */
{ 0x8002, KEY_VOLUMEDOWN },
{ 0x8003, KEY_CHANNELDOWN },
{ 0x8004, KEY_1 },
{ 0x8005, KEY_2 },
{ 0x8006, KEY_3 },
{ 0x8007, KEY_4 },
{ 0x8008, KEY_5 },
{ 0x8009, KEY_6 },
{ 0x800a, KEY_7 },
{ 0x800c, KEY_ZOOM }, /* [fullscreen] */
{ 0x800d, KEY_0 },
{ 0x800e, KEY_AGAIN }, /* [two arrows forming a circle] */
{ 0x8012, KEY_POWER2 }, /* [red power button] */
{ 0x801a, KEY_VOLUMEUP },
{ 0x801b, KEY_8 },
{ 0x801e, KEY_CHANNELUP },
{ 0x801f, KEY_9 },
};
static struct rc_map_list terratec_slim_2_map = {
.map = {
.scan = terratec_slim_2,
.size = ARRAY_SIZE(terratec_slim_2),
.rc_type = RC_TYPE_NEC,
.name = RC_MAP_TERRATEC_SLIM_2,
}
};
static int __init init_rc_map_terratec_slim_2(void)
{
return rc_map_register(&terratec_slim_2_map);
}
static void __exit exit_rc_map_terratec_slim_2(void)
{
rc_map_unregister(&terratec_slim_2_map);
}
module_init(init_rc_map_terratec_slim_2)
module_exit(exit_rc_map_terratec_slim_2)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
| gpl-2.0 |
InfinitiveOS-Devices/kernel_xiaomi_armani | net/ipv4/datagram.c | 6784 | 2074 | /*
* common UDP/RAW code
* Linux INET implementation
*
* Authors:
* Hideaki YOSHIFUJI <yoshfuji@linux-ipv6.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <net/ip.h>
#include <net/sock.h>
#include <net/route.h>
#include <net/tcp_states.h>
int ip4_datagram_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct sockaddr_in *usin = (struct sockaddr_in *) uaddr;
struct flowi4 *fl4;
struct rtable *rt;
__be32 saddr;
int oif;
int err;
if (addr_len < sizeof(*usin))
return -EINVAL;
if (usin->sin_family != AF_INET)
return -EAFNOSUPPORT;
sk_dst_reset(sk);
lock_sock(sk);
oif = sk->sk_bound_dev_if;
saddr = inet->inet_saddr;
if (ipv4_is_multicast(usin->sin_addr.s_addr)) {
if (!oif)
oif = inet->mc_index;
if (!saddr)
saddr = inet->mc_addr;
}
fl4 = &inet->cork.fl.u.ip4;
rt = ip_route_connect(fl4, usin->sin_addr.s_addr, saddr,
RT_CONN_FLAGS(sk), oif,
sk->sk_protocol,
inet->inet_sport, usin->sin_port, sk, true);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
if (err == -ENETUNREACH)
IP_INC_STATS_BH(sock_net(sk), IPSTATS_MIB_OUTNOROUTES);
goto out;
}
if ((rt->rt_flags & RTCF_BROADCAST) && !sock_flag(sk, SOCK_BROADCAST)) {
ip_rt_put(rt);
err = -EACCES;
goto out;
}
if (!inet->inet_saddr)
inet->inet_saddr = fl4->saddr; /* Update source address */
if (!inet->inet_rcv_saddr) {
inet->inet_rcv_saddr = fl4->saddr;
if (sk->sk_prot->rehash)
sk->sk_prot->rehash(sk);
}
inet->inet_daddr = fl4->daddr;
inet->inet_dport = usin->sin_port;
sk->sk_state = TCP_ESTABLISHED;
inet->inet_id = jiffies;
sk_dst_set(sk, &rt->dst);
err = 0;
out:
release_sock(sk);
return err;
}
EXPORT_SYMBOL(ip4_datagram_connect);
| gpl-2.0 |
cholokei/android_kernel_samsung_milletwifikx | drivers/input/misc/gpio_matrix.c | 8064 | 12640 | /* drivers/input/misc/gpio_matrix.c
*
* Copyright (C) 2007 Google, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/gpio.h>
#include <linux/gpio_event.h>
#include <linux/hrtimer.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/wakelock.h>
struct gpio_kp {
struct gpio_event_input_devs *input_devs;
struct gpio_event_matrix_info *keypad_info;
struct hrtimer timer;
struct wake_lock wake_lock;
int current_output;
unsigned int use_irq:1;
unsigned int key_state_changed:1;
unsigned int last_key_state_changed:1;
unsigned int some_keys_pressed:2;
unsigned int disabled_irq:1;
unsigned long keys_pressed[0];
};
static void clear_phantom_key(struct gpio_kp *kp, int out, int in)
{
struct gpio_event_matrix_info *mi = kp->keypad_info;
int key_index = out * mi->ninputs + in;
unsigned short keyentry = mi->keymap[key_index];
unsigned short keycode = keyentry & MATRIX_KEY_MASK;
unsigned short dev = keyentry >> MATRIX_CODE_BITS;
if (!test_bit(keycode, kp->input_devs->dev[dev]->key)) {
if (mi->flags & GPIOKPF_PRINT_PHANTOM_KEYS)
pr_info("gpiomatrix: phantom key %x, %d-%d (%d-%d) "
"cleared\n", keycode, out, in,
mi->output_gpios[out], mi->input_gpios[in]);
__clear_bit(key_index, kp->keys_pressed);
} else {
if (mi->flags & GPIOKPF_PRINT_PHANTOM_KEYS)
pr_info("gpiomatrix: phantom key %x, %d-%d (%d-%d) "
"not cleared\n", keycode, out, in,
mi->output_gpios[out], mi->input_gpios[in]);
}
}
static int restore_keys_for_input(struct gpio_kp *kp, int out, int in)
{
int rv = 0;
int key_index;
key_index = out * kp->keypad_info->ninputs + in;
while (out < kp->keypad_info->noutputs) {
if (test_bit(key_index, kp->keys_pressed)) {
rv = 1;
clear_phantom_key(kp, out, in);
}
key_index += kp->keypad_info->ninputs;
out++;
}
return rv;
}
static void remove_phantom_keys(struct gpio_kp *kp)
{
int out, in, inp;
int key_index;
if (kp->some_keys_pressed < 3)
return;
for (out = 0; out < kp->keypad_info->noutputs; out++) {
inp = -1;
key_index = out * kp->keypad_info->ninputs;
for (in = 0; in < kp->keypad_info->ninputs; in++, key_index++) {
if (test_bit(key_index, kp->keys_pressed)) {
if (inp == -1) {
inp = in;
continue;
}
if (inp >= 0) {
if (!restore_keys_for_input(kp, out + 1,
inp))
break;
clear_phantom_key(kp, out, inp);
inp = -2;
}
restore_keys_for_input(kp, out, in);
}
}
}
}
static void report_key(struct gpio_kp *kp, int key_index, int out, int in)
{
struct gpio_event_matrix_info *mi = kp->keypad_info;
int pressed = test_bit(key_index, kp->keys_pressed);
unsigned short keyentry = mi->keymap[key_index];
unsigned short keycode = keyentry & MATRIX_KEY_MASK;
unsigned short dev = keyentry >> MATRIX_CODE_BITS;
if (pressed != test_bit(keycode, kp->input_devs->dev[dev]->key)) {
if (keycode == KEY_RESERVED) {
if (mi->flags & GPIOKPF_PRINT_UNMAPPED_KEYS)
pr_info("gpiomatrix: unmapped key, %d-%d "
"(%d-%d) changed to %d\n",
out, in, mi->output_gpios[out],
mi->input_gpios[in], pressed);
} else {
if (mi->flags & GPIOKPF_PRINT_MAPPED_KEYS)
pr_info("gpiomatrix: key %x, %d-%d (%d-%d) "
"changed to %d\n", keycode,
out, in, mi->output_gpios[out],
mi->input_gpios[in], pressed);
input_report_key(kp->input_devs->dev[dev], keycode, pressed);
}
}
}
static void report_sync(struct gpio_kp *kp)
{
int i;
for (i = 0; i < kp->input_devs->count; i++)
input_sync(kp->input_devs->dev[i]);
}
static enum hrtimer_restart gpio_keypad_timer_func(struct hrtimer *timer)
{
int out, in;
int key_index;
int gpio;
struct gpio_kp *kp = container_of(timer, struct gpio_kp, timer);
struct gpio_event_matrix_info *mi = kp->keypad_info;
unsigned gpio_keypad_flags = mi->flags;
unsigned polarity = !!(gpio_keypad_flags & GPIOKPF_ACTIVE_HIGH);
out = kp->current_output;
if (out == mi->noutputs) {
out = 0;
kp->last_key_state_changed = kp->key_state_changed;
kp->key_state_changed = 0;
kp->some_keys_pressed = 0;
} else {
key_index = out * mi->ninputs;
for (in = 0; in < mi->ninputs; in++, key_index++) {
gpio = mi->input_gpios[in];
if (gpio_get_value(gpio) ^ !polarity) {
if (kp->some_keys_pressed < 3)
kp->some_keys_pressed++;
kp->key_state_changed |= !__test_and_set_bit(
key_index, kp->keys_pressed);
} else
kp->key_state_changed |= __test_and_clear_bit(
key_index, kp->keys_pressed);
}
gpio = mi->output_gpios[out];
if (gpio_keypad_flags & GPIOKPF_DRIVE_INACTIVE)
gpio_set_value(gpio, !polarity);
else
gpio_direction_input(gpio);
out++;
}
kp->current_output = out;
if (out < mi->noutputs) {
gpio = mi->output_gpios[out];
if (gpio_keypad_flags & GPIOKPF_DRIVE_INACTIVE)
gpio_set_value(gpio, polarity);
else
gpio_direction_output(gpio, polarity);
hrtimer_start(timer, mi->settle_time, HRTIMER_MODE_REL);
return HRTIMER_NORESTART;
}
if (gpio_keypad_flags & GPIOKPF_DEBOUNCE) {
if (kp->key_state_changed) {
hrtimer_start(&kp->timer, mi->debounce_delay,
HRTIMER_MODE_REL);
return HRTIMER_NORESTART;
}
kp->key_state_changed = kp->last_key_state_changed;
}
if (kp->key_state_changed) {
if (gpio_keypad_flags & GPIOKPF_REMOVE_SOME_PHANTOM_KEYS)
remove_phantom_keys(kp);
key_index = 0;
for (out = 0; out < mi->noutputs; out++)
for (in = 0; in < mi->ninputs; in++, key_index++)
report_key(kp, key_index, out, in);
report_sync(kp);
}
if (!kp->use_irq || kp->some_keys_pressed) {
hrtimer_start(timer, mi->poll_time, HRTIMER_MODE_REL);
return HRTIMER_NORESTART;
}
/* No keys are pressed, reenable interrupt */
for (out = 0; out < mi->noutputs; out++) {
if (gpio_keypad_flags & GPIOKPF_DRIVE_INACTIVE)
gpio_set_value(mi->output_gpios[out], polarity);
else
gpio_direction_output(mi->output_gpios[out], polarity);
}
for (in = 0; in < mi->ninputs; in++)
enable_irq(gpio_to_irq(mi->input_gpios[in]));
wake_unlock(&kp->wake_lock);
return HRTIMER_NORESTART;
}
static irqreturn_t gpio_keypad_irq_handler(int irq_in, void *dev_id)
{
int i;
struct gpio_kp *kp = dev_id;
struct gpio_event_matrix_info *mi = kp->keypad_info;
unsigned gpio_keypad_flags = mi->flags;
if (!kp->use_irq) {
/* ignore interrupt while registering the handler */
kp->disabled_irq = 1;
disable_irq_nosync(irq_in);
return IRQ_HANDLED;
}
for (i = 0; i < mi->ninputs; i++)
disable_irq_nosync(gpio_to_irq(mi->input_gpios[i]));
for (i = 0; i < mi->noutputs; i++) {
if (gpio_keypad_flags & GPIOKPF_DRIVE_INACTIVE)
gpio_set_value(mi->output_gpios[i],
!(gpio_keypad_flags & GPIOKPF_ACTIVE_HIGH));
else
gpio_direction_input(mi->output_gpios[i]);
}
wake_lock(&kp->wake_lock);
hrtimer_start(&kp->timer, ktime_set(0, 0), HRTIMER_MODE_REL);
return IRQ_HANDLED;
}
static int gpio_keypad_request_irqs(struct gpio_kp *kp)
{
int i;
int err;
unsigned int irq;
unsigned long request_flags;
struct gpio_event_matrix_info *mi = kp->keypad_info;
switch (mi->flags & (GPIOKPF_ACTIVE_HIGH|GPIOKPF_LEVEL_TRIGGERED_IRQ)) {
default:
request_flags = IRQF_TRIGGER_FALLING;
break;
case GPIOKPF_ACTIVE_HIGH:
request_flags = IRQF_TRIGGER_RISING;
break;
case GPIOKPF_LEVEL_TRIGGERED_IRQ:
request_flags = IRQF_TRIGGER_LOW;
break;
case GPIOKPF_LEVEL_TRIGGERED_IRQ | GPIOKPF_ACTIVE_HIGH:
request_flags = IRQF_TRIGGER_HIGH;
break;
}
for (i = 0; i < mi->ninputs; i++) {
err = irq = gpio_to_irq(mi->input_gpios[i]);
if (err < 0)
goto err_gpio_get_irq_num_failed;
err = request_irq(irq, gpio_keypad_irq_handler, request_flags,
"gpio_kp", kp);
if (err) {
pr_err("gpiomatrix: request_irq failed for input %d, "
"irq %d\n", mi->input_gpios[i], irq);
goto err_request_irq_failed;
}
err = enable_irq_wake(irq);
if (err) {
pr_err("gpiomatrix: set_irq_wake failed for input %d, "
"irq %d\n", mi->input_gpios[i], irq);
}
disable_irq(irq);
if (kp->disabled_irq) {
kp->disabled_irq = 0;
enable_irq(irq);
}
}
return 0;
for (i = mi->noutputs - 1; i >= 0; i--) {
free_irq(gpio_to_irq(mi->input_gpios[i]), kp);
err_request_irq_failed:
err_gpio_get_irq_num_failed:
;
}
return err;
}
int gpio_event_matrix_func(struct gpio_event_input_devs *input_devs,
struct gpio_event_info *info, void **data, int func)
{
int i;
int err;
int key_count;
struct gpio_kp *kp;
struct gpio_event_matrix_info *mi;
mi = container_of(info, struct gpio_event_matrix_info, info);
if (func == GPIO_EVENT_FUNC_SUSPEND || func == GPIO_EVENT_FUNC_RESUME) {
/* TODO: disable scanning */
return 0;
}
if (func == GPIO_EVENT_FUNC_INIT) {
if (mi->keymap == NULL ||
mi->input_gpios == NULL ||
mi->output_gpios == NULL) {
err = -ENODEV;
pr_err("gpiomatrix: Incomplete pdata\n");
goto err_invalid_platform_data;
}
key_count = mi->ninputs * mi->noutputs;
*data = kp = kzalloc(sizeof(*kp) + sizeof(kp->keys_pressed[0]) *
BITS_TO_LONGS(key_count), GFP_KERNEL);
if (kp == NULL) {
err = -ENOMEM;
pr_err("gpiomatrix: Failed to allocate private data\n");
goto err_kp_alloc_failed;
}
kp->input_devs = input_devs;
kp->keypad_info = mi;
for (i = 0; i < key_count; i++) {
unsigned short keyentry = mi->keymap[i];
unsigned short keycode = keyentry & MATRIX_KEY_MASK;
unsigned short dev = keyentry >> MATRIX_CODE_BITS;
if (dev >= input_devs->count) {
pr_err("gpiomatrix: bad device index %d >= "
"%d for key code %d\n",
dev, input_devs->count, keycode);
err = -EINVAL;
goto err_bad_keymap;
}
if (keycode && keycode <= KEY_MAX)
input_set_capability(input_devs->dev[dev],
EV_KEY, keycode);
}
for (i = 0; i < mi->noutputs; i++) {
err = gpio_request(mi->output_gpios[i], "gpio_kp_out");
if (err) {
pr_err("gpiomatrix: gpio_request failed for "
"output %d\n", mi->output_gpios[i]);
goto err_request_output_gpio_failed;
}
if (gpio_cansleep(mi->output_gpios[i])) {
pr_err("gpiomatrix: unsupported output gpio %d,"
" can sleep\n", mi->output_gpios[i]);
err = -EINVAL;
goto err_output_gpio_configure_failed;
}
if (mi->flags & GPIOKPF_DRIVE_INACTIVE)
err = gpio_direction_output(mi->output_gpios[i],
!(mi->flags & GPIOKPF_ACTIVE_HIGH));
else
err = gpio_direction_input(mi->output_gpios[i]);
if (err) {
pr_err("gpiomatrix: gpio_configure failed for "
"output %d\n", mi->output_gpios[i]);
goto err_output_gpio_configure_failed;
}
}
for (i = 0; i < mi->ninputs; i++) {
err = gpio_request(mi->input_gpios[i], "gpio_kp_in");
if (err) {
pr_err("gpiomatrix: gpio_request failed for "
"input %d\n", mi->input_gpios[i]);
goto err_request_input_gpio_failed;
}
err = gpio_direction_input(mi->input_gpios[i]);
if (err) {
pr_err("gpiomatrix: gpio_direction_input failed"
" for input %d\n", mi->input_gpios[i]);
goto err_gpio_direction_input_failed;
}
}
kp->current_output = mi->noutputs;
kp->key_state_changed = 1;
hrtimer_init(&kp->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
kp->timer.function = gpio_keypad_timer_func;
wake_lock_init(&kp->wake_lock, WAKE_LOCK_SUSPEND, "gpio_kp");
err = gpio_keypad_request_irqs(kp);
kp->use_irq = err == 0;
pr_info("GPIO Matrix Keypad Driver: Start keypad matrix for "
"%s%s in %s mode\n", input_devs->dev[0]->name,
(input_devs->count > 1) ? "..." : "",
kp->use_irq ? "interrupt" : "polling");
if (kp->use_irq)
wake_lock(&kp->wake_lock);
hrtimer_start(&kp->timer, ktime_set(0, 0), HRTIMER_MODE_REL);
return 0;
}
err = 0;
kp = *data;
if (kp->use_irq)
for (i = mi->noutputs - 1; i >= 0; i--)
free_irq(gpio_to_irq(mi->input_gpios[i]), kp);
hrtimer_cancel(&kp->timer);
wake_lock_destroy(&kp->wake_lock);
for (i = mi->noutputs - 1; i >= 0; i--) {
err_gpio_direction_input_failed:
gpio_free(mi->input_gpios[i]);
err_request_input_gpio_failed:
;
}
for (i = mi->noutputs - 1; i >= 0; i--) {
err_output_gpio_configure_failed:
gpio_free(mi->output_gpios[i]);
err_request_output_gpio_failed:
;
}
err_bad_keymap:
kfree(kp);
err_kp_alloc_failed:
err_invalid_platform_data:
return err;
}
| gpl-2.0 |
charles1018/kernel_sony_14.4.A.0.157 | sound/pci/ctxfi/cttimer.c | 8320 | 11344 | /*
* PCM timer handling on ctxfi
*
* This source file is released under GPL v2 license (no other versions).
* See the COPYING file included in the main directory of this source
* distribution for the license terms and conditions.
*/
#include <linux/slab.h>
#include <linux/math64.h>
#include <linux/moduleparam.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include "ctatc.h"
#include "cthardware.h"
#include "cttimer.h"
static bool use_system_timer;
MODULE_PARM_DESC(use_system_timer, "Force to use system-timer");
module_param(use_system_timer, bool, S_IRUGO);
struct ct_timer_ops {
void (*init)(struct ct_timer_instance *);
void (*prepare)(struct ct_timer_instance *);
void (*start)(struct ct_timer_instance *);
void (*stop)(struct ct_timer_instance *);
void (*free_instance)(struct ct_timer_instance *);
void (*interrupt)(struct ct_timer *);
void (*free_global)(struct ct_timer *);
};
/* timer instance -- assigned to each PCM stream */
struct ct_timer_instance {
spinlock_t lock;
struct ct_timer *timer_base;
struct ct_atc_pcm *apcm;
struct snd_pcm_substream *substream;
struct timer_list timer;
struct list_head instance_list;
struct list_head running_list;
unsigned int position;
unsigned int frag_count;
unsigned int running:1;
unsigned int need_update:1;
};
/* timer instance manager */
struct ct_timer {
spinlock_t lock; /* global timer lock (for xfitimer) */
spinlock_t list_lock; /* lock for instance list */
struct ct_atc *atc;
struct ct_timer_ops *ops;
struct list_head instance_head;
struct list_head running_head;
unsigned int wc; /* current wallclock */
unsigned int irq_handling:1; /* in IRQ handling */
unsigned int reprogram:1; /* need to reprogram the internval */
unsigned int running:1; /* global timer running */
};
/*
* system-timer-based updates
*/
static void ct_systimer_callback(unsigned long data)
{
struct ct_timer_instance *ti = (struct ct_timer_instance *)data;
struct snd_pcm_substream *substream = ti->substream;
struct snd_pcm_runtime *runtime = substream->runtime;
struct ct_atc_pcm *apcm = ti->apcm;
unsigned int period_size = runtime->period_size;
unsigned int buffer_size = runtime->buffer_size;
unsigned long flags;
unsigned int position, dist, interval;
position = substream->ops->pointer(substream);
dist = (position + buffer_size - ti->position) % buffer_size;
if (dist >= period_size ||
position / period_size != ti->position / period_size) {
apcm->interrupt(apcm);
ti->position = position;
}
/* Add extra HZ*5/1000 to avoid overrun issue when recording
* at 8kHz in 8-bit format or at 88kHz in 24-bit format. */
interval = ((period_size - (position % period_size))
* HZ + (runtime->rate - 1)) / runtime->rate + HZ * 5 / 1000;
spin_lock_irqsave(&ti->lock, flags);
if (ti->running)
mod_timer(&ti->timer, jiffies + interval);
spin_unlock_irqrestore(&ti->lock, flags);
}
static void ct_systimer_init(struct ct_timer_instance *ti)
{
setup_timer(&ti->timer, ct_systimer_callback,
(unsigned long)ti);
}
static void ct_systimer_start(struct ct_timer_instance *ti)
{
struct snd_pcm_runtime *runtime = ti->substream->runtime;
unsigned long flags;
spin_lock_irqsave(&ti->lock, flags);
ti->running = 1;
mod_timer(&ti->timer,
jiffies + (runtime->period_size * HZ +
(runtime->rate - 1)) / runtime->rate);
spin_unlock_irqrestore(&ti->lock, flags);
}
static void ct_systimer_stop(struct ct_timer_instance *ti)
{
unsigned long flags;
spin_lock_irqsave(&ti->lock, flags);
ti->running = 0;
del_timer(&ti->timer);
spin_unlock_irqrestore(&ti->lock, flags);
}
static void ct_systimer_prepare(struct ct_timer_instance *ti)
{
ct_systimer_stop(ti);
try_to_del_timer_sync(&ti->timer);
}
#define ct_systimer_free ct_systimer_prepare
static struct ct_timer_ops ct_systimer_ops = {
.init = ct_systimer_init,
.free_instance = ct_systimer_free,
.prepare = ct_systimer_prepare,
.start = ct_systimer_start,
.stop = ct_systimer_stop,
};
/*
* Handling multiple streams using a global emu20k1 timer irq
*/
#define CT_TIMER_FREQ 48000
#define MIN_TICKS 1
#define MAX_TICKS ((1 << 13) - 1)
static void ct_xfitimer_irq_rearm(struct ct_timer *atimer, int ticks)
{
struct hw *hw = atimer->atc->hw;
if (ticks > MAX_TICKS)
ticks = MAX_TICKS;
hw->set_timer_tick(hw, ticks);
if (!atimer->running)
hw->set_timer_irq(hw, 1);
atimer->running = 1;
}
static void ct_xfitimer_irq_stop(struct ct_timer *atimer)
{
if (atimer->running) {
struct hw *hw = atimer->atc->hw;
hw->set_timer_irq(hw, 0);
hw->set_timer_tick(hw, 0);
atimer->running = 0;
}
}
static inline unsigned int ct_xfitimer_get_wc(struct ct_timer *atimer)
{
struct hw *hw = atimer->atc->hw;
return hw->get_wc(hw);
}
/*
* reprogram the timer interval;
* checks the running instance list and determines the next timer interval.
* also updates the each stream position, returns the number of streams
* to call snd_pcm_period_elapsed() appropriately
*
* call this inside the lock and irq disabled
*/
static int ct_xfitimer_reprogram(struct ct_timer *atimer, int can_update)
{
struct ct_timer_instance *ti;
unsigned int min_intr = (unsigned int)-1;
int updates = 0;
unsigned int wc, diff;
if (list_empty(&atimer->running_head)) {
ct_xfitimer_irq_stop(atimer);
atimer->reprogram = 0; /* clear flag */
return 0;
}
wc = ct_xfitimer_get_wc(atimer);
diff = wc - atimer->wc;
atimer->wc = wc;
list_for_each_entry(ti, &atimer->running_head, running_list) {
if (ti->frag_count > diff)
ti->frag_count -= diff;
else {
unsigned int pos;
unsigned int period_size, rate;
period_size = ti->substream->runtime->period_size;
rate = ti->substream->runtime->rate;
pos = ti->substream->ops->pointer(ti->substream);
if (pos / period_size != ti->position / period_size) {
ti->need_update = 1;
ti->position = pos;
updates++;
}
pos %= period_size;
pos = period_size - pos;
ti->frag_count = div_u64((u64)pos * CT_TIMER_FREQ +
rate - 1, rate);
}
if (ti->need_update && !can_update)
min_intr = 0; /* pending to the next irq */
if (ti->frag_count < min_intr)
min_intr = ti->frag_count;
}
if (min_intr < MIN_TICKS)
min_intr = MIN_TICKS;
ct_xfitimer_irq_rearm(atimer, min_intr);
atimer->reprogram = 0; /* clear flag */
return updates;
}
/* look through the instance list and call period_elapsed if needed */
static void ct_xfitimer_check_period(struct ct_timer *atimer)
{
struct ct_timer_instance *ti;
unsigned long flags;
spin_lock_irqsave(&atimer->list_lock, flags);
list_for_each_entry(ti, &atimer->instance_head, instance_list) {
if (ti->running && ti->need_update) {
ti->need_update = 0;
ti->apcm->interrupt(ti->apcm);
}
}
spin_unlock_irqrestore(&atimer->list_lock, flags);
}
/* Handle timer-interrupt */
static void ct_xfitimer_callback(struct ct_timer *atimer)
{
int update;
unsigned long flags;
spin_lock_irqsave(&atimer->lock, flags);
atimer->irq_handling = 1;
do {
update = ct_xfitimer_reprogram(atimer, 1);
spin_unlock(&atimer->lock);
if (update)
ct_xfitimer_check_period(atimer);
spin_lock(&atimer->lock);
} while (atimer->reprogram);
atimer->irq_handling = 0;
spin_unlock_irqrestore(&atimer->lock, flags);
}
static void ct_xfitimer_prepare(struct ct_timer_instance *ti)
{
ti->frag_count = ti->substream->runtime->period_size;
ti->running = 0;
ti->need_update = 0;
}
/* start/stop the timer */
static void ct_xfitimer_update(struct ct_timer *atimer)
{
unsigned long flags;
spin_lock_irqsave(&atimer->lock, flags);
if (atimer->irq_handling) {
/* reached from IRQ handler; let it handle later */
atimer->reprogram = 1;
spin_unlock_irqrestore(&atimer->lock, flags);
return;
}
ct_xfitimer_irq_stop(atimer);
ct_xfitimer_reprogram(atimer, 0);
spin_unlock_irqrestore(&atimer->lock, flags);
}
static void ct_xfitimer_start(struct ct_timer_instance *ti)
{
struct ct_timer *atimer = ti->timer_base;
unsigned long flags;
spin_lock_irqsave(&atimer->lock, flags);
if (list_empty(&ti->running_list))
atimer->wc = ct_xfitimer_get_wc(atimer);
ti->running = 1;
ti->need_update = 0;
list_add(&ti->running_list, &atimer->running_head);
spin_unlock_irqrestore(&atimer->lock, flags);
ct_xfitimer_update(atimer);
}
static void ct_xfitimer_stop(struct ct_timer_instance *ti)
{
struct ct_timer *atimer = ti->timer_base;
unsigned long flags;
spin_lock_irqsave(&atimer->lock, flags);
list_del_init(&ti->running_list);
ti->running = 0;
spin_unlock_irqrestore(&atimer->lock, flags);
ct_xfitimer_update(atimer);
}
static void ct_xfitimer_free_global(struct ct_timer *atimer)
{
ct_xfitimer_irq_stop(atimer);
}
static struct ct_timer_ops ct_xfitimer_ops = {
.prepare = ct_xfitimer_prepare,
.start = ct_xfitimer_start,
.stop = ct_xfitimer_stop,
.interrupt = ct_xfitimer_callback,
.free_global = ct_xfitimer_free_global,
};
/*
* timer instance
*/
struct ct_timer_instance *
ct_timer_instance_new(struct ct_timer *atimer, struct ct_atc_pcm *apcm)
{
struct ct_timer_instance *ti;
ti = kzalloc(sizeof(*ti), GFP_KERNEL);
if (!ti)
return NULL;
spin_lock_init(&ti->lock);
INIT_LIST_HEAD(&ti->instance_list);
INIT_LIST_HEAD(&ti->running_list);
ti->timer_base = atimer;
ti->apcm = apcm;
ti->substream = apcm->substream;
if (atimer->ops->init)
atimer->ops->init(ti);
spin_lock_irq(&atimer->list_lock);
list_add(&ti->instance_list, &atimer->instance_head);
spin_unlock_irq(&atimer->list_lock);
return ti;
}
void ct_timer_prepare(struct ct_timer_instance *ti)
{
if (ti->timer_base->ops->prepare)
ti->timer_base->ops->prepare(ti);
ti->position = 0;
ti->running = 0;
}
void ct_timer_start(struct ct_timer_instance *ti)
{
struct ct_timer *atimer = ti->timer_base;
atimer->ops->start(ti);
}
void ct_timer_stop(struct ct_timer_instance *ti)
{
struct ct_timer *atimer = ti->timer_base;
atimer->ops->stop(ti);
}
void ct_timer_instance_free(struct ct_timer_instance *ti)
{
struct ct_timer *atimer = ti->timer_base;
atimer->ops->stop(ti); /* to be sure */
if (atimer->ops->free_instance)
atimer->ops->free_instance(ti);
spin_lock_irq(&atimer->list_lock);
list_del(&ti->instance_list);
spin_unlock_irq(&atimer->list_lock);
kfree(ti);
}
/*
* timer manager
*/
static void ct_timer_interrupt(void *data, unsigned int status)
{
struct ct_timer *timer = data;
/* Interval timer interrupt */
if ((status & IT_INT) && timer->ops->interrupt)
timer->ops->interrupt(timer);
}
struct ct_timer *ct_timer_new(struct ct_atc *atc)
{
struct ct_timer *atimer;
struct hw *hw;
atimer = kzalloc(sizeof(*atimer), GFP_KERNEL);
if (!atimer)
return NULL;
spin_lock_init(&atimer->lock);
spin_lock_init(&atimer->list_lock);
INIT_LIST_HEAD(&atimer->instance_head);
INIT_LIST_HEAD(&atimer->running_head);
atimer->atc = atc;
hw = atc->hw;
if (!use_system_timer && hw->set_timer_irq) {
snd_printd(KERN_INFO "ctxfi: Use xfi-native timer\n");
atimer->ops = &ct_xfitimer_ops;
hw->irq_callback_data = atimer;
hw->irq_callback = ct_timer_interrupt;
} else {
snd_printd(KERN_INFO "ctxfi: Use system timer\n");
atimer->ops = &ct_systimer_ops;
}
return atimer;
}
void ct_timer_free(struct ct_timer *atimer)
{
struct hw *hw = atimer->atc->hw;
hw->irq_callback = NULL;
if (atimer->ops->free_global)
atimer->ops->free_global(atimer);
kfree(atimer);
}
| gpl-2.0 |
tadeas482/kernel-old | drivers/isdn/capi/capilib.c | 9600 | 4630 |
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/isdn/capilli.h>
#define DBG(format, arg...) do { \
printk(KERN_DEBUG "%s: " format "\n" , __func__ , ## arg); \
} while (0)
struct capilib_msgidqueue {
struct capilib_msgidqueue *next;
u16 msgid;
};
struct capilib_ncci {
struct list_head list;
u16 applid;
u32 ncci;
u32 winsize;
int nmsg;
struct capilib_msgidqueue *msgidqueue;
struct capilib_msgidqueue *msgidlast;
struct capilib_msgidqueue *msgidfree;
struct capilib_msgidqueue msgidpool[CAPI_MAXDATAWINDOW];
};
// ---------------------------------------------------------------------------
// NCCI Handling
static inline void mq_init(struct capilib_ncci *np)
{
u_int i;
np->msgidqueue = NULL;
np->msgidlast = NULL;
np->nmsg = 0;
memset(np->msgidpool, 0, sizeof(np->msgidpool));
np->msgidfree = &np->msgidpool[0];
for (i = 1; i < np->winsize; i++) {
np->msgidpool[i].next = np->msgidfree;
np->msgidfree = &np->msgidpool[i];
}
}
static inline int mq_enqueue(struct capilib_ncci *np, u16 msgid)
{
struct capilib_msgidqueue *mq;
if ((mq = np->msgidfree) == NULL)
return 0;
np->msgidfree = mq->next;
mq->msgid = msgid;
mq->next = NULL;
if (np->msgidlast)
np->msgidlast->next = mq;
np->msgidlast = mq;
if (!np->msgidqueue)
np->msgidqueue = mq;
np->nmsg++;
return 1;
}
static inline int mq_dequeue(struct capilib_ncci *np, u16 msgid)
{
struct capilib_msgidqueue **pp;
for (pp = &np->msgidqueue; *pp; pp = &(*pp)->next) {
if ((*pp)->msgid == msgid) {
struct capilib_msgidqueue *mq = *pp;
*pp = mq->next;
if (mq == np->msgidlast)
np->msgidlast = NULL;
mq->next = np->msgidfree;
np->msgidfree = mq;
np->nmsg--;
return 1;
}
}
return 0;
}
void capilib_new_ncci(struct list_head *head, u16 applid, u32 ncci, u32 winsize)
{
struct capilib_ncci *np;
np = kmalloc(sizeof(*np), GFP_ATOMIC);
if (!np) {
printk(KERN_WARNING "capilib_new_ncci: no memory.\n");
return;
}
if (winsize > CAPI_MAXDATAWINDOW) {
printk(KERN_ERR "capi_new_ncci: winsize %d too big\n",
winsize);
winsize = CAPI_MAXDATAWINDOW;
}
np->applid = applid;
np->ncci = ncci;
np->winsize = winsize;
mq_init(np);
list_add_tail(&np->list, head);
DBG("kcapi: appl %d ncci 0x%x up", applid, ncci);
}
EXPORT_SYMBOL(capilib_new_ncci);
void capilib_free_ncci(struct list_head *head, u16 applid, u32 ncci)
{
struct list_head *l;
struct capilib_ncci *np;
list_for_each(l, head) {
np = list_entry(l, struct capilib_ncci, list);
if (np->applid != applid)
continue;
if (np->ncci != ncci)
continue;
printk(KERN_INFO "kcapi: appl %d ncci 0x%x down\n", applid, ncci);
list_del(&np->list);
kfree(np);
return;
}
printk(KERN_ERR "capilib_free_ncci: ncci 0x%x not found\n", ncci);
}
EXPORT_SYMBOL(capilib_free_ncci);
void capilib_release_appl(struct list_head *head, u16 applid)
{
struct list_head *l, *n;
struct capilib_ncci *np;
list_for_each_safe(l, n, head) {
np = list_entry(l, struct capilib_ncci, list);
if (np->applid != applid)
continue;
printk(KERN_INFO "kcapi: appl %d ncci 0x%x forced down\n", applid, np->ncci);
list_del(&np->list);
kfree(np);
}
}
EXPORT_SYMBOL(capilib_release_appl);
void capilib_release(struct list_head *head)
{
struct list_head *l, *n;
struct capilib_ncci *np;
list_for_each_safe(l, n, head) {
np = list_entry(l, struct capilib_ncci, list);
printk(KERN_INFO "kcapi: appl %d ncci 0x%x forced down\n", np->applid, np->ncci);
list_del(&np->list);
kfree(np);
}
}
EXPORT_SYMBOL(capilib_release);
u16 capilib_data_b3_req(struct list_head *head, u16 applid, u32 ncci, u16 msgid)
{
struct list_head *l;
struct capilib_ncci *np;
list_for_each(l, head) {
np = list_entry(l, struct capilib_ncci, list);
if (np->applid != applid)
continue;
if (np->ncci != ncci)
continue;
if (mq_enqueue(np, msgid) == 0)
return CAPI_SENDQUEUEFULL;
return CAPI_NOERROR;
}
printk(KERN_ERR "capilib_data_b3_req: ncci 0x%x not found\n", ncci);
return CAPI_NOERROR;
}
EXPORT_SYMBOL(capilib_data_b3_req);
void capilib_data_b3_conf(struct list_head *head, u16 applid, u32 ncci, u16 msgid)
{
struct list_head *l;
struct capilib_ncci *np;
list_for_each(l, head) {
np = list_entry(l, struct capilib_ncci, list);
if (np->applid != applid)
continue;
if (np->ncci != ncci)
continue;
if (mq_dequeue(np, msgid) == 0) {
printk(KERN_ERR "kcapi: msgid %hu ncci 0x%x not on queue\n",
msgid, ncci);
}
return;
}
printk(KERN_ERR "capilib_data_b3_conf: ncci 0x%x not found\n", ncci);
}
EXPORT_SYMBOL(capilib_data_b3_conf);
| gpl-2.0 |
JTdevAndroid/XKernel | arch/sh/mm/tlb-pteaex.c | 9856 | 2803 | /*
* arch/sh/mm/tlb-pteaex.c
*
* TLB operations for SH-X3 CPUs featuring PTE ASID Extensions.
*
* Copyright (C) 2009 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/kernel.h>
#include <linux/mm.h>
#include <linux/io.h>
#include <asm/mmu_context.h>
#include <asm/cacheflush.h>
void __update_tlb(struct vm_area_struct *vma, unsigned long address, pte_t pte)
{
unsigned long flags, pteval, vpn;
/*
* Handle debugger faulting in for debugee.
*/
if (vma && current->active_mm != vma->vm_mm)
return;
local_irq_save(flags);
/* Set PTEH register */
vpn = address & MMU_VPN_MASK;
__raw_writel(vpn, MMU_PTEH);
/* Set PTEAEX */
__raw_writel(get_asid(), MMU_PTEAEX);
pteval = pte.pte_low;
/* Set PTEA register */
#ifdef CONFIG_X2TLB
/*
* For the extended mode TLB this is trivial, only the ESZ and
* EPR bits need to be written out to PTEA, with the remainder of
* the protection bits (with the exception of the compat-mode SZ
* and PR bits, which are cleared) being written out in PTEL.
*/
__raw_writel(pte.pte_high, MMU_PTEA);
#endif
/* Set PTEL register */
pteval &= _PAGE_FLAGS_HARDWARE_MASK; /* drop software flags */
#ifdef CONFIG_CACHE_WRITETHROUGH
pteval |= _PAGE_WT;
#endif
/* conveniently, we want all the software flags to be 0 anyway */
__raw_writel(pteval, MMU_PTEL);
/* Load the TLB */
asm volatile("ldtlb": /* no output */ : /* no input */ : "memory");
local_irq_restore(flags);
}
/*
* While SH-X2 extended TLB mode splits out the memory-mapped I/UTLB
* data arrays, SH-X3 cores with PTEAEX split out the memory-mapped
* address arrays. In compat mode the second array is inaccessible, while
* in extended mode, the legacy 8-bit ASID field in address array 1 has
* undefined behaviour.
*/
void local_flush_tlb_one(unsigned long asid, unsigned long page)
{
jump_to_uncached();
__raw_writel(page, MMU_UTLB_ADDRESS_ARRAY | MMU_PAGE_ASSOC_BIT);
__raw_writel(asid, MMU_UTLB_ADDRESS_ARRAY2 | MMU_PAGE_ASSOC_BIT);
__raw_writel(page, MMU_ITLB_ADDRESS_ARRAY | MMU_PAGE_ASSOC_BIT);
__raw_writel(asid, MMU_ITLB_ADDRESS_ARRAY2 | MMU_PAGE_ASSOC_BIT);
back_to_cached();
}
void local_flush_tlb_all(void)
{
unsigned long flags, status;
int i;
/*
* Flush all the TLB.
*/
local_irq_save(flags);
jump_to_uncached();
status = __raw_readl(MMUCR);
status = ((status & MMUCR_URB) >> MMUCR_URB_SHIFT);
if (status == 0)
status = MMUCR_URB_NENTRIES;
for (i = 0; i < status; i++)
__raw_writel(0x0, MMU_UTLB_ADDRESS_ARRAY | (i << 8));
for (i = 0; i < 4; i++)
__raw_writel(0x0, MMU_ITLB_ADDRESS_ARRAY | (i << 8));
back_to_cached();
ctrl_barrier();
local_irq_restore(flags);
}
| gpl-2.0 |
tobigun/samsung-kernel-smg800f | arch/sh/mm/tlb-pteaex.c | 9856 | 2803 | /*
* arch/sh/mm/tlb-pteaex.c
*
* TLB operations for SH-X3 CPUs featuring PTE ASID Extensions.
*
* Copyright (C) 2009 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/kernel.h>
#include <linux/mm.h>
#include <linux/io.h>
#include <asm/mmu_context.h>
#include <asm/cacheflush.h>
void __update_tlb(struct vm_area_struct *vma, unsigned long address, pte_t pte)
{
unsigned long flags, pteval, vpn;
/*
* Handle debugger faulting in for debugee.
*/
if (vma && current->active_mm != vma->vm_mm)
return;
local_irq_save(flags);
/* Set PTEH register */
vpn = address & MMU_VPN_MASK;
__raw_writel(vpn, MMU_PTEH);
/* Set PTEAEX */
__raw_writel(get_asid(), MMU_PTEAEX);
pteval = pte.pte_low;
/* Set PTEA register */
#ifdef CONFIG_X2TLB
/*
* For the extended mode TLB this is trivial, only the ESZ and
* EPR bits need to be written out to PTEA, with the remainder of
* the protection bits (with the exception of the compat-mode SZ
* and PR bits, which are cleared) being written out in PTEL.
*/
__raw_writel(pte.pte_high, MMU_PTEA);
#endif
/* Set PTEL register */
pteval &= _PAGE_FLAGS_HARDWARE_MASK; /* drop software flags */
#ifdef CONFIG_CACHE_WRITETHROUGH
pteval |= _PAGE_WT;
#endif
/* conveniently, we want all the software flags to be 0 anyway */
__raw_writel(pteval, MMU_PTEL);
/* Load the TLB */
asm volatile("ldtlb": /* no output */ : /* no input */ : "memory");
local_irq_restore(flags);
}
/*
* While SH-X2 extended TLB mode splits out the memory-mapped I/UTLB
* data arrays, SH-X3 cores with PTEAEX split out the memory-mapped
* address arrays. In compat mode the second array is inaccessible, while
* in extended mode, the legacy 8-bit ASID field in address array 1 has
* undefined behaviour.
*/
void local_flush_tlb_one(unsigned long asid, unsigned long page)
{
jump_to_uncached();
__raw_writel(page, MMU_UTLB_ADDRESS_ARRAY | MMU_PAGE_ASSOC_BIT);
__raw_writel(asid, MMU_UTLB_ADDRESS_ARRAY2 | MMU_PAGE_ASSOC_BIT);
__raw_writel(page, MMU_ITLB_ADDRESS_ARRAY | MMU_PAGE_ASSOC_BIT);
__raw_writel(asid, MMU_ITLB_ADDRESS_ARRAY2 | MMU_PAGE_ASSOC_BIT);
back_to_cached();
}
void local_flush_tlb_all(void)
{
unsigned long flags, status;
int i;
/*
* Flush all the TLB.
*/
local_irq_save(flags);
jump_to_uncached();
status = __raw_readl(MMUCR);
status = ((status & MMUCR_URB) >> MMUCR_URB_SHIFT);
if (status == 0)
status = MMUCR_URB_NENTRIES;
for (i = 0; i < status; i++)
__raw_writel(0x0, MMU_UTLB_ADDRESS_ARRAY | (i << 8));
for (i = 0; i < 4; i++)
__raw_writel(0x0, MMU_ITLB_ADDRESS_ARRAY | (i << 8));
back_to_cached();
ctrl_barrier();
local_irq_restore(flags);
}
| gpl-2.0 |
MSM8226-Samsung/kernel_samsung_msm8226 | drivers/zorro/zorro-sysfs.c | 11648 | 3155 | /*
* File Attributes for Zorro Devices
*
* Copyright (C) 2003 Geert Uytterhoeven
*
* Loosely based on drivers/pci/pci-sysfs.c
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive
* for more details.
*/
#include <linux/kernel.h>
#include <linux/zorro.h>
#include <linux/stat.h>
#include <linux/string.h>
#include "zorro.h"
/* show configuration fields */
#define zorro_config_attr(name, field, format_string) \
static ssize_t \
show_##name(struct device *dev, struct device_attribute *attr, char *buf) \
{ \
struct zorro_dev *z; \
\
z = to_zorro_dev(dev); \
return sprintf(buf, format_string, z->field); \
} \
static DEVICE_ATTR(name, S_IRUGO, show_##name, NULL);
zorro_config_attr(id, id, "0x%08x\n");
zorro_config_attr(type, rom.er_Type, "0x%02x\n");
zorro_config_attr(serial, rom.er_SerialNumber, "0x%08x\n");
zorro_config_attr(slotaddr, slotaddr, "0x%04x\n");
zorro_config_attr(slotsize, slotsize, "0x%04x\n");
static ssize_t zorro_show_resource(struct device *dev, struct device_attribute *attr, char *buf)
{
struct zorro_dev *z = to_zorro_dev(dev);
return sprintf(buf, "0x%08lx 0x%08lx 0x%08lx\n",
(unsigned long)zorro_resource_start(z),
(unsigned long)zorro_resource_end(z),
zorro_resource_flags(z));
}
static DEVICE_ATTR(resource, S_IRUGO, zorro_show_resource, NULL);
static ssize_t zorro_read_config(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct zorro_dev *z = to_zorro_dev(container_of(kobj, struct device,
kobj));
struct ConfigDev cd;
/* Construct a ConfigDev */
memset(&cd, 0, sizeof(cd));
cd.cd_Rom = z->rom;
cd.cd_SlotAddr = z->slotaddr;
cd.cd_SlotSize = z->slotsize;
cd.cd_BoardAddr = (void *)zorro_resource_start(z);
cd.cd_BoardSize = zorro_resource_len(z);
return memory_read_from_buffer(buf, count, &off, &cd, sizeof(cd));
}
static struct bin_attribute zorro_config_attr = {
.attr = {
.name = "config",
.mode = S_IRUGO,
},
.size = sizeof(struct ConfigDev),
.read = zorro_read_config,
};
static ssize_t modalias_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct zorro_dev *z = to_zorro_dev(dev);
return sprintf(buf, ZORRO_DEVICE_MODALIAS_FMT "\n", z->id);
}
static DEVICE_ATTR(modalias, S_IRUGO, modalias_show, NULL);
int zorro_create_sysfs_dev_files(struct zorro_dev *z)
{
struct device *dev = &z->dev;
int error;
/* current configuration's attributes */
if ((error = device_create_file(dev, &dev_attr_id)) ||
(error = device_create_file(dev, &dev_attr_type)) ||
(error = device_create_file(dev, &dev_attr_serial)) ||
(error = device_create_file(dev, &dev_attr_slotaddr)) ||
(error = device_create_file(dev, &dev_attr_slotsize)) ||
(error = device_create_file(dev, &dev_attr_resource)) ||
(error = device_create_file(dev, &dev_attr_modalias)) ||
(error = sysfs_create_bin_file(&dev->kobj, &zorro_config_attr)))
return error;
return 0;
}
| gpl-2.0 |
Nick73/King_Kernel | arch/powerpc/platforms/52xx/mpc52xx_pm.c | 12160 | 5307 | #include <linux/init.h>
#include <linux/suspend.h>
#include <linux/io.h>
#include <asm/time.h>
#include <asm/cacheflush.h>
#include <asm/mpc52xx.h>
/* these are defined in mpc52xx_sleep.S, and only used here */
extern void mpc52xx_deep_sleep(void __iomem *sram, void __iomem *sdram_regs,
struct mpc52xx_cdm __iomem *, struct mpc52xx_intr __iomem*);
extern void mpc52xx_ds_sram(void);
extern const long mpc52xx_ds_sram_size;
extern void mpc52xx_ds_cached(void);
extern const long mpc52xx_ds_cached_size;
static void __iomem *mbar;
static void __iomem *sdram;
static struct mpc52xx_cdm __iomem *cdm;
static struct mpc52xx_intr __iomem *intr;
static struct mpc52xx_gpio_wkup __iomem *gpiow;
static void __iomem *sram;
static int sram_size;
struct mpc52xx_suspend mpc52xx_suspend;
static int mpc52xx_pm_valid(suspend_state_t state)
{
switch (state) {
case PM_SUSPEND_STANDBY:
return 1;
default:
return 0;
}
}
int mpc52xx_set_wakeup_gpio(u8 pin, u8 level)
{
u16 tmp;
/* enable gpio */
out_8(&gpiow->wkup_gpioe, in_8(&gpiow->wkup_gpioe) | (1 << pin));
/* set as input */
out_8(&gpiow->wkup_ddr, in_8(&gpiow->wkup_ddr) & ~(1 << pin));
/* enable deep sleep interrupt */
out_8(&gpiow->wkup_inten, in_8(&gpiow->wkup_inten) | (1 << pin));
/* low/high level creates wakeup interrupt */
tmp = in_be16(&gpiow->wkup_itype);
tmp &= ~(0x3 << (pin * 2));
tmp |= (!level + 1) << (pin * 2);
out_be16(&gpiow->wkup_itype, tmp);
/* master enable */
out_8(&gpiow->wkup_maste, 1);
return 0;
}
int mpc52xx_pm_prepare(void)
{
struct device_node *np;
const struct of_device_id immr_ids[] = {
{ .compatible = "fsl,mpc5200-immr", },
{ .compatible = "fsl,mpc5200b-immr", },
{ .type = "soc", .compatible = "mpc5200", }, /* lite5200 */
{ .type = "builtin", .compatible = "mpc5200", }, /* efika */
{}
};
struct resource res;
/* map the whole register space */
np = of_find_matching_node(NULL, immr_ids);
if (of_address_to_resource(np, 0, &res)) {
pr_err("mpc52xx_pm_prepare(): could not get IMMR address\n");
of_node_put(np);
return -ENOSYS;
}
mbar = ioremap(res.start, 0xc000); /* we should map whole region including SRAM */
of_node_put(np);
if (!mbar) {
pr_err("mpc52xx_pm_prepare(): could not map registers\n");
return -ENOSYS;
}
/* these offsets are from mpc5200 users manual */
sdram = mbar + 0x100;
cdm = mbar + 0x200;
intr = mbar + 0x500;
gpiow = mbar + 0xc00;
sram = mbar + 0x8000; /* Those will be handled by the */
sram_size = 0x4000; /* bestcomm driver soon */
/* call board suspend code, if applicable */
if (mpc52xx_suspend.board_suspend_prepare)
mpc52xx_suspend.board_suspend_prepare(mbar);
else {
printk(KERN_ALERT "%s: %i don't know how to wake up the board\n",
__func__, __LINE__);
goto out_unmap;
}
return 0;
out_unmap:
iounmap(mbar);
return -ENOSYS;
}
char saved_sram[0x4000];
int mpc52xx_pm_enter(suspend_state_t state)
{
u32 clk_enables;
u32 msr, hid0;
u32 intr_main_mask;
void __iomem * irq_0x500 = (void __iomem *)CONFIG_KERNEL_START + 0x500;
unsigned long irq_0x500_stop = (unsigned long)irq_0x500 + mpc52xx_ds_cached_size;
char saved_0x500[mpc52xx_ds_cached_size];
/* disable all interrupts in PIC */
intr_main_mask = in_be32(&intr->main_mask);
out_be32(&intr->main_mask, intr_main_mask | 0x1ffff);
/* don't let DEC expire any time soon */
mtspr(SPRN_DEC, 0x7fffffff);
/* save SRAM */
memcpy(saved_sram, sram, sram_size);
/* copy low level suspend code to sram */
memcpy(sram, mpc52xx_ds_sram, mpc52xx_ds_sram_size);
out_8(&cdm->ccs_sleep_enable, 1);
out_8(&cdm->osc_sleep_enable, 1);
out_8(&cdm->ccs_qreq_test, 1);
/* disable all but SDRAM and bestcomm (SRAM) clocks */
clk_enables = in_be32(&cdm->clk_enables);
out_be32(&cdm->clk_enables, clk_enables & 0x00088000);
/* disable power management */
msr = mfmsr();
mtmsr(msr & ~MSR_POW);
/* enable sleep mode, disable others */
hid0 = mfspr(SPRN_HID0);
mtspr(SPRN_HID0, (hid0 & ~(HID0_DOZE | HID0_NAP | HID0_DPM)) | HID0_SLEEP);
/* save original, copy our irq handler, flush from dcache and invalidate icache */
memcpy(saved_0x500, irq_0x500, mpc52xx_ds_cached_size);
memcpy(irq_0x500, mpc52xx_ds_cached, mpc52xx_ds_cached_size);
flush_icache_range((unsigned long)irq_0x500, irq_0x500_stop);
/* call low-level sleep code */
mpc52xx_deep_sleep(sram, sdram, cdm, intr);
/* restore original irq handler */
memcpy(irq_0x500, saved_0x500, mpc52xx_ds_cached_size);
flush_icache_range((unsigned long)irq_0x500, irq_0x500_stop);
/* restore old power mode */
mtmsr(msr & ~MSR_POW);
mtspr(SPRN_HID0, hid0);
mtmsr(msr);
out_be32(&cdm->clk_enables, clk_enables);
out_8(&cdm->ccs_sleep_enable, 0);
out_8(&cdm->osc_sleep_enable, 0);
/* restore SRAM */
memcpy(sram, saved_sram, sram_size);
/* reenable interrupts in PIC */
out_be32(&intr->main_mask, intr_main_mask);
return 0;
}
void mpc52xx_pm_finish(void)
{
/* call board resume code */
if (mpc52xx_suspend.board_resume_finish)
mpc52xx_suspend.board_resume_finish(mbar);
iounmap(mbar);
}
static const struct platform_suspend_ops mpc52xx_pm_ops = {
.valid = mpc52xx_pm_valid,
.prepare = mpc52xx_pm_prepare,
.enter = mpc52xx_pm_enter,
.finish = mpc52xx_pm_finish,
};
int __init mpc52xx_pm_init(void)
{
suspend_set_ops(&mpc52xx_pm_ops);
return 0;
}
| gpl-2.0 |
hephaex/kernel | kernel/gcov/gcc_4_7.c | 385 | 13558 | /*
* This code provides functions to handle gcc's profiling data format
* introduced with gcc 4.7.
*
* This file is based heavily on gcc_3_4.c file.
*
* For a better understanding, refer to gcc source:
* gcc/gcov-io.h
* libgcc/libgcov.c
*
* Uses gcc-internal data definitions.
*/
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/seq_file.h>
#include <linux/vmalloc.h>
#include "gcov.h"
#define GCOV_COUNTERS 8
#define GCOV_TAG_FUNCTION_LENGTH 3
static struct gcov_info *gcov_info_head;
/**
* struct gcov_ctr_info - information about counters for a single function
* @num: number of counter values for this type
* @values: array of counter values for this type
*
* This data is generated by gcc during compilation and doesn't change
* at run-time with the exception of the values array.
*/
struct gcov_ctr_info {
unsigned int num;
gcov_type *values;
};
/**
* struct gcov_fn_info - profiling meta data per function
* @key: comdat key
* @ident: unique ident of function
* @lineno_checksum: function lineo_checksum
* @cfg_checksum: function cfg checksum
* @ctrs: instrumented counters
*
* This data is generated by gcc during compilation and doesn't change
* at run-time.
*
* Information about a single function. This uses the trailing array
* idiom. The number of counters is determined from the merge pointer
* array in gcov_info. The key is used to detect which of a set of
* comdat functions was selected -- it points to the gcov_info object
* of the object file containing the selected comdat function.
*/
struct gcov_fn_info {
const struct gcov_info *key;
unsigned int ident;
unsigned int lineno_checksum;
unsigned int cfg_checksum;
struct gcov_ctr_info ctrs[0];
};
/**
* struct gcov_info - profiling data per object file
* @version: gcov version magic indicating the gcc version used for compilation
* @next: list head for a singly-linked list
* @stamp: uniquifying time stamp
* @filename: name of the associated gcov data file
* @merge: merge functions (null for unused counter type)
* @n_functions: number of instrumented functions
* @functions: pointer to pointers to function information
*
* This data is generated by gcc during compilation and doesn't change
* at run-time with the exception of the next pointer.
*/
struct gcov_info {
unsigned int version;
struct gcov_info *next;
unsigned int stamp;
const char *filename;
void (*merge[GCOV_COUNTERS])(gcov_type *, unsigned int);
unsigned int n_functions;
struct gcov_fn_info **functions;
};
/**
* gcov_info_filename - return info filename
* @info: profiling data set
*/
const char *gcov_info_filename(struct gcov_info *info)
{
return info->filename;
}
/**
* gcov_info_version - return info version
* @info: profiling data set
*/
unsigned int gcov_info_version(struct gcov_info *info)
{
return info->version;
}
/**
* gcov_info_next - return next profiling data set
* @info: profiling data set
*
* Returns next gcov_info following @info or first gcov_info in the chain if
* @info is %NULL.
*/
struct gcov_info *gcov_info_next(struct gcov_info *info)
{
if (!info)
return gcov_info_head;
return info->next;
}
/**
* gcov_info_link - link/add profiling data set to the list
* @info: profiling data set
*/
void gcov_info_link(struct gcov_info *info)
{
info->next = gcov_info_head;
gcov_info_head = info;
}
/**
* gcov_info_unlink - unlink/remove profiling data set from the list
* @prev: previous profiling data set
* @info: profiling data set
*/
void gcov_info_unlink(struct gcov_info *prev, struct gcov_info *info)
{
if (prev)
prev->next = info->next;
else
gcov_info_head = info->next;
}
/* Symbolic links to be created for each profiling data file. */
const struct gcov_link gcov_link[] = {
{ OBJ_TREE, "gcno" }, /* Link to .gcno file in $(objtree). */
{ 0, NULL},
};
/*
* Determine whether a counter is active. Doesn't change at run-time.
*/
static int counter_active(struct gcov_info *info, unsigned int type)
{
return info->merge[type] ? 1 : 0;
}
/* Determine number of active counters. Based on gcc magic. */
static unsigned int num_counter_active(struct gcov_info *info)
{
unsigned int i;
unsigned int result = 0;
for (i = 0; i < GCOV_COUNTERS; i++) {
if (counter_active(info, i))
result++;
}
return result;
}
/**
* gcov_info_reset - reset profiling data to zero
* @info: profiling data set
*/
void gcov_info_reset(struct gcov_info *info)
{
struct gcov_ctr_info *ci_ptr;
unsigned int fi_idx;
unsigned int ct_idx;
for (fi_idx = 0; fi_idx < info->n_functions; fi_idx++) {
ci_ptr = info->functions[fi_idx]->ctrs;
for (ct_idx = 0; ct_idx < GCOV_COUNTERS; ct_idx++) {
if (!counter_active(info, ct_idx))
continue;
memset(ci_ptr->values, 0,
sizeof(gcov_type) * ci_ptr->num);
ci_ptr++;
}
}
}
/**
* gcov_info_is_compatible - check if profiling data can be added
* @info1: first profiling data set
* @info2: second profiling data set
*
* Returns non-zero if profiling data can be added, zero otherwise.
*/
int gcov_info_is_compatible(struct gcov_info *info1, struct gcov_info *info2)
{
return (info1->stamp == info2->stamp);
}
/**
* gcov_info_add - add up profiling data
* @dest: profiling data set to which data is added
* @source: profiling data set which is added
*
* Adds profiling counts of @source to @dest.
*/
void gcov_info_add(struct gcov_info *dst, struct gcov_info *src)
{
struct gcov_ctr_info *dci_ptr;
struct gcov_ctr_info *sci_ptr;
unsigned int fi_idx;
unsigned int ct_idx;
unsigned int val_idx;
for (fi_idx = 0; fi_idx < src->n_functions; fi_idx++) {
dci_ptr = dst->functions[fi_idx]->ctrs;
sci_ptr = src->functions[fi_idx]->ctrs;
for (ct_idx = 0; ct_idx < GCOV_COUNTERS; ct_idx++) {
if (!counter_active(src, ct_idx))
continue;
for (val_idx = 0; val_idx < sci_ptr->num; val_idx++)
dci_ptr->values[val_idx] +=
sci_ptr->values[val_idx];
dci_ptr++;
sci_ptr++;
}
}
}
/**
* gcov_info_dup - duplicate profiling data set
* @info: profiling data set to duplicate
*
* Return newly allocated duplicate on success, %NULL on error.
*/
struct gcov_info *gcov_info_dup(struct gcov_info *info)
{
struct gcov_info *dup;
struct gcov_ctr_info *dci_ptr; /* dst counter info */
struct gcov_ctr_info *sci_ptr; /* src counter info */
unsigned int active;
unsigned int fi_idx; /* function info idx */
unsigned int ct_idx; /* counter type idx */
size_t fi_size; /* function info size */
size_t cv_size; /* counter values size */
dup = kmemdup(info, sizeof(*dup), GFP_KERNEL);
if (!dup)
return NULL;
dup->next = NULL;
dup->filename = NULL;
dup->functions = NULL;
dup->filename = kstrdup(info->filename, GFP_KERNEL);
if (!dup->filename)
goto err_free;
dup->functions = kcalloc(info->n_functions,
sizeof(struct gcov_fn_info *), GFP_KERNEL);
if (!dup->functions)
goto err_free;
active = num_counter_active(info);
fi_size = sizeof(struct gcov_fn_info);
fi_size += sizeof(struct gcov_ctr_info) * active;
for (fi_idx = 0; fi_idx < info->n_functions; fi_idx++) {
dup->functions[fi_idx] = kzalloc(fi_size, GFP_KERNEL);
if (!dup->functions[fi_idx])
goto err_free;
*(dup->functions[fi_idx]) = *(info->functions[fi_idx]);
sci_ptr = info->functions[fi_idx]->ctrs;
dci_ptr = dup->functions[fi_idx]->ctrs;
for (ct_idx = 0; ct_idx < active; ct_idx++) {
cv_size = sizeof(gcov_type) * sci_ptr->num;
dci_ptr->values = vmalloc(cv_size);
if (!dci_ptr->values)
goto err_free;
dci_ptr->num = sci_ptr->num;
memcpy(dci_ptr->values, sci_ptr->values, cv_size);
sci_ptr++;
dci_ptr++;
}
}
return dup;
err_free:
gcov_info_free(dup);
return NULL;
}
/**
* gcov_info_free - release memory for profiling data set duplicate
* @info: profiling data set duplicate to free
*/
void gcov_info_free(struct gcov_info *info)
{
unsigned int active;
unsigned int fi_idx;
unsigned int ct_idx;
struct gcov_ctr_info *ci_ptr;
if (!info->functions)
goto free_info;
active = num_counter_active(info);
for (fi_idx = 0; fi_idx < info->n_functions; fi_idx++) {
if (!info->functions[fi_idx])
continue;
ci_ptr = info->functions[fi_idx]->ctrs;
for (ct_idx = 0; ct_idx < active; ct_idx++, ci_ptr++)
vfree(ci_ptr->values);
kfree(info->functions[fi_idx]);
}
free_info:
kfree(info->functions);
kfree(info->filename);
kfree(info);
}
#define ITER_STRIDE PAGE_SIZE
/**
* struct gcov_iterator - specifies current file position in logical records
* @info: associated profiling data
* @buffer: buffer containing file data
* @size: size of buffer
* @pos: current position in file
*/
struct gcov_iterator {
struct gcov_info *info;
void *buffer;
size_t size;
loff_t pos;
};
/**
* store_gcov_u32 - store 32 bit number in gcov format to buffer
* @buffer: target buffer or NULL
* @off: offset into the buffer
* @v: value to be stored
*
* Number format defined by gcc: numbers are recorded in the 32 bit
* unsigned binary form of the endianness of the machine generating the
* file. Returns the number of bytes stored. If @buffer is %NULL, doesn't
* store anything.
*/
static size_t store_gcov_u32(void *buffer, size_t off, u32 v)
{
u32 *data;
if (buffer) {
data = buffer + off;
*data = v;
}
return sizeof(*data);
}
/**
* store_gcov_u64 - store 64 bit number in gcov format to buffer
* @buffer: target buffer or NULL
* @off: offset into the buffer
* @v: value to be stored
*
* Number format defined by gcc: numbers are recorded in the 32 bit
* unsigned binary form of the endianness of the machine generating the
* file. 64 bit numbers are stored as two 32 bit numbers, the low part
* first. Returns the number of bytes stored. If @buffer is %NULL, doesn't store
* anything.
*/
static size_t store_gcov_u64(void *buffer, size_t off, u64 v)
{
u32 *data;
if (buffer) {
data = buffer + off;
data[0] = (v & 0xffffffffUL);
data[1] = (v >> 32);
}
return sizeof(*data) * 2;
}
/**
* convert_to_gcda - convert profiling data set to gcda file format
* @buffer: the buffer to store file data or %NULL if no data should be stored
* @info: profiling data set to be converted
*
* Returns the number of bytes that were/would have been stored into the buffer.
*/
static size_t convert_to_gcda(char *buffer, struct gcov_info *info)
{
struct gcov_fn_info *fi_ptr;
struct gcov_ctr_info *ci_ptr;
unsigned int fi_idx;
unsigned int ct_idx;
unsigned int cv_idx;
size_t pos = 0;
/* File header. */
pos += store_gcov_u32(buffer, pos, GCOV_DATA_MAGIC);
pos += store_gcov_u32(buffer, pos, info->version);
pos += store_gcov_u32(buffer, pos, info->stamp);
for (fi_idx = 0; fi_idx < info->n_functions; fi_idx++) {
fi_ptr = info->functions[fi_idx];
/* Function record. */
pos += store_gcov_u32(buffer, pos, GCOV_TAG_FUNCTION);
pos += store_gcov_u32(buffer, pos, GCOV_TAG_FUNCTION_LENGTH);
pos += store_gcov_u32(buffer, pos, fi_ptr->ident);
pos += store_gcov_u32(buffer, pos, fi_ptr->lineno_checksum);
pos += store_gcov_u32(buffer, pos, fi_ptr->cfg_checksum);
ci_ptr = fi_ptr->ctrs;
for (ct_idx = 0; ct_idx < GCOV_COUNTERS; ct_idx++) {
if (!counter_active(info, ct_idx))
continue;
/* Counter record. */
pos += store_gcov_u32(buffer, pos,
GCOV_TAG_FOR_COUNTER(ct_idx));
pos += store_gcov_u32(buffer, pos, ci_ptr->num * 2);
for (cv_idx = 0; cv_idx < ci_ptr->num; cv_idx++) {
pos += store_gcov_u64(buffer, pos,
ci_ptr->values[cv_idx]);
}
ci_ptr++;
}
}
return pos;
}
/**
* gcov_iter_new - allocate and initialize profiling data iterator
* @info: profiling data set to be iterated
*
* Return file iterator on success, %NULL otherwise.
*/
struct gcov_iterator *gcov_iter_new(struct gcov_info *info)
{
struct gcov_iterator *iter;
iter = kzalloc(sizeof(struct gcov_iterator), GFP_KERNEL);
if (!iter)
goto err_free;
iter->info = info;
/* Dry-run to get the actual buffer size. */
iter->size = convert_to_gcda(NULL, info);
iter->buffer = vmalloc(iter->size);
if (!iter->buffer)
goto err_free;
convert_to_gcda(iter->buffer, info);
return iter;
err_free:
kfree(iter);
return NULL;
}
/**
* gcov_iter_get_info - return profiling data set for given file iterator
* @iter: file iterator
*/
void gcov_iter_free(struct gcov_iterator *iter)
{
vfree(iter->buffer);
kfree(iter);
}
/**
* gcov_iter_get_info - return profiling data set for given file iterator
* @iter: file iterator
*/
struct gcov_info *gcov_iter_get_info(struct gcov_iterator *iter)
{
return iter->info;
}
/**
* gcov_iter_start - reset file iterator to starting position
* @iter: file iterator
*/
void gcov_iter_start(struct gcov_iterator *iter)
{
iter->pos = 0;
}
/**
* gcov_iter_next - advance file iterator to next logical record
* @iter: file iterator
*
* Return zero if new position is valid, non-zero if iterator has reached end.
*/
int gcov_iter_next(struct gcov_iterator *iter)
{
if (iter->pos < iter->size)
iter->pos += ITER_STRIDE;
if (iter->pos >= iter->size)
return -EINVAL;
return 0;
}
/**
* gcov_iter_write - write data for current pos to seq_file
* @iter: file iterator
* @seq: seq_file handle
*
* Return zero on success, non-zero otherwise.
*/
int gcov_iter_write(struct gcov_iterator *iter, struct seq_file *seq)
{
size_t len;
if (iter->pos >= iter->size)
return -EINVAL;
len = ITER_STRIDE;
if (iter->pos + len > iter->size)
len = iter->size - iter->pos;
seq_write(seq, iter->buffer + iter->pos, len);
return 0;
}
| gpl-2.0 |
virtuous/kernel-7x30-froyo-v2 | fs/ocfs2/alloc.c | 385 | 201300 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* alloc.c
*
* Extent allocs and frees
*
* Copyright (C) 2002, 2004 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License 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 021110-1307, USA.
*/
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/highmem.h>
#include <linux/swap.h>
#include <linux/quotaops.h>
#define MLOG_MASK_PREFIX ML_DISK_ALLOC
#include <cluster/masklog.h>
#include "ocfs2.h"
#include "alloc.h"
#include "aops.h"
#include "blockcheck.h"
#include "dlmglue.h"
#include "extent_map.h"
#include "inode.h"
#include "journal.h"
#include "localalloc.h"
#include "suballoc.h"
#include "sysfile.h"
#include "file.h"
#include "super.h"
#include "uptodate.h"
#include "xattr.h"
#include "refcounttree.h"
#include "buffer_head_io.h"
enum ocfs2_contig_type {
CONTIG_NONE = 0,
CONTIG_LEFT,
CONTIG_RIGHT,
CONTIG_LEFTRIGHT,
};
static enum ocfs2_contig_type
ocfs2_extent_rec_contig(struct super_block *sb,
struct ocfs2_extent_rec *ext,
struct ocfs2_extent_rec *insert_rec);
/*
* Operations for a specific extent tree type.
*
* To implement an on-disk btree (extent tree) type in ocfs2, add
* an ocfs2_extent_tree_operations structure and the matching
* ocfs2_init_<thingy>_extent_tree() function. That's pretty much it
* for the allocation portion of the extent tree.
*/
struct ocfs2_extent_tree_operations {
/*
* last_eb_blk is the block number of the right most leaf extent
* block. Most on-disk structures containing an extent tree store
* this value for fast access. The ->eo_set_last_eb_blk() and
* ->eo_get_last_eb_blk() operations access this value. They are
* both required.
*/
void (*eo_set_last_eb_blk)(struct ocfs2_extent_tree *et,
u64 blkno);
u64 (*eo_get_last_eb_blk)(struct ocfs2_extent_tree *et);
/*
* The on-disk structure usually keeps track of how many total
* clusters are stored in this extent tree. This function updates
* that value. new_clusters is the delta, and must be
* added to the total. Required.
*/
void (*eo_update_clusters)(struct ocfs2_extent_tree *et,
u32 new_clusters);
/*
* If this extent tree is supported by an extent map, insert
* a record into the map.
*/
void (*eo_extent_map_insert)(struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *rec);
/*
* If this extent tree is supported by an extent map, truncate the
* map to clusters,
*/
void (*eo_extent_map_truncate)(struct ocfs2_extent_tree *et,
u32 clusters);
/*
* If ->eo_insert_check() exists, it is called before rec is
* inserted into the extent tree. It is optional.
*/
int (*eo_insert_check)(struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *rec);
int (*eo_sanity_check)(struct ocfs2_extent_tree *et);
/*
* --------------------------------------------------------------
* The remaining are internal to ocfs2_extent_tree and don't have
* accessor functions
*/
/*
* ->eo_fill_root_el() takes et->et_object and sets et->et_root_el.
* It is required.
*/
void (*eo_fill_root_el)(struct ocfs2_extent_tree *et);
/*
* ->eo_fill_max_leaf_clusters sets et->et_max_leaf_clusters if
* it exists. If it does not, et->et_max_leaf_clusters is set
* to 0 (unlimited). Optional.
*/
void (*eo_fill_max_leaf_clusters)(struct ocfs2_extent_tree *et);
/*
* ->eo_extent_contig test whether the 2 ocfs2_extent_rec
* are contiguous or not. Optional. Don't need to set it if use
* ocfs2_extent_rec as the tree leaf.
*/
enum ocfs2_contig_type
(*eo_extent_contig)(struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *ext,
struct ocfs2_extent_rec *insert_rec);
};
/*
* Pre-declare ocfs2_dinode_et_ops so we can use it as a sanity check
* in the methods.
*/
static u64 ocfs2_dinode_get_last_eb_blk(struct ocfs2_extent_tree *et);
static void ocfs2_dinode_set_last_eb_blk(struct ocfs2_extent_tree *et,
u64 blkno);
static void ocfs2_dinode_update_clusters(struct ocfs2_extent_tree *et,
u32 clusters);
static void ocfs2_dinode_extent_map_insert(struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *rec);
static void ocfs2_dinode_extent_map_truncate(struct ocfs2_extent_tree *et,
u32 clusters);
static int ocfs2_dinode_insert_check(struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *rec);
static int ocfs2_dinode_sanity_check(struct ocfs2_extent_tree *et);
static void ocfs2_dinode_fill_root_el(struct ocfs2_extent_tree *et);
static struct ocfs2_extent_tree_operations ocfs2_dinode_et_ops = {
.eo_set_last_eb_blk = ocfs2_dinode_set_last_eb_blk,
.eo_get_last_eb_blk = ocfs2_dinode_get_last_eb_blk,
.eo_update_clusters = ocfs2_dinode_update_clusters,
.eo_extent_map_insert = ocfs2_dinode_extent_map_insert,
.eo_extent_map_truncate = ocfs2_dinode_extent_map_truncate,
.eo_insert_check = ocfs2_dinode_insert_check,
.eo_sanity_check = ocfs2_dinode_sanity_check,
.eo_fill_root_el = ocfs2_dinode_fill_root_el,
};
static void ocfs2_dinode_set_last_eb_blk(struct ocfs2_extent_tree *et,
u64 blkno)
{
struct ocfs2_dinode *di = et->et_object;
BUG_ON(et->et_ops != &ocfs2_dinode_et_ops);
di->i_last_eb_blk = cpu_to_le64(blkno);
}
static u64 ocfs2_dinode_get_last_eb_blk(struct ocfs2_extent_tree *et)
{
struct ocfs2_dinode *di = et->et_object;
BUG_ON(et->et_ops != &ocfs2_dinode_et_ops);
return le64_to_cpu(di->i_last_eb_blk);
}
static void ocfs2_dinode_update_clusters(struct ocfs2_extent_tree *et,
u32 clusters)
{
struct ocfs2_inode_info *oi = cache_info_to_inode(et->et_ci);
struct ocfs2_dinode *di = et->et_object;
le32_add_cpu(&di->i_clusters, clusters);
spin_lock(&oi->ip_lock);
oi->ip_clusters = le32_to_cpu(di->i_clusters);
spin_unlock(&oi->ip_lock);
}
static void ocfs2_dinode_extent_map_insert(struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *rec)
{
struct inode *inode = &cache_info_to_inode(et->et_ci)->vfs_inode;
ocfs2_extent_map_insert_rec(inode, rec);
}
static void ocfs2_dinode_extent_map_truncate(struct ocfs2_extent_tree *et,
u32 clusters)
{
struct inode *inode = &cache_info_to_inode(et->et_ci)->vfs_inode;
ocfs2_extent_map_trunc(inode, clusters);
}
static int ocfs2_dinode_insert_check(struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *rec)
{
struct ocfs2_inode_info *oi = cache_info_to_inode(et->et_ci);
struct ocfs2_super *osb = OCFS2_SB(oi->vfs_inode.i_sb);
BUG_ON(oi->ip_dyn_features & OCFS2_INLINE_DATA_FL);
mlog_bug_on_msg(!ocfs2_sparse_alloc(osb) &&
(oi->ip_clusters != le32_to_cpu(rec->e_cpos)),
"Device %s, asking for sparse allocation: inode %llu, "
"cpos %u, clusters %u\n",
osb->dev_str,
(unsigned long long)oi->ip_blkno,
rec->e_cpos, oi->ip_clusters);
return 0;
}
static int ocfs2_dinode_sanity_check(struct ocfs2_extent_tree *et)
{
struct ocfs2_dinode *di = et->et_object;
BUG_ON(et->et_ops != &ocfs2_dinode_et_ops);
BUG_ON(!OCFS2_IS_VALID_DINODE(di));
return 0;
}
static void ocfs2_dinode_fill_root_el(struct ocfs2_extent_tree *et)
{
struct ocfs2_dinode *di = et->et_object;
et->et_root_el = &di->id2.i_list;
}
static void ocfs2_xattr_value_fill_root_el(struct ocfs2_extent_tree *et)
{
struct ocfs2_xattr_value_buf *vb = et->et_object;
et->et_root_el = &vb->vb_xv->xr_list;
}
static void ocfs2_xattr_value_set_last_eb_blk(struct ocfs2_extent_tree *et,
u64 blkno)
{
struct ocfs2_xattr_value_buf *vb = et->et_object;
vb->vb_xv->xr_last_eb_blk = cpu_to_le64(blkno);
}
static u64 ocfs2_xattr_value_get_last_eb_blk(struct ocfs2_extent_tree *et)
{
struct ocfs2_xattr_value_buf *vb = et->et_object;
return le64_to_cpu(vb->vb_xv->xr_last_eb_blk);
}
static void ocfs2_xattr_value_update_clusters(struct ocfs2_extent_tree *et,
u32 clusters)
{
struct ocfs2_xattr_value_buf *vb = et->et_object;
le32_add_cpu(&vb->vb_xv->xr_clusters, clusters);
}
static struct ocfs2_extent_tree_operations ocfs2_xattr_value_et_ops = {
.eo_set_last_eb_blk = ocfs2_xattr_value_set_last_eb_blk,
.eo_get_last_eb_blk = ocfs2_xattr_value_get_last_eb_blk,
.eo_update_clusters = ocfs2_xattr_value_update_clusters,
.eo_fill_root_el = ocfs2_xattr_value_fill_root_el,
};
static void ocfs2_xattr_tree_fill_root_el(struct ocfs2_extent_tree *et)
{
struct ocfs2_xattr_block *xb = et->et_object;
et->et_root_el = &xb->xb_attrs.xb_root.xt_list;
}
static void ocfs2_xattr_tree_fill_max_leaf_clusters(struct ocfs2_extent_tree *et)
{
struct super_block *sb = ocfs2_metadata_cache_get_super(et->et_ci);
et->et_max_leaf_clusters =
ocfs2_clusters_for_bytes(sb, OCFS2_MAX_XATTR_TREE_LEAF_SIZE);
}
static void ocfs2_xattr_tree_set_last_eb_blk(struct ocfs2_extent_tree *et,
u64 blkno)
{
struct ocfs2_xattr_block *xb = et->et_object;
struct ocfs2_xattr_tree_root *xt = &xb->xb_attrs.xb_root;
xt->xt_last_eb_blk = cpu_to_le64(blkno);
}
static u64 ocfs2_xattr_tree_get_last_eb_blk(struct ocfs2_extent_tree *et)
{
struct ocfs2_xattr_block *xb = et->et_object;
struct ocfs2_xattr_tree_root *xt = &xb->xb_attrs.xb_root;
return le64_to_cpu(xt->xt_last_eb_blk);
}
static void ocfs2_xattr_tree_update_clusters(struct ocfs2_extent_tree *et,
u32 clusters)
{
struct ocfs2_xattr_block *xb = et->et_object;
le32_add_cpu(&xb->xb_attrs.xb_root.xt_clusters, clusters);
}
static struct ocfs2_extent_tree_operations ocfs2_xattr_tree_et_ops = {
.eo_set_last_eb_blk = ocfs2_xattr_tree_set_last_eb_blk,
.eo_get_last_eb_blk = ocfs2_xattr_tree_get_last_eb_blk,
.eo_update_clusters = ocfs2_xattr_tree_update_clusters,
.eo_fill_root_el = ocfs2_xattr_tree_fill_root_el,
.eo_fill_max_leaf_clusters = ocfs2_xattr_tree_fill_max_leaf_clusters,
};
static void ocfs2_dx_root_set_last_eb_blk(struct ocfs2_extent_tree *et,
u64 blkno)
{
struct ocfs2_dx_root_block *dx_root = et->et_object;
dx_root->dr_last_eb_blk = cpu_to_le64(blkno);
}
static u64 ocfs2_dx_root_get_last_eb_blk(struct ocfs2_extent_tree *et)
{
struct ocfs2_dx_root_block *dx_root = et->et_object;
return le64_to_cpu(dx_root->dr_last_eb_blk);
}
static void ocfs2_dx_root_update_clusters(struct ocfs2_extent_tree *et,
u32 clusters)
{
struct ocfs2_dx_root_block *dx_root = et->et_object;
le32_add_cpu(&dx_root->dr_clusters, clusters);
}
static int ocfs2_dx_root_sanity_check(struct ocfs2_extent_tree *et)
{
struct ocfs2_dx_root_block *dx_root = et->et_object;
BUG_ON(!OCFS2_IS_VALID_DX_ROOT(dx_root));
return 0;
}
static void ocfs2_dx_root_fill_root_el(struct ocfs2_extent_tree *et)
{
struct ocfs2_dx_root_block *dx_root = et->et_object;
et->et_root_el = &dx_root->dr_list;
}
static struct ocfs2_extent_tree_operations ocfs2_dx_root_et_ops = {
.eo_set_last_eb_blk = ocfs2_dx_root_set_last_eb_blk,
.eo_get_last_eb_blk = ocfs2_dx_root_get_last_eb_blk,
.eo_update_clusters = ocfs2_dx_root_update_clusters,
.eo_sanity_check = ocfs2_dx_root_sanity_check,
.eo_fill_root_el = ocfs2_dx_root_fill_root_el,
};
static void ocfs2_refcount_tree_fill_root_el(struct ocfs2_extent_tree *et)
{
struct ocfs2_refcount_block *rb = et->et_object;
et->et_root_el = &rb->rf_list;
}
static void ocfs2_refcount_tree_set_last_eb_blk(struct ocfs2_extent_tree *et,
u64 blkno)
{
struct ocfs2_refcount_block *rb = et->et_object;
rb->rf_last_eb_blk = cpu_to_le64(blkno);
}
static u64 ocfs2_refcount_tree_get_last_eb_blk(struct ocfs2_extent_tree *et)
{
struct ocfs2_refcount_block *rb = et->et_object;
return le64_to_cpu(rb->rf_last_eb_blk);
}
static void ocfs2_refcount_tree_update_clusters(struct ocfs2_extent_tree *et,
u32 clusters)
{
struct ocfs2_refcount_block *rb = et->et_object;
le32_add_cpu(&rb->rf_clusters, clusters);
}
static enum ocfs2_contig_type
ocfs2_refcount_tree_extent_contig(struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *ext,
struct ocfs2_extent_rec *insert_rec)
{
return CONTIG_NONE;
}
static struct ocfs2_extent_tree_operations ocfs2_refcount_tree_et_ops = {
.eo_set_last_eb_blk = ocfs2_refcount_tree_set_last_eb_blk,
.eo_get_last_eb_blk = ocfs2_refcount_tree_get_last_eb_blk,
.eo_update_clusters = ocfs2_refcount_tree_update_clusters,
.eo_fill_root_el = ocfs2_refcount_tree_fill_root_el,
.eo_extent_contig = ocfs2_refcount_tree_extent_contig,
};
static void __ocfs2_init_extent_tree(struct ocfs2_extent_tree *et,
struct ocfs2_caching_info *ci,
struct buffer_head *bh,
ocfs2_journal_access_func access,
void *obj,
struct ocfs2_extent_tree_operations *ops)
{
et->et_ops = ops;
et->et_root_bh = bh;
et->et_ci = ci;
et->et_root_journal_access = access;
if (!obj)
obj = (void *)bh->b_data;
et->et_object = obj;
et->et_ops->eo_fill_root_el(et);
if (!et->et_ops->eo_fill_max_leaf_clusters)
et->et_max_leaf_clusters = 0;
else
et->et_ops->eo_fill_max_leaf_clusters(et);
}
void ocfs2_init_dinode_extent_tree(struct ocfs2_extent_tree *et,
struct ocfs2_caching_info *ci,
struct buffer_head *bh)
{
__ocfs2_init_extent_tree(et, ci, bh, ocfs2_journal_access_di,
NULL, &ocfs2_dinode_et_ops);
}
void ocfs2_init_xattr_tree_extent_tree(struct ocfs2_extent_tree *et,
struct ocfs2_caching_info *ci,
struct buffer_head *bh)
{
__ocfs2_init_extent_tree(et, ci, bh, ocfs2_journal_access_xb,
NULL, &ocfs2_xattr_tree_et_ops);
}
void ocfs2_init_xattr_value_extent_tree(struct ocfs2_extent_tree *et,
struct ocfs2_caching_info *ci,
struct ocfs2_xattr_value_buf *vb)
{
__ocfs2_init_extent_tree(et, ci, vb->vb_bh, vb->vb_access, vb,
&ocfs2_xattr_value_et_ops);
}
void ocfs2_init_dx_root_extent_tree(struct ocfs2_extent_tree *et,
struct ocfs2_caching_info *ci,
struct buffer_head *bh)
{
__ocfs2_init_extent_tree(et, ci, bh, ocfs2_journal_access_dr,
NULL, &ocfs2_dx_root_et_ops);
}
void ocfs2_init_refcount_extent_tree(struct ocfs2_extent_tree *et,
struct ocfs2_caching_info *ci,
struct buffer_head *bh)
{
__ocfs2_init_extent_tree(et, ci, bh, ocfs2_journal_access_rb,
NULL, &ocfs2_refcount_tree_et_ops);
}
static inline void ocfs2_et_set_last_eb_blk(struct ocfs2_extent_tree *et,
u64 new_last_eb_blk)
{
et->et_ops->eo_set_last_eb_blk(et, new_last_eb_blk);
}
static inline u64 ocfs2_et_get_last_eb_blk(struct ocfs2_extent_tree *et)
{
return et->et_ops->eo_get_last_eb_blk(et);
}
static inline void ocfs2_et_update_clusters(struct ocfs2_extent_tree *et,
u32 clusters)
{
et->et_ops->eo_update_clusters(et, clusters);
}
static inline void ocfs2_et_extent_map_insert(struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *rec)
{
if (et->et_ops->eo_extent_map_insert)
et->et_ops->eo_extent_map_insert(et, rec);
}
static inline void ocfs2_et_extent_map_truncate(struct ocfs2_extent_tree *et,
u32 clusters)
{
if (et->et_ops->eo_extent_map_truncate)
et->et_ops->eo_extent_map_truncate(et, clusters);
}
static inline int ocfs2_et_root_journal_access(handle_t *handle,
struct ocfs2_extent_tree *et,
int type)
{
return et->et_root_journal_access(handle, et->et_ci, et->et_root_bh,
type);
}
static inline enum ocfs2_contig_type
ocfs2_et_extent_contig(struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *rec,
struct ocfs2_extent_rec *insert_rec)
{
if (et->et_ops->eo_extent_contig)
return et->et_ops->eo_extent_contig(et, rec, insert_rec);
return ocfs2_extent_rec_contig(
ocfs2_metadata_cache_get_super(et->et_ci),
rec, insert_rec);
}
static inline int ocfs2_et_insert_check(struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *rec)
{
int ret = 0;
if (et->et_ops->eo_insert_check)
ret = et->et_ops->eo_insert_check(et, rec);
return ret;
}
static inline int ocfs2_et_sanity_check(struct ocfs2_extent_tree *et)
{
int ret = 0;
if (et->et_ops->eo_sanity_check)
ret = et->et_ops->eo_sanity_check(et);
return ret;
}
static void ocfs2_free_truncate_context(struct ocfs2_truncate_context *tc);
static int ocfs2_cache_extent_block_free(struct ocfs2_cached_dealloc_ctxt *ctxt,
struct ocfs2_extent_block *eb);
static void ocfs2_adjust_rightmost_records(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_path *path,
struct ocfs2_extent_rec *insert_rec);
/*
* Reset the actual path elements so that we can re-use the structure
* to build another path. Generally, this involves freeing the buffer
* heads.
*/
void ocfs2_reinit_path(struct ocfs2_path *path, int keep_root)
{
int i, start = 0, depth = 0;
struct ocfs2_path_item *node;
if (keep_root)
start = 1;
for(i = start; i < path_num_items(path); i++) {
node = &path->p_node[i];
brelse(node->bh);
node->bh = NULL;
node->el = NULL;
}
/*
* Tree depth may change during truncate, or insert. If we're
* keeping the root extent list, then make sure that our path
* structure reflects the proper depth.
*/
if (keep_root)
depth = le16_to_cpu(path_root_el(path)->l_tree_depth);
else
path_root_access(path) = NULL;
path->p_tree_depth = depth;
}
void ocfs2_free_path(struct ocfs2_path *path)
{
if (path) {
ocfs2_reinit_path(path, 0);
kfree(path);
}
}
/*
* All the elements of src into dest. After this call, src could be freed
* without affecting dest.
*
* Both paths should have the same root. Any non-root elements of dest
* will be freed.
*/
static void ocfs2_cp_path(struct ocfs2_path *dest, struct ocfs2_path *src)
{
int i;
BUG_ON(path_root_bh(dest) != path_root_bh(src));
BUG_ON(path_root_el(dest) != path_root_el(src));
BUG_ON(path_root_access(dest) != path_root_access(src));
ocfs2_reinit_path(dest, 1);
for(i = 1; i < OCFS2_MAX_PATH_DEPTH; i++) {
dest->p_node[i].bh = src->p_node[i].bh;
dest->p_node[i].el = src->p_node[i].el;
if (dest->p_node[i].bh)
get_bh(dest->p_node[i].bh);
}
}
/*
* Make the *dest path the same as src and re-initialize src path to
* have a root only.
*/
static void ocfs2_mv_path(struct ocfs2_path *dest, struct ocfs2_path *src)
{
int i;
BUG_ON(path_root_bh(dest) != path_root_bh(src));
BUG_ON(path_root_access(dest) != path_root_access(src));
for(i = 1; i < OCFS2_MAX_PATH_DEPTH; i++) {
brelse(dest->p_node[i].bh);
dest->p_node[i].bh = src->p_node[i].bh;
dest->p_node[i].el = src->p_node[i].el;
src->p_node[i].bh = NULL;
src->p_node[i].el = NULL;
}
}
/*
* Insert an extent block at given index.
*
* This will not take an additional reference on eb_bh.
*/
static inline void ocfs2_path_insert_eb(struct ocfs2_path *path, int index,
struct buffer_head *eb_bh)
{
struct ocfs2_extent_block *eb = (struct ocfs2_extent_block *)eb_bh->b_data;
/*
* Right now, no root bh is an extent block, so this helps
* catch code errors with dinode trees. The assertion can be
* safely removed if we ever need to insert extent block
* structures at the root.
*/
BUG_ON(index == 0);
path->p_node[index].bh = eb_bh;
path->p_node[index].el = &eb->h_list;
}
static struct ocfs2_path *ocfs2_new_path(struct buffer_head *root_bh,
struct ocfs2_extent_list *root_el,
ocfs2_journal_access_func access)
{
struct ocfs2_path *path;
BUG_ON(le16_to_cpu(root_el->l_tree_depth) >= OCFS2_MAX_PATH_DEPTH);
path = kzalloc(sizeof(*path), GFP_NOFS);
if (path) {
path->p_tree_depth = le16_to_cpu(root_el->l_tree_depth);
get_bh(root_bh);
path_root_bh(path) = root_bh;
path_root_el(path) = root_el;
path_root_access(path) = access;
}
return path;
}
struct ocfs2_path *ocfs2_new_path_from_path(struct ocfs2_path *path)
{
return ocfs2_new_path(path_root_bh(path), path_root_el(path),
path_root_access(path));
}
struct ocfs2_path *ocfs2_new_path_from_et(struct ocfs2_extent_tree *et)
{
return ocfs2_new_path(et->et_root_bh, et->et_root_el,
et->et_root_journal_access);
}
/*
* Journal the buffer at depth idx. All idx>0 are extent_blocks,
* otherwise it's the root_access function.
*
* I don't like the way this function's name looks next to
* ocfs2_journal_access_path(), but I don't have a better one.
*/
int ocfs2_path_bh_journal_access(handle_t *handle,
struct ocfs2_caching_info *ci,
struct ocfs2_path *path,
int idx)
{
ocfs2_journal_access_func access = path_root_access(path);
if (!access)
access = ocfs2_journal_access;
if (idx)
access = ocfs2_journal_access_eb;
return access(handle, ci, path->p_node[idx].bh,
OCFS2_JOURNAL_ACCESS_WRITE);
}
/*
* Convenience function to journal all components in a path.
*/
int ocfs2_journal_access_path(struct ocfs2_caching_info *ci,
handle_t *handle,
struct ocfs2_path *path)
{
int i, ret = 0;
if (!path)
goto out;
for(i = 0; i < path_num_items(path); i++) {
ret = ocfs2_path_bh_journal_access(handle, ci, path, i);
if (ret < 0) {
mlog_errno(ret);
goto out;
}
}
out:
return ret;
}
/*
* Return the index of the extent record which contains cluster #v_cluster.
* -1 is returned if it was not found.
*
* Should work fine on interior and exterior nodes.
*/
int ocfs2_search_extent_list(struct ocfs2_extent_list *el, u32 v_cluster)
{
int ret = -1;
int i;
struct ocfs2_extent_rec *rec;
u32 rec_end, rec_start, clusters;
for(i = 0; i < le16_to_cpu(el->l_next_free_rec); i++) {
rec = &el->l_recs[i];
rec_start = le32_to_cpu(rec->e_cpos);
clusters = ocfs2_rec_clusters(el, rec);
rec_end = rec_start + clusters;
if (v_cluster >= rec_start && v_cluster < rec_end) {
ret = i;
break;
}
}
return ret;
}
/*
* NOTE: ocfs2_block_extent_contig(), ocfs2_extents_adjacent() and
* ocfs2_extent_rec_contig only work properly against leaf nodes!
*/
static int ocfs2_block_extent_contig(struct super_block *sb,
struct ocfs2_extent_rec *ext,
u64 blkno)
{
u64 blk_end = le64_to_cpu(ext->e_blkno);
blk_end += ocfs2_clusters_to_blocks(sb,
le16_to_cpu(ext->e_leaf_clusters));
return blkno == blk_end;
}
static int ocfs2_extents_adjacent(struct ocfs2_extent_rec *left,
struct ocfs2_extent_rec *right)
{
u32 left_range;
left_range = le32_to_cpu(left->e_cpos) +
le16_to_cpu(left->e_leaf_clusters);
return (left_range == le32_to_cpu(right->e_cpos));
}
static enum ocfs2_contig_type
ocfs2_extent_rec_contig(struct super_block *sb,
struct ocfs2_extent_rec *ext,
struct ocfs2_extent_rec *insert_rec)
{
u64 blkno = le64_to_cpu(insert_rec->e_blkno);
/*
* Refuse to coalesce extent records with different flag
* fields - we don't want to mix unwritten extents with user
* data.
*/
if (ext->e_flags != insert_rec->e_flags)
return CONTIG_NONE;
if (ocfs2_extents_adjacent(ext, insert_rec) &&
ocfs2_block_extent_contig(sb, ext, blkno))
return CONTIG_RIGHT;
blkno = le64_to_cpu(ext->e_blkno);
if (ocfs2_extents_adjacent(insert_rec, ext) &&
ocfs2_block_extent_contig(sb, insert_rec, blkno))
return CONTIG_LEFT;
return CONTIG_NONE;
}
/*
* NOTE: We can have pretty much any combination of contiguousness and
* appending.
*
* The usefulness of APPEND_TAIL is more in that it lets us know that
* we'll have to update the path to that leaf.
*/
enum ocfs2_append_type {
APPEND_NONE = 0,
APPEND_TAIL,
};
enum ocfs2_split_type {
SPLIT_NONE = 0,
SPLIT_LEFT,
SPLIT_RIGHT,
};
struct ocfs2_insert_type {
enum ocfs2_split_type ins_split;
enum ocfs2_append_type ins_appending;
enum ocfs2_contig_type ins_contig;
int ins_contig_index;
int ins_tree_depth;
};
struct ocfs2_merge_ctxt {
enum ocfs2_contig_type c_contig_type;
int c_has_empty_extent;
int c_split_covers_rec;
};
static int ocfs2_validate_extent_block(struct super_block *sb,
struct buffer_head *bh)
{
int rc;
struct ocfs2_extent_block *eb =
(struct ocfs2_extent_block *)bh->b_data;
mlog(0, "Validating extent block %llu\n",
(unsigned long long)bh->b_blocknr);
BUG_ON(!buffer_uptodate(bh));
/*
* If the ecc fails, we return the error but otherwise
* leave the filesystem running. We know any error is
* local to this block.
*/
rc = ocfs2_validate_meta_ecc(sb, bh->b_data, &eb->h_check);
if (rc) {
mlog(ML_ERROR, "Checksum failed for extent block %llu\n",
(unsigned long long)bh->b_blocknr);
return rc;
}
/*
* Errors after here are fatal.
*/
if (!OCFS2_IS_VALID_EXTENT_BLOCK(eb)) {
ocfs2_error(sb,
"Extent block #%llu has bad signature %.*s",
(unsigned long long)bh->b_blocknr, 7,
eb->h_signature);
return -EINVAL;
}
if (le64_to_cpu(eb->h_blkno) != bh->b_blocknr) {
ocfs2_error(sb,
"Extent block #%llu has an invalid h_blkno "
"of %llu",
(unsigned long long)bh->b_blocknr,
(unsigned long long)le64_to_cpu(eb->h_blkno));
return -EINVAL;
}
if (le32_to_cpu(eb->h_fs_generation) != OCFS2_SB(sb)->fs_generation) {
ocfs2_error(sb,
"Extent block #%llu has an invalid "
"h_fs_generation of #%u",
(unsigned long long)bh->b_blocknr,
le32_to_cpu(eb->h_fs_generation));
return -EINVAL;
}
return 0;
}
int ocfs2_read_extent_block(struct ocfs2_caching_info *ci, u64 eb_blkno,
struct buffer_head **bh)
{
int rc;
struct buffer_head *tmp = *bh;
rc = ocfs2_read_block(ci, eb_blkno, &tmp,
ocfs2_validate_extent_block);
/* If ocfs2_read_block() got us a new bh, pass it up. */
if (!rc && !*bh)
*bh = tmp;
return rc;
}
/*
* How many free extents have we got before we need more meta data?
*/
int ocfs2_num_free_extents(struct ocfs2_super *osb,
struct ocfs2_extent_tree *et)
{
int retval;
struct ocfs2_extent_list *el = NULL;
struct ocfs2_extent_block *eb;
struct buffer_head *eb_bh = NULL;
u64 last_eb_blk = 0;
mlog_entry_void();
el = et->et_root_el;
last_eb_blk = ocfs2_et_get_last_eb_blk(et);
if (last_eb_blk) {
retval = ocfs2_read_extent_block(et->et_ci, last_eb_blk,
&eb_bh);
if (retval < 0) {
mlog_errno(retval);
goto bail;
}
eb = (struct ocfs2_extent_block *) eb_bh->b_data;
el = &eb->h_list;
}
BUG_ON(el->l_tree_depth != 0);
retval = le16_to_cpu(el->l_count) - le16_to_cpu(el->l_next_free_rec);
bail:
brelse(eb_bh);
mlog_exit(retval);
return retval;
}
/* expects array to already be allocated
*
* sets h_signature, h_blkno, h_suballoc_bit, h_suballoc_slot, and
* l_count for you
*/
static int ocfs2_create_new_meta_bhs(handle_t *handle,
struct ocfs2_extent_tree *et,
int wanted,
struct ocfs2_alloc_context *meta_ac,
struct buffer_head *bhs[])
{
int count, status, i;
u16 suballoc_bit_start;
u32 num_got;
u64 first_blkno;
struct ocfs2_super *osb =
OCFS2_SB(ocfs2_metadata_cache_get_super(et->et_ci));
struct ocfs2_extent_block *eb;
mlog_entry_void();
count = 0;
while (count < wanted) {
status = ocfs2_claim_metadata(osb,
handle,
meta_ac,
wanted - count,
&suballoc_bit_start,
&num_got,
&first_blkno);
if (status < 0) {
mlog_errno(status);
goto bail;
}
for(i = count; i < (num_got + count); i++) {
bhs[i] = sb_getblk(osb->sb, first_blkno);
if (bhs[i] == NULL) {
status = -EIO;
mlog_errno(status);
goto bail;
}
ocfs2_set_new_buffer_uptodate(et->et_ci, bhs[i]);
status = ocfs2_journal_access_eb(handle, et->et_ci,
bhs[i],
OCFS2_JOURNAL_ACCESS_CREATE);
if (status < 0) {
mlog_errno(status);
goto bail;
}
memset(bhs[i]->b_data, 0, osb->sb->s_blocksize);
eb = (struct ocfs2_extent_block *) bhs[i]->b_data;
/* Ok, setup the minimal stuff here. */
strcpy(eb->h_signature, OCFS2_EXTENT_BLOCK_SIGNATURE);
eb->h_blkno = cpu_to_le64(first_blkno);
eb->h_fs_generation = cpu_to_le32(osb->fs_generation);
eb->h_suballoc_slot = cpu_to_le16(osb->slot_num);
eb->h_suballoc_bit = cpu_to_le16(suballoc_bit_start);
eb->h_list.l_count =
cpu_to_le16(ocfs2_extent_recs_per_eb(osb->sb));
suballoc_bit_start++;
first_blkno++;
/* We'll also be dirtied by the caller, so
* this isn't absolutely necessary. */
status = ocfs2_journal_dirty(handle, bhs[i]);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
count += num_got;
}
status = 0;
bail:
if (status < 0) {
for(i = 0; i < wanted; i++) {
brelse(bhs[i]);
bhs[i] = NULL;
}
}
mlog_exit(status);
return status;
}
/*
* Helper function for ocfs2_add_branch() and ocfs2_shift_tree_depth().
*
* Returns the sum of the rightmost extent rec logical offset and
* cluster count.
*
* ocfs2_add_branch() uses this to determine what logical cluster
* value should be populated into the leftmost new branch records.
*
* ocfs2_shift_tree_depth() uses this to determine the # clusters
* value for the new topmost tree record.
*/
static inline u32 ocfs2_sum_rightmost_rec(struct ocfs2_extent_list *el)
{
int i;
i = le16_to_cpu(el->l_next_free_rec) - 1;
return le32_to_cpu(el->l_recs[i].e_cpos) +
ocfs2_rec_clusters(el, &el->l_recs[i]);
}
/*
* Change range of the branches in the right most path according to the leaf
* extent block's rightmost record.
*/
static int ocfs2_adjust_rightmost_branch(handle_t *handle,
struct ocfs2_extent_tree *et)
{
int status;
struct ocfs2_path *path = NULL;
struct ocfs2_extent_list *el;
struct ocfs2_extent_rec *rec;
path = ocfs2_new_path_from_et(et);
if (!path) {
status = -ENOMEM;
return status;
}
status = ocfs2_find_path(et->et_ci, path, UINT_MAX);
if (status < 0) {
mlog_errno(status);
goto out;
}
status = ocfs2_extend_trans(handle, path_num_items(path) +
handle->h_buffer_credits);
if (status < 0) {
mlog_errno(status);
goto out;
}
status = ocfs2_journal_access_path(et->et_ci, handle, path);
if (status < 0) {
mlog_errno(status);
goto out;
}
el = path_leaf_el(path);
rec = &el->l_recs[le32_to_cpu(el->l_next_free_rec) - 1];
ocfs2_adjust_rightmost_records(handle, et, path, rec);
out:
ocfs2_free_path(path);
return status;
}
/*
* Add an entire tree branch to our inode. eb_bh is the extent block
* to start at, if we don't want to start the branch at the root
* structure.
*
* last_eb_bh is required as we have to update it's next_leaf pointer
* for the new last extent block.
*
* the new branch will be 'empty' in the sense that every block will
* contain a single record with cluster count == 0.
*/
static int ocfs2_add_branch(handle_t *handle,
struct ocfs2_extent_tree *et,
struct buffer_head *eb_bh,
struct buffer_head **last_eb_bh,
struct ocfs2_alloc_context *meta_ac)
{
int status, new_blocks, i;
u64 next_blkno, new_last_eb_blk;
struct buffer_head *bh;
struct buffer_head **new_eb_bhs = NULL;
struct ocfs2_extent_block *eb;
struct ocfs2_extent_list *eb_el;
struct ocfs2_extent_list *el;
u32 new_cpos, root_end;
mlog_entry_void();
BUG_ON(!last_eb_bh || !*last_eb_bh);
if (eb_bh) {
eb = (struct ocfs2_extent_block *) eb_bh->b_data;
el = &eb->h_list;
} else
el = et->et_root_el;
/* we never add a branch to a leaf. */
BUG_ON(!el->l_tree_depth);
new_blocks = le16_to_cpu(el->l_tree_depth);
eb = (struct ocfs2_extent_block *)(*last_eb_bh)->b_data;
new_cpos = ocfs2_sum_rightmost_rec(&eb->h_list);
root_end = ocfs2_sum_rightmost_rec(et->et_root_el);
/*
* If there is a gap before the root end and the real end
* of the righmost leaf block, we need to remove the gap
* between new_cpos and root_end first so that the tree
* is consistent after we add a new branch(it will start
* from new_cpos).
*/
if (root_end > new_cpos) {
mlog(0, "adjust the cluster end from %u to %u\n",
root_end, new_cpos);
status = ocfs2_adjust_rightmost_branch(handle, et);
if (status) {
mlog_errno(status);
goto bail;
}
}
/* allocate the number of new eb blocks we need */
new_eb_bhs = kcalloc(new_blocks, sizeof(struct buffer_head *),
GFP_KERNEL);
if (!new_eb_bhs) {
status = -ENOMEM;
mlog_errno(status);
goto bail;
}
status = ocfs2_create_new_meta_bhs(handle, et, new_blocks,
meta_ac, new_eb_bhs);
if (status < 0) {
mlog_errno(status);
goto bail;
}
/* Note: new_eb_bhs[new_blocks - 1] is the guy which will be
* linked with the rest of the tree.
* conversly, new_eb_bhs[0] is the new bottommost leaf.
*
* when we leave the loop, new_last_eb_blk will point to the
* newest leaf, and next_blkno will point to the topmost extent
* block. */
next_blkno = new_last_eb_blk = 0;
for(i = 0; i < new_blocks; i++) {
bh = new_eb_bhs[i];
eb = (struct ocfs2_extent_block *) bh->b_data;
/* ocfs2_create_new_meta_bhs() should create it right! */
BUG_ON(!OCFS2_IS_VALID_EXTENT_BLOCK(eb));
eb_el = &eb->h_list;
status = ocfs2_journal_access_eb(handle, et->et_ci, bh,
OCFS2_JOURNAL_ACCESS_CREATE);
if (status < 0) {
mlog_errno(status);
goto bail;
}
eb->h_next_leaf_blk = 0;
eb_el->l_tree_depth = cpu_to_le16(i);
eb_el->l_next_free_rec = cpu_to_le16(1);
/*
* This actually counts as an empty extent as
* c_clusters == 0
*/
eb_el->l_recs[0].e_cpos = cpu_to_le32(new_cpos);
eb_el->l_recs[0].e_blkno = cpu_to_le64(next_blkno);
/*
* eb_el isn't always an interior node, but even leaf
* nodes want a zero'd flags and reserved field so
* this gets the whole 32 bits regardless of use.
*/
eb_el->l_recs[0].e_int_clusters = cpu_to_le32(0);
if (!eb_el->l_tree_depth)
new_last_eb_blk = le64_to_cpu(eb->h_blkno);
status = ocfs2_journal_dirty(handle, bh);
if (status < 0) {
mlog_errno(status);
goto bail;
}
next_blkno = le64_to_cpu(eb->h_blkno);
}
/* This is a bit hairy. We want to update up to three blocks
* here without leaving any of them in an inconsistent state
* in case of error. We don't have to worry about
* journal_dirty erroring as it won't unless we've aborted the
* handle (in which case we would never be here) so reserving
* the write with journal_access is all we need to do. */
status = ocfs2_journal_access_eb(handle, et->et_ci, *last_eb_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto bail;
}
status = ocfs2_et_root_journal_access(handle, et,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto bail;
}
if (eb_bh) {
status = ocfs2_journal_access_eb(handle, et->et_ci, eb_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
/* Link the new branch into the rest of the tree (el will
* either be on the root_bh, or the extent block passed in. */
i = le16_to_cpu(el->l_next_free_rec);
el->l_recs[i].e_blkno = cpu_to_le64(next_blkno);
el->l_recs[i].e_cpos = cpu_to_le32(new_cpos);
el->l_recs[i].e_int_clusters = 0;
le16_add_cpu(&el->l_next_free_rec, 1);
/* fe needs a new last extent block pointer, as does the
* next_leaf on the previously last-extent-block. */
ocfs2_et_set_last_eb_blk(et, new_last_eb_blk);
eb = (struct ocfs2_extent_block *) (*last_eb_bh)->b_data;
eb->h_next_leaf_blk = cpu_to_le64(new_last_eb_blk);
status = ocfs2_journal_dirty(handle, *last_eb_bh);
if (status < 0)
mlog_errno(status);
status = ocfs2_journal_dirty(handle, et->et_root_bh);
if (status < 0)
mlog_errno(status);
if (eb_bh) {
status = ocfs2_journal_dirty(handle, eb_bh);
if (status < 0)
mlog_errno(status);
}
/*
* Some callers want to track the rightmost leaf so pass it
* back here.
*/
brelse(*last_eb_bh);
get_bh(new_eb_bhs[0]);
*last_eb_bh = new_eb_bhs[0];
status = 0;
bail:
if (new_eb_bhs) {
for (i = 0; i < new_blocks; i++)
brelse(new_eb_bhs[i]);
kfree(new_eb_bhs);
}
mlog_exit(status);
return status;
}
/*
* adds another level to the allocation tree.
* returns back the new extent block so you can add a branch to it
* after this call.
*/
static int ocfs2_shift_tree_depth(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_alloc_context *meta_ac,
struct buffer_head **ret_new_eb_bh)
{
int status, i;
u32 new_clusters;
struct buffer_head *new_eb_bh = NULL;
struct ocfs2_extent_block *eb;
struct ocfs2_extent_list *root_el;
struct ocfs2_extent_list *eb_el;
mlog_entry_void();
status = ocfs2_create_new_meta_bhs(handle, et, 1, meta_ac,
&new_eb_bh);
if (status < 0) {
mlog_errno(status);
goto bail;
}
eb = (struct ocfs2_extent_block *) new_eb_bh->b_data;
/* ocfs2_create_new_meta_bhs() should create it right! */
BUG_ON(!OCFS2_IS_VALID_EXTENT_BLOCK(eb));
eb_el = &eb->h_list;
root_el = et->et_root_el;
status = ocfs2_journal_access_eb(handle, et->et_ci, new_eb_bh,
OCFS2_JOURNAL_ACCESS_CREATE);
if (status < 0) {
mlog_errno(status);
goto bail;
}
/* copy the root extent list data into the new extent block */
eb_el->l_tree_depth = root_el->l_tree_depth;
eb_el->l_next_free_rec = root_el->l_next_free_rec;
for (i = 0; i < le16_to_cpu(root_el->l_next_free_rec); i++)
eb_el->l_recs[i] = root_el->l_recs[i];
status = ocfs2_journal_dirty(handle, new_eb_bh);
if (status < 0) {
mlog_errno(status);
goto bail;
}
status = ocfs2_et_root_journal_access(handle, et,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto bail;
}
new_clusters = ocfs2_sum_rightmost_rec(eb_el);
/* update root_bh now */
le16_add_cpu(&root_el->l_tree_depth, 1);
root_el->l_recs[0].e_cpos = 0;
root_el->l_recs[0].e_blkno = eb->h_blkno;
root_el->l_recs[0].e_int_clusters = cpu_to_le32(new_clusters);
for (i = 1; i < le16_to_cpu(root_el->l_next_free_rec); i++)
memset(&root_el->l_recs[i], 0, sizeof(struct ocfs2_extent_rec));
root_el->l_next_free_rec = cpu_to_le16(1);
/* If this is our 1st tree depth shift, then last_eb_blk
* becomes the allocated extent block */
if (root_el->l_tree_depth == cpu_to_le16(1))
ocfs2_et_set_last_eb_blk(et, le64_to_cpu(eb->h_blkno));
status = ocfs2_journal_dirty(handle, et->et_root_bh);
if (status < 0) {
mlog_errno(status);
goto bail;
}
*ret_new_eb_bh = new_eb_bh;
new_eb_bh = NULL;
status = 0;
bail:
brelse(new_eb_bh);
mlog_exit(status);
return status;
}
/*
* Should only be called when there is no space left in any of the
* leaf nodes. What we want to do is find the lowest tree depth
* non-leaf extent block with room for new records. There are three
* valid results of this search:
*
* 1) a lowest extent block is found, then we pass it back in
* *lowest_eb_bh and return '0'
*
* 2) the search fails to find anything, but the root_el has room. We
* pass NULL back in *lowest_eb_bh, but still return '0'
*
* 3) the search fails to find anything AND the root_el is full, in
* which case we return > 0
*
* return status < 0 indicates an error.
*/
static int ocfs2_find_branch_target(struct ocfs2_extent_tree *et,
struct buffer_head **target_bh)
{
int status = 0, i;
u64 blkno;
struct ocfs2_extent_block *eb;
struct ocfs2_extent_list *el;
struct buffer_head *bh = NULL;
struct buffer_head *lowest_bh = NULL;
mlog_entry_void();
*target_bh = NULL;
el = et->et_root_el;
while(le16_to_cpu(el->l_tree_depth) > 1) {
if (le16_to_cpu(el->l_next_free_rec) == 0) {
ocfs2_error(ocfs2_metadata_cache_get_super(et->et_ci),
"Owner %llu has empty "
"extent list (next_free_rec == 0)",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci));
status = -EIO;
goto bail;
}
i = le16_to_cpu(el->l_next_free_rec) - 1;
blkno = le64_to_cpu(el->l_recs[i].e_blkno);
if (!blkno) {
ocfs2_error(ocfs2_metadata_cache_get_super(et->et_ci),
"Owner %llu has extent "
"list where extent # %d has no physical "
"block start",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci), i);
status = -EIO;
goto bail;
}
brelse(bh);
bh = NULL;
status = ocfs2_read_extent_block(et->et_ci, blkno, &bh);
if (status < 0) {
mlog_errno(status);
goto bail;
}
eb = (struct ocfs2_extent_block *) bh->b_data;
el = &eb->h_list;
if (le16_to_cpu(el->l_next_free_rec) <
le16_to_cpu(el->l_count)) {
brelse(lowest_bh);
lowest_bh = bh;
get_bh(lowest_bh);
}
}
/* If we didn't find one and the fe doesn't have any room,
* then return '1' */
el = et->et_root_el;
if (!lowest_bh && (el->l_next_free_rec == el->l_count))
status = 1;
*target_bh = lowest_bh;
bail:
brelse(bh);
mlog_exit(status);
return status;
}
/*
* Grow a b-tree so that it has more records.
*
* We might shift the tree depth in which case existing paths should
* be considered invalid.
*
* Tree depth after the grow is returned via *final_depth.
*
* *last_eb_bh will be updated by ocfs2_add_branch().
*/
static int ocfs2_grow_tree(handle_t *handle, struct ocfs2_extent_tree *et,
int *final_depth, struct buffer_head **last_eb_bh,
struct ocfs2_alloc_context *meta_ac)
{
int ret, shift;
struct ocfs2_extent_list *el = et->et_root_el;
int depth = le16_to_cpu(el->l_tree_depth);
struct buffer_head *bh = NULL;
BUG_ON(meta_ac == NULL);
shift = ocfs2_find_branch_target(et, &bh);
if (shift < 0) {
ret = shift;
mlog_errno(ret);
goto out;
}
/* We traveled all the way to the bottom of the allocation tree
* and didn't find room for any more extents - we need to add
* another tree level */
if (shift) {
BUG_ON(bh);
mlog(0, "need to shift tree depth (current = %d)\n", depth);
/* ocfs2_shift_tree_depth will return us a buffer with
* the new extent block (so we can pass that to
* ocfs2_add_branch). */
ret = ocfs2_shift_tree_depth(handle, et, meta_ac, &bh);
if (ret < 0) {
mlog_errno(ret);
goto out;
}
depth++;
if (depth == 1) {
/*
* Special case: we have room now if we shifted from
* tree_depth 0, so no more work needs to be done.
*
* We won't be calling add_branch, so pass
* back *last_eb_bh as the new leaf. At depth
* zero, it should always be null so there's
* no reason to brelse.
*/
BUG_ON(*last_eb_bh);
get_bh(bh);
*last_eb_bh = bh;
goto out;
}
}
/* call ocfs2_add_branch to add the final part of the tree with
* the new data. */
mlog(0, "add branch. bh = %p\n", bh);
ret = ocfs2_add_branch(handle, et, bh, last_eb_bh,
meta_ac);
if (ret < 0) {
mlog_errno(ret);
goto out;
}
out:
if (final_depth)
*final_depth = depth;
brelse(bh);
return ret;
}
/*
* This function will discard the rightmost extent record.
*/
static void ocfs2_shift_records_right(struct ocfs2_extent_list *el)
{
int next_free = le16_to_cpu(el->l_next_free_rec);
int count = le16_to_cpu(el->l_count);
unsigned int num_bytes;
BUG_ON(!next_free);
/* This will cause us to go off the end of our extent list. */
BUG_ON(next_free >= count);
num_bytes = sizeof(struct ocfs2_extent_rec) * next_free;
memmove(&el->l_recs[1], &el->l_recs[0], num_bytes);
}
static void ocfs2_rotate_leaf(struct ocfs2_extent_list *el,
struct ocfs2_extent_rec *insert_rec)
{
int i, insert_index, next_free, has_empty, num_bytes;
u32 insert_cpos = le32_to_cpu(insert_rec->e_cpos);
struct ocfs2_extent_rec *rec;
next_free = le16_to_cpu(el->l_next_free_rec);
has_empty = ocfs2_is_empty_extent(&el->l_recs[0]);
BUG_ON(!next_free);
/* The tree code before us didn't allow enough room in the leaf. */
BUG_ON(el->l_next_free_rec == el->l_count && !has_empty);
/*
* The easiest way to approach this is to just remove the
* empty extent and temporarily decrement next_free.
*/
if (has_empty) {
/*
* If next_free was 1 (only an empty extent), this
* loop won't execute, which is fine. We still want
* the decrement above to happen.
*/
for(i = 0; i < (next_free - 1); i++)
el->l_recs[i] = el->l_recs[i+1];
next_free--;
}
/*
* Figure out what the new record index should be.
*/
for(i = 0; i < next_free; i++) {
rec = &el->l_recs[i];
if (insert_cpos < le32_to_cpu(rec->e_cpos))
break;
}
insert_index = i;
mlog(0, "ins %u: index %d, has_empty %d, next_free %d, count %d\n",
insert_cpos, insert_index, has_empty, next_free, le16_to_cpu(el->l_count));
BUG_ON(insert_index < 0);
BUG_ON(insert_index >= le16_to_cpu(el->l_count));
BUG_ON(insert_index > next_free);
/*
* No need to memmove if we're just adding to the tail.
*/
if (insert_index != next_free) {
BUG_ON(next_free >= le16_to_cpu(el->l_count));
num_bytes = next_free - insert_index;
num_bytes *= sizeof(struct ocfs2_extent_rec);
memmove(&el->l_recs[insert_index + 1],
&el->l_recs[insert_index],
num_bytes);
}
/*
* Either we had an empty extent, and need to re-increment or
* there was no empty extent on a non full rightmost leaf node,
* in which case we still need to increment.
*/
next_free++;
el->l_next_free_rec = cpu_to_le16(next_free);
/*
* Make sure none of the math above just messed up our tree.
*/
BUG_ON(le16_to_cpu(el->l_next_free_rec) > le16_to_cpu(el->l_count));
el->l_recs[insert_index] = *insert_rec;
}
static void ocfs2_remove_empty_extent(struct ocfs2_extent_list *el)
{
int size, num_recs = le16_to_cpu(el->l_next_free_rec);
BUG_ON(num_recs == 0);
if (ocfs2_is_empty_extent(&el->l_recs[0])) {
num_recs--;
size = num_recs * sizeof(struct ocfs2_extent_rec);
memmove(&el->l_recs[0], &el->l_recs[1], size);
memset(&el->l_recs[num_recs], 0,
sizeof(struct ocfs2_extent_rec));
el->l_next_free_rec = cpu_to_le16(num_recs);
}
}
/*
* Create an empty extent record .
*
* l_next_free_rec may be updated.
*
* If an empty extent already exists do nothing.
*/
static void ocfs2_create_empty_extent(struct ocfs2_extent_list *el)
{
int next_free = le16_to_cpu(el->l_next_free_rec);
BUG_ON(le16_to_cpu(el->l_tree_depth) != 0);
if (next_free == 0)
goto set_and_inc;
if (ocfs2_is_empty_extent(&el->l_recs[0]))
return;
mlog_bug_on_msg(el->l_count == el->l_next_free_rec,
"Asked to create an empty extent in a full list:\n"
"count = %u, tree depth = %u",
le16_to_cpu(el->l_count),
le16_to_cpu(el->l_tree_depth));
ocfs2_shift_records_right(el);
set_and_inc:
le16_add_cpu(&el->l_next_free_rec, 1);
memset(&el->l_recs[0], 0, sizeof(struct ocfs2_extent_rec));
}
/*
* For a rotation which involves two leaf nodes, the "root node" is
* the lowest level tree node which contains a path to both leafs. This
* resulting set of information can be used to form a complete "subtree"
*
* This function is passed two full paths from the dinode down to a
* pair of adjacent leaves. It's task is to figure out which path
* index contains the subtree root - this can be the root index itself
* in a worst-case rotation.
*
* The array index of the subtree root is passed back.
*/
static int ocfs2_find_subtree_root(struct ocfs2_extent_tree *et,
struct ocfs2_path *left,
struct ocfs2_path *right)
{
int i = 0;
/*
* Check that the caller passed in two paths from the same tree.
*/
BUG_ON(path_root_bh(left) != path_root_bh(right));
do {
i++;
/*
* The caller didn't pass two adjacent paths.
*/
mlog_bug_on_msg(i > left->p_tree_depth,
"Owner %llu, left depth %u, right depth %u\n"
"left leaf blk %llu, right leaf blk %llu\n",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
left->p_tree_depth, right->p_tree_depth,
(unsigned long long)path_leaf_bh(left)->b_blocknr,
(unsigned long long)path_leaf_bh(right)->b_blocknr);
} while (left->p_node[i].bh->b_blocknr ==
right->p_node[i].bh->b_blocknr);
return i - 1;
}
typedef void (path_insert_t)(void *, struct buffer_head *);
/*
* Traverse a btree path in search of cpos, starting at root_el.
*
* This code can be called with a cpos larger than the tree, in which
* case it will return the rightmost path.
*/
static int __ocfs2_find_path(struct ocfs2_caching_info *ci,
struct ocfs2_extent_list *root_el, u32 cpos,
path_insert_t *func, void *data)
{
int i, ret = 0;
u32 range;
u64 blkno;
struct buffer_head *bh = NULL;
struct ocfs2_extent_block *eb;
struct ocfs2_extent_list *el;
struct ocfs2_extent_rec *rec;
el = root_el;
while (el->l_tree_depth) {
if (le16_to_cpu(el->l_next_free_rec) == 0) {
ocfs2_error(ocfs2_metadata_cache_get_super(ci),
"Owner %llu has empty extent list at "
"depth %u\n",
(unsigned long long)ocfs2_metadata_cache_owner(ci),
le16_to_cpu(el->l_tree_depth));
ret = -EROFS;
goto out;
}
for(i = 0; i < le16_to_cpu(el->l_next_free_rec) - 1; i++) {
rec = &el->l_recs[i];
/*
* In the case that cpos is off the allocation
* tree, this should just wind up returning the
* rightmost record.
*/
range = le32_to_cpu(rec->e_cpos) +
ocfs2_rec_clusters(el, rec);
if (cpos >= le32_to_cpu(rec->e_cpos) && cpos < range)
break;
}
blkno = le64_to_cpu(el->l_recs[i].e_blkno);
if (blkno == 0) {
ocfs2_error(ocfs2_metadata_cache_get_super(ci),
"Owner %llu has bad blkno in extent list "
"at depth %u (index %d)\n",
(unsigned long long)ocfs2_metadata_cache_owner(ci),
le16_to_cpu(el->l_tree_depth), i);
ret = -EROFS;
goto out;
}
brelse(bh);
bh = NULL;
ret = ocfs2_read_extent_block(ci, blkno, &bh);
if (ret) {
mlog_errno(ret);
goto out;
}
eb = (struct ocfs2_extent_block *) bh->b_data;
el = &eb->h_list;
if (le16_to_cpu(el->l_next_free_rec) >
le16_to_cpu(el->l_count)) {
ocfs2_error(ocfs2_metadata_cache_get_super(ci),
"Owner %llu has bad count in extent list "
"at block %llu (next free=%u, count=%u)\n",
(unsigned long long)ocfs2_metadata_cache_owner(ci),
(unsigned long long)bh->b_blocknr,
le16_to_cpu(el->l_next_free_rec),
le16_to_cpu(el->l_count));
ret = -EROFS;
goto out;
}
if (func)
func(data, bh);
}
out:
/*
* Catch any trailing bh that the loop didn't handle.
*/
brelse(bh);
return ret;
}
/*
* Given an initialized path (that is, it has a valid root extent
* list), this function will traverse the btree in search of the path
* which would contain cpos.
*
* The path traveled is recorded in the path structure.
*
* Note that this will not do any comparisons on leaf node extent
* records, so it will work fine in the case that we just added a tree
* branch.
*/
struct find_path_data {
int index;
struct ocfs2_path *path;
};
static void find_path_ins(void *data, struct buffer_head *bh)
{
struct find_path_data *fp = data;
get_bh(bh);
ocfs2_path_insert_eb(fp->path, fp->index, bh);
fp->index++;
}
int ocfs2_find_path(struct ocfs2_caching_info *ci,
struct ocfs2_path *path, u32 cpos)
{
struct find_path_data data;
data.index = 1;
data.path = path;
return __ocfs2_find_path(ci, path_root_el(path), cpos,
find_path_ins, &data);
}
static void find_leaf_ins(void *data, struct buffer_head *bh)
{
struct ocfs2_extent_block *eb =(struct ocfs2_extent_block *)bh->b_data;
struct ocfs2_extent_list *el = &eb->h_list;
struct buffer_head **ret = data;
/* We want to retain only the leaf block. */
if (le16_to_cpu(el->l_tree_depth) == 0) {
get_bh(bh);
*ret = bh;
}
}
/*
* Find the leaf block in the tree which would contain cpos. No
* checking of the actual leaf is done.
*
* Some paths want to call this instead of allocating a path structure
* and calling ocfs2_find_path().
*
* This function doesn't handle non btree extent lists.
*/
int ocfs2_find_leaf(struct ocfs2_caching_info *ci,
struct ocfs2_extent_list *root_el, u32 cpos,
struct buffer_head **leaf_bh)
{
int ret;
struct buffer_head *bh = NULL;
ret = __ocfs2_find_path(ci, root_el, cpos, find_leaf_ins, &bh);
if (ret) {
mlog_errno(ret);
goto out;
}
*leaf_bh = bh;
out:
return ret;
}
/*
* Adjust the adjacent records (left_rec, right_rec) involved in a rotation.
*
* Basically, we've moved stuff around at the bottom of the tree and
* we need to fix up the extent records above the changes to reflect
* the new changes.
*
* left_rec: the record on the left.
* left_child_el: is the child list pointed to by left_rec
* right_rec: the record to the right of left_rec
* right_child_el: is the child list pointed to by right_rec
*
* By definition, this only works on interior nodes.
*/
static void ocfs2_adjust_adjacent_records(struct ocfs2_extent_rec *left_rec,
struct ocfs2_extent_list *left_child_el,
struct ocfs2_extent_rec *right_rec,
struct ocfs2_extent_list *right_child_el)
{
u32 left_clusters, right_end;
/*
* Interior nodes never have holes. Their cpos is the cpos of
* the leftmost record in their child list. Their cluster
* count covers the full theoretical range of their child list
* - the range between their cpos and the cpos of the record
* immediately to their right.
*/
left_clusters = le32_to_cpu(right_child_el->l_recs[0].e_cpos);
if (!ocfs2_rec_clusters(right_child_el, &right_child_el->l_recs[0])) {
BUG_ON(right_child_el->l_tree_depth);
BUG_ON(le16_to_cpu(right_child_el->l_next_free_rec) <= 1);
left_clusters = le32_to_cpu(right_child_el->l_recs[1].e_cpos);
}
left_clusters -= le32_to_cpu(left_rec->e_cpos);
left_rec->e_int_clusters = cpu_to_le32(left_clusters);
/*
* Calculate the rightmost cluster count boundary before
* moving cpos - we will need to adjust clusters after
* updating e_cpos to keep the same highest cluster count.
*/
right_end = le32_to_cpu(right_rec->e_cpos);
right_end += le32_to_cpu(right_rec->e_int_clusters);
right_rec->e_cpos = left_rec->e_cpos;
le32_add_cpu(&right_rec->e_cpos, left_clusters);
right_end -= le32_to_cpu(right_rec->e_cpos);
right_rec->e_int_clusters = cpu_to_le32(right_end);
}
/*
* Adjust the adjacent root node records involved in a
* rotation. left_el_blkno is passed in as a key so that we can easily
* find it's index in the root list.
*/
static void ocfs2_adjust_root_records(struct ocfs2_extent_list *root_el,
struct ocfs2_extent_list *left_el,
struct ocfs2_extent_list *right_el,
u64 left_el_blkno)
{
int i;
BUG_ON(le16_to_cpu(root_el->l_tree_depth) <=
le16_to_cpu(left_el->l_tree_depth));
for(i = 0; i < le16_to_cpu(root_el->l_next_free_rec) - 1; i++) {
if (le64_to_cpu(root_el->l_recs[i].e_blkno) == left_el_blkno)
break;
}
/*
* The path walking code should have never returned a root and
* two paths which are not adjacent.
*/
BUG_ON(i >= (le16_to_cpu(root_el->l_next_free_rec) - 1));
ocfs2_adjust_adjacent_records(&root_el->l_recs[i], left_el,
&root_el->l_recs[i + 1], right_el);
}
/*
* We've changed a leaf block (in right_path) and need to reflect that
* change back up the subtree.
*
* This happens in multiple places:
* - When we've moved an extent record from the left path leaf to the right
* path leaf to make room for an empty extent in the left path leaf.
* - When our insert into the right path leaf is at the leftmost edge
* and requires an update of the path immediately to it's left. This
* can occur at the end of some types of rotation and appending inserts.
* - When we've adjusted the last extent record in the left path leaf and the
* 1st extent record in the right path leaf during cross extent block merge.
*/
static void ocfs2_complete_edge_insert(handle_t *handle,
struct ocfs2_path *left_path,
struct ocfs2_path *right_path,
int subtree_index)
{
int ret, i, idx;
struct ocfs2_extent_list *el, *left_el, *right_el;
struct ocfs2_extent_rec *left_rec, *right_rec;
struct buffer_head *root_bh = left_path->p_node[subtree_index].bh;
/*
* Update the counts and position values within all the
* interior nodes to reflect the leaf rotation we just did.
*
* The root node is handled below the loop.
*
* We begin the loop with right_el and left_el pointing to the
* leaf lists and work our way up.
*
* NOTE: within this loop, left_el and right_el always refer
* to the *child* lists.
*/
left_el = path_leaf_el(left_path);
right_el = path_leaf_el(right_path);
for(i = left_path->p_tree_depth - 1; i > subtree_index; i--) {
mlog(0, "Adjust records at index %u\n", i);
/*
* One nice property of knowing that all of these
* nodes are below the root is that we only deal with
* the leftmost right node record and the rightmost
* left node record.
*/
el = left_path->p_node[i].el;
idx = le16_to_cpu(left_el->l_next_free_rec) - 1;
left_rec = &el->l_recs[idx];
el = right_path->p_node[i].el;
right_rec = &el->l_recs[0];
ocfs2_adjust_adjacent_records(left_rec, left_el, right_rec,
right_el);
ret = ocfs2_journal_dirty(handle, left_path->p_node[i].bh);
if (ret)
mlog_errno(ret);
ret = ocfs2_journal_dirty(handle, right_path->p_node[i].bh);
if (ret)
mlog_errno(ret);
/*
* Setup our list pointers now so that the current
* parents become children in the next iteration.
*/
left_el = left_path->p_node[i].el;
right_el = right_path->p_node[i].el;
}
/*
* At the root node, adjust the two adjacent records which
* begin our path to the leaves.
*/
el = left_path->p_node[subtree_index].el;
left_el = left_path->p_node[subtree_index + 1].el;
right_el = right_path->p_node[subtree_index + 1].el;
ocfs2_adjust_root_records(el, left_el, right_el,
left_path->p_node[subtree_index + 1].bh->b_blocknr);
root_bh = left_path->p_node[subtree_index].bh;
ret = ocfs2_journal_dirty(handle, root_bh);
if (ret)
mlog_errno(ret);
}
static int ocfs2_rotate_subtree_right(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_path *left_path,
struct ocfs2_path *right_path,
int subtree_index)
{
int ret, i;
struct buffer_head *right_leaf_bh;
struct buffer_head *left_leaf_bh = NULL;
struct buffer_head *root_bh;
struct ocfs2_extent_list *right_el, *left_el;
struct ocfs2_extent_rec move_rec;
left_leaf_bh = path_leaf_bh(left_path);
left_el = path_leaf_el(left_path);
if (left_el->l_next_free_rec != left_el->l_count) {
ocfs2_error(ocfs2_metadata_cache_get_super(et->et_ci),
"Inode %llu has non-full interior leaf node %llu"
"(next free = %u)",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
(unsigned long long)left_leaf_bh->b_blocknr,
le16_to_cpu(left_el->l_next_free_rec));
return -EROFS;
}
/*
* This extent block may already have an empty record, so we
* return early if so.
*/
if (ocfs2_is_empty_extent(&left_el->l_recs[0]))
return 0;
root_bh = left_path->p_node[subtree_index].bh;
BUG_ON(root_bh != right_path->p_node[subtree_index].bh);
ret = ocfs2_path_bh_journal_access(handle, et->et_ci, right_path,
subtree_index);
if (ret) {
mlog_errno(ret);
goto out;
}
for(i = subtree_index + 1; i < path_num_items(right_path); i++) {
ret = ocfs2_path_bh_journal_access(handle, et->et_ci,
right_path, i);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_path_bh_journal_access(handle, et->et_ci,
left_path, i);
if (ret) {
mlog_errno(ret);
goto out;
}
}
right_leaf_bh = path_leaf_bh(right_path);
right_el = path_leaf_el(right_path);
/* This is a code error, not a disk corruption. */
mlog_bug_on_msg(!right_el->l_next_free_rec, "Inode %llu: Rotate fails "
"because rightmost leaf block %llu is empty\n",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
(unsigned long long)right_leaf_bh->b_blocknr);
ocfs2_create_empty_extent(right_el);
ret = ocfs2_journal_dirty(handle, right_leaf_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
/* Do the copy now. */
i = le16_to_cpu(left_el->l_next_free_rec) - 1;
move_rec = left_el->l_recs[i];
right_el->l_recs[0] = move_rec;
/*
* Clear out the record we just copied and shift everything
* over, leaving an empty extent in the left leaf.
*
* We temporarily subtract from next_free_rec so that the
* shift will lose the tail record (which is now defunct).
*/
le16_add_cpu(&left_el->l_next_free_rec, -1);
ocfs2_shift_records_right(left_el);
memset(&left_el->l_recs[0], 0, sizeof(struct ocfs2_extent_rec));
le16_add_cpu(&left_el->l_next_free_rec, 1);
ret = ocfs2_journal_dirty(handle, left_leaf_bh);
if (ret) {
mlog_errno(ret);
goto out;
}
ocfs2_complete_edge_insert(handle, left_path, right_path,
subtree_index);
out:
return ret;
}
/*
* Given a full path, determine what cpos value would return us a path
* containing the leaf immediately to the left of the current one.
*
* Will return zero if the path passed in is already the leftmost path.
*/
static int ocfs2_find_cpos_for_left_leaf(struct super_block *sb,
struct ocfs2_path *path, u32 *cpos)
{
int i, j, ret = 0;
u64 blkno;
struct ocfs2_extent_list *el;
BUG_ON(path->p_tree_depth == 0);
*cpos = 0;
blkno = path_leaf_bh(path)->b_blocknr;
/* Start at the tree node just above the leaf and work our way up. */
i = path->p_tree_depth - 1;
while (i >= 0) {
el = path->p_node[i].el;
/*
* Find the extent record just before the one in our
* path.
*/
for(j = 0; j < le16_to_cpu(el->l_next_free_rec); j++) {
if (le64_to_cpu(el->l_recs[j].e_blkno) == blkno) {
if (j == 0) {
if (i == 0) {
/*
* We've determined that the
* path specified is already
* the leftmost one - return a
* cpos of zero.
*/
goto out;
}
/*
* The leftmost record points to our
* leaf - we need to travel up the
* tree one level.
*/
goto next_node;
}
*cpos = le32_to_cpu(el->l_recs[j - 1].e_cpos);
*cpos = *cpos + ocfs2_rec_clusters(el,
&el->l_recs[j - 1]);
*cpos = *cpos - 1;
goto out;
}
}
/*
* If we got here, we never found a valid node where
* the tree indicated one should be.
*/
ocfs2_error(sb,
"Invalid extent tree at extent block %llu\n",
(unsigned long long)blkno);
ret = -EROFS;
goto out;
next_node:
blkno = path->p_node[i].bh->b_blocknr;
i--;
}
out:
return ret;
}
/*
* Extend the transaction by enough credits to complete the rotation,
* and still leave at least the original number of credits allocated
* to this transaction.
*/
static int ocfs2_extend_rotate_transaction(handle_t *handle, int subtree_depth,
int op_credits,
struct ocfs2_path *path)
{
int ret;
int credits = (path->p_tree_depth - subtree_depth) * 2 + 1 + op_credits;
if (handle->h_buffer_credits < credits) {
ret = ocfs2_extend_trans(handle,
credits - handle->h_buffer_credits);
if (ret)
return ret;
if (unlikely(handle->h_buffer_credits < credits))
return ocfs2_extend_trans(handle, credits);
}
return 0;
}
/*
* Trap the case where we're inserting into the theoretical range past
* the _actual_ left leaf range. Otherwise, we'll rotate a record
* whose cpos is less than ours into the right leaf.
*
* It's only necessary to look at the rightmost record of the left
* leaf because the logic that calls us should ensure that the
* theoretical ranges in the path components above the leaves are
* correct.
*/
static int ocfs2_rotate_requires_path_adjustment(struct ocfs2_path *left_path,
u32 insert_cpos)
{
struct ocfs2_extent_list *left_el;
struct ocfs2_extent_rec *rec;
int next_free;
left_el = path_leaf_el(left_path);
next_free = le16_to_cpu(left_el->l_next_free_rec);
rec = &left_el->l_recs[next_free - 1];
if (insert_cpos > le32_to_cpu(rec->e_cpos))
return 1;
return 0;
}
static int ocfs2_leftmost_rec_contains(struct ocfs2_extent_list *el, u32 cpos)
{
int next_free = le16_to_cpu(el->l_next_free_rec);
unsigned int range;
struct ocfs2_extent_rec *rec;
if (next_free == 0)
return 0;
rec = &el->l_recs[0];
if (ocfs2_is_empty_extent(rec)) {
/* Empty list. */
if (next_free == 1)
return 0;
rec = &el->l_recs[1];
}
range = le32_to_cpu(rec->e_cpos) + ocfs2_rec_clusters(el, rec);
if (cpos >= le32_to_cpu(rec->e_cpos) && cpos < range)
return 1;
return 0;
}
/*
* Rotate all the records in a btree right one record, starting at insert_cpos.
*
* The path to the rightmost leaf should be passed in.
*
* The array is assumed to be large enough to hold an entire path (tree depth).
*
* Upon succesful return from this function:
*
* - The 'right_path' array will contain a path to the leaf block
* whose range contains e_cpos.
* - That leaf block will have a single empty extent in list index 0.
* - In the case that the rotation requires a post-insert update,
* *ret_left_path will contain a valid path which can be passed to
* ocfs2_insert_path().
*/
static int ocfs2_rotate_tree_right(handle_t *handle,
struct ocfs2_extent_tree *et,
enum ocfs2_split_type split,
u32 insert_cpos,
struct ocfs2_path *right_path,
struct ocfs2_path **ret_left_path)
{
int ret, start, orig_credits = handle->h_buffer_credits;
u32 cpos;
struct ocfs2_path *left_path = NULL;
struct super_block *sb = ocfs2_metadata_cache_get_super(et->et_ci);
*ret_left_path = NULL;
left_path = ocfs2_new_path_from_path(right_path);
if (!left_path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
ret = ocfs2_find_cpos_for_left_leaf(sb, right_path, &cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
mlog(0, "Insert: %u, first left path cpos: %u\n", insert_cpos, cpos);
/*
* What we want to do here is:
*
* 1) Start with the rightmost path.
*
* 2) Determine a path to the leaf block directly to the left
* of that leaf.
*
* 3) Determine the 'subtree root' - the lowest level tree node
* which contains a path to both leaves.
*
* 4) Rotate the subtree.
*
* 5) Find the next subtree by considering the left path to be
* the new right path.
*
* The check at the top of this while loop also accepts
* insert_cpos == cpos because cpos is only a _theoretical_
* value to get us the left path - insert_cpos might very well
* be filling that hole.
*
* Stop at a cpos of '0' because we either started at the
* leftmost branch (i.e., a tree with one branch and a
* rotation inside of it), or we've gone as far as we can in
* rotating subtrees.
*/
while (cpos && insert_cpos <= cpos) {
mlog(0, "Rotating a tree: ins. cpos: %u, left path cpos: %u\n",
insert_cpos, cpos);
ret = ocfs2_find_path(et->et_ci, left_path, cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
mlog_bug_on_msg(path_leaf_bh(left_path) ==
path_leaf_bh(right_path),
"Owner %llu: error during insert of %u "
"(left path cpos %u) results in two identical "
"paths ending at %llu\n",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
insert_cpos, cpos,
(unsigned long long)
path_leaf_bh(left_path)->b_blocknr);
if (split == SPLIT_NONE &&
ocfs2_rotate_requires_path_adjustment(left_path,
insert_cpos)) {
/*
* We've rotated the tree as much as we
* should. The rest is up to
* ocfs2_insert_path() to complete, after the
* record insertion. We indicate this
* situation by returning the left path.
*
* The reason we don't adjust the records here
* before the record insert is that an error
* later might break the rule where a parent
* record e_cpos will reflect the actual
* e_cpos of the 1st nonempty record of the
* child list.
*/
*ret_left_path = left_path;
goto out_ret_path;
}
start = ocfs2_find_subtree_root(et, left_path, right_path);
mlog(0, "Subtree root at index %d (blk %llu, depth %d)\n",
start,
(unsigned long long) right_path->p_node[start].bh->b_blocknr,
right_path->p_tree_depth);
ret = ocfs2_extend_rotate_transaction(handle, start,
orig_credits, right_path);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_rotate_subtree_right(handle, et, left_path,
right_path, start);
if (ret) {
mlog_errno(ret);
goto out;
}
if (split != SPLIT_NONE &&
ocfs2_leftmost_rec_contains(path_leaf_el(right_path),
insert_cpos)) {
/*
* A rotate moves the rightmost left leaf
* record over to the leftmost right leaf
* slot. If we're doing an extent split
* instead of a real insert, then we have to
* check that the extent to be split wasn't
* just moved over. If it was, then we can
* exit here, passing left_path back -
* ocfs2_split_extent() is smart enough to
* search both leaves.
*/
*ret_left_path = left_path;
goto out_ret_path;
}
/*
* There is no need to re-read the next right path
* as we know that it'll be our current left
* path. Optimize by copying values instead.
*/
ocfs2_mv_path(right_path, left_path);
ret = ocfs2_find_cpos_for_left_leaf(sb, right_path, &cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
}
out:
ocfs2_free_path(left_path);
out_ret_path:
return ret;
}
static int ocfs2_update_edge_lengths(handle_t *handle,
struct ocfs2_extent_tree *et,
int subtree_index, struct ocfs2_path *path)
{
int i, idx, ret;
struct ocfs2_extent_rec *rec;
struct ocfs2_extent_list *el;
struct ocfs2_extent_block *eb;
u32 range;
/*
* In normal tree rotation process, we will never touch the
* tree branch above subtree_index and ocfs2_extend_rotate_transaction
* doesn't reserve the credits for them either.
*
* But we do have a special case here which will update the rightmost
* records for all the bh in the path.
* So we have to allocate extra credits and access them.
*/
ret = ocfs2_extend_trans(handle,
handle->h_buffer_credits + subtree_index);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_journal_access_path(et->et_ci, handle, path);
if (ret) {
mlog_errno(ret);
goto out;
}
/* Path should always be rightmost. */
eb = (struct ocfs2_extent_block *)path_leaf_bh(path)->b_data;
BUG_ON(eb->h_next_leaf_blk != 0ULL);
el = &eb->h_list;
BUG_ON(le16_to_cpu(el->l_next_free_rec) == 0);
idx = le16_to_cpu(el->l_next_free_rec) - 1;
rec = &el->l_recs[idx];
range = le32_to_cpu(rec->e_cpos) + ocfs2_rec_clusters(el, rec);
for (i = 0; i < path->p_tree_depth; i++) {
el = path->p_node[i].el;
idx = le16_to_cpu(el->l_next_free_rec) - 1;
rec = &el->l_recs[idx];
rec->e_int_clusters = cpu_to_le32(range);
le32_add_cpu(&rec->e_int_clusters, -le32_to_cpu(rec->e_cpos));
ocfs2_journal_dirty(handle, path->p_node[i].bh);
}
out:
return ret;
}
static void ocfs2_unlink_path(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_cached_dealloc_ctxt *dealloc,
struct ocfs2_path *path, int unlink_start)
{
int ret, i;
struct ocfs2_extent_block *eb;
struct ocfs2_extent_list *el;
struct buffer_head *bh;
for(i = unlink_start; i < path_num_items(path); i++) {
bh = path->p_node[i].bh;
eb = (struct ocfs2_extent_block *)bh->b_data;
/*
* Not all nodes might have had their final count
* decremented by the caller - handle this here.
*/
el = &eb->h_list;
if (le16_to_cpu(el->l_next_free_rec) > 1) {
mlog(ML_ERROR,
"Inode %llu, attempted to remove extent block "
"%llu with %u records\n",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
(unsigned long long)le64_to_cpu(eb->h_blkno),
le16_to_cpu(el->l_next_free_rec));
ocfs2_journal_dirty(handle, bh);
ocfs2_remove_from_cache(et->et_ci, bh);
continue;
}
el->l_next_free_rec = 0;
memset(&el->l_recs[0], 0, sizeof(struct ocfs2_extent_rec));
ocfs2_journal_dirty(handle, bh);
ret = ocfs2_cache_extent_block_free(dealloc, eb);
if (ret)
mlog_errno(ret);
ocfs2_remove_from_cache(et->et_ci, bh);
}
}
static void ocfs2_unlink_subtree(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_path *left_path,
struct ocfs2_path *right_path,
int subtree_index,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
int i;
struct buffer_head *root_bh = left_path->p_node[subtree_index].bh;
struct ocfs2_extent_list *root_el = left_path->p_node[subtree_index].el;
struct ocfs2_extent_list *el;
struct ocfs2_extent_block *eb;
el = path_leaf_el(left_path);
eb = (struct ocfs2_extent_block *)right_path->p_node[subtree_index + 1].bh->b_data;
for(i = 1; i < le16_to_cpu(root_el->l_next_free_rec); i++)
if (root_el->l_recs[i].e_blkno == eb->h_blkno)
break;
BUG_ON(i >= le16_to_cpu(root_el->l_next_free_rec));
memset(&root_el->l_recs[i], 0, sizeof(struct ocfs2_extent_rec));
le16_add_cpu(&root_el->l_next_free_rec, -1);
eb = (struct ocfs2_extent_block *)path_leaf_bh(left_path)->b_data;
eb->h_next_leaf_blk = 0;
ocfs2_journal_dirty(handle, root_bh);
ocfs2_journal_dirty(handle, path_leaf_bh(left_path));
ocfs2_unlink_path(handle, et, dealloc, right_path,
subtree_index + 1);
}
static int ocfs2_rotate_subtree_left(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_path *left_path,
struct ocfs2_path *right_path,
int subtree_index,
struct ocfs2_cached_dealloc_ctxt *dealloc,
int *deleted)
{
int ret, i, del_right_subtree = 0, right_has_empty = 0;
struct buffer_head *root_bh, *et_root_bh = path_root_bh(right_path);
struct ocfs2_extent_list *right_leaf_el, *left_leaf_el;
struct ocfs2_extent_block *eb;
*deleted = 0;
right_leaf_el = path_leaf_el(right_path);
left_leaf_el = path_leaf_el(left_path);
root_bh = left_path->p_node[subtree_index].bh;
BUG_ON(root_bh != right_path->p_node[subtree_index].bh);
if (!ocfs2_is_empty_extent(&left_leaf_el->l_recs[0]))
return 0;
eb = (struct ocfs2_extent_block *)path_leaf_bh(right_path)->b_data;
if (ocfs2_is_empty_extent(&right_leaf_el->l_recs[0])) {
/*
* It's legal for us to proceed if the right leaf is
* the rightmost one and it has an empty extent. There
* are two cases to handle - whether the leaf will be
* empty after removal or not. If the leaf isn't empty
* then just remove the empty extent up front. The
* next block will handle empty leaves by flagging
* them for unlink.
*
* Non rightmost leaves will throw -EAGAIN and the
* caller can manually move the subtree and retry.
*/
if (eb->h_next_leaf_blk != 0ULL)
return -EAGAIN;
if (le16_to_cpu(right_leaf_el->l_next_free_rec) > 1) {
ret = ocfs2_journal_access_eb(handle, et->et_ci,
path_leaf_bh(right_path),
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out;
}
ocfs2_remove_empty_extent(right_leaf_el);
} else
right_has_empty = 1;
}
if (eb->h_next_leaf_blk == 0ULL &&
le16_to_cpu(right_leaf_el->l_next_free_rec) == 1) {
/*
* We have to update i_last_eb_blk during the meta
* data delete.
*/
ret = ocfs2_et_root_journal_access(handle, et,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out;
}
del_right_subtree = 1;
}
/*
* Getting here with an empty extent in the right path implies
* that it's the rightmost path and will be deleted.
*/
BUG_ON(right_has_empty && !del_right_subtree);
ret = ocfs2_path_bh_journal_access(handle, et->et_ci, right_path,
subtree_index);
if (ret) {
mlog_errno(ret);
goto out;
}
for(i = subtree_index + 1; i < path_num_items(right_path); i++) {
ret = ocfs2_path_bh_journal_access(handle, et->et_ci,
right_path, i);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_path_bh_journal_access(handle, et->et_ci,
left_path, i);
if (ret) {
mlog_errno(ret);
goto out;
}
}
if (!right_has_empty) {
/*
* Only do this if we're moving a real
* record. Otherwise, the action is delayed until
* after removal of the right path in which case we
* can do a simple shift to remove the empty extent.
*/
ocfs2_rotate_leaf(left_leaf_el, &right_leaf_el->l_recs[0]);
memset(&right_leaf_el->l_recs[0], 0,
sizeof(struct ocfs2_extent_rec));
}
if (eb->h_next_leaf_blk == 0ULL) {
/*
* Move recs over to get rid of empty extent, decrease
* next_free. This is allowed to remove the last
* extent in our leaf (setting l_next_free_rec to
* zero) - the delete code below won't care.
*/
ocfs2_remove_empty_extent(right_leaf_el);
}
ret = ocfs2_journal_dirty(handle, path_leaf_bh(left_path));
if (ret)
mlog_errno(ret);
ret = ocfs2_journal_dirty(handle, path_leaf_bh(right_path));
if (ret)
mlog_errno(ret);
if (del_right_subtree) {
ocfs2_unlink_subtree(handle, et, left_path, right_path,
subtree_index, dealloc);
ret = ocfs2_update_edge_lengths(handle, et, subtree_index,
left_path);
if (ret) {
mlog_errno(ret);
goto out;
}
eb = (struct ocfs2_extent_block *)path_leaf_bh(left_path)->b_data;
ocfs2_et_set_last_eb_blk(et, le64_to_cpu(eb->h_blkno));
/*
* Removal of the extent in the left leaf was skipped
* above so we could delete the right path
* 1st.
*/
if (right_has_empty)
ocfs2_remove_empty_extent(left_leaf_el);
ret = ocfs2_journal_dirty(handle, et_root_bh);
if (ret)
mlog_errno(ret);
*deleted = 1;
} else
ocfs2_complete_edge_insert(handle, left_path, right_path,
subtree_index);
out:
return ret;
}
/*
* Given a full path, determine what cpos value would return us a path
* containing the leaf immediately to the right of the current one.
*
* Will return zero if the path passed in is already the rightmost path.
*
* This looks similar, but is subtly different to
* ocfs2_find_cpos_for_left_leaf().
*/
static int ocfs2_find_cpos_for_right_leaf(struct super_block *sb,
struct ocfs2_path *path, u32 *cpos)
{
int i, j, ret = 0;
u64 blkno;
struct ocfs2_extent_list *el;
*cpos = 0;
if (path->p_tree_depth == 0)
return 0;
blkno = path_leaf_bh(path)->b_blocknr;
/* Start at the tree node just above the leaf and work our way up. */
i = path->p_tree_depth - 1;
while (i >= 0) {
int next_free;
el = path->p_node[i].el;
/*
* Find the extent record just after the one in our
* path.
*/
next_free = le16_to_cpu(el->l_next_free_rec);
for(j = 0; j < le16_to_cpu(el->l_next_free_rec); j++) {
if (le64_to_cpu(el->l_recs[j].e_blkno) == blkno) {
if (j == (next_free - 1)) {
if (i == 0) {
/*
* We've determined that the
* path specified is already
* the rightmost one - return a
* cpos of zero.
*/
goto out;
}
/*
* The rightmost record points to our
* leaf - we need to travel up the
* tree one level.
*/
goto next_node;
}
*cpos = le32_to_cpu(el->l_recs[j + 1].e_cpos);
goto out;
}
}
/*
* If we got here, we never found a valid node where
* the tree indicated one should be.
*/
ocfs2_error(sb,
"Invalid extent tree at extent block %llu\n",
(unsigned long long)blkno);
ret = -EROFS;
goto out;
next_node:
blkno = path->p_node[i].bh->b_blocknr;
i--;
}
out:
return ret;
}
static int ocfs2_rotate_rightmost_leaf_left(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_path *path)
{
int ret;
struct buffer_head *bh = path_leaf_bh(path);
struct ocfs2_extent_list *el = path_leaf_el(path);
if (!ocfs2_is_empty_extent(&el->l_recs[0]))
return 0;
ret = ocfs2_path_bh_journal_access(handle, et->et_ci, path,
path_num_items(path) - 1);
if (ret) {
mlog_errno(ret);
goto out;
}
ocfs2_remove_empty_extent(el);
ret = ocfs2_journal_dirty(handle, bh);
if (ret)
mlog_errno(ret);
out:
return ret;
}
static int __ocfs2_rotate_tree_left(handle_t *handle,
struct ocfs2_extent_tree *et,
int orig_credits,
struct ocfs2_path *path,
struct ocfs2_cached_dealloc_ctxt *dealloc,
struct ocfs2_path **empty_extent_path)
{
int ret, subtree_root, deleted;
u32 right_cpos;
struct ocfs2_path *left_path = NULL;
struct ocfs2_path *right_path = NULL;
struct super_block *sb = ocfs2_metadata_cache_get_super(et->et_ci);
BUG_ON(!ocfs2_is_empty_extent(&(path_leaf_el(path)->l_recs[0])));
*empty_extent_path = NULL;
ret = ocfs2_find_cpos_for_right_leaf(sb, path, &right_cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
left_path = ocfs2_new_path_from_path(path);
if (!left_path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
ocfs2_cp_path(left_path, path);
right_path = ocfs2_new_path_from_path(path);
if (!right_path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
while (right_cpos) {
ret = ocfs2_find_path(et->et_ci, right_path, right_cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
subtree_root = ocfs2_find_subtree_root(et, left_path,
right_path);
mlog(0, "Subtree root at index %d (blk %llu, depth %d)\n",
subtree_root,
(unsigned long long)
right_path->p_node[subtree_root].bh->b_blocknr,
right_path->p_tree_depth);
ret = ocfs2_extend_rotate_transaction(handle, subtree_root,
orig_credits, left_path);
if (ret) {
mlog_errno(ret);
goto out;
}
/*
* Caller might still want to make changes to the
* tree root, so re-add it to the journal here.
*/
ret = ocfs2_path_bh_journal_access(handle, et->et_ci,
left_path, 0);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_rotate_subtree_left(handle, et, left_path,
right_path, subtree_root,
dealloc, &deleted);
if (ret == -EAGAIN) {
/*
* The rotation has to temporarily stop due to
* the right subtree having an empty
* extent. Pass it back to the caller for a
* fixup.
*/
*empty_extent_path = right_path;
right_path = NULL;
goto out;
}
if (ret) {
mlog_errno(ret);
goto out;
}
/*
* The subtree rotate might have removed records on
* the rightmost edge. If so, then rotation is
* complete.
*/
if (deleted)
break;
ocfs2_mv_path(left_path, right_path);
ret = ocfs2_find_cpos_for_right_leaf(sb, left_path,
&right_cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
}
out:
ocfs2_free_path(right_path);
ocfs2_free_path(left_path);
return ret;
}
static int ocfs2_remove_rightmost_path(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_path *path,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
int ret, subtree_index;
u32 cpos;
struct ocfs2_path *left_path = NULL;
struct ocfs2_extent_block *eb;
struct ocfs2_extent_list *el;
ret = ocfs2_et_sanity_check(et);
if (ret)
goto out;
/*
* There's two ways we handle this depending on
* whether path is the only existing one.
*/
ret = ocfs2_extend_rotate_transaction(handle, 0,
handle->h_buffer_credits,
path);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_journal_access_path(et->et_ci, handle, path);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_find_cpos_for_left_leaf(ocfs2_metadata_cache_get_super(et->et_ci),
path, &cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
if (cpos) {
/*
* We have a path to the left of this one - it needs
* an update too.
*/
left_path = ocfs2_new_path_from_path(path);
if (!left_path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
ret = ocfs2_find_path(et->et_ci, left_path, cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_journal_access_path(et->et_ci, handle, left_path);
if (ret) {
mlog_errno(ret);
goto out;
}
subtree_index = ocfs2_find_subtree_root(et, left_path, path);
ocfs2_unlink_subtree(handle, et, left_path, path,
subtree_index, dealloc);
ret = ocfs2_update_edge_lengths(handle, et, subtree_index,
left_path);
if (ret) {
mlog_errno(ret);
goto out;
}
eb = (struct ocfs2_extent_block *)path_leaf_bh(left_path)->b_data;
ocfs2_et_set_last_eb_blk(et, le64_to_cpu(eb->h_blkno));
} else {
/*
* 'path' is also the leftmost path which
* means it must be the only one. This gets
* handled differently because we want to
* revert the root back to having extents
* in-line.
*/
ocfs2_unlink_path(handle, et, dealloc, path, 1);
el = et->et_root_el;
el->l_tree_depth = 0;
el->l_next_free_rec = 0;
memset(&el->l_recs[0], 0, sizeof(struct ocfs2_extent_rec));
ocfs2_et_set_last_eb_blk(et, 0);
}
ocfs2_journal_dirty(handle, path_root_bh(path));
out:
ocfs2_free_path(left_path);
return ret;
}
/*
* Left rotation of btree records.
*
* In many ways, this is (unsurprisingly) the opposite of right
* rotation. We start at some non-rightmost path containing an empty
* extent in the leaf block. The code works its way to the rightmost
* path by rotating records to the left in every subtree.
*
* This is used by any code which reduces the number of extent records
* in a leaf. After removal, an empty record should be placed in the
* leftmost list position.
*
* This won't handle a length update of the rightmost path records if
* the rightmost tree leaf record is removed so the caller is
* responsible for detecting and correcting that.
*/
static int ocfs2_rotate_tree_left(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_path *path,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
int ret, orig_credits = handle->h_buffer_credits;
struct ocfs2_path *tmp_path = NULL, *restart_path = NULL;
struct ocfs2_extent_block *eb;
struct ocfs2_extent_list *el;
el = path_leaf_el(path);
if (!ocfs2_is_empty_extent(&el->l_recs[0]))
return 0;
if (path->p_tree_depth == 0) {
rightmost_no_delete:
/*
* Inline extents. This is trivially handled, so do
* it up front.
*/
ret = ocfs2_rotate_rightmost_leaf_left(handle, et, path);
if (ret)
mlog_errno(ret);
goto out;
}
/*
* Handle rightmost branch now. There's several cases:
* 1) simple rotation leaving records in there. That's trivial.
* 2) rotation requiring a branch delete - there's no more
* records left. Two cases of this:
* a) There are branches to the left.
* b) This is also the leftmost (the only) branch.
*
* 1) is handled via ocfs2_rotate_rightmost_leaf_left()
* 2a) we need the left branch so that we can update it with the unlink
* 2b) we need to bring the root back to inline extents.
*/
eb = (struct ocfs2_extent_block *)path_leaf_bh(path)->b_data;
el = &eb->h_list;
if (eb->h_next_leaf_blk == 0) {
/*
* This gets a bit tricky if we're going to delete the
* rightmost path. Get the other cases out of the way
* 1st.
*/
if (le16_to_cpu(el->l_next_free_rec) > 1)
goto rightmost_no_delete;
if (le16_to_cpu(el->l_next_free_rec) == 0) {
ret = -EIO;
ocfs2_error(ocfs2_metadata_cache_get_super(et->et_ci),
"Owner %llu has empty extent block at %llu",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
(unsigned long long)le64_to_cpu(eb->h_blkno));
goto out;
}
/*
* XXX: The caller can not trust "path" any more after
* this as it will have been deleted. What do we do?
*
* In theory the rotate-for-merge code will never get
* here because it'll always ask for a rotate in a
* nonempty list.
*/
ret = ocfs2_remove_rightmost_path(handle, et, path,
dealloc);
if (ret)
mlog_errno(ret);
goto out;
}
/*
* Now we can loop, remembering the path we get from -EAGAIN
* and restarting from there.
*/
try_rotate:
ret = __ocfs2_rotate_tree_left(handle, et, orig_credits, path,
dealloc, &restart_path);
if (ret && ret != -EAGAIN) {
mlog_errno(ret);
goto out;
}
while (ret == -EAGAIN) {
tmp_path = restart_path;
restart_path = NULL;
ret = __ocfs2_rotate_tree_left(handle, et, orig_credits,
tmp_path, dealloc,
&restart_path);
if (ret && ret != -EAGAIN) {
mlog_errno(ret);
goto out;
}
ocfs2_free_path(tmp_path);
tmp_path = NULL;
if (ret == 0)
goto try_rotate;
}
out:
ocfs2_free_path(tmp_path);
ocfs2_free_path(restart_path);
return ret;
}
static void ocfs2_cleanup_merge(struct ocfs2_extent_list *el,
int index)
{
struct ocfs2_extent_rec *rec = &el->l_recs[index];
unsigned int size;
if (rec->e_leaf_clusters == 0) {
/*
* We consumed all of the merged-from record. An empty
* extent cannot exist anywhere but the 1st array
* position, so move things over if the merged-from
* record doesn't occupy that position.
*
* This creates a new empty extent so the caller
* should be smart enough to have removed any existing
* ones.
*/
if (index > 0) {
BUG_ON(ocfs2_is_empty_extent(&el->l_recs[0]));
size = index * sizeof(struct ocfs2_extent_rec);
memmove(&el->l_recs[1], &el->l_recs[0], size);
}
/*
* Always memset - the caller doesn't check whether it
* created an empty extent, so there could be junk in
* the other fields.
*/
memset(&el->l_recs[0], 0, sizeof(struct ocfs2_extent_rec));
}
}
static int ocfs2_get_right_path(struct ocfs2_extent_tree *et,
struct ocfs2_path *left_path,
struct ocfs2_path **ret_right_path)
{
int ret;
u32 right_cpos;
struct ocfs2_path *right_path = NULL;
struct ocfs2_extent_list *left_el;
*ret_right_path = NULL;
/* This function shouldn't be called for non-trees. */
BUG_ON(left_path->p_tree_depth == 0);
left_el = path_leaf_el(left_path);
BUG_ON(left_el->l_next_free_rec != left_el->l_count);
ret = ocfs2_find_cpos_for_right_leaf(ocfs2_metadata_cache_get_super(et->et_ci),
left_path, &right_cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
/* This function shouldn't be called for the rightmost leaf. */
BUG_ON(right_cpos == 0);
right_path = ocfs2_new_path_from_path(left_path);
if (!right_path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
ret = ocfs2_find_path(et->et_ci, right_path, right_cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
*ret_right_path = right_path;
out:
if (ret)
ocfs2_free_path(right_path);
return ret;
}
/*
* Remove split_rec clusters from the record at index and merge them
* onto the beginning of the record "next" to it.
* For index < l_count - 1, the next means the extent rec at index + 1.
* For index == l_count - 1, the "next" means the 1st extent rec of the
* next extent block.
*/
static int ocfs2_merge_rec_right(struct ocfs2_path *left_path,
handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *split_rec,
int index)
{
int ret, next_free, i;
unsigned int split_clusters = le16_to_cpu(split_rec->e_leaf_clusters);
struct ocfs2_extent_rec *left_rec;
struct ocfs2_extent_rec *right_rec;
struct ocfs2_extent_list *right_el;
struct ocfs2_path *right_path = NULL;
int subtree_index = 0;
struct ocfs2_extent_list *el = path_leaf_el(left_path);
struct buffer_head *bh = path_leaf_bh(left_path);
struct buffer_head *root_bh = NULL;
BUG_ON(index >= le16_to_cpu(el->l_next_free_rec));
left_rec = &el->l_recs[index];
if (index == le16_to_cpu(el->l_next_free_rec) - 1 &&
le16_to_cpu(el->l_next_free_rec) == le16_to_cpu(el->l_count)) {
/* we meet with a cross extent block merge. */
ret = ocfs2_get_right_path(et, left_path, &right_path);
if (ret) {
mlog_errno(ret);
goto out;
}
right_el = path_leaf_el(right_path);
next_free = le16_to_cpu(right_el->l_next_free_rec);
BUG_ON(next_free <= 0);
right_rec = &right_el->l_recs[0];
if (ocfs2_is_empty_extent(right_rec)) {
BUG_ON(next_free <= 1);
right_rec = &right_el->l_recs[1];
}
BUG_ON(le32_to_cpu(left_rec->e_cpos) +
le16_to_cpu(left_rec->e_leaf_clusters) !=
le32_to_cpu(right_rec->e_cpos));
subtree_index = ocfs2_find_subtree_root(et, left_path,
right_path);
ret = ocfs2_extend_rotate_transaction(handle, subtree_index,
handle->h_buffer_credits,
right_path);
if (ret) {
mlog_errno(ret);
goto out;
}
root_bh = left_path->p_node[subtree_index].bh;
BUG_ON(root_bh != right_path->p_node[subtree_index].bh);
ret = ocfs2_path_bh_journal_access(handle, et->et_ci, right_path,
subtree_index);
if (ret) {
mlog_errno(ret);
goto out;
}
for (i = subtree_index + 1;
i < path_num_items(right_path); i++) {
ret = ocfs2_path_bh_journal_access(handle, et->et_ci,
right_path, i);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_path_bh_journal_access(handle, et->et_ci,
left_path, i);
if (ret) {
mlog_errno(ret);
goto out;
}
}
} else {
BUG_ON(index == le16_to_cpu(el->l_next_free_rec) - 1);
right_rec = &el->l_recs[index + 1];
}
ret = ocfs2_path_bh_journal_access(handle, et->et_ci, left_path,
path_num_items(left_path) - 1);
if (ret) {
mlog_errno(ret);
goto out;
}
le16_add_cpu(&left_rec->e_leaf_clusters, -split_clusters);
le32_add_cpu(&right_rec->e_cpos, -split_clusters);
le64_add_cpu(&right_rec->e_blkno,
-ocfs2_clusters_to_blocks(ocfs2_metadata_cache_get_super(et->et_ci),
split_clusters));
le16_add_cpu(&right_rec->e_leaf_clusters, split_clusters);
ocfs2_cleanup_merge(el, index);
ret = ocfs2_journal_dirty(handle, bh);
if (ret)
mlog_errno(ret);
if (right_path) {
ret = ocfs2_journal_dirty(handle, path_leaf_bh(right_path));
if (ret)
mlog_errno(ret);
ocfs2_complete_edge_insert(handle, left_path, right_path,
subtree_index);
}
out:
if (right_path)
ocfs2_free_path(right_path);
return ret;
}
static int ocfs2_get_left_path(struct ocfs2_extent_tree *et,
struct ocfs2_path *right_path,
struct ocfs2_path **ret_left_path)
{
int ret;
u32 left_cpos;
struct ocfs2_path *left_path = NULL;
*ret_left_path = NULL;
/* This function shouldn't be called for non-trees. */
BUG_ON(right_path->p_tree_depth == 0);
ret = ocfs2_find_cpos_for_left_leaf(ocfs2_metadata_cache_get_super(et->et_ci),
right_path, &left_cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
/* This function shouldn't be called for the leftmost leaf. */
BUG_ON(left_cpos == 0);
left_path = ocfs2_new_path_from_path(right_path);
if (!left_path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
ret = ocfs2_find_path(et->et_ci, left_path, left_cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
*ret_left_path = left_path;
out:
if (ret)
ocfs2_free_path(left_path);
return ret;
}
/*
* Remove split_rec clusters from the record at index and merge them
* onto the tail of the record "before" it.
* For index > 0, the "before" means the extent rec at index - 1.
*
* For index == 0, the "before" means the last record of the previous
* extent block. And there is also a situation that we may need to
* remove the rightmost leaf extent block in the right_path and change
* the right path to indicate the new rightmost path.
*/
static int ocfs2_merge_rec_left(struct ocfs2_path *right_path,
handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *split_rec,
struct ocfs2_cached_dealloc_ctxt *dealloc,
int index)
{
int ret, i, subtree_index = 0, has_empty_extent = 0;
unsigned int split_clusters = le16_to_cpu(split_rec->e_leaf_clusters);
struct ocfs2_extent_rec *left_rec;
struct ocfs2_extent_rec *right_rec;
struct ocfs2_extent_list *el = path_leaf_el(right_path);
struct buffer_head *bh = path_leaf_bh(right_path);
struct buffer_head *root_bh = NULL;
struct ocfs2_path *left_path = NULL;
struct ocfs2_extent_list *left_el;
BUG_ON(index < 0);
right_rec = &el->l_recs[index];
if (index == 0) {
/* we meet with a cross extent block merge. */
ret = ocfs2_get_left_path(et, right_path, &left_path);
if (ret) {
mlog_errno(ret);
goto out;
}
left_el = path_leaf_el(left_path);
BUG_ON(le16_to_cpu(left_el->l_next_free_rec) !=
le16_to_cpu(left_el->l_count));
left_rec = &left_el->l_recs[
le16_to_cpu(left_el->l_next_free_rec) - 1];
BUG_ON(le32_to_cpu(left_rec->e_cpos) +
le16_to_cpu(left_rec->e_leaf_clusters) !=
le32_to_cpu(split_rec->e_cpos));
subtree_index = ocfs2_find_subtree_root(et, left_path,
right_path);
ret = ocfs2_extend_rotate_transaction(handle, subtree_index,
handle->h_buffer_credits,
left_path);
if (ret) {
mlog_errno(ret);
goto out;
}
root_bh = left_path->p_node[subtree_index].bh;
BUG_ON(root_bh != right_path->p_node[subtree_index].bh);
ret = ocfs2_path_bh_journal_access(handle, et->et_ci, right_path,
subtree_index);
if (ret) {
mlog_errno(ret);
goto out;
}
for (i = subtree_index + 1;
i < path_num_items(right_path); i++) {
ret = ocfs2_path_bh_journal_access(handle, et->et_ci,
right_path, i);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_path_bh_journal_access(handle, et->et_ci,
left_path, i);
if (ret) {
mlog_errno(ret);
goto out;
}
}
} else {
left_rec = &el->l_recs[index - 1];
if (ocfs2_is_empty_extent(&el->l_recs[0]))
has_empty_extent = 1;
}
ret = ocfs2_path_bh_journal_access(handle, et->et_ci, right_path,
path_num_items(right_path) - 1);
if (ret) {
mlog_errno(ret);
goto out;
}
if (has_empty_extent && index == 1) {
/*
* The easy case - we can just plop the record right in.
*/
*left_rec = *split_rec;
has_empty_extent = 0;
} else
le16_add_cpu(&left_rec->e_leaf_clusters, split_clusters);
le32_add_cpu(&right_rec->e_cpos, split_clusters);
le64_add_cpu(&right_rec->e_blkno,
ocfs2_clusters_to_blocks(ocfs2_metadata_cache_get_super(et->et_ci),
split_clusters));
le16_add_cpu(&right_rec->e_leaf_clusters, -split_clusters);
ocfs2_cleanup_merge(el, index);
ret = ocfs2_journal_dirty(handle, bh);
if (ret)
mlog_errno(ret);
if (left_path) {
ret = ocfs2_journal_dirty(handle, path_leaf_bh(left_path));
if (ret)
mlog_errno(ret);
/*
* In the situation that the right_rec is empty and the extent
* block is empty also, ocfs2_complete_edge_insert can't handle
* it and we need to delete the right extent block.
*/
if (le16_to_cpu(right_rec->e_leaf_clusters) == 0 &&
le16_to_cpu(el->l_next_free_rec) == 1) {
ret = ocfs2_remove_rightmost_path(handle, et,
right_path,
dealloc);
if (ret) {
mlog_errno(ret);
goto out;
}
/* Now the rightmost extent block has been deleted.
* So we use the new rightmost path.
*/
ocfs2_mv_path(right_path, left_path);
left_path = NULL;
} else
ocfs2_complete_edge_insert(handle, left_path,
right_path, subtree_index);
}
out:
if (left_path)
ocfs2_free_path(left_path);
return ret;
}
static int ocfs2_try_to_merge_extent(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_path *path,
int split_index,
struct ocfs2_extent_rec *split_rec,
struct ocfs2_cached_dealloc_ctxt *dealloc,
struct ocfs2_merge_ctxt *ctxt)
{
int ret = 0;
struct ocfs2_extent_list *el = path_leaf_el(path);
struct ocfs2_extent_rec *rec = &el->l_recs[split_index];
BUG_ON(ctxt->c_contig_type == CONTIG_NONE);
if (ctxt->c_split_covers_rec && ctxt->c_has_empty_extent) {
/*
* The merge code will need to create an empty
* extent to take the place of the newly
* emptied slot. Remove any pre-existing empty
* extents - having more than one in a leaf is
* illegal.
*/
ret = ocfs2_rotate_tree_left(handle, et, path, dealloc);
if (ret) {
mlog_errno(ret);
goto out;
}
split_index--;
rec = &el->l_recs[split_index];
}
if (ctxt->c_contig_type == CONTIG_LEFTRIGHT) {
/*
* Left-right contig implies this.
*/
BUG_ON(!ctxt->c_split_covers_rec);
/*
* Since the leftright insert always covers the entire
* extent, this call will delete the insert record
* entirely, resulting in an empty extent record added to
* the extent block.
*
* Since the adding of an empty extent shifts
* everything back to the right, there's no need to
* update split_index here.
*
* When the split_index is zero, we need to merge it to the
* prevoius extent block. It is more efficient and easier
* if we do merge_right first and merge_left later.
*/
ret = ocfs2_merge_rec_right(path, handle, et, split_rec,
split_index);
if (ret) {
mlog_errno(ret);
goto out;
}
/*
* We can only get this from logic error above.
*/
BUG_ON(!ocfs2_is_empty_extent(&el->l_recs[0]));
/* The merge left us with an empty extent, remove it. */
ret = ocfs2_rotate_tree_left(handle, et, path, dealloc);
if (ret) {
mlog_errno(ret);
goto out;
}
rec = &el->l_recs[split_index];
/*
* Note that we don't pass split_rec here on purpose -
* we've merged it into the rec already.
*/
ret = ocfs2_merge_rec_left(path, handle, et, rec,
dealloc, split_index);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_rotate_tree_left(handle, et, path, dealloc);
/*
* Error from this last rotate is not critical, so
* print but don't bubble it up.
*/
if (ret)
mlog_errno(ret);
ret = 0;
} else {
/*
* Merge a record to the left or right.
*
* 'contig_type' is relative to the existing record,
* so for example, if we're "right contig", it's to
* the record on the left (hence the left merge).
*/
if (ctxt->c_contig_type == CONTIG_RIGHT) {
ret = ocfs2_merge_rec_left(path, handle, et,
split_rec, dealloc,
split_index);
if (ret) {
mlog_errno(ret);
goto out;
}
} else {
ret = ocfs2_merge_rec_right(path, handle,
et, split_rec,
split_index);
if (ret) {
mlog_errno(ret);
goto out;
}
}
if (ctxt->c_split_covers_rec) {
/*
* The merge may have left an empty extent in
* our leaf. Try to rotate it away.
*/
ret = ocfs2_rotate_tree_left(handle, et, path,
dealloc);
if (ret)
mlog_errno(ret);
ret = 0;
}
}
out:
return ret;
}
static void ocfs2_subtract_from_rec(struct super_block *sb,
enum ocfs2_split_type split,
struct ocfs2_extent_rec *rec,
struct ocfs2_extent_rec *split_rec)
{
u64 len_blocks;
len_blocks = ocfs2_clusters_to_blocks(sb,
le16_to_cpu(split_rec->e_leaf_clusters));
if (split == SPLIT_LEFT) {
/*
* Region is on the left edge of the existing
* record.
*/
le32_add_cpu(&rec->e_cpos,
le16_to_cpu(split_rec->e_leaf_clusters));
le64_add_cpu(&rec->e_blkno, len_blocks);
le16_add_cpu(&rec->e_leaf_clusters,
-le16_to_cpu(split_rec->e_leaf_clusters));
} else {
/*
* Region is on the right edge of the existing
* record.
*/
le16_add_cpu(&rec->e_leaf_clusters,
-le16_to_cpu(split_rec->e_leaf_clusters));
}
}
/*
* Do the final bits of extent record insertion at the target leaf
* list. If this leaf is part of an allocation tree, it is assumed
* that the tree above has been prepared.
*/
static void ocfs2_insert_at_leaf(struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *insert_rec,
struct ocfs2_extent_list *el,
struct ocfs2_insert_type *insert)
{
int i = insert->ins_contig_index;
unsigned int range;
struct ocfs2_extent_rec *rec;
BUG_ON(le16_to_cpu(el->l_tree_depth) != 0);
if (insert->ins_split != SPLIT_NONE) {
i = ocfs2_search_extent_list(el, le32_to_cpu(insert_rec->e_cpos));
BUG_ON(i == -1);
rec = &el->l_recs[i];
ocfs2_subtract_from_rec(ocfs2_metadata_cache_get_super(et->et_ci),
insert->ins_split, rec,
insert_rec);
goto rotate;
}
/*
* Contiguous insert - either left or right.
*/
if (insert->ins_contig != CONTIG_NONE) {
rec = &el->l_recs[i];
if (insert->ins_contig == CONTIG_LEFT) {
rec->e_blkno = insert_rec->e_blkno;
rec->e_cpos = insert_rec->e_cpos;
}
le16_add_cpu(&rec->e_leaf_clusters,
le16_to_cpu(insert_rec->e_leaf_clusters));
return;
}
/*
* Handle insert into an empty leaf.
*/
if (le16_to_cpu(el->l_next_free_rec) == 0 ||
((le16_to_cpu(el->l_next_free_rec) == 1) &&
ocfs2_is_empty_extent(&el->l_recs[0]))) {
el->l_recs[0] = *insert_rec;
el->l_next_free_rec = cpu_to_le16(1);
return;
}
/*
* Appending insert.
*/
if (insert->ins_appending == APPEND_TAIL) {
i = le16_to_cpu(el->l_next_free_rec) - 1;
rec = &el->l_recs[i];
range = le32_to_cpu(rec->e_cpos)
+ le16_to_cpu(rec->e_leaf_clusters);
BUG_ON(le32_to_cpu(insert_rec->e_cpos) < range);
mlog_bug_on_msg(le16_to_cpu(el->l_next_free_rec) >=
le16_to_cpu(el->l_count),
"owner %llu, depth %u, count %u, next free %u, "
"rec.cpos %u, rec.clusters %u, "
"insert.cpos %u, insert.clusters %u\n",
ocfs2_metadata_cache_owner(et->et_ci),
le16_to_cpu(el->l_tree_depth),
le16_to_cpu(el->l_count),
le16_to_cpu(el->l_next_free_rec),
le32_to_cpu(el->l_recs[i].e_cpos),
le16_to_cpu(el->l_recs[i].e_leaf_clusters),
le32_to_cpu(insert_rec->e_cpos),
le16_to_cpu(insert_rec->e_leaf_clusters));
i++;
el->l_recs[i] = *insert_rec;
le16_add_cpu(&el->l_next_free_rec, 1);
return;
}
rotate:
/*
* Ok, we have to rotate.
*
* At this point, it is safe to assume that inserting into an
* empty leaf and appending to a leaf have both been handled
* above.
*
* This leaf needs to have space, either by the empty 1st
* extent record, or by virtue of an l_next_rec < l_count.
*/
ocfs2_rotate_leaf(el, insert_rec);
}
static void ocfs2_adjust_rightmost_records(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_path *path,
struct ocfs2_extent_rec *insert_rec)
{
int ret, i, next_free;
struct buffer_head *bh;
struct ocfs2_extent_list *el;
struct ocfs2_extent_rec *rec;
/*
* Update everything except the leaf block.
*/
for (i = 0; i < path->p_tree_depth; i++) {
bh = path->p_node[i].bh;
el = path->p_node[i].el;
next_free = le16_to_cpu(el->l_next_free_rec);
if (next_free == 0) {
ocfs2_error(ocfs2_metadata_cache_get_super(et->et_ci),
"Owner %llu has a bad extent list",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci));
ret = -EIO;
return;
}
rec = &el->l_recs[next_free - 1];
rec->e_int_clusters = insert_rec->e_cpos;
le32_add_cpu(&rec->e_int_clusters,
le16_to_cpu(insert_rec->e_leaf_clusters));
le32_add_cpu(&rec->e_int_clusters,
-le32_to_cpu(rec->e_cpos));
ret = ocfs2_journal_dirty(handle, bh);
if (ret)
mlog_errno(ret);
}
}
static int ocfs2_append_rec_to_path(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *insert_rec,
struct ocfs2_path *right_path,
struct ocfs2_path **ret_left_path)
{
int ret, next_free;
struct ocfs2_extent_list *el;
struct ocfs2_path *left_path = NULL;
*ret_left_path = NULL;
/*
* This shouldn't happen for non-trees. The extent rec cluster
* count manipulation below only works for interior nodes.
*/
BUG_ON(right_path->p_tree_depth == 0);
/*
* If our appending insert is at the leftmost edge of a leaf,
* then we might need to update the rightmost records of the
* neighboring path.
*/
el = path_leaf_el(right_path);
next_free = le16_to_cpu(el->l_next_free_rec);
if (next_free == 0 ||
(next_free == 1 && ocfs2_is_empty_extent(&el->l_recs[0]))) {
u32 left_cpos;
ret = ocfs2_find_cpos_for_left_leaf(ocfs2_metadata_cache_get_super(et->et_ci),
right_path, &left_cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
mlog(0, "Append may need a left path update. cpos: %u, "
"left_cpos: %u\n", le32_to_cpu(insert_rec->e_cpos),
left_cpos);
/*
* No need to worry if the append is already in the
* leftmost leaf.
*/
if (left_cpos) {
left_path = ocfs2_new_path_from_path(right_path);
if (!left_path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
ret = ocfs2_find_path(et->et_ci, left_path,
left_cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
/*
* ocfs2_insert_path() will pass the left_path to the
* journal for us.
*/
}
}
ret = ocfs2_journal_access_path(et->et_ci, handle, right_path);
if (ret) {
mlog_errno(ret);
goto out;
}
ocfs2_adjust_rightmost_records(handle, et, right_path, insert_rec);
*ret_left_path = left_path;
ret = 0;
out:
if (ret != 0)
ocfs2_free_path(left_path);
return ret;
}
static void ocfs2_split_record(struct ocfs2_extent_tree *et,
struct ocfs2_path *left_path,
struct ocfs2_path *right_path,
struct ocfs2_extent_rec *split_rec,
enum ocfs2_split_type split)
{
int index;
u32 cpos = le32_to_cpu(split_rec->e_cpos);
struct ocfs2_extent_list *left_el = NULL, *right_el, *insert_el, *el;
struct ocfs2_extent_rec *rec, *tmprec;
right_el = path_leaf_el(right_path);
if (left_path)
left_el = path_leaf_el(left_path);
el = right_el;
insert_el = right_el;
index = ocfs2_search_extent_list(el, cpos);
if (index != -1) {
if (index == 0 && left_path) {
BUG_ON(ocfs2_is_empty_extent(&el->l_recs[0]));
/*
* This typically means that the record
* started in the left path but moved to the
* right as a result of rotation. We either
* move the existing record to the left, or we
* do the later insert there.
*
* In this case, the left path should always
* exist as the rotate code will have passed
* it back for a post-insert update.
*/
if (split == SPLIT_LEFT) {
/*
* It's a left split. Since we know
* that the rotate code gave us an
* empty extent in the left path, we
* can just do the insert there.
*/
insert_el = left_el;
} else {
/*
* Right split - we have to move the
* existing record over to the left
* leaf. The insert will be into the
* newly created empty extent in the
* right leaf.
*/
tmprec = &right_el->l_recs[index];
ocfs2_rotate_leaf(left_el, tmprec);
el = left_el;
memset(tmprec, 0, sizeof(*tmprec));
index = ocfs2_search_extent_list(left_el, cpos);
BUG_ON(index == -1);
}
}
} else {
BUG_ON(!left_path);
BUG_ON(!ocfs2_is_empty_extent(&left_el->l_recs[0]));
/*
* Left path is easy - we can just allow the insert to
* happen.
*/
el = left_el;
insert_el = left_el;
index = ocfs2_search_extent_list(el, cpos);
BUG_ON(index == -1);
}
rec = &el->l_recs[index];
ocfs2_subtract_from_rec(ocfs2_metadata_cache_get_super(et->et_ci),
split, rec, split_rec);
ocfs2_rotate_leaf(insert_el, split_rec);
}
/*
* This function only does inserts on an allocation b-tree. For tree
* depth = 0, ocfs2_insert_at_leaf() is called directly.
*
* right_path is the path we want to do the actual insert
* in. left_path should only be passed in if we need to update that
* portion of the tree after an edge insert.
*/
static int ocfs2_insert_path(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_path *left_path,
struct ocfs2_path *right_path,
struct ocfs2_extent_rec *insert_rec,
struct ocfs2_insert_type *insert)
{
int ret, subtree_index;
struct buffer_head *leaf_bh = path_leaf_bh(right_path);
if (left_path) {
int credits = handle->h_buffer_credits;
/*
* There's a chance that left_path got passed back to
* us without being accounted for in the
* journal. Extend our transaction here to be sure we
* can change those blocks.
*/
credits += left_path->p_tree_depth;
ret = ocfs2_extend_trans(handle, credits);
if (ret < 0) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_journal_access_path(et->et_ci, handle, left_path);
if (ret < 0) {
mlog_errno(ret);
goto out;
}
}
/*
* Pass both paths to the journal. The majority of inserts
* will be touching all components anyway.
*/
ret = ocfs2_journal_access_path(et->et_ci, handle, right_path);
if (ret < 0) {
mlog_errno(ret);
goto out;
}
if (insert->ins_split != SPLIT_NONE) {
/*
* We could call ocfs2_insert_at_leaf() for some types
* of splits, but it's easier to just let one separate
* function sort it all out.
*/
ocfs2_split_record(et, left_path, right_path,
insert_rec, insert->ins_split);
/*
* Split might have modified either leaf and we don't
* have a guarantee that the later edge insert will
* dirty this for us.
*/
if (left_path)
ret = ocfs2_journal_dirty(handle,
path_leaf_bh(left_path));
if (ret)
mlog_errno(ret);
} else
ocfs2_insert_at_leaf(et, insert_rec, path_leaf_el(right_path),
insert);
ret = ocfs2_journal_dirty(handle, leaf_bh);
if (ret)
mlog_errno(ret);
if (left_path) {
/*
* The rotate code has indicated that we need to fix
* up portions of the tree after the insert.
*
* XXX: Should we extend the transaction here?
*/
subtree_index = ocfs2_find_subtree_root(et, left_path,
right_path);
ocfs2_complete_edge_insert(handle, left_path, right_path,
subtree_index);
}
ret = 0;
out:
return ret;
}
static int ocfs2_do_insert_extent(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_extent_rec *insert_rec,
struct ocfs2_insert_type *type)
{
int ret, rotate = 0;
u32 cpos;
struct ocfs2_path *right_path = NULL;
struct ocfs2_path *left_path = NULL;
struct ocfs2_extent_list *el;
el = et->et_root_el;
ret = ocfs2_et_root_journal_access(handle, et,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out;
}
if (le16_to_cpu(el->l_tree_depth) == 0) {
ocfs2_insert_at_leaf(et, insert_rec, el, type);
goto out_update_clusters;
}
right_path = ocfs2_new_path_from_et(et);
if (!right_path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
/*
* Determine the path to start with. Rotations need the
* rightmost path, everything else can go directly to the
* target leaf.
*/
cpos = le32_to_cpu(insert_rec->e_cpos);
if (type->ins_appending == APPEND_NONE &&
type->ins_contig == CONTIG_NONE) {
rotate = 1;
cpos = UINT_MAX;
}
ret = ocfs2_find_path(et->et_ci, right_path, cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
/*
* Rotations and appends need special treatment - they modify
* parts of the tree's above them.
*
* Both might pass back a path immediate to the left of the
* one being inserted to. This will be cause
* ocfs2_insert_path() to modify the rightmost records of
* left_path to account for an edge insert.
*
* XXX: When modifying this code, keep in mind that an insert
* can wind up skipping both of these two special cases...
*/
if (rotate) {
ret = ocfs2_rotate_tree_right(handle, et, type->ins_split,
le32_to_cpu(insert_rec->e_cpos),
right_path, &left_path);
if (ret) {
mlog_errno(ret);
goto out;
}
/*
* ocfs2_rotate_tree_right() might have extended the
* transaction without re-journaling our tree root.
*/
ret = ocfs2_et_root_journal_access(handle, et,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out;
}
} else if (type->ins_appending == APPEND_TAIL
&& type->ins_contig != CONTIG_LEFT) {
ret = ocfs2_append_rec_to_path(handle, et, insert_rec,
right_path, &left_path);
if (ret) {
mlog_errno(ret);
goto out;
}
}
ret = ocfs2_insert_path(handle, et, left_path, right_path,
insert_rec, type);
if (ret) {
mlog_errno(ret);
goto out;
}
out_update_clusters:
if (type->ins_split == SPLIT_NONE)
ocfs2_et_update_clusters(et,
le16_to_cpu(insert_rec->e_leaf_clusters));
ret = ocfs2_journal_dirty(handle, et->et_root_bh);
if (ret)
mlog_errno(ret);
out:
ocfs2_free_path(left_path);
ocfs2_free_path(right_path);
return ret;
}
static enum ocfs2_contig_type
ocfs2_figure_merge_contig_type(struct ocfs2_extent_tree *et,
struct ocfs2_path *path,
struct ocfs2_extent_list *el, int index,
struct ocfs2_extent_rec *split_rec)
{
int status;
enum ocfs2_contig_type ret = CONTIG_NONE;
u32 left_cpos, right_cpos;
struct ocfs2_extent_rec *rec = NULL;
struct ocfs2_extent_list *new_el;
struct ocfs2_path *left_path = NULL, *right_path = NULL;
struct buffer_head *bh;
struct ocfs2_extent_block *eb;
struct super_block *sb = ocfs2_metadata_cache_get_super(et->et_ci);
if (index > 0) {
rec = &el->l_recs[index - 1];
} else if (path->p_tree_depth > 0) {
status = ocfs2_find_cpos_for_left_leaf(sb, path, &left_cpos);
if (status)
goto out;
if (left_cpos != 0) {
left_path = ocfs2_new_path_from_path(path);
if (!left_path)
goto out;
status = ocfs2_find_path(et->et_ci, left_path,
left_cpos);
if (status)
goto out;
new_el = path_leaf_el(left_path);
if (le16_to_cpu(new_el->l_next_free_rec) !=
le16_to_cpu(new_el->l_count)) {
bh = path_leaf_bh(left_path);
eb = (struct ocfs2_extent_block *)bh->b_data;
ocfs2_error(sb,
"Extent block #%llu has an "
"invalid l_next_free_rec of "
"%d. It should have "
"matched the l_count of %d",
(unsigned long long)le64_to_cpu(eb->h_blkno),
le16_to_cpu(new_el->l_next_free_rec),
le16_to_cpu(new_el->l_count));
status = -EINVAL;
goto out;
}
rec = &new_el->l_recs[
le16_to_cpu(new_el->l_next_free_rec) - 1];
}
}
/*
* We're careful to check for an empty extent record here -
* the merge code will know what to do if it sees one.
*/
if (rec) {
if (index == 1 && ocfs2_is_empty_extent(rec)) {
if (split_rec->e_cpos == el->l_recs[index].e_cpos)
ret = CONTIG_RIGHT;
} else {
ret = ocfs2_et_extent_contig(et, rec, split_rec);
}
}
rec = NULL;
if (index < (le16_to_cpu(el->l_next_free_rec) - 1))
rec = &el->l_recs[index + 1];
else if (le16_to_cpu(el->l_next_free_rec) == le16_to_cpu(el->l_count) &&
path->p_tree_depth > 0) {
status = ocfs2_find_cpos_for_right_leaf(sb, path, &right_cpos);
if (status)
goto out;
if (right_cpos == 0)
goto out;
right_path = ocfs2_new_path_from_path(path);
if (!right_path)
goto out;
status = ocfs2_find_path(et->et_ci, right_path, right_cpos);
if (status)
goto out;
new_el = path_leaf_el(right_path);
rec = &new_el->l_recs[0];
if (ocfs2_is_empty_extent(rec)) {
if (le16_to_cpu(new_el->l_next_free_rec) <= 1) {
bh = path_leaf_bh(right_path);
eb = (struct ocfs2_extent_block *)bh->b_data;
ocfs2_error(sb,
"Extent block #%llu has an "
"invalid l_next_free_rec of %d",
(unsigned long long)le64_to_cpu(eb->h_blkno),
le16_to_cpu(new_el->l_next_free_rec));
status = -EINVAL;
goto out;
}
rec = &new_el->l_recs[1];
}
}
if (rec) {
enum ocfs2_contig_type contig_type;
contig_type = ocfs2_et_extent_contig(et, rec, split_rec);
if (contig_type == CONTIG_LEFT && ret == CONTIG_RIGHT)
ret = CONTIG_LEFTRIGHT;
else if (ret == CONTIG_NONE)
ret = contig_type;
}
out:
if (left_path)
ocfs2_free_path(left_path);
if (right_path)
ocfs2_free_path(right_path);
return ret;
}
static void ocfs2_figure_contig_type(struct ocfs2_extent_tree *et,
struct ocfs2_insert_type *insert,
struct ocfs2_extent_list *el,
struct ocfs2_extent_rec *insert_rec)
{
int i;
enum ocfs2_contig_type contig_type = CONTIG_NONE;
BUG_ON(le16_to_cpu(el->l_tree_depth) != 0);
for(i = 0; i < le16_to_cpu(el->l_next_free_rec); i++) {
contig_type = ocfs2_et_extent_contig(et, &el->l_recs[i],
insert_rec);
if (contig_type != CONTIG_NONE) {
insert->ins_contig_index = i;
break;
}
}
insert->ins_contig = contig_type;
if (insert->ins_contig != CONTIG_NONE) {
struct ocfs2_extent_rec *rec =
&el->l_recs[insert->ins_contig_index];
unsigned int len = le16_to_cpu(rec->e_leaf_clusters) +
le16_to_cpu(insert_rec->e_leaf_clusters);
/*
* Caller might want us to limit the size of extents, don't
* calculate contiguousness if we might exceed that limit.
*/
if (et->et_max_leaf_clusters &&
(len > et->et_max_leaf_clusters))
insert->ins_contig = CONTIG_NONE;
}
}
/*
* This should only be called against the righmost leaf extent list.
*
* ocfs2_figure_appending_type() will figure out whether we'll have to
* insert at the tail of the rightmost leaf.
*
* This should also work against the root extent list for tree's with 0
* depth. If we consider the root extent list to be the rightmost leaf node
* then the logic here makes sense.
*/
static void ocfs2_figure_appending_type(struct ocfs2_insert_type *insert,
struct ocfs2_extent_list *el,
struct ocfs2_extent_rec *insert_rec)
{
int i;
u32 cpos = le32_to_cpu(insert_rec->e_cpos);
struct ocfs2_extent_rec *rec;
insert->ins_appending = APPEND_NONE;
BUG_ON(le16_to_cpu(el->l_tree_depth) != 0);
if (!el->l_next_free_rec)
goto set_tail_append;
if (ocfs2_is_empty_extent(&el->l_recs[0])) {
/* Were all records empty? */
if (le16_to_cpu(el->l_next_free_rec) == 1)
goto set_tail_append;
}
i = le16_to_cpu(el->l_next_free_rec) - 1;
rec = &el->l_recs[i];
if (cpos >=
(le32_to_cpu(rec->e_cpos) + le16_to_cpu(rec->e_leaf_clusters)))
goto set_tail_append;
return;
set_tail_append:
insert->ins_appending = APPEND_TAIL;
}
/*
* Helper function called at the begining of an insert.
*
* This computes a few things that are commonly used in the process of
* inserting into the btree:
* - Whether the new extent is contiguous with an existing one.
* - The current tree depth.
* - Whether the insert is an appending one.
* - The total # of free records in the tree.
*
* All of the information is stored on the ocfs2_insert_type
* structure.
*/
static int ocfs2_figure_insert_type(struct ocfs2_extent_tree *et,
struct buffer_head **last_eb_bh,
struct ocfs2_extent_rec *insert_rec,
int *free_records,
struct ocfs2_insert_type *insert)
{
int ret;
struct ocfs2_extent_block *eb;
struct ocfs2_extent_list *el;
struct ocfs2_path *path = NULL;
struct buffer_head *bh = NULL;
insert->ins_split = SPLIT_NONE;
el = et->et_root_el;
insert->ins_tree_depth = le16_to_cpu(el->l_tree_depth);
if (el->l_tree_depth) {
/*
* If we have tree depth, we read in the
* rightmost extent block ahead of time as
* ocfs2_figure_insert_type() and ocfs2_add_branch()
* may want it later.
*/
ret = ocfs2_read_extent_block(et->et_ci,
ocfs2_et_get_last_eb_blk(et),
&bh);
if (ret) {
mlog_exit(ret);
goto out;
}
eb = (struct ocfs2_extent_block *) bh->b_data;
el = &eb->h_list;
}
/*
* Unless we have a contiguous insert, we'll need to know if
* there is room left in our allocation tree for another
* extent record.
*
* XXX: This test is simplistic, we can search for empty
* extent records too.
*/
*free_records = le16_to_cpu(el->l_count) -
le16_to_cpu(el->l_next_free_rec);
if (!insert->ins_tree_depth) {
ocfs2_figure_contig_type(et, insert, el, insert_rec);
ocfs2_figure_appending_type(insert, el, insert_rec);
return 0;
}
path = ocfs2_new_path_from_et(et);
if (!path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
/*
* In the case that we're inserting past what the tree
* currently accounts for, ocfs2_find_path() will return for
* us the rightmost tree path. This is accounted for below in
* the appending code.
*/
ret = ocfs2_find_path(et->et_ci, path, le32_to_cpu(insert_rec->e_cpos));
if (ret) {
mlog_errno(ret);
goto out;
}
el = path_leaf_el(path);
/*
* Now that we have the path, there's two things we want to determine:
* 1) Contiguousness (also set contig_index if this is so)
*
* 2) Are we doing an append? We can trivially break this up
* into two types of appends: simple record append, or a
* rotate inside the tail leaf.
*/
ocfs2_figure_contig_type(et, insert, el, insert_rec);
/*
* The insert code isn't quite ready to deal with all cases of
* left contiguousness. Specifically, if it's an insert into
* the 1st record in a leaf, it will require the adjustment of
* cluster count on the last record of the path directly to it's
* left. For now, just catch that case and fool the layers
* above us. This works just fine for tree_depth == 0, which
* is why we allow that above.
*/
if (insert->ins_contig == CONTIG_LEFT &&
insert->ins_contig_index == 0)
insert->ins_contig = CONTIG_NONE;
/*
* Ok, so we can simply compare against last_eb to figure out
* whether the path doesn't exist. This will only happen in
* the case that we're doing a tail append, so maybe we can
* take advantage of that information somehow.
*/
if (ocfs2_et_get_last_eb_blk(et) ==
path_leaf_bh(path)->b_blocknr) {
/*
* Ok, ocfs2_find_path() returned us the rightmost
* tree path. This might be an appending insert. There are
* two cases:
* 1) We're doing a true append at the tail:
* -This might even be off the end of the leaf
* 2) We're "appending" by rotating in the tail
*/
ocfs2_figure_appending_type(insert, el, insert_rec);
}
out:
ocfs2_free_path(path);
if (ret == 0)
*last_eb_bh = bh;
else
brelse(bh);
return ret;
}
/*
* Insert an extent into a btree.
*
* The caller needs to update the owning btree's cluster count.
*/
int ocfs2_insert_extent(handle_t *handle,
struct ocfs2_extent_tree *et,
u32 cpos,
u64 start_blk,
u32 new_clusters,
u8 flags,
struct ocfs2_alloc_context *meta_ac)
{
int status;
int uninitialized_var(free_records);
struct buffer_head *last_eb_bh = NULL;
struct ocfs2_insert_type insert = {0, };
struct ocfs2_extent_rec rec;
mlog(0, "add %u clusters at position %u to owner %llu\n",
new_clusters, cpos,
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci));
memset(&rec, 0, sizeof(rec));
rec.e_cpos = cpu_to_le32(cpos);
rec.e_blkno = cpu_to_le64(start_blk);
rec.e_leaf_clusters = cpu_to_le16(new_clusters);
rec.e_flags = flags;
status = ocfs2_et_insert_check(et, &rec);
if (status) {
mlog_errno(status);
goto bail;
}
status = ocfs2_figure_insert_type(et, &last_eb_bh, &rec,
&free_records, &insert);
if (status < 0) {
mlog_errno(status);
goto bail;
}
mlog(0, "Insert.appending: %u, Insert.Contig: %u, "
"Insert.contig_index: %d, Insert.free_records: %d, "
"Insert.tree_depth: %d\n",
insert.ins_appending, insert.ins_contig, insert.ins_contig_index,
free_records, insert.ins_tree_depth);
if (insert.ins_contig == CONTIG_NONE && free_records == 0) {
status = ocfs2_grow_tree(handle, et,
&insert.ins_tree_depth, &last_eb_bh,
meta_ac);
if (status) {
mlog_errno(status);
goto bail;
}
}
/* Finally, we can add clusters. This might rotate the tree for us. */
status = ocfs2_do_insert_extent(handle, et, &rec, &insert);
if (status < 0)
mlog_errno(status);
else
ocfs2_et_extent_map_insert(et, &rec);
bail:
brelse(last_eb_bh);
mlog_exit(status);
return status;
}
/*
* Allcate and add clusters into the extent b-tree.
* The new clusters(clusters_to_add) will be inserted at logical_offset.
* The extent b-tree's root is specified by et, and
* it is not limited to the file storage. Any extent tree can use this
* function if it implements the proper ocfs2_extent_tree.
*/
int ocfs2_add_clusters_in_btree(handle_t *handle,
struct ocfs2_extent_tree *et,
u32 *logical_offset,
u32 clusters_to_add,
int mark_unwritten,
struct ocfs2_alloc_context *data_ac,
struct ocfs2_alloc_context *meta_ac,
enum ocfs2_alloc_restarted *reason_ret)
{
int status = 0;
int free_extents;
enum ocfs2_alloc_restarted reason = RESTART_NONE;
u32 bit_off, num_bits;
u64 block;
u8 flags = 0;
struct ocfs2_super *osb =
OCFS2_SB(ocfs2_metadata_cache_get_super(et->et_ci));
BUG_ON(!clusters_to_add);
if (mark_unwritten)
flags = OCFS2_EXT_UNWRITTEN;
free_extents = ocfs2_num_free_extents(osb, et);
if (free_extents < 0) {
status = free_extents;
mlog_errno(status);
goto leave;
}
/* there are two cases which could cause us to EAGAIN in the
* we-need-more-metadata case:
* 1) we haven't reserved *any*
* 2) we are so fragmented, we've needed to add metadata too
* many times. */
if (!free_extents && !meta_ac) {
mlog(0, "we haven't reserved any metadata!\n");
status = -EAGAIN;
reason = RESTART_META;
goto leave;
} else if ((!free_extents)
&& (ocfs2_alloc_context_bits_left(meta_ac)
< ocfs2_extend_meta_needed(et->et_root_el))) {
mlog(0, "filesystem is really fragmented...\n");
status = -EAGAIN;
reason = RESTART_META;
goto leave;
}
status = __ocfs2_claim_clusters(osb, handle, data_ac, 1,
clusters_to_add, &bit_off, &num_bits);
if (status < 0) {
if (status != -ENOSPC)
mlog_errno(status);
goto leave;
}
BUG_ON(num_bits > clusters_to_add);
/* reserve our write early -- insert_extent may update the tree root */
status = ocfs2_et_root_journal_access(handle, et,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto leave;
}
block = ocfs2_clusters_to_blocks(osb->sb, bit_off);
mlog(0, "Allocating %u clusters at block %u for owner %llu\n",
num_bits, bit_off,
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci));
status = ocfs2_insert_extent(handle, et, *logical_offset, block,
num_bits, flags, meta_ac);
if (status < 0) {
mlog_errno(status);
goto leave;
}
status = ocfs2_journal_dirty(handle, et->et_root_bh);
if (status < 0) {
mlog_errno(status);
goto leave;
}
clusters_to_add -= num_bits;
*logical_offset += num_bits;
if (clusters_to_add) {
mlog(0, "need to alloc once more, wanted = %u\n",
clusters_to_add);
status = -EAGAIN;
reason = RESTART_TRANS;
}
leave:
mlog_exit(status);
if (reason_ret)
*reason_ret = reason;
return status;
}
static void ocfs2_make_right_split_rec(struct super_block *sb,
struct ocfs2_extent_rec *split_rec,
u32 cpos,
struct ocfs2_extent_rec *rec)
{
u32 rec_cpos = le32_to_cpu(rec->e_cpos);
u32 rec_range = rec_cpos + le16_to_cpu(rec->e_leaf_clusters);
memset(split_rec, 0, sizeof(struct ocfs2_extent_rec));
split_rec->e_cpos = cpu_to_le32(cpos);
split_rec->e_leaf_clusters = cpu_to_le16(rec_range - cpos);
split_rec->e_blkno = rec->e_blkno;
le64_add_cpu(&split_rec->e_blkno,
ocfs2_clusters_to_blocks(sb, cpos - rec_cpos));
split_rec->e_flags = rec->e_flags;
}
static int ocfs2_split_and_insert(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_path *path,
struct buffer_head **last_eb_bh,
int split_index,
struct ocfs2_extent_rec *orig_split_rec,
struct ocfs2_alloc_context *meta_ac)
{
int ret = 0, depth;
unsigned int insert_range, rec_range, do_leftright = 0;
struct ocfs2_extent_rec tmprec;
struct ocfs2_extent_list *rightmost_el;
struct ocfs2_extent_rec rec;
struct ocfs2_extent_rec split_rec = *orig_split_rec;
struct ocfs2_insert_type insert;
struct ocfs2_extent_block *eb;
leftright:
/*
* Store a copy of the record on the stack - it might move
* around as the tree is manipulated below.
*/
rec = path_leaf_el(path)->l_recs[split_index];
rightmost_el = et->et_root_el;
depth = le16_to_cpu(rightmost_el->l_tree_depth);
if (depth) {
BUG_ON(!(*last_eb_bh));
eb = (struct ocfs2_extent_block *) (*last_eb_bh)->b_data;
rightmost_el = &eb->h_list;
}
if (le16_to_cpu(rightmost_el->l_next_free_rec) ==
le16_to_cpu(rightmost_el->l_count)) {
ret = ocfs2_grow_tree(handle, et,
&depth, last_eb_bh, meta_ac);
if (ret) {
mlog_errno(ret);
goto out;
}
}
memset(&insert, 0, sizeof(struct ocfs2_insert_type));
insert.ins_appending = APPEND_NONE;
insert.ins_contig = CONTIG_NONE;
insert.ins_tree_depth = depth;
insert_range = le32_to_cpu(split_rec.e_cpos) +
le16_to_cpu(split_rec.e_leaf_clusters);
rec_range = le32_to_cpu(rec.e_cpos) +
le16_to_cpu(rec.e_leaf_clusters);
if (split_rec.e_cpos == rec.e_cpos) {
insert.ins_split = SPLIT_LEFT;
} else if (insert_range == rec_range) {
insert.ins_split = SPLIT_RIGHT;
} else {
/*
* Left/right split. We fake this as a right split
* first and then make a second pass as a left split.
*/
insert.ins_split = SPLIT_RIGHT;
ocfs2_make_right_split_rec(ocfs2_metadata_cache_get_super(et->et_ci),
&tmprec, insert_range, &rec);
split_rec = tmprec;
BUG_ON(do_leftright);
do_leftright = 1;
}
ret = ocfs2_do_insert_extent(handle, et, &split_rec, &insert);
if (ret) {
mlog_errno(ret);
goto out;
}
if (do_leftright == 1) {
u32 cpos;
struct ocfs2_extent_list *el;
do_leftright++;
split_rec = *orig_split_rec;
ocfs2_reinit_path(path, 1);
cpos = le32_to_cpu(split_rec.e_cpos);
ret = ocfs2_find_path(et->et_ci, path, cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
el = path_leaf_el(path);
split_index = ocfs2_search_extent_list(el, cpos);
goto leftright;
}
out:
return ret;
}
static int ocfs2_replace_extent_rec(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_path *path,
struct ocfs2_extent_list *el,
int split_index,
struct ocfs2_extent_rec *split_rec)
{
int ret;
ret = ocfs2_path_bh_journal_access(handle, et->et_ci, path,
path_num_items(path) - 1);
if (ret) {
mlog_errno(ret);
goto out;
}
el->l_recs[split_index] = *split_rec;
ocfs2_journal_dirty(handle, path_leaf_bh(path));
out:
return ret;
}
/*
* Split part or all of the extent record at split_index in the leaf
* pointed to by path. Merge with the contiguous extent record if needed.
*
* Care is taken to handle contiguousness so as to not grow the tree.
*
* meta_ac is not strictly necessary - we only truly need it if growth
* of the tree is required. All other cases will degrade into a less
* optimal tree layout.
*
* last_eb_bh should be the rightmost leaf block for any extent
* btree. Since a split may grow the tree or a merge might shrink it,
* the caller cannot trust the contents of that buffer after this call.
*
* This code is optimized for readability - several passes might be
* made over certain portions of the tree. All of those blocks will
* have been brought into cache (and pinned via the journal), so the
* extra overhead is not expressed in terms of disk reads.
*/
int ocfs2_split_extent(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_path *path,
int split_index,
struct ocfs2_extent_rec *split_rec,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
int ret = 0;
struct ocfs2_extent_list *el = path_leaf_el(path);
struct buffer_head *last_eb_bh = NULL;
struct ocfs2_extent_rec *rec = &el->l_recs[split_index];
struct ocfs2_merge_ctxt ctxt;
struct ocfs2_extent_list *rightmost_el;
if (le32_to_cpu(rec->e_cpos) > le32_to_cpu(split_rec->e_cpos) ||
((le32_to_cpu(rec->e_cpos) + le16_to_cpu(rec->e_leaf_clusters)) <
(le32_to_cpu(split_rec->e_cpos) + le16_to_cpu(split_rec->e_leaf_clusters)))) {
ret = -EIO;
mlog_errno(ret);
goto out;
}
ctxt.c_contig_type = ocfs2_figure_merge_contig_type(et, path, el,
split_index,
split_rec);
/*
* The core merge / split code wants to know how much room is
* left in this allocation tree, so we pass the
* rightmost extent list.
*/
if (path->p_tree_depth) {
struct ocfs2_extent_block *eb;
ret = ocfs2_read_extent_block(et->et_ci,
ocfs2_et_get_last_eb_blk(et),
&last_eb_bh);
if (ret) {
mlog_exit(ret);
goto out;
}
eb = (struct ocfs2_extent_block *) last_eb_bh->b_data;
rightmost_el = &eb->h_list;
} else
rightmost_el = path_root_el(path);
if (rec->e_cpos == split_rec->e_cpos &&
rec->e_leaf_clusters == split_rec->e_leaf_clusters)
ctxt.c_split_covers_rec = 1;
else
ctxt.c_split_covers_rec = 0;
ctxt.c_has_empty_extent = ocfs2_is_empty_extent(&el->l_recs[0]);
mlog(0, "index: %d, contig: %u, has_empty: %u, split_covers: %u\n",
split_index, ctxt.c_contig_type, ctxt.c_has_empty_extent,
ctxt.c_split_covers_rec);
if (ctxt.c_contig_type == CONTIG_NONE) {
if (ctxt.c_split_covers_rec)
ret = ocfs2_replace_extent_rec(handle, et, path, el,
split_index, split_rec);
else
ret = ocfs2_split_and_insert(handle, et, path,
&last_eb_bh, split_index,
split_rec, meta_ac);
if (ret)
mlog_errno(ret);
} else {
ret = ocfs2_try_to_merge_extent(handle, et, path,
split_index, split_rec,
dealloc, &ctxt);
if (ret)
mlog_errno(ret);
}
out:
brelse(last_eb_bh);
return ret;
}
/*
* Change the flags of the already-existing extent at cpos for len clusters.
*
* new_flags: the flags we want to set.
* clear_flags: the flags we want to clear.
* phys: the new physical offset we want this new extent starts from.
*
* If the existing extent is larger than the request, initiate a
* split. An attempt will be made at merging with adjacent extents.
*
* The caller is responsible for passing down meta_ac if we'll need it.
*/
int ocfs2_change_extent_flag(handle_t *handle,
struct ocfs2_extent_tree *et,
u32 cpos, u32 len, u32 phys,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_cached_dealloc_ctxt *dealloc,
int new_flags, int clear_flags)
{
int ret, index;
struct super_block *sb = ocfs2_metadata_cache_get_super(et->et_ci);
u64 start_blkno = ocfs2_clusters_to_blocks(sb, phys);
struct ocfs2_extent_rec split_rec;
struct ocfs2_path *left_path = NULL;
struct ocfs2_extent_list *el;
struct ocfs2_extent_rec *rec;
left_path = ocfs2_new_path_from_et(et);
if (!left_path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
ret = ocfs2_find_path(et->et_ci, left_path, cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
el = path_leaf_el(left_path);
index = ocfs2_search_extent_list(el, cpos);
if (index == -1 || index >= le16_to_cpu(el->l_next_free_rec)) {
ocfs2_error(sb,
"Owner %llu has an extent at cpos %u which can no "
"longer be found.\n",
(unsigned long long)
ocfs2_metadata_cache_owner(et->et_ci), cpos);
ret = -EROFS;
goto out;
}
ret = -EIO;
rec = &el->l_recs[index];
if (new_flags && (rec->e_flags & new_flags)) {
mlog(ML_ERROR, "Owner %llu tried to set %d flags on an "
"extent that already had them",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
new_flags);
goto out;
}
if (clear_flags && !(rec->e_flags & clear_flags)) {
mlog(ML_ERROR, "Owner %llu tried to clear %d flags on an "
"extent that didn't have them",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
clear_flags);
goto out;
}
memset(&split_rec, 0, sizeof(struct ocfs2_extent_rec));
split_rec.e_cpos = cpu_to_le32(cpos);
split_rec.e_leaf_clusters = cpu_to_le16(len);
split_rec.e_blkno = cpu_to_le64(start_blkno);
split_rec.e_flags = rec->e_flags;
if (new_flags)
split_rec.e_flags |= new_flags;
if (clear_flags)
split_rec.e_flags &= ~clear_flags;
ret = ocfs2_split_extent(handle, et, left_path,
index, &split_rec, meta_ac,
dealloc);
if (ret)
mlog_errno(ret);
out:
ocfs2_free_path(left_path);
return ret;
}
/*
* Mark the already-existing extent at cpos as written for len clusters.
* This removes the unwritten extent flag.
*
* If the existing extent is larger than the request, initiate a
* split. An attempt will be made at merging with adjacent extents.
*
* The caller is responsible for passing down meta_ac if we'll need it.
*/
int ocfs2_mark_extent_written(struct inode *inode,
struct ocfs2_extent_tree *et,
handle_t *handle, u32 cpos, u32 len, u32 phys,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
int ret;
mlog(0, "Inode %lu cpos %u, len %u, phys clusters %u\n",
inode->i_ino, cpos, len, phys);
if (!ocfs2_writes_unwritten_extents(OCFS2_SB(inode->i_sb))) {
ocfs2_error(inode->i_sb, "Inode %llu has unwritten extents "
"that are being written to, but the feature bit "
"is not set in the super block.",
(unsigned long long)OCFS2_I(inode)->ip_blkno);
ret = -EROFS;
goto out;
}
/*
* XXX: This should be fixed up so that we just re-insert the
* next extent records.
*/
ocfs2_et_extent_map_truncate(et, 0);
ret = ocfs2_change_extent_flag(handle, et, cpos,
len, phys, meta_ac, dealloc,
0, OCFS2_EXT_UNWRITTEN);
if (ret)
mlog_errno(ret);
out:
return ret;
}
static int ocfs2_split_tree(handle_t *handle, struct ocfs2_extent_tree *et,
struct ocfs2_path *path,
int index, u32 new_range,
struct ocfs2_alloc_context *meta_ac)
{
int ret, depth, credits = handle->h_buffer_credits;
struct buffer_head *last_eb_bh = NULL;
struct ocfs2_extent_block *eb;
struct ocfs2_extent_list *rightmost_el, *el;
struct ocfs2_extent_rec split_rec;
struct ocfs2_extent_rec *rec;
struct ocfs2_insert_type insert;
/*
* Setup the record to split before we grow the tree.
*/
el = path_leaf_el(path);
rec = &el->l_recs[index];
ocfs2_make_right_split_rec(ocfs2_metadata_cache_get_super(et->et_ci),
&split_rec, new_range, rec);
depth = path->p_tree_depth;
if (depth > 0) {
ret = ocfs2_read_extent_block(et->et_ci,
ocfs2_et_get_last_eb_blk(et),
&last_eb_bh);
if (ret < 0) {
mlog_errno(ret);
goto out;
}
eb = (struct ocfs2_extent_block *) last_eb_bh->b_data;
rightmost_el = &eb->h_list;
} else
rightmost_el = path_leaf_el(path);
credits += path->p_tree_depth +
ocfs2_extend_meta_needed(et->et_root_el);
ret = ocfs2_extend_trans(handle, credits);
if (ret) {
mlog_errno(ret);
goto out;
}
if (le16_to_cpu(rightmost_el->l_next_free_rec) ==
le16_to_cpu(rightmost_el->l_count)) {
ret = ocfs2_grow_tree(handle, et, &depth, &last_eb_bh,
meta_ac);
if (ret) {
mlog_errno(ret);
goto out;
}
}
memset(&insert, 0, sizeof(struct ocfs2_insert_type));
insert.ins_appending = APPEND_NONE;
insert.ins_contig = CONTIG_NONE;
insert.ins_split = SPLIT_RIGHT;
insert.ins_tree_depth = depth;
ret = ocfs2_do_insert_extent(handle, et, &split_rec, &insert);
if (ret)
mlog_errno(ret);
out:
brelse(last_eb_bh);
return ret;
}
static int ocfs2_truncate_rec(handle_t *handle,
struct ocfs2_extent_tree *et,
struct ocfs2_path *path, int index,
struct ocfs2_cached_dealloc_ctxt *dealloc,
u32 cpos, u32 len)
{
int ret;
u32 left_cpos, rec_range, trunc_range;
int wants_rotate = 0, is_rightmost_tree_rec = 0;
struct super_block *sb = ocfs2_metadata_cache_get_super(et->et_ci);
struct ocfs2_path *left_path = NULL;
struct ocfs2_extent_list *el = path_leaf_el(path);
struct ocfs2_extent_rec *rec;
struct ocfs2_extent_block *eb;
if (ocfs2_is_empty_extent(&el->l_recs[0]) && index > 0) {
ret = ocfs2_rotate_tree_left(handle, et, path, dealloc);
if (ret) {
mlog_errno(ret);
goto out;
}
index--;
}
if (index == (le16_to_cpu(el->l_next_free_rec) - 1) &&
path->p_tree_depth) {
/*
* Check whether this is the rightmost tree record. If
* we remove all of this record or part of its right
* edge then an update of the record lengths above it
* will be required.
*/
eb = (struct ocfs2_extent_block *)path_leaf_bh(path)->b_data;
if (eb->h_next_leaf_blk == 0)
is_rightmost_tree_rec = 1;
}
rec = &el->l_recs[index];
if (index == 0 && path->p_tree_depth &&
le32_to_cpu(rec->e_cpos) == cpos) {
/*
* Changing the leftmost offset (via partial or whole
* record truncate) of an interior (or rightmost) path
* means we have to update the subtree that is formed
* by this leaf and the one to it's left.
*
* There are two cases we can skip:
* 1) Path is the leftmost one in our btree.
* 2) The leaf is rightmost and will be empty after
* we remove the extent record - the rotate code
* knows how to update the newly formed edge.
*/
ret = ocfs2_find_cpos_for_left_leaf(sb, path, &left_cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
if (left_cpos && le16_to_cpu(el->l_next_free_rec) > 1) {
left_path = ocfs2_new_path_from_path(path);
if (!left_path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
ret = ocfs2_find_path(et->et_ci, left_path,
left_cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
}
}
ret = ocfs2_extend_rotate_transaction(handle, 0,
handle->h_buffer_credits,
path);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_journal_access_path(et->et_ci, handle, path);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_journal_access_path(et->et_ci, handle, left_path);
if (ret) {
mlog_errno(ret);
goto out;
}
rec_range = le32_to_cpu(rec->e_cpos) + ocfs2_rec_clusters(el, rec);
trunc_range = cpos + len;
if (le32_to_cpu(rec->e_cpos) == cpos && rec_range == trunc_range) {
int next_free;
memset(rec, 0, sizeof(*rec));
ocfs2_cleanup_merge(el, index);
wants_rotate = 1;
next_free = le16_to_cpu(el->l_next_free_rec);
if (is_rightmost_tree_rec && next_free > 1) {
/*
* We skip the edge update if this path will
* be deleted by the rotate code.
*/
rec = &el->l_recs[next_free - 1];
ocfs2_adjust_rightmost_records(handle, et, path,
rec);
}
} else if (le32_to_cpu(rec->e_cpos) == cpos) {
/* Remove leftmost portion of the record. */
le32_add_cpu(&rec->e_cpos, len);
le64_add_cpu(&rec->e_blkno, ocfs2_clusters_to_blocks(sb, len));
le16_add_cpu(&rec->e_leaf_clusters, -len);
} else if (rec_range == trunc_range) {
/* Remove rightmost portion of the record */
le16_add_cpu(&rec->e_leaf_clusters, -len);
if (is_rightmost_tree_rec)
ocfs2_adjust_rightmost_records(handle, et, path, rec);
} else {
/* Caller should have trapped this. */
mlog(ML_ERROR, "Owner %llu: Invalid record truncate: (%u, %u) "
"(%u, %u)\n",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
le32_to_cpu(rec->e_cpos),
le16_to_cpu(rec->e_leaf_clusters), cpos, len);
BUG();
}
if (left_path) {
int subtree_index;
subtree_index = ocfs2_find_subtree_root(et, left_path, path);
ocfs2_complete_edge_insert(handle, left_path, path,
subtree_index);
}
ocfs2_journal_dirty(handle, path_leaf_bh(path));
ret = ocfs2_rotate_tree_left(handle, et, path, dealloc);
if (ret) {
mlog_errno(ret);
goto out;
}
out:
ocfs2_free_path(left_path);
return ret;
}
int ocfs2_remove_extent(handle_t *handle,
struct ocfs2_extent_tree *et,
u32 cpos, u32 len,
struct ocfs2_alloc_context *meta_ac,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
int ret, index;
u32 rec_range, trunc_range;
struct ocfs2_extent_rec *rec;
struct ocfs2_extent_list *el;
struct ocfs2_path *path = NULL;
/*
* XXX: Why are we truncating to 0 instead of wherever this
* affects us?
*/
ocfs2_et_extent_map_truncate(et, 0);
path = ocfs2_new_path_from_et(et);
if (!path) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
ret = ocfs2_find_path(et->et_ci, path, cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
el = path_leaf_el(path);
index = ocfs2_search_extent_list(el, cpos);
if (index == -1 || index >= le16_to_cpu(el->l_next_free_rec)) {
ocfs2_error(ocfs2_metadata_cache_get_super(et->et_ci),
"Owner %llu has an extent at cpos %u which can no "
"longer be found.\n",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
cpos);
ret = -EROFS;
goto out;
}
/*
* We have 3 cases of extent removal:
* 1) Range covers the entire extent rec
* 2) Range begins or ends on one edge of the extent rec
* 3) Range is in the middle of the extent rec (no shared edges)
*
* For case 1 we remove the extent rec and left rotate to
* fill the hole.
*
* For case 2 we just shrink the existing extent rec, with a
* tree update if the shrinking edge is also the edge of an
* extent block.
*
* For case 3 we do a right split to turn the extent rec into
* something case 2 can handle.
*/
rec = &el->l_recs[index];
rec_range = le32_to_cpu(rec->e_cpos) + ocfs2_rec_clusters(el, rec);
trunc_range = cpos + len;
BUG_ON(cpos < le32_to_cpu(rec->e_cpos) || trunc_range > rec_range);
mlog(0, "Owner %llu, remove (cpos %u, len %u). Existing index %d "
"(cpos %u, len %u)\n",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
cpos, len, index,
le32_to_cpu(rec->e_cpos), ocfs2_rec_clusters(el, rec));
if (le32_to_cpu(rec->e_cpos) == cpos || rec_range == trunc_range) {
ret = ocfs2_truncate_rec(handle, et, path, index, dealloc,
cpos, len);
if (ret) {
mlog_errno(ret);
goto out;
}
} else {
ret = ocfs2_split_tree(handle, et, path, index,
trunc_range, meta_ac);
if (ret) {
mlog_errno(ret);
goto out;
}
/*
* The split could have manipulated the tree enough to
* move the record location, so we have to look for it again.
*/
ocfs2_reinit_path(path, 1);
ret = ocfs2_find_path(et->et_ci, path, cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
el = path_leaf_el(path);
index = ocfs2_search_extent_list(el, cpos);
if (index == -1 || index >= le16_to_cpu(el->l_next_free_rec)) {
ocfs2_error(ocfs2_metadata_cache_get_super(et->et_ci),
"Owner %llu: split at cpos %u lost record.",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
cpos);
ret = -EROFS;
goto out;
}
/*
* Double check our values here. If anything is fishy,
* it's easier to catch it at the top level.
*/
rec = &el->l_recs[index];
rec_range = le32_to_cpu(rec->e_cpos) +
ocfs2_rec_clusters(el, rec);
if (rec_range != trunc_range) {
ocfs2_error(ocfs2_metadata_cache_get_super(et->et_ci),
"Owner %llu: error after split at cpos %u"
"trunc len %u, existing record is (%u,%u)",
(unsigned long long)ocfs2_metadata_cache_owner(et->et_ci),
cpos, len, le32_to_cpu(rec->e_cpos),
ocfs2_rec_clusters(el, rec));
ret = -EROFS;
goto out;
}
ret = ocfs2_truncate_rec(handle, et, path, index, dealloc,
cpos, len);
if (ret) {
mlog_errno(ret);
goto out;
}
}
out:
ocfs2_free_path(path);
return ret;
}
int ocfs2_remove_btree_range(struct inode *inode,
struct ocfs2_extent_tree *et,
u32 cpos, u32 phys_cpos, u32 len,
struct ocfs2_cached_dealloc_ctxt *dealloc)
{
int ret;
u64 phys_blkno = ocfs2_clusters_to_blocks(inode->i_sb, phys_cpos);
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct inode *tl_inode = osb->osb_tl_inode;
handle_t *handle;
struct ocfs2_alloc_context *meta_ac = NULL;
ret = ocfs2_lock_allocators(inode, et, 0, 1, NULL, &meta_ac);
if (ret) {
mlog_errno(ret);
return ret;
}
mutex_lock(&tl_inode->i_mutex);
if (ocfs2_truncate_log_needs_flush(osb)) {
ret = __ocfs2_flush_truncate_log(osb);
if (ret < 0) {
mlog_errno(ret);
goto out;
}
}
handle = ocfs2_start_trans(osb, ocfs2_remove_extent_credits(osb->sb));
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
goto out;
}
ret = ocfs2_et_root_journal_access(handle, et,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out;
}
vfs_dq_free_space_nodirty(inode,
ocfs2_clusters_to_bytes(inode->i_sb, len));
ret = ocfs2_remove_extent(handle, et, cpos, len, meta_ac, dealloc);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
ocfs2_et_update_clusters(et, -len);
ret = ocfs2_journal_dirty(handle, et->et_root_bh);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
ret = ocfs2_truncate_log_append(osb, handle, phys_blkno, len);
if (ret)
mlog_errno(ret);
out_commit:
ocfs2_commit_trans(osb, handle);
out:
mutex_unlock(&tl_inode->i_mutex);
if (meta_ac)
ocfs2_free_alloc_context(meta_ac);
return ret;
}
int ocfs2_truncate_log_needs_flush(struct ocfs2_super *osb)
{
struct buffer_head *tl_bh = osb->osb_tl_bh;
struct ocfs2_dinode *di;
struct ocfs2_truncate_log *tl;
di = (struct ocfs2_dinode *) tl_bh->b_data;
tl = &di->id2.i_dealloc;
mlog_bug_on_msg(le16_to_cpu(tl->tl_used) > le16_to_cpu(tl->tl_count),
"slot %d, invalid truncate log parameters: used = "
"%u, count = %u\n", osb->slot_num,
le16_to_cpu(tl->tl_used), le16_to_cpu(tl->tl_count));
return le16_to_cpu(tl->tl_used) == le16_to_cpu(tl->tl_count);
}
static int ocfs2_truncate_log_can_coalesce(struct ocfs2_truncate_log *tl,
unsigned int new_start)
{
unsigned int tail_index;
unsigned int current_tail;
/* No records, nothing to coalesce */
if (!le16_to_cpu(tl->tl_used))
return 0;
tail_index = le16_to_cpu(tl->tl_used) - 1;
current_tail = le32_to_cpu(tl->tl_recs[tail_index].t_start);
current_tail += le32_to_cpu(tl->tl_recs[tail_index].t_clusters);
return current_tail == new_start;
}
int ocfs2_truncate_log_append(struct ocfs2_super *osb,
handle_t *handle,
u64 start_blk,
unsigned int num_clusters)
{
int status, index;
unsigned int start_cluster, tl_count;
struct inode *tl_inode = osb->osb_tl_inode;
struct buffer_head *tl_bh = osb->osb_tl_bh;
struct ocfs2_dinode *di;
struct ocfs2_truncate_log *tl;
mlog_entry("start_blk = %llu, num_clusters = %u\n",
(unsigned long long)start_blk, num_clusters);
BUG_ON(mutex_trylock(&tl_inode->i_mutex));
start_cluster = ocfs2_blocks_to_clusters(osb->sb, start_blk);
di = (struct ocfs2_dinode *) tl_bh->b_data;
/* tl_bh is loaded from ocfs2_truncate_log_init(). It's validated
* by the underlying call to ocfs2_read_inode_block(), so any
* corruption is a code bug */
BUG_ON(!OCFS2_IS_VALID_DINODE(di));
tl = &di->id2.i_dealloc;
tl_count = le16_to_cpu(tl->tl_count);
mlog_bug_on_msg(tl_count > ocfs2_truncate_recs_per_inode(osb->sb) ||
tl_count == 0,
"Truncate record count on #%llu invalid "
"wanted %u, actual %u\n",
(unsigned long long)OCFS2_I(tl_inode)->ip_blkno,
ocfs2_truncate_recs_per_inode(osb->sb),
le16_to_cpu(tl->tl_count));
/* Caller should have known to flush before calling us. */
index = le16_to_cpu(tl->tl_used);
if (index >= tl_count) {
status = -ENOSPC;
mlog_errno(status);
goto bail;
}
status = ocfs2_journal_access_di(handle, INODE_CACHE(tl_inode), tl_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto bail;
}
mlog(0, "Log truncate of %u clusters starting at cluster %u to "
"%llu (index = %d)\n", num_clusters, start_cluster,
(unsigned long long)OCFS2_I(tl_inode)->ip_blkno, index);
if (ocfs2_truncate_log_can_coalesce(tl, start_cluster)) {
/*
* Move index back to the record we are coalescing with.
* ocfs2_truncate_log_can_coalesce() guarantees nonzero
*/
index--;
num_clusters += le32_to_cpu(tl->tl_recs[index].t_clusters);
mlog(0, "Coalesce with index %u (start = %u, clusters = %u)\n",
index, le32_to_cpu(tl->tl_recs[index].t_start),
num_clusters);
} else {
tl->tl_recs[index].t_start = cpu_to_le32(start_cluster);
tl->tl_used = cpu_to_le16(index + 1);
}
tl->tl_recs[index].t_clusters = cpu_to_le32(num_clusters);
status = ocfs2_journal_dirty(handle, tl_bh);
if (status < 0) {
mlog_errno(status);
goto bail;
}
bail:
mlog_exit(status);
return status;
}
static int ocfs2_replay_truncate_records(struct ocfs2_super *osb,
handle_t *handle,
struct inode *data_alloc_inode,
struct buffer_head *data_alloc_bh)
{
int status = 0;
int i;
unsigned int num_clusters;
u64 start_blk;
struct ocfs2_truncate_rec rec;
struct ocfs2_dinode *di;
struct ocfs2_truncate_log *tl;
struct inode *tl_inode = osb->osb_tl_inode;
struct buffer_head *tl_bh = osb->osb_tl_bh;
mlog_entry_void();
di = (struct ocfs2_dinode *) tl_bh->b_data;
tl = &di->id2.i_dealloc;
i = le16_to_cpu(tl->tl_used) - 1;
while (i >= 0) {
/* Caller has given us at least enough credits to
* update the truncate log dinode */
status = ocfs2_journal_access_di(handle, INODE_CACHE(tl_inode), tl_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto bail;
}
tl->tl_used = cpu_to_le16(i);
status = ocfs2_journal_dirty(handle, tl_bh);
if (status < 0) {
mlog_errno(status);
goto bail;
}
/* TODO: Perhaps we can calculate the bulk of the
* credits up front rather than extending like
* this. */
status = ocfs2_extend_trans(handle,
OCFS2_TRUNCATE_LOG_FLUSH_ONE_REC);
if (status < 0) {
mlog_errno(status);
goto bail;
}
rec = tl->tl_recs[i];
start_blk = ocfs2_clusters_to_blocks(data_alloc_inode->i_sb,
le32_to_cpu(rec.t_start));
num_clusters = le32_to_cpu(rec.t_clusters);
/* if start_blk is not set, we ignore the record as
* invalid. */
if (start_blk) {
mlog(0, "free record %d, start = %u, clusters = %u\n",
i, le32_to_cpu(rec.t_start), num_clusters);
status = ocfs2_free_clusters(handle, data_alloc_inode,
data_alloc_bh, start_blk,
num_clusters);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
i--;
}
bail:
mlog_exit(status);
return status;
}
/* Expects you to already be holding tl_inode->i_mutex */
int __ocfs2_flush_truncate_log(struct ocfs2_super *osb)
{
int status;
unsigned int num_to_flush;
handle_t *handle;
struct inode *tl_inode = osb->osb_tl_inode;
struct inode *data_alloc_inode = NULL;
struct buffer_head *tl_bh = osb->osb_tl_bh;
struct buffer_head *data_alloc_bh = NULL;
struct ocfs2_dinode *di;
struct ocfs2_truncate_log *tl;
mlog_entry_void();
BUG_ON(mutex_trylock(&tl_inode->i_mutex));
di = (struct ocfs2_dinode *) tl_bh->b_data;
/* tl_bh is loaded from ocfs2_truncate_log_init(). It's validated
* by the underlying call to ocfs2_read_inode_block(), so any
* corruption is a code bug */
BUG_ON(!OCFS2_IS_VALID_DINODE(di));
tl = &di->id2.i_dealloc;
num_to_flush = le16_to_cpu(tl->tl_used);
mlog(0, "Flush %u records from truncate log #%llu\n",
num_to_flush, (unsigned long long)OCFS2_I(tl_inode)->ip_blkno);
if (!num_to_flush) {
status = 0;
goto out;
}
data_alloc_inode = ocfs2_get_system_file_inode(osb,
GLOBAL_BITMAP_SYSTEM_INODE,
OCFS2_INVALID_SLOT);
if (!data_alloc_inode) {
status = -EINVAL;
mlog(ML_ERROR, "Could not get bitmap inode!\n");
goto out;
}
mutex_lock(&data_alloc_inode->i_mutex);
status = ocfs2_inode_lock(data_alloc_inode, &data_alloc_bh, 1);
if (status < 0) {
mlog_errno(status);
goto out_mutex;
}
handle = ocfs2_start_trans(osb, OCFS2_TRUNCATE_LOG_UPDATE);
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
mlog_errno(status);
goto out_unlock;
}
status = ocfs2_replay_truncate_records(osb, handle, data_alloc_inode,
data_alloc_bh);
if (status < 0)
mlog_errno(status);
ocfs2_commit_trans(osb, handle);
out_unlock:
brelse(data_alloc_bh);
ocfs2_inode_unlock(data_alloc_inode, 1);
out_mutex:
mutex_unlock(&data_alloc_inode->i_mutex);
iput(data_alloc_inode);
out:
mlog_exit(status);
return status;
}
int ocfs2_flush_truncate_log(struct ocfs2_super *osb)
{
int status;
struct inode *tl_inode = osb->osb_tl_inode;
mutex_lock(&tl_inode->i_mutex);
status = __ocfs2_flush_truncate_log(osb);
mutex_unlock(&tl_inode->i_mutex);
return status;
}
static void ocfs2_truncate_log_worker(struct work_struct *work)
{
int status;
struct ocfs2_super *osb =
container_of(work, struct ocfs2_super,
osb_truncate_log_wq.work);
mlog_entry_void();
status = ocfs2_flush_truncate_log(osb);
if (status < 0)
mlog_errno(status);
else
ocfs2_init_inode_steal_slot(osb);
mlog_exit(status);
}
#define OCFS2_TRUNCATE_LOG_FLUSH_INTERVAL (2 * HZ)
void ocfs2_schedule_truncate_log_flush(struct ocfs2_super *osb,
int cancel)
{
if (osb->osb_tl_inode) {
/* We want to push off log flushes while truncates are
* still running. */
if (cancel)
cancel_delayed_work(&osb->osb_truncate_log_wq);
queue_delayed_work(ocfs2_wq, &osb->osb_truncate_log_wq,
OCFS2_TRUNCATE_LOG_FLUSH_INTERVAL);
}
}
static int ocfs2_get_truncate_log_info(struct ocfs2_super *osb,
int slot_num,
struct inode **tl_inode,
struct buffer_head **tl_bh)
{
int status;
struct inode *inode = NULL;
struct buffer_head *bh = NULL;
inode = ocfs2_get_system_file_inode(osb,
TRUNCATE_LOG_SYSTEM_INODE,
slot_num);
if (!inode) {
status = -EINVAL;
mlog(ML_ERROR, "Could not get load truncate log inode!\n");
goto bail;
}
status = ocfs2_read_inode_block(inode, &bh);
if (status < 0) {
iput(inode);
mlog_errno(status);
goto bail;
}
*tl_inode = inode;
*tl_bh = bh;
bail:
mlog_exit(status);
return status;
}
/* called during the 1st stage of node recovery. we stamp a clean
* truncate log and pass back a copy for processing later. if the
* truncate log does not require processing, a *tl_copy is set to
* NULL. */
int ocfs2_begin_truncate_log_recovery(struct ocfs2_super *osb,
int slot_num,
struct ocfs2_dinode **tl_copy)
{
int status;
struct inode *tl_inode = NULL;
struct buffer_head *tl_bh = NULL;
struct ocfs2_dinode *di;
struct ocfs2_truncate_log *tl;
*tl_copy = NULL;
mlog(0, "recover truncate log from slot %d\n", slot_num);
status = ocfs2_get_truncate_log_info(osb, slot_num, &tl_inode, &tl_bh);
if (status < 0) {
mlog_errno(status);
goto bail;
}
di = (struct ocfs2_dinode *) tl_bh->b_data;
/* tl_bh is loaded from ocfs2_get_truncate_log_info(). It's
* validated by the underlying call to ocfs2_read_inode_block(),
* so any corruption is a code bug */
BUG_ON(!OCFS2_IS_VALID_DINODE(di));
tl = &di->id2.i_dealloc;
if (le16_to_cpu(tl->tl_used)) {
mlog(0, "We'll have %u logs to recover\n",
le16_to_cpu(tl->tl_used));
*tl_copy = kmalloc(tl_bh->b_size, GFP_KERNEL);
if (!(*tl_copy)) {
status = -ENOMEM;
mlog_errno(status);
goto bail;
}
/* Assuming the write-out below goes well, this copy
* will be passed back to recovery for processing. */
memcpy(*tl_copy, tl_bh->b_data, tl_bh->b_size);
/* All we need to do to clear the truncate log is set
* tl_used. */
tl->tl_used = 0;
ocfs2_compute_meta_ecc(osb->sb, tl_bh->b_data, &di->i_check);
status = ocfs2_write_block(osb, tl_bh, INODE_CACHE(tl_inode));
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
bail:
if (tl_inode)
iput(tl_inode);
brelse(tl_bh);
if (status < 0 && (*tl_copy)) {
kfree(*tl_copy);
*tl_copy = NULL;
}
mlog_exit(status);
return status;
}
int ocfs2_complete_truncate_log_recovery(struct ocfs2_super *osb,
struct ocfs2_dinode *tl_copy)
{
int status = 0;
int i;
unsigned int clusters, num_recs, start_cluster;
u64 start_blk;
handle_t *handle;
struct inode *tl_inode = osb->osb_tl_inode;
struct ocfs2_truncate_log *tl;
mlog_entry_void();
if (OCFS2_I(tl_inode)->ip_blkno == le64_to_cpu(tl_copy->i_blkno)) {
mlog(ML_ERROR, "Asked to recover my own truncate log!\n");
return -EINVAL;
}
tl = &tl_copy->id2.i_dealloc;
num_recs = le16_to_cpu(tl->tl_used);
mlog(0, "cleanup %u records from %llu\n", num_recs,
(unsigned long long)le64_to_cpu(tl_copy->i_blkno));
mutex_lock(&tl_inode->i_mutex);
for(i = 0; i < num_recs; i++) {
if (ocfs2_truncate_log_needs_flush(osb)) {
status = __ocfs2_flush_truncate_log(osb);
if (status < 0) {
mlog_errno(status);
goto bail_up;
}
}
handle = ocfs2_start_trans(osb, OCFS2_TRUNCATE_LOG_UPDATE);
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
mlog_errno(status);
goto bail_up;
}
clusters = le32_to_cpu(tl->tl_recs[i].t_clusters);
start_cluster = le32_to_cpu(tl->tl_recs[i].t_start);
start_blk = ocfs2_clusters_to_blocks(osb->sb, start_cluster);
status = ocfs2_truncate_log_append(osb, handle,
start_blk, clusters);
ocfs2_commit_trans(osb, handle);
if (status < 0) {
mlog_errno(status);
goto bail_up;
}
}
bail_up:
mutex_unlock(&tl_inode->i_mutex);
mlog_exit(status);
return status;
}
void ocfs2_truncate_log_shutdown(struct ocfs2_super *osb)
{
int status;
struct inode *tl_inode = osb->osb_tl_inode;
mlog_entry_void();
if (tl_inode) {
cancel_delayed_work(&osb->osb_truncate_log_wq);
flush_workqueue(ocfs2_wq);
status = ocfs2_flush_truncate_log(osb);
if (status < 0)
mlog_errno(status);
brelse(osb->osb_tl_bh);
iput(osb->osb_tl_inode);
}
mlog_exit_void();
}
int ocfs2_truncate_log_init(struct ocfs2_super *osb)
{
int status;
struct inode *tl_inode = NULL;
struct buffer_head *tl_bh = NULL;
mlog_entry_void();
status = ocfs2_get_truncate_log_info(osb,
osb->slot_num,
&tl_inode,
&tl_bh);
if (status < 0)
mlog_errno(status);
/* ocfs2_truncate_log_shutdown keys on the existence of
* osb->osb_tl_inode so we don't set any of the osb variables
* until we're sure all is well. */
INIT_DELAYED_WORK(&osb->osb_truncate_log_wq,
ocfs2_truncate_log_worker);
osb->osb_tl_bh = tl_bh;
osb->osb_tl_inode = tl_inode;
mlog_exit(status);
return status;
}
/*
* Delayed de-allocation of suballocator blocks.
*
* Some sets of block de-allocations might involve multiple suballocator inodes.
*
* The locking for this can get extremely complicated, especially when
* the suballocator inodes to delete from aren't known until deep
* within an unrelated codepath.
*
* ocfs2_extent_block structures are a good example of this - an inode
* btree could have been grown by any number of nodes each allocating
* out of their own suballoc inode.
*
* These structures allow the delay of block de-allocation until a
* later time, when locking of multiple cluster inodes won't cause
* deadlock.
*/
/*
* Describe a single bit freed from a suballocator. For the block
* suballocators, it represents one block. For the global cluster
* allocator, it represents some clusters and free_bit indicates
* clusters number.
*/
struct ocfs2_cached_block_free {
struct ocfs2_cached_block_free *free_next;
u64 free_blk;
unsigned int free_bit;
};
struct ocfs2_per_slot_free_list {
struct ocfs2_per_slot_free_list *f_next_suballocator;
int f_inode_type;
int f_slot;
struct ocfs2_cached_block_free *f_first;
};
static int ocfs2_free_cached_blocks(struct ocfs2_super *osb,
int sysfile_type,
int slot,
struct ocfs2_cached_block_free *head)
{
int ret;
u64 bg_blkno;
handle_t *handle;
struct inode *inode;
struct buffer_head *di_bh = NULL;
struct ocfs2_cached_block_free *tmp;
inode = ocfs2_get_system_file_inode(osb, sysfile_type, slot);
if (!inode) {
ret = -EINVAL;
mlog_errno(ret);
goto out;
}
mutex_lock(&inode->i_mutex);
ret = ocfs2_inode_lock(inode, &di_bh, 1);
if (ret) {
mlog_errno(ret);
goto out_mutex;
}
handle = ocfs2_start_trans(osb, OCFS2_SUBALLOC_FREE);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
goto out_unlock;
}
while (head) {
bg_blkno = ocfs2_which_suballoc_group(head->free_blk,
head->free_bit);
mlog(0, "Free bit: (bit %u, blkno %llu)\n",
head->free_bit, (unsigned long long)head->free_blk);
ret = ocfs2_free_suballoc_bits(handle, inode, di_bh,
head->free_bit, bg_blkno, 1);
if (ret) {
mlog_errno(ret);
goto out_journal;
}
ret = ocfs2_extend_trans(handle, OCFS2_SUBALLOC_FREE);
if (ret) {
mlog_errno(ret);
goto out_journal;
}
tmp = head;
head = head->free_next;
kfree(tmp);
}
out_journal:
ocfs2_commit_trans(osb, handle);
out_unlock:
ocfs2_inode_unlock(inode, 1);
brelse(di_bh);
out_mutex:
mutex_unlock(&inode->i_mutex);
iput(inode);
out:
while(head) {
/* Premature exit may have left some dangling items. */
tmp = head;
head = head->free_next;
kfree(tmp);
}
return ret;
}
int ocfs2_cache_cluster_dealloc(struct ocfs2_cached_dealloc_ctxt *ctxt,
u64 blkno, unsigned int bit)
{
int ret = 0;
struct ocfs2_cached_block_free *item;
item = kmalloc(sizeof(*item), GFP_NOFS);
if (item == NULL) {
ret = -ENOMEM;
mlog_errno(ret);
return ret;
}
mlog(0, "Insert clusters: (bit %u, blk %llu)\n",
bit, (unsigned long long)blkno);
item->free_blk = blkno;
item->free_bit = bit;
item->free_next = ctxt->c_global_allocator;
ctxt->c_global_allocator = item;
return ret;
}
static int ocfs2_free_cached_clusters(struct ocfs2_super *osb,
struct ocfs2_cached_block_free *head)
{
struct ocfs2_cached_block_free *tmp;
struct inode *tl_inode = osb->osb_tl_inode;
handle_t *handle;
int ret = 0;
mutex_lock(&tl_inode->i_mutex);
while (head) {
if (ocfs2_truncate_log_needs_flush(osb)) {
ret = __ocfs2_flush_truncate_log(osb);
if (ret < 0) {
mlog_errno(ret);
break;
}
}
handle = ocfs2_start_trans(osb, OCFS2_TRUNCATE_LOG_UPDATE);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
break;
}
ret = ocfs2_truncate_log_append(osb, handle, head->free_blk,
head->free_bit);
ocfs2_commit_trans(osb, handle);
tmp = head;
head = head->free_next;
kfree(tmp);
if (ret < 0) {
mlog_errno(ret);
break;
}
}
mutex_unlock(&tl_inode->i_mutex);
while (head) {
/* Premature exit may have left some dangling items. */
tmp = head;
head = head->free_next;
kfree(tmp);
}
return ret;
}
int ocfs2_run_deallocs(struct ocfs2_super *osb,
struct ocfs2_cached_dealloc_ctxt *ctxt)
{
int ret = 0, ret2;
struct ocfs2_per_slot_free_list *fl;
if (!ctxt)
return 0;
while (ctxt->c_first_suballocator) {
fl = ctxt->c_first_suballocator;
if (fl->f_first) {
mlog(0, "Free items: (type %u, slot %d)\n",
fl->f_inode_type, fl->f_slot);
ret2 = ocfs2_free_cached_blocks(osb,
fl->f_inode_type,
fl->f_slot,
fl->f_first);
if (ret2)
mlog_errno(ret2);
if (!ret)
ret = ret2;
}
ctxt->c_first_suballocator = fl->f_next_suballocator;
kfree(fl);
}
if (ctxt->c_global_allocator) {
ret2 = ocfs2_free_cached_clusters(osb,
ctxt->c_global_allocator);
if (ret2)
mlog_errno(ret2);
if (!ret)
ret = ret2;
ctxt->c_global_allocator = NULL;
}
return ret;
}
static struct ocfs2_per_slot_free_list *
ocfs2_find_per_slot_free_list(int type,
int slot,
struct ocfs2_cached_dealloc_ctxt *ctxt)
{
struct ocfs2_per_slot_free_list *fl = ctxt->c_first_suballocator;
while (fl) {
if (fl->f_inode_type == type && fl->f_slot == slot)
return fl;
fl = fl->f_next_suballocator;
}
fl = kmalloc(sizeof(*fl), GFP_NOFS);
if (fl) {
fl->f_inode_type = type;
fl->f_slot = slot;
fl->f_first = NULL;
fl->f_next_suballocator = ctxt->c_first_suballocator;
ctxt->c_first_suballocator = fl;
}
return fl;
}
int ocfs2_cache_block_dealloc(struct ocfs2_cached_dealloc_ctxt *ctxt,
int type, int slot, u64 blkno,
unsigned int bit)
{
int ret;
struct ocfs2_per_slot_free_list *fl;
struct ocfs2_cached_block_free *item;
fl = ocfs2_find_per_slot_free_list(type, slot, ctxt);
if (fl == NULL) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
item = kmalloc(sizeof(*item), GFP_NOFS);
if (item == NULL) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
mlog(0, "Insert: (type %d, slot %u, bit %u, blk %llu)\n",
type, slot, bit, (unsigned long long)blkno);
item->free_blk = blkno;
item->free_bit = bit;
item->free_next = fl->f_first;
fl->f_first = item;
ret = 0;
out:
return ret;
}
static int ocfs2_cache_extent_block_free(struct ocfs2_cached_dealloc_ctxt *ctxt,
struct ocfs2_extent_block *eb)
{
return ocfs2_cache_block_dealloc(ctxt, EXTENT_ALLOC_SYSTEM_INODE,
le16_to_cpu(eb->h_suballoc_slot),
le64_to_cpu(eb->h_blkno),
le16_to_cpu(eb->h_suballoc_bit));
}
/* This function will figure out whether the currently last extent
* block will be deleted, and if it will, what the new last extent
* block will be so we can update his h_next_leaf_blk field, as well
* as the dinodes i_last_eb_blk */
static int ocfs2_find_new_last_ext_blk(struct inode *inode,
unsigned int clusters_to_del,
struct ocfs2_path *path,
struct buffer_head **new_last_eb)
{
int next_free, ret = 0;
u32 cpos;
struct ocfs2_extent_rec *rec;
struct ocfs2_extent_block *eb;
struct ocfs2_extent_list *el;
struct buffer_head *bh = NULL;
*new_last_eb = NULL;
/* we have no tree, so of course, no last_eb. */
if (!path->p_tree_depth)
goto out;
/* trunc to zero special case - this makes tree_depth = 0
* regardless of what it is. */
if (OCFS2_I(inode)->ip_clusters == clusters_to_del)
goto out;
el = path_leaf_el(path);
BUG_ON(!el->l_next_free_rec);
/*
* Make sure that this extent list will actually be empty
* after we clear away the data. We can shortcut out if
* there's more than one non-empty extent in the
* list. Otherwise, a check of the remaining extent is
* necessary.
*/
next_free = le16_to_cpu(el->l_next_free_rec);
rec = NULL;
if (ocfs2_is_empty_extent(&el->l_recs[0])) {
if (next_free > 2)
goto out;
/* We may have a valid extent in index 1, check it. */
if (next_free == 2)
rec = &el->l_recs[1];
/*
* Fall through - no more nonempty extents, so we want
* to delete this leaf.
*/
} else {
if (next_free > 1)
goto out;
rec = &el->l_recs[0];
}
if (rec) {
/*
* Check it we'll only be trimming off the end of this
* cluster.
*/
if (le16_to_cpu(rec->e_leaf_clusters) > clusters_to_del)
goto out;
}
ret = ocfs2_find_cpos_for_left_leaf(inode->i_sb, path, &cpos);
if (ret) {
mlog_errno(ret);
goto out;
}
ret = ocfs2_find_leaf(INODE_CACHE(inode), path_root_el(path), cpos, &bh);
if (ret) {
mlog_errno(ret);
goto out;
}
eb = (struct ocfs2_extent_block *) bh->b_data;
el = &eb->h_list;
/* ocfs2_find_leaf() gets the eb from ocfs2_read_extent_block().
* Any corruption is a code bug. */
BUG_ON(!OCFS2_IS_VALID_EXTENT_BLOCK(eb));
*new_last_eb = bh;
get_bh(*new_last_eb);
mlog(0, "returning block %llu, (cpos: %u)\n",
(unsigned long long)le64_to_cpu(eb->h_blkno), cpos);
out:
brelse(bh);
return ret;
}
/*
* Trim some clusters off the rightmost edge of a tree. Only called
* during truncate.
*
* The caller needs to:
* - start journaling of each path component.
* - compute and fully set up any new last ext block
*/
static int ocfs2_trim_tree(struct inode *inode, struct ocfs2_path *path,
handle_t *handle, struct ocfs2_truncate_context *tc,
u32 clusters_to_del, u64 *delete_start, u8 *flags)
{
int ret, i, index = path->p_tree_depth;
u32 new_edge = 0;
u64 deleted_eb = 0;
struct buffer_head *bh;
struct ocfs2_extent_list *el;
struct ocfs2_extent_rec *rec;
*delete_start = 0;
*flags = 0;
while (index >= 0) {
bh = path->p_node[index].bh;
el = path->p_node[index].el;
mlog(0, "traveling tree (index = %d, block = %llu)\n",
index, (unsigned long long)bh->b_blocknr);
BUG_ON(le16_to_cpu(el->l_next_free_rec) == 0);
if (index !=
(path->p_tree_depth - le16_to_cpu(el->l_tree_depth))) {
ocfs2_error(inode->i_sb,
"Inode %lu has invalid ext. block %llu",
inode->i_ino,
(unsigned long long)bh->b_blocknr);
ret = -EROFS;
goto out;
}
find_tail_record:
i = le16_to_cpu(el->l_next_free_rec) - 1;
rec = &el->l_recs[i];
mlog(0, "Extent list before: record %d: (%u, %u, %llu), "
"next = %u\n", i, le32_to_cpu(rec->e_cpos),
ocfs2_rec_clusters(el, rec),
(unsigned long long)le64_to_cpu(rec->e_blkno),
le16_to_cpu(el->l_next_free_rec));
BUG_ON(ocfs2_rec_clusters(el, rec) < clusters_to_del);
if (le16_to_cpu(el->l_tree_depth) == 0) {
/*
* If the leaf block contains a single empty
* extent and no records, we can just remove
* the block.
*/
if (i == 0 && ocfs2_is_empty_extent(rec)) {
memset(rec, 0,
sizeof(struct ocfs2_extent_rec));
el->l_next_free_rec = cpu_to_le16(0);
goto delete;
}
/*
* Remove any empty extents by shifting things
* left. That should make life much easier on
* the code below. This condition is rare
* enough that we shouldn't see a performance
* hit.
*/
if (ocfs2_is_empty_extent(&el->l_recs[0])) {
le16_add_cpu(&el->l_next_free_rec, -1);
for(i = 0;
i < le16_to_cpu(el->l_next_free_rec); i++)
el->l_recs[i] = el->l_recs[i + 1];
memset(&el->l_recs[i], 0,
sizeof(struct ocfs2_extent_rec));
/*
* We've modified our extent list. The
* simplest way to handle this change
* is to being the search from the
* start again.
*/
goto find_tail_record;
}
le16_add_cpu(&rec->e_leaf_clusters, -clusters_to_del);
/*
* We'll use "new_edge" on our way back up the
* tree to know what our rightmost cpos is.
*/
new_edge = le16_to_cpu(rec->e_leaf_clusters);
new_edge += le32_to_cpu(rec->e_cpos);
/*
* The caller will use this to delete data blocks.
*/
*delete_start = le64_to_cpu(rec->e_blkno)
+ ocfs2_clusters_to_blocks(inode->i_sb,
le16_to_cpu(rec->e_leaf_clusters));
*flags = rec->e_flags;
/*
* If it's now empty, remove this record.
*/
if (le16_to_cpu(rec->e_leaf_clusters) == 0) {
memset(rec, 0,
sizeof(struct ocfs2_extent_rec));
le16_add_cpu(&el->l_next_free_rec, -1);
}
} else {
if (le64_to_cpu(rec->e_blkno) == deleted_eb) {
memset(rec, 0,
sizeof(struct ocfs2_extent_rec));
le16_add_cpu(&el->l_next_free_rec, -1);
goto delete;
}
/* Can this actually happen? */
if (le16_to_cpu(el->l_next_free_rec) == 0)
goto delete;
/*
* We never actually deleted any clusters
* because our leaf was empty. There's no
* reason to adjust the rightmost edge then.
*/
if (new_edge == 0)
goto delete;
rec->e_int_clusters = cpu_to_le32(new_edge);
le32_add_cpu(&rec->e_int_clusters,
-le32_to_cpu(rec->e_cpos));
/*
* A deleted child record should have been
* caught above.
*/
BUG_ON(le32_to_cpu(rec->e_int_clusters) == 0);
}
delete:
ret = ocfs2_journal_dirty(handle, bh);
if (ret) {
mlog_errno(ret);
goto out;
}
mlog(0, "extent list container %llu, after: record %d: "
"(%u, %u, %llu), next = %u.\n",
(unsigned long long)bh->b_blocknr, i,
le32_to_cpu(rec->e_cpos), ocfs2_rec_clusters(el, rec),
(unsigned long long)le64_to_cpu(rec->e_blkno),
le16_to_cpu(el->l_next_free_rec));
/*
* We must be careful to only attempt delete of an
* extent block (and not the root inode block).
*/
if (index > 0 && le16_to_cpu(el->l_next_free_rec) == 0) {
struct ocfs2_extent_block *eb =
(struct ocfs2_extent_block *)bh->b_data;
/*
* Save this for use when processing the
* parent block.
*/
deleted_eb = le64_to_cpu(eb->h_blkno);
mlog(0, "deleting this extent block.\n");
ocfs2_remove_from_cache(INODE_CACHE(inode), bh);
BUG_ON(ocfs2_rec_clusters(el, &el->l_recs[0]));
BUG_ON(le32_to_cpu(el->l_recs[0].e_cpos));
BUG_ON(le64_to_cpu(el->l_recs[0].e_blkno));
ret = ocfs2_cache_extent_block_free(&tc->tc_dealloc, eb);
/* An error here is not fatal. */
if (ret < 0)
mlog_errno(ret);
} else {
deleted_eb = 0;
}
index--;
}
ret = 0;
out:
return ret;
}
static int ocfs2_do_truncate(struct ocfs2_super *osb,
unsigned int clusters_to_del,
struct inode *inode,
struct buffer_head *fe_bh,
handle_t *handle,
struct ocfs2_truncate_context *tc,
struct ocfs2_path *path,
struct ocfs2_alloc_context *meta_ac)
{
int status;
struct ocfs2_dinode *fe;
struct ocfs2_extent_block *last_eb = NULL;
struct ocfs2_extent_list *el;
struct buffer_head *last_eb_bh = NULL;
u64 delete_blk = 0;
u8 rec_flags;
fe = (struct ocfs2_dinode *) fe_bh->b_data;
status = ocfs2_find_new_last_ext_blk(inode, clusters_to_del,
path, &last_eb_bh);
if (status < 0) {
mlog_errno(status);
goto bail;
}
/*
* Each component will be touched, so we might as well journal
* here to avoid having to handle errors later.
*/
status = ocfs2_journal_access_path(INODE_CACHE(inode), handle, path);
if (status < 0) {
mlog_errno(status);
goto bail;
}
if (last_eb_bh) {
status = ocfs2_journal_access_eb(handle, INODE_CACHE(inode), last_eb_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto bail;
}
last_eb = (struct ocfs2_extent_block *) last_eb_bh->b_data;
}
el = &(fe->id2.i_list);
/*
* Lower levels depend on this never happening, but it's best
* to check it up here before changing the tree.
*/
if (el->l_tree_depth && el->l_recs[0].e_int_clusters == 0) {
ocfs2_error(inode->i_sb,
"Inode %lu has an empty extent record, depth %u\n",
inode->i_ino, le16_to_cpu(el->l_tree_depth));
status = -EROFS;
goto bail;
}
vfs_dq_free_space_nodirty(inode,
ocfs2_clusters_to_bytes(osb->sb, clusters_to_del));
spin_lock(&OCFS2_I(inode)->ip_lock);
OCFS2_I(inode)->ip_clusters = le32_to_cpu(fe->i_clusters) -
clusters_to_del;
spin_unlock(&OCFS2_I(inode)->ip_lock);
le32_add_cpu(&fe->i_clusters, -clusters_to_del);
inode->i_blocks = ocfs2_inode_sector_count(inode);
status = ocfs2_trim_tree(inode, path, handle, tc,
clusters_to_del, &delete_blk, &rec_flags);
if (status) {
mlog_errno(status);
goto bail;
}
if (le32_to_cpu(fe->i_clusters) == 0) {
/* trunc to zero is a special case. */
el->l_tree_depth = 0;
fe->i_last_eb_blk = 0;
} else if (last_eb)
fe->i_last_eb_blk = last_eb->h_blkno;
status = ocfs2_journal_dirty(handle, fe_bh);
if (status < 0) {
mlog_errno(status);
goto bail;
}
if (last_eb) {
/* If there will be a new last extent block, then by
* definition, there cannot be any leaves to the right of
* him. */
last_eb->h_next_leaf_blk = 0;
status = ocfs2_journal_dirty(handle, last_eb_bh);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
if (delete_blk) {
if (rec_flags & OCFS2_EXT_REFCOUNTED)
status = ocfs2_decrease_refcount(inode, handle,
ocfs2_blocks_to_clusters(osb->sb,
delete_blk),
clusters_to_del, meta_ac,
&tc->tc_dealloc, 1);
else
status = ocfs2_truncate_log_append(osb, handle,
delete_blk,
clusters_to_del);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
status = 0;
bail:
brelse(last_eb_bh);
mlog_exit(status);
return status;
}
static int ocfs2_zero_func(handle_t *handle, struct buffer_head *bh)
{
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
return 0;
}
void ocfs2_map_and_dirty_page(struct inode *inode, handle_t *handle,
unsigned int from, unsigned int to,
struct page *page, int zero, u64 *phys)
{
int ret, partial = 0;
ret = ocfs2_map_page_blocks(page, phys, inode, from, to, 0);
if (ret)
mlog_errno(ret);
if (zero)
zero_user_segment(page, from, to);
/*
* Need to set the buffers we zero'd into uptodate
* here if they aren't - ocfs2_map_page_blocks()
* might've skipped some
*/
ret = walk_page_buffers(handle, page_buffers(page),
from, to, &partial,
ocfs2_zero_func);
if (ret < 0)
mlog_errno(ret);
else if (ocfs2_should_order_data(inode)) {
ret = ocfs2_jbd2_file_inode(handle, inode);
if (ret < 0)
mlog_errno(ret);
}
if (!partial)
SetPageUptodate(page);
flush_dcache_page(page);
}
static void ocfs2_zero_cluster_pages(struct inode *inode, loff_t start,
loff_t end, struct page **pages,
int numpages, u64 phys, handle_t *handle)
{
int i;
struct page *page;
unsigned int from, to = PAGE_CACHE_SIZE;
struct super_block *sb = inode->i_sb;
BUG_ON(!ocfs2_sparse_alloc(OCFS2_SB(sb)));
if (numpages == 0)
goto out;
to = PAGE_CACHE_SIZE;
for(i = 0; i < numpages; i++) {
page = pages[i];
from = start & (PAGE_CACHE_SIZE - 1);
if ((end >> PAGE_CACHE_SHIFT) == page->index)
to = end & (PAGE_CACHE_SIZE - 1);
BUG_ON(from > PAGE_CACHE_SIZE);
BUG_ON(to > PAGE_CACHE_SIZE);
ocfs2_map_and_dirty_page(inode, handle, from, to, page, 1,
&phys);
start = (page->index + 1) << PAGE_CACHE_SHIFT;
}
out:
if (pages)
ocfs2_unlock_and_free_pages(pages, numpages);
}
int ocfs2_grab_pages(struct inode *inode, loff_t start, loff_t end,
struct page **pages, int *num)
{
int numpages, ret = 0;
struct address_space *mapping = inode->i_mapping;
unsigned long index;
loff_t last_page_bytes;
BUG_ON(start > end);
numpages = 0;
last_page_bytes = PAGE_ALIGN(end);
index = start >> PAGE_CACHE_SHIFT;
do {
pages[numpages] = grab_cache_page(mapping, index);
if (!pages[numpages]) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
numpages++;
index++;
} while (index < (last_page_bytes >> PAGE_CACHE_SHIFT));
out:
if (ret != 0) {
if (pages)
ocfs2_unlock_and_free_pages(pages, numpages);
numpages = 0;
}
*num = numpages;
return ret;
}
static int ocfs2_grab_eof_pages(struct inode *inode, loff_t start, loff_t end,
struct page **pages, int *num)
{
struct super_block *sb = inode->i_sb;
BUG_ON(start >> OCFS2_SB(sb)->s_clustersize_bits !=
(end - 1) >> OCFS2_SB(sb)->s_clustersize_bits);
return ocfs2_grab_pages(inode, start, end, pages, num);
}
/*
* Zero the area past i_size but still within an allocated
* cluster. This avoids exposing nonzero data on subsequent file
* extends.
*
* We need to call this before i_size is updated on the inode because
* otherwise block_write_full_page() will skip writeout of pages past
* i_size. The new_i_size parameter is passed for this reason.
*/
int ocfs2_zero_range_for_truncate(struct inode *inode, handle_t *handle,
u64 range_start, u64 range_end)
{
int ret = 0, numpages;
struct page **pages = NULL;
u64 phys;
unsigned int ext_flags;
struct super_block *sb = inode->i_sb;
/*
* File systems which don't support sparse files zero on every
* extend.
*/
if (!ocfs2_sparse_alloc(OCFS2_SB(sb)))
return 0;
pages = kcalloc(ocfs2_pages_per_cluster(sb),
sizeof(struct page *), GFP_NOFS);
if (pages == NULL) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
if (range_start == range_end)
goto out;
ret = ocfs2_extent_map_get_blocks(inode,
range_start >> sb->s_blocksize_bits,
&phys, NULL, &ext_flags);
if (ret) {
mlog_errno(ret);
goto out;
}
/*
* Tail is a hole, or is marked unwritten. In either case, we
* can count on read and write to return/push zero's.
*/
if (phys == 0 || ext_flags & OCFS2_EXT_UNWRITTEN)
goto out;
ret = ocfs2_grab_eof_pages(inode, range_start, range_end, pages,
&numpages);
if (ret) {
mlog_errno(ret);
goto out;
}
ocfs2_zero_cluster_pages(inode, range_start, range_end, pages,
numpages, phys, handle);
/*
* Initiate writeout of the pages we zero'd here. We don't
* wait on them - the truncate_inode_pages() call later will
* do that for us.
*/
ret = do_sync_mapping_range(inode->i_mapping, range_start,
range_end - 1, SYNC_FILE_RANGE_WRITE);
if (ret)
mlog_errno(ret);
out:
if (pages)
kfree(pages);
return ret;
}
static void ocfs2_zero_dinode_id2_with_xattr(struct inode *inode,
struct ocfs2_dinode *di)
{
unsigned int blocksize = 1 << inode->i_sb->s_blocksize_bits;
unsigned int xattrsize = le16_to_cpu(di->i_xattr_inline_size);
if (le16_to_cpu(di->i_dyn_features) & OCFS2_INLINE_XATTR_FL)
memset(&di->id2, 0, blocksize -
offsetof(struct ocfs2_dinode, id2) -
xattrsize);
else
memset(&di->id2, 0, blocksize -
offsetof(struct ocfs2_dinode, id2));
}
void ocfs2_dinode_new_extent_list(struct inode *inode,
struct ocfs2_dinode *di)
{
ocfs2_zero_dinode_id2_with_xattr(inode, di);
di->id2.i_list.l_tree_depth = 0;
di->id2.i_list.l_next_free_rec = 0;
di->id2.i_list.l_count = cpu_to_le16(
ocfs2_extent_recs_per_inode_with_xattr(inode->i_sb, di));
}
void ocfs2_set_inode_data_inline(struct inode *inode, struct ocfs2_dinode *di)
{
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct ocfs2_inline_data *idata = &di->id2.i_data;
spin_lock(&oi->ip_lock);
oi->ip_dyn_features |= OCFS2_INLINE_DATA_FL;
di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
spin_unlock(&oi->ip_lock);
/*
* We clear the entire i_data structure here so that all
* fields can be properly initialized.
*/
ocfs2_zero_dinode_id2_with_xattr(inode, di);
idata->id_count = cpu_to_le16(
ocfs2_max_inline_data_with_xattr(inode->i_sb, di));
}
int ocfs2_convert_inline_data_to_extents(struct inode *inode,
struct buffer_head *di_bh)
{
int ret, i, has_data, num_pages = 0;
handle_t *handle;
u64 uninitialized_var(block);
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
struct ocfs2_alloc_context *data_ac = NULL;
struct page **pages = NULL;
loff_t end = osb->s_clustersize;
struct ocfs2_extent_tree et;
int did_quota = 0;
has_data = i_size_read(inode) ? 1 : 0;
if (has_data) {
pages = kcalloc(ocfs2_pages_per_cluster(osb->sb),
sizeof(struct page *), GFP_NOFS);
if (pages == NULL) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
ret = ocfs2_reserve_clusters(osb, 1, &data_ac);
if (ret) {
mlog_errno(ret);
goto out;
}
}
handle = ocfs2_start_trans(osb,
ocfs2_inline_to_extents_credits(osb->sb));
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
goto out_unlock;
}
ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
if (has_data) {
u32 bit_off, num;
unsigned int page_end;
u64 phys;
if (vfs_dq_alloc_space_nodirty(inode,
ocfs2_clusters_to_bytes(osb->sb, 1))) {
ret = -EDQUOT;
goto out_commit;
}
did_quota = 1;
ret = ocfs2_claim_clusters(osb, handle, data_ac, 1, &bit_off,
&num);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
/*
* Save two copies, one for insert, and one that can
* be changed by ocfs2_map_and_dirty_page() below.
*/
block = phys = ocfs2_clusters_to_blocks(inode->i_sb, bit_off);
/*
* Non sparse file systems zero on extend, so no need
* to do that now.
*/
if (!ocfs2_sparse_alloc(osb) &&
PAGE_CACHE_SIZE < osb->s_clustersize)
end = PAGE_CACHE_SIZE;
ret = ocfs2_grab_eof_pages(inode, 0, end, pages, &num_pages);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
/*
* This should populate the 1st page for us and mark
* it up to date.
*/
ret = ocfs2_read_inline_data(inode, pages[0], di_bh);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
page_end = PAGE_CACHE_SIZE;
if (PAGE_CACHE_SIZE > osb->s_clustersize)
page_end = osb->s_clustersize;
for (i = 0; i < num_pages; i++)
ocfs2_map_and_dirty_page(inode, handle, 0, page_end,
pages[i], i > 0, &phys);
}
spin_lock(&oi->ip_lock);
oi->ip_dyn_features &= ~OCFS2_INLINE_DATA_FL;
di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
spin_unlock(&oi->ip_lock);
ocfs2_dinode_new_extent_list(inode, di);
ocfs2_journal_dirty(handle, di_bh);
if (has_data) {
/*
* An error at this point should be extremely rare. If
* this proves to be false, we could always re-build
* the in-inode data from our pages.
*/
ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(inode), di_bh);
ret = ocfs2_insert_extent(handle, &et, 0, block, 1, 0, NULL);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
inode->i_blocks = ocfs2_inode_sector_count(inode);
}
out_commit:
if (ret < 0 && did_quota)
vfs_dq_free_space_nodirty(inode,
ocfs2_clusters_to_bytes(osb->sb, 1));
ocfs2_commit_trans(osb, handle);
out_unlock:
if (data_ac)
ocfs2_free_alloc_context(data_ac);
out:
if (pages) {
ocfs2_unlock_and_free_pages(pages, num_pages);
kfree(pages);
}
return ret;
}
/*
* It is expected, that by the time you call this function,
* inode->i_size and fe->i_size have been adjusted.
*
* WARNING: This will kfree the truncate context
*/
int ocfs2_commit_truncate(struct ocfs2_super *osb,
struct inode *inode,
struct buffer_head *fe_bh,
struct ocfs2_truncate_context *tc)
{
int status, i, credits, tl_sem = 0;
u32 clusters_to_del, new_highest_cpos, range;
u64 blkno = 0;
struct ocfs2_extent_list *el;
handle_t *handle = NULL;
struct inode *tl_inode = osb->osb_tl_inode;
struct ocfs2_path *path = NULL;
struct ocfs2_dinode *di = (struct ocfs2_dinode *)fe_bh->b_data;
struct ocfs2_alloc_context *meta_ac = NULL;
struct ocfs2_refcount_tree *ref_tree = NULL;
mlog_entry_void();
new_highest_cpos = ocfs2_clusters_for_bytes(osb->sb,
i_size_read(inode));
path = ocfs2_new_path(fe_bh, &di->id2.i_list,
ocfs2_journal_access_di);
if (!path) {
status = -ENOMEM;
mlog_errno(status);
goto bail;
}
ocfs2_extent_map_trunc(inode, new_highest_cpos);
start:
/*
* Check that we still have allocation to delete.
*/
if (OCFS2_I(inode)->ip_clusters == 0) {
status = 0;
goto bail;
}
credits = 0;
/*
* Truncate always works against the rightmost tree branch.
*/
status = ocfs2_find_path(INODE_CACHE(inode), path, UINT_MAX);
if (status) {
mlog_errno(status);
goto bail;
}
mlog(0, "inode->ip_clusters = %u, tree_depth = %u\n",
OCFS2_I(inode)->ip_clusters, path->p_tree_depth);
/*
* By now, el will point to the extent list on the bottom most
* portion of this tree. Only the tail record is considered in
* each pass.
*
* We handle the following cases, in order:
* - empty extent: delete the remaining branch
* - remove the entire record
* - remove a partial record
* - no record needs to be removed (truncate has completed)
*/
el = path_leaf_el(path);
if (le16_to_cpu(el->l_next_free_rec) == 0) {
ocfs2_error(inode->i_sb,
"Inode %llu has empty extent block at %llu\n",
(unsigned long long)OCFS2_I(inode)->ip_blkno,
(unsigned long long)path_leaf_bh(path)->b_blocknr);
status = -EROFS;
goto bail;
}
i = le16_to_cpu(el->l_next_free_rec) - 1;
range = le32_to_cpu(el->l_recs[i].e_cpos) +
ocfs2_rec_clusters(el, &el->l_recs[i]);
if (i == 0 && ocfs2_is_empty_extent(&el->l_recs[i])) {
clusters_to_del = 0;
} else if (le32_to_cpu(el->l_recs[i].e_cpos) >= new_highest_cpos) {
clusters_to_del = ocfs2_rec_clusters(el, &el->l_recs[i]);
blkno = le64_to_cpu(el->l_recs[i].e_blkno);
} else if (range > new_highest_cpos) {
clusters_to_del = (ocfs2_rec_clusters(el, &el->l_recs[i]) +
le32_to_cpu(el->l_recs[i].e_cpos)) -
new_highest_cpos;
blkno = le64_to_cpu(el->l_recs[i].e_blkno) +
ocfs2_clusters_to_blocks(inode->i_sb,
ocfs2_rec_clusters(el, &el->l_recs[i]) -
clusters_to_del);
} else {
status = 0;
goto bail;
}
mlog(0, "clusters_to_del = %u in this pass, tail blk=%llu\n",
clusters_to_del, (unsigned long long)path_leaf_bh(path)->b_blocknr);
if (el->l_recs[i].e_flags & OCFS2_EXT_REFCOUNTED && clusters_to_del) {
BUG_ON(!(OCFS2_I(inode)->ip_dyn_features &
OCFS2_HAS_REFCOUNT_FL));
status = ocfs2_lock_refcount_tree(osb,
le64_to_cpu(di->i_refcount_loc),
1, &ref_tree, NULL);
if (status) {
mlog_errno(status);
goto bail;
}
status = ocfs2_prepare_refcount_change_for_del(inode, fe_bh,
blkno,
clusters_to_del,
&credits,
&meta_ac);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
mutex_lock(&tl_inode->i_mutex);
tl_sem = 1;
/* ocfs2_truncate_log_needs_flush guarantees us at least one
* record is free for use. If there isn't any, we flush to get
* an empty truncate log. */
if (ocfs2_truncate_log_needs_flush(osb)) {
status = __ocfs2_flush_truncate_log(osb);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
credits += ocfs2_calc_tree_trunc_credits(osb->sb, clusters_to_del,
(struct ocfs2_dinode *)fe_bh->b_data,
el);
handle = ocfs2_start_trans(osb, credits);
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
handle = NULL;
mlog_errno(status);
goto bail;
}
status = ocfs2_do_truncate(osb, clusters_to_del, inode, fe_bh, handle,
tc, path, meta_ac);
if (status < 0) {
mlog_errno(status);
goto bail;
}
mutex_unlock(&tl_inode->i_mutex);
tl_sem = 0;
ocfs2_commit_trans(osb, handle);
handle = NULL;
ocfs2_reinit_path(path, 1);
if (meta_ac) {
ocfs2_free_alloc_context(meta_ac);
meta_ac = NULL;
}
if (ref_tree) {
ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
ref_tree = NULL;
}
/*
* The check above will catch the case where we've truncated
* away all allocation.
*/
goto start;
bail:
ocfs2_schedule_truncate_log_flush(osb, 1);
if (tl_sem)
mutex_unlock(&tl_inode->i_mutex);
if (handle)
ocfs2_commit_trans(osb, handle);
if (meta_ac)
ocfs2_free_alloc_context(meta_ac);
if (ref_tree)
ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
ocfs2_run_deallocs(osb, &tc->tc_dealloc);
ocfs2_free_path(path);
/* This will drop the ext_alloc cluster lock for us */
ocfs2_free_truncate_context(tc);
mlog_exit(status);
return status;
}
/*
* Expects the inode to already be locked.
*/
int ocfs2_prepare_truncate(struct ocfs2_super *osb,
struct inode *inode,
struct buffer_head *fe_bh,
struct ocfs2_truncate_context **tc)
{
int status;
unsigned int new_i_clusters;
struct ocfs2_dinode *fe;
struct ocfs2_extent_block *eb;
struct buffer_head *last_eb_bh = NULL;
mlog_entry_void();
*tc = NULL;
new_i_clusters = ocfs2_clusters_for_bytes(osb->sb,
i_size_read(inode));
fe = (struct ocfs2_dinode *) fe_bh->b_data;
mlog(0, "fe->i_clusters = %u, new_i_clusters = %u, fe->i_size ="
"%llu\n", le32_to_cpu(fe->i_clusters), new_i_clusters,
(unsigned long long)le64_to_cpu(fe->i_size));
*tc = kzalloc(sizeof(struct ocfs2_truncate_context), GFP_KERNEL);
if (!(*tc)) {
status = -ENOMEM;
mlog_errno(status);
goto bail;
}
ocfs2_init_dealloc_ctxt(&(*tc)->tc_dealloc);
if (fe->id2.i_list.l_tree_depth) {
status = ocfs2_read_extent_block(INODE_CACHE(inode),
le64_to_cpu(fe->i_last_eb_blk),
&last_eb_bh);
if (status < 0) {
mlog_errno(status);
goto bail;
}
eb = (struct ocfs2_extent_block *) last_eb_bh->b_data;
}
(*tc)->tc_last_eb_bh = last_eb_bh;
status = 0;
bail:
if (status < 0) {
if (*tc)
ocfs2_free_truncate_context(*tc);
*tc = NULL;
}
mlog_exit_void();
return status;
}
/*
* 'start' is inclusive, 'end' is not.
*/
int ocfs2_truncate_inline(struct inode *inode, struct buffer_head *di_bh,
unsigned int start, unsigned int end, int trunc)
{
int ret;
unsigned int numbytes;
handle_t *handle;
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
struct ocfs2_inline_data *idata = &di->id2.i_data;
if (end > i_size_read(inode))
end = i_size_read(inode);
BUG_ON(start >= end);
if (!(OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) ||
!(le16_to_cpu(di->i_dyn_features) & OCFS2_INLINE_DATA_FL) ||
!ocfs2_supports_inline_data(osb)) {
ocfs2_error(inode->i_sb,
"Inline data flags for inode %llu don't agree! "
"Disk: 0x%x, Memory: 0x%x, Superblock: 0x%x\n",
(unsigned long long)OCFS2_I(inode)->ip_blkno,
le16_to_cpu(di->i_dyn_features),
OCFS2_I(inode)->ip_dyn_features,
osb->s_feature_incompat);
ret = -EROFS;
goto out;
}
handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
mlog_errno(ret);
goto out;
}
ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (ret) {
mlog_errno(ret);
goto out_commit;
}
numbytes = end - start;
memset(idata->id_data + start, 0, numbytes);
/*
* No need to worry about the data page here - it's been
* truncated already and inline data doesn't need it for
* pushing zero's to disk, so we'll let readpage pick it up
* later.
*/
if (trunc) {
i_size_write(inode, start);
di->i_size = cpu_to_le64(start);
}
inode->i_blocks = ocfs2_inode_sector_count(inode);
inode->i_ctime = inode->i_mtime = CURRENT_TIME;
di->i_ctime = di->i_mtime = cpu_to_le64(inode->i_ctime.tv_sec);
di->i_ctime_nsec = di->i_mtime_nsec = cpu_to_le32(inode->i_ctime.tv_nsec);
ocfs2_journal_dirty(handle, di_bh);
out_commit:
ocfs2_commit_trans(osb, handle);
out:
return ret;
}
static void ocfs2_free_truncate_context(struct ocfs2_truncate_context *tc)
{
/*
* The caller is responsible for completing deallocation
* before freeing the context.
*/
if (tc->tc_dealloc.c_first_suballocator != NULL)
mlog(ML_NOTICE,
"Truncate completion has non-empty dealloc context\n");
brelse(tc->tc_last_eb_bh);
kfree(tc);
}
| gpl-2.0 |
blazingwolf/Acer-A500-Stock-Kernel-with-touchscreen-fix-for-ICS | drivers/media/radio/tef6862.c | 897 | 5739 | /*
* tef6862.c Philips TEF6862 Car Radio Enhanced Selectivity Tuner
* Copyright (c) 2009 Intel Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/i2c-id.h>
#include <linux/slab.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-device.h>
#include <media/v4l2-chip-ident.h>
#define DRIVER_NAME "tef6862"
#define FREQ_MUL 16000
#define TEF6862_LO_FREQ (875 * FREQ_MUL / 10)
#define TEF6862_HI_FREQ (108 * FREQ_MUL)
/* Write mode sub addresses */
#define WM_SUB_BANDWIDTH 0x0
#define WM_SUB_PLLM 0x1
#define WM_SUB_PLLL 0x2
#define WM_SUB_DAA 0x3
#define WM_SUB_AGC 0x4
#define WM_SUB_BAND 0x5
#define WM_SUB_CONTROL 0x6
#define WM_SUB_LEVEL 0x7
#define WM_SUB_IFCF 0x8
#define WM_SUB_IFCAP 0x9
#define WM_SUB_ACD 0xA
#define WM_SUB_TEST 0xF
/* Different modes of the MSA register */
#define MODE_BUFFER 0x0
#define MODE_PRESET 0x1
#define MODE_SEARCH 0x2
#define MODE_AF_UPDATE 0x3
#define MODE_JUMP 0x4
#define MODE_CHECK 0x5
#define MODE_LOAD 0x6
#define MODE_END 0x7
#define MODE_SHIFT 5
struct tef6862_state {
struct v4l2_subdev sd;
unsigned long freq;
};
static inline struct tef6862_state *to_state(struct v4l2_subdev *sd)
{
return container_of(sd, struct tef6862_state, sd);
}
static u16 tef6862_sigstr(struct i2c_client *client)
{
u8 buf[4];
int err = i2c_master_recv(client, buf, sizeof(buf));
if (err == sizeof(buf))
return buf[3] << 8;
return 0;
}
static int tef6862_g_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *v)
{
if (v->index > 0)
return -EINVAL;
/* only support FM for now */
strlcpy(v->name, "FM", sizeof(v->name));
v->type = V4L2_TUNER_RADIO;
v->rangelow = TEF6862_LO_FREQ;
v->rangehigh = TEF6862_HI_FREQ;
v->rxsubchans = V4L2_TUNER_SUB_MONO;
v->capability = V4L2_TUNER_CAP_LOW;
v->audmode = V4L2_TUNER_MODE_STEREO;
v->signal = tef6862_sigstr(v4l2_get_subdevdata(sd));
return 0;
}
static int tef6862_s_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *v)
{
return v->index ? -EINVAL : 0;
}
static int tef6862_s_frequency(struct v4l2_subdev *sd, struct v4l2_frequency *f)
{
struct tef6862_state *state = to_state(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
u16 pll;
u8 i2cmsg[3];
int err;
if (f->tuner != 0)
return -EINVAL;
pll = 1964 + ((f->frequency - TEF6862_LO_FREQ) * 20) / FREQ_MUL;
i2cmsg[0] = (MODE_PRESET << MODE_SHIFT) | WM_SUB_PLLM;
i2cmsg[1] = (pll >> 8) & 0xff;
i2cmsg[2] = pll & 0xff;
err = i2c_master_send(client, i2cmsg, sizeof(i2cmsg));
if (!err)
state->freq = f->frequency;
return err;
}
static int tef6862_g_frequency(struct v4l2_subdev *sd, struct v4l2_frequency *f)
{
struct tef6862_state *state = to_state(sd);
if (f->tuner != 0)
return -EINVAL;
f->type = V4L2_TUNER_RADIO;
f->frequency = state->freq;
return 0;
}
static int tef6862_g_chip_ident(struct v4l2_subdev *sd,
struct v4l2_dbg_chip_ident *chip)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_TEF6862, 0);
}
static const struct v4l2_subdev_tuner_ops tef6862_tuner_ops = {
.g_tuner = tef6862_g_tuner,
.s_tuner = tef6862_s_tuner,
.s_frequency = tef6862_s_frequency,
.g_frequency = tef6862_g_frequency,
};
static const struct v4l2_subdev_core_ops tef6862_core_ops = {
.g_chip_ident = tef6862_g_chip_ident,
};
static const struct v4l2_subdev_ops tef6862_ops = {
.core = &tef6862_core_ops,
.tuner = &tef6862_tuner_ops,
};
/*
* Generic i2c probe
* concerning the addresses: i2c wants 7 bit (without the r/w bit), so '>>1'
*/
static int __devinit tef6862_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct tef6862_state *state;
struct v4l2_subdev *sd;
/* Check if the adapter supports the needed features */
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -EIO;
v4l_info(client, "chip found @ 0x%02x (%s)\n",
client->addr << 1, client->adapter->name);
state = kmalloc(sizeof(struct tef6862_state), GFP_KERNEL);
if (state == NULL)
return -ENOMEM;
state->freq = TEF6862_LO_FREQ;
sd = &state->sd;
v4l2_i2c_subdev_init(sd, client, &tef6862_ops);
return 0;
}
static int __devexit tef6862_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
v4l2_device_unregister_subdev(sd);
kfree(to_state(sd));
return 0;
}
static const struct i2c_device_id tef6862_id[] = {
{DRIVER_NAME, 0},
{},
};
MODULE_DEVICE_TABLE(i2c, tef6862_id);
static struct i2c_driver tef6862_driver = {
.driver = {
.owner = THIS_MODULE,
.name = DRIVER_NAME,
},
.probe = tef6862_probe,
.remove = tef6862_remove,
.id_table = tef6862_id,
};
static __init int tef6862_init(void)
{
return i2c_add_driver(&tef6862_driver);
}
static __exit void tef6862_exit(void)
{
i2c_del_driver(&tef6862_driver);
}
module_init(tef6862_init);
module_exit(tef6862_exit);
MODULE_DESCRIPTION("TEF6862 Car Radio Enhanced Selectivity Tuner");
MODULE_AUTHOR("Mocean Laboratories");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
k2wl/3.0.y | drivers/staging/intel_sst/intelmid_ctrl.c | 2945 | 25214 | /*
* intelmid_ctrl.c - Intel Sound card driver for MID
*
* Copyright (C) 2008-10 Intel Corp
* Authors: Harsha Priya <priya.harsha@intel.com>
* Vinod Koul <vinod.koul@intel.com>
* Dharageswari R <dharageswari.r@intel.com>
* KP Jeeja <jeeja.kp@intel.com>
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* ALSA driver handling mixer controls for Intel MAD chipset
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <sound/core.h>
#include <sound/control.h>
#include "intel_sst.h"
#include "intel_sst_ioctl.h"
#include "intelmid_snd_control.h"
#include "intelmid.h"
#define HW_CH_BASE 4
#define HW_CH_0 "Hw1"
#define HW_CH_1 "Hw2"
#define HW_CH_2 "Hw3"
#define HW_CH_3 "Hw4"
static char *router_dmics[] = { "DMIC1",
"DMIC2",
"DMIC3",
"DMIC4",
"DMIC5",
"DMIC6"
};
static char *out_names_mrst[] = {"Headphones",
"Internal speakers"};
static char *in_names_mrst[] = {"AMIC",
"DMIC",
"HS_MIC"};
static char *line_out_names_mfld[] = {"Headset",
"IHF ",
"Vibra1 ",
"Vibra2 ",
"NONE "};
static char *out_names_mfld[] = {"Headset ",
"EarPiece "};
static char *in_names_mfld[] = {"AMIC",
"DMIC"};
struct snd_control_val intelmad_ctrl_val[MAX_VENDORS] = {
{
.playback_vol_max = 63,
.playback_vol_min = 0,
.capture_vol_max = 63,
.capture_vol_min = 0,
},
{
.playback_vol_max = 0,
.playback_vol_min = -31,
.capture_vol_max = 0,
.capture_vol_min = -20,
},
{
.playback_vol_max = 0,
.playback_vol_min = -31,
.capture_vol_max = 0,
.capture_vol_min = -31,
.master_vol_max = 0,
.master_vol_min = -126,
},
};
/* control path functionalities */
static inline int snd_intelmad_volume_info(struct snd_ctl_elem_info *uinfo,
int control_type, int max, int min)
{
WARN_ON(!uinfo);
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = control_type;
uinfo->value.integer.min = min;
uinfo->value.integer.max = max;
return 0;
}
/**
* snd_intelmad_mute_info - provides information about the mute controls
*
* @kcontrol: pointer to the control
* @uinfo: pointer to the structure where the control's info need
* to be filled
*
* This function is called when a mixer application requests for control's info
*/
static int snd_intelmad_mute_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
WARN_ON(!uinfo);
WARN_ON(!kcontrol);
/* set up the mute as a boolean mono control with min-max values */
uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
uinfo->count = MONO_CNTL;
uinfo->value.integer.min = MIN_MUTE;
uinfo->value.integer.max = MAX_MUTE;
return 0;
}
/**
* snd_intelmad_capture_volume_info - provides info about the volume control
*
* @kcontrol: pointer to the control
* @uinfo: pointer to the structure where the control's info need
* to be filled
*
* This function is called when a mixer application requests for control's info
*/
static int snd_intelmad_capture_volume_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
snd_intelmad_volume_info(uinfo, MONO_CNTL,
intelmad_ctrl_val[sst_card_vendor_id].capture_vol_max,
intelmad_ctrl_val[sst_card_vendor_id].capture_vol_min);
return 0;
}
/**
* snd_intelmad_playback_volume_info - provides info about the volume control
*
* @kcontrol: pointer to the control
* @uinfo: pointer to the structure where the control's info need
* to be filled
*
* This function is called when a mixer application requests for control's info
*/
static int snd_intelmad_playback_volume_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
snd_intelmad_volume_info(uinfo, STEREO_CNTL,
intelmad_ctrl_val[sst_card_vendor_id].playback_vol_max,
intelmad_ctrl_val[sst_card_vendor_id].playback_vol_min);
return 0;
}
static int snd_intelmad_master_volume_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
snd_intelmad_volume_info(uinfo, STEREO_CNTL,
intelmad_ctrl_val[sst_card_vendor_id].master_vol_max,
intelmad_ctrl_val[sst_card_vendor_id].master_vol_min);
return 0;
}
/**
* snd_intelmad_device_info_mrst - provides information about the devices available
*
* @kcontrol: pointer to the control
* @uinfo: pointer to the structure where the devices's info need
* to be filled
*
* This function is called when a mixer application requests for device's info
*/
static int snd_intelmad_device_info_mrst(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
WARN_ON(!kcontrol);
WARN_ON(!uinfo);
/* setup device select as drop down controls with different values */
if (kcontrol->id.numid == OUTPUT_SEL)
uinfo->value.enumerated.items = ARRAY_SIZE(out_names_mrst);
else
uinfo->value.enumerated.items = ARRAY_SIZE(in_names_mrst);
uinfo->count = MONO_CNTL;
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
if (uinfo->value.enumerated.item >= uinfo->value.enumerated.items)
uinfo->value.enumerated.item = 1;
if (kcontrol->id.numid == OUTPUT_SEL)
strncpy(uinfo->value.enumerated.name,
out_names_mrst[uinfo->value.enumerated.item],
sizeof(uinfo->value.enumerated.name)-1);
else
strncpy(uinfo->value.enumerated.name,
in_names_mrst[uinfo->value.enumerated.item],
sizeof(uinfo->value.enumerated.name)-1);
return 0;
}
static int snd_intelmad_device_info_mfld(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct snd_pmic_ops *scard_ops;
struct snd_intelmad *intelmaddata;
WARN_ON(!kcontrol);
WARN_ON(!uinfo);
intelmaddata = kcontrol->private_data;
WARN_ON(!intelmaddata->sstdrv_ops);
scard_ops = intelmaddata->sstdrv_ops->scard_ops;
/* setup device select as drop down controls with different values */
if (kcontrol->id.numid == OUTPUT_SEL)
uinfo->value.enumerated.items = ARRAY_SIZE(out_names_mfld);
else if (kcontrol->id.numid == INPUT_SEL)
uinfo->value.enumerated.items = ARRAY_SIZE(in_names_mfld);
else if (kcontrol->id.numid == LINEOUT_SEL_MFLD) {
uinfo->value.enumerated.items = ARRAY_SIZE(line_out_names_mfld);
scard_ops->line_out_names_cnt = uinfo->value.enumerated.items;
} else
return -EINVAL;
uinfo->count = MONO_CNTL;
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
if (uinfo->value.enumerated.item >= uinfo->value.enumerated.items)
uinfo->value.enumerated.item = 1;
if (kcontrol->id.numid == OUTPUT_SEL)
strncpy(uinfo->value.enumerated.name,
out_names_mfld[uinfo->value.enumerated.item],
sizeof(uinfo->value.enumerated.name)-1);
else if (kcontrol->id.numid == INPUT_SEL)
strncpy(uinfo->value.enumerated.name,
in_names_mfld[uinfo->value.enumerated.item],
sizeof(uinfo->value.enumerated.name)-1);
else if (kcontrol->id.numid == LINEOUT_SEL_MFLD)
strncpy(uinfo->value.enumerated.name,
line_out_names_mfld[uinfo->value.enumerated.item],
sizeof(uinfo->value.enumerated.name)-1);
else
return -EINVAL;
return 0;
}
/**
* snd_intelmad_volume_get - gets the current volume for the control
*
* @kcontrol: pointer to the control
* @uval: pointer to the structure where the control's info need
* to be filled
*
* This function is called when .get function of a control is invoked from app
*/
static int snd_intelmad_volume_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *uval)
{
int ret_val = 0, cntl_list[2] = {0,};
int value = 0;
struct snd_intelmad *intelmaddata;
struct snd_pmic_ops *scard_ops;
pr_debug("snd_intelmad_volume_get called\n");
WARN_ON(!uval);
WARN_ON(!kcontrol);
intelmaddata = kcontrol->private_data;
WARN_ON(!intelmaddata->sstdrv_ops);
scard_ops = intelmaddata->sstdrv_ops->scard_ops;
WARN_ON(!scard_ops);
switch (kcontrol->id.numid) {
case PLAYBACK_VOL:
cntl_list[0] = PMIC_SND_RIGHT_PB_VOL;
cntl_list[1] = PMIC_SND_LEFT_PB_VOL;
break;
case CAPTURE_VOL:
cntl_list[0] = PMIC_SND_CAPTURE_VOL;
break;
case MASTER_VOL:
cntl_list[0] = PMIC_SND_RIGHT_MASTER_VOL;
cntl_list[1] = PMIC_SND_LEFT_MASTER_VOL;
break;
default:
return -EINVAL;
}
ret_val = scard_ops->get_vol(cntl_list[0], &value);
uval->value.integer.value[0] = value;
if (ret_val)
return ret_val;
if (kcontrol->id.numid == PLAYBACK_VOL ||
kcontrol->id.numid == MASTER_VOL) {
ret_val = scard_ops->get_vol(cntl_list[1], &value);
uval->value.integer.value[1] = value;
}
return ret_val;
}
/**
* snd_intelmad_mute_get - gets the current mute status for the control
*
* @kcontrol: pointer to the control
* @uval: pointer to the structure where the control's info need
* to be filled
*
* This function is called when .get function of a control is invoked from app
*/
static int snd_intelmad_mute_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *uval)
{
int cntl_list = 0, ret_val = 0;
u8 value = 0;
struct snd_intelmad *intelmaddata;
struct snd_pmic_ops *scard_ops;
pr_debug("Mute_get called\n");
WARN_ON(!uval);
WARN_ON(!kcontrol);
intelmaddata = kcontrol->private_data;
WARN_ON(!intelmaddata->sstdrv_ops);
scard_ops = intelmaddata->sstdrv_ops->scard_ops;
WARN_ON(!scard_ops);
switch (kcontrol->id.numid) {
case PLAYBACK_MUTE:
if (intelmaddata->output_sel == STEREO_HEADPHONE)
cntl_list = PMIC_SND_LEFT_HP_MUTE;
else if ((intelmaddata->output_sel == INTERNAL_SPKR) ||
(intelmaddata->output_sel == MONO_EARPIECE))
cntl_list = PMIC_SND_LEFT_SPEAKER_MUTE;
break;
case CAPTURE_MUTE:
if (intelmaddata->input_sel == DMIC)
cntl_list = PMIC_SND_DMIC_MUTE;
else if (intelmaddata->input_sel == AMIC)
cntl_list = PMIC_SND_AMIC_MUTE;
else if (intelmaddata->input_sel == HS_MIC)
cntl_list = PMIC_SND_HP_MIC_MUTE;
break;
case MASTER_MUTE:
uval->value.integer.value[0] = intelmaddata->master_mute;
return 0;
default:
return -EINVAL;
}
ret_val = scard_ops->get_mute(cntl_list, &value);
uval->value.integer.value[0] = value;
return ret_val;
}
/**
* snd_intelmad_volume_set - sets the volume control's info
*
* @kcontrol: pointer to the control
* @uval: pointer to the structure where the control's info is
* available to be set
*
* This function is called when .set function of a control is invoked from app
*/
static int snd_intelmad_volume_set(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *uval)
{
int ret_val, cntl_list[2] = {0,};
struct snd_intelmad *intelmaddata;
struct snd_pmic_ops *scard_ops;
pr_debug("volume set called:%ld %ld\n",
uval->value.integer.value[0],
uval->value.integer.value[1]);
WARN_ON(!uval);
WARN_ON(!kcontrol);
intelmaddata = kcontrol->private_data;
WARN_ON(!intelmaddata->sstdrv_ops);
scard_ops = intelmaddata->sstdrv_ops->scard_ops;
WARN_ON(!scard_ops);
switch (kcontrol->id.numid) {
case PLAYBACK_VOL:
cntl_list[0] = PMIC_SND_LEFT_PB_VOL;
cntl_list[1] = PMIC_SND_RIGHT_PB_VOL;
break;
case CAPTURE_VOL:
cntl_list[0] = PMIC_SND_CAPTURE_VOL;
break;
case MASTER_VOL:
cntl_list[0] = PMIC_SND_LEFT_MASTER_VOL;
cntl_list[1] = PMIC_SND_RIGHT_MASTER_VOL;
break;
default:
return -EINVAL;
}
ret_val = scard_ops->set_vol(cntl_list[0],
uval->value.integer.value[0]);
if (ret_val)
return ret_val;
if (kcontrol->id.numid == PLAYBACK_VOL ||
kcontrol->id.numid == MASTER_VOL)
ret_val = scard_ops->set_vol(cntl_list[1],
uval->value.integer.value[1]);
return ret_val;
}
/**
* snd_intelmad_mute_set - sets the mute control's info
*
* @kcontrol: pointer to the control
* @uval: pointer to the structure where the control's info is
* available to be set
*
* This function is called when .set function of a control is invoked from app
*/
static int snd_intelmad_mute_set(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *uval)
{
int cntl_list[2] = {0,}, ret_val;
struct snd_intelmad *intelmaddata;
struct snd_pmic_ops *scard_ops;
pr_debug("snd_intelmad_mute_set called\n");
WARN_ON(!uval);
WARN_ON(!kcontrol);
intelmaddata = kcontrol->private_data;
WARN_ON(!intelmaddata->sstdrv_ops);
scard_ops = intelmaddata->sstdrv_ops->scard_ops;
WARN_ON(!scard_ops);
kcontrol->private_value = uval->value.integer.value[0];
switch (kcontrol->id.numid) {
case PLAYBACK_MUTE:
if (intelmaddata->output_sel == STEREO_HEADPHONE) {
cntl_list[0] = PMIC_SND_LEFT_HP_MUTE;
cntl_list[1] = PMIC_SND_RIGHT_HP_MUTE;
} else if ((intelmaddata->output_sel == INTERNAL_SPKR) ||
(intelmaddata->output_sel == MONO_EARPIECE)) {
cntl_list[0] = PMIC_SND_LEFT_SPEAKER_MUTE;
cntl_list[1] = PMIC_SND_RIGHT_SPEAKER_MUTE;
}
break;
case CAPTURE_MUTE:/*based on sel device mute the i/p dev*/
if (intelmaddata->input_sel == DMIC)
cntl_list[0] = PMIC_SND_DMIC_MUTE;
else if (intelmaddata->input_sel == AMIC)
cntl_list[0] = PMIC_SND_AMIC_MUTE;
else if (intelmaddata->input_sel == HS_MIC)
cntl_list[0] = PMIC_SND_HP_MIC_MUTE;
break;
case MASTER_MUTE:
cntl_list[0] = PMIC_SND_MUTE_ALL;
intelmaddata->master_mute = uval->value.integer.value[0];
break;
default:
return -EINVAL;
}
ret_val = scard_ops->set_mute(cntl_list[0],
uval->value.integer.value[0]);
if (ret_val)
return ret_val;
if (kcontrol->id.numid == PLAYBACK_MUTE)
ret_val = scard_ops->set_mute(cntl_list[1],
uval->value.integer.value[0]);
return ret_val;
}
/**
* snd_intelmad_device_get - get the device select control's info
*
* @kcontrol: pointer to the control
* @uval: pointer to the structure where the control's info is
* to be filled
*
* This function is called when .get function of a control is invoked from app
*/
static int snd_intelmad_device_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *uval)
{
struct snd_intelmad *intelmaddata;
struct snd_pmic_ops *scard_ops;
pr_debug("device_get called\n");
WARN_ON(!uval);
WARN_ON(!kcontrol);
intelmaddata = kcontrol->private_data;
scard_ops = intelmaddata->sstdrv_ops->scard_ops;
if (intelmaddata->cpu_id == CPU_CHIP_PENWELL) {
if (kcontrol->id.numid == OUTPUT_SEL)
uval->value.enumerated.item[0] =
scard_ops->output_dev_id;
else if (kcontrol->id.numid == INPUT_SEL)
uval->value.enumerated.item[0] =
scard_ops->input_dev_id;
else if (kcontrol->id.numid == LINEOUT_SEL_MFLD)
uval->value.enumerated.item[0] =
scard_ops->lineout_dev_id;
else
return -EINVAL;
} else if (intelmaddata->cpu_id == CPU_CHIP_LINCROFT) {
if (kcontrol->id.numid == OUTPUT_SEL)
/* There is a mismatch here.
* ALSA expects 1 for internal speaker.
* But internally, we may give 2 for internal speaker.
*/
if (scard_ops->output_dev_id == MONO_EARPIECE ||
scard_ops->output_dev_id == INTERNAL_SPKR)
uval->value.enumerated.item[0] = MONO_EARPIECE;
else if (scard_ops->output_dev_id == STEREO_HEADPHONE)
uval->value.enumerated.item[0] =
STEREO_HEADPHONE;
else
return -EINVAL;
else if (kcontrol->id.numid == INPUT_SEL)
uval->value.enumerated.item[0] =
scard_ops->input_dev_id;
else
return -EINVAL;
} else
uval->value.enumerated.item[0] = kcontrol->private_value;
return 0;
}
/**
* snd_intelmad_device_set - set the device select control's info
*
* @kcontrol: pointer to the control
* @uval: pointer to the structure where the control's info is
* available to be set
*
* This function is called when .set function of a control is invoked from app
*/
static int snd_intelmad_device_set(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *uval)
{
struct snd_intelmad *intelmaddata;
struct snd_pmic_ops *scard_ops;
int ret_val = 0, vendor, status;
struct intel_sst_pcm_control *pcm_control;
pr_debug("snd_intelmad_device_set called\n");
WARN_ON(!uval);
WARN_ON(!kcontrol);
status = -1;
intelmaddata = kcontrol->private_data;
WARN_ON(!intelmaddata->sstdrv_ops);
scard_ops = intelmaddata->sstdrv_ops->scard_ops;
WARN_ON(!scard_ops);
/* store value with driver */
kcontrol->private_value = uval->value.enumerated.item[0];
switch (kcontrol->id.numid) {
case OUTPUT_SEL:
ret_val = scard_ops->set_output_dev(
uval->value.enumerated.item[0]);
intelmaddata->output_sel = uval->value.enumerated.item[0];
break;
case INPUT_SEL:
vendor = intelmaddata->sstdrv_ops->vendor_id;
if ((vendor == SND_MX) || (vendor == SND_FS)) {
pcm_control = intelmaddata->sstdrv_ops->pcm_control;
if (uval->value.enumerated.item[0] == HS_MIC)
status = 1;
else
status = 0;
pcm_control->device_control(
SST_ENABLE_RX_TIME_SLOT, &status);
}
ret_val = scard_ops->set_input_dev(
uval->value.enumerated.item[0]);
intelmaddata->input_sel = uval->value.enumerated.item[0];
break;
case LINEOUT_SEL_MFLD:
ret_val = scard_ops->set_lineout_dev(
uval->value.enumerated.item[0]);
intelmaddata->lineout_sel = uval->value.enumerated.item[0];
break;
default:
return -EINVAL;
}
kcontrol->private_value = uval->value.enumerated.item[0];
return ret_val;
}
static int snd_intelmad_device_dmic_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *uval)
{
struct snd_intelmad *intelmaddata;
struct snd_pmic_ops *scard_ops;
WARN_ON(!uval);
WARN_ON(!kcontrol);
intelmaddata = kcontrol->private_data;
scard_ops = intelmaddata->sstdrv_ops->scard_ops;
if (scard_ops->input_dev_id != DMIC) {
pr_debug("input dev = 0x%x\n", scard_ops->input_dev_id);
return 0;
}
if (intelmaddata->cpu_id == CPU_CHIP_PENWELL)
uval->value.enumerated.item[0] = kcontrol->private_value;
else
pr_debug(" CPU id = 0x%xis invalid.\n",
intelmaddata->cpu_id);
return 0;
}
void msic_set_bit(u8 index, unsigned int *available_dmics)
{
*available_dmics |= (1 << index);
}
void msic_clear_bit(u8 index, unsigned int *available_dmics)
{
*available_dmics &= ~(1 << index);
}
int msic_is_set_bit(u8 index, unsigned int *available_dmics)
{
int ret_val;
ret_val = (*available_dmics & (1 << index));
return ret_val;
}
static int snd_intelmad_device_dmic_set(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *uval)
{
struct snd_intelmad *intelmaddata;
struct snd_pmic_ops *scard_ops;
int i, dmic_index;
unsigned int available_dmics;
int jump_count;
int max_dmics = ARRAY_SIZE(router_dmics);
WARN_ON(!uval);
WARN_ON(!kcontrol);
intelmaddata = kcontrol->private_data;
WARN_ON(!intelmaddata->sstdrv_ops);
scard_ops = intelmaddata->sstdrv_ops->scard_ops;
WARN_ON(!scard_ops);
if (scard_ops->input_dev_id != DMIC) {
pr_debug("input dev = 0x%x\n", scard_ops->input_dev_id);
return 0;
}
available_dmics = scard_ops->available_dmics;
if (kcontrol->private_value > uval->value.enumerated.item[0]) {
pr_debug("jump count -1.\n");
jump_count = -1;
} else {
pr_debug("jump count 1.\n");
jump_count = 1;
}
dmic_index = uval->value.enumerated.item[0];
pr_debug("set function. dmic_index = %d, avl_dmic = 0x%x\n",
dmic_index, available_dmics);
for (i = 0; i < max_dmics; i++) {
pr_debug("set function. loop index = 0x%x. dmic_index = 0x%x\n",
i, dmic_index);
if (!msic_is_set_bit(dmic_index, &available_dmics)) {
msic_clear_bit(kcontrol->private_value,
&available_dmics);
msic_set_bit(dmic_index, &available_dmics);
kcontrol->private_value = dmic_index;
scard_ops->available_dmics = available_dmics;
scard_ops->hw_dmic_map[kcontrol->id.numid-HW_CH_BASE] =
kcontrol->private_value;
scard_ops->set_hw_dmic_route
(kcontrol->id.numid-HW_CH_BASE);
return 0;
}
dmic_index += jump_count;
if (dmic_index > (max_dmics - 1) && jump_count == 1) {
pr_debug("Resettingthe dmic index to 0.\n");
dmic_index = 0;
} else if (dmic_index == -1 && jump_count == -1) {
pr_debug("Resetting the dmic index to 5.\n");
dmic_index = max_dmics - 1;
}
}
return -EINVAL;
}
static int snd_intelmad_device_dmic_info_mfld(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct snd_intelmad *intelmaddata;
struct snd_pmic_ops *scard_ops;
uinfo->count = MONO_CNTL;
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->value.enumerated.items = ARRAY_SIZE(router_dmics);
intelmaddata = kcontrol->private_data;
WARN_ON(!intelmaddata->sstdrv_ops);
scard_ops = intelmaddata->sstdrv_ops->scard_ops;
WARN_ON(!scard_ops);
if (uinfo->value.enumerated.item >= uinfo->value.enumerated.items)
uinfo->value.enumerated.item =
uinfo->value.enumerated.items - 1;
strncpy(uinfo->value.enumerated.name,
router_dmics[uinfo->value.enumerated.item],
sizeof(uinfo->value.enumerated.name)-1);
msic_set_bit(kcontrol->private_value, &scard_ops->available_dmics);
pr_debug("info function. avl_dmic = 0x%x",
scard_ops->available_dmics);
scard_ops->hw_dmic_map[kcontrol->id.numid-HW_CH_BASE] =
kcontrol->private_value;
return 0;
}
struct snd_kcontrol_new snd_intelmad_controls_mrst[MAX_CTRL] __devinitdata = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Playback Source",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_intelmad_device_info_mrst,
.get = snd_intelmad_device_get,
.put = snd_intelmad_device_set,
.private_value = 0,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Capture Source",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_intelmad_device_info_mrst,
.get = snd_intelmad_device_get,
.put = snd_intelmad_device_set,
.private_value = 0,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Playback Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_intelmad_playback_volume_info,
.get = snd_intelmad_volume_get,
.put = snd_intelmad_volume_set,
.private_value = 0,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Playback Switch",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_intelmad_mute_info,
.get = snd_intelmad_mute_get,
.put = snd_intelmad_mute_set,
.private_value = 0,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Capture Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_intelmad_capture_volume_info,
.get = snd_intelmad_volume_get,
.put = snd_intelmad_volume_set,
.private_value = 0,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Capture Switch",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_intelmad_mute_info,
.get = snd_intelmad_mute_get,
.put = snd_intelmad_mute_set,
.private_value = 0,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Master Playback Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_intelmad_master_volume_info,
.get = snd_intelmad_volume_get,
.put = snd_intelmad_volume_set,
.private_value = 0,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Master Playback Switch",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_intelmad_mute_info,
.get = snd_intelmad_mute_get,
.put = snd_intelmad_mute_set,
.private_value = 0,
},
};
struct snd_kcontrol_new
snd_intelmad_controls_mfld[MAX_CTRL_MFLD] __devinitdata = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Playback Source",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_intelmad_device_info_mfld,
.get = snd_intelmad_device_get,
.put = snd_intelmad_device_set,
.private_value = 0,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Capture Source",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_intelmad_device_info_mfld,
.get = snd_intelmad_device_get,
.put = snd_intelmad_device_set,
.private_value = 0,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Line out",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_intelmad_device_info_mfld,
.get = snd_intelmad_device_get,
.put = snd_intelmad_device_set,
.private_value = 0,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = HW_CH_0,
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_intelmad_device_dmic_info_mfld,
.get = snd_intelmad_device_dmic_get,
.put = snd_intelmad_device_dmic_set,
.private_value = 0
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = HW_CH_1,
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_intelmad_device_dmic_info_mfld,
.get = snd_intelmad_device_dmic_get,
.put = snd_intelmad_device_dmic_set,
.private_value = 1
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = HW_CH_2,
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_intelmad_device_dmic_info_mfld,
.get = snd_intelmad_device_dmic_get,
.put = snd_intelmad_device_dmic_set,
.private_value = 2
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = HW_CH_3,
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_intelmad_device_dmic_info_mfld,
.get = snd_intelmad_device_dmic_get,
.put = snd_intelmad_device_dmic_set,
.private_value = 3
}
};
| gpl-2.0 |
kolargol/linux | tools/perf/arch/x86/util/dwarf-regs.c | 3713 | 1796 | /*
* dwarf-regs.c : Mapping of DWARF debug register numbers into register names.
* Extracted from probe-finder.c
*
* Written by Masami Hiramatsu <mhiramat@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include <stddef.h>
#include <dwarf-regs.h>
/*
* Generic dwarf analysis helpers
*/
#define X86_32_MAX_REGS 8
const char *x86_32_regs_table[X86_32_MAX_REGS] = {
"%ax",
"%cx",
"%dx",
"%bx",
"$stack", /* Stack address instead of %sp */
"%bp",
"%si",
"%di",
};
#define X86_64_MAX_REGS 16
const char *x86_64_regs_table[X86_64_MAX_REGS] = {
"%ax",
"%dx",
"%cx",
"%bx",
"%si",
"%di",
"%bp",
"%sp",
"%r8",
"%r9",
"%r10",
"%r11",
"%r12",
"%r13",
"%r14",
"%r15",
};
/* TODO: switching by dwarf address size */
#ifdef __x86_64__
#define ARCH_MAX_REGS X86_64_MAX_REGS
#define arch_regs_table x86_64_regs_table
#else
#define ARCH_MAX_REGS X86_32_MAX_REGS
#define arch_regs_table x86_32_regs_table
#endif
/* Return architecture dependent register string (for kprobe-tracer) */
const char *get_arch_regstr(unsigned int n)
{
return (n <= ARCH_MAX_REGS) ? arch_regs_table[n] : NULL;
}
| gpl-2.0 |
ac100-ru/picasso-kernel | sound/soc/samsung/smdk2443_wm9710.c | 4481 | 1706 | /*
* smdk2443_wm9710.c -- SoC audio for smdk2443
*
* Copyright 2007 Wolfson Microelectronics PLC.
* Author: Graeme Gregory
* graeme.gregory@wolfsonmicro.com or linux@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 <sound/soc.h>
static struct snd_soc_card smdk2443;
static struct snd_soc_dai_link smdk2443_dai[] = {
{
.name = "AC97",
.stream_name = "AC97 HiFi",
.cpu_dai_name = "samsung-ac97",
.codec_dai_name = "ac97-hifi",
.codec_name = "ac97-codec",
.platform_name = "samsung-ac97",
},
};
static struct snd_soc_card smdk2443 = {
.name = "SMDK2443",
.owner = THIS_MODULE,
.dai_link = smdk2443_dai,
.num_links = ARRAY_SIZE(smdk2443_dai),
};
static struct platform_device *smdk2443_snd_ac97_device;
static int __init smdk2443_init(void)
{
int ret;
smdk2443_snd_ac97_device = platform_device_alloc("soc-audio", -1);
if (!smdk2443_snd_ac97_device)
return -ENOMEM;
platform_set_drvdata(smdk2443_snd_ac97_device, &smdk2443);
ret = platform_device_add(smdk2443_snd_ac97_device);
if (ret)
platform_device_put(smdk2443_snd_ac97_device);
return ret;
}
static void __exit smdk2443_exit(void)
{
platform_device_unregister(smdk2443_snd_ac97_device);
}
module_init(smdk2443_init);
module_exit(smdk2443_exit);
/* Module information */
MODULE_AUTHOR("Graeme Gregory, graeme.gregory@wolfsonmicro.com, www.wolfsonmicro.com");
MODULE_DESCRIPTION("ALSA SoC WM9710 SMDK2443");
MODULE_LICENSE("GPL");
| gpl-2.0 |
wan5xp/android_kernel_xiaomi_armani | arch/arm/mach-orion5x/rd88f5182-setup.c | 4737 | 7768 | /*
* arch/arm/mach-orion5x/rd88f5182-setup.c
*
* Marvell Orion-NAS Reference Design Setup
*
* Maintainer: Ronen Shitrit <rshitrit@marvell.com>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/gpio.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/pci.h>
#include <linux/irq.h>
#include <linux/mtd/physmap.h>
#include <linux/mv643xx_eth.h>
#include <linux/ata_platform.h>
#include <linux/i2c.h>
#include <asm/mach-types.h>
#include <asm/leds.h>
#include <asm/mach/arch.h>
#include <asm/mach/pci.h>
#include <mach/orion5x.h>
#include "common.h"
#include "mpp.h"
/*****************************************************************************
* RD-88F5182 Info
****************************************************************************/
/*
* 512K NOR flash Device bus boot chip select
*/
#define RD88F5182_NOR_BOOT_BASE 0xf4000000
#define RD88F5182_NOR_BOOT_SIZE SZ_512K
/*
* 16M NOR flash on Device bus chip select 1
*/
#define RD88F5182_NOR_BASE 0xfc000000
#define RD88F5182_NOR_SIZE SZ_16M
/*
* PCI
*/
#define RD88F5182_PCI_SLOT0_OFFS 7
#define RD88F5182_PCI_SLOT0_IRQ_A_PIN 7
#define RD88F5182_PCI_SLOT0_IRQ_B_PIN 6
/*
* GPIO Debug LED
*/
#define RD88F5182_GPIO_DBG_LED 0
/*****************************************************************************
* 16M NOR Flash on Device bus CS1
****************************************************************************/
static struct physmap_flash_data rd88f5182_nor_flash_data = {
.width = 1,
};
static struct resource rd88f5182_nor_flash_resource = {
.flags = IORESOURCE_MEM,
.start = RD88F5182_NOR_BASE,
.end = RD88F5182_NOR_BASE + RD88F5182_NOR_SIZE - 1,
};
static struct platform_device rd88f5182_nor_flash = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &rd88f5182_nor_flash_data,
},
.num_resources = 1,
.resource = &rd88f5182_nor_flash_resource,
};
#ifdef CONFIG_LEDS
/*****************************************************************************
* Use GPIO debug led as CPU active indication
****************************************************************************/
static void rd88f5182_dbgled_event(led_event_t evt)
{
int val;
if (evt == led_idle_end)
val = 1;
else if (evt == led_idle_start)
val = 0;
else
return;
gpio_set_value(RD88F5182_GPIO_DBG_LED, val);
}
static int __init rd88f5182_dbgled_init(void)
{
int pin;
if (machine_is_rd88f5182()) {
pin = RD88F5182_GPIO_DBG_LED;
if (gpio_request(pin, "DBGLED") == 0) {
if (gpio_direction_output(pin, 0) != 0) {
printk(KERN_ERR "rd88f5182_dbgled_init failed "
"to set output pin %d\n", pin);
gpio_free(pin);
return 0;
}
} else {
printk(KERN_ERR "rd88f5182_dbgled_init failed "
"to request gpio %d\n", pin);
return 0;
}
leds_event = rd88f5182_dbgled_event;
}
return 0;
}
__initcall(rd88f5182_dbgled_init);
#endif
/*****************************************************************************
* PCI
****************************************************************************/
void __init rd88f5182_pci_preinit(void)
{
int pin;
/*
* Configure PCI GPIO IRQ pins
*/
pin = RD88F5182_PCI_SLOT0_IRQ_A_PIN;
if (gpio_request(pin, "PCI IntA") == 0) {
if (gpio_direction_input(pin) == 0) {
irq_set_irq_type(gpio_to_irq(pin), IRQ_TYPE_LEVEL_LOW);
} else {
printk(KERN_ERR "rd88f5182_pci_preinit failed to "
"set_irq_type pin %d\n", pin);
gpio_free(pin);
}
} else {
printk(KERN_ERR "rd88f5182_pci_preinit failed to request gpio %d\n", pin);
}
pin = RD88F5182_PCI_SLOT0_IRQ_B_PIN;
if (gpio_request(pin, "PCI IntB") == 0) {
if (gpio_direction_input(pin) == 0) {
irq_set_irq_type(gpio_to_irq(pin), IRQ_TYPE_LEVEL_LOW);
} else {
printk(KERN_ERR "rd88f5182_pci_preinit failed to "
"set_irq_type pin %d\n", pin);
gpio_free(pin);
}
} else {
printk(KERN_ERR "rd88f5182_pci_preinit failed to gpio_request %d\n", pin);
}
}
static int __init rd88f5182_pci_map_irq(const struct pci_dev *dev, u8 slot,
u8 pin)
{
int irq;
/*
* Check for devices with hard-wired IRQs.
*/
irq = orion5x_pci_map_irq(dev, slot, pin);
if (irq != -1)
return irq;
/*
* PCI IRQs are connected via GPIOs
*/
switch (slot - RD88F5182_PCI_SLOT0_OFFS) {
case 0:
if (pin == 1)
return gpio_to_irq(RD88F5182_PCI_SLOT0_IRQ_A_PIN);
else
return gpio_to_irq(RD88F5182_PCI_SLOT0_IRQ_B_PIN);
default:
return -1;
}
}
static struct hw_pci rd88f5182_pci __initdata = {
.nr_controllers = 2,
.preinit = rd88f5182_pci_preinit,
.swizzle = pci_std_swizzle,
.setup = orion5x_pci_sys_setup,
.scan = orion5x_pci_sys_scan_bus,
.map_irq = rd88f5182_pci_map_irq,
};
static int __init rd88f5182_pci_init(void)
{
if (machine_is_rd88f5182())
pci_common_init(&rd88f5182_pci);
return 0;
}
subsys_initcall(rd88f5182_pci_init);
/*****************************************************************************
* Ethernet
****************************************************************************/
static struct mv643xx_eth_platform_data rd88f5182_eth_data = {
.phy_addr = MV643XX_ETH_PHY_ADDR(8),
};
/*****************************************************************************
* RTC DS1338 on I2C bus
****************************************************************************/
static struct i2c_board_info __initdata rd88f5182_i2c_rtc = {
I2C_BOARD_INFO("ds1338", 0x68),
};
/*****************************************************************************
* Sata
****************************************************************************/
static struct mv_sata_platform_data rd88f5182_sata_data = {
.n_ports = 2,
};
/*****************************************************************************
* General Setup
****************************************************************************/
static unsigned int rd88f5182_mpp_modes[] __initdata = {
MPP0_GPIO, /* Debug Led */
MPP1_GPIO, /* Reset Switch */
MPP2_UNUSED,
MPP3_GPIO, /* RTC Int */
MPP4_GPIO,
MPP5_GPIO,
MPP6_GPIO, /* PCI_intA */
MPP7_GPIO, /* PCI_intB */
MPP8_UNUSED,
MPP9_UNUSED,
MPP10_UNUSED,
MPP11_UNUSED,
MPP12_SATA_LED, /* SATA 0 presence */
MPP13_SATA_LED, /* SATA 1 presence */
MPP14_SATA_LED, /* SATA 0 active */
MPP15_SATA_LED, /* SATA 1 active */
MPP16_UNUSED,
MPP17_UNUSED,
MPP18_UNUSED,
MPP19_UNUSED,
0,
};
static void __init rd88f5182_init(void)
{
/*
* Setup basic Orion functions. Need to be called early.
*/
orion5x_init();
orion5x_mpp_conf(rd88f5182_mpp_modes);
/*
* MPP[20] PCI Clock to MV88F5182
* MPP[21] PCI Clock to mini PCI CON11
* MPP[22] USB 0 over current indication
* MPP[23] USB 1 over current indication
* MPP[24] USB 1 over current enable
* MPP[25] USB 0 over current enable
*/
/*
* Configure peripherals.
*/
orion5x_ehci0_init();
orion5x_ehci1_init();
orion5x_eth_init(&rd88f5182_eth_data);
orion5x_i2c_init();
orion5x_sata_init(&rd88f5182_sata_data);
orion5x_uart0_init();
orion5x_xor_init();
orion5x_setup_dev_boot_win(RD88F5182_NOR_BOOT_BASE,
RD88F5182_NOR_BOOT_SIZE);
orion5x_setup_dev1_win(RD88F5182_NOR_BASE, RD88F5182_NOR_SIZE);
platform_device_register(&rd88f5182_nor_flash);
i2c_register_board_info(0, &rd88f5182_i2c_rtc, 1);
}
MACHINE_START(RD88F5182, "Marvell Orion-NAS Reference Design")
/* Maintainer: Ronen Shitrit <rshitrit@marvell.com> */
.atag_offset = 0x100,
.init_machine = rd88f5182_init,
.map_io = orion5x_map_io,
.init_early = orion5x_init_early,
.init_irq = orion5x_init_irq,
.timer = &orion5x_timer,
.restart = orion5x_restart,
MACHINE_END
| gpl-2.0 |
MoKee/android_kernel_htc_msm8960 | arch/mips/pnx8550/common/prom.c | 4993 | 2464 | /*
*
* Per Hallsmark, per.hallsmark@mvista.com
*
* Based on jmr3927/common/prom.c
*
* 2004 (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 <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/serial_pnx8xxx.h>
#include <asm/bootinfo.h>
#include <uart.h>
/* #define DEBUG_CMDLINE */
extern int prom_argc;
extern char **prom_argv, **prom_envp;
typedef struct
{
char *name;
/* char *val; */
}t_env_var;
char * __init prom_getcmdline(void)
{
return &(arcs_cmdline[0]);
}
void __init prom_init_cmdline(void)
{
int i;
arcs_cmdline[0] = '\0';
for (i = 0; i < prom_argc; i++) {
strcat(arcs_cmdline, prom_argv[i]);
strcat(arcs_cmdline, " ");
}
}
char *prom_getenv(char *envname)
{
/*
* Return a pointer to the given environment variable.
* Environment variables are stored in the form of "memsize=64".
*/
t_env_var *env = (t_env_var *)prom_envp;
int i;
i = strlen(envname);
while(env->name) {
if(strncmp(envname, env->name, i) == 0) {
return(env->name + strlen(envname) + 1);
}
env++;
}
return(NULL);
}
inline unsigned char str2hexnum(unsigned char c)
{
if(c >= '0' && c <= '9')
return c - '0';
if(c >= 'a' && c <= 'f')
return c - 'a' + 10;
if(c >= 'A' && c <= 'F')
return c - 'A' + 10;
return 0; /* foo */
}
inline void str2eaddr(unsigned char *ea, unsigned char *str)
{
int i;
for(i = 0; i < 6; i++) {
unsigned char num;
if((*str == '.') || (*str == ':'))
str++;
num = str2hexnum(*str++) << 4;
num |= (str2hexnum(*str++));
ea[i] = num;
}
}
int get_ethernet_addr(char *ethernet_addr)
{
char *ethaddr_str;
ethaddr_str = prom_getenv("ethaddr");
if (!ethaddr_str) {
printk("ethaddr not set in boot prom\n");
return -1;
}
str2eaddr(ethernet_addr, ethaddr_str);
return 0;
}
void __init prom_free_prom_memory(void)
{
}
extern int pnx8550_console_port;
/* used by early printk */
void prom_putchar(char c)
{
if (pnx8550_console_port != -1) {
/* Wait until FIFO not full */
while( ((ip3106_fifo(UART_BASE, pnx8550_console_port) & PNX8XXX_UART_FIFO_TXFIFO) >> 16) >= 16)
;
/* Send one char */
ip3106_fifo(UART_BASE, pnx8550_console_port) = c;
}
}
EXPORT_SYMBOL(get_ethernet_addr);
EXPORT_SYMBOL(str2eaddr);
| gpl-2.0 |
marshallshen/android-os | drivers/watchdog/intel_scu_watchdog.c | 7297 | 15505 | /*
* Intel_SCU 0.2: An Intel SCU IOH Based Watchdog Device
* for Intel part #(s):
* - AF82MP20 PCH
*
* Copyright (C) 2009-2010 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General
* Public License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
* The full GNU General Public License is included in this
* distribution in the file called COPYING.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/compiler.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/miscdevice.h>
#include <linux/watchdog.h>
#include <linux/fs.h>
#include <linux/notifier.h>
#include <linux/reboot.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#include <linux/io.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/signal.h>
#include <linux/sfi.h>
#include <asm/irq.h>
#include <linux/atomic.h>
#include <asm/intel_scu_ipc.h>
#include <asm/apb_timer.h>
#include <asm/mrst.h>
#include "intel_scu_watchdog.h"
/* Bounds number of times we will retry loading time count */
/* This retry is a work around for a silicon bug. */
#define MAX_RETRY 16
#define IPC_SET_WATCHDOG_TIMER 0xF8
static int timer_margin = DEFAULT_SOFT_TO_HARD_MARGIN;
module_param(timer_margin, int, 0);
MODULE_PARM_DESC(timer_margin,
"Watchdog timer margin"
"Time between interrupt and resetting the system"
"The range is from 1 to 160"
"This is the time for all keep alives to arrive");
static int timer_set = DEFAULT_TIME;
module_param(timer_set, int, 0);
MODULE_PARM_DESC(timer_set,
"Default Watchdog timer setting"
"Complete cycle time"
"The range is from 1 to 170"
"This is the time for all keep alives to arrive");
/* After watchdog device is closed, check force_boot. If:
* force_boot == 0, then force boot on next watchdog interrupt after close,
* force_boot == 1, then force boot immediately when device is closed.
*/
static int force_boot;
module_param(force_boot, int, 0);
MODULE_PARM_DESC(force_boot,
"A value of 1 means that the driver will reboot"
"the system immediately if the /dev/watchdog device is closed"
"A value of 0 means that when /dev/watchdog device is closed"
"the watchdog timer will be refreshed for one more interval"
"of length: timer_set. At the end of this interval, the"
"watchdog timer will reset the system."
);
/* there is only one device in the system now; this can be made into
* an array in the future if we have more than one device */
static struct intel_scu_watchdog_dev watchdog_device;
/* Forces restart, if force_reboot is set */
static void watchdog_fire(void)
{
if (force_boot) {
pr_crit("Initiating system reboot\n");
emergency_restart();
pr_crit("Reboot didn't ?????\n");
}
else {
pr_crit("Immediate Reboot Disabled\n");
pr_crit("System will reset when watchdog timer times out!\n");
}
}
static int check_timer_margin(int new_margin)
{
if ((new_margin < MIN_TIME_CYCLE) ||
(new_margin > MAX_TIME - timer_set)) {
pr_debug("value of new_margin %d is out of the range %d to %d\n",
new_margin, MIN_TIME_CYCLE, MAX_TIME - timer_set);
return -EINVAL;
}
return 0;
}
/*
* IPC operations
*/
static int watchdog_set_ipc(int soft_threshold, int threshold)
{
u32 *ipc_wbuf;
u8 cbuf[16] = { '\0' };
int ipc_ret = 0;
ipc_wbuf = (u32 *)&cbuf;
ipc_wbuf[0] = soft_threshold;
ipc_wbuf[1] = threshold;
ipc_ret = intel_scu_ipc_command(
IPC_SET_WATCHDOG_TIMER,
0,
ipc_wbuf,
2,
NULL,
0);
if (ipc_ret != 0)
pr_err("Error setting SCU watchdog timer: %x\n", ipc_ret);
return ipc_ret;
};
/*
* Intel_SCU operations
*/
/* timer interrupt handler */
static irqreturn_t watchdog_timer_interrupt(int irq, void *dev_id)
{
int int_status;
int_status = ioread32(watchdog_device.timer_interrupt_status_addr);
pr_debug("irq, int_status: %x\n", int_status);
if (int_status != 0)
return IRQ_NONE;
/* has the timer been started? If not, then this is spurious */
if (watchdog_device.timer_started == 0) {
pr_debug("spurious interrupt received\n");
return IRQ_HANDLED;
}
/* temporarily disable the timer */
iowrite32(0x00000002, watchdog_device.timer_control_addr);
/* set the timer to the threshold */
iowrite32(watchdog_device.threshold,
watchdog_device.timer_load_count_addr);
/* allow the timer to run */
iowrite32(0x00000003, watchdog_device.timer_control_addr);
return IRQ_HANDLED;
}
static int intel_scu_keepalive(void)
{
/* read eoi register - clears interrupt */
ioread32(watchdog_device.timer_clear_interrupt_addr);
/* temporarily disable the timer */
iowrite32(0x00000002, watchdog_device.timer_control_addr);
/* set the timer to the soft_threshold */
iowrite32(watchdog_device.soft_threshold,
watchdog_device.timer_load_count_addr);
/* allow the timer to run */
iowrite32(0x00000003, watchdog_device.timer_control_addr);
return 0;
}
static int intel_scu_stop(void)
{
iowrite32(0, watchdog_device.timer_control_addr);
return 0;
}
static int intel_scu_set_heartbeat(u32 t)
{
int ipc_ret;
int retry_count;
u32 soft_value;
u32 hw_pre_value;
u32 hw_value;
watchdog_device.timer_set = t;
watchdog_device.threshold =
timer_margin * watchdog_device.timer_tbl_ptr->freq_hz;
watchdog_device.soft_threshold =
(watchdog_device.timer_set - timer_margin)
* watchdog_device.timer_tbl_ptr->freq_hz;
pr_debug("set_heartbeat: timer freq is %d\n",
watchdog_device.timer_tbl_ptr->freq_hz);
pr_debug("set_heartbeat: timer_set is %x (hex)\n",
watchdog_device.timer_set);
pr_debug("set_hearbeat: timer_margin is %x (hex)\n", timer_margin);
pr_debug("set_heartbeat: threshold is %x (hex)\n",
watchdog_device.threshold);
pr_debug("set_heartbeat: soft_threshold is %x (hex)\n",
watchdog_device.soft_threshold);
/* Adjust thresholds by FREQ_ADJUSTMENT factor, to make the */
/* watchdog timing come out right. */
watchdog_device.threshold =
watchdog_device.threshold / FREQ_ADJUSTMENT;
watchdog_device.soft_threshold =
watchdog_device.soft_threshold / FREQ_ADJUSTMENT;
/* temporarily disable the timer */
iowrite32(0x00000002, watchdog_device.timer_control_addr);
/* send the threshold and soft_threshold via IPC to the processor */
ipc_ret = watchdog_set_ipc(watchdog_device.soft_threshold,
watchdog_device.threshold);
if (ipc_ret != 0) {
/* Make sure the watchdog timer is stopped */
intel_scu_stop();
return ipc_ret;
}
/* Soft Threshold set loop. Early versions of silicon did */
/* not always set this count correctly. This loop checks */
/* the value and retries if it was not set correctly. */
retry_count = 0;
soft_value = watchdog_device.soft_threshold & 0xFFFF0000;
do {
/* Make sure timer is stopped */
intel_scu_stop();
if (MAX_RETRY < retry_count++) {
/* Unable to set timer value */
pr_err("Unable to set timer\n");
return -ENODEV;
}
/* set the timer to the soft threshold */
iowrite32(watchdog_device.soft_threshold,
watchdog_device.timer_load_count_addr);
/* read count value before starting timer */
hw_pre_value = ioread32(watchdog_device.timer_load_count_addr);
hw_pre_value = hw_pre_value & 0xFFFF0000;
/* Start the timer */
iowrite32(0x00000003, watchdog_device.timer_control_addr);
/* read the value the time loaded into its count reg */
hw_value = ioread32(watchdog_device.timer_load_count_addr);
hw_value = hw_value & 0xFFFF0000;
} while (soft_value != hw_value);
watchdog_device.timer_started = 1;
return 0;
}
/*
* /dev/watchdog handling
*/
static int intel_scu_open(struct inode *inode, struct file *file)
{
/* Set flag to indicate that watchdog device is open */
if (test_and_set_bit(0, &watchdog_device.driver_open))
return -EBUSY;
/* Check for reopen of driver. Reopens are not allowed */
if (watchdog_device.driver_closed)
return -EPERM;
return nonseekable_open(inode, file);
}
static int intel_scu_release(struct inode *inode, struct file *file)
{
/*
* This watchdog should not be closed, after the timer
* is started with the WDIPC_SETTIMEOUT ioctl
* If force_boot is set watchdog_fire() will cause an
* immediate reset. If force_boot is not set, the watchdog
* timer is refreshed for one more interval. At the end
* of that interval, the watchdog timer will reset the system.
*/
if (!test_and_clear_bit(0, &watchdog_device.driver_open)) {
pr_debug("intel_scu_release, without open\n");
return -ENOTTY;
}
if (!watchdog_device.timer_started) {
/* Just close, since timer has not been started */
pr_debug("closed, without starting timer\n");
return 0;
}
pr_crit("Unexpected close of /dev/watchdog!\n");
/* Since the timer was started, prevent future reopens */
watchdog_device.driver_closed = 1;
/* Refresh the timer for one more interval */
intel_scu_keepalive();
/* Reboot system (if force_boot is set) */
watchdog_fire();
/* We should only reach this point if force_boot is not set */
return 0;
}
static ssize_t intel_scu_write(struct file *file,
char const *data,
size_t len,
loff_t *ppos)
{
if (watchdog_device.timer_started)
/* Watchdog already started, keep it alive */
intel_scu_keepalive();
else
/* Start watchdog with timer value set by init */
intel_scu_set_heartbeat(watchdog_device.timer_set);
return len;
}
static long intel_scu_ioctl(struct file *file,
unsigned int cmd,
unsigned long arg)
{
void __user *argp = (void __user *)arg;
u32 __user *p = argp;
u32 new_margin;
static const struct watchdog_info ident = {
.options = WDIOF_SETTIMEOUT
| WDIOF_KEEPALIVEPING,
.firmware_version = 0, /* @todo Get from SCU via
ipc_get_scu_fw_version()? */
.identity = "Intel_SCU IOH Watchdog" /* len < 32 */
};
switch (cmd) {
case WDIOC_GETSUPPORT:
return copy_to_user(argp,
&ident,
sizeof(ident)) ? -EFAULT : 0;
case WDIOC_GETSTATUS:
case WDIOC_GETBOOTSTATUS:
return put_user(0, p);
case WDIOC_KEEPALIVE:
intel_scu_keepalive();
return 0;
case WDIOC_SETTIMEOUT:
if (get_user(new_margin, p))
return -EFAULT;
if (check_timer_margin(new_margin))
return -EINVAL;
if (intel_scu_set_heartbeat(new_margin))
return -EINVAL;
return 0;
case WDIOC_GETTIMEOUT:
return put_user(watchdog_device.soft_threshold, p);
default:
return -ENOTTY;
}
}
/*
* Notifier for system down
*/
static int intel_scu_notify_sys(struct notifier_block *this,
unsigned long code,
void *another_unused)
{
if (code == SYS_DOWN || code == SYS_HALT)
/* Turn off the watchdog timer. */
intel_scu_stop();
return NOTIFY_DONE;
}
/*
* Kernel Interfaces
*/
static const struct file_operations intel_scu_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.write = intel_scu_write,
.unlocked_ioctl = intel_scu_ioctl,
.open = intel_scu_open,
.release = intel_scu_release,
};
static int __init intel_scu_watchdog_init(void)
{
int ret;
u32 __iomem *tmp_addr;
/*
* We don't really need to check this as the SFI timer get will fail
* but if we do so we can exit with a clearer reason and no noise.
*
* If it isn't an intel MID device then it doesn't have this watchdog
*/
if (!mrst_identify_cpu())
return -ENODEV;
/* Check boot parameters to verify that their initial values */
/* are in range. */
/* Check value of timer_set boot parameter */
if ((timer_set < MIN_TIME_CYCLE) ||
(timer_set > MAX_TIME - MIN_TIME_CYCLE)) {
pr_err("value of timer_set %x (hex) is out of range from %x to %x (hex)\n",
timer_set, MIN_TIME_CYCLE, MAX_TIME - MIN_TIME_CYCLE);
return -EINVAL;
}
/* Check value of timer_margin boot parameter */
if (check_timer_margin(timer_margin))
return -EINVAL;
watchdog_device.timer_tbl_ptr = sfi_get_mtmr(sfi_mtimer_num-1);
if (watchdog_device.timer_tbl_ptr == NULL) {
pr_debug("timer is not available\n");
return -ENODEV;
}
/* make sure the timer exists */
if (watchdog_device.timer_tbl_ptr->phys_addr == 0) {
pr_debug("timer %d does not have valid physical memory\n",
sfi_mtimer_num);
return -ENODEV;
}
if (watchdog_device.timer_tbl_ptr->irq == 0) {
pr_debug("timer %d invalid irq\n", sfi_mtimer_num);
return -ENODEV;
}
tmp_addr = ioremap_nocache(watchdog_device.timer_tbl_ptr->phys_addr,
20);
if (tmp_addr == NULL) {
pr_debug("timer unable to ioremap\n");
return -ENOMEM;
}
watchdog_device.timer_load_count_addr = tmp_addr++;
watchdog_device.timer_current_value_addr = tmp_addr++;
watchdog_device.timer_control_addr = tmp_addr++;
watchdog_device.timer_clear_interrupt_addr = tmp_addr++;
watchdog_device.timer_interrupt_status_addr = tmp_addr++;
/* Set the default time values in device structure */
watchdog_device.timer_set = timer_set;
watchdog_device.threshold =
timer_margin * watchdog_device.timer_tbl_ptr->freq_hz;
watchdog_device.soft_threshold =
(watchdog_device.timer_set - timer_margin)
* watchdog_device.timer_tbl_ptr->freq_hz;
watchdog_device.intel_scu_notifier.notifier_call =
intel_scu_notify_sys;
ret = register_reboot_notifier(&watchdog_device.intel_scu_notifier);
if (ret) {
pr_err("cannot register notifier %d)\n", ret);
goto register_reboot_error;
}
watchdog_device.miscdev.minor = WATCHDOG_MINOR;
watchdog_device.miscdev.name = "watchdog";
watchdog_device.miscdev.fops = &intel_scu_fops;
ret = misc_register(&watchdog_device.miscdev);
if (ret) {
pr_err("cannot register miscdev %d err =%d\n",
WATCHDOG_MINOR, ret);
goto misc_register_error;
}
ret = request_irq((unsigned int)watchdog_device.timer_tbl_ptr->irq,
watchdog_timer_interrupt,
IRQF_SHARED, "watchdog",
&watchdog_device.timer_load_count_addr);
if (ret) {
pr_err("error requesting irq %d\n", ret);
goto request_irq_error;
}
/* Make sure timer is disabled before returning */
intel_scu_stop();
return 0;
/* error cleanup */
request_irq_error:
misc_deregister(&watchdog_device.miscdev);
misc_register_error:
unregister_reboot_notifier(&watchdog_device.intel_scu_notifier);
register_reboot_error:
intel_scu_stop();
iounmap(watchdog_device.timer_load_count_addr);
return ret;
}
static void __exit intel_scu_watchdog_exit(void)
{
misc_deregister(&watchdog_device.miscdev);
unregister_reboot_notifier(&watchdog_device.intel_scu_notifier);
/* disable the timer */
iowrite32(0x00000002, watchdog_device.timer_control_addr);
iounmap(watchdog_device.timer_load_count_addr);
}
late_initcall(intel_scu_watchdog_init);
module_exit(intel_scu_watchdog_exit);
MODULE_AUTHOR("Intel Corporation");
MODULE_DESCRIPTION("Intel SCU Watchdog Device Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
MODULE_VERSION(WDT_VER);
| gpl-2.0 |
cristianhristea/linux_kernel | security/tomoyo/realpath.c | 7809 | 8031 | /*
* security/tomoyo/realpath.c
*
* Copyright (C) 2005-2011 NTT DATA CORPORATION
*/
#include "common.h"
#include <linux/magic.h>
/**
* tomoyo_encode2 - Encode binary string to ascii string.
*
* @str: String in binary format.
* @str_len: Size of @str in byte.
*
* Returns pointer to @str in ascii format on success, NULL otherwise.
*
* This function uses kzalloc(), so caller must kfree() if this function
* didn't return NULL.
*/
char *tomoyo_encode2(const char *str, int str_len)
{
int i;
int len = 0;
const char *p = str;
char *cp;
char *cp0;
if (!p)
return NULL;
for (i = 0; i < str_len; i++) {
const unsigned char c = p[i];
if (c == '\\')
len += 2;
else if (c > ' ' && c < 127)
len++;
else
len += 4;
}
len++;
/* Reserve space for appending "/". */
cp = kzalloc(len + 10, GFP_NOFS);
if (!cp)
return NULL;
cp0 = cp;
p = str;
for (i = 0; i < str_len; i++) {
const unsigned char c = p[i];
if (c == '\\') {
*cp++ = '\\';
*cp++ = '\\';
} else if (c > ' ' && c < 127) {
*cp++ = c;
} else {
*cp++ = '\\';
*cp++ = (c >> 6) + '0';
*cp++ = ((c >> 3) & 7) + '0';
*cp++ = (c & 7) + '0';
}
}
return cp0;
}
/**
* tomoyo_encode - Encode binary string to ascii string.
*
* @str: String in binary format.
*
* Returns pointer to @str in ascii format on success, NULL otherwise.
*
* This function uses kzalloc(), so caller must kfree() if this function
* didn't return NULL.
*/
char *tomoyo_encode(const char *str)
{
return str ? tomoyo_encode2(str, strlen(str)) : NULL;
}
/**
* tomoyo_get_absolute_path - Get the path of a dentry but ignores chroot'ed root.
*
* @path: Pointer to "struct path".
* @buffer: Pointer to buffer to return value in.
* @buflen: Sizeof @buffer.
*
* Returns the buffer on success, an error code otherwise.
*
* If dentry is a directory, trailing '/' is appended.
*/
static char *tomoyo_get_absolute_path(struct path *path, char * const buffer,
const int buflen)
{
char *pos = ERR_PTR(-ENOMEM);
if (buflen >= 256) {
/* go to whatever namespace root we are under */
pos = d_absolute_path(path, buffer, buflen - 1);
if (!IS_ERR(pos) && *pos == '/' && pos[1]) {
struct inode *inode = path->dentry->d_inode;
if (inode && S_ISDIR(inode->i_mode)) {
buffer[buflen - 2] = '/';
buffer[buflen - 1] = '\0';
}
}
}
return pos;
}
/**
* tomoyo_get_dentry_path - Get the path of a dentry.
*
* @dentry: Pointer to "struct dentry".
* @buffer: Pointer to buffer to return value in.
* @buflen: Sizeof @buffer.
*
* Returns the buffer on success, an error code otherwise.
*
* If dentry is a directory, trailing '/' is appended.
*/
static char *tomoyo_get_dentry_path(struct dentry *dentry, char * const buffer,
const int buflen)
{
char *pos = ERR_PTR(-ENOMEM);
if (buflen >= 256) {
pos = dentry_path_raw(dentry, buffer, buflen - 1);
if (!IS_ERR(pos) && *pos == '/' && pos[1]) {
struct inode *inode = dentry->d_inode;
if (inode && S_ISDIR(inode->i_mode)) {
buffer[buflen - 2] = '/';
buffer[buflen - 1] = '\0';
}
}
}
return pos;
}
/**
* tomoyo_get_local_path - Get the path of a dentry.
*
* @dentry: Pointer to "struct dentry".
* @buffer: Pointer to buffer to return value in.
* @buflen: Sizeof @buffer.
*
* Returns the buffer on success, an error code otherwise.
*/
static char *tomoyo_get_local_path(struct dentry *dentry, char * const buffer,
const int buflen)
{
struct super_block *sb = dentry->d_sb;
char *pos = tomoyo_get_dentry_path(dentry, buffer, buflen);
if (IS_ERR(pos))
return pos;
/* Convert from $PID to self if $PID is current thread. */
if (sb->s_magic == PROC_SUPER_MAGIC && *pos == '/') {
char *ep;
const pid_t pid = (pid_t) simple_strtoul(pos + 1, &ep, 10);
if (*ep == '/' && pid && pid ==
task_tgid_nr_ns(current, sb->s_fs_info)) {
pos = ep - 5;
if (pos < buffer)
goto out;
memmove(pos, "/self", 5);
}
goto prepend_filesystem_name;
}
/* Use filesystem name for unnamed devices. */
if (!MAJOR(sb->s_dev))
goto prepend_filesystem_name;
{
struct inode *inode = sb->s_root->d_inode;
/*
* Use filesystem name if filesystem does not support rename()
* operation.
*/
if (inode->i_op && !inode->i_op->rename)
goto prepend_filesystem_name;
}
/* Prepend device name. */
{
char name[64];
int name_len;
const dev_t dev = sb->s_dev;
name[sizeof(name) - 1] = '\0';
snprintf(name, sizeof(name) - 1, "dev(%u,%u):", MAJOR(dev),
MINOR(dev));
name_len = strlen(name);
pos -= name_len;
if (pos < buffer)
goto out;
memmove(pos, name, name_len);
return pos;
}
/* Prepend filesystem name. */
prepend_filesystem_name:
{
const char *name = sb->s_type->name;
const int name_len = strlen(name);
pos -= name_len + 1;
if (pos < buffer)
goto out;
memmove(pos, name, name_len);
pos[name_len] = ':';
}
return pos;
out:
return ERR_PTR(-ENOMEM);
}
/**
* tomoyo_get_socket_name - Get the name of a socket.
*
* @path: Pointer to "struct path".
* @buffer: Pointer to buffer to return value in.
* @buflen: Sizeof @buffer.
*
* Returns the buffer.
*/
static char *tomoyo_get_socket_name(struct path *path, char * const buffer,
const int buflen)
{
struct inode *inode = path->dentry->d_inode;
struct socket *sock = inode ? SOCKET_I(inode) : NULL;
struct sock *sk = sock ? sock->sk : NULL;
if (sk) {
snprintf(buffer, buflen, "socket:[family=%u:type=%u:"
"protocol=%u]", sk->sk_family, sk->sk_type,
sk->sk_protocol);
} else {
snprintf(buffer, buflen, "socket:[unknown]");
}
return buffer;
}
/**
* tomoyo_realpath_from_path - Returns realpath(3) of the given pathname but ignores chroot'ed root.
*
* @path: Pointer to "struct path".
*
* Returns the realpath of the given @path on success, NULL otherwise.
*
* If dentry is a directory, trailing '/' is appended.
* Characters out of 0x20 < c < 0x7F range are converted to
* \ooo style octal string.
* Character \ is converted to \\ string.
*
* These functions use kzalloc(), so the caller must call kfree()
* if these functions didn't return NULL.
*/
char *tomoyo_realpath_from_path(struct path *path)
{
char *buf = NULL;
char *name = NULL;
unsigned int buf_len = PAGE_SIZE / 2;
struct dentry *dentry = path->dentry;
struct super_block *sb;
if (!dentry)
return NULL;
sb = dentry->d_sb;
while (1) {
char *pos;
struct inode *inode;
buf_len <<= 1;
kfree(buf);
buf = kmalloc(buf_len, GFP_NOFS);
if (!buf)
break;
/* To make sure that pos is '\0' terminated. */
buf[buf_len - 1] = '\0';
/* Get better name for socket. */
if (sb->s_magic == SOCKFS_MAGIC) {
pos = tomoyo_get_socket_name(path, buf, buf_len - 1);
goto encode;
}
/* For "pipe:[\$]". */
if (dentry->d_op && dentry->d_op->d_dname) {
pos = dentry->d_op->d_dname(dentry, buf, buf_len - 1);
goto encode;
}
inode = sb->s_root->d_inode;
/*
* Get local name for filesystems without rename() operation
* or dentry without vfsmount.
*/
if (!path->mnt || (inode->i_op && !inode->i_op->rename))
pos = tomoyo_get_local_path(path->dentry, buf,
buf_len - 1);
/* Get absolute name for the rest. */
else {
pos = tomoyo_get_absolute_path(path, buf, buf_len - 1);
/*
* Fall back to local name if absolute name is not
* available.
*/
if (pos == ERR_PTR(-EINVAL))
pos = tomoyo_get_local_path(path->dentry, buf,
buf_len - 1);
}
encode:
if (IS_ERR(pos))
continue;
name = tomoyo_encode(pos);
break;
}
kfree(buf);
if (!name)
tomoyo_warn_oom(__func__);
return name;
}
/**
* tomoyo_realpath_nofollow - Get realpath of a pathname.
*
* @pathname: The pathname to solve.
*
* Returns the realpath of @pathname on success, NULL otherwise.
*/
char *tomoyo_realpath_nofollow(const char *pathname)
{
struct path path;
if (pathname && kern_path(pathname, 0, &path) == 0) {
char *buf = tomoyo_realpath_from_path(&path);
path_put(&path);
return buf;
}
return NULL;
}
| gpl-2.0 |
craigacgomez/android_kernel_samsung_manta | drivers/staging/sbe-2t3e3/netdev.c | 8321 | 3507 | /*
* SBE 2T3E3 synchronous serial card driver for Linux
*
* Copyright (C) 2009-2010 Krzysztof Halasa <khc@pm.waw.pl>
*
* 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 code is based on a driver written by SBE Inc.
*/
#include <linux/capability.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/pci.h>
#include <linux/hdlc.h>
#include <linux/if_arp.h>
#include <linux/interrupt.h>
#include "2t3e3.h"
int t3e3_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct channel *sc = dev_to_priv(dev);
int cmd_2t3e3, len, rlen;
t3e3_param_t param;
t3e3_resp_t resp;
void *data = ifr->ifr_data + sizeof(cmd_2t3e3) + sizeof(len);
if (cmd == SIOCWANDEV)
return hdlc_ioctl(dev, ifr, cmd);
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (cmd != SIOCDEVPRIVATE + 15)
return -EINVAL;
if (copy_from_user(&cmd_2t3e3, ifr->ifr_data, sizeof(cmd_2t3e3)))
return -EFAULT;
if (copy_from_user(&len, ifr->ifr_data + sizeof(cmd_2t3e3), sizeof(len)))
return -EFAULT;
if (len > sizeof(param))
return -EFAULT;
if (len)
if (copy_from_user(¶m, data, len))
return -EFAULT;
t3e3_if_config(sc, cmd_2t3e3, (char *)¶m, &resp, &rlen);
if (rlen)
if (copy_to_user(data, &resp, rlen))
return -EFAULT;
return 0;
}
static struct net_device_stats* t3e3_get_stats(struct net_device *dev)
{
struct net_device_stats *nstats = &dev->stats;
struct channel *sc = dev_to_priv(dev);
t3e3_stats_t *stats = &sc->s;
memset(nstats, 0, sizeof(struct net_device_stats));
nstats->rx_packets = stats->in_packets;
nstats->tx_packets = stats->out_packets;
nstats->rx_bytes = stats->in_bytes;
nstats->tx_bytes = stats->out_bytes;
nstats->rx_errors = stats->in_errors;
nstats->tx_errors = stats->out_errors;
nstats->rx_crc_errors = stats->in_error_crc;
nstats->rx_dropped = stats->in_dropped;
nstats->tx_dropped = stats->out_dropped;
nstats->tx_carrier_errors = stats->out_error_lost_carr +
stats->out_error_no_carr;
return nstats;
}
int t3e3_open(struct net_device *dev)
{
struct channel *sc = dev_to_priv(dev);
int ret = hdlc_open(dev);
if (ret)
return ret;
sc->r.flags |= SBE_2T3E3_FLAG_NETWORK_UP;
dc_start(dev_to_priv(dev));
netif_start_queue(dev);
try_module_get(THIS_MODULE);
return 0;
}
int t3e3_close(struct net_device *dev)
{
struct channel *sc = dev_to_priv(dev);
hdlc_close(dev);
netif_stop_queue(dev);
dc_stop(sc);
sc->r.flags &= ~SBE_2T3E3_FLAG_NETWORK_UP;
module_put(THIS_MODULE);
return 0;
}
static int t3e3_attach(struct net_device *dev, unsigned short foo1,
unsigned short foo2)
{
return 0;
}
static const struct net_device_ops t3e3_ops = {
.ndo_open = t3e3_open,
.ndo_stop = t3e3_close,
.ndo_change_mtu = hdlc_change_mtu,
.ndo_start_xmit = hdlc_start_xmit,
.ndo_do_ioctl = t3e3_ioctl,
.ndo_get_stats = t3e3_get_stats,
};
int setup_device(struct net_device *dev, struct channel *sc)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
int retval;
dev->base_addr = pci_resource_start(sc->pdev, 0);
dev->irq = sc->pdev->irq;
dev->netdev_ops = &t3e3_ops;
dev->tx_queue_len = 100;
hdlc->xmit = t3e3_if_start_xmit;
hdlc->attach = t3e3_attach;
if ((retval = register_hdlc_device(dev))) {
dev_err(&sc->pdev->dev, "error registering HDLC device\n");
return retval;
}
return 0;
}
| gpl-2.0 |
aosp-lb-nozomi/android_kernel_sony_msm8660 | drivers/firmware/memmap.c | 9089 | 7301 | /*
* linux/drivers/firmware/memmap.c
* Copyright (C) 2008 SUSE LINUX Products GmbH
* by Bernhard Walle <bernhard.walle@gmx.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License v2.0 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/string.h>
#include <linux/firmware-map.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/bootmem.h>
#include <linux/slab.h>
/*
* Data types ------------------------------------------------------------------
*/
/*
* Firmware map entry. Because firmware memory maps are flat and not
* hierarchical, it's ok to organise them in a linked list. No parent
* information is necessary as for the resource tree.
*/
struct firmware_map_entry {
/*
* start and end must be u64 rather than resource_size_t, because e820
* resources can lie at addresses above 4G.
*/
u64 start; /* start of the memory range */
u64 end; /* end of the memory range (incl.) */
const char *type; /* type of the memory range */
struct list_head list; /* entry for the linked list */
struct kobject kobj; /* kobject for each entry */
};
/*
* Forward declarations --------------------------------------------------------
*/
static ssize_t memmap_attr_show(struct kobject *kobj,
struct attribute *attr, char *buf);
static ssize_t start_show(struct firmware_map_entry *entry, char *buf);
static ssize_t end_show(struct firmware_map_entry *entry, char *buf);
static ssize_t type_show(struct firmware_map_entry *entry, char *buf);
/*
* Static data -----------------------------------------------------------------
*/
struct memmap_attribute {
struct attribute attr;
ssize_t (*show)(struct firmware_map_entry *entry, char *buf);
};
static struct memmap_attribute memmap_start_attr = __ATTR_RO(start);
static struct memmap_attribute memmap_end_attr = __ATTR_RO(end);
static struct memmap_attribute memmap_type_attr = __ATTR_RO(type);
/*
* These are default attributes that are added for every memmap entry.
*/
static struct attribute *def_attrs[] = {
&memmap_start_attr.attr,
&memmap_end_attr.attr,
&memmap_type_attr.attr,
NULL
};
static const struct sysfs_ops memmap_attr_ops = {
.show = memmap_attr_show,
};
static struct kobj_type memmap_ktype = {
.sysfs_ops = &memmap_attr_ops,
.default_attrs = def_attrs,
};
/*
* Registration functions ------------------------------------------------------
*/
/*
* Firmware memory map entries. No locking is needed because the
* firmware_map_add() and firmware_map_add_early() functions are called
* in firmware initialisation code in one single thread of execution.
*/
static LIST_HEAD(map_entries);
/**
* firmware_map_add_entry() - Does the real work to add a firmware memmap entry.
* @start: Start of the memory range.
* @end: End of the memory range (inclusive).
* @type: Type of the memory range.
* @entry: Pre-allocated (either kmalloc() or bootmem allocator), uninitialised
* entry.
*
* Common implementation of firmware_map_add() and firmware_map_add_early()
* which expects a pre-allocated struct firmware_map_entry.
**/
static int firmware_map_add_entry(u64 start, u64 end,
const char *type,
struct firmware_map_entry *entry)
{
BUG_ON(start > end);
entry->start = start;
entry->end = end;
entry->type = type;
INIT_LIST_HEAD(&entry->list);
kobject_init(&entry->kobj, &memmap_ktype);
list_add_tail(&entry->list, &map_entries);
return 0;
}
/*
* Add memmap entry on sysfs
*/
static int add_sysfs_fw_map_entry(struct firmware_map_entry *entry)
{
static int map_entries_nr;
static struct kset *mmap_kset;
if (!mmap_kset) {
mmap_kset = kset_create_and_add("memmap", NULL, firmware_kobj);
if (!mmap_kset)
return -ENOMEM;
}
entry->kobj.kset = mmap_kset;
if (kobject_add(&entry->kobj, NULL, "%d", map_entries_nr++))
kobject_put(&entry->kobj);
return 0;
}
/**
* firmware_map_add_hotplug() - Adds a firmware mapping entry when we do
* memory hotplug.
* @start: Start of the memory range.
* @end: End of the memory range (inclusive).
* @type: Type of the memory range.
*
* Adds a firmware mapping entry. This function is for memory hotplug, it is
* similar to function firmware_map_add_early(). The only difference is that
* it will create the syfs entry dynamically.
*
* Returns 0 on success, or -ENOMEM if no memory could be allocated.
**/
int __meminit firmware_map_add_hotplug(u64 start, u64 end, const char *type)
{
struct firmware_map_entry *entry;
entry = kzalloc(sizeof(struct firmware_map_entry), GFP_ATOMIC);
if (!entry)
return -ENOMEM;
firmware_map_add_entry(start, end, type, entry);
/* create the memmap entry */
add_sysfs_fw_map_entry(entry);
return 0;
}
/**
* firmware_map_add_early() - Adds a firmware mapping entry.
* @start: Start of the memory range.
* @end: End of the memory range (inclusive).
* @type: Type of the memory range.
*
* Adds a firmware mapping entry. This function uses the bootmem allocator
* for memory allocation.
*
* That function must be called before late_initcall.
*
* Returns 0 on success, or -ENOMEM if no memory could be allocated.
**/
int __init firmware_map_add_early(u64 start, u64 end, const char *type)
{
struct firmware_map_entry *entry;
entry = alloc_bootmem(sizeof(struct firmware_map_entry));
if (WARN_ON(!entry))
return -ENOMEM;
return firmware_map_add_entry(start, end, type, entry);
}
/*
* Sysfs functions -------------------------------------------------------------
*/
static ssize_t start_show(struct firmware_map_entry *entry, char *buf)
{
return snprintf(buf, PAGE_SIZE, "0x%llx\n",
(unsigned long long)entry->start);
}
static ssize_t end_show(struct firmware_map_entry *entry, char *buf)
{
return snprintf(buf, PAGE_SIZE, "0x%llx\n",
(unsigned long long)entry->end);
}
static ssize_t type_show(struct firmware_map_entry *entry, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", entry->type);
}
#define to_memmap_attr(_attr) container_of(_attr, struct memmap_attribute, attr)
#define to_memmap_entry(obj) container_of(obj, struct firmware_map_entry, kobj)
static ssize_t memmap_attr_show(struct kobject *kobj,
struct attribute *attr, char *buf)
{
struct firmware_map_entry *entry = to_memmap_entry(kobj);
struct memmap_attribute *memmap_attr = to_memmap_attr(attr);
return memmap_attr->show(entry, buf);
}
/*
* Initialises stuff and adds the entries in the map_entries list to
* sysfs. Important is that firmware_map_add() and firmware_map_add_early()
* must be called before late_initcall. That's just because that function
* is called as late_initcall() function, which means that if you call
* firmware_map_add() or firmware_map_add_early() afterwards, the entries
* are not added to sysfs.
*/
static int __init memmap_init(void)
{
struct firmware_map_entry *entry;
list_for_each_entry(entry, &map_entries, list)
add_sysfs_fw_map_entry(entry);
return 0;
}
late_initcall(memmap_init);
| gpl-2.0 |
mikewadsten/asuswrt | release/src/router/ffmpeg/libavcodec/arm/vp56dsp_init_arm.c | 130 | 1276 | /*
* Copyright (c) 2010 Mans Rullgard <mans@mansr.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
#include "libavcodec/avcodec.h"
#include "libavcodec/vp56dsp.h"
void ff_vp6_edge_filter_hor_neon(uint8_t *yuv, int stride, int t);
void ff_vp6_edge_filter_ver_neon(uint8_t *yuv, int stride, int t);
void ff_vp56dsp_init_arm(VP56DSPContext *s, enum CodecID codec)
{
if (codec != CODEC_ID_VP5 && HAVE_NEON) {
s->edge_filter_hor = ff_vp6_edge_filter_hor_neon;
s->edge_filter_ver = ff_vp6_edge_filter_ver_neon;
}
}
| gpl-2.0 |
yueshu/kernel_rk3036 | drivers/video/backlight/pwm_bl.c | 130 | 9826 | /*
* linux/drivers/video/backlight/pwm_bl.c
*
* simple PWM based backlight control, board code has to setup
* 1) pin configuration so PWM waveforms can output
* 2) platform_data being correctly configured
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/gpio/consumer.h>
#include <linux/gpio.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/fb.h>
#include <linux/backlight.h>
#include <linux/err.h>
#include <linux/pwm.h>
#include <linux/pwm_backlight.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
struct pwm_bl_data {
struct pwm_device *pwm;
struct device *dev;
unsigned int period;
unsigned int lth_brightness;
unsigned int *levels;
bool enabled;
struct regulator *power_supply;
struct gpio_desc *enable_gpio;
unsigned int scale;
bool legacy;
int (*notify)(struct device *,
int brightness);
void (*notify_after)(struct device *,
int brightness);
int (*check_fb)(struct device *, struct fb_info *);
void (*exit)(struct device *);
};
static void pwm_backlight_power_on(struct pwm_bl_data *pb, int brightness)
{
int err;
if (pb->enabled)
return;
err = regulator_enable(pb->power_supply);
if (err < 0)
dev_err(pb->dev, "failed to enable power supply\n");
if (pb->enable_gpio)
gpiod_set_value(pb->enable_gpio, 1);
pwm_enable(pb->pwm);
pb->enabled = true;
}
static void pwm_backlight_power_off(struct pwm_bl_data *pb)
{
if (!pb->enabled)
return;
pwm_config(pb->pwm, 0, pb->period);
pwm_disable(pb->pwm);
if (pb->enable_gpio)
gpiod_set_value(pb->enable_gpio, 0);
regulator_disable(pb->power_supply);
pb->enabled = false;
}
static int compute_duty_cycle(struct pwm_bl_data *pb, int brightness)
{
unsigned int lth = pb->lth_brightness;
int duty_cycle;
if (pb->levels)
duty_cycle = pb->levels[brightness];
else
duty_cycle = brightness;
return (duty_cycle * (pb->period - lth) / pb->scale) + lth;
}
static int pwm_backlight_update_status(struct backlight_device *bl)
{
struct pwm_bl_data *pb = bl_get_data(bl);
int brightness = bl->props.brightness;
int duty_cycle;
if (bl->props.power != FB_BLANK_UNBLANK ||
bl->props.fb_blank != FB_BLANK_UNBLANK ||
bl->props.state & BL_CORE_FBBLANK)
brightness = 0;
if (pb->notify)
brightness = pb->notify(pb->dev, brightness);
if (brightness > 0) {
duty_cycle = compute_duty_cycle(pb, brightness);
pwm_config(pb->pwm, duty_cycle, pb->period);
pwm_backlight_power_on(pb, brightness);
} else
pwm_backlight_power_off(pb);
if (pb->notify_after)
pb->notify_after(pb->dev, brightness);
return 0;
}
static int pwm_backlight_check_fb(struct backlight_device *bl,
struct fb_info *info)
{
struct pwm_bl_data *pb = bl_get_data(bl);
return !pb->check_fb || pb->check_fb(pb->dev, info);
}
static const struct backlight_ops pwm_backlight_ops = {
.update_status = pwm_backlight_update_status,
.check_fb = pwm_backlight_check_fb,
};
#ifdef CONFIG_OF
static int pwm_backlight_parse_dt(struct device *dev,
struct platform_pwm_backlight_data *data)
{
struct device_node *node = dev->of_node;
struct property *prop;
int length;
u32 value;
int ret;
if (!node)
return -ENODEV;
memset(data, 0, sizeof(*data));
/* determine the number of brightness levels */
prop = of_find_property(node, "brightness-levels", &length);
if (!prop)
return -EINVAL;
data->max_brightness = length / sizeof(u32);
/* read brightness levels from DT property */
if (data->max_brightness > 0) {
size_t size = sizeof(*data->levels) * data->max_brightness;
data->levels = devm_kzalloc(dev, size, GFP_KERNEL);
if (!data->levels)
return -ENOMEM;
ret = of_property_read_u32_array(node, "brightness-levels",
data->levels,
data->max_brightness);
if (ret < 0)
return ret;
ret = of_property_read_u32(node, "default-brightness-level",
&value);
if (ret < 0)
return ret;
data->dft_brightness = value;
data->max_brightness--;
}
data->enable_gpio = -EINVAL;
return 0;
}
static struct of_device_id pwm_backlight_of_match[] = {
{ .compatible = "pwm-backlight" },
{ }
};
MODULE_DEVICE_TABLE(of, pwm_backlight_of_match);
#else
static int pwm_backlight_parse_dt(struct device *dev,
struct platform_pwm_backlight_data *data)
{
return -ENODEV;
}
#endif
static int pwm_backlight_probe(struct platform_device *pdev)
{
struct platform_pwm_backlight_data *data = dev_get_platdata(&pdev->dev);
struct platform_pwm_backlight_data defdata;
struct backlight_properties props;
struct backlight_device *bl;
struct pwm_bl_data *pb;
int ret;
if (!data) {
ret = pwm_backlight_parse_dt(&pdev->dev, &defdata);
if (ret < 0) {
dev_err(&pdev->dev, "failed to find platform data\n");
return ret;
}
data = &defdata;
}
if (data->init) {
ret = data->init(&pdev->dev);
if (ret < 0)
return ret;
}
pb = devm_kzalloc(&pdev->dev, sizeof(*pb), GFP_KERNEL);
if (!pb) {
ret = -ENOMEM;
goto err_alloc;
}
if (data->levels) {
unsigned int i;
for (i = 0; i <= data->max_brightness; i++)
if (data->levels[i] > pb->scale)
pb->scale = data->levels[i];
pb->levels = data->levels;
} else
pb->scale = data->max_brightness;
pb->notify = data->notify;
pb->notify_after = data->notify_after;
pb->check_fb = data->check_fb;
pb->exit = data->exit;
pb->dev = &pdev->dev;
pb->enabled = false;
pb->enable_gpio = devm_gpiod_get_optional(&pdev->dev, "enable",
GPIOD_OUT_HIGH);
if (IS_ERR(pb->enable_gpio)) {
ret = PTR_ERR(pb->enable_gpio);
goto err_alloc;
}
/*
* Compatibility fallback for drivers still using the integer GPIO
* platform data. Must go away soon.
*/
if (!pb->enable_gpio && gpio_is_valid(data->enable_gpio)) {
ret = devm_gpio_request_one(&pdev->dev, data->enable_gpio,
GPIOF_OUT_INIT_HIGH, "enable");
if (ret < 0) {
dev_err(&pdev->dev, "failed to request GPIO#%d: %d\n",
data->enable_gpio, ret);
goto err_alloc;
}
pb->enable_gpio = gpio_to_desc(data->enable_gpio);
}
pb->power_supply = devm_regulator_get(&pdev->dev, "power");
if (IS_ERR(pb->power_supply)) {
ret = PTR_ERR(pb->power_supply);
goto err_alloc;
}
pb->pwm = devm_pwm_get(&pdev->dev, NULL);
if (IS_ERR(pb->pwm) && PTR_ERR(pb->pwm) != -EPROBE_DEFER
&& !pdev->dev.of_node) {
dev_err(&pdev->dev, "unable to request PWM, trying legacy API\n");
pb->legacy = true;
pb->pwm = pwm_request(data->pwm_id, "pwm-backlight");
}
if (IS_ERR(pb->pwm)) {
ret = PTR_ERR(pb->pwm);
if (ret != -EPROBE_DEFER)
dev_err(&pdev->dev, "unable to request PWM\n");
goto err_alloc;
}
dev_dbg(&pdev->dev, "got pwm for backlight\n");
/*
* The DT case will set the pwm_period_ns field to 0 and store the
* period, parsed from the DT, in the PWM device. For the non-DT case,
* set the period from platform data if it has not already been set
* via the PWM lookup table.
*/
pb->period = pwm_get_period(pb->pwm);
if (!pb->period && (data->pwm_period_ns > 0)) {
pb->period = data->pwm_period_ns;
pwm_set_period(pb->pwm, data->pwm_period_ns);
}
pb->lth_brightness = data->lth_brightness * (pb->period / pb->scale);
memset(&props, 0, sizeof(struct backlight_properties));
props.type = BACKLIGHT_RAW;
props.max_brightness = data->max_brightness;
bl = backlight_device_register(dev_name(&pdev->dev), &pdev->dev, pb,
&pwm_backlight_ops, &props);
if (IS_ERR(bl)) {
dev_err(&pdev->dev, "failed to register backlight\n");
ret = PTR_ERR(bl);
goto err_alloc;
}
if (data->dft_brightness > data->max_brightness) {
dev_warn(&pdev->dev,
"invalid default brightness level: %u, using %u\n",
data->dft_brightness, data->max_brightness);
data->dft_brightness = data->max_brightness;
}
bl->props.brightness = data->dft_brightness;
backlight_update_status(bl);
platform_set_drvdata(pdev, bl);
return 0;
err_alloc:
if (data->exit)
data->exit(&pdev->dev);
return ret;
}
static int pwm_backlight_remove(struct platform_device *pdev)
{
struct backlight_device *bl = platform_get_drvdata(pdev);
struct pwm_bl_data *pb = bl_get_data(bl);
backlight_device_unregister(bl);
pwm_backlight_power_off(pb);
if (pb->exit)
pb->exit(&pdev->dev);
if (pb->legacy)
pwm_free(pb->pwm);
return 0;
}
static void pwm_backlight_shutdown(struct platform_device *pdev)
{
struct backlight_device *bl = platform_get_drvdata(pdev);
struct pwm_bl_data *pb = bl_get_data(bl);
pwm_backlight_power_off(pb);
}
#ifdef CONFIG_PM_SLEEP
static int pwm_backlight_suspend(struct device *dev)
{
struct backlight_device *bl = dev_get_drvdata(dev);
struct pwm_bl_data *pb = bl_get_data(bl);
if (pb->notify)
pb->notify(pb->dev, 0);
pwm_backlight_power_off(pb);
if (pb->notify_after)
pb->notify_after(pb->dev, 0);
return 0;
}
static int pwm_backlight_resume(struct device *dev)
{
struct backlight_device *bl = dev_get_drvdata(dev);
backlight_update_status(bl);
return 0;
}
#endif
static const struct dev_pm_ops pwm_backlight_pm_ops = {
#ifdef CONFIG_PM_SLEEP
.suspend = pwm_backlight_suspend,
.resume = pwm_backlight_resume,
.poweroff = pwm_backlight_suspend,
.restore = pwm_backlight_resume,
#endif
};
static struct platform_driver pwm_backlight_driver = {
.driver = {
.name = "pwm-backlight",
.pm = &pwm_backlight_pm_ops,
.of_match_table = of_match_ptr(pwm_backlight_of_match),
},
.probe = pwm_backlight_probe,
.remove = pwm_backlight_remove,
.shutdown = pwm_backlight_shutdown,
};
module_platform_driver(pwm_backlight_driver);
MODULE_DESCRIPTION("PWM based Backlight Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:pwm-backlight");
| gpl-2.0 |
wbdub/kernel_asus_tf300t | drivers/usb/gadget/langwell_udc.c | 386 | 91380 | /*
* Intel Langwell USB Device Controller driver
* Copyright (C) 2008-2009, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
/* #undef DEBUG */
/* #undef VERBOSE_DEBUG */
#if defined(CONFIG_USB_LANGWELL_OTG)
#define OTG_TRANSCEIVER
#endif
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <linux/list.h>
#include <linux/interrupt.h>
#include <linux/moduleparam.h>
#include <linux/device.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include <linux/usb/otg.h>
#include <linux/pm.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <asm/system.h>
#include <asm/unaligned.h>
#include "langwell_udc.h"
#define DRIVER_DESC "Intel Langwell USB Device Controller driver"
#define DRIVER_VERSION "16 May 2009"
static const char driver_name[] = "langwell_udc";
static const char driver_desc[] = DRIVER_DESC;
/* controller device global variable */
static struct langwell_udc *the_controller;
/* for endpoint 0 operations */
static const struct usb_endpoint_descriptor
langwell_ep0_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = 0,
.bmAttributes = USB_ENDPOINT_XFER_CONTROL,
.wMaxPacketSize = EP0_MAX_PKT_SIZE,
};
/*-------------------------------------------------------------------------*/
/* debugging */
#ifdef VERBOSE_DEBUG
static inline void print_all_registers(struct langwell_udc *dev)
{
int i;
/* Capability Registers */
dev_dbg(&dev->pdev->dev,
"Capability Registers (offset: 0x%04x, length: 0x%08x)\n",
CAP_REG_OFFSET, (u32)sizeof(struct langwell_cap_regs));
dev_dbg(&dev->pdev->dev, "caplength=0x%02x\n",
readb(&dev->cap_regs->caplength));
dev_dbg(&dev->pdev->dev, "hciversion=0x%04x\n",
readw(&dev->cap_regs->hciversion));
dev_dbg(&dev->pdev->dev, "hcsparams=0x%08x\n",
readl(&dev->cap_regs->hcsparams));
dev_dbg(&dev->pdev->dev, "hccparams=0x%08x\n",
readl(&dev->cap_regs->hccparams));
dev_dbg(&dev->pdev->dev, "dciversion=0x%04x\n",
readw(&dev->cap_regs->dciversion));
dev_dbg(&dev->pdev->dev, "dccparams=0x%08x\n",
readl(&dev->cap_regs->dccparams));
/* Operational Registers */
dev_dbg(&dev->pdev->dev,
"Operational Registers (offset: 0x%04x, length: 0x%08x)\n",
OP_REG_OFFSET, (u32)sizeof(struct langwell_op_regs));
dev_dbg(&dev->pdev->dev, "extsts=0x%08x\n",
readl(&dev->op_regs->extsts));
dev_dbg(&dev->pdev->dev, "extintr=0x%08x\n",
readl(&dev->op_regs->extintr));
dev_dbg(&dev->pdev->dev, "usbcmd=0x%08x\n",
readl(&dev->op_regs->usbcmd));
dev_dbg(&dev->pdev->dev, "usbsts=0x%08x\n",
readl(&dev->op_regs->usbsts));
dev_dbg(&dev->pdev->dev, "usbintr=0x%08x\n",
readl(&dev->op_regs->usbintr));
dev_dbg(&dev->pdev->dev, "frindex=0x%08x\n",
readl(&dev->op_regs->frindex));
dev_dbg(&dev->pdev->dev, "ctrldssegment=0x%08x\n",
readl(&dev->op_regs->ctrldssegment));
dev_dbg(&dev->pdev->dev, "deviceaddr=0x%08x\n",
readl(&dev->op_regs->deviceaddr));
dev_dbg(&dev->pdev->dev, "endpointlistaddr=0x%08x\n",
readl(&dev->op_regs->endpointlistaddr));
dev_dbg(&dev->pdev->dev, "ttctrl=0x%08x\n",
readl(&dev->op_regs->ttctrl));
dev_dbg(&dev->pdev->dev, "burstsize=0x%08x\n",
readl(&dev->op_regs->burstsize));
dev_dbg(&dev->pdev->dev, "txfilltuning=0x%08x\n",
readl(&dev->op_regs->txfilltuning));
dev_dbg(&dev->pdev->dev, "txttfilltuning=0x%08x\n",
readl(&dev->op_regs->txttfilltuning));
dev_dbg(&dev->pdev->dev, "ic_usb=0x%08x\n",
readl(&dev->op_regs->ic_usb));
dev_dbg(&dev->pdev->dev, "ulpi_viewport=0x%08x\n",
readl(&dev->op_regs->ulpi_viewport));
dev_dbg(&dev->pdev->dev, "configflag=0x%08x\n",
readl(&dev->op_regs->configflag));
dev_dbg(&dev->pdev->dev, "portsc1=0x%08x\n",
readl(&dev->op_regs->portsc1));
dev_dbg(&dev->pdev->dev, "devlc=0x%08x\n",
readl(&dev->op_regs->devlc));
dev_dbg(&dev->pdev->dev, "otgsc=0x%08x\n",
readl(&dev->op_regs->otgsc));
dev_dbg(&dev->pdev->dev, "usbmode=0x%08x\n",
readl(&dev->op_regs->usbmode));
dev_dbg(&dev->pdev->dev, "endptnak=0x%08x\n",
readl(&dev->op_regs->endptnak));
dev_dbg(&dev->pdev->dev, "endptnaken=0x%08x\n",
readl(&dev->op_regs->endptnaken));
dev_dbg(&dev->pdev->dev, "endptsetupstat=0x%08x\n",
readl(&dev->op_regs->endptsetupstat));
dev_dbg(&dev->pdev->dev, "endptprime=0x%08x\n",
readl(&dev->op_regs->endptprime));
dev_dbg(&dev->pdev->dev, "endptflush=0x%08x\n",
readl(&dev->op_regs->endptflush));
dev_dbg(&dev->pdev->dev, "endptstat=0x%08x\n",
readl(&dev->op_regs->endptstat));
dev_dbg(&dev->pdev->dev, "endptcomplete=0x%08x\n",
readl(&dev->op_regs->endptcomplete));
for (i = 0; i < dev->ep_max / 2; i++) {
dev_dbg(&dev->pdev->dev, "endptctrl[%d]=0x%08x\n",
i, readl(&dev->op_regs->endptctrl[i]));
}
}
#else
#define print_all_registers(dev) do { } while (0)
#endif /* VERBOSE_DEBUG */
/*-------------------------------------------------------------------------*/
#define is_in(ep) (((ep)->ep_num == 0) ? ((ep)->dev->ep0_dir == \
USB_DIR_IN) : (usb_endpoint_dir_in((ep)->desc)))
#define DIR_STRING(ep) (is_in(ep) ? "in" : "out")
static char *type_string(const struct usb_endpoint_descriptor *desc)
{
switch (usb_endpoint_type(desc)) {
case USB_ENDPOINT_XFER_BULK:
return "bulk";
case USB_ENDPOINT_XFER_ISOC:
return "iso";
case USB_ENDPOINT_XFER_INT:
return "int";
};
return "control";
}
/* configure endpoint control registers */
static void ep_reset(struct langwell_ep *ep, unsigned char ep_num,
unsigned char is_in, unsigned char ep_type)
{
struct langwell_udc *dev;
u32 endptctrl;
dev = ep->dev;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
endptctrl = readl(&dev->op_regs->endptctrl[ep_num]);
if (is_in) { /* TX */
if (ep_num)
endptctrl |= EPCTRL_TXR;
endptctrl |= EPCTRL_TXE;
endptctrl |= ep_type << EPCTRL_TXT_SHIFT;
} else { /* RX */
if (ep_num)
endptctrl |= EPCTRL_RXR;
endptctrl |= EPCTRL_RXE;
endptctrl |= ep_type << EPCTRL_RXT_SHIFT;
}
writel(endptctrl, &dev->op_regs->endptctrl[ep_num]);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* reset ep0 dQH and endptctrl */
static void ep0_reset(struct langwell_udc *dev)
{
struct langwell_ep *ep;
int i;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
/* ep0 in and out */
for (i = 0; i < 2; i++) {
ep = &dev->ep[i];
ep->dev = dev;
/* ep0 dQH */
ep->dqh = &dev->ep_dqh[i];
/* configure ep0 endpoint capabilities in dQH */
ep->dqh->dqh_ios = 1;
ep->dqh->dqh_mpl = EP0_MAX_PKT_SIZE;
/* enable ep0-in HW zero length termination select */
if (is_in(ep))
ep->dqh->dqh_zlt = 0;
ep->dqh->dqh_mult = 0;
ep->dqh->dtd_next = DTD_TERM;
/* configure ep0 control registers */
ep_reset(&dev->ep[0], 0, i, USB_ENDPOINT_XFER_CONTROL);
}
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/*-------------------------------------------------------------------------*/
/* endpoints operations */
/* configure endpoint, making it usable */
static int langwell_ep_enable(struct usb_ep *_ep,
const struct usb_endpoint_descriptor *desc)
{
struct langwell_udc *dev;
struct langwell_ep *ep;
u16 max = 0;
unsigned long flags;
int i, retval = 0;
unsigned char zlt, ios = 0, mult = 0;
ep = container_of(_ep, struct langwell_ep, ep);
dev = ep->dev;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
if (!_ep || !desc || ep->desc
|| desc->bDescriptorType != USB_DT_ENDPOINT)
return -EINVAL;
if (!dev->driver || dev->gadget.speed == USB_SPEED_UNKNOWN)
return -ESHUTDOWN;
max = le16_to_cpu(desc->wMaxPacketSize);
/*
* disable HW zero length termination select
* driver handles zero length packet through req->req.zero
*/
zlt = 1;
/*
* sanity check type, direction, address, and then
* initialize the endpoint capabilities fields in dQH
*/
switch (usb_endpoint_type(desc)) {
case USB_ENDPOINT_XFER_CONTROL:
ios = 1;
break;
case USB_ENDPOINT_XFER_BULK:
if ((dev->gadget.speed == USB_SPEED_HIGH
&& max != 512)
|| (dev->gadget.speed == USB_SPEED_FULL
&& max > 64)) {
goto done;
}
break;
case USB_ENDPOINT_XFER_INT:
if (strstr(ep->ep.name, "-iso")) /* bulk is ok */
goto done;
switch (dev->gadget.speed) {
case USB_SPEED_HIGH:
if (max <= 1024)
break;
case USB_SPEED_FULL:
if (max <= 64)
break;
default:
if (max <= 8)
break;
goto done;
}
break;
case USB_ENDPOINT_XFER_ISOC:
if (strstr(ep->ep.name, "-bulk")
|| strstr(ep->ep.name, "-int"))
goto done;
switch (dev->gadget.speed) {
case USB_SPEED_HIGH:
if (max <= 1024)
break;
case USB_SPEED_FULL:
if (max <= 1023)
break;
default:
goto done;
}
/*
* FIXME:
* calculate transactions needed for high bandwidth iso
*/
mult = (unsigned char)(1 + ((max >> 11) & 0x03));
max = max & 0x8ff; /* bit 0~10 */
/* 3 transactions at most */
if (mult > 3)
goto done;
break;
default:
goto done;
}
spin_lock_irqsave(&dev->lock, flags);
ep->ep.maxpacket = max;
ep->desc = desc;
ep->stopped = 0;
ep->ep_num = usb_endpoint_num(desc);
/* ep_type */
ep->ep_type = usb_endpoint_type(desc);
/* configure endpoint control registers */
ep_reset(ep, ep->ep_num, is_in(ep), ep->ep_type);
/* configure endpoint capabilities in dQH */
i = ep->ep_num * 2 + is_in(ep);
ep->dqh = &dev->ep_dqh[i];
ep->dqh->dqh_ios = ios;
ep->dqh->dqh_mpl = cpu_to_le16(max);
ep->dqh->dqh_zlt = zlt;
ep->dqh->dqh_mult = mult;
ep->dqh->dtd_next = DTD_TERM;
dev_dbg(&dev->pdev->dev, "enabled %s (ep%d%s-%s), max %04x\n",
_ep->name,
ep->ep_num,
DIR_STRING(ep),
type_string(desc),
max);
spin_unlock_irqrestore(&dev->lock, flags);
done:
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return retval;
}
/*-------------------------------------------------------------------------*/
/* retire a request */
static void done(struct langwell_ep *ep, struct langwell_request *req,
int status)
{
struct langwell_udc *dev = ep->dev;
unsigned stopped = ep->stopped;
struct langwell_dtd *curr_dtd, *next_dtd;
int i;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
/* remove the req from ep->queue */
list_del_init(&req->queue);
if (req->req.status == -EINPROGRESS)
req->req.status = status;
else
status = req->req.status;
/* free dTD for the request */
next_dtd = req->head;
for (i = 0; i < req->dtd_count; i++) {
curr_dtd = next_dtd;
if (i != req->dtd_count - 1)
next_dtd = curr_dtd->next_dtd_virt;
dma_pool_free(dev->dtd_pool, curr_dtd, curr_dtd->dtd_dma);
}
if (req->mapped) {
dma_unmap_single(&dev->pdev->dev,
req->req.dma, req->req.length,
is_in(ep) ? PCI_DMA_TODEVICE : PCI_DMA_FROMDEVICE);
req->req.dma = DMA_ADDR_INVALID;
req->mapped = 0;
} else
dma_sync_single_for_cpu(&dev->pdev->dev, req->req.dma,
req->req.length,
is_in(ep) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
if (status != -ESHUTDOWN)
dev_dbg(&dev->pdev->dev,
"complete %s, req %p, stat %d, len %u/%u\n",
ep->ep.name, &req->req, status,
req->req.actual, req->req.length);
/* don't modify queue heads during completion callback */
ep->stopped = 1;
spin_unlock(&dev->lock);
/* complete routine from gadget driver */
if (req->req.complete)
req->req.complete(&ep->ep, &req->req);
spin_lock(&dev->lock);
ep->stopped = stopped;
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
static void langwell_ep_fifo_flush(struct usb_ep *_ep);
/* delete all endpoint requests, called with spinlock held */
static void nuke(struct langwell_ep *ep, int status)
{
/* called with spinlock held */
ep->stopped = 1;
/* endpoint fifo flush */
if (&ep->ep && ep->desc)
langwell_ep_fifo_flush(&ep->ep);
while (!list_empty(&ep->queue)) {
struct langwell_request *req = NULL;
req = list_entry(ep->queue.next, struct langwell_request,
queue);
done(ep, req, status);
}
}
/*-------------------------------------------------------------------------*/
/* endpoint is no longer usable */
static int langwell_ep_disable(struct usb_ep *_ep)
{
struct langwell_ep *ep;
unsigned long flags;
struct langwell_udc *dev;
int ep_num;
u32 endptctrl;
ep = container_of(_ep, struct langwell_ep, ep);
dev = ep->dev;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
if (!_ep || !ep->desc)
return -EINVAL;
spin_lock_irqsave(&dev->lock, flags);
/* disable endpoint control register */
ep_num = ep->ep_num;
endptctrl = readl(&dev->op_regs->endptctrl[ep_num]);
if (is_in(ep))
endptctrl &= ~EPCTRL_TXE;
else
endptctrl &= ~EPCTRL_RXE;
writel(endptctrl, &dev->op_regs->endptctrl[ep_num]);
/* nuke all pending requests (does flush) */
nuke(ep, -ESHUTDOWN);
ep->desc = NULL;
ep->stopped = 1;
spin_unlock_irqrestore(&dev->lock, flags);
dev_dbg(&dev->pdev->dev, "disabled %s\n", _ep->name);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return 0;
}
/* allocate a request object to use with this endpoint */
static struct usb_request *langwell_alloc_request(struct usb_ep *_ep,
gfp_t gfp_flags)
{
struct langwell_ep *ep;
struct langwell_udc *dev;
struct langwell_request *req = NULL;
if (!_ep)
return NULL;
ep = container_of(_ep, struct langwell_ep, ep);
dev = ep->dev;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
req = kzalloc(sizeof(*req), gfp_flags);
if (!req)
return NULL;
req->req.dma = DMA_ADDR_INVALID;
INIT_LIST_HEAD(&req->queue);
dev_vdbg(&dev->pdev->dev, "alloc request for %s\n", _ep->name);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return &req->req;
}
/* free a request object */
static void langwell_free_request(struct usb_ep *_ep,
struct usb_request *_req)
{
struct langwell_ep *ep;
struct langwell_udc *dev;
struct langwell_request *req = NULL;
ep = container_of(_ep, struct langwell_ep, ep);
dev = ep->dev;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
if (!_ep || !_req)
return;
req = container_of(_req, struct langwell_request, req);
WARN_ON(!list_empty(&req->queue));
if (_req)
kfree(req);
dev_vdbg(&dev->pdev->dev, "free request for %s\n", _ep->name);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/*-------------------------------------------------------------------------*/
/* queue dTD and PRIME endpoint */
static int queue_dtd(struct langwell_ep *ep, struct langwell_request *req)
{
u32 bit_mask, usbcmd, endptstat, dtd_dma;
u8 dtd_status;
int i;
struct langwell_dqh *dqh;
struct langwell_udc *dev;
dev = ep->dev;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
i = ep->ep_num * 2 + is_in(ep);
dqh = &dev->ep_dqh[i];
if (ep->ep_num)
dev_vdbg(&dev->pdev->dev, "%s\n", ep->name);
else
/* ep0 */
dev_vdbg(&dev->pdev->dev, "%s-%s\n", ep->name, DIR_STRING(ep));
dev_vdbg(&dev->pdev->dev, "ep_dqh[%d] addr: 0x%p\n",
i, &(dev->ep_dqh[i]));
bit_mask = is_in(ep) ?
(1 << (ep->ep_num + 16)) : (1 << (ep->ep_num));
dev_vdbg(&dev->pdev->dev, "bit_mask = 0x%08x\n", bit_mask);
/* check if the pipe is empty */
if (!(list_empty(&ep->queue))) {
/* add dTD to the end of linked list */
struct langwell_request *lastreq;
lastreq = list_entry(ep->queue.prev,
struct langwell_request, queue);
lastreq->tail->dtd_next =
cpu_to_le32(req->head->dtd_dma & DTD_NEXT_MASK);
/* read prime bit, if 1 goto out */
if (readl(&dev->op_regs->endptprime) & bit_mask)
goto out;
do {
/* set ATDTW bit in USBCMD */
usbcmd = readl(&dev->op_regs->usbcmd);
writel(usbcmd | CMD_ATDTW, &dev->op_regs->usbcmd);
/* read correct status bit */
endptstat = readl(&dev->op_regs->endptstat) & bit_mask;
} while (!(readl(&dev->op_regs->usbcmd) & CMD_ATDTW));
/* write ATDTW bit to 0 */
usbcmd = readl(&dev->op_regs->usbcmd);
writel(usbcmd & ~CMD_ATDTW, &dev->op_regs->usbcmd);
if (endptstat)
goto out;
}
/* write dQH next pointer and terminate bit to 0 */
dtd_dma = req->head->dtd_dma & DTD_NEXT_MASK;
dqh->dtd_next = cpu_to_le32(dtd_dma);
/* clear active and halt bit */
dtd_status = (u8) ~(DTD_STS_ACTIVE | DTD_STS_HALTED);
dqh->dtd_status &= dtd_status;
dev_vdbg(&dev->pdev->dev, "dqh->dtd_status = 0x%x\n", dqh->dtd_status);
/* ensure that updates to the dQH will occur before priming */
wmb();
/* write 1 to endptprime register to PRIME endpoint */
bit_mask = is_in(ep) ? (1 << (ep->ep_num + 16)) : (1 << ep->ep_num);
dev_vdbg(&dev->pdev->dev, "endprime bit_mask = 0x%08x\n", bit_mask);
writel(bit_mask, &dev->op_regs->endptprime);
out:
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return 0;
}
/* fill in the dTD structure to build a transfer descriptor */
static struct langwell_dtd *build_dtd(struct langwell_request *req,
unsigned *length, dma_addr_t *dma, int *is_last)
{
u32 buf_ptr;
struct langwell_dtd *dtd;
struct langwell_udc *dev;
int i;
dev = req->ep->dev;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
/* the maximum transfer length, up to 16k bytes */
*length = min(req->req.length - req->req.actual,
(unsigned)DTD_MAX_TRANSFER_LENGTH);
/* create dTD dma_pool resource */
dtd = dma_pool_alloc(dev->dtd_pool, GFP_KERNEL, dma);
if (dtd == NULL)
return dtd;
dtd->dtd_dma = *dma;
/* initialize buffer page pointers */
buf_ptr = (u32)(req->req.dma + req->req.actual);
for (i = 0; i < 5; i++)
dtd->dtd_buf[i] = cpu_to_le32(buf_ptr + i * PAGE_SIZE);
req->req.actual += *length;
/* fill in total bytes with transfer size */
dtd->dtd_total = cpu_to_le16(*length);
dev_vdbg(&dev->pdev->dev, "dtd->dtd_total = %d\n", dtd->dtd_total);
/* set is_last flag if req->req.zero is set or not */
if (req->req.zero) {
if (*length == 0 || (*length % req->ep->ep.maxpacket) != 0)
*is_last = 1;
else
*is_last = 0;
} else if (req->req.length == req->req.actual) {
*is_last = 1;
} else
*is_last = 0;
if (*is_last == 0)
dev_vdbg(&dev->pdev->dev, "multi-dtd request!\n");
/* set interrupt on complete bit for the last dTD */
if (*is_last && !req->req.no_interrupt)
dtd->dtd_ioc = 1;
/* set multiplier override 0 for non-ISO and non-TX endpoint */
dtd->dtd_multo = 0;
/* set the active bit of status field to 1 */
dtd->dtd_status = DTD_STS_ACTIVE;
dev_vdbg(&dev->pdev->dev, "dtd->dtd_status = 0x%02x\n",
dtd->dtd_status);
dev_vdbg(&dev->pdev->dev, "length = %d, dma addr= 0x%08x\n",
*length, (int)*dma);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return dtd;
}
/* generate dTD linked list for a request */
static int req_to_dtd(struct langwell_request *req)
{
unsigned count;
int is_last, is_first = 1;
struct langwell_dtd *dtd, *last_dtd = NULL;
struct langwell_udc *dev;
dma_addr_t dma;
dev = req->ep->dev;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
do {
dtd = build_dtd(req, &count, &dma, &is_last);
if (dtd == NULL)
return -ENOMEM;
if (is_first) {
is_first = 0;
req->head = dtd;
} else {
last_dtd->dtd_next = cpu_to_le32(dma);
last_dtd->next_dtd_virt = dtd;
}
last_dtd = dtd;
req->dtd_count++;
} while (!is_last);
/* set terminate bit to 1 for the last dTD */
dtd->dtd_next = DTD_TERM;
req->tail = dtd;
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return 0;
}
/*-------------------------------------------------------------------------*/
/* queue (submits) an I/O requests to an endpoint */
static int langwell_ep_queue(struct usb_ep *_ep, struct usb_request *_req,
gfp_t gfp_flags)
{
struct langwell_request *req;
struct langwell_ep *ep;
struct langwell_udc *dev;
unsigned long flags;
int is_iso = 0, zlflag = 0;
/* always require a cpu-view buffer */
req = container_of(_req, struct langwell_request, req);
ep = container_of(_ep, struct langwell_ep, ep);
if (!_req || !_req->complete || !_req->buf
|| !list_empty(&req->queue)) {
return -EINVAL;
}
if (unlikely(!_ep || !ep->desc))
return -EINVAL;
dev = ep->dev;
req->ep = ep;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
if (usb_endpoint_xfer_isoc(ep->desc)) {
if (req->req.length > ep->ep.maxpacket)
return -EMSGSIZE;
is_iso = 1;
}
if (unlikely(!dev->driver || dev->gadget.speed == USB_SPEED_UNKNOWN))
return -ESHUTDOWN;
/* set up dma mapping in case the caller didn't */
if (_req->dma == DMA_ADDR_INVALID) {
/* WORKAROUND: WARN_ON(size == 0) */
if (_req->length == 0) {
dev_vdbg(&dev->pdev->dev, "req->length: 0->1\n");
zlflag = 1;
_req->length++;
}
_req->dma = dma_map_single(&dev->pdev->dev,
_req->buf, _req->length,
is_in(ep) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
if (zlflag && (_req->length == 1)) {
dev_vdbg(&dev->pdev->dev, "req->length: 1->0\n");
zlflag = 0;
_req->length = 0;
}
req->mapped = 1;
dev_vdbg(&dev->pdev->dev, "req->mapped = 1\n");
} else {
dma_sync_single_for_device(&dev->pdev->dev,
_req->dma, _req->length,
is_in(ep) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
req->mapped = 0;
dev_vdbg(&dev->pdev->dev, "req->mapped = 0\n");
}
dev_dbg(&dev->pdev->dev,
"%s queue req %p, len %u, buf %p, dma 0x%08x\n",
_ep->name,
_req, _req->length, _req->buf, (int)_req->dma);
_req->status = -EINPROGRESS;
_req->actual = 0;
req->dtd_count = 0;
spin_lock_irqsave(&dev->lock, flags);
/* build and put dTDs to endpoint queue */
if (!req_to_dtd(req)) {
queue_dtd(ep, req);
} else {
spin_unlock_irqrestore(&dev->lock, flags);
return -ENOMEM;
}
/* update ep0 state */
if (ep->ep_num == 0)
dev->ep0_state = DATA_STATE_XMIT;
if (likely(req != NULL)) {
list_add_tail(&req->queue, &ep->queue);
dev_vdbg(&dev->pdev->dev, "list_add_tail()\n");
}
spin_unlock_irqrestore(&dev->lock, flags);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return 0;
}
/* dequeue (cancels, unlinks) an I/O request from an endpoint */
static int langwell_ep_dequeue(struct usb_ep *_ep, struct usb_request *_req)
{
struct langwell_ep *ep;
struct langwell_udc *dev;
struct langwell_request *req;
unsigned long flags;
int stopped, ep_num, retval = 0;
u32 endptctrl;
ep = container_of(_ep, struct langwell_ep, ep);
dev = ep->dev;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
if (!_ep || !ep->desc || !_req)
return -EINVAL;
if (!dev->driver)
return -ESHUTDOWN;
spin_lock_irqsave(&dev->lock, flags);
stopped = ep->stopped;
/* quiesce dma while we patch the queue */
ep->stopped = 1;
ep_num = ep->ep_num;
/* disable endpoint control register */
endptctrl = readl(&dev->op_regs->endptctrl[ep_num]);
if (is_in(ep))
endptctrl &= ~EPCTRL_TXE;
else
endptctrl &= ~EPCTRL_RXE;
writel(endptctrl, &dev->op_regs->endptctrl[ep_num]);
/* make sure it's still queued on this endpoint */
list_for_each_entry(req, &ep->queue, queue) {
if (&req->req == _req)
break;
}
if (&req->req != _req) {
retval = -EINVAL;
goto done;
}
/* queue head may be partially complete. */
if (ep->queue.next == &req->queue) {
dev_dbg(&dev->pdev->dev, "unlink (%s) dma\n", _ep->name);
_req->status = -ECONNRESET;
langwell_ep_fifo_flush(&ep->ep);
/* not the last request in endpoint queue */
if (likely(ep->queue.next == &req->queue)) {
struct langwell_dqh *dqh;
struct langwell_request *next_req;
dqh = ep->dqh;
next_req = list_entry(req->queue.next,
struct langwell_request, queue);
/* point the dQH to the first dTD of next request */
writel((u32) next_req->head, &dqh->dqh_current);
}
} else {
struct langwell_request *prev_req;
prev_req = list_entry(req->queue.prev,
struct langwell_request, queue);
writel(readl(&req->tail->dtd_next),
&prev_req->tail->dtd_next);
}
done(ep, req, -ECONNRESET);
done:
/* enable endpoint again */
endptctrl = readl(&dev->op_regs->endptctrl[ep_num]);
if (is_in(ep))
endptctrl |= EPCTRL_TXE;
else
endptctrl |= EPCTRL_RXE;
writel(endptctrl, &dev->op_regs->endptctrl[ep_num]);
ep->stopped = stopped;
spin_unlock_irqrestore(&dev->lock, flags);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return retval;
}
/*-------------------------------------------------------------------------*/
/* endpoint set/clear halt */
static void ep_set_halt(struct langwell_ep *ep, int value)
{
u32 endptctrl = 0;
int ep_num;
struct langwell_udc *dev = ep->dev;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
ep_num = ep->ep_num;
endptctrl = readl(&dev->op_regs->endptctrl[ep_num]);
/* value: 1 - set halt, 0 - clear halt */
if (value) {
/* set the stall bit */
if (is_in(ep))
endptctrl |= EPCTRL_TXS;
else
endptctrl |= EPCTRL_RXS;
} else {
/* clear the stall bit and reset data toggle */
if (is_in(ep)) {
endptctrl &= ~EPCTRL_TXS;
endptctrl |= EPCTRL_TXR;
} else {
endptctrl &= ~EPCTRL_RXS;
endptctrl |= EPCTRL_RXR;
}
}
writel(endptctrl, &dev->op_regs->endptctrl[ep_num]);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* set the endpoint halt feature */
static int langwell_ep_set_halt(struct usb_ep *_ep, int value)
{
struct langwell_ep *ep;
struct langwell_udc *dev;
unsigned long flags;
int retval = 0;
ep = container_of(_ep, struct langwell_ep, ep);
dev = ep->dev;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
if (!_ep || !ep->desc)
return -EINVAL;
if (!dev->driver || dev->gadget.speed == USB_SPEED_UNKNOWN)
return -ESHUTDOWN;
if (usb_endpoint_xfer_isoc(ep->desc))
return -EOPNOTSUPP;
spin_lock_irqsave(&dev->lock, flags);
/*
* attempt to halt IN ep will fail if any transfer requests
* are still queue
*/
if (!list_empty(&ep->queue) && is_in(ep) && value) {
/* IN endpoint FIFO holds bytes */
dev_dbg(&dev->pdev->dev, "%s FIFO holds bytes\n", _ep->name);
retval = -EAGAIN;
goto done;
}
/* endpoint set/clear halt */
if (ep->ep_num) {
ep_set_halt(ep, value);
} else { /* endpoint 0 */
dev->ep0_state = WAIT_FOR_SETUP;
dev->ep0_dir = USB_DIR_OUT;
}
done:
spin_unlock_irqrestore(&dev->lock, flags);
dev_dbg(&dev->pdev->dev, "%s %s halt\n",
_ep->name, value ? "set" : "clear");
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return retval;
}
/* set the halt feature and ignores clear requests */
static int langwell_ep_set_wedge(struct usb_ep *_ep)
{
struct langwell_ep *ep;
struct langwell_udc *dev;
ep = container_of(_ep, struct langwell_ep, ep);
dev = ep->dev;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
if (!_ep || !ep->desc)
return -EINVAL;
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return usb_ep_set_halt(_ep);
}
/* flush contents of a fifo */
static void langwell_ep_fifo_flush(struct usb_ep *_ep)
{
struct langwell_ep *ep;
struct langwell_udc *dev;
u32 flush_bit;
unsigned long timeout;
ep = container_of(_ep, struct langwell_ep, ep);
dev = ep->dev;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
if (!_ep || !ep->desc) {
dev_vdbg(&dev->pdev->dev, "ep or ep->desc is NULL\n");
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return;
}
dev_vdbg(&dev->pdev->dev, "%s-%s fifo flush\n",
_ep->name, DIR_STRING(ep));
/* flush endpoint buffer */
if (ep->ep_num == 0)
flush_bit = (1 << 16) | 1;
else if (is_in(ep))
flush_bit = 1 << (ep->ep_num + 16); /* TX */
else
flush_bit = 1 << ep->ep_num; /* RX */
/* wait until flush complete */
timeout = jiffies + FLUSH_TIMEOUT;
do {
writel(flush_bit, &dev->op_regs->endptflush);
while (readl(&dev->op_regs->endptflush)) {
if (time_after(jiffies, timeout)) {
dev_err(&dev->pdev->dev, "ep flush timeout\n");
goto done;
}
cpu_relax();
}
} while (readl(&dev->op_regs->endptstat) & flush_bit);
done:
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* endpoints operations structure */
static const struct usb_ep_ops langwell_ep_ops = {
/* configure endpoint, making it usable */
.enable = langwell_ep_enable,
/* endpoint is no longer usable */
.disable = langwell_ep_disable,
/* allocate a request object to use with this endpoint */
.alloc_request = langwell_alloc_request,
/* free a request object */
.free_request = langwell_free_request,
/* queue (submits) an I/O requests to an endpoint */
.queue = langwell_ep_queue,
/* dequeue (cancels, unlinks) an I/O request from an endpoint */
.dequeue = langwell_ep_dequeue,
/* set the endpoint halt feature */
.set_halt = langwell_ep_set_halt,
/* set the halt feature and ignores clear requests */
.set_wedge = langwell_ep_set_wedge,
/* flush contents of a fifo */
.fifo_flush = langwell_ep_fifo_flush,
};
/*-------------------------------------------------------------------------*/
/* device controller usb_gadget_ops structure */
/* returns the current frame number */
static int langwell_get_frame(struct usb_gadget *_gadget)
{
struct langwell_udc *dev;
u16 retval;
if (!_gadget)
return -ENODEV;
dev = container_of(_gadget, struct langwell_udc, gadget);
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
retval = readl(&dev->op_regs->frindex) & FRINDEX_MASK;
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return retval;
}
/* enter or exit PHY low power state */
static void langwell_phy_low_power(struct langwell_udc *dev, bool flag)
{
u32 devlc;
u8 devlc_byte2;
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
devlc = readl(&dev->op_regs->devlc);
dev_vdbg(&dev->pdev->dev, "devlc = 0x%08x\n", devlc);
if (flag)
devlc |= LPM_PHCD;
else
devlc &= ~LPM_PHCD;
/* FIXME: workaround for Langwell A1/A2/A3 sighting */
devlc_byte2 = (devlc >> 16) & 0xff;
writeb(devlc_byte2, (u8 *)&dev->op_regs->devlc + 2);
devlc = readl(&dev->op_regs->devlc);
dev_vdbg(&dev->pdev->dev,
"%s PHY low power suspend, devlc = 0x%08x\n",
flag ? "enter" : "exit", devlc);
}
/* tries to wake up the host connected to this gadget */
static int langwell_wakeup(struct usb_gadget *_gadget)
{
struct langwell_udc *dev;
u32 portsc1;
unsigned long flags;
if (!_gadget)
return 0;
dev = container_of(_gadget, struct langwell_udc, gadget);
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
/* remote wakeup feature not enabled by host */
if (!dev->remote_wakeup) {
dev_info(&dev->pdev->dev, "remote wakeup is disabled\n");
return -ENOTSUPP;
}
spin_lock_irqsave(&dev->lock, flags);
portsc1 = readl(&dev->op_regs->portsc1);
if (!(portsc1 & PORTS_SUSP)) {
spin_unlock_irqrestore(&dev->lock, flags);
return 0;
}
/* LPM L1 to L0 or legacy remote wakeup */
if (dev->lpm && dev->lpm_state == LPM_L1)
dev_info(&dev->pdev->dev, "LPM L1 to L0 remote wakeup\n");
else
dev_info(&dev->pdev->dev, "device remote wakeup\n");
/* exit PHY low power suspend */
if (dev->pdev->device != 0x0829)
langwell_phy_low_power(dev, 0);
/* force port resume */
portsc1 |= PORTS_FPR;
writel(portsc1, &dev->op_regs->portsc1);
spin_unlock_irqrestore(&dev->lock, flags);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return 0;
}
/* notify controller that VBUS is powered or not */
static int langwell_vbus_session(struct usb_gadget *_gadget, int is_active)
{
struct langwell_udc *dev;
unsigned long flags;
u32 usbcmd;
if (!_gadget)
return -ENODEV;
dev = container_of(_gadget, struct langwell_udc, gadget);
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
spin_lock_irqsave(&dev->lock, flags);
dev_vdbg(&dev->pdev->dev, "VBUS status: %s\n",
is_active ? "on" : "off");
dev->vbus_active = (is_active != 0);
if (dev->driver && dev->softconnected && dev->vbus_active) {
usbcmd = readl(&dev->op_regs->usbcmd);
usbcmd |= CMD_RUNSTOP;
writel(usbcmd, &dev->op_regs->usbcmd);
} else {
usbcmd = readl(&dev->op_regs->usbcmd);
usbcmd &= ~CMD_RUNSTOP;
writel(usbcmd, &dev->op_regs->usbcmd);
}
spin_unlock_irqrestore(&dev->lock, flags);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return 0;
}
/* constrain controller's VBUS power usage */
static int langwell_vbus_draw(struct usb_gadget *_gadget, unsigned mA)
{
struct langwell_udc *dev;
if (!_gadget)
return -ENODEV;
dev = container_of(_gadget, struct langwell_udc, gadget);
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
if (dev->transceiver) {
dev_vdbg(&dev->pdev->dev, "otg_set_power\n");
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return otg_set_power(dev->transceiver, mA);
}
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return -ENOTSUPP;
}
/* D+ pullup, software-controlled connect/disconnect to USB host */
static int langwell_pullup(struct usb_gadget *_gadget, int is_on)
{
struct langwell_udc *dev;
u32 usbcmd;
unsigned long flags;
if (!_gadget)
return -ENODEV;
dev = container_of(_gadget, struct langwell_udc, gadget);
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
spin_lock_irqsave(&dev->lock, flags);
dev->softconnected = (is_on != 0);
if (dev->driver && dev->softconnected && dev->vbus_active) {
usbcmd = readl(&dev->op_regs->usbcmd);
usbcmd |= CMD_RUNSTOP;
writel(usbcmd, &dev->op_regs->usbcmd);
} else {
usbcmd = readl(&dev->op_regs->usbcmd);
usbcmd &= ~CMD_RUNSTOP;
writel(usbcmd, &dev->op_regs->usbcmd);
}
spin_unlock_irqrestore(&dev->lock, flags);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return 0;
}
static int langwell_start(struct usb_gadget_driver *driver,
int (*bind)(struct usb_gadget *));
static int langwell_stop(struct usb_gadget_driver *driver);
/* device controller usb_gadget_ops structure */
static const struct usb_gadget_ops langwell_ops = {
/* returns the current frame number */
.get_frame = langwell_get_frame,
/* tries to wake up the host connected to this gadget */
.wakeup = langwell_wakeup,
/* set the device selfpowered feature, always selfpowered */
/* .set_selfpowered = langwell_set_selfpowered, */
/* notify controller that VBUS is powered or not */
.vbus_session = langwell_vbus_session,
/* constrain controller's VBUS power usage */
.vbus_draw = langwell_vbus_draw,
/* D+ pullup, software-controlled connect/disconnect to USB host */
.pullup = langwell_pullup,
.start = langwell_start,
.stop = langwell_stop,
};
/*-------------------------------------------------------------------------*/
/* device controller operations */
/* reset device controller */
static int langwell_udc_reset(struct langwell_udc *dev)
{
u32 usbcmd, usbmode, devlc, endpointlistaddr;
u8 devlc_byte0, devlc_byte2;
unsigned long timeout;
if (!dev)
return -EINVAL;
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
/* set controller to stop state */
usbcmd = readl(&dev->op_regs->usbcmd);
usbcmd &= ~CMD_RUNSTOP;
writel(usbcmd, &dev->op_regs->usbcmd);
/* reset device controller */
usbcmd = readl(&dev->op_regs->usbcmd);
usbcmd |= CMD_RST;
writel(usbcmd, &dev->op_regs->usbcmd);
/* wait for reset to complete */
timeout = jiffies + RESET_TIMEOUT;
while (readl(&dev->op_regs->usbcmd) & CMD_RST) {
if (time_after(jiffies, timeout)) {
dev_err(&dev->pdev->dev, "device reset timeout\n");
return -ETIMEDOUT;
}
cpu_relax();
}
/* set controller to device mode */
usbmode = readl(&dev->op_regs->usbmode);
usbmode |= MODE_DEVICE;
/* turn setup lockout off, require setup tripwire in usbcmd */
usbmode |= MODE_SLOM;
writel(usbmode, &dev->op_regs->usbmode);
usbmode = readl(&dev->op_regs->usbmode);
dev_vdbg(&dev->pdev->dev, "usbmode=0x%08x\n", usbmode);
/* Write-Clear setup status */
writel(0, &dev->op_regs->usbsts);
/* if support USB LPM, ACK all LPM token */
if (dev->lpm) {
devlc = readl(&dev->op_regs->devlc);
dev_vdbg(&dev->pdev->dev, "devlc = 0x%08x\n", devlc);
/* FIXME: workaround for Langwell A1/A2/A3 sighting */
devlc &= ~LPM_STL; /* don't STALL LPM token */
devlc &= ~LPM_NYT_ACK; /* ACK LPM token */
devlc_byte0 = devlc & 0xff;
devlc_byte2 = (devlc >> 16) & 0xff;
writeb(devlc_byte0, (u8 *)&dev->op_regs->devlc);
writeb(devlc_byte2, (u8 *)&dev->op_regs->devlc + 2);
devlc = readl(&dev->op_regs->devlc);
dev_vdbg(&dev->pdev->dev,
"ACK LPM token, devlc = 0x%08x\n", devlc);
}
/* fill endpointlistaddr register */
endpointlistaddr = dev->ep_dqh_dma;
endpointlistaddr &= ENDPOINTLISTADDR_MASK;
writel(endpointlistaddr, &dev->op_regs->endpointlistaddr);
dev_vdbg(&dev->pdev->dev,
"dQH base (vir: %p, phy: 0x%08x), endpointlistaddr=0x%08x\n",
dev->ep_dqh, endpointlistaddr,
readl(&dev->op_regs->endpointlistaddr));
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return 0;
}
/* reinitialize device controller endpoints */
static int eps_reinit(struct langwell_udc *dev)
{
struct langwell_ep *ep;
char name[14];
int i;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
/* initialize ep0 */
ep = &dev->ep[0];
ep->dev = dev;
strncpy(ep->name, "ep0", sizeof(ep->name));
ep->ep.name = ep->name;
ep->ep.ops = &langwell_ep_ops;
ep->stopped = 0;
ep->ep.maxpacket = EP0_MAX_PKT_SIZE;
ep->ep_num = 0;
ep->desc = &langwell_ep0_desc;
INIT_LIST_HEAD(&ep->queue);
ep->ep_type = USB_ENDPOINT_XFER_CONTROL;
/* initialize other endpoints */
for (i = 2; i < dev->ep_max; i++) {
ep = &dev->ep[i];
if (i % 2)
snprintf(name, sizeof(name), "ep%din", i / 2);
else
snprintf(name, sizeof(name), "ep%dout", i / 2);
ep->dev = dev;
strncpy(ep->name, name, sizeof(ep->name));
ep->ep.name = ep->name;
ep->ep.ops = &langwell_ep_ops;
ep->stopped = 0;
ep->ep.maxpacket = (unsigned short) ~0;
ep->ep_num = i / 2;
INIT_LIST_HEAD(&ep->queue);
list_add_tail(&ep->ep.ep_list, &dev->gadget.ep_list);
}
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return 0;
}
/* enable interrupt and set controller to run state */
static void langwell_udc_start(struct langwell_udc *dev)
{
u32 usbintr, usbcmd;
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
/* enable interrupts */
usbintr = INTR_ULPIE /* ULPI */
| INTR_SLE /* suspend */
/* | INTR_SRE SOF received */
| INTR_URE /* USB reset */
| INTR_AAE /* async advance */
| INTR_SEE /* system error */
| INTR_FRE /* frame list rollover */
| INTR_PCE /* port change detect */
| INTR_UEE /* USB error interrupt */
| INTR_UE; /* USB interrupt */
writel(usbintr, &dev->op_regs->usbintr);
/* clear stopped bit */
dev->stopped = 0;
/* set controller to run */
usbcmd = readl(&dev->op_regs->usbcmd);
usbcmd |= CMD_RUNSTOP;
writel(usbcmd, &dev->op_regs->usbcmd);
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* disable interrupt and set controller to stop state */
static void langwell_udc_stop(struct langwell_udc *dev)
{
u32 usbcmd;
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
/* disable all interrupts */
writel(0, &dev->op_regs->usbintr);
/* set stopped bit */
dev->stopped = 1;
/* set controller to stop state */
usbcmd = readl(&dev->op_regs->usbcmd);
usbcmd &= ~CMD_RUNSTOP;
writel(usbcmd, &dev->op_regs->usbcmd);
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* stop all USB activities */
static void stop_activity(struct langwell_udc *dev,
struct usb_gadget_driver *driver)
{
struct langwell_ep *ep;
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
nuke(&dev->ep[0], -ESHUTDOWN);
list_for_each_entry(ep, &dev->gadget.ep_list, ep.ep_list) {
nuke(ep, -ESHUTDOWN);
}
/* report disconnect; the driver is already quiesced */
if (driver) {
spin_unlock(&dev->lock);
driver->disconnect(&dev->gadget);
spin_lock(&dev->lock);
}
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/*-------------------------------------------------------------------------*/
/* device "function" sysfs attribute file */
static ssize_t show_function(struct device *_dev,
struct device_attribute *attr, char *buf)
{
struct langwell_udc *dev = the_controller;
if (!dev->driver || !dev->driver->function
|| strlen(dev->driver->function) > PAGE_SIZE)
return 0;
return scnprintf(buf, PAGE_SIZE, "%s\n", dev->driver->function);
}
static DEVICE_ATTR(function, S_IRUGO, show_function, NULL);
/* device "langwell_udc" sysfs attribute file */
static ssize_t show_langwell_udc(struct device *_dev,
struct device_attribute *attr, char *buf)
{
struct langwell_udc *dev = the_controller;
struct langwell_request *req;
struct langwell_ep *ep = NULL;
char *next;
unsigned size;
unsigned t;
unsigned i;
unsigned long flags;
u32 tmp_reg;
next = buf;
size = PAGE_SIZE;
spin_lock_irqsave(&dev->lock, flags);
/* driver basic information */
t = scnprintf(next, size,
DRIVER_DESC "\n"
"%s version: %s\n"
"Gadget driver: %s\n\n",
driver_name, DRIVER_VERSION,
dev->driver ? dev->driver->driver.name : "(none)");
size -= t;
next += t;
/* device registers */
tmp_reg = readl(&dev->op_regs->usbcmd);
t = scnprintf(next, size,
"USBCMD reg:\n"
"SetupTW: %d\n"
"Run/Stop: %s\n\n",
(tmp_reg & CMD_SUTW) ? 1 : 0,
(tmp_reg & CMD_RUNSTOP) ? "Run" : "Stop");
size -= t;
next += t;
tmp_reg = readl(&dev->op_regs->usbsts);
t = scnprintf(next, size,
"USB Status Reg:\n"
"Device Suspend: %d\n"
"Reset Received: %d\n"
"System Error: %s\n"
"USB Error Interrupt: %s\n\n",
(tmp_reg & STS_SLI) ? 1 : 0,
(tmp_reg & STS_URI) ? 1 : 0,
(tmp_reg & STS_SEI) ? "Error" : "No error",
(tmp_reg & STS_UEI) ? "Error detected" : "No error");
size -= t;
next += t;
tmp_reg = readl(&dev->op_regs->usbintr);
t = scnprintf(next, size,
"USB Intrrupt Enable Reg:\n"
"Sleep Enable: %d\n"
"SOF Received Enable: %d\n"
"Reset Enable: %d\n"
"System Error Enable: %d\n"
"Port Change Dectected Enable: %d\n"
"USB Error Intr Enable: %d\n"
"USB Intr Enable: %d\n\n",
(tmp_reg & INTR_SLE) ? 1 : 0,
(tmp_reg & INTR_SRE) ? 1 : 0,
(tmp_reg & INTR_URE) ? 1 : 0,
(tmp_reg & INTR_SEE) ? 1 : 0,
(tmp_reg & INTR_PCE) ? 1 : 0,
(tmp_reg & INTR_UEE) ? 1 : 0,
(tmp_reg & INTR_UE) ? 1 : 0);
size -= t;
next += t;
tmp_reg = readl(&dev->op_regs->frindex);
t = scnprintf(next, size,
"USB Frame Index Reg:\n"
"Frame Number is 0x%08x\n\n",
(tmp_reg & FRINDEX_MASK));
size -= t;
next += t;
tmp_reg = readl(&dev->op_regs->deviceaddr);
t = scnprintf(next, size,
"USB Device Address Reg:\n"
"Device Addr is 0x%x\n\n",
USBADR(tmp_reg));
size -= t;
next += t;
tmp_reg = readl(&dev->op_regs->endpointlistaddr);
t = scnprintf(next, size,
"USB Endpoint List Address Reg:\n"
"Endpoint List Pointer is 0x%x\n\n",
EPBASE(tmp_reg));
size -= t;
next += t;
tmp_reg = readl(&dev->op_regs->portsc1);
t = scnprintf(next, size,
"USB Port Status & Control Reg:\n"
"Port Reset: %s\n"
"Port Suspend Mode: %s\n"
"Over-current Change: %s\n"
"Port Enable/Disable Change: %s\n"
"Port Enabled/Disabled: %s\n"
"Current Connect Status: %s\n"
"LPM Suspend Status: %s\n\n",
(tmp_reg & PORTS_PR) ? "Reset" : "Not Reset",
(tmp_reg & PORTS_SUSP) ? "Suspend " : "Not Suspend",
(tmp_reg & PORTS_OCC) ? "Detected" : "No",
(tmp_reg & PORTS_PEC) ? "Changed" : "Not Changed",
(tmp_reg & PORTS_PE) ? "Enable" : "Not Correct",
(tmp_reg & PORTS_CCS) ? "Attached" : "Not Attached",
(tmp_reg & PORTS_SLP) ? "LPM L1" : "LPM L0");
size -= t;
next += t;
tmp_reg = readl(&dev->op_regs->devlc);
t = scnprintf(next, size,
"Device LPM Control Reg:\n"
"Parallel Transceiver : %d\n"
"Serial Transceiver : %d\n"
"Port Speed: %s\n"
"Port Force Full Speed Connenct: %s\n"
"PHY Low Power Suspend Clock: %s\n"
"BmAttributes: %d\n\n",
LPM_PTS(tmp_reg),
(tmp_reg & LPM_STS) ? 1 : 0,
({
char *s;
switch (LPM_PSPD(tmp_reg)) {
case LPM_SPEED_FULL:
s = "Full Speed"; break;
case LPM_SPEED_LOW:
s = "Low Speed"; break;
case LPM_SPEED_HIGH:
s = "High Speed"; break;
default:
s = "Unknown Speed"; break;
}
s;
}),
(tmp_reg & LPM_PFSC) ? "Force Full Speed" : "Not Force",
(tmp_reg & LPM_PHCD) ? "Disabled" : "Enabled",
LPM_BA(tmp_reg));
size -= t;
next += t;
tmp_reg = readl(&dev->op_regs->usbmode);
t = scnprintf(next, size,
"USB Mode Reg:\n"
"Controller Mode is : %s\n\n", ({
char *s;
switch (MODE_CM(tmp_reg)) {
case MODE_IDLE:
s = "Idle"; break;
case MODE_DEVICE:
s = "Device Controller"; break;
case MODE_HOST:
s = "Host Controller"; break;
default:
s = "None"; break;
}
s;
}));
size -= t;
next += t;
tmp_reg = readl(&dev->op_regs->endptsetupstat);
t = scnprintf(next, size,
"Endpoint Setup Status Reg:\n"
"SETUP on ep 0x%04x\n\n",
tmp_reg & SETUPSTAT_MASK);
size -= t;
next += t;
for (i = 0; i < dev->ep_max / 2; i++) {
tmp_reg = readl(&dev->op_regs->endptctrl[i]);
t = scnprintf(next, size, "EP Ctrl Reg [%d]: 0x%08x\n",
i, tmp_reg);
size -= t;
next += t;
}
tmp_reg = readl(&dev->op_regs->endptprime);
t = scnprintf(next, size, "EP Prime Reg: 0x%08x\n\n", tmp_reg);
size -= t;
next += t;
/* langwell_udc, langwell_ep, langwell_request structure information */
ep = &dev->ep[0];
t = scnprintf(next, size, "%s MaxPacketSize: 0x%x, ep_num: %d\n",
ep->ep.name, ep->ep.maxpacket, ep->ep_num);
size -= t;
next += t;
if (list_empty(&ep->queue)) {
t = scnprintf(next, size, "its req queue is empty\n\n");
size -= t;
next += t;
} else {
list_for_each_entry(req, &ep->queue, queue) {
t = scnprintf(next, size,
"req %p actual 0x%x length 0x%x buf %p\n",
&req->req, req->req.actual,
req->req.length, req->req.buf);
size -= t;
next += t;
}
}
/* other gadget->eplist ep */
list_for_each_entry(ep, &dev->gadget.ep_list, ep.ep_list) {
if (ep->desc) {
t = scnprintf(next, size,
"\n%s MaxPacketSize: 0x%x, "
"ep_num: %d\n",
ep->ep.name, ep->ep.maxpacket,
ep->ep_num);
size -= t;
next += t;
if (list_empty(&ep->queue)) {
t = scnprintf(next, size,
"its req queue is empty\n\n");
size -= t;
next += t;
} else {
list_for_each_entry(req, &ep->queue, queue) {
t = scnprintf(next, size,
"req %p actual 0x%x length "
"0x%x buf %p\n",
&req->req, req->req.actual,
req->req.length, req->req.buf);
size -= t;
next += t;
}
}
}
}
spin_unlock_irqrestore(&dev->lock, flags);
return PAGE_SIZE - size;
}
static DEVICE_ATTR(langwell_udc, S_IRUGO, show_langwell_udc, NULL);
/* device "remote_wakeup" sysfs attribute file */
static ssize_t store_remote_wakeup(struct device *_dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct langwell_udc *dev = the_controller;
unsigned long flags;
ssize_t rc = count;
if (count > 2)
return -EINVAL;
if (count > 0 && buf[count-1] == '\n')
((char *) buf)[count-1] = 0;
if (buf[0] != '1')
return -EINVAL;
/* force remote wakeup enabled in case gadget driver doesn't support */
spin_lock_irqsave(&dev->lock, flags);
dev->remote_wakeup = 1;
dev->dev_status |= (1 << USB_DEVICE_REMOTE_WAKEUP);
spin_unlock_irqrestore(&dev->lock, flags);
langwell_wakeup(&dev->gadget);
return rc;
}
static DEVICE_ATTR(remote_wakeup, S_IWUSR, NULL, store_remote_wakeup);
/*-------------------------------------------------------------------------*/
/*
* when a driver is successfully registered, it will receive
* control requests including set_configuration(), which enables
* non-control requests. then usb traffic follows until a
* disconnect is reported. then a host may connect again, or
* the driver might get unbound.
*/
static int langwell_start(struct usb_gadget_driver *driver,
int (*bind)(struct usb_gadget *))
{
struct langwell_udc *dev = the_controller;
unsigned long flags;
int retval;
if (!dev)
return -ENODEV;
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
if (dev->driver)
return -EBUSY;
spin_lock_irqsave(&dev->lock, flags);
/* hook up the driver ... */
driver->driver.bus = NULL;
dev->driver = driver;
dev->gadget.dev.driver = &driver->driver;
spin_unlock_irqrestore(&dev->lock, flags);
retval = bind(&dev->gadget);
if (retval) {
dev_dbg(&dev->pdev->dev, "bind to driver %s --> %d\n",
driver->driver.name, retval);
dev->driver = NULL;
dev->gadget.dev.driver = NULL;
return retval;
}
retval = device_create_file(&dev->pdev->dev, &dev_attr_function);
if (retval)
goto err_unbind;
dev->usb_state = USB_STATE_ATTACHED;
dev->ep0_state = WAIT_FOR_SETUP;
dev->ep0_dir = USB_DIR_OUT;
/* enable interrupt and set controller to run state */
if (dev->got_irq)
langwell_udc_start(dev);
dev_vdbg(&dev->pdev->dev,
"After langwell_udc_start(), print all registers:\n");
print_all_registers(dev);
dev_info(&dev->pdev->dev, "register driver: %s\n",
driver->driver.name);
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return 0;
err_unbind:
driver->unbind(&dev->gadget);
dev->gadget.dev.driver = NULL;
dev->driver = NULL;
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return retval;
}
/* unregister gadget driver */
static int langwell_stop(struct usb_gadget_driver *driver)
{
struct langwell_udc *dev = the_controller;
unsigned long flags;
if (!dev)
return -ENODEV;
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
if (unlikely(!driver || !driver->unbind))
return -EINVAL;
/* exit PHY low power suspend */
if (dev->pdev->device != 0x0829)
langwell_phy_low_power(dev, 0);
/* unbind OTG transceiver */
if (dev->transceiver)
(void)otg_set_peripheral(dev->transceiver, 0);
/* disable interrupt and set controller to stop state */
langwell_udc_stop(dev);
dev->usb_state = USB_STATE_ATTACHED;
dev->ep0_state = WAIT_FOR_SETUP;
dev->ep0_dir = USB_DIR_OUT;
spin_lock_irqsave(&dev->lock, flags);
/* stop all usb activities */
dev->gadget.speed = USB_SPEED_UNKNOWN;
stop_activity(dev, driver);
spin_unlock_irqrestore(&dev->lock, flags);
/* unbind gadget driver */
driver->unbind(&dev->gadget);
dev->gadget.dev.driver = NULL;
dev->driver = NULL;
device_remove_file(&dev->pdev->dev, &dev_attr_function);
dev_info(&dev->pdev->dev, "unregistered driver '%s'\n",
driver->driver.name);
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return 0;
}
/*-------------------------------------------------------------------------*/
/*
* setup tripwire is used as a semaphore to ensure that the setup data
* payload is extracted from a dQH without being corrupted
*/
static void setup_tripwire(struct langwell_udc *dev)
{
u32 usbcmd,
endptsetupstat;
unsigned long timeout;
struct langwell_dqh *dqh;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
/* ep0 OUT dQH */
dqh = &dev->ep_dqh[EP_DIR_OUT];
/* Write-Clear endptsetupstat */
endptsetupstat = readl(&dev->op_regs->endptsetupstat);
writel(endptsetupstat, &dev->op_regs->endptsetupstat);
/* wait until endptsetupstat is cleared */
timeout = jiffies + SETUPSTAT_TIMEOUT;
while (readl(&dev->op_regs->endptsetupstat)) {
if (time_after(jiffies, timeout)) {
dev_err(&dev->pdev->dev, "setup_tripwire timeout\n");
break;
}
cpu_relax();
}
/* while a hazard exists when setup packet arrives */
do {
/* set setup tripwire bit */
usbcmd = readl(&dev->op_regs->usbcmd);
writel(usbcmd | CMD_SUTW, &dev->op_regs->usbcmd);
/* copy the setup packet to local buffer */
memcpy(&dev->local_setup_buff, &dqh->dqh_setup, 8);
} while (!(readl(&dev->op_regs->usbcmd) & CMD_SUTW));
/* Write-Clear setup tripwire bit */
usbcmd = readl(&dev->op_regs->usbcmd);
writel(usbcmd & ~CMD_SUTW, &dev->op_regs->usbcmd);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* protocol ep0 stall, will automatically be cleared on new transaction */
static void ep0_stall(struct langwell_udc *dev)
{
u32 endptctrl;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
/* set TX and RX to stall */
endptctrl = readl(&dev->op_regs->endptctrl[0]);
endptctrl |= EPCTRL_TXS | EPCTRL_RXS;
writel(endptctrl, &dev->op_regs->endptctrl[0]);
/* update ep0 state */
dev->ep0_state = WAIT_FOR_SETUP;
dev->ep0_dir = USB_DIR_OUT;
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* PRIME a status phase for ep0 */
static int prime_status_phase(struct langwell_udc *dev, int dir)
{
struct langwell_request *req;
struct langwell_ep *ep;
int status = 0;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
if (dir == EP_DIR_IN)
dev->ep0_dir = USB_DIR_IN;
else
dev->ep0_dir = USB_DIR_OUT;
ep = &dev->ep[0];
dev->ep0_state = WAIT_FOR_OUT_STATUS;
req = dev->status_req;
req->ep = ep;
req->req.length = 0;
req->req.status = -EINPROGRESS;
req->req.actual = 0;
req->req.complete = NULL;
req->dtd_count = 0;
if (!req_to_dtd(req))
status = queue_dtd(ep, req);
else
return -ENOMEM;
if (status)
dev_err(&dev->pdev->dev, "can't queue ep0 status request\n");
list_add_tail(&req->queue, &ep->queue);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return status;
}
/* SET_ADDRESS request routine */
static void set_address(struct langwell_udc *dev, u16 value,
u16 index, u16 length)
{
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
/* save the new address to device struct */
dev->dev_addr = (u8) value;
dev_vdbg(&dev->pdev->dev, "dev->dev_addr = %d\n", dev->dev_addr);
/* update usb state */
dev->usb_state = USB_STATE_ADDRESS;
/* STATUS phase */
if (prime_status_phase(dev, EP_DIR_IN))
ep0_stall(dev);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* return endpoint by windex */
static struct langwell_ep *get_ep_by_windex(struct langwell_udc *dev,
u16 wIndex)
{
struct langwell_ep *ep;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
if ((wIndex & USB_ENDPOINT_NUMBER_MASK) == 0)
return &dev->ep[0];
list_for_each_entry(ep, &dev->gadget.ep_list, ep.ep_list) {
u8 bEndpointAddress;
if (!ep->desc)
continue;
bEndpointAddress = ep->desc->bEndpointAddress;
if ((wIndex ^ bEndpointAddress) & USB_DIR_IN)
continue;
if ((wIndex & USB_ENDPOINT_NUMBER_MASK)
== (bEndpointAddress & USB_ENDPOINT_NUMBER_MASK))
return ep;
}
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return NULL;
}
/* return whether endpoint is stalled, 0: not stalled; 1: stalled */
static int ep_is_stall(struct langwell_ep *ep)
{
struct langwell_udc *dev = ep->dev;
u32 endptctrl;
int retval;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
endptctrl = readl(&dev->op_regs->endptctrl[ep->ep_num]);
if (is_in(ep))
retval = endptctrl & EPCTRL_TXS ? 1 : 0;
else
retval = endptctrl & EPCTRL_RXS ? 1 : 0;
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return retval;
}
/* GET_STATUS request routine */
static void get_status(struct langwell_udc *dev, u8 request_type, u16 value,
u16 index, u16 length)
{
struct langwell_request *req;
struct langwell_ep *ep;
u16 status_data = 0; /* 16 bits cpu view status data */
int status = 0;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
ep = &dev->ep[0];
if ((request_type & USB_RECIP_MASK) == USB_RECIP_DEVICE) {
/* get device status */
status_data = dev->dev_status;
} else if ((request_type & USB_RECIP_MASK) == USB_RECIP_INTERFACE) {
/* get interface status */
status_data = 0;
} else if ((request_type & USB_RECIP_MASK) == USB_RECIP_ENDPOINT) {
/* get endpoint status */
struct langwell_ep *epn;
epn = get_ep_by_windex(dev, index);
/* stall if endpoint doesn't exist */
if (!epn)
goto stall;
status_data = ep_is_stall(epn) << USB_ENDPOINT_HALT;
}
dev_dbg(&dev->pdev->dev, "get status data: 0x%04x\n", status_data);
dev->ep0_dir = USB_DIR_IN;
/* borrow the per device status_req */
req = dev->status_req;
/* fill in the reqest structure */
*((u16 *) req->req.buf) = cpu_to_le16(status_data);
req->ep = ep;
req->req.length = 2;
req->req.status = -EINPROGRESS;
req->req.actual = 0;
req->req.complete = NULL;
req->dtd_count = 0;
/* prime the data phase */
if (!req_to_dtd(req))
status = queue_dtd(ep, req);
else /* no mem */
goto stall;
if (status) {
dev_err(&dev->pdev->dev,
"response error on GET_STATUS request\n");
goto stall;
}
list_add_tail(&req->queue, &ep->queue);
dev->ep0_state = DATA_STATE_XMIT;
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return;
stall:
ep0_stall(dev);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* setup packet interrupt handler */
static void handle_setup_packet(struct langwell_udc *dev,
struct usb_ctrlrequest *setup)
{
u16 wValue = le16_to_cpu(setup->wValue);
u16 wIndex = le16_to_cpu(setup->wIndex);
u16 wLength = le16_to_cpu(setup->wLength);
u32 portsc1;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
/* ep0 fifo flush */
nuke(&dev->ep[0], -ESHUTDOWN);
dev_dbg(&dev->pdev->dev, "SETUP %02x.%02x v%04x i%04x l%04x\n",
setup->bRequestType, setup->bRequest,
wValue, wIndex, wLength);
/* RNDIS gadget delegate */
if ((setup->bRequestType == 0x21) && (setup->bRequest == 0x00)) {
/* USB_CDC_SEND_ENCAPSULATED_COMMAND */
goto delegate;
}
/* USB_CDC_GET_ENCAPSULATED_RESPONSE */
if ((setup->bRequestType == 0xa1) && (setup->bRequest == 0x01)) {
/* USB_CDC_GET_ENCAPSULATED_RESPONSE */
goto delegate;
}
/* We process some stardard setup requests here */
switch (setup->bRequest) {
case USB_REQ_GET_STATUS:
dev_dbg(&dev->pdev->dev, "SETUP: USB_REQ_GET_STATUS\n");
/* get status, DATA and STATUS phase */
if ((setup->bRequestType & (USB_DIR_IN | USB_TYPE_MASK))
!= (USB_DIR_IN | USB_TYPE_STANDARD))
break;
get_status(dev, setup->bRequestType, wValue, wIndex, wLength);
goto end;
case USB_REQ_SET_ADDRESS:
dev_dbg(&dev->pdev->dev, "SETUP: USB_REQ_SET_ADDRESS\n");
/* STATUS phase */
if (setup->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD
| USB_RECIP_DEVICE))
break;
set_address(dev, wValue, wIndex, wLength);
goto end;
case USB_REQ_CLEAR_FEATURE:
case USB_REQ_SET_FEATURE:
/* STATUS phase */
{
int rc = -EOPNOTSUPP;
if (setup->bRequest == USB_REQ_SET_FEATURE)
dev_dbg(&dev->pdev->dev,
"SETUP: USB_REQ_SET_FEATURE\n");
else if (setup->bRequest == USB_REQ_CLEAR_FEATURE)
dev_dbg(&dev->pdev->dev,
"SETUP: USB_REQ_CLEAR_FEATURE\n");
if ((setup->bRequestType & (USB_RECIP_MASK | USB_TYPE_MASK))
== (USB_RECIP_ENDPOINT | USB_TYPE_STANDARD)) {
struct langwell_ep *epn;
epn = get_ep_by_windex(dev, wIndex);
/* stall if endpoint doesn't exist */
if (!epn) {
ep0_stall(dev);
goto end;
}
if (wValue != 0 || wLength != 0
|| epn->ep_num > dev->ep_max)
break;
spin_unlock(&dev->lock);
rc = langwell_ep_set_halt(&epn->ep,
(setup->bRequest == USB_REQ_SET_FEATURE)
? 1 : 0);
spin_lock(&dev->lock);
} else if ((setup->bRequestType & (USB_RECIP_MASK
| USB_TYPE_MASK)) == (USB_RECIP_DEVICE
| USB_TYPE_STANDARD)) {
rc = 0;
switch (wValue) {
case USB_DEVICE_REMOTE_WAKEUP:
if (setup->bRequest == USB_REQ_SET_FEATURE) {
dev->remote_wakeup = 1;
dev->dev_status |= (1 << wValue);
} else {
dev->remote_wakeup = 0;
dev->dev_status &= ~(1 << wValue);
}
break;
case USB_DEVICE_TEST_MODE:
dev_dbg(&dev->pdev->dev, "SETUP: TEST MODE\n");
if ((wIndex & 0xff) ||
(dev->gadget.speed != USB_SPEED_HIGH))
ep0_stall(dev);
switch (wIndex >> 8) {
case TEST_J:
case TEST_K:
case TEST_SE0_NAK:
case TEST_PACKET:
case TEST_FORCE_EN:
if (prime_status_phase(dev, EP_DIR_IN))
ep0_stall(dev);
portsc1 = readl(&dev->op_regs->portsc1);
portsc1 |= (wIndex & 0xf00) << 8;
writel(portsc1, &dev->op_regs->portsc1);
goto end;
default:
rc = -EOPNOTSUPP;
}
break;
default:
rc = -EOPNOTSUPP;
break;
}
if (!gadget_is_otg(&dev->gadget))
break;
else if (setup->bRequest == USB_DEVICE_B_HNP_ENABLE) {
dev->gadget.b_hnp_enable = 1;
#ifdef OTG_TRANSCEIVER
if (!dev->lotg->otg.default_a)
dev->lotg->hsm.b_hnp_enable = 1;
#endif
} else if (setup->bRequest == USB_DEVICE_A_HNP_SUPPORT)
dev->gadget.a_hnp_support = 1;
else if (setup->bRequest ==
USB_DEVICE_A_ALT_HNP_SUPPORT)
dev->gadget.a_alt_hnp_support = 1;
else
break;
} else
break;
if (rc == 0) {
if (prime_status_phase(dev, EP_DIR_IN))
ep0_stall(dev);
}
goto end;
}
case USB_REQ_GET_DESCRIPTOR:
dev_dbg(&dev->pdev->dev,
"SETUP: USB_REQ_GET_DESCRIPTOR\n");
goto delegate;
case USB_REQ_SET_DESCRIPTOR:
dev_dbg(&dev->pdev->dev,
"SETUP: USB_REQ_SET_DESCRIPTOR unsupported\n");
goto delegate;
case USB_REQ_GET_CONFIGURATION:
dev_dbg(&dev->pdev->dev,
"SETUP: USB_REQ_GET_CONFIGURATION\n");
goto delegate;
case USB_REQ_SET_CONFIGURATION:
dev_dbg(&dev->pdev->dev,
"SETUP: USB_REQ_SET_CONFIGURATION\n");
goto delegate;
case USB_REQ_GET_INTERFACE:
dev_dbg(&dev->pdev->dev,
"SETUP: USB_REQ_GET_INTERFACE\n");
goto delegate;
case USB_REQ_SET_INTERFACE:
dev_dbg(&dev->pdev->dev,
"SETUP: USB_REQ_SET_INTERFACE\n");
goto delegate;
case USB_REQ_SYNCH_FRAME:
dev_dbg(&dev->pdev->dev,
"SETUP: USB_REQ_SYNCH_FRAME unsupported\n");
goto delegate;
default:
/* delegate USB standard requests to the gadget driver */
goto delegate;
delegate:
/* USB requests handled by gadget */
if (wLength) {
/* DATA phase from gadget, STATUS phase from udc */
dev->ep0_dir = (setup->bRequestType & USB_DIR_IN)
? USB_DIR_IN : USB_DIR_OUT;
dev_vdbg(&dev->pdev->dev,
"dev->ep0_dir = 0x%x, wLength = %d\n",
dev->ep0_dir, wLength);
spin_unlock(&dev->lock);
if (dev->driver->setup(&dev->gadget,
&dev->local_setup_buff) < 0)
ep0_stall(dev);
spin_lock(&dev->lock);
dev->ep0_state = (setup->bRequestType & USB_DIR_IN)
? DATA_STATE_XMIT : DATA_STATE_RECV;
} else {
/* no DATA phase, IN STATUS phase from gadget */
dev->ep0_dir = USB_DIR_IN;
dev_vdbg(&dev->pdev->dev,
"dev->ep0_dir = 0x%x, wLength = %d\n",
dev->ep0_dir, wLength);
spin_unlock(&dev->lock);
if (dev->driver->setup(&dev->gadget,
&dev->local_setup_buff) < 0)
ep0_stall(dev);
spin_lock(&dev->lock);
dev->ep0_state = WAIT_FOR_OUT_STATUS;
}
break;
}
end:
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* transfer completion, process endpoint request and free the completed dTDs
* for this request
*/
static int process_ep_req(struct langwell_udc *dev, int index,
struct langwell_request *curr_req)
{
struct langwell_dtd *curr_dtd;
struct langwell_dqh *curr_dqh;
int td_complete, actual, remaining_length;
int i, dir;
u8 dtd_status = 0;
int retval = 0;
curr_dqh = &dev->ep_dqh[index];
dir = index % 2;
curr_dtd = curr_req->head;
td_complete = 0;
actual = curr_req->req.length;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
for (i = 0; i < curr_req->dtd_count; i++) {
/* command execution states by dTD */
dtd_status = curr_dtd->dtd_status;
barrier();
remaining_length = le16_to_cpu(curr_dtd->dtd_total);
actual -= remaining_length;
if (!dtd_status) {
/* transfers completed successfully */
if (!remaining_length) {
td_complete++;
dev_vdbg(&dev->pdev->dev,
"dTD transmitted successfully\n");
} else {
if (dir) {
dev_vdbg(&dev->pdev->dev,
"TX dTD remains data\n");
retval = -EPROTO;
break;
} else {
td_complete++;
break;
}
}
} else {
/* transfers completed with errors */
if (dtd_status & DTD_STS_ACTIVE) {
dev_dbg(&dev->pdev->dev,
"dTD status ACTIVE dQH[%d]\n", index);
retval = 1;
return retval;
} else if (dtd_status & DTD_STS_HALTED) {
dev_err(&dev->pdev->dev,
"dTD error %08x dQH[%d]\n",
dtd_status, index);
/* clear the errors and halt condition */
curr_dqh->dtd_status = 0;
retval = -EPIPE;
break;
} else if (dtd_status & DTD_STS_DBE) {
dev_dbg(&dev->pdev->dev,
"data buffer (overflow) error\n");
retval = -EPROTO;
break;
} else if (dtd_status & DTD_STS_TRE) {
dev_dbg(&dev->pdev->dev,
"transaction(ISO) error\n");
retval = -EILSEQ;
break;
} else
dev_err(&dev->pdev->dev,
"unknown error (0x%x)!\n",
dtd_status);
}
if (i != curr_req->dtd_count - 1)
curr_dtd = (struct langwell_dtd *)
curr_dtd->next_dtd_virt;
}
if (retval)
return retval;
curr_req->req.actual = actual;
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return 0;
}
/* complete DATA or STATUS phase of ep0 prime status phase if needed */
static void ep0_req_complete(struct langwell_udc *dev,
struct langwell_ep *ep0, struct langwell_request *req)
{
u32 new_addr;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
if (dev->usb_state == USB_STATE_ADDRESS) {
/* set the new address */
new_addr = (u32)dev->dev_addr;
writel(new_addr << USBADR_SHIFT, &dev->op_regs->deviceaddr);
new_addr = USBADR(readl(&dev->op_regs->deviceaddr));
dev_vdbg(&dev->pdev->dev, "new_addr = %d\n", new_addr);
}
done(ep0, req, 0);
switch (dev->ep0_state) {
case DATA_STATE_XMIT:
/* receive status phase */
if (prime_status_phase(dev, EP_DIR_OUT))
ep0_stall(dev);
break;
case DATA_STATE_RECV:
/* send status phase */
if (prime_status_phase(dev, EP_DIR_IN))
ep0_stall(dev);
break;
case WAIT_FOR_OUT_STATUS:
dev->ep0_state = WAIT_FOR_SETUP;
break;
case WAIT_FOR_SETUP:
dev_err(&dev->pdev->dev, "unexpect ep0 packets\n");
break;
default:
ep0_stall(dev);
break;
}
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* USB transfer completion interrupt */
static void handle_trans_complete(struct langwell_udc *dev)
{
u32 complete_bits;
int i, ep_num, dir, bit_mask, status;
struct langwell_ep *epn;
struct langwell_request *curr_req, *temp_req;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
complete_bits = readl(&dev->op_regs->endptcomplete);
dev_vdbg(&dev->pdev->dev, "endptcomplete register: 0x%08x\n",
complete_bits);
/* Write-Clear the bits in endptcomplete register */
writel(complete_bits, &dev->op_regs->endptcomplete);
if (!complete_bits) {
dev_dbg(&dev->pdev->dev, "complete_bits = 0\n");
goto done;
}
for (i = 0; i < dev->ep_max; i++) {
ep_num = i / 2;
dir = i % 2;
bit_mask = 1 << (ep_num + 16 * dir);
if (!(complete_bits & bit_mask))
continue;
/* ep0 */
if (i == 1)
epn = &dev->ep[0];
else
epn = &dev->ep[i];
if (epn->name == NULL) {
dev_warn(&dev->pdev->dev, "invalid endpoint\n");
continue;
}
if (i < 2)
/* ep0 in and out */
dev_dbg(&dev->pdev->dev, "%s-%s transfer completed\n",
epn->name,
is_in(epn) ? "in" : "out");
else
dev_dbg(&dev->pdev->dev, "%s transfer completed\n",
epn->name);
/* process the req queue until an uncomplete request */
list_for_each_entry_safe(curr_req, temp_req,
&epn->queue, queue) {
status = process_ep_req(dev, i, curr_req);
dev_vdbg(&dev->pdev->dev, "%s req status: %d\n",
epn->name, status);
if (status)
break;
/* write back status to req */
curr_req->req.status = status;
/* ep0 request completion */
if (ep_num == 0) {
ep0_req_complete(dev, epn, curr_req);
break;
} else {
done(epn, curr_req, status);
}
}
}
done:
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* port change detect interrupt handler */
static void handle_port_change(struct langwell_udc *dev)
{
u32 portsc1, devlc;
u32 speed;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
if (dev->bus_reset)
dev->bus_reset = 0;
portsc1 = readl(&dev->op_regs->portsc1);
devlc = readl(&dev->op_regs->devlc);
dev_vdbg(&dev->pdev->dev, "portsc1 = 0x%08x, devlc = 0x%08x\n",
portsc1, devlc);
/* bus reset is finished */
if (!(portsc1 & PORTS_PR)) {
/* get the speed */
speed = LPM_PSPD(devlc);
switch (speed) {
case LPM_SPEED_HIGH:
dev->gadget.speed = USB_SPEED_HIGH;
break;
case LPM_SPEED_FULL:
dev->gadget.speed = USB_SPEED_FULL;
break;
case LPM_SPEED_LOW:
dev->gadget.speed = USB_SPEED_LOW;
break;
default:
dev->gadget.speed = USB_SPEED_UNKNOWN;
break;
}
dev_vdbg(&dev->pdev->dev,
"speed = %d, dev->gadget.speed = %d\n",
speed, dev->gadget.speed);
}
/* LPM L0 to L1 */
if (dev->lpm && dev->lpm_state == LPM_L0)
if (portsc1 & PORTS_SUSP && portsc1 & PORTS_SLP) {
dev_info(&dev->pdev->dev, "LPM L0 to L1\n");
dev->lpm_state = LPM_L1;
}
/* LPM L1 to L0, force resume or remote wakeup finished */
if (dev->lpm && dev->lpm_state == LPM_L1)
if (!(portsc1 & PORTS_SUSP)) {
dev_info(&dev->pdev->dev, "LPM L1 to L0\n");
dev->lpm_state = LPM_L0;
}
/* update USB state */
if (!dev->resume_state)
dev->usb_state = USB_STATE_DEFAULT;
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* USB reset interrupt handler */
static void handle_usb_reset(struct langwell_udc *dev)
{
u32 deviceaddr,
endptsetupstat,
endptcomplete;
unsigned long timeout;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
/* Write-Clear the device address */
deviceaddr = readl(&dev->op_regs->deviceaddr);
writel(deviceaddr & ~USBADR_MASK, &dev->op_regs->deviceaddr);
dev->dev_addr = 0;
/* clear usb state */
dev->resume_state = 0;
/* LPM L1 to L0, reset */
if (dev->lpm)
dev->lpm_state = LPM_L0;
dev->ep0_dir = USB_DIR_OUT;
dev->ep0_state = WAIT_FOR_SETUP;
/* remote wakeup reset to 0 when the device is reset */
dev->remote_wakeup = 0;
dev->dev_status = 1 << USB_DEVICE_SELF_POWERED;
dev->gadget.b_hnp_enable = 0;
dev->gadget.a_hnp_support = 0;
dev->gadget.a_alt_hnp_support = 0;
/* Write-Clear all the setup token semaphores */
endptsetupstat = readl(&dev->op_regs->endptsetupstat);
writel(endptsetupstat, &dev->op_regs->endptsetupstat);
/* Write-Clear all the endpoint complete status bits */
endptcomplete = readl(&dev->op_regs->endptcomplete);
writel(endptcomplete, &dev->op_regs->endptcomplete);
/* wait until all endptprime bits cleared */
timeout = jiffies + PRIME_TIMEOUT;
while (readl(&dev->op_regs->endptprime)) {
if (time_after(jiffies, timeout)) {
dev_err(&dev->pdev->dev, "USB reset timeout\n");
break;
}
cpu_relax();
}
/* write 1s to endptflush register to clear any primed buffers */
writel((u32) ~0, &dev->op_regs->endptflush);
if (readl(&dev->op_regs->portsc1) & PORTS_PR) {
dev_vdbg(&dev->pdev->dev, "USB bus reset\n");
/* bus is reseting */
dev->bus_reset = 1;
/* reset all the queues, stop all USB activities */
stop_activity(dev, dev->driver);
dev->usb_state = USB_STATE_DEFAULT;
} else {
dev_vdbg(&dev->pdev->dev, "device controller reset\n");
/* controller reset */
langwell_udc_reset(dev);
/* reset all the queues, stop all USB activities */
stop_activity(dev, dev->driver);
/* reset ep0 dQH and endptctrl */
ep0_reset(dev);
/* enable interrupt and set controller to run state */
langwell_udc_start(dev);
dev->usb_state = USB_STATE_ATTACHED;
}
#ifdef OTG_TRANSCEIVER
/* refer to USB OTG 6.6.2.3 b_hnp_en is cleared */
if (!dev->lotg->otg.default_a)
dev->lotg->hsm.b_hnp_enable = 0;
#endif
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* USB bus suspend/resume interrupt */
static void handle_bus_suspend(struct langwell_udc *dev)
{
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
dev->resume_state = dev->usb_state;
dev->usb_state = USB_STATE_SUSPENDED;
#ifdef OTG_TRANSCEIVER
if (dev->lotg->otg.default_a) {
if (dev->lotg->hsm.b_bus_suspend_vld == 1) {
dev->lotg->hsm.b_bus_suspend = 1;
/* notify transceiver the state changes */
if (spin_trylock(&dev->lotg->wq_lock)) {
langwell_update_transceiver();
spin_unlock(&dev->lotg->wq_lock);
}
}
dev->lotg->hsm.b_bus_suspend_vld++;
} else {
if (!dev->lotg->hsm.a_bus_suspend) {
dev->lotg->hsm.a_bus_suspend = 1;
/* notify transceiver the state changes */
if (spin_trylock(&dev->lotg->wq_lock)) {
langwell_update_transceiver();
spin_unlock(&dev->lotg->wq_lock);
}
}
}
#endif
/* report suspend to the driver */
if (dev->driver) {
if (dev->driver->suspend) {
spin_unlock(&dev->lock);
dev->driver->suspend(&dev->gadget);
spin_lock(&dev->lock);
dev_dbg(&dev->pdev->dev, "suspend %s\n",
dev->driver->driver.name);
}
}
/* enter PHY low power suspend */
if (dev->pdev->device != 0x0829)
langwell_phy_low_power(dev, 0);
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
static void handle_bus_resume(struct langwell_udc *dev)
{
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
dev->usb_state = dev->resume_state;
dev->resume_state = 0;
/* exit PHY low power suspend */
if (dev->pdev->device != 0x0829)
langwell_phy_low_power(dev, 0);
#ifdef OTG_TRANSCEIVER
if (dev->lotg->otg.default_a == 0)
dev->lotg->hsm.a_bus_suspend = 0;
#endif
/* report resume to the driver */
if (dev->driver) {
if (dev->driver->resume) {
spin_unlock(&dev->lock);
dev->driver->resume(&dev->gadget);
spin_lock(&dev->lock);
dev_dbg(&dev->pdev->dev, "resume %s\n",
dev->driver->driver.name);
}
}
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* USB device controller interrupt handler */
static irqreturn_t langwell_irq(int irq, void *_dev)
{
struct langwell_udc *dev = _dev;
u32 usbsts,
usbintr,
irq_sts,
portsc1;
dev_vdbg(&dev->pdev->dev, "---> %s()\n", __func__);
if (dev->stopped) {
dev_vdbg(&dev->pdev->dev, "handle IRQ_NONE\n");
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return IRQ_NONE;
}
spin_lock(&dev->lock);
/* USB status */
usbsts = readl(&dev->op_regs->usbsts);
/* USB interrupt enable */
usbintr = readl(&dev->op_regs->usbintr);
irq_sts = usbsts & usbintr;
dev_vdbg(&dev->pdev->dev,
"usbsts = 0x%08x, usbintr = 0x%08x, irq_sts = 0x%08x\n",
usbsts, usbintr, irq_sts);
if (!irq_sts) {
dev_vdbg(&dev->pdev->dev, "handle IRQ_NONE\n");
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
spin_unlock(&dev->lock);
return IRQ_NONE;
}
/* Write-Clear interrupt status bits */
writel(irq_sts, &dev->op_regs->usbsts);
/* resume from suspend */
portsc1 = readl(&dev->op_regs->portsc1);
if (dev->usb_state == USB_STATE_SUSPENDED)
if (!(portsc1 & PORTS_SUSP))
handle_bus_resume(dev);
/* USB interrupt */
if (irq_sts & STS_UI) {
dev_vdbg(&dev->pdev->dev, "USB interrupt\n");
/* setup packet received from ep0 */
if (readl(&dev->op_regs->endptsetupstat)
& EP0SETUPSTAT_MASK) {
dev_vdbg(&dev->pdev->dev,
"USB SETUP packet received interrupt\n");
/* setup tripwire semaphone */
setup_tripwire(dev);
handle_setup_packet(dev, &dev->local_setup_buff);
}
/* USB transfer completion */
if (readl(&dev->op_regs->endptcomplete)) {
dev_vdbg(&dev->pdev->dev,
"USB transfer completion interrupt\n");
handle_trans_complete(dev);
}
}
/* SOF received interrupt (for ISO transfer) */
if (irq_sts & STS_SRI) {
/* FIXME */
/* dev_vdbg(&dev->pdev->dev, "SOF received interrupt\n"); */
}
/* port change detect interrupt */
if (irq_sts & STS_PCI) {
dev_vdbg(&dev->pdev->dev, "port change detect interrupt\n");
handle_port_change(dev);
}
/* suspend interrrupt */
if (irq_sts & STS_SLI) {
dev_vdbg(&dev->pdev->dev, "suspend interrupt\n");
handle_bus_suspend(dev);
}
/* USB reset interrupt */
if (irq_sts & STS_URI) {
dev_vdbg(&dev->pdev->dev, "USB reset interrupt\n");
handle_usb_reset(dev);
}
/* USB error or system error interrupt */
if (irq_sts & (STS_UEI | STS_SEI)) {
/* FIXME */
dev_warn(&dev->pdev->dev, "error IRQ, irq_sts: %x\n", irq_sts);
}
spin_unlock(&dev->lock);
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return IRQ_HANDLED;
}
/*-------------------------------------------------------------------------*/
/* release device structure */
static void gadget_release(struct device *_dev)
{
struct langwell_udc *dev = the_controller;
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
complete(dev->done);
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
kfree(dev);
}
/* enable SRAM caching if SRAM detected */
static void sram_init(struct langwell_udc *dev)
{
struct pci_dev *pdev = dev->pdev;
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
dev->sram_addr = pci_resource_start(pdev, 1);
dev->sram_size = pci_resource_len(pdev, 1);
dev_info(&dev->pdev->dev, "Found private SRAM at %x size:%x\n",
dev->sram_addr, dev->sram_size);
dev->got_sram = 1;
if (pci_request_region(pdev, 1, kobject_name(&pdev->dev.kobj))) {
dev_warn(&dev->pdev->dev, "SRAM request failed\n");
dev->got_sram = 0;
} else if (!dma_declare_coherent_memory(&pdev->dev, dev->sram_addr,
dev->sram_addr, dev->sram_size, DMA_MEMORY_MAP)) {
dev_warn(&dev->pdev->dev, "SRAM DMA declare failed\n");
pci_release_region(pdev, 1);
dev->got_sram = 0;
}
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* release SRAM caching */
static void sram_deinit(struct langwell_udc *dev)
{
struct pci_dev *pdev = dev->pdev;
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
dma_release_declared_memory(&pdev->dev);
pci_release_region(pdev, 1);
dev->got_sram = 0;
dev_info(&dev->pdev->dev, "release SRAM caching\n");
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/* tear down the binding between this driver and the pci device */
static void langwell_udc_remove(struct pci_dev *pdev)
{
struct langwell_udc *dev = the_controller;
DECLARE_COMPLETION(done);
BUG_ON(dev->driver);
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
dev->done = &done;
#ifndef OTG_TRANSCEIVER
/* free dTD dma_pool and dQH */
if (dev->dtd_pool)
dma_pool_destroy(dev->dtd_pool);
if (dev->ep_dqh)
dma_free_coherent(&pdev->dev, dev->ep_dqh_size,
dev->ep_dqh, dev->ep_dqh_dma);
/* release SRAM caching */
if (dev->has_sram && dev->got_sram)
sram_deinit(dev);
#endif
if (dev->status_req) {
kfree(dev->status_req->req.buf);
kfree(dev->status_req);
}
kfree(dev->ep);
/* disable IRQ handler */
if (dev->got_irq)
free_irq(pdev->irq, dev);
#ifndef OTG_TRANSCEIVER
if (dev->cap_regs)
iounmap(dev->cap_regs);
if (dev->region)
release_mem_region(pci_resource_start(pdev, 0),
pci_resource_len(pdev, 0));
if (dev->enabled)
pci_disable_device(pdev);
#else
if (dev->transceiver) {
otg_put_transceiver(dev->transceiver);
dev->transceiver = NULL;
dev->lotg = NULL;
}
#endif
dev->cap_regs = NULL;
dev_info(&dev->pdev->dev, "unbind\n");
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
device_unregister(&dev->gadget.dev);
device_remove_file(&pdev->dev, &dev_attr_langwell_udc);
device_remove_file(&pdev->dev, &dev_attr_remote_wakeup);
#ifndef OTG_TRANSCEIVER
pci_set_drvdata(pdev, NULL);
#endif
/* free dev, wait for the release() finished */
wait_for_completion(&done);
the_controller = NULL;
}
/*
* wrap this driver around the specified device, but
* don't respond over USB until a gadget driver binds to us.
*/
static int langwell_udc_probe(struct pci_dev *pdev,
const struct pci_device_id *id)
{
struct langwell_udc *dev;
#ifndef OTG_TRANSCEIVER
unsigned long resource, len;
#endif
void __iomem *base = NULL;
size_t size;
int retval;
if (the_controller) {
dev_warn(&pdev->dev, "ignoring\n");
return -EBUSY;
}
/* alloc, and start init */
dev = kzalloc(sizeof *dev, GFP_KERNEL);
if (dev == NULL) {
retval = -ENOMEM;
goto error;
}
/* initialize device spinlock */
spin_lock_init(&dev->lock);
dev->pdev = pdev;
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
#ifdef OTG_TRANSCEIVER
/* PCI device is already enabled by otg_transceiver driver */
dev->enabled = 1;
/* mem region and register base */
dev->region = 1;
dev->transceiver = otg_get_transceiver();
dev->lotg = otg_to_langwell(dev->transceiver);
base = dev->lotg->regs;
#else
pci_set_drvdata(pdev, dev);
/* now all the pci goodies ... */
if (pci_enable_device(pdev) < 0) {
retval = -ENODEV;
goto error;
}
dev->enabled = 1;
/* control register: BAR 0 */
resource = pci_resource_start(pdev, 0);
len = pci_resource_len(pdev, 0);
if (!request_mem_region(resource, len, driver_name)) {
dev_err(&dev->pdev->dev, "controller already in use\n");
retval = -EBUSY;
goto error;
}
dev->region = 1;
base = ioremap_nocache(resource, len);
#endif
if (base == NULL) {
dev_err(&dev->pdev->dev, "can't map memory\n");
retval = -EFAULT;
goto error;
}
dev->cap_regs = (struct langwell_cap_regs __iomem *) base;
dev_vdbg(&dev->pdev->dev, "dev->cap_regs: %p\n", dev->cap_regs);
dev->op_regs = (struct langwell_op_regs __iomem *)
(base + OP_REG_OFFSET);
dev_vdbg(&dev->pdev->dev, "dev->op_regs: %p\n", dev->op_regs);
/* irq setup after old hardware is cleaned up */
if (!pdev->irq) {
dev_err(&dev->pdev->dev, "No IRQ. Check PCI setup!\n");
retval = -ENODEV;
goto error;
}
dev->has_sram = 1;
dev->got_sram = 0;
dev_vdbg(&dev->pdev->dev, "dev->has_sram: %d\n", dev->has_sram);
#ifndef OTG_TRANSCEIVER
/* enable SRAM caching if detected */
if (dev->has_sram && !dev->got_sram)
sram_init(dev);
dev_info(&dev->pdev->dev,
"irq %d, io mem: 0x%08lx, len: 0x%08lx, pci mem 0x%p\n",
pdev->irq, resource, len, base);
/* enables bus-mastering for device dev */
pci_set_master(pdev);
if (request_irq(pdev->irq, langwell_irq, IRQF_SHARED,
driver_name, dev) != 0) {
dev_err(&dev->pdev->dev,
"request interrupt %d failed\n", pdev->irq);
retval = -EBUSY;
goto error;
}
dev->got_irq = 1;
#endif
/* set stopped bit */
dev->stopped = 1;
/* capabilities and endpoint number */
dev->lpm = (readl(&dev->cap_regs->hccparams) & HCC_LEN) ? 1 : 0;
dev->dciversion = readw(&dev->cap_regs->dciversion);
dev->devcap = (readl(&dev->cap_regs->dccparams) & DEVCAP) ? 1 : 0;
dev_vdbg(&dev->pdev->dev, "dev->lpm: %d\n", dev->lpm);
dev_vdbg(&dev->pdev->dev, "dev->dciversion: 0x%04x\n",
dev->dciversion);
dev_vdbg(&dev->pdev->dev, "dccparams: 0x%08x\n",
readl(&dev->cap_regs->dccparams));
dev_vdbg(&dev->pdev->dev, "dev->devcap: %d\n", dev->devcap);
if (!dev->devcap) {
dev_err(&dev->pdev->dev, "can't support device mode\n");
retval = -ENODEV;
goto error;
}
/* a pair of endpoints (out/in) for each address */
dev->ep_max = DEN(readl(&dev->cap_regs->dccparams)) * 2;
dev_vdbg(&dev->pdev->dev, "dev->ep_max: %d\n", dev->ep_max);
/* allocate endpoints memory */
dev->ep = kzalloc(sizeof(struct langwell_ep) * dev->ep_max,
GFP_KERNEL);
if (!dev->ep) {
dev_err(&dev->pdev->dev, "allocate endpoints memory failed\n");
retval = -ENOMEM;
goto error;
}
/* allocate device dQH memory */
size = dev->ep_max * sizeof(struct langwell_dqh);
dev_vdbg(&dev->pdev->dev, "orig size = %zd\n", size);
if (size < DQH_ALIGNMENT)
size = DQH_ALIGNMENT;
else if ((size % DQH_ALIGNMENT) != 0) {
size += DQH_ALIGNMENT + 1;
size &= ~(DQH_ALIGNMENT - 1);
}
dev->ep_dqh = dma_alloc_coherent(&pdev->dev, size,
&dev->ep_dqh_dma, GFP_KERNEL);
if (!dev->ep_dqh) {
dev_err(&dev->pdev->dev, "allocate dQH memory failed\n");
retval = -ENOMEM;
goto error;
}
dev->ep_dqh_size = size;
dev_vdbg(&dev->pdev->dev, "ep_dqh_size = %zd\n", dev->ep_dqh_size);
/* initialize ep0 status request structure */
dev->status_req = kzalloc(sizeof(struct langwell_request), GFP_KERNEL);
if (!dev->status_req) {
dev_err(&dev->pdev->dev,
"allocate status_req memory failed\n");
retval = -ENOMEM;
goto error;
}
INIT_LIST_HEAD(&dev->status_req->queue);
/* allocate a small amount of memory to get valid address */
dev->status_req->req.buf = kmalloc(8, GFP_KERNEL);
dev->status_req->req.dma = virt_to_phys(dev->status_req->req.buf);
dev->resume_state = USB_STATE_NOTATTACHED;
dev->usb_state = USB_STATE_POWERED;
dev->ep0_dir = USB_DIR_OUT;
/* remote wakeup reset to 0 when the device is reset */
dev->remote_wakeup = 0;
dev->dev_status = 1 << USB_DEVICE_SELF_POWERED;
#ifndef OTG_TRANSCEIVER
/* reset device controller */
langwell_udc_reset(dev);
#endif
/* initialize gadget structure */
dev->gadget.ops = &langwell_ops; /* usb_gadget_ops */
dev->gadget.ep0 = &dev->ep[0].ep; /* gadget ep0 */
INIT_LIST_HEAD(&dev->gadget.ep_list); /* ep_list */
dev->gadget.speed = USB_SPEED_UNKNOWN; /* speed */
dev->gadget.is_dualspeed = 1; /* support dual speed */
#ifdef OTG_TRANSCEIVER
dev->gadget.is_otg = 1; /* support otg mode */
#endif
/* the "gadget" abstracts/virtualizes the controller */
dev_set_name(&dev->gadget.dev, "gadget");
dev->gadget.dev.parent = &pdev->dev;
dev->gadget.dev.dma_mask = pdev->dev.dma_mask;
dev->gadget.dev.release = gadget_release;
dev->gadget.name = driver_name; /* gadget name */
/* controller endpoints reinit */
eps_reinit(dev);
#ifndef OTG_TRANSCEIVER
/* reset ep0 dQH and endptctrl */
ep0_reset(dev);
#endif
/* create dTD dma_pool resource */
dev->dtd_pool = dma_pool_create("langwell_dtd",
&dev->pdev->dev,
sizeof(struct langwell_dtd),
DTD_ALIGNMENT,
DMA_BOUNDARY);
if (!dev->dtd_pool) {
retval = -ENOMEM;
goto error;
}
/* done */
dev_info(&dev->pdev->dev, "%s\n", driver_desc);
dev_info(&dev->pdev->dev, "irq %d, pci mem %p\n", pdev->irq, base);
dev_info(&dev->pdev->dev, "Driver version: " DRIVER_VERSION "\n");
dev_info(&dev->pdev->dev, "Support (max) %d endpoints\n", dev->ep_max);
dev_info(&dev->pdev->dev, "Device interface version: 0x%04x\n",
dev->dciversion);
dev_info(&dev->pdev->dev, "Controller mode: %s\n",
dev->devcap ? "Device" : "Host");
dev_info(&dev->pdev->dev, "Support USB LPM: %s\n",
dev->lpm ? "Yes" : "No");
dev_vdbg(&dev->pdev->dev,
"After langwell_udc_probe(), print all registers:\n");
print_all_registers(dev);
the_controller = dev;
retval = device_register(&dev->gadget.dev);
if (retval)
goto error;
retval = usb_add_gadget_udc(&pdev->dev, &dev->gadget);
if (retval)
goto error;
retval = device_create_file(&pdev->dev, &dev_attr_langwell_udc);
if (retval)
goto error;
retval = device_create_file(&pdev->dev, &dev_attr_remote_wakeup);
if (retval)
goto error_attr1;
dev_vdbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return 0;
error_attr1:
device_remove_file(&pdev->dev, &dev_attr_langwell_udc);
error:
if (dev) {
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
langwell_udc_remove(pdev);
}
return retval;
}
/* device controller suspend */
static int langwell_udc_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct langwell_udc *dev = the_controller;
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
usb_del_gadget_udc(&dev->gadget);
/* disable interrupt and set controller to stop state */
langwell_udc_stop(dev);
/* disable IRQ handler */
if (dev->got_irq)
free_irq(pdev->irq, dev);
dev->got_irq = 0;
/* save PCI state */
pci_save_state(pdev);
spin_lock_irq(&dev->lock);
/* stop all usb activities */
stop_activity(dev, dev->driver);
spin_unlock_irq(&dev->lock);
/* free dTD dma_pool and dQH */
if (dev->dtd_pool)
dma_pool_destroy(dev->dtd_pool);
if (dev->ep_dqh)
dma_free_coherent(&pdev->dev, dev->ep_dqh_size,
dev->ep_dqh, dev->ep_dqh_dma);
/* release SRAM caching */
if (dev->has_sram && dev->got_sram)
sram_deinit(dev);
/* set device power state */
pci_set_power_state(pdev, PCI_D3hot);
/* enter PHY low power suspend */
if (dev->pdev->device != 0x0829)
langwell_phy_low_power(dev, 1);
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return 0;
}
/* device controller resume */
static int langwell_udc_resume(struct pci_dev *pdev)
{
struct langwell_udc *dev = the_controller;
size_t size;
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
/* exit PHY low power suspend */
if (dev->pdev->device != 0x0829)
langwell_phy_low_power(dev, 0);
/* set device D0 power state */
pci_set_power_state(pdev, PCI_D0);
/* enable SRAM caching if detected */
if (dev->has_sram && !dev->got_sram)
sram_init(dev);
/* allocate device dQH memory */
size = dev->ep_max * sizeof(struct langwell_dqh);
dev_vdbg(&dev->pdev->dev, "orig size = %zd\n", size);
if (size < DQH_ALIGNMENT)
size = DQH_ALIGNMENT;
else if ((size % DQH_ALIGNMENT) != 0) {
size += DQH_ALIGNMENT + 1;
size &= ~(DQH_ALIGNMENT - 1);
}
dev->ep_dqh = dma_alloc_coherent(&pdev->dev, size,
&dev->ep_dqh_dma, GFP_KERNEL);
if (!dev->ep_dqh) {
dev_err(&dev->pdev->dev, "allocate dQH memory failed\n");
return -ENOMEM;
}
dev->ep_dqh_size = size;
dev_vdbg(&dev->pdev->dev, "ep_dqh_size = %zd\n", dev->ep_dqh_size);
/* create dTD dma_pool resource */
dev->dtd_pool = dma_pool_create("langwell_dtd",
&dev->pdev->dev,
sizeof(struct langwell_dtd),
DTD_ALIGNMENT,
DMA_BOUNDARY);
if (!dev->dtd_pool)
return -ENOMEM;
/* restore PCI state */
pci_restore_state(pdev);
/* enable IRQ handler */
if (request_irq(pdev->irq, langwell_irq, IRQF_SHARED,
driver_name, dev) != 0) {
dev_err(&dev->pdev->dev, "request interrupt %d failed\n",
pdev->irq);
return -EBUSY;
}
dev->got_irq = 1;
/* reset and start controller to run state */
if (dev->stopped) {
/* reset device controller */
langwell_udc_reset(dev);
/* reset ep0 dQH and endptctrl */
ep0_reset(dev);
/* start device if gadget is loaded */
if (dev->driver)
langwell_udc_start(dev);
}
/* reset USB status */
dev->usb_state = USB_STATE_ATTACHED;
dev->ep0_state = WAIT_FOR_SETUP;
dev->ep0_dir = USB_DIR_OUT;
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
return 0;
}
/* pci driver shutdown */
static void langwell_udc_shutdown(struct pci_dev *pdev)
{
struct langwell_udc *dev = the_controller;
u32 usbmode;
dev_dbg(&dev->pdev->dev, "---> %s()\n", __func__);
/* reset controller mode to IDLE */
usbmode = readl(&dev->op_regs->usbmode);
dev_dbg(&dev->pdev->dev, "usbmode = 0x%08x\n", usbmode);
usbmode &= (~3 | MODE_IDLE);
writel(usbmode, &dev->op_regs->usbmode);
dev_dbg(&dev->pdev->dev, "<--- %s()\n", __func__);
}
/*-------------------------------------------------------------------------*/
static const struct pci_device_id pci_ids[] = { {
.class = ((PCI_CLASS_SERIAL_USB << 8) | 0xfe),
.class_mask = ~0,
.vendor = 0x8086,
.device = 0x0811,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
}, { /* end: all zeroes */ }
};
MODULE_DEVICE_TABLE(pci, pci_ids);
static struct pci_driver langwell_pci_driver = {
.name = (char *) driver_name,
.id_table = pci_ids,
.probe = langwell_udc_probe,
.remove = langwell_udc_remove,
/* device controller suspend/resume */
.suspend = langwell_udc_suspend,
.resume = langwell_udc_resume,
.shutdown = langwell_udc_shutdown,
};
static int __init init(void)
{
#ifdef OTG_TRANSCEIVER
return langwell_register_peripheral(&langwell_pci_driver);
#else
return pci_register_driver(&langwell_pci_driver);
#endif
}
module_init(init);
static void __exit cleanup(void)
{
#ifdef OTG_TRANSCEIVER
return langwell_unregister_peripheral(&langwell_pci_driver);
#else
pci_unregister_driver(&langwell_pci_driver);
#endif
}
module_exit(cleanup);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_AUTHOR("Xiaochen Shen <xiaochen.shen@intel.com>");
MODULE_VERSION(DRIVER_VERSION);
MODULE_LICENSE("GPL");
| gpl-2.0 |
lathiat/linux | drivers/net/ethernet/intel/fm10k/fm10k_pci.c | 386 | 59305 | /* Intel Ethernet Switch Host Interface Driver
* Copyright(c) 2013 - 2015 Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* The full GNU General Public License is included in this distribution in
* the file called "COPYING".
*
* Contact Information:
* e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*/
#include <linux/module.h>
#include <linux/aer.h>
#include "fm10k.h"
static const struct fm10k_info *fm10k_info_tbl[] = {
[fm10k_device_pf] = &fm10k_pf_info,
[fm10k_device_vf] = &fm10k_vf_info,
};
/**
* fm10k_pci_tbl - PCI Device ID Table
*
* Wildcard entries (PCI_ANY_ID) should come last
* Last entry must be all 0s
*
* { Vendor ID, Device ID, SubVendor ID, SubDevice ID,
* Class, Class Mask, private data (not used) }
*/
static const struct pci_device_id fm10k_pci_tbl[] = {
{ PCI_VDEVICE(INTEL, FM10K_DEV_ID_PF), fm10k_device_pf },
{ PCI_VDEVICE(INTEL, FM10K_DEV_ID_VF), fm10k_device_vf },
/* required last entry */
{ 0, }
};
MODULE_DEVICE_TABLE(pci, fm10k_pci_tbl);
u16 fm10k_read_pci_cfg_word(struct fm10k_hw *hw, u32 reg)
{
struct fm10k_intfc *interface = hw->back;
u16 value = 0;
if (FM10K_REMOVED(hw->hw_addr))
return ~value;
pci_read_config_word(interface->pdev, reg, &value);
if (value == 0xFFFF)
fm10k_write_flush(hw);
return value;
}
u32 fm10k_read_reg(struct fm10k_hw *hw, int reg)
{
u32 __iomem *hw_addr = ACCESS_ONCE(hw->hw_addr);
u32 value = 0;
if (FM10K_REMOVED(hw_addr))
return ~value;
value = readl(&hw_addr[reg]);
if (!(~value) && (!reg || !(~readl(hw_addr)))) {
struct fm10k_intfc *interface = hw->back;
struct net_device *netdev = interface->netdev;
hw->hw_addr = NULL;
netif_device_detach(netdev);
netdev_err(netdev, "PCIe link lost, device now detached\n");
}
return value;
}
static int fm10k_hw_ready(struct fm10k_intfc *interface)
{
struct fm10k_hw *hw = &interface->hw;
fm10k_write_flush(hw);
return FM10K_REMOVED(hw->hw_addr) ? -ENODEV : 0;
}
void fm10k_service_event_schedule(struct fm10k_intfc *interface)
{
if (!test_bit(__FM10K_SERVICE_DISABLE, &interface->state) &&
!test_and_set_bit(__FM10K_SERVICE_SCHED, &interface->state))
queue_work(fm10k_workqueue, &interface->service_task);
}
static void fm10k_service_event_complete(struct fm10k_intfc *interface)
{
BUG_ON(!test_bit(__FM10K_SERVICE_SCHED, &interface->state));
/* flush memory to make sure state is correct before next watchog */
smp_mb__before_atomic();
clear_bit(__FM10K_SERVICE_SCHED, &interface->state);
}
/**
* fm10k_service_timer - Timer Call-back
* @data: pointer to interface cast into an unsigned long
**/
static void fm10k_service_timer(unsigned long data)
{
struct fm10k_intfc *interface = (struct fm10k_intfc *)data;
/* Reset the timer */
mod_timer(&interface->service_timer, (HZ * 2) + jiffies);
fm10k_service_event_schedule(interface);
}
static void fm10k_detach_subtask(struct fm10k_intfc *interface)
{
struct net_device *netdev = interface->netdev;
/* do nothing if device is still present or hw_addr is set */
if (netif_device_present(netdev) || interface->hw.hw_addr)
return;
rtnl_lock();
if (netif_running(netdev))
dev_close(netdev);
rtnl_unlock();
}
static void fm10k_reinit(struct fm10k_intfc *interface)
{
struct net_device *netdev = interface->netdev;
struct fm10k_hw *hw = &interface->hw;
int err;
WARN_ON(in_interrupt());
/* put off any impending NetWatchDogTimeout */
netdev->trans_start = jiffies;
while (test_and_set_bit(__FM10K_RESETTING, &interface->state))
usleep_range(1000, 2000);
rtnl_lock();
fm10k_iov_suspend(interface->pdev);
if (netif_running(netdev))
fm10k_close(netdev);
fm10k_mbx_free_irq(interface);
/* delay any future reset requests */
interface->last_reset = jiffies + (10 * HZ);
/* reset and initialize the hardware so it is in a known state */
err = hw->mac.ops.reset_hw(hw) ? : hw->mac.ops.init_hw(hw);
if (err)
dev_err(&interface->pdev->dev, "init_hw failed: %d\n", err);
/* reassociate interrupts */
fm10k_mbx_request_irq(interface);
/* reset clock */
fm10k_ts_reset(interface);
if (netif_running(netdev))
fm10k_open(netdev);
fm10k_iov_resume(interface->pdev);
rtnl_unlock();
clear_bit(__FM10K_RESETTING, &interface->state);
}
static void fm10k_reset_subtask(struct fm10k_intfc *interface)
{
if (!(interface->flags & FM10K_FLAG_RESET_REQUESTED))
return;
interface->flags &= ~FM10K_FLAG_RESET_REQUESTED;
netdev_err(interface->netdev, "Reset interface\n");
fm10k_reinit(interface);
}
/**
* fm10k_configure_swpri_map - Configure Receive SWPRI to PC mapping
* @interface: board private structure
*
* Configure the SWPRI to PC mapping for the port.
**/
static void fm10k_configure_swpri_map(struct fm10k_intfc *interface)
{
struct net_device *netdev = interface->netdev;
struct fm10k_hw *hw = &interface->hw;
int i;
/* clear flag indicating update is needed */
interface->flags &= ~FM10K_FLAG_SWPRI_CONFIG;
/* these registers are only available on the PF */
if (hw->mac.type != fm10k_mac_pf)
return;
/* configure SWPRI to PC map */
for (i = 0; i < FM10K_SWPRI_MAX; i++)
fm10k_write_reg(hw, FM10K_SWPRI_MAP(i),
netdev_get_prio_tc_map(netdev, i));
}
/**
* fm10k_watchdog_update_host_state - Update the link status based on host.
* @interface: board private structure
**/
static void fm10k_watchdog_update_host_state(struct fm10k_intfc *interface)
{
struct fm10k_hw *hw = &interface->hw;
s32 err;
if (test_bit(__FM10K_LINK_DOWN, &interface->state)) {
interface->host_ready = false;
if (time_is_after_jiffies(interface->link_down_event))
return;
clear_bit(__FM10K_LINK_DOWN, &interface->state);
}
if (interface->flags & FM10K_FLAG_SWPRI_CONFIG) {
if (rtnl_trylock()) {
fm10k_configure_swpri_map(interface);
rtnl_unlock();
}
}
/* lock the mailbox for transmit and receive */
fm10k_mbx_lock(interface);
err = hw->mac.ops.get_host_state(hw, &interface->host_ready);
if (err && time_is_before_jiffies(interface->last_reset))
interface->flags |= FM10K_FLAG_RESET_REQUESTED;
/* free the lock */
fm10k_mbx_unlock(interface);
}
/**
* fm10k_mbx_subtask - Process upstream and downstream mailboxes
* @interface: board private structure
*
* This function will process both the upstream and downstream mailboxes.
* It is necessary for us to hold the rtnl_lock while doing this as the
* mailbox accesses are protected by this lock.
**/
static void fm10k_mbx_subtask(struct fm10k_intfc *interface)
{
/* process upstream mailbox and update device state */
fm10k_watchdog_update_host_state(interface);
/* process downstream mailboxes */
fm10k_iov_mbx(interface);
}
/**
* fm10k_watchdog_host_is_ready - Update netdev status based on host ready
* @interface: board private structure
**/
static void fm10k_watchdog_host_is_ready(struct fm10k_intfc *interface)
{
struct net_device *netdev = interface->netdev;
/* only continue if link state is currently down */
if (netif_carrier_ok(netdev))
return;
netif_info(interface, drv, netdev, "NIC Link is up\n");
netif_carrier_on(netdev);
netif_tx_wake_all_queues(netdev);
}
/**
* fm10k_watchdog_host_not_ready - Update netdev status based on host not ready
* @interface: board private structure
**/
static void fm10k_watchdog_host_not_ready(struct fm10k_intfc *interface)
{
struct net_device *netdev = interface->netdev;
/* only continue if link state is currently up */
if (!netif_carrier_ok(netdev))
return;
netif_info(interface, drv, netdev, "NIC Link is down\n");
netif_carrier_off(netdev);
netif_tx_stop_all_queues(netdev);
}
/**
* fm10k_update_stats - Update the board statistics counters.
* @interface: board private structure
**/
void fm10k_update_stats(struct fm10k_intfc *interface)
{
struct net_device_stats *net_stats = &interface->netdev->stats;
struct fm10k_hw *hw = &interface->hw;
u64 rx_errors = 0, rx_csum_errors = 0, tx_csum_errors = 0;
u64 restart_queue = 0, tx_busy = 0, alloc_failed = 0;
u64 rx_bytes_nic = 0, rx_pkts_nic = 0, rx_drops_nic = 0;
u64 tx_bytes_nic = 0, tx_pkts_nic = 0;
u64 bytes, pkts;
int i;
/* do not allow stats update via service task for next second */
interface->next_stats_update = jiffies + HZ;
/* gather some stats to the interface struct that are per queue */
for (bytes = 0, pkts = 0, i = 0; i < interface->num_tx_queues; i++) {
struct fm10k_ring *tx_ring = interface->tx_ring[i];
restart_queue += tx_ring->tx_stats.restart_queue;
tx_busy += tx_ring->tx_stats.tx_busy;
tx_csum_errors += tx_ring->tx_stats.csum_err;
bytes += tx_ring->stats.bytes;
pkts += tx_ring->stats.packets;
}
interface->restart_queue = restart_queue;
interface->tx_busy = tx_busy;
net_stats->tx_bytes = bytes;
net_stats->tx_packets = pkts;
interface->tx_csum_errors = tx_csum_errors;
/* gather some stats to the interface struct that are per queue */
for (bytes = 0, pkts = 0, i = 0; i < interface->num_rx_queues; i++) {
struct fm10k_ring *rx_ring = interface->rx_ring[i];
bytes += rx_ring->stats.bytes;
pkts += rx_ring->stats.packets;
alloc_failed += rx_ring->rx_stats.alloc_failed;
rx_csum_errors += rx_ring->rx_stats.csum_err;
rx_errors += rx_ring->rx_stats.errors;
}
net_stats->rx_bytes = bytes;
net_stats->rx_packets = pkts;
interface->alloc_failed = alloc_failed;
interface->rx_csum_errors = rx_csum_errors;
hw->mac.ops.update_hw_stats(hw, &interface->stats);
for (i = 0; i < hw->mac.max_queues; i++) {
struct fm10k_hw_stats_q *q = &interface->stats.q[i];
tx_bytes_nic += q->tx_bytes.count;
tx_pkts_nic += q->tx_packets.count;
rx_bytes_nic += q->rx_bytes.count;
rx_pkts_nic += q->rx_packets.count;
rx_drops_nic += q->rx_drops.count;
}
interface->tx_bytes_nic = tx_bytes_nic;
interface->tx_packets_nic = tx_pkts_nic;
interface->rx_bytes_nic = rx_bytes_nic;
interface->rx_packets_nic = rx_pkts_nic;
interface->rx_drops_nic = rx_drops_nic;
/* Fill out the OS statistics structure */
net_stats->rx_errors = rx_errors;
net_stats->rx_dropped = interface->stats.nodesc_drop.count;
}
/**
* fm10k_watchdog_flush_tx - flush queues on host not ready
* @interface - pointer to the device interface structure
**/
static void fm10k_watchdog_flush_tx(struct fm10k_intfc *interface)
{
int some_tx_pending = 0;
int i;
/* nothing to do if carrier is up */
if (netif_carrier_ok(interface->netdev))
return;
for (i = 0; i < interface->num_tx_queues; i++) {
struct fm10k_ring *tx_ring = interface->tx_ring[i];
if (tx_ring->next_to_use != tx_ring->next_to_clean) {
some_tx_pending = 1;
break;
}
}
/* We've lost link, so the controller stops DMA, but we've got
* queued Tx work that's never going to get done, so reset
* controller to flush Tx.
*/
if (some_tx_pending)
interface->flags |= FM10K_FLAG_RESET_REQUESTED;
}
/**
* fm10k_watchdog_subtask - check and bring link up
* @interface - pointer to the device interface structure
**/
static void fm10k_watchdog_subtask(struct fm10k_intfc *interface)
{
/* if interface is down do nothing */
if (test_bit(__FM10K_DOWN, &interface->state) ||
test_bit(__FM10K_RESETTING, &interface->state))
return;
if (interface->host_ready)
fm10k_watchdog_host_is_ready(interface);
else
fm10k_watchdog_host_not_ready(interface);
/* update stats only once every second */
if (time_is_before_jiffies(interface->next_stats_update))
fm10k_update_stats(interface);
/* flush any uncompleted work */
fm10k_watchdog_flush_tx(interface);
}
/**
* fm10k_check_hang_subtask - check for hung queues and dropped interrupts
* @interface - pointer to the device interface structure
*
* This function serves two purposes. First it strobes the interrupt lines
* in order to make certain interrupts are occurring. Secondly it sets the
* bits needed to check for TX hangs. As a result we should immediately
* determine if a hang has occurred.
*/
static void fm10k_check_hang_subtask(struct fm10k_intfc *interface)
{
int i;
/* If we're down or resetting, just bail */
if (test_bit(__FM10K_DOWN, &interface->state) ||
test_bit(__FM10K_RESETTING, &interface->state))
return;
/* rate limit tx hang checks to only once every 2 seconds */
if (time_is_after_eq_jiffies(interface->next_tx_hang_check))
return;
interface->next_tx_hang_check = jiffies + (2 * HZ);
if (netif_carrier_ok(interface->netdev)) {
/* Force detection of hung controller */
for (i = 0; i < interface->num_tx_queues; i++)
set_check_for_tx_hang(interface->tx_ring[i]);
/* Rearm all in-use q_vectors for immediate firing */
for (i = 0; i < interface->num_q_vectors; i++) {
struct fm10k_q_vector *qv = interface->q_vector[i];
if (!qv->tx.count && !qv->rx.count)
continue;
writel(FM10K_ITR_ENABLE | FM10K_ITR_PENDING2, qv->itr);
}
}
}
/**
* fm10k_service_task - manages and runs subtasks
* @work: pointer to work_struct containing our data
**/
static void fm10k_service_task(struct work_struct *work)
{
struct fm10k_intfc *interface;
interface = container_of(work, struct fm10k_intfc, service_task);
/* tasks always capable of running, but must be rtnl protected */
fm10k_mbx_subtask(interface);
fm10k_detach_subtask(interface);
fm10k_reset_subtask(interface);
/* tasks only run when interface is up */
fm10k_watchdog_subtask(interface);
fm10k_check_hang_subtask(interface);
fm10k_ts_tx_subtask(interface);
/* release lock on service events to allow scheduling next event */
fm10k_service_event_complete(interface);
}
/**
* fm10k_configure_tx_ring - Configure Tx ring after Reset
* @interface: board private structure
* @ring: structure containing ring specific data
*
* Configure the Tx descriptor ring after a reset.
**/
static void fm10k_configure_tx_ring(struct fm10k_intfc *interface,
struct fm10k_ring *ring)
{
struct fm10k_hw *hw = &interface->hw;
u64 tdba = ring->dma;
u32 size = ring->count * sizeof(struct fm10k_tx_desc);
u32 txint = FM10K_INT_MAP_DISABLE;
u32 txdctl = FM10K_TXDCTL_ENABLE | (1 << FM10K_TXDCTL_MAX_TIME_SHIFT);
u8 reg_idx = ring->reg_idx;
/* disable queue to avoid issues while updating state */
fm10k_write_reg(hw, FM10K_TXDCTL(reg_idx), 0);
fm10k_write_flush(hw);
/* possible poll here to verify ring resources have been cleaned */
/* set location and size for descriptor ring */
fm10k_write_reg(hw, FM10K_TDBAL(reg_idx), tdba & DMA_BIT_MASK(32));
fm10k_write_reg(hw, FM10K_TDBAH(reg_idx), tdba >> 32);
fm10k_write_reg(hw, FM10K_TDLEN(reg_idx), size);
/* reset head and tail pointers */
fm10k_write_reg(hw, FM10K_TDH(reg_idx), 0);
fm10k_write_reg(hw, FM10K_TDT(reg_idx), 0);
/* store tail pointer */
ring->tail = &interface->uc_addr[FM10K_TDT(reg_idx)];
/* reset ntu and ntc to place SW in sync with hardwdare */
ring->next_to_clean = 0;
ring->next_to_use = 0;
/* Map interrupt */
if (ring->q_vector) {
txint = ring->q_vector->v_idx + NON_Q_VECTORS(hw);
txint |= FM10K_INT_MAP_TIMER0;
}
fm10k_write_reg(hw, FM10K_TXINT(reg_idx), txint);
/* enable use of FTAG bit in Tx descriptor, register is RO for VF */
fm10k_write_reg(hw, FM10K_PFVTCTL(reg_idx),
FM10K_PFVTCTL_FTAG_DESC_ENABLE);
/* enable queue */
fm10k_write_reg(hw, FM10K_TXDCTL(reg_idx), txdctl);
}
/**
* fm10k_enable_tx_ring - Verify Tx ring is enabled after configuration
* @interface: board private structure
* @ring: structure containing ring specific data
*
* Verify the Tx descriptor ring is ready for transmit.
**/
static void fm10k_enable_tx_ring(struct fm10k_intfc *interface,
struct fm10k_ring *ring)
{
struct fm10k_hw *hw = &interface->hw;
int wait_loop = 10;
u32 txdctl;
u8 reg_idx = ring->reg_idx;
/* if we are already enabled just exit */
if (fm10k_read_reg(hw, FM10K_TXDCTL(reg_idx)) & FM10K_TXDCTL_ENABLE)
return;
/* poll to verify queue is enabled */
do {
usleep_range(1000, 2000);
txdctl = fm10k_read_reg(hw, FM10K_TXDCTL(reg_idx));
} while (!(txdctl & FM10K_TXDCTL_ENABLE) && --wait_loop);
if (!wait_loop)
netif_err(interface, drv, interface->netdev,
"Could not enable Tx Queue %d\n", reg_idx);
}
/**
* fm10k_configure_tx - Configure Transmit Unit after Reset
* @interface: board private structure
*
* Configure the Tx unit of the MAC after a reset.
**/
static void fm10k_configure_tx(struct fm10k_intfc *interface)
{
int i;
/* Setup the HW Tx Head and Tail descriptor pointers */
for (i = 0; i < interface->num_tx_queues; i++)
fm10k_configure_tx_ring(interface, interface->tx_ring[i]);
/* poll here to verify that Tx rings are now enabled */
for (i = 0; i < interface->num_tx_queues; i++)
fm10k_enable_tx_ring(interface, interface->tx_ring[i]);
}
/**
* fm10k_configure_rx_ring - Configure Rx ring after Reset
* @interface: board private structure
* @ring: structure containing ring specific data
*
* Configure the Rx descriptor ring after a reset.
**/
static void fm10k_configure_rx_ring(struct fm10k_intfc *interface,
struct fm10k_ring *ring)
{
u64 rdba = ring->dma;
struct fm10k_hw *hw = &interface->hw;
u32 size = ring->count * sizeof(union fm10k_rx_desc);
u32 rxqctl = FM10K_RXQCTL_ENABLE | FM10K_RXQCTL_PF;
u32 rxdctl = FM10K_RXDCTL_WRITE_BACK_MIN_DELAY;
u32 srrctl = FM10K_SRRCTL_BUFFER_CHAINING_EN;
u32 rxint = FM10K_INT_MAP_DISABLE;
u8 rx_pause = interface->rx_pause;
u8 reg_idx = ring->reg_idx;
/* disable queue to avoid issues while updating state */
fm10k_write_reg(hw, FM10K_RXQCTL(reg_idx), 0);
fm10k_write_flush(hw);
/* possible poll here to verify ring resources have been cleaned */
/* set location and size for descriptor ring */
fm10k_write_reg(hw, FM10K_RDBAL(reg_idx), rdba & DMA_BIT_MASK(32));
fm10k_write_reg(hw, FM10K_RDBAH(reg_idx), rdba >> 32);
fm10k_write_reg(hw, FM10K_RDLEN(reg_idx), size);
/* reset head and tail pointers */
fm10k_write_reg(hw, FM10K_RDH(reg_idx), 0);
fm10k_write_reg(hw, FM10K_RDT(reg_idx), 0);
/* store tail pointer */
ring->tail = &interface->uc_addr[FM10K_RDT(reg_idx)];
/* reset ntu and ntc to place SW in sync with hardwdare */
ring->next_to_clean = 0;
ring->next_to_use = 0;
ring->next_to_alloc = 0;
/* Configure the Rx buffer size for one buff without split */
srrctl |= FM10K_RX_BUFSZ >> FM10K_SRRCTL_BSIZEPKT_SHIFT;
/* Configure the Rx ring to suppress loopback packets */
srrctl |= FM10K_SRRCTL_LOOPBACK_SUPPRESS;
fm10k_write_reg(hw, FM10K_SRRCTL(reg_idx), srrctl);
/* Enable drop on empty */
#ifdef CONFIG_DCB
if (interface->pfc_en)
rx_pause = interface->pfc_en;
#endif
if (!(rx_pause & (1 << ring->qos_pc)))
rxdctl |= FM10K_RXDCTL_DROP_ON_EMPTY;
fm10k_write_reg(hw, FM10K_RXDCTL(reg_idx), rxdctl);
/* assign default VLAN to queue */
ring->vid = hw->mac.default_vid;
/* Map interrupt */
if (ring->q_vector) {
rxint = ring->q_vector->v_idx + NON_Q_VECTORS(hw);
rxint |= FM10K_INT_MAP_TIMER1;
}
fm10k_write_reg(hw, FM10K_RXINT(reg_idx), rxint);
/* enable queue */
fm10k_write_reg(hw, FM10K_RXQCTL(reg_idx), rxqctl);
/* place buffers on ring for receive data */
fm10k_alloc_rx_buffers(ring, fm10k_desc_unused(ring));
}
/**
* fm10k_update_rx_drop_en - Configures the drop enable bits for Rx rings
* @interface: board private structure
*
* Configure the drop enable bits for the Rx rings.
**/
void fm10k_update_rx_drop_en(struct fm10k_intfc *interface)
{
struct fm10k_hw *hw = &interface->hw;
u8 rx_pause = interface->rx_pause;
int i;
#ifdef CONFIG_DCB
if (interface->pfc_en)
rx_pause = interface->pfc_en;
#endif
for (i = 0; i < interface->num_rx_queues; i++) {
struct fm10k_ring *ring = interface->rx_ring[i];
u32 rxdctl = FM10K_RXDCTL_WRITE_BACK_MIN_DELAY;
u8 reg_idx = ring->reg_idx;
if (!(rx_pause & (1 << ring->qos_pc)))
rxdctl |= FM10K_RXDCTL_DROP_ON_EMPTY;
fm10k_write_reg(hw, FM10K_RXDCTL(reg_idx), rxdctl);
}
}
/**
* fm10k_configure_dglort - Configure Receive DGLORT after reset
* @interface: board private structure
*
* Configure the DGLORT description and RSS tables.
**/
static void fm10k_configure_dglort(struct fm10k_intfc *interface)
{
struct fm10k_dglort_cfg dglort = { 0 };
struct fm10k_hw *hw = &interface->hw;
int i;
u32 mrqc;
/* Fill out hash function seeds */
for (i = 0; i < FM10K_RSSRK_SIZE; i++)
fm10k_write_reg(hw, FM10K_RSSRK(0, i), interface->rssrk[i]);
/* Write RETA table to hardware */
for (i = 0; i < FM10K_RETA_SIZE; i++)
fm10k_write_reg(hw, FM10K_RETA(0, i), interface->reta[i]);
/* Generate RSS hash based on packet types, TCP/UDP
* port numbers and/or IPv4/v6 src and dst addresses
*/
mrqc = FM10K_MRQC_IPV4 |
FM10K_MRQC_TCP_IPV4 |
FM10K_MRQC_IPV6 |
FM10K_MRQC_TCP_IPV6;
if (interface->flags & FM10K_FLAG_RSS_FIELD_IPV4_UDP)
mrqc |= FM10K_MRQC_UDP_IPV4;
if (interface->flags & FM10K_FLAG_RSS_FIELD_IPV6_UDP)
mrqc |= FM10K_MRQC_UDP_IPV6;
fm10k_write_reg(hw, FM10K_MRQC(0), mrqc);
/* configure default DGLORT mapping for RSS/DCB */
dglort.inner_rss = 1;
dglort.rss_l = fls(interface->ring_feature[RING_F_RSS].mask);
dglort.pc_l = fls(interface->ring_feature[RING_F_QOS].mask);
hw->mac.ops.configure_dglort_map(hw, &dglort);
/* assign GLORT per queue for queue mapped testing */
if (interface->glort_count > 64) {
memset(&dglort, 0, sizeof(dglort));
dglort.inner_rss = 1;
dglort.glort = interface->glort + 64;
dglort.idx = fm10k_dglort_pf_queue;
dglort.queue_l = fls(interface->num_rx_queues - 1);
hw->mac.ops.configure_dglort_map(hw, &dglort);
}
/* assign glort value for RSS/DCB specific to this interface */
memset(&dglort, 0, sizeof(dglort));
dglort.inner_rss = 1;
dglort.glort = interface->glort;
dglort.rss_l = fls(interface->ring_feature[RING_F_RSS].mask);
dglort.pc_l = fls(interface->ring_feature[RING_F_QOS].mask);
/* configure DGLORT mapping for RSS/DCB */
dglort.idx = fm10k_dglort_pf_rss;
if (interface->l2_accel)
dglort.shared_l = fls(interface->l2_accel->size);
hw->mac.ops.configure_dglort_map(hw, &dglort);
}
/**
* fm10k_configure_rx - Configure Receive Unit after Reset
* @interface: board private structure
*
* Configure the Rx unit of the MAC after a reset.
**/
static void fm10k_configure_rx(struct fm10k_intfc *interface)
{
int i;
/* Configure SWPRI to PC map */
fm10k_configure_swpri_map(interface);
/* Configure RSS and DGLORT map */
fm10k_configure_dglort(interface);
/* Setup the HW Rx Head and Tail descriptor pointers */
for (i = 0; i < interface->num_rx_queues; i++)
fm10k_configure_rx_ring(interface, interface->rx_ring[i]);
/* possible poll here to verify that Rx rings are now enabled */
}
static void fm10k_napi_enable_all(struct fm10k_intfc *interface)
{
struct fm10k_q_vector *q_vector;
int q_idx;
for (q_idx = 0; q_idx < interface->num_q_vectors; q_idx++) {
q_vector = interface->q_vector[q_idx];
napi_enable(&q_vector->napi);
}
}
static irqreturn_t fm10k_msix_clean_rings(int __always_unused irq, void *data)
{
struct fm10k_q_vector *q_vector = data;
if (q_vector->rx.count || q_vector->tx.count)
napi_schedule(&q_vector->napi);
return IRQ_HANDLED;
}
static irqreturn_t fm10k_msix_mbx_vf(int __always_unused irq, void *data)
{
struct fm10k_intfc *interface = data;
struct fm10k_hw *hw = &interface->hw;
struct fm10k_mbx_info *mbx = &hw->mbx;
/* re-enable mailbox interrupt and indicate 20us delay */
fm10k_write_reg(hw, FM10K_VFITR(FM10K_MBX_VECTOR),
FM10K_ITR_ENABLE | FM10K_MBX_INT_DELAY);
/* service upstream mailbox */
if (fm10k_mbx_trylock(interface)) {
mbx->ops.process(hw, mbx);
fm10k_mbx_unlock(interface);
}
hw->mac.get_host_state = 1;
fm10k_service_event_schedule(interface);
return IRQ_HANDLED;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/**
* fm10k_netpoll - A Polling 'interrupt' handler
* @netdev: network interface device structure
*
* This is used by netconsole to send skbs without having to re-enable
* interrupts. It's not called while the normal interrupt routine is executing.
**/
void fm10k_netpoll(struct net_device *netdev)
{
struct fm10k_intfc *interface = netdev_priv(netdev);
int i;
/* if interface is down do nothing */
if (test_bit(__FM10K_DOWN, &interface->state))
return;
for (i = 0; i < interface->num_q_vectors; i++)
fm10k_msix_clean_rings(0, interface->q_vector[i]);
}
#endif
#define FM10K_ERR_MSG(type) case (type): error = #type; break
static void fm10k_print_fault(struct fm10k_intfc *interface, int type,
struct fm10k_fault *fault)
{
struct pci_dev *pdev = interface->pdev;
char *error;
switch (type) {
case FM10K_PCA_FAULT:
switch (fault->type) {
default:
error = "Unknown PCA error";
break;
FM10K_ERR_MSG(PCA_NO_FAULT);
FM10K_ERR_MSG(PCA_UNMAPPED_ADDR);
FM10K_ERR_MSG(PCA_BAD_QACCESS_PF);
FM10K_ERR_MSG(PCA_BAD_QACCESS_VF);
FM10K_ERR_MSG(PCA_MALICIOUS_REQ);
FM10K_ERR_MSG(PCA_POISONED_TLP);
FM10K_ERR_MSG(PCA_TLP_ABORT);
}
break;
case FM10K_THI_FAULT:
switch (fault->type) {
default:
error = "Unknown THI error";
break;
FM10K_ERR_MSG(THI_NO_FAULT);
FM10K_ERR_MSG(THI_MAL_DIS_Q_FAULT);
}
break;
case FM10K_FUM_FAULT:
switch (fault->type) {
default:
error = "Unknown FUM error";
break;
FM10K_ERR_MSG(FUM_NO_FAULT);
FM10K_ERR_MSG(FUM_UNMAPPED_ADDR);
FM10K_ERR_MSG(FUM_BAD_VF_QACCESS);
FM10K_ERR_MSG(FUM_ADD_DECODE_ERR);
FM10K_ERR_MSG(FUM_RO_ERROR);
FM10K_ERR_MSG(FUM_QPRC_CRC_ERROR);
FM10K_ERR_MSG(FUM_CSR_TIMEOUT);
FM10K_ERR_MSG(FUM_INVALID_TYPE);
FM10K_ERR_MSG(FUM_INVALID_LENGTH);
FM10K_ERR_MSG(FUM_INVALID_BE);
FM10K_ERR_MSG(FUM_INVALID_ALIGN);
}
break;
default:
error = "Undocumented fault";
break;
}
dev_warn(&pdev->dev,
"%s Address: 0x%llx SpecInfo: 0x%x Func: %02x.%0x\n",
error, fault->address, fault->specinfo,
PCI_SLOT(fault->func), PCI_FUNC(fault->func));
}
static void fm10k_report_fault(struct fm10k_intfc *interface, u32 eicr)
{
struct fm10k_hw *hw = &interface->hw;
struct fm10k_fault fault = { 0 };
int type, err;
for (eicr &= FM10K_EICR_FAULT_MASK, type = FM10K_PCA_FAULT;
eicr;
eicr >>= 1, type += FM10K_FAULT_SIZE) {
/* only check if there is an error reported */
if (!(eicr & 0x1))
continue;
/* retrieve fault info */
err = hw->mac.ops.get_fault(hw, type, &fault);
if (err) {
dev_err(&interface->pdev->dev,
"error reading fault\n");
continue;
}
fm10k_print_fault(interface, type, &fault);
}
}
static void fm10k_reset_drop_on_empty(struct fm10k_intfc *interface, u32 eicr)
{
struct fm10k_hw *hw = &interface->hw;
const u32 rxdctl = FM10K_RXDCTL_WRITE_BACK_MIN_DELAY;
u32 maxholdq;
int q;
if (!(eicr & FM10K_EICR_MAXHOLDTIME))
return;
maxholdq = fm10k_read_reg(hw, FM10K_MAXHOLDQ(7));
if (maxholdq)
fm10k_write_reg(hw, FM10K_MAXHOLDQ(7), maxholdq);
for (q = 255;;) {
if (maxholdq & (1 << 31)) {
if (q < FM10K_MAX_QUEUES_PF) {
interface->rx_overrun_pf++;
fm10k_write_reg(hw, FM10K_RXDCTL(q), rxdctl);
} else {
interface->rx_overrun_vf++;
}
}
maxholdq *= 2;
if (!maxholdq)
q &= ~(32 - 1);
if (!q)
break;
if (q-- % 32)
continue;
maxholdq = fm10k_read_reg(hw, FM10K_MAXHOLDQ(q / 32));
if (maxholdq)
fm10k_write_reg(hw, FM10K_MAXHOLDQ(q / 32), maxholdq);
}
}
static irqreturn_t fm10k_msix_mbx_pf(int __always_unused irq, void *data)
{
struct fm10k_intfc *interface = data;
struct fm10k_hw *hw = &interface->hw;
struct fm10k_mbx_info *mbx = &hw->mbx;
u32 eicr;
/* unmask any set bits related to this interrupt */
eicr = fm10k_read_reg(hw, FM10K_EICR);
fm10k_write_reg(hw, FM10K_EICR, eicr & (FM10K_EICR_MAILBOX |
FM10K_EICR_SWITCHREADY |
FM10K_EICR_SWITCHNOTREADY));
/* report any faults found to the message log */
fm10k_report_fault(interface, eicr);
/* reset any queues disabled due to receiver overrun */
fm10k_reset_drop_on_empty(interface, eicr);
/* service mailboxes */
if (fm10k_mbx_trylock(interface)) {
mbx->ops.process(hw, mbx);
/* handle VFLRE events */
fm10k_iov_event(interface);
fm10k_mbx_unlock(interface);
}
/* if switch toggled state we should reset GLORTs */
if (eicr & FM10K_EICR_SWITCHNOTREADY) {
/* force link down for at least 4 seconds */
interface->link_down_event = jiffies + (4 * HZ);
set_bit(__FM10K_LINK_DOWN, &interface->state);
/* reset dglort_map back to no config */
hw->mac.dglort_map = FM10K_DGLORTMAP_NONE;
}
/* we should validate host state after interrupt event */
hw->mac.get_host_state = 1;
/* validate host state, and handle VF mailboxes in the service task */
fm10k_service_event_schedule(interface);
/* re-enable mailbox interrupt and indicate 20us delay */
fm10k_write_reg(hw, FM10K_ITR(FM10K_MBX_VECTOR),
FM10K_ITR_ENABLE | FM10K_MBX_INT_DELAY);
return IRQ_HANDLED;
}
void fm10k_mbx_free_irq(struct fm10k_intfc *interface)
{
struct msix_entry *entry = &interface->msix_entries[FM10K_MBX_VECTOR];
struct fm10k_hw *hw = &interface->hw;
int itr_reg;
/* disconnect the mailbox */
hw->mbx.ops.disconnect(hw, &hw->mbx);
/* disable Mailbox cause */
if (hw->mac.type == fm10k_mac_pf) {
fm10k_write_reg(hw, FM10K_EIMR,
FM10K_EIMR_DISABLE(PCA_FAULT) |
FM10K_EIMR_DISABLE(FUM_FAULT) |
FM10K_EIMR_DISABLE(MAILBOX) |
FM10K_EIMR_DISABLE(SWITCHREADY) |
FM10K_EIMR_DISABLE(SWITCHNOTREADY) |
FM10K_EIMR_DISABLE(SRAMERROR) |
FM10K_EIMR_DISABLE(VFLR) |
FM10K_EIMR_DISABLE(MAXHOLDTIME));
itr_reg = FM10K_ITR(FM10K_MBX_VECTOR);
} else {
itr_reg = FM10K_VFITR(FM10K_MBX_VECTOR);
}
fm10k_write_reg(hw, itr_reg, FM10K_ITR_MASK_SET);
free_irq(entry->vector, interface);
}
static s32 fm10k_mbx_mac_addr(struct fm10k_hw *hw, u32 **results,
struct fm10k_mbx_info *mbx)
{
bool vlan_override = hw->mac.vlan_override;
u16 default_vid = hw->mac.default_vid;
struct fm10k_intfc *interface;
s32 err;
err = fm10k_msg_mac_vlan_vf(hw, results, mbx);
if (err)
return err;
interface = container_of(hw, struct fm10k_intfc, hw);
/* MAC was changed so we need reset */
if (is_valid_ether_addr(hw->mac.perm_addr) &&
memcmp(hw->mac.perm_addr, hw->mac.addr, ETH_ALEN))
interface->flags |= FM10K_FLAG_RESET_REQUESTED;
/* VLAN override was changed, or default VLAN changed */
if ((vlan_override != hw->mac.vlan_override) ||
(default_vid != hw->mac.default_vid))
interface->flags |= FM10K_FLAG_RESET_REQUESTED;
return 0;
}
static s32 fm10k_1588_msg_vf(struct fm10k_hw *hw, u32 **results,
struct fm10k_mbx_info __always_unused *mbx)
{
struct fm10k_intfc *interface;
u64 timestamp;
s32 err;
err = fm10k_tlv_attr_get_u64(results[FM10K_1588_MSG_TIMESTAMP],
×tamp);
if (err)
return err;
interface = container_of(hw, struct fm10k_intfc, hw);
fm10k_ts_tx_hwtstamp(interface, 0, timestamp);
return 0;
}
/* generic error handler for mailbox issues */
static s32 fm10k_mbx_error(struct fm10k_hw *hw, u32 **results,
struct fm10k_mbx_info __always_unused *mbx)
{
struct fm10k_intfc *interface;
struct pci_dev *pdev;
interface = container_of(hw, struct fm10k_intfc, hw);
pdev = interface->pdev;
dev_err(&pdev->dev, "Unknown message ID %u\n",
**results & FM10K_TLV_ID_MASK);
return 0;
}
static const struct fm10k_msg_data vf_mbx_data[] = {
FM10K_TLV_MSG_TEST_HANDLER(fm10k_tlv_msg_test),
FM10K_VF_MSG_MAC_VLAN_HANDLER(fm10k_mbx_mac_addr),
FM10K_VF_MSG_LPORT_STATE_HANDLER(fm10k_msg_lport_state_vf),
FM10K_VF_MSG_1588_HANDLER(fm10k_1588_msg_vf),
FM10K_TLV_MSG_ERROR_HANDLER(fm10k_mbx_error),
};
static int fm10k_mbx_request_irq_vf(struct fm10k_intfc *interface)
{
struct msix_entry *entry = &interface->msix_entries[FM10K_MBX_VECTOR];
struct net_device *dev = interface->netdev;
struct fm10k_hw *hw = &interface->hw;
int err;
/* Use timer0 for interrupt moderation on the mailbox */
u32 itr = FM10K_INT_MAP_TIMER0 | entry->entry;
/* register mailbox handlers */
err = hw->mbx.ops.register_handlers(&hw->mbx, vf_mbx_data);
if (err)
return err;
/* request the IRQ */
err = request_irq(entry->vector, fm10k_msix_mbx_vf, 0,
dev->name, interface);
if (err) {
netif_err(interface, probe, dev,
"request_irq for msix_mbx failed: %d\n", err);
return err;
}
/* map all of the interrupt sources */
fm10k_write_reg(hw, FM10K_VFINT_MAP, itr);
/* enable interrupt */
fm10k_write_reg(hw, FM10K_VFITR(entry->entry), FM10K_ITR_ENABLE);
return 0;
}
static s32 fm10k_lport_map(struct fm10k_hw *hw, u32 **results,
struct fm10k_mbx_info *mbx)
{
struct fm10k_intfc *interface;
u32 dglort_map = hw->mac.dglort_map;
s32 err;
err = fm10k_msg_lport_map_pf(hw, results, mbx);
if (err)
return err;
interface = container_of(hw, struct fm10k_intfc, hw);
/* we need to reset if port count was just updated */
if (dglort_map != hw->mac.dglort_map)
interface->flags |= FM10K_FLAG_RESET_REQUESTED;
return 0;
}
static s32 fm10k_update_pvid(struct fm10k_hw *hw, u32 **results,
struct fm10k_mbx_info __always_unused *mbx)
{
struct fm10k_intfc *interface;
u16 glort, pvid;
u32 pvid_update;
s32 err;
err = fm10k_tlv_attr_get_u32(results[FM10K_PF_ATTR_ID_UPDATE_PVID],
&pvid_update);
if (err)
return err;
/* extract values from the pvid update */
glort = FM10K_MSG_HDR_FIELD_GET(pvid_update, UPDATE_PVID_GLORT);
pvid = FM10K_MSG_HDR_FIELD_GET(pvid_update, UPDATE_PVID_PVID);
/* if glort is not valid return error */
if (!fm10k_glort_valid_pf(hw, glort))
return FM10K_ERR_PARAM;
/* verify VID is valid */
if (pvid >= FM10K_VLAN_TABLE_VID_MAX)
return FM10K_ERR_PARAM;
interface = container_of(hw, struct fm10k_intfc, hw);
/* check to see if this belongs to one of the VFs */
err = fm10k_iov_update_pvid(interface, glort, pvid);
if (!err)
return 0;
/* we need to reset if default VLAN was just updated */
if (pvid != hw->mac.default_vid)
interface->flags |= FM10K_FLAG_RESET_REQUESTED;
hw->mac.default_vid = pvid;
return 0;
}
static s32 fm10k_1588_msg_pf(struct fm10k_hw *hw, u32 **results,
struct fm10k_mbx_info __always_unused *mbx)
{
struct fm10k_swapi_1588_timestamp timestamp;
struct fm10k_iov_data *iov_data;
struct fm10k_intfc *interface;
u16 sglort, vf_idx;
s32 err;
err = fm10k_tlv_attr_get_le_struct(
results[FM10K_PF_ATTR_ID_1588_TIMESTAMP],
×tamp, sizeof(timestamp));
if (err)
return err;
interface = container_of(hw, struct fm10k_intfc, hw);
if (timestamp.dglort) {
fm10k_ts_tx_hwtstamp(interface, timestamp.dglort,
le64_to_cpu(timestamp.egress));
return 0;
}
/* either dglort or sglort must be set */
if (!timestamp.sglort)
return FM10K_ERR_PARAM;
/* verify GLORT is at least one of the ones we own */
sglort = le16_to_cpu(timestamp.sglort);
if (!fm10k_glort_valid_pf(hw, sglort))
return FM10K_ERR_PARAM;
if (sglort == interface->glort) {
fm10k_ts_tx_hwtstamp(interface, 0,
le64_to_cpu(timestamp.ingress));
return 0;
}
/* if there is no iov_data then there is no mailboxes to process */
if (!ACCESS_ONCE(interface->iov_data))
return FM10K_ERR_PARAM;
rcu_read_lock();
/* notify VF if this timestamp belongs to it */
iov_data = interface->iov_data;
vf_idx = (hw->mac.dglort_map & FM10K_DGLORTMAP_NONE) - sglort;
if (!iov_data || vf_idx >= iov_data->num_vfs) {
err = FM10K_ERR_PARAM;
goto err_unlock;
}
err = hw->iov.ops.report_timestamp(hw, &iov_data->vf_info[vf_idx],
le64_to_cpu(timestamp.ingress));
err_unlock:
rcu_read_unlock();
return err;
}
static const struct fm10k_msg_data pf_mbx_data[] = {
FM10K_PF_MSG_ERR_HANDLER(XCAST_MODES, fm10k_msg_err_pf),
FM10K_PF_MSG_ERR_HANDLER(UPDATE_MAC_FWD_RULE, fm10k_msg_err_pf),
FM10K_PF_MSG_LPORT_MAP_HANDLER(fm10k_lport_map),
FM10K_PF_MSG_ERR_HANDLER(LPORT_CREATE, fm10k_msg_err_pf),
FM10K_PF_MSG_ERR_HANDLER(LPORT_DELETE, fm10k_msg_err_pf),
FM10K_PF_MSG_UPDATE_PVID_HANDLER(fm10k_update_pvid),
FM10K_PF_MSG_1588_TIMESTAMP_HANDLER(fm10k_1588_msg_pf),
FM10K_TLV_MSG_ERROR_HANDLER(fm10k_mbx_error),
};
static int fm10k_mbx_request_irq_pf(struct fm10k_intfc *interface)
{
struct msix_entry *entry = &interface->msix_entries[FM10K_MBX_VECTOR];
struct net_device *dev = interface->netdev;
struct fm10k_hw *hw = &interface->hw;
int err;
/* Use timer0 for interrupt moderation on the mailbox */
u32 mbx_itr = FM10K_INT_MAP_TIMER0 | entry->entry;
u32 other_itr = FM10K_INT_MAP_IMMEDIATE | entry->entry;
/* register mailbox handlers */
err = hw->mbx.ops.register_handlers(&hw->mbx, pf_mbx_data);
if (err)
return err;
/* request the IRQ */
err = request_irq(entry->vector, fm10k_msix_mbx_pf, 0,
dev->name, interface);
if (err) {
netif_err(interface, probe, dev,
"request_irq for msix_mbx failed: %d\n", err);
return err;
}
/* Enable interrupts w/ no moderation for "other" interrupts */
fm10k_write_reg(hw, FM10K_INT_MAP(fm10k_int_PCIeFault), other_itr);
fm10k_write_reg(hw, FM10K_INT_MAP(fm10k_int_SwitchUpDown), other_itr);
fm10k_write_reg(hw, FM10K_INT_MAP(fm10k_int_SRAM), other_itr);
fm10k_write_reg(hw, FM10K_INT_MAP(fm10k_int_MaxHoldTime), other_itr);
fm10k_write_reg(hw, FM10K_INT_MAP(fm10k_int_VFLR), other_itr);
/* Enable interrupts w/ moderation for mailbox */
fm10k_write_reg(hw, FM10K_INT_MAP(fm10k_int_Mailbox), mbx_itr);
/* Enable individual interrupt causes */
fm10k_write_reg(hw, FM10K_EIMR, FM10K_EIMR_ENABLE(PCA_FAULT) |
FM10K_EIMR_ENABLE(FUM_FAULT) |
FM10K_EIMR_ENABLE(MAILBOX) |
FM10K_EIMR_ENABLE(SWITCHREADY) |
FM10K_EIMR_ENABLE(SWITCHNOTREADY) |
FM10K_EIMR_ENABLE(SRAMERROR) |
FM10K_EIMR_ENABLE(VFLR) |
FM10K_EIMR_ENABLE(MAXHOLDTIME));
/* enable interrupt */
fm10k_write_reg(hw, FM10K_ITR(entry->entry), FM10K_ITR_ENABLE);
return 0;
}
int fm10k_mbx_request_irq(struct fm10k_intfc *interface)
{
struct fm10k_hw *hw = &interface->hw;
int err;
/* enable Mailbox cause */
if (hw->mac.type == fm10k_mac_pf)
err = fm10k_mbx_request_irq_pf(interface);
else
err = fm10k_mbx_request_irq_vf(interface);
/* connect mailbox */
if (!err)
err = hw->mbx.ops.connect(hw, &hw->mbx);
return err;
}
/**
* fm10k_qv_free_irq - release interrupts associated with queue vectors
* @interface: board private structure
*
* Release all interrupts associated with this interface
**/
void fm10k_qv_free_irq(struct fm10k_intfc *interface)
{
int vector = interface->num_q_vectors;
struct fm10k_hw *hw = &interface->hw;
struct msix_entry *entry;
entry = &interface->msix_entries[NON_Q_VECTORS(hw) + vector];
while (vector) {
struct fm10k_q_vector *q_vector;
vector--;
entry--;
q_vector = interface->q_vector[vector];
if (!q_vector->tx.count && !q_vector->rx.count)
continue;
/* disable interrupts */
writel(FM10K_ITR_MASK_SET, q_vector->itr);
free_irq(entry->vector, q_vector);
}
}
/**
* fm10k_qv_request_irq - initialize interrupts for queue vectors
* @interface: board private structure
*
* Attempts to configure interrupts using the best available
* capabilities of the hardware and kernel.
**/
int fm10k_qv_request_irq(struct fm10k_intfc *interface)
{
struct net_device *dev = interface->netdev;
struct fm10k_hw *hw = &interface->hw;
struct msix_entry *entry;
int ri = 0, ti = 0;
int vector, err;
entry = &interface->msix_entries[NON_Q_VECTORS(hw)];
for (vector = 0; vector < interface->num_q_vectors; vector++) {
struct fm10k_q_vector *q_vector = interface->q_vector[vector];
/* name the vector */
if (q_vector->tx.count && q_vector->rx.count) {
snprintf(q_vector->name, sizeof(q_vector->name) - 1,
"%s-TxRx-%d", dev->name, ri++);
ti++;
} else if (q_vector->rx.count) {
snprintf(q_vector->name, sizeof(q_vector->name) - 1,
"%s-rx-%d", dev->name, ri++);
} else if (q_vector->tx.count) {
snprintf(q_vector->name, sizeof(q_vector->name) - 1,
"%s-tx-%d", dev->name, ti++);
} else {
/* skip this unused q_vector */
continue;
}
/* Assign ITR register to q_vector */
q_vector->itr = (hw->mac.type == fm10k_mac_pf) ?
&interface->uc_addr[FM10K_ITR(entry->entry)] :
&interface->uc_addr[FM10K_VFITR(entry->entry)];
/* request the IRQ */
err = request_irq(entry->vector, &fm10k_msix_clean_rings, 0,
q_vector->name, q_vector);
if (err) {
netif_err(interface, probe, dev,
"request_irq failed for MSIX interrupt Error: %d\n",
err);
goto err_out;
}
/* Enable q_vector */
writel(FM10K_ITR_ENABLE, q_vector->itr);
entry++;
}
return 0;
err_out:
/* wind through the ring freeing all entries and vectors */
while (vector) {
struct fm10k_q_vector *q_vector;
entry--;
vector--;
q_vector = interface->q_vector[vector];
if (!q_vector->tx.count && !q_vector->rx.count)
continue;
/* disable interrupts */
writel(FM10K_ITR_MASK_SET, q_vector->itr);
free_irq(entry->vector, q_vector);
}
return err;
}
void fm10k_up(struct fm10k_intfc *interface)
{
struct fm10k_hw *hw = &interface->hw;
/* Enable Tx/Rx DMA */
hw->mac.ops.start_hw(hw);
/* configure Tx descriptor rings */
fm10k_configure_tx(interface);
/* configure Rx descriptor rings */
fm10k_configure_rx(interface);
/* configure interrupts */
hw->mac.ops.update_int_moderator(hw);
/* clear down bit to indicate we are ready to go */
clear_bit(__FM10K_DOWN, &interface->state);
/* enable polling cleanups */
fm10k_napi_enable_all(interface);
/* re-establish Rx filters */
fm10k_restore_rx_state(interface);
/* enable transmits */
netif_tx_start_all_queues(interface->netdev);
/* kick off the service timer now */
hw->mac.get_host_state = 1;
mod_timer(&interface->service_timer, jiffies);
}
static void fm10k_napi_disable_all(struct fm10k_intfc *interface)
{
struct fm10k_q_vector *q_vector;
int q_idx;
for (q_idx = 0; q_idx < interface->num_q_vectors; q_idx++) {
q_vector = interface->q_vector[q_idx];
napi_disable(&q_vector->napi);
}
}
void fm10k_down(struct fm10k_intfc *interface)
{
struct net_device *netdev = interface->netdev;
struct fm10k_hw *hw = &interface->hw;
/* signal that we are down to the interrupt handler and service task */
set_bit(__FM10K_DOWN, &interface->state);
/* call carrier off first to avoid false dev_watchdog timeouts */
netif_carrier_off(netdev);
/* disable transmits */
netif_tx_stop_all_queues(netdev);
netif_tx_disable(netdev);
/* reset Rx filters */
fm10k_reset_rx_state(interface);
/* allow 10ms for device to quiesce */
usleep_range(10000, 20000);
/* disable polling routines */
fm10k_napi_disable_all(interface);
/* capture stats one last time before stopping interface */
fm10k_update_stats(interface);
/* Disable DMA engine for Tx/Rx */
hw->mac.ops.stop_hw(hw);
/* free any buffers still on the rings */
fm10k_clean_all_tx_rings(interface);
fm10k_clean_all_rx_rings(interface);
}
/**
* fm10k_sw_init - Initialize general software structures
* @interface: host interface private structure to initialize
*
* fm10k_sw_init initializes the interface private data structure.
* Fields are initialized based on PCI device information and
* OS network device settings (MTU size).
**/
static int fm10k_sw_init(struct fm10k_intfc *interface,
const struct pci_device_id *ent)
{
const struct fm10k_info *fi = fm10k_info_tbl[ent->driver_data];
struct fm10k_hw *hw = &interface->hw;
struct pci_dev *pdev = interface->pdev;
struct net_device *netdev = interface->netdev;
u32 rss_key[FM10K_RSSRK_SIZE];
unsigned int rss;
int err;
/* initialize back pointer */
hw->back = interface;
hw->hw_addr = interface->uc_addr;
/* PCI config space info */
hw->vendor_id = pdev->vendor;
hw->device_id = pdev->device;
hw->revision_id = pdev->revision;
hw->subsystem_vendor_id = pdev->subsystem_vendor;
hw->subsystem_device_id = pdev->subsystem_device;
/* Setup hw api */
memcpy(&hw->mac.ops, fi->mac_ops, sizeof(hw->mac.ops));
hw->mac.type = fi->mac;
/* Setup IOV handlers */
if (fi->iov_ops)
memcpy(&hw->iov.ops, fi->iov_ops, sizeof(hw->iov.ops));
/* Set common capability flags and settings */
rss = min_t(int, FM10K_MAX_RSS_INDICES, num_online_cpus());
interface->ring_feature[RING_F_RSS].limit = rss;
fi->get_invariants(hw);
/* pick up the PCIe bus settings for reporting later */
if (hw->mac.ops.get_bus_info)
hw->mac.ops.get_bus_info(hw);
/* limit the usable DMA range */
if (hw->mac.ops.set_dma_mask)
hw->mac.ops.set_dma_mask(hw, dma_get_mask(&pdev->dev));
/* update netdev with DMA restrictions */
if (dma_get_mask(&pdev->dev) > DMA_BIT_MASK(32)) {
netdev->features |= NETIF_F_HIGHDMA;
netdev->vlan_features |= NETIF_F_HIGHDMA;
}
/* delay any future reset requests */
interface->last_reset = jiffies + (10 * HZ);
/* reset and initialize the hardware so it is in a known state */
err = hw->mac.ops.reset_hw(hw) ? : hw->mac.ops.init_hw(hw);
if (err) {
dev_err(&pdev->dev, "init_hw failed: %d\n", err);
return err;
}
/* initialize hardware statistics */
hw->mac.ops.update_hw_stats(hw, &interface->stats);
/* Set upper limit on IOV VFs that can be allocated */
pci_sriov_set_totalvfs(pdev, hw->iov.total_vfs);
/* Start with random Ethernet address */
eth_random_addr(hw->mac.addr);
/* Initialize MAC address from hardware */
err = hw->mac.ops.read_mac_addr(hw);
if (err) {
dev_warn(&pdev->dev,
"Failed to obtain MAC address defaulting to random\n");
/* tag address assignment as random */
netdev->addr_assign_type |= NET_ADDR_RANDOM;
}
memcpy(netdev->dev_addr, hw->mac.addr, netdev->addr_len);
memcpy(netdev->perm_addr, hw->mac.addr, netdev->addr_len);
if (!is_valid_ether_addr(netdev->perm_addr)) {
dev_err(&pdev->dev, "Invalid MAC Address\n");
return -EIO;
}
/* assign BAR 4 resources for use with PTP */
if (fm10k_read_reg(hw, FM10K_CTRL) & FM10K_CTRL_BAR4_ALLOWED)
interface->sw_addr = ioremap(pci_resource_start(pdev, 4),
pci_resource_len(pdev, 4));
hw->sw_addr = interface->sw_addr;
/* Only the PF can support VXLAN and NVGRE offloads */
if (hw->mac.type != fm10k_mac_pf) {
netdev->hw_enc_features = 0;
netdev->features &= ~NETIF_F_GSO_UDP_TUNNEL;
netdev->hw_features &= ~NETIF_F_GSO_UDP_TUNNEL;
}
/* initialize DCBNL interface */
fm10k_dcbnl_set_ops(netdev);
/* Initialize service timer and service task */
set_bit(__FM10K_SERVICE_DISABLE, &interface->state);
setup_timer(&interface->service_timer, &fm10k_service_timer,
(unsigned long)interface);
INIT_WORK(&interface->service_task, fm10k_service_task);
/* kick off service timer now, even when interface is down */
mod_timer(&interface->service_timer, (HZ * 2) + jiffies);
/* Intitialize timestamp data */
fm10k_ts_init(interface);
/* set default ring sizes */
interface->tx_ring_count = FM10K_DEFAULT_TXD;
interface->rx_ring_count = FM10K_DEFAULT_RXD;
/* set default interrupt moderation */
interface->tx_itr = FM10K_ITR_10K;
interface->rx_itr = FM10K_ITR_ADAPTIVE | FM10K_ITR_20K;
/* initialize vxlan_port list */
INIT_LIST_HEAD(&interface->vxlan_port);
netdev_rss_key_fill(rss_key, sizeof(rss_key));
memcpy(interface->rssrk, rss_key, sizeof(rss_key));
/* Start off interface as being down */
set_bit(__FM10K_DOWN, &interface->state);
return 0;
}
static void fm10k_slot_warn(struct fm10k_intfc *interface)
{
struct device *dev = &interface->pdev->dev;
struct fm10k_hw *hw = &interface->hw;
if (hw->mac.ops.is_slot_appropriate(hw))
return;
dev_warn(dev,
"For optimal performance, a %s %s slot is recommended.\n",
(hw->bus_caps.width == fm10k_bus_width_pcie_x1 ? "x1" :
hw->bus_caps.width == fm10k_bus_width_pcie_x4 ? "x4" :
"x8"),
(hw->bus_caps.speed == fm10k_bus_speed_2500 ? "2.5GT/s" :
hw->bus_caps.speed == fm10k_bus_speed_5000 ? "5.0GT/s" :
"8.0GT/s"));
dev_warn(dev,
"A slot with more lanes and/or higher speed is suggested.\n");
}
/**
* fm10k_probe - Device Initialization Routine
* @pdev: PCI device information struct
* @ent: entry in fm10k_pci_tbl
*
* Returns 0 on success, negative on failure
*
* fm10k_probe initializes an interface identified by a pci_dev structure.
* The OS initialization, configuring of the interface private structure,
* and a hardware reset occur.
**/
static int fm10k_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *netdev;
struct fm10k_intfc *interface;
struct fm10k_hw *hw;
int err;
err = pci_enable_device_mem(pdev);
if (err)
return err;
err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(48));
if (err)
err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
if (err) {
dev_err(&pdev->dev,
"DMA configuration failed: %d\n", err);
goto err_dma;
}
err = pci_request_selected_regions(pdev,
pci_select_bars(pdev,
IORESOURCE_MEM),
fm10k_driver_name);
if (err) {
dev_err(&pdev->dev,
"pci_request_selected_regions failed: %d\n", err);
goto err_pci_reg;
}
pci_enable_pcie_error_reporting(pdev);
pci_set_master(pdev);
pci_save_state(pdev);
netdev = fm10k_alloc_netdev();
if (!netdev) {
err = -ENOMEM;
goto err_alloc_netdev;
}
SET_NETDEV_DEV(netdev, &pdev->dev);
interface = netdev_priv(netdev);
pci_set_drvdata(pdev, interface);
interface->netdev = netdev;
interface->pdev = pdev;
hw = &interface->hw;
interface->uc_addr = ioremap(pci_resource_start(pdev, 0),
FM10K_UC_ADDR_SIZE);
if (!interface->uc_addr) {
err = -EIO;
goto err_ioremap;
}
err = fm10k_sw_init(interface, ent);
if (err)
goto err_sw_init;
/* enable debugfs support */
fm10k_dbg_intfc_init(interface);
err = fm10k_init_queueing_scheme(interface);
if (err)
goto err_sw_init;
err = fm10k_mbx_request_irq(interface);
if (err)
goto err_mbx_interrupt;
/* final check of hardware state before registering the interface */
err = fm10k_hw_ready(interface);
if (err)
goto err_register;
err = register_netdev(netdev);
if (err)
goto err_register;
/* carrier off reporting is important to ethtool even BEFORE open */
netif_carrier_off(netdev);
/* stop all the transmit queues from transmitting until link is up */
netif_tx_stop_all_queues(netdev);
/* Register PTP interface */
fm10k_ptp_register(interface);
/* print bus type/speed/width info */
dev_info(&pdev->dev, "(PCI Express:%s Width: %s Payload: %s)\n",
(hw->bus.speed == fm10k_bus_speed_8000 ? "8.0GT/s" :
hw->bus.speed == fm10k_bus_speed_5000 ? "5.0GT/s" :
hw->bus.speed == fm10k_bus_speed_2500 ? "2.5GT/s" :
"Unknown"),
(hw->bus.width == fm10k_bus_width_pcie_x8 ? "x8" :
hw->bus.width == fm10k_bus_width_pcie_x4 ? "x4" :
hw->bus.width == fm10k_bus_width_pcie_x1 ? "x1" :
"Unknown"),
(hw->bus.payload == fm10k_bus_payload_128 ? "128B" :
hw->bus.payload == fm10k_bus_payload_256 ? "256B" :
hw->bus.payload == fm10k_bus_payload_512 ? "512B" :
"Unknown"));
/* print warning for non-optimal configurations */
fm10k_slot_warn(interface);
/* enable SR-IOV after registering netdev to enforce PF/VF ordering */
fm10k_iov_configure(pdev, 0);
/* clear the service task disable bit to allow service task to start */
clear_bit(__FM10K_SERVICE_DISABLE, &interface->state);
return 0;
err_register:
fm10k_mbx_free_irq(interface);
err_mbx_interrupt:
fm10k_clear_queueing_scheme(interface);
err_sw_init:
if (interface->sw_addr)
iounmap(interface->sw_addr);
iounmap(interface->uc_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_netdev:
pci_release_selected_regions(pdev,
pci_select_bars(pdev, IORESOURCE_MEM));
err_pci_reg:
err_dma:
pci_disable_device(pdev);
return err;
}
/**
* fm10k_remove - Device Removal Routine
* @pdev: PCI device information struct
*
* fm10k_remove is called by the PCI subsystem to alert the driver
* that it should release a PCI device. The could be caused by a
* Hot-Plug event, or because the driver is going to be removed from
* memory.
**/
static void fm10k_remove(struct pci_dev *pdev)
{
struct fm10k_intfc *interface = pci_get_drvdata(pdev);
struct net_device *netdev = interface->netdev;
del_timer_sync(&interface->service_timer);
set_bit(__FM10K_SERVICE_DISABLE, &interface->state);
cancel_work_sync(&interface->service_task);
/* free netdev, this may bounce the interrupts due to setup_tc */
if (netdev->reg_state == NETREG_REGISTERED)
unregister_netdev(netdev);
/* cleanup timestamp handling */
fm10k_ptp_unregister(interface);
/* release VFs */
fm10k_iov_disable(pdev);
/* disable mailbox interrupt */
fm10k_mbx_free_irq(interface);
/* free interrupts */
fm10k_clear_queueing_scheme(interface);
/* remove any debugfs interfaces */
fm10k_dbg_intfc_exit(interface);
if (interface->sw_addr)
iounmap(interface->sw_addr);
iounmap(interface->uc_addr);
free_netdev(netdev);
pci_release_selected_regions(pdev,
pci_select_bars(pdev, IORESOURCE_MEM));
pci_disable_pcie_error_reporting(pdev);
pci_disable_device(pdev);
}
#ifdef CONFIG_PM
/**
* fm10k_resume - Restore device to pre-sleep state
* @pdev: PCI device information struct
*
* fm10k_resume is called after the system has powered back up from a sleep
* state and is ready to resume operation. This function is meant to restore
* the device back to its pre-sleep state.
**/
static int fm10k_resume(struct pci_dev *pdev)
{
struct fm10k_intfc *interface = pci_get_drvdata(pdev);
struct net_device *netdev = interface->netdev;
struct fm10k_hw *hw = &interface->hw;
u32 err;
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
/* pci_restore_state clears dev->state_saved so call
* pci_save_state to restore it.
*/
pci_save_state(pdev);
err = pci_enable_device_mem(pdev);
if (err) {
dev_err(&pdev->dev, "Cannot enable PCI device from suspend\n");
return err;
}
pci_set_master(pdev);
pci_wake_from_d3(pdev, false);
/* refresh hw_addr in case it was dropped */
hw->hw_addr = interface->uc_addr;
/* reset hardware to known state */
err = hw->mac.ops.init_hw(&interface->hw);
if (err)
return err;
/* reset statistics starting values */
hw->mac.ops.rebind_hw_stats(hw, &interface->stats);
/* reset clock */
fm10k_ts_reset(interface);
rtnl_lock();
err = fm10k_init_queueing_scheme(interface);
if (!err) {
fm10k_mbx_request_irq(interface);
if (netif_running(netdev))
err = fm10k_open(netdev);
}
rtnl_unlock();
if (err)
return err;
/* restore SR-IOV interface */
fm10k_iov_resume(pdev);
netif_device_attach(netdev);
return 0;
}
/**
* fm10k_suspend - Prepare the device for a system sleep state
* @pdev: PCI device information struct
*
* fm10k_suspend is meant to shutdown the device prior to the system entering
* a sleep state. The fm10k hardware does not support wake on lan so the
* driver simply needs to shut down the device so it is in a low power state.
**/
static int fm10k_suspend(struct pci_dev *pdev,
pm_message_t __always_unused state)
{
struct fm10k_intfc *interface = pci_get_drvdata(pdev);
struct net_device *netdev = interface->netdev;
int err = 0;
netif_device_detach(netdev);
fm10k_iov_suspend(pdev);
rtnl_lock();
if (netif_running(netdev))
fm10k_close(netdev);
fm10k_mbx_free_irq(interface);
fm10k_clear_queueing_scheme(interface);
rtnl_unlock();
err = pci_save_state(pdev);
if (err)
return err;
pci_disable_device(pdev);
pci_wake_from_d3(pdev, false);
pci_set_power_state(pdev, PCI_D3hot);
return 0;
}
#endif /* CONFIG_PM */
/**
* fm10k_io_error_detected - called when PCI error is detected
* @pdev: Pointer to PCI device
* @state: The current pci connection state
*
* This function is called after a PCI bus error affecting
* this device has been detected.
*/
static pci_ers_result_t fm10k_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct fm10k_intfc *interface = pci_get_drvdata(pdev);
struct net_device *netdev = interface->netdev;
netif_device_detach(netdev);
if (state == pci_channel_io_perm_failure)
return PCI_ERS_RESULT_DISCONNECT;
if (netif_running(netdev))
fm10k_close(netdev);
fm10k_mbx_free_irq(interface);
pci_disable_device(pdev);
/* Request a slot reset. */
return PCI_ERS_RESULT_NEED_RESET;
}
/**
* fm10k_io_slot_reset - called after the pci bus has been reset.
* @pdev: Pointer to PCI device
*
* Restart the card from scratch, as if from a cold-boot.
*/
static pci_ers_result_t fm10k_io_slot_reset(struct pci_dev *pdev)
{
struct fm10k_intfc *interface = pci_get_drvdata(pdev);
pci_ers_result_t result;
if (pci_enable_device_mem(pdev)) {
dev_err(&pdev->dev,
"Cannot re-enable PCI device after reset.\n");
result = PCI_ERS_RESULT_DISCONNECT;
} else {
pci_set_master(pdev);
pci_restore_state(pdev);
/* After second error pci->state_saved is false, this
* resets it so EEH doesn't break.
*/
pci_save_state(pdev);
pci_wake_from_d3(pdev, false);
/* refresh hw_addr in case it was dropped */
interface->hw.hw_addr = interface->uc_addr;
interface->flags |= FM10K_FLAG_RESET_REQUESTED;
fm10k_service_event_schedule(interface);
result = PCI_ERS_RESULT_RECOVERED;
}
pci_cleanup_aer_uncorrect_error_status(pdev);
return result;
}
/**
* fm10k_io_resume - called when traffic can start flowing again.
* @pdev: Pointer to PCI device
*
* This callback is called when the error recovery driver tells us that
* its OK to resume normal operation.
*/
static void fm10k_io_resume(struct pci_dev *pdev)
{
struct fm10k_intfc *interface = pci_get_drvdata(pdev);
struct net_device *netdev = interface->netdev;
struct fm10k_hw *hw = &interface->hw;
int err = 0;
/* reset hardware to known state */
hw->mac.ops.init_hw(&interface->hw);
/* reset statistics starting values */
hw->mac.ops.rebind_hw_stats(hw, &interface->stats);
/* reassociate interrupts */
fm10k_mbx_request_irq(interface);
/* reset clock */
fm10k_ts_reset(interface);
if (netif_running(netdev))
err = fm10k_open(netdev);
/* final check of hardware state before registering the interface */
err = err ? : fm10k_hw_ready(interface);
if (!err)
netif_device_attach(netdev);
}
static const struct pci_error_handlers fm10k_err_handler = {
.error_detected = fm10k_io_error_detected,
.slot_reset = fm10k_io_slot_reset,
.resume = fm10k_io_resume,
};
static struct pci_driver fm10k_driver = {
.name = fm10k_driver_name,
.id_table = fm10k_pci_tbl,
.probe = fm10k_probe,
.remove = fm10k_remove,
#ifdef CONFIG_PM
.suspend = fm10k_suspend,
.resume = fm10k_resume,
#endif
.sriov_configure = fm10k_iov_configure,
.err_handler = &fm10k_err_handler
};
/**
* fm10k_register_pci_driver - register driver interface
*
* This funciton is called on module load in order to register the driver.
**/
int fm10k_register_pci_driver(void)
{
return pci_register_driver(&fm10k_driver);
}
/**
* fm10k_unregister_pci_driver - unregister driver interface
*
* This funciton is called on module unload in order to remove the driver.
**/
void fm10k_unregister_pci_driver(void)
{
pci_unregister_driver(&fm10k_driver);
}
| gpl-2.0 |
zoobab/vzkernel | arch/microblaze/mm/fault.c | 642 | 8109 | /*
* arch/microblaze/mm/fault.c
*
* Copyright (C) 2007 Xilinx, Inc. All rights reserved.
*
* Derived from "arch/ppc/mm/fault.c"
* Copyright (C) 1995-1996 Gary Thomas (gdt@linuxppc.org)
*
* Derived from "arch/i386/mm/fault.c"
* Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
*
* Modified by Cort Dougan and Paul Mackerras.
*
* This file is subject to the terms and conditions of the GNU General
* Public License. See the file COPYING in the main directory of this
* archive for more details.
*
*/
#include <linux/module.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/ptrace.h>
#include <linux/mman.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/mmu.h>
#include <linux/mmu_context.h>
#include <linux/uaccess.h>
#include <asm/exceptions.h>
static unsigned long pte_misses; /* updated by do_page_fault() */
static unsigned long pte_errors; /* updated by do_page_fault() */
/*
* Check whether the instruction at regs->pc is a store using
* an update addressing form which will update r1.
*/
static int store_updates_sp(struct pt_regs *regs)
{
unsigned int inst;
if (get_user(inst, (unsigned int __user *)regs->pc))
return 0;
/* check for 1 in the rD field */
if (((inst >> 21) & 0x1f) != 1)
return 0;
/* check for store opcodes */
if ((inst & 0xd0000000) == 0xd0000000)
return 1;
return 0;
}
/*
* bad_page_fault is called when we have a bad access from the kernel.
* It is called from do_page_fault above and from some of the procedures
* in traps.c.
*/
void bad_page_fault(struct pt_regs *regs, unsigned long address, int sig)
{
const struct exception_table_entry *fixup;
/* MS: no context */
/* Are we prepared to handle this fault? */
fixup = search_exception_tables(regs->pc);
if (fixup) {
regs->pc = fixup->fixup;
return;
}
/* kernel has accessed a bad area */
die("kernel access of bad area", regs, sig);
}
/*
* The error_code parameter is ESR for a data fault,
* 0 for an instruction fault.
*/
void do_page_fault(struct pt_regs *regs, unsigned long address,
unsigned long error_code)
{
struct vm_area_struct *vma;
struct mm_struct *mm = current->mm;
siginfo_t info;
int code = SEGV_MAPERR;
int is_write = error_code & ESR_S;
int fault;
unsigned int flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE |
(is_write ? FAULT_FLAG_WRITE : 0);
regs->ear = address;
regs->esr = error_code;
/* On a kernel SLB miss we can only check for a valid exception entry */
if (unlikely(kernel_mode(regs) && (address >= TASK_SIZE))) {
pr_warn("kernel task_size exceed");
_exception(SIGSEGV, regs, code, address);
}
/* for instr TLB miss and instr storage exception ESR_S is undefined */
if ((error_code & 0x13) == 0x13 || (error_code & 0x11) == 0x11)
is_write = 0;
if (unlikely(in_atomic() || !mm)) {
if (kernel_mode(regs))
goto bad_area_nosemaphore;
/* in_atomic() in user mode is really bad,
as is current->mm == NULL. */
pr_emerg("Page fault in user mode with in_atomic(), mm = %p\n",
mm);
pr_emerg("r15 = %lx MSR = %lx\n",
regs->r15, regs->msr);
die("Weird page fault", regs, SIGSEGV);
}
/* When running in the kernel we expect faults to occur only to
* addresses in user space. All other faults represent errors in the
* kernel and should generate an OOPS. Unfortunately, in the case of an
* erroneous fault occurring in a code path which already holds mmap_sem
* we will deadlock attempting to validate the fault against the
* address space. Luckily the kernel only validly references user
* space from well defined areas of code, which are listed in the
* exceptions table.
*
* As the vast majority of faults will be valid we will only perform
* the source reference check when there is a possibility of a deadlock.
* Attempt to lock the address space, if we cannot we then validate the
* source. If this is invalid we can skip the address space check,
* thus avoiding the deadlock.
*/
if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
if (kernel_mode(regs) && !search_exception_tables(regs->pc))
goto bad_area_nosemaphore;
retry:
down_read(&mm->mmap_sem);
}
vma = find_vma(mm, address);
if (unlikely(!vma))
goto bad_area;
if (vma->vm_start <= address)
goto good_area;
if (unlikely(!(vma->vm_flags & VM_GROWSDOWN)))
goto bad_area;
if (unlikely(!is_write))
goto bad_area;
/*
* N.B. The ABI allows programs to access up to
* a few hundred bytes below the stack pointer (TBD).
* The kernel signal delivery code writes up to about 1.5kB
* below the stack pointer (r1) before decrementing it.
* The exec code can write slightly over 640kB to the stack
* before setting the user r1. Thus we allow the stack to
* expand to 1MB without further checks.
*/
if (unlikely(address + 0x100000 < vma->vm_end)) {
/* get user regs even if this fault is in kernel mode */
struct pt_regs *uregs = current->thread.regs;
if (uregs == NULL)
goto bad_area;
/*
* A user-mode access to an address a long way below
* the stack pointer is only valid if the instruction
* is one which would update the stack pointer to the
* address accessed if the instruction completed,
* i.e. either stwu rs,n(r1) or stwux rs,r1,rb
* (or the byte, halfword, float or double forms).
*
* If we don't check this then any write to the area
* between the last mapped region and the stack will
* expand the stack rather than segfaulting.
*/
if (address + 2048 < uregs->r1
&& (kernel_mode(regs) || !store_updates_sp(regs)))
goto bad_area;
}
if (expand_stack(vma, address))
goto bad_area;
good_area:
code = SEGV_ACCERR;
/* a write */
if (unlikely(is_write)) {
if (unlikely(!(vma->vm_flags & VM_WRITE)))
goto bad_area;
/* a read */
} else {
/* protection fault */
if (unlikely(error_code & 0x08000000))
goto bad_area;
if (unlikely(!(vma->vm_flags & (VM_READ | VM_EXEC))))
goto bad_area;
}
/*
* If for any reason at all we couldn't handle the fault,
* make sure we exit gracefully rather than endlessly redo
* the fault.
*/
fault = handle_mm_fault(mm, vma, address, flags);
if ((fault & VM_FAULT_RETRY) && fatal_signal_pending(current))
return;
if (unlikely(fault & VM_FAULT_ERROR)) {
if (fault & VM_FAULT_OOM)
goto out_of_memory;
else if (fault & VM_FAULT_SIGBUS)
goto do_sigbus;
BUG();
}
if (flags & FAULT_FLAG_ALLOW_RETRY) {
if (unlikely(fault & VM_FAULT_MAJOR))
current->maj_flt++;
else
current->min_flt++;
if (fault & VM_FAULT_RETRY) {
flags &= ~FAULT_FLAG_ALLOW_RETRY;
flags |= FAULT_FLAG_TRIED;
/*
* No need to up_read(&mm->mmap_sem) as we would
* have already released it in __lock_page_or_retry
* in mm/filemap.c.
*/
goto retry;
}
}
up_read(&mm->mmap_sem);
/*
* keep track of tlb+htab misses that are good addrs but
* just need pte's created via handle_mm_fault()
* -- Cort
*/
pte_misses++;
return;
bad_area:
up_read(&mm->mmap_sem);
bad_area_nosemaphore:
pte_errors++;
/* User mode accesses cause a SIGSEGV */
if (user_mode(regs)) {
_exception(SIGSEGV, regs, code, address);
/* info.si_signo = SIGSEGV;
info.si_errno = 0;
info.si_code = code;
info.si_addr = (void *) address;
force_sig_info(SIGSEGV, &info, current);*/
return;
}
bad_page_fault(regs, address, SIGSEGV);
return;
/*
* We ran out of memory, or some other thing happened to us that made
* us unable to handle the page fault gracefully.
*/
out_of_memory:
up_read(&mm->mmap_sem);
if (!user_mode(regs))
bad_page_fault(regs, address, SIGKILL);
else
pagefault_out_of_memory();
return;
do_sigbus:
up_read(&mm->mmap_sem);
if (user_mode(regs)) {
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_ADRERR;
info.si_addr = (void __user *)address;
force_sig_info(SIGBUS, &info, current);
return;
}
bad_page_fault(regs, address, SIGBUS);
}
| gpl-2.0 |
Rockman18/kernel-lgnas | arch/arm/mach-s3c2410/mach-smdk2410.c | 898 | 3256 | /* linux/arch/arm/mach-s3c2410/mach-smdk2410.c
*
* linux/arch/arm/mach-s3c2410/mach-smdk2410.c
*
* Copyright (C) 2004 by FS Forth-Systeme GmbH
* All rights reserved.
*
* @Author: Jonas Dietsche
*
* 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
*
* @History:
* derived from linux/arch/arm/mach-s3c2410/mach-bast.c, written by
* Ben Dooks <ben@simtec.co.uk>
*
***********************************************************************/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/serial_core.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <plat/regs-serial.h>
#include <plat/iic.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/common-smdk.h>
static struct map_desc smdk2410_iodesc[] __initdata = {
/* nothing here yet */
};
#define UCON S3C2410_UCON_DEFAULT
#define ULCON S3C2410_LCON_CS8 | S3C2410_LCON_PNONE | S3C2410_LCON_STOPB
#define UFCON S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE
static struct s3c2410_uartcfg smdk2410_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
}
};
static struct platform_device *smdk2410_devices[] __initdata = {
&s3c_device_ohci,
&s3c_device_lcd,
&s3c_device_wdt,
&s3c_device_i2c0,
&s3c_device_iis,
};
static void __init smdk2410_map_io(void)
{
s3c24xx_init_io(smdk2410_iodesc, ARRAY_SIZE(smdk2410_iodesc));
s3c24xx_init_clocks(0);
s3c24xx_init_uarts(smdk2410_uartcfgs, ARRAY_SIZE(smdk2410_uartcfgs));
}
static void __init smdk2410_init(void)
{
s3c_i2c0_set_platdata(NULL);
platform_add_devices(smdk2410_devices, ARRAY_SIZE(smdk2410_devices));
smdk_machine_init();
}
MACHINE_START(SMDK2410, "SMDK2410") /* @TODO: request a new identifier and switch
* to SMDK2410 */
/* Maintainer: Jonas Dietsche */
.phys_io = S3C2410_PA_UART,
.io_pg_offst = (((u32)S3C24XX_VA_UART) >> 18) & 0xfffc,
.boot_params = S3C2410_SDRAM_PA + 0x100,
.map_io = smdk2410_map_io,
.init_irq = s3c24xx_init_irq,
.init_machine = smdk2410_init,
.timer = &s3c24xx_timer,
MACHINE_END
| gpl-2.0 |
EPDCenter/android_kernel_bq_dc_v1 | drivers/staging/panel/panel.c | 2690 | 61486 | /*
* Front panel driver for Linux
* Copyright (C) 2000-2008, Willy Tarreau <w@1wt.eu>
*
* 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 code drives an LCD module (/dev/lcd), and a keypad (/dev/keypad)
* connected to a parallel printer port.
*
* The LCD module may either be an HD44780-like 8-bit parallel LCD, or a 1-bit
* serial module compatible with Samsung's KS0074. The pins may be connected in
* any combination, everything is programmable.
*
* The keypad consists in a matrix of push buttons connecting input pins to
* data output pins or to the ground. The combinations have to be hard-coded
* in the driver, though several profiles exist and adding new ones is easy.
*
* Several profiles are provided for commonly found LCD+keypad modules on the
* market, such as those found in Nexcom's appliances.
*
* FIXME:
* - the initialization/deinitialization process is very dirty and should
* be rewritten. It may even be buggy.
*
* TODO:
* - document 24 keys keyboard (3 rows of 8 cols, 32 diodes + 2 inputs)
* - make the LCD a part of a virtual screen of Vx*Vy
* - make the inputs list smp-safe
* - change the keyboard to a double mapping : signals -> key_id -> values
* so that applications can change values without knowing signals
*
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/miscdevice.h>
#include <linux/slab.h>
#include <linux/ioport.h>
#include <linux/fcntl.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/ctype.h>
#include <linux/parport.h>
#include <linux/version.h>
#include <linux/list.h>
#include <linux/notifier.h>
#include <linux/reboot.h>
#include <generated/utsrelease.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include <asm/system.h>
#define LCD_MINOR 156
#define KEYPAD_MINOR 185
#define PANEL_VERSION "0.9.5"
#define LCD_MAXBYTES 256 /* max burst write */
#define KEYPAD_BUFFER 64
/* poll the keyboard this every second */
#define INPUT_POLL_TIME (HZ/50)
/* a key starts to repeat after this times INPUT_POLL_TIME */
#define KEYPAD_REP_START (10)
/* a key repeats this times INPUT_POLL_TIME */
#define KEYPAD_REP_DELAY (2)
/* keep the light on this times INPUT_POLL_TIME for each flash */
#define FLASH_LIGHT_TEMPO (200)
/* converts an r_str() input to an active high, bits string : 000BAOSE */
#define PNL_PINPUT(a) ((((unsigned char)(a)) ^ 0x7F) >> 3)
#define PNL_PBUSY 0x80 /* inverted input, active low */
#define PNL_PACK 0x40 /* direct input, active low */
#define PNL_POUTPA 0x20 /* direct input, active high */
#define PNL_PSELECD 0x10 /* direct input, active high */
#define PNL_PERRORP 0x08 /* direct input, active low */
#define PNL_PBIDIR 0x20 /* bi-directional ports */
/* high to read data in or-ed with data out */
#define PNL_PINTEN 0x10
#define PNL_PSELECP 0x08 /* inverted output, active low */
#define PNL_PINITP 0x04 /* direct output, active low */
#define PNL_PAUTOLF 0x02 /* inverted output, active low */
#define PNL_PSTROBE 0x01 /* inverted output */
#define PNL_PD0 0x01
#define PNL_PD1 0x02
#define PNL_PD2 0x04
#define PNL_PD3 0x08
#define PNL_PD4 0x10
#define PNL_PD5 0x20
#define PNL_PD6 0x40
#define PNL_PD7 0x80
#define PIN_NONE 0
#define PIN_STROBE 1
#define PIN_D0 2
#define PIN_D1 3
#define PIN_D2 4
#define PIN_D3 5
#define PIN_D4 6
#define PIN_D5 7
#define PIN_D6 8
#define PIN_D7 9
#define PIN_AUTOLF 14
#define PIN_INITP 16
#define PIN_SELECP 17
#define PIN_NOT_SET 127
#define LCD_FLAG_S 0x0001
#define LCD_FLAG_ID 0x0002
#define LCD_FLAG_B 0x0004 /* blink on */
#define LCD_FLAG_C 0x0008 /* cursor on */
#define LCD_FLAG_D 0x0010 /* display on */
#define LCD_FLAG_F 0x0020 /* large font mode */
#define LCD_FLAG_N 0x0040 /* 2-rows mode */
#define LCD_FLAG_L 0x0080 /* backlight enabled */
#define LCD_ESCAPE_LEN 24 /* max chars for LCD escape command */
#define LCD_ESCAPE_CHAR 27 /* use char 27 for escape command */
/* macros to simplify use of the parallel port */
#define r_ctr(x) (parport_read_control((x)->port))
#define r_dtr(x) (parport_read_data((x)->port))
#define r_str(x) (parport_read_status((x)->port))
#define w_ctr(x, y) do { parport_write_control((x)->port, (y)); } while (0)
#define w_dtr(x, y) do { parport_write_data((x)->port, (y)); } while (0)
/* this defines which bits are to be used and which ones to be ignored */
/* logical or of the output bits involved in the scan matrix */
static __u8 scan_mask_o;
/* logical or of the input bits involved in the scan matrix */
static __u8 scan_mask_i;
typedef __u64 pmask_t;
enum input_type {
INPUT_TYPE_STD,
INPUT_TYPE_KBD,
};
enum input_state {
INPUT_ST_LOW,
INPUT_ST_RISING,
INPUT_ST_HIGH,
INPUT_ST_FALLING,
};
struct logical_input {
struct list_head list;
pmask_t mask;
pmask_t value;
enum input_type type;
enum input_state state;
__u8 rise_time, fall_time;
__u8 rise_timer, fall_timer, high_timer;
union {
struct { /* valid when type == INPUT_TYPE_STD */
void (*press_fct) (int);
void (*release_fct) (int);
int press_data;
int release_data;
} std;
struct { /* valid when type == INPUT_TYPE_KBD */
/* strings can be non null-terminated */
char press_str[sizeof(void *) + sizeof(int)];
char repeat_str[sizeof(void *) + sizeof(int)];
char release_str[sizeof(void *) + sizeof(int)];
} kbd;
} u;
};
LIST_HEAD(logical_inputs); /* list of all defined logical inputs */
/* physical contacts history
* Physical contacts are a 45 bits string of 9 groups of 5 bits each.
* The 8 lower groups correspond to output bits 0 to 7, and the 9th group
* corresponds to the ground.
* Within each group, bits are stored in the same order as read on the port :
* BAPSE (busy=4, ack=3, paper empty=2, select=1, error=0).
* So, each __u64 (or pmask_t) is represented like this :
* 0000000000000000000BAPSEBAPSEBAPSEBAPSEBAPSEBAPSEBAPSEBAPSEBAPSE
* <-----unused------><gnd><d07><d06><d05><d04><d03><d02><d01><d00>
*/
/* what has just been read from the I/O ports */
static pmask_t phys_read;
/* previous phys_read */
static pmask_t phys_read_prev;
/* stabilized phys_read (phys_read|phys_read_prev) */
static pmask_t phys_curr;
/* previous phys_curr */
static pmask_t phys_prev;
/* 0 means that at least one logical signal needs be computed */
static char inputs_stable;
/* these variables are specific to the keypad */
static char keypad_buffer[KEYPAD_BUFFER];
static int keypad_buflen;
static int keypad_start;
static char keypressed;
static wait_queue_head_t keypad_read_wait;
/* lcd-specific variables */
/* contains the LCD config state */
static unsigned long int lcd_flags;
/* contains the LCD X offset */
static unsigned long int lcd_addr_x;
/* contains the LCD Y offset */
static unsigned long int lcd_addr_y;
/* current escape sequence, 0 terminated */
static char lcd_escape[LCD_ESCAPE_LEN + 1];
/* not in escape state. >=0 = escape cmd len */
static int lcd_escape_len = -1;
/*
* Bit masks to convert LCD signals to parallel port outputs.
* _d_ are values for data port, _c_ are for control port.
* [0] = signal OFF, [1] = signal ON, [2] = mask
*/
#define BIT_CLR 0
#define BIT_SET 1
#define BIT_MSK 2
#define BIT_STATES 3
/*
* one entry for each bit on the LCD
*/
#define LCD_BIT_E 0
#define LCD_BIT_RS 1
#define LCD_BIT_RW 2
#define LCD_BIT_BL 3
#define LCD_BIT_CL 4
#define LCD_BIT_DA 5
#define LCD_BITS 6
/*
* each bit can be either connected to a DATA or CTRL port
*/
#define LCD_PORT_C 0
#define LCD_PORT_D 1
#define LCD_PORTS 2
static unsigned char lcd_bits[LCD_PORTS][LCD_BITS][BIT_STATES];
/*
* LCD protocols
*/
#define LCD_PROTO_PARALLEL 0
#define LCD_PROTO_SERIAL 1
#define LCD_PROTO_TI_DA8XX_LCD 2
/*
* LCD character sets
*/
#define LCD_CHARSET_NORMAL 0
#define LCD_CHARSET_KS0074 1
/*
* LCD types
*/
#define LCD_TYPE_NONE 0
#define LCD_TYPE_OLD 1
#define LCD_TYPE_KS0074 2
#define LCD_TYPE_HANTRONIX 3
#define LCD_TYPE_NEXCOM 4
#define LCD_TYPE_CUSTOM 5
/*
* keypad types
*/
#define KEYPAD_TYPE_NONE 0
#define KEYPAD_TYPE_OLD 1
#define KEYPAD_TYPE_NEW 2
#define KEYPAD_TYPE_NEXCOM 3
/*
* panel profiles
*/
#define PANEL_PROFILE_CUSTOM 0
#define PANEL_PROFILE_OLD 1
#define PANEL_PROFILE_NEW 2
#define PANEL_PROFILE_HANTRONIX 3
#define PANEL_PROFILE_NEXCOM 4
#define PANEL_PROFILE_LARGE 5
/*
* Construct custom config from the kernel's configuration
*/
#define DEFAULT_PROFILE PANEL_PROFILE_LARGE
#define DEFAULT_PARPORT 0
#define DEFAULT_LCD LCD_TYPE_OLD
#define DEFAULT_KEYPAD KEYPAD_TYPE_OLD
#define DEFAULT_LCD_WIDTH 40
#define DEFAULT_LCD_BWIDTH 40
#define DEFAULT_LCD_HWIDTH 64
#define DEFAULT_LCD_HEIGHT 2
#define DEFAULT_LCD_PROTO LCD_PROTO_PARALLEL
#define DEFAULT_LCD_PIN_E PIN_AUTOLF
#define DEFAULT_LCD_PIN_RS PIN_SELECP
#define DEFAULT_LCD_PIN_RW PIN_INITP
#define DEFAULT_LCD_PIN_SCL PIN_STROBE
#define DEFAULT_LCD_PIN_SDA PIN_D0
#define DEFAULT_LCD_PIN_BL PIN_NOT_SET
#define DEFAULT_LCD_CHARSET LCD_CHARSET_NORMAL
#ifdef CONFIG_PANEL_PROFILE
#undef DEFAULT_PROFILE
#define DEFAULT_PROFILE CONFIG_PANEL_PROFILE
#endif
#ifdef CONFIG_PANEL_PARPORT
#undef DEFAULT_PARPORT
#define DEFAULT_PARPORT CONFIG_PANEL_PARPORT
#endif
#if DEFAULT_PROFILE == 0 /* custom */
#ifdef CONFIG_PANEL_KEYPAD
#undef DEFAULT_KEYPAD
#define DEFAULT_KEYPAD CONFIG_PANEL_KEYPAD
#endif
#ifdef CONFIG_PANEL_LCD
#undef DEFAULT_LCD
#define DEFAULT_LCD CONFIG_PANEL_LCD
#endif
#ifdef CONFIG_PANEL_LCD_WIDTH
#undef DEFAULT_LCD_WIDTH
#define DEFAULT_LCD_WIDTH CONFIG_PANEL_LCD_WIDTH
#endif
#ifdef CONFIG_PANEL_LCD_BWIDTH
#undef DEFAULT_LCD_BWIDTH
#define DEFAULT_LCD_BWIDTH CONFIG_PANEL_LCD_BWIDTH
#endif
#ifdef CONFIG_PANEL_LCD_HWIDTH
#undef DEFAULT_LCD_HWIDTH
#define DEFAULT_LCD_HWIDTH CONFIG_PANEL_LCD_HWIDTH
#endif
#ifdef CONFIG_PANEL_LCD_HEIGHT
#undef DEFAULT_LCD_HEIGHT
#define DEFAULT_LCD_HEIGHT CONFIG_PANEL_LCD_HEIGHT
#endif
#ifdef CONFIG_PANEL_LCD_PROTO
#undef DEFAULT_LCD_PROTO
#define DEFAULT_LCD_PROTO CONFIG_PANEL_LCD_PROTO
#endif
#ifdef CONFIG_PANEL_LCD_PIN_E
#undef DEFAULT_LCD_PIN_E
#define DEFAULT_LCD_PIN_E CONFIG_PANEL_LCD_PIN_E
#endif
#ifdef CONFIG_PANEL_LCD_PIN_RS
#undef DEFAULT_LCD_PIN_RS
#define DEFAULT_LCD_PIN_RS CONFIG_PANEL_LCD_PIN_RS
#endif
#ifdef CONFIG_PANEL_LCD_PIN_RW
#undef DEFAULT_LCD_PIN_RW
#define DEFAULT_LCD_PIN_RW CONFIG_PANEL_LCD_PIN_RW
#endif
#ifdef CONFIG_PANEL_LCD_PIN_SCL
#undef DEFAULT_LCD_PIN_SCL
#define DEFAULT_LCD_PIN_SCL CONFIG_PANEL_LCD_PIN_SCL
#endif
#ifdef CONFIG_PANEL_LCD_PIN_SDA
#undef DEFAULT_LCD_PIN_SDA
#define DEFAULT_LCD_PIN_SDA CONFIG_PANEL_LCD_PIN_SDA
#endif
#ifdef CONFIG_PANEL_LCD_PIN_BL
#undef DEFAULT_LCD_PIN_BL
#define DEFAULT_LCD_PIN_BL CONFIG_PANEL_LCD_PIN_BL
#endif
#ifdef CONFIG_PANEL_LCD_CHARSET
#undef DEFAULT_LCD_CHARSET
#define DEFAULT_LCD_CHARSET CONFIG_PANEL_LCD_CHARSET
#endif
#endif /* DEFAULT_PROFILE == 0 */
/* global variables */
static int keypad_open_cnt; /* #times opened */
static int lcd_open_cnt; /* #times opened */
static struct pardevice *pprt;
static int lcd_initialized;
static int keypad_initialized;
static int light_tempo;
static char lcd_must_clear;
static char lcd_left_shift;
static char init_in_progress;
static void (*lcd_write_cmd) (int);
static void (*lcd_write_data) (int);
static void (*lcd_clear_fast) (void);
static DEFINE_SPINLOCK(pprt_lock);
static struct timer_list scan_timer;
MODULE_DESCRIPTION("Generic parallel port LCD/Keypad driver");
static int parport = -1;
module_param(parport, int, 0000);
MODULE_PARM_DESC(parport, "Parallel port index (0=lpt1, 1=lpt2, ...)");
static int lcd_height = -1;
module_param(lcd_height, int, 0000);
MODULE_PARM_DESC(lcd_height, "Number of lines on the LCD");
static int lcd_width = -1;
module_param(lcd_width, int, 0000);
MODULE_PARM_DESC(lcd_width, "Number of columns on the LCD");
static int lcd_bwidth = -1; /* internal buffer width (usually 40) */
module_param(lcd_bwidth, int, 0000);
MODULE_PARM_DESC(lcd_bwidth, "Internal LCD line width (40)");
static int lcd_hwidth = -1; /* hardware buffer width (usually 64) */
module_param(lcd_hwidth, int, 0000);
MODULE_PARM_DESC(lcd_hwidth, "LCD line hardware address (64)");
static int lcd_enabled = -1;
module_param(lcd_enabled, int, 0000);
MODULE_PARM_DESC(lcd_enabled, "Deprecated option, use lcd_type instead");
static int keypad_enabled = -1;
module_param(keypad_enabled, int, 0000);
MODULE_PARM_DESC(keypad_enabled, "Deprecated option, use keypad_type instead");
static int lcd_type = -1;
module_param(lcd_type, int, 0000);
MODULE_PARM_DESC(lcd_type,
"LCD type: 0=none, 1=old //, 2=serial ks0074, "
"3=hantronix //, 4=nexcom //, 5=compiled-in");
static int lcd_proto = -1;
module_param(lcd_proto, int, 0000);
MODULE_PARM_DESC(lcd_proto,
"LCD communication: 0=parallel (//), 1=serial,"
"2=TI LCD Interface");
static int lcd_charset = -1;
module_param(lcd_charset, int, 0000);
MODULE_PARM_DESC(lcd_charset, "LCD character set: 0=standard, 1=KS0074");
static int keypad_type = -1;
module_param(keypad_type, int, 0000);
MODULE_PARM_DESC(keypad_type,
"Keypad type: 0=none, 1=old 6 keys, 2=new 6+1 keys, "
"3=nexcom 4 keys");
static int profile = DEFAULT_PROFILE;
module_param(profile, int, 0000);
MODULE_PARM_DESC(profile,
"1=16x2 old kp; 2=serial 16x2, new kp; 3=16x2 hantronix; "
"4=16x2 nexcom; default=40x2, old kp");
/*
* These are the parallel port pins the LCD control signals are connected to.
* Set this to 0 if the signal is not used. Set it to its opposite value
* (negative) if the signal is negated. -MAXINT is used to indicate that the
* pin has not been explicitly specified.
*
* WARNING! no check will be performed about collisions with keypad !
*/
static int lcd_e_pin = PIN_NOT_SET;
module_param(lcd_e_pin, int, 0000);
MODULE_PARM_DESC(lcd_e_pin,
"# of the // port pin connected to LCD 'E' signal, "
"with polarity (-17..17)");
static int lcd_rs_pin = PIN_NOT_SET;
module_param(lcd_rs_pin, int, 0000);
MODULE_PARM_DESC(lcd_rs_pin,
"# of the // port pin connected to LCD 'RS' signal, "
"with polarity (-17..17)");
static int lcd_rw_pin = PIN_NOT_SET;
module_param(lcd_rw_pin, int, 0000);
MODULE_PARM_DESC(lcd_rw_pin,
"# of the // port pin connected to LCD 'RW' signal, "
"with polarity (-17..17)");
static int lcd_bl_pin = PIN_NOT_SET;
module_param(lcd_bl_pin, int, 0000);
MODULE_PARM_DESC(lcd_bl_pin,
"# of the // port pin connected to LCD backlight, "
"with polarity (-17..17)");
static int lcd_da_pin = PIN_NOT_SET;
module_param(lcd_da_pin, int, 0000);
MODULE_PARM_DESC(lcd_da_pin,
"# of the // port pin connected to serial LCD 'SDA' "
"signal, with polarity (-17..17)");
static int lcd_cl_pin = PIN_NOT_SET;
module_param(lcd_cl_pin, int, 0000);
MODULE_PARM_DESC(lcd_cl_pin,
"# of the // port pin connected to serial LCD 'SCL' "
"signal, with polarity (-17..17)");
static unsigned char *lcd_char_conv;
/* for some LCD drivers (ks0074) we need a charset conversion table. */
static unsigned char lcd_char_conv_ks0074[256] = {
/* 0|8 1|9 2|A 3|B 4|C 5|D 6|E 7|F */
/* 0x00 */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
/* 0x08 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
/* 0x10 */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
/* 0x18 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
/* 0x20 */ 0x20, 0x21, 0x22, 0x23, 0xa2, 0x25, 0x26, 0x27,
/* 0x28 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
/* 0x30 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
/* 0x38 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
/* 0x40 */ 0xa0, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
/* 0x48 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
/* 0x50 */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
/* 0x58 */ 0x58, 0x59, 0x5a, 0xfa, 0xfb, 0xfc, 0x1d, 0xc4,
/* 0x60 */ 0x96, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
/* 0x68 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
/* 0x70 */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
/* 0x78 */ 0x78, 0x79, 0x7a, 0xfd, 0xfe, 0xff, 0xce, 0x20,
/* 0x80 */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
/* 0x88 */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
/* 0x90 */ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
/* 0x98 */ 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
/* 0xA0 */ 0x20, 0x40, 0xb1, 0xa1, 0x24, 0xa3, 0xfe, 0x5f,
/* 0xA8 */ 0x22, 0xc8, 0x61, 0x14, 0x97, 0x2d, 0xad, 0x96,
/* 0xB0 */ 0x80, 0x8c, 0x82, 0x83, 0x27, 0x8f, 0x86, 0xdd,
/* 0xB8 */ 0x2c, 0x81, 0x6f, 0x15, 0x8b, 0x8a, 0x84, 0x60,
/* 0xC0 */ 0xe2, 0xe2, 0xe2, 0x5b, 0x5b, 0xae, 0xbc, 0xa9,
/* 0xC8 */ 0xc5, 0xbf, 0xc6, 0xf1, 0xe3, 0xe3, 0xe3, 0xe3,
/* 0xD0 */ 0x44, 0x5d, 0xa8, 0xe4, 0xec, 0xec, 0x5c, 0x78,
/* 0xD8 */ 0xab, 0xa6, 0xe5, 0x5e, 0x5e, 0xe6, 0xaa, 0xbe,
/* 0xE0 */ 0x7f, 0xe7, 0xaf, 0x7b, 0x7b, 0xaf, 0xbd, 0xc8,
/* 0xE8 */ 0xa4, 0xa5, 0xc7, 0xf6, 0xa7, 0xe8, 0x69, 0x69,
/* 0xF0 */ 0xed, 0x7d, 0xa8, 0xe4, 0xec, 0x5c, 0x5c, 0x25,
/* 0xF8 */ 0xac, 0xa6, 0xea, 0xef, 0x7e, 0xeb, 0xb2, 0x79,
};
char old_keypad_profile[][4][9] = {
{"S0", "Left\n", "Left\n", ""},
{"S1", "Down\n", "Down\n", ""},
{"S2", "Up\n", "Up\n", ""},
{"S3", "Right\n", "Right\n", ""},
{"S4", "Esc\n", "Esc\n", ""},
{"S5", "Ret\n", "Ret\n", ""},
{"", "", "", ""}
};
/* signals, press, repeat, release */
char new_keypad_profile[][4][9] = {
{"S0", "Left\n", "Left\n", ""},
{"S1", "Down\n", "Down\n", ""},
{"S2", "Up\n", "Up\n", ""},
{"S3", "Right\n", "Right\n", ""},
{"S4s5", "", "Esc\n", "Esc\n"},
{"s4S5", "", "Ret\n", "Ret\n"},
{"S4S5", "Help\n", "", ""},
/* add new signals above this line */
{"", "", "", ""}
};
/* signals, press, repeat, release */
char nexcom_keypad_profile[][4][9] = {
{"a-p-e-", "Down\n", "Down\n", ""},
{"a-p-E-", "Ret\n", "Ret\n", ""},
{"a-P-E-", "Esc\n", "Esc\n", ""},
{"a-P-e-", "Up\n", "Up\n", ""},
/* add new signals above this line */
{"", "", "", ""}
};
static char (*keypad_profile)[4][9] = old_keypad_profile;
/* FIXME: this should be converted to a bit array containing signals states */
static struct {
unsigned char e; /* parallel LCD E (data latch on falling edge) */
unsigned char rs; /* parallel LCD RS (0 = cmd, 1 = data) */
unsigned char rw; /* parallel LCD R/W (0 = W, 1 = R) */
unsigned char bl; /* parallel LCD backlight (0 = off, 1 = on) */
unsigned char cl; /* serial LCD clock (latch on rising edge) */
unsigned char da; /* serial LCD data */
} bits;
static void init_scan_timer(void);
/* sets data port bits according to current signals values */
static int set_data_bits(void)
{
int val, bit;
val = r_dtr(pprt);
for (bit = 0; bit < LCD_BITS; bit++)
val &= lcd_bits[LCD_PORT_D][bit][BIT_MSK];
val |= lcd_bits[LCD_PORT_D][LCD_BIT_E][bits.e]
| lcd_bits[LCD_PORT_D][LCD_BIT_RS][bits.rs]
| lcd_bits[LCD_PORT_D][LCD_BIT_RW][bits.rw]
| lcd_bits[LCD_PORT_D][LCD_BIT_BL][bits.bl]
| lcd_bits[LCD_PORT_D][LCD_BIT_CL][bits.cl]
| lcd_bits[LCD_PORT_D][LCD_BIT_DA][bits.da];
w_dtr(pprt, val);
return val;
}
/* sets ctrl port bits according to current signals values */
static int set_ctrl_bits(void)
{
int val, bit;
val = r_ctr(pprt);
for (bit = 0; bit < LCD_BITS; bit++)
val &= lcd_bits[LCD_PORT_C][bit][BIT_MSK];
val |= lcd_bits[LCD_PORT_C][LCD_BIT_E][bits.e]
| lcd_bits[LCD_PORT_C][LCD_BIT_RS][bits.rs]
| lcd_bits[LCD_PORT_C][LCD_BIT_RW][bits.rw]
| lcd_bits[LCD_PORT_C][LCD_BIT_BL][bits.bl]
| lcd_bits[LCD_PORT_C][LCD_BIT_CL][bits.cl]
| lcd_bits[LCD_PORT_C][LCD_BIT_DA][bits.da];
w_ctr(pprt, val);
return val;
}
/* sets ctrl & data port bits according to current signals values */
static void panel_set_bits(void)
{
set_data_bits();
set_ctrl_bits();
}
/*
* Converts a parallel port pin (from -25 to 25) to data and control ports
* masks, and data and control port bits. The signal will be considered
* unconnected if it's on pin 0 or an invalid pin (<-25 or >25).
*
* Result will be used this way :
* out(dport, in(dport) & d_val[2] | d_val[signal_state])
* out(cport, in(cport) & c_val[2] | c_val[signal_state])
*/
void pin_to_bits(int pin, unsigned char *d_val, unsigned char *c_val)
{
int d_bit, c_bit, inv;
d_val[0] = c_val[0] = d_val[1] = c_val[1] = 0;
d_val[2] = c_val[2] = 0xFF;
if (pin == 0)
return;
inv = (pin < 0);
if (inv)
pin = -pin;
d_bit = c_bit = 0;
switch (pin) {
case PIN_STROBE: /* strobe, inverted */
c_bit = PNL_PSTROBE;
inv = !inv;
break;
case PIN_D0...PIN_D7: /* D0 - D7 = 2 - 9 */
d_bit = 1 << (pin - 2);
break;
case PIN_AUTOLF: /* autofeed, inverted */
c_bit = PNL_PAUTOLF;
inv = !inv;
break;
case PIN_INITP: /* init, direct */
c_bit = PNL_PINITP;
break;
case PIN_SELECP: /* select_in, inverted */
c_bit = PNL_PSELECP;
inv = !inv;
break;
default: /* unknown pin, ignore */
break;
}
if (c_bit) {
c_val[2] &= ~c_bit;
c_val[!inv] = c_bit;
} else if (d_bit) {
d_val[2] &= ~d_bit;
d_val[!inv] = d_bit;
}
}
/* sleeps that many milliseconds with a reschedule */
static void long_sleep(int ms)
{
if (in_interrupt())
mdelay(ms);
else {
current->state = TASK_INTERRUPTIBLE;
schedule_timeout((ms * HZ + 999) / 1000);
}
}
/* send a serial byte to the LCD panel. The caller is responsible for locking
if needed. */
static void lcd_send_serial(int byte)
{
int bit;
/* the data bit is set on D0, and the clock on STROBE.
* LCD reads D0 on STROBE's rising edge. */
for (bit = 0; bit < 8; bit++) {
bits.cl = BIT_CLR; /* CLK low */
panel_set_bits();
bits.da = byte & 1;
panel_set_bits();
udelay(2); /* maintain the data during 2 us before CLK up */
bits.cl = BIT_SET; /* CLK high */
panel_set_bits();
udelay(1); /* maintain the strobe during 1 us */
byte >>= 1;
}
}
/* turn the backlight on or off */
static void lcd_backlight(int on)
{
if (lcd_bl_pin == PIN_NONE)
return;
/* The backlight is activated by seting the AUTOFEED line to +5V */
spin_lock(&pprt_lock);
bits.bl = on;
panel_set_bits();
spin_unlock(&pprt_lock);
}
/* send a command to the LCD panel in serial mode */
static void lcd_write_cmd_s(int cmd)
{
spin_lock(&pprt_lock);
lcd_send_serial(0x1F); /* R/W=W, RS=0 */
lcd_send_serial(cmd & 0x0F);
lcd_send_serial((cmd >> 4) & 0x0F);
udelay(40); /* the shortest command takes at least 40 us */
spin_unlock(&pprt_lock);
}
/* send data to the LCD panel in serial mode */
static void lcd_write_data_s(int data)
{
spin_lock(&pprt_lock);
lcd_send_serial(0x5F); /* R/W=W, RS=1 */
lcd_send_serial(data & 0x0F);
lcd_send_serial((data >> 4) & 0x0F);
udelay(40); /* the shortest data takes at least 40 us */
spin_unlock(&pprt_lock);
}
/* send a command to the LCD panel in 8 bits parallel mode */
static void lcd_write_cmd_p8(int cmd)
{
spin_lock(&pprt_lock);
/* present the data to the data port */
w_dtr(pprt, cmd);
udelay(20); /* maintain the data during 20 us before the strobe */
bits.e = BIT_SET;
bits.rs = BIT_CLR;
bits.rw = BIT_CLR;
set_ctrl_bits();
udelay(40); /* maintain the strobe during 40 us */
bits.e = BIT_CLR;
set_ctrl_bits();
udelay(120); /* the shortest command takes at least 120 us */
spin_unlock(&pprt_lock);
}
/* send data to the LCD panel in 8 bits parallel mode */
static void lcd_write_data_p8(int data)
{
spin_lock(&pprt_lock);
/* present the data to the data port */
w_dtr(pprt, data);
udelay(20); /* maintain the data during 20 us before the strobe */
bits.e = BIT_SET;
bits.rs = BIT_SET;
bits.rw = BIT_CLR;
set_ctrl_bits();
udelay(40); /* maintain the strobe during 40 us */
bits.e = BIT_CLR;
set_ctrl_bits();
udelay(45); /* the shortest data takes at least 45 us */
spin_unlock(&pprt_lock);
}
/* send a command to the TI LCD panel */
static void lcd_write_cmd_tilcd(int cmd)
{
spin_lock(&pprt_lock);
/* present the data to the control port */
w_ctr(pprt, cmd);
udelay(60);
spin_unlock(&pprt_lock);
}
/* send data to the TI LCD panel */
static void lcd_write_data_tilcd(int data)
{
spin_lock(&pprt_lock);
/* present the data to the data port */
w_dtr(pprt, data);
udelay(60);
spin_unlock(&pprt_lock);
}
static void lcd_gotoxy(void)
{
lcd_write_cmd(0x80 /* set DDRAM address */
| (lcd_addr_y ? lcd_hwidth : 0)
/* we force the cursor to stay at the end of the
line if it wants to go farther */
| ((lcd_addr_x < lcd_bwidth) ? lcd_addr_x &
(lcd_hwidth - 1) : lcd_bwidth - 1));
}
static void lcd_print(char c)
{
if (lcd_addr_x < lcd_bwidth) {
if (lcd_char_conv != NULL)
c = lcd_char_conv[(unsigned char)c];
lcd_write_data(c);
lcd_addr_x++;
}
/* prevents the cursor from wrapping onto the next line */
if (lcd_addr_x == lcd_bwidth)
lcd_gotoxy();
}
/* fills the display with spaces and resets X/Y */
static void lcd_clear_fast_s(void)
{
int pos;
lcd_addr_x = lcd_addr_y = 0;
lcd_gotoxy();
spin_lock(&pprt_lock);
for (pos = 0; pos < lcd_height * lcd_hwidth; pos++) {
lcd_send_serial(0x5F); /* R/W=W, RS=1 */
lcd_send_serial(' ' & 0x0F);
lcd_send_serial((' ' >> 4) & 0x0F);
udelay(40); /* the shortest data takes at least 40 us */
}
spin_unlock(&pprt_lock);
lcd_addr_x = lcd_addr_y = 0;
lcd_gotoxy();
}
/* fills the display with spaces and resets X/Y */
static void lcd_clear_fast_p8(void)
{
int pos;
lcd_addr_x = lcd_addr_y = 0;
lcd_gotoxy();
spin_lock(&pprt_lock);
for (pos = 0; pos < lcd_height * lcd_hwidth; pos++) {
/* present the data to the data port */
w_dtr(pprt, ' ');
/* maintain the data during 20 us before the strobe */
udelay(20);
bits.e = BIT_SET;
bits.rs = BIT_SET;
bits.rw = BIT_CLR;
set_ctrl_bits();
/* maintain the strobe during 40 us */
udelay(40);
bits.e = BIT_CLR;
set_ctrl_bits();
/* the shortest data takes at least 45 us */
udelay(45);
}
spin_unlock(&pprt_lock);
lcd_addr_x = lcd_addr_y = 0;
lcd_gotoxy();
}
/* fills the display with spaces and resets X/Y */
static void lcd_clear_fast_tilcd(void)
{
int pos;
lcd_addr_x = lcd_addr_y = 0;
lcd_gotoxy();
spin_lock(&pprt_lock);
for (pos = 0; pos < lcd_height * lcd_hwidth; pos++) {
/* present the data to the data port */
w_dtr(pprt, ' ');
udelay(60);
}
spin_unlock(&pprt_lock);
lcd_addr_x = lcd_addr_y = 0;
lcd_gotoxy();
}
/* clears the display and resets X/Y */
static void lcd_clear_display(void)
{
lcd_write_cmd(0x01); /* clear display */
lcd_addr_x = lcd_addr_y = 0;
/* we must wait a few milliseconds (15) */
long_sleep(15);
}
static void lcd_init_display(void)
{
lcd_flags = ((lcd_height > 1) ? LCD_FLAG_N : 0)
| LCD_FLAG_D | LCD_FLAG_C | LCD_FLAG_B;
long_sleep(20); /* wait 20 ms after power-up for the paranoid */
lcd_write_cmd(0x30); /* 8bits, 1 line, small fonts */
long_sleep(10);
lcd_write_cmd(0x30); /* 8bits, 1 line, small fonts */
long_sleep(10);
lcd_write_cmd(0x30); /* 8bits, 1 line, small fonts */
long_sleep(10);
lcd_write_cmd(0x30 /* set font height and lines number */
| ((lcd_flags & LCD_FLAG_F) ? 4 : 0)
| ((lcd_flags & LCD_FLAG_N) ? 8 : 0)
);
long_sleep(10);
lcd_write_cmd(0x08); /* display off, cursor off, blink off */
long_sleep(10);
lcd_write_cmd(0x08 /* set display mode */
| ((lcd_flags & LCD_FLAG_D) ? 4 : 0)
| ((lcd_flags & LCD_FLAG_C) ? 2 : 0)
| ((lcd_flags & LCD_FLAG_B) ? 1 : 0)
);
lcd_backlight((lcd_flags & LCD_FLAG_L) ? 1 : 0);
long_sleep(10);
/* entry mode set : increment, cursor shifting */
lcd_write_cmd(0x06);
lcd_clear_display();
}
/*
* These are the file operation function for user access to /dev/lcd
* This function can also be called from inside the kernel, by
* setting file and ppos to NULL.
*
*/
static inline int handle_lcd_special_code(void)
{
/* LCD special codes */
int processed = 0;
char *esc = lcd_escape + 2;
int oldflags = lcd_flags;
/* check for display mode flags */
switch (*esc) {
case 'D': /* Display ON */
lcd_flags |= LCD_FLAG_D;
processed = 1;
break;
case 'd': /* Display OFF */
lcd_flags &= ~LCD_FLAG_D;
processed = 1;
break;
case 'C': /* Cursor ON */
lcd_flags |= LCD_FLAG_C;
processed = 1;
break;
case 'c': /* Cursor OFF */
lcd_flags &= ~LCD_FLAG_C;
processed = 1;
break;
case 'B': /* Blink ON */
lcd_flags |= LCD_FLAG_B;
processed = 1;
break;
case 'b': /* Blink OFF */
lcd_flags &= ~LCD_FLAG_B;
processed = 1;
break;
case '+': /* Back light ON */
lcd_flags |= LCD_FLAG_L;
processed = 1;
break;
case '-': /* Back light OFF */
lcd_flags &= ~LCD_FLAG_L;
processed = 1;
break;
case '*':
/* flash back light using the keypad timer */
if (scan_timer.function != NULL) {
if (light_tempo == 0 && ((lcd_flags & LCD_FLAG_L) == 0))
lcd_backlight(1);
light_tempo = FLASH_LIGHT_TEMPO;
}
processed = 1;
break;
case 'f': /* Small Font */
lcd_flags &= ~LCD_FLAG_F;
processed = 1;
break;
case 'F': /* Large Font */
lcd_flags |= LCD_FLAG_F;
processed = 1;
break;
case 'n': /* One Line */
lcd_flags &= ~LCD_FLAG_N;
processed = 1;
break;
case 'N': /* Two Lines */
lcd_flags |= LCD_FLAG_N;
break;
case 'l': /* Shift Cursor Left */
if (lcd_addr_x > 0) {
/* back one char if not at end of line */
if (lcd_addr_x < lcd_bwidth)
lcd_write_cmd(0x10);
lcd_addr_x--;
}
processed = 1;
break;
case 'r': /* shift cursor right */
if (lcd_addr_x < lcd_width) {
/* allow the cursor to pass the end of the line */
if (lcd_addr_x <
(lcd_bwidth - 1))
lcd_write_cmd(0x14);
lcd_addr_x++;
}
processed = 1;
break;
case 'L': /* shift display left */
lcd_left_shift++;
lcd_write_cmd(0x18);
processed = 1;
break;
case 'R': /* shift display right */
lcd_left_shift--;
lcd_write_cmd(0x1C);
processed = 1;
break;
case 'k': { /* kill end of line */
int x;
for (x = lcd_addr_x; x < lcd_bwidth; x++)
lcd_write_data(' ');
/* restore cursor position */
lcd_gotoxy();
processed = 1;
break;
}
case 'I': /* reinitialize display */
lcd_init_display();
lcd_left_shift = 0;
processed = 1;
break;
case 'G': {
/* Generator : LGcxxxxx...xx; must have <c> between '0'
* and '7', representing the numerical ASCII code of the
* redefined character, and <xx...xx> a sequence of 16
* hex digits representing 8 bytes for each character.
* Most LCDs will only use 5 lower bits of the 7 first
* bytes.
*/
unsigned char cgbytes[8];
unsigned char cgaddr;
int cgoffset;
int shift;
char value;
int addr;
if (strchr(esc, ';') == NULL)
break;
esc++;
cgaddr = *(esc++) - '0';
if (cgaddr > 7) {
processed = 1;
break;
}
cgoffset = 0;
shift = 0;
value = 0;
while (*esc && cgoffset < 8) {
shift ^= 4;
if (*esc >= '0' && *esc <= '9')
value |= (*esc - '0') << shift;
else if (*esc >= 'A' && *esc <= 'Z')
value |= (*esc - 'A' + 10) << shift;
else if (*esc >= 'a' && *esc <= 'z')
value |= (*esc - 'a' + 10) << shift;
else {
esc++;
continue;
}
if (shift == 0) {
cgbytes[cgoffset++] = value;
value = 0;
}
esc++;
}
lcd_write_cmd(0x40 | (cgaddr * 8));
for (addr = 0; addr < cgoffset; addr++)
lcd_write_data(cgbytes[addr]);
/* ensures that we stop writing to CGRAM */
lcd_gotoxy();
processed = 1;
break;
}
case 'x': /* gotoxy : LxXXX[yYYY]; */
case 'y': /* gotoxy : LyYYY[xXXX]; */
if (strchr(esc, ';') == NULL)
break;
while (*esc) {
char *endp;
if (*esc == 'x') {
esc++;
lcd_addr_x = simple_strtoul(esc, &endp, 10);
esc = endp;
} else if (*esc == 'y') {
esc++;
lcd_addr_y = simple_strtoul(esc, &endp, 10);
esc = endp;
} else
break;
}
lcd_gotoxy();
processed = 1;
break;
}
/* Check wether one flag was changed */
if (oldflags != lcd_flags) {
/* check whether one of B,C,D flags were changed */
if ((oldflags ^ lcd_flags) &
(LCD_FLAG_B | LCD_FLAG_C | LCD_FLAG_D))
/* set display mode */
lcd_write_cmd(0x08
| ((lcd_flags & LCD_FLAG_D) ? 4 : 0)
| ((lcd_flags & LCD_FLAG_C) ? 2 : 0)
| ((lcd_flags & LCD_FLAG_B) ? 1 : 0));
/* check whether one of F,N flags was changed */
else if ((oldflags ^ lcd_flags) & (LCD_FLAG_F | LCD_FLAG_N))
lcd_write_cmd(0x30
| ((lcd_flags & LCD_FLAG_F) ? 4 : 0)
| ((lcd_flags & LCD_FLAG_N) ? 8 : 0));
/* check wether L flag was changed */
else if ((oldflags ^ lcd_flags) & (LCD_FLAG_L)) {
if (lcd_flags & (LCD_FLAG_L))
lcd_backlight(1);
else if (light_tempo == 0)
/* switch off the light only when the tempo
lighting is gone */
lcd_backlight(0);
}
}
return processed;
}
static ssize_t lcd_write(struct file *file,
const char *buf, size_t count, loff_t *ppos)
{
const char *tmp = buf;
char c;
for (; count-- > 0; (ppos ? (*ppos)++ : 0), ++tmp) {
if (!in_interrupt() && (((count + 1) & 0x1f) == 0))
/* let's be a little nice with other processes
that need some CPU */
schedule();
if (ppos == NULL && file == NULL)
/* let's not use get_user() from the kernel ! */
c = *tmp;
else if (get_user(c, tmp))
return -EFAULT;
/* first, we'll test if we're in escape mode */
if ((c != '\n') && lcd_escape_len >= 0) {
/* yes, let's add this char to the buffer */
lcd_escape[lcd_escape_len++] = c;
lcd_escape[lcd_escape_len] = 0;
} else {
/* aborts any previous escape sequence */
lcd_escape_len = -1;
switch (c) {
case LCD_ESCAPE_CHAR:
/* start of an escape sequence */
lcd_escape_len = 0;
lcd_escape[lcd_escape_len] = 0;
break;
case '\b':
/* go back one char and clear it */
if (lcd_addr_x > 0) {
/* check if we're not at the
end of the line */
if (lcd_addr_x < lcd_bwidth)
/* back one char */
lcd_write_cmd(0x10);
lcd_addr_x--;
}
/* replace with a space */
lcd_write_data(' ');
/* back one char again */
lcd_write_cmd(0x10);
break;
case '\014':
/* quickly clear the display */
lcd_clear_fast();
break;
case '\n':
/* flush the remainder of the current line and
go to the beginning of the next line */
for (; lcd_addr_x < lcd_bwidth; lcd_addr_x++)
lcd_write_data(' ');
lcd_addr_x = 0;
lcd_addr_y = (lcd_addr_y + 1) % lcd_height;
lcd_gotoxy();
break;
case '\r':
/* go to the beginning of the same line */
lcd_addr_x = 0;
lcd_gotoxy();
break;
case '\t':
/* print a space instead of the tab */
lcd_print(' ');
break;
default:
/* simply print this char */
lcd_print(c);
break;
}
}
/* now we'll see if we're in an escape mode and if the current
escape sequence can be understood. */
if (lcd_escape_len >= 2) {
int processed = 0;
if (!strcmp(lcd_escape, "[2J")) {
/* clear the display */
lcd_clear_fast();
processed = 1;
} else if (!strcmp(lcd_escape, "[H")) {
/* cursor to home */
lcd_addr_x = lcd_addr_y = 0;
lcd_gotoxy();
processed = 1;
}
/* codes starting with ^[[L */
else if ((lcd_escape_len >= 3) &&
(lcd_escape[0] == '[') &&
(lcd_escape[1] == 'L')) {
processed = handle_lcd_special_code();
}
/* LCD special escape codes */
/* flush the escape sequence if it's been processed
or if it is getting too long. */
if (processed || (lcd_escape_len >= LCD_ESCAPE_LEN))
lcd_escape_len = -1;
} /* escape codes */
}
return tmp - buf;
}
static int lcd_open(struct inode *inode, struct file *file)
{
if (lcd_open_cnt)
return -EBUSY; /* open only once at a time */
if (file->f_mode & FMODE_READ) /* device is write-only */
return -EPERM;
if (lcd_must_clear) {
lcd_clear_display();
lcd_must_clear = 0;
}
lcd_open_cnt++;
return nonseekable_open(inode, file);
}
static int lcd_release(struct inode *inode, struct file *file)
{
lcd_open_cnt--;
return 0;
}
static const struct file_operations lcd_fops = {
.write = lcd_write,
.open = lcd_open,
.release = lcd_release,
.llseek = no_llseek,
};
static struct miscdevice lcd_dev = {
LCD_MINOR,
"lcd",
&lcd_fops
};
/* public function usable from the kernel for any purpose */
void panel_lcd_print(char *s)
{
if (lcd_enabled && lcd_initialized)
lcd_write(NULL, s, strlen(s), NULL);
}
/* initialize the LCD driver */
void lcd_init(void)
{
switch (lcd_type) {
case LCD_TYPE_OLD:
/* parallel mode, 8 bits */
if (lcd_proto < 0)
lcd_proto = LCD_PROTO_PARALLEL;
if (lcd_charset < 0)
lcd_charset = LCD_CHARSET_NORMAL;
if (lcd_e_pin == PIN_NOT_SET)
lcd_e_pin = PIN_STROBE;
if (lcd_rs_pin == PIN_NOT_SET)
lcd_rs_pin = PIN_AUTOLF;
if (lcd_width < 0)
lcd_width = 40;
if (lcd_bwidth < 0)
lcd_bwidth = 40;
if (lcd_hwidth < 0)
lcd_hwidth = 64;
if (lcd_height < 0)
lcd_height = 2;
break;
case LCD_TYPE_KS0074:
/* serial mode, ks0074 */
if (lcd_proto < 0)
lcd_proto = LCD_PROTO_SERIAL;
if (lcd_charset < 0)
lcd_charset = LCD_CHARSET_KS0074;
if (lcd_bl_pin == PIN_NOT_SET)
lcd_bl_pin = PIN_AUTOLF;
if (lcd_cl_pin == PIN_NOT_SET)
lcd_cl_pin = PIN_STROBE;
if (lcd_da_pin == PIN_NOT_SET)
lcd_da_pin = PIN_D0;
if (lcd_width < 0)
lcd_width = 16;
if (lcd_bwidth < 0)
lcd_bwidth = 40;
if (lcd_hwidth < 0)
lcd_hwidth = 16;
if (lcd_height < 0)
lcd_height = 2;
break;
case LCD_TYPE_NEXCOM:
/* parallel mode, 8 bits, generic */
if (lcd_proto < 0)
lcd_proto = LCD_PROTO_PARALLEL;
if (lcd_charset < 0)
lcd_charset = LCD_CHARSET_NORMAL;
if (lcd_e_pin == PIN_NOT_SET)
lcd_e_pin = PIN_AUTOLF;
if (lcd_rs_pin == PIN_NOT_SET)
lcd_rs_pin = PIN_SELECP;
if (lcd_rw_pin == PIN_NOT_SET)
lcd_rw_pin = PIN_INITP;
if (lcd_width < 0)
lcd_width = 16;
if (lcd_bwidth < 0)
lcd_bwidth = 40;
if (lcd_hwidth < 0)
lcd_hwidth = 64;
if (lcd_height < 0)
lcd_height = 2;
break;
case LCD_TYPE_CUSTOM:
/* customer-defined */
if (lcd_proto < 0)
lcd_proto = DEFAULT_LCD_PROTO;
if (lcd_charset < 0)
lcd_charset = DEFAULT_LCD_CHARSET;
/* default geometry will be set later */
break;
case LCD_TYPE_HANTRONIX:
/* parallel mode, 8 bits, hantronix-like */
default:
if (lcd_proto < 0)
lcd_proto = LCD_PROTO_PARALLEL;
if (lcd_charset < 0)
lcd_charset = LCD_CHARSET_NORMAL;
if (lcd_e_pin == PIN_NOT_SET)
lcd_e_pin = PIN_STROBE;
if (lcd_rs_pin == PIN_NOT_SET)
lcd_rs_pin = PIN_SELECP;
if (lcd_width < 0)
lcd_width = 16;
if (lcd_bwidth < 0)
lcd_bwidth = 40;
if (lcd_hwidth < 0)
lcd_hwidth = 64;
if (lcd_height < 0)
lcd_height = 2;
break;
}
/* this is used to catch wrong and default values */
if (lcd_width <= 0)
lcd_width = DEFAULT_LCD_WIDTH;
if (lcd_bwidth <= 0)
lcd_bwidth = DEFAULT_LCD_BWIDTH;
if (lcd_hwidth <= 0)
lcd_hwidth = DEFAULT_LCD_HWIDTH;
if (lcd_height <= 0)
lcd_height = DEFAULT_LCD_HEIGHT;
if (lcd_proto == LCD_PROTO_SERIAL) { /* SERIAL */
lcd_write_cmd = lcd_write_cmd_s;
lcd_write_data = lcd_write_data_s;
lcd_clear_fast = lcd_clear_fast_s;
if (lcd_cl_pin == PIN_NOT_SET)
lcd_cl_pin = DEFAULT_LCD_PIN_SCL;
if (lcd_da_pin == PIN_NOT_SET)
lcd_da_pin = DEFAULT_LCD_PIN_SDA;
} else if (lcd_proto == LCD_PROTO_PARALLEL) { /* PARALLEL */
lcd_write_cmd = lcd_write_cmd_p8;
lcd_write_data = lcd_write_data_p8;
lcd_clear_fast = lcd_clear_fast_p8;
if (lcd_e_pin == PIN_NOT_SET)
lcd_e_pin = DEFAULT_LCD_PIN_E;
if (lcd_rs_pin == PIN_NOT_SET)
lcd_rs_pin = DEFAULT_LCD_PIN_RS;
if (lcd_rw_pin == PIN_NOT_SET)
lcd_rw_pin = DEFAULT_LCD_PIN_RW;
} else {
lcd_write_cmd = lcd_write_cmd_tilcd;
lcd_write_data = lcd_write_data_tilcd;
lcd_clear_fast = lcd_clear_fast_tilcd;
}
if (lcd_bl_pin == PIN_NOT_SET)
lcd_bl_pin = DEFAULT_LCD_PIN_BL;
if (lcd_e_pin == PIN_NOT_SET)
lcd_e_pin = PIN_NONE;
if (lcd_rs_pin == PIN_NOT_SET)
lcd_rs_pin = PIN_NONE;
if (lcd_rw_pin == PIN_NOT_SET)
lcd_rw_pin = PIN_NONE;
if (lcd_bl_pin == PIN_NOT_SET)
lcd_bl_pin = PIN_NONE;
if (lcd_cl_pin == PIN_NOT_SET)
lcd_cl_pin = PIN_NONE;
if (lcd_da_pin == PIN_NOT_SET)
lcd_da_pin = PIN_NONE;
if (lcd_charset < 0)
lcd_charset = DEFAULT_LCD_CHARSET;
if (lcd_charset == LCD_CHARSET_KS0074)
lcd_char_conv = lcd_char_conv_ks0074;
else
lcd_char_conv = NULL;
if (lcd_bl_pin != PIN_NONE)
init_scan_timer();
pin_to_bits(lcd_e_pin, lcd_bits[LCD_PORT_D][LCD_BIT_E],
lcd_bits[LCD_PORT_C][LCD_BIT_E]);
pin_to_bits(lcd_rs_pin, lcd_bits[LCD_PORT_D][LCD_BIT_RS],
lcd_bits[LCD_PORT_C][LCD_BIT_RS]);
pin_to_bits(lcd_rw_pin, lcd_bits[LCD_PORT_D][LCD_BIT_RW],
lcd_bits[LCD_PORT_C][LCD_BIT_RW]);
pin_to_bits(lcd_bl_pin, lcd_bits[LCD_PORT_D][LCD_BIT_BL],
lcd_bits[LCD_PORT_C][LCD_BIT_BL]);
pin_to_bits(lcd_cl_pin, lcd_bits[LCD_PORT_D][LCD_BIT_CL],
lcd_bits[LCD_PORT_C][LCD_BIT_CL]);
pin_to_bits(lcd_da_pin, lcd_bits[LCD_PORT_D][LCD_BIT_DA],
lcd_bits[LCD_PORT_C][LCD_BIT_DA]);
/* before this line, we must NOT send anything to the display.
* Since lcd_init_display() needs to write data, we have to
* enable mark the LCD initialized just before. */
lcd_initialized = 1;
lcd_init_display();
/* display a short message */
#ifdef CONFIG_PANEL_CHANGE_MESSAGE
#ifdef CONFIG_PANEL_BOOT_MESSAGE
panel_lcd_print("\x1b[Lc\x1b[Lb\x1b[L*" CONFIG_PANEL_BOOT_MESSAGE);
#endif
#else
panel_lcd_print("\x1b[Lc\x1b[Lb\x1b[L*Linux-" UTS_RELEASE "\nPanel-"
PANEL_VERSION);
#endif
lcd_addr_x = lcd_addr_y = 0;
/* clear the display on the next device opening */
lcd_must_clear = 1;
lcd_gotoxy();
}
/*
* These are the file operation function for user access to /dev/keypad
*/
static ssize_t keypad_read(struct file *file,
char *buf, size_t count, loff_t *ppos)
{
unsigned i = *ppos;
char *tmp = buf;
if (keypad_buflen == 0) {
if (file->f_flags & O_NONBLOCK)
return -EAGAIN;
interruptible_sleep_on(&keypad_read_wait);
if (signal_pending(current))
return -EINTR;
}
for (; count-- > 0 && (keypad_buflen > 0);
++i, ++tmp, --keypad_buflen) {
put_user(keypad_buffer[keypad_start], tmp);
keypad_start = (keypad_start + 1) % KEYPAD_BUFFER;
}
*ppos = i;
return tmp - buf;
}
static int keypad_open(struct inode *inode, struct file *file)
{
if (keypad_open_cnt)
return -EBUSY; /* open only once at a time */
if (file->f_mode & FMODE_WRITE) /* device is read-only */
return -EPERM;
keypad_buflen = 0; /* flush the buffer on opening */
keypad_open_cnt++;
return 0;
}
static int keypad_release(struct inode *inode, struct file *file)
{
keypad_open_cnt--;
return 0;
}
static const struct file_operations keypad_fops = {
.read = keypad_read, /* read */
.open = keypad_open, /* open */
.release = keypad_release, /* close */
.llseek = default_llseek,
};
static struct miscdevice keypad_dev = {
KEYPAD_MINOR,
"keypad",
&keypad_fops
};
static void keypad_send_key(char *string, int max_len)
{
if (init_in_progress)
return;
/* send the key to the device only if a process is attached to it. */
if (keypad_open_cnt > 0) {
while (max_len-- && keypad_buflen < KEYPAD_BUFFER && *string) {
keypad_buffer[(keypad_start + keypad_buflen++) %
KEYPAD_BUFFER] = *string++;
}
wake_up_interruptible(&keypad_read_wait);
}
}
/* this function scans all the bits involving at least one logical signal,
* and puts the results in the bitfield "phys_read" (one bit per established
* contact), and sets "phys_read_prev" to "phys_read".
*
* Note: to debounce input signals, we will only consider as switched a signal
* which is stable across 2 measures. Signals which are different between two
* reads will be kept as they previously were in their logical form (phys_prev).
* A signal which has just switched will have a 1 in
* (phys_read ^ phys_read_prev).
*/
static void phys_scan_contacts(void)
{
int bit, bitval;
char oldval;
char bitmask;
char gndmask;
phys_prev = phys_curr;
phys_read_prev = phys_read;
phys_read = 0; /* flush all signals */
/* keep track of old value, with all outputs disabled */
oldval = r_dtr(pprt) | scan_mask_o;
/* activate all keyboard outputs (active low) */
w_dtr(pprt, oldval & ~scan_mask_o);
/* will have a 1 for each bit set to gnd */
bitmask = PNL_PINPUT(r_str(pprt)) & scan_mask_i;
/* disable all matrix signals */
w_dtr(pprt, oldval);
/* now that all outputs are cleared, the only active input bits are
* directly connected to the ground
*/
/* 1 for each grounded input */
gndmask = PNL_PINPUT(r_str(pprt)) & scan_mask_i;
/* grounded inputs are signals 40-44 */
phys_read |= (pmask_t) gndmask << 40;
if (bitmask != gndmask) {
/* since clearing the outputs changed some inputs, we know
* that some input signals are currently tied to some outputs.
* So we'll scan them.
*/
for (bit = 0; bit < 8; bit++) {
bitval = 1 << bit;
if (!(scan_mask_o & bitval)) /* skip unused bits */
continue;
w_dtr(pprt, oldval & ~bitval); /* enable this output */
bitmask = PNL_PINPUT(r_str(pprt)) & ~gndmask;
phys_read |= (pmask_t) bitmask << (5 * bit);
}
w_dtr(pprt, oldval); /* disable all outputs */
}
/* this is easy: use old bits when they are flapping,
* use new ones when stable */
phys_curr = (phys_prev & (phys_read ^ phys_read_prev)) |
(phys_read & ~(phys_read ^ phys_read_prev));
}
static inline int input_state_high(struct logical_input *input)
{
#if 0
/* FIXME:
* this is an invalid test. It tries to catch
* transitions from single-key to multiple-key, but
* doesn't take into account the contacts polarity.
* The only solution to the problem is to parse keys
* from the most complex to the simplest combinations,
* and mark them as 'caught' once a combination
* matches, then unmatch it for all other ones.
*/
/* try to catch dangerous transitions cases :
* someone adds a bit, so this signal was a false
* positive resulting from a transition. We should
* invalidate the signal immediately and not call the
* release function.
* eg: 0 -(press A)-> A -(press B)-> AB : don't match A's release.
*/
if (((phys_prev & input->mask) == input->value)
&& ((phys_curr & input->mask) > input->value)) {
input->state = INPUT_ST_LOW; /* invalidate */
return 1;
}
#endif
if ((phys_curr & input->mask) == input->value) {
if ((input->type == INPUT_TYPE_STD) &&
(input->high_timer == 0)) {
input->high_timer++;
if (input->u.std.press_fct != NULL)
input->u.std.press_fct(input->u.std.press_data);
} else if (input->type == INPUT_TYPE_KBD) {
/* will turn on the light */
keypressed = 1;
if (input->high_timer == 0) {
char *press_str = input->u.kbd.press_str;
if (press_str[0])
keypad_send_key(press_str,
sizeof(press_str));
}
if (input->u.kbd.repeat_str[0]) {
char *repeat_str = input->u.kbd.repeat_str;
if (input->high_timer >= KEYPAD_REP_START) {
input->high_timer -= KEYPAD_REP_DELAY;
keypad_send_key(repeat_str,
sizeof(repeat_str));
}
/* we will need to come back here soon */
inputs_stable = 0;
}
if (input->high_timer < 255)
input->high_timer++;
}
return 1;
} else {
/* else signal falling down. Let's fall through. */
input->state = INPUT_ST_FALLING;
input->fall_timer = 0;
}
return 0;
}
static inline void input_state_falling(struct logical_input *input)
{
#if 0
/* FIXME !!! same comment as in input_state_high */
if (((phys_prev & input->mask) == input->value)
&& ((phys_curr & input->mask) > input->value)) {
input->state = INPUT_ST_LOW; /* invalidate */
return;
}
#endif
if ((phys_curr & input->mask) == input->value) {
if (input->type == INPUT_TYPE_KBD) {
/* will turn on the light */
keypressed = 1;
if (input->u.kbd.repeat_str[0]) {
char *repeat_str = input->u.kbd.repeat_str;
if (input->high_timer >= KEYPAD_REP_START)
input->high_timer -= KEYPAD_REP_DELAY;
keypad_send_key(repeat_str,
sizeof(repeat_str));
/* we will need to come back here soon */
inputs_stable = 0;
}
if (input->high_timer < 255)
input->high_timer++;
}
input->state = INPUT_ST_HIGH;
} else if (input->fall_timer >= input->fall_time) {
/* call release event */
if (input->type == INPUT_TYPE_STD) {
void (*release_fct)(int) = input->u.std.release_fct;
if (release_fct != NULL)
release_fct(input->u.std.release_data);
} else if (input->type == INPUT_TYPE_KBD) {
char *release_str = input->u.kbd.release_str;
if (release_str[0])
keypad_send_key(release_str,
sizeof(release_str));
}
input->state = INPUT_ST_LOW;
} else {
input->fall_timer++;
inputs_stable = 0;
}
}
static void panel_process_inputs(void)
{
struct list_head *item;
struct logical_input *input;
#if 0
printk(KERN_DEBUG
"entering panel_process_inputs with pp=%016Lx & pc=%016Lx\n",
phys_prev, phys_curr);
#endif
keypressed = 0;
inputs_stable = 1;
list_for_each(item, &logical_inputs) {
input = list_entry(item, struct logical_input, list);
switch (input->state) {
case INPUT_ST_LOW:
if ((phys_curr & input->mask) != input->value)
break;
/* if all needed ones were already set previously,
* this means that this logical signal has been
* activated by the releasing of another combined
* signal, so we don't want to match.
* eg: AB -(release B)-> A -(release A)-> 0 :
* don't match A.
*/
if ((phys_prev & input->mask) == input->value)
break;
input->rise_timer = 0;
input->state = INPUT_ST_RISING;
/* no break here, fall through */
case INPUT_ST_RISING:
if ((phys_curr & input->mask) != input->value) {
input->state = INPUT_ST_LOW;
break;
}
if (input->rise_timer < input->rise_time) {
inputs_stable = 0;
input->rise_timer++;
break;
}
input->high_timer = 0;
input->state = INPUT_ST_HIGH;
/* no break here, fall through */
case INPUT_ST_HIGH:
if (input_state_high(input))
break;
/* no break here, fall through */
case INPUT_ST_FALLING:
input_state_falling(input);
}
}
}
static void panel_scan_timer(void)
{
if (keypad_enabled && keypad_initialized) {
if (spin_trylock(&pprt_lock)) {
phys_scan_contacts();
/* no need for the parport anymore */
spin_unlock(&pprt_lock);
}
if (!inputs_stable || phys_curr != phys_prev)
panel_process_inputs();
}
if (lcd_enabled && lcd_initialized) {
if (keypressed) {
if (light_tempo == 0 && ((lcd_flags & LCD_FLAG_L) == 0))
lcd_backlight(1);
light_tempo = FLASH_LIGHT_TEMPO;
} else if (light_tempo > 0) {
light_tempo--;
if (light_tempo == 0 && ((lcd_flags & LCD_FLAG_L) == 0))
lcd_backlight(0);
}
}
mod_timer(&scan_timer, jiffies + INPUT_POLL_TIME);
}
static void init_scan_timer(void)
{
if (scan_timer.function != NULL)
return; /* already started */
init_timer(&scan_timer);
scan_timer.expires = jiffies + INPUT_POLL_TIME;
scan_timer.data = 0;
scan_timer.function = (void *)&panel_scan_timer;
add_timer(&scan_timer);
}
/* converts a name of the form "({BbAaPpSsEe}{01234567-})*" to a series of bits.
* if <omask> or <imask> are non-null, they will be or'ed with the bits
* corresponding to out and in bits respectively.
* returns 1 if ok, 0 if error (in which case, nothing is written).
*/
static int input_name2mask(char *name, pmask_t *mask, pmask_t *value,
char *imask, char *omask)
{
static char sigtab[10] = "EeSsPpAaBb";
char im, om;
pmask_t m, v;
om = im = m = v = 0ULL;
while (*name) {
int in, out, bit, neg;
for (in = 0; (in < sizeof(sigtab)) &&
(sigtab[in] != *name); in++)
;
if (in >= sizeof(sigtab))
return 0; /* input name not found */
neg = (in & 1); /* odd (lower) names are negated */
in >>= 1;
im |= (1 << in);
name++;
if (isdigit(*name)) {
out = *name - '0';
om |= (1 << out);
} else if (*name == '-')
out = 8;
else
return 0; /* unknown bit name */
bit = (out * 5) + in;
m |= 1ULL << bit;
if (!neg)
v |= 1ULL << bit;
name++;
}
*mask = m;
*value = v;
if (imask)
*imask |= im;
if (omask)
*omask |= om;
return 1;
}
/* tries to bind a key to the signal name <name>. The key will send the
* strings <press>, <repeat>, <release> for these respective events.
* Returns the pointer to the new key if ok, NULL if the key could not be bound.
*/
static struct logical_input *panel_bind_key(char *name, char *press,
char *repeat, char *release)
{
struct logical_input *key;
key = kzalloc(sizeof(struct logical_input), GFP_KERNEL);
if (!key) {
printk(KERN_ERR "panel: not enough memory\n");
return NULL;
}
if (!input_name2mask(name, &key->mask, &key->value, &scan_mask_i,
&scan_mask_o)) {
kfree(key);
return NULL;
}
key->type = INPUT_TYPE_KBD;
key->state = INPUT_ST_LOW;
key->rise_time = 1;
key->fall_time = 1;
#if 0
printk(KERN_DEBUG "bind: <%s> : m=%016Lx v=%016Lx\n", name, key->mask,
key->value);
#endif
strncpy(key->u.kbd.press_str, press, sizeof(key->u.kbd.press_str));
strncpy(key->u.kbd.repeat_str, repeat, sizeof(key->u.kbd.repeat_str));
strncpy(key->u.kbd.release_str, release,
sizeof(key->u.kbd.release_str));
list_add(&key->list, &logical_inputs);
return key;
}
#if 0
/* tries to bind a callback function to the signal name <name>. The function
* <press_fct> will be called with the <press_data> arg when the signal is
* activated, and so on for <release_fct>/<release_data>
* Returns the pointer to the new signal if ok, NULL if the signal could not
* be bound.
*/
static struct logical_input *panel_bind_callback(char *name,
void (*press_fct) (int),
int press_data,
void (*release_fct) (int),
int release_data)
{
struct logical_input *callback;
callback = kmalloc(sizeof(struct logical_input), GFP_KERNEL);
if (!callback) {
printk(KERN_ERR "panel: not enough memory\n");
return NULL;
}
memset(callback, 0, sizeof(struct logical_input));
if (!input_name2mask(name, &callback->mask, &callback->value,
&scan_mask_i, &scan_mask_o))
return NULL;
callback->type = INPUT_TYPE_STD;
callback->state = INPUT_ST_LOW;
callback->rise_time = 1;
callback->fall_time = 1;
callback->u.std.press_fct = press_fct;
callback->u.std.press_data = press_data;
callback->u.std.release_fct = release_fct;
callback->u.std.release_data = release_data;
list_add(&callback->list, &logical_inputs);
return callback;
}
#endif
static void keypad_init(void)
{
int keynum;
init_waitqueue_head(&keypad_read_wait);
keypad_buflen = 0; /* flushes any eventual noisy keystroke */
/* Let's create all known keys */
for (keynum = 0; keypad_profile[keynum][0][0]; keynum++) {
panel_bind_key(keypad_profile[keynum][0],
keypad_profile[keynum][1],
keypad_profile[keynum][2],
keypad_profile[keynum][3]);
}
init_scan_timer();
keypad_initialized = 1;
}
/**************************************************/
/* device initialization */
/**************************************************/
static int panel_notify_sys(struct notifier_block *this, unsigned long code,
void *unused)
{
if (lcd_enabled && lcd_initialized) {
switch (code) {
case SYS_DOWN:
panel_lcd_print
("\x0cReloading\nSystem...\x1b[Lc\x1b[Lb\x1b[L+");
break;
case SYS_HALT:
panel_lcd_print
("\x0cSystem Halted.\x1b[Lc\x1b[Lb\x1b[L+");
break;
case SYS_POWER_OFF:
panel_lcd_print("\x0cPower off.\x1b[Lc\x1b[Lb\x1b[L+");
break;
default:
break;
}
}
return NOTIFY_DONE;
}
static struct notifier_block panel_notifier = {
panel_notify_sys,
NULL,
0
};
static void panel_attach(struct parport *port)
{
if (port->number != parport)
return;
if (pprt) {
printk(KERN_ERR
"panel_attach(): port->number=%d parport=%d, "
"already registered !\n",
port->number, parport);
return;
}
pprt = parport_register_device(port, "panel", NULL, NULL, /* pf, kf */
NULL,
/*PARPORT_DEV_EXCL */
0, (void *)&pprt);
if (pprt == NULL) {
pr_err("panel_attach(): port->number=%d parport=%d, "
"parport_register_device() failed\n",
port->number, parport);
return;
}
if (parport_claim(pprt)) {
printk(KERN_ERR
"Panel: could not claim access to parport%d. "
"Aborting.\n", parport);
goto err_unreg_device;
}
/* must init LCD first, just in case an IRQ from the keypad is
* generated at keypad init
*/
if (lcd_enabled) {
lcd_init();
if (misc_register(&lcd_dev))
goto err_unreg_device;
}
if (keypad_enabled) {
keypad_init();
if (misc_register(&keypad_dev))
goto err_lcd_unreg;
}
return;
err_lcd_unreg:
if (lcd_enabled)
misc_deregister(&lcd_dev);
err_unreg_device:
parport_unregister_device(pprt);
pprt = NULL;
}
static void panel_detach(struct parport *port)
{
if (port->number != parport)
return;
if (!pprt) {
printk(KERN_ERR
"panel_detach(): port->number=%d parport=%d, "
"nothing to unregister.\n",
port->number, parport);
return;
}
if (keypad_enabled && keypad_initialized) {
misc_deregister(&keypad_dev);
keypad_initialized = 0;
}
if (lcd_enabled && lcd_initialized) {
misc_deregister(&lcd_dev);
lcd_initialized = 0;
}
parport_release(pprt);
parport_unregister_device(pprt);
pprt = NULL;
}
static struct parport_driver panel_driver = {
.name = "panel",
.attach = panel_attach,
.detach = panel_detach,
};
/* init function */
int panel_init(void)
{
/* for backwards compatibility */
if (keypad_type < 0)
keypad_type = keypad_enabled;
if (lcd_type < 0)
lcd_type = lcd_enabled;
if (parport < 0)
parport = DEFAULT_PARPORT;
/* take care of an eventual profile */
switch (profile) {
case PANEL_PROFILE_CUSTOM:
/* custom profile */
if (keypad_type < 0)
keypad_type = DEFAULT_KEYPAD;
if (lcd_type < 0)
lcd_type = DEFAULT_LCD;
break;
case PANEL_PROFILE_OLD:
/* 8 bits, 2*16, old keypad */
if (keypad_type < 0)
keypad_type = KEYPAD_TYPE_OLD;
if (lcd_type < 0)
lcd_type = LCD_TYPE_OLD;
if (lcd_width < 0)
lcd_width = 16;
if (lcd_hwidth < 0)
lcd_hwidth = 16;
break;
case PANEL_PROFILE_NEW:
/* serial, 2*16, new keypad */
if (keypad_type < 0)
keypad_type = KEYPAD_TYPE_NEW;
if (lcd_type < 0)
lcd_type = LCD_TYPE_KS0074;
break;
case PANEL_PROFILE_HANTRONIX:
/* 8 bits, 2*16 hantronix-like, no keypad */
if (keypad_type < 0)
keypad_type = KEYPAD_TYPE_NONE;
if (lcd_type < 0)
lcd_type = LCD_TYPE_HANTRONIX;
break;
case PANEL_PROFILE_NEXCOM:
/* generic 8 bits, 2*16, nexcom keypad, eg. Nexcom. */
if (keypad_type < 0)
keypad_type = KEYPAD_TYPE_NEXCOM;
if (lcd_type < 0)
lcd_type = LCD_TYPE_NEXCOM;
break;
case PANEL_PROFILE_LARGE:
/* 8 bits, 2*40, old keypad */
if (keypad_type < 0)
keypad_type = KEYPAD_TYPE_OLD;
if (lcd_type < 0)
lcd_type = LCD_TYPE_OLD;
break;
}
lcd_enabled = (lcd_type > 0);
keypad_enabled = (keypad_type > 0);
switch (keypad_type) {
case KEYPAD_TYPE_OLD:
keypad_profile = old_keypad_profile;
break;
case KEYPAD_TYPE_NEW:
keypad_profile = new_keypad_profile;
break;
case KEYPAD_TYPE_NEXCOM:
keypad_profile = nexcom_keypad_profile;
break;
default:
keypad_profile = NULL;
break;
}
/* tells various subsystems about the fact that we are initializing */
init_in_progress = 1;
if (parport_register_driver(&panel_driver)) {
printk(KERN_ERR
"Panel: could not register with parport. Aborting.\n");
return -EIO;
}
if (!lcd_enabled && !keypad_enabled) {
/* no device enabled, let's release the parport */
if (pprt) {
parport_release(pprt);
parport_unregister_device(pprt);
pprt = NULL;
}
parport_unregister_driver(&panel_driver);
printk(KERN_ERR "Panel driver version " PANEL_VERSION
" disabled.\n");
return -ENODEV;
}
register_reboot_notifier(&panel_notifier);
if (pprt)
printk(KERN_INFO "Panel driver version " PANEL_VERSION
" registered on parport%d (io=0x%lx).\n", parport,
pprt->port->base);
else
printk(KERN_INFO "Panel driver version " PANEL_VERSION
" not yet registered\n");
/* tells various subsystems about the fact that initialization
is finished */
init_in_progress = 0;
return 0;
}
static int __init panel_init_module(void)
{
return panel_init();
}
static void __exit panel_cleanup_module(void)
{
unregister_reboot_notifier(&panel_notifier);
if (scan_timer.function != NULL)
del_timer(&scan_timer);
if (pprt != NULL) {
if (keypad_enabled) {
misc_deregister(&keypad_dev);
keypad_initialized = 0;
}
if (lcd_enabled) {
panel_lcd_print("\x0cLCD driver " PANEL_VERSION
"\nunloaded.\x1b[Lc\x1b[Lb\x1b[L-");
misc_deregister(&lcd_dev);
lcd_initialized = 0;
}
/* TODO: free all input signals */
parport_release(pprt);
parport_unregister_device(pprt);
pprt = NULL;
}
parport_unregister_driver(&panel_driver);
}
module_init(panel_init_module);
module_exit(panel_cleanup_module);
MODULE_AUTHOR("Willy Tarreau");
MODULE_LICENSE("GPL");
/*
* Local variables:
* c-indent-level: 4
* tab-width: 8
* End:
*/
| gpl-2.0 |
pgielda/imx6-linux | arch/x86/kernel/cpu/perf_event_knc.c | 2690 | 8291 | /* Driver for Intel Xeon Phi "Knights Corner" PMU */
#include <linux/perf_event.h>
#include <linux/types.h>
#include <asm/hardirq.h>
#include "perf_event.h"
static const u64 knc_perfmon_event_map[] =
{
[PERF_COUNT_HW_CPU_CYCLES] = 0x002a,
[PERF_COUNT_HW_INSTRUCTIONS] = 0x0016,
[PERF_COUNT_HW_CACHE_REFERENCES] = 0x0028,
[PERF_COUNT_HW_CACHE_MISSES] = 0x0029,
[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x0012,
[PERF_COUNT_HW_BRANCH_MISSES] = 0x002b,
};
static const u64 __initconst knc_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
/* On Xeon Phi event "0" is a valid DATA_READ */
/* (L1 Data Cache Reads) Instruction. */
/* We code this as ARCH_PERFMON_EVENTSEL_INT as this */
/* bit will always be set in x86_pmu_hw_config(). */
[ C(RESULT_ACCESS) ] = ARCH_PERFMON_EVENTSEL_INT,
/* DATA_READ */
[ C(RESULT_MISS) ] = 0x0003, /* DATA_READ_MISS */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x0001, /* DATA_WRITE */
[ C(RESULT_MISS) ] = 0x0004, /* DATA_WRITE_MISS */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0011, /* L1_DATA_PF1 */
[ C(RESULT_MISS) ] = 0x001c, /* L1_DATA_PF1_MISS */
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x000c, /* CODE_READ */
[ C(RESULT_MISS) ] = 0x000e, /* CODE_CACHE_MISS */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0x10cb, /* L2_READ_MISS */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x10cc, /* L2_WRITE_HIT */
[ C(RESULT_MISS) ] = 0,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x10fc, /* L2_DATA_PF2 */
[ C(RESULT_MISS) ] = 0x10fe, /* L2_DATA_PF2_MISS */
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = ARCH_PERFMON_EVENTSEL_INT,
/* DATA_READ */
/* see note on L1 OP_READ */
[ C(RESULT_MISS) ] = 0x0002, /* DATA_PAGE_WALK */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x0001, /* DATA_WRITE */
[ C(RESULT_MISS) ] = 0x0002, /* DATA_PAGE_WALK */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x000c, /* CODE_READ */
[ C(RESULT_MISS) ] = 0x000d, /* CODE_PAGE_WALK */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0012, /* BRANCHES */
[ C(RESULT_MISS) ] = 0x002b, /* BRANCHES_MISPREDICTED */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
};
static u64 knc_pmu_event_map(int hw_event)
{
return knc_perfmon_event_map[hw_event];
}
static struct event_constraint knc_event_constraints[] =
{
INTEL_EVENT_CONSTRAINT(0xc3, 0x1), /* HWP_L2HIT */
INTEL_EVENT_CONSTRAINT(0xc4, 0x1), /* HWP_L2MISS */
INTEL_EVENT_CONSTRAINT(0xc8, 0x1), /* L2_READ_HIT_E */
INTEL_EVENT_CONSTRAINT(0xc9, 0x1), /* L2_READ_HIT_M */
INTEL_EVENT_CONSTRAINT(0xca, 0x1), /* L2_READ_HIT_S */
INTEL_EVENT_CONSTRAINT(0xcb, 0x1), /* L2_READ_MISS */
INTEL_EVENT_CONSTRAINT(0xcc, 0x1), /* L2_WRITE_HIT */
INTEL_EVENT_CONSTRAINT(0xce, 0x1), /* L2_STRONGLY_ORDERED_STREAMING_VSTORES_MISS */
INTEL_EVENT_CONSTRAINT(0xcf, 0x1), /* L2_WEAKLY_ORDERED_STREAMING_VSTORE_MISS */
INTEL_EVENT_CONSTRAINT(0xd7, 0x1), /* L2_VICTIM_REQ_WITH_DATA */
INTEL_EVENT_CONSTRAINT(0xe3, 0x1), /* SNP_HITM_BUNIT */
INTEL_EVENT_CONSTRAINT(0xe6, 0x1), /* SNP_HIT_L2 */
INTEL_EVENT_CONSTRAINT(0xe7, 0x1), /* SNP_HITM_L2 */
INTEL_EVENT_CONSTRAINT(0xf1, 0x1), /* L2_DATA_READ_MISS_CACHE_FILL */
INTEL_EVENT_CONSTRAINT(0xf2, 0x1), /* L2_DATA_WRITE_MISS_CACHE_FILL */
INTEL_EVENT_CONSTRAINT(0xf6, 0x1), /* L2_DATA_READ_MISS_MEM_FILL */
INTEL_EVENT_CONSTRAINT(0xf7, 0x1), /* L2_DATA_WRITE_MISS_MEM_FILL */
INTEL_EVENT_CONSTRAINT(0xfc, 0x1), /* L2_DATA_PF2 */
INTEL_EVENT_CONSTRAINT(0xfd, 0x1), /* L2_DATA_PF2_DROP */
INTEL_EVENT_CONSTRAINT(0xfe, 0x1), /* L2_DATA_PF2_MISS */
INTEL_EVENT_CONSTRAINT(0xff, 0x1), /* L2_DATA_HIT_INFLIGHT_PF2 */
EVENT_CONSTRAINT_END
};
#define MSR_KNC_IA32_PERF_GLOBAL_STATUS 0x0000002d
#define MSR_KNC_IA32_PERF_GLOBAL_OVF_CONTROL 0x0000002e
#define MSR_KNC_IA32_PERF_GLOBAL_CTRL 0x0000002f
#define KNC_ENABLE_COUNTER0 0x00000001
#define KNC_ENABLE_COUNTER1 0x00000002
static void knc_pmu_disable_all(void)
{
u64 val;
rdmsrl(MSR_KNC_IA32_PERF_GLOBAL_CTRL, val);
val &= ~(KNC_ENABLE_COUNTER0|KNC_ENABLE_COUNTER1);
wrmsrl(MSR_KNC_IA32_PERF_GLOBAL_CTRL, val);
}
static void knc_pmu_enable_all(int added)
{
u64 val;
rdmsrl(MSR_KNC_IA32_PERF_GLOBAL_CTRL, val);
val |= (KNC_ENABLE_COUNTER0|KNC_ENABLE_COUNTER1);
wrmsrl(MSR_KNC_IA32_PERF_GLOBAL_CTRL, val);
}
static inline void
knc_pmu_disable_event(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
u64 val;
val = hwc->config;
val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
(void)wrmsrl_safe(hwc->config_base + hwc->idx, val);
}
static void knc_pmu_enable_event(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
u64 val;
val = hwc->config;
val |= ARCH_PERFMON_EVENTSEL_ENABLE;
(void)wrmsrl_safe(hwc->config_base + hwc->idx, val);
}
static inline u64 knc_pmu_get_status(void)
{
u64 status;
rdmsrl(MSR_KNC_IA32_PERF_GLOBAL_STATUS, status);
return status;
}
static inline void knc_pmu_ack_status(u64 ack)
{
wrmsrl(MSR_KNC_IA32_PERF_GLOBAL_OVF_CONTROL, ack);
}
static int knc_pmu_handle_irq(struct pt_regs *regs)
{
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
int handled = 0;
int bit, loops;
u64 status;
cpuc = &__get_cpu_var(cpu_hw_events);
knc_pmu_disable_all();
status = knc_pmu_get_status();
if (!status) {
knc_pmu_enable_all(0);
return handled;
}
loops = 0;
again:
knc_pmu_ack_status(status);
if (++loops > 100) {
WARN_ONCE(1, "perf: irq loop stuck!\n");
perf_event_print_debug();
goto done;
}
inc_irq_stat(apic_perf_irqs);
for_each_set_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) {
struct perf_event *event = cpuc->events[bit];
handled++;
if (!test_bit(bit, cpuc->active_mask))
continue;
if (!intel_pmu_save_and_restart(event))
continue;
perf_sample_data_init(&data, 0, event->hw.last_period);
if (perf_event_overflow(event, &data, regs))
x86_pmu_stop(event, 0);
}
/*
* Repeat if there is more work to be done:
*/
status = knc_pmu_get_status();
if (status)
goto again;
done:
knc_pmu_enable_all(0);
return handled;
}
PMU_FORMAT_ATTR(event, "config:0-7" );
PMU_FORMAT_ATTR(umask, "config:8-15" );
PMU_FORMAT_ATTR(edge, "config:18" );
PMU_FORMAT_ATTR(inv, "config:23" );
PMU_FORMAT_ATTR(cmask, "config:24-31" );
static struct attribute *intel_knc_formats_attr[] = {
&format_attr_event.attr,
&format_attr_umask.attr,
&format_attr_edge.attr,
&format_attr_inv.attr,
&format_attr_cmask.attr,
NULL,
};
static const struct x86_pmu knc_pmu __initconst = {
.name = "knc",
.handle_irq = knc_pmu_handle_irq,
.disable_all = knc_pmu_disable_all,
.enable_all = knc_pmu_enable_all,
.enable = knc_pmu_enable_event,
.disable = knc_pmu_disable_event,
.hw_config = x86_pmu_hw_config,
.schedule_events = x86_schedule_events,
.eventsel = MSR_KNC_EVNTSEL0,
.perfctr = MSR_KNC_PERFCTR0,
.event_map = knc_pmu_event_map,
.max_events = ARRAY_SIZE(knc_perfmon_event_map),
.apic = 1,
.max_period = (1ULL << 39) - 1,
.version = 0,
.num_counters = 2,
.cntval_bits = 40,
.cntval_mask = (1ULL << 40) - 1,
.get_event_constraints = x86_get_event_constraints,
.event_constraints = knc_event_constraints,
.format_attrs = intel_knc_formats_attr,
};
__init int knc_pmu_init(void)
{
x86_pmu = knc_pmu;
memcpy(hw_cache_event_ids, knc_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
return 0;
}
| gpl-2.0 |
ruzarowski/boeffla-kernel-cm-s3 | drivers/media/video/saa7134/saa7134-input.c | 2946 | 25378 | /*
*
* handle saa7134 IR remotes via linux kernel input layer.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include "saa7134-reg.h"
#include "saa7134.h"
#define MODULE_NAME "saa7134"
static unsigned int disable_ir;
module_param(disable_ir, int, 0444);
MODULE_PARM_DESC(disable_ir,"disable infrared remote support");
static unsigned int ir_debug;
module_param(ir_debug, int, 0644);
MODULE_PARM_DESC(ir_debug,"enable debug messages [IR]");
static int pinnacle_remote;
module_param(pinnacle_remote, int, 0644); /* Choose Pinnacle PCTV remote */
MODULE_PARM_DESC(pinnacle_remote, "Specify Pinnacle PCTV remote: 0=coloured, 1=grey (defaults to 0)");
#define dprintk(fmt, arg...) if (ir_debug) \
printk(KERN_DEBUG "%s/ir: " fmt, dev->name , ## arg)
#define i2cdprintk(fmt, arg...) if (ir_debug) \
printk(KERN_DEBUG "%s/ir: " fmt, ir->name , ## arg)
/* Helper function for raw decoding at GPIO16 or GPIO18 */
static int saa7134_raw_decode_irq(struct saa7134_dev *dev);
/* -------------------- GPIO generic keycode builder -------------------- */
static int build_key(struct saa7134_dev *dev)
{
struct saa7134_card_ir *ir = dev->remote;
u32 gpio, data;
/* here comes the additional handshake steps for some cards */
switch (dev->board) {
case SAA7134_BOARD_GOTVIEW_7135:
saa_setb(SAA7134_GPIO_GPSTATUS1, 0x80);
saa_clearb(SAA7134_GPIO_GPSTATUS1, 0x80);
break;
}
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3,SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3,SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
if (ir->polling) {
if (ir->last_gpio == gpio)
return 0;
ir->last_gpio = gpio;
}
data = ir_extract_bits(gpio, ir->mask_keycode);
dprintk("build_key gpio=0x%x mask=0x%x data=%d\n",
gpio, ir->mask_keycode, data);
switch (dev->board) {
case SAA7134_BOARD_KWORLD_PLUS_TV_ANALOG:
if (data == ir->mask_keycode)
rc_keyup(ir->dev);
else
rc_keydown_notimeout(ir->dev, data, 0);
return 0;
}
if (ir->polling) {
if ((ir->mask_keydown && (0 != (gpio & ir->mask_keydown))) ||
(ir->mask_keyup && (0 == (gpio & ir->mask_keyup)))) {
rc_keydown_notimeout(ir->dev, data, 0);
} else {
rc_keyup(ir->dev);
}
}
else { /* IRQ driven mode - handle key press and release in one go */
if ((ir->mask_keydown && (0 != (gpio & ir->mask_keydown))) ||
(ir->mask_keyup && (0 == (gpio & ir->mask_keyup)))) {
rc_keydown_notimeout(ir->dev, data, 0);
rc_keyup(ir->dev);
}
}
return 0;
}
/* --------------------- Chip specific I2C key builders ----------------- */
static int get_key_flydvb_trio(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
int gpio;
int attempt = 0;
unsigned char b;
/* We need this to access GPI Used by the saa_readl macro. */
struct saa7134_dev *dev = ir->c->adapter->algo_data;
if (dev == NULL) {
i2cdprintk("get_key_flydvb_trio: "
"ir->c->adapter->algo_data is NULL!\n");
return -EIO;
}
/* rising SAA7134_GPIGPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
if (0x40000 & ~gpio)
return 0; /* No button press */
/* No button press - only before first key pressed */
if (b == 0xFF)
return 0;
/* poll IR chip */
/* weak up the IR chip */
b = 0;
while (1 != i2c_master_send(ir->c, &b, 1)) {
if ((attempt++) < 10) {
/*
* wait a bit for next attempt -
* I don't know how make it better
*/
msleep(10);
continue;
}
i2cdprintk("send wake up byte to pic16C505 (IR chip)"
"failed %dx\n", attempt);
return -EIO;
}
if (1 != i2c_master_recv(ir->c, &b, 1)) {
i2cdprintk("read error\n");
return -EIO;
}
*ir_key = b;
*ir_raw = b;
return 1;
}
static int get_key_msi_tvanywhere_plus(struct IR_i2c *ir, u32 *ir_key,
u32 *ir_raw)
{
unsigned char b;
int gpio;
/* <dev> is needed to access GPIO. Used by the saa_readl macro. */
struct saa7134_dev *dev = ir->c->adapter->algo_data;
if (dev == NULL) {
i2cdprintk("get_key_msi_tvanywhere_plus: "
"ir->c->adapter->algo_data is NULL!\n");
return -EIO;
}
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
/* GPIO&0x40 is pulsed low when a button is pressed. Don't do
I2C receive if gpio&0x40 is not low. */
if (gpio & 0x40)
return 0; /* No button press */
/* GPIO says there is a button press. Get it. */
if (1 != i2c_master_recv(ir->c, &b, 1)) {
i2cdprintk("read error\n");
return -EIO;
}
/* No button press */
if (b == 0xff)
return 0;
/* Button pressed */
dprintk("get_key_msi_tvanywhere_plus: Key = 0x%02X\n", b);
*ir_key = b;
*ir_raw = b;
return 1;
}
static int get_key_purpletv(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
unsigned char b;
/* poll IR chip */
if (1 != i2c_master_recv(ir->c, &b, 1)) {
i2cdprintk("read error\n");
return -EIO;
}
/* no button press */
if (b==0)
return 0;
/* repeating */
if (b & 0x80)
return 1;
*ir_key = b;
*ir_raw = b;
return 1;
}
static int get_key_hvr1110(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
unsigned char buf[5], cod4, code3, code4;
/* poll IR chip */
if (5 != i2c_master_recv(ir->c, buf, 5))
return -EIO;
cod4 = buf[4];
code4 = (cod4 >> 2);
code3 = buf[3];
if (code3 == 0)
/* no key pressed */
return 0;
/* return key */
*ir_key = code4;
*ir_raw = code4;
return 1;
}
static int get_key_beholdm6xx(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
unsigned char data[12];
u32 gpio;
struct saa7134_dev *dev = ir->c->adapter->algo_data;
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
if (0x400000 & ~gpio)
return 0; /* No button press */
ir->c->addr = 0x5a >> 1;
if (12 != i2c_master_recv(ir->c, data, 12)) {
i2cdprintk("read error\n");
return -EIO;
}
if (data[9] != (unsigned char)(~data[8]))
return 0;
*ir_raw = ((data[10] << 16) | (data[11] << 8) | (data[9] << 0));
*ir_key = *ir_raw;
return 1;
}
/* Common (grey or coloured) pinnacle PCTV remote handling
*
*/
static int get_key_pinnacle(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw,
int parity_offset, int marker, int code_modulo)
{
unsigned char b[4];
unsigned int start = 0,parity = 0,code = 0;
/* poll IR chip */
if (4 != i2c_master_recv(ir->c, b, 4)) {
i2cdprintk("read error\n");
return -EIO;
}
for (start = 0; start < ARRAY_SIZE(b); start++) {
if (b[start] == marker) {
code=b[(start+parity_offset + 1) % 4];
parity=b[(start+parity_offset) % 4];
}
}
/* Empty Request */
if (parity == 0)
return 0;
/* Repeating... */
if (ir->old == parity)
return 0;
ir->old = parity;
/* drop special codes when a key is held down a long time for the grey controller
In this case, the second bit of the code is asserted */
if (marker == 0xfe && (code & 0x40))
return 0;
code %= code_modulo;
*ir_raw = code;
*ir_key = code;
i2cdprintk("Pinnacle PCTV key %02x\n", code);
return 1;
}
/* The grey pinnacle PCTV remote
*
* There are one issue with this remote:
* - I2c packet does not change when the same key is pressed quickly. The workaround
* is to hold down each key for about half a second, so that another code is generated
* in the i2c packet, and the function can distinguish key presses.
*
* Sylvain Pasche <sylvain.pasche@gmail.com>
*/
static int get_key_pinnacle_grey(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
return get_key_pinnacle(ir, ir_key, ir_raw, 1, 0xfe, 0xff);
}
/* The new pinnacle PCTV remote (with the colored buttons)
*
* Ricardo Cerqueira <v4l@cerqueira.org>
*/
static int get_key_pinnacle_color(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
/* code_modulo parameter (0x88) is used to reduce code value to fit inside IR_KEYTAB_SIZE
*
* this is the only value that results in 42 unique
* codes < 128
*/
return get_key_pinnacle(ir, ir_key, ir_raw, 2, 0x80, 0x88);
}
void saa7134_input_irq(struct saa7134_dev *dev)
{
struct saa7134_card_ir *ir;
if (!dev || !dev->remote)
return;
ir = dev->remote;
if (!ir->running)
return;
if (!ir->polling && !ir->raw_decode) {
build_key(dev);
} else if (ir->raw_decode) {
saa7134_raw_decode_irq(dev);
}
}
static void saa7134_input_timer(unsigned long data)
{
struct saa7134_dev *dev = (struct saa7134_dev *)data;
struct saa7134_card_ir *ir = dev->remote;
build_key(dev);
mod_timer(&ir->timer, jiffies + msecs_to_jiffies(ir->polling));
}
static void ir_raw_decode_timer_end(unsigned long data)
{
struct saa7134_dev *dev = (struct saa7134_dev *)data;
struct saa7134_card_ir *ir = dev->remote;
ir_raw_event_handle(dev->remote->dev);
ir->active = false;
}
static int __saa7134_ir_start(void *priv)
{
struct saa7134_dev *dev = priv;
struct saa7134_card_ir *ir;
if (!dev || !dev->remote)
return -EINVAL;
ir = dev->remote;
if (ir->running)
return 0;
/* Moved here from saa7134_input_init1() because the latter
* is not called on device resume */
switch (dev->board) {
case SAA7134_BOARD_MD2819:
case SAA7134_BOARD_KWORLD_VSTREAM_XPERT:
case SAA7134_BOARD_AVERMEDIA_305:
case SAA7134_BOARD_AVERMEDIA_307:
case SAA7134_BOARD_AVERMEDIA_STUDIO_305:
case SAA7134_BOARD_AVERMEDIA_STUDIO_505:
case SAA7134_BOARD_AVERMEDIA_STUDIO_307:
case SAA7134_BOARD_AVERMEDIA_STUDIO_507:
case SAA7134_BOARD_AVERMEDIA_STUDIO_507UA:
case SAA7134_BOARD_AVERMEDIA_GO_007_FM:
case SAA7134_BOARD_AVERMEDIA_M102:
case SAA7134_BOARD_AVERMEDIA_GO_007_FM_PLUS:
/* Without this we won't receive key up events */
saa_setb(SAA7134_GPIO_GPMODE0, 0x4);
saa_setb(SAA7134_GPIO_GPSTATUS0, 0x4);
break;
case SAA7134_BOARD_AVERMEDIA_777:
case SAA7134_BOARD_AVERMEDIA_A16AR:
/* Without this we won't receive key up events */
saa_setb(SAA7134_GPIO_GPMODE1, 0x1);
saa_setb(SAA7134_GPIO_GPSTATUS1, 0x1);
break;
case SAA7134_BOARD_AVERMEDIA_A16D:
/* Without this we won't receive key up events */
saa_setb(SAA7134_GPIO_GPMODE1, 0x1);
saa_setb(SAA7134_GPIO_GPSTATUS1, 0x1);
break;
case SAA7134_BOARD_GOTVIEW_7135:
saa_setb(SAA7134_GPIO_GPMODE1, 0x80);
break;
}
ir->running = true;
ir->active = false;
if (ir->polling) {
setup_timer(&ir->timer, saa7134_input_timer,
(unsigned long)dev);
ir->timer.expires = jiffies + HZ;
add_timer(&ir->timer);
} else if (ir->raw_decode) {
/* set timer_end for code completion */
setup_timer(&ir->timer, ir_raw_decode_timer_end,
(unsigned long)dev);
}
return 0;
}
static void __saa7134_ir_stop(void *priv)
{
struct saa7134_dev *dev = priv;
struct saa7134_card_ir *ir;
if (!dev || !dev->remote)
return;
ir = dev->remote;
if (!ir->running)
return;
if (ir->polling || ir->raw_decode)
del_timer_sync(&ir->timer);
ir->active = false;
ir->running = false;
return;
}
int saa7134_ir_start(struct saa7134_dev *dev)
{
if (dev->remote->users)
return __saa7134_ir_start(dev);
return 0;
}
void saa7134_ir_stop(struct saa7134_dev *dev)
{
if (dev->remote->users)
__saa7134_ir_stop(dev);
}
static int saa7134_ir_open(struct rc_dev *rc)
{
struct saa7134_dev *dev = rc->priv;
dev->remote->users++;
return __saa7134_ir_start(dev);
}
static void saa7134_ir_close(struct rc_dev *rc)
{
struct saa7134_dev *dev = rc->priv;
dev->remote->users--;
if (!dev->remote->users)
__saa7134_ir_stop(dev);
}
int saa7134_input_init1(struct saa7134_dev *dev)
{
struct saa7134_card_ir *ir;
struct rc_dev *rc;
char *ir_codes = NULL;
u32 mask_keycode = 0;
u32 mask_keydown = 0;
u32 mask_keyup = 0;
unsigned polling = 0;
bool raw_decode = false;
int err;
if (dev->has_remote != SAA7134_REMOTE_GPIO)
return -ENODEV;
if (disable_ir)
return -ENODEV;
/* detect & configure */
switch (dev->board) {
case SAA7134_BOARD_FLYVIDEO2000:
case SAA7134_BOARD_FLYVIDEO3000:
case SAA7134_BOARD_FLYTVPLATINUM_FM:
case SAA7134_BOARD_FLYTVPLATINUM_MINI2:
case SAA7134_BOARD_ROVERMEDIA_LINK_PRO_FM:
ir_codes = RC_MAP_FLYVIDEO;
mask_keycode = 0xEC00000;
mask_keydown = 0x0040000;
break;
case SAA7134_BOARD_CINERGY400:
case SAA7134_BOARD_CINERGY600:
case SAA7134_BOARD_CINERGY600_MK3:
ir_codes = RC_MAP_CINERGY;
mask_keycode = 0x00003f;
mask_keyup = 0x040000;
break;
case SAA7134_BOARD_ECS_TVP3XP:
case SAA7134_BOARD_ECS_TVP3XP_4CB5:
ir_codes = RC_MAP_EZTV;
mask_keycode = 0x00017c;
mask_keyup = 0x000002;
polling = 50; // ms
break;
case SAA7134_BOARD_KWORLD_XPERT:
case SAA7134_BOARD_AVACSSMARTTV:
ir_codes = RC_MAP_PIXELVIEW;
mask_keycode = 0x00001F;
mask_keyup = 0x000020;
polling = 50; // ms
break;
case SAA7134_BOARD_MD2819:
case SAA7134_BOARD_KWORLD_VSTREAM_XPERT:
case SAA7134_BOARD_AVERMEDIA_305:
case SAA7134_BOARD_AVERMEDIA_307:
case SAA7134_BOARD_AVERMEDIA_STUDIO_305:
case SAA7134_BOARD_AVERMEDIA_STUDIO_505:
case SAA7134_BOARD_AVERMEDIA_STUDIO_307:
case SAA7134_BOARD_AVERMEDIA_STUDIO_507:
case SAA7134_BOARD_AVERMEDIA_STUDIO_507UA:
case SAA7134_BOARD_AVERMEDIA_GO_007_FM:
case SAA7134_BOARD_AVERMEDIA_M102:
case SAA7134_BOARD_AVERMEDIA_GO_007_FM_PLUS:
ir_codes = RC_MAP_AVERMEDIA;
mask_keycode = 0x0007C8;
mask_keydown = 0x000010;
polling = 50; // ms
/* GPIO stuff moved to __saa7134_ir_start() */
break;
case SAA7134_BOARD_AVERMEDIA_M135A:
ir_codes = RC_MAP_AVERMEDIA_M135A;
mask_keydown = 0x0040000; /* Enable GPIO18 line on both edges */
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = true;
break;
case SAA7134_BOARD_AVERMEDIA_M733A:
ir_codes = RC_MAP_AVERMEDIA_M733A_RM_K6;
mask_keydown = 0x0040000;
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = true;
break;
case SAA7134_BOARD_AVERMEDIA_777:
case SAA7134_BOARD_AVERMEDIA_A16AR:
ir_codes = RC_MAP_AVERMEDIA;
mask_keycode = 0x02F200;
mask_keydown = 0x000400;
polling = 50; // ms
/* GPIO stuff moved to __saa7134_ir_start() */
break;
case SAA7134_BOARD_AVERMEDIA_A16D:
ir_codes = RC_MAP_AVERMEDIA_A16D;
mask_keycode = 0x02F200;
mask_keydown = 0x000400;
polling = 50; /* ms */
/* GPIO stuff moved to __saa7134_ir_start() */
break;
case SAA7134_BOARD_KWORLD_TERMINATOR:
ir_codes = RC_MAP_PIXELVIEW;
mask_keycode = 0x00001f;
mask_keyup = 0x000060;
polling = 50; // ms
break;
case SAA7134_BOARD_MANLI_MTV001:
case SAA7134_BOARD_MANLI_MTV002:
ir_codes = RC_MAP_MANLI;
mask_keycode = 0x001f00;
mask_keyup = 0x004000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_BEHOLD_409FM:
case SAA7134_BOARD_BEHOLD_401:
case SAA7134_BOARD_BEHOLD_403:
case SAA7134_BOARD_BEHOLD_403FM:
case SAA7134_BOARD_BEHOLD_405:
case SAA7134_BOARD_BEHOLD_405FM:
case SAA7134_BOARD_BEHOLD_407:
case SAA7134_BOARD_BEHOLD_407FM:
case SAA7134_BOARD_BEHOLD_409:
case SAA7134_BOARD_BEHOLD_505FM:
case SAA7134_BOARD_BEHOLD_505RDS_MK5:
case SAA7134_BOARD_BEHOLD_505RDS_MK3:
case SAA7134_BOARD_BEHOLD_507_9FM:
case SAA7134_BOARD_BEHOLD_507RDS_MK3:
case SAA7134_BOARD_BEHOLD_507RDS_MK5:
ir_codes = RC_MAP_MANLI;
mask_keycode = 0x003f00;
mask_keyup = 0x004000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_BEHOLD_COLUMBUS_TVFM:
ir_codes = RC_MAP_BEHOLD_COLUMBUS;
mask_keycode = 0x003f00;
mask_keyup = 0x004000;
polling = 50; // ms
break;
case SAA7134_BOARD_SEDNA_PC_TV_CARDBUS:
ir_codes = RC_MAP_PCTV_SEDNA;
mask_keycode = 0x001f00;
mask_keyup = 0x004000;
polling = 50; // ms
break;
case SAA7134_BOARD_GOTVIEW_7135:
ir_codes = RC_MAP_GOTVIEW7135;
mask_keycode = 0x0003CC;
mask_keydown = 0x000010;
polling = 5; /* ms */
/* GPIO stuff moved to __saa7134_ir_start() */
break;
case SAA7134_BOARD_VIDEOMATE_TV_PVR:
case SAA7134_BOARD_VIDEOMATE_GOLD_PLUS:
case SAA7134_BOARD_VIDEOMATE_TV_GOLD_PLUSII:
ir_codes = RC_MAP_VIDEOMATE_TV_PVR;
mask_keycode = 0x00003F;
mask_keyup = 0x400000;
polling = 50; // ms
break;
case SAA7134_BOARD_PROTEUS_2309:
ir_codes = RC_MAP_PROTEUS_2309;
mask_keycode = 0x00007F;
mask_keyup = 0x000080;
polling = 50; // ms
break;
case SAA7134_BOARD_VIDEOMATE_DVBT_300:
case SAA7134_BOARD_VIDEOMATE_DVBT_200:
ir_codes = RC_MAP_VIDEOMATE_TV_PVR;
mask_keycode = 0x003F00;
mask_keyup = 0x040000;
break;
case SAA7134_BOARD_FLYDVBS_LR300:
case SAA7134_BOARD_FLYDVBT_LR301:
case SAA7134_BOARD_FLYDVBTDUO:
ir_codes = RC_MAP_FLYDVB;
mask_keycode = 0x0001F00;
mask_keydown = 0x0040000;
break;
case SAA7134_BOARD_ASUSTeK_P7131_DUAL:
case SAA7134_BOARD_ASUSTeK_P7131_HYBRID_LNA:
case SAA7134_BOARD_ASUSTeK_P7131_ANALOG:
ir_codes = RC_MAP_ASUS_PC39;
mask_keydown = 0x0040000; /* Enable GPIO18 line on both edges */
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = true;
break;
case SAA7134_BOARD_ENCORE_ENLTV:
case SAA7134_BOARD_ENCORE_ENLTV_FM:
ir_codes = RC_MAP_ENCORE_ENLTV;
mask_keycode = 0x00007f;
mask_keyup = 0x040000;
polling = 50; // ms
break;
case SAA7134_BOARD_ENCORE_ENLTV_FM53:
case SAA7134_BOARD_ENCORE_ENLTV_FM3:
ir_codes = RC_MAP_ENCORE_ENLTV_FM53;
mask_keydown = 0x0040000; /* Enable GPIO18 line on both edges */
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = true;
break;
case SAA7134_BOARD_10MOONSTVMASTER3:
ir_codes = RC_MAP_ENCORE_ENLTV;
mask_keycode = 0x5f80000;
mask_keyup = 0x8000000;
polling = 50; //ms
break;
case SAA7134_BOARD_GENIUS_TVGO_A11MCE:
ir_codes = RC_MAP_GENIUS_TVGO_A11MCE;
mask_keycode = 0xff;
mask_keydown = 0xf00000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_REAL_ANGEL_220:
ir_codes = RC_MAP_REAL_AUDIO_220_32_KEYS;
mask_keycode = 0x3f00;
mask_keyup = 0x4000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_KWORLD_PLUS_TV_ANALOG:
ir_codes = RC_MAP_KWORLD_PLUS_TV_ANALOG;
mask_keycode = 0x7f;
polling = 40; /* ms */
break;
case SAA7134_BOARD_VIDEOMATE_S350:
ir_codes = RC_MAP_VIDEOMATE_S350;
mask_keycode = 0x003f00;
mask_keydown = 0x040000;
break;
case SAA7134_BOARD_LEADTEK_WINFAST_DTV1000S:
ir_codes = RC_MAP_WINFAST;
mask_keycode = 0x5f00;
mask_keyup = 0x020000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_VIDEOMATE_M1F:
ir_codes = RC_MAP_VIDEOMATE_M1F;
mask_keycode = 0x0ff00;
mask_keyup = 0x040000;
break;
case SAA7134_BOARD_HAUPPAUGE_HVR1150:
case SAA7134_BOARD_HAUPPAUGE_HVR1120:
ir_codes = RC_MAP_HAUPPAUGE;
mask_keydown = 0x0040000; /* Enable GPIO18 line on both edges */
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = true;
break;
}
if (NULL == ir_codes) {
printk("%s: Oops: IR config error [card=%d]\n",
dev->name, dev->board);
return -ENODEV;
}
ir = kzalloc(sizeof(*ir), GFP_KERNEL);
rc = rc_allocate_device();
if (!ir || !rc) {
err = -ENOMEM;
goto err_out_free;
}
ir->dev = rc;
dev->remote = ir;
/* init hardware-specific stuff */
ir->mask_keycode = mask_keycode;
ir->mask_keydown = mask_keydown;
ir->mask_keyup = mask_keyup;
ir->polling = polling;
ir->raw_decode = raw_decode;
/* init input device */
snprintf(ir->name, sizeof(ir->name), "saa7134 IR (%s)",
saa7134_boards[dev->board].name);
snprintf(ir->phys, sizeof(ir->phys), "pci-%s/ir0",
pci_name(dev->pci));
rc->priv = dev;
rc->open = saa7134_ir_open;
rc->close = saa7134_ir_close;
if (raw_decode)
rc->driver_type = RC_DRIVER_IR_RAW;
rc->input_name = ir->name;
rc->input_phys = ir->phys;
rc->input_id.bustype = BUS_PCI;
rc->input_id.version = 1;
if (dev->pci->subsystem_vendor) {
rc->input_id.vendor = dev->pci->subsystem_vendor;
rc->input_id.product = dev->pci->subsystem_device;
} else {
rc->input_id.vendor = dev->pci->vendor;
rc->input_id.product = dev->pci->device;
}
rc->dev.parent = &dev->pci->dev;
rc->map_name = ir_codes;
rc->driver_name = MODULE_NAME;
err = rc_register_device(rc);
if (err)
goto err_out_free;
return 0;
err_out_free:
rc_free_device(rc);
dev->remote = NULL;
kfree(ir);
return err;
}
void saa7134_input_fini(struct saa7134_dev *dev)
{
if (NULL == dev->remote)
return;
saa7134_ir_stop(dev);
rc_unregister_device(dev->remote->dev);
kfree(dev->remote);
dev->remote = NULL;
}
void saa7134_probe_i2c_ir(struct saa7134_dev *dev)
{
struct i2c_board_info info;
struct i2c_msg msg_msi = {
.addr = 0x50,
.flags = I2C_M_RD,
.len = 0,
.buf = NULL,
};
int rc;
if (disable_ir) {
dprintk("IR has been disabled, not probing for i2c remote\n");
return;
}
memset(&info, 0, sizeof(struct i2c_board_info));
memset(&dev->init_data, 0, sizeof(dev->init_data));
strlcpy(info.type, "ir_video", I2C_NAME_SIZE);
switch (dev->board) {
case SAA7134_BOARD_PINNACLE_PCTV_110i:
case SAA7134_BOARD_PINNACLE_PCTV_310i:
dev->init_data.name = "Pinnacle PCTV";
if (pinnacle_remote == 0) {
dev->init_data.get_key = get_key_pinnacle_color;
dev->init_data.ir_codes = RC_MAP_PINNACLE_COLOR;
info.addr = 0x47;
} else {
dev->init_data.get_key = get_key_pinnacle_grey;
dev->init_data.ir_codes = RC_MAP_PINNACLE_GREY;
info.addr = 0x47;
}
break;
case SAA7134_BOARD_UPMOST_PURPLE_TV:
dev->init_data.name = "Purple TV";
dev->init_data.get_key = get_key_purpletv;
dev->init_data.ir_codes = RC_MAP_PURPLETV;
info.addr = 0x7a;
break;
case SAA7134_BOARD_MSI_TVATANYWHERE_PLUS:
dev->init_data.name = "MSI TV@nywhere Plus";
dev->init_data.get_key = get_key_msi_tvanywhere_plus;
dev->init_data.ir_codes = RC_MAP_MSI_TVANYWHERE_PLUS;
/*
* MSI TV@nyware Plus requires more frequent polling
* otherwise it will miss some keypresses
*/
dev->init_data.polling_interval = 50;
info.addr = 0x30;
/* MSI TV@nywhere Plus controller doesn't seem to
respond to probes unless we read something from
an existing device. Weird...
REVISIT: might no longer be needed */
rc = i2c_transfer(&dev->i2c_adap, &msg_msi, 1);
dprintk("probe 0x%02x @ %s: %s\n",
msg_msi.addr, dev->i2c_adap.name,
(1 == rc) ? "yes" : "no");
break;
case SAA7134_BOARD_HAUPPAUGE_HVR1110:
dev->init_data.name = "HVR 1110";
dev->init_data.get_key = get_key_hvr1110;
dev->init_data.ir_codes = RC_MAP_HAUPPAUGE;
info.addr = 0x71;
break;
case SAA7134_BOARD_BEHOLD_607FM_MK3:
case SAA7134_BOARD_BEHOLD_607FM_MK5:
case SAA7134_BOARD_BEHOLD_609FM_MK3:
case SAA7134_BOARD_BEHOLD_609FM_MK5:
case SAA7134_BOARD_BEHOLD_607RDS_MK3:
case SAA7134_BOARD_BEHOLD_607RDS_MK5:
case SAA7134_BOARD_BEHOLD_609RDS_MK3:
case SAA7134_BOARD_BEHOLD_609RDS_MK5:
case SAA7134_BOARD_BEHOLD_M6:
case SAA7134_BOARD_BEHOLD_M63:
case SAA7134_BOARD_BEHOLD_M6_EXTRA:
case SAA7134_BOARD_BEHOLD_H6:
case SAA7134_BOARD_BEHOLD_X7:
case SAA7134_BOARD_BEHOLD_H7:
case SAA7134_BOARD_BEHOLD_A7:
dev->init_data.name = "BeholdTV";
dev->init_data.get_key = get_key_beholdm6xx;
dev->init_data.ir_codes = RC_MAP_BEHOLD;
dev->init_data.type = RC_TYPE_NEC;
info.addr = 0x2d;
break;
case SAA7134_BOARD_AVERMEDIA_CARDBUS_501:
case SAA7134_BOARD_AVERMEDIA_CARDBUS_506:
info.addr = 0x40;
break;
case SAA7134_BOARD_FLYDVB_TRIO:
dev->init_data.name = "FlyDVB Trio";
dev->init_data.get_key = get_key_flydvb_trio;
dev->init_data.ir_codes = RC_MAP_FLYDVB;
info.addr = 0x0b;
break;
default:
dprintk("No I2C IR support for board %x\n", dev->board);
return;
}
if (dev->init_data.name)
info.platform_data = &dev->init_data;
i2c_new_device(&dev->i2c_adap, &info);
}
static int saa7134_raw_decode_irq(struct saa7134_dev *dev)
{
struct saa7134_card_ir *ir = dev->remote;
unsigned long timeout;
int space;
/* Generate initial event */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
space = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2) & ir->mask_keydown;
ir_raw_event_store_edge(dev->remote->dev, space ? IR_SPACE : IR_PULSE);
/*
* Wait 15 ms from the start of the first IR event before processing
* the event. This time is enough for NEC protocol. May need adjustments
* to work with other protocols.
*/
if (!ir->active) {
timeout = jiffies + msecs_to_jiffies(15);
mod_timer(&ir->timer, timeout);
ir->active = true;
}
return 1;
}
| gpl-2.0 |
El-Nath/bidji-find5 | drivers/rtc/rtc-msm.c | 3458 | 20970 | /*
* Copyright (C) 2008 Google, Inc.
* Copyright (c) 2009-2011 The Linux Foundation. All rights reserved.
* Author: San Mehat <san@google.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/module.h>
#include <linux/version.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/android_alarm.h>
#include <linux/rtc.h>
#include <linux/rtc-msm.h>
#include <linux/msm_rpcrouter.h>
#include <mach/msm_rpcrouter.h>
#define APP_TIMEREMOTE_PDEV_NAME "rs00000000"
#define TIMEREMOTE_PROCEEDURE_SET_JULIAN 6
#define TIMEREMOTE_PROCEEDURE_GET_JULIAN 7
#ifdef CONFIG_RTC_SECURE_TIME_SUPPORT
#define TIMEREMOTE_PROCEEDURE_GET_SECURE_JULIAN 11
#define TIMEREMOTE_PROCEEDURE_SET_SECURE_JULIAN 16
#endif
#define TIMEREMOTE_PROG_NUMBER 0x30000048
#define TIMEREMOTE_PROG_VER_1 0x00010001
#define TIMEREMOTE_PROG_VER_2 0x00040001
#define RTC_REQUEST_CB_PROC 0x17
#define RTC_CLIENT_INIT_PROC 0x12
#define RTC_EVENT_CB_PROC 0x1
#define RTC_CB_ID 0x1
/* Client request errors */
enum rtc_rpc_err {
ERR_NONE,
ERR_CLIENT_ID_PTR, /* Invalid client ID pointer */
ERR_CLIENT_TYPE, /* Invalid client type */
ERR_CLIENT_ID, /* Invalid client ID */
ERR_TASK_NOT_READY, /* task is not ready for clients */
ERR_INVALID_PROCESSOR, /* Invalid processor id */
ERR_UNSUPPORTED, /* Unsupported request */
ERR_GENERAL, /* Any General Error */
ERR_RPC, /* Any ONCRPC Error */
ERR_ALREADY_REG, /* Client already registered */
ERR_MAX
};
enum processor_type {
CLIENT_PROCESSOR_NONE = 0,
CLIENT_PROCESSOR_MODEM,
CLIENT_PROCESSOR_APP1,
CLIENT_PROCESSOR_APP2,
CLIENT_PROCESSOR_MAX
};
/* Client types */
enum client_type {
CLIENT_TYPE_GEN1 = 0,
CLIENT_FLOATING1,
CLIENT_FLOATING2,
CLIENT_TYPE_INTERNAL,
CLIENT_TYPE_GENOFF_UPDATE,
CLIENT_TYPE_MAX
};
/* Event types */
enum event_type {
EVENT_TOD_CHANGE = 0,
EVENT_GENOFF_CHANGE,
EVENT_MAX
};
struct tod_update_info {
uint32_t tick;
uint64_t stamp;
uint32_t freq;
};
enum time_bases_info {
TIME_RTC = 0,
TIME_TOD,
TIME_USER,
TIME_SECURE,
TIME_INVALID
};
struct genoff_update_info {
enum time_bases_info time_base;
uint64_t offset;
};
union cb_info {
struct tod_update_info tod_update;
struct genoff_update_info genoff_update;
};
struct rtc_cb_recv {
uint32_t client_cb_id;
enum event_type event;
uint32_t cb_info_ptr;
union cb_info cb_info_data;
};
struct msm_rtc {
int proc;
struct msm_rpc_client *rpc_client;
u8 client_id;
struct rtc_device *rtc;
#ifdef CONFIG_RTC_SECURE_TIME_SUPPORT
struct rtc_device *rtcsecure;
#endif
unsigned long rtcalarm_time;
};
struct rpc_time_julian {
uint32_t year;
uint32_t month;
uint32_t day;
uint32_t hour;
uint32_t minute;
uint32_t second;
uint32_t day_of_week;
};
struct rtc_tod_args {
int proc;
struct rtc_time *tm;
};
#ifdef CONFIG_PM
struct suspend_state_info {
atomic_t state;
int64_t tick_at_suspend;
};
static struct suspend_state_info suspend_state = {ATOMIC_INIT(0), 0};
void msmrtc_updateatsuspend(struct timespec *ts)
{
int64_t now, sleep, sclk_max;
if (atomic_read(&suspend_state.state)) {
now = msm_timer_get_sclk_time(&sclk_max);
if (now && suspend_state.tick_at_suspend) {
if (now < suspend_state.tick_at_suspend) {
sleep = sclk_max -
suspend_state.tick_at_suspend + now;
} else
sleep = now - suspend_state.tick_at_suspend;
timespec_add_ns(ts, sleep);
suspend_state.tick_at_suspend = now;
} else
pr_err("%s: Invalid ticks from SCLK now=%lld"
"tick_at_suspend=%lld", __func__, now,
suspend_state.tick_at_suspend);
}
}
#else
void msmrtc_updateatsuspend(struct timespec *ts) { }
#endif
EXPORT_SYMBOL(msmrtc_updateatsuspend);
static int msmrtc_tod_proc_args(struct msm_rpc_client *client, void *buff,
void *data)
{
struct rtc_tod_args *rtc_args = data;
if ((rtc_args->proc == TIMEREMOTE_PROCEEDURE_SET_JULIAN)
#ifdef CONFIG_RTC_SECURE_TIME_SUPPORT
|| (rtc_args->proc == TIMEREMOTE_PROCEEDURE_SET_SECURE_JULIAN)
#endif
) {
struct timeremote_set_julian_req {
uint32_t opt_arg;
struct rpc_time_julian time;
};
struct timeremote_set_julian_req *set_req = buff;
set_req->opt_arg = cpu_to_be32(0x1);
set_req->time.year = cpu_to_be32(rtc_args->tm->tm_year);
set_req->time.month = cpu_to_be32(rtc_args->tm->tm_mon + 1);
set_req->time.day = cpu_to_be32(rtc_args->tm->tm_mday);
set_req->time.hour = cpu_to_be32(rtc_args->tm->tm_hour);
set_req->time.minute = cpu_to_be32(rtc_args->tm->tm_min);
set_req->time.second = cpu_to_be32(rtc_args->tm->tm_sec);
set_req->time.day_of_week = cpu_to_be32(rtc_args->tm->tm_wday);
return sizeof(*set_req);
} else if ((rtc_args->proc == TIMEREMOTE_PROCEEDURE_GET_JULIAN)
#ifdef CONFIG_RTC_SECURE_TIME_SUPPORT
|| (rtc_args->proc == TIMEREMOTE_PROCEEDURE_GET_SECURE_JULIAN)
#endif
) {
*(uint32_t *)buff = (uint32_t) cpu_to_be32(0x1);
return sizeof(uint32_t);
} else
return 0;
}
static bool rtc_check_overflow(struct rtc_time *tm)
{
if (tm->tm_year < 138)
return false;
if (tm->tm_year > 138)
return true;
if ((tm->tm_year == 138) && (tm->tm_mon == 0) && (tm->tm_mday < 19))
return false;
return true;
}
static int msmrtc_tod_proc_result(struct msm_rpc_client *client, void *buff,
void *data)
{
struct rtc_tod_args *rtc_args = data;
if ((rtc_args->proc == TIMEREMOTE_PROCEEDURE_GET_JULIAN)
#ifdef CONFIG_RTC_SECURE_TIME_SUPPORT
|| (rtc_args->proc == TIMEREMOTE_PROCEEDURE_GET_SECURE_JULIAN)
#endif
) {
struct timeremote_get_julian_rep {
uint32_t opt_arg;
struct rpc_time_julian time;
};
struct timeremote_get_julian_rep *result = buff;
if (be32_to_cpu(result->opt_arg) != 0x1)
return -ENODATA;
rtc_args->tm->tm_year = be32_to_cpu(result->time.year);
rtc_args->tm->tm_mon = be32_to_cpu(result->time.month);
rtc_args->tm->tm_mday = be32_to_cpu(result->time.day);
rtc_args->tm->tm_hour = be32_to_cpu(result->time.hour);
rtc_args->tm->tm_min = be32_to_cpu(result->time.minute);
rtc_args->tm->tm_sec = be32_to_cpu(result->time.second);
rtc_args->tm->tm_wday = be32_to_cpu(result->time.day_of_week);
pr_debug("%s: %.2u/%.2u/%.4u %.2u:%.2u:%.2u (%.2u)\n",
__func__, rtc_args->tm->tm_mon, rtc_args->tm->tm_mday,
rtc_args->tm->tm_year, rtc_args->tm->tm_hour,
rtc_args->tm->tm_min, rtc_args->tm->tm_sec,
rtc_args->tm->tm_wday);
/* RTC layer expects years to start at 1900 */
rtc_args->tm->tm_year -= 1900;
/* RTC layer expects mons to be 0 based */
rtc_args->tm->tm_mon--;
if (rtc_valid_tm(rtc_args->tm) < 0) {
pr_err("%s: Retrieved data/time not valid\n", __func__);
rtc_time_to_tm(0, rtc_args->tm);
}
/*
* Check if the time received is > 01-19-2038, to prevent
* overflow. In such a case, return the EPOCH time.
*/
if (rtc_check_overflow(rtc_args->tm) == true) {
pr_err("Invalid time (year > 2038)\n");
rtc_time_to_tm(0, rtc_args->tm);
}
return 0;
} else
return 0;
}
static int
msmrtc_timeremote_set_time(struct device *dev, struct rtc_time *tm)
{
int rc;
struct rtc_tod_args rtc_args;
struct msm_rtc *rtc_pdata = dev_get_drvdata(dev);
if (tm->tm_year < 1900)
tm->tm_year += 1900;
if (tm->tm_year < 1970)
return -EINVAL;
dev_dbg(dev, "%s: %.2u/%.2u/%.4u %.2u:%.2u:%.2u (%.2u)\n",
__func__, tm->tm_mon, tm->tm_mday, tm->tm_year,
tm->tm_hour, tm->tm_min, tm->tm_sec, tm->tm_wday);
rtc_args.proc = TIMEREMOTE_PROCEEDURE_SET_JULIAN;
rtc_args.tm = tm;
rc = msm_rpc_client_req(rtc_pdata->rpc_client,
TIMEREMOTE_PROCEEDURE_SET_JULIAN,
msmrtc_tod_proc_args, &rtc_args,
NULL, NULL, -1);
if (rc) {
dev_err(dev, "%s: rtc time (TOD) could not be set\n", __func__);
return rc;
}
return 0;
}
static int
msmrtc_timeremote_read_time(struct device *dev, struct rtc_time *tm)
{
int rc;
struct rtc_tod_args rtc_args;
struct msm_rtc *rtc_pdata = dev_get_drvdata(dev);
rtc_args.proc = TIMEREMOTE_PROCEEDURE_GET_JULIAN;
rtc_args.tm = tm;
rc = msm_rpc_client_req(rtc_pdata->rpc_client,
TIMEREMOTE_PROCEEDURE_GET_JULIAN,
msmrtc_tod_proc_args, &rtc_args,
msmrtc_tod_proc_result, &rtc_args, -1);
if (rc) {
dev_err(dev, "%s: Error retrieving rtc (TOD) time\n", __func__);
return rc;
}
return 0;
}
static int
msmrtc_virtual_alarm_set(struct device *dev, struct rtc_wkalrm *a)
{
struct msm_rtc *rtc_pdata = dev_get_drvdata(dev);
unsigned long now = get_seconds();
if (!a->enabled) {
rtc_pdata->rtcalarm_time = 0;
return 0;
} else
rtc_tm_to_time(&a->time, &(rtc_pdata->rtcalarm_time));
if (now > rtc_pdata->rtcalarm_time) {
dev_err(dev, "%s: Attempt to set alarm in the past\n",
__func__);
rtc_pdata->rtcalarm_time = 0;
return -EINVAL;
}
return 0;
}
static struct rtc_class_ops msm_rtc_ops = {
.read_time = msmrtc_timeremote_read_time,
.set_time = msmrtc_timeremote_set_time,
.set_alarm = msmrtc_virtual_alarm_set,
};
#ifdef CONFIG_RTC_SECURE_TIME_SUPPORT
static int
msmrtc_timeremote_set_time_secure(struct device *dev, struct rtc_time *tm)
{
int rc;
struct rtc_tod_args rtc_args;
struct msm_rtc *rtc_pdata = dev_get_drvdata(dev);
if (tm->tm_year < 1900)
tm->tm_year += 1900;
if (tm->tm_year < 1970)
return -EINVAL;
dev_dbg(dev, "%s: %.2u/%.2u/%.4u %.2u:%.2u:%.2u (%.2u)\n",
__func__, tm->tm_mon, tm->tm_mday, tm->tm_year,
tm->tm_hour, tm->tm_min, tm->tm_sec, tm->tm_wday);
rtc_args.proc = TIMEREMOTE_PROCEEDURE_SET_SECURE_JULIAN;
rtc_args.tm = tm;
rc = msm_rpc_client_req(rtc_pdata->rpc_client,
TIMEREMOTE_PROCEEDURE_SET_SECURE_JULIAN,
msmrtc_tod_proc_args, &rtc_args,
NULL, NULL, -1);
if (rc) {
dev_err(dev,
"%s: rtc secure time could not be set\n", __func__);
return rc;
}
return 0;
}
static int
msmrtc_timeremote_read_time_secure(struct device *dev, struct rtc_time *tm)
{
int rc;
struct rtc_tod_args rtc_args;
struct msm_rtc *rtc_pdata = dev_get_drvdata(dev);
rtc_args.proc = TIMEREMOTE_PROCEEDURE_GET_SECURE_JULIAN;
rtc_args.tm = tm;
rc = msm_rpc_client_req(rtc_pdata->rpc_client,
TIMEREMOTE_PROCEEDURE_GET_SECURE_JULIAN, msmrtc_tod_proc_args,
&rtc_args, msmrtc_tod_proc_result, &rtc_args, -1);
if (rc) {
dev_err(dev,
"%s: Error retrieving secure rtc time\n", __func__);
return rc;
}
return 0;
}
static struct rtc_class_ops msm_rtc_ops_secure = {
.read_time = msmrtc_timeremote_read_time_secure,
.set_time = msmrtc_timeremote_set_time_secure,
};
#endif
static void process_cb_request(void *buffer)
{
struct rtc_cb_recv *rtc_cb = buffer;
struct timespec ts, tv;
rtc_cb->client_cb_id = be32_to_cpu(rtc_cb->client_cb_id);
rtc_cb->event = be32_to_cpu(rtc_cb->event);
rtc_cb->cb_info_ptr = be32_to_cpu(rtc_cb->cb_info_ptr);
if (rtc_cb->event == EVENT_TOD_CHANGE) {
/* A TOD update has been received from the Modem */
rtc_cb->cb_info_data.tod_update.tick =
be32_to_cpu(rtc_cb->cb_info_data.tod_update.tick);
rtc_cb->cb_info_data.tod_update.stamp =
be64_to_cpu(rtc_cb->cb_info_data.tod_update.stamp);
rtc_cb->cb_info_data.tod_update.freq =
be32_to_cpu(rtc_cb->cb_info_data.tod_update.freq);
pr_info("RPC CALL -- TOD TIME UPDATE: ttick = %d\n"
"stamp=%lld, freq = %d\n",
rtc_cb->cb_info_data.tod_update.tick,
rtc_cb->cb_info_data.tod_update.stamp,
rtc_cb->cb_info_data.tod_update.freq);
getnstimeofday(&ts);
msmrtc_updateatsuspend(&ts);
rtc_hctosys();
getnstimeofday(&tv);
/* Update the alarm information with the new time info. */
alarm_update_timedelta(ts, tv);
} else
pr_err("%s: Unknown event EVENT=%x\n",
__func__, rtc_cb->event);
}
static int msmrtc_cb_func(struct msm_rpc_client *client, void *buffer, int size)
{
int rc = -1;
struct rpc_request_hdr *recv = buffer;
recv->xid = be32_to_cpu(recv->xid);
recv->type = be32_to_cpu(recv->type);
recv->rpc_vers = be32_to_cpu(recv->rpc_vers);
recv->prog = be32_to_cpu(recv->prog);
recv->vers = be32_to_cpu(recv->vers);
recv->procedure = be32_to_cpu(recv->procedure);
if (recv->procedure == RTC_EVENT_CB_PROC)
process_cb_request((void *) (recv + 1));
msm_rpc_start_accepted_reply(client, recv->xid,
RPC_ACCEPTSTAT_SUCCESS);
rc = msm_rpc_send_accepted_reply(client, 0);
if (rc) {
pr_debug("%s: sending reply failed: %d\n", __func__, rc);
return rc;
}
return 0;
}
static int msmrtc_rpc_proc_args(struct msm_rpc_client *client, void *buff,
void *data)
{
struct msm_rtc *rtc_pdata = data;
if (rtc_pdata->proc == RTC_CLIENT_INIT_PROC) {
/* arguments passed to the client_init function */
struct rtc_client_init_req {
enum client_type client;
uint32_t client_id_ptr;
u8 client_id;
enum processor_type processor;
};
struct rtc_client_init_req *req_1 = buff;
req_1->client = cpu_to_be32(CLIENT_TYPE_INTERNAL);
req_1->client_id_ptr = cpu_to_be32(0x1);
req_1->client_id = (u8) cpu_to_be32(0x1);
req_1->processor = cpu_to_be32(CLIENT_PROCESSOR_APP1);
return sizeof(*req_1);
} else if (rtc_pdata->proc == RTC_REQUEST_CB_PROC) {
/* arguments passed to the request_cb function */
struct rtc_event_req {
u8 client_id;
uint32_t rtc_cb_id;
};
struct rtc_event_req *req_2 = buff;
req_2->client_id = (u8) cpu_to_be32(rtc_pdata->client_id);
req_2->rtc_cb_id = cpu_to_be32(RTC_CB_ID);
return sizeof(*req_2);
} else
return 0;
}
static int msmrtc_rpc_proc_result(struct msm_rpc_client *client, void *buff,
void *data)
{
uint32_t result = -EINVAL;
struct msm_rtc *rtc_pdata = data;
if (rtc_pdata->proc == RTC_CLIENT_INIT_PROC) {
/* process reply received from client_init function */
uint32_t client_id_ptr;
result = be32_to_cpu(*(uint32_t *)buff);
buff += sizeof(uint32_t);
client_id_ptr = be32_to_cpu(*(uint32_t *)(buff));
buff += sizeof(uint32_t);
if (client_id_ptr == 1)
rtc_pdata->client_id = (u8)
be32_to_cpu(*(uint32_t *)(buff));
else {
pr_debug("%s: Client-id not received from Modem\n",
__func__);
return -EINVAL;
}
} else if (rtc_pdata->proc == RTC_REQUEST_CB_PROC) {
/* process reply received from request_cb function */
result = be32_to_cpu(*(uint32_t *)buff);
}
if (result == ERR_NONE) {
pr_debug("%s: RPC client reply for PROC=%x success\n",
__func__, rtc_pdata->proc);
return 0;
}
pr_debug("%s: RPC client registration failed ERROR=%x\n",
__func__, result);
return -EINVAL;
}
static int msmrtc_setup_cb(struct msm_rtc *rtc_pdata)
{
int rc;
/* Register with the server with client specific info */
rtc_pdata->proc = RTC_CLIENT_INIT_PROC;
rc = msm_rpc_client_req(rtc_pdata->rpc_client, RTC_CLIENT_INIT_PROC,
msmrtc_rpc_proc_args, rtc_pdata,
msmrtc_rpc_proc_result, rtc_pdata, -1);
if (rc) {
pr_debug("%s: RPC client registration for PROC:%x failed\n",
__func__, RTC_CLIENT_INIT_PROC);
return rc;
}
/* Register with server for the callback event */
rtc_pdata->proc = RTC_REQUEST_CB_PROC;
rc = msm_rpc_client_req(rtc_pdata->rpc_client, RTC_REQUEST_CB_PROC,
msmrtc_rpc_proc_args, rtc_pdata,
msmrtc_rpc_proc_result, rtc_pdata, -1);
if (rc) {
pr_debug("%s: RPC client registration for PROC:%x failed\n",
__func__, RTC_REQUEST_CB_PROC);
}
return rc;
}
static int __devinit
msmrtc_probe(struct platform_device *pdev)
{
int rc;
struct msm_rtc *rtc_pdata = NULL;
struct rpcsvr_platform_device *rdev =
container_of(pdev, struct rpcsvr_platform_device, base);
uint32_t prog_version;
if (pdev->id == (TIMEREMOTE_PROG_VER_1 & RPC_VERSION_MAJOR_MASK))
prog_version = TIMEREMOTE_PROG_VER_1;
else if (pdev->id == (TIMEREMOTE_PROG_VER_2 &
RPC_VERSION_MAJOR_MASK))
prog_version = TIMEREMOTE_PROG_VER_2;
else
return -EINVAL;
rtc_pdata = kzalloc(sizeof(*rtc_pdata), GFP_KERNEL);
if (rtc_pdata == NULL) {
dev_err(&pdev->dev,
"%s: Unable to allocate memory\n", __func__);
return -ENOMEM;
}
rtc_pdata->rpc_client = msm_rpc_register_client("rtc", rdev->prog,
prog_version, 1, msmrtc_cb_func);
if (IS_ERR(rtc_pdata->rpc_client)) {
dev_err(&pdev->dev,
"%s: init RPC failed! VERS = %x\n", __func__,
prog_version);
rc = PTR_ERR(rtc_pdata->rpc_client);
kfree(rtc_pdata);
return rc;
}
/*
* Set up the callback client.
* For older targets this initialization will fail
*/
rc = msmrtc_setup_cb(rtc_pdata);
if (rc)
dev_dbg(&pdev->dev, "%s: Could not initialize RPC callback\n",
__func__);
rtc_pdata->rtcalarm_time = 0;
platform_set_drvdata(pdev, rtc_pdata);
rtc_pdata->rtc = rtc_device_register("msm_rtc",
&pdev->dev,
&msm_rtc_ops,
THIS_MODULE);
if (IS_ERR(rtc_pdata->rtc)) {
dev_err(&pdev->dev, "%s: Can't register RTC device (%ld)\n",
pdev->name, PTR_ERR(rtc_pdata->rtc));
rc = PTR_ERR(rtc_pdata->rtc);
goto fail_cb_setup;
}
#ifdef CONFIG_RTC_SECURE_TIME_SUPPORT
rtc_pdata->rtcsecure = rtc_device_register("msm_rtc_secure",
&pdev->dev,
&msm_rtc_ops_secure,
THIS_MODULE);
if (IS_ERR(rtc_pdata->rtcsecure)) {
dev_err(&pdev->dev,
"%s: Can't register RTC Secure device (%ld)\n",
pdev->name, PTR_ERR(rtc_pdata->rtcsecure));
rtc_device_unregister(rtc_pdata->rtc);
rc = PTR_ERR(rtc_pdata->rtcsecure);
goto fail_cb_setup;
}
#endif
#ifdef CONFIG_RTC_ASYNC_MODEM_SUPPORT
rtc_hctosys();
#endif
return 0;
fail_cb_setup:
msm_rpc_unregister_client(rtc_pdata->rpc_client);
kfree(rtc_pdata);
return rc;
}
#ifdef CONFIG_PM
static void
msmrtc_alarmtimer_expired(unsigned long _data,
struct msm_rtc *rtc_pdata)
{
pr_debug("%s: Generating alarm event (src %lu)\n",
rtc_pdata->rtc->name, _data);
rtc_update_irq(rtc_pdata->rtc, 1, RTC_IRQF | RTC_AF);
rtc_pdata->rtcalarm_time = 0;
}
static int
msmrtc_suspend(struct platform_device *dev, pm_message_t state)
{
int rc, diff;
struct rtc_time tm;
unsigned long now;
struct msm_rtc *rtc_pdata = platform_get_drvdata(dev);
suspend_state.tick_at_suspend = msm_timer_get_sclk_time(NULL);
if (rtc_pdata->rtcalarm_time) {
rc = msmrtc_timeremote_read_time(&dev->dev, &tm);
if (rc) {
dev_err(&dev->dev,
"%s: Unable to read from RTC\n", __func__);
return rc;
}
rtc_tm_to_time(&tm, &now);
diff = rtc_pdata->rtcalarm_time - now;
if (diff <= 0) {
msmrtc_alarmtimer_expired(1 , rtc_pdata);
msm_pm_set_max_sleep_time(0);
atomic_inc(&suspend_state.state);
return 0;
}
msm_pm_set_max_sleep_time((int64_t)
((int64_t) diff * NSEC_PER_SEC));
} else
msm_pm_set_max_sleep_time(0);
atomic_inc(&suspend_state.state);
return 0;
}
static int
msmrtc_resume(struct platform_device *dev)
{
int rc, diff;
struct rtc_time tm;
unsigned long now;
struct msm_rtc *rtc_pdata = platform_get_drvdata(dev);
if (rtc_pdata->rtcalarm_time) {
rc = msmrtc_timeremote_read_time(&dev->dev, &tm);
if (rc) {
dev_err(&dev->dev,
"%s: Unable to read from RTC\n", __func__);
return rc;
}
rtc_tm_to_time(&tm, &now);
diff = rtc_pdata->rtcalarm_time - now;
if (diff <= 0)
msmrtc_alarmtimer_expired(2 , rtc_pdata);
}
suspend_state.tick_at_suspend = 0;
atomic_dec(&suspend_state.state);
return 0;
}
#else
#define msmrtc_suspend NULL
#define msmrtc_resume NULL
#endif
static int __devexit msmrtc_remove(struct platform_device *pdev)
{
struct msm_rtc *rtc_pdata = platform_get_drvdata(pdev);
rtc_device_unregister(rtc_pdata->rtc);
#ifdef CONFIG_RTC_SECURE_TIME_SUPPORT
rtc_device_unregister(rtc_pdata->rtcsecure);
#endif
msm_rpc_unregister_client(rtc_pdata->rpc_client);
kfree(rtc_pdata);
return 0;
}
static struct platform_driver msmrtc_driver = {
.probe = msmrtc_probe,
.suspend = msmrtc_suspend,
.resume = msmrtc_resume,
.remove = __devexit_p(msmrtc_remove),
.driver = {
.name = APP_TIMEREMOTE_PDEV_NAME,
.owner = THIS_MODULE,
},
};
static int __init msmrtc_init(void)
{
int rc;
/*
* For backward compatibility, register multiple platform
* drivers with the RPC PROG_VERS to be supported.
*
* Explicit cast away of 'constness' for driver.name in order to
* initialize it here.
*/
snprintf((char *)msmrtc_driver.driver.name,
strlen(msmrtc_driver.driver.name)+1,
"rs%08x", TIMEREMOTE_PROG_NUMBER);
pr_debug("RTC Registering with %s\n", msmrtc_driver.driver.name);
rc = platform_driver_register(&msmrtc_driver);
if (rc)
pr_err("%s: platfrom_driver_register failed\n", __func__);
return rc;
}
static void __exit msmrtc_exit(void)
{
platform_driver_unregister(&msmrtc_driver);
}
module_init(msmrtc_init);
module_exit(msmrtc_exit);
MODULE_DESCRIPTION("RTC driver for Qualcomm MSM7x00a chipsets");
MODULE_AUTHOR("San Mehat <san@android.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
fileton/linux | fs/logfs/inode.c | 4226 | 11549 | /*
* fs/logfs/inode.c - inode handling code
*
* As should be obvious for Linux kernel code, license is GPLv2
*
* Copyright (c) 2005-2008 Joern Engel <joern@logfs.org>
*/
#include "logfs.h"
#include <linux/slab.h>
#include <linux/writeback.h>
#include <linux/backing-dev.h>
/*
* How soon to reuse old inode numbers? LogFS doesn't store deleted inodes
* on the medium. It therefore also lacks a method to store the previous
* generation number for deleted inodes. Instead a single generation number
* is stored which will be used for new inodes. Being just a 32bit counter,
* this can obvious wrap relatively quickly. So we only reuse inodes if we
* know that a fair number of inodes can be created before we have to increment
* the generation again - effectively adding some bits to the counter.
* But being too aggressive here means we keep a very large and very sparse
* inode file, wasting space on indirect blocks.
* So what is a good value? Beats me. 64k seems moderately bad on both
* fronts, so let's use that for now...
*
* NFS sucks, as everyone already knows.
*/
#define INOS_PER_WRAP (0x10000)
/*
* Logfs' requirement to read inodes for garbage collection makes life a bit
* harder. GC may have to read inodes that are in I_FREEING state, when they
* are being written out - and waiting for GC to make progress, naturally.
*
* So we cannot just call iget() or some variant of it, but first have to check
* whether the inode in question might be in I_FREEING state. Therefore we
* maintain our own per-sb list of "almost deleted" inodes and check against
* that list first. Normally this should be at most 1-2 entries long.
*
* Also, inodes have logfs-specific reference counting on top of what the vfs
* does. When .destroy_inode is called, normally the reference count will drop
* to zero and the inode gets deleted. But if GC accessed the inode, its
* refcount will remain nonzero and final deletion will have to wait.
*
* As a result we have two sets of functions to get/put inodes:
* logfs_safe_iget/logfs_safe_iput - safe to call from GC context
* logfs_iget/iput - normal version
*/
static struct kmem_cache *logfs_inode_cache;
static DEFINE_SPINLOCK(logfs_inode_lock);
static void logfs_inode_setops(struct inode *inode)
{
switch (inode->i_mode & S_IFMT) {
case S_IFDIR:
inode->i_op = &logfs_dir_iops;
inode->i_fop = &logfs_dir_fops;
inode->i_mapping->a_ops = &logfs_reg_aops;
break;
case S_IFREG:
inode->i_op = &logfs_reg_iops;
inode->i_fop = &logfs_reg_fops;
inode->i_mapping->a_ops = &logfs_reg_aops;
break;
case S_IFLNK:
inode->i_op = &logfs_symlink_iops;
inode->i_mapping->a_ops = &logfs_reg_aops;
break;
case S_IFSOCK: /* fall through */
case S_IFBLK: /* fall through */
case S_IFCHR: /* fall through */
case S_IFIFO:
init_special_inode(inode, inode->i_mode, inode->i_rdev);
break;
default:
BUG();
}
}
static struct inode *__logfs_iget(struct super_block *sb, ino_t ino)
{
struct inode *inode = iget_locked(sb, ino);
int err;
if (!inode)
return ERR_PTR(-ENOMEM);
if (!(inode->i_state & I_NEW))
return inode;
err = logfs_read_inode(inode);
if (err || inode->i_nlink == 0) {
/* inode->i_nlink == 0 can be true when called from
* block validator */
/* set i_nlink to 0 to prevent caching */
clear_nlink(inode);
logfs_inode(inode)->li_flags |= LOGFS_IF_ZOMBIE;
iget_failed(inode);
if (!err)
err = -ENOENT;
return ERR_PTR(err);
}
logfs_inode_setops(inode);
unlock_new_inode(inode);
return inode;
}
struct inode *logfs_iget(struct super_block *sb, ino_t ino)
{
BUG_ON(ino == LOGFS_INO_MASTER);
BUG_ON(ino == LOGFS_INO_SEGFILE);
return __logfs_iget(sb, ino);
}
/*
* is_cached is set to 1 if we hand out a cached inode, 0 otherwise.
* this allows logfs_iput to do the right thing later
*/
struct inode *logfs_safe_iget(struct super_block *sb, ino_t ino, int *is_cached)
{
struct logfs_super *super = logfs_super(sb);
struct logfs_inode *li;
if (ino == LOGFS_INO_MASTER)
return super->s_master_inode;
if (ino == LOGFS_INO_SEGFILE)
return super->s_segfile_inode;
spin_lock(&logfs_inode_lock);
list_for_each_entry(li, &super->s_freeing_list, li_freeing_list)
if (li->vfs_inode.i_ino == ino) {
li->li_refcount++;
spin_unlock(&logfs_inode_lock);
*is_cached = 1;
return &li->vfs_inode;
}
spin_unlock(&logfs_inode_lock);
*is_cached = 0;
return __logfs_iget(sb, ino);
}
static void logfs_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(logfs_inode_cache, logfs_inode(inode));
}
static void __logfs_destroy_inode(struct inode *inode)
{
struct logfs_inode *li = logfs_inode(inode);
BUG_ON(li->li_block);
list_del(&li->li_freeing_list);
call_rcu(&inode->i_rcu, logfs_i_callback);
}
static void __logfs_destroy_meta_inode(struct inode *inode)
{
struct logfs_inode *li = logfs_inode(inode);
BUG_ON(li->li_block);
call_rcu(&inode->i_rcu, logfs_i_callback);
}
static void logfs_destroy_inode(struct inode *inode)
{
struct logfs_inode *li = logfs_inode(inode);
if (inode->i_ino < LOGFS_RESERVED_INOS) {
/*
* The reserved inodes are never destroyed unless we are in
* unmont path.
*/
__logfs_destroy_meta_inode(inode);
return;
}
BUG_ON(list_empty(&li->li_freeing_list));
spin_lock(&logfs_inode_lock);
li->li_refcount--;
if (li->li_refcount == 0)
__logfs_destroy_inode(inode);
spin_unlock(&logfs_inode_lock);
}
void logfs_safe_iput(struct inode *inode, int is_cached)
{
if (inode->i_ino == LOGFS_INO_MASTER)
return;
if (inode->i_ino == LOGFS_INO_SEGFILE)
return;
if (is_cached) {
logfs_destroy_inode(inode);
return;
}
iput(inode);
}
static void logfs_init_inode(struct super_block *sb, struct inode *inode)
{
struct logfs_inode *li = logfs_inode(inode);
int i;
li->li_flags = 0;
li->li_height = 0;
li->li_used_bytes = 0;
li->li_block = NULL;
i_uid_write(inode, 0);
i_gid_write(inode, 0);
inode->i_size = 0;
inode->i_blocks = 0;
inode->i_ctime = CURRENT_TIME;
inode->i_mtime = CURRENT_TIME;
li->li_refcount = 1;
INIT_LIST_HEAD(&li->li_freeing_list);
for (i = 0; i < LOGFS_EMBEDDED_FIELDS; i++)
li->li_data[i] = 0;
return;
}
static struct inode *logfs_alloc_inode(struct super_block *sb)
{
struct logfs_inode *li;
li = kmem_cache_alloc(logfs_inode_cache, GFP_NOFS);
if (!li)
return NULL;
logfs_init_inode(sb, &li->vfs_inode);
return &li->vfs_inode;
}
/*
* In logfs inodes are written to an inode file. The inode file, like any
* other file, is managed with a inode. The inode file's inode, aka master
* inode, requires special handling in several respects. First, it cannot be
* written to the inode file, so it is stored in the journal instead.
*
* Secondly, this inode cannot be written back and destroyed before all other
* inodes have been written. The ordering is important. Linux' VFS is happily
* unaware of the ordering constraint and would ordinarily destroy the master
* inode at umount time while other inodes are still in use and dirty. Not
* good.
*
* So logfs makes sure the master inode is not written until all other inodes
* have been destroyed. Sadly, this method has another side-effect. The VFS
* will notice one remaining inode and print a frightening warning message.
* Worse, it is impossible to judge whether such a warning was caused by the
* master inode or any other inodes have leaked as well.
*
* Our attempt of solving this is with logfs_new_meta_inode() below. Its
* purpose is to create a new inode that will not trigger the warning if such
* an inode is still in use. An ugly hack, no doubt. Suggections for
* improvement are welcome.
*
* AV: that's what ->put_super() is for...
*/
struct inode *logfs_new_meta_inode(struct super_block *sb, u64 ino)
{
struct inode *inode;
inode = new_inode(sb);
if (!inode)
return ERR_PTR(-ENOMEM);
inode->i_mode = S_IFREG;
inode->i_ino = ino;
inode->i_data.a_ops = &logfs_reg_aops;
mapping_set_gfp_mask(&inode->i_data, GFP_NOFS);
return inode;
}
struct inode *logfs_read_meta_inode(struct super_block *sb, u64 ino)
{
struct inode *inode;
int err;
inode = logfs_new_meta_inode(sb, ino);
if (IS_ERR(inode))
return inode;
err = logfs_read_inode(inode);
if (err) {
iput(inode);
return ERR_PTR(err);
}
logfs_inode_setops(inode);
return inode;
}
static int logfs_write_inode(struct inode *inode, struct writeback_control *wbc)
{
int ret;
long flags = WF_LOCK;
/* Can only happen if creat() failed. Safe to skip. */
if (logfs_inode(inode)->li_flags & LOGFS_IF_STILLBORN)
return 0;
ret = __logfs_write_inode(inode, NULL, flags);
LOGFS_BUG_ON(ret, inode->i_sb);
return ret;
}
/* called with inode->i_lock held */
static int logfs_drop_inode(struct inode *inode)
{
struct logfs_super *super = logfs_super(inode->i_sb);
struct logfs_inode *li = logfs_inode(inode);
spin_lock(&logfs_inode_lock);
list_move(&li->li_freeing_list, &super->s_freeing_list);
spin_unlock(&logfs_inode_lock);
return generic_drop_inode(inode);
}
static void logfs_set_ino_generation(struct super_block *sb,
struct inode *inode)
{
struct logfs_super *super = logfs_super(sb);
u64 ino;
mutex_lock(&super->s_journal_mutex);
ino = logfs_seek_hole(super->s_master_inode, super->s_last_ino + 1);
super->s_last_ino = ino;
super->s_inos_till_wrap--;
if (super->s_inos_till_wrap < 0) {
super->s_last_ino = LOGFS_RESERVED_INOS;
super->s_generation++;
super->s_inos_till_wrap = INOS_PER_WRAP;
}
inode->i_ino = ino;
inode->i_generation = super->s_generation;
mutex_unlock(&super->s_journal_mutex);
}
struct inode *logfs_new_inode(struct inode *dir, umode_t mode)
{
struct super_block *sb = dir->i_sb;
struct inode *inode;
inode = new_inode(sb);
if (!inode)
return ERR_PTR(-ENOMEM);
logfs_init_inode(sb, inode);
/* inherit parent flags */
logfs_inode(inode)->li_flags |=
logfs_inode(dir)->li_flags & LOGFS_FL_INHERITED;
inode->i_mode = mode;
logfs_set_ino_generation(sb, inode);
inode_init_owner(inode, dir, mode);
logfs_inode_setops(inode);
insert_inode_hash(inode);
return inode;
}
static void logfs_init_once(void *_li)
{
struct logfs_inode *li = _li;
int i;
li->li_flags = 0;
li->li_used_bytes = 0;
li->li_refcount = 1;
for (i = 0; i < LOGFS_EMBEDDED_FIELDS; i++)
li->li_data[i] = 0;
inode_init_once(&li->vfs_inode);
}
static int logfs_sync_fs(struct super_block *sb, int wait)
{
logfs_get_wblocks(sb, NULL, WF_LOCK);
logfs_write_anchor(sb);
logfs_put_wblocks(sb, NULL, WF_LOCK);
return 0;
}
static void logfs_put_super(struct super_block *sb)
{
struct logfs_super *super = logfs_super(sb);
/* kill the meta-inodes */
iput(super->s_segfile_inode);
iput(super->s_master_inode);
iput(super->s_mapping_inode);
}
const struct super_operations logfs_super_operations = {
.alloc_inode = logfs_alloc_inode,
.destroy_inode = logfs_destroy_inode,
.evict_inode = logfs_evict_inode,
.drop_inode = logfs_drop_inode,
.put_super = logfs_put_super,
.write_inode = logfs_write_inode,
.statfs = logfs_statfs,
.sync_fs = logfs_sync_fs,
};
int logfs_init_inode_cache(void)
{
logfs_inode_cache = kmem_cache_create("logfs_inode_cache",
sizeof(struct logfs_inode), 0, SLAB_RECLAIM_ACCOUNT,
logfs_init_once);
if (!logfs_inode_cache)
return -ENOMEM;
return 0;
}
void logfs_destroy_inode_cache(void)
{
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
kmem_cache_destroy(logfs_inode_cache);
}
| gpl-2.0 |
blastagator/LGG2_TWRP_Kernel | net/netfilter/nf_conntrack_helper.c | 4226 | 8792 | /* Helper handling for netfilter. */
/* (C) 1999-2001 Paul `Rusty' Russell
* (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
* (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/types.h>
#include <linux/netfilter.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/vmalloc.h>
#include <linux/stddef.h>
#include <linux/random.h>
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/rculist.h>
#include <linux/rtnetlink.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_l3proto.h>
#include <net/netfilter/nf_conntrack_l4proto.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <net/netfilter/nf_conntrack_core.h>
#include <net/netfilter/nf_conntrack_extend.h>
static DEFINE_MUTEX(nf_ct_helper_mutex);
static struct hlist_head *nf_ct_helper_hash __read_mostly;
static unsigned int nf_ct_helper_hsize __read_mostly;
static unsigned int nf_ct_helper_count __read_mostly;
/* Stupid hash, but collision free for the default registrations of the
* helpers currently in the kernel. */
static unsigned int helper_hash(const struct nf_conntrack_tuple *tuple)
{
return (((tuple->src.l3num << 8) | tuple->dst.protonum) ^
(__force __u16)tuple->src.u.all) % nf_ct_helper_hsize;
}
static struct nf_conntrack_helper *
__nf_ct_helper_find(const struct nf_conntrack_tuple *tuple)
{
struct nf_conntrack_helper *helper;
struct nf_conntrack_tuple_mask mask = { .src.u.all = htons(0xFFFF) };
struct hlist_node *n;
unsigned int h;
if (!nf_ct_helper_count)
return NULL;
h = helper_hash(tuple);
hlist_for_each_entry_rcu(helper, n, &nf_ct_helper_hash[h], hnode) {
if (nf_ct_tuple_src_mask_cmp(tuple, &helper->tuple, &mask))
return helper;
}
return NULL;
}
struct nf_conntrack_helper *
__nf_conntrack_helper_find(const char *name, u16 l3num, u8 protonum)
{
struct nf_conntrack_helper *h;
struct hlist_node *n;
unsigned int i;
for (i = 0; i < nf_ct_helper_hsize; i++) {
hlist_for_each_entry_rcu(h, n, &nf_ct_helper_hash[i], hnode) {
if (!strcmp(h->name, name) &&
h->tuple.src.l3num == l3num &&
h->tuple.dst.protonum == protonum)
return h;
}
}
return NULL;
}
EXPORT_SYMBOL_GPL(__nf_conntrack_helper_find);
struct nf_conntrack_helper *
nf_conntrack_helper_try_module_get(const char *name, u16 l3num, u8 protonum)
{
struct nf_conntrack_helper *h;
h = __nf_conntrack_helper_find(name, l3num, protonum);
#ifdef CONFIG_MODULES
if (h == NULL) {
if (request_module("nfct-helper-%s", name) == 0)
h = __nf_conntrack_helper_find(name, l3num, protonum);
}
#endif
if (h != NULL && !try_module_get(h->me))
h = NULL;
return h;
}
EXPORT_SYMBOL_GPL(nf_conntrack_helper_try_module_get);
struct nf_conn_help *nf_ct_helper_ext_add(struct nf_conn *ct, gfp_t gfp)
{
struct nf_conn_help *help;
help = nf_ct_ext_add(ct, NF_CT_EXT_HELPER, gfp);
if (help)
INIT_HLIST_HEAD(&help->expectations);
else
pr_debug("failed to add helper extension area");
return help;
}
EXPORT_SYMBOL_GPL(nf_ct_helper_ext_add);
int __nf_ct_try_assign_helper(struct nf_conn *ct, struct nf_conn *tmpl,
gfp_t flags)
{
struct nf_conntrack_helper *helper = NULL;
struct nf_conn_help *help;
int ret = 0;
if (tmpl != NULL) {
help = nfct_help(tmpl);
if (help != NULL)
helper = help->helper;
}
help = nfct_help(ct);
if (helper == NULL)
helper = __nf_ct_helper_find(&ct->tuplehash[IP_CT_DIR_REPLY].tuple);
if (helper == NULL) {
if (help)
RCU_INIT_POINTER(help->helper, NULL);
goto out;
}
if (help == NULL) {
help = nf_ct_helper_ext_add(ct, flags);
if (help == NULL) {
ret = -ENOMEM;
goto out;
}
} else {
memset(&help->help, 0, sizeof(help->help));
}
rcu_assign_pointer(help->helper, helper);
out:
return ret;
}
EXPORT_SYMBOL_GPL(__nf_ct_try_assign_helper);
static inline int unhelp(struct nf_conntrack_tuple_hash *i,
const struct nf_conntrack_helper *me)
{
struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(i);
struct nf_conn_help *help = nfct_help(ct);
if (help && rcu_dereference_protected(
help->helper,
lockdep_is_held(&nf_conntrack_lock)
) == me) {
nf_conntrack_event(IPCT_HELPER, ct);
RCU_INIT_POINTER(help->helper, NULL);
}
return 0;
}
void nf_ct_helper_destroy(struct nf_conn *ct)
{
struct nf_conn_help *help = nfct_help(ct);
struct nf_conntrack_helper *helper;
if (help) {
rcu_read_lock();
helper = rcu_dereference(help->helper);
if (helper && helper->destroy)
helper->destroy(ct);
rcu_read_unlock();
}
}
static LIST_HEAD(nf_ct_helper_expectfn_list);
void nf_ct_helper_expectfn_register(struct nf_ct_helper_expectfn *n)
{
spin_lock_bh(&nf_conntrack_lock);
list_add_rcu(&n->head, &nf_ct_helper_expectfn_list);
spin_unlock_bh(&nf_conntrack_lock);
}
EXPORT_SYMBOL_GPL(nf_ct_helper_expectfn_register);
void nf_ct_helper_expectfn_unregister(struct nf_ct_helper_expectfn *n)
{
spin_lock_bh(&nf_conntrack_lock);
list_del_rcu(&n->head);
spin_unlock_bh(&nf_conntrack_lock);
}
EXPORT_SYMBOL_GPL(nf_ct_helper_expectfn_unregister);
struct nf_ct_helper_expectfn *
nf_ct_helper_expectfn_find_by_name(const char *name)
{
struct nf_ct_helper_expectfn *cur;
bool found = false;
rcu_read_lock();
list_for_each_entry_rcu(cur, &nf_ct_helper_expectfn_list, head) {
if (!strcmp(cur->name, name)) {
found = true;
break;
}
}
rcu_read_unlock();
return found ? cur : NULL;
}
EXPORT_SYMBOL_GPL(nf_ct_helper_expectfn_find_by_name);
struct nf_ct_helper_expectfn *
nf_ct_helper_expectfn_find_by_symbol(const void *symbol)
{
struct nf_ct_helper_expectfn *cur;
bool found = false;
rcu_read_lock();
list_for_each_entry_rcu(cur, &nf_ct_helper_expectfn_list, head) {
if (cur->expectfn == symbol) {
found = true;
break;
}
}
rcu_read_unlock();
return found ? cur : NULL;
}
EXPORT_SYMBOL_GPL(nf_ct_helper_expectfn_find_by_symbol);
int nf_conntrack_helper_register(struct nf_conntrack_helper *me)
{
unsigned int h = helper_hash(&me->tuple);
BUG_ON(me->expect_policy == NULL);
BUG_ON(me->expect_class_max >= NF_CT_MAX_EXPECT_CLASSES);
BUG_ON(strlen(me->name) > NF_CT_HELPER_NAME_LEN - 1);
mutex_lock(&nf_ct_helper_mutex);
hlist_add_head_rcu(&me->hnode, &nf_ct_helper_hash[h]);
nf_ct_helper_count++;
mutex_unlock(&nf_ct_helper_mutex);
return 0;
}
EXPORT_SYMBOL_GPL(nf_conntrack_helper_register);
static void __nf_conntrack_helper_unregister(struct nf_conntrack_helper *me,
struct net *net)
{
struct nf_conntrack_tuple_hash *h;
struct nf_conntrack_expect *exp;
const struct hlist_node *n, *next;
const struct hlist_nulls_node *nn;
unsigned int i;
/* Get rid of expectations */
for (i = 0; i < nf_ct_expect_hsize; i++) {
hlist_for_each_entry_safe(exp, n, next,
&net->ct.expect_hash[i], hnode) {
struct nf_conn_help *help = nfct_help(exp->master);
if ((rcu_dereference_protected(
help->helper,
lockdep_is_held(&nf_conntrack_lock)
) == me || exp->helper == me) &&
del_timer(&exp->timeout)) {
nf_ct_unlink_expect(exp);
nf_ct_expect_put(exp);
}
}
}
/* Get rid of expecteds, set helpers to NULL. */
hlist_nulls_for_each_entry(h, nn, &net->ct.unconfirmed, hnnode)
unhelp(h, me);
for (i = 0; i < net->ct.htable_size; i++) {
hlist_nulls_for_each_entry(h, nn, &net->ct.hash[i], hnnode)
unhelp(h, me);
}
}
void nf_conntrack_helper_unregister(struct nf_conntrack_helper *me)
{
struct net *net;
mutex_lock(&nf_ct_helper_mutex);
hlist_del_rcu(&me->hnode);
nf_ct_helper_count--;
mutex_unlock(&nf_ct_helper_mutex);
/* Make sure every nothing is still using the helper unless its a
* connection in the hash.
*/
synchronize_rcu();
rtnl_lock();
spin_lock_bh(&nf_conntrack_lock);
for_each_net(net)
__nf_conntrack_helper_unregister(me, net);
spin_unlock_bh(&nf_conntrack_lock);
rtnl_unlock();
}
EXPORT_SYMBOL_GPL(nf_conntrack_helper_unregister);
static struct nf_ct_ext_type helper_extend __read_mostly = {
.len = sizeof(struct nf_conn_help),
.align = __alignof__(struct nf_conn_help),
.id = NF_CT_EXT_HELPER,
};
int nf_conntrack_helper_init(void)
{
int err;
nf_ct_helper_hsize = 1; /* gets rounded up to use one page */
nf_ct_helper_hash = nf_ct_alloc_hashtable(&nf_ct_helper_hsize, 0);
if (!nf_ct_helper_hash)
return -ENOMEM;
err = nf_ct_extend_register(&helper_extend);
if (err < 0)
goto err1;
return 0;
err1:
nf_ct_free_hashtable(nf_ct_helper_hash, nf_ct_helper_hsize);
return err;
}
void nf_conntrack_helper_fini(void)
{
nf_ct_extend_unregister(&helper_extend);
nf_ct_free_hashtable(nf_ct_helper_hash, nf_ct_helper_hsize);
}
| gpl-2.0 |
ashyx/Samsung_Galaxy_Tab_A_kernel | drivers/infiniband/hw/mthca/mthca_pd.c | 15490 | 2597 | /*
* Copyright (c) 2004 Topspin Communications. All rights reserved.
* Copyright (c) 2005 Cisco Systems. All rights reserved.
* Copyright (c) 2005 Mellanox Technologies. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/errno.h>
#include "mthca_dev.h"
int mthca_pd_alloc(struct mthca_dev *dev, int privileged, struct mthca_pd *pd)
{
int err = 0;
pd->privileged = privileged;
atomic_set(&pd->sqp_count, 0);
pd->pd_num = mthca_alloc(&dev->pd_table.alloc);
if (pd->pd_num == -1)
return -ENOMEM;
if (privileged) {
err = mthca_mr_alloc_notrans(dev, pd->pd_num,
MTHCA_MPT_FLAG_LOCAL_READ |
MTHCA_MPT_FLAG_LOCAL_WRITE,
&pd->ntmr);
if (err)
mthca_free(&dev->pd_table.alloc, pd->pd_num);
}
return err;
}
void mthca_pd_free(struct mthca_dev *dev, struct mthca_pd *pd)
{
if (pd->privileged)
mthca_free_mr(dev, &pd->ntmr);
mthca_free(&dev->pd_table.alloc, pd->pd_num);
}
int mthca_init_pd_table(struct mthca_dev *dev)
{
return mthca_alloc_init(&dev->pd_table.alloc,
dev->limits.num_pds,
(1 << 24) - 1,
dev->limits.reserved_pds);
}
void mthca_cleanup_pd_table(struct mthca_dev *dev)
{
/* XXX check if any PDs are still allocated? */
mthca_alloc_cleanup(&dev->pd_table.alloc);
}
| gpl-2.0 |
paul-xxx/kernel_sony_fuji-3.7 | net/batman-adv/originator.c | 131 | 17812 | /* Copyright (C) 2009-2012 B.A.T.M.A.N. contributors:
*
* Marek Lindner, Simon Wunderlich
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA
*/
#include "main.h"
#include "originator.h"
#include "hash.h"
#include "translation-table.h"
#include "routing.h"
#include "gateway_client.h"
#include "hard-interface.h"
#include "unicast.h"
#include "soft-interface.h"
#include "bridge_loop_avoidance.h"
static void batadv_purge_orig(struct work_struct *work);
static void batadv_start_purge_timer(struct batadv_priv *bat_priv)
{
INIT_DELAYED_WORK(&bat_priv->orig_work, batadv_purge_orig);
queue_delayed_work(batadv_event_workqueue,
&bat_priv->orig_work, msecs_to_jiffies(1000));
}
/* returns 1 if they are the same originator */
static int batadv_compare_orig(const struct hlist_node *node, const void *data2)
{
const void *data1 = container_of(node, struct batadv_orig_node,
hash_entry);
return (memcmp(data1, data2, ETH_ALEN) == 0 ? 1 : 0);
}
int batadv_originator_init(struct batadv_priv *bat_priv)
{
if (bat_priv->orig_hash)
return 0;
bat_priv->orig_hash = batadv_hash_new(1024);
if (!bat_priv->orig_hash)
goto err;
batadv_start_purge_timer(bat_priv);
return 0;
err:
return -ENOMEM;
}
void batadv_neigh_node_free_ref(struct batadv_neigh_node *neigh_node)
{
if (atomic_dec_and_test(&neigh_node->refcount))
kfree_rcu(neigh_node, rcu);
}
/* increases the refcounter of a found router */
struct batadv_neigh_node *
batadv_orig_node_get_router(struct batadv_orig_node *orig_node)
{
struct batadv_neigh_node *router;
rcu_read_lock();
router = rcu_dereference(orig_node->router);
if (router && !atomic_inc_not_zero(&router->refcount))
router = NULL;
rcu_read_unlock();
return router;
}
struct batadv_neigh_node *
batadv_neigh_node_new(struct batadv_hard_iface *hard_iface,
const uint8_t *neigh_addr, uint32_t seqno)
{
struct batadv_priv *bat_priv = netdev_priv(hard_iface->soft_iface);
struct batadv_neigh_node *neigh_node;
neigh_node = kzalloc(sizeof(*neigh_node), GFP_ATOMIC);
if (!neigh_node)
goto out;
INIT_HLIST_NODE(&neigh_node->list);
memcpy(neigh_node->addr, neigh_addr, ETH_ALEN);
spin_lock_init(&neigh_node->lq_update_lock);
/* extra reference for return */
atomic_set(&neigh_node->refcount, 2);
batadv_dbg(BATADV_DBG_BATMAN, bat_priv,
"Creating new neighbor %pM, initial seqno %d\n",
neigh_addr, seqno);
out:
return neigh_node;
}
static void batadv_orig_node_free_rcu(struct rcu_head *rcu)
{
struct hlist_node *node, *node_tmp;
struct batadv_neigh_node *neigh_node, *tmp_neigh_node;
struct batadv_orig_node *orig_node;
orig_node = container_of(rcu, struct batadv_orig_node, rcu);
spin_lock_bh(&orig_node->neigh_list_lock);
/* for all bonding members ... */
list_for_each_entry_safe(neigh_node, tmp_neigh_node,
&orig_node->bond_list, bonding_list) {
list_del_rcu(&neigh_node->bonding_list);
batadv_neigh_node_free_ref(neigh_node);
}
/* for all neighbors towards this originator ... */
hlist_for_each_entry_safe(neigh_node, node, node_tmp,
&orig_node->neigh_list, list) {
hlist_del_rcu(&neigh_node->list);
batadv_neigh_node_free_ref(neigh_node);
}
spin_unlock_bh(&orig_node->neigh_list_lock);
batadv_frag_list_free(&orig_node->frag_list);
batadv_tt_global_del_orig(orig_node->bat_priv, orig_node,
"originator timed out");
kfree(orig_node->tt_buff);
kfree(orig_node->bcast_own);
kfree(orig_node->bcast_own_sum);
kfree(orig_node);
}
void batadv_orig_node_free_ref(struct batadv_orig_node *orig_node)
{
if (atomic_dec_and_test(&orig_node->refcount))
call_rcu(&orig_node->rcu, batadv_orig_node_free_rcu);
}
void batadv_originator_free(struct batadv_priv *bat_priv)
{
struct batadv_hashtable *hash = bat_priv->orig_hash;
struct hlist_node *node, *node_tmp;
struct hlist_head *head;
spinlock_t *list_lock; /* spinlock to protect write access */
struct batadv_orig_node *orig_node;
uint32_t i;
if (!hash)
return;
cancel_delayed_work_sync(&bat_priv->orig_work);
bat_priv->orig_hash = NULL;
for (i = 0; i < hash->size; i++) {
head = &hash->table[i];
list_lock = &hash->list_locks[i];
spin_lock_bh(list_lock);
hlist_for_each_entry_safe(orig_node, node, node_tmp,
head, hash_entry) {
hlist_del_rcu(node);
batadv_orig_node_free_ref(orig_node);
}
spin_unlock_bh(list_lock);
}
batadv_hash_destroy(hash);
}
/* this function finds or creates an originator entry for the given
* address if it does not exits
*/
struct batadv_orig_node *batadv_get_orig_node(struct batadv_priv *bat_priv,
const uint8_t *addr)
{
struct batadv_orig_node *orig_node;
int size;
int hash_added;
unsigned long reset_time;
orig_node = batadv_orig_hash_find(bat_priv, addr);
if (orig_node)
return orig_node;
batadv_dbg(BATADV_DBG_BATMAN, bat_priv,
"Creating new originator: %pM\n", addr);
orig_node = kzalloc(sizeof(*orig_node), GFP_ATOMIC);
if (!orig_node)
return NULL;
INIT_HLIST_HEAD(&orig_node->neigh_list);
INIT_LIST_HEAD(&orig_node->bond_list);
spin_lock_init(&orig_node->ogm_cnt_lock);
spin_lock_init(&orig_node->bcast_seqno_lock);
spin_lock_init(&orig_node->neigh_list_lock);
spin_lock_init(&orig_node->tt_buff_lock);
/* extra reference for return */
atomic_set(&orig_node->refcount, 2);
orig_node->tt_initialised = false;
orig_node->tt_poss_change = false;
orig_node->bat_priv = bat_priv;
memcpy(orig_node->orig, addr, ETH_ALEN);
orig_node->router = NULL;
orig_node->tt_crc = 0;
atomic_set(&orig_node->last_ttvn, 0);
orig_node->tt_buff = NULL;
orig_node->tt_buff_len = 0;
atomic_set(&orig_node->tt_size, 0);
reset_time = jiffies - 1 - msecs_to_jiffies(BATADV_RESET_PROTECTION_MS);
orig_node->bcast_seqno_reset = reset_time;
orig_node->batman_seqno_reset = reset_time;
atomic_set(&orig_node->bond_candidates, 0);
size = bat_priv->num_ifaces * sizeof(unsigned long) * BATADV_NUM_WORDS;
orig_node->bcast_own = kzalloc(size, GFP_ATOMIC);
if (!orig_node->bcast_own)
goto free_orig_node;
size = bat_priv->num_ifaces * sizeof(uint8_t);
orig_node->bcast_own_sum = kzalloc(size, GFP_ATOMIC);
INIT_LIST_HEAD(&orig_node->frag_list);
orig_node->last_frag_packet = 0;
if (!orig_node->bcast_own_sum)
goto free_bcast_own;
hash_added = batadv_hash_add(bat_priv->orig_hash, batadv_compare_orig,
batadv_choose_orig, orig_node,
&orig_node->hash_entry);
if (hash_added != 0)
goto free_bcast_own_sum;
return orig_node;
free_bcast_own_sum:
kfree(orig_node->bcast_own_sum);
free_bcast_own:
kfree(orig_node->bcast_own);
free_orig_node:
kfree(orig_node);
return NULL;
}
static bool
batadv_purge_orig_neighbors(struct batadv_priv *bat_priv,
struct batadv_orig_node *orig_node,
struct batadv_neigh_node **best_neigh_node)
{
struct hlist_node *node, *node_tmp;
struct batadv_neigh_node *neigh_node;
bool neigh_purged = false;
unsigned long last_seen;
struct batadv_hard_iface *if_incoming;
*best_neigh_node = NULL;
spin_lock_bh(&orig_node->neigh_list_lock);
/* for all neighbors towards this originator ... */
hlist_for_each_entry_safe(neigh_node, node, node_tmp,
&orig_node->neigh_list, list) {
last_seen = neigh_node->last_seen;
if_incoming = neigh_node->if_incoming;
if ((batadv_has_timed_out(last_seen, BATADV_PURGE_TIMEOUT)) ||
(if_incoming->if_status == BATADV_IF_INACTIVE) ||
(if_incoming->if_status == BATADV_IF_NOT_IN_USE) ||
(if_incoming->if_status == BATADV_IF_TO_BE_REMOVED)) {
if ((if_incoming->if_status == BATADV_IF_INACTIVE) ||
(if_incoming->if_status == BATADV_IF_NOT_IN_USE) ||
(if_incoming->if_status == BATADV_IF_TO_BE_REMOVED))
batadv_dbg(BATADV_DBG_BATMAN, bat_priv,
"neighbor purge: originator %pM, neighbor: %pM, iface: %s\n",
orig_node->orig, neigh_node->addr,
if_incoming->net_dev->name);
else
batadv_dbg(BATADV_DBG_BATMAN, bat_priv,
"neighbor timeout: originator %pM, neighbor: %pM, last_seen: %u\n",
orig_node->orig, neigh_node->addr,
jiffies_to_msecs(last_seen));
neigh_purged = true;
hlist_del_rcu(&neigh_node->list);
batadv_bonding_candidate_del(orig_node, neigh_node);
batadv_neigh_node_free_ref(neigh_node);
} else {
if ((!*best_neigh_node) ||
(neigh_node->tq_avg > (*best_neigh_node)->tq_avg))
*best_neigh_node = neigh_node;
}
}
spin_unlock_bh(&orig_node->neigh_list_lock);
return neigh_purged;
}
static bool batadv_purge_orig_node(struct batadv_priv *bat_priv,
struct batadv_orig_node *orig_node)
{
struct batadv_neigh_node *best_neigh_node;
if (batadv_has_timed_out(orig_node->last_seen,
2 * BATADV_PURGE_TIMEOUT)) {
batadv_dbg(BATADV_DBG_BATMAN, bat_priv,
"Originator timeout: originator %pM, last_seen %u\n",
orig_node->orig,
jiffies_to_msecs(orig_node->last_seen));
return true;
} else {
if (batadv_purge_orig_neighbors(bat_priv, orig_node,
&best_neigh_node))
batadv_update_route(bat_priv, orig_node,
best_neigh_node);
}
return false;
}
static void _batadv_purge_orig(struct batadv_priv *bat_priv)
{
struct batadv_hashtable *hash = bat_priv->orig_hash;
struct hlist_node *node, *node_tmp;
struct hlist_head *head;
spinlock_t *list_lock; /* spinlock to protect write access */
struct batadv_orig_node *orig_node;
uint32_t i;
if (!hash)
return;
/* for all origins... */
for (i = 0; i < hash->size; i++) {
head = &hash->table[i];
list_lock = &hash->list_locks[i];
spin_lock_bh(list_lock);
hlist_for_each_entry_safe(orig_node, node, node_tmp,
head, hash_entry) {
if (batadv_purge_orig_node(bat_priv, orig_node)) {
if (orig_node->gw_flags)
batadv_gw_node_delete(bat_priv,
orig_node);
hlist_del_rcu(node);
batadv_orig_node_free_ref(orig_node);
continue;
}
if (batadv_has_timed_out(orig_node->last_frag_packet,
BATADV_FRAG_TIMEOUT))
batadv_frag_list_free(&orig_node->frag_list);
}
spin_unlock_bh(list_lock);
}
batadv_gw_node_purge(bat_priv);
batadv_gw_election(bat_priv);
}
static void batadv_purge_orig(struct work_struct *work)
{
struct delayed_work *delayed_work;
struct batadv_priv *bat_priv;
delayed_work = container_of(work, struct delayed_work, work);
bat_priv = container_of(delayed_work, struct batadv_priv, orig_work);
_batadv_purge_orig(bat_priv);
batadv_start_purge_timer(bat_priv);
}
void batadv_purge_orig_ref(struct batadv_priv *bat_priv)
{
_batadv_purge_orig(bat_priv);
}
int batadv_orig_seq_print_text(struct seq_file *seq, void *offset)
{
struct net_device *net_dev = (struct net_device *)seq->private;
struct batadv_priv *bat_priv = netdev_priv(net_dev);
struct batadv_hashtable *hash = bat_priv->orig_hash;
struct hlist_node *node, *node_tmp;
struct hlist_head *head;
struct batadv_hard_iface *primary_if;
struct batadv_orig_node *orig_node;
struct batadv_neigh_node *neigh_node, *neigh_node_tmp;
int batman_count = 0;
int last_seen_secs;
int last_seen_msecs;
unsigned long last_seen_jiffies;
uint32_t i;
int ret = 0;
primary_if = batadv_primary_if_get_selected(bat_priv);
if (!primary_if) {
ret = seq_printf(seq,
"BATMAN mesh %s disabled - please specify interfaces to enable it\n",
net_dev->name);
goto out;
}
if (primary_if->if_status != BATADV_IF_ACTIVE) {
ret = seq_printf(seq,
"BATMAN mesh %s disabled - primary interface not active\n",
net_dev->name);
goto out;
}
seq_printf(seq, "[B.A.T.M.A.N. adv %s, MainIF/MAC: %s/%pM (%s)]\n",
BATADV_SOURCE_VERSION, primary_if->net_dev->name,
primary_if->net_dev->dev_addr, net_dev->name);
seq_printf(seq, " %-15s %s (%s/%i) %17s [%10s]: %20s ...\n",
"Originator", "last-seen", "#", BATADV_TQ_MAX_VALUE,
"Nexthop", "outgoingIF", "Potential nexthops");
for (i = 0; i < hash->size; i++) {
head = &hash->table[i];
rcu_read_lock();
hlist_for_each_entry_rcu(orig_node, node, head, hash_entry) {
neigh_node = batadv_orig_node_get_router(orig_node);
if (!neigh_node)
continue;
if (neigh_node->tq_avg == 0)
goto next;
last_seen_jiffies = jiffies - orig_node->last_seen;
last_seen_msecs = jiffies_to_msecs(last_seen_jiffies);
last_seen_secs = last_seen_msecs / 1000;
last_seen_msecs = last_seen_msecs % 1000;
seq_printf(seq, "%pM %4i.%03is (%3i) %pM [%10s]:",
orig_node->orig, last_seen_secs,
last_seen_msecs, neigh_node->tq_avg,
neigh_node->addr,
neigh_node->if_incoming->net_dev->name);
hlist_for_each_entry_rcu(neigh_node_tmp, node_tmp,
&orig_node->neigh_list, list) {
seq_printf(seq, " %pM (%3i)",
neigh_node_tmp->addr,
neigh_node_tmp->tq_avg);
}
seq_printf(seq, "\n");
batman_count++;
next:
batadv_neigh_node_free_ref(neigh_node);
}
rcu_read_unlock();
}
if (batman_count == 0)
seq_printf(seq, "No batman nodes in range ...\n");
out:
if (primary_if)
batadv_hardif_free_ref(primary_if);
return ret;
}
static int batadv_orig_node_add_if(struct batadv_orig_node *orig_node,
int max_if_num)
{
void *data_ptr;
size_t data_size, old_size;
data_size = max_if_num * sizeof(unsigned long) * BATADV_NUM_WORDS;
old_size = (max_if_num - 1) * sizeof(unsigned long) * BATADV_NUM_WORDS;
data_ptr = kmalloc(data_size, GFP_ATOMIC);
if (!data_ptr)
return -ENOMEM;
memcpy(data_ptr, orig_node->bcast_own, old_size);
kfree(orig_node->bcast_own);
orig_node->bcast_own = data_ptr;
data_ptr = kmalloc(max_if_num * sizeof(uint8_t), GFP_ATOMIC);
if (!data_ptr)
return -ENOMEM;
memcpy(data_ptr, orig_node->bcast_own_sum,
(max_if_num - 1) * sizeof(uint8_t));
kfree(orig_node->bcast_own_sum);
orig_node->bcast_own_sum = data_ptr;
return 0;
}
int batadv_orig_hash_add_if(struct batadv_hard_iface *hard_iface,
int max_if_num)
{
struct batadv_priv *bat_priv = netdev_priv(hard_iface->soft_iface);
struct batadv_hashtable *hash = bat_priv->orig_hash;
struct hlist_node *node;
struct hlist_head *head;
struct batadv_orig_node *orig_node;
uint32_t i;
int ret;
/* resize all orig nodes because orig_node->bcast_own(_sum) depend on
* if_num
*/
for (i = 0; i < hash->size; i++) {
head = &hash->table[i];
rcu_read_lock();
hlist_for_each_entry_rcu(orig_node, node, head, hash_entry) {
spin_lock_bh(&orig_node->ogm_cnt_lock);
ret = batadv_orig_node_add_if(orig_node, max_if_num);
spin_unlock_bh(&orig_node->ogm_cnt_lock);
if (ret == -ENOMEM)
goto err;
}
rcu_read_unlock();
}
return 0;
err:
rcu_read_unlock();
return -ENOMEM;
}
static int batadv_orig_node_del_if(struct batadv_orig_node *orig_node,
int max_if_num, int del_if_num)
{
void *data_ptr = NULL;
int chunk_size;
/* last interface was removed */
if (max_if_num == 0)
goto free_bcast_own;
chunk_size = sizeof(unsigned long) * BATADV_NUM_WORDS;
data_ptr = kmalloc(max_if_num * chunk_size, GFP_ATOMIC);
if (!data_ptr)
return -ENOMEM;
/* copy first part */
memcpy(data_ptr, orig_node->bcast_own, del_if_num * chunk_size);
/* copy second part */
memcpy((char *)data_ptr + del_if_num * chunk_size,
orig_node->bcast_own + ((del_if_num + 1) * chunk_size),
(max_if_num - del_if_num) * chunk_size);
free_bcast_own:
kfree(orig_node->bcast_own);
orig_node->bcast_own = data_ptr;
if (max_if_num == 0)
goto free_own_sum;
data_ptr = kmalloc(max_if_num * sizeof(uint8_t), GFP_ATOMIC);
if (!data_ptr)
return -ENOMEM;
memcpy(data_ptr, orig_node->bcast_own_sum,
del_if_num * sizeof(uint8_t));
memcpy((char *)data_ptr + del_if_num * sizeof(uint8_t),
orig_node->bcast_own_sum + ((del_if_num + 1) * sizeof(uint8_t)),
(max_if_num - del_if_num) * sizeof(uint8_t));
free_own_sum:
kfree(orig_node->bcast_own_sum);
orig_node->bcast_own_sum = data_ptr;
return 0;
}
int batadv_orig_hash_del_if(struct batadv_hard_iface *hard_iface,
int max_if_num)
{
struct batadv_priv *bat_priv = netdev_priv(hard_iface->soft_iface);
struct batadv_hashtable *hash = bat_priv->orig_hash;
struct hlist_node *node;
struct hlist_head *head;
struct batadv_hard_iface *hard_iface_tmp;
struct batadv_orig_node *orig_node;
uint32_t i;
int ret;
/* resize all orig nodes because orig_node->bcast_own(_sum) depend on
* if_num
*/
for (i = 0; i < hash->size; i++) {
head = &hash->table[i];
rcu_read_lock();
hlist_for_each_entry_rcu(orig_node, node, head, hash_entry) {
spin_lock_bh(&orig_node->ogm_cnt_lock);
ret = batadv_orig_node_del_if(orig_node, max_if_num,
hard_iface->if_num);
spin_unlock_bh(&orig_node->ogm_cnt_lock);
if (ret == -ENOMEM)
goto err;
}
rcu_read_unlock();
}
/* renumber remaining batman interfaces _inside_ of orig_hash_lock */
rcu_read_lock();
list_for_each_entry_rcu(hard_iface_tmp, &batadv_hardif_list, list) {
if (hard_iface_tmp->if_status == BATADV_IF_NOT_IN_USE)
continue;
if (hard_iface == hard_iface_tmp)
continue;
if (hard_iface->soft_iface != hard_iface_tmp->soft_iface)
continue;
if (hard_iface_tmp->if_num > hard_iface->if_num)
hard_iface_tmp->if_num--;
}
rcu_read_unlock();
hard_iface->if_num = -1;
return 0;
err:
rcu_read_unlock();
return -ENOMEM;
}
| gpl-2.0 |
junkyde/vikinger-stock | drivers/staging/prima/CORE/MAC/src/pe/lim/limStaHashApi.c | 387 | 2136 | /*
* Copyright (c) 2012, 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.
*/
/*
*
* Airgo Networks, Inc proprietary. All rights reserved.
* limStaHashApi.c: Provides access functions to get/set values of station hash entry fields.
* Author: Sunit Bhatia
* Date: 09/19/2006
* History:-
* Date Modified by Modification Information
*
* --------------------------------------------------------------------------
*
*/
#include "limStaHashApi.h"
/**
* limGetStaHashBssidx()
*
*FUNCTION:
* This function is called to Get the Bss Index of the currently associated Station.
*
*LOGIC:
*
*ASSUMPTIONS:
* NA
*
*NOTE:
* NA
*
* @param pMac pointer to Global Mac structure.
* @param assocId AssocID of the Station.
* @param bssidx pointer to the bss index, which will be returned by the function.
*
* @return success if GET operation is ok, else Failure.
*/
tSirRetStatus limGetStaHashBssidx(tpAniSirGlobal pMac, tANI_U16 assocId, tANI_U8 *bssidx, tpPESession psessionEntry)
{
tpDphHashNode pSta = dphGetHashEntry(pMac, assocId, &psessionEntry->dph.dphHashTable);
if (pSta == NULL)
{
PELOGE(limLog(pMac, LOGE, FL("invalid STA %d\n"), assocId);)
return eSIR_LIM_INVALID_STA;
}
*bssidx = (tANI_U8)pSta->bssId;
return eSIR_SUCCESS;
}
| gpl-2.0 |
ganjafuzz/PureKernel-v2-CAF | drivers/staging/prima/CORE/BAP/src/btampHCI.c | 387 | 374540 | /*
* Copyright (c) 2012, 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.
*/
/**
* \file btampHCI.c
*
* \brief Structures, functions & definitions for
* working with 802.11 Frames
*
*
* Copyright (C) 2009 Airgo Networks, Incorporated.
*
*
* This file was automatically generated by 'framesc'
* Fri Feb 27 17:29:19 2009 from the following file(s):
*
* btampHCI.frms
*
* PLEASE DON'T EDIT THIS FILE BY HAND!
*
*
*/
#ifndef ANI_OS_TYPE_OSX
#include <memory.h> /* For memcpy */
//#include <stdio.h> /* For _vsnprintf */
#include <stddef.h> /* For offsetof */
#endif
#define _vsnprintf vsnprintf
#include "vos_api.h"
#include "btampHCI.h"
#if defined ( _MSC_VER )
# pragma warning (disable: 4244)
# pragma warning (disable: 4505)
# pragma warning (disable: 4702)
# pragma warning (disable: 4996) /* ... was declared deprecated */
#endif /* Microsoft C/C++ */
/*Length of the value field expected in a TLV of type Connected Channel in an
AMP Assoc*/
#define WLAN_BAP_PAL_AMP_ASSOC_CONN_CH_TLV_MIN_LEN 3
/*Length of the value field expected in a TLV of type Prefered Channel in an
AMP Assoc*/
#define WLAN_BAP_PAL_AMP_ASSOC_PREF_CH_TLV_MIN_LEN 3
/*Length of the value field expected in a TLV of type MAC Address*/
#define WLAN_BAP_PAL_MAC_ADDR_TLV_LEN 6
/*Length of the value field expected in a TLV of type Capabilities*/
#define WLAN_BAP_PAL_CAPABILITIES_TLV_LEN 4
/*Length of the value field expected in a TLV of type Version*/
#define WLAN_BAP_PAL_VERSION_TLV_LEN 5
/*Length of the value field expected in a TLV of type Accept Phy Link*/
#define WLAN_BAP_PAL_ACC_PHY_LINK_TLV_MIN_LEN 3
/*Length of the value field expected in a TLV of type Accept Log Link*/
#define WLAN_BAP_PAL_ACC_LOG_LINK_TLV_LEN 37
/*Length of the value field expected in a TLV of type Create Log Link*/
#define WLAN_BAP_PAL_CREATE_LOG_LINK_TLV_LEN 37
/*Length of the value field expected in a TLV of type Create Phy Link*/
#define WLAN_BAP_PAL_CREATE_PHY_LINK_TLV_MIN_LEN 3
/*Length of the value field expected in a TLV of type Disconnect Log Link*/
#define WLAN_BAP_PAL_DISC_LOG_LINK_TLV_LEN 2
/*Length of the value field expected in a TLV of type Disconnect Phy Link*/
#define WLAN_BAP_PAL_DISC_PHY_LINK_TLV_LEN 2
/*Length of the value field expected in a TLV of type Flow Spec Modify*/
#define WLAN_BAP_PAL_FLOW_SPEC_MOD_TLV_LEN 34
/*Length of the value field expected in a TLV of type Flush*/
#define WLAN_BAP_PAL_FLUSH_TLV_LEN 2
/*Length of the value field expected in a TLV of type enhanced Flush*/
#define WLAN_BAP_PAL_ENHANCED_FLUSH_TLV_LEN 3
/*Length of the value field expected in a TLV of type Cancel Log Link*/
#define WLAN_BAP_PAL_CANCEL_LOG_LINK_TLV_LEN 2
/*Length of the value field expected in a TLV of type Read Best Effort Flush
Timeout*/
#define WLAN_BAP_PAL_READ_BE_FLUSH_TIMEOUT_TLV_LEN 2
/*Length of the value field expected in a TLV of type Read Failed Contact
Counter*/
#define WLAN_BAP_PAL_READ_FAILED_CONTACT_CNT_TLV_LEN 2
/*Length of the value field expected in a TLV of type Link Quality*/
#define WLAN_BAP_PAL_READ_LINK_QUALITY_TLV_LEN 2
/*Length of the value field expected in a TLV of type Read Link Supervision
Timeout*/
#define WLAN_BAP_PAL_READ_LINK_SVISISON_TIMEOUT_TLV_LEN 2
/*Length of the value field expected in a TLV of type Read Local AMP Assoc*/
#define WLAN_BAP_PAL_READ_LOCAL_AMP_ASSOC_TLV_LEN 5
/*Length of the value field expected in a TLV of type Read RSSI*/
#define WLAN_BAP_PAL_READ_RSSI_TLV_LEN 2
/*Length of the value field expected in a TLV of type Reset Failed Contact
Counter*/
#define WLAN_BAP_PAL_RESET_FAILED_CONTACT_CNT_TLV_LEN 2
/*Length of the value field expected in a TLV of type Set Event Mask*/
#define WLAN_BAP_PAL_SET_EVENT_MASK_TLV_LEN 8
/*Length of the value field expected in a TLV of type Set Event Mask2*/
#define WLAN_BAP_PAL_SET_EVENT_MASK2_TLV_LEN 8
/*Length of the value field expected in a TLV of type Set SHort Range Mode*/
#define WLAN_BAP_PAL_SET_SHORT_RANGE_MODE_TLV_LEN 2
/*Length of the value field expected in a TLV of type Write Best Effort Flush
Timeout*/
#define WLAN_BAP_PAL_WRITE_BE_FLUSH_TIMEOUT_TLV_LEN 6
/*Length of the value field expected in a TLV of type Write Connection Accept
Timeout*/
#define WLAN_BAP_PAL_WRITE_CON_ACC_TIMEOUT_TLV_LEN 2
/*Length of the value field expected in a TLV of type Write Flow Control Mode*/
#define WLAN_BAP_PAL_WRITE_FLOW_CTRL_MODE_TLV_LEN 1
/*Length of the value field expected in a TLV of type Write Link Supervision
Timeout*/
#define WLAN_BAP_PAL_WRITE_LINK_SVISION_TIMEOUT_TLV_LEN 4
/*Length of the value field expected in a TLV of type Write Location Data*/
#define WLAN_BAP_PAL_WRITE_LOCATION_DATA_CMD_TLV_LEN 5
/*Length of the value field expected in a TLV of type Write LL Acc Timeout*/
#define WLAN_BAP_PAL_WRITE_LOG_LINK_ACC_TIMEOUT_TLV_LEN 2
/*Length of the value field expected in a TLV of type Write Loopback Mode*/
#define WLAN_BAP_PAL_WRITE_LOOOPBACK_MODE_TLV_LEN 1
/*Length of the value field expected in a TLV of type Write Remote AMP Assoc*/
#define WLAN_BAP_PAL_WRITE_REMOTE_AMP_ASSOC_MIN_TLV_LEN 5
/* As per AMP specification */
/* Regulatory Extension Identifier for channel list */
#define WLAN_BAP_PAL_REG_EXTN_ID_VAL 201
/* Regulatory Class for channel list */
#define WLAN_BAP_PAL_REG_CLASS_VAL 254
/* Coverage ClASS for channel list */
#define WLAN_BAP_PAL_COVERAGE_CLASS_VAL 0
/* LOGGING and VALIDITY_CHECKING control */
//#define WLAN_BAPHCI_ENABLE_VALIDITY_CHECKING
//#define WLAN_BAPHCI_ENABLE_LOGGING
typedef unsigned char tFRAMES_BOOL;
typedef void (*pfnGeneric_t)(void);
typedef struct sFFDefn {
v_U8_t size;
size_t offset;
v_U16_t sig;
pfnGeneric_t pfn;
const char *name;
} tFFDefn;
typedef struct sIEDefn {
v_U8_t eid;
v_U16_t minSize;
v_U16_t maxSize;
size_t offset;
size_t presenceOffset;
size_t countOffset;
v_U16_t arraybound;
unsigned char oui[5];
unsigned char noui;
v_U16_t sig;
pfnGeneric_t pfn;
const char *name;
tFRAMES_BOOL fMandatory;
} tIEDefn;
#if !defined(countof)
#define countof(x) ( sizeof( (x) ) / sizeof( (x)[0] ) )
#endif
#if ! defined(BTAMP_MEMCPY)
# define BTAMP_MEMCPY(ctx, dst, src, len) \
memcpy( (dst), (src), (len) ) \
#endif
#if ! defined(BTAMP_MEMCMP)
# define BTAMP_MEMCMP(ctx, lhs, rhs, len) \
memcmp( (lhs), (rhs), (len) ) \
#endif
#ifndef BTAMP_HAVE_LOG_SEVERITIES
# define FRLOG_OFF ( 0 )
# define FRLOGP ( 1 )
# define FRLOGE ( 2 )
# define FRLOGW ( 3 )
# define FRLOG1 ( 4 )
# define FRLOG2 ( 5 )
# define FRLOG3 ( 6 )
# define FRLOG4 ( 7 )
#endif
#define FRFL(x) x
#ifdef BTAMP_ENABLE_LOGGING
#ifndef BTAMP_HAVE_LOG_MACROS
#include <stdio.h>
#include <stdarg.h>
#ifndef BTAMP_LOG_GATE
# define BTAMP_LOG_GATE FRLOGW
#endif // BTAMP_LOG_GATE
#ifdef WIN32
#if defined ( _CONSOLE ) || defined ( _WINDOWS ) || defined ( _DLL ) || defined ( _LIB )
#include <windows.h>
#define DBGPRINT OutputDebugStringA
#else /* Not User mode */
#define DBGPRINT DbgPrint
#endif /* User mode */
static void framesLog(void * pCtx, int nSev,
const char *lpszFormat, ...)
{
va_list val;
char buffer[1024];
(void)pCtx;
if ( nSev <= BTAMP_LOG_GATE )
{
va_start(val, lpszFormat);
_vsnprintf(buffer, 1024, lpszFormat, val);
va_end(val);
DBGPRINT(buffer);
}
}
static void framesDump(void * pCtx, int nSev, v_U8_t *pBuf, int nBuf)
{
char buffer[35];
int i, offset;
pCtx;
offset = 0;
if ( nSev > BTAMP_LOG_GATE ) return;
for (i = 0; i < nBuf/8; ++i)
{
_snprintf(buffer, 35, "%08x: %02x %02x %02x %02x %02x %02x %02x %02x\n", offset, *pBuf, *(pBuf + 1), *(pBuf + 2), *(pBuf + 3), *(pBuf + 4), *(pBuf + 5), *(pBuf + 6), *(pBuf + 7));
pBuf += 8; offset += 8;
DBGPRINT(buffer);
}
_snprintf(buffer, 35, "%08x: ", offset);
DBGPRINT(buffer);
for (i = 0; i < nBuf % 8; ++i)
{
_snprintf(buffer, 35, "%02x ", *pBuf);
++pBuf;
DBGPRINT(buffer);
}
DBGPRINT("\n");
}
#elif defined OS_X /* Not WIN32 */
static void framesLog(void * pCtx, int nSev,
const char *lpszFormat, ...)
{// To fill in when needed using IOLog
}
static void framesDump(void * pCtx, int nSev, v_U8_t *pBuf, int nBuf)
{
}
#elif defined LINUX
static void framesLog(void * pCtx, int nSev,
const char *lpszFormat, ...)
{
va_list marker;
(void)pCtx;
if ( nSev <= BTAMP_LOG_GATE )
{
va_start( marker, lpszFormat );
vprintf(lpszFormat, marker);
va_end( marker );
}
}
static void framesDump(void * pCtx, int nSev, v_U8_t *pBuf, int nBuf)
{
char buffer[35];
int i, offset;
(void)pCtx;
offset = 0;
if ( nSev > BTAMP_LOG_GATE ) return;
for (i = 0; i < nBuf/8; ++i)
{
printf("%08x: %02x %02x %02x %02x %02x %02x %02x %02x\n", offset, *pBuf, *(pBuf + 1), *(pBuf + 2), *(pBuf + 3), *(pBuf + 4), *(pBuf + 5), *(pBuf + 6), *(pBuf + 7));
pBuf += 8; offset += 8;
}
printf("%08x: ", offset);
for (i = 0; i < nBuf % 8; ++i)
{
printf("%02x ", *pBuf);
++pBuf;
}
printf("\n");
}
#endif /* WIN32 */
#define FRAMES_LOG0(ctx, sev, fmt) \
framesLog((ctx), (sev), (fmt));
#define FRAMES_LOG1(ctx, sev, fmt, p1) \
framesLog((ctx), (sev), (fmt), (p1));
#define FRAMES_LOG2(ctx, sev, fmt, p1, p2) \
framesLog((ctx), (sev), (fmt), (p1), (p2));
#define FRAMES_LOG3(ctx, sev, fmt, p1, p2, p3) \
framesLog((ctx), (sev), (fmt), (p1), (p2), (p3));
#define FRAMES_DUMP(ctx, sev, p, n) \
framesDump((ctx), (sev), (p), (n));
#ifndef FRAMES_SEV_FOR_FRAME
# define FRAMES_SEV_FOR_FRAME(ctx, sig) FRLOG3
#endif
#endif /* End BTAMP_HAVE_LOG_MACROS */
#else // ! BTAMP_ENABLE_LOGGING
# define FRAMES_LOG0(ctx, sev, fmt)
# define FRAMES_LOG1(ctx, sev, fmt, p1)
# define FRAMES_LOG2(ctx, sev, fmt, p1, p2)
# define FRAMES_LOG3(ctx, sev, fmt, p1, p2, p3)
# define FRAMES_DUMP(ctx, sev, p, n)
# ifndef FRAMES_SEV_FOR_FRAME
# define FRAMES_SEV_FOR_FRAME(ctx, sig) FRLOG3
# endif
#endif // BTAMP_ENABLE_LOGGING
#if defined( BTAMP_ENABLE_DBG_BREAK ) && defined ( WIN32 )
# define FRAMES_DBG_BREAK() { _asm int 3 }
#else
# define FRAMES_DBG_BREAK()
#endif
#if ! defined(BTAMP_PARAMETER_CHECK)
# if defined (BTAMP_HAVE_WIN32_API)
# define BTAMP_PARAMETER_CHECK(pBuf, nBuf, pFrm, nFrm) \
if (!pBuf || IsBadReadPtr(pBuf, nBuf)) return BTAMP_BAD_INPUT_BUFFER; \
if (!pFrm || IsBadWritePtr(pFrm, nFrm)) return BTAMP_BAD_OUTPUT_BUFFER \
# define BTAMP_PARAMETER_CHECK2(pSrc, pBuf, nBuf, pnConsumed) \
if (!pSrc || IsBadReadPtr(pSrc, 4)) return BTAMP_BAD_INPUT_BUFFER; \
if (!pBuf || IsBadWritePtr(pBuf, nBuf)) return BTAMP_BAD_OUTPUT_BUFFER; \
if (!nBuf) return BTAMP_BAD_OUTPUT_BUFFER; \
if (IsBadWritePtr(pnConsumed, 4)) return BTAMP_BAD_OUTPUT_BUFFER \
# else
# define BTAMP_PARAMETER_CHECK(pBuf, nBuf, pFrm, nFrm) \
if (!pBuf) return BTAMP_BAD_INPUT_BUFFER; \
if (!pFrm) return BTAMP_BAD_OUTPUT_BUFFER \
# define BTAMP_PARAMETER_CHECK2(pSrc, pBuf, nBuf, pnConsumed) \
if (!pSrc) return BTAMP_BAD_INPUT_BUFFER; \
if (!pBuf) return BTAMP_BAD_OUTPUT_BUFFER; \
if (!nBuf) return BTAMP_BAD_OUTPUT_BUFFER; \
if (!pnConsumed) return BTAMP_BAD_OUTPUT_BUFFER \
# endif
#endif
static void framesntohs(void * pCtx,
v_U16_t *pOut,
v_U8_t *pIn,
tFRAMES_BOOL fMsb)
{
(void)pCtx;
# if defined ( BTAMP_LITTLE_ENDIAN_HOST )
if ( !fMsb )
{
BTAMP_MEMCPY(pCtx, ( v_U16_t* )pOut, pIn, 2);
}
else
{
*pOut = ( v_U16_t )( *pIn << 8 ) | *( pIn + 1 );
}
# else
if ( !fMsb )
{
*pOut = ( v_U16_t )( *pIn | ( *( pIn + 1 ) << 8 ) );
}
else
{
BTAMP_MEMCPY(pCtx, ( v_U16_t* )pOut, pIn, 2);
}
# endif
}
static void framesntohl(void * pCtx,
v_U32_t *pOut,
v_U8_t *pIn,
tFRAMES_BOOL fMsb)
{
(void)pCtx;
# if defined ( BTAMP_LITTLE_ENDIAN_HOST )
if ( !fMsb )
{
*pOut = * ( v_U32_t* )pIn;
}
else
{
*pOut = ( v_U32_t )( *pIn << 24 ) |
( *( pIn + 1 ) << 16 ) |
( *( pIn + 2 ) << 8 ) |
( *( pIn + 3 ) );
}
# else
if ( !fMsb )
{
*pOut = ( v_U32_t )( *( pIn + 3 ) << 24 ) |
( *( pIn + 2 ) << 16 ) |
( *( pIn + 1 ) << 8 ) |
( *( pIn ) );
}
else
{
*pOut = * ( v_U32_t* )pIn;
}
# endif
}
static void frameshtons(void * pCtx
, v_U8_t *pOut,
v_U16_t pIn,
tFRAMES_BOOL fMsb)
{
(void)pCtx;
# if defined ( BTAMP_LITTLE_ENDIAN_HOST )
if ( !fMsb )
{
BTAMP_MEMCPY(pCtx, pOut, &pIn, 2);
}
else
{
*pOut = ( pIn & 0xff00 ) >> 8;
*( pOut + 1 ) = pIn & 0xff;
}
# else
if ( !fMsb )
{
*pOut = pIn & 0xff;
*( pOut + 1 ) = ( pIn & 0xff00 ) >> 8;
}
else
{
BTAMP_MEMCPY(pCtx, pOut, &pIn, 2);
}
# endif
}
static void frameshtonl(void * pCtx,
v_U8_t *pOut,
v_U32_t pIn,
tFRAMES_BOOL fMsb)
{
(void)pCtx;
# if defined ( BTAMP_LITTLE_ENDIAN_HOST )
if ( !fMsb )
{
BTAMP_MEMCPY(pCtx, pOut, &pIn, 4);
}
else
{
*pOut = ( pIn & 0xff000000 ) >> 24;
*( pOut + 1 ) = ( pIn & 0x00ff0000 ) >> 16;
*( pOut + 2 ) = ( pIn & 0x0000ff00 ) >> 8;
*( pOut + 3 ) = ( pIn & 0x000000ff );
}
# else
if ( !fMsb )
{
*( pOut ) = ( pIn & 0x000000ff );
*( pOut + 1 ) = ( pIn & 0x0000ff00 ) >> 8;
*( pOut + 2 ) = ( pIn & 0x00ff0000 ) >> 16;
*( pOut + 3 ) = ( pIn & 0xff000000 ) >> 24;
}
else
{
BTAMP_MEMCPY(pCtx, pOut, &pIn, 4);
}
# endif
}
typedef struct sTLVDefn {
v_U32_t id;
v_U32_t pec;
v_U32_t minSize;
v_U32_t maxSize;
size_t offset;
size_t presenceOffset;
v_U16_t sig;
pfnGeneric_t pfn;
const char * name;
v_U8_t fMandatory;
} tTLVDefn;
static tTLVDefn* FindTLVDefn( void * pCtx,
v_U8_t *pBuf,
v_U32_t nBuf,
tTLVDefn TLVs[ ] )
{
tTLVDefn *pTlv;
v_U32_t sType, sLen;
v_U32_t pec;
v_U16_t id;
sType = 1;
sLen = 2;
(void)pCtx;
if (sType == 2)
framesntohs( pCtx, &id, pBuf, 2 );
else {
id = *pBuf;
}
pTlv = &( TLVs[ 0 ] );
while ( 0xffff != pTlv->id )
{
if ( id == pTlv->id )
{
if ( 0 == pTlv->pec ) return pTlv;
if( nBuf > 5 )
{
pec = ( ( * ( pBuf + 4 ) ) << 16 ) |
( ( * ( pBuf + 5 ) ) << 8 ) |
* ( pBuf + 6 );
if ( pec == pTlv->pec )
{
return pTlv;
}
}
}
++pTlv;
}
return NULL;
}
static v_U32_t UnpackTlvCore( void * pCtx,
v_U8_t *pBuf,
v_U32_t nBuf,
tTLVDefn TLVs[ ],
v_U8_t *pFrm,
size_t nFrm );
static v_U32_t PackTlvCore(void * pCtx,
v_U8_t *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed,
tTLVDefn TLVs[],
v_U32_t *pidx);
static v_U32_t GetPackedSizeTlvCore(void * pCtx,
v_U8_t *pFrm,
v_U32_t *pnNeeded,
tTLVDefn TLVs[]);
v_U32_t btampUnpackTlvAMP_Assoc_Connected_Channel(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVAMP_Assoc_Connected_Channel *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_AMP_ASSOC_CONN_CH_TLV_MIN_LEN > tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR, "Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
BTAMP_MEMCPY(pCtx, pDst->country, pBuf, 3);
pBuf += 3;
tlvlen -= (v_U8_t)3;
if ( ! tlvlen )
{
pDst->num_triplets = 0U;
return 0U;
}
else
{
/* Maximum of 5 triplets allowed, based on size of triplets definition */
if (tlvlen / 3 > 5)
{
tlvlen = 15;
}
pDst->num_triplets = (v_U8_t)( tlvlen / 3 );
BTAMP_MEMCPY(pCtx, pDst->triplets, pBuf, ( tlvlen ) );
pBuf += ( tlvlen );
tlvlen -= ( tlvlen );
}
(void)pCtx;
return status;
} /* End btampUnpackTlvAMP_Assoc_Connected_Channel. */
typedef v_U32_t (*pfnUnpackTlvAMP_Assoc_Connected_Channel_t)(void *, v_U8_t*, v_U16_t, tBtampTLVAMP_Assoc_Connected_Channel*);
#define SigUnpackTlvAMP_Assoc_Connected_Channel ( 0x0001 )
v_U32_t btampUnpackTlvAMP_Assoc_MAC_Addr(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVAMP_Assoc_MAC_Addr *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_MAC_ADDR_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
BTAMP_MEMCPY(pCtx, pDst->mac_addr, pBuf, 6);
pBuf += 6;
tlvlen -= (v_U8_t)6;
(void)pCtx;
return status;
} /* End btampUnpackTlvAMP_Assoc_MAC_Addr. */
typedef v_U32_t (*pfnUnpackTlvAMP_Assoc_MAC_Addr_t)(void *, v_U8_t*, v_U16_t, tBtampTLVAMP_Assoc_MAC_Addr*);
#define SigUnpackTlvAMP_Assoc_MAC_Addr ( 0x0002 )
v_U32_t btampUnpackTlvAMP_Assoc_PAL_Capabilities(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVAMP_Assoc_PAL_Capabilities *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_CAPABILITIES_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
framesntohl(pCtx, &pDst->pal_capabilities, pBuf, 0);
pBuf += 4;
tlvlen -= (v_U8_t)4;
(void)pCtx;
return status;
} /* End btampUnpackTlvAMP_Assoc_PAL_Capabilities. */
typedef v_U32_t (*pfnUnpackTlvAMP_Assoc_PAL_Capabilities_t)(void *, v_U8_t*, v_U16_t, tBtampTLVAMP_Assoc_PAL_Capabilities*);
#define SigUnpackTlvAMP_Assoc_PAL_Capabilities ( 0x0003 )
v_U32_t btampUnpackTlvAMP_Assoc_PAL_Version(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVAMP_Assoc_PAL_Version *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_VERSION_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
pDst->pal_version = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->pal_CompanyID, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
framesntohs(pCtx, &pDst->pal_subversion, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvAMP_Assoc_PAL_Version. */
typedef v_U32_t (*pfnUnpackTlvAMP_Assoc_PAL_Version_t)(void *, v_U8_t*, v_U16_t, tBtampTLVAMP_Assoc_PAL_Version*);
#define SigUnpackTlvAMP_Assoc_PAL_Version ( 0x0004 )
v_U32_t btampUnpackTlvAMP_Assoc_Preferred_Channel_List(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVAMP_Assoc_Preferred_Channel_List *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_AMP_ASSOC_PREF_CH_TLV_MIN_LEN > tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
/* Contry String - 3 bytes */
BTAMP_MEMCPY(pCtx, pDst->country, pBuf, 3);
pBuf += 3;
tlvlen -= (v_U8_t)3;
if ( ! tlvlen )
{
pDst->num_triplets = 0U;
return status;
}
else
{
/* Maximum of 5 triplets allowed, based on size of triplets definition */
if (tlvlen / 3 > 5)
{
tlvlen = 15;
}
pDst->num_triplets = (v_U8_t)( tlvlen / 3 );
BTAMP_MEMCPY(pCtx, pDst->triplets, pBuf, ( tlvlen ) );
pBuf += ( tlvlen );
tlvlen -= ( tlvlen );
}
return status;
} /* End btampUnpackTlvAMP_Assoc_Preferred_Channel_List. */
typedef v_U32_t (*pfnUnpackTlvAMP_Assoc_Preferred_Channel_List_t)(void *, v_U8_t*, v_U16_t, tBtampTLVAMP_Assoc_Preferred_Channel_List*);
#define SigUnpackTlvAMP_Assoc_Preferred_Channel_List ( 0x0005 )
v_U32_t btampUnpackTlvFlow_Spec(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVFlow_Spec *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_FLOW_SPEC_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
pDst->flow_spec_id = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->service_type = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->max_sdu, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
framesntohl(pCtx, &pDst->sdu_inter_arrival, pBuf, 0);
pBuf += 4;
tlvlen -= (v_U8_t)4;
framesntohl(pCtx, &pDst->access_latency, pBuf, 0);
pBuf += 4;
tlvlen -= (v_U8_t)4;
framesntohl(pCtx, &pDst->flush_timeout, pBuf, 0);
pBuf += 4;
tlvlen -= (v_U8_t)4;
(void)pCtx;
return status;
} /* End btampUnpackTlvFlow_Spec. */
typedef v_U32_t (*pfnUnpackTlvFlow_Spec_t)(void *, v_U8_t*, v_U16_t, tBtampTLVFlow_Spec*);
#define SigUnpackTlvFlow_Spec ( 0x0006 )
v_U32_t btampUnpackTlvHCI_Accept_Logical_Link_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Accept_Logical_Link_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
#ifdef WLAN_BAPHCI_ENABLE_VALIDITY_CHECKING
if ( WLAN_BAP_PAL_ACC_LOG_LINK_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
// return BTAMP_INVALID_TLV_LENGTH;
}
#endif
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
BTAMP_MEMCPY(pCtx, pDst->tx_flow_spec, pBuf, 18);
pBuf += 18;
tlvlen -= (v_U8_t)18;
BTAMP_MEMCPY(pCtx, pDst->rx_flow_spec, pBuf, 18);
pBuf += 18;
tlvlen -= (v_U8_t)18;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Accept_Logical_Link_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Accept_Logical_Link_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Accept_Logical_Link_Cmd*);
#define SigUnpackTlvHCI_Accept_Logical_Link_Cmd ( 0x0007 )
v_U32_t btampUnpackTlvHCI_Accept_Physical_Link_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Accept_Physical_Link_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_ACC_PHY_LINK_TLV_MIN_LEN > tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->key_length = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->key_type = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
if (pDst->key_length > 32){
pDst->present = 0;
return BTAMP_SKIPPED_BAD_IE;
}
BTAMP_MEMCPY(pCtx, pDst->key_material, pBuf, ( pDst->key_length ) );
pBuf += ( pDst->key_length );
tlvlen -= ( pDst->key_length );
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Accept_Physical_Link_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Accept_Physical_Link_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Accept_Physical_Link_Cmd*);
#define SigUnpackTlvHCI_Accept_Physical_Link_Cmd ( 0x0008 )
v_U32_t btampUnpackTlvHCI_Channel_Selected_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Channel_Selected_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Channel_Selected_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Channel_Selected_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Channel_Selected_Event*);
#define SigUnpackTlvHCI_Channel_Selected_Event ( 0x0009 )
v_U32_t btampUnpackTlvHCI_Command_Complete_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Command_Complete_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
pDst->num_hci_command_packets = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->command_opcode, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
switch (pDst->command_opcode)
{
case 0x0c03:
pDst->cc_event.Reset.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 0x0c08:
pDst->cc_event.Flush.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->cc_event.Flush.log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
break;
case 0x043b:
pDst->cc_event.Logical_Link_Cancel.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->cc_event.Logical_Link_Cancel.phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->cc_event.Logical_Link_Cancel.tx_flow_spec_id = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 0x0c05:
pDst->cc_event.Set_Event_Mask.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 0x0c15:
pDst->cc_event.Read_Connection_Accept_TO.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->cc_event.Read_Connection_Accept_TO.connection_accept_timeout, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
break;
case 0x0c16:
pDst->cc_event.Write_Connection_Accept_TO.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 0x0c36:
pDst->cc_event.Read_Link_Supervision_TO.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->cc_event.Read_Link_Supervision_TO.log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
framesntohs(pCtx, &pDst->cc_event.Read_Link_Supervision_TO.link_supervision_timeout, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
break;
case 0x0c37:
pDst->cc_event.Write_Link_Supervision_TO.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->cc_event.Write_Link_Supervision_TO.log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
break;
case 0x0c61:
pDst->cc_event.Read_Logical_Link_Accept_TO.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->cc_event.Read_Logical_Link_Accept_TO.logical_link_accept_timeout, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
break;
case 0x0c62:
pDst->cc_event.Write_Logical_Link_Accept_TO.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 0x0c63:
pDst->cc_event.Set_Event_Mask_Page_2.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 0x0c64:
pDst->cc_event.Read_Location_Data.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->cc_event.Read_Location_Data.loc_domain_aware = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
BTAMP_MEMCPY(pCtx, pDst->cc_event.Read_Location_Data.loc_domain, pBuf, 3);
pBuf += 3;
tlvlen -= (v_U8_t)3;
pDst->cc_event.Read_Location_Data.loc_options = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 3173:
pDst->cc_event.Write_Location_Data.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 3174:
pDst->cc_event.Read_Flow_Control_Mode.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->cc_event.Read_Flow_Control_Mode.flow_control_mode = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 3175:
pDst->cc_event.Write_Flow_Control_Mode.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 3177:
pDst->cc_event.Read_BE_Flush_TO.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohl(pCtx, &pDst->cc_event.Read_BE_Flush_TO.best_effort_flush_timeout, pBuf, 0);
pBuf += 4;
tlvlen -= (v_U8_t)4;
break;
case 3178:
pDst->cc_event.Write_BE_Flush_TO.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 3179:
pDst->cc_event.Set_Short_Range_Mode.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 4097:
pDst->cc_event.Read_Local_Version_Info.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->cc_event.Read_Local_Version_Info.HC_HCI_Version = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->cc_event.Read_Local_Version_Info.HC_HCI_Revision, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
pDst->cc_event.Read_Local_Version_Info.HC_PAL_Version = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->cc_event.Read_Local_Version_Info.HC_Manufac_Name, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
framesntohs(pCtx, &pDst->cc_event.Read_Local_Version_Info.HC_PAL_Sub_Version, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
break;
case 4098:
pDst->cc_event.Read_Local_Supported_Cmds.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
BTAMP_MEMCPY(pCtx, pDst->cc_event.Read_Local_Supported_Cmds.HC_Support_Cmds, pBuf, 64);
pBuf += 64;
tlvlen -= (v_U8_t)64;
break;
case 4101:
pDst->cc_event.Read_Buffer_Size.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->cc_event.Read_Buffer_Size.HC_ACL_Data_Packet_Length, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
pDst->cc_event.Read_Buffer_Size.HC_SCO_Packet_Length = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->cc_event.Read_Buffer_Size.HC_Total_Num_ACL_Packets, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
framesntohs(pCtx, &pDst->cc_event.Read_Buffer_Size.HC_Total_Num_SCO_Packets, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
break;
case 4106:
pDst->cc_event.Read_Data_Block_Size.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->cc_event.Read_Data_Block_Size.HC_Max_ACL_Data_Packet_Length, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
framesntohs(pCtx, &pDst->cc_event.Read_Data_Block_Size.HC_Data_Block_Length, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
framesntohs(pCtx, &pDst->cc_event.Read_Data_Block_Size.HC_Total_Num_Data_Blocks, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
break;
case 5121:
pDst->cc_event.Read_Failed_Contact_Counter.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->cc_event.Read_Failed_Contact_Counter.log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
framesntohs(pCtx, &pDst->cc_event.Read_Failed_Contact_Counter.failed_contact_counter, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
break;
case 5122:
pDst->cc_event.Reset_Failed_Contact_Counter.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->cc_event.Reset_Failed_Contact_Counter.log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
break;
case 5123:
pDst->cc_event.Read_Link_Quality.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->cc_event.Read_Link_Quality.log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
pDst->cc_event.Read_Link_Quality.link_quality = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 5125:
pDst->cc_event.Read_RSSI.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->cc_event.Read_RSSI.phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->cc_event.Read_RSSI.rssi = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 5129:
pDst->cc_event.Read_Local_AMP_Info.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->cc_event.Read_Local_AMP_Info.HC_AMP_Status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohl(pCtx, &pDst->cc_event.Read_Local_AMP_Info.HC_Total_BW, pBuf, 0);
pBuf += 4;
tlvlen -= (v_U8_t)4;
framesntohl(pCtx, &pDst->cc_event.Read_Local_AMP_Info.HC_Max_Guaranteed_BW, pBuf, 0);
pBuf += 4;
tlvlen -= (v_U8_t)4;
framesntohl(pCtx, &pDst->cc_event.Read_Local_AMP_Info.HC_Min_Latency, pBuf, 0);
pBuf += 4;
tlvlen -= (v_U8_t)4;
framesntohl(pCtx, &pDst->cc_event.Read_Local_AMP_Info.HC_Max_PDU_Size, pBuf, 0);
pBuf += 4;
tlvlen -= (v_U8_t)4;
pDst->cc_event.Read_Local_AMP_Info.HC_Controller_Type = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->cc_event.Read_Local_AMP_Info.HC_PAL_Capabilities, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
framesntohs(pCtx, &pDst->cc_event.Read_Local_AMP_Info.HC_AMP_Assoc_Length, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
framesntohl(pCtx, &pDst->cc_event.Read_Local_AMP_Info.HC_Max_Flush_Timeout, pBuf, 0);
pBuf += 4;
tlvlen -= (v_U8_t)4;
framesntohl(pCtx, &pDst->cc_event.Read_Local_AMP_Info.HC_BE_Flush_Timeout, pBuf, 0);
pBuf += 4;
tlvlen -= (v_U8_t)4;
break;
case 5130:
pDst->cc_event.Read_Read_Local_AMP_Assoc.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->cc_event.Read_Read_Local_AMP_Assoc.phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->cc_event.Read_Read_Local_AMP_Assoc.remaining_length, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
if (pDst->cc_event.Read_Read_Local_AMP_Assoc.remaining_length > 248){
// pDst->cc_event.Read_Read_Local_AMP_Assoc.present = 0;
return BTAMP_SKIPPED_BAD_IE;
}
BTAMP_MEMCPY(pCtx, pDst->cc_event.Read_Read_Local_AMP_Assoc.AMP_assoc_fragment, pBuf, ( pDst->cc_event.Read_Read_Local_AMP_Assoc.remaining_length ) );
pBuf += ( pDst->cc_event.Read_Read_Local_AMP_Assoc.remaining_length );
tlvlen -= ( pDst->cc_event.Read_Read_Local_AMP_Assoc.remaining_length );
break;
case 5131:
pDst->cc_event.Write_Remote_AMP_Assoc.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->cc_event.Write_Remote_AMP_Assoc.phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 6145:
pDst->cc_event.Read_Loopback_Mode.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->cc_event.Read_Loopback_Mode.loopback_mode = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
case 6146:
pDst->cc_event.Write_Loopback_Mode.status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
break;
}
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Command_Complete_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Command_Complete_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Command_Complete_Event*);
#define SigUnpackTlvHCI_Command_Complete_Event ( 0x000a )
v_U32_t btampUnpackTlvHCI_Command_Status_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Command_Status_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
pDst->status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->num_hci_command_packets = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->command_opcode, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Command_Status_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Command_Status_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Command_Status_Event*);
#define SigUnpackTlvHCI_Command_Status_Event ( 0x000b )
v_U32_t btampUnpackTlvHCI_Create_Logical_Link_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Create_Logical_Link_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
#ifdef WLAN_BAPHCI_ENABLE_VALIDITY_CHECKING
if ( WLAN_BAP_PAL_CREATE_LOG_LINK_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
// return BTAMP_INVALID_TLV_LENGTH;
}
#endif
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
BTAMP_MEMCPY(pCtx, pDst->tx_flow_spec, pBuf, 18);
pBuf += 18;
tlvlen -= (v_U8_t)18;
BTAMP_MEMCPY(pCtx, pDst->rx_flow_spec, pBuf, 18);
pBuf += 18;
tlvlen -= (v_U8_t)18;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Create_Logical_Link_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Create_Logical_Link_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Create_Logical_Link_Cmd*);
#define SigUnpackTlvHCI_Create_Logical_Link_Cmd ( 0x000c )
v_U32_t btampUnpackTlvHCI_Create_Physical_Link_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Create_Physical_Link_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_CREATE_PHY_LINK_TLV_MIN_LEN > tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->key_length = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->key_type = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
if (pDst->key_length > 32){
pDst->present = 0;
return BTAMP_SKIPPED_BAD_IE;
}
BTAMP_MEMCPY(pCtx, pDst->key_material, pBuf, ( pDst->key_length ) );
pBuf += ( pDst->key_length );
tlvlen -= ( pDst->key_length );
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Create_Physical_Link_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Create_Physical_Link_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Create_Physical_Link_Cmd*);
#define SigUnpackTlvHCI_Create_Physical_Link_Cmd ( 0x000d )
v_U32_t btampUnpackTlvHCI_Data_Buffer_Overflow_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Data_Buffer_Overflow_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
pDst->link_type = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Data_Buffer_Overflow_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Data_Buffer_Overflow_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Data_Buffer_Overflow_Event*);
#define SigUnpackTlvHCI_Data_Buffer_Overflow_Event ( 0x000e )
v_U32_t btampUnpackTlvHCI_Disconnect_Logical_Link_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Disconnect_Logical_Link_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_DISC_LOG_LINK_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Disconnect_Logical_Link_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Disconnect_Logical_Link_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Disconnect_Logical_Link_Cmd*);
#define SigUnpackTlvHCI_Disconnect_Logical_Link_Cmd ( 0x000f )
v_U32_t btampUnpackTlvHCI_Disconnect_Logical_Link_Complete_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Disconnect_Logical_Link_Complete_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
pDst->status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
pDst->reason = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Disconnect_Logical_Link_Complete_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Disconnect_Logical_Link_Complete_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Disconnect_Logical_Link_Complete_Event*);
#define SigUnpackTlvHCI_Disconnect_Logical_Link_Complete_Event ( 0x0010 )
v_U32_t btampUnpackTlvHCI_Disconnect_Physical_Link_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Disconnect_Physical_Link_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
#ifdef WLAN_BAPHCI_ENABLE_VALIDITY_CHECKING
if ( WLAN_BAP_PAL_DISC_PHY_LINK_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
// return BTAMP_INVALID_TLV_LENGTH;
}
#endif
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->reason = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Disconnect_Physical_Link_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Disconnect_Physical_Link_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Disconnect_Physical_Link_Cmd*);
#define SigUnpackTlvHCI_Disconnect_Physical_Link_Cmd ( 0x0011 )
v_U32_t btampUnpackTlvHCI_Disconnect_Physical_Link_Complete_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Disconnect_Physical_Link_Complete_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
pDst->status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->reason = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Disconnect_Physical_Link_Complete_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Disconnect_Physical_Link_Complete_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Disconnect_Physical_Link_Complete_Event*);
#define SigUnpackTlvHCI_Disconnect_Physical_Link_Complete_Event ( 0x0012 )
v_U32_t btampUnpackTlvHCI_Flow_Spec_Modify_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Flow_Spec_Modify_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_FLOW_SPEC_MOD_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
pDst->be_aggr_counter = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
BTAMP_MEMCPY(pCtx, pDst->tx_flow_spec, pBuf, 18);
pBuf += 18;
tlvlen -= (v_U8_t)18;
BTAMP_MEMCPY(pCtx, pDst->rx_flow_spec, pBuf, 18);
pBuf += 18;
tlvlen -= (v_U8_t)18;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Flow_Spec_Modify_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Flow_Spec_Modify_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Flow_Spec_Modify_Cmd*);
#define SigUnpackTlvHCI_Flow_Spec_Modify_Cmd ( 0x0013 )
v_U32_t btampUnpackTlvHCI_Flow_Spec_Modify_Complete_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Flow_Spec_Modify_Complete_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
pDst->status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Flow_Spec_Modify_Complete_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Flow_Spec_Modify_Complete_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Flow_Spec_Modify_Complete_Event*);
#define SigUnpackTlvHCI_Flow_Spec_Modify_Complete_Event ( 0x0014 )
v_U32_t btampUnpackTlvHCI_Flush_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Flush_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_FLUSH_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Flush_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Flush_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Flush_Cmd*);
#define SigUnpackTlvHCI_Flush_Cmd ( 0x0015 )
v_U32_t btampUnpackTlvHCI_Flush_Occurred_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Flush_Occurred_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Flush_Occurred_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Flush_Occurred_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Flush_Occurred_Event*);
#define SigUnpackTlvHCI_Flush_Occurred_Event ( 0x0016 )
v_U32_t btampUnpackTlvHCI_Generic_AMP_Link_Key_Notification_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Generic_AMP_Link_Key_Notification_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
BTAMP_MEMCPY(pCtx, pDst->bd_addr, pBuf, 6);
pBuf += 6;
tlvlen -= (v_U8_t)6;
BTAMP_MEMCPY(pCtx, pDst->generic_amp_link_key, pBuf, 32);
pBuf += 32;
tlvlen -= (v_U8_t)32;
pDst->key_type = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Generic_AMP_Link_Key_Notification_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Generic_AMP_Link_Key_Notification_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Generic_AMP_Link_Key_Notification_Event*);
#define SigUnpackTlvHCI_Generic_AMP_Link_Key_Notification_Event ( 0x0017 )
v_U32_t btampUnpackTlvHCI_Hardware_Error_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Hardware_Error_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
pDst->hardware_code = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Hardware_Error_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Hardware_Error_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Hardware_Error_Event*);
#define SigUnpackTlvHCI_Hardware_Error_Event ( 0x0018 )
v_U32_t btampUnpackTlvHCI_Logical_Link_Cancel_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Logical_Link_Cancel_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_CANCEL_LOG_LINK_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->tx_flow_spec_id = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Logical_Link_Cancel_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Logical_Link_Cancel_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Logical_Link_Cancel_Cmd*);
#define SigUnpackTlvHCI_Logical_Link_Cancel_Cmd ( 0x0019 )
v_U32_t btampUnpackTlvHCI_Logical_Link_Complete_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Logical_Link_Complete_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
pDst->status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Logical_Link_Complete_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Logical_Link_Complete_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Logical_Link_Complete_Event*);
#define SigUnpackTlvHCI_Logical_Link_Complete_Event ( 0x001a )
v_U32_t btampUnpackTlvHCI_Loopback_Command_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Loopback_Command_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
BTAMP_MEMCPY(pCtx, pDst->hci_command_packet, pBuf, 64);
pBuf += 64;
tlvlen -= (v_U8_t)64;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Loopback_Command_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Loopback_Command_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Loopback_Command_Event*);
#define SigUnpackTlvHCI_Loopback_Command_Event ( 0x001b )
v_U32_t btampUnpackTlvHCI_Physical_Link_Complete_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Physical_Link_Complete_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
pDst->status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Physical_Link_Complete_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Physical_Link_Complete_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Physical_Link_Complete_Event*);
#define SigUnpackTlvHCI_Physical_Link_Complete_Event ( 0x001c )
v_U32_t btampUnpackTlvHCI_Physical_Link_Loss_Warning_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Physical_Link_Loss_Warning_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->reason = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Physical_Link_Loss_Warning_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Physical_Link_Loss_Warning_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Physical_Link_Loss_Warning_Event*);
#define SigUnpackTlvHCI_Physical_Link_Loss_Warning_Event ( 0x001d )
v_U32_t btampUnpackTlvHCI_Physical_Link_Recovery_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Physical_Link_Recovery_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Physical_Link_Recovery_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Physical_Link_Recovery_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Physical_Link_Recovery_Event*);
#define SigUnpackTlvHCI_Physical_Link_Recovery_Event ( 0x001e )
v_U32_t btampUnpackTlvHCI_Qos_Violation_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Qos_Violation_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Qos_Violation_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Qos_Violation_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Qos_Violation_Event*);
#define SigUnpackTlvHCI_Qos_Violation_Event ( 0x001f )
v_U32_t btampUnpackTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_Best_Effort_Flush_Timeout_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_READ_BE_FLUSH_TIMEOUT_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_Best_Effort_Flush_Timeout_Cmd*);
#define SigUnpackTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd ( 0x0020 )
v_U32_t btampUnpackTlvHCI_Read_Buffer_Size_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_Buffer_Size_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_Buffer_Size_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_Buffer_Size_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_Buffer_Size_Cmd*);
#define SigUnpackTlvHCI_Read_Buffer_Size_Cmd ( 0x0021 )
v_U32_t btampUnpackTlvHCI_Read_Connection_Accept_Timeout_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_Connection_Accept_Timeout_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_Connection_Accept_Timeout_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_Connection_Accept_Timeout_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_Connection_Accept_Timeout_Cmd*);
#define SigUnpackTlvHCI_Read_Connection_Accept_Timeout_Cmd ( 0x0022 )
v_U32_t btampUnpackTlvHCI_Read_Data_Block_Size_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_Data_Block_Size_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_Data_Block_Size_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_Data_Block_Size_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_Data_Block_Size_Cmd*);
#define SigUnpackTlvHCI_Read_Data_Block_Size_Cmd ( 0x0023 )
v_U32_t btampUnpackTlvHCI_Read_Failed_Contact_Counter_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_Failed_Contact_Counter_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_READ_FAILED_CONTACT_CNT_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_Failed_Contact_Counter_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_Failed_Contact_Counter_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_Failed_Contact_Counter_Cmd*);
#define SigUnpackTlvHCI_Read_Failed_Contact_Counter_Cmd ( 0x0024 )
v_U32_t btampUnpackTlvHCI_Read_Flow_Control_Mode_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_Flow_Control_Mode_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_Flow_Control_Mode_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_Flow_Control_Mode_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_Flow_Control_Mode_Cmd*);
#define SigUnpackTlvHCI_Read_Flow_Control_Mode_Cmd ( 0x0025 )
v_U32_t btampUnpackTlvHCI_Read_Link_Quality_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_Link_Quality_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_READ_LINK_QUALITY_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_Link_Quality_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_Link_Quality_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_Link_Quality_Cmd*);
#define SigUnpackTlvHCI_Read_Link_Quality_Cmd ( 0x0026 )
v_U32_t btampUnpackTlvHCI_Read_Link_Supervision_Timeout_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_Link_Supervision_Timeout_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_READ_LINK_SVISISON_TIMEOUT_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_Link_Supervision_Timeout_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_Link_Supervision_Timeout_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_Link_Supervision_Timeout_Cmd*);
#define SigUnpackTlvHCI_Read_Link_Supervision_Timeout_Cmd ( 0x0027 )
v_U32_t btampUnpackTlvHCI_Read_Local_AMP_Assoc_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_Local_AMP_Assoc_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s. tlvlen=%d.", __FUNCTION__, tlvlen);
#ifdef WLAN_BAPHCI_ENABLE_VALIDITY_CHECKING
if ( WLAN_BAP_PAL_READ_LOCAL_AMP_ASSOC_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
// return BTAMP_INVALID_TLV_LENGTH;
}
#endif
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->length_so_far, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
framesntohs(pCtx, &pDst->max_remote_amp_assoc_length, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_Local_AMP_Assoc_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_Local_AMP_Assoc_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_Local_AMP_Assoc_Cmd*);
#define SigUnpackTlvHCI_Read_Local_AMP_Assoc_Cmd ( 0x0028 )
v_U32_t btampUnpackTlvHCI_Read_Local_AMP_Information_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_Local_AMP_Information_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_Local_AMP_Information_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_Local_AMP_Information_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_Local_AMP_Information_Cmd*);
#define SigUnpackTlvHCI_Read_Local_AMP_Information_Cmd ( 0x0029 )
v_U32_t btampUnpackTlvHCI_Read_Local_Supported_Cmds_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_Local_Supported_Cmds_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_Local_Supported_Cmds_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_Local_Supported_Cmds_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_Local_Supported_Cmds_Cmd*);
#define SigUnpackTlvHCI_Read_Local_Supported_Cmds_Cmd ( 0x002a )
v_U32_t btampUnpackTlvHCI_Read_Local_Version_Info_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_Local_Version_Info_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_Local_Version_Info_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_Local_Version_Info_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_Local_Version_Info_Cmd*);
#define SigUnpackTlvHCI_Read_Local_Version_Info_Cmd ( 0x002b )
v_U32_t btampUnpackTlvHCI_Read_Location_Data_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_Location_Data_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_Location_Data_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_Location_Data_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_Location_Data_Cmd*);
#define SigUnpackTlvHCI_Read_Location_Data_Cmd ( 0x002c )
v_U32_t btampUnpackTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_Logical_Link_Accept_Timeout_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_Logical_Link_Accept_Timeout_Cmd*);
#define SigUnpackTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd ( 0x002d )
v_U32_t btampUnpackTlvHCI_Read_Loopback_Mode_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_Loopback_Mode_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_Loopback_Mode_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_Loopback_Mode_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_Loopback_Mode_Cmd*);
#define SigUnpackTlvHCI_Read_Loopback_Mode_Cmd ( 0x002e )
v_U32_t btampUnpackTlvHCI_Read_RSSI_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Read_RSSI_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_READ_RSSI_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Read_RSSI_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Read_RSSI_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Read_RSSI_Cmd*);
#define SigUnpackTlvHCI_Read_RSSI_Cmd ( 0x002f )
v_U32_t btampUnpackTlvHCI_Reset_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Reset_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Reset_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Reset_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Reset_Cmd*);
#define SigUnpackTlvHCI_Reset_Cmd ( 0x0030 )
v_U32_t btampUnpackTlvHCI_Reset_Failed_Contact_Counter_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Reset_Failed_Contact_Counter_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_RESET_FAILED_CONTACT_CNT_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Reset_Failed_Contact_Counter_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Reset_Failed_Contact_Counter_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Reset_Failed_Contact_Counter_Cmd*);
#define SigUnpackTlvHCI_Reset_Failed_Contact_Counter_Cmd ( 0x0031 )
v_U32_t btampUnpackTlvHCI_Set_Event_Mask_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Set_Event_Mask_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_SET_EVENT_MASK_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
BTAMP_MEMCPY(pCtx, pDst->event_mask, pBuf, 8);
pBuf += 8;
tlvlen -= (v_U8_t)8;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Set_Event_Mask_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Set_Event_Mask_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Set_Event_Mask_Cmd*);
#define SigUnpackTlvHCI_Set_Event_Mask_Cmd ( 0x0032 )
v_U32_t btampUnpackTlvHCI_Set_Event_Mask_Page_2_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Set_Event_Mask_Page_2_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s. tlvlen=%d.", __FUNCTION__, tlvlen);
#ifdef WLAN_BAPHCI_ENABLE_VALIDITY_CHECKING
if ( WLAN_BAP_PAL_SET_EVENT_MASK2_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
// return BTAMP_INVALID_TLV_LENGTH;
}
#endif
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
BTAMP_MEMCPY(pCtx, pDst->event_mask_page_2, pBuf, 8);
pBuf += 8;
tlvlen -= (v_U8_t)8;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Set_Event_Mask_Page_2_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Set_Event_Mask_Page_2_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Set_Event_Mask_Page_2_Cmd*);
#define SigUnpackTlvHCI_Set_Event_Mask_Page_2_Cmd ( 0x0033 )
v_U32_t btampUnpackTlvHCI_Set_Short_Range_Mode_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Set_Short_Range_Mode_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_SET_SHORT_RANGE_MODE_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->short_range_mode = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Set_Short_Range_Mode_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Set_Short_Range_Mode_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Set_Short_Range_Mode_Cmd*);
#define SigUnpackTlvHCI_Set_Short_Range_Mode_Cmd ( 0x0034 )
v_U32_t btampUnpackTlvHCI_Short_Range_Mode_Change_Complete_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Short_Range_Mode_Change_Complete_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
pDst->status = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
pDst->short_range_mode = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Short_Range_Mode_Change_Complete_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Short_Range_Mode_Change_Complete_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Short_Range_Mode_Change_Complete_Event*);
#define SigUnpackTlvHCI_Short_Range_Mode_Change_Complete_Event ( 0x0035 )
v_U32_t btampUnpackTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Write_Best_Effort_Flush_Timeout_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_WRITE_BE_FLUSH_TIMEOUT_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
framesntohl(pCtx, &pDst->best_effort_flush_timeout, pBuf, 0);
pBuf += 4;
tlvlen -= (v_U8_t)4;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Write_Best_Effort_Flush_Timeout_Cmd*);
#define SigUnpackTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd ( 0x0036 )
v_U32_t btampUnpackTlvHCI_Write_Connection_Accept_Timeout_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Write_Connection_Accept_Timeout_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_WRITE_CON_ACC_TIMEOUT_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
framesntohs(pCtx, &pDst->connection_accept_timeout, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Write_Connection_Accept_Timeout_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Write_Connection_Accept_Timeout_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Write_Connection_Accept_Timeout_Cmd*);
#define SigUnpackTlvHCI_Write_Connection_Accept_Timeout_Cmd ( 0x0037 )
v_U32_t btampUnpackTlvHCI_Write_Flow_Control_Mode_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Write_Flow_Control_Mode_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_WRITE_FLOW_CTRL_MODE_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
pDst->flow_control_mode = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Write_Flow_Control_Mode_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Write_Flow_Control_Mode_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Write_Flow_Control_Mode_Cmd*);
#define SigUnpackTlvHCI_Write_Flow_Control_Mode_Cmd ( 0x0038 )
v_U32_t btampUnpackTlvHCI_Write_Link_Supervision_Timeout_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Write_Link_Supervision_Timeout_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_WRITE_LINK_SVISION_TIMEOUT_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
framesntohs(pCtx, &pDst->link_supervision_timeout, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Write_Link_Supervision_Timeout_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Write_Link_Supervision_Timeout_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Write_Link_Supervision_Timeout_Cmd*);
#define SigUnpackTlvHCI_Write_Link_Supervision_Timeout_Cmd ( 0x0039 )
v_U32_t btampUnpackTlvHCI_Write_Location_Data_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Write_Location_Data_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_WRITE_LOCATION_DATA_CMD_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
pDst->loc_domain_aware = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
BTAMP_MEMCPY(pCtx, pDst->loc_domain, pBuf, 3);
pBuf += 3;
tlvlen -= (v_U8_t)3;
pDst->loc_options = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Write_Location_Data_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Write_Location_Data_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Write_Location_Data_Cmd*);
#define SigUnpackTlvHCI_Write_Location_Data_Cmd ( 0x003a )
v_U32_t btampUnpackTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Write_Logical_Link_Accept_Timeout_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_WRITE_LOG_LINK_ACC_TIMEOUT_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
framesntohs(pCtx, &pDst->logical_link_accept_timeout, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Write_Logical_Link_Accept_Timeout_Cmd*);
#define SigUnpackTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd ( 0x003b )
v_U32_t btampUnpackTlvHCI_Write_Loopback_Mode_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Write_Loopback_Mode_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_WRITE_LOOOPBACK_MODE_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
pDst->loopback_mode = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Write_Loopback_Mode_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Write_Loopback_Mode_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Write_Loopback_Mode_Cmd*);
#define SigUnpackTlvHCI_Write_Loopback_Mode_Cmd ( 0x003c )
v_U32_t btampUnpackTlvHCI_Write_Remote_AMP_ASSOC_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Write_Remote_AMP_ASSOC_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_WRITE_REMOTE_AMP_ASSOC_MIN_TLV_LEN > tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
pDst->phy_link_handle = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
framesntohs(pCtx, &pDst->length_so_far, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
framesntohs(pCtx, &pDst->amp_assoc_remaining_length, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
if (pDst->amp_assoc_remaining_length > 248){
pDst->present = 0;
return BTAMP_SKIPPED_BAD_IE;
}
BTAMP_MEMCPY(pCtx, pDst->amp_assoc_fragment, pBuf, ( pDst->amp_assoc_remaining_length ) );
pBuf += ( pDst->amp_assoc_remaining_length );
tlvlen -= ( pDst->amp_assoc_remaining_length );
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Write_Remote_AMP_ASSOC_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Write_Remote_AMP_ASSOC_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Write_Remote_AMP_ASSOC_Cmd*);
#define SigUnpackTlvHCI_Write_Remote_AMP_ASSOC_Cmd ( 0x003d )
v_U32_t btampUnpackTlvHCI_Enhanced_Flush_Cmd(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Enhanced_Flush_Cmd *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
/*-----------------------------------------------------------------------
TLV Sanity check
-------------------------------------------------------------------------*/
if ( WLAN_BAP_PAL_ENHANCED_FLUSH_TLV_LEN != tlvlen )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
/*Log invalid len*/
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR,
"Invalid TLV len on %s", __FUNCTION__);
#endif
return BTAMP_INVALID_TLV_LENGTH;
}
/*-----------------------------------------------------------------------
Parse TLV
-----------------------------------------------------------------------*/
pDst->present = 1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
pDst->packet_type = *pBuf;
pBuf += 1;
tlvlen -= (v_U8_t)1;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Enhanced_Flush_Cmd. */
typedef v_U32_t (*pfnUnpackTlvHCI_Enhanced_Flush_Cmd_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Enhanced_Flush_Cmd*);
#define SigUnpackTlvHCI_Enhanced_Flush_Cmd ( 0x003e )
v_U32_t btampUnpackTlvHCI_Enhanced_Flush_Complete_Event(void * pCtx, v_U8_t *pBuf, v_U16_t tlvlen, tBtampTLVHCI_Enhanced_Flush_Complete_Event *pDst)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pBuf; (void)tlvlen; /* Shutup the compiler */
pDst->present = 1;
framesntohs(pCtx, &pDst->log_link_handle, pBuf, 0);
pBuf += 2;
tlvlen -= (v_U8_t)2;
(void)pCtx;
return status;
} /* End btampUnpackTlvHCI_Enhanced_Flush_Completed_Event. */
typedef v_U32_t (*pfnUnpackTlvHCI_Enhanced_Flush_Complete_Event_t)(void *, v_U8_t*, v_U16_t, tBtampTLVHCI_Enhanced_Flush_Complete_Event*);
#define SigUnpackTlvHCI_Enhanced_Flush_Complete_Event ( 0x003f )
v_U32_t btampUnpackAMP_ASSOC(void * pCtx, v_U8_t *pBuf, v_U32_t nBuf, tBtampAMP_ASSOC *pFrm)
{
v_U32_t i;
static tTLVDefn TLVS[ ] = {
{BTAMP_TLV_AMP_ASSOC_MAC_ADDR, 0, 9, 9, offsetof(tBtampAMP_ASSOC, AMP_Assoc_MAC_Addr), offsetof(tBtampTLVAMP_Assoc_MAC_Addr, present), SigUnpackTlvAMP_Assoc_MAC_Addr, (pfnGeneric_t)btampUnpackTlvAMP_Assoc_MAC_Addr, "AMP_Assoc_MAC_Addr", 1, },
{BTAMP_TLV_AMP_ASSOC_PREFERRED_CHANNEL_LIST, 0, 9, 0xFF/*12*/, offsetof(tBtampAMP_ASSOC, AMP_Assoc_Preferred_Channel_List), offsetof(tBtampTLVAMP_Assoc_Preferred_Channel_List, present), SigUnpackTlvAMP_Assoc_Preferred_Channel_List, (pfnGeneric_t)btampUnpackTlvAMP_Assoc_Preferred_Channel_List, "AMP_Assoc_Preferred_Channel_List", 1, },
{BTAMP_TLV_AMP_ASSOC_CONNECTED_CHANNEL, 0, 9, 0xFF/*12*/, offsetof(tBtampAMP_ASSOC, AMP_Assoc_Connected_Channel), offsetof(tBtampTLVAMP_Assoc_Connected_Channel, present), SigUnpackTlvAMP_Assoc_Connected_Channel, (pfnGeneric_t)btampUnpackTlvAMP_Assoc_Connected_Channel, "AMP_Assoc_Connected_Channel", 0, },
{BTAMP_TLV_AMP_ASSOC_PAL_CAPABILITIES, 0, 7, 7, offsetof(tBtampAMP_ASSOC, AMP_Assoc_PAL_Capabilities), offsetof(tBtampTLVAMP_Assoc_PAL_Capabilities, present), SigUnpackTlvAMP_Assoc_PAL_Capabilities, (pfnGeneric_t)btampUnpackTlvAMP_Assoc_PAL_Capabilities, "AMP_Assoc_PAL_Capabilities", 0, },
{BTAMP_TLV_AMP_ASSOC_PAL_VERSION, 0, 8, 8, offsetof(tBtampAMP_ASSOC, AMP_Assoc_PAL_Version), offsetof(tBtampTLVAMP_Assoc_PAL_Version, present), SigUnpackTlvAMP_Assoc_PAL_Version, (pfnGeneric_t)btampUnpackTlvAMP_Assoc_PAL_Version, "AMP_Assoc_PAL_Version", 1, },
{ 0xffff, 0 },
};
v_U32_t status = 0;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"In btampUnpackAMP_ASSOC. nBuf - %d\n", nBuf);
#endif
status |= UnpackTlvCore(pCtx,pBuf,nBuf,TLVS,(v_U8_t*)pFrm,sizeof(*pFrm));
(void)i;
# ifdef BTAMP_DUMP_FRAMES
if (!BTAMP_FAILED(status))
{
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("Unpacked the AMP_ASSOC:\n"));
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), pBuf, nBuf);
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("to:\n"));
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("AMP_Assoc_MAC_Addr:\n"));
if (!pFrm->AMP_Assoc_MAC_Addr.present)
{
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("Not present.\n"));
}
else
{
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* )&pFrm->AMP_Assoc_MAC_Addr.mac_addr, 6);
}
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("AMP_Assoc_Preferred_Channel_List:\n"));
if (!pFrm->AMP_Assoc_Preferred_Channel_List.present)
{
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("Not present.\n"));
}
else
{
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* )&pFrm->AMP_Assoc_Preferred_Channel_List.country, 3);
FRAMES_LOG1(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("num_triplets: %d.\n"), pFrm->AMP_Assoc_Preferred_Channel_List.num_triplets);
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* ) pFrm->AMP_Assoc_Preferred_Channel_List.triplets, 3 * pFrm->AMP_Assoc_Preferred_Channel_List.num_triplets);
}
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("AMP_Assoc_Connected_Channel:\n"));
if (!pFrm->AMP_Assoc_Connected_Channel.present)
{
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("Not present.\n"));
}
else
{
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* )&pFrm->AMP_Assoc_Connected_Channel.country, 3);
FRAMES_LOG1(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("num_triplets: %d.\n"), pFrm->AMP_Assoc_Connected_Channel.num_triplets);
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* ) pFrm->AMP_Assoc_Connected_Channel.triplets, 3 * pFrm->AMP_Assoc_Connected_Channel.num_triplets);
}
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("AMP_Assoc_PAL_Capabilities:\n"));
if (!pFrm->AMP_Assoc_PAL_Capabilities.present)
{
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("Not present.\n"));
}
else
{
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* )&pFrm->AMP_Assoc_PAL_Capabilities.pal_capabilities, 4);
}
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("AMP_Assoc_PAL_Version:\n"));
if (!pFrm->AMP_Assoc_PAL_Version.present)
{
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("Not present.\n"));
}
else
{
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* )&pFrm->AMP_Assoc_PAL_Version.pal_version, 1);
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* )&pFrm->AMP_Assoc_PAL_Version.pal_CompanyID, 2);
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* )&pFrm->AMP_Assoc_PAL_Version.pal_subversion, 2);
}
}
# endif // BTAMP_DUMP_FRAMES
return status;
} /* End btampUnpackAMP_ASSOC. */
static v_U32_t UnpackTlvCore( void * pCtx,
v_U8_t *pBuf,
v_U32_t nBuf,
tTLVDefn TLVs[ ],
v_U8_t *pFrm,
size_t nFrm )
{
tTLVDefn *pTlv;
v_U32_t nBufRemaining, status, status2, npec;
v_U32_t sType, sLen;
v_U16_t id, len;
v_U8_t *pBufRemaining, *pfFound;
(void)pCtx; // Shutup the compiler
(void)nFrm;
status = BTAMP_PARSE_SUCCESS;
status2 = BTAMP_PARSE_SUCCESS;
pBufRemaining = pBuf;
nBufRemaining = nBuf;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"In UnpackTlvCore, nBufRemaining - %d\n", nBufRemaining);
#endif
// While we have data...
while ( nBufRemaining )
{
if ( 3 > nBufRemaining )
{
FRAMES_LOG0( pCtx, FRLOGE, FRFL( "This frame reports "
"fewer three byte(s) remaining.\n" ) );
status |= BTAMP_INCOMPLETE_TLV;
FRAMES_DBG_BREAK();
goto MandatoryCheck;
}
npec = 0U;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"Calling FindTLVDefn...\n", nBufRemaining);
#endif
// Look for a matching TLV definition,
pTlv = FindTLVDefn( pCtx, pBufRemaining, nBufRemaining, TLVs );
sType = 1;
sLen = 2;
// consume the type,
if (sType == 2)
framesntohs(pCtx, &id, pBufRemaining, 1);
else {
id = *pBufRemaining;
}
pBufRemaining += sType;
nBufRemaining -= sType;
// & length,
framesntohs(pCtx, &len, pBufRemaining, 1);
pBufRemaining += sLen;
nBufRemaining -= sLen;
if ( pTlv && pTlv->pec )
{
npec = 3U;
if ( 3 > nBufRemaining )
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"3 > nBufRemaining\n");
#endif
FRAMES_LOG2(pCtx, FRLOGW, FRFL("TLV %d reports length"
"%d, but it has a Private Enterprise Code (3 byte"
"s.\n"), id, len);
FRAMES_DUMP(pCtx, FRLOG1, pBuf, nBuf);
FRAMES_LOG2(pCtx, FRLOG1, FRFL("We've parsed %d bytes"
"of this buffer, and show %d left.\n"),
pBufRemaining - pBuf, nBufRemaining);
status |= BTAMP_INCOMPLETE_TLV;
FRAMES_DBG_BREAK();
goto MandatoryCheck;
}
pBufRemaining += 3;
nBufRemaining -= 3;
len -= 3;
}
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"Len - %d nBufRemaining - %d\n", len, nBufRemaining);
#endif
// Whether we found a hit or not, we can validate the reported
// length of this TLV:
if ( len > nBufRemaining )
{
FRAMES_LOG3(pCtx, FRLOGW, FRFL("TLV %d reports length %"
"d, but there are only %d bytes remaining in this f"
"rame.\n"), id, len, nBufRemaining );
FRAMES_DUMP( pCtx, FRLOG1, pBuf, nBuf );
FRAMES_LOG2( pCtx, FRLOG1, FRFL( "We've parsed %d bytes"
" of this buffer, and show %d left.\n"),
pBufRemaining - pBuf, nBufRemaining);
status |= BTAMP_INCOMPLETE_TLV;
FRAMES_DBG_BREAK();
goto MandatoryCheck;
}
// Now, *if* we found a hit...
if ( pTlv )
{
if ( nBufRemaining < pTlv->minSize - npec - (sType + sLen))
{
FRAMES_LOG3( pCtx, FRLOGW, FRFL("The IE %s must be "
"at least %d bytes in size, but there are only "
"%d bytes remaining in this frame.\n"),
pTlv->name, pTlv->minSize, nBufRemaining );
FRAMES_DUMP( pCtx, FRLOG1, pBuf, nBuf );
status |= BTAMP_INCOMPLETE_TLV;
FRAMES_DBG_BREAK( );
goto MandatoryCheck;
}
else if ( len > pTlv->maxSize - npec - (sType + sLen))
{
FRAMES_LOG1( pCtx, FRLOGW, FRFL("The TLV %s reports "
"an illegally large size; this TLV is presumably"
"corrupt or otherwise invalid & will be skipped "
"ipped.\n"), pTlv->name );
FRAMES_DUMP( pCtx, FRLOG1, pBuf, nBuf );
FRAMES_LOG2( pCtx, FRLOG1, FRFL("We've parsed %d by"
"tes of this buffer, and show %d left.\n"),
pBufRemaining - pBuf, nBufRemaining);
FRAMES_DBG_BREAK();
status |= BTAMP_SKIPPED_BAD_TLV;
}
else
{
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"pTlv->sig - %d\n", pTlv->sig);
#endif
switch (pTlv->sig)
{
case SigUnpackTlvAMP_Assoc_Connected_Channel:
status2 = ( (pfnUnpackTlvAMP_Assoc_Connected_Channel_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVAMP_Assoc_Connected_Channel* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvAMP_Assoc_MAC_Addr:
status2 = ( (pfnUnpackTlvAMP_Assoc_MAC_Addr_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVAMP_Assoc_MAC_Addr* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvAMP_Assoc_PAL_Capabilities:
status2 = ( (pfnUnpackTlvAMP_Assoc_PAL_Capabilities_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVAMP_Assoc_PAL_Capabilities* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvAMP_Assoc_PAL_Version:
status2 = ( (pfnUnpackTlvAMP_Assoc_PAL_Version_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVAMP_Assoc_PAL_Version* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvAMP_Assoc_Preferred_Channel_List:
status2 = ( (pfnUnpackTlvAMP_Assoc_Preferred_Channel_List_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVAMP_Assoc_Preferred_Channel_List* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvFlow_Spec:
status2 = ( (pfnUnpackTlvFlow_Spec_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVFlow_Spec* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Accept_Logical_Link_Cmd:
status2 = ( (pfnUnpackTlvHCI_Accept_Logical_Link_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Accept_Logical_Link_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Accept_Physical_Link_Cmd:
status2 = ( (pfnUnpackTlvHCI_Accept_Physical_Link_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Accept_Physical_Link_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Channel_Selected_Event:
status2 = ( (pfnUnpackTlvHCI_Channel_Selected_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Channel_Selected_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Command_Complete_Event:
status2 = ( (pfnUnpackTlvHCI_Command_Complete_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Command_Complete_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Command_Status_Event:
status2 = ( (pfnUnpackTlvHCI_Command_Status_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Command_Status_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Create_Logical_Link_Cmd:
status2 = ( (pfnUnpackTlvHCI_Create_Logical_Link_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Create_Logical_Link_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Create_Physical_Link_Cmd:
status2 = ( (pfnUnpackTlvHCI_Create_Physical_Link_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Create_Physical_Link_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Data_Buffer_Overflow_Event:
status2 = ( (pfnUnpackTlvHCI_Data_Buffer_Overflow_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Data_Buffer_Overflow_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Disconnect_Logical_Link_Cmd:
status2 = ( (pfnUnpackTlvHCI_Disconnect_Logical_Link_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Disconnect_Logical_Link_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Disconnect_Logical_Link_Complete_Event:
status2 = ( (pfnUnpackTlvHCI_Disconnect_Logical_Link_Complete_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Disconnect_Logical_Link_Complete_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Disconnect_Physical_Link_Cmd:
status2 = ( (pfnUnpackTlvHCI_Disconnect_Physical_Link_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Disconnect_Physical_Link_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Disconnect_Physical_Link_Complete_Event:
status2 = ( (pfnUnpackTlvHCI_Disconnect_Physical_Link_Complete_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Disconnect_Physical_Link_Complete_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Flow_Spec_Modify_Cmd:
status2 = ( (pfnUnpackTlvHCI_Flow_Spec_Modify_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Flow_Spec_Modify_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Flow_Spec_Modify_Complete_Event:
status2 = ( (pfnUnpackTlvHCI_Flow_Spec_Modify_Complete_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Flow_Spec_Modify_Complete_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Flush_Cmd:
status2 = ( (pfnUnpackTlvHCI_Flush_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Flush_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Flush_Occurred_Event:
status2 = ( (pfnUnpackTlvHCI_Flush_Occurred_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Flush_Occurred_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Generic_AMP_Link_Key_Notification_Event:
status2 = ( (pfnUnpackTlvHCI_Generic_AMP_Link_Key_Notification_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Generic_AMP_Link_Key_Notification_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Hardware_Error_Event:
status2 = ( (pfnUnpackTlvHCI_Hardware_Error_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Hardware_Error_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Logical_Link_Cancel_Cmd:
status2 = ( (pfnUnpackTlvHCI_Logical_Link_Cancel_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Logical_Link_Cancel_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Logical_Link_Complete_Event:
status2 = ( (pfnUnpackTlvHCI_Logical_Link_Complete_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Logical_Link_Complete_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Loopback_Command_Event:
status2 = ( (pfnUnpackTlvHCI_Loopback_Command_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Loopback_Command_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Physical_Link_Complete_Event:
status2 = ( (pfnUnpackTlvHCI_Physical_Link_Complete_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Physical_Link_Complete_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Physical_Link_Loss_Warning_Event:
status2 = ( (pfnUnpackTlvHCI_Physical_Link_Loss_Warning_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Physical_Link_Loss_Warning_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Physical_Link_Recovery_Event:
status2 = ( (pfnUnpackTlvHCI_Physical_Link_Recovery_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Physical_Link_Recovery_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Qos_Violation_Event:
status2 = ( (pfnUnpackTlvHCI_Qos_Violation_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Qos_Violation_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_Best_Effort_Flush_Timeout_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_Buffer_Size_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_Buffer_Size_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_Buffer_Size_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_Connection_Accept_Timeout_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_Connection_Accept_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_Connection_Accept_Timeout_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_Data_Block_Size_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_Data_Block_Size_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_Data_Block_Size_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_Failed_Contact_Counter_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_Failed_Contact_Counter_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_Failed_Contact_Counter_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_Flow_Control_Mode_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_Flow_Control_Mode_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_Flow_Control_Mode_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_Link_Quality_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_Link_Quality_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_Link_Quality_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_Link_Supervision_Timeout_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_Link_Supervision_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_Link_Supervision_Timeout_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_Local_AMP_Assoc_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_Local_AMP_Assoc_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_Local_AMP_Assoc_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_Local_AMP_Information_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_Local_AMP_Information_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_Local_AMP_Information_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_Local_Supported_Cmds_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_Local_Supported_Cmds_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_Local_Supported_Cmds_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_Local_Version_Info_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_Local_Version_Info_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_Local_Version_Info_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_Location_Data_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_Location_Data_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_Location_Data_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_Logical_Link_Accept_Timeout_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_Loopback_Mode_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_Loopback_Mode_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_Loopback_Mode_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Read_RSSI_Cmd:
status2 = ( (pfnUnpackTlvHCI_Read_RSSI_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Read_RSSI_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Reset_Cmd:
status2 = ( (pfnUnpackTlvHCI_Reset_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Reset_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Reset_Failed_Contact_Counter_Cmd:
status2 = ( (pfnUnpackTlvHCI_Reset_Failed_Contact_Counter_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Reset_Failed_Contact_Counter_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Set_Event_Mask_Cmd:
status2 = ( (pfnUnpackTlvHCI_Set_Event_Mask_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Set_Event_Mask_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Set_Event_Mask_Page_2_Cmd:
status2 = ( (pfnUnpackTlvHCI_Set_Event_Mask_Page_2_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Set_Event_Mask_Page_2_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Set_Short_Range_Mode_Cmd:
status2 = ( (pfnUnpackTlvHCI_Set_Short_Range_Mode_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Set_Short_Range_Mode_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Short_Range_Mode_Change_Complete_Event:
status2 = ( (pfnUnpackTlvHCI_Short_Range_Mode_Change_Complete_Event_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Short_Range_Mode_Change_Complete_Event* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd:
status2 = ( (pfnUnpackTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Write_Best_Effort_Flush_Timeout_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Write_Connection_Accept_Timeout_Cmd:
status2 = ( (pfnUnpackTlvHCI_Write_Connection_Accept_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Write_Connection_Accept_Timeout_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Write_Flow_Control_Mode_Cmd:
status2 = ( (pfnUnpackTlvHCI_Write_Flow_Control_Mode_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Write_Flow_Control_Mode_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Write_Link_Supervision_Timeout_Cmd:
status2 = ( (pfnUnpackTlvHCI_Write_Link_Supervision_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Write_Link_Supervision_Timeout_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Write_Location_Data_Cmd:
status2 = ( (pfnUnpackTlvHCI_Write_Location_Data_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Write_Location_Data_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd:
status2 = ( (pfnUnpackTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Write_Logical_Link_Accept_Timeout_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Write_Loopback_Mode_Cmd:
status2 = ( (pfnUnpackTlvHCI_Write_Loopback_Mode_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Write_Loopback_Mode_Cmd* )(pFrm + pTlv->offset ));
break;
case SigUnpackTlvHCI_Write_Remote_AMP_ASSOC_Cmd:
status2 = ( (pfnUnpackTlvHCI_Write_Remote_AMP_ASSOC_Cmd_t)(pTlv->pfn) )(pCtx, pBufRemaining, len, ( tBtampTLVHCI_Write_Remote_AMP_ASSOC_Cmd* )(pFrm + pTlv->offset ));
break;
default:
FRAMES_LOG1(pCtx, FRLOGE, FRFL("INTERNAL ERROR: I"
" don't know about the TLV signature %d-- thi"
"s is most likely a 'framesc' bug.\n"),
pTlv->sig);
FRAMES_DBG_BREAK();
return BTAMP_INTERNAL_ERROR;
} // End switch on sig.
} // End if on length check.
status |= status2;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"status - %x\n", status);
#endif
}
else
{
FRAMES_LOG2(pCtx, FRLOG3, FRFL("Skipping unknown TLV %d ("
"length %d)\n"), id, len);
FRAMES_DUMP(pCtx, FRLOG3, pBufRemaining - (sType + sLen), len);
status |= BTAMP_UNKNOWN_TLVS;
}
// Advance to the next TLV
pBufRemaining += len;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"len - %d nBufRemaining - %d\n", len, nBufRemaining);
#endif
if (len > nBufRemaining)
{
FRAMES_LOG0(pCtx, FRLOGW, FRFL("This TLV extends past th"
"e buffer as it was defined to us. This could mean "
"a corrupt frame, or just an incorrect length parame"
"ter.\n"));
FRAMES_DBG_BREAK();
status |= BTAMP_LAST_TLV_TOO_LONG;
goto MandatoryCheck;
}
nBufRemaining -= len;
} // End iteration over TLVs.
MandatoryCheck:
pTlv = &TLVs[0];
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"pTlv->id - %x\n", pTlv->id);
#endif
while (0xffff != pTlv->id)
{
if (pTlv->fMandatory)
{
pfFound = (v_U8_t*)(pFrm + pTlv->offset +
pTlv->presenceOffset);
if (!*pfFound)
{
FRAMES_LOG1(pCtx, FRLOGW, FRFL("ERROR: The mandatory "
"TLV %s wasn't seen.\n"),
pTlv->name);
FRAMES_DBG_BREAK();
status |= BTAMP_MANDATORY_TLV_MISSING;
}
}
++pTlv;
}
return status;
} /* End UnpacTlvkCore. */
v_U32_t btampGetPackedTlvAMP_Assoc_Connected_Channel(void * pCtx, tBtampTLVAMP_Assoc_Connected_Channel *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"In btampGetPackedTlvAMP_Assoc_Connected_Channel\n");
#endif
while ( pTlv->present )
{
*pnNeeded += 3;
if ( pTlv->num_triplets )
{
*pnNeeded += ( pTlv->num_triplets * 3 );
}
else break;
break;
}
return status;
} /* End btampGetPackedTLVAMP_Assoc_Connected_Channel. */
typedef v_U32_t (*pfnPackSizeTlvAMP_Assoc_Connected_Channel_t)(void *, tBtampTLVAMP_Assoc_Connected_Channel*, v_U32_t*);
#define SigPackSizeTlvAMP_Assoc_Connected_Channel ( 0x003e )
v_U32_t btampGetPackedTlvAMP_Assoc_MAC_Addr(void * pCtx, tBtampTLVAMP_Assoc_MAC_Addr *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"In btampGetPackedTlvAMP_Assoc_MAC_Addr\n");
#endif
while ( pTlv->present )
{
*pnNeeded += 6;
break;
}
return status;
} /* End btampGetPackedTLVAMP_Assoc_MAC_Addr. */
typedef v_U32_t (*pfnPackSizeTlvAMP_Assoc_MAC_Addr_t)(void *, tBtampTLVAMP_Assoc_MAC_Addr*, v_U32_t*);
#define SigPackSizeTlvAMP_Assoc_MAC_Addr ( 0x003f )
v_U32_t btampGetPackedTlvAMP_Assoc_PAL_Capabilities(void * pCtx, tBtampTLVAMP_Assoc_PAL_Capabilities *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"In btampGetPackedTlvAMP_Assoc_PAL_Capabilities\n");
#endif
while ( pTlv->present )
{
*pnNeeded += 4;
break;
}
return status;
} /* End btampGetPackedTLVAMP_Assoc_PAL_Capabilities. */
typedef v_U32_t (*pfnPackSizeTlvAMP_Assoc_PAL_Capabilities_t)(void *, tBtampTLVAMP_Assoc_PAL_Capabilities*, v_U32_t*);
#define SigPackSizeTlvAMP_Assoc_PAL_Capabilities ( 0x0040 )
v_U32_t btampGetPackedTlvAMP_Assoc_PAL_Version(void * pCtx, tBtampTLVAMP_Assoc_PAL_Version *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVAMP_Assoc_PAL_Version. */
typedef v_U32_t (*pfnPackSizeTlvAMP_Assoc_PAL_Version_t)(void *, tBtampTLVAMP_Assoc_PAL_Version*, v_U32_t*);
#define SigPackSizeTlvAMP_Assoc_PAL_Version ( 0x0041 )
v_U32_t btampGetPackedTlvAMP_Assoc_Preferred_Channel_List(void * pCtx, tBtampTLVAMP_Assoc_Preferred_Channel_List *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"In btampGetPackedTlvAMP_Assoc_Preferred_Channel_List\n");
#endif
while ( pTlv->present )
{
*pnNeeded += 3;
if ( pTlv->num_triplets )
{
*pnNeeded += ( pTlv->num_triplets * 3 );
}
else break;
break;
}
return status;
} /* End btampGetPackedTLVAMP_Assoc_Preferred_Channel_List. */
typedef v_U32_t (*pfnPackSizeTlvAMP_Assoc_Preferred_Channel_List_t)(void *, tBtampTLVAMP_Assoc_Preferred_Channel_List*, v_U32_t*);
#define SigPackSizeTlvAMP_Assoc_Preferred_Channel_List ( 0x0042 )
v_U32_t btampGetPackedTlvFlow_Spec(void * pCtx, tBtampTLVFlow_Spec *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 4;
*pnNeeded += 4;
*pnNeeded += 4;
break;
}
return status;
} /* End btampGetPackedTLVFlow_Spec. */
typedef v_U32_t (*pfnPackSizeTlvFlow_Spec_t)(void *, tBtampTLVFlow_Spec*, v_U32_t*);
#define SigPackSizeTlvFlow_Spec ( 0x0043 )
v_U32_t btampGetPackedTlvHCI_Accept_Logical_Link_Cmd(void * pCtx, tBtampTLVHCI_Accept_Logical_Link_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 18;
*pnNeeded += 18;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Accept_Logical_Link_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Accept_Logical_Link_Cmd_t)(void *, tBtampTLVHCI_Accept_Logical_Link_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Accept_Logical_Link_Cmd ( 0x0044 )
v_U32_t btampGetPackedTlvHCI_Accept_Physical_Link_Cmd(void * pCtx, tBtampTLVHCI_Accept_Physical_Link_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 1;
*pnNeeded += 1;
*pnNeeded += pTlv->key_length;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Accept_Physical_Link_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Accept_Physical_Link_Cmd_t)(void *, tBtampTLVHCI_Accept_Physical_Link_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Accept_Physical_Link_Cmd ( 0x0045 )
v_U32_t btampGetPackedTlvHCI_Channel_Selected_Event(void * pCtx, tBtampTLVHCI_Channel_Selected_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Channel_Selected_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Channel_Selected_Event_t)(void *, tBtampTLVHCI_Channel_Selected_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Channel_Selected_Event ( 0x0046 )
v_U32_t btampGetPackedTlvHCI_Command_Complete_Event(void * pCtx, tBtampTLVHCI_Command_Complete_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 2;
switch (pTlv->command_opcode)
{
case 3075:
*pnNeeded += 1;
break;
case 3080:
*pnNeeded += 1;
*pnNeeded += 2;
break;
case 1083:
*pnNeeded += 1;
*pnNeeded += 1;
*pnNeeded += 1;
break;
case 3077:
*pnNeeded += 1;
break;
case 3093:
*pnNeeded += 1;
*pnNeeded += 2;
break;
case 3094:
*pnNeeded += 1;
break;
case 3126:
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 2;
break;
case 3127:
*pnNeeded += 1;
*pnNeeded += 2;
break;
case 3169:
*pnNeeded += 1;
*pnNeeded += 2;
break;
case 3170:
*pnNeeded += 1;
break;
case 3171:
*pnNeeded += 1;
break;
case 3172:
*pnNeeded += 1;
*pnNeeded += 1;
*pnNeeded += 3;
*pnNeeded += 1;
break;
case 3173:
*pnNeeded += 1;
break;
case 3174:
*pnNeeded += 1;
*pnNeeded += 1;
break;
case 3175:
*pnNeeded += 1;
break;
case 3177:
*pnNeeded += 1;
*pnNeeded += 4;
break;
case 3178:
*pnNeeded += 1;
break;
case 3179:
*pnNeeded += 1;
break;
case 4097:
*pnNeeded += 1;
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 2;
break;
case 4098:
*pnNeeded += 1;
*pnNeeded += 64;
break;
case 4101:
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 2;
break;
case 4106:
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 2;
*pnNeeded += 2;
break;
case 5121:
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 2;
break;
case 5122:
*pnNeeded += 1;
*pnNeeded += 2;
break;
case 5123:
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 1;
break;
case 5125:
*pnNeeded += 1;
*pnNeeded += 1;
*pnNeeded += 1;
break;
case 5129:
*pnNeeded += 1;
*pnNeeded += 1;
*pnNeeded += 4;
*pnNeeded += 4;
*pnNeeded += 4;
*pnNeeded += 4;
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 2;
*pnNeeded += 4;
*pnNeeded += 4;
break;
case 5130:
*pnNeeded += 1;
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += pTlv->cc_event.Read_Read_Local_AMP_Assoc.remaining_length;
break;
case 5131:
*pnNeeded += 1;
*pnNeeded += 1;
break;
case 6145:
*pnNeeded += 1;
*pnNeeded += 1;
break;
case 6146:
*pnNeeded += 1;
break;
}
break;
}
return status;
} /* End btampGetPackedTLVHCI_Command_Complete_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Command_Complete_Event_t)(void *, tBtampTLVHCI_Command_Complete_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Command_Complete_Event ( 0x0047 )
v_U32_t btampGetPackedTlvHCI_Command_Status_Event(void * pCtx, tBtampTLVHCI_Command_Status_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 1;
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Command_Status_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Command_Status_Event_t)(void *, tBtampTLVHCI_Command_Status_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Command_Status_Event ( 0x0048 )
v_U32_t btampGetPackedTlvHCI_Create_Logical_Link_Cmd(void * pCtx, tBtampTLVHCI_Create_Logical_Link_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 18;
*pnNeeded += 18;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Create_Logical_Link_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Create_Logical_Link_Cmd_t)(void *, tBtampTLVHCI_Create_Logical_Link_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Create_Logical_Link_Cmd ( 0x0049 )
v_U32_t btampGetPackedTlvHCI_Create_Physical_Link_Cmd(void * pCtx, tBtampTLVHCI_Create_Physical_Link_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 1;
*pnNeeded += 1;
*pnNeeded += pTlv->key_length;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Create_Physical_Link_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Create_Physical_Link_Cmd_t)(void *, tBtampTLVHCI_Create_Physical_Link_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Create_Physical_Link_Cmd ( 0x004a )
v_U32_t btampGetPackedTlvHCI_Data_Buffer_Overflow_Event(void * pCtx, tBtampTLVHCI_Data_Buffer_Overflow_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Data_Buffer_Overflow_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Data_Buffer_Overflow_Event_t)(void *, tBtampTLVHCI_Data_Buffer_Overflow_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Data_Buffer_Overflow_Event ( 0x004b )
v_U32_t btampGetPackedTlvHCI_Disconnect_Logical_Link_Cmd(void * pCtx, tBtampTLVHCI_Disconnect_Logical_Link_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Disconnect_Logical_Link_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Disconnect_Logical_Link_Cmd_t)(void *, tBtampTLVHCI_Disconnect_Logical_Link_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Disconnect_Logical_Link_Cmd ( 0x004c )
v_U32_t btampGetPackedTlvHCI_Disconnect_Logical_Link_Complete_Event(void * pCtx, tBtampTLVHCI_Disconnect_Logical_Link_Complete_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Disconnect_Logical_Link_Complete_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Disconnect_Logical_Link_Complete_Event_t)(void *, tBtampTLVHCI_Disconnect_Logical_Link_Complete_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Disconnect_Logical_Link_Complete_Event ( 0x004d )
v_U32_t btampGetPackedTlvHCI_Disconnect_Physical_Link_Cmd(void * pCtx, tBtampTLVHCI_Disconnect_Physical_Link_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Disconnect_Physical_Link_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Disconnect_Physical_Link_Cmd_t)(void *, tBtampTLVHCI_Disconnect_Physical_Link_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Disconnect_Physical_Link_Cmd ( 0x004e )
v_U32_t btampGetPackedTlvHCI_Disconnect_Physical_Link_Complete_Event(void * pCtx, tBtampTLVHCI_Disconnect_Physical_Link_Complete_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 1;
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Disconnect_Physical_Link_Complete_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Disconnect_Physical_Link_Complete_Event_t)(void *, tBtampTLVHCI_Disconnect_Physical_Link_Complete_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Disconnect_Physical_Link_Complete_Event ( 0x004f )
v_U32_t btampGetPackedTlvHCI_Flow_Spec_Modify_Cmd(void * pCtx, tBtampTLVHCI_Flow_Spec_Modify_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
*pnNeeded += 1;
*pnNeeded += 18;
*pnNeeded += 18;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Flow_Spec_Modify_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Flow_Spec_Modify_Cmd_t)(void *, tBtampTLVHCI_Flow_Spec_Modify_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Flow_Spec_Modify_Cmd ( 0x0050 )
v_U32_t btampGetPackedTlvHCI_Flow_Spec_Modify_Complete_Event(void * pCtx, tBtampTLVHCI_Flow_Spec_Modify_Complete_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Flow_Spec_Modify_Complete_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Flow_Spec_Modify_Complete_Event_t)(void *, tBtampTLVHCI_Flow_Spec_Modify_Complete_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Flow_Spec_Modify_Complete_Event ( 0x0051 )
v_U32_t btampGetPackedTlvHCI_Flush_Cmd(void * pCtx, tBtampTLVHCI_Flush_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Flush_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Flush_Cmd_t)(void *, tBtampTLVHCI_Flush_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Flush_Cmd ( 0x0052 )
v_U32_t btampGetPackedTlvHCI_Flush_Occurred_Event(void * pCtx, tBtampTLVHCI_Flush_Occurred_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Flush_Occurred_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Flush_Occurred_Event_t)(void *, tBtampTLVHCI_Flush_Occurred_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Flush_Occurred_Event ( 0x0053 )
v_U32_t btampGetPackedTlvHCI_Num_Completed_Pkts_Event(void * pCtx, tBtampTLVHCI_Num_Completed_Pkts_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
// while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 2;
#if 0
// New
*pnNeeded += 2;
*pnNeeded += 2;
*pnNeeded += 2;
*pnNeeded += 2;
*pnNeeded += 2;
*pnNeeded += 2;
// End of New
#endif
// break;
}
return status;
} /* End btampGetPackedTLVHCI_Num_Completed_Pkts_Event. */
v_U32_t btampGetPackedTlvHCI_Num_Completed_Data_Blocks_Event(void * pCtx, tBtampTLVHCI_Num_Completed_Data_Blocks_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
// while ( pTlv->present )
{
*pnNeeded += 2;
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 2;
*pnNeeded += 2;
// break;
}
return status;
} /* End btampGetPackedTLVHCI_Num_Completed_Data_Blocks_Event. */
//typedef v_U32_t (*pfnPackSizeTlvHCI_Num_Completed_Pkts_Event_t)(void *, tBtampTLVHCI_Command_Status_Event*, v_U32_t*);
//#define SigPackSizeTlvHCI_Num_Completed_Pkts_Event ( 0x0048 )
v_U32_t btampGetPackedTlvHCI_Generic_AMP_Link_Key_Notification_Event(void * pCtx, tBtampTLVHCI_Generic_AMP_Link_Key_Notification_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 6;
*pnNeeded += 32;
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Generic_AMP_Link_Key_Notification_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Generic_AMP_Link_Key_Notification_Event_t)(void *, tBtampTLVHCI_Generic_AMP_Link_Key_Notification_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Generic_AMP_Link_Key_Notification_Event ( 0x0054 )
v_U32_t btampGetPackedTlvHCI_Hardware_Error_Event(void * pCtx, tBtampTLVHCI_Hardware_Error_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Hardware_Error_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Hardware_Error_Event_t)(void *, tBtampTLVHCI_Hardware_Error_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Hardware_Error_Event ( 0x0055 )
v_U32_t btampGetPackedTlvHCI_Logical_Link_Cancel_Cmd(void * pCtx, tBtampTLVHCI_Logical_Link_Cancel_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Logical_Link_Cancel_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Logical_Link_Cancel_Cmd_t)(void *, tBtampTLVHCI_Logical_Link_Cancel_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Logical_Link_Cancel_Cmd ( 0x0056 )
v_U32_t btampGetPackedTlvHCI_Logical_Link_Complete_Event(void * pCtx, tBtampTLVHCI_Logical_Link_Complete_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 1;
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Logical_Link_Complete_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Logical_Link_Complete_Event_t)(void *, tBtampTLVHCI_Logical_Link_Complete_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Logical_Link_Complete_Event ( 0x0057 )
v_U32_t btampGetPackedTlvHCI_Loopback_Command_Event(void * pCtx, tBtampTLVHCI_Loopback_Command_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 64;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Loopback_Command_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Loopback_Command_Event_t)(void *, tBtampTLVHCI_Loopback_Command_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Loopback_Command_Event ( 0x0058 )
v_U32_t btampGetPackedTlvHCI_Physical_Link_Complete_Event(void * pCtx, tBtampTLVHCI_Physical_Link_Complete_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Physical_Link_Complete_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Physical_Link_Complete_Event_t)(void *, tBtampTLVHCI_Physical_Link_Complete_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Physical_Link_Complete_Event ( 0x0059 )
v_U32_t btampGetPackedTlvHCI_Physical_Link_Loss_Warning_Event(void * pCtx, tBtampTLVHCI_Physical_Link_Loss_Warning_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Physical_Link_Loss_Warning_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Physical_Link_Loss_Warning_Event_t)(void *, tBtampTLVHCI_Physical_Link_Loss_Warning_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Physical_Link_Loss_Warning_Event ( 0x005a )
v_U32_t btampGetPackedTlvHCI_Physical_Link_Recovery_Event(void * pCtx, tBtampTLVHCI_Physical_Link_Recovery_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Physical_Link_Recovery_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Physical_Link_Recovery_Event_t)(void *, tBtampTLVHCI_Physical_Link_Recovery_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Physical_Link_Recovery_Event ( 0x005b )
v_U32_t btampGetPackedTlvHCI_Qos_Violation_Event(void * pCtx, tBtampTLVHCI_Qos_Violation_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Qos_Violation_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Qos_Violation_Event_t)(void *, tBtampTLVHCI_Qos_Violation_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Qos_Violation_Event ( 0x005c )
v_U32_t btampGetPackedTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd(void * pCtx, tBtampTLVHCI_Read_Best_Effort_Flush_Timeout_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_Best_Effort_Flush_Timeout_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd_t)(void *, tBtampTLVHCI_Read_Best_Effort_Flush_Timeout_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd ( 0x005d )
v_U32_t btampGetPackedTlvHCI_Read_Buffer_Size_Cmd(void * pCtx, tBtampTLVHCI_Read_Buffer_Size_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_Buffer_Size_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_Buffer_Size_Cmd_t)(void *, tBtampTLVHCI_Read_Buffer_Size_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_Buffer_Size_Cmd ( 0x005e )
v_U32_t btampGetPackedTlvHCI_Read_Connection_Accept_Timeout_Cmd(void * pCtx, tBtampTLVHCI_Read_Connection_Accept_Timeout_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_Connection_Accept_Timeout_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_Connection_Accept_Timeout_Cmd_t)(void *, tBtampTLVHCI_Read_Connection_Accept_Timeout_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_Connection_Accept_Timeout_Cmd ( 0x005f )
v_U32_t btampGetPackedTlvHCI_Read_Data_Block_Size_Cmd(void * pCtx, tBtampTLVHCI_Read_Data_Block_Size_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_Data_Block_Size_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_Data_Block_Size_Cmd_t)(void *, tBtampTLVHCI_Read_Data_Block_Size_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_Data_Block_Size_Cmd ( 0x0060 )
v_U32_t btampGetPackedTlvHCI_Read_Failed_Contact_Counter_Cmd(void * pCtx, tBtampTLVHCI_Read_Failed_Contact_Counter_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_Failed_Contact_Counter_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_Failed_Contact_Counter_Cmd_t)(void *, tBtampTLVHCI_Read_Failed_Contact_Counter_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_Failed_Contact_Counter_Cmd ( 0x0061 )
v_U32_t btampGetPackedTlvHCI_Read_Flow_Control_Mode_Cmd(void * pCtx, tBtampTLVHCI_Read_Flow_Control_Mode_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_Flow_Control_Mode_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_Flow_Control_Mode_Cmd_t)(void *, tBtampTLVHCI_Read_Flow_Control_Mode_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_Flow_Control_Mode_Cmd ( 0x0062 )
v_U32_t btampGetPackedTlvHCI_Read_Link_Quality_Cmd(void * pCtx, tBtampTLVHCI_Read_Link_Quality_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_Link_Quality_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_Link_Quality_Cmd_t)(void *, tBtampTLVHCI_Read_Link_Quality_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_Link_Quality_Cmd ( 0x0063 )
v_U32_t btampGetPackedTlvHCI_Read_Link_Supervision_Timeout_Cmd(void * pCtx, tBtampTLVHCI_Read_Link_Supervision_Timeout_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_Link_Supervision_Timeout_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_Link_Supervision_Timeout_Cmd_t)(void *, tBtampTLVHCI_Read_Link_Supervision_Timeout_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_Link_Supervision_Timeout_Cmd ( 0x0064 )
v_U32_t btampGetPackedTlvHCI_Read_Local_AMP_Assoc_Cmd(void * pCtx, tBtampTLVHCI_Read_Local_AMP_Assoc_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_Local_AMP_Assoc_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_Local_AMP_Assoc_Cmd_t)(void *, tBtampTLVHCI_Read_Local_AMP_Assoc_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_Local_AMP_Assoc_Cmd ( 0x0065 )
v_U32_t btampGetPackedTlvHCI_Read_Local_AMP_Information_Cmd(void * pCtx, tBtampTLVHCI_Read_Local_AMP_Information_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_Local_AMP_Information_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_Local_AMP_Information_Cmd_t)(void *, tBtampTLVHCI_Read_Local_AMP_Information_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_Local_AMP_Information_Cmd ( 0x0066 )
v_U32_t btampGetPackedTlvHCI_Read_Local_Supported_Cmds_Cmd(void * pCtx, tBtampTLVHCI_Read_Local_Supported_Cmds_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_Local_Supported_Cmds_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_Local_Supported_Cmds_Cmd_t)(void *, tBtampTLVHCI_Read_Local_Supported_Cmds_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_Local_Supported_Cmds_Cmd ( 0x0067 )
v_U32_t btampGetPackedTlvHCI_Read_Local_Version_Info_Cmd(void * pCtx, tBtampTLVHCI_Read_Local_Version_Info_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_Local_Version_Info_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_Local_Version_Info_Cmd_t)(void *, tBtampTLVHCI_Read_Local_Version_Info_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_Local_Version_Info_Cmd ( 0x0068 )
v_U32_t btampGetPackedTlvHCI_Read_Location_Data_Cmd(void * pCtx, tBtampTLVHCI_Read_Location_Data_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_Location_Data_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_Location_Data_Cmd_t)(void *, tBtampTLVHCI_Read_Location_Data_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_Location_Data_Cmd ( 0x0069 )
v_U32_t btampGetPackedTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd(void * pCtx, tBtampTLVHCI_Read_Logical_Link_Accept_Timeout_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_Logical_Link_Accept_Timeout_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd_t)(void *, tBtampTLVHCI_Read_Logical_Link_Accept_Timeout_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd ( 0x006a )
v_U32_t btampGetPackedTlvHCI_Read_Loopback_Mode_Cmd(void * pCtx, tBtampTLVHCI_Read_Loopback_Mode_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_Loopback_Mode_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_Loopback_Mode_Cmd_t)(void *, tBtampTLVHCI_Read_Loopback_Mode_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_Loopback_Mode_Cmd ( 0x006b )
v_U32_t btampGetPackedTlvHCI_Read_RSSI_Cmd(void * pCtx, tBtampTLVHCI_Read_RSSI_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Read_RSSI_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Read_RSSI_Cmd_t)(void *, tBtampTLVHCI_Read_RSSI_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Read_RSSI_Cmd ( 0x006c )
v_U32_t btampGetPackedTlvHCI_Reset_Cmd(void * pCtx, tBtampTLVHCI_Reset_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
break;
}
return status;
} /* End btampGetPackedTLVHCI_Reset_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Reset_Cmd_t)(void *, tBtampTLVHCI_Reset_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Reset_Cmd ( 0x006d )
v_U32_t btampGetPackedTlvHCI_Reset_Failed_Contact_Counter_Cmd(void * pCtx, tBtampTLVHCI_Reset_Failed_Contact_Counter_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Reset_Failed_Contact_Counter_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Reset_Failed_Contact_Counter_Cmd_t)(void *, tBtampTLVHCI_Reset_Failed_Contact_Counter_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Reset_Failed_Contact_Counter_Cmd ( 0x006e )
v_U32_t btampGetPackedTlvHCI_Set_Event_Mask_Cmd(void * pCtx, tBtampTLVHCI_Set_Event_Mask_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 8;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Set_Event_Mask_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Set_Event_Mask_Cmd_t)(void *, tBtampTLVHCI_Set_Event_Mask_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Set_Event_Mask_Cmd ( 0x006f )
v_U32_t btampGetPackedTlvHCI_Set_Event_Mask_Page_2_Cmd(void * pCtx, tBtampTLVHCI_Set_Event_Mask_Page_2_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 8;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Set_Event_Mask_Page_2_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Set_Event_Mask_Page_2_Cmd_t)(void *, tBtampTLVHCI_Set_Event_Mask_Page_2_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Set_Event_Mask_Page_2_Cmd ( 0x0070 )
v_U32_t btampGetPackedTlvHCI_Set_Short_Range_Mode_Cmd(void * pCtx, tBtampTLVHCI_Set_Short_Range_Mode_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Set_Short_Range_Mode_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Set_Short_Range_Mode_Cmd_t)(void *, tBtampTLVHCI_Set_Short_Range_Mode_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Set_Short_Range_Mode_Cmd ( 0x0071 )
v_U32_t btampGetPackedTlvHCI_Short_Range_Mode_Change_Complete_Event(void * pCtx, tBtampTLVHCI_Short_Range_Mode_Change_Complete_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 1;
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Short_Range_Mode_Change_Complete_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Short_Range_Mode_Change_Complete_Event_t)(void *, tBtampTLVHCI_Short_Range_Mode_Change_Complete_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Short_Range_Mode_Change_Complete_Event ( 0x0072 )
v_U32_t btampGetPackedTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd(void * pCtx, tBtampTLVHCI_Write_Best_Effort_Flush_Timeout_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
*pnNeeded += 4;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Write_Best_Effort_Flush_Timeout_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd_t)(void *, tBtampTLVHCI_Write_Best_Effort_Flush_Timeout_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd ( 0x0073 )
v_U32_t btampGetPackedTlvHCI_Write_Connection_Accept_Timeout_Cmd(void * pCtx, tBtampTLVHCI_Write_Connection_Accept_Timeout_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Write_Connection_Accept_Timeout_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Write_Connection_Accept_Timeout_Cmd_t)(void *, tBtampTLVHCI_Write_Connection_Accept_Timeout_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Write_Connection_Accept_Timeout_Cmd ( 0x0074 )
v_U32_t btampGetPackedTlvHCI_Write_Flow_Control_Mode_Cmd(void * pCtx, tBtampTLVHCI_Write_Flow_Control_Mode_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Write_Flow_Control_Mode_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Write_Flow_Control_Mode_Cmd_t)(void *, tBtampTLVHCI_Write_Flow_Control_Mode_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Write_Flow_Control_Mode_Cmd ( 0x0075 )
v_U32_t btampGetPackedTlvHCI_Write_Link_Supervision_Timeout_Cmd(void * pCtx, tBtampTLVHCI_Write_Link_Supervision_Timeout_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Write_Link_Supervision_Timeout_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Write_Link_Supervision_Timeout_Cmd_t)(void *, tBtampTLVHCI_Write_Link_Supervision_Timeout_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Write_Link_Supervision_Timeout_Cmd ( 0x0076 )
v_U32_t btampGetPackedTlvHCI_Write_Location_Data_Cmd(void * pCtx, tBtampTLVHCI_Write_Location_Data_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 3;
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Write_Location_Data_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Write_Location_Data_Cmd_t)(void *, tBtampTLVHCI_Write_Location_Data_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Write_Location_Data_Cmd ( 0x0077 )
v_U32_t btampGetPackedTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd(void * pCtx, tBtampTLVHCI_Write_Logical_Link_Accept_Timeout_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Write_Logical_Link_Accept_Timeout_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd_t)(void *, tBtampTLVHCI_Write_Logical_Link_Accept_Timeout_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd ( 0x0078 )
v_U32_t btampGetPackedTlvHCI_Write_Loopback_Mode_Cmd(void * pCtx, tBtampTLVHCI_Write_Loopback_Mode_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Write_Loopback_Mode_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Write_Loopback_Mode_Cmd_t)(void *, tBtampTLVHCI_Write_Loopback_Mode_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Write_Loopback_Mode_Cmd ( 0x0079 )
v_U32_t btampGetPackedTlvHCI_Write_Remote_AMP_ASSOC_Cmd(void * pCtx, tBtampTLVHCI_Write_Remote_AMP_ASSOC_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"In btampGetPackedTlvHCI_Write_Remote_AMP_ASSOC_Cmd\n");
#endif
while ( pTlv->present )
{
*pnNeeded += 1;
*pnNeeded += 2;
*pnNeeded += 2;
*pnNeeded += pTlv->amp_assoc_remaining_length;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Write_Remote_AMP_ASSOC_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Write_Remote_AMP_ASSOC_Cmd_t)(void *, tBtampTLVHCI_Write_Remote_AMP_ASSOC_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Write_Remote_AMP_ASSOC_Cmd ( 0x007a )
v_U32_t btampGetPackedTlvHCI_Enhanced_Flush_Cmd(void * pCtx, tBtampTLVHCI_Enhanced_Flush_Cmd *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
*pnNeeded += 1;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Enhanced_Flush_Cmd. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Enhanced_Flush_Cmd_t)(void *, tBtampTLVHCI_Enhanced_Flush_Cmd*, v_U32_t*);
#define SigPackSizeTlvHCI_Enhanced_Flush_Cmd ( 0x007b )
v_U32_t btampGetPackedTlvHCI_Enhanced_Flush_Complete_Event(void * pCtx, tBtampTLVHCI_Enhanced_Flush_Complete_Event *pTlv, v_U32_t *pnNeeded)
{
v_U32_t status = BTAMP_PARSE_SUCCESS;
(void)pCtx; (void)pTlv; (void)pnNeeded;
while ( pTlv->present )
{
*pnNeeded += 2;
break;
}
return status;
} /* End btampGetPackedTLVHCI_Enhanced_Flush_Complete_Event. */
typedef v_U32_t (*pfnPackSizeTlvHCI_Enhanced_Flush_Complete_Event_t)(void *, tBtampTLVHCI_Enhanced_Flush_Complete_Event*, v_U32_t*);
#define SigPackSizeTlvHCI_Enhanced_Flush_Complete_Event ( 0x007c )
v_U32_t btampGetPackedAMP_ASSOCSize(void * pCtx, tBtampAMP_ASSOC *pFrm, v_U32_t *pnNeeded)
{
static tTLVDefn TLVS[ ] = {
{BTAMP_TLV_AMP_ASSOC_MAC_ADDR, 0, 9, 9, offsetof(tBtampAMP_ASSOC, AMP_Assoc_MAC_Addr), offsetof(tBtampTLVAMP_Assoc_MAC_Addr, present), SigPackSizeTlvAMP_Assoc_MAC_Addr, (pfnGeneric_t)btampGetPackedTlvAMP_Assoc_MAC_Addr, "AMP_Assoc_MAC_Addr", 1, },
{BTAMP_TLV_AMP_ASSOC_PREFERRED_CHANNEL_LIST, 0, 9, 12, offsetof(tBtampAMP_ASSOC, AMP_Assoc_Preferred_Channel_List), offsetof(tBtampTLVAMP_Assoc_Preferred_Channel_List, present), SigPackSizeTlvAMP_Assoc_Preferred_Channel_List, (pfnGeneric_t)btampGetPackedTlvAMP_Assoc_Preferred_Channel_List, "AMP_Assoc_Preferred_Channel_List", 1, },
{BTAMP_TLV_AMP_ASSOC_CONNECTED_CHANNEL, 0, 9, 12, offsetof(tBtampAMP_ASSOC, AMP_Assoc_Connected_Channel), offsetof(tBtampTLVAMP_Assoc_Connected_Channel, present), SigPackSizeTlvAMP_Assoc_Connected_Channel, (pfnGeneric_t)btampGetPackedTlvAMP_Assoc_Connected_Channel, "AMP_Assoc_Connected_Channel", 0, },
{BTAMP_TLV_AMP_ASSOC_PAL_CAPABILITIES, 0, 7, 7, offsetof(tBtampAMP_ASSOC, AMP_Assoc_PAL_Capabilities), offsetof(tBtampTLVAMP_Assoc_PAL_Capabilities, present), SigPackSizeTlvAMP_Assoc_PAL_Capabilities, (pfnGeneric_t)btampGetPackedTlvAMP_Assoc_PAL_Capabilities, "AMP_Assoc_PAL_Capabilities", 0, },
{BTAMP_TLV_AMP_ASSOC_PAL_VERSION, 0, 8, 8, offsetof(tBtampAMP_ASSOC, AMP_Assoc_PAL_Version), offsetof(tBtampTLVAMP_Assoc_PAL_Version, present), SigPackSizeTlvAMP_Assoc_PAL_Version, (pfnGeneric_t)btampGetPackedTlvAMP_Assoc_PAL_Version, "AMP_Assoc_PAL_Version", 1, },
{ 0xffff, 0 },
};
v_U32_t status = 0;
*pnNeeded = 0;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"In btampGetPackedAMP_ASSOCSize\n");
#endif
status |= GetPackedSizeTlvCore(pCtx,(v_U8_t*)pFrm,pnNeeded,TLVS);
return status;
} /* End btampGetPackedAMP_ASSOCSize. */
static v_U32_t GetPackedSizeTlvCore(void * pCtx,
v_U8_t *pFrm,
v_U32_t *pnNeeded,
tTLVDefn TLVs[])
{
tTLVDefn *pTlv;
v_U32_t status, status2;
tFRAMES_BOOL *pfFound;
status = BTAMP_PARSE_SUCCESS;
status2 = BTAMP_PARSE_SUCCESS;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"In GetPackedSizeTlvCore\n");
#endif
pTlv = &( TLVs[0] );
while ( 0xffff != pTlv->id )
{
pfFound = (tFRAMES_BOOL*)(pFrm + pTlv->offset +
pTlv->presenceOffset);
if ( *pfFound )
{
*pnNeeded += 4U;
if ( pTlv->pec ) *pnNeeded += 3U;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"In GetPackedSizeTlvCore, pTlv->sig - %d\n", pTlv->sig);
#endif
switch (pTlv->sig)
{
case SigPackSizeTlvAMP_Assoc_Connected_Channel:
status2 = ( (pfnPackSizeTlvAMP_Assoc_Connected_Channel_t)(pTlv->pfn) )(pCtx, ( tBtampTLVAMP_Assoc_Connected_Channel* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvAMP_Assoc_MAC_Addr:
status2 = ( (pfnPackSizeTlvAMP_Assoc_MAC_Addr_t)(pTlv->pfn) )(pCtx, ( tBtampTLVAMP_Assoc_MAC_Addr* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvAMP_Assoc_PAL_Capabilities:
status2 = ( (pfnPackSizeTlvAMP_Assoc_PAL_Capabilities_t)(pTlv->pfn) )(pCtx, ( tBtampTLVAMP_Assoc_PAL_Capabilities* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvAMP_Assoc_PAL_Version:
status2 = ( (pfnPackSizeTlvAMP_Assoc_PAL_Version_t)(pTlv->pfn) )(pCtx, ( tBtampTLVAMP_Assoc_PAL_Version* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvAMP_Assoc_Preferred_Channel_List:
status2 = ( (pfnPackSizeTlvAMP_Assoc_Preferred_Channel_List_t)(pTlv->pfn) )(pCtx, ( tBtampTLVAMP_Assoc_Preferred_Channel_List* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvFlow_Spec:
status2 = ( (pfnPackSizeTlvFlow_Spec_t)(pTlv->pfn) )(pCtx, ( tBtampTLVFlow_Spec* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Accept_Logical_Link_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Accept_Logical_Link_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Accept_Logical_Link_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Accept_Physical_Link_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Accept_Physical_Link_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Accept_Physical_Link_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Channel_Selected_Event:
status2 = ( (pfnPackSizeTlvHCI_Channel_Selected_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Channel_Selected_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Command_Complete_Event:
status2 = ( (pfnPackSizeTlvHCI_Command_Complete_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Command_Complete_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Command_Status_Event:
status2 = ( (pfnPackSizeTlvHCI_Command_Status_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Command_Status_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Create_Logical_Link_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Create_Logical_Link_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Create_Logical_Link_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Create_Physical_Link_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Create_Physical_Link_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Create_Physical_Link_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Data_Buffer_Overflow_Event:
status2 = ( (pfnPackSizeTlvHCI_Data_Buffer_Overflow_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Data_Buffer_Overflow_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Disconnect_Logical_Link_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Disconnect_Logical_Link_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Disconnect_Logical_Link_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Disconnect_Logical_Link_Complete_Event:
status2 = ( (pfnPackSizeTlvHCI_Disconnect_Logical_Link_Complete_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Disconnect_Logical_Link_Complete_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Disconnect_Physical_Link_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Disconnect_Physical_Link_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Disconnect_Physical_Link_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Disconnect_Physical_Link_Complete_Event:
status2 = ( (pfnPackSizeTlvHCI_Disconnect_Physical_Link_Complete_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Disconnect_Physical_Link_Complete_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Flow_Spec_Modify_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Flow_Spec_Modify_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Flow_Spec_Modify_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Flow_Spec_Modify_Complete_Event:
status2 = ( (pfnPackSizeTlvHCI_Flow_Spec_Modify_Complete_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Flow_Spec_Modify_Complete_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Flush_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Flush_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Flush_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Flush_Occurred_Event:
status2 = ( (pfnPackSizeTlvHCI_Flush_Occurred_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Flush_Occurred_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Generic_AMP_Link_Key_Notification_Event:
status2 = ( (pfnPackSizeTlvHCI_Generic_AMP_Link_Key_Notification_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Generic_AMP_Link_Key_Notification_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Hardware_Error_Event:
status2 = ( (pfnPackSizeTlvHCI_Hardware_Error_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Hardware_Error_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Logical_Link_Cancel_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Logical_Link_Cancel_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Logical_Link_Cancel_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Logical_Link_Complete_Event:
status2 = ( (pfnPackSizeTlvHCI_Logical_Link_Complete_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Logical_Link_Complete_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Loopback_Command_Event:
status2 = ( (pfnPackSizeTlvHCI_Loopback_Command_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Loopback_Command_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Physical_Link_Complete_Event:
status2 = ( (pfnPackSizeTlvHCI_Physical_Link_Complete_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Physical_Link_Complete_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Physical_Link_Loss_Warning_Event:
status2 = ( (pfnPackSizeTlvHCI_Physical_Link_Loss_Warning_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Physical_Link_Loss_Warning_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Physical_Link_Recovery_Event:
status2 = ( (pfnPackSizeTlvHCI_Physical_Link_Recovery_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Physical_Link_Recovery_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Qos_Violation_Event:
status2 = ( (pfnPackSizeTlvHCI_Qos_Violation_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Qos_Violation_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Best_Effort_Flush_Timeout_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_Buffer_Size_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_Buffer_Size_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Buffer_Size_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_Connection_Accept_Timeout_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_Connection_Accept_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Connection_Accept_Timeout_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_Data_Block_Size_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_Data_Block_Size_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Data_Block_Size_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_Failed_Contact_Counter_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_Failed_Contact_Counter_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Failed_Contact_Counter_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_Flow_Control_Mode_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_Flow_Control_Mode_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Flow_Control_Mode_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_Link_Quality_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_Link_Quality_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Link_Quality_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_Link_Supervision_Timeout_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_Link_Supervision_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Link_Supervision_Timeout_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_Local_AMP_Assoc_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_Local_AMP_Assoc_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Local_AMP_Assoc_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_Local_AMP_Information_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_Local_AMP_Information_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Local_AMP_Information_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_Local_Supported_Cmds_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_Local_Supported_Cmds_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Local_Supported_Cmds_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_Local_Version_Info_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_Local_Version_Info_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Local_Version_Info_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_Location_Data_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_Location_Data_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Location_Data_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Logical_Link_Accept_Timeout_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_Loopback_Mode_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_Loopback_Mode_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Loopback_Mode_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Read_RSSI_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Read_RSSI_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_RSSI_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Reset_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Reset_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Reset_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Reset_Failed_Contact_Counter_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Reset_Failed_Contact_Counter_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Reset_Failed_Contact_Counter_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Set_Event_Mask_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Set_Event_Mask_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Set_Event_Mask_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Set_Event_Mask_Page_2_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Set_Event_Mask_Page_2_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Set_Event_Mask_Page_2_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Set_Short_Range_Mode_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Set_Short_Range_Mode_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Set_Short_Range_Mode_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Short_Range_Mode_Change_Complete_Event:
status2 = ( (pfnPackSizeTlvHCI_Short_Range_Mode_Change_Complete_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Short_Range_Mode_Change_Complete_Event* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Best_Effort_Flush_Timeout_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Write_Connection_Accept_Timeout_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Write_Connection_Accept_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Connection_Accept_Timeout_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Write_Flow_Control_Mode_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Write_Flow_Control_Mode_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Flow_Control_Mode_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Write_Link_Supervision_Timeout_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Write_Link_Supervision_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Link_Supervision_Timeout_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Write_Location_Data_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Write_Location_Data_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Location_Data_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Logical_Link_Accept_Timeout_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Write_Loopback_Mode_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Write_Loopback_Mode_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Loopback_Mode_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
case SigPackSizeTlvHCI_Write_Remote_AMP_ASSOC_Cmd:
status2 = ( (pfnPackSizeTlvHCI_Write_Remote_AMP_ASSOC_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Remote_AMP_ASSOC_Cmd* )(pFrm + pTlv->offset), pnNeeded);
if (status2) status |= status2;
break;
default:
FRAMES_LOG1(pCtx, FRLOGE, FRFL("INTERNAL ERROR-- I don"
"'t know about the TLV signature %d; this is most l"
"ikely a bug in 'framesc'.\n"), pTlv->sig);
return BTAMP_INTERNAL_ERROR;
}
}
++pTlv;
}
return status;
}
v_U32_t btampPackTlvAMP_Assoc_Connected_Channel(void * pCtx,
tBtampTLVAMP_Assoc_Connected_Channel *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 2;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"In btampPackTlvAMP_Assoc_Connected_Channel\n");
#endif
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvAMP_Assoc_Connected_Channel(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3, 0);
else *pBuf = 3;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->country, 3);
*pnConsumed += 3;
pBuf += 3;
nBuf -= 3;
if ( pSrc->num_triplets ) {
BTAMP_MEMCPY(pCtx, pBuf, &( pSrc->triplets ), ( pSrc->num_triplets * 3 ));
*pnConsumed += ( pSrc->num_triplets * 3 );
pBuf += ( ( pSrc->num_triplets * 3 ) );
nBuf -= ( ( pSrc->num_triplets * 3 ) );
}
else break;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
}
else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvAMP_Assoc_Connected_Channel. */
typedef v_U32_t (*pfnPackTlvAMP_Assoc_Connected_Channel_t)(void *, tBtampTLVAMP_Assoc_Connected_Channel *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvAMP_Assoc_Connected_Channel ( 0x007b )
v_U32_t btampPackTlvAMP_Assoc_MAC_Addr(void * pCtx,
tBtampTLVAMP_Assoc_MAC_Addr *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 2;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"In btampPackTlvAMP_Assoc_MAC_Addr\n");
#endif
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvAMP_Assoc_MAC_Addr(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 1, 0);
else *pBuf = 1;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->mac_addr, 6);
*pnConsumed += 6;
pBuf += 6;
nBuf -= 6;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvAMP_Assoc_MAC_Addr. */
typedef v_U32_t (*pfnPackTlvAMP_Assoc_MAC_Addr_t)(void *, tBtampTLVAMP_Assoc_MAC_Addr *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvAMP_Assoc_MAC_Addr ( 0x007c )
v_U32_t btampPackTlvAMP_Assoc_PAL_Capabilities(void * pCtx,
tBtampTLVAMP_Assoc_PAL_Capabilities *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 2;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"In btampPackTlvAMP_Assoc_PAL_Capabilities\n");
#endif
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvAMP_Assoc_PAL_Capabilities(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 4, 0);
else *pBuf = 4;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtonl(pCtx, pBuf, pSrc->pal_capabilities, 0);
*pnConsumed += 4;
pBuf += 4;
nBuf -= 4;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvAMP_Assoc_PAL_Capabilities. */
typedef v_U32_t (*pfnPackTlvAMP_Assoc_PAL_Capabilities_t)(void *, tBtampTLVAMP_Assoc_PAL_Capabilities *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvAMP_Assoc_PAL_Capabilities ( 0x007d )
v_U32_t btampPackTlvAMP_Assoc_PAL_Version(void * pCtx,
tBtampTLVAMP_Assoc_PAL_Version *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 2;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"In btampPackTlvAMP_Assoc_PAL_Version\n");
#endif
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvAMP_Assoc_PAL_Version(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 5, 0);
else *pBuf = 5;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->pal_version;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->pal_CompanyID, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, pSrc->pal_subversion, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvAMP_Assoc_PAL_Version. */
typedef v_U32_t (*pfnPackTlvAMP_Assoc_PAL_Version_t)(void *, tBtampTLVAMP_Assoc_PAL_Version *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvAMP_Assoc_PAL_Version ( 0x007e )
v_U32_t btampPackTlvAMP_Assoc_Preferred_Channel_List(void * pCtx,
tBtampTLVAMP_Assoc_Preferred_Channel_List *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 2;
#ifdef WLAN_BAPHCI_ENABLE_LOGGING
VOS_TRACE(VOS_MODULE_ID_BAP,VOS_TRACE_LEVEL_ERROR,
"In btampPackTlvAMP_Assoc_Preferred_Channel_List\n");
#endif
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvAMP_Assoc_Preferred_Channel_List(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 2, 0);
else *pBuf = 2;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->country, 3);
*pnConsumed += 3;
pBuf += 3;
nBuf -= 3;
if ( pSrc->num_triplets ) {
BTAMP_MEMCPY(pCtx, pBuf, &( pSrc->triplets ), ( pSrc->num_triplets * 3 ));
*pnConsumed += ( pSrc->num_triplets * 3 );
pBuf += ( ( pSrc->num_triplets * 3 ) );
nBuf -= ( ( pSrc->num_triplets * 3 ) );
}
else break;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvAMP_Assoc_Preferred_Channel_List. */
typedef v_U32_t (*pfnPackTlvAMP_Assoc_Preferred_Channel_List_t)(void *, tBtampTLVAMP_Assoc_Preferred_Channel_List *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvAMP_Assoc_Preferred_Channel_List ( 0x007f )
v_U32_t btampPackTlvFlow_Spec(void * pCtx,
tBtampTLVFlow_Spec *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvFlow_Spec(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 6, 0);
else *pBuf = 6;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->flow_spec_id;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->service_type;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->max_sdu, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtonl(pCtx, pBuf, pSrc->sdu_inter_arrival, 0);
*pnConsumed += 4;
pBuf += 4;
nBuf -= 4;
frameshtonl(pCtx, pBuf, pSrc->access_latency, 0);
*pnConsumed += 4;
pBuf += 4;
nBuf -= 4;
frameshtonl(pCtx, pBuf, pSrc->flush_timeout, 0);
*pnConsumed += 4;
pBuf += 4;
nBuf -= 4;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvFlow_Spec. */
typedef v_U32_t (*pfnPackTlvFlow_Spec_t)(void *, tBtampTLVFlow_Spec *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvFlow_Spec ( 0x0080 )
v_U32_t btampPackTlvHCI_Accept_Logical_Link_Cmd(void * pCtx,
tBtampTLVHCI_Accept_Logical_Link_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Accept_Logical_Link_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 1081, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->tx_flow_spec, 18);
*pnConsumed += 18;
pBuf += 18;
nBuf -= 18;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->rx_flow_spec, 18);
*pnConsumed += 18;
pBuf += 18;
nBuf -= 18;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Accept_Logical_Link_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Accept_Logical_Link_Cmd_t)(void *, tBtampTLVHCI_Accept_Logical_Link_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Accept_Logical_Link_Cmd ( 0x0081 )
v_U32_t btampPackTlvHCI_Accept_Physical_Link_Cmd(void * pCtx,
tBtampTLVHCI_Accept_Physical_Link_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Accept_Physical_Link_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 1078, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->key_length;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->key_type;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
BTAMP_MEMCPY(pCtx, pBuf, &( pSrc->key_material ), pSrc->key_length);
*pnConsumed += pSrc->key_length;
pBuf += ( pSrc->key_length );
nBuf -= ( pSrc->key_length );
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Accept_Physical_Link_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Accept_Physical_Link_Cmd_t)(void *, tBtampTLVHCI_Accept_Physical_Link_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Accept_Physical_Link_Cmd ( 0x0082 )
v_U32_t btampPackTlvHCI_Channel_Selected_Event(void * pCtx,
tBtampTLVHCI_Channel_Selected_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Channel_Selected_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 65, 0);
else *pBuf = 65;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Channel_Selected_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Channel_Selected_Event_t)(void *, tBtampTLVHCI_Channel_Selected_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Channel_Selected_Event ( 0x0083 )
v_U32_t btampPackTlvHCI_Command_Complete_Event(void * pCtx,
tBtampTLVHCI_Command_Complete_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Command_Complete_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 14, 0);
else *pBuf = 14;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->num_hci_command_packets;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->command_opcode, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
switch (pSrc->command_opcode)
{
case 3075:
*pBuf = pSrc->cc_event.Reset.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 3080:
*pBuf = pSrc->cc_event.Flush.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->cc_event.Flush.log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
case 1083:
*pBuf = pSrc->cc_event.Logical_Link_Cancel.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->cc_event.Logical_Link_Cancel.phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->cc_event.Logical_Link_Cancel.tx_flow_spec_id;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 3077:
*pBuf = pSrc->cc_event.Set_Event_Mask.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 3093:
*pBuf = pSrc->cc_event.Read_Connection_Accept_TO.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Connection_Accept_TO.connection_accept_timeout, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
case 3094:
*pBuf = pSrc->cc_event.Write_Connection_Accept_TO.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 3126:
*pBuf = pSrc->cc_event.Read_Link_Supervision_TO.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Link_Supervision_TO.log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Link_Supervision_TO.link_supervision_timeout, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
case 3127:
*pBuf = pSrc->cc_event.Write_Link_Supervision_TO.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->cc_event.Write_Link_Supervision_TO.log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
case 3169:
*pBuf = pSrc->cc_event.Read_Logical_Link_Accept_TO.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Logical_Link_Accept_TO.logical_link_accept_timeout, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
case 3170:
*pBuf = pSrc->cc_event.Write_Logical_Link_Accept_TO.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 3171:
*pBuf = pSrc->cc_event.Set_Event_Mask_Page_2.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 3172:
*pBuf = pSrc->cc_event.Read_Location_Data.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->cc_event.Read_Location_Data.loc_domain_aware;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->cc_event.Read_Location_Data.loc_domain, 3);
*pnConsumed += 3;
pBuf += 3;
nBuf -= 3;
*pBuf = pSrc->cc_event.Read_Location_Data.loc_options;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 3173:
*pBuf = pSrc->cc_event.Write_Location_Data.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 3174:
*pBuf = pSrc->cc_event.Read_Flow_Control_Mode.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->cc_event.Read_Flow_Control_Mode.flow_control_mode;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 3175:
*pBuf = pSrc->cc_event.Write_Flow_Control_Mode.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 3177:
*pBuf = pSrc->cc_event.Read_BE_Flush_TO.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtonl(pCtx, pBuf, pSrc->cc_event.Read_BE_Flush_TO.best_effort_flush_timeout, 0);
*pnConsumed += 4;
pBuf += 4;
nBuf -= 4;
break;
case 3178:
*pBuf = pSrc->cc_event.Write_BE_Flush_TO.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 3179:
*pBuf = pSrc->cc_event.Set_Short_Range_Mode.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 4097:
*pBuf = pSrc->cc_event.Read_Local_Version_Info.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->cc_event.Read_Local_Version_Info.HC_HCI_Version;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Local_Version_Info.HC_HCI_Revision, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
*pBuf = pSrc->cc_event.Read_Local_Version_Info.HC_PAL_Version;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Local_Version_Info.HC_Manufac_Name, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Local_Version_Info.HC_PAL_Sub_Version, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
case 4098:
*pBuf = pSrc->cc_event.Read_Local_Supported_Cmds.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->cc_event.Read_Local_Supported_Cmds.HC_Support_Cmds, 64);
*pnConsumed += 64;
pBuf += 64;
nBuf -= 64;
break;
case 4101:
*pBuf = pSrc->cc_event.Read_Buffer_Size.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Buffer_Size.HC_ACL_Data_Packet_Length, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
*pBuf = pSrc->cc_event.Read_Buffer_Size.HC_SCO_Packet_Length;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Buffer_Size.HC_Total_Num_ACL_Packets, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Buffer_Size.HC_Total_Num_SCO_Packets, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
case 4106:
*pBuf = pSrc->cc_event.Read_Data_Block_Size.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Data_Block_Size.HC_Max_ACL_Data_Packet_Length, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Data_Block_Size.HC_Data_Block_Length, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Data_Block_Size.HC_Total_Num_Data_Blocks, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
case 5121:
*pBuf = pSrc->cc_event.Read_Failed_Contact_Counter.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Failed_Contact_Counter.log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Failed_Contact_Counter.failed_contact_counter, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
case 5122:
*pBuf = pSrc->cc_event.Reset_Failed_Contact_Counter.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->cc_event.Reset_Failed_Contact_Counter.log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
case 5123:
*pBuf = pSrc->cc_event.Read_Link_Quality.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Link_Quality.log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
*pBuf = pSrc->cc_event.Read_Link_Quality.link_quality;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 5125:
*pBuf = pSrc->cc_event.Read_RSSI.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->cc_event.Read_RSSI.phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->cc_event.Read_RSSI.rssi;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 5129:
*pBuf = pSrc->cc_event.Read_Local_AMP_Info.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->cc_event.Read_Local_AMP_Info.HC_AMP_Status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtonl(pCtx, pBuf, pSrc->cc_event.Read_Local_AMP_Info.HC_Total_BW, 0);
*pnConsumed += 4;
pBuf += 4;
nBuf -= 4;
frameshtonl(pCtx, pBuf, pSrc->cc_event.Read_Local_AMP_Info.HC_Max_Guaranteed_BW, 0);
*pnConsumed += 4;
pBuf += 4;
nBuf -= 4;
frameshtonl(pCtx, pBuf, pSrc->cc_event.Read_Local_AMP_Info.HC_Min_Latency, 0);
*pnConsumed += 4;
pBuf += 4;
nBuf -= 4;
frameshtonl(pCtx, pBuf, pSrc->cc_event.Read_Local_AMP_Info.HC_Max_PDU_Size, 0);
*pnConsumed += 4;
pBuf += 4;
nBuf -= 4;
*pBuf = pSrc->cc_event.Read_Local_AMP_Info.HC_Controller_Type;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Local_AMP_Info.HC_PAL_Capabilities, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Local_AMP_Info.HC_AMP_Assoc_Length, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtonl(pCtx, pBuf, pSrc->cc_event.Read_Local_AMP_Info.HC_Max_Flush_Timeout, 0);
*pnConsumed += 4;
pBuf += 4;
nBuf -= 4;
frameshtonl(pCtx, pBuf, pSrc->cc_event.Read_Local_AMP_Info.HC_BE_Flush_Timeout, 0);
*pnConsumed += 4;
pBuf += 4;
nBuf -= 4;
break;
case 5130:
*pBuf = pSrc->cc_event.Read_Read_Local_AMP_Assoc.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->cc_event.Read_Read_Local_AMP_Assoc.phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->cc_event.Read_Read_Local_AMP_Assoc.remaining_length, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
BTAMP_MEMCPY(pCtx, pBuf, &( pSrc->cc_event.Read_Read_Local_AMP_Assoc.AMP_assoc_fragment ), pSrc->cc_event.Read_Read_Local_AMP_Assoc.remaining_length);
*pnConsumed += pSrc->cc_event.Read_Read_Local_AMP_Assoc.remaining_length;
pBuf += ( pSrc->cc_event.Read_Read_Local_AMP_Assoc.remaining_length );
nBuf -= ( pSrc->cc_event.Read_Read_Local_AMP_Assoc.remaining_length );
break;
case 5131:
*pBuf = pSrc->cc_event.Write_Remote_AMP_Assoc.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->cc_event.Write_Remote_AMP_Assoc.phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 6145:
*pBuf = pSrc->cc_event.Read_Loopback_Mode.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->cc_event.Read_Loopback_Mode.loopback_mode;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
case 6146:
*pBuf = pSrc->cc_event.Write_Loopback_Mode.status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Command_Complete_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Command_Complete_Event_t)(void *, tBtampTLVHCI_Command_Complete_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Command_Complete_Event ( 0x0084 )
v_U32_t btampPackTlvHCI_Command_Status_Event(void * pCtx,
tBtampTLVHCI_Command_Status_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Command_Status_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 15, 0);
else *pBuf = 15;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->num_hci_command_packets;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->command_opcode, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Command_Status_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Command_Status_Event_t)(void *, tBtampTLVHCI_Command_Status_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Command_Status_Event ( 0x0085 )
v_U32_t btampPackTlvHCI_Create_Logical_Link_Cmd(void * pCtx,
tBtampTLVHCI_Create_Logical_Link_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Create_Logical_Link_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 1080, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->tx_flow_spec, 18);
*pnConsumed += 18;
pBuf += 18;
nBuf -= 18;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->rx_flow_spec, 18);
*pnConsumed += 18;
pBuf += 18;
nBuf -= 18;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Create_Logical_Link_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Create_Logical_Link_Cmd_t)(void *, tBtampTLVHCI_Create_Logical_Link_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Create_Logical_Link_Cmd ( 0x0086 )
v_U32_t btampPackTlvHCI_Create_Physical_Link_Cmd(void * pCtx,
tBtampTLVHCI_Create_Physical_Link_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Create_Physical_Link_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 1077, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->key_length;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->key_type;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
BTAMP_MEMCPY(pCtx, pBuf, &( pSrc->key_material ), pSrc->key_length);
*pnConsumed += pSrc->key_length;
pBuf += ( pSrc->key_length );
nBuf -= ( pSrc->key_length );
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Create_Physical_Link_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Create_Physical_Link_Cmd_t)(void *, tBtampTLVHCI_Create_Physical_Link_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Create_Physical_Link_Cmd ( 0x0087 )
v_U32_t btampPackTlvHCI_Data_Buffer_Overflow_Event(void * pCtx,
tBtampTLVHCI_Data_Buffer_Overflow_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Data_Buffer_Overflow_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 26, 0);
else *pBuf = 26;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->link_type;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Data_Buffer_Overflow_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Data_Buffer_Overflow_Event_t)(void *, tBtampTLVHCI_Data_Buffer_Overflow_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Data_Buffer_Overflow_Event ( 0x0088 )
v_U32_t btampPackTlvHCI_Disconnect_Logical_Link_Cmd(void * pCtx,
tBtampTLVHCI_Disconnect_Logical_Link_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Disconnect_Logical_Link_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 1082, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Disconnect_Logical_Link_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Disconnect_Logical_Link_Cmd_t)(void *, tBtampTLVHCI_Disconnect_Logical_Link_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Disconnect_Logical_Link_Cmd ( 0x0089 )
v_U32_t btampPackTlvHCI_Disconnect_Logical_Link_Complete_Event(void * pCtx,
tBtampTLVHCI_Disconnect_Logical_Link_Complete_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Disconnect_Logical_Link_Complete_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 70, 0);
else *pBuf = 70;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
*pBuf = pSrc->reason;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Disconnect_Logical_Link_Complete_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Disconnect_Logical_Link_Complete_Event_t)(void *, tBtampTLVHCI_Disconnect_Logical_Link_Complete_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Disconnect_Logical_Link_Complete_Event ( 0x008a )
v_U32_t btampPackTlvHCI_Disconnect_Physical_Link_Cmd(void * pCtx,
tBtampTLVHCI_Disconnect_Physical_Link_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Disconnect_Physical_Link_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 1079, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->reason;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Disconnect_Physical_Link_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Disconnect_Physical_Link_Cmd_t)(void *, tBtampTLVHCI_Disconnect_Physical_Link_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Disconnect_Physical_Link_Cmd ( 0x008b )
v_U32_t btampPackTlvHCI_Disconnect_Physical_Link_Complete_Event(void * pCtx,
tBtampTLVHCI_Disconnect_Physical_Link_Complete_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Disconnect_Physical_Link_Complete_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 66, 0);
else *pBuf = 66;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->reason;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Disconnect_Physical_Link_Complete_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Disconnect_Physical_Link_Complete_Event_t)(void *, tBtampTLVHCI_Disconnect_Physical_Link_Complete_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Disconnect_Physical_Link_Complete_Event ( 0x008c )
v_U32_t btampPackTlvHCI_Flow_Spec_Modify_Cmd(void * pCtx,
tBtampTLVHCI_Flow_Spec_Modify_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Flow_Spec_Modify_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 1084, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
*pBuf = pSrc->be_aggr_counter;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->tx_flow_spec, 18);
*pnConsumed += 18;
pBuf += 18;
nBuf -= 18;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->rx_flow_spec, 18);
*pnConsumed += 18;
pBuf += 18;
nBuf -= 18;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Flow_Spec_Modify_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Flow_Spec_Modify_Cmd_t)(void *, tBtampTLVHCI_Flow_Spec_Modify_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Flow_Spec_Modify_Cmd ( 0x008d )
v_U32_t btampPackTlvHCI_Flow_Spec_Modify_Complete_Event(void * pCtx,
tBtampTLVHCI_Flow_Spec_Modify_Complete_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Flow_Spec_Modify_Complete_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 71, 0);
else *pBuf = 71;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Flow_Spec_Modify_Complete_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Flow_Spec_Modify_Complete_Event_t)(void *, tBtampTLVHCI_Flow_Spec_Modify_Complete_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Flow_Spec_Modify_Complete_Event ( 0x008e )
v_U32_t btampPackTlvHCI_Flush_Cmd(void * pCtx,
tBtampTLVHCI_Flush_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Flush_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3080, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Flush_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Flush_Cmd_t)(void *, tBtampTLVHCI_Flush_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Flush_Cmd ( 0x008f )
v_U32_t btampPackTlvHCI_Flush_Occurred_Event(void * pCtx,
tBtampTLVHCI_Flush_Occurred_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Flush_Occurred_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 17, 0);
else *pBuf = 17;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Flush_Occurred_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Flush_Occurred_Event_t)(void *, tBtampTLVHCI_Flush_Occurred_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Flush_Occurred_Event ( 0x0090 )
v_U32_t btampPackTlvHCI_Num_Completed_Pkts_Event(void * pCtx,
tBtampTLVHCI_Num_Completed_Pkts_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Num_Completed_Pkts_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
// while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 19, 0);
else *pBuf = 19;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->num_handles;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->conn_handles[0], 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, pSrc->num_completed_pkts[0], 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
#if 0
// New
frameshtons(pCtx, pBuf, 0, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, 0, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, 0, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, 0, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, 0, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, 0, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
// End of new
#endif
// break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Num_Completed_Pkts_Event. */
v_U32_t btampPackTlvHCI_Num_Completed_Data_Blocks_Event(void * pCtx,
tBtampTLVHCI_Num_Completed_Data_Blocks_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Num_Completed_Data_Blocks_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
// while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 72, 0);
else *pBuf = 72;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->total_num_data_blocks, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
*pBuf = pSrc->num_handles;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->conn_handles[0], 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, pSrc->num_completed_pkts[0], 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, pSrc->num_completed_blocks[0], 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
#if 0
// New
frameshtons(pCtx, pBuf, 0, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, 0, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, 0, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, 0, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, 0, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, 0, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
// End of new
#endif
// break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Num_Completed_Data_Blocks_Event. */
//typedef v_U32_t (*pfnPackTlvHCI_Num_Completed_Pkts_Event_t)(void *, tBtampTLVHCI_Num_Completed_Pkts_Event *, v_U8_t*, v_U32_t, v_U32_t*);
//#define SigPackTlvHCI_Num_Completed_Pkts_Event ( 0x0085 )
v_U32_t btampPackTlvHCI_Generic_AMP_Link_Key_Notification_Event(void * pCtx,
tBtampTLVHCI_Generic_AMP_Link_Key_Notification_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Generic_AMP_Link_Key_Notification_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 62, 0);
else *pBuf = 62;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->bd_addr, 6);
*pnConsumed += 6;
pBuf += 6;
nBuf -= 6;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->generic_amp_link_key, 32);
*pnConsumed += 32;
pBuf += 32;
nBuf -= 32;
*pBuf = pSrc->key_type;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Generic_AMP_Link_Key_Notification_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Generic_AMP_Link_Key_Notification_Event_t)(void *, tBtampTLVHCI_Generic_AMP_Link_Key_Notification_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Generic_AMP_Link_Key_Notification_Event ( 0x0091 )
v_U32_t btampPackTlvHCI_Hardware_Error_Event(void * pCtx,
tBtampTLVHCI_Hardware_Error_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Hardware_Error_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 16, 0);
else *pBuf = 16;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->hardware_code;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Hardware_Error_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Hardware_Error_Event_t)(void *, tBtampTLVHCI_Hardware_Error_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Hardware_Error_Event ( 0x0092 )
v_U32_t btampPackTlvHCI_Logical_Link_Cancel_Cmd(void * pCtx,
tBtampTLVHCI_Logical_Link_Cancel_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Logical_Link_Cancel_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 1083, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->tx_flow_spec_id;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Logical_Link_Cancel_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Logical_Link_Cancel_Cmd_t)(void *, tBtampTLVHCI_Logical_Link_Cancel_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Logical_Link_Cancel_Cmd ( 0x0093 )
v_U32_t btampPackTlvHCI_Logical_Link_Complete_Event(void * pCtx,
tBtampTLVHCI_Logical_Link_Complete_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Logical_Link_Complete_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 69, 0);
else *pBuf = 69;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->flow_spec_id;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Logical_Link_Complete_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Logical_Link_Complete_Event_t)(void *, tBtampTLVHCI_Logical_Link_Complete_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Logical_Link_Complete_Event ( 0x0094 )
v_U32_t btampPackTlvHCI_Loopback_Command_Event(void * pCtx,
tBtampTLVHCI_Loopback_Command_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Loopback_Command_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 25, 0);
else *pBuf = 25;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->hci_command_packet, 64);
*pnConsumed += 64;
pBuf += 64;
nBuf -= 64;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Loopback_Command_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Loopback_Command_Event_t)(void *, tBtampTLVHCI_Loopback_Command_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Loopback_Command_Event ( 0x0095 )
v_U32_t btampPackTlvHCI_Physical_Link_Complete_Event(void * pCtx,
tBtampTLVHCI_Physical_Link_Complete_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Physical_Link_Complete_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 64, 0);
else *pBuf = 64;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Physical_Link_Complete_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Physical_Link_Complete_Event_t)(void *, tBtampTLVHCI_Physical_Link_Complete_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Physical_Link_Complete_Event ( 0x0096 )
v_U32_t btampPackTlvHCI_Physical_Link_Loss_Warning_Event(void * pCtx,
tBtampTLVHCI_Physical_Link_Loss_Warning_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Physical_Link_Loss_Warning_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 67, 0);
else *pBuf = 67;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->reason;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Physical_Link_Loss_Warning_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Physical_Link_Loss_Warning_Event_t)(void *, tBtampTLVHCI_Physical_Link_Loss_Warning_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Physical_Link_Loss_Warning_Event ( 0x0097 )
v_U32_t btampPackTlvHCI_Physical_Link_Recovery_Event(void * pCtx,
tBtampTLVHCI_Physical_Link_Recovery_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Physical_Link_Recovery_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 68, 0);
else *pBuf = 68;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Physical_Link_Recovery_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Physical_Link_Recovery_Event_t)(void *, tBtampTLVHCI_Physical_Link_Recovery_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Physical_Link_Recovery_Event ( 0x0098 )
v_U32_t btampPackTlvHCI_Qos_Violation_Event(void * pCtx,
tBtampTLVHCI_Qos_Violation_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Qos_Violation_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 30, 0);
else *pBuf = 30;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Qos_Violation_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Qos_Violation_Event_t)(void *, tBtampTLVHCI_Qos_Violation_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Qos_Violation_Event ( 0x0099 )
v_U32_t btampPackTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd(void * pCtx,
tBtampTLVHCI_Read_Best_Effort_Flush_Timeout_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3177, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd_t)(void *, tBtampTLVHCI_Read_Best_Effort_Flush_Timeout_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd ( 0x009a )
v_U32_t btampPackTlvHCI_Read_Buffer_Size_Cmd(void * pCtx,
tBtampTLVHCI_Read_Buffer_Size_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_Buffer_Size_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 4101, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_Buffer_Size_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_Buffer_Size_Cmd_t)(void *, tBtampTLVHCI_Read_Buffer_Size_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_Buffer_Size_Cmd ( 0x009b )
v_U32_t btampPackTlvHCI_Read_Connection_Accept_Timeout_Cmd(void * pCtx,
tBtampTLVHCI_Read_Connection_Accept_Timeout_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_Connection_Accept_Timeout_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3093, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_Connection_Accept_Timeout_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_Connection_Accept_Timeout_Cmd_t)(void *, tBtampTLVHCI_Read_Connection_Accept_Timeout_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_Connection_Accept_Timeout_Cmd ( 0x009c )
v_U32_t btampPackTlvHCI_Read_Data_Block_Size_Cmd(void * pCtx,
tBtampTLVHCI_Read_Data_Block_Size_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_Data_Block_Size_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 4106, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_Data_Block_Size_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_Data_Block_Size_Cmd_t)(void *, tBtampTLVHCI_Read_Data_Block_Size_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_Data_Block_Size_Cmd ( 0x009d )
v_U32_t btampPackTlvHCI_Read_Failed_Contact_Counter_Cmd(void * pCtx,
tBtampTLVHCI_Read_Failed_Contact_Counter_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_Failed_Contact_Counter_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 5121, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_Failed_Contact_Counter_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_Failed_Contact_Counter_Cmd_t)(void *, tBtampTLVHCI_Read_Failed_Contact_Counter_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_Failed_Contact_Counter_Cmd ( 0x009e )
v_U32_t btampPackTlvHCI_Read_Flow_Control_Mode_Cmd(void * pCtx,
tBtampTLVHCI_Read_Flow_Control_Mode_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_Flow_Control_Mode_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3174, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_Flow_Control_Mode_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_Flow_Control_Mode_Cmd_t)(void *, tBtampTLVHCI_Read_Flow_Control_Mode_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_Flow_Control_Mode_Cmd ( 0x009f )
v_U32_t btampPackTlvHCI_Read_Link_Quality_Cmd(void * pCtx,
tBtampTLVHCI_Read_Link_Quality_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_Link_Quality_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 5123, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_Link_Quality_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_Link_Quality_Cmd_t)(void *, tBtampTLVHCI_Read_Link_Quality_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_Link_Quality_Cmd ( 0x00a0 )
v_U32_t btampPackTlvHCI_Read_Link_Supervision_Timeout_Cmd(void * pCtx,
tBtampTLVHCI_Read_Link_Supervision_Timeout_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_Link_Supervision_Timeout_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3126, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_Link_Supervision_Timeout_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_Link_Supervision_Timeout_Cmd_t)(void *, tBtampTLVHCI_Read_Link_Supervision_Timeout_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_Link_Supervision_Timeout_Cmd ( 0x00a1 )
v_U32_t btampPackTlvHCI_Read_Local_AMP_Assoc_Cmd(void * pCtx,
tBtampTLVHCI_Read_Local_AMP_Assoc_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_Local_AMP_Assoc_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 5130, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->length_so_far, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, pSrc->max_remote_amp_assoc_length, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_Local_AMP_Assoc_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_Local_AMP_Assoc_Cmd_t)(void *, tBtampTLVHCI_Read_Local_AMP_Assoc_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_Local_AMP_Assoc_Cmd ( 0x00a2 )
v_U32_t btampPackTlvHCI_Read_Local_AMP_Information_Cmd(void * pCtx,
tBtampTLVHCI_Read_Local_AMP_Information_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_Local_AMP_Information_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 5129, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_Local_AMP_Information_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_Local_AMP_Information_Cmd_t)(void *, tBtampTLVHCI_Read_Local_AMP_Information_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_Local_AMP_Information_Cmd ( 0x00a3 )
v_U32_t btampPackTlvHCI_Read_Local_Supported_Cmds_Cmd(void * pCtx,
tBtampTLVHCI_Read_Local_Supported_Cmds_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_Local_Supported_Cmds_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 4098, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_Local_Supported_Cmds_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_Local_Supported_Cmds_Cmd_t)(void *, tBtampTLVHCI_Read_Local_Supported_Cmds_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_Local_Supported_Cmds_Cmd ( 0x00a4 )
v_U32_t btampPackTlvHCI_Read_Local_Version_Info_Cmd(void * pCtx,
tBtampTLVHCI_Read_Local_Version_Info_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_Local_Version_Info_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 4097, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_Local_Version_Info_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_Local_Version_Info_Cmd_t)(void *, tBtampTLVHCI_Read_Local_Version_Info_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_Local_Version_Info_Cmd ( 0x00a5 )
v_U32_t btampPackTlvHCI_Read_Location_Data_Cmd(void * pCtx,
tBtampTLVHCI_Read_Location_Data_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_Location_Data_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3172, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_Location_Data_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_Location_Data_Cmd_t)(void *, tBtampTLVHCI_Read_Location_Data_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_Location_Data_Cmd ( 0x00a6 )
v_U32_t btampPackTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd(void * pCtx,
tBtampTLVHCI_Read_Logical_Link_Accept_Timeout_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3169, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd_t)(void *, tBtampTLVHCI_Read_Logical_Link_Accept_Timeout_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd ( 0x00a7 )
v_U32_t btampPackTlvHCI_Read_Loopback_Mode_Cmd(void * pCtx,
tBtampTLVHCI_Read_Loopback_Mode_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_Loopback_Mode_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 6145, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_Loopback_Mode_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_Loopback_Mode_Cmd_t)(void *, tBtampTLVHCI_Read_Loopback_Mode_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_Loopback_Mode_Cmd ( 0x00a8 )
v_U32_t btampPackTlvHCI_Read_RSSI_Cmd(void * pCtx,
tBtampTLVHCI_Read_RSSI_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Read_RSSI_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 5125, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Read_RSSI_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Read_RSSI_Cmd_t)(void *, tBtampTLVHCI_Read_RSSI_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Read_RSSI_Cmd ( 0x00a9 )
v_U32_t btampPackTlvHCI_Reset_Cmd(void * pCtx,
tBtampTLVHCI_Reset_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Reset_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3075, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Reset_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Reset_Cmd_t)(void *, tBtampTLVHCI_Reset_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Reset_Cmd ( 0x00aa )
v_U32_t btampPackTlvHCI_Reset_Failed_Contact_Counter_Cmd(void * pCtx,
tBtampTLVHCI_Reset_Failed_Contact_Counter_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Reset_Failed_Contact_Counter_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 5122, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Reset_Failed_Contact_Counter_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Reset_Failed_Contact_Counter_Cmd_t)(void *, tBtampTLVHCI_Reset_Failed_Contact_Counter_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Reset_Failed_Contact_Counter_Cmd ( 0x00ab )
v_U32_t btampPackTlvHCI_Set_Event_Mask_Cmd(void * pCtx,
tBtampTLVHCI_Set_Event_Mask_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Set_Event_Mask_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3077, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->event_mask, 8);
*pnConsumed += 8;
pBuf += 8;
nBuf -= 8;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Set_Event_Mask_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Set_Event_Mask_Cmd_t)(void *, tBtampTLVHCI_Set_Event_Mask_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Set_Event_Mask_Cmd ( 0x00ac )
v_U32_t btampPackTlvHCI_Set_Event_Mask_Page_2_Cmd(void * pCtx,
tBtampTLVHCI_Set_Event_Mask_Page_2_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Set_Event_Mask_Page_2_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3171, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->event_mask_page_2, 8);
*pnConsumed += 8;
pBuf += 8;
nBuf -= 8;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Set_Event_Mask_Page_2_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Set_Event_Mask_Page_2_Cmd_t)(void *, tBtampTLVHCI_Set_Event_Mask_Page_2_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Set_Event_Mask_Page_2_Cmd ( 0x00ad )
v_U32_t btampPackTlvHCI_Set_Short_Range_Mode_Cmd(void * pCtx,
tBtampTLVHCI_Set_Short_Range_Mode_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Set_Short_Range_Mode_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3179, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->short_range_mode;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Set_Short_Range_Mode_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Set_Short_Range_Mode_Cmd_t)(void *, tBtampTLVHCI_Set_Short_Range_Mode_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Set_Short_Range_Mode_Cmd ( 0x00ae )
v_U32_t btampPackTlvHCI_Short_Range_Mode_Change_Complete_Event(void * pCtx,
tBtampTLVHCI_Short_Range_Mode_Change_Complete_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Short_Range_Mode_Change_Complete_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 76, 0);
else *pBuf = 76;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->status;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
*pBuf = pSrc->short_range_mode;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Short_Range_Mode_Change_Complete_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Short_Range_Mode_Change_Complete_Event_t)(void *, tBtampTLVHCI_Short_Range_Mode_Change_Complete_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Short_Range_Mode_Change_Complete_Event ( 0x00af )
v_U32_t btampPackTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd(void * pCtx,
tBtampTLVHCI_Write_Best_Effort_Flush_Timeout_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3178, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtonl(pCtx, pBuf, pSrc->best_effort_flush_timeout, 0);
*pnConsumed += 4;
pBuf += 4;
nBuf -= 4;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd_t)(void *, tBtampTLVHCI_Write_Best_Effort_Flush_Timeout_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd ( 0x00b0 )
v_U32_t btampPackTlvHCI_Write_Connection_Accept_Timeout_Cmd(void * pCtx,
tBtampTLVHCI_Write_Connection_Accept_Timeout_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Write_Connection_Accept_Timeout_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3094, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->connection_accept_timeout, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Write_Connection_Accept_Timeout_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Write_Connection_Accept_Timeout_Cmd_t)(void *, tBtampTLVHCI_Write_Connection_Accept_Timeout_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Write_Connection_Accept_Timeout_Cmd ( 0x00b1 )
v_U32_t btampPackTlvHCI_Write_Flow_Control_Mode_Cmd(void * pCtx,
tBtampTLVHCI_Write_Flow_Control_Mode_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Write_Flow_Control_Mode_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3175, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->flow_control_mode;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Write_Flow_Control_Mode_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Write_Flow_Control_Mode_Cmd_t)(void *, tBtampTLVHCI_Write_Flow_Control_Mode_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Write_Flow_Control_Mode_Cmd ( 0x00b2 )
v_U32_t btampPackTlvHCI_Write_Link_Supervision_Timeout_Cmd(void * pCtx,
tBtampTLVHCI_Write_Link_Supervision_Timeout_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Write_Link_Supervision_Timeout_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3127, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, pSrc->link_supervision_timeout, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Write_Link_Supervision_Timeout_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Write_Link_Supervision_Timeout_Cmd_t)(void *, tBtampTLVHCI_Write_Link_Supervision_Timeout_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Write_Link_Supervision_Timeout_Cmd ( 0x00b3 )
v_U32_t btampPackTlvHCI_Write_Location_Data_Cmd(void * pCtx,
tBtampTLVHCI_Write_Location_Data_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Write_Location_Data_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3173, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->loc_domain_aware;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
BTAMP_MEMCPY(pCtx, pBuf, pSrc->loc_domain, 3);
*pnConsumed += 3;
pBuf += 3;
nBuf -= 3;
*pBuf = pSrc->loc_options;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Write_Location_Data_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Write_Location_Data_Cmd_t)(void *, tBtampTLVHCI_Write_Location_Data_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Write_Location_Data_Cmd ( 0x00b4 )
v_U32_t btampPackTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd(void * pCtx,
tBtampTLVHCI_Write_Logical_Link_Accept_Timeout_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3170, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->logical_link_accept_timeout, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd_t)(void *, tBtampTLVHCI_Write_Logical_Link_Accept_Timeout_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd ( 0x00b5 )
v_U32_t btampPackTlvHCI_Write_Loopback_Mode_Cmd(void * pCtx,
tBtampTLVHCI_Write_Loopback_Mode_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Write_Loopback_Mode_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 6146, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->loopback_mode;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Write_Loopback_Mode_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Write_Loopback_Mode_Cmd_t)(void *, tBtampTLVHCI_Write_Loopback_Mode_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Write_Loopback_Mode_Cmd ( 0x00b6 )
v_U32_t btampPackTlvHCI_Write_Remote_AMP_ASSOC_Cmd(void * pCtx,
tBtampTLVHCI_Write_Remote_AMP_ASSOC_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Write_Remote_AMP_ASSOC_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 5131, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
*pBuf = pSrc->phy_link_handle;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
frameshtons(pCtx, pBuf, pSrc->length_so_far, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
frameshtons(pCtx, pBuf, pSrc->amp_assoc_remaining_length, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
BTAMP_MEMCPY(pCtx, pBuf, &( pSrc->amp_assoc_fragment ), pSrc->amp_assoc_remaining_length);
*pnConsumed += pSrc->amp_assoc_remaining_length;
pBuf += ( pSrc->amp_assoc_remaining_length );
nBuf -= ( pSrc->amp_assoc_remaining_length );
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Write_Remote_AMP_ASSOC_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Write_Remote_AMP_ASSOC_Cmd_t)(void *, tBtampTLVHCI_Write_Remote_AMP_ASSOC_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Write_Remote_AMP_ASSOC_Cmd ( 0x00b7 )
v_U32_t btampPackTlvHCI_Enhanced_Flush_Cmd(void * pCtx,
tBtampTLVHCI_Enhanced_Flush_Cmd *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 2;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Enhanced_Flush_Cmd(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 3167, 0);
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
*pBuf = pSrc->packet_type;
*pnConsumed += 1;
pBuf += 1;
nBuf -= 1;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Enhanced_Flush_Cmd. */
typedef v_U32_t (*pfnPackTlvHCI_Enhanced_Flush_Cmd_t)(void *, tBtampTLVHCI_Enhanced_Flush_Cmd *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Enhanced_Flush_Cmd ( 0x00b8 )
v_U32_t btampPackTlvHCI_Enhanced_Flush_Complete_Event(void * pCtx,
tBtampTLVHCI_Enhanced_Flush_Complete_Event *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed)
{
v_U8_t* pTlvLen = 0;
v_U32_t nConsumedOnEntry;
v_U32_t status = BTAMP_PARSE_SUCCESS;
v_U32_t nNeeded = 0U;
v_U32_t sType = 0U;
v_U32_t sLen = 0U;
sType = 1;
sLen = 1;
// sanity checking
if( pCtx == NULL || pSrc == NULL ||
pBuf == NULL || pnConsumed == NULL)
{
VOS_TRACE( VOS_MODULE_ID_BAP, VOS_TRACE_LEVEL_ERROR, "bad input" );
return BTAMP_BAD_INPUT_BUFFER;
}
nConsumedOnEntry = *pnConsumed;
status = btampGetPackedTlvHCI_Enhanced_Flush_Complete_Event(pCtx, pSrc, &nNeeded);
if ( ! BTAMP_SUCCEEDED( status ) ) return status;
nNeeded += sType + sLen;
if ( nNeeded > nBuf ) return BTAMP_BUFFER_OVERFLOW;
pTlvLen = pBuf;
while ( pSrc->present )
{
if( sType == 2) frameshtons( pCtx, pBuf, 57, 0);
else *pBuf = 57;
pBuf += sType; nBuf -= sType; *pnConsumed += sType;
pTlvLen = pBuf;
pBuf += sLen; nBuf -= sLen; *pnConsumed += sLen;
frameshtons(pCtx, pBuf, pSrc->log_link_handle, 0);
*pnConsumed += 2;
pBuf += 2;
nBuf -= 2;
break;
}
if (pTlvLen && sLen == 2)
{
frameshtons( pCtx, pTlvLen, *pnConsumed - nConsumedOnEntry - sType - sLen, 0);
} else if(NULL != pTlvLen)
{
*pTlvLen = (v_U8_t)(*pnConsumed - nConsumedOnEntry - sType - sLen);
}
return status;
} /* End btampPackTlvHCI_Enhanced_Flush_Complete_Event. */
typedef v_U32_t (*pfnPackTlvHCI_Enhanced_Flush_Complete_Event_t)(void *, tBtampTLVHCI_Enhanced_Flush_Complete_Event *, v_U8_t*, v_U32_t, v_U32_t*);
#define SigPackTlvHCI_Enhanced_Flush_Complete_Event ( 0x00b9 )
v_U32_t btampPackAMP_ASSOC(void * pCtx, tBtampAMP_ASSOC *pFrm, v_U8_t *pBuf, v_U32_t nBuf, v_U32_t *pnConsumed)
{
v_U32_t i;
static tTLVDefn TLVS[ ] = {
{BTAMP_TLV_AMP_ASSOC_MAC_ADDR, 0, 9, 9, offsetof(tBtampAMP_ASSOC, AMP_Assoc_MAC_Addr), offsetof(tBtampTLVAMP_Assoc_MAC_Addr, present), SigPackTlvAMP_Assoc_MAC_Addr, (pfnGeneric_t)btampPackTlvAMP_Assoc_MAC_Addr, "AMP_Assoc_MAC_Addr", 1, },
{BTAMP_TLV_AMP_ASSOC_PREFERRED_CHANNEL_LIST, 0, 9, 12, offsetof(tBtampAMP_ASSOC, AMP_Assoc_Preferred_Channel_List), offsetof(tBtampTLVAMP_Assoc_Preferred_Channel_List, present), SigPackTlvAMP_Assoc_Preferred_Channel_List, (pfnGeneric_t)btampPackTlvAMP_Assoc_Preferred_Channel_List, "AMP_Assoc_Preferred_Channel_List", 1, },
{BTAMP_TLV_AMP_ASSOC_CONNECTED_CHANNEL, 0, 9, 12, offsetof(tBtampAMP_ASSOC, AMP_Assoc_Connected_Channel), offsetof(tBtampTLVAMP_Assoc_Connected_Channel, present), SigPackTlvAMP_Assoc_Connected_Channel, (pfnGeneric_t)btampPackTlvAMP_Assoc_Connected_Channel, "AMP_Assoc_Connected_Channel", 0, },
{BTAMP_TLV_AMP_ASSOC_PAL_CAPABILITIES, 0, 7, 7, offsetof(tBtampAMP_ASSOC, AMP_Assoc_PAL_Capabilities), offsetof(tBtampTLVAMP_Assoc_PAL_Capabilities, present), SigPackTlvAMP_Assoc_PAL_Capabilities, (pfnGeneric_t)btampPackTlvAMP_Assoc_PAL_Capabilities, "AMP_Assoc_PAL_Capabilities", 0, },
{BTAMP_TLV_AMP_ASSOC_PAL_VERSION, 0, 8, 8, offsetof(tBtampAMP_ASSOC, AMP_Assoc_PAL_Version), offsetof(tBtampTLVAMP_Assoc_PAL_Version, present), SigPackTlvAMP_Assoc_PAL_Version, (pfnGeneric_t)btampPackTlvAMP_Assoc_PAL_Version, "AMP_Assoc_PAL_Version", 1, },
{ 0xffff, 0 },
};
v_U32_t idx = 0;
v_U32_t status = 0;
(void)i;
*pnConsumed = 0U;
status |= PackTlvCore(pCtx,(v_U8_t*)pFrm,pBuf,nBuf,pnConsumed,TLVS,&idx);
# ifdef BTAMP_DUMP_FRAMES
if (!BTAMP_FAILED(status))
{
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("Packed the AMP_ASSOC:\n"));
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("AMP_Assoc_MAC_Addr:\n"));
if (!pFrm->AMP_Assoc_MAC_Addr.present)
{
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("Not present.\n"));
}
else
{
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* )&pFrm->AMP_Assoc_MAC_Addr.mac_addr, 6);
}
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("AMP_Assoc_Preferred_Channel_List:\n"));
if (!pFrm->AMP_Assoc_Preferred_Channel_List.present)
{
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("Not present.\n"));
}
else
{
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* )&pFrm->AMP_Assoc_Preferred_Channel_List.country, 3);
FRAMES_LOG1(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("num_triplets: %d.\n"), pFrm->AMP_Assoc_Preferred_Channel_List.num_triplets);
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* ) pFrm->AMP_Assoc_Preferred_Channel_List.triplets, 3 * pFrm->AMP_Assoc_Preferred_Channel_List.num_triplets);
}
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("AMP_Assoc_Connected_Channel:\n"));
if (!pFrm->AMP_Assoc_Connected_Channel.present)
{
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("Not present.\n"));
}
else
{
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* )&pFrm->AMP_Assoc_Connected_Channel.country, 3);
FRAMES_LOG1(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("num_triplets: %d.\n"), pFrm->AMP_Assoc_Connected_Channel.num_triplets);
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* ) pFrm->AMP_Assoc_Connected_Channel.triplets, 3 * pFrm->AMP_Assoc_Connected_Channel.num_triplets);
}
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("AMP_Assoc_PAL_Capabilities:\n"));
if (!pFrm->AMP_Assoc_PAL_Capabilities.present)
{
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("Not present.\n"));
}
else
{
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* )&pFrm->AMP_Assoc_PAL_Capabilities.pal_capabilities, 4);
}
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("AMP_Assoc_PAL_Version:\n"));
if (!pFrm->AMP_Assoc_PAL_Version.present)
{
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("Not present.\n"));
}
else
{
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* )&pFrm->AMP_Assoc_PAL_Version.pal_version, 1);
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* )&pFrm->AMP_Assoc_PAL_Version.pal_CompanyID, 2);
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), ( v_U8_t* )&pFrm->AMP_Assoc_PAL_Version.pal_subversion, 2);
}
FRAMES_LOG0(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), FRFL("to:\n"));
FRAMES_DUMP(pCtx, FRAMES_SEV_FOR_FRAME(pCtx, BTAMP_AMP_ASSOC), pBuf, nBuf);
}
# endif // BTAMP_DUMP_FRAMES
return status;
} /* End btampUnpackAMP_ASSOC. */
static v_U32_t PackTlvCore(void * pCtx,
v_U8_t *pSrc,
v_U8_t *pBuf,
v_U32_t nBuf,
v_U32_t *pnConsumed,
tTLVDefn TLVs[],
v_U32_t *pidx)
{
tTLVDefn *pTlv;
tFRAMES_BOOL *pfFound;
v_U8_t *pBufRemaining;
v_U32_t nBufRemaining, status, status2, len;
BTAMP_PARAMETER_CHECK2(pSrc, pBuf, nBuf, pnConsumed);
(void)pCtx;
status = BTAMP_PARSE_SUCCESS;
status2 = BTAMP_PARSE_SUCCESS;
pBufRemaining = pBuf;
nBufRemaining = nBuf;
pTlv = &( TLVs[0] );
while ( 0xffff != pTlv->id )
{
pfFound = (tFRAMES_BOOL*)(pSrc + pTlv->offset +
pTlv->presenceOffset);
if ( *pfFound && pTlv->minSize > nBufRemaining )
{
FRAMES_LOG3(pCtx, FRLOGE, FRFL("The TLV %s takes at least"
" %d bytes, but there are only %d left in the buffer."
"\n"), pTlv->name, pTlv->minSize, nBufRemaining);
return BTAMP_BUFFER_OVERFLOW;
}
len = 0U;
if ( *pfFound ) {
switch ( pTlv->sig )
{
case SigPackTlvAMP_Assoc_Connected_Channel:
status2 = ( (pfnPackTlvAMP_Assoc_Connected_Channel_t)(pTlv->pfn) )(pCtx, ( tBtampTLVAMP_Assoc_Connected_Channel* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvAMP_Assoc_MAC_Addr:
status2 = ( (pfnPackTlvAMP_Assoc_MAC_Addr_t)(pTlv->pfn) )(pCtx, ( tBtampTLVAMP_Assoc_MAC_Addr* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvAMP_Assoc_PAL_Capabilities:
status2 = ( (pfnPackTlvAMP_Assoc_PAL_Capabilities_t)(pTlv->pfn) )(pCtx, ( tBtampTLVAMP_Assoc_PAL_Capabilities* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvAMP_Assoc_PAL_Version:
status2 = ( (pfnPackTlvAMP_Assoc_PAL_Version_t)(pTlv->pfn) )(pCtx, ( tBtampTLVAMP_Assoc_PAL_Version* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvAMP_Assoc_Preferred_Channel_List:
status2 = ( (pfnPackTlvAMP_Assoc_Preferred_Channel_List_t)(pTlv->pfn) )(pCtx, ( tBtampTLVAMP_Assoc_Preferred_Channel_List* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvFlow_Spec:
status2 = ( (pfnPackTlvFlow_Spec_t)(pTlv->pfn) )(pCtx, ( tBtampTLVFlow_Spec* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Accept_Logical_Link_Cmd:
status2 = ( (pfnPackTlvHCI_Accept_Logical_Link_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Accept_Logical_Link_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Accept_Physical_Link_Cmd:
status2 = ( (pfnPackTlvHCI_Accept_Physical_Link_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Accept_Physical_Link_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Channel_Selected_Event:
status2 = ( (pfnPackTlvHCI_Channel_Selected_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Channel_Selected_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Command_Complete_Event:
status2 = ( (pfnPackTlvHCI_Command_Complete_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Command_Complete_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Command_Status_Event:
status2 = ( (pfnPackTlvHCI_Command_Status_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Command_Status_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Create_Logical_Link_Cmd:
status2 = ( (pfnPackTlvHCI_Create_Logical_Link_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Create_Logical_Link_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Create_Physical_Link_Cmd:
status2 = ( (pfnPackTlvHCI_Create_Physical_Link_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Create_Physical_Link_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Data_Buffer_Overflow_Event:
status2 = ( (pfnPackTlvHCI_Data_Buffer_Overflow_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Data_Buffer_Overflow_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Disconnect_Logical_Link_Cmd:
status2 = ( (pfnPackTlvHCI_Disconnect_Logical_Link_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Disconnect_Logical_Link_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Disconnect_Logical_Link_Complete_Event:
status2 = ( (pfnPackTlvHCI_Disconnect_Logical_Link_Complete_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Disconnect_Logical_Link_Complete_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Disconnect_Physical_Link_Cmd:
status2 = ( (pfnPackTlvHCI_Disconnect_Physical_Link_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Disconnect_Physical_Link_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Disconnect_Physical_Link_Complete_Event:
status2 = ( (pfnPackTlvHCI_Disconnect_Physical_Link_Complete_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Disconnect_Physical_Link_Complete_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Flow_Spec_Modify_Cmd:
status2 = ( (pfnPackTlvHCI_Flow_Spec_Modify_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Flow_Spec_Modify_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Flow_Spec_Modify_Complete_Event:
status2 = ( (pfnPackTlvHCI_Flow_Spec_Modify_Complete_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Flow_Spec_Modify_Complete_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Flush_Cmd:
status2 = ( (pfnPackTlvHCI_Flush_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Flush_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Flush_Occurred_Event:
status2 = ( (pfnPackTlvHCI_Flush_Occurred_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Flush_Occurred_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Generic_AMP_Link_Key_Notification_Event:
status2 = ( (pfnPackTlvHCI_Generic_AMP_Link_Key_Notification_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Generic_AMP_Link_Key_Notification_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Hardware_Error_Event:
status2 = ( (pfnPackTlvHCI_Hardware_Error_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Hardware_Error_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Logical_Link_Cancel_Cmd:
status2 = ( (pfnPackTlvHCI_Logical_Link_Cancel_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Logical_Link_Cancel_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Logical_Link_Complete_Event:
status2 = ( (pfnPackTlvHCI_Logical_Link_Complete_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Logical_Link_Complete_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Loopback_Command_Event:
status2 = ( (pfnPackTlvHCI_Loopback_Command_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Loopback_Command_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Physical_Link_Complete_Event:
status2 = ( (pfnPackTlvHCI_Physical_Link_Complete_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Physical_Link_Complete_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Physical_Link_Loss_Warning_Event:
status2 = ( (pfnPackTlvHCI_Physical_Link_Loss_Warning_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Physical_Link_Loss_Warning_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Physical_Link_Recovery_Event:
status2 = ( (pfnPackTlvHCI_Physical_Link_Recovery_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Physical_Link_Recovery_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Qos_Violation_Event:
status2 = ( (pfnPackTlvHCI_Qos_Violation_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Qos_Violation_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd:
status2 = ( (pfnPackTlvHCI_Read_Best_Effort_Flush_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Best_Effort_Flush_Timeout_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_Buffer_Size_Cmd:
status2 = ( (pfnPackTlvHCI_Read_Buffer_Size_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Buffer_Size_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_Connection_Accept_Timeout_Cmd:
status2 = ( (pfnPackTlvHCI_Read_Connection_Accept_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Connection_Accept_Timeout_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_Data_Block_Size_Cmd:
status2 = ( (pfnPackTlvHCI_Read_Data_Block_Size_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Data_Block_Size_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_Failed_Contact_Counter_Cmd:
status2 = ( (pfnPackTlvHCI_Read_Failed_Contact_Counter_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Failed_Contact_Counter_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_Flow_Control_Mode_Cmd:
status2 = ( (pfnPackTlvHCI_Read_Flow_Control_Mode_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Flow_Control_Mode_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_Link_Quality_Cmd:
status2 = ( (pfnPackTlvHCI_Read_Link_Quality_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Link_Quality_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_Link_Supervision_Timeout_Cmd:
status2 = ( (pfnPackTlvHCI_Read_Link_Supervision_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Link_Supervision_Timeout_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_Local_AMP_Assoc_Cmd:
status2 = ( (pfnPackTlvHCI_Read_Local_AMP_Assoc_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Local_AMP_Assoc_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_Local_AMP_Information_Cmd:
status2 = ( (pfnPackTlvHCI_Read_Local_AMP_Information_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Local_AMP_Information_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_Local_Supported_Cmds_Cmd:
status2 = ( (pfnPackTlvHCI_Read_Local_Supported_Cmds_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Local_Supported_Cmds_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_Local_Version_Info_Cmd:
status2 = ( (pfnPackTlvHCI_Read_Local_Version_Info_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Local_Version_Info_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_Location_Data_Cmd:
status2 = ( (pfnPackTlvHCI_Read_Location_Data_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Location_Data_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd:
status2 = ( (pfnPackTlvHCI_Read_Logical_Link_Accept_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Logical_Link_Accept_Timeout_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_Loopback_Mode_Cmd:
status2 = ( (pfnPackTlvHCI_Read_Loopback_Mode_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_Loopback_Mode_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Read_RSSI_Cmd:
status2 = ( (pfnPackTlvHCI_Read_RSSI_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Read_RSSI_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Reset_Cmd:
status2 = ( (pfnPackTlvHCI_Reset_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Reset_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Reset_Failed_Contact_Counter_Cmd:
status2 = ( (pfnPackTlvHCI_Reset_Failed_Contact_Counter_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Reset_Failed_Contact_Counter_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Set_Event_Mask_Cmd:
status2 = ( (pfnPackTlvHCI_Set_Event_Mask_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Set_Event_Mask_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Set_Event_Mask_Page_2_Cmd:
status2 = ( (pfnPackTlvHCI_Set_Event_Mask_Page_2_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Set_Event_Mask_Page_2_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Set_Short_Range_Mode_Cmd:
status2 = ( (pfnPackTlvHCI_Set_Short_Range_Mode_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Set_Short_Range_Mode_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Short_Range_Mode_Change_Complete_Event:
status2 = ( (pfnPackTlvHCI_Short_Range_Mode_Change_Complete_Event_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Short_Range_Mode_Change_Complete_Event* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd:
status2 = ( (pfnPackTlvHCI_Write_Best_Effort_Flush_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Best_Effort_Flush_Timeout_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Write_Connection_Accept_Timeout_Cmd:
status2 = ( (pfnPackTlvHCI_Write_Connection_Accept_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Connection_Accept_Timeout_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Write_Flow_Control_Mode_Cmd:
status2 = ( (pfnPackTlvHCI_Write_Flow_Control_Mode_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Flow_Control_Mode_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Write_Link_Supervision_Timeout_Cmd:
status2 = ( (pfnPackTlvHCI_Write_Link_Supervision_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Link_Supervision_Timeout_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Write_Location_Data_Cmd:
status2 = ( (pfnPackTlvHCI_Write_Location_Data_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Location_Data_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd:
status2 = ( (pfnPackTlvHCI_Write_Logical_Link_Accept_Timeout_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Logical_Link_Accept_Timeout_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Write_Loopback_Mode_Cmd:
status2 = ( (pfnPackTlvHCI_Write_Loopback_Mode_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Loopback_Mode_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
case SigPackTlvHCI_Write_Remote_AMP_ASSOC_Cmd:
status2 = ( (pfnPackTlvHCI_Write_Remote_AMP_ASSOC_Cmd_t)(pTlv->pfn) )(pCtx, ( tBtampTLVHCI_Write_Remote_AMP_ASSOC_Cmd* )(pSrc + pTlv->offset), pBufRemaining, nBufRemaining, &len);
if (status2) status |= status2;
break;
default:
FRAMES_LOG1(pCtx, FRLOGE, FRFL("INTERNAL ERROR-- I don't "
"know about the TLV %d; this is most likely a bug in "
"'framesc'.\n"), pTlv->sig);
return BTAMP_INTERNAL_ERROR;
}
} /* End if on *pfFound */
pBufRemaining += len;
nBufRemaining -= len;
*pnConsumed += len;
++pTlv;
if(len) ++*pidx;
}
return status;
}
| gpl-2.0 |
werty100/android_kernel_boxer8_ouya | drivers/net/cxgb3/cxgb3_main.c | 387 | 88686 | /*
* Copyright (c) 2003-2008 Chelsio, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/if_vlan.h>
#include <linux/mdio.h>
#include <linux/sockios.h>
#include <linux/workqueue.h>
#include <linux/proc_fs.h>
#include <linux/rtnetlink.h>
#include <linux/firmware.h>
#include <linux/log2.h>
#include <linux/stringify.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include "common.h"
#include "cxgb3_ioctl.h"
#include "regs.h"
#include "cxgb3_offload.h"
#include "version.h"
#include "cxgb3_ctl_defs.h"
#include "t3_cpl.h"
#include "firmware_exports.h"
enum {
MAX_TXQ_ENTRIES = 16384,
MAX_CTRL_TXQ_ENTRIES = 1024,
MAX_RSPQ_ENTRIES = 16384,
MAX_RX_BUFFERS = 16384,
MAX_RX_JUMBO_BUFFERS = 16384,
MIN_TXQ_ENTRIES = 4,
MIN_CTRL_TXQ_ENTRIES = 4,
MIN_RSPQ_ENTRIES = 32,
MIN_FL_ENTRIES = 32
};
#define PORT_MASK ((1 << MAX_NPORTS) - 1)
#define DFLT_MSG_ENABLE (NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK | \
NETIF_MSG_TIMER | NETIF_MSG_IFDOWN | NETIF_MSG_IFUP |\
NETIF_MSG_RX_ERR | NETIF_MSG_TX_ERR)
#define EEPROM_MAGIC 0x38E2F10C
#define CH_DEVICE(devid, idx) \
{ PCI_VENDOR_ID_CHELSIO, devid, PCI_ANY_ID, PCI_ANY_ID, 0, 0, idx }
static DEFINE_PCI_DEVICE_TABLE(cxgb3_pci_tbl) = {
CH_DEVICE(0x20, 0), /* PE9000 */
CH_DEVICE(0x21, 1), /* T302E */
CH_DEVICE(0x22, 2), /* T310E */
CH_DEVICE(0x23, 3), /* T320X */
CH_DEVICE(0x24, 1), /* T302X */
CH_DEVICE(0x25, 3), /* T320E */
CH_DEVICE(0x26, 2), /* T310X */
CH_DEVICE(0x30, 2), /* T3B10 */
CH_DEVICE(0x31, 3), /* T3B20 */
CH_DEVICE(0x32, 1), /* T3B02 */
CH_DEVICE(0x35, 6), /* T3C20-derived T3C10 */
CH_DEVICE(0x36, 3), /* S320E-CR */
CH_DEVICE(0x37, 7), /* N320E-G2 */
{0,}
};
MODULE_DESCRIPTION(DRV_DESC);
MODULE_AUTHOR("Chelsio Communications");
MODULE_LICENSE("Dual BSD/GPL");
MODULE_VERSION(DRV_VERSION);
MODULE_DEVICE_TABLE(pci, cxgb3_pci_tbl);
static int dflt_msg_enable = DFLT_MSG_ENABLE;
module_param(dflt_msg_enable, int, 0644);
MODULE_PARM_DESC(dflt_msg_enable, "Chelsio T3 default message enable bitmap");
/*
* The driver uses the best interrupt scheme available on a platform in the
* order MSI-X, MSI, legacy pin interrupts. This parameter determines which
* of these schemes the driver may consider as follows:
*
* msi = 2: choose from among all three options
* msi = 1: only consider MSI and pin interrupts
* msi = 0: force pin interrupts
*/
static int msi = 2;
module_param(msi, int, 0644);
MODULE_PARM_DESC(msi, "whether to use MSI or MSI-X");
/*
* The driver enables offload as a default.
* To disable it, use ofld_disable = 1.
*/
static int ofld_disable = 0;
module_param(ofld_disable, int, 0644);
MODULE_PARM_DESC(ofld_disable, "whether to enable offload at init time or not");
/*
* We have work elements that we need to cancel when an interface is taken
* down. Normally the work elements would be executed by keventd but that
* can deadlock because of linkwatch. If our close method takes the rtnl
* lock and linkwatch is ahead of our work elements in keventd, linkwatch
* will block keventd as it needs the rtnl lock, and we'll deadlock waiting
* for our work to complete. Get our own work queue to solve this.
*/
struct workqueue_struct *cxgb3_wq;
/**
* link_report - show link status and link speed/duplex
* @p: the port whose settings are to be reported
*
* Shows the link status, speed, and duplex of a port.
*/
static void link_report(struct net_device *dev)
{
if (!netif_carrier_ok(dev))
printk(KERN_INFO "%s: link down\n", dev->name);
else {
const char *s = "10Mbps";
const struct port_info *p = netdev_priv(dev);
switch (p->link_config.speed) {
case SPEED_10000:
s = "10Gbps";
break;
case SPEED_1000:
s = "1000Mbps";
break;
case SPEED_100:
s = "100Mbps";
break;
}
printk(KERN_INFO "%s: link up, %s, %s-duplex\n", dev->name, s,
p->link_config.duplex == DUPLEX_FULL ? "full" : "half");
}
}
static void enable_tx_fifo_drain(struct adapter *adapter,
struct port_info *pi)
{
t3_set_reg_field(adapter, A_XGM_TXFIFO_CFG + pi->mac.offset, 0,
F_ENDROPPKT);
t3_write_reg(adapter, A_XGM_RX_CTRL + pi->mac.offset, 0);
t3_write_reg(adapter, A_XGM_TX_CTRL + pi->mac.offset, F_TXEN);
t3_write_reg(adapter, A_XGM_RX_CTRL + pi->mac.offset, F_RXEN);
}
static void disable_tx_fifo_drain(struct adapter *adapter,
struct port_info *pi)
{
t3_set_reg_field(adapter, A_XGM_TXFIFO_CFG + pi->mac.offset,
F_ENDROPPKT, 0);
}
void t3_os_link_fault(struct adapter *adap, int port_id, int state)
{
struct net_device *dev = adap->port[port_id];
struct port_info *pi = netdev_priv(dev);
if (state == netif_carrier_ok(dev))
return;
if (state) {
struct cmac *mac = &pi->mac;
netif_carrier_on(dev);
disable_tx_fifo_drain(adap, pi);
/* Clear local faults */
t3_xgm_intr_disable(adap, pi->port_id);
t3_read_reg(adap, A_XGM_INT_STATUS +
pi->mac.offset);
t3_write_reg(adap,
A_XGM_INT_CAUSE + pi->mac.offset,
F_XGM_INT);
t3_set_reg_field(adap,
A_XGM_INT_ENABLE +
pi->mac.offset,
F_XGM_INT, F_XGM_INT);
t3_xgm_intr_enable(adap, pi->port_id);
t3_mac_enable(mac, MAC_DIRECTION_TX);
} else {
netif_carrier_off(dev);
/* Flush TX FIFO */
enable_tx_fifo_drain(adap, pi);
}
link_report(dev);
}
/**
* t3_os_link_changed - handle link status changes
* @adapter: the adapter associated with the link change
* @port_id: the port index whose limk status has changed
* @link_stat: the new status of the link
* @speed: the new speed setting
* @duplex: the new duplex setting
* @pause: the new flow-control setting
*
* This is the OS-dependent handler for link status changes. The OS
* neutral handler takes care of most of the processing for these events,
* then calls this handler for any OS-specific processing.
*/
void t3_os_link_changed(struct adapter *adapter, int port_id, int link_stat,
int speed, int duplex, int pause)
{
struct net_device *dev = adapter->port[port_id];
struct port_info *pi = netdev_priv(dev);
struct cmac *mac = &pi->mac;
/* Skip changes from disabled ports. */
if (!netif_running(dev))
return;
if (link_stat != netif_carrier_ok(dev)) {
if (link_stat) {
disable_tx_fifo_drain(adapter, pi);
t3_mac_enable(mac, MAC_DIRECTION_RX);
/* Clear local faults */
t3_xgm_intr_disable(adapter, pi->port_id);
t3_read_reg(adapter, A_XGM_INT_STATUS +
pi->mac.offset);
t3_write_reg(adapter,
A_XGM_INT_CAUSE + pi->mac.offset,
F_XGM_INT);
t3_set_reg_field(adapter,
A_XGM_INT_ENABLE + pi->mac.offset,
F_XGM_INT, F_XGM_INT);
t3_xgm_intr_enable(adapter, pi->port_id);
netif_carrier_on(dev);
} else {
netif_carrier_off(dev);
t3_xgm_intr_disable(adapter, pi->port_id);
t3_read_reg(adapter, A_XGM_INT_STATUS + pi->mac.offset);
t3_set_reg_field(adapter,
A_XGM_INT_ENABLE + pi->mac.offset,
F_XGM_INT, 0);
if (is_10G(adapter))
pi->phy.ops->power_down(&pi->phy, 1);
t3_read_reg(adapter, A_XGM_INT_STATUS + pi->mac.offset);
t3_mac_disable(mac, MAC_DIRECTION_RX);
t3_link_start(&pi->phy, mac, &pi->link_config);
/* Flush TX FIFO */
enable_tx_fifo_drain(adapter, pi);
}
link_report(dev);
}
}
/**
* t3_os_phymod_changed - handle PHY module changes
* @phy: the PHY reporting the module change
* @mod_type: new module type
*
* This is the OS-dependent handler for PHY module changes. It is
* invoked when a PHY module is removed or inserted for any OS-specific
* processing.
*/
void t3_os_phymod_changed(struct adapter *adap, int port_id)
{
static const char *mod_str[] = {
NULL, "SR", "LR", "LRM", "TWINAX", "TWINAX", "unknown"
};
const struct net_device *dev = adap->port[port_id];
const struct port_info *pi = netdev_priv(dev);
if (pi->phy.modtype == phy_modtype_none)
printk(KERN_INFO "%s: PHY module unplugged\n", dev->name);
else
printk(KERN_INFO "%s: %s PHY module inserted\n", dev->name,
mod_str[pi->phy.modtype]);
}
static void cxgb_set_rxmode(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
t3_mac_set_rx_mode(&pi->mac, dev);
}
/**
* link_start - enable a port
* @dev: the device to enable
*
* Performs the MAC and PHY actions needed to enable a port.
*/
static void link_start(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
struct cmac *mac = &pi->mac;
t3_mac_reset(mac);
t3_mac_set_num_ucast(mac, MAX_MAC_IDX);
t3_mac_set_mtu(mac, dev->mtu);
t3_mac_set_address(mac, LAN_MAC_IDX, dev->dev_addr);
t3_mac_set_address(mac, SAN_MAC_IDX, pi->iscsic.mac_addr);
t3_mac_set_rx_mode(mac, dev);
t3_link_start(&pi->phy, mac, &pi->link_config);
t3_mac_enable(mac, MAC_DIRECTION_RX | MAC_DIRECTION_TX);
}
static inline void cxgb_disable_msi(struct adapter *adapter)
{
if (adapter->flags & USING_MSIX) {
pci_disable_msix(adapter->pdev);
adapter->flags &= ~USING_MSIX;
} else if (adapter->flags & USING_MSI) {
pci_disable_msi(adapter->pdev);
adapter->flags &= ~USING_MSI;
}
}
/*
* Interrupt handler for asynchronous events used with MSI-X.
*/
static irqreturn_t t3_async_intr_handler(int irq, void *cookie)
{
t3_slow_intr_handler(cookie);
return IRQ_HANDLED;
}
/*
* Name the MSI-X interrupts.
*/
static void name_msix_vecs(struct adapter *adap)
{
int i, j, msi_idx = 1, n = sizeof(adap->msix_info[0].desc) - 1;
snprintf(adap->msix_info[0].desc, n, "%s", adap->name);
adap->msix_info[0].desc[n] = 0;
for_each_port(adap, j) {
struct net_device *d = adap->port[j];
const struct port_info *pi = netdev_priv(d);
for (i = 0; i < pi->nqsets; i++, msi_idx++) {
snprintf(adap->msix_info[msi_idx].desc, n,
"%s-%d", d->name, pi->first_qset + i);
adap->msix_info[msi_idx].desc[n] = 0;
}
}
}
static int request_msix_data_irqs(struct adapter *adap)
{
int i, j, err, qidx = 0;
for_each_port(adap, i) {
int nqsets = adap2pinfo(adap, i)->nqsets;
for (j = 0; j < nqsets; ++j) {
err = request_irq(adap->msix_info[qidx + 1].vec,
t3_intr_handler(adap,
adap->sge.qs[qidx].
rspq.polling), 0,
adap->msix_info[qidx + 1].desc,
&adap->sge.qs[qidx]);
if (err) {
while (--qidx >= 0)
free_irq(adap->msix_info[qidx + 1].vec,
&adap->sge.qs[qidx]);
return err;
}
qidx++;
}
}
return 0;
}
static void free_irq_resources(struct adapter *adapter)
{
if (adapter->flags & USING_MSIX) {
int i, n = 0;
free_irq(adapter->msix_info[0].vec, adapter);
for_each_port(adapter, i)
n += adap2pinfo(adapter, i)->nqsets;
for (i = 0; i < n; ++i)
free_irq(adapter->msix_info[i + 1].vec,
&adapter->sge.qs[i]);
} else
free_irq(adapter->pdev->irq, adapter);
}
static int await_mgmt_replies(struct adapter *adap, unsigned long init_cnt,
unsigned long n)
{
int attempts = 10;
while (adap->sge.qs[0].rspq.offload_pkts < init_cnt + n) {
if (!--attempts)
return -ETIMEDOUT;
msleep(10);
}
return 0;
}
static int init_tp_parity(struct adapter *adap)
{
int i;
struct sk_buff *skb;
struct cpl_set_tcb_field *greq;
unsigned long cnt = adap->sge.qs[0].rspq.offload_pkts;
t3_tp_set_offload_mode(adap, 1);
for (i = 0; i < 16; i++) {
struct cpl_smt_write_req *req;
skb = alloc_skb(sizeof(*req), GFP_KERNEL);
if (!skb)
skb = adap->nofail_skb;
if (!skb)
goto alloc_skb_fail;
req = (struct cpl_smt_write_req *)__skb_put(skb, sizeof(*req));
memset(req, 0, sizeof(*req));
req->wr.wr_hi = htonl(V_WR_OP(FW_WROPCODE_FORWARD));
OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_SMT_WRITE_REQ, i));
req->mtu_idx = NMTUS - 1;
req->iff = i;
t3_mgmt_tx(adap, skb);
if (skb == adap->nofail_skb) {
await_mgmt_replies(adap, cnt, i + 1);
adap->nofail_skb = alloc_skb(sizeof(*greq), GFP_KERNEL);
if (!adap->nofail_skb)
goto alloc_skb_fail;
}
}
for (i = 0; i < 2048; i++) {
struct cpl_l2t_write_req *req;
skb = alloc_skb(sizeof(*req), GFP_KERNEL);
if (!skb)
skb = adap->nofail_skb;
if (!skb)
goto alloc_skb_fail;
req = (struct cpl_l2t_write_req *)__skb_put(skb, sizeof(*req));
memset(req, 0, sizeof(*req));
req->wr.wr_hi = htonl(V_WR_OP(FW_WROPCODE_FORWARD));
OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_L2T_WRITE_REQ, i));
req->params = htonl(V_L2T_W_IDX(i));
t3_mgmt_tx(adap, skb);
if (skb == adap->nofail_skb) {
await_mgmt_replies(adap, cnt, 16 + i + 1);
adap->nofail_skb = alloc_skb(sizeof(*greq), GFP_KERNEL);
if (!adap->nofail_skb)
goto alloc_skb_fail;
}
}
for (i = 0; i < 2048; i++) {
struct cpl_rte_write_req *req;
skb = alloc_skb(sizeof(*req), GFP_KERNEL);
if (!skb)
skb = adap->nofail_skb;
if (!skb)
goto alloc_skb_fail;
req = (struct cpl_rte_write_req *)__skb_put(skb, sizeof(*req));
memset(req, 0, sizeof(*req));
req->wr.wr_hi = htonl(V_WR_OP(FW_WROPCODE_FORWARD));
OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_RTE_WRITE_REQ, i));
req->l2t_idx = htonl(V_L2T_W_IDX(i));
t3_mgmt_tx(adap, skb);
if (skb == adap->nofail_skb) {
await_mgmt_replies(adap, cnt, 16 + 2048 + i + 1);
adap->nofail_skb = alloc_skb(sizeof(*greq), GFP_KERNEL);
if (!adap->nofail_skb)
goto alloc_skb_fail;
}
}
skb = alloc_skb(sizeof(*greq), GFP_KERNEL);
if (!skb)
skb = adap->nofail_skb;
if (!skb)
goto alloc_skb_fail;
greq = (struct cpl_set_tcb_field *)__skb_put(skb, sizeof(*greq));
memset(greq, 0, sizeof(*greq));
greq->wr.wr_hi = htonl(V_WR_OP(FW_WROPCODE_FORWARD));
OPCODE_TID(greq) = htonl(MK_OPCODE_TID(CPL_SET_TCB_FIELD, 0));
greq->mask = cpu_to_be64(1);
t3_mgmt_tx(adap, skb);
i = await_mgmt_replies(adap, cnt, 16 + 2048 + 2048 + 1);
if (skb == adap->nofail_skb) {
i = await_mgmt_replies(adap, cnt, 16 + 2048 + 2048 + 1);
adap->nofail_skb = alloc_skb(sizeof(*greq), GFP_KERNEL);
}
t3_tp_set_offload_mode(adap, 0);
return i;
alloc_skb_fail:
t3_tp_set_offload_mode(adap, 0);
return -ENOMEM;
}
/**
* setup_rss - configure RSS
* @adap: the adapter
*
* Sets up RSS to distribute packets to multiple receive queues. We
* configure the RSS CPU lookup table to distribute to the number of HW
* receive queues, and the response queue lookup table to narrow that
* down to the response queues actually configured for each port.
* We always configure the RSS mapping for two ports since the mapping
* table has plenty of entries.
*/
static void setup_rss(struct adapter *adap)
{
int i;
unsigned int nq0 = adap2pinfo(adap, 0)->nqsets;
unsigned int nq1 = adap->port[1] ? adap2pinfo(adap, 1)->nqsets : 1;
u8 cpus[SGE_QSETS + 1];
u16 rspq_map[RSS_TABLE_SIZE];
for (i = 0; i < SGE_QSETS; ++i)
cpus[i] = i;
cpus[SGE_QSETS] = 0xff; /* terminator */
for (i = 0; i < RSS_TABLE_SIZE / 2; ++i) {
rspq_map[i] = i % nq0;
rspq_map[i + RSS_TABLE_SIZE / 2] = (i % nq1) + nq0;
}
t3_config_rss(adap, F_RQFEEDBACKENABLE | F_TNLLKPEN | F_TNLMAPEN |
F_TNLPRTEN | F_TNL2TUPEN | F_TNL4TUPEN |
V_RRCPLCPUSIZE(6) | F_HASHTOEPLITZ, cpus, rspq_map);
}
static void ring_dbs(struct adapter *adap)
{
int i, j;
for (i = 0; i < SGE_QSETS; i++) {
struct sge_qset *qs = &adap->sge.qs[i];
if (qs->adap)
for (j = 0; j < SGE_TXQ_PER_SET; j++)
t3_write_reg(adap, A_SG_KDOORBELL, F_SELEGRCNTX | V_EGRCNTX(qs->txq[j].cntxt_id));
}
}
static void init_napi(struct adapter *adap)
{
int i;
for (i = 0; i < SGE_QSETS; i++) {
struct sge_qset *qs = &adap->sge.qs[i];
if (qs->adap)
netif_napi_add(qs->netdev, &qs->napi, qs->napi.poll,
64);
}
/*
* netif_napi_add() can be called only once per napi_struct because it
* adds each new napi_struct to a list. Be careful not to call it a
* second time, e.g., during EEH recovery, by making a note of it.
*/
adap->flags |= NAPI_INIT;
}
/*
* Wait until all NAPI handlers are descheduled. This includes the handlers of
* both netdevices representing interfaces and the dummy ones for the extra
* queues.
*/
static void quiesce_rx(struct adapter *adap)
{
int i;
for (i = 0; i < SGE_QSETS; i++)
if (adap->sge.qs[i].adap)
napi_disable(&adap->sge.qs[i].napi);
}
static void enable_all_napi(struct adapter *adap)
{
int i;
for (i = 0; i < SGE_QSETS; i++)
if (adap->sge.qs[i].adap)
napi_enable(&adap->sge.qs[i].napi);
}
/**
* setup_sge_qsets - configure SGE Tx/Rx/response queues
* @adap: the adapter
*
* Determines how many sets of SGE queues to use and initializes them.
* We support multiple queue sets per port if we have MSI-X, otherwise
* just one queue set per port.
*/
static int setup_sge_qsets(struct adapter *adap)
{
int i, j, err, irq_idx = 0, qset_idx = 0;
unsigned int ntxq = SGE_TXQ_PER_SET;
if (adap->params.rev > 0 && !(adap->flags & USING_MSI))
irq_idx = -1;
for_each_port(adap, i) {
struct net_device *dev = adap->port[i];
struct port_info *pi = netdev_priv(dev);
pi->qs = &adap->sge.qs[pi->first_qset];
for (j = 0; j < pi->nqsets; ++j, ++qset_idx) {
err = t3_sge_alloc_qset(adap, qset_idx, 1,
(adap->flags & USING_MSIX) ? qset_idx + 1 :
irq_idx,
&adap->params.sge.qset[qset_idx], ntxq, dev,
netdev_get_tx_queue(dev, j));
if (err) {
t3_free_sge_resources(adap);
return err;
}
}
}
return 0;
}
static ssize_t attr_show(struct device *d, char *buf,
ssize_t(*format) (struct net_device *, char *))
{
ssize_t len;
/* Synchronize with ioctls that may shut down the device */
rtnl_lock();
len = (*format) (to_net_dev(d), buf);
rtnl_unlock();
return len;
}
static ssize_t attr_store(struct device *d,
const char *buf, size_t len,
ssize_t(*set) (struct net_device *, unsigned int),
unsigned int min_val, unsigned int max_val)
{
char *endp;
ssize_t ret;
unsigned int val;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
val = simple_strtoul(buf, &endp, 0);
if (endp == buf || val < min_val || val > max_val)
return -EINVAL;
rtnl_lock();
ret = (*set) (to_net_dev(d), val);
if (!ret)
ret = len;
rtnl_unlock();
return ret;
}
#define CXGB3_SHOW(name, val_expr) \
static ssize_t format_##name(struct net_device *dev, char *buf) \
{ \
struct port_info *pi = netdev_priv(dev); \
struct adapter *adap = pi->adapter; \
return sprintf(buf, "%u\n", val_expr); \
} \
static ssize_t show_##name(struct device *d, struct device_attribute *attr, \
char *buf) \
{ \
return attr_show(d, buf, format_##name); \
}
static ssize_t set_nfilters(struct net_device *dev, unsigned int val)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adap = pi->adapter;
int min_tids = is_offload(adap) ? MC5_MIN_TIDS : 0;
if (adap->flags & FULL_INIT_DONE)
return -EBUSY;
if (val && adap->params.rev == 0)
return -EINVAL;
if (val > t3_mc5_size(&adap->mc5) - adap->params.mc5.nservers -
min_tids)
return -EINVAL;
adap->params.mc5.nfilters = val;
return 0;
}
static ssize_t store_nfilters(struct device *d, struct device_attribute *attr,
const char *buf, size_t len)
{
return attr_store(d, buf, len, set_nfilters, 0, ~0);
}
static ssize_t set_nservers(struct net_device *dev, unsigned int val)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adap = pi->adapter;
if (adap->flags & FULL_INIT_DONE)
return -EBUSY;
if (val > t3_mc5_size(&adap->mc5) - adap->params.mc5.nfilters -
MC5_MIN_TIDS)
return -EINVAL;
adap->params.mc5.nservers = val;
return 0;
}
static ssize_t store_nservers(struct device *d, struct device_attribute *attr,
const char *buf, size_t len)
{
return attr_store(d, buf, len, set_nservers, 0, ~0);
}
#define CXGB3_ATTR_R(name, val_expr) \
CXGB3_SHOW(name, val_expr) \
static DEVICE_ATTR(name, S_IRUGO, show_##name, NULL)
#define CXGB3_ATTR_RW(name, val_expr, store_method) \
CXGB3_SHOW(name, val_expr) \
static DEVICE_ATTR(name, S_IRUGO | S_IWUSR, show_##name, store_method)
CXGB3_ATTR_R(cam_size, t3_mc5_size(&adap->mc5));
CXGB3_ATTR_RW(nfilters, adap->params.mc5.nfilters, store_nfilters);
CXGB3_ATTR_RW(nservers, adap->params.mc5.nservers, store_nservers);
static struct attribute *cxgb3_attrs[] = {
&dev_attr_cam_size.attr,
&dev_attr_nfilters.attr,
&dev_attr_nservers.attr,
NULL
};
static struct attribute_group cxgb3_attr_group = {.attrs = cxgb3_attrs };
static ssize_t tm_attr_show(struct device *d,
char *buf, int sched)
{
struct port_info *pi = netdev_priv(to_net_dev(d));
struct adapter *adap = pi->adapter;
unsigned int v, addr, bpt, cpt;
ssize_t len;
addr = A_TP_TX_MOD_Q1_Q0_RATE_LIMIT - sched / 2;
rtnl_lock();
t3_write_reg(adap, A_TP_TM_PIO_ADDR, addr);
v = t3_read_reg(adap, A_TP_TM_PIO_DATA);
if (sched & 1)
v >>= 16;
bpt = (v >> 8) & 0xff;
cpt = v & 0xff;
if (!cpt)
len = sprintf(buf, "disabled\n");
else {
v = (adap->params.vpd.cclk * 1000) / cpt;
len = sprintf(buf, "%u Kbps\n", (v * bpt) / 125);
}
rtnl_unlock();
return len;
}
static ssize_t tm_attr_store(struct device *d,
const char *buf, size_t len, int sched)
{
struct port_info *pi = netdev_priv(to_net_dev(d));
struct adapter *adap = pi->adapter;
unsigned int val;
char *endp;
ssize_t ret;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
val = simple_strtoul(buf, &endp, 0);
if (endp == buf || val > 10000000)
return -EINVAL;
rtnl_lock();
ret = t3_config_sched(adap, val, sched);
if (!ret)
ret = len;
rtnl_unlock();
return ret;
}
#define TM_ATTR(name, sched) \
static ssize_t show_##name(struct device *d, struct device_attribute *attr, \
char *buf) \
{ \
return tm_attr_show(d, buf, sched); \
} \
static ssize_t store_##name(struct device *d, struct device_attribute *attr, \
const char *buf, size_t len) \
{ \
return tm_attr_store(d, buf, len, sched); \
} \
static DEVICE_ATTR(name, S_IRUGO | S_IWUSR, show_##name, store_##name)
TM_ATTR(sched0, 0);
TM_ATTR(sched1, 1);
TM_ATTR(sched2, 2);
TM_ATTR(sched3, 3);
TM_ATTR(sched4, 4);
TM_ATTR(sched5, 5);
TM_ATTR(sched6, 6);
TM_ATTR(sched7, 7);
static struct attribute *offload_attrs[] = {
&dev_attr_sched0.attr,
&dev_attr_sched1.attr,
&dev_attr_sched2.attr,
&dev_attr_sched3.attr,
&dev_attr_sched4.attr,
&dev_attr_sched5.attr,
&dev_attr_sched6.attr,
&dev_attr_sched7.attr,
NULL
};
static struct attribute_group offload_attr_group = {.attrs = offload_attrs };
/*
* Sends an sk_buff to an offload queue driver
* after dealing with any active network taps.
*/
static inline int offload_tx(struct t3cdev *tdev, struct sk_buff *skb)
{
int ret;
local_bh_disable();
ret = t3_offload_tx(tdev, skb);
local_bh_enable();
return ret;
}
static int write_smt_entry(struct adapter *adapter, int idx)
{
struct cpl_smt_write_req *req;
struct port_info *pi = netdev_priv(adapter->port[idx]);
struct sk_buff *skb = alloc_skb(sizeof(*req), GFP_KERNEL);
if (!skb)
return -ENOMEM;
req = (struct cpl_smt_write_req *)__skb_put(skb, sizeof(*req));
req->wr.wr_hi = htonl(V_WR_OP(FW_WROPCODE_FORWARD));
OPCODE_TID(req) = htonl(MK_OPCODE_TID(CPL_SMT_WRITE_REQ, idx));
req->mtu_idx = NMTUS - 1; /* should be 0 but there's a T3 bug */
req->iff = idx;
memcpy(req->src_mac0, adapter->port[idx]->dev_addr, ETH_ALEN);
memcpy(req->src_mac1, pi->iscsic.mac_addr, ETH_ALEN);
skb->priority = 1;
offload_tx(&adapter->tdev, skb);
return 0;
}
static int init_smt(struct adapter *adapter)
{
int i;
for_each_port(adapter, i)
write_smt_entry(adapter, i);
return 0;
}
static void init_port_mtus(struct adapter *adapter)
{
unsigned int mtus = adapter->port[0]->mtu;
if (adapter->port[1])
mtus |= adapter->port[1]->mtu << 16;
t3_write_reg(adapter, A_TP_MTU_PORT_TABLE, mtus);
}
static int send_pktsched_cmd(struct adapter *adap, int sched, int qidx, int lo,
int hi, int port)
{
struct sk_buff *skb;
struct mngt_pktsched_wr *req;
int ret;
skb = alloc_skb(sizeof(*req), GFP_KERNEL);
if (!skb)
skb = adap->nofail_skb;
if (!skb)
return -ENOMEM;
req = (struct mngt_pktsched_wr *)skb_put(skb, sizeof(*req));
req->wr_hi = htonl(V_WR_OP(FW_WROPCODE_MNGT));
req->mngt_opcode = FW_MNGTOPCODE_PKTSCHED_SET;
req->sched = sched;
req->idx = qidx;
req->min = lo;
req->max = hi;
req->binding = port;
ret = t3_mgmt_tx(adap, skb);
if (skb == adap->nofail_skb) {
adap->nofail_skb = alloc_skb(sizeof(struct cpl_set_tcb_field),
GFP_KERNEL);
if (!adap->nofail_skb)
ret = -ENOMEM;
}
return ret;
}
static int bind_qsets(struct adapter *adap)
{
int i, j, err = 0;
for_each_port(adap, i) {
const struct port_info *pi = adap2pinfo(adap, i);
for (j = 0; j < pi->nqsets; ++j) {
int ret = send_pktsched_cmd(adap, 1,
pi->first_qset + j, -1,
-1, i);
if (ret)
err = ret;
}
}
return err;
}
#define FW_VERSION __stringify(FW_VERSION_MAJOR) "." \
__stringify(FW_VERSION_MINOR) "." __stringify(FW_VERSION_MICRO)
#define FW_FNAME "cxgb3/t3fw-" FW_VERSION ".bin"
#define TPSRAM_VERSION __stringify(TP_VERSION_MAJOR) "." \
__stringify(TP_VERSION_MINOR) "." __stringify(TP_VERSION_MICRO)
#define TPSRAM_NAME "cxgb3/t3%c_psram-" TPSRAM_VERSION ".bin"
#define AEL2005_OPT_EDC_NAME "cxgb3/ael2005_opt_edc.bin"
#define AEL2005_TWX_EDC_NAME "cxgb3/ael2005_twx_edc.bin"
#define AEL2020_TWX_EDC_NAME "cxgb3/ael2020_twx_edc.bin"
MODULE_FIRMWARE(FW_FNAME);
MODULE_FIRMWARE("cxgb3/t3b_psram-" TPSRAM_VERSION ".bin");
MODULE_FIRMWARE("cxgb3/t3c_psram-" TPSRAM_VERSION ".bin");
MODULE_FIRMWARE(AEL2005_OPT_EDC_NAME);
MODULE_FIRMWARE(AEL2005_TWX_EDC_NAME);
MODULE_FIRMWARE(AEL2020_TWX_EDC_NAME);
static inline const char *get_edc_fw_name(int edc_idx)
{
const char *fw_name = NULL;
switch (edc_idx) {
case EDC_OPT_AEL2005:
fw_name = AEL2005_OPT_EDC_NAME;
break;
case EDC_TWX_AEL2005:
fw_name = AEL2005_TWX_EDC_NAME;
break;
case EDC_TWX_AEL2020:
fw_name = AEL2020_TWX_EDC_NAME;
break;
}
return fw_name;
}
int t3_get_edc_fw(struct cphy *phy, int edc_idx, int size)
{
struct adapter *adapter = phy->adapter;
const struct firmware *fw;
char buf[64];
u32 csum;
const __be32 *p;
u16 *cache = phy->phy_cache;
int i, ret;
snprintf(buf, sizeof(buf), get_edc_fw_name(edc_idx));
ret = request_firmware(&fw, buf, &adapter->pdev->dev);
if (ret < 0) {
dev_err(&adapter->pdev->dev,
"could not upgrade firmware: unable to load %s\n",
buf);
return ret;
}
/* check size, take checksum in account */
if (fw->size > size + 4) {
CH_ERR(adapter, "firmware image too large %u, expected %d\n",
(unsigned int)fw->size, size + 4);
ret = -EINVAL;
}
/* compute checksum */
p = (const __be32 *)fw->data;
for (csum = 0, i = 0; i < fw->size / sizeof(csum); i++)
csum += ntohl(p[i]);
if (csum != 0xffffffff) {
CH_ERR(adapter, "corrupted firmware image, checksum %u\n",
csum);
ret = -EINVAL;
}
for (i = 0; i < size / 4 ; i++) {
*cache++ = (be32_to_cpu(p[i]) & 0xffff0000) >> 16;
*cache++ = be32_to_cpu(p[i]) & 0xffff;
}
release_firmware(fw);
return ret;
}
static int upgrade_fw(struct adapter *adap)
{
int ret;
const struct firmware *fw;
struct device *dev = &adap->pdev->dev;
ret = request_firmware(&fw, FW_FNAME, dev);
if (ret < 0) {
dev_err(dev, "could not upgrade firmware: unable to load %s\n",
FW_FNAME);
return ret;
}
ret = t3_load_fw(adap, fw->data, fw->size);
release_firmware(fw);
if (ret == 0)
dev_info(dev, "successful upgrade to firmware %d.%d.%d\n",
FW_VERSION_MAJOR, FW_VERSION_MINOR, FW_VERSION_MICRO);
else
dev_err(dev, "failed to upgrade to firmware %d.%d.%d\n",
FW_VERSION_MAJOR, FW_VERSION_MINOR, FW_VERSION_MICRO);
return ret;
}
static inline char t3rev2char(struct adapter *adapter)
{
char rev = 0;
switch(adapter->params.rev) {
case T3_REV_B:
case T3_REV_B2:
rev = 'b';
break;
case T3_REV_C:
rev = 'c';
break;
}
return rev;
}
static int update_tpsram(struct adapter *adap)
{
const struct firmware *tpsram;
char buf[64];
struct device *dev = &adap->pdev->dev;
int ret;
char rev;
rev = t3rev2char(adap);
if (!rev)
return 0;
snprintf(buf, sizeof(buf), TPSRAM_NAME, rev);
ret = request_firmware(&tpsram, buf, dev);
if (ret < 0) {
dev_err(dev, "could not load TP SRAM: unable to load %s\n",
buf);
return ret;
}
ret = t3_check_tpsram(adap, tpsram->data, tpsram->size);
if (ret)
goto release_tpsram;
ret = t3_set_proto_sram(adap, tpsram->data);
if (ret == 0)
dev_info(dev,
"successful update of protocol engine "
"to %d.%d.%d\n",
TP_VERSION_MAJOR, TP_VERSION_MINOR, TP_VERSION_MICRO);
else
dev_err(dev, "failed to update of protocol engine %d.%d.%d\n",
TP_VERSION_MAJOR, TP_VERSION_MINOR, TP_VERSION_MICRO);
if (ret)
dev_err(dev, "loading protocol SRAM failed\n");
release_tpsram:
release_firmware(tpsram);
return ret;
}
/**
* cxgb_up - enable the adapter
* @adapter: adapter being enabled
*
* Called when the first port is enabled, this function performs the
* actions necessary to make an adapter operational, such as completing
* the initialization of HW modules, and enabling interrupts.
*
* Must be called with the rtnl lock held.
*/
static int cxgb_up(struct adapter *adap)
{
int err;
if (!(adap->flags & FULL_INIT_DONE)) {
err = t3_check_fw_version(adap);
if (err == -EINVAL) {
err = upgrade_fw(adap);
CH_WARN(adap, "FW upgrade to %d.%d.%d %s\n",
FW_VERSION_MAJOR, FW_VERSION_MINOR,
FW_VERSION_MICRO, err ? "failed" : "succeeded");
}
err = t3_check_tpsram_version(adap);
if (err == -EINVAL) {
err = update_tpsram(adap);
CH_WARN(adap, "TP upgrade to %d.%d.%d %s\n",
TP_VERSION_MAJOR, TP_VERSION_MINOR,
TP_VERSION_MICRO, err ? "failed" : "succeeded");
}
/*
* Clear interrupts now to catch errors if t3_init_hw fails.
* We clear them again later as initialization may trigger
* conditions that can interrupt.
*/
t3_intr_clear(adap);
err = t3_init_hw(adap, 0);
if (err)
goto out;
t3_set_reg_field(adap, A_TP_PARA_REG5, 0, F_RXDDPOFFINIT);
t3_write_reg(adap, A_ULPRX_TDDP_PSZ, V_HPZ0(PAGE_SHIFT - 12));
err = setup_sge_qsets(adap);
if (err)
goto out;
setup_rss(adap);
if (!(adap->flags & NAPI_INIT))
init_napi(adap);
t3_start_sge_timers(adap);
adap->flags |= FULL_INIT_DONE;
}
t3_intr_clear(adap);
if (adap->flags & USING_MSIX) {
name_msix_vecs(adap);
err = request_irq(adap->msix_info[0].vec,
t3_async_intr_handler, 0,
adap->msix_info[0].desc, adap);
if (err)
goto irq_err;
err = request_msix_data_irqs(adap);
if (err) {
free_irq(adap->msix_info[0].vec, adap);
goto irq_err;
}
} else if ((err = request_irq(adap->pdev->irq,
t3_intr_handler(adap,
adap->sge.qs[0].rspq.
polling),
(adap->flags & USING_MSI) ?
0 : IRQF_SHARED,
adap->name, adap)))
goto irq_err;
enable_all_napi(adap);
t3_sge_start(adap);
t3_intr_enable(adap);
if (adap->params.rev >= T3_REV_C && !(adap->flags & TP_PARITY_INIT) &&
is_offload(adap) && init_tp_parity(adap) == 0)
adap->flags |= TP_PARITY_INIT;
if (adap->flags & TP_PARITY_INIT) {
t3_write_reg(adap, A_TP_INT_CAUSE,
F_CMCACHEPERR | F_ARPLUTPERR);
t3_write_reg(adap, A_TP_INT_ENABLE, 0x7fbfffff);
}
if (!(adap->flags & QUEUES_BOUND)) {
int ret = bind_qsets(adap);
if (ret < 0) {
CH_ERR(adap, "failed to bind qsets, err %d\n", ret);
t3_intr_disable(adap);
free_irq_resources(adap);
err = ret;
goto out;
}
adap->flags |= QUEUES_BOUND;
}
out:
return err;
irq_err:
CH_ERR(adap, "request_irq failed, err %d\n", err);
goto out;
}
/*
* Release resources when all the ports and offloading have been stopped.
*/
static void cxgb_down(struct adapter *adapter, int on_wq)
{
t3_sge_stop(adapter);
spin_lock_irq(&adapter->work_lock); /* sync with PHY intr task */
t3_intr_disable(adapter);
spin_unlock_irq(&adapter->work_lock);
free_irq_resources(adapter);
quiesce_rx(adapter);
t3_sge_stop(adapter);
if (!on_wq)
flush_workqueue(cxgb3_wq);/* wait for external IRQ handler */
}
static void schedule_chk_task(struct adapter *adap)
{
unsigned int timeo;
timeo = adap->params.linkpoll_period ?
(HZ * adap->params.linkpoll_period) / 10 :
adap->params.stats_update_period * HZ;
if (timeo)
queue_delayed_work(cxgb3_wq, &adap->adap_check_task, timeo);
}
static int offload_open(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
struct t3cdev *tdev = dev2t3cdev(dev);
int adap_up = adapter->open_device_map & PORT_MASK;
int err;
if (test_and_set_bit(OFFLOAD_DEVMAP_BIT, &adapter->open_device_map))
return 0;
if (!adap_up && (err = cxgb_up(adapter)) < 0)
goto out;
t3_tp_set_offload_mode(adapter, 1);
tdev->lldev = adapter->port[0];
err = cxgb3_offload_activate(adapter);
if (err)
goto out;
init_port_mtus(adapter);
t3_load_mtus(adapter, adapter->params.mtus, adapter->params.a_wnd,
adapter->params.b_wnd,
adapter->params.rev == 0 ?
adapter->port[0]->mtu : 0xffff);
init_smt(adapter);
if (sysfs_create_group(&tdev->lldev->dev.kobj, &offload_attr_group))
dev_dbg(&dev->dev, "cannot create sysfs group\n");
/* Call back all registered clients */
cxgb3_add_clients(tdev);
out:
/* restore them in case the offload module has changed them */
if (err) {
t3_tp_set_offload_mode(adapter, 0);
clear_bit(OFFLOAD_DEVMAP_BIT, &adapter->open_device_map);
cxgb3_set_dummy_ops(tdev);
}
return err;
}
static int offload_close(struct t3cdev *tdev)
{
struct adapter *adapter = tdev2adap(tdev);
struct t3c_data *td = T3C_DATA(tdev);
if (!test_bit(OFFLOAD_DEVMAP_BIT, &adapter->open_device_map))
return 0;
/* Call back all registered clients */
cxgb3_remove_clients(tdev);
sysfs_remove_group(&tdev->lldev->dev.kobj, &offload_attr_group);
/* Flush work scheduled while releasing TIDs */
flush_work_sync(&td->tid_release_task);
tdev->lldev = NULL;
cxgb3_set_dummy_ops(tdev);
t3_tp_set_offload_mode(adapter, 0);
clear_bit(OFFLOAD_DEVMAP_BIT, &adapter->open_device_map);
if (!adapter->open_device_map)
cxgb_down(adapter, 0);
cxgb3_offload_deactivate(adapter);
return 0;
}
static int cxgb_open(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
int other_ports = adapter->open_device_map & PORT_MASK;
int err;
if (!adapter->open_device_map && (err = cxgb_up(adapter)) < 0)
return err;
set_bit(pi->port_id, &adapter->open_device_map);
if (is_offload(adapter) && !ofld_disable) {
err = offload_open(dev);
if (err)
printk(KERN_WARNING
"Could not initialize offload capabilities\n");
}
netif_set_real_num_tx_queues(dev, pi->nqsets);
err = netif_set_real_num_rx_queues(dev, pi->nqsets);
if (err)
return err;
link_start(dev);
t3_port_intr_enable(adapter, pi->port_id);
netif_tx_start_all_queues(dev);
if (!other_ports)
schedule_chk_task(adapter);
cxgb3_event_notify(&adapter->tdev, OFFLOAD_PORT_UP, pi->port_id);
return 0;
}
static int __cxgb_close(struct net_device *dev, int on_wq)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
if (!adapter->open_device_map)
return 0;
/* Stop link fault interrupts */
t3_xgm_intr_disable(adapter, pi->port_id);
t3_read_reg(adapter, A_XGM_INT_STATUS + pi->mac.offset);
t3_port_intr_disable(adapter, pi->port_id);
netif_tx_stop_all_queues(dev);
pi->phy.ops->power_down(&pi->phy, 1);
netif_carrier_off(dev);
t3_mac_disable(&pi->mac, MAC_DIRECTION_TX | MAC_DIRECTION_RX);
spin_lock_irq(&adapter->work_lock); /* sync with update task */
clear_bit(pi->port_id, &adapter->open_device_map);
spin_unlock_irq(&adapter->work_lock);
if (!(adapter->open_device_map & PORT_MASK))
cancel_delayed_work_sync(&adapter->adap_check_task);
if (!adapter->open_device_map)
cxgb_down(adapter, on_wq);
cxgb3_event_notify(&adapter->tdev, OFFLOAD_PORT_DOWN, pi->port_id);
return 0;
}
static int cxgb_close(struct net_device *dev)
{
return __cxgb_close(dev, 0);
}
static struct net_device_stats *cxgb_get_stats(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
struct net_device_stats *ns = &pi->netstats;
const struct mac_stats *pstats;
spin_lock(&adapter->stats_lock);
pstats = t3_mac_update_stats(&pi->mac);
spin_unlock(&adapter->stats_lock);
ns->tx_bytes = pstats->tx_octets;
ns->tx_packets = pstats->tx_frames;
ns->rx_bytes = pstats->rx_octets;
ns->rx_packets = pstats->rx_frames;
ns->multicast = pstats->rx_mcast_frames;
ns->tx_errors = pstats->tx_underrun;
ns->rx_errors = pstats->rx_symbol_errs + pstats->rx_fcs_errs +
pstats->rx_too_long + pstats->rx_jabber + pstats->rx_short +
pstats->rx_fifo_ovfl;
/* detailed rx_errors */
ns->rx_length_errors = pstats->rx_jabber + pstats->rx_too_long;
ns->rx_over_errors = 0;
ns->rx_crc_errors = pstats->rx_fcs_errs;
ns->rx_frame_errors = pstats->rx_symbol_errs;
ns->rx_fifo_errors = pstats->rx_fifo_ovfl;
ns->rx_missed_errors = pstats->rx_cong_drops;
/* detailed tx_errors */
ns->tx_aborted_errors = 0;
ns->tx_carrier_errors = 0;
ns->tx_fifo_errors = pstats->tx_underrun;
ns->tx_heartbeat_errors = 0;
ns->tx_window_errors = 0;
return ns;
}
static u32 get_msglevel(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
return adapter->msg_enable;
}
static void set_msglevel(struct net_device *dev, u32 val)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
adapter->msg_enable = val;
}
static char stats_strings[][ETH_GSTRING_LEN] = {
"TxOctetsOK ",
"TxFramesOK ",
"TxMulticastFramesOK",
"TxBroadcastFramesOK",
"TxPauseFrames ",
"TxUnderrun ",
"TxExtUnderrun ",
"TxFrames64 ",
"TxFrames65To127 ",
"TxFrames128To255 ",
"TxFrames256To511 ",
"TxFrames512To1023 ",
"TxFrames1024To1518 ",
"TxFrames1519ToMax ",
"RxOctetsOK ",
"RxFramesOK ",
"RxMulticastFramesOK",
"RxBroadcastFramesOK",
"RxPauseFrames ",
"RxFCSErrors ",
"RxSymbolErrors ",
"RxShortErrors ",
"RxJabberErrors ",
"RxLengthErrors ",
"RxFIFOoverflow ",
"RxFrames64 ",
"RxFrames65To127 ",
"RxFrames128To255 ",
"RxFrames256To511 ",
"RxFrames512To1023 ",
"RxFrames1024To1518 ",
"RxFrames1519ToMax ",
"PhyFIFOErrors ",
"TSO ",
"VLANextractions ",
"VLANinsertions ",
"TxCsumOffload ",
"RxCsumGood ",
"LroAggregated ",
"LroFlushed ",
"LroNoDesc ",
"RxDrops ",
"CheckTXEnToggled ",
"CheckResets ",
"LinkFaults ",
};
static int get_sset_count(struct net_device *dev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return ARRAY_SIZE(stats_strings);
default:
return -EOPNOTSUPP;
}
}
#define T3_REGMAP_SIZE (3 * 1024)
static int get_regs_len(struct net_device *dev)
{
return T3_REGMAP_SIZE;
}
static int get_eeprom_len(struct net_device *dev)
{
return EEPROMSIZE;
}
static void get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
u32 fw_vers = 0;
u32 tp_vers = 0;
spin_lock(&adapter->stats_lock);
t3_get_fw_version(adapter, &fw_vers);
t3_get_tp_version(adapter, &tp_vers);
spin_unlock(&adapter->stats_lock);
strcpy(info->driver, DRV_NAME);
strcpy(info->version, DRV_VERSION);
strcpy(info->bus_info, pci_name(adapter->pdev));
if (!fw_vers)
strcpy(info->fw_version, "N/A");
else {
snprintf(info->fw_version, sizeof(info->fw_version),
"%s %u.%u.%u TP %u.%u.%u",
G_FW_VERSION_TYPE(fw_vers) ? "T" : "N",
G_FW_VERSION_MAJOR(fw_vers),
G_FW_VERSION_MINOR(fw_vers),
G_FW_VERSION_MICRO(fw_vers),
G_TP_VERSION_MAJOR(tp_vers),
G_TP_VERSION_MINOR(tp_vers),
G_TP_VERSION_MICRO(tp_vers));
}
}
static void get_strings(struct net_device *dev, u32 stringset, u8 * data)
{
if (stringset == ETH_SS_STATS)
memcpy(data, stats_strings, sizeof(stats_strings));
}
static unsigned long collect_sge_port_stats(struct adapter *adapter,
struct port_info *p, int idx)
{
int i;
unsigned long tot = 0;
for (i = p->first_qset; i < p->first_qset + p->nqsets; ++i)
tot += adapter->sge.qs[i].port_stats[idx];
return tot;
}
static void get_stats(struct net_device *dev, struct ethtool_stats *stats,
u64 *data)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
const struct mac_stats *s;
spin_lock(&adapter->stats_lock);
s = t3_mac_update_stats(&pi->mac);
spin_unlock(&adapter->stats_lock);
*data++ = s->tx_octets;
*data++ = s->tx_frames;
*data++ = s->tx_mcast_frames;
*data++ = s->tx_bcast_frames;
*data++ = s->tx_pause;
*data++ = s->tx_underrun;
*data++ = s->tx_fifo_urun;
*data++ = s->tx_frames_64;
*data++ = s->tx_frames_65_127;
*data++ = s->tx_frames_128_255;
*data++ = s->tx_frames_256_511;
*data++ = s->tx_frames_512_1023;
*data++ = s->tx_frames_1024_1518;
*data++ = s->tx_frames_1519_max;
*data++ = s->rx_octets;
*data++ = s->rx_frames;
*data++ = s->rx_mcast_frames;
*data++ = s->rx_bcast_frames;
*data++ = s->rx_pause;
*data++ = s->rx_fcs_errs;
*data++ = s->rx_symbol_errs;
*data++ = s->rx_short;
*data++ = s->rx_jabber;
*data++ = s->rx_too_long;
*data++ = s->rx_fifo_ovfl;
*data++ = s->rx_frames_64;
*data++ = s->rx_frames_65_127;
*data++ = s->rx_frames_128_255;
*data++ = s->rx_frames_256_511;
*data++ = s->rx_frames_512_1023;
*data++ = s->rx_frames_1024_1518;
*data++ = s->rx_frames_1519_max;
*data++ = pi->phy.fifo_errors;
*data++ = collect_sge_port_stats(adapter, pi, SGE_PSTAT_TSO);
*data++ = collect_sge_port_stats(adapter, pi, SGE_PSTAT_VLANEX);
*data++ = collect_sge_port_stats(adapter, pi, SGE_PSTAT_VLANINS);
*data++ = collect_sge_port_stats(adapter, pi, SGE_PSTAT_TX_CSUM);
*data++ = collect_sge_port_stats(adapter, pi, SGE_PSTAT_RX_CSUM_GOOD);
*data++ = 0;
*data++ = 0;
*data++ = 0;
*data++ = s->rx_cong_drops;
*data++ = s->num_toggled;
*data++ = s->num_resets;
*data++ = s->link_faults;
}
static inline void reg_block_dump(struct adapter *ap, void *buf,
unsigned int start, unsigned int end)
{
u32 *p = buf + start;
for (; start <= end; start += sizeof(u32))
*p++ = t3_read_reg(ap, start);
}
static void get_regs(struct net_device *dev, struct ethtool_regs *regs,
void *buf)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *ap = pi->adapter;
/*
* Version scheme:
* bits 0..9: chip version
* bits 10..15: chip revision
* bit 31: set for PCIe cards
*/
regs->version = 3 | (ap->params.rev << 10) | (is_pcie(ap) << 31);
/*
* We skip the MAC statistics registers because they are clear-on-read.
* Also reading multi-register stats would need to synchronize with the
* periodic mac stats accumulation. Hard to justify the complexity.
*/
memset(buf, 0, T3_REGMAP_SIZE);
reg_block_dump(ap, buf, 0, A_SG_RSPQ_CREDIT_RETURN);
reg_block_dump(ap, buf, A_SG_HI_DRB_HI_THRSH, A_ULPRX_PBL_ULIMIT);
reg_block_dump(ap, buf, A_ULPTX_CONFIG, A_MPS_INT_CAUSE);
reg_block_dump(ap, buf, A_CPL_SWITCH_CNTRL, A_CPL_MAP_TBL_DATA);
reg_block_dump(ap, buf, A_SMB_GLOBAL_TIME_CFG, A_XGM_SERDES_STAT3);
reg_block_dump(ap, buf, A_XGM_SERDES_STATUS0,
XGM_REG(A_XGM_SERDES_STAT3, 1));
reg_block_dump(ap, buf, XGM_REG(A_XGM_SERDES_STATUS0, 1),
XGM_REG(A_XGM_RX_SPI4_SOP_EOP_CNT, 1));
}
static int restart_autoneg(struct net_device *dev)
{
struct port_info *p = netdev_priv(dev);
if (!netif_running(dev))
return -EAGAIN;
if (p->link_config.autoneg != AUTONEG_ENABLE)
return -EINVAL;
p->phy.ops->autoneg_restart(&p->phy);
return 0;
}
static int set_phys_id(struct net_device *dev,
enum ethtool_phys_id_state state)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
switch (state) {
case ETHTOOL_ID_ACTIVE:
return 1; /* cycle on/off once per second */
case ETHTOOL_ID_OFF:
t3_set_reg_field(adapter, A_T3DBG_GPIO_EN, F_GPIO0_OUT_VAL, 0);
break;
case ETHTOOL_ID_ON:
case ETHTOOL_ID_INACTIVE:
t3_set_reg_field(adapter, A_T3DBG_GPIO_EN, F_GPIO0_OUT_VAL,
F_GPIO0_OUT_VAL);
}
return 0;
}
static int get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct port_info *p = netdev_priv(dev);
cmd->supported = p->link_config.supported;
cmd->advertising = p->link_config.advertising;
if (netif_carrier_ok(dev)) {
ethtool_cmd_speed_set(cmd, p->link_config.speed);
cmd->duplex = p->link_config.duplex;
} else {
ethtool_cmd_speed_set(cmd, -1);
cmd->duplex = -1;
}
cmd->port = (cmd->supported & SUPPORTED_TP) ? PORT_TP : PORT_FIBRE;
cmd->phy_address = p->phy.mdio.prtad;
cmd->transceiver = XCVR_EXTERNAL;
cmd->autoneg = p->link_config.autoneg;
cmd->maxtxpkt = 0;
cmd->maxrxpkt = 0;
return 0;
}
static int speed_duplex_to_caps(int speed, int duplex)
{
int cap = 0;
switch (speed) {
case SPEED_10:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_10baseT_Full;
else
cap = SUPPORTED_10baseT_Half;
break;
case SPEED_100:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_100baseT_Full;
else
cap = SUPPORTED_100baseT_Half;
break;
case SPEED_1000:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_1000baseT_Full;
else
cap = SUPPORTED_1000baseT_Half;
break;
case SPEED_10000:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_10000baseT_Full;
}
return cap;
}
#define ADVERTISED_MASK (ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full | \
ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full | \
ADVERTISED_1000baseT_Half | ADVERTISED_1000baseT_Full | \
ADVERTISED_10000baseT_Full)
static int set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct port_info *p = netdev_priv(dev);
struct link_config *lc = &p->link_config;
if (!(lc->supported & SUPPORTED_Autoneg)) {
/*
* PHY offers a single speed/duplex. See if that's what's
* being requested.
*/
if (cmd->autoneg == AUTONEG_DISABLE) {
u32 speed = ethtool_cmd_speed(cmd);
int cap = speed_duplex_to_caps(speed, cmd->duplex);
if (lc->supported & cap)
return 0;
}
return -EINVAL;
}
if (cmd->autoneg == AUTONEG_DISABLE) {
u32 speed = ethtool_cmd_speed(cmd);
int cap = speed_duplex_to_caps(speed, cmd->duplex);
if (!(lc->supported & cap) || (speed == SPEED_1000))
return -EINVAL;
lc->requested_speed = speed;
lc->requested_duplex = cmd->duplex;
lc->advertising = 0;
} else {
cmd->advertising &= ADVERTISED_MASK;
cmd->advertising &= lc->supported;
if (!cmd->advertising)
return -EINVAL;
lc->requested_speed = SPEED_INVALID;
lc->requested_duplex = DUPLEX_INVALID;
lc->advertising = cmd->advertising | ADVERTISED_Autoneg;
}
lc->autoneg = cmd->autoneg;
if (netif_running(dev))
t3_link_start(&p->phy, &p->mac, lc);
return 0;
}
static void get_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct port_info *p = netdev_priv(dev);
epause->autoneg = (p->link_config.requested_fc & PAUSE_AUTONEG) != 0;
epause->rx_pause = (p->link_config.fc & PAUSE_RX) != 0;
epause->tx_pause = (p->link_config.fc & PAUSE_TX) != 0;
}
static int set_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct port_info *p = netdev_priv(dev);
struct link_config *lc = &p->link_config;
if (epause->autoneg == AUTONEG_DISABLE)
lc->requested_fc = 0;
else if (lc->supported & SUPPORTED_Autoneg)
lc->requested_fc = PAUSE_AUTONEG;
else
return -EINVAL;
if (epause->rx_pause)
lc->requested_fc |= PAUSE_RX;
if (epause->tx_pause)
lc->requested_fc |= PAUSE_TX;
if (lc->autoneg == AUTONEG_ENABLE) {
if (netif_running(dev))
t3_link_start(&p->phy, &p->mac, lc);
} else {
lc->fc = lc->requested_fc & (PAUSE_RX | PAUSE_TX);
if (netif_running(dev))
t3_mac_set_speed_duplex_fc(&p->mac, -1, -1, lc->fc);
}
return 0;
}
static void get_sge_param(struct net_device *dev, struct ethtool_ringparam *e)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
const struct qset_params *q = &adapter->params.sge.qset[pi->first_qset];
e->rx_max_pending = MAX_RX_BUFFERS;
e->rx_mini_max_pending = 0;
e->rx_jumbo_max_pending = MAX_RX_JUMBO_BUFFERS;
e->tx_max_pending = MAX_TXQ_ENTRIES;
e->rx_pending = q->fl_size;
e->rx_mini_pending = q->rspq_size;
e->rx_jumbo_pending = q->jumbo_size;
e->tx_pending = q->txq_size[0];
}
static int set_sge_param(struct net_device *dev, struct ethtool_ringparam *e)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
struct qset_params *q;
int i;
if (e->rx_pending > MAX_RX_BUFFERS ||
e->rx_jumbo_pending > MAX_RX_JUMBO_BUFFERS ||
e->tx_pending > MAX_TXQ_ENTRIES ||
e->rx_mini_pending > MAX_RSPQ_ENTRIES ||
e->rx_mini_pending < MIN_RSPQ_ENTRIES ||
e->rx_pending < MIN_FL_ENTRIES ||
e->rx_jumbo_pending < MIN_FL_ENTRIES ||
e->tx_pending < adapter->params.nports * MIN_TXQ_ENTRIES)
return -EINVAL;
if (adapter->flags & FULL_INIT_DONE)
return -EBUSY;
q = &adapter->params.sge.qset[pi->first_qset];
for (i = 0; i < pi->nqsets; ++i, ++q) {
q->rspq_size = e->rx_mini_pending;
q->fl_size = e->rx_pending;
q->jumbo_size = e->rx_jumbo_pending;
q->txq_size[0] = e->tx_pending;
q->txq_size[1] = e->tx_pending;
q->txq_size[2] = e->tx_pending;
}
return 0;
}
static int set_coalesce(struct net_device *dev, struct ethtool_coalesce *c)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
struct qset_params *qsp;
struct sge_qset *qs;
int i;
if (c->rx_coalesce_usecs * 10 > M_NEWTIMER)
return -EINVAL;
for (i = 0; i < pi->nqsets; i++) {
qsp = &adapter->params.sge.qset[i];
qs = &adapter->sge.qs[i];
qsp->coalesce_usecs = c->rx_coalesce_usecs;
t3_update_qset_coalesce(qs, qsp);
}
return 0;
}
static int get_coalesce(struct net_device *dev, struct ethtool_coalesce *c)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
struct qset_params *q = adapter->params.sge.qset;
c->rx_coalesce_usecs = q->coalesce_usecs;
return 0;
}
static int get_eeprom(struct net_device *dev, struct ethtool_eeprom *e,
u8 * data)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
int i, err = 0;
u8 *buf = kmalloc(EEPROMSIZE, GFP_KERNEL);
if (!buf)
return -ENOMEM;
e->magic = EEPROM_MAGIC;
for (i = e->offset & ~3; !err && i < e->offset + e->len; i += 4)
err = t3_seeprom_read(adapter, i, (__le32 *) & buf[i]);
if (!err)
memcpy(data, buf + e->offset, e->len);
kfree(buf);
return err;
}
static int set_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom,
u8 * data)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
u32 aligned_offset, aligned_len;
__le32 *p;
u8 *buf;
int err;
if (eeprom->magic != EEPROM_MAGIC)
return -EINVAL;
aligned_offset = eeprom->offset & ~3;
aligned_len = (eeprom->len + (eeprom->offset & 3) + 3) & ~3;
if (aligned_offset != eeprom->offset || aligned_len != eeprom->len) {
buf = kmalloc(aligned_len, GFP_KERNEL);
if (!buf)
return -ENOMEM;
err = t3_seeprom_read(adapter, aligned_offset, (__le32 *) buf);
if (!err && aligned_len > 4)
err = t3_seeprom_read(adapter,
aligned_offset + aligned_len - 4,
(__le32 *) & buf[aligned_len - 4]);
if (err)
goto out;
memcpy(buf + (eeprom->offset & 3), data, eeprom->len);
} else
buf = data;
err = t3_seeprom_wp(adapter, 0);
if (err)
goto out;
for (p = (__le32 *) buf; !err && aligned_len; aligned_len -= 4, p++) {
err = t3_seeprom_write(adapter, aligned_offset, *p);
aligned_offset += 4;
}
if (!err)
err = t3_seeprom_wp(adapter, 1);
out:
if (buf != data)
kfree(buf);
return err;
}
static void get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
wol->supported = 0;
wol->wolopts = 0;
memset(&wol->sopass, 0, sizeof(wol->sopass));
}
static const struct ethtool_ops cxgb_ethtool_ops = {
.get_settings = get_settings,
.set_settings = set_settings,
.get_drvinfo = get_drvinfo,
.get_msglevel = get_msglevel,
.set_msglevel = set_msglevel,
.get_ringparam = get_sge_param,
.set_ringparam = set_sge_param,
.get_coalesce = get_coalesce,
.set_coalesce = set_coalesce,
.get_eeprom_len = get_eeprom_len,
.get_eeprom = get_eeprom,
.set_eeprom = set_eeprom,
.get_pauseparam = get_pauseparam,
.set_pauseparam = set_pauseparam,
.get_link = ethtool_op_get_link,
.get_strings = get_strings,
.set_phys_id = set_phys_id,
.nway_reset = restart_autoneg,
.get_sset_count = get_sset_count,
.get_ethtool_stats = get_stats,
.get_regs_len = get_regs_len,
.get_regs = get_regs,
.get_wol = get_wol,
};
static int in_range(int val, int lo, int hi)
{
return val < 0 || (val <= hi && val >= lo);
}
static int cxgb_extension_ioctl(struct net_device *dev, void __user *useraddr)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
u32 cmd;
int ret;
if (copy_from_user(&cmd, useraddr, sizeof(cmd)))
return -EFAULT;
switch (cmd) {
case CHELSIO_SET_QSET_PARAMS:{
int i;
struct qset_params *q;
struct ch_qset_params t;
int q1 = pi->first_qset;
int nqsets = pi->nqsets;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&t, useraddr, sizeof(t)))
return -EFAULT;
if (t.qset_idx >= SGE_QSETS)
return -EINVAL;
if (!in_range(t.intr_lat, 0, M_NEWTIMER) ||
!in_range(t.cong_thres, 0, 255) ||
!in_range(t.txq_size[0], MIN_TXQ_ENTRIES,
MAX_TXQ_ENTRIES) ||
!in_range(t.txq_size[1], MIN_TXQ_ENTRIES,
MAX_TXQ_ENTRIES) ||
!in_range(t.txq_size[2], MIN_CTRL_TXQ_ENTRIES,
MAX_CTRL_TXQ_ENTRIES) ||
!in_range(t.fl_size[0], MIN_FL_ENTRIES,
MAX_RX_BUFFERS) ||
!in_range(t.fl_size[1], MIN_FL_ENTRIES,
MAX_RX_JUMBO_BUFFERS) ||
!in_range(t.rspq_size, MIN_RSPQ_ENTRIES,
MAX_RSPQ_ENTRIES))
return -EINVAL;
if ((adapter->flags & FULL_INIT_DONE) &&
(t.rspq_size >= 0 || t.fl_size[0] >= 0 ||
t.fl_size[1] >= 0 || t.txq_size[0] >= 0 ||
t.txq_size[1] >= 0 || t.txq_size[2] >= 0 ||
t.polling >= 0 || t.cong_thres >= 0))
return -EBUSY;
/* Allow setting of any available qset when offload enabled */
if (test_bit(OFFLOAD_DEVMAP_BIT, &adapter->open_device_map)) {
q1 = 0;
for_each_port(adapter, i) {
pi = adap2pinfo(adapter, i);
nqsets += pi->first_qset + pi->nqsets;
}
}
if (t.qset_idx < q1)
return -EINVAL;
if (t.qset_idx > q1 + nqsets - 1)
return -EINVAL;
q = &adapter->params.sge.qset[t.qset_idx];
if (t.rspq_size >= 0)
q->rspq_size = t.rspq_size;
if (t.fl_size[0] >= 0)
q->fl_size = t.fl_size[0];
if (t.fl_size[1] >= 0)
q->jumbo_size = t.fl_size[1];
if (t.txq_size[0] >= 0)
q->txq_size[0] = t.txq_size[0];
if (t.txq_size[1] >= 0)
q->txq_size[1] = t.txq_size[1];
if (t.txq_size[2] >= 0)
q->txq_size[2] = t.txq_size[2];
if (t.cong_thres >= 0)
q->cong_thres = t.cong_thres;
if (t.intr_lat >= 0) {
struct sge_qset *qs =
&adapter->sge.qs[t.qset_idx];
q->coalesce_usecs = t.intr_lat;
t3_update_qset_coalesce(qs, q);
}
if (t.polling >= 0) {
if (adapter->flags & USING_MSIX)
q->polling = t.polling;
else {
/* No polling with INTx for T3A */
if (adapter->params.rev == 0 &&
!(adapter->flags & USING_MSI))
t.polling = 0;
for (i = 0; i < SGE_QSETS; i++) {
q = &adapter->params.sge.
qset[i];
q->polling = t.polling;
}
}
}
if (t.lro >= 0) {
if (t.lro)
dev->wanted_features |= NETIF_F_GRO;
else
dev->wanted_features &= ~NETIF_F_GRO;
netdev_update_features(dev);
}
break;
}
case CHELSIO_GET_QSET_PARAMS:{
struct qset_params *q;
struct ch_qset_params t;
int q1 = pi->first_qset;
int nqsets = pi->nqsets;
int i;
if (copy_from_user(&t, useraddr, sizeof(t)))
return -EFAULT;
/* Display qsets for all ports when offload enabled */
if (test_bit(OFFLOAD_DEVMAP_BIT, &adapter->open_device_map)) {
q1 = 0;
for_each_port(adapter, i) {
pi = adap2pinfo(adapter, i);
nqsets = pi->first_qset + pi->nqsets;
}
}
if (t.qset_idx >= nqsets)
return -EINVAL;
q = &adapter->params.sge.qset[q1 + t.qset_idx];
t.rspq_size = q->rspq_size;
t.txq_size[0] = q->txq_size[0];
t.txq_size[1] = q->txq_size[1];
t.txq_size[2] = q->txq_size[2];
t.fl_size[0] = q->fl_size;
t.fl_size[1] = q->jumbo_size;
t.polling = q->polling;
t.lro = !!(dev->features & NETIF_F_GRO);
t.intr_lat = q->coalesce_usecs;
t.cong_thres = q->cong_thres;
t.qnum = q1;
if (adapter->flags & USING_MSIX)
t.vector = adapter->msix_info[q1 + t.qset_idx + 1].vec;
else
t.vector = adapter->pdev->irq;
if (copy_to_user(useraddr, &t, sizeof(t)))
return -EFAULT;
break;
}
case CHELSIO_SET_QSET_NUM:{
struct ch_reg edata;
unsigned int i, first_qset = 0, other_qsets = 0;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (adapter->flags & FULL_INIT_DONE)
return -EBUSY;
if (copy_from_user(&edata, useraddr, sizeof(edata)))
return -EFAULT;
if (edata.val < 1 ||
(edata.val > 1 && !(adapter->flags & USING_MSIX)))
return -EINVAL;
for_each_port(adapter, i)
if (adapter->port[i] && adapter->port[i] != dev)
other_qsets += adap2pinfo(adapter, i)->nqsets;
if (edata.val + other_qsets > SGE_QSETS)
return -EINVAL;
pi->nqsets = edata.val;
for_each_port(adapter, i)
if (adapter->port[i]) {
pi = adap2pinfo(adapter, i);
pi->first_qset = first_qset;
first_qset += pi->nqsets;
}
break;
}
case CHELSIO_GET_QSET_NUM:{
struct ch_reg edata;
memset(&edata, 0, sizeof(struct ch_reg));
edata.cmd = CHELSIO_GET_QSET_NUM;
edata.val = pi->nqsets;
if (copy_to_user(useraddr, &edata, sizeof(edata)))
return -EFAULT;
break;
}
case CHELSIO_LOAD_FW:{
u8 *fw_data;
struct ch_mem_range t;
if (!capable(CAP_SYS_RAWIO))
return -EPERM;
if (copy_from_user(&t, useraddr, sizeof(t)))
return -EFAULT;
/* Check t.len sanity ? */
fw_data = memdup_user(useraddr + sizeof(t), t.len);
if (IS_ERR(fw_data))
return PTR_ERR(fw_data);
ret = t3_load_fw(adapter, fw_data, t.len);
kfree(fw_data);
if (ret)
return ret;
break;
}
case CHELSIO_SETMTUTAB:{
struct ch_mtus m;
int i;
if (!is_offload(adapter))
return -EOPNOTSUPP;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (offload_running(adapter))
return -EBUSY;
if (copy_from_user(&m, useraddr, sizeof(m)))
return -EFAULT;
if (m.nmtus != NMTUS)
return -EINVAL;
if (m.mtus[0] < 81) /* accommodate SACK */
return -EINVAL;
/* MTUs must be in ascending order */
for (i = 1; i < NMTUS; ++i)
if (m.mtus[i] < m.mtus[i - 1])
return -EINVAL;
memcpy(adapter->params.mtus, m.mtus,
sizeof(adapter->params.mtus));
break;
}
case CHELSIO_GET_PM:{
struct tp_params *p = &adapter->params.tp;
struct ch_pm m = {.cmd = CHELSIO_GET_PM };
if (!is_offload(adapter))
return -EOPNOTSUPP;
m.tx_pg_sz = p->tx_pg_size;
m.tx_num_pg = p->tx_num_pgs;
m.rx_pg_sz = p->rx_pg_size;
m.rx_num_pg = p->rx_num_pgs;
m.pm_total = p->pmtx_size + p->chan_rx_size * p->nchan;
if (copy_to_user(useraddr, &m, sizeof(m)))
return -EFAULT;
break;
}
case CHELSIO_SET_PM:{
struct ch_pm m;
struct tp_params *p = &adapter->params.tp;
if (!is_offload(adapter))
return -EOPNOTSUPP;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (adapter->flags & FULL_INIT_DONE)
return -EBUSY;
if (copy_from_user(&m, useraddr, sizeof(m)))
return -EFAULT;
if (!is_power_of_2(m.rx_pg_sz) ||
!is_power_of_2(m.tx_pg_sz))
return -EINVAL; /* not power of 2 */
if (!(m.rx_pg_sz & 0x14000))
return -EINVAL; /* not 16KB or 64KB */
if (!(m.tx_pg_sz & 0x1554000))
return -EINVAL;
if (m.tx_num_pg == -1)
m.tx_num_pg = p->tx_num_pgs;
if (m.rx_num_pg == -1)
m.rx_num_pg = p->rx_num_pgs;
if (m.tx_num_pg % 24 || m.rx_num_pg % 24)
return -EINVAL;
if (m.rx_num_pg * m.rx_pg_sz > p->chan_rx_size ||
m.tx_num_pg * m.tx_pg_sz > p->chan_tx_size)
return -EINVAL;
p->rx_pg_size = m.rx_pg_sz;
p->tx_pg_size = m.tx_pg_sz;
p->rx_num_pgs = m.rx_num_pg;
p->tx_num_pgs = m.tx_num_pg;
break;
}
case CHELSIO_GET_MEM:{
struct ch_mem_range t;
struct mc7 *mem;
u64 buf[32];
if (!is_offload(adapter))
return -EOPNOTSUPP;
if (!(adapter->flags & FULL_INIT_DONE))
return -EIO; /* need the memory controllers */
if (copy_from_user(&t, useraddr, sizeof(t)))
return -EFAULT;
if ((t.addr & 7) || (t.len & 7))
return -EINVAL;
if (t.mem_id == MEM_CM)
mem = &adapter->cm;
else if (t.mem_id == MEM_PMRX)
mem = &adapter->pmrx;
else if (t.mem_id == MEM_PMTX)
mem = &adapter->pmtx;
else
return -EINVAL;
/*
* Version scheme:
* bits 0..9: chip version
* bits 10..15: chip revision
*/
t.version = 3 | (adapter->params.rev << 10);
if (copy_to_user(useraddr, &t, sizeof(t)))
return -EFAULT;
/*
* Read 256 bytes at a time as len can be large and we don't
* want to use huge intermediate buffers.
*/
useraddr += sizeof(t); /* advance to start of buffer */
while (t.len) {
unsigned int chunk =
min_t(unsigned int, t.len, sizeof(buf));
ret =
t3_mc7_bd_read(mem, t.addr / 8, chunk / 8,
buf);
if (ret)
return ret;
if (copy_to_user(useraddr, buf, chunk))
return -EFAULT;
useraddr += chunk;
t.addr += chunk;
t.len -= chunk;
}
break;
}
case CHELSIO_SET_TRACE_FILTER:{
struct ch_trace t;
const struct trace_params *tp;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (!offload_running(adapter))
return -EAGAIN;
if (copy_from_user(&t, useraddr, sizeof(t)))
return -EFAULT;
tp = (const struct trace_params *)&t.sip;
if (t.config_tx)
t3_config_trace_filter(adapter, tp, 0,
t.invert_match,
t.trace_tx);
if (t.config_rx)
t3_config_trace_filter(adapter, tp, 1,
t.invert_match,
t.trace_rx);
break;
}
default:
return -EOPNOTSUPP;
}
return 0;
}
static int cxgb_ioctl(struct net_device *dev, struct ifreq *req, int cmd)
{
struct mii_ioctl_data *data = if_mii(req);
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
switch (cmd) {
case SIOCGMIIREG:
case SIOCSMIIREG:
/* Convert phy_id from older PRTAD/DEVAD format */
if (is_10G(adapter) &&
!mdio_phy_id_is_c45(data->phy_id) &&
(data->phy_id & 0x1f00) &&
!(data->phy_id & 0xe0e0))
data->phy_id = mdio_phy_id_c45(data->phy_id >> 8,
data->phy_id & 0x1f);
/* FALLTHRU */
case SIOCGMIIPHY:
return mdio_mii_ioctl(&pi->phy.mdio, data, cmd);
case SIOCCHIOCTL:
return cxgb_extension_ioctl(dev, req->ifr_data);
default:
return -EOPNOTSUPP;
}
}
static int cxgb_change_mtu(struct net_device *dev, int new_mtu)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
int ret;
if (new_mtu < 81) /* accommodate SACK */
return -EINVAL;
if ((ret = t3_mac_set_mtu(&pi->mac, new_mtu)))
return ret;
dev->mtu = new_mtu;
init_port_mtus(adapter);
if (adapter->params.rev == 0 && offload_running(adapter))
t3_load_mtus(adapter, adapter->params.mtus,
adapter->params.a_wnd, adapter->params.b_wnd,
adapter->port[0]->mtu);
return 0;
}
static int cxgb_set_mac_addr(struct net_device *dev, void *p)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data))
return -EINVAL;
memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
t3_mac_set_address(&pi->mac, LAN_MAC_IDX, dev->dev_addr);
if (offload_running(adapter))
write_smt_entry(adapter, pi->port_id);
return 0;
}
/**
* t3_synchronize_rx - wait for current Rx processing on a port to complete
* @adap: the adapter
* @p: the port
*
* Ensures that current Rx processing on any of the queues associated with
* the given port completes before returning. We do this by acquiring and
* releasing the locks of the response queues associated with the port.
*/
static void t3_synchronize_rx(struct adapter *adap, const struct port_info *p)
{
int i;
for (i = p->first_qset; i < p->first_qset + p->nqsets; i++) {
struct sge_rspq *q = &adap->sge.qs[i].rspq;
spin_lock_irq(&q->lock);
spin_unlock_irq(&q->lock);
}
}
static void cxgb_vlan_mode(struct net_device *dev, u32 features)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
if (adapter->params.rev > 0) {
t3_set_vlan_accel(adapter, 1 << pi->port_id,
features & NETIF_F_HW_VLAN_RX);
} else {
/* single control for all ports */
unsigned int i, have_vlans = features & NETIF_F_HW_VLAN_RX;
for_each_port(adapter, i)
have_vlans |=
adapter->port[i]->features & NETIF_F_HW_VLAN_RX;
t3_set_vlan_accel(adapter, 1, have_vlans);
}
t3_synchronize_rx(adapter, pi);
}
static u32 cxgb_fix_features(struct net_device *dev, u32 features)
{
/*
* Since there is no support for separate rx/tx vlan accel
* enable/disable make sure tx flag is always in same state as rx.
*/
if (features & NETIF_F_HW_VLAN_RX)
features |= NETIF_F_HW_VLAN_TX;
else
features &= ~NETIF_F_HW_VLAN_TX;
return features;
}
static int cxgb_set_features(struct net_device *dev, u32 features)
{
u32 changed = dev->features ^ features;
if (changed & NETIF_F_HW_VLAN_RX)
cxgb_vlan_mode(dev, features);
return 0;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void cxgb_netpoll(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
struct adapter *adapter = pi->adapter;
int qidx;
for (qidx = pi->first_qset; qidx < pi->first_qset + pi->nqsets; qidx++) {
struct sge_qset *qs = &adapter->sge.qs[qidx];
void *source;
if (adapter->flags & USING_MSIX)
source = qs;
else
source = adapter;
t3_intr_handler(adapter, qs->rspq.polling) (0, source);
}
}
#endif
/*
* Periodic accumulation of MAC statistics.
*/
static void mac_stats_update(struct adapter *adapter)
{
int i;
for_each_port(adapter, i) {
struct net_device *dev = adapter->port[i];
struct port_info *p = netdev_priv(dev);
if (netif_running(dev)) {
spin_lock(&adapter->stats_lock);
t3_mac_update_stats(&p->mac);
spin_unlock(&adapter->stats_lock);
}
}
}
static void check_link_status(struct adapter *adapter)
{
int i;
for_each_port(adapter, i) {
struct net_device *dev = adapter->port[i];
struct port_info *p = netdev_priv(dev);
int link_fault;
spin_lock_irq(&adapter->work_lock);
link_fault = p->link_fault;
spin_unlock_irq(&adapter->work_lock);
if (link_fault) {
t3_link_fault(adapter, i);
continue;
}
if (!(p->phy.caps & SUPPORTED_IRQ) && netif_running(dev)) {
t3_xgm_intr_disable(adapter, i);
t3_read_reg(adapter, A_XGM_INT_STATUS + p->mac.offset);
t3_link_changed(adapter, i);
t3_xgm_intr_enable(adapter, i);
}
}
}
static void check_t3b2_mac(struct adapter *adapter)
{
int i;
if (!rtnl_trylock()) /* synchronize with ifdown */
return;
for_each_port(adapter, i) {
struct net_device *dev = adapter->port[i];
struct port_info *p = netdev_priv(dev);
int status;
if (!netif_running(dev))
continue;
status = 0;
if (netif_running(dev) && netif_carrier_ok(dev))
status = t3b2_mac_watchdog_task(&p->mac);
if (status == 1)
p->mac.stats.num_toggled++;
else if (status == 2) {
struct cmac *mac = &p->mac;
t3_mac_set_mtu(mac, dev->mtu);
t3_mac_set_address(mac, LAN_MAC_IDX, dev->dev_addr);
cxgb_set_rxmode(dev);
t3_link_start(&p->phy, mac, &p->link_config);
t3_mac_enable(mac, MAC_DIRECTION_RX | MAC_DIRECTION_TX);
t3_port_intr_enable(adapter, p->port_id);
p->mac.stats.num_resets++;
}
}
rtnl_unlock();
}
static void t3_adap_check_task(struct work_struct *work)
{
struct adapter *adapter = container_of(work, struct adapter,
adap_check_task.work);
const struct adapter_params *p = &adapter->params;
int port;
unsigned int v, status, reset;
adapter->check_task_cnt++;
check_link_status(adapter);
/* Accumulate MAC stats if needed */
if (!p->linkpoll_period ||
(adapter->check_task_cnt * p->linkpoll_period) / 10 >=
p->stats_update_period) {
mac_stats_update(adapter);
adapter->check_task_cnt = 0;
}
if (p->rev == T3_REV_B2)
check_t3b2_mac(adapter);
/*
* Scan the XGMAC's to check for various conditions which we want to
* monitor in a periodic polling manner rather than via an interrupt
* condition. This is used for conditions which would otherwise flood
* the system with interrupts and we only really need to know that the
* conditions are "happening" ... For each condition we count the
* detection of the condition and reset it for the next polling loop.
*/
for_each_port(adapter, port) {
struct cmac *mac = &adap2pinfo(adapter, port)->mac;
u32 cause;
cause = t3_read_reg(adapter, A_XGM_INT_CAUSE + mac->offset);
reset = 0;
if (cause & F_RXFIFO_OVERFLOW) {
mac->stats.rx_fifo_ovfl++;
reset |= F_RXFIFO_OVERFLOW;
}
t3_write_reg(adapter, A_XGM_INT_CAUSE + mac->offset, reset);
}
/*
* We do the same as above for FL_EMPTY interrupts.
*/
status = t3_read_reg(adapter, A_SG_INT_CAUSE);
reset = 0;
if (status & F_FLEMPTY) {
struct sge_qset *qs = &adapter->sge.qs[0];
int i = 0;
reset |= F_FLEMPTY;
v = (t3_read_reg(adapter, A_SG_RSPQ_FL_STATUS) >> S_FL0EMPTY) &
0xffff;
while (v) {
qs->fl[i].empty += (v & 1);
if (i)
qs++;
i ^= 1;
v >>= 1;
}
}
t3_write_reg(adapter, A_SG_INT_CAUSE, reset);
/* Schedule the next check update if any port is active. */
spin_lock_irq(&adapter->work_lock);
if (adapter->open_device_map & PORT_MASK)
schedule_chk_task(adapter);
spin_unlock_irq(&adapter->work_lock);
}
static void db_full_task(struct work_struct *work)
{
struct adapter *adapter = container_of(work, struct adapter,
db_full_task);
cxgb3_event_notify(&adapter->tdev, OFFLOAD_DB_FULL, 0);
}
static void db_empty_task(struct work_struct *work)
{
struct adapter *adapter = container_of(work, struct adapter,
db_empty_task);
cxgb3_event_notify(&adapter->tdev, OFFLOAD_DB_EMPTY, 0);
}
static void db_drop_task(struct work_struct *work)
{
struct adapter *adapter = container_of(work, struct adapter,
db_drop_task);
unsigned long delay = 1000;
unsigned short r;
cxgb3_event_notify(&adapter->tdev, OFFLOAD_DB_DROP, 0);
/*
* Sleep a while before ringing the driver qset dbs.
* The delay is between 1000-2023 usecs.
*/
get_random_bytes(&r, 2);
delay += r & 1023;
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout(usecs_to_jiffies(delay));
ring_dbs(adapter);
}
/*
* Processes external (PHY) interrupts in process context.
*/
static void ext_intr_task(struct work_struct *work)
{
struct adapter *adapter = container_of(work, struct adapter,
ext_intr_handler_task);
int i;
/* Disable link fault interrupts */
for_each_port(adapter, i) {
struct net_device *dev = adapter->port[i];
struct port_info *p = netdev_priv(dev);
t3_xgm_intr_disable(adapter, i);
t3_read_reg(adapter, A_XGM_INT_STATUS + p->mac.offset);
}
/* Re-enable link fault interrupts */
t3_phy_intr_handler(adapter);
for_each_port(adapter, i)
t3_xgm_intr_enable(adapter, i);
/* Now reenable external interrupts */
spin_lock_irq(&adapter->work_lock);
if (adapter->slow_intr_mask) {
adapter->slow_intr_mask |= F_T3DBG;
t3_write_reg(adapter, A_PL_INT_CAUSE0, F_T3DBG);
t3_write_reg(adapter, A_PL_INT_ENABLE0,
adapter->slow_intr_mask);
}
spin_unlock_irq(&adapter->work_lock);
}
/*
* Interrupt-context handler for external (PHY) interrupts.
*/
void t3_os_ext_intr_handler(struct adapter *adapter)
{
/*
* Schedule a task to handle external interrupts as they may be slow
* and we use a mutex to protect MDIO registers. We disable PHY
* interrupts in the meantime and let the task reenable them when
* it's done.
*/
spin_lock(&adapter->work_lock);
if (adapter->slow_intr_mask) {
adapter->slow_intr_mask &= ~F_T3DBG;
t3_write_reg(adapter, A_PL_INT_ENABLE0,
adapter->slow_intr_mask);
queue_work(cxgb3_wq, &adapter->ext_intr_handler_task);
}
spin_unlock(&adapter->work_lock);
}
void t3_os_link_fault_handler(struct adapter *adapter, int port_id)
{
struct net_device *netdev = adapter->port[port_id];
struct port_info *pi = netdev_priv(netdev);
spin_lock(&adapter->work_lock);
pi->link_fault = 1;
spin_unlock(&adapter->work_lock);
}
static int t3_adapter_error(struct adapter *adapter, int reset, int on_wq)
{
int i, ret = 0;
if (is_offload(adapter) &&
test_bit(OFFLOAD_DEVMAP_BIT, &adapter->open_device_map)) {
cxgb3_event_notify(&adapter->tdev, OFFLOAD_STATUS_DOWN, 0);
offload_close(&adapter->tdev);
}
/* Stop all ports */
for_each_port(adapter, i) {
struct net_device *netdev = adapter->port[i];
if (netif_running(netdev))
__cxgb_close(netdev, on_wq);
}
/* Stop SGE timers */
t3_stop_sge_timers(adapter);
adapter->flags &= ~FULL_INIT_DONE;
if (reset)
ret = t3_reset_adapter(adapter);
pci_disable_device(adapter->pdev);
return ret;
}
static int t3_reenable_adapter(struct adapter *adapter)
{
if (pci_enable_device(adapter->pdev)) {
dev_err(&adapter->pdev->dev,
"Cannot re-enable PCI device after reset.\n");
goto err;
}
pci_set_master(adapter->pdev);
pci_restore_state(adapter->pdev);
pci_save_state(adapter->pdev);
/* Free sge resources */
t3_free_sge_resources(adapter);
if (t3_replay_prep_adapter(adapter))
goto err;
return 0;
err:
return -1;
}
static void t3_resume_ports(struct adapter *adapter)
{
int i;
/* Restart the ports */
for_each_port(adapter, i) {
struct net_device *netdev = adapter->port[i];
if (netif_running(netdev)) {
if (cxgb_open(netdev)) {
dev_err(&adapter->pdev->dev,
"can't bring device back up"
" after reset\n");
continue;
}
}
}
if (is_offload(adapter) && !ofld_disable)
cxgb3_event_notify(&adapter->tdev, OFFLOAD_STATUS_UP, 0);
}
/*
* processes a fatal error.
* Bring the ports down, reset the chip, bring the ports back up.
*/
static void fatal_error_task(struct work_struct *work)
{
struct adapter *adapter = container_of(work, struct adapter,
fatal_error_handler_task);
int err = 0;
rtnl_lock();
err = t3_adapter_error(adapter, 1, 1);
if (!err)
err = t3_reenable_adapter(adapter);
if (!err)
t3_resume_ports(adapter);
CH_ALERT(adapter, "adapter reset %s\n", err ? "failed" : "succeeded");
rtnl_unlock();
}
void t3_fatal_err(struct adapter *adapter)
{
unsigned int fw_status[4];
if (adapter->flags & FULL_INIT_DONE) {
t3_sge_stop(adapter);
t3_write_reg(adapter, A_XGM_TX_CTRL, 0);
t3_write_reg(adapter, A_XGM_RX_CTRL, 0);
t3_write_reg(adapter, XGM_REG(A_XGM_TX_CTRL, 1), 0);
t3_write_reg(adapter, XGM_REG(A_XGM_RX_CTRL, 1), 0);
spin_lock(&adapter->work_lock);
t3_intr_disable(adapter);
queue_work(cxgb3_wq, &adapter->fatal_error_handler_task);
spin_unlock(&adapter->work_lock);
}
CH_ALERT(adapter, "encountered fatal error, operation suspended\n");
if (!t3_cim_ctl_blk_read(adapter, 0xa0, 4, fw_status))
CH_ALERT(adapter, "FW status: 0x%x, 0x%x, 0x%x, 0x%x\n",
fw_status[0], fw_status[1],
fw_status[2], fw_status[3]);
}
/**
* t3_io_error_detected - called when PCI error is detected
* @pdev: Pointer to PCI device
* @state: The current pci connection state
*
* This function is called after a PCI bus error affecting
* this device has been detected.
*/
static pci_ers_result_t t3_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct adapter *adapter = pci_get_drvdata(pdev);
if (state == pci_channel_io_perm_failure)
return PCI_ERS_RESULT_DISCONNECT;
t3_adapter_error(adapter, 0, 0);
/* Request a slot reset. */
return PCI_ERS_RESULT_NEED_RESET;
}
/**
* t3_io_slot_reset - called after the pci bus has been reset.
* @pdev: Pointer to PCI device
*
* Restart the card from scratch, as if from a cold-boot.
*/
static pci_ers_result_t t3_io_slot_reset(struct pci_dev *pdev)
{
struct adapter *adapter = pci_get_drvdata(pdev);
if (!t3_reenable_adapter(adapter))
return PCI_ERS_RESULT_RECOVERED;
return PCI_ERS_RESULT_DISCONNECT;
}
/**
* t3_io_resume - called when traffic can start flowing again.
* @pdev: Pointer to PCI device
*
* This callback is called when the error recovery driver tells us that
* its OK to resume normal operation.
*/
static void t3_io_resume(struct pci_dev *pdev)
{
struct adapter *adapter = pci_get_drvdata(pdev);
CH_ALERT(adapter, "adapter recovering, PEX ERR 0x%x\n",
t3_read_reg(adapter, A_PCIE_PEX_ERR));
t3_resume_ports(adapter);
}
static struct pci_error_handlers t3_err_handler = {
.error_detected = t3_io_error_detected,
.slot_reset = t3_io_slot_reset,
.resume = t3_io_resume,
};
/*
* Set the number of qsets based on the number of CPUs and the number of ports,
* not to exceed the number of available qsets, assuming there are enough qsets
* per port in HW.
*/
static void set_nqsets(struct adapter *adap)
{
int i, j = 0;
int num_cpus = num_online_cpus();
int hwports = adap->params.nports;
int nqsets = adap->msix_nvectors - 1;
if (adap->params.rev > 0 && adap->flags & USING_MSIX) {
if (hwports == 2 &&
(hwports * nqsets > SGE_QSETS ||
num_cpus >= nqsets / hwports))
nqsets /= hwports;
if (nqsets > num_cpus)
nqsets = num_cpus;
if (nqsets < 1 || hwports == 4)
nqsets = 1;
} else
nqsets = 1;
for_each_port(adap, i) {
struct port_info *pi = adap2pinfo(adap, i);
pi->first_qset = j;
pi->nqsets = nqsets;
j = pi->first_qset + nqsets;
dev_info(&adap->pdev->dev,
"Port %d using %d queue sets.\n", i, nqsets);
}
}
static int __devinit cxgb_enable_msix(struct adapter *adap)
{
struct msix_entry entries[SGE_QSETS + 1];
int vectors;
int i, err;
vectors = ARRAY_SIZE(entries);
for (i = 0; i < vectors; ++i)
entries[i].entry = i;
while ((err = pci_enable_msix(adap->pdev, entries, vectors)) > 0)
vectors = err;
if (err < 0)
pci_disable_msix(adap->pdev);
if (!err && vectors < (adap->params.nports + 1)) {
pci_disable_msix(adap->pdev);
err = -1;
}
if (!err) {
for (i = 0; i < vectors; ++i)
adap->msix_info[i].vec = entries[i].vector;
adap->msix_nvectors = vectors;
}
return err;
}
static void __devinit print_port_info(struct adapter *adap,
const struct adapter_info *ai)
{
static const char *pci_variant[] = {
"PCI", "PCI-X", "PCI-X ECC", "PCI-X 266", "PCI Express"
};
int i;
char buf[80];
if (is_pcie(adap))
snprintf(buf, sizeof(buf), "%s x%d",
pci_variant[adap->params.pci.variant],
adap->params.pci.width);
else
snprintf(buf, sizeof(buf), "%s %dMHz/%d-bit",
pci_variant[adap->params.pci.variant],
adap->params.pci.speed, adap->params.pci.width);
for_each_port(adap, i) {
struct net_device *dev = adap->port[i];
const struct port_info *pi = netdev_priv(dev);
if (!test_bit(i, &adap->registered_device_map))
continue;
printk(KERN_INFO "%s: %s %s %sNIC (rev %d) %s%s\n",
dev->name, ai->desc, pi->phy.desc,
is_offload(adap) ? "R" : "", adap->params.rev, buf,
(adap->flags & USING_MSIX) ? " MSI-X" :
(adap->flags & USING_MSI) ? " MSI" : "");
if (adap->name == dev->name && adap->params.vpd.mclk)
printk(KERN_INFO
"%s: %uMB CM, %uMB PMTX, %uMB PMRX, S/N: %s\n",
adap->name, t3_mc7_size(&adap->cm) >> 20,
t3_mc7_size(&adap->pmtx) >> 20,
t3_mc7_size(&adap->pmrx) >> 20,
adap->params.vpd.sn);
}
}
static const struct net_device_ops cxgb_netdev_ops = {
.ndo_open = cxgb_open,
.ndo_stop = cxgb_close,
.ndo_start_xmit = t3_eth_xmit,
.ndo_get_stats = cxgb_get_stats,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_multicast_list = cxgb_set_rxmode,
.ndo_do_ioctl = cxgb_ioctl,
.ndo_change_mtu = cxgb_change_mtu,
.ndo_set_mac_address = cxgb_set_mac_addr,
.ndo_fix_features = cxgb_fix_features,
.ndo_set_features = cxgb_set_features,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = cxgb_netpoll,
#endif
};
static void __devinit cxgb3_init_iscsi_mac(struct net_device *dev)
{
struct port_info *pi = netdev_priv(dev);
memcpy(pi->iscsic.mac_addr, dev->dev_addr, ETH_ALEN);
pi->iscsic.mac_addr[3] |= 0x80;
}
static int __devinit init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
static int version_printed;
int i, err, pci_using_dac = 0;
resource_size_t mmio_start, mmio_len;
const struct adapter_info *ai;
struct adapter *adapter = NULL;
struct port_info *pi;
if (!version_printed) {
printk(KERN_INFO "%s - version %s\n", DRV_DESC, DRV_VERSION);
++version_printed;
}
if (!cxgb3_wq) {
cxgb3_wq = create_singlethread_workqueue(DRV_NAME);
if (!cxgb3_wq) {
printk(KERN_ERR DRV_NAME
": cannot initialize work queue\n");
return -ENOMEM;
}
}
err = pci_enable_device(pdev);
if (err) {
dev_err(&pdev->dev, "cannot enable PCI device\n");
goto out;
}
err = pci_request_regions(pdev, DRV_NAME);
if (err) {
/* Just info, some other driver may have claimed the device. */
dev_info(&pdev->dev, "cannot obtain PCI resources\n");
goto out_disable_device;
}
if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) {
pci_using_dac = 1;
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
if (err) {
dev_err(&pdev->dev, "unable to obtain 64-bit DMA for "
"coherent allocations\n");
goto out_release_regions;
}
} else if ((err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32))) != 0) {
dev_err(&pdev->dev, "no usable DMA configuration\n");
goto out_release_regions;
}
pci_set_master(pdev);
pci_save_state(pdev);
mmio_start = pci_resource_start(pdev, 0);
mmio_len = pci_resource_len(pdev, 0);
ai = t3_get_adapter_info(ent->driver_data);
adapter = kzalloc(sizeof(*adapter), GFP_KERNEL);
if (!adapter) {
err = -ENOMEM;
goto out_release_regions;
}
adapter->nofail_skb =
alloc_skb(sizeof(struct cpl_set_tcb_field), GFP_KERNEL);
if (!adapter->nofail_skb) {
dev_err(&pdev->dev, "cannot allocate nofail buffer\n");
err = -ENOMEM;
goto out_free_adapter;
}
adapter->regs = ioremap_nocache(mmio_start, mmio_len);
if (!adapter->regs) {
dev_err(&pdev->dev, "cannot map device registers\n");
err = -ENOMEM;
goto out_free_adapter;
}
adapter->pdev = pdev;
adapter->name = pci_name(pdev);
adapter->msg_enable = dflt_msg_enable;
adapter->mmio_len = mmio_len;
mutex_init(&adapter->mdio_lock);
spin_lock_init(&adapter->work_lock);
spin_lock_init(&adapter->stats_lock);
INIT_LIST_HEAD(&adapter->adapter_list);
INIT_WORK(&adapter->ext_intr_handler_task, ext_intr_task);
INIT_WORK(&adapter->fatal_error_handler_task, fatal_error_task);
INIT_WORK(&adapter->db_full_task, db_full_task);
INIT_WORK(&adapter->db_empty_task, db_empty_task);
INIT_WORK(&adapter->db_drop_task, db_drop_task);
INIT_DELAYED_WORK(&adapter->adap_check_task, t3_adap_check_task);
for (i = 0; i < ai->nports0 + ai->nports1; ++i) {
struct net_device *netdev;
netdev = alloc_etherdev_mq(sizeof(struct port_info), SGE_QSETS);
if (!netdev) {
err = -ENOMEM;
goto out_free_dev;
}
SET_NETDEV_DEV(netdev, &pdev->dev);
adapter->port[i] = netdev;
pi = netdev_priv(netdev);
pi->adapter = adapter;
pi->port_id = i;
netif_carrier_off(netdev);
netdev->irq = pdev->irq;
netdev->mem_start = mmio_start;
netdev->mem_end = mmio_start + mmio_len - 1;
netdev->hw_features = NETIF_F_SG | NETIF_F_IP_CSUM |
NETIF_F_TSO | NETIF_F_RXCSUM | NETIF_F_HW_VLAN_RX;
netdev->features |= netdev->hw_features | NETIF_F_HW_VLAN_TX;
if (pci_using_dac)
netdev->features |= NETIF_F_HIGHDMA;
netdev->netdev_ops = &cxgb_netdev_ops;
SET_ETHTOOL_OPS(netdev, &cxgb_ethtool_ops);
}
pci_set_drvdata(pdev, adapter);
if (t3_prep_adapter(adapter, ai, 1) < 0) {
err = -ENODEV;
goto out_free_dev;
}
/*
* The card is now ready to go. If any errors occur during device
* registration we do not fail the whole card but rather proceed only
* with the ports we manage to register successfully. However we must
* register at least one net device.
*/
for_each_port(adapter, i) {
err = register_netdev(adapter->port[i]);
if (err)
dev_warn(&pdev->dev,
"cannot register net device %s, skipping\n",
adapter->port[i]->name);
else {
/*
* Change the name we use for messages to the name of
* the first successfully registered interface.
*/
if (!adapter->registered_device_map)
adapter->name = adapter->port[i]->name;
__set_bit(i, &adapter->registered_device_map);
}
}
if (!adapter->registered_device_map) {
dev_err(&pdev->dev, "could not register any net devices\n");
goto out_free_dev;
}
for_each_port(adapter, i)
cxgb3_init_iscsi_mac(adapter->port[i]);
/* Driver's ready. Reflect it on LEDs */
t3_led_ready(adapter);
if (is_offload(adapter)) {
__set_bit(OFFLOAD_DEVMAP_BIT, &adapter->registered_device_map);
cxgb3_adapter_ofld(adapter);
}
/* See what interrupts we'll be using */
if (msi > 1 && cxgb_enable_msix(adapter) == 0)
adapter->flags |= USING_MSIX;
else if (msi > 0 && pci_enable_msi(pdev) == 0)
adapter->flags |= USING_MSI;
set_nqsets(adapter);
err = sysfs_create_group(&adapter->port[0]->dev.kobj,
&cxgb3_attr_group);
for_each_port(adapter, i)
cxgb_vlan_mode(adapter->port[i], adapter->port[i]->features);
print_port_info(adapter, ai);
return 0;
out_free_dev:
iounmap(adapter->regs);
for (i = ai->nports0 + ai->nports1 - 1; i >= 0; --i)
if (adapter->port[i])
free_netdev(adapter->port[i]);
out_free_adapter:
kfree(adapter);
out_release_regions:
pci_release_regions(pdev);
out_disable_device:
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
out:
return err;
}
static void __devexit remove_one(struct pci_dev *pdev)
{
struct adapter *adapter = pci_get_drvdata(pdev);
if (adapter) {
int i;
t3_sge_stop(adapter);
sysfs_remove_group(&adapter->port[0]->dev.kobj,
&cxgb3_attr_group);
if (is_offload(adapter)) {
cxgb3_adapter_unofld(adapter);
if (test_bit(OFFLOAD_DEVMAP_BIT,
&adapter->open_device_map))
offload_close(&adapter->tdev);
}
for_each_port(adapter, i)
if (test_bit(i, &adapter->registered_device_map))
unregister_netdev(adapter->port[i]);
t3_stop_sge_timers(adapter);
t3_free_sge_resources(adapter);
cxgb_disable_msi(adapter);
for_each_port(adapter, i)
if (adapter->port[i])
free_netdev(adapter->port[i]);
iounmap(adapter->regs);
if (adapter->nofail_skb)
kfree_skb(adapter->nofail_skb);
kfree(adapter);
pci_release_regions(pdev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
}
}
static struct pci_driver driver = {
.name = DRV_NAME,
.id_table = cxgb3_pci_tbl,
.probe = init_one,
.remove = __devexit_p(remove_one),
.err_handler = &t3_err_handler,
};
static int __init cxgb3_init_module(void)
{
int ret;
cxgb3_offload_init();
ret = pci_register_driver(&driver);
return ret;
}
static void __exit cxgb3_cleanup_module(void)
{
pci_unregister_driver(&driver);
if (cxgb3_wq)
destroy_workqueue(cxgb3_wq);
}
module_init(cxgb3_init_module);
module_exit(cxgb3_cleanup_module);
| gpl-2.0 |
kvinodhbabu/linux | sound/soc/samsung/odroidx2_max98090.c | 899 | 4792 | /*
* Copyright (C) 2014 Samsung Electronics Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/of.h>
#include <linux/module.h>
#include <sound/soc.h>
#include <sound/pcm_params.h>
#include "i2s.h"
struct odroidx2_drv_data {
const struct snd_soc_dapm_widget *dapm_widgets;
unsigned int num_dapm_widgets;
};
/* The I2S CDCLK output clock frequency for the MAX98090 codec */
#define MAX98090_MCLK 19200000
static struct snd_soc_dai_link odroidx2_dai[];
static int odroidx2_late_probe(struct snd_soc_card *card)
{
struct snd_soc_dai *codec_dai = card->rtd[0].codec_dai;
struct snd_soc_dai *cpu_dai = card->rtd[0].cpu_dai;
int ret;
ret = snd_soc_dai_set_sysclk(codec_dai, 0, MAX98090_MCLK,
SND_SOC_CLOCK_IN);
if (ret < 0 || of_find_property(odroidx2_dai[0].codec_of_node,
"clocks", NULL))
return ret;
/* Set the cpu DAI configuration in order to use CDCLK */
return snd_soc_dai_set_sysclk(cpu_dai, SAMSUNG_I2S_CDCLK,
0, SND_SOC_CLOCK_OUT);
}
static const struct snd_soc_dapm_widget odroidx2_dapm_widgets[] = {
SND_SOC_DAPM_HP("Headphone Jack", NULL),
SND_SOC_DAPM_MIC("Mic Jack", NULL),
SND_SOC_DAPM_MIC("DMIC", NULL),
};
static const struct snd_soc_dapm_widget odroidu3_dapm_widgets[] = {
SND_SOC_DAPM_HP("Headphone Jack", NULL),
SND_SOC_DAPM_SPK("Speakers", NULL),
};
static struct snd_soc_dai_link odroidx2_dai[] = {
{
.name = "MAX98090",
.stream_name = "MAX98090 PCM",
.codec_dai_name = "HiFi",
.dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBM_CFM,
}
};
static struct snd_soc_card odroidx2 = {
.owner = THIS_MODULE,
.dai_link = odroidx2_dai,
.num_links = ARRAY_SIZE(odroidx2_dai),
.fully_routed = true,
.late_probe = odroidx2_late_probe,
};
static const struct odroidx2_drv_data odroidx2_drvdata = {
.dapm_widgets = odroidx2_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(odroidx2_dapm_widgets),
};
static const struct odroidx2_drv_data odroidu3_drvdata = {
.dapm_widgets = odroidu3_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(odroidu3_dapm_widgets),
};
static const struct of_device_id odroidx2_audio_of_match[] = {
{
.compatible = "samsung,odroidx2-audio",
.data = &odroidx2_drvdata,
}, {
.compatible = "samsung,odroidu3-audio",
.data = &odroidu3_drvdata,
},
{ },
};
MODULE_DEVICE_TABLE(of, odroidx2_audio_of_match);
static int odroidx2_audio_probe(struct platform_device *pdev)
{
struct device_node *snd_node = pdev->dev.of_node;
struct snd_soc_card *card = &odroidx2;
struct device_node *i2s_node, *codec_node;
struct odroidx2_drv_data *dd;
const struct of_device_id *of_id;
int ret;
of_id = of_match_node(odroidx2_audio_of_match, snd_node);
dd = (struct odroidx2_drv_data *)of_id->data;
card->num_dapm_widgets = dd->num_dapm_widgets;
card->dapm_widgets = dd->dapm_widgets;
card->dev = &pdev->dev;
ret = snd_soc_of_parse_card_name(card, "samsung,model");
if (ret < 0)
return ret;
ret = snd_soc_of_parse_audio_routing(card, "samsung,audio-routing");
if (ret < 0)
return ret;
codec_node = of_parse_phandle(snd_node, "samsung,audio-codec", 0);
if (!codec_node) {
dev_err(&pdev->dev,
"Failed parsing samsung,i2s-codec property\n");
return -EINVAL;
}
i2s_node = of_parse_phandle(snd_node, "samsung,i2s-controller", 0);
if (!i2s_node) {
dev_err(&pdev->dev,
"Failed parsing samsung,i2s-controller property\n");
ret = -EINVAL;
goto err_put_codec_n;
}
odroidx2_dai[0].codec_of_node = codec_node;
odroidx2_dai[0].cpu_of_node = i2s_node;
odroidx2_dai[0].platform_of_node = i2s_node;
ret = snd_soc_register_card(card);
if (ret) {
dev_err(&pdev->dev, "snd_soc_register_card() failed: %d\n",
ret);
goto err_put_i2s_n;
}
return 0;
err_put_i2s_n:
of_node_put(i2s_node);
err_put_codec_n:
of_node_put(codec_node);
return ret;
}
static int odroidx2_audio_remove(struct platform_device *pdev)
{
struct snd_soc_card *card = platform_get_drvdata(pdev);
snd_soc_unregister_card(card);
of_node_put(odroidx2_dai[0].cpu_of_node);
of_node_put(odroidx2_dai[0].codec_of_node);
return 0;
}
static struct platform_driver odroidx2_audio_driver = {
.driver = {
.name = "odroidx2-audio",
.of_match_table = odroidx2_audio_of_match,
.pm = &snd_soc_pm_ops,
},
.probe = odroidx2_audio_probe,
.remove = odroidx2_audio_remove,
};
module_platform_driver(odroidx2_audio_driver);
MODULE_AUTHOR("Chen Zhen <zhen1.chen@samsung.com>");
MODULE_AUTHOR("Sylwester Nawrocki <s.nawrocki@samsung.com>");
MODULE_DESCRIPTION("ALSA SoC Odroid X2/U3 Audio Support");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
guoxf/linux | drivers/usb/misc/cytherm.c | 1923 | 10822 | /* -*- linux-c -*-
* Cypress USB Thermometer driver
*
* Copyright (c) 2004 Erik Rigtorp <erkki@linux.nu> <erik@rigtorp.com>
*
* This driver works with Elektor magazine USB Interface as published in
* issue #291. It should also work with the original starter kit/demo board
* from Cypress.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2.
*
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/usb.h>
#define DRIVER_VERSION "v1.0"
#define DRIVER_AUTHOR "Erik Rigtorp"
#define DRIVER_DESC "Cypress USB Thermometer driver"
#define USB_SKEL_VENDOR_ID 0x04b4
#define USB_SKEL_PRODUCT_ID 0x0002
static const struct usb_device_id id_table[] = {
{ USB_DEVICE(USB_SKEL_VENDOR_ID, USB_SKEL_PRODUCT_ID) },
{ }
};
MODULE_DEVICE_TABLE (usb, id_table);
/* Structure to hold all of our device specific stuff */
struct usb_cytherm {
struct usb_device *udev; /* save off the usb device pointer */
struct usb_interface *interface; /* the interface for this device */
int brightness;
};
/* local function prototypes */
static int cytherm_probe(struct usb_interface *interface,
const struct usb_device_id *id);
static void cytherm_disconnect(struct usb_interface *interface);
/* usb specific object needed to register this driver with the usb subsystem */
static struct usb_driver cytherm_driver = {
.name = "cytherm",
.probe = cytherm_probe,
.disconnect = cytherm_disconnect,
.id_table = id_table,
};
/* Vendor requests */
/* They all operate on one byte at a time */
#define PING 0x00
#define READ_ROM 0x01 /* Reads form ROM, value = address */
#define READ_RAM 0x02 /* Reads form RAM, value = address */
#define WRITE_RAM 0x03 /* Write to RAM, value = address, index = data */
#define READ_PORT 0x04 /* Reads from port, value = address */
#define WRITE_PORT 0x05 /* Write to port, value = address, index = data */
/* Send a vendor command to device */
static int vendor_command(struct usb_device *dev, unsigned char request,
unsigned char value, unsigned char index,
void *buf, int size)
{
return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
request,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_OTHER,
value,
index, buf, size,
USB_CTRL_GET_TIMEOUT);
}
#define BRIGHTNESS 0x2c /* RAM location for brightness value */
#define BRIGHTNESS_SEM 0x2b /* RAM location for brightness semaphore */
static ssize_t show_brightness(struct device *dev, struct device_attribute *attr, char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct usb_cytherm *cytherm = usb_get_intfdata(intf);
return sprintf(buf, "%i", cytherm->brightness);
}
static ssize_t set_brightness(struct device *dev, struct device_attribute *attr, const char *buf,
size_t count)
{
struct usb_interface *intf = to_usb_interface(dev);
struct usb_cytherm *cytherm = usb_get_intfdata(intf);
unsigned char *buffer;
int retval;
buffer = kmalloc(8, GFP_KERNEL);
if (!buffer) {
dev_err(&cytherm->udev->dev, "out of memory\n");
return 0;
}
cytherm->brightness = simple_strtoul(buf, NULL, 10);
if (cytherm->brightness > 0xFF)
cytherm->brightness = 0xFF;
else if (cytherm->brightness < 0)
cytherm->brightness = 0;
/* Set brightness */
retval = vendor_command(cytherm->udev, WRITE_RAM, BRIGHTNESS,
cytherm->brightness, buffer, 8);
if (retval)
dev_dbg(&cytherm->udev->dev, "retval = %d\n", retval);
/* Inform µC that we have changed the brightness setting */
retval = vendor_command(cytherm->udev, WRITE_RAM, BRIGHTNESS_SEM,
0x01, buffer, 8);
if (retval)
dev_dbg(&cytherm->udev->dev, "retval = %d\n", retval);
kfree(buffer);
return count;
}
static DEVICE_ATTR(brightness, S_IRUGO | S_IWUSR | S_IWGRP,
show_brightness, set_brightness);
#define TEMP 0x33 /* RAM location for temperature */
#define SIGN 0x34 /* RAM location for temperature sign */
static ssize_t show_temp(struct device *dev, struct device_attribute *attr, char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct usb_cytherm *cytherm = usb_get_intfdata(intf);
int retval;
unsigned char *buffer;
int temp, sign;
buffer = kmalloc(8, GFP_KERNEL);
if (!buffer) {
dev_err(&cytherm->udev->dev, "out of memory\n");
return 0;
}
/* read temperature */
retval = vendor_command(cytherm->udev, READ_RAM, TEMP, 0, buffer, 8);
if (retval)
dev_dbg(&cytherm->udev->dev, "retval = %d\n", retval);
temp = buffer[1];
/* read sign */
retval = vendor_command(cytherm->udev, READ_RAM, SIGN, 0, buffer, 8);
if (retval)
dev_dbg(&cytherm->udev->dev, "retval = %d\n", retval);
sign = buffer[1];
kfree(buffer);
return sprintf(buf, "%c%i.%i", sign ? '-' : '+', temp >> 1,
5*(temp - ((temp >> 1) << 1)));
}
static ssize_t set_temp(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
return count;
}
static DEVICE_ATTR(temp, S_IRUGO, show_temp, set_temp);
#define BUTTON 0x7a
static ssize_t show_button(struct device *dev, struct device_attribute *attr, char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct usb_cytherm *cytherm = usb_get_intfdata(intf);
int retval;
unsigned char *buffer;
buffer = kmalloc(8, GFP_KERNEL);
if (!buffer) {
dev_err(&cytherm->udev->dev, "out of memory\n");
return 0;
}
/* check button */
retval = vendor_command(cytherm->udev, READ_RAM, BUTTON, 0, buffer, 8);
if (retval)
dev_dbg(&cytherm->udev->dev, "retval = %d\n", retval);
retval = buffer[1];
kfree(buffer);
if (retval)
return sprintf(buf, "1");
else
return sprintf(buf, "0");
}
static ssize_t set_button(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
return count;
}
static DEVICE_ATTR(button, S_IRUGO, show_button, set_button);
static ssize_t show_port0(struct device *dev, struct device_attribute *attr, char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct usb_cytherm *cytherm = usb_get_intfdata(intf);
int retval;
unsigned char *buffer;
buffer = kmalloc(8, GFP_KERNEL);
if (!buffer) {
dev_err(&cytherm->udev->dev, "out of memory\n");
return 0;
}
retval = vendor_command(cytherm->udev, READ_PORT, 0, 0, buffer, 8);
if (retval)
dev_dbg(&cytherm->udev->dev, "retval = %d\n", retval);
retval = buffer[1];
kfree(buffer);
return sprintf(buf, "%d", retval);
}
static ssize_t set_port0(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
struct usb_interface *intf = to_usb_interface(dev);
struct usb_cytherm *cytherm = usb_get_intfdata(intf);
unsigned char *buffer;
int retval;
int tmp;
buffer = kmalloc(8, GFP_KERNEL);
if (!buffer) {
dev_err(&cytherm->udev->dev, "out of memory\n");
return 0;
}
tmp = simple_strtoul(buf, NULL, 10);
if (tmp > 0xFF)
tmp = 0xFF;
else if (tmp < 0)
tmp = 0;
retval = vendor_command(cytherm->udev, WRITE_PORT, 0,
tmp, buffer, 8);
if (retval)
dev_dbg(&cytherm->udev->dev, "retval = %d\n", retval);
kfree(buffer);
return count;
}
static DEVICE_ATTR(port0, S_IRUGO | S_IWUSR | S_IWGRP, show_port0, set_port0);
static ssize_t show_port1(struct device *dev, struct device_attribute *attr, char *buf)
{
struct usb_interface *intf = to_usb_interface(dev);
struct usb_cytherm *cytherm = usb_get_intfdata(intf);
int retval;
unsigned char *buffer;
buffer = kmalloc(8, GFP_KERNEL);
if (!buffer) {
dev_err(&cytherm->udev->dev, "out of memory\n");
return 0;
}
retval = vendor_command(cytherm->udev, READ_PORT, 1, 0, buffer, 8);
if (retval)
dev_dbg(&cytherm->udev->dev, "retval = %d\n", retval);
retval = buffer[1];
kfree(buffer);
return sprintf(buf, "%d", retval);
}
static ssize_t set_port1(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
struct usb_interface *intf = to_usb_interface(dev);
struct usb_cytherm *cytherm = usb_get_intfdata(intf);
unsigned char *buffer;
int retval;
int tmp;
buffer = kmalloc(8, GFP_KERNEL);
if (!buffer) {
dev_err(&cytherm->udev->dev, "out of memory\n");
return 0;
}
tmp = simple_strtoul(buf, NULL, 10);
if (tmp > 0xFF)
tmp = 0xFF;
else if (tmp < 0)
tmp = 0;
retval = vendor_command(cytherm->udev, WRITE_PORT, 1,
tmp, buffer, 8);
if (retval)
dev_dbg(&cytherm->udev->dev, "retval = %d\n", retval);
kfree(buffer);
return count;
}
static DEVICE_ATTR(port1, S_IRUGO | S_IWUSR | S_IWGRP, show_port1, set_port1);
static int cytherm_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(interface);
struct usb_cytherm *dev = NULL;
int retval = -ENOMEM;
dev = kzalloc (sizeof(struct usb_cytherm), GFP_KERNEL);
if (dev == NULL) {
dev_err (&interface->dev, "Out of memory\n");
goto error_mem;
}
dev->udev = usb_get_dev(udev);
usb_set_intfdata (interface, dev);
dev->brightness = 0xFF;
retval = device_create_file(&interface->dev, &dev_attr_brightness);
if (retval)
goto error;
retval = device_create_file(&interface->dev, &dev_attr_temp);
if (retval)
goto error;
retval = device_create_file(&interface->dev, &dev_attr_button);
if (retval)
goto error;
retval = device_create_file(&interface->dev, &dev_attr_port0);
if (retval)
goto error;
retval = device_create_file(&interface->dev, &dev_attr_port1);
if (retval)
goto error;
dev_info (&interface->dev,
"Cypress thermometer device now attached\n");
return 0;
error:
device_remove_file(&interface->dev, &dev_attr_brightness);
device_remove_file(&interface->dev, &dev_attr_temp);
device_remove_file(&interface->dev, &dev_attr_button);
device_remove_file(&interface->dev, &dev_attr_port0);
device_remove_file(&interface->dev, &dev_attr_port1);
usb_set_intfdata (interface, NULL);
usb_put_dev(dev->udev);
kfree(dev);
error_mem:
return retval;
}
static void cytherm_disconnect(struct usb_interface *interface)
{
struct usb_cytherm *dev;
dev = usb_get_intfdata (interface);
device_remove_file(&interface->dev, &dev_attr_brightness);
device_remove_file(&interface->dev, &dev_attr_temp);
device_remove_file(&interface->dev, &dev_attr_button);
device_remove_file(&interface->dev, &dev_attr_port0);
device_remove_file(&interface->dev, &dev_attr_port1);
/* first remove the files, then NULL the pointer */
usb_set_intfdata (interface, NULL);
usb_put_dev(dev->udev);
kfree(dev);
dev_info(&interface->dev, "Cypress thermometer now disconnected\n");
}
module_usb_driver(cytherm_driver);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
naota/hfsplus | drivers/power/isp1704_charger.c | 2947 | 12855 | /*
* ISP1704 USB Charger Detection driver
*
* Copyright (C) 2010 Nokia 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/device.h>
#include <linux/sysfs.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/delay.h>
#include <linux/usb/otg.h>
#include <linux/usb/ulpi.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include <linux/power/isp1704_charger.h>
/* Vendor specific Power Control register */
#define ISP1704_PWR_CTRL 0x3d
#define ISP1704_PWR_CTRL_SWCTRL (1 << 0)
#define ISP1704_PWR_CTRL_DET_COMP (1 << 1)
#define ISP1704_PWR_CTRL_BVALID_RISE (1 << 2)
#define ISP1704_PWR_CTRL_BVALID_FALL (1 << 3)
#define ISP1704_PWR_CTRL_DP_WKPU_EN (1 << 4)
#define ISP1704_PWR_CTRL_VDAT_DET (1 << 5)
#define ISP1704_PWR_CTRL_DPVSRC_EN (1 << 6)
#define ISP1704_PWR_CTRL_HWDETECT (1 << 7)
#define NXP_VENDOR_ID 0x04cc
static u16 isp170x_id[] = {
0x1704,
0x1707,
};
struct isp1704_charger {
struct device *dev;
struct power_supply psy;
struct otg_transceiver *otg;
struct notifier_block nb;
struct work_struct work;
/* properties */
char model[8];
unsigned present:1;
unsigned online:1;
unsigned current_max;
/* temp storage variables */
unsigned long event;
unsigned max_power;
};
/*
* Disable/enable the power from the isp1704 if a function for it
* has been provided with platform data.
*/
static void isp1704_charger_set_power(struct isp1704_charger *isp, bool on)
{
struct isp1704_charger_data *board = isp->dev->platform_data;
if (board->set_power)
board->set_power(on);
}
/*
* Determine is the charging port DCP (dedicated charger) or CDP (Host/HUB
* chargers).
*
* REVISIT: The method is defined in Battery Charging Specification and is
* applicable to any ULPI transceiver. Nothing isp170x specific here.
*/
static inline int isp1704_charger_type(struct isp1704_charger *isp)
{
u8 reg;
u8 func_ctrl;
u8 otg_ctrl;
int type = POWER_SUPPLY_TYPE_USB_DCP;
func_ctrl = otg_io_read(isp->otg, ULPI_FUNC_CTRL);
otg_ctrl = otg_io_read(isp->otg, ULPI_OTG_CTRL);
/* disable pulldowns */
reg = ULPI_OTG_CTRL_DM_PULLDOWN | ULPI_OTG_CTRL_DP_PULLDOWN;
otg_io_write(isp->otg, ULPI_CLR(ULPI_OTG_CTRL), reg);
/* full speed */
otg_io_write(isp->otg, ULPI_CLR(ULPI_FUNC_CTRL),
ULPI_FUNC_CTRL_XCVRSEL_MASK);
otg_io_write(isp->otg, ULPI_SET(ULPI_FUNC_CTRL),
ULPI_FUNC_CTRL_FULL_SPEED);
/* Enable strong pull-up on DP (1.5K) and reset */
reg = ULPI_FUNC_CTRL_TERMSELECT | ULPI_FUNC_CTRL_RESET;
otg_io_write(isp->otg, ULPI_SET(ULPI_FUNC_CTRL), reg);
usleep_range(1000, 2000);
reg = otg_io_read(isp->otg, ULPI_DEBUG);
if ((reg & 3) != 3)
type = POWER_SUPPLY_TYPE_USB_CDP;
/* recover original state */
otg_io_write(isp->otg, ULPI_FUNC_CTRL, func_ctrl);
otg_io_write(isp->otg, ULPI_OTG_CTRL, otg_ctrl);
return type;
}
/*
* ISP1704 detects PS/2 adapters as charger. To make sure the detected charger
* is actually a dedicated charger, the following steps need to be taken.
*/
static inline int isp1704_charger_verify(struct isp1704_charger *isp)
{
int ret = 0;
u8 r;
/* Reset the transceiver */
r = otg_io_read(isp->otg, ULPI_FUNC_CTRL);
r |= ULPI_FUNC_CTRL_RESET;
otg_io_write(isp->otg, ULPI_FUNC_CTRL, r);
usleep_range(1000, 2000);
/* Set normal mode */
r &= ~(ULPI_FUNC_CTRL_RESET | ULPI_FUNC_CTRL_OPMODE_MASK);
otg_io_write(isp->otg, ULPI_FUNC_CTRL, r);
/* Clear the DP and DM pull-down bits */
r = ULPI_OTG_CTRL_DP_PULLDOWN | ULPI_OTG_CTRL_DM_PULLDOWN;
otg_io_write(isp->otg, ULPI_CLR(ULPI_OTG_CTRL), r);
/* Enable strong pull-up on DP (1.5K) and reset */
r = ULPI_FUNC_CTRL_TERMSELECT | ULPI_FUNC_CTRL_RESET;
otg_io_write(isp->otg, ULPI_SET(ULPI_FUNC_CTRL), r);
usleep_range(1000, 2000);
/* Read the line state */
if (!otg_io_read(isp->otg, ULPI_DEBUG)) {
/* Disable strong pull-up on DP (1.5K) */
otg_io_write(isp->otg, ULPI_CLR(ULPI_FUNC_CTRL),
ULPI_FUNC_CTRL_TERMSELECT);
return 1;
}
/* Is it a charger or PS/2 connection */
/* Enable weak pull-up resistor on DP */
otg_io_write(isp->otg, ULPI_SET(ISP1704_PWR_CTRL),
ISP1704_PWR_CTRL_DP_WKPU_EN);
/* Disable strong pull-up on DP (1.5K) */
otg_io_write(isp->otg, ULPI_CLR(ULPI_FUNC_CTRL),
ULPI_FUNC_CTRL_TERMSELECT);
/* Enable weak pull-down resistor on DM */
otg_io_write(isp->otg, ULPI_SET(ULPI_OTG_CTRL),
ULPI_OTG_CTRL_DM_PULLDOWN);
/* It's a charger if the line states are clear */
if (!(otg_io_read(isp->otg, ULPI_DEBUG)))
ret = 1;
/* Disable weak pull-up resistor on DP */
otg_io_write(isp->otg, ULPI_CLR(ISP1704_PWR_CTRL),
ISP1704_PWR_CTRL_DP_WKPU_EN);
return ret;
}
static inline int isp1704_charger_detect(struct isp1704_charger *isp)
{
unsigned long timeout;
u8 pwr_ctrl;
int ret = 0;
pwr_ctrl = otg_io_read(isp->otg, ISP1704_PWR_CTRL);
/* set SW control bit in PWR_CTRL register */
otg_io_write(isp->otg, ISP1704_PWR_CTRL,
ISP1704_PWR_CTRL_SWCTRL);
/* enable manual charger detection */
otg_io_write(isp->otg, ULPI_SET(ISP1704_PWR_CTRL),
ISP1704_PWR_CTRL_SWCTRL
| ISP1704_PWR_CTRL_DPVSRC_EN);
usleep_range(1000, 2000);
timeout = jiffies + msecs_to_jiffies(300);
do {
/* Check if there is a charger */
if (otg_io_read(isp->otg, ISP1704_PWR_CTRL)
& ISP1704_PWR_CTRL_VDAT_DET) {
ret = isp1704_charger_verify(isp);
break;
}
} while (!time_after(jiffies, timeout) && isp->online);
/* recover original state */
otg_io_write(isp->otg, ISP1704_PWR_CTRL, pwr_ctrl);
return ret;
}
static void isp1704_charger_work(struct work_struct *data)
{
int detect;
unsigned long event;
unsigned power;
struct isp1704_charger *isp =
container_of(data, struct isp1704_charger, work);
static DEFINE_MUTEX(lock);
event = isp->event;
power = isp->max_power;
mutex_lock(&lock);
if (event != USB_EVENT_NONE)
isp1704_charger_set_power(isp, 1);
switch (event) {
case USB_EVENT_VBUS:
isp->online = true;
/* detect charger */
detect = isp1704_charger_detect(isp);
if (detect) {
isp->present = detect;
isp->psy.type = isp1704_charger_type(isp);
}
switch (isp->psy.type) {
case POWER_SUPPLY_TYPE_USB_DCP:
isp->current_max = 1800;
break;
case POWER_SUPPLY_TYPE_USB_CDP:
/*
* Only 500mA here or high speed chirp
* handshaking may break
*/
isp->current_max = 500;
/* FALLTHROUGH */
case POWER_SUPPLY_TYPE_USB:
default:
/* enable data pullups */
if (isp->otg->gadget)
usb_gadget_connect(isp->otg->gadget);
}
break;
case USB_EVENT_NONE:
isp->online = false;
isp->current_max = 0;
isp->present = 0;
isp->current_max = 0;
isp->psy.type = POWER_SUPPLY_TYPE_USB;
/*
* Disable data pullups. We need to prevent the controller from
* enumerating.
*
* FIXME: This is here to allow charger detection with Host/HUB
* chargers. The pullups may be enabled elsewhere, so this can
* not be the final solution.
*/
if (isp->otg->gadget)
usb_gadget_disconnect(isp->otg->gadget);
isp1704_charger_set_power(isp, 0);
break;
case USB_EVENT_ENUMERATED:
if (isp->present)
isp->current_max = 1800;
else
isp->current_max = power;
break;
default:
goto out;
}
power_supply_changed(&isp->psy);
out:
mutex_unlock(&lock);
}
static int isp1704_notifier_call(struct notifier_block *nb,
unsigned long event, void *power)
{
struct isp1704_charger *isp =
container_of(nb, struct isp1704_charger, nb);
isp->event = event;
if (power)
isp->max_power = *((unsigned *)power);
schedule_work(&isp->work);
return NOTIFY_OK;
}
static int isp1704_charger_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct isp1704_charger *isp =
container_of(psy, struct isp1704_charger, psy);
switch (psp) {
case POWER_SUPPLY_PROP_PRESENT:
val->intval = isp->present;
break;
case POWER_SUPPLY_PROP_ONLINE:
val->intval = isp->online;
break;
case POWER_SUPPLY_PROP_CURRENT_MAX:
val->intval = isp->current_max;
break;
case POWER_SUPPLY_PROP_MODEL_NAME:
val->strval = isp->model;
break;
case POWER_SUPPLY_PROP_MANUFACTURER:
val->strval = "NXP";
break;
default:
return -EINVAL;
}
return 0;
}
static enum power_supply_property power_props[] = {
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_CURRENT_MAX,
POWER_SUPPLY_PROP_MODEL_NAME,
POWER_SUPPLY_PROP_MANUFACTURER,
};
static inline int isp1704_test_ulpi(struct isp1704_charger *isp)
{
int vendor;
int product;
int i;
int ret = -ENODEV;
/* Test ULPI interface */
ret = otg_io_write(isp->otg, ULPI_SCRATCH, 0xaa);
if (ret < 0)
return ret;
ret = otg_io_read(isp->otg, ULPI_SCRATCH);
if (ret < 0)
return ret;
if (ret != 0xaa)
return -ENODEV;
/* Verify the product and vendor id matches */
vendor = otg_io_read(isp->otg, ULPI_VENDOR_ID_LOW);
vendor |= otg_io_read(isp->otg, ULPI_VENDOR_ID_HIGH) << 8;
if (vendor != NXP_VENDOR_ID)
return -ENODEV;
product = otg_io_read(isp->otg, ULPI_PRODUCT_ID_LOW);
product |= otg_io_read(isp->otg, ULPI_PRODUCT_ID_HIGH) << 8;
for (i = 0; i < ARRAY_SIZE(isp170x_id); i++) {
if (product == isp170x_id[i]) {
sprintf(isp->model, "isp%x", product);
return product;
}
}
dev_err(isp->dev, "product id %x not matching known ids", product);
return -ENODEV;
}
static int __devinit isp1704_charger_probe(struct platform_device *pdev)
{
struct isp1704_charger *isp;
int ret = -ENODEV;
isp = kzalloc(sizeof *isp, GFP_KERNEL);
if (!isp)
return -ENOMEM;
isp->otg = otg_get_transceiver();
if (!isp->otg)
goto fail0;
isp->dev = &pdev->dev;
platform_set_drvdata(pdev, isp);
isp1704_charger_set_power(isp, 1);
ret = isp1704_test_ulpi(isp);
if (ret < 0)
goto fail1;
isp->psy.name = "isp1704";
isp->psy.type = POWER_SUPPLY_TYPE_USB;
isp->psy.properties = power_props;
isp->psy.num_properties = ARRAY_SIZE(power_props);
isp->psy.get_property = isp1704_charger_get_property;
ret = power_supply_register(isp->dev, &isp->psy);
if (ret)
goto fail1;
/*
* REVISIT: using work in order to allow the otg notifications to be
* made atomically in the future.
*/
INIT_WORK(&isp->work, isp1704_charger_work);
isp->nb.notifier_call = isp1704_notifier_call;
ret = otg_register_notifier(isp->otg, &isp->nb);
if (ret)
goto fail2;
dev_info(isp->dev, "registered with product id %s\n", isp->model);
/*
* Taking over the D+ pullup.
*
* FIXME: The device will be disconnected if it was already
* enumerated. The charger driver should be always loaded before any
* gadget is loaded.
*/
if (isp->otg->gadget)
usb_gadget_disconnect(isp->otg->gadget);
/* Detect charger if VBUS is valid (the cable was already plugged). */
ret = otg_io_read(isp->otg, ULPI_USB_INT_STS);
isp1704_charger_set_power(isp, 0);
if ((ret & ULPI_INT_VBUS_VALID) && !isp->otg->default_a) {
isp->event = USB_EVENT_VBUS;
schedule_work(&isp->work);
}
return 0;
fail2:
power_supply_unregister(&isp->psy);
fail1:
otg_put_transceiver(isp->otg);
fail0:
kfree(isp);
dev_err(&pdev->dev, "failed to register isp1704 with error %d\n", ret);
return ret;
}
static int __devexit isp1704_charger_remove(struct platform_device *pdev)
{
struct isp1704_charger *isp = platform_get_drvdata(pdev);
otg_unregister_notifier(isp->otg, &isp->nb);
power_supply_unregister(&isp->psy);
otg_put_transceiver(isp->otg);
isp1704_charger_set_power(isp, 0);
kfree(isp);
return 0;
}
static struct platform_driver isp1704_charger_driver = {
.driver = {
.name = "isp1704_charger",
},
.probe = isp1704_charger_probe,
.remove = __devexit_p(isp1704_charger_remove),
};
static int __init isp1704_charger_init(void)
{
return platform_driver_register(&isp1704_charger_driver);
}
module_init(isp1704_charger_init);
static void __exit isp1704_charger_exit(void)
{
platform_driver_unregister(&isp1704_charger_driver);
}
module_exit(isp1704_charger_exit);
MODULE_ALIAS("platform:isp1704_charger");
MODULE_AUTHOR("Nokia Corporation");
MODULE_DESCRIPTION("ISP170x USB Charger driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
DroidTh3ory-xx/kernel_samsung_tuna_killr-air | drivers/ata/pata_atiixp.c | 3971 | 8131 | /*
* pata_atiixp.c - ATI PATA for new ATA layer
* (C) 2005 Red Hat Inc
* (C) 2009-2010 Bartlomiej Zolnierkiewicz
*
* Based on
*
* linux/drivers/ide/pci/atiixp.c Version 0.01-bart2 Feb. 26, 2004
*
* Copyright (C) 2003 ATI Inc. <hyu@ati.com>
* Copyright (C) 2004 Bartlomiej Zolnierkiewicz
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "pata_atiixp"
#define DRV_VERSION "0.4.6"
enum {
ATIIXP_IDE_PIO_TIMING = 0x40,
ATIIXP_IDE_MWDMA_TIMING = 0x44,
ATIIXP_IDE_PIO_CONTROL = 0x48,
ATIIXP_IDE_PIO_MODE = 0x4a,
ATIIXP_IDE_UDMA_CONTROL = 0x54,
ATIIXP_IDE_UDMA_MODE = 0x56
};
static int atiixp_cable_detect(struct ata_port *ap)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
u8 udma;
/* Hack from drivers/ide/pci. Really we want to know how to do the
raw detection not play follow the bios mode guess */
pci_read_config_byte(pdev, ATIIXP_IDE_UDMA_MODE + ap->port_no, &udma);
if ((udma & 0x07) >= 0x04 || (udma & 0x70) >= 0x40)
return ATA_CBL_PATA80;
return ATA_CBL_PATA40;
}
static DEFINE_SPINLOCK(atiixp_lock);
/**
* atiixp_set_pio_timing - set initial PIO mode data
* @ap: ATA interface
* @adev: ATA device
*
* Called by both the pio and dma setup functions to set the controller
* timings for PIO transfers. We must load both the mode number and
* timing values into the controller.
*/
static void atiixp_set_pio_timing(struct ata_port *ap, struct ata_device *adev, int pio)
{
static u8 pio_timings[5] = { 0x5D, 0x47, 0x34, 0x22, 0x20 };
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
int dn = 2 * ap->port_no + adev->devno;
int timing_shift = (16 * ap->port_no) + 8 * (adev->devno ^ 1);
u32 pio_timing_data;
u16 pio_mode_data;
pci_read_config_word(pdev, ATIIXP_IDE_PIO_MODE, &pio_mode_data);
pio_mode_data &= ~(0x7 << (4 * dn));
pio_mode_data |= pio << (4 * dn);
pci_write_config_word(pdev, ATIIXP_IDE_PIO_MODE, pio_mode_data);
pci_read_config_dword(pdev, ATIIXP_IDE_PIO_TIMING, &pio_timing_data);
pio_timing_data &= ~(0xFF << timing_shift);
pio_timing_data |= (pio_timings[pio] << timing_shift);
pci_write_config_dword(pdev, ATIIXP_IDE_PIO_TIMING, pio_timing_data);
}
/**
* atiixp_set_piomode - set initial PIO mode data
* @ap: ATA interface
* @adev: ATA device
*
* Called to do the PIO mode setup. We use a shared helper for this
* as the DMA setup must also adjust the PIO timing information.
*/
static void atiixp_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
unsigned long flags;
spin_lock_irqsave(&atiixp_lock, flags);
atiixp_set_pio_timing(ap, adev, adev->pio_mode - XFER_PIO_0);
spin_unlock_irqrestore(&atiixp_lock, flags);
}
/**
* atiixp_set_dmamode - set initial DMA mode data
* @ap: ATA interface
* @adev: ATA device
*
* Called to do the DMA mode setup. We use timing tables for most
* modes but must tune an appropriate PIO mode to match.
*/
static void atiixp_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
static u8 mwdma_timings[5] = { 0x77, 0x21, 0x20 };
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
int dma = adev->dma_mode;
int dn = 2 * ap->port_no + adev->devno;
int wanted_pio;
unsigned long flags;
spin_lock_irqsave(&atiixp_lock, flags);
if (adev->dma_mode >= XFER_UDMA_0) {
u16 udma_mode_data;
dma -= XFER_UDMA_0;
pci_read_config_word(pdev, ATIIXP_IDE_UDMA_MODE, &udma_mode_data);
udma_mode_data &= ~(0x7 << (4 * dn));
udma_mode_data |= dma << (4 * dn);
pci_write_config_word(pdev, ATIIXP_IDE_UDMA_MODE, udma_mode_data);
} else {
int timing_shift = (16 * ap->port_no) + 8 * (adev->devno ^ 1);
u32 mwdma_timing_data;
dma -= XFER_MW_DMA_0;
pci_read_config_dword(pdev, ATIIXP_IDE_MWDMA_TIMING,
&mwdma_timing_data);
mwdma_timing_data &= ~(0xFF << timing_shift);
mwdma_timing_data |= (mwdma_timings[dma] << timing_shift);
pci_write_config_dword(pdev, ATIIXP_IDE_MWDMA_TIMING,
mwdma_timing_data);
}
/*
* We must now look at the PIO mode situation. We may need to
* adjust the PIO mode to keep the timings acceptable
*/
if (adev->dma_mode >= XFER_MW_DMA_2)
wanted_pio = 4;
else if (adev->dma_mode == XFER_MW_DMA_1)
wanted_pio = 3;
else if (adev->dma_mode == XFER_MW_DMA_0)
wanted_pio = 0;
else BUG();
if (adev->pio_mode != wanted_pio)
atiixp_set_pio_timing(ap, adev, wanted_pio);
spin_unlock_irqrestore(&atiixp_lock, flags);
}
/**
* atiixp_bmdma_start - DMA start callback
* @qc: Command in progress
*
* When DMA begins we need to ensure that the UDMA control
* register for the channel is correctly set.
*
* Note: The host lock held by the libata layer protects
* us from two channels both trying to set DMA bits at once
*/
static void atiixp_bmdma_start(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_device *adev = qc->dev;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
int dn = (2 * ap->port_no) + adev->devno;
u16 tmp16;
pci_read_config_word(pdev, ATIIXP_IDE_UDMA_CONTROL, &tmp16);
if (ata_using_udma(adev))
tmp16 |= (1 << dn);
else
tmp16 &= ~(1 << dn);
pci_write_config_word(pdev, ATIIXP_IDE_UDMA_CONTROL, tmp16);
ata_bmdma_start(qc);
}
/**
* atiixp_dma_stop - DMA stop callback
* @qc: Command in progress
*
* DMA has completed. Clear the UDMA flag as the next operations will
* be PIO ones not UDMA data transfer.
*
* Note: The host lock held by the libata layer protects
* us from two channels both trying to set DMA bits at once
*/
static void atiixp_bmdma_stop(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
int dn = (2 * ap->port_no) + qc->dev->devno;
u16 tmp16;
pci_read_config_word(pdev, ATIIXP_IDE_UDMA_CONTROL, &tmp16);
tmp16 &= ~(1 << dn);
pci_write_config_word(pdev, ATIIXP_IDE_UDMA_CONTROL, tmp16);
ata_bmdma_stop(qc);
}
static struct scsi_host_template atiixp_sht = {
ATA_BMDMA_SHT(DRV_NAME),
.sg_tablesize = LIBATA_DUMB_MAX_PRD,
};
static struct ata_port_operations atiixp_port_ops = {
.inherits = &ata_bmdma_port_ops,
.qc_prep = ata_bmdma_dumb_qc_prep,
.bmdma_start = atiixp_bmdma_start,
.bmdma_stop = atiixp_bmdma_stop,
.cable_detect = atiixp_cable_detect,
.set_piomode = atiixp_set_piomode,
.set_dmamode = atiixp_set_dmamode,
};
static int atiixp_init_one(struct pci_dev *pdev, const struct pci_device_id *id)
{
static const struct ata_port_info info = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA12_ONLY,
.udma_mask = ATA_UDMA5,
.port_ops = &atiixp_port_ops
};
static const struct pci_bits atiixp_enable_bits[] = {
{ 0x48, 1, 0x01, 0x00 },
{ 0x48, 1, 0x08, 0x00 }
};
const struct ata_port_info *ppi[] = { &info, &info };
int i;
for (i = 0; i < 2; i++)
if (!pci_test_config_bits(pdev, &atiixp_enable_bits[i]))
ppi[i] = &ata_dummy_port_info;
return ata_pci_bmdma_init_one(pdev, ppi, &atiixp_sht, NULL,
ATA_HOST_PARALLEL_SCAN);
}
static const struct pci_device_id atiixp[] = {
{ PCI_VDEVICE(ATI, PCI_DEVICE_ID_ATI_IXP200_IDE), },
{ PCI_VDEVICE(ATI, PCI_DEVICE_ID_ATI_IXP300_IDE), },
{ PCI_VDEVICE(ATI, PCI_DEVICE_ID_ATI_IXP400_IDE), },
{ PCI_VDEVICE(ATI, PCI_DEVICE_ID_ATI_IXP600_IDE), },
{ PCI_VDEVICE(ATI, PCI_DEVICE_ID_ATI_IXP700_IDE), },
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_HUDSON2_IDE), },
{ },
};
static struct pci_driver atiixp_pci_driver = {
.name = DRV_NAME,
.id_table = atiixp,
.probe = atiixp_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM
.resume = ata_pci_device_resume,
.suspend = ata_pci_device_suspend,
#endif
};
static int __init atiixp_init(void)
{
return pci_register_driver(&atiixp_pci_driver);
}
static void __exit atiixp_exit(void)
{
pci_unregister_driver(&atiixp_pci_driver);
}
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("low-level driver for ATI IXP200/300/400");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, atiixp);
MODULE_VERSION(DRV_VERSION);
module_init(atiixp_init);
module_exit(atiixp_exit);
| gpl-2.0 |
d8ahazard/shooter-cm9-deviltoast | drivers/uwb/radio.c | 4739 | 4641 | /*
* UWB radio (channel) management.
*
* Copyright (C) 2008 Cambridge Silicon Radio Ltd.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/kernel.h>
#include <linux/uwb.h>
#include "uwb-internal.h"
static int uwb_radio_select_channel(struct uwb_rc *rc)
{
/*
* Default to channel 9 (BG1, TFC1) unless the user has
* selected a specific channel or there are no active PALs.
*/
if (rc->active_pals == 0)
return -1;
if (rc->beaconing_forced)
return rc->beaconing_forced;
return 9;
}
/*
* Notify all active PALs that the channel has changed.
*/
static void uwb_radio_channel_changed(struct uwb_rc *rc, int channel)
{
struct uwb_pal *pal;
list_for_each_entry(pal, &rc->pals, node) {
if (pal->channel && channel != pal->channel) {
pal->channel = channel;
if (pal->channel_changed)
pal->channel_changed(pal, pal->channel);
}
}
}
/*
* Change to a new channel and notify any active PALs of the new
* channel.
*
* When stopping the radio, PALs need to be notified first so they can
* terminate any active reservations.
*/
static int uwb_radio_change_channel(struct uwb_rc *rc, int channel)
{
int ret = 0;
if (channel == -1)
uwb_radio_channel_changed(rc, channel);
if (channel != rc->beaconing) {
if (rc->beaconing != -1 && channel != -1) {
/*
* FIXME: should signal the channel change
* with a Channel Change IE.
*/
ret = uwb_radio_change_channel(rc, -1);
if (ret < 0)
return ret;
}
ret = uwb_rc_beacon(rc, channel, 0);
}
if (channel != -1)
uwb_radio_channel_changed(rc, rc->beaconing);
return ret;
}
/**
* uwb_radio_start - request that the radio be started
* @pal: the PAL making the request.
*
* If the radio is not already active, aa suitable channel is selected
* and beacons are started.
*/
int uwb_radio_start(struct uwb_pal *pal)
{
struct uwb_rc *rc = pal->rc;
int ret = 0;
mutex_lock(&rc->uwb_dev.mutex);
if (!pal->channel) {
pal->channel = -1;
rc->active_pals++;
ret = uwb_radio_change_channel(rc, uwb_radio_select_channel(rc));
}
mutex_unlock(&rc->uwb_dev.mutex);
return ret;
}
EXPORT_SYMBOL_GPL(uwb_radio_start);
/**
* uwb_radio_stop - request tha the radio be stopped.
* @pal: the PAL making the request.
*
* Stops the radio if no other PAL is making use of it.
*/
void uwb_radio_stop(struct uwb_pal *pal)
{
struct uwb_rc *rc = pal->rc;
mutex_lock(&rc->uwb_dev.mutex);
if (pal->channel) {
rc->active_pals--;
uwb_radio_change_channel(rc, uwb_radio_select_channel(rc));
pal->channel = 0;
}
mutex_unlock(&rc->uwb_dev.mutex);
}
EXPORT_SYMBOL_GPL(uwb_radio_stop);
/*
* uwb_radio_force_channel - force a specific channel to be used
* @rc: the radio controller.
* @channel: the channel to use; -1 to force the radio to stop; 0 to
* use the default channel selection algorithm.
*/
int uwb_radio_force_channel(struct uwb_rc *rc, int channel)
{
int ret = 0;
mutex_lock(&rc->uwb_dev.mutex);
rc->beaconing_forced = channel;
ret = uwb_radio_change_channel(rc, uwb_radio_select_channel(rc));
mutex_unlock(&rc->uwb_dev.mutex);
return ret;
}
/*
* uwb_radio_setup - setup the radio manager
* @rc: the radio controller.
*
* The radio controller is reset to ensure it's in a known state
* before it's used.
*/
int uwb_radio_setup(struct uwb_rc *rc)
{
return uwb_rc_reset(rc);
}
/*
* uwb_radio_reset_state - reset any radio manager state
* @rc: the radio controller.
*
* All internal radio manager state is reset to values corresponding
* to a reset radio controller.
*/
void uwb_radio_reset_state(struct uwb_rc *rc)
{
struct uwb_pal *pal;
mutex_lock(&rc->uwb_dev.mutex);
list_for_each_entry(pal, &rc->pals, node) {
if (pal->channel) {
pal->channel = -1;
if (pal->channel_changed)
pal->channel_changed(pal, -1);
}
}
rc->beaconing = -1;
rc->scanning = -1;
mutex_unlock(&rc->uwb_dev.mutex);
}
/*
* uwb_radio_shutdown - shutdown the radio manager
* @rc: the radio controller.
*
* The radio controller is reset.
*/
void uwb_radio_shutdown(struct uwb_rc *rc)
{
uwb_radio_reset_state(rc);
uwb_rc_reset(rc);
}
| gpl-2.0 |
cooldudezach/android_kernel_zte_warplte | fs/squashfs/super.c | 4739 | 13940 | /*
* Squashfs - a compressed read only filesystem for Linux
*
* Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008
* Phillip Lougher <phillip@squashfs.org.uk>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* super.c
*/
/*
* This file implements code to read the superblock, read and initialise
* in-memory structures at mount time, and all the VFS glue code to register
* the filesystem.
*/
#include <linux/fs.h>
#include <linux/vfs.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <linux/pagemap.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/magic.h>
#include <linux/xattr.h>
#include "squashfs_fs.h"
#include "squashfs_fs_sb.h"
#include "squashfs_fs_i.h"
#include "squashfs.h"
#include "decompressor.h"
#include "xattr.h"
static struct file_system_type squashfs_fs_type;
static const struct super_operations squashfs_super_ops;
static const struct squashfs_decompressor *supported_squashfs_filesystem(short
major, short minor, short id)
{
const struct squashfs_decompressor *decompressor;
if (major < SQUASHFS_MAJOR) {
ERROR("Major/Minor mismatch, older Squashfs %d.%d "
"filesystems are unsupported\n", major, minor);
return NULL;
} else if (major > SQUASHFS_MAJOR || minor > SQUASHFS_MINOR) {
ERROR("Major/Minor mismatch, trying to mount newer "
"%d.%d filesystem\n", major, minor);
ERROR("Please update your kernel\n");
return NULL;
}
decompressor = squashfs_lookup_decompressor(id);
if (!decompressor->supported) {
ERROR("Filesystem uses \"%s\" compression. This is not "
"supported\n", decompressor->name);
return NULL;
}
return decompressor;
}
static int squashfs_fill_super(struct super_block *sb, void *data, int silent)
{
struct squashfs_sb_info *msblk;
struct squashfs_super_block *sblk = NULL;
char b[BDEVNAME_SIZE];
struct inode *root;
long long root_inode;
unsigned short flags;
unsigned int fragments;
u64 lookup_table_start, xattr_id_table_start, next_table;
int err;
TRACE("Entered squashfs_fill_superblock\n");
sb->s_fs_info = kzalloc(sizeof(*msblk), GFP_KERNEL);
if (sb->s_fs_info == NULL) {
ERROR("Failed to allocate squashfs_sb_info\n");
return -ENOMEM;
}
msblk = sb->s_fs_info;
msblk->devblksize = sb_min_blocksize(sb, SQUASHFS_DEVBLK_SIZE);
msblk->devblksize_log2 = ffz(~msblk->devblksize);
mutex_init(&msblk->read_data_mutex);
mutex_init(&msblk->meta_index_mutex);
/*
* msblk->bytes_used is checked in squashfs_read_table to ensure reads
* are not beyond filesystem end. But as we're using
* squashfs_read_table here to read the superblock (including the value
* of bytes_used) we need to set it to an initial sensible dummy value
*/
msblk->bytes_used = sizeof(*sblk);
sblk = squashfs_read_table(sb, SQUASHFS_START, sizeof(*sblk));
if (IS_ERR(sblk)) {
ERROR("unable to read squashfs_super_block\n");
err = PTR_ERR(sblk);
sblk = NULL;
goto failed_mount;
}
err = -EINVAL;
/* Check it is a SQUASHFS superblock */
sb->s_magic = le32_to_cpu(sblk->s_magic);
if (sb->s_magic != SQUASHFS_MAGIC) {
if (!silent)
ERROR("Can't find a SQUASHFS superblock on %s\n",
bdevname(sb->s_bdev, b));
goto failed_mount;
}
/* Check the MAJOR & MINOR versions and lookup compression type */
msblk->decompressor = supported_squashfs_filesystem(
le16_to_cpu(sblk->s_major),
le16_to_cpu(sblk->s_minor),
le16_to_cpu(sblk->compression));
if (msblk->decompressor == NULL)
goto failed_mount;
/* Check the filesystem does not extend beyond the end of the
block device */
msblk->bytes_used = le64_to_cpu(sblk->bytes_used);
if (msblk->bytes_used < 0 || msblk->bytes_used >
i_size_read(sb->s_bdev->bd_inode))
goto failed_mount;
/* Check block size for sanity */
msblk->block_size = le32_to_cpu(sblk->block_size);
if (msblk->block_size > SQUASHFS_FILE_MAX_SIZE)
goto failed_mount;
/*
* Check the system page size is not larger than the filesystem
* block size (by default 128K). This is currently not supported.
*/
if (PAGE_CACHE_SIZE > msblk->block_size) {
ERROR("Page size > filesystem block size (%d). This is "
"currently not supported!\n", msblk->block_size);
goto failed_mount;
}
/* Check block log for sanity */
msblk->block_log = le16_to_cpu(sblk->block_log);
if (msblk->block_log > SQUASHFS_FILE_MAX_LOG)
goto failed_mount;
/* Check that block_size and block_log match */
if (msblk->block_size != (1 << msblk->block_log))
goto failed_mount;
/* Check the root inode for sanity */
root_inode = le64_to_cpu(sblk->root_inode);
if (SQUASHFS_INODE_OFFSET(root_inode) > SQUASHFS_METADATA_SIZE)
goto failed_mount;
msblk->inode_table = le64_to_cpu(sblk->inode_table_start);
msblk->directory_table = le64_to_cpu(sblk->directory_table_start);
msblk->inodes = le32_to_cpu(sblk->inodes);
flags = le16_to_cpu(sblk->flags);
TRACE("Found valid superblock on %s\n", bdevname(sb->s_bdev, b));
TRACE("Inodes are %scompressed\n", SQUASHFS_UNCOMPRESSED_INODES(flags)
? "un" : "");
TRACE("Data is %scompressed\n", SQUASHFS_UNCOMPRESSED_DATA(flags)
? "un" : "");
TRACE("Filesystem size %lld bytes\n", msblk->bytes_used);
TRACE("Block size %d\n", msblk->block_size);
TRACE("Number of inodes %d\n", msblk->inodes);
TRACE("Number of fragments %d\n", le32_to_cpu(sblk->fragments));
TRACE("Number of ids %d\n", le16_to_cpu(sblk->no_ids));
TRACE("sblk->inode_table_start %llx\n", msblk->inode_table);
TRACE("sblk->directory_table_start %llx\n", msblk->directory_table);
TRACE("sblk->fragment_table_start %llx\n",
(u64) le64_to_cpu(sblk->fragment_table_start));
TRACE("sblk->id_table_start %llx\n",
(u64) le64_to_cpu(sblk->id_table_start));
sb->s_maxbytes = MAX_LFS_FILESIZE;
sb->s_flags |= MS_RDONLY;
sb->s_op = &squashfs_super_ops;
err = -ENOMEM;
msblk->block_cache = squashfs_cache_init("metadata",
SQUASHFS_CACHED_BLKS, SQUASHFS_METADATA_SIZE);
if (msblk->block_cache == NULL)
goto failed_mount;
/* Allocate read_page block */
msblk->read_page = squashfs_cache_init("data", 1, msblk->block_size);
if (msblk->read_page == NULL) {
ERROR("Failed to allocate read_page block\n");
goto failed_mount;
}
msblk->stream = squashfs_decompressor_init(sb, flags);
if (IS_ERR(msblk->stream)) {
err = PTR_ERR(msblk->stream);
msblk->stream = NULL;
goto failed_mount;
}
/* Handle xattrs */
sb->s_xattr = squashfs_xattr_handlers;
xattr_id_table_start = le64_to_cpu(sblk->xattr_id_table_start);
if (xattr_id_table_start == SQUASHFS_INVALID_BLK) {
next_table = msblk->bytes_used;
goto allocate_id_index_table;
}
/* Allocate and read xattr id lookup table */
msblk->xattr_id_table = squashfs_read_xattr_id_table(sb,
xattr_id_table_start, &msblk->xattr_table, &msblk->xattr_ids);
if (IS_ERR(msblk->xattr_id_table)) {
ERROR("unable to read xattr id index table\n");
err = PTR_ERR(msblk->xattr_id_table);
msblk->xattr_id_table = NULL;
if (err != -ENOTSUPP)
goto failed_mount;
}
next_table = msblk->xattr_table;
allocate_id_index_table:
/* Allocate and read id index table */
msblk->id_table = squashfs_read_id_index_table(sb,
le64_to_cpu(sblk->id_table_start), next_table,
le16_to_cpu(sblk->no_ids));
if (IS_ERR(msblk->id_table)) {
ERROR("unable to read id index table\n");
err = PTR_ERR(msblk->id_table);
msblk->id_table = NULL;
goto failed_mount;
}
next_table = le64_to_cpu(msblk->id_table[0]);
/* Handle inode lookup table */
lookup_table_start = le64_to_cpu(sblk->lookup_table_start);
if (lookup_table_start == SQUASHFS_INVALID_BLK)
goto handle_fragments;
/* Allocate and read inode lookup table */
msblk->inode_lookup_table = squashfs_read_inode_lookup_table(sb,
lookup_table_start, next_table, msblk->inodes);
if (IS_ERR(msblk->inode_lookup_table)) {
ERROR("unable to read inode lookup table\n");
err = PTR_ERR(msblk->inode_lookup_table);
msblk->inode_lookup_table = NULL;
goto failed_mount;
}
next_table = le64_to_cpu(msblk->inode_lookup_table[0]);
sb->s_export_op = &squashfs_export_ops;
handle_fragments:
fragments = le32_to_cpu(sblk->fragments);
if (fragments == 0)
goto check_directory_table;
msblk->fragment_cache = squashfs_cache_init("fragment",
SQUASHFS_CACHED_FRAGMENTS, msblk->block_size);
if (msblk->fragment_cache == NULL) {
err = -ENOMEM;
goto failed_mount;
}
/* Allocate and read fragment index table */
msblk->fragment_index = squashfs_read_fragment_index_table(sb,
le64_to_cpu(sblk->fragment_table_start), next_table, fragments);
if (IS_ERR(msblk->fragment_index)) {
ERROR("unable to read fragment index table\n");
err = PTR_ERR(msblk->fragment_index);
msblk->fragment_index = NULL;
goto failed_mount;
}
next_table = le64_to_cpu(msblk->fragment_index[0]);
check_directory_table:
/* Sanity check directory_table */
if (msblk->directory_table > next_table) {
err = -EINVAL;
goto failed_mount;
}
/* Sanity check inode_table */
if (msblk->inode_table >= msblk->directory_table) {
err = -EINVAL;
goto failed_mount;
}
/* allocate root */
root = new_inode(sb);
if (!root) {
err = -ENOMEM;
goto failed_mount;
}
err = squashfs_read_inode(root, root_inode);
if (err) {
make_bad_inode(root);
iput(root);
goto failed_mount;
}
insert_inode_hash(root);
sb->s_root = d_make_root(root);
if (sb->s_root == NULL) {
ERROR("Root inode create failed\n");
err = -ENOMEM;
goto failed_mount;
}
TRACE("Leaving squashfs_fill_super\n");
kfree(sblk);
return 0;
failed_mount:
squashfs_cache_delete(msblk->block_cache);
squashfs_cache_delete(msblk->fragment_cache);
squashfs_cache_delete(msblk->read_page);
squashfs_decompressor_free(msblk, msblk->stream);
kfree(msblk->inode_lookup_table);
kfree(msblk->fragment_index);
kfree(msblk->id_table);
kfree(msblk->xattr_id_table);
kfree(sb->s_fs_info);
sb->s_fs_info = NULL;
kfree(sblk);
return err;
}
static int squashfs_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct squashfs_sb_info *msblk = dentry->d_sb->s_fs_info;
u64 id = huge_encode_dev(dentry->d_sb->s_bdev->bd_dev);
TRACE("Entered squashfs_statfs\n");
buf->f_type = SQUASHFS_MAGIC;
buf->f_bsize = msblk->block_size;
buf->f_blocks = ((msblk->bytes_used - 1) >> msblk->block_log) + 1;
buf->f_bfree = buf->f_bavail = 0;
buf->f_files = msblk->inodes;
buf->f_ffree = 0;
buf->f_namelen = SQUASHFS_NAME_LEN;
buf->f_fsid.val[0] = (u32)id;
buf->f_fsid.val[1] = (u32)(id >> 32);
return 0;
}
static int squashfs_remount(struct super_block *sb, int *flags, char *data)
{
*flags |= MS_RDONLY;
return 0;
}
static void squashfs_put_super(struct super_block *sb)
{
if (sb->s_fs_info) {
struct squashfs_sb_info *sbi = sb->s_fs_info;
squashfs_cache_delete(sbi->block_cache);
squashfs_cache_delete(sbi->fragment_cache);
squashfs_cache_delete(sbi->read_page);
squashfs_decompressor_free(sbi, sbi->stream);
kfree(sbi->id_table);
kfree(sbi->fragment_index);
kfree(sbi->meta_index);
kfree(sbi->inode_lookup_table);
kfree(sbi->xattr_id_table);
kfree(sb->s_fs_info);
sb->s_fs_info = NULL;
}
}
static struct dentry *squashfs_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
return mount_bdev(fs_type, flags, dev_name, data, squashfs_fill_super);
}
static struct kmem_cache *squashfs_inode_cachep;
static void init_once(void *foo)
{
struct squashfs_inode_info *ei = foo;
inode_init_once(&ei->vfs_inode);
}
static int __init init_inodecache(void)
{
squashfs_inode_cachep = kmem_cache_create("squashfs_inode_cache",
sizeof(struct squashfs_inode_info), 0,
SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT, init_once);
return squashfs_inode_cachep ? 0 : -ENOMEM;
}
static void destroy_inodecache(void)
{
kmem_cache_destroy(squashfs_inode_cachep);
}
static int __init init_squashfs_fs(void)
{
int err = init_inodecache();
if (err)
return err;
err = register_filesystem(&squashfs_fs_type);
if (err) {
destroy_inodecache();
return err;
}
printk(KERN_INFO "squashfs: version 4.0 (2009/01/31) "
"Phillip Lougher\n");
return 0;
}
static void __exit exit_squashfs_fs(void)
{
unregister_filesystem(&squashfs_fs_type);
destroy_inodecache();
}
static struct inode *squashfs_alloc_inode(struct super_block *sb)
{
struct squashfs_inode_info *ei =
kmem_cache_alloc(squashfs_inode_cachep, GFP_KERNEL);
return ei ? &ei->vfs_inode : NULL;
}
static void squashfs_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(squashfs_inode_cachep, squashfs_i(inode));
}
static void squashfs_destroy_inode(struct inode *inode)
{
call_rcu(&inode->i_rcu, squashfs_i_callback);
}
static struct file_system_type squashfs_fs_type = {
.owner = THIS_MODULE,
.name = "squashfs",
.mount = squashfs_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV
};
static const struct super_operations squashfs_super_ops = {
.alloc_inode = squashfs_alloc_inode,
.destroy_inode = squashfs_destroy_inode,
.statfs = squashfs_statfs,
.put_super = squashfs_put_super,
.remount_fs = squashfs_remount
};
module_init(init_squashfs_fs);
module_exit(exit_squashfs_fs);
MODULE_DESCRIPTION("squashfs 4.0, a compressed read-only filesystem");
MODULE_AUTHOR("Phillip Lougher <phillip@squashfs.org.uk>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
yatto/Android_Kernel_ME302KL_CM13 | drivers/media/radio/radio-aztech.c | 7299 | 5060 | /*
* radio-aztech.c - Aztech radio card driver
*
* Converted to the radio-isa framework by Hans Verkuil <hans.verkuil@xs4all.nl>
* Converted to V4L2 API by Mauro Carvalho Chehab <mchehab@infradead.org>
* Adapted to support the Video for Linux API by
* Russell Kroll <rkroll@exploits.org>. Based on original tuner code by:
*
* Quay Ly
* Donald Song
* Jason Lewis (jlewis@twilight.vtc.vsc.edu)
* Scott McGrath (smcgrath@twilight.vtc.vsc.edu)
* William McGrath (wmcgrath@twilight.vtc.vsc.edu)
*
* Fully tested with the Keene USB FM Transmitter and the v4l2-compliance tool.
*/
#include <linux/module.h> /* Modules */
#include <linux/init.h> /* Initdata */
#include <linux/ioport.h> /* request_region */
#include <linux/delay.h> /* udelay */
#include <linux/videodev2.h> /* kernel radio structs */
#include <linux/io.h> /* outb, outb_p */
#include <linux/slab.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-ctrls.h>
#include "radio-isa.h"
MODULE_AUTHOR("Russell Kroll, Quay Lu, Donald Song, Jason Lewis, Scott McGrath, William McGrath");
MODULE_DESCRIPTION("A driver for the Aztech radio card.");
MODULE_LICENSE("GPL");
MODULE_VERSION("1.0.0");
/* acceptable ports: 0x350 (JP3 shorted), 0x358 (JP3 open) */
#ifndef CONFIG_RADIO_AZTECH_PORT
#define CONFIG_RADIO_AZTECH_PORT -1
#endif
#define AZTECH_MAX 2
static int io[AZTECH_MAX] = { [0] = CONFIG_RADIO_AZTECH_PORT,
[1 ... (AZTECH_MAX - 1)] = -1 };
static int radio_nr[AZTECH_MAX] = { [0 ... (AZTECH_MAX - 1)] = -1 };
static const int radio_wait_time = 1000;
module_param_array(io, int, NULL, 0444);
MODULE_PARM_DESC(io, "I/O addresses of the Aztech card (0x350 or 0x358)");
module_param_array(radio_nr, int, NULL, 0444);
MODULE_PARM_DESC(radio_nr, "Radio device numbers");
struct aztech {
struct radio_isa_card isa;
int curvol;
};
static void send_0_byte(struct aztech *az)
{
udelay(radio_wait_time);
outb_p(2 + az->curvol, az->isa.io);
outb_p(64 + 2 + az->curvol, az->isa.io);
}
static void send_1_byte(struct aztech *az)
{
udelay(radio_wait_time);
outb_p(128 + 2 + az->curvol, az->isa.io);
outb_p(128 + 64 + 2 + az->curvol, az->isa.io);
}
static struct radio_isa_card *aztech_alloc(void)
{
struct aztech *az = kzalloc(sizeof(*az), GFP_KERNEL);
return az ? &az->isa : NULL;
}
static int aztech_s_frequency(struct radio_isa_card *isa, u32 freq)
{
struct aztech *az = container_of(isa, struct aztech, isa);
int i;
freq += 171200; /* Add 10.7 MHz IF */
freq /= 800; /* Convert to 50 kHz units */
send_0_byte(az); /* 0: LSB of frequency */
for (i = 0; i < 13; i++) /* : frequency bits (1-13) */
if (freq & (1 << i))
send_1_byte(az);
else
send_0_byte(az);
send_0_byte(az); /* 14: test bit - always 0 */
send_0_byte(az); /* 15: test bit - always 0 */
send_0_byte(az); /* 16: band data 0 - always 0 */
if (isa->stereo) /* 17: stereo (1 to enable) */
send_1_byte(az);
else
send_0_byte(az);
send_1_byte(az); /* 18: band data 1 - unknown */
send_0_byte(az); /* 19: time base - always 0 */
send_0_byte(az); /* 20: spacing (0 = 25 kHz) */
send_1_byte(az); /* 21: spacing (1 = 25 kHz) */
send_0_byte(az); /* 22: spacing (0 = 25 kHz) */
send_1_byte(az); /* 23: AM/FM (FM = 1, always) */
/* latch frequency */
udelay(radio_wait_time);
outb_p(128 + 64 + az->curvol, az->isa.io);
return 0;
}
/* thanks to Michael Dwyer for giving me a dose of clues in
* the signal strength department..
*
* This card has a stereo bit - bit 0 set = mono, not set = stereo
*/
static u32 aztech_g_rxsubchans(struct radio_isa_card *isa)
{
if (inb(isa->io) & 1)
return V4L2_TUNER_SUB_MONO;
return V4L2_TUNER_SUB_STEREO;
}
static int aztech_s_stereo(struct radio_isa_card *isa, bool stereo)
{
return aztech_s_frequency(isa, isa->freq);
}
static int aztech_s_mute_volume(struct radio_isa_card *isa, bool mute, int vol)
{
struct aztech *az = container_of(isa, struct aztech, isa);
if (mute)
vol = 0;
az->curvol = (vol & 1) + ((vol & 2) << 1);
outb(az->curvol, isa->io);
return 0;
}
static const struct radio_isa_ops aztech_ops = {
.alloc = aztech_alloc,
.s_mute_volume = aztech_s_mute_volume,
.s_frequency = aztech_s_frequency,
.s_stereo = aztech_s_stereo,
.g_rxsubchans = aztech_g_rxsubchans,
};
static const int aztech_ioports[] = { 0x350, 0x358 };
static struct radio_isa_driver aztech_driver = {
.driver = {
.match = radio_isa_match,
.probe = radio_isa_probe,
.remove = radio_isa_remove,
.driver = {
.name = "radio-aztech",
},
},
.io_params = io,
.radio_nr_params = radio_nr,
.io_ports = aztech_ioports,
.num_of_io_ports = ARRAY_SIZE(aztech_ioports),
.region_size = 2,
.card = "Aztech Radio",
.ops = &aztech_ops,
.has_stereo = true,
.max_volume = 3,
};
static int __init aztech_init(void)
{
return isa_register_driver(&aztech_driver.driver, AZTECH_MAX);
}
static void __exit aztech_exit(void)
{
isa_unregister_driver(&aztech_driver.driver);
}
module_init(aztech_init);
module_exit(aztech_exit);
| gpl-2.0 |
asias/linux-kvm | drivers/block/ataflop.c | 8323 | 53212 | /*
* drivers/block/ataflop.c
*
* Copyright (C) 1993 Greg Harp
* Atari Support by Bjoern Brauel, Roman Hodek
*
* Big cleanup Sep 11..14 1994 Roman Hodek:
* - Driver now works interrupt driven
* - Support for two drives; should work, but I cannot test that :-(
* - Reading is done in whole tracks and buffered to speed up things
* - Disk change detection and drive deselecting after motor-off
* similar to TOS
* - Autodetection of disk format (DD/HD); untested yet, because I
* don't have an HD drive :-(
*
* Fixes Nov 13 1994 Martin Schaller:
* - Autodetection works now
* - Support for 5 1/4'' disks
* - Removed drive type (unknown on atari)
* - Do seeks with 8 Mhz
*
* Changes by Andreas Schwab:
* - After errors in multiple read mode try again reading single sectors
* (Feb 1995):
* - Clean up error handling
* - Set blk_size for proper size checking
* - Initialize track register when testing presence of floppy
* - Implement some ioctl's
*
* Changes by Torsten Lang:
* - When probing the floppies we should add the FDCCMDADD_H flag since
* the FDC will otherwise wait forever when no disk is inserted...
*
* ++ Freddi Aschwanden (fa) 20.9.95 fixes for medusa:
* - MFPDELAY() after each FDC access -> atari
* - more/other disk formats
* - DMA to the block buffer directly if we have a 32bit DMA
* - for medusa, the step rate is always 3ms
* - on medusa, use only cache_push()
* Roman:
* - Make disk format numbering independent from minors
* - Let user set max. supported drive type (speeds up format
* detection, saves buffer space)
*
* Roman 10/15/95:
* - implement some more ioctls
* - disk formatting
*
* Andreas 95/12/12:
* - increase gap size at start of track for HD/ED disks
*
* Michael (MSch) 11/07/96:
* - implemented FDSETPRM and FDDEFPRM ioctl
*
* Andreas (97/03/19):
* - implemented missing BLK* ioctls
*
* Things left to do:
* - Formatting
* - Maybe a better strategy for disk change detection (does anyone
* know one?)
*/
#include <linux/module.h>
#include <linux/fd.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/mutex.h>
#include <asm/atafd.h>
#include <asm/atafdreg.h>
#include <asm/atariints.h>
#include <asm/atari_stdma.h>
#include <asm/atari_stram.h>
#define FD_MAX_UNITS 2
#undef DEBUG
static DEFINE_MUTEX(ataflop_mutex);
static struct request *fd_request;
static int fdc_queue;
/* Disk types: DD, HD, ED */
static struct atari_disk_type {
const char *name;
unsigned spt; /* sectors per track */
unsigned blocks; /* total number of blocks */
unsigned fdc_speed; /* fdc_speed setting */
unsigned stretch; /* track doubling ? */
} atari_disk_type[] = {
{ "d360", 9, 720, 0, 0}, /* 0: 360kB diskette */
{ "D360", 9, 720, 0, 1}, /* 1: 360kb in 720k or 1.2MB drive */
{ "D720", 9,1440, 0, 0}, /* 2: 720kb in 720k or 1.2MB drive */
{ "D820", 10,1640, 0, 0}, /* 3: DD disk with 82 tracks/10 sectors */
/* formats above are probed for type DD */
#define MAX_TYPE_DD 3
{ "h1200",15,2400, 3, 0}, /* 4: 1.2MB diskette */
{ "H1440",18,2880, 3, 0}, /* 5: 1.4 MB diskette (HD) */
{ "H1640",20,3280, 3, 0}, /* 6: 1.64MB diskette (fat HD) 82 tr 20 sec */
/* formats above are probed for types DD and HD */
#define MAX_TYPE_HD 6
{ "E2880",36,5760, 3, 0}, /* 7: 2.8 MB diskette (ED) */
{ "E3280",40,6560, 3, 0}, /* 8: 3.2 MB diskette (fat ED) 82 tr 40 sec */
/* formats above are probed for types DD, HD and ED */
#define MAX_TYPE_ED 8
/* types below are never autoprobed */
{ "H1680",21,3360, 3, 0}, /* 9: 1.68MB diskette (fat HD) 80 tr 21 sec */
{ "h410",10,820, 0, 1}, /* 10: 410k diskette 41 tr 10 sec, stretch */
{ "h1476",18,2952, 3, 0}, /* 11: 1.48MB diskette 82 tr 18 sec */
{ "H1722",21,3444, 3, 0}, /* 12: 1.72MB diskette 82 tr 21 sec */
{ "h420",10,840, 0, 1}, /* 13: 420k diskette 42 tr 10 sec, stretch */
{ "H830",10,1660, 0, 0}, /* 14: 820k diskette 83 tr 10 sec */
{ "h1494",18,2952, 3, 0}, /* 15: 1.49MB diskette 83 tr 18 sec */
{ "H1743",21,3486, 3, 0}, /* 16: 1.74MB diskette 83 tr 21 sec */
{ "h880",11,1760, 0, 0}, /* 17: 880k diskette 80 tr 11 sec */
{ "D1040",13,2080, 0, 0}, /* 18: 1.04MB diskette 80 tr 13 sec */
{ "D1120",14,2240, 0, 0}, /* 19: 1.12MB diskette 80 tr 14 sec */
{ "h1600",20,3200, 3, 0}, /* 20: 1.60MB diskette 80 tr 20 sec */
{ "H1760",22,3520, 3, 0}, /* 21: 1.76MB diskette 80 tr 22 sec */
{ "H1920",24,3840, 3, 0}, /* 22: 1.92MB diskette 80 tr 24 sec */
{ "E3200",40,6400, 3, 0}, /* 23: 3.2MB diskette 80 tr 40 sec */
{ "E3520",44,7040, 3, 0}, /* 24: 3.52MB diskette 80 tr 44 sec */
{ "E3840",48,7680, 3, 0}, /* 25: 3.84MB diskette 80 tr 48 sec */
{ "H1840",23,3680, 3, 0}, /* 26: 1.84MB diskette 80 tr 23 sec */
{ "D800",10,1600, 0, 0}, /* 27: 800k diskette 80 tr 10 sec */
};
static int StartDiskType[] = {
MAX_TYPE_DD,
MAX_TYPE_HD,
MAX_TYPE_ED
};
#define TYPE_DD 0
#define TYPE_HD 1
#define TYPE_ED 2
static int DriveType = TYPE_HD;
static DEFINE_SPINLOCK(ataflop_lock);
/* Array for translating minors into disk formats */
static struct {
int index;
unsigned drive_types;
} minor2disktype[] = {
{ 0, TYPE_DD }, /* 1: d360 */
{ 4, TYPE_HD }, /* 2: h1200 */
{ 1, TYPE_DD }, /* 3: D360 */
{ 2, TYPE_DD }, /* 4: D720 */
{ 1, TYPE_DD }, /* 5: h360 = D360 */
{ 2, TYPE_DD }, /* 6: h720 = D720 */
{ 5, TYPE_HD }, /* 7: H1440 */
{ 7, TYPE_ED }, /* 8: E2880 */
/* some PC formats :-) */
{ 8, TYPE_ED }, /* 9: E3280 <- was "CompaQ" == E2880 for PC */
{ 5, TYPE_HD }, /* 10: h1440 = H1440 */
{ 9, TYPE_HD }, /* 11: H1680 */
{ 10, TYPE_DD }, /* 12: h410 */
{ 3, TYPE_DD }, /* 13: H820 <- == D820, 82x10 */
{ 11, TYPE_HD }, /* 14: h1476 */
{ 12, TYPE_HD }, /* 15: H1722 */
{ 13, TYPE_DD }, /* 16: h420 */
{ 14, TYPE_DD }, /* 17: H830 */
{ 15, TYPE_HD }, /* 18: h1494 */
{ 16, TYPE_HD }, /* 19: H1743 */
{ 17, TYPE_DD }, /* 20: h880 */
{ 18, TYPE_DD }, /* 21: D1040 */
{ 19, TYPE_DD }, /* 22: D1120 */
{ 20, TYPE_HD }, /* 23: h1600 */
{ 21, TYPE_HD }, /* 24: H1760 */
{ 22, TYPE_HD }, /* 25: H1920 */
{ 23, TYPE_ED }, /* 26: E3200 */
{ 24, TYPE_ED }, /* 27: E3520 */
{ 25, TYPE_ED }, /* 28: E3840 */
{ 26, TYPE_HD }, /* 29: H1840 */
{ 27, TYPE_DD }, /* 30: D800 */
{ 6, TYPE_HD }, /* 31: H1640 <- was H1600 == h1600 for PC */
};
#define NUM_DISK_MINORS ARRAY_SIZE(minor2disktype)
/*
* Maximum disk size (in kilobytes). This default is used whenever the
* current disk size is unknown.
*/
#define MAX_DISK_SIZE 3280
/*
* MSch: User-provided type information. 'drive' points to
* the respective entry of this array. Set by FDSETPRM ioctls.
*/
static struct atari_disk_type user_params[FD_MAX_UNITS];
/*
* User-provided permanent type information. 'drive' points to
* the respective entry of this array. Set by FDDEFPRM ioctls,
* restored upon disk change by floppy_revalidate() if valid (as seen by
* default_params[].blocks > 0 - a bit in unit[].flags might be used for this?)
*/
static struct atari_disk_type default_params[FD_MAX_UNITS];
/* current info on each unit */
static struct atari_floppy_struct {
int connected; /* !=0 : drive is connected */
int autoprobe; /* !=0 : do autoprobe */
struct atari_disk_type *disktype; /* current type of disk */
int track; /* current head position or -1 if
unknown */
unsigned int steprate; /* steprate setting */
unsigned int wpstat; /* current state of WP signal (for
disk change detection) */
int flags; /* flags */
struct gendisk *disk;
int ref;
int type;
} unit[FD_MAX_UNITS];
#define UD unit[drive]
#define UDT unit[drive].disktype
#define SUD unit[SelectedDrive]
#define SUDT unit[SelectedDrive].disktype
#define FDC_READ(reg) ({ \
/* unsigned long __flags; */ \
unsigned short __val; \
/* local_irq_save(__flags); */ \
dma_wd.dma_mode_status = 0x80 | (reg); \
udelay(25); \
__val = dma_wd.fdc_acces_seccount; \
MFPDELAY(); \
/* local_irq_restore(__flags); */ \
__val & 0xff; \
})
#define FDC_WRITE(reg,val) \
do { \
/* unsigned long __flags; */ \
/* local_irq_save(__flags); */ \
dma_wd.dma_mode_status = 0x80 | (reg); \
udelay(25); \
dma_wd.fdc_acces_seccount = (val); \
MFPDELAY(); \
/* local_irq_restore(__flags); */ \
} while(0)
/* Buffering variables:
* First, there is a DMA buffer in ST-RAM that is used for floppy DMA
* operations. Second, a track buffer is used to cache a whole track
* of the disk to save read operations. These are two separate buffers
* because that allows write operations without clearing the track buffer.
*/
static int MaxSectors[] = {
11, 22, 44
};
static int BufferSize[] = {
15*512, 30*512, 60*512
};
#define BUFFER_SIZE (BufferSize[DriveType])
unsigned char *DMABuffer; /* buffer for writes */
static unsigned long PhysDMABuffer; /* physical address */
static int UseTrackbuffer = -1; /* Do track buffering? */
module_param(UseTrackbuffer, int, 0);
unsigned char *TrackBuffer; /* buffer for reads */
static unsigned long PhysTrackBuffer; /* physical address */
static int BufferDrive, BufferSide, BufferTrack;
static int read_track; /* non-zero if we are reading whole tracks */
#define SECTOR_BUFFER(sec) (TrackBuffer + ((sec)-1)*512)
#define IS_BUFFERED(drive,side,track) \
(BufferDrive == (drive) && BufferSide == (side) && BufferTrack == (track))
/*
* These are global variables, as that's the easiest way to give
* information to interrupts. They are the data used for the current
* request.
*/
static int SelectedDrive = 0;
static int ReqCmd, ReqBlock;
static int ReqSide, ReqTrack, ReqSector, ReqCnt;
static int HeadSettleFlag = 0;
static unsigned char *ReqData, *ReqBuffer;
static int MotorOn = 0, MotorOffTrys;
static int IsFormatting = 0, FormatError;
static int UserSteprate[FD_MAX_UNITS] = { -1, -1 };
module_param_array(UserSteprate, int, NULL, 0);
/* Synchronization of FDC access. */
static volatile int fdc_busy = 0;
static DECLARE_WAIT_QUEUE_HEAD(fdc_wait);
static DECLARE_WAIT_QUEUE_HEAD(format_wait);
static unsigned long changed_floppies = 0xff, fake_change = 0;
#define CHECK_CHANGE_DELAY HZ/2
#define FD_MOTOR_OFF_DELAY (3*HZ)
#define FD_MOTOR_OFF_MAXTRY (10*20)
#define FLOPPY_TIMEOUT (6*HZ)
#define RECALIBRATE_ERRORS 4 /* After this many errors the drive
* will be recalibrated. */
#define MAX_ERRORS 8 /* After this many errors the driver
* will give up. */
/*
* The driver is trying to determine the correct media format
* while Probing is set. fd_rwsec_done() clears it after a
* successful access.
*/
static int Probing = 0;
/* This flag is set when a dummy seek is necessary to make the WP
* status bit accessible.
*/
static int NeedSeek = 0;
#ifdef DEBUG
#define DPRINT(a) printk a
#else
#define DPRINT(a)
#endif
/***************************** Prototypes *****************************/
static void fd_select_side( int side );
static void fd_select_drive( int drive );
static void fd_deselect( void );
static void fd_motor_off_timer( unsigned long dummy );
static void check_change( unsigned long dummy );
static irqreturn_t floppy_irq (int irq, void *dummy);
static void fd_error( void );
static int do_format(int drive, int type, struct atari_format_descr *desc);
static void do_fd_action( int drive );
static void fd_calibrate( void );
static void fd_calibrate_done( int status );
static void fd_seek( void );
static void fd_seek_done( int status );
static void fd_rwsec( void );
static void fd_readtrack_check( unsigned long dummy );
static void fd_rwsec_done( int status );
static void fd_rwsec_done1(int status);
static void fd_writetrack( void );
static void fd_writetrack_done( int status );
static void fd_times_out( unsigned long dummy );
static void finish_fdc( void );
static void finish_fdc_done( int dummy );
static void setup_req_params( int drive );
static void redo_fd_request( void);
static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode, unsigned int
cmd, unsigned long param);
static void fd_probe( int drive );
static int fd_test_drive_present( int drive );
static void config_types( void );
static int floppy_open(struct block_device *bdev, fmode_t mode);
static int floppy_release(struct gendisk *disk, fmode_t mode);
/************************* End of Prototypes **************************/
static DEFINE_TIMER(motor_off_timer, fd_motor_off_timer, 0, 0);
static DEFINE_TIMER(readtrack_timer, fd_readtrack_check, 0, 0);
static DEFINE_TIMER(timeout_timer, fd_times_out, 0, 0);
static DEFINE_TIMER(fd_timer, check_change, 0, 0);
static void fd_end_request_cur(int err)
{
if (!__blk_end_request_cur(fd_request, err))
fd_request = NULL;
}
static inline void start_motor_off_timer(void)
{
mod_timer(&motor_off_timer, jiffies + FD_MOTOR_OFF_DELAY);
MotorOffTrys = 0;
}
static inline void start_check_change_timer( void )
{
mod_timer(&fd_timer, jiffies + CHECK_CHANGE_DELAY);
}
static inline void start_timeout(void)
{
mod_timer(&timeout_timer, jiffies + FLOPPY_TIMEOUT);
}
static inline void stop_timeout(void)
{
del_timer(&timeout_timer);
}
/* Select the side to use. */
static void fd_select_side( int side )
{
unsigned long flags;
/* protect against various other ints mucking around with the PSG */
local_irq_save(flags);
sound_ym.rd_data_reg_sel = 14; /* Select PSG Port A */
sound_ym.wd_data = (side == 0) ? sound_ym.rd_data_reg_sel | 0x01 :
sound_ym.rd_data_reg_sel & 0xfe;
local_irq_restore(flags);
}
/* Select a drive, update the FDC's track register and set the correct
* clock speed for this disk's type.
*/
static void fd_select_drive( int drive )
{
unsigned long flags;
unsigned char tmp;
if (drive == SelectedDrive)
return;
/* protect against various other ints mucking around with the PSG */
local_irq_save(flags);
sound_ym.rd_data_reg_sel = 14; /* Select PSG Port A */
tmp = sound_ym.rd_data_reg_sel;
sound_ym.wd_data = (tmp | DSKDRVNONE) & ~(drive == 0 ? DSKDRV0 : DSKDRV1);
atari_dont_touch_floppy_select = 1;
local_irq_restore(flags);
/* restore track register to saved value */
FDC_WRITE( FDCREG_TRACK, UD.track );
udelay(25);
/* select 8/16 MHz */
if (UDT)
if (ATARIHW_PRESENT(FDCSPEED))
dma_wd.fdc_speed = UDT->fdc_speed;
SelectedDrive = drive;
}
/* Deselect both drives. */
static void fd_deselect( void )
{
unsigned long flags;
/* protect against various other ints mucking around with the PSG */
local_irq_save(flags);
atari_dont_touch_floppy_select = 0;
sound_ym.rd_data_reg_sel=14; /* Select PSG Port A */
sound_ym.wd_data = (sound_ym.rd_data_reg_sel |
(MACH_IS_FALCON ? 3 : 7)); /* no drives selected */
/* On Falcon, the drive B select line is used on the printer port, so
* leave it alone... */
SelectedDrive = -1;
local_irq_restore(flags);
}
/* This timer function deselects the drives when the FDC switched the
* motor off. The deselection cannot happen earlier because the FDC
* counts the index signals, which arrive only if one drive is selected.
*/
static void fd_motor_off_timer( unsigned long dummy )
{
unsigned char status;
if (SelectedDrive < 0)
/* no drive selected, needn't deselect anyone */
return;
if (stdma_islocked())
goto retry;
status = FDC_READ( FDCREG_STATUS );
if (!(status & 0x80)) {
/* motor already turned off by FDC -> deselect drives */
MotorOn = 0;
fd_deselect();
return;
}
/* not yet off, try again */
retry:
/* Test again later; if tested too often, it seems there is no disk
* in the drive and the FDC will leave the motor on forever (or,
* at least until a disk is inserted). So we'll test only twice
* per second from then on...
*/
mod_timer(&motor_off_timer,
jiffies + (MotorOffTrys++ < FD_MOTOR_OFF_MAXTRY ? HZ/20 : HZ/2));
}
/* This function is repeatedly called to detect disk changes (as good
* as possible) and keep track of the current state of the write protection.
*/
static void check_change( unsigned long dummy )
{
static int drive = 0;
unsigned long flags;
unsigned char old_porta;
int stat;
if (++drive > 1 || !UD.connected)
drive = 0;
/* protect against various other ints mucking around with the PSG */
local_irq_save(flags);
if (!stdma_islocked()) {
sound_ym.rd_data_reg_sel = 14;
old_porta = sound_ym.rd_data_reg_sel;
sound_ym.wd_data = (old_porta | DSKDRVNONE) &
~(drive == 0 ? DSKDRV0 : DSKDRV1);
stat = !!(FDC_READ( FDCREG_STATUS ) & FDCSTAT_WPROT);
sound_ym.wd_data = old_porta;
if (stat != UD.wpstat) {
DPRINT(( "wpstat[%d] = %d\n", drive, stat ));
UD.wpstat = stat;
set_bit (drive, &changed_floppies);
}
}
local_irq_restore(flags);
start_check_change_timer();
}
/* Handling of the Head Settling Flag: This flag should be set after each
* seek operation, because we don't use seeks with verify.
*/
static inline void set_head_settle_flag(void)
{
HeadSettleFlag = FDCCMDADD_E;
}
static inline int get_head_settle_flag(void)
{
int tmp = HeadSettleFlag;
HeadSettleFlag = 0;
return( tmp );
}
static inline void copy_buffer(void *from, void *to)
{
ulong *p1 = (ulong *)from, *p2 = (ulong *)to;
int cnt;
for (cnt = 512/4; cnt; cnt--)
*p2++ = *p1++;
}
/* General Interrupt Handling */
static void (*FloppyIRQHandler)( int status ) = NULL;
static irqreturn_t floppy_irq (int irq, void *dummy)
{
unsigned char status;
void (*handler)( int );
handler = xchg(&FloppyIRQHandler, NULL);
if (handler) {
nop();
status = FDC_READ( FDCREG_STATUS );
DPRINT(("FDC irq, status = %02x handler = %08lx\n",status,(unsigned long)handler));
handler( status );
}
else {
DPRINT(("FDC irq, no handler\n"));
}
return IRQ_HANDLED;
}
/* Error handling: If some error happened, retry some times, then
* recalibrate, then try again, and fail after MAX_ERRORS.
*/
static void fd_error( void )
{
if (IsFormatting) {
IsFormatting = 0;
FormatError = 1;
wake_up( &format_wait );
return;
}
if (!fd_request)
return;
fd_request->errors++;
if (fd_request->errors >= MAX_ERRORS) {
printk(KERN_ERR "fd%d: too many errors.\n", SelectedDrive );
fd_end_request_cur(-EIO);
}
else if (fd_request->errors == RECALIBRATE_ERRORS) {
printk(KERN_WARNING "fd%d: recalibrating\n", SelectedDrive );
if (SelectedDrive != -1)
SUD.track = -1;
}
redo_fd_request();
}
#define SET_IRQ_HANDLER(proc) do { FloppyIRQHandler = (proc); } while(0)
/* ---------- Formatting ---------- */
#define FILL(n,val) \
do { \
memset( p, val, n ); \
p += n; \
} while(0)
static int do_format(int drive, int type, struct atari_format_descr *desc)
{
unsigned char *p;
int sect, nsect;
unsigned long flags;
DPRINT(("do_format( dr=%d tr=%d he=%d offs=%d )\n",
drive, desc->track, desc->head, desc->sect_offset ));
local_irq_save(flags);
while( fdc_busy ) sleep_on( &fdc_wait );
fdc_busy = 1;
stdma_lock(floppy_irq, NULL);
atari_turnon_irq( IRQ_MFP_FDC ); /* should be already, just to be sure */
local_irq_restore(flags);
if (type) {
if (--type >= NUM_DISK_MINORS ||
minor2disktype[type].drive_types > DriveType) {
redo_fd_request();
return -EINVAL;
}
type = minor2disktype[type].index;
UDT = &atari_disk_type[type];
}
if (!UDT || desc->track >= UDT->blocks/UDT->spt/2 || desc->head >= 2) {
redo_fd_request();
return -EINVAL;
}
nsect = UDT->spt;
p = TrackBuffer;
/* The track buffer is used for the raw track data, so its
contents become invalid! */
BufferDrive = -1;
/* stop deselect timer */
del_timer( &motor_off_timer );
FILL( 60 * (nsect / 9), 0x4e );
for( sect = 0; sect < nsect; ++sect ) {
FILL( 12, 0 );
FILL( 3, 0xf5 );
*p++ = 0xfe;
*p++ = desc->track;
*p++ = desc->head;
*p++ = (nsect + sect - desc->sect_offset) % nsect + 1;
*p++ = 2;
*p++ = 0xf7;
FILL( 22, 0x4e );
FILL( 12, 0 );
FILL( 3, 0xf5 );
*p++ = 0xfb;
FILL( 512, 0xe5 );
*p++ = 0xf7;
FILL( 40, 0x4e );
}
FILL( TrackBuffer+BUFFER_SIZE-p, 0x4e );
IsFormatting = 1;
FormatError = 0;
ReqTrack = desc->track;
ReqSide = desc->head;
do_fd_action( drive );
sleep_on( &format_wait );
redo_fd_request();
return( FormatError ? -EIO : 0 );
}
/* do_fd_action() is the general procedure for a fd request: All
* required parameter settings (drive select, side select, track
* position) are checked and set if needed. For each of these
* parameters and the actual reading or writing exist two functions:
* one that starts the setting (or skips it if possible) and one
* callback for the "done" interrupt. Each done func calls the next
* set function to propagate the request down to fd_rwsec_done().
*/
static void do_fd_action( int drive )
{
DPRINT(("do_fd_action\n"));
if (UseTrackbuffer && !IsFormatting) {
repeat:
if (IS_BUFFERED( drive, ReqSide, ReqTrack )) {
if (ReqCmd == READ) {
copy_buffer( SECTOR_BUFFER(ReqSector), ReqData );
if (++ReqCnt < blk_rq_cur_sectors(fd_request)) {
/* read next sector */
setup_req_params( drive );
goto repeat;
}
else {
/* all sectors finished */
fd_end_request_cur(0);
redo_fd_request();
return;
}
}
else {
/* cmd == WRITE, pay attention to track buffer
* consistency! */
copy_buffer( ReqData, SECTOR_BUFFER(ReqSector) );
}
}
}
if (SelectedDrive != drive)
fd_select_drive( drive );
if (UD.track == -1)
fd_calibrate();
else if (UD.track != ReqTrack << UDT->stretch)
fd_seek();
else if (IsFormatting)
fd_writetrack();
else
fd_rwsec();
}
/* Seek to track 0 if the current track is unknown */
static void fd_calibrate( void )
{
if (SUD.track >= 0) {
fd_calibrate_done( 0 );
return;
}
if (ATARIHW_PRESENT(FDCSPEED))
dma_wd.fdc_speed = 0; /* always seek with 8 Mhz */;
DPRINT(("fd_calibrate\n"));
SET_IRQ_HANDLER( fd_calibrate_done );
/* we can't verify, since the speed may be incorrect */
FDC_WRITE( FDCREG_CMD, FDCCMD_RESTORE | SUD.steprate );
NeedSeek = 1;
MotorOn = 1;
start_timeout();
/* wait for IRQ */
}
static void fd_calibrate_done( int status )
{
DPRINT(("fd_calibrate_done()\n"));
stop_timeout();
/* set the correct speed now */
if (ATARIHW_PRESENT(FDCSPEED))
dma_wd.fdc_speed = SUDT->fdc_speed;
if (status & FDCSTAT_RECNF) {
printk(KERN_ERR "fd%d: restore failed\n", SelectedDrive );
fd_error();
}
else {
SUD.track = 0;
fd_seek();
}
}
/* Seek the drive to the requested track. The drive must have been
* calibrated at some point before this.
*/
static void fd_seek( void )
{
if (SUD.track == ReqTrack << SUDT->stretch) {
fd_seek_done( 0 );
return;
}
if (ATARIHW_PRESENT(FDCSPEED)) {
dma_wd.fdc_speed = 0; /* always seek witch 8 Mhz */
MFPDELAY();
}
DPRINT(("fd_seek() to track %d\n",ReqTrack));
FDC_WRITE( FDCREG_DATA, ReqTrack << SUDT->stretch);
udelay(25);
SET_IRQ_HANDLER( fd_seek_done );
FDC_WRITE( FDCREG_CMD, FDCCMD_SEEK | SUD.steprate );
MotorOn = 1;
set_head_settle_flag();
start_timeout();
/* wait for IRQ */
}
static void fd_seek_done( int status )
{
DPRINT(("fd_seek_done()\n"));
stop_timeout();
/* set the correct speed */
if (ATARIHW_PRESENT(FDCSPEED))
dma_wd.fdc_speed = SUDT->fdc_speed;
if (status & FDCSTAT_RECNF) {
printk(KERN_ERR "fd%d: seek error (to track %d)\n",
SelectedDrive, ReqTrack );
/* we don't know exactly which track we are on now! */
SUD.track = -1;
fd_error();
}
else {
SUD.track = ReqTrack << SUDT->stretch;
NeedSeek = 0;
if (IsFormatting)
fd_writetrack();
else
fd_rwsec();
}
}
/* This does the actual reading/writing after positioning the head
* over the correct track.
*/
static int MultReadInProgress = 0;
static void fd_rwsec( void )
{
unsigned long paddr, flags;
unsigned int rwflag, old_motoron;
unsigned int track;
DPRINT(("fd_rwsec(), Sec=%d, Access=%c\n",ReqSector, ReqCmd == WRITE ? 'w' : 'r' ));
if (ReqCmd == WRITE) {
if (ATARIHW_PRESENT(EXTD_DMA)) {
paddr = virt_to_phys(ReqData);
}
else {
copy_buffer( ReqData, DMABuffer );
paddr = PhysDMABuffer;
}
dma_cache_maintenance( paddr, 512, 1 );
rwflag = 0x100;
}
else {
if (read_track)
paddr = PhysTrackBuffer;
else
paddr = ATARIHW_PRESENT(EXTD_DMA) ?
virt_to_phys(ReqData) : PhysDMABuffer;
rwflag = 0;
}
fd_select_side( ReqSide );
/* Start sector of this operation */
FDC_WRITE( FDCREG_SECTOR, read_track ? 1 : ReqSector );
MFPDELAY();
/* Cheat for track if stretch != 0 */
if (SUDT->stretch) {
track = FDC_READ( FDCREG_TRACK);
MFPDELAY();
FDC_WRITE( FDCREG_TRACK, track >> SUDT->stretch);
}
udelay(25);
/* Setup DMA */
local_irq_save(flags);
dma_wd.dma_lo = (unsigned char)paddr;
MFPDELAY();
paddr >>= 8;
dma_wd.dma_md = (unsigned char)paddr;
MFPDELAY();
paddr >>= 8;
if (ATARIHW_PRESENT(EXTD_DMA))
st_dma_ext_dmahi = (unsigned short)paddr;
else
dma_wd.dma_hi = (unsigned char)paddr;
MFPDELAY();
local_irq_restore(flags);
/* Clear FIFO and switch DMA to correct mode */
dma_wd.dma_mode_status = 0x90 | rwflag;
MFPDELAY();
dma_wd.dma_mode_status = 0x90 | (rwflag ^ 0x100);
MFPDELAY();
dma_wd.dma_mode_status = 0x90 | rwflag;
MFPDELAY();
/* How many sectors for DMA */
dma_wd.fdc_acces_seccount = read_track ? SUDT->spt : 1;
udelay(25);
/* Start operation */
dma_wd.dma_mode_status = FDCSELREG_STP | rwflag;
udelay(25);
SET_IRQ_HANDLER( fd_rwsec_done );
dma_wd.fdc_acces_seccount =
(get_head_settle_flag() |
(rwflag ? FDCCMD_WRSEC : (FDCCMD_RDSEC | (read_track ? FDCCMDADD_M : 0))));
old_motoron = MotorOn;
MotorOn = 1;
NeedSeek = 1;
/* wait for interrupt */
if (read_track) {
/* If reading a whole track, wait about one disk rotation and
* then check if all sectors are read. The FDC will even
* search for the first non-existent sector and need 1 sec to
* recognise that it isn't present :-(
*/
MultReadInProgress = 1;
mod_timer(&readtrack_timer,
/* 1 rot. + 5 rot.s if motor was off */
jiffies + HZ/5 + (old_motoron ? 0 : HZ));
}
start_timeout();
}
static void fd_readtrack_check( unsigned long dummy )
{
unsigned long flags, addr, addr2;
local_irq_save(flags);
if (!MultReadInProgress) {
/* This prevents a race condition that could arise if the
* interrupt is triggered while the calling of this timer
* callback function takes place. The IRQ function then has
* already cleared 'MultReadInProgress' when flow of control
* gets here.
*/
local_irq_restore(flags);
return;
}
/* get the current DMA address */
/* ++ f.a. read twice to avoid being fooled by switcher */
addr = 0;
do {
addr2 = addr;
addr = dma_wd.dma_lo & 0xff;
MFPDELAY();
addr |= (dma_wd.dma_md & 0xff) << 8;
MFPDELAY();
if (ATARIHW_PRESENT( EXTD_DMA ))
addr |= (st_dma_ext_dmahi & 0xffff) << 16;
else
addr |= (dma_wd.dma_hi & 0xff) << 16;
MFPDELAY();
} while(addr != addr2);
if (addr >= PhysTrackBuffer + SUDT->spt*512) {
/* already read enough data, force an FDC interrupt to stop
* the read operation
*/
SET_IRQ_HANDLER( NULL );
MultReadInProgress = 0;
local_irq_restore(flags);
DPRINT(("fd_readtrack_check(): done\n"));
FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
udelay(25);
/* No error until now -- the FDC would have interrupted
* otherwise!
*/
fd_rwsec_done1(0);
}
else {
/* not yet finished, wait another tenth rotation */
local_irq_restore(flags);
DPRINT(("fd_readtrack_check(): not yet finished\n"));
mod_timer(&readtrack_timer, jiffies + HZ/5/10);
}
}
static void fd_rwsec_done( int status )
{
DPRINT(("fd_rwsec_done()\n"));
if (read_track) {
del_timer(&readtrack_timer);
if (!MultReadInProgress)
return;
MultReadInProgress = 0;
}
fd_rwsec_done1(status);
}
static void fd_rwsec_done1(int status)
{
unsigned int track;
stop_timeout();
/* Correct the track if stretch != 0 */
if (SUDT->stretch) {
track = FDC_READ( FDCREG_TRACK);
MFPDELAY();
FDC_WRITE( FDCREG_TRACK, track << SUDT->stretch);
}
if (!UseTrackbuffer) {
dma_wd.dma_mode_status = 0x90;
MFPDELAY();
if (!(dma_wd.dma_mode_status & 0x01)) {
printk(KERN_ERR "fd%d: DMA error\n", SelectedDrive );
goto err_end;
}
}
MFPDELAY();
if (ReqCmd == WRITE && (status & FDCSTAT_WPROT)) {
printk(KERN_NOTICE "fd%d: is write protected\n", SelectedDrive );
goto err_end;
}
if ((status & FDCSTAT_RECNF) &&
/* RECNF is no error after a multiple read when the FDC
searched for a non-existent sector! */
!(read_track && FDC_READ(FDCREG_SECTOR) > SUDT->spt)) {
if (Probing) {
if (SUDT > atari_disk_type) {
if (SUDT[-1].blocks > ReqBlock) {
/* try another disk type */
SUDT--;
set_capacity(unit[SelectedDrive].disk,
SUDT->blocks);
} else
Probing = 0;
}
else {
if (SUD.flags & FTD_MSG)
printk(KERN_INFO "fd%d: Auto-detected floppy type %s\n",
SelectedDrive, SUDT->name );
Probing=0;
}
} else {
/* record not found, but not probing. Maybe stretch wrong ? Restart probing */
if (SUD.autoprobe) {
SUDT = atari_disk_type + StartDiskType[DriveType];
set_capacity(unit[SelectedDrive].disk,
SUDT->blocks);
Probing = 1;
}
}
if (Probing) {
if (ATARIHW_PRESENT(FDCSPEED)) {
dma_wd.fdc_speed = SUDT->fdc_speed;
MFPDELAY();
}
setup_req_params( SelectedDrive );
BufferDrive = -1;
do_fd_action( SelectedDrive );
return;
}
printk(KERN_ERR "fd%d: sector %d not found (side %d, track %d)\n",
SelectedDrive, FDC_READ (FDCREG_SECTOR), ReqSide, ReqTrack );
goto err_end;
}
if (status & FDCSTAT_CRC) {
printk(KERN_ERR "fd%d: CRC error (side %d, track %d, sector %d)\n",
SelectedDrive, ReqSide, ReqTrack, FDC_READ (FDCREG_SECTOR) );
goto err_end;
}
if (status & FDCSTAT_LOST) {
printk(KERN_ERR "fd%d: lost data (side %d, track %d, sector %d)\n",
SelectedDrive, ReqSide, ReqTrack, FDC_READ (FDCREG_SECTOR) );
goto err_end;
}
Probing = 0;
if (ReqCmd == READ) {
if (!read_track) {
void *addr;
addr = ATARIHW_PRESENT( EXTD_DMA ) ? ReqData : DMABuffer;
dma_cache_maintenance( virt_to_phys(addr), 512, 0 );
if (!ATARIHW_PRESENT( EXTD_DMA ))
copy_buffer (addr, ReqData);
} else {
dma_cache_maintenance( PhysTrackBuffer, MaxSectors[DriveType] * 512, 0 );
BufferDrive = SelectedDrive;
BufferSide = ReqSide;
BufferTrack = ReqTrack;
copy_buffer (SECTOR_BUFFER (ReqSector), ReqData);
}
}
if (++ReqCnt < blk_rq_cur_sectors(fd_request)) {
/* read next sector */
setup_req_params( SelectedDrive );
do_fd_action( SelectedDrive );
}
else {
/* all sectors finished */
fd_end_request_cur(0);
redo_fd_request();
}
return;
err_end:
BufferDrive = -1;
fd_error();
}
static void fd_writetrack( void )
{
unsigned long paddr, flags;
unsigned int track;
DPRINT(("fd_writetrack() Tr=%d Si=%d\n", ReqTrack, ReqSide ));
paddr = PhysTrackBuffer;
dma_cache_maintenance( paddr, BUFFER_SIZE, 1 );
fd_select_side( ReqSide );
/* Cheat for track if stretch != 0 */
if (SUDT->stretch) {
track = FDC_READ( FDCREG_TRACK);
MFPDELAY();
FDC_WRITE(FDCREG_TRACK,track >> SUDT->stretch);
}
udelay(40);
/* Setup DMA */
local_irq_save(flags);
dma_wd.dma_lo = (unsigned char)paddr;
MFPDELAY();
paddr >>= 8;
dma_wd.dma_md = (unsigned char)paddr;
MFPDELAY();
paddr >>= 8;
if (ATARIHW_PRESENT( EXTD_DMA ))
st_dma_ext_dmahi = (unsigned short)paddr;
else
dma_wd.dma_hi = (unsigned char)paddr;
MFPDELAY();
local_irq_restore(flags);
/* Clear FIFO and switch DMA to correct mode */
dma_wd.dma_mode_status = 0x190;
MFPDELAY();
dma_wd.dma_mode_status = 0x90;
MFPDELAY();
dma_wd.dma_mode_status = 0x190;
MFPDELAY();
/* How many sectors for DMA */
dma_wd.fdc_acces_seccount = BUFFER_SIZE/512;
udelay(40);
/* Start operation */
dma_wd.dma_mode_status = FDCSELREG_STP | 0x100;
udelay(40);
SET_IRQ_HANDLER( fd_writetrack_done );
dma_wd.fdc_acces_seccount = FDCCMD_WRTRA | get_head_settle_flag();
MotorOn = 1;
start_timeout();
/* wait for interrupt */
}
static void fd_writetrack_done( int status )
{
DPRINT(("fd_writetrack_done()\n"));
stop_timeout();
if (status & FDCSTAT_WPROT) {
printk(KERN_NOTICE "fd%d: is write protected\n", SelectedDrive );
goto err_end;
}
if (status & FDCSTAT_LOST) {
printk(KERN_ERR "fd%d: lost data (side %d, track %d)\n",
SelectedDrive, ReqSide, ReqTrack );
goto err_end;
}
wake_up( &format_wait );
return;
err_end:
fd_error();
}
static void fd_times_out( unsigned long dummy )
{
atari_disable_irq( IRQ_MFP_FDC );
if (!FloppyIRQHandler) goto end; /* int occurred after timer was fired, but
* before we came here... */
SET_IRQ_HANDLER( NULL );
/* If the timeout occurred while the readtrack_check timer was
* active, we need to cancel it, else bad things will happen */
if (UseTrackbuffer)
del_timer( &readtrack_timer );
FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
udelay( 25 );
printk(KERN_ERR "floppy timeout\n" );
fd_error();
end:
atari_enable_irq( IRQ_MFP_FDC );
}
/* The (noop) seek operation here is needed to make the WP bit in the
* FDC status register accessible for check_change. If the last disk
* operation would have been a RDSEC, this bit would always read as 0
* no matter what :-( To save time, the seek goes to the track we're
* already on.
*/
static void finish_fdc( void )
{
if (!NeedSeek) {
finish_fdc_done( 0 );
}
else {
DPRINT(("finish_fdc: dummy seek started\n"));
FDC_WRITE (FDCREG_DATA, SUD.track);
SET_IRQ_HANDLER( finish_fdc_done );
FDC_WRITE (FDCREG_CMD, FDCCMD_SEEK);
MotorOn = 1;
start_timeout();
/* we must wait for the IRQ here, because the ST-DMA
is released immediately afterwards and the interrupt
may be delivered to the wrong driver. */
}
}
static void finish_fdc_done( int dummy )
{
unsigned long flags;
DPRINT(("finish_fdc_done entered\n"));
stop_timeout();
NeedSeek = 0;
if (timer_pending(&fd_timer) && time_before(fd_timer.expires, jiffies + 5))
/* If the check for a disk change is done too early after this
* last seek command, the WP bit still reads wrong :-((
*/
mod_timer(&fd_timer, jiffies + 5);
else
start_check_change_timer();
start_motor_off_timer();
local_irq_save(flags);
stdma_release();
fdc_busy = 0;
wake_up( &fdc_wait );
local_irq_restore(flags);
DPRINT(("finish_fdc() finished\n"));
}
/* The detection of disk changes is a dark chapter in Atari history :-(
* Because the "Drive ready" signal isn't present in the Atari
* hardware, one has to rely on the "Write Protect". This works fine,
* as long as no write protected disks are used. TOS solves this
* problem by introducing tri-state logic ("maybe changed") and
* looking at the serial number in block 0. This isn't possible for
* Linux, since the floppy driver can't make assumptions about the
* filesystem used on the disk and thus the contents of block 0. I've
* chosen the method to always say "The disk was changed" if it is
* unsure whether it was. This implies that every open or mount
* invalidates the disk buffers if you work with write protected
* disks. But at least this is better than working with incorrect data
* due to unrecognised disk changes.
*/
static unsigned int floppy_check_events(struct gendisk *disk,
unsigned int clearing)
{
struct atari_floppy_struct *p = disk->private_data;
unsigned int drive = p - unit;
if (test_bit (drive, &fake_change)) {
/* simulated change (e.g. after formatting) */
return DISK_EVENT_MEDIA_CHANGE;
}
if (test_bit (drive, &changed_floppies)) {
/* surely changed (the WP signal changed at least once) */
return DISK_EVENT_MEDIA_CHANGE;
}
if (UD.wpstat) {
/* WP is on -> could be changed: to be sure, buffers should be
* invalidated...
*/
return DISK_EVENT_MEDIA_CHANGE;
}
return 0;
}
static int floppy_revalidate(struct gendisk *disk)
{
struct atari_floppy_struct *p = disk->private_data;
unsigned int drive = p - unit;
if (test_bit(drive, &changed_floppies) ||
test_bit(drive, &fake_change) ||
p->disktype == 0) {
if (UD.flags & FTD_MSG)
printk(KERN_ERR "floppy: clear format %p!\n", UDT);
BufferDrive = -1;
clear_bit(drive, &fake_change);
clear_bit(drive, &changed_floppies);
/* MSch: clearing geometry makes sense only for autoprobe
formats, for 'permanent user-defined' parameter:
restore default_params[] here if flagged valid! */
if (default_params[drive].blocks == 0)
UDT = NULL;
else
UDT = &default_params[drive];
}
return 0;
}
/* This sets up the global variables describing the current request. */
static void setup_req_params( int drive )
{
int block = ReqBlock + ReqCnt;
ReqTrack = block / UDT->spt;
ReqSector = block - ReqTrack * UDT->spt + 1;
ReqSide = ReqTrack & 1;
ReqTrack >>= 1;
ReqData = ReqBuffer + 512 * ReqCnt;
if (UseTrackbuffer)
read_track = (ReqCmd == READ && fd_request->errors == 0);
else
read_track = 0;
DPRINT(("Request params: Si=%d Tr=%d Se=%d Data=%08lx\n",ReqSide,
ReqTrack, ReqSector, (unsigned long)ReqData ));
}
/*
* Round-robin between our available drives, doing one request from each
*/
static struct request *set_next_request(void)
{
struct request_queue *q;
int old_pos = fdc_queue;
struct request *rq = NULL;
do {
q = unit[fdc_queue].disk->queue;
if (++fdc_queue == FD_MAX_UNITS)
fdc_queue = 0;
if (q) {
rq = blk_fetch_request(q);
if (rq)
break;
}
} while (fdc_queue != old_pos);
return rq;
}
static void redo_fd_request(void)
{
int drive, type;
struct atari_floppy_struct *floppy;
DPRINT(("redo_fd_request: fd_request=%p dev=%s fd_request->sector=%ld\n",
fd_request, fd_request ? fd_request->rq_disk->disk_name : "",
fd_request ? blk_rq_pos(fd_request) : 0 ));
IsFormatting = 0;
repeat:
if (!fd_request) {
fd_request = set_next_request();
if (!fd_request)
goto the_end;
}
floppy = fd_request->rq_disk->private_data;
drive = floppy - unit;
type = floppy->type;
if (!UD.connected) {
/* drive not connected */
printk(KERN_ERR "Unknown Device: fd%d\n", drive );
fd_end_request_cur(-EIO);
goto repeat;
}
if (type == 0) {
if (!UDT) {
Probing = 1;
UDT = atari_disk_type + StartDiskType[DriveType];
set_capacity(floppy->disk, UDT->blocks);
UD.autoprobe = 1;
}
}
else {
/* user supplied disk type */
if (--type >= NUM_DISK_MINORS) {
printk(KERN_WARNING "fd%d: invalid disk format", drive );
fd_end_request_cur(-EIO);
goto repeat;
}
if (minor2disktype[type].drive_types > DriveType) {
printk(KERN_WARNING "fd%d: unsupported disk format", drive );
fd_end_request_cur(-EIO);
goto repeat;
}
type = minor2disktype[type].index;
UDT = &atari_disk_type[type];
set_capacity(floppy->disk, UDT->blocks);
UD.autoprobe = 0;
}
if (blk_rq_pos(fd_request) + 1 > UDT->blocks) {
fd_end_request_cur(-EIO);
goto repeat;
}
/* stop deselect timer */
del_timer( &motor_off_timer );
ReqCnt = 0;
ReqCmd = rq_data_dir(fd_request);
ReqBlock = blk_rq_pos(fd_request);
ReqBuffer = fd_request->buffer;
setup_req_params( drive );
do_fd_action( drive );
return;
the_end:
finish_fdc();
}
void do_fd_request(struct request_queue * q)
{
DPRINT(("do_fd_request for pid %d\n",current->pid));
while( fdc_busy ) sleep_on( &fdc_wait );
fdc_busy = 1;
stdma_lock(floppy_irq, NULL);
atari_disable_irq( IRQ_MFP_FDC );
redo_fd_request();
atari_enable_irq( IRQ_MFP_FDC );
}
static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long param)
{
struct gendisk *disk = bdev->bd_disk;
struct atari_floppy_struct *floppy = disk->private_data;
int drive = floppy - unit;
int type = floppy->type;
struct atari_format_descr fmt_desc;
struct atari_disk_type *dtp;
struct floppy_struct getprm;
int settype;
struct floppy_struct setprm;
void __user *argp = (void __user *)param;
switch (cmd) {
case FDGETPRM:
if (type) {
if (--type >= NUM_DISK_MINORS)
return -ENODEV;
if (minor2disktype[type].drive_types > DriveType)
return -ENODEV;
type = minor2disktype[type].index;
dtp = &atari_disk_type[type];
if (UD.flags & FTD_MSG)
printk (KERN_ERR "floppy%d: found dtp %p name %s!\n",
drive, dtp, dtp->name);
}
else {
if (!UDT)
return -ENXIO;
else
dtp = UDT;
}
memset((void *)&getprm, 0, sizeof(getprm));
getprm.size = dtp->blocks;
getprm.sect = dtp->spt;
getprm.head = 2;
getprm.track = dtp->blocks/dtp->spt/2;
getprm.stretch = dtp->stretch;
if (copy_to_user(argp, &getprm, sizeof(getprm)))
return -EFAULT;
return 0;
}
switch (cmd) {
case FDSETPRM:
case FDDEFPRM:
/*
* MSch 7/96: simple 'set geometry' case: just set the
* 'default' device params (minor == 0).
* Currently, the drive geometry is cleared after each
* disk change and subsequent revalidate()! simple
* implementation of FDDEFPRM: save geometry from a
* FDDEFPRM call and restore it in floppy_revalidate() !
*/
/* get the parameters from user space */
if (floppy->ref != 1 && floppy->ref != -1)
return -EBUSY;
if (copy_from_user(&setprm, argp, sizeof(setprm)))
return -EFAULT;
/*
* first of all: check for floppy change and revalidate,
* or the next access will revalidate - and clear UDT :-(
*/
if (floppy_check_events(disk, 0))
floppy_revalidate(disk);
if (UD.flags & FTD_MSG)
printk (KERN_INFO "floppy%d: setting size %d spt %d str %d!\n",
drive, setprm.size, setprm.sect, setprm.stretch);
/* what if type > 0 here? Overwrite specified entry ? */
if (type) {
/* refuse to re-set a predefined type for now */
redo_fd_request();
return -EINVAL;
}
/*
* type == 0: first look for a matching entry in the type list,
* and set the UD.disktype field to use the perdefined entry.
* TODO: add user-defined format to head of autoprobe list ?
* Useful to include the user-type for future autodetection!
*/
for (settype = 0; settype < NUM_DISK_MINORS; settype++) {
int setidx = 0;
if (minor2disktype[settype].drive_types > DriveType) {
/* skip this one, invalid for drive ... */
continue;
}
setidx = minor2disktype[settype].index;
dtp = &atari_disk_type[setidx];
/* found matching entry ?? */
if ( dtp->blocks == setprm.size
&& dtp->spt == setprm.sect
&& dtp->stretch == setprm.stretch ) {
if (UD.flags & FTD_MSG)
printk (KERN_INFO "floppy%d: setting %s %p!\n",
drive, dtp->name, dtp);
UDT = dtp;
set_capacity(floppy->disk, UDT->blocks);
if (cmd == FDDEFPRM) {
/* save settings as permanent default type */
default_params[drive].name = dtp->name;
default_params[drive].spt = dtp->spt;
default_params[drive].blocks = dtp->blocks;
default_params[drive].fdc_speed = dtp->fdc_speed;
default_params[drive].stretch = dtp->stretch;
}
return 0;
}
}
/* no matching disk type found above - setting user_params */
if (cmd == FDDEFPRM) {
/* set permanent type */
dtp = &default_params[drive];
} else
/* set user type (reset by disk change!) */
dtp = &user_params[drive];
dtp->name = "user format";
dtp->blocks = setprm.size;
dtp->spt = setprm.sect;
if (setprm.sect > 14)
dtp->fdc_speed = 3;
else
dtp->fdc_speed = 0;
dtp->stretch = setprm.stretch;
if (UD.flags & FTD_MSG)
printk (KERN_INFO "floppy%d: blk %d spt %d str %d!\n",
drive, dtp->blocks, dtp->spt, dtp->stretch);
/* sanity check */
if (setprm.track != dtp->blocks/dtp->spt/2 ||
setprm.head != 2) {
redo_fd_request();
return -EINVAL;
}
UDT = dtp;
set_capacity(floppy->disk, UDT->blocks);
return 0;
case FDMSGON:
UD.flags |= FTD_MSG;
return 0;
case FDMSGOFF:
UD.flags &= ~FTD_MSG;
return 0;
case FDSETEMSGTRESH:
return -EINVAL;
case FDFMTBEG:
return 0;
case FDFMTTRK:
if (floppy->ref != 1 && floppy->ref != -1)
return -EBUSY;
if (copy_from_user(&fmt_desc, argp, sizeof(fmt_desc)))
return -EFAULT;
return do_format(drive, type, &fmt_desc);
case FDCLRPRM:
UDT = NULL;
/* MSch: invalidate default_params */
default_params[drive].blocks = 0;
set_capacity(floppy->disk, MAX_DISK_SIZE * 2);
case FDFMTEND:
case FDFLUSH:
/* invalidate the buffer track to force a reread */
BufferDrive = -1;
set_bit(drive, &fake_change);
check_disk_change(bdev);
return 0;
default:
return -EINVAL;
}
}
static int fd_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
int ret;
mutex_lock(&ataflop_mutex);
ret = fd_locked_ioctl(bdev, mode, cmd, arg);
mutex_unlock(&ataflop_mutex);
return ret;
}
/* Initialize the 'unit' variable for drive 'drive' */
static void __init fd_probe( int drive )
{
UD.connected = 0;
UDT = NULL;
if (!fd_test_drive_present( drive ))
return;
UD.connected = 1;
UD.track = 0;
switch( UserSteprate[drive] ) {
case 2:
UD.steprate = FDCSTEP_2;
break;
case 3:
UD.steprate = FDCSTEP_3;
break;
case 6:
UD.steprate = FDCSTEP_6;
break;
case 12:
UD.steprate = FDCSTEP_12;
break;
default: /* should be -1 for "not set by user" */
if (ATARIHW_PRESENT( FDCSPEED ) || MACH_IS_MEDUSA)
UD.steprate = FDCSTEP_3;
else
UD.steprate = FDCSTEP_6;
break;
}
MotorOn = 1; /* from probe restore operation! */
}
/* This function tests the physical presence of a floppy drive (not
* whether a disk is inserted). This is done by issuing a restore
* command, waiting max. 2 seconds (that should be enough to move the
* head across the whole disk) and looking at the state of the "TR00"
* signal. This should now be raised if there is a drive connected
* (and there is no hardware failure :-) Otherwise, the drive is
* declared absent.
*/
static int __init fd_test_drive_present( int drive )
{
unsigned long timeout;
unsigned char status;
int ok;
if (drive >= (MACH_IS_FALCON ? 1 : 2)) return( 0 );
fd_select_drive( drive );
/* disable interrupt temporarily */
atari_turnoff_irq( IRQ_MFP_FDC );
FDC_WRITE (FDCREG_TRACK, 0xff00);
FDC_WRITE( FDCREG_CMD, FDCCMD_RESTORE | FDCCMDADD_H | FDCSTEP_6 );
timeout = jiffies + 2*HZ+HZ/2;
while (time_before(jiffies, timeout))
if (!(st_mfp.par_dt_reg & 0x20))
break;
status = FDC_READ( FDCREG_STATUS );
ok = (status & FDCSTAT_TR00) != 0;
/* force interrupt to abort restore operation (FDC would try
* about 50 seconds!) */
FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
udelay(500);
status = FDC_READ( FDCREG_STATUS );
udelay(20);
if (ok) {
/* dummy seek command to make WP bit accessible */
FDC_WRITE( FDCREG_DATA, 0 );
FDC_WRITE( FDCREG_CMD, FDCCMD_SEEK );
while( st_mfp.par_dt_reg & 0x20 )
;
status = FDC_READ( FDCREG_STATUS );
}
atari_turnon_irq( IRQ_MFP_FDC );
return( ok );
}
/* Look how many and which kind of drives are connected. If there are
* floppies, additionally start the disk-change and motor-off timers.
*/
static void __init config_types( void )
{
int drive, cnt = 0;
/* for probing drives, set the FDC speed to 8 MHz */
if (ATARIHW_PRESENT(FDCSPEED))
dma_wd.fdc_speed = 0;
printk(KERN_INFO "Probing floppy drive(s):\n");
for( drive = 0; drive < FD_MAX_UNITS; drive++ ) {
fd_probe( drive );
if (UD.connected) {
printk(KERN_INFO "fd%d\n", drive);
++cnt;
}
}
if (FDC_READ( FDCREG_STATUS ) & FDCSTAT_BUSY) {
/* If FDC is still busy from probing, give it another FORCI
* command to abort the operation. If this isn't done, the FDC
* will interrupt later and its IRQ line stays low, because
* the status register isn't read. And this will block any
* interrupts on this IRQ line :-(
*/
FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
udelay(500);
FDC_READ( FDCREG_STATUS );
udelay(20);
}
if (cnt > 0) {
start_motor_off_timer();
if (cnt == 1) fd_select_drive( 0 );
start_check_change_timer();
}
}
/*
* floppy_open check for aliasing (/dev/fd0 can be the same as
* /dev/PS0 etc), and disallows simultaneous access to the same
* drive with different device numbers.
*/
static int floppy_open(struct block_device *bdev, fmode_t mode)
{
struct atari_floppy_struct *p = bdev->bd_disk->private_data;
int type = MINOR(bdev->bd_dev) >> 2;
DPRINT(("fd_open: type=%d\n",type));
if (p->ref && p->type != type)
return -EBUSY;
if (p->ref == -1 || (p->ref && mode & FMODE_EXCL))
return -EBUSY;
if (mode & FMODE_EXCL)
p->ref = -1;
else
p->ref++;
p->type = type;
if (mode & FMODE_NDELAY)
return 0;
if (mode & (FMODE_READ|FMODE_WRITE)) {
check_disk_change(bdev);
if (mode & FMODE_WRITE) {
if (p->wpstat) {
if (p->ref < 0)
p->ref = 0;
else
p->ref--;
return -EROFS;
}
}
}
return 0;
}
static int floppy_unlocked_open(struct block_device *bdev, fmode_t mode)
{
int ret;
mutex_lock(&ataflop_mutex);
ret = floppy_open(bdev, mode);
mutex_unlock(&ataflop_mutex);
return ret;
}
static int floppy_release(struct gendisk *disk, fmode_t mode)
{
struct atari_floppy_struct *p = disk->private_data;
mutex_lock(&ataflop_mutex);
if (p->ref < 0)
p->ref = 0;
else if (!p->ref--) {
printk(KERN_ERR "floppy_release with fd_ref == 0");
p->ref = 0;
}
mutex_unlock(&ataflop_mutex);
return 0;
}
static const struct block_device_operations floppy_fops = {
.owner = THIS_MODULE,
.open = floppy_unlocked_open,
.release = floppy_release,
.ioctl = fd_ioctl,
.check_events = floppy_check_events,
.revalidate_disk= floppy_revalidate,
};
static struct kobject *floppy_find(dev_t dev, int *part, void *data)
{
int drive = *part & 3;
int type = *part >> 2;
if (drive >= FD_MAX_UNITS || type > NUM_DISK_MINORS)
return NULL;
*part = 0;
return get_disk(unit[drive].disk);
}
static int __init atari_floppy_init (void)
{
int i;
if (!MACH_IS_ATARI)
/* Amiga, Mac, ... don't have Atari-compatible floppy :-) */
return -ENODEV;
if (register_blkdev(FLOPPY_MAJOR,"fd"))
return -EBUSY;
for (i = 0; i < FD_MAX_UNITS; i++) {
unit[i].disk = alloc_disk(1);
if (!unit[i].disk)
goto Enomem;
}
if (UseTrackbuffer < 0)
/* not set by user -> use default: for now, we turn
track buffering off for all Medusas, though it
could be used with ones that have a counter
card. But the test is too hard :-( */
UseTrackbuffer = !MACH_IS_MEDUSA;
/* initialize variables */
SelectedDrive = -1;
BufferDrive = -1;
DMABuffer = atari_stram_alloc(BUFFER_SIZE+512, "ataflop");
if (!DMABuffer) {
printk(KERN_ERR "atari_floppy_init: cannot get dma buffer\n");
goto Enomem;
}
TrackBuffer = DMABuffer + 512;
PhysDMABuffer = virt_to_phys(DMABuffer);
PhysTrackBuffer = virt_to_phys(TrackBuffer);
BufferDrive = BufferSide = BufferTrack = -1;
for (i = 0; i < FD_MAX_UNITS; i++) {
unit[i].track = -1;
unit[i].flags = 0;
unit[i].disk->major = FLOPPY_MAJOR;
unit[i].disk->first_minor = i;
sprintf(unit[i].disk->disk_name, "fd%d", i);
unit[i].disk->fops = &floppy_fops;
unit[i].disk->private_data = &unit[i];
unit[i].disk->queue = blk_init_queue(do_fd_request,
&ataflop_lock);
if (!unit[i].disk->queue)
goto Enomem;
set_capacity(unit[i].disk, MAX_DISK_SIZE * 2);
add_disk(unit[i].disk);
}
blk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE,
floppy_find, NULL, NULL);
printk(KERN_INFO "Atari floppy driver: max. %cD, %strack buffering\n",
DriveType == 0 ? 'D' : DriveType == 1 ? 'H' : 'E',
UseTrackbuffer ? "" : "no ");
config_types();
return 0;
Enomem:
while (i--) {
struct request_queue *q = unit[i].disk->queue;
put_disk(unit[i].disk);
if (q)
blk_cleanup_queue(q);
}
unregister_blkdev(FLOPPY_MAJOR, "fd");
return -ENOMEM;
}
#ifndef MODULE
static int __init atari_floppy_setup(char *str)
{
int ints[3 + FD_MAX_UNITS];
int i;
if (!MACH_IS_ATARI)
return 0;
str = get_options(str, 3 + FD_MAX_UNITS, ints);
if (ints[0] < 1) {
printk(KERN_ERR "ataflop_setup: no arguments!\n" );
return 0;
}
else if (ints[0] > 2+FD_MAX_UNITS) {
printk(KERN_ERR "ataflop_setup: too many arguments\n" );
}
if (ints[1] < 0 || ints[1] > 2)
printk(KERN_ERR "ataflop_setup: bad drive type\n" );
else
DriveType = ints[1];
if (ints[0] >= 2)
UseTrackbuffer = (ints[2] > 0);
for( i = 3; i <= ints[0] && i-3 < FD_MAX_UNITS; ++i ) {
if (ints[i] != 2 && ints[i] != 3 && ints[i] != 6 && ints[i] != 12)
printk(KERN_ERR "ataflop_setup: bad steprate\n" );
else
UserSteprate[i-3] = ints[i];
}
return 1;
}
__setup("floppy=", atari_floppy_setup);
#endif
static void __exit atari_floppy_exit(void)
{
int i;
blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);
for (i = 0; i < FD_MAX_UNITS; i++) {
struct request_queue *q = unit[i].disk->queue;
del_gendisk(unit[i].disk);
put_disk(unit[i].disk);
blk_cleanup_queue(q);
}
unregister_blkdev(FLOPPY_MAJOR, "fd");
del_timer_sync(&fd_timer);
atari_stram_free( DMABuffer );
}
module_init(atari_floppy_init)
module_exit(atari_floppy_exit)
MODULE_LICENSE("GPL");
| gpl-2.0 |
freexperia/android_kernel_sony_msm8960t | drivers/block/ataflop.c | 8323 | 53212 | /*
* drivers/block/ataflop.c
*
* Copyright (C) 1993 Greg Harp
* Atari Support by Bjoern Brauel, Roman Hodek
*
* Big cleanup Sep 11..14 1994 Roman Hodek:
* - Driver now works interrupt driven
* - Support for two drives; should work, but I cannot test that :-(
* - Reading is done in whole tracks and buffered to speed up things
* - Disk change detection and drive deselecting after motor-off
* similar to TOS
* - Autodetection of disk format (DD/HD); untested yet, because I
* don't have an HD drive :-(
*
* Fixes Nov 13 1994 Martin Schaller:
* - Autodetection works now
* - Support for 5 1/4'' disks
* - Removed drive type (unknown on atari)
* - Do seeks with 8 Mhz
*
* Changes by Andreas Schwab:
* - After errors in multiple read mode try again reading single sectors
* (Feb 1995):
* - Clean up error handling
* - Set blk_size for proper size checking
* - Initialize track register when testing presence of floppy
* - Implement some ioctl's
*
* Changes by Torsten Lang:
* - When probing the floppies we should add the FDCCMDADD_H flag since
* the FDC will otherwise wait forever when no disk is inserted...
*
* ++ Freddi Aschwanden (fa) 20.9.95 fixes for medusa:
* - MFPDELAY() after each FDC access -> atari
* - more/other disk formats
* - DMA to the block buffer directly if we have a 32bit DMA
* - for medusa, the step rate is always 3ms
* - on medusa, use only cache_push()
* Roman:
* - Make disk format numbering independent from minors
* - Let user set max. supported drive type (speeds up format
* detection, saves buffer space)
*
* Roman 10/15/95:
* - implement some more ioctls
* - disk formatting
*
* Andreas 95/12/12:
* - increase gap size at start of track for HD/ED disks
*
* Michael (MSch) 11/07/96:
* - implemented FDSETPRM and FDDEFPRM ioctl
*
* Andreas (97/03/19):
* - implemented missing BLK* ioctls
*
* Things left to do:
* - Formatting
* - Maybe a better strategy for disk change detection (does anyone
* know one?)
*/
#include <linux/module.h>
#include <linux/fd.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/mutex.h>
#include <asm/atafd.h>
#include <asm/atafdreg.h>
#include <asm/atariints.h>
#include <asm/atari_stdma.h>
#include <asm/atari_stram.h>
#define FD_MAX_UNITS 2
#undef DEBUG
static DEFINE_MUTEX(ataflop_mutex);
static struct request *fd_request;
static int fdc_queue;
/* Disk types: DD, HD, ED */
static struct atari_disk_type {
const char *name;
unsigned spt; /* sectors per track */
unsigned blocks; /* total number of blocks */
unsigned fdc_speed; /* fdc_speed setting */
unsigned stretch; /* track doubling ? */
} atari_disk_type[] = {
{ "d360", 9, 720, 0, 0}, /* 0: 360kB diskette */
{ "D360", 9, 720, 0, 1}, /* 1: 360kb in 720k or 1.2MB drive */
{ "D720", 9,1440, 0, 0}, /* 2: 720kb in 720k or 1.2MB drive */
{ "D820", 10,1640, 0, 0}, /* 3: DD disk with 82 tracks/10 sectors */
/* formats above are probed for type DD */
#define MAX_TYPE_DD 3
{ "h1200",15,2400, 3, 0}, /* 4: 1.2MB diskette */
{ "H1440",18,2880, 3, 0}, /* 5: 1.4 MB diskette (HD) */
{ "H1640",20,3280, 3, 0}, /* 6: 1.64MB diskette (fat HD) 82 tr 20 sec */
/* formats above are probed for types DD and HD */
#define MAX_TYPE_HD 6
{ "E2880",36,5760, 3, 0}, /* 7: 2.8 MB diskette (ED) */
{ "E3280",40,6560, 3, 0}, /* 8: 3.2 MB diskette (fat ED) 82 tr 40 sec */
/* formats above are probed for types DD, HD and ED */
#define MAX_TYPE_ED 8
/* types below are never autoprobed */
{ "H1680",21,3360, 3, 0}, /* 9: 1.68MB diskette (fat HD) 80 tr 21 sec */
{ "h410",10,820, 0, 1}, /* 10: 410k diskette 41 tr 10 sec, stretch */
{ "h1476",18,2952, 3, 0}, /* 11: 1.48MB diskette 82 tr 18 sec */
{ "H1722",21,3444, 3, 0}, /* 12: 1.72MB diskette 82 tr 21 sec */
{ "h420",10,840, 0, 1}, /* 13: 420k diskette 42 tr 10 sec, stretch */
{ "H830",10,1660, 0, 0}, /* 14: 820k diskette 83 tr 10 sec */
{ "h1494",18,2952, 3, 0}, /* 15: 1.49MB diskette 83 tr 18 sec */
{ "H1743",21,3486, 3, 0}, /* 16: 1.74MB diskette 83 tr 21 sec */
{ "h880",11,1760, 0, 0}, /* 17: 880k diskette 80 tr 11 sec */
{ "D1040",13,2080, 0, 0}, /* 18: 1.04MB diskette 80 tr 13 sec */
{ "D1120",14,2240, 0, 0}, /* 19: 1.12MB diskette 80 tr 14 sec */
{ "h1600",20,3200, 3, 0}, /* 20: 1.60MB diskette 80 tr 20 sec */
{ "H1760",22,3520, 3, 0}, /* 21: 1.76MB diskette 80 tr 22 sec */
{ "H1920",24,3840, 3, 0}, /* 22: 1.92MB diskette 80 tr 24 sec */
{ "E3200",40,6400, 3, 0}, /* 23: 3.2MB diskette 80 tr 40 sec */
{ "E3520",44,7040, 3, 0}, /* 24: 3.52MB diskette 80 tr 44 sec */
{ "E3840",48,7680, 3, 0}, /* 25: 3.84MB diskette 80 tr 48 sec */
{ "H1840",23,3680, 3, 0}, /* 26: 1.84MB diskette 80 tr 23 sec */
{ "D800",10,1600, 0, 0}, /* 27: 800k diskette 80 tr 10 sec */
};
static int StartDiskType[] = {
MAX_TYPE_DD,
MAX_TYPE_HD,
MAX_TYPE_ED
};
#define TYPE_DD 0
#define TYPE_HD 1
#define TYPE_ED 2
static int DriveType = TYPE_HD;
static DEFINE_SPINLOCK(ataflop_lock);
/* Array for translating minors into disk formats */
static struct {
int index;
unsigned drive_types;
} minor2disktype[] = {
{ 0, TYPE_DD }, /* 1: d360 */
{ 4, TYPE_HD }, /* 2: h1200 */
{ 1, TYPE_DD }, /* 3: D360 */
{ 2, TYPE_DD }, /* 4: D720 */
{ 1, TYPE_DD }, /* 5: h360 = D360 */
{ 2, TYPE_DD }, /* 6: h720 = D720 */
{ 5, TYPE_HD }, /* 7: H1440 */
{ 7, TYPE_ED }, /* 8: E2880 */
/* some PC formats :-) */
{ 8, TYPE_ED }, /* 9: E3280 <- was "CompaQ" == E2880 for PC */
{ 5, TYPE_HD }, /* 10: h1440 = H1440 */
{ 9, TYPE_HD }, /* 11: H1680 */
{ 10, TYPE_DD }, /* 12: h410 */
{ 3, TYPE_DD }, /* 13: H820 <- == D820, 82x10 */
{ 11, TYPE_HD }, /* 14: h1476 */
{ 12, TYPE_HD }, /* 15: H1722 */
{ 13, TYPE_DD }, /* 16: h420 */
{ 14, TYPE_DD }, /* 17: H830 */
{ 15, TYPE_HD }, /* 18: h1494 */
{ 16, TYPE_HD }, /* 19: H1743 */
{ 17, TYPE_DD }, /* 20: h880 */
{ 18, TYPE_DD }, /* 21: D1040 */
{ 19, TYPE_DD }, /* 22: D1120 */
{ 20, TYPE_HD }, /* 23: h1600 */
{ 21, TYPE_HD }, /* 24: H1760 */
{ 22, TYPE_HD }, /* 25: H1920 */
{ 23, TYPE_ED }, /* 26: E3200 */
{ 24, TYPE_ED }, /* 27: E3520 */
{ 25, TYPE_ED }, /* 28: E3840 */
{ 26, TYPE_HD }, /* 29: H1840 */
{ 27, TYPE_DD }, /* 30: D800 */
{ 6, TYPE_HD }, /* 31: H1640 <- was H1600 == h1600 for PC */
};
#define NUM_DISK_MINORS ARRAY_SIZE(minor2disktype)
/*
* Maximum disk size (in kilobytes). This default is used whenever the
* current disk size is unknown.
*/
#define MAX_DISK_SIZE 3280
/*
* MSch: User-provided type information. 'drive' points to
* the respective entry of this array. Set by FDSETPRM ioctls.
*/
static struct atari_disk_type user_params[FD_MAX_UNITS];
/*
* User-provided permanent type information. 'drive' points to
* the respective entry of this array. Set by FDDEFPRM ioctls,
* restored upon disk change by floppy_revalidate() if valid (as seen by
* default_params[].blocks > 0 - a bit in unit[].flags might be used for this?)
*/
static struct atari_disk_type default_params[FD_MAX_UNITS];
/* current info on each unit */
static struct atari_floppy_struct {
int connected; /* !=0 : drive is connected */
int autoprobe; /* !=0 : do autoprobe */
struct atari_disk_type *disktype; /* current type of disk */
int track; /* current head position or -1 if
unknown */
unsigned int steprate; /* steprate setting */
unsigned int wpstat; /* current state of WP signal (for
disk change detection) */
int flags; /* flags */
struct gendisk *disk;
int ref;
int type;
} unit[FD_MAX_UNITS];
#define UD unit[drive]
#define UDT unit[drive].disktype
#define SUD unit[SelectedDrive]
#define SUDT unit[SelectedDrive].disktype
#define FDC_READ(reg) ({ \
/* unsigned long __flags; */ \
unsigned short __val; \
/* local_irq_save(__flags); */ \
dma_wd.dma_mode_status = 0x80 | (reg); \
udelay(25); \
__val = dma_wd.fdc_acces_seccount; \
MFPDELAY(); \
/* local_irq_restore(__flags); */ \
__val & 0xff; \
})
#define FDC_WRITE(reg,val) \
do { \
/* unsigned long __flags; */ \
/* local_irq_save(__flags); */ \
dma_wd.dma_mode_status = 0x80 | (reg); \
udelay(25); \
dma_wd.fdc_acces_seccount = (val); \
MFPDELAY(); \
/* local_irq_restore(__flags); */ \
} while(0)
/* Buffering variables:
* First, there is a DMA buffer in ST-RAM that is used for floppy DMA
* operations. Second, a track buffer is used to cache a whole track
* of the disk to save read operations. These are two separate buffers
* because that allows write operations without clearing the track buffer.
*/
static int MaxSectors[] = {
11, 22, 44
};
static int BufferSize[] = {
15*512, 30*512, 60*512
};
#define BUFFER_SIZE (BufferSize[DriveType])
unsigned char *DMABuffer; /* buffer for writes */
static unsigned long PhysDMABuffer; /* physical address */
static int UseTrackbuffer = -1; /* Do track buffering? */
module_param(UseTrackbuffer, int, 0);
unsigned char *TrackBuffer; /* buffer for reads */
static unsigned long PhysTrackBuffer; /* physical address */
static int BufferDrive, BufferSide, BufferTrack;
static int read_track; /* non-zero if we are reading whole tracks */
#define SECTOR_BUFFER(sec) (TrackBuffer + ((sec)-1)*512)
#define IS_BUFFERED(drive,side,track) \
(BufferDrive == (drive) && BufferSide == (side) && BufferTrack == (track))
/*
* These are global variables, as that's the easiest way to give
* information to interrupts. They are the data used for the current
* request.
*/
static int SelectedDrive = 0;
static int ReqCmd, ReqBlock;
static int ReqSide, ReqTrack, ReqSector, ReqCnt;
static int HeadSettleFlag = 0;
static unsigned char *ReqData, *ReqBuffer;
static int MotorOn = 0, MotorOffTrys;
static int IsFormatting = 0, FormatError;
static int UserSteprate[FD_MAX_UNITS] = { -1, -1 };
module_param_array(UserSteprate, int, NULL, 0);
/* Synchronization of FDC access. */
static volatile int fdc_busy = 0;
static DECLARE_WAIT_QUEUE_HEAD(fdc_wait);
static DECLARE_WAIT_QUEUE_HEAD(format_wait);
static unsigned long changed_floppies = 0xff, fake_change = 0;
#define CHECK_CHANGE_DELAY HZ/2
#define FD_MOTOR_OFF_DELAY (3*HZ)
#define FD_MOTOR_OFF_MAXTRY (10*20)
#define FLOPPY_TIMEOUT (6*HZ)
#define RECALIBRATE_ERRORS 4 /* After this many errors the drive
* will be recalibrated. */
#define MAX_ERRORS 8 /* After this many errors the driver
* will give up. */
/*
* The driver is trying to determine the correct media format
* while Probing is set. fd_rwsec_done() clears it after a
* successful access.
*/
static int Probing = 0;
/* This flag is set when a dummy seek is necessary to make the WP
* status bit accessible.
*/
static int NeedSeek = 0;
#ifdef DEBUG
#define DPRINT(a) printk a
#else
#define DPRINT(a)
#endif
/***************************** Prototypes *****************************/
static void fd_select_side( int side );
static void fd_select_drive( int drive );
static void fd_deselect( void );
static void fd_motor_off_timer( unsigned long dummy );
static void check_change( unsigned long dummy );
static irqreturn_t floppy_irq (int irq, void *dummy);
static void fd_error( void );
static int do_format(int drive, int type, struct atari_format_descr *desc);
static void do_fd_action( int drive );
static void fd_calibrate( void );
static void fd_calibrate_done( int status );
static void fd_seek( void );
static void fd_seek_done( int status );
static void fd_rwsec( void );
static void fd_readtrack_check( unsigned long dummy );
static void fd_rwsec_done( int status );
static void fd_rwsec_done1(int status);
static void fd_writetrack( void );
static void fd_writetrack_done( int status );
static void fd_times_out( unsigned long dummy );
static void finish_fdc( void );
static void finish_fdc_done( int dummy );
static void setup_req_params( int drive );
static void redo_fd_request( void);
static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode, unsigned int
cmd, unsigned long param);
static void fd_probe( int drive );
static int fd_test_drive_present( int drive );
static void config_types( void );
static int floppy_open(struct block_device *bdev, fmode_t mode);
static int floppy_release(struct gendisk *disk, fmode_t mode);
/************************* End of Prototypes **************************/
static DEFINE_TIMER(motor_off_timer, fd_motor_off_timer, 0, 0);
static DEFINE_TIMER(readtrack_timer, fd_readtrack_check, 0, 0);
static DEFINE_TIMER(timeout_timer, fd_times_out, 0, 0);
static DEFINE_TIMER(fd_timer, check_change, 0, 0);
static void fd_end_request_cur(int err)
{
if (!__blk_end_request_cur(fd_request, err))
fd_request = NULL;
}
static inline void start_motor_off_timer(void)
{
mod_timer(&motor_off_timer, jiffies + FD_MOTOR_OFF_DELAY);
MotorOffTrys = 0;
}
static inline void start_check_change_timer( void )
{
mod_timer(&fd_timer, jiffies + CHECK_CHANGE_DELAY);
}
static inline void start_timeout(void)
{
mod_timer(&timeout_timer, jiffies + FLOPPY_TIMEOUT);
}
static inline void stop_timeout(void)
{
del_timer(&timeout_timer);
}
/* Select the side to use. */
static void fd_select_side( int side )
{
unsigned long flags;
/* protect against various other ints mucking around with the PSG */
local_irq_save(flags);
sound_ym.rd_data_reg_sel = 14; /* Select PSG Port A */
sound_ym.wd_data = (side == 0) ? sound_ym.rd_data_reg_sel | 0x01 :
sound_ym.rd_data_reg_sel & 0xfe;
local_irq_restore(flags);
}
/* Select a drive, update the FDC's track register and set the correct
* clock speed for this disk's type.
*/
static void fd_select_drive( int drive )
{
unsigned long flags;
unsigned char tmp;
if (drive == SelectedDrive)
return;
/* protect against various other ints mucking around with the PSG */
local_irq_save(flags);
sound_ym.rd_data_reg_sel = 14; /* Select PSG Port A */
tmp = sound_ym.rd_data_reg_sel;
sound_ym.wd_data = (tmp | DSKDRVNONE) & ~(drive == 0 ? DSKDRV0 : DSKDRV1);
atari_dont_touch_floppy_select = 1;
local_irq_restore(flags);
/* restore track register to saved value */
FDC_WRITE( FDCREG_TRACK, UD.track );
udelay(25);
/* select 8/16 MHz */
if (UDT)
if (ATARIHW_PRESENT(FDCSPEED))
dma_wd.fdc_speed = UDT->fdc_speed;
SelectedDrive = drive;
}
/* Deselect both drives. */
static void fd_deselect( void )
{
unsigned long flags;
/* protect against various other ints mucking around with the PSG */
local_irq_save(flags);
atari_dont_touch_floppy_select = 0;
sound_ym.rd_data_reg_sel=14; /* Select PSG Port A */
sound_ym.wd_data = (sound_ym.rd_data_reg_sel |
(MACH_IS_FALCON ? 3 : 7)); /* no drives selected */
/* On Falcon, the drive B select line is used on the printer port, so
* leave it alone... */
SelectedDrive = -1;
local_irq_restore(flags);
}
/* This timer function deselects the drives when the FDC switched the
* motor off. The deselection cannot happen earlier because the FDC
* counts the index signals, which arrive only if one drive is selected.
*/
static void fd_motor_off_timer( unsigned long dummy )
{
unsigned char status;
if (SelectedDrive < 0)
/* no drive selected, needn't deselect anyone */
return;
if (stdma_islocked())
goto retry;
status = FDC_READ( FDCREG_STATUS );
if (!(status & 0x80)) {
/* motor already turned off by FDC -> deselect drives */
MotorOn = 0;
fd_deselect();
return;
}
/* not yet off, try again */
retry:
/* Test again later; if tested too often, it seems there is no disk
* in the drive and the FDC will leave the motor on forever (or,
* at least until a disk is inserted). So we'll test only twice
* per second from then on...
*/
mod_timer(&motor_off_timer,
jiffies + (MotorOffTrys++ < FD_MOTOR_OFF_MAXTRY ? HZ/20 : HZ/2));
}
/* This function is repeatedly called to detect disk changes (as good
* as possible) and keep track of the current state of the write protection.
*/
static void check_change( unsigned long dummy )
{
static int drive = 0;
unsigned long flags;
unsigned char old_porta;
int stat;
if (++drive > 1 || !UD.connected)
drive = 0;
/* protect against various other ints mucking around with the PSG */
local_irq_save(flags);
if (!stdma_islocked()) {
sound_ym.rd_data_reg_sel = 14;
old_porta = sound_ym.rd_data_reg_sel;
sound_ym.wd_data = (old_porta | DSKDRVNONE) &
~(drive == 0 ? DSKDRV0 : DSKDRV1);
stat = !!(FDC_READ( FDCREG_STATUS ) & FDCSTAT_WPROT);
sound_ym.wd_data = old_porta;
if (stat != UD.wpstat) {
DPRINT(( "wpstat[%d] = %d\n", drive, stat ));
UD.wpstat = stat;
set_bit (drive, &changed_floppies);
}
}
local_irq_restore(flags);
start_check_change_timer();
}
/* Handling of the Head Settling Flag: This flag should be set after each
* seek operation, because we don't use seeks with verify.
*/
static inline void set_head_settle_flag(void)
{
HeadSettleFlag = FDCCMDADD_E;
}
static inline int get_head_settle_flag(void)
{
int tmp = HeadSettleFlag;
HeadSettleFlag = 0;
return( tmp );
}
static inline void copy_buffer(void *from, void *to)
{
ulong *p1 = (ulong *)from, *p2 = (ulong *)to;
int cnt;
for (cnt = 512/4; cnt; cnt--)
*p2++ = *p1++;
}
/* General Interrupt Handling */
static void (*FloppyIRQHandler)( int status ) = NULL;
static irqreturn_t floppy_irq (int irq, void *dummy)
{
unsigned char status;
void (*handler)( int );
handler = xchg(&FloppyIRQHandler, NULL);
if (handler) {
nop();
status = FDC_READ( FDCREG_STATUS );
DPRINT(("FDC irq, status = %02x handler = %08lx\n",status,(unsigned long)handler));
handler( status );
}
else {
DPRINT(("FDC irq, no handler\n"));
}
return IRQ_HANDLED;
}
/* Error handling: If some error happened, retry some times, then
* recalibrate, then try again, and fail after MAX_ERRORS.
*/
static void fd_error( void )
{
if (IsFormatting) {
IsFormatting = 0;
FormatError = 1;
wake_up( &format_wait );
return;
}
if (!fd_request)
return;
fd_request->errors++;
if (fd_request->errors >= MAX_ERRORS) {
printk(KERN_ERR "fd%d: too many errors.\n", SelectedDrive );
fd_end_request_cur(-EIO);
}
else if (fd_request->errors == RECALIBRATE_ERRORS) {
printk(KERN_WARNING "fd%d: recalibrating\n", SelectedDrive );
if (SelectedDrive != -1)
SUD.track = -1;
}
redo_fd_request();
}
#define SET_IRQ_HANDLER(proc) do { FloppyIRQHandler = (proc); } while(0)
/* ---------- Formatting ---------- */
#define FILL(n,val) \
do { \
memset( p, val, n ); \
p += n; \
} while(0)
static int do_format(int drive, int type, struct atari_format_descr *desc)
{
unsigned char *p;
int sect, nsect;
unsigned long flags;
DPRINT(("do_format( dr=%d tr=%d he=%d offs=%d )\n",
drive, desc->track, desc->head, desc->sect_offset ));
local_irq_save(flags);
while( fdc_busy ) sleep_on( &fdc_wait );
fdc_busy = 1;
stdma_lock(floppy_irq, NULL);
atari_turnon_irq( IRQ_MFP_FDC ); /* should be already, just to be sure */
local_irq_restore(flags);
if (type) {
if (--type >= NUM_DISK_MINORS ||
minor2disktype[type].drive_types > DriveType) {
redo_fd_request();
return -EINVAL;
}
type = minor2disktype[type].index;
UDT = &atari_disk_type[type];
}
if (!UDT || desc->track >= UDT->blocks/UDT->spt/2 || desc->head >= 2) {
redo_fd_request();
return -EINVAL;
}
nsect = UDT->spt;
p = TrackBuffer;
/* The track buffer is used for the raw track data, so its
contents become invalid! */
BufferDrive = -1;
/* stop deselect timer */
del_timer( &motor_off_timer );
FILL( 60 * (nsect / 9), 0x4e );
for( sect = 0; sect < nsect; ++sect ) {
FILL( 12, 0 );
FILL( 3, 0xf5 );
*p++ = 0xfe;
*p++ = desc->track;
*p++ = desc->head;
*p++ = (nsect + sect - desc->sect_offset) % nsect + 1;
*p++ = 2;
*p++ = 0xf7;
FILL( 22, 0x4e );
FILL( 12, 0 );
FILL( 3, 0xf5 );
*p++ = 0xfb;
FILL( 512, 0xe5 );
*p++ = 0xf7;
FILL( 40, 0x4e );
}
FILL( TrackBuffer+BUFFER_SIZE-p, 0x4e );
IsFormatting = 1;
FormatError = 0;
ReqTrack = desc->track;
ReqSide = desc->head;
do_fd_action( drive );
sleep_on( &format_wait );
redo_fd_request();
return( FormatError ? -EIO : 0 );
}
/* do_fd_action() is the general procedure for a fd request: All
* required parameter settings (drive select, side select, track
* position) are checked and set if needed. For each of these
* parameters and the actual reading or writing exist two functions:
* one that starts the setting (or skips it if possible) and one
* callback for the "done" interrupt. Each done func calls the next
* set function to propagate the request down to fd_rwsec_done().
*/
static void do_fd_action( int drive )
{
DPRINT(("do_fd_action\n"));
if (UseTrackbuffer && !IsFormatting) {
repeat:
if (IS_BUFFERED( drive, ReqSide, ReqTrack )) {
if (ReqCmd == READ) {
copy_buffer( SECTOR_BUFFER(ReqSector), ReqData );
if (++ReqCnt < blk_rq_cur_sectors(fd_request)) {
/* read next sector */
setup_req_params( drive );
goto repeat;
}
else {
/* all sectors finished */
fd_end_request_cur(0);
redo_fd_request();
return;
}
}
else {
/* cmd == WRITE, pay attention to track buffer
* consistency! */
copy_buffer( ReqData, SECTOR_BUFFER(ReqSector) );
}
}
}
if (SelectedDrive != drive)
fd_select_drive( drive );
if (UD.track == -1)
fd_calibrate();
else if (UD.track != ReqTrack << UDT->stretch)
fd_seek();
else if (IsFormatting)
fd_writetrack();
else
fd_rwsec();
}
/* Seek to track 0 if the current track is unknown */
static void fd_calibrate( void )
{
if (SUD.track >= 0) {
fd_calibrate_done( 0 );
return;
}
if (ATARIHW_PRESENT(FDCSPEED))
dma_wd.fdc_speed = 0; /* always seek with 8 Mhz */;
DPRINT(("fd_calibrate\n"));
SET_IRQ_HANDLER( fd_calibrate_done );
/* we can't verify, since the speed may be incorrect */
FDC_WRITE( FDCREG_CMD, FDCCMD_RESTORE | SUD.steprate );
NeedSeek = 1;
MotorOn = 1;
start_timeout();
/* wait for IRQ */
}
static void fd_calibrate_done( int status )
{
DPRINT(("fd_calibrate_done()\n"));
stop_timeout();
/* set the correct speed now */
if (ATARIHW_PRESENT(FDCSPEED))
dma_wd.fdc_speed = SUDT->fdc_speed;
if (status & FDCSTAT_RECNF) {
printk(KERN_ERR "fd%d: restore failed\n", SelectedDrive );
fd_error();
}
else {
SUD.track = 0;
fd_seek();
}
}
/* Seek the drive to the requested track. The drive must have been
* calibrated at some point before this.
*/
static void fd_seek( void )
{
if (SUD.track == ReqTrack << SUDT->stretch) {
fd_seek_done( 0 );
return;
}
if (ATARIHW_PRESENT(FDCSPEED)) {
dma_wd.fdc_speed = 0; /* always seek witch 8 Mhz */
MFPDELAY();
}
DPRINT(("fd_seek() to track %d\n",ReqTrack));
FDC_WRITE( FDCREG_DATA, ReqTrack << SUDT->stretch);
udelay(25);
SET_IRQ_HANDLER( fd_seek_done );
FDC_WRITE( FDCREG_CMD, FDCCMD_SEEK | SUD.steprate );
MotorOn = 1;
set_head_settle_flag();
start_timeout();
/* wait for IRQ */
}
static void fd_seek_done( int status )
{
DPRINT(("fd_seek_done()\n"));
stop_timeout();
/* set the correct speed */
if (ATARIHW_PRESENT(FDCSPEED))
dma_wd.fdc_speed = SUDT->fdc_speed;
if (status & FDCSTAT_RECNF) {
printk(KERN_ERR "fd%d: seek error (to track %d)\n",
SelectedDrive, ReqTrack );
/* we don't know exactly which track we are on now! */
SUD.track = -1;
fd_error();
}
else {
SUD.track = ReqTrack << SUDT->stretch;
NeedSeek = 0;
if (IsFormatting)
fd_writetrack();
else
fd_rwsec();
}
}
/* This does the actual reading/writing after positioning the head
* over the correct track.
*/
static int MultReadInProgress = 0;
static void fd_rwsec( void )
{
unsigned long paddr, flags;
unsigned int rwflag, old_motoron;
unsigned int track;
DPRINT(("fd_rwsec(), Sec=%d, Access=%c\n",ReqSector, ReqCmd == WRITE ? 'w' : 'r' ));
if (ReqCmd == WRITE) {
if (ATARIHW_PRESENT(EXTD_DMA)) {
paddr = virt_to_phys(ReqData);
}
else {
copy_buffer( ReqData, DMABuffer );
paddr = PhysDMABuffer;
}
dma_cache_maintenance( paddr, 512, 1 );
rwflag = 0x100;
}
else {
if (read_track)
paddr = PhysTrackBuffer;
else
paddr = ATARIHW_PRESENT(EXTD_DMA) ?
virt_to_phys(ReqData) : PhysDMABuffer;
rwflag = 0;
}
fd_select_side( ReqSide );
/* Start sector of this operation */
FDC_WRITE( FDCREG_SECTOR, read_track ? 1 : ReqSector );
MFPDELAY();
/* Cheat for track if stretch != 0 */
if (SUDT->stretch) {
track = FDC_READ( FDCREG_TRACK);
MFPDELAY();
FDC_WRITE( FDCREG_TRACK, track >> SUDT->stretch);
}
udelay(25);
/* Setup DMA */
local_irq_save(flags);
dma_wd.dma_lo = (unsigned char)paddr;
MFPDELAY();
paddr >>= 8;
dma_wd.dma_md = (unsigned char)paddr;
MFPDELAY();
paddr >>= 8;
if (ATARIHW_PRESENT(EXTD_DMA))
st_dma_ext_dmahi = (unsigned short)paddr;
else
dma_wd.dma_hi = (unsigned char)paddr;
MFPDELAY();
local_irq_restore(flags);
/* Clear FIFO and switch DMA to correct mode */
dma_wd.dma_mode_status = 0x90 | rwflag;
MFPDELAY();
dma_wd.dma_mode_status = 0x90 | (rwflag ^ 0x100);
MFPDELAY();
dma_wd.dma_mode_status = 0x90 | rwflag;
MFPDELAY();
/* How many sectors for DMA */
dma_wd.fdc_acces_seccount = read_track ? SUDT->spt : 1;
udelay(25);
/* Start operation */
dma_wd.dma_mode_status = FDCSELREG_STP | rwflag;
udelay(25);
SET_IRQ_HANDLER( fd_rwsec_done );
dma_wd.fdc_acces_seccount =
(get_head_settle_flag() |
(rwflag ? FDCCMD_WRSEC : (FDCCMD_RDSEC | (read_track ? FDCCMDADD_M : 0))));
old_motoron = MotorOn;
MotorOn = 1;
NeedSeek = 1;
/* wait for interrupt */
if (read_track) {
/* If reading a whole track, wait about one disk rotation and
* then check if all sectors are read. The FDC will even
* search for the first non-existent sector and need 1 sec to
* recognise that it isn't present :-(
*/
MultReadInProgress = 1;
mod_timer(&readtrack_timer,
/* 1 rot. + 5 rot.s if motor was off */
jiffies + HZ/5 + (old_motoron ? 0 : HZ));
}
start_timeout();
}
static void fd_readtrack_check( unsigned long dummy )
{
unsigned long flags, addr, addr2;
local_irq_save(flags);
if (!MultReadInProgress) {
/* This prevents a race condition that could arise if the
* interrupt is triggered while the calling of this timer
* callback function takes place. The IRQ function then has
* already cleared 'MultReadInProgress' when flow of control
* gets here.
*/
local_irq_restore(flags);
return;
}
/* get the current DMA address */
/* ++ f.a. read twice to avoid being fooled by switcher */
addr = 0;
do {
addr2 = addr;
addr = dma_wd.dma_lo & 0xff;
MFPDELAY();
addr |= (dma_wd.dma_md & 0xff) << 8;
MFPDELAY();
if (ATARIHW_PRESENT( EXTD_DMA ))
addr |= (st_dma_ext_dmahi & 0xffff) << 16;
else
addr |= (dma_wd.dma_hi & 0xff) << 16;
MFPDELAY();
} while(addr != addr2);
if (addr >= PhysTrackBuffer + SUDT->spt*512) {
/* already read enough data, force an FDC interrupt to stop
* the read operation
*/
SET_IRQ_HANDLER( NULL );
MultReadInProgress = 0;
local_irq_restore(flags);
DPRINT(("fd_readtrack_check(): done\n"));
FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
udelay(25);
/* No error until now -- the FDC would have interrupted
* otherwise!
*/
fd_rwsec_done1(0);
}
else {
/* not yet finished, wait another tenth rotation */
local_irq_restore(flags);
DPRINT(("fd_readtrack_check(): not yet finished\n"));
mod_timer(&readtrack_timer, jiffies + HZ/5/10);
}
}
static void fd_rwsec_done( int status )
{
DPRINT(("fd_rwsec_done()\n"));
if (read_track) {
del_timer(&readtrack_timer);
if (!MultReadInProgress)
return;
MultReadInProgress = 0;
}
fd_rwsec_done1(status);
}
static void fd_rwsec_done1(int status)
{
unsigned int track;
stop_timeout();
/* Correct the track if stretch != 0 */
if (SUDT->stretch) {
track = FDC_READ( FDCREG_TRACK);
MFPDELAY();
FDC_WRITE( FDCREG_TRACK, track << SUDT->stretch);
}
if (!UseTrackbuffer) {
dma_wd.dma_mode_status = 0x90;
MFPDELAY();
if (!(dma_wd.dma_mode_status & 0x01)) {
printk(KERN_ERR "fd%d: DMA error\n", SelectedDrive );
goto err_end;
}
}
MFPDELAY();
if (ReqCmd == WRITE && (status & FDCSTAT_WPROT)) {
printk(KERN_NOTICE "fd%d: is write protected\n", SelectedDrive );
goto err_end;
}
if ((status & FDCSTAT_RECNF) &&
/* RECNF is no error after a multiple read when the FDC
searched for a non-existent sector! */
!(read_track && FDC_READ(FDCREG_SECTOR) > SUDT->spt)) {
if (Probing) {
if (SUDT > atari_disk_type) {
if (SUDT[-1].blocks > ReqBlock) {
/* try another disk type */
SUDT--;
set_capacity(unit[SelectedDrive].disk,
SUDT->blocks);
} else
Probing = 0;
}
else {
if (SUD.flags & FTD_MSG)
printk(KERN_INFO "fd%d: Auto-detected floppy type %s\n",
SelectedDrive, SUDT->name );
Probing=0;
}
} else {
/* record not found, but not probing. Maybe stretch wrong ? Restart probing */
if (SUD.autoprobe) {
SUDT = atari_disk_type + StartDiskType[DriveType];
set_capacity(unit[SelectedDrive].disk,
SUDT->blocks);
Probing = 1;
}
}
if (Probing) {
if (ATARIHW_PRESENT(FDCSPEED)) {
dma_wd.fdc_speed = SUDT->fdc_speed;
MFPDELAY();
}
setup_req_params( SelectedDrive );
BufferDrive = -1;
do_fd_action( SelectedDrive );
return;
}
printk(KERN_ERR "fd%d: sector %d not found (side %d, track %d)\n",
SelectedDrive, FDC_READ (FDCREG_SECTOR), ReqSide, ReqTrack );
goto err_end;
}
if (status & FDCSTAT_CRC) {
printk(KERN_ERR "fd%d: CRC error (side %d, track %d, sector %d)\n",
SelectedDrive, ReqSide, ReqTrack, FDC_READ (FDCREG_SECTOR) );
goto err_end;
}
if (status & FDCSTAT_LOST) {
printk(KERN_ERR "fd%d: lost data (side %d, track %d, sector %d)\n",
SelectedDrive, ReqSide, ReqTrack, FDC_READ (FDCREG_SECTOR) );
goto err_end;
}
Probing = 0;
if (ReqCmd == READ) {
if (!read_track) {
void *addr;
addr = ATARIHW_PRESENT( EXTD_DMA ) ? ReqData : DMABuffer;
dma_cache_maintenance( virt_to_phys(addr), 512, 0 );
if (!ATARIHW_PRESENT( EXTD_DMA ))
copy_buffer (addr, ReqData);
} else {
dma_cache_maintenance( PhysTrackBuffer, MaxSectors[DriveType] * 512, 0 );
BufferDrive = SelectedDrive;
BufferSide = ReqSide;
BufferTrack = ReqTrack;
copy_buffer (SECTOR_BUFFER (ReqSector), ReqData);
}
}
if (++ReqCnt < blk_rq_cur_sectors(fd_request)) {
/* read next sector */
setup_req_params( SelectedDrive );
do_fd_action( SelectedDrive );
}
else {
/* all sectors finished */
fd_end_request_cur(0);
redo_fd_request();
}
return;
err_end:
BufferDrive = -1;
fd_error();
}
static void fd_writetrack( void )
{
unsigned long paddr, flags;
unsigned int track;
DPRINT(("fd_writetrack() Tr=%d Si=%d\n", ReqTrack, ReqSide ));
paddr = PhysTrackBuffer;
dma_cache_maintenance( paddr, BUFFER_SIZE, 1 );
fd_select_side( ReqSide );
/* Cheat for track if stretch != 0 */
if (SUDT->stretch) {
track = FDC_READ( FDCREG_TRACK);
MFPDELAY();
FDC_WRITE(FDCREG_TRACK,track >> SUDT->stretch);
}
udelay(40);
/* Setup DMA */
local_irq_save(flags);
dma_wd.dma_lo = (unsigned char)paddr;
MFPDELAY();
paddr >>= 8;
dma_wd.dma_md = (unsigned char)paddr;
MFPDELAY();
paddr >>= 8;
if (ATARIHW_PRESENT( EXTD_DMA ))
st_dma_ext_dmahi = (unsigned short)paddr;
else
dma_wd.dma_hi = (unsigned char)paddr;
MFPDELAY();
local_irq_restore(flags);
/* Clear FIFO and switch DMA to correct mode */
dma_wd.dma_mode_status = 0x190;
MFPDELAY();
dma_wd.dma_mode_status = 0x90;
MFPDELAY();
dma_wd.dma_mode_status = 0x190;
MFPDELAY();
/* How many sectors for DMA */
dma_wd.fdc_acces_seccount = BUFFER_SIZE/512;
udelay(40);
/* Start operation */
dma_wd.dma_mode_status = FDCSELREG_STP | 0x100;
udelay(40);
SET_IRQ_HANDLER( fd_writetrack_done );
dma_wd.fdc_acces_seccount = FDCCMD_WRTRA | get_head_settle_flag();
MotorOn = 1;
start_timeout();
/* wait for interrupt */
}
static void fd_writetrack_done( int status )
{
DPRINT(("fd_writetrack_done()\n"));
stop_timeout();
if (status & FDCSTAT_WPROT) {
printk(KERN_NOTICE "fd%d: is write protected\n", SelectedDrive );
goto err_end;
}
if (status & FDCSTAT_LOST) {
printk(KERN_ERR "fd%d: lost data (side %d, track %d)\n",
SelectedDrive, ReqSide, ReqTrack );
goto err_end;
}
wake_up( &format_wait );
return;
err_end:
fd_error();
}
static void fd_times_out( unsigned long dummy )
{
atari_disable_irq( IRQ_MFP_FDC );
if (!FloppyIRQHandler) goto end; /* int occurred after timer was fired, but
* before we came here... */
SET_IRQ_HANDLER( NULL );
/* If the timeout occurred while the readtrack_check timer was
* active, we need to cancel it, else bad things will happen */
if (UseTrackbuffer)
del_timer( &readtrack_timer );
FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
udelay( 25 );
printk(KERN_ERR "floppy timeout\n" );
fd_error();
end:
atari_enable_irq( IRQ_MFP_FDC );
}
/* The (noop) seek operation here is needed to make the WP bit in the
* FDC status register accessible for check_change. If the last disk
* operation would have been a RDSEC, this bit would always read as 0
* no matter what :-( To save time, the seek goes to the track we're
* already on.
*/
static void finish_fdc( void )
{
if (!NeedSeek) {
finish_fdc_done( 0 );
}
else {
DPRINT(("finish_fdc: dummy seek started\n"));
FDC_WRITE (FDCREG_DATA, SUD.track);
SET_IRQ_HANDLER( finish_fdc_done );
FDC_WRITE (FDCREG_CMD, FDCCMD_SEEK);
MotorOn = 1;
start_timeout();
/* we must wait for the IRQ here, because the ST-DMA
is released immediately afterwards and the interrupt
may be delivered to the wrong driver. */
}
}
static void finish_fdc_done( int dummy )
{
unsigned long flags;
DPRINT(("finish_fdc_done entered\n"));
stop_timeout();
NeedSeek = 0;
if (timer_pending(&fd_timer) && time_before(fd_timer.expires, jiffies + 5))
/* If the check for a disk change is done too early after this
* last seek command, the WP bit still reads wrong :-((
*/
mod_timer(&fd_timer, jiffies + 5);
else
start_check_change_timer();
start_motor_off_timer();
local_irq_save(flags);
stdma_release();
fdc_busy = 0;
wake_up( &fdc_wait );
local_irq_restore(flags);
DPRINT(("finish_fdc() finished\n"));
}
/* The detection of disk changes is a dark chapter in Atari history :-(
* Because the "Drive ready" signal isn't present in the Atari
* hardware, one has to rely on the "Write Protect". This works fine,
* as long as no write protected disks are used. TOS solves this
* problem by introducing tri-state logic ("maybe changed") and
* looking at the serial number in block 0. This isn't possible for
* Linux, since the floppy driver can't make assumptions about the
* filesystem used on the disk and thus the contents of block 0. I've
* chosen the method to always say "The disk was changed" if it is
* unsure whether it was. This implies that every open or mount
* invalidates the disk buffers if you work with write protected
* disks. But at least this is better than working with incorrect data
* due to unrecognised disk changes.
*/
static unsigned int floppy_check_events(struct gendisk *disk,
unsigned int clearing)
{
struct atari_floppy_struct *p = disk->private_data;
unsigned int drive = p - unit;
if (test_bit (drive, &fake_change)) {
/* simulated change (e.g. after formatting) */
return DISK_EVENT_MEDIA_CHANGE;
}
if (test_bit (drive, &changed_floppies)) {
/* surely changed (the WP signal changed at least once) */
return DISK_EVENT_MEDIA_CHANGE;
}
if (UD.wpstat) {
/* WP is on -> could be changed: to be sure, buffers should be
* invalidated...
*/
return DISK_EVENT_MEDIA_CHANGE;
}
return 0;
}
static int floppy_revalidate(struct gendisk *disk)
{
struct atari_floppy_struct *p = disk->private_data;
unsigned int drive = p - unit;
if (test_bit(drive, &changed_floppies) ||
test_bit(drive, &fake_change) ||
p->disktype == 0) {
if (UD.flags & FTD_MSG)
printk(KERN_ERR "floppy: clear format %p!\n", UDT);
BufferDrive = -1;
clear_bit(drive, &fake_change);
clear_bit(drive, &changed_floppies);
/* MSch: clearing geometry makes sense only for autoprobe
formats, for 'permanent user-defined' parameter:
restore default_params[] here if flagged valid! */
if (default_params[drive].blocks == 0)
UDT = NULL;
else
UDT = &default_params[drive];
}
return 0;
}
/* This sets up the global variables describing the current request. */
static void setup_req_params( int drive )
{
int block = ReqBlock + ReqCnt;
ReqTrack = block / UDT->spt;
ReqSector = block - ReqTrack * UDT->spt + 1;
ReqSide = ReqTrack & 1;
ReqTrack >>= 1;
ReqData = ReqBuffer + 512 * ReqCnt;
if (UseTrackbuffer)
read_track = (ReqCmd == READ && fd_request->errors == 0);
else
read_track = 0;
DPRINT(("Request params: Si=%d Tr=%d Se=%d Data=%08lx\n",ReqSide,
ReqTrack, ReqSector, (unsigned long)ReqData ));
}
/*
* Round-robin between our available drives, doing one request from each
*/
static struct request *set_next_request(void)
{
struct request_queue *q;
int old_pos = fdc_queue;
struct request *rq = NULL;
do {
q = unit[fdc_queue].disk->queue;
if (++fdc_queue == FD_MAX_UNITS)
fdc_queue = 0;
if (q) {
rq = blk_fetch_request(q);
if (rq)
break;
}
} while (fdc_queue != old_pos);
return rq;
}
static void redo_fd_request(void)
{
int drive, type;
struct atari_floppy_struct *floppy;
DPRINT(("redo_fd_request: fd_request=%p dev=%s fd_request->sector=%ld\n",
fd_request, fd_request ? fd_request->rq_disk->disk_name : "",
fd_request ? blk_rq_pos(fd_request) : 0 ));
IsFormatting = 0;
repeat:
if (!fd_request) {
fd_request = set_next_request();
if (!fd_request)
goto the_end;
}
floppy = fd_request->rq_disk->private_data;
drive = floppy - unit;
type = floppy->type;
if (!UD.connected) {
/* drive not connected */
printk(KERN_ERR "Unknown Device: fd%d\n", drive );
fd_end_request_cur(-EIO);
goto repeat;
}
if (type == 0) {
if (!UDT) {
Probing = 1;
UDT = atari_disk_type + StartDiskType[DriveType];
set_capacity(floppy->disk, UDT->blocks);
UD.autoprobe = 1;
}
}
else {
/* user supplied disk type */
if (--type >= NUM_DISK_MINORS) {
printk(KERN_WARNING "fd%d: invalid disk format", drive );
fd_end_request_cur(-EIO);
goto repeat;
}
if (minor2disktype[type].drive_types > DriveType) {
printk(KERN_WARNING "fd%d: unsupported disk format", drive );
fd_end_request_cur(-EIO);
goto repeat;
}
type = minor2disktype[type].index;
UDT = &atari_disk_type[type];
set_capacity(floppy->disk, UDT->blocks);
UD.autoprobe = 0;
}
if (blk_rq_pos(fd_request) + 1 > UDT->blocks) {
fd_end_request_cur(-EIO);
goto repeat;
}
/* stop deselect timer */
del_timer( &motor_off_timer );
ReqCnt = 0;
ReqCmd = rq_data_dir(fd_request);
ReqBlock = blk_rq_pos(fd_request);
ReqBuffer = fd_request->buffer;
setup_req_params( drive );
do_fd_action( drive );
return;
the_end:
finish_fdc();
}
void do_fd_request(struct request_queue * q)
{
DPRINT(("do_fd_request for pid %d\n",current->pid));
while( fdc_busy ) sleep_on( &fdc_wait );
fdc_busy = 1;
stdma_lock(floppy_irq, NULL);
atari_disable_irq( IRQ_MFP_FDC );
redo_fd_request();
atari_enable_irq( IRQ_MFP_FDC );
}
static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long param)
{
struct gendisk *disk = bdev->bd_disk;
struct atari_floppy_struct *floppy = disk->private_data;
int drive = floppy - unit;
int type = floppy->type;
struct atari_format_descr fmt_desc;
struct atari_disk_type *dtp;
struct floppy_struct getprm;
int settype;
struct floppy_struct setprm;
void __user *argp = (void __user *)param;
switch (cmd) {
case FDGETPRM:
if (type) {
if (--type >= NUM_DISK_MINORS)
return -ENODEV;
if (minor2disktype[type].drive_types > DriveType)
return -ENODEV;
type = minor2disktype[type].index;
dtp = &atari_disk_type[type];
if (UD.flags & FTD_MSG)
printk (KERN_ERR "floppy%d: found dtp %p name %s!\n",
drive, dtp, dtp->name);
}
else {
if (!UDT)
return -ENXIO;
else
dtp = UDT;
}
memset((void *)&getprm, 0, sizeof(getprm));
getprm.size = dtp->blocks;
getprm.sect = dtp->spt;
getprm.head = 2;
getprm.track = dtp->blocks/dtp->spt/2;
getprm.stretch = dtp->stretch;
if (copy_to_user(argp, &getprm, sizeof(getprm)))
return -EFAULT;
return 0;
}
switch (cmd) {
case FDSETPRM:
case FDDEFPRM:
/*
* MSch 7/96: simple 'set geometry' case: just set the
* 'default' device params (minor == 0).
* Currently, the drive geometry is cleared after each
* disk change and subsequent revalidate()! simple
* implementation of FDDEFPRM: save geometry from a
* FDDEFPRM call and restore it in floppy_revalidate() !
*/
/* get the parameters from user space */
if (floppy->ref != 1 && floppy->ref != -1)
return -EBUSY;
if (copy_from_user(&setprm, argp, sizeof(setprm)))
return -EFAULT;
/*
* first of all: check for floppy change and revalidate,
* or the next access will revalidate - and clear UDT :-(
*/
if (floppy_check_events(disk, 0))
floppy_revalidate(disk);
if (UD.flags & FTD_MSG)
printk (KERN_INFO "floppy%d: setting size %d spt %d str %d!\n",
drive, setprm.size, setprm.sect, setprm.stretch);
/* what if type > 0 here? Overwrite specified entry ? */
if (type) {
/* refuse to re-set a predefined type for now */
redo_fd_request();
return -EINVAL;
}
/*
* type == 0: first look for a matching entry in the type list,
* and set the UD.disktype field to use the perdefined entry.
* TODO: add user-defined format to head of autoprobe list ?
* Useful to include the user-type for future autodetection!
*/
for (settype = 0; settype < NUM_DISK_MINORS; settype++) {
int setidx = 0;
if (minor2disktype[settype].drive_types > DriveType) {
/* skip this one, invalid for drive ... */
continue;
}
setidx = minor2disktype[settype].index;
dtp = &atari_disk_type[setidx];
/* found matching entry ?? */
if ( dtp->blocks == setprm.size
&& dtp->spt == setprm.sect
&& dtp->stretch == setprm.stretch ) {
if (UD.flags & FTD_MSG)
printk (KERN_INFO "floppy%d: setting %s %p!\n",
drive, dtp->name, dtp);
UDT = dtp;
set_capacity(floppy->disk, UDT->blocks);
if (cmd == FDDEFPRM) {
/* save settings as permanent default type */
default_params[drive].name = dtp->name;
default_params[drive].spt = dtp->spt;
default_params[drive].blocks = dtp->blocks;
default_params[drive].fdc_speed = dtp->fdc_speed;
default_params[drive].stretch = dtp->stretch;
}
return 0;
}
}
/* no matching disk type found above - setting user_params */
if (cmd == FDDEFPRM) {
/* set permanent type */
dtp = &default_params[drive];
} else
/* set user type (reset by disk change!) */
dtp = &user_params[drive];
dtp->name = "user format";
dtp->blocks = setprm.size;
dtp->spt = setprm.sect;
if (setprm.sect > 14)
dtp->fdc_speed = 3;
else
dtp->fdc_speed = 0;
dtp->stretch = setprm.stretch;
if (UD.flags & FTD_MSG)
printk (KERN_INFO "floppy%d: blk %d spt %d str %d!\n",
drive, dtp->blocks, dtp->spt, dtp->stretch);
/* sanity check */
if (setprm.track != dtp->blocks/dtp->spt/2 ||
setprm.head != 2) {
redo_fd_request();
return -EINVAL;
}
UDT = dtp;
set_capacity(floppy->disk, UDT->blocks);
return 0;
case FDMSGON:
UD.flags |= FTD_MSG;
return 0;
case FDMSGOFF:
UD.flags &= ~FTD_MSG;
return 0;
case FDSETEMSGTRESH:
return -EINVAL;
case FDFMTBEG:
return 0;
case FDFMTTRK:
if (floppy->ref != 1 && floppy->ref != -1)
return -EBUSY;
if (copy_from_user(&fmt_desc, argp, sizeof(fmt_desc)))
return -EFAULT;
return do_format(drive, type, &fmt_desc);
case FDCLRPRM:
UDT = NULL;
/* MSch: invalidate default_params */
default_params[drive].blocks = 0;
set_capacity(floppy->disk, MAX_DISK_SIZE * 2);
case FDFMTEND:
case FDFLUSH:
/* invalidate the buffer track to force a reread */
BufferDrive = -1;
set_bit(drive, &fake_change);
check_disk_change(bdev);
return 0;
default:
return -EINVAL;
}
}
static int fd_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
int ret;
mutex_lock(&ataflop_mutex);
ret = fd_locked_ioctl(bdev, mode, cmd, arg);
mutex_unlock(&ataflop_mutex);
return ret;
}
/* Initialize the 'unit' variable for drive 'drive' */
static void __init fd_probe( int drive )
{
UD.connected = 0;
UDT = NULL;
if (!fd_test_drive_present( drive ))
return;
UD.connected = 1;
UD.track = 0;
switch( UserSteprate[drive] ) {
case 2:
UD.steprate = FDCSTEP_2;
break;
case 3:
UD.steprate = FDCSTEP_3;
break;
case 6:
UD.steprate = FDCSTEP_6;
break;
case 12:
UD.steprate = FDCSTEP_12;
break;
default: /* should be -1 for "not set by user" */
if (ATARIHW_PRESENT( FDCSPEED ) || MACH_IS_MEDUSA)
UD.steprate = FDCSTEP_3;
else
UD.steprate = FDCSTEP_6;
break;
}
MotorOn = 1; /* from probe restore operation! */
}
/* This function tests the physical presence of a floppy drive (not
* whether a disk is inserted). This is done by issuing a restore
* command, waiting max. 2 seconds (that should be enough to move the
* head across the whole disk) and looking at the state of the "TR00"
* signal. This should now be raised if there is a drive connected
* (and there is no hardware failure :-) Otherwise, the drive is
* declared absent.
*/
static int __init fd_test_drive_present( int drive )
{
unsigned long timeout;
unsigned char status;
int ok;
if (drive >= (MACH_IS_FALCON ? 1 : 2)) return( 0 );
fd_select_drive( drive );
/* disable interrupt temporarily */
atari_turnoff_irq( IRQ_MFP_FDC );
FDC_WRITE (FDCREG_TRACK, 0xff00);
FDC_WRITE( FDCREG_CMD, FDCCMD_RESTORE | FDCCMDADD_H | FDCSTEP_6 );
timeout = jiffies + 2*HZ+HZ/2;
while (time_before(jiffies, timeout))
if (!(st_mfp.par_dt_reg & 0x20))
break;
status = FDC_READ( FDCREG_STATUS );
ok = (status & FDCSTAT_TR00) != 0;
/* force interrupt to abort restore operation (FDC would try
* about 50 seconds!) */
FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
udelay(500);
status = FDC_READ( FDCREG_STATUS );
udelay(20);
if (ok) {
/* dummy seek command to make WP bit accessible */
FDC_WRITE( FDCREG_DATA, 0 );
FDC_WRITE( FDCREG_CMD, FDCCMD_SEEK );
while( st_mfp.par_dt_reg & 0x20 )
;
status = FDC_READ( FDCREG_STATUS );
}
atari_turnon_irq( IRQ_MFP_FDC );
return( ok );
}
/* Look how many and which kind of drives are connected. If there are
* floppies, additionally start the disk-change and motor-off timers.
*/
static void __init config_types( void )
{
int drive, cnt = 0;
/* for probing drives, set the FDC speed to 8 MHz */
if (ATARIHW_PRESENT(FDCSPEED))
dma_wd.fdc_speed = 0;
printk(KERN_INFO "Probing floppy drive(s):\n");
for( drive = 0; drive < FD_MAX_UNITS; drive++ ) {
fd_probe( drive );
if (UD.connected) {
printk(KERN_INFO "fd%d\n", drive);
++cnt;
}
}
if (FDC_READ( FDCREG_STATUS ) & FDCSTAT_BUSY) {
/* If FDC is still busy from probing, give it another FORCI
* command to abort the operation. If this isn't done, the FDC
* will interrupt later and its IRQ line stays low, because
* the status register isn't read. And this will block any
* interrupts on this IRQ line :-(
*/
FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
udelay(500);
FDC_READ( FDCREG_STATUS );
udelay(20);
}
if (cnt > 0) {
start_motor_off_timer();
if (cnt == 1) fd_select_drive( 0 );
start_check_change_timer();
}
}
/*
* floppy_open check for aliasing (/dev/fd0 can be the same as
* /dev/PS0 etc), and disallows simultaneous access to the same
* drive with different device numbers.
*/
static int floppy_open(struct block_device *bdev, fmode_t mode)
{
struct atari_floppy_struct *p = bdev->bd_disk->private_data;
int type = MINOR(bdev->bd_dev) >> 2;
DPRINT(("fd_open: type=%d\n",type));
if (p->ref && p->type != type)
return -EBUSY;
if (p->ref == -1 || (p->ref && mode & FMODE_EXCL))
return -EBUSY;
if (mode & FMODE_EXCL)
p->ref = -1;
else
p->ref++;
p->type = type;
if (mode & FMODE_NDELAY)
return 0;
if (mode & (FMODE_READ|FMODE_WRITE)) {
check_disk_change(bdev);
if (mode & FMODE_WRITE) {
if (p->wpstat) {
if (p->ref < 0)
p->ref = 0;
else
p->ref--;
return -EROFS;
}
}
}
return 0;
}
static int floppy_unlocked_open(struct block_device *bdev, fmode_t mode)
{
int ret;
mutex_lock(&ataflop_mutex);
ret = floppy_open(bdev, mode);
mutex_unlock(&ataflop_mutex);
return ret;
}
static int floppy_release(struct gendisk *disk, fmode_t mode)
{
struct atari_floppy_struct *p = disk->private_data;
mutex_lock(&ataflop_mutex);
if (p->ref < 0)
p->ref = 0;
else if (!p->ref--) {
printk(KERN_ERR "floppy_release with fd_ref == 0");
p->ref = 0;
}
mutex_unlock(&ataflop_mutex);
return 0;
}
static const struct block_device_operations floppy_fops = {
.owner = THIS_MODULE,
.open = floppy_unlocked_open,
.release = floppy_release,
.ioctl = fd_ioctl,
.check_events = floppy_check_events,
.revalidate_disk= floppy_revalidate,
};
static struct kobject *floppy_find(dev_t dev, int *part, void *data)
{
int drive = *part & 3;
int type = *part >> 2;
if (drive >= FD_MAX_UNITS || type > NUM_DISK_MINORS)
return NULL;
*part = 0;
return get_disk(unit[drive].disk);
}
static int __init atari_floppy_init (void)
{
int i;
if (!MACH_IS_ATARI)
/* Amiga, Mac, ... don't have Atari-compatible floppy :-) */
return -ENODEV;
if (register_blkdev(FLOPPY_MAJOR,"fd"))
return -EBUSY;
for (i = 0; i < FD_MAX_UNITS; i++) {
unit[i].disk = alloc_disk(1);
if (!unit[i].disk)
goto Enomem;
}
if (UseTrackbuffer < 0)
/* not set by user -> use default: for now, we turn
track buffering off for all Medusas, though it
could be used with ones that have a counter
card. But the test is too hard :-( */
UseTrackbuffer = !MACH_IS_MEDUSA;
/* initialize variables */
SelectedDrive = -1;
BufferDrive = -1;
DMABuffer = atari_stram_alloc(BUFFER_SIZE+512, "ataflop");
if (!DMABuffer) {
printk(KERN_ERR "atari_floppy_init: cannot get dma buffer\n");
goto Enomem;
}
TrackBuffer = DMABuffer + 512;
PhysDMABuffer = virt_to_phys(DMABuffer);
PhysTrackBuffer = virt_to_phys(TrackBuffer);
BufferDrive = BufferSide = BufferTrack = -1;
for (i = 0; i < FD_MAX_UNITS; i++) {
unit[i].track = -1;
unit[i].flags = 0;
unit[i].disk->major = FLOPPY_MAJOR;
unit[i].disk->first_minor = i;
sprintf(unit[i].disk->disk_name, "fd%d", i);
unit[i].disk->fops = &floppy_fops;
unit[i].disk->private_data = &unit[i];
unit[i].disk->queue = blk_init_queue(do_fd_request,
&ataflop_lock);
if (!unit[i].disk->queue)
goto Enomem;
set_capacity(unit[i].disk, MAX_DISK_SIZE * 2);
add_disk(unit[i].disk);
}
blk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE,
floppy_find, NULL, NULL);
printk(KERN_INFO "Atari floppy driver: max. %cD, %strack buffering\n",
DriveType == 0 ? 'D' : DriveType == 1 ? 'H' : 'E',
UseTrackbuffer ? "" : "no ");
config_types();
return 0;
Enomem:
while (i--) {
struct request_queue *q = unit[i].disk->queue;
put_disk(unit[i].disk);
if (q)
blk_cleanup_queue(q);
}
unregister_blkdev(FLOPPY_MAJOR, "fd");
return -ENOMEM;
}
#ifndef MODULE
static int __init atari_floppy_setup(char *str)
{
int ints[3 + FD_MAX_UNITS];
int i;
if (!MACH_IS_ATARI)
return 0;
str = get_options(str, 3 + FD_MAX_UNITS, ints);
if (ints[0] < 1) {
printk(KERN_ERR "ataflop_setup: no arguments!\n" );
return 0;
}
else if (ints[0] > 2+FD_MAX_UNITS) {
printk(KERN_ERR "ataflop_setup: too many arguments\n" );
}
if (ints[1] < 0 || ints[1] > 2)
printk(KERN_ERR "ataflop_setup: bad drive type\n" );
else
DriveType = ints[1];
if (ints[0] >= 2)
UseTrackbuffer = (ints[2] > 0);
for( i = 3; i <= ints[0] && i-3 < FD_MAX_UNITS; ++i ) {
if (ints[i] != 2 && ints[i] != 3 && ints[i] != 6 && ints[i] != 12)
printk(KERN_ERR "ataflop_setup: bad steprate\n" );
else
UserSteprate[i-3] = ints[i];
}
return 1;
}
__setup("floppy=", atari_floppy_setup);
#endif
static void __exit atari_floppy_exit(void)
{
int i;
blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);
for (i = 0; i < FD_MAX_UNITS; i++) {
struct request_queue *q = unit[i].disk->queue;
del_gendisk(unit[i].disk);
put_disk(unit[i].disk);
blk_cleanup_queue(q);
}
unregister_blkdev(FLOPPY_MAJOR, "fd");
del_timer_sync(&fd_timer);
atari_stram_free( DMABuffer );
}
module_init(atari_floppy_init)
module_exit(atari_floppy_exit)
MODULE_LICENSE("GPL");
| gpl-2.0 |
TheFlyhalf205/android_kernel_htc_msm8960 | fs/minix/itree_v2.c | 9091 | 1925 | #include <linux/buffer_head.h>
#include "minix.h"
enum {DIRECT = 7, DEPTH = 4}; /* Have triple indirect */
typedef u32 block_t; /* 32 bit, host order */
static inline unsigned long block_to_cpu(block_t n)
{
return n;
}
static inline block_t cpu_to_block(unsigned long n)
{
return n;
}
static inline block_t *i_data(struct inode *inode)
{
return (block_t *)minix_i(inode)->u.i2_data;
}
#define DIRCOUNT 7
#define INDIRCOUNT(sb) (1 << ((sb)->s_blocksize_bits - 2))
static int block_to_path(struct inode * inode, long block, int offsets[DEPTH])
{
int n = 0;
char b[BDEVNAME_SIZE];
struct super_block *sb = inode->i_sb;
if (block < 0) {
printk("MINIX-fs: block_to_path: block %ld < 0 on dev %s\n",
block, bdevname(sb->s_bdev, b));
} else if (block >= (minix_sb(inode->i_sb)->s_max_size/sb->s_blocksize)) {
if (printk_ratelimit())
printk("MINIX-fs: block_to_path: "
"block %ld too big on dev %s\n",
block, bdevname(sb->s_bdev, b));
} else if (block < DIRCOUNT) {
offsets[n++] = block;
} else if ((block -= DIRCOUNT) < INDIRCOUNT(sb)) {
offsets[n++] = DIRCOUNT;
offsets[n++] = block;
} else if ((block -= INDIRCOUNT(sb)) < INDIRCOUNT(sb) * INDIRCOUNT(sb)) {
offsets[n++] = DIRCOUNT + 1;
offsets[n++] = block / INDIRCOUNT(sb);
offsets[n++] = block % INDIRCOUNT(sb);
} else {
block -= INDIRCOUNT(sb) * INDIRCOUNT(sb);
offsets[n++] = DIRCOUNT + 2;
offsets[n++] = (block / INDIRCOUNT(sb)) / INDIRCOUNT(sb);
offsets[n++] = (block / INDIRCOUNT(sb)) % INDIRCOUNT(sb);
offsets[n++] = block % INDIRCOUNT(sb);
}
return n;
}
#include "itree_common.c"
int V2_minix_get_block(struct inode * inode, long block,
struct buffer_head *bh_result, int create)
{
return get_block(inode, block, bh_result, create);
}
void V2_minix_truncate(struct inode * inode)
{
truncate(inode);
}
unsigned V2_minix_blocks(loff_t size, struct super_block *sb)
{
return nblocks(size, sb);
}
| gpl-2.0 |
tom--pollard/linux-raspberrypi_4.1 | arch/arm/boot/compressed/string.c | 10115 | 1885 | /*
* arch/arm/boot/compressed/string.c
*
* Small subset of simple string routines
*/
#include <linux/string.h>
void *memcpy(void *__dest, __const void *__src, size_t __n)
{
int i = 0;
unsigned char *d = (unsigned char *)__dest, *s = (unsigned char *)__src;
for (i = __n >> 3; i > 0; i--) {
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
}
if (__n & 1 << 2) {
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
}
if (__n & 1 << 1) {
*d++ = *s++;
*d++ = *s++;
}
if (__n & 1)
*d++ = *s++;
return __dest;
}
void *memmove(void *__dest, __const void *__src, size_t count)
{
unsigned char *d = __dest;
const unsigned char *s = __src;
if (__dest == __src)
return __dest;
if (__dest < __src)
return memcpy(__dest, __src, count);
while (count--)
d[count] = s[count];
return __dest;
}
size_t strlen(const char *s)
{
const char *sc = s;
while (*sc != '\0')
sc++;
return sc - s;
}
int memcmp(const void *cs, const void *ct, size_t count)
{
const unsigned char *su1 = cs, *su2 = ct, *end = su1 + count;
int res = 0;
while (su1 < end) {
res = *su1++ - *su2++;
if (res)
break;
}
return res;
}
int strcmp(const char *cs, const char *ct)
{
unsigned char c1, c2;
int res = 0;
do {
c1 = *cs++;
c2 = *ct++;
res = c1 - c2;
if (res)
break;
} while (c1);
return res;
}
void *memchr(const void *s, int c, size_t count)
{
const unsigned char *p = s;
while (count--)
if ((unsigned char)c == *p++)
return (void *)(p - 1);
return NULL;
}
char *strchr(const char *s, int c)
{
while (*s != (char)c)
if (*s++ == '\0')
return NULL;
return (char *)s;
}
#undef memset
void *memset(void *s, int c, size_t count)
{
char *xs = s;
while (count--)
*xs++ = c;
return s;
}
void __memzero(void *s, size_t count)
{
memset(s, 0, count);
}
| gpl-2.0 |
xjljian/android_kernel_huawei_msm8916 | arch/arm/boot/compressed/string.c | 10115 | 1885 | /*
* arch/arm/boot/compressed/string.c
*
* Small subset of simple string routines
*/
#include <linux/string.h>
void *memcpy(void *__dest, __const void *__src, size_t __n)
{
int i = 0;
unsigned char *d = (unsigned char *)__dest, *s = (unsigned char *)__src;
for (i = __n >> 3; i > 0; i--) {
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
}
if (__n & 1 << 2) {
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
}
if (__n & 1 << 1) {
*d++ = *s++;
*d++ = *s++;
}
if (__n & 1)
*d++ = *s++;
return __dest;
}
void *memmove(void *__dest, __const void *__src, size_t count)
{
unsigned char *d = __dest;
const unsigned char *s = __src;
if (__dest == __src)
return __dest;
if (__dest < __src)
return memcpy(__dest, __src, count);
while (count--)
d[count] = s[count];
return __dest;
}
size_t strlen(const char *s)
{
const char *sc = s;
while (*sc != '\0')
sc++;
return sc - s;
}
int memcmp(const void *cs, const void *ct, size_t count)
{
const unsigned char *su1 = cs, *su2 = ct, *end = su1 + count;
int res = 0;
while (su1 < end) {
res = *su1++ - *su2++;
if (res)
break;
}
return res;
}
int strcmp(const char *cs, const char *ct)
{
unsigned char c1, c2;
int res = 0;
do {
c1 = *cs++;
c2 = *ct++;
res = c1 - c2;
if (res)
break;
} while (c1);
return res;
}
void *memchr(const void *s, int c, size_t count)
{
const unsigned char *p = s;
while (count--)
if ((unsigned char)c == *p++)
return (void *)(p - 1);
return NULL;
}
char *strchr(const char *s, int c)
{
while (*s != (char)c)
if (*s++ == '\0')
return NULL;
return (char *)s;
}
#undef memset
void *memset(void *s, int c, size_t count)
{
char *xs = s;
while (count--)
*xs++ = c;
return s;
}
void __memzero(void *s, size_t count)
{
memset(s, 0, count);
}
| gpl-2.0 |
AKKP/lge-kernel-star | drivers/target/target_core_transport.c | 132 | 172769 | /*******************************************************************************
* Filename: target_core_transport.c
*
* This file contains the Generic Target Engine Core.
*
* Copyright (c) 2002, 2003, 2004, 2005 PyX Technologies, Inc.
* Copyright (c) 2005, 2006, 2007 SBE, Inc.
* Copyright (c) 2007-2010 Rising Tide Systems
* Copyright (c) 2008-2010 Linux-iSCSI.org
*
* Nicholas A. Bellinger <nab@kernel.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
******************************************************************************/
#include <linux/version.h>
#include <linux/net.h>
#include <linux/delay.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/slab.h>
#include <linux/blkdev.h>
#include <linux/spinlock.h>
#include <linux/kthread.h>
#include <linux/in.h>
#include <linux/cdrom.h>
#include <asm/unaligned.h>
#include <net/sock.h>
#include <net/tcp.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/libsas.h> /* For TASK_ATTR_* */
#include <target/target_core_base.h>
#include <target/target_core_device.h>
#include <target/target_core_tmr.h>
#include <target/target_core_tpg.h>
#include <target/target_core_transport.h>
#include <target/target_core_fabric_ops.h>
#include <target/target_core_configfs.h>
#include "target_core_alua.h"
#include "target_core_hba.h"
#include "target_core_pr.h"
#include "target_core_scdb.h"
#include "target_core_ua.h"
/* #define DEBUG_CDB_HANDLER */
#ifdef DEBUG_CDB_HANDLER
#define DEBUG_CDB_H(x...) printk(KERN_INFO x)
#else
#define DEBUG_CDB_H(x...)
#endif
/* #define DEBUG_CMD_MAP */
#ifdef DEBUG_CMD_MAP
#define DEBUG_CMD_M(x...) printk(KERN_INFO x)
#else
#define DEBUG_CMD_M(x...)
#endif
/* #define DEBUG_MEM_ALLOC */
#ifdef DEBUG_MEM_ALLOC
#define DEBUG_MEM(x...) printk(KERN_INFO x)
#else
#define DEBUG_MEM(x...)
#endif
/* #define DEBUG_MEM2_ALLOC */
#ifdef DEBUG_MEM2_ALLOC
#define DEBUG_MEM2(x...) printk(KERN_INFO x)
#else
#define DEBUG_MEM2(x...)
#endif
/* #define DEBUG_SG_CALC */
#ifdef DEBUG_SG_CALC
#define DEBUG_SC(x...) printk(KERN_INFO x)
#else
#define DEBUG_SC(x...)
#endif
/* #define DEBUG_SE_OBJ */
#ifdef DEBUG_SE_OBJ
#define DEBUG_SO(x...) printk(KERN_INFO x)
#else
#define DEBUG_SO(x...)
#endif
/* #define DEBUG_CMD_VOL */
#ifdef DEBUG_CMD_VOL
#define DEBUG_VOL(x...) printk(KERN_INFO x)
#else
#define DEBUG_VOL(x...)
#endif
/* #define DEBUG_CMD_STOP */
#ifdef DEBUG_CMD_STOP
#define DEBUG_CS(x...) printk(KERN_INFO x)
#else
#define DEBUG_CS(x...)
#endif
/* #define DEBUG_PASSTHROUGH */
#ifdef DEBUG_PASSTHROUGH
#define DEBUG_PT(x...) printk(KERN_INFO x)
#else
#define DEBUG_PT(x...)
#endif
/* #define DEBUG_TASK_STOP */
#ifdef DEBUG_TASK_STOP
#define DEBUG_TS(x...) printk(KERN_INFO x)
#else
#define DEBUG_TS(x...)
#endif
/* #define DEBUG_TRANSPORT_STOP */
#ifdef DEBUG_TRANSPORT_STOP
#define DEBUG_TRANSPORT_S(x...) printk(KERN_INFO x)
#else
#define DEBUG_TRANSPORT_S(x...)
#endif
/* #define DEBUG_TASK_FAILURE */
#ifdef DEBUG_TASK_FAILURE
#define DEBUG_TF(x...) printk(KERN_INFO x)
#else
#define DEBUG_TF(x...)
#endif
/* #define DEBUG_DEV_OFFLINE */
#ifdef DEBUG_DEV_OFFLINE
#define DEBUG_DO(x...) printk(KERN_INFO x)
#else
#define DEBUG_DO(x...)
#endif
/* #define DEBUG_TASK_STATE */
#ifdef DEBUG_TASK_STATE
#define DEBUG_TSTATE(x...) printk(KERN_INFO x)
#else
#define DEBUG_TSTATE(x...)
#endif
/* #define DEBUG_STATUS_THR */
#ifdef DEBUG_STATUS_THR
#define DEBUG_ST(x...) printk(KERN_INFO x)
#else
#define DEBUG_ST(x...)
#endif
/* #define DEBUG_TASK_TIMEOUT */
#ifdef DEBUG_TASK_TIMEOUT
#define DEBUG_TT(x...) printk(KERN_INFO x)
#else
#define DEBUG_TT(x...)
#endif
/* #define DEBUG_GENERIC_REQUEST_FAILURE */
#ifdef DEBUG_GENERIC_REQUEST_FAILURE
#define DEBUG_GRF(x...) printk(KERN_INFO x)
#else
#define DEBUG_GRF(x...)
#endif
/* #define DEBUG_SAM_TASK_ATTRS */
#ifdef DEBUG_SAM_TASK_ATTRS
#define DEBUG_STA(x...) printk(KERN_INFO x)
#else
#define DEBUG_STA(x...)
#endif
struct se_global *se_global;
static struct kmem_cache *se_cmd_cache;
static struct kmem_cache *se_sess_cache;
struct kmem_cache *se_tmr_req_cache;
struct kmem_cache *se_ua_cache;
struct kmem_cache *se_mem_cache;
struct kmem_cache *t10_pr_reg_cache;
struct kmem_cache *t10_alua_lu_gp_cache;
struct kmem_cache *t10_alua_lu_gp_mem_cache;
struct kmem_cache *t10_alua_tg_pt_gp_cache;
struct kmem_cache *t10_alua_tg_pt_gp_mem_cache;
/* Used for transport_dev_get_map_*() */
typedef int (*map_func_t)(struct se_task *, u32);
static int transport_generic_write_pending(struct se_cmd *);
static int transport_processing_thread(void *);
static int __transport_execute_tasks(struct se_device *dev);
static void transport_complete_task_attr(struct se_cmd *cmd);
static void transport_direct_request_timeout(struct se_cmd *cmd);
static void transport_free_dev_tasks(struct se_cmd *cmd);
static u32 transport_generic_get_cdb_count(struct se_cmd *cmd,
unsigned long long starting_lba, u32 sectors,
enum dma_data_direction data_direction,
struct list_head *mem_list, int set_counts);
static int transport_generic_get_mem(struct se_cmd *cmd, u32 length,
u32 dma_size);
static int transport_generic_remove(struct se_cmd *cmd,
int release_to_pool, int session_reinstatement);
static int transport_get_sectors(struct se_cmd *cmd);
static struct list_head *transport_init_se_mem_list(void);
static int transport_map_sg_to_mem(struct se_cmd *cmd,
struct list_head *se_mem_list, void *in_mem,
u32 *se_mem_cnt);
static void transport_memcpy_se_mem_read_contig(struct se_cmd *cmd,
unsigned char *dst, struct list_head *se_mem_list);
static void transport_release_fe_cmd(struct se_cmd *cmd);
static void transport_remove_cmd_from_queue(struct se_cmd *cmd,
struct se_queue_obj *qobj);
static int transport_set_sense_codes(struct se_cmd *cmd, u8 asc, u8 ascq);
static void transport_stop_all_task_timers(struct se_cmd *cmd);
int init_se_global(void)
{
struct se_global *global;
global = kzalloc(sizeof(struct se_global), GFP_KERNEL);
if (!(global)) {
printk(KERN_ERR "Unable to allocate memory for struct se_global\n");
return -1;
}
INIT_LIST_HEAD(&global->g_lu_gps_list);
INIT_LIST_HEAD(&global->g_se_tpg_list);
INIT_LIST_HEAD(&global->g_hba_list);
INIT_LIST_HEAD(&global->g_se_dev_list);
spin_lock_init(&global->g_device_lock);
spin_lock_init(&global->hba_lock);
spin_lock_init(&global->se_tpg_lock);
spin_lock_init(&global->lu_gps_lock);
spin_lock_init(&global->plugin_class_lock);
se_cmd_cache = kmem_cache_create("se_cmd_cache",
sizeof(struct se_cmd), __alignof__(struct se_cmd), 0, NULL);
if (!(se_cmd_cache)) {
printk(KERN_ERR "kmem_cache_create for struct se_cmd failed\n");
goto out;
}
se_tmr_req_cache = kmem_cache_create("se_tmr_cache",
sizeof(struct se_tmr_req), __alignof__(struct se_tmr_req),
0, NULL);
if (!(se_tmr_req_cache)) {
printk(KERN_ERR "kmem_cache_create() for struct se_tmr_req"
" failed\n");
goto out;
}
se_sess_cache = kmem_cache_create("se_sess_cache",
sizeof(struct se_session), __alignof__(struct se_session),
0, NULL);
if (!(se_sess_cache)) {
printk(KERN_ERR "kmem_cache_create() for struct se_session"
" failed\n");
goto out;
}
se_ua_cache = kmem_cache_create("se_ua_cache",
sizeof(struct se_ua), __alignof__(struct se_ua),
0, NULL);
if (!(se_ua_cache)) {
printk(KERN_ERR "kmem_cache_create() for struct se_ua failed\n");
goto out;
}
se_mem_cache = kmem_cache_create("se_mem_cache",
sizeof(struct se_mem), __alignof__(struct se_mem), 0, NULL);
if (!(se_mem_cache)) {
printk(KERN_ERR "kmem_cache_create() for struct se_mem failed\n");
goto out;
}
t10_pr_reg_cache = kmem_cache_create("t10_pr_reg_cache",
sizeof(struct t10_pr_registration),
__alignof__(struct t10_pr_registration), 0, NULL);
if (!(t10_pr_reg_cache)) {
printk(KERN_ERR "kmem_cache_create() for struct t10_pr_registration"
" failed\n");
goto out;
}
t10_alua_lu_gp_cache = kmem_cache_create("t10_alua_lu_gp_cache",
sizeof(struct t10_alua_lu_gp), __alignof__(struct t10_alua_lu_gp),
0, NULL);
if (!(t10_alua_lu_gp_cache)) {
printk(KERN_ERR "kmem_cache_create() for t10_alua_lu_gp_cache"
" failed\n");
goto out;
}
t10_alua_lu_gp_mem_cache = kmem_cache_create("t10_alua_lu_gp_mem_cache",
sizeof(struct t10_alua_lu_gp_member),
__alignof__(struct t10_alua_lu_gp_member), 0, NULL);
if (!(t10_alua_lu_gp_mem_cache)) {
printk(KERN_ERR "kmem_cache_create() for t10_alua_lu_gp_mem_"
"cache failed\n");
goto out;
}
t10_alua_tg_pt_gp_cache = kmem_cache_create("t10_alua_tg_pt_gp_cache",
sizeof(struct t10_alua_tg_pt_gp),
__alignof__(struct t10_alua_tg_pt_gp), 0, NULL);
if (!(t10_alua_tg_pt_gp_cache)) {
printk(KERN_ERR "kmem_cache_create() for t10_alua_tg_pt_gp_"
"cache failed\n");
goto out;
}
t10_alua_tg_pt_gp_mem_cache = kmem_cache_create(
"t10_alua_tg_pt_gp_mem_cache",
sizeof(struct t10_alua_tg_pt_gp_member),
__alignof__(struct t10_alua_tg_pt_gp_member),
0, NULL);
if (!(t10_alua_tg_pt_gp_mem_cache)) {
printk(KERN_ERR "kmem_cache_create() for t10_alua_tg_pt_gp_"
"mem_t failed\n");
goto out;
}
se_global = global;
return 0;
out:
if (se_cmd_cache)
kmem_cache_destroy(se_cmd_cache);
if (se_tmr_req_cache)
kmem_cache_destroy(se_tmr_req_cache);
if (se_sess_cache)
kmem_cache_destroy(se_sess_cache);
if (se_ua_cache)
kmem_cache_destroy(se_ua_cache);
if (se_mem_cache)
kmem_cache_destroy(se_mem_cache);
if (t10_pr_reg_cache)
kmem_cache_destroy(t10_pr_reg_cache);
if (t10_alua_lu_gp_cache)
kmem_cache_destroy(t10_alua_lu_gp_cache);
if (t10_alua_lu_gp_mem_cache)
kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
if (t10_alua_tg_pt_gp_cache)
kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
if (t10_alua_tg_pt_gp_mem_cache)
kmem_cache_destroy(t10_alua_tg_pt_gp_mem_cache);
kfree(global);
return -1;
}
void release_se_global(void)
{
struct se_global *global;
global = se_global;
if (!(global))
return;
kmem_cache_destroy(se_cmd_cache);
kmem_cache_destroy(se_tmr_req_cache);
kmem_cache_destroy(se_sess_cache);
kmem_cache_destroy(se_ua_cache);
kmem_cache_destroy(se_mem_cache);
kmem_cache_destroy(t10_pr_reg_cache);
kmem_cache_destroy(t10_alua_lu_gp_cache);
kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
kmem_cache_destroy(t10_alua_tg_pt_gp_mem_cache);
kfree(global);
se_global = NULL;
}
/* SCSI statistics table index */
static struct scsi_index_table scsi_index_table;
/*
* Initialize the index table for allocating unique row indexes to various mib
* tables.
*/
void init_scsi_index_table(void)
{
memset(&scsi_index_table, 0, sizeof(struct scsi_index_table));
spin_lock_init(&scsi_index_table.lock);
}
/*
* Allocate a new row index for the entry type specified
*/
u32 scsi_get_new_index(scsi_index_t type)
{
u32 new_index;
if ((type < 0) || (type >= SCSI_INDEX_TYPE_MAX)) {
printk(KERN_ERR "Invalid index type %d\n", type);
return -EINVAL;
}
spin_lock(&scsi_index_table.lock);
new_index = ++scsi_index_table.scsi_mib_index[type];
if (new_index == 0)
new_index = ++scsi_index_table.scsi_mib_index[type];
spin_unlock(&scsi_index_table.lock);
return new_index;
}
void transport_init_queue_obj(struct se_queue_obj *qobj)
{
atomic_set(&qobj->queue_cnt, 0);
INIT_LIST_HEAD(&qobj->qobj_list);
init_waitqueue_head(&qobj->thread_wq);
spin_lock_init(&qobj->cmd_queue_lock);
}
EXPORT_SYMBOL(transport_init_queue_obj);
static int transport_subsystem_reqmods(void)
{
int ret;
ret = request_module("target_core_iblock");
if (ret != 0)
printk(KERN_ERR "Unable to load target_core_iblock\n");
ret = request_module("target_core_file");
if (ret != 0)
printk(KERN_ERR "Unable to load target_core_file\n");
ret = request_module("target_core_pscsi");
if (ret != 0)
printk(KERN_ERR "Unable to load target_core_pscsi\n");
ret = request_module("target_core_stgt");
if (ret != 0)
printk(KERN_ERR "Unable to load target_core_stgt\n");
return 0;
}
int transport_subsystem_check_init(void)
{
if (se_global->g_sub_api_initialized)
return 0;
/*
* Request the loading of known TCM subsystem plugins..
*/
if (transport_subsystem_reqmods() < 0)
return -1;
se_global->g_sub_api_initialized = 1;
return 0;
}
struct se_session *transport_init_session(void)
{
struct se_session *se_sess;
se_sess = kmem_cache_zalloc(se_sess_cache, GFP_KERNEL);
if (!(se_sess)) {
printk(KERN_ERR "Unable to allocate struct se_session from"
" se_sess_cache\n");
return ERR_PTR(-ENOMEM);
}
INIT_LIST_HEAD(&se_sess->sess_list);
INIT_LIST_HEAD(&se_sess->sess_acl_list);
return se_sess;
}
EXPORT_SYMBOL(transport_init_session);
/*
* Called with spin_lock_bh(&struct se_portal_group->session_lock called.
*/
void __transport_register_session(
struct se_portal_group *se_tpg,
struct se_node_acl *se_nacl,
struct se_session *se_sess,
void *fabric_sess_ptr)
{
unsigned char buf[PR_REG_ISID_LEN];
se_sess->se_tpg = se_tpg;
se_sess->fabric_sess_ptr = fabric_sess_ptr;
/*
* Used by struct se_node_acl's under ConfigFS to locate active se_session-t
*
* Only set for struct se_session's that will actually be moving I/O.
* eg: *NOT* discovery sessions.
*/
if (se_nacl) {
/*
* If the fabric module supports an ISID based TransportID,
* save this value in binary from the fabric I_T Nexus now.
*/
if (TPG_TFO(se_tpg)->sess_get_initiator_sid != NULL) {
memset(&buf[0], 0, PR_REG_ISID_LEN);
TPG_TFO(se_tpg)->sess_get_initiator_sid(se_sess,
&buf[0], PR_REG_ISID_LEN);
se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]);
}
spin_lock_irq(&se_nacl->nacl_sess_lock);
/*
* The se_nacl->nacl_sess pointer will be set to the
* last active I_T Nexus for each struct se_node_acl.
*/
se_nacl->nacl_sess = se_sess;
list_add_tail(&se_sess->sess_acl_list,
&se_nacl->acl_sess_list);
spin_unlock_irq(&se_nacl->nacl_sess_lock);
}
list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list);
printk(KERN_INFO "TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n",
TPG_TFO(se_tpg)->get_fabric_name(), se_sess->fabric_sess_ptr);
}
EXPORT_SYMBOL(__transport_register_session);
void transport_register_session(
struct se_portal_group *se_tpg,
struct se_node_acl *se_nacl,
struct se_session *se_sess,
void *fabric_sess_ptr)
{
spin_lock_bh(&se_tpg->session_lock);
__transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr);
spin_unlock_bh(&se_tpg->session_lock);
}
EXPORT_SYMBOL(transport_register_session);
void transport_deregister_session_configfs(struct se_session *se_sess)
{
struct se_node_acl *se_nacl;
/*
* Used by struct se_node_acl's under ConfigFS to locate active struct se_session
*/
se_nacl = se_sess->se_node_acl;
if ((se_nacl)) {
spin_lock_irq(&se_nacl->nacl_sess_lock);
list_del(&se_sess->sess_acl_list);
/*
* If the session list is empty, then clear the pointer.
* Otherwise, set the struct se_session pointer from the tail
* element of the per struct se_node_acl active session list.
*/
if (list_empty(&se_nacl->acl_sess_list))
se_nacl->nacl_sess = NULL;
else {
se_nacl->nacl_sess = container_of(
se_nacl->acl_sess_list.prev,
struct se_session, sess_acl_list);
}
spin_unlock_irq(&se_nacl->nacl_sess_lock);
}
}
EXPORT_SYMBOL(transport_deregister_session_configfs);
void transport_free_session(struct se_session *se_sess)
{
kmem_cache_free(se_sess_cache, se_sess);
}
EXPORT_SYMBOL(transport_free_session);
void transport_deregister_session(struct se_session *se_sess)
{
struct se_portal_group *se_tpg = se_sess->se_tpg;
struct se_node_acl *se_nacl;
if (!(se_tpg)) {
transport_free_session(se_sess);
return;
}
spin_lock_bh(&se_tpg->session_lock);
list_del(&se_sess->sess_list);
se_sess->se_tpg = NULL;
se_sess->fabric_sess_ptr = NULL;
spin_unlock_bh(&se_tpg->session_lock);
/*
* Determine if we need to do extra work for this initiator node's
* struct se_node_acl if it had been previously dynamically generated.
*/
se_nacl = se_sess->se_node_acl;
if ((se_nacl)) {
spin_lock_bh(&se_tpg->acl_node_lock);
if (se_nacl->dynamic_node_acl) {
if (!(TPG_TFO(se_tpg)->tpg_check_demo_mode_cache(
se_tpg))) {
list_del(&se_nacl->acl_list);
se_tpg->num_node_acls--;
spin_unlock_bh(&se_tpg->acl_node_lock);
core_tpg_wait_for_nacl_pr_ref(se_nacl);
core_free_device_list_for_node(se_nacl, se_tpg);
TPG_TFO(se_tpg)->tpg_release_fabric_acl(se_tpg,
se_nacl);
spin_lock_bh(&se_tpg->acl_node_lock);
}
}
spin_unlock_bh(&se_tpg->acl_node_lock);
}
transport_free_session(se_sess);
printk(KERN_INFO "TARGET_CORE[%s]: Deregistered fabric_sess\n",
TPG_TFO(se_tpg)->get_fabric_name());
}
EXPORT_SYMBOL(transport_deregister_session);
/*
* Called with T_TASK(cmd)->t_state_lock held.
*/
static void transport_all_task_dev_remove_state(struct se_cmd *cmd)
{
struct se_device *dev;
struct se_task *task;
unsigned long flags;
if (!T_TASK(cmd))
return;
list_for_each_entry(task, &T_TASK(cmd)->t_task_list, t_list) {
dev = task->se_dev;
if (!(dev))
continue;
if (atomic_read(&task->task_active))
continue;
if (!(atomic_read(&task->task_state_active)))
continue;
spin_lock_irqsave(&dev->execute_task_lock, flags);
list_del(&task->t_state_list);
DEBUG_TSTATE("Removed ITT: 0x%08x dev: %p task[%p]\n",
CMD_TFO(cmd)->tfo_get_task_tag(cmd), dev, task);
spin_unlock_irqrestore(&dev->execute_task_lock, flags);
atomic_set(&task->task_state_active, 0);
atomic_dec(&T_TASK(cmd)->t_task_cdbs_ex_left);
}
}
/* transport_cmd_check_stop():
*
* 'transport_off = 1' determines if t_transport_active should be cleared.
* 'transport_off = 2' determines if task_dev_state should be removed.
*
* A non-zero u8 t_state sets cmd->t_state.
* Returns 1 when command is stopped, else 0.
*/
static int transport_cmd_check_stop(
struct se_cmd *cmd,
int transport_off,
u8 t_state)
{
unsigned long flags;
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
/*
* Determine if IOCTL context caller in requesting the stopping of this
* command for LUN shutdown purposes.
*/
if (atomic_read(&T_TASK(cmd)->transport_lun_stop)) {
DEBUG_CS("%s:%d atomic_read(&T_TASK(cmd)->transport_lun_stop)"
" == TRUE for ITT: 0x%08x\n", __func__, __LINE__,
CMD_TFO(cmd)->get_task_tag(cmd));
cmd->deferred_t_state = cmd->t_state;
cmd->t_state = TRANSPORT_DEFERRED_CMD;
atomic_set(&T_TASK(cmd)->t_transport_active, 0);
if (transport_off == 2)
transport_all_task_dev_remove_state(cmd);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
complete(&T_TASK(cmd)->transport_lun_stop_comp);
return 1;
}
/*
* Determine if frontend context caller is requesting the stopping of
* this command for frontend excpections.
*/
if (atomic_read(&T_TASK(cmd)->t_transport_stop)) {
DEBUG_CS("%s:%d atomic_read(&T_TASK(cmd)->t_transport_stop) =="
" TRUE for ITT: 0x%08x\n", __func__, __LINE__,
CMD_TFO(cmd)->get_task_tag(cmd));
cmd->deferred_t_state = cmd->t_state;
cmd->t_state = TRANSPORT_DEFERRED_CMD;
if (transport_off == 2)
transport_all_task_dev_remove_state(cmd);
/*
* Clear struct se_cmd->se_lun before the transport_off == 2 handoff
* to FE.
*/
if (transport_off == 2)
cmd->se_lun = NULL;
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
complete(&T_TASK(cmd)->t_transport_stop_comp);
return 1;
}
if (transport_off) {
atomic_set(&T_TASK(cmd)->t_transport_active, 0);
if (transport_off == 2) {
transport_all_task_dev_remove_state(cmd);
/*
* Clear struct se_cmd->se_lun before the transport_off == 2
* handoff to fabric module.
*/
cmd->se_lun = NULL;
/*
* Some fabric modules like tcm_loop can release
* their internally allocated I/O reference now and
* struct se_cmd now.
*/
if (CMD_TFO(cmd)->check_stop_free != NULL) {
spin_unlock_irqrestore(
&T_TASK(cmd)->t_state_lock, flags);
CMD_TFO(cmd)->check_stop_free(cmd);
return 1;
}
}
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
return 0;
} else if (t_state)
cmd->t_state = t_state;
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
return 0;
}
static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd)
{
return transport_cmd_check_stop(cmd, 2, 0);
}
static void transport_lun_remove_cmd(struct se_cmd *cmd)
{
struct se_lun *lun = SE_LUN(cmd);
unsigned long flags;
if (!lun)
return;
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
if (!(atomic_read(&T_TASK(cmd)->transport_dev_active))) {
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
goto check_lun;
}
atomic_set(&T_TASK(cmd)->transport_dev_active, 0);
transport_all_task_dev_remove_state(cmd);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
check_lun:
spin_lock_irqsave(&lun->lun_cmd_lock, flags);
if (atomic_read(&T_TASK(cmd)->transport_lun_active)) {
list_del(&cmd->se_lun_list);
atomic_set(&T_TASK(cmd)->transport_lun_active, 0);
#if 0
printk(KERN_INFO "Removed ITT: 0x%08x from LUN LIST[%d]\n"
CMD_TFO(cmd)->get_task_tag(cmd), lun->unpacked_lun);
#endif
}
spin_unlock_irqrestore(&lun->lun_cmd_lock, flags);
}
void transport_cmd_finish_abort(struct se_cmd *cmd, int remove)
{
transport_remove_cmd_from_queue(cmd, SE_DEV(cmd)->dev_queue_obj);
transport_lun_remove_cmd(cmd);
if (transport_cmd_check_stop_to_fabric(cmd))
return;
if (remove)
transport_generic_remove(cmd, 0, 0);
}
void transport_cmd_finish_abort_tmr(struct se_cmd *cmd)
{
transport_remove_cmd_from_queue(cmd, SE_DEV(cmd)->dev_queue_obj);
if (transport_cmd_check_stop_to_fabric(cmd))
return;
transport_generic_remove(cmd, 0, 0);
}
static int transport_add_cmd_to_queue(
struct se_cmd *cmd,
int t_state)
{
struct se_device *dev = cmd->se_dev;
struct se_queue_obj *qobj = dev->dev_queue_obj;
struct se_queue_req *qr;
unsigned long flags;
qr = kzalloc(sizeof(struct se_queue_req), GFP_ATOMIC);
if (!(qr)) {
printk(KERN_ERR "Unable to allocate memory for"
" struct se_queue_req\n");
return -1;
}
INIT_LIST_HEAD(&qr->qr_list);
qr->cmd = (void *)cmd;
qr->state = t_state;
if (t_state) {
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
cmd->t_state = t_state;
atomic_set(&T_TASK(cmd)->t_transport_active, 1);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
}
spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
list_add_tail(&qr->qr_list, &qobj->qobj_list);
atomic_inc(&T_TASK(cmd)->t_transport_queue_active);
spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
atomic_inc(&qobj->queue_cnt);
wake_up_interruptible(&qobj->thread_wq);
return 0;
}
/*
* Called with struct se_queue_obj->cmd_queue_lock held.
*/
static struct se_queue_req *
__transport_get_qr_from_queue(struct se_queue_obj *qobj)
{
struct se_cmd *cmd;
struct se_queue_req *qr = NULL;
if (list_empty(&qobj->qobj_list))
return NULL;
list_for_each_entry(qr, &qobj->qobj_list, qr_list)
break;
if (qr->cmd) {
cmd = (struct se_cmd *)qr->cmd;
atomic_dec(&T_TASK(cmd)->t_transport_queue_active);
}
list_del(&qr->qr_list);
atomic_dec(&qobj->queue_cnt);
return qr;
}
static struct se_queue_req *
transport_get_qr_from_queue(struct se_queue_obj *qobj)
{
struct se_cmd *cmd;
struct se_queue_req *qr;
unsigned long flags;
spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
if (list_empty(&qobj->qobj_list)) {
spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
return NULL;
}
list_for_each_entry(qr, &qobj->qobj_list, qr_list)
break;
if (qr->cmd) {
cmd = (struct se_cmd *)qr->cmd;
atomic_dec(&T_TASK(cmd)->t_transport_queue_active);
}
list_del(&qr->qr_list);
atomic_dec(&qobj->queue_cnt);
spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
return qr;
}
static void transport_remove_cmd_from_queue(struct se_cmd *cmd,
struct se_queue_obj *qobj)
{
struct se_cmd *q_cmd;
struct se_queue_req *qr = NULL, *qr_p = NULL;
unsigned long flags;
spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
if (!(atomic_read(&T_TASK(cmd)->t_transport_queue_active))) {
spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
return;
}
list_for_each_entry_safe(qr, qr_p, &qobj->qobj_list, qr_list) {
q_cmd = (struct se_cmd *)qr->cmd;
if (q_cmd != cmd)
continue;
atomic_dec(&T_TASK(q_cmd)->t_transport_queue_active);
atomic_dec(&qobj->queue_cnt);
list_del(&qr->qr_list);
kfree(qr);
}
spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
if (atomic_read(&T_TASK(cmd)->t_transport_queue_active)) {
printk(KERN_ERR "ITT: 0x%08x t_transport_queue_active: %d\n",
CMD_TFO(cmd)->get_task_tag(cmd),
atomic_read(&T_TASK(cmd)->t_transport_queue_active));
}
}
/*
* Completion function used by TCM subsystem plugins (such as FILEIO)
* for queueing up response from struct se_subsystem_api->do_task()
*/
void transport_complete_sync_cache(struct se_cmd *cmd, int good)
{
struct se_task *task = list_entry(T_TASK(cmd)->t_task_list.next,
struct se_task, t_list);
if (good) {
cmd->scsi_status = SAM_STAT_GOOD;
task->task_scsi_status = GOOD;
} else {
task->task_scsi_status = SAM_STAT_CHECK_CONDITION;
task->task_error_status = PYX_TRANSPORT_ILLEGAL_REQUEST;
TASK_CMD(task)->transport_error_status =
PYX_TRANSPORT_ILLEGAL_REQUEST;
}
transport_complete_task(task, good);
}
EXPORT_SYMBOL(transport_complete_sync_cache);
/* transport_complete_task():
*
* Called from interrupt and non interrupt context depending
* on the transport plugin.
*/
void transport_complete_task(struct se_task *task, int success)
{
struct se_cmd *cmd = TASK_CMD(task);
struct se_device *dev = task->se_dev;
int t_state;
unsigned long flags;
#if 0
printk(KERN_INFO "task: %p CDB: 0x%02x obj_ptr: %p\n", task,
T_TASK(cmd)->t_task_cdb[0], dev);
#endif
if (dev) {
spin_lock_irqsave(&SE_HBA(dev)->hba_queue_lock, flags);
atomic_inc(&dev->depth_left);
atomic_inc(&SE_HBA(dev)->left_queue_depth);
spin_unlock_irqrestore(&SE_HBA(dev)->hba_queue_lock, flags);
}
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
atomic_set(&task->task_active, 0);
/*
* See if any sense data exists, if so set the TASK_SENSE flag.
* Also check for any other post completion work that needs to be
* done by the plugins.
*/
if (dev && dev->transport->transport_complete) {
if (dev->transport->transport_complete(task) != 0) {
cmd->se_cmd_flags |= SCF_TRANSPORT_TASK_SENSE;
task->task_sense = 1;
success = 1;
}
}
/*
* See if we are waiting for outstanding struct se_task
* to complete for an exception condition
*/
if (atomic_read(&task->task_stop)) {
/*
* Decrement T_TASK(cmd)->t_se_count if this task had
* previously thrown its timeout exception handler.
*/
if (atomic_read(&task->task_timeout)) {
atomic_dec(&T_TASK(cmd)->t_se_count);
atomic_set(&task->task_timeout, 0);
}
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
complete(&task->task_stop_comp);
return;
}
/*
* If the task's timeout handler has fired, use the t_task_cdbs_timeout
* left counter to determine when the struct se_cmd is ready to be queued to
* the processing thread.
*/
if (atomic_read(&task->task_timeout)) {
if (!(atomic_dec_and_test(
&T_TASK(cmd)->t_task_cdbs_timeout_left))) {
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock,
flags);
return;
}
t_state = TRANSPORT_COMPLETE_TIMEOUT;
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
transport_add_cmd_to_queue(cmd, t_state);
return;
}
atomic_dec(&T_TASK(cmd)->t_task_cdbs_timeout_left);
/*
* Decrement the outstanding t_task_cdbs_left count. The last
* struct se_task from struct se_cmd will complete itself into the
* device queue depending upon int success.
*/
if (!(atomic_dec_and_test(&T_TASK(cmd)->t_task_cdbs_left))) {
if (!success)
T_TASK(cmd)->t_tasks_failed = 1;
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
return;
}
if (!success || T_TASK(cmd)->t_tasks_failed) {
t_state = TRANSPORT_COMPLETE_FAILURE;
if (!task->task_error_status) {
task->task_error_status =
PYX_TRANSPORT_UNKNOWN_SAM_OPCODE;
cmd->transport_error_status =
PYX_TRANSPORT_UNKNOWN_SAM_OPCODE;
}
} else {
atomic_set(&T_TASK(cmd)->t_transport_complete, 1);
t_state = TRANSPORT_COMPLETE_OK;
}
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
transport_add_cmd_to_queue(cmd, t_state);
}
EXPORT_SYMBOL(transport_complete_task);
/*
* Called by transport_add_tasks_from_cmd() once a struct se_cmd's
* struct se_task list are ready to be added to the active execution list
* struct se_device
* Called with se_dev_t->execute_task_lock called.
*/
static inline int transport_add_task_check_sam_attr(
struct se_task *task,
struct se_task *task_prev,
struct se_device *dev)
{
/*
* No SAM Task attribute emulation enabled, add to tail of
* execution queue
*/
if (dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED) {
list_add_tail(&task->t_execute_list, &dev->execute_task_list);
return 0;
}
/*
* HEAD_OF_QUEUE attribute for received CDB, which means
* the first task that is associated with a struct se_cmd goes to
* head of the struct se_device->execute_task_list, and task_prev
* after that for each subsequent task
*/
if (task->task_se_cmd->sam_task_attr == TASK_ATTR_HOQ) {
list_add(&task->t_execute_list,
(task_prev != NULL) ?
&task_prev->t_execute_list :
&dev->execute_task_list);
DEBUG_STA("Set HEAD_OF_QUEUE for task CDB: 0x%02x"
" in execution queue\n",
T_TASK(task->task_se_cmd)->t_task_cdb[0]);
return 1;
}
/*
* For ORDERED, SIMPLE or UNTAGGED attribute tasks once they have been
* transitioned from Dermant -> Active state, and are added to the end
* of the struct se_device->execute_task_list
*/
list_add_tail(&task->t_execute_list, &dev->execute_task_list);
return 0;
}
/* __transport_add_task_to_execute_queue():
*
* Called with se_dev_t->execute_task_lock called.
*/
static void __transport_add_task_to_execute_queue(
struct se_task *task,
struct se_task *task_prev,
struct se_device *dev)
{
int head_of_queue;
head_of_queue = transport_add_task_check_sam_attr(task, task_prev, dev);
atomic_inc(&dev->execute_tasks);
if (atomic_read(&task->task_state_active))
return;
/*
* Determine if this task needs to go to HEAD_OF_QUEUE for the
* state list as well. Running with SAM Task Attribute emulation
* will always return head_of_queue == 0 here
*/
if (head_of_queue)
list_add(&task->t_state_list, (task_prev) ?
&task_prev->t_state_list :
&dev->state_task_list);
else
list_add_tail(&task->t_state_list, &dev->state_task_list);
atomic_set(&task->task_state_active, 1);
DEBUG_TSTATE("Added ITT: 0x%08x task[%p] to dev: %p\n",
CMD_TFO(task->task_se_cmd)->get_task_tag(task->task_se_cmd),
task, dev);
}
static void transport_add_tasks_to_state_queue(struct se_cmd *cmd)
{
struct se_device *dev;
struct se_task *task;
unsigned long flags;
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
list_for_each_entry(task, &T_TASK(cmd)->t_task_list, t_list) {
dev = task->se_dev;
if (atomic_read(&task->task_state_active))
continue;
spin_lock(&dev->execute_task_lock);
list_add_tail(&task->t_state_list, &dev->state_task_list);
atomic_set(&task->task_state_active, 1);
DEBUG_TSTATE("Added ITT: 0x%08x task[%p] to dev: %p\n",
CMD_TFO(task->task_se_cmd)->get_task_tag(
task->task_se_cmd), task, dev);
spin_unlock(&dev->execute_task_lock);
}
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
}
static void transport_add_tasks_from_cmd(struct se_cmd *cmd)
{
struct se_device *dev = SE_DEV(cmd);
struct se_task *task, *task_prev = NULL;
unsigned long flags;
spin_lock_irqsave(&dev->execute_task_lock, flags);
list_for_each_entry(task, &T_TASK(cmd)->t_task_list, t_list) {
if (atomic_read(&task->task_execute_queue))
continue;
/*
* __transport_add_task_to_execute_queue() handles the
* SAM Task Attribute emulation if enabled
*/
__transport_add_task_to_execute_queue(task, task_prev, dev);
atomic_set(&task->task_execute_queue, 1);
task_prev = task;
}
spin_unlock_irqrestore(&dev->execute_task_lock, flags);
return;
}
/* transport_get_task_from_execute_queue():
*
* Called with dev->execute_task_lock held.
*/
static struct se_task *
transport_get_task_from_execute_queue(struct se_device *dev)
{
struct se_task *task;
if (list_empty(&dev->execute_task_list))
return NULL;
list_for_each_entry(task, &dev->execute_task_list, t_execute_list)
break;
list_del(&task->t_execute_list);
atomic_set(&task->task_execute_queue, 0);
atomic_dec(&dev->execute_tasks);
return task;
}
/* transport_remove_task_from_execute_queue():
*
*
*/
void transport_remove_task_from_execute_queue(
struct se_task *task,
struct se_device *dev)
{
unsigned long flags;
if (atomic_read(&task->task_execute_queue) == 0) {
dump_stack();
return;
}
spin_lock_irqsave(&dev->execute_task_lock, flags);
list_del(&task->t_execute_list);
atomic_set(&task->task_execute_queue, 0);
atomic_dec(&dev->execute_tasks);
spin_unlock_irqrestore(&dev->execute_task_lock, flags);
}
unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd)
{
switch (cmd->data_direction) {
case DMA_NONE:
return "NONE";
case DMA_FROM_DEVICE:
return "READ";
case DMA_TO_DEVICE:
return "WRITE";
case DMA_BIDIRECTIONAL:
return "BIDI";
default:
break;
}
return "UNKNOWN";
}
void transport_dump_dev_state(
struct se_device *dev,
char *b,
int *bl)
{
*bl += sprintf(b + *bl, "Status: ");
switch (dev->dev_status) {
case TRANSPORT_DEVICE_ACTIVATED:
*bl += sprintf(b + *bl, "ACTIVATED");
break;
case TRANSPORT_DEVICE_DEACTIVATED:
*bl += sprintf(b + *bl, "DEACTIVATED");
break;
case TRANSPORT_DEVICE_SHUTDOWN:
*bl += sprintf(b + *bl, "SHUTDOWN");
break;
case TRANSPORT_DEVICE_OFFLINE_ACTIVATED:
case TRANSPORT_DEVICE_OFFLINE_DEACTIVATED:
*bl += sprintf(b + *bl, "OFFLINE");
break;
default:
*bl += sprintf(b + *bl, "UNKNOWN=%d", dev->dev_status);
break;
}
*bl += sprintf(b + *bl, " Execute/Left/Max Queue Depth: %d/%d/%d",
atomic_read(&dev->execute_tasks), atomic_read(&dev->depth_left),
dev->queue_depth);
*bl += sprintf(b + *bl, " SectorSize: %u MaxSectors: %u\n",
DEV_ATTRIB(dev)->block_size, DEV_ATTRIB(dev)->max_sectors);
*bl += sprintf(b + *bl, " ");
}
/* transport_release_all_cmds():
*
*
*/
static void transport_release_all_cmds(struct se_device *dev)
{
struct se_cmd *cmd = NULL;
struct se_queue_req *qr = NULL, *qr_p = NULL;
int bug_out = 0, t_state;
unsigned long flags;
spin_lock_irqsave(&dev->dev_queue_obj->cmd_queue_lock, flags);
list_for_each_entry_safe(qr, qr_p, &dev->dev_queue_obj->qobj_list,
qr_list) {
cmd = (struct se_cmd *)qr->cmd;
t_state = qr->state;
list_del(&qr->qr_list);
kfree(qr);
spin_unlock_irqrestore(&dev->dev_queue_obj->cmd_queue_lock,
flags);
printk(KERN_ERR "Releasing ITT: 0x%08x, i_state: %u,"
" t_state: %u directly\n",
CMD_TFO(cmd)->get_task_tag(cmd),
CMD_TFO(cmd)->get_cmd_state(cmd), t_state);
transport_release_fe_cmd(cmd);
bug_out = 1;
spin_lock_irqsave(&dev->dev_queue_obj->cmd_queue_lock, flags);
}
spin_unlock_irqrestore(&dev->dev_queue_obj->cmd_queue_lock, flags);
#if 0
if (bug_out)
BUG();
#endif
}
void transport_dump_vpd_proto_id(
struct t10_vpd *vpd,
unsigned char *p_buf,
int p_buf_len)
{
unsigned char buf[VPD_TMP_BUF_SIZE];
int len;
memset(buf, 0, VPD_TMP_BUF_SIZE);
len = sprintf(buf, "T10 VPD Protocol Identifier: ");
switch (vpd->protocol_identifier) {
case 0x00:
sprintf(buf+len, "Fibre Channel\n");
break;
case 0x10:
sprintf(buf+len, "Parallel SCSI\n");
break;
case 0x20:
sprintf(buf+len, "SSA\n");
break;
case 0x30:
sprintf(buf+len, "IEEE 1394\n");
break;
case 0x40:
sprintf(buf+len, "SCSI Remote Direct Memory Access"
" Protocol\n");
break;
case 0x50:
sprintf(buf+len, "Internet SCSI (iSCSI)\n");
break;
case 0x60:
sprintf(buf+len, "SAS Serial SCSI Protocol\n");
break;
case 0x70:
sprintf(buf+len, "Automation/Drive Interface Transport"
" Protocol\n");
break;
case 0x80:
sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n");
break;
default:
sprintf(buf+len, "Unknown 0x%02x\n",
vpd->protocol_identifier);
break;
}
if (p_buf)
strncpy(p_buf, buf, p_buf_len);
else
printk(KERN_INFO "%s", buf);
}
void
transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83)
{
/*
* Check if the Protocol Identifier Valid (PIV) bit is set..
*
* from spc3r23.pdf section 7.5.1
*/
if (page_83[1] & 0x80) {
vpd->protocol_identifier = (page_83[0] & 0xf0);
vpd->protocol_identifier_set = 1;
transport_dump_vpd_proto_id(vpd, NULL, 0);
}
}
EXPORT_SYMBOL(transport_set_vpd_proto_id);
int transport_dump_vpd_assoc(
struct t10_vpd *vpd,
unsigned char *p_buf,
int p_buf_len)
{
unsigned char buf[VPD_TMP_BUF_SIZE];
int ret = 0, len;
memset(buf, 0, VPD_TMP_BUF_SIZE);
len = sprintf(buf, "T10 VPD Identifier Association: ");
switch (vpd->association) {
case 0x00:
sprintf(buf+len, "addressed logical unit\n");
break;
case 0x10:
sprintf(buf+len, "target port\n");
break;
case 0x20:
sprintf(buf+len, "SCSI target device\n");
break;
default:
sprintf(buf+len, "Unknown 0x%02x\n", vpd->association);
ret = -1;
break;
}
if (p_buf)
strncpy(p_buf, buf, p_buf_len);
else
printk("%s", buf);
return ret;
}
int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83)
{
/*
* The VPD identification association..
*
* from spc3r23.pdf Section 7.6.3.1 Table 297
*/
vpd->association = (page_83[1] & 0x30);
return transport_dump_vpd_assoc(vpd, NULL, 0);
}
EXPORT_SYMBOL(transport_set_vpd_assoc);
int transport_dump_vpd_ident_type(
struct t10_vpd *vpd,
unsigned char *p_buf,
int p_buf_len)
{
unsigned char buf[VPD_TMP_BUF_SIZE];
int ret = 0, len;
memset(buf, 0, VPD_TMP_BUF_SIZE);
len = sprintf(buf, "T10 VPD Identifier Type: ");
switch (vpd->device_identifier_type) {
case 0x00:
sprintf(buf+len, "Vendor specific\n");
break;
case 0x01:
sprintf(buf+len, "T10 Vendor ID based\n");
break;
case 0x02:
sprintf(buf+len, "EUI-64 based\n");
break;
case 0x03:
sprintf(buf+len, "NAA\n");
break;
case 0x04:
sprintf(buf+len, "Relative target port identifier\n");
break;
case 0x08:
sprintf(buf+len, "SCSI name string\n");
break;
default:
sprintf(buf+len, "Unsupported: 0x%02x\n",
vpd->device_identifier_type);
ret = -1;
break;
}
if (p_buf)
strncpy(p_buf, buf, p_buf_len);
else
printk("%s", buf);
return ret;
}
int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83)
{
/*
* The VPD identifier type..
*
* from spc3r23.pdf Section 7.6.3.1 Table 298
*/
vpd->device_identifier_type = (page_83[1] & 0x0f);
return transport_dump_vpd_ident_type(vpd, NULL, 0);
}
EXPORT_SYMBOL(transport_set_vpd_ident_type);
int transport_dump_vpd_ident(
struct t10_vpd *vpd,
unsigned char *p_buf,
int p_buf_len)
{
unsigned char buf[VPD_TMP_BUF_SIZE];
int ret = 0;
memset(buf, 0, VPD_TMP_BUF_SIZE);
switch (vpd->device_identifier_code_set) {
case 0x01: /* Binary */
sprintf(buf, "T10 VPD Binary Device Identifier: %s\n",
&vpd->device_identifier[0]);
break;
case 0x02: /* ASCII */
sprintf(buf, "T10 VPD ASCII Device Identifier: %s\n",
&vpd->device_identifier[0]);
break;
case 0x03: /* UTF-8 */
sprintf(buf, "T10 VPD UTF-8 Device Identifier: %s\n",
&vpd->device_identifier[0]);
break;
default:
sprintf(buf, "T10 VPD Device Identifier encoding unsupported:"
" 0x%02x", vpd->device_identifier_code_set);
ret = -1;
break;
}
if (p_buf)
strncpy(p_buf, buf, p_buf_len);
else
printk("%s", buf);
return ret;
}
int
transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83)
{
static const char hex_str[] = "0123456789abcdef";
int j = 0, i = 4; /* offset to start of the identifer */
/*
* The VPD Code Set (encoding)
*
* from spc3r23.pdf Section 7.6.3.1 Table 296
*/
vpd->device_identifier_code_set = (page_83[0] & 0x0f);
switch (vpd->device_identifier_code_set) {
case 0x01: /* Binary */
vpd->device_identifier[j++] =
hex_str[vpd->device_identifier_type];
while (i < (4 + page_83[3])) {
vpd->device_identifier[j++] =
hex_str[(page_83[i] & 0xf0) >> 4];
vpd->device_identifier[j++] =
hex_str[page_83[i] & 0x0f];
i++;
}
break;
case 0x02: /* ASCII */
case 0x03: /* UTF-8 */
while (i < (4 + page_83[3]))
vpd->device_identifier[j++] = page_83[i++];
break;
default:
break;
}
return transport_dump_vpd_ident(vpd, NULL, 0);
}
EXPORT_SYMBOL(transport_set_vpd_ident);
static void core_setup_task_attr_emulation(struct se_device *dev)
{
/*
* If this device is from Target_Core_Mod/pSCSI, disable the
* SAM Task Attribute emulation.
*
* This is currently not available in upsream Linux/SCSI Target
* mode code, and is assumed to be disabled while using TCM/pSCSI.
*/
if (TRANSPORT(dev)->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV) {
dev->dev_task_attr_type = SAM_TASK_ATTR_PASSTHROUGH;
return;
}
dev->dev_task_attr_type = SAM_TASK_ATTR_EMULATED;
DEBUG_STA("%s: Using SAM_TASK_ATTR_EMULATED for SPC: 0x%02x"
" device\n", TRANSPORT(dev)->name,
TRANSPORT(dev)->get_device_rev(dev));
}
static void scsi_dump_inquiry(struct se_device *dev)
{
struct t10_wwn *wwn = DEV_T10_WWN(dev);
int i, device_type;
/*
* Print Linux/SCSI style INQUIRY formatting to the kernel ring buffer
*/
printk(" Vendor: ");
for (i = 0; i < 8; i++)
if (wwn->vendor[i] >= 0x20)
printk("%c", wwn->vendor[i]);
else
printk(" ");
printk(" Model: ");
for (i = 0; i < 16; i++)
if (wwn->model[i] >= 0x20)
printk("%c", wwn->model[i]);
else
printk(" ");
printk(" Revision: ");
for (i = 0; i < 4; i++)
if (wwn->revision[i] >= 0x20)
printk("%c", wwn->revision[i]);
else
printk(" ");
printk("\n");
device_type = TRANSPORT(dev)->get_device_type(dev);
printk(" Type: %s ", scsi_device_type(device_type));
printk(" ANSI SCSI revision: %02x\n",
TRANSPORT(dev)->get_device_rev(dev));
}
struct se_device *transport_add_device_to_core_hba(
struct se_hba *hba,
struct se_subsystem_api *transport,
struct se_subsystem_dev *se_dev,
u32 device_flags,
void *transport_dev,
struct se_dev_limits *dev_limits,
const char *inquiry_prod,
const char *inquiry_rev)
{
int force_pt;
struct se_device *dev;
dev = kzalloc(sizeof(struct se_device), GFP_KERNEL);
if (!(dev)) {
printk(KERN_ERR "Unable to allocate memory for se_dev_t\n");
return NULL;
}
dev->dev_queue_obj = kzalloc(sizeof(struct se_queue_obj), GFP_KERNEL);
if (!(dev->dev_queue_obj)) {
printk(KERN_ERR "Unable to allocate memory for"
" dev->dev_queue_obj\n");
kfree(dev);
return NULL;
}
transport_init_queue_obj(dev->dev_queue_obj);
dev->dev_status_queue_obj = kzalloc(sizeof(struct se_queue_obj),
GFP_KERNEL);
if (!(dev->dev_status_queue_obj)) {
printk(KERN_ERR "Unable to allocate memory for"
" dev->dev_status_queue_obj\n");
kfree(dev->dev_queue_obj);
kfree(dev);
return NULL;
}
transport_init_queue_obj(dev->dev_status_queue_obj);
dev->dev_flags = device_flags;
dev->dev_status |= TRANSPORT_DEVICE_DEACTIVATED;
dev->dev_ptr = (void *) transport_dev;
dev->se_hba = hba;
dev->se_sub_dev = se_dev;
dev->transport = transport;
atomic_set(&dev->active_cmds, 0);
INIT_LIST_HEAD(&dev->dev_list);
INIT_LIST_HEAD(&dev->dev_sep_list);
INIT_LIST_HEAD(&dev->dev_tmr_list);
INIT_LIST_HEAD(&dev->execute_task_list);
INIT_LIST_HEAD(&dev->delayed_cmd_list);
INIT_LIST_HEAD(&dev->ordered_cmd_list);
INIT_LIST_HEAD(&dev->state_task_list);
spin_lock_init(&dev->execute_task_lock);
spin_lock_init(&dev->delayed_cmd_lock);
spin_lock_init(&dev->ordered_cmd_lock);
spin_lock_init(&dev->state_task_lock);
spin_lock_init(&dev->dev_alua_lock);
spin_lock_init(&dev->dev_reservation_lock);
spin_lock_init(&dev->dev_status_lock);
spin_lock_init(&dev->dev_status_thr_lock);
spin_lock_init(&dev->se_port_lock);
spin_lock_init(&dev->se_tmr_lock);
dev->queue_depth = dev_limits->queue_depth;
atomic_set(&dev->depth_left, dev->queue_depth);
atomic_set(&dev->dev_ordered_id, 0);
se_dev_set_default_attribs(dev, dev_limits);
dev->dev_index = scsi_get_new_index(SCSI_DEVICE_INDEX);
dev->creation_time = get_jiffies_64();
spin_lock_init(&dev->stats_lock);
spin_lock(&hba->device_lock);
list_add_tail(&dev->dev_list, &hba->hba_dev_list);
hba->dev_count++;
spin_unlock(&hba->device_lock);
/*
* Setup the SAM Task Attribute emulation for struct se_device
*/
core_setup_task_attr_emulation(dev);
/*
* Force PR and ALUA passthrough emulation with internal object use.
*/
force_pt = (hba->hba_flags & HBA_FLAGS_INTERNAL_USE);
/*
* Setup the Reservations infrastructure for struct se_device
*/
core_setup_reservations(dev, force_pt);
/*
* Setup the Asymmetric Logical Unit Assignment for struct se_device
*/
if (core_setup_alua(dev, force_pt) < 0)
goto out;
/*
* Startup the struct se_device processing thread
*/
dev->process_thread = kthread_run(transport_processing_thread, dev,
"LIO_%s", TRANSPORT(dev)->name);
if (IS_ERR(dev->process_thread)) {
printk(KERN_ERR "Unable to create kthread: LIO_%s\n",
TRANSPORT(dev)->name);
goto out;
}
/*
* Preload the initial INQUIRY const values if we are doing
* anything virtual (IBLOCK, FILEIO, RAMDISK), but not for TCM/pSCSI
* passthrough because this is being provided by the backend LLD.
* This is required so that transport_get_inquiry() copies these
* originals once back into DEV_T10_WWN(dev) for the virtual device
* setup.
*/
if (TRANSPORT(dev)->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV) {
if (!(inquiry_prod) || !(inquiry_prod)) {
printk(KERN_ERR "All non TCM/pSCSI plugins require"
" INQUIRY consts\n");
goto out;
}
strncpy(&DEV_T10_WWN(dev)->vendor[0], "LIO-ORG", 8);
strncpy(&DEV_T10_WWN(dev)->model[0], inquiry_prod, 16);
strncpy(&DEV_T10_WWN(dev)->revision[0], inquiry_rev, 4);
}
scsi_dump_inquiry(dev);
return dev;
out:
kthread_stop(dev->process_thread);
spin_lock(&hba->device_lock);
list_del(&dev->dev_list);
hba->dev_count--;
spin_unlock(&hba->device_lock);
se_release_vpd_for_dev(dev);
kfree(dev->dev_status_queue_obj);
kfree(dev->dev_queue_obj);
kfree(dev);
return NULL;
}
EXPORT_SYMBOL(transport_add_device_to_core_hba);
/* transport_generic_prepare_cdb():
*
* Since the Initiator sees iSCSI devices as LUNs, the SCSI CDB will
* contain the iSCSI LUN in bits 7-5 of byte 1 as per SAM-2.
* The point of this is since we are mapping iSCSI LUNs to
* SCSI Target IDs having a non-zero LUN in the CDB will throw the
* devices and HBAs for a loop.
*/
static inline void transport_generic_prepare_cdb(
unsigned char *cdb)
{
switch (cdb[0]) {
case READ_10: /* SBC - RDProtect */
case READ_12: /* SBC - RDProtect */
case READ_16: /* SBC - RDProtect */
case SEND_DIAGNOSTIC: /* SPC - SELF-TEST Code */
case VERIFY: /* SBC - VRProtect */
case VERIFY_16: /* SBC - VRProtect */
case WRITE_VERIFY: /* SBC - VRProtect */
case WRITE_VERIFY_12: /* SBC - VRProtect */
break;
default:
cdb[1] &= 0x1f; /* clear logical unit number */
break;
}
}
static struct se_task *
transport_generic_get_task(struct se_cmd *cmd,
enum dma_data_direction data_direction)
{
struct se_task *task;
struct se_device *dev = SE_DEV(cmd);
unsigned long flags;
task = dev->transport->alloc_task(cmd);
if (!task) {
printk(KERN_ERR "Unable to allocate struct se_task\n");
return NULL;
}
INIT_LIST_HEAD(&task->t_list);
INIT_LIST_HEAD(&task->t_execute_list);
INIT_LIST_HEAD(&task->t_state_list);
init_completion(&task->task_stop_comp);
task->task_no = T_TASK(cmd)->t_tasks_no++;
task->task_se_cmd = cmd;
task->se_dev = dev;
task->task_data_direction = data_direction;
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
list_add_tail(&task->t_list, &T_TASK(cmd)->t_task_list);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
return task;
}
static int transport_generic_cmd_sequencer(struct se_cmd *, unsigned char *);
void transport_device_setup_cmd(struct se_cmd *cmd)
{
cmd->se_dev = SE_LUN(cmd)->lun_se_dev;
}
EXPORT_SYMBOL(transport_device_setup_cmd);
/*
* Used by fabric modules containing a local struct se_cmd within their
* fabric dependent per I/O descriptor.
*/
void transport_init_se_cmd(
struct se_cmd *cmd,
struct target_core_fabric_ops *tfo,
struct se_session *se_sess,
u32 data_length,
int data_direction,
int task_attr,
unsigned char *sense_buffer)
{
INIT_LIST_HEAD(&cmd->se_lun_list);
INIT_LIST_HEAD(&cmd->se_delayed_list);
INIT_LIST_HEAD(&cmd->se_ordered_list);
/*
* Setup t_task pointer to t_task_backstore
*/
cmd->t_task = &cmd->t_task_backstore;
INIT_LIST_HEAD(&T_TASK(cmd)->t_task_list);
init_completion(&T_TASK(cmd)->transport_lun_fe_stop_comp);
init_completion(&T_TASK(cmd)->transport_lun_stop_comp);
init_completion(&T_TASK(cmd)->t_transport_stop_comp);
spin_lock_init(&T_TASK(cmd)->t_state_lock);
atomic_set(&T_TASK(cmd)->transport_dev_active, 1);
cmd->se_tfo = tfo;
cmd->se_sess = se_sess;
cmd->data_length = data_length;
cmd->data_direction = data_direction;
cmd->sam_task_attr = task_attr;
cmd->sense_buffer = sense_buffer;
}
EXPORT_SYMBOL(transport_init_se_cmd);
static int transport_check_alloc_task_attr(struct se_cmd *cmd)
{
/*
* Check if SAM Task Attribute emulation is enabled for this
* struct se_device storage object
*/
if (SE_DEV(cmd)->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
return 0;
if (cmd->sam_task_attr == TASK_ATTR_ACA) {
DEBUG_STA("SAM Task Attribute ACA"
" emulation is not supported\n");
return -1;
}
/*
* Used to determine when ORDERED commands should go from
* Dormant to Active status.
*/
cmd->se_ordered_id = atomic_inc_return(&SE_DEV(cmd)->dev_ordered_id);
smp_mb__after_atomic_inc();
DEBUG_STA("Allocated se_ordered_id: %u for Task Attr: 0x%02x on %s\n",
cmd->se_ordered_id, cmd->sam_task_attr,
TRANSPORT(cmd->se_dev)->name);
return 0;
}
void transport_free_se_cmd(
struct se_cmd *se_cmd)
{
if (se_cmd->se_tmr_req)
core_tmr_release_req(se_cmd->se_tmr_req);
/*
* Check and free any extended CDB buffer that was allocated
*/
if (T_TASK(se_cmd)->t_task_cdb != T_TASK(se_cmd)->__t_task_cdb)
kfree(T_TASK(se_cmd)->t_task_cdb);
}
EXPORT_SYMBOL(transport_free_se_cmd);
static void transport_generic_wait_for_tasks(struct se_cmd *, int, int);
/* transport_generic_allocate_tasks():
*
* Called from fabric RX Thread.
*/
int transport_generic_allocate_tasks(
struct se_cmd *cmd,
unsigned char *cdb)
{
int ret;
transport_generic_prepare_cdb(cdb);
/*
* This is needed for early exceptions.
*/
cmd->transport_wait_for_tasks = &transport_generic_wait_for_tasks;
transport_device_setup_cmd(cmd);
/*
* Ensure that the received CDB is less than the max (252 + 8) bytes
* for VARIABLE_LENGTH_CMD
*/
if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) {
printk(KERN_ERR "Received SCSI CDB with command_size: %d that"
" exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE);
return -1;
}
/*
* If the received CDB is larger than TCM_MAX_COMMAND_SIZE,
* allocate the additional extended CDB buffer now.. Otherwise
* setup the pointer from __t_task_cdb to t_task_cdb.
*/
if (scsi_command_size(cdb) > sizeof(T_TASK(cmd)->__t_task_cdb)) {
T_TASK(cmd)->t_task_cdb = kzalloc(scsi_command_size(cdb),
GFP_KERNEL);
if (!(T_TASK(cmd)->t_task_cdb)) {
printk(KERN_ERR "Unable to allocate T_TASK(cmd)->t_task_cdb"
" %u > sizeof(T_TASK(cmd)->__t_task_cdb): %lu ops\n",
scsi_command_size(cdb),
(unsigned long)sizeof(T_TASK(cmd)->__t_task_cdb));
return -1;
}
} else
T_TASK(cmd)->t_task_cdb = &T_TASK(cmd)->__t_task_cdb[0];
/*
* Copy the original CDB into T_TASK(cmd).
*/
memcpy(T_TASK(cmd)->t_task_cdb, cdb, scsi_command_size(cdb));
/*
* Setup the received CDB based on SCSI defined opcodes and
* perform unit attention, persistent reservations and ALUA
* checks for virtual device backends. The T_TASK(cmd)->t_task_cdb
* pointer is expected to be setup before we reach this point.
*/
ret = transport_generic_cmd_sequencer(cmd, cdb);
if (ret < 0)
return ret;
/*
* Check for SAM Task Attribute Emulation
*/
if (transport_check_alloc_task_attr(cmd) < 0) {
cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
return -2;
}
spin_lock(&cmd->se_lun->lun_sep_lock);
if (cmd->se_lun->lun_sep)
cmd->se_lun->lun_sep->sep_stats.cmd_pdus++;
spin_unlock(&cmd->se_lun->lun_sep_lock);
return 0;
}
EXPORT_SYMBOL(transport_generic_allocate_tasks);
/*
* Used by fabric module frontends not defining a TFO->new_cmd_map()
* to queue up a newly setup se_cmd w/ TRANSPORT_NEW_CMD statis
*/
int transport_generic_handle_cdb(
struct se_cmd *cmd)
{
if (!SE_LUN(cmd)) {
dump_stack();
printk(KERN_ERR "SE_LUN(cmd) is NULL\n");
return -1;
}
transport_add_cmd_to_queue(cmd, TRANSPORT_NEW_CMD);
return 0;
}
EXPORT_SYMBOL(transport_generic_handle_cdb);
/*
* Used by fabric module frontends defining a TFO->new_cmd_map() caller
* to queue up a newly setup se_cmd w/ TRANSPORT_NEW_CMD_MAP in order to
* complete setup in TCM process context w/ TFO->new_cmd_map().
*/
int transport_generic_handle_cdb_map(
struct se_cmd *cmd)
{
if (!SE_LUN(cmd)) {
dump_stack();
printk(KERN_ERR "SE_LUN(cmd) is NULL\n");
return -1;
}
transport_add_cmd_to_queue(cmd, TRANSPORT_NEW_CMD_MAP);
return 0;
}
EXPORT_SYMBOL(transport_generic_handle_cdb_map);
/* transport_generic_handle_data():
*
*
*/
int transport_generic_handle_data(
struct se_cmd *cmd)
{
/*
* For the software fabric case, then we assume the nexus is being
* failed/shutdown when signals are pending from the kthread context
* caller, so we return a failure. For the HW target mode case running
* in interrupt code, the signal_pending() check is skipped.
*/
if (!in_interrupt() && signal_pending(current))
return -1;
/*
* If the received CDB has aleady been ABORTED by the generic
* target engine, we now call transport_check_aborted_status()
* to queue any delated TASK_ABORTED status for the received CDB to the
* fabric module as we are expecting no further incoming DATA OUT
* sequences at this point.
*/
if (transport_check_aborted_status(cmd, 1) != 0)
return 0;
transport_add_cmd_to_queue(cmd, TRANSPORT_PROCESS_WRITE);
return 0;
}
EXPORT_SYMBOL(transport_generic_handle_data);
/* transport_generic_handle_tmr():
*
*
*/
int transport_generic_handle_tmr(
struct se_cmd *cmd)
{
/*
* This is needed for early exceptions.
*/
cmd->transport_wait_for_tasks = &transport_generic_wait_for_tasks;
transport_device_setup_cmd(cmd);
transport_add_cmd_to_queue(cmd, TRANSPORT_PROCESS_TMR);
return 0;
}
EXPORT_SYMBOL(transport_generic_handle_tmr);
void transport_generic_free_cmd_intr(
struct se_cmd *cmd)
{
transport_add_cmd_to_queue(cmd, TRANSPORT_FREE_CMD_INTR);
}
EXPORT_SYMBOL(transport_generic_free_cmd_intr);
static int transport_stop_tasks_for_cmd(struct se_cmd *cmd)
{
struct se_task *task, *task_tmp;
unsigned long flags;
int ret = 0;
DEBUG_TS("ITT[0x%08x] - Stopping tasks\n",
CMD_TFO(cmd)->get_task_tag(cmd));
/*
* No tasks remain in the execution queue
*/
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
list_for_each_entry_safe(task, task_tmp,
&T_TASK(cmd)->t_task_list, t_list) {
DEBUG_TS("task_no[%d] - Processing task %p\n",
task->task_no, task);
/*
* If the struct se_task has not been sent and is not active,
* remove the struct se_task from the execution queue.
*/
if (!atomic_read(&task->task_sent) &&
!atomic_read(&task->task_active)) {
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock,
flags);
transport_remove_task_from_execute_queue(task,
task->se_dev);
DEBUG_TS("task_no[%d] - Removed from execute queue\n",
task->task_no);
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
continue;
}
/*
* If the struct se_task is active, sleep until it is returned
* from the plugin.
*/
if (atomic_read(&task->task_active)) {
atomic_set(&task->task_stop, 1);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock,
flags);
DEBUG_TS("task_no[%d] - Waiting to complete\n",
task->task_no);
wait_for_completion(&task->task_stop_comp);
DEBUG_TS("task_no[%d] - Stopped successfully\n",
task->task_no);
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
atomic_dec(&T_TASK(cmd)->t_task_cdbs_left);
atomic_set(&task->task_active, 0);
atomic_set(&task->task_stop, 0);
} else {
DEBUG_TS("task_no[%d] - Did nothing\n", task->task_no);
ret++;
}
__transport_stop_task_timer(task, &flags);
}
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
return ret;
}
static void transport_failure_reset_queue_depth(struct se_device *dev)
{
unsigned long flags;
spin_lock_irqsave(&SE_HBA(dev)->hba_queue_lock, flags);;
atomic_inc(&dev->depth_left);
atomic_inc(&SE_HBA(dev)->left_queue_depth);
spin_unlock_irqrestore(&SE_HBA(dev)->hba_queue_lock, flags);
}
/*
* Handle SAM-esque emulation for generic transport request failures.
*/
static void transport_generic_request_failure(
struct se_cmd *cmd,
struct se_device *dev,
int complete,
int sc)
{
DEBUG_GRF("-----[ Storage Engine Exception for cmd: %p ITT: 0x%08x"
" CDB: 0x%02x\n", cmd, CMD_TFO(cmd)->get_task_tag(cmd),
T_TASK(cmd)->t_task_cdb[0]);
DEBUG_GRF("-----[ i_state: %d t_state/def_t_state:"
" %d/%d transport_error_status: %d\n",
CMD_TFO(cmd)->get_cmd_state(cmd),
cmd->t_state, cmd->deferred_t_state,
cmd->transport_error_status);
DEBUG_GRF("-----[ t_task_cdbs: %d t_task_cdbs_left: %d"
" t_task_cdbs_sent: %d t_task_cdbs_ex_left: %d --"
" t_transport_active: %d t_transport_stop: %d"
" t_transport_sent: %d\n", T_TASK(cmd)->t_task_cdbs,
atomic_read(&T_TASK(cmd)->t_task_cdbs_left),
atomic_read(&T_TASK(cmd)->t_task_cdbs_sent),
atomic_read(&T_TASK(cmd)->t_task_cdbs_ex_left),
atomic_read(&T_TASK(cmd)->t_transport_active),
atomic_read(&T_TASK(cmd)->t_transport_stop),
atomic_read(&T_TASK(cmd)->t_transport_sent));
transport_stop_all_task_timers(cmd);
if (dev)
transport_failure_reset_queue_depth(dev);
/*
* For SAM Task Attribute emulation for failed struct se_cmd
*/
if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
transport_complete_task_attr(cmd);
if (complete) {
transport_direct_request_timeout(cmd);
cmd->transport_error_status = PYX_TRANSPORT_LU_COMM_FAILURE;
}
switch (cmd->transport_error_status) {
case PYX_TRANSPORT_UNKNOWN_SAM_OPCODE:
cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
break;
case PYX_TRANSPORT_REQ_TOO_MANY_SECTORS:
cmd->scsi_sense_reason = TCM_SECTOR_COUNT_TOO_MANY;
break;
case PYX_TRANSPORT_INVALID_CDB_FIELD:
cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
break;
case PYX_TRANSPORT_INVALID_PARAMETER_LIST:
cmd->scsi_sense_reason = TCM_INVALID_PARAMETER_LIST;
break;
case PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES:
if (!sc)
transport_new_cmd_failure(cmd);
/*
* Currently for PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES,
* we force this session to fall back to session
* recovery.
*/
CMD_TFO(cmd)->fall_back_to_erl0(cmd->se_sess);
CMD_TFO(cmd)->stop_session(cmd->se_sess, 0, 0);
goto check_stop;
case PYX_TRANSPORT_LU_COMM_FAILURE:
case PYX_TRANSPORT_ILLEGAL_REQUEST:
cmd->scsi_sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
break;
case PYX_TRANSPORT_UNKNOWN_MODE_PAGE:
cmd->scsi_sense_reason = TCM_UNKNOWN_MODE_PAGE;
break;
case PYX_TRANSPORT_WRITE_PROTECTED:
cmd->scsi_sense_reason = TCM_WRITE_PROTECTED;
break;
case PYX_TRANSPORT_RESERVATION_CONFLICT:
/*
* No SENSE Data payload for this case, set SCSI Status
* and queue the response to $FABRIC_MOD.
*
* Uses linux/include/scsi/scsi.h SAM status codes defs
*/
cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
/*
* For UA Interlock Code 11b, a RESERVATION CONFLICT will
* establish a UNIT ATTENTION with PREVIOUS RESERVATION
* CONFLICT STATUS.
*
* See spc4r17, section 7.4.6 Control Mode Page, Table 349
*/
if (SE_SESS(cmd) &&
DEV_ATTRIB(cmd->se_dev)->emulate_ua_intlck_ctrl == 2)
core_scsi3_ua_allocate(SE_SESS(cmd)->se_node_acl,
cmd->orig_fe_lun, 0x2C,
ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
CMD_TFO(cmd)->queue_status(cmd);
goto check_stop;
case PYX_TRANSPORT_USE_SENSE_REASON:
/*
* struct se_cmd->scsi_sense_reason already set
*/
break;
default:
printk(KERN_ERR "Unknown transport error for CDB 0x%02x: %d\n",
T_TASK(cmd)->t_task_cdb[0],
cmd->transport_error_status);
cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
break;
}
if (!sc)
transport_new_cmd_failure(cmd);
else
transport_send_check_condition_and_sense(cmd,
cmd->scsi_sense_reason, 0);
check_stop:
transport_lun_remove_cmd(cmd);
if (!(transport_cmd_check_stop_to_fabric(cmd)))
;
}
static void transport_direct_request_timeout(struct se_cmd *cmd)
{
unsigned long flags;
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
if (!(atomic_read(&T_TASK(cmd)->t_transport_timeout))) {
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
return;
}
if (atomic_read(&T_TASK(cmd)->t_task_cdbs_timeout_left)) {
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
return;
}
atomic_sub(atomic_read(&T_TASK(cmd)->t_transport_timeout),
&T_TASK(cmd)->t_se_count);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
}
static void transport_generic_request_timeout(struct se_cmd *cmd)
{
unsigned long flags;
/*
* Reset T_TASK(cmd)->t_se_count to allow transport_generic_remove()
* to allow last call to free memory resources.
*/
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
if (atomic_read(&T_TASK(cmd)->t_transport_timeout) > 1) {
int tmp = (atomic_read(&T_TASK(cmd)->t_transport_timeout) - 1);
atomic_sub(tmp, &T_TASK(cmd)->t_se_count);
}
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
transport_generic_remove(cmd, 0, 0);
}
static int
transport_generic_allocate_buf(struct se_cmd *cmd, u32 data_length)
{
unsigned char *buf;
buf = kzalloc(data_length, GFP_KERNEL);
if (!(buf)) {
printk(KERN_ERR "Unable to allocate memory for buffer\n");
return -1;
}
T_TASK(cmd)->t_tasks_se_num = 0;
T_TASK(cmd)->t_task_buf = buf;
return 0;
}
static inline u32 transport_lba_21(unsigned char *cdb)
{
return ((cdb[1] & 0x1f) << 16) | (cdb[2] << 8) | cdb[3];
}
static inline u32 transport_lba_32(unsigned char *cdb)
{
return (cdb[2] << 24) | (cdb[3] << 16) | (cdb[4] << 8) | cdb[5];
}
static inline unsigned long long transport_lba_64(unsigned char *cdb)
{
unsigned int __v1, __v2;
__v1 = (cdb[2] << 24) | (cdb[3] << 16) | (cdb[4] << 8) | cdb[5];
__v2 = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
return ((unsigned long long)__v2) | (unsigned long long)__v1 << 32;
}
/*
* For VARIABLE_LENGTH_CDB w/ 32 byte extended CDBs
*/
static inline unsigned long long transport_lba_64_ext(unsigned char *cdb)
{
unsigned int __v1, __v2;
__v1 = (cdb[12] << 24) | (cdb[13] << 16) | (cdb[14] << 8) | cdb[15];
__v2 = (cdb[16] << 24) | (cdb[17] << 16) | (cdb[18] << 8) | cdb[19];
return ((unsigned long long)__v2) | (unsigned long long)__v1 << 32;
}
static void transport_set_supported_SAM_opcode(struct se_cmd *se_cmd)
{
unsigned long flags;
spin_lock_irqsave(&T_TASK(se_cmd)->t_state_lock, flags);
se_cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
spin_unlock_irqrestore(&T_TASK(se_cmd)->t_state_lock, flags);
}
/*
* Called from interrupt context.
*/
static void transport_task_timeout_handler(unsigned long data)
{
struct se_task *task = (struct se_task *)data;
struct se_cmd *cmd = TASK_CMD(task);
unsigned long flags;
DEBUG_TT("transport task timeout fired! task: %p cmd: %p\n", task, cmd);
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
if (task->task_flags & TF_STOP) {
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
return;
}
task->task_flags &= ~TF_RUNNING;
/*
* Determine if transport_complete_task() has already been called.
*/
if (!(atomic_read(&task->task_active))) {
DEBUG_TT("transport task: %p cmd: %p timeout task_active"
" == 0\n", task, cmd);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
return;
}
atomic_inc(&T_TASK(cmd)->t_se_count);
atomic_inc(&T_TASK(cmd)->t_transport_timeout);
T_TASK(cmd)->t_tasks_failed = 1;
atomic_set(&task->task_timeout, 1);
task->task_error_status = PYX_TRANSPORT_TASK_TIMEOUT;
task->task_scsi_status = 1;
if (atomic_read(&task->task_stop)) {
DEBUG_TT("transport task: %p cmd: %p timeout task_stop"
" == 1\n", task, cmd);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
complete(&task->task_stop_comp);
return;
}
if (!(atomic_dec_and_test(&T_TASK(cmd)->t_task_cdbs_left))) {
DEBUG_TT("transport task: %p cmd: %p timeout non zero"
" t_task_cdbs_left\n", task, cmd);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
return;
}
DEBUG_TT("transport task: %p cmd: %p timeout ZERO t_task_cdbs_left\n",
task, cmd);
cmd->t_state = TRANSPORT_COMPLETE_FAILURE;
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
transport_add_cmd_to_queue(cmd, TRANSPORT_COMPLETE_FAILURE);
}
/*
* Called with T_TASK(cmd)->t_state_lock held.
*/
static void transport_start_task_timer(struct se_task *task)
{
struct se_device *dev = task->se_dev;
int timeout;
if (task->task_flags & TF_RUNNING)
return;
/*
* If the task_timeout is disabled, exit now.
*/
timeout = DEV_ATTRIB(dev)->task_timeout;
if (!(timeout))
return;
init_timer(&task->task_timer);
task->task_timer.expires = (get_jiffies_64() + timeout * HZ);
task->task_timer.data = (unsigned long) task;
task->task_timer.function = transport_task_timeout_handler;
task->task_flags |= TF_RUNNING;
add_timer(&task->task_timer);
#if 0
printk(KERN_INFO "Starting task timer for cmd: %p task: %p seconds:"
" %d\n", task->task_se_cmd, task, timeout);
#endif
}
/*
* Called with spin_lock_irq(&T_TASK(cmd)->t_state_lock) held.
*/
void __transport_stop_task_timer(struct se_task *task, unsigned long *flags)
{
struct se_cmd *cmd = TASK_CMD(task);
if (!(task->task_flags & TF_RUNNING))
return;
task->task_flags |= TF_STOP;
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, *flags);
del_timer_sync(&task->task_timer);
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, *flags);
task->task_flags &= ~TF_RUNNING;
task->task_flags &= ~TF_STOP;
}
static void transport_stop_all_task_timers(struct se_cmd *cmd)
{
struct se_task *task = NULL, *task_tmp;
unsigned long flags;
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
list_for_each_entry_safe(task, task_tmp,
&T_TASK(cmd)->t_task_list, t_list)
__transport_stop_task_timer(task, &flags);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
}
static inline int transport_tcq_window_closed(struct se_device *dev)
{
if (dev->dev_tcq_window_closed++ <
PYX_TRANSPORT_WINDOW_CLOSED_THRESHOLD) {
msleep(PYX_TRANSPORT_WINDOW_CLOSED_WAIT_SHORT);
} else
msleep(PYX_TRANSPORT_WINDOW_CLOSED_WAIT_LONG);
wake_up_interruptible(&dev->dev_queue_obj->thread_wq);
return 0;
}
/*
* Called from Fabric Module context from transport_execute_tasks()
*
* The return of this function determins if the tasks from struct se_cmd
* get added to the execution queue in transport_execute_tasks(),
* or are added to the delayed or ordered lists here.
*/
static inline int transport_execute_task_attr(struct se_cmd *cmd)
{
if (SE_DEV(cmd)->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
return 1;
/*
* Check for the existence of HEAD_OF_QUEUE, and if true return 1
* to allow the passed struct se_cmd list of tasks to the front of the list.
*/
if (cmd->sam_task_attr == TASK_ATTR_HOQ) {
atomic_inc(&SE_DEV(cmd)->dev_hoq_count);
smp_mb__after_atomic_inc();
DEBUG_STA("Added HEAD_OF_QUEUE for CDB:"
" 0x%02x, se_ordered_id: %u\n",
T_TASK(cmd)->t_task_cdb[0],
cmd->se_ordered_id);
return 1;
} else if (cmd->sam_task_attr == TASK_ATTR_ORDERED) {
spin_lock(&SE_DEV(cmd)->ordered_cmd_lock);
list_add_tail(&cmd->se_ordered_list,
&SE_DEV(cmd)->ordered_cmd_list);
spin_unlock(&SE_DEV(cmd)->ordered_cmd_lock);
atomic_inc(&SE_DEV(cmd)->dev_ordered_sync);
smp_mb__after_atomic_inc();
DEBUG_STA("Added ORDERED for CDB: 0x%02x to ordered"
" list, se_ordered_id: %u\n",
T_TASK(cmd)->t_task_cdb[0],
cmd->se_ordered_id);
/*
* Add ORDERED command to tail of execution queue if
* no other older commands exist that need to be
* completed first.
*/
if (!(atomic_read(&SE_DEV(cmd)->simple_cmds)))
return 1;
} else {
/*
* For SIMPLE and UNTAGGED Task Attribute commands
*/
atomic_inc(&SE_DEV(cmd)->simple_cmds);
smp_mb__after_atomic_inc();
}
/*
* Otherwise if one or more outstanding ORDERED task attribute exist,
* add the dormant task(s) built for the passed struct se_cmd to the
* execution queue and become in Active state for this struct se_device.
*/
if (atomic_read(&SE_DEV(cmd)->dev_ordered_sync) != 0) {
/*
* Otherwise, add cmd w/ tasks to delayed cmd queue that
* will be drained upon completion of HEAD_OF_QUEUE task.
*/
spin_lock(&SE_DEV(cmd)->delayed_cmd_lock);
cmd->se_cmd_flags |= SCF_DELAYED_CMD_FROM_SAM_ATTR;
list_add_tail(&cmd->se_delayed_list,
&SE_DEV(cmd)->delayed_cmd_list);
spin_unlock(&SE_DEV(cmd)->delayed_cmd_lock);
DEBUG_STA("Added CDB: 0x%02x Task Attr: 0x%02x to"
" delayed CMD list, se_ordered_id: %u\n",
T_TASK(cmd)->t_task_cdb[0], cmd->sam_task_attr,
cmd->se_ordered_id);
/*
* Return zero to let transport_execute_tasks() know
* not to add the delayed tasks to the execution list.
*/
return 0;
}
/*
* Otherwise, no ORDERED task attributes exist..
*/
return 1;
}
/*
* Called from fabric module context in transport_generic_new_cmd() and
* transport_generic_process_write()
*/
static int transport_execute_tasks(struct se_cmd *cmd)
{
int add_tasks;
if (!(cmd->se_cmd_flags & SCF_SE_DISABLE_ONLINE_CHECK)) {
if (se_dev_check_online(cmd->se_orig_obj_ptr) != 0) {
cmd->transport_error_status =
PYX_TRANSPORT_LU_COMM_FAILURE;
transport_generic_request_failure(cmd, NULL, 0, 1);
return 0;
}
}
/*
* Call transport_cmd_check_stop() to see if a fabric exception
* has occurred that prevents execution.
*/
if (!(transport_cmd_check_stop(cmd, 0, TRANSPORT_PROCESSING))) {
/*
* Check for SAM Task Attribute emulation and HEAD_OF_QUEUE
* attribute for the tasks of the received struct se_cmd CDB
*/
add_tasks = transport_execute_task_attr(cmd);
if (add_tasks == 0)
goto execute_tasks;
/*
* This calls transport_add_tasks_from_cmd() to handle
* HEAD_OF_QUEUE ordering for SAM Task Attribute emulation
* (if enabled) in __transport_add_task_to_execute_queue() and
* transport_add_task_check_sam_attr().
*/
transport_add_tasks_from_cmd(cmd);
}
/*
* Kick the execution queue for the cmd associated struct se_device
* storage object.
*/
execute_tasks:
__transport_execute_tasks(SE_DEV(cmd));
return 0;
}
/*
* Called to check struct se_device tcq depth window, and once open pull struct se_task
* from struct se_device->execute_task_list and
*
* Called from transport_processing_thread()
*/
static int __transport_execute_tasks(struct se_device *dev)
{
int error;
struct se_cmd *cmd = NULL;
struct se_task *task;
unsigned long flags;
/*
* Check if there is enough room in the device and HBA queue to send
* struct se_transport_task's to the selected transport.
*/
check_depth:
spin_lock_irqsave(&SE_HBA(dev)->hba_queue_lock, flags);
if (!(atomic_read(&dev->depth_left)) ||
!(atomic_read(&SE_HBA(dev)->left_queue_depth))) {
spin_unlock_irqrestore(&SE_HBA(dev)->hba_queue_lock, flags);
return transport_tcq_window_closed(dev);
}
dev->dev_tcq_window_closed = 0;
spin_lock(&dev->execute_task_lock);
task = transport_get_task_from_execute_queue(dev);
spin_unlock(&dev->execute_task_lock);
if (!task) {
spin_unlock_irqrestore(&SE_HBA(dev)->hba_queue_lock, flags);
return 0;
}
atomic_dec(&dev->depth_left);
atomic_dec(&SE_HBA(dev)->left_queue_depth);
spin_unlock_irqrestore(&SE_HBA(dev)->hba_queue_lock, flags);
cmd = TASK_CMD(task);
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
atomic_set(&task->task_active, 1);
atomic_set(&task->task_sent, 1);
atomic_inc(&T_TASK(cmd)->t_task_cdbs_sent);
if (atomic_read(&T_TASK(cmd)->t_task_cdbs_sent) ==
T_TASK(cmd)->t_task_cdbs)
atomic_set(&cmd->transport_sent, 1);
transport_start_task_timer(task);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
/*
* The struct se_cmd->transport_emulate_cdb() function pointer is used
* to grab REPORT_LUNS CDBs before they hit the
* struct se_subsystem_api->do_task() caller below.
*/
if (cmd->transport_emulate_cdb) {
error = cmd->transport_emulate_cdb(cmd);
if (error != 0) {
cmd->transport_error_status = error;
atomic_set(&task->task_active, 0);
atomic_set(&cmd->transport_sent, 0);
transport_stop_tasks_for_cmd(cmd);
transport_generic_request_failure(cmd, dev, 0, 1);
goto check_depth;
}
/*
* Handle the successful completion for transport_emulate_cdb()
* for synchronous operation, following SCF_EMULATE_CDB_ASYNC
* Otherwise the caller is expected to complete the task with
* proper status.
*/
if (!(cmd->se_cmd_flags & SCF_EMULATE_CDB_ASYNC)) {
cmd->scsi_status = SAM_STAT_GOOD;
task->task_scsi_status = GOOD;
transport_complete_task(task, 1);
}
} else {
/*
* Currently for all virtual TCM plugins including IBLOCK, FILEIO and
* RAMDISK we use the internal transport_emulate_control_cdb() logic
* with struct se_subsystem_api callers for the primary SPC-3 TYPE_DISK
* LUN emulation code.
*
* For TCM/pSCSI and all other SCF_SCSI_DATA_SG_IO_CDB I/O tasks we
* call ->do_task() directly and let the underlying TCM subsystem plugin
* code handle the CDB emulation.
*/
if ((TRANSPORT(dev)->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV) &&
(!(TASK_CMD(task)->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB)))
error = transport_emulate_control_cdb(task);
else
error = TRANSPORT(dev)->do_task(task);
if (error != 0) {
cmd->transport_error_status = error;
atomic_set(&task->task_active, 0);
atomic_set(&cmd->transport_sent, 0);
transport_stop_tasks_for_cmd(cmd);
transport_generic_request_failure(cmd, dev, 0, 1);
}
}
goto check_depth;
return 0;
}
void transport_new_cmd_failure(struct se_cmd *se_cmd)
{
unsigned long flags;
/*
* Any unsolicited data will get dumped for failed command inside of
* the fabric plugin
*/
spin_lock_irqsave(&T_TASK(se_cmd)->t_state_lock, flags);
se_cmd->se_cmd_flags |= SCF_SE_CMD_FAILED;
se_cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
spin_unlock_irqrestore(&T_TASK(se_cmd)->t_state_lock, flags);
CMD_TFO(se_cmd)->new_cmd_failure(se_cmd);
}
static void transport_nop_wait_for_tasks(struct se_cmd *, int, int);
static inline u32 transport_get_sectors_6(
unsigned char *cdb,
struct se_cmd *cmd,
int *ret)
{
struct se_device *dev = SE_LUN(cmd)->lun_se_dev;
/*
* Assume TYPE_DISK for non struct se_device objects.
* Use 8-bit sector value.
*/
if (!dev)
goto type_disk;
/*
* Use 24-bit allocation length for TYPE_TAPE.
*/
if (TRANSPORT(dev)->get_device_type(dev) == TYPE_TAPE)
return (u32)(cdb[2] << 16) + (cdb[3] << 8) + cdb[4];
/*
* Everything else assume TYPE_DISK Sector CDB location.
* Use 8-bit sector value.
*/
type_disk:
return (u32)cdb[4];
}
static inline u32 transport_get_sectors_10(
unsigned char *cdb,
struct se_cmd *cmd,
int *ret)
{
struct se_device *dev = SE_LUN(cmd)->lun_se_dev;
/*
* Assume TYPE_DISK for non struct se_device objects.
* Use 16-bit sector value.
*/
if (!dev)
goto type_disk;
/*
* XXX_10 is not defined in SSC, throw an exception
*/
if (TRANSPORT(dev)->get_device_type(dev) == TYPE_TAPE) {
*ret = -1;
return 0;
}
/*
* Everything else assume TYPE_DISK Sector CDB location.
* Use 16-bit sector value.
*/
type_disk:
return (u32)(cdb[7] << 8) + cdb[8];
}
static inline u32 transport_get_sectors_12(
unsigned char *cdb,
struct se_cmd *cmd,
int *ret)
{
struct se_device *dev = SE_LUN(cmd)->lun_se_dev;
/*
* Assume TYPE_DISK for non struct se_device objects.
* Use 32-bit sector value.
*/
if (!dev)
goto type_disk;
/*
* XXX_12 is not defined in SSC, throw an exception
*/
if (TRANSPORT(dev)->get_device_type(dev) == TYPE_TAPE) {
*ret = -1;
return 0;
}
/*
* Everything else assume TYPE_DISK Sector CDB location.
* Use 32-bit sector value.
*/
type_disk:
return (u32)(cdb[6] << 24) + (cdb[7] << 16) + (cdb[8] << 8) + cdb[9];
}
static inline u32 transport_get_sectors_16(
unsigned char *cdb,
struct se_cmd *cmd,
int *ret)
{
struct se_device *dev = SE_LUN(cmd)->lun_se_dev;
/*
* Assume TYPE_DISK for non struct se_device objects.
* Use 32-bit sector value.
*/
if (!dev)
goto type_disk;
/*
* Use 24-bit allocation length for TYPE_TAPE.
*/
if (TRANSPORT(dev)->get_device_type(dev) == TYPE_TAPE)
return (u32)(cdb[12] << 16) + (cdb[13] << 8) + cdb[14];
type_disk:
return (u32)(cdb[10] << 24) + (cdb[11] << 16) +
(cdb[12] << 8) + cdb[13];
}
/*
* Used for VARIABLE_LENGTH_CDB WRITE_32 and READ_32 variants
*/
static inline u32 transport_get_sectors_32(
unsigned char *cdb,
struct se_cmd *cmd,
int *ret)
{
/*
* Assume TYPE_DISK for non struct se_device objects.
* Use 32-bit sector value.
*/
return (u32)(cdb[28] << 24) + (cdb[29] << 16) +
(cdb[30] << 8) + cdb[31];
}
static inline u32 transport_get_size(
u32 sectors,
unsigned char *cdb,
struct se_cmd *cmd)
{
struct se_device *dev = SE_DEV(cmd);
if (TRANSPORT(dev)->get_device_type(dev) == TYPE_TAPE) {
if (cdb[1] & 1) { /* sectors */
return DEV_ATTRIB(dev)->block_size * sectors;
} else /* bytes */
return sectors;
}
#if 0
printk(KERN_INFO "Returning block_size: %u, sectors: %u == %u for"
" %s object\n", DEV_ATTRIB(dev)->block_size, sectors,
DEV_ATTRIB(dev)->block_size * sectors,
TRANSPORT(dev)->name);
#endif
return DEV_ATTRIB(dev)->block_size * sectors;
}
unsigned char transport_asciihex_to_binaryhex(unsigned char val[2])
{
unsigned char result = 0;
/*
* MSB
*/
if ((val[0] >= 'a') && (val[0] <= 'f'))
result = ((val[0] - 'a' + 10) & 0xf) << 4;
else
if ((val[0] >= 'A') && (val[0] <= 'F'))
result = ((val[0] - 'A' + 10) & 0xf) << 4;
else /* digit */
result = ((val[0] - '0') & 0xf) << 4;
/*
* LSB
*/
if ((val[1] >= 'a') && (val[1] <= 'f'))
result |= ((val[1] - 'a' + 10) & 0xf);
else
if ((val[1] >= 'A') && (val[1] <= 'F'))
result |= ((val[1] - 'A' + 10) & 0xf);
else /* digit */
result |= ((val[1] - '0') & 0xf);
return result;
}
EXPORT_SYMBOL(transport_asciihex_to_binaryhex);
static void transport_xor_callback(struct se_cmd *cmd)
{
unsigned char *buf, *addr;
struct se_mem *se_mem;
unsigned int offset;
int i;
/*
* From sbc3r22.pdf section 5.48 XDWRITEREAD (10) command
*
* 1) read the specified logical block(s);
* 2) transfer logical blocks from the data-out buffer;
* 3) XOR the logical blocks transferred from the data-out buffer with
* the logical blocks read, storing the resulting XOR data in a buffer;
* 4) if the DISABLE WRITE bit is set to zero, then write the logical
* blocks transferred from the data-out buffer; and
* 5) transfer the resulting XOR data to the data-in buffer.
*/
buf = kmalloc(cmd->data_length, GFP_KERNEL);
if (!(buf)) {
printk(KERN_ERR "Unable to allocate xor_callback buf\n");
return;
}
/*
* Copy the scatterlist WRITE buffer located at T_TASK(cmd)->t_mem_list
* into the locally allocated *buf
*/
transport_memcpy_se_mem_read_contig(cmd, buf, T_TASK(cmd)->t_mem_list);
/*
* Now perform the XOR against the BIDI read memory located at
* T_TASK(cmd)->t_mem_bidi_list
*/
offset = 0;
list_for_each_entry(se_mem, T_TASK(cmd)->t_mem_bidi_list, se_list) {
addr = (unsigned char *)kmap_atomic(se_mem->se_page, KM_USER0);
if (!(addr))
goto out;
for (i = 0; i < se_mem->se_len; i++)
*(addr + se_mem->se_off + i) ^= *(buf + offset + i);
offset += se_mem->se_len;
kunmap_atomic(addr, KM_USER0);
}
out:
kfree(buf);
}
/*
* Used to obtain Sense Data from underlying Linux/SCSI struct scsi_cmnd
*/
static int transport_get_sense_data(struct se_cmd *cmd)
{
unsigned char *buffer = cmd->sense_buffer, *sense_buffer = NULL;
struct se_device *dev;
struct se_task *task = NULL, *task_tmp;
unsigned long flags;
u32 offset = 0;
if (!SE_LUN(cmd)) {
printk(KERN_ERR "SE_LUN(cmd) is NULL\n");
return -1;
}
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
return 0;
}
list_for_each_entry_safe(task, task_tmp,
&T_TASK(cmd)->t_task_list, t_list) {
if (!task->task_sense)
continue;
dev = task->se_dev;
if (!(dev))
continue;
if (!TRANSPORT(dev)->get_sense_buffer) {
printk(KERN_ERR "TRANSPORT(dev)->get_sense_buffer"
" is NULL\n");
continue;
}
sense_buffer = TRANSPORT(dev)->get_sense_buffer(task);
if (!(sense_buffer)) {
printk(KERN_ERR "ITT[0x%08x]_TASK[%d]: Unable to locate"
" sense buffer for task with sense\n",
CMD_TFO(cmd)->get_task_tag(cmd), task->task_no);
continue;
}
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
offset = CMD_TFO(cmd)->set_fabric_sense_len(cmd,
TRANSPORT_SENSE_BUFFER);
memcpy((void *)&buffer[offset], (void *)sense_buffer,
TRANSPORT_SENSE_BUFFER);
cmd->scsi_status = task->task_scsi_status;
/* Automatically padded */
cmd->scsi_sense_length =
(TRANSPORT_SENSE_BUFFER + offset);
printk(KERN_INFO "HBA_[%u]_PLUG[%s]: Set SAM STATUS: 0x%02x"
" and sense\n",
dev->se_hba->hba_id, TRANSPORT(dev)->name,
cmd->scsi_status);
return 0;
}
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
return -1;
}
static int transport_allocate_resources(struct se_cmd *cmd)
{
u32 length = cmd->data_length;
if ((cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB) ||
(cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB))
return transport_generic_get_mem(cmd, length, PAGE_SIZE);
else if (cmd->se_cmd_flags & SCF_SCSI_CONTROL_NONSG_IO_CDB)
return transport_generic_allocate_buf(cmd, length);
else
return 0;
}
static int
transport_handle_reservation_conflict(struct se_cmd *cmd)
{
cmd->transport_wait_for_tasks = &transport_nop_wait_for_tasks;
cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
cmd->se_cmd_flags |= SCF_SCSI_RESERVATION_CONFLICT;
cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
/*
* For UA Interlock Code 11b, a RESERVATION CONFLICT will
* establish a UNIT ATTENTION with PREVIOUS RESERVATION
* CONFLICT STATUS.
*
* See spc4r17, section 7.4.6 Control Mode Page, Table 349
*/
if (SE_SESS(cmd) &&
DEV_ATTRIB(cmd->se_dev)->emulate_ua_intlck_ctrl == 2)
core_scsi3_ua_allocate(SE_SESS(cmd)->se_node_acl,
cmd->orig_fe_lun, 0x2C,
ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
return -2;
}
/* transport_generic_cmd_sequencer():
*
* Generic Command Sequencer that should work for most DAS transport
* drivers.
*
* Called from transport_generic_allocate_tasks() in the $FABRIC_MOD
* RX Thread.
*
* FIXME: Need to support other SCSI OPCODES where as well.
*/
static int transport_generic_cmd_sequencer(
struct se_cmd *cmd,
unsigned char *cdb)
{
struct se_device *dev = SE_DEV(cmd);
struct se_subsystem_dev *su_dev = dev->se_sub_dev;
int ret = 0, sector_ret = 0, passthrough;
u32 sectors = 0, size = 0, pr_reg_type = 0;
u16 service_action;
u8 alua_ascq = 0;
/*
* Check for an existing UNIT ATTENTION condition
*/
if (core_scsi3_ua_check(cmd, cdb) < 0) {
cmd->transport_wait_for_tasks =
&transport_nop_wait_for_tasks;
cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
cmd->scsi_sense_reason = TCM_CHECK_CONDITION_UNIT_ATTENTION;
return -2;
}
/*
* Check status of Asymmetric Logical Unit Assignment port
*/
ret = T10_ALUA(su_dev)->alua_state_check(cmd, cdb, &alua_ascq);
if (ret != 0) {
cmd->transport_wait_for_tasks = &transport_nop_wait_for_tasks;
/*
* Set SCSI additional sense code (ASC) to 'LUN Not Accessible';
* The ALUA additional sense code qualifier (ASCQ) is determined
* by the ALUA primary or secondary access state..
*/
if (ret > 0) {
#if 0
printk(KERN_INFO "[%s]: ALUA TG Port not available,"
" SenseKey: NOT_READY, ASC/ASCQ: 0x04/0x%02x\n",
CMD_TFO(cmd)->get_fabric_name(), alua_ascq);
#endif
transport_set_sense_codes(cmd, 0x04, alua_ascq);
cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
cmd->scsi_sense_reason = TCM_CHECK_CONDITION_NOT_READY;
return -2;
}
goto out_invalid_cdb_field;
}
/*
* Check status for SPC-3 Persistent Reservations
*/
if (T10_PR_OPS(su_dev)->t10_reservation_check(cmd, &pr_reg_type) != 0) {
if (T10_PR_OPS(su_dev)->t10_seq_non_holder(
cmd, cdb, pr_reg_type) != 0)
return transport_handle_reservation_conflict(cmd);
/*
* This means the CDB is allowed for the SCSI Initiator port
* when said port is *NOT* holding the legacy SPC-2 or
* SPC-3 Persistent Reservation.
*/
}
switch (cdb[0]) {
case READ_6:
sectors = transport_get_sectors_6(cdb, cmd, §or_ret);
if (sector_ret)
goto out_unsupported_cdb;
size = transport_get_size(sectors, cdb, cmd);
cmd->transport_split_cdb = &split_cdb_XX_6;
T_TASK(cmd)->t_task_lba = transport_lba_21(cdb);
cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
break;
case READ_10:
sectors = transport_get_sectors_10(cdb, cmd, §or_ret);
if (sector_ret)
goto out_unsupported_cdb;
size = transport_get_size(sectors, cdb, cmd);
cmd->transport_split_cdb = &split_cdb_XX_10;
T_TASK(cmd)->t_task_lba = transport_lba_32(cdb);
cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
break;
case READ_12:
sectors = transport_get_sectors_12(cdb, cmd, §or_ret);
if (sector_ret)
goto out_unsupported_cdb;
size = transport_get_size(sectors, cdb, cmd);
cmd->transport_split_cdb = &split_cdb_XX_12;
T_TASK(cmd)->t_task_lba = transport_lba_32(cdb);
cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
break;
case READ_16:
sectors = transport_get_sectors_16(cdb, cmd, §or_ret);
if (sector_ret)
goto out_unsupported_cdb;
size = transport_get_size(sectors, cdb, cmd);
cmd->transport_split_cdb = &split_cdb_XX_16;
T_TASK(cmd)->t_task_lba = transport_lba_64(cdb);
cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
break;
case WRITE_6:
sectors = transport_get_sectors_6(cdb, cmd, §or_ret);
if (sector_ret)
goto out_unsupported_cdb;
size = transport_get_size(sectors, cdb, cmd);
cmd->transport_split_cdb = &split_cdb_XX_6;
T_TASK(cmd)->t_task_lba = transport_lba_21(cdb);
cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
break;
case WRITE_10:
sectors = transport_get_sectors_10(cdb, cmd, §or_ret);
if (sector_ret)
goto out_unsupported_cdb;
size = transport_get_size(sectors, cdb, cmd);
cmd->transport_split_cdb = &split_cdb_XX_10;
T_TASK(cmd)->t_task_lba = transport_lba_32(cdb);
T_TASK(cmd)->t_tasks_fua = (cdb[1] & 0x8);
cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
break;
case WRITE_12:
sectors = transport_get_sectors_12(cdb, cmd, §or_ret);
if (sector_ret)
goto out_unsupported_cdb;
size = transport_get_size(sectors, cdb, cmd);
cmd->transport_split_cdb = &split_cdb_XX_12;
T_TASK(cmd)->t_task_lba = transport_lba_32(cdb);
T_TASK(cmd)->t_tasks_fua = (cdb[1] & 0x8);
cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
break;
case WRITE_16:
sectors = transport_get_sectors_16(cdb, cmd, §or_ret);
if (sector_ret)
goto out_unsupported_cdb;
size = transport_get_size(sectors, cdb, cmd);
cmd->transport_split_cdb = &split_cdb_XX_16;
T_TASK(cmd)->t_task_lba = transport_lba_64(cdb);
T_TASK(cmd)->t_tasks_fua = (cdb[1] & 0x8);
cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
break;
case XDWRITEREAD_10:
if ((cmd->data_direction != DMA_TO_DEVICE) ||
!(T_TASK(cmd)->t_tasks_bidi))
goto out_invalid_cdb_field;
sectors = transport_get_sectors_10(cdb, cmd, §or_ret);
if (sector_ret)
goto out_unsupported_cdb;
size = transport_get_size(sectors, cdb, cmd);
cmd->transport_split_cdb = &split_cdb_XX_10;
T_TASK(cmd)->t_task_lba = transport_lba_32(cdb);
cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
passthrough = (TRANSPORT(dev)->transport_type ==
TRANSPORT_PLUGIN_PHBA_PDEV);
/*
* Skip the remaining assignments for TCM/PSCSI passthrough
*/
if (passthrough)
break;
/*
* Setup BIDI XOR callback to be run during transport_generic_complete_ok()
*/
cmd->transport_complete_callback = &transport_xor_callback;
T_TASK(cmd)->t_tasks_fua = (cdb[1] & 0x8);
break;
case VARIABLE_LENGTH_CMD:
service_action = get_unaligned_be16(&cdb[8]);
/*
* Determine if this is TCM/PSCSI device and we should disable
* internal emulation for this CDB.
*/
passthrough = (TRANSPORT(dev)->transport_type ==
TRANSPORT_PLUGIN_PHBA_PDEV);
switch (service_action) {
case XDWRITEREAD_32:
sectors = transport_get_sectors_32(cdb, cmd, §or_ret);
if (sector_ret)
goto out_unsupported_cdb;
size = transport_get_size(sectors, cdb, cmd);
/*
* Use WRITE_32 and READ_32 opcodes for the emulated
* XDWRITE_READ_32 logic.
*/
cmd->transport_split_cdb = &split_cdb_XX_32;
T_TASK(cmd)->t_task_lba = transport_lba_64_ext(cdb);
cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
/*
* Skip the remaining assignments for TCM/PSCSI passthrough
*/
if (passthrough)
break;
/*
* Setup BIDI XOR callback to be run during
* transport_generic_complete_ok()
*/
cmd->transport_complete_callback = &transport_xor_callback;
T_TASK(cmd)->t_tasks_fua = (cdb[10] & 0x8);
break;
case WRITE_SAME_32:
sectors = transport_get_sectors_32(cdb, cmd, §or_ret);
if (sector_ret)
goto out_unsupported_cdb;
size = transport_get_size(sectors, cdb, cmd);
T_TASK(cmd)->t_task_lba = get_unaligned_be64(&cdb[12]);
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
/*
* Skip the remaining assignments for TCM/PSCSI passthrough
*/
if (passthrough)
break;
if ((cdb[10] & 0x04) || (cdb[10] & 0x02)) {
printk(KERN_ERR "WRITE_SAME PBDATA and LBDATA"
" bits not supported for Block Discard"
" Emulation\n");
goto out_invalid_cdb_field;
}
/*
* Currently for the emulated case we only accept
* tpws with the UNMAP=1 bit set.
*/
if (!(cdb[10] & 0x08)) {
printk(KERN_ERR "WRITE_SAME w/o UNMAP bit not"
" supported for Block Discard Emulation\n");
goto out_invalid_cdb_field;
}
break;
default:
printk(KERN_ERR "VARIABLE_LENGTH_CMD service action"
" 0x%04x not supported\n", service_action);
goto out_unsupported_cdb;
}
break;
case 0xa3:
if (TRANSPORT(dev)->get_device_type(dev) != TYPE_ROM) {
/* MAINTENANCE_IN from SCC-2 */
/*
* Check for emulated MI_REPORT_TARGET_PGS.
*/
if (cdb[1] == MI_REPORT_TARGET_PGS) {
cmd->transport_emulate_cdb =
(T10_ALUA(su_dev)->alua_type ==
SPC3_ALUA_EMULATED) ?
&core_emulate_report_target_port_groups :
NULL;
}
size = (cdb[6] << 24) | (cdb[7] << 16) |
(cdb[8] << 8) | cdb[9];
} else {
/* GPCMD_SEND_KEY from multi media commands */
size = (cdb[8] << 8) + cdb[9];
}
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case MODE_SELECT:
size = cdb[4];
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
break;
case MODE_SELECT_10:
size = (cdb[7] << 8) + cdb[8];
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
break;
case MODE_SENSE:
size = cdb[4];
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case MODE_SENSE_10:
case GPCMD_READ_BUFFER_CAPACITY:
case GPCMD_SEND_OPC:
case LOG_SELECT:
case LOG_SENSE:
size = (cdb[7] << 8) + cdb[8];
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case READ_BLOCK_LIMITS:
size = READ_BLOCK_LEN;
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case GPCMD_GET_CONFIGURATION:
case GPCMD_READ_FORMAT_CAPACITIES:
case GPCMD_READ_DISC_INFO:
case GPCMD_READ_TRACK_RZONE_INFO:
size = (cdb[7] << 8) + cdb[8];
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
break;
case PERSISTENT_RESERVE_IN:
case PERSISTENT_RESERVE_OUT:
cmd->transport_emulate_cdb =
(T10_RES(su_dev)->res_type ==
SPC3_PERSISTENT_RESERVATIONS) ?
&core_scsi3_emulate_pr : NULL;
size = (cdb[7] << 8) + cdb[8];
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case GPCMD_MECHANISM_STATUS:
case GPCMD_READ_DVD_STRUCTURE:
size = (cdb[8] << 8) + cdb[9];
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
break;
case READ_POSITION:
size = READ_POSITION_LEN;
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case 0xa4:
if (TRANSPORT(dev)->get_device_type(dev) != TYPE_ROM) {
/* MAINTENANCE_OUT from SCC-2
*
* Check for emulated MO_SET_TARGET_PGS.
*/
if (cdb[1] == MO_SET_TARGET_PGS) {
cmd->transport_emulate_cdb =
(T10_ALUA(su_dev)->alua_type ==
SPC3_ALUA_EMULATED) ?
&core_emulate_set_target_port_groups :
NULL;
}
size = (cdb[6] << 24) | (cdb[7] << 16) |
(cdb[8] << 8) | cdb[9];
} else {
/* GPCMD_REPORT_KEY from multi media commands */
size = (cdb[8] << 8) + cdb[9];
}
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case INQUIRY:
size = (cdb[3] << 8) + cdb[4];
/*
* Do implict HEAD_OF_QUEUE processing for INQUIRY.
* See spc4r17 section 5.3
*/
if (SE_DEV(cmd)->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
cmd->sam_task_attr = TASK_ATTR_HOQ;
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case READ_BUFFER:
size = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case READ_CAPACITY:
size = READ_CAP_LEN;
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case READ_MEDIA_SERIAL_NUMBER:
case SECURITY_PROTOCOL_IN:
case SECURITY_PROTOCOL_OUT:
size = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case SERVICE_ACTION_IN:
case ACCESS_CONTROL_IN:
case ACCESS_CONTROL_OUT:
case EXTENDED_COPY:
case READ_ATTRIBUTE:
case RECEIVE_COPY_RESULTS:
case WRITE_ATTRIBUTE:
size = (cdb[10] << 24) | (cdb[11] << 16) |
(cdb[12] << 8) | cdb[13];
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case RECEIVE_DIAGNOSTIC:
case SEND_DIAGNOSTIC:
size = (cdb[3] << 8) | cdb[4];
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
/* #warning FIXME: Figure out correct GPCMD_READ_CD blocksize. */
#if 0
case GPCMD_READ_CD:
sectors = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
size = (2336 * sectors);
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
#endif
case READ_TOC:
size = cdb[8];
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case REQUEST_SENSE:
size = cdb[4];
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case READ_ELEMENT_STATUS:
size = 65536 * cdb[7] + 256 * cdb[8] + cdb[9];
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case WRITE_BUFFER:
size = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case RESERVE:
case RESERVE_10:
/*
* The SPC-2 RESERVE does not contain a size in the SCSI CDB.
* Assume the passthrough or $FABRIC_MOD will tell us about it.
*/
if (cdb[0] == RESERVE_10)
size = (cdb[7] << 8) | cdb[8];
else
size = cmd->data_length;
/*
* Setup the legacy emulated handler for SPC-2 and
* >= SPC-3 compatible reservation handling (CRH=1)
* Otherwise, we assume the underlying SCSI logic is
* is running in SPC_PASSTHROUGH, and wants reservations
* emulation disabled.
*/
cmd->transport_emulate_cdb =
(T10_RES(su_dev)->res_type !=
SPC_PASSTHROUGH) ?
&core_scsi2_emulate_crh : NULL;
cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
break;
case RELEASE:
case RELEASE_10:
/*
* The SPC-2 RELEASE does not contain a size in the SCSI CDB.
* Assume the passthrough or $FABRIC_MOD will tell us about it.
*/
if (cdb[0] == RELEASE_10)
size = (cdb[7] << 8) | cdb[8];
else
size = cmd->data_length;
cmd->transport_emulate_cdb =
(T10_RES(su_dev)->res_type !=
SPC_PASSTHROUGH) ?
&core_scsi2_emulate_crh : NULL;
cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
break;
case SYNCHRONIZE_CACHE:
case 0x91: /* SYNCHRONIZE_CACHE_16: */
/*
* Extract LBA and range to be flushed for emulated SYNCHRONIZE_CACHE
*/
if (cdb[0] == SYNCHRONIZE_CACHE) {
sectors = transport_get_sectors_10(cdb, cmd, §or_ret);
T_TASK(cmd)->t_task_lba = transport_lba_32(cdb);
} else {
sectors = transport_get_sectors_16(cdb, cmd, §or_ret);
T_TASK(cmd)->t_task_lba = transport_lba_64(cdb);
}
if (sector_ret)
goto out_unsupported_cdb;
size = transport_get_size(sectors, cdb, cmd);
cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
/*
* For TCM/pSCSI passthrough, skip cmd->transport_emulate_cdb()
*/
if (TRANSPORT(dev)->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV)
break;
/*
* Set SCF_EMULATE_CDB_ASYNC to ensure asynchronous operation
* for SYNCHRONIZE_CACHE* Immed=1 case in __transport_execute_tasks()
*/
cmd->se_cmd_flags |= SCF_EMULATE_CDB_ASYNC;
/*
* Check to ensure that LBA + Range does not exceed past end of
* device.
*/
if (transport_get_sectors(cmd) < 0)
goto out_invalid_cdb_field;
break;
case UNMAP:
size = get_unaligned_be16(&cdb[7]);
passthrough = (TRANSPORT(dev)->transport_type ==
TRANSPORT_PLUGIN_PHBA_PDEV);
/*
* Determine if the received UNMAP used to for direct passthrough
* into Linux/SCSI with struct request via TCM/pSCSI or we are
* signaling the use of internal transport_generic_unmap() emulation
* for UNMAP -> Linux/BLOCK disbard with TCM/IBLOCK and TCM/FILEIO
* subsystem plugin backstores.
*/
if (!(passthrough))
cmd->se_cmd_flags |= SCF_EMULATE_SYNC_UNMAP;
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
case WRITE_SAME_16:
sectors = transport_get_sectors_16(cdb, cmd, §or_ret);
if (sector_ret)
goto out_unsupported_cdb;
size = transport_get_size(sectors, cdb, cmd);
T_TASK(cmd)->t_task_lba = get_unaligned_be16(&cdb[2]);
passthrough = (TRANSPORT(dev)->transport_type ==
TRANSPORT_PLUGIN_PHBA_PDEV);
/*
* Determine if the received WRITE_SAME_16 is used to for direct
* passthrough into Linux/SCSI with struct request via TCM/pSCSI
* or we are signaling the use of internal WRITE_SAME + UNMAP=1
* emulation for -> Linux/BLOCK disbard with TCM/IBLOCK and
* TCM/FILEIO subsystem plugin backstores.
*/
if (!(passthrough)) {
if ((cdb[1] & 0x04) || (cdb[1] & 0x02)) {
printk(KERN_ERR "WRITE_SAME PBDATA and LBDATA"
" bits not supported for Block Discard"
" Emulation\n");
goto out_invalid_cdb_field;
}
/*
* Currently for the emulated case we only accept
* tpws with the UNMAP=1 bit set.
*/
if (!(cdb[1] & 0x08)) {
printk(KERN_ERR "WRITE_SAME w/o UNMAP bit not "
" supported for Block Discard Emulation\n");
goto out_invalid_cdb_field;
}
}
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
break;
case ALLOW_MEDIUM_REMOVAL:
case GPCMD_CLOSE_TRACK:
case ERASE:
case INITIALIZE_ELEMENT_STATUS:
case GPCMD_LOAD_UNLOAD:
case REZERO_UNIT:
case SEEK_10:
case GPCMD_SET_SPEED:
case SPACE:
case START_STOP:
case TEST_UNIT_READY:
case VERIFY:
case WRITE_FILEMARKS:
case MOVE_MEDIUM:
cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
break;
case REPORT_LUNS:
cmd->transport_emulate_cdb =
&transport_core_report_lun_response;
size = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
/*
* Do implict HEAD_OF_QUEUE processing for REPORT_LUNS
* See spc4r17 section 5.3
*/
if (SE_DEV(cmd)->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
cmd->sam_task_attr = TASK_ATTR_HOQ;
cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
break;
default:
printk(KERN_WARNING "TARGET_CORE[%s]: Unsupported SCSI Opcode"
" 0x%02x, sending CHECK_CONDITION.\n",
CMD_TFO(cmd)->get_fabric_name(), cdb[0]);
cmd->transport_wait_for_tasks = &transport_nop_wait_for_tasks;
goto out_unsupported_cdb;
}
if (size != cmd->data_length) {
printk(KERN_WARNING "TARGET_CORE[%s]: Expected Transfer Length:"
" %u does not match SCSI CDB Length: %u for SAM Opcode:"
" 0x%02x\n", CMD_TFO(cmd)->get_fabric_name(),
cmd->data_length, size, cdb[0]);
cmd->cmd_spdtl = size;
if (cmd->data_direction == DMA_TO_DEVICE) {
printk(KERN_ERR "Rejecting underflow/overflow"
" WRITE data\n");
goto out_invalid_cdb_field;
}
/*
* Reject READ_* or WRITE_* with overflow/underflow for
* type SCF_SCSI_DATA_SG_IO_CDB.
*/
if (!(ret) && (DEV_ATTRIB(dev)->block_size != 512)) {
printk(KERN_ERR "Failing OVERFLOW/UNDERFLOW for LBA op"
" CDB on non 512-byte sector setup subsystem"
" plugin: %s\n", TRANSPORT(dev)->name);
/* Returns CHECK_CONDITION + INVALID_CDB_FIELD */
goto out_invalid_cdb_field;
}
if (size > cmd->data_length) {
cmd->se_cmd_flags |= SCF_OVERFLOW_BIT;
cmd->residual_count = (size - cmd->data_length);
} else {
cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
cmd->residual_count = (cmd->data_length - size);
}
cmd->data_length = size;
}
transport_set_supported_SAM_opcode(cmd);
return ret;
out_unsupported_cdb:
cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
return -2;
out_invalid_cdb_field:
cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
return -2;
}
static inline void transport_release_tasks(struct se_cmd *);
/*
* This function will copy a contiguous *src buffer into a destination
* struct scatterlist array.
*/
static void transport_memcpy_write_contig(
struct se_cmd *cmd,
struct scatterlist *sg_d,
unsigned char *src)
{
u32 i = 0, length = 0, total_length = cmd->data_length;
void *dst;
while (total_length) {
length = sg_d[i].length;
if (length > total_length)
length = total_length;
dst = sg_virt(&sg_d[i]);
memcpy(dst, src, length);
if (!(total_length -= length))
return;
src += length;
i++;
}
}
/*
* This function will copy a struct scatterlist array *sg_s into a destination
* contiguous *dst buffer.
*/
static void transport_memcpy_read_contig(
struct se_cmd *cmd,
unsigned char *dst,
struct scatterlist *sg_s)
{
u32 i = 0, length = 0, total_length = cmd->data_length;
void *src;
while (total_length) {
length = sg_s[i].length;
if (length > total_length)
length = total_length;
src = sg_virt(&sg_s[i]);
memcpy(dst, src, length);
if (!(total_length -= length))
return;
dst += length;
i++;
}
}
static void transport_memcpy_se_mem_read_contig(
struct se_cmd *cmd,
unsigned char *dst,
struct list_head *se_mem_list)
{
struct se_mem *se_mem;
void *src;
u32 length = 0, total_length = cmd->data_length;
list_for_each_entry(se_mem, se_mem_list, se_list) {
length = se_mem->se_len;
if (length > total_length)
length = total_length;
src = page_address(se_mem->se_page) + se_mem->se_off;
memcpy(dst, src, length);
if (!(total_length -= length))
return;
dst += length;
}
}
/*
* Called from transport_generic_complete_ok() and
* transport_generic_request_failure() to determine which dormant/delayed
* and ordered cmds need to have their tasks added to the execution queue.
*/
static void transport_complete_task_attr(struct se_cmd *cmd)
{
struct se_device *dev = SE_DEV(cmd);
struct se_cmd *cmd_p, *cmd_tmp;
int new_active_tasks = 0;
if (cmd->sam_task_attr == TASK_ATTR_SIMPLE) {
atomic_dec(&dev->simple_cmds);
smp_mb__after_atomic_dec();
dev->dev_cur_ordered_id++;
DEBUG_STA("Incremented dev->dev_cur_ordered_id: %u for"
" SIMPLE: %u\n", dev->dev_cur_ordered_id,
cmd->se_ordered_id);
} else if (cmd->sam_task_attr == TASK_ATTR_HOQ) {
atomic_dec(&dev->dev_hoq_count);
smp_mb__after_atomic_dec();
dev->dev_cur_ordered_id++;
DEBUG_STA("Incremented dev_cur_ordered_id: %u for"
" HEAD_OF_QUEUE: %u\n", dev->dev_cur_ordered_id,
cmd->se_ordered_id);
} else if (cmd->sam_task_attr == TASK_ATTR_ORDERED) {
spin_lock(&dev->ordered_cmd_lock);
list_del(&cmd->se_ordered_list);
atomic_dec(&dev->dev_ordered_sync);
smp_mb__after_atomic_dec();
spin_unlock(&dev->ordered_cmd_lock);
dev->dev_cur_ordered_id++;
DEBUG_STA("Incremented dev_cur_ordered_id: %u for ORDERED:"
" %u\n", dev->dev_cur_ordered_id, cmd->se_ordered_id);
}
/*
* Process all commands up to the last received
* ORDERED task attribute which requires another blocking
* boundary
*/
spin_lock(&dev->delayed_cmd_lock);
list_for_each_entry_safe(cmd_p, cmd_tmp,
&dev->delayed_cmd_list, se_delayed_list) {
list_del(&cmd_p->se_delayed_list);
spin_unlock(&dev->delayed_cmd_lock);
DEBUG_STA("Calling add_tasks() for"
" cmd_p: 0x%02x Task Attr: 0x%02x"
" Dormant -> Active, se_ordered_id: %u\n",
T_TASK(cmd_p)->t_task_cdb[0],
cmd_p->sam_task_attr, cmd_p->se_ordered_id);
transport_add_tasks_from_cmd(cmd_p);
new_active_tasks++;
spin_lock(&dev->delayed_cmd_lock);
if (cmd_p->sam_task_attr == TASK_ATTR_ORDERED)
break;
}
spin_unlock(&dev->delayed_cmd_lock);
/*
* If new tasks have become active, wake up the transport thread
* to do the processing of the Active tasks.
*/
if (new_active_tasks != 0)
wake_up_interruptible(&dev->dev_queue_obj->thread_wq);
}
static void transport_generic_complete_ok(struct se_cmd *cmd)
{
int reason = 0;
/*
* Check if we need to move delayed/dormant tasks from cmds on the
* delayed execution list after a HEAD_OF_QUEUE or ORDERED Task
* Attribute.
*/
if (SE_DEV(cmd)->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
transport_complete_task_attr(cmd);
/*
* Check if we need to retrieve a sense buffer from
* the struct se_cmd in question.
*/
if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
if (transport_get_sense_data(cmd) < 0)
reason = TCM_NON_EXISTENT_LUN;
/*
* Only set when an struct se_task->task_scsi_status returned
* a non GOOD status.
*/
if (cmd->scsi_status) {
transport_send_check_condition_and_sense(
cmd, reason, 1);
transport_lun_remove_cmd(cmd);
transport_cmd_check_stop_to_fabric(cmd);
return;
}
}
/*
* Check for a callback, used by amongst other things
* XDWRITE_READ_10 emulation.
*/
if (cmd->transport_complete_callback)
cmd->transport_complete_callback(cmd);
switch (cmd->data_direction) {
case DMA_FROM_DEVICE:
spin_lock(&cmd->se_lun->lun_sep_lock);
if (SE_LUN(cmd)->lun_sep) {
SE_LUN(cmd)->lun_sep->sep_stats.tx_data_octets +=
cmd->data_length;
}
spin_unlock(&cmd->se_lun->lun_sep_lock);
/*
* If enabled by TCM fabirc module pre-registered SGL
* memory, perform the memcpy() from the TCM internal
* contigious buffer back to the original SGL.
*/
if (cmd->se_cmd_flags & SCF_PASSTHROUGH_CONTIG_TO_SG)
transport_memcpy_write_contig(cmd,
T_TASK(cmd)->t_task_pt_sgl,
T_TASK(cmd)->t_task_buf);
CMD_TFO(cmd)->queue_data_in(cmd);
break;
case DMA_TO_DEVICE:
spin_lock(&cmd->se_lun->lun_sep_lock);
if (SE_LUN(cmd)->lun_sep) {
SE_LUN(cmd)->lun_sep->sep_stats.rx_data_octets +=
cmd->data_length;
}
spin_unlock(&cmd->se_lun->lun_sep_lock);
/*
* Check if we need to send READ payload for BIDI-COMMAND
*/
if (T_TASK(cmd)->t_mem_bidi_list != NULL) {
spin_lock(&cmd->se_lun->lun_sep_lock);
if (SE_LUN(cmd)->lun_sep) {
SE_LUN(cmd)->lun_sep->sep_stats.tx_data_octets +=
cmd->data_length;
}
spin_unlock(&cmd->se_lun->lun_sep_lock);
CMD_TFO(cmd)->queue_data_in(cmd);
break;
}
/* Fall through for DMA_TO_DEVICE */
case DMA_NONE:
CMD_TFO(cmd)->queue_status(cmd);
break;
default:
break;
}
transport_lun_remove_cmd(cmd);
transport_cmd_check_stop_to_fabric(cmd);
}
static void transport_free_dev_tasks(struct se_cmd *cmd)
{
struct se_task *task, *task_tmp;
unsigned long flags;
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
list_for_each_entry_safe(task, task_tmp,
&T_TASK(cmd)->t_task_list, t_list) {
if (atomic_read(&task->task_active))
continue;
kfree(task->task_sg_bidi);
kfree(task->task_sg);
list_del(&task->t_list);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
if (task->se_dev)
TRANSPORT(task->se_dev)->free_task(task);
else
printk(KERN_ERR "task[%u] - task->se_dev is NULL\n",
task->task_no);
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
}
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
}
static inline void transport_free_pages(struct se_cmd *cmd)
{
struct se_mem *se_mem, *se_mem_tmp;
int free_page = 1;
if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC)
free_page = 0;
if (cmd->se_dev->transport->do_se_mem_map)
free_page = 0;
if (T_TASK(cmd)->t_task_buf) {
kfree(T_TASK(cmd)->t_task_buf);
T_TASK(cmd)->t_task_buf = NULL;
return;
}
/*
* Caller will handle releasing of struct se_mem.
*/
if (cmd->se_cmd_flags & SCF_CMD_PASSTHROUGH_NOALLOC)
return;
if (!(T_TASK(cmd)->t_tasks_se_num))
return;
list_for_each_entry_safe(se_mem, se_mem_tmp,
T_TASK(cmd)->t_mem_list, se_list) {
/*
* We only release call __free_page(struct se_mem->se_page) when
* SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC is NOT in use,
*/
if (free_page)
__free_page(se_mem->se_page);
list_del(&se_mem->se_list);
kmem_cache_free(se_mem_cache, se_mem);
}
if (T_TASK(cmd)->t_mem_bidi_list && T_TASK(cmd)->t_tasks_se_bidi_num) {
list_for_each_entry_safe(se_mem, se_mem_tmp,
T_TASK(cmd)->t_mem_bidi_list, se_list) {
/*
* We only release call __free_page(struct se_mem->se_page) when
* SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC is NOT in use,
*/
if (free_page)
__free_page(se_mem->se_page);
list_del(&se_mem->se_list);
kmem_cache_free(se_mem_cache, se_mem);
}
}
kfree(T_TASK(cmd)->t_mem_bidi_list);
T_TASK(cmd)->t_mem_bidi_list = NULL;
kfree(T_TASK(cmd)->t_mem_list);
T_TASK(cmd)->t_mem_list = NULL;
T_TASK(cmd)->t_tasks_se_num = 0;
}
static inline void transport_release_tasks(struct se_cmd *cmd)
{
transport_free_dev_tasks(cmd);
}
static inline int transport_dec_and_check(struct se_cmd *cmd)
{
unsigned long flags;
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
if (atomic_read(&T_TASK(cmd)->t_fe_count)) {
if (!(atomic_dec_and_test(&T_TASK(cmd)->t_fe_count))) {
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock,
flags);
return 1;
}
}
if (atomic_read(&T_TASK(cmd)->t_se_count)) {
if (!(atomic_dec_and_test(&T_TASK(cmd)->t_se_count))) {
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock,
flags);
return 1;
}
}
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
return 0;
}
static void transport_release_fe_cmd(struct se_cmd *cmd)
{
unsigned long flags;
if (transport_dec_and_check(cmd))
return;
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
if (!(atomic_read(&T_TASK(cmd)->transport_dev_active))) {
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
goto free_pages;
}
atomic_set(&T_TASK(cmd)->transport_dev_active, 0);
transport_all_task_dev_remove_state(cmd);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
transport_release_tasks(cmd);
free_pages:
transport_free_pages(cmd);
transport_free_se_cmd(cmd);
CMD_TFO(cmd)->release_cmd_direct(cmd);
}
static int transport_generic_remove(
struct se_cmd *cmd,
int release_to_pool,
int session_reinstatement)
{
unsigned long flags;
if (!(T_TASK(cmd)))
goto release_cmd;
if (transport_dec_and_check(cmd)) {
if (session_reinstatement) {
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
transport_all_task_dev_remove_state(cmd);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock,
flags);
}
return 1;
}
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
if (!(atomic_read(&T_TASK(cmd)->transport_dev_active))) {
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
goto free_pages;
}
atomic_set(&T_TASK(cmd)->transport_dev_active, 0);
transport_all_task_dev_remove_state(cmd);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
transport_release_tasks(cmd);
free_pages:
transport_free_pages(cmd);
release_cmd:
if (release_to_pool) {
transport_release_cmd_to_pool(cmd);
} else {
transport_free_se_cmd(cmd);
CMD_TFO(cmd)->release_cmd_direct(cmd);
}
return 0;
}
/*
* transport_generic_map_mem_to_cmd - Perform SGL -> struct se_mem map
* @cmd: Associated se_cmd descriptor
* @mem: SGL style memory for TCM WRITE / READ
* @sg_mem_num: Number of SGL elements
* @mem_bidi_in: SGL style memory for TCM BIDI READ
* @sg_mem_bidi_num: Number of BIDI READ SGL elements
*
* Return: nonzero return cmd was rejected for -ENOMEM or inproper usage
* of parameters.
*/
int transport_generic_map_mem_to_cmd(
struct se_cmd *cmd,
struct scatterlist *mem,
u32 sg_mem_num,
struct scatterlist *mem_bidi_in,
u32 sg_mem_bidi_num)
{
u32 se_mem_cnt_out = 0;
int ret;
if (!(mem) || !(sg_mem_num))
return 0;
/*
* Passed *mem will contain a list_head containing preformatted
* struct se_mem elements...
*/
if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM)) {
if ((mem_bidi_in) || (sg_mem_bidi_num)) {
printk(KERN_ERR "SCF_CMD_PASSTHROUGH_NOALLOC not supported"
" with BIDI-COMMAND\n");
return -ENOSYS;
}
T_TASK(cmd)->t_mem_list = (struct list_head *)mem;
T_TASK(cmd)->t_tasks_se_num = sg_mem_num;
cmd->se_cmd_flags |= SCF_CMD_PASSTHROUGH_NOALLOC;
return 0;
}
/*
* Otherwise, assume the caller is passing a struct scatterlist
* array from include/linux/scatterlist.h
*/
if ((cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB) ||
(cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB)) {
/*
* For CDB using TCM struct se_mem linked list scatterlist memory
* processed into a TCM struct se_subsystem_dev, we do the mapping
* from the passed physical memory to struct se_mem->se_page here.
*/
T_TASK(cmd)->t_mem_list = transport_init_se_mem_list();
if (!(T_TASK(cmd)->t_mem_list))
return -ENOMEM;
ret = transport_map_sg_to_mem(cmd,
T_TASK(cmd)->t_mem_list, mem, &se_mem_cnt_out);
if (ret < 0)
return -ENOMEM;
T_TASK(cmd)->t_tasks_se_num = se_mem_cnt_out;
/*
* Setup BIDI READ list of struct se_mem elements
*/
if ((mem_bidi_in) && (sg_mem_bidi_num)) {
T_TASK(cmd)->t_mem_bidi_list = transport_init_se_mem_list();
if (!(T_TASK(cmd)->t_mem_bidi_list)) {
kfree(T_TASK(cmd)->t_mem_list);
return -ENOMEM;
}
se_mem_cnt_out = 0;
ret = transport_map_sg_to_mem(cmd,
T_TASK(cmd)->t_mem_bidi_list, mem_bidi_in,
&se_mem_cnt_out);
if (ret < 0) {
kfree(T_TASK(cmd)->t_mem_list);
return -ENOMEM;
}
T_TASK(cmd)->t_tasks_se_bidi_num = se_mem_cnt_out;
}
cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
} else if (cmd->se_cmd_flags & SCF_SCSI_CONTROL_NONSG_IO_CDB) {
if (mem_bidi_in || sg_mem_bidi_num) {
printk(KERN_ERR "BIDI-Commands not supported using "
"SCF_SCSI_CONTROL_NONSG_IO_CDB\n");
return -ENOSYS;
}
/*
* For incoming CDBs using a contiguous buffer internall with TCM,
* save the passed struct scatterlist memory. After TCM storage object
* processing has completed for this struct se_cmd, TCM core will call
* transport_memcpy_[write,read]_contig() as necessary from
* transport_generic_complete_ok() and transport_write_pending() in order
* to copy the TCM buffer to/from the original passed *mem in SGL ->
* struct scatterlist format.
*/
cmd->se_cmd_flags |= SCF_PASSTHROUGH_CONTIG_TO_SG;
T_TASK(cmd)->t_task_pt_sgl = mem;
}
return 0;
}
EXPORT_SYMBOL(transport_generic_map_mem_to_cmd);
static inline long long transport_dev_end_lba(struct se_device *dev)
{
return dev->transport->get_blocks(dev) + 1;
}
static int transport_get_sectors(struct se_cmd *cmd)
{
struct se_device *dev = SE_DEV(cmd);
T_TASK(cmd)->t_tasks_sectors =
(cmd->data_length / DEV_ATTRIB(dev)->block_size);
if (!(T_TASK(cmd)->t_tasks_sectors))
T_TASK(cmd)->t_tasks_sectors = 1;
if (TRANSPORT(dev)->get_device_type(dev) != TYPE_DISK)
return 0;
if ((T_TASK(cmd)->t_task_lba + T_TASK(cmd)->t_tasks_sectors) >
transport_dev_end_lba(dev)) {
printk(KERN_ERR "LBA: %llu Sectors: %u exceeds"
" transport_dev_end_lba(): %llu\n",
T_TASK(cmd)->t_task_lba, T_TASK(cmd)->t_tasks_sectors,
transport_dev_end_lba(dev));
cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
cmd->scsi_sense_reason = TCM_SECTOR_COUNT_TOO_MANY;
return PYX_TRANSPORT_REQ_TOO_MANY_SECTORS;
}
return 0;
}
static int transport_new_cmd_obj(struct se_cmd *cmd)
{
struct se_device *dev = SE_DEV(cmd);
u32 task_cdbs = 0, rc;
if (!(cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB)) {
task_cdbs++;
T_TASK(cmd)->t_task_cdbs++;
} else {
int set_counts = 1;
/*
* Setup any BIDI READ tasks and memory from
* T_TASK(cmd)->t_mem_bidi_list so the READ struct se_tasks
* are queued first for the non pSCSI passthrough case.
*/
if ((T_TASK(cmd)->t_mem_bidi_list != NULL) &&
(TRANSPORT(dev)->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV)) {
rc = transport_generic_get_cdb_count(cmd,
T_TASK(cmd)->t_task_lba,
T_TASK(cmd)->t_tasks_sectors,
DMA_FROM_DEVICE, T_TASK(cmd)->t_mem_bidi_list,
set_counts);
if (!(rc)) {
cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
cmd->scsi_sense_reason =
TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
return PYX_TRANSPORT_LU_COMM_FAILURE;
}
set_counts = 0;
}
/*
* Setup the tasks and memory from T_TASK(cmd)->t_mem_list
* Note for BIDI transfers this will contain the WRITE payload
*/
task_cdbs = transport_generic_get_cdb_count(cmd,
T_TASK(cmd)->t_task_lba,
T_TASK(cmd)->t_tasks_sectors,
cmd->data_direction, T_TASK(cmd)->t_mem_list,
set_counts);
if (!(task_cdbs)) {
cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
cmd->scsi_sense_reason =
TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
return PYX_TRANSPORT_LU_COMM_FAILURE;
}
T_TASK(cmd)->t_task_cdbs += task_cdbs;
#if 0
printk(KERN_INFO "data_length: %u, LBA: %llu t_tasks_sectors:"
" %u, t_task_cdbs: %u\n", obj_ptr, cmd->data_length,
T_TASK(cmd)->t_task_lba, T_TASK(cmd)->t_tasks_sectors,
T_TASK(cmd)->t_task_cdbs);
#endif
}
atomic_set(&T_TASK(cmd)->t_task_cdbs_left, task_cdbs);
atomic_set(&T_TASK(cmd)->t_task_cdbs_ex_left, task_cdbs);
atomic_set(&T_TASK(cmd)->t_task_cdbs_timeout_left, task_cdbs);
return 0;
}
static struct list_head *transport_init_se_mem_list(void)
{
struct list_head *se_mem_list;
se_mem_list = kzalloc(sizeof(struct list_head), GFP_KERNEL);
if (!(se_mem_list)) {
printk(KERN_ERR "Unable to allocate memory for se_mem_list\n");
return NULL;
}
INIT_LIST_HEAD(se_mem_list);
return se_mem_list;
}
static int
transport_generic_get_mem(struct se_cmd *cmd, u32 length, u32 dma_size)
{
unsigned char *buf;
struct se_mem *se_mem;
T_TASK(cmd)->t_mem_list = transport_init_se_mem_list();
if (!(T_TASK(cmd)->t_mem_list))
return -ENOMEM;
/*
* If the device uses memory mapping this is enough.
*/
if (cmd->se_dev->transport->do_se_mem_map)
return 0;
/*
* Setup BIDI-COMMAND READ list of struct se_mem elements
*/
if (T_TASK(cmd)->t_tasks_bidi) {
T_TASK(cmd)->t_mem_bidi_list = transport_init_se_mem_list();
if (!(T_TASK(cmd)->t_mem_bidi_list)) {
kfree(T_TASK(cmd)->t_mem_list);
return -ENOMEM;
}
}
while (length) {
se_mem = kmem_cache_zalloc(se_mem_cache, GFP_KERNEL);
if (!(se_mem)) {
printk(KERN_ERR "Unable to allocate struct se_mem\n");
goto out;
}
/* #warning FIXME Allocate contigous pages for struct se_mem elements */
se_mem->se_page = alloc_pages(GFP_KERNEL, 0);
if (!(se_mem->se_page)) {
printk(KERN_ERR "alloc_pages() failed\n");
goto out;
}
buf = kmap_atomic(se_mem->se_page, KM_IRQ0);
if (!(buf)) {
printk(KERN_ERR "kmap_atomic() failed\n");
goto out;
}
INIT_LIST_HEAD(&se_mem->se_list);
se_mem->se_len = (length > dma_size) ? dma_size : length;
memset(buf, 0, se_mem->se_len);
kunmap_atomic(buf, KM_IRQ0);
list_add_tail(&se_mem->se_list, T_TASK(cmd)->t_mem_list);
T_TASK(cmd)->t_tasks_se_num++;
DEBUG_MEM("Allocated struct se_mem page(%p) Length(%u)"
" Offset(%u)\n", se_mem->se_page, se_mem->se_len,
se_mem->se_off);
length -= se_mem->se_len;
}
DEBUG_MEM("Allocated total struct se_mem elements(%u)\n",
T_TASK(cmd)->t_tasks_se_num);
return 0;
out:
if (se_mem)
__free_pages(se_mem->se_page, 0);
kmem_cache_free(se_mem_cache, se_mem);
return -1;
}
u32 transport_calc_sg_num(
struct se_task *task,
struct se_mem *in_se_mem,
u32 task_offset)
{
struct se_cmd *se_cmd = task->task_se_cmd;
struct se_device *se_dev = SE_DEV(se_cmd);
struct se_mem *se_mem = in_se_mem;
struct target_core_fabric_ops *tfo = CMD_TFO(se_cmd);
u32 sg_length, task_size = task->task_size, task_sg_num_padded;
while (task_size != 0) {
DEBUG_SC("se_mem->se_page(%p) se_mem->se_len(%u)"
" se_mem->se_off(%u) task_offset(%u)\n",
se_mem->se_page, se_mem->se_len,
se_mem->se_off, task_offset);
if (task_offset == 0) {
if (task_size >= se_mem->se_len) {
sg_length = se_mem->se_len;
if (!(list_is_last(&se_mem->se_list,
T_TASK(se_cmd)->t_mem_list)))
se_mem = list_entry(se_mem->se_list.next,
struct se_mem, se_list);
} else {
sg_length = task_size;
task_size -= sg_length;
goto next;
}
DEBUG_SC("sg_length(%u) task_size(%u)\n",
sg_length, task_size);
} else {
if ((se_mem->se_len - task_offset) > task_size) {
sg_length = task_size;
task_size -= sg_length;
goto next;
} else {
sg_length = (se_mem->se_len - task_offset);
if (!(list_is_last(&se_mem->se_list,
T_TASK(se_cmd)->t_mem_list)))
se_mem = list_entry(se_mem->se_list.next,
struct se_mem, se_list);
}
DEBUG_SC("sg_length(%u) task_size(%u)\n",
sg_length, task_size);
task_offset = 0;
}
task_size -= sg_length;
next:
DEBUG_SC("task[%u] - Reducing task_size to(%u)\n",
task->task_no, task_size);
task->task_sg_num++;
}
/*
* Check if the fabric module driver is requesting that all
* struct se_task->task_sg[] be chained together.. If so,
* then allocate an extra padding SG entry for linking and
* marking the end of the chained SGL.
*/
if (tfo->task_sg_chaining) {
task_sg_num_padded = (task->task_sg_num + 1);
task->task_padded_sg = 1;
} else
task_sg_num_padded = task->task_sg_num;
task->task_sg = kzalloc(task_sg_num_padded *
sizeof(struct scatterlist), GFP_KERNEL);
if (!(task->task_sg)) {
printk(KERN_ERR "Unable to allocate memory for"
" task->task_sg\n");
return 0;
}
sg_init_table(&task->task_sg[0], task_sg_num_padded);
/*
* Setup task->task_sg_bidi for SCSI READ payload for
* TCM/pSCSI passthrough if present for BIDI-COMMAND
*/
if ((T_TASK(se_cmd)->t_mem_bidi_list != NULL) &&
(TRANSPORT(se_dev)->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV)) {
task->task_sg_bidi = kzalloc(task_sg_num_padded *
sizeof(struct scatterlist), GFP_KERNEL);
if (!(task->task_sg_bidi)) {
printk(KERN_ERR "Unable to allocate memory for"
" task->task_sg_bidi\n");
return 0;
}
sg_init_table(&task->task_sg_bidi[0], task_sg_num_padded);
}
/*
* For the chaining case, setup the proper end of SGL for the
* initial submission struct task into struct se_subsystem_api.
* This will be cleared later by transport_do_task_sg_chain()
*/
if (task->task_padded_sg) {
sg_mark_end(&task->task_sg[task->task_sg_num - 1]);
/*
* Added the 'if' check before marking end of bi-directional
* scatterlist (which gets created only in case of request
* (RD + WR).
*/
if (task->task_sg_bidi)
sg_mark_end(&task->task_sg_bidi[task->task_sg_num - 1]);
}
DEBUG_SC("Successfully allocated task->task_sg_num(%u),"
" task_sg_num_padded(%u)\n", task->task_sg_num,
task_sg_num_padded);
return task->task_sg_num;
}
static inline int transport_set_tasks_sectors_disk(
struct se_task *task,
struct se_device *dev,
unsigned long long lba,
u32 sectors,
int *max_sectors_set)
{
if ((lba + sectors) > transport_dev_end_lba(dev)) {
task->task_sectors = ((transport_dev_end_lba(dev) - lba) + 1);
if (task->task_sectors > DEV_ATTRIB(dev)->max_sectors) {
task->task_sectors = DEV_ATTRIB(dev)->max_sectors;
*max_sectors_set = 1;
}
} else {
if (sectors > DEV_ATTRIB(dev)->max_sectors) {
task->task_sectors = DEV_ATTRIB(dev)->max_sectors;
*max_sectors_set = 1;
} else
task->task_sectors = sectors;
}
return 0;
}
static inline int transport_set_tasks_sectors_non_disk(
struct se_task *task,
struct se_device *dev,
unsigned long long lba,
u32 sectors,
int *max_sectors_set)
{
if (sectors > DEV_ATTRIB(dev)->max_sectors) {
task->task_sectors = DEV_ATTRIB(dev)->max_sectors;
*max_sectors_set = 1;
} else
task->task_sectors = sectors;
return 0;
}
static inline int transport_set_tasks_sectors(
struct se_task *task,
struct se_device *dev,
unsigned long long lba,
u32 sectors,
int *max_sectors_set)
{
return (TRANSPORT(dev)->get_device_type(dev) == TYPE_DISK) ?
transport_set_tasks_sectors_disk(task, dev, lba, sectors,
max_sectors_set) :
transport_set_tasks_sectors_non_disk(task, dev, lba, sectors,
max_sectors_set);
}
static int transport_map_sg_to_mem(
struct se_cmd *cmd,
struct list_head *se_mem_list,
void *in_mem,
u32 *se_mem_cnt)
{
struct se_mem *se_mem;
struct scatterlist *sg;
u32 sg_count = 1, cmd_size = cmd->data_length;
if (!in_mem) {
printk(KERN_ERR "No source scatterlist\n");
return -1;
}
sg = (struct scatterlist *)in_mem;
while (cmd_size) {
se_mem = kmem_cache_zalloc(se_mem_cache, GFP_KERNEL);
if (!(se_mem)) {
printk(KERN_ERR "Unable to allocate struct se_mem\n");
return -1;
}
INIT_LIST_HEAD(&se_mem->se_list);
DEBUG_MEM("sg_to_mem: Starting loop with cmd_size: %u"
" sg_page: %p offset: %d length: %d\n", cmd_size,
sg_page(sg), sg->offset, sg->length);
se_mem->se_page = sg_page(sg);
se_mem->se_off = sg->offset;
if (cmd_size > sg->length) {
se_mem->se_len = sg->length;
sg = sg_next(sg);
sg_count++;
} else
se_mem->se_len = cmd_size;
cmd_size -= se_mem->se_len;
DEBUG_MEM("sg_to_mem: *se_mem_cnt: %u cmd_size: %u\n",
*se_mem_cnt, cmd_size);
DEBUG_MEM("sg_to_mem: Final se_page: %p se_off: %d se_len: %d\n",
se_mem->se_page, se_mem->se_off, se_mem->se_len);
list_add_tail(&se_mem->se_list, se_mem_list);
(*se_mem_cnt)++;
}
DEBUG_MEM("task[0] - Mapped(%u) struct scatterlist segments to(%u)"
" struct se_mem\n", sg_count, *se_mem_cnt);
if (sg_count != *se_mem_cnt)
BUG();
return 0;
}
/* transport_map_mem_to_sg():
*
*
*/
int transport_map_mem_to_sg(
struct se_task *task,
struct list_head *se_mem_list,
void *in_mem,
struct se_mem *in_se_mem,
struct se_mem **out_se_mem,
u32 *se_mem_cnt,
u32 *task_offset)
{
struct se_cmd *se_cmd = task->task_se_cmd;
struct se_mem *se_mem = in_se_mem;
struct scatterlist *sg = (struct scatterlist *)in_mem;
u32 task_size = task->task_size, sg_no = 0;
if (!sg) {
printk(KERN_ERR "Unable to locate valid struct"
" scatterlist pointer\n");
return -1;
}
while (task_size != 0) {
/*
* Setup the contigious array of scatterlists for
* this struct se_task.
*/
sg_assign_page(sg, se_mem->se_page);
if (*task_offset == 0) {
sg->offset = se_mem->se_off;
if (task_size >= se_mem->se_len) {
sg->length = se_mem->se_len;
if (!(list_is_last(&se_mem->se_list,
T_TASK(se_cmd)->t_mem_list))) {
se_mem = list_entry(se_mem->se_list.next,
struct se_mem, se_list);
(*se_mem_cnt)++;
}
} else {
sg->length = task_size;
/*
* Determine if we need to calculate an offset
* into the struct se_mem on the next go around..
*/
task_size -= sg->length;
if (!(task_size))
*task_offset = sg->length;
goto next;
}
} else {
sg->offset = (*task_offset + se_mem->se_off);
if ((se_mem->se_len - *task_offset) > task_size) {
sg->length = task_size;
/*
* Determine if we need to calculate an offset
* into the struct se_mem on the next go around..
*/
task_size -= sg->length;
if (!(task_size))
*task_offset += sg->length;
goto next;
} else {
sg->length = (se_mem->se_len - *task_offset);
if (!(list_is_last(&se_mem->se_list,
T_TASK(se_cmd)->t_mem_list))) {
se_mem = list_entry(se_mem->se_list.next,
struct se_mem, se_list);
(*se_mem_cnt)++;
}
}
*task_offset = 0;
}
task_size -= sg->length;
next:
DEBUG_MEM("task[%u] mem_to_sg - sg[%u](%p)(%u)(%u) - Reducing"
" task_size to(%u), task_offset: %u\n", task->task_no, sg_no,
sg_page(sg), sg->length, sg->offset, task_size, *task_offset);
sg_no++;
if (!(task_size))
break;
sg = sg_next(sg);
if (task_size > se_cmd->data_length)
BUG();
}
*out_se_mem = se_mem;
DEBUG_MEM("task[%u] - Mapped(%u) struct se_mem segments to total(%u)"
" SGs\n", task->task_no, *se_mem_cnt, sg_no);
return 0;
}
/*
* This function can be used by HW target mode drivers to create a linked
* scatterlist from all contiguously allocated struct se_task->task_sg[].
* This is intended to be called during the completion path by TCM Core
* when struct target_core_fabric_ops->check_task_sg_chaining is enabled.
*/
void transport_do_task_sg_chain(struct se_cmd *cmd)
{
struct scatterlist *sg_head = NULL, *sg_link = NULL, *sg_first = NULL;
struct scatterlist *sg_head_cur = NULL, *sg_link_cur = NULL;
struct scatterlist *sg, *sg_end = NULL, *sg_end_cur = NULL;
struct se_task *task;
struct target_core_fabric_ops *tfo = CMD_TFO(cmd);
u32 task_sg_num = 0, sg_count = 0;
int i;
if (tfo->task_sg_chaining == 0) {
printk(KERN_ERR "task_sg_chaining is diabled for fabric module:"
" %s\n", tfo->get_fabric_name());
dump_stack();
return;
}
/*
* Walk the struct se_task list and setup scatterlist chains
* for each contiguosly allocated struct se_task->task_sg[].
*/
list_for_each_entry(task, &T_TASK(cmd)->t_task_list, t_list) {
if (!(task->task_sg) || !(task->task_padded_sg))
continue;
if (sg_head && sg_link) {
sg_head_cur = &task->task_sg[0];
sg_link_cur = &task->task_sg[task->task_sg_num];
/*
* Either add chain or mark end of scatterlist
*/
if (!(list_is_last(&task->t_list,
&T_TASK(cmd)->t_task_list))) {
/*
* Clear existing SGL termination bit set in
* transport_calc_sg_num(), see sg_mark_end()
*/
sg_end_cur = &task->task_sg[task->task_sg_num - 1];
sg_end_cur->page_link &= ~0x02;
sg_chain(sg_head, task_sg_num, sg_head_cur);
sg_count += task->task_sg_num;
task_sg_num = (task->task_sg_num + 1);
} else {
sg_chain(sg_head, task_sg_num, sg_head_cur);
sg_count += task->task_sg_num;
task_sg_num = task->task_sg_num;
}
sg_head = sg_head_cur;
sg_link = sg_link_cur;
continue;
}
sg_head = sg_first = &task->task_sg[0];
sg_link = &task->task_sg[task->task_sg_num];
/*
* Check for single task..
*/
if (!(list_is_last(&task->t_list, &T_TASK(cmd)->t_task_list))) {
/*
* Clear existing SGL termination bit set in
* transport_calc_sg_num(), see sg_mark_end()
*/
sg_end = &task->task_sg[task->task_sg_num - 1];
sg_end->page_link &= ~0x02;
sg_count += task->task_sg_num;
task_sg_num = (task->task_sg_num + 1);
} else {
sg_count += task->task_sg_num;
task_sg_num = task->task_sg_num;
}
}
/*
* Setup the starting pointer and total t_tasks_sg_linked_no including
* padding SGs for linking and to mark the end.
*/
T_TASK(cmd)->t_tasks_sg_chained = sg_first;
T_TASK(cmd)->t_tasks_sg_chained_no = sg_count;
DEBUG_CMD_M("Setup cmd: %p T_TASK(cmd)->t_tasks_sg_chained: %p and"
" t_tasks_sg_chained_no: %u\n", cmd, T_TASK(cmd)->t_tasks_sg_chained,
T_TASK(cmd)->t_tasks_sg_chained_no);
for_each_sg(T_TASK(cmd)->t_tasks_sg_chained, sg,
T_TASK(cmd)->t_tasks_sg_chained_no, i) {
DEBUG_CMD_M("SG[%d]: %p page: %p length: %d offset: %d, magic: 0x%08x\n",
i, sg, sg_page(sg), sg->length, sg->offset, sg->sg_magic);
if (sg_is_chain(sg))
DEBUG_CMD_M("SG: %p sg_is_chain=1\n", sg);
if (sg_is_last(sg))
DEBUG_CMD_M("SG: %p sg_is_last=1\n", sg);
}
}
EXPORT_SYMBOL(transport_do_task_sg_chain);
static int transport_do_se_mem_map(
struct se_device *dev,
struct se_task *task,
struct list_head *se_mem_list,
void *in_mem,
struct se_mem *in_se_mem,
struct se_mem **out_se_mem,
u32 *se_mem_cnt,
u32 *task_offset_in)
{
u32 task_offset = *task_offset_in;
int ret = 0;
/*
* se_subsystem_api_t->do_se_mem_map is used when internal allocation
* has been done by the transport plugin.
*/
if (TRANSPORT(dev)->do_se_mem_map) {
ret = TRANSPORT(dev)->do_se_mem_map(task, se_mem_list,
in_mem, in_se_mem, out_se_mem, se_mem_cnt,
task_offset_in);
if (ret == 0)
T_TASK(task->task_se_cmd)->t_tasks_se_num += *se_mem_cnt;
return ret;
}
BUG_ON(list_empty(se_mem_list));
/*
* This is the normal path for all normal non BIDI and BIDI-COMMAND
* WRITE payloads.. If we need to do BIDI READ passthrough for
* TCM/pSCSI the first call to transport_do_se_mem_map ->
* transport_calc_sg_num() -> transport_map_mem_to_sg() will do the
* allocation for task->task_sg_bidi, and the subsequent call to
* transport_do_se_mem_map() from transport_generic_get_cdb_count()
*/
if (!(task->task_sg_bidi)) {
/*
* Assume default that transport plugin speaks preallocated
* scatterlists.
*/
if (!(transport_calc_sg_num(task, in_se_mem, task_offset)))
return -1;
/*
* struct se_task->task_sg now contains the struct scatterlist array.
*/
return transport_map_mem_to_sg(task, se_mem_list, task->task_sg,
in_se_mem, out_se_mem, se_mem_cnt,
task_offset_in);
}
/*
* Handle the se_mem_list -> struct task->task_sg_bidi
* memory map for the extra BIDI READ payload
*/
return transport_map_mem_to_sg(task, se_mem_list, task->task_sg_bidi,
in_se_mem, out_se_mem, se_mem_cnt,
task_offset_in);
}
static u32 transport_generic_get_cdb_count(
struct se_cmd *cmd,
unsigned long long lba,
u32 sectors,
enum dma_data_direction data_direction,
struct list_head *mem_list,
int set_counts)
{
unsigned char *cdb = NULL;
struct se_task *task;
struct se_mem *se_mem = NULL, *se_mem_lout = NULL;
struct se_mem *se_mem_bidi = NULL, *se_mem_bidi_lout = NULL;
struct se_device *dev = SE_DEV(cmd);
int max_sectors_set = 0, ret;
u32 task_offset_in = 0, se_mem_cnt = 0, se_mem_bidi_cnt = 0, task_cdbs = 0;
if (!mem_list) {
printk(KERN_ERR "mem_list is NULL in transport_generic_get"
"_cdb_count()\n");
return 0;
}
/*
* While using RAMDISK_DR backstores is the only case where
* mem_list will ever be empty at this point.
*/
if (!(list_empty(mem_list)))
se_mem = list_entry(mem_list->next, struct se_mem, se_list);
/*
* Check for extra se_mem_bidi mapping for BIDI-COMMANDs to
* struct se_task->task_sg_bidi for TCM/pSCSI passthrough operation
*/
if ((T_TASK(cmd)->t_mem_bidi_list != NULL) &&
!(list_empty(T_TASK(cmd)->t_mem_bidi_list)) &&
(TRANSPORT(dev)->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV))
se_mem_bidi = list_entry(T_TASK(cmd)->t_mem_bidi_list->next,
struct se_mem, se_list);
while (sectors) {
DEBUG_VOL("ITT[0x%08x] LBA(%llu) SectorsLeft(%u) EOBJ(%llu)\n",
CMD_TFO(cmd)->get_task_tag(cmd), lba, sectors,
transport_dev_end_lba(dev));
task = transport_generic_get_task(cmd, data_direction);
if (!(task))
goto out;
transport_set_tasks_sectors(task, dev, lba, sectors,
&max_sectors_set);
task->task_lba = lba;
lba += task->task_sectors;
sectors -= task->task_sectors;
task->task_size = (task->task_sectors *
DEV_ATTRIB(dev)->block_size);
cdb = TRANSPORT(dev)->get_cdb(task);
if ((cdb)) {
memcpy(cdb, T_TASK(cmd)->t_task_cdb,
scsi_command_size(T_TASK(cmd)->t_task_cdb));
cmd->transport_split_cdb(task->task_lba,
&task->task_sectors, cdb);
}
/*
* Perform the SE OBJ plugin and/or Transport plugin specific
* mapping for T_TASK(cmd)->t_mem_list. And setup the
* task->task_sg and if necessary task->task_sg_bidi
*/
ret = transport_do_se_mem_map(dev, task, mem_list,
NULL, se_mem, &se_mem_lout, &se_mem_cnt,
&task_offset_in);
if (ret < 0)
goto out;
se_mem = se_mem_lout;
/*
* Setup the T_TASK(cmd)->t_mem_bidi_list -> task->task_sg_bidi
* mapping for SCSI READ for BIDI-COMMAND passthrough with TCM/pSCSI
*
* Note that the first call to transport_do_se_mem_map() above will
* allocate struct se_task->task_sg_bidi in transport_do_se_mem_map()
* -> transport_calc_sg_num(), and the second here will do the
* mapping for SCSI READ for BIDI-COMMAND passthrough with TCM/pSCSI.
*/
if (task->task_sg_bidi != NULL) {
ret = transport_do_se_mem_map(dev, task,
T_TASK(cmd)->t_mem_bidi_list, NULL,
se_mem_bidi, &se_mem_bidi_lout, &se_mem_bidi_cnt,
&task_offset_in);
if (ret < 0)
goto out;
se_mem_bidi = se_mem_bidi_lout;
}
task_cdbs++;
DEBUG_VOL("Incremented task_cdbs(%u) task->task_sg_num(%u)\n",
task_cdbs, task->task_sg_num);
if (max_sectors_set) {
max_sectors_set = 0;
continue;
}
if (!sectors)
break;
}
if (set_counts) {
atomic_inc(&T_TASK(cmd)->t_fe_count);
atomic_inc(&T_TASK(cmd)->t_se_count);
}
DEBUG_VOL("ITT[0x%08x] total %s cdbs(%u)\n",
CMD_TFO(cmd)->get_task_tag(cmd), (data_direction == DMA_TO_DEVICE)
? "DMA_TO_DEVICE" : "DMA_FROM_DEVICE", task_cdbs);
return task_cdbs;
out:
return 0;
}
static int
transport_map_control_cmd_to_task(struct se_cmd *cmd)
{
struct se_device *dev = SE_DEV(cmd);
unsigned char *cdb;
struct se_task *task;
int ret;
task = transport_generic_get_task(cmd, cmd->data_direction);
if (!task)
return PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES;
cdb = TRANSPORT(dev)->get_cdb(task);
if (cdb)
memcpy(cdb, cmd->t_task->t_task_cdb,
scsi_command_size(cmd->t_task->t_task_cdb));
task->task_size = cmd->data_length;
task->task_sg_num =
(cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB) ? 1 : 0;
atomic_inc(&cmd->t_task->t_fe_count);
atomic_inc(&cmd->t_task->t_se_count);
if (cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB) {
struct se_mem *se_mem = NULL, *se_mem_lout = NULL;
u32 se_mem_cnt = 0, task_offset = 0;
if (!list_empty(T_TASK(cmd)->t_mem_list))
se_mem = list_entry(T_TASK(cmd)->t_mem_list->next,
struct se_mem, se_list);
ret = transport_do_se_mem_map(dev, task,
cmd->t_task->t_mem_list, NULL, se_mem,
&se_mem_lout, &se_mem_cnt, &task_offset);
if (ret < 0)
return PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES;
if (dev->transport->map_task_SG)
return dev->transport->map_task_SG(task);
return 0;
} else if (cmd->se_cmd_flags & SCF_SCSI_CONTROL_NONSG_IO_CDB) {
if (dev->transport->map_task_non_SG)
return dev->transport->map_task_non_SG(task);
return 0;
} else if (cmd->se_cmd_flags & SCF_SCSI_NON_DATA_CDB) {
if (dev->transport->cdb_none)
return dev->transport->cdb_none(task);
return 0;
} else {
BUG();
return PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES;
}
}
/* transport_generic_new_cmd(): Called from transport_processing_thread()
*
* Allocate storage transport resources from a set of values predefined
* by transport_generic_cmd_sequencer() from the iSCSI Target RX process.
* Any non zero return here is treated as an "out of resource' op here.
*/
/*
* Generate struct se_task(s) and/or their payloads for this CDB.
*/
static int transport_generic_new_cmd(struct se_cmd *cmd)
{
struct se_portal_group *se_tpg;
struct se_task *task;
struct se_device *dev = SE_DEV(cmd);
int ret = 0;
/*
* Determine is the TCM fabric module has already allocated physical
* memory, and is directly calling transport_generic_map_mem_to_cmd()
* to setup beforehand the linked list of physical memory at
* T_TASK(cmd)->t_mem_list of struct se_mem->se_page
*/
if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC)) {
ret = transport_allocate_resources(cmd);
if (ret < 0)
return ret;
}
ret = transport_get_sectors(cmd);
if (ret < 0)
return ret;
ret = transport_new_cmd_obj(cmd);
if (ret < 0)
return ret;
/*
* Determine if the calling TCM fabric module is talking to
* Linux/NET via kernel sockets and needs to allocate a
* struct iovec array to complete the struct se_cmd
*/
se_tpg = SE_LUN(cmd)->lun_sep->sep_tpg;
if (TPG_TFO(se_tpg)->alloc_cmd_iovecs != NULL) {
ret = TPG_TFO(se_tpg)->alloc_cmd_iovecs(cmd);
if (ret < 0)
return PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES;
}
if (cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB) {
list_for_each_entry(task, &T_TASK(cmd)->t_task_list, t_list) {
if (atomic_read(&task->task_sent))
continue;
if (!dev->transport->map_task_SG)
continue;
ret = dev->transport->map_task_SG(task);
if (ret < 0)
return ret;
}
} else {
ret = transport_map_control_cmd_to_task(cmd);
if (ret < 0)
return ret;
}
/*
* For WRITEs, let the iSCSI Target RX Thread know its buffer is ready..
* This WRITE struct se_cmd (and all of its associated struct se_task's)
* will be added to the struct se_device execution queue after its WRITE
* data has arrived. (ie: It gets handled by the transport processing
* thread a second time)
*/
if (cmd->data_direction == DMA_TO_DEVICE) {
transport_add_tasks_to_state_queue(cmd);
return transport_generic_write_pending(cmd);
}
/*
* Everything else but a WRITE, add the struct se_cmd's struct se_task's
* to the execution queue.
*/
transport_execute_tasks(cmd);
return 0;
}
/* transport_generic_process_write():
*
*
*/
void transport_generic_process_write(struct se_cmd *cmd)
{
#if 0
/*
* Copy SCSI Presented DTL sector(s) from received buffers allocated to
* original EDTL
*/
if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
if (!T_TASK(cmd)->t_tasks_se_num) {
unsigned char *dst, *buf =
(unsigned char *)T_TASK(cmd)->t_task_buf;
dst = kzalloc(cmd->cmd_spdtl), GFP_KERNEL);
if (!(dst)) {
printk(KERN_ERR "Unable to allocate memory for"
" WRITE underflow\n");
transport_generic_request_failure(cmd, NULL,
PYX_TRANSPORT_REQ_TOO_MANY_SECTORS, 1);
return;
}
memcpy(dst, buf, cmd->cmd_spdtl);
kfree(T_TASK(cmd)->t_task_buf);
T_TASK(cmd)->t_task_buf = dst;
} else {
struct scatterlist *sg =
(struct scatterlist *sg)T_TASK(cmd)->t_task_buf;
struct scatterlist *orig_sg;
orig_sg = kzalloc(sizeof(struct scatterlist) *
T_TASK(cmd)->t_tasks_se_num,
GFP_KERNEL))) {
if (!(orig_sg)) {
printk(KERN_ERR "Unable to allocate memory"
" for WRITE underflow\n");
transport_generic_request_failure(cmd, NULL,
PYX_TRANSPORT_REQ_TOO_MANY_SECTORS, 1);
return;
}
memcpy(orig_sg, T_TASK(cmd)->t_task_buf,
sizeof(struct scatterlist) *
T_TASK(cmd)->t_tasks_se_num);
cmd->data_length = cmd->cmd_spdtl;
/*
* FIXME, clear out original struct se_task and state
* information.
*/
if (transport_generic_new_cmd(cmd) < 0) {
transport_generic_request_failure(cmd, NULL,
PYX_TRANSPORT_REQ_TOO_MANY_SECTORS, 1);
kfree(orig_sg);
return;
}
transport_memcpy_write_sg(cmd, orig_sg);
}
}
#endif
transport_execute_tasks(cmd);
}
EXPORT_SYMBOL(transport_generic_process_write);
/* transport_generic_write_pending():
*
*
*/
static int transport_generic_write_pending(struct se_cmd *cmd)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
cmd->t_state = TRANSPORT_WRITE_PENDING;
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
/*
* For the TCM control CDBs using a contiguous buffer, do the memcpy
* from the passed Linux/SCSI struct scatterlist located at
* T_TASK(se_cmd)->t_task_pt_buf to the contiguous buffer at
* T_TASK(se_cmd)->t_task_buf.
*/
if (cmd->se_cmd_flags & SCF_PASSTHROUGH_CONTIG_TO_SG)
transport_memcpy_read_contig(cmd,
T_TASK(cmd)->t_task_buf,
T_TASK(cmd)->t_task_pt_sgl);
/*
* Clear the se_cmd for WRITE_PENDING status in order to set
* T_TASK(cmd)->t_transport_active=0 so that transport_generic_handle_data
* can be called from HW target mode interrupt code. This is safe
* to be called with transport_off=1 before the CMD_TFO(cmd)->write_pending
* because the se_cmd->se_lun pointer is not being cleared.
*/
transport_cmd_check_stop(cmd, 1, 0);
/*
* Call the fabric write_pending function here to let the
* frontend know that WRITE buffers are ready.
*/
ret = CMD_TFO(cmd)->write_pending(cmd);
if (ret < 0)
return ret;
return PYX_TRANSPORT_WRITE_PENDING;
}
/* transport_release_cmd_to_pool():
*
*
*/
void transport_release_cmd_to_pool(struct se_cmd *cmd)
{
BUG_ON(!T_TASK(cmd));
BUG_ON(!CMD_TFO(cmd));
transport_free_se_cmd(cmd);
CMD_TFO(cmd)->release_cmd_to_pool(cmd);
}
EXPORT_SYMBOL(transport_release_cmd_to_pool);
/* transport_generic_free_cmd():
*
* Called from processing frontend to release storage engine resources
*/
void transport_generic_free_cmd(
struct se_cmd *cmd,
int wait_for_tasks,
int release_to_pool,
int session_reinstatement)
{
if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) || !T_TASK(cmd))
transport_release_cmd_to_pool(cmd);
else {
core_dec_lacl_count(cmd->se_sess->se_node_acl, cmd);
if (SE_LUN(cmd)) {
#if 0
printk(KERN_INFO "cmd: %p ITT: 0x%08x contains"
" SE_LUN(cmd)\n", cmd,
CMD_TFO(cmd)->get_task_tag(cmd));
#endif
transport_lun_remove_cmd(cmd);
}
if (wait_for_tasks && cmd->transport_wait_for_tasks)
cmd->transport_wait_for_tasks(cmd, 0, 0);
transport_free_dev_tasks(cmd);
transport_generic_remove(cmd, release_to_pool,
session_reinstatement);
}
}
EXPORT_SYMBOL(transport_generic_free_cmd);
static void transport_nop_wait_for_tasks(
struct se_cmd *cmd,
int remove_cmd,
int session_reinstatement)
{
return;
}
/* transport_lun_wait_for_tasks():
*
* Called from ConfigFS context to stop the passed struct se_cmd to allow
* an struct se_lun to be successfully shutdown.
*/
static int transport_lun_wait_for_tasks(struct se_cmd *cmd, struct se_lun *lun)
{
unsigned long flags;
int ret;
/*
* If the frontend has already requested this struct se_cmd to
* be stopped, we can safely ignore this struct se_cmd.
*/
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
if (atomic_read(&T_TASK(cmd)->t_transport_stop)) {
atomic_set(&T_TASK(cmd)->transport_lun_stop, 0);
DEBUG_TRANSPORT_S("ConfigFS ITT[0x%08x] - t_transport_stop =="
" TRUE, skipping\n", CMD_TFO(cmd)->get_task_tag(cmd));
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
transport_cmd_check_stop(cmd, 1, 0);
return -1;
}
atomic_set(&T_TASK(cmd)->transport_lun_fe_stop, 1);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
wake_up_interruptible(&SE_DEV(cmd)->dev_queue_obj->thread_wq);
ret = transport_stop_tasks_for_cmd(cmd);
DEBUG_TRANSPORT_S("ConfigFS: cmd: %p t_task_cdbs: %d stop tasks ret:"
" %d\n", cmd, T_TASK(cmd)->t_task_cdbs, ret);
if (!ret) {
DEBUG_TRANSPORT_S("ConfigFS: ITT[0x%08x] - stopping cmd....\n",
CMD_TFO(cmd)->get_task_tag(cmd));
wait_for_completion(&T_TASK(cmd)->transport_lun_stop_comp);
DEBUG_TRANSPORT_S("ConfigFS: ITT[0x%08x] - stopped cmd....\n",
CMD_TFO(cmd)->get_task_tag(cmd));
}
transport_remove_cmd_from_queue(cmd, SE_DEV(cmd)->dev_queue_obj);
return 0;
}
/* #define DEBUG_CLEAR_LUN */
#ifdef DEBUG_CLEAR_LUN
#define DEBUG_CLEAR_L(x...) printk(KERN_INFO x)
#else
#define DEBUG_CLEAR_L(x...)
#endif
static void __transport_clear_lun_from_sessions(struct se_lun *lun)
{
struct se_cmd *cmd = NULL;
unsigned long lun_flags, cmd_flags;
/*
* Do exception processing and return CHECK_CONDITION status to the
* Initiator Port.
*/
spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
while (!list_empty_careful(&lun->lun_cmd_list)) {
cmd = list_entry(lun->lun_cmd_list.next,
struct se_cmd, se_lun_list);
list_del(&cmd->se_lun_list);
if (!(T_TASK(cmd))) {
printk(KERN_ERR "ITT: 0x%08x, T_TASK(cmd) = NULL"
"[i,t]_state: %u/%u\n",
CMD_TFO(cmd)->get_task_tag(cmd),
CMD_TFO(cmd)->get_cmd_state(cmd), cmd->t_state);
BUG();
}
atomic_set(&T_TASK(cmd)->transport_lun_active, 0);
/*
* This will notify iscsi_target_transport.c:
* transport_cmd_check_stop() that a LUN shutdown is in
* progress for the iscsi_cmd_t.
*/
spin_lock(&T_TASK(cmd)->t_state_lock);
DEBUG_CLEAR_L("SE_LUN[%d] - Setting T_TASK(cmd)->transport"
"_lun_stop for ITT: 0x%08x\n",
SE_LUN(cmd)->unpacked_lun,
CMD_TFO(cmd)->get_task_tag(cmd));
atomic_set(&T_TASK(cmd)->transport_lun_stop, 1);
spin_unlock(&T_TASK(cmd)->t_state_lock);
spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
if (!(SE_LUN(cmd))) {
printk(KERN_ERR "ITT: 0x%08x, [i,t]_state: %u/%u\n",
CMD_TFO(cmd)->get_task_tag(cmd),
CMD_TFO(cmd)->get_cmd_state(cmd), cmd->t_state);
BUG();
}
/*
* If the Storage engine still owns the iscsi_cmd_t, determine
* and/or stop its context.
*/
DEBUG_CLEAR_L("SE_LUN[%d] - ITT: 0x%08x before transport"
"_lun_wait_for_tasks()\n", SE_LUN(cmd)->unpacked_lun,
CMD_TFO(cmd)->get_task_tag(cmd));
if (transport_lun_wait_for_tasks(cmd, SE_LUN(cmd)) < 0) {
spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
continue;
}
DEBUG_CLEAR_L("SE_LUN[%d] - ITT: 0x%08x after transport_lun"
"_wait_for_tasks(): SUCCESS\n",
SE_LUN(cmd)->unpacked_lun,
CMD_TFO(cmd)->get_task_tag(cmd));
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, cmd_flags);
if (!(atomic_read(&T_TASK(cmd)->transport_dev_active))) {
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, cmd_flags);
goto check_cond;
}
atomic_set(&T_TASK(cmd)->transport_dev_active, 0);
transport_all_task_dev_remove_state(cmd);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, cmd_flags);
transport_free_dev_tasks(cmd);
/*
* The Storage engine stopped this struct se_cmd before it was
* send to the fabric frontend for delivery back to the
* Initiator Node. Return this SCSI CDB back with an
* CHECK_CONDITION status.
*/
check_cond:
transport_send_check_condition_and_sense(cmd,
TCM_NON_EXISTENT_LUN, 0);
/*
* If the fabric frontend is waiting for this iscsi_cmd_t to
* be released, notify the waiting thread now that LU has
* finished accessing it.
*/
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, cmd_flags);
if (atomic_read(&T_TASK(cmd)->transport_lun_fe_stop)) {
DEBUG_CLEAR_L("SE_LUN[%d] - Detected FE stop for"
" struct se_cmd: %p ITT: 0x%08x\n",
lun->unpacked_lun,
cmd, CMD_TFO(cmd)->get_task_tag(cmd));
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock,
cmd_flags);
transport_cmd_check_stop(cmd, 1, 0);
complete(&T_TASK(cmd)->transport_lun_fe_stop_comp);
spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
continue;
}
DEBUG_CLEAR_L("SE_LUN[%d] - ITT: 0x%08x finished processing\n",
lun->unpacked_lun, CMD_TFO(cmd)->get_task_tag(cmd));
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, cmd_flags);
spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
}
spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
}
static int transport_clear_lun_thread(void *p)
{
struct se_lun *lun = (struct se_lun *)p;
__transport_clear_lun_from_sessions(lun);
complete(&lun->lun_shutdown_comp);
return 0;
}
int transport_clear_lun_from_sessions(struct se_lun *lun)
{
struct task_struct *kt;
kt = kthread_run(transport_clear_lun_thread, (void *)lun,
"tcm_cl_%u", lun->unpacked_lun);
if (IS_ERR(kt)) {
printk(KERN_ERR "Unable to start clear_lun thread\n");
return -1;
}
wait_for_completion(&lun->lun_shutdown_comp);
return 0;
}
/* transport_generic_wait_for_tasks():
*
* Called from frontend or passthrough context to wait for storage engine
* to pause and/or release frontend generated struct se_cmd.
*/
static void transport_generic_wait_for_tasks(
struct se_cmd *cmd,
int remove_cmd,
int session_reinstatement)
{
unsigned long flags;
if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) && !(cmd->se_tmr_req))
return;
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
/*
* If we are already stopped due to an external event (ie: LUN shutdown)
* sleep until the connection can have the passed struct se_cmd back.
* The T_TASK(cmd)->transport_lun_stopped_sem will be upped by
* transport_clear_lun_from_sessions() once the ConfigFS context caller
* has completed its operation on the struct se_cmd.
*/
if (atomic_read(&T_TASK(cmd)->transport_lun_stop)) {
DEBUG_TRANSPORT_S("wait_for_tasks: Stopping"
" wait_for_completion(&T_TASK(cmd)transport_lun_fe"
"_stop_comp); for ITT: 0x%08x\n",
CMD_TFO(cmd)->get_task_tag(cmd));
/*
* There is a special case for WRITES where a FE exception +
* LUN shutdown means ConfigFS context is still sleeping on
* transport_lun_stop_comp in transport_lun_wait_for_tasks().
* We go ahead and up transport_lun_stop_comp just to be sure
* here.
*/
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
complete(&T_TASK(cmd)->transport_lun_stop_comp);
wait_for_completion(&T_TASK(cmd)->transport_lun_fe_stop_comp);
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
transport_all_task_dev_remove_state(cmd);
/*
* At this point, the frontend who was the originator of this
* struct se_cmd, now owns the structure and can be released through
* normal means below.
*/
DEBUG_TRANSPORT_S("wait_for_tasks: Stopped"
" wait_for_completion(&T_TASK(cmd)transport_lun_fe_"
"stop_comp); for ITT: 0x%08x\n",
CMD_TFO(cmd)->get_task_tag(cmd));
atomic_set(&T_TASK(cmd)->transport_lun_stop, 0);
}
if (!atomic_read(&T_TASK(cmd)->t_transport_active) ||
atomic_read(&T_TASK(cmd)->t_transport_aborted))
goto remove;
atomic_set(&T_TASK(cmd)->t_transport_stop, 1);
DEBUG_TRANSPORT_S("wait_for_tasks: Stopping %p ITT: 0x%08x"
" i_state: %d, t_state/def_t_state: %d/%d, t_transport_stop"
" = TRUE\n", cmd, CMD_TFO(cmd)->get_task_tag(cmd),
CMD_TFO(cmd)->get_cmd_state(cmd), cmd->t_state,
cmd->deferred_t_state);
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
wake_up_interruptible(&SE_DEV(cmd)->dev_queue_obj->thread_wq);
wait_for_completion(&T_TASK(cmd)->t_transport_stop_comp);
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
atomic_set(&T_TASK(cmd)->t_transport_active, 0);
atomic_set(&T_TASK(cmd)->t_transport_stop, 0);
DEBUG_TRANSPORT_S("wait_for_tasks: Stopped wait_for_compltion("
"&T_TASK(cmd)->t_transport_stop_comp) for ITT: 0x%08x\n",
CMD_TFO(cmd)->get_task_tag(cmd));
remove:
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
if (!remove_cmd)
return;
transport_generic_free_cmd(cmd, 0, 0, session_reinstatement);
}
static int transport_get_sense_codes(
struct se_cmd *cmd,
u8 *asc,
u8 *ascq)
{
*asc = cmd->scsi_asc;
*ascq = cmd->scsi_ascq;
return 0;
}
static int transport_set_sense_codes(
struct se_cmd *cmd,
u8 asc,
u8 ascq)
{
cmd->scsi_asc = asc;
cmd->scsi_ascq = ascq;
return 0;
}
int transport_send_check_condition_and_sense(
struct se_cmd *cmd,
u8 reason,
int from_transport)
{
unsigned char *buffer = cmd->sense_buffer;
unsigned long flags;
int offset;
u8 asc = 0, ascq = 0;
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
return 0;
}
cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION;
spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
if (!reason && from_transport)
goto after_reason;
if (!from_transport)
cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE;
/*
* Data Segment and SenseLength of the fabric response PDU.
*
* TRANSPORT_SENSE_BUFFER is now set to SCSI_SENSE_BUFFERSIZE
* from include/scsi/scsi_cmnd.h
*/
offset = CMD_TFO(cmd)->set_fabric_sense_len(cmd,
TRANSPORT_SENSE_BUFFER);
/*
* Actual SENSE DATA, see SPC-3 7.23.2 SPC_SENSE_KEY_OFFSET uses
* SENSE KEY values from include/scsi/scsi.h
*/
switch (reason) {
case TCM_NON_EXISTENT_LUN:
case TCM_UNSUPPORTED_SCSI_OPCODE:
case TCM_SECTOR_COUNT_TOO_MANY:
/* CURRENT ERROR */
buffer[offset] = 0x70;
/* ILLEGAL REQUEST */
buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
/* INVALID COMMAND OPERATION CODE */
buffer[offset+SPC_ASC_KEY_OFFSET] = 0x20;
break;
case TCM_UNKNOWN_MODE_PAGE:
/* CURRENT ERROR */
buffer[offset] = 0x70;
/* ILLEGAL REQUEST */
buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
/* INVALID FIELD IN CDB */
buffer[offset+SPC_ASC_KEY_OFFSET] = 0x24;
break;
case TCM_CHECK_CONDITION_ABORT_CMD:
/* CURRENT ERROR */
buffer[offset] = 0x70;
/* ABORTED COMMAND */
buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
/* BUS DEVICE RESET FUNCTION OCCURRED */
buffer[offset+SPC_ASC_KEY_OFFSET] = 0x29;
buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x03;
break;
case TCM_INCORRECT_AMOUNT_OF_DATA:
/* CURRENT ERROR */
buffer[offset] = 0x70;
/* ABORTED COMMAND */
buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
/* WRITE ERROR */
buffer[offset+SPC_ASC_KEY_OFFSET] = 0x0c;
/* NOT ENOUGH UNSOLICITED DATA */
buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x0d;
break;
case TCM_INVALID_CDB_FIELD:
/* CURRENT ERROR */
buffer[offset] = 0x70;
/* ABORTED COMMAND */
buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
/* INVALID FIELD IN CDB */
buffer[offset+SPC_ASC_KEY_OFFSET] = 0x24;
break;
case TCM_INVALID_PARAMETER_LIST:
/* CURRENT ERROR */
buffer[offset] = 0x70;
/* ABORTED COMMAND */
buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
/* INVALID FIELD IN PARAMETER LIST */
buffer[offset+SPC_ASC_KEY_OFFSET] = 0x26;
break;
case TCM_UNEXPECTED_UNSOLICITED_DATA:
/* CURRENT ERROR */
buffer[offset] = 0x70;
/* ABORTED COMMAND */
buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
/* WRITE ERROR */
buffer[offset+SPC_ASC_KEY_OFFSET] = 0x0c;
/* UNEXPECTED_UNSOLICITED_DATA */
buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x0c;
break;
case TCM_SERVICE_CRC_ERROR:
/* CURRENT ERROR */
buffer[offset] = 0x70;
/* ABORTED COMMAND */
buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
/* PROTOCOL SERVICE CRC ERROR */
buffer[offset+SPC_ASC_KEY_OFFSET] = 0x47;
/* N/A */
buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x05;
break;
case TCM_SNACK_REJECTED:
/* CURRENT ERROR */
buffer[offset] = 0x70;
/* ABORTED COMMAND */
buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
/* READ ERROR */
buffer[offset+SPC_ASC_KEY_OFFSET] = 0x11;
/* FAILED RETRANSMISSION REQUEST */
buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x13;
break;
case TCM_WRITE_PROTECTED:
/* CURRENT ERROR */
buffer[offset] = 0x70;
/* DATA PROTECT */
buffer[offset+SPC_SENSE_KEY_OFFSET] = DATA_PROTECT;
/* WRITE PROTECTED */
buffer[offset+SPC_ASC_KEY_OFFSET] = 0x27;
break;
case TCM_CHECK_CONDITION_UNIT_ATTENTION:
/* CURRENT ERROR */
buffer[offset] = 0x70;
/* UNIT ATTENTION */
buffer[offset+SPC_SENSE_KEY_OFFSET] = UNIT_ATTENTION;
core_scsi3_ua_for_check_condition(cmd, &asc, &ascq);
buffer[offset+SPC_ASC_KEY_OFFSET] = asc;
buffer[offset+SPC_ASCQ_KEY_OFFSET] = ascq;
break;
case TCM_CHECK_CONDITION_NOT_READY:
/* CURRENT ERROR */
buffer[offset] = 0x70;
/* Not Ready */
buffer[offset+SPC_SENSE_KEY_OFFSET] = NOT_READY;
transport_get_sense_codes(cmd, &asc, &ascq);
buffer[offset+SPC_ASC_KEY_OFFSET] = asc;
buffer[offset+SPC_ASCQ_KEY_OFFSET] = ascq;
break;
case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
default:
/* CURRENT ERROR */
buffer[offset] = 0x70;
/* ILLEGAL REQUEST */
buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
/* LOGICAL UNIT COMMUNICATION FAILURE */
buffer[offset+SPC_ASC_KEY_OFFSET] = 0x80;
break;
}
/*
* This code uses linux/include/scsi/scsi.h SAM status codes!
*/
cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
/*
* Automatically padded, this value is encoded in the fabric's
* data_length response PDU containing the SCSI defined sense data.
*/
cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER + offset;
after_reason:
CMD_TFO(cmd)->queue_status(cmd);
return 0;
}
EXPORT_SYMBOL(transport_send_check_condition_and_sense);
int transport_check_aborted_status(struct se_cmd *cmd, int send_status)
{
int ret = 0;
if (atomic_read(&T_TASK(cmd)->t_transport_aborted) != 0) {
if (!(send_status) ||
(cmd->se_cmd_flags & SCF_SENT_DELAYED_TAS))
return 1;
#if 0
printk(KERN_INFO "Sending delayed SAM_STAT_TASK_ABORTED"
" status for CDB: 0x%02x ITT: 0x%08x\n",
T_TASK(cmd)->t_task_cdb[0],
CMD_TFO(cmd)->get_task_tag(cmd));
#endif
cmd->se_cmd_flags |= SCF_SENT_DELAYED_TAS;
CMD_TFO(cmd)->queue_status(cmd);
ret = 1;
}
return ret;
}
EXPORT_SYMBOL(transport_check_aborted_status);
void transport_send_task_abort(struct se_cmd *cmd)
{
/*
* If there are still expected incoming fabric WRITEs, we wait
* until until they have completed before sending a TASK_ABORTED
* response. This response with TASK_ABORTED status will be
* queued back to fabric module by transport_check_aborted_status().
*/
if (cmd->data_direction == DMA_TO_DEVICE) {
if (CMD_TFO(cmd)->write_pending_status(cmd) != 0) {
atomic_inc(&T_TASK(cmd)->t_transport_aborted);
smp_mb__after_atomic_inc();
cmd->scsi_status = SAM_STAT_TASK_ABORTED;
transport_new_cmd_failure(cmd);
return;
}
}
cmd->scsi_status = SAM_STAT_TASK_ABORTED;
#if 0
printk(KERN_INFO "Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x,"
" ITT: 0x%08x\n", T_TASK(cmd)->t_task_cdb[0],
CMD_TFO(cmd)->get_task_tag(cmd));
#endif
CMD_TFO(cmd)->queue_status(cmd);
}
/* transport_generic_do_tmr():
*
*
*/
int transport_generic_do_tmr(struct se_cmd *cmd)
{
struct se_cmd *ref_cmd;
struct se_device *dev = SE_DEV(cmd);
struct se_tmr_req *tmr = cmd->se_tmr_req;
int ret;
switch (tmr->function) {
case TMR_ABORT_TASK:
ref_cmd = tmr->ref_cmd;
tmr->response = TMR_FUNCTION_REJECTED;
break;
case TMR_ABORT_TASK_SET:
case TMR_CLEAR_ACA:
case TMR_CLEAR_TASK_SET:
tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
break;
case TMR_LUN_RESET:
ret = core_tmr_lun_reset(dev, tmr, NULL, NULL);
tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE :
TMR_FUNCTION_REJECTED;
break;
case TMR_TARGET_WARM_RESET:
tmr->response = TMR_FUNCTION_REJECTED;
break;
case TMR_TARGET_COLD_RESET:
tmr->response = TMR_FUNCTION_REJECTED;
break;
default:
printk(KERN_ERR "Uknown TMR function: 0x%02x.\n",
tmr->function);
tmr->response = TMR_FUNCTION_REJECTED;
break;
}
cmd->t_state = TRANSPORT_ISTATE_PROCESSING;
CMD_TFO(cmd)->queue_tm_rsp(cmd);
transport_cmd_check_stop(cmd, 2, 0);
return 0;
}
/*
* Called with spin_lock_irq(&dev->execute_task_lock); held
*
*/
static struct se_task *
transport_get_task_from_state_list(struct se_device *dev)
{
struct se_task *task;
if (list_empty(&dev->state_task_list))
return NULL;
list_for_each_entry(task, &dev->state_task_list, t_state_list)
break;
list_del(&task->t_state_list);
atomic_set(&task->task_state_active, 0);
return task;
}
static void transport_processing_shutdown(struct se_device *dev)
{
struct se_cmd *cmd;
struct se_queue_req *qr;
struct se_task *task;
u8 state;
unsigned long flags;
/*
* Empty the struct se_device's struct se_task state list.
*/
spin_lock_irqsave(&dev->execute_task_lock, flags);
while ((task = transport_get_task_from_state_list(dev))) {
if (!(TASK_CMD(task))) {
printk(KERN_ERR "TASK_CMD(task) is NULL!\n");
continue;
}
cmd = TASK_CMD(task);
if (!T_TASK(cmd)) {
printk(KERN_ERR "T_TASK(cmd) is NULL for task: %p cmd:"
" %p ITT: 0x%08x\n", task, cmd,
CMD_TFO(cmd)->get_task_tag(cmd));
continue;
}
spin_unlock_irqrestore(&dev->execute_task_lock, flags);
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
DEBUG_DO("PT: cmd: %p task: %p ITT/CmdSN: 0x%08x/0x%08x,"
" i_state/def_i_state: %d/%d, t_state/def_t_state:"
" %d/%d cdb: 0x%02x\n", cmd, task,
CMD_TFO(cmd)->get_task_tag(cmd), cmd->cmd_sn,
CMD_TFO(cmd)->get_cmd_state(cmd), cmd->deferred_i_state,
cmd->t_state, cmd->deferred_t_state,
T_TASK(cmd)->t_task_cdb[0]);
DEBUG_DO("PT: ITT[0x%08x] - t_task_cdbs: %d t_task_cdbs_left:"
" %d t_task_cdbs_sent: %d -- t_transport_active: %d"
" t_transport_stop: %d t_transport_sent: %d\n",
CMD_TFO(cmd)->get_task_tag(cmd),
T_TASK(cmd)->t_task_cdbs,
atomic_read(&T_TASK(cmd)->t_task_cdbs_left),
atomic_read(&T_TASK(cmd)->t_task_cdbs_sent),
atomic_read(&T_TASK(cmd)->t_transport_active),
atomic_read(&T_TASK(cmd)->t_transport_stop),
atomic_read(&T_TASK(cmd)->t_transport_sent));
if (atomic_read(&task->task_active)) {
atomic_set(&task->task_stop, 1);
spin_unlock_irqrestore(
&T_TASK(cmd)->t_state_lock, flags);
DEBUG_DO("Waiting for task: %p to shutdown for dev:"
" %p\n", task, dev);
wait_for_completion(&task->task_stop_comp);
DEBUG_DO("Completed task: %p shutdown for dev: %p\n",
task, dev);
spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
atomic_dec(&T_TASK(cmd)->t_task_cdbs_left);
atomic_set(&task->task_active, 0);
atomic_set(&task->task_stop, 0);
} else {
if (atomic_read(&task->task_execute_queue) != 0)
transport_remove_task_from_execute_queue(task, dev);
}
__transport_stop_task_timer(task, &flags);
if (!(atomic_dec_and_test(&T_TASK(cmd)->t_task_cdbs_ex_left))) {
spin_unlock_irqrestore(
&T_TASK(cmd)->t_state_lock, flags);
DEBUG_DO("Skipping task: %p, dev: %p for"
" t_task_cdbs_ex_left: %d\n", task, dev,
atomic_read(&T_TASK(cmd)->t_task_cdbs_ex_left));
spin_lock_irqsave(&dev->execute_task_lock, flags);
continue;
}
if (atomic_read(&T_TASK(cmd)->t_transport_active)) {
DEBUG_DO("got t_transport_active = 1 for task: %p, dev:"
" %p\n", task, dev);
if (atomic_read(&T_TASK(cmd)->t_fe_count)) {
spin_unlock_irqrestore(
&T_TASK(cmd)->t_state_lock, flags);
transport_send_check_condition_and_sense(
cmd, TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE,
0);
transport_remove_cmd_from_queue(cmd,
SE_DEV(cmd)->dev_queue_obj);
transport_lun_remove_cmd(cmd);
transport_cmd_check_stop(cmd, 1, 0);
} else {
spin_unlock_irqrestore(
&T_TASK(cmd)->t_state_lock, flags);
transport_remove_cmd_from_queue(cmd,
SE_DEV(cmd)->dev_queue_obj);
transport_lun_remove_cmd(cmd);
if (transport_cmd_check_stop(cmd, 1, 0))
transport_generic_remove(cmd, 0, 0);
}
spin_lock_irqsave(&dev->execute_task_lock, flags);
continue;
}
DEBUG_DO("Got t_transport_active = 0 for task: %p, dev: %p\n",
task, dev);
if (atomic_read(&T_TASK(cmd)->t_fe_count)) {
spin_unlock_irqrestore(
&T_TASK(cmd)->t_state_lock, flags);
transport_send_check_condition_and_sense(cmd,
TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE, 0);
transport_remove_cmd_from_queue(cmd,
SE_DEV(cmd)->dev_queue_obj);
transport_lun_remove_cmd(cmd);
transport_cmd_check_stop(cmd, 1, 0);
} else {
spin_unlock_irqrestore(
&T_TASK(cmd)->t_state_lock, flags);
transport_remove_cmd_from_queue(cmd,
SE_DEV(cmd)->dev_queue_obj);
transport_lun_remove_cmd(cmd);
if (transport_cmd_check_stop(cmd, 1, 0))
transport_generic_remove(cmd, 0, 0);
}
spin_lock_irqsave(&dev->execute_task_lock, flags);
}
spin_unlock_irqrestore(&dev->execute_task_lock, flags);
/*
* Empty the struct se_device's struct se_cmd list.
*/
spin_lock_irqsave(&dev->dev_queue_obj->cmd_queue_lock, flags);
while ((qr = __transport_get_qr_from_queue(dev->dev_queue_obj))) {
spin_unlock_irqrestore(
&dev->dev_queue_obj->cmd_queue_lock, flags);
cmd = (struct se_cmd *)qr->cmd;
state = qr->state;
kfree(qr);
DEBUG_DO("From Device Queue: cmd: %p t_state: %d\n",
cmd, state);
if (atomic_read(&T_TASK(cmd)->t_fe_count)) {
transport_send_check_condition_and_sense(cmd,
TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE, 0);
transport_lun_remove_cmd(cmd);
transport_cmd_check_stop(cmd, 1, 0);
} else {
transport_lun_remove_cmd(cmd);
if (transport_cmd_check_stop(cmd, 1, 0))
transport_generic_remove(cmd, 0, 0);
}
spin_lock_irqsave(&dev->dev_queue_obj->cmd_queue_lock, flags);
}
spin_unlock_irqrestore(&dev->dev_queue_obj->cmd_queue_lock, flags);
}
/* transport_processing_thread():
*
*
*/
static int transport_processing_thread(void *param)
{
int ret, t_state;
struct se_cmd *cmd;
struct se_device *dev = (struct se_device *) param;
struct se_queue_req *qr;
set_user_nice(current, -20);
while (!kthread_should_stop()) {
ret = wait_event_interruptible(dev->dev_queue_obj->thread_wq,
atomic_read(&dev->dev_queue_obj->queue_cnt) ||
kthread_should_stop());
if (ret < 0)
goto out;
spin_lock_irq(&dev->dev_status_lock);
if (dev->dev_status & TRANSPORT_DEVICE_SHUTDOWN) {
spin_unlock_irq(&dev->dev_status_lock);
transport_processing_shutdown(dev);
continue;
}
spin_unlock_irq(&dev->dev_status_lock);
get_cmd:
__transport_execute_tasks(dev);
qr = transport_get_qr_from_queue(dev->dev_queue_obj);
if (!(qr))
continue;
cmd = (struct se_cmd *)qr->cmd;
t_state = qr->state;
kfree(qr);
switch (t_state) {
case TRANSPORT_NEW_CMD_MAP:
if (!(CMD_TFO(cmd)->new_cmd_map)) {
printk(KERN_ERR "CMD_TFO(cmd)->new_cmd_map is"
" NULL for TRANSPORT_NEW_CMD_MAP\n");
BUG();
}
ret = CMD_TFO(cmd)->new_cmd_map(cmd);
if (ret < 0) {
cmd->transport_error_status = ret;
transport_generic_request_failure(cmd, NULL,
0, (cmd->data_direction !=
DMA_TO_DEVICE));
break;
}
/* Fall through */
case TRANSPORT_NEW_CMD:
ret = transport_generic_new_cmd(cmd);
if (ret < 0) {
cmd->transport_error_status = ret;
transport_generic_request_failure(cmd, NULL,
0, (cmd->data_direction !=
DMA_TO_DEVICE));
}
break;
case TRANSPORT_PROCESS_WRITE:
transport_generic_process_write(cmd);
break;
case TRANSPORT_COMPLETE_OK:
transport_stop_all_task_timers(cmd);
transport_generic_complete_ok(cmd);
break;
case TRANSPORT_REMOVE:
transport_generic_remove(cmd, 1, 0);
break;
case TRANSPORT_FREE_CMD_INTR:
transport_generic_free_cmd(cmd, 0, 1, 0);
break;
case TRANSPORT_PROCESS_TMR:
transport_generic_do_tmr(cmd);
break;
case TRANSPORT_COMPLETE_FAILURE:
transport_generic_request_failure(cmd, NULL, 1, 1);
break;
case TRANSPORT_COMPLETE_TIMEOUT:
transport_stop_all_task_timers(cmd);
transport_generic_request_timeout(cmd);
break;
default:
printk(KERN_ERR "Unknown t_state: %d deferred_t_state:"
" %d for ITT: 0x%08x i_state: %d on SE LUN:"
" %u\n", t_state, cmd->deferred_t_state,
CMD_TFO(cmd)->get_task_tag(cmd),
CMD_TFO(cmd)->get_cmd_state(cmd),
SE_LUN(cmd)->unpacked_lun);
BUG();
}
goto get_cmd;
}
out:
transport_release_all_cmds(dev);
dev->process_thread = NULL;
return 0;
}
| gpl-2.0 |
CSE3320/kernel-code | .backup_do_not_remove/arch/powerpc/kvm/book3s_hv_ras.c | 132 | 10433 | // SPDX-License-Identifier: GPL-2.0-only
/*
*
* Copyright 2012 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
*/
#include <linux/types.h>
#include <linux/string.h>
#include <linux/kvm.h>
#include <linux/kvm_host.h>
#include <linux/kernel.h>
#include <asm/opal.h>
#include <asm/mce.h>
#include <asm/machdep.h>
#include <asm/cputhreads.h>
#include <asm/hmi.h>
#include <asm/kvm_ppc.h>
/* SRR1 bits for machine check on POWER7 */
#define SRR1_MC_LDSTERR (1ul << (63-42))
#define SRR1_MC_IFETCH_SH (63-45)
#define SRR1_MC_IFETCH_MASK 0x7
#define SRR1_MC_IFETCH_SLBPAR 2 /* SLB parity error */
#define SRR1_MC_IFETCH_SLBMULTI 3 /* SLB multi-hit */
#define SRR1_MC_IFETCH_SLBPARMULTI 4 /* SLB parity + multi-hit */
#define SRR1_MC_IFETCH_TLBMULTI 5 /* I-TLB multi-hit */
/* DSISR bits for machine check on POWER7 */
#define DSISR_MC_DERAT_MULTI 0x800 /* D-ERAT multi-hit */
#define DSISR_MC_TLB_MULTI 0x400 /* D-TLB multi-hit */
#define DSISR_MC_SLB_PARITY 0x100 /* SLB parity error */
#define DSISR_MC_SLB_MULTI 0x080 /* SLB multi-hit */
#define DSISR_MC_SLB_PARMULTI 0x040 /* SLB parity + multi-hit */
/* POWER7 SLB flush and reload */
static void reload_slb(struct kvm_vcpu *vcpu)
{
struct slb_shadow *slb;
unsigned long i, n;
/* First clear out SLB */
asm volatile("slbmte %0,%0; slbia" : : "r" (0));
/* Do they have an SLB shadow buffer registered? */
slb = vcpu->arch.slb_shadow.pinned_addr;
if (!slb)
return;
/* Sanity check */
n = min_t(u32, be32_to_cpu(slb->persistent), SLB_MIN_SIZE);
if ((void *) &slb->save_area[n] > vcpu->arch.slb_shadow.pinned_end)
return;
/* Load up the SLB from that */
for (i = 0; i < n; ++i) {
unsigned long rb = be64_to_cpu(slb->save_area[i].esid);
unsigned long rs = be64_to_cpu(slb->save_area[i].vsid);
rb = (rb & ~0xFFFul) | i; /* insert entry number */
asm volatile("slbmte %0,%1" : : "r" (rs), "r" (rb));
}
}
/*
* On POWER7, see if we can handle a machine check that occurred inside
* the guest in real mode, without switching to the host partition.
*/
static void kvmppc_realmode_mc_power7(struct kvm_vcpu *vcpu)
{
unsigned long srr1 = vcpu->arch.shregs.msr;
struct machine_check_event mce_evt;
long handled = 1;
if (srr1 & SRR1_MC_LDSTERR) {
/* error on load/store */
unsigned long dsisr = vcpu->arch.shregs.dsisr;
if (dsisr & (DSISR_MC_SLB_PARMULTI | DSISR_MC_SLB_MULTI |
DSISR_MC_SLB_PARITY | DSISR_MC_DERAT_MULTI)) {
/* flush and reload SLB; flushes D-ERAT too */
reload_slb(vcpu);
dsisr &= ~(DSISR_MC_SLB_PARMULTI | DSISR_MC_SLB_MULTI |
DSISR_MC_SLB_PARITY | DSISR_MC_DERAT_MULTI);
}
if (dsisr & DSISR_MC_TLB_MULTI) {
tlbiel_all_lpid(vcpu->kvm->arch.radix);
dsisr &= ~DSISR_MC_TLB_MULTI;
}
/* Any other errors we don't understand? */
if (dsisr & 0xffffffffUL)
handled = 0;
}
switch ((srr1 >> SRR1_MC_IFETCH_SH) & SRR1_MC_IFETCH_MASK) {
case 0:
break;
case SRR1_MC_IFETCH_SLBPAR:
case SRR1_MC_IFETCH_SLBMULTI:
case SRR1_MC_IFETCH_SLBPARMULTI:
reload_slb(vcpu);
break;
case SRR1_MC_IFETCH_TLBMULTI:
tlbiel_all_lpid(vcpu->kvm->arch.radix);
break;
default:
handled = 0;
}
/*
* Now get the event and stash it in the vcpu struct so it can
* be handled by the primary thread in virtual mode. We can't
* call machine_check_queue_event() here if we are running on
* an offline secondary thread.
*/
if (get_mce_event(&mce_evt, MCE_EVENT_RELEASE)) {
if (handled && mce_evt.version == MCE_V1)
mce_evt.disposition = MCE_DISPOSITION_RECOVERED;
} else {
memset(&mce_evt, 0, sizeof(mce_evt));
}
vcpu->arch.mce_evt = mce_evt;
}
void kvmppc_realmode_machine_check(struct kvm_vcpu *vcpu)
{
kvmppc_realmode_mc_power7(vcpu);
}
/* Check if dynamic split is in force and return subcore size accordingly. */
static inline int kvmppc_cur_subcore_size(void)
{
if (local_paca->kvm_hstate.kvm_split_mode)
return local_paca->kvm_hstate.kvm_split_mode->subcore_size;
return threads_per_subcore;
}
void kvmppc_subcore_enter_guest(void)
{
int thread_id, subcore_id;
thread_id = cpu_thread_in_core(local_paca->paca_index);
subcore_id = thread_id / kvmppc_cur_subcore_size();
local_paca->sibling_subcore_state->in_guest[subcore_id] = 1;
}
EXPORT_SYMBOL_GPL(kvmppc_subcore_enter_guest);
void kvmppc_subcore_exit_guest(void)
{
int thread_id, subcore_id;
thread_id = cpu_thread_in_core(local_paca->paca_index);
subcore_id = thread_id / kvmppc_cur_subcore_size();
local_paca->sibling_subcore_state->in_guest[subcore_id] = 0;
}
EXPORT_SYMBOL_GPL(kvmppc_subcore_exit_guest);
static bool kvmppc_tb_resync_required(void)
{
if (test_and_set_bit(CORE_TB_RESYNC_REQ_BIT,
&local_paca->sibling_subcore_state->flags))
return false;
return true;
}
static void kvmppc_tb_resync_done(void)
{
clear_bit(CORE_TB_RESYNC_REQ_BIT,
&local_paca->sibling_subcore_state->flags);
}
/*
* kvmppc_realmode_hmi_handler() is called only by primary thread during
* guest exit path.
*
* There are multiple reasons why HMI could occur, one of them is
* Timebase (TB) error. If this HMI is due to TB error, then TB would
* have been in stopped state. The opal hmi handler Will fix it and
* restore the TB value with host timebase value. For HMI caused due
* to non-TB errors, opal hmi handler will not touch/restore TB register
* and hence there won't be any change in TB value.
*
* Since we are not sure about the cause of this HMI, we can't be sure
* about the content of TB register whether it holds guest or host timebase
* value. Hence the idea is to resync the TB on every HMI, so that we
* know about the exact state of the TB value. Resync TB call will
* restore TB to host timebase.
*
* Things to consider:
* - On TB error, HMI interrupt is reported on all the threads of the core
* that has encountered TB error irrespective of split-core mode.
* - The very first thread on the core that get chance to fix TB error
* would rsync the TB with local chipTOD value.
* - The resync TB is a core level action i.e. it will sync all the TBs
* in that core independent of split-core mode. This means if we trigger
* TB sync from a thread from one subcore, it would affect TB values of
* sibling subcores of the same core.
*
* All threads need to co-ordinate before making opal hmi handler.
* All threads will use sibling_subcore_state->in_guest[] (shared by all
* threads in the core) in paca which holds information about whether
* sibling subcores are in Guest mode or host mode. The in_guest[] array
* is of size MAX_SUBCORE_PER_CORE=4, indexed using subcore id to set/unset
* subcore status. Only primary threads from each subcore is responsible
* to set/unset its designated array element while entering/exiting the
* guset.
*
* After invoking opal hmi handler call, one of the thread (of entire core)
* will need to resync the TB. Bit 63 from subcore state bitmap flags
* (sibling_subcore_state->flags) will be used to co-ordinate between
* primary threads to decide who takes up the responsibility.
*
* This is what we do:
* - Primary thread from each subcore tries to set resync required bit[63]
* of paca->sibling_subcore_state->flags.
* - The first primary thread that is able to set the flag takes the
* responsibility of TB resync. (Let us call it as thread leader)
* - All other threads which are in host will call
* wait_for_subcore_guest_exit() and wait for in_guest[0-3] from
* paca->sibling_subcore_state to get cleared.
* - All the primary thread will clear its subcore status from subcore
* state in_guest[] array respectively.
* - Once all primary threads clear in_guest[0-3], all of them will invoke
* opal hmi handler.
* - Now all threads will wait for TB resync to complete by invoking
* wait_for_tb_resync() except the thread leader.
* - Thread leader will do a TB resync by invoking opal_resync_timebase()
* call and the it will clear the resync required bit.
* - All other threads will now come out of resync wait loop and proceed
* with individual execution.
* - On return of this function, primary thread will signal all
* secondary threads to proceed.
* - All secondary threads will eventually call opal hmi handler on
* their exit path.
*
* Returns 1 if the timebase offset should be applied, 0 if not.
*/
long kvmppc_realmode_hmi_handler(void)
{
bool resync_req;
__this_cpu_inc(irq_stat.hmi_exceptions);
if (hmi_handle_debugtrig(NULL) >= 0)
return 1;
/*
* By now primary thread has already completed guest->host
* partition switch but haven't signaled secondaries yet.
* All the secondary threads on this subcore is waiting
* for primary thread to signal them to go ahead.
*
* For threads from subcore which isn't in guest, they all will
* wait until all other subcores on this core exit the guest.
*
* Now set the resync required bit. If you are the first to
* set this bit then kvmppc_tb_resync_required() function will
* return true. For rest all other subcores
* kvmppc_tb_resync_required() will return false.
*
* If resync_req == true, then this thread is responsible to
* initiate TB resync after hmi handler has completed.
* All other threads on this core will wait until this thread
* clears the resync required bit flag.
*/
resync_req = kvmppc_tb_resync_required();
/* Reset the subcore status to indicate it has exited guest */
kvmppc_subcore_exit_guest();
/*
* Wait for other subcores on this core to exit the guest.
* All the primary threads and threads from subcore that are
* not in guest will wait here until all subcores are out
* of guest context.
*/
wait_for_subcore_guest_exit();
/*
* At this point we are sure that primary threads from each
* subcore on this core have completed guest->host partition
* switch. Now it is safe to call HMI handler.
*/
if (ppc_md.hmi_exception_early)
ppc_md.hmi_exception_early(NULL);
/*
* Check if this thread is responsible to resync TB.
* All other threads will wait until this thread completes the
* TB resync.
*/
if (resync_req) {
opal_resync_timebase();
/* Reset TB resync req bit */
kvmppc_tb_resync_done();
} else {
wait_for_tb_resync();
}
/*
* Reset tb_offset_applied so the guest exit code won't try
* to subtract the previous timebase offset from the timebase.
*/
if (local_paca->kvm_hstate.kvm_vcore)
local_paca->kvm_hstate.kvm_vcore->tb_offset_applied = 0;
return 0;
}
| gpl-2.0 |
VincenzoDo/my-kernel | drivers/media/radio/saa7706h.c | 1668 | 12186 | /*
* saa7706.c Philips SAA7706H Car Radio DSP driver
* Copyright (c) 2009 Intel Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ctrls.h>
#define DRIVER_NAME "saa7706h"
/* the I2C memory map looks like this
$1C00 - $FFFF Not Used
$2200 - $3FFF Reserved YRAM (DSP2) space
$2000 - $21FF YRAM (DSP2)
$1FF0 - $1FFF Hardware Registers
$1280 - $1FEF Reserved XRAM (DSP2) space
$1000 - $127F XRAM (DSP2)
$0FFF DSP CONTROL
$0A00 - $0FFE Reserved
$0980 - $09FF Reserved YRAM (DSP1) space
$0800 - $097F YRAM (DSP1)
$0200 - $07FF Not Used
$0180 - $01FF Reserved XRAM (DSP1) space
$0000 - $017F XRAM (DSP1)
*/
#define SAA7706H_REG_CTRL 0x0fff
#define SAA7706H_CTRL_BYP_PLL 0x0001
#define SAA7706H_CTRL_PLL_DIV_MASK 0x003e
#define SAA7706H_CTRL_PLL3_62975MHZ 0x003e
#define SAA7706H_CTRL_DSP_TURBO 0x0040
#define SAA7706H_CTRL_PC_RESET_DSP1 0x0080
#define SAA7706H_CTRL_PC_RESET_DSP2 0x0100
#define SAA7706H_CTRL_DSP1_ROM_EN_MASK 0x0600
#define SAA7706H_CTRL_DSP1_FUNC_PROM 0x0000
#define SAA7706H_CTRL_DSP2_ROM_EN_MASK 0x1800
#define SAA7706H_CTRL_DSP2_FUNC_PROM 0x0000
#define SAA7706H_CTRL_DIG_SIL_INTERPOL 0x8000
#define SAA7706H_REG_EVALUATION 0x1ff0
#define SAA7706H_EVAL_DISABLE_CHARGE_PUMP 0x000001
#define SAA7706H_EVAL_DCS_CLOCK 0x000002
#define SAA7706H_EVAL_GNDRC1_ENABLE 0x000004
#define SAA7706H_EVAL_GNDRC2_ENABLE 0x000008
#define SAA7706H_REG_CL_GEN1 0x1ff3
#define SAA7706H_CL_GEN1_MIN_LOOPGAIN_MASK 0x00000f
#define SAA7706H_CL_GEN1_LOOPGAIN_MASK 0x0000f0
#define SAA7706H_CL_GEN1_COARSE_RATION 0xffff00
#define SAA7706H_REG_CL_GEN2 0x1ff4
#define SAA7706H_CL_GEN2_WSEDGE_FALLING 0x000001
#define SAA7706H_CL_GEN2_STOP_VCO 0x000002
#define SAA7706H_CL_GEN2_FRERUN 0x000004
#define SAA7706H_CL_GEN2_ADAPTIVE 0x000008
#define SAA7706H_CL_GEN2_FINE_RATIO_MASK 0x0ffff0
#define SAA7706H_REG_CL_GEN4 0x1ff6
#define SAA7706H_CL_GEN4_BYPASS_PLL1 0x001000
#define SAA7706H_CL_GEN4_PLL1_DIV_MASK 0x03e000
#define SAA7706H_CL_GEN4_DSP1_TURBO 0x040000
#define SAA7706H_REG_SEL 0x1ff7
#define SAA7706H_SEL_DSP2_SRCA_MASK 0x000007
#define SAA7706H_SEL_DSP2_FMTA_MASK 0x000031
#define SAA7706H_SEL_DSP2_SRCB_MASK 0x0001c0
#define SAA7706H_SEL_DSP2_FMTB_MASK 0x000e00
#define SAA7706H_SEL_DSP1_SRC_MASK 0x003000
#define SAA7706H_SEL_DSP1_FMT_MASK 0x01c003
#define SAA7706H_SEL_SPDIF2 0x020000
#define SAA7706H_SEL_HOST_IO_FMT_MASK 0x1c0000
#define SAA7706H_SEL_EN_HOST_IO 0x200000
#define SAA7706H_REG_IAC 0x1ff8
#define SAA7706H_REG_CLK_SET 0x1ff9
#define SAA7706H_REG_CLK_COEFF 0x1ffa
#define SAA7706H_REG_INPUT_SENS 0x1ffb
#define SAA7706H_INPUT_SENS_RDS_VOL_MASK 0x0003f
#define SAA7706H_INPUT_SENS_FM_VOL_MASK 0x00fc0
#define SAA7706H_INPUT_SENS_FM_MPX 0x01000
#define SAA7706H_INPUT_SENS_OFF_FILTER_A_EN 0x02000
#define SAA7706H_INPUT_SENS_OFF_FILTER_B_EN 0x04000
#define SAA7706H_REG_PHONE_NAV_AUDIO 0x1ffc
#define SAA7706H_REG_IO_CONF_DSP2 0x1ffd
#define SAA7706H_REG_STATUS_DSP2 0x1ffe
#define SAA7706H_REG_PC_DSP2 0x1fff
#define SAA7706H_DSP1_MOD0 0x0800
#define SAA7706H_DSP1_ROM_VER 0x097f
#define SAA7706H_DSP2_MPTR0 0x1000
#define SAA7706H_DSP1_MODPNTR 0x0000
#define SAA7706H_DSP2_XMEM_CONTLLCW 0x113e
#define SAA7706H_DSP2_XMEM_BUSAMP 0x114a
#define SAA7706H_DSP2_XMEM_FDACPNTR 0x11f9
#define SAA7706H_DSP2_XMEM_IIS1PNTR 0x11fb
#define SAA7706H_DSP2_YMEM_PVGA 0x212a
#define SAA7706H_DSP2_YMEM_PVAT1 0x212b
#define SAA7706H_DSP2_YMEM_PVAT 0x212c
#define SAA7706H_DSP2_YMEM_ROM_VER 0x21ff
#define SUPPORTED_DSP1_ROM_VER 0x667
struct saa7706h_state {
struct v4l2_subdev sd;
struct v4l2_ctrl_handler hdl;
unsigned muted;
};
static inline struct saa7706h_state *to_state(struct v4l2_subdev *sd)
{
return container_of(sd, struct saa7706h_state, sd);
}
static int saa7706h_i2c_send(struct i2c_client *client, const u8 *data, int len)
{
int err = i2c_master_send(client, data, len);
if (err == len)
return 0;
return err > 0 ? -EIO : err;
}
static int saa7706h_i2c_transfer(struct i2c_client *client,
struct i2c_msg *msgs, int num)
{
int err = i2c_transfer(client->adapter, msgs, num);
if (err == num)
return 0;
return err > 0 ? -EIO : err;
}
static int saa7706h_set_reg24(struct v4l2_subdev *sd, u16 reg, u32 val)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
u8 buf[5];
int pos = 0;
buf[pos++] = reg >> 8;
buf[pos++] = reg;
buf[pos++] = val >> 16;
buf[pos++] = val >> 8;
buf[pos++] = val;
return saa7706h_i2c_send(client, buf, pos);
}
static int saa7706h_set_reg24_err(struct v4l2_subdev *sd, u16 reg, u32 val,
int *err)
{
return *err ? *err : saa7706h_set_reg24(sd, reg, val);
}
static int saa7706h_set_reg16(struct v4l2_subdev *sd, u16 reg, u16 val)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
u8 buf[4];
int pos = 0;
buf[pos++] = reg >> 8;
buf[pos++] = reg;
buf[pos++] = val >> 8;
buf[pos++] = val;
return saa7706h_i2c_send(client, buf, pos);
}
static int saa7706h_set_reg16_err(struct v4l2_subdev *sd, u16 reg, u16 val,
int *err)
{
return *err ? *err : saa7706h_set_reg16(sd, reg, val);
}
static int saa7706h_get_reg16(struct v4l2_subdev *sd, u16 reg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
u8 buf[2];
int err;
u8 regaddr[] = {reg >> 8, reg};
struct i2c_msg msg[] = {
{
.addr = client->addr,
.len = sizeof(regaddr),
.buf = regaddr
},
{
.addr = client->addr,
.flags = I2C_M_RD,
.len = sizeof(buf),
.buf = buf
}
};
err = saa7706h_i2c_transfer(client, msg, ARRAY_SIZE(msg));
if (err)
return err;
return buf[0] << 8 | buf[1];
}
static int saa7706h_unmute(struct v4l2_subdev *sd)
{
struct saa7706h_state *state = to_state(sd);
int err = 0;
err = saa7706h_set_reg16_err(sd, SAA7706H_REG_CTRL,
SAA7706H_CTRL_PLL3_62975MHZ | SAA7706H_CTRL_PC_RESET_DSP1 |
SAA7706H_CTRL_PC_RESET_DSP2, &err);
/* newer versions of the chip requires a small sleep after reset */
msleep(1);
err = saa7706h_set_reg16_err(sd, SAA7706H_REG_CTRL,
SAA7706H_CTRL_PLL3_62975MHZ, &err);
err = saa7706h_set_reg24_err(sd, SAA7706H_REG_EVALUATION, 0, &err);
err = saa7706h_set_reg24_err(sd, SAA7706H_REG_CL_GEN1, 0x040022, &err);
err = saa7706h_set_reg24_err(sd, SAA7706H_REG_CL_GEN2,
SAA7706H_CL_GEN2_WSEDGE_FALLING, &err);
err = saa7706h_set_reg24_err(sd, SAA7706H_REG_CL_GEN4, 0x024080, &err);
err = saa7706h_set_reg24_err(sd, SAA7706H_REG_SEL, 0x200080, &err);
err = saa7706h_set_reg24_err(sd, SAA7706H_REG_IAC, 0xf4caed, &err);
err = saa7706h_set_reg24_err(sd, SAA7706H_REG_CLK_SET, 0x124334, &err);
err = saa7706h_set_reg24_err(sd, SAA7706H_REG_CLK_COEFF, 0x004a1a,
&err);
err = saa7706h_set_reg24_err(sd, SAA7706H_REG_INPUT_SENS, 0x0071c7,
&err);
err = saa7706h_set_reg24_err(sd, SAA7706H_REG_PHONE_NAV_AUDIO,
0x0e22ff, &err);
err = saa7706h_set_reg24_err(sd, SAA7706H_REG_IO_CONF_DSP2, 0x001ff8,
&err);
err = saa7706h_set_reg24_err(sd, SAA7706H_REG_STATUS_DSP2, 0x080003,
&err);
err = saa7706h_set_reg24_err(sd, SAA7706H_REG_PC_DSP2, 0x000004, &err);
err = saa7706h_set_reg16_err(sd, SAA7706H_DSP1_MOD0, 0x0c6c, &err);
err = saa7706h_set_reg24_err(sd, SAA7706H_DSP2_MPTR0, 0x000b4b, &err);
err = saa7706h_set_reg24_err(sd, SAA7706H_DSP1_MODPNTR, 0x000600, &err);
err = saa7706h_set_reg24_err(sd, SAA7706H_DSP1_MODPNTR, 0x0000c0, &err);
err = saa7706h_set_reg24_err(sd, SAA7706H_DSP2_XMEM_CONTLLCW, 0x000819,
&err);
err = saa7706h_set_reg24_err(sd, SAA7706H_DSP2_XMEM_CONTLLCW, 0x00085a,
&err);
err = saa7706h_set_reg24_err(sd, SAA7706H_DSP2_XMEM_BUSAMP, 0x7fffff,
&err);
err = saa7706h_set_reg24_err(sd, SAA7706H_DSP2_XMEM_FDACPNTR, 0x2000cb,
&err);
err = saa7706h_set_reg24_err(sd, SAA7706H_DSP2_XMEM_IIS1PNTR, 0x2000cb,
&err);
err = saa7706h_set_reg16_err(sd, SAA7706H_DSP2_YMEM_PVGA, 0x0f80, &err);
err = saa7706h_set_reg16_err(sd, SAA7706H_DSP2_YMEM_PVAT1, 0x0800,
&err);
err = saa7706h_set_reg16_err(sd, SAA7706H_DSP2_YMEM_PVAT, 0x0800, &err);
err = saa7706h_set_reg24_err(sd, SAA7706H_DSP2_XMEM_CONTLLCW, 0x000905,
&err);
if (!err)
state->muted = 0;
return err;
}
static int saa7706h_mute(struct v4l2_subdev *sd)
{
struct saa7706h_state *state = to_state(sd);
int err;
err = saa7706h_set_reg16(sd, SAA7706H_REG_CTRL,
SAA7706H_CTRL_PLL3_62975MHZ | SAA7706H_CTRL_PC_RESET_DSP1 |
SAA7706H_CTRL_PC_RESET_DSP2);
if (!err)
state->muted = 1;
return err;
}
static int saa7706h_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct saa7706h_state *state =
container_of(ctrl->handler, struct saa7706h_state, hdl);
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
if (ctrl->val)
return saa7706h_mute(&state->sd);
return saa7706h_unmute(&state->sd);
}
return -EINVAL;
}
static const struct v4l2_ctrl_ops saa7706h_ctrl_ops = {
.s_ctrl = saa7706h_s_ctrl,
};
static const struct v4l2_subdev_core_ops saa7706h_core_ops = {
.g_ext_ctrls = v4l2_subdev_g_ext_ctrls,
.try_ext_ctrls = v4l2_subdev_try_ext_ctrls,
.s_ext_ctrls = v4l2_subdev_s_ext_ctrls,
.g_ctrl = v4l2_subdev_g_ctrl,
.s_ctrl = v4l2_subdev_s_ctrl,
.queryctrl = v4l2_subdev_queryctrl,
.querymenu = v4l2_subdev_querymenu,
};
static const struct v4l2_subdev_ops saa7706h_ops = {
.core = &saa7706h_core_ops,
};
/*
* Generic i2c probe
* concerning the addresses: i2c wants 7 bit (without the r/w bit), so '>>1'
*/
static int saa7706h_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct saa7706h_state *state;
struct v4l2_subdev *sd;
int err;
/* Check if the adapter supports the needed features */
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -EIO;
v4l_info(client, "chip found @ 0x%02x (%s)\n",
client->addr << 1, client->adapter->name);
state = kzalloc(sizeof(struct saa7706h_state), GFP_KERNEL);
if (state == NULL)
return -ENOMEM;
sd = &state->sd;
v4l2_i2c_subdev_init(sd, client, &saa7706h_ops);
v4l2_ctrl_handler_init(&state->hdl, 4);
v4l2_ctrl_new_std(&state->hdl, &saa7706h_ctrl_ops,
V4L2_CID_AUDIO_MUTE, 0, 1, 1, 1);
sd->ctrl_handler = &state->hdl;
err = state->hdl.error;
if (err)
goto err;
/* check the rom versions */
err = saa7706h_get_reg16(sd, SAA7706H_DSP1_ROM_VER);
if (err < 0)
goto err;
if (err != SUPPORTED_DSP1_ROM_VER)
v4l2_warn(sd, "Unknown DSP1 ROM code version: 0x%x\n", err);
state->muted = 1;
/* startup in a muted state */
err = saa7706h_mute(sd);
if (err)
goto err;
return 0;
err:
v4l2_device_unregister_subdev(sd);
v4l2_ctrl_handler_free(&state->hdl);
kfree(to_state(sd));
printk(KERN_ERR DRIVER_NAME ": Failed to probe: %d\n", err);
return err;
}
static int saa7706h_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
struct saa7706h_state *state = to_state(sd);
saa7706h_mute(sd);
v4l2_device_unregister_subdev(sd);
v4l2_ctrl_handler_free(&state->hdl);
kfree(to_state(sd));
return 0;
}
static const struct i2c_device_id saa7706h_id[] = {
{DRIVER_NAME, 0},
{},
};
MODULE_DEVICE_TABLE(i2c, saa7706h_id);
static struct i2c_driver saa7706h_driver = {
.driver = {
.owner = THIS_MODULE,
.name = DRIVER_NAME,
},
.probe = saa7706h_probe,
.remove = saa7706h_remove,
.id_table = saa7706h_id,
};
module_i2c_driver(saa7706h_driver);
MODULE_DESCRIPTION("SAA7706H Car Radio DSP driver");
MODULE_AUTHOR("Mocean Laboratories");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
ISTweak/android_kernel_sharp_is05 | arch/arm/mach-at91/board-eb9200.c | 1668 | 3461 | /*
* linux/arch/arm/mach-at91/board-eb9200.c
*
* Copyright (C) 2005 SAN People, adapted for ATEB9200 from Embest
* by Andrew Patrikalakis
*
* 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/types.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/device.h>
#include <mach/hardware.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <asm/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/board.h>
#include <mach/gpio.h>
#include "generic.h"
static void __init eb9200_map_io(void)
{
/* Initialize processor: 18.432 MHz crystal */
at91rm9200_initialize(18432000, AT91RM9200_BGA);
/* DBGU on ttyS0. (Rx & Tx only) */
at91_register_uart(0, 0, 0);
/* USART1 on ttyS1. (Rx, Tx, CTS, RTS, DTR, DSR, DCD, RI) */
at91_register_uart(AT91RM9200_ID_US1, 1, ATMEL_UART_CTS | ATMEL_UART_RTS
| ATMEL_UART_DTR | ATMEL_UART_DSR | ATMEL_UART_DCD
| ATMEL_UART_RI);
/* USART2 on ttyS2. (Rx, Tx) - IRDA */
at91_register_uart(AT91RM9200_ID_US2, 2, 0);
/* set serial console to ttyS0 (ie, DBGU) */
at91_set_serial_console(0);
}
static void __init eb9200_init_irq(void)
{
at91rm9200_init_interrupts(NULL);
}
static struct at91_eth_data __initdata eb9200_eth_data = {
.phy_irq_pin = AT91_PIN_PC4,
.is_rmii = 1,
};
static struct at91_usbh_data __initdata eb9200_usbh_data = {
.ports = 2,
};
static struct at91_udc_data __initdata eb9200_udc_data = {
.vbus_pin = AT91_PIN_PD4,
.pullup_pin = AT91_PIN_PD5,
};
static struct at91_cf_data __initdata eb9200_cf_data = {
.det_pin = AT91_PIN_PB0,
.rst_pin = AT91_PIN_PC5,
// .irq_pin = ... not connected
// .vcc_pin = ... always powered
};
static struct at91_mmc_data __initdata eb9200_mmc_data = {
.slot_b = 0,
.wire4 = 1,
};
static struct i2c_board_info __initdata eb9200_i2c_devices[] = {
{
I2C_BOARD_INFO("24c512", 0x50),
},
};
static void __init eb9200_board_init(void)
{
/* Serial */
at91_add_device_serial();
/* Ethernet */
at91_add_device_eth(&eb9200_eth_data);
/* USB Host */
at91_add_device_usbh(&eb9200_usbh_data);
/* USB Device */
at91_add_device_udc(&eb9200_udc_data);
/* I2C */
at91_add_device_i2c(eb9200_i2c_devices, ARRAY_SIZE(eb9200_i2c_devices));
/* Compact Flash */
at91_add_device_cf(&eb9200_cf_data);
/* SPI */
at91_add_device_spi(NULL, 0);
/* MMC */
/* only supports 1 or 4 bit interface, not wired through to SPI */
at91_add_device_mmc(0, &eb9200_mmc_data);
}
MACHINE_START(ATEB9200, "Embest ATEB9200")
.phys_io = AT91_BASE_SYS,
.io_pg_offst = (AT91_VA_BASE_SYS >> 18) & 0xfffc,
.boot_params = AT91_SDRAM_BASE + 0x100,
.timer = &at91rm9200_timer,
.map_io = eb9200_map_io,
.init_irq = eb9200_init_irq,
.init_machine = eb9200_board_init,
MACHINE_END
| gpl-2.0 |
shuiqingliu/android_kernel_lenovo_stuttgart | arch/powerpc/sysdev/qe_lib/qe_ic.c | 2180 | 11868 | /*
* arch/powerpc/sysdev/qe_lib/qe_ic.c
*
* Copyright (C) 2006 Freescale Semicondutor, Inc. All rights reserved.
*
* Author: Li Yang <leoli@freescale.com>
* Based on code from Shlomi Gridish <gridish@freescale.com>
*
* QUICC ENGINE Interrupt Controller
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/reboot.h>
#include <linux/slab.h>
#include <linux/stddef.h>
#include <linux/sched.h>
#include <linux/signal.h>
#include <linux/sysdev.h>
#include <linux/device.h>
#include <linux/bootmem.h>
#include <linux/spinlock.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/prom.h>
#include <asm/qe_ic.h>
#include "qe_ic.h"
static DEFINE_RAW_SPINLOCK(qe_ic_lock);
static struct qe_ic_info qe_ic_info[] = {
[1] = {
.mask = 0x00008000,
.mask_reg = QEIC_CIMR,
.pri_code = 0,
.pri_reg = QEIC_CIPWCC,
},
[2] = {
.mask = 0x00004000,
.mask_reg = QEIC_CIMR,
.pri_code = 1,
.pri_reg = QEIC_CIPWCC,
},
[3] = {
.mask = 0x00002000,
.mask_reg = QEIC_CIMR,
.pri_code = 2,
.pri_reg = QEIC_CIPWCC,
},
[10] = {
.mask = 0x00000040,
.mask_reg = QEIC_CIMR,
.pri_code = 1,
.pri_reg = QEIC_CIPZCC,
},
[11] = {
.mask = 0x00000020,
.mask_reg = QEIC_CIMR,
.pri_code = 2,
.pri_reg = QEIC_CIPZCC,
},
[12] = {
.mask = 0x00000010,
.mask_reg = QEIC_CIMR,
.pri_code = 3,
.pri_reg = QEIC_CIPZCC,
},
[13] = {
.mask = 0x00000008,
.mask_reg = QEIC_CIMR,
.pri_code = 4,
.pri_reg = QEIC_CIPZCC,
},
[14] = {
.mask = 0x00000004,
.mask_reg = QEIC_CIMR,
.pri_code = 5,
.pri_reg = QEIC_CIPZCC,
},
[15] = {
.mask = 0x00000002,
.mask_reg = QEIC_CIMR,
.pri_code = 6,
.pri_reg = QEIC_CIPZCC,
},
[20] = {
.mask = 0x10000000,
.mask_reg = QEIC_CRIMR,
.pri_code = 3,
.pri_reg = QEIC_CIPRTA,
},
[25] = {
.mask = 0x00800000,
.mask_reg = QEIC_CRIMR,
.pri_code = 0,
.pri_reg = QEIC_CIPRTB,
},
[26] = {
.mask = 0x00400000,
.mask_reg = QEIC_CRIMR,
.pri_code = 1,
.pri_reg = QEIC_CIPRTB,
},
[27] = {
.mask = 0x00200000,
.mask_reg = QEIC_CRIMR,
.pri_code = 2,
.pri_reg = QEIC_CIPRTB,
},
[28] = {
.mask = 0x00100000,
.mask_reg = QEIC_CRIMR,
.pri_code = 3,
.pri_reg = QEIC_CIPRTB,
},
[32] = {
.mask = 0x80000000,
.mask_reg = QEIC_CIMR,
.pri_code = 0,
.pri_reg = QEIC_CIPXCC,
},
[33] = {
.mask = 0x40000000,
.mask_reg = QEIC_CIMR,
.pri_code = 1,
.pri_reg = QEIC_CIPXCC,
},
[34] = {
.mask = 0x20000000,
.mask_reg = QEIC_CIMR,
.pri_code = 2,
.pri_reg = QEIC_CIPXCC,
},
[35] = {
.mask = 0x10000000,
.mask_reg = QEIC_CIMR,
.pri_code = 3,
.pri_reg = QEIC_CIPXCC,
},
[36] = {
.mask = 0x08000000,
.mask_reg = QEIC_CIMR,
.pri_code = 4,
.pri_reg = QEIC_CIPXCC,
},
[40] = {
.mask = 0x00800000,
.mask_reg = QEIC_CIMR,
.pri_code = 0,
.pri_reg = QEIC_CIPYCC,
},
[41] = {
.mask = 0x00400000,
.mask_reg = QEIC_CIMR,
.pri_code = 1,
.pri_reg = QEIC_CIPYCC,
},
[42] = {
.mask = 0x00200000,
.mask_reg = QEIC_CIMR,
.pri_code = 2,
.pri_reg = QEIC_CIPYCC,
},
[43] = {
.mask = 0x00100000,
.mask_reg = QEIC_CIMR,
.pri_code = 3,
.pri_reg = QEIC_CIPYCC,
},
};
static inline u32 qe_ic_read(volatile __be32 __iomem * base, unsigned int reg)
{
return in_be32(base + (reg >> 2));
}
static inline void qe_ic_write(volatile __be32 __iomem * base, unsigned int reg,
u32 value)
{
out_be32(base + (reg >> 2), value);
}
static inline struct qe_ic *qe_ic_from_irq(unsigned int virq)
{
return irq_get_chip_data(virq);
}
static inline struct qe_ic *qe_ic_from_irq_data(struct irq_data *d)
{
return irq_data_get_irq_chip_data(d);
}
static void qe_ic_unmask_irq(struct irq_data *d)
{
struct qe_ic *qe_ic = qe_ic_from_irq_data(d);
unsigned int src = irqd_to_hwirq(d);
unsigned long flags;
u32 temp;
raw_spin_lock_irqsave(&qe_ic_lock, flags);
temp = qe_ic_read(qe_ic->regs, qe_ic_info[src].mask_reg);
qe_ic_write(qe_ic->regs, qe_ic_info[src].mask_reg,
temp | qe_ic_info[src].mask);
raw_spin_unlock_irqrestore(&qe_ic_lock, flags);
}
static void qe_ic_mask_irq(struct irq_data *d)
{
struct qe_ic *qe_ic = qe_ic_from_irq_data(d);
unsigned int src = irqd_to_hwirq(d);
unsigned long flags;
u32 temp;
raw_spin_lock_irqsave(&qe_ic_lock, flags);
temp = qe_ic_read(qe_ic->regs, qe_ic_info[src].mask_reg);
qe_ic_write(qe_ic->regs, qe_ic_info[src].mask_reg,
temp & ~qe_ic_info[src].mask);
/* Flush the above write before enabling interrupts; otherwise,
* spurious interrupts will sometimes happen. To be 100% sure
* that the write has reached the device before interrupts are
* enabled, the mask register would have to be read back; however,
* this is not required for correctness, only to avoid wasting
* time on a large number of spurious interrupts. In testing,
* a sync reduced the observed spurious interrupts to zero.
*/
mb();
raw_spin_unlock_irqrestore(&qe_ic_lock, flags);
}
static struct irq_chip qe_ic_irq_chip = {
.name = "QEIC",
.irq_unmask = qe_ic_unmask_irq,
.irq_mask = qe_ic_mask_irq,
.irq_mask_ack = qe_ic_mask_irq,
};
static int qe_ic_host_match(struct irq_host *h, struct device_node *node)
{
/* Exact match, unless qe_ic node is NULL */
return h->of_node == NULL || h->of_node == node;
}
static int qe_ic_host_map(struct irq_host *h, unsigned int virq,
irq_hw_number_t hw)
{
struct qe_ic *qe_ic = h->host_data;
struct irq_chip *chip;
if (qe_ic_info[hw].mask == 0) {
printk(KERN_ERR "Can't map reserved IRQ\n");
return -EINVAL;
}
/* Default chip */
chip = &qe_ic->hc_irq;
irq_set_chip_data(virq, qe_ic);
irq_set_status_flags(virq, IRQ_LEVEL);
irq_set_chip_and_handler(virq, chip, handle_level_irq);
return 0;
}
static int qe_ic_host_xlate(struct irq_host *h, struct device_node *ct,
const u32 * intspec, unsigned int intsize,
irq_hw_number_t * out_hwirq,
unsigned int *out_flags)
{
*out_hwirq = intspec[0];
if (intsize > 1)
*out_flags = intspec[1];
else
*out_flags = IRQ_TYPE_NONE;
return 0;
}
static struct irq_host_ops qe_ic_host_ops = {
.match = qe_ic_host_match,
.map = qe_ic_host_map,
.xlate = qe_ic_host_xlate,
};
/* Return an interrupt vector or NO_IRQ if no interrupt is pending. */
unsigned int qe_ic_get_low_irq(struct qe_ic *qe_ic)
{
int irq;
BUG_ON(qe_ic == NULL);
/* get the interrupt source vector. */
irq = qe_ic_read(qe_ic->regs, QEIC_CIVEC) >> 26;
if (irq == 0)
return NO_IRQ;
return irq_linear_revmap(qe_ic->irqhost, irq);
}
/* Return an interrupt vector or NO_IRQ if no interrupt is pending. */
unsigned int qe_ic_get_high_irq(struct qe_ic *qe_ic)
{
int irq;
BUG_ON(qe_ic == NULL);
/* get the interrupt source vector. */
irq = qe_ic_read(qe_ic->regs, QEIC_CHIVEC) >> 26;
if (irq == 0)
return NO_IRQ;
return irq_linear_revmap(qe_ic->irqhost, irq);
}
void __init qe_ic_init(struct device_node *node, unsigned int flags,
void (*low_handler)(unsigned int irq, struct irq_desc *desc),
void (*high_handler)(unsigned int irq, struct irq_desc *desc))
{
struct qe_ic *qe_ic;
struct resource res;
u32 temp = 0, ret, high_active = 0;
ret = of_address_to_resource(node, 0, &res);
if (ret)
return;
qe_ic = kzalloc(sizeof(*qe_ic), GFP_KERNEL);
if (qe_ic == NULL)
return;
qe_ic->irqhost = irq_alloc_host(node, IRQ_HOST_MAP_LINEAR,
NR_QE_IC_INTS, &qe_ic_host_ops, 0);
if (qe_ic->irqhost == NULL) {
kfree(qe_ic);
return;
}
qe_ic->regs = ioremap(res.start, res.end - res.start + 1);
qe_ic->irqhost->host_data = qe_ic;
qe_ic->hc_irq = qe_ic_irq_chip;
qe_ic->virq_high = irq_of_parse_and_map(node, 0);
qe_ic->virq_low = irq_of_parse_and_map(node, 1);
if (qe_ic->virq_low == NO_IRQ) {
printk(KERN_ERR "Failed to map QE_IC low IRQ\n");
kfree(qe_ic);
return;
}
/* default priority scheme is grouped. If spread mode is */
/* required, configure cicr accordingly. */
if (flags & QE_IC_SPREADMODE_GRP_W)
temp |= CICR_GWCC;
if (flags & QE_IC_SPREADMODE_GRP_X)
temp |= CICR_GXCC;
if (flags & QE_IC_SPREADMODE_GRP_Y)
temp |= CICR_GYCC;
if (flags & QE_IC_SPREADMODE_GRP_Z)
temp |= CICR_GZCC;
if (flags & QE_IC_SPREADMODE_GRP_RISCA)
temp |= CICR_GRTA;
if (flags & QE_IC_SPREADMODE_GRP_RISCB)
temp |= CICR_GRTB;
/* choose destination signal for highest priority interrupt */
if (flags & QE_IC_HIGH_SIGNAL) {
temp |= (SIGNAL_HIGH << CICR_HPIT_SHIFT);
high_active = 1;
}
qe_ic_write(qe_ic->regs, QEIC_CICR, temp);
irq_set_handler_data(qe_ic->virq_low, qe_ic);
irq_set_chained_handler(qe_ic->virq_low, low_handler);
if (qe_ic->virq_high != NO_IRQ &&
qe_ic->virq_high != qe_ic->virq_low) {
irq_set_handler_data(qe_ic->virq_high, qe_ic);
irq_set_chained_handler(qe_ic->virq_high, high_handler);
}
}
void qe_ic_set_highest_priority(unsigned int virq, int high)
{
struct qe_ic *qe_ic = qe_ic_from_irq(virq);
unsigned int src = virq_to_hw(virq);
u32 temp = 0;
temp = qe_ic_read(qe_ic->regs, QEIC_CICR);
temp &= ~CICR_HP_MASK;
temp |= src << CICR_HP_SHIFT;
temp &= ~CICR_HPIT_MASK;
temp |= (high ? SIGNAL_HIGH : SIGNAL_LOW) << CICR_HPIT_SHIFT;
qe_ic_write(qe_ic->regs, QEIC_CICR, temp);
}
/* Set Priority level within its group, from 1 to 8 */
int qe_ic_set_priority(unsigned int virq, unsigned int priority)
{
struct qe_ic *qe_ic = qe_ic_from_irq(virq);
unsigned int src = virq_to_hw(virq);
u32 temp;
if (priority > 8 || priority == 0)
return -EINVAL;
if (src > 127)
return -EINVAL;
if (qe_ic_info[src].pri_reg == 0)
return -EINVAL;
temp = qe_ic_read(qe_ic->regs, qe_ic_info[src].pri_reg);
if (priority < 4) {
temp &= ~(0x7 << (32 - priority * 3));
temp |= qe_ic_info[src].pri_code << (32 - priority * 3);
} else {
temp &= ~(0x7 << (24 - priority * 3));
temp |= qe_ic_info[src].pri_code << (24 - priority * 3);
}
qe_ic_write(qe_ic->regs, qe_ic_info[src].pri_reg, temp);
return 0;
}
/* Set a QE priority to use high irq, only priority 1~2 can use high irq */
int qe_ic_set_high_priority(unsigned int virq, unsigned int priority, int high)
{
struct qe_ic *qe_ic = qe_ic_from_irq(virq);
unsigned int src = virq_to_hw(virq);
u32 temp, control_reg = QEIC_CICNR, shift = 0;
if (priority > 2 || priority == 0)
return -EINVAL;
switch (qe_ic_info[src].pri_reg) {
case QEIC_CIPZCC:
shift = CICNR_ZCC1T_SHIFT;
break;
case QEIC_CIPWCC:
shift = CICNR_WCC1T_SHIFT;
break;
case QEIC_CIPYCC:
shift = CICNR_YCC1T_SHIFT;
break;
case QEIC_CIPXCC:
shift = CICNR_XCC1T_SHIFT;
break;
case QEIC_CIPRTA:
shift = CRICR_RTA1T_SHIFT;
control_reg = QEIC_CRICR;
break;
case QEIC_CIPRTB:
shift = CRICR_RTB1T_SHIFT;
control_reg = QEIC_CRICR;
break;
default:
return -EINVAL;
}
shift += (2 - priority) * 2;
temp = qe_ic_read(qe_ic->regs, control_reg);
temp &= ~(SIGNAL_MASK << shift);
temp |= (high ? SIGNAL_HIGH : SIGNAL_LOW) << shift;
qe_ic_write(qe_ic->regs, control_reg, temp);
return 0;
}
static struct sysdev_class qe_ic_sysclass = {
.name = "qe_ic",
};
static struct sys_device device_qe_ic = {
.id = 0,
.cls = &qe_ic_sysclass,
};
static int __init init_qe_ic_sysfs(void)
{
int rc;
printk(KERN_DEBUG "Registering qe_ic with sysfs...\n");
rc = sysdev_class_register(&qe_ic_sysclass);
if (rc) {
printk(KERN_ERR "Failed registering qe_ic sys class\n");
return -ENODEV;
}
rc = sysdev_register(&device_qe_ic);
if (rc) {
printk(KERN_ERR "Failed registering qe_ic sys device\n");
return -ENODEV;
}
return 0;
}
subsys_initcall(init_qe_ic_sysfs);
| gpl-2.0 |
prasidh09/cse506 | unionfs-3.10.y/drivers/net/ethernet/sfc/mcdi.c | 2180 | 32563 | /****************************************************************************
* Driver for Solarflare Solarstorm network controllers and boards
* Copyright 2008-2011 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include <linux/delay.h>
#include "net_driver.h"
#include "nic.h"
#include "io.h"
#include "regs.h"
#include "mcdi_pcol.h"
#include "phy.h"
/**************************************************************************
*
* Management-Controller-to-Driver Interface
*
**************************************************************************
*/
#define MCDI_RPC_TIMEOUT (10 * HZ)
#define MCDI_PDU(efx) \
(efx_port_num(efx) ? MC_SMEM_P1_PDU_OFST : MC_SMEM_P0_PDU_OFST)
#define MCDI_DOORBELL(efx) \
(efx_port_num(efx) ? MC_SMEM_P1_DOORBELL_OFST : MC_SMEM_P0_DOORBELL_OFST)
#define MCDI_STATUS(efx) \
(efx_port_num(efx) ? MC_SMEM_P1_STATUS_OFST : MC_SMEM_P0_STATUS_OFST)
/* A reboot/assertion causes the MCDI status word to be set after the
* command word is set or a REBOOT event is sent. If we notice a reboot
* via these mechanisms then wait 10ms for the status word to be set. */
#define MCDI_STATUS_DELAY_US 100
#define MCDI_STATUS_DELAY_COUNT 100
#define MCDI_STATUS_SLEEP_MS \
(MCDI_STATUS_DELAY_US * MCDI_STATUS_DELAY_COUNT / 1000)
#define SEQ_MASK \
EFX_MASK32(EFX_WIDTH(MCDI_HEADER_SEQ))
static inline struct efx_mcdi_iface *efx_mcdi(struct efx_nic *efx)
{
struct siena_nic_data *nic_data;
EFX_BUG_ON_PARANOID(efx_nic_rev(efx) < EFX_REV_SIENA_A0);
nic_data = efx->nic_data;
return &nic_data->mcdi;
}
void efx_mcdi_init(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi;
if (efx_nic_rev(efx) < EFX_REV_SIENA_A0)
return;
mcdi = efx_mcdi(efx);
init_waitqueue_head(&mcdi->wq);
spin_lock_init(&mcdi->iface_lock);
atomic_set(&mcdi->state, MCDI_STATE_QUIESCENT);
mcdi->mode = MCDI_MODE_POLL;
(void) efx_mcdi_poll_reboot(efx);
}
static void efx_mcdi_copyin(struct efx_nic *efx, unsigned cmd,
const u8 *inbuf, size_t inlen)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
unsigned pdu = FR_CZ_MC_TREG_SMEM + MCDI_PDU(efx);
unsigned doorbell = FR_CZ_MC_TREG_SMEM + MCDI_DOORBELL(efx);
unsigned int i;
efx_dword_t hdr;
u32 xflags, seqno;
BUG_ON(atomic_read(&mcdi->state) == MCDI_STATE_QUIESCENT);
BUG_ON(inlen & 3 || inlen >= MC_SMEM_PDU_LEN);
seqno = mcdi->seqno & SEQ_MASK;
xflags = 0;
if (mcdi->mode == MCDI_MODE_EVENTS)
xflags |= MCDI_HEADER_XFLAGS_EVREQ;
EFX_POPULATE_DWORD_6(hdr,
MCDI_HEADER_RESPONSE, 0,
MCDI_HEADER_RESYNC, 1,
MCDI_HEADER_CODE, cmd,
MCDI_HEADER_DATALEN, inlen,
MCDI_HEADER_SEQ, seqno,
MCDI_HEADER_XFLAGS, xflags);
efx_writed(efx, &hdr, pdu);
for (i = 0; i < inlen; i += 4)
_efx_writed(efx, *((__le32 *)(inbuf + i)), pdu + 4 + i);
/* Ensure the payload is written out before the header */
wmb();
/* ring the doorbell with a distinctive value */
_efx_writed(efx, (__force __le32) 0x45789abc, doorbell);
}
static void efx_mcdi_copyout(struct efx_nic *efx, u8 *outbuf, size_t outlen)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
unsigned int pdu = FR_CZ_MC_TREG_SMEM + MCDI_PDU(efx);
int i;
BUG_ON(atomic_read(&mcdi->state) == MCDI_STATE_QUIESCENT);
BUG_ON(outlen & 3 || outlen >= MC_SMEM_PDU_LEN);
for (i = 0; i < outlen; i += 4)
*((__le32 *)(outbuf + i)) = _efx_readd(efx, pdu + 4 + i);
}
static int efx_mcdi_poll(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
unsigned long time, finish;
unsigned int respseq, respcmd, error;
unsigned int pdu = FR_CZ_MC_TREG_SMEM + MCDI_PDU(efx);
unsigned int rc, spins;
efx_dword_t reg;
/* Check for a reboot atomically with respect to efx_mcdi_copyout() */
rc = -efx_mcdi_poll_reboot(efx);
if (rc)
goto out;
/* Poll for completion. Poll quickly (once a us) for the 1st jiffy,
* because generally mcdi responses are fast. After that, back off
* and poll once a jiffy (approximately)
*/
spins = TICK_USEC;
finish = jiffies + MCDI_RPC_TIMEOUT;
while (1) {
if (spins != 0) {
--spins;
udelay(1);
} else {
schedule_timeout_uninterruptible(1);
}
time = jiffies;
rmb();
efx_readd(efx, ®, pdu);
/* All 1's indicates that shared memory is in reset (and is
* not a valid header). Wait for it to come out reset before
* completing the command */
if (EFX_DWORD_FIELD(reg, EFX_DWORD_0) != 0xffffffff &&
EFX_DWORD_FIELD(reg, MCDI_HEADER_RESPONSE))
break;
if (time_after(time, finish))
return -ETIMEDOUT;
}
mcdi->resplen = EFX_DWORD_FIELD(reg, MCDI_HEADER_DATALEN);
respseq = EFX_DWORD_FIELD(reg, MCDI_HEADER_SEQ);
respcmd = EFX_DWORD_FIELD(reg, MCDI_HEADER_CODE);
error = EFX_DWORD_FIELD(reg, MCDI_HEADER_ERROR);
if (error && mcdi->resplen == 0) {
netif_err(efx, hw, efx->net_dev, "MC rebooted\n");
rc = EIO;
} else if ((respseq ^ mcdi->seqno) & SEQ_MASK) {
netif_err(efx, hw, efx->net_dev,
"MC response mismatch tx seq 0x%x rx seq 0x%x\n",
respseq, mcdi->seqno);
rc = EIO;
} else if (error) {
efx_readd(efx, ®, pdu + 4);
switch (EFX_DWORD_FIELD(reg, EFX_DWORD_0)) {
#define TRANSLATE_ERROR(name) \
case MC_CMD_ERR_ ## name: \
rc = name; \
break
TRANSLATE_ERROR(ENOENT);
TRANSLATE_ERROR(EINTR);
TRANSLATE_ERROR(EACCES);
TRANSLATE_ERROR(EBUSY);
TRANSLATE_ERROR(EINVAL);
TRANSLATE_ERROR(EDEADLK);
TRANSLATE_ERROR(ENOSYS);
TRANSLATE_ERROR(ETIME);
#undef TRANSLATE_ERROR
default:
rc = EIO;
break;
}
} else
rc = 0;
out:
mcdi->resprc = rc;
if (rc)
mcdi->resplen = 0;
/* Return rc=0 like wait_event_timeout() */
return 0;
}
/* Test and clear MC-rebooted flag for this port/function; reset
* software state as necessary.
*/
int efx_mcdi_poll_reboot(struct efx_nic *efx)
{
unsigned int addr = FR_CZ_MC_TREG_SMEM + MCDI_STATUS(efx);
efx_dword_t reg;
uint32_t value;
if (efx_nic_rev(efx) < EFX_REV_SIENA_A0)
return false;
efx_readd(efx, ®, addr);
value = EFX_DWORD_FIELD(reg, EFX_DWORD_0);
if (value == 0)
return 0;
/* MAC statistics have been cleared on the NIC; clear our copy
* so that efx_update_diff_stat() can continue to work.
*/
memset(&efx->mac_stats, 0, sizeof(efx->mac_stats));
EFX_ZERO_DWORD(reg);
efx_writed(efx, ®, addr);
if (value == MC_STATUS_DWORD_ASSERT)
return -EINTR;
else
return -EIO;
}
static void efx_mcdi_acquire(struct efx_mcdi_iface *mcdi)
{
/* Wait until the interface becomes QUIESCENT and we win the race
* to mark it RUNNING. */
wait_event(mcdi->wq,
atomic_cmpxchg(&mcdi->state,
MCDI_STATE_QUIESCENT,
MCDI_STATE_RUNNING)
== MCDI_STATE_QUIESCENT);
}
static int efx_mcdi_await_completion(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
if (wait_event_timeout(
mcdi->wq,
atomic_read(&mcdi->state) == MCDI_STATE_COMPLETED,
MCDI_RPC_TIMEOUT) == 0)
return -ETIMEDOUT;
/* Check if efx_mcdi_set_mode() switched us back to polled completions.
* In which case, poll for completions directly. If efx_mcdi_ev_cpl()
* completed the request first, then we'll just end up completing the
* request again, which is safe.
*
* We need an smp_rmb() to synchronise with efx_mcdi_mode_poll(), which
* wait_event_timeout() implicitly provides.
*/
if (mcdi->mode == MCDI_MODE_POLL)
return efx_mcdi_poll(efx);
return 0;
}
static bool efx_mcdi_complete(struct efx_mcdi_iface *mcdi)
{
/* If the interface is RUNNING, then move to COMPLETED and wake any
* waiters. If the interface isn't in RUNNING then we've received a
* duplicate completion after we've already transitioned back to
* QUIESCENT. [A subsequent invocation would increment seqno, so would
* have failed the seqno check].
*/
if (atomic_cmpxchg(&mcdi->state,
MCDI_STATE_RUNNING,
MCDI_STATE_COMPLETED) == MCDI_STATE_RUNNING) {
wake_up(&mcdi->wq);
return true;
}
return false;
}
static void efx_mcdi_release(struct efx_mcdi_iface *mcdi)
{
atomic_set(&mcdi->state, MCDI_STATE_QUIESCENT);
wake_up(&mcdi->wq);
}
static void efx_mcdi_ev_cpl(struct efx_nic *efx, unsigned int seqno,
unsigned int datalen, unsigned int errno)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
bool wake = false;
spin_lock(&mcdi->iface_lock);
if ((seqno ^ mcdi->seqno) & SEQ_MASK) {
if (mcdi->credits)
/* The request has been cancelled */
--mcdi->credits;
else
netif_err(efx, hw, efx->net_dev,
"MC response mismatch tx seq 0x%x rx "
"seq 0x%x\n", seqno, mcdi->seqno);
} else {
mcdi->resprc = errno;
mcdi->resplen = datalen;
wake = true;
}
spin_unlock(&mcdi->iface_lock);
if (wake)
efx_mcdi_complete(mcdi);
}
int efx_mcdi_rpc(struct efx_nic *efx, unsigned cmd,
const u8 *inbuf, size_t inlen, u8 *outbuf, size_t outlen,
size_t *outlen_actual)
{
efx_mcdi_rpc_start(efx, cmd, inbuf, inlen);
return efx_mcdi_rpc_finish(efx, cmd, inlen,
outbuf, outlen, outlen_actual);
}
void efx_mcdi_rpc_start(struct efx_nic *efx, unsigned cmd, const u8 *inbuf,
size_t inlen)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
BUG_ON(efx_nic_rev(efx) < EFX_REV_SIENA_A0);
efx_mcdi_acquire(mcdi);
/* Serialise with efx_mcdi_ev_cpl() and efx_mcdi_ev_death() */
spin_lock_bh(&mcdi->iface_lock);
++mcdi->seqno;
spin_unlock_bh(&mcdi->iface_lock);
efx_mcdi_copyin(efx, cmd, inbuf, inlen);
}
int efx_mcdi_rpc_finish(struct efx_nic *efx, unsigned cmd, size_t inlen,
u8 *outbuf, size_t outlen, size_t *outlen_actual)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
int rc;
BUG_ON(efx_nic_rev(efx) < EFX_REV_SIENA_A0);
if (mcdi->mode == MCDI_MODE_POLL)
rc = efx_mcdi_poll(efx);
else
rc = efx_mcdi_await_completion(efx);
if (rc != 0) {
/* Close the race with efx_mcdi_ev_cpl() executing just too late
* and completing a request we've just cancelled, by ensuring
* that the seqno check therein fails.
*/
spin_lock_bh(&mcdi->iface_lock);
++mcdi->seqno;
++mcdi->credits;
spin_unlock_bh(&mcdi->iface_lock);
netif_err(efx, hw, efx->net_dev,
"MC command 0x%x inlen %d mode %d timed out\n",
cmd, (int)inlen, mcdi->mode);
} else {
size_t resplen;
/* At the very least we need a memory barrier here to ensure
* we pick up changes from efx_mcdi_ev_cpl(). Protect against
* a spurious efx_mcdi_ev_cpl() running concurrently by
* acquiring the iface_lock. */
spin_lock_bh(&mcdi->iface_lock);
rc = -mcdi->resprc;
resplen = mcdi->resplen;
spin_unlock_bh(&mcdi->iface_lock);
if (rc == 0) {
efx_mcdi_copyout(efx, outbuf,
min(outlen, mcdi->resplen + 3) & ~0x3);
if (outlen_actual != NULL)
*outlen_actual = resplen;
} else if (cmd == MC_CMD_REBOOT && rc == -EIO)
; /* Don't reset if MC_CMD_REBOOT returns EIO */
else if (rc == -EIO || rc == -EINTR) {
netif_err(efx, hw, efx->net_dev, "MC fatal error %d\n",
-rc);
efx_schedule_reset(efx, RESET_TYPE_MC_FAILURE);
} else
netif_dbg(efx, hw, efx->net_dev,
"MC command 0x%x inlen %d failed rc=%d\n",
cmd, (int)inlen, -rc);
if (rc == -EIO || rc == -EINTR) {
msleep(MCDI_STATUS_SLEEP_MS);
efx_mcdi_poll_reboot(efx);
}
}
efx_mcdi_release(mcdi);
return rc;
}
void efx_mcdi_mode_poll(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi;
if (efx_nic_rev(efx) < EFX_REV_SIENA_A0)
return;
mcdi = efx_mcdi(efx);
if (mcdi->mode == MCDI_MODE_POLL)
return;
/* We can switch from event completion to polled completion, because
* mcdi requests are always completed in shared memory. We do this by
* switching the mode to POLL'd then completing the request.
* efx_mcdi_await_completion() will then call efx_mcdi_poll().
*
* We need an smp_wmb() to synchronise with efx_mcdi_await_completion(),
* which efx_mcdi_complete() provides for us.
*/
mcdi->mode = MCDI_MODE_POLL;
efx_mcdi_complete(mcdi);
}
void efx_mcdi_mode_event(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi;
if (efx_nic_rev(efx) < EFX_REV_SIENA_A0)
return;
mcdi = efx_mcdi(efx);
if (mcdi->mode == MCDI_MODE_EVENTS)
return;
/* We can't switch from polled to event completion in the middle of a
* request, because the completion method is specified in the request.
* So acquire the interface to serialise the requestors. We don't need
* to acquire the iface_lock to change the mode here, but we do need a
* write memory barrier ensure that efx_mcdi_rpc() sees it, which
* efx_mcdi_acquire() provides.
*/
efx_mcdi_acquire(mcdi);
mcdi->mode = MCDI_MODE_EVENTS;
efx_mcdi_release(mcdi);
}
static void efx_mcdi_ev_death(struct efx_nic *efx, int rc)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
/* If there is an outstanding MCDI request, it has been terminated
* either by a BADASSERT or REBOOT event. If the mcdi interface is
* in polled mode, then do nothing because the MC reboot handler will
* set the header correctly. However, if the mcdi interface is waiting
* for a CMDDONE event it won't receive it [and since all MCDI events
* are sent to the same queue, we can't be racing with
* efx_mcdi_ev_cpl()]
*
* There's a race here with efx_mcdi_rpc(), because we might receive
* a REBOOT event *before* the request has been copied out. In polled
* mode (during startup) this is irrelevant, because efx_mcdi_complete()
* is ignored. In event mode, this condition is just an edge-case of
* receiving a REBOOT event after posting the MCDI request. Did the mc
* reboot before or after the copyout? The best we can do always is
* just return failure.
*/
spin_lock(&mcdi->iface_lock);
if (efx_mcdi_complete(mcdi)) {
if (mcdi->mode == MCDI_MODE_EVENTS) {
mcdi->resprc = rc;
mcdi->resplen = 0;
++mcdi->credits;
}
} else {
int count;
/* Nobody was waiting for an MCDI request, so trigger a reset */
efx_schedule_reset(efx, RESET_TYPE_MC_FAILURE);
/* Consume the status word since efx_mcdi_rpc_finish() won't */
for (count = 0; count < MCDI_STATUS_DELAY_COUNT; ++count) {
if (efx_mcdi_poll_reboot(efx))
break;
udelay(MCDI_STATUS_DELAY_US);
}
}
spin_unlock(&mcdi->iface_lock);
}
static unsigned int efx_mcdi_event_link_speed[] = {
[MCDI_EVENT_LINKCHANGE_SPEED_100M] = 100,
[MCDI_EVENT_LINKCHANGE_SPEED_1G] = 1000,
[MCDI_EVENT_LINKCHANGE_SPEED_10G] = 10000,
};
static void efx_mcdi_process_link_change(struct efx_nic *efx, efx_qword_t *ev)
{
u32 flags, fcntl, speed, lpa;
speed = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_SPEED);
EFX_BUG_ON_PARANOID(speed >= ARRAY_SIZE(efx_mcdi_event_link_speed));
speed = efx_mcdi_event_link_speed[speed];
flags = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_LINK_FLAGS);
fcntl = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_FCNTL);
lpa = EFX_QWORD_FIELD(*ev, MCDI_EVENT_LINKCHANGE_LP_CAP);
/* efx->link_state is only modified by efx_mcdi_phy_get_link(),
* which is only run after flushing the event queues. Therefore, it
* is safe to modify the link state outside of the mac_lock here.
*/
efx_mcdi_phy_decode_link(efx, &efx->link_state, speed, flags, fcntl);
efx_mcdi_phy_check_fcntl(efx, lpa);
efx_link_status_changed(efx);
}
/* Called from falcon_process_eventq for MCDI events */
void efx_mcdi_process_event(struct efx_channel *channel,
efx_qword_t *event)
{
struct efx_nic *efx = channel->efx;
int code = EFX_QWORD_FIELD(*event, MCDI_EVENT_CODE);
u32 data = EFX_QWORD_FIELD(*event, MCDI_EVENT_DATA);
switch (code) {
case MCDI_EVENT_CODE_BADSSERT:
netif_err(efx, hw, efx->net_dev,
"MC watchdog or assertion failure at 0x%x\n", data);
efx_mcdi_ev_death(efx, EINTR);
break;
case MCDI_EVENT_CODE_PMNOTICE:
netif_info(efx, wol, efx->net_dev, "MCDI PM event.\n");
break;
case MCDI_EVENT_CODE_CMDDONE:
efx_mcdi_ev_cpl(efx,
MCDI_EVENT_FIELD(*event, CMDDONE_SEQ),
MCDI_EVENT_FIELD(*event, CMDDONE_DATALEN),
MCDI_EVENT_FIELD(*event, CMDDONE_ERRNO));
break;
case MCDI_EVENT_CODE_LINKCHANGE:
efx_mcdi_process_link_change(efx, event);
break;
case MCDI_EVENT_CODE_SENSOREVT:
efx_mcdi_sensor_event(efx, event);
break;
case MCDI_EVENT_CODE_SCHEDERR:
netif_info(efx, hw, efx->net_dev,
"MC Scheduler error address=0x%x\n", data);
break;
case MCDI_EVENT_CODE_REBOOT:
netif_info(efx, hw, efx->net_dev, "MC Reboot\n");
efx_mcdi_ev_death(efx, EIO);
break;
case MCDI_EVENT_CODE_MAC_STATS_DMA:
/* MAC stats are gather lazily. We can ignore this. */
break;
case MCDI_EVENT_CODE_FLR:
efx_sriov_flr(efx, MCDI_EVENT_FIELD(*event, FLR_VF));
break;
case MCDI_EVENT_CODE_PTP_RX:
case MCDI_EVENT_CODE_PTP_FAULT:
case MCDI_EVENT_CODE_PTP_PPS:
efx_ptp_event(efx, event);
break;
default:
netif_err(efx, hw, efx->net_dev, "Unknown MCDI event 0x%x\n",
code);
}
}
/**************************************************************************
*
* Specific request functions
*
**************************************************************************
*/
void efx_mcdi_print_fwver(struct efx_nic *efx, char *buf, size_t len)
{
u8 outbuf[ALIGN(MC_CMD_GET_VERSION_OUT_LEN, 4)];
size_t outlength;
const __le16 *ver_words;
int rc;
BUILD_BUG_ON(MC_CMD_GET_VERSION_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_VERSION, NULL, 0,
outbuf, sizeof(outbuf), &outlength);
if (rc)
goto fail;
if (outlength < MC_CMD_GET_VERSION_OUT_LEN) {
rc = -EIO;
goto fail;
}
ver_words = (__le16 *)MCDI_PTR(outbuf, GET_VERSION_OUT_VERSION);
snprintf(buf, len, "%u.%u.%u.%u",
le16_to_cpu(ver_words[0]), le16_to_cpu(ver_words[1]),
le16_to_cpu(ver_words[2]), le16_to_cpu(ver_words[3]));
return;
fail:
netif_err(efx, probe, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
buf[0] = 0;
}
int efx_mcdi_drv_attach(struct efx_nic *efx, bool driver_operating,
bool *was_attached)
{
u8 inbuf[MC_CMD_DRV_ATTACH_IN_LEN];
u8 outbuf[MC_CMD_DRV_ATTACH_OUT_LEN];
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_NEW_STATE,
driver_operating ? 1 : 0);
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_UPDATE, 1);
rc = efx_mcdi_rpc(efx, MC_CMD_DRV_ATTACH, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_DRV_ATTACH_OUT_LEN) {
rc = -EIO;
goto fail;
}
if (was_attached != NULL)
*was_attached = MCDI_DWORD(outbuf, DRV_ATTACH_OUT_OLD_STATE);
return 0;
fail:
netif_err(efx, probe, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_get_board_cfg(struct efx_nic *efx, u8 *mac_address,
u16 *fw_subtype_list, u32 *capabilities)
{
uint8_t outbuf[MC_CMD_GET_BOARD_CFG_OUT_LENMAX];
size_t outlen, offset, i;
int port_num = efx_port_num(efx);
int rc;
BUILD_BUG_ON(MC_CMD_GET_BOARD_CFG_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_BOARD_CFG, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_GET_BOARD_CFG_OUT_LENMIN) {
rc = -EIO;
goto fail;
}
offset = (port_num)
? MC_CMD_GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT1_OFST
: MC_CMD_GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT0_OFST;
if (mac_address)
memcpy(mac_address, outbuf + offset, ETH_ALEN);
if (fw_subtype_list) {
/* Byte-swap and truncate or zero-pad as necessary */
offset = MC_CMD_GET_BOARD_CFG_OUT_FW_SUBTYPE_LIST_OFST;
for (i = 0;
i < MC_CMD_GET_BOARD_CFG_OUT_FW_SUBTYPE_LIST_MAXNUM;
i++) {
fw_subtype_list[i] =
(offset + 2 <= outlen) ?
le16_to_cpup((__le16 *)(outbuf + offset)) : 0;
offset += 2;
}
}
if (capabilities) {
if (port_num)
*capabilities = MCDI_DWORD(outbuf,
GET_BOARD_CFG_OUT_CAPABILITIES_PORT1);
else
*capabilities = MCDI_DWORD(outbuf,
GET_BOARD_CFG_OUT_CAPABILITIES_PORT0);
}
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d len=%d\n",
__func__, rc, (int)outlen);
return rc;
}
int efx_mcdi_log_ctrl(struct efx_nic *efx, bool evq, bool uart, u32 dest_evq)
{
u8 inbuf[MC_CMD_LOG_CTRL_IN_LEN];
u32 dest = 0;
int rc;
if (uart)
dest |= MC_CMD_LOG_CTRL_IN_LOG_DEST_UART;
if (evq)
dest |= MC_CMD_LOG_CTRL_IN_LOG_DEST_EVQ;
MCDI_SET_DWORD(inbuf, LOG_CTRL_IN_LOG_DEST, dest);
MCDI_SET_DWORD(inbuf, LOG_CTRL_IN_LOG_DEST_EVQ, dest_evq);
BUILD_BUG_ON(MC_CMD_LOG_CTRL_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_LOG_CTRL, inbuf, sizeof(inbuf),
NULL, 0, NULL);
if (rc)
goto fail;
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_nvram_types(struct efx_nic *efx, u32 *nvram_types_out)
{
u8 outbuf[MC_CMD_NVRAM_TYPES_OUT_LEN];
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_NVRAM_TYPES_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_TYPES, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_NVRAM_TYPES_OUT_LEN) {
rc = -EIO;
goto fail;
}
*nvram_types_out = MCDI_DWORD(outbuf, NVRAM_TYPES_OUT_TYPES);
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n",
__func__, rc);
return rc;
}
int efx_mcdi_nvram_info(struct efx_nic *efx, unsigned int type,
size_t *size_out, size_t *erase_size_out,
bool *protected_out)
{
u8 inbuf[MC_CMD_NVRAM_INFO_IN_LEN];
u8 outbuf[MC_CMD_NVRAM_INFO_OUT_LEN];
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_INFO_IN_TYPE, type);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_INFO, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_NVRAM_INFO_OUT_LEN) {
rc = -EIO;
goto fail;
}
*size_out = MCDI_DWORD(outbuf, NVRAM_INFO_OUT_SIZE);
*erase_size_out = MCDI_DWORD(outbuf, NVRAM_INFO_OUT_ERASESIZE);
*protected_out = !!(MCDI_DWORD(outbuf, NVRAM_INFO_OUT_FLAGS) &
(1 << MC_CMD_NVRAM_INFO_OUT_PROTECTED_LBN));
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_nvram_update_start(struct efx_nic *efx, unsigned int type)
{
u8 inbuf[MC_CMD_NVRAM_UPDATE_START_IN_LEN];
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_UPDATE_START_IN_TYPE, type);
BUILD_BUG_ON(MC_CMD_NVRAM_UPDATE_START_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_UPDATE_START, inbuf, sizeof(inbuf),
NULL, 0, NULL);
if (rc)
goto fail;
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_nvram_read(struct efx_nic *efx, unsigned int type,
loff_t offset, u8 *buffer, size_t length)
{
u8 inbuf[MC_CMD_NVRAM_READ_IN_LEN];
u8 outbuf[MC_CMD_NVRAM_READ_OUT_LEN(EFX_MCDI_NVRAM_LEN_MAX)];
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_OFFSET, offset);
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_LENGTH, length);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_READ, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
memcpy(buffer, MCDI_PTR(outbuf, NVRAM_READ_OUT_READ_BUFFER), length);
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_nvram_write(struct efx_nic *efx, unsigned int type,
loff_t offset, const u8 *buffer, size_t length)
{
u8 inbuf[MC_CMD_NVRAM_WRITE_IN_LEN(EFX_MCDI_NVRAM_LEN_MAX)];
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_WRITE_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, NVRAM_WRITE_IN_OFFSET, offset);
MCDI_SET_DWORD(inbuf, NVRAM_WRITE_IN_LENGTH, length);
memcpy(MCDI_PTR(inbuf, NVRAM_WRITE_IN_WRITE_BUFFER), buffer, length);
BUILD_BUG_ON(MC_CMD_NVRAM_WRITE_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_WRITE, inbuf,
ALIGN(MC_CMD_NVRAM_WRITE_IN_LEN(length), 4),
NULL, 0, NULL);
if (rc)
goto fail;
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_nvram_erase(struct efx_nic *efx, unsigned int type,
loff_t offset, size_t length)
{
u8 inbuf[MC_CMD_NVRAM_ERASE_IN_LEN];
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_ERASE_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, NVRAM_ERASE_IN_OFFSET, offset);
MCDI_SET_DWORD(inbuf, NVRAM_ERASE_IN_LENGTH, length);
BUILD_BUG_ON(MC_CMD_NVRAM_ERASE_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_ERASE, inbuf, sizeof(inbuf),
NULL, 0, NULL);
if (rc)
goto fail;
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_nvram_update_finish(struct efx_nic *efx, unsigned int type)
{
u8 inbuf[MC_CMD_NVRAM_UPDATE_FINISH_IN_LEN];
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_UPDATE_FINISH_IN_TYPE, type);
BUILD_BUG_ON(MC_CMD_NVRAM_UPDATE_FINISH_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_UPDATE_FINISH, inbuf, sizeof(inbuf),
NULL, 0, NULL);
if (rc)
goto fail;
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
static int efx_mcdi_nvram_test(struct efx_nic *efx, unsigned int type)
{
u8 inbuf[MC_CMD_NVRAM_TEST_IN_LEN];
u8 outbuf[MC_CMD_NVRAM_TEST_OUT_LEN];
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_TEST_IN_TYPE, type);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_TEST, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), NULL);
if (rc)
return rc;
switch (MCDI_DWORD(outbuf, NVRAM_TEST_OUT_RESULT)) {
case MC_CMD_NVRAM_TEST_PASS:
case MC_CMD_NVRAM_TEST_NOTSUPP:
return 0;
default:
return -EIO;
}
}
int efx_mcdi_nvram_test_all(struct efx_nic *efx)
{
u32 nvram_types;
unsigned int type;
int rc;
rc = efx_mcdi_nvram_types(efx, &nvram_types);
if (rc)
goto fail1;
type = 0;
while (nvram_types != 0) {
if (nvram_types & 1) {
rc = efx_mcdi_nvram_test(efx, type);
if (rc)
goto fail2;
}
type++;
nvram_types >>= 1;
}
return 0;
fail2:
netif_err(efx, hw, efx->net_dev, "%s: failed type=%u\n",
__func__, type);
fail1:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
static int efx_mcdi_read_assertion(struct efx_nic *efx)
{
u8 inbuf[MC_CMD_GET_ASSERTS_IN_LEN];
u8 outbuf[MC_CMD_GET_ASSERTS_OUT_LEN];
unsigned int flags, index, ofst;
const char *reason;
size_t outlen;
int retry;
int rc;
/* Attempt to read any stored assertion state before we reboot
* the mcfw out of the assertion handler. Retry twice, once
* because a boot-time assertion might cause this command to fail
* with EINTR. And once again because GET_ASSERTS can race with
* MC_CMD_REBOOT running on the other port. */
retry = 2;
do {
MCDI_SET_DWORD(inbuf, GET_ASSERTS_IN_CLEAR, 1);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_ASSERTS,
inbuf, MC_CMD_GET_ASSERTS_IN_LEN,
outbuf, sizeof(outbuf), &outlen);
} while ((rc == -EINTR || rc == -EIO) && retry-- > 0);
if (rc)
return rc;
if (outlen < MC_CMD_GET_ASSERTS_OUT_LEN)
return -EIO;
/* Print out any recorded assertion state */
flags = MCDI_DWORD(outbuf, GET_ASSERTS_OUT_GLOBAL_FLAGS);
if (flags == MC_CMD_GET_ASSERTS_FLAGS_NO_FAILS)
return 0;
reason = (flags == MC_CMD_GET_ASSERTS_FLAGS_SYS_FAIL)
? "system-level assertion"
: (flags == MC_CMD_GET_ASSERTS_FLAGS_THR_FAIL)
? "thread-level assertion"
: (flags == MC_CMD_GET_ASSERTS_FLAGS_WDOG_FIRED)
? "watchdog reset"
: "unknown assertion";
netif_err(efx, hw, efx->net_dev,
"MCPU %s at PC = 0x%.8x in thread 0x%.8x\n", reason,
MCDI_DWORD(outbuf, GET_ASSERTS_OUT_SAVED_PC_OFFS),
MCDI_DWORD(outbuf, GET_ASSERTS_OUT_THREAD_OFFS));
/* Print out the registers */
ofst = MC_CMD_GET_ASSERTS_OUT_GP_REGS_OFFS_OFST;
for (index = 1; index < 32; index++) {
netif_err(efx, hw, efx->net_dev, "R%.2d (?): 0x%.8x\n", index,
MCDI_DWORD2(outbuf, ofst));
ofst += sizeof(efx_dword_t);
}
return 0;
}
static void efx_mcdi_exit_assertion(struct efx_nic *efx)
{
u8 inbuf[MC_CMD_REBOOT_IN_LEN];
/* If the MC is running debug firmware, it might now be
* waiting for a debugger to attach, but we just want it to
* reboot. We set a flag that makes the command a no-op if it
* has already done so. We don't know what return code to
* expect (0 or -EIO), so ignore it.
*/
BUILD_BUG_ON(MC_CMD_REBOOT_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, REBOOT_IN_FLAGS,
MC_CMD_REBOOT_FLAGS_AFTER_ASSERTION);
(void) efx_mcdi_rpc(efx, MC_CMD_REBOOT, inbuf, MC_CMD_REBOOT_IN_LEN,
NULL, 0, NULL);
}
int efx_mcdi_handle_assertion(struct efx_nic *efx)
{
int rc;
rc = efx_mcdi_read_assertion(efx);
if (rc)
return rc;
efx_mcdi_exit_assertion(efx);
return 0;
}
void efx_mcdi_set_id_led(struct efx_nic *efx, enum efx_led_mode mode)
{
u8 inbuf[MC_CMD_SET_ID_LED_IN_LEN];
int rc;
BUILD_BUG_ON(EFX_LED_OFF != MC_CMD_LED_OFF);
BUILD_BUG_ON(EFX_LED_ON != MC_CMD_LED_ON);
BUILD_BUG_ON(EFX_LED_DEFAULT != MC_CMD_LED_DEFAULT);
BUILD_BUG_ON(MC_CMD_SET_ID_LED_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, SET_ID_LED_IN_STATE, mode);
rc = efx_mcdi_rpc(efx, MC_CMD_SET_ID_LED, inbuf, sizeof(inbuf),
NULL, 0, NULL);
if (rc)
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n",
__func__, rc);
}
int efx_mcdi_reset_port(struct efx_nic *efx)
{
int rc = efx_mcdi_rpc(efx, MC_CMD_ENTITY_RESET, NULL, 0, NULL, 0, NULL);
if (rc)
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n",
__func__, rc);
return rc;
}
int efx_mcdi_reset_mc(struct efx_nic *efx)
{
u8 inbuf[MC_CMD_REBOOT_IN_LEN];
int rc;
BUILD_BUG_ON(MC_CMD_REBOOT_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, REBOOT_IN_FLAGS, 0);
rc = efx_mcdi_rpc(efx, MC_CMD_REBOOT, inbuf, sizeof(inbuf),
NULL, 0, NULL);
/* White is black, and up is down */
if (rc == -EIO)
return 0;
if (rc == 0)
rc = -EIO;
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
static int efx_mcdi_wol_filter_set(struct efx_nic *efx, u32 type,
const u8 *mac, int *id_out)
{
u8 inbuf[MC_CMD_WOL_FILTER_SET_IN_LEN];
u8 outbuf[MC_CMD_WOL_FILTER_SET_OUT_LEN];
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, WOL_FILTER_SET_IN_WOL_TYPE, type);
MCDI_SET_DWORD(inbuf, WOL_FILTER_SET_IN_FILTER_MODE,
MC_CMD_FILTER_MODE_SIMPLE);
memcpy(MCDI_PTR(inbuf, WOL_FILTER_SET_IN_MAGIC_MAC), mac, ETH_ALEN);
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_SET, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_WOL_FILTER_SET_OUT_LEN) {
rc = -EIO;
goto fail;
}
*id_out = (int)MCDI_DWORD(outbuf, WOL_FILTER_SET_OUT_FILTER_ID);
return 0;
fail:
*id_out = -1;
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int
efx_mcdi_wol_filter_set_magic(struct efx_nic *efx, const u8 *mac, int *id_out)
{
return efx_mcdi_wol_filter_set(efx, MC_CMD_WOL_TYPE_MAGIC, mac, id_out);
}
int efx_mcdi_wol_filter_get_magic(struct efx_nic *efx, int *id_out)
{
u8 outbuf[MC_CMD_WOL_FILTER_GET_OUT_LEN];
size_t outlen;
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_GET, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_WOL_FILTER_GET_OUT_LEN) {
rc = -EIO;
goto fail;
}
*id_out = (int)MCDI_DWORD(outbuf, WOL_FILTER_GET_OUT_FILTER_ID);
return 0;
fail:
*id_out = -1;
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_wol_filter_remove(struct efx_nic *efx, int id)
{
u8 inbuf[MC_CMD_WOL_FILTER_REMOVE_IN_LEN];
int rc;
MCDI_SET_DWORD(inbuf, WOL_FILTER_REMOVE_IN_FILTER_ID, (u32)id);
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_REMOVE, inbuf, sizeof(inbuf),
NULL, 0, NULL);
if (rc)
goto fail;
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_flush_rxqs(struct efx_nic *efx)
{
struct efx_channel *channel;
struct efx_rx_queue *rx_queue;
__le32 *qid;
int rc, count;
BUILD_BUG_ON(EFX_MAX_CHANNELS >
MC_CMD_FLUSH_RX_QUEUES_IN_QID_OFST_MAXNUM);
qid = kmalloc(EFX_MAX_CHANNELS * sizeof(*qid), GFP_KERNEL);
if (qid == NULL)
return -ENOMEM;
count = 0;
efx_for_each_channel(channel, efx) {
efx_for_each_channel_rx_queue(rx_queue, channel) {
if (rx_queue->flush_pending) {
rx_queue->flush_pending = false;
atomic_dec(&efx->rxq_flush_pending);
qid[count++] = cpu_to_le32(
efx_rx_queue_index(rx_queue));
}
}
}
rc = efx_mcdi_rpc(efx, MC_CMD_FLUSH_RX_QUEUES, (u8 *)qid,
count * sizeof(*qid), NULL, 0, NULL);
WARN_ON(rc < 0);
kfree(qid);
return rc;
}
int efx_mcdi_wol_filter_reset(struct efx_nic *efx)
{
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_RESET, NULL, 0, NULL, 0, NULL);
if (rc)
goto fail;
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
| gpl-2.0 |
omega-roms/G900I_Omega_Kernel_LL_5.0 | drivers/net/wireless/ath/ath9k/xmit.c | 2692 | 65341 | /*
* Copyright (c) 2008-2011 Atheros Communications 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.
*/
#include <linux/dma-mapping.h>
#include "ath9k.h"
#include "ar9003_mac.h"
#define BITS_PER_BYTE 8
#define OFDM_PLCP_BITS 22
#define HT_RC_2_STREAMS(_rc) ((((_rc) & 0x78) >> 3) + 1)
#define L_STF 8
#define L_LTF 8
#define L_SIG 4
#define HT_SIG 8
#define HT_STF 4
#define HT_LTF(_ns) (4 * (_ns))
#define SYMBOL_TIME(_ns) ((_ns) << 2) /* ns * 4 us */
#define SYMBOL_TIME_HALFGI(_ns) (((_ns) * 18 + 4) / 5) /* ns * 3.6 us */
#define NUM_SYMBOLS_PER_USEC(_usec) (_usec >> 2)
#define NUM_SYMBOLS_PER_USEC_HALFGI(_usec) (((_usec*5)-4)/18)
static u16 bits_per_symbol[][2] = {
/* 20MHz 40MHz */
{ 26, 54 }, /* 0: BPSK */
{ 52, 108 }, /* 1: QPSK 1/2 */
{ 78, 162 }, /* 2: QPSK 3/4 */
{ 104, 216 }, /* 3: 16-QAM 1/2 */
{ 156, 324 }, /* 4: 16-QAM 3/4 */
{ 208, 432 }, /* 5: 64-QAM 2/3 */
{ 234, 486 }, /* 6: 64-QAM 3/4 */
{ 260, 540 }, /* 7: 64-QAM 5/6 */
};
#define IS_HT_RATE(_rate) ((_rate) & 0x80)
static void ath_tx_send_normal(struct ath_softc *sc, struct ath_txq *txq,
struct ath_atx_tid *tid, struct sk_buff *skb);
static void ath_tx_complete(struct ath_softc *sc, struct sk_buff *skb,
int tx_flags, struct ath_txq *txq);
static void ath_tx_complete_buf(struct ath_softc *sc, struct ath_buf *bf,
struct ath_txq *txq, struct list_head *bf_q,
struct ath_tx_status *ts, int txok);
static void ath_tx_txqaddbuf(struct ath_softc *sc, struct ath_txq *txq,
struct list_head *head, bool internal);
static void ath_tx_rc_status(struct ath_softc *sc, struct ath_buf *bf,
struct ath_tx_status *ts, int nframes, int nbad,
int txok);
static void ath_tx_update_baw(struct ath_softc *sc, struct ath_atx_tid *tid,
int seqno);
static struct ath_buf *ath_tx_setup_buffer(struct ath_softc *sc,
struct ath_txq *txq,
struct ath_atx_tid *tid,
struct sk_buff *skb);
enum {
MCS_HT20,
MCS_HT20_SGI,
MCS_HT40,
MCS_HT40_SGI,
};
static int ath_max_4ms_framelen[4][32] = {
[MCS_HT20] = {
3212, 6432, 9648, 12864, 19300, 25736, 28952, 32172,
6424, 12852, 19280, 25708, 38568, 51424, 57852, 64280,
9628, 19260, 28896, 38528, 57792, 65532, 65532, 65532,
12828, 25656, 38488, 51320, 65532, 65532, 65532, 65532,
},
[MCS_HT20_SGI] = {
3572, 7144, 10720, 14296, 21444, 28596, 32172, 35744,
7140, 14284, 21428, 28568, 42856, 57144, 64288, 65532,
10700, 21408, 32112, 42816, 64228, 65532, 65532, 65532,
14256, 28516, 42780, 57040, 65532, 65532, 65532, 65532,
},
[MCS_HT40] = {
6680, 13360, 20044, 26724, 40092, 53456, 60140, 65532,
13348, 26700, 40052, 53400, 65532, 65532, 65532, 65532,
20004, 40008, 60016, 65532, 65532, 65532, 65532, 65532,
26644, 53292, 65532, 65532, 65532, 65532, 65532, 65532,
},
[MCS_HT40_SGI] = {
7420, 14844, 22272, 29696, 44544, 59396, 65532, 65532,
14832, 29668, 44504, 59340, 65532, 65532, 65532, 65532,
22232, 44464, 65532, 65532, 65532, 65532, 65532, 65532,
29616, 59232, 65532, 65532, 65532, 65532, 65532, 65532,
}
};
/*********************/
/* Aggregation logic */
/*********************/
static void ath_txq_lock(struct ath_softc *sc, struct ath_txq *txq)
__acquires(&txq->axq_lock)
{
spin_lock_bh(&txq->axq_lock);
}
static void ath_txq_unlock(struct ath_softc *sc, struct ath_txq *txq)
__releases(&txq->axq_lock)
{
spin_unlock_bh(&txq->axq_lock);
}
static void ath_txq_unlock_complete(struct ath_softc *sc, struct ath_txq *txq)
__releases(&txq->axq_lock)
{
struct sk_buff_head q;
struct sk_buff *skb;
__skb_queue_head_init(&q);
skb_queue_splice_init(&txq->complete_q, &q);
spin_unlock_bh(&txq->axq_lock);
while ((skb = __skb_dequeue(&q)))
ieee80211_tx_status(sc->hw, skb);
}
static void ath_tx_queue_tid(struct ath_txq *txq, struct ath_atx_tid *tid)
{
struct ath_atx_ac *ac = tid->ac;
if (tid->paused)
return;
if (tid->sched)
return;
tid->sched = true;
list_add_tail(&tid->list, &ac->tid_q);
if (ac->sched)
return;
ac->sched = true;
list_add_tail(&ac->list, &txq->axq_acq);
}
static void ath_tx_resume_tid(struct ath_softc *sc, struct ath_atx_tid *tid)
{
struct ath_txq *txq = tid->ac->txq;
WARN_ON(!tid->paused);
ath_txq_lock(sc, txq);
tid->paused = false;
if (skb_queue_empty(&tid->buf_q))
goto unlock;
ath_tx_queue_tid(txq, tid);
ath_txq_schedule(sc, txq);
unlock:
ath_txq_unlock_complete(sc, txq);
}
static struct ath_frame_info *get_frame_info(struct sk_buff *skb)
{
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
BUILD_BUG_ON(sizeof(struct ath_frame_info) >
sizeof(tx_info->rate_driver_data));
return (struct ath_frame_info *) &tx_info->rate_driver_data[0];
}
static void ath_send_bar(struct ath_atx_tid *tid, u16 seqno)
{
ieee80211_send_bar(tid->an->vif, tid->an->sta->addr, tid->tidno,
seqno << IEEE80211_SEQ_SEQ_SHIFT);
}
static void ath_tx_flush_tid(struct ath_softc *sc, struct ath_atx_tid *tid)
{
struct ath_txq *txq = tid->ac->txq;
struct sk_buff *skb;
struct ath_buf *bf;
struct list_head bf_head;
struct ath_tx_status ts;
struct ath_frame_info *fi;
bool sendbar = false;
INIT_LIST_HEAD(&bf_head);
memset(&ts, 0, sizeof(ts));
while ((skb = __skb_dequeue(&tid->buf_q))) {
fi = get_frame_info(skb);
bf = fi->bf;
if (bf && fi->retries) {
list_add_tail(&bf->list, &bf_head);
ath_tx_update_baw(sc, tid, bf->bf_state.seqno);
ath_tx_complete_buf(sc, bf, txq, &bf_head, &ts, 0);
sendbar = true;
} else {
ath_tx_send_normal(sc, txq, NULL, skb);
}
}
if (tid->baw_head == tid->baw_tail) {
tid->state &= ~AGGR_ADDBA_COMPLETE;
tid->state &= ~AGGR_CLEANUP;
}
if (sendbar) {
ath_txq_unlock(sc, txq);
ath_send_bar(tid, tid->seq_start);
ath_txq_lock(sc, txq);
}
}
static void ath_tx_update_baw(struct ath_softc *sc, struct ath_atx_tid *tid,
int seqno)
{
int index, cindex;
index = ATH_BA_INDEX(tid->seq_start, seqno);
cindex = (tid->baw_head + index) & (ATH_TID_MAX_BUFS - 1);
__clear_bit(cindex, tid->tx_buf);
while (tid->baw_head != tid->baw_tail && !test_bit(tid->baw_head, tid->tx_buf)) {
INCR(tid->seq_start, IEEE80211_SEQ_MAX);
INCR(tid->baw_head, ATH_TID_MAX_BUFS);
if (tid->bar_index >= 0)
tid->bar_index--;
}
}
static void ath_tx_addto_baw(struct ath_softc *sc, struct ath_atx_tid *tid,
u16 seqno)
{
int index, cindex;
index = ATH_BA_INDEX(tid->seq_start, seqno);
cindex = (tid->baw_head + index) & (ATH_TID_MAX_BUFS - 1);
__set_bit(cindex, tid->tx_buf);
if (index >= ((tid->baw_tail - tid->baw_head) &
(ATH_TID_MAX_BUFS - 1))) {
tid->baw_tail = cindex;
INCR(tid->baw_tail, ATH_TID_MAX_BUFS);
}
}
/*
* TODO: For frame(s) that are in the retry state, we will reuse the
* sequence number(s) without setting the retry bit. The
* alternative is to give up on these and BAR the receiver's window
* forward.
*/
static void ath_tid_drain(struct ath_softc *sc, struct ath_txq *txq,
struct ath_atx_tid *tid)
{
struct sk_buff *skb;
struct ath_buf *bf;
struct list_head bf_head;
struct ath_tx_status ts;
struct ath_frame_info *fi;
memset(&ts, 0, sizeof(ts));
INIT_LIST_HEAD(&bf_head);
while ((skb = __skb_dequeue(&tid->buf_q))) {
fi = get_frame_info(skb);
bf = fi->bf;
if (!bf) {
ath_tx_complete(sc, skb, ATH_TX_ERROR, txq);
continue;
}
list_add_tail(&bf->list, &bf_head);
if (fi->retries)
ath_tx_update_baw(sc, tid, bf->bf_state.seqno);
ath_tx_complete_buf(sc, bf, txq, &bf_head, &ts, 0);
}
tid->seq_next = tid->seq_start;
tid->baw_tail = tid->baw_head;
tid->bar_index = -1;
}
static void ath_tx_set_retry(struct ath_softc *sc, struct ath_txq *txq,
struct sk_buff *skb, int count)
{
struct ath_frame_info *fi = get_frame_info(skb);
struct ath_buf *bf = fi->bf;
struct ieee80211_hdr *hdr;
int prev = fi->retries;
TX_STAT_INC(txq->axq_qnum, a_retries);
fi->retries += count;
if (prev > 0)
return;
hdr = (struct ieee80211_hdr *)skb->data;
hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_RETRY);
dma_sync_single_for_device(sc->dev, bf->bf_buf_addr,
sizeof(*hdr), DMA_TO_DEVICE);
}
static struct ath_buf *ath_tx_get_buffer(struct ath_softc *sc)
{
struct ath_buf *bf = NULL;
spin_lock_bh(&sc->tx.txbuflock);
if (unlikely(list_empty(&sc->tx.txbuf))) {
spin_unlock_bh(&sc->tx.txbuflock);
return NULL;
}
bf = list_first_entry(&sc->tx.txbuf, struct ath_buf, list);
list_del(&bf->list);
spin_unlock_bh(&sc->tx.txbuflock);
return bf;
}
static void ath_tx_return_buffer(struct ath_softc *sc, struct ath_buf *bf)
{
spin_lock_bh(&sc->tx.txbuflock);
list_add_tail(&bf->list, &sc->tx.txbuf);
spin_unlock_bh(&sc->tx.txbuflock);
}
static struct ath_buf* ath_clone_txbuf(struct ath_softc *sc, struct ath_buf *bf)
{
struct ath_buf *tbf;
tbf = ath_tx_get_buffer(sc);
if (WARN_ON(!tbf))
return NULL;
ATH_TXBUF_RESET(tbf);
tbf->bf_mpdu = bf->bf_mpdu;
tbf->bf_buf_addr = bf->bf_buf_addr;
memcpy(tbf->bf_desc, bf->bf_desc, sc->sc_ah->caps.tx_desc_len);
tbf->bf_state = bf->bf_state;
return tbf;
}
static void ath_tx_count_frames(struct ath_softc *sc, struct ath_buf *bf,
struct ath_tx_status *ts, int txok,
int *nframes, int *nbad)
{
struct ath_frame_info *fi;
u16 seq_st = 0;
u32 ba[WME_BA_BMP_SIZE >> 5];
int ba_index;
int isaggr = 0;
*nbad = 0;
*nframes = 0;
isaggr = bf_isaggr(bf);
if (isaggr) {
seq_st = ts->ts_seqnum;
memcpy(ba, &ts->ba_low, WME_BA_BMP_SIZE >> 3);
}
while (bf) {
fi = get_frame_info(bf->bf_mpdu);
ba_index = ATH_BA_INDEX(seq_st, bf->bf_state.seqno);
(*nframes)++;
if (!txok || (isaggr && !ATH_BA_ISSET(ba, ba_index)))
(*nbad)++;
bf = bf->bf_next;
}
}
static void ath_tx_complete_aggr(struct ath_softc *sc, struct ath_txq *txq,
struct ath_buf *bf, struct list_head *bf_q,
struct ath_tx_status *ts, int txok, bool retry)
{
struct ath_node *an = NULL;
struct sk_buff *skb;
struct ieee80211_sta *sta;
struct ieee80211_hw *hw = sc->hw;
struct ieee80211_hdr *hdr;
struct ieee80211_tx_info *tx_info;
struct ath_atx_tid *tid = NULL;
struct ath_buf *bf_next, *bf_last = bf->bf_lastbf;
struct list_head bf_head;
struct sk_buff_head bf_pending;
u16 seq_st = 0, acked_cnt = 0, txfail_cnt = 0, seq_first;
u32 ba[WME_BA_BMP_SIZE >> 5];
int isaggr, txfail, txpending, sendbar = 0, needreset = 0, nbad = 0;
bool rc_update = true;
struct ieee80211_tx_rate rates[4];
struct ath_frame_info *fi;
int nframes;
u8 tidno;
bool flush = !!(ts->ts_status & ATH9K_TX_FLUSH);
int i, retries;
int bar_index = -1;
skb = bf->bf_mpdu;
hdr = (struct ieee80211_hdr *)skb->data;
tx_info = IEEE80211_SKB_CB(skb);
memcpy(rates, tx_info->control.rates, sizeof(rates));
retries = ts->ts_longretry + 1;
for (i = 0; i < ts->ts_rateindex; i++)
retries += rates[i].count;
rcu_read_lock();
sta = ieee80211_find_sta_by_ifaddr(hw, hdr->addr1, hdr->addr2);
if (!sta) {
rcu_read_unlock();
INIT_LIST_HEAD(&bf_head);
while (bf) {
bf_next = bf->bf_next;
if (!bf->bf_stale || bf_next != NULL)
list_move_tail(&bf->list, &bf_head);
ath_tx_complete_buf(sc, bf, txq, &bf_head, ts, 0);
bf = bf_next;
}
return;
}
an = (struct ath_node *)sta->drv_priv;
tidno = ieee80211_get_qos_ctl(hdr)[0] & IEEE80211_QOS_CTL_TID_MASK;
tid = ATH_AN_2_TID(an, tidno);
seq_first = tid->seq_start;
/*
* The hardware occasionally sends a tx status for the wrong TID.
* In this case, the BA status cannot be considered valid and all
* subframes need to be retransmitted
*/
if (tidno != ts->tid)
txok = false;
isaggr = bf_isaggr(bf);
memset(ba, 0, WME_BA_BMP_SIZE >> 3);
if (isaggr && txok) {
if (ts->ts_flags & ATH9K_TX_BA) {
seq_st = ts->ts_seqnum;
memcpy(ba, &ts->ba_low, WME_BA_BMP_SIZE >> 3);
} else {
/*
* AR5416 can become deaf/mute when BA
* issue happens. Chip needs to be reset.
* But AP code may have sychronization issues
* when perform internal reset in this routine.
* Only enable reset in STA mode for now.
*/
if (sc->sc_ah->opmode == NL80211_IFTYPE_STATION)
needreset = 1;
}
}
__skb_queue_head_init(&bf_pending);
ath_tx_count_frames(sc, bf, ts, txok, &nframes, &nbad);
while (bf) {
u16 seqno = bf->bf_state.seqno;
txfail = txpending = sendbar = 0;
bf_next = bf->bf_next;
skb = bf->bf_mpdu;
tx_info = IEEE80211_SKB_CB(skb);
fi = get_frame_info(skb);
if (ATH_BA_ISSET(ba, ATH_BA_INDEX(seq_st, seqno))) {
/* transmit completion, subframe is
* acked by block ack */
acked_cnt++;
} else if (!isaggr && txok) {
/* transmit completion */
acked_cnt++;
} else if ((tid->state & AGGR_CLEANUP) || !retry) {
/*
* cleanup in progress, just fail
* the un-acked sub-frames
*/
txfail = 1;
} else if (flush) {
txpending = 1;
} else if (fi->retries < ATH_MAX_SW_RETRIES) {
if (txok || !an->sleeping)
ath_tx_set_retry(sc, txq, bf->bf_mpdu,
retries);
txpending = 1;
} else {
txfail = 1;
txfail_cnt++;
bar_index = max_t(int, bar_index,
ATH_BA_INDEX(seq_first, seqno));
}
/*
* Make sure the last desc is reclaimed if it
* not a holding desc.
*/
INIT_LIST_HEAD(&bf_head);
if ((sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_EDMA) ||
bf_next != NULL || !bf_last->bf_stale)
list_move_tail(&bf->list, &bf_head);
if (!txpending || (tid->state & AGGR_CLEANUP)) {
/*
* complete the acked-ones/xretried ones; update
* block-ack window
*/
ath_tx_update_baw(sc, tid, seqno);
if (rc_update && (acked_cnt == 1 || txfail_cnt == 1)) {
memcpy(tx_info->control.rates, rates, sizeof(rates));
ath_tx_rc_status(sc, bf, ts, nframes, nbad, txok);
rc_update = false;
}
ath_tx_complete_buf(sc, bf, txq, &bf_head, ts,
!txfail);
} else {
/* retry the un-acked ones */
if (!(sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_EDMA) &&
bf->bf_next == NULL && bf_last->bf_stale) {
struct ath_buf *tbf;
tbf = ath_clone_txbuf(sc, bf_last);
/*
* Update tx baw and complete the
* frame with failed status if we
* run out of tx buf.
*/
if (!tbf) {
ath_tx_update_baw(sc, tid, seqno);
ath_tx_complete_buf(sc, bf, txq,
&bf_head, ts, 0);
bar_index = max_t(int, bar_index,
ATH_BA_INDEX(seq_first, seqno));
break;
}
fi->bf = tbf;
}
/*
* Put this buffer to the temporary pending
* queue to retain ordering
*/
__skb_queue_tail(&bf_pending, skb);
}
bf = bf_next;
}
/* prepend un-acked frames to the beginning of the pending frame queue */
if (!skb_queue_empty(&bf_pending)) {
if (an->sleeping)
ieee80211_sta_set_buffered(sta, tid->tidno, true);
skb_queue_splice(&bf_pending, &tid->buf_q);
if (!an->sleeping) {
ath_tx_queue_tid(txq, tid);
if (ts->ts_status & ATH9K_TXERR_FILT)
tid->ac->clear_ps_filter = true;
}
}
if (bar_index >= 0) {
u16 bar_seq = ATH_BA_INDEX2SEQ(seq_first, bar_index);
if (BAW_WITHIN(tid->seq_start, tid->baw_size, bar_seq))
tid->bar_index = ATH_BA_INDEX(tid->seq_start, bar_seq);
ath_txq_unlock(sc, txq);
ath_send_bar(tid, ATH_BA_INDEX2SEQ(seq_first, bar_index + 1));
ath_txq_lock(sc, txq);
}
if (tid->state & AGGR_CLEANUP)
ath_tx_flush_tid(sc, tid);
rcu_read_unlock();
if (needreset) {
RESET_STAT_INC(sc, RESET_TYPE_TX_ERROR);
ieee80211_queue_work(sc->hw, &sc->hw_reset_work);
}
}
static bool ath_lookup_legacy(struct ath_buf *bf)
{
struct sk_buff *skb;
struct ieee80211_tx_info *tx_info;
struct ieee80211_tx_rate *rates;
int i;
skb = bf->bf_mpdu;
tx_info = IEEE80211_SKB_CB(skb);
rates = tx_info->control.rates;
for (i = 0; i < 4; i++) {
if (!rates[i].count || rates[i].idx < 0)
break;
if (!(rates[i].flags & IEEE80211_TX_RC_MCS))
return true;
}
return false;
}
static u32 ath_lookup_rate(struct ath_softc *sc, struct ath_buf *bf,
struct ath_atx_tid *tid)
{
struct sk_buff *skb;
struct ieee80211_tx_info *tx_info;
struct ieee80211_tx_rate *rates;
u32 max_4ms_framelen, frmlen;
u16 aggr_limit, bt_aggr_limit, legacy = 0;
int i;
skb = bf->bf_mpdu;
tx_info = IEEE80211_SKB_CB(skb);
rates = tx_info->control.rates;
/*
* Find the lowest frame length among the rate series that will have a
* 4ms transmit duration.
* TODO - TXOP limit needs to be considered.
*/
max_4ms_framelen = ATH_AMPDU_LIMIT_MAX;
for (i = 0; i < 4; i++) {
int modeidx;
if (!rates[i].count)
continue;
if (!(rates[i].flags & IEEE80211_TX_RC_MCS)) {
legacy = 1;
break;
}
if (rates[i].flags & IEEE80211_TX_RC_40_MHZ_WIDTH)
modeidx = MCS_HT40;
else
modeidx = MCS_HT20;
if (rates[i].flags & IEEE80211_TX_RC_SHORT_GI)
modeidx++;
frmlen = ath_max_4ms_framelen[modeidx][rates[i].idx];
max_4ms_framelen = min(max_4ms_framelen, frmlen);
}
/*
* limit aggregate size by the minimum rate if rate selected is
* not a probe rate, if rate selected is a probe rate then
* avoid aggregation of this packet.
*/
if (tx_info->flags & IEEE80211_TX_CTL_RATE_CTRL_PROBE || legacy)
return 0;
aggr_limit = min(max_4ms_framelen, (u32)ATH_AMPDU_LIMIT_MAX);
/*
* Override the default aggregation limit for BTCOEX.
*/
bt_aggr_limit = ath9k_btcoex_aggr_limit(sc, max_4ms_framelen);
if (bt_aggr_limit)
aggr_limit = bt_aggr_limit;
/*
* h/w can accept aggregates up to 16 bit lengths (65535).
* The IE, however can hold up to 65536, which shows up here
* as zero. Ignore 65536 since we are constrained by hw.
*/
if (tid->an->maxampdu)
aggr_limit = min(aggr_limit, tid->an->maxampdu);
return aggr_limit;
}
/*
* Returns the number of delimiters to be added to
* meet the minimum required mpdudensity.
*/
static int ath_compute_num_delims(struct ath_softc *sc, struct ath_atx_tid *tid,
struct ath_buf *bf, u16 frmlen,
bool first_subfrm)
{
#define FIRST_DESC_NDELIMS 60
struct sk_buff *skb = bf->bf_mpdu;
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
u32 nsymbits, nsymbols;
u16 minlen;
u8 flags, rix;
int width, streams, half_gi, ndelim, mindelim;
struct ath_frame_info *fi = get_frame_info(bf->bf_mpdu);
/* Select standard number of delimiters based on frame length alone */
ndelim = ATH_AGGR_GET_NDELIM(frmlen);
/*
* If encryption enabled, hardware requires some more padding between
* subframes.
* TODO - this could be improved to be dependent on the rate.
* The hardware can keep up at lower rates, but not higher rates
*/
if ((fi->keyix != ATH9K_TXKEYIX_INVALID) &&
!(sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_EDMA))
ndelim += ATH_AGGR_ENCRYPTDELIM;
/*
* Add delimiter when using RTS/CTS with aggregation
* and non enterprise AR9003 card
*/
if (first_subfrm && !AR_SREV_9580_10_OR_LATER(sc->sc_ah) &&
(sc->sc_ah->ent_mode & AR_ENT_OTP_MIN_PKT_SIZE_DISABLE))
ndelim = max(ndelim, FIRST_DESC_NDELIMS);
/*
* Convert desired mpdu density from microeconds to bytes based
* on highest rate in rate series (i.e. first rate) to determine
* required minimum length for subframe. Take into account
* whether high rate is 20 or 40Mhz and half or full GI.
*
* If there is no mpdu density restriction, no further calculation
* is needed.
*/
if (tid->an->mpdudensity == 0)
return ndelim;
rix = tx_info->control.rates[0].idx;
flags = tx_info->control.rates[0].flags;
width = (flags & IEEE80211_TX_RC_40_MHZ_WIDTH) ? 1 : 0;
half_gi = (flags & IEEE80211_TX_RC_SHORT_GI) ? 1 : 0;
if (half_gi)
nsymbols = NUM_SYMBOLS_PER_USEC_HALFGI(tid->an->mpdudensity);
else
nsymbols = NUM_SYMBOLS_PER_USEC(tid->an->mpdudensity);
if (nsymbols == 0)
nsymbols = 1;
streams = HT_RC_2_STREAMS(rix);
nsymbits = bits_per_symbol[rix % 8][width] * streams;
minlen = (nsymbols * nsymbits) / BITS_PER_BYTE;
if (frmlen < minlen) {
mindelim = (minlen - frmlen) / ATH_AGGR_DELIM_SZ;
ndelim = max(mindelim, ndelim);
}
return ndelim;
}
static enum ATH_AGGR_STATUS ath_tx_form_aggr(struct ath_softc *sc,
struct ath_txq *txq,
struct ath_atx_tid *tid,
struct list_head *bf_q,
int *aggr_len)
{
#define PADBYTES(_len) ((4 - ((_len) % 4)) % 4)
struct ath_buf *bf, *bf_first = NULL, *bf_prev = NULL;
int rl = 0, nframes = 0, ndelim, prev_al = 0;
u16 aggr_limit = 0, al = 0, bpad = 0,
al_delta, h_baw = tid->baw_size / 2;
enum ATH_AGGR_STATUS status = ATH_AGGR_DONE;
struct ieee80211_tx_info *tx_info;
struct ath_frame_info *fi;
struct sk_buff *skb;
u16 seqno;
do {
skb = skb_peek(&tid->buf_q);
fi = get_frame_info(skb);
bf = fi->bf;
if (!fi->bf)
bf = ath_tx_setup_buffer(sc, txq, tid, skb);
if (!bf)
continue;
bf->bf_state.bf_type = BUF_AMPDU | BUF_AGGR;
seqno = bf->bf_state.seqno;
/* do not step over block-ack window */
if (!BAW_WITHIN(tid->seq_start, tid->baw_size, seqno)) {
status = ATH_AGGR_BAW_CLOSED;
break;
}
if (tid->bar_index > ATH_BA_INDEX(tid->seq_start, seqno)) {
struct ath_tx_status ts = {};
struct list_head bf_head;
INIT_LIST_HEAD(&bf_head);
list_add(&bf->list, &bf_head);
__skb_unlink(skb, &tid->buf_q);
ath_tx_update_baw(sc, tid, seqno);
ath_tx_complete_buf(sc, bf, txq, &bf_head, &ts, 0);
continue;
}
if (!bf_first)
bf_first = bf;
if (!rl) {
aggr_limit = ath_lookup_rate(sc, bf, tid);
rl = 1;
}
/* do not exceed aggregation limit */
al_delta = ATH_AGGR_DELIM_SZ + fi->framelen;
if (nframes &&
((aggr_limit < (al + bpad + al_delta + prev_al)) ||
ath_lookup_legacy(bf))) {
status = ATH_AGGR_LIMITED;
break;
}
tx_info = IEEE80211_SKB_CB(bf->bf_mpdu);
if (nframes && (tx_info->flags & IEEE80211_TX_CTL_RATE_CTRL_PROBE))
break;
/* do not exceed subframe limit */
if (nframes >= min((int)h_baw, ATH_AMPDU_SUBFRAME_DEFAULT)) {
status = ATH_AGGR_LIMITED;
break;
}
/* add padding for previous frame to aggregation length */
al += bpad + al_delta;
/*
* Get the delimiters needed to meet the MPDU
* density for this node.
*/
ndelim = ath_compute_num_delims(sc, tid, bf_first, fi->framelen,
!nframes);
bpad = PADBYTES(al_delta) + (ndelim << 2);
nframes++;
bf->bf_next = NULL;
/* link buffers of this frame to the aggregate */
if (!fi->retries)
ath_tx_addto_baw(sc, tid, seqno);
bf->bf_state.ndelim = ndelim;
__skb_unlink(skb, &tid->buf_q);
list_add_tail(&bf->list, bf_q);
if (bf_prev)
bf_prev->bf_next = bf;
bf_prev = bf;
} while (!skb_queue_empty(&tid->buf_q));
*aggr_len = al;
return status;
#undef PADBYTES
}
/*
* rix - rate index
* pktlen - total bytes (delims + data + fcs + pads + pad delims)
* width - 0 for 20 MHz, 1 for 40 MHz
* half_gi - to use 4us v/s 3.6 us for symbol time
*/
static u32 ath_pkt_duration(struct ath_softc *sc, u8 rix, int pktlen,
int width, int half_gi, bool shortPreamble)
{
u32 nbits, nsymbits, duration, nsymbols;
int streams;
/* find number of symbols: PLCP + data */
streams = HT_RC_2_STREAMS(rix);
nbits = (pktlen << 3) + OFDM_PLCP_BITS;
nsymbits = bits_per_symbol[rix % 8][width] * streams;
nsymbols = (nbits + nsymbits - 1) / nsymbits;
if (!half_gi)
duration = SYMBOL_TIME(nsymbols);
else
duration = SYMBOL_TIME_HALFGI(nsymbols);
/* addup duration for legacy/ht training and signal fields */
duration += L_STF + L_LTF + L_SIG + HT_SIG + HT_STF + HT_LTF(streams);
return duration;
}
static void ath_buf_set_rate(struct ath_softc *sc, struct ath_buf *bf,
struct ath_tx_info *info, int len)
{
struct ath_hw *ah = sc->sc_ah;
struct sk_buff *skb;
struct ieee80211_tx_info *tx_info;
struct ieee80211_tx_rate *rates;
const struct ieee80211_rate *rate;
struct ieee80211_hdr *hdr;
int i;
u8 rix = 0;
skb = bf->bf_mpdu;
tx_info = IEEE80211_SKB_CB(skb);
rates = tx_info->control.rates;
hdr = (struct ieee80211_hdr *)skb->data;
/* set dur_update_en for l-sig computation except for PS-Poll frames */
info->dur_update = !ieee80211_is_pspoll(hdr->frame_control);
/*
* We check if Short Preamble is needed for the CTS rate by
* checking the BSS's global flag.
* But for the rate series, IEEE80211_TX_RC_USE_SHORT_PREAMBLE is used.
*/
rate = ieee80211_get_rts_cts_rate(sc->hw, tx_info);
info->rtscts_rate = rate->hw_value;
if (tx_info->control.vif &&
tx_info->control.vif->bss_conf.use_short_preamble)
info->rtscts_rate |= rate->hw_value_short;
for (i = 0; i < 4; i++) {
bool is_40, is_sgi, is_sp;
int phy;
if (!rates[i].count || (rates[i].idx < 0))
continue;
rix = rates[i].idx;
info->rates[i].Tries = rates[i].count;
if (rates[i].flags & IEEE80211_TX_RC_USE_RTS_CTS) {
info->rates[i].RateFlags |= ATH9K_RATESERIES_RTS_CTS;
info->flags |= ATH9K_TXDESC_RTSENA;
} else if (rates[i].flags & IEEE80211_TX_RC_USE_CTS_PROTECT) {
info->rates[i].RateFlags |= ATH9K_RATESERIES_RTS_CTS;
info->flags |= ATH9K_TXDESC_CTSENA;
}
if (rates[i].flags & IEEE80211_TX_RC_40_MHZ_WIDTH)
info->rates[i].RateFlags |= ATH9K_RATESERIES_2040;
if (rates[i].flags & IEEE80211_TX_RC_SHORT_GI)
info->rates[i].RateFlags |= ATH9K_RATESERIES_HALFGI;
is_sgi = !!(rates[i].flags & IEEE80211_TX_RC_SHORT_GI);
is_40 = !!(rates[i].flags & IEEE80211_TX_RC_40_MHZ_WIDTH);
is_sp = !!(rates[i].flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE);
if (rates[i].flags & IEEE80211_TX_RC_MCS) {
/* MCS rates */
info->rates[i].Rate = rix | 0x80;
info->rates[i].ChSel = ath_txchainmask_reduction(sc,
ah->txchainmask, info->rates[i].Rate);
info->rates[i].PktDuration = ath_pkt_duration(sc, rix, len,
is_40, is_sgi, is_sp);
if (rix < 8 && (tx_info->flags & IEEE80211_TX_CTL_STBC))
info->rates[i].RateFlags |= ATH9K_RATESERIES_STBC;
continue;
}
/* legacy rates */
if ((tx_info->band == IEEE80211_BAND_2GHZ) &&
!(rate->flags & IEEE80211_RATE_ERP_G))
phy = WLAN_RC_PHY_CCK;
else
phy = WLAN_RC_PHY_OFDM;
rate = &sc->sbands[tx_info->band].bitrates[rates[i].idx];
info->rates[i].Rate = rate->hw_value;
if (rate->hw_value_short) {
if (rates[i].flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE)
info->rates[i].Rate |= rate->hw_value_short;
} else {
is_sp = false;
}
if (bf->bf_state.bfs_paprd)
info->rates[i].ChSel = ah->txchainmask;
else
info->rates[i].ChSel = ath_txchainmask_reduction(sc,
ah->txchainmask, info->rates[i].Rate);
info->rates[i].PktDuration = ath9k_hw_computetxtime(sc->sc_ah,
phy, rate->bitrate * 100, len, rix, is_sp);
}
/* For AR5416 - RTS cannot be followed by a frame larger than 8K */
if (bf_isaggr(bf) && (len > sc->sc_ah->caps.rts_aggr_limit))
info->flags &= ~ATH9K_TXDESC_RTSENA;
/* ATH9K_TXDESC_RTSENA and ATH9K_TXDESC_CTSENA are mutually exclusive. */
if (info->flags & ATH9K_TXDESC_RTSENA)
info->flags &= ~ATH9K_TXDESC_CTSENA;
}
static enum ath9k_pkt_type get_hw_packet_type(struct sk_buff *skb)
{
struct ieee80211_hdr *hdr;
enum ath9k_pkt_type htype;
__le16 fc;
hdr = (struct ieee80211_hdr *)skb->data;
fc = hdr->frame_control;
if (ieee80211_is_beacon(fc))
htype = ATH9K_PKT_TYPE_BEACON;
else if (ieee80211_is_probe_resp(fc))
htype = ATH9K_PKT_TYPE_PROBE_RESP;
else if (ieee80211_is_atim(fc))
htype = ATH9K_PKT_TYPE_ATIM;
else if (ieee80211_is_pspoll(fc))
htype = ATH9K_PKT_TYPE_PSPOLL;
else
htype = ATH9K_PKT_TYPE_NORMAL;
return htype;
}
static void ath_tx_fill_desc(struct ath_softc *sc, struct ath_buf *bf,
struct ath_txq *txq, int len)
{
struct ath_hw *ah = sc->sc_ah;
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(bf->bf_mpdu);
struct ath_buf *bf_first = bf;
struct ath_tx_info info;
bool aggr = !!(bf->bf_state.bf_type & BUF_AGGR);
memset(&info, 0, sizeof(info));
info.is_first = true;
info.is_last = true;
info.txpower = MAX_RATE_POWER;
info.qcu = txq->axq_qnum;
info.flags = ATH9K_TXDESC_INTREQ;
if (tx_info->flags & IEEE80211_TX_CTL_NO_ACK)
info.flags |= ATH9K_TXDESC_NOACK;
if (tx_info->flags & IEEE80211_TX_CTL_LDPC)
info.flags |= ATH9K_TXDESC_LDPC;
ath_buf_set_rate(sc, bf, &info, len);
if (tx_info->flags & IEEE80211_TX_CTL_CLEAR_PS_FILT)
info.flags |= ATH9K_TXDESC_CLRDMASK;
if (bf->bf_state.bfs_paprd)
info.flags |= (u32) bf->bf_state.bfs_paprd << ATH9K_TXDESC_PAPRD_S;
while (bf) {
struct sk_buff *skb = bf->bf_mpdu;
struct ath_frame_info *fi = get_frame_info(skb);
info.type = get_hw_packet_type(skb);
if (bf->bf_next)
info.link = bf->bf_next->bf_daddr;
else
info.link = 0;
info.buf_addr[0] = bf->bf_buf_addr;
info.buf_len[0] = skb->len;
info.pkt_len = fi->framelen;
info.keyix = fi->keyix;
info.keytype = fi->keytype;
if (aggr) {
if (bf == bf_first)
info.aggr = AGGR_BUF_FIRST;
else if (!bf->bf_next)
info.aggr = AGGR_BUF_LAST;
else
info.aggr = AGGR_BUF_MIDDLE;
info.ndelim = bf->bf_state.ndelim;
info.aggr_len = len;
}
ath9k_hw_set_txdesc(ah, bf->bf_desc, &info);
bf = bf->bf_next;
}
}
static void ath_tx_sched_aggr(struct ath_softc *sc, struct ath_txq *txq,
struct ath_atx_tid *tid)
{
struct ath_buf *bf;
enum ATH_AGGR_STATUS status;
struct ieee80211_tx_info *tx_info;
struct list_head bf_q;
int aggr_len;
do {
if (skb_queue_empty(&tid->buf_q))
return;
INIT_LIST_HEAD(&bf_q);
status = ath_tx_form_aggr(sc, txq, tid, &bf_q, &aggr_len);
/*
* no frames picked up to be aggregated;
* block-ack window is not open.
*/
if (list_empty(&bf_q))
break;
bf = list_first_entry(&bf_q, struct ath_buf, list);
bf->bf_lastbf = list_entry(bf_q.prev, struct ath_buf, list);
tx_info = IEEE80211_SKB_CB(bf->bf_mpdu);
if (tid->ac->clear_ps_filter) {
tid->ac->clear_ps_filter = false;
tx_info->flags |= IEEE80211_TX_CTL_CLEAR_PS_FILT;
} else {
tx_info->flags &= ~IEEE80211_TX_CTL_CLEAR_PS_FILT;
}
/* if only one frame, send as non-aggregate */
if (bf == bf->bf_lastbf) {
aggr_len = get_frame_info(bf->bf_mpdu)->framelen;
bf->bf_state.bf_type = BUF_AMPDU;
} else {
TX_STAT_INC(txq->axq_qnum, a_aggr);
}
ath_tx_fill_desc(sc, bf, txq, aggr_len);
ath_tx_txqaddbuf(sc, txq, &bf_q, false);
} while (txq->axq_ampdu_depth < ATH_AGGR_MIN_QDEPTH &&
status != ATH_AGGR_BAW_CLOSED);
}
int ath_tx_aggr_start(struct ath_softc *sc, struct ieee80211_sta *sta,
u16 tid, u16 *ssn)
{
struct ath_atx_tid *txtid;
struct ath_node *an;
an = (struct ath_node *)sta->drv_priv;
txtid = ATH_AN_2_TID(an, tid);
if (txtid->state & (AGGR_CLEANUP | AGGR_ADDBA_COMPLETE))
return -EAGAIN;
txtid->state |= AGGR_ADDBA_PROGRESS;
txtid->paused = true;
*ssn = txtid->seq_start = txtid->seq_next;
txtid->bar_index = -1;
memset(txtid->tx_buf, 0, sizeof(txtid->tx_buf));
txtid->baw_head = txtid->baw_tail = 0;
return 0;
}
void ath_tx_aggr_stop(struct ath_softc *sc, struct ieee80211_sta *sta, u16 tid)
{
struct ath_node *an = (struct ath_node *)sta->drv_priv;
struct ath_atx_tid *txtid = ATH_AN_2_TID(an, tid);
struct ath_txq *txq = txtid->ac->txq;
if (txtid->state & AGGR_CLEANUP)
return;
if (!(txtid->state & AGGR_ADDBA_COMPLETE)) {
txtid->state &= ~AGGR_ADDBA_PROGRESS;
return;
}
ath_txq_lock(sc, txq);
txtid->paused = true;
/*
* If frames are still being transmitted for this TID, they will be
* cleaned up during tx completion. To prevent race conditions, this
* TID can only be reused after all in-progress subframes have been
* completed.
*/
if (txtid->baw_head != txtid->baw_tail)
txtid->state |= AGGR_CLEANUP;
else
txtid->state &= ~AGGR_ADDBA_COMPLETE;
ath_tx_flush_tid(sc, txtid);
ath_txq_unlock_complete(sc, txq);
}
void ath_tx_aggr_sleep(struct ieee80211_sta *sta, struct ath_softc *sc,
struct ath_node *an)
{
struct ath_atx_tid *tid;
struct ath_atx_ac *ac;
struct ath_txq *txq;
bool buffered;
int tidno;
for (tidno = 0, tid = &an->tid[tidno];
tidno < WME_NUM_TID; tidno++, tid++) {
if (!tid->sched)
continue;
ac = tid->ac;
txq = ac->txq;
ath_txq_lock(sc, txq);
buffered = !skb_queue_empty(&tid->buf_q);
tid->sched = false;
list_del(&tid->list);
if (ac->sched) {
ac->sched = false;
list_del(&ac->list);
}
ath_txq_unlock(sc, txq);
ieee80211_sta_set_buffered(sta, tidno, buffered);
}
}
void ath_tx_aggr_wakeup(struct ath_softc *sc, struct ath_node *an)
{
struct ath_atx_tid *tid;
struct ath_atx_ac *ac;
struct ath_txq *txq;
int tidno;
for (tidno = 0, tid = &an->tid[tidno];
tidno < WME_NUM_TID; tidno++, tid++) {
ac = tid->ac;
txq = ac->txq;
ath_txq_lock(sc, txq);
ac->clear_ps_filter = true;
if (!skb_queue_empty(&tid->buf_q) && !tid->paused) {
ath_tx_queue_tid(txq, tid);
ath_txq_schedule(sc, txq);
}
ath_txq_unlock_complete(sc, txq);
}
}
void ath_tx_aggr_resume(struct ath_softc *sc, struct ieee80211_sta *sta, u16 tid)
{
struct ath_atx_tid *txtid;
struct ath_node *an;
an = (struct ath_node *)sta->drv_priv;
txtid = ATH_AN_2_TID(an, tid);
txtid->baw_size = IEEE80211_MIN_AMPDU_BUF << sta->ht_cap.ampdu_factor;
txtid->state |= AGGR_ADDBA_COMPLETE;
txtid->state &= ~AGGR_ADDBA_PROGRESS;
ath_tx_resume_tid(sc, txtid);
}
/********************/
/* Queue Management */
/********************/
static void ath_txq_drain_pending_buffers(struct ath_softc *sc,
struct ath_txq *txq)
{
struct ath_atx_ac *ac, *ac_tmp;
struct ath_atx_tid *tid, *tid_tmp;
list_for_each_entry_safe(ac, ac_tmp, &txq->axq_acq, list) {
list_del(&ac->list);
ac->sched = false;
list_for_each_entry_safe(tid, tid_tmp, &ac->tid_q, list) {
list_del(&tid->list);
tid->sched = false;
ath_tid_drain(sc, txq, tid);
}
}
}
struct ath_txq *ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
{
struct ath_hw *ah = sc->sc_ah;
struct ath9k_tx_queue_info qi;
static const int subtype_txq_to_hwq[] = {
[WME_AC_BE] = ATH_TXQ_AC_BE,
[WME_AC_BK] = ATH_TXQ_AC_BK,
[WME_AC_VI] = ATH_TXQ_AC_VI,
[WME_AC_VO] = ATH_TXQ_AC_VO,
};
int axq_qnum, i;
memset(&qi, 0, sizeof(qi));
qi.tqi_subtype = subtype_txq_to_hwq[subtype];
qi.tqi_aifs = ATH9K_TXQ_USEDEFAULT;
qi.tqi_cwmin = ATH9K_TXQ_USEDEFAULT;
qi.tqi_cwmax = ATH9K_TXQ_USEDEFAULT;
qi.tqi_physCompBuf = 0;
/*
* Enable interrupts only for EOL and DESC conditions.
* We mark tx descriptors to receive a DESC interrupt
* when a tx queue gets deep; otherwise waiting for the
* EOL to reap descriptors. Note that this is done to
* reduce interrupt load and this only defers reaping
* descriptors, never transmitting frames. Aside from
* reducing interrupts this also permits more concurrency.
* The only potential downside is if the tx queue backs
* up in which case the top half of the kernel may backup
* due to a lack of tx descriptors.
*
* The UAPSD queue is an exception, since we take a desc-
* based intr on the EOSP frames.
*/
if (ah->caps.hw_caps & ATH9K_HW_CAP_EDMA) {
qi.tqi_qflags = TXQ_FLAG_TXINT_ENABLE;
} else {
if (qtype == ATH9K_TX_QUEUE_UAPSD)
qi.tqi_qflags = TXQ_FLAG_TXDESCINT_ENABLE;
else
qi.tqi_qflags = TXQ_FLAG_TXEOLINT_ENABLE |
TXQ_FLAG_TXDESCINT_ENABLE;
}
axq_qnum = ath9k_hw_setuptxqueue(ah, qtype, &qi);
if (axq_qnum == -1) {
/*
* NB: don't print a message, this happens
* normally on parts with too few tx queues
*/
return NULL;
}
if (!ATH_TXQ_SETUP(sc, axq_qnum)) {
struct ath_txq *txq = &sc->tx.txq[axq_qnum];
txq->axq_qnum = axq_qnum;
txq->mac80211_qnum = -1;
txq->axq_link = NULL;
__skb_queue_head_init(&txq->complete_q);
INIT_LIST_HEAD(&txq->axq_q);
INIT_LIST_HEAD(&txq->axq_acq);
spin_lock_init(&txq->axq_lock);
txq->axq_depth = 0;
txq->axq_ampdu_depth = 0;
txq->axq_tx_inprogress = false;
sc->tx.txqsetup |= 1<<axq_qnum;
txq->txq_headidx = txq->txq_tailidx = 0;
for (i = 0; i < ATH_TXFIFO_DEPTH; i++)
INIT_LIST_HEAD(&txq->txq_fifo[i]);
}
return &sc->tx.txq[axq_qnum];
}
int ath_txq_update(struct ath_softc *sc, int qnum,
struct ath9k_tx_queue_info *qinfo)
{
struct ath_hw *ah = sc->sc_ah;
int error = 0;
struct ath9k_tx_queue_info qi;
if (qnum == sc->beacon.beaconq) {
/*
* XXX: for beacon queue, we just save the parameter.
* It will be picked up by ath_beaconq_config when
* it's necessary.
*/
sc->beacon.beacon_qi = *qinfo;
return 0;
}
BUG_ON(sc->tx.txq[qnum].axq_qnum != qnum);
ath9k_hw_get_txq_props(ah, qnum, &qi);
qi.tqi_aifs = qinfo->tqi_aifs;
qi.tqi_cwmin = qinfo->tqi_cwmin;
qi.tqi_cwmax = qinfo->tqi_cwmax;
qi.tqi_burstTime = qinfo->tqi_burstTime;
qi.tqi_readyTime = qinfo->tqi_readyTime;
if (!ath9k_hw_set_txq_props(ah, qnum, &qi)) {
ath_err(ath9k_hw_common(sc->sc_ah),
"Unable to update hardware queue %u!\n", qnum);
error = -EIO;
} else {
ath9k_hw_resettxqueue(ah, qnum);
}
return error;
}
int ath_cabq_update(struct ath_softc *sc)
{
struct ath9k_tx_queue_info qi;
struct ath_beacon_config *cur_conf = &sc->cur_beacon_conf;
int qnum = sc->beacon.cabq->axq_qnum;
ath9k_hw_get_txq_props(sc->sc_ah, qnum, &qi);
/*
* Ensure the readytime % is within the bounds.
*/
if (sc->config.cabqReadytime < ATH9K_READY_TIME_LO_BOUND)
sc->config.cabqReadytime = ATH9K_READY_TIME_LO_BOUND;
else if (sc->config.cabqReadytime > ATH9K_READY_TIME_HI_BOUND)
sc->config.cabqReadytime = ATH9K_READY_TIME_HI_BOUND;
qi.tqi_readyTime = (cur_conf->beacon_interval *
sc->config.cabqReadytime) / 100;
ath_txq_update(sc, qnum, &qi);
return 0;
}
static bool bf_is_ampdu_not_probing(struct ath_buf *bf)
{
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(bf->bf_mpdu);
return bf_isampdu(bf) && !(info->flags & IEEE80211_TX_CTL_RATE_CTRL_PROBE);
}
static void ath_drain_txq_list(struct ath_softc *sc, struct ath_txq *txq,
struct list_head *list, bool retry_tx)
{
struct ath_buf *bf, *lastbf;
struct list_head bf_head;
struct ath_tx_status ts;
memset(&ts, 0, sizeof(ts));
ts.ts_status = ATH9K_TX_FLUSH;
INIT_LIST_HEAD(&bf_head);
while (!list_empty(list)) {
bf = list_first_entry(list, struct ath_buf, list);
if (bf->bf_stale) {
list_del(&bf->list);
ath_tx_return_buffer(sc, bf);
continue;
}
lastbf = bf->bf_lastbf;
list_cut_position(&bf_head, list, &lastbf->list);
txq->axq_depth--;
if (bf_is_ampdu_not_probing(bf))
txq->axq_ampdu_depth--;
if (bf_isampdu(bf))
ath_tx_complete_aggr(sc, txq, bf, &bf_head, &ts, 0,
retry_tx);
else
ath_tx_complete_buf(sc, bf, txq, &bf_head, &ts, 0);
}
}
/*
* Drain a given TX queue (could be Beacon or Data)
*
* This assumes output has been stopped and
* we do not need to block ath_tx_tasklet.
*/
void ath_draintxq(struct ath_softc *sc, struct ath_txq *txq, bool retry_tx)
{
ath_txq_lock(sc, txq);
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_EDMA) {
int idx = txq->txq_tailidx;
while (!list_empty(&txq->txq_fifo[idx])) {
ath_drain_txq_list(sc, txq, &txq->txq_fifo[idx],
retry_tx);
INCR(idx, ATH_TXFIFO_DEPTH);
}
txq->txq_tailidx = idx;
}
txq->axq_link = NULL;
txq->axq_tx_inprogress = false;
ath_drain_txq_list(sc, txq, &txq->axq_q, retry_tx);
/* flush any pending frames if aggregation is enabled */
if ((sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_HT) && !retry_tx)
ath_txq_drain_pending_buffers(sc, txq);
ath_txq_unlock_complete(sc, txq);
}
bool ath_drain_all_txq(struct ath_softc *sc, bool retry_tx)
{
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
struct ath_txq *txq;
int i;
u32 npend = 0;
if (sc->sc_flags & SC_OP_INVALID)
return true;
ath9k_hw_abort_tx_dma(ah);
/* Check if any queue remains active */
for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++) {
if (!ATH_TXQ_SETUP(sc, i))
continue;
if (ath9k_hw_numtxpending(ah, sc->tx.txq[i].axq_qnum))
npend |= BIT(i);
}
if (npend)
ath_err(common, "Failed to stop TX DMA, queues=0x%03x!\n", npend);
for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++) {
if (!ATH_TXQ_SETUP(sc, i))
continue;
/*
* The caller will resume queues with ieee80211_wake_queues.
* Mark the queue as not stopped to prevent ath_tx_complete
* from waking the queue too early.
*/
txq = &sc->tx.txq[i];
txq->stopped = false;
ath_draintxq(sc, txq, retry_tx);
}
return !npend;
}
void ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
{
ath9k_hw_releasetxqueue(sc->sc_ah, txq->axq_qnum);
sc->tx.txqsetup &= ~(1<<txq->axq_qnum);
}
/* For each axq_acq entry, for each tid, try to schedule packets
* for transmit until ampdu_depth has reached min Q depth.
*/
void ath_txq_schedule(struct ath_softc *sc, struct ath_txq *txq)
{
struct ath_atx_ac *ac, *ac_tmp, *last_ac;
struct ath_atx_tid *tid, *last_tid;
if (work_pending(&sc->hw_reset_work) || list_empty(&txq->axq_acq) ||
txq->axq_ampdu_depth >= ATH_AGGR_MIN_QDEPTH)
return;
ac = list_first_entry(&txq->axq_acq, struct ath_atx_ac, list);
last_ac = list_entry(txq->axq_acq.prev, struct ath_atx_ac, list);
list_for_each_entry_safe(ac, ac_tmp, &txq->axq_acq, list) {
last_tid = list_entry(ac->tid_q.prev, struct ath_atx_tid, list);
list_del(&ac->list);
ac->sched = false;
while (!list_empty(&ac->tid_q)) {
tid = list_first_entry(&ac->tid_q, struct ath_atx_tid,
list);
list_del(&tid->list);
tid->sched = false;
if (tid->paused)
continue;
ath_tx_sched_aggr(sc, txq, tid);
/*
* add tid to round-robin queue if more frames
* are pending for the tid
*/
if (!skb_queue_empty(&tid->buf_q))
ath_tx_queue_tid(txq, tid);
if (tid == last_tid ||
txq->axq_ampdu_depth >= ATH_AGGR_MIN_QDEPTH)
break;
}
if (!list_empty(&ac->tid_q) && !ac->sched) {
ac->sched = true;
list_add_tail(&ac->list, &txq->axq_acq);
}
if (ac == last_ac ||
txq->axq_ampdu_depth >= ATH_AGGR_MIN_QDEPTH)
return;
}
}
/***********/
/* TX, DMA */
/***********/
/*
* Insert a chain of ath_buf (descriptors) on a txq and
* assume the descriptors are already chained together by caller.
*/
static void ath_tx_txqaddbuf(struct ath_softc *sc, struct ath_txq *txq,
struct list_head *head, bool internal)
{
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
struct ath_buf *bf, *bf_last;
bool puttxbuf = false;
bool edma;
/*
* Insert the frame on the outbound list and
* pass it on to the hardware.
*/
if (list_empty(head))
return;
edma = !!(ah->caps.hw_caps & ATH9K_HW_CAP_EDMA);
bf = list_first_entry(head, struct ath_buf, list);
bf_last = list_entry(head->prev, struct ath_buf, list);
ath_dbg(common, QUEUE, "qnum: %d, txq depth: %d\n",
txq->axq_qnum, txq->axq_depth);
if (edma && list_empty(&txq->txq_fifo[txq->txq_headidx])) {
list_splice_tail_init(head, &txq->txq_fifo[txq->txq_headidx]);
INCR(txq->txq_headidx, ATH_TXFIFO_DEPTH);
puttxbuf = true;
} else {
list_splice_tail_init(head, &txq->axq_q);
if (txq->axq_link) {
ath9k_hw_set_desc_link(ah, txq->axq_link, bf->bf_daddr);
ath_dbg(common, XMIT, "link[%u] (%p)=%llx (%p)\n",
txq->axq_qnum, txq->axq_link,
ito64(bf->bf_daddr), bf->bf_desc);
} else if (!edma)
puttxbuf = true;
txq->axq_link = bf_last->bf_desc;
}
if (puttxbuf) {
TX_STAT_INC(txq->axq_qnum, puttxbuf);
ath9k_hw_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
ath_dbg(common, XMIT, "TXDP[%u] = %llx (%p)\n",
txq->axq_qnum, ito64(bf->bf_daddr), bf->bf_desc);
}
if (!edma) {
TX_STAT_INC(txq->axq_qnum, txstart);
ath9k_hw_txstart(ah, txq->axq_qnum);
}
if (!internal) {
txq->axq_depth++;
if (bf_is_ampdu_not_probing(bf))
txq->axq_ampdu_depth++;
}
}
static void ath_tx_send_ampdu(struct ath_softc *sc, struct ath_atx_tid *tid,
struct sk_buff *skb, struct ath_tx_control *txctl)
{
struct ath_frame_info *fi = get_frame_info(skb);
struct list_head bf_head;
struct ath_buf *bf;
/*
* Do not queue to h/w when any of the following conditions is true:
* - there are pending frames in software queue
* - the TID is currently paused for ADDBA/BAR request
* - seqno is not within block-ack window
* - h/w queue depth exceeds low water mark
*/
if (!skb_queue_empty(&tid->buf_q) || tid->paused ||
!BAW_WITHIN(tid->seq_start, tid->baw_size, tid->seq_next) ||
txctl->txq->axq_ampdu_depth >= ATH_AGGR_MIN_QDEPTH) {
/*
* Add this frame to software queue for scheduling later
* for aggregation.
*/
TX_STAT_INC(txctl->txq->axq_qnum, a_queued_sw);
__skb_queue_tail(&tid->buf_q, skb);
if (!txctl->an || !txctl->an->sleeping)
ath_tx_queue_tid(txctl->txq, tid);
return;
}
bf = ath_tx_setup_buffer(sc, txctl->txq, tid, skb);
if (!bf)
return;
bf->bf_state.bf_type = BUF_AMPDU;
INIT_LIST_HEAD(&bf_head);
list_add(&bf->list, &bf_head);
/* Add sub-frame to BAW */
ath_tx_addto_baw(sc, tid, bf->bf_state.seqno);
/* Queue to h/w without aggregation */
TX_STAT_INC(txctl->txq->axq_qnum, a_queued_hw);
bf->bf_lastbf = bf;
ath_tx_fill_desc(sc, bf, txctl->txq, fi->framelen);
ath_tx_txqaddbuf(sc, txctl->txq, &bf_head, false);
}
static void ath_tx_send_normal(struct ath_softc *sc, struct ath_txq *txq,
struct ath_atx_tid *tid, struct sk_buff *skb)
{
struct ath_frame_info *fi = get_frame_info(skb);
struct list_head bf_head;
struct ath_buf *bf;
bf = fi->bf;
if (!bf)
bf = ath_tx_setup_buffer(sc, txq, tid, skb);
if (!bf)
return;
INIT_LIST_HEAD(&bf_head);
list_add_tail(&bf->list, &bf_head);
bf->bf_state.bf_type = 0;
bf->bf_lastbf = bf;
ath_tx_fill_desc(sc, bf, txq, fi->framelen);
ath_tx_txqaddbuf(sc, txq, &bf_head, false);
TX_STAT_INC(txq->axq_qnum, queued);
}
static void setup_frame_info(struct ieee80211_hw *hw, struct sk_buff *skb,
int framelen)
{
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ieee80211_sta *sta = tx_info->control.sta;
struct ieee80211_key_conf *hw_key = tx_info->control.hw_key;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
struct ath_frame_info *fi = get_frame_info(skb);
struct ath_node *an = NULL;
enum ath9k_key_type keytype;
keytype = ath9k_cmn_get_hw_crypto_keytype(skb);
if (sta)
an = (struct ath_node *) sta->drv_priv;
memset(fi, 0, sizeof(*fi));
if (hw_key)
fi->keyix = hw_key->hw_key_idx;
else if (an && ieee80211_is_data(hdr->frame_control) && an->ps_key > 0)
fi->keyix = an->ps_key;
else
fi->keyix = ATH9K_TXKEYIX_INVALID;
fi->keytype = keytype;
fi->framelen = framelen;
}
u8 ath_txchainmask_reduction(struct ath_softc *sc, u8 chainmask, u32 rate)
{
struct ath_hw *ah = sc->sc_ah;
struct ath9k_channel *curchan = ah->curchan;
if ((ah->caps.hw_caps & ATH9K_HW_CAP_APM) &&
(curchan->channelFlags & CHANNEL_5GHZ) &&
(chainmask == 0x7) && (rate < 0x90))
return 0x3;
else
return chainmask;
}
/*
* Assign a descriptor (and sequence number if necessary,
* and map buffer for DMA. Frees skb on error
*/
static struct ath_buf *ath_tx_setup_buffer(struct ath_softc *sc,
struct ath_txq *txq,
struct ath_atx_tid *tid,
struct sk_buff *skb)
{
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
struct ath_frame_info *fi = get_frame_info(skb);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
struct ath_buf *bf;
int fragno;
u16 seqno;
bf = ath_tx_get_buffer(sc);
if (!bf) {
ath_dbg(common, XMIT, "TX buffers are full\n");
goto error;
}
ATH_TXBUF_RESET(bf);
if (tid) {
fragno = le16_to_cpu(hdr->seq_ctrl) & IEEE80211_SCTL_FRAG;
seqno = tid->seq_next;
hdr->seq_ctrl = cpu_to_le16(tid->seq_next << IEEE80211_SEQ_SEQ_SHIFT);
if (fragno)
hdr->seq_ctrl |= cpu_to_le16(fragno);
if (!ieee80211_has_morefrags(hdr->frame_control))
INCR(tid->seq_next, IEEE80211_SEQ_MAX);
bf->bf_state.seqno = seqno;
}
bf->bf_mpdu = skb;
bf->bf_buf_addr = dma_map_single(sc->dev, skb->data,
skb->len, DMA_TO_DEVICE);
if (unlikely(dma_mapping_error(sc->dev, bf->bf_buf_addr))) {
bf->bf_mpdu = NULL;
bf->bf_buf_addr = 0;
ath_err(ath9k_hw_common(sc->sc_ah),
"dma_mapping_error() on TX\n");
ath_tx_return_buffer(sc, bf);
goto error;
}
fi->bf = bf;
return bf;
error:
dev_kfree_skb_any(skb);
return NULL;
}
/* FIXME: tx power */
static void ath_tx_start_dma(struct ath_softc *sc, struct sk_buff *skb,
struct ath_tx_control *txctl)
{
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
struct ath_atx_tid *tid = NULL;
struct ath_buf *bf;
u8 tidno;
if ((sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_HT) && txctl->an &&
ieee80211_is_data_qos(hdr->frame_control)) {
tidno = ieee80211_get_qos_ctl(hdr)[0] &
IEEE80211_QOS_CTL_TID_MASK;
tid = ATH_AN_2_TID(txctl->an, tidno);
WARN_ON(tid->ac->txq != txctl->txq);
}
if ((tx_info->flags & IEEE80211_TX_CTL_AMPDU) && tid) {
/*
* Try aggregation if it's a unicast data frame
* and the destination is HT capable.
*/
ath_tx_send_ampdu(sc, tid, skb, txctl);
} else {
bf = ath_tx_setup_buffer(sc, txctl->txq, tid, skb);
if (!bf)
return;
bf->bf_state.bfs_paprd = txctl->paprd;
if (txctl->paprd)
bf->bf_state.bfs_paprd_timestamp = jiffies;
ath_tx_send_normal(sc, txctl->txq, tid, skb);
}
}
/* Upon failure caller should free skb */
int ath_tx_start(struct ieee80211_hw *hw, struct sk_buff *skb,
struct ath_tx_control *txctl)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct ieee80211_sta *sta = info->control.sta;
struct ieee80211_vif *vif = info->control.vif;
struct ath_softc *sc = hw->priv;
struct ath_txq *txq = txctl->txq;
int padpos, padsize;
int frmlen = skb->len + FCS_LEN;
int q;
/* NOTE: sta can be NULL according to net/mac80211.h */
if (sta)
txctl->an = (struct ath_node *)sta->drv_priv;
if (info->control.hw_key)
frmlen += info->control.hw_key->icv_len;
/*
* As a temporary workaround, assign seq# here; this will likely need
* to be cleaned up to work better with Beacon transmission and virtual
* BSSes.
*/
if (info->flags & IEEE80211_TX_CTL_ASSIGN_SEQ) {
if (info->flags & IEEE80211_TX_CTL_FIRST_FRAGMENT)
sc->tx.seq_no += 0x10;
hdr->seq_ctrl &= cpu_to_le16(IEEE80211_SCTL_FRAG);
hdr->seq_ctrl |= cpu_to_le16(sc->tx.seq_no);
}
/* Add the padding after the header if this is not already done */
padpos = ath9k_cmn_padpos(hdr->frame_control);
padsize = padpos & 3;
if (padsize && skb->len > padpos) {
if (skb_headroom(skb) < padsize)
return -ENOMEM;
skb_push(skb, padsize);
memmove(skb->data, skb->data + padsize, padpos);
hdr = (struct ieee80211_hdr *) skb->data;
}
if ((vif && vif->type != NL80211_IFTYPE_AP &&
vif->type != NL80211_IFTYPE_AP_VLAN) ||
!ieee80211_is_data(hdr->frame_control))
info->flags |= IEEE80211_TX_CTL_CLEAR_PS_FILT;
setup_frame_info(hw, skb, frmlen);
/*
* At this point, the vif, hw_key and sta pointers in the tx control
* info are no longer valid (overwritten by the ath_frame_info data.
*/
q = skb_get_queue_mapping(skb);
ath_txq_lock(sc, txq);
if (txq == sc->tx.txq_map[q] &&
++txq->pending_frames > ATH_MAX_QDEPTH && !txq->stopped) {
ieee80211_stop_queue(sc->hw, q);
txq->stopped = true;
}
ath_tx_start_dma(sc, skb, txctl);
ath_txq_unlock(sc, txq);
return 0;
}
/*****************/
/* TX Completion */
/*****************/
static void ath_tx_complete(struct ath_softc *sc, struct sk_buff *skb,
int tx_flags, struct ath_txq *txq)
{
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
struct ieee80211_hdr * hdr = (struct ieee80211_hdr *)skb->data;
int q, padpos, padsize;
ath_dbg(common, XMIT, "TX complete: skb: %p\n", skb);
if (!(tx_flags & ATH_TX_ERROR))
/* Frame was ACKed */
tx_info->flags |= IEEE80211_TX_STAT_ACK;
padpos = ath9k_cmn_padpos(hdr->frame_control);
padsize = padpos & 3;
if (padsize && skb->len>padpos+padsize) {
/*
* Remove MAC header padding before giving the frame back to
* mac80211.
*/
memmove(skb->data + padsize, skb->data, padpos);
skb_pull(skb, padsize);
}
if ((sc->ps_flags & PS_WAIT_FOR_TX_ACK) && !txq->axq_depth) {
sc->ps_flags &= ~PS_WAIT_FOR_TX_ACK;
ath_dbg(common, PS,
"Going back to sleep after having received TX status (0x%lx)\n",
sc->ps_flags & (PS_WAIT_FOR_BEACON |
PS_WAIT_FOR_CAB |
PS_WAIT_FOR_PSPOLL_DATA |
PS_WAIT_FOR_TX_ACK));
}
q = skb_get_queue_mapping(skb);
if (txq == sc->tx.txq_map[q]) {
if (WARN_ON(--txq->pending_frames < 0))
txq->pending_frames = 0;
if (txq->stopped && txq->pending_frames < ATH_MAX_QDEPTH) {
ieee80211_wake_queue(sc->hw, q);
txq->stopped = false;
}
}
__skb_queue_tail(&txq->complete_q, skb);
}
static void ath_tx_complete_buf(struct ath_softc *sc, struct ath_buf *bf,
struct ath_txq *txq, struct list_head *bf_q,
struct ath_tx_status *ts, int txok)
{
struct sk_buff *skb = bf->bf_mpdu;
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
unsigned long flags;
int tx_flags = 0;
if (!txok)
tx_flags |= ATH_TX_ERROR;
if (ts->ts_status & ATH9K_TXERR_FILT)
tx_info->flags |= IEEE80211_TX_STAT_TX_FILTERED;
dma_unmap_single(sc->dev, bf->bf_buf_addr, skb->len, DMA_TO_DEVICE);
bf->bf_buf_addr = 0;
if (bf->bf_state.bfs_paprd) {
if (time_after(jiffies,
bf->bf_state.bfs_paprd_timestamp +
msecs_to_jiffies(ATH_PAPRD_TIMEOUT)))
dev_kfree_skb_any(skb);
else
complete(&sc->paprd_complete);
} else {
ath_debug_stat_tx(sc, bf, ts, txq, tx_flags);
ath_tx_complete(sc, skb, tx_flags, txq);
}
/* At this point, skb (bf->bf_mpdu) is consumed...make sure we don't
* accidentally reference it later.
*/
bf->bf_mpdu = NULL;
/*
* Return the list of ath_buf of this mpdu to free queue
*/
spin_lock_irqsave(&sc->tx.txbuflock, flags);
list_splice_tail_init(bf_q, &sc->tx.txbuf);
spin_unlock_irqrestore(&sc->tx.txbuflock, flags);
}
static void ath_tx_rc_status(struct ath_softc *sc, struct ath_buf *bf,
struct ath_tx_status *ts, int nframes, int nbad,
int txok)
{
struct sk_buff *skb = bf->bf_mpdu;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ieee80211_hw *hw = sc->hw;
struct ath_hw *ah = sc->sc_ah;
u8 i, tx_rateindex;
if (txok)
tx_info->status.ack_signal = ts->ts_rssi;
tx_rateindex = ts->ts_rateindex;
WARN_ON(tx_rateindex >= hw->max_rates);
if (tx_info->flags & IEEE80211_TX_CTL_AMPDU) {
tx_info->flags |= IEEE80211_TX_STAT_AMPDU;
BUG_ON(nbad > nframes);
}
tx_info->status.ampdu_len = nframes;
tx_info->status.ampdu_ack_len = nframes - nbad;
if ((ts->ts_status & ATH9K_TXERR_FILT) == 0 &&
(tx_info->flags & IEEE80211_TX_CTL_NO_ACK) == 0) {
/*
* If an underrun error is seen assume it as an excessive
* retry only if max frame trigger level has been reached
* (2 KB for single stream, and 4 KB for dual stream).
* Adjust the long retry as if the frame was tried
* hw->max_rate_tries times to affect how rate control updates
* PER for the failed rate.
* In case of congestion on the bus penalizing this type of
* underruns should help hardware actually transmit new frames
* successfully by eventually preferring slower rates.
* This itself should also alleviate congestion on the bus.
*/
if (unlikely(ts->ts_flags & (ATH9K_TX_DATA_UNDERRUN |
ATH9K_TX_DELIM_UNDERRUN)) &&
ieee80211_is_data(hdr->frame_control) &&
ah->tx_trig_level >= sc->sc_ah->config.max_txtrig_level)
tx_info->status.rates[tx_rateindex].count =
hw->max_rate_tries;
}
for (i = tx_rateindex + 1; i < hw->max_rates; i++) {
tx_info->status.rates[i].count = 0;
tx_info->status.rates[i].idx = -1;
}
tx_info->status.rates[tx_rateindex].count = ts->ts_longretry + 1;
}
static void ath_tx_process_buffer(struct ath_softc *sc, struct ath_txq *txq,
struct ath_tx_status *ts, struct ath_buf *bf,
struct list_head *bf_head)
{
int txok;
txq->axq_depth--;
txok = !(ts->ts_status & ATH9K_TXERR_MASK);
txq->axq_tx_inprogress = false;
if (bf_is_ampdu_not_probing(bf))
txq->axq_ampdu_depth--;
if (!bf_isampdu(bf)) {
ath_tx_rc_status(sc, bf, ts, 1, txok ? 0 : 1, txok);
ath_tx_complete_buf(sc, bf, txq, bf_head, ts, txok);
} else
ath_tx_complete_aggr(sc, txq, bf, bf_head, ts, txok, true);
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_HT)
ath_txq_schedule(sc, txq);
}
static void ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
{
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
struct ath_buf *bf, *lastbf, *bf_held = NULL;
struct list_head bf_head;
struct ath_desc *ds;
struct ath_tx_status ts;
int status;
ath_dbg(common, QUEUE, "tx queue %d (%x), link %p\n",
txq->axq_qnum, ath9k_hw_gettxbuf(sc->sc_ah, txq->axq_qnum),
txq->axq_link);
ath_txq_lock(sc, txq);
for (;;) {
if (work_pending(&sc->hw_reset_work))
break;
if (list_empty(&txq->axq_q)) {
txq->axq_link = NULL;
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_HT)
ath_txq_schedule(sc, txq);
break;
}
bf = list_first_entry(&txq->axq_q, struct ath_buf, list);
/*
* There is a race condition that a BH gets scheduled
* after sw writes TxE and before hw re-load the last
* descriptor to get the newly chained one.
* Software must keep the last DONE descriptor as a
* holding descriptor - software does so by marking
* it with the STALE flag.
*/
bf_held = NULL;
if (bf->bf_stale) {
bf_held = bf;
if (list_is_last(&bf_held->list, &txq->axq_q))
break;
bf = list_entry(bf_held->list.next, struct ath_buf,
list);
}
lastbf = bf->bf_lastbf;
ds = lastbf->bf_desc;
memset(&ts, 0, sizeof(ts));
status = ath9k_hw_txprocdesc(ah, ds, &ts);
if (status == -EINPROGRESS)
break;
TX_STAT_INC(txq->axq_qnum, txprocdesc);
/*
* Remove ath_buf's of the same transmit unit from txq,
* however leave the last descriptor back as the holding
* descriptor for hw.
*/
lastbf->bf_stale = true;
INIT_LIST_HEAD(&bf_head);
if (!list_is_singular(&lastbf->list))
list_cut_position(&bf_head,
&txq->axq_q, lastbf->list.prev);
if (bf_held) {
list_del(&bf_held->list);
ath_tx_return_buffer(sc, bf_held);
}
ath_tx_process_buffer(sc, txq, &ts, bf, &bf_head);
}
ath_txq_unlock_complete(sc, txq);
}
static void ath_tx_complete_poll_work(struct work_struct *work)
{
struct ath_softc *sc = container_of(work, struct ath_softc,
tx_complete_work.work);
struct ath_txq *txq;
int i;
bool needreset = false;
#ifdef CONFIG_ATH9K_DEBUGFS
sc->tx_complete_poll_work_seen++;
#endif
for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++)
if (ATH_TXQ_SETUP(sc, i)) {
txq = &sc->tx.txq[i];
ath_txq_lock(sc, txq);
if (txq->axq_depth) {
if (txq->axq_tx_inprogress) {
needreset = true;
ath_txq_unlock(sc, txq);
break;
} else {
txq->axq_tx_inprogress = true;
}
}
ath_txq_unlock_complete(sc, txq);
}
if (needreset) {
ath_dbg(ath9k_hw_common(sc->sc_ah), RESET,
"tx hung, resetting the chip\n");
RESET_STAT_INC(sc, RESET_TYPE_TX_HANG);
ieee80211_queue_work(sc->hw, &sc->hw_reset_work);
}
ieee80211_queue_delayed_work(sc->hw, &sc->tx_complete_work,
msecs_to_jiffies(ATH_TX_COMPLETE_POLL_INT));
}
void ath_tx_tasklet(struct ath_softc *sc)
{
struct ath_hw *ah = sc->sc_ah;
u32 qcumask = ((1 << ATH9K_NUM_TX_QUEUES) - 1) & ah->intr_txqs;
int i;
for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++) {
if (ATH_TXQ_SETUP(sc, i) && (qcumask & (1 << i)))
ath_tx_processq(sc, &sc->tx.txq[i]);
}
}
void ath_tx_edma_tasklet(struct ath_softc *sc)
{
struct ath_tx_status ts;
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
struct ath_hw *ah = sc->sc_ah;
struct ath_txq *txq;
struct ath_buf *bf, *lastbf;
struct list_head bf_head;
int status;
for (;;) {
if (work_pending(&sc->hw_reset_work))
break;
status = ath9k_hw_txprocdesc(ah, NULL, (void *)&ts);
if (status == -EINPROGRESS)
break;
if (status == -EIO) {
ath_dbg(common, XMIT, "Error processing tx status\n");
break;
}
/* Process beacon completions separately */
if (ts.qid == sc->beacon.beaconq) {
sc->beacon.tx_processed = true;
sc->beacon.tx_last = !(ts.ts_status & ATH9K_TXERR_MASK);
continue;
}
txq = &sc->tx.txq[ts.qid];
ath_txq_lock(sc, txq);
if (list_empty(&txq->txq_fifo[txq->txq_tailidx])) {
ath_txq_unlock(sc, txq);
return;
}
bf = list_first_entry(&txq->txq_fifo[txq->txq_tailidx],
struct ath_buf, list);
lastbf = bf->bf_lastbf;
INIT_LIST_HEAD(&bf_head);
list_cut_position(&bf_head, &txq->txq_fifo[txq->txq_tailidx],
&lastbf->list);
if (list_empty(&txq->txq_fifo[txq->txq_tailidx])) {
INCR(txq->txq_tailidx, ATH_TXFIFO_DEPTH);
if (!list_empty(&txq->axq_q)) {
struct list_head bf_q;
INIT_LIST_HEAD(&bf_q);
txq->axq_link = NULL;
list_splice_tail_init(&txq->axq_q, &bf_q);
ath_tx_txqaddbuf(sc, txq, &bf_q, true);
}
}
ath_tx_process_buffer(sc, txq, &ts, bf, &bf_head);
ath_txq_unlock_complete(sc, txq);
}
}
/*****************/
/* Init, Cleanup */
/*****************/
static int ath_txstatus_setup(struct ath_softc *sc, int size)
{
struct ath_descdma *dd = &sc->txsdma;
u8 txs_len = sc->sc_ah->caps.txs_len;
dd->dd_desc_len = size * txs_len;
dd->dd_desc = dma_alloc_coherent(sc->dev, dd->dd_desc_len,
&dd->dd_desc_paddr, GFP_KERNEL);
if (!dd->dd_desc)
return -ENOMEM;
return 0;
}
static int ath_tx_edma_init(struct ath_softc *sc)
{
int err;
err = ath_txstatus_setup(sc, ATH_TXSTATUS_RING_SIZE);
if (!err)
ath9k_hw_setup_statusring(sc->sc_ah, sc->txsdma.dd_desc,
sc->txsdma.dd_desc_paddr,
ATH_TXSTATUS_RING_SIZE);
return err;
}
static void ath_tx_edma_cleanup(struct ath_softc *sc)
{
struct ath_descdma *dd = &sc->txsdma;
dma_free_coherent(sc->dev, dd->dd_desc_len, dd->dd_desc,
dd->dd_desc_paddr);
}
int ath_tx_init(struct ath_softc *sc, int nbufs)
{
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
int error = 0;
spin_lock_init(&sc->tx.txbuflock);
error = ath_descdma_setup(sc, &sc->tx.txdma, &sc->tx.txbuf,
"tx", nbufs, 1, 1);
if (error != 0) {
ath_err(common,
"Failed to allocate tx descriptors: %d\n", error);
goto err;
}
error = ath_descdma_setup(sc, &sc->beacon.bdma, &sc->beacon.bbuf,
"beacon", ATH_BCBUF, 1, 1);
if (error != 0) {
ath_err(common,
"Failed to allocate beacon descriptors: %d\n", error);
goto err;
}
INIT_DELAYED_WORK(&sc->tx_complete_work, ath_tx_complete_poll_work);
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_EDMA) {
error = ath_tx_edma_init(sc);
if (error)
goto err;
}
err:
if (error != 0)
ath_tx_cleanup(sc);
return error;
}
void ath_tx_cleanup(struct ath_softc *sc)
{
if (sc->beacon.bdma.dd_desc_len != 0)
ath_descdma_cleanup(sc, &sc->beacon.bdma, &sc->beacon.bbuf);
if (sc->tx.txdma.dd_desc_len != 0)
ath_descdma_cleanup(sc, &sc->tx.txdma, &sc->tx.txbuf);
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_EDMA)
ath_tx_edma_cleanup(sc);
}
void ath_tx_node_init(struct ath_softc *sc, struct ath_node *an)
{
struct ath_atx_tid *tid;
struct ath_atx_ac *ac;
int tidno, acno;
for (tidno = 0, tid = &an->tid[tidno];
tidno < WME_NUM_TID;
tidno++, tid++) {
tid->an = an;
tid->tidno = tidno;
tid->seq_start = tid->seq_next = 0;
tid->baw_size = WME_MAX_BA;
tid->baw_head = tid->baw_tail = 0;
tid->sched = false;
tid->paused = false;
tid->state &= ~AGGR_CLEANUP;
__skb_queue_head_init(&tid->buf_q);
acno = TID_TO_WME_AC(tidno);
tid->ac = &an->ac[acno];
tid->state &= ~AGGR_ADDBA_COMPLETE;
tid->state &= ~AGGR_ADDBA_PROGRESS;
}
for (acno = 0, ac = &an->ac[acno];
acno < WME_NUM_AC; acno++, ac++) {
ac->sched = false;
ac->txq = sc->tx.txq_map[acno];
INIT_LIST_HEAD(&ac->tid_q);
}
}
void ath_tx_node_cleanup(struct ath_softc *sc, struct ath_node *an)
{
struct ath_atx_ac *ac;
struct ath_atx_tid *tid;
struct ath_txq *txq;
int tidno;
for (tidno = 0, tid = &an->tid[tidno];
tidno < WME_NUM_TID; tidno++, tid++) {
ac = tid->ac;
txq = ac->txq;
ath_txq_lock(sc, txq);
if (tid->sched) {
list_del(&tid->list);
tid->sched = false;
}
if (ac->sched) {
list_del(&ac->list);
tid->ac->sched = false;
}
ath_tid_drain(sc, txq, tid);
tid->state &= ~AGGR_ADDBA_COMPLETE;
tid->state &= ~AGGR_CLEANUP;
ath_txq_unlock(sc, txq);
}
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.