repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
chen2011521/xt560_kernel | drivers/gpu/drm/nouveau/nv10_fifo.c | 8135 | 7971 | /*
* Copyright (C) 2007 Ben Skeggs.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include "drmP.h"
#include "drm.h"
#include "nouveau_drv.h"
#include "nouveau_ramht.h"
#define NV10_RAMFC(c) (dev_priv->ramfc->pinst + ((c) * NV10_RAMFC__SIZE))
#define NV10_RAMFC__SIZE ((dev_priv->chipset) >= 0x17 ? 64 : 32)
int
nv10_fifo_channel_id(struct drm_device *dev)
{
return nv_rd32(dev, NV03_PFIFO_CACHE1_PUSH1) &
NV10_PFIFO_CACHE1_PUSH1_CHID_MASK;
}
int
nv10_fifo_create_context(struct nouveau_channel *chan)
{
struct drm_nouveau_private *dev_priv = chan->dev->dev_private;
struct drm_device *dev = chan->dev;
uint32_t fc = NV10_RAMFC(chan->id);
int ret;
ret = nouveau_gpuobj_new_fake(dev, NV10_RAMFC(chan->id), ~0,
NV10_RAMFC__SIZE, NVOBJ_FLAG_ZERO_ALLOC |
NVOBJ_FLAG_ZERO_FREE, &chan->ramfc);
if (ret)
return ret;
chan->user = ioremap(pci_resource_start(dev->pdev, 0) +
NV03_USER(chan->id), PAGE_SIZE);
if (!chan->user)
return -ENOMEM;
/* Fill entries that are seen filled in dumps of nvidia driver just
* after channel's is put into DMA mode
*/
nv_wi32(dev, fc + 0, chan->pushbuf_base);
nv_wi32(dev, fc + 4, chan->pushbuf_base);
nv_wi32(dev, fc + 12, chan->pushbuf->pinst >> 4);
nv_wi32(dev, fc + 20, NV_PFIFO_CACHE1_DMA_FETCH_TRIG_128_BYTES |
NV_PFIFO_CACHE1_DMA_FETCH_SIZE_128_BYTES |
NV_PFIFO_CACHE1_DMA_FETCH_MAX_REQS_8 |
#ifdef __BIG_ENDIAN
NV_PFIFO_CACHE1_BIG_ENDIAN |
#endif
0);
/* enable the fifo dma operation */
nv_wr32(dev, NV04_PFIFO_MODE,
nv_rd32(dev, NV04_PFIFO_MODE) | (1 << chan->id));
return 0;
}
static void
nv10_fifo_do_load_context(struct drm_device *dev, int chid)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
uint32_t fc = NV10_RAMFC(chid), tmp;
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_PUT, nv_ri32(dev, fc + 0));
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_GET, nv_ri32(dev, fc + 4));
nv_wr32(dev, NV10_PFIFO_CACHE1_REF_CNT, nv_ri32(dev, fc + 8));
tmp = nv_ri32(dev, fc + 12);
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_INSTANCE, tmp & 0xFFFF);
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_DCOUNT, tmp >> 16);
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_STATE, nv_ri32(dev, fc + 16));
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_FETCH, nv_ri32(dev, fc + 20));
nv_wr32(dev, NV04_PFIFO_CACHE1_ENGINE, nv_ri32(dev, fc + 24));
nv_wr32(dev, NV04_PFIFO_CACHE1_PULL1, nv_ri32(dev, fc + 28));
if (dev_priv->chipset < 0x17)
goto out;
nv_wr32(dev, NV10_PFIFO_CACHE1_ACQUIRE_VALUE, nv_ri32(dev, fc + 32));
tmp = nv_ri32(dev, fc + 36);
nv_wr32(dev, NV10_PFIFO_CACHE1_ACQUIRE_TIMESTAMP, tmp);
nv_wr32(dev, NV10_PFIFO_CACHE1_ACQUIRE_TIMEOUT, nv_ri32(dev, fc + 40));
nv_wr32(dev, NV10_PFIFO_CACHE1_SEMAPHORE, nv_ri32(dev, fc + 44));
nv_wr32(dev, NV10_PFIFO_CACHE1_DMA_SUBROUTINE, nv_ri32(dev, fc + 48));
out:
nv_wr32(dev, NV03_PFIFO_CACHE1_GET, 0);
nv_wr32(dev, NV03_PFIFO_CACHE1_PUT, 0);
}
int
nv10_fifo_load_context(struct nouveau_channel *chan)
{
struct drm_device *dev = chan->dev;
uint32_t tmp;
nv10_fifo_do_load_context(dev, chan->id);
nv_wr32(dev, NV03_PFIFO_CACHE1_PUSH1,
NV03_PFIFO_CACHE1_PUSH1_DMA | chan->id);
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_PUSH, 1);
/* Reset NV04_PFIFO_CACHE1_DMA_CTL_AT_INFO to INVALID */
tmp = nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_CTL) & ~(1 << 31);
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_CTL, tmp);
return 0;
}
int
nv10_fifo_unload_context(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_fifo_engine *pfifo = &dev_priv->engine.fifo;
uint32_t fc, tmp;
int chid;
chid = pfifo->channel_id(dev);
if (chid < 0 || chid >= dev_priv->engine.fifo.channels)
return 0;
fc = NV10_RAMFC(chid);
nv_wi32(dev, fc + 0, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_PUT));
nv_wi32(dev, fc + 4, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_GET));
nv_wi32(dev, fc + 8, nv_rd32(dev, NV10_PFIFO_CACHE1_REF_CNT));
tmp = nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_INSTANCE) & 0xFFFF;
tmp |= (nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_DCOUNT) << 16);
nv_wi32(dev, fc + 12, tmp);
nv_wi32(dev, fc + 16, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_STATE));
nv_wi32(dev, fc + 20, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_FETCH));
nv_wi32(dev, fc + 24, nv_rd32(dev, NV04_PFIFO_CACHE1_ENGINE));
nv_wi32(dev, fc + 28, nv_rd32(dev, NV04_PFIFO_CACHE1_PULL1));
if (dev_priv->chipset < 0x17)
goto out;
nv_wi32(dev, fc + 32, nv_rd32(dev, NV10_PFIFO_CACHE1_ACQUIRE_VALUE));
tmp = nv_rd32(dev, NV10_PFIFO_CACHE1_ACQUIRE_TIMESTAMP);
nv_wi32(dev, fc + 36, tmp);
nv_wi32(dev, fc + 40, nv_rd32(dev, NV10_PFIFO_CACHE1_ACQUIRE_TIMEOUT));
nv_wi32(dev, fc + 44, nv_rd32(dev, NV10_PFIFO_CACHE1_SEMAPHORE));
nv_wi32(dev, fc + 48, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_GET));
out:
nv10_fifo_do_load_context(dev, pfifo->channels - 1);
nv_wr32(dev, NV03_PFIFO_CACHE1_PUSH1, pfifo->channels - 1);
return 0;
}
static void
nv10_fifo_init_reset(struct drm_device *dev)
{
nv_wr32(dev, NV03_PMC_ENABLE,
nv_rd32(dev, NV03_PMC_ENABLE) & ~NV_PMC_ENABLE_PFIFO);
nv_wr32(dev, NV03_PMC_ENABLE,
nv_rd32(dev, NV03_PMC_ENABLE) | NV_PMC_ENABLE_PFIFO);
nv_wr32(dev, 0x003224, 0x000f0078);
nv_wr32(dev, 0x002044, 0x0101ffff);
nv_wr32(dev, 0x002040, 0x000000ff);
nv_wr32(dev, 0x002500, 0x00000000);
nv_wr32(dev, 0x003000, 0x00000000);
nv_wr32(dev, 0x003050, 0x00000000);
nv_wr32(dev, 0x003258, 0x00000000);
nv_wr32(dev, 0x003210, 0x00000000);
nv_wr32(dev, 0x003270, 0x00000000);
}
static void
nv10_fifo_init_ramxx(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
nv_wr32(dev, NV03_PFIFO_RAMHT, (0x03 << 24) /* search 128 */ |
((dev_priv->ramht->bits - 9) << 16) |
(dev_priv->ramht->gpuobj->pinst >> 8));
nv_wr32(dev, NV03_PFIFO_RAMRO, dev_priv->ramro->pinst >> 8);
if (dev_priv->chipset < 0x17) {
nv_wr32(dev, NV03_PFIFO_RAMFC, dev_priv->ramfc->pinst >> 8);
} else {
nv_wr32(dev, NV03_PFIFO_RAMFC, (dev_priv->ramfc->pinst >> 8) |
(1 << 16) /* 64 Bytes entry*/);
/* XXX nvidia blob set bit 18, 21,23 for nv20 & nv30 */
}
}
static void
nv10_fifo_init_intr(struct drm_device *dev)
{
nouveau_irq_register(dev, 8, nv04_fifo_isr);
nv_wr32(dev, 0x002100, 0xffffffff);
nv_wr32(dev, 0x002140, 0xffffffff);
}
int
nv10_fifo_init(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_fifo_engine *pfifo = &dev_priv->engine.fifo;
int i;
nv10_fifo_init_reset(dev);
nv10_fifo_init_ramxx(dev);
nv10_fifo_do_load_context(dev, pfifo->channels - 1);
nv_wr32(dev, NV03_PFIFO_CACHE1_PUSH1, pfifo->channels - 1);
nv10_fifo_init_intr(dev);
pfifo->enable(dev);
pfifo->reassign(dev, true);
for (i = 0; i < dev_priv->engine.fifo.channels; i++) {
if (dev_priv->channels.ptr[i]) {
uint32_t mode = nv_rd32(dev, NV04_PFIFO_MODE);
nv_wr32(dev, NV04_PFIFO_MODE, mode | (1 << i));
}
}
return 0;
}
| gpl-2.0 |
htc-msm8960/android_kernel_htc_msm8930 | arch/um/drivers/pcap_kern.c | 9671 | 2588 | /*
* Copyright (C) 2002 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL.
*/
#include "linux/init.h"
#include <linux/netdevice.h>
#include "net_kern.h"
#include "pcap_user.h"
struct pcap_init {
char *host_if;
int promisc;
int optimize;
char *filter;
};
void pcap_init(struct net_device *dev, void *data)
{
struct uml_net_private *pri;
struct pcap_data *ppri;
struct pcap_init *init = data;
pri = netdev_priv(dev);
ppri = (struct pcap_data *) pri->user;
ppri->host_if = init->host_if;
ppri->promisc = init->promisc;
ppri->optimize = init->optimize;
ppri->filter = init->filter;
printk("pcap backend, host interface %s\n", ppri->host_if);
}
static int pcap_read(int fd, struct sk_buff *skb, struct uml_net_private *lp)
{
return pcap_user_read(fd, skb_mac_header(skb),
skb->dev->mtu + ETH_HEADER_OTHER,
(struct pcap_data *) &lp->user);
}
static int pcap_write(int fd, struct sk_buff *skb, struct uml_net_private *lp)
{
return -EPERM;
}
static const struct net_kern_info pcap_kern_info = {
.init = pcap_init,
.protocol = eth_protocol,
.read = pcap_read,
.write = pcap_write,
};
int pcap_setup(char *str, char **mac_out, void *data)
{
struct pcap_init *init = data;
char *remain, *host_if = NULL, *options[2] = { NULL, NULL };
int i;
*init = ((struct pcap_init)
{ .host_if = "eth0",
.promisc = 1,
.optimize = 0,
.filter = NULL });
remain = split_if_spec(str, &host_if, &init->filter,
&options[0], &options[1], mac_out, NULL);
if (remain != NULL) {
printk(KERN_ERR "pcap_setup - Extra garbage on "
"specification : '%s'\n", remain);
return 0;
}
if (host_if != NULL)
init->host_if = host_if;
for (i = 0; i < ARRAY_SIZE(options); i++) {
if (options[i] == NULL)
continue;
if (!strcmp(options[i], "promisc"))
init->promisc = 1;
else if (!strcmp(options[i], "nopromisc"))
init->promisc = 0;
else if (!strcmp(options[i], "optimize"))
init->optimize = 1;
else if (!strcmp(options[i], "nooptimize"))
init->optimize = 0;
else {
printk(KERN_ERR "pcap_setup : bad option - '%s'\n",
options[i]);
return 0;
}
}
return 1;
}
static struct transport pcap_transport = {
.list = LIST_HEAD_INIT(pcap_transport.list),
.name = "pcap",
.setup = pcap_setup,
.user = &pcap_user_info,
.kern = &pcap_kern_info,
.private_size = sizeof(struct pcap_data),
.setup_size = sizeof(struct pcap_init),
};
static int register_pcap(void)
{
register_transport(&pcap_transport);
return 0;
}
late_initcall(register_pcap);
| gpl-2.0 |
SamsungGalaxyS6/kernel_samsung_exynos7420 | arch/avr32/boards/atngw100/mrmt.c | 9671 | 10132 | /*
* Board-specific setup code for Remote Media Terminal 1 (RMT1)
* add-on board for the ATNGW100 Network Gateway
*
* Copyright (C) 2008 Mediama Technologies
* Based on ATNGW100 Network Gateway (Copyright (C) Atmel)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/linkage.h>
#include <linux/platform_device.h>
#include <linux/types.h>
#include <linux/fb.h>
#include <linux/leds.h>
#include <linux/input.h>
#include <linux/gpio_keys.h>
#include <linux/atmel_serial.h>
#include <linux/spi/spi.h>
#include <linux/spi/ads7846.h>
#include <video/atmel_lcdc.h>
#include <sound/atmel-ac97c.h>
#include <asm/delay.h>
#include <asm/io.h>
#include <asm/setup.h>
#include <mach/at32ap700x.h>
#include <mach/board.h>
#include <mach/init.h>
#include <mach/portmux.h>
/* Define board-specifoic GPIO assignments */
#define PIN_LCD_BL GPIO_PIN_PA(28)
#define PWM_CH_BL 0 /* Must match with GPIO pin definition */
#define PIN_LCD_DISP GPIO_PIN_PA(31)
#define PIN_AC97_RST_N GPIO_PIN_PA(30)
#define PB_EXTINT_BASE 25
#define TS_IRQ 0
#define PIN_TS_EXTINT GPIO_PIN_PB(PB_EXTINT_BASE+TS_IRQ)
#define PIN_PB_LEFT GPIO_PIN_PB(11)
#define PIN_PB_RIGHT GPIO_PIN_PB(12)
#define PIN_PWR_SW_N GPIO_PIN_PB(14)
#define PIN_PWR_ON GPIO_PIN_PB(13)
#define PIN_ZB_RST_N GPIO_PIN_PA(21)
#define PIN_BT_RST GPIO_PIN_PA(22)
#define PIN_LED_SYS GPIO_PIN_PA(16)
#define PIN_LED_A GPIO_PIN_PA(19)
#define PIN_LED_B GPIO_PIN_PE(19)
#ifdef CONFIG_BOARD_MRMT_LCD_LQ043T3DX0X
/* Sharp LQ043T3DX0x (or compatible) panel */
static struct fb_videomode __initdata lcd_fb_modes[] = {
{
.name = "480x272 @ 59.94Hz",
.refresh = 59.94,
.xres = 480, .yres = 272,
.pixclock = KHZ2PICOS(9000),
.left_margin = 2, .right_margin = 2,
.upper_margin = 3, .lower_margin = 9,
.hsync_len = 41, .vsync_len = 1,
.sync = 0,
.vmode = FB_VMODE_NONINTERLACED,
},
};
static struct fb_monspecs __initdata lcd_fb_default_monspecs = {
.manufacturer = "SHA",
.monitor = "LQ043T3DX02",
.modedb = lcd_fb_modes,
.modedb_len = ARRAY_SIZE(lcd_fb_modes),
.hfmin = 14915,
.hfmax = 17638,
.vfmin = 53,
.vfmax = 61,
.dclkmax = 9260000,
};
static struct atmel_lcdfb_info __initdata rmt_lcdc_data = {
.default_bpp = 24,
.default_dmacon = ATMEL_LCDC_DMAEN | ATMEL_LCDC_DMA2DEN,
.default_lcdcon2 = (ATMEL_LCDC_DISTYPE_TFT
| ATMEL_LCDC_CLKMOD_ALWAYSACTIVE
| ATMEL_LCDC_INVCLK_NORMAL
| ATMEL_LCDC_MEMOR_BIG),
.lcd_wiring_mode = ATMEL_LCDC_WIRING_RGB,
.default_monspecs = &lcd_fb_default_monspecs,
.guard_time = 2,
};
#endif
#ifdef CONFIG_BOARD_MRMT_LCD_KWH043GM08
/* Sharp KWH043GM08-Fxx (or compatible) panel */
static struct fb_videomode __initdata lcd_fb_modes[] = {
{
.name = "480x272 @ 59.94Hz",
.refresh = 59.94,
.xres = 480, .yres = 272,
.pixclock = KHZ2PICOS(9000),
.left_margin = 2, .right_margin = 2,
.upper_margin = 3, .lower_margin = 9,
.hsync_len = 41, .vsync_len = 1,
.sync = 0,
.vmode = FB_VMODE_NONINTERLACED,
},
};
static struct fb_monspecs __initdata lcd_fb_default_monspecs = {
.manufacturer = "FOR",
.monitor = "KWH043GM08",
.modedb = lcd_fb_modes,
.modedb_len = ARRAY_SIZE(lcd_fb_modes),
.hfmin = 14915,
.hfmax = 17638,
.vfmin = 53,
.vfmax = 61,
.dclkmax = 9260000,
};
static struct atmel_lcdfb_info __initdata rmt_lcdc_data = {
.default_bpp = 24,
.default_dmacon = ATMEL_LCDC_DMAEN | ATMEL_LCDC_DMA2DEN,
.default_lcdcon2 = (ATMEL_LCDC_DISTYPE_TFT
| ATMEL_LCDC_CLKMOD_ALWAYSACTIVE
| ATMEL_LCDC_INVCLK_INVERTED
| ATMEL_LCDC_MEMOR_BIG),
.lcd_wiring_mode = ATMEL_LCDC_WIRING_RGB,
.default_monspecs = &lcd_fb_default_monspecs,
.guard_time = 2,
};
#endif
#ifdef CONFIG_BOARD_MRMT_AC97
static struct ac97c_platform_data __initdata ac97c0_data = {
.reset_pin = PIN_AC97_RST_N,
};
#endif
#ifdef CONFIG_BOARD_MRMT_UCB1400_TS
/* NOTE: IRQ assignment relies on kernel module parameter */
static struct platform_device rmt_ts_device = {
.name = "ucb1400_ts",
.id = -1,
}
};
#endif
#ifdef CONFIG_BOARD_MRMT_BL_PWM
/* PWM LEDs: LCD Backlight, etc */
static struct gpio_led rmt_pwm_led[] = {
/* here the "gpio" is actually a PWM channel */
{ .name = "backlight", .gpio = PWM_CH_BL, },
};
static struct gpio_led_platform_data rmt_pwm_led_data = {
.num_leds = ARRAY_SIZE(rmt_pwm_led),
.leds = rmt_pwm_led,
};
static struct platform_device rmt_pwm_led_dev = {
.name = "leds-atmel-pwm",
.id = -1,
.dev = {
.platform_data = &rmt_pwm_led_data,
},
};
#endif
#ifdef CONFIG_BOARD_MRMT_ADS7846_TS
static int ads7846_pendown_state(void)
{
return !gpio_get_value( PIN_TS_EXTINT ); /* PENIRQ.*/
}
static struct ads7846_platform_data ads_info = {
.model = 7846,
.keep_vref_on = 0, /* Use external VREF pin */
.vref_delay_usecs = 0,
.vref_mv = 3300, /* VREF = 3.3V */
.settle_delay_usecs = 800,
.penirq_recheck_delay_usecs = 800,
.x_plate_ohms = 750,
.y_plate_ohms = 300,
.pressure_max = 4096,
.debounce_max = 1,
.debounce_rep = 0,
.debounce_tol = (~0),
.get_pendown_state = ads7846_pendown_state,
.filter = NULL,
.filter_init = NULL,
};
static struct spi_board_info spi01_board_info[] __initdata = {
{
.modalias = "ads7846",
.max_speed_hz = 31250*26,
.bus_num = 0,
.chip_select = 1,
.platform_data = &ads_info,
.irq = AT32_EXTINT(TS_IRQ),
},
};
#endif
/* GPIO Keys: left, right, power, etc */
static const struct gpio_keys_button rmt_gpio_keys_buttons[] = {
[0] = {
.type = EV_KEY,
.code = KEY_POWER,
.gpio = PIN_PWR_SW_N,
.active_low = 1,
.desc = "power button",
},
[1] = {
.type = EV_KEY,
.code = KEY_LEFT,
.gpio = PIN_PB_LEFT,
.active_low = 1,
.desc = "left button",
},
[2] = {
.type = EV_KEY,
.code = KEY_RIGHT,
.gpio = PIN_PB_RIGHT,
.active_low = 1,
.desc = "right button",
},
};
static const struct gpio_keys_platform_data rmt_gpio_keys_data = {
.nbuttons = ARRAY_SIZE(rmt_gpio_keys_buttons),
.buttons = (void *) rmt_gpio_keys_buttons,
};
static struct platform_device rmt_gpio_keys = {
.name = "gpio-keys",
.id = -1,
.dev = {
.platform_data = (void *) &rmt_gpio_keys_data,
}
};
#ifdef CONFIG_BOARD_MRMT_RTC_I2C
static struct i2c_board_info __initdata mrmt1_i2c_rtc = {
I2C_BOARD_INFO("s35390a", 0x30),
.irq = 0,
};
#endif
static void mrmt_power_off(void)
{
/* PWR_ON=0 will force power off */
gpio_set_value( PIN_PWR_ON, 0 );
}
static int __init mrmt1_init(void)
{
gpio_set_value( PIN_PWR_ON, 1 ); /* Ensure PWR_ON is enabled */
pm_power_off = mrmt_power_off;
/* Setup USARTS (other than console) */
at32_map_usart(2, 1, 0); /* USART 2: /dev/ttyS1, RMT1:DB9M */
at32_map_usart(3, 2, ATMEL_USART_RTS | ATMEL_USART_CTS);
/* USART 3: /dev/ttyS2, RMT1:Wireless, w/ RTS/CTS */
at32_add_device_usart(1);
at32_add_device_usart(2);
/* Select GPIO Key pins */
at32_select_gpio( PIN_PWR_SW_N, AT32_GPIOF_DEGLITCH);
at32_select_gpio( PIN_PB_LEFT, AT32_GPIOF_DEGLITCH);
at32_select_gpio( PIN_PB_RIGHT, AT32_GPIOF_DEGLITCH);
platform_device_register(&rmt_gpio_keys);
#ifdef CONFIG_BOARD_MRMT_RTC_I2C
i2c_register_board_info(0, &mrmt1_i2c_rtc, 1);
#endif
#ifndef CONFIG_BOARD_MRMT_LCD_DISABLE
/* User "alternate" LCDC inferface on Port E & D */
/* NB: exclude LCDC_CC pin, as NGW100 reserves it for other use */
at32_add_device_lcdc(0, &rmt_lcdc_data,
fbmem_start, fbmem_size,
(ATMEL_LCDC_ALT_24BIT | ATMEL_LCDC_PE_DVAL ) );
#endif
#ifdef CONFIG_BOARD_MRMT_AC97
at32_add_device_ac97c(0, &ac97c0_data, AC97C_BOTH);
#endif
#ifdef CONFIG_BOARD_MRMT_ADS7846_TS
/* Select the Touchscreen interrupt pin mode */
at32_select_periph( GPIO_PIOB_BASE, 1 << (PB_EXTINT_BASE+TS_IRQ),
GPIO_PERIPH_A, AT32_GPIOF_DEGLITCH);
irq_set_irq_type(AT32_EXTINT(TS_IRQ), IRQ_TYPE_EDGE_FALLING);
at32_spi_setup_slaves(0,spi01_board_info,ARRAY_SIZE(spi01_board_info));
spi_register_board_info(spi01_board_info,ARRAY_SIZE(spi01_board_info));
#endif
#ifdef CONFIG_BOARD_MRMT_UCB1400_TS
/* Select the Touchscreen interrupt pin mode */
at32_select_periph( GPIO_PIOB_BASE, 1 << (PB_EXTINT_BASE+TS_IRQ),
GPIO_PERIPH_A, AT32_GPIOF_DEGLITCH);
platform_device_register(&rmt_ts_device);
#endif
at32_select_gpio( PIN_LCD_DISP, AT32_GPIOF_OUTPUT );
gpio_request( PIN_LCD_DISP, "LCD_DISP" );
gpio_direction_output( PIN_LCD_DISP, 0 ); /* LCD DISP */
#ifdef CONFIG_BOARD_MRMT_LCD_DISABLE
/* Keep Backlight and DISP off */
at32_select_gpio( PIN_LCD_BL, AT32_GPIOF_OUTPUT );
gpio_request( PIN_LCD_BL, "LCD_BL" );
gpio_direction_output( PIN_LCD_BL, 0 ); /* Backlight */
#else
gpio_set_value( PIN_LCD_DISP, 1 ); /* DISP asserted first */
#ifdef CONFIG_BOARD_MRMT_BL_PWM
/* Use PWM for Backlight controls */
at32_add_device_pwm(1 << PWM_CH_BL);
platform_device_register(&rmt_pwm_led_dev);
#else
/* Backlight always on */
udelay( 1 );
at32_select_gpio( PIN_LCD_BL, AT32_GPIOF_OUTPUT );
gpio_request( PIN_LCD_BL, "LCD_BL" );
gpio_direction_output( PIN_LCD_BL, 1 );
#endif
#endif
/* Make sure BT and Zigbee modules in reset */
at32_select_gpio( PIN_BT_RST, AT32_GPIOF_OUTPUT );
gpio_request( PIN_BT_RST, "BT_RST" );
gpio_direction_output( PIN_BT_RST, 1 );
/* BT Module in Reset */
at32_select_gpio( PIN_ZB_RST_N, AT32_GPIOF_OUTPUT );
gpio_request( PIN_ZB_RST_N, "ZB_RST_N" );
gpio_direction_output( PIN_ZB_RST_N, 0 );
/* XBee Module in Reset */
#ifdef CONFIG_BOARD_MRMT_WIRELESS_ZB
udelay( 1000 );
/* Unreset the XBee Module */
gpio_set_value( PIN_ZB_RST_N, 1 );
#endif
#ifdef CONFIG_BOARD_MRMT_WIRELESS_BT
udelay( 1000 );
/* Unreset the BT Module */
gpio_set_value( PIN_BT_RST, 0 );
#endif
return 0;
}
arch_initcall(mrmt1_init);
static int __init mrmt1_early_init(void)
{
/* To maintain power-on signal in case boot loader did not already */
at32_select_gpio( PIN_PWR_ON, AT32_GPIOF_OUTPUT );
gpio_request( PIN_PWR_ON, "PIN_PWR_ON" );
gpio_direction_output( PIN_PWR_ON, 1 );
return 0;
}
core_initcall(mrmt1_early_init);
| gpl-2.0 |
wanam/Adam-Kernel-GalaxyS6-G920F | arch/x86/math-emu/reg_ld_str.c | 14279 | 32290 | /*---------------------------------------------------------------------------+
| reg_ld_str.c |
| |
| All of the functions which transfer data between user memory and FPU_REGs.|
| |
| Copyright (C) 1992,1993,1994,1996,1997 |
| W. Metzenthen, 22 Parker St, Ormond, Vic 3163, Australia |
| E-mail billm@suburbia.net |
| |
| |
+---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------+
| Note: |
| The file contains code which accesses user memory. |
| Emulator static data may change when user memory is accessed, due to |
| other processes using the emulator while swapping is in progress. |
+---------------------------------------------------------------------------*/
#include "fpu_emu.h"
#include <asm/uaccess.h>
#include "fpu_system.h"
#include "exception.h"
#include "reg_constant.h"
#include "control_w.h"
#include "status_w.h"
#define DOUBLE_Emax 1023 /* largest valid exponent */
#define DOUBLE_Ebias 1023
#define DOUBLE_Emin (-1022) /* smallest valid exponent */
#define SINGLE_Emax 127 /* largest valid exponent */
#define SINGLE_Ebias 127
#define SINGLE_Emin (-126) /* smallest valid exponent */
static u_char normalize_no_excep(FPU_REG *r, int exp, int sign)
{
u_char tag;
setexponent16(r, exp);
tag = FPU_normalize_nuo(r);
stdexp(r);
if (sign)
setnegative(r);
return tag;
}
int FPU_tagof(FPU_REG *ptr)
{
int exp;
exp = exponent16(ptr) & 0x7fff;
if (exp == 0) {
if (!(ptr->sigh | ptr->sigl)) {
return TAG_Zero;
}
/* The number is a de-normal or pseudodenormal. */
return TAG_Special;
}
if (exp == 0x7fff) {
/* Is an Infinity, a NaN, or an unsupported data type. */
return TAG_Special;
}
if (!(ptr->sigh & 0x80000000)) {
/* Unsupported data type. */
/* Valid numbers have the ms bit set to 1. */
/* Unnormal. */
return TAG_Special;
}
return TAG_Valid;
}
/* Get a long double from user memory */
int FPU_load_extended(long double __user *s, int stnr)
{
FPU_REG *sti_ptr = &st(stnr);
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_READ, s, 10);
__copy_from_user(sti_ptr, s, 10);
RE_ENTRANT_CHECK_ON;
return FPU_tagof(sti_ptr);
}
/* Get a double from user memory */
int FPU_load_double(double __user *dfloat, FPU_REG *loaded_data)
{
int exp, tag, negative;
unsigned m64, l64;
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_READ, dfloat, 8);
FPU_get_user(m64, 1 + (unsigned long __user *)dfloat);
FPU_get_user(l64, (unsigned long __user *)dfloat);
RE_ENTRANT_CHECK_ON;
negative = (m64 & 0x80000000) ? SIGN_Negative : SIGN_Positive;
exp = ((m64 & 0x7ff00000) >> 20) - DOUBLE_Ebias + EXTENDED_Ebias;
m64 &= 0xfffff;
if (exp > DOUBLE_Emax + EXTENDED_Ebias) {
/* Infinity or NaN */
if ((m64 == 0) && (l64 == 0)) {
/* +- infinity */
loaded_data->sigh = 0x80000000;
loaded_data->sigl = 0x00000000;
exp = EXP_Infinity + EXTENDED_Ebias;
tag = TAG_Special;
} else {
/* Must be a signaling or quiet NaN */
exp = EXP_NaN + EXTENDED_Ebias;
loaded_data->sigh = (m64 << 11) | 0x80000000;
loaded_data->sigh |= l64 >> 21;
loaded_data->sigl = l64 << 11;
tag = TAG_Special; /* The calling function must look for NaNs */
}
} else if (exp < DOUBLE_Emin + EXTENDED_Ebias) {
/* Zero or de-normal */
if ((m64 == 0) && (l64 == 0)) {
/* Zero */
reg_copy(&CONST_Z, loaded_data);
exp = 0;
tag = TAG_Zero;
} else {
/* De-normal */
loaded_data->sigh = m64 << 11;
loaded_data->sigh |= l64 >> 21;
loaded_data->sigl = l64 << 11;
return normalize_no_excep(loaded_data, DOUBLE_Emin,
negative)
| (denormal_operand() < 0 ? FPU_Exception : 0);
}
} else {
loaded_data->sigh = (m64 << 11) | 0x80000000;
loaded_data->sigh |= l64 >> 21;
loaded_data->sigl = l64 << 11;
tag = TAG_Valid;
}
setexponent16(loaded_data, exp | negative);
return tag;
}
/* Get a float from user memory */
int FPU_load_single(float __user *single, FPU_REG *loaded_data)
{
unsigned m32;
int exp, tag, negative;
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_READ, single, 4);
FPU_get_user(m32, (unsigned long __user *)single);
RE_ENTRANT_CHECK_ON;
negative = (m32 & 0x80000000) ? SIGN_Negative : SIGN_Positive;
if (!(m32 & 0x7fffffff)) {
/* Zero */
reg_copy(&CONST_Z, loaded_data);
addexponent(loaded_data, negative);
return TAG_Zero;
}
exp = ((m32 & 0x7f800000) >> 23) - SINGLE_Ebias + EXTENDED_Ebias;
m32 = (m32 & 0x7fffff) << 8;
if (exp < SINGLE_Emin + EXTENDED_Ebias) {
/* De-normals */
loaded_data->sigh = m32;
loaded_data->sigl = 0;
return normalize_no_excep(loaded_data, SINGLE_Emin, negative)
| (denormal_operand() < 0 ? FPU_Exception : 0);
} else if (exp > SINGLE_Emax + EXTENDED_Ebias) {
/* Infinity or NaN */
if (m32 == 0) {
/* +- infinity */
loaded_data->sigh = 0x80000000;
loaded_data->sigl = 0x00000000;
exp = EXP_Infinity + EXTENDED_Ebias;
tag = TAG_Special;
} else {
/* Must be a signaling or quiet NaN */
exp = EXP_NaN + EXTENDED_Ebias;
loaded_data->sigh = m32 | 0x80000000;
loaded_data->sigl = 0;
tag = TAG_Special; /* The calling function must look for NaNs */
}
} else {
loaded_data->sigh = m32 | 0x80000000;
loaded_data->sigl = 0;
tag = TAG_Valid;
}
setexponent16(loaded_data, exp | negative); /* Set the sign. */
return tag;
}
/* Get a long long from user memory */
int FPU_load_int64(long long __user *_s)
{
long long s;
int sign;
FPU_REG *st0_ptr = &st(0);
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_READ, _s, 8);
if (copy_from_user(&s, _s, 8))
FPU_abort;
RE_ENTRANT_CHECK_ON;
if (s == 0) {
reg_copy(&CONST_Z, st0_ptr);
return TAG_Zero;
}
if (s > 0)
sign = SIGN_Positive;
else {
s = -s;
sign = SIGN_Negative;
}
significand(st0_ptr) = s;
return normalize_no_excep(st0_ptr, 63, sign);
}
/* Get a long from user memory */
int FPU_load_int32(long __user *_s, FPU_REG *loaded_data)
{
long s;
int negative;
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_READ, _s, 4);
FPU_get_user(s, _s);
RE_ENTRANT_CHECK_ON;
if (s == 0) {
reg_copy(&CONST_Z, loaded_data);
return TAG_Zero;
}
if (s > 0)
negative = SIGN_Positive;
else {
s = -s;
negative = SIGN_Negative;
}
loaded_data->sigh = s;
loaded_data->sigl = 0;
return normalize_no_excep(loaded_data, 31, negative);
}
/* Get a short from user memory */
int FPU_load_int16(short __user *_s, FPU_REG *loaded_data)
{
int s, negative;
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_READ, _s, 2);
/* Cast as short to get the sign extended. */
FPU_get_user(s, _s);
RE_ENTRANT_CHECK_ON;
if (s == 0) {
reg_copy(&CONST_Z, loaded_data);
return TAG_Zero;
}
if (s > 0)
negative = SIGN_Positive;
else {
s = -s;
negative = SIGN_Negative;
}
loaded_data->sigh = s << 16;
loaded_data->sigl = 0;
return normalize_no_excep(loaded_data, 15, negative);
}
/* Get a packed bcd array from user memory */
int FPU_load_bcd(u_char __user *s)
{
FPU_REG *st0_ptr = &st(0);
int pos;
u_char bcd;
long long l = 0;
int sign;
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_READ, s, 10);
RE_ENTRANT_CHECK_ON;
for (pos = 8; pos >= 0; pos--) {
l *= 10;
RE_ENTRANT_CHECK_OFF;
FPU_get_user(bcd, s + pos);
RE_ENTRANT_CHECK_ON;
l += bcd >> 4;
l *= 10;
l += bcd & 0x0f;
}
RE_ENTRANT_CHECK_OFF;
FPU_get_user(sign, s + 9);
sign = sign & 0x80 ? SIGN_Negative : SIGN_Positive;
RE_ENTRANT_CHECK_ON;
if (l == 0) {
reg_copy(&CONST_Z, st0_ptr);
addexponent(st0_ptr, sign); /* Set the sign. */
return TAG_Zero;
} else {
significand(st0_ptr) = l;
return normalize_no_excep(st0_ptr, 63, sign);
}
}
/*===========================================================================*/
/* Put a long double into user memory */
int FPU_store_extended(FPU_REG *st0_ptr, u_char st0_tag,
long double __user * d)
{
/*
The only exception raised by an attempt to store to an
extended format is the Invalid Stack exception, i.e.
attempting to store from an empty register.
*/
if (st0_tag != TAG_Empty) {
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, d, 10);
FPU_put_user(st0_ptr->sigl, (unsigned long __user *)d);
FPU_put_user(st0_ptr->sigh,
(unsigned long __user *)((u_char __user *) d + 4));
FPU_put_user(exponent16(st0_ptr),
(unsigned short __user *)((u_char __user *) d +
8));
RE_ENTRANT_CHECK_ON;
return 1;
}
/* Empty register (stack underflow) */
EXCEPTION(EX_StackUnder);
if (control_word & CW_Invalid) {
/* The masked response */
/* Put out the QNaN indefinite */
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, d, 10);
FPU_put_user(0, (unsigned long __user *)d);
FPU_put_user(0xc0000000, 1 + (unsigned long __user *)d);
FPU_put_user(0xffff, 4 + (short __user *)d);
RE_ENTRANT_CHECK_ON;
return 1;
} else
return 0;
}
/* Put a double into user memory */
int FPU_store_double(FPU_REG *st0_ptr, u_char st0_tag, double __user *dfloat)
{
unsigned long l[2];
unsigned long increment = 0; /* avoid gcc warnings */
int precision_loss;
int exp;
FPU_REG tmp;
l[0] = 0;
l[1] = 0;
if (st0_tag == TAG_Valid) {
reg_copy(st0_ptr, &tmp);
exp = exponent(&tmp);
if (exp < DOUBLE_Emin) { /* It may be a denormal */
addexponent(&tmp, -DOUBLE_Emin + 52); /* largest exp to be 51 */
denormal_arg:
if ((precision_loss = FPU_round_to_int(&tmp, st0_tag))) {
#ifdef PECULIAR_486
/* Did it round to a non-denormal ? */
/* This behaviour might be regarded as peculiar, it appears
that the 80486 rounds to the dest precision, then
converts to decide underflow. */
if (!
((tmp.sigh == 0x00100000) && (tmp.sigl == 0)
&& (st0_ptr->sigl & 0x000007ff)))
#endif /* PECULIAR_486 */
{
EXCEPTION(EX_Underflow);
/* This is a special case: see sec 16.2.5.1 of
the 80486 book */
if (!(control_word & CW_Underflow))
return 0;
}
EXCEPTION(precision_loss);
if (!(control_word & CW_Precision))
return 0;
}
l[0] = tmp.sigl;
l[1] = tmp.sigh;
} else {
if (tmp.sigl & 0x000007ff) {
precision_loss = 1;
switch (control_word & CW_RC) {
case RC_RND:
/* Rounding can get a little messy.. */
increment = ((tmp.sigl & 0x7ff) > 0x400) | /* nearest */
((tmp.sigl & 0xc00) == 0xc00); /* odd -> even */
break;
case RC_DOWN: /* towards -infinity */
increment =
signpositive(&tmp) ? 0 : tmp.
sigl & 0x7ff;
break;
case RC_UP: /* towards +infinity */
increment =
signpositive(&tmp) ? tmp.
sigl & 0x7ff : 0;
break;
case RC_CHOP:
increment = 0;
break;
}
/* Truncate the mantissa */
tmp.sigl &= 0xfffff800;
if (increment) {
if (tmp.sigl >= 0xfffff800) {
/* the sigl part overflows */
if (tmp.sigh == 0xffffffff) {
/* The sigh part overflows */
tmp.sigh = 0x80000000;
exp++;
if (exp >= EXP_OVER)
goto overflow;
} else {
tmp.sigh++;
}
tmp.sigl = 0x00000000;
} else {
/* We only need to increment sigl */
tmp.sigl += 0x00000800;
}
}
} else
precision_loss = 0;
l[0] = (tmp.sigl >> 11) | (tmp.sigh << 21);
l[1] = ((tmp.sigh >> 11) & 0xfffff);
if (exp > DOUBLE_Emax) {
overflow:
EXCEPTION(EX_Overflow);
if (!(control_word & CW_Overflow))
return 0;
set_precision_flag_up();
if (!(control_word & CW_Precision))
return 0;
/* This is a special case: see sec 16.2.5.1 of the 80486 book */
/* Overflow to infinity */
l[1] = 0x7ff00000; /* Set to + INF */
} else {
if (precision_loss) {
if (increment)
set_precision_flag_up();
else
set_precision_flag_down();
}
/* Add the exponent */
l[1] |= (((exp + DOUBLE_Ebias) & 0x7ff) << 20);
}
}
} else if (st0_tag == TAG_Zero) {
/* Number is zero */
} else if (st0_tag == TAG_Special) {
st0_tag = FPU_Special(st0_ptr);
if (st0_tag == TW_Denormal) {
/* A denormal will always underflow. */
#ifndef PECULIAR_486
/* An 80486 is supposed to be able to generate
a denormal exception here, but... */
/* Underflow has priority. */
if (control_word & CW_Underflow)
denormal_operand();
#endif /* PECULIAR_486 */
reg_copy(st0_ptr, &tmp);
goto denormal_arg;
} else if (st0_tag == TW_Infinity) {
l[1] = 0x7ff00000;
} else if (st0_tag == TW_NaN) {
/* Is it really a NaN ? */
if ((exponent(st0_ptr) == EXP_OVER)
&& (st0_ptr->sigh & 0x80000000)) {
/* See if we can get a valid NaN from the FPU_REG */
l[0] =
(st0_ptr->sigl >> 11) | (st0_ptr->
sigh << 21);
l[1] = ((st0_ptr->sigh >> 11) & 0xfffff);
if (!(st0_ptr->sigh & 0x40000000)) {
/* It is a signalling NaN */
EXCEPTION(EX_Invalid);
if (!(control_word & CW_Invalid))
return 0;
l[1] |= (0x40000000 >> 11);
}
l[1] |= 0x7ff00000;
} else {
/* It is an unsupported data type */
EXCEPTION(EX_Invalid);
if (!(control_word & CW_Invalid))
return 0;
l[1] = 0xfff80000;
}
}
} else if (st0_tag == TAG_Empty) {
/* Empty register (stack underflow) */
EXCEPTION(EX_StackUnder);
if (control_word & CW_Invalid) {
/* The masked response */
/* Put out the QNaN indefinite */
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, dfloat, 8);
FPU_put_user(0, (unsigned long __user *)dfloat);
FPU_put_user(0xfff80000,
1 + (unsigned long __user *)dfloat);
RE_ENTRANT_CHECK_ON;
return 1;
} else
return 0;
}
if (getsign(st0_ptr))
l[1] |= 0x80000000;
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, dfloat, 8);
FPU_put_user(l[0], (unsigned long __user *)dfloat);
FPU_put_user(l[1], 1 + (unsigned long __user *)dfloat);
RE_ENTRANT_CHECK_ON;
return 1;
}
/* Put a float into user memory */
int FPU_store_single(FPU_REG *st0_ptr, u_char st0_tag, float __user *single)
{
long templ = 0;
unsigned long increment = 0; /* avoid gcc warnings */
int precision_loss;
int exp;
FPU_REG tmp;
if (st0_tag == TAG_Valid) {
reg_copy(st0_ptr, &tmp);
exp = exponent(&tmp);
if (exp < SINGLE_Emin) {
addexponent(&tmp, -SINGLE_Emin + 23); /* largest exp to be 22 */
denormal_arg:
if ((precision_loss = FPU_round_to_int(&tmp, st0_tag))) {
#ifdef PECULIAR_486
/* Did it round to a non-denormal ? */
/* This behaviour might be regarded as peculiar, it appears
that the 80486 rounds to the dest precision, then
converts to decide underflow. */
if (!((tmp.sigl == 0x00800000) &&
((st0_ptr->sigh & 0x000000ff)
|| st0_ptr->sigl)))
#endif /* PECULIAR_486 */
{
EXCEPTION(EX_Underflow);
/* This is a special case: see sec 16.2.5.1 of
the 80486 book */
if (!(control_word & CW_Underflow))
return 0;
}
EXCEPTION(precision_loss);
if (!(control_word & CW_Precision))
return 0;
}
templ = tmp.sigl;
} else {
if (tmp.sigl | (tmp.sigh & 0x000000ff)) {
unsigned long sigh = tmp.sigh;
unsigned long sigl = tmp.sigl;
precision_loss = 1;
switch (control_word & CW_RC) {
case RC_RND:
increment = ((sigh & 0xff) > 0x80) /* more than half */
||(((sigh & 0xff) == 0x80) && sigl) /* more than half */
||((sigh & 0x180) == 0x180); /* round to even */
break;
case RC_DOWN: /* towards -infinity */
increment = signpositive(&tmp)
? 0 : (sigl | (sigh & 0xff));
break;
case RC_UP: /* towards +infinity */
increment = signpositive(&tmp)
? (sigl | (sigh & 0xff)) : 0;
break;
case RC_CHOP:
increment = 0;
break;
}
/* Truncate part of the mantissa */
tmp.sigl = 0;
if (increment) {
if (sigh >= 0xffffff00) {
/* The sigh part overflows */
tmp.sigh = 0x80000000;
exp++;
if (exp >= EXP_OVER)
goto overflow;
} else {
tmp.sigh &= 0xffffff00;
tmp.sigh += 0x100;
}
} else {
tmp.sigh &= 0xffffff00; /* Finish the truncation */
}
} else
precision_loss = 0;
templ = (tmp.sigh >> 8) & 0x007fffff;
if (exp > SINGLE_Emax) {
overflow:
EXCEPTION(EX_Overflow);
if (!(control_word & CW_Overflow))
return 0;
set_precision_flag_up();
if (!(control_word & CW_Precision))
return 0;
/* This is a special case: see sec 16.2.5.1 of the 80486 book. */
/* Masked response is overflow to infinity. */
templ = 0x7f800000;
} else {
if (precision_loss) {
if (increment)
set_precision_flag_up();
else
set_precision_flag_down();
}
/* Add the exponent */
templ |= ((exp + SINGLE_Ebias) & 0xff) << 23;
}
}
} else if (st0_tag == TAG_Zero) {
templ = 0;
} else if (st0_tag == TAG_Special) {
st0_tag = FPU_Special(st0_ptr);
if (st0_tag == TW_Denormal) {
reg_copy(st0_ptr, &tmp);
/* A denormal will always underflow. */
#ifndef PECULIAR_486
/* An 80486 is supposed to be able to generate
a denormal exception here, but... */
/* Underflow has priority. */
if (control_word & CW_Underflow)
denormal_operand();
#endif /* PECULIAR_486 */
goto denormal_arg;
} else if (st0_tag == TW_Infinity) {
templ = 0x7f800000;
} else if (st0_tag == TW_NaN) {
/* Is it really a NaN ? */
if ((exponent(st0_ptr) == EXP_OVER)
&& (st0_ptr->sigh & 0x80000000)) {
/* See if we can get a valid NaN from the FPU_REG */
templ = st0_ptr->sigh >> 8;
if (!(st0_ptr->sigh & 0x40000000)) {
/* It is a signalling NaN */
EXCEPTION(EX_Invalid);
if (!(control_word & CW_Invalid))
return 0;
templ |= (0x40000000 >> 8);
}
templ |= 0x7f800000;
} else {
/* It is an unsupported data type */
EXCEPTION(EX_Invalid);
if (!(control_word & CW_Invalid))
return 0;
templ = 0xffc00000;
}
}
#ifdef PARANOID
else {
EXCEPTION(EX_INTERNAL | 0x164);
return 0;
}
#endif
} else if (st0_tag == TAG_Empty) {
/* Empty register (stack underflow) */
EXCEPTION(EX_StackUnder);
if (control_word & EX_Invalid) {
/* The masked response */
/* Put out the QNaN indefinite */
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, single, 4);
FPU_put_user(0xffc00000,
(unsigned long __user *)single);
RE_ENTRANT_CHECK_ON;
return 1;
} else
return 0;
}
#ifdef PARANOID
else {
EXCEPTION(EX_INTERNAL | 0x163);
return 0;
}
#endif
if (getsign(st0_ptr))
templ |= 0x80000000;
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, single, 4);
FPU_put_user(templ, (unsigned long __user *)single);
RE_ENTRANT_CHECK_ON;
return 1;
}
/* Put a long long into user memory */
int FPU_store_int64(FPU_REG *st0_ptr, u_char st0_tag, long long __user *d)
{
FPU_REG t;
long long tll;
int precision_loss;
if (st0_tag == TAG_Empty) {
/* Empty register (stack underflow) */
EXCEPTION(EX_StackUnder);
goto invalid_operand;
} else if (st0_tag == TAG_Special) {
st0_tag = FPU_Special(st0_ptr);
if ((st0_tag == TW_Infinity) || (st0_tag == TW_NaN)) {
EXCEPTION(EX_Invalid);
goto invalid_operand;
}
}
reg_copy(st0_ptr, &t);
precision_loss = FPU_round_to_int(&t, st0_tag);
((long *)&tll)[0] = t.sigl;
((long *)&tll)[1] = t.sigh;
if ((precision_loss == 1) ||
((t.sigh & 0x80000000) &&
!((t.sigh == 0x80000000) && (t.sigl == 0) && signnegative(&t)))) {
EXCEPTION(EX_Invalid);
/* This is a special case: see sec 16.2.5.1 of the 80486 book */
invalid_operand:
if (control_word & EX_Invalid) {
/* Produce something like QNaN "indefinite" */
tll = 0x8000000000000000LL;
} else
return 0;
} else {
if (precision_loss)
set_precision_flag(precision_loss);
if (signnegative(&t))
tll = -tll;
}
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, d, 8);
if (copy_to_user(d, &tll, 8))
FPU_abort;
RE_ENTRANT_CHECK_ON;
return 1;
}
/* Put a long into user memory */
int FPU_store_int32(FPU_REG *st0_ptr, u_char st0_tag, long __user *d)
{
FPU_REG t;
int precision_loss;
if (st0_tag == TAG_Empty) {
/* Empty register (stack underflow) */
EXCEPTION(EX_StackUnder);
goto invalid_operand;
} else if (st0_tag == TAG_Special) {
st0_tag = FPU_Special(st0_ptr);
if ((st0_tag == TW_Infinity) || (st0_tag == TW_NaN)) {
EXCEPTION(EX_Invalid);
goto invalid_operand;
}
}
reg_copy(st0_ptr, &t);
precision_loss = FPU_round_to_int(&t, st0_tag);
if (t.sigh ||
((t.sigl & 0x80000000) &&
!((t.sigl == 0x80000000) && signnegative(&t)))) {
EXCEPTION(EX_Invalid);
/* This is a special case: see sec 16.2.5.1 of the 80486 book */
invalid_operand:
if (control_word & EX_Invalid) {
/* Produce something like QNaN "indefinite" */
t.sigl = 0x80000000;
} else
return 0;
} else {
if (precision_loss)
set_precision_flag(precision_loss);
if (signnegative(&t))
t.sigl = -(long)t.sigl;
}
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, d, 4);
FPU_put_user(t.sigl, (unsigned long __user *)d);
RE_ENTRANT_CHECK_ON;
return 1;
}
/* Put a short into user memory */
int FPU_store_int16(FPU_REG *st0_ptr, u_char st0_tag, short __user *d)
{
FPU_REG t;
int precision_loss;
if (st0_tag == TAG_Empty) {
/* Empty register (stack underflow) */
EXCEPTION(EX_StackUnder);
goto invalid_operand;
} else if (st0_tag == TAG_Special) {
st0_tag = FPU_Special(st0_ptr);
if ((st0_tag == TW_Infinity) || (st0_tag == TW_NaN)) {
EXCEPTION(EX_Invalid);
goto invalid_operand;
}
}
reg_copy(st0_ptr, &t);
precision_loss = FPU_round_to_int(&t, st0_tag);
if (t.sigh ||
((t.sigl & 0xffff8000) &&
!((t.sigl == 0x8000) && signnegative(&t)))) {
EXCEPTION(EX_Invalid);
/* This is a special case: see sec 16.2.5.1 of the 80486 book */
invalid_operand:
if (control_word & EX_Invalid) {
/* Produce something like QNaN "indefinite" */
t.sigl = 0x8000;
} else
return 0;
} else {
if (precision_loss)
set_precision_flag(precision_loss);
if (signnegative(&t))
t.sigl = -t.sigl;
}
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, d, 2);
FPU_put_user((short)t.sigl, d);
RE_ENTRANT_CHECK_ON;
return 1;
}
/* Put a packed bcd array into user memory */
int FPU_store_bcd(FPU_REG *st0_ptr, u_char st0_tag, u_char __user *d)
{
FPU_REG t;
unsigned long long ll;
u_char b;
int i, precision_loss;
u_char sign = (getsign(st0_ptr) == SIGN_NEG) ? 0x80 : 0;
if (st0_tag == TAG_Empty) {
/* Empty register (stack underflow) */
EXCEPTION(EX_StackUnder);
goto invalid_operand;
} else if (st0_tag == TAG_Special) {
st0_tag = FPU_Special(st0_ptr);
if ((st0_tag == TW_Infinity) || (st0_tag == TW_NaN)) {
EXCEPTION(EX_Invalid);
goto invalid_operand;
}
}
reg_copy(st0_ptr, &t);
precision_loss = FPU_round_to_int(&t, st0_tag);
ll = significand(&t);
/* Check for overflow, by comparing with 999999999999999999 decimal. */
if ((t.sigh > 0x0de0b6b3) ||
((t.sigh == 0x0de0b6b3) && (t.sigl > 0xa763ffff))) {
EXCEPTION(EX_Invalid);
/* This is a special case: see sec 16.2.5.1 of the 80486 book */
invalid_operand:
if (control_word & CW_Invalid) {
/* Produce the QNaN "indefinite" */
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, d, 10);
for (i = 0; i < 7; i++)
FPU_put_user(0, d + i); /* These bytes "undefined" */
FPU_put_user(0xc0, d + 7); /* This byte "undefined" */
FPU_put_user(0xff, d + 8);
FPU_put_user(0xff, d + 9);
RE_ENTRANT_CHECK_ON;
return 1;
} else
return 0;
} else if (precision_loss) {
/* Precision loss doesn't stop the data transfer */
set_precision_flag(precision_loss);
}
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, d, 10);
RE_ENTRANT_CHECK_ON;
for (i = 0; i < 9; i++) {
b = FPU_div_small(&ll, 10);
b |= (FPU_div_small(&ll, 10)) << 4;
RE_ENTRANT_CHECK_OFF;
FPU_put_user(b, d + i);
RE_ENTRANT_CHECK_ON;
}
RE_ENTRANT_CHECK_OFF;
FPU_put_user(sign, d + 9);
RE_ENTRANT_CHECK_ON;
return 1;
}
/*===========================================================================*/
/* r gets mangled such that sig is int, sign:
it is NOT normalized */
/* The return value (in eax) is zero if the result is exact,
if bits are changed due to rounding, truncation, etc, then
a non-zero value is returned */
/* Overflow is signalled by a non-zero return value (in eax).
In the case of overflow, the returned significand always has the
largest possible value */
int FPU_round_to_int(FPU_REG *r, u_char tag)
{
u_char very_big;
unsigned eax;
if (tag == TAG_Zero) {
/* Make sure that zero is returned */
significand(r) = 0;
return 0; /* o.k. */
}
if (exponent(r) > 63) {
r->sigl = r->sigh = ~0; /* The largest representable number */
return 1; /* overflow */
}
eax = FPU_shrxs(&r->sigl, 63 - exponent(r));
very_big = !(~(r->sigh) | ~(r->sigl)); /* test for 0xfff...fff */
#define half_or_more (eax & 0x80000000)
#define frac_part (eax)
#define more_than_half ((eax & 0x80000001) == 0x80000001)
switch (control_word & CW_RC) {
case RC_RND:
if (more_than_half /* nearest */
|| (half_or_more && (r->sigl & 1))) { /* odd -> even */
if (very_big)
return 1; /* overflow */
significand(r)++;
return PRECISION_LOST_UP;
}
break;
case RC_DOWN:
if (frac_part && getsign(r)) {
if (very_big)
return 1; /* overflow */
significand(r)++;
return PRECISION_LOST_UP;
}
break;
case RC_UP:
if (frac_part && !getsign(r)) {
if (very_big)
return 1; /* overflow */
significand(r)++;
return PRECISION_LOST_UP;
}
break;
case RC_CHOP:
break;
}
return eax ? PRECISION_LOST_DOWN : 0;
}
/*===========================================================================*/
u_char __user *fldenv(fpu_addr_modes addr_modes, u_char __user *s)
{
unsigned short tag_word = 0;
u_char tag;
int i;
if ((addr_modes.default_mode == VM86) ||
((addr_modes.default_mode == PM16)
^ (addr_modes.override.operand_size == OP_SIZE_PREFIX))) {
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_READ, s, 0x0e);
FPU_get_user(control_word, (unsigned short __user *)s);
FPU_get_user(partial_status, (unsigned short __user *)(s + 2));
FPU_get_user(tag_word, (unsigned short __user *)(s + 4));
FPU_get_user(instruction_address.offset,
(unsigned short __user *)(s + 6));
FPU_get_user(instruction_address.selector,
(unsigned short __user *)(s + 8));
FPU_get_user(operand_address.offset,
(unsigned short __user *)(s + 0x0a));
FPU_get_user(operand_address.selector,
(unsigned short __user *)(s + 0x0c));
RE_ENTRANT_CHECK_ON;
s += 0x0e;
if (addr_modes.default_mode == VM86) {
instruction_address.offset
+= (instruction_address.selector & 0xf000) << 4;
operand_address.offset +=
(operand_address.selector & 0xf000) << 4;
}
} else {
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_READ, s, 0x1c);
FPU_get_user(control_word, (unsigned short __user *)s);
FPU_get_user(partial_status, (unsigned short __user *)(s + 4));
FPU_get_user(tag_word, (unsigned short __user *)(s + 8));
FPU_get_user(instruction_address.offset,
(unsigned long __user *)(s + 0x0c));
FPU_get_user(instruction_address.selector,
(unsigned short __user *)(s + 0x10));
FPU_get_user(instruction_address.opcode,
(unsigned short __user *)(s + 0x12));
FPU_get_user(operand_address.offset,
(unsigned long __user *)(s + 0x14));
FPU_get_user(operand_address.selector,
(unsigned long __user *)(s + 0x18));
RE_ENTRANT_CHECK_ON;
s += 0x1c;
}
#ifdef PECULIAR_486
control_word &= ~0xe080;
#endif /* PECULIAR_486 */
top = (partial_status >> SW_Top_Shift) & 7;
if (partial_status & ~control_word & CW_Exceptions)
partial_status |= (SW_Summary | SW_Backward);
else
partial_status &= ~(SW_Summary | SW_Backward);
for (i = 0; i < 8; i++) {
tag = tag_word & 3;
tag_word >>= 2;
if (tag == TAG_Empty)
/* New tag is empty. Accept it */
FPU_settag(i, TAG_Empty);
else if (FPU_gettag(i) == TAG_Empty) {
/* Old tag is empty and new tag is not empty. New tag is determined
by old reg contents */
if (exponent(&fpu_register(i)) == -EXTENDED_Ebias) {
if (!
(fpu_register(i).sigl | fpu_register(i).
sigh))
FPU_settag(i, TAG_Zero);
else
FPU_settag(i, TAG_Special);
} else if (exponent(&fpu_register(i)) ==
0x7fff - EXTENDED_Ebias) {
FPU_settag(i, TAG_Special);
} else if (fpu_register(i).sigh & 0x80000000)
FPU_settag(i, TAG_Valid);
else
FPU_settag(i, TAG_Special); /* An Un-normal */
}
/* Else old tag is not empty and new tag is not empty. Old tag
remains correct */
}
return s;
}
void frstor(fpu_addr_modes addr_modes, u_char __user *data_address)
{
int i, regnr;
u_char __user *s = fldenv(addr_modes, data_address);
int offset = (top & 7) * 10, other = 80 - offset;
/* Copy all registers in stack order. */
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_READ, s, 80);
__copy_from_user(register_base + offset, s, other);
if (offset)
__copy_from_user(register_base, s + other, offset);
RE_ENTRANT_CHECK_ON;
for (i = 0; i < 8; i++) {
regnr = (i + top) & 7;
if (FPU_gettag(regnr) != TAG_Empty)
/* The loaded data over-rides all other cases. */
FPU_settag(regnr, FPU_tagof(&st(i)));
}
}
u_char __user *fstenv(fpu_addr_modes addr_modes, u_char __user *d)
{
if ((addr_modes.default_mode == VM86) ||
((addr_modes.default_mode == PM16)
^ (addr_modes.override.operand_size == OP_SIZE_PREFIX))) {
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, d, 14);
#ifdef PECULIAR_486
FPU_put_user(control_word & ~0xe080, (unsigned long __user *)d);
#else
FPU_put_user(control_word, (unsigned short __user *)d);
#endif /* PECULIAR_486 */
FPU_put_user(status_word(), (unsigned short __user *)(d + 2));
FPU_put_user(fpu_tag_word, (unsigned short __user *)(d + 4));
FPU_put_user(instruction_address.offset,
(unsigned short __user *)(d + 6));
FPU_put_user(operand_address.offset,
(unsigned short __user *)(d + 0x0a));
if (addr_modes.default_mode == VM86) {
FPU_put_user((instruction_address.
offset & 0xf0000) >> 4,
(unsigned short __user *)(d + 8));
FPU_put_user((operand_address.offset & 0xf0000) >> 4,
(unsigned short __user *)(d + 0x0c));
} else {
FPU_put_user(instruction_address.selector,
(unsigned short __user *)(d + 8));
FPU_put_user(operand_address.selector,
(unsigned short __user *)(d + 0x0c));
}
RE_ENTRANT_CHECK_ON;
d += 0x0e;
} else {
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, d, 7 * 4);
#ifdef PECULIAR_486
control_word &= ~0xe080;
/* An 80486 sets nearly all of the reserved bits to 1. */
control_word |= 0xffff0040;
partial_status = status_word() | 0xffff0000;
fpu_tag_word |= 0xffff0000;
I387->soft.fcs &= ~0xf8000000;
I387->soft.fos |= 0xffff0000;
#endif /* PECULIAR_486 */
if (__copy_to_user(d, &control_word, 7 * 4))
FPU_abort;
RE_ENTRANT_CHECK_ON;
d += 0x1c;
}
control_word |= CW_Exceptions;
partial_status &= ~(SW_Summary | SW_Backward);
return d;
}
void fsave(fpu_addr_modes addr_modes, u_char __user *data_address)
{
u_char __user *d;
int offset = (top & 7) * 10, other = 80 - offset;
d = fstenv(addr_modes, data_address);
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, d, 80);
/* Copy all registers in stack order. */
if (__copy_to_user(d, register_base + offset, other))
FPU_abort;
if (offset)
if (__copy_to_user(d + other, register_base, offset))
FPU_abort;
RE_ENTRANT_CHECK_ON;
finit();
}
/*===========================================================================*/
| gpl-2.0 |
alianmohammad/gem5-linux-kernel | drivers/media/parport/bw-qcam.c | 456 | 30379 | /*
* QuickCam Driver For Video4Linux.
*
* Video4Linux conversion work by Alan Cox.
* Parport compatibility by Phil Blundell.
* Busy loop avoidance by Mark Cooke.
*
* Module parameters:
*
* maxpoll=<1 - 5000>
*
* When polling the QuickCam for a response, busy-wait for a
* maximum of this many loops. The default of 250 gives little
* impact on interactive response.
*
* NOTE: If this parameter is set too high, the processor
* will busy wait until this loop times out, and then
* slowly poll for a further 5 seconds before failing
* the transaction. You have been warned.
*
* yieldlines=<1 - 250>
*
* When acquiring a frame from the camera, the data gathering
* loop will yield back to the scheduler after completing
* this many lines. The default of 4 provides a trade-off
* between increased frame acquisition time and impact on
* interactive response.
*/
/* qcam-lib.c -- Library for programming with the Connectix QuickCam.
* See the included documentation for usage instructions and details
* of the protocol involved. */
/* Version 0.5, August 4, 1996 */
/* Version 0.7, August 27, 1996 */
/* Version 0.9, November 17, 1996 */
/******************************************************************
Copyright (C) 1996 by Scott Laird
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL SCOTT LAIRD 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/delay.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/parport.h>
#include <linux/sched.h>
#include <linux/videodev2.h>
#include <linux/mutex.h>
#include <asm/uaccess.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-device.h>
#include <media/v4l2-fh.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-event.h>
#include <media/videobuf2-vmalloc.h>
/* One from column A... */
#define QC_NOTSET 0
#define QC_UNIDIR 1
#define QC_BIDIR 2
#define QC_SERIAL 3
/* ... and one from column B */
#define QC_ANY 0x00
#define QC_FORCE_UNIDIR 0x10
#define QC_FORCE_BIDIR 0x20
#define QC_FORCE_SERIAL 0x30
/* in the port_mode member */
#define QC_MODE_MASK 0x07
#define QC_FORCE_MASK 0x70
#define MAX_HEIGHT 243
#define MAX_WIDTH 336
/* Bit fields for status flags */
#define QC_PARAM_CHANGE 0x01 /* Camera status change has occurred */
struct qcam {
struct v4l2_device v4l2_dev;
struct video_device vdev;
struct v4l2_ctrl_handler hdl;
struct vb2_queue vb_vidq;
struct pardevice *pdev;
struct parport *pport;
struct mutex lock;
struct mutex queue_lock;
int width, height;
int bpp;
int mode;
int contrast, brightness, whitebal;
int port_mode;
int transfer_scale;
int top, left;
int status;
unsigned int saved_bits;
unsigned long in_use;
};
static unsigned int maxpoll = 250; /* Maximum busy-loop count for qcam I/O */
static unsigned int yieldlines = 4; /* Yield after this many during capture */
static int video_nr = -1;
static unsigned int force_init; /* Whether to probe aggressively */
module_param(maxpoll, int, 0);
module_param(yieldlines, int, 0);
module_param(video_nr, int, 0);
/* Set force_init=1 to avoid detection by polling status register and
* immediately attempt to initialize qcam */
module_param(force_init, int, 0);
#define MAX_CAMS 4
static struct qcam *qcams[MAX_CAMS];
static unsigned int num_cams;
static inline int read_lpstatus(struct qcam *q)
{
return parport_read_status(q->pport);
}
static inline int read_lpdata(struct qcam *q)
{
return parport_read_data(q->pport);
}
static inline void write_lpdata(struct qcam *q, int d)
{
parport_write_data(q->pport, d);
}
static void write_lpcontrol(struct qcam *q, int d)
{
if (d & 0x20) {
/* Set bidirectional mode to reverse (data in) */
parport_data_reverse(q->pport);
} else {
/* Set bidirectional mode to forward (data out) */
parport_data_forward(q->pport);
}
/* Now issue the regular port command, but strip out the
* direction flag */
d &= ~0x20;
parport_write_control(q->pport, d);
}
/* qc_waithand busy-waits for a handshake signal from the QuickCam.
* Almost all communication with the camera requires handshaking. */
static int qc_waithand(struct qcam *q, int val)
{
int status;
int runs = 0;
if (val) {
while (!((status = read_lpstatus(q)) & 8)) {
/* 1000 is enough spins on the I/O for all normal
cases, at that point we start to poll slowly
until the camera wakes up. However, we are
busy blocked until the camera responds, so
setting it lower is much better for interactive
response. */
if (runs++ > maxpoll)
msleep_interruptible(5);
if (runs > (maxpoll + 1000)) /* 5 seconds */
return -1;
}
} else {
while (((status = read_lpstatus(q)) & 8)) {
/* 1000 is enough spins on the I/O for all normal
cases, at that point we start to poll slowly
until the camera wakes up. However, we are
busy blocked until the camera responds, so
setting it lower is much better for interactive
response. */
if (runs++ > maxpoll)
msleep_interruptible(5);
if (runs++ > (maxpoll + 1000)) /* 5 seconds */
return -1;
}
}
return status;
}
/* Waithand2 is used when the qcam is in bidirectional mode, and the
* handshaking signal is CamRdy2 (bit 0 of data reg) instead of CamRdy1
* (bit 3 of status register). It also returns the last value read,
* since this data is useful. */
static unsigned int qc_waithand2(struct qcam *q, int val)
{
unsigned int status;
int runs = 0;
do {
status = read_lpdata(q);
/* 1000 is enough spins on the I/O for all normal
cases, at that point we start to poll slowly
until the camera wakes up. However, we are
busy blocked until the camera responds, so
setting it lower is much better for interactive
response. */
if (runs++ > maxpoll)
msleep_interruptible(5);
if (runs++ > (maxpoll + 1000)) /* 5 seconds */
return 0;
} while ((status & 1) != val);
return status;
}
/* qc_command is probably a bit of a misnomer -- it's used to send
* bytes *to* the camera. Generally, these bytes are either commands
* or arguments to commands, so the name fits, but it still bugs me a
* bit. See the documentation for a list of commands. */
static int qc_command(struct qcam *q, int command)
{
int n1, n2;
int cmd;
write_lpdata(q, command);
write_lpcontrol(q, 6);
n1 = qc_waithand(q, 1);
write_lpcontrol(q, 0xe);
n2 = qc_waithand(q, 0);
cmd = (n1 & 0xf0) | ((n2 & 0xf0) >> 4);
return cmd;
}
static int qc_readparam(struct qcam *q)
{
int n1, n2;
int cmd;
write_lpcontrol(q, 6);
n1 = qc_waithand(q, 1);
write_lpcontrol(q, 0xe);
n2 = qc_waithand(q, 0);
cmd = (n1 & 0xf0) | ((n2 & 0xf0) >> 4);
return cmd;
}
/* Try to detect a QuickCam. It appears to flash the upper 4 bits of
the status register at 5-10 Hz. This is only used in the autoprobe
code. Be aware that this isn't the way Connectix detects the
camera (they send a reset and try to handshake), but this should be
almost completely safe, while their method screws up my printer if
I plug it in before the camera. */
static int qc_detect(struct qcam *q)
{
int reg, lastreg;
int count = 0;
int i;
if (force_init)
return 1;
lastreg = reg = read_lpstatus(q) & 0xf0;
for (i = 0; i < 500; i++) {
reg = read_lpstatus(q) & 0xf0;
if (reg != lastreg)
count++;
lastreg = reg;
mdelay(2);
}
#if 0
/* Force camera detection during testing. Sometimes the camera
won't be flashing these bits. Possibly unloading the module
in the middle of a grab? Or some timeout condition?
I've seen this parameter as low as 19 on my 450Mhz box - mpc */
printk(KERN_DEBUG "Debugging: QCam detection counter <30-200 counts as detected>: %d\n", count);
return 1;
#endif
/* Be (even more) liberal in what you accept... */
if (count > 20 && count < 400) {
return 1; /* found */
} else {
printk(KERN_ERR "No Quickcam found on port %s\n",
q->pport->name);
printk(KERN_DEBUG "Quickcam detection counter: %u\n", count);
return 0; /* not found */
}
}
/* Decide which scan mode to use. There's no real requirement that
* the scanmode match the resolution in q->height and q-> width -- the
* camera takes the picture at the resolution specified in the
* "scanmode" and then returns the image at the resolution specified
* with the resolution commands. If the scan is bigger than the
* requested resolution, the upper-left hand corner of the scan is
* returned. If the scan is smaller, then the rest of the image
* returned contains garbage. */
static int qc_setscanmode(struct qcam *q)
{
int old_mode = q->mode;
switch (q->transfer_scale) {
case 1:
q->mode = 0;
break;
case 2:
q->mode = 4;
break;
case 4:
q->mode = 8;
break;
}
switch (q->bpp) {
case 4:
break;
case 6:
q->mode += 2;
break;
}
switch (q->port_mode & QC_MODE_MASK) {
case QC_BIDIR:
q->mode += 1;
break;
case QC_NOTSET:
case QC_UNIDIR:
break;
}
if (q->mode != old_mode)
q->status |= QC_PARAM_CHANGE;
return 0;
}
/* Reset the QuickCam. This uses the same sequence the Windows
* QuickPic program uses. Someone with a bi-directional port should
* check that bi-directional mode is detected right, and then
* implement bi-directional mode in qc_readbyte(). */
static void qc_reset(struct qcam *q)
{
switch (q->port_mode & QC_FORCE_MASK) {
case QC_FORCE_UNIDIR:
q->port_mode = (q->port_mode & ~QC_MODE_MASK) | QC_UNIDIR;
break;
case QC_FORCE_BIDIR:
q->port_mode = (q->port_mode & ~QC_MODE_MASK) | QC_BIDIR;
break;
case QC_ANY:
write_lpcontrol(q, 0x20);
write_lpdata(q, 0x75);
if (read_lpdata(q) != 0x75)
q->port_mode = (q->port_mode & ~QC_MODE_MASK) | QC_BIDIR;
else
q->port_mode = (q->port_mode & ~QC_MODE_MASK) | QC_UNIDIR;
break;
}
write_lpcontrol(q, 0xb);
udelay(250);
write_lpcontrol(q, 0xe);
qc_setscanmode(q); /* in case port_mode changed */
}
/* Reset the QuickCam and program for brightness, contrast,
* white-balance, and resolution. */
static void qc_set(struct qcam *q)
{
int val;
int val2;
/* Set the brightness. Yes, this is repetitive, but it works.
* Shorter versions seem to fail subtly. Feel free to try :-). */
/* I think the problem was in qc_command, not here -- bls */
qc_command(q, 0xb);
qc_command(q, q->brightness);
val = q->height / q->transfer_scale;
qc_command(q, 0x11);
qc_command(q, val);
if ((q->port_mode & QC_MODE_MASK) == QC_UNIDIR && q->bpp == 6) {
/* The normal "transfers per line" calculation doesn't seem to work
as expected here (and yet it works fine in qc_scan). No idea
why this case is the odd man out. Fortunately, Laird's original
working version gives me a good way to guess at working values.
-- bls */
val = q->width;
val2 = q->transfer_scale * 4;
} else {
val = q->width * q->bpp;
val2 = (((q->port_mode & QC_MODE_MASK) == QC_BIDIR) ? 24 : 8) *
q->transfer_scale;
}
val = DIV_ROUND_UP(val, val2);
qc_command(q, 0x13);
qc_command(q, val);
/* Setting top and left -- bls */
qc_command(q, 0xd);
qc_command(q, q->top);
qc_command(q, 0xf);
qc_command(q, q->left / 2);
qc_command(q, 0x19);
qc_command(q, q->contrast);
qc_command(q, 0x1f);
qc_command(q, q->whitebal);
/* Clear flag that we must update the grabbing parameters on the camera
before we grab the next frame */
q->status &= (~QC_PARAM_CHANGE);
}
/* Qc_readbytes reads some bytes from the QC and puts them in
the supplied buffer. It returns the number of bytes read,
or -1 on error. */
static inline int qc_readbytes(struct qcam *q, char buffer[])
{
int ret = 1;
unsigned int hi, lo;
unsigned int hi2, lo2;
static int state;
if (buffer == NULL) {
state = 0;
return 0;
}
switch (q->port_mode & QC_MODE_MASK) {
case QC_BIDIR: /* Bi-directional Port */
write_lpcontrol(q, 0x26);
lo = (qc_waithand2(q, 1) >> 1);
hi = (read_lpstatus(q) >> 3) & 0x1f;
write_lpcontrol(q, 0x2e);
lo2 = (qc_waithand2(q, 0) >> 1);
hi2 = (read_lpstatus(q) >> 3) & 0x1f;
switch (q->bpp) {
case 4:
buffer[0] = lo & 0xf;
buffer[1] = ((lo & 0x70) >> 4) | ((hi & 1) << 3);
buffer[2] = (hi & 0x1e) >> 1;
buffer[3] = lo2 & 0xf;
buffer[4] = ((lo2 & 0x70) >> 4) | ((hi2 & 1) << 3);
buffer[5] = (hi2 & 0x1e) >> 1;
ret = 6;
break;
case 6:
buffer[0] = lo & 0x3f;
buffer[1] = ((lo & 0x40) >> 6) | (hi << 1);
buffer[2] = lo2 & 0x3f;
buffer[3] = ((lo2 & 0x40) >> 6) | (hi2 << 1);
ret = 4;
break;
}
break;
case QC_UNIDIR: /* Unidirectional Port */
write_lpcontrol(q, 6);
lo = (qc_waithand(q, 1) & 0xf0) >> 4;
write_lpcontrol(q, 0xe);
hi = (qc_waithand(q, 0) & 0xf0) >> 4;
switch (q->bpp) {
case 4:
buffer[0] = lo;
buffer[1] = hi;
ret = 2;
break;
case 6:
switch (state) {
case 0:
buffer[0] = (lo << 2) | ((hi & 0xc) >> 2);
q->saved_bits = (hi & 3) << 4;
state = 1;
ret = 1;
break;
case 1:
buffer[0] = lo | q->saved_bits;
q->saved_bits = hi << 2;
state = 2;
ret = 1;
break;
case 2:
buffer[0] = ((lo & 0xc) >> 2) | q->saved_bits;
buffer[1] = ((lo & 3) << 4) | hi;
state = 0;
ret = 2;
break;
}
break;
}
break;
}
return ret;
}
/* requests a scan from the camera. It sends the correct instructions
* to the camera and then reads back the correct number of bytes. In
* previous versions of this routine the return structure contained
* the raw output from the camera, and there was a 'qc_convertscan'
* function that converted that to a useful format. In version 0.3 I
* rolled qc_convertscan into qc_scan and now I only return the
* converted scan. The format is just an one-dimensional array of
* characters, one for each pixel, with 0=black up to n=white, where
* n=2^(bit depth)-1. Ask me for more details if you don't understand
* this. */
static long qc_capture(struct qcam *q, u8 *buf, unsigned long len)
{
int i, j, k, yield;
int bytes;
int linestotrans, transperline;
int divisor;
int pixels_per_line;
int pixels_read = 0;
int got = 0;
char buffer[6];
int shift = 8 - q->bpp;
char invert;
if (q->mode == -1)
return -ENXIO;
qc_command(q, 0x7);
qc_command(q, q->mode);
if ((q->port_mode & QC_MODE_MASK) == QC_BIDIR) {
write_lpcontrol(q, 0x2e); /* turn port around */
write_lpcontrol(q, 0x26);
qc_waithand(q, 1);
write_lpcontrol(q, 0x2e);
qc_waithand(q, 0);
}
/* strange -- should be 15:63 below, but 4bpp is odd */
invert = (q->bpp == 4) ? 16 : 63;
linestotrans = q->height / q->transfer_scale;
pixels_per_line = q->width / q->transfer_scale;
transperline = q->width * q->bpp;
divisor = (((q->port_mode & QC_MODE_MASK) == QC_BIDIR) ? 24 : 8) *
q->transfer_scale;
transperline = DIV_ROUND_UP(transperline, divisor);
for (i = 0, yield = yieldlines; i < linestotrans; i++) {
for (pixels_read = j = 0; j < transperline; j++) {
bytes = qc_readbytes(q, buffer);
for (k = 0; k < bytes && (pixels_read + k) < pixels_per_line; k++) {
int o;
if (buffer[k] == 0 && invert == 16) {
/* 4bpp is odd (again) -- inverter is 16, not 15, but output
must be 0-15 -- bls */
buffer[k] = 16;
}
o = i * pixels_per_line + pixels_read + k;
if (o < len) {
u8 ch = invert - buffer[k];
got++;
buf[o] = ch << shift;
}
}
pixels_read += bytes;
}
qc_readbytes(q, NULL); /* reset state machine */
/* Grabbing an entire frame from the quickcam is a lengthy
process. We don't (usually) want to busy-block the
processor for the entire frame. yieldlines is a module
parameter. If we yield every line, the minimum frame
time will be 240 / 200 = 1.2 seconds. The compile-time
default is to yield every 4 lines. */
if (i >= yield) {
msleep_interruptible(5);
yield = i + yieldlines;
}
}
if ((q->port_mode & QC_MODE_MASK) == QC_BIDIR) {
write_lpcontrol(q, 2);
write_lpcontrol(q, 6);
udelay(3);
write_lpcontrol(q, 0xe);
}
if (got < len)
return got;
return len;
}
/* ------------------------------------------------------------------
Videobuf operations
------------------------------------------------------------------*/
static int queue_setup(struct vb2_queue *vq, const struct v4l2_format *fmt,
unsigned int *nbuffers, unsigned int *nplanes,
unsigned int sizes[], void *alloc_ctxs[])
{
struct qcam *dev = vb2_get_drv_priv(vq);
if (0 == *nbuffers)
*nbuffers = 3;
*nplanes = 1;
mutex_lock(&dev->lock);
if (fmt)
sizes[0] = fmt->fmt.pix.width * fmt->fmt.pix.height;
else
sizes[0] = (dev->width / dev->transfer_scale) *
(dev->height / dev->transfer_scale);
mutex_unlock(&dev->lock);
return 0;
}
static void buffer_queue(struct vb2_buffer *vb)
{
vb2_buffer_done(vb, VB2_BUF_STATE_DONE);
}
static int buffer_finish(struct vb2_buffer *vb)
{
struct qcam *qcam = vb2_get_drv_priv(vb->vb2_queue);
void *vbuf = vb2_plane_vaddr(vb, 0);
int size = vb->vb2_queue->plane_sizes[0];
int len;
mutex_lock(&qcam->lock);
parport_claim_or_block(qcam->pdev);
qc_reset(qcam);
/* Update the camera parameters if we need to */
if (qcam->status & QC_PARAM_CHANGE)
qc_set(qcam);
len = qc_capture(qcam, vbuf, size);
parport_release(qcam->pdev);
mutex_unlock(&qcam->lock);
v4l2_get_timestamp(&vb->v4l2_buf.timestamp);
if (len != size)
vb->state = VB2_BUF_STATE_ERROR;
vb2_set_plane_payload(vb, 0, len);
return 0;
}
static struct vb2_ops qcam_video_qops = {
.queue_setup = queue_setup,
.buf_queue = buffer_queue,
.buf_finish = buffer_finish,
.wait_prepare = vb2_ops_wait_prepare,
.wait_finish = vb2_ops_wait_finish,
};
/*
* Video4linux interfacing
*/
static int qcam_querycap(struct file *file, void *priv,
struct v4l2_capability *vcap)
{
struct qcam *qcam = video_drvdata(file);
strlcpy(vcap->driver, qcam->v4l2_dev.name, sizeof(vcap->driver));
strlcpy(vcap->card, "Connectix B&W Quickcam", sizeof(vcap->card));
strlcpy(vcap->bus_info, qcam->pport->name, sizeof(vcap->bus_info));
vcap->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE |
V4L2_CAP_STREAMING;
vcap->capabilities = vcap->device_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
}
static int qcam_enum_input(struct file *file, void *fh, struct v4l2_input *vin)
{
if (vin->index > 0)
return -EINVAL;
strlcpy(vin->name, "Camera", sizeof(vin->name));
vin->type = V4L2_INPUT_TYPE_CAMERA;
vin->audioset = 0;
vin->tuner = 0;
vin->std = 0;
vin->status = 0;
return 0;
}
static int qcam_g_input(struct file *file, void *fh, unsigned int *inp)
{
*inp = 0;
return 0;
}
static int qcam_s_input(struct file *file, void *fh, unsigned int inp)
{
return (inp > 0) ? -EINVAL : 0;
}
static int qcam_g_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct qcam *qcam = video_drvdata(file);
struct v4l2_pix_format *pix = &fmt->fmt.pix;
pix->width = qcam->width / qcam->transfer_scale;
pix->height = qcam->height / qcam->transfer_scale;
pix->pixelformat = (qcam->bpp == 4) ? V4L2_PIX_FMT_Y4 : V4L2_PIX_FMT_Y6;
pix->field = V4L2_FIELD_NONE;
pix->bytesperline = pix->width;
pix->sizeimage = pix->width * pix->height;
/* Just a guess */
pix->colorspace = V4L2_COLORSPACE_SRGB;
pix->priv = 0;
return 0;
}
static int qcam_try_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct v4l2_pix_format *pix = &fmt->fmt.pix;
if (pix->height <= 60 || pix->width <= 80) {
pix->height = 60;
pix->width = 80;
} else if (pix->height <= 120 || pix->width <= 160) {
pix->height = 120;
pix->width = 160;
} else {
pix->height = 240;
pix->width = 320;
}
if (pix->pixelformat != V4L2_PIX_FMT_Y4 &&
pix->pixelformat != V4L2_PIX_FMT_Y6)
pix->pixelformat = V4L2_PIX_FMT_Y4;
pix->field = V4L2_FIELD_NONE;
pix->bytesperline = pix->width;
pix->sizeimage = pix->width * pix->height;
/* Just a guess */
pix->colorspace = V4L2_COLORSPACE_SRGB;
pix->priv = 0;
return 0;
}
static int qcam_s_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct qcam *qcam = video_drvdata(file);
struct v4l2_pix_format *pix = &fmt->fmt.pix;
int ret = qcam_try_fmt_vid_cap(file, fh, fmt);
if (ret)
return ret;
if (vb2_is_busy(&qcam->vb_vidq))
return -EBUSY;
qcam->width = 320;
qcam->height = 240;
if (pix->height == 60)
qcam->transfer_scale = 4;
else if (pix->height == 120)
qcam->transfer_scale = 2;
else
qcam->transfer_scale = 1;
if (pix->pixelformat == V4L2_PIX_FMT_Y6)
qcam->bpp = 6;
else
qcam->bpp = 4;
qc_setscanmode(qcam);
/* We must update the camera before we grab. We could
just have changed the grab size */
qcam->status |= QC_PARAM_CHANGE;
return 0;
}
static int qcam_enum_fmt_vid_cap(struct file *file, void *fh, struct v4l2_fmtdesc *fmt)
{
static struct v4l2_fmtdesc formats[] = {
{ 0, 0, 0,
"4-Bit Monochrome", V4L2_PIX_FMT_Y4,
{ 0, 0, 0, 0 }
},
{ 1, 0, 0,
"6-Bit Monochrome", V4L2_PIX_FMT_Y6,
{ 0, 0, 0, 0 }
},
};
enum v4l2_buf_type type = fmt->type;
if (fmt->index > 1)
return -EINVAL;
*fmt = formats[fmt->index];
fmt->type = type;
return 0;
}
static int qcam_enum_framesizes(struct file *file, void *fh,
struct v4l2_frmsizeenum *fsize)
{
static const struct v4l2_frmsize_discrete sizes[] = {
{ 80, 60 },
{ 160, 120 },
{ 320, 240 },
};
if (fsize->index > 2)
return -EINVAL;
if (fsize->pixel_format != V4L2_PIX_FMT_Y4 &&
fsize->pixel_format != V4L2_PIX_FMT_Y6)
return -EINVAL;
fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
fsize->discrete = sizes[fsize->index];
return 0;
}
static int qcam_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct qcam *qcam =
container_of(ctrl->handler, struct qcam, hdl);
int ret = 0;
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
qcam->brightness = ctrl->val;
break;
case V4L2_CID_CONTRAST:
qcam->contrast = ctrl->val;
break;
case V4L2_CID_GAMMA:
qcam->whitebal = ctrl->val;
break;
default:
ret = -EINVAL;
break;
}
if (ret == 0)
qcam->status |= QC_PARAM_CHANGE;
return ret;
}
static const struct v4l2_file_operations qcam_fops = {
.owner = THIS_MODULE,
.open = v4l2_fh_open,
.release = vb2_fop_release,
.poll = vb2_fop_poll,
.unlocked_ioctl = video_ioctl2,
.read = vb2_fop_read,
.mmap = vb2_fop_mmap,
};
static const struct v4l2_ioctl_ops qcam_ioctl_ops = {
.vidioc_querycap = qcam_querycap,
.vidioc_g_input = qcam_g_input,
.vidioc_s_input = qcam_s_input,
.vidioc_enum_input = qcam_enum_input,
.vidioc_enum_fmt_vid_cap = qcam_enum_fmt_vid_cap,
.vidioc_enum_framesizes = qcam_enum_framesizes,
.vidioc_g_fmt_vid_cap = qcam_g_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = qcam_s_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = qcam_try_fmt_vid_cap,
.vidioc_reqbufs = vb2_ioctl_reqbufs,
.vidioc_create_bufs = vb2_ioctl_create_bufs,
.vidioc_prepare_buf = vb2_ioctl_prepare_buf,
.vidioc_querybuf = vb2_ioctl_querybuf,
.vidioc_qbuf = vb2_ioctl_qbuf,
.vidioc_dqbuf = vb2_ioctl_dqbuf,
.vidioc_streamon = vb2_ioctl_streamon,
.vidioc_streamoff = vb2_ioctl_streamoff,
.vidioc_log_status = v4l2_ctrl_log_status,
.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
};
static const struct v4l2_ctrl_ops qcam_ctrl_ops = {
.s_ctrl = qcam_s_ctrl,
};
/* Initialize the QuickCam driver control structure. This is where
* defaults are set for people who don't have a config file.*/
static struct qcam *qcam_init(struct parport *port)
{
struct qcam *qcam;
struct v4l2_device *v4l2_dev;
struct vb2_queue *q;
int err;
qcam = kzalloc(sizeof(struct qcam), GFP_KERNEL);
if (qcam == NULL)
return NULL;
v4l2_dev = &qcam->v4l2_dev;
snprintf(v4l2_dev->name, sizeof(v4l2_dev->name), "bw-qcam%d", num_cams);
if (v4l2_device_register(port->dev, v4l2_dev) < 0) {
v4l2_err(v4l2_dev, "Could not register v4l2_device\n");
kfree(qcam);
return NULL;
}
v4l2_ctrl_handler_init(&qcam->hdl, 3);
v4l2_ctrl_new_std(&qcam->hdl, &qcam_ctrl_ops,
V4L2_CID_BRIGHTNESS, 0, 255, 1, 180);
v4l2_ctrl_new_std(&qcam->hdl, &qcam_ctrl_ops,
V4L2_CID_CONTRAST, 0, 255, 1, 192);
v4l2_ctrl_new_std(&qcam->hdl, &qcam_ctrl_ops,
V4L2_CID_GAMMA, 0, 255, 1, 105);
if (qcam->hdl.error) {
v4l2_err(v4l2_dev, "couldn't register controls\n");
goto exit;
}
mutex_init(&qcam->lock);
mutex_init(&qcam->queue_lock);
/* initialize queue */
q = &qcam->vb_vidq;
q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ;
q->drv_priv = qcam;
q->ops = &qcam_video_qops;
q->mem_ops = &vb2_vmalloc_memops;
q->timestamp_type = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
err = vb2_queue_init(q);
if (err < 0) {
v4l2_err(v4l2_dev, "couldn't init vb2_queue for %s.\n", port->name);
goto exit;
}
qcam->vdev.queue = q;
qcam->vdev.queue->lock = &qcam->queue_lock;
qcam->pport = port;
qcam->pdev = parport_register_device(port, v4l2_dev->name, NULL, NULL,
NULL, 0, NULL);
if (qcam->pdev == NULL) {
v4l2_err(v4l2_dev, "couldn't register for %s.\n", port->name);
goto exit;
}
strlcpy(qcam->vdev.name, "Connectix QuickCam", sizeof(qcam->vdev.name));
qcam->vdev.v4l2_dev = v4l2_dev;
qcam->vdev.ctrl_handler = &qcam->hdl;
qcam->vdev.fops = &qcam_fops;
qcam->vdev.lock = &qcam->lock;
qcam->vdev.ioctl_ops = &qcam_ioctl_ops;
set_bit(V4L2_FL_USE_FH_PRIO, &qcam->vdev.flags);
qcam->vdev.release = video_device_release_empty;
video_set_drvdata(&qcam->vdev, qcam);
qcam->port_mode = (QC_ANY | QC_NOTSET);
qcam->width = 320;
qcam->height = 240;
qcam->bpp = 4;
qcam->transfer_scale = 2;
qcam->contrast = 192;
qcam->brightness = 180;
qcam->whitebal = 105;
qcam->top = 1;
qcam->left = 14;
qcam->mode = -1;
qcam->status = QC_PARAM_CHANGE;
return qcam;
exit:
v4l2_ctrl_handler_free(&qcam->hdl);
kfree(qcam);
return NULL;
}
static int qc_calibrate(struct qcam *q)
{
/*
* Bugfix by Hanno Mueller hmueller@kabel.de, Mai 21 96
* The white balance is an individual value for each
* quickcam.
*/
int value;
int count = 0;
qc_command(q, 27); /* AutoAdjustOffset */
qc_command(q, 0); /* Dummy Parameter, ignored by the camera */
/* GetOffset (33) will read 255 until autocalibration */
/* is finished. After that, a value of 1-254 will be */
/* returned. */
do {
qc_command(q, 33);
value = qc_readparam(q);
mdelay(1);
schedule();
count++;
} while (value == 0xff && count < 2048);
q->whitebal = value;
return value;
}
static int init_bwqcam(struct parport *port)
{
struct qcam *qcam;
if (num_cams == MAX_CAMS) {
printk(KERN_ERR "Too many Quickcams (max %d)\n", MAX_CAMS);
return -ENOSPC;
}
qcam = qcam_init(port);
if (qcam == NULL)
return -ENODEV;
parport_claim_or_block(qcam->pdev);
qc_reset(qcam);
if (qc_detect(qcam) == 0) {
parport_release(qcam->pdev);
parport_unregister_device(qcam->pdev);
kfree(qcam);
return -ENODEV;
}
qc_calibrate(qcam);
v4l2_ctrl_handler_setup(&qcam->hdl);
parport_release(qcam->pdev);
v4l2_info(&qcam->v4l2_dev, "Connectix Quickcam on %s\n", qcam->pport->name);
if (video_register_device(&qcam->vdev, VFL_TYPE_GRABBER, video_nr) < 0) {
parport_unregister_device(qcam->pdev);
kfree(qcam);
return -ENODEV;
}
qcams[num_cams++] = qcam;
return 0;
}
static void close_bwqcam(struct qcam *qcam)
{
video_unregister_device(&qcam->vdev);
v4l2_ctrl_handler_free(&qcam->hdl);
parport_unregister_device(qcam->pdev);
kfree(qcam);
}
/* The parport parameter controls which parports will be scanned.
* Scanning all parports causes some printers to print a garbage page.
* -- March 14, 1999 Billy Donahue <billy@escape.com> */
#ifdef MODULE
static char *parport[MAX_CAMS] = { NULL, };
module_param_array(parport, charp, NULL, 0);
#endif
static int accept_bwqcam(struct parport *port)
{
#ifdef MODULE
int n;
if (parport[0] && strncmp(parport[0], "auto", 4) != 0) {
/* user gave parport parameters */
for (n = 0; n < MAX_CAMS && parport[n]; n++) {
char *ep;
unsigned long r;
r = simple_strtoul(parport[n], &ep, 0);
if (ep == parport[n]) {
printk(KERN_ERR
"bw-qcam: bad port specifier \"%s\"\n",
parport[n]);
continue;
}
if (r == port->number)
return 1;
}
return 0;
}
#endif
return 1;
}
static void bwqcam_attach(struct parport *port)
{
if (accept_bwqcam(port))
init_bwqcam(port);
}
static void bwqcam_detach(struct parport *port)
{
int i;
for (i = 0; i < num_cams; i++) {
struct qcam *qcam = qcams[i];
if (qcam && qcam->pdev->port == port) {
qcams[i] = NULL;
close_bwqcam(qcam);
}
}
}
static struct parport_driver bwqcam_driver = {
.name = "bw-qcam",
.attach = bwqcam_attach,
.detach = bwqcam_detach,
};
static void __exit exit_bw_qcams(void)
{
parport_unregister_driver(&bwqcam_driver);
}
static int __init init_bw_qcams(void)
{
#ifdef MODULE
/* Do some sanity checks on the module parameters. */
if (maxpoll > 5000) {
printk(KERN_INFO "Connectix Quickcam max-poll was above 5000. Using 5000.\n");
maxpoll = 5000;
}
if (yieldlines < 1) {
printk(KERN_INFO "Connectix Quickcam yieldlines was less than 1. Using 1.\n");
yieldlines = 1;
}
#endif
return parport_register_driver(&bwqcam_driver);
}
module_init(init_bw_qcams);
module_exit(exit_bw_qcams);
MODULE_LICENSE("GPL");
MODULE_VERSION("0.0.3");
| gpl-2.0 |
wangxiaofei6485/linux-2.6.32-fl2440 | arch/arm/mach-omap1/board-fsample.c | 456 | 8321 | /*
* linux/arch/arm/mach-omap1/board-fsample.c
*
* Modified from board-perseus2.c
*
* Original OMAP730 support by Jean Pihet <j-pihet@ti.com>
* Updated for 2.6 by Kevin Hilman <kjh@hilman.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include <linux/input.h>
#include <mach/hardware.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/flash.h>
#include <asm/mach/map.h>
#include <mach/tc.h>
#include <mach/gpio.h>
#include <mach/mux.h>
#include <mach/fpga.h>
#include <mach/nand.h>
#include <mach/keypad.h>
#include <mach/common.h>
#include <mach/board.h>
/* fsample is pretty close to p2-sample */
#define fsample_cpld_read(reg) __raw_readb(reg)
#define fsample_cpld_write(val, reg) __raw_writeb(val, reg)
#define FSAMPLE_CPLD_BASE 0xE8100000
#define FSAMPLE_CPLD_SIZE SZ_4K
#define FSAMPLE_CPLD_START 0x05080000
#define FSAMPLE_CPLD_REG_A (FSAMPLE_CPLD_BASE + 0x00)
#define FSAMPLE_CPLD_SWITCH (FSAMPLE_CPLD_BASE + 0x02)
#define FSAMPLE_CPLD_UART (FSAMPLE_CPLD_BASE + 0x02)
#define FSAMPLE_CPLD_REG_B (FSAMPLE_CPLD_BASE + 0x04)
#define FSAMPLE_CPLD_VERSION (FSAMPLE_CPLD_BASE + 0x06)
#define FSAMPLE_CPLD_SET_CLR (FSAMPLE_CPLD_BASE + 0x06)
#define FSAMPLE_CPLD_BIT_BT_RESET 0
#define FSAMPLE_CPLD_BIT_LCD_RESET 1
#define FSAMPLE_CPLD_BIT_CAM_PWDN 2
#define FSAMPLE_CPLD_BIT_CHARGER_ENABLE 3
#define FSAMPLE_CPLD_BIT_SD_MMC_EN 4
#define FSAMPLE_CPLD_BIT_aGPS_PWREN 5
#define FSAMPLE_CPLD_BIT_BACKLIGHT 6
#define FSAMPLE_CPLD_BIT_aGPS_EN_RESET 7
#define FSAMPLE_CPLD_BIT_aGPS_SLEEPx_N 8
#define FSAMPLE_CPLD_BIT_OTG_RESET 9
#define fsample_cpld_set(bit) \
fsample_cpld_write((((bit) & 15) << 4) | 0x0f, FSAMPLE_CPLD_SET_CLR)
#define fsample_cpld_clear(bit) \
fsample_cpld_write(0xf0 | ((bit) & 15), FSAMPLE_CPLD_SET_CLR)
static int fsample_keymap[] = {
KEY(0,0,KEY_UP),
KEY(0,1,KEY_RIGHT),
KEY(0,2,KEY_LEFT),
KEY(0,3,KEY_DOWN),
KEY(0,4,KEY_ENTER),
KEY(1,0,KEY_F10),
KEY(1,1,KEY_SEND),
KEY(1,2,KEY_END),
KEY(1,3,KEY_VOLUMEDOWN),
KEY(1,4,KEY_VOLUMEUP),
KEY(1,5,KEY_RECORD),
KEY(2,0,KEY_F9),
KEY(2,1,KEY_3),
KEY(2,2,KEY_6),
KEY(2,3,KEY_9),
KEY(2,4,KEY_KPDOT),
KEY(3,0,KEY_BACK),
KEY(3,1,KEY_2),
KEY(3,2,KEY_5),
KEY(3,3,KEY_8),
KEY(3,4,KEY_0),
KEY(3,5,KEY_KPSLASH),
KEY(4,0,KEY_HOME),
KEY(4,1,KEY_1),
KEY(4,2,KEY_4),
KEY(4,3,KEY_7),
KEY(4,4,KEY_KPASTERISK),
KEY(4,5,KEY_POWER),
0
};
static struct resource smc91x_resources[] = {
[0] = {
.start = H2P2_DBG_FPGA_ETHR_START, /* Physical */
.end = H2P2_DBG_FPGA_ETHR_START + 0xf,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = INT_730_MPU_EXT_NIRQ,
.end = 0,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHEDGE,
},
};
static struct mtd_partition nor_partitions[] = {
/* bootloader (U-Boot, etc) in first sector */
{
.name = "bootloader",
.offset = 0,
.size = SZ_128K,
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
/* bootloader params in the next sector */
{
.name = "params",
.offset = MTDPART_OFS_APPEND,
.size = SZ_128K,
.mask_flags = 0,
},
/* kernel */
{
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = SZ_2M,
.mask_flags = 0
},
/* rest of flash is a file system */
{
.name = "rootfs",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
.mask_flags = 0
},
};
static struct flash_platform_data nor_data = {
.map_name = "cfi_probe",
.width = 2,
.parts = nor_partitions,
.nr_parts = ARRAY_SIZE(nor_partitions),
};
static struct resource nor_resource = {
.start = OMAP_CS0_PHYS,
.end = OMAP_CS0_PHYS + SZ_32M - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device nor_device = {
.name = "omapflash",
.id = 0,
.dev = {
.platform_data = &nor_data,
},
.num_resources = 1,
.resource = &nor_resource,
};
static struct omap_nand_platform_data nand_data = {
.options = NAND_SAMSUNG_LP_OPTIONS,
};
static struct resource nand_resource = {
.start = OMAP_CS3_PHYS,
.end = OMAP_CS3_PHYS + SZ_4K - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device nand_device = {
.name = "omapnand",
.id = 0,
.dev = {
.platform_data = &nand_data,
},
.num_resources = 1,
.resource = &nand_resource,
};
static struct platform_device smc91x_device = {
.name = "smc91x",
.id = 0,
.num_resources = ARRAY_SIZE(smc91x_resources),
.resource = smc91x_resources,
};
static struct resource kp_resources[] = {
[0] = {
.start = INT_730_MPUIO_KEYPAD,
.end = INT_730_MPUIO_KEYPAD,
.flags = IORESOURCE_IRQ,
},
};
static struct omap_kp_platform_data kp_data = {
.rows = 8,
.cols = 8,
.keymap = fsample_keymap,
.keymapsize = ARRAY_SIZE(fsample_keymap),
.delay = 4,
};
static struct platform_device kp_device = {
.name = "omap-keypad",
.id = -1,
.dev = {
.platform_data = &kp_data,
},
.num_resources = ARRAY_SIZE(kp_resources),
.resource = kp_resources,
};
static struct platform_device lcd_device = {
.name = "lcd_p2",
.id = -1,
};
static struct platform_device *devices[] __initdata = {
&nor_device,
&nand_device,
&smc91x_device,
&kp_device,
&lcd_device,
};
#define P2_NAND_RB_GPIO_PIN 62
static int nand_dev_ready(struct omap_nand_platform_data *data)
{
return gpio_get_value(P2_NAND_RB_GPIO_PIN);
}
static struct omap_lcd_config fsample_lcd_config __initdata = {
.ctrl_name = "internal",
};
static struct omap_board_config_kernel fsample_config[] = {
{ OMAP_TAG_LCD, &fsample_lcd_config },
};
static void __init omap_fsample_init(void)
{
if (gpio_request(P2_NAND_RB_GPIO_PIN, "NAND ready") < 0)
BUG();
nand_data.dev_ready = nand_dev_ready;
omap_cfg_reg(L3_1610_FLASH_CS2B_OE);
omap_cfg_reg(M8_1610_FLASH_CS2B_WE);
platform_add_devices(devices, ARRAY_SIZE(devices));
omap_board_config = fsample_config;
omap_board_config_size = ARRAY_SIZE(fsample_config);
omap_serial_init();
omap_register_i2c_bus(1, 100, NULL, 0);
}
static void __init fsample_init_smc91x(void)
{
fpga_write(1, H2P2_DBG_FPGA_LAN_RESET);
mdelay(50);
fpga_write(fpga_read(H2P2_DBG_FPGA_LAN_RESET) & ~1,
H2P2_DBG_FPGA_LAN_RESET);
mdelay(50);
}
static void __init omap_fsample_init_irq(void)
{
omap1_init_common_hw();
omap_init_irq();
omap_gpio_init();
fsample_init_smc91x();
}
/* Only FPGA needs to be mapped here. All others are done with ioremap */
static struct map_desc omap_fsample_io_desc[] __initdata = {
{
.virtual = H2P2_DBG_FPGA_BASE,
.pfn = __phys_to_pfn(H2P2_DBG_FPGA_START),
.length = H2P2_DBG_FPGA_SIZE,
.type = MT_DEVICE
},
{
.virtual = FSAMPLE_CPLD_BASE,
.pfn = __phys_to_pfn(FSAMPLE_CPLD_START),
.length = FSAMPLE_CPLD_SIZE,
.type = MT_DEVICE
}
};
static void __init omap_fsample_map_io(void)
{
omap1_map_common_io();
iotable_init(omap_fsample_io_desc,
ARRAY_SIZE(omap_fsample_io_desc));
/* Early, board-dependent init */
/*
* Hold GSM Reset until needed
*/
omap_writew(omap_readw(OMAP730_DSP_M_CTL) & ~1, OMAP730_DSP_M_CTL);
/*
* UARTs -> done automagically by 8250 driver
*/
/*
* CSx timings, GPIO Mux ... setup
*/
/* Flash: CS0 timings setup */
omap_writel(0x0000fff3, OMAP730_FLASH_CFG_0);
omap_writel(0x00000088, OMAP730_FLASH_ACFG_0);
/*
* Ethernet support through the debug board
* CS1 timings setup
*/
omap_writel(0x0000fff3, OMAP730_FLASH_CFG_1);
omap_writel(0x00000000, OMAP730_FLASH_ACFG_1);
/*
* Configure MPU_EXT_NIRQ IO in IO_CONF9 register,
* It is used as the Ethernet controller interrupt
*/
omap_writel(omap_readl(OMAP730_IO_CONF_9) & 0x1FFFFFFF, OMAP730_IO_CONF_9);
}
MACHINE_START(OMAP_FSAMPLE, "OMAP730 F-Sample")
/* Maintainer: Brian Swetland <swetland@google.com> */
.phys_io = 0xfff00000,
.io_pg_offst = ((0xfef00000) >> 18) & 0xfffc,
.boot_params = 0x10000100,
.map_io = omap_fsample_map_io,
.init_irq = omap_fsample_init_irq,
.init_machine = omap_fsample_init,
.timer = &omap_timer,
MACHINE_END
| gpl-2.0 |
jemmy655/linux | drivers/crypto/mv_cesa.c | 712 | 30150 | /*
* Support for Marvell's crypto engine which can be found on some Orion5X
* boards.
*
* Author: Sebastian Andrzej Siewior < sebastian at breakpoint dot cc >
* License: GPLv2
*
*/
#include <crypto/aes.h>
#include <crypto/algapi.h>
#include <linux/crypto.h>
#include <linux/genalloc.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kthread.h>
#include <linux/platform_device.h>
#include <linux/scatterlist.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/clk.h>
#include <crypto/internal/hash.h>
#include <crypto/sha.h>
#include <linux/of.h>
#include <linux/of_platform.h>
#include <linux/of_irq.h>
#include "mv_cesa.h"
#define MV_CESA "MV-CESA:"
#define MAX_HW_HASH_SIZE 0xFFFF
#define MV_CESA_EXPIRE 500 /* msec */
#define MV_CESA_DEFAULT_SRAM_SIZE 2048
/*
* STM:
* /---------------------------------------\
* | | request complete
* \./ |
* IDLE -> new request -> BUSY -> done -> DEQUEUE
* /°\ |
* | | more scatter entries
* \________________/
*/
enum engine_status {
ENGINE_IDLE,
ENGINE_BUSY,
ENGINE_W_DEQUEUE,
};
/**
* struct req_progress - used for every crypt request
* @src_sg_it: sg iterator for src
* @dst_sg_it: sg iterator for dst
* @sg_src_left: bytes left in src to process (scatter list)
* @src_start: offset to add to src start position (scatter list)
* @crypt_len: length of current hw crypt/hash process
* @hw_nbytes: total bytes to process in hw for this request
* @copy_back: whether to copy data back (crypt) or not (hash)
* @sg_dst_left: bytes left dst to process in this scatter list
* @dst_start: offset to add to dst start position (scatter list)
* @hw_processed_bytes: number of bytes processed by hw (request).
*
* sg helper are used to iterate over the scatterlist. Since the size of the
* SRAM may be less than the scatter size, this struct struct is used to keep
* track of progress within current scatterlist.
*/
struct req_progress {
struct sg_mapping_iter src_sg_it;
struct sg_mapping_iter dst_sg_it;
void (*complete) (void);
void (*process) (int is_first);
/* src mostly */
int sg_src_left;
int src_start;
int crypt_len;
int hw_nbytes;
/* dst mostly */
int copy_back;
int sg_dst_left;
int dst_start;
int hw_processed_bytes;
};
struct crypto_priv {
void __iomem *reg;
void __iomem *sram;
struct gen_pool *sram_pool;
dma_addr_t sram_dma;
int irq;
struct clk *clk;
struct task_struct *queue_th;
/* the lock protects queue and eng_st */
spinlock_t lock;
struct crypto_queue queue;
enum engine_status eng_st;
struct timer_list completion_timer;
struct crypto_async_request *cur_req;
struct req_progress p;
int max_req_size;
int sram_size;
int has_sha1;
int has_hmac_sha1;
};
static struct crypto_priv *cpg;
struct mv_ctx {
u8 aes_enc_key[AES_KEY_LEN];
u32 aes_dec_key[8];
int key_len;
u32 need_calc_aes_dkey;
};
enum crypto_op {
COP_AES_ECB,
COP_AES_CBC,
};
struct mv_req_ctx {
enum crypto_op op;
int decrypt;
};
enum hash_op {
COP_SHA1,
COP_HMAC_SHA1
};
struct mv_tfm_hash_ctx {
struct crypto_shash *fallback;
struct crypto_shash *base_hash;
u32 ivs[2 * SHA1_DIGEST_SIZE / 4];
int count_add;
enum hash_op op;
};
struct mv_req_hash_ctx {
u64 count;
u32 state[SHA1_DIGEST_SIZE / 4];
u8 buffer[SHA1_BLOCK_SIZE];
int first_hash; /* marks that we don't have previous state */
int last_chunk; /* marks that this is the 'final' request */
int extra_bytes; /* unprocessed bytes in buffer */
enum hash_op op;
int count_add;
};
static void mv_completion_timer_callback(unsigned long unused)
{
int active = readl(cpg->reg + SEC_ACCEL_CMD) & SEC_CMD_EN_SEC_ACCL0;
printk(KERN_ERR MV_CESA
"completion timer expired (CESA %sactive), cleaning up.\n",
active ? "" : "in");
del_timer(&cpg->completion_timer);
writel(SEC_CMD_DISABLE_SEC, cpg->reg + SEC_ACCEL_CMD);
while(readl(cpg->reg + SEC_ACCEL_CMD) & SEC_CMD_DISABLE_SEC)
printk(KERN_INFO MV_CESA "%s: waiting for engine finishing\n", __func__);
cpg->eng_st = ENGINE_W_DEQUEUE;
wake_up_process(cpg->queue_th);
}
static void mv_setup_timer(void)
{
setup_timer(&cpg->completion_timer, &mv_completion_timer_callback, 0);
mod_timer(&cpg->completion_timer,
jiffies + msecs_to_jiffies(MV_CESA_EXPIRE));
}
static void compute_aes_dec_key(struct mv_ctx *ctx)
{
struct crypto_aes_ctx gen_aes_key;
int key_pos;
if (!ctx->need_calc_aes_dkey)
return;
crypto_aes_expand_key(&gen_aes_key, ctx->aes_enc_key, ctx->key_len);
key_pos = ctx->key_len + 24;
memcpy(ctx->aes_dec_key, &gen_aes_key.key_enc[key_pos], 4 * 4);
switch (ctx->key_len) {
case AES_KEYSIZE_256:
key_pos -= 2;
/* fall */
case AES_KEYSIZE_192:
key_pos -= 2;
memcpy(&ctx->aes_dec_key[4], &gen_aes_key.key_enc[key_pos],
4 * 4);
break;
}
ctx->need_calc_aes_dkey = 0;
}
static int mv_setkey_aes(struct crypto_ablkcipher *cipher, const u8 *key,
unsigned int len)
{
struct crypto_tfm *tfm = crypto_ablkcipher_tfm(cipher);
struct mv_ctx *ctx = crypto_tfm_ctx(tfm);
switch (len) {
case AES_KEYSIZE_128:
case AES_KEYSIZE_192:
case AES_KEYSIZE_256:
break;
default:
crypto_ablkcipher_set_flags(cipher, CRYPTO_TFM_RES_BAD_KEY_LEN);
return -EINVAL;
}
ctx->key_len = len;
ctx->need_calc_aes_dkey = 1;
memcpy(ctx->aes_enc_key, key, AES_KEY_LEN);
return 0;
}
static void copy_src_to_buf(struct req_progress *p, char *dbuf, int len)
{
int ret;
void *sbuf;
int copy_len;
while (len) {
if (!p->sg_src_left) {
ret = sg_miter_next(&p->src_sg_it);
BUG_ON(!ret);
p->sg_src_left = p->src_sg_it.length;
p->src_start = 0;
}
sbuf = p->src_sg_it.addr + p->src_start;
copy_len = min(p->sg_src_left, len);
memcpy(dbuf, sbuf, copy_len);
p->src_start += copy_len;
p->sg_src_left -= copy_len;
len -= copy_len;
dbuf += copy_len;
}
}
static void setup_data_in(void)
{
struct req_progress *p = &cpg->p;
int data_in_sram =
min(p->hw_nbytes - p->hw_processed_bytes, cpg->max_req_size);
copy_src_to_buf(p, cpg->sram + SRAM_DATA_IN_START + p->crypt_len,
data_in_sram - p->crypt_len);
p->crypt_len = data_in_sram;
}
static void mv_process_current_q(int first_block)
{
struct ablkcipher_request *req = ablkcipher_request_cast(cpg->cur_req);
struct mv_ctx *ctx = crypto_tfm_ctx(req->base.tfm);
struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);
struct sec_accel_config op;
switch (req_ctx->op) {
case COP_AES_ECB:
op.config = CFG_OP_CRYPT_ONLY | CFG_ENCM_AES | CFG_ENC_MODE_ECB;
break;
case COP_AES_CBC:
default:
op.config = CFG_OP_CRYPT_ONLY | CFG_ENCM_AES | CFG_ENC_MODE_CBC;
op.enc_iv = ENC_IV_POINT(SRAM_DATA_IV) |
ENC_IV_BUF_POINT(SRAM_DATA_IV_BUF);
if (first_block)
memcpy(cpg->sram + SRAM_DATA_IV, req->info, 16);
break;
}
if (req_ctx->decrypt) {
op.config |= CFG_DIR_DEC;
memcpy(cpg->sram + SRAM_DATA_KEY_P, ctx->aes_dec_key,
AES_KEY_LEN);
} else {
op.config |= CFG_DIR_ENC;
memcpy(cpg->sram + SRAM_DATA_KEY_P, ctx->aes_enc_key,
AES_KEY_LEN);
}
switch (ctx->key_len) {
case AES_KEYSIZE_128:
op.config |= CFG_AES_LEN_128;
break;
case AES_KEYSIZE_192:
op.config |= CFG_AES_LEN_192;
break;
case AES_KEYSIZE_256:
op.config |= CFG_AES_LEN_256;
break;
}
op.enc_p = ENC_P_SRC(SRAM_DATA_IN_START) |
ENC_P_DST(SRAM_DATA_OUT_START);
op.enc_key_p = SRAM_DATA_KEY_P;
setup_data_in();
op.enc_len = cpg->p.crypt_len;
memcpy(cpg->sram + SRAM_CONFIG, &op,
sizeof(struct sec_accel_config));
/* GO */
mv_setup_timer();
writel(SEC_CMD_EN_SEC_ACCL0, cpg->reg + SEC_ACCEL_CMD);
}
static void mv_crypto_algo_completion(void)
{
struct ablkcipher_request *req = ablkcipher_request_cast(cpg->cur_req);
struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);
sg_miter_stop(&cpg->p.src_sg_it);
sg_miter_stop(&cpg->p.dst_sg_it);
if (req_ctx->op != COP_AES_CBC)
return ;
memcpy(req->info, cpg->sram + SRAM_DATA_IV_BUF, 16);
}
static void mv_process_hash_current(int first_block)
{
struct ahash_request *req = ahash_request_cast(cpg->cur_req);
const struct mv_tfm_hash_ctx *tfm_ctx = crypto_tfm_ctx(req->base.tfm);
struct mv_req_hash_ctx *req_ctx = ahash_request_ctx(req);
struct req_progress *p = &cpg->p;
struct sec_accel_config op = { 0 };
int is_last;
switch (req_ctx->op) {
case COP_SHA1:
default:
op.config = CFG_OP_MAC_ONLY | CFG_MACM_SHA1;
break;
case COP_HMAC_SHA1:
op.config = CFG_OP_MAC_ONLY | CFG_MACM_HMAC_SHA1;
memcpy(cpg->sram + SRAM_HMAC_IV_IN,
tfm_ctx->ivs, sizeof(tfm_ctx->ivs));
break;
}
op.mac_src_p =
MAC_SRC_DATA_P(SRAM_DATA_IN_START) | MAC_SRC_TOTAL_LEN((u32)
req_ctx->
count);
setup_data_in();
op.mac_digest =
MAC_DIGEST_P(SRAM_DIGEST_BUF) | MAC_FRAG_LEN(p->crypt_len);
op.mac_iv =
MAC_INNER_IV_P(SRAM_HMAC_IV_IN) |
MAC_OUTER_IV_P(SRAM_HMAC_IV_OUT);
is_last = req_ctx->last_chunk
&& (p->hw_processed_bytes + p->crypt_len >= p->hw_nbytes)
&& (req_ctx->count <= MAX_HW_HASH_SIZE);
if (req_ctx->first_hash) {
if (is_last)
op.config |= CFG_NOT_FRAG;
else
op.config |= CFG_FIRST_FRAG;
req_ctx->first_hash = 0;
} else {
if (is_last)
op.config |= CFG_LAST_FRAG;
else
op.config |= CFG_MID_FRAG;
if (first_block) {
writel(req_ctx->state[0], cpg->reg + DIGEST_INITIAL_VAL_A);
writel(req_ctx->state[1], cpg->reg + DIGEST_INITIAL_VAL_B);
writel(req_ctx->state[2], cpg->reg + DIGEST_INITIAL_VAL_C);
writel(req_ctx->state[3], cpg->reg + DIGEST_INITIAL_VAL_D);
writel(req_ctx->state[4], cpg->reg + DIGEST_INITIAL_VAL_E);
}
}
memcpy(cpg->sram + SRAM_CONFIG, &op, sizeof(struct sec_accel_config));
/* GO */
mv_setup_timer();
writel(SEC_CMD_EN_SEC_ACCL0, cpg->reg + SEC_ACCEL_CMD);
}
static inline int mv_hash_import_sha1_ctx(const struct mv_req_hash_ctx *ctx,
struct shash_desc *desc)
{
int i;
struct sha1_state shash_state;
shash_state.count = ctx->count + ctx->count_add;
for (i = 0; i < 5; i++)
shash_state.state[i] = ctx->state[i];
memcpy(shash_state.buffer, ctx->buffer, sizeof(shash_state.buffer));
return crypto_shash_import(desc, &shash_state);
}
static int mv_hash_final_fallback(struct ahash_request *req)
{
const struct mv_tfm_hash_ctx *tfm_ctx = crypto_tfm_ctx(req->base.tfm);
struct mv_req_hash_ctx *req_ctx = ahash_request_ctx(req);
SHASH_DESC_ON_STACK(shash, tfm_ctx->fallback);
int rc;
shash->tfm = tfm_ctx->fallback;
shash->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
if (unlikely(req_ctx->first_hash)) {
crypto_shash_init(shash);
crypto_shash_update(shash, req_ctx->buffer,
req_ctx->extra_bytes);
} else {
/* only SHA1 for now....
*/
rc = mv_hash_import_sha1_ctx(req_ctx, shash);
if (rc)
goto out;
}
rc = crypto_shash_final(shash, req->result);
out:
return rc;
}
static void mv_save_digest_state(struct mv_req_hash_ctx *ctx)
{
ctx->state[0] = readl(cpg->reg + DIGEST_INITIAL_VAL_A);
ctx->state[1] = readl(cpg->reg + DIGEST_INITIAL_VAL_B);
ctx->state[2] = readl(cpg->reg + DIGEST_INITIAL_VAL_C);
ctx->state[3] = readl(cpg->reg + DIGEST_INITIAL_VAL_D);
ctx->state[4] = readl(cpg->reg + DIGEST_INITIAL_VAL_E);
}
static void mv_hash_algo_completion(void)
{
struct ahash_request *req = ahash_request_cast(cpg->cur_req);
struct mv_req_hash_ctx *ctx = ahash_request_ctx(req);
if (ctx->extra_bytes)
copy_src_to_buf(&cpg->p, ctx->buffer, ctx->extra_bytes);
sg_miter_stop(&cpg->p.src_sg_it);
if (likely(ctx->last_chunk)) {
if (likely(ctx->count <= MAX_HW_HASH_SIZE)) {
memcpy(req->result, cpg->sram + SRAM_DIGEST_BUF,
crypto_ahash_digestsize(crypto_ahash_reqtfm
(req)));
} else {
mv_save_digest_state(ctx);
mv_hash_final_fallback(req);
}
} else {
mv_save_digest_state(ctx);
}
}
static void dequeue_complete_req(void)
{
struct crypto_async_request *req = cpg->cur_req;
void *buf;
int ret;
cpg->p.hw_processed_bytes += cpg->p.crypt_len;
if (cpg->p.copy_back) {
int need_copy_len = cpg->p.crypt_len;
int sram_offset = 0;
do {
int dst_copy;
if (!cpg->p.sg_dst_left) {
ret = sg_miter_next(&cpg->p.dst_sg_it);
BUG_ON(!ret);
cpg->p.sg_dst_left = cpg->p.dst_sg_it.length;
cpg->p.dst_start = 0;
}
buf = cpg->p.dst_sg_it.addr;
buf += cpg->p.dst_start;
dst_copy = min(need_copy_len, cpg->p.sg_dst_left);
memcpy(buf,
cpg->sram + SRAM_DATA_OUT_START + sram_offset,
dst_copy);
sram_offset += dst_copy;
cpg->p.sg_dst_left -= dst_copy;
need_copy_len -= dst_copy;
cpg->p.dst_start += dst_copy;
} while (need_copy_len > 0);
}
cpg->p.crypt_len = 0;
BUG_ON(cpg->eng_st != ENGINE_W_DEQUEUE);
if (cpg->p.hw_processed_bytes < cpg->p.hw_nbytes) {
/* process next scatter list entry */
cpg->eng_st = ENGINE_BUSY;
cpg->p.process(0);
} else {
cpg->p.complete();
cpg->eng_st = ENGINE_IDLE;
local_bh_disable();
req->complete(req, 0);
local_bh_enable();
}
}
static int count_sgs(struct scatterlist *sl, unsigned int total_bytes)
{
int i = 0;
size_t cur_len;
while (sl) {
cur_len = sl[i].length;
++i;
if (total_bytes > cur_len)
total_bytes -= cur_len;
else
break;
}
return i;
}
static void mv_start_new_crypt_req(struct ablkcipher_request *req)
{
struct req_progress *p = &cpg->p;
int num_sgs;
cpg->cur_req = &req->base;
memset(p, 0, sizeof(struct req_progress));
p->hw_nbytes = req->nbytes;
p->complete = mv_crypto_algo_completion;
p->process = mv_process_current_q;
p->copy_back = 1;
num_sgs = count_sgs(req->src, req->nbytes);
sg_miter_start(&p->src_sg_it, req->src, num_sgs, SG_MITER_FROM_SG);
num_sgs = count_sgs(req->dst, req->nbytes);
sg_miter_start(&p->dst_sg_it, req->dst, num_sgs, SG_MITER_TO_SG);
mv_process_current_q(1);
}
static void mv_start_new_hash_req(struct ahash_request *req)
{
struct req_progress *p = &cpg->p;
struct mv_req_hash_ctx *ctx = ahash_request_ctx(req);
int num_sgs, hw_bytes, old_extra_bytes, rc;
cpg->cur_req = &req->base;
memset(p, 0, sizeof(struct req_progress));
hw_bytes = req->nbytes + ctx->extra_bytes;
old_extra_bytes = ctx->extra_bytes;
ctx->extra_bytes = hw_bytes % SHA1_BLOCK_SIZE;
if (ctx->extra_bytes != 0
&& (!ctx->last_chunk || ctx->count > MAX_HW_HASH_SIZE))
hw_bytes -= ctx->extra_bytes;
else
ctx->extra_bytes = 0;
num_sgs = count_sgs(req->src, req->nbytes);
sg_miter_start(&p->src_sg_it, req->src, num_sgs, SG_MITER_FROM_SG);
if (hw_bytes) {
p->hw_nbytes = hw_bytes;
p->complete = mv_hash_algo_completion;
p->process = mv_process_hash_current;
if (unlikely(old_extra_bytes)) {
memcpy(cpg->sram + SRAM_DATA_IN_START, ctx->buffer,
old_extra_bytes);
p->crypt_len = old_extra_bytes;
}
mv_process_hash_current(1);
} else {
copy_src_to_buf(p, ctx->buffer + old_extra_bytes,
ctx->extra_bytes - old_extra_bytes);
sg_miter_stop(&p->src_sg_it);
if (ctx->last_chunk)
rc = mv_hash_final_fallback(req);
else
rc = 0;
cpg->eng_st = ENGINE_IDLE;
local_bh_disable();
req->base.complete(&req->base, rc);
local_bh_enable();
}
}
static int queue_manag(void *data)
{
cpg->eng_st = ENGINE_IDLE;
do {
struct crypto_async_request *async_req = NULL;
struct crypto_async_request *backlog = NULL;
__set_current_state(TASK_INTERRUPTIBLE);
if (cpg->eng_st == ENGINE_W_DEQUEUE)
dequeue_complete_req();
spin_lock_irq(&cpg->lock);
if (cpg->eng_st == ENGINE_IDLE) {
backlog = crypto_get_backlog(&cpg->queue);
async_req = crypto_dequeue_request(&cpg->queue);
if (async_req) {
BUG_ON(cpg->eng_st != ENGINE_IDLE);
cpg->eng_st = ENGINE_BUSY;
}
}
spin_unlock_irq(&cpg->lock);
if (backlog) {
backlog->complete(backlog, -EINPROGRESS);
backlog = NULL;
}
if (async_req) {
if (crypto_tfm_alg_type(async_req->tfm) !=
CRYPTO_ALG_TYPE_AHASH) {
struct ablkcipher_request *req =
ablkcipher_request_cast(async_req);
mv_start_new_crypt_req(req);
} else {
struct ahash_request *req =
ahash_request_cast(async_req);
mv_start_new_hash_req(req);
}
async_req = NULL;
}
schedule();
} while (!kthread_should_stop());
return 0;
}
static int mv_handle_req(struct crypto_async_request *req)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&cpg->lock, flags);
ret = crypto_enqueue_request(&cpg->queue, req);
spin_unlock_irqrestore(&cpg->lock, flags);
wake_up_process(cpg->queue_th);
return ret;
}
static int mv_enc_aes_ecb(struct ablkcipher_request *req)
{
struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);
req_ctx->op = COP_AES_ECB;
req_ctx->decrypt = 0;
return mv_handle_req(&req->base);
}
static int mv_dec_aes_ecb(struct ablkcipher_request *req)
{
struct mv_ctx *ctx = crypto_tfm_ctx(req->base.tfm);
struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);
req_ctx->op = COP_AES_ECB;
req_ctx->decrypt = 1;
compute_aes_dec_key(ctx);
return mv_handle_req(&req->base);
}
static int mv_enc_aes_cbc(struct ablkcipher_request *req)
{
struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);
req_ctx->op = COP_AES_CBC;
req_ctx->decrypt = 0;
return mv_handle_req(&req->base);
}
static int mv_dec_aes_cbc(struct ablkcipher_request *req)
{
struct mv_ctx *ctx = crypto_tfm_ctx(req->base.tfm);
struct mv_req_ctx *req_ctx = ablkcipher_request_ctx(req);
req_ctx->op = COP_AES_CBC;
req_ctx->decrypt = 1;
compute_aes_dec_key(ctx);
return mv_handle_req(&req->base);
}
static int mv_cra_init(struct crypto_tfm *tfm)
{
tfm->crt_ablkcipher.reqsize = sizeof(struct mv_req_ctx);
return 0;
}
static void mv_init_hash_req_ctx(struct mv_req_hash_ctx *ctx, int op,
int is_last, unsigned int req_len,
int count_add)
{
memset(ctx, 0, sizeof(*ctx));
ctx->op = op;
ctx->count = req_len;
ctx->first_hash = 1;
ctx->last_chunk = is_last;
ctx->count_add = count_add;
}
static void mv_update_hash_req_ctx(struct mv_req_hash_ctx *ctx, int is_last,
unsigned req_len)
{
ctx->last_chunk = is_last;
ctx->count += req_len;
}
static int mv_hash_init(struct ahash_request *req)
{
const struct mv_tfm_hash_ctx *tfm_ctx = crypto_tfm_ctx(req->base.tfm);
mv_init_hash_req_ctx(ahash_request_ctx(req), tfm_ctx->op, 0, 0,
tfm_ctx->count_add);
return 0;
}
static int mv_hash_update(struct ahash_request *req)
{
if (!req->nbytes)
return 0;
mv_update_hash_req_ctx(ahash_request_ctx(req), 0, req->nbytes);
return mv_handle_req(&req->base);
}
static int mv_hash_final(struct ahash_request *req)
{
struct mv_req_hash_ctx *ctx = ahash_request_ctx(req);
ahash_request_set_crypt(req, NULL, req->result, 0);
mv_update_hash_req_ctx(ctx, 1, 0);
return mv_handle_req(&req->base);
}
static int mv_hash_finup(struct ahash_request *req)
{
mv_update_hash_req_ctx(ahash_request_ctx(req), 1, req->nbytes);
return mv_handle_req(&req->base);
}
static int mv_hash_digest(struct ahash_request *req)
{
const struct mv_tfm_hash_ctx *tfm_ctx = crypto_tfm_ctx(req->base.tfm);
mv_init_hash_req_ctx(ahash_request_ctx(req), tfm_ctx->op, 1,
req->nbytes, tfm_ctx->count_add);
return mv_handle_req(&req->base);
}
static void mv_hash_init_ivs(struct mv_tfm_hash_ctx *ctx, const void *istate,
const void *ostate)
{
const struct sha1_state *isha1_state = istate, *osha1_state = ostate;
int i;
for (i = 0; i < 5; i++) {
ctx->ivs[i] = cpu_to_be32(isha1_state->state[i]);
ctx->ivs[i + 5] = cpu_to_be32(osha1_state->state[i]);
}
}
static int mv_hash_setkey(struct crypto_ahash *tfm, const u8 * key,
unsigned int keylen)
{
int rc;
struct mv_tfm_hash_ctx *ctx = crypto_tfm_ctx(&tfm->base);
int bs, ds, ss;
if (!ctx->base_hash)
return 0;
rc = crypto_shash_setkey(ctx->fallback, key, keylen);
if (rc)
return rc;
/* Can't see a way to extract the ipad/opad from the fallback tfm
so I'm basically copying code from the hmac module */
bs = crypto_shash_blocksize(ctx->base_hash);
ds = crypto_shash_digestsize(ctx->base_hash);
ss = crypto_shash_statesize(ctx->base_hash);
{
SHASH_DESC_ON_STACK(shash, ctx->base_hash);
unsigned int i;
char ipad[ss];
char opad[ss];
shash->tfm = ctx->base_hash;
shash->flags = crypto_shash_get_flags(ctx->base_hash) &
CRYPTO_TFM_REQ_MAY_SLEEP;
if (keylen > bs) {
int err;
err =
crypto_shash_digest(shash, key, keylen, ipad);
if (err)
return err;
keylen = ds;
} else
memcpy(ipad, key, keylen);
memset(ipad + keylen, 0, bs - keylen);
memcpy(opad, ipad, bs);
for (i = 0; i < bs; i++) {
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
rc = crypto_shash_init(shash) ? :
crypto_shash_update(shash, ipad, bs) ? :
crypto_shash_export(shash, ipad) ? :
crypto_shash_init(shash) ? :
crypto_shash_update(shash, opad, bs) ? :
crypto_shash_export(shash, opad);
if (rc == 0)
mv_hash_init_ivs(ctx, ipad, opad);
return rc;
}
}
static int mv_cra_hash_init(struct crypto_tfm *tfm, const char *base_hash_name,
enum hash_op op, int count_add)
{
const char *fallback_driver_name = crypto_tfm_alg_name(tfm);
struct mv_tfm_hash_ctx *ctx = crypto_tfm_ctx(tfm);
struct crypto_shash *fallback_tfm = NULL;
struct crypto_shash *base_hash = NULL;
int err = -ENOMEM;
ctx->op = op;
ctx->count_add = count_add;
/* Allocate a fallback and abort if it failed. */
fallback_tfm = crypto_alloc_shash(fallback_driver_name, 0,
CRYPTO_ALG_NEED_FALLBACK);
if (IS_ERR(fallback_tfm)) {
printk(KERN_WARNING MV_CESA
"Fallback driver '%s' could not be loaded!\n",
fallback_driver_name);
err = PTR_ERR(fallback_tfm);
goto out;
}
ctx->fallback = fallback_tfm;
if (base_hash_name) {
/* Allocate a hash to compute the ipad/opad of hmac. */
base_hash = crypto_alloc_shash(base_hash_name, 0,
CRYPTO_ALG_NEED_FALLBACK);
if (IS_ERR(base_hash)) {
printk(KERN_WARNING MV_CESA
"Base driver '%s' could not be loaded!\n",
base_hash_name);
err = PTR_ERR(base_hash);
goto err_bad_base;
}
}
ctx->base_hash = base_hash;
crypto_ahash_set_reqsize(__crypto_ahash_cast(tfm),
sizeof(struct mv_req_hash_ctx) +
crypto_shash_descsize(ctx->fallback));
return 0;
err_bad_base:
crypto_free_shash(fallback_tfm);
out:
return err;
}
static void mv_cra_hash_exit(struct crypto_tfm *tfm)
{
struct mv_tfm_hash_ctx *ctx = crypto_tfm_ctx(tfm);
crypto_free_shash(ctx->fallback);
if (ctx->base_hash)
crypto_free_shash(ctx->base_hash);
}
static int mv_cra_hash_sha1_init(struct crypto_tfm *tfm)
{
return mv_cra_hash_init(tfm, NULL, COP_SHA1, 0);
}
static int mv_cra_hash_hmac_sha1_init(struct crypto_tfm *tfm)
{
return mv_cra_hash_init(tfm, "sha1", COP_HMAC_SHA1, SHA1_BLOCK_SIZE);
}
static irqreturn_t crypto_int(int irq, void *priv)
{
u32 val;
val = readl(cpg->reg + SEC_ACCEL_INT_STATUS);
if (!(val & SEC_INT_ACCEL0_DONE))
return IRQ_NONE;
if (!del_timer(&cpg->completion_timer)) {
printk(KERN_WARNING MV_CESA
"got an interrupt but no pending timer?\n");
}
val &= ~SEC_INT_ACCEL0_DONE;
writel(val, cpg->reg + FPGA_INT_STATUS);
writel(val, cpg->reg + SEC_ACCEL_INT_STATUS);
BUG_ON(cpg->eng_st != ENGINE_BUSY);
cpg->eng_st = ENGINE_W_DEQUEUE;
wake_up_process(cpg->queue_th);
return IRQ_HANDLED;
}
static struct crypto_alg mv_aes_alg_ecb = {
.cra_name = "ecb(aes)",
.cra_driver_name = "mv-ecb-aes",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_ASYNC,
.cra_blocksize = 16,
.cra_ctxsize = sizeof(struct mv_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = mv_cra_init,
.cra_u = {
.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.setkey = mv_setkey_aes,
.encrypt = mv_enc_aes_ecb,
.decrypt = mv_dec_aes_ecb,
},
},
};
static struct crypto_alg mv_aes_alg_cbc = {
.cra_name = "cbc(aes)",
.cra_driver_name = "mv-cbc-aes",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_ASYNC,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct mv_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = mv_cra_init,
.cra_u = {
.ablkcipher = {
.ivsize = AES_BLOCK_SIZE,
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.setkey = mv_setkey_aes,
.encrypt = mv_enc_aes_cbc,
.decrypt = mv_dec_aes_cbc,
},
},
};
static struct ahash_alg mv_sha1_alg = {
.init = mv_hash_init,
.update = mv_hash_update,
.final = mv_hash_final,
.finup = mv_hash_finup,
.digest = mv_hash_digest,
.halg = {
.digestsize = SHA1_DIGEST_SIZE,
.base = {
.cra_name = "sha1",
.cra_driver_name = "mv-sha1",
.cra_priority = 300,
.cra_flags =
CRYPTO_ALG_ASYNC | CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA1_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct mv_tfm_hash_ctx),
.cra_init = mv_cra_hash_sha1_init,
.cra_exit = mv_cra_hash_exit,
.cra_module = THIS_MODULE,
}
}
};
static struct ahash_alg mv_hmac_sha1_alg = {
.init = mv_hash_init,
.update = mv_hash_update,
.final = mv_hash_final,
.finup = mv_hash_finup,
.digest = mv_hash_digest,
.setkey = mv_hash_setkey,
.halg = {
.digestsize = SHA1_DIGEST_SIZE,
.base = {
.cra_name = "hmac(sha1)",
.cra_driver_name = "mv-hmac-sha1",
.cra_priority = 300,
.cra_flags =
CRYPTO_ALG_ASYNC | CRYPTO_ALG_KERN_DRIVER_ONLY |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA1_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct mv_tfm_hash_ctx),
.cra_init = mv_cra_hash_hmac_sha1_init,
.cra_exit = mv_cra_hash_exit,
.cra_module = THIS_MODULE,
}
}
};
static int mv_cesa_get_sram(struct platform_device *pdev,
struct crypto_priv *cp)
{
struct resource *res;
u32 sram_size = MV_CESA_DEFAULT_SRAM_SIZE;
of_property_read_u32(pdev->dev.of_node, "marvell,crypto-sram-size",
&sram_size);
cp->sram_size = sram_size;
cp->sram_pool = of_gen_pool_get(pdev->dev.of_node,
"marvell,crypto-srams", 0);
if (cp->sram_pool) {
cp->sram = gen_pool_dma_alloc(cp->sram_pool, sram_size,
&cp->sram_dma);
if (cp->sram)
return 0;
return -ENOMEM;
}
res = platform_get_resource_byname(pdev, IORESOURCE_MEM,
"sram");
if (!res || resource_size(res) < cp->sram_size)
return -EINVAL;
cp->sram = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(cp->sram))
return PTR_ERR(cp->sram);
return 0;
}
static int mv_probe(struct platform_device *pdev)
{
struct crypto_priv *cp;
struct resource *res;
int irq;
int ret;
if (cpg) {
printk(KERN_ERR MV_CESA "Second crypto dev?\n");
return -EEXIST;
}
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "regs");
if (!res)
return -ENXIO;
cp = kzalloc(sizeof(*cp), GFP_KERNEL);
if (!cp)
return -ENOMEM;
spin_lock_init(&cp->lock);
crypto_init_queue(&cp->queue, 50);
cp->reg = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(cp->reg)) {
ret = PTR_ERR(cp->reg);
goto err;
}
ret = mv_cesa_get_sram(pdev, cp);
if (ret)
goto err;
cp->max_req_size = cp->sram_size - SRAM_CFG_SPACE;
if (pdev->dev.of_node)
irq = irq_of_parse_and_map(pdev->dev.of_node, 0);
else
irq = platform_get_irq(pdev, 0);
if (irq < 0 || irq == NO_IRQ) {
ret = irq;
goto err;
}
cp->irq = irq;
platform_set_drvdata(pdev, cp);
cpg = cp;
cp->queue_th = kthread_run(queue_manag, cp, "mv_crypto");
if (IS_ERR(cp->queue_th)) {
ret = PTR_ERR(cp->queue_th);
goto err;
}
ret = request_irq(irq, crypto_int, 0, dev_name(&pdev->dev),
cp);
if (ret)
goto err_thread;
/* Not all platforms can gate the clock, so it is not
an error if the clock does not exists. */
cp->clk = clk_get(&pdev->dev, NULL);
if (!IS_ERR(cp->clk))
clk_prepare_enable(cp->clk);
writel(0, cpg->reg + SEC_ACCEL_INT_STATUS);
writel(SEC_INT_ACCEL0_DONE, cpg->reg + SEC_ACCEL_INT_MASK);
writel(SEC_CFG_STOP_DIG_ERR, cpg->reg + SEC_ACCEL_CFG);
writel(SRAM_CONFIG, cpg->reg + SEC_ACCEL_DESC_P0);
ret = crypto_register_alg(&mv_aes_alg_ecb);
if (ret) {
printk(KERN_WARNING MV_CESA
"Could not register aes-ecb driver\n");
goto err_irq;
}
ret = crypto_register_alg(&mv_aes_alg_cbc);
if (ret) {
printk(KERN_WARNING MV_CESA
"Could not register aes-cbc driver\n");
goto err_unreg_ecb;
}
ret = crypto_register_ahash(&mv_sha1_alg);
if (ret == 0)
cpg->has_sha1 = 1;
else
printk(KERN_WARNING MV_CESA "Could not register sha1 driver\n");
ret = crypto_register_ahash(&mv_hmac_sha1_alg);
if (ret == 0) {
cpg->has_hmac_sha1 = 1;
} else {
printk(KERN_WARNING MV_CESA
"Could not register hmac-sha1 driver\n");
}
return 0;
err_unreg_ecb:
crypto_unregister_alg(&mv_aes_alg_ecb);
err_irq:
free_irq(irq, cp);
if (!IS_ERR(cp->clk)) {
clk_disable_unprepare(cp->clk);
clk_put(cp->clk);
}
err_thread:
kthread_stop(cp->queue_th);
err:
kfree(cp);
cpg = NULL;
return ret;
}
static int mv_remove(struct platform_device *pdev)
{
struct crypto_priv *cp = platform_get_drvdata(pdev);
crypto_unregister_alg(&mv_aes_alg_ecb);
crypto_unregister_alg(&mv_aes_alg_cbc);
if (cp->has_sha1)
crypto_unregister_ahash(&mv_sha1_alg);
if (cp->has_hmac_sha1)
crypto_unregister_ahash(&mv_hmac_sha1_alg);
kthread_stop(cp->queue_th);
free_irq(cp->irq, cp);
memset(cp->sram, 0, cp->sram_size);
if (!IS_ERR(cp->clk)) {
clk_disable_unprepare(cp->clk);
clk_put(cp->clk);
}
kfree(cp);
cpg = NULL;
return 0;
}
static const struct of_device_id mv_cesa_of_match_table[] = {
{ .compatible = "marvell,orion-crypto", },
{ .compatible = "marvell,kirkwood-crypto", },
{ .compatible = "marvell,dove-crypto", },
{}
};
MODULE_DEVICE_TABLE(of, mv_cesa_of_match_table);
static struct platform_driver marvell_crypto = {
.probe = mv_probe,
.remove = mv_remove,
.driver = {
.name = "mv_crypto",
.of_match_table = mv_cesa_of_match_table,
},
};
MODULE_ALIAS("platform:mv_crypto");
module_platform_driver(marvell_crypto);
MODULE_AUTHOR("Sebastian Andrzej Siewior <sebastian@breakpoint.cc>");
MODULE_DESCRIPTION("Support for Marvell's cryptographic engine");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Sricharanti/sricharan | fs/afs/file.c | 712 | 8872 | /* AFS filesystem file handling
*
* Copyright (C) 2002, 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/writeback.h>
#include <linux/gfp.h>
#include "internal.h"
static int afs_readpage(struct file *file, struct page *page);
static void afs_invalidatepage(struct page *page, unsigned int offset,
unsigned int length);
static int afs_releasepage(struct page *page, gfp_t gfp_flags);
static int afs_launder_page(struct page *page);
static int afs_readpages(struct file *filp, struct address_space *mapping,
struct list_head *pages, unsigned nr_pages);
const struct file_operations afs_file_operations = {
.open = afs_open,
.release = afs_release,
.llseek = generic_file_llseek,
.read = do_sync_read,
.write = do_sync_write,
.aio_read = generic_file_aio_read,
.aio_write = afs_file_write,
.mmap = generic_file_readonly_mmap,
.splice_read = generic_file_splice_read,
.fsync = afs_fsync,
.lock = afs_lock,
.flock = afs_flock,
};
const struct inode_operations afs_file_inode_operations = {
.getattr = afs_getattr,
.setattr = afs_setattr,
.permission = afs_permission,
};
const struct address_space_operations afs_fs_aops = {
.readpage = afs_readpage,
.readpages = afs_readpages,
.set_page_dirty = afs_set_page_dirty,
.launder_page = afs_launder_page,
.releasepage = afs_releasepage,
.invalidatepage = afs_invalidatepage,
.write_begin = afs_write_begin,
.write_end = afs_write_end,
.writepage = afs_writepage,
.writepages = afs_writepages,
};
/*
* open an AFS file or directory and attach a key to it
*/
int afs_open(struct inode *inode, struct file *file)
{
struct afs_vnode *vnode = AFS_FS_I(inode);
struct key *key;
int ret;
_enter("{%x:%u},", vnode->fid.vid, vnode->fid.vnode);
key = afs_request_key(vnode->volume->cell);
if (IS_ERR(key)) {
_leave(" = %ld [key]", PTR_ERR(key));
return PTR_ERR(key);
}
ret = afs_validate(vnode, key);
if (ret < 0) {
_leave(" = %d [val]", ret);
return ret;
}
file->private_data = key;
_leave(" = 0");
return 0;
}
/*
* release an AFS file or directory and discard its key
*/
int afs_release(struct inode *inode, struct file *file)
{
struct afs_vnode *vnode = AFS_FS_I(inode);
_enter("{%x:%u},", vnode->fid.vid, vnode->fid.vnode);
key_put(file->private_data);
_leave(" = 0");
return 0;
}
#ifdef CONFIG_AFS_FSCACHE
/*
* deal with notification that a page was read from the cache
*/
static void afs_file_readpage_read_complete(struct page *page,
void *data,
int error)
{
_enter("%p,%p,%d", page, data, error);
/* if the read completes with an error, we just unlock the page and let
* the VM reissue the readpage */
if (!error)
SetPageUptodate(page);
unlock_page(page);
}
#endif
/*
* read page from file, directory or symlink, given a key to use
*/
int afs_page_filler(void *data, struct page *page)
{
struct inode *inode = page->mapping->host;
struct afs_vnode *vnode = AFS_FS_I(inode);
struct key *key = data;
size_t len;
off_t offset;
int ret;
_enter("{%x},{%lu},{%lu}", key_serial(key), inode->i_ino, page->index);
BUG_ON(!PageLocked(page));
ret = -ESTALE;
if (test_bit(AFS_VNODE_DELETED, &vnode->flags))
goto error;
/* is it cached? */
#ifdef CONFIG_AFS_FSCACHE
ret = fscache_read_or_alloc_page(vnode->cache,
page,
afs_file_readpage_read_complete,
NULL,
GFP_KERNEL);
#else
ret = -ENOBUFS;
#endif
switch (ret) {
/* read BIO submitted (page in cache) */
case 0:
break;
/* page not yet cached */
case -ENODATA:
_debug("cache said ENODATA");
goto go_on;
/* page will not be cached */
case -ENOBUFS:
_debug("cache said ENOBUFS");
default:
go_on:
offset = page->index << PAGE_CACHE_SHIFT;
len = min_t(size_t, i_size_read(inode) - offset, PAGE_SIZE);
/* read the contents of the file from the server into the
* page */
ret = afs_vnode_fetch_data(vnode, key, offset, len, page);
if (ret < 0) {
if (ret == -ENOENT) {
_debug("got NOENT from server"
" - marking file deleted and stale");
set_bit(AFS_VNODE_DELETED, &vnode->flags);
ret = -ESTALE;
}
#ifdef CONFIG_AFS_FSCACHE
fscache_uncache_page(vnode->cache, page);
#endif
BUG_ON(PageFsCache(page));
goto error;
}
SetPageUptodate(page);
/* send the page to the cache */
#ifdef CONFIG_AFS_FSCACHE
if (PageFsCache(page) &&
fscache_write_page(vnode->cache, page, GFP_KERNEL) != 0) {
fscache_uncache_page(vnode->cache, page);
BUG_ON(PageFsCache(page));
}
#endif
unlock_page(page);
}
_leave(" = 0");
return 0;
error:
SetPageError(page);
unlock_page(page);
_leave(" = %d", ret);
return ret;
}
/*
* read page from file, directory or symlink, given a file to nominate the key
* to be used
*/
static int afs_readpage(struct file *file, struct page *page)
{
struct key *key;
int ret;
if (file) {
key = file->private_data;
ASSERT(key != NULL);
ret = afs_page_filler(key, page);
} else {
struct inode *inode = page->mapping->host;
key = afs_request_key(AFS_FS_S(inode->i_sb)->volume->cell);
if (IS_ERR(key)) {
ret = PTR_ERR(key);
} else {
ret = afs_page_filler(key, page);
key_put(key);
}
}
return ret;
}
/*
* read a set of pages
*/
static int afs_readpages(struct file *file, struct address_space *mapping,
struct list_head *pages, unsigned nr_pages)
{
struct key *key = file->private_data;
struct afs_vnode *vnode;
int ret = 0;
_enter("{%d},{%lu},,%d",
key_serial(key), mapping->host->i_ino, nr_pages);
ASSERT(key != NULL);
vnode = AFS_FS_I(mapping->host);
if (test_bit(AFS_VNODE_DELETED, &vnode->flags)) {
_leave(" = -ESTALE");
return -ESTALE;
}
/* attempt to read as many of the pages as possible */
#ifdef CONFIG_AFS_FSCACHE
ret = fscache_read_or_alloc_pages(vnode->cache,
mapping,
pages,
&nr_pages,
afs_file_readpage_read_complete,
NULL,
mapping_gfp_mask(mapping));
#else
ret = -ENOBUFS;
#endif
switch (ret) {
/* all pages are being read from the cache */
case 0:
BUG_ON(!list_empty(pages));
BUG_ON(nr_pages != 0);
_leave(" = 0 [reading all]");
return 0;
/* there were pages that couldn't be read from the cache */
case -ENODATA:
case -ENOBUFS:
break;
/* other error */
default:
_leave(" = %d", ret);
return ret;
}
/* load the missing pages from the network */
ret = read_cache_pages(mapping, pages, afs_page_filler, key);
_leave(" = %d [netting]", ret);
return ret;
}
/*
* write back a dirty page
*/
static int afs_launder_page(struct page *page)
{
_enter("{%lu}", page->index);
return 0;
}
/*
* invalidate part or all of a page
* - release a page and clean up its private data if offset is 0 (indicating
* the entire page)
*/
static void afs_invalidatepage(struct page *page, unsigned int offset,
unsigned int length)
{
struct afs_writeback *wb = (struct afs_writeback *) page_private(page);
_enter("{%lu},%u,%u", page->index, offset, length);
BUG_ON(!PageLocked(page));
/* we clean up only if the entire page is being invalidated */
if (offset == 0 && length == PAGE_CACHE_SIZE) {
#ifdef CONFIG_AFS_FSCACHE
if (PageFsCache(page)) {
struct afs_vnode *vnode = AFS_FS_I(page->mapping->host);
fscache_wait_on_page_write(vnode->cache, page);
fscache_uncache_page(vnode->cache, page);
}
#endif
if (PagePrivate(page)) {
if (wb && !PageWriteback(page)) {
set_page_private(page, 0);
afs_put_writeback(wb);
}
if (!page_private(page))
ClearPagePrivate(page);
}
}
_leave("");
}
/*
* release a page and clean up its private state if it's not busy
* - return true if the page can now be released, false if not
*/
static int afs_releasepage(struct page *page, gfp_t gfp_flags)
{
struct afs_writeback *wb = (struct afs_writeback *) page_private(page);
struct afs_vnode *vnode = AFS_FS_I(page->mapping->host);
_enter("{{%x:%u}[%lu],%lx},%x",
vnode->fid.vid, vnode->fid.vnode, page->index, page->flags,
gfp_flags);
/* deny if page is being written to the cache and the caller hasn't
* elected to wait */
#ifdef CONFIG_AFS_FSCACHE
if (!fscache_maybe_release_page(vnode->cache, page, gfp_flags)) {
_leave(" = F [cache busy]");
return 0;
}
#endif
if (PagePrivate(page)) {
if (wb) {
set_page_private(page, 0);
afs_put_writeback(wb);
}
ClearPagePrivate(page);
}
/* indicate that the page can be released */
_leave(" = T");
return 1;
}
| gpl-2.0 |
VincenzoDo/my-kernel | fs/nfs/filelayout/filelayoutdev.c | 968 | 8497 | /*
* Device operations for the pnfs nfs4 file layout driver.
*
* Copyright (c) 2002
* The Regents of the University of Michigan
* All Rights Reserved
*
* Dean Hildebrand <dhildebz@umich.edu>
* Garth Goodson <Garth.Goodson@netapp.com>
*
* Permission is granted to use, copy, create derivative works, and
* redistribute this software and such derivative works for any purpose,
* so long as the name of the University of Michigan is not used in
* any advertising or publicity pertaining to the use or distribution
* of this software without specific, written prior authorization. If
* the above copyright notice or any other identification of the
* University of Michigan is included in any copy of any portion of
* this software, then the disclaimer below must also be included.
*
* This software is provided as is, without representation or warranty
* of any kind either express or implied, including without limitation
* the implied warranties of merchantability, fitness for a particular
* purpose, or noninfringement. The Regents of the University of
* Michigan shall not be liable for any damages, including special,
* indirect, incidental, or consequential damages, with respect to any
* claim arising out of or in connection with the use of the software,
* even if it has been or is hereafter advised of the possibility of
* such damages.
*/
#include <linux/nfs_fs.h>
#include <linux/vmalloc.h>
#include <linux/module.h>
#include "../internal.h"
#include "../nfs4session.h"
#include "filelayout.h"
#define NFSDBG_FACILITY NFSDBG_PNFS_LD
static unsigned int dataserver_timeo = NFS4_DEF_DS_TIMEO;
static unsigned int dataserver_retrans = NFS4_DEF_DS_RETRANS;
void
nfs4_fl_free_deviceid(struct nfs4_file_layout_dsaddr *dsaddr)
{
struct nfs4_pnfs_ds *ds;
int i;
nfs4_print_deviceid(&dsaddr->id_node.deviceid);
for (i = 0; i < dsaddr->ds_num; i++) {
ds = dsaddr->ds_list[i];
if (ds != NULL)
nfs4_pnfs_ds_put(ds);
}
kfree(dsaddr->stripe_indices);
kfree_rcu(dsaddr, id_node.rcu);
}
/* Decode opaque device data and return the result */
struct nfs4_file_layout_dsaddr *
nfs4_fl_alloc_deviceid_node(struct nfs_server *server, struct pnfs_device *pdev,
gfp_t gfp_flags)
{
int i;
u32 cnt, num;
u8 *indexp;
__be32 *p;
u8 *stripe_indices;
u8 max_stripe_index;
struct nfs4_file_layout_dsaddr *dsaddr = NULL;
struct xdr_stream stream;
struct xdr_buf buf;
struct page *scratch;
struct list_head dsaddrs;
struct nfs4_pnfs_ds_addr *da;
/* set up xdr stream */
scratch = alloc_page(gfp_flags);
if (!scratch)
goto out_err;
xdr_init_decode_pages(&stream, &buf, pdev->pages, pdev->pglen);
xdr_set_scratch_buffer(&stream, page_address(scratch), PAGE_SIZE);
/* Get the stripe count (number of stripe index) */
p = xdr_inline_decode(&stream, 4);
if (unlikely(!p))
goto out_err_free_scratch;
cnt = be32_to_cpup(p);
dprintk("%s stripe count %d\n", __func__, cnt);
if (cnt > NFS4_PNFS_MAX_STRIPE_CNT) {
printk(KERN_WARNING "NFS: %s: stripe count %d greater than "
"supported maximum %d\n", __func__,
cnt, NFS4_PNFS_MAX_STRIPE_CNT);
goto out_err_free_scratch;
}
/* read stripe indices */
stripe_indices = kcalloc(cnt, sizeof(u8), gfp_flags);
if (!stripe_indices)
goto out_err_free_scratch;
p = xdr_inline_decode(&stream, cnt << 2);
if (unlikely(!p))
goto out_err_free_stripe_indices;
indexp = &stripe_indices[0];
max_stripe_index = 0;
for (i = 0; i < cnt; i++) {
*indexp = be32_to_cpup(p++);
max_stripe_index = max(max_stripe_index, *indexp);
indexp++;
}
/* Check the multipath list count */
p = xdr_inline_decode(&stream, 4);
if (unlikely(!p))
goto out_err_free_stripe_indices;
num = be32_to_cpup(p);
dprintk("%s ds_num %u\n", __func__, num);
if (num > NFS4_PNFS_MAX_MULTI_CNT) {
printk(KERN_WARNING "NFS: %s: multipath count %d greater than "
"supported maximum %d\n", __func__,
num, NFS4_PNFS_MAX_MULTI_CNT);
goto out_err_free_stripe_indices;
}
/* validate stripe indices are all < num */
if (max_stripe_index >= num) {
printk(KERN_WARNING "NFS: %s: stripe index %u >= num ds %u\n",
__func__, max_stripe_index, num);
goto out_err_free_stripe_indices;
}
dsaddr = kzalloc(sizeof(*dsaddr) +
(sizeof(struct nfs4_pnfs_ds *) * (num - 1)),
gfp_flags);
if (!dsaddr)
goto out_err_free_stripe_indices;
dsaddr->stripe_count = cnt;
dsaddr->stripe_indices = stripe_indices;
stripe_indices = NULL;
dsaddr->ds_num = num;
nfs4_init_deviceid_node(&dsaddr->id_node, server, &pdev->dev_id);
INIT_LIST_HEAD(&dsaddrs);
for (i = 0; i < dsaddr->ds_num; i++) {
int j;
u32 mp_count;
p = xdr_inline_decode(&stream, 4);
if (unlikely(!p))
goto out_err_free_deviceid;
mp_count = be32_to_cpup(p); /* multipath count */
for (j = 0; j < mp_count; j++) {
da = nfs4_decode_mp_ds_addr(server->nfs_client->cl_net,
&stream, gfp_flags);
if (da)
list_add_tail(&da->da_node, &dsaddrs);
}
if (list_empty(&dsaddrs)) {
dprintk("%s: no suitable DS addresses found\n",
__func__);
goto out_err_free_deviceid;
}
dsaddr->ds_list[i] = nfs4_pnfs_ds_add(&dsaddrs, gfp_flags);
if (!dsaddr->ds_list[i])
goto out_err_drain_dsaddrs;
/* If DS was already in cache, free ds addrs */
while (!list_empty(&dsaddrs)) {
da = list_first_entry(&dsaddrs,
struct nfs4_pnfs_ds_addr,
da_node);
list_del_init(&da->da_node);
kfree(da->da_remotestr);
kfree(da);
}
}
__free_page(scratch);
return dsaddr;
out_err_drain_dsaddrs:
while (!list_empty(&dsaddrs)) {
da = list_first_entry(&dsaddrs, struct nfs4_pnfs_ds_addr,
da_node);
list_del_init(&da->da_node);
kfree(da->da_remotestr);
kfree(da);
}
out_err_free_deviceid:
nfs4_fl_free_deviceid(dsaddr);
/* stripe_indicies was part of dsaddr */
goto out_err_free_scratch;
out_err_free_stripe_indices:
kfree(stripe_indices);
out_err_free_scratch:
__free_page(scratch);
out_err:
dprintk("%s ERROR: returning NULL\n", __func__);
return NULL;
}
void
nfs4_fl_put_deviceid(struct nfs4_file_layout_dsaddr *dsaddr)
{
nfs4_put_deviceid_node(&dsaddr->id_node);
}
/*
* Want res = (offset - layout->pattern_offset)/ layout->stripe_unit
* Then: ((res + fsi) % dsaddr->stripe_count)
*/
u32
nfs4_fl_calc_j_index(struct pnfs_layout_segment *lseg, loff_t offset)
{
struct nfs4_filelayout_segment *flseg = FILELAYOUT_LSEG(lseg);
u64 tmp;
tmp = offset - flseg->pattern_offset;
do_div(tmp, flseg->stripe_unit);
tmp += flseg->first_stripe_index;
return do_div(tmp, flseg->dsaddr->stripe_count);
}
u32
nfs4_fl_calc_ds_index(struct pnfs_layout_segment *lseg, u32 j)
{
return FILELAYOUT_LSEG(lseg)->dsaddr->stripe_indices[j];
}
struct nfs_fh *
nfs4_fl_select_ds_fh(struct pnfs_layout_segment *lseg, u32 j)
{
struct nfs4_filelayout_segment *flseg = FILELAYOUT_LSEG(lseg);
u32 i;
if (flseg->stripe_type == STRIPE_SPARSE) {
if (flseg->num_fh == 1)
i = 0;
else if (flseg->num_fh == 0)
/* Use the MDS OPEN fh set in nfs_read_rpcsetup */
return NULL;
else
i = nfs4_fl_calc_ds_index(lseg, j);
} else
i = j;
return flseg->fh_array[i];
}
/* Upon return, either ds is connected, or ds is NULL */
struct nfs4_pnfs_ds *
nfs4_fl_prepare_ds(struct pnfs_layout_segment *lseg, u32 ds_idx)
{
struct nfs4_file_layout_dsaddr *dsaddr = FILELAYOUT_LSEG(lseg)->dsaddr;
struct nfs4_pnfs_ds *ds = dsaddr->ds_list[ds_idx];
struct nfs4_deviceid_node *devid = FILELAYOUT_DEVID_NODE(lseg);
struct nfs4_pnfs_ds *ret = ds;
struct nfs_server *s = NFS_SERVER(lseg->pls_layout->plh_inode);
if (ds == NULL) {
printk(KERN_ERR "NFS: %s: No data server for offset index %d\n",
__func__, ds_idx);
pnfs_generic_mark_devid_invalid(devid);
goto out;
}
smp_rmb();
if (ds->ds_clp)
goto out_test_devid;
nfs4_pnfs_ds_connect(s, ds, devid, dataserver_timeo,
dataserver_retrans, 4,
s->nfs_client->cl_minorversion,
s->nfs_client->cl_rpcclient->cl_auth->au_flavor);
out_test_devid:
if (filelayout_test_devid_unavailable(devid))
ret = NULL;
out:
return ret;
}
module_param(dataserver_retrans, uint, 0644);
MODULE_PARM_DESC(dataserver_retrans, "The number of times the NFSv4.1 client "
"retries a request before it attempts further "
" recovery action.");
module_param(dataserver_timeo, uint, 0644);
MODULE_PARM_DESC(dataserver_timeo, "The time (in tenths of a second) the "
"NFSv4.1 client waits for a response from a "
" data server before it retries an NFS request.");
| gpl-2.0 |
srfarias/srfarias_kernel_msm8916 | drivers/power/avs/smartreflex.c | 2248 | 30013 | /*
* OMAP SmartReflex Voltage Control
*
* Author: Thara Gopinath <thara@ti.com>
*
* Copyright (C) 2012 Texas Instruments, Inc.
* Thara Gopinath <thara@ti.com>
*
* Copyright (C) 2008 Nokia Corporation
* Kalle Jokiniemi
*
* Copyright (C) 2007 Texas Instruments, Inc.
* Lesly A M <x0080970@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/debugfs.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/pm_runtime.h>
#include <linux/power/smartreflex.h>
#define SMARTREFLEX_NAME_LEN 16
#define NVALUE_NAME_LEN 40
#define SR_DISABLE_TIMEOUT 200
/* sr_list contains all the instances of smartreflex module */
static LIST_HEAD(sr_list);
static struct omap_sr_class_data *sr_class;
static struct omap_sr_pmic_data *sr_pmic_data;
static struct dentry *sr_dbg_dir;
static inline void sr_write_reg(struct omap_sr *sr, unsigned offset, u32 value)
{
__raw_writel(value, (sr->base + offset));
}
static inline void sr_modify_reg(struct omap_sr *sr, unsigned offset, u32 mask,
u32 value)
{
u32 reg_val;
/*
* Smartreflex error config register is special as it contains
* certain status bits which if written a 1 into means a clear
* of those bits. So in order to make sure no accidental write of
* 1 happens to those status bits, do a clear of them in the read
* value. This mean this API doesn't rewrite values in these bits
* if they are currently set, but does allow the caller to write
* those bits.
*/
if (sr->ip_type == SR_TYPE_V1 && offset == ERRCONFIG_V1)
mask |= ERRCONFIG_STATUS_V1_MASK;
else if (sr->ip_type == SR_TYPE_V2 && offset == ERRCONFIG_V2)
mask |= ERRCONFIG_VPBOUNDINTST_V2;
reg_val = __raw_readl(sr->base + offset);
reg_val &= ~mask;
value &= mask;
reg_val |= value;
__raw_writel(reg_val, (sr->base + offset));
}
static inline u32 sr_read_reg(struct omap_sr *sr, unsigned offset)
{
return __raw_readl(sr->base + offset);
}
static struct omap_sr *_sr_lookup(struct voltagedomain *voltdm)
{
struct omap_sr *sr_info;
if (!voltdm) {
pr_err("%s: Null voltage domain passed!\n", __func__);
return ERR_PTR(-EINVAL);
}
list_for_each_entry(sr_info, &sr_list, node) {
if (voltdm == sr_info->voltdm)
return sr_info;
}
return ERR_PTR(-ENODATA);
}
static irqreturn_t sr_interrupt(int irq, void *data)
{
struct omap_sr *sr_info = data;
u32 status = 0;
switch (sr_info->ip_type) {
case SR_TYPE_V1:
/* Read the status bits */
status = sr_read_reg(sr_info, ERRCONFIG_V1);
/* Clear them by writing back */
sr_write_reg(sr_info, ERRCONFIG_V1, status);
break;
case SR_TYPE_V2:
/* Read the status bits */
status = sr_read_reg(sr_info, IRQSTATUS);
/* Clear them by writing back */
sr_write_reg(sr_info, IRQSTATUS, status);
break;
default:
dev_err(&sr_info->pdev->dev, "UNKNOWN IP type %d\n",
sr_info->ip_type);
return IRQ_NONE;
}
if (sr_class->notify)
sr_class->notify(sr_info, status);
return IRQ_HANDLED;
}
static void sr_set_clk_length(struct omap_sr *sr)
{
struct clk *fck;
u32 fclk_speed;
fck = clk_get(&sr->pdev->dev, "fck");
if (IS_ERR(fck)) {
dev_err(&sr->pdev->dev, "%s: unable to get fck for device %s\n",
__func__, dev_name(&sr->pdev->dev));
return;
}
fclk_speed = clk_get_rate(fck);
clk_put(fck);
switch (fclk_speed) {
case 12000000:
sr->clk_length = SRCLKLENGTH_12MHZ_SYSCLK;
break;
case 13000000:
sr->clk_length = SRCLKLENGTH_13MHZ_SYSCLK;
break;
case 19200000:
sr->clk_length = SRCLKLENGTH_19MHZ_SYSCLK;
break;
case 26000000:
sr->clk_length = SRCLKLENGTH_26MHZ_SYSCLK;
break;
case 38400000:
sr->clk_length = SRCLKLENGTH_38MHZ_SYSCLK;
break;
default:
dev_err(&sr->pdev->dev, "%s: Invalid fclk rate: %d\n",
__func__, fclk_speed);
break;
}
}
static void sr_start_vddautocomp(struct omap_sr *sr)
{
if (!sr_class || !(sr_class->enable) || !(sr_class->configure)) {
dev_warn(&sr->pdev->dev,
"%s: smartreflex class driver not registered\n",
__func__);
return;
}
if (!sr_class->enable(sr))
sr->autocomp_active = true;
}
static void sr_stop_vddautocomp(struct omap_sr *sr)
{
if (!sr_class || !(sr_class->disable)) {
dev_warn(&sr->pdev->dev,
"%s: smartreflex class driver not registered\n",
__func__);
return;
}
if (sr->autocomp_active) {
sr_class->disable(sr, 1);
sr->autocomp_active = false;
}
}
/*
* This function handles the intializations which have to be done
* only when both sr device and class driver regiter has
* completed. This will be attempted to be called from both sr class
* driver register and sr device intializtion API's. Only one call
* will ultimately succeed.
*
* Currently this function registers interrupt handler for a particular SR
* if smartreflex class driver is already registered and has
* requested for interrupts and the SR interrupt line in present.
*/
static int sr_late_init(struct omap_sr *sr_info)
{
struct omap_sr_data *pdata = sr_info->pdev->dev.platform_data;
struct resource *mem;
int ret = 0;
if (sr_class->notify && sr_class->notify_flags && sr_info->irq) {
ret = request_irq(sr_info->irq, sr_interrupt,
0, sr_info->name, sr_info);
if (ret)
goto error;
disable_irq(sr_info->irq);
}
if (pdata && pdata->enable_on_init)
sr_start_vddautocomp(sr_info);
return ret;
error:
iounmap(sr_info->base);
mem = platform_get_resource(sr_info->pdev, IORESOURCE_MEM, 0);
release_mem_region(mem->start, resource_size(mem));
list_del(&sr_info->node);
dev_err(&sr_info->pdev->dev, "%s: ERROR in registering"
"interrupt handler. Smartreflex will"
"not function as desired\n", __func__);
kfree(sr_info);
return ret;
}
static void sr_v1_disable(struct omap_sr *sr)
{
int timeout = 0;
int errconf_val = ERRCONFIG_MCUACCUMINTST | ERRCONFIG_MCUVALIDINTST |
ERRCONFIG_MCUBOUNDINTST;
/* Enable MCUDisableAcknowledge interrupt */
sr_modify_reg(sr, ERRCONFIG_V1,
ERRCONFIG_MCUDISACKINTEN, ERRCONFIG_MCUDISACKINTEN);
/* SRCONFIG - disable SR */
sr_modify_reg(sr, SRCONFIG, SRCONFIG_SRENABLE, 0x0);
/* Disable all other SR interrupts and clear the status as needed */
if (sr_read_reg(sr, ERRCONFIG_V1) & ERRCONFIG_VPBOUNDINTST_V1)
errconf_val |= ERRCONFIG_VPBOUNDINTST_V1;
sr_modify_reg(sr, ERRCONFIG_V1,
(ERRCONFIG_MCUACCUMINTEN | ERRCONFIG_MCUVALIDINTEN |
ERRCONFIG_MCUBOUNDINTEN | ERRCONFIG_VPBOUNDINTEN_V1),
errconf_val);
/*
* Wait for SR to be disabled.
* wait until ERRCONFIG.MCUDISACKINTST = 1. Typical latency is 1us.
*/
sr_test_cond_timeout((sr_read_reg(sr, ERRCONFIG_V1) &
ERRCONFIG_MCUDISACKINTST), SR_DISABLE_TIMEOUT,
timeout);
if (timeout >= SR_DISABLE_TIMEOUT)
dev_warn(&sr->pdev->dev, "%s: Smartreflex disable timedout\n",
__func__);
/* Disable MCUDisableAcknowledge interrupt & clear pending interrupt */
sr_modify_reg(sr, ERRCONFIG_V1, ERRCONFIG_MCUDISACKINTEN,
ERRCONFIG_MCUDISACKINTST);
}
static void sr_v2_disable(struct omap_sr *sr)
{
int timeout = 0;
/* Enable MCUDisableAcknowledge interrupt */
sr_write_reg(sr, IRQENABLE_SET, IRQENABLE_MCUDISABLEACKINT);
/* SRCONFIG - disable SR */
sr_modify_reg(sr, SRCONFIG, SRCONFIG_SRENABLE, 0x0);
/*
* Disable all other SR interrupts and clear the status
* write to status register ONLY on need basis - only if status
* is set.
*/
if (sr_read_reg(sr, ERRCONFIG_V2) & ERRCONFIG_VPBOUNDINTST_V2)
sr_modify_reg(sr, ERRCONFIG_V2, ERRCONFIG_VPBOUNDINTEN_V2,
ERRCONFIG_VPBOUNDINTST_V2);
else
sr_modify_reg(sr, ERRCONFIG_V2, ERRCONFIG_VPBOUNDINTEN_V2,
0x0);
sr_write_reg(sr, IRQENABLE_CLR, (IRQENABLE_MCUACCUMINT |
IRQENABLE_MCUVALIDINT |
IRQENABLE_MCUBOUNDSINT));
sr_write_reg(sr, IRQSTATUS, (IRQSTATUS_MCUACCUMINT |
IRQSTATUS_MCVALIDINT |
IRQSTATUS_MCBOUNDSINT));
/*
* Wait for SR to be disabled.
* wait until IRQSTATUS.MCUDISACKINTST = 1. Typical latency is 1us.
*/
sr_test_cond_timeout((sr_read_reg(sr, IRQSTATUS) &
IRQSTATUS_MCUDISABLEACKINT), SR_DISABLE_TIMEOUT,
timeout);
if (timeout >= SR_DISABLE_TIMEOUT)
dev_warn(&sr->pdev->dev, "%s: Smartreflex disable timedout\n",
__func__);
/* Disable MCUDisableAcknowledge interrupt & clear pending interrupt */
sr_write_reg(sr, IRQENABLE_CLR, IRQENABLE_MCUDISABLEACKINT);
sr_write_reg(sr, IRQSTATUS, IRQSTATUS_MCUDISABLEACKINT);
}
static struct omap_sr_nvalue_table *sr_retrieve_nvalue_row(
struct omap_sr *sr, u32 efuse_offs)
{
int i;
if (!sr->nvalue_table) {
dev_warn(&sr->pdev->dev, "%s: Missing ntarget value table\n",
__func__);
return NULL;
}
for (i = 0; i < sr->nvalue_count; i++) {
if (sr->nvalue_table[i].efuse_offs == efuse_offs)
return &sr->nvalue_table[i];
}
return NULL;
}
/* Public Functions */
/**
* sr_configure_errgen() - Configures the smrtreflex to perform AVS using the
* error generator module.
* @voltdm: VDD pointer to which the SR module to be configured belongs to.
*
* This API is to be called from the smartreflex class driver to
* configure the error generator module inside the smartreflex module.
* SR settings if using the ERROR module inside Smartreflex.
* SR CLASS 3 by default uses only the ERROR module where as
* SR CLASS 2 can choose between ERROR module and MINMAXAVG
* module. Returns 0 on success and error value in case of failure.
*/
int sr_configure_errgen(struct voltagedomain *voltdm)
{
u32 sr_config, sr_errconfig, errconfig_offs;
u32 vpboundint_en, vpboundint_st;
u32 senp_en = 0, senn_en = 0;
u8 senp_shift, senn_shift;
struct omap_sr *sr = _sr_lookup(voltdm);
if (IS_ERR(sr)) {
pr_warning("%s: omap_sr struct for voltdm not found\n", __func__);
return PTR_ERR(sr);
}
if (!sr->clk_length)
sr_set_clk_length(sr);
senp_en = sr->senp_mod;
senn_en = sr->senn_mod;
sr_config = (sr->clk_length << SRCONFIG_SRCLKLENGTH_SHIFT) |
SRCONFIG_SENENABLE | SRCONFIG_ERRGEN_EN;
switch (sr->ip_type) {
case SR_TYPE_V1:
sr_config |= SRCONFIG_DELAYCTRL;
senn_shift = SRCONFIG_SENNENABLE_V1_SHIFT;
senp_shift = SRCONFIG_SENPENABLE_V1_SHIFT;
errconfig_offs = ERRCONFIG_V1;
vpboundint_en = ERRCONFIG_VPBOUNDINTEN_V1;
vpboundint_st = ERRCONFIG_VPBOUNDINTST_V1;
break;
case SR_TYPE_V2:
senn_shift = SRCONFIG_SENNENABLE_V2_SHIFT;
senp_shift = SRCONFIG_SENPENABLE_V2_SHIFT;
errconfig_offs = ERRCONFIG_V2;
vpboundint_en = ERRCONFIG_VPBOUNDINTEN_V2;
vpboundint_st = ERRCONFIG_VPBOUNDINTST_V2;
break;
default:
dev_err(&sr->pdev->dev, "%s: Trying to Configure smartreflex"
"module without specifying the ip\n", __func__);
return -EINVAL;
}
sr_config |= ((senn_en << senn_shift) | (senp_en << senp_shift));
sr_write_reg(sr, SRCONFIG, sr_config);
sr_errconfig = (sr->err_weight << ERRCONFIG_ERRWEIGHT_SHIFT) |
(sr->err_maxlimit << ERRCONFIG_ERRMAXLIMIT_SHIFT) |
(sr->err_minlimit << ERRCONFIG_ERRMINLIMIT_SHIFT);
sr_modify_reg(sr, errconfig_offs, (SR_ERRWEIGHT_MASK |
SR_ERRMAXLIMIT_MASK | SR_ERRMINLIMIT_MASK),
sr_errconfig);
/* Enabling the interrupts if the ERROR module is used */
sr_modify_reg(sr, errconfig_offs, (vpboundint_en | vpboundint_st),
vpboundint_en);
return 0;
}
/**
* sr_disable_errgen() - Disables SmartReflex AVS module's errgen component
* @voltdm: VDD pointer to which the SR module to be configured belongs to.
*
* This API is to be called from the smartreflex class driver to
* disable the error generator module inside the smartreflex module.
*
* Returns 0 on success and error value in case of failure.
*/
int sr_disable_errgen(struct voltagedomain *voltdm)
{
u32 errconfig_offs;
u32 vpboundint_en, vpboundint_st;
struct omap_sr *sr = _sr_lookup(voltdm);
if (IS_ERR(sr)) {
pr_warning("%s: omap_sr struct for voltdm not found\n", __func__);
return PTR_ERR(sr);
}
switch (sr->ip_type) {
case SR_TYPE_V1:
errconfig_offs = ERRCONFIG_V1;
vpboundint_en = ERRCONFIG_VPBOUNDINTEN_V1;
vpboundint_st = ERRCONFIG_VPBOUNDINTST_V1;
break;
case SR_TYPE_V2:
errconfig_offs = ERRCONFIG_V2;
vpboundint_en = ERRCONFIG_VPBOUNDINTEN_V2;
vpboundint_st = ERRCONFIG_VPBOUNDINTST_V2;
break;
default:
dev_err(&sr->pdev->dev, "%s: Trying to Configure smartreflex"
"module without specifying the ip\n", __func__);
return -EINVAL;
}
/* Disable the interrupts of ERROR module */
sr_modify_reg(sr, errconfig_offs, vpboundint_en | vpboundint_st, 0);
/* Disable the Sensor and errorgen */
sr_modify_reg(sr, SRCONFIG, SRCONFIG_SENENABLE | SRCONFIG_ERRGEN_EN, 0);
return 0;
}
/**
* sr_configure_minmax() - Configures the smrtreflex to perform AVS using the
* minmaxavg module.
* @voltdm: VDD pointer to which the SR module to be configured belongs to.
*
* This API is to be called from the smartreflex class driver to
* configure the minmaxavg module inside the smartreflex module.
* SR settings if using the ERROR module inside Smartreflex.
* SR CLASS 3 by default uses only the ERROR module where as
* SR CLASS 2 can choose between ERROR module and MINMAXAVG
* module. Returns 0 on success and error value in case of failure.
*/
int sr_configure_minmax(struct voltagedomain *voltdm)
{
u32 sr_config, sr_avgwt;
u32 senp_en = 0, senn_en = 0;
u8 senp_shift, senn_shift;
struct omap_sr *sr = _sr_lookup(voltdm);
if (IS_ERR(sr)) {
pr_warning("%s: omap_sr struct for voltdm not found\n", __func__);
return PTR_ERR(sr);
}
if (!sr->clk_length)
sr_set_clk_length(sr);
senp_en = sr->senp_mod;
senn_en = sr->senn_mod;
sr_config = (sr->clk_length << SRCONFIG_SRCLKLENGTH_SHIFT) |
SRCONFIG_SENENABLE |
(sr->accum_data << SRCONFIG_ACCUMDATA_SHIFT);
switch (sr->ip_type) {
case SR_TYPE_V1:
sr_config |= SRCONFIG_DELAYCTRL;
senn_shift = SRCONFIG_SENNENABLE_V1_SHIFT;
senp_shift = SRCONFIG_SENPENABLE_V1_SHIFT;
break;
case SR_TYPE_V2:
senn_shift = SRCONFIG_SENNENABLE_V2_SHIFT;
senp_shift = SRCONFIG_SENPENABLE_V2_SHIFT;
break;
default:
dev_err(&sr->pdev->dev, "%s: Trying to Configure smartreflex"
"module without specifying the ip\n", __func__);
return -EINVAL;
}
sr_config |= ((senn_en << senn_shift) | (senp_en << senp_shift));
sr_write_reg(sr, SRCONFIG, sr_config);
sr_avgwt = (sr->senp_avgweight << AVGWEIGHT_SENPAVGWEIGHT_SHIFT) |
(sr->senn_avgweight << AVGWEIGHT_SENNAVGWEIGHT_SHIFT);
sr_write_reg(sr, AVGWEIGHT, sr_avgwt);
/*
* Enabling the interrupts if MINMAXAVG module is used.
* TODO: check if all the interrupts are mandatory
*/
switch (sr->ip_type) {
case SR_TYPE_V1:
sr_modify_reg(sr, ERRCONFIG_V1,
(ERRCONFIG_MCUACCUMINTEN | ERRCONFIG_MCUVALIDINTEN |
ERRCONFIG_MCUBOUNDINTEN),
(ERRCONFIG_MCUACCUMINTEN | ERRCONFIG_MCUACCUMINTST |
ERRCONFIG_MCUVALIDINTEN | ERRCONFIG_MCUVALIDINTST |
ERRCONFIG_MCUBOUNDINTEN | ERRCONFIG_MCUBOUNDINTST));
break;
case SR_TYPE_V2:
sr_write_reg(sr, IRQSTATUS,
IRQSTATUS_MCUACCUMINT | IRQSTATUS_MCVALIDINT |
IRQSTATUS_MCBOUNDSINT | IRQSTATUS_MCUDISABLEACKINT);
sr_write_reg(sr, IRQENABLE_SET,
IRQENABLE_MCUACCUMINT | IRQENABLE_MCUVALIDINT |
IRQENABLE_MCUBOUNDSINT | IRQENABLE_MCUDISABLEACKINT);
break;
default:
dev_err(&sr->pdev->dev, "%s: Trying to Configure smartreflex"
"module without specifying the ip\n", __func__);
return -EINVAL;
}
return 0;
}
/**
* sr_enable() - Enables the smartreflex module.
* @voltdm: VDD pointer to which the SR module to be configured belongs to.
* @volt: The voltage at which the Voltage domain associated with
* the smartreflex module is operating at.
* This is required only to program the correct Ntarget value.
*
* This API is to be called from the smartreflex class driver to
* enable a smartreflex module. Returns 0 on success. Returns error
* value if the voltage passed is wrong or if ntarget value is wrong.
*/
int sr_enable(struct voltagedomain *voltdm, unsigned long volt)
{
struct omap_volt_data *volt_data;
struct omap_sr *sr = _sr_lookup(voltdm);
struct omap_sr_nvalue_table *nvalue_row;
int ret;
if (IS_ERR(sr)) {
pr_warning("%s: omap_sr struct for voltdm not found\n", __func__);
return PTR_ERR(sr);
}
volt_data = omap_voltage_get_voltdata(sr->voltdm, volt);
if (IS_ERR(volt_data)) {
dev_warn(&sr->pdev->dev, "%s: Unable to get voltage table"
"for nominal voltage %ld\n", __func__, volt);
return PTR_ERR(volt_data);
}
nvalue_row = sr_retrieve_nvalue_row(sr, volt_data->sr_efuse_offs);
if (!nvalue_row) {
dev_warn(&sr->pdev->dev, "%s: failure getting SR data for this voltage %ld\n",
__func__, volt);
return -ENODATA;
}
/* errminlimit is opp dependent and hence linked to voltage */
sr->err_minlimit = nvalue_row->errminlimit;
pm_runtime_get_sync(&sr->pdev->dev);
/* Check if SR is already enabled. If yes do nothing */
if (sr_read_reg(sr, SRCONFIG) & SRCONFIG_SRENABLE)
return 0;
/* Configure SR */
ret = sr_class->configure(sr);
if (ret)
return ret;
sr_write_reg(sr, NVALUERECIPROCAL, nvalue_row->nvalue);
/* SRCONFIG - enable SR */
sr_modify_reg(sr, SRCONFIG, SRCONFIG_SRENABLE, SRCONFIG_SRENABLE);
return 0;
}
/**
* sr_disable() - Disables the smartreflex module.
* @voltdm: VDD pointer to which the SR module to be configured belongs to.
*
* This API is to be called from the smartreflex class driver to
* disable a smartreflex module.
*/
void sr_disable(struct voltagedomain *voltdm)
{
struct omap_sr *sr = _sr_lookup(voltdm);
if (IS_ERR(sr)) {
pr_warning("%s: omap_sr struct for voltdm not found\n", __func__);
return;
}
/* Check if SR clocks are already disabled. If yes do nothing */
if (pm_runtime_suspended(&sr->pdev->dev))
return;
/*
* Disable SR if only it is indeed enabled. Else just
* disable the clocks.
*/
if (sr_read_reg(sr, SRCONFIG) & SRCONFIG_SRENABLE) {
switch (sr->ip_type) {
case SR_TYPE_V1:
sr_v1_disable(sr);
break;
case SR_TYPE_V2:
sr_v2_disable(sr);
break;
default:
dev_err(&sr->pdev->dev, "UNKNOWN IP type %d\n",
sr->ip_type);
}
}
pm_runtime_put_sync_suspend(&sr->pdev->dev);
}
/**
* sr_register_class() - API to register a smartreflex class parameters.
* @class_data: The structure containing various sr class specific data.
*
* This API is to be called by the smartreflex class driver to register itself
* with the smartreflex driver during init. Returns 0 on success else the
* error value.
*/
int sr_register_class(struct omap_sr_class_data *class_data)
{
struct omap_sr *sr_info;
if (!class_data) {
pr_warning("%s:, Smartreflex class data passed is NULL\n",
__func__);
return -EINVAL;
}
if (sr_class) {
pr_warning("%s: Smartreflex class driver already registered\n",
__func__);
return -EBUSY;
}
sr_class = class_data;
/*
* Call into late init to do intializations that require
* both sr driver and sr class driver to be initiallized.
*/
list_for_each_entry(sr_info, &sr_list, node)
sr_late_init(sr_info);
return 0;
}
/**
* omap_sr_enable() - API to enable SR clocks and to call into the
* registered smartreflex class enable API.
* @voltdm: VDD pointer to which the SR module to be configured belongs to.
*
* This API is to be called from the kernel in order to enable
* a particular smartreflex module. This API will do the initial
* configurations to turn on the smartreflex module and in turn call
* into the registered smartreflex class enable API.
*/
void omap_sr_enable(struct voltagedomain *voltdm)
{
struct omap_sr *sr = _sr_lookup(voltdm);
if (IS_ERR(sr)) {
pr_warning("%s: omap_sr struct for voltdm not found\n", __func__);
return;
}
if (!sr->autocomp_active)
return;
if (!sr_class || !(sr_class->enable) || !(sr_class->configure)) {
dev_warn(&sr->pdev->dev, "%s: smartreflex class driver not"
"registered\n", __func__);
return;
}
sr_class->enable(sr);
}
/**
* omap_sr_disable() - API to disable SR without resetting the voltage
* processor voltage
* @voltdm: VDD pointer to which the SR module to be configured belongs to.
*
* This API is to be called from the kernel in order to disable
* a particular smartreflex module. This API will in turn call
* into the registered smartreflex class disable API. This API will tell
* the smartreflex class disable not to reset the VP voltage after
* disabling smartreflex.
*/
void omap_sr_disable(struct voltagedomain *voltdm)
{
struct omap_sr *sr = _sr_lookup(voltdm);
if (IS_ERR(sr)) {
pr_warning("%s: omap_sr struct for voltdm not found\n", __func__);
return;
}
if (!sr->autocomp_active)
return;
if (!sr_class || !(sr_class->disable)) {
dev_warn(&sr->pdev->dev, "%s: smartreflex class driver not"
"registered\n", __func__);
return;
}
sr_class->disable(sr, 0);
}
/**
* omap_sr_disable_reset_volt() - API to disable SR and reset the
* voltage processor voltage
* @voltdm: VDD pointer to which the SR module to be configured belongs to.
*
* This API is to be called from the kernel in order to disable
* a particular smartreflex module. This API will in turn call
* into the registered smartreflex class disable API. This API will tell
* the smartreflex class disable to reset the VP voltage after
* disabling smartreflex.
*/
void omap_sr_disable_reset_volt(struct voltagedomain *voltdm)
{
struct omap_sr *sr = _sr_lookup(voltdm);
if (IS_ERR(sr)) {
pr_warning("%s: omap_sr struct for voltdm not found\n", __func__);
return;
}
if (!sr->autocomp_active)
return;
if (!sr_class || !(sr_class->disable)) {
dev_warn(&sr->pdev->dev, "%s: smartreflex class driver not"
"registered\n", __func__);
return;
}
sr_class->disable(sr, 1);
}
/**
* omap_sr_register_pmic() - API to register pmic specific info.
* @pmic_data: The structure containing pmic specific data.
*
* This API is to be called from the PMIC specific code to register with
* smartreflex driver pmic specific info. Currently the only info required
* is the smartreflex init on the PMIC side.
*/
void omap_sr_register_pmic(struct omap_sr_pmic_data *pmic_data)
{
if (!pmic_data) {
pr_warning("%s: Trying to register NULL PMIC data structure"
"with smartreflex\n", __func__);
return;
}
sr_pmic_data = pmic_data;
}
/* PM Debug FS entries to enable and disable smartreflex. */
static int omap_sr_autocomp_show(void *data, u64 *val)
{
struct omap_sr *sr_info = data;
if (!sr_info) {
pr_warning("%s: omap_sr struct not found\n", __func__);
return -EINVAL;
}
*val = sr_info->autocomp_active;
return 0;
}
static int omap_sr_autocomp_store(void *data, u64 val)
{
struct omap_sr *sr_info = data;
if (!sr_info) {
pr_warning("%s: omap_sr struct not found\n", __func__);
return -EINVAL;
}
/* Sanity check */
if (val > 1) {
pr_warning("%s: Invalid argument %lld\n", __func__, val);
return -EINVAL;
}
/* control enable/disable only if there is a delta in value */
if (sr_info->autocomp_active != val) {
if (!val)
sr_stop_vddautocomp(sr_info);
else
sr_start_vddautocomp(sr_info);
}
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(pm_sr_fops, omap_sr_autocomp_show,
omap_sr_autocomp_store, "%llu\n");
static int __init omap_sr_probe(struct platform_device *pdev)
{
struct omap_sr *sr_info;
struct omap_sr_data *pdata = pdev->dev.platform_data;
struct resource *mem, *irq;
struct dentry *nvalue_dir;
int i, ret = 0;
sr_info = kzalloc(sizeof(struct omap_sr), GFP_KERNEL);
if (!sr_info) {
dev_err(&pdev->dev, "%s: unable to allocate sr_info\n",
__func__);
return -ENOMEM;
}
platform_set_drvdata(pdev, sr_info);
if (!pdata) {
dev_err(&pdev->dev, "%s: platform data missing\n", __func__);
ret = -EINVAL;
goto err_free_devinfo;
}
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem) {
dev_err(&pdev->dev, "%s: no mem resource\n", __func__);
ret = -ENODEV;
goto err_free_devinfo;
}
mem = request_mem_region(mem->start, resource_size(mem),
dev_name(&pdev->dev));
if (!mem) {
dev_err(&pdev->dev, "%s: no mem region\n", __func__);
ret = -EBUSY;
goto err_free_devinfo;
}
irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
pm_runtime_enable(&pdev->dev);
pm_runtime_irq_safe(&pdev->dev);
sr_info->name = kasprintf(GFP_KERNEL, "%s", pdata->name);
if (!sr_info->name) {
dev_err(&pdev->dev, "%s: Unable to alloc SR instance name\n",
__func__);
ret = -ENOMEM;
goto err_release_region;
}
sr_info->pdev = pdev;
sr_info->srid = pdev->id;
sr_info->voltdm = pdata->voltdm;
sr_info->nvalue_table = pdata->nvalue_table;
sr_info->nvalue_count = pdata->nvalue_count;
sr_info->senn_mod = pdata->senn_mod;
sr_info->senp_mod = pdata->senp_mod;
sr_info->err_weight = pdata->err_weight;
sr_info->err_maxlimit = pdata->err_maxlimit;
sr_info->accum_data = pdata->accum_data;
sr_info->senn_avgweight = pdata->senn_avgweight;
sr_info->senp_avgweight = pdata->senp_avgweight;
sr_info->autocomp_active = false;
sr_info->ip_type = pdata->ip_type;
sr_info->base = ioremap(mem->start, resource_size(mem));
if (!sr_info->base) {
dev_err(&pdev->dev, "%s: ioremap fail\n", __func__);
ret = -ENOMEM;
goto err_free_name;
}
if (irq)
sr_info->irq = irq->start;
sr_set_clk_length(sr_info);
list_add(&sr_info->node, &sr_list);
/*
* Call into late init to do intializations that require
* both sr driver and sr class driver to be initiallized.
*/
if (sr_class) {
ret = sr_late_init(sr_info);
if (ret) {
pr_warning("%s: Error in SR late init\n", __func__);
goto err_iounmap;
}
}
dev_info(&pdev->dev, "%s: SmartReflex driver initialized\n", __func__);
if (!sr_dbg_dir) {
sr_dbg_dir = debugfs_create_dir("smartreflex", NULL);
if (IS_ERR_OR_NULL(sr_dbg_dir)) {
ret = PTR_ERR(sr_dbg_dir);
pr_err("%s:sr debugfs dir creation failed(%d)\n",
__func__, ret);
goto err_iounmap;
}
}
sr_info->dbg_dir = debugfs_create_dir(sr_info->name, sr_dbg_dir);
if (IS_ERR_OR_NULL(sr_info->dbg_dir)) {
dev_err(&pdev->dev, "%s: Unable to create debugfs directory\n",
__func__);
ret = PTR_ERR(sr_info->dbg_dir);
goto err_debugfs;
}
(void) debugfs_create_file("autocomp", S_IRUGO | S_IWUSR,
sr_info->dbg_dir, (void *)sr_info, &pm_sr_fops);
(void) debugfs_create_x32("errweight", S_IRUGO, sr_info->dbg_dir,
&sr_info->err_weight);
(void) debugfs_create_x32("errmaxlimit", S_IRUGO, sr_info->dbg_dir,
&sr_info->err_maxlimit);
nvalue_dir = debugfs_create_dir("nvalue", sr_info->dbg_dir);
if (IS_ERR_OR_NULL(nvalue_dir)) {
dev_err(&pdev->dev, "%s: Unable to create debugfs directory"
"for n-values\n", __func__);
ret = PTR_ERR(nvalue_dir);
goto err_debugfs;
}
if (sr_info->nvalue_count == 0 || !sr_info->nvalue_table) {
dev_warn(&pdev->dev, "%s: %s: No Voltage table for the corresponding vdd. Cannot create debugfs entries for n-values\n",
__func__, sr_info->name);
ret = -ENODATA;
goto err_debugfs;
}
for (i = 0; i < sr_info->nvalue_count; i++) {
char name[NVALUE_NAME_LEN + 1];
snprintf(name, sizeof(name), "volt_%lu",
sr_info->nvalue_table[i].volt_nominal);
(void) debugfs_create_x32(name, S_IRUGO | S_IWUSR, nvalue_dir,
&(sr_info->nvalue_table[i].nvalue));
snprintf(name, sizeof(name), "errminlimit_%lu",
sr_info->nvalue_table[i].volt_nominal);
(void) debugfs_create_x32(name, S_IRUGO | S_IWUSR, nvalue_dir,
&(sr_info->nvalue_table[i].errminlimit));
}
return ret;
err_debugfs:
debugfs_remove_recursive(sr_info->dbg_dir);
err_iounmap:
list_del(&sr_info->node);
iounmap(sr_info->base);
err_free_name:
kfree(sr_info->name);
err_release_region:
release_mem_region(mem->start, resource_size(mem));
err_free_devinfo:
kfree(sr_info);
return ret;
}
static int omap_sr_remove(struct platform_device *pdev)
{
struct omap_sr_data *pdata = pdev->dev.platform_data;
struct omap_sr *sr_info;
struct resource *mem;
if (!pdata) {
dev_err(&pdev->dev, "%s: platform data missing\n", __func__);
return -EINVAL;
}
sr_info = _sr_lookup(pdata->voltdm);
if (IS_ERR(sr_info)) {
dev_warn(&pdev->dev, "%s: omap_sr struct not found\n",
__func__);
return PTR_ERR(sr_info);
}
if (sr_info->autocomp_active)
sr_stop_vddautocomp(sr_info);
if (sr_info->dbg_dir)
debugfs_remove_recursive(sr_info->dbg_dir);
list_del(&sr_info->node);
iounmap(sr_info->base);
kfree(sr_info->name);
kfree(sr_info);
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(mem->start, resource_size(mem));
return 0;
}
static void omap_sr_shutdown(struct platform_device *pdev)
{
struct omap_sr_data *pdata = pdev->dev.platform_data;
struct omap_sr *sr_info;
if (!pdata) {
dev_err(&pdev->dev, "%s: platform data missing\n", __func__);
return;
}
sr_info = _sr_lookup(pdata->voltdm);
if (IS_ERR(sr_info)) {
dev_warn(&pdev->dev, "%s: omap_sr struct not found\n",
__func__);
return;
}
if (sr_info->autocomp_active)
sr_stop_vddautocomp(sr_info);
return;
}
static struct platform_driver smartreflex_driver = {
.remove = omap_sr_remove,
.shutdown = omap_sr_shutdown,
.driver = {
.name = "smartreflex",
},
};
static int __init sr_init(void)
{
int ret = 0;
/*
* sr_init is a late init. If by then a pmic specific API is not
* registered either there is no need for anything to be done on
* the PMIC side or somebody has forgotten to register a PMIC
* handler. Warn for the second condition.
*/
if (sr_pmic_data && sr_pmic_data->sr_pmic_init)
sr_pmic_data->sr_pmic_init();
else
pr_warning("%s: No PMIC hook to init smartreflex\n", __func__);
ret = platform_driver_probe(&smartreflex_driver, omap_sr_probe);
if (ret) {
pr_err("%s: platform driver register failed for SR\n",
__func__);
return ret;
}
return 0;
}
late_initcall(sr_init);
static void __exit sr_exit(void)
{
platform_driver_unregister(&smartreflex_driver);
}
module_exit(sr_exit);
MODULE_DESCRIPTION("OMAP Smartreflex Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" DRIVER_NAME);
MODULE_AUTHOR("Texas Instruments Inc");
| gpl-2.0 |
TheTypoMaster/android_kernel_samsung_exynos5433 | sound/isa/gus/gusclassic.c | 2248 | 7329 | /*
* Driver for Gravis UltraSound Classic soundcard
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/init.h>
#include <linux/err.h>
#include <linux/isa.h>
#include <linux/delay.h>
#include <linux/time.h>
#include <linux/module.h>
#include <asm/dma.h>
#include <sound/core.h>
#include <sound/gus.h>
#define SNDRV_LEGACY_FIND_FREE_IRQ
#define SNDRV_LEGACY_FIND_FREE_DMA
#include <sound/initval.h>
#define CRD_NAME "Gravis UltraSound Classic"
#define DEV_NAME "gusclassic"
MODULE_DESCRIPTION(CRD_NAME);
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Gravis,UltraSound Classic}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE; /* Enable this card */
static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0x220,0x230,0x240,0x250,0x260 */
static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 3,5,9,11,12,15 */
static int dma1[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 1,3,5,6,7 */
static int dma2[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 1,3,5,6,7 */
static int joystick_dac[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 29};
/* 0 to 31, (0.59V-4.52V or 0.389V-2.98V) */
static int channels[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 24};
static int pcm_channels[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 2};
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for " CRD_NAME " soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for " CRD_NAME " soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable " CRD_NAME " soundcard.");
module_param_array(port, long, NULL, 0444);
MODULE_PARM_DESC(port, "Port # for " CRD_NAME " driver.");
module_param_array(irq, int, NULL, 0444);
MODULE_PARM_DESC(irq, "IRQ # for " CRD_NAME " driver.");
module_param_array(dma1, int, NULL, 0444);
MODULE_PARM_DESC(dma1, "DMA1 # for " CRD_NAME " driver.");
module_param_array(dma2, int, NULL, 0444);
MODULE_PARM_DESC(dma2, "DMA2 # for " CRD_NAME " driver.");
module_param_array(joystick_dac, int, NULL, 0444);
MODULE_PARM_DESC(joystick_dac, "Joystick DAC level 0.59V-4.52V or 0.389V-2.98V for " CRD_NAME " driver.");
module_param_array(channels, int, NULL, 0444);
MODULE_PARM_DESC(channels, "GF1 channels for " CRD_NAME " driver.");
module_param_array(pcm_channels, int, NULL, 0444);
MODULE_PARM_DESC(pcm_channels, "Reserved PCM channels for " CRD_NAME " driver.");
static int snd_gusclassic_match(struct device *dev, unsigned int n)
{
return enable[n];
}
static int snd_gusclassic_create(struct snd_card *card,
struct device *dev, unsigned int n,
struct snd_gus_card **rgus)
{
static long possible_ports[] = {0x220, 0x230, 0x240, 0x250, 0x260};
static int possible_irqs[] = {5, 11, 12, 9, 7, 15, 3, 4, -1};
static int possible_dmas[] = {5, 6, 7, 1, 3, -1};
int i, error;
if (irq[n] == SNDRV_AUTO_IRQ) {
irq[n] = snd_legacy_find_free_irq(possible_irqs);
if (irq[n] < 0) {
dev_err(dev, "unable to find a free IRQ\n");
return -EBUSY;
}
}
if (dma1[n] == SNDRV_AUTO_DMA) {
dma1[n] = snd_legacy_find_free_dma(possible_dmas);
if (dma1[n] < 0) {
dev_err(dev, "unable to find a free DMA1\n");
return -EBUSY;
}
}
if (dma2[n] == SNDRV_AUTO_DMA) {
dma2[n] = snd_legacy_find_free_dma(possible_dmas);
if (dma2[n] < 0) {
dev_err(dev, "unable to find a free DMA2\n");
return -EBUSY;
}
}
if (port[n] != SNDRV_AUTO_PORT)
return snd_gus_create(card, port[n], irq[n], dma1[n], dma2[n],
0, channels[n], pcm_channels[n], 0, rgus);
i = 0;
do {
port[n] = possible_ports[i];
error = snd_gus_create(card, port[n], irq[n], dma1[n], dma2[n],
0, channels[n], pcm_channels[n], 0, rgus);
} while (error < 0 && ++i < ARRAY_SIZE(possible_ports));
return error;
}
static int snd_gusclassic_detect(struct snd_gus_card *gus)
{
unsigned char d;
snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 0); /* reset GF1 */
if (((d = snd_gf1_i_look8(gus, SNDRV_GF1_GB_RESET)) & 0x07) != 0) {
snd_printdd("[0x%lx] check 1 failed - 0x%x\n", gus->gf1.port, d);
return -ENODEV;
}
udelay(160);
snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 1); /* release reset */
udelay(160);
if (((d = snd_gf1_i_look8(gus, SNDRV_GF1_GB_RESET)) & 0x07) != 1) {
snd_printdd("[0x%lx] check 2 failed - 0x%x\n", gus->gf1.port, d);
return -ENODEV;
}
return 0;
}
static int snd_gusclassic_probe(struct device *dev, unsigned int n)
{
struct snd_card *card;
struct snd_gus_card *gus;
int error;
error = snd_card_create(index[n], id[n], THIS_MODULE, 0, &card);
if (error < 0)
return error;
if (pcm_channels[n] < 2)
pcm_channels[n] = 2;
error = snd_gusclassic_create(card, dev, n, &gus);
if (error < 0)
goto out;
error = snd_gusclassic_detect(gus);
if (error < 0)
goto out;
gus->joystick_dac = joystick_dac[n];
error = snd_gus_initialize(gus);
if (error < 0)
goto out;
error = -ENODEV;
if (gus->max_flag || gus->ess_flag) {
dev_err(dev, "GUS Classic or ACE soundcard was "
"not detected at 0x%lx\n", gus->gf1.port);
goto out;
}
error = snd_gf1_new_mixer(gus);
if (error < 0)
goto out;
error = snd_gf1_pcm_new(gus, 0, 0, NULL);
if (error < 0)
goto out;
if (!gus->ace_flag) {
error = snd_gf1_rawmidi_new(gus, 0, NULL);
if (error < 0)
goto out;
}
sprintf(card->longname + strlen(card->longname),
" at 0x%lx, irq %d, dma %d",
gus->gf1.port, gus->gf1.irq, gus->gf1.dma1);
if (gus->gf1.dma2 >= 0)
sprintf(card->longname + strlen(card->longname),
"&%d", gus->gf1.dma2);
snd_card_set_dev(card, dev);
error = snd_card_register(card);
if (error < 0)
goto out;
dev_set_drvdata(dev, card);
return 0;
out: snd_card_free(card);
return error;
}
static int snd_gusclassic_remove(struct device *dev, unsigned int n)
{
snd_card_free(dev_get_drvdata(dev));
dev_set_drvdata(dev, NULL);
return 0;
}
static struct isa_driver snd_gusclassic_driver = {
.match = snd_gusclassic_match,
.probe = snd_gusclassic_probe,
.remove = snd_gusclassic_remove,
#if 0 /* FIXME */
.suspend = snd_gusclassic_suspend,
.remove = snd_gusclassic_remove,
#endif
.driver = {
.name = DEV_NAME
}
};
static int __init alsa_card_gusclassic_init(void)
{
return isa_register_driver(&snd_gusclassic_driver, SNDRV_CARDS);
}
static void __exit alsa_card_gusclassic_exit(void)
{
isa_unregister_driver(&snd_gusclassic_driver);
}
module_init(alsa_card_gusclassic_init);
module_exit(alsa_card_gusclassic_exit);
| gpl-2.0 |
DC07/spirit_msm8916 | arch/sh/kernel/cpu/sh4/setup-sh4-202.c | 2504 | 4657 | /*
* SH4-202 Setup
*
* Copyright (C) 2006 Paul Mundt
* Copyright (C) 2009 Magnus Damm
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/platform_device.h>
#include <linux/init.h>
#include <linux/serial.h>
#include <linux/serial_sci.h>
#include <linux/sh_timer.h>
#include <linux/sh_intc.h>
#include <linux/io.h>
static struct plat_sci_port scif0_platform_data = {
.mapbase = 0xffe80000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE | SCSCR_REIE,
.scbrr_algo_id = SCBRR_ALGO_2,
.type = PORT_SCIF,
.irqs = { evt2irq(0x700),
evt2irq(0x720),
evt2irq(0x760),
evt2irq(0x740) },
};
static struct platform_device scif0_device = {
.name = "sh-sci",
.id = 0,
.dev = {
.platform_data = &scif0_platform_data,
},
};
static struct sh_timer_config tmu0_platform_data = {
.channel_offset = 0x04,
.timer_bit = 0,
.clockevent_rating = 200,
};
static struct resource tmu0_resources[] = {
[0] = {
.start = 0xffd80008,
.end = 0xffd80013,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x400),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu0_device = {
.name = "sh_tmu",
.id = 0,
.dev = {
.platform_data = &tmu0_platform_data,
},
.resource = tmu0_resources,
.num_resources = ARRAY_SIZE(tmu0_resources),
};
static struct sh_timer_config tmu1_platform_data = {
.channel_offset = 0x10,
.timer_bit = 1,
.clocksource_rating = 200,
};
static struct resource tmu1_resources[] = {
[0] = {
.start = 0xffd80014,
.end = 0xffd8001f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x420),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu1_device = {
.name = "sh_tmu",
.id = 1,
.dev = {
.platform_data = &tmu1_platform_data,
},
.resource = tmu1_resources,
.num_resources = ARRAY_SIZE(tmu1_resources),
};
static struct sh_timer_config tmu2_platform_data = {
.channel_offset = 0x1c,
.timer_bit = 2,
};
static struct resource tmu2_resources[] = {
[0] = {
.start = 0xffd80020,
.end = 0xffd8002f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x440),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device tmu2_device = {
.name = "sh_tmu",
.id = 2,
.dev = {
.platform_data = &tmu2_platform_data,
},
.resource = tmu2_resources,
.num_resources = ARRAY_SIZE(tmu2_resources),
};
static struct platform_device *sh4202_devices[] __initdata = {
&scif0_device,
&tmu0_device,
&tmu1_device,
&tmu2_device,
};
static int __init sh4202_devices_setup(void)
{
return platform_add_devices(sh4202_devices,
ARRAY_SIZE(sh4202_devices));
}
arch_initcall(sh4202_devices_setup);
static struct platform_device *sh4202_early_devices[] __initdata = {
&scif0_device,
&tmu0_device,
&tmu1_device,
&tmu2_device,
};
void __init plat_early_device_setup(void)
{
early_platform_add_devices(sh4202_early_devices,
ARRAY_SIZE(sh4202_early_devices));
}
enum {
UNUSED = 0,
/* interrupt sources */
IRL0, IRL1, IRL2, IRL3, /* only IRLM mode supported */
HUDI, TMU0, TMU1, TMU2, RTC, SCIF, WDT,
};
static struct intc_vect vectors[] __initdata = {
INTC_VECT(HUDI, 0x600),
INTC_VECT(TMU0, 0x400), INTC_VECT(TMU1, 0x420),
INTC_VECT(TMU2, 0x440), INTC_VECT(TMU2, 0x460),
INTC_VECT(RTC, 0x480), INTC_VECT(RTC, 0x4a0),
INTC_VECT(RTC, 0x4c0),
INTC_VECT(SCIF, 0x700), INTC_VECT(SCIF, 0x720),
INTC_VECT(SCIF, 0x740), INTC_VECT(SCIF, 0x760),
INTC_VECT(WDT, 0x560),
};
static struct intc_prio_reg prio_registers[] __initdata = {
{ 0xffd00004, 0, 16, 4, /* IPRA */ { TMU0, TMU1, TMU2, RTC } },
{ 0xffd00008, 0, 16, 4, /* IPRB */ { WDT, 0, 0, 0 } },
{ 0xffd0000c, 0, 16, 4, /* IPRC */ { 0, 0, SCIF, HUDI } },
{ 0xffd00010, 0, 16, 4, /* IPRD */ { IRL0, IRL1, IRL2, IRL3 } },
};
static DECLARE_INTC_DESC(intc_desc, "sh4-202", vectors, NULL,
NULL, prio_registers, NULL);
static struct intc_vect vectors_irlm[] __initdata = {
INTC_VECT(IRL0, 0x240), INTC_VECT(IRL1, 0x2a0),
INTC_VECT(IRL2, 0x300), INTC_VECT(IRL3, 0x360),
};
static DECLARE_INTC_DESC(intc_desc_irlm, "sh4-202_irlm", vectors_irlm, NULL,
NULL, prio_registers, NULL);
void __init plat_irq_setup(void)
{
register_intc_controller(&intc_desc);
}
#define INTC_ICR 0xffd00000UL
#define INTC_ICR_IRLM (1<<7)
void __init plat_irq_setup_pins(int mode)
{
switch (mode) {
case IRQ_MODE_IRQ: /* individual interrupt mode for IRL3-0 */
__raw_writew(__raw_readw(INTC_ICR) | INTC_ICR_IRLM, INTC_ICR);
register_intc_controller(&intc_desc_irlm);
break;
default:
BUG();
}
}
| gpl-2.0 |
cdesjardins/DTS-Eagle-Integration_CAF-Android-kernel | arch/x86/kernel/cpu/mcheck/mce-apei.c | 2504 | 4398 | /*
* Bridge between MCE and APEI
*
* On some machine, corrected memory errors are reported via APEI
* generic hardware error source (GHES) instead of corrected Machine
* Check. These corrected memory errors can be reported to user space
* through /dev/mcelog via faking a corrected Machine Check, so that
* the error memory page can be offlined by /sbin/mcelog if the error
* count for one page is beyond the threshold.
*
* For fatal MCE, save MCE record into persistent storage via ERST, so
* that the MCE record can be logged after reboot via ERST.
*
* Copyright 2010 Intel Corp.
* Author: Huang Ying <ying.huang@intel.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/export.h>
#include <linux/kernel.h>
#include <linux/acpi.h>
#include <linux/cper.h>
#include <acpi/apei.h>
#include <asm/mce.h>
#include "mce-internal.h"
void apei_mce_report_mem_error(int corrected, struct cper_sec_mem_err *mem_err)
{
struct mce m;
/* Only corrected MC is reported */
if (!corrected || !(mem_err->validation_bits &
CPER_MEM_VALID_PHYSICAL_ADDRESS))
return;
mce_setup(&m);
m.bank = 1;
/* Fake a memory read corrected error with unknown channel */
m.status = MCI_STATUS_VAL | MCI_STATUS_EN | MCI_STATUS_ADDRV | 0x9f;
m.addr = mem_err->physical_addr;
mce_log(&m);
mce_notify_irq();
}
EXPORT_SYMBOL_GPL(apei_mce_report_mem_error);
#define CPER_CREATOR_MCE \
UUID_LE(0x75a574e3, 0x5052, 0x4b29, 0x8a, 0x8e, 0xbe, 0x2c, \
0x64, 0x90, 0xb8, 0x9d)
#define CPER_SECTION_TYPE_MCE \
UUID_LE(0xfe08ffbe, 0x95e4, 0x4be7, 0xbc, 0x73, 0x40, 0x96, \
0x04, 0x4a, 0x38, 0xfc)
/*
* CPER specification (in UEFI specification 2.3 appendix N) requires
* byte-packed.
*/
struct cper_mce_record {
struct cper_record_header hdr;
struct cper_section_descriptor sec_hdr;
struct mce mce;
} __packed;
int apei_write_mce(struct mce *m)
{
struct cper_mce_record rcd;
memset(&rcd, 0, sizeof(rcd));
memcpy(rcd.hdr.signature, CPER_SIG_RECORD, CPER_SIG_SIZE);
rcd.hdr.revision = CPER_RECORD_REV;
rcd.hdr.signature_end = CPER_SIG_END;
rcd.hdr.section_count = 1;
rcd.hdr.error_severity = CPER_SEV_FATAL;
/* timestamp, platform_id, partition_id are all invalid */
rcd.hdr.validation_bits = 0;
rcd.hdr.record_length = sizeof(rcd);
rcd.hdr.creator_id = CPER_CREATOR_MCE;
rcd.hdr.notification_type = CPER_NOTIFY_MCE;
rcd.hdr.record_id = cper_next_record_id();
rcd.hdr.flags = CPER_HW_ERROR_FLAGS_PREVERR;
rcd.sec_hdr.section_offset = (void *)&rcd.mce - (void *)&rcd;
rcd.sec_hdr.section_length = sizeof(rcd.mce);
rcd.sec_hdr.revision = CPER_SEC_REV;
/* fru_id and fru_text is invalid */
rcd.sec_hdr.validation_bits = 0;
rcd.sec_hdr.flags = CPER_SEC_PRIMARY;
rcd.sec_hdr.section_type = CPER_SECTION_TYPE_MCE;
rcd.sec_hdr.section_severity = CPER_SEV_FATAL;
memcpy(&rcd.mce, m, sizeof(*m));
return erst_write(&rcd.hdr);
}
ssize_t apei_read_mce(struct mce *m, u64 *record_id)
{
struct cper_mce_record rcd;
int rc, pos;
rc = erst_get_record_id_begin(&pos);
if (rc)
return rc;
retry:
rc = erst_get_record_id_next(&pos, record_id);
if (rc)
goto out;
/* no more record */
if (*record_id == APEI_ERST_INVALID_RECORD_ID)
goto out;
rc = erst_read(*record_id, &rcd.hdr, sizeof(rcd));
/* someone else has cleared the record, try next one */
if (rc == -ENOENT)
goto retry;
else if (rc < 0)
goto out;
/* try to skip other type records in storage */
else if (rc != sizeof(rcd) ||
uuid_le_cmp(rcd.hdr.creator_id, CPER_CREATOR_MCE))
goto retry;
memcpy(m, &rcd.mce, sizeof(*m));
rc = sizeof(*m);
out:
erst_get_record_id_end();
return rc;
}
/* Check whether there is record in ERST */
int apei_check_mce(void)
{
return erst_get_record_count();
}
int apei_clear_mce(u64 record_id)
{
return erst_clear(record_id);
}
| gpl-2.0 |
mukulsoni/android_kernel_samsung_ms013g-G4SWA | net/l2tp/l2tp_eth.c | 2760 | 7362 | /*
* L2TPv3 ethernet pseudowire driver
*
* Copyright (c) 2008,2009,2010 Katalix Systems Ltd
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/socket.h>
#include <linux/hash.h>
#include <linux/l2tp.h>
#include <linux/in.h>
#include <linux/etherdevice.h>
#include <linux/spinlock.h>
#include <net/sock.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/udp.h>
#include <net/inet_common.h>
#include <net/inet_hashtables.h>
#include <net/tcp_states.h>
#include <net/protocol.h>
#include <net/xfrm.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include "l2tp_core.h"
/* Default device name. May be overridden by name specified by user */
#define L2TP_ETH_DEV_NAME "l2tpeth%d"
/* via netdev_priv() */
struct l2tp_eth {
struct net_device *dev;
struct sock *tunnel_sock;
struct l2tp_session *session;
struct list_head list;
};
/* via l2tp_session_priv() */
struct l2tp_eth_sess {
struct net_device *dev;
};
/* per-net private data for this module */
static unsigned int l2tp_eth_net_id;
struct l2tp_eth_net {
struct list_head l2tp_eth_dev_list;
spinlock_t l2tp_eth_lock;
};
static inline struct l2tp_eth_net *l2tp_eth_pernet(struct net *net)
{
return net_generic(net, l2tp_eth_net_id);
}
static int l2tp_eth_dev_init(struct net_device *dev)
{
struct l2tp_eth *priv = netdev_priv(dev);
priv->dev = dev;
eth_hw_addr_random(dev);
memset(&dev->broadcast[0], 0xff, 6);
return 0;
}
static void l2tp_eth_dev_uninit(struct net_device *dev)
{
struct l2tp_eth *priv = netdev_priv(dev);
struct l2tp_eth_net *pn = l2tp_eth_pernet(dev_net(dev));
spin_lock(&pn->l2tp_eth_lock);
list_del_init(&priv->list);
spin_unlock(&pn->l2tp_eth_lock);
dev_put(dev);
}
static int l2tp_eth_dev_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct l2tp_eth *priv = netdev_priv(dev);
struct l2tp_session *session = priv->session;
l2tp_xmit_skb(session, skb, session->hdr_len);
dev->stats.tx_bytes += skb->len;
dev->stats.tx_packets++;
return 0;
}
static struct net_device_ops l2tp_eth_netdev_ops = {
.ndo_init = l2tp_eth_dev_init,
.ndo_uninit = l2tp_eth_dev_uninit,
.ndo_start_xmit = l2tp_eth_dev_xmit,
};
static void l2tp_eth_dev_setup(struct net_device *dev)
{
ether_setup(dev);
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
dev->netdev_ops = &l2tp_eth_netdev_ops;
dev->destructor = free_netdev;
}
static void l2tp_eth_dev_recv(struct l2tp_session *session, struct sk_buff *skb, int data_len)
{
struct l2tp_eth_sess *spriv = l2tp_session_priv(session);
struct net_device *dev = spriv->dev;
if (session->debug & L2TP_MSG_DATA) {
unsigned int length;
int offset;
u8 *ptr = skb->data;
length = min(32u, skb->len);
if (!pskb_may_pull(skb, length))
goto error;
printk(KERN_DEBUG "%s: eth recv: ", session->name);
offset = 0;
do {
printk(" %02X", ptr[offset]);
} while (++offset < length);
printk("\n");
}
if (!pskb_may_pull(skb, sizeof(ETH_HLEN)))
goto error;
secpath_reset(skb);
/* checksums verified by L2TP */
skb->ip_summed = CHECKSUM_NONE;
skb_dst_drop(skb);
nf_reset(skb);
if (dev_forward_skb(dev, skb) == NET_RX_SUCCESS) {
dev->stats.rx_packets++;
dev->stats.rx_bytes += data_len;
} else
dev->stats.rx_errors++;
return;
error:
dev->stats.rx_errors++;
kfree_skb(skb);
}
static void l2tp_eth_delete(struct l2tp_session *session)
{
struct l2tp_eth_sess *spriv;
struct net_device *dev;
if (session) {
spriv = l2tp_session_priv(session);
dev = spriv->dev;
if (dev) {
unregister_netdev(dev);
spriv->dev = NULL;
}
}
}
#if defined(CONFIG_L2TP_DEBUGFS) || defined(CONFIG_L2TP_DEBUGFS_MODULE)
static void l2tp_eth_show(struct seq_file *m, void *arg)
{
struct l2tp_session *session = arg;
struct l2tp_eth_sess *spriv = l2tp_session_priv(session);
struct net_device *dev = spriv->dev;
seq_printf(m, " interface %s\n", dev->name);
}
#endif
static int l2tp_eth_create(struct net *net, u32 tunnel_id, u32 session_id, u32 peer_session_id, struct l2tp_session_cfg *cfg)
{
struct net_device *dev;
char name[IFNAMSIZ];
struct l2tp_tunnel *tunnel;
struct l2tp_session *session;
struct l2tp_eth *priv;
struct l2tp_eth_sess *spriv;
int rc;
struct l2tp_eth_net *pn;
tunnel = l2tp_tunnel_find(net, tunnel_id);
if (!tunnel) {
rc = -ENODEV;
goto out;
}
session = l2tp_session_find(net, tunnel, session_id);
if (session) {
rc = -EEXIST;
goto out;
}
if (cfg->ifname) {
dev = dev_get_by_name(net, cfg->ifname);
if (dev) {
dev_put(dev);
rc = -EEXIST;
goto out;
}
strlcpy(name, cfg->ifname, IFNAMSIZ);
} else
strcpy(name, L2TP_ETH_DEV_NAME);
session = l2tp_session_create(sizeof(*spriv), tunnel, session_id,
peer_session_id, cfg);
if (!session) {
rc = -ENOMEM;
goto out;
}
dev = alloc_netdev(sizeof(*priv), name, l2tp_eth_dev_setup);
if (!dev) {
rc = -ENOMEM;
goto out_del_session;
}
dev_net_set(dev, net);
if (session->mtu == 0)
session->mtu = dev->mtu - session->hdr_len;
dev->mtu = session->mtu;
dev->needed_headroom += session->hdr_len;
priv = netdev_priv(dev);
priv->dev = dev;
priv->session = session;
INIT_LIST_HEAD(&priv->list);
priv->tunnel_sock = tunnel->sock;
session->recv_skb = l2tp_eth_dev_recv;
session->session_close = l2tp_eth_delete;
#if defined(CONFIG_L2TP_DEBUGFS) || defined(CONFIG_L2TP_DEBUGFS_MODULE)
session->show = l2tp_eth_show;
#endif
spriv = l2tp_session_priv(session);
spriv->dev = dev;
rc = register_netdev(dev);
if (rc < 0)
goto out_del_dev;
/* Must be done after register_netdev() */
strlcpy(session->ifname, dev->name, IFNAMSIZ);
dev_hold(dev);
pn = l2tp_eth_pernet(dev_net(dev));
spin_lock(&pn->l2tp_eth_lock);
list_add(&priv->list, &pn->l2tp_eth_dev_list);
spin_unlock(&pn->l2tp_eth_lock);
return 0;
out_del_dev:
free_netdev(dev);
out_del_session:
l2tp_session_delete(session);
out:
return rc;
}
static __net_init int l2tp_eth_init_net(struct net *net)
{
struct l2tp_eth_net *pn = net_generic(net, l2tp_eth_net_id);
INIT_LIST_HEAD(&pn->l2tp_eth_dev_list);
spin_lock_init(&pn->l2tp_eth_lock);
return 0;
}
static struct pernet_operations l2tp_eth_net_ops = {
.init = l2tp_eth_init_net,
.id = &l2tp_eth_net_id,
.size = sizeof(struct l2tp_eth_net),
};
static const struct l2tp_nl_cmd_ops l2tp_eth_nl_cmd_ops = {
.session_create = l2tp_eth_create,
.session_delete = l2tp_session_delete,
};
static int __init l2tp_eth_init(void)
{
int err = 0;
err = l2tp_nl_register_ops(L2TP_PWTYPE_ETH, &l2tp_eth_nl_cmd_ops);
if (err)
goto out;
err = register_pernet_device(&l2tp_eth_net_ops);
if (err)
goto out_unreg;
printk(KERN_INFO "L2TP ethernet pseudowire support (L2TPv3)\n");
return 0;
out_unreg:
l2tp_nl_unregister_ops(L2TP_PWTYPE_ETH);
out:
return err;
}
static void __exit l2tp_eth_exit(void)
{
unregister_pernet_device(&l2tp_eth_net_ops);
l2tp_nl_unregister_ops(L2TP_PWTYPE_ETH);
}
module_init(l2tp_eth_init);
module_exit(l2tp_eth_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("James Chapman <jchapman@katalix.com>");
MODULE_DESCRIPTION("L2TP ethernet pseudowire driver");
MODULE_VERSION("1.0");
| gpl-2.0 |
piasek1906/Piasek-KK-G2 | arch/hexagon/kernel/signal.c | 3016 | 9307 | /*
* Signal support for Hexagon processor
*
* Copyright (c) 2010-2011, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <linux/linkage.h>
#include <linux/syscalls.h>
#include <linux/freezer.h>
#include <linux/tracehook.h>
#include <asm/registers.h>
#include <asm/thread_info.h>
#include <asm/unistd.h>
#include <asm/uaccess.h>
#include <asm/ucontext.h>
#include <asm/cacheflush.h>
#include <asm/signal.h>
#include <asm/vdso.h>
#define _BLOCKABLE (~(sigmask(SIGKILL) | sigmask(SIGSTOP)))
struct rt_sigframe {
unsigned long tramp[2];
struct siginfo info;
struct ucontext uc;
};
static void __user *get_sigframe(struct k_sigaction *ka, struct pt_regs *regs,
size_t frame_size)
{
unsigned long sp = regs->r29;
/* Switch to signal stack if appropriate */
if ((ka->sa.sa_flags & SA_ONSTACK) && (sas_ss_flags(sp) == 0))
sp = current->sas_ss_sp + current->sas_ss_size;
return (void __user *)((sp - frame_size) & ~(sizeof(long long) - 1));
}
static int setup_sigcontext(struct pt_regs *regs, struct sigcontext __user *sc)
{
unsigned long tmp;
int err = 0;
err |= copy_to_user(&sc->sc_regs.r0, ®s->r00,
32*sizeof(unsigned long));
err |= __put_user(regs->sa0, &sc->sc_regs.sa0);
err |= __put_user(regs->lc0, &sc->sc_regs.lc0);
err |= __put_user(regs->sa1, &sc->sc_regs.sa1);
err |= __put_user(regs->lc1, &sc->sc_regs.lc1);
err |= __put_user(regs->m0, &sc->sc_regs.m0);
err |= __put_user(regs->m1, &sc->sc_regs.m1);
err |= __put_user(regs->usr, &sc->sc_regs.usr);
err |= __put_user(regs->preds, &sc->sc_regs.p3_0);
err |= __put_user(regs->gp, &sc->sc_regs.gp);
err |= __put_user(regs->ugp, &sc->sc_regs.ugp);
tmp = pt_elr(regs); err |= __put_user(tmp, &sc->sc_regs.pc);
tmp = pt_cause(regs); err |= __put_user(tmp, &sc->sc_regs.cause);
tmp = pt_badva(regs); err |= __put_user(tmp, &sc->sc_regs.badva);
return err;
}
static int restore_sigcontext(struct pt_regs *regs,
struct sigcontext __user *sc)
{
unsigned long tmp;
int err = 0;
err |= copy_from_user(®s->r00, &sc->sc_regs.r0,
32 * sizeof(unsigned long));
err |= __get_user(regs->sa0, &sc->sc_regs.sa0);
err |= __get_user(regs->lc0, &sc->sc_regs.lc0);
err |= __get_user(regs->sa1, &sc->sc_regs.sa1);
err |= __get_user(regs->lc1, &sc->sc_regs.lc1);
err |= __get_user(regs->m0, &sc->sc_regs.m0);
err |= __get_user(regs->m1, &sc->sc_regs.m1);
err |= __get_user(regs->usr, &sc->sc_regs.usr);
err |= __get_user(regs->preds, &sc->sc_regs.p3_0);
err |= __get_user(regs->gp, &sc->sc_regs.gp);
err |= __get_user(regs->ugp, &sc->sc_regs.ugp);
err |= __get_user(tmp, &sc->sc_regs.pc); pt_set_elr(regs, tmp);
return err;
}
/*
* Setup signal stack frame with siginfo structure
*/
static int setup_rt_frame(int signr, struct k_sigaction *ka, siginfo_t *info,
sigset_t *set, struct pt_regs *regs)
{
int err = 0;
struct rt_sigframe __user *frame;
struct hexagon_vdso *vdso = current->mm->context.vdso;
frame = get_sigframe(ka, regs, sizeof(struct rt_sigframe));
if (!access_ok(VERIFY_WRITE, frame, sizeof(struct rt_sigframe)))
goto sigsegv;
if (copy_siginfo_to_user(&frame->info, info))
goto sigsegv;
/* The on-stack signal trampoline is no longer executed;
* however, the libgcc signal frame unwinding code checks for
* the presence of these two numeric magic values.
*/
err |= __put_user(0x7800d166, &frame->tramp[0]);
err |= __put_user(0x5400c004, &frame->tramp[1]);
err |= setup_sigcontext(regs, &frame->uc.uc_mcontext);
err |= __copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set));
if (err)
goto sigsegv;
/* Load r0/r1 pair with signumber/siginfo pointer... */
regs->r0100 = ((unsigned long long)((unsigned long)&frame->info) << 32)
| (unsigned long long)signr;
regs->r02 = (unsigned long) &frame->uc;
regs->r31 = (unsigned long) vdso->rt_signal_trampoline;
pt_psp(regs) = (unsigned long) frame;
pt_set_elr(regs, (unsigned long)ka->sa.sa_handler);
return 0;
sigsegv:
force_sigsegv(signr, current);
return -EFAULT;
}
/*
* Setup invocation of signal handler
*/
static int handle_signal(int sig, siginfo_t *info, struct k_sigaction *ka,
sigset_t *oldset, struct pt_regs *regs)
{
int rc;
/*
* If we're handling a signal that aborted a system call,
* set up the error return value before adding the signal
* frame to the stack.
*/
if (regs->syscall_nr >= 0) {
switch (regs->r00) {
case -ERESTART_RESTARTBLOCK:
case -ERESTARTNOHAND:
regs->r00 = -EINTR;
break;
case -ERESTARTSYS:
if (!(ka->sa.sa_flags & SA_RESTART)) {
regs->r00 = -EINTR;
break;
}
/* Fall through */
case -ERESTARTNOINTR:
regs->r06 = regs->syscall_nr;
pt_set_elr(regs, pt_elr(regs) - 4);
regs->r00 = regs->restart_r0;
break;
default:
break;
}
}
/*
* Set up the stack frame; not doing the SA_SIGINFO thing. We
* only set up the rt_frame flavor.
*/
rc = setup_rt_frame(sig, ka, info, oldset, regs);
/* If there was an error on setup, no signal was delivered. */
if (rc)
return rc;
block_sigmask(ka, sig);
return 0;
}
/*
* Called from return-from-event code.
*/
static void do_signal(struct pt_regs *regs)
{
struct k_sigaction sigact;
siginfo_t info;
int signo;
if (!user_mode(regs))
return;
if (try_to_freeze())
goto no_signal;
signo = get_signal_to_deliver(&info, &sigact, regs, NULL);
if (signo > 0) {
sigset_t *oldset;
if (test_thread_flag(TIF_RESTORE_SIGMASK))
oldset = ¤t->saved_sigmask;
else
oldset = ¤t->blocked;
if (handle_signal(signo, &info, &sigact, oldset, regs) == 0) {
/*
* Successful delivery case. The saved sigmask is
* stored in the signal frame, and will be restored
* by sigreturn. We can clear the TIF flag.
*/
clear_thread_flag(TIF_RESTORE_SIGMASK);
tracehook_signal_handler(signo, &info, &sigact, regs,
test_thread_flag(TIF_SINGLESTEP));
}
return;
}
no_signal:
/*
* If we came from a system call, handle the restart.
*/
if (regs->syscall_nr >= 0) {
switch (regs->r00) {
case -ERESTARTNOHAND:
case -ERESTARTSYS:
case -ERESTARTNOINTR:
regs->r06 = regs->syscall_nr;
break;
case -ERESTART_RESTARTBLOCK:
regs->r06 = __NR_restart_syscall;
break;
default:
goto no_restart;
}
pt_set_elr(regs, pt_elr(regs) - 4);
regs->r00 = regs->restart_r0;
}
no_restart:
/* If there's no signal to deliver, put the saved sigmask back */
if (test_thread_flag(TIF_RESTORE_SIGMASK)) {
clear_thread_flag(TIF_RESTORE_SIGMASK);
sigprocmask(SIG_SETMASK, ¤t->saved_sigmask, NULL);
}
}
void do_notify_resume(struct pt_regs *regs, unsigned long thread_info_flags)
{
if (thread_info_flags & _TIF_SIGPENDING)
do_signal(regs);
if (thread_info_flags & _TIF_NOTIFY_RESUME) {
clear_thread_flag(TIF_NOTIFY_RESUME);
if (current->replacement_session_keyring)
key_replace_session_keyring();
}
}
/*
* Architecture-specific wrappers for signal-related system calls
*/
asmlinkage int sys_sigaltstack(const stack_t __user *uss, stack_t __user *uoss)
{
struct pt_regs *regs = current_thread_info()->regs;
return do_sigaltstack(uss, uoss, regs->r29);
}
asmlinkage int sys_rt_sigreturn(void)
{
struct pt_regs *regs = current_thread_info()->regs;
struct rt_sigframe __user *frame;
sigset_t blocked;
frame = (struct rt_sigframe __user *)pt_psp(regs);
if (!access_ok(VERIFY_READ, frame, sizeof(*frame)))
goto badframe;
if (__copy_from_user(&blocked, &frame->uc.uc_sigmask, sizeof(blocked)))
goto badframe;
sigdelsetmask(&blocked, ~_BLOCKABLE);
set_current_blocked(&blocked);
if (restore_sigcontext(regs, &frame->uc.uc_mcontext))
goto badframe;
/* Restore the user's stack as well */
pt_psp(regs) = regs->r29;
/*
* Leave a trace in the stack frame that this was a sigreturn.
* If the system call is to replay, we've already restored the
* number in the GPR slot and it will be regenerated on the
* new system call trap entry. Note that if restore_sigcontext()
* did something other than a bulk copy of the pt_regs struct,
* we could avoid this assignment by simply not overwriting
* regs->syscall_nr.
*/
regs->syscall_nr = __NR_rt_sigreturn;
/*
* If we were meticulous, we'd only call this if we knew that
* we were actually going to use an alternate stack, and we'd
* consider any error to be fatal. What we do here, in common
* with many other architectures, is call it blindly and only
* consider the -EFAULT return case to be proof of a problem.
*/
if (do_sigaltstack(&frame->uc.uc_stack, NULL, pt_psp(regs)) == -EFAULT)
goto badframe;
return 0;
badframe:
force_sig(SIGSEGV, current);
return 0;
}
| gpl-2.0 |
Sangsub/android-samsung-2.6.35-gingerbread | net/ieee802154/nl-mac.c | 4040 | 16109 | /*
* Netlink inteface for IEEE 802.15.4 stack
*
* Copyright 2007, 2008 Siemens AG
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Written by:
* Sergey Lapin <slapin@ossfans.org>
* Dmitry Eremin-Solenikov <dbaryshkov@gmail.com>
* Maxim Osipov <maxim.osipov@siemens.com>
*/
#include <linux/gfp.h>
#include <linux/kernel.h>
#include <linux/if_arp.h>
#include <linux/netdevice.h>
#include <net/netlink.h>
#include <net/genetlink.h>
#include <net/sock.h>
#include <linux/nl802154.h>
#include <net/af_ieee802154.h>
#include <net/nl802154.h>
#include <net/ieee802154.h>
#include <net/ieee802154_netdev.h>
#include <net/wpan-phy.h>
#include "ieee802154.h"
static struct genl_multicast_group ieee802154_coord_mcgrp = {
.name = IEEE802154_MCAST_COORD_NAME,
};
static struct genl_multicast_group ieee802154_beacon_mcgrp = {
.name = IEEE802154_MCAST_BEACON_NAME,
};
int ieee802154_nl_assoc_indic(struct net_device *dev,
struct ieee802154_addr *addr, u8 cap)
{
struct sk_buff *msg;
pr_debug("%s\n", __func__);
if (addr->addr_type != IEEE802154_ADDR_LONG) {
pr_err("%s: received non-long source address!\n", __func__);
return -EINVAL;
}
msg = ieee802154_nl_create(0, IEEE802154_ASSOCIATE_INDIC);
if (!msg)
return -ENOBUFS;
NLA_PUT_STRING(msg, IEEE802154_ATTR_DEV_NAME, dev->name);
NLA_PUT_U32(msg, IEEE802154_ATTR_DEV_INDEX, dev->ifindex);
NLA_PUT(msg, IEEE802154_ATTR_HW_ADDR, IEEE802154_ADDR_LEN,
dev->dev_addr);
NLA_PUT(msg, IEEE802154_ATTR_SRC_HW_ADDR, IEEE802154_ADDR_LEN,
addr->hwaddr);
NLA_PUT_U8(msg, IEEE802154_ATTR_CAPABILITY, cap);
return ieee802154_nl_mcast(msg, ieee802154_coord_mcgrp.id);
nla_put_failure:
nlmsg_free(msg);
return -ENOBUFS;
}
EXPORT_SYMBOL(ieee802154_nl_assoc_indic);
int ieee802154_nl_assoc_confirm(struct net_device *dev, u16 short_addr,
u8 status)
{
struct sk_buff *msg;
pr_debug("%s\n", __func__);
msg = ieee802154_nl_create(0, IEEE802154_ASSOCIATE_CONF);
if (!msg)
return -ENOBUFS;
NLA_PUT_STRING(msg, IEEE802154_ATTR_DEV_NAME, dev->name);
NLA_PUT_U32(msg, IEEE802154_ATTR_DEV_INDEX, dev->ifindex);
NLA_PUT(msg, IEEE802154_ATTR_HW_ADDR, IEEE802154_ADDR_LEN,
dev->dev_addr);
NLA_PUT_U16(msg, IEEE802154_ATTR_SHORT_ADDR, short_addr);
NLA_PUT_U8(msg, IEEE802154_ATTR_STATUS, status);
return ieee802154_nl_mcast(msg, ieee802154_coord_mcgrp.id);
nla_put_failure:
nlmsg_free(msg);
return -ENOBUFS;
}
EXPORT_SYMBOL(ieee802154_nl_assoc_confirm);
int ieee802154_nl_disassoc_indic(struct net_device *dev,
struct ieee802154_addr *addr, u8 reason)
{
struct sk_buff *msg;
pr_debug("%s\n", __func__);
msg = ieee802154_nl_create(0, IEEE802154_DISASSOCIATE_INDIC);
if (!msg)
return -ENOBUFS;
NLA_PUT_STRING(msg, IEEE802154_ATTR_DEV_NAME, dev->name);
NLA_PUT_U32(msg, IEEE802154_ATTR_DEV_INDEX, dev->ifindex);
NLA_PUT(msg, IEEE802154_ATTR_HW_ADDR, IEEE802154_ADDR_LEN,
dev->dev_addr);
if (addr->addr_type == IEEE802154_ADDR_LONG)
NLA_PUT(msg, IEEE802154_ATTR_SRC_HW_ADDR, IEEE802154_ADDR_LEN,
addr->hwaddr);
else
NLA_PUT_U16(msg, IEEE802154_ATTR_SRC_SHORT_ADDR,
addr->short_addr);
NLA_PUT_U8(msg, IEEE802154_ATTR_REASON, reason);
return ieee802154_nl_mcast(msg, ieee802154_coord_mcgrp.id);
nla_put_failure:
nlmsg_free(msg);
return -ENOBUFS;
}
EXPORT_SYMBOL(ieee802154_nl_disassoc_indic);
int ieee802154_nl_disassoc_confirm(struct net_device *dev, u8 status)
{
struct sk_buff *msg;
pr_debug("%s\n", __func__);
msg = ieee802154_nl_create(0, IEEE802154_DISASSOCIATE_CONF);
if (!msg)
return -ENOBUFS;
NLA_PUT_STRING(msg, IEEE802154_ATTR_DEV_NAME, dev->name);
NLA_PUT_U32(msg, IEEE802154_ATTR_DEV_INDEX, dev->ifindex);
NLA_PUT(msg, IEEE802154_ATTR_HW_ADDR, IEEE802154_ADDR_LEN,
dev->dev_addr);
NLA_PUT_U8(msg, IEEE802154_ATTR_STATUS, status);
return ieee802154_nl_mcast(msg, ieee802154_coord_mcgrp.id);
nla_put_failure:
nlmsg_free(msg);
return -ENOBUFS;
}
EXPORT_SYMBOL(ieee802154_nl_disassoc_confirm);
int ieee802154_nl_beacon_indic(struct net_device *dev,
u16 panid, u16 coord_addr)
{
struct sk_buff *msg;
pr_debug("%s\n", __func__);
msg = ieee802154_nl_create(0, IEEE802154_BEACON_NOTIFY_INDIC);
if (!msg)
return -ENOBUFS;
NLA_PUT_STRING(msg, IEEE802154_ATTR_DEV_NAME, dev->name);
NLA_PUT_U32(msg, IEEE802154_ATTR_DEV_INDEX, dev->ifindex);
NLA_PUT(msg, IEEE802154_ATTR_HW_ADDR, IEEE802154_ADDR_LEN,
dev->dev_addr);
NLA_PUT_U16(msg, IEEE802154_ATTR_COORD_SHORT_ADDR, coord_addr);
NLA_PUT_U16(msg, IEEE802154_ATTR_COORD_PAN_ID, panid);
return ieee802154_nl_mcast(msg, ieee802154_coord_mcgrp.id);
nla_put_failure:
nlmsg_free(msg);
return -ENOBUFS;
}
EXPORT_SYMBOL(ieee802154_nl_beacon_indic);
int ieee802154_nl_scan_confirm(struct net_device *dev,
u8 status, u8 scan_type, u32 unscanned, u8 page,
u8 *edl/* , struct list_head *pan_desc_list */)
{
struct sk_buff *msg;
pr_debug("%s\n", __func__);
msg = ieee802154_nl_create(0, IEEE802154_SCAN_CONF);
if (!msg)
return -ENOBUFS;
NLA_PUT_STRING(msg, IEEE802154_ATTR_DEV_NAME, dev->name);
NLA_PUT_U32(msg, IEEE802154_ATTR_DEV_INDEX, dev->ifindex);
NLA_PUT(msg, IEEE802154_ATTR_HW_ADDR, IEEE802154_ADDR_LEN,
dev->dev_addr);
NLA_PUT_U8(msg, IEEE802154_ATTR_STATUS, status);
NLA_PUT_U8(msg, IEEE802154_ATTR_SCAN_TYPE, scan_type);
NLA_PUT_U32(msg, IEEE802154_ATTR_CHANNELS, unscanned);
NLA_PUT_U8(msg, IEEE802154_ATTR_PAGE, page);
if (edl)
NLA_PUT(msg, IEEE802154_ATTR_ED_LIST, 27, edl);
return ieee802154_nl_mcast(msg, ieee802154_coord_mcgrp.id);
nla_put_failure:
nlmsg_free(msg);
return -ENOBUFS;
}
EXPORT_SYMBOL(ieee802154_nl_scan_confirm);
int ieee802154_nl_start_confirm(struct net_device *dev, u8 status)
{
struct sk_buff *msg;
pr_debug("%s\n", __func__);
msg = ieee802154_nl_create(0, IEEE802154_START_CONF);
if (!msg)
return -ENOBUFS;
NLA_PUT_STRING(msg, IEEE802154_ATTR_DEV_NAME, dev->name);
NLA_PUT_U32(msg, IEEE802154_ATTR_DEV_INDEX, dev->ifindex);
NLA_PUT(msg, IEEE802154_ATTR_HW_ADDR, IEEE802154_ADDR_LEN,
dev->dev_addr);
NLA_PUT_U8(msg, IEEE802154_ATTR_STATUS, status);
return ieee802154_nl_mcast(msg, ieee802154_coord_mcgrp.id);
nla_put_failure:
nlmsg_free(msg);
return -ENOBUFS;
}
EXPORT_SYMBOL(ieee802154_nl_start_confirm);
static int ieee802154_nl_fill_iface(struct sk_buff *msg, u32 pid,
u32 seq, int flags, struct net_device *dev)
{
void *hdr;
struct wpan_phy *phy;
pr_debug("%s\n", __func__);
hdr = genlmsg_put(msg, 0, seq, &nl802154_family, flags,
IEEE802154_LIST_IFACE);
if (!hdr)
goto out;
phy = ieee802154_mlme_ops(dev)->get_phy(dev);
BUG_ON(!phy);
NLA_PUT_STRING(msg, IEEE802154_ATTR_DEV_NAME, dev->name);
NLA_PUT_STRING(msg, IEEE802154_ATTR_PHY_NAME, wpan_phy_name(phy));
NLA_PUT_U32(msg, IEEE802154_ATTR_DEV_INDEX, dev->ifindex);
NLA_PUT(msg, IEEE802154_ATTR_HW_ADDR, IEEE802154_ADDR_LEN,
dev->dev_addr);
NLA_PUT_U16(msg, IEEE802154_ATTR_SHORT_ADDR,
ieee802154_mlme_ops(dev)->get_short_addr(dev));
NLA_PUT_U16(msg, IEEE802154_ATTR_PAN_ID,
ieee802154_mlme_ops(dev)->get_pan_id(dev));
wpan_phy_put(phy);
return genlmsg_end(msg, hdr);
nla_put_failure:
wpan_phy_put(phy);
genlmsg_cancel(msg, hdr);
out:
return -EMSGSIZE;
}
/* Requests from userspace */
static struct net_device *ieee802154_nl_get_dev(struct genl_info *info)
{
struct net_device *dev;
if (info->attrs[IEEE802154_ATTR_DEV_NAME]) {
char name[IFNAMSIZ + 1];
nla_strlcpy(name, info->attrs[IEEE802154_ATTR_DEV_NAME],
sizeof(name));
dev = dev_get_by_name(&init_net, name);
} else if (info->attrs[IEEE802154_ATTR_DEV_INDEX])
dev = dev_get_by_index(&init_net,
nla_get_u32(info->attrs[IEEE802154_ATTR_DEV_INDEX]));
else
return NULL;
if (!dev)
return NULL;
if (dev->type != ARPHRD_IEEE802154) {
dev_put(dev);
return NULL;
}
return dev;
}
static int ieee802154_associate_req(struct sk_buff *skb,
struct genl_info *info)
{
struct net_device *dev;
struct ieee802154_addr addr;
u8 page;
int ret = -EINVAL;
if (!info->attrs[IEEE802154_ATTR_CHANNEL] ||
!info->attrs[IEEE802154_ATTR_COORD_PAN_ID] ||
(!info->attrs[IEEE802154_ATTR_COORD_HW_ADDR] &&
!info->attrs[IEEE802154_ATTR_COORD_SHORT_ADDR]) ||
!info->attrs[IEEE802154_ATTR_CAPABILITY])
return -EINVAL;
dev = ieee802154_nl_get_dev(info);
if (!dev)
return -ENODEV;
if (info->attrs[IEEE802154_ATTR_COORD_HW_ADDR]) {
addr.addr_type = IEEE802154_ADDR_LONG;
nla_memcpy(addr.hwaddr,
info->attrs[IEEE802154_ATTR_COORD_HW_ADDR],
IEEE802154_ADDR_LEN);
} else {
addr.addr_type = IEEE802154_ADDR_SHORT;
addr.short_addr = nla_get_u16(
info->attrs[IEEE802154_ATTR_COORD_SHORT_ADDR]);
}
addr.pan_id = nla_get_u16(info->attrs[IEEE802154_ATTR_COORD_PAN_ID]);
if (info->attrs[IEEE802154_ATTR_PAGE])
page = nla_get_u8(info->attrs[IEEE802154_ATTR_PAGE]);
else
page = 0;
ret = ieee802154_mlme_ops(dev)->assoc_req(dev, &addr,
nla_get_u8(info->attrs[IEEE802154_ATTR_CHANNEL]),
page,
nla_get_u8(info->attrs[IEEE802154_ATTR_CAPABILITY]));
dev_put(dev);
return ret;
}
static int ieee802154_associate_resp(struct sk_buff *skb,
struct genl_info *info)
{
struct net_device *dev;
struct ieee802154_addr addr;
int ret = -EINVAL;
if (!info->attrs[IEEE802154_ATTR_STATUS] ||
!info->attrs[IEEE802154_ATTR_DEST_HW_ADDR] ||
!info->attrs[IEEE802154_ATTR_DEST_SHORT_ADDR])
return -EINVAL;
dev = ieee802154_nl_get_dev(info);
if (!dev)
return -ENODEV;
addr.addr_type = IEEE802154_ADDR_LONG;
nla_memcpy(addr.hwaddr, info->attrs[IEEE802154_ATTR_DEST_HW_ADDR],
IEEE802154_ADDR_LEN);
addr.pan_id = ieee802154_mlme_ops(dev)->get_pan_id(dev);
ret = ieee802154_mlme_ops(dev)->assoc_resp(dev, &addr,
nla_get_u16(info->attrs[IEEE802154_ATTR_DEST_SHORT_ADDR]),
nla_get_u8(info->attrs[IEEE802154_ATTR_STATUS]));
dev_put(dev);
return ret;
}
static int ieee802154_disassociate_req(struct sk_buff *skb,
struct genl_info *info)
{
struct net_device *dev;
struct ieee802154_addr addr;
int ret = -EINVAL;
if ((!info->attrs[IEEE802154_ATTR_DEST_HW_ADDR] &&
!info->attrs[IEEE802154_ATTR_DEST_SHORT_ADDR]) ||
!info->attrs[IEEE802154_ATTR_REASON])
return -EINVAL;
dev = ieee802154_nl_get_dev(info);
if (!dev)
return -ENODEV;
if (info->attrs[IEEE802154_ATTR_DEST_HW_ADDR]) {
addr.addr_type = IEEE802154_ADDR_LONG;
nla_memcpy(addr.hwaddr,
info->attrs[IEEE802154_ATTR_DEST_HW_ADDR],
IEEE802154_ADDR_LEN);
} else {
addr.addr_type = IEEE802154_ADDR_SHORT;
addr.short_addr = nla_get_u16(
info->attrs[IEEE802154_ATTR_DEST_SHORT_ADDR]);
}
addr.pan_id = ieee802154_mlme_ops(dev)->get_pan_id(dev);
ret = ieee802154_mlme_ops(dev)->disassoc_req(dev, &addr,
nla_get_u8(info->attrs[IEEE802154_ATTR_REASON]));
dev_put(dev);
return ret;
}
/*
* PANid, channel, beacon_order = 15, superframe_order = 15,
* PAN_coordinator, battery_life_extension = 0,
* coord_realignment = 0, security_enable = 0
*/
static int ieee802154_start_req(struct sk_buff *skb, struct genl_info *info)
{
struct net_device *dev;
struct ieee802154_addr addr;
u8 channel, bcn_ord, sf_ord;
u8 page;
int pan_coord, blx, coord_realign;
int ret;
if (!info->attrs[IEEE802154_ATTR_COORD_PAN_ID] ||
!info->attrs[IEEE802154_ATTR_COORD_SHORT_ADDR] ||
!info->attrs[IEEE802154_ATTR_CHANNEL] ||
!info->attrs[IEEE802154_ATTR_BCN_ORD] ||
!info->attrs[IEEE802154_ATTR_SF_ORD] ||
!info->attrs[IEEE802154_ATTR_PAN_COORD] ||
!info->attrs[IEEE802154_ATTR_BAT_EXT] ||
!info->attrs[IEEE802154_ATTR_COORD_REALIGN]
)
return -EINVAL;
dev = ieee802154_nl_get_dev(info);
if (!dev)
return -ENODEV;
addr.addr_type = IEEE802154_ADDR_SHORT;
addr.short_addr = nla_get_u16(
info->attrs[IEEE802154_ATTR_COORD_SHORT_ADDR]);
addr.pan_id = nla_get_u16(info->attrs[IEEE802154_ATTR_COORD_PAN_ID]);
channel = nla_get_u8(info->attrs[IEEE802154_ATTR_CHANNEL]);
bcn_ord = nla_get_u8(info->attrs[IEEE802154_ATTR_BCN_ORD]);
sf_ord = nla_get_u8(info->attrs[IEEE802154_ATTR_SF_ORD]);
pan_coord = nla_get_u8(info->attrs[IEEE802154_ATTR_PAN_COORD]);
blx = nla_get_u8(info->attrs[IEEE802154_ATTR_BAT_EXT]);
coord_realign = nla_get_u8(info->attrs[IEEE802154_ATTR_COORD_REALIGN]);
if (info->attrs[IEEE802154_ATTR_PAGE])
page = nla_get_u8(info->attrs[IEEE802154_ATTR_PAGE]);
else
page = 0;
if (addr.short_addr == IEEE802154_ADDR_BROADCAST) {
ieee802154_nl_start_confirm(dev, IEEE802154_NO_SHORT_ADDRESS);
dev_put(dev);
return -EINVAL;
}
ret = ieee802154_mlme_ops(dev)->start_req(dev, &addr, channel, page,
bcn_ord, sf_ord, pan_coord, blx, coord_realign);
dev_put(dev);
return ret;
}
static int ieee802154_scan_req(struct sk_buff *skb, struct genl_info *info)
{
struct net_device *dev;
int ret;
u8 type;
u32 channels;
u8 duration;
u8 page;
if (!info->attrs[IEEE802154_ATTR_SCAN_TYPE] ||
!info->attrs[IEEE802154_ATTR_CHANNELS] ||
!info->attrs[IEEE802154_ATTR_DURATION])
return -EINVAL;
dev = ieee802154_nl_get_dev(info);
if (!dev)
return -ENODEV;
type = nla_get_u8(info->attrs[IEEE802154_ATTR_SCAN_TYPE]);
channels = nla_get_u32(info->attrs[IEEE802154_ATTR_CHANNELS]);
duration = nla_get_u8(info->attrs[IEEE802154_ATTR_DURATION]);
if (info->attrs[IEEE802154_ATTR_PAGE])
page = nla_get_u8(info->attrs[IEEE802154_ATTR_PAGE]);
else
page = 0;
ret = ieee802154_mlme_ops(dev)->scan_req(dev, type, channels, page,
duration);
dev_put(dev);
return ret;
}
static int ieee802154_list_iface(struct sk_buff *skb,
struct genl_info *info)
{
/* Request for interface name, index, type, IEEE address,
PAN Id, short address */
struct sk_buff *msg;
struct net_device *dev = NULL;
int rc = -ENOBUFS;
pr_debug("%s\n", __func__);
dev = ieee802154_nl_get_dev(info);
if (!dev)
return -ENODEV;
msg = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
if (!msg)
goto out_dev;
rc = ieee802154_nl_fill_iface(msg, info->snd_pid, info->snd_seq,
0, dev);
if (rc < 0)
goto out_free;
dev_put(dev);
return genlmsg_reply(msg, info);
out_free:
nlmsg_free(msg);
out_dev:
dev_put(dev);
return rc;
}
static int ieee802154_dump_iface(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct net_device *dev;
int idx;
int s_idx = cb->args[0];
pr_debug("%s\n", __func__);
idx = 0;
for_each_netdev(net, dev) {
if (idx < s_idx || (dev->type != ARPHRD_IEEE802154))
goto cont;
if (ieee802154_nl_fill_iface(skb, NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq, NLM_F_MULTI, dev) < 0)
break;
cont:
idx++;
}
cb->args[0] = idx;
return skb->len;
}
static struct genl_ops ieee802154_coordinator_ops[] = {
IEEE802154_OP(IEEE802154_ASSOCIATE_REQ, ieee802154_associate_req),
IEEE802154_OP(IEEE802154_ASSOCIATE_RESP, ieee802154_associate_resp),
IEEE802154_OP(IEEE802154_DISASSOCIATE_REQ, ieee802154_disassociate_req),
IEEE802154_OP(IEEE802154_SCAN_REQ, ieee802154_scan_req),
IEEE802154_OP(IEEE802154_START_REQ, ieee802154_start_req),
IEEE802154_DUMP(IEEE802154_LIST_IFACE, ieee802154_list_iface,
ieee802154_dump_iface),
};
/*
* No need to unregister as family unregistration will do it.
*/
int nl802154_mac_register(void)
{
int i;
int rc;
rc = genl_register_mc_group(&nl802154_family,
&ieee802154_coord_mcgrp);
if (rc)
return rc;
rc = genl_register_mc_group(&nl802154_family,
&ieee802154_beacon_mcgrp);
if (rc)
return rc;
for (i = 0; i < ARRAY_SIZE(ieee802154_coordinator_ops); i++) {
rc = genl_register_ops(&nl802154_family,
&ieee802154_coordinator_ops[i]);
if (rc)
return rc;
}
return 0;
}
| gpl-2.0 |
ShivangDave/android_kernel_sony_msm7x27a-Mesona | arch/blackfin/mach-bf561/boards/ezkit.c | 4552 | 15346 | /*
* Copyright 2004-2009 Analog Devices Inc.
* 2005 National ICT Australia (NICTA)
* Aidan Williams <aidan@nicta.com.au>
*
* Licensed under the GPL-2 or later.
*/
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/spi/spi.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <asm/dma.h>
#include <asm/bfin5xx_spi.h>
#include <asm/portmux.h>
#include <asm/dpmc.h>
/*
* Name the Board for the /proc/cpuinfo
*/
const char bfin_board_name[] = "ADI BF561-EZKIT";
#if defined(CONFIG_USB_ISP1760_HCD) || defined(CONFIG_USB_ISP1760_HCD_MODULE)
#include <linux/usb/isp1760.h>
static struct resource bfin_isp1760_resources[] = {
[0] = {
.start = 0x2C0F0000,
.end = 0x203C0000 + 0xfffff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_PF10,
.end = IRQ_PF10,
.flags = IORESOURCE_IRQ,
},
};
static struct isp1760_platform_data isp1760_priv = {
.is_isp1761 = 0,
.bus_width_16 = 1,
.port1_otg = 0,
.analog_oc = 0,
.dack_polarity_high = 0,
.dreq_polarity_high = 0,
};
static struct platform_device bfin_isp1760_device = {
.name = "isp1760",
.id = 0,
.dev = {
.platform_data = &isp1760_priv,
},
.num_resources = ARRAY_SIZE(bfin_isp1760_resources),
.resource = bfin_isp1760_resources,
};
#endif
#if defined(CONFIG_USB_ISP1362_HCD) || defined(CONFIG_USB_ISP1362_HCD_MODULE)
#include <linux/usb/isp1362.h>
static struct resource isp1362_hcd_resources[] = {
{
.start = 0x2c060000,
.end = 0x2c060000,
.flags = IORESOURCE_MEM,
}, {
.start = 0x2c060004,
.end = 0x2c060004,
.flags = IORESOURCE_MEM,
}, {
.start = IRQ_PF8,
.end = IRQ_PF8,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_LOWEDGE,
},
};
static struct isp1362_platform_data isp1362_priv = {
.sel15Kres = 1,
.clknotstop = 0,
.oc_enable = 0,
.int_act_high = 0,
.int_edge_triggered = 0,
.remote_wakeup_connected = 0,
.no_power_switching = 1,
.power_switching_mode = 0,
};
static struct platform_device isp1362_hcd_device = {
.name = "isp1362-hcd",
.id = 0,
.dev = {
.platform_data = &isp1362_priv,
},
.num_resources = ARRAY_SIZE(isp1362_hcd_resources),
.resource = isp1362_hcd_resources,
};
#endif
#if defined(CONFIG_USB_NET2272) || defined(CONFIG_USB_NET2272_MODULE)
static struct resource net2272_bfin_resources[] = {
{
.start = 0x2C000000,
.end = 0x2C000000 + 0x7F,
.flags = IORESOURCE_MEM,
}, {
.start = 1,
.flags = IORESOURCE_BUS,
}, {
.start = IRQ_PF10,
.end = IRQ_PF10,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_LOWLEVEL,
},
};
static struct platform_device net2272_bfin_device = {
.name = "net2272",
.id = -1,
.num_resources = ARRAY_SIZE(net2272_bfin_resources),
.resource = net2272_bfin_resources,
};
#endif
/*
* USB-LAN EzExtender board
* Driver needs to know address, irq and flag pin.
*/
#if defined(CONFIG_SMC91X) || defined(CONFIG_SMC91X_MODULE)
#include <linux/smc91x.h>
static struct smc91x_platdata smc91x_info = {
.flags = SMC91X_USE_32BIT | SMC91X_NOWAIT,
.leda = RPC_LED_100_10,
.ledb = RPC_LED_TX_RX,
};
static struct resource smc91x_resources[] = {
{
.name = "smc91x-regs",
.start = 0x2C010300,
.end = 0x2C010300 + 16,
.flags = IORESOURCE_MEM,
}, {
.start = IRQ_PF9,
.end = IRQ_PF9,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL,
},
};
static struct platform_device smc91x_device = {
.name = "smc91x",
.id = 0,
.num_resources = ARRAY_SIZE(smc91x_resources),
.resource = smc91x_resources,
.dev = {
.platform_data = &smc91x_info,
},
};
#endif
#if defined(CONFIG_SERIAL_BFIN) || defined(CONFIG_SERIAL_BFIN_MODULE)
#ifdef CONFIG_SERIAL_BFIN_UART0
static struct resource bfin_uart0_resources[] = {
{
.start = BFIN_UART_THR,
.end = BFIN_UART_GCTL+2,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART_TX,
.end = IRQ_UART_TX,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_UART_RX,
.end = IRQ_UART_RX,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_UART_ERROR,
.end = IRQ_UART_ERROR,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART_TX,
.end = CH_UART_TX,
.flags = IORESOURCE_DMA,
},
{
.start = CH_UART_RX,
.end = CH_UART_RX,
.flags = IORESOURCE_DMA,
},
};
static unsigned short bfin_uart0_peripherals[] = {
P_UART0_TX, P_UART0_RX, 0
};
static struct platform_device bfin_uart0_device = {
.name = "bfin-uart",
.id = 0,
.num_resources = ARRAY_SIZE(bfin_uart0_resources),
.resource = bfin_uart0_resources,
.dev = {
.platform_data = &bfin_uart0_peripherals, /* Passed to driver */
},
};
#endif
#endif
#if defined(CONFIG_BFIN_SIR) || defined(CONFIG_BFIN_SIR_MODULE)
#ifdef CONFIG_BFIN_SIR0
static struct resource bfin_sir0_resources[] = {
{
.start = 0xFFC00400,
.end = 0xFFC004FF,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART0_RX,
.end = IRQ_UART0_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART0_RX,
.end = CH_UART0_RX+1,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device bfin_sir0_device = {
.name = "bfin_sir",
.id = 0,
.num_resources = ARRAY_SIZE(bfin_sir0_resources),
.resource = bfin_sir0_resources,
};
#endif
#endif
#if defined(CONFIG_MTD_PHYSMAP) || defined(CONFIG_MTD_PHYSMAP_MODULE)
static struct mtd_partition ezkit_partitions[] = {
{
.name = "bootloader(nor)",
.size = 0x40000,
.offset = 0,
}, {
.name = "linux kernel(nor)",
.size = 0x1C0000,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "file system(nor)",
.size = 0x800000 - 0x40000 - 0x1C0000 - 0x2000 * 8,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "config(nor)",
.size = 0x2000 * 7,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "u-boot env(nor)",
.size = 0x2000,
.offset = MTDPART_OFS_APPEND,
}
};
static struct physmap_flash_data ezkit_flash_data = {
.width = 2,
.parts = ezkit_partitions,
.nr_parts = ARRAY_SIZE(ezkit_partitions),
};
static struct resource ezkit_flash_resource = {
.start = 0x20000000,
.end = 0x207fffff,
.flags = IORESOURCE_MEM,
};
static struct platform_device ezkit_flash_device = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &ezkit_flash_data,
},
.num_resources = 1,
.resource = &ezkit_flash_resource,
};
#endif
#if defined(CONFIG_SPI_BFIN5XX) || defined(CONFIG_SPI_BFIN5XX_MODULE)
/* SPI (0) */
static struct resource bfin_spi0_resource[] = {
[0] = {
.start = SPI0_REGBASE,
.end = SPI0_REGBASE + 0xFF,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = CH_SPI,
.end = CH_SPI,
.flags = IORESOURCE_DMA,
},
[2] = {
.start = IRQ_SPI,
.end = IRQ_SPI,
.flags = IORESOURCE_IRQ,
}
};
/* SPI controller data */
static struct bfin5xx_spi_master bfin_spi0_info = {
.num_chipselect = 8,
.enable_dma = 1, /* master has the ability to do dma transfer */
.pin_req = {P_SPI0_SCK, P_SPI0_MISO, P_SPI0_MOSI, 0},
};
static struct platform_device bfin_spi0_device = {
.name = "bfin-spi",
.id = 0, /* Bus number */
.num_resources = ARRAY_SIZE(bfin_spi0_resource),
.resource = bfin_spi0_resource,
.dev = {
.platform_data = &bfin_spi0_info, /* Passed to driver */
},
};
#endif
static struct spi_board_info bfin_spi_board_info[] __initdata = {
#if defined(CONFIG_SND_BF5XX_SOC_AD183X) \
|| defined(CONFIG_SND_BF5XX_SOC_AD183X_MODULE)
{
.modalias = "ad183x",
.max_speed_hz = 3125000, /* max spi clock (SCK) speed in HZ */
.bus_num = 0,
.chip_select = 4,
.platform_data = "ad1836", /* only includes chip name for the moment */
.mode = SPI_MODE_3,
},
#endif
#if defined(CONFIG_SPI_SPIDEV) || defined(CONFIG_SPI_SPIDEV_MODULE)
{
.modalias = "spidev",
.max_speed_hz = 3125000, /* max spi clock (SCK) speed in HZ */
.bus_num = 0,
.chip_select = 1,
},
#endif
};
#if defined(CONFIG_KEYBOARD_GPIO) || defined(CONFIG_KEYBOARD_GPIO_MODULE)
#include <linux/input.h>
#include <linux/gpio_keys.h>
static struct gpio_keys_button bfin_gpio_keys_table[] = {
{BTN_0, GPIO_PF5, 1, "gpio-keys: BTN0"},
{BTN_1, GPIO_PF6, 1, "gpio-keys: BTN1"},
{BTN_2, GPIO_PF7, 1, "gpio-keys: BTN2"},
{BTN_3, GPIO_PF8, 1, "gpio-keys: BTN3"},
};
static struct gpio_keys_platform_data bfin_gpio_keys_data = {
.buttons = bfin_gpio_keys_table,
.nbuttons = ARRAY_SIZE(bfin_gpio_keys_table),
};
static struct platform_device bfin_device_gpiokeys = {
.name = "gpio-keys",
.dev = {
.platform_data = &bfin_gpio_keys_data,
},
};
#endif
#if defined(CONFIG_I2C_GPIO) || defined(CONFIG_I2C_GPIO_MODULE)
#include <linux/i2c-gpio.h>
static struct i2c_gpio_platform_data i2c_gpio_data = {
.sda_pin = GPIO_PF1,
.scl_pin = GPIO_PF0,
.sda_is_open_drain = 0,
.scl_is_open_drain = 0,
.udelay = 10,
};
static struct platform_device i2c_gpio_device = {
.name = "i2c-gpio",
.id = 0,
.dev = {
.platform_data = &i2c_gpio_data,
},
};
#endif
static const unsigned int cclk_vlev_datasheet[] =
{
VRPAIR(VLEV_085, 250000000),
VRPAIR(VLEV_090, 300000000),
VRPAIR(VLEV_095, 313000000),
VRPAIR(VLEV_100, 350000000),
VRPAIR(VLEV_105, 400000000),
VRPAIR(VLEV_110, 444000000),
VRPAIR(VLEV_115, 450000000),
VRPAIR(VLEV_120, 475000000),
VRPAIR(VLEV_125, 500000000),
VRPAIR(VLEV_130, 600000000),
};
static struct bfin_dpmc_platform_data bfin_dmpc_vreg_data = {
.tuple_tab = cclk_vlev_datasheet,
.tabsize = ARRAY_SIZE(cclk_vlev_datasheet),
.vr_settling_time = 25 /* us */,
};
static struct platform_device bfin_dpmc = {
.name = "bfin dpmc",
.dev = {
.platform_data = &bfin_dmpc_vreg_data,
},
};
#if defined(CONFIG_VIDEO_BLACKFIN_CAPTURE) \
|| defined(CONFIG_VIDEO_BLACKFIN_CAPTURE_MODULE)
#include <linux/videodev2.h>
#include <media/blackfin/bfin_capture.h>
#include <media/blackfin/ppi.h>
static const unsigned short ppi_req[] = {
P_PPI0_D0, P_PPI0_D1, P_PPI0_D2, P_PPI0_D3,
P_PPI0_D4, P_PPI0_D5, P_PPI0_D6, P_PPI0_D7,
P_PPI0_CLK, P_PPI0_FS1, P_PPI0_FS2,
0,
};
static const struct ppi_info ppi_info = {
.type = PPI_TYPE_PPI,
.dma_ch = CH_PPI0,
.irq_err = IRQ_PPI1_ERROR,
.base = (void __iomem *)PPI0_CONTROL,
.pin_req = ppi_req,
};
#if defined(CONFIG_VIDEO_ADV7183) \
|| defined(CONFIG_VIDEO_ADV7183_MODULE)
#include <media/adv7183.h>
static struct v4l2_input adv7183_inputs[] = {
{
.index = 0,
.name = "Composite",
.type = V4L2_INPUT_TYPE_CAMERA,
.std = V4L2_STD_ALL,
},
{
.index = 1,
.name = "S-Video",
.type = V4L2_INPUT_TYPE_CAMERA,
.std = V4L2_STD_ALL,
},
{
.index = 2,
.name = "Component",
.type = V4L2_INPUT_TYPE_CAMERA,
.std = V4L2_STD_ALL,
},
};
static struct bcap_route adv7183_routes[] = {
{
.input = ADV7183_COMPOSITE4,
.output = ADV7183_8BIT_OUT,
},
{
.input = ADV7183_SVIDEO0,
.output = ADV7183_8BIT_OUT,
},
{
.input = ADV7183_COMPONENT0,
.output = ADV7183_8BIT_OUT,
},
};
static const unsigned adv7183_gpio[] = {
GPIO_PF13, /* reset pin */
GPIO_PF2, /* output enable pin */
};
static struct bfin_capture_config bfin_capture_data = {
.card_name = "BF561",
.inputs = adv7183_inputs,
.num_inputs = ARRAY_SIZE(adv7183_inputs),
.routes = adv7183_routes,
.i2c_adapter_id = 0,
.board_info = {
.type = "adv7183",
.addr = 0x20,
.platform_data = (void *)adv7183_gpio,
},
.ppi_info = &ppi_info,
.ppi_control = (PACK_EN | DLEN_8 | DMA32 | FLD_SEL),
};
#endif
static struct platform_device bfin_capture_device = {
.name = "bfin_capture",
.dev = {
.platform_data = &bfin_capture_data,
},
};
#endif
#if defined(CONFIG_SND_BF5XX_I2S) || defined(CONFIG_SND_BF5XX_I2S_MODULE)
static struct platform_device bfin_i2s = {
.name = "bfin-i2s",
.id = CONFIG_SND_BF5XX_SPORT_NUM,
/* TODO: add platform data here */
};
#endif
#if defined(CONFIG_SND_BF5XX_TDM) || defined(CONFIG_SND_BF5XX_TDM_MODULE)
static struct platform_device bfin_tdm = {
.name = "bfin-tdm",
.id = CONFIG_SND_BF5XX_SPORT_NUM,
/* TODO: add platform data here */
};
#endif
#if defined(CONFIG_SND_BF5XX_AC97) || defined(CONFIG_SND_BF5XX_AC97_MODULE)
static struct platform_device bfin_ac97 = {
.name = "bfin-ac97",
.id = CONFIG_SND_BF5XX_SPORT_NUM,
/* TODO: add platform data here */
};
#endif
static struct platform_device *ezkit_devices[] __initdata = {
&bfin_dpmc,
#if defined(CONFIG_SMC91X) || defined(CONFIG_SMC91X_MODULE)
&smc91x_device,
#endif
#if defined(CONFIG_USB_NET2272) || defined(CONFIG_USB_NET2272_MODULE)
&net2272_bfin_device,
#endif
#if defined(CONFIG_USB_ISP1760_HCD) || defined(CONFIG_USB_ISP1760_HCD_MODULE)
&bfin_isp1760_device,
#endif
#if defined(CONFIG_SPI_BFIN5XX) || defined(CONFIG_SPI_BFIN5XX_MODULE)
&bfin_spi0_device,
#endif
#if defined(CONFIG_SERIAL_BFIN) || defined(CONFIG_SERIAL_BFIN_MODULE)
#ifdef CONFIG_SERIAL_BFIN_UART0
&bfin_uart0_device,
#endif
#endif
#if defined(CONFIG_BFIN_SIR) || defined(CONFIG_BFIN_SIR_MODULE)
#ifdef CONFIG_BFIN_SIR0
&bfin_sir0_device,
#endif
#endif
#if defined(CONFIG_KEYBOARD_GPIO) || defined(CONFIG_KEYBOARD_GPIO_MODULE)
&bfin_device_gpiokeys,
#endif
#if defined(CONFIG_I2C_GPIO) || defined(CONFIG_I2C_GPIO_MODULE)
&i2c_gpio_device,
#endif
#if defined(CONFIG_USB_ISP1362_HCD) || defined(CONFIG_USB_ISP1362_HCD_MODULE)
&isp1362_hcd_device,
#endif
#if defined(CONFIG_MTD_PHYSMAP) || defined(CONFIG_MTD_PHYSMAP_MODULE)
&ezkit_flash_device,
#endif
#if defined(CONFIG_VIDEO_BLACKFIN_CAPTURE) \
|| defined(CONFIG_VIDEO_BLACKFIN_CAPTURE_MODULE)
&bfin_capture_device,
#endif
#if defined(CONFIG_SND_BF5XX_I2S) || defined(CONFIG_SND_BF5XX_I2S_MODULE)
&bfin_i2s,
#endif
#if defined(CONFIG_SND_BF5XX_TDM) || defined(CONFIG_SND_BF5XX_TDM_MODULE)
&bfin_tdm,
#endif
#if defined(CONFIG_SND_BF5XX_AC97) || defined(CONFIG_SND_BF5XX_AC97_MODULE)
&bfin_ac97,
#endif
};
static int __init net2272_init(void)
{
#if defined(CONFIG_USB_NET2272) || defined(CONFIG_USB_NET2272_MODULE)
int ret;
ret = gpio_request(GPIO_PF11, "net2272");
if (ret)
return ret;
/* Reset the USB chip */
gpio_direction_output(GPIO_PF11, 0);
mdelay(2);
gpio_set_value(GPIO_PF11, 1);
#endif
return 0;
}
static int __init ezkit_init(void)
{
int ret;
printk(KERN_INFO "%s(): registering device resources\n", __func__);
ret = platform_add_devices(ezkit_devices, ARRAY_SIZE(ezkit_devices));
if (ret < 0)
return ret;
#if defined(CONFIG_SMC91X) || defined(CONFIG_SMC91X_MODULE)
bfin_write_FIO0_DIR(bfin_read_FIO0_DIR() | (1 << 12));
SSYNC();
#endif
#if defined(CONFIG_SND_BF5XX_SOC_AD183X) || defined(CONFIG_SND_BF5XX_SOC_AD183X_MODULE)
bfin_write_FIO0_DIR(bfin_read_FIO0_DIR() | (1 << 15));
bfin_write_FIO0_FLAG_S(1 << 15);
SSYNC();
/*
* This initialization lasts for approximately 4500 MCLKs.
* MCLK = 12.288MHz
*/
udelay(400);
#endif
if (net2272_init())
pr_warning("unable to configure net2272; it probably won't work\n");
spi_register_board_info(bfin_spi_board_info, ARRAY_SIZE(bfin_spi_board_info));
return 0;
}
arch_initcall(ezkit_init);
static struct platform_device *ezkit_early_devices[] __initdata = {
#if defined(CONFIG_SERIAL_BFIN_CONSOLE) || defined(CONFIG_EARLY_PRINTK)
#ifdef CONFIG_SERIAL_BFIN_UART0
&bfin_uart0_device,
#endif
#endif
};
void __init native_machine_early_platform_add_devices(void)
{
printk(KERN_INFO "register early platform devices\n");
early_platform_add_devices(ezkit_early_devices,
ARRAY_SIZE(ezkit_early_devices));
}
| gpl-2.0 |
AOKP/kernel_sony_apq8064 | arch/arm/mach-integrator/integrator_ap.c | 4552 | 12259 | /*
* linux/arch/arm/mach-integrator/integrator_ap.c
*
* Copyright (C) 2000-2003 Deep Blue Solutions 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.
*
* 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/kernel.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/syscore_ops.h>
#include <linux/amba/bus.h>
#include <linux/amba/kmi.h>
#include <linux/clocksource.h>
#include <linux/clockchips.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/mtd/physmap.h>
#include <linux/clk.h>
#include <video/vga.h>
#include <mach/hardware.h>
#include <mach/platform.h>
#include <asm/hardware/arm_timer.h>
#include <asm/setup.h>
#include <asm/param.h> /* HZ */
#include <asm/mach-types.h>
#include <asm/sched_clock.h>
#include <mach/lm.h>
#include <mach/irqs.h>
#include <asm/mach/arch.h>
#include <asm/mach/irq.h>
#include <asm/mach/map.h>
#include <asm/mach/time.h>
#include <plat/fpga-irq.h>
#include "common.h"
/*
* All IO addresses are mapped onto VA 0xFFFx.xxxx, where x.xxxx
* is the (PA >> 12).
*
* Setup a VA for the Integrator interrupt controller (for header #0,
* just for now).
*/
#define VA_IC_BASE __io_address(INTEGRATOR_IC_BASE)
#define VA_SC_BASE __io_address(INTEGRATOR_SC_BASE)
#define VA_EBI_BASE __io_address(INTEGRATOR_EBI_BASE)
#define VA_CMIC_BASE __io_address(INTEGRATOR_HDR_IC)
/*
* Logical Physical
* e8000000 40000000 PCI memory PHYS_PCI_MEM_BASE (max 512M)
* ec000000 61000000 PCI config space PHYS_PCI_CONFIG_BASE (max 16M)
* ed000000 62000000 PCI V3 regs PHYS_PCI_V3_BASE (max 64k)
* ee000000 60000000 PCI IO PHYS_PCI_IO_BASE (max 16M)
* ef000000 Cache flush
* f1000000 10000000 Core module registers
* f1100000 11000000 System controller registers
* f1200000 12000000 EBI registers
* f1300000 13000000 Counter/Timer
* f1400000 14000000 Interrupt controller
* f1600000 16000000 UART 0
* f1700000 17000000 UART 1
* f1a00000 1a000000 Debug LEDs
* f1b00000 1b000000 GPIO
*/
static struct map_desc ap_io_desc[] __initdata = {
{
.virtual = IO_ADDRESS(INTEGRATOR_HDR_BASE),
.pfn = __phys_to_pfn(INTEGRATOR_HDR_BASE),
.length = SZ_4K,
.type = MT_DEVICE
}, {
.virtual = IO_ADDRESS(INTEGRATOR_SC_BASE),
.pfn = __phys_to_pfn(INTEGRATOR_SC_BASE),
.length = SZ_4K,
.type = MT_DEVICE
}, {
.virtual = IO_ADDRESS(INTEGRATOR_EBI_BASE),
.pfn = __phys_to_pfn(INTEGRATOR_EBI_BASE),
.length = SZ_4K,
.type = MT_DEVICE
}, {
.virtual = IO_ADDRESS(INTEGRATOR_CT_BASE),
.pfn = __phys_to_pfn(INTEGRATOR_CT_BASE),
.length = SZ_4K,
.type = MT_DEVICE
}, {
.virtual = IO_ADDRESS(INTEGRATOR_IC_BASE),
.pfn = __phys_to_pfn(INTEGRATOR_IC_BASE),
.length = SZ_4K,
.type = MT_DEVICE
}, {
.virtual = IO_ADDRESS(INTEGRATOR_UART0_BASE),
.pfn = __phys_to_pfn(INTEGRATOR_UART0_BASE),
.length = SZ_4K,
.type = MT_DEVICE
}, {
.virtual = IO_ADDRESS(INTEGRATOR_UART1_BASE),
.pfn = __phys_to_pfn(INTEGRATOR_UART1_BASE),
.length = SZ_4K,
.type = MT_DEVICE
}, {
.virtual = IO_ADDRESS(INTEGRATOR_DBG_BASE),
.pfn = __phys_to_pfn(INTEGRATOR_DBG_BASE),
.length = SZ_4K,
.type = MT_DEVICE
}, {
.virtual = IO_ADDRESS(INTEGRATOR_AP_GPIO_BASE),
.pfn = __phys_to_pfn(INTEGRATOR_AP_GPIO_BASE),
.length = SZ_4K,
.type = MT_DEVICE
}, {
.virtual = PCI_MEMORY_VADDR,
.pfn = __phys_to_pfn(PHYS_PCI_MEM_BASE),
.length = SZ_16M,
.type = MT_DEVICE
}, {
.virtual = PCI_CONFIG_VADDR,
.pfn = __phys_to_pfn(PHYS_PCI_CONFIG_BASE),
.length = SZ_16M,
.type = MT_DEVICE
}, {
.virtual = PCI_V3_VADDR,
.pfn = __phys_to_pfn(PHYS_PCI_V3_BASE),
.length = SZ_64K,
.type = MT_DEVICE
}, {
.virtual = PCI_IO_VADDR,
.pfn = __phys_to_pfn(PHYS_PCI_IO_BASE),
.length = SZ_64K,
.type = MT_DEVICE
}
};
static void __init ap_map_io(void)
{
iotable_init(ap_io_desc, ARRAY_SIZE(ap_io_desc));
vga_base = PCI_MEMORY_VADDR;
}
#define INTEGRATOR_SC_VALID_INT 0x003fffff
static struct fpga_irq_data sc_irq_data = {
.base = VA_IC_BASE,
.irq_start = 0,
.chip.name = "SC",
};
static void __init ap_init_irq(void)
{
/* Disable all interrupts initially. */
/* Do the core module ones */
writel(-1, VA_CMIC_BASE + IRQ_ENABLE_CLEAR);
/* do the header card stuff next */
writel(-1, VA_IC_BASE + IRQ_ENABLE_CLEAR);
writel(-1, VA_IC_BASE + FIQ_ENABLE_CLEAR);
fpga_irq_init(-1, INTEGRATOR_SC_VALID_INT, &sc_irq_data);
}
#ifdef CONFIG_PM
static unsigned long ic_irq_enable;
static int irq_suspend(void)
{
ic_irq_enable = readl(VA_IC_BASE + IRQ_ENABLE);
return 0;
}
static void irq_resume(void)
{
/* disable all irq sources */
writel(-1, VA_CMIC_BASE + IRQ_ENABLE_CLEAR);
writel(-1, VA_IC_BASE + IRQ_ENABLE_CLEAR);
writel(-1, VA_IC_BASE + FIQ_ENABLE_CLEAR);
writel(ic_irq_enable, VA_IC_BASE + IRQ_ENABLE_SET);
}
#else
#define irq_suspend NULL
#define irq_resume NULL
#endif
static struct syscore_ops irq_syscore_ops = {
.suspend = irq_suspend,
.resume = irq_resume,
};
static int __init irq_syscore_init(void)
{
register_syscore_ops(&irq_syscore_ops);
return 0;
}
device_initcall(irq_syscore_init);
/*
* Flash handling.
*/
#define SC_CTRLC (VA_SC_BASE + INTEGRATOR_SC_CTRLC_OFFSET)
#define SC_CTRLS (VA_SC_BASE + INTEGRATOR_SC_CTRLS_OFFSET)
#define EBI_CSR1 (VA_EBI_BASE + INTEGRATOR_EBI_CSR1_OFFSET)
#define EBI_LOCK (VA_EBI_BASE + INTEGRATOR_EBI_LOCK_OFFSET)
static int ap_flash_init(struct platform_device *dev)
{
u32 tmp;
writel(INTEGRATOR_SC_CTRL_nFLVPPEN | INTEGRATOR_SC_CTRL_nFLWP, SC_CTRLC);
tmp = readl(EBI_CSR1) | INTEGRATOR_EBI_WRITE_ENABLE;
writel(tmp, EBI_CSR1);
if (!(readl(EBI_CSR1) & INTEGRATOR_EBI_WRITE_ENABLE)) {
writel(0xa05f, EBI_LOCK);
writel(tmp, EBI_CSR1);
writel(0, EBI_LOCK);
}
return 0;
}
static void ap_flash_exit(struct platform_device *dev)
{
u32 tmp;
writel(INTEGRATOR_SC_CTRL_nFLVPPEN | INTEGRATOR_SC_CTRL_nFLWP, SC_CTRLC);
tmp = readl(EBI_CSR1) & ~INTEGRATOR_EBI_WRITE_ENABLE;
writel(tmp, EBI_CSR1);
if (readl(EBI_CSR1) & INTEGRATOR_EBI_WRITE_ENABLE) {
writel(0xa05f, EBI_LOCK);
writel(tmp, EBI_CSR1);
writel(0, EBI_LOCK);
}
}
static void ap_flash_set_vpp(struct platform_device *pdev, int on)
{
void __iomem *reg = on ? SC_CTRLS : SC_CTRLC;
writel(INTEGRATOR_SC_CTRL_nFLVPPEN, reg);
}
static struct physmap_flash_data ap_flash_data = {
.width = 4,
.init = ap_flash_init,
.exit = ap_flash_exit,
.set_vpp = ap_flash_set_vpp,
};
static struct resource cfi_flash_resource = {
.start = INTEGRATOR_FLASH_BASE,
.end = INTEGRATOR_FLASH_BASE + INTEGRATOR_FLASH_SIZE - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device cfi_flash_device = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &ap_flash_data,
},
.num_resources = 1,
.resource = &cfi_flash_resource,
};
static void __init ap_init(void)
{
unsigned long sc_dec;
int i;
platform_device_register(&cfi_flash_device);
sc_dec = readl(VA_SC_BASE + INTEGRATOR_SC_DEC_OFFSET);
for (i = 0; i < 4; i++) {
struct lm_device *lmdev;
if ((sc_dec & (16 << i)) == 0)
continue;
lmdev = kzalloc(sizeof(struct lm_device), GFP_KERNEL);
if (!lmdev)
continue;
lmdev->resource.start = 0xc0000000 + 0x10000000 * i;
lmdev->resource.end = lmdev->resource.start + 0x0fffffff;
lmdev->resource.flags = IORESOURCE_MEM;
lmdev->irq = IRQ_AP_EXPINT0 + i;
lmdev->id = i;
lm_device_register(lmdev);
}
}
/*
* Where is the timer (VA)?
*/
#define TIMER0_VA_BASE IO_ADDRESS(INTEGRATOR_TIMER0_BASE)
#define TIMER1_VA_BASE IO_ADDRESS(INTEGRATOR_TIMER1_BASE)
#define TIMER2_VA_BASE IO_ADDRESS(INTEGRATOR_TIMER2_BASE)
static unsigned long timer_reload;
static u32 notrace integrator_read_sched_clock(void)
{
return -readl((void __iomem *) TIMER2_VA_BASE + TIMER_VALUE);
}
static void integrator_clocksource_init(unsigned long inrate)
{
void __iomem *base = (void __iomem *)TIMER2_VA_BASE;
u32 ctrl = TIMER_CTRL_ENABLE | TIMER_CTRL_PERIODIC;
unsigned long rate = inrate;
if (rate >= 1500000) {
rate /= 16;
ctrl |= TIMER_CTRL_DIV16;
}
writel(0xffff, base + TIMER_LOAD);
writel(ctrl, base + TIMER_CTRL);
clocksource_mmio_init(base + TIMER_VALUE, "timer2",
rate, 200, 16, clocksource_mmio_readl_down);
setup_sched_clock(integrator_read_sched_clock, 16, rate);
}
static void __iomem * const clkevt_base = (void __iomem *)TIMER1_VA_BASE;
/*
* IRQ handler for the timer
*/
static irqreturn_t integrator_timer_interrupt(int irq, void *dev_id)
{
struct clock_event_device *evt = dev_id;
/* clear the interrupt */
writel(1, clkevt_base + TIMER_INTCLR);
evt->event_handler(evt);
return IRQ_HANDLED;
}
static void clkevt_set_mode(enum clock_event_mode mode, struct clock_event_device *evt)
{
u32 ctrl = readl(clkevt_base + TIMER_CTRL) & ~TIMER_CTRL_ENABLE;
/* Disable timer */
writel(ctrl, clkevt_base + TIMER_CTRL);
switch (mode) {
case CLOCK_EVT_MODE_PERIODIC:
/* Enable the timer and start the periodic tick */
writel(timer_reload, clkevt_base + TIMER_LOAD);
ctrl |= TIMER_CTRL_PERIODIC | TIMER_CTRL_ENABLE;
writel(ctrl, clkevt_base + TIMER_CTRL);
break;
case CLOCK_EVT_MODE_ONESHOT:
/* Leave the timer disabled, .set_next_event will enable it */
ctrl &= ~TIMER_CTRL_PERIODIC;
writel(ctrl, clkevt_base + TIMER_CTRL);
break;
case CLOCK_EVT_MODE_UNUSED:
case CLOCK_EVT_MODE_SHUTDOWN:
case CLOCK_EVT_MODE_RESUME:
default:
/* Just leave in disabled state */
break;
}
}
static int clkevt_set_next_event(unsigned long next, struct clock_event_device *evt)
{
unsigned long ctrl = readl(clkevt_base + TIMER_CTRL);
writel(ctrl & ~TIMER_CTRL_ENABLE, clkevt_base + TIMER_CTRL);
writel(next, clkevt_base + TIMER_LOAD);
writel(ctrl | TIMER_CTRL_ENABLE, clkevt_base + TIMER_CTRL);
return 0;
}
static struct clock_event_device integrator_clockevent = {
.name = "timer1",
.features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT,
.set_mode = clkevt_set_mode,
.set_next_event = clkevt_set_next_event,
.rating = 300,
};
static struct irqaction integrator_timer_irq = {
.name = "timer",
.flags = IRQF_DISABLED | IRQF_TIMER | IRQF_IRQPOLL,
.handler = integrator_timer_interrupt,
.dev_id = &integrator_clockevent,
};
static void integrator_clockevent_init(unsigned long inrate)
{
unsigned long rate = inrate;
unsigned int ctrl = 0;
/* Calculate and program a divisor */
if (rate > 0x100000 * HZ) {
rate /= 256;
ctrl |= TIMER_CTRL_DIV256;
} else if (rate > 0x10000 * HZ) {
rate /= 16;
ctrl |= TIMER_CTRL_DIV16;
}
timer_reload = rate / HZ;
writel(ctrl, clkevt_base + TIMER_CTRL);
setup_irq(IRQ_TIMERINT1, &integrator_timer_irq);
clockevents_config_and_register(&integrator_clockevent,
rate,
1,
0xffffU);
}
/*
* Set up timer(s).
*/
static void __init ap_init_timer(void)
{
struct clk *clk;
unsigned long rate;
clk = clk_get_sys("ap_timer", NULL);
BUG_ON(IS_ERR(clk));
clk_enable(clk);
rate = clk_get_rate(clk);
writel(0, TIMER0_VA_BASE + TIMER_CTRL);
writel(0, TIMER1_VA_BASE + TIMER_CTRL);
writel(0, TIMER2_VA_BASE + TIMER_CTRL);
integrator_clocksource_init(rate);
integrator_clockevent_init(rate);
}
static struct sys_timer ap_timer = {
.init = ap_init_timer,
};
MACHINE_START(INTEGRATOR, "ARM-Integrator")
/* Maintainer: ARM Ltd/Deep Blue Solutions Ltd */
.atag_offset = 0x100,
.reserve = integrator_reserve,
.map_io = ap_map_io,
.nr_irqs = NR_IRQS_INTEGRATOR_AP,
.init_early = integrator_init_early,
.init_irq = ap_init_irq,
.timer = &ap_timer,
.init_machine = ap_init,
.restart = integrator_restart,
MACHINE_END
| gpl-2.0 |
srfarias/Ultra-Kernel | net/ipv6/exthdrs_core.c | 4552 | 3507 | /*
* IPv6 library code, needed by static components when full IPv6 support is
* not configured or static.
*/
#include <linux/export.h>
#include <net/ipv6.h>
/*
* find out if nexthdr is a well-known extension header or a protocol
*/
int ipv6_ext_hdr(u8 nexthdr)
{
/*
* find out if nexthdr is an extension header or a protocol
*/
return (nexthdr == NEXTHDR_HOP) ||
(nexthdr == NEXTHDR_ROUTING) ||
(nexthdr == NEXTHDR_FRAGMENT) ||
(nexthdr == NEXTHDR_AUTH) ||
(nexthdr == NEXTHDR_NONE) ||
(nexthdr == NEXTHDR_DEST);
}
/*
* Skip any extension headers. This is used by the ICMP module.
*
* Note that strictly speaking this conflicts with RFC 2460 4.0:
* ...The contents and semantics of each extension header determine whether
* or not to proceed to the next header. Therefore, extension headers must
* be processed strictly in the order they appear in the packet; a
* receiver must not, for example, scan through a packet looking for a
* particular kind of extension header and process that header prior to
* processing all preceding ones.
*
* We do exactly this. This is a protocol bug. We can't decide after a
* seeing an unknown discard-with-error flavour TLV option if it's a
* ICMP error message or not (errors should never be send in reply to
* ICMP error messages).
*
* But I see no other way to do this. This might need to be reexamined
* when Linux implements ESP (and maybe AUTH) headers.
* --AK
*
* This function parses (probably truncated) exthdr set "hdr".
* "nexthdrp" initially points to some place,
* where type of the first header can be found.
*
* It skips all well-known exthdrs, and returns pointer to the start
* of unparsable area i.e. the first header with unknown type.
* If it is not NULL *nexthdr is updated by type/protocol of this header.
*
* NOTES: - if packet terminated with NEXTHDR_NONE it returns NULL.
* - it may return pointer pointing beyond end of packet,
* if the last recognized header is truncated in the middle.
* - if packet is truncated, so that all parsed headers are skipped,
* it returns NULL.
* - First fragment header is skipped, not-first ones
* are considered as unparsable.
* - Reports the offset field of the final fragment header so it is
* possible to tell whether this is a first fragment, later fragment,
* or not fragmented.
* - ESP is unparsable for now and considered like
* normal payload protocol.
* - Note also special handling of AUTH header. Thanks to IPsec wizards.
*
* --ANK (980726)
*/
int ipv6_skip_exthdr(const struct sk_buff *skb, int start, u8 *nexthdrp,
__be16 *frag_offp)
{
u8 nexthdr = *nexthdrp;
*frag_offp = 0;
while (ipv6_ext_hdr(nexthdr)) {
struct ipv6_opt_hdr _hdr, *hp;
int hdrlen;
if (nexthdr == NEXTHDR_NONE)
return -1;
hp = skb_header_pointer(skb, start, sizeof(_hdr), &_hdr);
if (hp == NULL)
return -1;
if (nexthdr == NEXTHDR_FRAGMENT) {
__be16 _frag_off, *fp;
fp = skb_header_pointer(skb,
start+offsetof(struct frag_hdr,
frag_off),
sizeof(_frag_off),
&_frag_off);
if (fp == NULL)
return -1;
*frag_offp = *fp;
if (ntohs(*frag_offp) & ~0x7)
break;
hdrlen = 8;
} else if (nexthdr == NEXTHDR_AUTH)
hdrlen = (hp->hdrlen+2)<<2;
else
hdrlen = ipv6_optlen(hp);
nexthdr = hp->nexthdr;
start += hdrlen;
}
*nexthdrp = nexthdr;
return start;
}
EXPORT_SYMBOL(ipv6_ext_hdr);
EXPORT_SYMBOL(ipv6_skip_exthdr);
| gpl-2.0 |
aatjitra/cm12 | arch/mips/bcm63xx/prom.c | 4552 | 1240 | /*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 2008 Maxime Bizon <mbizon@freebox.fr>
*/
#include <linux/init.h>
#include <linux/bootmem.h>
#include <asm/bootinfo.h>
#include <bcm63xx_board.h>
#include <bcm63xx_cpu.h>
#include <bcm63xx_io.h>
#include <bcm63xx_regs.h>
#include <bcm63xx_gpio.h>
void __init prom_init(void)
{
u32 reg, mask;
bcm63xx_cpu_init();
/* stop any running watchdog */
bcm_wdt_writel(WDT_STOP_1, WDT_CTL_REG);
bcm_wdt_writel(WDT_STOP_2, WDT_CTL_REG);
/* disable all hardware blocks clock for now */
if (BCMCPU_IS_6338())
mask = CKCTL_6338_ALL_SAFE_EN;
else if (BCMCPU_IS_6345())
mask = CKCTL_6345_ALL_SAFE_EN;
else if (BCMCPU_IS_6348())
mask = CKCTL_6348_ALL_SAFE_EN;
else if (BCMCPU_IS_6358())
mask = CKCTL_6358_ALL_SAFE_EN;
else if (BCMCPU_IS_6368())
mask = CKCTL_6368_ALL_SAFE_EN;
else
mask = 0;
reg = bcm_perf_readl(PERF_CKCTL_REG);
reg &= ~mask;
bcm_perf_writel(reg, PERF_CKCTL_REG);
/* register gpiochip */
bcm63xx_gpio_init();
/* do low level board init */
board_prom_init();
}
void __init prom_free_prom_memory(void)
{
}
| gpl-2.0 |
dragonpt/Kernel_3.4.67_KK_Wiko_DarkMoon | arch/mips/bcm63xx/clk.c | 4552 | 5286 | /*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 2008 Maxime Bizon <mbizon@freebox.fr>
*/
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <bcm63xx_cpu.h>
#include <bcm63xx_io.h>
#include <bcm63xx_regs.h>
#include <bcm63xx_clk.h>
static DEFINE_MUTEX(clocks_mutex);
static void clk_enable_unlocked(struct clk *clk)
{
if (clk->set && (clk->usage++) == 0)
clk->set(clk, 1);
}
static void clk_disable_unlocked(struct clk *clk)
{
if (clk->set && (--clk->usage) == 0)
clk->set(clk, 0);
}
static void bcm_hwclock_set(u32 mask, int enable)
{
u32 reg;
reg = bcm_perf_readl(PERF_CKCTL_REG);
if (enable)
reg |= mask;
else
reg &= ~mask;
bcm_perf_writel(reg, PERF_CKCTL_REG);
}
/*
* Ethernet MAC "misc" clock: dma clocks and main clock on 6348
*/
static void enet_misc_set(struct clk *clk, int enable)
{
u32 mask;
if (BCMCPU_IS_6338())
mask = CKCTL_6338_ENET_EN;
else if (BCMCPU_IS_6345())
mask = CKCTL_6345_ENET_EN;
else if (BCMCPU_IS_6348())
mask = CKCTL_6348_ENET_EN;
else
/* BCMCPU_IS_6358 */
mask = CKCTL_6358_EMUSB_EN;
bcm_hwclock_set(mask, enable);
}
static struct clk clk_enet_misc = {
.set = enet_misc_set,
};
/*
* Ethernet MAC clocks: only revelant on 6358, silently enable misc
* clocks
*/
static void enetx_set(struct clk *clk, int enable)
{
if (enable)
clk_enable_unlocked(&clk_enet_misc);
else
clk_disable_unlocked(&clk_enet_misc);
if (BCMCPU_IS_6358()) {
u32 mask;
if (clk->id == 0)
mask = CKCTL_6358_ENET0_EN;
else
mask = CKCTL_6358_ENET1_EN;
bcm_hwclock_set(mask, enable);
}
}
static struct clk clk_enet0 = {
.id = 0,
.set = enetx_set,
};
static struct clk clk_enet1 = {
.id = 1,
.set = enetx_set,
};
/*
* Ethernet PHY clock
*/
static void ephy_set(struct clk *clk, int enable)
{
if (!BCMCPU_IS_6358())
return;
bcm_hwclock_set(CKCTL_6358_EPHY_EN, enable);
}
static struct clk clk_ephy = {
.set = ephy_set,
};
/*
* Ethernet switch clock
*/
static void enetsw_set(struct clk *clk, int enable)
{
if (!BCMCPU_IS_6368())
return;
bcm_hwclock_set(CKCTL_6368_ROBOSW_CLK_EN |
CKCTL_6368_SWPKT_USB_EN |
CKCTL_6368_SWPKT_SAR_EN, enable);
if (enable) {
u32 val;
/* reset switch core afer clock change */
val = bcm_perf_readl(PERF_SOFTRESET_6368_REG);
val &= ~SOFTRESET_6368_ENETSW_MASK;
bcm_perf_writel(val, PERF_SOFTRESET_6368_REG);
msleep(10);
val |= SOFTRESET_6368_ENETSW_MASK;
bcm_perf_writel(val, PERF_SOFTRESET_6368_REG);
msleep(10);
}
}
static struct clk clk_enetsw = {
.set = enetsw_set,
};
/*
* PCM clock
*/
static void pcm_set(struct clk *clk, int enable)
{
if (!BCMCPU_IS_6358())
return;
bcm_hwclock_set(CKCTL_6358_PCM_EN, enable);
}
static struct clk clk_pcm = {
.set = pcm_set,
};
/*
* USB host clock
*/
static void usbh_set(struct clk *clk, int enable)
{
if (BCMCPU_IS_6348())
bcm_hwclock_set(CKCTL_6348_USBH_EN, enable);
else if (BCMCPU_IS_6368())
bcm_hwclock_set(CKCTL_6368_USBH_CLK_EN, enable);
}
static struct clk clk_usbh = {
.set = usbh_set,
};
/*
* SPI clock
*/
static void spi_set(struct clk *clk, int enable)
{
u32 mask;
if (BCMCPU_IS_6338())
mask = CKCTL_6338_SPI_EN;
else if (BCMCPU_IS_6348())
mask = CKCTL_6348_SPI_EN;
else
/* BCMCPU_IS_6358 */
mask = CKCTL_6358_SPI_EN;
bcm_hwclock_set(mask, enable);
}
static struct clk clk_spi = {
.set = spi_set,
};
/*
* XTM clock
*/
static void xtm_set(struct clk *clk, int enable)
{
if (!BCMCPU_IS_6368())
return;
bcm_hwclock_set(CKCTL_6368_SAR_CLK_EN |
CKCTL_6368_SWPKT_SAR_EN, enable);
if (enable) {
u32 val;
/* reset sar core afer clock change */
val = bcm_perf_readl(PERF_SOFTRESET_6368_REG);
val &= ~SOFTRESET_6368_SAR_MASK;
bcm_perf_writel(val, PERF_SOFTRESET_6368_REG);
mdelay(1);
val |= SOFTRESET_6368_SAR_MASK;
bcm_perf_writel(val, PERF_SOFTRESET_6368_REG);
mdelay(1);
}
}
static struct clk clk_xtm = {
.set = xtm_set,
};
/*
* Internal peripheral clock
*/
static struct clk clk_periph = {
.rate = (50 * 1000 * 1000),
};
/*
* Linux clock API implementation
*/
int clk_enable(struct clk *clk)
{
mutex_lock(&clocks_mutex);
clk_enable_unlocked(clk);
mutex_unlock(&clocks_mutex);
return 0;
}
EXPORT_SYMBOL(clk_enable);
void clk_disable(struct clk *clk)
{
mutex_lock(&clocks_mutex);
clk_disable_unlocked(clk);
mutex_unlock(&clocks_mutex);
}
EXPORT_SYMBOL(clk_disable);
unsigned long clk_get_rate(struct clk *clk)
{
return clk->rate;
}
EXPORT_SYMBOL(clk_get_rate);
struct clk *clk_get(struct device *dev, const char *id)
{
if (!strcmp(id, "enet0"))
return &clk_enet0;
if (!strcmp(id, "enet1"))
return &clk_enet1;
if (!strcmp(id, "enetsw"))
return &clk_enetsw;
if (!strcmp(id, "ephy"))
return &clk_ephy;
if (!strcmp(id, "usbh"))
return &clk_usbh;
if (!strcmp(id, "spi"))
return &clk_spi;
if (!strcmp(id, "xtm"))
return &clk_xtm;
if (!strcmp(id, "periph"))
return &clk_periph;
if (BCMCPU_IS_6358() && !strcmp(id, "pcm"))
return &clk_pcm;
return ERR_PTR(-ENOENT);
}
EXPORT_SYMBOL(clk_get);
void clk_put(struct clk *clk)
{
}
EXPORT_SYMBOL(clk_put);
| gpl-2.0 |
daeiron/LGD855_kernel | fs/xfs/xfs_rtalloc.c | 4808 | 62202 | /*
* Copyright (c) 2000-2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_dir2.h"
#include "xfs_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_alloc.h"
#include "xfs_bmap.h"
#include "xfs_rtalloc.h"
#include "xfs_fsops.h"
#include "xfs_error.h"
#include "xfs_rw.h"
#include "xfs_inode_item.h"
#include "xfs_trans_space.h"
#include "xfs_utils.h"
#include "xfs_trace.h"
#include "xfs_buf.h"
/*
* Prototypes for internal functions.
*/
STATIC int xfs_rtallocate_range(xfs_mount_t *, xfs_trans_t *, xfs_rtblock_t,
xfs_extlen_t, xfs_buf_t **, xfs_fsblock_t *);
STATIC int xfs_rtany_summary(xfs_mount_t *, xfs_trans_t *, int, int,
xfs_rtblock_t, xfs_buf_t **, xfs_fsblock_t *, int *);
STATIC int xfs_rtcheck_range(xfs_mount_t *, xfs_trans_t *, xfs_rtblock_t,
xfs_extlen_t, int, xfs_rtblock_t *, int *);
STATIC int xfs_rtfind_back(xfs_mount_t *, xfs_trans_t *, xfs_rtblock_t,
xfs_rtblock_t, xfs_rtblock_t *);
STATIC int xfs_rtfind_forw(xfs_mount_t *, xfs_trans_t *, xfs_rtblock_t,
xfs_rtblock_t, xfs_rtblock_t *);
STATIC int xfs_rtget_summary( xfs_mount_t *, xfs_trans_t *, int,
xfs_rtblock_t, xfs_buf_t **, xfs_fsblock_t *, xfs_suminfo_t *);
STATIC int xfs_rtmodify_range(xfs_mount_t *, xfs_trans_t *, xfs_rtblock_t,
xfs_extlen_t, int);
STATIC int xfs_rtmodify_summary(xfs_mount_t *, xfs_trans_t *, int,
xfs_rtblock_t, int, xfs_buf_t **, xfs_fsblock_t *);
/*
* Internal functions.
*/
/*
* Allocate space to the bitmap or summary file, and zero it, for growfs.
*/
STATIC int /* error */
xfs_growfs_rt_alloc(
xfs_mount_t *mp, /* file system mount point */
xfs_extlen_t oblocks, /* old count of blocks */
xfs_extlen_t nblocks, /* new count of blocks */
xfs_inode_t *ip) /* inode (bitmap/summary) */
{
xfs_fileoff_t bno; /* block number in file */
xfs_buf_t *bp; /* temporary buffer for zeroing */
int committed; /* transaction committed flag */
xfs_daddr_t d; /* disk block address */
int error; /* error return value */
xfs_fsblock_t firstblock; /* first block allocated in xaction */
xfs_bmap_free_t flist; /* list of freed blocks */
xfs_fsblock_t fsbno; /* filesystem block for bno */
xfs_bmbt_irec_t map; /* block map output */
int nmap; /* number of block maps */
int resblks; /* space reservation */
/*
* Allocate space to the file, as necessary.
*/
while (oblocks < nblocks) {
int cancelflags = 0;
xfs_trans_t *tp;
tp = xfs_trans_alloc(mp, XFS_TRANS_GROWFSRT_ALLOC);
resblks = XFS_GROWFSRT_SPACE_RES(mp, nblocks - oblocks);
/*
* Reserve space & log for one extent added to the file.
*/
if ((error = xfs_trans_reserve(tp, resblks,
XFS_GROWRTALLOC_LOG_RES(mp), 0,
XFS_TRANS_PERM_LOG_RES,
XFS_DEFAULT_PERM_LOG_COUNT)))
goto error_cancel;
cancelflags = XFS_TRANS_RELEASE_LOG_RES;
/*
* Lock the inode.
*/
xfs_ilock(ip, XFS_ILOCK_EXCL);
xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
xfs_bmap_init(&flist, &firstblock);
/*
* Allocate blocks to the bitmap file.
*/
nmap = 1;
cancelflags |= XFS_TRANS_ABORT;
error = xfs_bmapi_write(tp, ip, oblocks, nblocks - oblocks,
XFS_BMAPI_METADATA, &firstblock,
resblks, &map, &nmap, &flist);
if (!error && nmap < 1)
error = XFS_ERROR(ENOSPC);
if (error)
goto error_cancel;
/*
* Free any blocks freed up in the transaction, then commit.
*/
error = xfs_bmap_finish(&tp, &flist, &committed);
if (error)
goto error_cancel;
error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
if (error)
goto error;
/*
* Now we need to clear the allocated blocks.
* Do this one block per transaction, to keep it simple.
*/
cancelflags = 0;
for (bno = map.br_startoff, fsbno = map.br_startblock;
bno < map.br_startoff + map.br_blockcount;
bno++, fsbno++) {
tp = xfs_trans_alloc(mp, XFS_TRANS_GROWFSRT_ZERO);
/*
* Reserve log for one block zeroing.
*/
if ((error = xfs_trans_reserve(tp, 0,
XFS_GROWRTZERO_LOG_RES(mp), 0, 0, 0)))
goto error_cancel;
/*
* Lock the bitmap inode.
*/
xfs_ilock(ip, XFS_ILOCK_EXCL);
xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
/*
* Get a buffer for the block.
*/
d = XFS_FSB_TO_DADDR(mp, fsbno);
bp = xfs_trans_get_buf(tp, mp->m_ddev_targp, d,
mp->m_bsize, 0);
if (bp == NULL) {
error = XFS_ERROR(EIO);
error_cancel:
xfs_trans_cancel(tp, cancelflags);
goto error;
}
memset(bp->b_addr, 0, mp->m_sb.sb_blocksize);
xfs_trans_log_buf(tp, bp, 0, mp->m_sb.sb_blocksize - 1);
/*
* Commit the transaction.
*/
error = xfs_trans_commit(tp, 0);
if (error)
goto error;
}
/*
* Go on to the next extent, if any.
*/
oblocks = map.br_startoff + map.br_blockcount;
}
return 0;
error:
return error;
}
/*
* Attempt to allocate an extent minlen<=len<=maxlen starting from
* bitmap block bbno. If we don't get maxlen then use prod to trim
* the length, if given. Returns error; returns starting block in *rtblock.
* The lengths are all in rtextents.
*/
STATIC int /* error */
xfs_rtallocate_extent_block(
xfs_mount_t *mp, /* file system mount point */
xfs_trans_t *tp, /* transaction pointer */
xfs_rtblock_t bbno, /* bitmap block number */
xfs_extlen_t minlen, /* minimum length to allocate */
xfs_extlen_t maxlen, /* maximum length to allocate */
xfs_extlen_t *len, /* out: actual length allocated */
xfs_rtblock_t *nextp, /* out: next block to try */
xfs_buf_t **rbpp, /* in/out: summary block buffer */
xfs_fsblock_t *rsb, /* in/out: summary block number */
xfs_extlen_t prod, /* extent product factor */
xfs_rtblock_t *rtblock) /* out: start block allocated */
{
xfs_rtblock_t besti; /* best rtblock found so far */
xfs_rtblock_t bestlen; /* best length found so far */
xfs_rtblock_t end; /* last rtblock in chunk */
int error; /* error value */
xfs_rtblock_t i; /* current rtblock trying */
xfs_rtblock_t next; /* next rtblock to try */
int stat; /* status from internal calls */
/*
* Loop over all the extents starting in this bitmap block,
* looking for one that's long enough.
*/
for (i = XFS_BLOCKTOBIT(mp, bbno), besti = -1, bestlen = 0,
end = XFS_BLOCKTOBIT(mp, bbno + 1) - 1;
i <= end;
i++) {
/*
* See if there's a free extent of maxlen starting at i.
* If it's not so then next will contain the first non-free.
*/
error = xfs_rtcheck_range(mp, tp, i, maxlen, 1, &next, &stat);
if (error) {
return error;
}
if (stat) {
/*
* i for maxlen is all free, allocate and return that.
*/
error = xfs_rtallocate_range(mp, tp, i, maxlen, rbpp,
rsb);
if (error) {
return error;
}
*len = maxlen;
*rtblock = i;
return 0;
}
/*
* In the case where we have a variable-sized allocation
* request, figure out how big this free piece is,
* and if it's big enough for the minimum, and the best
* so far, remember it.
*/
if (minlen < maxlen) {
xfs_rtblock_t thislen; /* this extent size */
thislen = next - i;
if (thislen >= minlen && thislen > bestlen) {
besti = i;
bestlen = thislen;
}
}
/*
* If not done yet, find the start of the next free space.
*/
if (next < end) {
error = xfs_rtfind_forw(mp, tp, next, end, &i);
if (error) {
return error;
}
} else
break;
}
/*
* Searched the whole thing & didn't find a maxlen free extent.
*/
if (minlen < maxlen && besti != -1) {
xfs_extlen_t p; /* amount to trim length by */
/*
* If size should be a multiple of prod, make that so.
*/
if (prod > 1 && (p = do_mod(bestlen, prod)))
bestlen -= p;
/*
* Allocate besti for bestlen & return that.
*/
error = xfs_rtallocate_range(mp, tp, besti, bestlen, rbpp, rsb);
if (error) {
return error;
}
*len = bestlen;
*rtblock = besti;
return 0;
}
/*
* Allocation failed. Set *nextp to the next block to try.
*/
*nextp = next;
*rtblock = NULLRTBLOCK;
return 0;
}
/*
* Allocate an extent of length minlen<=len<=maxlen, starting at block
* bno. If we don't get maxlen then use prod to trim the length, if given.
* Returns error; returns starting block in *rtblock.
* The lengths are all in rtextents.
*/
STATIC int /* error */
xfs_rtallocate_extent_exact(
xfs_mount_t *mp, /* file system mount point */
xfs_trans_t *tp, /* transaction pointer */
xfs_rtblock_t bno, /* starting block number to allocate */
xfs_extlen_t minlen, /* minimum length to allocate */
xfs_extlen_t maxlen, /* maximum length to allocate */
xfs_extlen_t *len, /* out: actual length allocated */
xfs_buf_t **rbpp, /* in/out: summary block buffer */
xfs_fsblock_t *rsb, /* in/out: summary block number */
xfs_extlen_t prod, /* extent product factor */
xfs_rtblock_t *rtblock) /* out: start block allocated */
{
int error; /* error value */
xfs_extlen_t i; /* extent length trimmed due to prod */
int isfree; /* extent is free */
xfs_rtblock_t next; /* next block to try (dummy) */
ASSERT(minlen % prod == 0 && maxlen % prod == 0);
/*
* Check if the range in question (for maxlen) is free.
*/
error = xfs_rtcheck_range(mp, tp, bno, maxlen, 1, &next, &isfree);
if (error) {
return error;
}
if (isfree) {
/*
* If it is, allocate it and return success.
*/
error = xfs_rtallocate_range(mp, tp, bno, maxlen, rbpp, rsb);
if (error) {
return error;
}
*len = maxlen;
*rtblock = bno;
return 0;
}
/*
* If not, allocate what there is, if it's at least minlen.
*/
maxlen = next - bno;
if (maxlen < minlen) {
/*
* Failed, return failure status.
*/
*rtblock = NULLRTBLOCK;
return 0;
}
/*
* Trim off tail of extent, if prod is specified.
*/
if (prod > 1 && (i = maxlen % prod)) {
maxlen -= i;
if (maxlen < minlen) {
/*
* Now we can't do it, return failure status.
*/
*rtblock = NULLRTBLOCK;
return 0;
}
}
/*
* Allocate what we can and return it.
*/
error = xfs_rtallocate_range(mp, tp, bno, maxlen, rbpp, rsb);
if (error) {
return error;
}
*len = maxlen;
*rtblock = bno;
return 0;
}
/*
* Allocate an extent of length minlen<=len<=maxlen, starting as near
* to bno as possible. If we don't get maxlen then use prod to trim
* the length, if given. The lengths are all in rtextents.
*/
STATIC int /* error */
xfs_rtallocate_extent_near(
xfs_mount_t *mp, /* file system mount point */
xfs_trans_t *tp, /* transaction pointer */
xfs_rtblock_t bno, /* starting block number to allocate */
xfs_extlen_t minlen, /* minimum length to allocate */
xfs_extlen_t maxlen, /* maximum length to allocate */
xfs_extlen_t *len, /* out: actual length allocated */
xfs_buf_t **rbpp, /* in/out: summary block buffer */
xfs_fsblock_t *rsb, /* in/out: summary block number */
xfs_extlen_t prod, /* extent product factor */
xfs_rtblock_t *rtblock) /* out: start block allocated */
{
int any; /* any useful extents from summary */
xfs_rtblock_t bbno; /* bitmap block number */
int error; /* error value */
int i; /* bitmap block offset (loop control) */
int j; /* secondary loop control */
int log2len; /* log2 of minlen */
xfs_rtblock_t n; /* next block to try */
xfs_rtblock_t r; /* result block */
ASSERT(minlen % prod == 0 && maxlen % prod == 0);
/*
* If the block number given is off the end, silently set it to
* the last block.
*/
if (bno >= mp->m_sb.sb_rextents)
bno = mp->m_sb.sb_rextents - 1;
/*
* Try the exact allocation first.
*/
error = xfs_rtallocate_extent_exact(mp, tp, bno, minlen, maxlen, len,
rbpp, rsb, prod, &r);
if (error) {
return error;
}
/*
* If the exact allocation worked, return that.
*/
if (r != NULLRTBLOCK) {
*rtblock = r;
return 0;
}
bbno = XFS_BITTOBLOCK(mp, bno);
i = 0;
ASSERT(minlen != 0);
log2len = xfs_highbit32(minlen);
/*
* Loop over all bitmap blocks (bbno + i is current block).
*/
for (;;) {
/*
* Get summary information of extents of all useful levels
* starting in this bitmap block.
*/
error = xfs_rtany_summary(mp, tp, log2len, mp->m_rsumlevels - 1,
bbno + i, rbpp, rsb, &any);
if (error) {
return error;
}
/*
* If there are any useful extents starting here, try
* allocating one.
*/
if (any) {
/*
* On the positive side of the starting location.
*/
if (i >= 0) {
/*
* Try to allocate an extent starting in
* this block.
*/
error = xfs_rtallocate_extent_block(mp, tp,
bbno + i, minlen, maxlen, len, &n, rbpp,
rsb, prod, &r);
if (error) {
return error;
}
/*
* If it worked, return it.
*/
if (r != NULLRTBLOCK) {
*rtblock = r;
return 0;
}
}
/*
* On the negative side of the starting location.
*/
else { /* i < 0 */
/*
* Loop backwards through the bitmap blocks from
* the starting point-1 up to where we are now.
* There should be an extent which ends in this
* bitmap block and is long enough.
*/
for (j = -1; j > i; j--) {
/*
* Grab the summary information for
* this bitmap block.
*/
error = xfs_rtany_summary(mp, tp,
log2len, mp->m_rsumlevels - 1,
bbno + j, rbpp, rsb, &any);
if (error) {
return error;
}
/*
* If there's no extent given in the
* summary that means the extent we
* found must carry over from an
* earlier block. If there is an
* extent given, we've already tried
* that allocation, don't do it again.
*/
if (any)
continue;
error = xfs_rtallocate_extent_block(mp,
tp, bbno + j, minlen, maxlen,
len, &n, rbpp, rsb, prod, &r);
if (error) {
return error;
}
/*
* If it works, return the extent.
*/
if (r != NULLRTBLOCK) {
*rtblock = r;
return 0;
}
}
/*
* There weren't intervening bitmap blocks
* with a long enough extent, or the
* allocation didn't work for some reason
* (i.e. it's a little * too short).
* Try to allocate from the summary block
* that we found.
*/
error = xfs_rtallocate_extent_block(mp, tp,
bbno + i, minlen, maxlen, len, &n, rbpp,
rsb, prod, &r);
if (error) {
return error;
}
/*
* If it works, return the extent.
*/
if (r != NULLRTBLOCK) {
*rtblock = r;
return 0;
}
}
}
/*
* Loop control. If we were on the positive side, and there's
* still more blocks on the negative side, go there.
*/
if (i > 0 && (int)bbno - i >= 0)
i = -i;
/*
* If positive, and no more negative, but there are more
* positive, go there.
*/
else if (i > 0 && (int)bbno + i < mp->m_sb.sb_rbmblocks - 1)
i++;
/*
* If negative or 0 (just started), and there are positive
* blocks to go, go there. The 0 case moves to block 1.
*/
else if (i <= 0 && (int)bbno - i < mp->m_sb.sb_rbmblocks - 1)
i = 1 - i;
/*
* If negative or 0 and there are more negative blocks,
* go there.
*/
else if (i <= 0 && (int)bbno + i > 0)
i--;
/*
* Must be done. Return failure.
*/
else
break;
}
*rtblock = NULLRTBLOCK;
return 0;
}
/*
* Allocate an extent of length minlen<=len<=maxlen, with no position
* specified. If we don't get maxlen then use prod to trim
* the length, if given. The lengths are all in rtextents.
*/
STATIC int /* error */
xfs_rtallocate_extent_size(
xfs_mount_t *mp, /* file system mount point */
xfs_trans_t *tp, /* transaction pointer */
xfs_extlen_t minlen, /* minimum length to allocate */
xfs_extlen_t maxlen, /* maximum length to allocate */
xfs_extlen_t *len, /* out: actual length allocated */
xfs_buf_t **rbpp, /* in/out: summary block buffer */
xfs_fsblock_t *rsb, /* in/out: summary block number */
xfs_extlen_t prod, /* extent product factor */
xfs_rtblock_t *rtblock) /* out: start block allocated */
{
int error; /* error value */
int i; /* bitmap block number */
int l; /* level number (loop control) */
xfs_rtblock_t n; /* next block to be tried */
xfs_rtblock_t r; /* result block number */
xfs_suminfo_t sum; /* summary information for extents */
ASSERT(minlen % prod == 0 && maxlen % prod == 0);
ASSERT(maxlen != 0);
/*
* Loop over all the levels starting with maxlen.
* At each level, look at all the bitmap blocks, to see if there
* are extents starting there that are long enough (>= maxlen).
* Note, only on the initial level can the allocation fail if
* the summary says there's an extent.
*/
for (l = xfs_highbit32(maxlen); l < mp->m_rsumlevels; l++) {
/*
* Loop over all the bitmap blocks.
*/
for (i = 0; i < mp->m_sb.sb_rbmblocks; i++) {
/*
* Get the summary for this level/block.
*/
error = xfs_rtget_summary(mp, tp, l, i, rbpp, rsb,
&sum);
if (error) {
return error;
}
/*
* Nothing there, on to the next block.
*/
if (!sum)
continue;
/*
* Try allocating the extent.
*/
error = xfs_rtallocate_extent_block(mp, tp, i, maxlen,
maxlen, len, &n, rbpp, rsb, prod, &r);
if (error) {
return error;
}
/*
* If it worked, return that.
*/
if (r != NULLRTBLOCK) {
*rtblock = r;
return 0;
}
/*
* If the "next block to try" returned from the
* allocator is beyond the next bitmap block,
* skip to that bitmap block.
*/
if (XFS_BITTOBLOCK(mp, n) > i + 1)
i = XFS_BITTOBLOCK(mp, n) - 1;
}
}
/*
* Didn't find any maxlen blocks. Try smaller ones, unless
* we're asking for a fixed size extent.
*/
if (minlen > --maxlen) {
*rtblock = NULLRTBLOCK;
return 0;
}
ASSERT(minlen != 0);
ASSERT(maxlen != 0);
/*
* Loop over sizes, from maxlen down to minlen.
* This time, when we do the allocations, allow smaller ones
* to succeed.
*/
for (l = xfs_highbit32(maxlen); l >= xfs_highbit32(minlen); l--) {
/*
* Loop over all the bitmap blocks, try an allocation
* starting in that block.
*/
for (i = 0; i < mp->m_sb.sb_rbmblocks; i++) {
/*
* Get the summary information for this level/block.
*/
error = xfs_rtget_summary(mp, tp, l, i, rbpp, rsb,
&sum);
if (error) {
return error;
}
/*
* If nothing there, go on to next.
*/
if (!sum)
continue;
/*
* Try the allocation. Make sure the specified
* minlen/maxlen are in the possible range for
* this summary level.
*/
error = xfs_rtallocate_extent_block(mp, tp, i,
XFS_RTMAX(minlen, 1 << l),
XFS_RTMIN(maxlen, (1 << (l + 1)) - 1),
len, &n, rbpp, rsb, prod, &r);
if (error) {
return error;
}
/*
* If it worked, return that extent.
*/
if (r != NULLRTBLOCK) {
*rtblock = r;
return 0;
}
/*
* If the "next block to try" returned from the
* allocator is beyond the next bitmap block,
* skip to that bitmap block.
*/
if (XFS_BITTOBLOCK(mp, n) > i + 1)
i = XFS_BITTOBLOCK(mp, n) - 1;
}
}
/*
* Got nothing, return failure.
*/
*rtblock = NULLRTBLOCK;
return 0;
}
/*
* Mark an extent specified by start and len allocated.
* Updates all the summary information as well as the bitmap.
*/
STATIC int /* error */
xfs_rtallocate_range(
xfs_mount_t *mp, /* file system mount point */
xfs_trans_t *tp, /* transaction pointer */
xfs_rtblock_t start, /* start block to allocate */
xfs_extlen_t len, /* length to allocate */
xfs_buf_t **rbpp, /* in/out: summary block buffer */
xfs_fsblock_t *rsb) /* in/out: summary block number */
{
xfs_rtblock_t end; /* end of the allocated extent */
int error; /* error value */
xfs_rtblock_t postblock; /* first block allocated > end */
xfs_rtblock_t preblock; /* first block allocated < start */
end = start + len - 1;
/*
* Assume we're allocating out of the middle of a free extent.
* We need to find the beginning and end of the extent so we can
* properly update the summary.
*/
error = xfs_rtfind_back(mp, tp, start, 0, &preblock);
if (error) {
return error;
}
/*
* Find the next allocated block (end of free extent).
*/
error = xfs_rtfind_forw(mp, tp, end, mp->m_sb.sb_rextents - 1,
&postblock);
if (error) {
return error;
}
/*
* Decrement the summary information corresponding to the entire
* (old) free extent.
*/
error = xfs_rtmodify_summary(mp, tp,
XFS_RTBLOCKLOG(postblock + 1 - preblock),
XFS_BITTOBLOCK(mp, preblock), -1, rbpp, rsb);
if (error) {
return error;
}
/*
* If there are blocks not being allocated at the front of the
* old extent, add summary data for them to be free.
*/
if (preblock < start) {
error = xfs_rtmodify_summary(mp, tp,
XFS_RTBLOCKLOG(start - preblock),
XFS_BITTOBLOCK(mp, preblock), 1, rbpp, rsb);
if (error) {
return error;
}
}
/*
* If there are blocks not being allocated at the end of the
* old extent, add summary data for them to be free.
*/
if (postblock > end) {
error = xfs_rtmodify_summary(mp, tp,
XFS_RTBLOCKLOG(postblock - end),
XFS_BITTOBLOCK(mp, end + 1), 1, rbpp, rsb);
if (error) {
return error;
}
}
/*
* Modify the bitmap to mark this extent allocated.
*/
error = xfs_rtmodify_range(mp, tp, start, len, 0);
return error;
}
/*
* Return whether there are any free extents in the size range given
* by low and high, for the bitmap block bbno.
*/
STATIC int /* error */
xfs_rtany_summary(
xfs_mount_t *mp, /* file system mount structure */
xfs_trans_t *tp, /* transaction pointer */
int low, /* low log2 extent size */
int high, /* high log2 extent size */
xfs_rtblock_t bbno, /* bitmap block number */
xfs_buf_t **rbpp, /* in/out: summary block buffer */
xfs_fsblock_t *rsb, /* in/out: summary block number */
int *stat) /* out: any good extents here? */
{
int error; /* error value */
int log; /* loop counter, log2 of ext. size */
xfs_suminfo_t sum; /* summary data */
/*
* Loop over logs of extent sizes. Order is irrelevant.
*/
for (log = low; log <= high; log++) {
/*
* Get one summary datum.
*/
error = xfs_rtget_summary(mp, tp, log, bbno, rbpp, rsb, &sum);
if (error) {
return error;
}
/*
* If there are any, return success.
*/
if (sum) {
*stat = 1;
return 0;
}
}
/*
* Found nothing, return failure.
*/
*stat = 0;
return 0;
}
/*
* Get a buffer for the bitmap or summary file block specified.
* The buffer is returned read and locked.
*/
STATIC int /* error */
xfs_rtbuf_get(
xfs_mount_t *mp, /* file system mount structure */
xfs_trans_t *tp, /* transaction pointer */
xfs_rtblock_t block, /* block number in bitmap or summary */
int issum, /* is summary not bitmap */
xfs_buf_t **bpp) /* output: buffer for the block */
{
xfs_buf_t *bp; /* block buffer, result */
xfs_inode_t *ip; /* bitmap or summary inode */
xfs_bmbt_irec_t map;
int nmap;
int error; /* error value */
ip = issum ? mp->m_rsumip : mp->m_rbmip;
error = xfs_bmapi_read(ip, block, 1, &map, &nmap, XFS_DATA_FORK);
if (error)
return error;
ASSERT(map.br_startblock != NULLFSBLOCK);
error = xfs_trans_read_buf(mp, tp, mp->m_ddev_targp,
XFS_FSB_TO_DADDR(mp, map.br_startblock),
mp->m_bsize, 0, &bp);
if (error)
return error;
ASSERT(!xfs_buf_geterror(bp));
*bpp = bp;
return 0;
}
#ifdef DEBUG
/*
* Check that the given extent (block range) is allocated already.
*/
STATIC int /* error */
xfs_rtcheck_alloc_range(
xfs_mount_t *mp, /* file system mount point */
xfs_trans_t *tp, /* transaction pointer */
xfs_rtblock_t bno, /* starting block number of extent */
xfs_extlen_t len, /* length of extent */
int *stat) /* out: 1 for allocated, 0 for not */
{
xfs_rtblock_t new; /* dummy for xfs_rtcheck_range */
return xfs_rtcheck_range(mp, tp, bno, len, 0, &new, stat);
}
#endif
/*
* Check that the given range is either all allocated (val = 0) or
* all free (val = 1).
*/
STATIC int /* error */
xfs_rtcheck_range(
xfs_mount_t *mp, /* file system mount point */
xfs_trans_t *tp, /* transaction pointer */
xfs_rtblock_t start, /* starting block number of extent */
xfs_extlen_t len, /* length of extent */
int val, /* 1 for free, 0 for allocated */
xfs_rtblock_t *new, /* out: first block not matching */
int *stat) /* out: 1 for matches, 0 for not */
{
xfs_rtword_t *b; /* current word in buffer */
int bit; /* bit number in the word */
xfs_rtblock_t block; /* bitmap block number */
xfs_buf_t *bp; /* buf for the block */
xfs_rtword_t *bufp; /* starting word in buffer */
int error; /* error value */
xfs_rtblock_t i; /* current bit number rel. to start */
xfs_rtblock_t lastbit; /* last useful bit in word */
xfs_rtword_t mask; /* mask of relevant bits for value */
xfs_rtword_t wdiff; /* difference from wanted value */
int word; /* word number in the buffer */
/*
* Compute starting bitmap block number
*/
block = XFS_BITTOBLOCK(mp, start);
/*
* Read the bitmap block.
*/
error = xfs_rtbuf_get(mp, tp, block, 0, &bp);
if (error) {
return error;
}
bufp = bp->b_addr;
/*
* Compute the starting word's address, and starting bit.
*/
word = XFS_BITTOWORD(mp, start);
b = &bufp[word];
bit = (int)(start & (XFS_NBWORD - 1));
/*
* 0 (allocated) => all zero's; 1 (free) => all one's.
*/
val = -val;
/*
* If not starting on a word boundary, deal with the first
* (partial) word.
*/
if (bit) {
/*
* Compute first bit not examined.
*/
lastbit = XFS_RTMIN(bit + len, XFS_NBWORD);
/*
* Mask of relevant bits.
*/
mask = (((xfs_rtword_t)1 << (lastbit - bit)) - 1) << bit;
/*
* Compute difference between actual and desired value.
*/
if ((wdiff = (*b ^ val) & mask)) {
/*
* Different, compute first wrong bit and return.
*/
xfs_trans_brelse(tp, bp);
i = XFS_RTLOBIT(wdiff) - bit;
*new = start + i;
*stat = 0;
return 0;
}
i = lastbit - bit;
/*
* Go on to next block if that's where the next word is
* and we need the next word.
*/
if (++word == XFS_BLOCKWSIZE(mp) && i < len) {
/*
* If done with this block, get the next one.
*/
xfs_trans_brelse(tp, bp);
error = xfs_rtbuf_get(mp, tp, ++block, 0, &bp);
if (error) {
return error;
}
b = bufp = bp->b_addr;
word = 0;
} else {
/*
* Go on to the next word in the buffer.
*/
b++;
}
} else {
/*
* Starting on a word boundary, no partial word.
*/
i = 0;
}
/*
* Loop over whole words in buffers. When we use up one buffer
* we move on to the next one.
*/
while (len - i >= XFS_NBWORD) {
/*
* Compute difference between actual and desired value.
*/
if ((wdiff = *b ^ val)) {
/*
* Different, compute first wrong bit and return.
*/
xfs_trans_brelse(tp, bp);
i += XFS_RTLOBIT(wdiff);
*new = start + i;
*stat = 0;
return 0;
}
i += XFS_NBWORD;
/*
* Go on to next block if that's where the next word is
* and we need the next word.
*/
if (++word == XFS_BLOCKWSIZE(mp) && i < len) {
/*
* If done with this block, get the next one.
*/
xfs_trans_brelse(tp, bp);
error = xfs_rtbuf_get(mp, tp, ++block, 0, &bp);
if (error) {
return error;
}
b = bufp = bp->b_addr;
word = 0;
} else {
/*
* Go on to the next word in the buffer.
*/
b++;
}
}
/*
* If not ending on a word boundary, deal with the last
* (partial) word.
*/
if ((lastbit = len - i)) {
/*
* Mask of relevant bits.
*/
mask = ((xfs_rtword_t)1 << lastbit) - 1;
/*
* Compute difference between actual and desired value.
*/
if ((wdiff = (*b ^ val) & mask)) {
/*
* Different, compute first wrong bit and return.
*/
xfs_trans_brelse(tp, bp);
i += XFS_RTLOBIT(wdiff);
*new = start + i;
*stat = 0;
return 0;
} else
i = len;
}
/*
* Successful, return.
*/
xfs_trans_brelse(tp, bp);
*new = start + i;
*stat = 1;
return 0;
}
/*
* Copy and transform the summary file, given the old and new
* parameters in the mount structures.
*/
STATIC int /* error */
xfs_rtcopy_summary(
xfs_mount_t *omp, /* old file system mount point */
xfs_mount_t *nmp, /* new file system mount point */
xfs_trans_t *tp) /* transaction pointer */
{
xfs_rtblock_t bbno; /* bitmap block number */
xfs_buf_t *bp; /* summary buffer */
int error; /* error return value */
int log; /* summary level number (log length) */
xfs_suminfo_t sum; /* summary data */
xfs_fsblock_t sumbno; /* summary block number */
bp = NULL;
for (log = omp->m_rsumlevels - 1; log >= 0; log--) {
for (bbno = omp->m_sb.sb_rbmblocks - 1;
(xfs_srtblock_t)bbno >= 0;
bbno--) {
error = xfs_rtget_summary(omp, tp, log, bbno, &bp,
&sumbno, &sum);
if (error)
return error;
if (sum == 0)
continue;
error = xfs_rtmodify_summary(omp, tp, log, bbno, -sum,
&bp, &sumbno);
if (error)
return error;
error = xfs_rtmodify_summary(nmp, tp, log, bbno, sum,
&bp, &sumbno);
if (error)
return error;
ASSERT(sum > 0);
}
}
return 0;
}
/*
* Searching backward from start to limit, find the first block whose
* allocated/free state is different from start's.
*/
STATIC int /* error */
xfs_rtfind_back(
xfs_mount_t *mp, /* file system mount point */
xfs_trans_t *tp, /* transaction pointer */
xfs_rtblock_t start, /* starting block to look at */
xfs_rtblock_t limit, /* last block to look at */
xfs_rtblock_t *rtblock) /* out: start block found */
{
xfs_rtword_t *b; /* current word in buffer */
int bit; /* bit number in the word */
xfs_rtblock_t block; /* bitmap block number */
xfs_buf_t *bp; /* buf for the block */
xfs_rtword_t *bufp; /* starting word in buffer */
int error; /* error value */
xfs_rtblock_t firstbit; /* first useful bit in the word */
xfs_rtblock_t i; /* current bit number rel. to start */
xfs_rtblock_t len; /* length of inspected area */
xfs_rtword_t mask; /* mask of relevant bits for value */
xfs_rtword_t want; /* mask for "good" values */
xfs_rtword_t wdiff; /* difference from wanted value */
int word; /* word number in the buffer */
/*
* Compute and read in starting bitmap block for starting block.
*/
block = XFS_BITTOBLOCK(mp, start);
error = xfs_rtbuf_get(mp, tp, block, 0, &bp);
if (error) {
return error;
}
bufp = bp->b_addr;
/*
* Get the first word's index & point to it.
*/
word = XFS_BITTOWORD(mp, start);
b = &bufp[word];
bit = (int)(start & (XFS_NBWORD - 1));
len = start - limit + 1;
/*
* Compute match value, based on the bit at start: if 1 (free)
* then all-ones, else all-zeroes.
*/
want = (*b & ((xfs_rtword_t)1 << bit)) ? -1 : 0;
/*
* If the starting position is not word-aligned, deal with the
* partial word.
*/
if (bit < XFS_NBWORD - 1) {
/*
* Calculate first (leftmost) bit number to look at,
* and mask for all the relevant bits in this word.
*/
firstbit = XFS_RTMAX((xfs_srtblock_t)(bit - len + 1), 0);
mask = (((xfs_rtword_t)1 << (bit - firstbit + 1)) - 1) <<
firstbit;
/*
* Calculate the difference between the value there
* and what we're looking for.
*/
if ((wdiff = (*b ^ want) & mask)) {
/*
* Different. Mark where we are and return.
*/
xfs_trans_brelse(tp, bp);
i = bit - XFS_RTHIBIT(wdiff);
*rtblock = start - i + 1;
return 0;
}
i = bit - firstbit + 1;
/*
* Go on to previous block if that's where the previous word is
* and we need the previous word.
*/
if (--word == -1 && i < len) {
/*
* If done with this block, get the previous one.
*/
xfs_trans_brelse(tp, bp);
error = xfs_rtbuf_get(mp, tp, --block, 0, &bp);
if (error) {
return error;
}
bufp = bp->b_addr;
word = XFS_BLOCKWMASK(mp);
b = &bufp[word];
} else {
/*
* Go on to the previous word in the buffer.
*/
b--;
}
} else {
/*
* Starting on a word boundary, no partial word.
*/
i = 0;
}
/*
* Loop over whole words in buffers. When we use up one buffer
* we move on to the previous one.
*/
while (len - i >= XFS_NBWORD) {
/*
* Compute difference between actual and desired value.
*/
if ((wdiff = *b ^ want)) {
/*
* Different, mark where we are and return.
*/
xfs_trans_brelse(tp, bp);
i += XFS_NBWORD - 1 - XFS_RTHIBIT(wdiff);
*rtblock = start - i + 1;
return 0;
}
i += XFS_NBWORD;
/*
* Go on to previous block if that's where the previous word is
* and we need the previous word.
*/
if (--word == -1 && i < len) {
/*
* If done with this block, get the previous one.
*/
xfs_trans_brelse(tp, bp);
error = xfs_rtbuf_get(mp, tp, --block, 0, &bp);
if (error) {
return error;
}
bufp = bp->b_addr;
word = XFS_BLOCKWMASK(mp);
b = &bufp[word];
} else {
/*
* Go on to the previous word in the buffer.
*/
b--;
}
}
/*
* If not ending on a word boundary, deal with the last
* (partial) word.
*/
if (len - i) {
/*
* Calculate first (leftmost) bit number to look at,
* and mask for all the relevant bits in this word.
*/
firstbit = XFS_NBWORD - (len - i);
mask = (((xfs_rtword_t)1 << (len - i)) - 1) << firstbit;
/*
* Compute difference between actual and desired value.
*/
if ((wdiff = (*b ^ want) & mask)) {
/*
* Different, mark where we are and return.
*/
xfs_trans_brelse(tp, bp);
i += XFS_NBWORD - 1 - XFS_RTHIBIT(wdiff);
*rtblock = start - i + 1;
return 0;
} else
i = len;
}
/*
* No match, return that we scanned the whole area.
*/
xfs_trans_brelse(tp, bp);
*rtblock = start - i + 1;
return 0;
}
/*
* Searching forward from start to limit, find the first block whose
* allocated/free state is different from start's.
*/
STATIC int /* error */
xfs_rtfind_forw(
xfs_mount_t *mp, /* file system mount point */
xfs_trans_t *tp, /* transaction pointer */
xfs_rtblock_t start, /* starting block to look at */
xfs_rtblock_t limit, /* last block to look at */
xfs_rtblock_t *rtblock) /* out: start block found */
{
xfs_rtword_t *b; /* current word in buffer */
int bit; /* bit number in the word */
xfs_rtblock_t block; /* bitmap block number */
xfs_buf_t *bp; /* buf for the block */
xfs_rtword_t *bufp; /* starting word in buffer */
int error; /* error value */
xfs_rtblock_t i; /* current bit number rel. to start */
xfs_rtblock_t lastbit; /* last useful bit in the word */
xfs_rtblock_t len; /* length of inspected area */
xfs_rtword_t mask; /* mask of relevant bits for value */
xfs_rtword_t want; /* mask for "good" values */
xfs_rtword_t wdiff; /* difference from wanted value */
int word; /* word number in the buffer */
/*
* Compute and read in starting bitmap block for starting block.
*/
block = XFS_BITTOBLOCK(mp, start);
error = xfs_rtbuf_get(mp, tp, block, 0, &bp);
if (error) {
return error;
}
bufp = bp->b_addr;
/*
* Get the first word's index & point to it.
*/
word = XFS_BITTOWORD(mp, start);
b = &bufp[word];
bit = (int)(start & (XFS_NBWORD - 1));
len = limit - start + 1;
/*
* Compute match value, based on the bit at start: if 1 (free)
* then all-ones, else all-zeroes.
*/
want = (*b & ((xfs_rtword_t)1 << bit)) ? -1 : 0;
/*
* If the starting position is not word-aligned, deal with the
* partial word.
*/
if (bit) {
/*
* Calculate last (rightmost) bit number to look at,
* and mask for all the relevant bits in this word.
*/
lastbit = XFS_RTMIN(bit + len, XFS_NBWORD);
mask = (((xfs_rtword_t)1 << (lastbit - bit)) - 1) << bit;
/*
* Calculate the difference between the value there
* and what we're looking for.
*/
if ((wdiff = (*b ^ want) & mask)) {
/*
* Different. Mark where we are and return.
*/
xfs_trans_brelse(tp, bp);
i = XFS_RTLOBIT(wdiff) - bit;
*rtblock = start + i - 1;
return 0;
}
i = lastbit - bit;
/*
* Go on to next block if that's where the next word is
* and we need the next word.
*/
if (++word == XFS_BLOCKWSIZE(mp) && i < len) {
/*
* If done with this block, get the previous one.
*/
xfs_trans_brelse(tp, bp);
error = xfs_rtbuf_get(mp, tp, ++block, 0, &bp);
if (error) {
return error;
}
b = bufp = bp->b_addr;
word = 0;
} else {
/*
* Go on to the previous word in the buffer.
*/
b++;
}
} else {
/*
* Starting on a word boundary, no partial word.
*/
i = 0;
}
/*
* Loop over whole words in buffers. When we use up one buffer
* we move on to the next one.
*/
while (len - i >= XFS_NBWORD) {
/*
* Compute difference between actual and desired value.
*/
if ((wdiff = *b ^ want)) {
/*
* Different, mark where we are and return.
*/
xfs_trans_brelse(tp, bp);
i += XFS_RTLOBIT(wdiff);
*rtblock = start + i - 1;
return 0;
}
i += XFS_NBWORD;
/*
* Go on to next block if that's where the next word is
* and we need the next word.
*/
if (++word == XFS_BLOCKWSIZE(mp) && i < len) {
/*
* If done with this block, get the next one.
*/
xfs_trans_brelse(tp, bp);
error = xfs_rtbuf_get(mp, tp, ++block, 0, &bp);
if (error) {
return error;
}
b = bufp = bp->b_addr;
word = 0;
} else {
/*
* Go on to the next word in the buffer.
*/
b++;
}
}
/*
* If not ending on a word boundary, deal with the last
* (partial) word.
*/
if ((lastbit = len - i)) {
/*
* Calculate mask for all the relevant bits in this word.
*/
mask = ((xfs_rtword_t)1 << lastbit) - 1;
/*
* Compute difference between actual and desired value.
*/
if ((wdiff = (*b ^ want) & mask)) {
/*
* Different, mark where we are and return.
*/
xfs_trans_brelse(tp, bp);
i += XFS_RTLOBIT(wdiff);
*rtblock = start + i - 1;
return 0;
} else
i = len;
}
/*
* No match, return that we scanned the whole area.
*/
xfs_trans_brelse(tp, bp);
*rtblock = start + i - 1;
return 0;
}
/*
* Mark an extent specified by start and len freed.
* Updates all the summary information as well as the bitmap.
*/
STATIC int /* error */
xfs_rtfree_range(
xfs_mount_t *mp, /* file system mount point */
xfs_trans_t *tp, /* transaction pointer */
xfs_rtblock_t start, /* starting block to free */
xfs_extlen_t len, /* length to free */
xfs_buf_t **rbpp, /* in/out: summary block buffer */
xfs_fsblock_t *rsb) /* in/out: summary block number */
{
xfs_rtblock_t end; /* end of the freed extent */
int error; /* error value */
xfs_rtblock_t postblock; /* first block freed > end */
xfs_rtblock_t preblock; /* first block freed < start */
end = start + len - 1;
/*
* Modify the bitmap to mark this extent freed.
*/
error = xfs_rtmodify_range(mp, tp, start, len, 1);
if (error) {
return error;
}
/*
* Assume we're freeing out of the middle of an allocated extent.
* We need to find the beginning and end of the extent so we can
* properly update the summary.
*/
error = xfs_rtfind_back(mp, tp, start, 0, &preblock);
if (error) {
return error;
}
/*
* Find the next allocated block (end of allocated extent).
*/
error = xfs_rtfind_forw(mp, tp, end, mp->m_sb.sb_rextents - 1,
&postblock);
if (error)
return error;
/*
* If there are blocks not being freed at the front of the
* old extent, add summary data for them to be allocated.
*/
if (preblock < start) {
error = xfs_rtmodify_summary(mp, tp,
XFS_RTBLOCKLOG(start - preblock),
XFS_BITTOBLOCK(mp, preblock), -1, rbpp, rsb);
if (error) {
return error;
}
}
/*
* If there are blocks not being freed at the end of the
* old extent, add summary data for them to be allocated.
*/
if (postblock > end) {
error = xfs_rtmodify_summary(mp, tp,
XFS_RTBLOCKLOG(postblock - end),
XFS_BITTOBLOCK(mp, end + 1), -1, rbpp, rsb);
if (error) {
return error;
}
}
/*
* Increment the summary information corresponding to the entire
* (new) free extent.
*/
error = xfs_rtmodify_summary(mp, tp,
XFS_RTBLOCKLOG(postblock + 1 - preblock),
XFS_BITTOBLOCK(mp, preblock), 1, rbpp, rsb);
return error;
}
/*
* Read and return the summary information for a given extent size,
* bitmap block combination.
* Keeps track of a current summary block, so we don't keep reading
* it from the buffer cache.
*/
STATIC int /* error */
xfs_rtget_summary(
xfs_mount_t *mp, /* file system mount structure */
xfs_trans_t *tp, /* transaction pointer */
int log, /* log2 of extent size */
xfs_rtblock_t bbno, /* bitmap block number */
xfs_buf_t **rbpp, /* in/out: summary block buffer */
xfs_fsblock_t *rsb, /* in/out: summary block number */
xfs_suminfo_t *sum) /* out: summary info for this block */
{
xfs_buf_t *bp; /* buffer for summary block */
int error; /* error value */
xfs_fsblock_t sb; /* summary fsblock */
int so; /* index into the summary file */
xfs_suminfo_t *sp; /* pointer to returned data */
/*
* Compute entry number in the summary file.
*/
so = XFS_SUMOFFS(mp, log, bbno);
/*
* Compute the block number in the summary file.
*/
sb = XFS_SUMOFFSTOBLOCK(mp, so);
/*
* If we have an old buffer, and the block number matches, use that.
*/
if (rbpp && *rbpp && *rsb == sb)
bp = *rbpp;
/*
* Otherwise we have to get the buffer.
*/
else {
/*
* If there was an old one, get rid of it first.
*/
if (rbpp && *rbpp)
xfs_trans_brelse(tp, *rbpp);
error = xfs_rtbuf_get(mp, tp, sb, 1, &bp);
if (error) {
return error;
}
/*
* Remember this buffer and block for the next call.
*/
if (rbpp) {
*rbpp = bp;
*rsb = sb;
}
}
/*
* Point to the summary information & copy it out.
*/
sp = XFS_SUMPTR(mp, bp, so);
*sum = *sp;
/*
* Drop the buffer if we're not asked to remember it.
*/
if (!rbpp)
xfs_trans_brelse(tp, bp);
return 0;
}
/*
* Set the given range of bitmap bits to the given value.
* Do whatever I/O and logging is required.
*/
STATIC int /* error */
xfs_rtmodify_range(
xfs_mount_t *mp, /* file system mount point */
xfs_trans_t *tp, /* transaction pointer */
xfs_rtblock_t start, /* starting block to modify */
xfs_extlen_t len, /* length of extent to modify */
int val) /* 1 for free, 0 for allocated */
{
xfs_rtword_t *b; /* current word in buffer */
int bit; /* bit number in the word */
xfs_rtblock_t block; /* bitmap block number */
xfs_buf_t *bp; /* buf for the block */
xfs_rtword_t *bufp; /* starting word in buffer */
int error; /* error value */
xfs_rtword_t *first; /* first used word in the buffer */
int i; /* current bit number rel. to start */
int lastbit; /* last useful bit in word */
xfs_rtword_t mask; /* mask o frelevant bits for value */
int word; /* word number in the buffer */
/*
* Compute starting bitmap block number.
*/
block = XFS_BITTOBLOCK(mp, start);
/*
* Read the bitmap block, and point to its data.
*/
error = xfs_rtbuf_get(mp, tp, block, 0, &bp);
if (error) {
return error;
}
bufp = bp->b_addr;
/*
* Compute the starting word's address, and starting bit.
*/
word = XFS_BITTOWORD(mp, start);
first = b = &bufp[word];
bit = (int)(start & (XFS_NBWORD - 1));
/*
* 0 (allocated) => all zeroes; 1 (free) => all ones.
*/
val = -val;
/*
* If not starting on a word boundary, deal with the first
* (partial) word.
*/
if (bit) {
/*
* Compute first bit not changed and mask of relevant bits.
*/
lastbit = XFS_RTMIN(bit + len, XFS_NBWORD);
mask = (((xfs_rtword_t)1 << (lastbit - bit)) - 1) << bit;
/*
* Set/clear the active bits.
*/
if (val)
*b |= mask;
else
*b &= ~mask;
i = lastbit - bit;
/*
* Go on to the next block if that's where the next word is
* and we need the next word.
*/
if (++word == XFS_BLOCKWSIZE(mp) && i < len) {
/*
* Log the changed part of this block.
* Get the next one.
*/
xfs_trans_log_buf(tp, bp,
(uint)((char *)first - (char *)bufp),
(uint)((char *)b - (char *)bufp));
error = xfs_rtbuf_get(mp, tp, ++block, 0, &bp);
if (error) {
return error;
}
first = b = bufp = bp->b_addr;
word = 0;
} else {
/*
* Go on to the next word in the buffer
*/
b++;
}
} else {
/*
* Starting on a word boundary, no partial word.
*/
i = 0;
}
/*
* Loop over whole words in buffers. When we use up one buffer
* we move on to the next one.
*/
while (len - i >= XFS_NBWORD) {
/*
* Set the word value correctly.
*/
*b = val;
i += XFS_NBWORD;
/*
* Go on to the next block if that's where the next word is
* and we need the next word.
*/
if (++word == XFS_BLOCKWSIZE(mp) && i < len) {
/*
* Log the changed part of this block.
* Get the next one.
*/
xfs_trans_log_buf(tp, bp,
(uint)((char *)first - (char *)bufp),
(uint)((char *)b - (char *)bufp));
error = xfs_rtbuf_get(mp, tp, ++block, 0, &bp);
if (error) {
return error;
}
first = b = bufp = bp->b_addr;
word = 0;
} else {
/*
* Go on to the next word in the buffer
*/
b++;
}
}
/*
* If not ending on a word boundary, deal with the last
* (partial) word.
*/
if ((lastbit = len - i)) {
/*
* Compute a mask of relevant bits.
*/
bit = 0;
mask = ((xfs_rtword_t)1 << lastbit) - 1;
/*
* Set/clear the active bits.
*/
if (val)
*b |= mask;
else
*b &= ~mask;
b++;
}
/*
* Log any remaining changed bytes.
*/
if (b > first)
xfs_trans_log_buf(tp, bp, (uint)((char *)first - (char *)bufp),
(uint)((char *)b - (char *)bufp - 1));
return 0;
}
/*
* Read and modify the summary information for a given extent size,
* bitmap block combination.
* Keeps track of a current summary block, so we don't keep reading
* it from the buffer cache.
*/
STATIC int /* error */
xfs_rtmodify_summary(
xfs_mount_t *mp, /* file system mount point */
xfs_trans_t *tp, /* transaction pointer */
int log, /* log2 of extent size */
xfs_rtblock_t bbno, /* bitmap block number */
int delta, /* change to make to summary info */
xfs_buf_t **rbpp, /* in/out: summary block buffer */
xfs_fsblock_t *rsb) /* in/out: summary block number */
{
xfs_buf_t *bp; /* buffer for the summary block */
int error; /* error value */
xfs_fsblock_t sb; /* summary fsblock */
int so; /* index into the summary file */
xfs_suminfo_t *sp; /* pointer to returned data */
/*
* Compute entry number in the summary file.
*/
so = XFS_SUMOFFS(mp, log, bbno);
/*
* Compute the block number in the summary file.
*/
sb = XFS_SUMOFFSTOBLOCK(mp, so);
/*
* If we have an old buffer, and the block number matches, use that.
*/
if (rbpp && *rbpp && *rsb == sb)
bp = *rbpp;
/*
* Otherwise we have to get the buffer.
*/
else {
/*
* If there was an old one, get rid of it first.
*/
if (rbpp && *rbpp)
xfs_trans_brelse(tp, *rbpp);
error = xfs_rtbuf_get(mp, tp, sb, 1, &bp);
if (error) {
return error;
}
/*
* Remember this buffer and block for the next call.
*/
if (rbpp) {
*rbpp = bp;
*rsb = sb;
}
}
/*
* Point to the summary information, modify and log it.
*/
sp = XFS_SUMPTR(mp, bp, so);
*sp += delta;
xfs_trans_log_buf(tp, bp, (uint)((char *)sp - (char *)bp->b_addr),
(uint)((char *)sp - (char *)bp->b_addr + sizeof(*sp) - 1));
return 0;
}
/*
* Visible (exported) functions.
*/
/*
* Grow the realtime area of the filesystem.
*/
int
xfs_growfs_rt(
xfs_mount_t *mp, /* mount point for filesystem */
xfs_growfs_rt_t *in) /* growfs rt input struct */
{
xfs_rtblock_t bmbno; /* bitmap block number */
xfs_buf_t *bp; /* temporary buffer */
int error; /* error return value */
xfs_mount_t *nmp; /* new (fake) mount structure */
xfs_drfsbno_t nrblocks; /* new number of realtime blocks */
xfs_extlen_t nrbmblocks; /* new number of rt bitmap blocks */
xfs_drtbno_t nrextents; /* new number of realtime extents */
uint8_t nrextslog; /* new log2 of sb_rextents */
xfs_extlen_t nrsumblocks; /* new number of summary blocks */
uint nrsumlevels; /* new rt summary levels */
uint nrsumsize; /* new size of rt summary, bytes */
xfs_sb_t *nsbp; /* new superblock */
xfs_extlen_t rbmblocks; /* current number of rt bitmap blocks */
xfs_extlen_t rsumblocks; /* current number of rt summary blks */
xfs_sb_t *sbp; /* old superblock */
xfs_fsblock_t sumbno; /* summary block number */
sbp = &mp->m_sb;
/*
* Initial error checking.
*/
if (!capable(CAP_SYS_ADMIN))
return XFS_ERROR(EPERM);
if (mp->m_rtdev_targp == NULL || mp->m_rbmip == NULL ||
(nrblocks = in->newblocks) <= sbp->sb_rblocks ||
(sbp->sb_rblocks && (in->extsize != sbp->sb_rextsize)))
return XFS_ERROR(EINVAL);
if ((error = xfs_sb_validate_fsb_count(sbp, nrblocks)))
return error;
/*
* Read in the last block of the device, make sure it exists.
*/
bp = xfs_buf_read_uncached(mp, mp->m_rtdev_targp,
XFS_FSB_TO_BB(mp, nrblocks - 1),
XFS_FSB_TO_B(mp, 1), 0);
if (!bp)
return EIO;
xfs_buf_relse(bp);
/*
* Calculate new parameters. These are the final values to be reached.
*/
nrextents = nrblocks;
do_div(nrextents, in->extsize);
nrbmblocks = howmany_64(nrextents, NBBY * sbp->sb_blocksize);
nrextslog = xfs_highbit32(nrextents);
nrsumlevels = nrextslog + 1;
nrsumsize = (uint)sizeof(xfs_suminfo_t) * nrsumlevels * nrbmblocks;
nrsumblocks = XFS_B_TO_FSB(mp, nrsumsize);
nrsumsize = XFS_FSB_TO_B(mp, nrsumblocks);
/*
* New summary size can't be more than half the size of
* the log. This prevents us from getting a log overflow,
* since we'll log basically the whole summary file at once.
*/
if (nrsumblocks > (mp->m_sb.sb_logblocks >> 1))
return XFS_ERROR(EINVAL);
/*
* Get the old block counts for bitmap and summary inodes.
* These can't change since other growfs callers are locked out.
*/
rbmblocks = XFS_B_TO_FSB(mp, mp->m_rbmip->i_d.di_size);
rsumblocks = XFS_B_TO_FSB(mp, mp->m_rsumip->i_d.di_size);
/*
* Allocate space to the bitmap and summary files, as necessary.
*/
error = xfs_growfs_rt_alloc(mp, rbmblocks, nrbmblocks, mp->m_rbmip);
if (error)
return error;
error = xfs_growfs_rt_alloc(mp, rsumblocks, nrsumblocks, mp->m_rsumip);
if (error)
return error;
/*
* Allocate a new (fake) mount/sb.
*/
nmp = kmem_alloc(sizeof(*nmp), KM_SLEEP);
/*
* Loop over the bitmap blocks.
* We will do everything one bitmap block at a time.
* Skip the current block if it is exactly full.
* This also deals with the case where there were no rtextents before.
*/
for (bmbno = sbp->sb_rbmblocks -
((sbp->sb_rextents & ((1 << mp->m_blkbit_log) - 1)) != 0);
bmbno < nrbmblocks;
bmbno++) {
xfs_trans_t *tp;
int cancelflags = 0;
*nmp = *mp;
nsbp = &nmp->m_sb;
/*
* Calculate new sb and mount fields for this round.
*/
nsbp->sb_rextsize = in->extsize;
nsbp->sb_rbmblocks = bmbno + 1;
nsbp->sb_rblocks =
XFS_RTMIN(nrblocks,
nsbp->sb_rbmblocks * NBBY *
nsbp->sb_blocksize * nsbp->sb_rextsize);
nsbp->sb_rextents = nsbp->sb_rblocks;
do_div(nsbp->sb_rextents, nsbp->sb_rextsize);
ASSERT(nsbp->sb_rextents != 0);
nsbp->sb_rextslog = xfs_highbit32(nsbp->sb_rextents);
nrsumlevels = nmp->m_rsumlevels = nsbp->sb_rextslog + 1;
nrsumsize =
(uint)sizeof(xfs_suminfo_t) * nrsumlevels *
nsbp->sb_rbmblocks;
nrsumblocks = XFS_B_TO_FSB(mp, nrsumsize);
nmp->m_rsumsize = nrsumsize = XFS_FSB_TO_B(mp, nrsumblocks);
/*
* Start a transaction, get the log reservation.
*/
tp = xfs_trans_alloc(mp, XFS_TRANS_GROWFSRT_FREE);
if ((error = xfs_trans_reserve(tp, 0,
XFS_GROWRTFREE_LOG_RES(nmp), 0, 0, 0)))
goto error_cancel;
/*
* Lock out other callers by grabbing the bitmap inode lock.
*/
xfs_ilock(mp->m_rbmip, XFS_ILOCK_EXCL);
xfs_trans_ijoin(tp, mp->m_rbmip, XFS_ILOCK_EXCL);
/*
* Update the bitmap inode's size.
*/
mp->m_rbmip->i_d.di_size =
nsbp->sb_rbmblocks * nsbp->sb_blocksize;
xfs_trans_log_inode(tp, mp->m_rbmip, XFS_ILOG_CORE);
cancelflags |= XFS_TRANS_ABORT;
/*
* Get the summary inode into the transaction.
*/
xfs_ilock(mp->m_rsumip, XFS_ILOCK_EXCL);
xfs_trans_ijoin(tp, mp->m_rsumip, XFS_ILOCK_EXCL);
/*
* Update the summary inode's size.
*/
mp->m_rsumip->i_d.di_size = nmp->m_rsumsize;
xfs_trans_log_inode(tp, mp->m_rsumip, XFS_ILOG_CORE);
/*
* Copy summary data from old to new sizes.
* Do this when the real size (not block-aligned) changes.
*/
if (sbp->sb_rbmblocks != nsbp->sb_rbmblocks ||
mp->m_rsumlevels != nmp->m_rsumlevels) {
error = xfs_rtcopy_summary(mp, nmp, tp);
if (error)
goto error_cancel;
}
/*
* Update superblock fields.
*/
if (nsbp->sb_rextsize != sbp->sb_rextsize)
xfs_trans_mod_sb(tp, XFS_TRANS_SB_REXTSIZE,
nsbp->sb_rextsize - sbp->sb_rextsize);
if (nsbp->sb_rbmblocks != sbp->sb_rbmblocks)
xfs_trans_mod_sb(tp, XFS_TRANS_SB_RBMBLOCKS,
nsbp->sb_rbmblocks - sbp->sb_rbmblocks);
if (nsbp->sb_rblocks != sbp->sb_rblocks)
xfs_trans_mod_sb(tp, XFS_TRANS_SB_RBLOCKS,
nsbp->sb_rblocks - sbp->sb_rblocks);
if (nsbp->sb_rextents != sbp->sb_rextents)
xfs_trans_mod_sb(tp, XFS_TRANS_SB_REXTENTS,
nsbp->sb_rextents - sbp->sb_rextents);
if (nsbp->sb_rextslog != sbp->sb_rextslog)
xfs_trans_mod_sb(tp, XFS_TRANS_SB_REXTSLOG,
nsbp->sb_rextslog - sbp->sb_rextslog);
/*
* Free new extent.
*/
bp = NULL;
error = xfs_rtfree_range(nmp, tp, sbp->sb_rextents,
nsbp->sb_rextents - sbp->sb_rextents, &bp, &sumbno);
if (error) {
error_cancel:
xfs_trans_cancel(tp, cancelflags);
break;
}
/*
* Mark more blocks free in the superblock.
*/
xfs_trans_mod_sb(tp, XFS_TRANS_SB_FREXTENTS,
nsbp->sb_rextents - sbp->sb_rextents);
/*
* Update mp values into the real mp structure.
*/
mp->m_rsumlevels = nrsumlevels;
mp->m_rsumsize = nrsumsize;
error = xfs_trans_commit(tp, 0);
if (error)
break;
}
/*
* Free the fake mp structure.
*/
kmem_free(nmp);
return error;
}
/*
* Allocate an extent in the realtime subvolume, with the usual allocation
* parameters. The length units are all in realtime extents, as is the
* result block number.
*/
int /* error */
xfs_rtallocate_extent(
xfs_trans_t *tp, /* transaction pointer */
xfs_rtblock_t bno, /* starting block number to allocate */
xfs_extlen_t minlen, /* minimum length to allocate */
xfs_extlen_t maxlen, /* maximum length to allocate */
xfs_extlen_t *len, /* out: actual length allocated */
xfs_alloctype_t type, /* allocation type XFS_ALLOCTYPE... */
int wasdel, /* was a delayed allocation extent */
xfs_extlen_t prod, /* extent product factor */
xfs_rtblock_t *rtblock) /* out: start block allocated */
{
xfs_mount_t *mp = tp->t_mountp;
int error; /* error value */
xfs_rtblock_t r; /* result allocated block */
xfs_fsblock_t sb; /* summary file block number */
xfs_buf_t *sumbp; /* summary file block buffer */
ASSERT(xfs_isilocked(mp->m_rbmip, XFS_ILOCK_EXCL));
ASSERT(minlen > 0 && minlen <= maxlen);
/*
* If prod is set then figure out what to do to minlen and maxlen.
*/
if (prod > 1) {
xfs_extlen_t i;
if ((i = maxlen % prod))
maxlen -= i;
if ((i = minlen % prod))
minlen += prod - i;
if (maxlen < minlen) {
*rtblock = NULLRTBLOCK;
return 0;
}
}
sumbp = NULL;
/*
* Allocate by size, or near another block, or exactly at some block.
*/
switch (type) {
case XFS_ALLOCTYPE_ANY_AG:
error = xfs_rtallocate_extent_size(mp, tp, minlen, maxlen, len,
&sumbp, &sb, prod, &r);
break;
case XFS_ALLOCTYPE_NEAR_BNO:
error = xfs_rtallocate_extent_near(mp, tp, bno, minlen, maxlen,
len, &sumbp, &sb, prod, &r);
break;
case XFS_ALLOCTYPE_THIS_BNO:
error = xfs_rtallocate_extent_exact(mp, tp, bno, minlen, maxlen,
len, &sumbp, &sb, prod, &r);
break;
default:
error = EIO;
ASSERT(0);
}
if (error)
return error;
/*
* If it worked, update the superblock.
*/
if (r != NULLRTBLOCK) {
long slen = (long)*len;
ASSERT(*len >= minlen && *len <= maxlen);
if (wasdel)
xfs_trans_mod_sb(tp, XFS_TRANS_SB_RES_FREXTENTS, -slen);
else
xfs_trans_mod_sb(tp, XFS_TRANS_SB_FREXTENTS, -slen);
}
*rtblock = r;
return 0;
}
/*
* Free an extent in the realtime subvolume. Length is expressed in
* realtime extents, as is the block number.
*/
int /* error */
xfs_rtfree_extent(
xfs_trans_t *tp, /* transaction pointer */
xfs_rtblock_t bno, /* starting block number to free */
xfs_extlen_t len) /* length of extent freed */
{
int error; /* error value */
xfs_mount_t *mp; /* file system mount structure */
xfs_fsblock_t sb; /* summary file block number */
xfs_buf_t *sumbp; /* summary file block buffer */
mp = tp->t_mountp;
ASSERT(mp->m_rbmip->i_itemp != NULL);
ASSERT(xfs_isilocked(mp->m_rbmip, XFS_ILOCK_EXCL));
#if defined(__KERNEL__) && defined(DEBUG)
/*
* Check to see that this whole range is currently allocated.
*/
{
int stat; /* result from checking range */
error = xfs_rtcheck_alloc_range(mp, tp, bno, len, &stat);
if (error) {
return error;
}
ASSERT(stat);
}
#endif
sumbp = NULL;
/*
* Free the range of realtime blocks.
*/
error = xfs_rtfree_range(mp, tp, bno, len, &sumbp, &sb);
if (error) {
return error;
}
/*
* Mark more blocks free in the superblock.
*/
xfs_trans_mod_sb(tp, XFS_TRANS_SB_FREXTENTS, (long)len);
/*
* If we've now freed all the blocks, reset the file sequence
* number to 0.
*/
if (tp->t_frextents_delta + mp->m_sb.sb_frextents ==
mp->m_sb.sb_rextents) {
if (!(mp->m_rbmip->i_d.di_flags & XFS_DIFLAG_NEWRTBM))
mp->m_rbmip->i_d.di_flags |= XFS_DIFLAG_NEWRTBM;
*(__uint64_t *)&mp->m_rbmip->i_d.di_atime = 0;
xfs_trans_log_inode(tp, mp->m_rbmip, XFS_ILOG_CORE);
}
return 0;
}
/*
* Initialize realtime fields in the mount structure.
*/
int /* error */
xfs_rtmount_init(
xfs_mount_t *mp) /* file system mount structure */
{
xfs_buf_t *bp; /* buffer for last block of subvolume */
xfs_daddr_t d; /* address of last block of subvolume */
xfs_sb_t *sbp; /* filesystem superblock copy in mount */
sbp = &mp->m_sb;
if (sbp->sb_rblocks == 0)
return 0;
if (mp->m_rtdev_targp == NULL) {
xfs_warn(mp,
"Filesystem has a realtime volume, use rtdev=device option");
return XFS_ERROR(ENODEV);
}
mp->m_rsumlevels = sbp->sb_rextslog + 1;
mp->m_rsumsize =
(uint)sizeof(xfs_suminfo_t) * mp->m_rsumlevels *
sbp->sb_rbmblocks;
mp->m_rsumsize = roundup(mp->m_rsumsize, sbp->sb_blocksize);
mp->m_rbmip = mp->m_rsumip = NULL;
/*
* Check that the realtime section is an ok size.
*/
d = (xfs_daddr_t)XFS_FSB_TO_BB(mp, mp->m_sb.sb_rblocks);
if (XFS_BB_TO_FSB(mp, d) != mp->m_sb.sb_rblocks) {
xfs_warn(mp, "realtime mount -- %llu != %llu",
(unsigned long long) XFS_BB_TO_FSB(mp, d),
(unsigned long long) mp->m_sb.sb_rblocks);
return XFS_ERROR(EFBIG);
}
bp = xfs_buf_read_uncached(mp, mp->m_rtdev_targp,
d - XFS_FSB_TO_BB(mp, 1),
XFS_FSB_TO_B(mp, 1), 0);
if (!bp) {
xfs_warn(mp, "realtime device size check failed");
return EIO;
}
xfs_buf_relse(bp);
return 0;
}
/*
* Get the bitmap and summary inodes into the mount structure
* at mount time.
*/
int /* error */
xfs_rtmount_inodes(
xfs_mount_t *mp) /* file system mount structure */
{
int error; /* error return value */
xfs_sb_t *sbp;
sbp = &mp->m_sb;
if (sbp->sb_rbmino == NULLFSINO)
return 0;
error = xfs_iget(mp, NULL, sbp->sb_rbmino, 0, 0, &mp->m_rbmip);
if (error)
return error;
ASSERT(mp->m_rbmip != NULL);
ASSERT(sbp->sb_rsumino != NULLFSINO);
error = xfs_iget(mp, NULL, sbp->sb_rsumino, 0, 0, &mp->m_rsumip);
if (error) {
IRELE(mp->m_rbmip);
return error;
}
ASSERT(mp->m_rsumip != NULL);
return 0;
}
void
xfs_rtunmount_inodes(
struct xfs_mount *mp)
{
if (mp->m_rbmip)
IRELE(mp->m_rbmip);
if (mp->m_rsumip)
IRELE(mp->m_rsumip);
}
/*
* Pick an extent for allocation at the start of a new realtime file.
* Use the sequence number stored in the atime field of the bitmap inode.
* Translate this to a fraction of the rtextents, and return the product
* of rtextents and the fraction.
* The fraction sequence is 0, 1/2, 1/4, 3/4, 1/8, ..., 7/8, 1/16, ...
*/
int /* error */
xfs_rtpick_extent(
xfs_mount_t *mp, /* file system mount point */
xfs_trans_t *tp, /* transaction pointer */
xfs_extlen_t len, /* allocation length (rtextents) */
xfs_rtblock_t *pick) /* result rt extent */
{
xfs_rtblock_t b; /* result block */
int log2; /* log of sequence number */
__uint64_t resid; /* residual after log removed */
__uint64_t seq; /* sequence number of file creation */
__uint64_t *seqp; /* pointer to seqno in inode */
ASSERT(xfs_isilocked(mp->m_rbmip, XFS_ILOCK_EXCL));
seqp = (__uint64_t *)&mp->m_rbmip->i_d.di_atime;
if (!(mp->m_rbmip->i_d.di_flags & XFS_DIFLAG_NEWRTBM)) {
mp->m_rbmip->i_d.di_flags |= XFS_DIFLAG_NEWRTBM;
*seqp = 0;
}
seq = *seqp;
if ((log2 = xfs_highbit64(seq)) == -1)
b = 0;
else {
resid = seq - (1ULL << log2);
b = (mp->m_sb.sb_rextents * ((resid << 1) + 1ULL)) >>
(log2 + 1);
if (b >= mp->m_sb.sb_rextents)
b = do_mod(b, mp->m_sb.sb_rextents);
if (b + len > mp->m_sb.sb_rextents)
b = mp->m_sb.sb_rextents - len;
}
*seqp = seq + 1;
xfs_trans_log_inode(tp, mp->m_rbmip, XFS_ILOG_CORE);
*pick = b;
return 0;
}
| gpl-2.0 |
Frank77GLD/android_kernel_YG_m805_892x | fs/jffs2/read.c | 4808 | 7016 | /*
* JFFS2 -- Journalling Flash File System, Version 2.
*
* Copyright © 2001-2007 Red Hat, Inc.
*
* Created by David Woodhouse <dwmw2@infradead.org>
*
* For licensing information, see the file 'LICENCE' in this directory.
*
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/crc32.h>
#include <linux/pagemap.h>
#include <linux/mtd/mtd.h>
#include <linux/compiler.h>
#include "nodelist.h"
#include "compr.h"
int jffs2_read_dnode(struct jffs2_sb_info *c, struct jffs2_inode_info *f,
struct jffs2_full_dnode *fd, unsigned char *buf,
int ofs, int len)
{
struct jffs2_raw_inode *ri;
size_t readlen;
uint32_t crc;
unsigned char *decomprbuf = NULL;
unsigned char *readbuf = NULL;
int ret = 0;
ri = jffs2_alloc_raw_inode();
if (!ri)
return -ENOMEM;
ret = jffs2_flash_read(c, ref_offset(fd->raw), sizeof(*ri), &readlen, (char *)ri);
if (ret) {
jffs2_free_raw_inode(ri);
printk(KERN_WARNING "Error reading node from 0x%08x: %d\n", ref_offset(fd->raw), ret);
return ret;
}
if (readlen != sizeof(*ri)) {
jffs2_free_raw_inode(ri);
printk(KERN_WARNING "Short read from 0x%08x: wanted 0x%zx bytes, got 0x%zx\n",
ref_offset(fd->raw), sizeof(*ri), readlen);
return -EIO;
}
crc = crc32(0, ri, sizeof(*ri)-8);
D1(printk(KERN_DEBUG "Node read from %08x: node_crc %08x, calculated CRC %08x. dsize %x, csize %x, offset %x, buf %p\n",
ref_offset(fd->raw), je32_to_cpu(ri->node_crc),
crc, je32_to_cpu(ri->dsize), je32_to_cpu(ri->csize),
je32_to_cpu(ri->offset), buf));
if (crc != je32_to_cpu(ri->node_crc)) {
printk(KERN_WARNING "Node CRC %08x != calculated CRC %08x for node at %08x\n",
je32_to_cpu(ri->node_crc), crc, ref_offset(fd->raw));
ret = -EIO;
goto out_ri;
}
/* There was a bug where we wrote hole nodes out with csize/dsize
swapped. Deal with it */
if (ri->compr == JFFS2_COMPR_ZERO && !je32_to_cpu(ri->dsize) &&
je32_to_cpu(ri->csize)) {
ri->dsize = ri->csize;
ri->csize = cpu_to_je32(0);
}
D1(if(ofs + len > je32_to_cpu(ri->dsize)) {
printk(KERN_WARNING "jffs2_read_dnode() asked for %d bytes at %d from %d-byte node\n",
len, ofs, je32_to_cpu(ri->dsize));
ret = -EINVAL;
goto out_ri;
});
if (ri->compr == JFFS2_COMPR_ZERO) {
memset(buf, 0, len);
goto out_ri;
}
/* Cases:
Reading whole node and it's uncompressed - read directly to buffer provided, check CRC.
Reading whole node and it's compressed - read into comprbuf, check CRC and decompress to buffer provided
Reading partial node and it's uncompressed - read into readbuf, check CRC, and copy
Reading partial node and it's compressed - read into readbuf, check checksum, decompress to decomprbuf and copy
*/
if (ri->compr == JFFS2_COMPR_NONE && len == je32_to_cpu(ri->dsize)) {
readbuf = buf;
} else {
readbuf = kmalloc(je32_to_cpu(ri->csize), GFP_KERNEL);
if (!readbuf) {
ret = -ENOMEM;
goto out_ri;
}
}
if (ri->compr != JFFS2_COMPR_NONE) {
if (len < je32_to_cpu(ri->dsize)) {
decomprbuf = kmalloc(je32_to_cpu(ri->dsize), GFP_KERNEL);
if (!decomprbuf) {
ret = -ENOMEM;
goto out_readbuf;
}
} else {
decomprbuf = buf;
}
} else {
decomprbuf = readbuf;
}
D2(printk(KERN_DEBUG "Read %d bytes to %p\n", je32_to_cpu(ri->csize),
readbuf));
ret = jffs2_flash_read(c, (ref_offset(fd->raw)) + sizeof(*ri),
je32_to_cpu(ri->csize), &readlen, readbuf);
if (!ret && readlen != je32_to_cpu(ri->csize))
ret = -EIO;
if (ret)
goto out_decomprbuf;
crc = crc32(0, readbuf, je32_to_cpu(ri->csize));
if (crc != je32_to_cpu(ri->data_crc)) {
printk(KERN_WARNING "Data CRC %08x != calculated CRC %08x for node at %08x\n",
je32_to_cpu(ri->data_crc), crc, ref_offset(fd->raw));
ret = -EIO;
goto out_decomprbuf;
}
D2(printk(KERN_DEBUG "Data CRC matches calculated CRC %08x\n", crc));
if (ri->compr != JFFS2_COMPR_NONE) {
D2(printk(KERN_DEBUG "Decompress %d bytes from %p to %d bytes at %p\n",
je32_to_cpu(ri->csize), readbuf, je32_to_cpu(ri->dsize), decomprbuf));
ret = jffs2_decompress(c, f, ri->compr | (ri->usercompr << 8), readbuf, decomprbuf, je32_to_cpu(ri->csize), je32_to_cpu(ri->dsize));
if (ret) {
printk(KERN_WARNING "Error: jffs2_decompress returned %d\n", ret);
goto out_decomprbuf;
}
}
if (len < je32_to_cpu(ri->dsize)) {
memcpy(buf, decomprbuf+ofs, len);
}
out_decomprbuf:
if(decomprbuf != buf && decomprbuf != readbuf)
kfree(decomprbuf);
out_readbuf:
if(readbuf != buf)
kfree(readbuf);
out_ri:
jffs2_free_raw_inode(ri);
return ret;
}
int jffs2_read_inode_range(struct jffs2_sb_info *c, struct jffs2_inode_info *f,
unsigned char *buf, uint32_t offset, uint32_t len)
{
uint32_t end = offset + len;
struct jffs2_node_frag *frag;
int ret;
D1(printk(KERN_DEBUG "jffs2_read_inode_range: ino #%u, range 0x%08x-0x%08x\n",
f->inocache->ino, offset, offset+len));
frag = jffs2_lookup_node_frag(&f->fragtree, offset);
/* XXX FIXME: Where a single physical node actually shows up in two
frags, we read it twice. Don't do that. */
/* Now we're pointing at the first frag which overlaps our page
* (or perhaps is before it, if we've been asked to read off the
* end of the file). */
while(offset < end) {
D2(printk(KERN_DEBUG "jffs2_read_inode_range: offset %d, end %d\n", offset, end));
if (unlikely(!frag || frag->ofs > offset ||
frag->ofs + frag->size <= offset)) {
uint32_t holesize = end - offset;
if (frag && frag->ofs > offset) {
D1(printk(KERN_NOTICE "Eep. Hole in ino #%u fraglist. frag->ofs = 0x%08x, offset = 0x%08x\n", f->inocache->ino, frag->ofs, offset));
holesize = min(holesize, frag->ofs - offset);
}
D1(printk(KERN_DEBUG "Filling non-frag hole from %d-%d\n", offset, offset+holesize));
memset(buf, 0, holesize);
buf += holesize;
offset += holesize;
continue;
} else if (unlikely(!frag->node)) {
uint32_t holeend = min(end, frag->ofs + frag->size);
D1(printk(KERN_DEBUG "Filling frag hole from %d-%d (frag 0x%x 0x%x)\n", offset, holeend, frag->ofs, frag->ofs + frag->size));
memset(buf, 0, holeend - offset);
buf += holeend - offset;
offset = holeend;
frag = frag_next(frag);
continue;
} else {
uint32_t readlen;
uint32_t fragofs; /* offset within the frag to start reading */
fragofs = offset - frag->ofs;
readlen = min(frag->size - fragofs, end - offset);
D1(printk(KERN_DEBUG "Reading %d-%d from node at 0x%08x (%d)\n",
frag->ofs+fragofs, frag->ofs+fragofs+readlen,
ref_offset(frag->node->raw), ref_flags(frag->node->raw)));
ret = jffs2_read_dnode(c, f, frag->node, buf, fragofs + frag->ofs - frag->node->ofs, readlen);
D2(printk(KERN_DEBUG "node read done\n"));
if (ret) {
D1(printk(KERN_DEBUG"jffs2_read_inode_range error %d\n",ret));
memset(buf, 0, readlen);
return ret;
}
buf += readlen;
offset += readlen;
frag = frag_next(frag);
D2(printk(KERN_DEBUG "node read was OK. Looping\n"));
}
}
return 0;
}
| gpl-2.0 |
pablohaylan/I9500_Stock_Kernel_KK_4.4.2 | drivers/regulator/max8660.c | 4808 | 13712 | /*
* max8660.c -- Voltage regulation for the Maxim 8660/8661
*
* based on max1586.c and wm8400-regulator.c
*
* Copyright (C) 2009 Wolfram Sang, Pengutronix e.K.
*
* 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
*
* Some info:
*
* Datasheet: http://datasheets.maxim-ic.com/en/ds/MAX8660-MAX8661.pdf
*
* This chip is a bit nasty because it is a write-only device. Thus, the driver
* uses shadow registers to keep track of its values. The main problem appears
* to be the initialization: When Linux boots up, we cannot know if the chip is
* in the default state or not, so we would have to pass such information in
* platform_data. As this adds a bit of complexity to the driver, this is left
* out for now until it is really needed.
*
* [A|S|M]DTV1 registers are currently not used, but [A|S|M]DTV2.
*
* If the driver is feature complete, it might be worth to check if one set of
* functions for V3-V7 is sufficient. For maximum flexibility during
* development, they are separated for now.
*
*/
#include <linux/module.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <linux/regulator/driver.h>
#include <linux/slab.h>
#include <linux/regulator/max8660.h>
#define MAX8660_DCDC_MIN_UV 725000
#define MAX8660_DCDC_MAX_UV 1800000
#define MAX8660_DCDC_STEP 25000
#define MAX8660_DCDC_MAX_SEL 0x2b
#define MAX8660_LDO5_MIN_UV 1700000
#define MAX8660_LDO5_MAX_UV 2000000
#define MAX8660_LDO5_STEP 25000
#define MAX8660_LDO5_MAX_SEL 0x0c
#define MAX8660_LDO67_MIN_UV 1800000
#define MAX8660_LDO67_MAX_UV 3300000
#define MAX8660_LDO67_STEP 100000
#define MAX8660_LDO67_MAX_SEL 0x0f
enum {
MAX8660_OVER1,
MAX8660_OVER2,
MAX8660_VCC1,
MAX8660_ADTV1,
MAX8660_ADTV2,
MAX8660_SDTV1,
MAX8660_SDTV2,
MAX8660_MDTV1,
MAX8660_MDTV2,
MAX8660_L12VCR,
MAX8660_FPWM,
MAX8660_N_REGS, /* not a real register */
};
struct max8660 {
struct i2c_client *client;
u8 shadow_regs[MAX8660_N_REGS]; /* as chip is write only */
struct regulator_dev *rdev[];
};
static int max8660_write(struct max8660 *max8660, u8 reg, u8 mask, u8 val)
{
static const u8 max8660_addresses[MAX8660_N_REGS] =
{ 0x10, 0x12, 0x20, 0x23, 0x24, 0x29, 0x2a, 0x32, 0x33, 0x39, 0x80 };
int ret;
u8 reg_val = (max8660->shadow_regs[reg] & mask) | val;
dev_vdbg(&max8660->client->dev, "Writing reg %02x with %02x\n",
max8660_addresses[reg], reg_val);
ret = i2c_smbus_write_byte_data(max8660->client,
max8660_addresses[reg], reg_val);
if (ret == 0)
max8660->shadow_regs[reg] = reg_val;
return ret;
}
/*
* DCDC functions
*/
static int max8660_dcdc_is_enabled(struct regulator_dev *rdev)
{
struct max8660 *max8660 = rdev_get_drvdata(rdev);
u8 val = max8660->shadow_regs[MAX8660_OVER1];
u8 mask = (rdev_get_id(rdev) == MAX8660_V3) ? 1 : 4;
return !!(val & mask);
}
static int max8660_dcdc_enable(struct regulator_dev *rdev)
{
struct max8660 *max8660 = rdev_get_drvdata(rdev);
u8 bit = (rdev_get_id(rdev) == MAX8660_V3) ? 1 : 4;
return max8660_write(max8660, MAX8660_OVER1, 0xff, bit);
}
static int max8660_dcdc_disable(struct regulator_dev *rdev)
{
struct max8660 *max8660 = rdev_get_drvdata(rdev);
u8 mask = (rdev_get_id(rdev) == MAX8660_V3) ? ~1 : ~4;
return max8660_write(max8660, MAX8660_OVER1, mask, 0);
}
static int max8660_dcdc_list(struct regulator_dev *rdev, unsigned selector)
{
if (selector > MAX8660_DCDC_MAX_SEL)
return -EINVAL;
return MAX8660_DCDC_MIN_UV + selector * MAX8660_DCDC_STEP;
}
static int max8660_dcdc_get(struct regulator_dev *rdev)
{
struct max8660 *max8660 = rdev_get_drvdata(rdev);
u8 reg = (rdev_get_id(rdev) == MAX8660_V3) ? MAX8660_ADTV2 : MAX8660_SDTV2;
u8 selector = max8660->shadow_regs[reg];
return MAX8660_DCDC_MIN_UV + selector * MAX8660_DCDC_STEP;
}
static int max8660_dcdc_set(struct regulator_dev *rdev, int min_uV, int max_uV,
unsigned int *s)
{
struct max8660 *max8660 = rdev_get_drvdata(rdev);
u8 reg, selector, bits;
int ret;
if (min_uV < MAX8660_DCDC_MIN_UV || min_uV > MAX8660_DCDC_MAX_UV)
return -EINVAL;
if (max_uV < MAX8660_DCDC_MIN_UV || max_uV > MAX8660_DCDC_MAX_UV)
return -EINVAL;
selector = DIV_ROUND_UP(min_uV - MAX8660_DCDC_MIN_UV,
MAX8660_DCDC_STEP);
ret = max8660_dcdc_list(rdev, selector);
if (ret < 0 || ret > max_uV)
return -EINVAL;
*s = selector;
reg = (rdev_get_id(rdev) == MAX8660_V3) ? MAX8660_ADTV2 : MAX8660_SDTV2;
ret = max8660_write(max8660, reg, 0, selector);
if (ret)
return ret;
/* Select target voltage register and activate regulation */
bits = (rdev_get_id(rdev) == MAX8660_V3) ? 0x03 : 0x30;
return max8660_write(max8660, MAX8660_VCC1, 0xff, bits);
}
static struct regulator_ops max8660_dcdc_ops = {
.is_enabled = max8660_dcdc_is_enabled,
.list_voltage = max8660_dcdc_list,
.set_voltage = max8660_dcdc_set,
.get_voltage = max8660_dcdc_get,
};
/*
* LDO5 functions
*/
static int max8660_ldo5_list(struct regulator_dev *rdev, unsigned selector)
{
if (selector > MAX8660_LDO5_MAX_SEL)
return -EINVAL;
return MAX8660_LDO5_MIN_UV + selector * MAX8660_LDO5_STEP;
}
static int max8660_ldo5_get(struct regulator_dev *rdev)
{
struct max8660 *max8660 = rdev_get_drvdata(rdev);
u8 selector = max8660->shadow_regs[MAX8660_MDTV2];
return MAX8660_LDO5_MIN_UV + selector * MAX8660_LDO5_STEP;
}
static int max8660_ldo5_set(struct regulator_dev *rdev, int min_uV, int max_uV,
unsigned int *s)
{
struct max8660 *max8660 = rdev_get_drvdata(rdev);
u8 selector;
int ret;
if (min_uV < MAX8660_LDO5_MIN_UV || min_uV > MAX8660_LDO5_MAX_UV)
return -EINVAL;
if (max_uV < MAX8660_LDO5_MIN_UV || max_uV > MAX8660_LDO5_MAX_UV)
return -EINVAL;
selector = DIV_ROUND_UP(min_uV - MAX8660_LDO5_MIN_UV,
MAX8660_LDO5_STEP);
ret = max8660_ldo5_list(rdev, selector);
if (ret < 0 || ret > max_uV)
return -EINVAL;
*s = selector;
ret = max8660_write(max8660, MAX8660_MDTV2, 0, selector);
if (ret)
return ret;
/* Select target voltage register and activate regulation */
return max8660_write(max8660, MAX8660_VCC1, 0xff, 0xc0);
}
static struct regulator_ops max8660_ldo5_ops = {
.list_voltage = max8660_ldo5_list,
.set_voltage = max8660_ldo5_set,
.get_voltage = max8660_ldo5_get,
};
/*
* LDO67 functions
*/
static int max8660_ldo67_is_enabled(struct regulator_dev *rdev)
{
struct max8660 *max8660 = rdev_get_drvdata(rdev);
u8 val = max8660->shadow_regs[MAX8660_OVER2];
u8 mask = (rdev_get_id(rdev) == MAX8660_V6) ? 2 : 4;
return !!(val & mask);
}
static int max8660_ldo67_enable(struct regulator_dev *rdev)
{
struct max8660 *max8660 = rdev_get_drvdata(rdev);
u8 bit = (rdev_get_id(rdev) == MAX8660_V6) ? 2 : 4;
return max8660_write(max8660, MAX8660_OVER2, 0xff, bit);
}
static int max8660_ldo67_disable(struct regulator_dev *rdev)
{
struct max8660 *max8660 = rdev_get_drvdata(rdev);
u8 mask = (rdev_get_id(rdev) == MAX8660_V6) ? ~2 : ~4;
return max8660_write(max8660, MAX8660_OVER2, mask, 0);
}
static int max8660_ldo67_list(struct regulator_dev *rdev, unsigned selector)
{
if (selector > MAX8660_LDO67_MAX_SEL)
return -EINVAL;
return MAX8660_LDO67_MIN_UV + selector * MAX8660_LDO67_STEP;
}
static int max8660_ldo67_get(struct regulator_dev *rdev)
{
struct max8660 *max8660 = rdev_get_drvdata(rdev);
u8 shift = (rdev_get_id(rdev) == MAX8660_V6) ? 0 : 4;
u8 selector = (max8660->shadow_regs[MAX8660_L12VCR] >> shift) & 0xf;
return MAX8660_LDO67_MIN_UV + selector * MAX8660_LDO67_STEP;
}
static int max8660_ldo67_set(struct regulator_dev *rdev, int min_uV,
int max_uV, unsigned int *s)
{
struct max8660 *max8660 = rdev_get_drvdata(rdev);
u8 selector;
int ret;
if (min_uV < MAX8660_LDO67_MIN_UV || min_uV > MAX8660_LDO67_MAX_UV)
return -EINVAL;
if (max_uV < MAX8660_LDO67_MIN_UV || max_uV > MAX8660_LDO67_MAX_UV)
return -EINVAL;
selector = DIV_ROUND_UP(min_uV - MAX8660_LDO67_MIN_UV,
MAX8660_LDO67_STEP);
ret = max8660_ldo67_list(rdev, selector);
if (ret < 0 || ret > max_uV)
return -EINVAL;
*s = selector;
if (rdev_get_id(rdev) == MAX8660_V6)
return max8660_write(max8660, MAX8660_L12VCR, 0xf0, selector);
else
return max8660_write(max8660, MAX8660_L12VCR, 0x0f, selector << 4);
}
static struct regulator_ops max8660_ldo67_ops = {
.is_enabled = max8660_ldo67_is_enabled,
.enable = max8660_ldo67_enable,
.disable = max8660_ldo67_disable,
.list_voltage = max8660_ldo67_list,
.get_voltage = max8660_ldo67_get,
.set_voltage = max8660_ldo67_set,
};
static struct regulator_desc max8660_reg[] = {
{
.name = "V3(DCDC)",
.id = MAX8660_V3,
.ops = &max8660_dcdc_ops,
.type = REGULATOR_VOLTAGE,
.n_voltages = MAX8660_DCDC_MAX_SEL + 1,
.owner = THIS_MODULE,
},
{
.name = "V4(DCDC)",
.id = MAX8660_V4,
.ops = &max8660_dcdc_ops,
.type = REGULATOR_VOLTAGE,
.n_voltages = MAX8660_DCDC_MAX_SEL + 1,
.owner = THIS_MODULE,
},
{
.name = "V5(LDO)",
.id = MAX8660_V5,
.ops = &max8660_ldo5_ops,
.type = REGULATOR_VOLTAGE,
.n_voltages = MAX8660_LDO5_MAX_SEL + 1,
.owner = THIS_MODULE,
},
{
.name = "V6(LDO)",
.id = MAX8660_V6,
.ops = &max8660_ldo67_ops,
.type = REGULATOR_VOLTAGE,
.n_voltages = MAX8660_LDO67_MAX_SEL + 1,
.owner = THIS_MODULE,
},
{
.name = "V7(LDO)",
.id = MAX8660_V7,
.ops = &max8660_ldo67_ops,
.type = REGULATOR_VOLTAGE,
.n_voltages = MAX8660_LDO67_MAX_SEL + 1,
.owner = THIS_MODULE,
},
};
static int __devinit max8660_probe(struct i2c_client *client,
const struct i2c_device_id *i2c_id)
{
struct regulator_dev **rdev;
struct max8660_platform_data *pdata = client->dev.platform_data;
struct max8660 *max8660;
int boot_on, i, id, ret = -EINVAL;
if (pdata->num_subdevs > MAX8660_V_END) {
dev_err(&client->dev, "Too many regulators found!\n");
goto out;
}
max8660 = kzalloc(sizeof(struct max8660) +
sizeof(struct regulator_dev *) * MAX8660_V_END,
GFP_KERNEL);
if (!max8660) {
ret = -ENOMEM;
goto out;
}
max8660->client = client;
rdev = max8660->rdev;
if (pdata->en34_is_high) {
/* Simulate always on */
max8660->shadow_regs[MAX8660_OVER1] = 5;
} else {
/* Otherwise devices can be toggled via software */
max8660_dcdc_ops.enable = max8660_dcdc_enable;
max8660_dcdc_ops.disable = max8660_dcdc_disable;
}
/*
* First, set up shadow registers to prevent glitches. As some
* registers are shared between regulators, everything must be properly
* set up for all regulators in advance.
*/
max8660->shadow_regs[MAX8660_ADTV1] =
max8660->shadow_regs[MAX8660_ADTV2] =
max8660->shadow_regs[MAX8660_SDTV1] =
max8660->shadow_regs[MAX8660_SDTV2] = 0x1b;
max8660->shadow_regs[MAX8660_MDTV1] =
max8660->shadow_regs[MAX8660_MDTV2] = 0x04;
for (i = 0; i < pdata->num_subdevs; i++) {
if (!pdata->subdevs[i].platform_data)
goto err_free;
boot_on = pdata->subdevs[i].platform_data->constraints.boot_on;
switch (pdata->subdevs[i].id) {
case MAX8660_V3:
if (boot_on)
max8660->shadow_regs[MAX8660_OVER1] |= 1;
break;
case MAX8660_V4:
if (boot_on)
max8660->shadow_regs[MAX8660_OVER1] |= 4;
break;
case MAX8660_V5:
break;
case MAX8660_V6:
if (boot_on)
max8660->shadow_regs[MAX8660_OVER2] |= 2;
break;
case MAX8660_V7:
if (!strcmp(i2c_id->name, "max8661")) {
dev_err(&client->dev, "Regulator not on this chip!\n");
goto err_free;
}
if (boot_on)
max8660->shadow_regs[MAX8660_OVER2] |= 4;
break;
default:
dev_err(&client->dev, "invalid regulator %s\n",
pdata->subdevs[i].name);
goto err_free;
}
}
/* Finally register devices */
for (i = 0; i < pdata->num_subdevs; i++) {
id = pdata->subdevs[i].id;
rdev[i] = regulator_register(&max8660_reg[id], &client->dev,
pdata->subdevs[i].platform_data,
max8660, NULL);
if (IS_ERR(rdev[i])) {
ret = PTR_ERR(rdev[i]);
dev_err(&client->dev, "failed to register %s\n",
max8660_reg[id].name);
goto err_unregister;
}
}
i2c_set_clientdata(client, max8660);
dev_info(&client->dev, "Maxim 8660/8661 regulator driver loaded\n");
return 0;
err_unregister:
while (--i >= 0)
regulator_unregister(rdev[i]);
err_free:
kfree(max8660);
out:
return ret;
}
static int __devexit max8660_remove(struct i2c_client *client)
{
struct max8660 *max8660 = i2c_get_clientdata(client);
int i;
for (i = 0; i < MAX8660_V_END; i++)
if (max8660->rdev[i])
regulator_unregister(max8660->rdev[i]);
kfree(max8660);
return 0;
}
static const struct i2c_device_id max8660_id[] = {
{ "max8660", 0 },
{ "max8661", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, max8660_id);
static struct i2c_driver max8660_driver = {
.probe = max8660_probe,
.remove = __devexit_p(max8660_remove),
.driver = {
.name = "max8660",
.owner = THIS_MODULE,
},
.id_table = max8660_id,
};
static int __init max8660_init(void)
{
return i2c_add_driver(&max8660_driver);
}
subsys_initcall(max8660_init);
static void __exit max8660_exit(void)
{
i2c_del_driver(&max8660_driver);
}
module_exit(max8660_exit);
/* Module information */
MODULE_DESCRIPTION("MAXIM 8660/8661 voltage regulator driver");
MODULE_AUTHOR("Wolfram Sang");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
semdoc/kernel_google_msm | drivers/scsi/lpfc/lpfc_bsg.c | 4808 | 149549 | /*******************************************************************
* This file is part of the Emulex Linux Device Driver for *
* Fibre Channel Host Bus Adapters. *
* Copyright (C) 2009-2011 Emulex. All rights reserved. *
* EMULEX and SLI are trademarks of Emulex. *
* www.emulex.com *
* *
* 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. *
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND *
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE *
* DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
* TO BE LEGALLY INVALID. See the GNU General Public License for *
* more details, a copy of which can be found in the file COPYING *
* included with this package. *
*******************************************************************/
#include <linux/interrupt.h>
#include <linux/mempool.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/list.h>
#include <scsi/scsi.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_transport_fc.h>
#include <scsi/scsi_bsg_fc.h>
#include <scsi/fc/fc_fs.h>
#include "lpfc_hw4.h"
#include "lpfc_hw.h"
#include "lpfc_sli.h"
#include "lpfc_sli4.h"
#include "lpfc_nl.h"
#include "lpfc_bsg.h"
#include "lpfc_disc.h"
#include "lpfc_scsi.h"
#include "lpfc.h"
#include "lpfc_logmsg.h"
#include "lpfc_crtn.h"
#include "lpfc_debugfs.h"
#include "lpfc_vport.h"
#include "lpfc_version.h"
struct lpfc_bsg_event {
struct list_head node;
struct kref kref;
wait_queue_head_t wq;
/* Event type and waiter identifiers */
uint32_t type_mask;
uint32_t req_id;
uint32_t reg_id;
/* next two flags are here for the auto-delete logic */
unsigned long wait_time_stamp;
int waiting;
/* seen and not seen events */
struct list_head events_to_get;
struct list_head events_to_see;
/* job waiting for this event to finish */
struct fc_bsg_job *set_job;
};
struct lpfc_bsg_iocb {
struct lpfc_iocbq *cmdiocbq;
struct lpfc_iocbq *rspiocbq;
struct lpfc_dmabuf *bmp;
struct lpfc_nodelist *ndlp;
/* job waiting for this iocb to finish */
struct fc_bsg_job *set_job;
};
struct lpfc_bsg_mbox {
LPFC_MBOXQ_t *pmboxq;
MAILBOX_t *mb;
struct lpfc_dmabuf *dmabuffers; /* for BIU diags */
uint8_t *ext; /* extended mailbox data */
uint32_t mbOffset; /* from app */
uint32_t inExtWLen; /* from app */
uint32_t outExtWLen; /* from app */
/* job waiting for this mbox command to finish */
struct fc_bsg_job *set_job;
};
#define MENLO_DID 0x0000FC0E
struct lpfc_bsg_menlo {
struct lpfc_iocbq *cmdiocbq;
struct lpfc_iocbq *rspiocbq;
struct lpfc_dmabuf *bmp;
/* job waiting for this iocb to finish */
struct fc_bsg_job *set_job;
};
#define TYPE_EVT 1
#define TYPE_IOCB 2
#define TYPE_MBOX 3
#define TYPE_MENLO 4
struct bsg_job_data {
uint32_t type;
union {
struct lpfc_bsg_event *evt;
struct lpfc_bsg_iocb iocb;
struct lpfc_bsg_mbox mbox;
struct lpfc_bsg_menlo menlo;
} context_un;
};
struct event_data {
struct list_head node;
uint32_t type;
uint32_t immed_dat;
void *data;
uint32_t len;
};
#define BUF_SZ_4K 4096
#define SLI_CT_ELX_LOOPBACK 0x10
enum ELX_LOOPBACK_CMD {
ELX_LOOPBACK_XRI_SETUP,
ELX_LOOPBACK_DATA,
};
#define ELX_LOOPBACK_HEADER_SZ \
(size_t)(&((struct lpfc_sli_ct_request *)NULL)->un)
struct lpfc_dmabufext {
struct lpfc_dmabuf dma;
uint32_t size;
uint32_t flag;
};
/**
* lpfc_bsg_send_mgmt_cmd_cmp - lpfc_bsg_send_mgmt_cmd's completion handler
* @phba: Pointer to HBA context object.
* @cmdiocbq: Pointer to command iocb.
* @rspiocbq: Pointer to response iocb.
*
* This function is the completion handler for iocbs issued using
* lpfc_bsg_send_mgmt_cmd function. This function is called by the
* ring event handler function without any lock held. This function
* can be called from both worker thread context and interrupt
* context. This function also can be called from another thread which
* cleans up the SLI layer objects.
* This function copies the contents of the response iocb to the
* response iocb memory object provided by the caller of
* lpfc_sli_issue_iocb_wait and then wakes up the thread which
* sleeps for the iocb completion.
**/
static void
lpfc_bsg_send_mgmt_cmd_cmp(struct lpfc_hba *phba,
struct lpfc_iocbq *cmdiocbq,
struct lpfc_iocbq *rspiocbq)
{
struct bsg_job_data *dd_data;
struct fc_bsg_job *job;
IOCB_t *rsp;
struct lpfc_dmabuf *bmp;
struct lpfc_nodelist *ndlp;
struct lpfc_bsg_iocb *iocb;
unsigned long flags;
int rc = 0;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
dd_data = cmdiocbq->context2;
if (!dd_data) {
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
lpfc_sli_release_iocbq(phba, cmdiocbq);
return;
}
iocb = &dd_data->context_un.iocb;
job = iocb->set_job;
job->dd_data = NULL; /* so timeout handler does not reply */
bmp = iocb->bmp;
rsp = &rspiocbq->iocb;
ndlp = cmdiocbq->context1;
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
pci_unmap_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
if (rsp->ulpStatus) {
if (rsp->ulpStatus == IOSTAT_LOCAL_REJECT) {
switch (rsp->un.ulpWord[4] & 0xff) {
case IOERR_SEQUENCE_TIMEOUT:
rc = -ETIMEDOUT;
break;
case IOERR_INVALID_RPI:
rc = -EFAULT;
break;
default:
rc = -EACCES;
break;
}
} else
rc = -EACCES;
} else
job->reply->reply_payload_rcv_len =
rsp->un.genreq64.bdl.bdeSize;
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
lpfc_sli_release_iocbq(phba, cmdiocbq);
lpfc_nlp_put(ndlp);
kfree(bmp);
kfree(dd_data);
/* make error code available to userspace */
job->reply->result = rc;
/* complete the job back to userspace */
job->job_done(job);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
/**
* lpfc_bsg_send_mgmt_cmd - send a CT command from a bsg request
* @job: fc_bsg_job to handle
**/
static int
lpfc_bsg_send_mgmt_cmd(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct lpfc_rport_data *rdata = job->rport->dd_data;
struct lpfc_nodelist *ndlp = rdata->pnode;
struct ulp_bde64 *bpl = NULL;
uint32_t timeout;
struct lpfc_iocbq *cmdiocbq = NULL;
IOCB_t *cmd;
struct lpfc_dmabuf *bmp = NULL;
int request_nseg;
int reply_nseg;
struct scatterlist *sgel = NULL;
int numbde;
dma_addr_t busaddr;
struct bsg_job_data *dd_data;
uint32_t creg_val;
int rc = 0;
int iocb_stat;
/* in case no data is transferred */
job->reply->reply_payload_rcv_len = 0;
/* allocate our bsg tracking structure */
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2733 Failed allocation of dd_data\n");
rc = -ENOMEM;
goto no_dd_data;
}
if (!lpfc_nlp_get(ndlp)) {
rc = -ENODEV;
goto no_ndlp;
}
bmp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (!bmp) {
rc = -ENOMEM;
goto free_ndlp;
}
if (ndlp->nlp_flag & NLP_ELS_SND_MASK) {
rc = -ENODEV;
goto free_bmp;
}
cmdiocbq = lpfc_sli_get_iocbq(phba);
if (!cmdiocbq) {
rc = -ENOMEM;
goto free_bmp;
}
cmd = &cmdiocbq->iocb;
bmp->virt = lpfc_mbuf_alloc(phba, 0, &bmp->phys);
if (!bmp->virt) {
rc = -ENOMEM;
goto free_cmdiocbq;
}
INIT_LIST_HEAD(&bmp->list);
bpl = (struct ulp_bde64 *) bmp->virt;
request_nseg = pci_map_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
for_each_sg(job->request_payload.sg_list, sgel, request_nseg, numbde) {
busaddr = sg_dma_address(sgel);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
bpl->tus.f.bdeSize = sg_dma_len(sgel);
bpl->tus.w = cpu_to_le32(bpl->tus.w);
bpl->addrLow = cpu_to_le32(putPaddrLow(busaddr));
bpl->addrHigh = cpu_to_le32(putPaddrHigh(busaddr));
bpl++;
}
reply_nseg = pci_map_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
for_each_sg(job->reply_payload.sg_list, sgel, reply_nseg, numbde) {
busaddr = sg_dma_address(sgel);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64I;
bpl->tus.f.bdeSize = sg_dma_len(sgel);
bpl->tus.w = cpu_to_le32(bpl->tus.w);
bpl->addrLow = cpu_to_le32(putPaddrLow(busaddr));
bpl->addrHigh = cpu_to_le32(putPaddrHigh(busaddr));
bpl++;
}
cmd->un.genreq64.bdl.ulpIoTag32 = 0;
cmd->un.genreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
cmd->un.genreq64.bdl.addrLow = putPaddrLow(bmp->phys);
cmd->un.genreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
cmd->un.genreq64.bdl.bdeSize =
(request_nseg + reply_nseg) * sizeof(struct ulp_bde64);
cmd->ulpCommand = CMD_GEN_REQUEST64_CR;
cmd->un.genreq64.w5.hcsw.Fctl = (SI | LA);
cmd->un.genreq64.w5.hcsw.Dfctl = 0;
cmd->un.genreq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
cmd->un.genreq64.w5.hcsw.Type = FC_TYPE_CT;
cmd->ulpBdeCount = 1;
cmd->ulpLe = 1;
cmd->ulpClass = CLASS3;
cmd->ulpContext = ndlp->nlp_rpi;
if (phba->sli_rev == LPFC_SLI_REV4)
cmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
cmd->ulpOwner = OWN_CHIP;
cmdiocbq->vport = phba->pport;
cmdiocbq->context3 = bmp;
cmdiocbq->iocb_flag |= LPFC_IO_LIBDFC;
timeout = phba->fc_ratov * 2;
cmd->ulpTimeout = timeout;
cmdiocbq->iocb_cmpl = lpfc_bsg_send_mgmt_cmd_cmp;
cmdiocbq->context1 = ndlp;
cmdiocbq->context2 = dd_data;
dd_data->type = TYPE_IOCB;
dd_data->context_un.iocb.cmdiocbq = cmdiocbq;
dd_data->context_un.iocb.set_job = job;
dd_data->context_un.iocb.bmp = bmp;
if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
if (lpfc_readl(phba->HCregaddr, &creg_val)) {
rc = -EIO ;
goto free_cmdiocbq;
}
creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
writel(creg_val, phba->HCregaddr);
readl(phba->HCregaddr); /* flush */
}
iocb_stat = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, cmdiocbq, 0);
if (iocb_stat == IOCB_SUCCESS)
return 0; /* done for now */
else if (iocb_stat == IOCB_BUSY)
rc = -EAGAIN;
else
rc = -EIO;
/* iocb failed so cleanup */
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
pci_unmap_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
free_cmdiocbq:
lpfc_sli_release_iocbq(phba, cmdiocbq);
free_bmp:
kfree(bmp);
free_ndlp:
lpfc_nlp_put(ndlp);
no_ndlp:
kfree(dd_data);
no_dd_data:
/* make error code available to userspace */
job->reply->result = rc;
job->dd_data = NULL;
return rc;
}
/**
* lpfc_bsg_rport_els_cmp - lpfc_bsg_rport_els's completion handler
* @phba: Pointer to HBA context object.
* @cmdiocbq: Pointer to command iocb.
* @rspiocbq: Pointer to response iocb.
*
* This function is the completion handler for iocbs issued using
* lpfc_bsg_rport_els_cmp function. This function is called by the
* ring event handler function without any lock held. This function
* can be called from both worker thread context and interrupt
* context. This function also can be called from other thread which
* cleans up the SLI layer objects.
* This function copies the contents of the response iocb to the
* response iocb memory object provided by the caller of
* lpfc_sli_issue_iocb_wait and then wakes up the thread which
* sleeps for the iocb completion.
**/
static void
lpfc_bsg_rport_els_cmp(struct lpfc_hba *phba,
struct lpfc_iocbq *cmdiocbq,
struct lpfc_iocbq *rspiocbq)
{
struct bsg_job_data *dd_data;
struct fc_bsg_job *job;
IOCB_t *rsp;
struct lpfc_nodelist *ndlp;
struct lpfc_dmabuf *pbuflist = NULL;
struct fc_bsg_ctels_reply *els_reply;
uint8_t *rjt_data;
unsigned long flags;
int rc = 0;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
dd_data = cmdiocbq->context1;
/* normal completion and timeout crossed paths, already done */
if (!dd_data) {
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
if (cmdiocbq->context2 && rspiocbq)
memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
&rspiocbq->iocb, sizeof(IOCB_t));
job = dd_data->context_un.iocb.set_job;
cmdiocbq = dd_data->context_un.iocb.cmdiocbq;
rspiocbq = dd_data->context_un.iocb.rspiocbq;
rsp = &rspiocbq->iocb;
ndlp = dd_data->context_un.iocb.ndlp;
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
pci_unmap_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
if (job->reply->result == -EAGAIN)
rc = -EAGAIN;
else if (rsp->ulpStatus == IOSTAT_SUCCESS)
job->reply->reply_payload_rcv_len =
rsp->un.elsreq64.bdl.bdeSize;
else if (rsp->ulpStatus == IOSTAT_LS_RJT) {
job->reply->reply_payload_rcv_len =
sizeof(struct fc_bsg_ctels_reply);
/* LS_RJT data returned in word 4 */
rjt_data = (uint8_t *)&rsp->un.ulpWord[4];
els_reply = &job->reply->reply_data.ctels_reply;
els_reply->status = FC_CTELS_STATUS_REJECT;
els_reply->rjt_data.action = rjt_data[3];
els_reply->rjt_data.reason_code = rjt_data[2];
els_reply->rjt_data.reason_explanation = rjt_data[1];
els_reply->rjt_data.vendor_unique = rjt_data[0];
} else
rc = -EIO;
pbuflist = (struct lpfc_dmabuf *) cmdiocbq->context3;
lpfc_mbuf_free(phba, pbuflist->virt, pbuflist->phys);
lpfc_sli_release_iocbq(phba, rspiocbq);
lpfc_sli_release_iocbq(phba, cmdiocbq);
lpfc_nlp_put(ndlp);
kfree(dd_data);
/* make error code available to userspace */
job->reply->result = rc;
job->dd_data = NULL;
/* complete the job back to userspace */
job->job_done(job);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
/**
* lpfc_bsg_rport_els - send an ELS command from a bsg request
* @job: fc_bsg_job to handle
**/
static int
lpfc_bsg_rport_els(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct lpfc_rport_data *rdata = job->rport->dd_data;
struct lpfc_nodelist *ndlp = rdata->pnode;
uint32_t elscmd;
uint32_t cmdsize;
uint32_t rspsize;
struct lpfc_iocbq *rspiocbq;
struct lpfc_iocbq *cmdiocbq;
IOCB_t *rsp;
uint16_t rpi = 0;
struct lpfc_dmabuf *pcmd;
struct lpfc_dmabuf *prsp;
struct lpfc_dmabuf *pbuflist = NULL;
struct ulp_bde64 *bpl;
int request_nseg;
int reply_nseg;
struct scatterlist *sgel = NULL;
int numbde;
dma_addr_t busaddr;
struct bsg_job_data *dd_data;
uint32_t creg_val;
int rc = 0;
/* in case no data is transferred */
job->reply->reply_payload_rcv_len = 0;
/* allocate our bsg tracking structure */
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2735 Failed allocation of dd_data\n");
rc = -ENOMEM;
goto no_dd_data;
}
if (!lpfc_nlp_get(ndlp)) {
rc = -ENODEV;
goto free_dd_data;
}
elscmd = job->request->rqst_data.r_els.els_code;
cmdsize = job->request_payload.payload_len;
rspsize = job->reply_payload.payload_len;
rspiocbq = lpfc_sli_get_iocbq(phba);
if (!rspiocbq) {
lpfc_nlp_put(ndlp);
rc = -ENOMEM;
goto free_dd_data;
}
rsp = &rspiocbq->iocb;
rpi = ndlp->nlp_rpi;
cmdiocbq = lpfc_prep_els_iocb(vport, 1, cmdsize, 0, ndlp,
ndlp->nlp_DID, elscmd);
if (!cmdiocbq) {
rc = -EIO;
goto free_rspiocbq;
}
/* prep els iocb set context1 to the ndlp, context2 to the command
* dmabuf, context3 holds the data dmabuf
*/
pcmd = (struct lpfc_dmabuf *) cmdiocbq->context2;
prsp = (struct lpfc_dmabuf *) pcmd->list.next;
lpfc_mbuf_free(phba, pcmd->virt, pcmd->phys);
kfree(pcmd);
lpfc_mbuf_free(phba, prsp->virt, prsp->phys);
kfree(prsp);
cmdiocbq->context2 = NULL;
pbuflist = (struct lpfc_dmabuf *) cmdiocbq->context3;
bpl = (struct ulp_bde64 *) pbuflist->virt;
request_nseg = pci_map_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
for_each_sg(job->request_payload.sg_list, sgel, request_nseg, numbde) {
busaddr = sg_dma_address(sgel);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
bpl->tus.f.bdeSize = sg_dma_len(sgel);
bpl->tus.w = cpu_to_le32(bpl->tus.w);
bpl->addrLow = cpu_to_le32(putPaddrLow(busaddr));
bpl->addrHigh = cpu_to_le32(putPaddrHigh(busaddr));
bpl++;
}
reply_nseg = pci_map_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
for_each_sg(job->reply_payload.sg_list, sgel, reply_nseg, numbde) {
busaddr = sg_dma_address(sgel);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64I;
bpl->tus.f.bdeSize = sg_dma_len(sgel);
bpl->tus.w = cpu_to_le32(bpl->tus.w);
bpl->addrLow = cpu_to_le32(putPaddrLow(busaddr));
bpl->addrHigh = cpu_to_le32(putPaddrHigh(busaddr));
bpl++;
}
cmdiocbq->iocb.un.elsreq64.bdl.bdeSize =
(request_nseg + reply_nseg) * sizeof(struct ulp_bde64);
if (phba->sli_rev == LPFC_SLI_REV4)
cmdiocbq->iocb.ulpContext = phba->sli4_hba.rpi_ids[rpi];
else
cmdiocbq->iocb.ulpContext = rpi;
cmdiocbq->iocb_flag |= LPFC_IO_LIBDFC;
cmdiocbq->context1 = NULL;
cmdiocbq->context2 = NULL;
cmdiocbq->iocb_cmpl = lpfc_bsg_rport_els_cmp;
cmdiocbq->context1 = dd_data;
cmdiocbq->context2 = rspiocbq;
dd_data->type = TYPE_IOCB;
dd_data->context_un.iocb.cmdiocbq = cmdiocbq;
dd_data->context_un.iocb.rspiocbq = rspiocbq;
dd_data->context_un.iocb.set_job = job;
dd_data->context_un.iocb.bmp = NULL;
dd_data->context_un.iocb.ndlp = ndlp;
if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
if (lpfc_readl(phba->HCregaddr, &creg_val)) {
rc = -EIO;
goto linkdown_err;
}
creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
writel(creg_val, phba->HCregaddr);
readl(phba->HCregaddr); /* flush */
}
rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, cmdiocbq, 0);
lpfc_nlp_put(ndlp);
if (rc == IOCB_SUCCESS)
return 0; /* done for now */
else if (rc == IOCB_BUSY)
rc = -EAGAIN;
else
rc = -EIO;
linkdown_err:
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
pci_unmap_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
lpfc_mbuf_free(phba, pbuflist->virt, pbuflist->phys);
lpfc_sli_release_iocbq(phba, cmdiocbq);
free_rspiocbq:
lpfc_sli_release_iocbq(phba, rspiocbq);
free_dd_data:
kfree(dd_data);
no_dd_data:
/* make error code available to userspace */
job->reply->result = rc;
job->dd_data = NULL;
return rc;
}
/**
* lpfc_bsg_event_free - frees an allocated event structure
* @kref: Pointer to a kref.
*
* Called from kref_put. Back cast the kref into an event structure address.
* Free any events to get, delete associated nodes, free any events to see,
* free any data then free the event itself.
**/
static void
lpfc_bsg_event_free(struct kref *kref)
{
struct lpfc_bsg_event *evt = container_of(kref, struct lpfc_bsg_event,
kref);
struct event_data *ed;
list_del(&evt->node);
while (!list_empty(&evt->events_to_get)) {
ed = list_entry(evt->events_to_get.next, typeof(*ed), node);
list_del(&ed->node);
kfree(ed->data);
kfree(ed);
}
while (!list_empty(&evt->events_to_see)) {
ed = list_entry(evt->events_to_see.next, typeof(*ed), node);
list_del(&ed->node);
kfree(ed->data);
kfree(ed);
}
kfree(evt);
}
/**
* lpfc_bsg_event_ref - increments the kref for an event
* @evt: Pointer to an event structure.
**/
static inline void
lpfc_bsg_event_ref(struct lpfc_bsg_event *evt)
{
kref_get(&evt->kref);
}
/**
* lpfc_bsg_event_unref - Uses kref_put to free an event structure
* @evt: Pointer to an event structure.
**/
static inline void
lpfc_bsg_event_unref(struct lpfc_bsg_event *evt)
{
kref_put(&evt->kref, lpfc_bsg_event_free);
}
/**
* lpfc_bsg_event_new - allocate and initialize a event structure
* @ev_mask: Mask of events.
* @ev_reg_id: Event reg id.
* @ev_req_id: Event request id.
**/
static struct lpfc_bsg_event *
lpfc_bsg_event_new(uint32_t ev_mask, int ev_reg_id, uint32_t ev_req_id)
{
struct lpfc_bsg_event *evt = kzalloc(sizeof(*evt), GFP_KERNEL);
if (!evt)
return NULL;
INIT_LIST_HEAD(&evt->events_to_get);
INIT_LIST_HEAD(&evt->events_to_see);
evt->type_mask = ev_mask;
evt->req_id = ev_req_id;
evt->reg_id = ev_reg_id;
evt->wait_time_stamp = jiffies;
init_waitqueue_head(&evt->wq);
kref_init(&evt->kref);
return evt;
}
/**
* diag_cmd_data_free - Frees an lpfc dma buffer extension
* @phba: Pointer to HBA context object.
* @mlist: Pointer to an lpfc dma buffer extension.
**/
static int
diag_cmd_data_free(struct lpfc_hba *phba, struct lpfc_dmabufext *mlist)
{
struct lpfc_dmabufext *mlast;
struct pci_dev *pcidev;
struct list_head head, *curr, *next;
if ((!mlist) || (!lpfc_is_link_up(phba) &&
(phba->link_flag & LS_LOOPBACK_MODE))) {
return 0;
}
pcidev = phba->pcidev;
list_add_tail(&head, &mlist->dma.list);
list_for_each_safe(curr, next, &head) {
mlast = list_entry(curr, struct lpfc_dmabufext , dma.list);
if (mlast->dma.virt)
dma_free_coherent(&pcidev->dev,
mlast->size,
mlast->dma.virt,
mlast->dma.phys);
kfree(mlast);
}
return 0;
}
/**
* lpfc_bsg_ct_unsol_event - process an unsolicited CT command
* @phba:
* @pring:
* @piocbq:
*
* This function is called when an unsolicited CT command is received. It
* forwards the event to any processes registered to receive CT events.
**/
int
lpfc_bsg_ct_unsol_event(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
struct lpfc_iocbq *piocbq)
{
uint32_t evt_req_id = 0;
uint32_t cmd;
uint32_t len;
struct lpfc_dmabuf *dmabuf = NULL;
struct lpfc_bsg_event *evt;
struct event_data *evt_dat = NULL;
struct lpfc_iocbq *iocbq;
size_t offset = 0;
struct list_head head;
struct ulp_bde64 *bde;
dma_addr_t dma_addr;
int i;
struct lpfc_dmabuf *bdeBuf1 = piocbq->context2;
struct lpfc_dmabuf *bdeBuf2 = piocbq->context3;
struct lpfc_hbq_entry *hbqe;
struct lpfc_sli_ct_request *ct_req;
struct fc_bsg_job *job = NULL;
unsigned long flags;
int size = 0;
INIT_LIST_HEAD(&head);
list_add_tail(&head, &piocbq->list);
if (piocbq->iocb.ulpBdeCount == 0 ||
piocbq->iocb.un.cont64[0].tus.f.bdeSize == 0)
goto error_ct_unsol_exit;
if (phba->link_state == LPFC_HBA_ERROR ||
(!(phba->sli.sli_flag & LPFC_SLI_ACTIVE)))
goto error_ct_unsol_exit;
if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)
dmabuf = bdeBuf1;
else {
dma_addr = getPaddr(piocbq->iocb.un.cont64[0].addrHigh,
piocbq->iocb.un.cont64[0].addrLow);
dmabuf = lpfc_sli_ringpostbuf_get(phba, pring, dma_addr);
}
if (dmabuf == NULL)
goto error_ct_unsol_exit;
ct_req = (struct lpfc_sli_ct_request *)dmabuf->virt;
evt_req_id = ct_req->FsType;
cmd = ct_req->CommandResponse.bits.CmdRsp;
len = ct_req->CommandResponse.bits.Size;
if (!(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED))
lpfc_sli_ringpostbuf_put(phba, pring, dmabuf);
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_for_each_entry(evt, &phba->ct_ev_waiters, node) {
if (!(evt->type_mask & FC_REG_CT_EVENT) ||
evt->req_id != evt_req_id)
continue;
lpfc_bsg_event_ref(evt);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
evt_dat = kzalloc(sizeof(*evt_dat), GFP_KERNEL);
if (evt_dat == NULL) {
spin_lock_irqsave(&phba->ct_ev_lock, flags);
lpfc_bsg_event_unref(evt);
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2614 Memory allocation failed for "
"CT event\n");
break;
}
if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
/* take accumulated byte count from the last iocbq */
iocbq = list_entry(head.prev, typeof(*iocbq), list);
evt_dat->len = iocbq->iocb.unsli3.rcvsli3.acc_len;
} else {
list_for_each_entry(iocbq, &head, list) {
for (i = 0; i < iocbq->iocb.ulpBdeCount; i++)
evt_dat->len +=
iocbq->iocb.un.cont64[i].tus.f.bdeSize;
}
}
evt_dat->data = kzalloc(evt_dat->len, GFP_KERNEL);
if (evt_dat->data == NULL) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2615 Memory allocation failed for "
"CT event data, size %d\n",
evt_dat->len);
kfree(evt_dat);
spin_lock_irqsave(&phba->ct_ev_lock, flags);
lpfc_bsg_event_unref(evt);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
goto error_ct_unsol_exit;
}
list_for_each_entry(iocbq, &head, list) {
size = 0;
if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
bdeBuf1 = iocbq->context2;
bdeBuf2 = iocbq->context3;
}
for (i = 0; i < iocbq->iocb.ulpBdeCount; i++) {
if (phba->sli3_options &
LPFC_SLI3_HBQ_ENABLED) {
if (i == 0) {
hbqe = (struct lpfc_hbq_entry *)
&iocbq->iocb.un.ulpWord[0];
size = hbqe->bde.tus.f.bdeSize;
dmabuf = bdeBuf1;
} else if (i == 1) {
hbqe = (struct lpfc_hbq_entry *)
&iocbq->iocb.unsli3.
sli3Words[4];
size = hbqe->bde.tus.f.bdeSize;
dmabuf = bdeBuf2;
}
if ((offset + size) > evt_dat->len)
size = evt_dat->len - offset;
} else {
size = iocbq->iocb.un.cont64[i].
tus.f.bdeSize;
bde = &iocbq->iocb.un.cont64[i];
dma_addr = getPaddr(bde->addrHigh,
bde->addrLow);
dmabuf = lpfc_sli_ringpostbuf_get(phba,
pring, dma_addr);
}
if (!dmabuf) {
lpfc_printf_log(phba, KERN_ERR,
LOG_LIBDFC, "2616 No dmabuf "
"found for iocbq 0x%p\n",
iocbq);
kfree(evt_dat->data);
kfree(evt_dat);
spin_lock_irqsave(&phba->ct_ev_lock,
flags);
lpfc_bsg_event_unref(evt);
spin_unlock_irqrestore(
&phba->ct_ev_lock, flags);
goto error_ct_unsol_exit;
}
memcpy((char *)(evt_dat->data) + offset,
dmabuf->virt, size);
offset += size;
if (evt_req_id != SLI_CT_ELX_LOOPBACK &&
!(phba->sli3_options &
LPFC_SLI3_HBQ_ENABLED)) {
lpfc_sli_ringpostbuf_put(phba, pring,
dmabuf);
} else {
switch (cmd) {
case ELX_LOOPBACK_DATA:
if (phba->sli_rev <
LPFC_SLI_REV4)
diag_cmd_data_free(phba,
(struct lpfc_dmabufext
*)dmabuf);
break;
case ELX_LOOPBACK_XRI_SETUP:
if ((phba->sli_rev ==
LPFC_SLI_REV2) ||
(phba->sli3_options &
LPFC_SLI3_HBQ_ENABLED
)) {
lpfc_in_buf_free(phba,
dmabuf);
} else {
lpfc_post_buffer(phba,
pring,
1);
}
break;
default:
if (!(phba->sli3_options &
LPFC_SLI3_HBQ_ENABLED))
lpfc_post_buffer(phba,
pring,
1);
break;
}
}
}
}
spin_lock_irqsave(&phba->ct_ev_lock, flags);
if (phba->sli_rev == LPFC_SLI_REV4) {
evt_dat->immed_dat = phba->ctx_idx;
phba->ctx_idx = (phba->ctx_idx + 1) % 64;
/* Provide warning for over-run of the ct_ctx array */
if (phba->ct_ctx[evt_dat->immed_dat].flags &
UNSOL_VALID)
lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
"2717 CT context array entry "
"[%d] over-run: oxid:x%x, "
"sid:x%x\n", phba->ctx_idx,
phba->ct_ctx[
evt_dat->immed_dat].oxid,
phba->ct_ctx[
evt_dat->immed_dat].SID);
phba->ct_ctx[evt_dat->immed_dat].rxid =
piocbq->iocb.ulpContext;
phba->ct_ctx[evt_dat->immed_dat].oxid =
piocbq->iocb.unsli3.rcvsli3.ox_id;
phba->ct_ctx[evt_dat->immed_dat].SID =
piocbq->iocb.un.rcvels.remoteID;
phba->ct_ctx[evt_dat->immed_dat].flags = UNSOL_VALID;
} else
evt_dat->immed_dat = piocbq->iocb.ulpContext;
evt_dat->type = FC_REG_CT_EVENT;
list_add(&evt_dat->node, &evt->events_to_see);
if (evt_req_id == SLI_CT_ELX_LOOPBACK) {
wake_up_interruptible(&evt->wq);
lpfc_bsg_event_unref(evt);
break;
}
list_move(evt->events_to_see.prev, &evt->events_to_get);
lpfc_bsg_event_unref(evt);
job = evt->set_job;
evt->set_job = NULL;
if (job) {
job->reply->reply_payload_rcv_len = size;
/* make error code available to userspace */
job->reply->result = 0;
job->dd_data = NULL;
/* complete the job back to userspace */
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
job->job_done(job);
spin_lock_irqsave(&phba->ct_ev_lock, flags);
}
}
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
error_ct_unsol_exit:
if (!list_empty(&head))
list_del(&head);
if ((phba->sli_rev < LPFC_SLI_REV4) &&
(evt_req_id == SLI_CT_ELX_LOOPBACK))
return 0;
return 1;
}
/**
* lpfc_bsg_hba_set_event - process a SET_EVENT bsg vendor command
* @job: SET_EVENT fc_bsg_job
**/
static int
lpfc_bsg_hba_set_event(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct set_ct_event *event_req;
struct lpfc_bsg_event *evt;
int rc = 0;
struct bsg_job_data *dd_data = NULL;
uint32_t ev_mask;
unsigned long flags;
if (job->request_len <
sizeof(struct fc_bsg_request) + sizeof(struct set_ct_event)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2612 Received SET_CT_EVENT below minimum "
"size\n");
rc = -EINVAL;
goto job_error;
}
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (dd_data == NULL) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2734 Failed allocation of dd_data\n");
rc = -ENOMEM;
goto job_error;
}
event_req = (struct set_ct_event *)
job->request->rqst_data.h_vendor.vendor_cmd;
ev_mask = ((uint32_t)(unsigned long)event_req->type_mask &
FC_REG_EVENT_MASK);
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_for_each_entry(evt, &phba->ct_ev_waiters, node) {
if (evt->reg_id == event_req->ev_reg_id) {
lpfc_bsg_event_ref(evt);
evt->wait_time_stamp = jiffies;
break;
}
}
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
if (&evt->node == &phba->ct_ev_waiters) {
/* no event waiting struct yet - first call */
evt = lpfc_bsg_event_new(ev_mask, event_req->ev_reg_id,
event_req->ev_req_id);
if (!evt) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2617 Failed allocation of event "
"waiter\n");
rc = -ENOMEM;
goto job_error;
}
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_add(&evt->node, &phba->ct_ev_waiters);
lpfc_bsg_event_ref(evt);
evt->wait_time_stamp = jiffies;
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
}
spin_lock_irqsave(&phba->ct_ev_lock, flags);
evt->waiting = 1;
dd_data->type = TYPE_EVT;
dd_data->context_un.evt = evt;
evt->set_job = job; /* for unsolicited command */
job->dd_data = dd_data; /* for fc transport timeout callback*/
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return 0; /* call job done later */
job_error:
if (dd_data != NULL)
kfree(dd_data);
job->dd_data = NULL;
return rc;
}
/**
* lpfc_bsg_hba_get_event - process a GET_EVENT bsg vendor command
* @job: GET_EVENT fc_bsg_job
**/
static int
lpfc_bsg_hba_get_event(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct get_ct_event *event_req;
struct get_ct_event_reply *event_reply;
struct lpfc_bsg_event *evt;
struct event_data *evt_dat = NULL;
unsigned long flags;
uint32_t rc = 0;
if (job->request_len <
sizeof(struct fc_bsg_request) + sizeof(struct get_ct_event)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2613 Received GET_CT_EVENT request below "
"minimum size\n");
rc = -EINVAL;
goto job_error;
}
event_req = (struct get_ct_event *)
job->request->rqst_data.h_vendor.vendor_cmd;
event_reply = (struct get_ct_event_reply *)
job->reply->reply_data.vendor_reply.vendor_rsp;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_for_each_entry(evt, &phba->ct_ev_waiters, node) {
if (evt->reg_id == event_req->ev_reg_id) {
if (list_empty(&evt->events_to_get))
break;
lpfc_bsg_event_ref(evt);
evt->wait_time_stamp = jiffies;
evt_dat = list_entry(evt->events_to_get.prev,
struct event_data, node);
list_del(&evt_dat->node);
break;
}
}
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
/* The app may continue to ask for event data until it gets
* an error indicating that there isn't anymore
*/
if (evt_dat == NULL) {
job->reply->reply_payload_rcv_len = 0;
rc = -ENOENT;
goto job_error;
}
if (evt_dat->len > job->request_payload.payload_len) {
evt_dat->len = job->request_payload.payload_len;
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2618 Truncated event data at %d "
"bytes\n",
job->request_payload.payload_len);
}
event_reply->type = evt_dat->type;
event_reply->immed_data = evt_dat->immed_dat;
if (evt_dat->len > 0)
job->reply->reply_payload_rcv_len =
sg_copy_from_buffer(job->request_payload.sg_list,
job->request_payload.sg_cnt,
evt_dat->data, evt_dat->len);
else
job->reply->reply_payload_rcv_len = 0;
if (evt_dat) {
kfree(evt_dat->data);
kfree(evt_dat);
}
spin_lock_irqsave(&phba->ct_ev_lock, flags);
lpfc_bsg_event_unref(evt);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
job->dd_data = NULL;
job->reply->result = 0;
job->job_done(job);
return 0;
job_error:
job->dd_data = NULL;
job->reply->result = rc;
return rc;
}
/**
* lpfc_issue_ct_rsp_cmp - lpfc_issue_ct_rsp's completion handler
* @phba: Pointer to HBA context object.
* @cmdiocbq: Pointer to command iocb.
* @rspiocbq: Pointer to response iocb.
*
* This function is the completion handler for iocbs issued using
* lpfc_issue_ct_rsp_cmp function. This function is called by the
* ring event handler function without any lock held. This function
* can be called from both worker thread context and interrupt
* context. This function also can be called from other thread which
* cleans up the SLI layer objects.
* This function copy the contents of the response iocb to the
* response iocb memory object provided by the caller of
* lpfc_sli_issue_iocb_wait and then wakes up the thread which
* sleeps for the iocb completion.
**/
static void
lpfc_issue_ct_rsp_cmp(struct lpfc_hba *phba,
struct lpfc_iocbq *cmdiocbq,
struct lpfc_iocbq *rspiocbq)
{
struct bsg_job_data *dd_data;
struct fc_bsg_job *job;
IOCB_t *rsp;
struct lpfc_dmabuf *bmp;
struct lpfc_nodelist *ndlp;
unsigned long flags;
int rc = 0;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
dd_data = cmdiocbq->context2;
/* normal completion and timeout crossed paths, already done */
if (!dd_data) {
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
job = dd_data->context_un.iocb.set_job;
bmp = dd_data->context_un.iocb.bmp;
rsp = &rspiocbq->iocb;
ndlp = dd_data->context_un.iocb.ndlp;
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
if (rsp->ulpStatus) {
if (rsp->ulpStatus == IOSTAT_LOCAL_REJECT) {
switch (rsp->un.ulpWord[4] & 0xff) {
case IOERR_SEQUENCE_TIMEOUT:
rc = -ETIMEDOUT;
break;
case IOERR_INVALID_RPI:
rc = -EFAULT;
break;
default:
rc = -EACCES;
break;
}
} else
rc = -EACCES;
} else
job->reply->reply_payload_rcv_len =
rsp->un.genreq64.bdl.bdeSize;
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
lpfc_sli_release_iocbq(phba, cmdiocbq);
lpfc_nlp_put(ndlp);
kfree(bmp);
kfree(dd_data);
/* make error code available to userspace */
job->reply->result = rc;
job->dd_data = NULL;
/* complete the job back to userspace */
job->job_done(job);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
/**
* lpfc_issue_ct_rsp - issue a ct response
* @phba: Pointer to HBA context object.
* @job: Pointer to the job object.
* @tag: tag index value into the ports context exchange array.
* @bmp: Pointer to a dma buffer descriptor.
* @num_entry: Number of enties in the bde.
**/
static int
lpfc_issue_ct_rsp(struct lpfc_hba *phba, struct fc_bsg_job *job, uint32_t tag,
struct lpfc_dmabuf *bmp, int num_entry)
{
IOCB_t *icmd;
struct lpfc_iocbq *ctiocb = NULL;
int rc = 0;
struct lpfc_nodelist *ndlp = NULL;
struct bsg_job_data *dd_data;
uint32_t creg_val;
/* allocate our bsg tracking structure */
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2736 Failed allocation of dd_data\n");
rc = -ENOMEM;
goto no_dd_data;
}
/* Allocate buffer for command iocb */
ctiocb = lpfc_sli_get_iocbq(phba);
if (!ctiocb) {
rc = -ENOMEM;
goto no_ctiocb;
}
icmd = &ctiocb->iocb;
icmd->un.xseq64.bdl.ulpIoTag32 = 0;
icmd->un.xseq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
icmd->un.xseq64.bdl.addrLow = putPaddrLow(bmp->phys);
icmd->un.xseq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
icmd->un.xseq64.bdl.bdeSize = (num_entry * sizeof(struct ulp_bde64));
icmd->un.xseq64.w5.hcsw.Fctl = (LS | LA);
icmd->un.xseq64.w5.hcsw.Dfctl = 0;
icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_DD_SOL_CTL;
icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_CT;
/* Fill in rest of iocb */
icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CX;
icmd->ulpBdeCount = 1;
icmd->ulpLe = 1;
icmd->ulpClass = CLASS3;
if (phba->sli_rev == LPFC_SLI_REV4) {
/* Do not issue unsol response if oxid not marked as valid */
if (!(phba->ct_ctx[tag].flags & UNSOL_VALID)) {
rc = IOCB_ERROR;
goto issue_ct_rsp_exit;
}
icmd->ulpContext = phba->ct_ctx[tag].rxid;
icmd->unsli3.rcvsli3.ox_id = phba->ct_ctx[tag].oxid;
ndlp = lpfc_findnode_did(phba->pport, phba->ct_ctx[tag].SID);
if (!ndlp) {
lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
"2721 ndlp null for oxid %x SID %x\n",
icmd->ulpContext,
phba->ct_ctx[tag].SID);
rc = IOCB_ERROR;
goto issue_ct_rsp_exit;
}
/* Check if the ndlp is active */
if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)) {
rc = -IOCB_ERROR;
goto issue_ct_rsp_exit;
}
/* get a refernece count so the ndlp doesn't go away while
* we respond
*/
if (!lpfc_nlp_get(ndlp)) {
rc = -IOCB_ERROR;
goto issue_ct_rsp_exit;
}
icmd->un.ulpWord[3] =
phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
/* The exchange is done, mark the entry as invalid */
phba->ct_ctx[tag].flags &= ~UNSOL_VALID;
} else
icmd->ulpContext = (ushort) tag;
icmd->ulpTimeout = phba->fc_ratov * 2;
/* Xmit CT response on exchange <xid> */
lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
"2722 Xmit CT response on exchange x%x Data: x%x x%x x%x\n",
icmd->ulpContext, icmd->ulpIoTag, tag, phba->link_state);
ctiocb->iocb_cmpl = NULL;
ctiocb->iocb_flag |= LPFC_IO_LIBDFC;
ctiocb->vport = phba->pport;
ctiocb->context3 = bmp;
ctiocb->iocb_cmpl = lpfc_issue_ct_rsp_cmp;
ctiocb->context2 = dd_data;
ctiocb->context1 = ndlp;
dd_data->type = TYPE_IOCB;
dd_data->context_un.iocb.cmdiocbq = ctiocb;
dd_data->context_un.iocb.rspiocbq = NULL;
dd_data->context_un.iocb.set_job = job;
dd_data->context_un.iocb.bmp = bmp;
dd_data->context_un.iocb.ndlp = ndlp;
if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
if (lpfc_readl(phba->HCregaddr, &creg_val)) {
rc = -IOCB_ERROR;
goto issue_ct_rsp_exit;
}
creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
writel(creg_val, phba->HCregaddr);
readl(phba->HCregaddr); /* flush */
}
rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
if (rc == IOCB_SUCCESS)
return 0; /* done for now */
issue_ct_rsp_exit:
lpfc_sli_release_iocbq(phba, ctiocb);
no_ctiocb:
kfree(dd_data);
no_dd_data:
return rc;
}
/**
* lpfc_bsg_send_mgmt_rsp - process a SEND_MGMT_RESP bsg vendor command
* @job: SEND_MGMT_RESP fc_bsg_job
**/
static int
lpfc_bsg_send_mgmt_rsp(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct send_mgmt_resp *mgmt_resp = (struct send_mgmt_resp *)
job->request->rqst_data.h_vendor.vendor_cmd;
struct ulp_bde64 *bpl;
struct lpfc_dmabuf *bmp = NULL;
struct scatterlist *sgel = NULL;
int request_nseg;
int numbde;
dma_addr_t busaddr;
uint32_t tag = mgmt_resp->tag;
unsigned long reqbfrcnt =
(unsigned long)job->request_payload.payload_len;
int rc = 0;
/* in case no data is transferred */
job->reply->reply_payload_rcv_len = 0;
if (!reqbfrcnt || (reqbfrcnt > (80 * BUF_SZ_4K))) {
rc = -ERANGE;
goto send_mgmt_rsp_exit;
}
bmp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (!bmp) {
rc = -ENOMEM;
goto send_mgmt_rsp_exit;
}
bmp->virt = lpfc_mbuf_alloc(phba, 0, &bmp->phys);
if (!bmp->virt) {
rc = -ENOMEM;
goto send_mgmt_rsp_free_bmp;
}
INIT_LIST_HEAD(&bmp->list);
bpl = (struct ulp_bde64 *) bmp->virt;
request_nseg = pci_map_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
for_each_sg(job->request_payload.sg_list, sgel, request_nseg, numbde) {
busaddr = sg_dma_address(sgel);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
bpl->tus.f.bdeSize = sg_dma_len(sgel);
bpl->tus.w = cpu_to_le32(bpl->tus.w);
bpl->addrLow = cpu_to_le32(putPaddrLow(busaddr));
bpl->addrHigh = cpu_to_le32(putPaddrHigh(busaddr));
bpl++;
}
rc = lpfc_issue_ct_rsp(phba, job, tag, bmp, request_nseg);
if (rc == IOCB_SUCCESS)
return 0; /* done for now */
/* TBD need to handle a timeout */
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
rc = -EACCES;
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
send_mgmt_rsp_free_bmp:
kfree(bmp);
send_mgmt_rsp_exit:
/* make error code available to userspace */
job->reply->result = rc;
job->dd_data = NULL;
return rc;
}
/**
* lpfc_bsg_diag_mode_enter - process preparing into device diag loopback mode
* @phba: Pointer to HBA context object.
*
* This function is responsible for preparing driver for diag loopback
* on device.
*/
static int
lpfc_bsg_diag_mode_enter(struct lpfc_hba *phba)
{
struct lpfc_vport **vports;
struct Scsi_Host *shost;
struct lpfc_sli *psli;
struct lpfc_sli_ring *pring;
int i = 0;
psli = &phba->sli;
if (!psli)
return -ENODEV;
pring = &psli->ring[LPFC_FCP_RING];
if (!pring)
return -ENODEV;
if ((phba->link_state == LPFC_HBA_ERROR) ||
(psli->sli_flag & LPFC_BLOCK_MGMT_IO) ||
(!(psli->sli_flag & LPFC_SLI_ACTIVE)))
return -EACCES;
vports = lpfc_create_vport_work_array(phba);
if (vports) {
for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
shost = lpfc_shost_from_vport(vports[i]);
scsi_block_requests(shost);
}
lpfc_destroy_vport_work_array(phba, vports);
} else {
shost = lpfc_shost_from_vport(phba->pport);
scsi_block_requests(shost);
}
while (pring->txcmplq_cnt) {
if (i++ > 500) /* wait up to 5 seconds */
break;
msleep(10);
}
return 0;
}
/**
* lpfc_bsg_diag_mode_exit - exit process from device diag loopback mode
* @phba: Pointer to HBA context object.
*
* This function is responsible for driver exit processing of setting up
* diag loopback mode on device.
*/
static void
lpfc_bsg_diag_mode_exit(struct lpfc_hba *phba)
{
struct Scsi_Host *shost;
struct lpfc_vport **vports;
int i;
vports = lpfc_create_vport_work_array(phba);
if (vports) {
for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
shost = lpfc_shost_from_vport(vports[i]);
scsi_unblock_requests(shost);
}
lpfc_destroy_vport_work_array(phba, vports);
} else {
shost = lpfc_shost_from_vport(phba->pport);
scsi_unblock_requests(shost);
}
return;
}
/**
* lpfc_sli3_bsg_diag_loopback_mode - process an sli3 bsg vendor command
* @phba: Pointer to HBA context object.
* @job: LPFC_BSG_VENDOR_DIAG_MODE
*
* This function is responsible for placing an sli3 port into diagnostic
* loopback mode in order to perform a diagnostic loopback test.
* All new scsi requests are blocked, a small delay is used to allow the
* scsi requests to complete then the link is brought down. If the link is
* is placed in loopback mode then scsi requests are again allowed
* so the scsi mid-layer doesn't give up on the port.
* All of this is done in-line.
*/
static int
lpfc_sli3_bsg_diag_loopback_mode(struct lpfc_hba *phba, struct fc_bsg_job *job)
{
struct diag_mode_set *loopback_mode;
uint32_t link_flags;
uint32_t timeout;
LPFC_MBOXQ_t *pmboxq = NULL;
int mbxstatus = MBX_SUCCESS;
int i = 0;
int rc = 0;
/* no data to return just the return code */
job->reply->reply_payload_rcv_len = 0;
if (job->request_len < sizeof(struct fc_bsg_request) +
sizeof(struct diag_mode_set)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2738 Received DIAG MODE request size:%d "
"below the minimum size:%d\n",
job->request_len,
(int)(sizeof(struct fc_bsg_request) +
sizeof(struct diag_mode_set)));
rc = -EINVAL;
goto job_error;
}
rc = lpfc_bsg_diag_mode_enter(phba);
if (rc)
goto job_error;
/* bring the link to diagnostic mode */
loopback_mode = (struct diag_mode_set *)
job->request->rqst_data.h_vendor.vendor_cmd;
link_flags = loopback_mode->type;
timeout = loopback_mode->timeout * 100;
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq) {
rc = -ENOMEM;
goto loopback_mode_exit;
}
memset((void *)pmboxq, 0, sizeof(LPFC_MBOXQ_t));
pmboxq->u.mb.mbxCommand = MBX_DOWN_LINK;
pmboxq->u.mb.mbxOwner = OWN_HOST;
mbxstatus = lpfc_sli_issue_mbox_wait(phba, pmboxq, LPFC_MBOX_TMO);
if ((mbxstatus == MBX_SUCCESS) && (pmboxq->u.mb.mbxStatus == 0)) {
/* wait for link down before proceeding */
i = 0;
while (phba->link_state != LPFC_LINK_DOWN) {
if (i++ > timeout) {
rc = -ETIMEDOUT;
goto loopback_mode_exit;
}
msleep(10);
}
memset((void *)pmboxq, 0, sizeof(LPFC_MBOXQ_t));
if (link_flags == INTERNAL_LOOP_BACK)
pmboxq->u.mb.un.varInitLnk.link_flags = FLAGS_LOCAL_LB;
else
pmboxq->u.mb.un.varInitLnk.link_flags =
FLAGS_TOPOLOGY_MODE_LOOP;
pmboxq->u.mb.mbxCommand = MBX_INIT_LINK;
pmboxq->u.mb.mbxOwner = OWN_HOST;
mbxstatus = lpfc_sli_issue_mbox_wait(phba, pmboxq,
LPFC_MBOX_TMO);
if ((mbxstatus != MBX_SUCCESS) || (pmboxq->u.mb.mbxStatus))
rc = -ENODEV;
else {
spin_lock_irq(&phba->hbalock);
phba->link_flag |= LS_LOOPBACK_MODE;
spin_unlock_irq(&phba->hbalock);
/* wait for the link attention interrupt */
msleep(100);
i = 0;
while (phba->link_state != LPFC_HBA_READY) {
if (i++ > timeout) {
rc = -ETIMEDOUT;
break;
}
msleep(10);
}
}
} else
rc = -ENODEV;
loopback_mode_exit:
lpfc_bsg_diag_mode_exit(phba);
/*
* Let SLI layer release mboxq if mbox command completed after timeout.
*/
if (pmboxq && mbxstatus != MBX_TIMEOUT)
mempool_free(pmboxq, phba->mbox_mem_pool);
job_error:
/* make error code available to userspace */
job->reply->result = rc;
/* complete the job back to userspace if no error */
if (rc == 0)
job->job_done(job);
return rc;
}
/**
* lpfc_sli4_bsg_set_link_diag_state - set sli4 link diag state
* @phba: Pointer to HBA context object.
* @diag: Flag for set link to diag or nomral operation state.
*
* This function is responsible for issuing a sli4 mailbox command for setting
* link to either diag state or normal operation state.
*/
static int
lpfc_sli4_bsg_set_link_diag_state(struct lpfc_hba *phba, uint32_t diag)
{
LPFC_MBOXQ_t *pmboxq;
struct lpfc_mbx_set_link_diag_state *link_diag_state;
uint32_t req_len, alloc_len;
int mbxstatus = MBX_SUCCESS, rc;
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq)
return -ENOMEM;
req_len = (sizeof(struct lpfc_mbx_set_link_diag_state) -
sizeof(struct lpfc_sli4_cfg_mhdr));
alloc_len = lpfc_sli4_config(phba, pmboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
LPFC_MBOX_OPCODE_FCOE_LINK_DIAG_STATE,
req_len, LPFC_SLI4_MBX_EMBED);
if (alloc_len != req_len) {
rc = -ENOMEM;
goto link_diag_state_set_out;
}
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3128 Set link to diagnostic state:x%x (x%x/x%x)\n",
diag, phba->sli4_hba.lnk_info.lnk_tp,
phba->sli4_hba.lnk_info.lnk_no);
link_diag_state = &pmboxq->u.mqe.un.link_diag_state;
bf_set(lpfc_mbx_set_diag_state_link_num, &link_diag_state->u.req,
phba->sli4_hba.lnk_info.lnk_no);
bf_set(lpfc_mbx_set_diag_state_link_type, &link_diag_state->u.req,
phba->sli4_hba.lnk_info.lnk_tp);
if (diag)
bf_set(lpfc_mbx_set_diag_state_diag,
&link_diag_state->u.req, 1);
else
bf_set(lpfc_mbx_set_diag_state_diag,
&link_diag_state->u.req, 0);
mbxstatus = lpfc_sli_issue_mbox_wait(phba, pmboxq, LPFC_MBOX_TMO);
if ((mbxstatus == MBX_SUCCESS) && (pmboxq->u.mb.mbxStatus == 0))
rc = 0;
else
rc = -ENODEV;
link_diag_state_set_out:
if (pmboxq && (mbxstatus != MBX_TIMEOUT))
mempool_free(pmboxq, phba->mbox_mem_pool);
return rc;
}
/**
* lpfc_sli4_bsg_set_internal_loopback - set sli4 internal loopback diagnostic
* @phba: Pointer to HBA context object.
*
* This function is responsible for issuing a sli4 mailbox command for setting
* up internal loopback diagnostic.
*/
static int
lpfc_sli4_bsg_set_internal_loopback(struct lpfc_hba *phba)
{
LPFC_MBOXQ_t *pmboxq;
uint32_t req_len, alloc_len;
struct lpfc_mbx_set_link_diag_loopback *link_diag_loopback;
int mbxstatus = MBX_SUCCESS, rc = 0;
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq)
return -ENOMEM;
req_len = (sizeof(struct lpfc_mbx_set_link_diag_loopback) -
sizeof(struct lpfc_sli4_cfg_mhdr));
alloc_len = lpfc_sli4_config(phba, pmboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
LPFC_MBOX_OPCODE_FCOE_LINK_DIAG_LOOPBACK,
req_len, LPFC_SLI4_MBX_EMBED);
if (alloc_len != req_len) {
mempool_free(pmboxq, phba->mbox_mem_pool);
return -ENOMEM;
}
link_diag_loopback = &pmboxq->u.mqe.un.link_diag_loopback;
bf_set(lpfc_mbx_set_diag_state_link_num,
&link_diag_loopback->u.req, phba->sli4_hba.lnk_info.lnk_no);
bf_set(lpfc_mbx_set_diag_state_link_type,
&link_diag_loopback->u.req, phba->sli4_hba.lnk_info.lnk_tp);
bf_set(lpfc_mbx_set_diag_lpbk_type, &link_diag_loopback->u.req,
LPFC_DIAG_LOOPBACK_TYPE_INTERNAL);
mbxstatus = lpfc_sli_issue_mbox_wait(phba, pmboxq, LPFC_MBOX_TMO);
if ((mbxstatus != MBX_SUCCESS) || (pmboxq->u.mb.mbxStatus)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"3127 Failed setup loopback mode mailbox "
"command, rc:x%x, status:x%x\n", mbxstatus,
pmboxq->u.mb.mbxStatus);
rc = -ENODEV;
}
if (pmboxq && (mbxstatus != MBX_TIMEOUT))
mempool_free(pmboxq, phba->mbox_mem_pool);
return rc;
}
/**
* lpfc_sli4_diag_fcport_reg_setup - setup port registrations for diagnostic
* @phba: Pointer to HBA context object.
*
* This function set up SLI4 FC port registrations for diagnostic run, which
* includes all the rpis, vfi, and also vpi.
*/
static int
lpfc_sli4_diag_fcport_reg_setup(struct lpfc_hba *phba)
{
int rc;
if (phba->pport->fc_flag & FC_VFI_REGISTERED) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"3136 Port still had vfi registered: "
"mydid:x%x, fcfi:%d, vfi:%d, vpi:%d\n",
phba->pport->fc_myDID, phba->fcf.fcfi,
phba->sli4_hba.vfi_ids[phba->pport->vfi],
phba->vpi_ids[phba->pport->vpi]);
return -EINVAL;
}
rc = lpfc_issue_reg_vfi(phba->pport);
return rc;
}
/**
* lpfc_sli4_bsg_diag_loopback_mode - process an sli4 bsg vendor command
* @phba: Pointer to HBA context object.
* @job: LPFC_BSG_VENDOR_DIAG_MODE
*
* This function is responsible for placing an sli4 port into diagnostic
* loopback mode in order to perform a diagnostic loopback test.
*/
static int
lpfc_sli4_bsg_diag_loopback_mode(struct lpfc_hba *phba, struct fc_bsg_job *job)
{
struct diag_mode_set *loopback_mode;
uint32_t link_flags, timeout;
int i, rc = 0;
/* no data to return just the return code */
job->reply->reply_payload_rcv_len = 0;
if (job->request_len < sizeof(struct fc_bsg_request) +
sizeof(struct diag_mode_set)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"3011 Received DIAG MODE request size:%d "
"below the minimum size:%d\n",
job->request_len,
(int)(sizeof(struct fc_bsg_request) +
sizeof(struct diag_mode_set)));
rc = -EINVAL;
goto job_error;
}
rc = lpfc_bsg_diag_mode_enter(phba);
if (rc)
goto job_error;
/* indicate we are in loobpack diagnostic mode */
spin_lock_irq(&phba->hbalock);
phba->link_flag |= LS_LOOPBACK_MODE;
spin_unlock_irq(&phba->hbalock);
/* reset port to start frome scratch */
rc = lpfc_selective_reset(phba);
if (rc)
goto job_error;
/* bring the link to diagnostic mode */
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3129 Bring link to diagnostic state.\n");
loopback_mode = (struct diag_mode_set *)
job->request->rqst_data.h_vendor.vendor_cmd;
link_flags = loopback_mode->type;
timeout = loopback_mode->timeout * 100;
rc = lpfc_sli4_bsg_set_link_diag_state(phba, 1);
if (rc) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"3130 Failed to bring link to diagnostic "
"state, rc:x%x\n", rc);
goto loopback_mode_exit;
}
/* wait for link down before proceeding */
i = 0;
while (phba->link_state != LPFC_LINK_DOWN) {
if (i++ > timeout) {
rc = -ETIMEDOUT;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3131 Timeout waiting for link to "
"diagnostic mode, timeout:%d ms\n",
timeout * 10);
goto loopback_mode_exit;
}
msleep(10);
}
/* set up loopback mode */
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3132 Set up loopback mode:x%x\n", link_flags);
if (link_flags == INTERNAL_LOOP_BACK)
rc = lpfc_sli4_bsg_set_internal_loopback(phba);
else if (link_flags == EXTERNAL_LOOP_BACK)
rc = lpfc_hba_init_link_fc_topology(phba,
FLAGS_TOPOLOGY_MODE_PT_PT,
MBX_NOWAIT);
else {
rc = -EINVAL;
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"3141 Loopback mode:x%x not supported\n",
link_flags);
goto loopback_mode_exit;
}
if (!rc) {
/* wait for the link attention interrupt */
msleep(100);
i = 0;
while (phba->link_state < LPFC_LINK_UP) {
if (i++ > timeout) {
rc = -ETIMEDOUT;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3137 Timeout waiting for link up "
"in loopback mode, timeout:%d ms\n",
timeout * 10);
break;
}
msleep(10);
}
}
/* port resource registration setup for loopback diagnostic */
if (!rc) {
/* set up a none zero myDID for loopback test */
phba->pport->fc_myDID = 1;
rc = lpfc_sli4_diag_fcport_reg_setup(phba);
} else
goto loopback_mode_exit;
if (!rc) {
/* wait for the port ready */
msleep(100);
i = 0;
while (phba->link_state != LPFC_HBA_READY) {
if (i++ > timeout) {
rc = -ETIMEDOUT;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3133 Timeout waiting for port "
"loopback mode ready, timeout:%d ms\n",
timeout * 10);
break;
}
msleep(10);
}
}
loopback_mode_exit:
/* clear loopback diagnostic mode */
if (rc) {
spin_lock_irq(&phba->hbalock);
phba->link_flag &= ~LS_LOOPBACK_MODE;
spin_unlock_irq(&phba->hbalock);
}
lpfc_bsg_diag_mode_exit(phba);
job_error:
/* make error code available to userspace */
job->reply->result = rc;
/* complete the job back to userspace if no error */
if (rc == 0)
job->job_done(job);
return rc;
}
/**
* lpfc_bsg_diag_loopback_mode - bsg vendor command for diag loopback mode
* @job: LPFC_BSG_VENDOR_DIAG_MODE
*
* This function is responsible for responding to check and dispatch bsg diag
* command from the user to proper driver action routines.
*/
static int
lpfc_bsg_diag_loopback_mode(struct fc_bsg_job *job)
{
struct Scsi_Host *shost;
struct lpfc_vport *vport;
struct lpfc_hba *phba;
int rc;
shost = job->shost;
if (!shost)
return -ENODEV;
vport = (struct lpfc_vport *)job->shost->hostdata;
if (!vport)
return -ENODEV;
phba = vport->phba;
if (!phba)
return -ENODEV;
if (phba->sli_rev < LPFC_SLI_REV4)
rc = lpfc_sli3_bsg_diag_loopback_mode(phba, job);
else if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
LPFC_SLI_INTF_IF_TYPE_2)
rc = lpfc_sli4_bsg_diag_loopback_mode(phba, job);
else
rc = -ENODEV;
return rc;
}
/**
* lpfc_sli4_bsg_diag_mode_end - sli4 bsg vendor command for ending diag mode
* @job: LPFC_BSG_VENDOR_DIAG_MODE_END
*
* This function is responsible for responding to check and dispatch bsg diag
* command from the user to proper driver action routines.
*/
static int
lpfc_sli4_bsg_diag_mode_end(struct fc_bsg_job *job)
{
struct Scsi_Host *shost;
struct lpfc_vport *vport;
struct lpfc_hba *phba;
struct diag_mode_set *loopback_mode_end_cmd;
uint32_t timeout;
int rc, i;
shost = job->shost;
if (!shost)
return -ENODEV;
vport = (struct lpfc_vport *)job->shost->hostdata;
if (!vport)
return -ENODEV;
phba = vport->phba;
if (!phba)
return -ENODEV;
if (phba->sli_rev < LPFC_SLI_REV4)
return -ENODEV;
if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) !=
LPFC_SLI_INTF_IF_TYPE_2)
return -ENODEV;
/* clear loopback diagnostic mode */
spin_lock_irq(&phba->hbalock);
phba->link_flag &= ~LS_LOOPBACK_MODE;
spin_unlock_irq(&phba->hbalock);
loopback_mode_end_cmd = (struct diag_mode_set *)
job->request->rqst_data.h_vendor.vendor_cmd;
timeout = loopback_mode_end_cmd->timeout * 100;
rc = lpfc_sli4_bsg_set_link_diag_state(phba, 0);
if (rc) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"3139 Failed to bring link to diagnostic "
"state, rc:x%x\n", rc);
goto loopback_mode_end_exit;
}
/* wait for link down before proceeding */
i = 0;
while (phba->link_state != LPFC_LINK_DOWN) {
if (i++ > timeout) {
rc = -ETIMEDOUT;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3140 Timeout waiting for link to "
"diagnostic mode_end, timeout:%d ms\n",
timeout * 10);
/* there is nothing much we can do here */
break;
}
msleep(10);
}
/* reset port resource registrations */
rc = lpfc_selective_reset(phba);
phba->pport->fc_myDID = 0;
loopback_mode_end_exit:
/* make return code available to userspace */
job->reply->result = rc;
/* complete the job back to userspace if no error */
if (rc == 0)
job->job_done(job);
return rc;
}
/**
* lpfc_sli4_bsg_link_diag_test - sli4 bsg vendor command for diag link test
* @job: LPFC_BSG_VENDOR_DIAG_LINK_TEST
*
* This function is to perform SLI4 diag link test request from the user
* applicaiton.
*/
static int
lpfc_sli4_bsg_link_diag_test(struct fc_bsg_job *job)
{
struct Scsi_Host *shost;
struct lpfc_vport *vport;
struct lpfc_hba *phba;
LPFC_MBOXQ_t *pmboxq;
struct sli4_link_diag *link_diag_test_cmd;
uint32_t req_len, alloc_len;
uint32_t timeout;
struct lpfc_mbx_run_link_diag_test *run_link_diag_test;
union lpfc_sli4_cfg_shdr *shdr;
uint32_t shdr_status, shdr_add_status;
struct diag_status *diag_status_reply;
int mbxstatus, rc = 0;
shost = job->shost;
if (!shost) {
rc = -ENODEV;
goto job_error;
}
vport = (struct lpfc_vport *)job->shost->hostdata;
if (!vport) {
rc = -ENODEV;
goto job_error;
}
phba = vport->phba;
if (!phba) {
rc = -ENODEV;
goto job_error;
}
if (phba->sli_rev < LPFC_SLI_REV4) {
rc = -ENODEV;
goto job_error;
}
if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) !=
LPFC_SLI_INTF_IF_TYPE_2) {
rc = -ENODEV;
goto job_error;
}
if (job->request_len < sizeof(struct fc_bsg_request) +
sizeof(struct sli4_link_diag)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"3013 Received LINK DIAG TEST request "
" size:%d below the minimum size:%d\n",
job->request_len,
(int)(sizeof(struct fc_bsg_request) +
sizeof(struct sli4_link_diag)));
rc = -EINVAL;
goto job_error;
}
rc = lpfc_bsg_diag_mode_enter(phba);
if (rc)
goto job_error;
link_diag_test_cmd = (struct sli4_link_diag *)
job->request->rqst_data.h_vendor.vendor_cmd;
timeout = link_diag_test_cmd->timeout * 100;
rc = lpfc_sli4_bsg_set_link_diag_state(phba, 1);
if (rc)
goto job_error;
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq) {
rc = -ENOMEM;
goto link_diag_test_exit;
}
req_len = (sizeof(struct lpfc_mbx_set_link_diag_state) -
sizeof(struct lpfc_sli4_cfg_mhdr));
alloc_len = lpfc_sli4_config(phba, pmboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
LPFC_MBOX_OPCODE_FCOE_LINK_DIAG_STATE,
req_len, LPFC_SLI4_MBX_EMBED);
if (alloc_len != req_len) {
rc = -ENOMEM;
goto link_diag_test_exit;
}
run_link_diag_test = &pmboxq->u.mqe.un.link_diag_test;
bf_set(lpfc_mbx_run_diag_test_link_num, &run_link_diag_test->u.req,
phba->sli4_hba.lnk_info.lnk_no);
bf_set(lpfc_mbx_run_diag_test_link_type, &run_link_diag_test->u.req,
phba->sli4_hba.lnk_info.lnk_tp);
bf_set(lpfc_mbx_run_diag_test_test_id, &run_link_diag_test->u.req,
link_diag_test_cmd->test_id);
bf_set(lpfc_mbx_run_diag_test_loops, &run_link_diag_test->u.req,
link_diag_test_cmd->loops);
bf_set(lpfc_mbx_run_diag_test_test_ver, &run_link_diag_test->u.req,
link_diag_test_cmd->test_version);
bf_set(lpfc_mbx_run_diag_test_err_act, &run_link_diag_test->u.req,
link_diag_test_cmd->error_action);
mbxstatus = lpfc_sli_issue_mbox(phba, pmboxq, MBX_POLL);
shdr = (union lpfc_sli4_cfg_shdr *)
&pmboxq->u.mqe.un.sli4_config.header.cfg_shdr;
shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
if (shdr_status || shdr_add_status || mbxstatus) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"3010 Run link diag test mailbox failed with "
"mbx_status x%x status x%x, add_status x%x\n",
mbxstatus, shdr_status, shdr_add_status);
}
diag_status_reply = (struct diag_status *)
job->reply->reply_data.vendor_reply.vendor_rsp;
if (job->reply_len <
sizeof(struct fc_bsg_request) + sizeof(struct diag_status)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"3012 Received Run link diag test reply "
"below minimum size (%d): reply_len:%d\n",
(int)(sizeof(struct fc_bsg_request) +
sizeof(struct diag_status)),
job->reply_len);
rc = -EINVAL;
goto job_error;
}
diag_status_reply->mbox_status = mbxstatus;
diag_status_reply->shdr_status = shdr_status;
diag_status_reply->shdr_add_status = shdr_add_status;
link_diag_test_exit:
rc = lpfc_sli4_bsg_set_link_diag_state(phba, 0);
if (pmboxq)
mempool_free(pmboxq, phba->mbox_mem_pool);
lpfc_bsg_diag_mode_exit(phba);
job_error:
/* make error code available to userspace */
job->reply->result = rc;
/* complete the job back to userspace if no error */
if (rc == 0)
job->job_done(job);
return rc;
}
/**
* lpfcdiag_loop_self_reg - obtains a remote port login id
* @phba: Pointer to HBA context object
* @rpi: Pointer to a remote port login id
*
* This function obtains a remote port login id so the diag loopback test
* can send and receive its own unsolicited CT command.
**/
static int lpfcdiag_loop_self_reg(struct lpfc_hba *phba, uint16_t *rpi)
{
LPFC_MBOXQ_t *mbox;
struct lpfc_dmabuf *dmabuff;
int status;
mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!mbox)
return -ENOMEM;
if (phba->sli_rev < LPFC_SLI_REV4)
status = lpfc_reg_rpi(phba, 0, phba->pport->fc_myDID,
(uint8_t *)&phba->pport->fc_sparam,
mbox, *rpi);
else {
*rpi = lpfc_sli4_alloc_rpi(phba);
status = lpfc_reg_rpi(phba, phba->pport->vpi,
phba->pport->fc_myDID,
(uint8_t *)&phba->pport->fc_sparam,
mbox, *rpi);
}
if (status) {
mempool_free(mbox, phba->mbox_mem_pool);
if (phba->sli_rev == LPFC_SLI_REV4)
lpfc_sli4_free_rpi(phba, *rpi);
return -ENOMEM;
}
dmabuff = (struct lpfc_dmabuf *) mbox->context1;
mbox->context1 = NULL;
mbox->context2 = NULL;
status = lpfc_sli_issue_mbox_wait(phba, mbox, LPFC_MBOX_TMO);
if ((status != MBX_SUCCESS) || (mbox->u.mb.mbxStatus)) {
lpfc_mbuf_free(phba, dmabuff->virt, dmabuff->phys);
kfree(dmabuff);
if (status != MBX_TIMEOUT)
mempool_free(mbox, phba->mbox_mem_pool);
if (phba->sli_rev == LPFC_SLI_REV4)
lpfc_sli4_free_rpi(phba, *rpi);
return -ENODEV;
}
if (phba->sli_rev < LPFC_SLI_REV4)
*rpi = mbox->u.mb.un.varWords[0];
lpfc_mbuf_free(phba, dmabuff->virt, dmabuff->phys);
kfree(dmabuff);
mempool_free(mbox, phba->mbox_mem_pool);
return 0;
}
/**
* lpfcdiag_loop_self_unreg - unregs from the rpi
* @phba: Pointer to HBA context object
* @rpi: Remote port login id
*
* This function unregisters the rpi obtained in lpfcdiag_loop_self_reg
**/
static int lpfcdiag_loop_self_unreg(struct lpfc_hba *phba, uint16_t rpi)
{
LPFC_MBOXQ_t *mbox;
int status;
/* Allocate mboxq structure */
mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (mbox == NULL)
return -ENOMEM;
if (phba->sli_rev < LPFC_SLI_REV4)
lpfc_unreg_login(phba, 0, rpi, mbox);
else
lpfc_unreg_login(phba, phba->pport->vpi,
phba->sli4_hba.rpi_ids[rpi], mbox);
status = lpfc_sli_issue_mbox_wait(phba, mbox, LPFC_MBOX_TMO);
if ((status != MBX_SUCCESS) || (mbox->u.mb.mbxStatus)) {
if (status != MBX_TIMEOUT)
mempool_free(mbox, phba->mbox_mem_pool);
return -EIO;
}
mempool_free(mbox, phba->mbox_mem_pool);
if (phba->sli_rev == LPFC_SLI_REV4)
lpfc_sli4_free_rpi(phba, rpi);
return 0;
}
/**
* lpfcdiag_loop_get_xri - obtains the transmit and receive ids
* @phba: Pointer to HBA context object
* @rpi: Remote port login id
* @txxri: Pointer to transmit exchange id
* @rxxri: Pointer to response exchabge id
*
* This function obtains the transmit and receive ids required to send
* an unsolicited ct command with a payload. A special lpfc FsType and CmdRsp
* flags are used to the unsolicted response handler is able to process
* the ct command sent on the same port.
**/
static int lpfcdiag_loop_get_xri(struct lpfc_hba *phba, uint16_t rpi,
uint16_t *txxri, uint16_t * rxxri)
{
struct lpfc_bsg_event *evt;
struct lpfc_iocbq *cmdiocbq, *rspiocbq;
IOCB_t *cmd, *rsp;
struct lpfc_dmabuf *dmabuf;
struct ulp_bde64 *bpl = NULL;
struct lpfc_sli_ct_request *ctreq = NULL;
int ret_val = 0;
int time_left;
int iocb_stat = 0;
unsigned long flags;
*txxri = 0;
*rxxri = 0;
evt = lpfc_bsg_event_new(FC_REG_CT_EVENT, current->pid,
SLI_CT_ELX_LOOPBACK);
if (!evt)
return -ENOMEM;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_add(&evt->node, &phba->ct_ev_waiters);
lpfc_bsg_event_ref(evt);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
cmdiocbq = lpfc_sli_get_iocbq(phba);
rspiocbq = lpfc_sli_get_iocbq(phba);
dmabuf = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (dmabuf) {
dmabuf->virt = lpfc_mbuf_alloc(phba, 0, &dmabuf->phys);
if (dmabuf->virt) {
INIT_LIST_HEAD(&dmabuf->list);
bpl = (struct ulp_bde64 *) dmabuf->virt;
memset(bpl, 0, sizeof(*bpl));
ctreq = (struct lpfc_sli_ct_request *)(bpl + 1);
bpl->addrHigh =
le32_to_cpu(putPaddrHigh(dmabuf->phys +
sizeof(*bpl)));
bpl->addrLow =
le32_to_cpu(putPaddrLow(dmabuf->phys +
sizeof(*bpl)));
bpl->tus.f.bdeFlags = 0;
bpl->tus.f.bdeSize = ELX_LOOPBACK_HEADER_SZ;
bpl->tus.w = le32_to_cpu(bpl->tus.w);
}
}
if (cmdiocbq == NULL || rspiocbq == NULL ||
dmabuf == NULL || bpl == NULL || ctreq == NULL ||
dmabuf->virt == NULL) {
ret_val = -ENOMEM;
goto err_get_xri_exit;
}
cmd = &cmdiocbq->iocb;
rsp = &rspiocbq->iocb;
memset(ctreq, 0, ELX_LOOPBACK_HEADER_SZ);
ctreq->RevisionId.bits.Revision = SLI_CT_REVISION;
ctreq->RevisionId.bits.InId = 0;
ctreq->FsType = SLI_CT_ELX_LOOPBACK;
ctreq->FsSubType = 0;
ctreq->CommandResponse.bits.CmdRsp = ELX_LOOPBACK_XRI_SETUP;
ctreq->CommandResponse.bits.Size = 0;
cmd->un.xseq64.bdl.addrHigh = putPaddrHigh(dmabuf->phys);
cmd->un.xseq64.bdl.addrLow = putPaddrLow(dmabuf->phys);
cmd->un.xseq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
cmd->un.xseq64.bdl.bdeSize = sizeof(*bpl);
cmd->un.xseq64.w5.hcsw.Fctl = LA;
cmd->un.xseq64.w5.hcsw.Dfctl = 0;
cmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
cmd->un.xseq64.w5.hcsw.Type = FC_TYPE_CT;
cmd->ulpCommand = CMD_XMIT_SEQUENCE64_CR;
cmd->ulpBdeCount = 1;
cmd->ulpLe = 1;
cmd->ulpClass = CLASS3;
cmd->ulpContext = rpi;
cmdiocbq->iocb_flag |= LPFC_IO_LIBDFC;
cmdiocbq->vport = phba->pport;
iocb_stat = lpfc_sli_issue_iocb_wait(phba, LPFC_ELS_RING, cmdiocbq,
rspiocbq,
(phba->fc_ratov * 2)
+ LPFC_DRVR_TIMEOUT);
if (iocb_stat) {
ret_val = -EIO;
goto err_get_xri_exit;
}
*txxri = rsp->ulpContext;
evt->waiting = 1;
evt->wait_time_stamp = jiffies;
time_left = wait_event_interruptible_timeout(
evt->wq, !list_empty(&evt->events_to_see),
((phba->fc_ratov * 2) + LPFC_DRVR_TIMEOUT) * HZ);
if (list_empty(&evt->events_to_see))
ret_val = (time_left) ? -EINTR : -ETIMEDOUT;
else {
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_move(evt->events_to_see.prev, &evt->events_to_get);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
*rxxri = (list_entry(evt->events_to_get.prev,
typeof(struct event_data),
node))->immed_dat;
}
evt->waiting = 0;
err_get_xri_exit:
spin_lock_irqsave(&phba->ct_ev_lock, flags);
lpfc_bsg_event_unref(evt); /* release ref */
lpfc_bsg_event_unref(evt); /* delete */
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
if (dmabuf) {
if (dmabuf->virt)
lpfc_mbuf_free(phba, dmabuf->virt, dmabuf->phys);
kfree(dmabuf);
}
if (cmdiocbq && (iocb_stat != IOCB_TIMEDOUT))
lpfc_sli_release_iocbq(phba, cmdiocbq);
if (rspiocbq)
lpfc_sli_release_iocbq(phba, rspiocbq);
return ret_val;
}
/**
* lpfc_bsg_dma_page_alloc - allocate a bsg mbox page sized dma buffers
* @phba: Pointer to HBA context object
*
* This function allocates BSG_MBOX_SIZE (4KB) page size dma buffer and.
* retruns the pointer to the buffer.
**/
static struct lpfc_dmabuf *
lpfc_bsg_dma_page_alloc(struct lpfc_hba *phba)
{
struct lpfc_dmabuf *dmabuf;
struct pci_dev *pcidev = phba->pcidev;
/* allocate dma buffer struct */
dmabuf = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (!dmabuf)
return NULL;
INIT_LIST_HEAD(&dmabuf->list);
/* now, allocate dma buffer */
dmabuf->virt = dma_alloc_coherent(&pcidev->dev, BSG_MBOX_SIZE,
&(dmabuf->phys), GFP_KERNEL);
if (!dmabuf->virt) {
kfree(dmabuf);
return NULL;
}
memset((uint8_t *)dmabuf->virt, 0, BSG_MBOX_SIZE);
return dmabuf;
}
/**
* lpfc_bsg_dma_page_free - free a bsg mbox page sized dma buffer
* @phba: Pointer to HBA context object.
* @dmabuf: Pointer to the bsg mbox page sized dma buffer descriptor.
*
* This routine just simply frees a dma buffer and its associated buffer
* descriptor referred by @dmabuf.
**/
static void
lpfc_bsg_dma_page_free(struct lpfc_hba *phba, struct lpfc_dmabuf *dmabuf)
{
struct pci_dev *pcidev = phba->pcidev;
if (!dmabuf)
return;
if (dmabuf->virt)
dma_free_coherent(&pcidev->dev, BSG_MBOX_SIZE,
dmabuf->virt, dmabuf->phys);
kfree(dmabuf);
return;
}
/**
* lpfc_bsg_dma_page_list_free - free a list of bsg mbox page sized dma buffers
* @phba: Pointer to HBA context object.
* @dmabuf_list: Pointer to a list of bsg mbox page sized dma buffer descs.
*
* This routine just simply frees all dma buffers and their associated buffer
* descriptors referred by @dmabuf_list.
**/
static void
lpfc_bsg_dma_page_list_free(struct lpfc_hba *phba,
struct list_head *dmabuf_list)
{
struct lpfc_dmabuf *dmabuf, *next_dmabuf;
if (list_empty(dmabuf_list))
return;
list_for_each_entry_safe(dmabuf, next_dmabuf, dmabuf_list, list) {
list_del_init(&dmabuf->list);
lpfc_bsg_dma_page_free(phba, dmabuf);
}
return;
}
/**
* diag_cmd_data_alloc - fills in a bde struct with dma buffers
* @phba: Pointer to HBA context object
* @bpl: Pointer to 64 bit bde structure
* @size: Number of bytes to process
* @nocopydata: Flag to copy user data into the allocated buffer
*
* This function allocates page size buffers and populates an lpfc_dmabufext.
* If allowed the user data pointed to with indataptr is copied into the kernel
* memory. The chained list of page size buffers is returned.
**/
static struct lpfc_dmabufext *
diag_cmd_data_alloc(struct lpfc_hba *phba,
struct ulp_bde64 *bpl, uint32_t size,
int nocopydata)
{
struct lpfc_dmabufext *mlist = NULL;
struct lpfc_dmabufext *dmp;
int cnt, offset = 0, i = 0;
struct pci_dev *pcidev;
pcidev = phba->pcidev;
while (size) {
/* We get chunks of 4K */
if (size > BUF_SZ_4K)
cnt = BUF_SZ_4K;
else
cnt = size;
/* allocate struct lpfc_dmabufext buffer header */
dmp = kmalloc(sizeof(struct lpfc_dmabufext), GFP_KERNEL);
if (!dmp)
goto out;
INIT_LIST_HEAD(&dmp->dma.list);
/* Queue it to a linked list */
if (mlist)
list_add_tail(&dmp->dma.list, &mlist->dma.list);
else
mlist = dmp;
/* allocate buffer */
dmp->dma.virt = dma_alloc_coherent(&pcidev->dev,
cnt,
&(dmp->dma.phys),
GFP_KERNEL);
if (!dmp->dma.virt)
goto out;
dmp->size = cnt;
if (nocopydata) {
bpl->tus.f.bdeFlags = 0;
pci_dma_sync_single_for_device(phba->pcidev,
dmp->dma.phys, LPFC_BPL_SIZE, PCI_DMA_TODEVICE);
} else {
memset((uint8_t *)dmp->dma.virt, 0, cnt);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64I;
}
/* build buffer ptr list for IOCB */
bpl->addrLow = le32_to_cpu(putPaddrLow(dmp->dma.phys));
bpl->addrHigh = le32_to_cpu(putPaddrHigh(dmp->dma.phys));
bpl->tus.f.bdeSize = (ushort) cnt;
bpl->tus.w = le32_to_cpu(bpl->tus.w);
bpl++;
i++;
offset += cnt;
size -= cnt;
}
mlist->flag = i;
return mlist;
out:
diag_cmd_data_free(phba, mlist);
return NULL;
}
/**
* lpfcdiag_loop_post_rxbufs - post the receive buffers for an unsol CT cmd
* @phba: Pointer to HBA context object
* @rxxri: Receive exchange id
* @len: Number of data bytes
*
* This function allocates and posts a data buffer of sufficient size to receive
* an unsolicted CT command.
**/
static int lpfcdiag_loop_post_rxbufs(struct lpfc_hba *phba, uint16_t rxxri,
size_t len)
{
struct lpfc_sli *psli = &phba->sli;
struct lpfc_sli_ring *pring = &psli->ring[LPFC_ELS_RING];
struct lpfc_iocbq *cmdiocbq;
IOCB_t *cmd = NULL;
struct list_head head, *curr, *next;
struct lpfc_dmabuf *rxbmp;
struct lpfc_dmabuf *dmp;
struct lpfc_dmabuf *mp[2] = {NULL, NULL};
struct ulp_bde64 *rxbpl = NULL;
uint32_t num_bde;
struct lpfc_dmabufext *rxbuffer = NULL;
int ret_val = 0;
int iocb_stat;
int i = 0;
cmdiocbq = lpfc_sli_get_iocbq(phba);
rxbmp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (rxbmp != NULL) {
rxbmp->virt = lpfc_mbuf_alloc(phba, 0, &rxbmp->phys);
if (rxbmp->virt) {
INIT_LIST_HEAD(&rxbmp->list);
rxbpl = (struct ulp_bde64 *) rxbmp->virt;
rxbuffer = diag_cmd_data_alloc(phba, rxbpl, len, 0);
}
}
if (!cmdiocbq || !rxbmp || !rxbpl || !rxbuffer) {
ret_val = -ENOMEM;
goto err_post_rxbufs_exit;
}
/* Queue buffers for the receive exchange */
num_bde = (uint32_t)rxbuffer->flag;
dmp = &rxbuffer->dma;
cmd = &cmdiocbq->iocb;
i = 0;
INIT_LIST_HEAD(&head);
list_add_tail(&head, &dmp->list);
list_for_each_safe(curr, next, &head) {
mp[i] = list_entry(curr, struct lpfc_dmabuf, list);
list_del(curr);
if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
mp[i]->buffer_tag = lpfc_sli_get_buffer_tag(phba);
cmd->un.quexri64cx.buff.bde.addrHigh =
putPaddrHigh(mp[i]->phys);
cmd->un.quexri64cx.buff.bde.addrLow =
putPaddrLow(mp[i]->phys);
cmd->un.quexri64cx.buff.bde.tus.f.bdeSize =
((struct lpfc_dmabufext *)mp[i])->size;
cmd->un.quexri64cx.buff.buffer_tag = mp[i]->buffer_tag;
cmd->ulpCommand = CMD_QUE_XRI64_CX;
cmd->ulpPU = 0;
cmd->ulpLe = 1;
cmd->ulpBdeCount = 1;
cmd->unsli3.que_xri64cx_ext_words.ebde_count = 0;
} else {
cmd->un.cont64[i].addrHigh = putPaddrHigh(mp[i]->phys);
cmd->un.cont64[i].addrLow = putPaddrLow(mp[i]->phys);
cmd->un.cont64[i].tus.f.bdeSize =
((struct lpfc_dmabufext *)mp[i])->size;
cmd->ulpBdeCount = ++i;
if ((--num_bde > 0) && (i < 2))
continue;
cmd->ulpCommand = CMD_QUE_XRI_BUF64_CX;
cmd->ulpLe = 1;
}
cmd->ulpClass = CLASS3;
cmd->ulpContext = rxxri;
iocb_stat = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, cmdiocbq,
0);
if (iocb_stat == IOCB_ERROR) {
diag_cmd_data_free(phba,
(struct lpfc_dmabufext *)mp[0]);
if (mp[1])
diag_cmd_data_free(phba,
(struct lpfc_dmabufext *)mp[1]);
dmp = list_entry(next, struct lpfc_dmabuf, list);
ret_val = -EIO;
goto err_post_rxbufs_exit;
}
lpfc_sli_ringpostbuf_put(phba, pring, mp[0]);
if (mp[1]) {
lpfc_sli_ringpostbuf_put(phba, pring, mp[1]);
mp[1] = NULL;
}
/* The iocb was freed by lpfc_sli_issue_iocb */
cmdiocbq = lpfc_sli_get_iocbq(phba);
if (!cmdiocbq) {
dmp = list_entry(next, struct lpfc_dmabuf, list);
ret_val = -EIO;
goto err_post_rxbufs_exit;
}
cmd = &cmdiocbq->iocb;
i = 0;
}
list_del(&head);
err_post_rxbufs_exit:
if (rxbmp) {
if (rxbmp->virt)
lpfc_mbuf_free(phba, rxbmp->virt, rxbmp->phys);
kfree(rxbmp);
}
if (cmdiocbq)
lpfc_sli_release_iocbq(phba, cmdiocbq);
return ret_val;
}
/**
* lpfc_bsg_diag_loopback_run - run loopback on a port by issue ct cmd to itself
* @job: LPFC_BSG_VENDOR_DIAG_TEST fc_bsg_job
*
* This function receives a user data buffer to be transmitted and received on
* the same port, the link must be up and in loopback mode prior
* to being called.
* 1. A kernel buffer is allocated to copy the user data into.
* 2. The port registers with "itself".
* 3. The transmit and receive exchange ids are obtained.
* 4. The receive exchange id is posted.
* 5. A new els loopback event is created.
* 6. The command and response iocbs are allocated.
* 7. The cmd iocb FsType is set to elx loopback and the CmdRsp to looppback.
*
* This function is meant to be called n times while the port is in loopback
* so it is the apps responsibility to issue a reset to take the port out
* of loopback mode.
**/
static int
lpfc_bsg_diag_loopback_run(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct diag_mode_test *diag_mode;
struct lpfc_bsg_event *evt;
struct event_data *evdat;
struct lpfc_sli *psli = &phba->sli;
uint32_t size;
uint32_t full_size;
size_t segment_len = 0, segment_offset = 0, current_offset = 0;
uint16_t rpi = 0;
struct lpfc_iocbq *cmdiocbq, *rspiocbq = NULL;
IOCB_t *cmd, *rsp = NULL;
struct lpfc_sli_ct_request *ctreq;
struct lpfc_dmabuf *txbmp;
struct ulp_bde64 *txbpl = NULL;
struct lpfc_dmabufext *txbuffer = NULL;
struct list_head head;
struct lpfc_dmabuf *curr;
uint16_t txxri = 0, rxxri;
uint32_t num_bde;
uint8_t *ptr = NULL, *rx_databuf = NULL;
int rc = 0;
int time_left;
int iocb_stat;
unsigned long flags;
void *dataout = NULL;
uint32_t total_mem;
/* in case no data is returned return just the return code */
job->reply->reply_payload_rcv_len = 0;
if (job->request_len <
sizeof(struct fc_bsg_request) + sizeof(struct diag_mode_test)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2739 Received DIAG TEST request below minimum "
"size\n");
rc = -EINVAL;
goto loopback_test_exit;
}
if (job->request_payload.payload_len !=
job->reply_payload.payload_len) {
rc = -EINVAL;
goto loopback_test_exit;
}
diag_mode = (struct diag_mode_test *)
job->request->rqst_data.h_vendor.vendor_cmd;
if ((phba->link_state == LPFC_HBA_ERROR) ||
(psli->sli_flag & LPFC_BLOCK_MGMT_IO) ||
(!(psli->sli_flag & LPFC_SLI_ACTIVE))) {
rc = -EACCES;
goto loopback_test_exit;
}
if (!lpfc_is_link_up(phba) || !(phba->link_flag & LS_LOOPBACK_MODE)) {
rc = -EACCES;
goto loopback_test_exit;
}
size = job->request_payload.payload_len;
full_size = size + ELX_LOOPBACK_HEADER_SZ; /* plus the header */
if ((size == 0) || (size > 80 * BUF_SZ_4K)) {
rc = -ERANGE;
goto loopback_test_exit;
}
if (full_size >= BUF_SZ_4K) {
/*
* Allocate memory for ioctl data. If buffer is bigger than 64k,
* then we allocate 64k and re-use that buffer over and over to
* xfer the whole block. This is because Linux kernel has a
* problem allocating more than 120k of kernel space memory. Saw
* problem with GET_FCPTARGETMAPPING...
*/
if (size <= (64 * 1024))
total_mem = full_size;
else
total_mem = 64 * 1024;
} else
/* Allocate memory for ioctl data */
total_mem = BUF_SZ_4K;
dataout = kmalloc(total_mem, GFP_KERNEL);
if (dataout == NULL) {
rc = -ENOMEM;
goto loopback_test_exit;
}
ptr = dataout;
ptr += ELX_LOOPBACK_HEADER_SZ;
sg_copy_to_buffer(job->request_payload.sg_list,
job->request_payload.sg_cnt,
ptr, size);
rc = lpfcdiag_loop_self_reg(phba, &rpi);
if (rc)
goto loopback_test_exit;
if (phba->sli_rev < LPFC_SLI_REV4) {
rc = lpfcdiag_loop_get_xri(phba, rpi, &txxri, &rxxri);
if (rc) {
lpfcdiag_loop_self_unreg(phba, rpi);
goto loopback_test_exit;
}
rc = lpfcdiag_loop_post_rxbufs(phba, rxxri, full_size);
if (rc) {
lpfcdiag_loop_self_unreg(phba, rpi);
goto loopback_test_exit;
}
}
evt = lpfc_bsg_event_new(FC_REG_CT_EVENT, current->pid,
SLI_CT_ELX_LOOPBACK);
if (!evt) {
lpfcdiag_loop_self_unreg(phba, rpi);
rc = -ENOMEM;
goto loopback_test_exit;
}
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_add(&evt->node, &phba->ct_ev_waiters);
lpfc_bsg_event_ref(evt);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
cmdiocbq = lpfc_sli_get_iocbq(phba);
if (phba->sli_rev < LPFC_SLI_REV4)
rspiocbq = lpfc_sli_get_iocbq(phba);
txbmp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (txbmp) {
txbmp->virt = lpfc_mbuf_alloc(phba, 0, &txbmp->phys);
if (txbmp->virt) {
INIT_LIST_HEAD(&txbmp->list);
txbpl = (struct ulp_bde64 *) txbmp->virt;
txbuffer = diag_cmd_data_alloc(phba,
txbpl, full_size, 0);
}
}
if (!cmdiocbq || !txbmp || !txbpl || !txbuffer || !txbmp->virt) {
rc = -ENOMEM;
goto err_loopback_test_exit;
}
if ((phba->sli_rev < LPFC_SLI_REV4) && !rspiocbq) {
rc = -ENOMEM;
goto err_loopback_test_exit;
}
cmd = &cmdiocbq->iocb;
if (phba->sli_rev < LPFC_SLI_REV4)
rsp = &rspiocbq->iocb;
INIT_LIST_HEAD(&head);
list_add_tail(&head, &txbuffer->dma.list);
list_for_each_entry(curr, &head, list) {
segment_len = ((struct lpfc_dmabufext *)curr)->size;
if (current_offset == 0) {
ctreq = curr->virt;
memset(ctreq, 0, ELX_LOOPBACK_HEADER_SZ);
ctreq->RevisionId.bits.Revision = SLI_CT_REVISION;
ctreq->RevisionId.bits.InId = 0;
ctreq->FsType = SLI_CT_ELX_LOOPBACK;
ctreq->FsSubType = 0;
ctreq->CommandResponse.bits.CmdRsp = ELX_LOOPBACK_DATA;
ctreq->CommandResponse.bits.Size = size;
segment_offset = ELX_LOOPBACK_HEADER_SZ;
} else
segment_offset = 0;
BUG_ON(segment_offset >= segment_len);
memcpy(curr->virt + segment_offset,
ptr + current_offset,
segment_len - segment_offset);
current_offset += segment_len - segment_offset;
BUG_ON(current_offset > size);
}
list_del(&head);
/* Build the XMIT_SEQUENCE iocb */
num_bde = (uint32_t)txbuffer->flag;
cmd->un.xseq64.bdl.addrHigh = putPaddrHigh(txbmp->phys);
cmd->un.xseq64.bdl.addrLow = putPaddrLow(txbmp->phys);
cmd->un.xseq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
cmd->un.xseq64.bdl.bdeSize = (num_bde * sizeof(struct ulp_bde64));
cmd->un.xseq64.w5.hcsw.Fctl = (LS | LA);
cmd->un.xseq64.w5.hcsw.Dfctl = 0;
cmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
cmd->un.xseq64.w5.hcsw.Type = FC_TYPE_CT;
cmd->ulpCommand = CMD_XMIT_SEQUENCE64_CX;
cmd->ulpBdeCount = 1;
cmd->ulpLe = 1;
cmd->ulpClass = CLASS3;
if (phba->sli_rev < LPFC_SLI_REV4) {
cmd->ulpContext = txxri;
} else {
cmd->un.xseq64.bdl.ulpIoTag32 = 0;
cmd->un.ulpWord[3] = phba->sli4_hba.rpi_ids[rpi];
cmdiocbq->context3 = txbmp;
cmdiocbq->sli4_xritag = NO_XRI;
cmd->unsli3.rcvsli3.ox_id = 0xffff;
}
cmdiocbq->iocb_flag |= LPFC_IO_LIBDFC;
cmdiocbq->vport = phba->pport;
iocb_stat = lpfc_sli_issue_iocb_wait(phba, LPFC_ELS_RING, cmdiocbq,
rspiocbq, (phba->fc_ratov * 2) +
LPFC_DRVR_TIMEOUT);
if ((iocb_stat != IOCB_SUCCESS) || ((phba->sli_rev < LPFC_SLI_REV4) &&
(rsp->ulpStatus != IOCB_SUCCESS))) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"3126 Failed loopback test issue iocb: "
"iocb_stat:x%x\n", iocb_stat);
rc = -EIO;
goto err_loopback_test_exit;
}
evt->waiting = 1;
time_left = wait_event_interruptible_timeout(
evt->wq, !list_empty(&evt->events_to_see),
((phba->fc_ratov * 2) + LPFC_DRVR_TIMEOUT) * HZ);
evt->waiting = 0;
if (list_empty(&evt->events_to_see)) {
rc = (time_left) ? -EINTR : -ETIMEDOUT;
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"3125 Not receiving unsolicited event, "
"rc:x%x\n", rc);
} else {
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_move(evt->events_to_see.prev, &evt->events_to_get);
evdat = list_entry(evt->events_to_get.prev,
typeof(*evdat), node);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
rx_databuf = evdat->data;
if (evdat->len != full_size) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"1603 Loopback test did not receive expected "
"data length. actual length 0x%x expected "
"length 0x%x\n",
evdat->len, full_size);
rc = -EIO;
} else if (rx_databuf == NULL)
rc = -EIO;
else {
rc = IOCB_SUCCESS;
/* skip over elx loopback header */
rx_databuf += ELX_LOOPBACK_HEADER_SZ;
job->reply->reply_payload_rcv_len =
sg_copy_from_buffer(job->reply_payload.sg_list,
job->reply_payload.sg_cnt,
rx_databuf, size);
job->reply->reply_payload_rcv_len = size;
}
}
err_loopback_test_exit:
lpfcdiag_loop_self_unreg(phba, rpi);
spin_lock_irqsave(&phba->ct_ev_lock, flags);
lpfc_bsg_event_unref(evt); /* release ref */
lpfc_bsg_event_unref(evt); /* delete */
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
if (cmdiocbq != NULL)
lpfc_sli_release_iocbq(phba, cmdiocbq);
if (rspiocbq != NULL)
lpfc_sli_release_iocbq(phba, rspiocbq);
if (txbmp != NULL) {
if (txbpl != NULL) {
if (txbuffer != NULL)
diag_cmd_data_free(phba, txbuffer);
lpfc_mbuf_free(phba, txbmp->virt, txbmp->phys);
}
kfree(txbmp);
}
loopback_test_exit:
kfree(dataout);
/* make error code available to userspace */
job->reply->result = rc;
job->dd_data = NULL;
/* complete the job back to userspace if no error */
if (rc == IOCB_SUCCESS)
job->job_done(job);
return rc;
}
/**
* lpfc_bsg_get_dfc_rev - process a GET_DFC_REV bsg vendor command
* @job: GET_DFC_REV fc_bsg_job
**/
static int
lpfc_bsg_get_dfc_rev(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct get_mgmt_rev *event_req;
struct get_mgmt_rev_reply *event_reply;
int rc = 0;
if (job->request_len <
sizeof(struct fc_bsg_request) + sizeof(struct get_mgmt_rev)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2740 Received GET_DFC_REV request below "
"minimum size\n");
rc = -EINVAL;
goto job_error;
}
event_req = (struct get_mgmt_rev *)
job->request->rqst_data.h_vendor.vendor_cmd;
event_reply = (struct get_mgmt_rev_reply *)
job->reply->reply_data.vendor_reply.vendor_rsp;
if (job->reply_len <
sizeof(struct fc_bsg_request) + sizeof(struct get_mgmt_rev_reply)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2741 Received GET_DFC_REV reply below "
"minimum size\n");
rc = -EINVAL;
goto job_error;
}
event_reply->info.a_Major = MANAGEMENT_MAJOR_REV;
event_reply->info.a_Minor = MANAGEMENT_MINOR_REV;
job_error:
job->reply->result = rc;
if (rc == 0)
job->job_done(job);
return rc;
}
/**
* lpfc_bsg_issue_mbox_cmpl - lpfc_bsg_issue_mbox mbox completion handler
* @phba: Pointer to HBA context object.
* @pmboxq: Pointer to mailbox command.
*
* This is completion handler function for mailbox commands issued from
* lpfc_bsg_issue_mbox function. This function is called by the
* mailbox event handler function with no lock held. This function
* will wake up thread waiting on the wait queue pointed by context1
* of the mailbox.
**/
void
lpfc_bsg_issue_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
{
struct bsg_job_data *dd_data;
struct fc_bsg_job *job;
uint32_t size;
unsigned long flags;
uint8_t *pmb, *pmb_buf;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
dd_data = pmboxq->context1;
/* job already timed out? */
if (!dd_data) {
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
/*
* The outgoing buffer is readily referred from the dma buffer,
* just need to get header part from mailboxq structure.
*/
pmb = (uint8_t *)&pmboxq->u.mb;
pmb_buf = (uint8_t *)dd_data->context_un.mbox.mb;
memcpy(pmb_buf, pmb, sizeof(MAILBOX_t));
job = dd_data->context_un.mbox.set_job;
if (job) {
size = job->reply_payload.payload_len;
job->reply->reply_payload_rcv_len =
sg_copy_from_buffer(job->reply_payload.sg_list,
job->reply_payload.sg_cnt,
pmb_buf, size);
/* need to hold the lock until we set job->dd_data to NULL
* to hold off the timeout handler returning to the mid-layer
* while we are still processing the job.
*/
job->dd_data = NULL;
dd_data->context_un.mbox.set_job = NULL;
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
} else {
dd_data->context_un.mbox.set_job = NULL;
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
}
mempool_free(dd_data->context_un.mbox.pmboxq, phba->mbox_mem_pool);
lpfc_bsg_dma_page_free(phba, dd_data->context_un.mbox.dmabuffers);
kfree(dd_data);
if (job) {
job->reply->result = 0;
job->job_done(job);
}
return;
}
/**
* lpfc_bsg_check_cmd_access - test for a supported mailbox command
* @phba: Pointer to HBA context object.
* @mb: Pointer to a mailbox object.
* @vport: Pointer to a vport object.
*
* Some commands require the port to be offline, some may not be called from
* the application.
**/
static int lpfc_bsg_check_cmd_access(struct lpfc_hba *phba,
MAILBOX_t *mb, struct lpfc_vport *vport)
{
/* return negative error values for bsg job */
switch (mb->mbxCommand) {
/* Offline only */
case MBX_INIT_LINK:
case MBX_DOWN_LINK:
case MBX_CONFIG_LINK:
case MBX_CONFIG_RING:
case MBX_RESET_RING:
case MBX_UNREG_LOGIN:
case MBX_CLEAR_LA:
case MBX_DUMP_CONTEXT:
case MBX_RUN_DIAGS:
case MBX_RESTART:
case MBX_SET_MASK:
if (!(vport->fc_flag & FC_OFFLINE_MODE)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2743 Command 0x%x is illegal in on-line "
"state\n",
mb->mbxCommand);
return -EPERM;
}
case MBX_WRITE_NV:
case MBX_WRITE_VPARMS:
case MBX_LOAD_SM:
case MBX_READ_NV:
case MBX_READ_CONFIG:
case MBX_READ_RCONFIG:
case MBX_READ_STATUS:
case MBX_READ_XRI:
case MBX_READ_REV:
case MBX_READ_LNK_STAT:
case MBX_DUMP_MEMORY:
case MBX_DOWN_LOAD:
case MBX_UPDATE_CFG:
case MBX_KILL_BOARD:
case MBX_LOAD_AREA:
case MBX_LOAD_EXP_ROM:
case MBX_BEACON:
case MBX_DEL_LD_ENTRY:
case MBX_SET_DEBUG:
case MBX_WRITE_WWN:
case MBX_SLI4_CONFIG:
case MBX_READ_EVENT_LOG:
case MBX_READ_EVENT_LOG_STATUS:
case MBX_WRITE_EVENT_LOG:
case MBX_PORT_CAPABILITIES:
case MBX_PORT_IOV_CONTROL:
case MBX_RUN_BIU_DIAG64:
break;
case MBX_SET_VARIABLE:
lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
"1226 mbox: set_variable 0x%x, 0x%x\n",
mb->un.varWords[0],
mb->un.varWords[1]);
if ((mb->un.varWords[0] == SETVAR_MLOMNT)
&& (mb->un.varWords[1] == 1)) {
phba->wait_4_mlo_maint_flg = 1;
} else if (mb->un.varWords[0] == SETVAR_MLORST) {
spin_lock_irq(&phba->hbalock);
phba->link_flag &= ~LS_LOOPBACK_MODE;
spin_unlock_irq(&phba->hbalock);
phba->fc_topology = LPFC_TOPOLOGY_PT_PT;
}
break;
case MBX_READ_SPARM64:
case MBX_READ_TOPOLOGY:
case MBX_REG_LOGIN:
case MBX_REG_LOGIN64:
case MBX_CONFIG_PORT:
case MBX_RUN_BIU_DIAG:
default:
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2742 Unknown Command 0x%x\n",
mb->mbxCommand);
return -EPERM;
}
return 0; /* ok */
}
/**
* lpfc_bsg_mbox_ext_cleanup - clean up context of multi-buffer mbox session
* @phba: Pointer to HBA context object.
*
* This is routine clean up and reset BSG handling of multi-buffer mbox
* command session.
**/
static void
lpfc_bsg_mbox_ext_session_reset(struct lpfc_hba *phba)
{
if (phba->mbox_ext_buf_ctx.state == LPFC_BSG_MBOX_IDLE)
return;
/* free all memory, including dma buffers */
lpfc_bsg_dma_page_list_free(phba,
&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
lpfc_bsg_dma_page_free(phba, phba->mbox_ext_buf_ctx.mbx_dmabuf);
/* multi-buffer write mailbox command pass-through complete */
memset((char *)&phba->mbox_ext_buf_ctx, 0,
sizeof(struct lpfc_mbox_ext_buf_ctx));
INIT_LIST_HEAD(&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
return;
}
/**
* lpfc_bsg_issue_mbox_ext_handle_job - job handler for multi-buffer mbox cmpl
* @phba: Pointer to HBA context object.
* @pmboxq: Pointer to mailbox command.
*
* This is routine handles BSG job for mailbox commands completions with
* multiple external buffers.
**/
static struct fc_bsg_job *
lpfc_bsg_issue_mbox_ext_handle_job(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
{
struct bsg_job_data *dd_data;
struct fc_bsg_job *job;
uint8_t *pmb, *pmb_buf;
unsigned long flags;
uint32_t size;
int rc = 0;
struct lpfc_dmabuf *dmabuf;
struct lpfc_sli_config_mbox *sli_cfg_mbx;
uint8_t *pmbx;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
dd_data = pmboxq->context1;
/* has the job already timed out? */
if (!dd_data) {
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
job = NULL;
goto job_done_out;
}
/*
* The outgoing buffer is readily referred from the dma buffer,
* just need to get header part from mailboxq structure.
*/
pmb = (uint8_t *)&pmboxq->u.mb;
pmb_buf = (uint8_t *)dd_data->context_un.mbox.mb;
/* Copy the byte swapped response mailbox back to the user */
memcpy(pmb_buf, pmb, sizeof(MAILBOX_t));
/* if there is any non-embedded extended data copy that too */
dmabuf = phba->mbox_ext_buf_ctx.mbx_dmabuf;
sli_cfg_mbx = (struct lpfc_sli_config_mbox *)dmabuf->virt;
if (!bsg_bf_get(lpfc_mbox_hdr_emb,
&sli_cfg_mbx->un.sli_config_emb0_subsys.sli_config_hdr)) {
pmbx = (uint8_t *)dmabuf->virt;
/* byte swap the extended data following the mailbox command */
lpfc_sli_pcimem_bcopy(&pmbx[sizeof(MAILBOX_t)],
&pmbx[sizeof(MAILBOX_t)],
sli_cfg_mbx->un.sli_config_emb0_subsys.mse[0].buf_len);
}
job = dd_data->context_un.mbox.set_job;
if (job) {
size = job->reply_payload.payload_len;
job->reply->reply_payload_rcv_len =
sg_copy_from_buffer(job->reply_payload.sg_list,
job->reply_payload.sg_cnt,
pmb_buf, size);
/* result for successful */
job->reply->result = 0;
job->dd_data = NULL;
/* need to hold the lock util we set job->dd_data to NULL
* to hold off the timeout handler from midlayer to take
* any action.
*/
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2937 SLI_CONFIG ext-buffer maibox command "
"(x%x/x%x) complete bsg job done, bsize:%d\n",
phba->mbox_ext_buf_ctx.nembType,
phba->mbox_ext_buf_ctx.mboxType, size);
lpfc_idiag_mbxacc_dump_bsg_mbox(phba,
phba->mbox_ext_buf_ctx.nembType,
phba->mbox_ext_buf_ctx.mboxType,
dma_ebuf, sta_pos_addr,
phba->mbox_ext_buf_ctx.mbx_dmabuf, 0);
} else
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
job_done_out:
if (!job)
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2938 SLI_CONFIG ext-buffer maibox "
"command (x%x/x%x) failure, rc:x%x\n",
phba->mbox_ext_buf_ctx.nembType,
phba->mbox_ext_buf_ctx.mboxType, rc);
/* state change */
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_DONE;
kfree(dd_data);
return job;
}
/**
* lpfc_bsg_issue_read_mbox_ext_cmpl - compl handler for multi-buffer read mbox
* @phba: Pointer to HBA context object.
* @pmboxq: Pointer to mailbox command.
*
* This is completion handler function for mailbox read commands with multiple
* external buffers.
**/
static void
lpfc_bsg_issue_read_mbox_ext_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
{
struct fc_bsg_job *job;
/* handle the BSG job with mailbox command */
if (phba->mbox_ext_buf_ctx.state == LPFC_BSG_MBOX_ABTS)
pmboxq->u.mb.mbxStatus = MBXERR_ERROR;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2939 SLI_CONFIG ext-buffer rd maibox command "
"complete, ctxState:x%x, mbxStatus:x%x\n",
phba->mbox_ext_buf_ctx.state, pmboxq->u.mb.mbxStatus);
job = lpfc_bsg_issue_mbox_ext_handle_job(phba, pmboxq);
if (pmboxq->u.mb.mbxStatus || phba->mbox_ext_buf_ctx.numBuf == 1)
lpfc_bsg_mbox_ext_session_reset(phba);
/* free base driver mailbox structure memory */
mempool_free(pmboxq, phba->mbox_mem_pool);
/* complete the bsg job if we have it */
if (job)
job->job_done(job);
return;
}
/**
* lpfc_bsg_issue_write_mbox_ext_cmpl - cmpl handler for multi-buffer write mbox
* @phba: Pointer to HBA context object.
* @pmboxq: Pointer to mailbox command.
*
* This is completion handler function for mailbox write commands with multiple
* external buffers.
**/
static void
lpfc_bsg_issue_write_mbox_ext_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
{
struct fc_bsg_job *job;
/* handle the BSG job with the mailbox command */
if (phba->mbox_ext_buf_ctx.state == LPFC_BSG_MBOX_ABTS)
pmboxq->u.mb.mbxStatus = MBXERR_ERROR;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2940 SLI_CONFIG ext-buffer wr maibox command "
"complete, ctxState:x%x, mbxStatus:x%x\n",
phba->mbox_ext_buf_ctx.state, pmboxq->u.mb.mbxStatus);
job = lpfc_bsg_issue_mbox_ext_handle_job(phba, pmboxq);
/* free all memory, including dma buffers */
mempool_free(pmboxq, phba->mbox_mem_pool);
lpfc_bsg_mbox_ext_session_reset(phba);
/* complete the bsg job if we have it */
if (job)
job->job_done(job);
return;
}
static void
lpfc_bsg_sli_cfg_dma_desc_setup(struct lpfc_hba *phba, enum nemb_type nemb_tp,
uint32_t index, struct lpfc_dmabuf *mbx_dmabuf,
struct lpfc_dmabuf *ext_dmabuf)
{
struct lpfc_sli_config_mbox *sli_cfg_mbx;
/* pointer to the start of mailbox command */
sli_cfg_mbx = (struct lpfc_sli_config_mbox *)mbx_dmabuf->virt;
if (nemb_tp == nemb_mse) {
if (index == 0) {
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_hi =
putPaddrHigh(mbx_dmabuf->phys +
sizeof(MAILBOX_t));
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_lo =
putPaddrLow(mbx_dmabuf->phys +
sizeof(MAILBOX_t));
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2943 SLI_CONFIG(mse)[%d], "
"bufLen:%d, addrHi:x%x, addrLo:x%x\n",
index,
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].buf_len,
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_hi,
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_lo);
} else {
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_hi =
putPaddrHigh(ext_dmabuf->phys);
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_lo =
putPaddrLow(ext_dmabuf->phys);
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2944 SLI_CONFIG(mse)[%d], "
"bufLen:%d, addrHi:x%x, addrLo:x%x\n",
index,
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].buf_len,
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_hi,
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_lo);
}
} else {
if (index == 0) {
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_hi =
putPaddrHigh(mbx_dmabuf->phys +
sizeof(MAILBOX_t));
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_lo =
putPaddrLow(mbx_dmabuf->phys +
sizeof(MAILBOX_t));
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3007 SLI_CONFIG(hbd)[%d], "
"bufLen:%d, addrHi:x%x, addrLo:x%x\n",
index,
bsg_bf_get(lpfc_mbox_sli_config_ecmn_hbd_len,
&sli_cfg_mbx->un.
sli_config_emb1_subsys.hbd[index]),
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_hi,
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_lo);
} else {
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_hi =
putPaddrHigh(ext_dmabuf->phys);
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_lo =
putPaddrLow(ext_dmabuf->phys);
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3008 SLI_CONFIG(hbd)[%d], "
"bufLen:%d, addrHi:x%x, addrLo:x%x\n",
index,
bsg_bf_get(lpfc_mbox_sli_config_ecmn_hbd_len,
&sli_cfg_mbx->un.
sli_config_emb1_subsys.hbd[index]),
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_hi,
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_lo);
}
}
return;
}
/**
* lpfc_bsg_sli_cfg_mse_read_cmd_ext - sli_config non-embedded mailbox cmd read
* @phba: Pointer to HBA context object.
* @mb: Pointer to a BSG mailbox object.
* @nemb_tp: Enumerate of non-embedded mailbox command type.
* @dmabuff: Pointer to a DMA buffer descriptor.
*
* This routine performs SLI_CONFIG (0x9B) read mailbox command operation with
* non-embedded external bufffers.
**/
static int
lpfc_bsg_sli_cfg_read_cmd_ext(struct lpfc_hba *phba, struct fc_bsg_job *job,
enum nemb_type nemb_tp,
struct lpfc_dmabuf *dmabuf)
{
struct lpfc_sli_config_mbox *sli_cfg_mbx;
struct dfc_mbox_req *mbox_req;
struct lpfc_dmabuf *curr_dmabuf, *next_dmabuf;
uint32_t ext_buf_cnt, ext_buf_index;
struct lpfc_dmabuf *ext_dmabuf = NULL;
struct bsg_job_data *dd_data = NULL;
LPFC_MBOXQ_t *pmboxq = NULL;
MAILBOX_t *pmb;
uint8_t *pmbx;
int rc, i;
mbox_req =
(struct dfc_mbox_req *)job->request->rqst_data.h_vendor.vendor_cmd;
/* pointer to the start of mailbox command */
sli_cfg_mbx = (struct lpfc_sli_config_mbox *)dmabuf->virt;
if (nemb_tp == nemb_mse) {
ext_buf_cnt = bsg_bf_get(lpfc_mbox_hdr_mse_cnt,
&sli_cfg_mbx->un.sli_config_emb0_subsys.sli_config_hdr);
if (ext_buf_cnt > LPFC_MBX_SLI_CONFIG_MAX_MSE) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2945 Handled SLI_CONFIG(mse) rd, "
"ext_buf_cnt(%d) out of range(%d)\n",
ext_buf_cnt,
LPFC_MBX_SLI_CONFIG_MAX_MSE);
rc = -ERANGE;
goto job_error;
}
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2941 Handled SLI_CONFIG(mse) rd, "
"ext_buf_cnt:%d\n", ext_buf_cnt);
} else {
/* sanity check on interface type for support */
if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) !=
LPFC_SLI_INTF_IF_TYPE_2) {
rc = -ENODEV;
goto job_error;
}
/* nemb_tp == nemb_hbd */
ext_buf_cnt = sli_cfg_mbx->un.sli_config_emb1_subsys.hbd_count;
if (ext_buf_cnt > LPFC_MBX_SLI_CONFIG_MAX_HBD) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2946 Handled SLI_CONFIG(hbd) rd, "
"ext_buf_cnt(%d) out of range(%d)\n",
ext_buf_cnt,
LPFC_MBX_SLI_CONFIG_MAX_HBD);
rc = -ERANGE;
goto job_error;
}
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2942 Handled SLI_CONFIG(hbd) rd, "
"ext_buf_cnt:%d\n", ext_buf_cnt);
}
/* before dma descriptor setup */
lpfc_idiag_mbxacc_dump_bsg_mbox(phba, nemb_tp, mbox_rd, dma_mbox,
sta_pre_addr, dmabuf, ext_buf_cnt);
/* reject non-embedded mailbox command with none external buffer */
if (ext_buf_cnt == 0) {
rc = -EPERM;
goto job_error;
} else if (ext_buf_cnt > 1) {
/* additional external read buffers */
for (i = 1; i < ext_buf_cnt; i++) {
ext_dmabuf = lpfc_bsg_dma_page_alloc(phba);
if (!ext_dmabuf) {
rc = -ENOMEM;
goto job_error;
}
list_add_tail(&ext_dmabuf->list,
&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
}
}
/* bsg tracking structure */
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
rc = -ENOMEM;
goto job_error;
}
/* mailbox command structure for base driver */
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq) {
rc = -ENOMEM;
goto job_error;
}
memset(pmboxq, 0, sizeof(LPFC_MBOXQ_t));
/* for the first external buffer */
lpfc_bsg_sli_cfg_dma_desc_setup(phba, nemb_tp, 0, dmabuf, dmabuf);
/* for the rest of external buffer descriptors if any */
if (ext_buf_cnt > 1) {
ext_buf_index = 1;
list_for_each_entry_safe(curr_dmabuf, next_dmabuf,
&phba->mbox_ext_buf_ctx.ext_dmabuf_list, list) {
lpfc_bsg_sli_cfg_dma_desc_setup(phba, nemb_tp,
ext_buf_index, dmabuf,
curr_dmabuf);
ext_buf_index++;
}
}
/* after dma descriptor setup */
lpfc_idiag_mbxacc_dump_bsg_mbox(phba, nemb_tp, mbox_rd, dma_mbox,
sta_pos_addr, dmabuf, ext_buf_cnt);
/* construct base driver mbox command */
pmb = &pmboxq->u.mb;
pmbx = (uint8_t *)dmabuf->virt;
memcpy(pmb, pmbx, sizeof(*pmb));
pmb->mbxOwner = OWN_HOST;
pmboxq->vport = phba->pport;
/* multi-buffer handling context */
phba->mbox_ext_buf_ctx.nembType = nemb_tp;
phba->mbox_ext_buf_ctx.mboxType = mbox_rd;
phba->mbox_ext_buf_ctx.numBuf = ext_buf_cnt;
phba->mbox_ext_buf_ctx.mbxTag = mbox_req->extMboxTag;
phba->mbox_ext_buf_ctx.seqNum = mbox_req->extSeqNum;
phba->mbox_ext_buf_ctx.mbx_dmabuf = dmabuf;
/* callback for multi-buffer read mailbox command */
pmboxq->mbox_cmpl = lpfc_bsg_issue_read_mbox_ext_cmpl;
/* context fields to callback function */
pmboxq->context1 = dd_data;
dd_data->type = TYPE_MBOX;
dd_data->context_un.mbox.pmboxq = pmboxq;
dd_data->context_un.mbox.mb = (MAILBOX_t *)pmbx;
dd_data->context_un.mbox.set_job = job;
job->dd_data = dd_data;
/* state change */
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_PORT;
/*
* Non-embedded mailbox subcommand data gets byte swapped here because
* the lower level driver code only does the first 64 mailbox words.
*/
if ((!bsg_bf_get(lpfc_mbox_hdr_emb,
&sli_cfg_mbx->un.sli_config_emb0_subsys.sli_config_hdr)) &&
(nemb_tp == nemb_mse))
lpfc_sli_pcimem_bcopy(&pmbx[sizeof(MAILBOX_t)],
&pmbx[sizeof(MAILBOX_t)],
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[0].buf_len);
rc = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
if ((rc == MBX_SUCCESS) || (rc == MBX_BUSY)) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2947 Issued SLI_CONFIG ext-buffer "
"maibox command, rc:x%x\n", rc);
return SLI_CONFIG_HANDLED;
}
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2948 Failed to issue SLI_CONFIG ext-buffer "
"maibox command, rc:x%x\n", rc);
rc = -EPIPE;
job_error:
if (pmboxq)
mempool_free(pmboxq, phba->mbox_mem_pool);
lpfc_bsg_dma_page_list_free(phba,
&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
kfree(dd_data);
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_IDLE;
return rc;
}
/**
* lpfc_bsg_sli_cfg_write_cmd_ext - sli_config non-embedded mailbox cmd write
* @phba: Pointer to HBA context object.
* @mb: Pointer to a BSG mailbox object.
* @dmabuff: Pointer to a DMA buffer descriptor.
*
* This routine performs SLI_CONFIG (0x9B) write mailbox command operation with
* non-embedded external bufffers.
**/
static int
lpfc_bsg_sli_cfg_write_cmd_ext(struct lpfc_hba *phba, struct fc_bsg_job *job,
enum nemb_type nemb_tp,
struct lpfc_dmabuf *dmabuf)
{
struct dfc_mbox_req *mbox_req;
struct lpfc_sli_config_mbox *sli_cfg_mbx;
uint32_t ext_buf_cnt;
struct bsg_job_data *dd_data = NULL;
LPFC_MBOXQ_t *pmboxq = NULL;
MAILBOX_t *pmb;
uint8_t *mbx;
int rc = SLI_CONFIG_NOT_HANDLED, i;
mbox_req =
(struct dfc_mbox_req *)job->request->rqst_data.h_vendor.vendor_cmd;
/* pointer to the start of mailbox command */
sli_cfg_mbx = (struct lpfc_sli_config_mbox *)dmabuf->virt;
if (nemb_tp == nemb_mse) {
ext_buf_cnt = bsg_bf_get(lpfc_mbox_hdr_mse_cnt,
&sli_cfg_mbx->un.sli_config_emb0_subsys.sli_config_hdr);
if (ext_buf_cnt > LPFC_MBX_SLI_CONFIG_MAX_MSE) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2953 Failed SLI_CONFIG(mse) wr, "
"ext_buf_cnt(%d) out of range(%d)\n",
ext_buf_cnt,
LPFC_MBX_SLI_CONFIG_MAX_MSE);
return -ERANGE;
}
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2949 Handled SLI_CONFIG(mse) wr, "
"ext_buf_cnt:%d\n", ext_buf_cnt);
} else {
/* sanity check on interface type for support */
if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) !=
LPFC_SLI_INTF_IF_TYPE_2)
return -ENODEV;
/* nemb_tp == nemb_hbd */
ext_buf_cnt = sli_cfg_mbx->un.sli_config_emb1_subsys.hbd_count;
if (ext_buf_cnt > LPFC_MBX_SLI_CONFIG_MAX_HBD) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2954 Failed SLI_CONFIG(hbd) wr, "
"ext_buf_cnt(%d) out of range(%d)\n",
ext_buf_cnt,
LPFC_MBX_SLI_CONFIG_MAX_HBD);
return -ERANGE;
}
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2950 Handled SLI_CONFIG(hbd) wr, "
"ext_buf_cnt:%d\n", ext_buf_cnt);
}
/* before dma buffer descriptor setup */
lpfc_idiag_mbxacc_dump_bsg_mbox(phba, nemb_tp, mbox_wr, dma_mbox,
sta_pre_addr, dmabuf, ext_buf_cnt);
if (ext_buf_cnt == 0)
return -EPERM;
/* for the first external buffer */
lpfc_bsg_sli_cfg_dma_desc_setup(phba, nemb_tp, 0, dmabuf, dmabuf);
/* after dma descriptor setup */
lpfc_idiag_mbxacc_dump_bsg_mbox(phba, nemb_tp, mbox_wr, dma_mbox,
sta_pos_addr, dmabuf, ext_buf_cnt);
/* log for looking forward */
for (i = 1; i < ext_buf_cnt; i++) {
if (nemb_tp == nemb_mse)
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2951 SLI_CONFIG(mse), buf[%d]-length:%d\n",
i, sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[i].buf_len);
else
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2952 SLI_CONFIG(hbd), buf[%d]-length:%d\n",
i, bsg_bf_get(lpfc_mbox_sli_config_ecmn_hbd_len,
&sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[i]));
}
/* multi-buffer handling context */
phba->mbox_ext_buf_ctx.nembType = nemb_tp;
phba->mbox_ext_buf_ctx.mboxType = mbox_wr;
phba->mbox_ext_buf_ctx.numBuf = ext_buf_cnt;
phba->mbox_ext_buf_ctx.mbxTag = mbox_req->extMboxTag;
phba->mbox_ext_buf_ctx.seqNum = mbox_req->extSeqNum;
phba->mbox_ext_buf_ctx.mbx_dmabuf = dmabuf;
if (ext_buf_cnt == 1) {
/* bsg tracking structure */
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
rc = -ENOMEM;
goto job_error;
}
/* mailbox command structure for base driver */
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq) {
rc = -ENOMEM;
goto job_error;
}
memset(pmboxq, 0, sizeof(LPFC_MBOXQ_t));
pmb = &pmboxq->u.mb;
mbx = (uint8_t *)dmabuf->virt;
memcpy(pmb, mbx, sizeof(*pmb));
pmb->mbxOwner = OWN_HOST;
pmboxq->vport = phba->pport;
/* callback for multi-buffer read mailbox command */
pmboxq->mbox_cmpl = lpfc_bsg_issue_write_mbox_ext_cmpl;
/* context fields to callback function */
pmboxq->context1 = dd_data;
dd_data->type = TYPE_MBOX;
dd_data->context_un.mbox.pmboxq = pmboxq;
dd_data->context_un.mbox.mb = (MAILBOX_t *)mbx;
dd_data->context_un.mbox.set_job = job;
job->dd_data = dd_data;
/* state change */
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_PORT;
rc = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
if ((rc == MBX_SUCCESS) || (rc == MBX_BUSY)) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2955 Issued SLI_CONFIG ext-buffer "
"maibox command, rc:x%x\n", rc);
return SLI_CONFIG_HANDLED;
}
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2956 Failed to issue SLI_CONFIG ext-buffer "
"maibox command, rc:x%x\n", rc);
rc = -EPIPE;
goto job_error;
}
/* wait for additoinal external buffers */
job->reply->result = 0;
job->job_done(job);
return SLI_CONFIG_HANDLED;
job_error:
if (pmboxq)
mempool_free(pmboxq, phba->mbox_mem_pool);
kfree(dd_data);
return rc;
}
/**
* lpfc_bsg_handle_sli_cfg_mbox - handle sli-cfg mailbox cmd with ext buffer
* @phba: Pointer to HBA context object.
* @mb: Pointer to a BSG mailbox object.
* @dmabuff: Pointer to a DMA buffer descriptor.
*
* This routine handles SLI_CONFIG (0x9B) mailbox command with non-embedded
* external bufffers, including both 0x9B with non-embedded MSEs and 0x9B
* with embedded sussystem 0x1 and opcodes with external HBDs.
**/
static int
lpfc_bsg_handle_sli_cfg_mbox(struct lpfc_hba *phba, struct fc_bsg_job *job,
struct lpfc_dmabuf *dmabuf)
{
struct lpfc_sli_config_mbox *sli_cfg_mbx;
uint32_t subsys;
uint32_t opcode;
int rc = SLI_CONFIG_NOT_HANDLED;
/* state change on new multi-buffer pass-through mailbox command */
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_HOST;
sli_cfg_mbx = (struct lpfc_sli_config_mbox *)dmabuf->virt;
if (!bsg_bf_get(lpfc_mbox_hdr_emb,
&sli_cfg_mbx->un.sli_config_emb0_subsys.sli_config_hdr)) {
subsys = bsg_bf_get(lpfc_emb0_subcmnd_subsys,
&sli_cfg_mbx->un.sli_config_emb0_subsys);
opcode = bsg_bf_get(lpfc_emb0_subcmnd_opcode,
&sli_cfg_mbx->un.sli_config_emb0_subsys);
if (subsys == SLI_CONFIG_SUBSYS_FCOE) {
switch (opcode) {
case FCOE_OPCODE_READ_FCF:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2957 Handled SLI_CONFIG "
"subsys_fcoe, opcode:x%x\n",
opcode);
rc = lpfc_bsg_sli_cfg_read_cmd_ext(phba, job,
nemb_mse, dmabuf);
break;
case FCOE_OPCODE_ADD_FCF:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2958 Handled SLI_CONFIG "
"subsys_fcoe, opcode:x%x\n",
opcode);
rc = lpfc_bsg_sli_cfg_write_cmd_ext(phba, job,
nemb_mse, dmabuf);
break;
default:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2959 Reject SLI_CONFIG "
"subsys_fcoe, opcode:x%x\n",
opcode);
rc = -EPERM;
break;
}
} else if (subsys == SLI_CONFIG_SUBSYS_COMN) {
switch (opcode) {
case COMN_OPCODE_GET_CNTL_ADDL_ATTRIBUTES:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3106 Handled SLI_CONFIG "
"subsys_comn, opcode:x%x\n",
opcode);
rc = lpfc_bsg_sli_cfg_read_cmd_ext(phba, job,
nemb_mse, dmabuf);
break;
default:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3107 Reject SLI_CONFIG "
"subsys_comn, opcode:x%x\n",
opcode);
rc = -EPERM;
break;
}
} else {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2977 Reject SLI_CONFIG "
"subsys:x%d, opcode:x%x\n",
subsys, opcode);
rc = -EPERM;
}
} else {
subsys = bsg_bf_get(lpfc_emb1_subcmnd_subsys,
&sli_cfg_mbx->un.sli_config_emb1_subsys);
opcode = bsg_bf_get(lpfc_emb1_subcmnd_opcode,
&sli_cfg_mbx->un.sli_config_emb1_subsys);
if (subsys == SLI_CONFIG_SUBSYS_COMN) {
switch (opcode) {
case COMN_OPCODE_READ_OBJECT:
case COMN_OPCODE_READ_OBJECT_LIST:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2960 Handled SLI_CONFIG "
"subsys_comn, opcode:x%x\n",
opcode);
rc = lpfc_bsg_sli_cfg_read_cmd_ext(phba, job,
nemb_hbd, dmabuf);
break;
case COMN_OPCODE_WRITE_OBJECT:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2961 Handled SLI_CONFIG "
"subsys_comn, opcode:x%x\n",
opcode);
rc = lpfc_bsg_sli_cfg_write_cmd_ext(phba, job,
nemb_hbd, dmabuf);
break;
default:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2962 Not handled SLI_CONFIG "
"subsys_comn, opcode:x%x\n",
opcode);
rc = SLI_CONFIG_NOT_HANDLED;
break;
}
} else {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2978 Not handled SLI_CONFIG "
"subsys:x%d, opcode:x%x\n",
subsys, opcode);
rc = SLI_CONFIG_NOT_HANDLED;
}
}
/* state reset on not handled new multi-buffer mailbox command */
if (rc != SLI_CONFIG_HANDLED)
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_IDLE;
return rc;
}
/**
* lpfc_bsg_mbox_ext_abort_req - request to abort mbox command with ext buffers
* @phba: Pointer to HBA context object.
*
* This routine is for requesting to abort a pass-through mailbox command with
* multiple external buffers due to error condition.
**/
static void
lpfc_bsg_mbox_ext_abort(struct lpfc_hba *phba)
{
if (phba->mbox_ext_buf_ctx.state == LPFC_BSG_MBOX_PORT)
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_ABTS;
else
lpfc_bsg_mbox_ext_session_reset(phba);
return;
}
/**
* lpfc_bsg_read_ebuf_get - get the next mailbox read external buffer
* @phba: Pointer to HBA context object.
* @dmabuf: Pointer to a DMA buffer descriptor.
*
* This routine extracts the next mailbox read external buffer back to
* user space through BSG.
**/
static int
lpfc_bsg_read_ebuf_get(struct lpfc_hba *phba, struct fc_bsg_job *job)
{
struct lpfc_sli_config_mbox *sli_cfg_mbx;
struct lpfc_dmabuf *dmabuf;
uint8_t *pbuf;
uint32_t size;
uint32_t index;
index = phba->mbox_ext_buf_ctx.seqNum;
phba->mbox_ext_buf_ctx.seqNum++;
sli_cfg_mbx = (struct lpfc_sli_config_mbox *)
phba->mbox_ext_buf_ctx.mbx_dmabuf->virt;
if (phba->mbox_ext_buf_ctx.nembType == nemb_mse) {
size = bsg_bf_get(lpfc_mbox_sli_config_mse_len,
&sli_cfg_mbx->un.sli_config_emb0_subsys.mse[index]);
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2963 SLI_CONFIG (mse) ext-buffer rd get "
"buffer[%d], size:%d\n", index, size);
} else {
size = bsg_bf_get(lpfc_mbox_sli_config_ecmn_hbd_len,
&sli_cfg_mbx->un.sli_config_emb1_subsys.hbd[index]);
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2964 SLI_CONFIG (hbd) ext-buffer rd get "
"buffer[%d], size:%d\n", index, size);
}
if (list_empty(&phba->mbox_ext_buf_ctx.ext_dmabuf_list))
return -EPIPE;
dmabuf = list_first_entry(&phba->mbox_ext_buf_ctx.ext_dmabuf_list,
struct lpfc_dmabuf, list);
list_del_init(&dmabuf->list);
/* after dma buffer descriptor setup */
lpfc_idiag_mbxacc_dump_bsg_mbox(phba, phba->mbox_ext_buf_ctx.nembType,
mbox_rd, dma_ebuf, sta_pos_addr,
dmabuf, index);
pbuf = (uint8_t *)dmabuf->virt;
job->reply->reply_payload_rcv_len =
sg_copy_from_buffer(job->reply_payload.sg_list,
job->reply_payload.sg_cnt,
pbuf, size);
lpfc_bsg_dma_page_free(phba, dmabuf);
if (phba->mbox_ext_buf_ctx.seqNum == phba->mbox_ext_buf_ctx.numBuf) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2965 SLI_CONFIG (hbd) ext-buffer rd mbox "
"command session done\n");
lpfc_bsg_mbox_ext_session_reset(phba);
}
job->reply->result = 0;
job->job_done(job);
return SLI_CONFIG_HANDLED;
}
/**
* lpfc_bsg_write_ebuf_set - set the next mailbox write external buffer
* @phba: Pointer to HBA context object.
* @dmabuf: Pointer to a DMA buffer descriptor.
*
* This routine sets up the next mailbox read external buffer obtained
* from user space through BSG.
**/
static int
lpfc_bsg_write_ebuf_set(struct lpfc_hba *phba, struct fc_bsg_job *job,
struct lpfc_dmabuf *dmabuf)
{
struct lpfc_sli_config_mbox *sli_cfg_mbx;
struct bsg_job_data *dd_data = NULL;
LPFC_MBOXQ_t *pmboxq = NULL;
MAILBOX_t *pmb;
enum nemb_type nemb_tp;
uint8_t *pbuf;
uint32_t size;
uint32_t index;
int rc;
index = phba->mbox_ext_buf_ctx.seqNum;
phba->mbox_ext_buf_ctx.seqNum++;
nemb_tp = phba->mbox_ext_buf_ctx.nembType;
sli_cfg_mbx = (struct lpfc_sli_config_mbox *)
phba->mbox_ext_buf_ctx.mbx_dmabuf->virt;
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
rc = -ENOMEM;
goto job_error;
}
pbuf = (uint8_t *)dmabuf->virt;
size = job->request_payload.payload_len;
sg_copy_to_buffer(job->request_payload.sg_list,
job->request_payload.sg_cnt,
pbuf, size);
if (phba->mbox_ext_buf_ctx.nembType == nemb_mse) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2966 SLI_CONFIG (mse) ext-buffer wr set "
"buffer[%d], size:%d\n",
phba->mbox_ext_buf_ctx.seqNum, size);
} else {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2967 SLI_CONFIG (hbd) ext-buffer wr set "
"buffer[%d], size:%d\n",
phba->mbox_ext_buf_ctx.seqNum, size);
}
/* set up external buffer descriptor and add to external buffer list */
lpfc_bsg_sli_cfg_dma_desc_setup(phba, nemb_tp, index,
phba->mbox_ext_buf_ctx.mbx_dmabuf,
dmabuf);
list_add_tail(&dmabuf->list, &phba->mbox_ext_buf_ctx.ext_dmabuf_list);
/* after write dma buffer */
lpfc_idiag_mbxacc_dump_bsg_mbox(phba, phba->mbox_ext_buf_ctx.nembType,
mbox_wr, dma_ebuf, sta_pos_addr,
dmabuf, index);
if (phba->mbox_ext_buf_ctx.seqNum == phba->mbox_ext_buf_ctx.numBuf) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2968 SLI_CONFIG ext-buffer wr all %d "
"ebuffers received\n",
phba->mbox_ext_buf_ctx.numBuf);
/* mailbox command structure for base driver */
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq) {
rc = -ENOMEM;
goto job_error;
}
memset(pmboxq, 0, sizeof(LPFC_MBOXQ_t));
pbuf = (uint8_t *)phba->mbox_ext_buf_ctx.mbx_dmabuf->virt;
pmb = &pmboxq->u.mb;
memcpy(pmb, pbuf, sizeof(*pmb));
pmb->mbxOwner = OWN_HOST;
pmboxq->vport = phba->pport;
/* callback for multi-buffer write mailbox command */
pmboxq->mbox_cmpl = lpfc_bsg_issue_write_mbox_ext_cmpl;
/* context fields to callback function */
pmboxq->context1 = dd_data;
dd_data->type = TYPE_MBOX;
dd_data->context_un.mbox.pmboxq = pmboxq;
dd_data->context_un.mbox.mb = (MAILBOX_t *)pbuf;
dd_data->context_un.mbox.set_job = job;
job->dd_data = dd_data;
/* state change */
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_PORT;
rc = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
if ((rc == MBX_SUCCESS) || (rc == MBX_BUSY)) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2969 Issued SLI_CONFIG ext-buffer "
"maibox command, rc:x%x\n", rc);
return SLI_CONFIG_HANDLED;
}
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2970 Failed to issue SLI_CONFIG ext-buffer "
"maibox command, rc:x%x\n", rc);
rc = -EPIPE;
goto job_error;
}
/* wait for additoinal external buffers */
job->reply->result = 0;
job->job_done(job);
return SLI_CONFIG_HANDLED;
job_error:
lpfc_bsg_dma_page_free(phba, dmabuf);
kfree(dd_data);
return rc;
}
/**
* lpfc_bsg_handle_sli_cfg_ebuf - handle ext buffer with sli-cfg mailbox cmd
* @phba: Pointer to HBA context object.
* @mb: Pointer to a BSG mailbox object.
* @dmabuff: Pointer to a DMA buffer descriptor.
*
* This routine handles the external buffer with SLI_CONFIG (0x9B) mailbox
* command with multiple non-embedded external buffers.
**/
static int
lpfc_bsg_handle_sli_cfg_ebuf(struct lpfc_hba *phba, struct fc_bsg_job *job,
struct lpfc_dmabuf *dmabuf)
{
int rc;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2971 SLI_CONFIG buffer (type:x%x)\n",
phba->mbox_ext_buf_ctx.mboxType);
if (phba->mbox_ext_buf_ctx.mboxType == mbox_rd) {
if (phba->mbox_ext_buf_ctx.state != LPFC_BSG_MBOX_DONE) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2972 SLI_CONFIG rd buffer state "
"mismatch:x%x\n",
phba->mbox_ext_buf_ctx.state);
lpfc_bsg_mbox_ext_abort(phba);
return -EPIPE;
}
rc = lpfc_bsg_read_ebuf_get(phba, job);
if (rc == SLI_CONFIG_HANDLED)
lpfc_bsg_dma_page_free(phba, dmabuf);
} else { /* phba->mbox_ext_buf_ctx.mboxType == mbox_wr */
if (phba->mbox_ext_buf_ctx.state != LPFC_BSG_MBOX_HOST) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2973 SLI_CONFIG wr buffer state "
"mismatch:x%x\n",
phba->mbox_ext_buf_ctx.state);
lpfc_bsg_mbox_ext_abort(phba);
return -EPIPE;
}
rc = lpfc_bsg_write_ebuf_set(phba, job, dmabuf);
}
return rc;
}
/**
* lpfc_bsg_handle_sli_cfg_ext - handle sli-cfg mailbox with external buffer
* @phba: Pointer to HBA context object.
* @mb: Pointer to a BSG mailbox object.
* @dmabuff: Pointer to a DMA buffer descriptor.
*
* This routine checkes and handles non-embedded multi-buffer SLI_CONFIG
* (0x9B) mailbox commands and external buffers.
**/
static int
lpfc_bsg_handle_sli_cfg_ext(struct lpfc_hba *phba, struct fc_bsg_job *job,
struct lpfc_dmabuf *dmabuf)
{
struct dfc_mbox_req *mbox_req;
int rc = SLI_CONFIG_NOT_HANDLED;
mbox_req =
(struct dfc_mbox_req *)job->request->rqst_data.h_vendor.vendor_cmd;
/* mbox command with/without single external buffer */
if (mbox_req->extMboxTag == 0 && mbox_req->extSeqNum == 0)
return rc;
/* mbox command and first external buffer */
if (phba->mbox_ext_buf_ctx.state == LPFC_BSG_MBOX_IDLE) {
if (mbox_req->extSeqNum == 1) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2974 SLI_CONFIG mailbox: tag:%d, "
"seq:%d\n", mbox_req->extMboxTag,
mbox_req->extSeqNum);
rc = lpfc_bsg_handle_sli_cfg_mbox(phba, job, dmabuf);
return rc;
} else
goto sli_cfg_ext_error;
}
/*
* handle additional external buffers
*/
/* check broken pipe conditions */
if (mbox_req->extMboxTag != phba->mbox_ext_buf_ctx.mbxTag)
goto sli_cfg_ext_error;
if (mbox_req->extSeqNum > phba->mbox_ext_buf_ctx.numBuf)
goto sli_cfg_ext_error;
if (mbox_req->extSeqNum != phba->mbox_ext_buf_ctx.seqNum + 1)
goto sli_cfg_ext_error;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2975 SLI_CONFIG mailbox external buffer: "
"extSta:x%x, tag:%d, seq:%d\n",
phba->mbox_ext_buf_ctx.state, mbox_req->extMboxTag,
mbox_req->extSeqNum);
rc = lpfc_bsg_handle_sli_cfg_ebuf(phba, job, dmabuf);
return rc;
sli_cfg_ext_error:
/* all other cases, broken pipe */
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2976 SLI_CONFIG mailbox broken pipe: "
"ctxSta:x%x, ctxNumBuf:%d "
"ctxTag:%d, ctxSeq:%d, tag:%d, seq:%d\n",
phba->mbox_ext_buf_ctx.state,
phba->mbox_ext_buf_ctx.numBuf,
phba->mbox_ext_buf_ctx.mbxTag,
phba->mbox_ext_buf_ctx.seqNum,
mbox_req->extMboxTag, mbox_req->extSeqNum);
lpfc_bsg_mbox_ext_session_reset(phba);
return -EPIPE;
}
/**
* lpfc_bsg_issue_mbox - issues a mailbox command on behalf of an app
* @phba: Pointer to HBA context object.
* @mb: Pointer to a mailbox object.
* @vport: Pointer to a vport object.
*
* Allocate a tracking object, mailbox command memory, get a mailbox
* from the mailbox pool, copy the caller mailbox command.
*
* If offline and the sli is active we need to poll for the command (port is
* being reset) and com-plete the job, otherwise issue the mailbox command and
* let our completion handler finish the command.
**/
static uint32_t
lpfc_bsg_issue_mbox(struct lpfc_hba *phba, struct fc_bsg_job *job,
struct lpfc_vport *vport)
{
LPFC_MBOXQ_t *pmboxq = NULL; /* internal mailbox queue */
MAILBOX_t *pmb; /* shortcut to the pmboxq mailbox */
/* a 4k buffer to hold the mb and extended data from/to the bsg */
uint8_t *pmbx = NULL;
struct bsg_job_data *dd_data = NULL; /* bsg data tracking structure */
struct lpfc_dmabuf *dmabuf = NULL;
struct dfc_mbox_req *mbox_req;
struct READ_EVENT_LOG_VAR *rdEventLog;
uint32_t transmit_length, receive_length, mode;
struct lpfc_mbx_sli4_config *sli4_config;
struct lpfc_mbx_nembed_cmd *nembed_sge;
struct mbox_header *header;
struct ulp_bde64 *bde;
uint8_t *ext = NULL;
int rc = 0;
uint8_t *from;
uint32_t size;
/* in case no data is transferred */
job->reply->reply_payload_rcv_len = 0;
/* sanity check to protect driver */
if (job->reply_payload.payload_len > BSG_MBOX_SIZE ||
job->request_payload.payload_len > BSG_MBOX_SIZE) {
rc = -ERANGE;
goto job_done;
}
/*
* Don't allow mailbox commands to be sent when blocked or when in
* the middle of discovery
*/
if (phba->sli.sli_flag & LPFC_BLOCK_MGMT_IO) {
rc = -EAGAIN;
goto job_done;
}
mbox_req =
(struct dfc_mbox_req *)job->request->rqst_data.h_vendor.vendor_cmd;
/* check if requested extended data lengths are valid */
if ((mbox_req->inExtWLen > BSG_MBOX_SIZE/sizeof(uint32_t)) ||
(mbox_req->outExtWLen > BSG_MBOX_SIZE/sizeof(uint32_t))) {
rc = -ERANGE;
goto job_done;
}
dmabuf = lpfc_bsg_dma_page_alloc(phba);
if (!dmabuf || !dmabuf->virt) {
rc = -ENOMEM;
goto job_done;
}
/* Get the mailbox command or external buffer from BSG */
pmbx = (uint8_t *)dmabuf->virt;
size = job->request_payload.payload_len;
sg_copy_to_buffer(job->request_payload.sg_list,
job->request_payload.sg_cnt, pmbx, size);
/* Handle possible SLI_CONFIG with non-embedded payloads */
if (phba->sli_rev == LPFC_SLI_REV4) {
rc = lpfc_bsg_handle_sli_cfg_ext(phba, job, dmabuf);
if (rc == SLI_CONFIG_HANDLED)
goto job_cont;
if (rc)
goto job_done;
/* SLI_CONFIG_NOT_HANDLED for other mailbox commands */
}
rc = lpfc_bsg_check_cmd_access(phba, (MAILBOX_t *)pmbx, vport);
if (rc != 0)
goto job_done; /* must be negative */
/* allocate our bsg tracking structure */
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2727 Failed allocation of dd_data\n");
rc = -ENOMEM;
goto job_done;
}
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq) {
rc = -ENOMEM;
goto job_done;
}
memset(pmboxq, 0, sizeof(LPFC_MBOXQ_t));
pmb = &pmboxq->u.mb;
memcpy(pmb, pmbx, sizeof(*pmb));
pmb->mbxOwner = OWN_HOST;
pmboxq->vport = vport;
/* If HBA encountered an error attention, allow only DUMP
* or RESTART mailbox commands until the HBA is restarted.
*/
if (phba->pport->stopped &&
pmb->mbxCommand != MBX_DUMP_MEMORY &&
pmb->mbxCommand != MBX_RESTART &&
pmb->mbxCommand != MBX_WRITE_VPARMS &&
pmb->mbxCommand != MBX_WRITE_WWN)
lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX,
"2797 mbox: Issued mailbox cmd "
"0x%x while in stopped state.\n",
pmb->mbxCommand);
/* extended mailbox commands will need an extended buffer */
if (mbox_req->inExtWLen || mbox_req->outExtWLen) {
from = pmbx;
ext = from + sizeof(MAILBOX_t);
pmboxq->context2 = ext;
pmboxq->in_ext_byte_len =
mbox_req->inExtWLen * sizeof(uint32_t);
pmboxq->out_ext_byte_len =
mbox_req->outExtWLen * sizeof(uint32_t);
pmboxq->mbox_offset_word = mbox_req->mbOffset;
}
/* biu diag will need a kernel buffer to transfer the data
* allocate our own buffer and setup the mailbox command to
* use ours
*/
if (pmb->mbxCommand == MBX_RUN_BIU_DIAG64) {
transmit_length = pmb->un.varWords[1];
receive_length = pmb->un.varWords[4];
/* transmit length cannot be greater than receive length or
* mailbox extension size
*/
if ((transmit_length > receive_length) ||
(transmit_length > BSG_MBOX_SIZE - sizeof(MAILBOX_t))) {
rc = -ERANGE;
goto job_done;
}
pmb->un.varBIUdiag.un.s2.xmit_bde64.addrHigh =
putPaddrHigh(dmabuf->phys + sizeof(MAILBOX_t));
pmb->un.varBIUdiag.un.s2.xmit_bde64.addrLow =
putPaddrLow(dmabuf->phys + sizeof(MAILBOX_t));
pmb->un.varBIUdiag.un.s2.rcv_bde64.addrHigh =
putPaddrHigh(dmabuf->phys + sizeof(MAILBOX_t)
+ pmb->un.varBIUdiag.un.s2.xmit_bde64.tus.f.bdeSize);
pmb->un.varBIUdiag.un.s2.rcv_bde64.addrLow =
putPaddrLow(dmabuf->phys + sizeof(MAILBOX_t)
+ pmb->un.varBIUdiag.un.s2.xmit_bde64.tus.f.bdeSize);
} else if (pmb->mbxCommand == MBX_READ_EVENT_LOG) {
rdEventLog = &pmb->un.varRdEventLog;
receive_length = rdEventLog->rcv_bde64.tus.f.bdeSize;
mode = bf_get(lpfc_event_log, rdEventLog);
/* receive length cannot be greater than mailbox
* extension size
*/
if (receive_length > BSG_MBOX_SIZE - sizeof(MAILBOX_t)) {
rc = -ERANGE;
goto job_done;
}
/* mode zero uses a bde like biu diags command */
if (mode == 0) {
pmb->un.varWords[3] = putPaddrLow(dmabuf->phys
+ sizeof(MAILBOX_t));
pmb->un.varWords[4] = putPaddrHigh(dmabuf->phys
+ sizeof(MAILBOX_t));
}
} else if (phba->sli_rev == LPFC_SLI_REV4) {
/* Let type 4 (well known data) through because the data is
* returned in varwords[4-8]
* otherwise check the recieve length and fetch the buffer addr
*/
if ((pmb->mbxCommand == MBX_DUMP_MEMORY) &&
(pmb->un.varDmp.type != DMP_WELL_KNOWN)) {
/* rebuild the command for sli4 using our own buffers
* like we do for biu diags
*/
receive_length = pmb->un.varWords[2];
/* receive length cannot be greater than mailbox
* extension size
*/
if (receive_length == 0) {
rc = -ERANGE;
goto job_done;
}
pmb->un.varWords[3] = putPaddrLow(dmabuf->phys
+ sizeof(MAILBOX_t));
pmb->un.varWords[4] = putPaddrHigh(dmabuf->phys
+ sizeof(MAILBOX_t));
} else if ((pmb->mbxCommand == MBX_UPDATE_CFG) &&
pmb->un.varUpdateCfg.co) {
bde = (struct ulp_bde64 *)&pmb->un.varWords[4];
/* bde size cannot be greater than mailbox ext size */
if (bde->tus.f.bdeSize >
BSG_MBOX_SIZE - sizeof(MAILBOX_t)) {
rc = -ERANGE;
goto job_done;
}
bde->addrHigh = putPaddrHigh(dmabuf->phys
+ sizeof(MAILBOX_t));
bde->addrLow = putPaddrLow(dmabuf->phys
+ sizeof(MAILBOX_t));
} else if (pmb->mbxCommand == MBX_SLI4_CONFIG) {
/* Handling non-embedded SLI_CONFIG mailbox command */
sli4_config = &pmboxq->u.mqe.un.sli4_config;
if (!bf_get(lpfc_mbox_hdr_emb,
&sli4_config->header.cfg_mhdr)) {
/* rebuild the command for sli4 using our
* own buffers like we do for biu diags
*/
header = (struct mbox_header *)
&pmb->un.varWords[0];
nembed_sge = (struct lpfc_mbx_nembed_cmd *)
&pmb->un.varWords[0];
receive_length = nembed_sge->sge[0].length;
/* receive length cannot be greater than
* mailbox extension size
*/
if ((receive_length == 0) ||
(receive_length >
BSG_MBOX_SIZE - sizeof(MAILBOX_t))) {
rc = -ERANGE;
goto job_done;
}
nembed_sge->sge[0].pa_hi =
putPaddrHigh(dmabuf->phys
+ sizeof(MAILBOX_t));
nembed_sge->sge[0].pa_lo =
putPaddrLow(dmabuf->phys
+ sizeof(MAILBOX_t));
}
}
}
dd_data->context_un.mbox.dmabuffers = dmabuf;
/* setup wake call as IOCB callback */
pmboxq->mbox_cmpl = lpfc_bsg_issue_mbox_cmpl;
/* setup context field to pass wait_queue pointer to wake function */
pmboxq->context1 = dd_data;
dd_data->type = TYPE_MBOX;
dd_data->context_un.mbox.pmboxq = pmboxq;
dd_data->context_un.mbox.mb = (MAILBOX_t *)pmbx;
dd_data->context_un.mbox.set_job = job;
dd_data->context_un.mbox.ext = ext;
dd_data->context_un.mbox.mbOffset = mbox_req->mbOffset;
dd_data->context_un.mbox.inExtWLen = mbox_req->inExtWLen;
dd_data->context_un.mbox.outExtWLen = mbox_req->outExtWLen;
job->dd_data = dd_data;
if ((vport->fc_flag & FC_OFFLINE_MODE) ||
(!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))) {
rc = lpfc_sli_issue_mbox(phba, pmboxq, MBX_POLL);
if (rc != MBX_SUCCESS) {
rc = (rc == MBX_TIMEOUT) ? -ETIME : -ENODEV;
goto job_done;
}
/* job finished, copy the data */
memcpy(pmbx, pmb, sizeof(*pmb));
job->reply->reply_payload_rcv_len =
sg_copy_from_buffer(job->reply_payload.sg_list,
job->reply_payload.sg_cnt,
pmbx, size);
/* not waiting mbox already done */
rc = 0;
goto job_done;
}
rc = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
if ((rc == MBX_SUCCESS) || (rc == MBX_BUSY))
return 1; /* job started */
job_done:
/* common exit for error or job completed inline */
if (pmboxq)
mempool_free(pmboxq, phba->mbox_mem_pool);
lpfc_bsg_dma_page_free(phba, dmabuf);
kfree(dd_data);
job_cont:
return rc;
}
/**
* lpfc_bsg_mbox_cmd - process an fc bsg LPFC_BSG_VENDOR_MBOX command
* @job: MBOX fc_bsg_job for LPFC_BSG_VENDOR_MBOX.
**/
static int
lpfc_bsg_mbox_cmd(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct dfc_mbox_req *mbox_req;
int rc = 0;
/* mix-and-match backward compatibility */
job->reply->reply_payload_rcv_len = 0;
if (job->request_len <
sizeof(struct fc_bsg_request) + sizeof(struct dfc_mbox_req)) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2737 Mix-and-match backward compability "
"between MBOX_REQ old size:%d and "
"new request size:%d\n",
(int)(job->request_len -
sizeof(struct fc_bsg_request)),
(int)sizeof(struct dfc_mbox_req));
mbox_req = (struct dfc_mbox_req *)
job->request->rqst_data.h_vendor.vendor_cmd;
mbox_req->extMboxTag = 0;
mbox_req->extSeqNum = 0;
}
rc = lpfc_bsg_issue_mbox(phba, job, vport);
if (rc == 0) {
/* job done */
job->reply->result = 0;
job->dd_data = NULL;
job->job_done(job);
} else if (rc == 1)
/* job submitted, will complete later*/
rc = 0; /* return zero, no error */
else {
/* some error occurred */
job->reply->result = rc;
job->dd_data = NULL;
}
return rc;
}
/**
* lpfc_bsg_menlo_cmd_cmp - lpfc_menlo_cmd completion handler
* @phba: Pointer to HBA context object.
* @cmdiocbq: Pointer to command iocb.
* @rspiocbq: Pointer to response iocb.
*
* This function is the completion handler for iocbs issued using
* lpfc_menlo_cmd function. This function is called by the
* ring event handler function without any lock held. This function
* can be called from both worker thread context and interrupt
* context. This function also can be called from another thread which
* cleans up the SLI layer objects.
* This function copies the contents of the response iocb to the
* response iocb memory object provided by the caller of
* lpfc_sli_issue_iocb_wait and then wakes up the thread which
* sleeps for the iocb completion.
**/
static void
lpfc_bsg_menlo_cmd_cmp(struct lpfc_hba *phba,
struct lpfc_iocbq *cmdiocbq,
struct lpfc_iocbq *rspiocbq)
{
struct bsg_job_data *dd_data;
struct fc_bsg_job *job;
IOCB_t *rsp;
struct lpfc_dmabuf *bmp;
struct lpfc_bsg_menlo *menlo;
unsigned long flags;
struct menlo_response *menlo_resp;
int rc = 0;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
dd_data = cmdiocbq->context1;
if (!dd_data) {
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
menlo = &dd_data->context_un.menlo;
job = menlo->set_job;
job->dd_data = NULL; /* so timeout handler does not reply */
spin_lock(&phba->hbalock);
cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
if (cmdiocbq->context2 && rspiocbq)
memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
&rspiocbq->iocb, sizeof(IOCB_t));
spin_unlock(&phba->hbalock);
bmp = menlo->bmp;
rspiocbq = menlo->rspiocbq;
rsp = &rspiocbq->iocb;
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
pci_unmap_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
/* always return the xri, this would be used in the case
* of a menlo download to allow the data to be sent as a continuation
* of the exchange.
*/
menlo_resp = (struct menlo_response *)
job->reply->reply_data.vendor_reply.vendor_rsp;
menlo_resp->xri = rsp->ulpContext;
if (rsp->ulpStatus) {
if (rsp->ulpStatus == IOSTAT_LOCAL_REJECT) {
switch (rsp->un.ulpWord[4] & 0xff) {
case IOERR_SEQUENCE_TIMEOUT:
rc = -ETIMEDOUT;
break;
case IOERR_INVALID_RPI:
rc = -EFAULT;
break;
default:
rc = -EACCES;
break;
}
} else
rc = -EACCES;
} else
job->reply->reply_payload_rcv_len =
rsp->un.genreq64.bdl.bdeSize;
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
lpfc_sli_release_iocbq(phba, rspiocbq);
lpfc_sli_release_iocbq(phba, cmdiocbq);
kfree(bmp);
kfree(dd_data);
/* make error code available to userspace */
job->reply->result = rc;
/* complete the job back to userspace */
job->job_done(job);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
/**
* lpfc_menlo_cmd - send an ioctl for menlo hardware
* @job: fc_bsg_job to handle
*
* This function issues a gen request 64 CR ioctl for all menlo cmd requests,
* all the command completions will return the xri for the command.
* For menlo data requests a gen request 64 CX is used to continue the exchange
* supplied in the menlo request header xri field.
**/
static int
lpfc_menlo_cmd(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct lpfc_iocbq *cmdiocbq, *rspiocbq;
IOCB_t *cmd, *rsp;
int rc = 0;
struct menlo_command *menlo_cmd;
struct menlo_response *menlo_resp;
struct lpfc_dmabuf *bmp = NULL;
int request_nseg;
int reply_nseg;
struct scatterlist *sgel = NULL;
int numbde;
dma_addr_t busaddr;
struct bsg_job_data *dd_data;
struct ulp_bde64 *bpl = NULL;
/* in case no data is returned return just the return code */
job->reply->reply_payload_rcv_len = 0;
if (job->request_len <
sizeof(struct fc_bsg_request) +
sizeof(struct menlo_command)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2784 Received MENLO_CMD request below "
"minimum size\n");
rc = -ERANGE;
goto no_dd_data;
}
if (job->reply_len <
sizeof(struct fc_bsg_request) + sizeof(struct menlo_response)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2785 Received MENLO_CMD reply below "
"minimum size\n");
rc = -ERANGE;
goto no_dd_data;
}
if (!(phba->menlo_flag & HBA_MENLO_SUPPORT)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2786 Adapter does not support menlo "
"commands\n");
rc = -EPERM;
goto no_dd_data;
}
menlo_cmd = (struct menlo_command *)
job->request->rqst_data.h_vendor.vendor_cmd;
menlo_resp = (struct menlo_response *)
job->reply->reply_data.vendor_reply.vendor_rsp;
/* allocate our bsg tracking structure */
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2787 Failed allocation of dd_data\n");
rc = -ENOMEM;
goto no_dd_data;
}
bmp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (!bmp) {
rc = -ENOMEM;
goto free_dd;
}
cmdiocbq = lpfc_sli_get_iocbq(phba);
if (!cmdiocbq) {
rc = -ENOMEM;
goto free_bmp;
}
rspiocbq = lpfc_sli_get_iocbq(phba);
if (!rspiocbq) {
rc = -ENOMEM;
goto free_cmdiocbq;
}
rsp = &rspiocbq->iocb;
bmp->virt = lpfc_mbuf_alloc(phba, 0, &bmp->phys);
if (!bmp->virt) {
rc = -ENOMEM;
goto free_rspiocbq;
}
INIT_LIST_HEAD(&bmp->list);
bpl = (struct ulp_bde64 *) bmp->virt;
request_nseg = pci_map_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
for_each_sg(job->request_payload.sg_list, sgel, request_nseg, numbde) {
busaddr = sg_dma_address(sgel);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
bpl->tus.f.bdeSize = sg_dma_len(sgel);
bpl->tus.w = cpu_to_le32(bpl->tus.w);
bpl->addrLow = cpu_to_le32(putPaddrLow(busaddr));
bpl->addrHigh = cpu_to_le32(putPaddrHigh(busaddr));
bpl++;
}
reply_nseg = pci_map_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
for_each_sg(job->reply_payload.sg_list, sgel, reply_nseg, numbde) {
busaddr = sg_dma_address(sgel);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64I;
bpl->tus.f.bdeSize = sg_dma_len(sgel);
bpl->tus.w = cpu_to_le32(bpl->tus.w);
bpl->addrLow = cpu_to_le32(putPaddrLow(busaddr));
bpl->addrHigh = cpu_to_le32(putPaddrHigh(busaddr));
bpl++;
}
cmd = &cmdiocbq->iocb;
cmd->un.genreq64.bdl.ulpIoTag32 = 0;
cmd->un.genreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
cmd->un.genreq64.bdl.addrLow = putPaddrLow(bmp->phys);
cmd->un.genreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
cmd->un.genreq64.bdl.bdeSize =
(request_nseg + reply_nseg) * sizeof(struct ulp_bde64);
cmd->un.genreq64.w5.hcsw.Fctl = (SI | LA);
cmd->un.genreq64.w5.hcsw.Dfctl = 0;
cmd->un.genreq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CMD;
cmd->un.genreq64.w5.hcsw.Type = MENLO_TRANSPORT_TYPE; /* 0xfe */
cmd->ulpBdeCount = 1;
cmd->ulpClass = CLASS3;
cmd->ulpOwner = OWN_CHIP;
cmd->ulpLe = 1; /* Limited Edition */
cmdiocbq->iocb_flag |= LPFC_IO_LIBDFC;
cmdiocbq->vport = phba->pport;
/* We want the firmware to timeout before we do */
cmd->ulpTimeout = MENLO_TIMEOUT - 5;
cmdiocbq->context3 = bmp;
cmdiocbq->context2 = rspiocbq;
cmdiocbq->iocb_cmpl = lpfc_bsg_menlo_cmd_cmp;
cmdiocbq->context1 = dd_data;
cmdiocbq->context2 = rspiocbq;
if (menlo_cmd->cmd == LPFC_BSG_VENDOR_MENLO_CMD) {
cmd->ulpCommand = CMD_GEN_REQUEST64_CR;
cmd->ulpPU = MENLO_PU; /* 3 */
cmd->un.ulpWord[4] = MENLO_DID; /* 0x0000FC0E */
cmd->ulpContext = MENLO_CONTEXT; /* 0 */
} else {
cmd->ulpCommand = CMD_GEN_REQUEST64_CX;
cmd->ulpPU = 1;
cmd->un.ulpWord[4] = 0;
cmd->ulpContext = menlo_cmd->xri;
}
dd_data->type = TYPE_MENLO;
dd_data->context_un.menlo.cmdiocbq = cmdiocbq;
dd_data->context_un.menlo.rspiocbq = rspiocbq;
dd_data->context_un.menlo.set_job = job;
dd_data->context_un.menlo.bmp = bmp;
rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, cmdiocbq,
MENLO_TIMEOUT - 5);
if (rc == IOCB_SUCCESS)
return 0; /* done for now */
/* iocb failed so cleanup */
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
pci_unmap_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
free_rspiocbq:
lpfc_sli_release_iocbq(phba, rspiocbq);
free_cmdiocbq:
lpfc_sli_release_iocbq(phba, cmdiocbq);
free_bmp:
kfree(bmp);
free_dd:
kfree(dd_data);
no_dd_data:
/* make error code available to userspace */
job->reply->result = rc;
job->dd_data = NULL;
return rc;
}
/**
* lpfc_bsg_hst_vendor - process a vendor-specific fc_bsg_job
* @job: fc_bsg_job to handle
**/
static int
lpfc_bsg_hst_vendor(struct fc_bsg_job *job)
{
int command = job->request->rqst_data.h_vendor.vendor_cmd[0];
int rc;
switch (command) {
case LPFC_BSG_VENDOR_SET_CT_EVENT:
rc = lpfc_bsg_hba_set_event(job);
break;
case LPFC_BSG_VENDOR_GET_CT_EVENT:
rc = lpfc_bsg_hba_get_event(job);
break;
case LPFC_BSG_VENDOR_SEND_MGMT_RESP:
rc = lpfc_bsg_send_mgmt_rsp(job);
break;
case LPFC_BSG_VENDOR_DIAG_MODE:
rc = lpfc_bsg_diag_loopback_mode(job);
break;
case LPFC_BSG_VENDOR_DIAG_MODE_END:
rc = lpfc_sli4_bsg_diag_mode_end(job);
break;
case LPFC_BSG_VENDOR_DIAG_RUN_LOOPBACK:
rc = lpfc_bsg_diag_loopback_run(job);
break;
case LPFC_BSG_VENDOR_LINK_DIAG_TEST:
rc = lpfc_sli4_bsg_link_diag_test(job);
break;
case LPFC_BSG_VENDOR_GET_MGMT_REV:
rc = lpfc_bsg_get_dfc_rev(job);
break;
case LPFC_BSG_VENDOR_MBOX:
rc = lpfc_bsg_mbox_cmd(job);
break;
case LPFC_BSG_VENDOR_MENLO_CMD:
case LPFC_BSG_VENDOR_MENLO_DATA:
rc = lpfc_menlo_cmd(job);
break;
default:
rc = -EINVAL;
job->reply->reply_payload_rcv_len = 0;
/* make error code available to userspace */
job->reply->result = rc;
break;
}
return rc;
}
/**
* lpfc_bsg_request - handle a bsg request from the FC transport
* @job: fc_bsg_job to handle
**/
int
lpfc_bsg_request(struct fc_bsg_job *job)
{
uint32_t msgcode;
int rc;
msgcode = job->request->msgcode;
switch (msgcode) {
case FC_BSG_HST_VENDOR:
rc = lpfc_bsg_hst_vendor(job);
break;
case FC_BSG_RPT_ELS:
rc = lpfc_bsg_rport_els(job);
break;
case FC_BSG_RPT_CT:
rc = lpfc_bsg_send_mgmt_cmd(job);
break;
default:
rc = -EINVAL;
job->reply->reply_payload_rcv_len = 0;
/* make error code available to userspace */
job->reply->result = rc;
break;
}
return rc;
}
/**
* lpfc_bsg_timeout - handle timeout of a bsg request from the FC transport
* @job: fc_bsg_job that has timed out
*
* This function just aborts the job's IOCB. The aborted IOCB will return to
* the waiting function which will handle passing the error back to userspace
**/
int
lpfc_bsg_timeout(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct lpfc_iocbq *cmdiocb;
struct lpfc_bsg_event *evt;
struct lpfc_bsg_iocb *iocb;
struct lpfc_bsg_mbox *mbox;
struct lpfc_bsg_menlo *menlo;
struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
struct bsg_job_data *dd_data;
unsigned long flags;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
dd_data = (struct bsg_job_data *)job->dd_data;
/* timeout and completion crossed paths if no dd_data */
if (!dd_data) {
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return 0;
}
switch (dd_data->type) {
case TYPE_IOCB:
iocb = &dd_data->context_un.iocb;
cmdiocb = iocb->cmdiocbq;
/* hint to completion handler that the job timed out */
job->reply->result = -EAGAIN;
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
/* this will call our completion handler */
spin_lock_irq(&phba->hbalock);
lpfc_sli_issue_abort_iotag(phba, pring, cmdiocb);
spin_unlock_irq(&phba->hbalock);
break;
case TYPE_EVT:
evt = dd_data->context_un.evt;
/* this event has no job anymore */
evt->set_job = NULL;
job->dd_data = NULL;
job->reply->reply_payload_rcv_len = 0;
/* Return -EAGAIN which is our way of signallying the
* app to retry.
*/
job->reply->result = -EAGAIN;
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
job->job_done(job);
break;
case TYPE_MBOX:
mbox = &dd_data->context_un.mbox;
/* this mbox has no job anymore */
mbox->set_job = NULL;
job->dd_data = NULL;
job->reply->reply_payload_rcv_len = 0;
job->reply->result = -EAGAIN;
/* the mbox completion handler can now be run */
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
job->job_done(job);
if (phba->mbox_ext_buf_ctx.state == LPFC_BSG_MBOX_PORT)
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_ABTS;
break;
case TYPE_MENLO:
menlo = &dd_data->context_un.menlo;
cmdiocb = menlo->cmdiocbq;
/* hint to completion handler that the job timed out */
job->reply->result = -EAGAIN;
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
/* this will call our completion handler */
spin_lock_irq(&phba->hbalock);
lpfc_sli_issue_abort_iotag(phba, pring, cmdiocb);
spin_unlock_irq(&phba->hbalock);
break;
default:
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
break;
}
/* scsi transport fc fc_bsg_job_timeout expects a zero return code,
* otherwise an error message will be displayed on the console
* so always return success (zero)
*/
return 0;
}
| gpl-2.0 |
aweosomeabhijeet/android_kernel_sony_nicki | fs/xfs/xfs_bmap.c | 4808 | 181964 | /*
* Copyright (c) 2000-2006 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_dir2.h"
#include "xfs_da_btree.h"
#include "xfs_bmap_btree.h"
#include "xfs_alloc_btree.h"
#include "xfs_ialloc_btree.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_btree.h"
#include "xfs_mount.h"
#include "xfs_itable.h"
#include "xfs_inode_item.h"
#include "xfs_extfree_item.h"
#include "xfs_alloc.h"
#include "xfs_bmap.h"
#include "xfs_rtalloc.h"
#include "xfs_error.h"
#include "xfs_attr_leaf.h"
#include "xfs_rw.h"
#include "xfs_quota.h"
#include "xfs_trans_space.h"
#include "xfs_buf_item.h"
#include "xfs_filestream.h"
#include "xfs_vnodeops.h"
#include "xfs_trace.h"
kmem_zone_t *xfs_bmap_free_item_zone;
/*
* Prototypes for internal bmap routines.
*/
#ifdef DEBUG
STATIC void
xfs_bmap_check_leaf_extents(
struct xfs_btree_cur *cur,
struct xfs_inode *ip,
int whichfork);
#else
#define xfs_bmap_check_leaf_extents(cur, ip, whichfork) do { } while (0)
#endif
/*
* Called from xfs_bmap_add_attrfork to handle extents format files.
*/
STATIC int /* error */
xfs_bmap_add_attrfork_extents(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_fsblock_t *firstblock, /* first block allocated */
xfs_bmap_free_t *flist, /* blocks to free at commit */
int *flags); /* inode logging flags */
/*
* Called from xfs_bmap_add_attrfork to handle local format files.
*/
STATIC int /* error */
xfs_bmap_add_attrfork_local(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_fsblock_t *firstblock, /* first block allocated */
xfs_bmap_free_t *flist, /* blocks to free at commit */
int *flags); /* inode logging flags */
/*
* xfs_bmap_alloc is called by xfs_bmapi to allocate an extent for a file.
* It figures out where to ask the underlying allocator to put the new extent.
*/
STATIC int /* error */
xfs_bmap_alloc(
xfs_bmalloca_t *ap); /* bmap alloc argument struct */
/*
* Transform a btree format file with only one leaf node, where the
* extents list will fit in the inode, into an extents format file.
* Since the file extents are already in-core, all we have to do is
* give up the space for the btree root and pitch the leaf block.
*/
STATIC int /* error */
xfs_bmap_btree_to_extents(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_btree_cur_t *cur, /* btree cursor */
int *logflagsp, /* inode logging flags */
int whichfork); /* data or attr fork */
/*
* Remove the entry "free" from the free item list. Prev points to the
* previous entry, unless "free" is the head of the list.
*/
STATIC void
xfs_bmap_del_free(
xfs_bmap_free_t *flist, /* free item list header */
xfs_bmap_free_item_t *prev, /* previous item on list, if any */
xfs_bmap_free_item_t *free); /* list item to be freed */
/*
* Convert an extents-format file into a btree-format file.
* The new file will have a root block (in the inode) and a single child block.
*/
STATIC int /* error */
xfs_bmap_extents_to_btree(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_fsblock_t *firstblock, /* first-block-allocated */
xfs_bmap_free_t *flist, /* blocks freed in xaction */
xfs_btree_cur_t **curp, /* cursor returned to caller */
int wasdel, /* converting a delayed alloc */
int *logflagsp, /* inode logging flags */
int whichfork); /* data or attr fork */
/*
* Convert a local file to an extents file.
* This code is sort of bogus, since the file data needs to get
* logged so it won't be lost. The bmap-level manipulations are ok, though.
*/
STATIC int /* error */
xfs_bmap_local_to_extents(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_fsblock_t *firstblock, /* first block allocated in xaction */
xfs_extlen_t total, /* total blocks needed by transaction */
int *logflagsp, /* inode logging flags */
int whichfork); /* data or attr fork */
/*
* Search the extents list for the inode, for the extent containing bno.
* If bno lies in a hole, point to the next entry. If bno lies past eof,
* *eofp will be set, and *prevp will contain the last entry (null if none).
* Else, *lastxp will be set to the index of the found
* entry; *gotp will contain the entry.
*/
STATIC xfs_bmbt_rec_host_t * /* pointer to found extent entry */
xfs_bmap_search_extents(
xfs_inode_t *ip, /* incore inode pointer */
xfs_fileoff_t bno, /* block number searched for */
int whichfork, /* data or attr fork */
int *eofp, /* out: end of file found */
xfs_extnum_t *lastxp, /* out: last extent index */
xfs_bmbt_irec_t *gotp, /* out: extent entry found */
xfs_bmbt_irec_t *prevp); /* out: previous extent entry found */
/*
* Compute the worst-case number of indirect blocks that will be used
* for ip's delayed extent of length "len".
*/
STATIC xfs_filblks_t
xfs_bmap_worst_indlen(
xfs_inode_t *ip, /* incore inode pointer */
xfs_filblks_t len); /* delayed extent length */
#ifdef DEBUG
/*
* Perform various validation checks on the values being returned
* from xfs_bmapi().
*/
STATIC void
xfs_bmap_validate_ret(
xfs_fileoff_t bno,
xfs_filblks_t len,
int flags,
xfs_bmbt_irec_t *mval,
int nmap,
int ret_nmap);
#else
#define xfs_bmap_validate_ret(bno,len,flags,mval,onmap,nmap)
#endif /* DEBUG */
STATIC int
xfs_bmap_count_tree(
xfs_mount_t *mp,
xfs_trans_t *tp,
xfs_ifork_t *ifp,
xfs_fsblock_t blockno,
int levelin,
int *count);
STATIC void
xfs_bmap_count_leaves(
xfs_ifork_t *ifp,
xfs_extnum_t idx,
int numrecs,
int *count);
STATIC void
xfs_bmap_disk_count_leaves(
struct xfs_mount *mp,
struct xfs_btree_block *block,
int numrecs,
int *count);
/*
* Bmap internal routines.
*/
STATIC int /* error */
xfs_bmbt_lookup_eq(
struct xfs_btree_cur *cur,
xfs_fileoff_t off,
xfs_fsblock_t bno,
xfs_filblks_t len,
int *stat) /* success/failure */
{
cur->bc_rec.b.br_startoff = off;
cur->bc_rec.b.br_startblock = bno;
cur->bc_rec.b.br_blockcount = len;
return xfs_btree_lookup(cur, XFS_LOOKUP_EQ, stat);
}
STATIC int /* error */
xfs_bmbt_lookup_ge(
struct xfs_btree_cur *cur,
xfs_fileoff_t off,
xfs_fsblock_t bno,
xfs_filblks_t len,
int *stat) /* success/failure */
{
cur->bc_rec.b.br_startoff = off;
cur->bc_rec.b.br_startblock = bno;
cur->bc_rec.b.br_blockcount = len;
return xfs_btree_lookup(cur, XFS_LOOKUP_GE, stat);
}
/*
* Check if the inode needs to be converted to btree format.
*/
static inline bool xfs_bmap_needs_btree(struct xfs_inode *ip, int whichfork)
{
return XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_NEXTENTS(ip, whichfork) >
XFS_IFORK_MAXEXT(ip, whichfork);
}
/*
* Check if the inode should be converted to extent format.
*/
static inline bool xfs_bmap_wants_extents(struct xfs_inode *ip, int whichfork)
{
return XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE &&
XFS_IFORK_NEXTENTS(ip, whichfork) <=
XFS_IFORK_MAXEXT(ip, whichfork);
}
/*
* Update the record referred to by cur to the value given
* by [off, bno, len, state].
* This either works (return 0) or gets an EFSCORRUPTED error.
*/
STATIC int
xfs_bmbt_update(
struct xfs_btree_cur *cur,
xfs_fileoff_t off,
xfs_fsblock_t bno,
xfs_filblks_t len,
xfs_exntst_t state)
{
union xfs_btree_rec rec;
xfs_bmbt_disk_set_allf(&rec.bmbt, off, bno, len, state);
return xfs_btree_update(cur, &rec);
}
/*
* Called from xfs_bmap_add_attrfork to handle btree format files.
*/
STATIC int /* error */
xfs_bmap_add_attrfork_btree(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_fsblock_t *firstblock, /* first block allocated */
xfs_bmap_free_t *flist, /* blocks to free at commit */
int *flags) /* inode logging flags */
{
xfs_btree_cur_t *cur; /* btree cursor */
int error; /* error return value */
xfs_mount_t *mp; /* file system mount struct */
int stat; /* newroot status */
mp = ip->i_mount;
if (ip->i_df.if_broot_bytes <= XFS_IFORK_DSIZE(ip))
*flags |= XFS_ILOG_DBROOT;
else {
cur = xfs_bmbt_init_cursor(mp, tp, ip, XFS_DATA_FORK);
cur->bc_private.b.flist = flist;
cur->bc_private.b.firstblock = *firstblock;
if ((error = xfs_bmbt_lookup_ge(cur, 0, 0, 0, &stat)))
goto error0;
/* must be at least one entry */
XFS_WANT_CORRUPTED_GOTO(stat == 1, error0);
if ((error = xfs_btree_new_iroot(cur, flags, &stat)))
goto error0;
if (stat == 0) {
xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
return XFS_ERROR(ENOSPC);
}
*firstblock = cur->bc_private.b.firstblock;
cur->bc_private.b.allocated = 0;
xfs_btree_del_cursor(cur, XFS_BTREE_NOERROR);
}
return 0;
error0:
xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
return error;
}
/*
* Called from xfs_bmap_add_attrfork to handle extents format files.
*/
STATIC int /* error */
xfs_bmap_add_attrfork_extents(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_fsblock_t *firstblock, /* first block allocated */
xfs_bmap_free_t *flist, /* blocks to free at commit */
int *flags) /* inode logging flags */
{
xfs_btree_cur_t *cur; /* bmap btree cursor */
int error; /* error return value */
if (ip->i_d.di_nextents * sizeof(xfs_bmbt_rec_t) <= XFS_IFORK_DSIZE(ip))
return 0;
cur = NULL;
error = xfs_bmap_extents_to_btree(tp, ip, firstblock, flist, &cur, 0,
flags, XFS_DATA_FORK);
if (cur) {
cur->bc_private.b.allocated = 0;
xfs_btree_del_cursor(cur,
error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
}
return error;
}
/*
* Called from xfs_bmap_add_attrfork to handle local format files.
*/
STATIC int /* error */
xfs_bmap_add_attrfork_local(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_fsblock_t *firstblock, /* first block allocated */
xfs_bmap_free_t *flist, /* blocks to free at commit */
int *flags) /* inode logging flags */
{
xfs_da_args_t dargs; /* args for dir/attr code */
int error; /* error return value */
xfs_mount_t *mp; /* mount structure pointer */
if (ip->i_df.if_bytes <= XFS_IFORK_DSIZE(ip))
return 0;
if (S_ISDIR(ip->i_d.di_mode)) {
mp = ip->i_mount;
memset(&dargs, 0, sizeof(dargs));
dargs.dp = ip;
dargs.firstblock = firstblock;
dargs.flist = flist;
dargs.total = mp->m_dirblkfsbs;
dargs.whichfork = XFS_DATA_FORK;
dargs.trans = tp;
error = xfs_dir2_sf_to_block(&dargs);
} else
error = xfs_bmap_local_to_extents(tp, ip, firstblock, 1, flags,
XFS_DATA_FORK);
return error;
}
/*
* Convert a delayed allocation to a real allocation.
*/
STATIC int /* error */
xfs_bmap_add_extent_delay_real(
struct xfs_bmalloca *bma)
{
struct xfs_bmbt_irec *new = &bma->got;
int diff; /* temp value */
xfs_bmbt_rec_host_t *ep; /* extent entry for idx */
int error; /* error return value */
int i; /* temp state */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_fileoff_t new_endoff; /* end offset of new entry */
xfs_bmbt_irec_t r[3]; /* neighbor extent entries */
/* left is 0, right is 1, prev is 2 */
int rval=0; /* return value (logging flags) */
int state = 0;/* state bits, accessed thru macros */
xfs_filblks_t da_new; /* new count del alloc blocks used */
xfs_filblks_t da_old; /* old count del alloc blocks used */
xfs_filblks_t temp=0; /* value for da_new calculations */
xfs_filblks_t temp2=0;/* value for da_new calculations */
int tmp_rval; /* partial logging flags */
ifp = XFS_IFORK_PTR(bma->ip, XFS_DATA_FORK);
ASSERT(bma->idx >= 0);
ASSERT(bma->idx <= ifp->if_bytes / sizeof(struct xfs_bmbt_rec));
ASSERT(!isnullstartblock(new->br_startblock));
ASSERT(!bma->cur ||
(bma->cur->bc_private.b.flags & XFS_BTCUR_BPRV_WASDEL));
XFS_STATS_INC(xs_add_exlist);
#define LEFT r[0]
#define RIGHT r[1]
#define PREV r[2]
/*
* Set up a bunch of variables to make the tests simpler.
*/
ep = xfs_iext_get_ext(ifp, bma->idx);
xfs_bmbt_get_all(ep, &PREV);
new_endoff = new->br_startoff + new->br_blockcount;
ASSERT(PREV.br_startoff <= new->br_startoff);
ASSERT(PREV.br_startoff + PREV.br_blockcount >= new_endoff);
da_old = startblockval(PREV.br_startblock);
da_new = 0;
/*
* Set flags determining what part of the previous delayed allocation
* extent is being replaced by a real allocation.
*/
if (PREV.br_startoff == new->br_startoff)
state |= BMAP_LEFT_FILLING;
if (PREV.br_startoff + PREV.br_blockcount == new_endoff)
state |= BMAP_RIGHT_FILLING;
/*
* Check and set flags if this segment has a left neighbor.
* Don't set contiguous if the combined extent would be too large.
*/
if (bma->idx > 0) {
state |= BMAP_LEFT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx - 1), &LEFT);
if (isnullstartblock(LEFT.br_startblock))
state |= BMAP_LEFT_DELAY;
}
if ((state & BMAP_LEFT_VALID) && !(state & BMAP_LEFT_DELAY) &&
LEFT.br_startoff + LEFT.br_blockcount == new->br_startoff &&
LEFT.br_startblock + LEFT.br_blockcount == new->br_startblock &&
LEFT.br_state == new->br_state &&
LEFT.br_blockcount + new->br_blockcount <= MAXEXTLEN)
state |= BMAP_LEFT_CONTIG;
/*
* Check and set flags if this segment has a right neighbor.
* Don't set contiguous if the combined extent would be too large.
* Also check for all-three-contiguous being too large.
*/
if (bma->idx < bma->ip->i_df.if_bytes / (uint)sizeof(xfs_bmbt_rec_t) - 1) {
state |= BMAP_RIGHT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx + 1), &RIGHT);
if (isnullstartblock(RIGHT.br_startblock))
state |= BMAP_RIGHT_DELAY;
}
if ((state & BMAP_RIGHT_VALID) && !(state & BMAP_RIGHT_DELAY) &&
new_endoff == RIGHT.br_startoff &&
new->br_startblock + new->br_blockcount == RIGHT.br_startblock &&
new->br_state == RIGHT.br_state &&
new->br_blockcount + RIGHT.br_blockcount <= MAXEXTLEN &&
((state & (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
BMAP_RIGHT_FILLING)) !=
(BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
BMAP_RIGHT_FILLING) ||
LEFT.br_blockcount + new->br_blockcount + RIGHT.br_blockcount
<= MAXEXTLEN))
state |= BMAP_RIGHT_CONTIG;
error = 0;
/*
* Switch out based on the FILLING and CONTIG state bits.
*/
switch (state & (BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG)) {
case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
/*
* Filling in all of a previously delayed allocation extent.
* The left and right neighbors are both contiguous with new.
*/
bma->idx--;
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx),
LEFT.br_blockcount + PREV.br_blockcount +
RIGHT.br_blockcount);
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_iext_remove(bma->ip, bma->idx + 1, 2, state);
bma->ip->i_d.di_nextents--;
if (bma->cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
error = xfs_bmbt_lookup_eq(bma->cur, RIGHT.br_startoff,
RIGHT.br_startblock,
RIGHT.br_blockcount, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_btree_delete(bma->cur, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_btree_decrement(bma->cur, 0, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, LEFT.br_startoff,
LEFT.br_startblock,
LEFT.br_blockcount +
PREV.br_blockcount +
RIGHT.br_blockcount, LEFT.br_state);
if (error)
goto done;
}
break;
case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
/*
* Filling in all of a previously delayed allocation extent.
* The left neighbor is contiguous, the right is not.
*/
bma->idx--;
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx),
LEFT.br_blockcount + PREV.br_blockcount);
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_iext_remove(bma->ip, bma->idx + 1, 1, state);
if (bma->cur == NULL)
rval = XFS_ILOG_DEXT;
else {
rval = 0;
error = xfs_bmbt_lookup_eq(bma->cur, LEFT.br_startoff,
LEFT.br_startblock, LEFT.br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, LEFT.br_startoff,
LEFT.br_startblock,
LEFT.br_blockcount +
PREV.br_blockcount, LEFT.br_state);
if (error)
goto done;
}
break;
case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
/*
* Filling in all of a previously delayed allocation extent.
* The right neighbor is contiguous, the left is not.
*/
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_startblock(ep, new->br_startblock);
xfs_bmbt_set_blockcount(ep,
PREV.br_blockcount + RIGHT.br_blockcount);
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_iext_remove(bma->ip, bma->idx + 1, 1, state);
if (bma->cur == NULL)
rval = XFS_ILOG_DEXT;
else {
rval = 0;
error = xfs_bmbt_lookup_eq(bma->cur, RIGHT.br_startoff,
RIGHT.br_startblock,
RIGHT.br_blockcount, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, PREV.br_startoff,
new->br_startblock,
PREV.br_blockcount +
RIGHT.br_blockcount, PREV.br_state);
if (error)
goto done;
}
break;
case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING:
/*
* Filling in all of a previously delayed allocation extent.
* Neither the left nor right neighbors are contiguous with
* the new one.
*/
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_startblock(ep, new->br_startblock);
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
bma->ip->i_d.di_nextents++;
if (bma->cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 0, done);
bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
error = xfs_btree_insert(bma->cur, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
break;
case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG:
/*
* Filling in the first part of a previous delayed allocation.
* The left neighbor is contiguous.
*/
trace_xfs_bmap_pre_update(bma->ip, bma->idx - 1, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx - 1),
LEFT.br_blockcount + new->br_blockcount);
xfs_bmbt_set_startoff(ep,
PREV.br_startoff + new->br_blockcount);
trace_xfs_bmap_post_update(bma->ip, bma->idx - 1, state, _THIS_IP_);
temp = PREV.br_blockcount - new->br_blockcount;
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep, temp);
if (bma->cur == NULL)
rval = XFS_ILOG_DEXT;
else {
rval = 0;
error = xfs_bmbt_lookup_eq(bma->cur, LEFT.br_startoff,
LEFT.br_startblock, LEFT.br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, LEFT.br_startoff,
LEFT.br_startblock,
LEFT.br_blockcount +
new->br_blockcount,
LEFT.br_state);
if (error)
goto done;
}
da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
startblockval(PREV.br_startblock));
xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
bma->idx--;
break;
case BMAP_LEFT_FILLING:
/*
* Filling in the first part of a previous delayed allocation.
* The left neighbor is not contiguous.
*/
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_startoff(ep, new_endoff);
temp = PREV.br_blockcount - new->br_blockcount;
xfs_bmbt_set_blockcount(ep, temp);
xfs_iext_insert(bma->ip, bma->idx, 1, new, state);
bma->ip->i_d.di_nextents++;
if (bma->cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 0, done);
bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
error = xfs_btree_insert(bma->cur, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
if (xfs_bmap_needs_btree(bma->ip, XFS_DATA_FORK)) {
error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
bma->firstblock, bma->flist,
&bma->cur, 1, &tmp_rval, XFS_DATA_FORK);
rval |= tmp_rval;
if (error)
goto done;
}
da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
startblockval(PREV.br_startblock) -
(bma->cur ? bma->cur->bc_private.b.allocated : 0));
ep = xfs_iext_get_ext(ifp, bma->idx + 1);
xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
trace_xfs_bmap_post_update(bma->ip, bma->idx + 1, state, _THIS_IP_);
break;
case BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
/*
* Filling in the last part of a previous delayed allocation.
* The right neighbor is contiguous with the new allocation.
*/
temp = PREV.br_blockcount - new->br_blockcount;
trace_xfs_bmap_pre_update(bma->ip, bma->idx + 1, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep, temp);
xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, bma->idx + 1),
new->br_startoff, new->br_startblock,
new->br_blockcount + RIGHT.br_blockcount,
RIGHT.br_state);
trace_xfs_bmap_post_update(bma->ip, bma->idx + 1, state, _THIS_IP_);
if (bma->cur == NULL)
rval = XFS_ILOG_DEXT;
else {
rval = 0;
error = xfs_bmbt_lookup_eq(bma->cur, RIGHT.br_startoff,
RIGHT.br_startblock,
RIGHT.br_blockcount, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, new->br_startoff,
new->br_startblock,
new->br_blockcount +
RIGHT.br_blockcount,
RIGHT.br_state);
if (error)
goto done;
}
da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
startblockval(PREV.br_startblock));
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
bma->idx++;
break;
case BMAP_RIGHT_FILLING:
/*
* Filling in the last part of a previous delayed allocation.
* The right neighbor is not contiguous.
*/
temp = PREV.br_blockcount - new->br_blockcount;
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep, temp);
xfs_iext_insert(bma->ip, bma->idx + 1, 1, new, state);
bma->ip->i_d.di_nextents++;
if (bma->cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 0, done);
bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
error = xfs_btree_insert(bma->cur, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
if (xfs_bmap_needs_btree(bma->ip, XFS_DATA_FORK)) {
error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
bma->firstblock, bma->flist, &bma->cur, 1,
&tmp_rval, XFS_DATA_FORK);
rval |= tmp_rval;
if (error)
goto done;
}
da_new = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(bma->ip, temp),
startblockval(PREV.br_startblock) -
(bma->cur ? bma->cur->bc_private.b.allocated : 0));
ep = xfs_iext_get_ext(ifp, bma->idx);
xfs_bmbt_set_startblock(ep, nullstartblock(da_new));
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
bma->idx++;
break;
case 0:
/*
* Filling in the middle part of a previous delayed allocation.
* Contiguity is impossible here.
* This case is avoided almost all the time.
*
* We start with a delayed allocation:
*
* +ddddddddddddddddddddddddddddddddddddddddddddddddddddddd+
* PREV @ idx
*
* and we are allocating:
* +rrrrrrrrrrrrrrrrr+
* new
*
* and we set it up for insertion as:
* +ddddddddddddddddddd+rrrrrrrrrrrrrrrrr+ddddddddddddddddd+
* new
* PREV @ idx LEFT RIGHT
* inserted at idx + 1
*/
temp = new->br_startoff - PREV.br_startoff;
temp2 = PREV.br_startoff + PREV.br_blockcount - new_endoff;
trace_xfs_bmap_pre_update(bma->ip, bma->idx, 0, _THIS_IP_);
xfs_bmbt_set_blockcount(ep, temp); /* truncate PREV */
LEFT = *new;
RIGHT.br_state = PREV.br_state;
RIGHT.br_startblock = nullstartblock(
(int)xfs_bmap_worst_indlen(bma->ip, temp2));
RIGHT.br_startoff = new_endoff;
RIGHT.br_blockcount = temp2;
/* insert LEFT (r[0]) and RIGHT (r[1]) at the same time */
xfs_iext_insert(bma->ip, bma->idx + 1, 2, &LEFT, state);
bma->ip->i_d.di_nextents++;
if (bma->cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
error = xfs_bmbt_lookup_eq(bma->cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 0, done);
bma->cur->bc_rec.b.br_state = XFS_EXT_NORM;
error = xfs_btree_insert(bma->cur, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
if (xfs_bmap_needs_btree(bma->ip, XFS_DATA_FORK)) {
error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
bma->firstblock, bma->flist, &bma->cur,
1, &tmp_rval, XFS_DATA_FORK);
rval |= tmp_rval;
if (error)
goto done;
}
temp = xfs_bmap_worst_indlen(bma->ip, temp);
temp2 = xfs_bmap_worst_indlen(bma->ip, temp2);
diff = (int)(temp + temp2 - startblockval(PREV.br_startblock) -
(bma->cur ? bma->cur->bc_private.b.allocated : 0));
if (diff > 0) {
error = xfs_icsb_modify_counters(bma->ip->i_mount,
XFS_SBS_FDBLOCKS,
-((int64_t)diff), 0);
ASSERT(!error);
if (error)
goto done;
}
ep = xfs_iext_get_ext(ifp, bma->idx);
xfs_bmbt_set_startblock(ep, nullstartblock((int)temp));
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
trace_xfs_bmap_pre_update(bma->ip, bma->idx + 2, state, _THIS_IP_);
xfs_bmbt_set_startblock(xfs_iext_get_ext(ifp, bma->idx + 2),
nullstartblock((int)temp2));
trace_xfs_bmap_post_update(bma->ip, bma->idx + 2, state, _THIS_IP_);
bma->idx++;
da_new = temp + temp2;
break;
case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
case BMAP_LEFT_FILLING | BMAP_RIGHT_CONTIG:
case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
case BMAP_LEFT_CONTIG:
case BMAP_RIGHT_CONTIG:
/*
* These cases are all impossible.
*/
ASSERT(0);
}
/* convert to a btree if necessary */
if (xfs_bmap_needs_btree(bma->ip, XFS_DATA_FORK)) {
int tmp_logflags; /* partial log flag return val */
ASSERT(bma->cur == NULL);
error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
bma->firstblock, bma->flist, &bma->cur,
da_old > 0, &tmp_logflags, XFS_DATA_FORK);
bma->logflags |= tmp_logflags;
if (error)
goto done;
}
/* adjust for changes in reserved delayed indirect blocks */
if (da_old || da_new) {
temp = da_new;
if (bma->cur)
temp += bma->cur->bc_private.b.allocated;
ASSERT(temp <= da_old);
if (temp < da_old)
xfs_icsb_modify_counters(bma->ip->i_mount,
XFS_SBS_FDBLOCKS,
(int64_t)(da_old - temp), 0);
}
/* clear out the allocated field, done with it now in any case. */
if (bma->cur)
bma->cur->bc_private.b.allocated = 0;
xfs_bmap_check_leaf_extents(bma->cur, bma->ip, XFS_DATA_FORK);
done:
bma->logflags |= rval;
return error;
#undef LEFT
#undef RIGHT
#undef PREV
}
/*
* Convert an unwritten allocation to a real allocation or vice versa.
*/
STATIC int /* error */
xfs_bmap_add_extent_unwritten_real(
struct xfs_trans *tp,
xfs_inode_t *ip, /* incore inode pointer */
xfs_extnum_t *idx, /* extent number to update/insert */
xfs_btree_cur_t **curp, /* if *curp is null, not a btree */
xfs_bmbt_irec_t *new, /* new data to add to file extents */
xfs_fsblock_t *first, /* pointer to firstblock variable */
xfs_bmap_free_t *flist, /* list of extents to be freed */
int *logflagsp) /* inode logging flags */
{
xfs_btree_cur_t *cur; /* btree cursor */
xfs_bmbt_rec_host_t *ep; /* extent entry for idx */
int error; /* error return value */
int i; /* temp state */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_fileoff_t new_endoff; /* end offset of new entry */
xfs_exntst_t newext; /* new extent state */
xfs_exntst_t oldext; /* old extent state */
xfs_bmbt_irec_t r[3]; /* neighbor extent entries */
/* left is 0, right is 1, prev is 2 */
int rval=0; /* return value (logging flags) */
int state = 0;/* state bits, accessed thru macros */
*logflagsp = 0;
cur = *curp;
ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
ASSERT(*idx >= 0);
ASSERT(*idx <= ifp->if_bytes / sizeof(struct xfs_bmbt_rec));
ASSERT(!isnullstartblock(new->br_startblock));
XFS_STATS_INC(xs_add_exlist);
#define LEFT r[0]
#define RIGHT r[1]
#define PREV r[2]
/*
* Set up a bunch of variables to make the tests simpler.
*/
error = 0;
ep = xfs_iext_get_ext(ifp, *idx);
xfs_bmbt_get_all(ep, &PREV);
newext = new->br_state;
oldext = (newext == XFS_EXT_UNWRITTEN) ?
XFS_EXT_NORM : XFS_EXT_UNWRITTEN;
ASSERT(PREV.br_state == oldext);
new_endoff = new->br_startoff + new->br_blockcount;
ASSERT(PREV.br_startoff <= new->br_startoff);
ASSERT(PREV.br_startoff + PREV.br_blockcount >= new_endoff);
/*
* Set flags determining what part of the previous oldext allocation
* extent is being replaced by a newext allocation.
*/
if (PREV.br_startoff == new->br_startoff)
state |= BMAP_LEFT_FILLING;
if (PREV.br_startoff + PREV.br_blockcount == new_endoff)
state |= BMAP_RIGHT_FILLING;
/*
* Check and set flags if this segment has a left neighbor.
* Don't set contiguous if the combined extent would be too large.
*/
if (*idx > 0) {
state |= BMAP_LEFT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx - 1), &LEFT);
if (isnullstartblock(LEFT.br_startblock))
state |= BMAP_LEFT_DELAY;
}
if ((state & BMAP_LEFT_VALID) && !(state & BMAP_LEFT_DELAY) &&
LEFT.br_startoff + LEFT.br_blockcount == new->br_startoff &&
LEFT.br_startblock + LEFT.br_blockcount == new->br_startblock &&
LEFT.br_state == newext &&
LEFT.br_blockcount + new->br_blockcount <= MAXEXTLEN)
state |= BMAP_LEFT_CONTIG;
/*
* Check and set flags if this segment has a right neighbor.
* Don't set contiguous if the combined extent would be too large.
* Also check for all-three-contiguous being too large.
*/
if (*idx < ip->i_df.if_bytes / (uint)sizeof(xfs_bmbt_rec_t) - 1) {
state |= BMAP_RIGHT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx + 1), &RIGHT);
if (isnullstartblock(RIGHT.br_startblock))
state |= BMAP_RIGHT_DELAY;
}
if ((state & BMAP_RIGHT_VALID) && !(state & BMAP_RIGHT_DELAY) &&
new_endoff == RIGHT.br_startoff &&
new->br_startblock + new->br_blockcount == RIGHT.br_startblock &&
newext == RIGHT.br_state &&
new->br_blockcount + RIGHT.br_blockcount <= MAXEXTLEN &&
((state & (BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
BMAP_RIGHT_FILLING)) !=
(BMAP_LEFT_CONTIG | BMAP_LEFT_FILLING |
BMAP_RIGHT_FILLING) ||
LEFT.br_blockcount + new->br_blockcount + RIGHT.br_blockcount
<= MAXEXTLEN))
state |= BMAP_RIGHT_CONTIG;
/*
* Switch out based on the FILLING and CONTIG state bits.
*/
switch (state & (BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG)) {
case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG |
BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
/*
* Setting all of a previous oldext extent to newext.
* The left and right neighbors are both contiguous with new.
*/
--*idx;
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx),
LEFT.br_blockcount + PREV.br_blockcount +
RIGHT.br_blockcount);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
xfs_iext_remove(ip, *idx + 1, 2, state);
ip->i_d.di_nextents -= 2;
if (cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
if ((error = xfs_bmbt_lookup_eq(cur, RIGHT.br_startoff,
RIGHT.br_startblock,
RIGHT.br_blockcount, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_delete(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_decrement(cur, 0, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_delete(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_decrement(cur, 0, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur, LEFT.br_startoff,
LEFT.br_startblock,
LEFT.br_blockcount + PREV.br_blockcount +
RIGHT.br_blockcount, LEFT.br_state)))
goto done;
}
break;
case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
/*
* Setting all of a previous oldext extent to newext.
* The left neighbor is contiguous, the right is not.
*/
--*idx;
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx),
LEFT.br_blockcount + PREV.br_blockcount);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
xfs_iext_remove(ip, *idx + 1, 1, state);
ip->i_d.di_nextents--;
if (cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
PREV.br_startblock, PREV.br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_delete(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_decrement(cur, 0, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur, LEFT.br_startoff,
LEFT.br_startblock,
LEFT.br_blockcount + PREV.br_blockcount,
LEFT.br_state)))
goto done;
}
break;
case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
/*
* Setting all of a previous oldext extent to newext.
* The right neighbor is contiguous, the left is not.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep,
PREV.br_blockcount + RIGHT.br_blockcount);
xfs_bmbt_set_state(ep, newext);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
xfs_iext_remove(ip, *idx + 1, 1, state);
ip->i_d.di_nextents--;
if (cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
if ((error = xfs_bmbt_lookup_eq(cur, RIGHT.br_startoff,
RIGHT.br_startblock,
RIGHT.br_blockcount, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_delete(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_btree_decrement(cur, 0, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur, new->br_startoff,
new->br_startblock,
new->br_blockcount + RIGHT.br_blockcount,
newext)))
goto done;
}
break;
case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING:
/*
* Setting all of a previous oldext extent to newext.
* Neither the left nor right neighbors are contiguous with
* the new one.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_state(ep, newext);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
if (cur == NULL)
rval = XFS_ILOG_DEXT;
else {
rval = 0;
if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
newext)))
goto done;
}
break;
case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG:
/*
* Setting the first part of a previous oldext extent to newext.
* The left neighbor is contiguous.
*/
trace_xfs_bmap_pre_update(ip, *idx - 1, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx - 1),
LEFT.br_blockcount + new->br_blockcount);
xfs_bmbt_set_startoff(ep,
PREV.br_startoff + new->br_blockcount);
trace_xfs_bmap_post_update(ip, *idx - 1, state, _THIS_IP_);
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_startblock(ep,
new->br_startblock + new->br_blockcount);
xfs_bmbt_set_blockcount(ep,
PREV.br_blockcount - new->br_blockcount);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
--*idx;
if (cur == NULL)
rval = XFS_ILOG_DEXT;
else {
rval = 0;
if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
PREV.br_startblock, PREV.br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur,
PREV.br_startoff + new->br_blockcount,
PREV.br_startblock + new->br_blockcount,
PREV.br_blockcount - new->br_blockcount,
oldext)))
goto done;
if ((error = xfs_btree_decrement(cur, 0, &i)))
goto done;
error = xfs_bmbt_update(cur, LEFT.br_startoff,
LEFT.br_startblock,
LEFT.br_blockcount + new->br_blockcount,
LEFT.br_state);
if (error)
goto done;
}
break;
case BMAP_LEFT_FILLING:
/*
* Setting the first part of a previous oldext extent to newext.
* The left neighbor is not contiguous.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
ASSERT(ep && xfs_bmbt_get_state(ep) == oldext);
xfs_bmbt_set_startoff(ep, new_endoff);
xfs_bmbt_set_blockcount(ep,
PREV.br_blockcount - new->br_blockcount);
xfs_bmbt_set_startblock(ep,
new->br_startblock + new->br_blockcount);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
xfs_iext_insert(ip, *idx, 1, new, state);
ip->i_d.di_nextents++;
if (cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
PREV.br_startblock, PREV.br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur,
PREV.br_startoff + new->br_blockcount,
PREV.br_startblock + new->br_blockcount,
PREV.br_blockcount - new->br_blockcount,
oldext)))
goto done;
cur->bc_rec.b = *new;
if ((error = xfs_btree_insert(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
break;
case BMAP_RIGHT_FILLING | BMAP_RIGHT_CONTIG:
/*
* Setting the last part of a previous oldext extent to newext.
* The right neighbor is contiguous with the new allocation.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep,
PREV.br_blockcount - new->br_blockcount);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
++*idx;
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, *idx),
new->br_startoff, new->br_startblock,
new->br_blockcount + RIGHT.br_blockcount, newext);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
if (cur == NULL)
rval = XFS_ILOG_DEXT;
else {
rval = 0;
if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
PREV.br_startblock,
PREV.br_blockcount, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur, PREV.br_startoff,
PREV.br_startblock,
PREV.br_blockcount - new->br_blockcount,
oldext)))
goto done;
if ((error = xfs_btree_increment(cur, 0, &i)))
goto done;
if ((error = xfs_bmbt_update(cur, new->br_startoff,
new->br_startblock,
new->br_blockcount + RIGHT.br_blockcount,
newext)))
goto done;
}
break;
case BMAP_RIGHT_FILLING:
/*
* Setting the last part of a previous oldext extent to newext.
* The right neighbor is not contiguous.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep,
PREV.br_blockcount - new->br_blockcount);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
++*idx;
xfs_iext_insert(ip, *idx, 1, new, state);
ip->i_d.di_nextents++;
if (cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
PREV.br_startblock, PREV.br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
if ((error = xfs_bmbt_update(cur, PREV.br_startoff,
PREV.br_startblock,
PREV.br_blockcount - new->br_blockcount,
oldext)))
goto done;
if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 0, done);
cur->bc_rec.b.br_state = XFS_EXT_NORM;
if ((error = xfs_btree_insert(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
break;
case 0:
/*
* Setting the middle part of a previous oldext extent to
* newext. Contiguity is impossible here.
* One extent becomes three extents.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep,
new->br_startoff - PREV.br_startoff);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
r[0] = *new;
r[1].br_startoff = new_endoff;
r[1].br_blockcount =
PREV.br_startoff + PREV.br_blockcount - new_endoff;
r[1].br_startblock = new->br_startblock + new->br_blockcount;
r[1].br_state = oldext;
++*idx;
xfs_iext_insert(ip, *idx, 2, &r[0], state);
ip->i_d.di_nextents += 2;
if (cur == NULL)
rval = XFS_ILOG_CORE | XFS_ILOG_DEXT;
else {
rval = XFS_ILOG_CORE;
if ((error = xfs_bmbt_lookup_eq(cur, PREV.br_startoff,
PREV.br_startblock, PREV.br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
/* new right extent - oldext */
if ((error = xfs_bmbt_update(cur, r[1].br_startoff,
r[1].br_startblock, r[1].br_blockcount,
r[1].br_state)))
goto done;
/* new left extent - oldext */
cur->bc_rec.b = PREV;
cur->bc_rec.b.br_blockcount =
new->br_startoff - PREV.br_startoff;
if ((error = xfs_btree_insert(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
/*
* Reset the cursor to the position of the new extent
* we are about to insert as we can't trust it after
* the previous insert.
*/
if ((error = xfs_bmbt_lookup_eq(cur, new->br_startoff,
new->br_startblock, new->br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 0, done);
/* new middle extent - newext */
cur->bc_rec.b.br_state = new->br_state;
if ((error = xfs_btree_insert(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
break;
case BMAP_LEFT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
case BMAP_LEFT_FILLING | BMAP_RIGHT_CONTIG:
case BMAP_RIGHT_FILLING | BMAP_LEFT_CONTIG:
case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
case BMAP_LEFT_CONTIG:
case BMAP_RIGHT_CONTIG:
/*
* These cases are all impossible.
*/
ASSERT(0);
}
/* convert to a btree if necessary */
if (xfs_bmap_needs_btree(ip, XFS_DATA_FORK)) {
int tmp_logflags; /* partial log flag return val */
ASSERT(cur == NULL);
error = xfs_bmap_extents_to_btree(tp, ip, first, flist, &cur,
0, &tmp_logflags, XFS_DATA_FORK);
*logflagsp |= tmp_logflags;
if (error)
goto done;
}
/* clear out the allocated field, done with it now in any case. */
if (cur) {
cur->bc_private.b.allocated = 0;
*curp = cur;
}
xfs_bmap_check_leaf_extents(*curp, ip, XFS_DATA_FORK);
done:
*logflagsp |= rval;
return error;
#undef LEFT
#undef RIGHT
#undef PREV
}
/*
* Convert a hole to a delayed allocation.
*/
STATIC void
xfs_bmap_add_extent_hole_delay(
xfs_inode_t *ip, /* incore inode pointer */
xfs_extnum_t *idx, /* extent number to update/insert */
xfs_bmbt_irec_t *new) /* new data to add to file extents */
{
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_bmbt_irec_t left; /* left neighbor extent entry */
xfs_filblks_t newlen=0; /* new indirect size */
xfs_filblks_t oldlen=0; /* old indirect size */
xfs_bmbt_irec_t right; /* right neighbor extent entry */
int state; /* state bits, accessed thru macros */
xfs_filblks_t temp=0; /* temp for indirect calculations */
ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
state = 0;
ASSERT(isnullstartblock(new->br_startblock));
/*
* Check and set flags if this segment has a left neighbor
*/
if (*idx > 0) {
state |= BMAP_LEFT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx - 1), &left);
if (isnullstartblock(left.br_startblock))
state |= BMAP_LEFT_DELAY;
}
/*
* Check and set flags if the current (right) segment exists.
* If it doesn't exist, we're converting the hole at end-of-file.
*/
if (*idx < ip->i_df.if_bytes / (uint)sizeof(xfs_bmbt_rec_t)) {
state |= BMAP_RIGHT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *idx), &right);
if (isnullstartblock(right.br_startblock))
state |= BMAP_RIGHT_DELAY;
}
/*
* Set contiguity flags on the left and right neighbors.
* Don't let extents get too large, even if the pieces are contiguous.
*/
if ((state & BMAP_LEFT_VALID) && (state & BMAP_LEFT_DELAY) &&
left.br_startoff + left.br_blockcount == new->br_startoff &&
left.br_blockcount + new->br_blockcount <= MAXEXTLEN)
state |= BMAP_LEFT_CONTIG;
if ((state & BMAP_RIGHT_VALID) && (state & BMAP_RIGHT_DELAY) &&
new->br_startoff + new->br_blockcount == right.br_startoff &&
new->br_blockcount + right.br_blockcount <= MAXEXTLEN &&
(!(state & BMAP_LEFT_CONTIG) ||
(left.br_blockcount + new->br_blockcount +
right.br_blockcount <= MAXEXTLEN)))
state |= BMAP_RIGHT_CONTIG;
/*
* Switch out based on the contiguity flags.
*/
switch (state & (BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG)) {
case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
/*
* New allocation is contiguous with delayed allocations
* on the left and on the right.
* Merge all three into a single extent record.
*/
--*idx;
temp = left.br_blockcount + new->br_blockcount +
right.br_blockcount;
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx), temp);
oldlen = startblockval(left.br_startblock) +
startblockval(new->br_startblock) +
startblockval(right.br_startblock);
newlen = xfs_bmap_worst_indlen(ip, temp);
xfs_bmbt_set_startblock(xfs_iext_get_ext(ifp, *idx),
nullstartblock((int)newlen));
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
xfs_iext_remove(ip, *idx + 1, 1, state);
break;
case BMAP_LEFT_CONTIG:
/*
* New allocation is contiguous with a delayed allocation
* on the left.
* Merge the new allocation with the left neighbor.
*/
--*idx;
temp = left.br_blockcount + new->br_blockcount;
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, *idx), temp);
oldlen = startblockval(left.br_startblock) +
startblockval(new->br_startblock);
newlen = xfs_bmap_worst_indlen(ip, temp);
xfs_bmbt_set_startblock(xfs_iext_get_ext(ifp, *idx),
nullstartblock((int)newlen));
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
break;
case BMAP_RIGHT_CONTIG:
/*
* New allocation is contiguous with a delayed allocation
* on the right.
* Merge the new allocation with the right neighbor.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
temp = new->br_blockcount + right.br_blockcount;
oldlen = startblockval(new->br_startblock) +
startblockval(right.br_startblock);
newlen = xfs_bmap_worst_indlen(ip, temp);
xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, *idx),
new->br_startoff,
nullstartblock((int)newlen), temp, right.br_state);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
break;
case 0:
/*
* New allocation is not contiguous with another
* delayed allocation.
* Insert a new entry.
*/
oldlen = newlen = 0;
xfs_iext_insert(ip, *idx, 1, new, state);
break;
}
if (oldlen != newlen) {
ASSERT(oldlen > newlen);
xfs_icsb_modify_counters(ip->i_mount, XFS_SBS_FDBLOCKS,
(int64_t)(oldlen - newlen), 0);
/*
* Nothing to do for disk quota accounting here.
*/
}
}
/*
* Convert a hole to a real allocation.
*/
STATIC int /* error */
xfs_bmap_add_extent_hole_real(
struct xfs_bmalloca *bma,
int whichfork)
{
struct xfs_bmbt_irec *new = &bma->got;
int error; /* error return value */
int i; /* temp state */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_bmbt_irec_t left; /* left neighbor extent entry */
xfs_bmbt_irec_t right; /* right neighbor extent entry */
int rval=0; /* return value (logging flags) */
int state; /* state bits, accessed thru macros */
ifp = XFS_IFORK_PTR(bma->ip, whichfork);
ASSERT(bma->idx >= 0);
ASSERT(bma->idx <= ifp->if_bytes / sizeof(struct xfs_bmbt_rec));
ASSERT(!isnullstartblock(new->br_startblock));
ASSERT(!bma->cur ||
!(bma->cur->bc_private.b.flags & XFS_BTCUR_BPRV_WASDEL));
XFS_STATS_INC(xs_add_exlist);
state = 0;
if (whichfork == XFS_ATTR_FORK)
state |= BMAP_ATTRFORK;
/*
* Check and set flags if this segment has a left neighbor.
*/
if (bma->idx > 0) {
state |= BMAP_LEFT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx - 1), &left);
if (isnullstartblock(left.br_startblock))
state |= BMAP_LEFT_DELAY;
}
/*
* Check and set flags if this segment has a current value.
* Not true if we're inserting into the "hole" at eof.
*/
if (bma->idx < ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t)) {
state |= BMAP_RIGHT_VALID;
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx), &right);
if (isnullstartblock(right.br_startblock))
state |= BMAP_RIGHT_DELAY;
}
/*
* We're inserting a real allocation between "left" and "right".
* Set the contiguity flags. Don't let extents get too large.
*/
if ((state & BMAP_LEFT_VALID) && !(state & BMAP_LEFT_DELAY) &&
left.br_startoff + left.br_blockcount == new->br_startoff &&
left.br_startblock + left.br_blockcount == new->br_startblock &&
left.br_state == new->br_state &&
left.br_blockcount + new->br_blockcount <= MAXEXTLEN)
state |= BMAP_LEFT_CONTIG;
if ((state & BMAP_RIGHT_VALID) && !(state & BMAP_RIGHT_DELAY) &&
new->br_startoff + new->br_blockcount == right.br_startoff &&
new->br_startblock + new->br_blockcount == right.br_startblock &&
new->br_state == right.br_state &&
new->br_blockcount + right.br_blockcount <= MAXEXTLEN &&
(!(state & BMAP_LEFT_CONTIG) ||
left.br_blockcount + new->br_blockcount +
right.br_blockcount <= MAXEXTLEN))
state |= BMAP_RIGHT_CONTIG;
error = 0;
/*
* Select which case we're in here, and implement it.
*/
switch (state & (BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG)) {
case BMAP_LEFT_CONTIG | BMAP_RIGHT_CONTIG:
/*
* New allocation is contiguous with real allocations on the
* left and on the right.
* Merge all three into a single extent record.
*/
--bma->idx;
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx),
left.br_blockcount + new->br_blockcount +
right.br_blockcount);
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_iext_remove(bma->ip, bma->idx + 1, 1, state);
XFS_IFORK_NEXT_SET(bma->ip, whichfork,
XFS_IFORK_NEXTENTS(bma->ip, whichfork) - 1);
if (bma->cur == NULL) {
rval = XFS_ILOG_CORE | xfs_ilog_fext(whichfork);
} else {
rval = XFS_ILOG_CORE;
error = xfs_bmbt_lookup_eq(bma->cur, right.br_startoff,
right.br_startblock, right.br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_btree_delete(bma->cur, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_btree_decrement(bma->cur, 0, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, left.br_startoff,
left.br_startblock,
left.br_blockcount +
new->br_blockcount +
right.br_blockcount,
left.br_state);
if (error)
goto done;
}
break;
case BMAP_LEFT_CONTIG:
/*
* New allocation is contiguous with a real allocation
* on the left.
* Merge the new allocation with the left neighbor.
*/
--bma->idx;
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(xfs_iext_get_ext(ifp, bma->idx),
left.br_blockcount + new->br_blockcount);
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
if (bma->cur == NULL) {
rval = xfs_ilog_fext(whichfork);
} else {
rval = 0;
error = xfs_bmbt_lookup_eq(bma->cur, left.br_startoff,
left.br_startblock, left.br_blockcount,
&i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, left.br_startoff,
left.br_startblock,
left.br_blockcount +
new->br_blockcount,
left.br_state);
if (error)
goto done;
}
break;
case BMAP_RIGHT_CONTIG:
/*
* New allocation is contiguous with a real allocation
* on the right.
* Merge the new allocation with the right neighbor.
*/
trace_xfs_bmap_pre_update(bma->ip, bma->idx, state, _THIS_IP_);
xfs_bmbt_set_allf(xfs_iext_get_ext(ifp, bma->idx),
new->br_startoff, new->br_startblock,
new->br_blockcount + right.br_blockcount,
right.br_state);
trace_xfs_bmap_post_update(bma->ip, bma->idx, state, _THIS_IP_);
if (bma->cur == NULL) {
rval = xfs_ilog_fext(whichfork);
} else {
rval = 0;
error = xfs_bmbt_lookup_eq(bma->cur,
right.br_startoff,
right.br_startblock,
right.br_blockcount, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
error = xfs_bmbt_update(bma->cur, new->br_startoff,
new->br_startblock,
new->br_blockcount +
right.br_blockcount,
right.br_state);
if (error)
goto done;
}
break;
case 0:
/*
* New allocation is not contiguous with another
* real allocation.
* Insert a new entry.
*/
xfs_iext_insert(bma->ip, bma->idx, 1, new, state);
XFS_IFORK_NEXT_SET(bma->ip, whichfork,
XFS_IFORK_NEXTENTS(bma->ip, whichfork) + 1);
if (bma->cur == NULL) {
rval = XFS_ILOG_CORE | xfs_ilog_fext(whichfork);
} else {
rval = XFS_ILOG_CORE;
error = xfs_bmbt_lookup_eq(bma->cur,
new->br_startoff,
new->br_startblock,
new->br_blockcount, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 0, done);
bma->cur->bc_rec.b.br_state = new->br_state;
error = xfs_btree_insert(bma->cur, &i);
if (error)
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
break;
}
/* convert to a btree if necessary */
if (xfs_bmap_needs_btree(bma->ip, whichfork)) {
int tmp_logflags; /* partial log flag return val */
ASSERT(bma->cur == NULL);
error = xfs_bmap_extents_to_btree(bma->tp, bma->ip,
bma->firstblock, bma->flist, &bma->cur,
0, &tmp_logflags, whichfork);
bma->logflags |= tmp_logflags;
if (error)
goto done;
}
/* clear out the allocated field, done with it now in any case. */
if (bma->cur)
bma->cur->bc_private.b.allocated = 0;
xfs_bmap_check_leaf_extents(bma->cur, bma->ip, whichfork);
done:
bma->logflags |= rval;
return error;
}
/*
* Adjust the size of the new extent based on di_extsize and rt extsize.
*/
STATIC int
xfs_bmap_extsize_align(
xfs_mount_t *mp,
xfs_bmbt_irec_t *gotp, /* next extent pointer */
xfs_bmbt_irec_t *prevp, /* previous extent pointer */
xfs_extlen_t extsz, /* align to this extent size */
int rt, /* is this a realtime inode? */
int eof, /* is extent at end-of-file? */
int delay, /* creating delalloc extent? */
int convert, /* overwriting unwritten extent? */
xfs_fileoff_t *offp, /* in/out: aligned offset */
xfs_extlen_t *lenp) /* in/out: aligned length */
{
xfs_fileoff_t orig_off; /* original offset */
xfs_extlen_t orig_alen; /* original length */
xfs_fileoff_t orig_end; /* original off+len */
xfs_fileoff_t nexto; /* next file offset */
xfs_fileoff_t prevo; /* previous file offset */
xfs_fileoff_t align_off; /* temp for offset */
xfs_extlen_t align_alen; /* temp for length */
xfs_extlen_t temp; /* temp for calculations */
if (convert)
return 0;
orig_off = align_off = *offp;
orig_alen = align_alen = *lenp;
orig_end = orig_off + orig_alen;
/*
* If this request overlaps an existing extent, then don't
* attempt to perform any additional alignment.
*/
if (!delay && !eof &&
(orig_off >= gotp->br_startoff) &&
(orig_end <= gotp->br_startoff + gotp->br_blockcount)) {
return 0;
}
/*
* If the file offset is unaligned vs. the extent size
* we need to align it. This will be possible unless
* the file was previously written with a kernel that didn't
* perform this alignment, or if a truncate shot us in the
* foot.
*/
temp = do_mod(orig_off, extsz);
if (temp) {
align_alen += temp;
align_off -= temp;
}
/*
* Same adjustment for the end of the requested area.
*/
if ((temp = (align_alen % extsz))) {
align_alen += extsz - temp;
}
/*
* If the previous block overlaps with this proposed allocation
* then move the start forward without adjusting the length.
*/
if (prevp->br_startoff != NULLFILEOFF) {
if (prevp->br_startblock == HOLESTARTBLOCK)
prevo = prevp->br_startoff;
else
prevo = prevp->br_startoff + prevp->br_blockcount;
} else
prevo = 0;
if (align_off != orig_off && align_off < prevo)
align_off = prevo;
/*
* If the next block overlaps with this proposed allocation
* then move the start back without adjusting the length,
* but not before offset 0.
* This may of course make the start overlap previous block,
* and if we hit the offset 0 limit then the next block
* can still overlap too.
*/
if (!eof && gotp->br_startoff != NULLFILEOFF) {
if ((delay && gotp->br_startblock == HOLESTARTBLOCK) ||
(!delay && gotp->br_startblock == DELAYSTARTBLOCK))
nexto = gotp->br_startoff + gotp->br_blockcount;
else
nexto = gotp->br_startoff;
} else
nexto = NULLFILEOFF;
if (!eof &&
align_off + align_alen != orig_end &&
align_off + align_alen > nexto)
align_off = nexto > align_alen ? nexto - align_alen : 0;
/*
* If we're now overlapping the next or previous extent that
* means we can't fit an extsz piece in this hole. Just move
* the start forward to the first valid spot and set
* the length so we hit the end.
*/
if (align_off != orig_off && align_off < prevo)
align_off = prevo;
if (align_off + align_alen != orig_end &&
align_off + align_alen > nexto &&
nexto != NULLFILEOFF) {
ASSERT(nexto > prevo);
align_alen = nexto - align_off;
}
/*
* If realtime, and the result isn't a multiple of the realtime
* extent size we need to remove blocks until it is.
*/
if (rt && (temp = (align_alen % mp->m_sb.sb_rextsize))) {
/*
* We're not covering the original request, or
* we won't be able to once we fix the length.
*/
if (orig_off < align_off ||
orig_end > align_off + align_alen ||
align_alen - temp < orig_alen)
return XFS_ERROR(EINVAL);
/*
* Try to fix it by moving the start up.
*/
if (align_off + temp <= orig_off) {
align_alen -= temp;
align_off += temp;
}
/*
* Try to fix it by moving the end in.
*/
else if (align_off + align_alen - temp >= orig_end)
align_alen -= temp;
/*
* Set the start to the minimum then trim the length.
*/
else {
align_alen -= orig_off - align_off;
align_off = orig_off;
align_alen -= align_alen % mp->m_sb.sb_rextsize;
}
/*
* Result doesn't cover the request, fail it.
*/
if (orig_off < align_off || orig_end > align_off + align_alen)
return XFS_ERROR(EINVAL);
} else {
ASSERT(orig_off >= align_off);
ASSERT(orig_end <= align_off + align_alen);
}
#ifdef DEBUG
if (!eof && gotp->br_startoff != NULLFILEOFF)
ASSERT(align_off + align_alen <= gotp->br_startoff);
if (prevp->br_startoff != NULLFILEOFF)
ASSERT(align_off >= prevp->br_startoff + prevp->br_blockcount);
#endif
*lenp = align_alen;
*offp = align_off;
return 0;
}
#define XFS_ALLOC_GAP_UNITS 4
STATIC void
xfs_bmap_adjacent(
xfs_bmalloca_t *ap) /* bmap alloc argument struct */
{
xfs_fsblock_t adjust; /* adjustment to block numbers */
xfs_agnumber_t fb_agno; /* ag number of ap->firstblock */
xfs_mount_t *mp; /* mount point structure */
int nullfb; /* true if ap->firstblock isn't set */
int rt; /* true if inode is realtime */
#define ISVALID(x,y) \
(rt ? \
(x) < mp->m_sb.sb_rblocks : \
XFS_FSB_TO_AGNO(mp, x) == XFS_FSB_TO_AGNO(mp, y) && \
XFS_FSB_TO_AGNO(mp, x) < mp->m_sb.sb_agcount && \
XFS_FSB_TO_AGBNO(mp, x) < mp->m_sb.sb_agblocks)
mp = ap->ip->i_mount;
nullfb = *ap->firstblock == NULLFSBLOCK;
rt = XFS_IS_REALTIME_INODE(ap->ip) && ap->userdata;
fb_agno = nullfb ? NULLAGNUMBER : XFS_FSB_TO_AGNO(mp, *ap->firstblock);
/*
* If allocating at eof, and there's a previous real block,
* try to use its last block as our starting point.
*/
if (ap->eof && ap->prev.br_startoff != NULLFILEOFF &&
!isnullstartblock(ap->prev.br_startblock) &&
ISVALID(ap->prev.br_startblock + ap->prev.br_blockcount,
ap->prev.br_startblock)) {
ap->blkno = ap->prev.br_startblock + ap->prev.br_blockcount;
/*
* Adjust for the gap between prevp and us.
*/
adjust = ap->offset -
(ap->prev.br_startoff + ap->prev.br_blockcount);
if (adjust &&
ISVALID(ap->blkno + adjust, ap->prev.br_startblock))
ap->blkno += adjust;
}
/*
* If not at eof, then compare the two neighbor blocks.
* Figure out whether either one gives us a good starting point,
* and pick the better one.
*/
else if (!ap->eof) {
xfs_fsblock_t gotbno; /* right side block number */
xfs_fsblock_t gotdiff=0; /* right side difference */
xfs_fsblock_t prevbno; /* left side block number */
xfs_fsblock_t prevdiff=0; /* left side difference */
/*
* If there's a previous (left) block, select a requested
* start block based on it.
*/
if (ap->prev.br_startoff != NULLFILEOFF &&
!isnullstartblock(ap->prev.br_startblock) &&
(prevbno = ap->prev.br_startblock +
ap->prev.br_blockcount) &&
ISVALID(prevbno, ap->prev.br_startblock)) {
/*
* Calculate gap to end of previous block.
*/
adjust = prevdiff = ap->offset -
(ap->prev.br_startoff +
ap->prev.br_blockcount);
/*
* Figure the startblock based on the previous block's
* end and the gap size.
* Heuristic!
* If the gap is large relative to the piece we're
* allocating, or using it gives us an invalid block
* number, then just use the end of the previous block.
*/
if (prevdiff <= XFS_ALLOC_GAP_UNITS * ap->length &&
ISVALID(prevbno + prevdiff,
ap->prev.br_startblock))
prevbno += adjust;
else
prevdiff += adjust;
/*
* If the firstblock forbids it, can't use it,
* must use default.
*/
if (!rt && !nullfb &&
XFS_FSB_TO_AGNO(mp, prevbno) != fb_agno)
prevbno = NULLFSBLOCK;
}
/*
* No previous block or can't follow it, just default.
*/
else
prevbno = NULLFSBLOCK;
/*
* If there's a following (right) block, select a requested
* start block based on it.
*/
if (!isnullstartblock(ap->got.br_startblock)) {
/*
* Calculate gap to start of next block.
*/
adjust = gotdiff = ap->got.br_startoff - ap->offset;
/*
* Figure the startblock based on the next block's
* start and the gap size.
*/
gotbno = ap->got.br_startblock;
/*
* Heuristic!
* If the gap is large relative to the piece we're
* allocating, or using it gives us an invalid block
* number, then just use the start of the next block
* offset by our length.
*/
if (gotdiff <= XFS_ALLOC_GAP_UNITS * ap->length &&
ISVALID(gotbno - gotdiff, gotbno))
gotbno -= adjust;
else if (ISVALID(gotbno - ap->length, gotbno)) {
gotbno -= ap->length;
gotdiff += adjust - ap->length;
} else
gotdiff += adjust;
/*
* If the firstblock forbids it, can't use it,
* must use default.
*/
if (!rt && !nullfb &&
XFS_FSB_TO_AGNO(mp, gotbno) != fb_agno)
gotbno = NULLFSBLOCK;
}
/*
* No next block, just default.
*/
else
gotbno = NULLFSBLOCK;
/*
* If both valid, pick the better one, else the only good
* one, else ap->blkno is already set (to 0 or the inode block).
*/
if (prevbno != NULLFSBLOCK && gotbno != NULLFSBLOCK)
ap->blkno = prevdiff <= gotdiff ? prevbno : gotbno;
else if (prevbno != NULLFSBLOCK)
ap->blkno = prevbno;
else if (gotbno != NULLFSBLOCK)
ap->blkno = gotbno;
}
#undef ISVALID
}
STATIC int
xfs_bmap_rtalloc(
xfs_bmalloca_t *ap) /* bmap alloc argument struct */
{
xfs_alloctype_t atype = 0; /* type for allocation routines */
int error; /* error return value */
xfs_mount_t *mp; /* mount point structure */
xfs_extlen_t prod = 0; /* product factor for allocators */
xfs_extlen_t ralen = 0; /* realtime allocation length */
xfs_extlen_t align; /* minimum allocation alignment */
xfs_rtblock_t rtb;
mp = ap->ip->i_mount;
align = xfs_get_extsz_hint(ap->ip);
prod = align / mp->m_sb.sb_rextsize;
error = xfs_bmap_extsize_align(mp, &ap->got, &ap->prev,
align, 1, ap->eof, 0,
ap->conv, &ap->offset, &ap->length);
if (error)
return error;
ASSERT(ap->length);
ASSERT(ap->length % mp->m_sb.sb_rextsize == 0);
/*
* If the offset & length are not perfectly aligned
* then kill prod, it will just get us in trouble.
*/
if (do_mod(ap->offset, align) || ap->length % align)
prod = 1;
/*
* Set ralen to be the actual requested length in rtextents.
*/
ralen = ap->length / mp->m_sb.sb_rextsize;
/*
* If the old value was close enough to MAXEXTLEN that
* we rounded up to it, cut it back so it's valid again.
* Note that if it's a really large request (bigger than
* MAXEXTLEN), we don't hear about that number, and can't
* adjust the starting point to match it.
*/
if (ralen * mp->m_sb.sb_rextsize >= MAXEXTLEN)
ralen = MAXEXTLEN / mp->m_sb.sb_rextsize;
/*
* Lock out other modifications to the RT bitmap inode.
*/
xfs_ilock(mp->m_rbmip, XFS_ILOCK_EXCL);
xfs_trans_ijoin(ap->tp, mp->m_rbmip, XFS_ILOCK_EXCL);
/*
* If it's an allocation to an empty file at offset 0,
* pick an extent that will space things out in the rt area.
*/
if (ap->eof && ap->offset == 0) {
xfs_rtblock_t uninitialized_var(rtx); /* realtime extent no */
error = xfs_rtpick_extent(mp, ap->tp, ralen, &rtx);
if (error)
return error;
ap->blkno = rtx * mp->m_sb.sb_rextsize;
} else {
ap->blkno = 0;
}
xfs_bmap_adjacent(ap);
/*
* Realtime allocation, done through xfs_rtallocate_extent.
*/
atype = ap->blkno == 0 ? XFS_ALLOCTYPE_ANY_AG : XFS_ALLOCTYPE_NEAR_BNO;
do_div(ap->blkno, mp->m_sb.sb_rextsize);
rtb = ap->blkno;
ap->length = ralen;
if ((error = xfs_rtallocate_extent(ap->tp, ap->blkno, 1, ap->length,
&ralen, atype, ap->wasdel, prod, &rtb)))
return error;
if (rtb == NULLFSBLOCK && prod > 1 &&
(error = xfs_rtallocate_extent(ap->tp, ap->blkno, 1,
ap->length, &ralen, atype,
ap->wasdel, 1, &rtb)))
return error;
ap->blkno = rtb;
if (ap->blkno != NULLFSBLOCK) {
ap->blkno *= mp->m_sb.sb_rextsize;
ralen *= mp->m_sb.sb_rextsize;
ap->length = ralen;
ap->ip->i_d.di_nblocks += ralen;
xfs_trans_log_inode(ap->tp, ap->ip, XFS_ILOG_CORE);
if (ap->wasdel)
ap->ip->i_delayed_blks -= ralen;
/*
* Adjust the disk quota also. This was reserved
* earlier.
*/
xfs_trans_mod_dquot_byino(ap->tp, ap->ip,
ap->wasdel ? XFS_TRANS_DQ_DELRTBCOUNT :
XFS_TRANS_DQ_RTBCOUNT, (long) ralen);
} else {
ap->length = 0;
}
return 0;
}
STATIC int
xfs_bmap_btalloc_nullfb(
struct xfs_bmalloca *ap,
struct xfs_alloc_arg *args,
xfs_extlen_t *blen)
{
struct xfs_mount *mp = ap->ip->i_mount;
struct xfs_perag *pag;
xfs_agnumber_t ag, startag;
int notinit = 0;
int error;
if (ap->userdata && xfs_inode_is_filestream(ap->ip))
args->type = XFS_ALLOCTYPE_NEAR_BNO;
else
args->type = XFS_ALLOCTYPE_START_BNO;
args->total = ap->total;
/*
* Search for an allocation group with a single extent large enough
* for the request. If one isn't found, then adjust the minimum
* allocation size to the largest space found.
*/
startag = ag = XFS_FSB_TO_AGNO(mp, args->fsbno);
if (startag == NULLAGNUMBER)
startag = ag = 0;
pag = xfs_perag_get(mp, ag);
while (*blen < args->maxlen) {
if (!pag->pagf_init) {
error = xfs_alloc_pagf_init(mp, args->tp, ag,
XFS_ALLOC_FLAG_TRYLOCK);
if (error) {
xfs_perag_put(pag);
return error;
}
}
/*
* See xfs_alloc_fix_freelist...
*/
if (pag->pagf_init) {
xfs_extlen_t longest;
longest = xfs_alloc_longest_free_extent(mp, pag);
if (*blen < longest)
*blen = longest;
} else
notinit = 1;
if (xfs_inode_is_filestream(ap->ip)) {
if (*blen >= args->maxlen)
break;
if (ap->userdata) {
/*
* If startag is an invalid AG, we've
* come here once before and
* xfs_filestream_new_ag picked the
* best currently available.
*
* Don't continue looping, since we
* could loop forever.
*/
if (startag == NULLAGNUMBER)
break;
error = xfs_filestream_new_ag(ap, &ag);
xfs_perag_put(pag);
if (error)
return error;
/* loop again to set 'blen'*/
startag = NULLAGNUMBER;
pag = xfs_perag_get(mp, ag);
continue;
}
}
if (++ag == mp->m_sb.sb_agcount)
ag = 0;
if (ag == startag)
break;
xfs_perag_put(pag);
pag = xfs_perag_get(mp, ag);
}
xfs_perag_put(pag);
/*
* Since the above loop did a BUF_TRYLOCK, it is
* possible that there is space for this request.
*/
if (notinit || *blen < ap->minlen)
args->minlen = ap->minlen;
/*
* If the best seen length is less than the request
* length, use the best as the minimum.
*/
else if (*blen < args->maxlen)
args->minlen = *blen;
/*
* Otherwise we've seen an extent as big as maxlen,
* use that as the minimum.
*/
else
args->minlen = args->maxlen;
/*
* set the failure fallback case to look in the selected
* AG as the stream may have moved.
*/
if (xfs_inode_is_filestream(ap->ip))
ap->blkno = args->fsbno = XFS_AGB_TO_FSB(mp, ag, 0);
return 0;
}
STATIC int
xfs_bmap_btalloc(
xfs_bmalloca_t *ap) /* bmap alloc argument struct */
{
xfs_mount_t *mp; /* mount point structure */
xfs_alloctype_t atype = 0; /* type for allocation routines */
xfs_extlen_t align; /* minimum allocation alignment */
xfs_agnumber_t fb_agno; /* ag number of ap->firstblock */
xfs_agnumber_t ag;
xfs_alloc_arg_t args;
xfs_extlen_t blen;
xfs_extlen_t nextminlen = 0;
int nullfb; /* true if ap->firstblock isn't set */
int isaligned;
int tryagain;
int error;
ASSERT(ap->length);
mp = ap->ip->i_mount;
align = ap->userdata ? xfs_get_extsz_hint(ap->ip) : 0;
if (unlikely(align)) {
error = xfs_bmap_extsize_align(mp, &ap->got, &ap->prev,
align, 0, ap->eof, 0, ap->conv,
&ap->offset, &ap->length);
ASSERT(!error);
ASSERT(ap->length);
}
nullfb = *ap->firstblock == NULLFSBLOCK;
fb_agno = nullfb ? NULLAGNUMBER : XFS_FSB_TO_AGNO(mp, *ap->firstblock);
if (nullfb) {
if (ap->userdata && xfs_inode_is_filestream(ap->ip)) {
ag = xfs_filestream_lookup_ag(ap->ip);
ag = (ag != NULLAGNUMBER) ? ag : 0;
ap->blkno = XFS_AGB_TO_FSB(mp, ag, 0);
} else {
ap->blkno = XFS_INO_TO_FSB(mp, ap->ip->i_ino);
}
} else
ap->blkno = *ap->firstblock;
xfs_bmap_adjacent(ap);
/*
* If allowed, use ap->blkno; otherwise must use firstblock since
* it's in the right allocation group.
*/
if (nullfb || XFS_FSB_TO_AGNO(mp, ap->blkno) == fb_agno)
;
else
ap->blkno = *ap->firstblock;
/*
* Normal allocation, done through xfs_alloc_vextent.
*/
tryagain = isaligned = 0;
args.tp = ap->tp;
args.mp = mp;
args.fsbno = ap->blkno;
/* Trim the allocation back to the maximum an AG can fit. */
args.maxlen = MIN(ap->length, XFS_ALLOC_AG_MAX_USABLE(mp));
args.firstblock = *ap->firstblock;
blen = 0;
if (nullfb) {
error = xfs_bmap_btalloc_nullfb(ap, &args, &blen);
if (error)
return error;
} else if (ap->flist->xbf_low) {
if (xfs_inode_is_filestream(ap->ip))
args.type = XFS_ALLOCTYPE_FIRST_AG;
else
args.type = XFS_ALLOCTYPE_START_BNO;
args.total = args.minlen = ap->minlen;
} else {
args.type = XFS_ALLOCTYPE_NEAR_BNO;
args.total = ap->total;
args.minlen = ap->minlen;
}
/* apply extent size hints if obtained earlier */
if (unlikely(align)) {
args.prod = align;
if ((args.mod = (xfs_extlen_t)do_mod(ap->offset, args.prod)))
args.mod = (xfs_extlen_t)(args.prod - args.mod);
} else if (mp->m_sb.sb_blocksize >= PAGE_CACHE_SIZE) {
args.prod = 1;
args.mod = 0;
} else {
args.prod = PAGE_CACHE_SIZE >> mp->m_sb.sb_blocklog;
if ((args.mod = (xfs_extlen_t)(do_mod(ap->offset, args.prod))))
args.mod = (xfs_extlen_t)(args.prod - args.mod);
}
/*
* If we are not low on available data blocks, and the
* underlying logical volume manager is a stripe, and
* the file offset is zero then try to allocate data
* blocks on stripe unit boundary.
* NOTE: ap->aeof is only set if the allocation length
* is >= the stripe unit and the allocation offset is
* at the end of file.
*/
if (!ap->flist->xbf_low && ap->aeof) {
if (!ap->offset) {
args.alignment = mp->m_dalign;
atype = args.type;
isaligned = 1;
/*
* Adjust for alignment
*/
if (blen > args.alignment && blen <= args.maxlen)
args.minlen = blen - args.alignment;
args.minalignslop = 0;
} else {
/*
* First try an exact bno allocation.
* If it fails then do a near or start bno
* allocation with alignment turned on.
*/
atype = args.type;
tryagain = 1;
args.type = XFS_ALLOCTYPE_THIS_BNO;
args.alignment = 1;
/*
* Compute the minlen+alignment for the
* next case. Set slop so that the value
* of minlen+alignment+slop doesn't go up
* between the calls.
*/
if (blen > mp->m_dalign && blen <= args.maxlen)
nextminlen = blen - mp->m_dalign;
else
nextminlen = args.minlen;
if (nextminlen + mp->m_dalign > args.minlen + 1)
args.minalignslop =
nextminlen + mp->m_dalign -
args.minlen - 1;
else
args.minalignslop = 0;
}
} else {
args.alignment = 1;
args.minalignslop = 0;
}
args.minleft = ap->minleft;
args.wasdel = ap->wasdel;
args.isfl = 0;
args.userdata = ap->userdata;
if ((error = xfs_alloc_vextent(&args)))
return error;
if (tryagain && args.fsbno == NULLFSBLOCK) {
/*
* Exact allocation failed. Now try with alignment
* turned on.
*/
args.type = atype;
args.fsbno = ap->blkno;
args.alignment = mp->m_dalign;
args.minlen = nextminlen;
args.minalignslop = 0;
isaligned = 1;
if ((error = xfs_alloc_vextent(&args)))
return error;
}
if (isaligned && args.fsbno == NULLFSBLOCK) {
/*
* allocation failed, so turn off alignment and
* try again.
*/
args.type = atype;
args.fsbno = ap->blkno;
args.alignment = 0;
if ((error = xfs_alloc_vextent(&args)))
return error;
}
if (args.fsbno == NULLFSBLOCK && nullfb &&
args.minlen > ap->minlen) {
args.minlen = ap->minlen;
args.type = XFS_ALLOCTYPE_START_BNO;
args.fsbno = ap->blkno;
if ((error = xfs_alloc_vextent(&args)))
return error;
}
if (args.fsbno == NULLFSBLOCK && nullfb) {
args.fsbno = 0;
args.type = XFS_ALLOCTYPE_FIRST_AG;
args.total = ap->minlen;
args.minleft = 0;
if ((error = xfs_alloc_vextent(&args)))
return error;
ap->flist->xbf_low = 1;
}
if (args.fsbno != NULLFSBLOCK) {
/*
* check the allocation happened at the same or higher AG than
* the first block that was allocated.
*/
ASSERT(*ap->firstblock == NULLFSBLOCK ||
XFS_FSB_TO_AGNO(mp, *ap->firstblock) ==
XFS_FSB_TO_AGNO(mp, args.fsbno) ||
(ap->flist->xbf_low &&
XFS_FSB_TO_AGNO(mp, *ap->firstblock) <
XFS_FSB_TO_AGNO(mp, args.fsbno)));
ap->blkno = args.fsbno;
if (*ap->firstblock == NULLFSBLOCK)
*ap->firstblock = args.fsbno;
ASSERT(nullfb || fb_agno == args.agno ||
(ap->flist->xbf_low && fb_agno < args.agno));
ap->length = args.len;
ap->ip->i_d.di_nblocks += args.len;
xfs_trans_log_inode(ap->tp, ap->ip, XFS_ILOG_CORE);
if (ap->wasdel)
ap->ip->i_delayed_blks -= args.len;
/*
* Adjust the disk quota also. This was reserved
* earlier.
*/
xfs_trans_mod_dquot_byino(ap->tp, ap->ip,
ap->wasdel ? XFS_TRANS_DQ_DELBCOUNT :
XFS_TRANS_DQ_BCOUNT,
(long) args.len);
} else {
ap->blkno = NULLFSBLOCK;
ap->length = 0;
}
return 0;
}
/*
* xfs_bmap_alloc is called by xfs_bmapi to allocate an extent for a file.
* It figures out where to ask the underlying allocator to put the new extent.
*/
STATIC int
xfs_bmap_alloc(
xfs_bmalloca_t *ap) /* bmap alloc argument struct */
{
if (XFS_IS_REALTIME_INODE(ap->ip) && ap->userdata)
return xfs_bmap_rtalloc(ap);
return xfs_bmap_btalloc(ap);
}
/*
* Transform a btree format file with only one leaf node, where the
* extents list will fit in the inode, into an extents format file.
* Since the file extents are already in-core, all we have to do is
* give up the space for the btree root and pitch the leaf block.
*/
STATIC int /* error */
xfs_bmap_btree_to_extents(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_btree_cur_t *cur, /* btree cursor */
int *logflagsp, /* inode logging flags */
int whichfork) /* data or attr fork */
{
/* REFERENCED */
struct xfs_btree_block *cblock;/* child btree block */
xfs_fsblock_t cbno; /* child block number */
xfs_buf_t *cbp; /* child block's buffer */
int error; /* error return value */
xfs_ifork_t *ifp; /* inode fork data */
xfs_mount_t *mp; /* mount point structure */
__be64 *pp; /* ptr to block address */
struct xfs_btree_block *rblock;/* root btree block */
mp = ip->i_mount;
ifp = XFS_IFORK_PTR(ip, whichfork);
ASSERT(ifp->if_flags & XFS_IFEXTENTS);
ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE);
rblock = ifp->if_broot;
ASSERT(be16_to_cpu(rblock->bb_level) == 1);
ASSERT(be16_to_cpu(rblock->bb_numrecs) == 1);
ASSERT(xfs_bmbt_maxrecs(mp, ifp->if_broot_bytes, 0) == 1);
pp = XFS_BMAP_BROOT_PTR_ADDR(mp, rblock, 1, ifp->if_broot_bytes);
cbno = be64_to_cpu(*pp);
*logflagsp = 0;
#ifdef DEBUG
if ((error = xfs_btree_check_lptr(cur, cbno, 1)))
return error;
#endif
if ((error = xfs_btree_read_bufl(mp, tp, cbno, 0, &cbp,
XFS_BMAP_BTREE_REF)))
return error;
cblock = XFS_BUF_TO_BLOCK(cbp);
if ((error = xfs_btree_check_block(cur, cblock, 0, cbp)))
return error;
xfs_bmap_add_free(cbno, 1, cur->bc_private.b.flist, mp);
ip->i_d.di_nblocks--;
xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_BCOUNT, -1L);
xfs_trans_binval(tp, cbp);
if (cur->bc_bufs[0] == cbp)
cur->bc_bufs[0] = NULL;
xfs_iroot_realloc(ip, -1, whichfork);
ASSERT(ifp->if_broot == NULL);
ASSERT((ifp->if_flags & XFS_IFBROOT) == 0);
XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_EXTENTS);
*logflagsp = XFS_ILOG_CORE | xfs_ilog_fext(whichfork);
return 0;
}
/*
* Called by xfs_bmapi to update file extent records and the btree
* after removing space (or undoing a delayed allocation).
*/
STATIC int /* error */
xfs_bmap_del_extent(
xfs_inode_t *ip, /* incore inode pointer */
xfs_trans_t *tp, /* current transaction pointer */
xfs_extnum_t *idx, /* extent number to update/delete */
xfs_bmap_free_t *flist, /* list of extents to be freed */
xfs_btree_cur_t *cur, /* if null, not a btree */
xfs_bmbt_irec_t *del, /* data to remove from extents */
int *logflagsp, /* inode logging flags */
int whichfork) /* data or attr fork */
{
xfs_filblks_t da_new; /* new delay-alloc indirect blocks */
xfs_filblks_t da_old; /* old delay-alloc indirect blocks */
xfs_fsblock_t del_endblock=0; /* first block past del */
xfs_fileoff_t del_endoff; /* first offset past del */
int delay; /* current block is delayed allocated */
int do_fx; /* free extent at end of routine */
xfs_bmbt_rec_host_t *ep; /* current extent entry pointer */
int error; /* error return value */
int flags; /* inode logging flags */
xfs_bmbt_irec_t got; /* current extent entry */
xfs_fileoff_t got_endoff; /* first offset past got */
int i; /* temp state */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_mount_t *mp; /* mount structure */
xfs_filblks_t nblks; /* quota/sb block count */
xfs_bmbt_irec_t new; /* new record to be inserted */
/* REFERENCED */
uint qfield; /* quota field to update */
xfs_filblks_t temp; /* for indirect length calculations */
xfs_filblks_t temp2; /* for indirect length calculations */
int state = 0;
XFS_STATS_INC(xs_del_exlist);
if (whichfork == XFS_ATTR_FORK)
state |= BMAP_ATTRFORK;
mp = ip->i_mount;
ifp = XFS_IFORK_PTR(ip, whichfork);
ASSERT((*idx >= 0) && (*idx < ifp->if_bytes /
(uint)sizeof(xfs_bmbt_rec_t)));
ASSERT(del->br_blockcount > 0);
ep = xfs_iext_get_ext(ifp, *idx);
xfs_bmbt_get_all(ep, &got);
ASSERT(got.br_startoff <= del->br_startoff);
del_endoff = del->br_startoff + del->br_blockcount;
got_endoff = got.br_startoff + got.br_blockcount;
ASSERT(got_endoff >= del_endoff);
delay = isnullstartblock(got.br_startblock);
ASSERT(isnullstartblock(del->br_startblock) == delay);
flags = 0;
qfield = 0;
error = 0;
/*
* If deleting a real allocation, must free up the disk space.
*/
if (!delay) {
flags = XFS_ILOG_CORE;
/*
* Realtime allocation. Free it and record di_nblocks update.
*/
if (whichfork == XFS_DATA_FORK && XFS_IS_REALTIME_INODE(ip)) {
xfs_fsblock_t bno;
xfs_filblks_t len;
ASSERT(do_mod(del->br_blockcount,
mp->m_sb.sb_rextsize) == 0);
ASSERT(do_mod(del->br_startblock,
mp->m_sb.sb_rextsize) == 0);
bno = del->br_startblock;
len = del->br_blockcount;
do_div(bno, mp->m_sb.sb_rextsize);
do_div(len, mp->m_sb.sb_rextsize);
error = xfs_rtfree_extent(tp, bno, (xfs_extlen_t)len);
if (error)
goto done;
do_fx = 0;
nblks = len * mp->m_sb.sb_rextsize;
qfield = XFS_TRANS_DQ_RTBCOUNT;
}
/*
* Ordinary allocation.
*/
else {
do_fx = 1;
nblks = del->br_blockcount;
qfield = XFS_TRANS_DQ_BCOUNT;
}
/*
* Set up del_endblock and cur for later.
*/
del_endblock = del->br_startblock + del->br_blockcount;
if (cur) {
if ((error = xfs_bmbt_lookup_eq(cur, got.br_startoff,
got.br_startblock, got.br_blockcount,
&i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
}
da_old = da_new = 0;
} else {
da_old = startblockval(got.br_startblock);
da_new = 0;
nblks = 0;
do_fx = 0;
}
/*
* Set flag value to use in switch statement.
* Left-contig is 2, right-contig is 1.
*/
switch (((got.br_startoff == del->br_startoff) << 1) |
(got_endoff == del_endoff)) {
case 3:
/*
* Matches the whole extent. Delete the entry.
*/
xfs_iext_remove(ip, *idx, 1,
whichfork == XFS_ATTR_FORK ? BMAP_ATTRFORK : 0);
--*idx;
if (delay)
break;
XFS_IFORK_NEXT_SET(ip, whichfork,
XFS_IFORK_NEXTENTS(ip, whichfork) - 1);
flags |= XFS_ILOG_CORE;
if (!cur) {
flags |= xfs_ilog_fext(whichfork);
break;
}
if ((error = xfs_btree_delete(cur, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
break;
case 2:
/*
* Deleting the first part of the extent.
*/
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_startoff(ep, del_endoff);
temp = got.br_blockcount - del->br_blockcount;
xfs_bmbt_set_blockcount(ep, temp);
if (delay) {
temp = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
da_old);
xfs_bmbt_set_startblock(ep, nullstartblock((int)temp));
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
da_new = temp;
break;
}
xfs_bmbt_set_startblock(ep, del_endblock);
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
if (!cur) {
flags |= xfs_ilog_fext(whichfork);
break;
}
if ((error = xfs_bmbt_update(cur, del_endoff, del_endblock,
got.br_blockcount - del->br_blockcount,
got.br_state)))
goto done;
break;
case 1:
/*
* Deleting the last part of the extent.
*/
temp = got.br_blockcount - del->br_blockcount;
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep, temp);
if (delay) {
temp = XFS_FILBLKS_MIN(xfs_bmap_worst_indlen(ip, temp),
da_old);
xfs_bmbt_set_startblock(ep, nullstartblock((int)temp));
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
da_new = temp;
break;
}
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
if (!cur) {
flags |= xfs_ilog_fext(whichfork);
break;
}
if ((error = xfs_bmbt_update(cur, got.br_startoff,
got.br_startblock,
got.br_blockcount - del->br_blockcount,
got.br_state)))
goto done;
break;
case 0:
/*
* Deleting the middle of the extent.
*/
temp = del->br_startoff - got.br_startoff;
trace_xfs_bmap_pre_update(ip, *idx, state, _THIS_IP_);
xfs_bmbt_set_blockcount(ep, temp);
new.br_startoff = del_endoff;
temp2 = got_endoff - del_endoff;
new.br_blockcount = temp2;
new.br_state = got.br_state;
if (!delay) {
new.br_startblock = del_endblock;
flags |= XFS_ILOG_CORE;
if (cur) {
if ((error = xfs_bmbt_update(cur,
got.br_startoff,
got.br_startblock, temp,
got.br_state)))
goto done;
if ((error = xfs_btree_increment(cur, 0, &i)))
goto done;
cur->bc_rec.b = new;
error = xfs_btree_insert(cur, &i);
if (error && error != ENOSPC)
goto done;
/*
* If get no-space back from btree insert,
* it tried a split, and we have a zero
* block reservation.
* Fix up our state and return the error.
*/
if (error == ENOSPC) {
/*
* Reset the cursor, don't trust
* it after any insert operation.
*/
if ((error = xfs_bmbt_lookup_eq(cur,
got.br_startoff,
got.br_startblock,
temp, &i)))
goto done;
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
/*
* Update the btree record back
* to the original value.
*/
if ((error = xfs_bmbt_update(cur,
got.br_startoff,
got.br_startblock,
got.br_blockcount,
got.br_state)))
goto done;
/*
* Reset the extent record back
* to the original value.
*/
xfs_bmbt_set_blockcount(ep,
got.br_blockcount);
flags = 0;
error = XFS_ERROR(ENOSPC);
goto done;
}
XFS_WANT_CORRUPTED_GOTO(i == 1, done);
} else
flags |= xfs_ilog_fext(whichfork);
XFS_IFORK_NEXT_SET(ip, whichfork,
XFS_IFORK_NEXTENTS(ip, whichfork) + 1);
} else {
ASSERT(whichfork == XFS_DATA_FORK);
temp = xfs_bmap_worst_indlen(ip, temp);
xfs_bmbt_set_startblock(ep, nullstartblock((int)temp));
temp2 = xfs_bmap_worst_indlen(ip, temp2);
new.br_startblock = nullstartblock((int)temp2);
da_new = temp + temp2;
while (da_new > da_old) {
if (temp) {
temp--;
da_new--;
xfs_bmbt_set_startblock(ep,
nullstartblock((int)temp));
}
if (da_new == da_old)
break;
if (temp2) {
temp2--;
da_new--;
new.br_startblock =
nullstartblock((int)temp2);
}
}
}
trace_xfs_bmap_post_update(ip, *idx, state, _THIS_IP_);
xfs_iext_insert(ip, *idx + 1, 1, &new, state);
++*idx;
break;
}
/*
* If we need to, add to list of extents to delete.
*/
if (do_fx)
xfs_bmap_add_free(del->br_startblock, del->br_blockcount, flist,
mp);
/*
* Adjust inode # blocks in the file.
*/
if (nblks)
ip->i_d.di_nblocks -= nblks;
/*
* Adjust quota data.
*/
if (qfield)
xfs_trans_mod_dquot_byino(tp, ip, qfield, (long)-nblks);
/*
* Account for change in delayed indirect blocks.
* Nothing to do for disk quota accounting here.
*/
ASSERT(da_old >= da_new);
if (da_old > da_new) {
xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS,
(int64_t)(da_old - da_new), 0);
}
done:
*logflagsp = flags;
return error;
}
/*
* Remove the entry "free" from the free item list. Prev points to the
* previous entry, unless "free" is the head of the list.
*/
STATIC void
xfs_bmap_del_free(
xfs_bmap_free_t *flist, /* free item list header */
xfs_bmap_free_item_t *prev, /* previous item on list, if any */
xfs_bmap_free_item_t *free) /* list item to be freed */
{
if (prev)
prev->xbfi_next = free->xbfi_next;
else
flist->xbf_first = free->xbfi_next;
flist->xbf_count--;
kmem_zone_free(xfs_bmap_free_item_zone, free);
}
/*
* Convert an extents-format file into a btree-format file.
* The new file will have a root block (in the inode) and a single child block.
*/
STATIC int /* error */
xfs_bmap_extents_to_btree(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_fsblock_t *firstblock, /* first-block-allocated */
xfs_bmap_free_t *flist, /* blocks freed in xaction */
xfs_btree_cur_t **curp, /* cursor returned to caller */
int wasdel, /* converting a delayed alloc */
int *logflagsp, /* inode logging flags */
int whichfork) /* data or attr fork */
{
struct xfs_btree_block *ablock; /* allocated (child) bt block */
xfs_buf_t *abp; /* buffer for ablock */
xfs_alloc_arg_t args; /* allocation arguments */
xfs_bmbt_rec_t *arp; /* child record pointer */
struct xfs_btree_block *block; /* btree root block */
xfs_btree_cur_t *cur; /* bmap btree cursor */
xfs_bmbt_rec_host_t *ep; /* extent record pointer */
int error; /* error return value */
xfs_extnum_t i, cnt; /* extent record index */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_bmbt_key_t *kp; /* root block key pointer */
xfs_mount_t *mp; /* mount structure */
xfs_extnum_t nextents; /* number of file extents */
xfs_bmbt_ptr_t *pp; /* root block address pointer */
ifp = XFS_IFORK_PTR(ip, whichfork);
ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS);
/*
* Make space in the inode incore.
*/
xfs_iroot_realloc(ip, 1, whichfork);
ifp->if_flags |= XFS_IFBROOT;
/*
* Fill in the root.
*/
block = ifp->if_broot;
block->bb_magic = cpu_to_be32(XFS_BMAP_MAGIC);
block->bb_level = cpu_to_be16(1);
block->bb_numrecs = cpu_to_be16(1);
block->bb_u.l.bb_leftsib = cpu_to_be64(NULLDFSBNO);
block->bb_u.l.bb_rightsib = cpu_to_be64(NULLDFSBNO);
/*
* Need a cursor. Can't allocate until bb_level is filled in.
*/
mp = ip->i_mount;
cur = xfs_bmbt_init_cursor(mp, tp, ip, whichfork);
cur->bc_private.b.firstblock = *firstblock;
cur->bc_private.b.flist = flist;
cur->bc_private.b.flags = wasdel ? XFS_BTCUR_BPRV_WASDEL : 0;
/*
* Convert to a btree with two levels, one record in root.
*/
XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_BTREE);
args.tp = tp;
args.mp = mp;
args.firstblock = *firstblock;
if (*firstblock == NULLFSBLOCK) {
args.type = XFS_ALLOCTYPE_START_BNO;
args.fsbno = XFS_INO_TO_FSB(mp, ip->i_ino);
} else if (flist->xbf_low) {
args.type = XFS_ALLOCTYPE_START_BNO;
args.fsbno = *firstblock;
} else {
args.type = XFS_ALLOCTYPE_NEAR_BNO;
args.fsbno = *firstblock;
}
args.minlen = args.maxlen = args.prod = 1;
args.total = args.minleft = args.alignment = args.mod = args.isfl =
args.minalignslop = 0;
args.wasdel = wasdel;
*logflagsp = 0;
if ((error = xfs_alloc_vextent(&args))) {
xfs_iroot_realloc(ip, -1, whichfork);
xfs_btree_del_cursor(cur, XFS_BTREE_ERROR);
return error;
}
/*
* Allocation can't fail, the space was reserved.
*/
ASSERT(args.fsbno != NULLFSBLOCK);
ASSERT(*firstblock == NULLFSBLOCK ||
args.agno == XFS_FSB_TO_AGNO(mp, *firstblock) ||
(flist->xbf_low &&
args.agno > XFS_FSB_TO_AGNO(mp, *firstblock)));
*firstblock = cur->bc_private.b.firstblock = args.fsbno;
cur->bc_private.b.allocated++;
ip->i_d.di_nblocks++;
xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_BCOUNT, 1L);
abp = xfs_btree_get_bufl(mp, tp, args.fsbno, 0);
/*
* Fill in the child block.
*/
ablock = XFS_BUF_TO_BLOCK(abp);
ablock->bb_magic = cpu_to_be32(XFS_BMAP_MAGIC);
ablock->bb_level = 0;
ablock->bb_u.l.bb_leftsib = cpu_to_be64(NULLDFSBNO);
ablock->bb_u.l.bb_rightsib = cpu_to_be64(NULLDFSBNO);
arp = XFS_BMBT_REC_ADDR(mp, ablock, 1);
nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
for (cnt = i = 0; i < nextents; i++) {
ep = xfs_iext_get_ext(ifp, i);
if (!isnullstartblock(xfs_bmbt_get_startblock(ep))) {
arp->l0 = cpu_to_be64(ep->l0);
arp->l1 = cpu_to_be64(ep->l1);
arp++; cnt++;
}
}
ASSERT(cnt == XFS_IFORK_NEXTENTS(ip, whichfork));
xfs_btree_set_numrecs(ablock, cnt);
/*
* Fill in the root key and pointer.
*/
kp = XFS_BMBT_KEY_ADDR(mp, block, 1);
arp = XFS_BMBT_REC_ADDR(mp, ablock, 1);
kp->br_startoff = cpu_to_be64(xfs_bmbt_disk_get_startoff(arp));
pp = XFS_BMBT_PTR_ADDR(mp, block, 1, xfs_bmbt_get_maxrecs(cur,
be16_to_cpu(block->bb_level)));
*pp = cpu_to_be64(args.fsbno);
/*
* Do all this logging at the end so that
* the root is at the right level.
*/
xfs_btree_log_block(cur, abp, XFS_BB_ALL_BITS);
xfs_btree_log_recs(cur, abp, 1, be16_to_cpu(ablock->bb_numrecs));
ASSERT(*curp == NULL);
*curp = cur;
*logflagsp = XFS_ILOG_CORE | xfs_ilog_fbroot(whichfork);
return 0;
}
/*
* Calculate the default attribute fork offset for newly created inodes.
*/
uint
xfs_default_attroffset(
struct xfs_inode *ip)
{
struct xfs_mount *mp = ip->i_mount;
uint offset;
if (mp->m_sb.sb_inodesize == 256) {
offset = XFS_LITINO(mp) -
XFS_BMDR_SPACE_CALC(MINABTPTRS);
} else {
offset = XFS_BMDR_SPACE_CALC(6 * MINABTPTRS);
}
ASSERT(offset < XFS_LITINO(mp));
return offset;
}
/*
* Helper routine to reset inode di_forkoff field when switching
* attribute fork from local to extent format - we reset it where
* possible to make space available for inline data fork extents.
*/
STATIC void
xfs_bmap_forkoff_reset(
xfs_mount_t *mp,
xfs_inode_t *ip,
int whichfork)
{
if (whichfork == XFS_ATTR_FORK &&
ip->i_d.di_format != XFS_DINODE_FMT_DEV &&
ip->i_d.di_format != XFS_DINODE_FMT_UUID &&
ip->i_d.di_format != XFS_DINODE_FMT_BTREE) {
uint dfl_forkoff = xfs_default_attroffset(ip) >> 3;
if (dfl_forkoff > ip->i_d.di_forkoff)
ip->i_d.di_forkoff = dfl_forkoff;
}
}
/*
* Convert a local file to an extents file.
* This code is out of bounds for data forks of regular files,
* since the file data needs to get logged so things will stay consistent.
* (The bmap-level manipulations are ok, though).
*/
STATIC int /* error */
xfs_bmap_local_to_extents(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode pointer */
xfs_fsblock_t *firstblock, /* first block allocated in xaction */
xfs_extlen_t total, /* total blocks needed by transaction */
int *logflagsp, /* inode logging flags */
int whichfork) /* data or attr fork */
{
int error; /* error return value */
int flags; /* logging flags returned */
xfs_ifork_t *ifp; /* inode fork pointer */
/*
* We don't want to deal with the case of keeping inode data inline yet.
* So sending the data fork of a regular inode is invalid.
*/
ASSERT(!(S_ISREG(ip->i_d.di_mode) && whichfork == XFS_DATA_FORK));
ifp = XFS_IFORK_PTR(ip, whichfork);
ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL);
flags = 0;
error = 0;
if (ifp->if_bytes) {
xfs_alloc_arg_t args; /* allocation arguments */
xfs_buf_t *bp; /* buffer for extent block */
xfs_bmbt_rec_host_t *ep;/* extent record pointer */
args.tp = tp;
args.mp = ip->i_mount;
args.firstblock = *firstblock;
ASSERT((ifp->if_flags &
(XFS_IFINLINE|XFS_IFEXTENTS|XFS_IFEXTIREC)) == XFS_IFINLINE);
/*
* Allocate a block. We know we need only one, since the
* file currently fits in an inode.
*/
if (*firstblock == NULLFSBLOCK) {
args.fsbno = XFS_INO_TO_FSB(args.mp, ip->i_ino);
args.type = XFS_ALLOCTYPE_START_BNO;
} else {
args.fsbno = *firstblock;
args.type = XFS_ALLOCTYPE_NEAR_BNO;
}
args.total = total;
args.mod = args.minleft = args.alignment = args.wasdel =
args.isfl = args.minalignslop = 0;
args.minlen = args.maxlen = args.prod = 1;
if ((error = xfs_alloc_vextent(&args)))
goto done;
/*
* Can't fail, the space was reserved.
*/
ASSERT(args.fsbno != NULLFSBLOCK);
ASSERT(args.len == 1);
*firstblock = args.fsbno;
bp = xfs_btree_get_bufl(args.mp, tp, args.fsbno, 0);
memcpy(bp->b_addr, ifp->if_u1.if_data, ifp->if_bytes);
xfs_trans_log_buf(tp, bp, 0, ifp->if_bytes - 1);
xfs_bmap_forkoff_reset(args.mp, ip, whichfork);
xfs_idata_realloc(ip, -ifp->if_bytes, whichfork);
xfs_iext_add(ifp, 0, 1);
ep = xfs_iext_get_ext(ifp, 0);
xfs_bmbt_set_allf(ep, 0, args.fsbno, 1, XFS_EXT_NORM);
trace_xfs_bmap_post_update(ip, 0,
whichfork == XFS_ATTR_FORK ? BMAP_ATTRFORK : 0,
_THIS_IP_);
XFS_IFORK_NEXT_SET(ip, whichfork, 1);
ip->i_d.di_nblocks = 1;
xfs_trans_mod_dquot_byino(tp, ip,
XFS_TRANS_DQ_BCOUNT, 1L);
flags |= xfs_ilog_fext(whichfork);
} else {
ASSERT(XFS_IFORK_NEXTENTS(ip, whichfork) == 0);
xfs_bmap_forkoff_reset(ip->i_mount, ip, whichfork);
}
ifp->if_flags &= ~XFS_IFINLINE;
ifp->if_flags |= XFS_IFEXTENTS;
XFS_IFORK_FMT_SET(ip, whichfork, XFS_DINODE_FMT_EXTENTS);
flags |= XFS_ILOG_CORE;
done:
*logflagsp = flags;
return error;
}
/*
* Search the extent records for the entry containing block bno.
* If bno lies in a hole, point to the next entry. If bno lies
* past eof, *eofp will be set, and *prevp will contain the last
* entry (null if none). Else, *lastxp will be set to the index
* of the found entry; *gotp will contain the entry.
*/
STATIC xfs_bmbt_rec_host_t * /* pointer to found extent entry */
xfs_bmap_search_multi_extents(
xfs_ifork_t *ifp, /* inode fork pointer */
xfs_fileoff_t bno, /* block number searched for */
int *eofp, /* out: end of file found */
xfs_extnum_t *lastxp, /* out: last extent index */
xfs_bmbt_irec_t *gotp, /* out: extent entry found */
xfs_bmbt_irec_t *prevp) /* out: previous extent entry found */
{
xfs_bmbt_rec_host_t *ep; /* extent record pointer */
xfs_extnum_t lastx; /* last extent index */
/*
* Initialize the extent entry structure to catch access to
* uninitialized br_startblock field.
*/
gotp->br_startoff = 0xffa5a5a5a5a5a5a5LL;
gotp->br_blockcount = 0xa55a5a5a5a5a5a5aLL;
gotp->br_state = XFS_EXT_INVALID;
#if XFS_BIG_BLKNOS
gotp->br_startblock = 0xffffa5a5a5a5a5a5LL;
#else
gotp->br_startblock = 0xffffa5a5;
#endif
prevp->br_startoff = NULLFILEOFF;
ep = xfs_iext_bno_to_ext(ifp, bno, &lastx);
if (lastx > 0) {
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, lastx - 1), prevp);
}
if (lastx < (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t))) {
xfs_bmbt_get_all(ep, gotp);
*eofp = 0;
} else {
if (lastx > 0) {
*gotp = *prevp;
}
*eofp = 1;
ep = NULL;
}
*lastxp = lastx;
return ep;
}
/*
* Search the extents list for the inode, for the extent containing bno.
* If bno lies in a hole, point to the next entry. If bno lies past eof,
* *eofp will be set, and *prevp will contain the last entry (null if none).
* Else, *lastxp will be set to the index of the found
* entry; *gotp will contain the entry.
*/
STATIC xfs_bmbt_rec_host_t * /* pointer to found extent entry */
xfs_bmap_search_extents(
xfs_inode_t *ip, /* incore inode pointer */
xfs_fileoff_t bno, /* block number searched for */
int fork, /* data or attr fork */
int *eofp, /* out: end of file found */
xfs_extnum_t *lastxp, /* out: last extent index */
xfs_bmbt_irec_t *gotp, /* out: extent entry found */
xfs_bmbt_irec_t *prevp) /* out: previous extent entry found */
{
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_bmbt_rec_host_t *ep; /* extent record pointer */
XFS_STATS_INC(xs_look_exlist);
ifp = XFS_IFORK_PTR(ip, fork);
ep = xfs_bmap_search_multi_extents(ifp, bno, eofp, lastxp, gotp, prevp);
if (unlikely(!(gotp->br_startblock) && (*lastxp != NULLEXTNUM) &&
!(XFS_IS_REALTIME_INODE(ip) && fork == XFS_DATA_FORK))) {
xfs_alert_tag(ip->i_mount, XFS_PTAG_FSBLOCK_ZERO,
"Access to block zero in inode %llu "
"start_block: %llx start_off: %llx "
"blkcnt: %llx extent-state: %x lastx: %x\n",
(unsigned long long)ip->i_ino,
(unsigned long long)gotp->br_startblock,
(unsigned long long)gotp->br_startoff,
(unsigned long long)gotp->br_blockcount,
gotp->br_state, *lastxp);
*lastxp = NULLEXTNUM;
*eofp = 1;
return NULL;
}
return ep;
}
/*
* Compute the worst-case number of indirect blocks that will be used
* for ip's delayed extent of length "len".
*/
STATIC xfs_filblks_t
xfs_bmap_worst_indlen(
xfs_inode_t *ip, /* incore inode pointer */
xfs_filblks_t len) /* delayed extent length */
{
int level; /* btree level number */
int maxrecs; /* maximum record count at this level */
xfs_mount_t *mp; /* mount structure */
xfs_filblks_t rval; /* return value */
mp = ip->i_mount;
maxrecs = mp->m_bmap_dmxr[0];
for (level = 0, rval = 0;
level < XFS_BM_MAXLEVELS(mp, XFS_DATA_FORK);
level++) {
len += maxrecs - 1;
do_div(len, maxrecs);
rval += len;
if (len == 1)
return rval + XFS_BM_MAXLEVELS(mp, XFS_DATA_FORK) -
level - 1;
if (level == 0)
maxrecs = mp->m_bmap_dmxr[1];
}
return rval;
}
/*
* Convert inode from non-attributed to attributed.
* Must not be in a transaction, ip must not be locked.
*/
int /* error code */
xfs_bmap_add_attrfork(
xfs_inode_t *ip, /* incore inode pointer */
int size, /* space new attribute needs */
int rsvd) /* xact may use reserved blks */
{
xfs_fsblock_t firstblock; /* 1st block/ag allocated */
xfs_bmap_free_t flist; /* freed extent records */
xfs_mount_t *mp; /* mount structure */
xfs_trans_t *tp; /* transaction pointer */
int blks; /* space reservation */
int version = 1; /* superblock attr version */
int committed; /* xaction was committed */
int logflags; /* logging flags */
int error; /* error return value */
ASSERT(XFS_IFORK_Q(ip) == 0);
mp = ip->i_mount;
ASSERT(!XFS_NOT_DQATTACHED(mp, ip));
tp = xfs_trans_alloc(mp, XFS_TRANS_ADDAFORK);
blks = XFS_ADDAFORK_SPACE_RES(mp);
if (rsvd)
tp->t_flags |= XFS_TRANS_RESERVE;
if ((error = xfs_trans_reserve(tp, blks, XFS_ADDAFORK_LOG_RES(mp), 0,
XFS_TRANS_PERM_LOG_RES, XFS_ADDAFORK_LOG_COUNT)))
goto error0;
xfs_ilock(ip, XFS_ILOCK_EXCL);
error = xfs_trans_reserve_quota_nblks(tp, ip, blks, 0, rsvd ?
XFS_QMOPT_RES_REGBLKS | XFS_QMOPT_FORCE_RES :
XFS_QMOPT_RES_REGBLKS);
if (error) {
xfs_iunlock(ip, XFS_ILOCK_EXCL);
xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES);
return error;
}
if (XFS_IFORK_Q(ip))
goto error1;
if (ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS) {
/*
* For inodes coming from pre-6.2 filesystems.
*/
ASSERT(ip->i_d.di_aformat == 0);
ip->i_d.di_aformat = XFS_DINODE_FMT_EXTENTS;
}
ASSERT(ip->i_d.di_anextents == 0);
xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
switch (ip->i_d.di_format) {
case XFS_DINODE_FMT_DEV:
ip->i_d.di_forkoff = roundup(sizeof(xfs_dev_t), 8) >> 3;
break;
case XFS_DINODE_FMT_UUID:
ip->i_d.di_forkoff = roundup(sizeof(uuid_t), 8) >> 3;
break;
case XFS_DINODE_FMT_LOCAL:
case XFS_DINODE_FMT_EXTENTS:
case XFS_DINODE_FMT_BTREE:
ip->i_d.di_forkoff = xfs_attr_shortform_bytesfit(ip, size);
if (!ip->i_d.di_forkoff)
ip->i_d.di_forkoff = xfs_default_attroffset(ip) >> 3;
else if (mp->m_flags & XFS_MOUNT_ATTR2)
version = 2;
break;
default:
ASSERT(0);
error = XFS_ERROR(EINVAL);
goto error1;
}
ASSERT(ip->i_afp == NULL);
ip->i_afp = kmem_zone_zalloc(xfs_ifork_zone, KM_SLEEP);
ip->i_afp->if_flags = XFS_IFEXTENTS;
logflags = 0;
xfs_bmap_init(&flist, &firstblock);
switch (ip->i_d.di_format) {
case XFS_DINODE_FMT_LOCAL:
error = xfs_bmap_add_attrfork_local(tp, ip, &firstblock, &flist,
&logflags);
break;
case XFS_DINODE_FMT_EXTENTS:
error = xfs_bmap_add_attrfork_extents(tp, ip, &firstblock,
&flist, &logflags);
break;
case XFS_DINODE_FMT_BTREE:
error = xfs_bmap_add_attrfork_btree(tp, ip, &firstblock, &flist,
&logflags);
break;
default:
error = 0;
break;
}
if (logflags)
xfs_trans_log_inode(tp, ip, logflags);
if (error)
goto error2;
if (!xfs_sb_version_hasattr(&mp->m_sb) ||
(!xfs_sb_version_hasattr2(&mp->m_sb) && version == 2)) {
__int64_t sbfields = 0;
spin_lock(&mp->m_sb_lock);
if (!xfs_sb_version_hasattr(&mp->m_sb)) {
xfs_sb_version_addattr(&mp->m_sb);
sbfields |= XFS_SB_VERSIONNUM;
}
if (!xfs_sb_version_hasattr2(&mp->m_sb) && version == 2) {
xfs_sb_version_addattr2(&mp->m_sb);
sbfields |= (XFS_SB_VERSIONNUM | XFS_SB_FEATURES2);
}
if (sbfields) {
spin_unlock(&mp->m_sb_lock);
xfs_mod_sb(tp, sbfields);
} else
spin_unlock(&mp->m_sb_lock);
}
error = xfs_bmap_finish(&tp, &flist, &committed);
if (error)
goto error2;
return xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
error2:
xfs_bmap_cancel(&flist);
error1:
xfs_iunlock(ip, XFS_ILOCK_EXCL);
error0:
xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES|XFS_TRANS_ABORT);
return error;
}
/*
* Add the extent to the list of extents to be free at transaction end.
* The list is maintained sorted (by block number).
*/
/* ARGSUSED */
void
xfs_bmap_add_free(
xfs_fsblock_t bno, /* fs block number of extent */
xfs_filblks_t len, /* length of extent */
xfs_bmap_free_t *flist, /* list of extents */
xfs_mount_t *mp) /* mount point structure */
{
xfs_bmap_free_item_t *cur; /* current (next) element */
xfs_bmap_free_item_t *new; /* new element */
xfs_bmap_free_item_t *prev; /* previous element */
#ifdef DEBUG
xfs_agnumber_t agno;
xfs_agblock_t agbno;
ASSERT(bno != NULLFSBLOCK);
ASSERT(len > 0);
ASSERT(len <= MAXEXTLEN);
ASSERT(!isnullstartblock(bno));
agno = XFS_FSB_TO_AGNO(mp, bno);
agbno = XFS_FSB_TO_AGBNO(mp, bno);
ASSERT(agno < mp->m_sb.sb_agcount);
ASSERT(agbno < mp->m_sb.sb_agblocks);
ASSERT(len < mp->m_sb.sb_agblocks);
ASSERT(agbno + len <= mp->m_sb.sb_agblocks);
#endif
ASSERT(xfs_bmap_free_item_zone != NULL);
new = kmem_zone_alloc(xfs_bmap_free_item_zone, KM_SLEEP);
new->xbfi_startblock = bno;
new->xbfi_blockcount = (xfs_extlen_t)len;
for (prev = NULL, cur = flist->xbf_first;
cur != NULL;
prev = cur, cur = cur->xbfi_next) {
if (cur->xbfi_startblock >= bno)
break;
}
if (prev)
prev->xbfi_next = new;
else
flist->xbf_first = new;
new->xbfi_next = cur;
flist->xbf_count++;
}
/*
* Compute and fill in the value of the maximum depth of a bmap btree
* in this filesystem. Done once, during mount.
*/
void
xfs_bmap_compute_maxlevels(
xfs_mount_t *mp, /* file system mount structure */
int whichfork) /* data or attr fork */
{
int level; /* btree level */
uint maxblocks; /* max blocks at this level */
uint maxleafents; /* max leaf entries possible */
int maxrootrecs; /* max records in root block */
int minleafrecs; /* min records in leaf block */
int minnoderecs; /* min records in node block */
int sz; /* root block size */
/*
* The maximum number of extents in a file, hence the maximum
* number of leaf entries, is controlled by the type of di_nextents
* (a signed 32-bit number, xfs_extnum_t), or by di_anextents
* (a signed 16-bit number, xfs_aextnum_t).
*
* Note that we can no longer assume that if we are in ATTR1 that
* the fork offset of all the inodes will be
* (xfs_default_attroffset(ip) >> 3) because we could have mounted
* with ATTR2 and then mounted back with ATTR1, keeping the
* di_forkoff's fixed but probably at various positions. Therefore,
* for both ATTR1 and ATTR2 we have to assume the worst case scenario
* of a minimum size available.
*/
if (whichfork == XFS_DATA_FORK) {
maxleafents = MAXEXTNUM;
sz = XFS_BMDR_SPACE_CALC(MINDBTPTRS);
} else {
maxleafents = MAXAEXTNUM;
sz = XFS_BMDR_SPACE_CALC(MINABTPTRS);
}
maxrootrecs = xfs_bmdr_maxrecs(mp, sz, 0);
minleafrecs = mp->m_bmap_dmnr[0];
minnoderecs = mp->m_bmap_dmnr[1];
maxblocks = (maxleafents + minleafrecs - 1) / minleafrecs;
for (level = 1; maxblocks > 1; level++) {
if (maxblocks <= maxrootrecs)
maxblocks = 1;
else
maxblocks = (maxblocks + minnoderecs - 1) / minnoderecs;
}
mp->m_bm_maxlevels[whichfork] = level;
}
/*
* Routine to be called at transaction's end by xfs_bmapi, xfs_bunmapi
* caller. Frees all the extents that need freeing, which must be done
* last due to locking considerations. We never free any extents in
* the first transaction.
*
* Return 1 if the given transaction was committed and a new one
* started, and 0 otherwise in the committed parameter.
*/
int /* error */
xfs_bmap_finish(
xfs_trans_t **tp, /* transaction pointer addr */
xfs_bmap_free_t *flist, /* i/o: list extents to free */
int *committed) /* xact committed or not */
{
xfs_efd_log_item_t *efd; /* extent free data */
xfs_efi_log_item_t *efi; /* extent free intention */
int error; /* error return value */
xfs_bmap_free_item_t *free; /* free extent item */
unsigned int logres; /* new log reservation */
unsigned int logcount; /* new log count */
xfs_mount_t *mp; /* filesystem mount structure */
xfs_bmap_free_item_t *next; /* next item on free list */
xfs_trans_t *ntp; /* new transaction pointer */
ASSERT((*tp)->t_flags & XFS_TRANS_PERM_LOG_RES);
if (flist->xbf_count == 0) {
*committed = 0;
return 0;
}
ntp = *tp;
efi = xfs_trans_get_efi(ntp, flist->xbf_count);
for (free = flist->xbf_first; free; free = free->xbfi_next)
xfs_trans_log_efi_extent(ntp, efi, free->xbfi_startblock,
free->xbfi_blockcount);
logres = ntp->t_log_res;
logcount = ntp->t_log_count;
ntp = xfs_trans_dup(*tp);
error = xfs_trans_commit(*tp, 0);
*tp = ntp;
*committed = 1;
/*
* We have a new transaction, so we should return committed=1,
* even though we're returning an error.
*/
if (error)
return error;
/*
* transaction commit worked ok so we can drop the extra ticket
* reference that we gained in xfs_trans_dup()
*/
xfs_log_ticket_put(ntp->t_ticket);
if ((error = xfs_trans_reserve(ntp, 0, logres, 0, XFS_TRANS_PERM_LOG_RES,
logcount)))
return error;
efd = xfs_trans_get_efd(ntp, efi, flist->xbf_count);
for (free = flist->xbf_first; free != NULL; free = next) {
next = free->xbfi_next;
if ((error = xfs_free_extent(ntp, free->xbfi_startblock,
free->xbfi_blockcount))) {
/*
* The bmap free list will be cleaned up at a
* higher level. The EFI will be canceled when
* this transaction is aborted.
* Need to force shutdown here to make sure it
* happens, since this transaction may not be
* dirty yet.
*/
mp = ntp->t_mountp;
if (!XFS_FORCED_SHUTDOWN(mp))
xfs_force_shutdown(mp,
(error == EFSCORRUPTED) ?
SHUTDOWN_CORRUPT_INCORE :
SHUTDOWN_META_IO_ERROR);
return error;
}
xfs_trans_log_efd_extent(ntp, efd, free->xbfi_startblock,
free->xbfi_blockcount);
xfs_bmap_del_free(flist, NULL, free);
}
return 0;
}
/*
* Free up any items left in the list.
*/
void
xfs_bmap_cancel(
xfs_bmap_free_t *flist) /* list of bmap_free_items */
{
xfs_bmap_free_item_t *free; /* free list item */
xfs_bmap_free_item_t *next;
if (flist->xbf_count == 0)
return;
ASSERT(flist->xbf_first != NULL);
for (free = flist->xbf_first; free; free = next) {
next = free->xbfi_next;
xfs_bmap_del_free(flist, NULL, free);
}
ASSERT(flist->xbf_count == 0);
}
/*
* Returns the file-relative block number of the first unused block(s)
* in the file with at least "len" logically contiguous blocks free.
* This is the lowest-address hole if the file has holes, else the first block
* past the end of file.
* Return 0 if the file is currently local (in-inode).
*/
int /* error */
xfs_bmap_first_unused(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode */
xfs_extlen_t len, /* size of hole to find */
xfs_fileoff_t *first_unused, /* unused block */
int whichfork) /* data or attr fork */
{
int error; /* error return value */
int idx; /* extent record index */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_fileoff_t lastaddr; /* last block number seen */
xfs_fileoff_t lowest; /* lowest useful block */
xfs_fileoff_t max; /* starting useful block */
xfs_fileoff_t off; /* offset for this block */
xfs_extnum_t nextents; /* number of extent entries */
ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE ||
XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS ||
XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL);
if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) {
*first_unused = 0;
return 0;
}
ifp = XFS_IFORK_PTR(ip, whichfork);
if (!(ifp->if_flags & XFS_IFEXTENTS) &&
(error = xfs_iread_extents(tp, ip, whichfork)))
return error;
lowest = *first_unused;
nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
for (idx = 0, lastaddr = 0, max = lowest; idx < nextents; idx++) {
xfs_bmbt_rec_host_t *ep = xfs_iext_get_ext(ifp, idx);
off = xfs_bmbt_get_startoff(ep);
/*
* See if the hole before this extent will work.
*/
if (off >= lowest + len && off - max >= len) {
*first_unused = max;
return 0;
}
lastaddr = off + xfs_bmbt_get_blockcount(ep);
max = XFS_FILEOFF_MAX(lastaddr, lowest);
}
*first_unused = max;
return 0;
}
/*
* Returns the file-relative block number of the last block + 1 before
* last_block (input value) in the file.
* This is not based on i_size, it is based on the extent records.
* Returns 0 for local files, as they do not have extent records.
*/
int /* error */
xfs_bmap_last_before(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode */
xfs_fileoff_t *last_block, /* last block */
int whichfork) /* data or attr fork */
{
xfs_fileoff_t bno; /* input file offset */
int eof; /* hit end of file */
xfs_bmbt_rec_host_t *ep; /* pointer to last extent */
int error; /* error return value */
xfs_bmbt_irec_t got; /* current extent value */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_extnum_t lastx; /* last extent used */
xfs_bmbt_irec_t prev; /* previous extent value */
if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_LOCAL)
return XFS_ERROR(EIO);
if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) {
*last_block = 0;
return 0;
}
ifp = XFS_IFORK_PTR(ip, whichfork);
if (!(ifp->if_flags & XFS_IFEXTENTS) &&
(error = xfs_iread_extents(tp, ip, whichfork)))
return error;
bno = *last_block - 1;
ep = xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got,
&prev);
if (eof || xfs_bmbt_get_startoff(ep) > bno) {
if (prev.br_startoff == NULLFILEOFF)
*last_block = 0;
else
*last_block = prev.br_startoff + prev.br_blockcount;
}
/*
* Otherwise *last_block is already the right answer.
*/
return 0;
}
STATIC int
xfs_bmap_last_extent(
struct xfs_trans *tp,
struct xfs_inode *ip,
int whichfork,
struct xfs_bmbt_irec *rec,
int *is_empty)
{
struct xfs_ifork *ifp = XFS_IFORK_PTR(ip, whichfork);
int error;
int nextents;
if (!(ifp->if_flags & XFS_IFEXTENTS)) {
error = xfs_iread_extents(tp, ip, whichfork);
if (error)
return error;
}
nextents = ifp->if_bytes / sizeof(xfs_bmbt_rec_t);
if (nextents == 0) {
*is_empty = 1;
return 0;
}
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, nextents - 1), rec);
*is_empty = 0;
return 0;
}
/*
* Check the last inode extent to determine whether this allocation will result
* in blocks being allocated at the end of the file. When we allocate new data
* blocks at the end of the file which do not start at the previous data block,
* we will try to align the new blocks at stripe unit boundaries.
*
* Returns 0 in bma->aeof if the file (fork) is empty as any new write will be
* at, or past the EOF.
*/
STATIC int
xfs_bmap_isaeof(
struct xfs_bmalloca *bma,
int whichfork)
{
struct xfs_bmbt_irec rec;
int is_empty;
int error;
bma->aeof = 0;
error = xfs_bmap_last_extent(NULL, bma->ip, whichfork, &rec,
&is_empty);
if (error || is_empty)
return error;
/*
* Check if we are allocation or past the last extent, or at least into
* the last delayed allocated extent.
*/
bma->aeof = bma->offset >= rec.br_startoff + rec.br_blockcount ||
(bma->offset >= rec.br_startoff &&
isnullstartblock(rec.br_startblock));
return 0;
}
/*
* Check if the endoff is outside the last extent. If so the caller will grow
* the allocation to a stripe unit boundary. All offsets are considered outside
* the end of file for an empty fork, so 1 is returned in *eof in that case.
*/
int
xfs_bmap_eof(
struct xfs_inode *ip,
xfs_fileoff_t endoff,
int whichfork,
int *eof)
{
struct xfs_bmbt_irec rec;
int error;
error = xfs_bmap_last_extent(NULL, ip, whichfork, &rec, eof);
if (error || *eof)
return error;
*eof = endoff >= rec.br_startoff + rec.br_blockcount;
return 0;
}
/*
* Returns the file-relative block number of the first block past eof in
* the file. This is not based on i_size, it is based on the extent records.
* Returns 0 for local files, as they do not have extent records.
*/
int
xfs_bmap_last_offset(
struct xfs_trans *tp,
struct xfs_inode *ip,
xfs_fileoff_t *last_block,
int whichfork)
{
struct xfs_bmbt_irec rec;
int is_empty;
int error;
*last_block = 0;
if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL)
return 0;
if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
return XFS_ERROR(EIO);
error = xfs_bmap_last_extent(NULL, ip, whichfork, &rec, &is_empty);
if (error || is_empty)
return error;
*last_block = rec.br_startoff + rec.br_blockcount;
return 0;
}
/*
* Returns whether the selected fork of the inode has exactly one
* block or not. For the data fork we check this matches di_size,
* implying the file's range is 0..bsize-1.
*/
int /* 1=>1 block, 0=>otherwise */
xfs_bmap_one_block(
xfs_inode_t *ip, /* incore inode */
int whichfork) /* data or attr fork */
{
xfs_bmbt_rec_host_t *ep; /* ptr to fork's extent */
xfs_ifork_t *ifp; /* inode fork pointer */
int rval; /* return value */
xfs_bmbt_irec_t s; /* internal version of extent */
#ifndef DEBUG
if (whichfork == XFS_DATA_FORK)
return XFS_ISIZE(ip) == ip->i_mount->m_sb.sb_blocksize;
#endif /* !DEBUG */
if (XFS_IFORK_NEXTENTS(ip, whichfork) != 1)
return 0;
if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
return 0;
ifp = XFS_IFORK_PTR(ip, whichfork);
ASSERT(ifp->if_flags & XFS_IFEXTENTS);
ep = xfs_iext_get_ext(ifp, 0);
xfs_bmbt_get_all(ep, &s);
rval = s.br_startoff == 0 && s.br_blockcount == 1;
if (rval && whichfork == XFS_DATA_FORK)
ASSERT(XFS_ISIZE(ip) == ip->i_mount->m_sb.sb_blocksize);
return rval;
}
STATIC int
xfs_bmap_sanity_check(
struct xfs_mount *mp,
struct xfs_buf *bp,
int level)
{
struct xfs_btree_block *block = XFS_BUF_TO_BLOCK(bp);
if (block->bb_magic != cpu_to_be32(XFS_BMAP_MAGIC) ||
be16_to_cpu(block->bb_level) != level ||
be16_to_cpu(block->bb_numrecs) == 0 ||
be16_to_cpu(block->bb_numrecs) > mp->m_bmap_dmxr[level != 0])
return 0;
return 1;
}
/*
* Read in the extents to if_extents.
* All inode fields are set up by caller, we just traverse the btree
* and copy the records in. If the file system cannot contain unwritten
* extents, the records are checked for no "state" flags.
*/
int /* error */
xfs_bmap_read_extents(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode */
int whichfork) /* data or attr fork */
{
struct xfs_btree_block *block; /* current btree block */
xfs_fsblock_t bno; /* block # of "block" */
xfs_buf_t *bp; /* buffer for "block" */
int error; /* error return value */
xfs_exntfmt_t exntf; /* XFS_EXTFMT_NOSTATE, if checking */
xfs_extnum_t i, j; /* index into the extents list */
xfs_ifork_t *ifp; /* fork structure */
int level; /* btree level, for checking */
xfs_mount_t *mp; /* file system mount structure */
__be64 *pp; /* pointer to block address */
/* REFERENCED */
xfs_extnum_t room; /* number of entries there's room for */
bno = NULLFSBLOCK;
mp = ip->i_mount;
ifp = XFS_IFORK_PTR(ip, whichfork);
exntf = (whichfork != XFS_DATA_FORK) ? XFS_EXTFMT_NOSTATE :
XFS_EXTFMT_INODE(ip);
block = ifp->if_broot;
/*
* Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out.
*/
level = be16_to_cpu(block->bb_level);
ASSERT(level > 0);
pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, 1, ifp->if_broot_bytes);
bno = be64_to_cpu(*pp);
ASSERT(bno != NULLDFSBNO);
ASSERT(XFS_FSB_TO_AGNO(mp, bno) < mp->m_sb.sb_agcount);
ASSERT(XFS_FSB_TO_AGBNO(mp, bno) < mp->m_sb.sb_agblocks);
/*
* Go down the tree until leaf level is reached, following the first
* pointer (leftmost) at each level.
*/
while (level-- > 0) {
if ((error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp,
XFS_BMAP_BTREE_REF)))
return error;
block = XFS_BUF_TO_BLOCK(bp);
XFS_WANT_CORRUPTED_GOTO(
xfs_bmap_sanity_check(mp, bp, level),
error0);
if (level == 0)
break;
pp = XFS_BMBT_PTR_ADDR(mp, block, 1, mp->m_bmap_dmxr[1]);
bno = be64_to_cpu(*pp);
XFS_WANT_CORRUPTED_GOTO(XFS_FSB_SANITY_CHECK(mp, bno), error0);
xfs_trans_brelse(tp, bp);
}
/*
* Here with bp and block set to the leftmost leaf node in the tree.
*/
room = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
i = 0;
/*
* Loop over all leaf nodes. Copy information to the extent records.
*/
for (;;) {
xfs_bmbt_rec_t *frp;
xfs_fsblock_t nextbno;
xfs_extnum_t num_recs;
xfs_extnum_t start;
num_recs = xfs_btree_get_numrecs(block);
if (unlikely(i + num_recs > room)) {
ASSERT(i + num_recs <= room);
xfs_warn(ip->i_mount,
"corrupt dinode %Lu, (btree extents).",
(unsigned long long) ip->i_ino);
XFS_CORRUPTION_ERROR("xfs_bmap_read_extents(1)",
XFS_ERRLEVEL_LOW, ip->i_mount, block);
goto error0;
}
XFS_WANT_CORRUPTED_GOTO(
xfs_bmap_sanity_check(mp, bp, 0),
error0);
/*
* Read-ahead the next leaf block, if any.
*/
nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
if (nextbno != NULLFSBLOCK)
xfs_btree_reada_bufl(mp, nextbno, 1);
/*
* Copy records into the extent records.
*/
frp = XFS_BMBT_REC_ADDR(mp, block, 1);
start = i;
for (j = 0; j < num_recs; j++, i++, frp++) {
xfs_bmbt_rec_host_t *trp = xfs_iext_get_ext(ifp, i);
trp->l0 = be64_to_cpu(frp->l0);
trp->l1 = be64_to_cpu(frp->l1);
}
if (exntf == XFS_EXTFMT_NOSTATE) {
/*
* Check all attribute bmap btree records and
* any "older" data bmap btree records for a
* set bit in the "extent flag" position.
*/
if (unlikely(xfs_check_nostate_extents(ifp,
start, num_recs))) {
XFS_ERROR_REPORT("xfs_bmap_read_extents(2)",
XFS_ERRLEVEL_LOW,
ip->i_mount);
goto error0;
}
}
xfs_trans_brelse(tp, bp);
bno = nextbno;
/*
* If we've reached the end, stop.
*/
if (bno == NULLFSBLOCK)
break;
if ((error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp,
XFS_BMAP_BTREE_REF)))
return error;
block = XFS_BUF_TO_BLOCK(bp);
}
ASSERT(i == (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t)));
ASSERT(i == XFS_IFORK_NEXTENTS(ip, whichfork));
XFS_BMAP_TRACE_EXLIST(ip, i, whichfork);
return 0;
error0:
xfs_trans_brelse(tp, bp);
return XFS_ERROR(EFSCORRUPTED);
}
#ifdef DEBUG
/*
* Add bmap trace insert entries for all the contents of the extent records.
*/
void
xfs_bmap_trace_exlist(
xfs_inode_t *ip, /* incore inode pointer */
xfs_extnum_t cnt, /* count of entries in the list */
int whichfork, /* data or attr fork */
unsigned long caller_ip)
{
xfs_extnum_t idx; /* extent record index */
xfs_ifork_t *ifp; /* inode fork pointer */
int state = 0;
if (whichfork == XFS_ATTR_FORK)
state |= BMAP_ATTRFORK;
ifp = XFS_IFORK_PTR(ip, whichfork);
ASSERT(cnt == (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t)));
for (idx = 0; idx < cnt; idx++)
trace_xfs_extlist(ip, idx, whichfork, caller_ip);
}
/*
* Validate that the bmbt_irecs being returned from bmapi are valid
* given the callers original parameters. Specifically check the
* ranges of the returned irecs to ensure that they only extent beyond
* the given parameters if the XFS_BMAPI_ENTIRE flag was set.
*/
STATIC void
xfs_bmap_validate_ret(
xfs_fileoff_t bno,
xfs_filblks_t len,
int flags,
xfs_bmbt_irec_t *mval,
int nmap,
int ret_nmap)
{
int i; /* index to map values */
ASSERT(ret_nmap <= nmap);
for (i = 0; i < ret_nmap; i++) {
ASSERT(mval[i].br_blockcount > 0);
if (!(flags & XFS_BMAPI_ENTIRE)) {
ASSERT(mval[i].br_startoff >= bno);
ASSERT(mval[i].br_blockcount <= len);
ASSERT(mval[i].br_startoff + mval[i].br_blockcount <=
bno + len);
} else {
ASSERT(mval[i].br_startoff < bno + len);
ASSERT(mval[i].br_startoff + mval[i].br_blockcount >
bno);
}
ASSERT(i == 0 ||
mval[i - 1].br_startoff + mval[i - 1].br_blockcount ==
mval[i].br_startoff);
ASSERT(mval[i].br_startblock != DELAYSTARTBLOCK &&
mval[i].br_startblock != HOLESTARTBLOCK);
ASSERT(mval[i].br_state == XFS_EXT_NORM ||
mval[i].br_state == XFS_EXT_UNWRITTEN);
}
}
#endif /* DEBUG */
/*
* Trim the returned map to the required bounds
*/
STATIC void
xfs_bmapi_trim_map(
struct xfs_bmbt_irec *mval,
struct xfs_bmbt_irec *got,
xfs_fileoff_t *bno,
xfs_filblks_t len,
xfs_fileoff_t obno,
xfs_fileoff_t end,
int n,
int flags)
{
if ((flags & XFS_BMAPI_ENTIRE) ||
got->br_startoff + got->br_blockcount <= obno) {
*mval = *got;
if (isnullstartblock(got->br_startblock))
mval->br_startblock = DELAYSTARTBLOCK;
return;
}
if (obno > *bno)
*bno = obno;
ASSERT((*bno >= obno) || (n == 0));
ASSERT(*bno < end);
mval->br_startoff = *bno;
if (isnullstartblock(got->br_startblock))
mval->br_startblock = DELAYSTARTBLOCK;
else
mval->br_startblock = got->br_startblock +
(*bno - got->br_startoff);
/*
* Return the minimum of what we got and what we asked for for
* the length. We can use the len variable here because it is
* modified below and we could have been there before coming
* here if the first part of the allocation didn't overlap what
* was asked for.
*/
mval->br_blockcount = XFS_FILBLKS_MIN(end - *bno,
got->br_blockcount - (*bno - got->br_startoff));
mval->br_state = got->br_state;
ASSERT(mval->br_blockcount <= len);
return;
}
/*
* Update and validate the extent map to return
*/
STATIC void
xfs_bmapi_update_map(
struct xfs_bmbt_irec **map,
xfs_fileoff_t *bno,
xfs_filblks_t *len,
xfs_fileoff_t obno,
xfs_fileoff_t end,
int *n,
int flags)
{
xfs_bmbt_irec_t *mval = *map;
ASSERT((flags & XFS_BMAPI_ENTIRE) ||
((mval->br_startoff + mval->br_blockcount) <= end));
ASSERT((flags & XFS_BMAPI_ENTIRE) || (mval->br_blockcount <= *len) ||
(mval->br_startoff < obno));
*bno = mval->br_startoff + mval->br_blockcount;
*len = end - *bno;
if (*n > 0 && mval->br_startoff == mval[-1].br_startoff) {
/* update previous map with new information */
ASSERT(mval->br_startblock == mval[-1].br_startblock);
ASSERT(mval->br_blockcount > mval[-1].br_blockcount);
ASSERT(mval->br_state == mval[-1].br_state);
mval[-1].br_blockcount = mval->br_blockcount;
mval[-1].br_state = mval->br_state;
} else if (*n > 0 && mval->br_startblock != DELAYSTARTBLOCK &&
mval[-1].br_startblock != DELAYSTARTBLOCK &&
mval[-1].br_startblock != HOLESTARTBLOCK &&
mval->br_startblock == mval[-1].br_startblock +
mval[-1].br_blockcount &&
((flags & XFS_BMAPI_IGSTATE) ||
mval[-1].br_state == mval->br_state)) {
ASSERT(mval->br_startoff ==
mval[-1].br_startoff + mval[-1].br_blockcount);
mval[-1].br_blockcount += mval->br_blockcount;
} else if (*n > 0 &&
mval->br_startblock == DELAYSTARTBLOCK &&
mval[-1].br_startblock == DELAYSTARTBLOCK &&
mval->br_startoff ==
mval[-1].br_startoff + mval[-1].br_blockcount) {
mval[-1].br_blockcount += mval->br_blockcount;
mval[-1].br_state = mval->br_state;
} else if (!((*n == 0) &&
((mval->br_startoff + mval->br_blockcount) <=
obno))) {
mval++;
(*n)++;
}
*map = mval;
}
/*
* Map file blocks to filesystem blocks without allocation.
*/
int
xfs_bmapi_read(
struct xfs_inode *ip,
xfs_fileoff_t bno,
xfs_filblks_t len,
struct xfs_bmbt_irec *mval,
int *nmap,
int flags)
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_ifork *ifp;
struct xfs_bmbt_irec got;
struct xfs_bmbt_irec prev;
xfs_fileoff_t obno;
xfs_fileoff_t end;
xfs_extnum_t lastx;
int error;
int eof;
int n = 0;
int whichfork = (flags & XFS_BMAPI_ATTRFORK) ?
XFS_ATTR_FORK : XFS_DATA_FORK;
ASSERT(*nmap >= 1);
ASSERT(!(flags & ~(XFS_BMAPI_ATTRFORK|XFS_BMAPI_ENTIRE|
XFS_BMAPI_IGSTATE)));
if (unlikely(XFS_TEST_ERROR(
(XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE),
mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) {
XFS_ERROR_REPORT("xfs_bmapi_read", XFS_ERRLEVEL_LOW, mp);
return XFS_ERROR(EFSCORRUPTED);
}
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
XFS_STATS_INC(xs_blk_mapr);
ifp = XFS_IFORK_PTR(ip, whichfork);
if (!(ifp->if_flags & XFS_IFEXTENTS)) {
error = xfs_iread_extents(NULL, ip, whichfork);
if (error)
return error;
}
xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got, &prev);
end = bno + len;
obno = bno;
while (bno < end && n < *nmap) {
/* Reading past eof, act as though there's a hole up to end. */
if (eof)
got.br_startoff = end;
if (got.br_startoff > bno) {
/* Reading in a hole. */
mval->br_startoff = bno;
mval->br_startblock = HOLESTARTBLOCK;
mval->br_blockcount =
XFS_FILBLKS_MIN(len, got.br_startoff - bno);
mval->br_state = XFS_EXT_NORM;
bno += mval->br_blockcount;
len -= mval->br_blockcount;
mval++;
n++;
continue;
}
/* set up the extent map to return. */
xfs_bmapi_trim_map(mval, &got, &bno, len, obno, end, n, flags);
xfs_bmapi_update_map(&mval, &bno, &len, obno, end, &n, flags);
/* If we're done, stop now. */
if (bno >= end || n >= *nmap)
break;
/* Else go on to the next record. */
if (++lastx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t))
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, lastx), &got);
else
eof = 1;
}
*nmap = n;
return 0;
}
STATIC int
xfs_bmapi_reserve_delalloc(
struct xfs_inode *ip,
xfs_fileoff_t aoff,
xfs_filblks_t len,
struct xfs_bmbt_irec *got,
struct xfs_bmbt_irec *prev,
xfs_extnum_t *lastx,
int eof)
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_ifork *ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
xfs_extlen_t alen;
xfs_extlen_t indlen;
char rt = XFS_IS_REALTIME_INODE(ip);
xfs_extlen_t extsz;
int error;
alen = XFS_FILBLKS_MIN(len, MAXEXTLEN);
if (!eof)
alen = XFS_FILBLKS_MIN(alen, got->br_startoff - aoff);
/* Figure out the extent size, adjust alen */
extsz = xfs_get_extsz_hint(ip);
if (extsz) {
/*
* Make sure we don't exceed a single extent length when we
* align the extent by reducing length we are going to
* allocate by the maximum amount extent size aligment may
* require.
*/
alen = XFS_FILBLKS_MIN(len, MAXEXTLEN - (2 * extsz - 1));
error = xfs_bmap_extsize_align(mp, got, prev, extsz, rt, eof,
1, 0, &aoff, &alen);
ASSERT(!error);
}
if (rt)
extsz = alen / mp->m_sb.sb_rextsize;
/*
* Make a transaction-less quota reservation for delayed allocation
* blocks. This number gets adjusted later. We return if we haven't
* allocated blocks already inside this loop.
*/
error = xfs_trans_reserve_quota_nblks(NULL, ip, (long)alen, 0,
rt ? XFS_QMOPT_RES_RTBLKS : XFS_QMOPT_RES_REGBLKS);
if (error)
return error;
/*
* Split changing sb for alen and indlen since they could be coming
* from different places.
*/
indlen = (xfs_extlen_t)xfs_bmap_worst_indlen(ip, alen);
ASSERT(indlen > 0);
if (rt) {
error = xfs_mod_incore_sb(mp, XFS_SBS_FREXTENTS,
-((int64_t)extsz), 0);
} else {
error = xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS,
-((int64_t)alen), 0);
}
if (error)
goto out_unreserve_quota;
error = xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS,
-((int64_t)indlen), 0);
if (error)
goto out_unreserve_blocks;
ip->i_delayed_blks += alen;
got->br_startoff = aoff;
got->br_startblock = nullstartblock(indlen);
got->br_blockcount = alen;
got->br_state = XFS_EXT_NORM;
xfs_bmap_add_extent_hole_delay(ip, lastx, got);
/*
* Update our extent pointer, given that xfs_bmap_add_extent_hole_delay
* might have merged it into one of the neighbouring ones.
*/
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, *lastx), got);
ASSERT(got->br_startoff <= aoff);
ASSERT(got->br_startoff + got->br_blockcount >= aoff + alen);
ASSERT(isnullstartblock(got->br_startblock));
ASSERT(got->br_state == XFS_EXT_NORM);
return 0;
out_unreserve_blocks:
if (rt)
xfs_mod_incore_sb(mp, XFS_SBS_FREXTENTS, extsz, 0);
else
xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS, alen, 0);
out_unreserve_quota:
if (XFS_IS_QUOTA_ON(mp))
xfs_trans_unreserve_quota_nblks(NULL, ip, alen, 0, rt ?
XFS_QMOPT_RES_RTBLKS : XFS_QMOPT_RES_REGBLKS);
return error;
}
/*
* Map file blocks to filesystem blocks, adding delayed allocations as needed.
*/
int
xfs_bmapi_delay(
struct xfs_inode *ip, /* incore inode */
xfs_fileoff_t bno, /* starting file offs. mapped */
xfs_filblks_t len, /* length to map in file */
struct xfs_bmbt_irec *mval, /* output: map values */
int *nmap, /* i/o: mval size/count */
int flags) /* XFS_BMAPI_... */
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_ifork *ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
struct xfs_bmbt_irec got; /* current file extent record */
struct xfs_bmbt_irec prev; /* previous file extent record */
xfs_fileoff_t obno; /* old block number (offset) */
xfs_fileoff_t end; /* end of mapped file region */
xfs_extnum_t lastx; /* last useful extent number */
int eof; /* we've hit the end of extents */
int n = 0; /* current extent index */
int error = 0;
ASSERT(*nmap >= 1);
ASSERT(*nmap <= XFS_BMAP_MAX_NMAP);
ASSERT(!(flags & ~XFS_BMAPI_ENTIRE));
if (unlikely(XFS_TEST_ERROR(
(XFS_IFORK_FORMAT(ip, XFS_DATA_FORK) != XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_FORMAT(ip, XFS_DATA_FORK) != XFS_DINODE_FMT_BTREE),
mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) {
XFS_ERROR_REPORT("xfs_bmapi_delay", XFS_ERRLEVEL_LOW, mp);
return XFS_ERROR(EFSCORRUPTED);
}
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
XFS_STATS_INC(xs_blk_mapw);
if (!(ifp->if_flags & XFS_IFEXTENTS)) {
error = xfs_iread_extents(NULL, ip, XFS_DATA_FORK);
if (error)
return error;
}
xfs_bmap_search_extents(ip, bno, XFS_DATA_FORK, &eof, &lastx, &got, &prev);
end = bno + len;
obno = bno;
while (bno < end && n < *nmap) {
if (eof || got.br_startoff > bno) {
error = xfs_bmapi_reserve_delalloc(ip, bno, len, &got,
&prev, &lastx, eof);
if (error) {
if (n == 0) {
*nmap = 0;
return error;
}
break;
}
}
/* set up the extent map to return. */
xfs_bmapi_trim_map(mval, &got, &bno, len, obno, end, n, flags);
xfs_bmapi_update_map(&mval, &bno, &len, obno, end, &n, flags);
/* If we're done, stop now. */
if (bno >= end || n >= *nmap)
break;
/* Else go on to the next record. */
prev = got;
if (++lastx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t))
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, lastx), &got);
else
eof = 1;
}
*nmap = n;
return 0;
}
STATIC int
xfs_bmapi_allocate(
struct xfs_bmalloca *bma,
int flags)
{
struct xfs_mount *mp = bma->ip->i_mount;
int whichfork = (flags & XFS_BMAPI_ATTRFORK) ?
XFS_ATTR_FORK : XFS_DATA_FORK;
struct xfs_ifork *ifp = XFS_IFORK_PTR(bma->ip, whichfork);
int tmp_logflags = 0;
int error;
int rt;
ASSERT(bma->length > 0);
rt = (whichfork == XFS_DATA_FORK) && XFS_IS_REALTIME_INODE(bma->ip);
/*
* For the wasdelay case, we could also just allocate the stuff asked
* for in this bmap call but that wouldn't be as good.
*/
if (bma->wasdel) {
bma->length = (xfs_extlen_t)bma->got.br_blockcount;
bma->offset = bma->got.br_startoff;
if (bma->idx != NULLEXTNUM && bma->idx) {
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx - 1),
&bma->prev);
}
} else {
bma->length = XFS_FILBLKS_MIN(bma->length, MAXEXTLEN);
if (!bma->eof)
bma->length = XFS_FILBLKS_MIN(bma->length,
bma->got.br_startoff - bma->offset);
}
/*
* Indicate if this is the first user data in the file, or just any
* user data.
*/
if (!(flags & XFS_BMAPI_METADATA)) {
bma->userdata = (bma->offset == 0) ?
XFS_ALLOC_INITIAL_USER_DATA : XFS_ALLOC_USERDATA;
}
bma->minlen = (flags & XFS_BMAPI_CONTIG) ? bma->length : 1;
/*
* Only want to do the alignment at the eof if it is userdata and
* allocation length is larger than a stripe unit.
*/
if (mp->m_dalign && bma->length >= mp->m_dalign &&
!(flags & XFS_BMAPI_METADATA) && whichfork == XFS_DATA_FORK) {
error = xfs_bmap_isaeof(bma, whichfork);
if (error)
return error;
}
error = xfs_bmap_alloc(bma);
if (error)
return error;
if (bma->flist->xbf_low)
bma->minleft = 0;
if (bma->cur)
bma->cur->bc_private.b.firstblock = *bma->firstblock;
if (bma->blkno == NULLFSBLOCK)
return 0;
if ((ifp->if_flags & XFS_IFBROOT) && !bma->cur) {
bma->cur = xfs_bmbt_init_cursor(mp, bma->tp, bma->ip, whichfork);
bma->cur->bc_private.b.firstblock = *bma->firstblock;
bma->cur->bc_private.b.flist = bma->flist;
}
/*
* Bump the number of extents we've allocated
* in this call.
*/
bma->nallocs++;
if (bma->cur)
bma->cur->bc_private.b.flags =
bma->wasdel ? XFS_BTCUR_BPRV_WASDEL : 0;
bma->got.br_startoff = bma->offset;
bma->got.br_startblock = bma->blkno;
bma->got.br_blockcount = bma->length;
bma->got.br_state = XFS_EXT_NORM;
/*
* A wasdelay extent has been initialized, so shouldn't be flagged
* as unwritten.
*/
if (!bma->wasdel && (flags & XFS_BMAPI_PREALLOC) &&
xfs_sb_version_hasextflgbit(&mp->m_sb))
bma->got.br_state = XFS_EXT_UNWRITTEN;
if (bma->wasdel)
error = xfs_bmap_add_extent_delay_real(bma);
else
error = xfs_bmap_add_extent_hole_real(bma, whichfork);
bma->logflags |= tmp_logflags;
if (error)
return error;
/*
* Update our extent pointer, given that xfs_bmap_add_extent_delay_real
* or xfs_bmap_add_extent_hole_real might have merged it into one of
* the neighbouring ones.
*/
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx), &bma->got);
ASSERT(bma->got.br_startoff <= bma->offset);
ASSERT(bma->got.br_startoff + bma->got.br_blockcount >=
bma->offset + bma->length);
ASSERT(bma->got.br_state == XFS_EXT_NORM ||
bma->got.br_state == XFS_EXT_UNWRITTEN);
return 0;
}
STATIC int
xfs_bmapi_convert_unwritten(
struct xfs_bmalloca *bma,
struct xfs_bmbt_irec *mval,
xfs_filblks_t len,
int flags)
{
int whichfork = (flags & XFS_BMAPI_ATTRFORK) ?
XFS_ATTR_FORK : XFS_DATA_FORK;
struct xfs_ifork *ifp = XFS_IFORK_PTR(bma->ip, whichfork);
int tmp_logflags = 0;
int error;
/* check if we need to do unwritten->real conversion */
if (mval->br_state == XFS_EXT_UNWRITTEN &&
(flags & XFS_BMAPI_PREALLOC))
return 0;
/* check if we need to do real->unwritten conversion */
if (mval->br_state == XFS_EXT_NORM &&
(flags & (XFS_BMAPI_PREALLOC | XFS_BMAPI_CONVERT)) !=
(XFS_BMAPI_PREALLOC | XFS_BMAPI_CONVERT))
return 0;
/*
* Modify (by adding) the state flag, if writing.
*/
ASSERT(mval->br_blockcount <= len);
if ((ifp->if_flags & XFS_IFBROOT) && !bma->cur) {
bma->cur = xfs_bmbt_init_cursor(bma->ip->i_mount, bma->tp,
bma->ip, whichfork);
bma->cur->bc_private.b.firstblock = *bma->firstblock;
bma->cur->bc_private.b.flist = bma->flist;
}
mval->br_state = (mval->br_state == XFS_EXT_UNWRITTEN)
? XFS_EXT_NORM : XFS_EXT_UNWRITTEN;
error = xfs_bmap_add_extent_unwritten_real(bma->tp, bma->ip, &bma->idx,
&bma->cur, mval, bma->firstblock, bma->flist,
&tmp_logflags);
bma->logflags |= tmp_logflags;
if (error)
return error;
/*
* Update our extent pointer, given that
* xfs_bmap_add_extent_unwritten_real might have merged it into one
* of the neighbouring ones.
*/
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma->idx), &bma->got);
/*
* We may have combined previously unwritten space with written space,
* so generate another request.
*/
if (mval->br_blockcount < len)
return EAGAIN;
return 0;
}
/*
* Map file blocks to filesystem blocks, and allocate blocks or convert the
* extent state if necessary. Details behaviour is controlled by the flags
* parameter. Only allocates blocks from a single allocation group, to avoid
* locking problems.
*
* The returned value in "firstblock" from the first call in a transaction
* must be remembered and presented to subsequent calls in "firstblock".
* An upper bound for the number of blocks to be allocated is supplied to
* the first call in "total"; if no allocation group has that many free
* blocks then the call will fail (return NULLFSBLOCK in "firstblock").
*/
int
xfs_bmapi_write(
struct xfs_trans *tp, /* transaction pointer */
struct xfs_inode *ip, /* incore inode */
xfs_fileoff_t bno, /* starting file offs. mapped */
xfs_filblks_t len, /* length to map in file */
int flags, /* XFS_BMAPI_... */
xfs_fsblock_t *firstblock, /* first allocated block
controls a.g. for allocs */
xfs_extlen_t total, /* total blocks needed */
struct xfs_bmbt_irec *mval, /* output: map values */
int *nmap, /* i/o: mval size/count */
struct xfs_bmap_free *flist) /* i/o: list extents to free */
{
struct xfs_mount *mp = ip->i_mount;
struct xfs_ifork *ifp;
struct xfs_bmalloca bma = { 0 }; /* args for xfs_bmap_alloc */
xfs_fileoff_t end; /* end of mapped file region */
int eof; /* after the end of extents */
int error; /* error return */
int n; /* current extent index */
xfs_fileoff_t obno; /* old block number (offset) */
int whichfork; /* data or attr fork */
char inhole; /* current location is hole in file */
char wasdelay; /* old extent was delayed */
#ifdef DEBUG
xfs_fileoff_t orig_bno; /* original block number value */
int orig_flags; /* original flags arg value */
xfs_filblks_t orig_len; /* original value of len arg */
struct xfs_bmbt_irec *orig_mval; /* original value of mval */
int orig_nmap; /* original value of *nmap */
orig_bno = bno;
orig_len = len;
orig_flags = flags;
orig_mval = mval;
orig_nmap = *nmap;
#endif
ASSERT(*nmap >= 1);
ASSERT(*nmap <= XFS_BMAP_MAX_NMAP);
ASSERT(!(flags & XFS_BMAPI_IGSTATE));
ASSERT(tp != NULL);
ASSERT(len > 0);
whichfork = (flags & XFS_BMAPI_ATTRFORK) ?
XFS_ATTR_FORK : XFS_DATA_FORK;
if (unlikely(XFS_TEST_ERROR(
(XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_LOCAL),
mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) {
XFS_ERROR_REPORT("xfs_bmapi_write", XFS_ERRLEVEL_LOW, mp);
return XFS_ERROR(EFSCORRUPTED);
}
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
ifp = XFS_IFORK_PTR(ip, whichfork);
XFS_STATS_INC(xs_blk_mapw);
if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_LOCAL) {
error = xfs_bmap_local_to_extents(tp, ip, firstblock, total,
&bma.logflags, whichfork);
if (error)
goto error0;
}
if (*firstblock == NULLFSBLOCK) {
if (XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE)
bma.minleft = be16_to_cpu(ifp->if_broot->bb_level) + 1;
else
bma.minleft = 1;
} else {
bma.minleft = 0;
}
if (!(ifp->if_flags & XFS_IFEXTENTS)) {
error = xfs_iread_extents(tp, ip, whichfork);
if (error)
goto error0;
}
xfs_bmap_search_extents(ip, bno, whichfork, &eof, &bma.idx, &bma.got,
&bma.prev);
n = 0;
end = bno + len;
obno = bno;
bma.tp = tp;
bma.ip = ip;
bma.total = total;
bma.userdata = 0;
bma.flist = flist;
bma.firstblock = firstblock;
while (bno < end && n < *nmap) {
inhole = eof || bma.got.br_startoff > bno;
wasdelay = !inhole && isnullstartblock(bma.got.br_startblock);
/*
* First, deal with the hole before the allocated space
* that we found, if any.
*/
if (inhole || wasdelay) {
bma.eof = eof;
bma.conv = !!(flags & XFS_BMAPI_CONVERT);
bma.wasdel = wasdelay;
bma.offset = bno;
/*
* There's a 32/64 bit type mismatch between the
* allocation length request (which can be 64 bits in
* length) and the bma length request, which is
* xfs_extlen_t and therefore 32 bits. Hence we have to
* check for 32-bit overflows and handle them here.
*/
if (len > (xfs_filblks_t)MAXEXTLEN)
bma.length = MAXEXTLEN;
else
bma.length = len;
ASSERT(len > 0);
ASSERT(bma.length > 0);
error = xfs_bmapi_allocate(&bma, flags);
if (error)
goto error0;
if (bma.blkno == NULLFSBLOCK)
break;
}
/* Deal with the allocated space we found. */
xfs_bmapi_trim_map(mval, &bma.got, &bno, len, obno,
end, n, flags);
/* Execute unwritten extent conversion if necessary */
error = xfs_bmapi_convert_unwritten(&bma, mval, len, flags);
if (error == EAGAIN)
continue;
if (error)
goto error0;
/* update the extent map to return */
xfs_bmapi_update_map(&mval, &bno, &len, obno, end, &n, flags);
/*
* If we're done, stop now. Stop when we've allocated
* XFS_BMAP_MAX_NMAP extents no matter what. Otherwise
* the transaction may get too big.
*/
if (bno >= end || n >= *nmap || bma.nallocs >= *nmap)
break;
/* Else go on to the next record. */
bma.prev = bma.got;
if (++bma.idx < ifp->if_bytes / sizeof(xfs_bmbt_rec_t)) {
xfs_bmbt_get_all(xfs_iext_get_ext(ifp, bma.idx),
&bma.got);
} else
eof = 1;
}
*nmap = n;
/*
* Transform from btree to extents, give it cur.
*/
if (xfs_bmap_wants_extents(ip, whichfork)) {
int tmp_logflags = 0;
ASSERT(bma.cur);
error = xfs_bmap_btree_to_extents(tp, ip, bma.cur,
&tmp_logflags, whichfork);
bma.logflags |= tmp_logflags;
if (error)
goto error0;
}
ASSERT(XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE ||
XFS_IFORK_NEXTENTS(ip, whichfork) >
XFS_IFORK_MAXEXT(ip, whichfork));
error = 0;
error0:
/*
* Log everything. Do this after conversion, there's no point in
* logging the extent records if we've converted to btree format.
*/
if ((bma.logflags & xfs_ilog_fext(whichfork)) &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
bma.logflags &= ~xfs_ilog_fext(whichfork);
else if ((bma.logflags & xfs_ilog_fbroot(whichfork)) &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)
bma.logflags &= ~xfs_ilog_fbroot(whichfork);
/*
* Log whatever the flags say, even if error. Otherwise we might miss
* detecting a case where the data is changed, there's an error,
* and it's not logged so we don't shutdown when we should.
*/
if (bma.logflags)
xfs_trans_log_inode(tp, ip, bma.logflags);
if (bma.cur) {
if (!error) {
ASSERT(*firstblock == NULLFSBLOCK ||
XFS_FSB_TO_AGNO(mp, *firstblock) ==
XFS_FSB_TO_AGNO(mp,
bma.cur->bc_private.b.firstblock) ||
(flist->xbf_low &&
XFS_FSB_TO_AGNO(mp, *firstblock) <
XFS_FSB_TO_AGNO(mp,
bma.cur->bc_private.b.firstblock)));
*firstblock = bma.cur->bc_private.b.firstblock;
}
xfs_btree_del_cursor(bma.cur,
error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
}
if (!error)
xfs_bmap_validate_ret(orig_bno, orig_len, orig_flags, orig_mval,
orig_nmap, *nmap);
return error;
}
/*
* Unmap (remove) blocks from a file.
* If nexts is nonzero then the number of extents to remove is limited to
* that value. If not all extents in the block range can be removed then
* *done is set.
*/
int /* error */
xfs_bunmapi(
xfs_trans_t *tp, /* transaction pointer */
struct xfs_inode *ip, /* incore inode */
xfs_fileoff_t bno, /* starting offset to unmap */
xfs_filblks_t len, /* length to unmap in file */
int flags, /* misc flags */
xfs_extnum_t nexts, /* number of extents max */
xfs_fsblock_t *firstblock, /* first allocated block
controls a.g. for allocs */
xfs_bmap_free_t *flist, /* i/o: list extents to free */
int *done) /* set if not done yet */
{
xfs_btree_cur_t *cur; /* bmap btree cursor */
xfs_bmbt_irec_t del; /* extent being deleted */
int eof; /* is deleting at eof */
xfs_bmbt_rec_host_t *ep; /* extent record pointer */
int error; /* error return value */
xfs_extnum_t extno; /* extent number in list */
xfs_bmbt_irec_t got; /* current extent record */
xfs_ifork_t *ifp; /* inode fork pointer */
int isrt; /* freeing in rt area */
xfs_extnum_t lastx; /* last extent index used */
int logflags; /* transaction logging flags */
xfs_extlen_t mod; /* rt extent offset */
xfs_mount_t *mp; /* mount structure */
xfs_extnum_t nextents; /* number of file extents */
xfs_bmbt_irec_t prev; /* previous extent record */
xfs_fileoff_t start; /* first file offset deleted */
int tmp_logflags; /* partial logging flags */
int wasdel; /* was a delayed alloc extent */
int whichfork; /* data or attribute fork */
xfs_fsblock_t sum;
trace_xfs_bunmap(ip, bno, len, flags, _RET_IP_);
whichfork = (flags & XFS_BMAPI_ATTRFORK) ?
XFS_ATTR_FORK : XFS_DATA_FORK;
ifp = XFS_IFORK_PTR(ip, whichfork);
if (unlikely(
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)) {
XFS_ERROR_REPORT("xfs_bunmapi", XFS_ERRLEVEL_LOW,
ip->i_mount);
return XFS_ERROR(EFSCORRUPTED);
}
mp = ip->i_mount;
if (XFS_FORCED_SHUTDOWN(mp))
return XFS_ERROR(EIO);
ASSERT(len > 0);
ASSERT(nexts >= 0);
if (!(ifp->if_flags & XFS_IFEXTENTS) &&
(error = xfs_iread_extents(tp, ip, whichfork)))
return error;
nextents = ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t);
if (nextents == 0) {
*done = 1;
return 0;
}
XFS_STATS_INC(xs_blk_unmap);
isrt = (whichfork == XFS_DATA_FORK) && XFS_IS_REALTIME_INODE(ip);
start = bno;
bno = start + len - 1;
ep = xfs_bmap_search_extents(ip, bno, whichfork, &eof, &lastx, &got,
&prev);
/*
* Check to see if the given block number is past the end of the
* file, back up to the last block if so...
*/
if (eof) {
ep = xfs_iext_get_ext(ifp, --lastx);
xfs_bmbt_get_all(ep, &got);
bno = got.br_startoff + got.br_blockcount - 1;
}
logflags = 0;
if (ifp->if_flags & XFS_IFBROOT) {
ASSERT(XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_BTREE);
cur = xfs_bmbt_init_cursor(mp, tp, ip, whichfork);
cur->bc_private.b.firstblock = *firstblock;
cur->bc_private.b.flist = flist;
cur->bc_private.b.flags = 0;
} else
cur = NULL;
if (isrt) {
/*
* Synchronize by locking the bitmap inode.
*/
xfs_ilock(mp->m_rbmip, XFS_ILOCK_EXCL);
xfs_trans_ijoin(tp, mp->m_rbmip, XFS_ILOCK_EXCL);
}
extno = 0;
while (bno != (xfs_fileoff_t)-1 && bno >= start && lastx >= 0 &&
(nexts == 0 || extno < nexts)) {
/*
* Is the found extent after a hole in which bno lives?
* Just back up to the previous extent, if so.
*/
if (got.br_startoff > bno) {
if (--lastx < 0)
break;
ep = xfs_iext_get_ext(ifp, lastx);
xfs_bmbt_get_all(ep, &got);
}
/*
* Is the last block of this extent before the range
* we're supposed to delete? If so, we're done.
*/
bno = XFS_FILEOFF_MIN(bno,
got.br_startoff + got.br_blockcount - 1);
if (bno < start)
break;
/*
* Then deal with the (possibly delayed) allocated space
* we found.
*/
ASSERT(ep != NULL);
del = got;
wasdel = isnullstartblock(del.br_startblock);
if (got.br_startoff < start) {
del.br_startoff = start;
del.br_blockcount -= start - got.br_startoff;
if (!wasdel)
del.br_startblock += start - got.br_startoff;
}
if (del.br_startoff + del.br_blockcount > bno + 1)
del.br_blockcount = bno + 1 - del.br_startoff;
sum = del.br_startblock + del.br_blockcount;
if (isrt &&
(mod = do_mod(sum, mp->m_sb.sb_rextsize))) {
/*
* Realtime extent not lined up at the end.
* The extent could have been split into written
* and unwritten pieces, or we could just be
* unmapping part of it. But we can't really
* get rid of part of a realtime extent.
*/
if (del.br_state == XFS_EXT_UNWRITTEN ||
!xfs_sb_version_hasextflgbit(&mp->m_sb)) {
/*
* This piece is unwritten, or we're not
* using unwritten extents. Skip over it.
*/
ASSERT(bno >= mod);
bno -= mod > del.br_blockcount ?
del.br_blockcount : mod;
if (bno < got.br_startoff) {
if (--lastx >= 0)
xfs_bmbt_get_all(xfs_iext_get_ext(
ifp, lastx), &got);
}
continue;
}
/*
* It's written, turn it unwritten.
* This is better than zeroing it.
*/
ASSERT(del.br_state == XFS_EXT_NORM);
ASSERT(xfs_trans_get_block_res(tp) > 0);
/*
* If this spans a realtime extent boundary,
* chop it back to the start of the one we end at.
*/
if (del.br_blockcount > mod) {
del.br_startoff += del.br_blockcount - mod;
del.br_startblock += del.br_blockcount - mod;
del.br_blockcount = mod;
}
del.br_state = XFS_EXT_UNWRITTEN;
error = xfs_bmap_add_extent_unwritten_real(tp, ip,
&lastx, &cur, &del, firstblock, flist,
&logflags);
if (error)
goto error0;
goto nodelete;
}
if (isrt && (mod = do_mod(del.br_startblock, mp->m_sb.sb_rextsize))) {
/*
* Realtime extent is lined up at the end but not
* at the front. We'll get rid of full extents if
* we can.
*/
mod = mp->m_sb.sb_rextsize - mod;
if (del.br_blockcount > mod) {
del.br_blockcount -= mod;
del.br_startoff += mod;
del.br_startblock += mod;
} else if ((del.br_startoff == start &&
(del.br_state == XFS_EXT_UNWRITTEN ||
xfs_trans_get_block_res(tp) == 0)) ||
!xfs_sb_version_hasextflgbit(&mp->m_sb)) {
/*
* Can't make it unwritten. There isn't
* a full extent here so just skip it.
*/
ASSERT(bno >= del.br_blockcount);
bno -= del.br_blockcount;
if (got.br_startoff > bno) {
if (--lastx >= 0) {
ep = xfs_iext_get_ext(ifp,
lastx);
xfs_bmbt_get_all(ep, &got);
}
}
continue;
} else if (del.br_state == XFS_EXT_UNWRITTEN) {
/*
* This one is already unwritten.
* It must have a written left neighbor.
* Unwrite the killed part of that one and
* try again.
*/
ASSERT(lastx > 0);
xfs_bmbt_get_all(xfs_iext_get_ext(ifp,
lastx - 1), &prev);
ASSERT(prev.br_state == XFS_EXT_NORM);
ASSERT(!isnullstartblock(prev.br_startblock));
ASSERT(del.br_startblock ==
prev.br_startblock + prev.br_blockcount);
if (prev.br_startoff < start) {
mod = start - prev.br_startoff;
prev.br_blockcount -= mod;
prev.br_startblock += mod;
prev.br_startoff = start;
}
prev.br_state = XFS_EXT_UNWRITTEN;
lastx--;
error = xfs_bmap_add_extent_unwritten_real(tp,
ip, &lastx, &cur, &prev,
firstblock, flist, &logflags);
if (error)
goto error0;
goto nodelete;
} else {
ASSERT(del.br_state == XFS_EXT_NORM);
del.br_state = XFS_EXT_UNWRITTEN;
error = xfs_bmap_add_extent_unwritten_real(tp,
ip, &lastx, &cur, &del,
firstblock, flist, &logflags);
if (error)
goto error0;
goto nodelete;
}
}
if (wasdel) {
ASSERT(startblockval(del.br_startblock) > 0);
/* Update realtime/data freespace, unreserve quota */
if (isrt) {
xfs_filblks_t rtexts;
rtexts = XFS_FSB_TO_B(mp, del.br_blockcount);
do_div(rtexts, mp->m_sb.sb_rextsize);
xfs_mod_incore_sb(mp, XFS_SBS_FREXTENTS,
(int64_t)rtexts, 0);
(void)xfs_trans_reserve_quota_nblks(NULL,
ip, -((long)del.br_blockcount), 0,
XFS_QMOPT_RES_RTBLKS);
} else {
xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS,
(int64_t)del.br_blockcount, 0);
(void)xfs_trans_reserve_quota_nblks(NULL,
ip, -((long)del.br_blockcount), 0,
XFS_QMOPT_RES_REGBLKS);
}
ip->i_delayed_blks -= del.br_blockcount;
if (cur)
cur->bc_private.b.flags |=
XFS_BTCUR_BPRV_WASDEL;
} else if (cur)
cur->bc_private.b.flags &= ~XFS_BTCUR_BPRV_WASDEL;
/*
* If it's the case where the directory code is running
* with no block reservation, and the deleted block is in
* the middle of its extent, and the resulting insert
* of an extent would cause transformation to btree format,
* then reject it. The calling code will then swap
* blocks around instead.
* We have to do this now, rather than waiting for the
* conversion to btree format, since the transaction
* will be dirty.
*/
if (!wasdel && xfs_trans_get_block_res(tp) == 0 &&
XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS &&
XFS_IFORK_NEXTENTS(ip, whichfork) >= /* Note the >= */
XFS_IFORK_MAXEXT(ip, whichfork) &&
del.br_startoff > got.br_startoff &&
del.br_startoff + del.br_blockcount <
got.br_startoff + got.br_blockcount) {
error = XFS_ERROR(ENOSPC);
goto error0;
}
error = xfs_bmap_del_extent(ip, tp, &lastx, flist, cur, &del,
&tmp_logflags, whichfork);
logflags |= tmp_logflags;
if (error)
goto error0;
bno = del.br_startoff - 1;
nodelete:
/*
* If not done go on to the next (previous) record.
*/
if (bno != (xfs_fileoff_t)-1 && bno >= start) {
if (lastx >= 0) {
ep = xfs_iext_get_ext(ifp, lastx);
if (xfs_bmbt_get_startoff(ep) > bno) {
if (--lastx >= 0)
ep = xfs_iext_get_ext(ifp,
lastx);
}
xfs_bmbt_get_all(ep, &got);
}
extno++;
}
}
*done = bno == (xfs_fileoff_t)-1 || bno < start || lastx < 0;
/*
* Convert to a btree if necessary.
*/
if (xfs_bmap_needs_btree(ip, whichfork)) {
ASSERT(cur == NULL);
error = xfs_bmap_extents_to_btree(tp, ip, firstblock, flist,
&cur, 0, &tmp_logflags, whichfork);
logflags |= tmp_logflags;
if (error)
goto error0;
}
/*
* transform from btree to extents, give it cur
*/
else if (xfs_bmap_wants_extents(ip, whichfork)) {
ASSERT(cur != NULL);
error = xfs_bmap_btree_to_extents(tp, ip, cur, &tmp_logflags,
whichfork);
logflags |= tmp_logflags;
if (error)
goto error0;
}
/*
* transform from extents to local?
*/
error = 0;
error0:
/*
* Log everything. Do this after conversion, there's no point in
* logging the extent records if we've converted to btree format.
*/
if ((logflags & xfs_ilog_fext(whichfork)) &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_EXTENTS)
logflags &= ~xfs_ilog_fext(whichfork);
else if ((logflags & xfs_ilog_fbroot(whichfork)) &&
XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE)
logflags &= ~xfs_ilog_fbroot(whichfork);
/*
* Log inode even in the error case, if the transaction
* is dirty we'll need to shut down the filesystem.
*/
if (logflags)
xfs_trans_log_inode(tp, ip, logflags);
if (cur) {
if (!error) {
*firstblock = cur->bc_private.b.firstblock;
cur->bc_private.b.allocated = 0;
}
xfs_btree_del_cursor(cur,
error ? XFS_BTREE_ERROR : XFS_BTREE_NOERROR);
}
return error;
}
/*
* returns 1 for success, 0 if we failed to map the extent.
*/
STATIC int
xfs_getbmapx_fix_eof_hole(
xfs_inode_t *ip, /* xfs incore inode pointer */
struct getbmapx *out, /* output structure */
int prealloced, /* this is a file with
* preallocated data space */
__int64_t end, /* last block requested */
xfs_fsblock_t startblock)
{
__int64_t fixlen;
xfs_mount_t *mp; /* file system mount point */
xfs_ifork_t *ifp; /* inode fork pointer */
xfs_extnum_t lastx; /* last extent pointer */
xfs_fileoff_t fileblock;
if (startblock == HOLESTARTBLOCK) {
mp = ip->i_mount;
out->bmv_block = -1;
fixlen = XFS_FSB_TO_BB(mp, XFS_B_TO_FSB(mp, XFS_ISIZE(ip)));
fixlen -= out->bmv_offset;
if (prealloced && out->bmv_offset + out->bmv_length == end) {
/* Came to hole at EOF. Trim it. */
if (fixlen <= 0)
return 0;
out->bmv_length = fixlen;
}
} else {
if (startblock == DELAYSTARTBLOCK)
out->bmv_block = -2;
else
out->bmv_block = xfs_fsb_to_db(ip, startblock);
fileblock = XFS_BB_TO_FSB(ip->i_mount, out->bmv_offset);
ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
if (xfs_iext_bno_to_ext(ifp, fileblock, &lastx) &&
(lastx == (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t))-1))
out->bmv_oflags |= BMV_OF_LAST;
}
return 1;
}
/*
* Get inode's extents as described in bmv, and format for output.
* Calls formatter to fill the user's buffer until all extents
* are mapped, until the passed-in bmv->bmv_count slots have
* been filled, or until the formatter short-circuits the loop,
* if it is tracking filled-in extents on its own.
*/
int /* error code */
xfs_getbmap(
xfs_inode_t *ip,
struct getbmapx *bmv, /* user bmap structure */
xfs_bmap_format_t formatter, /* format to user */
void *arg) /* formatter arg */
{
__int64_t bmvend; /* last block requested */
int error = 0; /* return value */
__int64_t fixlen; /* length for -1 case */
int i; /* extent number */
int lock; /* lock state */
xfs_bmbt_irec_t *map; /* buffer for user's data */
xfs_mount_t *mp; /* file system mount point */
int nex; /* # of user extents can do */
int nexleft; /* # of user extents left */
int subnex; /* # of bmapi's can do */
int nmap; /* number of map entries */
struct getbmapx *out; /* output structure */
int whichfork; /* data or attr fork */
int prealloced; /* this is a file with
* preallocated data space */
int iflags; /* interface flags */
int bmapi_flags; /* flags for xfs_bmapi */
int cur_ext = 0;
mp = ip->i_mount;
iflags = bmv->bmv_iflags;
whichfork = iflags & BMV_IF_ATTRFORK ? XFS_ATTR_FORK : XFS_DATA_FORK;
if (whichfork == XFS_ATTR_FORK) {
if (XFS_IFORK_Q(ip)) {
if (ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS &&
ip->i_d.di_aformat != XFS_DINODE_FMT_BTREE &&
ip->i_d.di_aformat != XFS_DINODE_FMT_LOCAL)
return XFS_ERROR(EINVAL);
} else if (unlikely(
ip->i_d.di_aformat != 0 &&
ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS)) {
XFS_ERROR_REPORT("xfs_getbmap", XFS_ERRLEVEL_LOW,
ip->i_mount);
return XFS_ERROR(EFSCORRUPTED);
}
prealloced = 0;
fixlen = 1LL << 32;
} else {
if (ip->i_d.di_format != XFS_DINODE_FMT_EXTENTS &&
ip->i_d.di_format != XFS_DINODE_FMT_BTREE &&
ip->i_d.di_format != XFS_DINODE_FMT_LOCAL)
return XFS_ERROR(EINVAL);
if (xfs_get_extsz_hint(ip) ||
ip->i_d.di_flags & (XFS_DIFLAG_PREALLOC|XFS_DIFLAG_APPEND)){
prealloced = 1;
fixlen = XFS_MAXIOFFSET(mp);
} else {
prealloced = 0;
fixlen = XFS_ISIZE(ip);
}
}
if (bmv->bmv_length == -1) {
fixlen = XFS_FSB_TO_BB(mp, XFS_B_TO_FSB(mp, fixlen));
bmv->bmv_length =
max_t(__int64_t, fixlen - bmv->bmv_offset, 0);
} else if (bmv->bmv_length == 0) {
bmv->bmv_entries = 0;
return 0;
} else if (bmv->bmv_length < 0) {
return XFS_ERROR(EINVAL);
}
nex = bmv->bmv_count - 1;
if (nex <= 0)
return XFS_ERROR(EINVAL);
bmvend = bmv->bmv_offset + bmv->bmv_length;
if (bmv->bmv_count > ULONG_MAX / sizeof(struct getbmapx))
return XFS_ERROR(ENOMEM);
out = kmem_zalloc(bmv->bmv_count * sizeof(struct getbmapx), KM_MAYFAIL);
if (!out) {
out = kmem_zalloc_large(bmv->bmv_count *
sizeof(struct getbmapx));
if (!out)
return XFS_ERROR(ENOMEM);
}
xfs_ilock(ip, XFS_IOLOCK_SHARED);
if (whichfork == XFS_DATA_FORK && !(iflags & BMV_IF_DELALLOC)) {
if (ip->i_delayed_blks || XFS_ISIZE(ip) > ip->i_d.di_size) {
error = xfs_flush_pages(ip, 0, -1, 0, FI_REMAPF);
if (error)
goto out_unlock_iolock;
}
/*
* even after flushing the inode, there can still be delalloc
* blocks on the inode beyond EOF due to speculative
* preallocation. These are not removed until the release
* function is called or the inode is inactivated. Hence we
* cannot assert here that ip->i_delayed_blks == 0.
*/
}
lock = xfs_ilock_map_shared(ip);
/*
* Don't let nex be bigger than the number of extents
* we can have assuming alternating holes and real extents.
*/
if (nex > XFS_IFORK_NEXTENTS(ip, whichfork) * 2 + 1)
nex = XFS_IFORK_NEXTENTS(ip, whichfork) * 2 + 1;
bmapi_flags = xfs_bmapi_aflag(whichfork);
if (!(iflags & BMV_IF_PREALLOC))
bmapi_flags |= XFS_BMAPI_IGSTATE;
/*
* Allocate enough space to handle "subnex" maps at a time.
*/
error = ENOMEM;
subnex = 16;
map = kmem_alloc(subnex * sizeof(*map), KM_MAYFAIL | KM_NOFS);
if (!map)
goto out_unlock_ilock;
bmv->bmv_entries = 0;
if (XFS_IFORK_NEXTENTS(ip, whichfork) == 0 &&
(whichfork == XFS_ATTR_FORK || !(iflags & BMV_IF_DELALLOC))) {
error = 0;
goto out_free_map;
}
nexleft = nex;
do {
nmap = (nexleft > subnex) ? subnex : nexleft;
error = xfs_bmapi_read(ip, XFS_BB_TO_FSBT(mp, bmv->bmv_offset),
XFS_BB_TO_FSB(mp, bmv->bmv_length),
map, &nmap, bmapi_flags);
if (error)
goto out_free_map;
ASSERT(nmap <= subnex);
for (i = 0; i < nmap && nexleft && bmv->bmv_length; i++) {
out[cur_ext].bmv_oflags = 0;
if (map[i].br_state == XFS_EXT_UNWRITTEN)
out[cur_ext].bmv_oflags |= BMV_OF_PREALLOC;
else if (map[i].br_startblock == DELAYSTARTBLOCK)
out[cur_ext].bmv_oflags |= BMV_OF_DELALLOC;
out[cur_ext].bmv_offset =
XFS_FSB_TO_BB(mp, map[i].br_startoff);
out[cur_ext].bmv_length =
XFS_FSB_TO_BB(mp, map[i].br_blockcount);
out[cur_ext].bmv_unused1 = 0;
out[cur_ext].bmv_unused2 = 0;
ASSERT(((iflags & BMV_IF_DELALLOC) != 0) ||
(map[i].br_startblock != DELAYSTARTBLOCK));
if (map[i].br_startblock == HOLESTARTBLOCK &&
whichfork == XFS_ATTR_FORK) {
/* came to the end of attribute fork */
out[cur_ext].bmv_oflags |= BMV_OF_LAST;
goto out_free_map;
}
if (!xfs_getbmapx_fix_eof_hole(ip, &out[cur_ext],
prealloced, bmvend,
map[i].br_startblock))
goto out_free_map;
bmv->bmv_offset =
out[cur_ext].bmv_offset +
out[cur_ext].bmv_length;
bmv->bmv_length =
max_t(__int64_t, 0, bmvend - bmv->bmv_offset);
/*
* In case we don't want to return the hole,
* don't increase cur_ext so that we can reuse
* it in the next loop.
*/
if ((iflags & BMV_IF_NO_HOLES) &&
map[i].br_startblock == HOLESTARTBLOCK) {
memset(&out[cur_ext], 0, sizeof(out[cur_ext]));
continue;
}
nexleft--;
bmv->bmv_entries++;
cur_ext++;
}
} while (nmap && nexleft && bmv->bmv_length);
out_free_map:
kmem_free(map);
out_unlock_ilock:
xfs_iunlock_map_shared(ip, lock);
out_unlock_iolock:
xfs_iunlock(ip, XFS_IOLOCK_SHARED);
for (i = 0; i < cur_ext; i++) {
int full = 0; /* user array is full */
/* format results & advance arg */
error = formatter(&arg, &out[i], &full);
if (error || full)
break;
}
if (is_vmalloc_addr(out))
kmem_free_large(out);
else
kmem_free(out);
return error;
}
#ifdef DEBUG
STATIC struct xfs_buf *
xfs_bmap_get_bp(
struct xfs_btree_cur *cur,
xfs_fsblock_t bno)
{
struct xfs_log_item_desc *lidp;
int i;
if (!cur)
return NULL;
for (i = 0; i < XFS_BTREE_MAXLEVELS; i++) {
if (!cur->bc_bufs[i])
break;
if (XFS_BUF_ADDR(cur->bc_bufs[i]) == bno)
return cur->bc_bufs[i];
}
/* Chase down all the log items to see if the bp is there */
list_for_each_entry(lidp, &cur->bc_tp->t_items, lid_trans) {
struct xfs_buf_log_item *bip;
bip = (struct xfs_buf_log_item *)lidp->lid_item;
if (bip->bli_item.li_type == XFS_LI_BUF &&
XFS_BUF_ADDR(bip->bli_buf) == bno)
return bip->bli_buf;
}
return NULL;
}
STATIC void
xfs_check_block(
struct xfs_btree_block *block,
xfs_mount_t *mp,
int root,
short sz)
{
int i, j, dmxr;
__be64 *pp, *thispa; /* pointer to block address */
xfs_bmbt_key_t *prevp, *keyp;
ASSERT(be16_to_cpu(block->bb_level) > 0);
prevp = NULL;
for( i = 1; i <= xfs_btree_get_numrecs(block); i++) {
dmxr = mp->m_bmap_dmxr[0];
keyp = XFS_BMBT_KEY_ADDR(mp, block, i);
if (prevp) {
ASSERT(be64_to_cpu(prevp->br_startoff) <
be64_to_cpu(keyp->br_startoff));
}
prevp = keyp;
/*
* Compare the block numbers to see if there are dups.
*/
if (root)
pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, i, sz);
else
pp = XFS_BMBT_PTR_ADDR(mp, block, i, dmxr);
for (j = i+1; j <= be16_to_cpu(block->bb_numrecs); j++) {
if (root)
thispa = XFS_BMAP_BROOT_PTR_ADDR(mp, block, j, sz);
else
thispa = XFS_BMBT_PTR_ADDR(mp, block, j, dmxr);
if (*thispa == *pp) {
xfs_warn(mp, "%s: thispa(%d) == pp(%d) %Ld",
__func__, j, i,
(unsigned long long)be64_to_cpu(*thispa));
panic("%s: ptrs are equal in node\n",
__func__);
}
}
}
}
/*
* Check that the extents for the inode ip are in the right order in all
* btree leaves.
*/
STATIC void
xfs_bmap_check_leaf_extents(
xfs_btree_cur_t *cur, /* btree cursor or null */
xfs_inode_t *ip, /* incore inode pointer */
int whichfork) /* data or attr fork */
{
struct xfs_btree_block *block; /* current btree block */
xfs_fsblock_t bno; /* block # of "block" */
xfs_buf_t *bp; /* buffer for "block" */
int error; /* error return value */
xfs_extnum_t i=0, j; /* index into the extents list */
xfs_ifork_t *ifp; /* fork structure */
int level; /* btree level, for checking */
xfs_mount_t *mp; /* file system mount structure */
__be64 *pp; /* pointer to block address */
xfs_bmbt_rec_t *ep; /* pointer to current extent */
xfs_bmbt_rec_t last = {0, 0}; /* last extent in prev block */
xfs_bmbt_rec_t *nextp; /* pointer to next extent */
int bp_release = 0;
if (XFS_IFORK_FORMAT(ip, whichfork) != XFS_DINODE_FMT_BTREE) {
return;
}
bno = NULLFSBLOCK;
mp = ip->i_mount;
ifp = XFS_IFORK_PTR(ip, whichfork);
block = ifp->if_broot;
/*
* Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out.
*/
level = be16_to_cpu(block->bb_level);
ASSERT(level > 0);
xfs_check_block(block, mp, 1, ifp->if_broot_bytes);
pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, 1, ifp->if_broot_bytes);
bno = be64_to_cpu(*pp);
ASSERT(bno != NULLDFSBNO);
ASSERT(XFS_FSB_TO_AGNO(mp, bno) < mp->m_sb.sb_agcount);
ASSERT(XFS_FSB_TO_AGBNO(mp, bno) < mp->m_sb.sb_agblocks);
/*
* Go down the tree until leaf level is reached, following the first
* pointer (leftmost) at each level.
*/
while (level-- > 0) {
/* See if buf is in cur first */
bp = xfs_bmap_get_bp(cur, XFS_FSB_TO_DADDR(mp, bno));
if (bp) {
bp_release = 0;
} else {
bp_release = 1;
}
if (!bp && (error = xfs_btree_read_bufl(mp, NULL, bno, 0, &bp,
XFS_BMAP_BTREE_REF)))
goto error_norelse;
block = XFS_BUF_TO_BLOCK(bp);
XFS_WANT_CORRUPTED_GOTO(
xfs_bmap_sanity_check(mp, bp, level),
error0);
if (level == 0)
break;
/*
* Check this block for basic sanity (increasing keys and
* no duplicate blocks).
*/
xfs_check_block(block, mp, 0, 0);
pp = XFS_BMBT_PTR_ADDR(mp, block, 1, mp->m_bmap_dmxr[1]);
bno = be64_to_cpu(*pp);
XFS_WANT_CORRUPTED_GOTO(XFS_FSB_SANITY_CHECK(mp, bno), error0);
if (bp_release) {
bp_release = 0;
xfs_trans_brelse(NULL, bp);
}
}
/*
* Here with bp and block set to the leftmost leaf node in the tree.
*/
i = 0;
/*
* Loop over all leaf nodes checking that all extents are in the right order.
*/
for (;;) {
xfs_fsblock_t nextbno;
xfs_extnum_t num_recs;
num_recs = xfs_btree_get_numrecs(block);
/*
* Read-ahead the next leaf block, if any.
*/
nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
/*
* Check all the extents to make sure they are OK.
* If we had a previous block, the last entry should
* conform with the first entry in this one.
*/
ep = XFS_BMBT_REC_ADDR(mp, block, 1);
if (i) {
ASSERT(xfs_bmbt_disk_get_startoff(&last) +
xfs_bmbt_disk_get_blockcount(&last) <=
xfs_bmbt_disk_get_startoff(ep));
}
for (j = 1; j < num_recs; j++) {
nextp = XFS_BMBT_REC_ADDR(mp, block, j + 1);
ASSERT(xfs_bmbt_disk_get_startoff(ep) +
xfs_bmbt_disk_get_blockcount(ep) <=
xfs_bmbt_disk_get_startoff(nextp));
ep = nextp;
}
last = *ep;
i += num_recs;
if (bp_release) {
bp_release = 0;
xfs_trans_brelse(NULL, bp);
}
bno = nextbno;
/*
* If we've reached the end, stop.
*/
if (bno == NULLFSBLOCK)
break;
bp = xfs_bmap_get_bp(cur, XFS_FSB_TO_DADDR(mp, bno));
if (bp) {
bp_release = 0;
} else {
bp_release = 1;
}
if (!bp && (error = xfs_btree_read_bufl(mp, NULL, bno, 0, &bp,
XFS_BMAP_BTREE_REF)))
goto error_norelse;
block = XFS_BUF_TO_BLOCK(bp);
}
if (bp_release) {
bp_release = 0;
xfs_trans_brelse(NULL, bp);
}
return;
error0:
xfs_warn(mp, "%s: at error0", __func__);
if (bp_release)
xfs_trans_brelse(NULL, bp);
error_norelse:
xfs_warn(mp, "%s: BAD after btree leaves for %d extents",
__func__, i);
panic("%s: CORRUPTED BTREE OR SOMETHING", __func__);
return;
}
#endif
/*
* Count fsblocks of the given fork.
*/
int /* error */
xfs_bmap_count_blocks(
xfs_trans_t *tp, /* transaction pointer */
xfs_inode_t *ip, /* incore inode */
int whichfork, /* data or attr fork */
int *count) /* out: count of blocks */
{
struct xfs_btree_block *block; /* current btree block */
xfs_fsblock_t bno; /* block # of "block" */
xfs_ifork_t *ifp; /* fork structure */
int level; /* btree level, for checking */
xfs_mount_t *mp; /* file system mount structure */
__be64 *pp; /* pointer to block address */
bno = NULLFSBLOCK;
mp = ip->i_mount;
ifp = XFS_IFORK_PTR(ip, whichfork);
if ( XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS ) {
xfs_bmap_count_leaves(ifp, 0,
ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t),
count);
return 0;
}
/*
* Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out.
*/
block = ifp->if_broot;
level = be16_to_cpu(block->bb_level);
ASSERT(level > 0);
pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, 1, ifp->if_broot_bytes);
bno = be64_to_cpu(*pp);
ASSERT(bno != NULLDFSBNO);
ASSERT(XFS_FSB_TO_AGNO(mp, bno) < mp->m_sb.sb_agcount);
ASSERT(XFS_FSB_TO_AGBNO(mp, bno) < mp->m_sb.sb_agblocks);
if (unlikely(xfs_bmap_count_tree(mp, tp, ifp, bno, level, count) < 0)) {
XFS_ERROR_REPORT("xfs_bmap_count_blocks(2)", XFS_ERRLEVEL_LOW,
mp);
return XFS_ERROR(EFSCORRUPTED);
}
return 0;
}
/*
* Recursively walks each level of a btree
* to count total fsblocks is use.
*/
STATIC int /* error */
xfs_bmap_count_tree(
xfs_mount_t *mp, /* file system mount point */
xfs_trans_t *tp, /* transaction pointer */
xfs_ifork_t *ifp, /* inode fork pointer */
xfs_fsblock_t blockno, /* file system block number */
int levelin, /* level in btree */
int *count) /* Count of blocks */
{
int error;
xfs_buf_t *bp, *nbp;
int level = levelin;
__be64 *pp;
xfs_fsblock_t bno = blockno;
xfs_fsblock_t nextbno;
struct xfs_btree_block *block, *nextblock;
int numrecs;
if ((error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp, XFS_BMAP_BTREE_REF)))
return error;
*count += 1;
block = XFS_BUF_TO_BLOCK(bp);
if (--level) {
/* Not at node above leaves, count this level of nodes */
nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
while (nextbno != NULLFSBLOCK) {
if ((error = xfs_btree_read_bufl(mp, tp, nextbno,
0, &nbp, XFS_BMAP_BTREE_REF)))
return error;
*count += 1;
nextblock = XFS_BUF_TO_BLOCK(nbp);
nextbno = be64_to_cpu(nextblock->bb_u.l.bb_rightsib);
xfs_trans_brelse(tp, nbp);
}
/* Dive to the next level */
pp = XFS_BMBT_PTR_ADDR(mp, block, 1, mp->m_bmap_dmxr[1]);
bno = be64_to_cpu(*pp);
if (unlikely((error =
xfs_bmap_count_tree(mp, tp, ifp, bno, level, count)) < 0)) {
xfs_trans_brelse(tp, bp);
XFS_ERROR_REPORT("xfs_bmap_count_tree(1)",
XFS_ERRLEVEL_LOW, mp);
return XFS_ERROR(EFSCORRUPTED);
}
xfs_trans_brelse(tp, bp);
} else {
/* count all level 1 nodes and their leaves */
for (;;) {
nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
numrecs = be16_to_cpu(block->bb_numrecs);
xfs_bmap_disk_count_leaves(mp, block, numrecs, count);
xfs_trans_brelse(tp, bp);
if (nextbno == NULLFSBLOCK)
break;
bno = nextbno;
if ((error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp,
XFS_BMAP_BTREE_REF)))
return error;
*count += 1;
block = XFS_BUF_TO_BLOCK(bp);
}
}
return 0;
}
/*
* Count leaf blocks given a range of extent records.
*/
STATIC void
xfs_bmap_count_leaves(
xfs_ifork_t *ifp,
xfs_extnum_t idx,
int numrecs,
int *count)
{
int b;
for (b = 0; b < numrecs; b++) {
xfs_bmbt_rec_host_t *frp = xfs_iext_get_ext(ifp, idx + b);
*count += xfs_bmbt_get_blockcount(frp);
}
}
/*
* Count leaf blocks given a range of extent records originally
* in btree format.
*/
STATIC void
xfs_bmap_disk_count_leaves(
struct xfs_mount *mp,
struct xfs_btree_block *block,
int numrecs,
int *count)
{
int b;
xfs_bmbt_rec_t *frp;
for (b = 1; b <= numrecs; b++) {
frp = XFS_BMBT_REC_ADDR(mp, block, b);
*count += xfs_bmbt_disk_get_blockcount(frp);
}
}
/*
* dead simple method of punching delalyed allocation blocks from a range in
* the inode. Walks a block at a time so will be slow, but is only executed in
* rare error cases so the overhead is not critical. This will alays punch out
* both the start and end blocks, even if the ranges only partially overlap
* them, so it is up to the caller to ensure that partial blocks are not
* passed in.
*/
int
xfs_bmap_punch_delalloc_range(
struct xfs_inode *ip,
xfs_fileoff_t start_fsb,
xfs_fileoff_t length)
{
xfs_fileoff_t remaining = length;
int error = 0;
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
do {
int done;
xfs_bmbt_irec_t imap;
int nimaps = 1;
xfs_fsblock_t firstblock;
xfs_bmap_free_t flist;
/*
* Map the range first and check that it is a delalloc extent
* before trying to unmap the range. Otherwise we will be
* trying to remove a real extent (which requires a
* transaction) or a hole, which is probably a bad idea...
*/
error = xfs_bmapi_read(ip, start_fsb, 1, &imap, &nimaps,
XFS_BMAPI_ENTIRE);
if (error) {
/* something screwed, just bail */
if (!XFS_FORCED_SHUTDOWN(ip->i_mount)) {
xfs_alert(ip->i_mount,
"Failed delalloc mapping lookup ino %lld fsb %lld.",
ip->i_ino, start_fsb);
}
break;
}
if (!nimaps) {
/* nothing there */
goto next_block;
}
if (imap.br_startblock != DELAYSTARTBLOCK) {
/* been converted, ignore */
goto next_block;
}
WARN_ON(imap.br_blockcount == 0);
/*
* Note: while we initialise the firstblock/flist pair, they
* should never be used because blocks should never be
* allocated or freed for a delalloc extent and hence we need
* don't cancel or finish them after the xfs_bunmapi() call.
*/
xfs_bmap_init(&flist, &firstblock);
error = xfs_bunmapi(NULL, ip, start_fsb, 1, 0, 1, &firstblock,
&flist, &done);
if (error)
break;
ASSERT(!flist.xbf_count && !flist.xbf_first);
next_block:
start_fsb++;
remaining--;
} while(remaining > 0);
return error;
}
| gpl-2.0 |
AOSPA-legacy/android_kernel_oppo_n1 | drivers/video/backlight/ltv350qv.c | 4808 | 8207 | /*
* Power control for Samsung LTV350QV Quarter VGA LCD Panel
*
* Copyright (C) 2006, 2007 Atmel Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/lcd.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/spi/spi.h>
#include "ltv350qv.h"
#define POWER_IS_ON(pwr) ((pwr) <= FB_BLANK_NORMAL)
struct ltv350qv {
struct spi_device *spi;
u8 *buffer;
int power;
struct lcd_device *ld;
};
/*
* The power-on and power-off sequences are taken from the
* LTV350QV-F04 data sheet from Samsung. The register definitions are
* taken from the S6F2002 command list also from Samsung. Both
* documents are distributed with the AVR32 Linux BSP CD from Atmel.
*
* There's still some voodoo going on here, but it's a lot better than
* in the first incarnation of the driver where all we had was the raw
* numbers from the initialization sequence.
*/
static int ltv350qv_write_reg(struct ltv350qv *lcd, u8 reg, u16 val)
{
struct spi_message msg;
struct spi_transfer index_xfer = {
.len = 3,
.cs_change = 1,
};
struct spi_transfer value_xfer = {
.len = 3,
};
spi_message_init(&msg);
/* register index */
lcd->buffer[0] = LTV_OPC_INDEX;
lcd->buffer[1] = 0x00;
lcd->buffer[2] = reg & 0x7f;
index_xfer.tx_buf = lcd->buffer;
spi_message_add_tail(&index_xfer, &msg);
/* register value */
lcd->buffer[4] = LTV_OPC_DATA;
lcd->buffer[5] = val >> 8;
lcd->buffer[6] = val;
value_xfer.tx_buf = lcd->buffer + 4;
spi_message_add_tail(&value_xfer, &msg);
return spi_sync(lcd->spi, &msg);
}
/* The comments are taken straight from the data sheet */
static int ltv350qv_power_on(struct ltv350qv *lcd)
{
int ret;
/* Power On Reset Display off State */
if (ltv350qv_write_reg(lcd, LTV_PWRCTL1, 0x0000))
goto err;
msleep(15);
/* Power Setting Function 1 */
if (ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE))
goto err;
if (ltv350qv_write_reg(lcd, LTV_PWRCTL2, LTV_VCOML_ENABLE))
goto err_power1;
/* Power Setting Function 2 */
if (ltv350qv_write_reg(lcd, LTV_PWRCTL1,
LTV_VCOM_DISABLE | LTV_DRIVE_CURRENT(5)
| LTV_SUPPLY_CURRENT(5)))
goto err_power2;
msleep(55);
/* Instruction Setting */
ret = ltv350qv_write_reg(lcd, LTV_IFCTL,
LTV_NMD | LTV_REV | LTV_NL(0x1d));
ret |= ltv350qv_write_reg(lcd, LTV_DATACTL,
LTV_DS_SAME | LTV_CHS_480
| LTV_DF_RGB | LTV_RGB_BGR);
ret |= ltv350qv_write_reg(lcd, LTV_ENTRY_MODE,
LTV_VSPL_ACTIVE_LOW
| LTV_HSPL_ACTIVE_LOW
| LTV_DPL_SAMPLE_RISING
| LTV_EPL_ACTIVE_LOW
| LTV_SS_RIGHT_TO_LEFT);
ret |= ltv350qv_write_reg(lcd, LTV_GATECTL1, LTV_CLW(3));
ret |= ltv350qv_write_reg(lcd, LTV_GATECTL2,
LTV_NW_INV_1LINE | LTV_FWI(3));
ret |= ltv350qv_write_reg(lcd, LTV_VBP, 0x000a);
ret |= ltv350qv_write_reg(lcd, LTV_HBP, 0x0021);
ret |= ltv350qv_write_reg(lcd, LTV_SOTCTL, LTV_SDT(3) | LTV_EQ(0));
ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(0), 0x0103);
ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(1), 0x0301);
ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(2), 0x1f0f);
ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(3), 0x1f0f);
ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(4), 0x0707);
ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(5), 0x0307);
ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(6), 0x0707);
ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(7), 0x0000);
ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(8), 0x0004);
ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(9), 0x0000);
if (ret)
goto err_settings;
/* Wait more than 2 frames */
msleep(20);
/* Display On Sequence */
ret = ltv350qv_write_reg(lcd, LTV_PWRCTL1,
LTV_VCOM_DISABLE | LTV_VCOMOUT_ENABLE
| LTV_POWER_ON | LTV_DRIVE_CURRENT(5)
| LTV_SUPPLY_CURRENT(5));
ret |= ltv350qv_write_reg(lcd, LTV_GATECTL2,
LTV_NW_INV_1LINE | LTV_DSC | LTV_FWI(3));
if (ret)
goto err_disp_on;
/* Display should now be ON. Phew. */
return 0;
err_disp_on:
/*
* Try to recover. Error handling probably isn't very useful
* at this point, just make a best effort to switch the panel
* off.
*/
ltv350qv_write_reg(lcd, LTV_PWRCTL1,
LTV_VCOM_DISABLE | LTV_DRIVE_CURRENT(5)
| LTV_SUPPLY_CURRENT(5));
ltv350qv_write_reg(lcd, LTV_GATECTL2,
LTV_NW_INV_1LINE | LTV_FWI(3));
err_settings:
err_power2:
err_power1:
ltv350qv_write_reg(lcd, LTV_PWRCTL2, 0x0000);
msleep(1);
err:
ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE);
return -EIO;
}
static int ltv350qv_power_off(struct ltv350qv *lcd)
{
int ret;
/* Display Off Sequence */
ret = ltv350qv_write_reg(lcd, LTV_PWRCTL1,
LTV_VCOM_DISABLE
| LTV_DRIVE_CURRENT(5)
| LTV_SUPPLY_CURRENT(5));
ret |= ltv350qv_write_reg(lcd, LTV_GATECTL2,
LTV_NW_INV_1LINE | LTV_FWI(3));
/* Power down setting 1 */
ret |= ltv350qv_write_reg(lcd, LTV_PWRCTL2, 0x0000);
/* Wait at least 1 ms */
msleep(1);
/* Power down setting 2 */
ret |= ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE);
/*
* No point in trying to recover here. If we can't switch the
* panel off, what are we supposed to do other than inform the
* user about the failure?
*/
if (ret)
return -EIO;
/* Display power should now be OFF */
return 0;
}
static int ltv350qv_power(struct ltv350qv *lcd, int power)
{
int ret = 0;
if (POWER_IS_ON(power) && !POWER_IS_ON(lcd->power))
ret = ltv350qv_power_on(lcd);
else if (!POWER_IS_ON(power) && POWER_IS_ON(lcd->power))
ret = ltv350qv_power_off(lcd);
if (!ret)
lcd->power = power;
return ret;
}
static int ltv350qv_set_power(struct lcd_device *ld, int power)
{
struct ltv350qv *lcd = lcd_get_data(ld);
return ltv350qv_power(lcd, power);
}
static int ltv350qv_get_power(struct lcd_device *ld)
{
struct ltv350qv *lcd = lcd_get_data(ld);
return lcd->power;
}
static struct lcd_ops ltv_ops = {
.get_power = ltv350qv_get_power,
.set_power = ltv350qv_set_power,
};
static int __devinit ltv350qv_probe(struct spi_device *spi)
{
struct ltv350qv *lcd;
struct lcd_device *ld;
int ret;
lcd = kzalloc(sizeof(struct ltv350qv), GFP_KERNEL);
if (!lcd)
return -ENOMEM;
lcd->spi = spi;
lcd->power = FB_BLANK_POWERDOWN;
lcd->buffer = kzalloc(8, GFP_KERNEL);
if (!lcd->buffer) {
ret = -ENOMEM;
goto out_free_lcd;
}
ld = lcd_device_register("ltv350qv", &spi->dev, lcd, <v_ops);
if (IS_ERR(ld)) {
ret = PTR_ERR(ld);
goto out_free_buffer;
}
lcd->ld = ld;
ret = ltv350qv_power(lcd, FB_BLANK_UNBLANK);
if (ret)
goto out_unregister;
dev_set_drvdata(&spi->dev, lcd);
return 0;
out_unregister:
lcd_device_unregister(ld);
out_free_buffer:
kfree(lcd->buffer);
out_free_lcd:
kfree(lcd);
return ret;
}
static int __devexit ltv350qv_remove(struct spi_device *spi)
{
struct ltv350qv *lcd = dev_get_drvdata(&spi->dev);
ltv350qv_power(lcd, FB_BLANK_POWERDOWN);
lcd_device_unregister(lcd->ld);
kfree(lcd->buffer);
kfree(lcd);
return 0;
}
#ifdef CONFIG_PM
static int ltv350qv_suspend(struct spi_device *spi, pm_message_t state)
{
struct ltv350qv *lcd = dev_get_drvdata(&spi->dev);
return ltv350qv_power(lcd, FB_BLANK_POWERDOWN);
}
static int ltv350qv_resume(struct spi_device *spi)
{
struct ltv350qv *lcd = dev_get_drvdata(&spi->dev);
return ltv350qv_power(lcd, FB_BLANK_UNBLANK);
}
#else
#define ltv350qv_suspend NULL
#define ltv350qv_resume NULL
#endif
/* Power down all displays on reboot, poweroff or halt */
static void ltv350qv_shutdown(struct spi_device *spi)
{
struct ltv350qv *lcd = dev_get_drvdata(&spi->dev);
ltv350qv_power(lcd, FB_BLANK_POWERDOWN);
}
static struct spi_driver ltv350qv_driver = {
.driver = {
.name = "ltv350qv",
.bus = &spi_bus_type,
.owner = THIS_MODULE,
},
.probe = ltv350qv_probe,
.remove = __devexit_p(ltv350qv_remove),
.shutdown = ltv350qv_shutdown,
.suspend = ltv350qv_suspend,
.resume = ltv350qv_resume,
};
module_spi_driver(ltv350qv_driver);
MODULE_AUTHOR("Haavard Skinnemoen (Atmel)");
MODULE_DESCRIPTION("Samsung LTV350QV LCD Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("spi:ltv350qv");
| gpl-2.0 |
CyanogenMod/android_kernel_amazon_hdx-common | sound/soc/imx/imx-pcm-dma-mx2.c | 4808 | 4504 | /*
* imx-pcm-dma-mx2.c -- ALSA Soc Audio Layer
*
* Copyright 2009 Sascha Hauer <s.hauer@pengutronix.de>
*
* This code is based on code copyrighted by Freescale,
* Liam Girdwood, Javier Martin and probably others.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/dmaengine.h>
#include <linux/types.h>
#include <sound/core.h>
#include <sound/initval.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/dmaengine_pcm.h>
#include <mach/dma.h>
#include "imx-pcm.h"
static bool filter(struct dma_chan *chan, void *param)
{
if (!imx_dma_is_general_purpose(chan))
return false;
chan->private = param;
return true;
}
static int snd_imx_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct dma_chan *chan = snd_dmaengine_pcm_get_chan(substream);
struct imx_pcm_dma_params *dma_params;
struct dma_slave_config slave_config;
int ret;
dma_params = snd_soc_dai_get_dma_data(rtd->cpu_dai, substream);
ret = snd_hwparams_to_dma_slave_config(substream, params, &slave_config);
if (ret)
return ret;
slave_config.device_fc = false;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
slave_config.dst_addr = dma_params->dma_addr;
slave_config.dst_maxburst = dma_params->burstsize;
} else {
slave_config.src_addr = dma_params->dma_addr;
slave_config.src_maxburst = dma_params->burstsize;
}
ret = dmaengine_slave_config(chan, &slave_config);
if (ret)
return ret;
snd_pcm_set_runtime_buffer(substream, &substream->dma_buffer);
return 0;
}
static struct snd_pcm_hardware snd_imx_hardware = {
.info = SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rate_min = 8000,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = IMX_SSI_DMABUF_SIZE,
.period_bytes_min = 128,
.period_bytes_max = 65535, /* Limited by SDMA engine */
.periods_min = 2,
.periods_max = 255,
.fifo_size = 0,
};
static int snd_imx_open(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct imx_pcm_dma_params *dma_params;
struct imx_dma_data *dma_data;
int ret;
snd_soc_set_runtime_hwparams(substream, &snd_imx_hardware);
dma_params = snd_soc_dai_get_dma_data(rtd->cpu_dai, substream);
dma_data = kzalloc(sizeof(*dma_data), GFP_KERNEL);
dma_data->peripheral_type = IMX_DMATYPE_SSI;
dma_data->priority = DMA_PRIO_HIGH;
dma_data->dma_request = dma_params->dma;
ret = snd_dmaengine_pcm_open(substream, filter, dma_data);
if (ret) {
kfree(dma_data);
return 0;
}
snd_dmaengine_pcm_set_data(substream, dma_data);
return 0;
}
static int snd_imx_close(struct snd_pcm_substream *substream)
{
struct imx_dma_data *dma_data = snd_dmaengine_pcm_get_data(substream);
snd_dmaengine_pcm_close(substream);
kfree(dma_data);
return 0;
}
static struct snd_pcm_ops imx_pcm_ops = {
.open = snd_imx_open,
.close = snd_imx_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_imx_pcm_hw_params,
.trigger = snd_dmaengine_pcm_trigger,
.pointer = snd_dmaengine_pcm_pointer,
.mmap = snd_imx_pcm_mmap,
};
static struct snd_soc_platform_driver imx_soc_platform_mx2 = {
.ops = &imx_pcm_ops,
.pcm_new = imx_pcm_new,
.pcm_free = imx_pcm_free,
};
static int __devinit imx_soc_platform_probe(struct platform_device *pdev)
{
return snd_soc_register_platform(&pdev->dev, &imx_soc_platform_mx2);
}
static int __devexit imx_soc_platform_remove(struct platform_device *pdev)
{
snd_soc_unregister_platform(&pdev->dev);
return 0;
}
static struct platform_driver imx_pcm_driver = {
.driver = {
.name = "imx-pcm-audio",
.owner = THIS_MODULE,
},
.probe = imx_soc_platform_probe,
.remove = __devexit_p(imx_soc_platform_remove),
};
module_platform_driver(imx_pcm_driver);
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:imx-pcm-audio");
| gpl-2.0 |
Buckmarble/Lunar_kernel_sense_m7 | drivers/scsi/lpfc/lpfc_bsg.c | 4808 | 149549 | /*******************************************************************
* This file is part of the Emulex Linux Device Driver for *
* Fibre Channel Host Bus Adapters. *
* Copyright (C) 2009-2011 Emulex. All rights reserved. *
* EMULEX and SLI are trademarks of Emulex. *
* www.emulex.com *
* *
* 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. *
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND *
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE *
* DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
* TO BE LEGALLY INVALID. See the GNU General Public License for *
* more details, a copy of which can be found in the file COPYING *
* included with this package. *
*******************************************************************/
#include <linux/interrupt.h>
#include <linux/mempool.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/list.h>
#include <scsi/scsi.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_transport_fc.h>
#include <scsi/scsi_bsg_fc.h>
#include <scsi/fc/fc_fs.h>
#include "lpfc_hw4.h"
#include "lpfc_hw.h"
#include "lpfc_sli.h"
#include "lpfc_sli4.h"
#include "lpfc_nl.h"
#include "lpfc_bsg.h"
#include "lpfc_disc.h"
#include "lpfc_scsi.h"
#include "lpfc.h"
#include "lpfc_logmsg.h"
#include "lpfc_crtn.h"
#include "lpfc_debugfs.h"
#include "lpfc_vport.h"
#include "lpfc_version.h"
struct lpfc_bsg_event {
struct list_head node;
struct kref kref;
wait_queue_head_t wq;
/* Event type and waiter identifiers */
uint32_t type_mask;
uint32_t req_id;
uint32_t reg_id;
/* next two flags are here for the auto-delete logic */
unsigned long wait_time_stamp;
int waiting;
/* seen and not seen events */
struct list_head events_to_get;
struct list_head events_to_see;
/* job waiting for this event to finish */
struct fc_bsg_job *set_job;
};
struct lpfc_bsg_iocb {
struct lpfc_iocbq *cmdiocbq;
struct lpfc_iocbq *rspiocbq;
struct lpfc_dmabuf *bmp;
struct lpfc_nodelist *ndlp;
/* job waiting for this iocb to finish */
struct fc_bsg_job *set_job;
};
struct lpfc_bsg_mbox {
LPFC_MBOXQ_t *pmboxq;
MAILBOX_t *mb;
struct lpfc_dmabuf *dmabuffers; /* for BIU diags */
uint8_t *ext; /* extended mailbox data */
uint32_t mbOffset; /* from app */
uint32_t inExtWLen; /* from app */
uint32_t outExtWLen; /* from app */
/* job waiting for this mbox command to finish */
struct fc_bsg_job *set_job;
};
#define MENLO_DID 0x0000FC0E
struct lpfc_bsg_menlo {
struct lpfc_iocbq *cmdiocbq;
struct lpfc_iocbq *rspiocbq;
struct lpfc_dmabuf *bmp;
/* job waiting for this iocb to finish */
struct fc_bsg_job *set_job;
};
#define TYPE_EVT 1
#define TYPE_IOCB 2
#define TYPE_MBOX 3
#define TYPE_MENLO 4
struct bsg_job_data {
uint32_t type;
union {
struct lpfc_bsg_event *evt;
struct lpfc_bsg_iocb iocb;
struct lpfc_bsg_mbox mbox;
struct lpfc_bsg_menlo menlo;
} context_un;
};
struct event_data {
struct list_head node;
uint32_t type;
uint32_t immed_dat;
void *data;
uint32_t len;
};
#define BUF_SZ_4K 4096
#define SLI_CT_ELX_LOOPBACK 0x10
enum ELX_LOOPBACK_CMD {
ELX_LOOPBACK_XRI_SETUP,
ELX_LOOPBACK_DATA,
};
#define ELX_LOOPBACK_HEADER_SZ \
(size_t)(&((struct lpfc_sli_ct_request *)NULL)->un)
struct lpfc_dmabufext {
struct lpfc_dmabuf dma;
uint32_t size;
uint32_t flag;
};
/**
* lpfc_bsg_send_mgmt_cmd_cmp - lpfc_bsg_send_mgmt_cmd's completion handler
* @phba: Pointer to HBA context object.
* @cmdiocbq: Pointer to command iocb.
* @rspiocbq: Pointer to response iocb.
*
* This function is the completion handler for iocbs issued using
* lpfc_bsg_send_mgmt_cmd function. This function is called by the
* ring event handler function without any lock held. This function
* can be called from both worker thread context and interrupt
* context. This function also can be called from another thread which
* cleans up the SLI layer objects.
* This function copies the contents of the response iocb to the
* response iocb memory object provided by the caller of
* lpfc_sli_issue_iocb_wait and then wakes up the thread which
* sleeps for the iocb completion.
**/
static void
lpfc_bsg_send_mgmt_cmd_cmp(struct lpfc_hba *phba,
struct lpfc_iocbq *cmdiocbq,
struct lpfc_iocbq *rspiocbq)
{
struct bsg_job_data *dd_data;
struct fc_bsg_job *job;
IOCB_t *rsp;
struct lpfc_dmabuf *bmp;
struct lpfc_nodelist *ndlp;
struct lpfc_bsg_iocb *iocb;
unsigned long flags;
int rc = 0;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
dd_data = cmdiocbq->context2;
if (!dd_data) {
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
lpfc_sli_release_iocbq(phba, cmdiocbq);
return;
}
iocb = &dd_data->context_un.iocb;
job = iocb->set_job;
job->dd_data = NULL; /* so timeout handler does not reply */
bmp = iocb->bmp;
rsp = &rspiocbq->iocb;
ndlp = cmdiocbq->context1;
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
pci_unmap_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
if (rsp->ulpStatus) {
if (rsp->ulpStatus == IOSTAT_LOCAL_REJECT) {
switch (rsp->un.ulpWord[4] & 0xff) {
case IOERR_SEQUENCE_TIMEOUT:
rc = -ETIMEDOUT;
break;
case IOERR_INVALID_RPI:
rc = -EFAULT;
break;
default:
rc = -EACCES;
break;
}
} else
rc = -EACCES;
} else
job->reply->reply_payload_rcv_len =
rsp->un.genreq64.bdl.bdeSize;
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
lpfc_sli_release_iocbq(phba, cmdiocbq);
lpfc_nlp_put(ndlp);
kfree(bmp);
kfree(dd_data);
/* make error code available to userspace */
job->reply->result = rc;
/* complete the job back to userspace */
job->job_done(job);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
/**
* lpfc_bsg_send_mgmt_cmd - send a CT command from a bsg request
* @job: fc_bsg_job to handle
**/
static int
lpfc_bsg_send_mgmt_cmd(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct lpfc_rport_data *rdata = job->rport->dd_data;
struct lpfc_nodelist *ndlp = rdata->pnode;
struct ulp_bde64 *bpl = NULL;
uint32_t timeout;
struct lpfc_iocbq *cmdiocbq = NULL;
IOCB_t *cmd;
struct lpfc_dmabuf *bmp = NULL;
int request_nseg;
int reply_nseg;
struct scatterlist *sgel = NULL;
int numbde;
dma_addr_t busaddr;
struct bsg_job_data *dd_data;
uint32_t creg_val;
int rc = 0;
int iocb_stat;
/* in case no data is transferred */
job->reply->reply_payload_rcv_len = 0;
/* allocate our bsg tracking structure */
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2733 Failed allocation of dd_data\n");
rc = -ENOMEM;
goto no_dd_data;
}
if (!lpfc_nlp_get(ndlp)) {
rc = -ENODEV;
goto no_ndlp;
}
bmp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (!bmp) {
rc = -ENOMEM;
goto free_ndlp;
}
if (ndlp->nlp_flag & NLP_ELS_SND_MASK) {
rc = -ENODEV;
goto free_bmp;
}
cmdiocbq = lpfc_sli_get_iocbq(phba);
if (!cmdiocbq) {
rc = -ENOMEM;
goto free_bmp;
}
cmd = &cmdiocbq->iocb;
bmp->virt = lpfc_mbuf_alloc(phba, 0, &bmp->phys);
if (!bmp->virt) {
rc = -ENOMEM;
goto free_cmdiocbq;
}
INIT_LIST_HEAD(&bmp->list);
bpl = (struct ulp_bde64 *) bmp->virt;
request_nseg = pci_map_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
for_each_sg(job->request_payload.sg_list, sgel, request_nseg, numbde) {
busaddr = sg_dma_address(sgel);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
bpl->tus.f.bdeSize = sg_dma_len(sgel);
bpl->tus.w = cpu_to_le32(bpl->tus.w);
bpl->addrLow = cpu_to_le32(putPaddrLow(busaddr));
bpl->addrHigh = cpu_to_le32(putPaddrHigh(busaddr));
bpl++;
}
reply_nseg = pci_map_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
for_each_sg(job->reply_payload.sg_list, sgel, reply_nseg, numbde) {
busaddr = sg_dma_address(sgel);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64I;
bpl->tus.f.bdeSize = sg_dma_len(sgel);
bpl->tus.w = cpu_to_le32(bpl->tus.w);
bpl->addrLow = cpu_to_le32(putPaddrLow(busaddr));
bpl->addrHigh = cpu_to_le32(putPaddrHigh(busaddr));
bpl++;
}
cmd->un.genreq64.bdl.ulpIoTag32 = 0;
cmd->un.genreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
cmd->un.genreq64.bdl.addrLow = putPaddrLow(bmp->phys);
cmd->un.genreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
cmd->un.genreq64.bdl.bdeSize =
(request_nseg + reply_nseg) * sizeof(struct ulp_bde64);
cmd->ulpCommand = CMD_GEN_REQUEST64_CR;
cmd->un.genreq64.w5.hcsw.Fctl = (SI | LA);
cmd->un.genreq64.w5.hcsw.Dfctl = 0;
cmd->un.genreq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
cmd->un.genreq64.w5.hcsw.Type = FC_TYPE_CT;
cmd->ulpBdeCount = 1;
cmd->ulpLe = 1;
cmd->ulpClass = CLASS3;
cmd->ulpContext = ndlp->nlp_rpi;
if (phba->sli_rev == LPFC_SLI_REV4)
cmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
cmd->ulpOwner = OWN_CHIP;
cmdiocbq->vport = phba->pport;
cmdiocbq->context3 = bmp;
cmdiocbq->iocb_flag |= LPFC_IO_LIBDFC;
timeout = phba->fc_ratov * 2;
cmd->ulpTimeout = timeout;
cmdiocbq->iocb_cmpl = lpfc_bsg_send_mgmt_cmd_cmp;
cmdiocbq->context1 = ndlp;
cmdiocbq->context2 = dd_data;
dd_data->type = TYPE_IOCB;
dd_data->context_un.iocb.cmdiocbq = cmdiocbq;
dd_data->context_un.iocb.set_job = job;
dd_data->context_un.iocb.bmp = bmp;
if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
if (lpfc_readl(phba->HCregaddr, &creg_val)) {
rc = -EIO ;
goto free_cmdiocbq;
}
creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
writel(creg_val, phba->HCregaddr);
readl(phba->HCregaddr); /* flush */
}
iocb_stat = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, cmdiocbq, 0);
if (iocb_stat == IOCB_SUCCESS)
return 0; /* done for now */
else if (iocb_stat == IOCB_BUSY)
rc = -EAGAIN;
else
rc = -EIO;
/* iocb failed so cleanup */
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
pci_unmap_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
free_cmdiocbq:
lpfc_sli_release_iocbq(phba, cmdiocbq);
free_bmp:
kfree(bmp);
free_ndlp:
lpfc_nlp_put(ndlp);
no_ndlp:
kfree(dd_data);
no_dd_data:
/* make error code available to userspace */
job->reply->result = rc;
job->dd_data = NULL;
return rc;
}
/**
* lpfc_bsg_rport_els_cmp - lpfc_bsg_rport_els's completion handler
* @phba: Pointer to HBA context object.
* @cmdiocbq: Pointer to command iocb.
* @rspiocbq: Pointer to response iocb.
*
* This function is the completion handler for iocbs issued using
* lpfc_bsg_rport_els_cmp function. This function is called by the
* ring event handler function without any lock held. This function
* can be called from both worker thread context and interrupt
* context. This function also can be called from other thread which
* cleans up the SLI layer objects.
* This function copies the contents of the response iocb to the
* response iocb memory object provided by the caller of
* lpfc_sli_issue_iocb_wait and then wakes up the thread which
* sleeps for the iocb completion.
**/
static void
lpfc_bsg_rport_els_cmp(struct lpfc_hba *phba,
struct lpfc_iocbq *cmdiocbq,
struct lpfc_iocbq *rspiocbq)
{
struct bsg_job_data *dd_data;
struct fc_bsg_job *job;
IOCB_t *rsp;
struct lpfc_nodelist *ndlp;
struct lpfc_dmabuf *pbuflist = NULL;
struct fc_bsg_ctels_reply *els_reply;
uint8_t *rjt_data;
unsigned long flags;
int rc = 0;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
dd_data = cmdiocbq->context1;
/* normal completion and timeout crossed paths, already done */
if (!dd_data) {
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
if (cmdiocbq->context2 && rspiocbq)
memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
&rspiocbq->iocb, sizeof(IOCB_t));
job = dd_data->context_un.iocb.set_job;
cmdiocbq = dd_data->context_un.iocb.cmdiocbq;
rspiocbq = dd_data->context_un.iocb.rspiocbq;
rsp = &rspiocbq->iocb;
ndlp = dd_data->context_un.iocb.ndlp;
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
pci_unmap_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
if (job->reply->result == -EAGAIN)
rc = -EAGAIN;
else if (rsp->ulpStatus == IOSTAT_SUCCESS)
job->reply->reply_payload_rcv_len =
rsp->un.elsreq64.bdl.bdeSize;
else if (rsp->ulpStatus == IOSTAT_LS_RJT) {
job->reply->reply_payload_rcv_len =
sizeof(struct fc_bsg_ctels_reply);
/* LS_RJT data returned in word 4 */
rjt_data = (uint8_t *)&rsp->un.ulpWord[4];
els_reply = &job->reply->reply_data.ctels_reply;
els_reply->status = FC_CTELS_STATUS_REJECT;
els_reply->rjt_data.action = rjt_data[3];
els_reply->rjt_data.reason_code = rjt_data[2];
els_reply->rjt_data.reason_explanation = rjt_data[1];
els_reply->rjt_data.vendor_unique = rjt_data[0];
} else
rc = -EIO;
pbuflist = (struct lpfc_dmabuf *) cmdiocbq->context3;
lpfc_mbuf_free(phba, pbuflist->virt, pbuflist->phys);
lpfc_sli_release_iocbq(phba, rspiocbq);
lpfc_sli_release_iocbq(phba, cmdiocbq);
lpfc_nlp_put(ndlp);
kfree(dd_data);
/* make error code available to userspace */
job->reply->result = rc;
job->dd_data = NULL;
/* complete the job back to userspace */
job->job_done(job);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
/**
* lpfc_bsg_rport_els - send an ELS command from a bsg request
* @job: fc_bsg_job to handle
**/
static int
lpfc_bsg_rport_els(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct lpfc_rport_data *rdata = job->rport->dd_data;
struct lpfc_nodelist *ndlp = rdata->pnode;
uint32_t elscmd;
uint32_t cmdsize;
uint32_t rspsize;
struct lpfc_iocbq *rspiocbq;
struct lpfc_iocbq *cmdiocbq;
IOCB_t *rsp;
uint16_t rpi = 0;
struct lpfc_dmabuf *pcmd;
struct lpfc_dmabuf *prsp;
struct lpfc_dmabuf *pbuflist = NULL;
struct ulp_bde64 *bpl;
int request_nseg;
int reply_nseg;
struct scatterlist *sgel = NULL;
int numbde;
dma_addr_t busaddr;
struct bsg_job_data *dd_data;
uint32_t creg_val;
int rc = 0;
/* in case no data is transferred */
job->reply->reply_payload_rcv_len = 0;
/* allocate our bsg tracking structure */
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2735 Failed allocation of dd_data\n");
rc = -ENOMEM;
goto no_dd_data;
}
if (!lpfc_nlp_get(ndlp)) {
rc = -ENODEV;
goto free_dd_data;
}
elscmd = job->request->rqst_data.r_els.els_code;
cmdsize = job->request_payload.payload_len;
rspsize = job->reply_payload.payload_len;
rspiocbq = lpfc_sli_get_iocbq(phba);
if (!rspiocbq) {
lpfc_nlp_put(ndlp);
rc = -ENOMEM;
goto free_dd_data;
}
rsp = &rspiocbq->iocb;
rpi = ndlp->nlp_rpi;
cmdiocbq = lpfc_prep_els_iocb(vport, 1, cmdsize, 0, ndlp,
ndlp->nlp_DID, elscmd);
if (!cmdiocbq) {
rc = -EIO;
goto free_rspiocbq;
}
/* prep els iocb set context1 to the ndlp, context2 to the command
* dmabuf, context3 holds the data dmabuf
*/
pcmd = (struct lpfc_dmabuf *) cmdiocbq->context2;
prsp = (struct lpfc_dmabuf *) pcmd->list.next;
lpfc_mbuf_free(phba, pcmd->virt, pcmd->phys);
kfree(pcmd);
lpfc_mbuf_free(phba, prsp->virt, prsp->phys);
kfree(prsp);
cmdiocbq->context2 = NULL;
pbuflist = (struct lpfc_dmabuf *) cmdiocbq->context3;
bpl = (struct ulp_bde64 *) pbuflist->virt;
request_nseg = pci_map_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
for_each_sg(job->request_payload.sg_list, sgel, request_nseg, numbde) {
busaddr = sg_dma_address(sgel);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
bpl->tus.f.bdeSize = sg_dma_len(sgel);
bpl->tus.w = cpu_to_le32(bpl->tus.w);
bpl->addrLow = cpu_to_le32(putPaddrLow(busaddr));
bpl->addrHigh = cpu_to_le32(putPaddrHigh(busaddr));
bpl++;
}
reply_nseg = pci_map_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
for_each_sg(job->reply_payload.sg_list, sgel, reply_nseg, numbde) {
busaddr = sg_dma_address(sgel);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64I;
bpl->tus.f.bdeSize = sg_dma_len(sgel);
bpl->tus.w = cpu_to_le32(bpl->tus.w);
bpl->addrLow = cpu_to_le32(putPaddrLow(busaddr));
bpl->addrHigh = cpu_to_le32(putPaddrHigh(busaddr));
bpl++;
}
cmdiocbq->iocb.un.elsreq64.bdl.bdeSize =
(request_nseg + reply_nseg) * sizeof(struct ulp_bde64);
if (phba->sli_rev == LPFC_SLI_REV4)
cmdiocbq->iocb.ulpContext = phba->sli4_hba.rpi_ids[rpi];
else
cmdiocbq->iocb.ulpContext = rpi;
cmdiocbq->iocb_flag |= LPFC_IO_LIBDFC;
cmdiocbq->context1 = NULL;
cmdiocbq->context2 = NULL;
cmdiocbq->iocb_cmpl = lpfc_bsg_rport_els_cmp;
cmdiocbq->context1 = dd_data;
cmdiocbq->context2 = rspiocbq;
dd_data->type = TYPE_IOCB;
dd_data->context_un.iocb.cmdiocbq = cmdiocbq;
dd_data->context_un.iocb.rspiocbq = rspiocbq;
dd_data->context_un.iocb.set_job = job;
dd_data->context_un.iocb.bmp = NULL;
dd_data->context_un.iocb.ndlp = ndlp;
if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
if (lpfc_readl(phba->HCregaddr, &creg_val)) {
rc = -EIO;
goto linkdown_err;
}
creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
writel(creg_val, phba->HCregaddr);
readl(phba->HCregaddr); /* flush */
}
rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, cmdiocbq, 0);
lpfc_nlp_put(ndlp);
if (rc == IOCB_SUCCESS)
return 0; /* done for now */
else if (rc == IOCB_BUSY)
rc = -EAGAIN;
else
rc = -EIO;
linkdown_err:
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
pci_unmap_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
lpfc_mbuf_free(phba, pbuflist->virt, pbuflist->phys);
lpfc_sli_release_iocbq(phba, cmdiocbq);
free_rspiocbq:
lpfc_sli_release_iocbq(phba, rspiocbq);
free_dd_data:
kfree(dd_data);
no_dd_data:
/* make error code available to userspace */
job->reply->result = rc;
job->dd_data = NULL;
return rc;
}
/**
* lpfc_bsg_event_free - frees an allocated event structure
* @kref: Pointer to a kref.
*
* Called from kref_put. Back cast the kref into an event structure address.
* Free any events to get, delete associated nodes, free any events to see,
* free any data then free the event itself.
**/
static void
lpfc_bsg_event_free(struct kref *kref)
{
struct lpfc_bsg_event *evt = container_of(kref, struct lpfc_bsg_event,
kref);
struct event_data *ed;
list_del(&evt->node);
while (!list_empty(&evt->events_to_get)) {
ed = list_entry(evt->events_to_get.next, typeof(*ed), node);
list_del(&ed->node);
kfree(ed->data);
kfree(ed);
}
while (!list_empty(&evt->events_to_see)) {
ed = list_entry(evt->events_to_see.next, typeof(*ed), node);
list_del(&ed->node);
kfree(ed->data);
kfree(ed);
}
kfree(evt);
}
/**
* lpfc_bsg_event_ref - increments the kref for an event
* @evt: Pointer to an event structure.
**/
static inline void
lpfc_bsg_event_ref(struct lpfc_bsg_event *evt)
{
kref_get(&evt->kref);
}
/**
* lpfc_bsg_event_unref - Uses kref_put to free an event structure
* @evt: Pointer to an event structure.
**/
static inline void
lpfc_bsg_event_unref(struct lpfc_bsg_event *evt)
{
kref_put(&evt->kref, lpfc_bsg_event_free);
}
/**
* lpfc_bsg_event_new - allocate and initialize a event structure
* @ev_mask: Mask of events.
* @ev_reg_id: Event reg id.
* @ev_req_id: Event request id.
**/
static struct lpfc_bsg_event *
lpfc_bsg_event_new(uint32_t ev_mask, int ev_reg_id, uint32_t ev_req_id)
{
struct lpfc_bsg_event *evt = kzalloc(sizeof(*evt), GFP_KERNEL);
if (!evt)
return NULL;
INIT_LIST_HEAD(&evt->events_to_get);
INIT_LIST_HEAD(&evt->events_to_see);
evt->type_mask = ev_mask;
evt->req_id = ev_req_id;
evt->reg_id = ev_reg_id;
evt->wait_time_stamp = jiffies;
init_waitqueue_head(&evt->wq);
kref_init(&evt->kref);
return evt;
}
/**
* diag_cmd_data_free - Frees an lpfc dma buffer extension
* @phba: Pointer to HBA context object.
* @mlist: Pointer to an lpfc dma buffer extension.
**/
static int
diag_cmd_data_free(struct lpfc_hba *phba, struct lpfc_dmabufext *mlist)
{
struct lpfc_dmabufext *mlast;
struct pci_dev *pcidev;
struct list_head head, *curr, *next;
if ((!mlist) || (!lpfc_is_link_up(phba) &&
(phba->link_flag & LS_LOOPBACK_MODE))) {
return 0;
}
pcidev = phba->pcidev;
list_add_tail(&head, &mlist->dma.list);
list_for_each_safe(curr, next, &head) {
mlast = list_entry(curr, struct lpfc_dmabufext , dma.list);
if (mlast->dma.virt)
dma_free_coherent(&pcidev->dev,
mlast->size,
mlast->dma.virt,
mlast->dma.phys);
kfree(mlast);
}
return 0;
}
/**
* lpfc_bsg_ct_unsol_event - process an unsolicited CT command
* @phba:
* @pring:
* @piocbq:
*
* This function is called when an unsolicited CT command is received. It
* forwards the event to any processes registered to receive CT events.
**/
int
lpfc_bsg_ct_unsol_event(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
struct lpfc_iocbq *piocbq)
{
uint32_t evt_req_id = 0;
uint32_t cmd;
uint32_t len;
struct lpfc_dmabuf *dmabuf = NULL;
struct lpfc_bsg_event *evt;
struct event_data *evt_dat = NULL;
struct lpfc_iocbq *iocbq;
size_t offset = 0;
struct list_head head;
struct ulp_bde64 *bde;
dma_addr_t dma_addr;
int i;
struct lpfc_dmabuf *bdeBuf1 = piocbq->context2;
struct lpfc_dmabuf *bdeBuf2 = piocbq->context3;
struct lpfc_hbq_entry *hbqe;
struct lpfc_sli_ct_request *ct_req;
struct fc_bsg_job *job = NULL;
unsigned long flags;
int size = 0;
INIT_LIST_HEAD(&head);
list_add_tail(&head, &piocbq->list);
if (piocbq->iocb.ulpBdeCount == 0 ||
piocbq->iocb.un.cont64[0].tus.f.bdeSize == 0)
goto error_ct_unsol_exit;
if (phba->link_state == LPFC_HBA_ERROR ||
(!(phba->sli.sli_flag & LPFC_SLI_ACTIVE)))
goto error_ct_unsol_exit;
if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)
dmabuf = bdeBuf1;
else {
dma_addr = getPaddr(piocbq->iocb.un.cont64[0].addrHigh,
piocbq->iocb.un.cont64[0].addrLow);
dmabuf = lpfc_sli_ringpostbuf_get(phba, pring, dma_addr);
}
if (dmabuf == NULL)
goto error_ct_unsol_exit;
ct_req = (struct lpfc_sli_ct_request *)dmabuf->virt;
evt_req_id = ct_req->FsType;
cmd = ct_req->CommandResponse.bits.CmdRsp;
len = ct_req->CommandResponse.bits.Size;
if (!(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED))
lpfc_sli_ringpostbuf_put(phba, pring, dmabuf);
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_for_each_entry(evt, &phba->ct_ev_waiters, node) {
if (!(evt->type_mask & FC_REG_CT_EVENT) ||
evt->req_id != evt_req_id)
continue;
lpfc_bsg_event_ref(evt);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
evt_dat = kzalloc(sizeof(*evt_dat), GFP_KERNEL);
if (evt_dat == NULL) {
spin_lock_irqsave(&phba->ct_ev_lock, flags);
lpfc_bsg_event_unref(evt);
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2614 Memory allocation failed for "
"CT event\n");
break;
}
if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
/* take accumulated byte count from the last iocbq */
iocbq = list_entry(head.prev, typeof(*iocbq), list);
evt_dat->len = iocbq->iocb.unsli3.rcvsli3.acc_len;
} else {
list_for_each_entry(iocbq, &head, list) {
for (i = 0; i < iocbq->iocb.ulpBdeCount; i++)
evt_dat->len +=
iocbq->iocb.un.cont64[i].tus.f.bdeSize;
}
}
evt_dat->data = kzalloc(evt_dat->len, GFP_KERNEL);
if (evt_dat->data == NULL) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2615 Memory allocation failed for "
"CT event data, size %d\n",
evt_dat->len);
kfree(evt_dat);
spin_lock_irqsave(&phba->ct_ev_lock, flags);
lpfc_bsg_event_unref(evt);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
goto error_ct_unsol_exit;
}
list_for_each_entry(iocbq, &head, list) {
size = 0;
if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
bdeBuf1 = iocbq->context2;
bdeBuf2 = iocbq->context3;
}
for (i = 0; i < iocbq->iocb.ulpBdeCount; i++) {
if (phba->sli3_options &
LPFC_SLI3_HBQ_ENABLED) {
if (i == 0) {
hbqe = (struct lpfc_hbq_entry *)
&iocbq->iocb.un.ulpWord[0];
size = hbqe->bde.tus.f.bdeSize;
dmabuf = bdeBuf1;
} else if (i == 1) {
hbqe = (struct lpfc_hbq_entry *)
&iocbq->iocb.unsli3.
sli3Words[4];
size = hbqe->bde.tus.f.bdeSize;
dmabuf = bdeBuf2;
}
if ((offset + size) > evt_dat->len)
size = evt_dat->len - offset;
} else {
size = iocbq->iocb.un.cont64[i].
tus.f.bdeSize;
bde = &iocbq->iocb.un.cont64[i];
dma_addr = getPaddr(bde->addrHigh,
bde->addrLow);
dmabuf = lpfc_sli_ringpostbuf_get(phba,
pring, dma_addr);
}
if (!dmabuf) {
lpfc_printf_log(phba, KERN_ERR,
LOG_LIBDFC, "2616 No dmabuf "
"found for iocbq 0x%p\n",
iocbq);
kfree(evt_dat->data);
kfree(evt_dat);
spin_lock_irqsave(&phba->ct_ev_lock,
flags);
lpfc_bsg_event_unref(evt);
spin_unlock_irqrestore(
&phba->ct_ev_lock, flags);
goto error_ct_unsol_exit;
}
memcpy((char *)(evt_dat->data) + offset,
dmabuf->virt, size);
offset += size;
if (evt_req_id != SLI_CT_ELX_LOOPBACK &&
!(phba->sli3_options &
LPFC_SLI3_HBQ_ENABLED)) {
lpfc_sli_ringpostbuf_put(phba, pring,
dmabuf);
} else {
switch (cmd) {
case ELX_LOOPBACK_DATA:
if (phba->sli_rev <
LPFC_SLI_REV4)
diag_cmd_data_free(phba,
(struct lpfc_dmabufext
*)dmabuf);
break;
case ELX_LOOPBACK_XRI_SETUP:
if ((phba->sli_rev ==
LPFC_SLI_REV2) ||
(phba->sli3_options &
LPFC_SLI3_HBQ_ENABLED
)) {
lpfc_in_buf_free(phba,
dmabuf);
} else {
lpfc_post_buffer(phba,
pring,
1);
}
break;
default:
if (!(phba->sli3_options &
LPFC_SLI3_HBQ_ENABLED))
lpfc_post_buffer(phba,
pring,
1);
break;
}
}
}
}
spin_lock_irqsave(&phba->ct_ev_lock, flags);
if (phba->sli_rev == LPFC_SLI_REV4) {
evt_dat->immed_dat = phba->ctx_idx;
phba->ctx_idx = (phba->ctx_idx + 1) % 64;
/* Provide warning for over-run of the ct_ctx array */
if (phba->ct_ctx[evt_dat->immed_dat].flags &
UNSOL_VALID)
lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
"2717 CT context array entry "
"[%d] over-run: oxid:x%x, "
"sid:x%x\n", phba->ctx_idx,
phba->ct_ctx[
evt_dat->immed_dat].oxid,
phba->ct_ctx[
evt_dat->immed_dat].SID);
phba->ct_ctx[evt_dat->immed_dat].rxid =
piocbq->iocb.ulpContext;
phba->ct_ctx[evt_dat->immed_dat].oxid =
piocbq->iocb.unsli3.rcvsli3.ox_id;
phba->ct_ctx[evt_dat->immed_dat].SID =
piocbq->iocb.un.rcvels.remoteID;
phba->ct_ctx[evt_dat->immed_dat].flags = UNSOL_VALID;
} else
evt_dat->immed_dat = piocbq->iocb.ulpContext;
evt_dat->type = FC_REG_CT_EVENT;
list_add(&evt_dat->node, &evt->events_to_see);
if (evt_req_id == SLI_CT_ELX_LOOPBACK) {
wake_up_interruptible(&evt->wq);
lpfc_bsg_event_unref(evt);
break;
}
list_move(evt->events_to_see.prev, &evt->events_to_get);
lpfc_bsg_event_unref(evt);
job = evt->set_job;
evt->set_job = NULL;
if (job) {
job->reply->reply_payload_rcv_len = size;
/* make error code available to userspace */
job->reply->result = 0;
job->dd_data = NULL;
/* complete the job back to userspace */
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
job->job_done(job);
spin_lock_irqsave(&phba->ct_ev_lock, flags);
}
}
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
error_ct_unsol_exit:
if (!list_empty(&head))
list_del(&head);
if ((phba->sli_rev < LPFC_SLI_REV4) &&
(evt_req_id == SLI_CT_ELX_LOOPBACK))
return 0;
return 1;
}
/**
* lpfc_bsg_hba_set_event - process a SET_EVENT bsg vendor command
* @job: SET_EVENT fc_bsg_job
**/
static int
lpfc_bsg_hba_set_event(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct set_ct_event *event_req;
struct lpfc_bsg_event *evt;
int rc = 0;
struct bsg_job_data *dd_data = NULL;
uint32_t ev_mask;
unsigned long flags;
if (job->request_len <
sizeof(struct fc_bsg_request) + sizeof(struct set_ct_event)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2612 Received SET_CT_EVENT below minimum "
"size\n");
rc = -EINVAL;
goto job_error;
}
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (dd_data == NULL) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2734 Failed allocation of dd_data\n");
rc = -ENOMEM;
goto job_error;
}
event_req = (struct set_ct_event *)
job->request->rqst_data.h_vendor.vendor_cmd;
ev_mask = ((uint32_t)(unsigned long)event_req->type_mask &
FC_REG_EVENT_MASK);
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_for_each_entry(evt, &phba->ct_ev_waiters, node) {
if (evt->reg_id == event_req->ev_reg_id) {
lpfc_bsg_event_ref(evt);
evt->wait_time_stamp = jiffies;
break;
}
}
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
if (&evt->node == &phba->ct_ev_waiters) {
/* no event waiting struct yet - first call */
evt = lpfc_bsg_event_new(ev_mask, event_req->ev_reg_id,
event_req->ev_req_id);
if (!evt) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2617 Failed allocation of event "
"waiter\n");
rc = -ENOMEM;
goto job_error;
}
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_add(&evt->node, &phba->ct_ev_waiters);
lpfc_bsg_event_ref(evt);
evt->wait_time_stamp = jiffies;
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
}
spin_lock_irqsave(&phba->ct_ev_lock, flags);
evt->waiting = 1;
dd_data->type = TYPE_EVT;
dd_data->context_un.evt = evt;
evt->set_job = job; /* for unsolicited command */
job->dd_data = dd_data; /* for fc transport timeout callback*/
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return 0; /* call job done later */
job_error:
if (dd_data != NULL)
kfree(dd_data);
job->dd_data = NULL;
return rc;
}
/**
* lpfc_bsg_hba_get_event - process a GET_EVENT bsg vendor command
* @job: GET_EVENT fc_bsg_job
**/
static int
lpfc_bsg_hba_get_event(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct get_ct_event *event_req;
struct get_ct_event_reply *event_reply;
struct lpfc_bsg_event *evt;
struct event_data *evt_dat = NULL;
unsigned long flags;
uint32_t rc = 0;
if (job->request_len <
sizeof(struct fc_bsg_request) + sizeof(struct get_ct_event)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2613 Received GET_CT_EVENT request below "
"minimum size\n");
rc = -EINVAL;
goto job_error;
}
event_req = (struct get_ct_event *)
job->request->rqst_data.h_vendor.vendor_cmd;
event_reply = (struct get_ct_event_reply *)
job->reply->reply_data.vendor_reply.vendor_rsp;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_for_each_entry(evt, &phba->ct_ev_waiters, node) {
if (evt->reg_id == event_req->ev_reg_id) {
if (list_empty(&evt->events_to_get))
break;
lpfc_bsg_event_ref(evt);
evt->wait_time_stamp = jiffies;
evt_dat = list_entry(evt->events_to_get.prev,
struct event_data, node);
list_del(&evt_dat->node);
break;
}
}
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
/* The app may continue to ask for event data until it gets
* an error indicating that there isn't anymore
*/
if (evt_dat == NULL) {
job->reply->reply_payload_rcv_len = 0;
rc = -ENOENT;
goto job_error;
}
if (evt_dat->len > job->request_payload.payload_len) {
evt_dat->len = job->request_payload.payload_len;
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2618 Truncated event data at %d "
"bytes\n",
job->request_payload.payload_len);
}
event_reply->type = evt_dat->type;
event_reply->immed_data = evt_dat->immed_dat;
if (evt_dat->len > 0)
job->reply->reply_payload_rcv_len =
sg_copy_from_buffer(job->request_payload.sg_list,
job->request_payload.sg_cnt,
evt_dat->data, evt_dat->len);
else
job->reply->reply_payload_rcv_len = 0;
if (evt_dat) {
kfree(evt_dat->data);
kfree(evt_dat);
}
spin_lock_irqsave(&phba->ct_ev_lock, flags);
lpfc_bsg_event_unref(evt);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
job->dd_data = NULL;
job->reply->result = 0;
job->job_done(job);
return 0;
job_error:
job->dd_data = NULL;
job->reply->result = rc;
return rc;
}
/**
* lpfc_issue_ct_rsp_cmp - lpfc_issue_ct_rsp's completion handler
* @phba: Pointer to HBA context object.
* @cmdiocbq: Pointer to command iocb.
* @rspiocbq: Pointer to response iocb.
*
* This function is the completion handler for iocbs issued using
* lpfc_issue_ct_rsp_cmp function. This function is called by the
* ring event handler function without any lock held. This function
* can be called from both worker thread context and interrupt
* context. This function also can be called from other thread which
* cleans up the SLI layer objects.
* This function copy the contents of the response iocb to the
* response iocb memory object provided by the caller of
* lpfc_sli_issue_iocb_wait and then wakes up the thread which
* sleeps for the iocb completion.
**/
static void
lpfc_issue_ct_rsp_cmp(struct lpfc_hba *phba,
struct lpfc_iocbq *cmdiocbq,
struct lpfc_iocbq *rspiocbq)
{
struct bsg_job_data *dd_data;
struct fc_bsg_job *job;
IOCB_t *rsp;
struct lpfc_dmabuf *bmp;
struct lpfc_nodelist *ndlp;
unsigned long flags;
int rc = 0;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
dd_data = cmdiocbq->context2;
/* normal completion and timeout crossed paths, already done */
if (!dd_data) {
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
job = dd_data->context_un.iocb.set_job;
bmp = dd_data->context_un.iocb.bmp;
rsp = &rspiocbq->iocb;
ndlp = dd_data->context_un.iocb.ndlp;
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
if (rsp->ulpStatus) {
if (rsp->ulpStatus == IOSTAT_LOCAL_REJECT) {
switch (rsp->un.ulpWord[4] & 0xff) {
case IOERR_SEQUENCE_TIMEOUT:
rc = -ETIMEDOUT;
break;
case IOERR_INVALID_RPI:
rc = -EFAULT;
break;
default:
rc = -EACCES;
break;
}
} else
rc = -EACCES;
} else
job->reply->reply_payload_rcv_len =
rsp->un.genreq64.bdl.bdeSize;
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
lpfc_sli_release_iocbq(phba, cmdiocbq);
lpfc_nlp_put(ndlp);
kfree(bmp);
kfree(dd_data);
/* make error code available to userspace */
job->reply->result = rc;
job->dd_data = NULL;
/* complete the job back to userspace */
job->job_done(job);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
/**
* lpfc_issue_ct_rsp - issue a ct response
* @phba: Pointer to HBA context object.
* @job: Pointer to the job object.
* @tag: tag index value into the ports context exchange array.
* @bmp: Pointer to a dma buffer descriptor.
* @num_entry: Number of enties in the bde.
**/
static int
lpfc_issue_ct_rsp(struct lpfc_hba *phba, struct fc_bsg_job *job, uint32_t tag,
struct lpfc_dmabuf *bmp, int num_entry)
{
IOCB_t *icmd;
struct lpfc_iocbq *ctiocb = NULL;
int rc = 0;
struct lpfc_nodelist *ndlp = NULL;
struct bsg_job_data *dd_data;
uint32_t creg_val;
/* allocate our bsg tracking structure */
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2736 Failed allocation of dd_data\n");
rc = -ENOMEM;
goto no_dd_data;
}
/* Allocate buffer for command iocb */
ctiocb = lpfc_sli_get_iocbq(phba);
if (!ctiocb) {
rc = -ENOMEM;
goto no_ctiocb;
}
icmd = &ctiocb->iocb;
icmd->un.xseq64.bdl.ulpIoTag32 = 0;
icmd->un.xseq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
icmd->un.xseq64.bdl.addrLow = putPaddrLow(bmp->phys);
icmd->un.xseq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
icmd->un.xseq64.bdl.bdeSize = (num_entry * sizeof(struct ulp_bde64));
icmd->un.xseq64.w5.hcsw.Fctl = (LS | LA);
icmd->un.xseq64.w5.hcsw.Dfctl = 0;
icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_DD_SOL_CTL;
icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_CT;
/* Fill in rest of iocb */
icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CX;
icmd->ulpBdeCount = 1;
icmd->ulpLe = 1;
icmd->ulpClass = CLASS3;
if (phba->sli_rev == LPFC_SLI_REV4) {
/* Do not issue unsol response if oxid not marked as valid */
if (!(phba->ct_ctx[tag].flags & UNSOL_VALID)) {
rc = IOCB_ERROR;
goto issue_ct_rsp_exit;
}
icmd->ulpContext = phba->ct_ctx[tag].rxid;
icmd->unsli3.rcvsli3.ox_id = phba->ct_ctx[tag].oxid;
ndlp = lpfc_findnode_did(phba->pport, phba->ct_ctx[tag].SID);
if (!ndlp) {
lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
"2721 ndlp null for oxid %x SID %x\n",
icmd->ulpContext,
phba->ct_ctx[tag].SID);
rc = IOCB_ERROR;
goto issue_ct_rsp_exit;
}
/* Check if the ndlp is active */
if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)) {
rc = -IOCB_ERROR;
goto issue_ct_rsp_exit;
}
/* get a refernece count so the ndlp doesn't go away while
* we respond
*/
if (!lpfc_nlp_get(ndlp)) {
rc = -IOCB_ERROR;
goto issue_ct_rsp_exit;
}
icmd->un.ulpWord[3] =
phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
/* The exchange is done, mark the entry as invalid */
phba->ct_ctx[tag].flags &= ~UNSOL_VALID;
} else
icmd->ulpContext = (ushort) tag;
icmd->ulpTimeout = phba->fc_ratov * 2;
/* Xmit CT response on exchange <xid> */
lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
"2722 Xmit CT response on exchange x%x Data: x%x x%x x%x\n",
icmd->ulpContext, icmd->ulpIoTag, tag, phba->link_state);
ctiocb->iocb_cmpl = NULL;
ctiocb->iocb_flag |= LPFC_IO_LIBDFC;
ctiocb->vport = phba->pport;
ctiocb->context3 = bmp;
ctiocb->iocb_cmpl = lpfc_issue_ct_rsp_cmp;
ctiocb->context2 = dd_data;
ctiocb->context1 = ndlp;
dd_data->type = TYPE_IOCB;
dd_data->context_un.iocb.cmdiocbq = ctiocb;
dd_data->context_un.iocb.rspiocbq = NULL;
dd_data->context_un.iocb.set_job = job;
dd_data->context_un.iocb.bmp = bmp;
dd_data->context_un.iocb.ndlp = ndlp;
if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
if (lpfc_readl(phba->HCregaddr, &creg_val)) {
rc = -IOCB_ERROR;
goto issue_ct_rsp_exit;
}
creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
writel(creg_val, phba->HCregaddr);
readl(phba->HCregaddr); /* flush */
}
rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
if (rc == IOCB_SUCCESS)
return 0; /* done for now */
issue_ct_rsp_exit:
lpfc_sli_release_iocbq(phba, ctiocb);
no_ctiocb:
kfree(dd_data);
no_dd_data:
return rc;
}
/**
* lpfc_bsg_send_mgmt_rsp - process a SEND_MGMT_RESP bsg vendor command
* @job: SEND_MGMT_RESP fc_bsg_job
**/
static int
lpfc_bsg_send_mgmt_rsp(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct send_mgmt_resp *mgmt_resp = (struct send_mgmt_resp *)
job->request->rqst_data.h_vendor.vendor_cmd;
struct ulp_bde64 *bpl;
struct lpfc_dmabuf *bmp = NULL;
struct scatterlist *sgel = NULL;
int request_nseg;
int numbde;
dma_addr_t busaddr;
uint32_t tag = mgmt_resp->tag;
unsigned long reqbfrcnt =
(unsigned long)job->request_payload.payload_len;
int rc = 0;
/* in case no data is transferred */
job->reply->reply_payload_rcv_len = 0;
if (!reqbfrcnt || (reqbfrcnt > (80 * BUF_SZ_4K))) {
rc = -ERANGE;
goto send_mgmt_rsp_exit;
}
bmp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (!bmp) {
rc = -ENOMEM;
goto send_mgmt_rsp_exit;
}
bmp->virt = lpfc_mbuf_alloc(phba, 0, &bmp->phys);
if (!bmp->virt) {
rc = -ENOMEM;
goto send_mgmt_rsp_free_bmp;
}
INIT_LIST_HEAD(&bmp->list);
bpl = (struct ulp_bde64 *) bmp->virt;
request_nseg = pci_map_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
for_each_sg(job->request_payload.sg_list, sgel, request_nseg, numbde) {
busaddr = sg_dma_address(sgel);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
bpl->tus.f.bdeSize = sg_dma_len(sgel);
bpl->tus.w = cpu_to_le32(bpl->tus.w);
bpl->addrLow = cpu_to_le32(putPaddrLow(busaddr));
bpl->addrHigh = cpu_to_le32(putPaddrHigh(busaddr));
bpl++;
}
rc = lpfc_issue_ct_rsp(phba, job, tag, bmp, request_nseg);
if (rc == IOCB_SUCCESS)
return 0; /* done for now */
/* TBD need to handle a timeout */
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
rc = -EACCES;
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
send_mgmt_rsp_free_bmp:
kfree(bmp);
send_mgmt_rsp_exit:
/* make error code available to userspace */
job->reply->result = rc;
job->dd_data = NULL;
return rc;
}
/**
* lpfc_bsg_diag_mode_enter - process preparing into device diag loopback mode
* @phba: Pointer to HBA context object.
*
* This function is responsible for preparing driver for diag loopback
* on device.
*/
static int
lpfc_bsg_diag_mode_enter(struct lpfc_hba *phba)
{
struct lpfc_vport **vports;
struct Scsi_Host *shost;
struct lpfc_sli *psli;
struct lpfc_sli_ring *pring;
int i = 0;
psli = &phba->sli;
if (!psli)
return -ENODEV;
pring = &psli->ring[LPFC_FCP_RING];
if (!pring)
return -ENODEV;
if ((phba->link_state == LPFC_HBA_ERROR) ||
(psli->sli_flag & LPFC_BLOCK_MGMT_IO) ||
(!(psli->sli_flag & LPFC_SLI_ACTIVE)))
return -EACCES;
vports = lpfc_create_vport_work_array(phba);
if (vports) {
for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
shost = lpfc_shost_from_vport(vports[i]);
scsi_block_requests(shost);
}
lpfc_destroy_vport_work_array(phba, vports);
} else {
shost = lpfc_shost_from_vport(phba->pport);
scsi_block_requests(shost);
}
while (pring->txcmplq_cnt) {
if (i++ > 500) /* wait up to 5 seconds */
break;
msleep(10);
}
return 0;
}
/**
* lpfc_bsg_diag_mode_exit - exit process from device diag loopback mode
* @phba: Pointer to HBA context object.
*
* This function is responsible for driver exit processing of setting up
* diag loopback mode on device.
*/
static void
lpfc_bsg_diag_mode_exit(struct lpfc_hba *phba)
{
struct Scsi_Host *shost;
struct lpfc_vport **vports;
int i;
vports = lpfc_create_vport_work_array(phba);
if (vports) {
for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
shost = lpfc_shost_from_vport(vports[i]);
scsi_unblock_requests(shost);
}
lpfc_destroy_vport_work_array(phba, vports);
} else {
shost = lpfc_shost_from_vport(phba->pport);
scsi_unblock_requests(shost);
}
return;
}
/**
* lpfc_sli3_bsg_diag_loopback_mode - process an sli3 bsg vendor command
* @phba: Pointer to HBA context object.
* @job: LPFC_BSG_VENDOR_DIAG_MODE
*
* This function is responsible for placing an sli3 port into diagnostic
* loopback mode in order to perform a diagnostic loopback test.
* All new scsi requests are blocked, a small delay is used to allow the
* scsi requests to complete then the link is brought down. If the link is
* is placed in loopback mode then scsi requests are again allowed
* so the scsi mid-layer doesn't give up on the port.
* All of this is done in-line.
*/
static int
lpfc_sli3_bsg_diag_loopback_mode(struct lpfc_hba *phba, struct fc_bsg_job *job)
{
struct diag_mode_set *loopback_mode;
uint32_t link_flags;
uint32_t timeout;
LPFC_MBOXQ_t *pmboxq = NULL;
int mbxstatus = MBX_SUCCESS;
int i = 0;
int rc = 0;
/* no data to return just the return code */
job->reply->reply_payload_rcv_len = 0;
if (job->request_len < sizeof(struct fc_bsg_request) +
sizeof(struct diag_mode_set)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2738 Received DIAG MODE request size:%d "
"below the minimum size:%d\n",
job->request_len,
(int)(sizeof(struct fc_bsg_request) +
sizeof(struct diag_mode_set)));
rc = -EINVAL;
goto job_error;
}
rc = lpfc_bsg_diag_mode_enter(phba);
if (rc)
goto job_error;
/* bring the link to diagnostic mode */
loopback_mode = (struct diag_mode_set *)
job->request->rqst_data.h_vendor.vendor_cmd;
link_flags = loopback_mode->type;
timeout = loopback_mode->timeout * 100;
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq) {
rc = -ENOMEM;
goto loopback_mode_exit;
}
memset((void *)pmboxq, 0, sizeof(LPFC_MBOXQ_t));
pmboxq->u.mb.mbxCommand = MBX_DOWN_LINK;
pmboxq->u.mb.mbxOwner = OWN_HOST;
mbxstatus = lpfc_sli_issue_mbox_wait(phba, pmboxq, LPFC_MBOX_TMO);
if ((mbxstatus == MBX_SUCCESS) && (pmboxq->u.mb.mbxStatus == 0)) {
/* wait for link down before proceeding */
i = 0;
while (phba->link_state != LPFC_LINK_DOWN) {
if (i++ > timeout) {
rc = -ETIMEDOUT;
goto loopback_mode_exit;
}
msleep(10);
}
memset((void *)pmboxq, 0, sizeof(LPFC_MBOXQ_t));
if (link_flags == INTERNAL_LOOP_BACK)
pmboxq->u.mb.un.varInitLnk.link_flags = FLAGS_LOCAL_LB;
else
pmboxq->u.mb.un.varInitLnk.link_flags =
FLAGS_TOPOLOGY_MODE_LOOP;
pmboxq->u.mb.mbxCommand = MBX_INIT_LINK;
pmboxq->u.mb.mbxOwner = OWN_HOST;
mbxstatus = lpfc_sli_issue_mbox_wait(phba, pmboxq,
LPFC_MBOX_TMO);
if ((mbxstatus != MBX_SUCCESS) || (pmboxq->u.mb.mbxStatus))
rc = -ENODEV;
else {
spin_lock_irq(&phba->hbalock);
phba->link_flag |= LS_LOOPBACK_MODE;
spin_unlock_irq(&phba->hbalock);
/* wait for the link attention interrupt */
msleep(100);
i = 0;
while (phba->link_state != LPFC_HBA_READY) {
if (i++ > timeout) {
rc = -ETIMEDOUT;
break;
}
msleep(10);
}
}
} else
rc = -ENODEV;
loopback_mode_exit:
lpfc_bsg_diag_mode_exit(phba);
/*
* Let SLI layer release mboxq if mbox command completed after timeout.
*/
if (pmboxq && mbxstatus != MBX_TIMEOUT)
mempool_free(pmboxq, phba->mbox_mem_pool);
job_error:
/* make error code available to userspace */
job->reply->result = rc;
/* complete the job back to userspace if no error */
if (rc == 0)
job->job_done(job);
return rc;
}
/**
* lpfc_sli4_bsg_set_link_diag_state - set sli4 link diag state
* @phba: Pointer to HBA context object.
* @diag: Flag for set link to diag or nomral operation state.
*
* This function is responsible for issuing a sli4 mailbox command for setting
* link to either diag state or normal operation state.
*/
static int
lpfc_sli4_bsg_set_link_diag_state(struct lpfc_hba *phba, uint32_t diag)
{
LPFC_MBOXQ_t *pmboxq;
struct lpfc_mbx_set_link_diag_state *link_diag_state;
uint32_t req_len, alloc_len;
int mbxstatus = MBX_SUCCESS, rc;
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq)
return -ENOMEM;
req_len = (sizeof(struct lpfc_mbx_set_link_diag_state) -
sizeof(struct lpfc_sli4_cfg_mhdr));
alloc_len = lpfc_sli4_config(phba, pmboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
LPFC_MBOX_OPCODE_FCOE_LINK_DIAG_STATE,
req_len, LPFC_SLI4_MBX_EMBED);
if (alloc_len != req_len) {
rc = -ENOMEM;
goto link_diag_state_set_out;
}
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3128 Set link to diagnostic state:x%x (x%x/x%x)\n",
diag, phba->sli4_hba.lnk_info.lnk_tp,
phba->sli4_hba.lnk_info.lnk_no);
link_diag_state = &pmboxq->u.mqe.un.link_diag_state;
bf_set(lpfc_mbx_set_diag_state_link_num, &link_diag_state->u.req,
phba->sli4_hba.lnk_info.lnk_no);
bf_set(lpfc_mbx_set_diag_state_link_type, &link_diag_state->u.req,
phba->sli4_hba.lnk_info.lnk_tp);
if (diag)
bf_set(lpfc_mbx_set_diag_state_diag,
&link_diag_state->u.req, 1);
else
bf_set(lpfc_mbx_set_diag_state_diag,
&link_diag_state->u.req, 0);
mbxstatus = lpfc_sli_issue_mbox_wait(phba, pmboxq, LPFC_MBOX_TMO);
if ((mbxstatus == MBX_SUCCESS) && (pmboxq->u.mb.mbxStatus == 0))
rc = 0;
else
rc = -ENODEV;
link_diag_state_set_out:
if (pmboxq && (mbxstatus != MBX_TIMEOUT))
mempool_free(pmboxq, phba->mbox_mem_pool);
return rc;
}
/**
* lpfc_sli4_bsg_set_internal_loopback - set sli4 internal loopback diagnostic
* @phba: Pointer to HBA context object.
*
* This function is responsible for issuing a sli4 mailbox command for setting
* up internal loopback diagnostic.
*/
static int
lpfc_sli4_bsg_set_internal_loopback(struct lpfc_hba *phba)
{
LPFC_MBOXQ_t *pmboxq;
uint32_t req_len, alloc_len;
struct lpfc_mbx_set_link_diag_loopback *link_diag_loopback;
int mbxstatus = MBX_SUCCESS, rc = 0;
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq)
return -ENOMEM;
req_len = (sizeof(struct lpfc_mbx_set_link_diag_loopback) -
sizeof(struct lpfc_sli4_cfg_mhdr));
alloc_len = lpfc_sli4_config(phba, pmboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
LPFC_MBOX_OPCODE_FCOE_LINK_DIAG_LOOPBACK,
req_len, LPFC_SLI4_MBX_EMBED);
if (alloc_len != req_len) {
mempool_free(pmboxq, phba->mbox_mem_pool);
return -ENOMEM;
}
link_diag_loopback = &pmboxq->u.mqe.un.link_diag_loopback;
bf_set(lpfc_mbx_set_diag_state_link_num,
&link_diag_loopback->u.req, phba->sli4_hba.lnk_info.lnk_no);
bf_set(lpfc_mbx_set_diag_state_link_type,
&link_diag_loopback->u.req, phba->sli4_hba.lnk_info.lnk_tp);
bf_set(lpfc_mbx_set_diag_lpbk_type, &link_diag_loopback->u.req,
LPFC_DIAG_LOOPBACK_TYPE_INTERNAL);
mbxstatus = lpfc_sli_issue_mbox_wait(phba, pmboxq, LPFC_MBOX_TMO);
if ((mbxstatus != MBX_SUCCESS) || (pmboxq->u.mb.mbxStatus)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"3127 Failed setup loopback mode mailbox "
"command, rc:x%x, status:x%x\n", mbxstatus,
pmboxq->u.mb.mbxStatus);
rc = -ENODEV;
}
if (pmboxq && (mbxstatus != MBX_TIMEOUT))
mempool_free(pmboxq, phba->mbox_mem_pool);
return rc;
}
/**
* lpfc_sli4_diag_fcport_reg_setup - setup port registrations for diagnostic
* @phba: Pointer to HBA context object.
*
* This function set up SLI4 FC port registrations for diagnostic run, which
* includes all the rpis, vfi, and also vpi.
*/
static int
lpfc_sli4_diag_fcport_reg_setup(struct lpfc_hba *phba)
{
int rc;
if (phba->pport->fc_flag & FC_VFI_REGISTERED) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"3136 Port still had vfi registered: "
"mydid:x%x, fcfi:%d, vfi:%d, vpi:%d\n",
phba->pport->fc_myDID, phba->fcf.fcfi,
phba->sli4_hba.vfi_ids[phba->pport->vfi],
phba->vpi_ids[phba->pport->vpi]);
return -EINVAL;
}
rc = lpfc_issue_reg_vfi(phba->pport);
return rc;
}
/**
* lpfc_sli4_bsg_diag_loopback_mode - process an sli4 bsg vendor command
* @phba: Pointer to HBA context object.
* @job: LPFC_BSG_VENDOR_DIAG_MODE
*
* This function is responsible for placing an sli4 port into diagnostic
* loopback mode in order to perform a diagnostic loopback test.
*/
static int
lpfc_sli4_bsg_diag_loopback_mode(struct lpfc_hba *phba, struct fc_bsg_job *job)
{
struct diag_mode_set *loopback_mode;
uint32_t link_flags, timeout;
int i, rc = 0;
/* no data to return just the return code */
job->reply->reply_payload_rcv_len = 0;
if (job->request_len < sizeof(struct fc_bsg_request) +
sizeof(struct diag_mode_set)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"3011 Received DIAG MODE request size:%d "
"below the minimum size:%d\n",
job->request_len,
(int)(sizeof(struct fc_bsg_request) +
sizeof(struct diag_mode_set)));
rc = -EINVAL;
goto job_error;
}
rc = lpfc_bsg_diag_mode_enter(phba);
if (rc)
goto job_error;
/* indicate we are in loobpack diagnostic mode */
spin_lock_irq(&phba->hbalock);
phba->link_flag |= LS_LOOPBACK_MODE;
spin_unlock_irq(&phba->hbalock);
/* reset port to start frome scratch */
rc = lpfc_selective_reset(phba);
if (rc)
goto job_error;
/* bring the link to diagnostic mode */
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3129 Bring link to diagnostic state.\n");
loopback_mode = (struct diag_mode_set *)
job->request->rqst_data.h_vendor.vendor_cmd;
link_flags = loopback_mode->type;
timeout = loopback_mode->timeout * 100;
rc = lpfc_sli4_bsg_set_link_diag_state(phba, 1);
if (rc) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"3130 Failed to bring link to diagnostic "
"state, rc:x%x\n", rc);
goto loopback_mode_exit;
}
/* wait for link down before proceeding */
i = 0;
while (phba->link_state != LPFC_LINK_DOWN) {
if (i++ > timeout) {
rc = -ETIMEDOUT;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3131 Timeout waiting for link to "
"diagnostic mode, timeout:%d ms\n",
timeout * 10);
goto loopback_mode_exit;
}
msleep(10);
}
/* set up loopback mode */
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3132 Set up loopback mode:x%x\n", link_flags);
if (link_flags == INTERNAL_LOOP_BACK)
rc = lpfc_sli4_bsg_set_internal_loopback(phba);
else if (link_flags == EXTERNAL_LOOP_BACK)
rc = lpfc_hba_init_link_fc_topology(phba,
FLAGS_TOPOLOGY_MODE_PT_PT,
MBX_NOWAIT);
else {
rc = -EINVAL;
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"3141 Loopback mode:x%x not supported\n",
link_flags);
goto loopback_mode_exit;
}
if (!rc) {
/* wait for the link attention interrupt */
msleep(100);
i = 0;
while (phba->link_state < LPFC_LINK_UP) {
if (i++ > timeout) {
rc = -ETIMEDOUT;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3137 Timeout waiting for link up "
"in loopback mode, timeout:%d ms\n",
timeout * 10);
break;
}
msleep(10);
}
}
/* port resource registration setup for loopback diagnostic */
if (!rc) {
/* set up a none zero myDID for loopback test */
phba->pport->fc_myDID = 1;
rc = lpfc_sli4_diag_fcport_reg_setup(phba);
} else
goto loopback_mode_exit;
if (!rc) {
/* wait for the port ready */
msleep(100);
i = 0;
while (phba->link_state != LPFC_HBA_READY) {
if (i++ > timeout) {
rc = -ETIMEDOUT;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3133 Timeout waiting for port "
"loopback mode ready, timeout:%d ms\n",
timeout * 10);
break;
}
msleep(10);
}
}
loopback_mode_exit:
/* clear loopback diagnostic mode */
if (rc) {
spin_lock_irq(&phba->hbalock);
phba->link_flag &= ~LS_LOOPBACK_MODE;
spin_unlock_irq(&phba->hbalock);
}
lpfc_bsg_diag_mode_exit(phba);
job_error:
/* make error code available to userspace */
job->reply->result = rc;
/* complete the job back to userspace if no error */
if (rc == 0)
job->job_done(job);
return rc;
}
/**
* lpfc_bsg_diag_loopback_mode - bsg vendor command for diag loopback mode
* @job: LPFC_BSG_VENDOR_DIAG_MODE
*
* This function is responsible for responding to check and dispatch bsg diag
* command from the user to proper driver action routines.
*/
static int
lpfc_bsg_diag_loopback_mode(struct fc_bsg_job *job)
{
struct Scsi_Host *shost;
struct lpfc_vport *vport;
struct lpfc_hba *phba;
int rc;
shost = job->shost;
if (!shost)
return -ENODEV;
vport = (struct lpfc_vport *)job->shost->hostdata;
if (!vport)
return -ENODEV;
phba = vport->phba;
if (!phba)
return -ENODEV;
if (phba->sli_rev < LPFC_SLI_REV4)
rc = lpfc_sli3_bsg_diag_loopback_mode(phba, job);
else if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
LPFC_SLI_INTF_IF_TYPE_2)
rc = lpfc_sli4_bsg_diag_loopback_mode(phba, job);
else
rc = -ENODEV;
return rc;
}
/**
* lpfc_sli4_bsg_diag_mode_end - sli4 bsg vendor command for ending diag mode
* @job: LPFC_BSG_VENDOR_DIAG_MODE_END
*
* This function is responsible for responding to check and dispatch bsg diag
* command from the user to proper driver action routines.
*/
static int
lpfc_sli4_bsg_diag_mode_end(struct fc_bsg_job *job)
{
struct Scsi_Host *shost;
struct lpfc_vport *vport;
struct lpfc_hba *phba;
struct diag_mode_set *loopback_mode_end_cmd;
uint32_t timeout;
int rc, i;
shost = job->shost;
if (!shost)
return -ENODEV;
vport = (struct lpfc_vport *)job->shost->hostdata;
if (!vport)
return -ENODEV;
phba = vport->phba;
if (!phba)
return -ENODEV;
if (phba->sli_rev < LPFC_SLI_REV4)
return -ENODEV;
if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) !=
LPFC_SLI_INTF_IF_TYPE_2)
return -ENODEV;
/* clear loopback diagnostic mode */
spin_lock_irq(&phba->hbalock);
phba->link_flag &= ~LS_LOOPBACK_MODE;
spin_unlock_irq(&phba->hbalock);
loopback_mode_end_cmd = (struct diag_mode_set *)
job->request->rqst_data.h_vendor.vendor_cmd;
timeout = loopback_mode_end_cmd->timeout * 100;
rc = lpfc_sli4_bsg_set_link_diag_state(phba, 0);
if (rc) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"3139 Failed to bring link to diagnostic "
"state, rc:x%x\n", rc);
goto loopback_mode_end_exit;
}
/* wait for link down before proceeding */
i = 0;
while (phba->link_state != LPFC_LINK_DOWN) {
if (i++ > timeout) {
rc = -ETIMEDOUT;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3140 Timeout waiting for link to "
"diagnostic mode_end, timeout:%d ms\n",
timeout * 10);
/* there is nothing much we can do here */
break;
}
msleep(10);
}
/* reset port resource registrations */
rc = lpfc_selective_reset(phba);
phba->pport->fc_myDID = 0;
loopback_mode_end_exit:
/* make return code available to userspace */
job->reply->result = rc;
/* complete the job back to userspace if no error */
if (rc == 0)
job->job_done(job);
return rc;
}
/**
* lpfc_sli4_bsg_link_diag_test - sli4 bsg vendor command for diag link test
* @job: LPFC_BSG_VENDOR_DIAG_LINK_TEST
*
* This function is to perform SLI4 diag link test request from the user
* applicaiton.
*/
static int
lpfc_sli4_bsg_link_diag_test(struct fc_bsg_job *job)
{
struct Scsi_Host *shost;
struct lpfc_vport *vport;
struct lpfc_hba *phba;
LPFC_MBOXQ_t *pmboxq;
struct sli4_link_diag *link_diag_test_cmd;
uint32_t req_len, alloc_len;
uint32_t timeout;
struct lpfc_mbx_run_link_diag_test *run_link_diag_test;
union lpfc_sli4_cfg_shdr *shdr;
uint32_t shdr_status, shdr_add_status;
struct diag_status *diag_status_reply;
int mbxstatus, rc = 0;
shost = job->shost;
if (!shost) {
rc = -ENODEV;
goto job_error;
}
vport = (struct lpfc_vport *)job->shost->hostdata;
if (!vport) {
rc = -ENODEV;
goto job_error;
}
phba = vport->phba;
if (!phba) {
rc = -ENODEV;
goto job_error;
}
if (phba->sli_rev < LPFC_SLI_REV4) {
rc = -ENODEV;
goto job_error;
}
if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) !=
LPFC_SLI_INTF_IF_TYPE_2) {
rc = -ENODEV;
goto job_error;
}
if (job->request_len < sizeof(struct fc_bsg_request) +
sizeof(struct sli4_link_diag)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"3013 Received LINK DIAG TEST request "
" size:%d below the minimum size:%d\n",
job->request_len,
(int)(sizeof(struct fc_bsg_request) +
sizeof(struct sli4_link_diag)));
rc = -EINVAL;
goto job_error;
}
rc = lpfc_bsg_diag_mode_enter(phba);
if (rc)
goto job_error;
link_diag_test_cmd = (struct sli4_link_diag *)
job->request->rqst_data.h_vendor.vendor_cmd;
timeout = link_diag_test_cmd->timeout * 100;
rc = lpfc_sli4_bsg_set_link_diag_state(phba, 1);
if (rc)
goto job_error;
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq) {
rc = -ENOMEM;
goto link_diag_test_exit;
}
req_len = (sizeof(struct lpfc_mbx_set_link_diag_state) -
sizeof(struct lpfc_sli4_cfg_mhdr));
alloc_len = lpfc_sli4_config(phba, pmboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
LPFC_MBOX_OPCODE_FCOE_LINK_DIAG_STATE,
req_len, LPFC_SLI4_MBX_EMBED);
if (alloc_len != req_len) {
rc = -ENOMEM;
goto link_diag_test_exit;
}
run_link_diag_test = &pmboxq->u.mqe.un.link_diag_test;
bf_set(lpfc_mbx_run_diag_test_link_num, &run_link_diag_test->u.req,
phba->sli4_hba.lnk_info.lnk_no);
bf_set(lpfc_mbx_run_diag_test_link_type, &run_link_diag_test->u.req,
phba->sli4_hba.lnk_info.lnk_tp);
bf_set(lpfc_mbx_run_diag_test_test_id, &run_link_diag_test->u.req,
link_diag_test_cmd->test_id);
bf_set(lpfc_mbx_run_diag_test_loops, &run_link_diag_test->u.req,
link_diag_test_cmd->loops);
bf_set(lpfc_mbx_run_diag_test_test_ver, &run_link_diag_test->u.req,
link_diag_test_cmd->test_version);
bf_set(lpfc_mbx_run_diag_test_err_act, &run_link_diag_test->u.req,
link_diag_test_cmd->error_action);
mbxstatus = lpfc_sli_issue_mbox(phba, pmboxq, MBX_POLL);
shdr = (union lpfc_sli4_cfg_shdr *)
&pmboxq->u.mqe.un.sli4_config.header.cfg_shdr;
shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
if (shdr_status || shdr_add_status || mbxstatus) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"3010 Run link diag test mailbox failed with "
"mbx_status x%x status x%x, add_status x%x\n",
mbxstatus, shdr_status, shdr_add_status);
}
diag_status_reply = (struct diag_status *)
job->reply->reply_data.vendor_reply.vendor_rsp;
if (job->reply_len <
sizeof(struct fc_bsg_request) + sizeof(struct diag_status)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"3012 Received Run link diag test reply "
"below minimum size (%d): reply_len:%d\n",
(int)(sizeof(struct fc_bsg_request) +
sizeof(struct diag_status)),
job->reply_len);
rc = -EINVAL;
goto job_error;
}
diag_status_reply->mbox_status = mbxstatus;
diag_status_reply->shdr_status = shdr_status;
diag_status_reply->shdr_add_status = shdr_add_status;
link_diag_test_exit:
rc = lpfc_sli4_bsg_set_link_diag_state(phba, 0);
if (pmboxq)
mempool_free(pmboxq, phba->mbox_mem_pool);
lpfc_bsg_diag_mode_exit(phba);
job_error:
/* make error code available to userspace */
job->reply->result = rc;
/* complete the job back to userspace if no error */
if (rc == 0)
job->job_done(job);
return rc;
}
/**
* lpfcdiag_loop_self_reg - obtains a remote port login id
* @phba: Pointer to HBA context object
* @rpi: Pointer to a remote port login id
*
* This function obtains a remote port login id so the diag loopback test
* can send and receive its own unsolicited CT command.
**/
static int lpfcdiag_loop_self_reg(struct lpfc_hba *phba, uint16_t *rpi)
{
LPFC_MBOXQ_t *mbox;
struct lpfc_dmabuf *dmabuff;
int status;
mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!mbox)
return -ENOMEM;
if (phba->sli_rev < LPFC_SLI_REV4)
status = lpfc_reg_rpi(phba, 0, phba->pport->fc_myDID,
(uint8_t *)&phba->pport->fc_sparam,
mbox, *rpi);
else {
*rpi = lpfc_sli4_alloc_rpi(phba);
status = lpfc_reg_rpi(phba, phba->pport->vpi,
phba->pport->fc_myDID,
(uint8_t *)&phba->pport->fc_sparam,
mbox, *rpi);
}
if (status) {
mempool_free(mbox, phba->mbox_mem_pool);
if (phba->sli_rev == LPFC_SLI_REV4)
lpfc_sli4_free_rpi(phba, *rpi);
return -ENOMEM;
}
dmabuff = (struct lpfc_dmabuf *) mbox->context1;
mbox->context1 = NULL;
mbox->context2 = NULL;
status = lpfc_sli_issue_mbox_wait(phba, mbox, LPFC_MBOX_TMO);
if ((status != MBX_SUCCESS) || (mbox->u.mb.mbxStatus)) {
lpfc_mbuf_free(phba, dmabuff->virt, dmabuff->phys);
kfree(dmabuff);
if (status != MBX_TIMEOUT)
mempool_free(mbox, phba->mbox_mem_pool);
if (phba->sli_rev == LPFC_SLI_REV4)
lpfc_sli4_free_rpi(phba, *rpi);
return -ENODEV;
}
if (phba->sli_rev < LPFC_SLI_REV4)
*rpi = mbox->u.mb.un.varWords[0];
lpfc_mbuf_free(phba, dmabuff->virt, dmabuff->phys);
kfree(dmabuff);
mempool_free(mbox, phba->mbox_mem_pool);
return 0;
}
/**
* lpfcdiag_loop_self_unreg - unregs from the rpi
* @phba: Pointer to HBA context object
* @rpi: Remote port login id
*
* This function unregisters the rpi obtained in lpfcdiag_loop_self_reg
**/
static int lpfcdiag_loop_self_unreg(struct lpfc_hba *phba, uint16_t rpi)
{
LPFC_MBOXQ_t *mbox;
int status;
/* Allocate mboxq structure */
mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (mbox == NULL)
return -ENOMEM;
if (phba->sli_rev < LPFC_SLI_REV4)
lpfc_unreg_login(phba, 0, rpi, mbox);
else
lpfc_unreg_login(phba, phba->pport->vpi,
phba->sli4_hba.rpi_ids[rpi], mbox);
status = lpfc_sli_issue_mbox_wait(phba, mbox, LPFC_MBOX_TMO);
if ((status != MBX_SUCCESS) || (mbox->u.mb.mbxStatus)) {
if (status != MBX_TIMEOUT)
mempool_free(mbox, phba->mbox_mem_pool);
return -EIO;
}
mempool_free(mbox, phba->mbox_mem_pool);
if (phba->sli_rev == LPFC_SLI_REV4)
lpfc_sli4_free_rpi(phba, rpi);
return 0;
}
/**
* lpfcdiag_loop_get_xri - obtains the transmit and receive ids
* @phba: Pointer to HBA context object
* @rpi: Remote port login id
* @txxri: Pointer to transmit exchange id
* @rxxri: Pointer to response exchabge id
*
* This function obtains the transmit and receive ids required to send
* an unsolicited ct command with a payload. A special lpfc FsType and CmdRsp
* flags are used to the unsolicted response handler is able to process
* the ct command sent on the same port.
**/
static int lpfcdiag_loop_get_xri(struct lpfc_hba *phba, uint16_t rpi,
uint16_t *txxri, uint16_t * rxxri)
{
struct lpfc_bsg_event *evt;
struct lpfc_iocbq *cmdiocbq, *rspiocbq;
IOCB_t *cmd, *rsp;
struct lpfc_dmabuf *dmabuf;
struct ulp_bde64 *bpl = NULL;
struct lpfc_sli_ct_request *ctreq = NULL;
int ret_val = 0;
int time_left;
int iocb_stat = 0;
unsigned long flags;
*txxri = 0;
*rxxri = 0;
evt = lpfc_bsg_event_new(FC_REG_CT_EVENT, current->pid,
SLI_CT_ELX_LOOPBACK);
if (!evt)
return -ENOMEM;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_add(&evt->node, &phba->ct_ev_waiters);
lpfc_bsg_event_ref(evt);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
cmdiocbq = lpfc_sli_get_iocbq(phba);
rspiocbq = lpfc_sli_get_iocbq(phba);
dmabuf = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (dmabuf) {
dmabuf->virt = lpfc_mbuf_alloc(phba, 0, &dmabuf->phys);
if (dmabuf->virt) {
INIT_LIST_HEAD(&dmabuf->list);
bpl = (struct ulp_bde64 *) dmabuf->virt;
memset(bpl, 0, sizeof(*bpl));
ctreq = (struct lpfc_sli_ct_request *)(bpl + 1);
bpl->addrHigh =
le32_to_cpu(putPaddrHigh(dmabuf->phys +
sizeof(*bpl)));
bpl->addrLow =
le32_to_cpu(putPaddrLow(dmabuf->phys +
sizeof(*bpl)));
bpl->tus.f.bdeFlags = 0;
bpl->tus.f.bdeSize = ELX_LOOPBACK_HEADER_SZ;
bpl->tus.w = le32_to_cpu(bpl->tus.w);
}
}
if (cmdiocbq == NULL || rspiocbq == NULL ||
dmabuf == NULL || bpl == NULL || ctreq == NULL ||
dmabuf->virt == NULL) {
ret_val = -ENOMEM;
goto err_get_xri_exit;
}
cmd = &cmdiocbq->iocb;
rsp = &rspiocbq->iocb;
memset(ctreq, 0, ELX_LOOPBACK_HEADER_SZ);
ctreq->RevisionId.bits.Revision = SLI_CT_REVISION;
ctreq->RevisionId.bits.InId = 0;
ctreq->FsType = SLI_CT_ELX_LOOPBACK;
ctreq->FsSubType = 0;
ctreq->CommandResponse.bits.CmdRsp = ELX_LOOPBACK_XRI_SETUP;
ctreq->CommandResponse.bits.Size = 0;
cmd->un.xseq64.bdl.addrHigh = putPaddrHigh(dmabuf->phys);
cmd->un.xseq64.bdl.addrLow = putPaddrLow(dmabuf->phys);
cmd->un.xseq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
cmd->un.xseq64.bdl.bdeSize = sizeof(*bpl);
cmd->un.xseq64.w5.hcsw.Fctl = LA;
cmd->un.xseq64.w5.hcsw.Dfctl = 0;
cmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
cmd->un.xseq64.w5.hcsw.Type = FC_TYPE_CT;
cmd->ulpCommand = CMD_XMIT_SEQUENCE64_CR;
cmd->ulpBdeCount = 1;
cmd->ulpLe = 1;
cmd->ulpClass = CLASS3;
cmd->ulpContext = rpi;
cmdiocbq->iocb_flag |= LPFC_IO_LIBDFC;
cmdiocbq->vport = phba->pport;
iocb_stat = lpfc_sli_issue_iocb_wait(phba, LPFC_ELS_RING, cmdiocbq,
rspiocbq,
(phba->fc_ratov * 2)
+ LPFC_DRVR_TIMEOUT);
if (iocb_stat) {
ret_val = -EIO;
goto err_get_xri_exit;
}
*txxri = rsp->ulpContext;
evt->waiting = 1;
evt->wait_time_stamp = jiffies;
time_left = wait_event_interruptible_timeout(
evt->wq, !list_empty(&evt->events_to_see),
((phba->fc_ratov * 2) + LPFC_DRVR_TIMEOUT) * HZ);
if (list_empty(&evt->events_to_see))
ret_val = (time_left) ? -EINTR : -ETIMEDOUT;
else {
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_move(evt->events_to_see.prev, &evt->events_to_get);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
*rxxri = (list_entry(evt->events_to_get.prev,
typeof(struct event_data),
node))->immed_dat;
}
evt->waiting = 0;
err_get_xri_exit:
spin_lock_irqsave(&phba->ct_ev_lock, flags);
lpfc_bsg_event_unref(evt); /* release ref */
lpfc_bsg_event_unref(evt); /* delete */
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
if (dmabuf) {
if (dmabuf->virt)
lpfc_mbuf_free(phba, dmabuf->virt, dmabuf->phys);
kfree(dmabuf);
}
if (cmdiocbq && (iocb_stat != IOCB_TIMEDOUT))
lpfc_sli_release_iocbq(phba, cmdiocbq);
if (rspiocbq)
lpfc_sli_release_iocbq(phba, rspiocbq);
return ret_val;
}
/**
* lpfc_bsg_dma_page_alloc - allocate a bsg mbox page sized dma buffers
* @phba: Pointer to HBA context object
*
* This function allocates BSG_MBOX_SIZE (4KB) page size dma buffer and.
* retruns the pointer to the buffer.
**/
static struct lpfc_dmabuf *
lpfc_bsg_dma_page_alloc(struct lpfc_hba *phba)
{
struct lpfc_dmabuf *dmabuf;
struct pci_dev *pcidev = phba->pcidev;
/* allocate dma buffer struct */
dmabuf = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (!dmabuf)
return NULL;
INIT_LIST_HEAD(&dmabuf->list);
/* now, allocate dma buffer */
dmabuf->virt = dma_alloc_coherent(&pcidev->dev, BSG_MBOX_SIZE,
&(dmabuf->phys), GFP_KERNEL);
if (!dmabuf->virt) {
kfree(dmabuf);
return NULL;
}
memset((uint8_t *)dmabuf->virt, 0, BSG_MBOX_SIZE);
return dmabuf;
}
/**
* lpfc_bsg_dma_page_free - free a bsg mbox page sized dma buffer
* @phba: Pointer to HBA context object.
* @dmabuf: Pointer to the bsg mbox page sized dma buffer descriptor.
*
* This routine just simply frees a dma buffer and its associated buffer
* descriptor referred by @dmabuf.
**/
static void
lpfc_bsg_dma_page_free(struct lpfc_hba *phba, struct lpfc_dmabuf *dmabuf)
{
struct pci_dev *pcidev = phba->pcidev;
if (!dmabuf)
return;
if (dmabuf->virt)
dma_free_coherent(&pcidev->dev, BSG_MBOX_SIZE,
dmabuf->virt, dmabuf->phys);
kfree(dmabuf);
return;
}
/**
* lpfc_bsg_dma_page_list_free - free a list of bsg mbox page sized dma buffers
* @phba: Pointer to HBA context object.
* @dmabuf_list: Pointer to a list of bsg mbox page sized dma buffer descs.
*
* This routine just simply frees all dma buffers and their associated buffer
* descriptors referred by @dmabuf_list.
**/
static void
lpfc_bsg_dma_page_list_free(struct lpfc_hba *phba,
struct list_head *dmabuf_list)
{
struct lpfc_dmabuf *dmabuf, *next_dmabuf;
if (list_empty(dmabuf_list))
return;
list_for_each_entry_safe(dmabuf, next_dmabuf, dmabuf_list, list) {
list_del_init(&dmabuf->list);
lpfc_bsg_dma_page_free(phba, dmabuf);
}
return;
}
/**
* diag_cmd_data_alloc - fills in a bde struct with dma buffers
* @phba: Pointer to HBA context object
* @bpl: Pointer to 64 bit bde structure
* @size: Number of bytes to process
* @nocopydata: Flag to copy user data into the allocated buffer
*
* This function allocates page size buffers and populates an lpfc_dmabufext.
* If allowed the user data pointed to with indataptr is copied into the kernel
* memory. The chained list of page size buffers is returned.
**/
static struct lpfc_dmabufext *
diag_cmd_data_alloc(struct lpfc_hba *phba,
struct ulp_bde64 *bpl, uint32_t size,
int nocopydata)
{
struct lpfc_dmabufext *mlist = NULL;
struct lpfc_dmabufext *dmp;
int cnt, offset = 0, i = 0;
struct pci_dev *pcidev;
pcidev = phba->pcidev;
while (size) {
/* We get chunks of 4K */
if (size > BUF_SZ_4K)
cnt = BUF_SZ_4K;
else
cnt = size;
/* allocate struct lpfc_dmabufext buffer header */
dmp = kmalloc(sizeof(struct lpfc_dmabufext), GFP_KERNEL);
if (!dmp)
goto out;
INIT_LIST_HEAD(&dmp->dma.list);
/* Queue it to a linked list */
if (mlist)
list_add_tail(&dmp->dma.list, &mlist->dma.list);
else
mlist = dmp;
/* allocate buffer */
dmp->dma.virt = dma_alloc_coherent(&pcidev->dev,
cnt,
&(dmp->dma.phys),
GFP_KERNEL);
if (!dmp->dma.virt)
goto out;
dmp->size = cnt;
if (nocopydata) {
bpl->tus.f.bdeFlags = 0;
pci_dma_sync_single_for_device(phba->pcidev,
dmp->dma.phys, LPFC_BPL_SIZE, PCI_DMA_TODEVICE);
} else {
memset((uint8_t *)dmp->dma.virt, 0, cnt);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64I;
}
/* build buffer ptr list for IOCB */
bpl->addrLow = le32_to_cpu(putPaddrLow(dmp->dma.phys));
bpl->addrHigh = le32_to_cpu(putPaddrHigh(dmp->dma.phys));
bpl->tus.f.bdeSize = (ushort) cnt;
bpl->tus.w = le32_to_cpu(bpl->tus.w);
bpl++;
i++;
offset += cnt;
size -= cnt;
}
mlist->flag = i;
return mlist;
out:
diag_cmd_data_free(phba, mlist);
return NULL;
}
/**
* lpfcdiag_loop_post_rxbufs - post the receive buffers for an unsol CT cmd
* @phba: Pointer to HBA context object
* @rxxri: Receive exchange id
* @len: Number of data bytes
*
* This function allocates and posts a data buffer of sufficient size to receive
* an unsolicted CT command.
**/
static int lpfcdiag_loop_post_rxbufs(struct lpfc_hba *phba, uint16_t rxxri,
size_t len)
{
struct lpfc_sli *psli = &phba->sli;
struct lpfc_sli_ring *pring = &psli->ring[LPFC_ELS_RING];
struct lpfc_iocbq *cmdiocbq;
IOCB_t *cmd = NULL;
struct list_head head, *curr, *next;
struct lpfc_dmabuf *rxbmp;
struct lpfc_dmabuf *dmp;
struct lpfc_dmabuf *mp[2] = {NULL, NULL};
struct ulp_bde64 *rxbpl = NULL;
uint32_t num_bde;
struct lpfc_dmabufext *rxbuffer = NULL;
int ret_val = 0;
int iocb_stat;
int i = 0;
cmdiocbq = lpfc_sli_get_iocbq(phba);
rxbmp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (rxbmp != NULL) {
rxbmp->virt = lpfc_mbuf_alloc(phba, 0, &rxbmp->phys);
if (rxbmp->virt) {
INIT_LIST_HEAD(&rxbmp->list);
rxbpl = (struct ulp_bde64 *) rxbmp->virt;
rxbuffer = diag_cmd_data_alloc(phba, rxbpl, len, 0);
}
}
if (!cmdiocbq || !rxbmp || !rxbpl || !rxbuffer) {
ret_val = -ENOMEM;
goto err_post_rxbufs_exit;
}
/* Queue buffers for the receive exchange */
num_bde = (uint32_t)rxbuffer->flag;
dmp = &rxbuffer->dma;
cmd = &cmdiocbq->iocb;
i = 0;
INIT_LIST_HEAD(&head);
list_add_tail(&head, &dmp->list);
list_for_each_safe(curr, next, &head) {
mp[i] = list_entry(curr, struct lpfc_dmabuf, list);
list_del(curr);
if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
mp[i]->buffer_tag = lpfc_sli_get_buffer_tag(phba);
cmd->un.quexri64cx.buff.bde.addrHigh =
putPaddrHigh(mp[i]->phys);
cmd->un.quexri64cx.buff.bde.addrLow =
putPaddrLow(mp[i]->phys);
cmd->un.quexri64cx.buff.bde.tus.f.bdeSize =
((struct lpfc_dmabufext *)mp[i])->size;
cmd->un.quexri64cx.buff.buffer_tag = mp[i]->buffer_tag;
cmd->ulpCommand = CMD_QUE_XRI64_CX;
cmd->ulpPU = 0;
cmd->ulpLe = 1;
cmd->ulpBdeCount = 1;
cmd->unsli3.que_xri64cx_ext_words.ebde_count = 0;
} else {
cmd->un.cont64[i].addrHigh = putPaddrHigh(mp[i]->phys);
cmd->un.cont64[i].addrLow = putPaddrLow(mp[i]->phys);
cmd->un.cont64[i].tus.f.bdeSize =
((struct lpfc_dmabufext *)mp[i])->size;
cmd->ulpBdeCount = ++i;
if ((--num_bde > 0) && (i < 2))
continue;
cmd->ulpCommand = CMD_QUE_XRI_BUF64_CX;
cmd->ulpLe = 1;
}
cmd->ulpClass = CLASS3;
cmd->ulpContext = rxxri;
iocb_stat = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, cmdiocbq,
0);
if (iocb_stat == IOCB_ERROR) {
diag_cmd_data_free(phba,
(struct lpfc_dmabufext *)mp[0]);
if (mp[1])
diag_cmd_data_free(phba,
(struct lpfc_dmabufext *)mp[1]);
dmp = list_entry(next, struct lpfc_dmabuf, list);
ret_val = -EIO;
goto err_post_rxbufs_exit;
}
lpfc_sli_ringpostbuf_put(phba, pring, mp[0]);
if (mp[1]) {
lpfc_sli_ringpostbuf_put(phba, pring, mp[1]);
mp[1] = NULL;
}
/* The iocb was freed by lpfc_sli_issue_iocb */
cmdiocbq = lpfc_sli_get_iocbq(phba);
if (!cmdiocbq) {
dmp = list_entry(next, struct lpfc_dmabuf, list);
ret_val = -EIO;
goto err_post_rxbufs_exit;
}
cmd = &cmdiocbq->iocb;
i = 0;
}
list_del(&head);
err_post_rxbufs_exit:
if (rxbmp) {
if (rxbmp->virt)
lpfc_mbuf_free(phba, rxbmp->virt, rxbmp->phys);
kfree(rxbmp);
}
if (cmdiocbq)
lpfc_sli_release_iocbq(phba, cmdiocbq);
return ret_val;
}
/**
* lpfc_bsg_diag_loopback_run - run loopback on a port by issue ct cmd to itself
* @job: LPFC_BSG_VENDOR_DIAG_TEST fc_bsg_job
*
* This function receives a user data buffer to be transmitted and received on
* the same port, the link must be up and in loopback mode prior
* to being called.
* 1. A kernel buffer is allocated to copy the user data into.
* 2. The port registers with "itself".
* 3. The transmit and receive exchange ids are obtained.
* 4. The receive exchange id is posted.
* 5. A new els loopback event is created.
* 6. The command and response iocbs are allocated.
* 7. The cmd iocb FsType is set to elx loopback and the CmdRsp to looppback.
*
* This function is meant to be called n times while the port is in loopback
* so it is the apps responsibility to issue a reset to take the port out
* of loopback mode.
**/
static int
lpfc_bsg_diag_loopback_run(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct diag_mode_test *diag_mode;
struct lpfc_bsg_event *evt;
struct event_data *evdat;
struct lpfc_sli *psli = &phba->sli;
uint32_t size;
uint32_t full_size;
size_t segment_len = 0, segment_offset = 0, current_offset = 0;
uint16_t rpi = 0;
struct lpfc_iocbq *cmdiocbq, *rspiocbq = NULL;
IOCB_t *cmd, *rsp = NULL;
struct lpfc_sli_ct_request *ctreq;
struct lpfc_dmabuf *txbmp;
struct ulp_bde64 *txbpl = NULL;
struct lpfc_dmabufext *txbuffer = NULL;
struct list_head head;
struct lpfc_dmabuf *curr;
uint16_t txxri = 0, rxxri;
uint32_t num_bde;
uint8_t *ptr = NULL, *rx_databuf = NULL;
int rc = 0;
int time_left;
int iocb_stat;
unsigned long flags;
void *dataout = NULL;
uint32_t total_mem;
/* in case no data is returned return just the return code */
job->reply->reply_payload_rcv_len = 0;
if (job->request_len <
sizeof(struct fc_bsg_request) + sizeof(struct diag_mode_test)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2739 Received DIAG TEST request below minimum "
"size\n");
rc = -EINVAL;
goto loopback_test_exit;
}
if (job->request_payload.payload_len !=
job->reply_payload.payload_len) {
rc = -EINVAL;
goto loopback_test_exit;
}
diag_mode = (struct diag_mode_test *)
job->request->rqst_data.h_vendor.vendor_cmd;
if ((phba->link_state == LPFC_HBA_ERROR) ||
(psli->sli_flag & LPFC_BLOCK_MGMT_IO) ||
(!(psli->sli_flag & LPFC_SLI_ACTIVE))) {
rc = -EACCES;
goto loopback_test_exit;
}
if (!lpfc_is_link_up(phba) || !(phba->link_flag & LS_LOOPBACK_MODE)) {
rc = -EACCES;
goto loopback_test_exit;
}
size = job->request_payload.payload_len;
full_size = size + ELX_LOOPBACK_HEADER_SZ; /* plus the header */
if ((size == 0) || (size > 80 * BUF_SZ_4K)) {
rc = -ERANGE;
goto loopback_test_exit;
}
if (full_size >= BUF_SZ_4K) {
/*
* Allocate memory for ioctl data. If buffer is bigger than 64k,
* then we allocate 64k and re-use that buffer over and over to
* xfer the whole block. This is because Linux kernel has a
* problem allocating more than 120k of kernel space memory. Saw
* problem with GET_FCPTARGETMAPPING...
*/
if (size <= (64 * 1024))
total_mem = full_size;
else
total_mem = 64 * 1024;
} else
/* Allocate memory for ioctl data */
total_mem = BUF_SZ_4K;
dataout = kmalloc(total_mem, GFP_KERNEL);
if (dataout == NULL) {
rc = -ENOMEM;
goto loopback_test_exit;
}
ptr = dataout;
ptr += ELX_LOOPBACK_HEADER_SZ;
sg_copy_to_buffer(job->request_payload.sg_list,
job->request_payload.sg_cnt,
ptr, size);
rc = lpfcdiag_loop_self_reg(phba, &rpi);
if (rc)
goto loopback_test_exit;
if (phba->sli_rev < LPFC_SLI_REV4) {
rc = lpfcdiag_loop_get_xri(phba, rpi, &txxri, &rxxri);
if (rc) {
lpfcdiag_loop_self_unreg(phba, rpi);
goto loopback_test_exit;
}
rc = lpfcdiag_loop_post_rxbufs(phba, rxxri, full_size);
if (rc) {
lpfcdiag_loop_self_unreg(phba, rpi);
goto loopback_test_exit;
}
}
evt = lpfc_bsg_event_new(FC_REG_CT_EVENT, current->pid,
SLI_CT_ELX_LOOPBACK);
if (!evt) {
lpfcdiag_loop_self_unreg(phba, rpi);
rc = -ENOMEM;
goto loopback_test_exit;
}
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_add(&evt->node, &phba->ct_ev_waiters);
lpfc_bsg_event_ref(evt);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
cmdiocbq = lpfc_sli_get_iocbq(phba);
if (phba->sli_rev < LPFC_SLI_REV4)
rspiocbq = lpfc_sli_get_iocbq(phba);
txbmp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (txbmp) {
txbmp->virt = lpfc_mbuf_alloc(phba, 0, &txbmp->phys);
if (txbmp->virt) {
INIT_LIST_HEAD(&txbmp->list);
txbpl = (struct ulp_bde64 *) txbmp->virt;
txbuffer = diag_cmd_data_alloc(phba,
txbpl, full_size, 0);
}
}
if (!cmdiocbq || !txbmp || !txbpl || !txbuffer || !txbmp->virt) {
rc = -ENOMEM;
goto err_loopback_test_exit;
}
if ((phba->sli_rev < LPFC_SLI_REV4) && !rspiocbq) {
rc = -ENOMEM;
goto err_loopback_test_exit;
}
cmd = &cmdiocbq->iocb;
if (phba->sli_rev < LPFC_SLI_REV4)
rsp = &rspiocbq->iocb;
INIT_LIST_HEAD(&head);
list_add_tail(&head, &txbuffer->dma.list);
list_for_each_entry(curr, &head, list) {
segment_len = ((struct lpfc_dmabufext *)curr)->size;
if (current_offset == 0) {
ctreq = curr->virt;
memset(ctreq, 0, ELX_LOOPBACK_HEADER_SZ);
ctreq->RevisionId.bits.Revision = SLI_CT_REVISION;
ctreq->RevisionId.bits.InId = 0;
ctreq->FsType = SLI_CT_ELX_LOOPBACK;
ctreq->FsSubType = 0;
ctreq->CommandResponse.bits.CmdRsp = ELX_LOOPBACK_DATA;
ctreq->CommandResponse.bits.Size = size;
segment_offset = ELX_LOOPBACK_HEADER_SZ;
} else
segment_offset = 0;
BUG_ON(segment_offset >= segment_len);
memcpy(curr->virt + segment_offset,
ptr + current_offset,
segment_len - segment_offset);
current_offset += segment_len - segment_offset;
BUG_ON(current_offset > size);
}
list_del(&head);
/* Build the XMIT_SEQUENCE iocb */
num_bde = (uint32_t)txbuffer->flag;
cmd->un.xseq64.bdl.addrHigh = putPaddrHigh(txbmp->phys);
cmd->un.xseq64.bdl.addrLow = putPaddrLow(txbmp->phys);
cmd->un.xseq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
cmd->un.xseq64.bdl.bdeSize = (num_bde * sizeof(struct ulp_bde64));
cmd->un.xseq64.w5.hcsw.Fctl = (LS | LA);
cmd->un.xseq64.w5.hcsw.Dfctl = 0;
cmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
cmd->un.xseq64.w5.hcsw.Type = FC_TYPE_CT;
cmd->ulpCommand = CMD_XMIT_SEQUENCE64_CX;
cmd->ulpBdeCount = 1;
cmd->ulpLe = 1;
cmd->ulpClass = CLASS3;
if (phba->sli_rev < LPFC_SLI_REV4) {
cmd->ulpContext = txxri;
} else {
cmd->un.xseq64.bdl.ulpIoTag32 = 0;
cmd->un.ulpWord[3] = phba->sli4_hba.rpi_ids[rpi];
cmdiocbq->context3 = txbmp;
cmdiocbq->sli4_xritag = NO_XRI;
cmd->unsli3.rcvsli3.ox_id = 0xffff;
}
cmdiocbq->iocb_flag |= LPFC_IO_LIBDFC;
cmdiocbq->vport = phba->pport;
iocb_stat = lpfc_sli_issue_iocb_wait(phba, LPFC_ELS_RING, cmdiocbq,
rspiocbq, (phba->fc_ratov * 2) +
LPFC_DRVR_TIMEOUT);
if ((iocb_stat != IOCB_SUCCESS) || ((phba->sli_rev < LPFC_SLI_REV4) &&
(rsp->ulpStatus != IOCB_SUCCESS))) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"3126 Failed loopback test issue iocb: "
"iocb_stat:x%x\n", iocb_stat);
rc = -EIO;
goto err_loopback_test_exit;
}
evt->waiting = 1;
time_left = wait_event_interruptible_timeout(
evt->wq, !list_empty(&evt->events_to_see),
((phba->fc_ratov * 2) + LPFC_DRVR_TIMEOUT) * HZ);
evt->waiting = 0;
if (list_empty(&evt->events_to_see)) {
rc = (time_left) ? -EINTR : -ETIMEDOUT;
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"3125 Not receiving unsolicited event, "
"rc:x%x\n", rc);
} else {
spin_lock_irqsave(&phba->ct_ev_lock, flags);
list_move(evt->events_to_see.prev, &evt->events_to_get);
evdat = list_entry(evt->events_to_get.prev,
typeof(*evdat), node);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
rx_databuf = evdat->data;
if (evdat->len != full_size) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"1603 Loopback test did not receive expected "
"data length. actual length 0x%x expected "
"length 0x%x\n",
evdat->len, full_size);
rc = -EIO;
} else if (rx_databuf == NULL)
rc = -EIO;
else {
rc = IOCB_SUCCESS;
/* skip over elx loopback header */
rx_databuf += ELX_LOOPBACK_HEADER_SZ;
job->reply->reply_payload_rcv_len =
sg_copy_from_buffer(job->reply_payload.sg_list,
job->reply_payload.sg_cnt,
rx_databuf, size);
job->reply->reply_payload_rcv_len = size;
}
}
err_loopback_test_exit:
lpfcdiag_loop_self_unreg(phba, rpi);
spin_lock_irqsave(&phba->ct_ev_lock, flags);
lpfc_bsg_event_unref(evt); /* release ref */
lpfc_bsg_event_unref(evt); /* delete */
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
if (cmdiocbq != NULL)
lpfc_sli_release_iocbq(phba, cmdiocbq);
if (rspiocbq != NULL)
lpfc_sli_release_iocbq(phba, rspiocbq);
if (txbmp != NULL) {
if (txbpl != NULL) {
if (txbuffer != NULL)
diag_cmd_data_free(phba, txbuffer);
lpfc_mbuf_free(phba, txbmp->virt, txbmp->phys);
}
kfree(txbmp);
}
loopback_test_exit:
kfree(dataout);
/* make error code available to userspace */
job->reply->result = rc;
job->dd_data = NULL;
/* complete the job back to userspace if no error */
if (rc == IOCB_SUCCESS)
job->job_done(job);
return rc;
}
/**
* lpfc_bsg_get_dfc_rev - process a GET_DFC_REV bsg vendor command
* @job: GET_DFC_REV fc_bsg_job
**/
static int
lpfc_bsg_get_dfc_rev(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct get_mgmt_rev *event_req;
struct get_mgmt_rev_reply *event_reply;
int rc = 0;
if (job->request_len <
sizeof(struct fc_bsg_request) + sizeof(struct get_mgmt_rev)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2740 Received GET_DFC_REV request below "
"minimum size\n");
rc = -EINVAL;
goto job_error;
}
event_req = (struct get_mgmt_rev *)
job->request->rqst_data.h_vendor.vendor_cmd;
event_reply = (struct get_mgmt_rev_reply *)
job->reply->reply_data.vendor_reply.vendor_rsp;
if (job->reply_len <
sizeof(struct fc_bsg_request) + sizeof(struct get_mgmt_rev_reply)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2741 Received GET_DFC_REV reply below "
"minimum size\n");
rc = -EINVAL;
goto job_error;
}
event_reply->info.a_Major = MANAGEMENT_MAJOR_REV;
event_reply->info.a_Minor = MANAGEMENT_MINOR_REV;
job_error:
job->reply->result = rc;
if (rc == 0)
job->job_done(job);
return rc;
}
/**
* lpfc_bsg_issue_mbox_cmpl - lpfc_bsg_issue_mbox mbox completion handler
* @phba: Pointer to HBA context object.
* @pmboxq: Pointer to mailbox command.
*
* This is completion handler function for mailbox commands issued from
* lpfc_bsg_issue_mbox function. This function is called by the
* mailbox event handler function with no lock held. This function
* will wake up thread waiting on the wait queue pointed by context1
* of the mailbox.
**/
void
lpfc_bsg_issue_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
{
struct bsg_job_data *dd_data;
struct fc_bsg_job *job;
uint32_t size;
unsigned long flags;
uint8_t *pmb, *pmb_buf;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
dd_data = pmboxq->context1;
/* job already timed out? */
if (!dd_data) {
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
/*
* The outgoing buffer is readily referred from the dma buffer,
* just need to get header part from mailboxq structure.
*/
pmb = (uint8_t *)&pmboxq->u.mb;
pmb_buf = (uint8_t *)dd_data->context_un.mbox.mb;
memcpy(pmb_buf, pmb, sizeof(MAILBOX_t));
job = dd_data->context_un.mbox.set_job;
if (job) {
size = job->reply_payload.payload_len;
job->reply->reply_payload_rcv_len =
sg_copy_from_buffer(job->reply_payload.sg_list,
job->reply_payload.sg_cnt,
pmb_buf, size);
/* need to hold the lock until we set job->dd_data to NULL
* to hold off the timeout handler returning to the mid-layer
* while we are still processing the job.
*/
job->dd_data = NULL;
dd_data->context_un.mbox.set_job = NULL;
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
} else {
dd_data->context_un.mbox.set_job = NULL;
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
}
mempool_free(dd_data->context_un.mbox.pmboxq, phba->mbox_mem_pool);
lpfc_bsg_dma_page_free(phba, dd_data->context_un.mbox.dmabuffers);
kfree(dd_data);
if (job) {
job->reply->result = 0;
job->job_done(job);
}
return;
}
/**
* lpfc_bsg_check_cmd_access - test for a supported mailbox command
* @phba: Pointer to HBA context object.
* @mb: Pointer to a mailbox object.
* @vport: Pointer to a vport object.
*
* Some commands require the port to be offline, some may not be called from
* the application.
**/
static int lpfc_bsg_check_cmd_access(struct lpfc_hba *phba,
MAILBOX_t *mb, struct lpfc_vport *vport)
{
/* return negative error values for bsg job */
switch (mb->mbxCommand) {
/* Offline only */
case MBX_INIT_LINK:
case MBX_DOWN_LINK:
case MBX_CONFIG_LINK:
case MBX_CONFIG_RING:
case MBX_RESET_RING:
case MBX_UNREG_LOGIN:
case MBX_CLEAR_LA:
case MBX_DUMP_CONTEXT:
case MBX_RUN_DIAGS:
case MBX_RESTART:
case MBX_SET_MASK:
if (!(vport->fc_flag & FC_OFFLINE_MODE)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2743 Command 0x%x is illegal in on-line "
"state\n",
mb->mbxCommand);
return -EPERM;
}
case MBX_WRITE_NV:
case MBX_WRITE_VPARMS:
case MBX_LOAD_SM:
case MBX_READ_NV:
case MBX_READ_CONFIG:
case MBX_READ_RCONFIG:
case MBX_READ_STATUS:
case MBX_READ_XRI:
case MBX_READ_REV:
case MBX_READ_LNK_STAT:
case MBX_DUMP_MEMORY:
case MBX_DOWN_LOAD:
case MBX_UPDATE_CFG:
case MBX_KILL_BOARD:
case MBX_LOAD_AREA:
case MBX_LOAD_EXP_ROM:
case MBX_BEACON:
case MBX_DEL_LD_ENTRY:
case MBX_SET_DEBUG:
case MBX_WRITE_WWN:
case MBX_SLI4_CONFIG:
case MBX_READ_EVENT_LOG:
case MBX_READ_EVENT_LOG_STATUS:
case MBX_WRITE_EVENT_LOG:
case MBX_PORT_CAPABILITIES:
case MBX_PORT_IOV_CONTROL:
case MBX_RUN_BIU_DIAG64:
break;
case MBX_SET_VARIABLE:
lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
"1226 mbox: set_variable 0x%x, 0x%x\n",
mb->un.varWords[0],
mb->un.varWords[1]);
if ((mb->un.varWords[0] == SETVAR_MLOMNT)
&& (mb->un.varWords[1] == 1)) {
phba->wait_4_mlo_maint_flg = 1;
} else if (mb->un.varWords[0] == SETVAR_MLORST) {
spin_lock_irq(&phba->hbalock);
phba->link_flag &= ~LS_LOOPBACK_MODE;
spin_unlock_irq(&phba->hbalock);
phba->fc_topology = LPFC_TOPOLOGY_PT_PT;
}
break;
case MBX_READ_SPARM64:
case MBX_READ_TOPOLOGY:
case MBX_REG_LOGIN:
case MBX_REG_LOGIN64:
case MBX_CONFIG_PORT:
case MBX_RUN_BIU_DIAG:
default:
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2742 Unknown Command 0x%x\n",
mb->mbxCommand);
return -EPERM;
}
return 0; /* ok */
}
/**
* lpfc_bsg_mbox_ext_cleanup - clean up context of multi-buffer mbox session
* @phba: Pointer to HBA context object.
*
* This is routine clean up and reset BSG handling of multi-buffer mbox
* command session.
**/
static void
lpfc_bsg_mbox_ext_session_reset(struct lpfc_hba *phba)
{
if (phba->mbox_ext_buf_ctx.state == LPFC_BSG_MBOX_IDLE)
return;
/* free all memory, including dma buffers */
lpfc_bsg_dma_page_list_free(phba,
&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
lpfc_bsg_dma_page_free(phba, phba->mbox_ext_buf_ctx.mbx_dmabuf);
/* multi-buffer write mailbox command pass-through complete */
memset((char *)&phba->mbox_ext_buf_ctx, 0,
sizeof(struct lpfc_mbox_ext_buf_ctx));
INIT_LIST_HEAD(&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
return;
}
/**
* lpfc_bsg_issue_mbox_ext_handle_job - job handler for multi-buffer mbox cmpl
* @phba: Pointer to HBA context object.
* @pmboxq: Pointer to mailbox command.
*
* This is routine handles BSG job for mailbox commands completions with
* multiple external buffers.
**/
static struct fc_bsg_job *
lpfc_bsg_issue_mbox_ext_handle_job(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
{
struct bsg_job_data *dd_data;
struct fc_bsg_job *job;
uint8_t *pmb, *pmb_buf;
unsigned long flags;
uint32_t size;
int rc = 0;
struct lpfc_dmabuf *dmabuf;
struct lpfc_sli_config_mbox *sli_cfg_mbx;
uint8_t *pmbx;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
dd_data = pmboxq->context1;
/* has the job already timed out? */
if (!dd_data) {
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
job = NULL;
goto job_done_out;
}
/*
* The outgoing buffer is readily referred from the dma buffer,
* just need to get header part from mailboxq structure.
*/
pmb = (uint8_t *)&pmboxq->u.mb;
pmb_buf = (uint8_t *)dd_data->context_un.mbox.mb;
/* Copy the byte swapped response mailbox back to the user */
memcpy(pmb_buf, pmb, sizeof(MAILBOX_t));
/* if there is any non-embedded extended data copy that too */
dmabuf = phba->mbox_ext_buf_ctx.mbx_dmabuf;
sli_cfg_mbx = (struct lpfc_sli_config_mbox *)dmabuf->virt;
if (!bsg_bf_get(lpfc_mbox_hdr_emb,
&sli_cfg_mbx->un.sli_config_emb0_subsys.sli_config_hdr)) {
pmbx = (uint8_t *)dmabuf->virt;
/* byte swap the extended data following the mailbox command */
lpfc_sli_pcimem_bcopy(&pmbx[sizeof(MAILBOX_t)],
&pmbx[sizeof(MAILBOX_t)],
sli_cfg_mbx->un.sli_config_emb0_subsys.mse[0].buf_len);
}
job = dd_data->context_un.mbox.set_job;
if (job) {
size = job->reply_payload.payload_len;
job->reply->reply_payload_rcv_len =
sg_copy_from_buffer(job->reply_payload.sg_list,
job->reply_payload.sg_cnt,
pmb_buf, size);
/* result for successful */
job->reply->result = 0;
job->dd_data = NULL;
/* need to hold the lock util we set job->dd_data to NULL
* to hold off the timeout handler from midlayer to take
* any action.
*/
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2937 SLI_CONFIG ext-buffer maibox command "
"(x%x/x%x) complete bsg job done, bsize:%d\n",
phba->mbox_ext_buf_ctx.nembType,
phba->mbox_ext_buf_ctx.mboxType, size);
lpfc_idiag_mbxacc_dump_bsg_mbox(phba,
phba->mbox_ext_buf_ctx.nembType,
phba->mbox_ext_buf_ctx.mboxType,
dma_ebuf, sta_pos_addr,
phba->mbox_ext_buf_ctx.mbx_dmabuf, 0);
} else
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
job_done_out:
if (!job)
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2938 SLI_CONFIG ext-buffer maibox "
"command (x%x/x%x) failure, rc:x%x\n",
phba->mbox_ext_buf_ctx.nembType,
phba->mbox_ext_buf_ctx.mboxType, rc);
/* state change */
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_DONE;
kfree(dd_data);
return job;
}
/**
* lpfc_bsg_issue_read_mbox_ext_cmpl - compl handler for multi-buffer read mbox
* @phba: Pointer to HBA context object.
* @pmboxq: Pointer to mailbox command.
*
* This is completion handler function for mailbox read commands with multiple
* external buffers.
**/
static void
lpfc_bsg_issue_read_mbox_ext_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
{
struct fc_bsg_job *job;
/* handle the BSG job with mailbox command */
if (phba->mbox_ext_buf_ctx.state == LPFC_BSG_MBOX_ABTS)
pmboxq->u.mb.mbxStatus = MBXERR_ERROR;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2939 SLI_CONFIG ext-buffer rd maibox command "
"complete, ctxState:x%x, mbxStatus:x%x\n",
phba->mbox_ext_buf_ctx.state, pmboxq->u.mb.mbxStatus);
job = lpfc_bsg_issue_mbox_ext_handle_job(phba, pmboxq);
if (pmboxq->u.mb.mbxStatus || phba->mbox_ext_buf_ctx.numBuf == 1)
lpfc_bsg_mbox_ext_session_reset(phba);
/* free base driver mailbox structure memory */
mempool_free(pmboxq, phba->mbox_mem_pool);
/* complete the bsg job if we have it */
if (job)
job->job_done(job);
return;
}
/**
* lpfc_bsg_issue_write_mbox_ext_cmpl - cmpl handler for multi-buffer write mbox
* @phba: Pointer to HBA context object.
* @pmboxq: Pointer to mailbox command.
*
* This is completion handler function for mailbox write commands with multiple
* external buffers.
**/
static void
lpfc_bsg_issue_write_mbox_ext_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
{
struct fc_bsg_job *job;
/* handle the BSG job with the mailbox command */
if (phba->mbox_ext_buf_ctx.state == LPFC_BSG_MBOX_ABTS)
pmboxq->u.mb.mbxStatus = MBXERR_ERROR;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2940 SLI_CONFIG ext-buffer wr maibox command "
"complete, ctxState:x%x, mbxStatus:x%x\n",
phba->mbox_ext_buf_ctx.state, pmboxq->u.mb.mbxStatus);
job = lpfc_bsg_issue_mbox_ext_handle_job(phba, pmboxq);
/* free all memory, including dma buffers */
mempool_free(pmboxq, phba->mbox_mem_pool);
lpfc_bsg_mbox_ext_session_reset(phba);
/* complete the bsg job if we have it */
if (job)
job->job_done(job);
return;
}
static void
lpfc_bsg_sli_cfg_dma_desc_setup(struct lpfc_hba *phba, enum nemb_type nemb_tp,
uint32_t index, struct lpfc_dmabuf *mbx_dmabuf,
struct lpfc_dmabuf *ext_dmabuf)
{
struct lpfc_sli_config_mbox *sli_cfg_mbx;
/* pointer to the start of mailbox command */
sli_cfg_mbx = (struct lpfc_sli_config_mbox *)mbx_dmabuf->virt;
if (nemb_tp == nemb_mse) {
if (index == 0) {
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_hi =
putPaddrHigh(mbx_dmabuf->phys +
sizeof(MAILBOX_t));
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_lo =
putPaddrLow(mbx_dmabuf->phys +
sizeof(MAILBOX_t));
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2943 SLI_CONFIG(mse)[%d], "
"bufLen:%d, addrHi:x%x, addrLo:x%x\n",
index,
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].buf_len,
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_hi,
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_lo);
} else {
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_hi =
putPaddrHigh(ext_dmabuf->phys);
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_lo =
putPaddrLow(ext_dmabuf->phys);
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2944 SLI_CONFIG(mse)[%d], "
"bufLen:%d, addrHi:x%x, addrLo:x%x\n",
index,
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].buf_len,
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_hi,
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[index].pa_lo);
}
} else {
if (index == 0) {
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_hi =
putPaddrHigh(mbx_dmabuf->phys +
sizeof(MAILBOX_t));
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_lo =
putPaddrLow(mbx_dmabuf->phys +
sizeof(MAILBOX_t));
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3007 SLI_CONFIG(hbd)[%d], "
"bufLen:%d, addrHi:x%x, addrLo:x%x\n",
index,
bsg_bf_get(lpfc_mbox_sli_config_ecmn_hbd_len,
&sli_cfg_mbx->un.
sli_config_emb1_subsys.hbd[index]),
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_hi,
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_lo);
} else {
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_hi =
putPaddrHigh(ext_dmabuf->phys);
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_lo =
putPaddrLow(ext_dmabuf->phys);
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3008 SLI_CONFIG(hbd)[%d], "
"bufLen:%d, addrHi:x%x, addrLo:x%x\n",
index,
bsg_bf_get(lpfc_mbox_sli_config_ecmn_hbd_len,
&sli_cfg_mbx->un.
sli_config_emb1_subsys.hbd[index]),
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_hi,
sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[index].pa_lo);
}
}
return;
}
/**
* lpfc_bsg_sli_cfg_mse_read_cmd_ext - sli_config non-embedded mailbox cmd read
* @phba: Pointer to HBA context object.
* @mb: Pointer to a BSG mailbox object.
* @nemb_tp: Enumerate of non-embedded mailbox command type.
* @dmabuff: Pointer to a DMA buffer descriptor.
*
* This routine performs SLI_CONFIG (0x9B) read mailbox command operation with
* non-embedded external bufffers.
**/
static int
lpfc_bsg_sli_cfg_read_cmd_ext(struct lpfc_hba *phba, struct fc_bsg_job *job,
enum nemb_type nemb_tp,
struct lpfc_dmabuf *dmabuf)
{
struct lpfc_sli_config_mbox *sli_cfg_mbx;
struct dfc_mbox_req *mbox_req;
struct lpfc_dmabuf *curr_dmabuf, *next_dmabuf;
uint32_t ext_buf_cnt, ext_buf_index;
struct lpfc_dmabuf *ext_dmabuf = NULL;
struct bsg_job_data *dd_data = NULL;
LPFC_MBOXQ_t *pmboxq = NULL;
MAILBOX_t *pmb;
uint8_t *pmbx;
int rc, i;
mbox_req =
(struct dfc_mbox_req *)job->request->rqst_data.h_vendor.vendor_cmd;
/* pointer to the start of mailbox command */
sli_cfg_mbx = (struct lpfc_sli_config_mbox *)dmabuf->virt;
if (nemb_tp == nemb_mse) {
ext_buf_cnt = bsg_bf_get(lpfc_mbox_hdr_mse_cnt,
&sli_cfg_mbx->un.sli_config_emb0_subsys.sli_config_hdr);
if (ext_buf_cnt > LPFC_MBX_SLI_CONFIG_MAX_MSE) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2945 Handled SLI_CONFIG(mse) rd, "
"ext_buf_cnt(%d) out of range(%d)\n",
ext_buf_cnt,
LPFC_MBX_SLI_CONFIG_MAX_MSE);
rc = -ERANGE;
goto job_error;
}
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2941 Handled SLI_CONFIG(mse) rd, "
"ext_buf_cnt:%d\n", ext_buf_cnt);
} else {
/* sanity check on interface type for support */
if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) !=
LPFC_SLI_INTF_IF_TYPE_2) {
rc = -ENODEV;
goto job_error;
}
/* nemb_tp == nemb_hbd */
ext_buf_cnt = sli_cfg_mbx->un.sli_config_emb1_subsys.hbd_count;
if (ext_buf_cnt > LPFC_MBX_SLI_CONFIG_MAX_HBD) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2946 Handled SLI_CONFIG(hbd) rd, "
"ext_buf_cnt(%d) out of range(%d)\n",
ext_buf_cnt,
LPFC_MBX_SLI_CONFIG_MAX_HBD);
rc = -ERANGE;
goto job_error;
}
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2942 Handled SLI_CONFIG(hbd) rd, "
"ext_buf_cnt:%d\n", ext_buf_cnt);
}
/* before dma descriptor setup */
lpfc_idiag_mbxacc_dump_bsg_mbox(phba, nemb_tp, mbox_rd, dma_mbox,
sta_pre_addr, dmabuf, ext_buf_cnt);
/* reject non-embedded mailbox command with none external buffer */
if (ext_buf_cnt == 0) {
rc = -EPERM;
goto job_error;
} else if (ext_buf_cnt > 1) {
/* additional external read buffers */
for (i = 1; i < ext_buf_cnt; i++) {
ext_dmabuf = lpfc_bsg_dma_page_alloc(phba);
if (!ext_dmabuf) {
rc = -ENOMEM;
goto job_error;
}
list_add_tail(&ext_dmabuf->list,
&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
}
}
/* bsg tracking structure */
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
rc = -ENOMEM;
goto job_error;
}
/* mailbox command structure for base driver */
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq) {
rc = -ENOMEM;
goto job_error;
}
memset(pmboxq, 0, sizeof(LPFC_MBOXQ_t));
/* for the first external buffer */
lpfc_bsg_sli_cfg_dma_desc_setup(phba, nemb_tp, 0, dmabuf, dmabuf);
/* for the rest of external buffer descriptors if any */
if (ext_buf_cnt > 1) {
ext_buf_index = 1;
list_for_each_entry_safe(curr_dmabuf, next_dmabuf,
&phba->mbox_ext_buf_ctx.ext_dmabuf_list, list) {
lpfc_bsg_sli_cfg_dma_desc_setup(phba, nemb_tp,
ext_buf_index, dmabuf,
curr_dmabuf);
ext_buf_index++;
}
}
/* after dma descriptor setup */
lpfc_idiag_mbxacc_dump_bsg_mbox(phba, nemb_tp, mbox_rd, dma_mbox,
sta_pos_addr, dmabuf, ext_buf_cnt);
/* construct base driver mbox command */
pmb = &pmboxq->u.mb;
pmbx = (uint8_t *)dmabuf->virt;
memcpy(pmb, pmbx, sizeof(*pmb));
pmb->mbxOwner = OWN_HOST;
pmboxq->vport = phba->pport;
/* multi-buffer handling context */
phba->mbox_ext_buf_ctx.nembType = nemb_tp;
phba->mbox_ext_buf_ctx.mboxType = mbox_rd;
phba->mbox_ext_buf_ctx.numBuf = ext_buf_cnt;
phba->mbox_ext_buf_ctx.mbxTag = mbox_req->extMboxTag;
phba->mbox_ext_buf_ctx.seqNum = mbox_req->extSeqNum;
phba->mbox_ext_buf_ctx.mbx_dmabuf = dmabuf;
/* callback for multi-buffer read mailbox command */
pmboxq->mbox_cmpl = lpfc_bsg_issue_read_mbox_ext_cmpl;
/* context fields to callback function */
pmboxq->context1 = dd_data;
dd_data->type = TYPE_MBOX;
dd_data->context_un.mbox.pmboxq = pmboxq;
dd_data->context_un.mbox.mb = (MAILBOX_t *)pmbx;
dd_data->context_un.mbox.set_job = job;
job->dd_data = dd_data;
/* state change */
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_PORT;
/*
* Non-embedded mailbox subcommand data gets byte swapped here because
* the lower level driver code only does the first 64 mailbox words.
*/
if ((!bsg_bf_get(lpfc_mbox_hdr_emb,
&sli_cfg_mbx->un.sli_config_emb0_subsys.sli_config_hdr)) &&
(nemb_tp == nemb_mse))
lpfc_sli_pcimem_bcopy(&pmbx[sizeof(MAILBOX_t)],
&pmbx[sizeof(MAILBOX_t)],
sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[0].buf_len);
rc = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
if ((rc == MBX_SUCCESS) || (rc == MBX_BUSY)) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2947 Issued SLI_CONFIG ext-buffer "
"maibox command, rc:x%x\n", rc);
return SLI_CONFIG_HANDLED;
}
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2948 Failed to issue SLI_CONFIG ext-buffer "
"maibox command, rc:x%x\n", rc);
rc = -EPIPE;
job_error:
if (pmboxq)
mempool_free(pmboxq, phba->mbox_mem_pool);
lpfc_bsg_dma_page_list_free(phba,
&phba->mbox_ext_buf_ctx.ext_dmabuf_list);
kfree(dd_data);
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_IDLE;
return rc;
}
/**
* lpfc_bsg_sli_cfg_write_cmd_ext - sli_config non-embedded mailbox cmd write
* @phba: Pointer to HBA context object.
* @mb: Pointer to a BSG mailbox object.
* @dmabuff: Pointer to a DMA buffer descriptor.
*
* This routine performs SLI_CONFIG (0x9B) write mailbox command operation with
* non-embedded external bufffers.
**/
static int
lpfc_bsg_sli_cfg_write_cmd_ext(struct lpfc_hba *phba, struct fc_bsg_job *job,
enum nemb_type nemb_tp,
struct lpfc_dmabuf *dmabuf)
{
struct dfc_mbox_req *mbox_req;
struct lpfc_sli_config_mbox *sli_cfg_mbx;
uint32_t ext_buf_cnt;
struct bsg_job_data *dd_data = NULL;
LPFC_MBOXQ_t *pmboxq = NULL;
MAILBOX_t *pmb;
uint8_t *mbx;
int rc = SLI_CONFIG_NOT_HANDLED, i;
mbox_req =
(struct dfc_mbox_req *)job->request->rqst_data.h_vendor.vendor_cmd;
/* pointer to the start of mailbox command */
sli_cfg_mbx = (struct lpfc_sli_config_mbox *)dmabuf->virt;
if (nemb_tp == nemb_mse) {
ext_buf_cnt = bsg_bf_get(lpfc_mbox_hdr_mse_cnt,
&sli_cfg_mbx->un.sli_config_emb0_subsys.sli_config_hdr);
if (ext_buf_cnt > LPFC_MBX_SLI_CONFIG_MAX_MSE) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2953 Failed SLI_CONFIG(mse) wr, "
"ext_buf_cnt(%d) out of range(%d)\n",
ext_buf_cnt,
LPFC_MBX_SLI_CONFIG_MAX_MSE);
return -ERANGE;
}
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2949 Handled SLI_CONFIG(mse) wr, "
"ext_buf_cnt:%d\n", ext_buf_cnt);
} else {
/* sanity check on interface type for support */
if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) !=
LPFC_SLI_INTF_IF_TYPE_2)
return -ENODEV;
/* nemb_tp == nemb_hbd */
ext_buf_cnt = sli_cfg_mbx->un.sli_config_emb1_subsys.hbd_count;
if (ext_buf_cnt > LPFC_MBX_SLI_CONFIG_MAX_HBD) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2954 Failed SLI_CONFIG(hbd) wr, "
"ext_buf_cnt(%d) out of range(%d)\n",
ext_buf_cnt,
LPFC_MBX_SLI_CONFIG_MAX_HBD);
return -ERANGE;
}
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2950 Handled SLI_CONFIG(hbd) wr, "
"ext_buf_cnt:%d\n", ext_buf_cnt);
}
/* before dma buffer descriptor setup */
lpfc_idiag_mbxacc_dump_bsg_mbox(phba, nemb_tp, mbox_wr, dma_mbox,
sta_pre_addr, dmabuf, ext_buf_cnt);
if (ext_buf_cnt == 0)
return -EPERM;
/* for the first external buffer */
lpfc_bsg_sli_cfg_dma_desc_setup(phba, nemb_tp, 0, dmabuf, dmabuf);
/* after dma descriptor setup */
lpfc_idiag_mbxacc_dump_bsg_mbox(phba, nemb_tp, mbox_wr, dma_mbox,
sta_pos_addr, dmabuf, ext_buf_cnt);
/* log for looking forward */
for (i = 1; i < ext_buf_cnt; i++) {
if (nemb_tp == nemb_mse)
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2951 SLI_CONFIG(mse), buf[%d]-length:%d\n",
i, sli_cfg_mbx->un.sli_config_emb0_subsys.
mse[i].buf_len);
else
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2952 SLI_CONFIG(hbd), buf[%d]-length:%d\n",
i, bsg_bf_get(lpfc_mbox_sli_config_ecmn_hbd_len,
&sli_cfg_mbx->un.sli_config_emb1_subsys.
hbd[i]));
}
/* multi-buffer handling context */
phba->mbox_ext_buf_ctx.nembType = nemb_tp;
phba->mbox_ext_buf_ctx.mboxType = mbox_wr;
phba->mbox_ext_buf_ctx.numBuf = ext_buf_cnt;
phba->mbox_ext_buf_ctx.mbxTag = mbox_req->extMboxTag;
phba->mbox_ext_buf_ctx.seqNum = mbox_req->extSeqNum;
phba->mbox_ext_buf_ctx.mbx_dmabuf = dmabuf;
if (ext_buf_cnt == 1) {
/* bsg tracking structure */
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
rc = -ENOMEM;
goto job_error;
}
/* mailbox command structure for base driver */
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq) {
rc = -ENOMEM;
goto job_error;
}
memset(pmboxq, 0, sizeof(LPFC_MBOXQ_t));
pmb = &pmboxq->u.mb;
mbx = (uint8_t *)dmabuf->virt;
memcpy(pmb, mbx, sizeof(*pmb));
pmb->mbxOwner = OWN_HOST;
pmboxq->vport = phba->pport;
/* callback for multi-buffer read mailbox command */
pmboxq->mbox_cmpl = lpfc_bsg_issue_write_mbox_ext_cmpl;
/* context fields to callback function */
pmboxq->context1 = dd_data;
dd_data->type = TYPE_MBOX;
dd_data->context_un.mbox.pmboxq = pmboxq;
dd_data->context_un.mbox.mb = (MAILBOX_t *)mbx;
dd_data->context_un.mbox.set_job = job;
job->dd_data = dd_data;
/* state change */
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_PORT;
rc = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
if ((rc == MBX_SUCCESS) || (rc == MBX_BUSY)) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2955 Issued SLI_CONFIG ext-buffer "
"maibox command, rc:x%x\n", rc);
return SLI_CONFIG_HANDLED;
}
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2956 Failed to issue SLI_CONFIG ext-buffer "
"maibox command, rc:x%x\n", rc);
rc = -EPIPE;
goto job_error;
}
/* wait for additoinal external buffers */
job->reply->result = 0;
job->job_done(job);
return SLI_CONFIG_HANDLED;
job_error:
if (pmboxq)
mempool_free(pmboxq, phba->mbox_mem_pool);
kfree(dd_data);
return rc;
}
/**
* lpfc_bsg_handle_sli_cfg_mbox - handle sli-cfg mailbox cmd with ext buffer
* @phba: Pointer to HBA context object.
* @mb: Pointer to a BSG mailbox object.
* @dmabuff: Pointer to a DMA buffer descriptor.
*
* This routine handles SLI_CONFIG (0x9B) mailbox command with non-embedded
* external bufffers, including both 0x9B with non-embedded MSEs and 0x9B
* with embedded sussystem 0x1 and opcodes with external HBDs.
**/
static int
lpfc_bsg_handle_sli_cfg_mbox(struct lpfc_hba *phba, struct fc_bsg_job *job,
struct lpfc_dmabuf *dmabuf)
{
struct lpfc_sli_config_mbox *sli_cfg_mbx;
uint32_t subsys;
uint32_t opcode;
int rc = SLI_CONFIG_NOT_HANDLED;
/* state change on new multi-buffer pass-through mailbox command */
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_HOST;
sli_cfg_mbx = (struct lpfc_sli_config_mbox *)dmabuf->virt;
if (!bsg_bf_get(lpfc_mbox_hdr_emb,
&sli_cfg_mbx->un.sli_config_emb0_subsys.sli_config_hdr)) {
subsys = bsg_bf_get(lpfc_emb0_subcmnd_subsys,
&sli_cfg_mbx->un.sli_config_emb0_subsys);
opcode = bsg_bf_get(lpfc_emb0_subcmnd_opcode,
&sli_cfg_mbx->un.sli_config_emb0_subsys);
if (subsys == SLI_CONFIG_SUBSYS_FCOE) {
switch (opcode) {
case FCOE_OPCODE_READ_FCF:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2957 Handled SLI_CONFIG "
"subsys_fcoe, opcode:x%x\n",
opcode);
rc = lpfc_bsg_sli_cfg_read_cmd_ext(phba, job,
nemb_mse, dmabuf);
break;
case FCOE_OPCODE_ADD_FCF:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2958 Handled SLI_CONFIG "
"subsys_fcoe, opcode:x%x\n",
opcode);
rc = lpfc_bsg_sli_cfg_write_cmd_ext(phba, job,
nemb_mse, dmabuf);
break;
default:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2959 Reject SLI_CONFIG "
"subsys_fcoe, opcode:x%x\n",
opcode);
rc = -EPERM;
break;
}
} else if (subsys == SLI_CONFIG_SUBSYS_COMN) {
switch (opcode) {
case COMN_OPCODE_GET_CNTL_ADDL_ATTRIBUTES:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3106 Handled SLI_CONFIG "
"subsys_comn, opcode:x%x\n",
opcode);
rc = lpfc_bsg_sli_cfg_read_cmd_ext(phba, job,
nemb_mse, dmabuf);
break;
default:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"3107 Reject SLI_CONFIG "
"subsys_comn, opcode:x%x\n",
opcode);
rc = -EPERM;
break;
}
} else {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2977 Reject SLI_CONFIG "
"subsys:x%d, opcode:x%x\n",
subsys, opcode);
rc = -EPERM;
}
} else {
subsys = bsg_bf_get(lpfc_emb1_subcmnd_subsys,
&sli_cfg_mbx->un.sli_config_emb1_subsys);
opcode = bsg_bf_get(lpfc_emb1_subcmnd_opcode,
&sli_cfg_mbx->un.sli_config_emb1_subsys);
if (subsys == SLI_CONFIG_SUBSYS_COMN) {
switch (opcode) {
case COMN_OPCODE_READ_OBJECT:
case COMN_OPCODE_READ_OBJECT_LIST:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2960 Handled SLI_CONFIG "
"subsys_comn, opcode:x%x\n",
opcode);
rc = lpfc_bsg_sli_cfg_read_cmd_ext(phba, job,
nemb_hbd, dmabuf);
break;
case COMN_OPCODE_WRITE_OBJECT:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2961 Handled SLI_CONFIG "
"subsys_comn, opcode:x%x\n",
opcode);
rc = lpfc_bsg_sli_cfg_write_cmd_ext(phba, job,
nemb_hbd, dmabuf);
break;
default:
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2962 Not handled SLI_CONFIG "
"subsys_comn, opcode:x%x\n",
opcode);
rc = SLI_CONFIG_NOT_HANDLED;
break;
}
} else {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2978 Not handled SLI_CONFIG "
"subsys:x%d, opcode:x%x\n",
subsys, opcode);
rc = SLI_CONFIG_NOT_HANDLED;
}
}
/* state reset on not handled new multi-buffer mailbox command */
if (rc != SLI_CONFIG_HANDLED)
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_IDLE;
return rc;
}
/**
* lpfc_bsg_mbox_ext_abort_req - request to abort mbox command with ext buffers
* @phba: Pointer to HBA context object.
*
* This routine is for requesting to abort a pass-through mailbox command with
* multiple external buffers due to error condition.
**/
static void
lpfc_bsg_mbox_ext_abort(struct lpfc_hba *phba)
{
if (phba->mbox_ext_buf_ctx.state == LPFC_BSG_MBOX_PORT)
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_ABTS;
else
lpfc_bsg_mbox_ext_session_reset(phba);
return;
}
/**
* lpfc_bsg_read_ebuf_get - get the next mailbox read external buffer
* @phba: Pointer to HBA context object.
* @dmabuf: Pointer to a DMA buffer descriptor.
*
* This routine extracts the next mailbox read external buffer back to
* user space through BSG.
**/
static int
lpfc_bsg_read_ebuf_get(struct lpfc_hba *phba, struct fc_bsg_job *job)
{
struct lpfc_sli_config_mbox *sli_cfg_mbx;
struct lpfc_dmabuf *dmabuf;
uint8_t *pbuf;
uint32_t size;
uint32_t index;
index = phba->mbox_ext_buf_ctx.seqNum;
phba->mbox_ext_buf_ctx.seqNum++;
sli_cfg_mbx = (struct lpfc_sli_config_mbox *)
phba->mbox_ext_buf_ctx.mbx_dmabuf->virt;
if (phba->mbox_ext_buf_ctx.nembType == nemb_mse) {
size = bsg_bf_get(lpfc_mbox_sli_config_mse_len,
&sli_cfg_mbx->un.sli_config_emb0_subsys.mse[index]);
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2963 SLI_CONFIG (mse) ext-buffer rd get "
"buffer[%d], size:%d\n", index, size);
} else {
size = bsg_bf_get(lpfc_mbox_sli_config_ecmn_hbd_len,
&sli_cfg_mbx->un.sli_config_emb1_subsys.hbd[index]);
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2964 SLI_CONFIG (hbd) ext-buffer rd get "
"buffer[%d], size:%d\n", index, size);
}
if (list_empty(&phba->mbox_ext_buf_ctx.ext_dmabuf_list))
return -EPIPE;
dmabuf = list_first_entry(&phba->mbox_ext_buf_ctx.ext_dmabuf_list,
struct lpfc_dmabuf, list);
list_del_init(&dmabuf->list);
/* after dma buffer descriptor setup */
lpfc_idiag_mbxacc_dump_bsg_mbox(phba, phba->mbox_ext_buf_ctx.nembType,
mbox_rd, dma_ebuf, sta_pos_addr,
dmabuf, index);
pbuf = (uint8_t *)dmabuf->virt;
job->reply->reply_payload_rcv_len =
sg_copy_from_buffer(job->reply_payload.sg_list,
job->reply_payload.sg_cnt,
pbuf, size);
lpfc_bsg_dma_page_free(phba, dmabuf);
if (phba->mbox_ext_buf_ctx.seqNum == phba->mbox_ext_buf_ctx.numBuf) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2965 SLI_CONFIG (hbd) ext-buffer rd mbox "
"command session done\n");
lpfc_bsg_mbox_ext_session_reset(phba);
}
job->reply->result = 0;
job->job_done(job);
return SLI_CONFIG_HANDLED;
}
/**
* lpfc_bsg_write_ebuf_set - set the next mailbox write external buffer
* @phba: Pointer to HBA context object.
* @dmabuf: Pointer to a DMA buffer descriptor.
*
* This routine sets up the next mailbox read external buffer obtained
* from user space through BSG.
**/
static int
lpfc_bsg_write_ebuf_set(struct lpfc_hba *phba, struct fc_bsg_job *job,
struct lpfc_dmabuf *dmabuf)
{
struct lpfc_sli_config_mbox *sli_cfg_mbx;
struct bsg_job_data *dd_data = NULL;
LPFC_MBOXQ_t *pmboxq = NULL;
MAILBOX_t *pmb;
enum nemb_type nemb_tp;
uint8_t *pbuf;
uint32_t size;
uint32_t index;
int rc;
index = phba->mbox_ext_buf_ctx.seqNum;
phba->mbox_ext_buf_ctx.seqNum++;
nemb_tp = phba->mbox_ext_buf_ctx.nembType;
sli_cfg_mbx = (struct lpfc_sli_config_mbox *)
phba->mbox_ext_buf_ctx.mbx_dmabuf->virt;
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
rc = -ENOMEM;
goto job_error;
}
pbuf = (uint8_t *)dmabuf->virt;
size = job->request_payload.payload_len;
sg_copy_to_buffer(job->request_payload.sg_list,
job->request_payload.sg_cnt,
pbuf, size);
if (phba->mbox_ext_buf_ctx.nembType == nemb_mse) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2966 SLI_CONFIG (mse) ext-buffer wr set "
"buffer[%d], size:%d\n",
phba->mbox_ext_buf_ctx.seqNum, size);
} else {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2967 SLI_CONFIG (hbd) ext-buffer wr set "
"buffer[%d], size:%d\n",
phba->mbox_ext_buf_ctx.seqNum, size);
}
/* set up external buffer descriptor and add to external buffer list */
lpfc_bsg_sli_cfg_dma_desc_setup(phba, nemb_tp, index,
phba->mbox_ext_buf_ctx.mbx_dmabuf,
dmabuf);
list_add_tail(&dmabuf->list, &phba->mbox_ext_buf_ctx.ext_dmabuf_list);
/* after write dma buffer */
lpfc_idiag_mbxacc_dump_bsg_mbox(phba, phba->mbox_ext_buf_ctx.nembType,
mbox_wr, dma_ebuf, sta_pos_addr,
dmabuf, index);
if (phba->mbox_ext_buf_ctx.seqNum == phba->mbox_ext_buf_ctx.numBuf) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2968 SLI_CONFIG ext-buffer wr all %d "
"ebuffers received\n",
phba->mbox_ext_buf_ctx.numBuf);
/* mailbox command structure for base driver */
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq) {
rc = -ENOMEM;
goto job_error;
}
memset(pmboxq, 0, sizeof(LPFC_MBOXQ_t));
pbuf = (uint8_t *)phba->mbox_ext_buf_ctx.mbx_dmabuf->virt;
pmb = &pmboxq->u.mb;
memcpy(pmb, pbuf, sizeof(*pmb));
pmb->mbxOwner = OWN_HOST;
pmboxq->vport = phba->pport;
/* callback for multi-buffer write mailbox command */
pmboxq->mbox_cmpl = lpfc_bsg_issue_write_mbox_ext_cmpl;
/* context fields to callback function */
pmboxq->context1 = dd_data;
dd_data->type = TYPE_MBOX;
dd_data->context_un.mbox.pmboxq = pmboxq;
dd_data->context_un.mbox.mb = (MAILBOX_t *)pbuf;
dd_data->context_un.mbox.set_job = job;
job->dd_data = dd_data;
/* state change */
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_PORT;
rc = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
if ((rc == MBX_SUCCESS) || (rc == MBX_BUSY)) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2969 Issued SLI_CONFIG ext-buffer "
"maibox command, rc:x%x\n", rc);
return SLI_CONFIG_HANDLED;
}
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2970 Failed to issue SLI_CONFIG ext-buffer "
"maibox command, rc:x%x\n", rc);
rc = -EPIPE;
goto job_error;
}
/* wait for additoinal external buffers */
job->reply->result = 0;
job->job_done(job);
return SLI_CONFIG_HANDLED;
job_error:
lpfc_bsg_dma_page_free(phba, dmabuf);
kfree(dd_data);
return rc;
}
/**
* lpfc_bsg_handle_sli_cfg_ebuf - handle ext buffer with sli-cfg mailbox cmd
* @phba: Pointer to HBA context object.
* @mb: Pointer to a BSG mailbox object.
* @dmabuff: Pointer to a DMA buffer descriptor.
*
* This routine handles the external buffer with SLI_CONFIG (0x9B) mailbox
* command with multiple non-embedded external buffers.
**/
static int
lpfc_bsg_handle_sli_cfg_ebuf(struct lpfc_hba *phba, struct fc_bsg_job *job,
struct lpfc_dmabuf *dmabuf)
{
int rc;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2971 SLI_CONFIG buffer (type:x%x)\n",
phba->mbox_ext_buf_ctx.mboxType);
if (phba->mbox_ext_buf_ctx.mboxType == mbox_rd) {
if (phba->mbox_ext_buf_ctx.state != LPFC_BSG_MBOX_DONE) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2972 SLI_CONFIG rd buffer state "
"mismatch:x%x\n",
phba->mbox_ext_buf_ctx.state);
lpfc_bsg_mbox_ext_abort(phba);
return -EPIPE;
}
rc = lpfc_bsg_read_ebuf_get(phba, job);
if (rc == SLI_CONFIG_HANDLED)
lpfc_bsg_dma_page_free(phba, dmabuf);
} else { /* phba->mbox_ext_buf_ctx.mboxType == mbox_wr */
if (phba->mbox_ext_buf_ctx.state != LPFC_BSG_MBOX_HOST) {
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2973 SLI_CONFIG wr buffer state "
"mismatch:x%x\n",
phba->mbox_ext_buf_ctx.state);
lpfc_bsg_mbox_ext_abort(phba);
return -EPIPE;
}
rc = lpfc_bsg_write_ebuf_set(phba, job, dmabuf);
}
return rc;
}
/**
* lpfc_bsg_handle_sli_cfg_ext - handle sli-cfg mailbox with external buffer
* @phba: Pointer to HBA context object.
* @mb: Pointer to a BSG mailbox object.
* @dmabuff: Pointer to a DMA buffer descriptor.
*
* This routine checkes and handles non-embedded multi-buffer SLI_CONFIG
* (0x9B) mailbox commands and external buffers.
**/
static int
lpfc_bsg_handle_sli_cfg_ext(struct lpfc_hba *phba, struct fc_bsg_job *job,
struct lpfc_dmabuf *dmabuf)
{
struct dfc_mbox_req *mbox_req;
int rc = SLI_CONFIG_NOT_HANDLED;
mbox_req =
(struct dfc_mbox_req *)job->request->rqst_data.h_vendor.vendor_cmd;
/* mbox command with/without single external buffer */
if (mbox_req->extMboxTag == 0 && mbox_req->extSeqNum == 0)
return rc;
/* mbox command and first external buffer */
if (phba->mbox_ext_buf_ctx.state == LPFC_BSG_MBOX_IDLE) {
if (mbox_req->extSeqNum == 1) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2974 SLI_CONFIG mailbox: tag:%d, "
"seq:%d\n", mbox_req->extMboxTag,
mbox_req->extSeqNum);
rc = lpfc_bsg_handle_sli_cfg_mbox(phba, job, dmabuf);
return rc;
} else
goto sli_cfg_ext_error;
}
/*
* handle additional external buffers
*/
/* check broken pipe conditions */
if (mbox_req->extMboxTag != phba->mbox_ext_buf_ctx.mbxTag)
goto sli_cfg_ext_error;
if (mbox_req->extSeqNum > phba->mbox_ext_buf_ctx.numBuf)
goto sli_cfg_ext_error;
if (mbox_req->extSeqNum != phba->mbox_ext_buf_ctx.seqNum + 1)
goto sli_cfg_ext_error;
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2975 SLI_CONFIG mailbox external buffer: "
"extSta:x%x, tag:%d, seq:%d\n",
phba->mbox_ext_buf_ctx.state, mbox_req->extMboxTag,
mbox_req->extSeqNum);
rc = lpfc_bsg_handle_sli_cfg_ebuf(phba, job, dmabuf);
return rc;
sli_cfg_ext_error:
/* all other cases, broken pipe */
lpfc_printf_log(phba, KERN_ERR, LOG_LIBDFC,
"2976 SLI_CONFIG mailbox broken pipe: "
"ctxSta:x%x, ctxNumBuf:%d "
"ctxTag:%d, ctxSeq:%d, tag:%d, seq:%d\n",
phba->mbox_ext_buf_ctx.state,
phba->mbox_ext_buf_ctx.numBuf,
phba->mbox_ext_buf_ctx.mbxTag,
phba->mbox_ext_buf_ctx.seqNum,
mbox_req->extMboxTag, mbox_req->extSeqNum);
lpfc_bsg_mbox_ext_session_reset(phba);
return -EPIPE;
}
/**
* lpfc_bsg_issue_mbox - issues a mailbox command on behalf of an app
* @phba: Pointer to HBA context object.
* @mb: Pointer to a mailbox object.
* @vport: Pointer to a vport object.
*
* Allocate a tracking object, mailbox command memory, get a mailbox
* from the mailbox pool, copy the caller mailbox command.
*
* If offline and the sli is active we need to poll for the command (port is
* being reset) and com-plete the job, otherwise issue the mailbox command and
* let our completion handler finish the command.
**/
static uint32_t
lpfc_bsg_issue_mbox(struct lpfc_hba *phba, struct fc_bsg_job *job,
struct lpfc_vport *vport)
{
LPFC_MBOXQ_t *pmboxq = NULL; /* internal mailbox queue */
MAILBOX_t *pmb; /* shortcut to the pmboxq mailbox */
/* a 4k buffer to hold the mb and extended data from/to the bsg */
uint8_t *pmbx = NULL;
struct bsg_job_data *dd_data = NULL; /* bsg data tracking structure */
struct lpfc_dmabuf *dmabuf = NULL;
struct dfc_mbox_req *mbox_req;
struct READ_EVENT_LOG_VAR *rdEventLog;
uint32_t transmit_length, receive_length, mode;
struct lpfc_mbx_sli4_config *sli4_config;
struct lpfc_mbx_nembed_cmd *nembed_sge;
struct mbox_header *header;
struct ulp_bde64 *bde;
uint8_t *ext = NULL;
int rc = 0;
uint8_t *from;
uint32_t size;
/* in case no data is transferred */
job->reply->reply_payload_rcv_len = 0;
/* sanity check to protect driver */
if (job->reply_payload.payload_len > BSG_MBOX_SIZE ||
job->request_payload.payload_len > BSG_MBOX_SIZE) {
rc = -ERANGE;
goto job_done;
}
/*
* Don't allow mailbox commands to be sent when blocked or when in
* the middle of discovery
*/
if (phba->sli.sli_flag & LPFC_BLOCK_MGMT_IO) {
rc = -EAGAIN;
goto job_done;
}
mbox_req =
(struct dfc_mbox_req *)job->request->rqst_data.h_vendor.vendor_cmd;
/* check if requested extended data lengths are valid */
if ((mbox_req->inExtWLen > BSG_MBOX_SIZE/sizeof(uint32_t)) ||
(mbox_req->outExtWLen > BSG_MBOX_SIZE/sizeof(uint32_t))) {
rc = -ERANGE;
goto job_done;
}
dmabuf = lpfc_bsg_dma_page_alloc(phba);
if (!dmabuf || !dmabuf->virt) {
rc = -ENOMEM;
goto job_done;
}
/* Get the mailbox command or external buffer from BSG */
pmbx = (uint8_t *)dmabuf->virt;
size = job->request_payload.payload_len;
sg_copy_to_buffer(job->request_payload.sg_list,
job->request_payload.sg_cnt, pmbx, size);
/* Handle possible SLI_CONFIG with non-embedded payloads */
if (phba->sli_rev == LPFC_SLI_REV4) {
rc = lpfc_bsg_handle_sli_cfg_ext(phba, job, dmabuf);
if (rc == SLI_CONFIG_HANDLED)
goto job_cont;
if (rc)
goto job_done;
/* SLI_CONFIG_NOT_HANDLED for other mailbox commands */
}
rc = lpfc_bsg_check_cmd_access(phba, (MAILBOX_t *)pmbx, vport);
if (rc != 0)
goto job_done; /* must be negative */
/* allocate our bsg tracking structure */
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2727 Failed allocation of dd_data\n");
rc = -ENOMEM;
goto job_done;
}
pmboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmboxq) {
rc = -ENOMEM;
goto job_done;
}
memset(pmboxq, 0, sizeof(LPFC_MBOXQ_t));
pmb = &pmboxq->u.mb;
memcpy(pmb, pmbx, sizeof(*pmb));
pmb->mbxOwner = OWN_HOST;
pmboxq->vport = vport;
/* If HBA encountered an error attention, allow only DUMP
* or RESTART mailbox commands until the HBA is restarted.
*/
if (phba->pport->stopped &&
pmb->mbxCommand != MBX_DUMP_MEMORY &&
pmb->mbxCommand != MBX_RESTART &&
pmb->mbxCommand != MBX_WRITE_VPARMS &&
pmb->mbxCommand != MBX_WRITE_WWN)
lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX,
"2797 mbox: Issued mailbox cmd "
"0x%x while in stopped state.\n",
pmb->mbxCommand);
/* extended mailbox commands will need an extended buffer */
if (mbox_req->inExtWLen || mbox_req->outExtWLen) {
from = pmbx;
ext = from + sizeof(MAILBOX_t);
pmboxq->context2 = ext;
pmboxq->in_ext_byte_len =
mbox_req->inExtWLen * sizeof(uint32_t);
pmboxq->out_ext_byte_len =
mbox_req->outExtWLen * sizeof(uint32_t);
pmboxq->mbox_offset_word = mbox_req->mbOffset;
}
/* biu diag will need a kernel buffer to transfer the data
* allocate our own buffer and setup the mailbox command to
* use ours
*/
if (pmb->mbxCommand == MBX_RUN_BIU_DIAG64) {
transmit_length = pmb->un.varWords[1];
receive_length = pmb->un.varWords[4];
/* transmit length cannot be greater than receive length or
* mailbox extension size
*/
if ((transmit_length > receive_length) ||
(transmit_length > BSG_MBOX_SIZE - sizeof(MAILBOX_t))) {
rc = -ERANGE;
goto job_done;
}
pmb->un.varBIUdiag.un.s2.xmit_bde64.addrHigh =
putPaddrHigh(dmabuf->phys + sizeof(MAILBOX_t));
pmb->un.varBIUdiag.un.s2.xmit_bde64.addrLow =
putPaddrLow(dmabuf->phys + sizeof(MAILBOX_t));
pmb->un.varBIUdiag.un.s2.rcv_bde64.addrHigh =
putPaddrHigh(dmabuf->phys + sizeof(MAILBOX_t)
+ pmb->un.varBIUdiag.un.s2.xmit_bde64.tus.f.bdeSize);
pmb->un.varBIUdiag.un.s2.rcv_bde64.addrLow =
putPaddrLow(dmabuf->phys + sizeof(MAILBOX_t)
+ pmb->un.varBIUdiag.un.s2.xmit_bde64.tus.f.bdeSize);
} else if (pmb->mbxCommand == MBX_READ_EVENT_LOG) {
rdEventLog = &pmb->un.varRdEventLog;
receive_length = rdEventLog->rcv_bde64.tus.f.bdeSize;
mode = bf_get(lpfc_event_log, rdEventLog);
/* receive length cannot be greater than mailbox
* extension size
*/
if (receive_length > BSG_MBOX_SIZE - sizeof(MAILBOX_t)) {
rc = -ERANGE;
goto job_done;
}
/* mode zero uses a bde like biu diags command */
if (mode == 0) {
pmb->un.varWords[3] = putPaddrLow(dmabuf->phys
+ sizeof(MAILBOX_t));
pmb->un.varWords[4] = putPaddrHigh(dmabuf->phys
+ sizeof(MAILBOX_t));
}
} else if (phba->sli_rev == LPFC_SLI_REV4) {
/* Let type 4 (well known data) through because the data is
* returned in varwords[4-8]
* otherwise check the recieve length and fetch the buffer addr
*/
if ((pmb->mbxCommand == MBX_DUMP_MEMORY) &&
(pmb->un.varDmp.type != DMP_WELL_KNOWN)) {
/* rebuild the command for sli4 using our own buffers
* like we do for biu diags
*/
receive_length = pmb->un.varWords[2];
/* receive length cannot be greater than mailbox
* extension size
*/
if (receive_length == 0) {
rc = -ERANGE;
goto job_done;
}
pmb->un.varWords[3] = putPaddrLow(dmabuf->phys
+ sizeof(MAILBOX_t));
pmb->un.varWords[4] = putPaddrHigh(dmabuf->phys
+ sizeof(MAILBOX_t));
} else if ((pmb->mbxCommand == MBX_UPDATE_CFG) &&
pmb->un.varUpdateCfg.co) {
bde = (struct ulp_bde64 *)&pmb->un.varWords[4];
/* bde size cannot be greater than mailbox ext size */
if (bde->tus.f.bdeSize >
BSG_MBOX_SIZE - sizeof(MAILBOX_t)) {
rc = -ERANGE;
goto job_done;
}
bde->addrHigh = putPaddrHigh(dmabuf->phys
+ sizeof(MAILBOX_t));
bde->addrLow = putPaddrLow(dmabuf->phys
+ sizeof(MAILBOX_t));
} else if (pmb->mbxCommand == MBX_SLI4_CONFIG) {
/* Handling non-embedded SLI_CONFIG mailbox command */
sli4_config = &pmboxq->u.mqe.un.sli4_config;
if (!bf_get(lpfc_mbox_hdr_emb,
&sli4_config->header.cfg_mhdr)) {
/* rebuild the command for sli4 using our
* own buffers like we do for biu diags
*/
header = (struct mbox_header *)
&pmb->un.varWords[0];
nembed_sge = (struct lpfc_mbx_nembed_cmd *)
&pmb->un.varWords[0];
receive_length = nembed_sge->sge[0].length;
/* receive length cannot be greater than
* mailbox extension size
*/
if ((receive_length == 0) ||
(receive_length >
BSG_MBOX_SIZE - sizeof(MAILBOX_t))) {
rc = -ERANGE;
goto job_done;
}
nembed_sge->sge[0].pa_hi =
putPaddrHigh(dmabuf->phys
+ sizeof(MAILBOX_t));
nembed_sge->sge[0].pa_lo =
putPaddrLow(dmabuf->phys
+ sizeof(MAILBOX_t));
}
}
}
dd_data->context_un.mbox.dmabuffers = dmabuf;
/* setup wake call as IOCB callback */
pmboxq->mbox_cmpl = lpfc_bsg_issue_mbox_cmpl;
/* setup context field to pass wait_queue pointer to wake function */
pmboxq->context1 = dd_data;
dd_data->type = TYPE_MBOX;
dd_data->context_un.mbox.pmboxq = pmboxq;
dd_data->context_un.mbox.mb = (MAILBOX_t *)pmbx;
dd_data->context_un.mbox.set_job = job;
dd_data->context_un.mbox.ext = ext;
dd_data->context_un.mbox.mbOffset = mbox_req->mbOffset;
dd_data->context_un.mbox.inExtWLen = mbox_req->inExtWLen;
dd_data->context_un.mbox.outExtWLen = mbox_req->outExtWLen;
job->dd_data = dd_data;
if ((vport->fc_flag & FC_OFFLINE_MODE) ||
(!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))) {
rc = lpfc_sli_issue_mbox(phba, pmboxq, MBX_POLL);
if (rc != MBX_SUCCESS) {
rc = (rc == MBX_TIMEOUT) ? -ETIME : -ENODEV;
goto job_done;
}
/* job finished, copy the data */
memcpy(pmbx, pmb, sizeof(*pmb));
job->reply->reply_payload_rcv_len =
sg_copy_from_buffer(job->reply_payload.sg_list,
job->reply_payload.sg_cnt,
pmbx, size);
/* not waiting mbox already done */
rc = 0;
goto job_done;
}
rc = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
if ((rc == MBX_SUCCESS) || (rc == MBX_BUSY))
return 1; /* job started */
job_done:
/* common exit for error or job completed inline */
if (pmboxq)
mempool_free(pmboxq, phba->mbox_mem_pool);
lpfc_bsg_dma_page_free(phba, dmabuf);
kfree(dd_data);
job_cont:
return rc;
}
/**
* lpfc_bsg_mbox_cmd - process an fc bsg LPFC_BSG_VENDOR_MBOX command
* @job: MBOX fc_bsg_job for LPFC_BSG_VENDOR_MBOX.
**/
static int
lpfc_bsg_mbox_cmd(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct dfc_mbox_req *mbox_req;
int rc = 0;
/* mix-and-match backward compatibility */
job->reply->reply_payload_rcv_len = 0;
if (job->request_len <
sizeof(struct fc_bsg_request) + sizeof(struct dfc_mbox_req)) {
lpfc_printf_log(phba, KERN_INFO, LOG_LIBDFC,
"2737 Mix-and-match backward compability "
"between MBOX_REQ old size:%d and "
"new request size:%d\n",
(int)(job->request_len -
sizeof(struct fc_bsg_request)),
(int)sizeof(struct dfc_mbox_req));
mbox_req = (struct dfc_mbox_req *)
job->request->rqst_data.h_vendor.vendor_cmd;
mbox_req->extMboxTag = 0;
mbox_req->extSeqNum = 0;
}
rc = lpfc_bsg_issue_mbox(phba, job, vport);
if (rc == 0) {
/* job done */
job->reply->result = 0;
job->dd_data = NULL;
job->job_done(job);
} else if (rc == 1)
/* job submitted, will complete later*/
rc = 0; /* return zero, no error */
else {
/* some error occurred */
job->reply->result = rc;
job->dd_data = NULL;
}
return rc;
}
/**
* lpfc_bsg_menlo_cmd_cmp - lpfc_menlo_cmd completion handler
* @phba: Pointer to HBA context object.
* @cmdiocbq: Pointer to command iocb.
* @rspiocbq: Pointer to response iocb.
*
* This function is the completion handler for iocbs issued using
* lpfc_menlo_cmd function. This function is called by the
* ring event handler function without any lock held. This function
* can be called from both worker thread context and interrupt
* context. This function also can be called from another thread which
* cleans up the SLI layer objects.
* This function copies the contents of the response iocb to the
* response iocb memory object provided by the caller of
* lpfc_sli_issue_iocb_wait and then wakes up the thread which
* sleeps for the iocb completion.
**/
static void
lpfc_bsg_menlo_cmd_cmp(struct lpfc_hba *phba,
struct lpfc_iocbq *cmdiocbq,
struct lpfc_iocbq *rspiocbq)
{
struct bsg_job_data *dd_data;
struct fc_bsg_job *job;
IOCB_t *rsp;
struct lpfc_dmabuf *bmp;
struct lpfc_bsg_menlo *menlo;
unsigned long flags;
struct menlo_response *menlo_resp;
int rc = 0;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
dd_data = cmdiocbq->context1;
if (!dd_data) {
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
menlo = &dd_data->context_un.menlo;
job = menlo->set_job;
job->dd_data = NULL; /* so timeout handler does not reply */
spin_lock(&phba->hbalock);
cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
if (cmdiocbq->context2 && rspiocbq)
memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
&rspiocbq->iocb, sizeof(IOCB_t));
spin_unlock(&phba->hbalock);
bmp = menlo->bmp;
rspiocbq = menlo->rspiocbq;
rsp = &rspiocbq->iocb;
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
pci_unmap_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
/* always return the xri, this would be used in the case
* of a menlo download to allow the data to be sent as a continuation
* of the exchange.
*/
menlo_resp = (struct menlo_response *)
job->reply->reply_data.vendor_reply.vendor_rsp;
menlo_resp->xri = rsp->ulpContext;
if (rsp->ulpStatus) {
if (rsp->ulpStatus == IOSTAT_LOCAL_REJECT) {
switch (rsp->un.ulpWord[4] & 0xff) {
case IOERR_SEQUENCE_TIMEOUT:
rc = -ETIMEDOUT;
break;
case IOERR_INVALID_RPI:
rc = -EFAULT;
break;
default:
rc = -EACCES;
break;
}
} else
rc = -EACCES;
} else
job->reply->reply_payload_rcv_len =
rsp->un.genreq64.bdl.bdeSize;
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
lpfc_sli_release_iocbq(phba, rspiocbq);
lpfc_sli_release_iocbq(phba, cmdiocbq);
kfree(bmp);
kfree(dd_data);
/* make error code available to userspace */
job->reply->result = rc;
/* complete the job back to userspace */
job->job_done(job);
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return;
}
/**
* lpfc_menlo_cmd - send an ioctl for menlo hardware
* @job: fc_bsg_job to handle
*
* This function issues a gen request 64 CR ioctl for all menlo cmd requests,
* all the command completions will return the xri for the command.
* For menlo data requests a gen request 64 CX is used to continue the exchange
* supplied in the menlo request header xri field.
**/
static int
lpfc_menlo_cmd(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct lpfc_iocbq *cmdiocbq, *rspiocbq;
IOCB_t *cmd, *rsp;
int rc = 0;
struct menlo_command *menlo_cmd;
struct menlo_response *menlo_resp;
struct lpfc_dmabuf *bmp = NULL;
int request_nseg;
int reply_nseg;
struct scatterlist *sgel = NULL;
int numbde;
dma_addr_t busaddr;
struct bsg_job_data *dd_data;
struct ulp_bde64 *bpl = NULL;
/* in case no data is returned return just the return code */
job->reply->reply_payload_rcv_len = 0;
if (job->request_len <
sizeof(struct fc_bsg_request) +
sizeof(struct menlo_command)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2784 Received MENLO_CMD request below "
"minimum size\n");
rc = -ERANGE;
goto no_dd_data;
}
if (job->reply_len <
sizeof(struct fc_bsg_request) + sizeof(struct menlo_response)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2785 Received MENLO_CMD reply below "
"minimum size\n");
rc = -ERANGE;
goto no_dd_data;
}
if (!(phba->menlo_flag & HBA_MENLO_SUPPORT)) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2786 Adapter does not support menlo "
"commands\n");
rc = -EPERM;
goto no_dd_data;
}
menlo_cmd = (struct menlo_command *)
job->request->rqst_data.h_vendor.vendor_cmd;
menlo_resp = (struct menlo_response *)
job->reply->reply_data.vendor_reply.vendor_rsp;
/* allocate our bsg tracking structure */
dd_data = kmalloc(sizeof(struct bsg_job_data), GFP_KERNEL);
if (!dd_data) {
lpfc_printf_log(phba, KERN_WARNING, LOG_LIBDFC,
"2787 Failed allocation of dd_data\n");
rc = -ENOMEM;
goto no_dd_data;
}
bmp = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
if (!bmp) {
rc = -ENOMEM;
goto free_dd;
}
cmdiocbq = lpfc_sli_get_iocbq(phba);
if (!cmdiocbq) {
rc = -ENOMEM;
goto free_bmp;
}
rspiocbq = lpfc_sli_get_iocbq(phba);
if (!rspiocbq) {
rc = -ENOMEM;
goto free_cmdiocbq;
}
rsp = &rspiocbq->iocb;
bmp->virt = lpfc_mbuf_alloc(phba, 0, &bmp->phys);
if (!bmp->virt) {
rc = -ENOMEM;
goto free_rspiocbq;
}
INIT_LIST_HEAD(&bmp->list);
bpl = (struct ulp_bde64 *) bmp->virt;
request_nseg = pci_map_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
for_each_sg(job->request_payload.sg_list, sgel, request_nseg, numbde) {
busaddr = sg_dma_address(sgel);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64;
bpl->tus.f.bdeSize = sg_dma_len(sgel);
bpl->tus.w = cpu_to_le32(bpl->tus.w);
bpl->addrLow = cpu_to_le32(putPaddrLow(busaddr));
bpl->addrHigh = cpu_to_le32(putPaddrHigh(busaddr));
bpl++;
}
reply_nseg = pci_map_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
for_each_sg(job->reply_payload.sg_list, sgel, reply_nseg, numbde) {
busaddr = sg_dma_address(sgel);
bpl->tus.f.bdeFlags = BUFF_TYPE_BDE_64I;
bpl->tus.f.bdeSize = sg_dma_len(sgel);
bpl->tus.w = cpu_to_le32(bpl->tus.w);
bpl->addrLow = cpu_to_le32(putPaddrLow(busaddr));
bpl->addrHigh = cpu_to_le32(putPaddrHigh(busaddr));
bpl++;
}
cmd = &cmdiocbq->iocb;
cmd->un.genreq64.bdl.ulpIoTag32 = 0;
cmd->un.genreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
cmd->un.genreq64.bdl.addrLow = putPaddrLow(bmp->phys);
cmd->un.genreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
cmd->un.genreq64.bdl.bdeSize =
(request_nseg + reply_nseg) * sizeof(struct ulp_bde64);
cmd->un.genreq64.w5.hcsw.Fctl = (SI | LA);
cmd->un.genreq64.w5.hcsw.Dfctl = 0;
cmd->un.genreq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CMD;
cmd->un.genreq64.w5.hcsw.Type = MENLO_TRANSPORT_TYPE; /* 0xfe */
cmd->ulpBdeCount = 1;
cmd->ulpClass = CLASS3;
cmd->ulpOwner = OWN_CHIP;
cmd->ulpLe = 1; /* Limited Edition */
cmdiocbq->iocb_flag |= LPFC_IO_LIBDFC;
cmdiocbq->vport = phba->pport;
/* We want the firmware to timeout before we do */
cmd->ulpTimeout = MENLO_TIMEOUT - 5;
cmdiocbq->context3 = bmp;
cmdiocbq->context2 = rspiocbq;
cmdiocbq->iocb_cmpl = lpfc_bsg_menlo_cmd_cmp;
cmdiocbq->context1 = dd_data;
cmdiocbq->context2 = rspiocbq;
if (menlo_cmd->cmd == LPFC_BSG_VENDOR_MENLO_CMD) {
cmd->ulpCommand = CMD_GEN_REQUEST64_CR;
cmd->ulpPU = MENLO_PU; /* 3 */
cmd->un.ulpWord[4] = MENLO_DID; /* 0x0000FC0E */
cmd->ulpContext = MENLO_CONTEXT; /* 0 */
} else {
cmd->ulpCommand = CMD_GEN_REQUEST64_CX;
cmd->ulpPU = 1;
cmd->un.ulpWord[4] = 0;
cmd->ulpContext = menlo_cmd->xri;
}
dd_data->type = TYPE_MENLO;
dd_data->context_un.menlo.cmdiocbq = cmdiocbq;
dd_data->context_un.menlo.rspiocbq = rspiocbq;
dd_data->context_un.menlo.set_job = job;
dd_data->context_un.menlo.bmp = bmp;
rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, cmdiocbq,
MENLO_TIMEOUT - 5);
if (rc == IOCB_SUCCESS)
return 0; /* done for now */
/* iocb failed so cleanup */
pci_unmap_sg(phba->pcidev, job->request_payload.sg_list,
job->request_payload.sg_cnt, DMA_TO_DEVICE);
pci_unmap_sg(phba->pcidev, job->reply_payload.sg_list,
job->reply_payload.sg_cnt, DMA_FROM_DEVICE);
lpfc_mbuf_free(phba, bmp->virt, bmp->phys);
free_rspiocbq:
lpfc_sli_release_iocbq(phba, rspiocbq);
free_cmdiocbq:
lpfc_sli_release_iocbq(phba, cmdiocbq);
free_bmp:
kfree(bmp);
free_dd:
kfree(dd_data);
no_dd_data:
/* make error code available to userspace */
job->reply->result = rc;
job->dd_data = NULL;
return rc;
}
/**
* lpfc_bsg_hst_vendor - process a vendor-specific fc_bsg_job
* @job: fc_bsg_job to handle
**/
static int
lpfc_bsg_hst_vendor(struct fc_bsg_job *job)
{
int command = job->request->rqst_data.h_vendor.vendor_cmd[0];
int rc;
switch (command) {
case LPFC_BSG_VENDOR_SET_CT_EVENT:
rc = lpfc_bsg_hba_set_event(job);
break;
case LPFC_BSG_VENDOR_GET_CT_EVENT:
rc = lpfc_bsg_hba_get_event(job);
break;
case LPFC_BSG_VENDOR_SEND_MGMT_RESP:
rc = lpfc_bsg_send_mgmt_rsp(job);
break;
case LPFC_BSG_VENDOR_DIAG_MODE:
rc = lpfc_bsg_diag_loopback_mode(job);
break;
case LPFC_BSG_VENDOR_DIAG_MODE_END:
rc = lpfc_sli4_bsg_diag_mode_end(job);
break;
case LPFC_BSG_VENDOR_DIAG_RUN_LOOPBACK:
rc = lpfc_bsg_diag_loopback_run(job);
break;
case LPFC_BSG_VENDOR_LINK_DIAG_TEST:
rc = lpfc_sli4_bsg_link_diag_test(job);
break;
case LPFC_BSG_VENDOR_GET_MGMT_REV:
rc = lpfc_bsg_get_dfc_rev(job);
break;
case LPFC_BSG_VENDOR_MBOX:
rc = lpfc_bsg_mbox_cmd(job);
break;
case LPFC_BSG_VENDOR_MENLO_CMD:
case LPFC_BSG_VENDOR_MENLO_DATA:
rc = lpfc_menlo_cmd(job);
break;
default:
rc = -EINVAL;
job->reply->reply_payload_rcv_len = 0;
/* make error code available to userspace */
job->reply->result = rc;
break;
}
return rc;
}
/**
* lpfc_bsg_request - handle a bsg request from the FC transport
* @job: fc_bsg_job to handle
**/
int
lpfc_bsg_request(struct fc_bsg_job *job)
{
uint32_t msgcode;
int rc;
msgcode = job->request->msgcode;
switch (msgcode) {
case FC_BSG_HST_VENDOR:
rc = lpfc_bsg_hst_vendor(job);
break;
case FC_BSG_RPT_ELS:
rc = lpfc_bsg_rport_els(job);
break;
case FC_BSG_RPT_CT:
rc = lpfc_bsg_send_mgmt_cmd(job);
break;
default:
rc = -EINVAL;
job->reply->reply_payload_rcv_len = 0;
/* make error code available to userspace */
job->reply->result = rc;
break;
}
return rc;
}
/**
* lpfc_bsg_timeout - handle timeout of a bsg request from the FC transport
* @job: fc_bsg_job that has timed out
*
* This function just aborts the job's IOCB. The aborted IOCB will return to
* the waiting function which will handle passing the error back to userspace
**/
int
lpfc_bsg_timeout(struct fc_bsg_job *job)
{
struct lpfc_vport *vport = (struct lpfc_vport *)job->shost->hostdata;
struct lpfc_hba *phba = vport->phba;
struct lpfc_iocbq *cmdiocb;
struct lpfc_bsg_event *evt;
struct lpfc_bsg_iocb *iocb;
struct lpfc_bsg_mbox *mbox;
struct lpfc_bsg_menlo *menlo;
struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
struct bsg_job_data *dd_data;
unsigned long flags;
spin_lock_irqsave(&phba->ct_ev_lock, flags);
dd_data = (struct bsg_job_data *)job->dd_data;
/* timeout and completion crossed paths if no dd_data */
if (!dd_data) {
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
return 0;
}
switch (dd_data->type) {
case TYPE_IOCB:
iocb = &dd_data->context_un.iocb;
cmdiocb = iocb->cmdiocbq;
/* hint to completion handler that the job timed out */
job->reply->result = -EAGAIN;
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
/* this will call our completion handler */
spin_lock_irq(&phba->hbalock);
lpfc_sli_issue_abort_iotag(phba, pring, cmdiocb);
spin_unlock_irq(&phba->hbalock);
break;
case TYPE_EVT:
evt = dd_data->context_un.evt;
/* this event has no job anymore */
evt->set_job = NULL;
job->dd_data = NULL;
job->reply->reply_payload_rcv_len = 0;
/* Return -EAGAIN which is our way of signallying the
* app to retry.
*/
job->reply->result = -EAGAIN;
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
job->job_done(job);
break;
case TYPE_MBOX:
mbox = &dd_data->context_un.mbox;
/* this mbox has no job anymore */
mbox->set_job = NULL;
job->dd_data = NULL;
job->reply->reply_payload_rcv_len = 0;
job->reply->result = -EAGAIN;
/* the mbox completion handler can now be run */
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
job->job_done(job);
if (phba->mbox_ext_buf_ctx.state == LPFC_BSG_MBOX_PORT)
phba->mbox_ext_buf_ctx.state = LPFC_BSG_MBOX_ABTS;
break;
case TYPE_MENLO:
menlo = &dd_data->context_un.menlo;
cmdiocb = menlo->cmdiocbq;
/* hint to completion handler that the job timed out */
job->reply->result = -EAGAIN;
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
/* this will call our completion handler */
spin_lock_irq(&phba->hbalock);
lpfc_sli_issue_abort_iotag(phba, pring, cmdiocb);
spin_unlock_irq(&phba->hbalock);
break;
default:
spin_unlock_irqrestore(&phba->ct_ev_lock, flags);
break;
}
/* scsi transport fc fc_bsg_job_timeout expects a zero return code,
* otherwise an error message will be displayed on the console
* so always return success (zero)
*/
return 0;
}
| gpl-2.0 |
flar2/xoom-ElementalX | drivers/scsi/pas16.c | 5064 | 18258 | #define AUTOSENSE
#define PSEUDO_DMA
#define FOO
#define UNSAFE /* Not unsafe for PAS16 -- use it */
#define PDEBUG 0
/*
* This driver adapted from Drew Eckhardt's Trantor T128 driver
*
* Copyright 1993, Drew Eckhardt
* Visionary Computing
* (Unix and Linux consulting and custom programming)
* drew@colorado.edu
* +1 (303) 666-5836
*
* ( Based on T128 - DISTRIBUTION RELEASE 3. )
*
* Modified to work with the Pro Audio Spectrum/Studio 16
* by John Weidman.
*
*
* For more information, please consult
*
* Media Vision
* (510) 770-8600
* (800) 348-7116
*
* and
*
* NCR 5380 Family
* SCSI Protocol Controller
* Databook
*
* NCR Microelectronics
* 1635 Aeroplaza Drive
* Colorado Springs, CO 80916
* 1+ (719) 578-3400
* 1+ (800) 334-5454
*/
/*
* Options :
* AUTOSENSE - if defined, REQUEST SENSE will be performed automatically
* for commands that return with a CHECK CONDITION status.
*
* LIMIT_TRANSFERSIZE - if defined, limit the pseudo-dma transfers to 512
* bytes at a time. Since interrupts are disabled by default during
* these transfers, we might need this to give reasonable interrupt
* service time if the transfer size gets too large.
*
* PSEUDO_DMA - enables PSEUDO-DMA hardware, should give a 3-4X performance
* increase compared to polled I/O.
*
* PARITY - enable parity checking. Not supported.
*
* SCSI2 - enable support for SCSI-II tagged queueing. Untested.
*
* UNSAFE - leave interrupts enabled during pseudo-DMA transfers. This
* parameter comes from the NCR5380 code. It is NOT unsafe with
* the PAS16 and you should use it. If you don't you will have
* a problem with dropped characters during high speed
* communications during SCSI transfers. If you really don't
* want to use UNSAFE you can try defining LIMIT_TRANSFERSIZE or
* twiddle with the transfer size in the high level code.
*
* USLEEP - enable support for devices that don't disconnect. Untested.
*
* The card is detected and initialized in one of several ways :
* 1. Autoprobe (default) - There are many different models of
* the Pro Audio Spectrum/Studio 16, and I only have one of
* them, so this may require a little tweaking. An interrupt
* is triggered to autoprobe for the interrupt line. Note:
* with the newer model boards, the interrupt is set via
* software after reset using the default_irq for the
* current board number.
*
* 2. With command line overrides - pas16=port,irq may be
* used on the LILO command line to override the defaults.
*
* 3. With the PAS16_OVERRIDE compile time define. This is
* specified as an array of address, irq tuples. Ie, for
* one board at the default 0x388 address, IRQ10, I could say
* -DPAS16_OVERRIDE={{0x388, 10}}
* NOTE: Untested.
*
* 4. When included as a module, with arguments passed on the command line:
* pas16_irq=xx the interrupt
* pas16_addr=xx the port
* e.g. "modprobe pas16 pas16_addr=0x388 pas16_irq=5"
*
* Note that if the override methods are used, place holders must
* be specified for other boards in the system.
*
*
* Configuration notes :
* The current driver does not support interrupt sharing with the
* sound portion of the card. If you use the same irq for the
* scsi port and sound you will have problems. Either use
* a different irq for the scsi port or don't use interrupts
* for the scsi port.
*
* If you have problems with your card not being recognized, use
* the LILO command line override. Try to get it recognized without
* interrupts. Ie, for a board at the default 0x388 base port,
* boot: linux pas16=0x388,255
*
* SCSI_IRQ_NONE (255) should be specified for no interrupt,
* IRQ_AUTO (254) to autoprobe for an IRQ line if overridden
* on the command line.
*
* (IRQ_AUTO == 254, SCSI_IRQ_NONE == 255 in NCR5380.h)
*/
#include <linux/module.h>
#include <asm/system.h>
#include <linux/signal.h>
#include <linux/proc_fs.h>
#include <asm/io.h>
#include <asm/dma.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/stat.h>
#include <linux/init.h>
#include "scsi.h"
#include <scsi/scsi_host.h>
#include "pas16.h"
#define AUTOPROBE_IRQ
#include "NCR5380.h"
static int pas_maxi = 0;
static int pas_wmaxi = 0;
static unsigned short pas16_addr = 0;
static int pas16_irq = 0;
static const int scsi_irq_translate[] =
{ 0, 0, 1, 2, 3, 4, 5, 6, 0, 0, 7, 8, 9, 0, 10, 11 };
/* The default_irqs array contains values used to set the irq into the
* board via software (as must be done on newer model boards without
* irq jumpers on the board). The first value in the array will be
* assigned to logical board 0, the next to board 1, etc.
*/
static int default_irqs[] __initdata =
{ PAS16_DEFAULT_BOARD_1_IRQ,
PAS16_DEFAULT_BOARD_2_IRQ,
PAS16_DEFAULT_BOARD_3_IRQ,
PAS16_DEFAULT_BOARD_4_IRQ
};
static struct override {
unsigned short io_port;
int irq;
} overrides
#ifdef PAS16_OVERRIDE
[] __initdata = PAS16_OVERRIDE;
#else
[4] __initdata = {{0,IRQ_AUTO}, {0,IRQ_AUTO}, {0,IRQ_AUTO},
{0,IRQ_AUTO}};
#endif
#define NO_OVERRIDES ARRAY_SIZE(overrides)
static struct base {
unsigned short io_port;
int noauto;
} bases[] __initdata =
{ {PAS16_DEFAULT_BASE_1, 0},
{PAS16_DEFAULT_BASE_2, 0},
{PAS16_DEFAULT_BASE_3, 0},
{PAS16_DEFAULT_BASE_4, 0}
};
#define NO_BASES ARRAY_SIZE(bases)
static const unsigned short pas16_offset[ 8 ] =
{
0x1c00, /* OUTPUT_DATA_REG */
0x1c01, /* INITIATOR_COMMAND_REG */
0x1c02, /* MODE_REG */
0x1c03, /* TARGET_COMMAND_REG */
0x3c00, /* STATUS_REG ro, SELECT_ENABLE_REG wo */
0x3c01, /* BUS_AND_STATUS_REG ro, START_DMA_SEND_REG wo */
0x3c02, /* INPUT_DATA_REGISTER ro, (N/A on PAS16 ?)
* START_DMA_TARGET_RECEIVE_REG wo
*/
0x3c03, /* RESET_PARITY_INTERRUPT_REG ro,
* START_DMA_INITIATOR_RECEIVE_REG wo
*/
};
/*----------------------------------------------------------------*/
/* the following will set the monitor border color (useful to find
where something crashed or gets stuck at */
/* 1 = blue
2 = green
3 = cyan
4 = red
5 = magenta
6 = yellow
7 = white
*/
#if 1
#define rtrc(i) {inb(0x3da); outb(0x31, 0x3c0); outb((i), 0x3c0);}
#else
#define rtrc(i) {}
#endif
/*
* Function : enable_board( int board_num, unsigned short port )
*
* Purpose : set address in new model board
*
* Inputs : board_num - logical board number 0-3, port - base address
*
*/
static void __init
enable_board( int board_num, unsigned short port )
{
outb( 0xbc + board_num, MASTER_ADDRESS_PTR );
outb( port >> 2, MASTER_ADDRESS_PTR );
}
/*
* Function : init_board( unsigned short port, int irq )
*
* Purpose : Set the board up to handle the SCSI interface
*
* Inputs : port - base address of the board,
* irq - irq to assign to the SCSI port
* force_irq - set it even if it conflicts with sound driver
*
*/
static void __init
init_board( unsigned short io_port, int irq, int force_irq )
{
unsigned int tmp;
unsigned int pas_irq_code;
/* Initialize the SCSI part of the board */
outb( 0x30, io_port + P_TIMEOUT_COUNTER_REG ); /* Timeout counter */
outb( 0x01, io_port + P_TIMEOUT_STATUS_REG_OFFSET ); /* Reset TC */
outb( 0x01, io_port + WAIT_STATE ); /* 1 Wait state */
NCR5380_read( RESET_PARITY_INTERRUPT_REG );
/* Set the SCSI interrupt pointer without mucking up the sound
* interrupt pointer in the same byte.
*/
pas_irq_code = ( irq < 16 ) ? scsi_irq_translate[irq] : 0;
tmp = inb( io_port + IO_CONFIG_3 );
if( (( tmp & 0x0f ) == pas_irq_code) && pas_irq_code > 0
&& !force_irq )
{
printk( "pas16: WARNING: Can't use same irq as sound "
"driver -- interrupts disabled\n" );
/* Set up the drive parameters, disable 5380 interrupts */
outb( 0x4d, io_port + SYS_CONFIG_4 );
}
else
{
tmp = ( tmp & 0x0f ) | ( pas_irq_code << 4 );
outb( tmp, io_port + IO_CONFIG_3 );
/* Set up the drive parameters and enable 5380 interrupts */
outb( 0x6d, io_port + SYS_CONFIG_4 );
}
}
/*
* Function : pas16_hw_detect( unsigned short board_num )
*
* Purpose : determine if a pas16 board is present
*
* Inputs : board_num - logical board number ( 0 - 3 )
*
* Returns : 0 if board not found, 1 if found.
*/
static int __init
pas16_hw_detect( unsigned short board_num )
{
unsigned char board_rev, tmp;
unsigned short io_port = bases[ board_num ].io_port;
/* See if we can find a PAS16 board at the address associated
* with this logical board number.
*/
/* First, attempt to take a newer model board out of reset and
* give it a base address. This shouldn't affect older boards.
*/
enable_board( board_num, io_port );
/* Now see if it looks like a PAS16 board */
board_rev = inb( io_port + PCB_CONFIG );
if( board_rev == 0xff )
return 0;
tmp = board_rev ^ 0xe0;
outb( tmp, io_port + PCB_CONFIG );
tmp = inb( io_port + PCB_CONFIG );
outb( board_rev, io_port + PCB_CONFIG );
if( board_rev != tmp ) /* Not a PAS-16 */
return 0;
if( ( inb( io_port + OPERATION_MODE_1 ) & 0x03 ) != 0x03 )
return 0; /* return if no SCSI interface found */
/* Mediavision has some new model boards that return ID bits
* that indicate a SCSI interface, but they're not (LMS). We'll
* put in an additional test to try to weed them out.
*/
outb( 0x01, io_port + WAIT_STATE ); /* 1 Wait state */
NCR5380_write( MODE_REG, 0x20 ); /* Is it really SCSI? */
if( NCR5380_read( MODE_REG ) != 0x20 ) /* Write to a reg. */
return 0; /* and try to read */
NCR5380_write( MODE_REG, 0x00 ); /* it back. */
if( NCR5380_read( MODE_REG ) != 0x00 )
return 0;
return 1;
}
/*
* Function : pas16_setup(char *str, int *ints)
*
* Purpose : LILO command line initialization of the overrides array,
*
* Inputs : str - unused, ints - array of integer parameters with ints[0]
* equal to the number of ints.
*
*/
void __init pas16_setup(char *str, int *ints)
{
static int commandline_current = 0;
int i;
if (ints[0] != 2)
printk("pas16_setup : usage pas16=io_port,irq\n");
else
if (commandline_current < NO_OVERRIDES) {
overrides[commandline_current].io_port = (unsigned short) ints[1];
overrides[commandline_current].irq = ints[2];
for (i = 0; i < NO_BASES; ++i)
if (bases[i].io_port == (unsigned short) ints[1]) {
bases[i].noauto = 1;
break;
}
++commandline_current;
}
}
/*
* Function : int pas16_detect(struct scsi_host_template * tpnt)
*
* Purpose : detects and initializes PAS16 controllers
* that were autoprobed, overridden on the LILO command line,
* or specified at compile time.
*
* Inputs : tpnt - template for this SCSI adapter.
*
* Returns : 1 if a host adapter was found, 0 if not.
*
*/
int __init pas16_detect(struct scsi_host_template * tpnt)
{
static int current_override = 0;
static unsigned short current_base = 0;
struct Scsi_Host *instance;
unsigned short io_port;
int count;
tpnt->proc_name = "pas16";
tpnt->proc_info = &pas16_proc_info;
if (pas16_addr != 0) {
overrides[0].io_port = pas16_addr;
/*
* This is how we avoid seeing more than
* one host adapter at the same I/O port.
* Cribbed shamelessly from pas16_setup().
*/
for (count = 0; count < NO_BASES; ++count)
if (bases[count].io_port == pas16_addr) {
bases[count].noauto = 1;
break;
}
}
if (pas16_irq != 0)
overrides[0].irq = pas16_irq;
for (count = 0; current_override < NO_OVERRIDES; ++current_override) {
io_port = 0;
if (overrides[current_override].io_port)
{
io_port = overrides[current_override].io_port;
enable_board( current_override, io_port );
init_board( io_port, overrides[current_override].irq, 1 );
}
else
for (; !io_port && (current_base < NO_BASES); ++current_base) {
#if (PDEBUG & PDEBUG_INIT)
printk("scsi-pas16 : probing io_port %04x\n", (unsigned int) bases[current_base].io_port);
#endif
if ( !bases[current_base].noauto &&
pas16_hw_detect( current_base ) ){
io_port = bases[current_base].io_port;
init_board( io_port, default_irqs[ current_base ], 0 );
#if (PDEBUG & PDEBUG_INIT)
printk("scsi-pas16 : detected board.\n");
#endif
}
}
#if defined(PDEBUG) && (PDEBUG & PDEBUG_INIT)
printk("scsi-pas16 : io_port = %04x\n", (unsigned int) io_port);
#endif
if (!io_port)
break;
instance = scsi_register (tpnt, sizeof(struct NCR5380_hostdata));
if(instance == NULL)
break;
instance->io_port = io_port;
NCR5380_init(instance, 0);
if (overrides[current_override].irq != IRQ_AUTO)
instance->irq = overrides[current_override].irq;
else
instance->irq = NCR5380_probe_irq(instance, PAS16_IRQS);
if (instance->irq != SCSI_IRQ_NONE)
if (request_irq(instance->irq, pas16_intr, IRQF_DISABLED,
"pas16", instance)) {
printk("scsi%d : IRQ%d not free, interrupts disabled\n",
instance->host_no, instance->irq);
instance->irq = SCSI_IRQ_NONE;
}
if (instance->irq == SCSI_IRQ_NONE) {
printk("scsi%d : interrupts not enabled. for better interactive performance,\n", instance->host_no);
printk("scsi%d : please jumper the board for a free IRQ.\n", instance->host_no);
/* Disable 5380 interrupts, leave drive params the same */
outb( 0x4d, io_port + SYS_CONFIG_4 );
outb( (inb(io_port + IO_CONFIG_3) & 0x0f), io_port + IO_CONFIG_3 );
}
#if defined(PDEBUG) && (PDEBUG & PDEBUG_INIT)
printk("scsi%d : irq = %d\n", instance->host_no, instance->irq);
#endif
printk("scsi%d : at 0x%04x", instance->host_no, (int)
instance->io_port);
if (instance->irq == SCSI_IRQ_NONE)
printk (" interrupts disabled");
else
printk (" irq %d", instance->irq);
printk(" options CAN_QUEUE=%d CMD_PER_LUN=%d release=%d",
CAN_QUEUE, CMD_PER_LUN, PAS16_PUBLIC_RELEASE);
NCR5380_print_options(instance);
printk("\n");
++current_override;
++count;
}
return count;
}
/*
* Function : int pas16_biosparam(Disk *disk, struct block_device *dev, int *ip)
*
* Purpose : Generates a BIOS / DOS compatible H-C-S mapping for
* the specified device / size.
*
* Inputs : size = size of device in sectors (512 bytes), dev = block device
* major / minor, ip[] = {heads, sectors, cylinders}
*
* Returns : always 0 (success), initializes ip
*
*/
/*
* XXX Most SCSI boards use this mapping, I could be incorrect. Some one
* using hard disks on a trantor should verify that this mapping corresponds
* to that used by the BIOS / ASPI driver by running the linux fdisk program
* and matching the H_C_S coordinates to what DOS uses.
*/
int pas16_biosparam(struct scsi_device *sdev, struct block_device *dev,
sector_t capacity, int * ip)
{
int size = capacity;
ip[0] = 64;
ip[1] = 32;
ip[2] = size >> 11; /* I think I have it as /(32*64) */
if( ip[2] > 1024 ) { /* yes, >, not >= */
ip[0]=255;
ip[1]=63;
ip[2]=size/(63*255);
if( ip[2] > 1023 ) /* yes >1023... */
ip[2] = 1023;
}
return 0;
}
/*
* Function : int NCR5380_pread (struct Scsi_Host *instance,
* unsigned char *dst, int len)
*
* Purpose : Fast 5380 pseudo-dma read function, transfers len bytes to
* dst
*
* Inputs : dst = destination, len = length in bytes
*
* Returns : 0 on success, non zero on a failure such as a watchdog
* timeout.
*/
static inline int NCR5380_pread (struct Scsi_Host *instance, unsigned char *dst,
int len) {
register unsigned char *d = dst;
register unsigned short reg = (unsigned short) (instance->io_port +
P_DATA_REG_OFFSET);
register int i = len;
int ii = 0;
while ( !(inb(instance->io_port + P_STATUS_REG_OFFSET) & P_ST_RDY) )
++ii;
insb( reg, d, i );
if ( inb(instance->io_port + P_TIMEOUT_STATUS_REG_OFFSET) & P_TS_TIM) {
outb( P_TS_CT, instance->io_port + P_TIMEOUT_STATUS_REG_OFFSET);
printk("scsi%d : watchdog timer fired in NCR5380_pread()\n",
instance->host_no);
return -1;
}
if (ii > pas_maxi)
pas_maxi = ii;
return 0;
}
/*
* Function : int NCR5380_pwrite (struct Scsi_Host *instance,
* unsigned char *src, int len)
*
* Purpose : Fast 5380 pseudo-dma write function, transfers len bytes from
* src
*
* Inputs : src = source, len = length in bytes
*
* Returns : 0 on success, non zero on a failure such as a watchdog
* timeout.
*/
static inline int NCR5380_pwrite (struct Scsi_Host *instance, unsigned char *src,
int len) {
register unsigned char *s = src;
register unsigned short reg = (instance->io_port + P_DATA_REG_OFFSET);
register int i = len;
int ii = 0;
while ( !((inb(instance->io_port + P_STATUS_REG_OFFSET)) & P_ST_RDY) )
++ii;
outsb( reg, s, i );
if (inb(instance->io_port + P_TIMEOUT_STATUS_REG_OFFSET) & P_TS_TIM) {
outb( P_TS_CT, instance->io_port + P_TIMEOUT_STATUS_REG_OFFSET);
printk("scsi%d : watchdog timer fired in NCR5380_pwrite()\n",
instance->host_no);
return -1;
}
if (ii > pas_maxi)
pas_wmaxi = ii;
return 0;
}
#include "NCR5380.c"
static int pas16_release(struct Scsi_Host *shost)
{
if (shost->irq)
free_irq(shost->irq, shost);
NCR5380_exit(shost);
if (shost->dma_channel != 0xff)
free_dma(shost->dma_channel);
if (shost->io_port && shost->n_io_port)
release_region(shost->io_port, shost->n_io_port);
scsi_unregister(shost);
return 0;
}
static struct scsi_host_template driver_template = {
.name = "Pro Audio Spectrum-16 SCSI",
.detect = pas16_detect,
.release = pas16_release,
.queuecommand = pas16_queue_command,
.eh_abort_handler = pas16_abort,
.eh_bus_reset_handler = pas16_bus_reset,
.bios_param = pas16_biosparam,
.can_queue = CAN_QUEUE,
.this_id = 7,
.sg_tablesize = SG_ALL,
.cmd_per_lun = CMD_PER_LUN,
.use_clustering = DISABLE_CLUSTERING,
};
#include "scsi_module.c"
#ifdef MODULE
module_param(pas16_addr, ushort, 0);
module_param(pas16_irq, int, 0);
#endif
MODULE_LICENSE("GPL");
| gpl-2.0 |
NoelMacwan/SXDNickiUnified | arch/x86/kernel/apic/hw_nmi.c | 5320 | 2150 | /*
* HW NMI watchdog support
*
* started by Don Zickus, Copyright (C) 2010 Red Hat, Inc.
*
* Arch specific calls to support NMI watchdog
*
* Bits copied from original nmi.c file
*
*/
#include <asm/apic.h>
#include <linux/cpumask.h>
#include <linux/kdebug.h>
#include <linux/notifier.h>
#include <linux/kprobes.h>
#include <linux/nmi.h>
#include <linux/module.h>
#include <linux/delay.h>
#ifdef CONFIG_HARDLOCKUP_DETECTOR
u64 hw_nmi_get_sample_period(int watchdog_thresh)
{
return (u64)(cpu_khz) * 1000 * watchdog_thresh;
}
#endif
#ifdef arch_trigger_all_cpu_backtrace
/* For reliability, we're prepared to waste bits here. */
static DECLARE_BITMAP(backtrace_mask, NR_CPUS) __read_mostly;
/* "in progress" flag of arch_trigger_all_cpu_backtrace */
static unsigned long backtrace_flag;
void arch_trigger_all_cpu_backtrace(void)
{
int i;
if (test_and_set_bit(0, &backtrace_flag))
/*
* If there is already a trigger_all_cpu_backtrace() in progress
* (backtrace_flag == 1), don't output double cpu dump infos.
*/
return;
cpumask_copy(to_cpumask(backtrace_mask), cpu_online_mask);
printk(KERN_INFO "sending NMI to all CPUs:\n");
apic->send_IPI_all(NMI_VECTOR);
/* Wait for up to 10 seconds for all CPUs to do the backtrace */
for (i = 0; i < 10 * 1000; i++) {
if (cpumask_empty(to_cpumask(backtrace_mask)))
break;
mdelay(1);
}
clear_bit(0, &backtrace_flag);
smp_mb__after_clear_bit();
}
static int __kprobes
arch_trigger_all_cpu_backtrace_handler(unsigned int cmd, struct pt_regs *regs)
{
int cpu;
cpu = smp_processor_id();
if (cpumask_test_cpu(cpu, to_cpumask(backtrace_mask))) {
static arch_spinlock_t lock = __ARCH_SPIN_LOCK_UNLOCKED;
arch_spin_lock(&lock);
printk(KERN_WARNING "NMI backtrace for cpu %d\n", cpu);
show_regs(regs);
arch_spin_unlock(&lock);
cpumask_clear_cpu(cpu, to_cpumask(backtrace_mask));
return NMI_HANDLED;
}
return NMI_DONE;
}
static int __init register_trigger_all_cpu_backtrace(void)
{
register_nmi_handler(NMI_LOCAL, arch_trigger_all_cpu_backtrace_handler,
0, "arch_bt");
return 0;
}
early_initcall(register_trigger_all_cpu_backtrace);
#endif
| gpl-2.0 |
syhost/android_kernel_xiaomi_msm8226-common | arch/powerpc/platforms/cell/celleb_pci.c | 7368 | 12174 | /*
* Support for PCI on Celleb platform.
*
* (C) Copyright 2006-2007 TOSHIBA CORPORATION
*
* This code is based on arch/powerpc/kernel/rtas_pci.c:
* Copyright (C) 2001 Dave Engebretsen, IBM Corporation
* Copyright (C) 2003 Anton Blanchard <anton@au.ibm.com>, IBM
*
* 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.
*/
#undef DEBUG
#include <linux/kernel.h>
#include <linux/threads.h>
#include <linux/pci.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/pci_regs.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/slab.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/prom.h>
#include <asm/pci-bridge.h>
#include <asm/ppc-pci.h>
#include "celleb_pci.h"
#define MAX_PCI_DEVICES 32
#define MAX_PCI_FUNCTIONS 8
#define MAX_PCI_BASE_ADDRS 3 /* use 64 bit address */
/* definition for fake pci configuration area for GbE, .... ,and etc. */
struct celleb_pci_resource {
struct resource r[MAX_PCI_BASE_ADDRS];
};
struct celleb_pci_private {
unsigned char *fake_config[MAX_PCI_DEVICES][MAX_PCI_FUNCTIONS];
struct celleb_pci_resource *res[MAX_PCI_DEVICES][MAX_PCI_FUNCTIONS];
};
static inline u8 celleb_fake_config_readb(void *addr)
{
u8 *p = addr;
return *p;
}
static inline u16 celleb_fake_config_readw(void *addr)
{
__le16 *p = addr;
return le16_to_cpu(*p);
}
static inline u32 celleb_fake_config_readl(void *addr)
{
__le32 *p = addr;
return le32_to_cpu(*p);
}
static inline void celleb_fake_config_writeb(u32 val, void *addr)
{
u8 *p = addr;
*p = val;
}
static inline void celleb_fake_config_writew(u32 val, void *addr)
{
__le16 val16;
__le16 *p = addr;
val16 = cpu_to_le16(val);
*p = val16;
}
static inline void celleb_fake_config_writel(u32 val, void *addr)
{
__le32 val32;
__le32 *p = addr;
val32 = cpu_to_le32(val);
*p = val32;
}
static unsigned char *get_fake_config_start(struct pci_controller *hose,
int devno, int fn)
{
struct celleb_pci_private *private = hose->private_data;
if (private == NULL)
return NULL;
return private->fake_config[devno][fn];
}
static struct celleb_pci_resource *get_resource_start(
struct pci_controller *hose,
int devno, int fn)
{
struct celleb_pci_private *private = hose->private_data;
if (private == NULL)
return NULL;
return private->res[devno][fn];
}
static void celleb_config_read_fake(unsigned char *config, int where,
int size, u32 *val)
{
char *p = config + where;
switch (size) {
case 1:
*val = celleb_fake_config_readb(p);
break;
case 2:
*val = celleb_fake_config_readw(p);
break;
case 4:
*val = celleb_fake_config_readl(p);
break;
}
}
static void celleb_config_write_fake(unsigned char *config, int where,
int size, u32 val)
{
char *p = config + where;
switch (size) {
case 1:
celleb_fake_config_writeb(val, p);
break;
case 2:
celleb_fake_config_writew(val, p);
break;
case 4:
celleb_fake_config_writel(val, p);
break;
}
}
static int celleb_fake_pci_read_config(struct pci_bus *bus,
unsigned int devfn, int where, int size, u32 *val)
{
char *config;
struct pci_controller *hose = pci_bus_to_host(bus);
unsigned int devno = devfn >> 3;
unsigned int fn = devfn & 0x7;
/* allignment check */
BUG_ON(where % size);
pr_debug(" fake read: bus=0x%x, ", bus->number);
config = get_fake_config_start(hose, devno, fn);
pr_debug("devno=0x%x, where=0x%x, size=0x%x, ", devno, where, size);
if (!config) {
pr_debug("failed\n");
return PCIBIOS_DEVICE_NOT_FOUND;
}
celleb_config_read_fake(config, where, size, val);
pr_debug("val=0x%x\n", *val);
return PCIBIOS_SUCCESSFUL;
}
static int celleb_fake_pci_write_config(struct pci_bus *bus,
unsigned int devfn, int where, int size, u32 val)
{
char *config;
struct pci_controller *hose = pci_bus_to_host(bus);
struct celleb_pci_resource *res;
unsigned int devno = devfn >> 3;
unsigned int fn = devfn & 0x7;
/* allignment check */
BUG_ON(where % size);
config = get_fake_config_start(hose, devno, fn);
if (!config)
return PCIBIOS_DEVICE_NOT_FOUND;
if (val == ~0) {
int i = (where - PCI_BASE_ADDRESS_0) >> 3;
switch (where) {
case PCI_BASE_ADDRESS_0:
case PCI_BASE_ADDRESS_2:
if (size != 4)
return PCIBIOS_DEVICE_NOT_FOUND;
res = get_resource_start(hose, devno, fn);
if (!res)
return PCIBIOS_DEVICE_NOT_FOUND;
celleb_config_write_fake(config, where, size,
(res->r[i].end - res->r[i].start));
return PCIBIOS_SUCCESSFUL;
case PCI_BASE_ADDRESS_1:
case PCI_BASE_ADDRESS_3:
case PCI_BASE_ADDRESS_4:
case PCI_BASE_ADDRESS_5:
break;
default:
break;
}
}
celleb_config_write_fake(config, where, size, val);
pr_debug(" fake write: where=%x, size=%d, val=%x\n",
where, size, val);
return PCIBIOS_SUCCESSFUL;
}
static struct pci_ops celleb_fake_pci_ops = {
.read = celleb_fake_pci_read_config,
.write = celleb_fake_pci_write_config,
};
static inline void celleb_setup_pci_base_addrs(struct pci_controller *hose,
unsigned int devno, unsigned int fn,
unsigned int num_base_addr)
{
u32 val;
unsigned char *config;
struct celleb_pci_resource *res;
config = get_fake_config_start(hose, devno, fn);
res = get_resource_start(hose, devno, fn);
if (!config || !res)
return;
switch (num_base_addr) {
case 3:
val = (res->r[2].start & 0xfffffff0)
| PCI_BASE_ADDRESS_MEM_TYPE_64;
celleb_config_write_fake(config, PCI_BASE_ADDRESS_4, 4, val);
val = res->r[2].start >> 32;
celleb_config_write_fake(config, PCI_BASE_ADDRESS_5, 4, val);
/* FALLTHROUGH */
case 2:
val = (res->r[1].start & 0xfffffff0)
| PCI_BASE_ADDRESS_MEM_TYPE_64;
celleb_config_write_fake(config, PCI_BASE_ADDRESS_2, 4, val);
val = res->r[1].start >> 32;
celleb_config_write_fake(config, PCI_BASE_ADDRESS_3, 4, val);
/* FALLTHROUGH */
case 1:
val = (res->r[0].start & 0xfffffff0)
| PCI_BASE_ADDRESS_MEM_TYPE_64;
celleb_config_write_fake(config, PCI_BASE_ADDRESS_0, 4, val);
val = res->r[0].start >> 32;
celleb_config_write_fake(config, PCI_BASE_ADDRESS_1, 4, val);
break;
}
val = PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER;
celleb_config_write_fake(config, PCI_COMMAND, 2, val);
}
static int __init celleb_setup_fake_pci_device(struct device_node *node,
struct pci_controller *hose)
{
unsigned int rlen;
int num_base_addr = 0;
u32 val;
const u32 *wi0, *wi1, *wi2, *wi3, *wi4;
unsigned int devno, fn;
struct celleb_pci_private *private = hose->private_data;
unsigned char **config = NULL;
struct celleb_pci_resource **res = NULL;
const char *name;
const unsigned long *li;
int size, result;
if (private == NULL) {
printk(KERN_ERR "PCI: "
"memory space for pci controller is not assigned\n");
goto error;
}
name = of_get_property(node, "model", &rlen);
if (!name) {
printk(KERN_ERR "PCI: model property not found.\n");
goto error;
}
wi4 = of_get_property(node, "reg", &rlen);
if (wi4 == NULL)
goto error;
devno = ((wi4[0] >> 8) & 0xff) >> 3;
fn = (wi4[0] >> 8) & 0x7;
pr_debug("PCI: celleb_setup_fake_pci() %s devno=%x fn=%x\n", name,
devno, fn);
size = 256;
config = &private->fake_config[devno][fn];
*config = zalloc_maybe_bootmem(size, GFP_KERNEL);
if (*config == NULL) {
printk(KERN_ERR "PCI: "
"not enough memory for fake configuration space\n");
goto error;
}
pr_debug("PCI: fake config area assigned 0x%016lx\n",
(unsigned long)*config);
size = sizeof(struct celleb_pci_resource);
res = &private->res[devno][fn];
*res = zalloc_maybe_bootmem(size, GFP_KERNEL);
if (*res == NULL) {
printk(KERN_ERR
"PCI: not enough memory for resource data space\n");
goto error;
}
pr_debug("PCI: res assigned 0x%016lx\n", (unsigned long)*res);
wi0 = of_get_property(node, "device-id", NULL);
wi1 = of_get_property(node, "vendor-id", NULL);
wi2 = of_get_property(node, "class-code", NULL);
wi3 = of_get_property(node, "revision-id", NULL);
if (!wi0 || !wi1 || !wi2 || !wi3) {
printk(KERN_ERR "PCI: Missing device tree properties.\n");
goto error;
}
celleb_config_write_fake(*config, PCI_DEVICE_ID, 2, wi0[0] & 0xffff);
celleb_config_write_fake(*config, PCI_VENDOR_ID, 2, wi1[0] & 0xffff);
pr_debug("class-code = 0x%08x\n", wi2[0]);
celleb_config_write_fake(*config, PCI_CLASS_PROG, 1, wi2[0] & 0xff);
celleb_config_write_fake(*config, PCI_CLASS_DEVICE, 2,
(wi2[0] >> 8) & 0xffff);
celleb_config_write_fake(*config, PCI_REVISION_ID, 1, wi3[0]);
while (num_base_addr < MAX_PCI_BASE_ADDRS) {
result = of_address_to_resource(node,
num_base_addr, &(*res)->r[num_base_addr]);
if (result)
break;
num_base_addr++;
}
celleb_setup_pci_base_addrs(hose, devno, fn, num_base_addr);
li = of_get_property(node, "interrupts", &rlen);
if (!li) {
printk(KERN_ERR "PCI: interrupts not found.\n");
goto error;
}
val = li[0];
celleb_config_write_fake(*config, PCI_INTERRUPT_PIN, 1, 1);
celleb_config_write_fake(*config, PCI_INTERRUPT_LINE, 1, val);
#ifdef DEBUG
pr_debug("PCI: %s irq=%ld\n", name, li[0]);
for (i = 0; i < 6; i++) {
celleb_config_read_fake(*config,
PCI_BASE_ADDRESS_0 + 0x4 * i, 4,
&val);
pr_debug("PCI: %s fn=%d base_address_%d=0x%x\n",
name, fn, i, val);
}
#endif
celleb_config_write_fake(*config, PCI_HEADER_TYPE, 1,
PCI_HEADER_TYPE_NORMAL);
return 0;
error:
if (mem_init_done) {
if (config && *config)
kfree(*config);
if (res && *res)
kfree(*res);
} else {
if (config && *config) {
size = 256;
free_bootmem((unsigned long)(*config), size);
}
if (res && *res) {
size = sizeof(struct celleb_pci_resource);
free_bootmem((unsigned long)(*res), size);
}
}
return 1;
}
static int __init phb_set_bus_ranges(struct device_node *dev,
struct pci_controller *phb)
{
const int *bus_range;
unsigned int len;
bus_range = of_get_property(dev, "bus-range", &len);
if (bus_range == NULL || len < 2 * sizeof(int))
return 1;
phb->first_busno = bus_range[0];
phb->last_busno = bus_range[1];
return 0;
}
static void __init celleb_alloc_private_mem(struct pci_controller *hose)
{
hose->private_data =
zalloc_maybe_bootmem(sizeof(struct celleb_pci_private),
GFP_KERNEL);
}
static int __init celleb_setup_fake_pci(struct device_node *dev,
struct pci_controller *phb)
{
struct device_node *node;
phb->ops = &celleb_fake_pci_ops;
celleb_alloc_private_mem(phb);
for (node = of_get_next_child(dev, NULL);
node != NULL; node = of_get_next_child(dev, node))
celleb_setup_fake_pci_device(node, phb);
return 0;
}
static struct celleb_phb_spec celleb_fake_pci_spec __initdata = {
.setup = celleb_setup_fake_pci,
};
static struct of_device_id celleb_phb_match[] __initdata = {
{
.name = "pci-pseudo",
.data = &celleb_fake_pci_spec,
}, {
.name = "epci",
.data = &celleb_epci_spec,
}, {
.name = "pcie",
.data = &celleb_pciex_spec,
}, {
},
};
int __init celleb_setup_phb(struct pci_controller *phb)
{
struct device_node *dev = phb->dn;
const struct of_device_id *match;
struct celleb_phb_spec *phb_spec;
int rc;
match = of_match_node(celleb_phb_match, dev);
if (!match)
return 1;
phb_set_bus_ranges(dev, phb);
phb->buid = 1;
phb_spec = match->data;
rc = (*phb_spec->setup)(dev, phb);
if (rc)
return 1;
if (phb_spec->ops)
iowa_register_bus(phb, phb_spec->ops,
phb_spec->iowa_init,
phb_spec->iowa_data);
return 0;
}
int celleb_pci_probe_mode(struct pci_bus *bus)
{
return PCI_PROBE_DEVTREE;
}
| gpl-2.0 |
lostemp/android-kernel-v3.10 | security/apparmor/context.c | 10696 | 5518 | /*
* AppArmor security module
*
* This file contains AppArmor functions used to manipulate object security
* contexts.
*
* Copyright (C) 1998-2008 Novell/SUSE
* Copyright 2009-2010 Canonical 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, version 2 of the
* License.
*
*
* AppArmor sets confinement on every task, via the the aa_task_cxt and
* the aa_task_cxt.profile, both of which are required and are not allowed
* to be NULL. The aa_task_cxt is not reference counted and is unique
* to each cred (which is reference count). The profile pointed to by
* the task_cxt is reference counted.
*
* TODO
* If a task uses change_hat it currently does not return to the old
* cred or task context but instead creates a new one. Ideally the task
* should return to the previous cred if it has not been modified.
*
*/
#include "include/context.h"
#include "include/policy.h"
/**
* aa_alloc_task_context - allocate a new task_cxt
* @flags: gfp flags for allocation
*
* Returns: allocated buffer or NULL on failure
*/
struct aa_task_cxt *aa_alloc_task_context(gfp_t flags)
{
return kzalloc(sizeof(struct aa_task_cxt), flags);
}
/**
* aa_free_task_context - free a task_cxt
* @cxt: task_cxt to free (MAYBE NULL)
*/
void aa_free_task_context(struct aa_task_cxt *cxt)
{
if (cxt) {
aa_put_profile(cxt->profile);
aa_put_profile(cxt->previous);
aa_put_profile(cxt->onexec);
kzfree(cxt);
}
}
/**
* aa_dup_task_context - duplicate a task context, incrementing reference counts
* @new: a blank task context (NOT NULL)
* @old: the task context to copy (NOT NULL)
*/
void aa_dup_task_context(struct aa_task_cxt *new, const struct aa_task_cxt *old)
{
*new = *old;
aa_get_profile(new->profile);
aa_get_profile(new->previous);
aa_get_profile(new->onexec);
}
/**
* aa_replace_current_profile - replace the current tasks profiles
* @profile: new profile (NOT NULL)
*
* Returns: 0 or error on failure
*/
int aa_replace_current_profile(struct aa_profile *profile)
{
struct aa_task_cxt *cxt = current_cred()->security;
struct cred *new;
BUG_ON(!profile);
if (cxt->profile == profile)
return 0;
new = prepare_creds();
if (!new)
return -ENOMEM;
cxt = new->security;
if (unconfined(profile) || (cxt->profile->ns != profile->ns)) {
/* if switching to unconfined or a different profile namespace
* clear out context state
*/
aa_put_profile(cxt->previous);
aa_put_profile(cxt->onexec);
cxt->previous = NULL;
cxt->onexec = NULL;
cxt->token = 0;
}
/* be careful switching cxt->profile, when racing replacement it
* is possible that cxt->profile->replacedby is the reference keeping
* @profile valid, so make sure to get its reference before dropping
* the reference on cxt->profile */
aa_get_profile(profile);
aa_put_profile(cxt->profile);
cxt->profile = profile;
commit_creds(new);
return 0;
}
/**
* aa_set_current_onexec - set the tasks change_profile to happen onexec
* @profile: system profile to set at exec (MAYBE NULL to clear value)
*
* Returns: 0 or error on failure
*/
int aa_set_current_onexec(struct aa_profile *profile)
{
struct aa_task_cxt *cxt;
struct cred *new = prepare_creds();
if (!new)
return -ENOMEM;
cxt = new->security;
aa_get_profile(profile);
aa_put_profile(cxt->onexec);
cxt->onexec = profile;
commit_creds(new);
return 0;
}
/**
* aa_set_current_hat - set the current tasks hat
* @profile: profile to set as the current hat (NOT NULL)
* @token: token value that must be specified to change from the hat
*
* Do switch of tasks hat. If the task is currently in a hat
* validate the token to match.
*
* Returns: 0 or error on failure
*/
int aa_set_current_hat(struct aa_profile *profile, u64 token)
{
struct aa_task_cxt *cxt;
struct cred *new = prepare_creds();
if (!new)
return -ENOMEM;
BUG_ON(!profile);
cxt = new->security;
if (!cxt->previous) {
/* transfer refcount */
cxt->previous = cxt->profile;
cxt->token = token;
} else if (cxt->token == token) {
aa_put_profile(cxt->profile);
} else {
/* previous_profile && cxt->token != token */
abort_creds(new);
return -EACCES;
}
cxt->profile = aa_get_profile(aa_newest_version(profile));
/* clear exec on switching context */
aa_put_profile(cxt->onexec);
cxt->onexec = NULL;
commit_creds(new);
return 0;
}
/**
* aa_restore_previous_profile - exit from hat context restoring the profile
* @token: the token that must be matched to exit hat context
*
* Attempt to return out of a hat to the previous profile. The token
* must match the stored token value.
*
* Returns: 0 or error of failure
*/
int aa_restore_previous_profile(u64 token)
{
struct aa_task_cxt *cxt;
struct cred *new = prepare_creds();
if (!new)
return -ENOMEM;
cxt = new->security;
if (cxt->token != token) {
abort_creds(new);
return -EACCES;
}
/* ignore restores when there is no saved profile */
if (!cxt->previous) {
abort_creds(new);
return 0;
}
aa_put_profile(cxt->profile);
cxt->profile = aa_newest_version(cxt->previous);
BUG_ON(!cxt->profile);
if (unlikely(cxt->profile != cxt->previous)) {
aa_get_profile(cxt->profile);
aa_put_profile(cxt->previous);
}
/* clear exec && prev information when restoring to previous context */
cxt->previous = NULL;
cxt->token = 0;
aa_put_profile(cxt->onexec);
cxt->onexec = NULL;
commit_creds(new);
return 0;
}
| gpl-2.0 |
CallMeAldy/AK-Mako-Old | fs/ncpfs/getopt.c | 12744 | 1903 | /*
* getopt.c
*/
#include <linux/kernel.h>
#include <linux/string.h>
#include <asm/errno.h>
#include "getopt.h"
/**
* ncp_getopt - option parser
* @caller: name of the caller, for error messages
* @options: the options string
* @opts: an array of &struct option entries controlling parser operations
* @optopt: output; will contain the current option
* @optarg: output; will contain the value (if one exists)
* @value: output; may be NULL; will be overwritten with the integer value
* of the current argument.
*
* Helper to parse options on the format used by mount ("a=b,c=d,e,f").
* Returns opts->val if a matching entry in the 'opts' array is found,
* 0 when no more tokens are found, -1 if an error is encountered.
*/
int ncp_getopt(const char *caller, char **options, const struct ncp_option *opts,
char **optopt, char **optarg, unsigned long *value)
{
char *token;
char *val;
do {
if ((token = strsep(options, ",")) == NULL)
return 0;
} while (*token == '\0');
if (optopt)
*optopt = token;
if ((val = strchr (token, '=')) != NULL) {
*val++ = 0;
}
*optarg = val;
for (; opts->name; opts++) {
if (!strcmp(opts->name, token)) {
if (!val) {
if (opts->has_arg & OPT_NOPARAM) {
return opts->val;
}
printk(KERN_INFO "%s: the %s option requires an argument\n",
caller, token);
return -EINVAL;
}
if (opts->has_arg & OPT_INT) {
char* v;
*value = simple_strtoul(val, &v, 0);
if (!*v) {
return opts->val;
}
printk(KERN_INFO "%s: invalid numeric value in %s=%s\n",
caller, token, val);
return -EDOM;
}
if (opts->has_arg & OPT_STRING) {
return opts->val;
}
printk(KERN_INFO "%s: unexpected argument %s to the %s option\n",
caller, val, token);
return -EINVAL;
}
}
printk(KERN_INFO "%s: Unrecognized mount option %s\n", caller, token);
return -EOPNOTSUPP;
}
| gpl-2.0 |
3EleVen/android_kernel_google_msm | fs/ncpfs/getopt.c | 12744 | 1903 | /*
* getopt.c
*/
#include <linux/kernel.h>
#include <linux/string.h>
#include <asm/errno.h>
#include "getopt.h"
/**
* ncp_getopt - option parser
* @caller: name of the caller, for error messages
* @options: the options string
* @opts: an array of &struct option entries controlling parser operations
* @optopt: output; will contain the current option
* @optarg: output; will contain the value (if one exists)
* @value: output; may be NULL; will be overwritten with the integer value
* of the current argument.
*
* Helper to parse options on the format used by mount ("a=b,c=d,e,f").
* Returns opts->val if a matching entry in the 'opts' array is found,
* 0 when no more tokens are found, -1 if an error is encountered.
*/
int ncp_getopt(const char *caller, char **options, const struct ncp_option *opts,
char **optopt, char **optarg, unsigned long *value)
{
char *token;
char *val;
do {
if ((token = strsep(options, ",")) == NULL)
return 0;
} while (*token == '\0');
if (optopt)
*optopt = token;
if ((val = strchr (token, '=')) != NULL) {
*val++ = 0;
}
*optarg = val;
for (; opts->name; opts++) {
if (!strcmp(opts->name, token)) {
if (!val) {
if (opts->has_arg & OPT_NOPARAM) {
return opts->val;
}
printk(KERN_INFO "%s: the %s option requires an argument\n",
caller, token);
return -EINVAL;
}
if (opts->has_arg & OPT_INT) {
char* v;
*value = simple_strtoul(val, &v, 0);
if (!*v) {
return opts->val;
}
printk(KERN_INFO "%s: invalid numeric value in %s=%s\n",
caller, token, val);
return -EDOM;
}
if (opts->has_arg & OPT_STRING) {
return opts->val;
}
printk(KERN_INFO "%s: unexpected argument %s to the %s option\n",
caller, val, token);
return -EINVAL;
}
}
printk(KERN_INFO "%s: Unrecognized mount option %s\n", caller, token);
return -EOPNOTSUPP;
}
| gpl-2.0 |
f1vefour/mako | fs/ncpfs/getopt.c | 12744 | 1903 | /*
* getopt.c
*/
#include <linux/kernel.h>
#include <linux/string.h>
#include <asm/errno.h>
#include "getopt.h"
/**
* ncp_getopt - option parser
* @caller: name of the caller, for error messages
* @options: the options string
* @opts: an array of &struct option entries controlling parser operations
* @optopt: output; will contain the current option
* @optarg: output; will contain the value (if one exists)
* @value: output; may be NULL; will be overwritten with the integer value
* of the current argument.
*
* Helper to parse options on the format used by mount ("a=b,c=d,e,f").
* Returns opts->val if a matching entry in the 'opts' array is found,
* 0 when no more tokens are found, -1 if an error is encountered.
*/
int ncp_getopt(const char *caller, char **options, const struct ncp_option *opts,
char **optopt, char **optarg, unsigned long *value)
{
char *token;
char *val;
do {
if ((token = strsep(options, ",")) == NULL)
return 0;
} while (*token == '\0');
if (optopt)
*optopt = token;
if ((val = strchr (token, '=')) != NULL) {
*val++ = 0;
}
*optarg = val;
for (; opts->name; opts++) {
if (!strcmp(opts->name, token)) {
if (!val) {
if (opts->has_arg & OPT_NOPARAM) {
return opts->val;
}
printk(KERN_INFO "%s: the %s option requires an argument\n",
caller, token);
return -EINVAL;
}
if (opts->has_arg & OPT_INT) {
char* v;
*value = simple_strtoul(val, &v, 0);
if (!*v) {
return opts->val;
}
printk(KERN_INFO "%s: invalid numeric value in %s=%s\n",
caller, token, val);
return -EDOM;
}
if (opts->has_arg & OPT_STRING) {
return opts->val;
}
printk(KERN_INFO "%s: unexpected argument %s to the %s option\n",
caller, val, token);
return -EINVAL;
}
}
printk(KERN_INFO "%s: Unrecognized mount option %s\n", caller, token);
return -EOPNOTSUPP;
}
| gpl-2.0 |
krzycz/prd | drivers/acpi/tables.c | 457 | 10457 | /*
* acpi_tables.c - ACPI Boot-Time Table Parsing
*
* Copyright (C) 2001 Paul Diefenbaugh <paul.s.diefenbaugh@intel.com>
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
*/
#define pr_fmt(fmt) "ACPI: " fmt
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/smp.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/irq.h>
#include <linux/errno.h>
#include <linux/acpi.h>
#include <linux/bootmem.h>
#define ACPI_MAX_TABLES 128
static char *mps_inti_flags_polarity[] = { "dfl", "high", "res", "low" };
static char *mps_inti_flags_trigger[] = { "dfl", "edge", "res", "level" };
static struct acpi_table_desc initial_tables[ACPI_MAX_TABLES] __initdata;
static int acpi_apic_instance __initdata;
/*
* Disable table checksum verification for the early stage due to the size
* limitation of the current x86 early mapping implementation.
*/
static bool acpi_verify_table_checksum __initdata = false;
void acpi_table_print_madt_entry(struct acpi_subtable_header *header)
{
if (!header)
return;
switch (header->type) {
case ACPI_MADT_TYPE_LOCAL_APIC:
{
struct acpi_madt_local_apic *p =
(struct acpi_madt_local_apic *)header;
pr_info("LAPIC (acpi_id[0x%02x] lapic_id[0x%02x] %s)\n",
p->processor_id, p->id,
(p->lapic_flags & ACPI_MADT_ENABLED) ? "enabled" : "disabled");
}
break;
case ACPI_MADT_TYPE_LOCAL_X2APIC:
{
struct acpi_madt_local_x2apic *p =
(struct acpi_madt_local_x2apic *)header;
pr_info("X2APIC (apic_id[0x%02x] uid[0x%02x] %s)\n",
p->local_apic_id, p->uid,
(p->lapic_flags & ACPI_MADT_ENABLED) ? "enabled" : "disabled");
}
break;
case ACPI_MADT_TYPE_IO_APIC:
{
struct acpi_madt_io_apic *p =
(struct acpi_madt_io_apic *)header;
pr_info("IOAPIC (id[0x%02x] address[0x%08x] gsi_base[%d])\n",
p->id, p->address, p->global_irq_base);
}
break;
case ACPI_MADT_TYPE_INTERRUPT_OVERRIDE:
{
struct acpi_madt_interrupt_override *p =
(struct acpi_madt_interrupt_override *)header;
pr_info("INT_SRC_OVR (bus %d bus_irq %d global_irq %d %s %s)\n",
p->bus, p->source_irq, p->global_irq,
mps_inti_flags_polarity[p->inti_flags & ACPI_MADT_POLARITY_MASK],
mps_inti_flags_trigger[(p->inti_flags & ACPI_MADT_TRIGGER_MASK) >> 2]);
if (p->inti_flags &
~(ACPI_MADT_POLARITY_MASK | ACPI_MADT_TRIGGER_MASK))
pr_info("INT_SRC_OVR unexpected reserved flags: 0x%x\n",
p->inti_flags &
~(ACPI_MADT_POLARITY_MASK | ACPI_MADT_TRIGGER_MASK));
}
break;
case ACPI_MADT_TYPE_NMI_SOURCE:
{
struct acpi_madt_nmi_source *p =
(struct acpi_madt_nmi_source *)header;
pr_info("NMI_SRC (%s %s global_irq %d)\n",
mps_inti_flags_polarity[p->inti_flags & ACPI_MADT_POLARITY_MASK],
mps_inti_flags_trigger[(p->inti_flags & ACPI_MADT_TRIGGER_MASK) >> 2],
p->global_irq);
}
break;
case ACPI_MADT_TYPE_LOCAL_APIC_NMI:
{
struct acpi_madt_local_apic_nmi *p =
(struct acpi_madt_local_apic_nmi *)header;
pr_info("LAPIC_NMI (acpi_id[0x%02x] %s %s lint[0x%x])\n",
p->processor_id,
mps_inti_flags_polarity[p->inti_flags & ACPI_MADT_POLARITY_MASK ],
mps_inti_flags_trigger[(p->inti_flags & ACPI_MADT_TRIGGER_MASK) >> 2],
p->lint);
}
break;
case ACPI_MADT_TYPE_LOCAL_X2APIC_NMI:
{
u16 polarity, trigger;
struct acpi_madt_local_x2apic_nmi *p =
(struct acpi_madt_local_x2apic_nmi *)header;
polarity = p->inti_flags & ACPI_MADT_POLARITY_MASK;
trigger = (p->inti_flags & ACPI_MADT_TRIGGER_MASK) >> 2;
pr_info("X2APIC_NMI (uid[0x%02x] %s %s lint[0x%x])\n",
p->uid,
mps_inti_flags_polarity[polarity],
mps_inti_flags_trigger[trigger],
p->lint);
}
break;
case ACPI_MADT_TYPE_LOCAL_APIC_OVERRIDE:
{
struct acpi_madt_local_apic_override *p =
(struct acpi_madt_local_apic_override *)header;
pr_info("LAPIC_ADDR_OVR (address[%p])\n",
(void *)(unsigned long)p->address);
}
break;
case ACPI_MADT_TYPE_IO_SAPIC:
{
struct acpi_madt_io_sapic *p =
(struct acpi_madt_io_sapic *)header;
pr_info("IOSAPIC (id[0x%x] address[%p] gsi_base[%d])\n",
p->id, (void *)(unsigned long)p->address,
p->global_irq_base);
}
break;
case ACPI_MADT_TYPE_LOCAL_SAPIC:
{
struct acpi_madt_local_sapic *p =
(struct acpi_madt_local_sapic *)header;
pr_info("LSAPIC (acpi_id[0x%02x] lsapic_id[0x%02x] lsapic_eid[0x%02x] %s)\n",
p->processor_id, p->id, p->eid,
(p->lapic_flags & ACPI_MADT_ENABLED) ? "enabled" : "disabled");
}
break;
case ACPI_MADT_TYPE_INTERRUPT_SOURCE:
{
struct acpi_madt_interrupt_source *p =
(struct acpi_madt_interrupt_source *)header;
pr_info("PLAT_INT_SRC (%s %s type[0x%x] id[0x%04x] eid[0x%x] iosapic_vector[0x%x] global_irq[0x%x]\n",
mps_inti_flags_polarity[p->inti_flags & ACPI_MADT_POLARITY_MASK],
mps_inti_flags_trigger[(p->inti_flags & ACPI_MADT_TRIGGER_MASK) >> 2],
p->type, p->id, p->eid, p->io_sapic_vector,
p->global_irq);
}
break;
default:
pr_warn("Found unsupported MADT entry (type = 0x%x)\n",
header->type);
break;
}
}
int __init
acpi_table_parse_entries(char *id,
unsigned long table_size,
int entry_id,
acpi_tbl_entry_handler handler,
unsigned int max_entries)
{
struct acpi_table_header *table_header = NULL;
struct acpi_subtable_header *entry;
unsigned int count = 0;
unsigned long table_end;
acpi_size tbl_size;
if (acpi_disabled)
return -ENODEV;
if (!handler)
return -EINVAL;
if (strncmp(id, ACPI_SIG_MADT, 4) == 0)
acpi_get_table_with_size(id, acpi_apic_instance, &table_header, &tbl_size);
else
acpi_get_table_with_size(id, 0, &table_header, &tbl_size);
if (!table_header) {
pr_warn("%4.4s not present\n", id);
return -ENODEV;
}
table_end = (unsigned long)table_header + table_header->length;
/* Parse all entries looking for a match. */
entry = (struct acpi_subtable_header *)
((unsigned long)table_header + table_size);
while (((unsigned long)entry) + sizeof(struct acpi_subtable_header) <
table_end) {
if (entry->type == entry_id
&& (!max_entries || count++ < max_entries))
if (handler(entry, table_end))
goto err;
/*
* If entry->length is 0, break from this loop to avoid
* infinite loop.
*/
if (entry->length == 0) {
pr_err("[%4.4s:0x%02x] Invalid zero length\n", id, entry_id);
goto err;
}
entry = (struct acpi_subtable_header *)
((unsigned long)entry + entry->length);
}
if (max_entries && count > max_entries) {
pr_warn("[%4.4s:0x%02x] ignored %i entries of %i found\n",
id, entry_id, count - max_entries, count);
}
early_acpi_os_unmap_memory((char *)table_header, tbl_size);
return count;
err:
early_acpi_os_unmap_memory((char *)table_header, tbl_size);
return -EINVAL;
}
int __init
acpi_table_parse_madt(enum acpi_madt_type id,
acpi_tbl_entry_handler handler, unsigned int max_entries)
{
return acpi_table_parse_entries(ACPI_SIG_MADT,
sizeof(struct acpi_table_madt), id,
handler, max_entries);
}
/**
* acpi_table_parse - find table with @id, run @handler on it
* @id: table id to find
* @handler: handler to run
*
* Scan the ACPI System Descriptor Table (STD) for a table matching @id,
* run @handler on it.
*
* Return 0 if table found, -errno if not.
*/
int __init acpi_table_parse(char *id, acpi_tbl_table_handler handler)
{
struct acpi_table_header *table = NULL;
acpi_size tbl_size;
if (acpi_disabled)
return -ENODEV;
if (!id || !handler)
return -EINVAL;
if (strncmp(id, ACPI_SIG_MADT, 4) == 0)
acpi_get_table_with_size(id, acpi_apic_instance, &table, &tbl_size);
else
acpi_get_table_with_size(id, 0, &table, &tbl_size);
if (table) {
handler(table);
early_acpi_os_unmap_memory(table, tbl_size);
return 0;
} else
return -ENODEV;
}
/*
* The BIOS is supposed to supply a single APIC/MADT,
* but some report two. Provide a knob to use either.
* (don't you wish instance 0 and 1 were not the same?)
*/
static void __init check_multiple_madt(void)
{
struct acpi_table_header *table = NULL;
acpi_size tbl_size;
acpi_get_table_with_size(ACPI_SIG_MADT, 2, &table, &tbl_size);
if (table) {
pr_warn("BIOS bug: multiple APIC/MADT found, using %d\n",
acpi_apic_instance);
pr_warn("If \"acpi_apic_instance=%d\" works better, "
"notify linux-acpi@vger.kernel.org\n",
acpi_apic_instance ? 0 : 2);
early_acpi_os_unmap_memory(table, tbl_size);
} else
acpi_apic_instance = 0;
return;
}
/*
* acpi_table_init()
*
* find RSDP, find and checksum SDT/XSDT.
* checksum all tables, print SDT/XSDT
*
* result: sdt_entry[] is initialized
*/
int __init acpi_table_init(void)
{
acpi_status status;
if (acpi_verify_table_checksum) {
pr_info("Early table checksum verification enabled\n");
acpi_gbl_verify_table_checksum = TRUE;
} else {
pr_info("Early table checksum verification disabled\n");
acpi_gbl_verify_table_checksum = FALSE;
}
status = acpi_initialize_tables(initial_tables, ACPI_MAX_TABLES, 0);
if (ACPI_FAILURE(status))
return -EINVAL;
check_multiple_madt();
return 0;
}
static int __init acpi_parse_apic_instance(char *str)
{
if (!str)
return -EINVAL;
if (kstrtoint(str, 0, &acpi_apic_instance))
return -EINVAL;
pr_notice("Shall use APIC/MADT table %d\n", acpi_apic_instance);
return 0;
}
early_param("acpi_apic_instance", acpi_parse_apic_instance);
static int __init acpi_force_table_verification_setup(char *s)
{
acpi_verify_table_checksum = true;
return 0;
}
early_param("acpi_force_table_verification", acpi_force_table_verification_setup);
| gpl-2.0 |
Fenix46/android_kernel_asus_grouper | fs/partitions/efi.c | 457 | 21481 | /************************************************************
* EFI GUID Partition Table handling
*
* http://www.uefi.org/specs/
* http://www.intel.com/technology/efi/
*
* efi.[ch] by Matt Domsch <Matt_Domsch@dell.com>
* Copyright 2000,2001,2002,2004 Dell Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* TODO:
*
* Changelog:
* Mon Nov 09 2004 Matt Domsch <Matt_Domsch@dell.com>
* - test for valid PMBR and valid PGPT before ever reading
* AGPT, allow override with 'gpt' kernel command line option.
* - check for first/last_usable_lba outside of size of disk
*
* Tue Mar 26 2002 Matt Domsch <Matt_Domsch@dell.com>
* - Ported to 2.5.7-pre1 and 2.5.7-dj2
* - Applied patch to avoid fault in alternate header handling
* - cleaned up find_valid_gpt
* - On-disk structure and copy in memory is *always* LE now -
* swab fields as needed
* - remove print_gpt_header()
* - only use first max_p partition entries, to keep the kernel minor number
* and partition numbers tied.
*
* Mon Feb 04 2002 Matt Domsch <Matt_Domsch@dell.com>
* - Removed __PRIPTR_PREFIX - not being used
*
* Mon Jan 14 2002 Matt Domsch <Matt_Domsch@dell.com>
* - Ported to 2.5.2-pre11 + library crc32 patch Linus applied
*
* Thu Dec 6 2001 Matt Domsch <Matt_Domsch@dell.com>
* - Added compare_gpts().
* - moved le_efi_guid_to_cpus() back into this file. GPT is the only
* thing that keeps EFI GUIDs on disk.
* - Changed gpt structure names and members to be simpler and more Linux-like.
*
* Wed Oct 17 2001 Matt Domsch <Matt_Domsch@dell.com>
* - Removed CONFIG_DEVFS_VOLUMES_UUID code entirely per Martin Wilck
*
* Wed Oct 10 2001 Matt Domsch <Matt_Domsch@dell.com>
* - Changed function comments to DocBook style per Andreas Dilger suggestion.
*
* Mon Oct 08 2001 Matt Domsch <Matt_Domsch@dell.com>
* - Change read_lba() to use the page cache per Al Viro's work.
* - print u64s properly on all architectures
* - fixed debug_printk(), now Dprintk()
*
* Mon Oct 01 2001 Matt Domsch <Matt_Domsch@dell.com>
* - Style cleanups
* - made most functions static
* - Endianness addition
* - remove test for second alternate header, as it's not per spec,
* and is unnecessary. There's now a method to read/write the last
* sector of an odd-sized disk from user space. No tools have ever
* been released which used this code, so it's effectively dead.
* - Per Asit Mallick of Intel, added a test for a valid PMBR.
* - Added kernel command line option 'gpt' to override valid PMBR test.
*
* Wed Jun 6 2001 Martin Wilck <Martin.Wilck@Fujitsu-Siemens.com>
* - added devfs volume UUID support (/dev/volumes/uuids) for
* mounting file systems by the partition GUID.
*
* Tue Dec 5 2000 Matt Domsch <Matt_Domsch@dell.com>
* - Moved crc32() to linux/lib, added efi_crc32().
*
* Thu Nov 30 2000 Matt Domsch <Matt_Domsch@dell.com>
* - Replaced Intel's CRC32 function with an equivalent
* non-license-restricted version.
*
* Wed Oct 25 2000 Matt Domsch <Matt_Domsch@dell.com>
* - Fixed the last_lba() call to return the proper last block
*
* Thu Oct 12 2000 Matt Domsch <Matt_Domsch@dell.com>
* - Thanks to Andries Brouwer for his debugging assistance.
* - Code works, detects all the partitions.
*
************************************************************/
#include <linux/crc32.h>
#include <linux/ctype.h>
#include <linux/math64.h>
#include <linux/slab.h>
#include "check.h"
#include "efi.h"
/* This allows a kernel command line option 'gpt' to override
* the test for invalid PMBR. Not __initdata because reloading
* the partition tables happens after init too.
*/
static int force_gpt;
static u64 force_gpt_sector;
static int __init
force_gpt_fn(char *str)
{
force_gpt = 1;
return 1;
}
__setup("gpt", force_gpt_fn);
static int __init force_gpt_sector_fn(char *str)
{
force_gpt_sector = simple_strtoull(str, NULL, 0);
return 1;
}
__setup("gpt_sector=", force_gpt_sector_fn);
/**
* efi_crc32() - EFI version of crc32 function
* @buf: buffer to calculate crc32 of
* @len - length of buf
*
* Description: Returns EFI-style CRC32 value for @buf
*
* This function uses the little endian Ethernet polynomial
* but seeds the function with ~0, and xor's with ~0 at the end.
* Note, the EFI Specification, v1.02, has a reference to
* Dr. Dobbs Journal, May 1994 (actually it's in May 1992).
*/
static inline u32
efi_crc32(const void *buf, unsigned long len)
{
return (crc32(~0L, buf, len) ^ ~0L);
}
/**
* last_lba(): return number of last logical block of device
* @bdev: block device
*
* Description: Returns last LBA value on success, 0 on error.
* This is stored (by sd and ide-geometry) in
* the part[0] entry for this disk, and is the number of
* physical sectors available on the disk.
*/
static u64 last_lba(struct block_device *bdev)
{
if (!bdev || !bdev->bd_inode)
return 0;
return div_u64(bdev->bd_inode->i_size,
bdev_logical_block_size(bdev)) - 1ULL;
}
static inline int
pmbr_part_valid(struct partition *part)
{
if (part->sys_ind == EFI_PMBR_OSTYPE_EFI_GPT &&
le32_to_cpu(part->start_sect) == 1UL)
return 1;
return 0;
}
/**
* is_pmbr_valid(): test Protective MBR for validity
* @mbr: pointer to a legacy mbr structure
*
* Description: Returns 1 if PMBR is valid, 0 otherwise.
* Validity depends on two things:
* 1) MSDOS signature is in the last two bytes of the MBR
* 2) One partition of type 0xEE is found
*/
static int
is_pmbr_valid(legacy_mbr *mbr)
{
int i;
if (!mbr || le16_to_cpu(mbr->signature) != MSDOS_MBR_SIGNATURE)
return 0;
for (i = 0; i < 4; i++)
if (pmbr_part_valid(&mbr->partition_record[i]))
return 1;
return 0;
}
/**
* read_lba(): Read bytes from disk, starting at given LBA
* @state
* @lba
* @buffer
* @size_t
*
* Description: Reads @count bytes from @state->bdev into @buffer.
* Returns number of bytes read on success, 0 on error.
*/
static size_t read_lba(struct parsed_partitions *state,
u64 lba, u8 *buffer, size_t count)
{
size_t totalreadcount = 0;
struct block_device *bdev = state->bdev;
sector_t n = lba * (bdev_logical_block_size(bdev) / 512);
if (!buffer || lba > last_lba(bdev))
return 0;
while (count) {
int copied = 512;
Sector sect;
unsigned char *data = read_part_sector(state, n++, §);
if (!data)
break;
if (copied > count)
copied = count;
memcpy(buffer, data, copied);
put_dev_sector(sect);
buffer += copied;
totalreadcount +=copied;
count -= copied;
}
return totalreadcount;
}
/**
* alloc_read_gpt_entries(): reads partition entries from disk
* @state
* @gpt - GPT header
*
* Description: Returns ptes on success, NULL on error.
* Allocates space for PTEs based on information found in @gpt.
* Notes: remember to free pte when you're done!
*/
static gpt_entry *alloc_read_gpt_entries(struct parsed_partitions *state,
gpt_header *gpt)
{
size_t count;
gpt_entry *pte;
if (!gpt)
return NULL;
count = le32_to_cpu(gpt->num_partition_entries) *
le32_to_cpu(gpt->sizeof_partition_entry);
if (!count)
return NULL;
pte = kzalloc(count, GFP_KERNEL);
if (!pte)
return NULL;
if (read_lba(state, le64_to_cpu(gpt->partition_entry_lba),
(u8 *) pte,
count) < count) {
kfree(pte);
pte=NULL;
return NULL;
}
return pte;
}
/**
* alloc_read_gpt_header(): Allocates GPT header, reads into it from disk
* @state
* @lba is the Logical Block Address of the partition table
*
* Description: returns GPT header on success, NULL on error. Allocates
* and fills a GPT header starting at @ from @state->bdev.
* Note: remember to free gpt when finished with it.
*/
static gpt_header *alloc_read_gpt_header(struct parsed_partitions *state,
u64 lba)
{
gpt_header *gpt;
unsigned ssz = bdev_logical_block_size(state->bdev);
gpt = kzalloc(ssz, GFP_KERNEL);
if (!gpt)
return NULL;
if (read_lba(state, lba, (u8 *) gpt, ssz) < ssz) {
kfree(gpt);
gpt=NULL;
return NULL;
}
return gpt;
}
/**
* is_gpt_valid() - tests one GPT header and PTEs for validity
* @state
* @lba is the logical block address of the GPT header to test
* @gpt is a GPT header ptr, filled on return.
* @ptes is a PTEs ptr, filled on return.
*
* Description: returns 1 if valid, 0 on error.
* If valid, returns pointers to newly allocated GPT header and PTEs.
*/
static int is_gpt_valid(struct parsed_partitions *state, u64 lba,
gpt_header **gpt, gpt_entry **ptes)
{
u32 crc, origcrc;
u64 lastlba;
if (!ptes)
return 0;
if (!(*gpt = alloc_read_gpt_header(state, lba)))
return 0;
/* Check the GUID Partition Table signature */
if (le64_to_cpu((*gpt)->signature) != GPT_HEADER_SIGNATURE) {
pr_debug("GUID Partition Table Header signature is wrong:"
"%lld != %lld\n",
(unsigned long long)le64_to_cpu((*gpt)->signature),
(unsigned long long)GPT_HEADER_SIGNATURE);
goto fail;
}
/* Check the GUID Partition Table header size */
if (le32_to_cpu((*gpt)->header_size) >
bdev_logical_block_size(state->bdev)) {
pr_debug("GUID Partition Table Header size is wrong: %u > %u\n",
le32_to_cpu((*gpt)->header_size),
bdev_logical_block_size(state->bdev));
goto fail;
}
/* Check the GUID Partition Table CRC */
origcrc = le32_to_cpu((*gpt)->header_crc32);
(*gpt)->header_crc32 = 0;
crc = efi_crc32((const unsigned char *) (*gpt), le32_to_cpu((*gpt)->header_size));
if (crc != origcrc) {
pr_debug("GUID Partition Table Header CRC is wrong: %x != %x\n",
crc, origcrc);
goto fail;
}
(*gpt)->header_crc32 = cpu_to_le32(origcrc);
/* Check that the my_lba entry points to the LBA that contains
* the GUID Partition Table */
if (le64_to_cpu((*gpt)->my_lba) != lba) {
pr_debug("GPT my_lba incorrect: %lld != %lld\n",
(unsigned long long)le64_to_cpu((*gpt)->my_lba),
(unsigned long long)lba);
goto fail;
}
/* Check the first_usable_lba and last_usable_lba are
* within the disk.
*/
lastlba = last_lba(state->bdev);
if (le64_to_cpu((*gpt)->first_usable_lba) > lastlba) {
pr_debug("GPT: first_usable_lba incorrect: %lld > %lld\n",
(unsigned long long)le64_to_cpu((*gpt)->first_usable_lba),
(unsigned long long)lastlba);
goto fail;
}
if (le64_to_cpu((*gpt)->last_usable_lba) > lastlba) {
pr_debug("GPT: last_usable_lba incorrect: %lld > %lld\n",
(unsigned long long)le64_to_cpu((*gpt)->last_usable_lba),
(unsigned long long)lastlba);
goto fail;
}
/* Check that sizeof_partition_entry has the correct value */
if (le32_to_cpu((*gpt)->sizeof_partition_entry) != sizeof(gpt_entry)) {
pr_debug("GUID Partitition Entry Size check failed.\n");
goto fail;
}
if (!(*ptes = alloc_read_gpt_entries(state, *gpt)))
goto fail;
/* Check the GUID Partition Entry Array CRC */
crc = efi_crc32((const unsigned char *) (*ptes),
le32_to_cpu((*gpt)->num_partition_entries) *
le32_to_cpu((*gpt)->sizeof_partition_entry));
if (crc != le32_to_cpu((*gpt)->partition_entry_array_crc32)) {
pr_debug("GUID Partitition Entry Array CRC check failed.\n");
goto fail_ptes;
}
/* We're done, all's well */
return 1;
fail_ptes:
kfree(*ptes);
*ptes = NULL;
fail:
kfree(*gpt);
*gpt = NULL;
return 0;
}
/**
* is_pte_valid() - tests one PTE for validity
* @pte is the pte to check
* @lastlba is last lba of the disk
*
* Description: returns 1 if valid, 0 on error.
*/
static inline int
is_pte_valid(const gpt_entry *pte, const u64 lastlba)
{
if ((!efi_guidcmp(pte->partition_type_guid, NULL_GUID)) ||
le64_to_cpu(pte->starting_lba) > lastlba ||
le64_to_cpu(pte->ending_lba) > lastlba)
return 0;
return 1;
}
/**
* compare_gpts() - Search disk for valid GPT headers and PTEs
* @pgpt is the primary GPT header
* @agpt is the alternate GPT header
* @lastlba is the last LBA number
* Description: Returns nothing. Sanity checks pgpt and agpt fields
* and prints warnings on discrepancies.
*
*/
static void
compare_gpts(gpt_header *pgpt, gpt_header *agpt, u64 lastlba)
{
int error_found = 0;
if (!pgpt || !agpt)
return;
if (le64_to_cpu(pgpt->my_lba) != le64_to_cpu(agpt->alternate_lba)) {
printk(KERN_WARNING
"GPT:Primary header LBA != Alt. header alternate_lba\n");
printk(KERN_WARNING "GPT:%lld != %lld\n",
(unsigned long long)le64_to_cpu(pgpt->my_lba),
(unsigned long long)le64_to_cpu(agpt->alternate_lba));
error_found++;
}
if (le64_to_cpu(pgpt->alternate_lba) != le64_to_cpu(agpt->my_lba)) {
printk(KERN_WARNING
"GPT:Primary header alternate_lba != Alt. header my_lba\n");
printk(KERN_WARNING "GPT:%lld != %lld\n",
(unsigned long long)le64_to_cpu(pgpt->alternate_lba),
(unsigned long long)le64_to_cpu(agpt->my_lba));
error_found++;
}
if (le64_to_cpu(pgpt->first_usable_lba) !=
le64_to_cpu(agpt->first_usable_lba)) {
printk(KERN_WARNING "GPT:first_usable_lbas don't match.\n");
printk(KERN_WARNING "GPT:%lld != %lld\n",
(unsigned long long)le64_to_cpu(pgpt->first_usable_lba),
(unsigned long long)le64_to_cpu(agpt->first_usable_lba));
error_found++;
}
if (le64_to_cpu(pgpt->last_usable_lba) !=
le64_to_cpu(agpt->last_usable_lba)) {
printk(KERN_WARNING "GPT:last_usable_lbas don't match.\n");
printk(KERN_WARNING "GPT:%lld != %lld\n",
(unsigned long long)le64_to_cpu(pgpt->last_usable_lba),
(unsigned long long)le64_to_cpu(agpt->last_usable_lba));
error_found++;
}
if (efi_guidcmp(pgpt->disk_guid, agpt->disk_guid)) {
printk(KERN_WARNING "GPT:disk_guids don't match.\n");
error_found++;
}
if (le32_to_cpu(pgpt->num_partition_entries) !=
le32_to_cpu(agpt->num_partition_entries)) {
printk(KERN_WARNING "GPT:num_partition_entries don't match: "
"0x%x != 0x%x\n",
le32_to_cpu(pgpt->num_partition_entries),
le32_to_cpu(agpt->num_partition_entries));
error_found++;
}
if (le32_to_cpu(pgpt->sizeof_partition_entry) !=
le32_to_cpu(agpt->sizeof_partition_entry)) {
printk(KERN_WARNING
"GPT:sizeof_partition_entry values don't match: "
"0x%x != 0x%x\n",
le32_to_cpu(pgpt->sizeof_partition_entry),
le32_to_cpu(agpt->sizeof_partition_entry));
error_found++;
}
if (le32_to_cpu(pgpt->partition_entry_array_crc32) !=
le32_to_cpu(agpt->partition_entry_array_crc32)) {
printk(KERN_WARNING
"GPT:partition_entry_array_crc32 values don't match: "
"0x%x != 0x%x\n",
le32_to_cpu(pgpt->partition_entry_array_crc32),
le32_to_cpu(agpt->partition_entry_array_crc32));
error_found++;
}
if (le64_to_cpu(pgpt->alternate_lba) != lastlba) {
printk(KERN_WARNING
"GPT:Primary header thinks Alt. header is not at the end of the disk.\n");
printk(KERN_WARNING "GPT:%lld != %lld\n",
(unsigned long long)le64_to_cpu(pgpt->alternate_lba),
(unsigned long long)lastlba);
error_found++;
}
if (le64_to_cpu(agpt->my_lba) != lastlba) {
printk(KERN_WARNING
"GPT:Alternate GPT header not at the end of the disk.\n");
printk(KERN_WARNING "GPT:%lld != %lld\n",
(unsigned long long)le64_to_cpu(agpt->my_lba),
(unsigned long long)lastlba);
error_found++;
}
if (error_found)
printk(KERN_WARNING
"GPT: Use GNU Parted to correct GPT errors.\n");
return;
}
/**
* find_valid_gpt() - Search disk for valid GPT headers and PTEs
* @state
* @gpt is a GPT header ptr, filled on return.
* @ptes is a PTEs ptr, filled on return.
* Description: Returns 1 if valid, 0 on error.
* If valid, returns pointers to newly allocated GPT header and PTEs.
* Validity depends on PMBR being valid (or being overridden by the
* 'gpt' kernel command line option) and finding either the Primary
* GPT header and PTEs valid, or the Alternate GPT header and PTEs
* valid. If the Primary GPT header is not valid, the Alternate GPT header
* is not checked unless the 'gpt' kernel command line option is passed.
* This protects against devices which misreport their size, and forces
* the user to decide to use the Alternate GPT.
*/
static int find_valid_gpt(struct parsed_partitions *state, gpt_header **gpt,
gpt_entry **ptes)
{
int good_pgpt = 0, good_agpt = 0, good_pmbr = 0;
gpt_header *pgpt = NULL, *agpt = NULL;
gpt_entry *pptes = NULL, *aptes = NULL;
legacy_mbr *legacymbr;
u64 lastlba;
if (!ptes)
return 0;
lastlba = last_lba(state->bdev);
if (!force_gpt) {
/* This will be added to the EFI Spec. per Intel after v1.02. */
legacymbr = kzalloc(sizeof (*legacymbr), GFP_KERNEL);
if (legacymbr) {
read_lba(state, 0, (u8 *) legacymbr,
sizeof (*legacymbr));
good_pmbr = is_pmbr_valid(legacymbr);
kfree(legacymbr);
}
if (!good_pmbr)
goto fail;
}
good_pgpt = is_gpt_valid(state, GPT_PRIMARY_PARTITION_TABLE_LBA,
&pgpt, &pptes);
if (good_pgpt)
good_agpt = is_gpt_valid(state,
le64_to_cpu(pgpt->alternate_lba),
&agpt, &aptes);
if (!good_agpt && force_gpt)
good_agpt = is_gpt_valid(state, lastlba, &agpt, &aptes);
if (!good_agpt && force_gpt && force_gpt_sector)
good_agpt = is_gpt_valid(state, force_gpt_sector, &agpt, &aptes);
/* The obviously unsuccessful case */
if (!good_pgpt && !good_agpt)
goto fail;
compare_gpts(pgpt, agpt, lastlba);
/* The good cases */
if (good_pgpt) {
*gpt = pgpt;
*ptes = pptes;
kfree(agpt);
kfree(aptes);
if (!good_agpt) {
printk(KERN_WARNING
"Alternate GPT is invalid, "
"using primary GPT.\n");
}
return 1;
}
else if (good_agpt) {
*gpt = agpt;
*ptes = aptes;
kfree(pgpt);
kfree(pptes);
printk(KERN_WARNING
"Primary GPT is invalid, using alternate GPT.\n");
return 1;
}
fail:
kfree(pgpt);
kfree(agpt);
kfree(pptes);
kfree(aptes);
*gpt = NULL;
*ptes = NULL;
return 0;
}
/**
* efi_partition(struct parsed_partitions *state)
* @state
*
* Description: called from check.c, if the disk contains GPT
* partitions, sets up partition entries in the kernel.
*
* If the first block on the disk is a legacy MBR,
* it will get handled by msdos_partition().
* If it's a Protective MBR, we'll handle it here.
*
* We do not create a Linux partition for GPT, but
* only for the actual data partitions.
* Returns:
* -1 if unable to read the partition table
* 0 if this isn't our partition table
* 1 if successful
*
*/
int efi_partition(struct parsed_partitions *state)
{
gpt_header *gpt = NULL;
gpt_entry *ptes = NULL;
u32 i;
unsigned ssz = bdev_logical_block_size(state->bdev) / 512;
u8 unparsed_guid[37];
if (!find_valid_gpt(state, &gpt, &ptes) || !gpt || !ptes) {
kfree(gpt);
kfree(ptes);
return 0;
}
pr_debug("GUID Partition Table is valid! Yea!\n");
for (i = 0; i < le32_to_cpu(gpt->num_partition_entries) && i < state->limit-1; i++) {
struct partition_meta_info *info;
unsigned label_count = 0;
unsigned label_max;
u64 start = le64_to_cpu(ptes[i].starting_lba);
u64 size = le64_to_cpu(ptes[i].ending_lba) -
le64_to_cpu(ptes[i].starting_lba) + 1ULL;
if (!is_pte_valid(&ptes[i], last_lba(state->bdev)))
continue;
put_partition(state, i+1, start * ssz, size * ssz);
/* If this is a RAID volume, tell md */
if (!efi_guidcmp(ptes[i].partition_type_guid,
PARTITION_LINUX_RAID_GUID))
state->parts[i + 1].flags = ADDPART_FLAG_RAID;
info = &state->parts[i + 1].info;
/* Instead of doing a manual swap to big endian, reuse the
* common ASCII hex format as the interim.
*/
efi_guid_unparse(&ptes[i].unique_partition_guid, unparsed_guid);
part_pack_uuid(unparsed_guid, info->uuid);
/* Naively convert UTF16-LE to 7 bits. */
label_max = min(sizeof(info->volname) - 1,
sizeof(ptes[i].partition_name));
info->volname[label_max] = 0;
while (label_count < label_max) {
u8 c = ptes[i].partition_name[label_count] & 0xff;
if (c && !isprint(c))
c = '!';
info->volname[label_count] = c;
label_count++;
}
state->parts[i + 1].has_info = true;
}
kfree(ptes);
kfree(gpt);
strlcat(state->pp_buf, "\n", PAGE_SIZE);
return 1;
}
| gpl-2.0 |
sandy-harris/random.gcm | drivers/crypto/nx/nx.c | 457 | 24172 | /**
* Routines supporting the Power 7+ Nest Accelerators driver
*
* Copyright (C) 2011-2012 International Business Machines Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 only.
*
* 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.
*
* Author: Kent Yoder <yoder1@us.ibm.com>
*/
#include <crypto/internal/aead.h>
#include <crypto/internal/hash.h>
#include <crypto/aes.h>
#include <crypto/sha.h>
#include <crypto/algapi.h>
#include <crypto/scatterwalk.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/scatterlist.h>
#include <linux/device.h>
#include <linux/of.h>
#include <linux/types.h>
#include <asm/hvcall.h>
#include <asm/vio.h>
#include "nx_csbcpb.h"
#include "nx.h"
/**
* nx_hcall_sync - make an H_COP_OP hcall for the passed in op structure
*
* @nx_ctx: the crypto context handle
* @op: PFO operation struct to pass in
* @may_sleep: flag indicating the request can sleep
*
* Make the hcall, retrying while the hardware is busy. If we cannot yield
* the thread, limit the number of retries to 10 here.
*/
int nx_hcall_sync(struct nx_crypto_ctx *nx_ctx,
struct vio_pfo_op *op,
u32 may_sleep)
{
int rc, retries = 10;
struct vio_dev *viodev = nx_driver.viodev;
atomic_inc(&(nx_ctx->stats->sync_ops));
do {
rc = vio_h_cop_sync(viodev, op);
} while (rc == -EBUSY && !may_sleep && retries--);
if (rc) {
dev_dbg(&viodev->dev, "vio_h_cop_sync failed: rc: %d "
"hcall rc: %ld\n", rc, op->hcall_err);
atomic_inc(&(nx_ctx->stats->errors));
atomic_set(&(nx_ctx->stats->last_error), op->hcall_err);
atomic_set(&(nx_ctx->stats->last_error_pid), current->pid);
}
return rc;
}
/**
* nx_build_sg_list - build an NX scatter list describing a single buffer
*
* @sg_head: pointer to the first scatter list element to build
* @start_addr: pointer to the linear buffer
* @len: length of the data at @start_addr
* @sgmax: the largest number of scatter list elements we're allowed to create
*
* This function will start writing nx_sg elements at @sg_head and keep
* writing them until all of the data from @start_addr is described or
* until sgmax elements have been written. Scatter list elements will be
* created such that none of the elements describes a buffer that crosses a 4K
* boundary.
*/
struct nx_sg *nx_build_sg_list(struct nx_sg *sg_head,
u8 *start_addr,
unsigned int *len,
u32 sgmax)
{
unsigned int sg_len = 0;
struct nx_sg *sg;
u64 sg_addr = (u64)start_addr;
u64 end_addr;
/* determine the start and end for this address range - slightly
* different if this is in VMALLOC_REGION */
if (is_vmalloc_addr(start_addr))
sg_addr = page_to_phys(vmalloc_to_page(start_addr))
+ offset_in_page(sg_addr);
else
sg_addr = __pa(sg_addr);
end_addr = sg_addr + *len;
/* each iteration will write one struct nx_sg element and add the
* length of data described by that element to sg_len. Once @len bytes
* have been described (or @sgmax elements have been written), the
* loop ends. min_t is used to ensure @end_addr falls on the same page
* as sg_addr, if not, we need to create another nx_sg element for the
* data on the next page.
*
* Also when using vmalloc'ed data, every time that a system page
* boundary is crossed the physical address needs to be re-calculated.
*/
for (sg = sg_head; sg_len < *len; sg++) {
u64 next_page;
sg->addr = sg_addr;
sg_addr = min_t(u64, NX_PAGE_NUM(sg_addr + NX_PAGE_SIZE),
end_addr);
next_page = (sg->addr & PAGE_MASK) + PAGE_SIZE;
sg->len = min_t(u64, sg_addr, next_page) - sg->addr;
sg_len += sg->len;
if (sg_addr >= next_page &&
is_vmalloc_addr(start_addr + sg_len)) {
sg_addr = page_to_phys(vmalloc_to_page(
start_addr + sg_len));
end_addr = sg_addr + *len - sg_len;
}
if ((sg - sg_head) == sgmax) {
pr_err("nx: scatter/gather list overflow, pid: %d\n",
current->pid);
sg++;
break;
}
}
*len = sg_len;
/* return the moved sg_head pointer */
return sg;
}
/**
* nx_walk_and_build - walk a linux scatterlist and build an nx scatterlist
*
* @nx_dst: pointer to the first nx_sg element to write
* @sglen: max number of nx_sg entries we're allowed to write
* @sg_src: pointer to the source linux scatterlist to walk
* @start: number of bytes to fast-forward past at the beginning of @sg_src
* @src_len: number of bytes to walk in @sg_src
*/
struct nx_sg *nx_walk_and_build(struct nx_sg *nx_dst,
unsigned int sglen,
struct scatterlist *sg_src,
unsigned int start,
unsigned int *src_len)
{
struct scatter_walk walk;
struct nx_sg *nx_sg = nx_dst;
unsigned int n, offset = 0, len = *src_len;
char *dst;
/* we need to fast forward through @start bytes first */
for (;;) {
scatterwalk_start(&walk, sg_src);
if (start < offset + sg_src->length)
break;
offset += sg_src->length;
sg_src = sg_next(sg_src);
}
/* start - offset is the number of bytes to advance in the scatterlist
* element we're currently looking at */
scatterwalk_advance(&walk, start - offset);
while (len && (nx_sg - nx_dst) < sglen) {
n = scatterwalk_clamp(&walk, len);
if (!n) {
/* In cases where we have scatterlist chain sg_next
* handles with it properly */
scatterwalk_start(&walk, sg_next(walk.sg));
n = scatterwalk_clamp(&walk, len);
}
dst = scatterwalk_map(&walk);
nx_sg = nx_build_sg_list(nx_sg, dst, &n, sglen - (nx_sg - nx_dst));
len -= n;
scatterwalk_unmap(dst);
scatterwalk_advance(&walk, n);
scatterwalk_done(&walk, SCATTERWALK_FROM_SG, len);
}
/* update to_process */
*src_len -= len;
/* return the moved destination pointer */
return nx_sg;
}
/**
* trim_sg_list - ensures the bound in sg list.
* @sg: sg list head
* @end: sg lisg end
* @delta: is the amount we need to crop in order to bound the list.
*
*/
static long int trim_sg_list(struct nx_sg *sg,
struct nx_sg *end,
unsigned int delta,
unsigned int *nbytes)
{
long int oplen;
long int data_back;
unsigned int is_delta = delta;
while (delta && end > sg) {
struct nx_sg *last = end - 1;
if (last->len > delta) {
last->len -= delta;
delta = 0;
} else {
end--;
delta -= last->len;
}
}
/* There are cases where we need to crop list in order to make it
* a block size multiple, but we also need to align data. In order to
* that we need to calculate how much we need to put back to be
* processed
*/
oplen = (sg - end) * sizeof(struct nx_sg);
if (is_delta) {
data_back = (abs(oplen) / AES_BLOCK_SIZE) * sg->len;
data_back = *nbytes - (data_back & ~(AES_BLOCK_SIZE - 1));
*nbytes -= data_back;
}
return oplen;
}
/**
* nx_build_sg_lists - walk the input scatterlists and build arrays of NX
* scatterlists based on them.
*
* @nx_ctx: NX crypto context for the lists we're building
* @desc: the block cipher descriptor for the operation
* @dst: destination scatterlist
* @src: source scatterlist
* @nbytes: length of data described in the scatterlists
* @offset: number of bytes to fast-forward past at the beginning of
* scatterlists.
* @iv: destination for the iv data, if the algorithm requires it
*
* This is common code shared by all the AES algorithms. It uses the block
* cipher walk routines to traverse input and output scatterlists, building
* corresponding NX scatterlists
*/
int nx_build_sg_lists(struct nx_crypto_ctx *nx_ctx,
struct blkcipher_desc *desc,
struct scatterlist *dst,
struct scatterlist *src,
unsigned int *nbytes,
unsigned int offset,
u8 *iv)
{
unsigned int delta = 0;
unsigned int total = *nbytes;
struct nx_sg *nx_insg = nx_ctx->in_sg;
struct nx_sg *nx_outsg = nx_ctx->out_sg;
unsigned int max_sg_len;
max_sg_len = min_t(u64, nx_ctx->ap->sglen,
nx_driver.of.max_sg_len/sizeof(struct nx_sg));
max_sg_len = min_t(u64, max_sg_len,
nx_ctx->ap->databytelen/NX_PAGE_SIZE);
if (iv)
memcpy(iv, desc->info, AES_BLOCK_SIZE);
*nbytes = min_t(u64, *nbytes, nx_ctx->ap->databytelen);
nx_outsg = nx_walk_and_build(nx_outsg, max_sg_len, dst,
offset, nbytes);
nx_insg = nx_walk_and_build(nx_insg, max_sg_len, src,
offset, nbytes);
if (*nbytes < total)
delta = *nbytes - (*nbytes & ~(AES_BLOCK_SIZE - 1));
/* these lengths should be negative, which will indicate to phyp that
* the input and output parameters are scatterlists, not linear
* buffers */
nx_ctx->op.inlen = trim_sg_list(nx_ctx->in_sg, nx_insg, delta, nbytes);
nx_ctx->op.outlen = trim_sg_list(nx_ctx->out_sg, nx_outsg, delta, nbytes);
return 0;
}
/**
* nx_ctx_init - initialize an nx_ctx's vio_pfo_op struct
*
* @nx_ctx: the nx context to initialize
* @function: the function code for the op
*/
void nx_ctx_init(struct nx_crypto_ctx *nx_ctx, unsigned int function)
{
spin_lock_init(&nx_ctx->lock);
memset(nx_ctx->kmem, 0, nx_ctx->kmem_len);
nx_ctx->csbcpb->csb.valid |= NX_CSB_VALID_BIT;
nx_ctx->op.flags = function;
nx_ctx->op.csbcpb = __pa(nx_ctx->csbcpb);
nx_ctx->op.in = __pa(nx_ctx->in_sg);
nx_ctx->op.out = __pa(nx_ctx->out_sg);
if (nx_ctx->csbcpb_aead) {
nx_ctx->csbcpb_aead->csb.valid |= NX_CSB_VALID_BIT;
nx_ctx->op_aead.flags = function;
nx_ctx->op_aead.csbcpb = __pa(nx_ctx->csbcpb_aead);
nx_ctx->op_aead.in = __pa(nx_ctx->in_sg);
nx_ctx->op_aead.out = __pa(nx_ctx->out_sg);
}
}
static void nx_of_update_status(struct device *dev,
struct property *p,
struct nx_of *props)
{
if (!strncmp(p->value, "okay", p->length)) {
props->status = NX_WAITING;
props->flags |= NX_OF_FLAG_STATUS_SET;
} else {
dev_info(dev, "%s: status '%s' is not 'okay'\n", __func__,
(char *)p->value);
}
}
static void nx_of_update_sglen(struct device *dev,
struct property *p,
struct nx_of *props)
{
if (p->length != sizeof(props->max_sg_len)) {
dev_err(dev, "%s: unexpected format for "
"ibm,max-sg-len property\n", __func__);
dev_dbg(dev, "%s: ibm,max-sg-len is %d bytes "
"long, expected %zd bytes\n", __func__,
p->length, sizeof(props->max_sg_len));
return;
}
props->max_sg_len = *(u32 *)p->value;
props->flags |= NX_OF_FLAG_MAXSGLEN_SET;
}
static void nx_of_update_msc(struct device *dev,
struct property *p,
struct nx_of *props)
{
struct msc_triplet *trip;
struct max_sync_cop *msc;
unsigned int bytes_so_far, i, lenp;
msc = (struct max_sync_cop *)p->value;
lenp = p->length;
/* You can't tell if the data read in for this property is sane by its
* size alone. This is because there are sizes embedded in the data
* structure. The best we can do is check lengths as we parse and bail
* as soon as a length error is detected. */
bytes_so_far = 0;
while ((bytes_so_far + sizeof(struct max_sync_cop)) <= lenp) {
bytes_so_far += sizeof(struct max_sync_cop);
trip = msc->trip;
for (i = 0;
((bytes_so_far + sizeof(struct msc_triplet)) <= lenp) &&
i < msc->triplets;
i++) {
if (msc->fc > NX_MAX_FC || msc->mode > NX_MAX_MODE) {
dev_err(dev, "unknown function code/mode "
"combo: %d/%d (ignored)\n", msc->fc,
msc->mode);
goto next_loop;
}
if (!trip->sglen || trip->databytelen < NX_PAGE_SIZE) {
dev_warn(dev, "bogus sglen/databytelen: "
"%u/%u (ignored)\n", trip->sglen,
trip->databytelen);
goto next_loop;
}
switch (trip->keybitlen) {
case 128:
case 160:
props->ap[msc->fc][msc->mode][0].databytelen =
trip->databytelen;
props->ap[msc->fc][msc->mode][0].sglen =
trip->sglen;
break;
case 192:
props->ap[msc->fc][msc->mode][1].databytelen =
trip->databytelen;
props->ap[msc->fc][msc->mode][1].sglen =
trip->sglen;
break;
case 256:
if (msc->fc == NX_FC_AES) {
props->ap[msc->fc][msc->mode][2].
databytelen = trip->databytelen;
props->ap[msc->fc][msc->mode][2].sglen =
trip->sglen;
} else if (msc->fc == NX_FC_AES_HMAC ||
msc->fc == NX_FC_SHA) {
props->ap[msc->fc][msc->mode][1].
databytelen = trip->databytelen;
props->ap[msc->fc][msc->mode][1].sglen =
trip->sglen;
} else {
dev_warn(dev, "unknown function "
"code/key bit len combo"
": (%u/256)\n", msc->fc);
}
break;
case 512:
props->ap[msc->fc][msc->mode][2].databytelen =
trip->databytelen;
props->ap[msc->fc][msc->mode][2].sglen =
trip->sglen;
break;
default:
dev_warn(dev, "unknown function code/key bit "
"len combo: (%u/%u)\n", msc->fc,
trip->keybitlen);
break;
}
next_loop:
bytes_so_far += sizeof(struct msc_triplet);
trip++;
}
msc = (struct max_sync_cop *)trip;
}
props->flags |= NX_OF_FLAG_MAXSYNCCOP_SET;
}
/**
* nx_of_init - read openFirmware values from the device tree
*
* @dev: device handle
* @props: pointer to struct to hold the properties values
*
* Called once at driver probe time, this function will read out the
* openFirmware properties we use at runtime. If all the OF properties are
* acceptable, when we exit this function props->flags will indicate that
* we're ready to register our crypto algorithms.
*/
static void nx_of_init(struct device *dev, struct nx_of *props)
{
struct device_node *base_node = dev->of_node;
struct property *p;
p = of_find_property(base_node, "status", NULL);
if (!p)
dev_info(dev, "%s: property 'status' not found\n", __func__);
else
nx_of_update_status(dev, p, props);
p = of_find_property(base_node, "ibm,max-sg-len", NULL);
if (!p)
dev_info(dev, "%s: property 'ibm,max-sg-len' not found\n",
__func__);
else
nx_of_update_sglen(dev, p, props);
p = of_find_property(base_node, "ibm,max-sync-cop", NULL);
if (!p)
dev_info(dev, "%s: property 'ibm,max-sync-cop' not found\n",
__func__);
else
nx_of_update_msc(dev, p, props);
}
static bool nx_check_prop(struct device *dev, u32 fc, u32 mode, int slot)
{
struct alg_props *props = &nx_driver.of.ap[fc][mode][slot];
if (!props->sglen || props->databytelen < NX_PAGE_SIZE) {
if (dev)
dev_warn(dev, "bogus sglen/databytelen for %u/%u/%u: "
"%u/%u (ignored)\n", fc, mode, slot,
props->sglen, props->databytelen);
return false;
}
return true;
}
static bool nx_check_props(struct device *dev, u32 fc, u32 mode)
{
int i;
for (i = 0; i < 3; i++)
if (!nx_check_prop(dev, fc, mode, i))
return false;
return true;
}
static int nx_register_alg(struct crypto_alg *alg, u32 fc, u32 mode)
{
return nx_check_props(&nx_driver.viodev->dev, fc, mode) ?
crypto_register_alg(alg) : 0;
}
static int nx_register_aead(struct aead_alg *alg, u32 fc, u32 mode)
{
return nx_check_props(&nx_driver.viodev->dev, fc, mode) ?
crypto_register_aead(alg) : 0;
}
static int nx_register_shash(struct shash_alg *alg, u32 fc, u32 mode, int slot)
{
return (slot >= 0 ? nx_check_prop(&nx_driver.viodev->dev,
fc, mode, slot) :
nx_check_props(&nx_driver.viodev->dev, fc, mode)) ?
crypto_register_shash(alg) : 0;
}
static void nx_unregister_alg(struct crypto_alg *alg, u32 fc, u32 mode)
{
if (nx_check_props(NULL, fc, mode))
crypto_unregister_alg(alg);
}
static void nx_unregister_aead(struct aead_alg *alg, u32 fc, u32 mode)
{
if (nx_check_props(NULL, fc, mode))
crypto_unregister_aead(alg);
}
static void nx_unregister_shash(struct shash_alg *alg, u32 fc, u32 mode,
int slot)
{
if (slot >= 0 ? nx_check_prop(NULL, fc, mode, slot) :
nx_check_props(NULL, fc, mode))
crypto_unregister_shash(alg);
}
/**
* nx_register_algs - register algorithms with the crypto API
*
* Called from nx_probe()
*
* If all OF properties are in an acceptable state, the driver flags will
* indicate that we're ready and we'll create our debugfs files and register
* out crypto algorithms.
*/
static int nx_register_algs(void)
{
int rc = -1;
if (nx_driver.of.flags != NX_OF_FLAG_MASK_READY)
goto out;
memset(&nx_driver.stats, 0, sizeof(struct nx_stats));
rc = NX_DEBUGFS_INIT(&nx_driver);
if (rc)
goto out;
nx_driver.of.status = NX_OKAY;
rc = nx_register_alg(&nx_ecb_aes_alg, NX_FC_AES, NX_MODE_AES_ECB);
if (rc)
goto out;
rc = nx_register_alg(&nx_cbc_aes_alg, NX_FC_AES, NX_MODE_AES_CBC);
if (rc)
goto out_unreg_ecb;
rc = nx_register_alg(&nx_ctr3686_aes_alg, NX_FC_AES, NX_MODE_AES_CTR);
if (rc)
goto out_unreg_cbc;
rc = nx_register_aead(&nx_gcm_aes_alg, NX_FC_AES, NX_MODE_AES_GCM);
if (rc)
goto out_unreg_ctr3686;
rc = nx_register_aead(&nx_gcm4106_aes_alg, NX_FC_AES, NX_MODE_AES_GCM);
if (rc)
goto out_unreg_gcm;
rc = nx_register_aead(&nx_ccm_aes_alg, NX_FC_AES, NX_MODE_AES_CCM);
if (rc)
goto out_unreg_gcm4106;
rc = nx_register_aead(&nx_ccm4309_aes_alg, NX_FC_AES, NX_MODE_AES_CCM);
if (rc)
goto out_unreg_ccm;
rc = nx_register_shash(&nx_shash_sha256_alg, NX_FC_SHA, NX_MODE_SHA,
NX_PROPS_SHA256);
if (rc)
goto out_unreg_ccm4309;
rc = nx_register_shash(&nx_shash_sha512_alg, NX_FC_SHA, NX_MODE_SHA,
NX_PROPS_SHA512);
if (rc)
goto out_unreg_s256;
rc = nx_register_shash(&nx_shash_aes_xcbc_alg,
NX_FC_AES, NX_MODE_AES_XCBC_MAC, -1);
if (rc)
goto out_unreg_s512;
goto out;
out_unreg_s512:
nx_unregister_shash(&nx_shash_sha512_alg, NX_FC_SHA, NX_MODE_SHA,
NX_PROPS_SHA512);
out_unreg_s256:
nx_unregister_shash(&nx_shash_sha256_alg, NX_FC_SHA, NX_MODE_SHA,
NX_PROPS_SHA256);
out_unreg_ccm4309:
nx_unregister_aead(&nx_ccm4309_aes_alg, NX_FC_AES, NX_MODE_AES_CCM);
out_unreg_ccm:
nx_unregister_aead(&nx_ccm_aes_alg, NX_FC_AES, NX_MODE_AES_CCM);
out_unreg_gcm4106:
nx_unregister_aead(&nx_gcm4106_aes_alg, NX_FC_AES, NX_MODE_AES_GCM);
out_unreg_gcm:
nx_unregister_aead(&nx_gcm_aes_alg, NX_FC_AES, NX_MODE_AES_GCM);
out_unreg_ctr3686:
nx_unregister_alg(&nx_ctr3686_aes_alg, NX_FC_AES, NX_MODE_AES_CTR);
out_unreg_cbc:
nx_unregister_alg(&nx_cbc_aes_alg, NX_FC_AES, NX_MODE_AES_CBC);
out_unreg_ecb:
nx_unregister_alg(&nx_ecb_aes_alg, NX_FC_AES, NX_MODE_AES_ECB);
out:
return rc;
}
/**
* nx_crypto_ctx_init - create and initialize a crypto api context
*
* @nx_ctx: the crypto api context
* @fc: function code for the context
* @mode: the function code specific mode for this context
*/
static int nx_crypto_ctx_init(struct nx_crypto_ctx *nx_ctx, u32 fc, u32 mode)
{
if (nx_driver.of.status != NX_OKAY) {
pr_err("Attempt to initialize NX crypto context while device "
"is not available!\n");
return -ENODEV;
}
/* we need an extra page for csbcpb_aead for these modes */
if (mode == NX_MODE_AES_GCM || mode == NX_MODE_AES_CCM)
nx_ctx->kmem_len = (5 * NX_PAGE_SIZE) +
sizeof(struct nx_csbcpb);
else
nx_ctx->kmem_len = (4 * NX_PAGE_SIZE) +
sizeof(struct nx_csbcpb);
nx_ctx->kmem = kmalloc(nx_ctx->kmem_len, GFP_KERNEL);
if (!nx_ctx->kmem)
return -ENOMEM;
/* the csbcpb and scatterlists must be 4K aligned pages */
nx_ctx->csbcpb = (struct nx_csbcpb *)(round_up((u64)nx_ctx->kmem,
(u64)NX_PAGE_SIZE));
nx_ctx->in_sg = (struct nx_sg *)((u8 *)nx_ctx->csbcpb + NX_PAGE_SIZE);
nx_ctx->out_sg = (struct nx_sg *)((u8 *)nx_ctx->in_sg + NX_PAGE_SIZE);
if (mode == NX_MODE_AES_GCM || mode == NX_MODE_AES_CCM)
nx_ctx->csbcpb_aead =
(struct nx_csbcpb *)((u8 *)nx_ctx->out_sg +
NX_PAGE_SIZE);
/* give each context a pointer to global stats and their OF
* properties */
nx_ctx->stats = &nx_driver.stats;
memcpy(nx_ctx->props, nx_driver.of.ap[fc][mode],
sizeof(struct alg_props) * 3);
return 0;
}
/* entry points from the crypto tfm initializers */
int nx_crypto_ctx_aes_ccm_init(struct crypto_aead *tfm)
{
crypto_aead_set_reqsize(tfm, sizeof(struct nx_ccm_rctx));
return nx_crypto_ctx_init(crypto_aead_ctx(tfm), NX_FC_AES,
NX_MODE_AES_CCM);
}
int nx_crypto_ctx_aes_gcm_init(struct crypto_aead *tfm)
{
crypto_aead_set_reqsize(tfm, sizeof(struct nx_gcm_rctx));
return nx_crypto_ctx_init(crypto_aead_ctx(tfm), NX_FC_AES,
NX_MODE_AES_GCM);
}
int nx_crypto_ctx_aes_ctr_init(struct crypto_tfm *tfm)
{
return nx_crypto_ctx_init(crypto_tfm_ctx(tfm), NX_FC_AES,
NX_MODE_AES_CTR);
}
int nx_crypto_ctx_aes_cbc_init(struct crypto_tfm *tfm)
{
return nx_crypto_ctx_init(crypto_tfm_ctx(tfm), NX_FC_AES,
NX_MODE_AES_CBC);
}
int nx_crypto_ctx_aes_ecb_init(struct crypto_tfm *tfm)
{
return nx_crypto_ctx_init(crypto_tfm_ctx(tfm), NX_FC_AES,
NX_MODE_AES_ECB);
}
int nx_crypto_ctx_sha_init(struct crypto_tfm *tfm)
{
return nx_crypto_ctx_init(crypto_tfm_ctx(tfm), NX_FC_SHA, NX_MODE_SHA);
}
int nx_crypto_ctx_aes_xcbc_init(struct crypto_tfm *tfm)
{
return nx_crypto_ctx_init(crypto_tfm_ctx(tfm), NX_FC_AES,
NX_MODE_AES_XCBC_MAC);
}
/**
* nx_crypto_ctx_exit - destroy a crypto api context
*
* @tfm: the crypto transform pointer for the context
*
* As crypto API contexts are destroyed, this exit hook is called to free the
* memory associated with it.
*/
void nx_crypto_ctx_exit(struct crypto_tfm *tfm)
{
struct nx_crypto_ctx *nx_ctx = crypto_tfm_ctx(tfm);
kzfree(nx_ctx->kmem);
nx_ctx->csbcpb = NULL;
nx_ctx->csbcpb_aead = NULL;
nx_ctx->in_sg = NULL;
nx_ctx->out_sg = NULL;
}
void nx_crypto_ctx_aead_exit(struct crypto_aead *tfm)
{
struct nx_crypto_ctx *nx_ctx = crypto_aead_ctx(tfm);
kzfree(nx_ctx->kmem);
}
static int nx_probe(struct vio_dev *viodev, const struct vio_device_id *id)
{
dev_dbg(&viodev->dev, "driver probed: %s resource id: 0x%x\n",
viodev->name, viodev->resource_id);
if (nx_driver.viodev) {
dev_err(&viodev->dev, "%s: Attempt to register more than one "
"instance of the hardware\n", __func__);
return -EINVAL;
}
nx_driver.viodev = viodev;
nx_of_init(&viodev->dev, &nx_driver.of);
return nx_register_algs();
}
static int nx_remove(struct vio_dev *viodev)
{
dev_dbg(&viodev->dev, "entering nx_remove for UA 0x%x\n",
viodev->unit_address);
if (nx_driver.of.status == NX_OKAY) {
NX_DEBUGFS_FINI(&nx_driver);
nx_unregister_shash(&nx_shash_aes_xcbc_alg,
NX_FC_AES, NX_MODE_AES_XCBC_MAC, -1);
nx_unregister_shash(&nx_shash_sha512_alg,
NX_FC_SHA, NX_MODE_SHA, NX_PROPS_SHA256);
nx_unregister_shash(&nx_shash_sha256_alg,
NX_FC_SHA, NX_MODE_SHA, NX_PROPS_SHA512);
nx_unregister_aead(&nx_ccm4309_aes_alg,
NX_FC_AES, NX_MODE_AES_CCM);
nx_unregister_aead(&nx_ccm_aes_alg, NX_FC_AES, NX_MODE_AES_CCM);
nx_unregister_aead(&nx_gcm4106_aes_alg,
NX_FC_AES, NX_MODE_AES_GCM);
nx_unregister_aead(&nx_gcm_aes_alg,
NX_FC_AES, NX_MODE_AES_GCM);
nx_unregister_alg(&nx_ctr3686_aes_alg,
NX_FC_AES, NX_MODE_AES_CTR);
nx_unregister_alg(&nx_cbc_aes_alg, NX_FC_AES, NX_MODE_AES_CBC);
nx_unregister_alg(&nx_ecb_aes_alg, NX_FC_AES, NX_MODE_AES_ECB);
}
return 0;
}
/* module wide initialization/cleanup */
static int __init nx_init(void)
{
return vio_register_driver(&nx_driver.viodriver);
}
static void __exit nx_fini(void)
{
vio_unregister_driver(&nx_driver.viodriver);
}
static struct vio_device_id nx_crypto_driver_ids[] = {
{ "ibm,sym-encryption-v1", "ibm,sym-encryption" },
{ "", "" }
};
MODULE_DEVICE_TABLE(vio, nx_crypto_driver_ids);
/* driver state structure */
struct nx_crypto_driver nx_driver = {
.viodriver = {
.id_table = nx_crypto_driver_ids,
.probe = nx_probe,
.remove = nx_remove,
.name = NX_NAME,
},
};
module_init(nx_init);
module_exit(nx_fini);
MODULE_AUTHOR("Kent Yoder <yoder1@us.ibm.com>");
MODULE_DESCRIPTION(NX_STRING);
MODULE_LICENSE("GPL");
MODULE_VERSION(NX_VERSION);
| gpl-2.0 |
HTC-MSM8916/android_kernel_htc_msm8916 | fs/isofs/inode.c | 969 | 40949 | /*
* linux/fs/isofs/inode.c
*
* (C) 1991 Linus Torvalds - minix filesystem
* 1992, 1993, 1994 Eric Youngdale Modified for ISO 9660 filesystem.
* 1994 Eberhard Mönkeberg - multi session handling.
* 1995 Mark Dobie - allow mounting of some weird VideoCDs and PhotoCDs.
* 1997 Gordon Chaffee - Joliet CDs
* 1998 Eric Lammerts - ISO 9660 Level 3
* 2004 Paul Serice - Inode Support pushed out from 4GB to 128GB
* 2004 Paul Serice - NFS Export Operations
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/nls.h>
#include <linux/ctype.h>
#include <linux/statfs.h>
#include <linux/cdrom.h>
#include <linux/parser.h>
#include <linux/mpage.h>
#include <linux/user_namespace.h>
#include "isofs.h"
#include "zisofs.h"
#define BEQUIET
static int isofs_hashi(const struct dentry *parent, const struct inode *inode,
struct qstr *qstr);
static int isofs_hash(const struct dentry *parent, const struct inode *inode,
struct qstr *qstr);
static int isofs_dentry_cmpi(const struct dentry *parent,
const struct inode *pinode,
const struct dentry *dentry, const struct inode *inode,
unsigned int len, const char *str, const struct qstr *name);
static int isofs_dentry_cmp(const struct dentry *parent,
const struct inode *pinode,
const struct dentry *dentry, const struct inode *inode,
unsigned int len, const char *str, const struct qstr *name);
#ifdef CONFIG_JOLIET
static int isofs_hashi_ms(const struct dentry *parent, const struct inode *inode,
struct qstr *qstr);
static int isofs_hash_ms(const struct dentry *parent, const struct inode *inode,
struct qstr *qstr);
static int isofs_dentry_cmpi_ms(const struct dentry *parent,
const struct inode *pinode,
const struct dentry *dentry, const struct inode *inode,
unsigned int len, const char *str, const struct qstr *name);
static int isofs_dentry_cmp_ms(const struct dentry *parent,
const struct inode *pinode,
const struct dentry *dentry, const struct inode *inode,
unsigned int len, const char *str, const struct qstr *name);
#endif
static void isofs_put_super(struct super_block *sb)
{
struct isofs_sb_info *sbi = ISOFS_SB(sb);
#ifdef CONFIG_JOLIET
unload_nls(sbi->s_nls_iocharset);
#endif
kfree(sbi);
sb->s_fs_info = NULL;
return;
}
static int isofs_read_inode(struct inode *);
static int isofs_statfs (struct dentry *, struct kstatfs *);
static struct kmem_cache *isofs_inode_cachep;
static struct inode *isofs_alloc_inode(struct super_block *sb)
{
struct iso_inode_info *ei;
ei = kmem_cache_alloc(isofs_inode_cachep, GFP_KERNEL);
if (!ei)
return NULL;
return &ei->vfs_inode;
}
static void isofs_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(isofs_inode_cachep, ISOFS_I(inode));
}
static void isofs_destroy_inode(struct inode *inode)
{
call_rcu(&inode->i_rcu, isofs_i_callback);
}
static void init_once(void *foo)
{
struct iso_inode_info *ei = foo;
inode_init_once(&ei->vfs_inode);
}
static int init_inodecache(void)
{
isofs_inode_cachep = kmem_cache_create("isofs_inode_cache",
sizeof(struct iso_inode_info),
0, (SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD),
init_once);
if (isofs_inode_cachep == NULL)
return -ENOMEM;
return 0;
}
static void destroy_inodecache(void)
{
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
kmem_cache_destroy(isofs_inode_cachep);
}
static int isofs_remount(struct super_block *sb, int *flags, char *data)
{
if (!(*flags & MS_RDONLY))
return -EROFS;
return 0;
}
static const struct super_operations isofs_sops = {
.alloc_inode = isofs_alloc_inode,
.destroy_inode = isofs_destroy_inode,
.put_super = isofs_put_super,
.statfs = isofs_statfs,
.remount_fs = isofs_remount,
.show_options = generic_show_options,
};
static const struct dentry_operations isofs_dentry_ops[] = {
{
.d_hash = isofs_hash,
.d_compare = isofs_dentry_cmp,
},
{
.d_hash = isofs_hashi,
.d_compare = isofs_dentry_cmpi,
},
#ifdef CONFIG_JOLIET
{
.d_hash = isofs_hash_ms,
.d_compare = isofs_dentry_cmp_ms,
},
{
.d_hash = isofs_hashi_ms,
.d_compare = isofs_dentry_cmpi_ms,
},
#endif
};
struct iso9660_options{
unsigned int rock:1;
unsigned int joliet:1;
unsigned int cruft:1;
unsigned int hide:1;
unsigned int showassoc:1;
unsigned int nocompress:1;
unsigned int overriderockperm:1;
unsigned int uid_set:1;
unsigned int gid_set:1;
unsigned int utf8:1;
unsigned char map;
unsigned char check;
unsigned int blocksize;
umode_t fmode;
umode_t dmode;
kgid_t gid;
kuid_t uid;
char *iocharset;
/* LVE */
s32 session;
s32 sbsector;
};
/*
* Compute the hash for the isofs name corresponding to the dentry.
*/
static int
isofs_hash_common(const struct dentry *dentry, struct qstr *qstr, int ms)
{
const char *name;
int len;
len = qstr->len;
name = qstr->name;
if (ms) {
while (len && name[len-1] == '.')
len--;
}
qstr->hash = full_name_hash(name, len);
return 0;
}
/*
* Compute the hash for the isofs name corresponding to the dentry.
*/
static int
isofs_hashi_common(const struct dentry *dentry, struct qstr *qstr, int ms)
{
const char *name;
int len;
char c;
unsigned long hash;
len = qstr->len;
name = qstr->name;
if (ms) {
while (len && name[len-1] == '.')
len--;
}
hash = init_name_hash();
while (len--) {
c = tolower(*name++);
hash = partial_name_hash(c, hash);
}
qstr->hash = end_name_hash(hash);
return 0;
}
/*
* Compare of two isofs names.
*/
static int isofs_dentry_cmp_common(
unsigned int len, const char *str,
const struct qstr *name, int ms, int ci)
{
int alen, blen;
/* A filename cannot end in '.' or we treat it like it has none */
alen = name->len;
blen = len;
if (ms) {
while (alen && name->name[alen-1] == '.')
alen--;
while (blen && str[blen-1] == '.')
blen--;
}
if (alen == blen) {
if (ci) {
if (strnicmp(name->name, str, alen) == 0)
return 0;
} else {
if (strncmp(name->name, str, alen) == 0)
return 0;
}
}
return 1;
}
static int
isofs_hash(const struct dentry *dentry, const struct inode *inode,
struct qstr *qstr)
{
return isofs_hash_common(dentry, qstr, 0);
}
static int
isofs_hashi(const struct dentry *dentry, const struct inode *inode,
struct qstr *qstr)
{
return isofs_hashi_common(dentry, qstr, 0);
}
static int
isofs_dentry_cmp(const struct dentry *parent, const struct inode *pinode,
const struct dentry *dentry, const struct inode *inode,
unsigned int len, const char *str, const struct qstr *name)
{
return isofs_dentry_cmp_common(len, str, name, 0, 0);
}
static int
isofs_dentry_cmpi(const struct dentry *parent, const struct inode *pinode,
const struct dentry *dentry, const struct inode *inode,
unsigned int len, const char *str, const struct qstr *name)
{
return isofs_dentry_cmp_common(len, str, name, 0, 1);
}
#ifdef CONFIG_JOLIET
static int
isofs_hash_ms(const struct dentry *dentry, const struct inode *inode,
struct qstr *qstr)
{
return isofs_hash_common(dentry, qstr, 1);
}
static int
isofs_hashi_ms(const struct dentry *dentry, const struct inode *inode,
struct qstr *qstr)
{
return isofs_hashi_common(dentry, qstr, 1);
}
static int
isofs_dentry_cmp_ms(const struct dentry *parent, const struct inode *pinode,
const struct dentry *dentry, const struct inode *inode,
unsigned int len, const char *str, const struct qstr *name)
{
return isofs_dentry_cmp_common(len, str, name, 1, 0);
}
static int
isofs_dentry_cmpi_ms(const struct dentry *parent, const struct inode *pinode,
const struct dentry *dentry, const struct inode *inode,
unsigned int len, const char *str, const struct qstr *name)
{
return isofs_dentry_cmp_common(len, str, name, 1, 1);
}
#endif
enum {
Opt_block, Opt_check_r, Opt_check_s, Opt_cruft, Opt_gid, Opt_ignore,
Opt_iocharset, Opt_map_a, Opt_map_n, Opt_map_o, Opt_mode, Opt_nojoliet,
Opt_norock, Opt_sb, Opt_session, Opt_uid, Opt_unhide, Opt_utf8, Opt_err,
Opt_nocompress, Opt_hide, Opt_showassoc, Opt_dmode, Opt_overriderockperm,
};
static const match_table_t tokens = {
{Opt_norock, "norock"},
{Opt_nojoliet, "nojoliet"},
{Opt_unhide, "unhide"},
{Opt_hide, "hide"},
{Opt_showassoc, "showassoc"},
{Opt_cruft, "cruft"},
{Opt_utf8, "utf8"},
{Opt_iocharset, "iocharset=%s"},
{Opt_map_a, "map=acorn"},
{Opt_map_a, "map=a"},
{Opt_map_n, "map=normal"},
{Opt_map_n, "map=n"},
{Opt_map_o, "map=off"},
{Opt_map_o, "map=o"},
{Opt_session, "session=%u"},
{Opt_sb, "sbsector=%u"},
{Opt_check_r, "check=relaxed"},
{Opt_check_r, "check=r"},
{Opt_check_s, "check=strict"},
{Opt_check_s, "check=s"},
{Opt_uid, "uid=%u"},
{Opt_gid, "gid=%u"},
{Opt_mode, "mode=%u"},
{Opt_dmode, "dmode=%u"},
{Opt_overriderockperm, "overriderockperm"},
{Opt_block, "block=%u"},
{Opt_ignore, "conv=binary"},
{Opt_ignore, "conv=b"},
{Opt_ignore, "conv=text"},
{Opt_ignore, "conv=t"},
{Opt_ignore, "conv=mtext"},
{Opt_ignore, "conv=m"},
{Opt_ignore, "conv=auto"},
{Opt_ignore, "conv=a"},
{Opt_nocompress, "nocompress"},
{Opt_err, NULL}
};
static int parse_options(char *options, struct iso9660_options *popt)
{
char *p;
int option;
popt->map = 'n';
popt->rock = 1;
popt->joliet = 1;
popt->cruft = 0;
popt->hide = 0;
popt->showassoc = 0;
popt->check = 'u'; /* unset */
popt->nocompress = 0;
popt->blocksize = 1024;
popt->fmode = popt->dmode = ISOFS_INVALID_MODE;
popt->uid_set = 0;
popt->gid_set = 0;
popt->gid = GLOBAL_ROOT_GID;
popt->uid = GLOBAL_ROOT_UID;
popt->iocharset = NULL;
popt->utf8 = 0;
popt->overriderockperm = 0;
popt->session=-1;
popt->sbsector=-1;
if (!options)
return 1;
while ((p = strsep(&options, ",")) != NULL) {
int token;
substring_t args[MAX_OPT_ARGS];
unsigned n;
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case Opt_norock:
popt->rock = 0;
break;
case Opt_nojoliet:
popt->joliet = 0;
break;
case Opt_hide:
popt->hide = 1;
break;
case Opt_unhide:
case Opt_showassoc:
popt->showassoc = 1;
break;
case Opt_cruft:
popt->cruft = 1;
break;
case Opt_utf8:
popt->utf8 = 1;
break;
#ifdef CONFIG_JOLIET
case Opt_iocharset:
popt->iocharset = match_strdup(&args[0]);
break;
#endif
case Opt_map_a:
popt->map = 'a';
break;
case Opt_map_o:
popt->map = 'o';
break;
case Opt_map_n:
popt->map = 'n';
break;
case Opt_session:
if (match_int(&args[0], &option))
return 0;
n = option;
if (n > 99)
return 0;
popt->session = n + 1;
break;
case Opt_sb:
if (match_int(&args[0], &option))
return 0;
popt->sbsector = option;
break;
case Opt_check_r:
popt->check = 'r';
break;
case Opt_check_s:
popt->check = 's';
break;
case Opt_ignore:
break;
case Opt_uid:
if (match_int(&args[0], &option))
return 0;
popt->uid = make_kuid(current_user_ns(), option);
if (!uid_valid(popt->uid))
return 0;
popt->uid_set = 1;
break;
case Opt_gid:
if (match_int(&args[0], &option))
return 0;
popt->gid = make_kgid(current_user_ns(), option);
if (!gid_valid(popt->gid))
return 0;
popt->gid_set = 1;
break;
case Opt_mode:
if (match_int(&args[0], &option))
return 0;
popt->fmode = option;
break;
case Opt_dmode:
if (match_int(&args[0], &option))
return 0;
popt->dmode = option;
break;
case Opt_overriderockperm:
popt->overriderockperm = 1;
break;
case Opt_block:
if (match_int(&args[0], &option))
return 0;
n = option;
if (n != 512 && n != 1024 && n != 2048)
return 0;
popt->blocksize = n;
break;
case Opt_nocompress:
popt->nocompress = 1;
break;
default:
return 0;
}
}
return 1;
}
/*
* look if the driver can tell the multi session redirection value
*
* don't change this if you don't know what you do, please!
* Multisession is legal only with XA disks.
* A non-XA disk with more than one volume descriptor may do it right, but
* usually is written in a nowhere standardized "multi-partition" manner.
* Multisession uses absolute addressing (solely the first frame of the whole
* track is #0), multi-partition uses relative addressing (each first frame of
* each track is #0), and a track is not a session.
*
* A broken CDwriter software or drive firmware does not set new standards,
* at least not if conflicting with the existing ones.
*
* emoenke@gwdg.de
*/
#define WE_OBEY_THE_WRITTEN_STANDARDS 1
static unsigned int isofs_get_last_session(struct super_block *sb, s32 session)
{
struct cdrom_multisession ms_info;
unsigned int vol_desc_start;
struct block_device *bdev = sb->s_bdev;
int i;
vol_desc_start=0;
ms_info.addr_format=CDROM_LBA;
if(session >= 0 && session <= 99) {
struct cdrom_tocentry Te;
Te.cdte_track=session;
Te.cdte_format=CDROM_LBA;
i = ioctl_by_bdev(bdev, CDROMREADTOCENTRY, (unsigned long) &Te);
if (!i) {
printk(KERN_DEBUG "ISOFS: Session %d start %d type %d\n",
session, Te.cdte_addr.lba,
Te.cdte_ctrl&CDROM_DATA_TRACK);
if ((Te.cdte_ctrl&CDROM_DATA_TRACK) == 4)
return Te.cdte_addr.lba;
}
printk(KERN_ERR "ISOFS: Invalid session number or type of track\n");
}
i = ioctl_by_bdev(bdev, CDROMMULTISESSION, (unsigned long) &ms_info);
if (session > 0)
printk(KERN_ERR "ISOFS: Invalid session number\n");
#if 0
printk(KERN_DEBUG "isofs.inode: CDROMMULTISESSION: rc=%d\n",i);
if (i==0) {
printk(KERN_DEBUG "isofs.inode: XA disk: %s\n",ms_info.xa_flag?"yes":"no");
printk(KERN_DEBUG "isofs.inode: vol_desc_start = %d\n", ms_info.addr.lba);
}
#endif
if (i==0)
#if WE_OBEY_THE_WRITTEN_STANDARDS
if (ms_info.xa_flag) /* necessary for a valid ms_info.addr */
#endif
vol_desc_start=ms_info.addr.lba;
return vol_desc_start;
}
/*
* Check if root directory is empty (has less than 3 files).
*
* Used to detect broken CDs where ISO root directory is empty but Joliet root
* directory is OK. If such CD has Rock Ridge extensions, they will be disabled
* (and Joliet used instead) or else no files would be visible.
*/
static bool rootdir_empty(struct super_block *sb, unsigned long block)
{
int offset = 0, files = 0, de_len;
struct iso_directory_record *de;
struct buffer_head *bh;
bh = sb_bread(sb, block);
if (!bh)
return true;
while (files < 3) {
de = (struct iso_directory_record *) (bh->b_data + offset);
de_len = *(unsigned char *) de;
if (de_len == 0)
break;
files++;
offset += de_len;
}
brelse(bh);
return files < 3;
}
/*
* Initialize the superblock and read the root inode.
*
* Note: a check_disk_change() has been done immediately prior
* to this call, so we don't need to check again.
*/
static int isofs_fill_super(struct super_block *s, void *data, int silent)
{
struct buffer_head *bh = NULL, *pri_bh = NULL;
struct hs_primary_descriptor *h_pri = NULL;
struct iso_primary_descriptor *pri = NULL;
struct iso_supplementary_descriptor *sec = NULL;
struct iso_directory_record *rootp;
struct inode *inode;
struct iso9660_options opt;
struct isofs_sb_info *sbi;
unsigned long first_data_zone;
int joliet_level = 0;
int iso_blknum, block;
int orig_zonesize;
int table, error = -EINVAL;
unsigned int vol_desc_start;
save_mount_options(s, data);
sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
if (!sbi)
return -ENOMEM;
s->s_fs_info = sbi;
if (!parse_options((char *)data, &opt))
goto out_freesbi;
/*
* First of all, get the hardware blocksize for this device.
* If we don't know what it is, or the hardware blocksize is
* larger than the blocksize the user specified, then use
* that value.
*/
/*
* What if bugger tells us to go beyond page size?
*/
opt.blocksize = sb_min_blocksize(s, opt.blocksize);
sbi->s_high_sierra = 0; /* default is iso9660 */
vol_desc_start = (opt.sbsector != -1) ?
opt.sbsector : isofs_get_last_session(s,opt.session);
for (iso_blknum = vol_desc_start+16;
iso_blknum < vol_desc_start+100; iso_blknum++) {
struct hs_volume_descriptor *hdp;
struct iso_volume_descriptor *vdp;
block = iso_blknum << (ISOFS_BLOCK_BITS - s->s_blocksize_bits);
if (!(bh = sb_bread(s, block)))
goto out_no_read;
vdp = (struct iso_volume_descriptor *)bh->b_data;
hdp = (struct hs_volume_descriptor *)bh->b_data;
/*
* Due to the overlapping physical location of the descriptors,
* ISO CDs can match hdp->id==HS_STANDARD_ID as well. To ensure
* proper identification in this case, we first check for ISO.
*/
if (strncmp (vdp->id, ISO_STANDARD_ID, sizeof vdp->id) == 0) {
if (isonum_711(vdp->type) == ISO_VD_END)
break;
if (isonum_711(vdp->type) == ISO_VD_PRIMARY) {
if (pri == NULL) {
pri = (struct iso_primary_descriptor *)vdp;
/* Save the buffer in case we need it ... */
pri_bh = bh;
bh = NULL;
}
}
#ifdef CONFIG_JOLIET
else if (isonum_711(vdp->type) == ISO_VD_SUPPLEMENTARY) {
sec = (struct iso_supplementary_descriptor *)vdp;
if (sec->escape[0] == 0x25 && sec->escape[1] == 0x2f) {
if (opt.joliet) {
if (sec->escape[2] == 0x40)
joliet_level = 1;
else if (sec->escape[2] == 0x43)
joliet_level = 2;
else if (sec->escape[2] == 0x45)
joliet_level = 3;
printk(KERN_DEBUG "ISO 9660 Extensions: "
"Microsoft Joliet Level %d\n",
joliet_level);
}
goto root_found;
} else {
/* Unknown supplementary volume descriptor */
sec = NULL;
}
}
#endif
} else {
if (strncmp (hdp->id, HS_STANDARD_ID, sizeof hdp->id) == 0) {
if (isonum_711(hdp->type) != ISO_VD_PRIMARY)
goto out_freebh;
sbi->s_high_sierra = 1;
opt.rock = 0;
h_pri = (struct hs_primary_descriptor *)vdp;
goto root_found;
}
}
/* Just skip any volume descriptors we don't recognize */
brelse(bh);
bh = NULL;
}
/*
* If we fall through, either no volume descriptor was found,
* or else we passed a primary descriptor looking for others.
*/
if (!pri)
goto out_unknown_format;
brelse(bh);
bh = pri_bh;
pri_bh = NULL;
root_found:
if (joliet_level && (pri == NULL || !opt.rock)) {
/* This is the case of Joliet with the norock mount flag.
* A disc with both Joliet and Rock Ridge is handled later
*/
pri = (struct iso_primary_descriptor *) sec;
}
if(sbi->s_high_sierra){
rootp = (struct iso_directory_record *) h_pri->root_directory_record;
sbi->s_nzones = isonum_733(h_pri->volume_space_size);
sbi->s_log_zone_size = isonum_723(h_pri->logical_block_size);
sbi->s_max_size = isonum_733(h_pri->volume_space_size);
} else {
if (!pri)
goto out_freebh;
rootp = (struct iso_directory_record *) pri->root_directory_record;
sbi->s_nzones = isonum_733(pri->volume_space_size);
sbi->s_log_zone_size = isonum_723(pri->logical_block_size);
sbi->s_max_size = isonum_733(pri->volume_space_size);
}
sbi->s_ninodes = 0; /* No way to figure this out easily */
orig_zonesize = sbi->s_log_zone_size;
/*
* If the zone size is smaller than the hardware sector size,
* this is a fatal error. This would occur if the disc drive
* had sectors that were 2048 bytes, but the filesystem had
* blocks that were 512 bytes (which should only very rarely
* happen.)
*/
if (orig_zonesize < opt.blocksize)
goto out_bad_size;
/* RDE: convert log zone size to bit shift */
switch (sbi->s_log_zone_size) {
case 512: sbi->s_log_zone_size = 9; break;
case 1024: sbi->s_log_zone_size = 10; break;
case 2048: sbi->s_log_zone_size = 11; break;
default:
goto out_bad_zone_size;
}
s->s_magic = ISOFS_SUPER_MAGIC;
/*
* With multi-extent files, file size is only limited by the maximum
* size of a file system, which is 8 TB.
*/
s->s_maxbytes = 0x80000000000LL;
/* Set this for reference. Its not currently used except on write
which we don't have .. */
first_data_zone = isonum_733(rootp->extent) +
isonum_711(rootp->ext_attr_length);
sbi->s_firstdatazone = first_data_zone;
#ifndef BEQUIET
printk(KERN_DEBUG "ISOFS: Max size:%ld Log zone size:%ld\n",
sbi->s_max_size, 1UL << sbi->s_log_zone_size);
printk(KERN_DEBUG "ISOFS: First datazone:%ld\n", sbi->s_firstdatazone);
if(sbi->s_high_sierra)
printk(KERN_DEBUG "ISOFS: Disc in High Sierra format.\n");
#endif
/*
* If the Joliet level is set, we _may_ decide to use the
* secondary descriptor, but can't be sure until after we
* read the root inode. But before reading the root inode
* we may need to change the device blocksize, and would
* rather release the old buffer first. So, we cache the
* first_data_zone value from the secondary descriptor.
*/
if (joliet_level) {
pri = (struct iso_primary_descriptor *) sec;
rootp = (struct iso_directory_record *)
pri->root_directory_record;
first_data_zone = isonum_733(rootp->extent) +
isonum_711(rootp->ext_attr_length);
}
/*
* We're all done using the volume descriptor, and may need
* to change the device blocksize, so release the buffer now.
*/
brelse(pri_bh);
brelse(bh);
/*
* Force the blocksize to 512 for 512 byte sectors. The file
* read primitives really get it wrong in a bad way if we don't
* do this.
*
* Note - we should never be setting the blocksize to something
* less than the hardware sector size for the device. If we
* do, we would end up having to read larger buffers and split
* out portions to satisfy requests.
*
* Note2- the idea here is that we want to deal with the optimal
* zonesize in the filesystem. If we have it set to something less,
* then we have horrible problems with trying to piece together
* bits of adjacent blocks in order to properly read directory
* entries. By forcing the blocksize in this way, we ensure
* that we will never be required to do this.
*/
sb_set_blocksize(s, orig_zonesize);
sbi->s_nls_iocharset = NULL;
#ifdef CONFIG_JOLIET
if (joliet_level && opt.utf8 == 0) {
char *p = opt.iocharset ? opt.iocharset : CONFIG_NLS_DEFAULT;
sbi->s_nls_iocharset = load_nls(p);
if (! sbi->s_nls_iocharset) {
/* Fail only if explicit charset specified */
if (opt.iocharset)
goto out_freesbi;
sbi->s_nls_iocharset = load_nls_default();
}
}
#endif
s->s_op = &isofs_sops;
s->s_export_op = &isofs_export_ops;
sbi->s_mapping = opt.map;
sbi->s_rock = (opt.rock ? 2 : 0);
sbi->s_rock_offset = -1; /* initial offset, will guess until SP is found*/
sbi->s_cruft = opt.cruft;
sbi->s_hide = opt.hide;
sbi->s_showassoc = opt.showassoc;
sbi->s_uid = opt.uid;
sbi->s_gid = opt.gid;
sbi->s_uid_set = opt.uid_set;
sbi->s_gid_set = opt.gid_set;
sbi->s_utf8 = opt.utf8;
sbi->s_nocompress = opt.nocompress;
sbi->s_overriderockperm = opt.overriderockperm;
/*
* It would be incredibly stupid to allow people to mark every file
* on the disk as suid, so we merely allow them to set the default
* permissions.
*/
if (opt.fmode != ISOFS_INVALID_MODE)
sbi->s_fmode = opt.fmode & 0777;
else
sbi->s_fmode = ISOFS_INVALID_MODE;
if (opt.dmode != ISOFS_INVALID_MODE)
sbi->s_dmode = opt.dmode & 0777;
else
sbi->s_dmode = ISOFS_INVALID_MODE;
/*
* Read the root inode, which _may_ result in changing
* the s_rock flag. Once we have the final s_rock value,
* we then decide whether to use the Joliet descriptor.
*/
inode = isofs_iget(s, sbi->s_firstdatazone, 0);
if (IS_ERR(inode))
goto out_no_root;
/*
* Fix for broken CDs with Rock Ridge and empty ISO root directory but
* correct Joliet root directory.
*/
if (sbi->s_rock == 1 && joliet_level &&
rootdir_empty(s, sbi->s_firstdatazone)) {
printk(KERN_NOTICE
"ISOFS: primary root directory is empty. "
"Disabling Rock Ridge and switching to Joliet.");
sbi->s_rock = 0;
}
/*
* If this disk has both Rock Ridge and Joliet on it, then we
* want to use Rock Ridge by default. This can be overridden
* by using the norock mount option. There is still one other
* possibility that is not taken into account: a Rock Ridge
* CD with Unicode names. Until someone sees such a beast, it
* will not be supported.
*/
if (sbi->s_rock == 1) {
joliet_level = 0;
} else if (joliet_level) {
sbi->s_rock = 0;
if (sbi->s_firstdatazone != first_data_zone) {
sbi->s_firstdatazone = first_data_zone;
printk(KERN_DEBUG
"ISOFS: changing to secondary root\n");
iput(inode);
inode = isofs_iget(s, sbi->s_firstdatazone, 0);
if (IS_ERR(inode))
goto out_no_root;
}
}
if (opt.check == 'u') {
/* Only Joliet is case insensitive by default */
if (joliet_level)
opt.check = 'r';
else
opt.check = 's';
}
sbi->s_joliet_level = joliet_level;
/* Make sure the root inode is a directory */
if (!S_ISDIR(inode->i_mode)) {
printk(KERN_WARNING
"isofs_fill_super: root inode is not a directory. "
"Corrupted media?\n");
goto out_iput;
}
table = 0;
if (joliet_level)
table += 2;
if (opt.check == 'r')
table++;
s->s_d_op = &isofs_dentry_ops[table];
/* get the root dentry */
s->s_root = d_make_root(inode);
if (!(s->s_root)) {
error = -ENOMEM;
goto out_no_inode;
}
kfree(opt.iocharset);
return 0;
/*
* Display error messages and free resources.
*/
out_iput:
iput(inode);
goto out_no_inode;
out_no_root:
error = PTR_ERR(inode);
if (error != -ENOMEM)
printk(KERN_WARNING "%s: get root inode failed\n", __func__);
out_no_inode:
#ifdef CONFIG_JOLIET
unload_nls(sbi->s_nls_iocharset);
#endif
goto out_freesbi;
out_no_read:
printk(KERN_WARNING "%s: bread failed, dev=%s, iso_blknum=%d, block=%d\n",
__func__, s->s_id, iso_blknum, block);
goto out_freebh;
out_bad_zone_size:
printk(KERN_WARNING "ISOFS: Bad logical zone size %ld\n",
sbi->s_log_zone_size);
goto out_freebh;
out_bad_size:
printk(KERN_WARNING "ISOFS: Logical zone size(%d) < hardware blocksize(%u)\n",
orig_zonesize, opt.blocksize);
goto out_freebh;
out_unknown_format:
if (!silent)
printk(KERN_WARNING "ISOFS: Unable to identify CD-ROM format.\n");
out_freebh:
brelse(bh);
brelse(pri_bh);
out_freesbi:
kfree(opt.iocharset);
kfree(sbi);
s->s_fs_info = NULL;
return error;
}
static int isofs_statfs (struct dentry *dentry, struct kstatfs *buf)
{
struct super_block *sb = dentry->d_sb;
u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
buf->f_type = ISOFS_SUPER_MAGIC;
buf->f_bsize = sb->s_blocksize;
buf->f_blocks = (ISOFS_SB(sb)->s_nzones
<< (ISOFS_SB(sb)->s_log_zone_size - sb->s_blocksize_bits));
buf->f_bfree = 0;
buf->f_bavail = 0;
buf->f_files = ISOFS_SB(sb)->s_ninodes;
buf->f_ffree = 0;
buf->f_fsid.val[0] = (u32)id;
buf->f_fsid.val[1] = (u32)(id >> 32);
buf->f_namelen = NAME_MAX;
return 0;
}
/*
* Get a set of blocks; filling in buffer_heads if already allocated
* or getblk() if they are not. Returns the number of blocks inserted
* (-ve == error.)
*/
int isofs_get_blocks(struct inode *inode, sector_t iblock,
struct buffer_head **bh, unsigned long nblocks)
{
unsigned long b_off = iblock;
unsigned offset, sect_size;
unsigned int firstext;
unsigned long nextblk, nextoff;
int section, rv, error;
struct iso_inode_info *ei = ISOFS_I(inode);
error = -EIO;
rv = 0;
if (iblock != b_off) {
printk(KERN_DEBUG "%s: block number too large\n", __func__);
goto abort;
}
offset = 0;
firstext = ei->i_first_extent;
sect_size = ei->i_section_size >> ISOFS_BUFFER_BITS(inode);
nextblk = ei->i_next_section_block;
nextoff = ei->i_next_section_offset;
section = 0;
while (nblocks) {
/* If we are *way* beyond the end of the file, print a message.
* Access beyond the end of the file up to the next page boundary
* is normal, however because of the way the page cache works.
* In this case, we just return 0 so that we can properly fill
* the page with useless information without generating any
* I/O errors.
*/
if (b_off > ((inode->i_size + PAGE_CACHE_SIZE - 1) >> ISOFS_BUFFER_BITS(inode))) {
printk(KERN_DEBUG "%s: block >= EOF (%lu, %llu)\n",
__func__, b_off,
(unsigned long long)inode->i_size);
goto abort;
}
/* On the last section, nextblk == 0, section size is likely to
* exceed sect_size by a partial block, and access beyond the
* end of the file will reach beyond the section size, too.
*/
while (nextblk && (b_off >= (offset + sect_size))) {
struct inode *ninode;
offset += sect_size;
ninode = isofs_iget(inode->i_sb, nextblk, nextoff);
if (IS_ERR(ninode)) {
error = PTR_ERR(ninode);
goto abort;
}
firstext = ISOFS_I(ninode)->i_first_extent;
sect_size = ISOFS_I(ninode)->i_section_size >> ISOFS_BUFFER_BITS(ninode);
nextblk = ISOFS_I(ninode)->i_next_section_block;
nextoff = ISOFS_I(ninode)->i_next_section_offset;
iput(ninode);
if (++section > 100) {
printk(KERN_DEBUG "%s: More than 100 file sections ?!?"
" aborting...\n", __func__);
printk(KERN_DEBUG "%s: block=%lu firstext=%u sect_size=%u "
"nextblk=%lu nextoff=%lu\n", __func__,
b_off, firstext, (unsigned) sect_size,
nextblk, nextoff);
goto abort;
}
}
if (*bh) {
map_bh(*bh, inode->i_sb, firstext + b_off - offset);
} else {
*bh = sb_getblk(inode->i_sb, firstext+b_off-offset);
if (!*bh)
goto abort;
}
bh++; /* Next buffer head */
b_off++; /* Next buffer offset */
nblocks--;
rv++;
}
error = 0;
abort:
return rv != 0 ? rv : error;
}
/*
* Used by the standard interfaces.
*/
static int isofs_get_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
int ret;
if (create) {
printk(KERN_DEBUG "%s: Kernel tries to allocate a block\n", __func__);
return -EROFS;
}
ret = isofs_get_blocks(inode, iblock, &bh_result, 1);
return ret < 0 ? ret : 0;
}
static int isofs_bmap(struct inode *inode, sector_t block)
{
struct buffer_head dummy;
int error;
dummy.b_state = 0;
dummy.b_blocknr = -1000;
error = isofs_get_block(inode, block, &dummy, 0);
if (!error)
return dummy.b_blocknr;
return 0;
}
struct buffer_head *isofs_bread(struct inode *inode, sector_t block)
{
sector_t blknr = isofs_bmap(inode, block);
if (!blknr)
return NULL;
return sb_bread(inode->i_sb, blknr);
}
static int isofs_readpage(struct file *file, struct page *page)
{
return mpage_readpage(page, isofs_get_block);
}
static int isofs_readpages(struct file *file, struct address_space *mapping,
struct list_head *pages, unsigned nr_pages)
{
return mpage_readpages(mapping, pages, nr_pages, isofs_get_block);
}
static sector_t _isofs_bmap(struct address_space *mapping, sector_t block)
{
return generic_block_bmap(mapping,block,isofs_get_block);
}
static const struct address_space_operations isofs_aops = {
.readpage = isofs_readpage,
.readpages = isofs_readpages,
.bmap = _isofs_bmap
};
static int isofs_read_level3_size(struct inode *inode)
{
unsigned long bufsize = ISOFS_BUFFER_SIZE(inode);
int high_sierra = ISOFS_SB(inode->i_sb)->s_high_sierra;
struct buffer_head *bh = NULL;
unsigned long block, offset, block_saved, offset_saved;
int i = 0;
int more_entries = 0;
struct iso_directory_record *tmpde = NULL;
struct iso_inode_info *ei = ISOFS_I(inode);
inode->i_size = 0;
/* The first 16 blocks are reserved as the System Area. Thus,
* no inodes can appear in block 0. We use this to flag that
* this is the last section. */
ei->i_next_section_block = 0;
ei->i_next_section_offset = 0;
block = ei->i_iget5_block;
offset = ei->i_iget5_offset;
do {
struct iso_directory_record *de;
unsigned int de_len;
if (!bh) {
bh = sb_bread(inode->i_sb, block);
if (!bh)
goto out_noread;
}
de = (struct iso_directory_record *) (bh->b_data + offset);
de_len = *(unsigned char *) de;
if (de_len == 0) {
brelse(bh);
bh = NULL;
++block;
offset = 0;
continue;
}
block_saved = block;
offset_saved = offset;
offset += de_len;
/* Make sure we have a full directory entry */
if (offset >= bufsize) {
int slop = bufsize - offset + de_len;
if (!tmpde) {
tmpde = kmalloc(256, GFP_KERNEL);
if (!tmpde)
goto out_nomem;
}
memcpy(tmpde, de, slop);
offset &= bufsize - 1;
block++;
brelse(bh);
bh = NULL;
if (offset) {
bh = sb_bread(inode->i_sb, block);
if (!bh)
goto out_noread;
memcpy((void *)tmpde+slop, bh->b_data, offset);
}
de = tmpde;
}
inode->i_size += isonum_733(de->size);
if (i == 1) {
ei->i_next_section_block = block_saved;
ei->i_next_section_offset = offset_saved;
}
more_entries = de->flags[-high_sierra] & 0x80;
i++;
if (i > 100)
goto out_toomany;
} while (more_entries);
out:
kfree(tmpde);
if (bh)
brelse(bh);
return 0;
out_nomem:
if (bh)
brelse(bh);
return -ENOMEM;
out_noread:
printk(KERN_INFO "ISOFS: unable to read i-node block %lu\n", block);
kfree(tmpde);
return -EIO;
out_toomany:
printk(KERN_INFO "%s: More than 100 file sections ?!?, aborting...\n"
"isofs_read_level3_size: inode=%lu\n",
__func__, inode->i_ino);
goto out;
}
static int isofs_read_inode(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
struct isofs_sb_info *sbi = ISOFS_SB(sb);
unsigned long bufsize = ISOFS_BUFFER_SIZE(inode);
unsigned long block;
int high_sierra = sbi->s_high_sierra;
struct buffer_head *bh = NULL;
struct iso_directory_record *de;
struct iso_directory_record *tmpde = NULL;
unsigned int de_len;
unsigned long offset;
struct iso_inode_info *ei = ISOFS_I(inode);
int ret = -EIO;
block = ei->i_iget5_block;
bh = sb_bread(inode->i_sb, block);
if (!bh)
goto out_badread;
offset = ei->i_iget5_offset;
de = (struct iso_directory_record *) (bh->b_data + offset);
de_len = *(unsigned char *) de;
if (offset + de_len > bufsize) {
int frag1 = bufsize - offset;
tmpde = kmalloc(de_len, GFP_KERNEL);
if (tmpde == NULL) {
printk(KERN_INFO "%s: out of memory\n", __func__);
ret = -ENOMEM;
goto fail;
}
memcpy(tmpde, bh->b_data + offset, frag1);
brelse(bh);
bh = sb_bread(inode->i_sb, ++block);
if (!bh)
goto out_badread;
memcpy((char *)tmpde+frag1, bh->b_data, de_len - frag1);
de = tmpde;
}
inode->i_ino = isofs_get_ino(ei->i_iget5_block,
ei->i_iget5_offset,
ISOFS_BUFFER_BITS(inode));
/* Assume it is a normal-format file unless told otherwise */
ei->i_file_format = isofs_file_normal;
if (de->flags[-high_sierra] & 2) {
if (sbi->s_dmode != ISOFS_INVALID_MODE)
inode->i_mode = S_IFDIR | sbi->s_dmode;
else
inode->i_mode = S_IFDIR | S_IRUGO | S_IXUGO;
set_nlink(inode, 1); /*
* Set to 1. We know there are 2, but
* the find utility tries to optimize
* if it is 2, and it screws up. It is
* easier to give 1 which tells find to
* do it the hard way.
*/
} else {
if (sbi->s_fmode != ISOFS_INVALID_MODE) {
inode->i_mode = S_IFREG | sbi->s_fmode;
} else {
/*
* Set default permissions: r-x for all. The disc
* could be shared with DOS machines so virtually
* anything could be a valid executable.
*/
inode->i_mode = S_IFREG | S_IRUGO | S_IXUGO;
}
set_nlink(inode, 1);
}
inode->i_uid = sbi->s_uid;
inode->i_gid = sbi->s_gid;
inode->i_blocks = 0;
ei->i_format_parm[0] = 0;
ei->i_format_parm[1] = 0;
ei->i_format_parm[2] = 0;
ei->i_section_size = isonum_733(de->size);
if (de->flags[-high_sierra] & 0x80) {
ret = isofs_read_level3_size(inode);
if (ret < 0)
goto fail;
ret = -EIO;
} else {
ei->i_next_section_block = 0;
ei->i_next_section_offset = 0;
inode->i_size = isonum_733(de->size);
}
/*
* Some dipshit decided to store some other bit of information
* in the high byte of the file length. Truncate size in case
* this CDROM was mounted with the cruft option.
*/
if (sbi->s_cruft)
inode->i_size &= 0x00ffffff;
if (de->interleave[0]) {
printk(KERN_DEBUG "ISOFS: Interleaved files not (yet) supported.\n");
inode->i_size = 0;
}
/* I have no idea what file_unit_size is used for, so
we will flag it for now */
if (de->file_unit_size[0] != 0) {
printk(KERN_DEBUG "ISOFS: File unit size != 0 for ISO file (%ld).\n",
inode->i_ino);
}
/* I have no idea what other flag bits are used for, so
we will flag it for now */
#ifdef DEBUG
if((de->flags[-high_sierra] & ~2)!= 0){
printk(KERN_DEBUG "ISOFS: Unusual flag settings for ISO file "
"(%ld %x).\n",
inode->i_ino, de->flags[-high_sierra]);
}
#endif
inode->i_mtime.tv_sec =
inode->i_atime.tv_sec =
inode->i_ctime.tv_sec = iso_date(de->date, high_sierra);
inode->i_mtime.tv_nsec =
inode->i_atime.tv_nsec =
inode->i_ctime.tv_nsec = 0;
ei->i_first_extent = (isonum_733(de->extent) +
isonum_711(de->ext_attr_length));
/* Set the number of blocks for stat() - should be done before RR */
inode->i_blocks = (inode->i_size + 511) >> 9;
/*
* Now test for possible Rock Ridge extensions which will override
* some of these numbers in the inode structure.
*/
if (!high_sierra) {
parse_rock_ridge_inode(de, inode);
/* if we want uid/gid set, override the rock ridge setting */
if (sbi->s_uid_set)
inode->i_uid = sbi->s_uid;
if (sbi->s_gid_set)
inode->i_gid = sbi->s_gid;
}
/* Now set final access rights if overriding rock ridge setting */
if (S_ISDIR(inode->i_mode) && sbi->s_overriderockperm &&
sbi->s_dmode != ISOFS_INVALID_MODE)
inode->i_mode = S_IFDIR | sbi->s_dmode;
if (S_ISREG(inode->i_mode) && sbi->s_overriderockperm &&
sbi->s_fmode != ISOFS_INVALID_MODE)
inode->i_mode = S_IFREG | sbi->s_fmode;
/* Install the inode operations vector */
if (S_ISREG(inode->i_mode)) {
inode->i_fop = &generic_ro_fops;
switch (ei->i_file_format) {
#ifdef CONFIG_ZISOFS
case isofs_file_compressed:
inode->i_data.a_ops = &zisofs_aops;
break;
#endif
default:
inode->i_data.a_ops = &isofs_aops;
break;
}
} else if (S_ISDIR(inode->i_mode)) {
inode->i_op = &isofs_dir_inode_operations;
inode->i_fop = &isofs_dir_operations;
} else if (S_ISLNK(inode->i_mode)) {
inode->i_op = &page_symlink_inode_operations;
inode->i_data.a_ops = &isofs_symlink_aops;
} else
/* XXX - parse_rock_ridge_inode() had already set i_rdev. */
init_special_inode(inode, inode->i_mode, inode->i_rdev);
ret = 0;
out:
kfree(tmpde);
if (bh)
brelse(bh);
return ret;
out_badread:
printk(KERN_WARNING "ISOFS: unable to read i-node block\n");
fail:
goto out;
}
struct isofs_iget5_callback_data {
unsigned long block;
unsigned long offset;
};
static int isofs_iget5_test(struct inode *ino, void *data)
{
struct iso_inode_info *i = ISOFS_I(ino);
struct isofs_iget5_callback_data *d =
(struct isofs_iget5_callback_data*)data;
return (i->i_iget5_block == d->block)
&& (i->i_iget5_offset == d->offset);
}
static int isofs_iget5_set(struct inode *ino, void *data)
{
struct iso_inode_info *i = ISOFS_I(ino);
struct isofs_iget5_callback_data *d =
(struct isofs_iget5_callback_data*)data;
i->i_iget5_block = d->block;
i->i_iget5_offset = d->offset;
return 0;
}
/* Store, in the inode's containing structure, the block and block
* offset that point to the underlying meta-data for the inode. The
* code below is otherwise similar to the iget() code in
* include/linux/fs.h */
struct inode *isofs_iget(struct super_block *sb,
unsigned long block,
unsigned long offset)
{
unsigned long hashval;
struct inode *inode;
struct isofs_iget5_callback_data data;
long ret;
if (offset >= 1ul << sb->s_blocksize_bits)
return ERR_PTR(-EINVAL);
data.block = block;
data.offset = offset;
hashval = (block << sb->s_blocksize_bits) | offset;
inode = iget5_locked(sb, hashval, &isofs_iget5_test,
&isofs_iget5_set, &data);
if (!inode)
return ERR_PTR(-ENOMEM);
if (inode->i_state & I_NEW) {
ret = isofs_read_inode(inode);
if (ret < 0) {
iget_failed(inode);
inode = ERR_PTR(ret);
} else {
unlock_new_inode(inode);
}
}
return inode;
}
static struct dentry *isofs_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
/* We don't support read-write mounts */
if (!(flags & MS_RDONLY))
return ERR_PTR(-EACCES);
return mount_bdev(fs_type, flags, dev_name, data, isofs_fill_super);
}
static struct file_system_type iso9660_fs_type = {
.owner = THIS_MODULE,
.name = "iso9660",
.mount = isofs_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("iso9660");
MODULE_ALIAS("iso9660");
static int __init init_iso9660_fs(void)
{
int err = init_inodecache();
if (err)
goto out;
#ifdef CONFIG_ZISOFS
err = zisofs_init();
if (err)
goto out1;
#endif
err = register_filesystem(&iso9660_fs_type);
if (err)
goto out2;
return 0;
out2:
#ifdef CONFIG_ZISOFS
zisofs_cleanup();
out1:
#endif
destroy_inodecache();
out:
return err;
}
static void __exit exit_iso9660_fs(void)
{
unregister_filesystem(&iso9660_fs_type);
#ifdef CONFIG_ZISOFS
zisofs_cleanup();
#endif
destroy_inodecache();
}
module_init(init_iso9660_fs)
module_exit(exit_iso9660_fs)
MODULE_LICENSE("GPL");
| gpl-2.0 |
shaumux/semc-kernel-qsd8k-jb | arch/arm/mach-kirkwood/tsx1x-common.c | 969 | 2993 | #include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/platform_device.h>
#include <linux/mtd/physmap.h>
#include <linux/spi/flash.h>
#include <linux/spi/spi.h>
#include <linux/spi/orion_spi.h>
#include <linux/serial_reg.h>
#include <mach/kirkwood.h>
#include "common.h"
/*
* QNAP TS-x1x Boards flash
*/
/****************************************************************************
* 16 MiB NOR flash. The struct mtd_partition is not in the same order as the
* partitions on the device because we want to keep compatability with
* the QNAP firmware.
* Layout as used by QNAP:
* 0x00000000-0x00080000 : "U-Boot"
* 0x00200000-0x00400000 : "Kernel"
* 0x00400000-0x00d00000 : "RootFS"
* 0x00d00000-0x01000000 : "RootFS2"
* 0x00080000-0x000c0000 : "U-Boot Config"
* 0x000c0000-0x00200000 : "NAS Config"
*
* We'll use "RootFS1" instead of "RootFS" to stay compatible with the layout
* used by the QNAP TS-109/TS-209.
*
***************************************************************************/
struct mtd_partition qnap_tsx1x_partitions[] = {
{
.name = "U-Boot",
.size = 0x00080000,
.offset = 0,
.mask_flags = MTD_WRITEABLE,
}, {
.name = "Kernel",
.size = 0x00200000,
.offset = 0x00200000,
}, {
.name = "RootFS1",
.size = 0x00900000,
.offset = 0x00400000,
}, {
.name = "RootFS2",
.size = 0x00300000,
.offset = 0x00d00000,
}, {
.name = "U-Boot Config",
.size = 0x00040000,
.offset = 0x00080000,
}, {
.name = "NAS Config",
.size = 0x00140000,
.offset = 0x000c0000,
},
};
const struct flash_platform_data qnap_tsx1x_flash = {
.type = "m25p128",
.name = "spi_flash",
.parts = qnap_tsx1x_partitions,
.nr_parts = ARRAY_SIZE(qnap_tsx1x_partitions),
};
struct spi_board_info __initdata qnap_tsx1x_spi_slave_info[] = {
{
.modalias = "m25p80",
.platform_data = &qnap_tsx1x_flash,
.irq = -1,
.max_speed_hz = 20000000,
.bus_num = 0,
.chip_select = 0,
},
};
void __init qnap_tsx1x_register_flash(void)
{
spi_register_board_info(qnap_tsx1x_spi_slave_info,
ARRAY_SIZE(qnap_tsx1x_spi_slave_info));
kirkwood_spi_init();
}
/*****************************************************************************
* QNAP TS-x1x specific power off method via UART1-attached PIC
****************************************************************************/
#define UART1_REG(x) (UART1_VIRT_BASE + ((UART_##x) << 2))
void qnap_tsx1x_power_off(void)
{
/* 19200 baud divisor */
const unsigned divisor = ((kirkwood_tclk + (8 * 19200)) / (16 * 19200));
pr_info("%s: triggering power-off...\n", __func__);
/* hijack UART1 and reset into sane state (19200,8n1) */
writel(0x83, UART1_REG(LCR));
writel(divisor & 0xff, UART1_REG(DLL));
writel((divisor >> 8) & 0xff, UART1_REG(DLM));
writel(0x03, UART1_REG(LCR));
writel(0x00, UART1_REG(IER));
writel(0x00, UART1_REG(FCR));
writel(0x00, UART1_REG(MCR));
/* send the power-off command 'A' to PIC */
writel('A', UART1_REG(TX));
}
| gpl-2.0 |
JamesAng/lx-std | arch/arm/plat-omap/mailbox.c | 2249 | 9486 | /*
* OMAP mailbox driver
*
* Copyright (C) 2006-2009 Nokia Corporation. All rights reserved.
*
* Contact: Hiroshi DOYU <Hiroshi.DOYU@nokia.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/kfifo.h>
#include <linux/err.h>
#include <linux/notifier.h>
#include <linux/module.h>
#include <plat/mailbox.h>
static struct omap_mbox **mboxes;
static int mbox_configured;
static DEFINE_MUTEX(mbox_configured_lock);
static unsigned int mbox_kfifo_size = CONFIG_OMAP_MBOX_KFIFO_SIZE;
module_param(mbox_kfifo_size, uint, S_IRUGO);
MODULE_PARM_DESC(mbox_kfifo_size, "Size of omap's mailbox kfifo (bytes)");
/* Mailbox FIFO handle functions */
static inline mbox_msg_t mbox_fifo_read(struct omap_mbox *mbox)
{
return mbox->ops->fifo_read(mbox);
}
static inline void mbox_fifo_write(struct omap_mbox *mbox, mbox_msg_t msg)
{
mbox->ops->fifo_write(mbox, msg);
}
static inline int mbox_fifo_empty(struct omap_mbox *mbox)
{
return mbox->ops->fifo_empty(mbox);
}
static inline int mbox_fifo_full(struct omap_mbox *mbox)
{
return mbox->ops->fifo_full(mbox);
}
/* Mailbox IRQ handle functions */
static inline void ack_mbox_irq(struct omap_mbox *mbox, omap_mbox_irq_t irq)
{
if (mbox->ops->ack_irq)
mbox->ops->ack_irq(mbox, irq);
}
static inline int is_mbox_irq(struct omap_mbox *mbox, omap_mbox_irq_t irq)
{
return mbox->ops->is_irq(mbox, irq);
}
/*
* message sender
*/
static int __mbox_poll_for_space(struct omap_mbox *mbox)
{
int ret = 0, i = 1000;
while (mbox_fifo_full(mbox)) {
if (mbox->ops->type == OMAP_MBOX_TYPE2)
return -1;
if (--i == 0)
return -1;
udelay(1);
}
return ret;
}
int omap_mbox_msg_send(struct omap_mbox *mbox, mbox_msg_t msg)
{
struct omap_mbox_queue *mq = mbox->txq;
int ret = 0, len;
spin_lock_bh(&mq->lock);
if (kfifo_avail(&mq->fifo) < sizeof(msg)) {
ret = -ENOMEM;
goto out;
}
if (kfifo_is_empty(&mq->fifo) && !__mbox_poll_for_space(mbox)) {
mbox_fifo_write(mbox, msg);
goto out;
}
len = kfifo_in(&mq->fifo, (unsigned char *)&msg, sizeof(msg));
WARN_ON(len != sizeof(msg));
tasklet_schedule(&mbox->txq->tasklet);
out:
spin_unlock_bh(&mq->lock);
return ret;
}
EXPORT_SYMBOL(omap_mbox_msg_send);
static void mbox_tx_tasklet(unsigned long tx_data)
{
struct omap_mbox *mbox = (struct omap_mbox *)tx_data;
struct omap_mbox_queue *mq = mbox->txq;
mbox_msg_t msg;
int ret;
while (kfifo_len(&mq->fifo)) {
if (__mbox_poll_for_space(mbox)) {
omap_mbox_enable_irq(mbox, IRQ_TX);
break;
}
ret = kfifo_out(&mq->fifo, (unsigned char *)&msg,
sizeof(msg));
WARN_ON(ret != sizeof(msg));
mbox_fifo_write(mbox, msg);
}
}
/*
* Message receiver(workqueue)
*/
static void mbox_rx_work(struct work_struct *work)
{
struct omap_mbox_queue *mq =
container_of(work, struct omap_mbox_queue, work);
mbox_msg_t msg;
int len;
while (kfifo_len(&mq->fifo) >= sizeof(msg)) {
len = kfifo_out(&mq->fifo, (unsigned char *)&msg, sizeof(msg));
WARN_ON(len != sizeof(msg));
blocking_notifier_call_chain(&mq->mbox->notifier, len,
(void *)msg);
spin_lock_irq(&mq->lock);
if (mq->full) {
mq->full = false;
omap_mbox_enable_irq(mq->mbox, IRQ_RX);
}
spin_unlock_irq(&mq->lock);
}
}
/*
* Mailbox interrupt handler
*/
static void __mbox_tx_interrupt(struct omap_mbox *mbox)
{
omap_mbox_disable_irq(mbox, IRQ_TX);
ack_mbox_irq(mbox, IRQ_TX);
tasklet_schedule(&mbox->txq->tasklet);
}
static void __mbox_rx_interrupt(struct omap_mbox *mbox)
{
struct omap_mbox_queue *mq = mbox->rxq;
mbox_msg_t msg;
int len;
while (!mbox_fifo_empty(mbox)) {
if (unlikely(kfifo_avail(&mq->fifo) < sizeof(msg))) {
omap_mbox_disable_irq(mbox, IRQ_RX);
mq->full = true;
goto nomem;
}
msg = mbox_fifo_read(mbox);
len = kfifo_in(&mq->fifo, (unsigned char *)&msg, sizeof(msg));
WARN_ON(len != sizeof(msg));
if (mbox->ops->type == OMAP_MBOX_TYPE1)
break;
}
/* no more messages in the fifo. clear IRQ source. */
ack_mbox_irq(mbox, IRQ_RX);
nomem:
schedule_work(&mbox->rxq->work);
}
static irqreturn_t mbox_interrupt(int irq, void *p)
{
struct omap_mbox *mbox = p;
if (is_mbox_irq(mbox, IRQ_TX))
__mbox_tx_interrupt(mbox);
if (is_mbox_irq(mbox, IRQ_RX))
__mbox_rx_interrupt(mbox);
return IRQ_HANDLED;
}
static struct omap_mbox_queue *mbox_queue_alloc(struct omap_mbox *mbox,
void (*work) (struct work_struct *),
void (*tasklet)(unsigned long))
{
struct omap_mbox_queue *mq;
mq = kzalloc(sizeof(struct omap_mbox_queue), GFP_KERNEL);
if (!mq)
return NULL;
spin_lock_init(&mq->lock);
if (kfifo_alloc(&mq->fifo, mbox_kfifo_size, GFP_KERNEL))
goto error;
if (work)
INIT_WORK(&mq->work, work);
if (tasklet)
tasklet_init(&mq->tasklet, tasklet, (unsigned long)mbox);
return mq;
error:
kfree(mq);
return NULL;
}
static void mbox_queue_free(struct omap_mbox_queue *q)
{
kfifo_free(&q->fifo);
kfree(q);
}
static int omap_mbox_startup(struct omap_mbox *mbox)
{
int ret = 0;
struct omap_mbox_queue *mq;
mutex_lock(&mbox_configured_lock);
if (!mbox_configured++) {
if (likely(mbox->ops->startup)) {
ret = mbox->ops->startup(mbox);
if (unlikely(ret))
goto fail_startup;
} else
goto fail_startup;
}
if (!mbox->use_count++) {
ret = request_irq(mbox->irq, mbox_interrupt, IRQF_SHARED,
mbox->name, mbox);
if (unlikely(ret)) {
pr_err("failed to register mailbox interrupt:%d\n",
ret);
goto fail_request_irq;
}
mq = mbox_queue_alloc(mbox, NULL, mbox_tx_tasklet);
if (!mq) {
ret = -ENOMEM;
goto fail_alloc_txq;
}
mbox->txq = mq;
mq = mbox_queue_alloc(mbox, mbox_rx_work, NULL);
if (!mq) {
ret = -ENOMEM;
goto fail_alloc_rxq;
}
mbox->rxq = mq;
mq->mbox = mbox;
omap_mbox_enable_irq(mbox, IRQ_RX);
}
mutex_unlock(&mbox_configured_lock);
return 0;
fail_alloc_rxq:
mbox_queue_free(mbox->txq);
fail_alloc_txq:
free_irq(mbox->irq, mbox);
fail_request_irq:
if (mbox->ops->shutdown)
mbox->ops->shutdown(mbox);
mbox->use_count--;
fail_startup:
mbox_configured--;
mutex_unlock(&mbox_configured_lock);
return ret;
}
static void omap_mbox_fini(struct omap_mbox *mbox)
{
mutex_lock(&mbox_configured_lock);
if (!--mbox->use_count) {
omap_mbox_disable_irq(mbox, IRQ_RX);
free_irq(mbox->irq, mbox);
tasklet_kill(&mbox->txq->tasklet);
flush_work(&mbox->rxq->work);
mbox_queue_free(mbox->txq);
mbox_queue_free(mbox->rxq);
}
if (likely(mbox->ops->shutdown)) {
if (!--mbox_configured)
mbox->ops->shutdown(mbox);
}
mutex_unlock(&mbox_configured_lock);
}
struct omap_mbox *omap_mbox_get(const char *name, struct notifier_block *nb)
{
struct omap_mbox *_mbox, *mbox = NULL;
int i, ret;
if (!mboxes)
return ERR_PTR(-EINVAL);
for (i = 0; (_mbox = mboxes[i]); i++) {
if (!strcmp(_mbox->name, name)) {
mbox = _mbox;
break;
}
}
if (!mbox)
return ERR_PTR(-ENOENT);
if (nb)
blocking_notifier_chain_register(&mbox->notifier, nb);
ret = omap_mbox_startup(mbox);
if (ret) {
blocking_notifier_chain_unregister(&mbox->notifier, nb);
return ERR_PTR(-ENODEV);
}
return mbox;
}
EXPORT_SYMBOL(omap_mbox_get);
void omap_mbox_put(struct omap_mbox *mbox, struct notifier_block *nb)
{
blocking_notifier_chain_unregister(&mbox->notifier, nb);
omap_mbox_fini(mbox);
}
EXPORT_SYMBOL(omap_mbox_put);
static struct class omap_mbox_class = { .name = "mbox", };
int omap_mbox_register(struct device *parent, struct omap_mbox **list)
{
int ret;
int i;
mboxes = list;
if (!mboxes)
return -EINVAL;
for (i = 0; mboxes[i]; i++) {
struct omap_mbox *mbox = mboxes[i];
mbox->dev = device_create(&omap_mbox_class,
parent, 0, mbox, "%s", mbox->name);
if (IS_ERR(mbox->dev)) {
ret = PTR_ERR(mbox->dev);
goto err_out;
}
BLOCKING_INIT_NOTIFIER_HEAD(&mbox->notifier);
}
return 0;
err_out:
while (i--)
device_unregister(mboxes[i]->dev);
return ret;
}
EXPORT_SYMBOL(omap_mbox_register);
int omap_mbox_unregister(void)
{
int i;
if (!mboxes)
return -EINVAL;
for (i = 0; mboxes[i]; i++)
device_unregister(mboxes[i]->dev);
mboxes = NULL;
return 0;
}
EXPORT_SYMBOL(omap_mbox_unregister);
static int __init omap_mbox_init(void)
{
int err;
err = class_register(&omap_mbox_class);
if (err)
return err;
/* kfifo size sanity check: alignment and minimal size */
mbox_kfifo_size = ALIGN(mbox_kfifo_size, sizeof(mbox_msg_t));
mbox_kfifo_size = max_t(unsigned int, mbox_kfifo_size,
sizeof(mbox_msg_t));
return 0;
}
subsys_initcall(omap_mbox_init);
static void __exit omap_mbox_exit(void)
{
class_unregister(&omap_mbox_class);
}
module_exit(omap_mbox_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("omap mailbox: interrupt driven messaging");
MODULE_AUTHOR("Toshihiro Kobayashi");
MODULE_AUTHOR("Hiroshi DOYU");
| gpl-2.0 |
djvoleur/V_920P_BOF7 | drivers/ata/sata_sil24.c | 2249 | 38479 | /*
* sata_sil24.c - Driver for Silicon Image 3124/3132 SATA-2 controllers
*
* Copyright 2005 Tejun Heo
*
* Based on preview driver from Silicon Image.
*
* 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.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/gfp.h>
#include <linux/pci.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_cmnd.h>
#include <linux/libata.h>
#define DRV_NAME "sata_sil24"
#define DRV_VERSION "1.1"
/*
* Port request block (PRB) 32 bytes
*/
struct sil24_prb {
__le16 ctrl;
__le16 prot;
__le32 rx_cnt;
u8 fis[6 * 4];
};
/*
* Scatter gather entry (SGE) 16 bytes
*/
struct sil24_sge {
__le64 addr;
__le32 cnt;
__le32 flags;
};
enum {
SIL24_HOST_BAR = 0,
SIL24_PORT_BAR = 2,
/* sil24 fetches in chunks of 64bytes. The first block
* contains the PRB and two SGEs. From the second block, it's
* consisted of four SGEs and called SGT. Calculate the
* number of SGTs that fit into one page.
*/
SIL24_PRB_SZ = sizeof(struct sil24_prb)
+ 2 * sizeof(struct sil24_sge),
SIL24_MAX_SGT = (PAGE_SIZE - SIL24_PRB_SZ)
/ (4 * sizeof(struct sil24_sge)),
/* This will give us one unused SGEs for ATA. This extra SGE
* will be used to store CDB for ATAPI devices.
*/
SIL24_MAX_SGE = 4 * SIL24_MAX_SGT + 1,
/*
* Global controller registers (128 bytes @ BAR0)
*/
/* 32 bit regs */
HOST_SLOT_STAT = 0x00, /* 32 bit slot stat * 4 */
HOST_CTRL = 0x40,
HOST_IRQ_STAT = 0x44,
HOST_PHY_CFG = 0x48,
HOST_BIST_CTRL = 0x50,
HOST_BIST_PTRN = 0x54,
HOST_BIST_STAT = 0x58,
HOST_MEM_BIST_STAT = 0x5c,
HOST_FLASH_CMD = 0x70,
/* 8 bit regs */
HOST_FLASH_DATA = 0x74,
HOST_TRANSITION_DETECT = 0x75,
HOST_GPIO_CTRL = 0x76,
HOST_I2C_ADDR = 0x78, /* 32 bit */
HOST_I2C_DATA = 0x7c,
HOST_I2C_XFER_CNT = 0x7e,
HOST_I2C_CTRL = 0x7f,
/* HOST_SLOT_STAT bits */
HOST_SSTAT_ATTN = (1 << 31),
/* HOST_CTRL bits */
HOST_CTRL_M66EN = (1 << 16), /* M66EN PCI bus signal */
HOST_CTRL_TRDY = (1 << 17), /* latched PCI TRDY */
HOST_CTRL_STOP = (1 << 18), /* latched PCI STOP */
HOST_CTRL_DEVSEL = (1 << 19), /* latched PCI DEVSEL */
HOST_CTRL_REQ64 = (1 << 20), /* latched PCI REQ64 */
HOST_CTRL_GLOBAL_RST = (1 << 31), /* global reset */
/*
* Port registers
* (8192 bytes @ +0x0000, +0x2000, +0x4000 and +0x6000 @ BAR2)
*/
PORT_REGS_SIZE = 0x2000,
PORT_LRAM = 0x0000, /* 31 LRAM slots and PMP regs */
PORT_LRAM_SLOT_SZ = 0x0080, /* 32 bytes PRB + 2 SGE, ACT... */
PORT_PMP = 0x0f80, /* 8 bytes PMP * 16 (128 bytes) */
PORT_PMP_STATUS = 0x0000, /* port device status offset */
PORT_PMP_QACTIVE = 0x0004, /* port device QActive offset */
PORT_PMP_SIZE = 0x0008, /* 8 bytes per PMP */
/* 32 bit regs */
PORT_CTRL_STAT = 0x1000, /* write: ctrl-set, read: stat */
PORT_CTRL_CLR = 0x1004, /* write: ctrl-clear */
PORT_IRQ_STAT = 0x1008, /* high: status, low: interrupt */
PORT_IRQ_ENABLE_SET = 0x1010, /* write: enable-set */
PORT_IRQ_ENABLE_CLR = 0x1014, /* write: enable-clear */
PORT_ACTIVATE_UPPER_ADDR= 0x101c,
PORT_EXEC_FIFO = 0x1020, /* command execution fifo */
PORT_CMD_ERR = 0x1024, /* command error number */
PORT_FIS_CFG = 0x1028,
PORT_FIFO_THRES = 0x102c,
/* 16 bit regs */
PORT_DECODE_ERR_CNT = 0x1040,
PORT_DECODE_ERR_THRESH = 0x1042,
PORT_CRC_ERR_CNT = 0x1044,
PORT_CRC_ERR_THRESH = 0x1046,
PORT_HSHK_ERR_CNT = 0x1048,
PORT_HSHK_ERR_THRESH = 0x104a,
/* 32 bit regs */
PORT_PHY_CFG = 0x1050,
PORT_SLOT_STAT = 0x1800,
PORT_CMD_ACTIVATE = 0x1c00, /* 64 bit cmd activate * 31 (248 bytes) */
PORT_CONTEXT = 0x1e04,
PORT_EXEC_DIAG = 0x1e00, /* 32bit exec diag * 16 (64 bytes, 0-10 used on 3124) */
PORT_PSD_DIAG = 0x1e40, /* 32bit psd diag * 16 (64 bytes, 0-8 used on 3124) */
PORT_SCONTROL = 0x1f00,
PORT_SSTATUS = 0x1f04,
PORT_SERROR = 0x1f08,
PORT_SACTIVE = 0x1f0c,
/* PORT_CTRL_STAT bits */
PORT_CS_PORT_RST = (1 << 0), /* port reset */
PORT_CS_DEV_RST = (1 << 1), /* device reset */
PORT_CS_INIT = (1 << 2), /* port initialize */
PORT_CS_IRQ_WOC = (1 << 3), /* interrupt write one to clear */
PORT_CS_CDB16 = (1 << 5), /* 0=12b cdb, 1=16b cdb */
PORT_CS_PMP_RESUME = (1 << 6), /* PMP resume */
PORT_CS_32BIT_ACTV = (1 << 10), /* 32-bit activation */
PORT_CS_PMP_EN = (1 << 13), /* port multiplier enable */
PORT_CS_RDY = (1 << 31), /* port ready to accept commands */
/* PORT_IRQ_STAT/ENABLE_SET/CLR */
/* bits[11:0] are masked */
PORT_IRQ_COMPLETE = (1 << 0), /* command(s) completed */
PORT_IRQ_ERROR = (1 << 1), /* command execution error */
PORT_IRQ_PORTRDY_CHG = (1 << 2), /* port ready change */
PORT_IRQ_PWR_CHG = (1 << 3), /* power management change */
PORT_IRQ_PHYRDY_CHG = (1 << 4), /* PHY ready change */
PORT_IRQ_COMWAKE = (1 << 5), /* COMWAKE received */
PORT_IRQ_UNK_FIS = (1 << 6), /* unknown FIS received */
PORT_IRQ_DEV_XCHG = (1 << 7), /* device exchanged */
PORT_IRQ_8B10B = (1 << 8), /* 8b/10b decode error threshold */
PORT_IRQ_CRC = (1 << 9), /* CRC error threshold */
PORT_IRQ_HANDSHAKE = (1 << 10), /* handshake error threshold */
PORT_IRQ_SDB_NOTIFY = (1 << 11), /* SDB notify received */
DEF_PORT_IRQ = PORT_IRQ_COMPLETE | PORT_IRQ_ERROR |
PORT_IRQ_PHYRDY_CHG | PORT_IRQ_DEV_XCHG |
PORT_IRQ_UNK_FIS | PORT_IRQ_SDB_NOTIFY,
/* bits[27:16] are unmasked (raw) */
PORT_IRQ_RAW_SHIFT = 16,
PORT_IRQ_MASKED_MASK = 0x7ff,
PORT_IRQ_RAW_MASK = (0x7ff << PORT_IRQ_RAW_SHIFT),
/* ENABLE_SET/CLR specific, intr steering - 2 bit field */
PORT_IRQ_STEER_SHIFT = 30,
PORT_IRQ_STEER_MASK = (3 << PORT_IRQ_STEER_SHIFT),
/* PORT_CMD_ERR constants */
PORT_CERR_DEV = 1, /* Error bit in D2H Register FIS */
PORT_CERR_SDB = 2, /* Error bit in SDB FIS */
PORT_CERR_DATA = 3, /* Error in data FIS not detected by dev */
PORT_CERR_SEND = 4, /* Initial cmd FIS transmission failure */
PORT_CERR_INCONSISTENT = 5, /* Protocol mismatch */
PORT_CERR_DIRECTION = 6, /* Data direction mismatch */
PORT_CERR_UNDERRUN = 7, /* Ran out of SGEs while writing */
PORT_CERR_OVERRUN = 8, /* Ran out of SGEs while reading */
PORT_CERR_PKT_PROT = 11, /* DIR invalid in 1st PIO setup of ATAPI */
PORT_CERR_SGT_BOUNDARY = 16, /* PLD ecode 00 - SGT not on qword boundary */
PORT_CERR_SGT_TGTABRT = 17, /* PLD ecode 01 - target abort */
PORT_CERR_SGT_MSTABRT = 18, /* PLD ecode 10 - master abort */
PORT_CERR_SGT_PCIPERR = 19, /* PLD ecode 11 - PCI parity err while fetching SGT */
PORT_CERR_CMD_BOUNDARY = 24, /* ctrl[15:13] 001 - PRB not on qword boundary */
PORT_CERR_CMD_TGTABRT = 25, /* ctrl[15:13] 010 - target abort */
PORT_CERR_CMD_MSTABRT = 26, /* ctrl[15:13] 100 - master abort */
PORT_CERR_CMD_PCIPERR = 27, /* ctrl[15:13] 110 - PCI parity err while fetching PRB */
PORT_CERR_XFR_UNDEF = 32, /* PSD ecode 00 - undefined */
PORT_CERR_XFR_TGTABRT = 33, /* PSD ecode 01 - target abort */
PORT_CERR_XFR_MSTABRT = 34, /* PSD ecode 10 - master abort */
PORT_CERR_XFR_PCIPERR = 35, /* PSD ecode 11 - PCI prity err during transfer */
PORT_CERR_SENDSERVICE = 36, /* FIS received while sending service */
/* bits of PRB control field */
PRB_CTRL_PROTOCOL = (1 << 0), /* override def. ATA protocol */
PRB_CTRL_PACKET_READ = (1 << 4), /* PACKET cmd read */
PRB_CTRL_PACKET_WRITE = (1 << 5), /* PACKET cmd write */
PRB_CTRL_NIEN = (1 << 6), /* Mask completion irq */
PRB_CTRL_SRST = (1 << 7), /* Soft reset request (ign BSY?) */
/* PRB protocol field */
PRB_PROT_PACKET = (1 << 0),
PRB_PROT_TCQ = (1 << 1),
PRB_PROT_NCQ = (1 << 2),
PRB_PROT_READ = (1 << 3),
PRB_PROT_WRITE = (1 << 4),
PRB_PROT_TRANSPARENT = (1 << 5),
/*
* Other constants
*/
SGE_TRM = (1 << 31), /* Last SGE in chain */
SGE_LNK = (1 << 30), /* linked list
Points to SGT, not SGE */
SGE_DRD = (1 << 29), /* discard data read (/dev/null)
data address ignored */
SIL24_MAX_CMDS = 31,
/* board id */
BID_SIL3124 = 0,
BID_SIL3132 = 1,
BID_SIL3131 = 2,
/* host flags */
SIL24_COMMON_FLAGS = ATA_FLAG_SATA | ATA_FLAG_PIO_DMA |
ATA_FLAG_NCQ | ATA_FLAG_ACPI_SATA |
ATA_FLAG_AN | ATA_FLAG_PMP,
SIL24_FLAG_PCIX_IRQ_WOC = (1 << 24), /* IRQ loss errata on PCI-X */
IRQ_STAT_4PORTS = 0xf,
};
struct sil24_ata_block {
struct sil24_prb prb;
struct sil24_sge sge[SIL24_MAX_SGE];
};
struct sil24_atapi_block {
struct sil24_prb prb;
u8 cdb[16];
struct sil24_sge sge[SIL24_MAX_SGE];
};
union sil24_cmd_block {
struct sil24_ata_block ata;
struct sil24_atapi_block atapi;
};
static const struct sil24_cerr_info {
unsigned int err_mask, action;
const char *desc;
} sil24_cerr_db[] = {
[0] = { AC_ERR_DEV, 0,
"device error" },
[PORT_CERR_DEV] = { AC_ERR_DEV, 0,
"device error via D2H FIS" },
[PORT_CERR_SDB] = { AC_ERR_DEV, 0,
"device error via SDB FIS" },
[PORT_CERR_DATA] = { AC_ERR_ATA_BUS, ATA_EH_RESET,
"error in data FIS" },
[PORT_CERR_SEND] = { AC_ERR_ATA_BUS, ATA_EH_RESET,
"failed to transmit command FIS" },
[PORT_CERR_INCONSISTENT] = { AC_ERR_HSM, ATA_EH_RESET,
"protocol mismatch" },
[PORT_CERR_DIRECTION] = { AC_ERR_HSM, ATA_EH_RESET,
"data directon mismatch" },
[PORT_CERR_UNDERRUN] = { AC_ERR_HSM, ATA_EH_RESET,
"ran out of SGEs while writing" },
[PORT_CERR_OVERRUN] = { AC_ERR_HSM, ATA_EH_RESET,
"ran out of SGEs while reading" },
[PORT_CERR_PKT_PROT] = { AC_ERR_HSM, ATA_EH_RESET,
"invalid data directon for ATAPI CDB" },
[PORT_CERR_SGT_BOUNDARY] = { AC_ERR_SYSTEM, ATA_EH_RESET,
"SGT not on qword boundary" },
[PORT_CERR_SGT_TGTABRT] = { AC_ERR_HOST_BUS, ATA_EH_RESET,
"PCI target abort while fetching SGT" },
[PORT_CERR_SGT_MSTABRT] = { AC_ERR_HOST_BUS, ATA_EH_RESET,
"PCI master abort while fetching SGT" },
[PORT_CERR_SGT_PCIPERR] = { AC_ERR_HOST_BUS, ATA_EH_RESET,
"PCI parity error while fetching SGT" },
[PORT_CERR_CMD_BOUNDARY] = { AC_ERR_SYSTEM, ATA_EH_RESET,
"PRB not on qword boundary" },
[PORT_CERR_CMD_TGTABRT] = { AC_ERR_HOST_BUS, ATA_EH_RESET,
"PCI target abort while fetching PRB" },
[PORT_CERR_CMD_MSTABRT] = { AC_ERR_HOST_BUS, ATA_EH_RESET,
"PCI master abort while fetching PRB" },
[PORT_CERR_CMD_PCIPERR] = { AC_ERR_HOST_BUS, ATA_EH_RESET,
"PCI parity error while fetching PRB" },
[PORT_CERR_XFR_UNDEF] = { AC_ERR_HOST_BUS, ATA_EH_RESET,
"undefined error while transferring data" },
[PORT_CERR_XFR_TGTABRT] = { AC_ERR_HOST_BUS, ATA_EH_RESET,
"PCI target abort while transferring data" },
[PORT_CERR_XFR_MSTABRT] = { AC_ERR_HOST_BUS, ATA_EH_RESET,
"PCI master abort while transferring data" },
[PORT_CERR_XFR_PCIPERR] = { AC_ERR_HOST_BUS, ATA_EH_RESET,
"PCI parity error while transferring data" },
[PORT_CERR_SENDSERVICE] = { AC_ERR_HSM, ATA_EH_RESET,
"FIS received while sending service FIS" },
};
/*
* ap->private_data
*
* The preview driver always returned 0 for status. We emulate it
* here from the previous interrupt.
*/
struct sil24_port_priv {
union sil24_cmd_block *cmd_block; /* 32 cmd blocks */
dma_addr_t cmd_block_dma; /* DMA base addr for them */
int do_port_rst;
};
static void sil24_dev_config(struct ata_device *dev);
static int sil24_scr_read(struct ata_link *link, unsigned sc_reg, u32 *val);
static int sil24_scr_write(struct ata_link *link, unsigned sc_reg, u32 val);
static int sil24_qc_defer(struct ata_queued_cmd *qc);
static void sil24_qc_prep(struct ata_queued_cmd *qc);
static unsigned int sil24_qc_issue(struct ata_queued_cmd *qc);
static bool sil24_qc_fill_rtf(struct ata_queued_cmd *qc);
static void sil24_pmp_attach(struct ata_port *ap);
static void sil24_pmp_detach(struct ata_port *ap);
static void sil24_freeze(struct ata_port *ap);
static void sil24_thaw(struct ata_port *ap);
static int sil24_softreset(struct ata_link *link, unsigned int *class,
unsigned long deadline);
static int sil24_hardreset(struct ata_link *link, unsigned int *class,
unsigned long deadline);
static int sil24_pmp_hardreset(struct ata_link *link, unsigned int *class,
unsigned long deadline);
static void sil24_error_handler(struct ata_port *ap);
static void sil24_post_internal_cmd(struct ata_queued_cmd *qc);
static int sil24_port_start(struct ata_port *ap);
static int sil24_init_one(struct pci_dev *pdev, const struct pci_device_id *ent);
#ifdef CONFIG_PM
static int sil24_pci_device_resume(struct pci_dev *pdev);
static int sil24_port_resume(struct ata_port *ap);
#endif
static const struct pci_device_id sil24_pci_tbl[] = {
{ PCI_VDEVICE(CMD, 0x3124), BID_SIL3124 },
{ PCI_VDEVICE(INTEL, 0x3124), BID_SIL3124 },
{ PCI_VDEVICE(CMD, 0x3132), BID_SIL3132 },
{ PCI_VDEVICE(CMD, 0x0242), BID_SIL3132 },
{ PCI_VDEVICE(CMD, 0x0244), BID_SIL3132 },
{ PCI_VDEVICE(CMD, 0x3131), BID_SIL3131 },
{ PCI_VDEVICE(CMD, 0x3531), BID_SIL3131 },
{ } /* terminate list */
};
static struct pci_driver sil24_pci_driver = {
.name = DRV_NAME,
.id_table = sil24_pci_tbl,
.probe = sil24_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM
.suspend = ata_pci_device_suspend,
.resume = sil24_pci_device_resume,
#endif
};
static struct scsi_host_template sil24_sht = {
ATA_NCQ_SHT(DRV_NAME),
.can_queue = SIL24_MAX_CMDS,
.sg_tablesize = SIL24_MAX_SGE,
.dma_boundary = ATA_DMA_BOUNDARY,
};
static struct ata_port_operations sil24_ops = {
.inherits = &sata_pmp_port_ops,
.qc_defer = sil24_qc_defer,
.qc_prep = sil24_qc_prep,
.qc_issue = sil24_qc_issue,
.qc_fill_rtf = sil24_qc_fill_rtf,
.freeze = sil24_freeze,
.thaw = sil24_thaw,
.softreset = sil24_softreset,
.hardreset = sil24_hardreset,
.pmp_softreset = sil24_softreset,
.pmp_hardreset = sil24_pmp_hardreset,
.error_handler = sil24_error_handler,
.post_internal_cmd = sil24_post_internal_cmd,
.dev_config = sil24_dev_config,
.scr_read = sil24_scr_read,
.scr_write = sil24_scr_write,
.pmp_attach = sil24_pmp_attach,
.pmp_detach = sil24_pmp_detach,
.port_start = sil24_port_start,
#ifdef CONFIG_PM
.port_resume = sil24_port_resume,
#endif
};
static bool sata_sil24_msi; /* Disable MSI */
module_param_named(msi, sata_sil24_msi, bool, S_IRUGO);
MODULE_PARM_DESC(msi, "Enable MSI (Default: false)");
/*
* Use bits 30-31 of port_flags to encode available port numbers.
* Current maxium is 4.
*/
#define SIL24_NPORTS2FLAG(nports) ((((unsigned)(nports) - 1) & 0x3) << 30)
#define SIL24_FLAG2NPORTS(flag) ((((flag) >> 30) & 0x3) + 1)
static const struct ata_port_info sil24_port_info[] = {
/* sil_3124 */
{
.flags = SIL24_COMMON_FLAGS | SIL24_NPORTS2FLAG(4) |
SIL24_FLAG_PCIX_IRQ_WOC,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
.port_ops = &sil24_ops,
},
/* sil_3132 */
{
.flags = SIL24_COMMON_FLAGS | SIL24_NPORTS2FLAG(2),
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
.port_ops = &sil24_ops,
},
/* sil_3131/sil_3531 */
{
.flags = SIL24_COMMON_FLAGS | SIL24_NPORTS2FLAG(1),
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
.port_ops = &sil24_ops,
},
};
static int sil24_tag(int tag)
{
if (unlikely(ata_tag_internal(tag)))
return 0;
return tag;
}
static unsigned long sil24_port_offset(struct ata_port *ap)
{
return ap->port_no * PORT_REGS_SIZE;
}
static void __iomem *sil24_port_base(struct ata_port *ap)
{
return ap->host->iomap[SIL24_PORT_BAR] + sil24_port_offset(ap);
}
static void sil24_dev_config(struct ata_device *dev)
{
void __iomem *port = sil24_port_base(dev->link->ap);
if (dev->cdb_len == 16)
writel(PORT_CS_CDB16, port + PORT_CTRL_STAT);
else
writel(PORT_CS_CDB16, port + PORT_CTRL_CLR);
}
static void sil24_read_tf(struct ata_port *ap, int tag, struct ata_taskfile *tf)
{
void __iomem *port = sil24_port_base(ap);
struct sil24_prb __iomem *prb;
u8 fis[6 * 4];
prb = port + PORT_LRAM + sil24_tag(tag) * PORT_LRAM_SLOT_SZ;
memcpy_fromio(fis, prb->fis, sizeof(fis));
ata_tf_from_fis(fis, tf);
}
static int sil24_scr_map[] = {
[SCR_CONTROL] = 0,
[SCR_STATUS] = 1,
[SCR_ERROR] = 2,
[SCR_ACTIVE] = 3,
};
static int sil24_scr_read(struct ata_link *link, unsigned sc_reg, u32 *val)
{
void __iomem *scr_addr = sil24_port_base(link->ap) + PORT_SCONTROL;
if (sc_reg < ARRAY_SIZE(sil24_scr_map)) {
*val = readl(scr_addr + sil24_scr_map[sc_reg] * 4);
return 0;
}
return -EINVAL;
}
static int sil24_scr_write(struct ata_link *link, unsigned sc_reg, u32 val)
{
void __iomem *scr_addr = sil24_port_base(link->ap) + PORT_SCONTROL;
if (sc_reg < ARRAY_SIZE(sil24_scr_map)) {
writel(val, scr_addr + sil24_scr_map[sc_reg] * 4);
return 0;
}
return -EINVAL;
}
static void sil24_config_port(struct ata_port *ap)
{
void __iomem *port = sil24_port_base(ap);
/* configure IRQ WoC */
if (ap->flags & SIL24_FLAG_PCIX_IRQ_WOC)
writel(PORT_CS_IRQ_WOC, port + PORT_CTRL_STAT);
else
writel(PORT_CS_IRQ_WOC, port + PORT_CTRL_CLR);
/* zero error counters. */
writew(0x8000, port + PORT_DECODE_ERR_THRESH);
writew(0x8000, port + PORT_CRC_ERR_THRESH);
writew(0x8000, port + PORT_HSHK_ERR_THRESH);
writew(0x0000, port + PORT_DECODE_ERR_CNT);
writew(0x0000, port + PORT_CRC_ERR_CNT);
writew(0x0000, port + PORT_HSHK_ERR_CNT);
/* always use 64bit activation */
writel(PORT_CS_32BIT_ACTV, port + PORT_CTRL_CLR);
/* clear port multiplier enable and resume bits */
writel(PORT_CS_PMP_EN | PORT_CS_PMP_RESUME, port + PORT_CTRL_CLR);
}
static void sil24_config_pmp(struct ata_port *ap, int attached)
{
void __iomem *port = sil24_port_base(ap);
if (attached)
writel(PORT_CS_PMP_EN, port + PORT_CTRL_STAT);
else
writel(PORT_CS_PMP_EN, port + PORT_CTRL_CLR);
}
static void sil24_clear_pmp(struct ata_port *ap)
{
void __iomem *port = sil24_port_base(ap);
int i;
writel(PORT_CS_PMP_RESUME, port + PORT_CTRL_CLR);
for (i = 0; i < SATA_PMP_MAX_PORTS; i++) {
void __iomem *pmp_base = port + PORT_PMP + i * PORT_PMP_SIZE;
writel(0, pmp_base + PORT_PMP_STATUS);
writel(0, pmp_base + PORT_PMP_QACTIVE);
}
}
static int sil24_init_port(struct ata_port *ap)
{
void __iomem *port = sil24_port_base(ap);
struct sil24_port_priv *pp = ap->private_data;
u32 tmp;
/* clear PMP error status */
if (sata_pmp_attached(ap))
sil24_clear_pmp(ap);
writel(PORT_CS_INIT, port + PORT_CTRL_STAT);
ata_wait_register(ap, port + PORT_CTRL_STAT,
PORT_CS_INIT, PORT_CS_INIT, 10, 100);
tmp = ata_wait_register(ap, port + PORT_CTRL_STAT,
PORT_CS_RDY, 0, 10, 100);
if ((tmp & (PORT_CS_INIT | PORT_CS_RDY)) != PORT_CS_RDY) {
pp->do_port_rst = 1;
ap->link.eh_context.i.action |= ATA_EH_RESET;
return -EIO;
}
return 0;
}
static int sil24_exec_polled_cmd(struct ata_port *ap, int pmp,
const struct ata_taskfile *tf,
int is_cmd, u32 ctrl,
unsigned long timeout_msec)
{
void __iomem *port = sil24_port_base(ap);
struct sil24_port_priv *pp = ap->private_data;
struct sil24_prb *prb = &pp->cmd_block[0].ata.prb;
dma_addr_t paddr = pp->cmd_block_dma;
u32 irq_enabled, irq_mask, irq_stat;
int rc;
prb->ctrl = cpu_to_le16(ctrl);
ata_tf_to_fis(tf, pmp, is_cmd, prb->fis);
/* temporarily plug completion and error interrupts */
irq_enabled = readl(port + PORT_IRQ_ENABLE_SET);
writel(PORT_IRQ_COMPLETE | PORT_IRQ_ERROR, port + PORT_IRQ_ENABLE_CLR);
/*
* The barrier is required to ensure that writes to cmd_block reach
* the memory before the write to PORT_CMD_ACTIVATE.
*/
wmb();
writel((u32)paddr, port + PORT_CMD_ACTIVATE);
writel((u64)paddr >> 32, port + PORT_CMD_ACTIVATE + 4);
irq_mask = (PORT_IRQ_COMPLETE | PORT_IRQ_ERROR) << PORT_IRQ_RAW_SHIFT;
irq_stat = ata_wait_register(ap, port + PORT_IRQ_STAT, irq_mask, 0x0,
10, timeout_msec);
writel(irq_mask, port + PORT_IRQ_STAT); /* clear IRQs */
irq_stat >>= PORT_IRQ_RAW_SHIFT;
if (irq_stat & PORT_IRQ_COMPLETE)
rc = 0;
else {
/* force port into known state */
sil24_init_port(ap);
if (irq_stat & PORT_IRQ_ERROR)
rc = -EIO;
else
rc = -EBUSY;
}
/* restore IRQ enabled */
writel(irq_enabled, port + PORT_IRQ_ENABLE_SET);
return rc;
}
static int sil24_softreset(struct ata_link *link, unsigned int *class,
unsigned long deadline)
{
struct ata_port *ap = link->ap;
int pmp = sata_srst_pmp(link);
unsigned long timeout_msec = 0;
struct ata_taskfile tf;
const char *reason;
int rc;
DPRINTK("ENTER\n");
/* put the port into known state */
if (sil24_init_port(ap)) {
reason = "port not ready";
goto err;
}
/* do SRST */
if (time_after(deadline, jiffies))
timeout_msec = jiffies_to_msecs(deadline - jiffies);
ata_tf_init(link->device, &tf); /* doesn't really matter */
rc = sil24_exec_polled_cmd(ap, pmp, &tf, 0, PRB_CTRL_SRST,
timeout_msec);
if (rc == -EBUSY) {
reason = "timeout";
goto err;
} else if (rc) {
reason = "SRST command error";
goto err;
}
sil24_read_tf(ap, 0, &tf);
*class = ata_dev_classify(&tf);
DPRINTK("EXIT, class=%u\n", *class);
return 0;
err:
ata_link_err(link, "softreset failed (%s)\n", reason);
return -EIO;
}
static int sil24_hardreset(struct ata_link *link, unsigned int *class,
unsigned long deadline)
{
struct ata_port *ap = link->ap;
void __iomem *port = sil24_port_base(ap);
struct sil24_port_priv *pp = ap->private_data;
int did_port_rst = 0;
const char *reason;
int tout_msec, rc;
u32 tmp;
retry:
/* Sometimes, DEV_RST is not enough to recover the controller.
* This happens often after PM DMA CS errata.
*/
if (pp->do_port_rst) {
ata_port_warn(ap,
"controller in dubious state, performing PORT_RST\n");
writel(PORT_CS_PORT_RST, port + PORT_CTRL_STAT);
ata_msleep(ap, 10);
writel(PORT_CS_PORT_RST, port + PORT_CTRL_CLR);
ata_wait_register(ap, port + PORT_CTRL_STAT, PORT_CS_RDY, 0,
10, 5000);
/* restore port configuration */
sil24_config_port(ap);
sil24_config_pmp(ap, ap->nr_pmp_links);
pp->do_port_rst = 0;
did_port_rst = 1;
}
/* sil24 does the right thing(tm) without any protection */
sata_set_spd(link);
tout_msec = 100;
if (ata_link_online(link))
tout_msec = 5000;
writel(PORT_CS_DEV_RST, port + PORT_CTRL_STAT);
tmp = ata_wait_register(ap, port + PORT_CTRL_STAT,
PORT_CS_DEV_RST, PORT_CS_DEV_RST, 10,
tout_msec);
/* SStatus oscillates between zero and valid status after
* DEV_RST, debounce it.
*/
rc = sata_link_debounce(link, sata_deb_timing_long, deadline);
if (rc) {
reason = "PHY debouncing failed";
goto err;
}
if (tmp & PORT_CS_DEV_RST) {
if (ata_link_offline(link))
return 0;
reason = "link not ready";
goto err;
}
/* Sil24 doesn't store signature FIS after hardreset, so we
* can't wait for BSY to clear. Some devices take a long time
* to get ready and those devices will choke if we don't wait
* for BSY clearance here. Tell libata to perform follow-up
* softreset.
*/
return -EAGAIN;
err:
if (!did_port_rst) {
pp->do_port_rst = 1;
goto retry;
}
ata_link_err(link, "hardreset failed (%s)\n", reason);
return -EIO;
}
static inline void sil24_fill_sg(struct ata_queued_cmd *qc,
struct sil24_sge *sge)
{
struct scatterlist *sg;
struct sil24_sge *last_sge = NULL;
unsigned int si;
for_each_sg(qc->sg, sg, qc->n_elem, si) {
sge->addr = cpu_to_le64(sg_dma_address(sg));
sge->cnt = cpu_to_le32(sg_dma_len(sg));
sge->flags = 0;
last_sge = sge;
sge++;
}
last_sge->flags = cpu_to_le32(SGE_TRM);
}
static int sil24_qc_defer(struct ata_queued_cmd *qc)
{
struct ata_link *link = qc->dev->link;
struct ata_port *ap = link->ap;
u8 prot = qc->tf.protocol;
/*
* There is a bug in the chip:
* Port LRAM Causes the PRB/SGT Data to be Corrupted
* If the host issues a read request for LRAM and SActive registers
* while active commands are available in the port, PRB/SGT data in
* the LRAM can become corrupted. This issue applies only when
* reading from, but not writing to, the LRAM.
*
* Therefore, reading LRAM when there is no particular error [and
* other commands may be outstanding] is prohibited.
*
* To avoid this bug there are two situations where a command must run
* exclusive of any other commands on the port:
*
* - ATAPI commands which check the sense data
* - Passthrough ATA commands which always have ATA_QCFLAG_RESULT_TF
* set.
*
*/
int is_excl = (ata_is_atapi(prot) ||
(qc->flags & ATA_QCFLAG_RESULT_TF));
if (unlikely(ap->excl_link)) {
if (link == ap->excl_link) {
if (ap->nr_active_links)
return ATA_DEFER_PORT;
qc->flags |= ATA_QCFLAG_CLEAR_EXCL;
} else
return ATA_DEFER_PORT;
} else if (unlikely(is_excl)) {
ap->excl_link = link;
if (ap->nr_active_links)
return ATA_DEFER_PORT;
qc->flags |= ATA_QCFLAG_CLEAR_EXCL;
}
return ata_std_qc_defer(qc);
}
static void sil24_qc_prep(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct sil24_port_priv *pp = ap->private_data;
union sil24_cmd_block *cb;
struct sil24_prb *prb;
struct sil24_sge *sge;
u16 ctrl = 0;
cb = &pp->cmd_block[sil24_tag(qc->tag)];
if (!ata_is_atapi(qc->tf.protocol)) {
prb = &cb->ata.prb;
sge = cb->ata.sge;
if (ata_is_data(qc->tf.protocol)) {
u16 prot = 0;
ctrl = PRB_CTRL_PROTOCOL;
if (ata_is_ncq(qc->tf.protocol))
prot |= PRB_PROT_NCQ;
if (qc->tf.flags & ATA_TFLAG_WRITE)
prot |= PRB_PROT_WRITE;
else
prot |= PRB_PROT_READ;
prb->prot = cpu_to_le16(prot);
}
} else {
prb = &cb->atapi.prb;
sge = cb->atapi.sge;
memset(cb->atapi.cdb, 0, sizeof(cb->atapi.cdb));
memcpy(cb->atapi.cdb, qc->cdb, qc->dev->cdb_len);
if (ata_is_data(qc->tf.protocol)) {
if (qc->tf.flags & ATA_TFLAG_WRITE)
ctrl = PRB_CTRL_PACKET_WRITE;
else
ctrl = PRB_CTRL_PACKET_READ;
}
}
prb->ctrl = cpu_to_le16(ctrl);
ata_tf_to_fis(&qc->tf, qc->dev->link->pmp, 1, prb->fis);
if (qc->flags & ATA_QCFLAG_DMAMAP)
sil24_fill_sg(qc, sge);
}
static unsigned int sil24_qc_issue(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct sil24_port_priv *pp = ap->private_data;
void __iomem *port = sil24_port_base(ap);
unsigned int tag = sil24_tag(qc->tag);
dma_addr_t paddr;
void __iomem *activate;
paddr = pp->cmd_block_dma + tag * sizeof(*pp->cmd_block);
activate = port + PORT_CMD_ACTIVATE + tag * 8;
/*
* The barrier is required to ensure that writes to cmd_block reach
* the memory before the write to PORT_CMD_ACTIVATE.
*/
wmb();
writel((u32)paddr, activate);
writel((u64)paddr >> 32, activate + 4);
return 0;
}
static bool sil24_qc_fill_rtf(struct ata_queued_cmd *qc)
{
sil24_read_tf(qc->ap, qc->tag, &qc->result_tf);
return true;
}
static void sil24_pmp_attach(struct ata_port *ap)
{
u32 *gscr = ap->link.device->gscr;
sil24_config_pmp(ap, 1);
sil24_init_port(ap);
if (sata_pmp_gscr_vendor(gscr) == 0x11ab &&
sata_pmp_gscr_devid(gscr) == 0x4140) {
ata_port_info(ap,
"disabling NCQ support due to sil24-mv4140 quirk\n");
ap->flags &= ~ATA_FLAG_NCQ;
}
}
static void sil24_pmp_detach(struct ata_port *ap)
{
sil24_init_port(ap);
sil24_config_pmp(ap, 0);
ap->flags |= ATA_FLAG_NCQ;
}
static int sil24_pmp_hardreset(struct ata_link *link, unsigned int *class,
unsigned long deadline)
{
int rc;
rc = sil24_init_port(link->ap);
if (rc) {
ata_link_err(link, "hardreset failed (port not ready)\n");
return rc;
}
return sata_std_hardreset(link, class, deadline);
}
static void sil24_freeze(struct ata_port *ap)
{
void __iomem *port = sil24_port_base(ap);
/* Port-wide IRQ mask in HOST_CTRL doesn't really work, clear
* PORT_IRQ_ENABLE instead.
*/
writel(0xffff, port + PORT_IRQ_ENABLE_CLR);
}
static void sil24_thaw(struct ata_port *ap)
{
void __iomem *port = sil24_port_base(ap);
u32 tmp;
/* clear IRQ */
tmp = readl(port + PORT_IRQ_STAT);
writel(tmp, port + PORT_IRQ_STAT);
/* turn IRQ back on */
writel(DEF_PORT_IRQ, port + PORT_IRQ_ENABLE_SET);
}
static void sil24_error_intr(struct ata_port *ap)
{
void __iomem *port = sil24_port_base(ap);
struct sil24_port_priv *pp = ap->private_data;
struct ata_queued_cmd *qc = NULL;
struct ata_link *link;
struct ata_eh_info *ehi;
int abort = 0, freeze = 0;
u32 irq_stat;
/* on error, we need to clear IRQ explicitly */
irq_stat = readl(port + PORT_IRQ_STAT);
writel(irq_stat, port + PORT_IRQ_STAT);
/* first, analyze and record host port events */
link = &ap->link;
ehi = &link->eh_info;
ata_ehi_clear_desc(ehi);
ata_ehi_push_desc(ehi, "irq_stat 0x%08x", irq_stat);
if (irq_stat & PORT_IRQ_SDB_NOTIFY) {
ata_ehi_push_desc(ehi, "SDB notify");
sata_async_notification(ap);
}
if (irq_stat & (PORT_IRQ_PHYRDY_CHG | PORT_IRQ_DEV_XCHG)) {
ata_ehi_hotplugged(ehi);
ata_ehi_push_desc(ehi, "%s",
irq_stat & PORT_IRQ_PHYRDY_CHG ?
"PHY RDY changed" : "device exchanged");
freeze = 1;
}
if (irq_stat & PORT_IRQ_UNK_FIS) {
ehi->err_mask |= AC_ERR_HSM;
ehi->action |= ATA_EH_RESET;
ata_ehi_push_desc(ehi, "unknown FIS");
freeze = 1;
}
/* deal with command error */
if (irq_stat & PORT_IRQ_ERROR) {
const struct sil24_cerr_info *ci = NULL;
unsigned int err_mask = 0, action = 0;
u32 context, cerr;
int pmp;
abort = 1;
/* DMA Context Switch Failure in Port Multiplier Mode
* errata. If we have active commands to 3 or more
* devices, any error condition on active devices can
* corrupt DMA context switching.
*/
if (ap->nr_active_links >= 3) {
ehi->err_mask |= AC_ERR_OTHER;
ehi->action |= ATA_EH_RESET;
ata_ehi_push_desc(ehi, "PMP DMA CS errata");
pp->do_port_rst = 1;
freeze = 1;
}
/* find out the offending link and qc */
if (sata_pmp_attached(ap)) {
context = readl(port + PORT_CONTEXT);
pmp = (context >> 5) & 0xf;
if (pmp < ap->nr_pmp_links) {
link = &ap->pmp_link[pmp];
ehi = &link->eh_info;
qc = ata_qc_from_tag(ap, link->active_tag);
ata_ehi_clear_desc(ehi);
ata_ehi_push_desc(ehi, "irq_stat 0x%08x",
irq_stat);
} else {
err_mask |= AC_ERR_HSM;
action |= ATA_EH_RESET;
freeze = 1;
}
} else
qc = ata_qc_from_tag(ap, link->active_tag);
/* analyze CMD_ERR */
cerr = readl(port + PORT_CMD_ERR);
if (cerr < ARRAY_SIZE(sil24_cerr_db))
ci = &sil24_cerr_db[cerr];
if (ci && ci->desc) {
err_mask |= ci->err_mask;
action |= ci->action;
if (action & ATA_EH_RESET)
freeze = 1;
ata_ehi_push_desc(ehi, "%s", ci->desc);
} else {
err_mask |= AC_ERR_OTHER;
action |= ATA_EH_RESET;
freeze = 1;
ata_ehi_push_desc(ehi, "unknown command error %d",
cerr);
}
/* record error info */
if (qc)
qc->err_mask |= err_mask;
else
ehi->err_mask |= err_mask;
ehi->action |= action;
/* if PMP, resume */
if (sata_pmp_attached(ap))
writel(PORT_CS_PMP_RESUME, port + PORT_CTRL_STAT);
}
/* freeze or abort */
if (freeze)
ata_port_freeze(ap);
else if (abort) {
if (qc)
ata_link_abort(qc->dev->link);
else
ata_port_abort(ap);
}
}
static inline void sil24_host_intr(struct ata_port *ap)
{
void __iomem *port = sil24_port_base(ap);
u32 slot_stat, qc_active;
int rc;
/* If PCIX_IRQ_WOC, there's an inherent race window between
* clearing IRQ pending status and reading PORT_SLOT_STAT
* which may cause spurious interrupts afterwards. This is
* unavoidable and much better than losing interrupts which
* happens if IRQ pending is cleared after reading
* PORT_SLOT_STAT.
*/
if (ap->flags & SIL24_FLAG_PCIX_IRQ_WOC)
writel(PORT_IRQ_COMPLETE, port + PORT_IRQ_STAT);
slot_stat = readl(port + PORT_SLOT_STAT);
if (unlikely(slot_stat & HOST_SSTAT_ATTN)) {
sil24_error_intr(ap);
return;
}
qc_active = slot_stat & ~HOST_SSTAT_ATTN;
rc = ata_qc_complete_multiple(ap, qc_active);
if (rc > 0)
return;
if (rc < 0) {
struct ata_eh_info *ehi = &ap->link.eh_info;
ehi->err_mask |= AC_ERR_HSM;
ehi->action |= ATA_EH_RESET;
ata_port_freeze(ap);
return;
}
/* spurious interrupts are expected if PCIX_IRQ_WOC */
if (!(ap->flags & SIL24_FLAG_PCIX_IRQ_WOC) && ata_ratelimit())
ata_port_info(ap,
"spurious interrupt (slot_stat 0x%x active_tag %d sactive 0x%x)\n",
slot_stat, ap->link.active_tag, ap->link.sactive);
}
static irqreturn_t sil24_interrupt(int irq, void *dev_instance)
{
struct ata_host *host = dev_instance;
void __iomem *host_base = host->iomap[SIL24_HOST_BAR];
unsigned handled = 0;
u32 status;
int i;
status = readl(host_base + HOST_IRQ_STAT);
if (status == 0xffffffff) {
printk(KERN_ERR DRV_NAME ": IRQ status == 0xffffffff, "
"PCI fault or device removal?\n");
goto out;
}
if (!(status & IRQ_STAT_4PORTS))
goto out;
spin_lock(&host->lock);
for (i = 0; i < host->n_ports; i++)
if (status & (1 << i)) {
sil24_host_intr(host->ports[i]);
handled++;
}
spin_unlock(&host->lock);
out:
return IRQ_RETVAL(handled);
}
static void sil24_error_handler(struct ata_port *ap)
{
struct sil24_port_priv *pp = ap->private_data;
if (sil24_init_port(ap))
ata_eh_freeze_port(ap);
sata_pmp_error_handler(ap);
pp->do_port_rst = 0;
}
static void sil24_post_internal_cmd(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
/* make DMA engine forget about the failed command */
if ((qc->flags & ATA_QCFLAG_FAILED) && sil24_init_port(ap))
ata_eh_freeze_port(ap);
}
static int sil24_port_start(struct ata_port *ap)
{
struct device *dev = ap->host->dev;
struct sil24_port_priv *pp;
union sil24_cmd_block *cb;
size_t cb_size = sizeof(*cb) * SIL24_MAX_CMDS;
dma_addr_t cb_dma;
pp = devm_kzalloc(dev, sizeof(*pp), GFP_KERNEL);
if (!pp)
return -ENOMEM;
cb = dmam_alloc_coherent(dev, cb_size, &cb_dma, GFP_KERNEL);
if (!cb)
return -ENOMEM;
memset(cb, 0, cb_size);
pp->cmd_block = cb;
pp->cmd_block_dma = cb_dma;
ap->private_data = pp;
ata_port_pbar_desc(ap, SIL24_HOST_BAR, -1, "host");
ata_port_pbar_desc(ap, SIL24_PORT_BAR, sil24_port_offset(ap), "port");
return 0;
}
static void sil24_init_controller(struct ata_host *host)
{
void __iomem *host_base = host->iomap[SIL24_HOST_BAR];
u32 tmp;
int i;
/* GPIO off */
writel(0, host_base + HOST_FLASH_CMD);
/* clear global reset & mask interrupts during initialization */
writel(0, host_base + HOST_CTRL);
/* init ports */
for (i = 0; i < host->n_ports; i++) {
struct ata_port *ap = host->ports[i];
void __iomem *port = sil24_port_base(ap);
/* Initial PHY setting */
writel(0x20c, port + PORT_PHY_CFG);
/* Clear port RST */
tmp = readl(port + PORT_CTRL_STAT);
if (tmp & PORT_CS_PORT_RST) {
writel(PORT_CS_PORT_RST, port + PORT_CTRL_CLR);
tmp = ata_wait_register(NULL, port + PORT_CTRL_STAT,
PORT_CS_PORT_RST,
PORT_CS_PORT_RST, 10, 100);
if (tmp & PORT_CS_PORT_RST)
dev_err(host->dev,
"failed to clear port RST\n");
}
/* configure port */
sil24_config_port(ap);
}
/* Turn on interrupts */
writel(IRQ_STAT_4PORTS, host_base + HOST_CTRL);
}
static int sil24_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
{
extern int __MARKER__sil24_cmd_block_is_sized_wrongly;
struct ata_port_info pi = sil24_port_info[ent->driver_data];
const struct ata_port_info *ppi[] = { &pi, NULL };
void __iomem * const *iomap;
struct ata_host *host;
int rc;
u32 tmp;
/* cause link error if sil24_cmd_block is sized wrongly */
if (sizeof(union sil24_cmd_block) != PAGE_SIZE)
__MARKER__sil24_cmd_block_is_sized_wrongly = 1;
ata_print_version_once(&pdev->dev, DRV_VERSION);
/* acquire resources */
rc = pcim_enable_device(pdev);
if (rc)
return rc;
rc = pcim_iomap_regions(pdev,
(1 << SIL24_HOST_BAR) | (1 << SIL24_PORT_BAR),
DRV_NAME);
if (rc)
return rc;
iomap = pcim_iomap_table(pdev);
/* apply workaround for completion IRQ loss on PCI-X errata */
if (pi.flags & SIL24_FLAG_PCIX_IRQ_WOC) {
tmp = readl(iomap[SIL24_HOST_BAR] + HOST_CTRL);
if (tmp & (HOST_CTRL_TRDY | HOST_CTRL_STOP | HOST_CTRL_DEVSEL))
dev_info(&pdev->dev,
"Applying completion IRQ loss on PCI-X errata fix\n");
else
pi.flags &= ~SIL24_FLAG_PCIX_IRQ_WOC;
}
/* allocate and fill host */
host = ata_host_alloc_pinfo(&pdev->dev, ppi,
SIL24_FLAG2NPORTS(ppi[0]->flags));
if (!host)
return -ENOMEM;
host->iomap = iomap;
/* configure and activate the device */
if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) {
rc = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
if (rc) {
rc = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
if (rc) {
dev_err(&pdev->dev,
"64-bit DMA enable failed\n");
return rc;
}
}
} else {
rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (rc) {
dev_err(&pdev->dev, "32-bit DMA enable failed\n");
return rc;
}
rc = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
if (rc) {
dev_err(&pdev->dev,
"32-bit consistent DMA enable failed\n");
return rc;
}
}
/* Set max read request size to 4096. This slightly increases
* write throughput for pci-e variants.
*/
pcie_set_readrq(pdev, 4096);
sil24_init_controller(host);
if (sata_sil24_msi && !pci_enable_msi(pdev)) {
dev_info(&pdev->dev, "Using MSI\n");
pci_intx(pdev, 0);
}
pci_set_master(pdev);
return ata_host_activate(host, pdev->irq, sil24_interrupt, IRQF_SHARED,
&sil24_sht);
}
#ifdef CONFIG_PM
static int sil24_pci_device_resume(struct pci_dev *pdev)
{
struct ata_host *host = dev_get_drvdata(&pdev->dev);
void __iomem *host_base = host->iomap[SIL24_HOST_BAR];
int rc;
rc = ata_pci_device_do_resume(pdev);
if (rc)
return rc;
if (pdev->dev.power.power_state.event == PM_EVENT_SUSPEND)
writel(HOST_CTRL_GLOBAL_RST, host_base + HOST_CTRL);
sil24_init_controller(host);
ata_host_resume(host);
return 0;
}
static int sil24_port_resume(struct ata_port *ap)
{
sil24_config_pmp(ap, ap->nr_pmp_links);
return 0;
}
#endif
module_pci_driver(sil24_pci_driver);
MODULE_AUTHOR("Tejun Heo");
MODULE_DESCRIPTION("Silicon Image 3124/3132 SATA low-level driver");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, sil24_pci_tbl);
| gpl-2.0 |
abhishekr700/Nemesis_Kernel | net/802/fc.c | 3017 | 3366 | /*
* NET3: Fibre Channel device handling subroutines
*
* 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.
*
* Vineet Abraham <vma@iol.unh.edu>
* v 1.0 03/22/99
*/
#include <asm/uaccess.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/fcdevice.h>
#include <linux/skbuff.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <linux/net.h>
#include <linux/proc_fs.h>
#include <linux/init.h>
#include <linux/export.h>
#include <net/arp.h>
/*
* Put the headers on a Fibre Channel packet.
*/
static int fc_header(struct sk_buff *skb, struct net_device *dev,
unsigned short type,
const void *daddr, const void *saddr, unsigned int len)
{
struct fch_hdr *fch;
int hdr_len;
/*
* Add the 802.2 SNAP header if IP as the IPv4 code calls
* dev->hard_header directly.
*/
if (type == ETH_P_IP || type == ETH_P_ARP)
{
struct fcllc *fcllc;
hdr_len = sizeof(struct fch_hdr) + sizeof(struct fcllc);
fch = (struct fch_hdr *)skb_push(skb, hdr_len);
fcllc = (struct fcllc *)(fch+1);
fcllc->dsap = fcllc->ssap = EXTENDED_SAP;
fcllc->llc = UI_CMD;
fcllc->protid[0] = fcllc->protid[1] = fcllc->protid[2] = 0x00;
fcllc->ethertype = htons(type);
}
else
{
hdr_len = sizeof(struct fch_hdr);
fch = (struct fch_hdr *)skb_push(skb, hdr_len);
}
if(saddr)
memcpy(fch->saddr,saddr,dev->addr_len);
else
memcpy(fch->saddr,dev->dev_addr,dev->addr_len);
if(daddr)
{
memcpy(fch->daddr,daddr,dev->addr_len);
return hdr_len;
}
return -hdr_len;
}
/*
* A neighbour discovery of some species (eg arp) has completed. We
* can now send the packet.
*/
static int fc_rebuild_header(struct sk_buff *skb)
{
#ifdef CONFIG_INET
struct fch_hdr *fch=(struct fch_hdr *)skb->data;
struct fcllc *fcllc=(struct fcllc *)(skb->data+sizeof(struct fch_hdr));
if(fcllc->ethertype != htons(ETH_P_IP)) {
printk("fc_rebuild_header: Don't know how to resolve type %04X addresses ?\n", ntohs(fcllc->ethertype));
return 0;
}
return arp_find(fch->daddr, skb);
#else
return 0;
#endif
}
static const struct header_ops fc_header_ops = {
.create = fc_header,
.rebuild = fc_rebuild_header,
};
static void fc_setup(struct net_device *dev)
{
dev->header_ops = &fc_header_ops;
dev->type = ARPHRD_IEEE802;
dev->hard_header_len = FC_HLEN;
dev->mtu = 2024;
dev->addr_len = FC_ALEN;
dev->tx_queue_len = 100; /* Long queues on fc */
dev->flags = IFF_BROADCAST;
memset(dev->broadcast, 0xFF, FC_ALEN);
}
/**
* alloc_fcdev - Register fibre channel device
* @sizeof_priv: Size of additional driver-private structure to be allocated
* for this fibre channel device
*
* Fill in the fields of the device structure with fibre channel-generic values.
*
* Constructs a new net device, complete with a private data area of
* size @sizeof_priv. A 32-byte (not bit) alignment is enforced for
* this private data area.
*/
struct net_device *alloc_fcdev(int sizeof_priv)
{
return alloc_netdev(sizeof_priv, "fc%d", fc_setup);
}
EXPORT_SYMBOL(alloc_fcdev);
| gpl-2.0 |
bigzz/linux-linaro-lsk | drivers/pinctrl/pinctrl-ab8505.c | 3529 | 17150 | /*
* Copyright (C) ST-Ericsson SA 2012
*
* Author: Patrice Chotard <patrice.chotard@stericsson.com> for ST-Ericsson.
*
* 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/gpio.h>
#include <linux/pinctrl/pinctrl.h>
#include <linux/mfd/abx500/ab8500.h>
#include "pinctrl-abx500.h"
/* All the pins that can be used for GPIO and some other functions */
#define ABX500_GPIO(offset) (offset)
#define AB8505_PIN_N4 ABX500_GPIO(1)
#define AB8505_PIN_R5 ABX500_GPIO(2)
#define AB8505_PIN_P5 ABX500_GPIO(3)
/* hole */
#define AB8505_PIN_B16 ABX500_GPIO(10)
#define AB8505_PIN_B17 ABX500_GPIO(11)
/* hole */
#define AB8505_PIN_D17 ABX500_GPIO(13)
#define AB8505_PIN_C16 ABX500_GPIO(14)
/* hole */
#define AB8505_PIN_P2 ABX500_GPIO(17)
#define AB8505_PIN_N3 ABX500_GPIO(18)
#define AB8505_PIN_T1 ABX500_GPIO(19)
#define AB8505_PIN_P3 ABX500_GPIO(20)
/* hole */
#define AB8505_PIN_H14 ABX500_GPIO(34)
/* hole */
#define AB8505_PIN_J15 ABX500_GPIO(40)
#define AB8505_PIN_J14 ABX500_GPIO(41)
/* hole */
#define AB8505_PIN_L4 ABX500_GPIO(50)
/* hole */
#define AB8505_PIN_D16 ABX500_GPIO(52)
#define AB8505_PIN_D15 ABX500_GPIO(53)
/* indicates the higher GPIO number */
#define AB8505_GPIO_MAX_NUMBER 53
/*
* The names of the pins are denoted by GPIO number and ball name, even
* though they can be used for other things than GPIO, this is the first
* column in the table of the data sheet and often used on schematics and
* such.
*/
static const struct pinctrl_pin_desc ab8505_pins[] = {
PINCTRL_PIN(AB8505_PIN_N4, "GPIO1_N4"),
PINCTRL_PIN(AB8505_PIN_R5, "GPIO2_R5"),
PINCTRL_PIN(AB8505_PIN_P5, "GPIO3_P5"),
/* hole */
PINCTRL_PIN(AB8505_PIN_B16, "GPIO10_B16"),
PINCTRL_PIN(AB8505_PIN_B17, "GPIO11_B17"),
/* hole */
PINCTRL_PIN(AB8505_PIN_D17, "GPIO13_D17"),
PINCTRL_PIN(AB8505_PIN_C16, "GPIO14_C16"),
/* hole */
PINCTRL_PIN(AB8505_PIN_P2, "GPIO17_P2"),
PINCTRL_PIN(AB8505_PIN_N3, "GPIO18_N3"),
PINCTRL_PIN(AB8505_PIN_T1, "GPIO19_T1"),
PINCTRL_PIN(AB8505_PIN_P3, "GPIO20_P3"),
/* hole */
PINCTRL_PIN(AB8505_PIN_H14, "GPIO34_H14"),
/* hole */
PINCTRL_PIN(AB8505_PIN_J15, "GPIO40_J15"),
PINCTRL_PIN(AB8505_PIN_J14, "GPIO41_J14"),
/* hole */
PINCTRL_PIN(AB8505_PIN_L4, "GPIO50_L4"),
/* hole */
PINCTRL_PIN(AB8505_PIN_D16, "GPIO52_D16"),
PINCTRL_PIN(AB8505_PIN_D15, "GPIO53_D15"),
};
/*
* Maps local GPIO offsets to local pin numbers
*/
static const struct abx500_pinrange ab8505_pinranges[] = {
ABX500_PINRANGE(1, 3, ABX500_ALT_A),
ABX500_PINRANGE(10, 2, ABX500_DEFAULT),
ABX500_PINRANGE(13, 1, ABX500_DEFAULT),
ABX500_PINRANGE(14, 1, ABX500_ALT_A),
ABX500_PINRANGE(17, 4, ABX500_ALT_A),
ABX500_PINRANGE(34, 1, ABX500_ALT_A),
ABX500_PINRANGE(40, 2, ABX500_ALT_A),
ABX500_PINRANGE(50, 1, ABX500_DEFAULT),
ABX500_PINRANGE(52, 2, ABX500_ALT_A),
};
/*
* Read the pin group names like this:
* sysclkreq2_d_1 = first groups of pins for sysclkreq2 on default function
*
* The groups are arranged as sets per altfunction column, so we can
* mux in one group at a time by selecting the same altfunction for them
* all. When functions require pins on different altfunctions, you need
* to combine several groups.
*/
/* default column */
static const unsigned sysclkreq2_d_1_pins[] = { AB8505_PIN_N4 };
static const unsigned sysclkreq3_d_1_pins[] = { AB8505_PIN_R5 };
static const unsigned sysclkreq4_d_1_pins[] = { AB8505_PIN_P5 };
static const unsigned gpio10_d_1_pins[] = { AB8505_PIN_B16 };
static const unsigned gpio11_d_1_pins[] = { AB8505_PIN_B17 };
static const unsigned gpio13_d_1_pins[] = { AB8505_PIN_D17 };
static const unsigned pwmout1_d_1_pins[] = { AB8505_PIN_C16 };
/* audio data interface 2*/
static const unsigned adi2_d_1_pins[] = { AB8505_PIN_P2, AB8505_PIN_N3,
AB8505_PIN_T1, AB8505_PIN_P3 };
static const unsigned extcpena_d_1_pins[] = { AB8505_PIN_H14 };
/* modem SDA/SCL */
static const unsigned modsclsda_d_1_pins[] = { AB8505_PIN_J15, AB8505_PIN_J14 };
static const unsigned gpio50_d_1_pins[] = { AB8505_PIN_L4 };
static const unsigned resethw_d_1_pins[] = { AB8505_PIN_D16 };
static const unsigned service_d_1_pins[] = { AB8505_PIN_D15 };
/* Altfunction A column */
static const unsigned gpio1_a_1_pins[] = { AB8505_PIN_N4 };
static const unsigned gpio2_a_1_pins[] = { AB8505_PIN_R5 };
static const unsigned gpio3_a_1_pins[] = { AB8505_PIN_P5 };
static const unsigned hiqclkena_a_1_pins[] = { AB8505_PIN_B16 };
static const unsigned pdmclk_a_1_pins[] = { AB8505_PIN_B17 };
static const unsigned uarttxdata_a_1_pins[] = { AB8505_PIN_D17 };
static const unsigned gpio14_a_1_pins[] = { AB8505_PIN_C16 };
static const unsigned gpio17_a_1_pins[] = { AB8505_PIN_P2 };
static const unsigned gpio18_a_1_pins[] = { AB8505_PIN_N3 };
static const unsigned gpio19_a_1_pins[] = { AB8505_PIN_T1 };
static const unsigned gpio20_a_1_pins[] = { AB8505_PIN_P3 };
static const unsigned gpio34_a_1_pins[] = { AB8505_PIN_H14 };
static const unsigned gpio40_a_1_pins[] = { AB8505_PIN_J15 };
static const unsigned gpio41_a_1_pins[] = { AB8505_PIN_J14 };
static const unsigned uartrxdata_a_1_pins[] = { AB8505_PIN_J14 };
static const unsigned gpio50_a_1_pins[] = { AB8505_PIN_L4 };
static const unsigned gpio52_a_1_pins[] = { AB8505_PIN_D16 };
static const unsigned gpio53_a_1_pins[] = { AB8505_PIN_D15 };
/* Altfunction B colum */
static const unsigned pdmdata_b_1_pins[] = { AB8505_PIN_B16 };
static const unsigned extvibrapwm1_b_1_pins[] = { AB8505_PIN_D17 };
static const unsigned extvibrapwm2_b_1_pins[] = { AB8505_PIN_L4 };
/* Altfunction C column */
static const unsigned usbvdat_c_1_pins[] = { AB8505_PIN_D17 };
#define AB8505_PIN_GROUP(a, b) { .name = #a, .pins = a##_pins, \
.npins = ARRAY_SIZE(a##_pins), .altsetting = b }
static const struct abx500_pingroup ab8505_groups[] = {
AB8505_PIN_GROUP(sysclkreq2_d_1, ABX500_DEFAULT),
AB8505_PIN_GROUP(sysclkreq3_d_1, ABX500_DEFAULT),
AB8505_PIN_GROUP(sysclkreq4_d_1, ABX500_DEFAULT),
AB8505_PIN_GROUP(gpio10_d_1, ABX500_DEFAULT),
AB8505_PIN_GROUP(gpio11_d_1, ABX500_DEFAULT),
AB8505_PIN_GROUP(gpio13_d_1, ABX500_DEFAULT),
AB8505_PIN_GROUP(pwmout1_d_1, ABX500_DEFAULT),
AB8505_PIN_GROUP(adi2_d_1, ABX500_DEFAULT),
AB8505_PIN_GROUP(extcpena_d_1, ABX500_DEFAULT),
AB8505_PIN_GROUP(modsclsda_d_1, ABX500_DEFAULT),
AB8505_PIN_GROUP(gpio50_d_1, ABX500_DEFAULT),
AB8505_PIN_GROUP(resethw_d_1, ABX500_DEFAULT),
AB8505_PIN_GROUP(service_d_1, ABX500_DEFAULT),
AB8505_PIN_GROUP(gpio1_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(gpio2_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(gpio3_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(hiqclkena_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(pdmclk_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(uarttxdata_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(gpio14_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(gpio17_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(gpio18_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(gpio19_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(gpio20_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(gpio34_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(gpio40_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(gpio41_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(uartrxdata_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(gpio52_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(gpio53_a_1, ABX500_ALT_A),
AB8505_PIN_GROUP(pdmdata_b_1, ABX500_ALT_B),
AB8505_PIN_GROUP(extvibrapwm1_b_1, ABX500_ALT_B),
AB8505_PIN_GROUP(extvibrapwm2_b_1, ABX500_ALT_B),
AB8505_PIN_GROUP(usbvdat_c_1, ABX500_ALT_C),
};
/* We use this macro to define the groups applicable to a function */
#define AB8505_FUNC_GROUPS(a, b...) \
static const char * const a##_groups[] = { b };
AB8505_FUNC_GROUPS(sysclkreq, "sysclkreq2_d_1", "sysclkreq3_d_1",
"sysclkreq4_d_1");
AB8505_FUNC_GROUPS(gpio, "gpio1_a_1", "gpio2_a_1", "gpio3_a_1",
"gpio10_d_1", "gpio11_d_1", "gpio13_d_1", "gpio14_a_1",
"gpio17_a_1", "gpio18_a_1", "gpio19_a_1", "gpio20_a_1",
"gpio34_a_1", "gpio40_a_1", "gpio41_a_1", "gpio50_d_1",
"gpio52_a_1", "gpio53_a_1");
AB8505_FUNC_GROUPS(pwmout, "pwmout1_d_1");
AB8505_FUNC_GROUPS(adi2, "adi2_d_1");
AB8505_FUNC_GROUPS(extcpena, "extcpena_d_1");
AB8505_FUNC_GROUPS(modsclsda, "modsclsda_d_1");
AB8505_FUNC_GROUPS(resethw, "resethw_d_1");
AB8505_FUNC_GROUPS(service, "service_d_1");
AB8505_FUNC_GROUPS(hiqclkena, "hiqclkena_a_1");
AB8505_FUNC_GROUPS(pdm, "pdmclk_a_1", "pdmdata_b_1");
AB8505_FUNC_GROUPS(uartdata, "uarttxdata_a_1", "uartrxdata_a_1");
AB8505_FUNC_GROUPS(extvibra, "extvibrapwm1_b_1", "extvibrapwm2_b_1");
AB8505_FUNC_GROUPS(usbvdat, "usbvdat_c_1");
#define FUNCTION(fname) \
{ \
.name = #fname, \
.groups = fname##_groups, \
.ngroups = ARRAY_SIZE(fname##_groups), \
}
static const struct abx500_function ab8505_functions[] = {
FUNCTION(sysclkreq),
FUNCTION(gpio),
FUNCTION(pwmout),
FUNCTION(adi2),
FUNCTION(extcpena),
FUNCTION(modsclsda),
FUNCTION(resethw),
FUNCTION(service),
FUNCTION(hiqclkena),
FUNCTION(pdm),
FUNCTION(uartdata),
FUNCTION(extvibra),
FUNCTION(extvibra),
FUNCTION(usbvdat),
};
/*
* this table translates what's is in the AB8505 specification regarding the
* balls alternate functions (as for DB, default, ALT_A, ALT_B and ALT_C).
* ALTERNATE_FUNCTIONS(GPIO_NUMBER, GPIOSEL bit, ALTERNATFUNC bit1,
* ALTERNATEFUNC bit2, ALTA val, ALTB val, ALTC val),
*
* example :
*
* ALTERNATE_FUNCTIONS(13, 4, 3, 4, 1, 0, 2),
* means that pin AB8505_PIN_D18 (pin 13) supports 4 mux (default/ALT_A,
* ALT_B and ALT_C), so GPIOSEL and ALTERNATFUNC registers are used to
* select the mux. ALTA, ALTB and ALTC val indicates values to write in
* ALTERNATFUNC register. We need to specifies these values as SOC
* designers didn't apply the same logic on how to select mux in the
* ABx500 family.
*
* As this pins supports at least ALT_B mux, default mux is
* selected by writing 1 in GPIOSEL bit :
*
* | GPIOSEL bit=4 | alternatfunc bit2=4 | alternatfunc bit1=3
* default | 1 | 0 | 0
* alt_A | 0 | 0 | 1
* alt_B | 0 | 0 | 0
* alt_C | 0 | 1 | 0
*
* ALTERNATE_FUNCTIONS(1, 0, UNUSED, UNUSED),
* means that pin AB9540_PIN_R4 (pin 1) supports 2 mux, so only GPIOSEL
* register is used to select the mux. As this pins doesn't support at
* least ALT_B mux, default mux is by writing 0 in GPIOSEL bit :
*
* | GPIOSEL bit=0 | alternatfunc bit2= | alternatfunc bit1=
* default | 0 | 0 | 0
* alt_A | 1 | 0 | 0
*/
static struct
alternate_functions ab8505_alternate_functions[AB8505_GPIO_MAX_NUMBER + 1] = {
ALTERNATE_FUNCTIONS(0, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO0 */
ALTERNATE_FUNCTIONS(1, 0, UNUSED, UNUSED, 0, 0, 0), /* GPIO1, altA controlled by bit 0 */
ALTERNATE_FUNCTIONS(2, 1, UNUSED, UNUSED, 0, 0, 0), /* GPIO2, altA controlled by bit 1 */
ALTERNATE_FUNCTIONS(3, 2, UNUSED, UNUSED, 0, 0, 0), /* GPIO3, altA controlled by bit 2*/
ALTERNATE_FUNCTIONS(4, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO4, bit 3 reserved */
ALTERNATE_FUNCTIONS(5, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO5, bit 4 reserved */
ALTERNATE_FUNCTIONS(6, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO6, bit 5 reserved */
ALTERNATE_FUNCTIONS(7, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO7, bit 6 reserved */
ALTERNATE_FUNCTIONS(8, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO8, bit 7 reserved */
ALTERNATE_FUNCTIONS(9, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO9, bit 0 reserved */
ALTERNATE_FUNCTIONS(10, 1, 0, UNUSED, 1, 0, 0), /* GPIO10, altA and altB controlled by bit 0 */
ALTERNATE_FUNCTIONS(11, 2, 1, UNUSED, 0, 0, 0), /* GPIO11, altA controlled by bit 2 */
ALTERNATE_FUNCTIONS(12, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO12, bit3 reseved */
ALTERNATE_FUNCTIONS(13, 4, 3, 4, 1, 0, 2), /* GPIO13, altA altB and altC controlled by bit 3 and 4 */
ALTERNATE_FUNCTIONS(14, 5, UNUSED, UNUSED, 0, 0, 0), /* GPIO14, altA controlled by bit 5 */
ALTERNATE_FUNCTIONS(15, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO15, bit 6 reserved */
ALTERNATE_FUNCTIONS(16, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO15, bit 7 reserved */
/*
* pins 17 to 20 are special case, only bit 0 is used to select
* alternate function for these 4 pins.
* bits 1 to 3 are reserved
*/
ALTERNATE_FUNCTIONS(17, 0, UNUSED, UNUSED, 0, 0, 0), /* GPIO17, altA controlled by bit 0 */
ALTERNATE_FUNCTIONS(18, 0, UNUSED, UNUSED, 0, 0, 0), /* GPIO18, altA controlled by bit 0 */
ALTERNATE_FUNCTIONS(19, 0, UNUSED, UNUSED, 0, 0, 0), /* GPIO19, altA controlled by bit 0 */
ALTERNATE_FUNCTIONS(20, 0, UNUSED, UNUSED, 0, 0, 0), /* GPIO20, altA controlled by bit 0 */
ALTERNATE_FUNCTIONS(21, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO21, bit 4 reserved */
ALTERNATE_FUNCTIONS(22, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO22, bit 5 reserved */
ALTERNATE_FUNCTIONS(23, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO23, bit 6 reserved */
ALTERNATE_FUNCTIONS(24, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO24, bit 7 reserved */
ALTERNATE_FUNCTIONS(25, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO25, bit 0 reserved */
ALTERNATE_FUNCTIONS(26, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO26, bit 1 reserved */
ALTERNATE_FUNCTIONS(27, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO27, bit 2 reserved */
ALTERNATE_FUNCTIONS(28, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO28, bit 3 reserved */
ALTERNATE_FUNCTIONS(29, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO29, bit 4 reserved */
ALTERNATE_FUNCTIONS(30, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO30, bit 5 reserved */
ALTERNATE_FUNCTIONS(31, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO31, bit 6 reserved */
ALTERNATE_FUNCTIONS(32, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO32, bit 7 reserved */
ALTERNATE_FUNCTIONS(33, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO33, bit 0 reserved */
ALTERNATE_FUNCTIONS(34, 1, UNUSED, UNUSED, 0, 0, 0), /* GPIO34, altA controlled by bit 1 */
ALTERNATE_FUNCTIONS(35, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO35, bit 2 reserved */
ALTERNATE_FUNCTIONS(36, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO36, bit 2 reserved */
ALTERNATE_FUNCTIONS(37, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO37, bit 2 reserved */
ALTERNATE_FUNCTIONS(38, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO38, bit 2 reserved */
ALTERNATE_FUNCTIONS(39, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO39, bit 2 reserved */
ALTERNATE_FUNCTIONS(40, 7, UNUSED, UNUSED, 0, 0, 0), /* GPIO40, altA controlled by bit 7*/
ALTERNATE_FUNCTIONS(41, 0, UNUSED, UNUSED, 0, 0, 0), /* GPIO41, altA controlled by bit 0 */
ALTERNATE_FUNCTIONS(42, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO42, bit 1 reserved */
ALTERNATE_FUNCTIONS(43, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO43, bit 2 reserved */
ALTERNATE_FUNCTIONS(44, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO44, bit 3 reserved */
ALTERNATE_FUNCTIONS(45, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO45, bit 4 reserved */
ALTERNATE_FUNCTIONS(46, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO46, bit 5 reserved */
ALTERNATE_FUNCTIONS(47, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO47, bit 6 reserved */
ALTERNATE_FUNCTIONS(48, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO48, bit 7 reserved */
ALTERNATE_FUNCTIONS(49, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO49, bit 0 reserved */
ALTERNATE_FUNCTIONS(50, 1, 2, UNUSED, 1, 0, 0), /* GPIO50, altA controlled by bit 1 */
ALTERNATE_FUNCTIONS(51, UNUSED, UNUSED, UNUSED, 0, 0, 0), /* no GPIO49, bit 0 reserved */
ALTERNATE_FUNCTIONS(52, 3, UNUSED, UNUSED, 0, 0, 0), /* GPIO52, altA controlled by bit 3 */
ALTERNATE_FUNCTIONS(53, 4, UNUSED, UNUSED, 0, 0, 0), /* GPIO53, altA controlled by bit 4 */
};
/*
* For AB8505 Only some GPIOs are interrupt capable, and they are
* organized in discontiguous clusters:
*
* GPIO10 to GPIO11
* GPIO13
* GPIO40 and GPIO41
* GPIO50
* GPIO52 to GPIO53
*/
static struct abx500_gpio_irq_cluster ab8505_gpio_irq_cluster[] = {
GPIO_IRQ_CLUSTER(10, 11, AB8500_INT_GPIO10R),
GPIO_IRQ_CLUSTER(13, 13, AB8500_INT_GPIO13R),
GPIO_IRQ_CLUSTER(40, 41, AB8500_INT_GPIO40R),
GPIO_IRQ_CLUSTER(50, 50, AB9540_INT_GPIO50R),
GPIO_IRQ_CLUSTER(52, 53, AB9540_INT_GPIO52R),
};
static struct abx500_pinctrl_soc_data ab8505_soc = {
.gpio_ranges = ab8505_pinranges,
.gpio_num_ranges = ARRAY_SIZE(ab8505_pinranges),
.pins = ab8505_pins,
.npins = ARRAY_SIZE(ab8505_pins),
.functions = ab8505_functions,
.nfunctions = ARRAY_SIZE(ab8505_functions),
.groups = ab8505_groups,
.ngroups = ARRAY_SIZE(ab8505_groups),
.alternate_functions = ab8505_alternate_functions,
.gpio_irq_cluster = ab8505_gpio_irq_cluster,
.ngpio_irq_cluster = ARRAY_SIZE(ab8505_gpio_irq_cluster),
.irq_gpio_rising_offset = AB8500_INT_GPIO6R,
.irq_gpio_falling_offset = AB8500_INT_GPIO6F,
.irq_gpio_factor = 1,
};
void
abx500_pinctrl_ab8505_init(struct abx500_pinctrl_soc_data **soc)
{
*soc = &ab8505_soc;
}
| gpl-2.0 |
motley-git/Kernel-Nexus7 | arch/sh/kernel/cpu/sh5/clock-sh5.c | 4041 | 1860 | /*
* arch/sh/kernel/cpu/sh5/clock-sh5.c
*
* SH-5 support for the clock framework
*
* Copyright (C) 2008 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <asm/clock.h>
#include <asm/io.h>
static int ifc_table[] = { 2, 4, 6, 8, 10, 12, 16, 24 };
/* Clock, Power and Reset Controller */
#define CPRC_BLOCK_OFF 0x01010000
#define CPRC_BASE (PHYS_PERIPHERAL_BLOCK + CPRC_BLOCK_OFF)
static unsigned long cprc_base;
static void master_clk_init(struct clk *clk)
{
int idx = (__raw_readl(cprc_base + 0x00) >> 6) & 0x0007;
clk->rate *= ifc_table[idx];
}
static struct clk_ops sh5_master_clk_ops = {
.init = master_clk_init,
};
static unsigned long module_clk_recalc(struct clk *clk)
{
int idx = (__raw_readw(cprc_base) >> 12) & 0x0007;
return clk->parent->rate / ifc_table[idx];
}
static struct clk_ops sh5_module_clk_ops = {
.recalc = module_clk_recalc,
};
static unsigned long bus_clk_recalc(struct clk *clk)
{
int idx = (__raw_readw(cprc_base) >> 3) & 0x0007;
return clk->parent->rate / ifc_table[idx];
}
static struct clk_ops sh5_bus_clk_ops = {
.recalc = bus_clk_recalc,
};
static unsigned long cpu_clk_recalc(struct clk *clk)
{
int idx = (__raw_readw(cprc_base) & 0x0007);
return clk->parent->rate / ifc_table[idx];
}
static struct clk_ops sh5_cpu_clk_ops = {
.recalc = cpu_clk_recalc,
};
static struct clk_ops *sh5_clk_ops[] = {
&sh5_master_clk_ops,
&sh5_module_clk_ops,
&sh5_bus_clk_ops,
&sh5_cpu_clk_ops,
};
void __init arch_init_clk_ops(struct clk_ops **ops, int idx)
{
cprc_base = (unsigned long)ioremap_nocache(CPRC_BASE, 1024);
BUG_ON(!cprc_base);
if (idx < ARRAY_SIZE(sh5_clk_ops))
*ops = sh5_clk_ops[idx];
}
| gpl-2.0 |
4u2ore/memul-aurora | drivers/input/keyboard/samsung-keypad.c | 4809 | 17561 | /*
* Samsung keypad driver
*
* Copyright (C) 2010 Samsung Electronics Co.Ltd
* Author: Joonyoung Shim <jy0922.shim@samsung.com>
* Author: Donghwa Lee <dh09.lee@samsung.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pm.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h>
#include <linux/of.h>
#include <linux/of_gpio.h>
#include <linux/sched.h>
#include <linux/input/samsung-keypad.h>
#define SAMSUNG_KEYIFCON 0x00
#define SAMSUNG_KEYIFSTSCLR 0x04
#define SAMSUNG_KEYIFCOL 0x08
#define SAMSUNG_KEYIFROW 0x0c
#define SAMSUNG_KEYIFFC 0x10
/* SAMSUNG_KEYIFCON */
#define SAMSUNG_KEYIFCON_INT_F_EN (1 << 0)
#define SAMSUNG_KEYIFCON_INT_R_EN (1 << 1)
#define SAMSUNG_KEYIFCON_DF_EN (1 << 2)
#define SAMSUNG_KEYIFCON_FC_EN (1 << 3)
#define SAMSUNG_KEYIFCON_WAKEUPEN (1 << 4)
/* SAMSUNG_KEYIFSTSCLR */
#define SAMSUNG_KEYIFSTSCLR_P_INT_MASK (0xff << 0)
#define SAMSUNG_KEYIFSTSCLR_R_INT_MASK (0xff << 8)
#define SAMSUNG_KEYIFSTSCLR_R_INT_OFFSET 8
#define S5PV210_KEYIFSTSCLR_P_INT_MASK (0x3fff << 0)
#define S5PV210_KEYIFSTSCLR_R_INT_MASK (0x3fff << 16)
#define S5PV210_KEYIFSTSCLR_R_INT_OFFSET 16
/* SAMSUNG_KEYIFCOL */
#define SAMSUNG_KEYIFCOL_MASK (0xff << 0)
#define S5PV210_KEYIFCOLEN_MASK (0xff << 8)
/* SAMSUNG_KEYIFROW */
#define SAMSUNG_KEYIFROW_MASK (0xff << 0)
#define S5PV210_KEYIFROW_MASK (0x3fff << 0)
/* SAMSUNG_KEYIFFC */
#define SAMSUNG_KEYIFFC_MASK (0x3ff << 0)
enum samsung_keypad_type {
KEYPAD_TYPE_SAMSUNG,
KEYPAD_TYPE_S5PV210,
};
struct samsung_keypad {
struct input_dev *input_dev;
struct platform_device *pdev;
struct clk *clk;
void __iomem *base;
wait_queue_head_t wait;
bool stopped;
bool wake_enabled;
int irq;
enum samsung_keypad_type type;
unsigned int row_shift;
unsigned int rows;
unsigned int cols;
unsigned int row_state[SAMSUNG_MAX_COLS];
#ifdef CONFIG_OF
int row_gpios[SAMSUNG_MAX_ROWS];
int col_gpios[SAMSUNG_MAX_COLS];
#endif
unsigned short keycodes[];
};
static void samsung_keypad_scan(struct samsung_keypad *keypad,
unsigned int *row_state)
{
unsigned int col;
unsigned int val;
for (col = 0; col < keypad->cols; col++) {
if (keypad->type == KEYPAD_TYPE_S5PV210) {
val = S5PV210_KEYIFCOLEN_MASK;
val &= ~(1 << col) << 8;
} else {
val = SAMSUNG_KEYIFCOL_MASK;
val &= ~(1 << col);
}
writel(val, keypad->base + SAMSUNG_KEYIFCOL);
mdelay(1);
val = readl(keypad->base + SAMSUNG_KEYIFROW);
row_state[col] = ~val & ((1 << keypad->rows) - 1);
}
/* KEYIFCOL reg clear */
writel(0, keypad->base + SAMSUNG_KEYIFCOL);
}
static bool samsung_keypad_report(struct samsung_keypad *keypad,
unsigned int *row_state)
{
struct input_dev *input_dev = keypad->input_dev;
unsigned int changed;
unsigned int pressed;
unsigned int key_down = 0;
unsigned int val;
unsigned int col, row;
for (col = 0; col < keypad->cols; col++) {
changed = row_state[col] ^ keypad->row_state[col];
key_down |= row_state[col];
if (!changed)
continue;
for (row = 0; row < keypad->rows; row++) {
if (!(changed & (1 << row)))
continue;
pressed = row_state[col] & (1 << row);
dev_dbg(&keypad->input_dev->dev,
"key %s, row: %d, col: %d\n",
pressed ? "pressed" : "released", row, col);
val = MATRIX_SCAN_CODE(row, col, keypad->row_shift);
input_event(input_dev, EV_MSC, MSC_SCAN, val);
input_report_key(input_dev,
keypad->keycodes[val], pressed);
}
input_sync(keypad->input_dev);
}
memcpy(keypad->row_state, row_state, sizeof(keypad->row_state));
return key_down;
}
static irqreturn_t samsung_keypad_irq(int irq, void *dev_id)
{
struct samsung_keypad *keypad = dev_id;
unsigned int row_state[SAMSUNG_MAX_COLS];
unsigned int val;
bool key_down;
pm_runtime_get_sync(&keypad->pdev->dev);
do {
val = readl(keypad->base + SAMSUNG_KEYIFSTSCLR);
/* Clear interrupt. */
writel(~0x0, keypad->base + SAMSUNG_KEYIFSTSCLR);
samsung_keypad_scan(keypad, row_state);
key_down = samsung_keypad_report(keypad, row_state);
if (key_down)
wait_event_timeout(keypad->wait, keypad->stopped,
msecs_to_jiffies(50));
} while (key_down && !keypad->stopped);
pm_runtime_put(&keypad->pdev->dev);
return IRQ_HANDLED;
}
static void samsung_keypad_start(struct samsung_keypad *keypad)
{
unsigned int val;
pm_runtime_get_sync(&keypad->pdev->dev);
/* Tell IRQ thread that it may poll the device. */
keypad->stopped = false;
clk_enable(keypad->clk);
/* Enable interrupt bits. */
val = readl(keypad->base + SAMSUNG_KEYIFCON);
val |= SAMSUNG_KEYIFCON_INT_F_EN | SAMSUNG_KEYIFCON_INT_R_EN;
writel(val, keypad->base + SAMSUNG_KEYIFCON);
/* KEYIFCOL reg clear. */
writel(0, keypad->base + SAMSUNG_KEYIFCOL);
pm_runtime_put(&keypad->pdev->dev);
}
static void samsung_keypad_stop(struct samsung_keypad *keypad)
{
unsigned int val;
pm_runtime_get_sync(&keypad->pdev->dev);
/* Signal IRQ thread to stop polling and disable the handler. */
keypad->stopped = true;
wake_up(&keypad->wait);
disable_irq(keypad->irq);
/* Clear interrupt. */
writel(~0x0, keypad->base + SAMSUNG_KEYIFSTSCLR);
/* Disable interrupt bits. */
val = readl(keypad->base + SAMSUNG_KEYIFCON);
val &= ~(SAMSUNG_KEYIFCON_INT_F_EN | SAMSUNG_KEYIFCON_INT_R_EN);
writel(val, keypad->base + SAMSUNG_KEYIFCON);
clk_disable(keypad->clk);
/*
* Now that chip should not generate interrupts we can safely
* re-enable the handler.
*/
enable_irq(keypad->irq);
pm_runtime_put(&keypad->pdev->dev);
}
static int samsung_keypad_open(struct input_dev *input_dev)
{
struct samsung_keypad *keypad = input_get_drvdata(input_dev);
samsung_keypad_start(keypad);
return 0;
}
static void samsung_keypad_close(struct input_dev *input_dev)
{
struct samsung_keypad *keypad = input_get_drvdata(input_dev);
samsung_keypad_stop(keypad);
}
#ifdef CONFIG_OF
static struct samsung_keypad_platdata *samsung_keypad_parse_dt(
struct device *dev)
{
struct samsung_keypad_platdata *pdata;
struct matrix_keymap_data *keymap_data;
uint32_t *keymap, num_rows = 0, num_cols = 0;
struct device_node *np = dev->of_node, *key_np;
unsigned int key_count = 0;
pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata) {
dev_err(dev, "could not allocate memory for platform data\n");
return NULL;
}
of_property_read_u32(np, "samsung,keypad-num-rows", &num_rows);
of_property_read_u32(np, "samsung,keypad-num-columns", &num_cols);
if (!num_rows || !num_cols) {
dev_err(dev, "number of keypad rows/columns not specified\n");
return NULL;
}
pdata->rows = num_rows;
pdata->cols = num_cols;
keymap_data = devm_kzalloc(dev, sizeof(*keymap_data), GFP_KERNEL);
if (!keymap_data) {
dev_err(dev, "could not allocate memory for keymap data\n");
return NULL;
}
pdata->keymap_data = keymap_data;
for_each_child_of_node(np, key_np)
key_count++;
keymap_data->keymap_size = key_count;
keymap = devm_kzalloc(dev, sizeof(uint32_t) * key_count, GFP_KERNEL);
if (!keymap) {
dev_err(dev, "could not allocate memory for keymap\n");
return NULL;
}
keymap_data->keymap = keymap;
for_each_child_of_node(np, key_np) {
u32 row, col, key_code;
of_property_read_u32(key_np, "keypad,row", &row);
of_property_read_u32(key_np, "keypad,column", &col);
of_property_read_u32(key_np, "linux,code", &key_code);
*keymap++ = KEY(row, col, key_code);
}
if (of_get_property(np, "linux,input-no-autorepeat", NULL))
pdata->no_autorepeat = true;
if (of_get_property(np, "linux,input-wakeup", NULL))
pdata->wakeup = true;
return pdata;
}
static void samsung_keypad_parse_dt_gpio(struct device *dev,
struct samsung_keypad *keypad)
{
struct device_node *np = dev->of_node;
int gpio, ret, row, col;
for (row = 0; row < keypad->rows; row++) {
gpio = of_get_named_gpio(np, "row-gpios", row);
keypad->row_gpios[row] = gpio;
if (!gpio_is_valid(gpio)) {
dev_err(dev, "keypad row[%d]: invalid gpio %d\n",
row, gpio);
continue;
}
ret = gpio_request(gpio, "keypad-row");
if (ret)
dev_err(dev, "keypad row[%d] gpio request failed\n",
row);
}
for (col = 0; col < keypad->cols; col++) {
gpio = of_get_named_gpio(np, "col-gpios", col);
keypad->col_gpios[col] = gpio;
if (!gpio_is_valid(gpio)) {
dev_err(dev, "keypad column[%d]: invalid gpio %d\n",
col, gpio);
continue;
}
ret = gpio_request(gpio, "keypad-col");
if (ret)
dev_err(dev, "keypad column[%d] gpio request failed\n",
col);
}
}
static void samsung_keypad_dt_gpio_free(struct samsung_keypad *keypad)
{
int cnt;
for (cnt = 0; cnt < keypad->rows; cnt++)
if (gpio_is_valid(keypad->row_gpios[cnt]))
gpio_free(keypad->row_gpios[cnt]);
for (cnt = 0; cnt < keypad->cols; cnt++)
if (gpio_is_valid(keypad->col_gpios[cnt]))
gpio_free(keypad->col_gpios[cnt]);
}
#else
static
struct samsung_keypad_platdata *samsung_keypad_parse_dt(struct device *dev)
{
return NULL;
}
static void samsung_keypad_dt_gpio_free(struct samsung_keypad *keypad)
{
}
#endif
static int __devinit samsung_keypad_probe(struct platform_device *pdev)
{
const struct samsung_keypad_platdata *pdata;
const struct matrix_keymap_data *keymap_data;
struct samsung_keypad *keypad;
struct resource *res;
struct input_dev *input_dev;
unsigned int row_shift;
unsigned int keymap_size;
int error;
if (pdev->dev.of_node)
pdata = samsung_keypad_parse_dt(&pdev->dev);
else
pdata = pdev->dev.platform_data;
if (!pdata) {
dev_err(&pdev->dev, "no platform data defined\n");
return -EINVAL;
}
keymap_data = pdata->keymap_data;
if (!keymap_data) {
dev_err(&pdev->dev, "no keymap data defined\n");
return -EINVAL;
}
if (!pdata->rows || pdata->rows > SAMSUNG_MAX_ROWS)
return -EINVAL;
if (!pdata->cols || pdata->cols > SAMSUNG_MAX_COLS)
return -EINVAL;
/* initialize the gpio */
if (pdata->cfg_gpio)
pdata->cfg_gpio(pdata->rows, pdata->cols);
row_shift = get_count_order(pdata->cols);
keymap_size = (pdata->rows << row_shift) * sizeof(keypad->keycodes[0]);
keypad = kzalloc(sizeof(*keypad) + keymap_size, GFP_KERNEL);
input_dev = input_allocate_device();
if (!keypad || !input_dev) {
error = -ENOMEM;
goto err_free_mem;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
error = -ENODEV;
goto err_free_mem;
}
keypad->base = ioremap(res->start, resource_size(res));
if (!keypad->base) {
error = -EBUSY;
goto err_free_mem;
}
keypad->clk = clk_get(&pdev->dev, "keypad");
if (IS_ERR(keypad->clk)) {
dev_err(&pdev->dev, "failed to get keypad clk\n");
error = PTR_ERR(keypad->clk);
goto err_unmap_base;
}
keypad->input_dev = input_dev;
keypad->pdev = pdev;
keypad->row_shift = row_shift;
keypad->rows = pdata->rows;
keypad->cols = pdata->cols;
keypad->stopped = true;
init_waitqueue_head(&keypad->wait);
if (pdev->dev.of_node) {
#ifdef CONFIG_OF
samsung_keypad_parse_dt_gpio(&pdev->dev, keypad);
keypad->type = of_device_is_compatible(pdev->dev.of_node,
"samsung,s5pv210-keypad");
#endif
} else {
keypad->type = platform_get_device_id(pdev)->driver_data;
}
input_dev->name = pdev->name;
input_dev->id.bustype = BUS_HOST;
input_dev->dev.parent = &pdev->dev;
input_set_drvdata(input_dev, keypad);
input_dev->open = samsung_keypad_open;
input_dev->close = samsung_keypad_close;
input_dev->evbit[0] = BIT_MASK(EV_KEY);
if (!pdata->no_autorepeat)
input_dev->evbit[0] |= BIT_MASK(EV_REP);
input_set_capability(input_dev, EV_MSC, MSC_SCAN);
input_dev->keycode = keypad->keycodes;
input_dev->keycodesize = sizeof(keypad->keycodes[0]);
input_dev->keycodemax = pdata->rows << row_shift;
matrix_keypad_build_keymap(keymap_data, row_shift,
input_dev->keycode, input_dev->keybit);
keypad->irq = platform_get_irq(pdev, 0);
if (keypad->irq < 0) {
error = keypad->irq;
goto err_put_clk;
}
error = request_threaded_irq(keypad->irq, NULL, samsung_keypad_irq,
IRQF_ONESHOT, dev_name(&pdev->dev), keypad);
if (error) {
dev_err(&pdev->dev, "failed to register keypad interrupt\n");
goto err_put_clk;
}
device_init_wakeup(&pdev->dev, pdata->wakeup);
platform_set_drvdata(pdev, keypad);
pm_runtime_enable(&pdev->dev);
error = input_register_device(keypad->input_dev);
if (error)
goto err_free_irq;
if (pdev->dev.of_node) {
devm_kfree(&pdev->dev, (void *)pdata->keymap_data->keymap);
devm_kfree(&pdev->dev, (void *)pdata->keymap_data);
devm_kfree(&pdev->dev, (void *)pdata);
}
return 0;
err_free_irq:
free_irq(keypad->irq, keypad);
pm_runtime_disable(&pdev->dev);
device_init_wakeup(&pdev->dev, 0);
platform_set_drvdata(pdev, NULL);
err_put_clk:
clk_put(keypad->clk);
samsung_keypad_dt_gpio_free(keypad);
err_unmap_base:
iounmap(keypad->base);
err_free_mem:
input_free_device(input_dev);
kfree(keypad);
return error;
}
static int __devexit samsung_keypad_remove(struct platform_device *pdev)
{
struct samsung_keypad *keypad = platform_get_drvdata(pdev);
pm_runtime_disable(&pdev->dev);
device_init_wakeup(&pdev->dev, 0);
platform_set_drvdata(pdev, NULL);
input_unregister_device(keypad->input_dev);
/*
* It is safe to free IRQ after unregistering device because
* samsung_keypad_close will shut off interrupts.
*/
free_irq(keypad->irq, keypad);
clk_put(keypad->clk);
samsung_keypad_dt_gpio_free(keypad);
iounmap(keypad->base);
kfree(keypad);
return 0;
}
#ifdef CONFIG_PM_RUNTIME
static int samsung_keypad_runtime_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct samsung_keypad *keypad = platform_get_drvdata(pdev);
unsigned int val;
int error;
if (keypad->stopped)
return 0;
/* This may fail on some SoCs due to lack of controller support */
error = enable_irq_wake(keypad->irq);
if (!error)
keypad->wake_enabled = true;
val = readl(keypad->base + SAMSUNG_KEYIFCON);
val |= SAMSUNG_KEYIFCON_WAKEUPEN;
writel(val, keypad->base + SAMSUNG_KEYIFCON);
clk_disable(keypad->clk);
return 0;
}
static int samsung_keypad_runtime_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct samsung_keypad *keypad = platform_get_drvdata(pdev);
unsigned int val;
if (keypad->stopped)
return 0;
clk_enable(keypad->clk);
val = readl(keypad->base + SAMSUNG_KEYIFCON);
val &= ~SAMSUNG_KEYIFCON_WAKEUPEN;
writel(val, keypad->base + SAMSUNG_KEYIFCON);
if (keypad->wake_enabled)
disable_irq_wake(keypad->irq);
return 0;
}
#endif
#ifdef CONFIG_PM_SLEEP
static void samsung_keypad_toggle_wakeup(struct samsung_keypad *keypad,
bool enable)
{
unsigned int val;
clk_enable(keypad->clk);
val = readl(keypad->base + SAMSUNG_KEYIFCON);
if (enable) {
val |= SAMSUNG_KEYIFCON_WAKEUPEN;
if (device_may_wakeup(&keypad->pdev->dev))
enable_irq_wake(keypad->irq);
} else {
val &= ~SAMSUNG_KEYIFCON_WAKEUPEN;
if (device_may_wakeup(&keypad->pdev->dev))
disable_irq_wake(keypad->irq);
}
writel(val, keypad->base + SAMSUNG_KEYIFCON);
clk_disable(keypad->clk);
}
static int samsung_keypad_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct samsung_keypad *keypad = platform_get_drvdata(pdev);
struct input_dev *input_dev = keypad->input_dev;
mutex_lock(&input_dev->mutex);
if (input_dev->users)
samsung_keypad_stop(keypad);
samsung_keypad_toggle_wakeup(keypad, true);
mutex_unlock(&input_dev->mutex);
return 0;
}
static int samsung_keypad_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct samsung_keypad *keypad = platform_get_drvdata(pdev);
struct input_dev *input_dev = keypad->input_dev;
mutex_lock(&input_dev->mutex);
samsung_keypad_toggle_wakeup(keypad, false);
if (input_dev->users)
samsung_keypad_start(keypad);
mutex_unlock(&input_dev->mutex);
return 0;
}
#endif
static const struct dev_pm_ops samsung_keypad_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(samsung_keypad_suspend, samsung_keypad_resume)
SET_RUNTIME_PM_OPS(samsung_keypad_runtime_suspend,
samsung_keypad_runtime_resume, NULL)
};
#ifdef CONFIG_OF
static const struct of_device_id samsung_keypad_dt_match[] = {
{ .compatible = "samsung,s3c6410-keypad" },
{ .compatible = "samsung,s5pv210-keypad" },
{},
};
MODULE_DEVICE_TABLE(of, samsung_keypad_dt_match);
#else
#define samsung_keypad_dt_match NULL
#endif
static struct platform_device_id samsung_keypad_driver_ids[] = {
{
.name = "samsung-keypad",
.driver_data = KEYPAD_TYPE_SAMSUNG,
}, {
.name = "s5pv210-keypad",
.driver_data = KEYPAD_TYPE_S5PV210,
},
{ },
};
MODULE_DEVICE_TABLE(platform, samsung_keypad_driver_ids);
static struct platform_driver samsung_keypad_driver = {
.probe = samsung_keypad_probe,
.remove = __devexit_p(samsung_keypad_remove),
.driver = {
.name = "samsung-keypad",
.owner = THIS_MODULE,
.of_match_table = samsung_keypad_dt_match,
.pm = &samsung_keypad_pm_ops,
},
.id_table = samsung_keypad_driver_ids,
};
module_platform_driver(samsung_keypad_driver);
MODULE_DESCRIPTION("Samsung keypad driver");
MODULE_AUTHOR("Joonyoung Shim <jy0922.shim@samsung.com>");
MODULE_AUTHOR("Donghwa Lee <dh09.lee@samsung.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
TeamNuclear/android_kernel_oneplus_msm8974 | drivers/rtc/rtc-m41t93.c | 4809 | 5700 | /*
*
* Driver for ST M41T93 SPI RTC
*
* (c) 2010 Nikolaus Voss, Weinmann Medical GmbH
*
* 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/bcd.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/rtc.h>
#include <linux/spi/spi.h>
#define M41T93_REG_SSEC 0
#define M41T93_REG_ST_SEC 1
#define M41T93_REG_MIN 2
#define M41T93_REG_CENT_HOUR 3
#define M41T93_REG_WDAY 4
#define M41T93_REG_DAY 5
#define M41T93_REG_MON 6
#define M41T93_REG_YEAR 7
#define M41T93_REG_ALM_HOUR_HT 0xc
#define M41T93_REG_FLAGS 0xf
#define M41T93_FLAG_ST (1 << 7)
#define M41T93_FLAG_OF (1 << 2)
#define M41T93_FLAG_BL (1 << 4)
#define M41T93_FLAG_HT (1 << 6)
static inline int m41t93_set_reg(struct spi_device *spi, u8 addr, u8 data)
{
u8 buf[2];
/* MSB must be '1' to write */
buf[0] = addr | 0x80;
buf[1] = data;
return spi_write(spi, buf, sizeof(buf));
}
static int m41t93_set_time(struct device *dev, struct rtc_time *tm)
{
struct spi_device *spi = to_spi_device(dev);
u8 buf[9] = {0x80}; /* write cmd + 8 data bytes */
u8 * const data = &buf[1]; /* ptr to first data byte */
dev_dbg(dev, "%s secs=%d, mins=%d, "
"hours=%d, mday=%d, mon=%d, year=%d, wday=%d\n",
"write", tm->tm_sec, tm->tm_min,
tm->tm_hour, tm->tm_mday,
tm->tm_mon, tm->tm_year, tm->tm_wday);
if (tm->tm_year < 100) {
dev_warn(&spi->dev, "unsupported date (before 2000-01-01).\n");
return -EINVAL;
}
data[M41T93_REG_SSEC] = 0;
data[M41T93_REG_ST_SEC] = bin2bcd(tm->tm_sec);
data[M41T93_REG_MIN] = bin2bcd(tm->tm_min);
data[M41T93_REG_CENT_HOUR] = bin2bcd(tm->tm_hour) |
((tm->tm_year/100-1) << 6);
data[M41T93_REG_DAY] = bin2bcd(tm->tm_mday);
data[M41T93_REG_WDAY] = bin2bcd(tm->tm_wday + 1);
data[M41T93_REG_MON] = bin2bcd(tm->tm_mon + 1);
data[M41T93_REG_YEAR] = bin2bcd(tm->tm_year % 100);
return spi_write(spi, buf, sizeof(buf));
}
static int m41t93_get_time(struct device *dev, struct rtc_time *tm)
{
struct spi_device *spi = to_spi_device(dev);
const u8 start_addr = 0;
u8 buf[8];
int century_after_1900;
int tmp;
int ret = 0;
/* Check status of clock. Two states must be considered:
1. halt bit (HT) is set: the clock is running but update of readout
registers has been disabled due to power failure. This is normal
case after poweron. Time is valid after resetting HT bit.
2. oscillator fail bit (OF) is set. Oscillator has be stopped and
time is invalid:
a) OF can be immeditely reset.
b) OF cannot be immediately reset: oscillator has to be restarted.
*/
tmp = spi_w8r8(spi, M41T93_REG_ALM_HOUR_HT);
if (tmp < 0)
return tmp;
if (tmp & M41T93_FLAG_HT) {
dev_dbg(&spi->dev, "HT bit is set, reenable clock update.\n");
m41t93_set_reg(spi, M41T93_REG_ALM_HOUR_HT,
tmp & ~M41T93_FLAG_HT);
}
tmp = spi_w8r8(spi, M41T93_REG_FLAGS);
if (tmp < 0)
return tmp;
if (tmp & M41T93_FLAG_OF) {
ret = -EINVAL;
dev_warn(&spi->dev, "OF bit is set, resetting.\n");
m41t93_set_reg(spi, M41T93_REG_FLAGS, tmp & ~M41T93_FLAG_OF);
tmp = spi_w8r8(spi, M41T93_REG_FLAGS);
if (tmp < 0)
return tmp;
else if (tmp & M41T93_FLAG_OF) {
u8 reset_osc = buf[M41T93_REG_ST_SEC] | M41T93_FLAG_ST;
dev_warn(&spi->dev,
"OF bit is still set, kickstarting clock.\n");
m41t93_set_reg(spi, M41T93_REG_ST_SEC, reset_osc);
reset_osc &= ~M41T93_FLAG_ST;
m41t93_set_reg(spi, M41T93_REG_ST_SEC, reset_osc);
}
}
if (tmp & M41T93_FLAG_BL)
dev_warn(&spi->dev, "BL bit is set, replace battery.\n");
/* read actual time/date */
tmp = spi_write_then_read(spi, &start_addr, 1, buf, sizeof(buf));
if (tmp < 0)
return tmp;
tm->tm_sec = bcd2bin(buf[M41T93_REG_ST_SEC]);
tm->tm_min = bcd2bin(buf[M41T93_REG_MIN]);
tm->tm_hour = bcd2bin(buf[M41T93_REG_CENT_HOUR] & 0x3f);
tm->tm_mday = bcd2bin(buf[M41T93_REG_DAY]);
tm->tm_mon = bcd2bin(buf[M41T93_REG_MON]) - 1;
tm->tm_wday = bcd2bin(buf[M41T93_REG_WDAY] & 0x0f) - 1;
century_after_1900 = (buf[M41T93_REG_CENT_HOUR] >> 6) + 1;
tm->tm_year = bcd2bin(buf[M41T93_REG_YEAR]) + century_after_1900 * 100;
dev_dbg(dev, "%s secs=%d, mins=%d, "
"hours=%d, mday=%d, mon=%d, year=%d, wday=%d\n",
"read", tm->tm_sec, tm->tm_min,
tm->tm_hour, tm->tm_mday,
tm->tm_mon, tm->tm_year, tm->tm_wday);
return ret < 0 ? ret : rtc_valid_tm(tm);
}
static const struct rtc_class_ops m41t93_rtc_ops = {
.read_time = m41t93_get_time,
.set_time = m41t93_set_time,
};
static struct spi_driver m41t93_driver;
static int __devinit m41t93_probe(struct spi_device *spi)
{
struct rtc_device *rtc;
int res;
spi->bits_per_word = 8;
spi_setup(spi);
res = spi_w8r8(spi, M41T93_REG_WDAY);
if (res < 0 || (res & 0xf8) != 0) {
dev_err(&spi->dev, "not found 0x%x.\n", res);
return -ENODEV;
}
rtc = rtc_device_register(m41t93_driver.driver.name,
&spi->dev, &m41t93_rtc_ops, THIS_MODULE);
if (IS_ERR(rtc))
return PTR_ERR(rtc);
dev_set_drvdata(&spi->dev, rtc);
return 0;
}
static int __devexit m41t93_remove(struct spi_device *spi)
{
struct rtc_device *rtc = spi_get_drvdata(spi);
if (rtc)
rtc_device_unregister(rtc);
return 0;
}
static struct spi_driver m41t93_driver = {
.driver = {
.name = "rtc-m41t93",
.owner = THIS_MODULE,
},
.probe = m41t93_probe,
.remove = __devexit_p(m41t93_remove),
};
module_spi_driver(m41t93_driver);
MODULE_AUTHOR("Nikolaus Voss <n.voss@weinmann.de>");
MODULE_DESCRIPTION("Driver for ST M41T93 SPI RTC");
MODULE_LICENSE("GPL");
MODULE_ALIAS("spi:rtc-m41t93");
| gpl-2.0 |
forumber/temiz_kernel_g2 | drivers/isdn/mISDN/tei.c | 4809 | 33082 | /*
*
* Author Karsten Keil <kkeil@novell.com>
*
* Copyright 2008 by Karsten Keil <kkeil@novell.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include "layer2.h"
#include <linux/random.h>
#include <linux/slab.h>
#include "core.h"
#define ID_REQUEST 1
#define ID_ASSIGNED 2
#define ID_DENIED 3
#define ID_CHK_REQ 4
#define ID_CHK_RES 5
#define ID_REMOVE 6
#define ID_VERIFY 7
#define TEI_ENTITY_ID 0xf
#define MGR_PH_ACTIVE 16
#define MGR_PH_NOTREADY 17
#define DATIMER_VAL 10000
static u_int *debug;
static struct Fsm deactfsm = {NULL, 0, 0, NULL, NULL};
static struct Fsm teifsmu = {NULL, 0, 0, NULL, NULL};
static struct Fsm teifsmn = {NULL, 0, 0, NULL, NULL};
enum {
ST_L1_DEACT,
ST_L1_DEACT_PENDING,
ST_L1_ACTIV,
};
#define DEACT_STATE_COUNT (ST_L1_ACTIV + 1)
static char *strDeactState[] =
{
"ST_L1_DEACT",
"ST_L1_DEACT_PENDING",
"ST_L1_ACTIV",
};
enum {
EV_ACTIVATE,
EV_ACTIVATE_IND,
EV_DEACTIVATE,
EV_DEACTIVATE_IND,
EV_UI,
EV_DATIMER,
};
#define DEACT_EVENT_COUNT (EV_DATIMER + 1)
static char *strDeactEvent[] =
{
"EV_ACTIVATE",
"EV_ACTIVATE_IND",
"EV_DEACTIVATE",
"EV_DEACTIVATE_IND",
"EV_UI",
"EV_DATIMER",
};
static void
da_debug(struct FsmInst *fi, char *fmt, ...)
{
struct manager *mgr = fi->userdata;
struct va_format vaf;
va_list va;
if (!(*debug & DEBUG_L2_TEIFSM))
return;
va_start(va, fmt);
vaf.fmt = fmt;
vaf.va = &va;
printk(KERN_DEBUG "mgr(%d): %pV\n", mgr->ch.st->dev->id, &vaf);
va_end(va);
}
static void
da_activate(struct FsmInst *fi, int event, void *arg)
{
struct manager *mgr = fi->userdata;
if (fi->state == ST_L1_DEACT_PENDING)
mISDN_FsmDelTimer(&mgr->datimer, 1);
mISDN_FsmChangeState(fi, ST_L1_ACTIV);
}
static void
da_deactivate_ind(struct FsmInst *fi, int event, void *arg)
{
mISDN_FsmChangeState(fi, ST_L1_DEACT);
}
static void
da_deactivate(struct FsmInst *fi, int event, void *arg)
{
struct manager *mgr = fi->userdata;
struct layer2 *l2;
u_long flags;
read_lock_irqsave(&mgr->lock, flags);
list_for_each_entry(l2, &mgr->layer2, list) {
if (l2->l2m.state > ST_L2_4) {
/* have still activ TEI */
read_unlock_irqrestore(&mgr->lock, flags);
return;
}
}
read_unlock_irqrestore(&mgr->lock, flags);
/* All TEI are inactiv */
if (!test_bit(OPTION_L1_HOLD, &mgr->options)) {
mISDN_FsmAddTimer(&mgr->datimer, DATIMER_VAL, EV_DATIMER,
NULL, 1);
mISDN_FsmChangeState(fi, ST_L1_DEACT_PENDING);
}
}
static void
da_ui(struct FsmInst *fi, int event, void *arg)
{
struct manager *mgr = fi->userdata;
/* restart da timer */
if (!test_bit(OPTION_L1_HOLD, &mgr->options)) {
mISDN_FsmDelTimer(&mgr->datimer, 2);
mISDN_FsmAddTimer(&mgr->datimer, DATIMER_VAL, EV_DATIMER,
NULL, 2);
}
}
static void
da_timer(struct FsmInst *fi, int event, void *arg)
{
struct manager *mgr = fi->userdata;
struct layer2 *l2;
u_long flags;
/* check again */
read_lock_irqsave(&mgr->lock, flags);
list_for_each_entry(l2, &mgr->layer2, list) {
if (l2->l2m.state > ST_L2_4) {
/* have still activ TEI */
read_unlock_irqrestore(&mgr->lock, flags);
mISDN_FsmChangeState(fi, ST_L1_ACTIV);
return;
}
}
read_unlock_irqrestore(&mgr->lock, flags);
/* All TEI are inactiv */
mISDN_FsmChangeState(fi, ST_L1_DEACT);
_queue_data(&mgr->ch, PH_DEACTIVATE_REQ, MISDN_ID_ANY, 0, NULL,
GFP_ATOMIC);
}
static struct FsmNode DeactFnList[] =
{
{ST_L1_DEACT, EV_ACTIVATE_IND, da_activate},
{ST_L1_ACTIV, EV_DEACTIVATE_IND, da_deactivate_ind},
{ST_L1_ACTIV, EV_DEACTIVATE, da_deactivate},
{ST_L1_DEACT_PENDING, EV_ACTIVATE, da_activate},
{ST_L1_DEACT_PENDING, EV_UI, da_ui},
{ST_L1_DEACT_PENDING, EV_DATIMER, da_timer},
};
enum {
ST_TEI_NOP,
ST_TEI_IDREQ,
ST_TEI_IDVERIFY,
};
#define TEI_STATE_COUNT (ST_TEI_IDVERIFY + 1)
static char *strTeiState[] =
{
"ST_TEI_NOP",
"ST_TEI_IDREQ",
"ST_TEI_IDVERIFY",
};
enum {
EV_IDREQ,
EV_ASSIGN,
EV_ASSIGN_REQ,
EV_DENIED,
EV_CHKREQ,
EV_CHKRESP,
EV_REMOVE,
EV_VERIFY,
EV_TIMER,
};
#define TEI_EVENT_COUNT (EV_TIMER + 1)
static char *strTeiEvent[] =
{
"EV_IDREQ",
"EV_ASSIGN",
"EV_ASSIGN_REQ",
"EV_DENIED",
"EV_CHKREQ",
"EV_CHKRESP",
"EV_REMOVE",
"EV_VERIFY",
"EV_TIMER",
};
static void
tei_debug(struct FsmInst *fi, char *fmt, ...)
{
struct teimgr *tm = fi->userdata;
struct va_format vaf;
va_list va;
if (!(*debug & DEBUG_L2_TEIFSM))
return;
va_start(va, fmt);
vaf.fmt = fmt;
vaf.va = &va;
printk(KERN_DEBUG "sapi(%d) tei(%d): %pV\n",
tm->l2->sapi, tm->l2->tei, &vaf);
va_end(va);
}
static int
get_free_id(struct manager *mgr)
{
u64 ids = 0;
int i;
struct layer2 *l2;
list_for_each_entry(l2, &mgr->layer2, list) {
if (l2->ch.nr > 63) {
printk(KERN_WARNING
"%s: more as 63 layer2 for one device\n",
__func__);
return -EBUSY;
}
test_and_set_bit(l2->ch.nr, (u_long *)&ids);
}
for (i = 1; i < 64; i++)
if (!test_bit(i, (u_long *)&ids))
return i;
printk(KERN_WARNING "%s: more as 63 layer2 for one device\n",
__func__);
return -EBUSY;
}
static int
get_free_tei(struct manager *mgr)
{
u64 ids = 0;
int i;
struct layer2 *l2;
list_for_each_entry(l2, &mgr->layer2, list) {
if (l2->ch.nr == 0)
continue;
if ((l2->ch.addr & 0xff) != 0)
continue;
i = l2->ch.addr >> 8;
if (i < 64)
continue;
i -= 64;
test_and_set_bit(i, (u_long *)&ids);
}
for (i = 0; i < 64; i++)
if (!test_bit(i, (u_long *)&ids))
return i + 64;
printk(KERN_WARNING "%s: more as 63 dynamic tei for one device\n",
__func__);
return -1;
}
static void
teiup_create(struct manager *mgr, u_int prim, int len, void *arg)
{
struct sk_buff *skb;
struct mISDNhead *hh;
int err;
skb = mI_alloc_skb(len, GFP_ATOMIC);
if (!skb)
return;
hh = mISDN_HEAD_P(skb);
hh->prim = prim;
hh->id = (mgr->ch.nr << 16) | mgr->ch.addr;
if (len)
memcpy(skb_put(skb, len), arg, len);
err = mgr->up->send(mgr->up, skb);
if (err) {
printk(KERN_WARNING "%s: err=%d\n", __func__, err);
dev_kfree_skb(skb);
}
}
static u_int
new_id(struct manager *mgr)
{
u_int id;
id = mgr->nextid++;
if (id == 0x7fff)
mgr->nextid = 1;
id <<= 16;
id |= GROUP_TEI << 8;
id |= TEI_SAPI;
return id;
}
static void
do_send(struct manager *mgr)
{
if (!test_bit(MGR_PH_ACTIVE, &mgr->options))
return;
if (!test_and_set_bit(MGR_PH_NOTREADY, &mgr->options)) {
struct sk_buff *skb = skb_dequeue(&mgr->sendq);
if (!skb) {
test_and_clear_bit(MGR_PH_NOTREADY, &mgr->options);
return;
}
mgr->lastid = mISDN_HEAD_ID(skb);
mISDN_FsmEvent(&mgr->deact, EV_UI, NULL);
if (mgr->ch.recv(mgr->ch.peer, skb)) {
dev_kfree_skb(skb);
test_and_clear_bit(MGR_PH_NOTREADY, &mgr->options);
mgr->lastid = MISDN_ID_NONE;
}
}
}
static void
do_ack(struct manager *mgr, u_int id)
{
if (test_bit(MGR_PH_NOTREADY, &mgr->options)) {
if (id == mgr->lastid) {
if (test_bit(MGR_PH_ACTIVE, &mgr->options)) {
struct sk_buff *skb;
skb = skb_dequeue(&mgr->sendq);
if (skb) {
mgr->lastid = mISDN_HEAD_ID(skb);
if (!mgr->ch.recv(mgr->ch.peer, skb))
return;
dev_kfree_skb(skb);
}
}
mgr->lastid = MISDN_ID_NONE;
test_and_clear_bit(MGR_PH_NOTREADY, &mgr->options);
}
}
}
static void
mgr_send_down(struct manager *mgr, struct sk_buff *skb)
{
skb_queue_tail(&mgr->sendq, skb);
if (!test_bit(MGR_PH_ACTIVE, &mgr->options)) {
_queue_data(&mgr->ch, PH_ACTIVATE_REQ, MISDN_ID_ANY, 0,
NULL, GFP_KERNEL);
} else {
do_send(mgr);
}
}
static int
dl_unit_data(struct manager *mgr, struct sk_buff *skb)
{
if (!test_bit(MGR_OPT_NETWORK, &mgr->options)) /* only net send UI */
return -EINVAL;
if (!test_bit(MGR_PH_ACTIVE, &mgr->options))
_queue_data(&mgr->ch, PH_ACTIVATE_REQ, MISDN_ID_ANY, 0,
NULL, GFP_KERNEL);
skb_push(skb, 3);
skb->data[0] = 0x02; /* SAPI 0 C/R = 1 */
skb->data[1] = 0xff; /* TEI 127 */
skb->data[2] = UI; /* UI frame */
mISDN_HEAD_PRIM(skb) = PH_DATA_REQ;
mISDN_HEAD_ID(skb) = new_id(mgr);
skb_queue_tail(&mgr->sendq, skb);
do_send(mgr);
return 0;
}
static unsigned int
random_ri(void)
{
u16 x;
get_random_bytes(&x, sizeof(x));
return x;
}
static struct layer2 *
findtei(struct manager *mgr, int tei)
{
struct layer2 *l2;
u_long flags;
read_lock_irqsave(&mgr->lock, flags);
list_for_each_entry(l2, &mgr->layer2, list) {
if ((l2->sapi == 0) && (l2->tei > 0) &&
(l2->tei != GROUP_TEI) && (l2->tei == tei))
goto done;
}
l2 = NULL;
done:
read_unlock_irqrestore(&mgr->lock, flags);
return l2;
}
static void
put_tei_msg(struct manager *mgr, u_char m_id, unsigned int ri, int tei)
{
struct sk_buff *skb;
u_char bp[8];
bp[0] = (TEI_SAPI << 2);
if (test_bit(MGR_OPT_NETWORK, &mgr->options))
bp[0] |= 2; /* CR:=1 for net command */
bp[1] = (GROUP_TEI << 1) | 0x1;
bp[2] = UI;
bp[3] = TEI_ENTITY_ID;
bp[4] = ri >> 8;
bp[5] = ri & 0xff;
bp[6] = m_id;
bp[7] = ((tei << 1) & 0xff) | 1;
skb = _alloc_mISDN_skb(PH_DATA_REQ, new_id(mgr), 8, bp, GFP_ATOMIC);
if (!skb) {
printk(KERN_WARNING "%s: no skb for tei msg\n", __func__);
return;
}
mgr_send_down(mgr, skb);
}
static void
tei_id_request(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
if (tm->l2->tei != GROUP_TEI) {
tm->tei_m.printdebug(&tm->tei_m,
"assign request for already assigned tei %d",
tm->l2->tei);
return;
}
tm->ri = random_ri();
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(&tm->tei_m,
"assign request ri %d", tm->ri);
put_tei_msg(tm->mgr, ID_REQUEST, tm->ri, GROUP_TEI);
mISDN_FsmChangeState(fi, ST_TEI_IDREQ);
mISDN_FsmAddTimer(&tm->timer, tm->tval, EV_TIMER, NULL, 1);
tm->nval = 3;
}
static void
tei_id_assign(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
struct layer2 *l2;
u_char *dp = arg;
int ri, tei;
ri = ((unsigned int) *dp++ << 8);
ri += *dp++;
dp++;
tei = *dp >> 1;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "identity assign ri %d tei %d",
ri, tei);
l2 = findtei(tm->mgr, tei);
if (l2) { /* same tei is in use */
if (ri != l2->tm->ri) {
tm->tei_m.printdebug(fi,
"possible duplicate assignment tei %d", tei);
tei_l2(l2, MDL_ERROR_RSP, 0);
}
} else if (ri == tm->ri) {
mISDN_FsmDelTimer(&tm->timer, 1);
mISDN_FsmChangeState(fi, ST_TEI_NOP);
tei_l2(tm->l2, MDL_ASSIGN_REQ, tei);
}
}
static void
tei_id_test_dup(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
struct layer2 *l2;
u_char *dp = arg;
int tei, ri;
ri = ((unsigned int) *dp++ << 8);
ri += *dp++;
dp++;
tei = *dp >> 1;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "foreign identity assign ri %d tei %d",
ri, tei);
l2 = findtei(tm->mgr, tei);
if (l2) { /* same tei is in use */
if (ri != l2->tm->ri) { /* and it wasn't our request */
tm->tei_m.printdebug(fi,
"possible duplicate assignment tei %d", tei);
mISDN_FsmEvent(&l2->tm->tei_m, EV_VERIFY, NULL);
}
}
}
static void
tei_id_denied(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
u_char *dp = arg;
int ri, tei;
ri = ((unsigned int) *dp++ << 8);
ri += *dp++;
dp++;
tei = *dp >> 1;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "identity denied ri %d tei %d",
ri, tei);
}
static void
tei_id_chk_req(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
u_char *dp = arg;
int tei;
tei = *(dp + 3) >> 1;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "identity check req tei %d", tei);
if ((tm->l2->tei != GROUP_TEI) && ((tei == GROUP_TEI) ||
(tei == tm->l2->tei))) {
mISDN_FsmDelTimer(&tm->timer, 4);
mISDN_FsmChangeState(&tm->tei_m, ST_TEI_NOP);
put_tei_msg(tm->mgr, ID_CHK_RES, random_ri(), tm->l2->tei);
}
}
static void
tei_id_remove(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
u_char *dp = arg;
int tei;
tei = *(dp + 3) >> 1;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "identity remove tei %d", tei);
if ((tm->l2->tei != GROUP_TEI) &&
((tei == GROUP_TEI) || (tei == tm->l2->tei))) {
mISDN_FsmDelTimer(&tm->timer, 5);
mISDN_FsmChangeState(&tm->tei_m, ST_TEI_NOP);
tei_l2(tm->l2, MDL_REMOVE_REQ, 0);
}
}
static void
tei_id_verify(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "id verify request for tei %d",
tm->l2->tei);
put_tei_msg(tm->mgr, ID_VERIFY, 0, tm->l2->tei);
mISDN_FsmChangeState(&tm->tei_m, ST_TEI_IDVERIFY);
mISDN_FsmAddTimer(&tm->timer, tm->tval, EV_TIMER, NULL, 2);
tm->nval = 2;
}
static void
tei_id_req_tout(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
if (--tm->nval) {
tm->ri = random_ri();
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "assign req(%d) ri %d",
4 - tm->nval, tm->ri);
put_tei_msg(tm->mgr, ID_REQUEST, tm->ri, GROUP_TEI);
mISDN_FsmAddTimer(&tm->timer, tm->tval, EV_TIMER, NULL, 3);
} else {
tm->tei_m.printdebug(fi, "assign req failed");
tei_l2(tm->l2, MDL_ERROR_RSP, 0);
mISDN_FsmChangeState(fi, ST_TEI_NOP);
}
}
static void
tei_id_ver_tout(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
if (--tm->nval) {
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi,
"id verify req(%d) for tei %d",
3 - tm->nval, tm->l2->tei);
put_tei_msg(tm->mgr, ID_VERIFY, 0, tm->l2->tei);
mISDN_FsmAddTimer(&tm->timer, tm->tval, EV_TIMER, NULL, 4);
} else {
tm->tei_m.printdebug(fi, "verify req for tei %d failed",
tm->l2->tei);
tei_l2(tm->l2, MDL_REMOVE_REQ, 0);
mISDN_FsmChangeState(fi, ST_TEI_NOP);
}
}
static struct FsmNode TeiFnListUser[] =
{
{ST_TEI_NOP, EV_IDREQ, tei_id_request},
{ST_TEI_NOP, EV_ASSIGN, tei_id_test_dup},
{ST_TEI_NOP, EV_VERIFY, tei_id_verify},
{ST_TEI_NOP, EV_REMOVE, tei_id_remove},
{ST_TEI_NOP, EV_CHKREQ, tei_id_chk_req},
{ST_TEI_IDREQ, EV_TIMER, tei_id_req_tout},
{ST_TEI_IDREQ, EV_ASSIGN, tei_id_assign},
{ST_TEI_IDREQ, EV_DENIED, tei_id_denied},
{ST_TEI_IDVERIFY, EV_TIMER, tei_id_ver_tout},
{ST_TEI_IDVERIFY, EV_REMOVE, tei_id_remove},
{ST_TEI_IDVERIFY, EV_CHKREQ, tei_id_chk_req},
};
static void
tei_l2remove(struct layer2 *l2)
{
put_tei_msg(l2->tm->mgr, ID_REMOVE, 0, l2->tei);
tei_l2(l2, MDL_REMOVE_REQ, 0);
list_del(&l2->ch.list);
l2->ch.ctrl(&l2->ch, CLOSE_CHANNEL, NULL);
}
static void
tei_assign_req(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
u_char *dp = arg;
if (tm->l2->tei == GROUP_TEI) {
tm->tei_m.printdebug(&tm->tei_m,
"net tei assign request without tei");
return;
}
tm->ri = ((unsigned int) *dp++ << 8);
tm->ri += *dp++;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(&tm->tei_m,
"net assign request ri %d teim %d", tm->ri, *dp);
put_tei_msg(tm->mgr, ID_ASSIGNED, tm->ri, tm->l2->tei);
mISDN_FsmChangeState(fi, ST_TEI_NOP);
}
static void
tei_id_chk_req_net(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "id check request for tei %d",
tm->l2->tei);
tm->rcnt = 0;
put_tei_msg(tm->mgr, ID_CHK_REQ, 0, tm->l2->tei);
mISDN_FsmChangeState(&tm->tei_m, ST_TEI_IDVERIFY);
mISDN_FsmAddTimer(&tm->timer, tm->tval, EV_TIMER, NULL, 2);
tm->nval = 2;
}
static void
tei_id_chk_resp(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
u_char *dp = arg;
int tei;
tei = dp[3] >> 1;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "identity check resp tei %d", tei);
if (tei == tm->l2->tei)
tm->rcnt++;
}
static void
tei_id_verify_net(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
u_char *dp = arg;
int tei;
tei = dp[3] >> 1;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi, "identity verify req tei %d/%d",
tei, tm->l2->tei);
if (tei == tm->l2->tei)
tei_id_chk_req_net(fi, event, arg);
}
static void
tei_id_ver_tout_net(struct FsmInst *fi, int event, void *arg)
{
struct teimgr *tm = fi->userdata;
if (tm->rcnt == 1) {
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi,
"check req for tei %d successful\n", tm->l2->tei);
mISDN_FsmChangeState(fi, ST_TEI_NOP);
} else if (tm->rcnt > 1) {
/* duplicate assignment; remove */
tei_l2remove(tm->l2);
} else if (--tm->nval) {
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(fi,
"id check req(%d) for tei %d",
3 - tm->nval, tm->l2->tei);
put_tei_msg(tm->mgr, ID_CHK_REQ, 0, tm->l2->tei);
mISDN_FsmAddTimer(&tm->timer, tm->tval, EV_TIMER, NULL, 4);
} else {
tm->tei_m.printdebug(fi, "check req for tei %d failed",
tm->l2->tei);
mISDN_FsmChangeState(fi, ST_TEI_NOP);
tei_l2remove(tm->l2);
}
}
static struct FsmNode TeiFnListNet[] =
{
{ST_TEI_NOP, EV_ASSIGN_REQ, tei_assign_req},
{ST_TEI_NOP, EV_VERIFY, tei_id_verify_net},
{ST_TEI_NOP, EV_CHKREQ, tei_id_chk_req_net},
{ST_TEI_IDVERIFY, EV_TIMER, tei_id_ver_tout_net},
{ST_TEI_IDVERIFY, EV_CHKRESP, tei_id_chk_resp},
};
static void
tei_ph_data_ind(struct teimgr *tm, u_int mt, u_char *dp, int len)
{
if (test_bit(FLG_FIXED_TEI, &tm->l2->flag))
return;
if (*debug & DEBUG_L2_TEI)
tm->tei_m.printdebug(&tm->tei_m, "tei handler mt %x", mt);
if (mt == ID_ASSIGNED)
mISDN_FsmEvent(&tm->tei_m, EV_ASSIGN, dp);
else if (mt == ID_DENIED)
mISDN_FsmEvent(&tm->tei_m, EV_DENIED, dp);
else if (mt == ID_CHK_REQ)
mISDN_FsmEvent(&tm->tei_m, EV_CHKREQ, dp);
else if (mt == ID_REMOVE)
mISDN_FsmEvent(&tm->tei_m, EV_REMOVE, dp);
else if (mt == ID_VERIFY)
mISDN_FsmEvent(&tm->tei_m, EV_VERIFY, dp);
else if (mt == ID_CHK_RES)
mISDN_FsmEvent(&tm->tei_m, EV_CHKRESP, dp);
}
static struct layer2 *
create_new_tei(struct manager *mgr, int tei, int sapi)
{
u_long opt = 0;
u_long flags;
int id;
struct layer2 *l2;
if (!mgr->up)
return NULL;
if ((tei >= 0) && (tei < 64))
test_and_set_bit(OPTION_L2_FIXEDTEI, &opt);
if (mgr->ch.st->dev->Dprotocols
& ((1 << ISDN_P_TE_E1) | (1 << ISDN_P_NT_E1)))
test_and_set_bit(OPTION_L2_PMX, &opt);
l2 = create_l2(mgr->up, ISDN_P_LAPD_NT, opt, tei, sapi);
if (!l2) {
printk(KERN_WARNING "%s:no memory for layer2\n", __func__);
return NULL;
}
l2->tm = kzalloc(sizeof(struct teimgr), GFP_KERNEL);
if (!l2->tm) {
kfree(l2);
printk(KERN_WARNING "%s:no memory for teimgr\n", __func__);
return NULL;
}
l2->tm->mgr = mgr;
l2->tm->l2 = l2;
l2->tm->tei_m.debug = *debug & DEBUG_L2_TEIFSM;
l2->tm->tei_m.userdata = l2->tm;
l2->tm->tei_m.printdebug = tei_debug;
l2->tm->tei_m.fsm = &teifsmn;
l2->tm->tei_m.state = ST_TEI_NOP;
l2->tm->tval = 2000; /* T202 2 sec */
mISDN_FsmInitTimer(&l2->tm->tei_m, &l2->tm->timer);
write_lock_irqsave(&mgr->lock, flags);
id = get_free_id(mgr);
list_add_tail(&l2->list, &mgr->layer2);
write_unlock_irqrestore(&mgr->lock, flags);
if (id < 0) {
l2->ch.ctrl(&l2->ch, CLOSE_CHANNEL, NULL);
printk(KERN_WARNING "%s:no free id\n", __func__);
return NULL;
} else {
l2->ch.nr = id;
__add_layer2(&l2->ch, mgr->ch.st);
l2->ch.recv = mgr->ch.recv;
l2->ch.peer = mgr->ch.peer;
l2->ch.ctrl(&l2->ch, OPEN_CHANNEL, NULL);
}
return l2;
}
static void
new_tei_req(struct manager *mgr, u_char *dp)
{
int tei, ri;
struct layer2 *l2;
ri = dp[0] << 8;
ri += dp[1];
if (!mgr->up)
goto denied;
if (!(dp[3] & 1)) /* Extension bit != 1 */
goto denied;
if (dp[3] != 0xff)
tei = dp[3] >> 1; /* 3GPP TS 08.56 6.1.11.2 */
else
tei = get_free_tei(mgr);
if (tei < 0) {
printk(KERN_WARNING "%s:No free tei\n", __func__);
goto denied;
}
l2 = create_new_tei(mgr, tei, CTRL_SAPI);
if (!l2)
goto denied;
else
mISDN_FsmEvent(&l2->tm->tei_m, EV_ASSIGN_REQ, dp);
return;
denied:
put_tei_msg(mgr, ID_DENIED, ri, GROUP_TEI);
}
static int
ph_data_ind(struct manager *mgr, struct sk_buff *skb)
{
int ret = -EINVAL;
struct layer2 *l2, *nl2;
u_char mt;
if (skb->len < 8) {
if (*debug & DEBUG_L2_TEI)
printk(KERN_DEBUG "%s: short mgr frame %d/8\n",
__func__, skb->len);
goto done;
}
if ((skb->data[0] >> 2) != TEI_SAPI) /* not for us */
goto done;
if (skb->data[0] & 1) /* EA0 formal error */
goto done;
if (!(skb->data[1] & 1)) /* EA1 formal error */
goto done;
if ((skb->data[1] >> 1) != GROUP_TEI) /* not for us */
goto done;
if ((skb->data[2] & 0xef) != UI) /* not UI */
goto done;
if (skb->data[3] != TEI_ENTITY_ID) /* not tei entity */
goto done;
mt = skb->data[6];
switch (mt) {
case ID_REQUEST:
case ID_CHK_RES:
case ID_VERIFY:
if (!test_bit(MGR_OPT_NETWORK, &mgr->options))
goto done;
break;
case ID_ASSIGNED:
case ID_DENIED:
case ID_CHK_REQ:
case ID_REMOVE:
if (test_bit(MGR_OPT_NETWORK, &mgr->options))
goto done;
break;
default:
goto done;
}
ret = 0;
if (mt == ID_REQUEST) {
new_tei_req(mgr, &skb->data[4]);
goto done;
}
list_for_each_entry_safe(l2, nl2, &mgr->layer2, list) {
tei_ph_data_ind(l2->tm, mt, &skb->data[4], skb->len - 4);
}
done:
return ret;
}
int
l2_tei(struct layer2 *l2, u_int cmd, u_long arg)
{
struct teimgr *tm = l2->tm;
if (test_bit(FLG_FIXED_TEI, &l2->flag))
return 0;
if (*debug & DEBUG_L2_TEI)
printk(KERN_DEBUG "%s: cmd(%x)\n", __func__, cmd);
switch (cmd) {
case MDL_ASSIGN_IND:
mISDN_FsmEvent(&tm->tei_m, EV_IDREQ, NULL);
break;
case MDL_ERROR_IND:
if (test_bit(MGR_OPT_NETWORK, &tm->mgr->options))
mISDN_FsmEvent(&tm->tei_m, EV_CHKREQ, &l2->tei);
if (test_bit(MGR_OPT_USER, &tm->mgr->options))
mISDN_FsmEvent(&tm->tei_m, EV_VERIFY, NULL);
break;
case MDL_STATUS_UP_IND:
if (test_bit(MGR_OPT_NETWORK, &tm->mgr->options))
mISDN_FsmEvent(&tm->mgr->deact, EV_ACTIVATE, NULL);
break;
case MDL_STATUS_DOWN_IND:
if (test_bit(MGR_OPT_NETWORK, &tm->mgr->options))
mISDN_FsmEvent(&tm->mgr->deact, EV_DEACTIVATE, NULL);
break;
case MDL_STATUS_UI_IND:
if (test_bit(MGR_OPT_NETWORK, &tm->mgr->options))
mISDN_FsmEvent(&tm->mgr->deact, EV_UI, NULL);
break;
}
return 0;
}
void
TEIrelease(struct layer2 *l2)
{
struct teimgr *tm = l2->tm;
u_long flags;
mISDN_FsmDelTimer(&tm->timer, 1);
write_lock_irqsave(&tm->mgr->lock, flags);
list_del(&l2->list);
write_unlock_irqrestore(&tm->mgr->lock, flags);
l2->tm = NULL;
kfree(tm);
}
static int
create_teimgr(struct manager *mgr, struct channel_req *crq)
{
struct layer2 *l2;
u_long opt = 0;
u_long flags;
int id;
if (*debug & DEBUG_L2_TEI)
printk(KERN_DEBUG "%s: %s proto(%x) adr(%d %d %d %d)\n",
__func__, dev_name(&mgr->ch.st->dev->dev),
crq->protocol, crq->adr.dev, crq->adr.channel,
crq->adr.sapi, crq->adr.tei);
if (crq->adr.tei > GROUP_TEI)
return -EINVAL;
if (crq->adr.tei < 64)
test_and_set_bit(OPTION_L2_FIXEDTEI, &opt);
if (crq->adr.tei == 0)
test_and_set_bit(OPTION_L2_PTP, &opt);
if (test_bit(MGR_OPT_NETWORK, &mgr->options)) {
if (crq->protocol == ISDN_P_LAPD_TE)
return -EPROTONOSUPPORT;
if ((crq->adr.tei != 0) && (crq->adr.tei != 127))
return -EINVAL;
if (mgr->up) {
printk(KERN_WARNING
"%s: only one network manager is allowed\n",
__func__);
return -EBUSY;
}
} else if (test_bit(MGR_OPT_USER, &mgr->options)) {
if (crq->protocol == ISDN_P_LAPD_NT)
return -EPROTONOSUPPORT;
if ((crq->adr.tei >= 64) && (crq->adr.tei < GROUP_TEI))
return -EINVAL; /* dyn tei */
} else {
if (crq->protocol == ISDN_P_LAPD_NT)
test_and_set_bit(MGR_OPT_NETWORK, &mgr->options);
if (crq->protocol == ISDN_P_LAPD_TE)
test_and_set_bit(MGR_OPT_USER, &mgr->options);
}
if (mgr->ch.st->dev->Dprotocols
& ((1 << ISDN_P_TE_E1) | (1 << ISDN_P_NT_E1)))
test_and_set_bit(OPTION_L2_PMX, &opt);
if ((crq->protocol == ISDN_P_LAPD_NT) && (crq->adr.tei == 127)) {
mgr->up = crq->ch;
id = DL_INFO_L2_CONNECT;
teiup_create(mgr, DL_INFORMATION_IND, sizeof(id), &id);
crq->ch = NULL;
if (!list_empty(&mgr->layer2)) {
read_lock_irqsave(&mgr->lock, flags);
list_for_each_entry(l2, &mgr->layer2, list) {
l2->up = mgr->up;
l2->ch.ctrl(&l2->ch, OPEN_CHANNEL, NULL);
}
read_unlock_irqrestore(&mgr->lock, flags);
}
return 0;
}
l2 = create_l2(crq->ch, crq->protocol, opt,
crq->adr.tei, crq->adr.sapi);
if (!l2)
return -ENOMEM;
l2->tm = kzalloc(sizeof(struct teimgr), GFP_KERNEL);
if (!l2->tm) {
kfree(l2);
printk(KERN_ERR "kmalloc teimgr failed\n");
return -ENOMEM;
}
l2->tm->mgr = mgr;
l2->tm->l2 = l2;
l2->tm->tei_m.debug = *debug & DEBUG_L2_TEIFSM;
l2->tm->tei_m.userdata = l2->tm;
l2->tm->tei_m.printdebug = tei_debug;
if (crq->protocol == ISDN_P_LAPD_TE) {
l2->tm->tei_m.fsm = &teifsmu;
l2->tm->tei_m.state = ST_TEI_NOP;
l2->tm->tval = 1000; /* T201 1 sec */
} else {
l2->tm->tei_m.fsm = &teifsmn;
l2->tm->tei_m.state = ST_TEI_NOP;
l2->tm->tval = 2000; /* T202 2 sec */
}
mISDN_FsmInitTimer(&l2->tm->tei_m, &l2->tm->timer);
write_lock_irqsave(&mgr->lock, flags);
id = get_free_id(mgr);
list_add_tail(&l2->list, &mgr->layer2);
write_unlock_irqrestore(&mgr->lock, flags);
if (id < 0) {
l2->ch.ctrl(&l2->ch, CLOSE_CHANNEL, NULL);
} else {
l2->ch.nr = id;
l2->up->nr = id;
crq->ch = &l2->ch;
id = 0;
}
return id;
}
static int
mgr_send(struct mISDNchannel *ch, struct sk_buff *skb)
{
struct manager *mgr;
struct mISDNhead *hh = mISDN_HEAD_P(skb);
int ret = -EINVAL;
mgr = container_of(ch, struct manager, ch);
if (*debug & DEBUG_L2_RECV)
printk(KERN_DEBUG "%s: prim(%x) id(%x)\n",
__func__, hh->prim, hh->id);
switch (hh->prim) {
case PH_DATA_IND:
mISDN_FsmEvent(&mgr->deact, EV_UI, NULL);
ret = ph_data_ind(mgr, skb);
break;
case PH_DATA_CNF:
do_ack(mgr, hh->id);
ret = 0;
break;
case PH_ACTIVATE_IND:
test_and_set_bit(MGR_PH_ACTIVE, &mgr->options);
mISDN_FsmEvent(&mgr->deact, EV_ACTIVATE_IND, NULL);
do_send(mgr);
ret = 0;
break;
case PH_DEACTIVATE_IND:
test_and_clear_bit(MGR_PH_ACTIVE, &mgr->options);
mISDN_FsmEvent(&mgr->deact, EV_DEACTIVATE_IND, NULL);
ret = 0;
break;
case DL_UNITDATA_REQ:
return dl_unit_data(mgr, skb);
}
if (!ret)
dev_kfree_skb(skb);
return ret;
}
static int
free_teimanager(struct manager *mgr)
{
struct layer2 *l2, *nl2;
test_and_clear_bit(OPTION_L1_HOLD, &mgr->options);
if (test_bit(MGR_OPT_NETWORK, &mgr->options)) {
/* not locked lock is taken in release tei */
mgr->up = NULL;
if (test_bit(OPTION_L2_CLEANUP, &mgr->options)) {
list_for_each_entry_safe(l2, nl2, &mgr->layer2, list) {
put_tei_msg(mgr, ID_REMOVE, 0, l2->tei);
mutex_lock(&mgr->ch.st->lmutex);
list_del(&l2->ch.list);
mutex_unlock(&mgr->ch.st->lmutex);
l2->ch.ctrl(&l2->ch, CLOSE_CHANNEL, NULL);
}
test_and_clear_bit(MGR_OPT_NETWORK, &mgr->options);
} else {
list_for_each_entry_safe(l2, nl2, &mgr->layer2, list) {
l2->up = NULL;
}
}
}
if (test_bit(MGR_OPT_USER, &mgr->options)) {
if (list_empty(&mgr->layer2))
test_and_clear_bit(MGR_OPT_USER, &mgr->options);
}
mgr->ch.st->dev->D.ctrl(&mgr->ch.st->dev->D, CLOSE_CHANNEL, NULL);
return 0;
}
static int
ctrl_teimanager(struct manager *mgr, void *arg)
{
/* currently we only have one option */
int *val = (int *)arg;
int ret = 0;
switch (val[0]) {
case IMCLEAR_L2:
if (val[1])
test_and_set_bit(OPTION_L2_CLEANUP, &mgr->options);
else
test_and_clear_bit(OPTION_L2_CLEANUP, &mgr->options);
break;
case IMHOLD_L1:
if (val[1])
test_and_set_bit(OPTION_L1_HOLD, &mgr->options);
else
test_and_clear_bit(OPTION_L1_HOLD, &mgr->options);
break;
default:
ret = -EINVAL;
}
return ret;
}
/* This function does create a L2 for fixed TEI in NT Mode */
static int
check_data(struct manager *mgr, struct sk_buff *skb)
{
struct mISDNhead *hh = mISDN_HEAD_P(skb);
int ret, tei, sapi;
struct layer2 *l2;
if (*debug & DEBUG_L2_CTRL)
printk(KERN_DEBUG "%s: prim(%x) id(%x)\n",
__func__, hh->prim, hh->id);
if (test_bit(MGR_OPT_USER, &mgr->options))
return -ENOTCONN;
if (hh->prim != PH_DATA_IND)
return -ENOTCONN;
if (skb->len != 3)
return -ENOTCONN;
if (skb->data[0] & 3) /* EA0 and CR must be 0 */
return -EINVAL;
sapi = skb->data[0] >> 2;
if (!(skb->data[1] & 1)) /* invalid EA1 */
return -EINVAL;
tei = skb->data[1] >> 1;
if (tei > 63) /* not a fixed tei */
return -ENOTCONN;
if ((skb->data[2] & ~0x10) != SABME)
return -ENOTCONN;
/* We got a SABME for a fixed TEI */
if (*debug & DEBUG_L2_CTRL)
printk(KERN_DEBUG "%s: SABME sapi(%d) tei(%d)\n",
__func__, sapi, tei);
l2 = create_new_tei(mgr, tei, sapi);
if (!l2) {
if (*debug & DEBUG_L2_CTRL)
printk(KERN_DEBUG "%s: failed to create new tei\n",
__func__);
return -ENOMEM;
}
ret = l2->ch.send(&l2->ch, skb);
return ret;
}
void
delete_teimanager(struct mISDNchannel *ch)
{
struct manager *mgr;
struct layer2 *l2, *nl2;
mgr = container_of(ch, struct manager, ch);
/* not locked lock is taken in release tei */
list_for_each_entry_safe(l2, nl2, &mgr->layer2, list) {
mutex_lock(&mgr->ch.st->lmutex);
list_del(&l2->ch.list);
mutex_unlock(&mgr->ch.st->lmutex);
l2->ch.ctrl(&l2->ch, CLOSE_CHANNEL, NULL);
}
list_del(&mgr->ch.list);
list_del(&mgr->bcast.list);
skb_queue_purge(&mgr->sendq);
kfree(mgr);
}
static int
mgr_ctrl(struct mISDNchannel *ch, u_int cmd, void *arg)
{
struct manager *mgr;
int ret = -EINVAL;
mgr = container_of(ch, struct manager, ch);
if (*debug & DEBUG_L2_CTRL)
printk(KERN_DEBUG "%s(%x, %p)\n", __func__, cmd, arg);
switch (cmd) {
case OPEN_CHANNEL:
ret = create_teimgr(mgr, arg);
break;
case CLOSE_CHANNEL:
ret = free_teimanager(mgr);
break;
case CONTROL_CHANNEL:
ret = ctrl_teimanager(mgr, arg);
break;
case CHECK_DATA:
ret = check_data(mgr, arg);
break;
}
return ret;
}
static int
mgr_bcast(struct mISDNchannel *ch, struct sk_buff *skb)
{
struct manager *mgr = container_of(ch, struct manager, bcast);
struct mISDNhead *hh = mISDN_HEAD_P(skb);
struct sk_buff *cskb = NULL;
struct layer2 *l2;
u_long flags;
int ret;
read_lock_irqsave(&mgr->lock, flags);
list_for_each_entry(l2, &mgr->layer2, list) {
if ((hh->id & MISDN_ID_SAPI_MASK) ==
(l2->ch.addr & MISDN_ID_SAPI_MASK)) {
if (list_is_last(&l2->list, &mgr->layer2)) {
cskb = skb;
skb = NULL;
} else {
if (!cskb)
cskb = skb_copy(skb, GFP_KERNEL);
}
if (cskb) {
ret = l2->ch.send(&l2->ch, cskb);
if (ret) {
if (*debug & DEBUG_SEND_ERR)
printk(KERN_DEBUG
"%s ch%d prim(%x) addr(%x)"
" err %d\n",
__func__, l2->ch.nr,
hh->prim, l2->ch.addr, ret);
} else
cskb = NULL;
} else {
printk(KERN_WARNING "%s ch%d addr %x no mem\n",
__func__, ch->nr, ch->addr);
goto out;
}
}
}
out:
read_unlock_irqrestore(&mgr->lock, flags);
if (cskb)
dev_kfree_skb(cskb);
if (skb)
dev_kfree_skb(skb);
return 0;
}
static int
mgr_bcast_ctrl(struct mISDNchannel *ch, u_int cmd, void *arg)
{
return -EINVAL;
}
int
create_teimanager(struct mISDNdevice *dev)
{
struct manager *mgr;
mgr = kzalloc(sizeof(struct manager), GFP_KERNEL);
if (!mgr)
return -ENOMEM;
INIT_LIST_HEAD(&mgr->layer2);
rwlock_init(&mgr->lock);
skb_queue_head_init(&mgr->sendq);
mgr->nextid = 1;
mgr->lastid = MISDN_ID_NONE;
mgr->ch.send = mgr_send;
mgr->ch.ctrl = mgr_ctrl;
mgr->ch.st = dev->D.st;
set_channel_address(&mgr->ch, TEI_SAPI, GROUP_TEI);
add_layer2(&mgr->ch, dev->D.st);
mgr->bcast.send = mgr_bcast;
mgr->bcast.ctrl = mgr_bcast_ctrl;
mgr->bcast.st = dev->D.st;
set_channel_address(&mgr->bcast, 0, GROUP_TEI);
add_layer2(&mgr->bcast, dev->D.st);
mgr->deact.debug = *debug & DEBUG_MANAGER;
mgr->deact.userdata = mgr;
mgr->deact.printdebug = da_debug;
mgr->deact.fsm = &deactfsm;
mgr->deact.state = ST_L1_DEACT;
mISDN_FsmInitTimer(&mgr->deact, &mgr->datimer);
dev->teimgr = &mgr->ch;
return 0;
}
int TEIInit(u_int *deb)
{
debug = deb;
teifsmu.state_count = TEI_STATE_COUNT;
teifsmu.event_count = TEI_EVENT_COUNT;
teifsmu.strEvent = strTeiEvent;
teifsmu.strState = strTeiState;
mISDN_FsmNew(&teifsmu, TeiFnListUser, ARRAY_SIZE(TeiFnListUser));
teifsmn.state_count = TEI_STATE_COUNT;
teifsmn.event_count = TEI_EVENT_COUNT;
teifsmn.strEvent = strTeiEvent;
teifsmn.strState = strTeiState;
mISDN_FsmNew(&teifsmn, TeiFnListNet, ARRAY_SIZE(TeiFnListNet));
deactfsm.state_count = DEACT_STATE_COUNT;
deactfsm.event_count = DEACT_EVENT_COUNT;
deactfsm.strEvent = strDeactEvent;
deactfsm.strState = strDeactState;
mISDN_FsmNew(&deactfsm, DeactFnList, ARRAY_SIZE(DeactFnList));
return 0;
}
void TEIFree(void)
{
mISDN_FsmFree(&teifsmu);
mISDN_FsmFree(&teifsmn);
mISDN_FsmFree(&deactfsm);
}
| gpl-2.0 |
davidmueller13/lt03lte_tw_kernel_5.1.1 | drivers/isdn/hardware/mISDN/hfcmulti.c | 4809 | 153691 | /*
* hfcmulti.c low level driver for hfc-4s/hfc-8s/hfc-e1 based cards
*
* Author Andreas Eversberg (jolly@eversberg.eu)
* ported to mqueue mechanism:
* Peter Sprenger (sprengermoving-bytes.de)
*
* inspired by existing hfc-pci driver:
* Copyright 1999 by Werner Cornelius (werner@isdn-development.de)
* Copyright 2008 by Karsten Keil (kkeil@suse.de)
* Copyright 2008 by Andreas Eversberg (jolly@eversberg.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, 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.
*
*
* Thanks to Cologne Chip AG for this great controller!
*/
/*
* module parameters:
* type:
* By default (0), the card is automatically detected.
* Or use the following combinations:
* Bit 0-7 = 0x00001 = HFC-E1 (1 port)
* or Bit 0-7 = 0x00004 = HFC-4S (4 ports)
* or Bit 0-7 = 0x00008 = HFC-8S (8 ports)
* Bit 8 = 0x00100 = uLaw (instead of aLaw)
* Bit 9 = 0x00200 = Disable DTMF detect on all B-channels via hardware
* Bit 10 = spare
* Bit 11 = 0x00800 = Force PCM bus into slave mode. (otherwhise auto)
* or Bit 12 = 0x01000 = Force PCM bus into master mode. (otherwhise auto)
* Bit 13 = spare
* Bit 14 = 0x04000 = Use external ram (128K)
* Bit 15 = 0x08000 = Use external ram (512K)
* Bit 16 = 0x10000 = Use 64 timeslots instead of 32
* or Bit 17 = 0x20000 = Use 128 timeslots instead of anything else
* Bit 18 = spare
* Bit 19 = 0x80000 = Send the Watchdog a Signal (Dual E1 with Watchdog)
* (all other bits are reserved and shall be 0)
* example: 0x20204 one HFC-4S with dtmf detection and 128 timeslots on PCM
* bus (PCM master)
*
* port: (optional or required for all ports on all installed cards)
* HFC-4S/HFC-8S only bits:
* Bit 0 = 0x001 = Use master clock for this S/T interface
* (ony once per chip).
* Bit 1 = 0x002 = transmitter line setup (non capacitive mode)
* Don't use this unless you know what you are doing!
* Bit 2 = 0x004 = Disable E-channel. (No E-channel processing)
* example: 0x0001,0x0000,0x0000,0x0000 one HFC-4S with master clock
* received from port 1
*
* HFC-E1 only bits:
* Bit 0 = 0x0001 = interface: 0=copper, 1=optical
* Bit 1 = 0x0002 = reserved (later for 32 B-channels transparent mode)
* Bit 2 = 0x0004 = Report LOS
* Bit 3 = 0x0008 = Report AIS
* Bit 4 = 0x0010 = Report SLIP
* Bit 5 = 0x0020 = Report RDI
* Bit 8 = 0x0100 = Turn off CRC-4 Multiframe Mode, use double frame
* mode instead.
* Bit 9 = 0x0200 = Force get clock from interface, even in NT mode.
* or Bit 10 = 0x0400 = Force put clock to interface, even in TE mode.
* Bit 11 = 0x0800 = Use direct RX clock for PCM sync rather than PLL.
* (E1 only)
* Bit 12-13 = 0xX000 = elastic jitter buffer (1-3), Set both bits to 0
* for default.
* (all other bits are reserved and shall be 0)
*
* debug:
* NOTE: only one debug value must be given for all cards
* enable debugging (see hfc_multi.h for debug options)
*
* poll:
* NOTE: only one poll value must be given for all cards
* Give the number of samples for each fifo process.
* By default 128 is used. Decrease to reduce delay, increase to
* reduce cpu load. If unsure, don't mess with it!
* Valid is 8, 16, 32, 64, 128, 256.
*
* pcm:
* NOTE: only one pcm value must be given for every card.
* The PCM bus id tells the mISDNdsp module about the connected PCM bus.
* By default (0), the PCM bus id is 100 for the card that is PCM master.
* If multiple cards are PCM master (because they are not interconnected),
* each card with PCM master will have increasing PCM id.
* All PCM busses with the same ID are expected to be connected and have
* common time slots slots.
* Only one chip of the PCM bus must be master, the others slave.
* -1 means no support of PCM bus not even.
* Omit this value, if all cards are interconnected or none is connected.
* If unsure, don't give this parameter.
*
* dslot:
* NOTE: only one dslot value must be given for every card.
* Also this value must be given for non-E1 cards. If omitted, the E1
* card has D-channel on time slot 16, which is default.
* If 1..15 or 17..31, an alternate time slot is used for D-channel.
* In this case, the application must be able to handle this.
* If -1 is given, the D-channel is disabled and all 31 slots can be used
* for B-channel. (only for specific applications)
* If you don't know how to use it, you don't need it!
*
* iomode:
* NOTE: only one mode value must be given for every card.
* -> See hfc_multi.h for HFC_IO_MODE_* values
* By default, the IO mode is pci memory IO (MEMIO).
* Some cards require specific IO mode, so it cannot be changed.
* It may be useful to set IO mode to register io (REGIO) to solve
* PCI bridge problems.
* If unsure, don't give this parameter.
*
* clockdelay_nt:
* NOTE: only one clockdelay_nt value must be given once for all cards.
* Give the value of the clock control register (A_ST_CLK_DLY)
* of the S/T interfaces in NT mode.
* This register is needed for the TBR3 certification, so don't change it.
*
* clockdelay_te:
* NOTE: only one clockdelay_te value must be given once
* Give the value of the clock control register (A_ST_CLK_DLY)
* of the S/T interfaces in TE mode.
* This register is needed for the TBR3 certification, so don't change it.
*
* clock:
* NOTE: only one clock value must be given once
* Selects interface with clock source for mISDN and applications.
* Set to card number starting with 1. Set to -1 to disable.
* By default, the first card is used as clock source.
*
* hwid:
* NOTE: only one hwid value must be given once
* Enable special embedded devices with XHFC controllers.
*/
/*
* debug register access (never use this, it will flood your system log)
* #define HFC_REGISTER_DEBUG
*/
#define HFC_MULTI_VERSION "2.03"
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/mISDNhw.h>
#include <linux/mISDNdsp.h>
/*
#define IRQCOUNT_DEBUG
#define IRQ_DEBUG
*/
#include "hfc_multi.h"
#ifdef ECHOPREP
#include "gaintab.h"
#endif
#define MAX_CARDS 8
#define MAX_PORTS (8 * MAX_CARDS)
static LIST_HEAD(HFClist);
static spinlock_t HFClock; /* global hfc list lock */
static void ph_state_change(struct dchannel *);
static struct hfc_multi *syncmaster;
static int plxsd_master; /* if we have a master card (yet) */
static spinlock_t plx_lock; /* may not acquire other lock inside */
#define TYP_E1 1
#define TYP_4S 4
#define TYP_8S 8
static int poll_timer = 6; /* default = 128 samples = 16ms */
/* number of POLL_TIMER interrupts for G2 timeout (ca 1s) */
static int nt_t1_count[] = { 3840, 1920, 960, 480, 240, 120, 60, 30 };
#define CLKDEL_TE 0x0f /* CLKDEL in TE mode */
#define CLKDEL_NT 0x6c /* CLKDEL in NT mode
(0x60 MUST be included!) */
#define DIP_4S 0x1 /* DIP Switches for Beronet 1S/2S/4S cards */
#define DIP_8S 0x2 /* DIP Switches for Beronet 8S+ cards */
#define DIP_E1 0x3 /* DIP Switches for Beronet E1 cards */
/*
* module stuff
*/
static uint type[MAX_CARDS];
static int pcm[MAX_CARDS];
static int dslot[MAX_CARDS];
static uint iomode[MAX_CARDS];
static uint port[MAX_PORTS];
static uint debug;
static uint poll;
static int clock;
static uint timer;
static uint clockdelay_te = CLKDEL_TE;
static uint clockdelay_nt = CLKDEL_NT;
#define HWID_NONE 0
#define HWID_MINIP4 1
#define HWID_MINIP8 2
#define HWID_MINIP16 3
static uint hwid = HWID_NONE;
static int HFC_cnt, Port_cnt, PCM_cnt = 99;
MODULE_AUTHOR("Andreas Eversberg");
MODULE_LICENSE("GPL");
MODULE_VERSION(HFC_MULTI_VERSION);
module_param(debug, uint, S_IRUGO | S_IWUSR);
module_param(poll, uint, S_IRUGO | S_IWUSR);
module_param(clock, int, S_IRUGO | S_IWUSR);
module_param(timer, uint, S_IRUGO | S_IWUSR);
module_param(clockdelay_te, uint, S_IRUGO | S_IWUSR);
module_param(clockdelay_nt, uint, S_IRUGO | S_IWUSR);
module_param_array(type, uint, NULL, S_IRUGO | S_IWUSR);
module_param_array(pcm, int, NULL, S_IRUGO | S_IWUSR);
module_param_array(dslot, int, NULL, S_IRUGO | S_IWUSR);
module_param_array(iomode, uint, NULL, S_IRUGO | S_IWUSR);
module_param_array(port, uint, NULL, S_IRUGO | S_IWUSR);
module_param(hwid, uint, S_IRUGO | S_IWUSR); /* The hardware ID */
#ifdef HFC_REGISTER_DEBUG
#define HFC_outb(hc, reg, val) \
(hc->HFC_outb(hc, reg, val, __func__, __LINE__))
#define HFC_outb_nodebug(hc, reg, val) \
(hc->HFC_outb_nodebug(hc, reg, val, __func__, __LINE__))
#define HFC_inb(hc, reg) \
(hc->HFC_inb(hc, reg, __func__, __LINE__))
#define HFC_inb_nodebug(hc, reg) \
(hc->HFC_inb_nodebug(hc, reg, __func__, __LINE__))
#define HFC_inw(hc, reg) \
(hc->HFC_inw(hc, reg, __func__, __LINE__))
#define HFC_inw_nodebug(hc, reg) \
(hc->HFC_inw_nodebug(hc, reg, __func__, __LINE__))
#define HFC_wait(hc) \
(hc->HFC_wait(hc, __func__, __LINE__))
#define HFC_wait_nodebug(hc) \
(hc->HFC_wait_nodebug(hc, __func__, __LINE__))
#else
#define HFC_outb(hc, reg, val) (hc->HFC_outb(hc, reg, val))
#define HFC_outb_nodebug(hc, reg, val) (hc->HFC_outb_nodebug(hc, reg, val))
#define HFC_inb(hc, reg) (hc->HFC_inb(hc, reg))
#define HFC_inb_nodebug(hc, reg) (hc->HFC_inb_nodebug(hc, reg))
#define HFC_inw(hc, reg) (hc->HFC_inw(hc, reg))
#define HFC_inw_nodebug(hc, reg) (hc->HFC_inw_nodebug(hc, reg))
#define HFC_wait(hc) (hc->HFC_wait(hc))
#define HFC_wait_nodebug(hc) (hc->HFC_wait_nodebug(hc))
#endif
#ifdef CONFIG_MISDN_HFCMULTI_8xx
#include "hfc_multi_8xx.h"
#endif
/* HFC_IO_MODE_PCIMEM */
static void
#ifdef HFC_REGISTER_DEBUG
HFC_outb_pcimem(struct hfc_multi *hc, u_char reg, u_char val,
const char *function, int line)
#else
HFC_outb_pcimem(struct hfc_multi *hc, u_char reg, u_char val)
#endif
{
writeb(val, hc->pci_membase + reg);
}
static u_char
#ifdef HFC_REGISTER_DEBUG
HFC_inb_pcimem(struct hfc_multi *hc, u_char reg, const char *function, int line)
#else
HFC_inb_pcimem(struct hfc_multi *hc, u_char reg)
#endif
{
return readb(hc->pci_membase + reg);
}
static u_short
#ifdef HFC_REGISTER_DEBUG
HFC_inw_pcimem(struct hfc_multi *hc, u_char reg, const char *function, int line)
#else
HFC_inw_pcimem(struct hfc_multi *hc, u_char reg)
#endif
{
return readw(hc->pci_membase + reg);
}
static void
#ifdef HFC_REGISTER_DEBUG
HFC_wait_pcimem(struct hfc_multi *hc, const char *function, int line)
#else
HFC_wait_pcimem(struct hfc_multi *hc)
#endif
{
while (readb(hc->pci_membase + R_STATUS) & V_BUSY)
cpu_relax();
}
/* HFC_IO_MODE_REGIO */
static void
#ifdef HFC_REGISTER_DEBUG
HFC_outb_regio(struct hfc_multi *hc, u_char reg, u_char val,
const char *function, int line)
#else
HFC_outb_regio(struct hfc_multi *hc, u_char reg, u_char val)
#endif
{
outb(reg, hc->pci_iobase + 4);
outb(val, hc->pci_iobase);
}
static u_char
#ifdef HFC_REGISTER_DEBUG
HFC_inb_regio(struct hfc_multi *hc, u_char reg, const char *function, int line)
#else
HFC_inb_regio(struct hfc_multi *hc, u_char reg)
#endif
{
outb(reg, hc->pci_iobase + 4);
return inb(hc->pci_iobase);
}
static u_short
#ifdef HFC_REGISTER_DEBUG
HFC_inw_regio(struct hfc_multi *hc, u_char reg, const char *function, int line)
#else
HFC_inw_regio(struct hfc_multi *hc, u_char reg)
#endif
{
outb(reg, hc->pci_iobase + 4);
return inw(hc->pci_iobase);
}
static void
#ifdef HFC_REGISTER_DEBUG
HFC_wait_regio(struct hfc_multi *hc, const char *function, int line)
#else
HFC_wait_regio(struct hfc_multi *hc)
#endif
{
outb(R_STATUS, hc->pci_iobase + 4);
while (inb(hc->pci_iobase) & V_BUSY)
cpu_relax();
}
#ifdef HFC_REGISTER_DEBUG
static void
HFC_outb_debug(struct hfc_multi *hc, u_char reg, u_char val,
const char *function, int line)
{
char regname[256] = "", bits[9] = "xxxxxxxx";
int i;
i = -1;
while (hfc_register_names[++i].name) {
if (hfc_register_names[i].reg == reg)
strcat(regname, hfc_register_names[i].name);
}
if (regname[0] == '\0')
strcpy(regname, "register");
bits[7] = '0' + (!!(val & 1));
bits[6] = '0' + (!!(val & 2));
bits[5] = '0' + (!!(val & 4));
bits[4] = '0' + (!!(val & 8));
bits[3] = '0' + (!!(val & 16));
bits[2] = '0' + (!!(val & 32));
bits[1] = '0' + (!!(val & 64));
bits[0] = '0' + (!!(val & 128));
printk(KERN_DEBUG
"HFC_outb(chip %d, %02x=%s, 0x%02x=%s); in %s() line %d\n",
hc->id, reg, regname, val, bits, function, line);
HFC_outb_nodebug(hc, reg, val);
}
static u_char
HFC_inb_debug(struct hfc_multi *hc, u_char reg, const char *function, int line)
{
char regname[256] = "", bits[9] = "xxxxxxxx";
u_char val = HFC_inb_nodebug(hc, reg);
int i;
i = 0;
while (hfc_register_names[i++].name)
;
while (hfc_register_names[++i].name) {
if (hfc_register_names[i].reg == reg)
strcat(regname, hfc_register_names[i].name);
}
if (regname[0] == '\0')
strcpy(regname, "register");
bits[7] = '0' + (!!(val & 1));
bits[6] = '0' + (!!(val & 2));
bits[5] = '0' + (!!(val & 4));
bits[4] = '0' + (!!(val & 8));
bits[3] = '0' + (!!(val & 16));
bits[2] = '0' + (!!(val & 32));
bits[1] = '0' + (!!(val & 64));
bits[0] = '0' + (!!(val & 128));
printk(KERN_DEBUG
"HFC_inb(chip %d, %02x=%s) = 0x%02x=%s; in %s() line %d\n",
hc->id, reg, regname, val, bits, function, line);
return val;
}
static u_short
HFC_inw_debug(struct hfc_multi *hc, u_char reg, const char *function, int line)
{
char regname[256] = "";
u_short val = HFC_inw_nodebug(hc, reg);
int i;
i = 0;
while (hfc_register_names[i++].name)
;
while (hfc_register_names[++i].name) {
if (hfc_register_names[i].reg == reg)
strcat(regname, hfc_register_names[i].name);
}
if (regname[0] == '\0')
strcpy(regname, "register");
printk(KERN_DEBUG
"HFC_inw(chip %d, %02x=%s) = 0x%04x; in %s() line %d\n",
hc->id, reg, regname, val, function, line);
return val;
}
static void
HFC_wait_debug(struct hfc_multi *hc, const char *function, int line)
{
printk(KERN_DEBUG "HFC_wait(chip %d); in %s() line %d\n",
hc->id, function, line);
HFC_wait_nodebug(hc);
}
#endif
/* write fifo data (REGIO) */
static void
write_fifo_regio(struct hfc_multi *hc, u_char *data, int len)
{
outb(A_FIFO_DATA0, (hc->pci_iobase) + 4);
while (len >> 2) {
outl(cpu_to_le32(*(u32 *)data), hc->pci_iobase);
data += 4;
len -= 4;
}
while (len >> 1) {
outw(cpu_to_le16(*(u16 *)data), hc->pci_iobase);
data += 2;
len -= 2;
}
while (len) {
outb(*data, hc->pci_iobase);
data++;
len--;
}
}
/* write fifo data (PCIMEM) */
static void
write_fifo_pcimem(struct hfc_multi *hc, u_char *data, int len)
{
while (len >> 2) {
writel(cpu_to_le32(*(u32 *)data),
hc->pci_membase + A_FIFO_DATA0);
data += 4;
len -= 4;
}
while (len >> 1) {
writew(cpu_to_le16(*(u16 *)data),
hc->pci_membase + A_FIFO_DATA0);
data += 2;
len -= 2;
}
while (len) {
writeb(*data, hc->pci_membase + A_FIFO_DATA0);
data++;
len--;
}
}
/* read fifo data (REGIO) */
static void
read_fifo_regio(struct hfc_multi *hc, u_char *data, int len)
{
outb(A_FIFO_DATA0, (hc->pci_iobase) + 4);
while (len >> 2) {
*(u32 *)data = le32_to_cpu(inl(hc->pci_iobase));
data += 4;
len -= 4;
}
while (len >> 1) {
*(u16 *)data = le16_to_cpu(inw(hc->pci_iobase));
data += 2;
len -= 2;
}
while (len) {
*data = inb(hc->pci_iobase);
data++;
len--;
}
}
/* read fifo data (PCIMEM) */
static void
read_fifo_pcimem(struct hfc_multi *hc, u_char *data, int len)
{
while (len >> 2) {
*(u32 *)data =
le32_to_cpu(readl(hc->pci_membase + A_FIFO_DATA0));
data += 4;
len -= 4;
}
while (len >> 1) {
*(u16 *)data =
le16_to_cpu(readw(hc->pci_membase + A_FIFO_DATA0));
data += 2;
len -= 2;
}
while (len) {
*data = readb(hc->pci_membase + A_FIFO_DATA0);
data++;
len--;
}
}
static void
enable_hwirq(struct hfc_multi *hc)
{
hc->hw.r_irq_ctrl |= V_GLOB_IRQ_EN;
HFC_outb(hc, R_IRQ_CTRL, hc->hw.r_irq_ctrl);
}
static void
disable_hwirq(struct hfc_multi *hc)
{
hc->hw.r_irq_ctrl &= ~((u_char)V_GLOB_IRQ_EN);
HFC_outb(hc, R_IRQ_CTRL, hc->hw.r_irq_ctrl);
}
#define NUM_EC 2
#define MAX_TDM_CHAN 32
inline void
enablepcibridge(struct hfc_multi *c)
{
HFC_outb(c, R_BRG_PCM_CFG, (0x0 << 6) | 0x3); /* was _io before */
}
inline void
disablepcibridge(struct hfc_multi *c)
{
HFC_outb(c, R_BRG_PCM_CFG, (0x0 << 6) | 0x2); /* was _io before */
}
inline unsigned char
readpcibridge(struct hfc_multi *hc, unsigned char address)
{
unsigned short cipv;
unsigned char data;
if (!hc->pci_iobase)
return 0;
/* slow down a PCI read access by 1 PCI clock cycle */
HFC_outb(hc, R_CTRL, 0x4); /*was _io before*/
if (address == 0)
cipv = 0x4000;
else
cipv = 0x5800;
/* select local bridge port address by writing to CIP port */
/* data = HFC_inb(c, cipv); * was _io before */
outw(cipv, hc->pci_iobase + 4);
data = inb(hc->pci_iobase);
/* restore R_CTRL for normal PCI read cycle speed */
HFC_outb(hc, R_CTRL, 0x0); /* was _io before */
return data;
}
inline void
writepcibridge(struct hfc_multi *hc, unsigned char address, unsigned char data)
{
unsigned short cipv;
unsigned int datav;
if (!hc->pci_iobase)
return;
if (address == 0)
cipv = 0x4000;
else
cipv = 0x5800;
/* select local bridge port address by writing to CIP port */
outw(cipv, hc->pci_iobase + 4);
/* define a 32 bit dword with 4 identical bytes for write sequence */
datav = data | ((__u32) data << 8) | ((__u32) data << 16) |
((__u32) data << 24);
/*
* write this 32 bit dword to the bridge data port
* this will initiate a write sequence of up to 4 writes to the same
* address on the local bus interface the number of write accesses
* is undefined but >=1 and depends on the next PCI transaction
* during write sequence on the local bus
*/
outl(datav, hc->pci_iobase);
}
inline void
cpld_set_reg(struct hfc_multi *hc, unsigned char reg)
{
/* Do data pin read low byte */
HFC_outb(hc, R_GPIO_OUT1, reg);
}
inline void
cpld_write_reg(struct hfc_multi *hc, unsigned char reg, unsigned char val)
{
cpld_set_reg(hc, reg);
enablepcibridge(hc);
writepcibridge(hc, 1, val);
disablepcibridge(hc);
return;
}
inline unsigned char
cpld_read_reg(struct hfc_multi *hc, unsigned char reg)
{
unsigned char bytein;
cpld_set_reg(hc, reg);
/* Do data pin read low byte */
HFC_outb(hc, R_GPIO_OUT1, reg);
enablepcibridge(hc);
bytein = readpcibridge(hc, 1);
disablepcibridge(hc);
return bytein;
}
inline void
vpm_write_address(struct hfc_multi *hc, unsigned short addr)
{
cpld_write_reg(hc, 0, 0xff & addr);
cpld_write_reg(hc, 1, 0x01 & (addr >> 8));
}
inline unsigned short
vpm_read_address(struct hfc_multi *c)
{
unsigned short addr;
unsigned short highbit;
addr = cpld_read_reg(c, 0);
highbit = cpld_read_reg(c, 1);
addr = addr | (highbit << 8);
return addr & 0x1ff;
}
inline unsigned char
vpm_in(struct hfc_multi *c, int which, unsigned short addr)
{
unsigned char res;
vpm_write_address(c, addr);
if (!which)
cpld_set_reg(c, 2);
else
cpld_set_reg(c, 3);
enablepcibridge(c);
res = readpcibridge(c, 1);
disablepcibridge(c);
cpld_set_reg(c, 0);
return res;
}
inline void
vpm_out(struct hfc_multi *c, int which, unsigned short addr,
unsigned char data)
{
vpm_write_address(c, addr);
enablepcibridge(c);
if (!which)
cpld_set_reg(c, 2);
else
cpld_set_reg(c, 3);
writepcibridge(c, 1, data);
cpld_set_reg(c, 0);
disablepcibridge(c);
{
unsigned char regin;
regin = vpm_in(c, which, addr);
if (regin != data)
printk(KERN_DEBUG "Wrote 0x%x to register 0x%x but got back "
"0x%x\n", data, addr, regin);
}
}
static void
vpm_init(struct hfc_multi *wc)
{
unsigned char reg;
unsigned int mask;
unsigned int i, x, y;
unsigned int ver;
for (x = 0; x < NUM_EC; x++) {
/* Setup GPIO's */
if (!x) {
ver = vpm_in(wc, x, 0x1a0);
printk(KERN_DEBUG "VPM: Chip %d: ver %02x\n", x, ver);
}
for (y = 0; y < 4; y++) {
vpm_out(wc, x, 0x1a8 + y, 0x00); /* GPIO out */
vpm_out(wc, x, 0x1ac + y, 0x00); /* GPIO dir */
vpm_out(wc, x, 0x1b0 + y, 0x00); /* GPIO sel */
}
/* Setup TDM path - sets fsync and tdm_clk as inputs */
reg = vpm_in(wc, x, 0x1a3); /* misc_con */
vpm_out(wc, x, 0x1a3, reg & ~2);
/* Setup Echo length (256 taps) */
vpm_out(wc, x, 0x022, 1);
vpm_out(wc, x, 0x023, 0xff);
/* Setup timeslots */
vpm_out(wc, x, 0x02f, 0x00);
mask = 0x02020202 << (x * 4);
/* Setup the tdm channel masks for all chips */
for (i = 0; i < 4; i++)
vpm_out(wc, x, 0x33 - i, (mask >> (i << 3)) & 0xff);
/* Setup convergence rate */
printk(KERN_DEBUG "VPM: A-law mode\n");
reg = 0x00 | 0x10 | 0x01;
vpm_out(wc, x, 0x20, reg);
printk(KERN_DEBUG "VPM reg 0x20 is %x\n", reg);
/*vpm_out(wc, x, 0x20, (0x00 | 0x08 | 0x20 | 0x10)); */
vpm_out(wc, x, 0x24, 0x02);
reg = vpm_in(wc, x, 0x24);
printk(KERN_DEBUG "NLP Thresh is set to %d (0x%x)\n", reg, reg);
/* Initialize echo cans */
for (i = 0; i < MAX_TDM_CHAN; i++) {
if (mask & (0x00000001 << i))
vpm_out(wc, x, i, 0x00);
}
/*
* ARM arch at least disallows a udelay of
* more than 2ms... it gives a fake "__bad_udelay"
* reference at link-time.
* long delays in kernel code are pretty sucky anyway
* for now work around it using 5 x 2ms instead of 1 x 10ms
*/
udelay(2000);
udelay(2000);
udelay(2000);
udelay(2000);
udelay(2000);
/* Put in bypass mode */
for (i = 0; i < MAX_TDM_CHAN; i++) {
if (mask & (0x00000001 << i))
vpm_out(wc, x, i, 0x01);
}
/* Enable bypass */
for (i = 0; i < MAX_TDM_CHAN; i++) {
if (mask & (0x00000001 << i))
vpm_out(wc, x, 0x78 + i, 0x01);
}
}
}
#ifdef UNUSED
static void
vpm_check(struct hfc_multi *hctmp)
{
unsigned char gpi2;
gpi2 = HFC_inb(hctmp, R_GPI_IN2);
if ((gpi2 & 0x3) != 0x3)
printk(KERN_DEBUG "Got interrupt 0x%x from VPM!\n", gpi2);
}
#endif /* UNUSED */
/*
* Interface to enable/disable the HW Echocan
*
* these functions are called within a spin_lock_irqsave on
* the channel instance lock, so we are not disturbed by irqs
*
* we can later easily change the interface to make other
* things configurable, for now we configure the taps
*
*/
static void
vpm_echocan_on(struct hfc_multi *hc, int ch, int taps)
{
unsigned int timeslot;
unsigned int unit;
struct bchannel *bch = hc->chan[ch].bch;
#ifdef TXADJ
int txadj = -4;
struct sk_buff *skb;
#endif
if (hc->chan[ch].protocol != ISDN_P_B_RAW)
return;
if (!bch)
return;
#ifdef TXADJ
skb = _alloc_mISDN_skb(PH_CONTROL_IND, HFC_VOL_CHANGE_TX,
sizeof(int), &txadj, GFP_ATOMIC);
if (skb)
recv_Bchannel_skb(bch, skb);
#endif
timeslot = ((ch / 4) * 8) + ((ch % 4) * 4) + 1;
unit = ch % 4;
printk(KERN_NOTICE "vpm_echocan_on called taps [%d] on timeslot %d\n",
taps, timeslot);
vpm_out(hc, unit, timeslot, 0x7e);
}
static void
vpm_echocan_off(struct hfc_multi *hc, int ch)
{
unsigned int timeslot;
unsigned int unit;
struct bchannel *bch = hc->chan[ch].bch;
#ifdef TXADJ
int txadj = 0;
struct sk_buff *skb;
#endif
if (hc->chan[ch].protocol != ISDN_P_B_RAW)
return;
if (!bch)
return;
#ifdef TXADJ
skb = _alloc_mISDN_skb(PH_CONTROL_IND, HFC_VOL_CHANGE_TX,
sizeof(int), &txadj, GFP_ATOMIC);
if (skb)
recv_Bchannel_skb(bch, skb);
#endif
timeslot = ((ch / 4) * 8) + ((ch % 4) * 4) + 1;
unit = ch % 4;
printk(KERN_NOTICE "vpm_echocan_off called on timeslot %d\n",
timeslot);
/* FILLME */
vpm_out(hc, unit, timeslot, 0x01);
}
/*
* Speech Design resync feature
* NOTE: This is called sometimes outside interrupt handler.
* We must lock irqsave, so no other interrupt (other card) will occur!
* Also multiple interrupts may nest, so must lock each access (lists, card)!
*/
static inline void
hfcmulti_resync(struct hfc_multi *locked, struct hfc_multi *newmaster, int rm)
{
struct hfc_multi *hc, *next, *pcmmaster = NULL;
void __iomem *plx_acc_32;
u_int pv;
u_long flags;
spin_lock_irqsave(&HFClock, flags);
spin_lock(&plx_lock); /* must be locked inside other locks */
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG "%s: RESYNC(syncmaster=0x%p)\n",
__func__, syncmaster);
/* select new master */
if (newmaster) {
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG "using provided controller\n");
} else {
list_for_each_entry_safe(hc, next, &HFClist, list) {
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
if (hc->syncronized) {
newmaster = hc;
break;
}
}
}
}
/* Disable sync of all cards */
list_for_each_entry_safe(hc, next, &HFClist, list) {
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
plx_acc_32 = hc->plx_membase + PLX_GPIOC;
pv = readl(plx_acc_32);
pv &= ~PLX_SYNC_O_EN;
writel(pv, plx_acc_32);
if (test_bit(HFC_CHIP_PCM_MASTER, &hc->chip)) {
pcmmaster = hc;
if (hc->ctype == HFC_TYPE_E1) {
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG
"Schedule SYNC_I\n");
hc->e1_resync |= 1; /* get SYNC_I */
}
}
}
}
if (newmaster) {
hc = newmaster;
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG "id=%d (0x%p) = syncronized with "
"interface.\n", hc->id, hc);
/* Enable new sync master */
plx_acc_32 = hc->plx_membase + PLX_GPIOC;
pv = readl(plx_acc_32);
pv |= PLX_SYNC_O_EN;
writel(pv, plx_acc_32);
/* switch to jatt PLL, if not disabled by RX_SYNC */
if (hc->ctype == HFC_TYPE_E1
&& !test_bit(HFC_CHIP_RX_SYNC, &hc->chip)) {
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG "Schedule jatt PLL\n");
hc->e1_resync |= 2; /* switch to jatt */
}
} else {
if (pcmmaster) {
hc = pcmmaster;
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG
"id=%d (0x%p) = PCM master syncronized "
"with QUARTZ\n", hc->id, hc);
if (hc->ctype == HFC_TYPE_E1) {
/* Use the crystal clock for the PCM
master card */
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG
"Schedule QUARTZ for HFC-E1\n");
hc->e1_resync |= 4; /* switch quartz */
} else {
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG
"QUARTZ is automatically "
"enabled by HFC-%dS\n", hc->ctype);
}
plx_acc_32 = hc->plx_membase + PLX_GPIOC;
pv = readl(plx_acc_32);
pv |= PLX_SYNC_O_EN;
writel(pv, plx_acc_32);
} else
if (!rm)
printk(KERN_ERR "%s no pcm master, this MUST "
"not happen!\n", __func__);
}
syncmaster = newmaster;
spin_unlock(&plx_lock);
spin_unlock_irqrestore(&HFClock, flags);
}
/* This must be called AND hc must be locked irqsave!!! */
inline void
plxsd_checksync(struct hfc_multi *hc, int rm)
{
if (hc->syncronized) {
if (syncmaster == NULL) {
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG "%s: GOT sync on card %d"
" (id=%d)\n", __func__, hc->id + 1,
hc->id);
hfcmulti_resync(hc, hc, rm);
}
} else {
if (syncmaster == hc) {
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG "%s: LOST sync on card %d"
" (id=%d)\n", __func__, hc->id + 1,
hc->id);
hfcmulti_resync(hc, NULL, rm);
}
}
}
/*
* free hardware resources used by driver
*/
static void
release_io_hfcmulti(struct hfc_multi *hc)
{
void __iomem *plx_acc_32;
u_int pv;
u_long plx_flags;
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: entered\n", __func__);
/* soft reset also masks all interrupts */
hc->hw.r_cirm |= V_SRES;
HFC_outb(hc, R_CIRM, hc->hw.r_cirm);
udelay(1000);
hc->hw.r_cirm &= ~V_SRES;
HFC_outb(hc, R_CIRM, hc->hw.r_cirm);
udelay(1000); /* instead of 'wait' that may cause locking */
/* release Speech Design card, if PLX was initialized */
if (test_bit(HFC_CHIP_PLXSD, &hc->chip) && hc->plx_membase) {
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG "%s: release PLXSD card %d\n",
__func__, hc->id + 1);
spin_lock_irqsave(&plx_lock, plx_flags);
plx_acc_32 = hc->plx_membase + PLX_GPIOC;
writel(PLX_GPIOC_INIT, plx_acc_32);
pv = readl(plx_acc_32);
/* Termination off */
pv &= ~PLX_TERM_ON;
/* Disconnect the PCM */
pv |= PLX_SLAVE_EN_N;
pv &= ~PLX_MASTER_EN;
pv &= ~PLX_SYNC_O_EN;
/* Put the DSP in Reset */
pv &= ~PLX_DSP_RES_N;
writel(pv, plx_acc_32);
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: PCM off: PLX_GPIO=%x\n",
__func__, pv);
spin_unlock_irqrestore(&plx_lock, plx_flags);
}
/* disable memory mapped ports / io ports */
test_and_clear_bit(HFC_CHIP_PLXSD, &hc->chip); /* prevent resync */
if (hc->pci_dev)
pci_write_config_word(hc->pci_dev, PCI_COMMAND, 0);
if (hc->pci_membase)
iounmap(hc->pci_membase);
if (hc->plx_membase)
iounmap(hc->plx_membase);
if (hc->pci_iobase)
release_region(hc->pci_iobase, 8);
if (hc->xhfc_membase)
iounmap((void *)hc->xhfc_membase);
if (hc->pci_dev) {
pci_disable_device(hc->pci_dev);
pci_set_drvdata(hc->pci_dev, NULL);
}
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: done\n", __func__);
}
/*
* function called to reset the HFC chip. A complete software reset of chip
* and fifos is done. All configuration of the chip is done.
*/
static int
init_chip(struct hfc_multi *hc)
{
u_long flags, val, val2 = 0, rev;
int i, err = 0;
u_char r_conf_en, rval;
void __iomem *plx_acc_32;
u_int pv;
u_long plx_flags, hfc_flags;
int plx_count;
struct hfc_multi *pos, *next, *plx_last_hc;
spin_lock_irqsave(&hc->lock, flags);
/* reset all registers */
memset(&hc->hw, 0, sizeof(struct hfcm_hw));
/* revision check */
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: entered\n", __func__);
val = HFC_inb(hc, R_CHIP_ID);
if ((val >> 4) != 0x8 && (val >> 4) != 0xc && (val >> 4) != 0xe &&
(val >> 1) != 0x31) {
printk(KERN_INFO "HFC_multi: unknown CHIP_ID:%x\n", (u_int)val);
err = -EIO;
goto out;
}
rev = HFC_inb(hc, R_CHIP_RV);
printk(KERN_INFO
"HFC_multi: detected HFC with chip ID=0x%lx revision=%ld%s\n",
val, rev, (rev == 0 && (hc->ctype != HFC_TYPE_XHFC)) ?
" (old FIFO handling)" : "");
if (hc->ctype != HFC_TYPE_XHFC && rev == 0) {
test_and_set_bit(HFC_CHIP_REVISION0, &hc->chip);
printk(KERN_WARNING
"HFC_multi: NOTE: Your chip is revision 0, "
"ask Cologne Chip for update. Newer chips "
"have a better FIFO handling. Old chips "
"still work but may have slightly lower "
"HDLC transmit performance.\n");
}
if (rev > 1) {
printk(KERN_WARNING "HFC_multi: WARNING: This driver doesn't "
"consider chip revision = %ld. The chip / "
"bridge may not work.\n", rev);
}
/* set s-ram size */
hc->Flen = 0x10;
hc->Zmin = 0x80;
hc->Zlen = 384;
hc->DTMFbase = 0x1000;
if (test_bit(HFC_CHIP_EXRAM_128, &hc->chip)) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: changing to 128K extenal RAM\n",
__func__);
hc->hw.r_ctrl |= V_EXT_RAM;
hc->hw.r_ram_sz = 1;
hc->Flen = 0x20;
hc->Zmin = 0xc0;
hc->Zlen = 1856;
hc->DTMFbase = 0x2000;
}
if (test_bit(HFC_CHIP_EXRAM_512, &hc->chip)) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: changing to 512K extenal RAM\n",
__func__);
hc->hw.r_ctrl |= V_EXT_RAM;
hc->hw.r_ram_sz = 2;
hc->Flen = 0x20;
hc->Zmin = 0xc0;
hc->Zlen = 8000;
hc->DTMFbase = 0x2000;
}
if (hc->ctype == HFC_TYPE_XHFC) {
hc->Flen = 0x8;
hc->Zmin = 0x0;
hc->Zlen = 64;
hc->DTMFbase = 0x0;
}
hc->max_trans = poll << 1;
if (hc->max_trans > hc->Zlen)
hc->max_trans = hc->Zlen;
/* Speech Design PLX bridge */
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG "%s: initializing PLXSD card %d\n",
__func__, hc->id + 1);
spin_lock_irqsave(&plx_lock, plx_flags);
plx_acc_32 = hc->plx_membase + PLX_GPIOC;
writel(PLX_GPIOC_INIT, plx_acc_32);
pv = readl(plx_acc_32);
/* The first and the last cards are terminating the PCM bus */
pv |= PLX_TERM_ON; /* hc is currently the last */
/* Disconnect the PCM */
pv |= PLX_SLAVE_EN_N;
pv &= ~PLX_MASTER_EN;
pv &= ~PLX_SYNC_O_EN;
/* Put the DSP in Reset */
pv &= ~PLX_DSP_RES_N;
writel(pv, plx_acc_32);
spin_unlock_irqrestore(&plx_lock, plx_flags);
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: slave/term: PLX_GPIO=%x\n",
__func__, pv);
/*
* If we are the 3rd PLXSD card or higher, we must turn
* termination of last PLXSD card off.
*/
spin_lock_irqsave(&HFClock, hfc_flags);
plx_count = 0;
plx_last_hc = NULL;
list_for_each_entry_safe(pos, next, &HFClist, list) {
if (test_bit(HFC_CHIP_PLXSD, &pos->chip)) {
plx_count++;
if (pos != hc)
plx_last_hc = pos;
}
}
if (plx_count >= 3) {
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG "%s: card %d is between, so "
"we disable termination\n",
__func__, plx_last_hc->id + 1);
spin_lock_irqsave(&plx_lock, plx_flags);
plx_acc_32 = plx_last_hc->plx_membase + PLX_GPIOC;
pv = readl(plx_acc_32);
pv &= ~PLX_TERM_ON;
writel(pv, plx_acc_32);
spin_unlock_irqrestore(&plx_lock, plx_flags);
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: term off: PLX_GPIO=%x\n",
__func__, pv);
}
spin_unlock_irqrestore(&HFClock, hfc_flags);
hc->hw.r_pcm_md0 = V_F0_LEN; /* shift clock for DSP */
}
if (test_bit(HFC_CHIP_EMBSD, &hc->chip))
hc->hw.r_pcm_md0 = V_F0_LEN; /* shift clock for DSP */
/* we only want the real Z2 read-pointer for revision > 0 */
if (!test_bit(HFC_CHIP_REVISION0, &hc->chip))
hc->hw.r_ram_sz |= V_FZ_MD;
/* select pcm mode */
if (test_bit(HFC_CHIP_PCM_SLAVE, &hc->chip)) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: setting PCM into slave mode\n",
__func__);
} else
if (test_bit(HFC_CHIP_PCM_MASTER, &hc->chip) && !plxsd_master) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: setting PCM into master mode\n",
__func__);
hc->hw.r_pcm_md0 |= V_PCM_MD;
} else {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: performing PCM auto detect\n",
__func__);
}
/* soft reset */
HFC_outb(hc, R_CTRL, hc->hw.r_ctrl);
if (hc->ctype == HFC_TYPE_XHFC)
HFC_outb(hc, 0x0C /* R_FIFO_THRES */,
0x11 /* 16 Bytes TX/RX */);
else
HFC_outb(hc, R_RAM_SZ, hc->hw.r_ram_sz);
HFC_outb(hc, R_FIFO_MD, 0);
if (hc->ctype == HFC_TYPE_XHFC)
hc->hw.r_cirm = V_SRES | V_HFCRES | V_PCMRES | V_STRES;
else
hc->hw.r_cirm = V_SRES | V_HFCRES | V_PCMRES | V_STRES
| V_RLD_EPR;
HFC_outb(hc, R_CIRM, hc->hw.r_cirm);
udelay(100);
hc->hw.r_cirm = 0;
HFC_outb(hc, R_CIRM, hc->hw.r_cirm);
udelay(100);
if (hc->ctype != HFC_TYPE_XHFC)
HFC_outb(hc, R_RAM_SZ, hc->hw.r_ram_sz);
/* Speech Design PLX bridge pcm and sync mode */
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
spin_lock_irqsave(&plx_lock, plx_flags);
plx_acc_32 = hc->plx_membase + PLX_GPIOC;
pv = readl(plx_acc_32);
/* Connect PCM */
if (hc->hw.r_pcm_md0 & V_PCM_MD) {
pv |= PLX_MASTER_EN | PLX_SLAVE_EN_N;
pv |= PLX_SYNC_O_EN;
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: master: PLX_GPIO=%x\n",
__func__, pv);
} else {
pv &= ~(PLX_MASTER_EN | PLX_SLAVE_EN_N);
pv &= ~PLX_SYNC_O_EN;
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: slave: PLX_GPIO=%x\n",
__func__, pv);
}
writel(pv, plx_acc_32);
spin_unlock_irqrestore(&plx_lock, plx_flags);
}
/* PCM setup */
HFC_outb(hc, R_PCM_MD0, hc->hw.r_pcm_md0 | 0x90);
if (hc->slots == 32)
HFC_outb(hc, R_PCM_MD1, 0x00);
if (hc->slots == 64)
HFC_outb(hc, R_PCM_MD1, 0x10);
if (hc->slots == 128)
HFC_outb(hc, R_PCM_MD1, 0x20);
HFC_outb(hc, R_PCM_MD0, hc->hw.r_pcm_md0 | 0xa0);
if (test_bit(HFC_CHIP_PLXSD, &hc->chip))
HFC_outb(hc, R_PCM_MD2, V_SYNC_SRC); /* sync via SYNC_I / O */
else if (test_bit(HFC_CHIP_EMBSD, &hc->chip))
HFC_outb(hc, R_PCM_MD2, 0x10); /* V_C2O_EN */
else
HFC_outb(hc, R_PCM_MD2, 0x00); /* sync from interface */
HFC_outb(hc, R_PCM_MD0, hc->hw.r_pcm_md0 | 0x00);
for (i = 0; i < 256; i++) {
HFC_outb_nodebug(hc, R_SLOT, i);
HFC_outb_nodebug(hc, A_SL_CFG, 0);
if (hc->ctype != HFC_TYPE_XHFC)
HFC_outb_nodebug(hc, A_CONF, 0);
hc->slot_owner[i] = -1;
}
/* set clock speed */
if (test_bit(HFC_CHIP_CLOCK2, &hc->chip)) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: setting double clock\n", __func__);
HFC_outb(hc, R_BRG_PCM_CFG, V_PCM_CLK);
}
if (test_bit(HFC_CHIP_EMBSD, &hc->chip))
HFC_outb(hc, 0x02 /* R_CLK_CFG */, 0x40 /* V_CLKO_OFF */);
/* B410P GPIO */
if (test_bit(HFC_CHIP_B410P, &hc->chip)) {
printk(KERN_NOTICE "Setting GPIOs\n");
HFC_outb(hc, R_GPIO_SEL, 0x30);
HFC_outb(hc, R_GPIO_EN1, 0x3);
udelay(1000);
printk(KERN_NOTICE "calling vpm_init\n");
vpm_init(hc);
}
/* check if R_F0_CNT counts (8 kHz frame count) */
val = HFC_inb(hc, R_F0_CNTL);
val += HFC_inb(hc, R_F0_CNTH) << 8;
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"HFC_multi F0_CNT %ld after reset\n", val);
spin_unlock_irqrestore(&hc->lock, flags);
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout((HZ / 100) ? : 1); /* Timeout minimum 10ms */
spin_lock_irqsave(&hc->lock, flags);
val2 = HFC_inb(hc, R_F0_CNTL);
val2 += HFC_inb(hc, R_F0_CNTH) << 8;
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"HFC_multi F0_CNT %ld after 10 ms (1st try)\n",
val2);
if (val2 >= val + 8) { /* 1 ms */
/* it counts, so we keep the pcm mode */
if (test_bit(HFC_CHIP_PCM_MASTER, &hc->chip))
printk(KERN_INFO "controller is PCM bus MASTER\n");
else
if (test_bit(HFC_CHIP_PCM_SLAVE, &hc->chip))
printk(KERN_INFO "controller is PCM bus SLAVE\n");
else {
test_and_set_bit(HFC_CHIP_PCM_SLAVE, &hc->chip);
printk(KERN_INFO "controller is PCM bus SLAVE "
"(auto detected)\n");
}
} else {
/* does not count */
if (test_bit(HFC_CHIP_PCM_MASTER, &hc->chip)) {
controller_fail:
printk(KERN_ERR "HFC_multi ERROR, getting no 125us "
"pulse. Seems that controller fails.\n");
err = -EIO;
goto out;
}
if (test_bit(HFC_CHIP_PCM_SLAVE, &hc->chip)) {
printk(KERN_INFO "controller is PCM bus SLAVE "
"(ignoring missing PCM clock)\n");
} else {
/* only one pcm master */
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)
&& plxsd_master) {
printk(KERN_ERR "HFC_multi ERROR, no clock "
"on another Speech Design card found. "
"Please be sure to connect PCM cable.\n");
err = -EIO;
goto out;
}
/* retry with master clock */
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
spin_lock_irqsave(&plx_lock, plx_flags);
plx_acc_32 = hc->plx_membase + PLX_GPIOC;
pv = readl(plx_acc_32);
pv |= PLX_MASTER_EN | PLX_SLAVE_EN_N;
pv |= PLX_SYNC_O_EN;
writel(pv, plx_acc_32);
spin_unlock_irqrestore(&plx_lock, plx_flags);
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: master: "
"PLX_GPIO=%x\n", __func__, pv);
}
hc->hw.r_pcm_md0 |= V_PCM_MD;
HFC_outb(hc, R_PCM_MD0, hc->hw.r_pcm_md0 | 0x00);
spin_unlock_irqrestore(&hc->lock, flags);
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout((HZ / 100) ?: 1); /* Timeout min. 10ms */
spin_lock_irqsave(&hc->lock, flags);
val2 = HFC_inb(hc, R_F0_CNTL);
val2 += HFC_inb(hc, R_F0_CNTH) << 8;
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "HFC_multi F0_CNT %ld after "
"10 ms (2nd try)\n", val2);
if (val2 >= val + 8) { /* 1 ms */
test_and_set_bit(HFC_CHIP_PCM_MASTER,
&hc->chip);
printk(KERN_INFO "controller is PCM bus MASTER "
"(auto detected)\n");
} else
goto controller_fail;
}
}
/* Release the DSP Reset */
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
if (test_bit(HFC_CHIP_PCM_MASTER, &hc->chip))
plxsd_master = 1;
spin_lock_irqsave(&plx_lock, plx_flags);
plx_acc_32 = hc->plx_membase + PLX_GPIOC;
pv = readl(plx_acc_32);
pv |= PLX_DSP_RES_N;
writel(pv, plx_acc_32);
spin_unlock_irqrestore(&plx_lock, plx_flags);
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: reset off: PLX_GPIO=%x\n",
__func__, pv);
}
/* pcm id */
if (hc->pcm)
printk(KERN_INFO "controller has given PCM BUS ID %d\n",
hc->pcm);
else {
if (test_bit(HFC_CHIP_PCM_MASTER, &hc->chip)
|| test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
PCM_cnt++; /* SD has proprietary bridging */
}
hc->pcm = PCM_cnt;
printk(KERN_INFO "controller has PCM BUS ID %d "
"(auto selected)\n", hc->pcm);
}
/* set up timer */
HFC_outb(hc, R_TI_WD, poll_timer);
hc->hw.r_irqmsk_misc |= V_TI_IRQMSK;
/* set E1 state machine IRQ */
if (hc->ctype == HFC_TYPE_E1)
hc->hw.r_irqmsk_misc |= V_STA_IRQMSK;
/* set DTMF detection */
if (test_bit(HFC_CHIP_DTMF, &hc->chip)) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: enabling DTMF detection "
"for all B-channel\n", __func__);
hc->hw.r_dtmf = V_DTMF_EN | V_DTMF_STOP;
if (test_bit(HFC_CHIP_ULAW, &hc->chip))
hc->hw.r_dtmf |= V_ULAW_SEL;
HFC_outb(hc, R_DTMF_N, 102 - 1);
hc->hw.r_irqmsk_misc |= V_DTMF_IRQMSK;
}
/* conference engine */
if (test_bit(HFC_CHIP_ULAW, &hc->chip))
r_conf_en = V_CONF_EN | V_ULAW;
else
r_conf_en = V_CONF_EN;
if (hc->ctype != HFC_TYPE_XHFC)
HFC_outb(hc, R_CONF_EN, r_conf_en);
/* setting leds */
switch (hc->leds) {
case 1: /* HFC-E1 OEM */
if (test_bit(HFC_CHIP_WATCHDOG, &hc->chip))
HFC_outb(hc, R_GPIO_SEL, 0x32);
else
HFC_outb(hc, R_GPIO_SEL, 0x30);
HFC_outb(hc, R_GPIO_EN1, 0x0f);
HFC_outb(hc, R_GPIO_OUT1, 0x00);
HFC_outb(hc, R_GPIO_EN0, V_GPIO_EN2 | V_GPIO_EN3);
break;
case 2: /* HFC-4S OEM */
case 3:
HFC_outb(hc, R_GPIO_SEL, 0xf0);
HFC_outb(hc, R_GPIO_EN1, 0xff);
HFC_outb(hc, R_GPIO_OUT1, 0x00);
break;
}
if (test_bit(HFC_CHIP_EMBSD, &hc->chip)) {
hc->hw.r_st_sync = 0x10; /* V_AUTO_SYNCI */
HFC_outb(hc, R_ST_SYNC, hc->hw.r_st_sync);
}
/* set master clock */
if (hc->masterclk >= 0) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: setting ST master clock "
"to port %d (0..%d)\n",
__func__, hc->masterclk, hc->ports - 1);
hc->hw.r_st_sync |= (hc->masterclk | V_AUTO_SYNC);
HFC_outb(hc, R_ST_SYNC, hc->hw.r_st_sync);
}
/* setting misc irq */
HFC_outb(hc, R_IRQMSK_MISC, hc->hw.r_irqmsk_misc);
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "r_irqmsk_misc.2: 0x%x\n",
hc->hw.r_irqmsk_misc);
/* RAM access test */
HFC_outb(hc, R_RAM_ADDR0, 0);
HFC_outb(hc, R_RAM_ADDR1, 0);
HFC_outb(hc, R_RAM_ADDR2, 0);
for (i = 0; i < 256; i++) {
HFC_outb_nodebug(hc, R_RAM_ADDR0, i);
HFC_outb_nodebug(hc, R_RAM_DATA, ((i * 3) & 0xff));
}
for (i = 0; i < 256; i++) {
HFC_outb_nodebug(hc, R_RAM_ADDR0, i);
HFC_inb_nodebug(hc, R_RAM_DATA);
rval = HFC_inb_nodebug(hc, R_INT_DATA);
if (rval != ((i * 3) & 0xff)) {
printk(KERN_DEBUG
"addr:%x val:%x should:%x\n", i, rval,
(i * 3) & 0xff);
err++;
}
}
if (err) {
printk(KERN_DEBUG "aborting - %d RAM access errors\n", err);
err = -EIO;
goto out;
}
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: done\n", __func__);
out:
spin_unlock_irqrestore(&hc->lock, flags);
return err;
}
/*
* control the watchdog
*/
static void
hfcmulti_watchdog(struct hfc_multi *hc)
{
hc->wdcount++;
if (hc->wdcount > 10) {
hc->wdcount = 0;
hc->wdbyte = hc->wdbyte == V_GPIO_OUT2 ?
V_GPIO_OUT3 : V_GPIO_OUT2;
/* printk("Sending Watchdog Kill %x\n",hc->wdbyte); */
HFC_outb(hc, R_GPIO_EN0, V_GPIO_EN2 | V_GPIO_EN3);
HFC_outb(hc, R_GPIO_OUT0, hc->wdbyte);
}
}
/*
* output leds
*/
static void
hfcmulti_leds(struct hfc_multi *hc)
{
unsigned long lled;
unsigned long leddw;
int i, state, active, leds;
struct dchannel *dch;
int led[4];
hc->ledcount += poll;
if (hc->ledcount > 4096) {
hc->ledcount -= 4096;
hc->ledstate = 0xAFFEAFFE;
}
switch (hc->leds) {
case 1: /* HFC-E1 OEM */
/* 2 red blinking: NT mode deactivate
* 2 red steady: TE mode deactivate
* left green: L1 active
* left red: frame sync, but no L1
* right green: L2 active
*/
if (hc->chan[hc->dslot].sync != 2) { /* no frame sync */
if (hc->chan[hc->dslot].dch->dev.D.protocol
!= ISDN_P_NT_E1) {
led[0] = 1;
led[1] = 1;
} else if (hc->ledcount >> 11) {
led[0] = 1;
led[1] = 1;
} else {
led[0] = 0;
led[1] = 0;
}
led[2] = 0;
led[3] = 0;
} else { /* with frame sync */
/* TODO make it work */
led[0] = 0;
led[1] = 0;
led[2] = 0;
led[3] = 1;
}
leds = (led[0] | (led[1]<<2) | (led[2]<<1) | (led[3]<<3))^0xF;
/* leds are inverted */
if (leds != (int)hc->ledstate) {
HFC_outb_nodebug(hc, R_GPIO_OUT1, leds);
hc->ledstate = leds;
}
break;
case 2: /* HFC-4S OEM */
/* red blinking = PH_DEACTIVATE NT Mode
* red steady = PH_DEACTIVATE TE Mode
* green steady = PH_ACTIVATE
*/
for (i = 0; i < 4; i++) {
state = 0;
active = -1;
dch = hc->chan[(i << 2) | 2].dch;
if (dch) {
state = dch->state;
if (dch->dev.D.protocol == ISDN_P_NT_S0)
active = 3;
else
active = 7;
}
if (state) {
if (state == active) {
led[i] = 1; /* led green */
} else
if (dch->dev.D.protocol == ISDN_P_TE_S0)
/* TE mode: led red */
led[i] = 2;
else
if (hc->ledcount >> 11)
/* led red */
led[i] = 2;
else
/* led off */
led[i] = 0;
} else
led[i] = 0; /* led off */
}
if (test_bit(HFC_CHIP_B410P, &hc->chip)) {
leds = 0;
for (i = 0; i < 4; i++) {
if (led[i] == 1) {
/*green*/
leds |= (0x2 << (i * 2));
} else if (led[i] == 2) {
/*red*/
leds |= (0x1 << (i * 2));
}
}
if (leds != (int)hc->ledstate) {
vpm_out(hc, 0, 0x1a8 + 3, leds);
hc->ledstate = leds;
}
} else {
leds = ((led[3] > 0) << 0) | ((led[1] > 0) << 1) |
((led[0] > 0) << 2) | ((led[2] > 0) << 3) |
((led[3] & 1) << 4) | ((led[1] & 1) << 5) |
((led[0] & 1) << 6) | ((led[2] & 1) << 7);
if (leds != (int)hc->ledstate) {
HFC_outb_nodebug(hc, R_GPIO_EN1, leds & 0x0F);
HFC_outb_nodebug(hc, R_GPIO_OUT1, leds >> 4);
hc->ledstate = leds;
}
}
break;
case 3: /* HFC 1S/2S Beronet */
/* red blinking = PH_DEACTIVATE NT Mode
* red steady = PH_DEACTIVATE TE Mode
* green steady = PH_ACTIVATE
*/
for (i = 0; i < 2; i++) {
state = 0;
active = -1;
dch = hc->chan[(i << 2) | 2].dch;
if (dch) {
state = dch->state;
if (dch->dev.D.protocol == ISDN_P_NT_S0)
active = 3;
else
active = 7;
}
if (state) {
if (state == active) {
led[i] = 1; /* led green */
} else
if (dch->dev.D.protocol == ISDN_P_TE_S0)
/* TE mode: led red */
led[i] = 2;
else
if (hc->ledcount >> 11)
/* led red */
led[i] = 2;
else
/* led off */
led[i] = 0;
} else
led[i] = 0; /* led off */
}
leds = (led[0] > 0) | ((led[1] > 0) << 1) | ((led[0]&1) << 2)
| ((led[1]&1) << 3);
if (leds != (int)hc->ledstate) {
HFC_outb_nodebug(hc, R_GPIO_EN1,
((led[0] > 0) << 2) | ((led[1] > 0) << 3));
HFC_outb_nodebug(hc, R_GPIO_OUT1,
((led[0] & 1) << 2) | ((led[1] & 1) << 3));
hc->ledstate = leds;
}
break;
case 8: /* HFC 8S+ Beronet */
lled = 0;
for (i = 0; i < 8; i++) {
state = 0;
active = -1;
dch = hc->chan[(i << 2) | 2].dch;
if (dch) {
state = dch->state;
if (dch->dev.D.protocol == ISDN_P_NT_S0)
active = 3;
else
active = 7;
}
if (state) {
if (state == active) {
lled |= 0 << i;
} else
if (hc->ledcount >> 11)
lled |= 0 << i;
else
lled |= 1 << i;
} else
lled |= 1 << i;
}
leddw = lled << 24 | lled << 16 | lled << 8 | lled;
if (leddw != hc->ledstate) {
/* HFC_outb(hc, R_BRG_PCM_CFG, 1);
HFC_outb(c, R_BRG_PCM_CFG, (0x0 << 6) | 0x3); */
/* was _io before */
HFC_outb_nodebug(hc, R_BRG_PCM_CFG, 1 | V_PCM_CLK);
outw(0x4000, hc->pci_iobase + 4);
outl(leddw, hc->pci_iobase);
HFC_outb_nodebug(hc, R_BRG_PCM_CFG, V_PCM_CLK);
hc->ledstate = leddw;
}
break;
}
}
/*
* read dtmf coefficients
*/
static void
hfcmulti_dtmf(struct hfc_multi *hc)
{
s32 *coeff;
u_int mantissa;
int co, ch;
struct bchannel *bch = NULL;
u8 exponent;
int dtmf = 0;
int addr;
u16 w_float;
struct sk_buff *skb;
struct mISDNhead *hh;
if (debug & DEBUG_HFCMULTI_DTMF)
printk(KERN_DEBUG "%s: dtmf detection irq\n", __func__);
for (ch = 0; ch <= 31; ch++) {
/* only process enabled B-channels */
bch = hc->chan[ch].bch;
if (!bch)
continue;
if (!hc->created[hc->chan[ch].port])
continue;
if (!test_bit(FLG_TRANSPARENT, &bch->Flags))
continue;
if (debug & DEBUG_HFCMULTI_DTMF)
printk(KERN_DEBUG "%s: dtmf channel %d:",
__func__, ch);
coeff = &(hc->chan[ch].coeff[hc->chan[ch].coeff_count * 16]);
dtmf = 1;
for (co = 0; co < 8; co++) {
/* read W(n-1) coefficient */
addr = hc->DTMFbase + ((co << 7) | (ch << 2));
HFC_outb_nodebug(hc, R_RAM_ADDR0, addr);
HFC_outb_nodebug(hc, R_RAM_ADDR1, addr >> 8);
HFC_outb_nodebug(hc, R_RAM_ADDR2, (addr >> 16)
| V_ADDR_INC);
w_float = HFC_inb_nodebug(hc, R_RAM_DATA);
w_float |= (HFC_inb_nodebug(hc, R_RAM_DATA) << 8);
if (debug & DEBUG_HFCMULTI_DTMF)
printk(" %04x", w_float);
/* decode float (see chip doc) */
mantissa = w_float & 0x0fff;
if (w_float & 0x8000)
mantissa |= 0xfffff000;
exponent = (w_float >> 12) & 0x7;
if (exponent) {
mantissa ^= 0x1000;
mantissa <<= (exponent - 1);
}
/* store coefficient */
coeff[co << 1] = mantissa;
/* read W(n) coefficient */
w_float = HFC_inb_nodebug(hc, R_RAM_DATA);
w_float |= (HFC_inb_nodebug(hc, R_RAM_DATA) << 8);
if (debug & DEBUG_HFCMULTI_DTMF)
printk(" %04x", w_float);
/* decode float (see chip doc) */
mantissa = w_float & 0x0fff;
if (w_float & 0x8000)
mantissa |= 0xfffff000;
exponent = (w_float >> 12) & 0x7;
if (exponent) {
mantissa ^= 0x1000;
mantissa <<= (exponent - 1);
}
/* store coefficient */
coeff[(co << 1) | 1] = mantissa;
}
if (debug & DEBUG_HFCMULTI_DTMF)
printk(" DTMF ready %08x %08x %08x %08x "
"%08x %08x %08x %08x\n",
coeff[0], coeff[1], coeff[2], coeff[3],
coeff[4], coeff[5], coeff[6], coeff[7]);
hc->chan[ch].coeff_count++;
if (hc->chan[ch].coeff_count == 8) {
hc->chan[ch].coeff_count = 0;
skb = mI_alloc_skb(512, GFP_ATOMIC);
if (!skb) {
printk(KERN_DEBUG "%s: No memory for skb\n",
__func__);
continue;
}
hh = mISDN_HEAD_P(skb);
hh->prim = PH_CONTROL_IND;
hh->id = DTMF_HFC_COEF;
memcpy(skb_put(skb, 512), hc->chan[ch].coeff, 512);
recv_Bchannel_skb(bch, skb);
}
}
/* restart DTMF processing */
hc->dtmf = dtmf;
if (dtmf)
HFC_outb_nodebug(hc, R_DTMF, hc->hw.r_dtmf | V_RST_DTMF);
}
/*
* fill fifo as much as possible
*/
static void
hfcmulti_tx(struct hfc_multi *hc, int ch)
{
int i, ii, temp, len = 0;
int Zspace, z1, z2; /* must be int for calculation */
int Fspace, f1, f2;
u_char *d;
int *txpending, slot_tx;
struct bchannel *bch;
struct dchannel *dch;
struct sk_buff **sp = NULL;
int *idxp;
bch = hc->chan[ch].bch;
dch = hc->chan[ch].dch;
if ((!dch) && (!bch))
return;
txpending = &hc->chan[ch].txpending;
slot_tx = hc->chan[ch].slot_tx;
if (dch) {
if (!test_bit(FLG_ACTIVE, &dch->Flags))
return;
sp = &dch->tx_skb;
idxp = &dch->tx_idx;
} else {
if (!test_bit(FLG_ACTIVE, &bch->Flags))
return;
sp = &bch->tx_skb;
idxp = &bch->tx_idx;
}
if (*sp)
len = (*sp)->len;
if ((!len) && *txpending != 1)
return; /* no data */
if (test_bit(HFC_CHIP_B410P, &hc->chip) &&
(hc->chan[ch].protocol == ISDN_P_B_RAW) &&
(hc->chan[ch].slot_rx < 0) &&
(hc->chan[ch].slot_tx < 0))
HFC_outb_nodebug(hc, R_FIFO, 0x20 | (ch << 1));
else
HFC_outb_nodebug(hc, R_FIFO, ch << 1);
HFC_wait_nodebug(hc);
if (*txpending == 2) {
/* reset fifo */
HFC_outb_nodebug(hc, R_INC_RES_FIFO, V_RES_F);
HFC_wait_nodebug(hc);
HFC_outb(hc, A_SUBCH_CFG, 0);
*txpending = 1;
}
next_frame:
if (dch || test_bit(FLG_HDLC, &bch->Flags)) {
f1 = HFC_inb_nodebug(hc, A_F1);
f2 = HFC_inb_nodebug(hc, A_F2);
while (f2 != (temp = HFC_inb_nodebug(hc, A_F2))) {
if (debug & DEBUG_HFCMULTI_FIFO)
printk(KERN_DEBUG
"%s(card %d): reread f2 because %d!=%d\n",
__func__, hc->id + 1, temp, f2);
f2 = temp; /* repeat until F2 is equal */
}
Fspace = f2 - f1 - 1;
if (Fspace < 0)
Fspace += hc->Flen;
/*
* Old FIFO handling doesn't give us the current Z2 read
* pointer, so we cannot send the next frame before the fifo
* is empty. It makes no difference except for a slightly
* lower performance.
*/
if (test_bit(HFC_CHIP_REVISION0, &hc->chip)) {
if (f1 != f2)
Fspace = 0;
else
Fspace = 1;
}
/* one frame only for ST D-channels, to allow resending */
if (hc->ctype != HFC_TYPE_E1 && dch) {
if (f1 != f2)
Fspace = 0;
}
/* F-counter full condition */
if (Fspace == 0)
return;
}
z1 = HFC_inw_nodebug(hc, A_Z1) - hc->Zmin;
z2 = HFC_inw_nodebug(hc, A_Z2) - hc->Zmin;
while (z2 != (temp = (HFC_inw_nodebug(hc, A_Z2) - hc->Zmin))) {
if (debug & DEBUG_HFCMULTI_FIFO)
printk(KERN_DEBUG "%s(card %d): reread z2 because "
"%d!=%d\n", __func__, hc->id + 1, temp, z2);
z2 = temp; /* repeat unti Z2 is equal */
}
hc->chan[ch].Zfill = z1 - z2;
if (hc->chan[ch].Zfill < 0)
hc->chan[ch].Zfill += hc->Zlen;
Zspace = z2 - z1;
if (Zspace <= 0)
Zspace += hc->Zlen;
Zspace -= 4; /* keep not too full, so pointers will not overrun */
/* fill transparent data only to maxinum transparent load (minus 4) */
if (bch && test_bit(FLG_TRANSPARENT, &bch->Flags))
Zspace = Zspace - hc->Zlen + hc->max_trans;
if (Zspace <= 0) /* no space of 4 bytes */
return;
/* if no data */
if (!len) {
if (z1 == z2) { /* empty */
/* if done with FIFO audio data during PCM connection */
if (bch && (!test_bit(FLG_HDLC, &bch->Flags)) &&
*txpending && slot_tx >= 0) {
if (debug & DEBUG_HFCMULTI_MODE)
printk(KERN_DEBUG
"%s: reconnecting PCM due to no "
"more FIFO data: channel %d "
"slot_tx %d\n",
__func__, ch, slot_tx);
/* connect slot */
if (hc->ctype == HFC_TYPE_XHFC)
HFC_outb(hc, A_CON_HDLC, 0xc0
| 0x07 << 2 | V_HDLC_TRP | V_IFF);
/* Enable FIFO, no interrupt */
else
HFC_outb(hc, A_CON_HDLC, 0xc0 | 0x00 |
V_HDLC_TRP | V_IFF);
HFC_outb_nodebug(hc, R_FIFO, ch << 1 | 1);
HFC_wait_nodebug(hc);
if (hc->ctype == HFC_TYPE_XHFC)
HFC_outb(hc, A_CON_HDLC, 0xc0
| 0x07 << 2 | V_HDLC_TRP | V_IFF);
/* Enable FIFO, no interrupt */
else
HFC_outb(hc, A_CON_HDLC, 0xc0 | 0x00 |
V_HDLC_TRP | V_IFF);
HFC_outb_nodebug(hc, R_FIFO, ch << 1);
HFC_wait_nodebug(hc);
}
*txpending = 0;
}
return; /* no data */
}
/* "fill fifo if empty" feature */
if (bch && test_bit(FLG_FILLEMPTY, &bch->Flags)
&& !test_bit(FLG_HDLC, &bch->Flags) && z2 == z1) {
if (debug & DEBUG_HFCMULTI_FILL)
printk(KERN_DEBUG "%s: buffer empty, so we have "
"underrun\n", __func__);
/* fill buffer, to prevent future underrun */
hc->write_fifo(hc, hc->silence_data, poll >> 1);
Zspace -= (poll >> 1);
}
/* if audio data and connected slot */
if (bch && (!test_bit(FLG_HDLC, &bch->Flags)) && (!*txpending)
&& slot_tx >= 0) {
if (debug & DEBUG_HFCMULTI_MODE)
printk(KERN_DEBUG "%s: disconnecting PCM due to "
"FIFO data: channel %d slot_tx %d\n",
__func__, ch, slot_tx);
/* disconnect slot */
if (hc->ctype == HFC_TYPE_XHFC)
HFC_outb(hc, A_CON_HDLC, 0x80
| 0x07 << 2 | V_HDLC_TRP | V_IFF);
/* Enable FIFO, no interrupt */
else
HFC_outb(hc, A_CON_HDLC, 0x80 | 0x00 |
V_HDLC_TRP | V_IFF);
HFC_outb_nodebug(hc, R_FIFO, ch << 1 | 1);
HFC_wait_nodebug(hc);
if (hc->ctype == HFC_TYPE_XHFC)
HFC_outb(hc, A_CON_HDLC, 0x80
| 0x07 << 2 | V_HDLC_TRP | V_IFF);
/* Enable FIFO, no interrupt */
else
HFC_outb(hc, A_CON_HDLC, 0x80 | 0x00 |
V_HDLC_TRP | V_IFF);
HFC_outb_nodebug(hc, R_FIFO, ch << 1);
HFC_wait_nodebug(hc);
}
*txpending = 1;
/* show activity */
hc->activity[hc->chan[ch].port] = 1;
/* fill fifo to what we have left */
ii = len;
if (dch || test_bit(FLG_HDLC, &bch->Flags))
temp = 1;
else
temp = 0;
i = *idxp;
d = (*sp)->data + i;
if (ii - i > Zspace)
ii = Zspace + i;
if (debug & DEBUG_HFCMULTI_FIFO)
printk(KERN_DEBUG "%s(card %d): fifo(%d) has %d bytes space "
"left (z1=%04x, z2=%04x) sending %d of %d bytes %s\n",
__func__, hc->id + 1, ch, Zspace, z1, z2, ii-i, len-i,
temp ? "HDLC" : "TRANS");
/* Have to prep the audio data */
hc->write_fifo(hc, d, ii - i);
hc->chan[ch].Zfill += ii - i;
*idxp = ii;
/* if not all data has been written */
if (ii != len) {
/* NOTE: fifo is started by the calling function */
return;
}
/* if all data has been written, terminate frame */
if (dch || test_bit(FLG_HDLC, &bch->Flags)) {
/* increment f-counter */
HFC_outb_nodebug(hc, R_INC_RES_FIFO, V_INC_F);
HFC_wait_nodebug(hc);
}
/* send confirm, since get_net_bframe will not do it with trans */
if (bch && test_bit(FLG_TRANSPARENT, &bch->Flags))
confirm_Bsend(bch);
/* check for next frame */
dev_kfree_skb(*sp);
if (bch && get_next_bframe(bch)) { /* hdlc is confirmed here */
len = (*sp)->len;
goto next_frame;
}
if (dch && get_next_dframe(dch)) {
len = (*sp)->len;
goto next_frame;
}
/*
* now we have no more data, so in case of transparent,
* we set the last byte in fifo to 'silence' in case we will get
* no more data at all. this prevents sending an undefined value.
*/
if (bch && test_bit(FLG_TRANSPARENT, &bch->Flags))
HFC_outb_nodebug(hc, A_FIFO_DATA0_NOINC, hc->silence);
}
/* NOTE: only called if E1 card is in active state */
static void
hfcmulti_rx(struct hfc_multi *hc, int ch)
{
int temp;
int Zsize, z1, z2 = 0; /* = 0, to make GCC happy */
int f1 = 0, f2 = 0; /* = 0, to make GCC happy */
int again = 0;
struct bchannel *bch;
struct dchannel *dch;
struct sk_buff *skb, **sp = NULL;
int maxlen;
bch = hc->chan[ch].bch;
dch = hc->chan[ch].dch;
if ((!dch) && (!bch))
return;
if (dch) {
if (!test_bit(FLG_ACTIVE, &dch->Flags))
return;
sp = &dch->rx_skb;
maxlen = dch->maxlen;
} else {
if (!test_bit(FLG_ACTIVE, &bch->Flags))
return;
sp = &bch->rx_skb;
maxlen = bch->maxlen;
}
next_frame:
/* on first AND before getting next valid frame, R_FIFO must be written
to. */
if (test_bit(HFC_CHIP_B410P, &hc->chip) &&
(hc->chan[ch].protocol == ISDN_P_B_RAW) &&
(hc->chan[ch].slot_rx < 0) &&
(hc->chan[ch].slot_tx < 0))
HFC_outb_nodebug(hc, R_FIFO, 0x20 | (ch << 1) | 1);
else
HFC_outb_nodebug(hc, R_FIFO, (ch << 1) | 1);
HFC_wait_nodebug(hc);
/* ignore if rx is off BUT change fifo (above) to start pending TX */
if (hc->chan[ch].rx_off)
return;
if (dch || test_bit(FLG_HDLC, &bch->Flags)) {
f1 = HFC_inb_nodebug(hc, A_F1);
while (f1 != (temp = HFC_inb_nodebug(hc, A_F1))) {
if (debug & DEBUG_HFCMULTI_FIFO)
printk(KERN_DEBUG
"%s(card %d): reread f1 because %d!=%d\n",
__func__, hc->id + 1, temp, f1);
f1 = temp; /* repeat until F1 is equal */
}
f2 = HFC_inb_nodebug(hc, A_F2);
}
z1 = HFC_inw_nodebug(hc, A_Z1) - hc->Zmin;
while (z1 != (temp = (HFC_inw_nodebug(hc, A_Z1) - hc->Zmin))) {
if (debug & DEBUG_HFCMULTI_FIFO)
printk(KERN_DEBUG "%s(card %d): reread z2 because "
"%d!=%d\n", __func__, hc->id + 1, temp, z2);
z1 = temp; /* repeat until Z1 is equal */
}
z2 = HFC_inw_nodebug(hc, A_Z2) - hc->Zmin;
Zsize = z1 - z2;
if ((dch || test_bit(FLG_HDLC, &bch->Flags)) && f1 != f2)
/* complete hdlc frame */
Zsize++;
if (Zsize < 0)
Zsize += hc->Zlen;
/* if buffer is empty */
if (Zsize <= 0)
return;
if (*sp == NULL) {
*sp = mI_alloc_skb(maxlen + 3, GFP_ATOMIC);
if (*sp == NULL) {
printk(KERN_DEBUG "%s: No mem for rx_skb\n",
__func__);
return;
}
}
/* show activity */
hc->activity[hc->chan[ch].port] = 1;
/* empty fifo with what we have */
if (dch || test_bit(FLG_HDLC, &bch->Flags)) {
if (debug & DEBUG_HFCMULTI_FIFO)
printk(KERN_DEBUG "%s(card %d): fifo(%d) reading %d "
"bytes (z1=%04x, z2=%04x) HDLC %s (f1=%d, f2=%d) "
"got=%d (again %d)\n", __func__, hc->id + 1, ch,
Zsize, z1, z2, (f1 == f2) ? "fragment" : "COMPLETE",
f1, f2, Zsize + (*sp)->len, again);
/* HDLC */
if ((Zsize + (*sp)->len) > (maxlen + 3)) {
if (debug & DEBUG_HFCMULTI_FIFO)
printk(KERN_DEBUG
"%s(card %d): hdlc-frame too large.\n",
__func__, hc->id + 1);
skb_trim(*sp, 0);
HFC_outb_nodebug(hc, R_INC_RES_FIFO, V_RES_F);
HFC_wait_nodebug(hc);
return;
}
hc->read_fifo(hc, skb_put(*sp, Zsize), Zsize);
if (f1 != f2) {
/* increment Z2,F2-counter */
HFC_outb_nodebug(hc, R_INC_RES_FIFO, V_INC_F);
HFC_wait_nodebug(hc);
/* check size */
if ((*sp)->len < 4) {
if (debug & DEBUG_HFCMULTI_FIFO)
printk(KERN_DEBUG
"%s(card %d): Frame below minimum "
"size\n", __func__, hc->id + 1);
skb_trim(*sp, 0);
goto next_frame;
}
/* there is at least one complete frame, check crc */
if ((*sp)->data[(*sp)->len - 1]) {
if (debug & DEBUG_HFCMULTI_CRC)
printk(KERN_DEBUG
"%s: CRC-error\n", __func__);
skb_trim(*sp, 0);
goto next_frame;
}
skb_trim(*sp, (*sp)->len - 3);
if ((*sp)->len < MISDN_COPY_SIZE) {
skb = *sp;
*sp = mI_alloc_skb(skb->len, GFP_ATOMIC);
if (*sp) {
memcpy(skb_put(*sp, skb->len),
skb->data, skb->len);
skb_trim(skb, 0);
} else {
printk(KERN_DEBUG "%s: No mem\n",
__func__);
*sp = skb;
skb = NULL;
}
} else {
skb = NULL;
}
if (debug & DEBUG_HFCMULTI_FIFO) {
printk(KERN_DEBUG "%s(card %d):",
__func__, hc->id + 1);
temp = 0;
while (temp < (*sp)->len)
printk(" %02x", (*sp)->data[temp++]);
printk("\n");
}
if (dch)
recv_Dchannel(dch);
else
recv_Bchannel(bch, MISDN_ID_ANY);
*sp = skb;
again++;
goto next_frame;
}
/* there is an incomplete frame */
} else {
/* transparent */
if (Zsize > skb_tailroom(*sp))
Zsize = skb_tailroom(*sp);
hc->read_fifo(hc, skb_put(*sp, Zsize), Zsize);
if (((*sp)->len) < MISDN_COPY_SIZE) {
skb = *sp;
*sp = mI_alloc_skb(skb->len, GFP_ATOMIC);
if (*sp) {
memcpy(skb_put(*sp, skb->len),
skb->data, skb->len);
skb_trim(skb, 0);
} else {
printk(KERN_DEBUG "%s: No mem\n", __func__);
*sp = skb;
skb = NULL;
}
} else {
skb = NULL;
}
if (debug & DEBUG_HFCMULTI_FIFO)
printk(KERN_DEBUG
"%s(card %d): fifo(%d) reading %d bytes "
"(z1=%04x, z2=%04x) TRANS\n",
__func__, hc->id + 1, ch, Zsize, z1, z2);
/* only bch is transparent */
recv_Bchannel(bch, hc->chan[ch].Zfill);
*sp = skb;
}
}
/*
* Interrupt handler
*/
static void
signal_state_up(struct dchannel *dch, int info, char *msg)
{
struct sk_buff *skb;
int id, data = info;
if (debug & DEBUG_HFCMULTI_STATE)
printk(KERN_DEBUG "%s: %s\n", __func__, msg);
id = TEI_SAPI | (GROUP_TEI << 8); /* manager address */
skb = _alloc_mISDN_skb(MPH_INFORMATION_IND, id, sizeof(data), &data,
GFP_ATOMIC);
if (!skb)
return;
recv_Dchannel_skb(dch, skb);
}
static inline void
handle_timer_irq(struct hfc_multi *hc)
{
int ch, temp;
struct dchannel *dch;
u_long flags;
/* process queued resync jobs */
if (hc->e1_resync) {
/* lock, so e1_resync gets not changed */
spin_lock_irqsave(&HFClock, flags);
if (hc->e1_resync & 1) {
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG "Enable SYNC_I\n");
HFC_outb(hc, R_SYNC_CTRL, V_EXT_CLK_SYNC);
/* disable JATT, if RX_SYNC is set */
if (test_bit(HFC_CHIP_RX_SYNC, &hc->chip))
HFC_outb(hc, R_SYNC_OUT, V_SYNC_E1_RX);
}
if (hc->e1_resync & 2) {
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG "Enable jatt PLL\n");
HFC_outb(hc, R_SYNC_CTRL, V_SYNC_OFFS);
}
if (hc->e1_resync & 4) {
if (debug & DEBUG_HFCMULTI_PLXSD)
printk(KERN_DEBUG
"Enable QUARTZ for HFC-E1\n");
/* set jatt to quartz */
HFC_outb(hc, R_SYNC_CTRL, V_EXT_CLK_SYNC
| V_JATT_OFF);
/* switch to JATT, in case it is not already */
HFC_outb(hc, R_SYNC_OUT, 0);
}
hc->e1_resync = 0;
spin_unlock_irqrestore(&HFClock, flags);
}
if (hc->ctype != HFC_TYPE_E1 || hc->e1_state == 1)
for (ch = 0; ch <= 31; ch++) {
if (hc->created[hc->chan[ch].port]) {
hfcmulti_tx(hc, ch);
/* fifo is started when switching to rx-fifo */
hfcmulti_rx(hc, ch);
if (hc->chan[ch].dch &&
hc->chan[ch].nt_timer > -1) {
dch = hc->chan[ch].dch;
if (!(--hc->chan[ch].nt_timer)) {
schedule_event(dch,
FLG_PHCHANGE);
if (debug &
DEBUG_HFCMULTI_STATE)
printk(KERN_DEBUG
"%s: nt_timer at "
"state %x\n",
__func__,
dch->state);
}
}
}
}
if (hc->ctype == HFC_TYPE_E1 && hc->created[0]) {
dch = hc->chan[hc->dslot].dch;
if (test_bit(HFC_CFG_REPORT_LOS, &hc->chan[hc->dslot].cfg)) {
/* LOS */
temp = HFC_inb_nodebug(hc, R_SYNC_STA) & V_SIG_LOS;
if (!temp && hc->chan[hc->dslot].los)
signal_state_up(dch, L1_SIGNAL_LOS_ON,
"LOS detected");
if (temp && !hc->chan[hc->dslot].los)
signal_state_up(dch, L1_SIGNAL_LOS_OFF,
"LOS gone");
hc->chan[hc->dslot].los = temp;
}
if (test_bit(HFC_CFG_REPORT_AIS, &hc->chan[hc->dslot].cfg)) {
/* AIS */
temp = HFC_inb_nodebug(hc, R_SYNC_STA) & V_AIS;
if (!temp && hc->chan[hc->dslot].ais)
signal_state_up(dch, L1_SIGNAL_AIS_ON,
"AIS detected");
if (temp && !hc->chan[hc->dslot].ais)
signal_state_up(dch, L1_SIGNAL_AIS_OFF,
"AIS gone");
hc->chan[hc->dslot].ais = temp;
}
if (test_bit(HFC_CFG_REPORT_SLIP, &hc->chan[hc->dslot].cfg)) {
/* SLIP */
temp = HFC_inb_nodebug(hc, R_SLIP) & V_FOSLIP_RX;
if (!temp && hc->chan[hc->dslot].slip_rx)
signal_state_up(dch, L1_SIGNAL_SLIP_RX,
" bit SLIP detected RX");
hc->chan[hc->dslot].slip_rx = temp;
temp = HFC_inb_nodebug(hc, R_SLIP) & V_FOSLIP_TX;
if (!temp && hc->chan[hc->dslot].slip_tx)
signal_state_up(dch, L1_SIGNAL_SLIP_TX,
" bit SLIP detected TX");
hc->chan[hc->dslot].slip_tx = temp;
}
if (test_bit(HFC_CFG_REPORT_RDI, &hc->chan[hc->dslot].cfg)) {
/* RDI */
temp = HFC_inb_nodebug(hc, R_RX_SL0_0) & V_A;
if (!temp && hc->chan[hc->dslot].rdi)
signal_state_up(dch, L1_SIGNAL_RDI_ON,
"RDI detected");
if (temp && !hc->chan[hc->dslot].rdi)
signal_state_up(dch, L1_SIGNAL_RDI_OFF,
"RDI gone");
hc->chan[hc->dslot].rdi = temp;
}
temp = HFC_inb_nodebug(hc, R_JATT_DIR);
switch (hc->chan[hc->dslot].sync) {
case 0:
if ((temp & 0x60) == 0x60) {
if (debug & DEBUG_HFCMULTI_SYNC)
printk(KERN_DEBUG
"%s: (id=%d) E1 now "
"in clock sync\n",
__func__, hc->id);
HFC_outb(hc, R_RX_OFF,
hc->chan[hc->dslot].jitter | V_RX_INIT);
HFC_outb(hc, R_TX_OFF,
hc->chan[hc->dslot].jitter | V_RX_INIT);
hc->chan[hc->dslot].sync = 1;
goto check_framesync;
}
break;
case 1:
if ((temp & 0x60) != 0x60) {
if (debug & DEBUG_HFCMULTI_SYNC)
printk(KERN_DEBUG
"%s: (id=%d) E1 "
"lost clock sync\n",
__func__, hc->id);
hc->chan[hc->dslot].sync = 0;
break;
}
check_framesync:
temp = HFC_inb_nodebug(hc, R_SYNC_STA);
if (temp == 0x27) {
if (debug & DEBUG_HFCMULTI_SYNC)
printk(KERN_DEBUG
"%s: (id=%d) E1 "
"now in frame sync\n",
__func__, hc->id);
hc->chan[hc->dslot].sync = 2;
}
break;
case 2:
if ((temp & 0x60) != 0x60) {
if (debug & DEBUG_HFCMULTI_SYNC)
printk(KERN_DEBUG
"%s: (id=%d) E1 lost "
"clock & frame sync\n",
__func__, hc->id);
hc->chan[hc->dslot].sync = 0;
break;
}
temp = HFC_inb_nodebug(hc, R_SYNC_STA);
if (temp != 0x27) {
if (debug & DEBUG_HFCMULTI_SYNC)
printk(KERN_DEBUG
"%s: (id=%d) E1 "
"lost frame sync\n",
__func__, hc->id);
hc->chan[hc->dslot].sync = 1;
}
break;
}
}
if (test_bit(HFC_CHIP_WATCHDOG, &hc->chip))
hfcmulti_watchdog(hc);
if (hc->leds)
hfcmulti_leds(hc);
}
static void
ph_state_irq(struct hfc_multi *hc, u_char r_irq_statech)
{
struct dchannel *dch;
int ch;
int active;
u_char st_status, temp;
/* state machine */
for (ch = 0; ch <= 31; ch++) {
if (hc->chan[ch].dch) {
dch = hc->chan[ch].dch;
if (r_irq_statech & 1) {
HFC_outb_nodebug(hc, R_ST_SEL,
hc->chan[ch].port);
/* undocumented: delay after R_ST_SEL */
udelay(1);
/* undocumented: status changes during read */
st_status = HFC_inb_nodebug(hc, A_ST_RD_STATE);
while (st_status != (temp =
HFC_inb_nodebug(hc, A_ST_RD_STATE))) {
if (debug & DEBUG_HFCMULTI_STATE)
printk(KERN_DEBUG "%s: reread "
"STATE because %d!=%d\n",
__func__, temp,
st_status);
st_status = temp; /* repeat */
}
/* Speech Design TE-sync indication */
if (test_bit(HFC_CHIP_PLXSD, &hc->chip) &&
dch->dev.D.protocol == ISDN_P_TE_S0) {
if (st_status & V_FR_SYNC_ST)
hc->syncronized |=
(1 << hc->chan[ch].port);
else
hc->syncronized &=
~(1 << hc->chan[ch].port);
}
dch->state = st_status & 0x0f;
if (dch->dev.D.protocol == ISDN_P_NT_S0)
active = 3;
else
active = 7;
if (dch->state == active) {
HFC_outb_nodebug(hc, R_FIFO,
(ch << 1) | 1);
HFC_wait_nodebug(hc);
HFC_outb_nodebug(hc,
R_INC_RES_FIFO, V_RES_F);
HFC_wait_nodebug(hc);
dch->tx_idx = 0;
}
schedule_event(dch, FLG_PHCHANGE);
if (debug & DEBUG_HFCMULTI_STATE)
printk(KERN_DEBUG
"%s: S/T newstate %x port %d\n",
__func__, dch->state,
hc->chan[ch].port);
}
r_irq_statech >>= 1;
}
}
if (test_bit(HFC_CHIP_PLXSD, &hc->chip))
plxsd_checksync(hc, 0);
}
static void
fifo_irq(struct hfc_multi *hc, int block)
{
int ch, j;
struct dchannel *dch;
struct bchannel *bch;
u_char r_irq_fifo_bl;
r_irq_fifo_bl = HFC_inb_nodebug(hc, R_IRQ_FIFO_BL0 + block);
j = 0;
while (j < 8) {
ch = (block << 2) + (j >> 1);
dch = hc->chan[ch].dch;
bch = hc->chan[ch].bch;
if (((!dch) && (!bch)) || (!hc->created[hc->chan[ch].port])) {
j += 2;
continue;
}
if (dch && (r_irq_fifo_bl & (1 << j)) &&
test_bit(FLG_ACTIVE, &dch->Flags)) {
hfcmulti_tx(hc, ch);
/* start fifo */
HFC_outb_nodebug(hc, R_FIFO, 0);
HFC_wait_nodebug(hc);
}
if (bch && (r_irq_fifo_bl & (1 << j)) &&
test_bit(FLG_ACTIVE, &bch->Flags)) {
hfcmulti_tx(hc, ch);
/* start fifo */
HFC_outb_nodebug(hc, R_FIFO, 0);
HFC_wait_nodebug(hc);
}
j++;
if (dch && (r_irq_fifo_bl & (1 << j)) &&
test_bit(FLG_ACTIVE, &dch->Flags)) {
hfcmulti_rx(hc, ch);
}
if (bch && (r_irq_fifo_bl & (1 << j)) &&
test_bit(FLG_ACTIVE, &bch->Flags)) {
hfcmulti_rx(hc, ch);
}
j++;
}
}
#ifdef IRQ_DEBUG
int irqsem;
#endif
static irqreturn_t
hfcmulti_interrupt(int intno, void *dev_id)
{
#ifdef IRQCOUNT_DEBUG
static int iq1 = 0, iq2 = 0, iq3 = 0, iq4 = 0,
iq5 = 0, iq6 = 0, iqcnt = 0;
#endif
struct hfc_multi *hc = dev_id;
struct dchannel *dch;
u_char r_irq_statech, status, r_irq_misc, r_irq_oview;
int i;
void __iomem *plx_acc;
u_short wval;
u_char e1_syncsta, temp;
u_long flags;
if (!hc) {
printk(KERN_ERR "HFC-multi: Spurious interrupt!\n");
return IRQ_NONE;
}
spin_lock(&hc->lock);
#ifdef IRQ_DEBUG
if (irqsem)
printk(KERN_ERR "irq for card %d during irq from "
"card %d, this is no bug.\n", hc->id + 1, irqsem);
irqsem = hc->id + 1;
#endif
#ifdef CONFIG_MISDN_HFCMULTI_8xx
if (hc->immap->im_cpm.cp_pbdat & hc->pb_irqmsk)
goto irq_notforus;
#endif
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
spin_lock_irqsave(&plx_lock, flags);
plx_acc = hc->plx_membase + PLX_INTCSR;
wval = readw(plx_acc);
spin_unlock_irqrestore(&plx_lock, flags);
if (!(wval & PLX_INTCSR_LINTI1_STATUS))
goto irq_notforus;
}
status = HFC_inb_nodebug(hc, R_STATUS);
r_irq_statech = HFC_inb_nodebug(hc, R_IRQ_STATECH);
#ifdef IRQCOUNT_DEBUG
if (r_irq_statech)
iq1++;
if (status & V_DTMF_STA)
iq2++;
if (status & V_LOST_STA)
iq3++;
if (status & V_EXT_IRQSTA)
iq4++;
if (status & V_MISC_IRQSTA)
iq5++;
if (status & V_FR_IRQSTA)
iq6++;
if (iqcnt++ > 5000) {
printk(KERN_ERR "iq1:%x iq2:%x iq3:%x iq4:%x iq5:%x iq6:%x\n",
iq1, iq2, iq3, iq4, iq5, iq6);
iqcnt = 0;
}
#endif
if (!r_irq_statech &&
!(status & (V_DTMF_STA | V_LOST_STA | V_EXT_IRQSTA |
V_MISC_IRQSTA | V_FR_IRQSTA))) {
/* irq is not for us */
goto irq_notforus;
}
hc->irqcnt++;
if (r_irq_statech) {
if (hc->ctype != HFC_TYPE_E1)
ph_state_irq(hc, r_irq_statech);
}
if (status & V_EXT_IRQSTA)
; /* external IRQ */
if (status & V_LOST_STA) {
/* LOST IRQ */
HFC_outb(hc, R_INC_RES_FIFO, V_RES_LOST); /* clear irq! */
}
if (status & V_MISC_IRQSTA) {
/* misc IRQ */
r_irq_misc = HFC_inb_nodebug(hc, R_IRQ_MISC);
r_irq_misc &= hc->hw.r_irqmsk_misc; /* ignore disabled irqs */
if (r_irq_misc & V_STA_IRQ) {
if (hc->ctype == HFC_TYPE_E1) {
/* state machine */
dch = hc->chan[hc->dslot].dch;
e1_syncsta = HFC_inb_nodebug(hc, R_SYNC_STA);
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)
&& hc->e1_getclock) {
if (e1_syncsta & V_FR_SYNC_E1)
hc->syncronized = 1;
else
hc->syncronized = 0;
}
/* undocumented: status changes during read */
dch->state = HFC_inb_nodebug(hc, R_E1_RD_STA);
while (dch->state != (temp =
HFC_inb_nodebug(hc, R_E1_RD_STA))) {
if (debug & DEBUG_HFCMULTI_STATE)
printk(KERN_DEBUG "%s: reread "
"STATE because %d!=%d\n",
__func__, temp,
dch->state);
dch->state = temp; /* repeat */
}
dch->state = HFC_inb_nodebug(hc, R_E1_RD_STA)
& 0x7;
schedule_event(dch, FLG_PHCHANGE);
if (debug & DEBUG_HFCMULTI_STATE)
printk(KERN_DEBUG
"%s: E1 (id=%d) newstate %x\n",
__func__, hc->id, dch->state);
if (test_bit(HFC_CHIP_PLXSD, &hc->chip))
plxsd_checksync(hc, 0);
}
}
if (r_irq_misc & V_TI_IRQ) {
if (hc->iclock_on)
mISDN_clock_update(hc->iclock, poll, NULL);
handle_timer_irq(hc);
}
if (r_irq_misc & V_DTMF_IRQ)
hfcmulti_dtmf(hc);
if (r_irq_misc & V_IRQ_PROC) {
static int irq_proc_cnt;
if (!irq_proc_cnt++)
printk(KERN_DEBUG "%s: got V_IRQ_PROC -"
" this should not happen\n", __func__);
}
}
if (status & V_FR_IRQSTA) {
/* FIFO IRQ */
r_irq_oview = HFC_inb_nodebug(hc, R_IRQ_OVIEW);
for (i = 0; i < 8; i++) {
if (r_irq_oview & (1 << i))
fifo_irq(hc, i);
}
}
#ifdef IRQ_DEBUG
irqsem = 0;
#endif
spin_unlock(&hc->lock);
return IRQ_HANDLED;
irq_notforus:
#ifdef IRQ_DEBUG
irqsem = 0;
#endif
spin_unlock(&hc->lock);
return IRQ_NONE;
}
/*
* timer callback for D-chan busy resolution. Currently no function
*/
static void
hfcmulti_dbusy_timer(struct hfc_multi *hc)
{
}
/*
* activate/deactivate hardware for selected channels and mode
*
* configure B-channel with the given protocol
* ch eqals to the HFC-channel (0-31)
* ch is the number of channel (0-4,4-7,8-11,12-15,16-19,20-23,24-27,28-31
* for S/T, 1-31 for E1)
* the hdlc interrupts will be set/unset
*/
static int
mode_hfcmulti(struct hfc_multi *hc, int ch, int protocol, int slot_tx,
int bank_tx, int slot_rx, int bank_rx)
{
int flow_tx = 0, flow_rx = 0, routing = 0;
int oslot_tx, oslot_rx;
int conf;
if (ch < 0 || ch > 31)
return -EINVAL;
oslot_tx = hc->chan[ch].slot_tx;
oslot_rx = hc->chan[ch].slot_rx;
conf = hc->chan[ch].conf;
if (debug & DEBUG_HFCMULTI_MODE)
printk(KERN_DEBUG
"%s: card %d channel %d protocol %x slot old=%d new=%d "
"bank new=%d (TX) slot old=%d new=%d bank new=%d (RX)\n",
__func__, hc->id, ch, protocol, oslot_tx, slot_tx,
bank_tx, oslot_rx, slot_rx, bank_rx);
if (oslot_tx >= 0 && slot_tx != oslot_tx) {
/* remove from slot */
if (debug & DEBUG_HFCMULTI_MODE)
printk(KERN_DEBUG "%s: remove from slot %d (TX)\n",
__func__, oslot_tx);
if (hc->slot_owner[oslot_tx << 1] == ch) {
HFC_outb(hc, R_SLOT, oslot_tx << 1);
HFC_outb(hc, A_SL_CFG, 0);
if (hc->ctype != HFC_TYPE_XHFC)
HFC_outb(hc, A_CONF, 0);
hc->slot_owner[oslot_tx << 1] = -1;
} else {
if (debug & DEBUG_HFCMULTI_MODE)
printk(KERN_DEBUG
"%s: we are not owner of this tx slot "
"anymore, channel %d is.\n",
__func__, hc->slot_owner[oslot_tx << 1]);
}
}
if (oslot_rx >= 0 && slot_rx != oslot_rx) {
/* remove from slot */
if (debug & DEBUG_HFCMULTI_MODE)
printk(KERN_DEBUG
"%s: remove from slot %d (RX)\n",
__func__, oslot_rx);
if (hc->slot_owner[(oslot_rx << 1) | 1] == ch) {
HFC_outb(hc, R_SLOT, (oslot_rx << 1) | V_SL_DIR);
HFC_outb(hc, A_SL_CFG, 0);
hc->slot_owner[(oslot_rx << 1) | 1] = -1;
} else {
if (debug & DEBUG_HFCMULTI_MODE)
printk(KERN_DEBUG
"%s: we are not owner of this rx slot "
"anymore, channel %d is.\n",
__func__,
hc->slot_owner[(oslot_rx << 1) | 1]);
}
}
if (slot_tx < 0) {
flow_tx = 0x80; /* FIFO->ST */
/* disable pcm slot */
hc->chan[ch].slot_tx = -1;
hc->chan[ch].bank_tx = 0;
} else {
/* set pcm slot */
if (hc->chan[ch].txpending)
flow_tx = 0x80; /* FIFO->ST */
else
flow_tx = 0xc0; /* PCM->ST */
/* put on slot */
routing = bank_tx ? 0xc0 : 0x80;
if (conf >= 0 || bank_tx > 1)
routing = 0x40; /* loop */
if (debug & DEBUG_HFCMULTI_MODE)
printk(KERN_DEBUG "%s: put channel %d to slot %d bank"
" %d flow %02x routing %02x conf %d (TX)\n",
__func__, ch, slot_tx, bank_tx,
flow_tx, routing, conf);
HFC_outb(hc, R_SLOT, slot_tx << 1);
HFC_outb(hc, A_SL_CFG, (ch << 1) | routing);
if (hc->ctype != HFC_TYPE_XHFC)
HFC_outb(hc, A_CONF,
(conf < 0) ? 0 : (conf | V_CONF_SL));
hc->slot_owner[slot_tx << 1] = ch;
hc->chan[ch].slot_tx = slot_tx;
hc->chan[ch].bank_tx = bank_tx;
}
if (slot_rx < 0) {
/* disable pcm slot */
flow_rx = 0x80; /* ST->FIFO */
hc->chan[ch].slot_rx = -1;
hc->chan[ch].bank_rx = 0;
} else {
/* set pcm slot */
if (hc->chan[ch].txpending)
flow_rx = 0x80; /* ST->FIFO */
else
flow_rx = 0xc0; /* ST->(FIFO,PCM) */
/* put on slot */
routing = bank_rx ? 0x80 : 0xc0; /* reversed */
if (conf >= 0 || bank_rx > 1)
routing = 0x40; /* loop */
if (debug & DEBUG_HFCMULTI_MODE)
printk(KERN_DEBUG "%s: put channel %d to slot %d bank"
" %d flow %02x routing %02x conf %d (RX)\n",
__func__, ch, slot_rx, bank_rx,
flow_rx, routing, conf);
HFC_outb(hc, R_SLOT, (slot_rx << 1) | V_SL_DIR);
HFC_outb(hc, A_SL_CFG, (ch << 1) | V_CH_DIR | routing);
hc->slot_owner[(slot_rx << 1) | 1] = ch;
hc->chan[ch].slot_rx = slot_rx;
hc->chan[ch].bank_rx = bank_rx;
}
switch (protocol) {
case (ISDN_P_NONE):
/* disable TX fifo */
HFC_outb(hc, R_FIFO, ch << 1);
HFC_wait(hc);
HFC_outb(hc, A_CON_HDLC, flow_tx | 0x00 | V_IFF);
HFC_outb(hc, A_SUBCH_CFG, 0);
HFC_outb(hc, A_IRQ_MSK, 0);
HFC_outb(hc, R_INC_RES_FIFO, V_RES_F);
HFC_wait(hc);
/* disable RX fifo */
HFC_outb(hc, R_FIFO, (ch << 1) | 1);
HFC_wait(hc);
HFC_outb(hc, A_CON_HDLC, flow_rx | 0x00);
HFC_outb(hc, A_SUBCH_CFG, 0);
HFC_outb(hc, A_IRQ_MSK, 0);
HFC_outb(hc, R_INC_RES_FIFO, V_RES_F);
HFC_wait(hc);
if (hc->chan[ch].bch && hc->ctype != HFC_TYPE_E1) {
hc->hw.a_st_ctrl0[hc->chan[ch].port] &=
((ch & 0x3) == 0) ? ~V_B1_EN : ~V_B2_EN;
HFC_outb(hc, R_ST_SEL, hc->chan[ch].port);
/* undocumented: delay after R_ST_SEL */
udelay(1);
HFC_outb(hc, A_ST_CTRL0,
hc->hw.a_st_ctrl0[hc->chan[ch].port]);
}
if (hc->chan[ch].bch) {
test_and_clear_bit(FLG_HDLC, &hc->chan[ch].bch->Flags);
test_and_clear_bit(FLG_TRANSPARENT,
&hc->chan[ch].bch->Flags);
}
break;
case (ISDN_P_B_RAW): /* B-channel */
if (test_bit(HFC_CHIP_B410P, &hc->chip) &&
(hc->chan[ch].slot_rx < 0) &&
(hc->chan[ch].slot_tx < 0)) {
printk(KERN_DEBUG
"Setting B-channel %d to echo cancelable "
"state on PCM slot %d\n", ch,
((ch / 4) * 8) + ((ch % 4) * 4) + 1);
printk(KERN_DEBUG
"Enabling pass through for channel\n");
vpm_out(hc, ch, ((ch / 4) * 8) +
((ch % 4) * 4) + 1, 0x01);
/* rx path */
/* S/T -> PCM */
HFC_outb(hc, R_FIFO, (ch << 1));
HFC_wait(hc);
HFC_outb(hc, A_CON_HDLC, 0xc0 | V_HDLC_TRP | V_IFF);
HFC_outb(hc, R_SLOT, (((ch / 4) * 8) +
((ch % 4) * 4) + 1) << 1);
HFC_outb(hc, A_SL_CFG, 0x80 | (ch << 1));
/* PCM -> FIFO */
HFC_outb(hc, R_FIFO, 0x20 | (ch << 1) | 1);
HFC_wait(hc);
HFC_outb(hc, A_CON_HDLC, 0x20 | V_HDLC_TRP | V_IFF);
HFC_outb(hc, A_SUBCH_CFG, 0);
HFC_outb(hc, A_IRQ_MSK, 0);
HFC_outb(hc, R_INC_RES_FIFO, V_RES_F);
HFC_wait(hc);
HFC_outb(hc, R_SLOT, ((((ch / 4) * 8) +
((ch % 4) * 4) + 1) << 1) | 1);
HFC_outb(hc, A_SL_CFG, 0x80 | 0x20 | (ch << 1) | 1);
/* tx path */
/* PCM -> S/T */
HFC_outb(hc, R_FIFO, (ch << 1) | 1);
HFC_wait(hc);
HFC_outb(hc, A_CON_HDLC, 0xc0 | V_HDLC_TRP | V_IFF);
HFC_outb(hc, R_SLOT, ((((ch / 4) * 8) +
((ch % 4) * 4)) << 1) | 1);
HFC_outb(hc, A_SL_CFG, 0x80 | 0x40 | (ch << 1) | 1);
/* FIFO -> PCM */
HFC_outb(hc, R_FIFO, 0x20 | (ch << 1));
HFC_wait(hc);
HFC_outb(hc, A_CON_HDLC, 0x20 | V_HDLC_TRP | V_IFF);
HFC_outb(hc, A_SUBCH_CFG, 0);
HFC_outb(hc, A_IRQ_MSK, 0);
HFC_outb(hc, R_INC_RES_FIFO, V_RES_F);
HFC_wait(hc);
/* tx silence */
HFC_outb_nodebug(hc, A_FIFO_DATA0_NOINC, hc->silence);
HFC_outb(hc, R_SLOT, (((ch / 4) * 8) +
((ch % 4) * 4)) << 1);
HFC_outb(hc, A_SL_CFG, 0x80 | 0x20 | (ch << 1));
} else {
/* enable TX fifo */
HFC_outb(hc, R_FIFO, ch << 1);
HFC_wait(hc);
if (hc->ctype == HFC_TYPE_XHFC)
HFC_outb(hc, A_CON_HDLC, flow_tx | 0x07 << 2 |
V_HDLC_TRP | V_IFF);
/* Enable FIFO, no interrupt */
else
HFC_outb(hc, A_CON_HDLC, flow_tx | 0x00 |
V_HDLC_TRP | V_IFF);
HFC_outb(hc, A_SUBCH_CFG, 0);
HFC_outb(hc, A_IRQ_MSK, 0);
HFC_outb(hc, R_INC_RES_FIFO, V_RES_F);
HFC_wait(hc);
/* tx silence */
HFC_outb_nodebug(hc, A_FIFO_DATA0_NOINC, hc->silence);
/* enable RX fifo */
HFC_outb(hc, R_FIFO, (ch << 1) | 1);
HFC_wait(hc);
if (hc->ctype == HFC_TYPE_XHFC)
HFC_outb(hc, A_CON_HDLC, flow_rx | 0x07 << 2 |
V_HDLC_TRP);
/* Enable FIFO, no interrupt*/
else
HFC_outb(hc, A_CON_HDLC, flow_rx | 0x00 |
V_HDLC_TRP);
HFC_outb(hc, A_SUBCH_CFG, 0);
HFC_outb(hc, A_IRQ_MSK, 0);
HFC_outb(hc, R_INC_RES_FIFO, V_RES_F);
HFC_wait(hc);
}
if (hc->ctype != HFC_TYPE_E1) {
hc->hw.a_st_ctrl0[hc->chan[ch].port] |=
((ch & 0x3) == 0) ? V_B1_EN : V_B2_EN;
HFC_outb(hc, R_ST_SEL, hc->chan[ch].port);
/* undocumented: delay after R_ST_SEL */
udelay(1);
HFC_outb(hc, A_ST_CTRL0,
hc->hw.a_st_ctrl0[hc->chan[ch].port]);
}
if (hc->chan[ch].bch)
test_and_set_bit(FLG_TRANSPARENT,
&hc->chan[ch].bch->Flags);
break;
case (ISDN_P_B_HDLC): /* B-channel */
case (ISDN_P_TE_S0): /* D-channel */
case (ISDN_P_NT_S0):
case (ISDN_P_TE_E1):
case (ISDN_P_NT_E1):
/* enable TX fifo */
HFC_outb(hc, R_FIFO, ch << 1);
HFC_wait(hc);
if (hc->ctype == HFC_TYPE_E1 || hc->chan[ch].bch) {
/* E1 or B-channel */
HFC_outb(hc, A_CON_HDLC, flow_tx | 0x04);
HFC_outb(hc, A_SUBCH_CFG, 0);
} else {
/* D-Channel without HDLC fill flags */
HFC_outb(hc, A_CON_HDLC, flow_tx | 0x04 | V_IFF);
HFC_outb(hc, A_SUBCH_CFG, 2);
}
HFC_outb(hc, A_IRQ_MSK, V_IRQ);
HFC_outb(hc, R_INC_RES_FIFO, V_RES_F);
HFC_wait(hc);
/* enable RX fifo */
HFC_outb(hc, R_FIFO, (ch << 1) | 1);
HFC_wait(hc);
HFC_outb(hc, A_CON_HDLC, flow_rx | 0x04);
if (hc->ctype == HFC_TYPE_E1 || hc->chan[ch].bch)
HFC_outb(hc, A_SUBCH_CFG, 0); /* full 8 bits */
else
HFC_outb(hc, A_SUBCH_CFG, 2); /* 2 bits dchannel */
HFC_outb(hc, A_IRQ_MSK, V_IRQ);
HFC_outb(hc, R_INC_RES_FIFO, V_RES_F);
HFC_wait(hc);
if (hc->chan[ch].bch) {
test_and_set_bit(FLG_HDLC, &hc->chan[ch].bch->Flags);
if (hc->ctype != HFC_TYPE_E1) {
hc->hw.a_st_ctrl0[hc->chan[ch].port] |=
((ch & 0x3) == 0) ? V_B1_EN : V_B2_EN;
HFC_outb(hc, R_ST_SEL, hc->chan[ch].port);
/* undocumented: delay after R_ST_SEL */
udelay(1);
HFC_outb(hc, A_ST_CTRL0,
hc->hw.a_st_ctrl0[hc->chan[ch].port]);
}
}
break;
default:
printk(KERN_DEBUG "%s: protocol not known %x\n",
__func__, protocol);
hc->chan[ch].protocol = ISDN_P_NONE;
return -ENOPROTOOPT;
}
hc->chan[ch].protocol = protocol;
return 0;
}
/*
* connect/disconnect PCM
*/
static void
hfcmulti_pcm(struct hfc_multi *hc, int ch, int slot_tx, int bank_tx,
int slot_rx, int bank_rx)
{
if (slot_tx < 0 || slot_rx < 0 || bank_tx < 0 || bank_rx < 0) {
/* disable PCM */
mode_hfcmulti(hc, ch, hc->chan[ch].protocol, -1, 0, -1, 0);
return;
}
/* enable pcm */
mode_hfcmulti(hc, ch, hc->chan[ch].protocol, slot_tx, bank_tx,
slot_rx, bank_rx);
}
/*
* set/disable conference
*/
static void
hfcmulti_conf(struct hfc_multi *hc, int ch, int num)
{
if (num >= 0 && num <= 7)
hc->chan[ch].conf = num;
else
hc->chan[ch].conf = -1;
mode_hfcmulti(hc, ch, hc->chan[ch].protocol, hc->chan[ch].slot_tx,
hc->chan[ch].bank_tx, hc->chan[ch].slot_rx,
hc->chan[ch].bank_rx);
}
/*
* set/disable sample loop
*/
/* NOTE: this function is experimental and therefore disabled */
/*
* Layer 1 callback function
*/
static int
hfcm_l1callback(struct dchannel *dch, u_int cmd)
{
struct hfc_multi *hc = dch->hw;
u_long flags;
switch (cmd) {
case INFO3_P8:
case INFO3_P10:
break;
case HW_RESET_REQ:
/* start activation */
spin_lock_irqsave(&hc->lock, flags);
if (hc->ctype == HFC_TYPE_E1) {
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG
"%s: HW_RESET_REQ no BRI\n",
__func__);
} else {
HFC_outb(hc, R_ST_SEL, hc->chan[dch->slot].port);
/* undocumented: delay after R_ST_SEL */
udelay(1);
HFC_outb(hc, A_ST_WR_STATE, V_ST_LD_STA | 3); /* F3 */
udelay(6); /* wait at least 5,21us */
HFC_outb(hc, A_ST_WR_STATE, 3);
HFC_outb(hc, A_ST_WR_STATE, 3 | (V_ST_ACT * 3));
/* activate */
}
spin_unlock_irqrestore(&hc->lock, flags);
l1_event(dch->l1, HW_POWERUP_IND);
break;
case HW_DEACT_REQ:
/* start deactivation */
spin_lock_irqsave(&hc->lock, flags);
if (hc->ctype == HFC_TYPE_E1) {
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG
"%s: HW_DEACT_REQ no BRI\n",
__func__);
} else {
HFC_outb(hc, R_ST_SEL, hc->chan[dch->slot].port);
/* undocumented: delay after R_ST_SEL */
udelay(1);
HFC_outb(hc, A_ST_WR_STATE, V_ST_ACT * 2);
/* deactivate */
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
hc->syncronized &=
~(1 << hc->chan[dch->slot].port);
plxsd_checksync(hc, 0);
}
}
skb_queue_purge(&dch->squeue);
if (dch->tx_skb) {
dev_kfree_skb(dch->tx_skb);
dch->tx_skb = NULL;
}
dch->tx_idx = 0;
if (dch->rx_skb) {
dev_kfree_skb(dch->rx_skb);
dch->rx_skb = NULL;
}
test_and_clear_bit(FLG_TX_BUSY, &dch->Flags);
if (test_and_clear_bit(FLG_BUSY_TIMER, &dch->Flags))
del_timer(&dch->timer);
spin_unlock_irqrestore(&hc->lock, flags);
break;
case HW_POWERUP_REQ:
spin_lock_irqsave(&hc->lock, flags);
if (hc->ctype == HFC_TYPE_E1) {
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG
"%s: HW_POWERUP_REQ no BRI\n",
__func__);
} else {
HFC_outb(hc, R_ST_SEL, hc->chan[dch->slot].port);
/* undocumented: delay after R_ST_SEL */
udelay(1);
HFC_outb(hc, A_ST_WR_STATE, 3 | 0x10); /* activate */
udelay(6); /* wait at least 5,21us */
HFC_outb(hc, A_ST_WR_STATE, 3); /* activate */
}
spin_unlock_irqrestore(&hc->lock, flags);
break;
case PH_ACTIVATE_IND:
test_and_set_bit(FLG_ACTIVE, &dch->Flags);
_queue_data(&dch->dev.D, cmd, MISDN_ID_ANY, 0, NULL,
GFP_ATOMIC);
break;
case PH_DEACTIVATE_IND:
test_and_clear_bit(FLG_ACTIVE, &dch->Flags);
_queue_data(&dch->dev.D, cmd, MISDN_ID_ANY, 0, NULL,
GFP_ATOMIC);
break;
default:
if (dch->debug & DEBUG_HW)
printk(KERN_DEBUG "%s: unknown command %x\n",
__func__, cmd);
return -1;
}
return 0;
}
/*
* Layer2 -> Layer 1 Transfer
*/
static int
handle_dmsg(struct mISDNchannel *ch, struct sk_buff *skb)
{
struct mISDNdevice *dev = container_of(ch, struct mISDNdevice, D);
struct dchannel *dch = container_of(dev, struct dchannel, dev);
struct hfc_multi *hc = dch->hw;
struct mISDNhead *hh = mISDN_HEAD_P(skb);
int ret = -EINVAL;
unsigned int id;
u_long flags;
switch (hh->prim) {
case PH_DATA_REQ:
if (skb->len < 1)
break;
spin_lock_irqsave(&hc->lock, flags);
ret = dchannel_senddata(dch, skb);
if (ret > 0) { /* direct TX */
id = hh->id; /* skb can be freed */
hfcmulti_tx(hc, dch->slot);
ret = 0;
/* start fifo */
HFC_outb(hc, R_FIFO, 0);
HFC_wait(hc);
spin_unlock_irqrestore(&hc->lock, flags);
queue_ch_frame(ch, PH_DATA_CNF, id, NULL);
} else
spin_unlock_irqrestore(&hc->lock, flags);
return ret;
case PH_ACTIVATE_REQ:
if (dch->dev.D.protocol != ISDN_P_TE_S0) {
spin_lock_irqsave(&hc->lock, flags);
ret = 0;
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG
"%s: PH_ACTIVATE port %d (0..%d)\n",
__func__, hc->chan[dch->slot].port,
hc->ports - 1);
/* start activation */
if (hc->ctype == HFC_TYPE_E1) {
ph_state_change(dch);
if (debug & DEBUG_HFCMULTI_STATE)
printk(KERN_DEBUG
"%s: E1 report state %x \n",
__func__, dch->state);
} else {
HFC_outb(hc, R_ST_SEL,
hc->chan[dch->slot].port);
/* undocumented: delay after R_ST_SEL */
udelay(1);
HFC_outb(hc, A_ST_WR_STATE, V_ST_LD_STA | 1);
/* G1 */
udelay(6); /* wait at least 5,21us */
HFC_outb(hc, A_ST_WR_STATE, 1);
HFC_outb(hc, A_ST_WR_STATE, 1 |
(V_ST_ACT * 3)); /* activate */
dch->state = 1;
}
spin_unlock_irqrestore(&hc->lock, flags);
} else
ret = l1_event(dch->l1, hh->prim);
break;
case PH_DEACTIVATE_REQ:
test_and_clear_bit(FLG_L2_ACTIVATED, &dch->Flags);
if (dch->dev.D.protocol != ISDN_P_TE_S0) {
spin_lock_irqsave(&hc->lock, flags);
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG
"%s: PH_DEACTIVATE port %d (0..%d)\n",
__func__, hc->chan[dch->slot].port,
hc->ports - 1);
/* start deactivation */
if (hc->ctype == HFC_TYPE_E1) {
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG
"%s: PH_DEACTIVATE no BRI\n",
__func__);
} else {
HFC_outb(hc, R_ST_SEL,
hc->chan[dch->slot].port);
/* undocumented: delay after R_ST_SEL */
udelay(1);
HFC_outb(hc, A_ST_WR_STATE, V_ST_ACT * 2);
/* deactivate */
dch->state = 1;
}
skb_queue_purge(&dch->squeue);
if (dch->tx_skb) {
dev_kfree_skb(dch->tx_skb);
dch->tx_skb = NULL;
}
dch->tx_idx = 0;
if (dch->rx_skb) {
dev_kfree_skb(dch->rx_skb);
dch->rx_skb = NULL;
}
test_and_clear_bit(FLG_TX_BUSY, &dch->Flags);
if (test_and_clear_bit(FLG_BUSY_TIMER, &dch->Flags))
del_timer(&dch->timer);
#ifdef FIXME
if (test_and_clear_bit(FLG_L1_BUSY, &dch->Flags))
dchannel_sched_event(&hc->dch, D_CLEARBUSY);
#endif
ret = 0;
spin_unlock_irqrestore(&hc->lock, flags);
} else
ret = l1_event(dch->l1, hh->prim);
break;
}
if (!ret)
dev_kfree_skb(skb);
return ret;
}
static void
deactivate_bchannel(struct bchannel *bch)
{
struct hfc_multi *hc = bch->hw;
u_long flags;
spin_lock_irqsave(&hc->lock, flags);
mISDN_clear_bchannel(bch);
hc->chan[bch->slot].coeff_count = 0;
hc->chan[bch->slot].rx_off = 0;
hc->chan[bch->slot].conf = -1;
mode_hfcmulti(hc, bch->slot, ISDN_P_NONE, -1, 0, -1, 0);
spin_unlock_irqrestore(&hc->lock, flags);
}
static int
handle_bmsg(struct mISDNchannel *ch, struct sk_buff *skb)
{
struct bchannel *bch = container_of(ch, struct bchannel, ch);
struct hfc_multi *hc = bch->hw;
int ret = -EINVAL;
struct mISDNhead *hh = mISDN_HEAD_P(skb);
unsigned int id;
u_long flags;
switch (hh->prim) {
case PH_DATA_REQ:
if (!skb->len)
break;
spin_lock_irqsave(&hc->lock, flags);
ret = bchannel_senddata(bch, skb);
if (ret > 0) { /* direct TX */
id = hh->id; /* skb can be freed */
hfcmulti_tx(hc, bch->slot);
ret = 0;
/* start fifo */
HFC_outb_nodebug(hc, R_FIFO, 0);
HFC_wait_nodebug(hc);
if (!test_bit(FLG_TRANSPARENT, &bch->Flags)) {
spin_unlock_irqrestore(&hc->lock, flags);
queue_ch_frame(ch, PH_DATA_CNF, id, NULL);
} else
spin_unlock_irqrestore(&hc->lock, flags);
} else
spin_unlock_irqrestore(&hc->lock, flags);
return ret;
case PH_ACTIVATE_REQ:
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG "%s: PH_ACTIVATE ch %d (0..32)\n",
__func__, bch->slot);
spin_lock_irqsave(&hc->lock, flags);
/* activate B-channel if not already activated */
if (!test_and_set_bit(FLG_ACTIVE, &bch->Flags)) {
hc->chan[bch->slot].txpending = 0;
ret = mode_hfcmulti(hc, bch->slot,
ch->protocol,
hc->chan[bch->slot].slot_tx,
hc->chan[bch->slot].bank_tx,
hc->chan[bch->slot].slot_rx,
hc->chan[bch->slot].bank_rx);
if (!ret) {
if (ch->protocol == ISDN_P_B_RAW && !hc->dtmf
&& test_bit(HFC_CHIP_DTMF, &hc->chip)) {
/* start decoder */
hc->dtmf = 1;
if (debug & DEBUG_HFCMULTI_DTMF)
printk(KERN_DEBUG
"%s: start dtmf decoder\n",
__func__);
HFC_outb(hc, R_DTMF, hc->hw.r_dtmf |
V_RST_DTMF);
}
}
} else
ret = 0;
spin_unlock_irqrestore(&hc->lock, flags);
if (!ret)
_queue_data(ch, PH_ACTIVATE_IND, MISDN_ID_ANY, 0, NULL,
GFP_KERNEL);
break;
case PH_CONTROL_REQ:
spin_lock_irqsave(&hc->lock, flags);
switch (hh->id) {
case HFC_SPL_LOOP_ON: /* set sample loop */
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG
"%s: HFC_SPL_LOOP_ON (len = %d)\n",
__func__, skb->len);
ret = 0;
break;
case HFC_SPL_LOOP_OFF: /* set silence */
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG "%s: HFC_SPL_LOOP_OFF\n",
__func__);
ret = 0;
break;
default:
printk(KERN_ERR
"%s: unknown PH_CONTROL_REQ info %x\n",
__func__, hh->id);
ret = -EINVAL;
}
spin_unlock_irqrestore(&hc->lock, flags);
break;
case PH_DEACTIVATE_REQ:
deactivate_bchannel(bch); /* locked there */
_queue_data(ch, PH_DEACTIVATE_IND, MISDN_ID_ANY, 0, NULL,
GFP_KERNEL);
ret = 0;
break;
}
if (!ret)
dev_kfree_skb(skb);
return ret;
}
/*
* bchannel control function
*/
static int
channel_bctrl(struct bchannel *bch, struct mISDN_ctrl_req *cq)
{
int ret = 0;
struct dsp_features *features =
(struct dsp_features *)(*((u_long *)&cq->p1));
struct hfc_multi *hc = bch->hw;
int slot_tx;
int bank_tx;
int slot_rx;
int bank_rx;
int num;
switch (cq->op) {
case MISDN_CTRL_GETOP:
cq->op = MISDN_CTRL_HFC_OP | MISDN_CTRL_HW_FEATURES_OP
| MISDN_CTRL_RX_OFF | MISDN_CTRL_FILL_EMPTY;
break;
case MISDN_CTRL_RX_OFF: /* turn off / on rx stream */
hc->chan[bch->slot].rx_off = !!cq->p1;
if (!hc->chan[bch->slot].rx_off) {
/* reset fifo on rx on */
HFC_outb_nodebug(hc, R_FIFO, (bch->slot << 1) | 1);
HFC_wait_nodebug(hc);
HFC_outb_nodebug(hc, R_INC_RES_FIFO, V_RES_F);
HFC_wait_nodebug(hc);
}
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG "%s: RX_OFF request (nr=%d off=%d)\n",
__func__, bch->nr, hc->chan[bch->slot].rx_off);
break;
case MISDN_CTRL_FILL_EMPTY: /* fill fifo, if empty */
test_and_set_bit(FLG_FILLEMPTY, &bch->Flags);
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG "%s: FILL_EMPTY request (nr=%d "
"off=%d)\n", __func__, bch->nr, !!cq->p1);
break;
case MISDN_CTRL_HW_FEATURES: /* fill features structure */
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG "%s: HW_FEATURE request\n",
__func__);
/* create confirm */
features->hfc_id = hc->id;
if (test_bit(HFC_CHIP_DTMF, &hc->chip))
features->hfc_dtmf = 1;
if (test_bit(HFC_CHIP_CONF, &hc->chip))
features->hfc_conf = 1;
features->hfc_loops = 0;
if (test_bit(HFC_CHIP_B410P, &hc->chip)) {
features->hfc_echocanhw = 1;
} else {
features->pcm_id = hc->pcm;
features->pcm_slots = hc->slots;
features->pcm_banks = 2;
}
break;
case MISDN_CTRL_HFC_PCM_CONN: /* connect to pcm timeslot (0..N) */
slot_tx = cq->p1 & 0xff;
bank_tx = cq->p1 >> 8;
slot_rx = cq->p2 & 0xff;
bank_rx = cq->p2 >> 8;
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG
"%s: HFC_PCM_CONN slot %d bank %d (TX) "
"slot %d bank %d (RX)\n",
__func__, slot_tx, bank_tx,
slot_rx, bank_rx);
if (slot_tx < hc->slots && bank_tx <= 2 &&
slot_rx < hc->slots && bank_rx <= 2)
hfcmulti_pcm(hc, bch->slot,
slot_tx, bank_tx, slot_rx, bank_rx);
else {
printk(KERN_WARNING
"%s: HFC_PCM_CONN slot %d bank %d (TX) "
"slot %d bank %d (RX) out of range\n",
__func__, slot_tx, bank_tx,
slot_rx, bank_rx);
ret = -EINVAL;
}
break;
case MISDN_CTRL_HFC_PCM_DISC: /* release interface from pcm timeslot */
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG "%s: HFC_PCM_DISC\n",
__func__);
hfcmulti_pcm(hc, bch->slot, -1, 0, -1, 0);
break;
case MISDN_CTRL_HFC_CONF_JOIN: /* join conference (0..7) */
num = cq->p1 & 0xff;
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG "%s: HFC_CONF_JOIN conf %d\n",
__func__, num);
if (num <= 7)
hfcmulti_conf(hc, bch->slot, num);
else {
printk(KERN_WARNING
"%s: HW_CONF_JOIN conf %d out of range\n",
__func__, num);
ret = -EINVAL;
}
break;
case MISDN_CTRL_HFC_CONF_SPLIT: /* split conference */
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG "%s: HFC_CONF_SPLIT\n", __func__);
hfcmulti_conf(hc, bch->slot, -1);
break;
case MISDN_CTRL_HFC_ECHOCAN_ON:
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG "%s: HFC_ECHOCAN_ON\n", __func__);
if (test_bit(HFC_CHIP_B410P, &hc->chip))
vpm_echocan_on(hc, bch->slot, cq->p1);
else
ret = -EINVAL;
break;
case MISDN_CTRL_HFC_ECHOCAN_OFF:
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG "%s: HFC_ECHOCAN_OFF\n",
__func__);
if (test_bit(HFC_CHIP_B410P, &hc->chip))
vpm_echocan_off(hc, bch->slot);
else
ret = -EINVAL;
break;
default:
printk(KERN_WARNING "%s: unknown Op %x\n",
__func__, cq->op);
ret = -EINVAL;
break;
}
return ret;
}
static int
hfcm_bctrl(struct mISDNchannel *ch, u_int cmd, void *arg)
{
struct bchannel *bch = container_of(ch, struct bchannel, ch);
struct hfc_multi *hc = bch->hw;
int err = -EINVAL;
u_long flags;
if (bch->debug & DEBUG_HW)
printk(KERN_DEBUG "%s: cmd:%x %p\n",
__func__, cmd, arg);
switch (cmd) {
case CLOSE_CHANNEL:
test_and_clear_bit(FLG_OPEN, &bch->Flags);
if (test_bit(FLG_ACTIVE, &bch->Flags))
deactivate_bchannel(bch); /* locked there */
ch->protocol = ISDN_P_NONE;
ch->peer = NULL;
module_put(THIS_MODULE);
err = 0;
break;
case CONTROL_CHANNEL:
spin_lock_irqsave(&hc->lock, flags);
err = channel_bctrl(bch, arg);
spin_unlock_irqrestore(&hc->lock, flags);
break;
default:
printk(KERN_WARNING "%s: unknown prim(%x)\n",
__func__, cmd);
}
return err;
}
/*
* handle D-channel events
*
* handle state change event
*/
static void
ph_state_change(struct dchannel *dch)
{
struct hfc_multi *hc;
int ch, i;
if (!dch) {
printk(KERN_WARNING "%s: ERROR given dch is NULL\n", __func__);
return;
}
hc = dch->hw;
ch = dch->slot;
if (hc->ctype == HFC_TYPE_E1) {
if (dch->dev.D.protocol == ISDN_P_TE_E1) {
if (debug & DEBUG_HFCMULTI_STATE)
printk(KERN_DEBUG
"%s: E1 TE (id=%d) newstate %x\n",
__func__, hc->id, dch->state);
} else {
if (debug & DEBUG_HFCMULTI_STATE)
printk(KERN_DEBUG
"%s: E1 NT (id=%d) newstate %x\n",
__func__, hc->id, dch->state);
}
switch (dch->state) {
case (1):
if (hc->e1_state != 1) {
for (i = 1; i <= 31; i++) {
/* reset fifos on e1 activation */
HFC_outb_nodebug(hc, R_FIFO,
(i << 1) | 1);
HFC_wait_nodebug(hc);
HFC_outb_nodebug(hc, R_INC_RES_FIFO,
V_RES_F);
HFC_wait_nodebug(hc);
}
}
test_and_set_bit(FLG_ACTIVE, &dch->Flags);
_queue_data(&dch->dev.D, PH_ACTIVATE_IND,
MISDN_ID_ANY, 0, NULL, GFP_ATOMIC);
break;
default:
if (hc->e1_state != 1)
return;
test_and_clear_bit(FLG_ACTIVE, &dch->Flags);
_queue_data(&dch->dev.D, PH_DEACTIVATE_IND,
MISDN_ID_ANY, 0, NULL, GFP_ATOMIC);
}
hc->e1_state = dch->state;
} else {
if (dch->dev.D.protocol == ISDN_P_TE_S0) {
if (debug & DEBUG_HFCMULTI_STATE)
printk(KERN_DEBUG
"%s: S/T TE newstate %x\n",
__func__, dch->state);
switch (dch->state) {
case (0):
l1_event(dch->l1, HW_RESET_IND);
break;
case (3):
l1_event(dch->l1, HW_DEACT_IND);
break;
case (5):
case (8):
l1_event(dch->l1, ANYSIGNAL);
break;
case (6):
l1_event(dch->l1, INFO2);
break;
case (7):
l1_event(dch->l1, INFO4_P8);
break;
}
} else {
if (debug & DEBUG_HFCMULTI_STATE)
printk(KERN_DEBUG "%s: S/T NT newstate %x\n",
__func__, dch->state);
switch (dch->state) {
case (2):
if (hc->chan[ch].nt_timer == 0) {
hc->chan[ch].nt_timer = -1;
HFC_outb(hc, R_ST_SEL,
hc->chan[ch].port);
/* undocumented: delay after R_ST_SEL */
udelay(1);
HFC_outb(hc, A_ST_WR_STATE, 4 |
V_ST_LD_STA); /* G4 */
udelay(6); /* wait at least 5,21us */
HFC_outb(hc, A_ST_WR_STATE, 4);
dch->state = 4;
} else {
/* one extra count for the next event */
hc->chan[ch].nt_timer =
nt_t1_count[poll_timer] + 1;
HFC_outb(hc, R_ST_SEL,
hc->chan[ch].port);
/* undocumented: delay after R_ST_SEL */
udelay(1);
/* allow G2 -> G3 transition */
HFC_outb(hc, A_ST_WR_STATE, 2 |
V_SET_G2_G3);
}
break;
case (1):
hc->chan[ch].nt_timer = -1;
test_and_clear_bit(FLG_ACTIVE, &dch->Flags);
_queue_data(&dch->dev.D, PH_DEACTIVATE_IND,
MISDN_ID_ANY, 0, NULL, GFP_ATOMIC);
break;
case (4):
hc->chan[ch].nt_timer = -1;
break;
case (3):
hc->chan[ch].nt_timer = -1;
test_and_set_bit(FLG_ACTIVE, &dch->Flags);
_queue_data(&dch->dev.D, PH_ACTIVATE_IND,
MISDN_ID_ANY, 0, NULL, GFP_ATOMIC);
break;
}
}
}
}
/*
* called for card mode init message
*/
static void
hfcmulti_initmode(struct dchannel *dch)
{
struct hfc_multi *hc = dch->hw;
u_char a_st_wr_state, r_e1_wr_sta;
int i, pt;
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: entered\n", __func__);
if (hc->ctype == HFC_TYPE_E1) {
hc->chan[hc->dslot].slot_tx = -1;
hc->chan[hc->dslot].slot_rx = -1;
hc->chan[hc->dslot].conf = -1;
if (hc->dslot) {
mode_hfcmulti(hc, hc->dslot, dch->dev.D.protocol,
-1, 0, -1, 0);
dch->timer.function = (void *) hfcmulti_dbusy_timer;
dch->timer.data = (long) dch;
init_timer(&dch->timer);
}
for (i = 1; i <= 31; i++) {
if (i == hc->dslot)
continue;
hc->chan[i].slot_tx = -1;
hc->chan[i].slot_rx = -1;
hc->chan[i].conf = -1;
mode_hfcmulti(hc, i, ISDN_P_NONE, -1, 0, -1, 0);
}
/* E1 */
if (test_bit(HFC_CFG_REPORT_LOS, &hc->chan[hc->dslot].cfg)) {
HFC_outb(hc, R_LOS0, 255); /* 2 ms */
HFC_outb(hc, R_LOS1, 255); /* 512 ms */
}
if (test_bit(HFC_CFG_OPTICAL, &hc->chan[hc->dslot].cfg)) {
HFC_outb(hc, R_RX0, 0);
hc->hw.r_tx0 = 0 | V_OUT_EN;
} else {
HFC_outb(hc, R_RX0, 1);
hc->hw.r_tx0 = 1 | V_OUT_EN;
}
hc->hw.r_tx1 = V_ATX | V_NTRI;
HFC_outb(hc, R_TX0, hc->hw.r_tx0);
HFC_outb(hc, R_TX1, hc->hw.r_tx1);
HFC_outb(hc, R_TX_FR0, 0x00);
HFC_outb(hc, R_TX_FR1, 0xf8);
if (test_bit(HFC_CFG_CRC4, &hc->chan[hc->dslot].cfg))
HFC_outb(hc, R_TX_FR2, V_TX_MF | V_TX_E | V_NEG_E);
HFC_outb(hc, R_RX_FR0, V_AUTO_RESYNC | V_AUTO_RECO | 0);
if (test_bit(HFC_CFG_CRC4, &hc->chan[hc->dslot].cfg))
HFC_outb(hc, R_RX_FR1, V_RX_MF | V_RX_MF_SYNC);
if (dch->dev.D.protocol == ISDN_P_NT_E1) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: E1 port is NT-mode\n",
__func__);
r_e1_wr_sta = 0; /* G0 */
hc->e1_getclock = 0;
} else {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: E1 port is TE-mode\n",
__func__);
r_e1_wr_sta = 0; /* F0 */
hc->e1_getclock = 1;
}
if (test_bit(HFC_CHIP_RX_SYNC, &hc->chip))
HFC_outb(hc, R_SYNC_OUT, V_SYNC_E1_RX);
else
HFC_outb(hc, R_SYNC_OUT, 0);
if (test_bit(HFC_CHIP_E1CLOCK_GET, &hc->chip))
hc->e1_getclock = 1;
if (test_bit(HFC_CHIP_E1CLOCK_PUT, &hc->chip))
hc->e1_getclock = 0;
if (test_bit(HFC_CHIP_PCM_SLAVE, &hc->chip)) {
/* SLAVE (clock master) */
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: E1 port is clock master "
"(clock from PCM)\n", __func__);
HFC_outb(hc, R_SYNC_CTRL, V_EXT_CLK_SYNC | V_PCM_SYNC);
} else {
if (hc->e1_getclock) {
/* MASTER (clock slave) */
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: E1 port is clock slave "
"(clock to PCM)\n", __func__);
HFC_outb(hc, R_SYNC_CTRL, V_SYNC_OFFS);
} else {
/* MASTER (clock master) */
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: E1 port is "
"clock master "
"(clock from QUARTZ)\n",
__func__);
HFC_outb(hc, R_SYNC_CTRL, V_EXT_CLK_SYNC |
V_PCM_SYNC | V_JATT_OFF);
HFC_outb(hc, R_SYNC_OUT, 0);
}
}
HFC_outb(hc, R_JATT_ATT, 0x9c); /* undoc register */
HFC_outb(hc, R_PWM_MD, V_PWM0_MD);
HFC_outb(hc, R_PWM0, 0x50);
HFC_outb(hc, R_PWM1, 0xff);
/* state machine setup */
HFC_outb(hc, R_E1_WR_STA, r_e1_wr_sta | V_E1_LD_STA);
udelay(6); /* wait at least 5,21us */
HFC_outb(hc, R_E1_WR_STA, r_e1_wr_sta);
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
hc->syncronized = 0;
plxsd_checksync(hc, 0);
}
} else {
i = dch->slot;
hc->chan[i].slot_tx = -1;
hc->chan[i].slot_rx = -1;
hc->chan[i].conf = -1;
mode_hfcmulti(hc, i, dch->dev.D.protocol, -1, 0, -1, 0);
dch->timer.function = (void *)hfcmulti_dbusy_timer;
dch->timer.data = (long) dch;
init_timer(&dch->timer);
hc->chan[i - 2].slot_tx = -1;
hc->chan[i - 2].slot_rx = -1;
hc->chan[i - 2].conf = -1;
mode_hfcmulti(hc, i - 2, ISDN_P_NONE, -1, 0, -1, 0);
hc->chan[i - 1].slot_tx = -1;
hc->chan[i - 1].slot_rx = -1;
hc->chan[i - 1].conf = -1;
mode_hfcmulti(hc, i - 1, ISDN_P_NONE, -1, 0, -1, 0);
/* ST */
pt = hc->chan[i].port;
/* select interface */
HFC_outb(hc, R_ST_SEL, pt);
/* undocumented: delay after R_ST_SEL */
udelay(1);
if (dch->dev.D.protocol == ISDN_P_NT_S0) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: ST port %d is NT-mode\n",
__func__, pt);
/* clock delay */
HFC_outb(hc, A_ST_CLK_DLY, clockdelay_nt);
a_st_wr_state = 1; /* G1 */
hc->hw.a_st_ctrl0[pt] = V_ST_MD;
} else {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: ST port %d is TE-mode\n",
__func__, pt);
/* clock delay */
HFC_outb(hc, A_ST_CLK_DLY, clockdelay_te);
a_st_wr_state = 2; /* F2 */
hc->hw.a_st_ctrl0[pt] = 0;
}
if (!test_bit(HFC_CFG_NONCAP_TX, &hc->chan[i].cfg))
hc->hw.a_st_ctrl0[pt] |= V_TX_LI;
if (hc->ctype == HFC_TYPE_XHFC) {
hc->hw.a_st_ctrl0[pt] |= 0x40 /* V_ST_PU_CTRL */;
HFC_outb(hc, 0x35 /* A_ST_CTRL3 */,
0x7c << 1 /* V_ST_PULSE */);
}
/* line setup */
HFC_outb(hc, A_ST_CTRL0, hc->hw.a_st_ctrl0[pt]);
/* disable E-channel */
if ((dch->dev.D.protocol == ISDN_P_NT_S0) ||
test_bit(HFC_CFG_DIS_ECHANNEL, &hc->chan[i].cfg))
HFC_outb(hc, A_ST_CTRL1, V_E_IGNO);
else
HFC_outb(hc, A_ST_CTRL1, 0);
/* enable B-channel receive */
HFC_outb(hc, A_ST_CTRL2, V_B1_RX_EN | V_B2_RX_EN);
/* state machine setup */
HFC_outb(hc, A_ST_WR_STATE, a_st_wr_state | V_ST_LD_STA);
udelay(6); /* wait at least 5,21us */
HFC_outb(hc, A_ST_WR_STATE, a_st_wr_state);
hc->hw.r_sci_msk |= 1 << pt;
/* state machine interrupts */
HFC_outb(hc, R_SCI_MSK, hc->hw.r_sci_msk);
/* unset sync on port */
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
hc->syncronized &=
~(1 << hc->chan[dch->slot].port);
plxsd_checksync(hc, 0);
}
}
if (debug & DEBUG_HFCMULTI_INIT)
printk("%s: done\n", __func__);
}
static int
open_dchannel(struct hfc_multi *hc, struct dchannel *dch,
struct channel_req *rq)
{
int err = 0;
u_long flags;
if (debug & DEBUG_HW_OPEN)
printk(KERN_DEBUG "%s: dev(%d) open from %p\n", __func__,
dch->dev.id, __builtin_return_address(0));
if (rq->protocol == ISDN_P_NONE)
return -EINVAL;
if ((dch->dev.D.protocol != ISDN_P_NONE) &&
(dch->dev.D.protocol != rq->protocol)) {
if (debug & DEBUG_HFCMULTI_MODE)
printk(KERN_DEBUG "%s: change protocol %x to %x\n",
__func__, dch->dev.D.protocol, rq->protocol);
}
if ((dch->dev.D.protocol == ISDN_P_TE_S0) &&
(rq->protocol != ISDN_P_TE_S0))
l1_event(dch->l1, CLOSE_CHANNEL);
if (dch->dev.D.protocol != rq->protocol) {
if (rq->protocol == ISDN_P_TE_S0) {
err = create_l1(dch, hfcm_l1callback);
if (err)
return err;
}
dch->dev.D.protocol = rq->protocol;
spin_lock_irqsave(&hc->lock, flags);
hfcmulti_initmode(dch);
spin_unlock_irqrestore(&hc->lock, flags);
}
if (((rq->protocol == ISDN_P_NT_S0) && (dch->state == 3)) ||
((rq->protocol == ISDN_P_TE_S0) && (dch->state == 7)) ||
((rq->protocol == ISDN_P_NT_E1) && (dch->state == 1)) ||
((rq->protocol == ISDN_P_TE_E1) && (dch->state == 1))) {
_queue_data(&dch->dev.D, PH_ACTIVATE_IND, MISDN_ID_ANY,
0, NULL, GFP_KERNEL);
}
rq->ch = &dch->dev.D;
if (!try_module_get(THIS_MODULE))
printk(KERN_WARNING "%s:cannot get module\n", __func__);
return 0;
}
static int
open_bchannel(struct hfc_multi *hc, struct dchannel *dch,
struct channel_req *rq)
{
struct bchannel *bch;
int ch;
if (!test_channelmap(rq->adr.channel, dch->dev.channelmap))
return -EINVAL;
if (rq->protocol == ISDN_P_NONE)
return -EINVAL;
if (hc->ctype == HFC_TYPE_E1)
ch = rq->adr.channel;
else
ch = (rq->adr.channel - 1) + (dch->slot - 2);
bch = hc->chan[ch].bch;
if (!bch) {
printk(KERN_ERR "%s:internal error ch %d has no bch\n",
__func__, ch);
return -EINVAL;
}
if (test_and_set_bit(FLG_OPEN, &bch->Flags))
return -EBUSY; /* b-channel can be only open once */
test_and_clear_bit(FLG_FILLEMPTY, &bch->Flags);
bch->ch.protocol = rq->protocol;
hc->chan[ch].rx_off = 0;
rq->ch = &bch->ch;
if (!try_module_get(THIS_MODULE))
printk(KERN_WARNING "%s:cannot get module\n", __func__);
return 0;
}
/*
* device control function
*/
static int
channel_dctrl(struct dchannel *dch, struct mISDN_ctrl_req *cq)
{
struct hfc_multi *hc = dch->hw;
int ret = 0;
int wd_mode, wd_cnt;
switch (cq->op) {
case MISDN_CTRL_GETOP:
cq->op = MISDN_CTRL_HFC_OP;
break;
case MISDN_CTRL_HFC_WD_INIT: /* init the watchdog */
wd_cnt = cq->p1 & 0xf;
wd_mode = !!(cq->p1 >> 4);
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG "%s: MISDN_CTRL_HFC_WD_INIT mode %s"
", counter 0x%x\n", __func__,
wd_mode ? "AUTO" : "MANUAL", wd_cnt);
/* set the watchdog timer */
HFC_outb(hc, R_TI_WD, poll_timer | (wd_cnt << 4));
hc->hw.r_bert_wd_md = (wd_mode ? V_AUTO_WD_RES : 0);
if (hc->ctype == HFC_TYPE_XHFC)
hc->hw.r_bert_wd_md |= 0x40 /* V_WD_EN */;
/* init the watchdog register and reset the counter */
HFC_outb(hc, R_BERT_WD_MD, hc->hw.r_bert_wd_md | V_WD_RES);
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
/* enable the watchdog output for Speech-Design */
HFC_outb(hc, R_GPIO_SEL, V_GPIO_SEL7);
HFC_outb(hc, R_GPIO_EN1, V_GPIO_EN15);
HFC_outb(hc, R_GPIO_OUT1, 0);
HFC_outb(hc, R_GPIO_OUT1, V_GPIO_OUT15);
}
break;
case MISDN_CTRL_HFC_WD_RESET: /* reset the watchdog counter */
if (debug & DEBUG_HFCMULTI_MSG)
printk(KERN_DEBUG "%s: MISDN_CTRL_HFC_WD_RESET\n",
__func__);
HFC_outb(hc, R_BERT_WD_MD, hc->hw.r_bert_wd_md | V_WD_RES);
break;
default:
printk(KERN_WARNING "%s: unknown Op %x\n",
__func__, cq->op);
ret = -EINVAL;
break;
}
return ret;
}
static int
hfcm_dctrl(struct mISDNchannel *ch, u_int cmd, void *arg)
{
struct mISDNdevice *dev = container_of(ch, struct mISDNdevice, D);
struct dchannel *dch = container_of(dev, struct dchannel, dev);
struct hfc_multi *hc = dch->hw;
struct channel_req *rq;
int err = 0;
u_long flags;
if (dch->debug & DEBUG_HW)
printk(KERN_DEBUG "%s: cmd:%x %p\n",
__func__, cmd, arg);
switch (cmd) {
case OPEN_CHANNEL:
rq = arg;
switch (rq->protocol) {
case ISDN_P_TE_S0:
case ISDN_P_NT_S0:
if (hc->ctype == HFC_TYPE_E1) {
err = -EINVAL;
break;
}
err = open_dchannel(hc, dch, rq); /* locked there */
break;
case ISDN_P_TE_E1:
case ISDN_P_NT_E1:
if (hc->ctype != HFC_TYPE_E1) {
err = -EINVAL;
break;
}
err = open_dchannel(hc, dch, rq); /* locked there */
break;
default:
spin_lock_irqsave(&hc->lock, flags);
err = open_bchannel(hc, dch, rq);
spin_unlock_irqrestore(&hc->lock, flags);
}
break;
case CLOSE_CHANNEL:
if (debug & DEBUG_HW_OPEN)
printk(KERN_DEBUG "%s: dev(%d) close from %p\n",
__func__, dch->dev.id,
__builtin_return_address(0));
module_put(THIS_MODULE);
break;
case CONTROL_CHANNEL:
spin_lock_irqsave(&hc->lock, flags);
err = channel_dctrl(dch, arg);
spin_unlock_irqrestore(&hc->lock, flags);
break;
default:
if (dch->debug & DEBUG_HW)
printk(KERN_DEBUG "%s: unknown command %x\n",
__func__, cmd);
err = -EINVAL;
}
return err;
}
static int
clockctl(void *priv, int enable)
{
struct hfc_multi *hc = priv;
hc->iclock_on = enable;
return 0;
}
/*
* initialize the card
*/
/*
* start timer irq, wait some time and check if we have interrupts.
* if not, reset chip and try again.
*/
static int
init_card(struct hfc_multi *hc)
{
int err = -EIO;
u_long flags;
void __iomem *plx_acc;
u_long plx_flags;
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: entered\n", __func__);
spin_lock_irqsave(&hc->lock, flags);
/* set interrupts but leave global interrupt disabled */
hc->hw.r_irq_ctrl = V_FIFO_IRQ;
disable_hwirq(hc);
spin_unlock_irqrestore(&hc->lock, flags);
if (request_irq(hc->irq, hfcmulti_interrupt, IRQF_SHARED,
"HFC-multi", hc)) {
printk(KERN_WARNING "mISDN: Could not get interrupt %d.\n",
hc->irq);
hc->irq = 0;
return -EIO;
}
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
spin_lock_irqsave(&plx_lock, plx_flags);
plx_acc = hc->plx_membase + PLX_INTCSR;
writew((PLX_INTCSR_PCIINT_ENABLE | PLX_INTCSR_LINTI1_ENABLE),
plx_acc); /* enable PCI & LINT1 irq */
spin_unlock_irqrestore(&plx_lock, plx_flags);
}
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: IRQ %d count %d\n",
__func__, hc->irq, hc->irqcnt);
err = init_chip(hc);
if (err)
goto error;
/*
* Finally enable IRQ output
* this is only allowed, if an IRQ routine is already
* established for this HFC, so don't do that earlier
*/
spin_lock_irqsave(&hc->lock, flags);
enable_hwirq(hc);
spin_unlock_irqrestore(&hc->lock, flags);
/* printk(KERN_DEBUG "no master irq set!!!\n"); */
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout((100 * HZ) / 1000); /* Timeout 100ms */
/* turn IRQ off until chip is completely initialized */
spin_lock_irqsave(&hc->lock, flags);
disable_hwirq(hc);
spin_unlock_irqrestore(&hc->lock, flags);
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: IRQ %d count %d\n",
__func__, hc->irq, hc->irqcnt);
if (hc->irqcnt) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: done\n", __func__);
return 0;
}
if (test_bit(HFC_CHIP_PCM_SLAVE, &hc->chip)) {
printk(KERN_INFO "ignoring missing interrupts\n");
return 0;
}
printk(KERN_ERR "HFC PCI: IRQ(%d) getting no interrupts during init.\n",
hc->irq);
err = -EIO;
error:
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
spin_lock_irqsave(&plx_lock, plx_flags);
plx_acc = hc->plx_membase + PLX_INTCSR;
writew(0x00, plx_acc); /*disable IRQs*/
spin_unlock_irqrestore(&plx_lock, plx_flags);
}
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: free irq %d\n", __func__, hc->irq);
if (hc->irq) {
free_irq(hc->irq, hc);
hc->irq = 0;
}
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: done (err=%d)\n", __func__, err);
return err;
}
/*
* find pci device and set it up
*/
static int
setup_pci(struct hfc_multi *hc, struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct hm_map *m = (struct hm_map *)ent->driver_data;
printk(KERN_INFO
"HFC-multi: card manufacturer: '%s' card name: '%s' clock: %s\n",
m->vendor_name, m->card_name, m->clock2 ? "double" : "normal");
hc->pci_dev = pdev;
if (m->clock2)
test_and_set_bit(HFC_CHIP_CLOCK2, &hc->chip);
if (ent->device == 0xB410) {
test_and_set_bit(HFC_CHIP_B410P, &hc->chip);
test_and_set_bit(HFC_CHIP_PCM_MASTER, &hc->chip);
test_and_clear_bit(HFC_CHIP_PCM_SLAVE, &hc->chip);
hc->slots = 32;
}
if (hc->pci_dev->irq <= 0) {
printk(KERN_WARNING "HFC-multi: No IRQ for PCI card found.\n");
return -EIO;
}
if (pci_enable_device(hc->pci_dev)) {
printk(KERN_WARNING "HFC-multi: Error enabling PCI card.\n");
return -EIO;
}
hc->leds = m->leds;
hc->ledstate = 0xAFFEAFFE;
hc->opticalsupport = m->opticalsupport;
hc->pci_iobase = 0;
hc->pci_membase = NULL;
hc->plx_membase = NULL;
/* set memory access methods */
if (m->io_mode) /* use mode from card config */
hc->io_mode = m->io_mode;
switch (hc->io_mode) {
case HFC_IO_MODE_PLXSD:
test_and_set_bit(HFC_CHIP_PLXSD, &hc->chip);
hc->slots = 128; /* required */
hc->HFC_outb = HFC_outb_pcimem;
hc->HFC_inb = HFC_inb_pcimem;
hc->HFC_inw = HFC_inw_pcimem;
hc->HFC_wait = HFC_wait_pcimem;
hc->read_fifo = read_fifo_pcimem;
hc->write_fifo = write_fifo_pcimem;
hc->plx_origmembase = hc->pci_dev->resource[0].start;
/* MEMBASE 1 is PLX PCI Bridge */
if (!hc->plx_origmembase) {
printk(KERN_WARNING
"HFC-multi: No IO-Memory for PCI PLX bridge found\n");
pci_disable_device(hc->pci_dev);
return -EIO;
}
hc->plx_membase = ioremap(hc->plx_origmembase, 0x80);
if (!hc->plx_membase) {
printk(KERN_WARNING
"HFC-multi: failed to remap plx address space. "
"(internal error)\n");
pci_disable_device(hc->pci_dev);
return -EIO;
}
printk(KERN_INFO
"HFC-multi: plx_membase:%#lx plx_origmembase:%#lx\n",
(u_long)hc->plx_membase, hc->plx_origmembase);
hc->pci_origmembase = hc->pci_dev->resource[2].start;
/* MEMBASE 1 is PLX PCI Bridge */
if (!hc->pci_origmembase) {
printk(KERN_WARNING
"HFC-multi: No IO-Memory for PCI card found\n");
pci_disable_device(hc->pci_dev);
return -EIO;
}
hc->pci_membase = ioremap(hc->pci_origmembase, 0x400);
if (!hc->pci_membase) {
printk(KERN_WARNING "HFC-multi: failed to remap io "
"address space. (internal error)\n");
pci_disable_device(hc->pci_dev);
return -EIO;
}
printk(KERN_INFO
"card %d: defined at MEMBASE %#lx (%#lx) IRQ %d HZ %d "
"leds-type %d\n",
hc->id, (u_long)hc->pci_membase, hc->pci_origmembase,
hc->pci_dev->irq, HZ, hc->leds);
pci_write_config_word(hc->pci_dev, PCI_COMMAND, PCI_ENA_MEMIO);
break;
case HFC_IO_MODE_PCIMEM:
hc->HFC_outb = HFC_outb_pcimem;
hc->HFC_inb = HFC_inb_pcimem;
hc->HFC_inw = HFC_inw_pcimem;
hc->HFC_wait = HFC_wait_pcimem;
hc->read_fifo = read_fifo_pcimem;
hc->write_fifo = write_fifo_pcimem;
hc->pci_origmembase = hc->pci_dev->resource[1].start;
if (!hc->pci_origmembase) {
printk(KERN_WARNING
"HFC-multi: No IO-Memory for PCI card found\n");
pci_disable_device(hc->pci_dev);
return -EIO;
}
hc->pci_membase = ioremap(hc->pci_origmembase, 256);
if (!hc->pci_membase) {
printk(KERN_WARNING
"HFC-multi: failed to remap io address space. "
"(internal error)\n");
pci_disable_device(hc->pci_dev);
return -EIO;
}
printk(KERN_INFO "card %d: defined at MEMBASE %#lx (%#lx) IRQ "
"%d HZ %d leds-type %d\n", hc->id, (u_long)hc->pci_membase,
hc->pci_origmembase, hc->pci_dev->irq, HZ, hc->leds);
pci_write_config_word(hc->pci_dev, PCI_COMMAND, PCI_ENA_MEMIO);
break;
case HFC_IO_MODE_REGIO:
hc->HFC_outb = HFC_outb_regio;
hc->HFC_inb = HFC_inb_regio;
hc->HFC_inw = HFC_inw_regio;
hc->HFC_wait = HFC_wait_regio;
hc->read_fifo = read_fifo_regio;
hc->write_fifo = write_fifo_regio;
hc->pci_iobase = (u_int) hc->pci_dev->resource[0].start;
if (!hc->pci_iobase) {
printk(KERN_WARNING
"HFC-multi: No IO for PCI card found\n");
pci_disable_device(hc->pci_dev);
return -EIO;
}
if (!request_region(hc->pci_iobase, 8, "hfcmulti")) {
printk(KERN_WARNING "HFC-multi: failed to request "
"address space at 0x%08lx (internal error)\n",
hc->pci_iobase);
pci_disable_device(hc->pci_dev);
return -EIO;
}
printk(KERN_INFO
"%s %s: defined at IOBASE %#x IRQ %d HZ %d leds-type %d\n",
m->vendor_name, m->card_name, (u_int) hc->pci_iobase,
hc->pci_dev->irq, HZ, hc->leds);
pci_write_config_word(hc->pci_dev, PCI_COMMAND, PCI_ENA_REGIO);
break;
default:
printk(KERN_WARNING "HFC-multi: Invalid IO mode.\n");
pci_disable_device(hc->pci_dev);
return -EIO;
}
pci_set_drvdata(hc->pci_dev, hc);
/* At this point the needed PCI config is done */
/* fifos are still not enabled */
return 0;
}
/*
* remove port
*/
static void
release_port(struct hfc_multi *hc, struct dchannel *dch)
{
int pt, ci, i = 0;
u_long flags;
struct bchannel *pb;
ci = dch->slot;
pt = hc->chan[ci].port;
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: entered for port %d\n",
__func__, pt + 1);
if (pt >= hc->ports) {
printk(KERN_WARNING "%s: ERROR port out of range (%d).\n",
__func__, pt + 1);
return;
}
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: releasing port=%d\n",
__func__, pt + 1);
if (dch->dev.D.protocol == ISDN_P_TE_S0)
l1_event(dch->l1, CLOSE_CHANNEL);
hc->chan[ci].dch = NULL;
if (hc->created[pt]) {
hc->created[pt] = 0;
mISDN_unregister_device(&dch->dev);
}
spin_lock_irqsave(&hc->lock, flags);
if (dch->timer.function) {
del_timer(&dch->timer);
dch->timer.function = NULL;
}
if (hc->ctype == HFC_TYPE_E1) { /* E1 */
/* remove sync */
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
hc->syncronized = 0;
plxsd_checksync(hc, 1);
}
/* free channels */
for (i = 0; i <= 31; i++) {
if (hc->chan[i].bch) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: free port %d channel %d\n",
__func__, hc->chan[i].port + 1, i);
pb = hc->chan[i].bch;
hc->chan[i].bch = NULL;
spin_unlock_irqrestore(&hc->lock, flags);
mISDN_freebchannel(pb);
kfree(pb);
kfree(hc->chan[i].coeff);
spin_lock_irqsave(&hc->lock, flags);
}
}
} else {
/* remove sync */
if (test_bit(HFC_CHIP_PLXSD, &hc->chip)) {
hc->syncronized &=
~(1 << hc->chan[ci].port);
plxsd_checksync(hc, 1);
}
/* free channels */
if (hc->chan[ci - 2].bch) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: free port %d channel %d\n",
__func__, hc->chan[ci - 2].port + 1,
ci - 2);
pb = hc->chan[ci - 2].bch;
hc->chan[ci - 2].bch = NULL;
spin_unlock_irqrestore(&hc->lock, flags);
mISDN_freebchannel(pb);
kfree(pb);
kfree(hc->chan[ci - 2].coeff);
spin_lock_irqsave(&hc->lock, flags);
}
if (hc->chan[ci - 1].bch) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: free port %d channel %d\n",
__func__, hc->chan[ci - 1].port + 1,
ci - 1);
pb = hc->chan[ci - 1].bch;
hc->chan[ci - 1].bch = NULL;
spin_unlock_irqrestore(&hc->lock, flags);
mISDN_freebchannel(pb);
kfree(pb);
kfree(hc->chan[ci - 1].coeff);
spin_lock_irqsave(&hc->lock, flags);
}
}
spin_unlock_irqrestore(&hc->lock, flags);
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: free port %d channel D\n", __func__, pt);
mISDN_freedchannel(dch);
kfree(dch);
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: done!\n", __func__);
}
static void
release_card(struct hfc_multi *hc)
{
u_long flags;
int ch;
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: release card (%d) entered\n",
__func__, hc->id);
/* unregister clock source */
if (hc->iclock)
mISDN_unregister_clock(hc->iclock);
/* disable irq */
spin_lock_irqsave(&hc->lock, flags);
disable_hwirq(hc);
spin_unlock_irqrestore(&hc->lock, flags);
udelay(1000);
/* dimm leds */
if (hc->leds)
hfcmulti_leds(hc);
/* disable D-channels & B-channels */
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: disable all channels (d and b)\n",
__func__);
for (ch = 0; ch <= 31; ch++) {
if (hc->chan[ch].dch)
release_port(hc, hc->chan[ch].dch);
}
/* release hardware & irq */
if (hc->irq) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: free irq %d\n",
__func__, hc->irq);
free_irq(hc->irq, hc);
hc->irq = 0;
}
release_io_hfcmulti(hc);
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: remove instance from list\n",
__func__);
list_del(&hc->list);
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: delete instance\n", __func__);
if (hc == syncmaster)
syncmaster = NULL;
kfree(hc);
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: card successfully removed\n",
__func__);
}
static int
init_e1_port(struct hfc_multi *hc, struct hm_map *m)
{
struct dchannel *dch;
struct bchannel *bch;
int ch, ret = 0;
char name[MISDN_MAX_IDLEN];
dch = kzalloc(sizeof(struct dchannel), GFP_KERNEL);
if (!dch)
return -ENOMEM;
dch->debug = debug;
mISDN_initdchannel(dch, MAX_DFRAME_LEN_L1, ph_state_change);
dch->hw = hc;
dch->dev.Dprotocols = (1 << ISDN_P_TE_E1) | (1 << ISDN_P_NT_E1);
dch->dev.Bprotocols = (1 << (ISDN_P_B_RAW & ISDN_P_B_MASK)) |
(1 << (ISDN_P_B_HDLC & ISDN_P_B_MASK));
dch->dev.D.send = handle_dmsg;
dch->dev.D.ctrl = hfcm_dctrl;
dch->dev.nrbchan = (hc->dslot) ? 30 : 31;
dch->slot = hc->dslot;
hc->chan[hc->dslot].dch = dch;
hc->chan[hc->dslot].port = 0;
hc->chan[hc->dslot].nt_timer = -1;
for (ch = 1; ch <= 31; ch++) {
if (ch == hc->dslot) /* skip dchannel */
continue;
bch = kzalloc(sizeof(struct bchannel), GFP_KERNEL);
if (!bch) {
printk(KERN_ERR "%s: no memory for bchannel\n",
__func__);
ret = -ENOMEM;
goto free_chan;
}
hc->chan[ch].coeff = kzalloc(512, GFP_KERNEL);
if (!hc->chan[ch].coeff) {
printk(KERN_ERR "%s: no memory for coeffs\n",
__func__);
ret = -ENOMEM;
kfree(bch);
goto free_chan;
}
bch->nr = ch;
bch->slot = ch;
bch->debug = debug;
mISDN_initbchannel(bch, MAX_DATA_MEM);
bch->hw = hc;
bch->ch.send = handle_bmsg;
bch->ch.ctrl = hfcm_bctrl;
bch->ch.nr = ch;
list_add(&bch->ch.list, &dch->dev.bchannels);
hc->chan[ch].bch = bch;
hc->chan[ch].port = 0;
set_channelmap(bch->nr, dch->dev.channelmap);
}
/* set optical line type */
if (port[Port_cnt] & 0x001) {
if (!m->opticalsupport) {
printk(KERN_INFO
"This board has no optical "
"support\n");
} else {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: PORT set optical "
"interfacs: card(%d) "
"port(%d)\n",
__func__,
HFC_cnt + 1, 1);
test_and_set_bit(HFC_CFG_OPTICAL,
&hc->chan[hc->dslot].cfg);
}
}
/* set LOS report */
if (port[Port_cnt] & 0x004) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: PORT set "
"LOS report: card(%d) port(%d)\n",
__func__, HFC_cnt + 1, 1);
test_and_set_bit(HFC_CFG_REPORT_LOS,
&hc->chan[hc->dslot].cfg);
}
/* set AIS report */
if (port[Port_cnt] & 0x008) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: PORT set "
"AIS report: card(%d) port(%d)\n",
__func__, HFC_cnt + 1, 1);
test_and_set_bit(HFC_CFG_REPORT_AIS,
&hc->chan[hc->dslot].cfg);
}
/* set SLIP report */
if (port[Port_cnt] & 0x010) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: PORT set SLIP report: "
"card(%d) port(%d)\n",
__func__, HFC_cnt + 1, 1);
test_and_set_bit(HFC_CFG_REPORT_SLIP,
&hc->chan[hc->dslot].cfg);
}
/* set RDI report */
if (port[Port_cnt] & 0x020) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: PORT set RDI report: "
"card(%d) port(%d)\n",
__func__, HFC_cnt + 1, 1);
test_and_set_bit(HFC_CFG_REPORT_RDI,
&hc->chan[hc->dslot].cfg);
}
/* set CRC-4 Mode */
if (!(port[Port_cnt] & 0x100)) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: PORT turn on CRC4 report:"
" card(%d) port(%d)\n",
__func__, HFC_cnt + 1, 1);
test_and_set_bit(HFC_CFG_CRC4,
&hc->chan[hc->dslot].cfg);
} else {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: PORT turn off CRC4"
" report: card(%d) port(%d)\n",
__func__, HFC_cnt + 1, 1);
}
/* set forced clock */
if (port[Port_cnt] & 0x0200) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: PORT force getting clock from "
"E1: card(%d) port(%d)\n",
__func__, HFC_cnt + 1, 1);
test_and_set_bit(HFC_CHIP_E1CLOCK_GET, &hc->chip);
} else
if (port[Port_cnt] & 0x0400) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: PORT force putting clock to "
"E1: card(%d) port(%d)\n",
__func__, HFC_cnt + 1, 1);
test_and_set_bit(HFC_CHIP_E1CLOCK_PUT, &hc->chip);
}
/* set JATT PLL */
if (port[Port_cnt] & 0x0800) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: PORT disable JATT PLL on "
"E1: card(%d) port(%d)\n",
__func__, HFC_cnt + 1, 1);
test_and_set_bit(HFC_CHIP_RX_SYNC, &hc->chip);
}
/* set elastic jitter buffer */
if (port[Port_cnt] & 0x3000) {
hc->chan[hc->dslot].jitter = (port[Port_cnt]>>12) & 0x3;
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: PORT set elastic "
"buffer to %d: card(%d) port(%d)\n",
__func__, hc->chan[hc->dslot].jitter,
HFC_cnt + 1, 1);
} else
hc->chan[hc->dslot].jitter = 2; /* default */
snprintf(name, MISDN_MAX_IDLEN - 1, "hfc-e1.%d", HFC_cnt + 1);
ret = mISDN_register_device(&dch->dev, &hc->pci_dev->dev, name);
if (ret)
goto free_chan;
hc->created[0] = 1;
return ret;
free_chan:
release_port(hc, dch);
return ret;
}
static int
init_multi_port(struct hfc_multi *hc, int pt)
{
struct dchannel *dch;
struct bchannel *bch;
int ch, i, ret = 0;
char name[MISDN_MAX_IDLEN];
dch = kzalloc(sizeof(struct dchannel), GFP_KERNEL);
if (!dch)
return -ENOMEM;
dch->debug = debug;
mISDN_initdchannel(dch, MAX_DFRAME_LEN_L1, ph_state_change);
dch->hw = hc;
dch->dev.Dprotocols = (1 << ISDN_P_TE_S0) | (1 << ISDN_P_NT_S0);
dch->dev.Bprotocols = (1 << (ISDN_P_B_RAW & ISDN_P_B_MASK)) |
(1 << (ISDN_P_B_HDLC & ISDN_P_B_MASK));
dch->dev.D.send = handle_dmsg;
dch->dev.D.ctrl = hfcm_dctrl;
dch->dev.nrbchan = 2;
i = pt << 2;
dch->slot = i + 2;
hc->chan[i + 2].dch = dch;
hc->chan[i + 2].port = pt;
hc->chan[i + 2].nt_timer = -1;
for (ch = 0; ch < dch->dev.nrbchan; ch++) {
bch = kzalloc(sizeof(struct bchannel), GFP_KERNEL);
if (!bch) {
printk(KERN_ERR "%s: no memory for bchannel\n",
__func__);
ret = -ENOMEM;
goto free_chan;
}
hc->chan[i + ch].coeff = kzalloc(512, GFP_KERNEL);
if (!hc->chan[i + ch].coeff) {
printk(KERN_ERR "%s: no memory for coeffs\n",
__func__);
ret = -ENOMEM;
kfree(bch);
goto free_chan;
}
bch->nr = ch + 1;
bch->slot = i + ch;
bch->debug = debug;
mISDN_initbchannel(bch, MAX_DATA_MEM);
bch->hw = hc;
bch->ch.send = handle_bmsg;
bch->ch.ctrl = hfcm_bctrl;
bch->ch.nr = ch + 1;
list_add(&bch->ch.list, &dch->dev.bchannels);
hc->chan[i + ch].bch = bch;
hc->chan[i + ch].port = pt;
set_channelmap(bch->nr, dch->dev.channelmap);
}
/* set master clock */
if (port[Port_cnt] & 0x001) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: PROTOCOL set master clock: "
"card(%d) port(%d)\n",
__func__, HFC_cnt + 1, pt + 1);
if (dch->dev.D.protocol != ISDN_P_TE_S0) {
printk(KERN_ERR "Error: Master clock "
"for port(%d) of card(%d) is only"
" possible with TE-mode\n",
pt + 1, HFC_cnt + 1);
ret = -EINVAL;
goto free_chan;
}
if (hc->masterclk >= 0) {
printk(KERN_ERR "Error: Master clock "
"for port(%d) of card(%d) already "
"defined for port(%d)\n",
pt + 1, HFC_cnt + 1, hc->masterclk + 1);
ret = -EINVAL;
goto free_chan;
}
hc->masterclk = pt;
}
/* set transmitter line to non capacitive */
if (port[Port_cnt] & 0x002) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: PROTOCOL set non capacitive "
"transmitter: card(%d) port(%d)\n",
__func__, HFC_cnt + 1, pt + 1);
test_and_set_bit(HFC_CFG_NONCAP_TX,
&hc->chan[i + 2].cfg);
}
/* disable E-channel */
if (port[Port_cnt] & 0x004) {
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: PROTOCOL disable E-channel: "
"card(%d) port(%d)\n",
__func__, HFC_cnt + 1, pt + 1);
test_and_set_bit(HFC_CFG_DIS_ECHANNEL,
&hc->chan[i + 2].cfg);
}
if (hc->ctype == HFC_TYPE_XHFC) {
snprintf(name, MISDN_MAX_IDLEN - 1, "xhfc.%d-%d",
HFC_cnt + 1, pt + 1);
ret = mISDN_register_device(&dch->dev, NULL, name);
} else {
snprintf(name, MISDN_MAX_IDLEN - 1, "hfc-%ds.%d-%d",
hc->ctype, HFC_cnt + 1, pt + 1);
ret = mISDN_register_device(&dch->dev, &hc->pci_dev->dev, name);
}
if (ret)
goto free_chan;
hc->created[pt] = 1;
return ret;
free_chan:
release_port(hc, dch);
return ret;
}
static int
hfcmulti_init(struct hm_map *m, struct pci_dev *pdev,
const struct pci_device_id *ent)
{
int ret_err = 0;
int pt;
struct hfc_multi *hc;
u_long flags;
u_char dips = 0, pmj = 0; /* dip settings, port mode Jumpers */
int i;
if (HFC_cnt >= MAX_CARDS) {
printk(KERN_ERR "too many cards (max=%d).\n",
MAX_CARDS);
return -EINVAL;
}
if ((type[HFC_cnt] & 0xff) && (type[HFC_cnt] & 0xff) != m->type) {
printk(KERN_WARNING "HFC-MULTI: Card '%s:%s' type %d found but "
"type[%d] %d was supplied as module parameter\n",
m->vendor_name, m->card_name, m->type, HFC_cnt,
type[HFC_cnt] & 0xff);
printk(KERN_WARNING "HFC-MULTI: Load module without parameters "
"first, to see cards and their types.");
return -EINVAL;
}
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: Registering %s:%s chip type %d (0x%x)\n",
__func__, m->vendor_name, m->card_name, m->type,
type[HFC_cnt]);
/* allocate card+fifo structure */
hc = kzalloc(sizeof(struct hfc_multi), GFP_KERNEL);
if (!hc) {
printk(KERN_ERR "No kmem for HFC-Multi card\n");
return -ENOMEM;
}
spin_lock_init(&hc->lock);
hc->mtyp = m;
hc->ctype = m->type;
hc->ports = m->ports;
hc->id = HFC_cnt;
hc->pcm = pcm[HFC_cnt];
hc->io_mode = iomode[HFC_cnt];
if (dslot[HFC_cnt] < 0 && hc->ctype == HFC_TYPE_E1) {
hc->dslot = 0;
printk(KERN_INFO "HFC-E1 card has disabled D-channel, but "
"31 B-channels\n");
}
if (dslot[HFC_cnt] > 0 && dslot[HFC_cnt] < 32
&& hc->ctype == HFC_TYPE_E1) {
hc->dslot = dslot[HFC_cnt];
printk(KERN_INFO "HFC-E1 card has alternating D-channel on "
"time slot %d\n", dslot[HFC_cnt]);
} else
hc->dslot = 16;
/* set chip specific features */
hc->masterclk = -1;
if (type[HFC_cnt] & 0x100) {
test_and_set_bit(HFC_CHIP_ULAW, &hc->chip);
hc->silence = 0xff; /* ulaw silence */
} else
hc->silence = 0x2a; /* alaw silence */
if ((poll >> 1) > sizeof(hc->silence_data)) {
printk(KERN_ERR "HFCMULTI error: silence_data too small, "
"please fix\n");
return -EINVAL;
}
for (i = 0; i < (poll >> 1); i++)
hc->silence_data[i] = hc->silence;
if (hc->ctype != HFC_TYPE_XHFC) {
if (!(type[HFC_cnt] & 0x200))
test_and_set_bit(HFC_CHIP_DTMF, &hc->chip);
test_and_set_bit(HFC_CHIP_CONF, &hc->chip);
}
if (type[HFC_cnt] & 0x800)
test_and_set_bit(HFC_CHIP_PCM_SLAVE, &hc->chip);
if (type[HFC_cnt] & 0x1000) {
test_and_set_bit(HFC_CHIP_PCM_MASTER, &hc->chip);
test_and_clear_bit(HFC_CHIP_PCM_SLAVE, &hc->chip);
}
if (type[HFC_cnt] & 0x4000)
test_and_set_bit(HFC_CHIP_EXRAM_128, &hc->chip);
if (type[HFC_cnt] & 0x8000)
test_and_set_bit(HFC_CHIP_EXRAM_512, &hc->chip);
hc->slots = 32;
if (type[HFC_cnt] & 0x10000)
hc->slots = 64;
if (type[HFC_cnt] & 0x20000)
hc->slots = 128;
if (type[HFC_cnt] & 0x80000) {
test_and_set_bit(HFC_CHIP_WATCHDOG, &hc->chip);
hc->wdcount = 0;
hc->wdbyte = V_GPIO_OUT2;
printk(KERN_NOTICE "Watchdog enabled\n");
}
if (pdev && ent)
/* setup pci, hc->slots may change due to PLXSD */
ret_err = setup_pci(hc, pdev, ent);
else
#ifdef CONFIG_MISDN_HFCMULTI_8xx
ret_err = setup_embedded(hc, m);
#else
{
printk(KERN_WARNING "Embedded IO Mode not selected\n");
ret_err = -EIO;
}
#endif
if (ret_err) {
if (hc == syncmaster)
syncmaster = NULL;
kfree(hc);
return ret_err;
}
hc->HFC_outb_nodebug = hc->HFC_outb;
hc->HFC_inb_nodebug = hc->HFC_inb;
hc->HFC_inw_nodebug = hc->HFC_inw;
hc->HFC_wait_nodebug = hc->HFC_wait;
#ifdef HFC_REGISTER_DEBUG
hc->HFC_outb = HFC_outb_debug;
hc->HFC_inb = HFC_inb_debug;
hc->HFC_inw = HFC_inw_debug;
hc->HFC_wait = HFC_wait_debug;
#endif
/* create channels */
for (pt = 0; pt < hc->ports; pt++) {
if (Port_cnt >= MAX_PORTS) {
printk(KERN_ERR "too many ports (max=%d).\n",
MAX_PORTS);
ret_err = -EINVAL;
goto free_card;
}
if (hc->ctype == HFC_TYPE_E1)
ret_err = init_e1_port(hc, m);
else
ret_err = init_multi_port(hc, pt);
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG
"%s: Registering D-channel, card(%d) port(%d)"
"result %d\n",
__func__, HFC_cnt + 1, pt, ret_err);
if (ret_err) {
while (pt) { /* release already registered ports */
pt--;
release_port(hc, hc->chan[(pt << 2) + 2].dch);
}
goto free_card;
}
Port_cnt++;
}
/* disp switches */
switch (m->dip_type) {
case DIP_4S:
/*
* Get DIP setting for beroNet 1S/2S/4S cards
* DIP Setting: (collect GPIO 13/14/15 (R_GPIO_IN1) +
* GPI 19/23 (R_GPI_IN2))
*/
dips = ((~HFC_inb(hc, R_GPIO_IN1) & 0xE0) >> 5) |
((~HFC_inb(hc, R_GPI_IN2) & 0x80) >> 3) |
(~HFC_inb(hc, R_GPI_IN2) & 0x08);
/* Port mode (TE/NT) jumpers */
pmj = ((HFC_inb(hc, R_GPI_IN3) >> 4) & 0xf);
if (test_bit(HFC_CHIP_B410P, &hc->chip))
pmj = ~pmj & 0xf;
printk(KERN_INFO "%s: %s DIPs(0x%x) jumpers(0x%x)\n",
m->vendor_name, m->card_name, dips, pmj);
break;
case DIP_8S:
/*
* Get DIP Setting for beroNet 8S0+ cards
* Enable PCI auxbridge function
*/
HFC_outb(hc, R_BRG_PCM_CFG, 1 | V_PCM_CLK);
/* prepare access to auxport */
outw(0x4000, hc->pci_iobase + 4);
/*
* some dummy reads are required to
* read valid DIP switch data
*/
dips = inb(hc->pci_iobase);
dips = inb(hc->pci_iobase);
dips = inb(hc->pci_iobase);
dips = ~inb(hc->pci_iobase) & 0x3F;
outw(0x0, hc->pci_iobase + 4);
/* disable PCI auxbridge function */
HFC_outb(hc, R_BRG_PCM_CFG, V_PCM_CLK);
printk(KERN_INFO "%s: %s DIPs(0x%x)\n",
m->vendor_name, m->card_name, dips);
break;
case DIP_E1:
/*
* get DIP Setting for beroNet E1 cards
* DIP Setting: collect GPI 4/5/6/7 (R_GPI_IN0)
*/
dips = (~HFC_inb(hc, R_GPI_IN0) & 0xF0) >> 4;
printk(KERN_INFO "%s: %s DIPs(0x%x)\n",
m->vendor_name, m->card_name, dips);
break;
}
/* add to list */
spin_lock_irqsave(&HFClock, flags);
list_add_tail(&hc->list, &HFClist);
spin_unlock_irqrestore(&HFClock, flags);
/* use as clock source */
if (clock == HFC_cnt + 1)
hc->iclock = mISDN_register_clock("HFCMulti", 0, clockctl, hc);
/* initialize hardware */
hc->irq = (m->irq) ? : hc->pci_dev->irq;
ret_err = init_card(hc);
if (ret_err) {
printk(KERN_ERR "init card returns %d\n", ret_err);
release_card(hc);
return ret_err;
}
/* start IRQ and return */
spin_lock_irqsave(&hc->lock, flags);
enable_hwirq(hc);
spin_unlock_irqrestore(&hc->lock, flags);
return 0;
free_card:
release_io_hfcmulti(hc);
if (hc == syncmaster)
syncmaster = NULL;
kfree(hc);
return ret_err;
}
static void __devexit hfc_remove_pci(struct pci_dev *pdev)
{
struct hfc_multi *card = pci_get_drvdata(pdev);
u_long flags;
if (debug)
printk(KERN_INFO "removing hfc_multi card vendor:%x "
"device:%x subvendor:%x subdevice:%x\n",
pdev->vendor, pdev->device,
pdev->subsystem_vendor, pdev->subsystem_device);
if (card) {
spin_lock_irqsave(&HFClock, flags);
release_card(card);
spin_unlock_irqrestore(&HFClock, flags);
} else {
if (debug)
printk(KERN_DEBUG "%s: drvdata already removed\n",
__func__);
}
}
#define VENDOR_CCD "Cologne Chip AG"
#define VENDOR_BN "beroNet GmbH"
#define VENDOR_DIG "Digium Inc."
#define VENDOR_JH "Junghanns.NET GmbH"
#define VENDOR_PRIM "PrimuX"
static const struct hm_map hfcm_map[] = {
/*0*/ {VENDOR_BN, "HFC-1S Card (mini PCI)", 4, 1, 1, 3, 0, DIP_4S, 0, 0},
/*1*/ {VENDOR_BN, "HFC-2S Card", 4, 2, 1, 3, 0, DIP_4S, 0, 0},
/*2*/ {VENDOR_BN, "HFC-2S Card (mini PCI)", 4, 2, 1, 3, 0, DIP_4S, 0, 0},
/*3*/ {VENDOR_BN, "HFC-4S Card", 4, 4, 1, 2, 0, DIP_4S, 0, 0},
/*4*/ {VENDOR_BN, "HFC-4S Card (mini PCI)", 4, 4, 1, 2, 0, 0, 0, 0},
/*5*/ {VENDOR_CCD, "HFC-4S Eval (old)", 4, 4, 0, 0, 0, 0, 0, 0},
/*6*/ {VENDOR_CCD, "HFC-4S IOB4ST", 4, 4, 1, 2, 0, DIP_4S, 0, 0},
/*7*/ {VENDOR_CCD, "HFC-4S", 4, 4, 1, 2, 0, 0, 0, 0},
/*8*/ {VENDOR_DIG, "HFC-4S Card", 4, 4, 0, 2, 0, 0, HFC_IO_MODE_REGIO, 0},
/*9*/ {VENDOR_CCD, "HFC-4S Swyx 4xS0 SX2 QuadBri", 4, 4, 1, 2, 0, 0, 0, 0},
/*10*/ {VENDOR_JH, "HFC-4S (junghanns 2.0)", 4, 4, 1, 2, 0, 0, 0, 0},
/*11*/ {VENDOR_PRIM, "HFC-2S Primux Card", 4, 2, 0, 0, 0, 0, 0, 0},
/*12*/ {VENDOR_BN, "HFC-8S Card", 8, 8, 1, 0, 0, 0, 0, 0},
/*13*/ {VENDOR_BN, "HFC-8S Card (+)", 8, 8, 1, 8, 0, DIP_8S,
HFC_IO_MODE_REGIO, 0},
/*14*/ {VENDOR_CCD, "HFC-8S Eval (old)", 8, 8, 0, 0, 0, 0, 0, 0},
/*15*/ {VENDOR_CCD, "HFC-8S IOB4ST Recording", 8, 8, 1, 0, 0, 0, 0, 0},
/*16*/ {VENDOR_CCD, "HFC-8S IOB8ST", 8, 8, 1, 0, 0, 0, 0, 0},
/*17*/ {VENDOR_CCD, "HFC-8S", 8, 8, 1, 0, 0, 0, 0, 0},
/*18*/ {VENDOR_CCD, "HFC-8S", 8, 8, 1, 0, 0, 0, 0, 0},
/*19*/ {VENDOR_BN, "HFC-E1 Card", 1, 1, 0, 1, 0, DIP_E1, 0, 0},
/*20*/ {VENDOR_BN, "HFC-E1 Card (mini PCI)", 1, 1, 0, 1, 0, 0, 0, 0},
/*21*/ {VENDOR_BN, "HFC-E1+ Card (Dual)", 1, 1, 0, 1, 0, DIP_E1, 0, 0},
/*22*/ {VENDOR_BN, "HFC-E1 Card (Dual)", 1, 1, 0, 1, 0, DIP_E1, 0, 0},
/*23*/ {VENDOR_CCD, "HFC-E1 Eval (old)", 1, 1, 0, 0, 0, 0, 0, 0},
/*24*/ {VENDOR_CCD, "HFC-E1 IOB1E1", 1, 1, 0, 1, 0, 0, 0, 0},
/*25*/ {VENDOR_CCD, "HFC-E1", 1, 1, 0, 1, 0, 0, 0, 0},
/*26*/ {VENDOR_CCD, "HFC-4S Speech Design", 4, 4, 0, 0, 0, 0,
HFC_IO_MODE_PLXSD, 0},
/*27*/ {VENDOR_CCD, "HFC-E1 Speech Design", 1, 1, 0, 0, 0, 0,
HFC_IO_MODE_PLXSD, 0},
/*28*/ {VENDOR_CCD, "HFC-4S OpenVox", 4, 4, 1, 0, 0, 0, 0, 0},
/*29*/ {VENDOR_CCD, "HFC-2S OpenVox", 4, 2, 1, 0, 0, 0, 0, 0},
/*30*/ {VENDOR_CCD, "HFC-8S OpenVox", 8, 8, 1, 0, 0, 0, 0, 0},
/*31*/ {VENDOR_CCD, "XHFC-4S Speech Design", 5, 4, 0, 0, 0, 0,
HFC_IO_MODE_EMBSD, XHFC_IRQ},
/*32*/ {VENDOR_JH, "HFC-8S (junghanns)", 8, 8, 1, 0, 0, 0, 0, 0},
/*33*/ {VENDOR_BN, "HFC-2S Beronet Card PCIe", 4, 2, 1, 3, 0, DIP_4S, 0, 0},
/*34*/ {VENDOR_BN, "HFC-4S Beronet Card PCIe", 4, 4, 1, 2, 0, DIP_4S, 0, 0},
};
#undef H
#define H(x) ((unsigned long)&hfcm_map[x])
static struct pci_device_id hfmultipci_ids[] __devinitdata = {
/* Cards with HFC-4S Chip */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC4S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_BN1SM, 0, 0, H(0)}, /* BN1S mini PCI */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC4S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_BN2S, 0, 0, H(1)}, /* BN2S */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC4S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_BN2SM, 0, 0, H(2)}, /* BN2S mini PCI */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC4S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_BN4S, 0, 0, H(3)}, /* BN4S */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC4S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_BN4SM, 0, 0, H(4)}, /* BN4S mini PCI */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC4S, PCI_VENDOR_ID_CCD,
PCI_DEVICE_ID_CCD_HFC4S, 0, 0, H(5)}, /* Old Eval */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC4S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_IOB4ST, 0, 0, H(6)}, /* IOB4ST */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC4S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_HFC4S, 0, 0, H(7)}, /* 4S */
{ PCI_VENDOR_ID_DIGIUM, PCI_DEVICE_ID_DIGIUM_HFC4S,
PCI_VENDOR_ID_DIGIUM, PCI_DEVICE_ID_DIGIUM_HFC4S, 0, 0, H(8)},
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC4S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_SWYX4S, 0, 0, H(9)}, /* 4S Swyx */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC4S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_JH4S20, 0, 0, H(10)},
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC4S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_PMX2S, 0, 0, H(11)}, /* Primux */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC4S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_OV4S, 0, 0, H(28)}, /* OpenVox 4 */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC4S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_OV2S, 0, 0, H(29)}, /* OpenVox 2 */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC4S, PCI_VENDOR_ID_CCD,
0xb761, 0, 0, H(33)}, /* BN2S PCIe */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC4S, PCI_VENDOR_ID_CCD,
0xb762, 0, 0, H(34)}, /* BN4S PCIe */
/* Cards with HFC-8S Chip */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC8S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_BN8S, 0, 0, H(12)}, /* BN8S */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC8S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_BN8SP, 0, 0, H(13)}, /* BN8S+ */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC8S, PCI_VENDOR_ID_CCD,
PCI_DEVICE_ID_CCD_HFC8S, 0, 0, H(14)}, /* old Eval */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC8S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_IOB8STR, 0, 0, H(15)}, /* IOB8ST Recording */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC8S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_IOB8ST, 0, 0, H(16)}, /* IOB8ST */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC8S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_IOB8ST_1, 0, 0, H(17)}, /* IOB8ST */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC8S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_HFC8S, 0, 0, H(18)}, /* 8S */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC8S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_OV8S, 0, 0, H(30)}, /* OpenVox 8 */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFC8S, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_JH8S, 0, 0, H(32)}, /* Junganns 8S */
/* Cards with HFC-E1 Chip */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFCE1, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_BNE1, 0, 0, H(19)}, /* BNE1 */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFCE1, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_BNE1M, 0, 0, H(20)}, /* BNE1 mini PCI */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFCE1, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_BNE1DP, 0, 0, H(21)}, /* BNE1 + (Dual) */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFCE1, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_BNE1D, 0, 0, H(22)}, /* BNE1 (Dual) */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFCE1, PCI_VENDOR_ID_CCD,
PCI_DEVICE_ID_CCD_HFCE1, 0, 0, H(23)}, /* Old Eval */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFCE1, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_IOB1E1, 0, 0, H(24)}, /* IOB1E1 */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFCE1, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_HFCE1, 0, 0, H(25)}, /* E1 */
{ PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9030, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_SPD4S, 0, 0, H(26)}, /* PLX PCI Bridge */
{ PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9030, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_SPDE1, 0, 0, H(27)}, /* PLX PCI Bridge */
{ PCI_VENDOR_ID_CCD, PCI_DEVICE_ID_CCD_HFCE1, PCI_VENDOR_ID_CCD,
PCI_SUBDEVICE_ID_CCD_JHSE1, 0, 0, H(25)}, /* Junghanns E1 */
{ PCI_VDEVICE(CCD, PCI_DEVICE_ID_CCD_HFC4S), 0 },
{ PCI_VDEVICE(CCD, PCI_DEVICE_ID_CCD_HFC8S), 0 },
{ PCI_VDEVICE(CCD, PCI_DEVICE_ID_CCD_HFCE1), 0 },
{0, }
};
#undef H
MODULE_DEVICE_TABLE(pci, hfmultipci_ids);
static int
hfcmulti_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct hm_map *m = (struct hm_map *)ent->driver_data;
int ret;
if (m == NULL && ent->vendor == PCI_VENDOR_ID_CCD && (
ent->device == PCI_DEVICE_ID_CCD_HFC4S ||
ent->device == PCI_DEVICE_ID_CCD_HFC8S ||
ent->device == PCI_DEVICE_ID_CCD_HFCE1)) {
printk(KERN_ERR
"Unknown HFC multiport controller (vendor:%04x device:%04x "
"subvendor:%04x subdevice:%04x)\n", pdev->vendor,
pdev->device, pdev->subsystem_vendor,
pdev->subsystem_device);
printk(KERN_ERR
"Please contact the driver maintainer for support.\n");
return -ENODEV;
}
ret = hfcmulti_init(m, pdev, ent);
if (ret)
return ret;
HFC_cnt++;
printk(KERN_INFO "%d devices registered\n", HFC_cnt);
return 0;
}
static struct pci_driver hfcmultipci_driver = {
.name = "hfc_multi",
.probe = hfcmulti_probe,
.remove = __devexit_p(hfc_remove_pci),
.id_table = hfmultipci_ids,
};
static void __exit
HFCmulti_cleanup(void)
{
struct hfc_multi *card, *next;
/* get rid of all devices of this driver */
list_for_each_entry_safe(card, next, &HFClist, list)
release_card(card);
pci_unregister_driver(&hfcmultipci_driver);
}
static int __init
HFCmulti_init(void)
{
int err;
int i, xhfc = 0;
struct hm_map m;
printk(KERN_INFO "mISDN: HFC-multi driver %s\n", HFC_MULTI_VERSION);
#ifdef IRQ_DEBUG
printk(KERN_DEBUG "%s: IRQ_DEBUG IS ENABLED!\n", __func__);
#endif
spin_lock_init(&HFClock);
spin_lock_init(&plx_lock);
if (debug & DEBUG_HFCMULTI_INIT)
printk(KERN_DEBUG "%s: init entered\n", __func__);
switch (poll) {
case 0:
poll_timer = 6;
poll = 128;
break;
case 8:
poll_timer = 2;
break;
case 16:
poll_timer = 3;
break;
case 32:
poll_timer = 4;
break;
case 64:
poll_timer = 5;
break;
case 128:
poll_timer = 6;
break;
case 256:
poll_timer = 7;
break;
default:
printk(KERN_ERR
"%s: Wrong poll value (%d).\n", __func__, poll);
err = -EINVAL;
return err;
}
if (!clock)
clock = 1;
/* Register the embedded devices.
* This should be done before the PCI cards registration */
switch (hwid) {
case HWID_MINIP4:
xhfc = 1;
m = hfcm_map[31];
break;
case HWID_MINIP8:
xhfc = 2;
m = hfcm_map[31];
break;
case HWID_MINIP16:
xhfc = 4;
m = hfcm_map[31];
break;
default:
xhfc = 0;
}
for (i = 0; i < xhfc; ++i) {
err = hfcmulti_init(&m, NULL, NULL);
if (err) {
printk(KERN_ERR "error registering embedded driver: "
"%x\n", err);
return err;
}
HFC_cnt++;
printk(KERN_INFO "%d devices registered\n", HFC_cnt);
}
/* Register the PCI cards */
err = pci_register_driver(&hfcmultipci_driver);
if (err < 0) {
printk(KERN_ERR "error registering pci driver: %x\n", err);
return err;
}
return 0;
}
module_init(HFCmulti_init);
module_exit(HFCmulti_cleanup);
| gpl-2.0 |
ModdedPA/android_kernel_google_msm | drivers/isdn/hardware/eicon/divamnt.c | 4809 | 5653 | /* $Id: divamnt.c,v 1.32.6.10 2005/02/11 19:40:25 armin Exp $
*
* Driver for Eicon DIVA Server ISDN cards.
* Maint module
*
* Copyright 2000-2003 by Armin Schindler (mac@melware.de)
* Copyright 2000-2003 Cytronics & Melware (info@melware.de)
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/poll.h>
#include <linux/mutex.h>
#include <asm/uaccess.h>
#include "platform.h"
#include "di_defs.h"
#include "divasync.h"
#include "debug_if.h"
static DEFINE_MUTEX(maint_mutex);
static char *main_revision = "$Revision: 1.32.6.10 $";
static int major;
MODULE_DESCRIPTION("Maint driver for Eicon DIVA Server cards");
MODULE_AUTHOR("Cytronics & Melware, Eicon Networks");
MODULE_SUPPORTED_DEVICE("DIVA card driver");
MODULE_LICENSE("GPL");
static int buffer_length = 128;
module_param(buffer_length, int, 0);
static unsigned long diva_dbg_mem = 0;
module_param(diva_dbg_mem, ulong, 0);
static char *DRIVERNAME =
"Eicon DIVA - MAINT module (http://www.melware.net)";
static char *DRIVERLNAME = "diva_mnt";
static char *DEVNAME = "DivasMAINT";
char *DRIVERRELEASE_MNT = "2.0";
static wait_queue_head_t msgwaitq;
static unsigned long opened;
static struct timeval start_time;
extern int mntfunc_init(int *, void **, unsigned long);
extern void mntfunc_finit(void);
extern int maint_read_write(void __user *buf, int count);
/*
* helper functions
*/
static char *getrev(const char *revision)
{
char *rev;
char *p;
if ((p = strchr(revision, ':'))) {
rev = p + 2;
p = strchr(rev, '$');
*--p = 0;
} else
rev = "1.0";
return rev;
}
/*
* kernel/user space copy functions
*/
int diva_os_copy_to_user(void *os_handle, void __user *dst, const void *src,
int length)
{
return (copy_to_user(dst, src, length));
}
int diva_os_copy_from_user(void *os_handle, void *dst, const void __user *src,
int length)
{
return (copy_from_user(dst, src, length));
}
/*
* get time
*/
void diva_os_get_time(dword *sec, dword *usec)
{
struct timeval tv;
do_gettimeofday(&tv);
if (tv.tv_sec > start_time.tv_sec) {
if (start_time.tv_usec > tv.tv_usec) {
tv.tv_sec--;
tv.tv_usec += 1000000;
}
*sec = (dword) (tv.tv_sec - start_time.tv_sec);
*usec = (dword) (tv.tv_usec - start_time.tv_usec);
} else if (tv.tv_sec == start_time.tv_sec) {
*sec = 0;
if (start_time.tv_usec < tv.tv_usec) {
*usec = (dword) (tv.tv_usec - start_time.tv_usec);
} else {
*usec = 0;
}
} else {
*sec = (dword) tv.tv_sec;
*usec = (dword) tv.tv_usec;
}
}
/*
* device node operations
*/
static unsigned int maint_poll(struct file *file, poll_table *wait)
{
unsigned int mask = 0;
poll_wait(file, &msgwaitq, wait);
mask = POLLOUT | POLLWRNORM;
if (file->private_data || diva_dbg_q_length()) {
mask |= POLLIN | POLLRDNORM;
}
return (mask);
}
static int maint_open(struct inode *ino, struct file *filep)
{
int ret;
mutex_lock(&maint_mutex);
/* only one open is allowed, so we test
it atomically */
if (test_and_set_bit(0, &opened))
ret = -EBUSY;
else {
filep->private_data = NULL;
ret = nonseekable_open(ino, filep);
}
mutex_unlock(&maint_mutex);
return ret;
}
static int maint_close(struct inode *ino, struct file *filep)
{
if (filep->private_data) {
diva_os_free(0, filep->private_data);
filep->private_data = NULL;
}
/* clear 'used' flag */
clear_bit(0, &opened);
return (0);
}
static ssize_t divas_maint_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
return (maint_read_write((char __user *) buf, (int) count));
}
static ssize_t divas_maint_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
return (maint_read_write(buf, (int) count));
}
static const struct file_operations divas_maint_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read = divas_maint_read,
.write = divas_maint_write,
.poll = maint_poll,
.open = maint_open,
.release = maint_close
};
static void divas_maint_unregister_chrdev(void)
{
unregister_chrdev(major, DEVNAME);
}
static int DIVA_INIT_FUNCTION divas_maint_register_chrdev(void)
{
if ((major = register_chrdev(0, DEVNAME, &divas_maint_fops)) < 0)
{
printk(KERN_ERR "%s: failed to create /dev entry.\n",
DRIVERLNAME);
return (0);
}
return (1);
}
/*
* wake up reader
*/
void diva_maint_wakeup_read(void)
{
wake_up_interruptible(&msgwaitq);
}
/*
* Driver Load
*/
static int DIVA_INIT_FUNCTION maint_init(void)
{
char tmprev[50];
int ret = 0;
void *buffer = NULL;
do_gettimeofday(&start_time);
init_waitqueue_head(&msgwaitq);
printk(KERN_INFO "%s\n", DRIVERNAME);
printk(KERN_INFO "%s: Rel:%s Rev:", DRIVERLNAME, DRIVERRELEASE_MNT);
strcpy(tmprev, main_revision);
printk("%s Build: %s \n", getrev(tmprev), DIVA_BUILD);
if (!divas_maint_register_chrdev()) {
ret = -EIO;
goto out;
}
if (!(mntfunc_init(&buffer_length, &buffer, diva_dbg_mem))) {
printk(KERN_ERR "%s: failed to connect to DIDD.\n",
DRIVERLNAME);
divas_maint_unregister_chrdev();
ret = -EIO;
goto out;
}
printk(KERN_INFO "%s: trace buffer = %p - %d kBytes, %s (Major: %d)\n",
DRIVERLNAME, buffer, (buffer_length / 1024),
(diva_dbg_mem == 0) ? "internal" : "external", major);
out:
return (ret);
}
/*
** Driver Unload
*/
static void DIVA_EXIT_FUNCTION maint_exit(void)
{
divas_maint_unregister_chrdev();
mntfunc_finit();
printk(KERN_INFO "%s: module unloaded.\n", DRIVERLNAME);
}
module_init(maint_init);
module_exit(maint_exit);
| gpl-2.0 |
ptmr3/android_kernel_lge_g3 | drivers/regulator/pcf50633-regulator.c | 4809 | 9334 | /* NXP PCF50633 PMIC Driver
*
* (C) 2006-2008 by Openmoko, Inc.
* Author: Balaji Rao <balajirrao@openmoko.org>
* All rights reserved.
*
* Broken down from monstrous PCF50633 driver mainly by
* Harald Welte and Andy Green and Werner Almesberger
*
* 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/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/mfd/pcf50633/core.h>
#include <linux/mfd/pcf50633/pmic.h>
#define PCF50633_REGULATOR(_name, _id, _n) \
{ \
.name = _name, \
.id = _id, \
.ops = &pcf50633_regulator_ops, \
.n_voltages = _n, \
.type = REGULATOR_VOLTAGE, \
.owner = THIS_MODULE, \
}
static const u8 pcf50633_regulator_registers[PCF50633_NUM_REGULATORS] = {
[PCF50633_REGULATOR_AUTO] = PCF50633_REG_AUTOOUT,
[PCF50633_REGULATOR_DOWN1] = PCF50633_REG_DOWN1OUT,
[PCF50633_REGULATOR_DOWN2] = PCF50633_REG_DOWN2OUT,
[PCF50633_REGULATOR_MEMLDO] = PCF50633_REG_MEMLDOOUT,
[PCF50633_REGULATOR_LDO1] = PCF50633_REG_LDO1OUT,
[PCF50633_REGULATOR_LDO2] = PCF50633_REG_LDO2OUT,
[PCF50633_REGULATOR_LDO3] = PCF50633_REG_LDO3OUT,
[PCF50633_REGULATOR_LDO4] = PCF50633_REG_LDO4OUT,
[PCF50633_REGULATOR_LDO5] = PCF50633_REG_LDO5OUT,
[PCF50633_REGULATOR_LDO6] = PCF50633_REG_LDO6OUT,
[PCF50633_REGULATOR_HCLDO] = PCF50633_REG_HCLDOOUT,
};
/* Bits from voltage value */
static u8 auto_voltage_bits(unsigned int millivolts)
{
if (millivolts < 1800)
return 0;
if (millivolts > 3800)
return 0xff;
millivolts -= 625;
return millivolts / 25;
}
static u8 down_voltage_bits(unsigned int millivolts)
{
if (millivolts < 625)
return 0;
else if (millivolts > 3000)
return 0xff;
millivolts -= 625;
return millivolts / 25;
}
static u8 ldo_voltage_bits(unsigned int millivolts)
{
if (millivolts < 900)
return 0;
else if (millivolts > 3600)
return 0x1f;
millivolts -= 900;
return millivolts / 100;
}
/* Obtain voltage value from bits */
static unsigned int auto_voltage_value(u8 bits)
{
if (bits < 0x2f)
return 0;
return 625 + (bits * 25);
}
static unsigned int down_voltage_value(u8 bits)
{
return 625 + (bits * 25);
}
static unsigned int ldo_voltage_value(u8 bits)
{
bits &= 0x1f;
return 900 + (bits * 100);
}
static int pcf50633_regulator_set_voltage(struct regulator_dev *rdev,
int min_uV, int max_uV,
unsigned *selector)
{
struct pcf50633 *pcf;
int regulator_id, millivolts;
u8 volt_bits, regnr;
pcf = rdev_get_drvdata(rdev);
regulator_id = rdev_get_id(rdev);
if (regulator_id >= PCF50633_NUM_REGULATORS)
return -EINVAL;
millivolts = min_uV / 1000;
regnr = pcf50633_regulator_registers[regulator_id];
switch (regulator_id) {
case PCF50633_REGULATOR_AUTO:
volt_bits = auto_voltage_bits(millivolts);
break;
case PCF50633_REGULATOR_DOWN1:
volt_bits = down_voltage_bits(millivolts);
break;
case PCF50633_REGULATOR_DOWN2:
volt_bits = down_voltage_bits(millivolts);
break;
case PCF50633_REGULATOR_LDO1:
case PCF50633_REGULATOR_LDO2:
case PCF50633_REGULATOR_LDO3:
case PCF50633_REGULATOR_LDO4:
case PCF50633_REGULATOR_LDO5:
case PCF50633_REGULATOR_LDO6:
case PCF50633_REGULATOR_HCLDO:
case PCF50633_REGULATOR_MEMLDO:
volt_bits = ldo_voltage_bits(millivolts);
break;
default:
return -EINVAL;
}
*selector = volt_bits;
return pcf50633_reg_write(pcf, regnr, volt_bits);
}
static int pcf50633_regulator_voltage_value(enum pcf50633_regulator_id id,
u8 bits)
{
int millivolts;
switch (id) {
case PCF50633_REGULATOR_AUTO:
millivolts = auto_voltage_value(bits);
break;
case PCF50633_REGULATOR_DOWN1:
millivolts = down_voltage_value(bits);
break;
case PCF50633_REGULATOR_DOWN2:
millivolts = down_voltage_value(bits);
break;
case PCF50633_REGULATOR_LDO1:
case PCF50633_REGULATOR_LDO2:
case PCF50633_REGULATOR_LDO3:
case PCF50633_REGULATOR_LDO4:
case PCF50633_REGULATOR_LDO5:
case PCF50633_REGULATOR_LDO6:
case PCF50633_REGULATOR_HCLDO:
case PCF50633_REGULATOR_MEMLDO:
millivolts = ldo_voltage_value(bits);
break;
default:
return -EINVAL;
}
return millivolts * 1000;
}
static int pcf50633_regulator_get_voltage(struct regulator_dev *rdev)
{
struct pcf50633 *pcf;
int regulator_id;
u8 volt_bits, regnr;
pcf = rdev_get_drvdata(rdev);
regulator_id = rdev_get_id(rdev);
if (regulator_id >= PCF50633_NUM_REGULATORS)
return -EINVAL;
regnr = pcf50633_regulator_registers[regulator_id];
volt_bits = pcf50633_reg_read(pcf, regnr);
return pcf50633_regulator_voltage_value(regulator_id, volt_bits);
}
static int pcf50633_regulator_list_voltage(struct regulator_dev *rdev,
unsigned int index)
{
struct pcf50633 *pcf;
int regulator_id;
pcf = rdev_get_drvdata(rdev);
regulator_id = rdev_get_id(rdev);
switch (regulator_id) {
case PCF50633_REGULATOR_AUTO:
index += 0x2f;
break;
default:
break;
}
return pcf50633_regulator_voltage_value(regulator_id, index);
}
static int pcf50633_regulator_enable(struct regulator_dev *rdev)
{
struct pcf50633 *pcf = rdev_get_drvdata(rdev);
int regulator_id;
u8 regnr;
regulator_id = rdev_get_id(rdev);
if (regulator_id >= PCF50633_NUM_REGULATORS)
return -EINVAL;
/* The *ENA register is always one after the *OUT register */
regnr = pcf50633_regulator_registers[regulator_id] + 1;
return pcf50633_reg_set_bit_mask(pcf, regnr, PCF50633_REGULATOR_ON,
PCF50633_REGULATOR_ON);
}
static int pcf50633_regulator_disable(struct regulator_dev *rdev)
{
struct pcf50633 *pcf = rdev_get_drvdata(rdev);
int regulator_id;
u8 regnr;
regulator_id = rdev_get_id(rdev);
if (regulator_id >= PCF50633_NUM_REGULATORS)
return -EINVAL;
/* the *ENA register is always one after the *OUT register */
regnr = pcf50633_regulator_registers[regulator_id] + 1;
return pcf50633_reg_set_bit_mask(pcf, regnr,
PCF50633_REGULATOR_ON, 0);
}
static int pcf50633_regulator_is_enabled(struct regulator_dev *rdev)
{
struct pcf50633 *pcf = rdev_get_drvdata(rdev);
int regulator_id = rdev_get_id(rdev);
u8 regnr;
regulator_id = rdev_get_id(rdev);
if (regulator_id >= PCF50633_NUM_REGULATORS)
return -EINVAL;
/* the *ENA register is always one after the *OUT register */
regnr = pcf50633_regulator_registers[regulator_id] + 1;
return pcf50633_reg_read(pcf, regnr) & PCF50633_REGULATOR_ON;
}
static struct regulator_ops pcf50633_regulator_ops = {
.set_voltage = pcf50633_regulator_set_voltage,
.get_voltage = pcf50633_regulator_get_voltage,
.list_voltage = pcf50633_regulator_list_voltage,
.enable = pcf50633_regulator_enable,
.disable = pcf50633_regulator_disable,
.is_enabled = pcf50633_regulator_is_enabled,
};
static struct regulator_desc regulators[] = {
[PCF50633_REGULATOR_AUTO] =
PCF50633_REGULATOR("auto", PCF50633_REGULATOR_AUTO, 81),
[PCF50633_REGULATOR_DOWN1] =
PCF50633_REGULATOR("down1", PCF50633_REGULATOR_DOWN1, 96),
[PCF50633_REGULATOR_DOWN2] =
PCF50633_REGULATOR("down2", PCF50633_REGULATOR_DOWN2, 96),
[PCF50633_REGULATOR_LDO1] =
PCF50633_REGULATOR("ldo1", PCF50633_REGULATOR_LDO1, 28),
[PCF50633_REGULATOR_LDO2] =
PCF50633_REGULATOR("ldo2", PCF50633_REGULATOR_LDO2, 28),
[PCF50633_REGULATOR_LDO3] =
PCF50633_REGULATOR("ldo3", PCF50633_REGULATOR_LDO3, 28),
[PCF50633_REGULATOR_LDO4] =
PCF50633_REGULATOR("ldo4", PCF50633_REGULATOR_LDO4, 28),
[PCF50633_REGULATOR_LDO5] =
PCF50633_REGULATOR("ldo5", PCF50633_REGULATOR_LDO5, 28),
[PCF50633_REGULATOR_LDO6] =
PCF50633_REGULATOR("ldo6", PCF50633_REGULATOR_LDO6, 28),
[PCF50633_REGULATOR_HCLDO] =
PCF50633_REGULATOR("hcldo", PCF50633_REGULATOR_HCLDO, 28),
[PCF50633_REGULATOR_MEMLDO] =
PCF50633_REGULATOR("memldo", PCF50633_REGULATOR_MEMLDO, 28),
};
static int __devinit pcf50633_regulator_probe(struct platform_device *pdev)
{
struct regulator_dev *rdev;
struct pcf50633 *pcf;
/* Already set by core driver */
pcf = dev_to_pcf50633(pdev->dev.parent);
rdev = regulator_register(®ulators[pdev->id], &pdev->dev,
pdev->dev.platform_data, pcf, NULL);
if (IS_ERR(rdev))
return PTR_ERR(rdev);
platform_set_drvdata(pdev, rdev);
if (pcf->pdata->regulator_registered)
pcf->pdata->regulator_registered(pcf, pdev->id);
return 0;
}
static int __devexit pcf50633_regulator_remove(struct platform_device *pdev)
{
struct regulator_dev *rdev = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
regulator_unregister(rdev);
return 0;
}
static struct platform_driver pcf50633_regulator_driver = {
.driver = {
.name = "pcf50633-regltr",
},
.probe = pcf50633_regulator_probe,
.remove = __devexit_p(pcf50633_regulator_remove),
};
static int __init pcf50633_regulator_init(void)
{
return platform_driver_register(&pcf50633_regulator_driver);
}
subsys_initcall(pcf50633_regulator_init);
static void __exit pcf50633_regulator_exit(void)
{
platform_driver_unregister(&pcf50633_regulator_driver);
}
module_exit(pcf50633_regulator_exit);
MODULE_AUTHOR("Balaji Rao <balajirrao@openmoko.org>");
MODULE_DESCRIPTION("PCF50633 regulator driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:pcf50633-regulator");
| gpl-2.0 |
netarchy/Supersonic-2.6.35-Gingersense | sound/synth/emux/emux.c | 4809 | 4303 | /*
* Copyright (C) 2000 Takashi Iwai <tiwai@suse.de>
*
* Routines for control of EMU WaveTable chip
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/wait.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <sound/core.h>
#include <sound/emux_synth.h>
#include <linux/init.h>
#include "emux_voice.h"
MODULE_AUTHOR("Takashi Iwai");
MODULE_DESCRIPTION("Routines for control of EMU WaveTable chip");
MODULE_LICENSE("GPL");
/*
* create a new hardware dependent device for Emu8000/Emu10k1
*/
int snd_emux_new(struct snd_emux **remu)
{
struct snd_emux *emu;
*remu = NULL;
emu = kzalloc(sizeof(*emu), GFP_KERNEL);
if (emu == NULL)
return -ENOMEM;
spin_lock_init(&emu->voice_lock);
mutex_init(&emu->register_mutex);
emu->client = -1;
#ifdef CONFIG_SND_SEQUENCER_OSS
emu->oss_synth = NULL;
#endif
emu->max_voices = 0;
emu->use_time = 0;
init_timer(&emu->tlist);
emu->tlist.function = snd_emux_timer_callback;
emu->tlist.data = (unsigned long)emu;
emu->timer_active = 0;
*remu = emu;
return 0;
}
EXPORT_SYMBOL(snd_emux_new);
/*
*/
static int sf_sample_new(void *private_data, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr,
const void __user *buf, long count)
{
struct snd_emux *emu = private_data;
return emu->ops.sample_new(emu, sp, hdr, buf, count);
}
static int sf_sample_free(void *private_data, struct snd_sf_sample *sp,
struct snd_util_memhdr *hdr)
{
struct snd_emux *emu = private_data;
return emu->ops.sample_free(emu, sp, hdr);
}
static void sf_sample_reset(void *private_data)
{
struct snd_emux *emu = private_data;
emu->ops.sample_reset(emu);
}
int snd_emux_register(struct snd_emux *emu, struct snd_card *card, int index, char *name)
{
int err;
struct snd_sf_callback sf_cb;
if (snd_BUG_ON(!emu->hw || emu->max_voices <= 0))
return -EINVAL;
if (snd_BUG_ON(!card || !name))
return -EINVAL;
emu->card = card;
emu->name = kstrdup(name, GFP_KERNEL);
emu->voices = kcalloc(emu->max_voices, sizeof(struct snd_emux_voice),
GFP_KERNEL);
if (emu->voices == NULL)
return -ENOMEM;
/* create soundfont list */
memset(&sf_cb, 0, sizeof(sf_cb));
sf_cb.private_data = emu;
if (emu->ops.sample_new)
sf_cb.sample_new = sf_sample_new;
if (emu->ops.sample_free)
sf_cb.sample_free = sf_sample_free;
if (emu->ops.sample_reset)
sf_cb.sample_reset = sf_sample_reset;
emu->sflist = snd_sf_new(&sf_cb, emu->memhdr);
if (emu->sflist == NULL)
return -ENOMEM;
if ((err = snd_emux_init_hwdep(emu)) < 0)
return err;
snd_emux_init_voices(emu);
snd_emux_init_seq(emu, card, index);
#ifdef CONFIG_SND_SEQUENCER_OSS
snd_emux_init_seq_oss(emu);
#endif
snd_emux_init_virmidi(emu, card);
#ifdef CONFIG_PROC_FS
snd_emux_proc_init(emu, card, index);
#endif
return 0;
}
EXPORT_SYMBOL(snd_emux_register);
/*
*/
int snd_emux_free(struct snd_emux *emu)
{
unsigned long flags;
if (! emu)
return -EINVAL;
spin_lock_irqsave(&emu->voice_lock, flags);
if (emu->timer_active)
del_timer(&emu->tlist);
spin_unlock_irqrestore(&emu->voice_lock, flags);
#ifdef CONFIG_PROC_FS
snd_emux_proc_free(emu);
#endif
snd_emux_delete_virmidi(emu);
#ifdef CONFIG_SND_SEQUENCER_OSS
snd_emux_detach_seq_oss(emu);
#endif
snd_emux_detach_seq(emu);
snd_emux_delete_hwdep(emu);
if (emu->sflist)
snd_sf_free(emu->sflist);
kfree(emu->voices);
kfree(emu->name);
kfree(emu);
return 0;
}
EXPORT_SYMBOL(snd_emux_free);
/*
* INIT part
*/
static int __init alsa_emux_init(void)
{
return 0;
}
static void __exit alsa_emux_exit(void)
{
}
module_init(alsa_emux_init)
module_exit(alsa_emux_exit)
| gpl-2.0 |
justin0406/HD-GEE | drivers/net/ethernet/intel/ixgbe/ixgbe_82599.c | 4809 | 68773 | /*******************************************************************************
Intel 10 Gigabit PCI Express Linux driver
Copyright(c) 1999 - 2012 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include "ixgbe.h"
#include "ixgbe_phy.h"
#include "ixgbe_mbx.h"
#define IXGBE_82599_MAX_TX_QUEUES 128
#define IXGBE_82599_MAX_RX_QUEUES 128
#define IXGBE_82599_RAR_ENTRIES 128
#define IXGBE_82599_MC_TBL_SIZE 128
#define IXGBE_82599_VFT_TBL_SIZE 128
#define IXGBE_82599_RX_PB_SIZE 512
static void ixgbe_disable_tx_laser_multispeed_fiber(struct ixgbe_hw *hw);
static void ixgbe_enable_tx_laser_multispeed_fiber(struct ixgbe_hw *hw);
static void ixgbe_flap_tx_laser_multispeed_fiber(struct ixgbe_hw *hw);
static s32 ixgbe_setup_mac_link_multispeed_fiber(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg,
bool autoneg_wait_to_complete);
static s32 ixgbe_setup_mac_link_smartspeed(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg,
bool autoneg_wait_to_complete);
static s32 ixgbe_start_mac_link_82599(struct ixgbe_hw *hw,
bool autoneg_wait_to_complete);
static s32 ixgbe_setup_mac_link_82599(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg,
bool autoneg_wait_to_complete);
static s32 ixgbe_setup_copper_link_82599(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg,
bool autoneg_wait_to_complete);
static s32 ixgbe_verify_fw_version_82599(struct ixgbe_hw *hw);
static bool ixgbe_verify_lesm_fw_enabled_82599(struct ixgbe_hw *hw);
static void ixgbe_init_mac_link_ops_82599(struct ixgbe_hw *hw)
{
struct ixgbe_mac_info *mac = &hw->mac;
/* enable the laser control functions for SFP+ fiber */
if (mac->ops.get_media_type(hw) == ixgbe_media_type_fiber) {
mac->ops.disable_tx_laser =
&ixgbe_disable_tx_laser_multispeed_fiber;
mac->ops.enable_tx_laser =
&ixgbe_enable_tx_laser_multispeed_fiber;
mac->ops.flap_tx_laser = &ixgbe_flap_tx_laser_multispeed_fiber;
} else {
mac->ops.disable_tx_laser = NULL;
mac->ops.enable_tx_laser = NULL;
mac->ops.flap_tx_laser = NULL;
}
if (hw->phy.multispeed_fiber) {
/* Set up dual speed SFP+ support */
mac->ops.setup_link = &ixgbe_setup_mac_link_multispeed_fiber;
} else {
if ((mac->ops.get_media_type(hw) ==
ixgbe_media_type_backplane) &&
(hw->phy.smart_speed == ixgbe_smart_speed_auto ||
hw->phy.smart_speed == ixgbe_smart_speed_on) &&
!ixgbe_verify_lesm_fw_enabled_82599(hw))
mac->ops.setup_link = &ixgbe_setup_mac_link_smartspeed;
else
mac->ops.setup_link = &ixgbe_setup_mac_link_82599;
}
}
static s32 ixgbe_setup_sfp_modules_82599(struct ixgbe_hw *hw)
{
s32 ret_val = 0;
u32 reg_anlp1 = 0;
u32 i = 0;
u16 list_offset, data_offset, data_value;
if (hw->phy.sfp_type != ixgbe_sfp_type_unknown) {
ixgbe_init_mac_link_ops_82599(hw);
hw->phy.ops.reset = NULL;
ret_val = ixgbe_get_sfp_init_sequence_offsets(hw, &list_offset,
&data_offset);
if (ret_val != 0)
goto setup_sfp_out;
/* PHY config will finish before releasing the semaphore */
ret_val = hw->mac.ops.acquire_swfw_sync(hw,
IXGBE_GSSR_MAC_CSR_SM);
if (ret_val != 0) {
ret_val = IXGBE_ERR_SWFW_SYNC;
goto setup_sfp_out;
}
hw->eeprom.ops.read(hw, ++data_offset, &data_value);
while (data_value != 0xffff) {
IXGBE_WRITE_REG(hw, IXGBE_CORECTL, data_value);
IXGBE_WRITE_FLUSH(hw);
hw->eeprom.ops.read(hw, ++data_offset, &data_value);
}
/* Release the semaphore */
hw->mac.ops.release_swfw_sync(hw, IXGBE_GSSR_MAC_CSR_SM);
/*
* Delay obtaining semaphore again to allow FW access,
* semaphore_delay is in ms usleep_range needs us.
*/
usleep_range(hw->eeprom.semaphore_delay * 1000,
hw->eeprom.semaphore_delay * 2000);
/* Now restart DSP by setting Restart_AN and clearing LMS */
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, ((IXGBE_READ_REG(hw,
IXGBE_AUTOC) & ~IXGBE_AUTOC_LMS_MASK) |
IXGBE_AUTOC_AN_RESTART));
/* Wait for AN to leave state 0 */
for (i = 0; i < 10; i++) {
usleep_range(4000, 8000);
reg_anlp1 = IXGBE_READ_REG(hw, IXGBE_ANLP1);
if (reg_anlp1 & IXGBE_ANLP1_AN_STATE_MASK)
break;
}
if (!(reg_anlp1 & IXGBE_ANLP1_AN_STATE_MASK)) {
hw_dbg(hw, "sfp module setup not complete\n");
ret_val = IXGBE_ERR_SFP_SETUP_NOT_COMPLETE;
goto setup_sfp_out;
}
/* Restart DSP by setting Restart_AN and return to SFI mode */
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, (IXGBE_READ_REG(hw,
IXGBE_AUTOC) | IXGBE_AUTOC_LMS_10G_SERIAL |
IXGBE_AUTOC_AN_RESTART));
}
setup_sfp_out:
return ret_val;
}
static s32 ixgbe_get_invariants_82599(struct ixgbe_hw *hw)
{
struct ixgbe_mac_info *mac = &hw->mac;
ixgbe_init_mac_link_ops_82599(hw);
mac->mcft_size = IXGBE_82599_MC_TBL_SIZE;
mac->vft_size = IXGBE_82599_VFT_TBL_SIZE;
mac->num_rar_entries = IXGBE_82599_RAR_ENTRIES;
mac->max_rx_queues = IXGBE_82599_MAX_RX_QUEUES;
mac->max_tx_queues = IXGBE_82599_MAX_TX_QUEUES;
mac->max_msix_vectors = ixgbe_get_pcie_msix_count_generic(hw);
return 0;
}
/**
* ixgbe_init_phy_ops_82599 - PHY/SFP specific init
* @hw: pointer to hardware structure
*
* Initialize any function pointers that were not able to be
* set during get_invariants because the PHY/SFP type was
* not known. Perform the SFP init if necessary.
*
**/
static s32 ixgbe_init_phy_ops_82599(struct ixgbe_hw *hw)
{
struct ixgbe_mac_info *mac = &hw->mac;
struct ixgbe_phy_info *phy = &hw->phy;
s32 ret_val = 0;
/* Identify the PHY or SFP module */
ret_val = phy->ops.identify(hw);
/* Setup function pointers based on detected SFP module and speeds */
ixgbe_init_mac_link_ops_82599(hw);
/* If copper media, overwrite with copper function pointers */
if (mac->ops.get_media_type(hw) == ixgbe_media_type_copper) {
mac->ops.setup_link = &ixgbe_setup_copper_link_82599;
mac->ops.get_link_capabilities =
&ixgbe_get_copper_link_capabilities_generic;
}
/* Set necessary function pointers based on phy type */
switch (hw->phy.type) {
case ixgbe_phy_tn:
phy->ops.check_link = &ixgbe_check_phy_link_tnx;
phy->ops.setup_link = &ixgbe_setup_phy_link_tnx;
phy->ops.get_firmware_version =
&ixgbe_get_phy_firmware_version_tnx;
break;
default:
break;
}
return ret_val;
}
/**
* ixgbe_get_link_capabilities_82599 - Determines link capabilities
* @hw: pointer to hardware structure
* @speed: pointer to link speed
* @negotiation: true when autoneg or autotry is enabled
*
* Determines the link capabilities by reading the AUTOC register.
**/
static s32 ixgbe_get_link_capabilities_82599(struct ixgbe_hw *hw,
ixgbe_link_speed *speed,
bool *negotiation)
{
s32 status = 0;
u32 autoc = 0;
/* Determine 1G link capabilities off of SFP+ type */
if (hw->phy.sfp_type == ixgbe_sfp_type_1g_cu_core0 ||
hw->phy.sfp_type == ixgbe_sfp_type_1g_cu_core1) {
*speed = IXGBE_LINK_SPEED_1GB_FULL;
*negotiation = true;
goto out;
}
/*
* Determine link capabilities based on the stored value of AUTOC,
* which represents EEPROM defaults. If AUTOC value has not been
* stored, use the current register value.
*/
if (hw->mac.orig_link_settings_stored)
autoc = hw->mac.orig_autoc;
else
autoc = IXGBE_READ_REG(hw, IXGBE_AUTOC);
switch (autoc & IXGBE_AUTOC_LMS_MASK) {
case IXGBE_AUTOC_LMS_1G_LINK_NO_AN:
*speed = IXGBE_LINK_SPEED_1GB_FULL;
*negotiation = false;
break;
case IXGBE_AUTOC_LMS_10G_LINK_NO_AN:
*speed = IXGBE_LINK_SPEED_10GB_FULL;
*negotiation = false;
break;
case IXGBE_AUTOC_LMS_1G_AN:
*speed = IXGBE_LINK_SPEED_1GB_FULL;
*negotiation = true;
break;
case IXGBE_AUTOC_LMS_10G_SERIAL:
*speed = IXGBE_LINK_SPEED_10GB_FULL;
*negotiation = false;
break;
case IXGBE_AUTOC_LMS_KX4_KX_KR:
case IXGBE_AUTOC_LMS_KX4_KX_KR_1G_AN:
*speed = IXGBE_LINK_SPEED_UNKNOWN;
if (autoc & IXGBE_AUTOC_KR_SUPP)
*speed |= IXGBE_LINK_SPEED_10GB_FULL;
if (autoc & IXGBE_AUTOC_KX4_SUPP)
*speed |= IXGBE_LINK_SPEED_10GB_FULL;
if (autoc & IXGBE_AUTOC_KX_SUPP)
*speed |= IXGBE_LINK_SPEED_1GB_FULL;
*negotiation = true;
break;
case IXGBE_AUTOC_LMS_KX4_KX_KR_SGMII:
*speed = IXGBE_LINK_SPEED_100_FULL;
if (autoc & IXGBE_AUTOC_KR_SUPP)
*speed |= IXGBE_LINK_SPEED_10GB_FULL;
if (autoc & IXGBE_AUTOC_KX4_SUPP)
*speed |= IXGBE_LINK_SPEED_10GB_FULL;
if (autoc & IXGBE_AUTOC_KX_SUPP)
*speed |= IXGBE_LINK_SPEED_1GB_FULL;
*negotiation = true;
break;
case IXGBE_AUTOC_LMS_SGMII_1G_100M:
*speed = IXGBE_LINK_SPEED_1GB_FULL | IXGBE_LINK_SPEED_100_FULL;
*negotiation = false;
break;
default:
status = IXGBE_ERR_LINK_SETUP;
goto out;
break;
}
if (hw->phy.multispeed_fiber) {
*speed |= IXGBE_LINK_SPEED_10GB_FULL |
IXGBE_LINK_SPEED_1GB_FULL;
*negotiation = true;
}
out:
return status;
}
/**
* ixgbe_get_media_type_82599 - Get media type
* @hw: pointer to hardware structure
*
* Returns the media type (fiber, copper, backplane)
**/
static enum ixgbe_media_type ixgbe_get_media_type_82599(struct ixgbe_hw *hw)
{
enum ixgbe_media_type media_type;
/* Detect if there is a copper PHY attached. */
switch (hw->phy.type) {
case ixgbe_phy_cu_unknown:
case ixgbe_phy_tn:
media_type = ixgbe_media_type_copper;
goto out;
default:
break;
}
switch (hw->device_id) {
case IXGBE_DEV_ID_82599_KX4:
case IXGBE_DEV_ID_82599_KX4_MEZZ:
case IXGBE_DEV_ID_82599_COMBO_BACKPLANE:
case IXGBE_DEV_ID_82599_KR:
case IXGBE_DEV_ID_82599_BACKPLANE_FCOE:
case IXGBE_DEV_ID_82599_XAUI_LOM:
/* Default device ID is mezzanine card KX/KX4 */
media_type = ixgbe_media_type_backplane;
break;
case IXGBE_DEV_ID_82599_SFP:
case IXGBE_DEV_ID_82599_SFP_FCOE:
case IXGBE_DEV_ID_82599_SFP_EM:
case IXGBE_DEV_ID_82599_SFP_SF2:
case IXGBE_DEV_ID_82599_SFP_SF_QP:
case IXGBE_DEV_ID_82599EN_SFP:
media_type = ixgbe_media_type_fiber;
break;
case IXGBE_DEV_ID_82599_CX4:
media_type = ixgbe_media_type_cx4;
break;
case IXGBE_DEV_ID_82599_T3_LOM:
media_type = ixgbe_media_type_copper;
break;
case IXGBE_DEV_ID_82599_LS:
media_type = ixgbe_media_type_fiber_lco;
break;
default:
media_type = ixgbe_media_type_unknown;
break;
}
out:
return media_type;
}
/**
* ixgbe_start_mac_link_82599 - Setup MAC link settings
* @hw: pointer to hardware structure
* @autoneg_wait_to_complete: true when waiting for completion is needed
*
* Configures link settings based on values in the ixgbe_hw struct.
* Restarts the link. Performs autonegotiation if needed.
**/
static s32 ixgbe_start_mac_link_82599(struct ixgbe_hw *hw,
bool autoneg_wait_to_complete)
{
u32 autoc_reg;
u32 links_reg;
u32 i;
s32 status = 0;
/* Restart link */
autoc_reg = IXGBE_READ_REG(hw, IXGBE_AUTOC);
autoc_reg |= IXGBE_AUTOC_AN_RESTART;
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, autoc_reg);
/* Only poll for autoneg to complete if specified to do so */
if (autoneg_wait_to_complete) {
if ((autoc_reg & IXGBE_AUTOC_LMS_MASK) ==
IXGBE_AUTOC_LMS_KX4_KX_KR ||
(autoc_reg & IXGBE_AUTOC_LMS_MASK) ==
IXGBE_AUTOC_LMS_KX4_KX_KR_1G_AN ||
(autoc_reg & IXGBE_AUTOC_LMS_MASK) ==
IXGBE_AUTOC_LMS_KX4_KX_KR_SGMII) {
links_reg = 0; /* Just in case Autoneg time = 0 */
for (i = 0; i < IXGBE_AUTO_NEG_TIME; i++) {
links_reg = IXGBE_READ_REG(hw, IXGBE_LINKS);
if (links_reg & IXGBE_LINKS_KX_AN_COMP)
break;
msleep(100);
}
if (!(links_reg & IXGBE_LINKS_KX_AN_COMP)) {
status = IXGBE_ERR_AUTONEG_NOT_COMPLETE;
hw_dbg(hw, "Autoneg did not complete.\n");
}
}
}
/* Add delay to filter out noises during initial link setup */
msleep(50);
return status;
}
/**
* ixgbe_disable_tx_laser_multispeed_fiber - Disable Tx laser
* @hw: pointer to hardware structure
*
* The base drivers may require better control over SFP+ module
* PHY states. This includes selectively shutting down the Tx
* laser on the PHY, effectively halting physical link.
**/
static void ixgbe_disable_tx_laser_multispeed_fiber(struct ixgbe_hw *hw)
{
u32 esdp_reg = IXGBE_READ_REG(hw, IXGBE_ESDP);
/* Disable tx laser; allow 100us to go dark per spec */
esdp_reg |= IXGBE_ESDP_SDP3;
IXGBE_WRITE_REG(hw, IXGBE_ESDP, esdp_reg);
IXGBE_WRITE_FLUSH(hw);
udelay(100);
}
/**
* ixgbe_enable_tx_laser_multispeed_fiber - Enable Tx laser
* @hw: pointer to hardware structure
*
* The base drivers may require better control over SFP+ module
* PHY states. This includes selectively turning on the Tx
* laser on the PHY, effectively starting physical link.
**/
static void ixgbe_enable_tx_laser_multispeed_fiber(struct ixgbe_hw *hw)
{
u32 esdp_reg = IXGBE_READ_REG(hw, IXGBE_ESDP);
/* Enable tx laser; allow 100ms to light up */
esdp_reg &= ~IXGBE_ESDP_SDP3;
IXGBE_WRITE_REG(hw, IXGBE_ESDP, esdp_reg);
IXGBE_WRITE_FLUSH(hw);
msleep(100);
}
/**
* ixgbe_flap_tx_laser_multispeed_fiber - Flap Tx laser
* @hw: pointer to hardware structure
*
* When the driver changes the link speeds that it can support,
* it sets autotry_restart to true to indicate that we need to
* initiate a new autotry session with the link partner. To do
* so, we set the speed then disable and re-enable the tx laser, to
* alert the link partner that it also needs to restart autotry on its
* end. This is consistent with true clause 37 autoneg, which also
* involves a loss of signal.
**/
static void ixgbe_flap_tx_laser_multispeed_fiber(struct ixgbe_hw *hw)
{
if (hw->mac.autotry_restart) {
ixgbe_disable_tx_laser_multispeed_fiber(hw);
ixgbe_enable_tx_laser_multispeed_fiber(hw);
hw->mac.autotry_restart = false;
}
}
/**
* ixgbe_setup_mac_link_multispeed_fiber - Set MAC link speed
* @hw: pointer to hardware structure
* @speed: new link speed
* @autoneg: true if autonegotiation enabled
* @autoneg_wait_to_complete: true when waiting for completion is needed
*
* Set the link speed in the AUTOC register and restarts link.
**/
static s32 ixgbe_setup_mac_link_multispeed_fiber(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg,
bool autoneg_wait_to_complete)
{
s32 status = 0;
ixgbe_link_speed link_speed = IXGBE_LINK_SPEED_UNKNOWN;
ixgbe_link_speed highest_link_speed = IXGBE_LINK_SPEED_UNKNOWN;
u32 speedcnt = 0;
u32 esdp_reg = IXGBE_READ_REG(hw, IXGBE_ESDP);
u32 i = 0;
bool link_up = false;
bool negotiation;
/* Mask off requested but non-supported speeds */
status = hw->mac.ops.get_link_capabilities(hw, &link_speed,
&negotiation);
if (status != 0)
return status;
speed &= link_speed;
/*
* Try each speed one by one, highest priority first. We do this in
* software because 10gb fiber doesn't support speed autonegotiation.
*/
if (speed & IXGBE_LINK_SPEED_10GB_FULL) {
speedcnt++;
highest_link_speed = IXGBE_LINK_SPEED_10GB_FULL;
/* If we already have link at this speed, just jump out */
status = hw->mac.ops.check_link(hw, &link_speed, &link_up,
false);
if (status != 0)
return status;
if ((link_speed == IXGBE_LINK_SPEED_10GB_FULL) && link_up)
goto out;
/* Set the module link speed */
esdp_reg |= (IXGBE_ESDP_SDP5_DIR | IXGBE_ESDP_SDP5);
IXGBE_WRITE_REG(hw, IXGBE_ESDP, esdp_reg);
IXGBE_WRITE_FLUSH(hw);
/* Allow module to change analog characteristics (1G->10G) */
msleep(40);
status = ixgbe_setup_mac_link_82599(hw,
IXGBE_LINK_SPEED_10GB_FULL,
autoneg,
autoneg_wait_to_complete);
if (status != 0)
return status;
/* Flap the tx laser if it has not already been done */
hw->mac.ops.flap_tx_laser(hw);
/*
* Wait for the controller to acquire link. Per IEEE 802.3ap,
* Section 73.10.2, we may have to wait up to 500ms if KR is
* attempted. 82599 uses the same timing for 10g SFI.
*/
for (i = 0; i < 5; i++) {
/* Wait for the link partner to also set speed */
msleep(100);
/* If we have link, just jump out */
status = hw->mac.ops.check_link(hw, &link_speed,
&link_up, false);
if (status != 0)
return status;
if (link_up)
goto out;
}
}
if (speed & IXGBE_LINK_SPEED_1GB_FULL) {
speedcnt++;
if (highest_link_speed == IXGBE_LINK_SPEED_UNKNOWN)
highest_link_speed = IXGBE_LINK_SPEED_1GB_FULL;
/* If we already have link at this speed, just jump out */
status = hw->mac.ops.check_link(hw, &link_speed, &link_up,
false);
if (status != 0)
return status;
if ((link_speed == IXGBE_LINK_SPEED_1GB_FULL) && link_up)
goto out;
/* Set the module link speed */
esdp_reg &= ~IXGBE_ESDP_SDP5;
esdp_reg |= IXGBE_ESDP_SDP5_DIR;
IXGBE_WRITE_REG(hw, IXGBE_ESDP, esdp_reg);
IXGBE_WRITE_FLUSH(hw);
/* Allow module to change analog characteristics (10G->1G) */
msleep(40);
status = ixgbe_setup_mac_link_82599(hw,
IXGBE_LINK_SPEED_1GB_FULL,
autoneg,
autoneg_wait_to_complete);
if (status != 0)
return status;
/* Flap the tx laser if it has not already been done */
hw->mac.ops.flap_tx_laser(hw);
/* Wait for the link partner to also set speed */
msleep(100);
/* If we have link, just jump out */
status = hw->mac.ops.check_link(hw, &link_speed, &link_up,
false);
if (status != 0)
return status;
if (link_up)
goto out;
}
/*
* We didn't get link. Configure back to the highest speed we tried,
* (if there was more than one). We call ourselves back with just the
* single highest speed that the user requested.
*/
if (speedcnt > 1)
status = ixgbe_setup_mac_link_multispeed_fiber(hw,
highest_link_speed,
autoneg,
autoneg_wait_to_complete);
out:
/* Set autoneg_advertised value based on input link speed */
hw->phy.autoneg_advertised = 0;
if (speed & IXGBE_LINK_SPEED_10GB_FULL)
hw->phy.autoneg_advertised |= IXGBE_LINK_SPEED_10GB_FULL;
if (speed & IXGBE_LINK_SPEED_1GB_FULL)
hw->phy.autoneg_advertised |= IXGBE_LINK_SPEED_1GB_FULL;
return status;
}
/**
* ixgbe_setup_mac_link_smartspeed - Set MAC link speed using SmartSpeed
* @hw: pointer to hardware structure
* @speed: new link speed
* @autoneg: true if autonegotiation enabled
* @autoneg_wait_to_complete: true when waiting for completion is needed
*
* Implements the Intel SmartSpeed algorithm.
**/
static s32 ixgbe_setup_mac_link_smartspeed(struct ixgbe_hw *hw,
ixgbe_link_speed speed, bool autoneg,
bool autoneg_wait_to_complete)
{
s32 status = 0;
ixgbe_link_speed link_speed = IXGBE_LINK_SPEED_UNKNOWN;
s32 i, j;
bool link_up = false;
u32 autoc_reg = IXGBE_READ_REG(hw, IXGBE_AUTOC);
/* Set autoneg_advertised value based on input link speed */
hw->phy.autoneg_advertised = 0;
if (speed & IXGBE_LINK_SPEED_10GB_FULL)
hw->phy.autoneg_advertised |= IXGBE_LINK_SPEED_10GB_FULL;
if (speed & IXGBE_LINK_SPEED_1GB_FULL)
hw->phy.autoneg_advertised |= IXGBE_LINK_SPEED_1GB_FULL;
if (speed & IXGBE_LINK_SPEED_100_FULL)
hw->phy.autoneg_advertised |= IXGBE_LINK_SPEED_100_FULL;
/*
* Implement Intel SmartSpeed algorithm. SmartSpeed will reduce the
* autoneg advertisement if link is unable to be established at the
* highest negotiated rate. This can sometimes happen due to integrity
* issues with the physical media connection.
*/
/* First, try to get link with full advertisement */
hw->phy.smart_speed_active = false;
for (j = 0; j < IXGBE_SMARTSPEED_MAX_RETRIES; j++) {
status = ixgbe_setup_mac_link_82599(hw, speed, autoneg,
autoneg_wait_to_complete);
if (status != 0)
goto out;
/*
* Wait for the controller to acquire link. Per IEEE 802.3ap,
* Section 73.10.2, we may have to wait up to 500ms if KR is
* attempted, or 200ms if KX/KX4/BX/BX4 is attempted, per
* Table 9 in the AN MAS.
*/
for (i = 0; i < 5; i++) {
mdelay(100);
/* If we have link, just jump out */
status = hw->mac.ops.check_link(hw, &link_speed,
&link_up, false);
if (status != 0)
goto out;
if (link_up)
goto out;
}
}
/*
* We didn't get link. If we advertised KR plus one of KX4/KX
* (or BX4/BX), then disable KR and try again.
*/
if (((autoc_reg & IXGBE_AUTOC_KR_SUPP) == 0) ||
((autoc_reg & IXGBE_AUTOC_KX4_KX_SUPP_MASK) == 0))
goto out;
/* Turn SmartSpeed on to disable KR support */
hw->phy.smart_speed_active = true;
status = ixgbe_setup_mac_link_82599(hw, speed, autoneg,
autoneg_wait_to_complete);
if (status != 0)
goto out;
/*
* Wait for the controller to acquire link. 600ms will allow for
* the AN link_fail_inhibit_timer as well for multiple cycles of
* parallel detect, both 10g and 1g. This allows for the maximum
* connect attempts as defined in the AN MAS table 73-7.
*/
for (i = 0; i < 6; i++) {
mdelay(100);
/* If we have link, just jump out */
status = hw->mac.ops.check_link(hw, &link_speed,
&link_up, false);
if (status != 0)
goto out;
if (link_up)
goto out;
}
/* We didn't get link. Turn SmartSpeed back off. */
hw->phy.smart_speed_active = false;
status = ixgbe_setup_mac_link_82599(hw, speed, autoneg,
autoneg_wait_to_complete);
out:
if (link_up && (link_speed == IXGBE_LINK_SPEED_1GB_FULL))
hw_dbg(hw, "Smartspeed has downgraded the link speed from "
"the maximum advertised\n");
return status;
}
/**
* ixgbe_setup_mac_link_82599 - Set MAC link speed
* @hw: pointer to hardware structure
* @speed: new link speed
* @autoneg: true if autonegotiation enabled
* @autoneg_wait_to_complete: true when waiting for completion is needed
*
* Set the link speed in the AUTOC register and restarts link.
**/
static s32 ixgbe_setup_mac_link_82599(struct ixgbe_hw *hw,
ixgbe_link_speed speed, bool autoneg,
bool autoneg_wait_to_complete)
{
s32 status = 0;
u32 autoc = IXGBE_READ_REG(hw, IXGBE_AUTOC);
u32 autoc2 = IXGBE_READ_REG(hw, IXGBE_AUTOC2);
u32 start_autoc = autoc;
u32 orig_autoc = 0;
u32 link_mode = autoc & IXGBE_AUTOC_LMS_MASK;
u32 pma_pmd_1g = autoc & IXGBE_AUTOC_1G_PMA_PMD_MASK;
u32 pma_pmd_10g_serial = autoc2 & IXGBE_AUTOC2_10G_SERIAL_PMA_PMD_MASK;
u32 links_reg;
u32 i;
ixgbe_link_speed link_capabilities = IXGBE_LINK_SPEED_UNKNOWN;
/* Check to see if speed passed in is supported. */
status = hw->mac.ops.get_link_capabilities(hw, &link_capabilities,
&autoneg);
if (status != 0)
goto out;
speed &= link_capabilities;
if (speed == IXGBE_LINK_SPEED_UNKNOWN) {
status = IXGBE_ERR_LINK_SETUP;
goto out;
}
/* Use stored value (EEPROM defaults) of AUTOC to find KR/KX4 support*/
if (hw->mac.orig_link_settings_stored)
orig_autoc = hw->mac.orig_autoc;
else
orig_autoc = autoc;
if (link_mode == IXGBE_AUTOC_LMS_KX4_KX_KR ||
link_mode == IXGBE_AUTOC_LMS_KX4_KX_KR_1G_AN ||
link_mode == IXGBE_AUTOC_LMS_KX4_KX_KR_SGMII) {
/* Set KX4/KX/KR support according to speed requested */
autoc &= ~(IXGBE_AUTOC_KX4_KX_SUPP_MASK | IXGBE_AUTOC_KR_SUPP);
if (speed & IXGBE_LINK_SPEED_10GB_FULL)
if (orig_autoc & IXGBE_AUTOC_KX4_SUPP)
autoc |= IXGBE_AUTOC_KX4_SUPP;
if ((orig_autoc & IXGBE_AUTOC_KR_SUPP) &&
(hw->phy.smart_speed_active == false))
autoc |= IXGBE_AUTOC_KR_SUPP;
if (speed & IXGBE_LINK_SPEED_1GB_FULL)
autoc |= IXGBE_AUTOC_KX_SUPP;
} else if ((pma_pmd_1g == IXGBE_AUTOC_1G_SFI) &&
(link_mode == IXGBE_AUTOC_LMS_1G_LINK_NO_AN ||
link_mode == IXGBE_AUTOC_LMS_1G_AN)) {
/* Switch from 1G SFI to 10G SFI if requested */
if ((speed == IXGBE_LINK_SPEED_10GB_FULL) &&
(pma_pmd_10g_serial == IXGBE_AUTOC2_10G_SFI)) {
autoc &= ~IXGBE_AUTOC_LMS_MASK;
autoc |= IXGBE_AUTOC_LMS_10G_SERIAL;
}
} else if ((pma_pmd_10g_serial == IXGBE_AUTOC2_10G_SFI) &&
(link_mode == IXGBE_AUTOC_LMS_10G_SERIAL)) {
/* Switch from 10G SFI to 1G SFI if requested */
if ((speed == IXGBE_LINK_SPEED_1GB_FULL) &&
(pma_pmd_1g == IXGBE_AUTOC_1G_SFI)) {
autoc &= ~IXGBE_AUTOC_LMS_MASK;
if (autoneg)
autoc |= IXGBE_AUTOC_LMS_1G_AN;
else
autoc |= IXGBE_AUTOC_LMS_1G_LINK_NO_AN;
}
}
if (autoc != start_autoc) {
/* Restart link */
autoc |= IXGBE_AUTOC_AN_RESTART;
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, autoc);
/* Only poll for autoneg to complete if specified to do so */
if (autoneg_wait_to_complete) {
if (link_mode == IXGBE_AUTOC_LMS_KX4_KX_KR ||
link_mode == IXGBE_AUTOC_LMS_KX4_KX_KR_1G_AN ||
link_mode == IXGBE_AUTOC_LMS_KX4_KX_KR_SGMII) {
links_reg = 0; /*Just in case Autoneg time=0*/
for (i = 0; i < IXGBE_AUTO_NEG_TIME; i++) {
links_reg =
IXGBE_READ_REG(hw, IXGBE_LINKS);
if (links_reg & IXGBE_LINKS_KX_AN_COMP)
break;
msleep(100);
}
if (!(links_reg & IXGBE_LINKS_KX_AN_COMP)) {
status =
IXGBE_ERR_AUTONEG_NOT_COMPLETE;
hw_dbg(hw, "Autoneg did not "
"complete.\n");
}
}
}
/* Add delay to filter out noises during initial link setup */
msleep(50);
}
out:
return status;
}
/**
* ixgbe_setup_copper_link_82599 - Set the PHY autoneg advertised field
* @hw: pointer to hardware structure
* @speed: new link speed
* @autoneg: true if autonegotiation enabled
* @autoneg_wait_to_complete: true if waiting is needed to complete
*
* Restarts link on PHY and MAC based on settings passed in.
**/
static s32 ixgbe_setup_copper_link_82599(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg,
bool autoneg_wait_to_complete)
{
s32 status;
/* Setup the PHY according to input speed */
status = hw->phy.ops.setup_link_speed(hw, speed, autoneg,
autoneg_wait_to_complete);
/* Set up MAC */
ixgbe_start_mac_link_82599(hw, autoneg_wait_to_complete);
return status;
}
/**
* ixgbe_reset_hw_82599 - Perform hardware reset
* @hw: pointer to hardware structure
*
* Resets the hardware by resetting the transmit and receive units, masks
* and clears all interrupts, perform a PHY reset, and perform a link (MAC)
* reset.
**/
static s32 ixgbe_reset_hw_82599(struct ixgbe_hw *hw)
{
ixgbe_link_speed link_speed;
s32 status;
u32 ctrl, i, autoc, autoc2;
bool link_up = false;
/* Call adapter stop to disable tx/rx and clear interrupts */
status = hw->mac.ops.stop_adapter(hw);
if (status != 0)
goto reset_hw_out;
/* flush pending Tx transactions */
ixgbe_clear_tx_pending(hw);
/* PHY ops must be identified and initialized prior to reset */
/* Identify PHY and related function pointers */
status = hw->phy.ops.init(hw);
if (status == IXGBE_ERR_SFP_NOT_SUPPORTED)
goto reset_hw_out;
/* Setup SFP module if there is one present. */
if (hw->phy.sfp_setup_needed) {
status = hw->mac.ops.setup_sfp(hw);
hw->phy.sfp_setup_needed = false;
}
if (status == IXGBE_ERR_SFP_NOT_SUPPORTED)
goto reset_hw_out;
/* Reset PHY */
if (hw->phy.reset_disable == false && hw->phy.ops.reset != NULL)
hw->phy.ops.reset(hw);
mac_reset_top:
/*
* Issue global reset to the MAC. Needs to be SW reset if link is up.
* If link reset is used when link is up, it might reset the PHY when
* mng is using it. If link is down or the flag to force full link
* reset is set, then perform link reset.
*/
ctrl = IXGBE_CTRL_LNK_RST;
if (!hw->force_full_reset) {
hw->mac.ops.check_link(hw, &link_speed, &link_up, false);
if (link_up)
ctrl = IXGBE_CTRL_RST;
}
ctrl |= IXGBE_READ_REG(hw, IXGBE_CTRL);
IXGBE_WRITE_REG(hw, IXGBE_CTRL, ctrl);
IXGBE_WRITE_FLUSH(hw);
/* Poll for reset bit to self-clear indicating reset is complete */
for (i = 0; i < 10; i++) {
udelay(1);
ctrl = IXGBE_READ_REG(hw, IXGBE_CTRL);
if (!(ctrl & IXGBE_CTRL_RST_MASK))
break;
}
if (ctrl & IXGBE_CTRL_RST_MASK) {
status = IXGBE_ERR_RESET_FAILED;
hw_dbg(hw, "Reset polling failed to complete.\n");
}
msleep(50);
/*
* Double resets are required for recovery from certain error
* conditions. Between resets, it is necessary to stall to allow time
* for any pending HW events to complete.
*/
if (hw->mac.flags & IXGBE_FLAGS_DOUBLE_RESET_REQUIRED) {
hw->mac.flags &= ~IXGBE_FLAGS_DOUBLE_RESET_REQUIRED;
goto mac_reset_top;
}
/*
* Store the original AUTOC/AUTOC2 values if they have not been
* stored off yet. Otherwise restore the stored original
* values since the reset operation sets back to defaults.
*/
autoc = IXGBE_READ_REG(hw, IXGBE_AUTOC);
autoc2 = IXGBE_READ_REG(hw, IXGBE_AUTOC2);
if (hw->mac.orig_link_settings_stored == false) {
hw->mac.orig_autoc = autoc;
hw->mac.orig_autoc2 = autoc2;
hw->mac.orig_link_settings_stored = true;
} else {
if (autoc != hw->mac.orig_autoc)
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, (hw->mac.orig_autoc |
IXGBE_AUTOC_AN_RESTART));
if ((autoc2 & IXGBE_AUTOC2_UPPER_MASK) !=
(hw->mac.orig_autoc2 & IXGBE_AUTOC2_UPPER_MASK)) {
autoc2 &= ~IXGBE_AUTOC2_UPPER_MASK;
autoc2 |= (hw->mac.orig_autoc2 &
IXGBE_AUTOC2_UPPER_MASK);
IXGBE_WRITE_REG(hw, IXGBE_AUTOC2, autoc2);
}
}
/* Store the permanent mac address */
hw->mac.ops.get_mac_addr(hw, hw->mac.perm_addr);
/*
* Store MAC address from RAR0, clear receive address registers, and
* clear the multicast table. Also reset num_rar_entries to 128,
* since we modify this value when programming the SAN MAC address.
*/
hw->mac.num_rar_entries = 128;
hw->mac.ops.init_rx_addrs(hw);
/* Store the permanent SAN mac address */
hw->mac.ops.get_san_mac_addr(hw, hw->mac.san_addr);
/* Add the SAN MAC address to the RAR only if it's a valid address */
if (ixgbe_validate_mac_addr(hw->mac.san_addr) == 0) {
hw->mac.ops.set_rar(hw, hw->mac.num_rar_entries - 1,
hw->mac.san_addr, 0, IXGBE_RAH_AV);
/* Reserve the last RAR for the SAN MAC address */
hw->mac.num_rar_entries--;
}
/* Store the alternative WWNN/WWPN prefix */
hw->mac.ops.get_wwn_prefix(hw, &hw->mac.wwnn_prefix,
&hw->mac.wwpn_prefix);
reset_hw_out:
return status;
}
/**
* ixgbe_reinit_fdir_tables_82599 - Reinitialize Flow Director tables.
* @hw: pointer to hardware structure
**/
s32 ixgbe_reinit_fdir_tables_82599(struct ixgbe_hw *hw)
{
int i;
u32 fdirctrl = IXGBE_READ_REG(hw, IXGBE_FDIRCTRL);
fdirctrl &= ~IXGBE_FDIRCTRL_INIT_DONE;
/*
* Before starting reinitialization process,
* FDIRCMD.CMD must be zero.
*/
for (i = 0; i < IXGBE_FDIRCMD_CMD_POLL; i++) {
if (!(IXGBE_READ_REG(hw, IXGBE_FDIRCMD) &
IXGBE_FDIRCMD_CMD_MASK))
break;
udelay(10);
}
if (i >= IXGBE_FDIRCMD_CMD_POLL) {
hw_dbg(hw, "Flow Director previous command isn't complete, "
"aborting table re-initialization.\n");
return IXGBE_ERR_FDIR_REINIT_FAILED;
}
IXGBE_WRITE_REG(hw, IXGBE_FDIRFREE, 0);
IXGBE_WRITE_FLUSH(hw);
/*
* 82599 adapters flow director init flow cannot be restarted,
* Workaround 82599 silicon errata by performing the following steps
* before re-writing the FDIRCTRL control register with the same value.
* - write 1 to bit 8 of FDIRCMD register &
* - write 0 to bit 8 of FDIRCMD register
*/
IXGBE_WRITE_REG(hw, IXGBE_FDIRCMD,
(IXGBE_READ_REG(hw, IXGBE_FDIRCMD) |
IXGBE_FDIRCMD_CLEARHT));
IXGBE_WRITE_FLUSH(hw);
IXGBE_WRITE_REG(hw, IXGBE_FDIRCMD,
(IXGBE_READ_REG(hw, IXGBE_FDIRCMD) &
~IXGBE_FDIRCMD_CLEARHT));
IXGBE_WRITE_FLUSH(hw);
/*
* Clear FDIR Hash register to clear any leftover hashes
* waiting to be programmed.
*/
IXGBE_WRITE_REG(hw, IXGBE_FDIRHASH, 0x00);
IXGBE_WRITE_FLUSH(hw);
IXGBE_WRITE_REG(hw, IXGBE_FDIRCTRL, fdirctrl);
IXGBE_WRITE_FLUSH(hw);
/* Poll init-done after we write FDIRCTRL register */
for (i = 0; i < IXGBE_FDIR_INIT_DONE_POLL; i++) {
if (IXGBE_READ_REG(hw, IXGBE_FDIRCTRL) &
IXGBE_FDIRCTRL_INIT_DONE)
break;
udelay(10);
}
if (i >= IXGBE_FDIR_INIT_DONE_POLL) {
hw_dbg(hw, "Flow Director Signature poll time exceeded!\n");
return IXGBE_ERR_FDIR_REINIT_FAILED;
}
/* Clear FDIR statistics registers (read to clear) */
IXGBE_READ_REG(hw, IXGBE_FDIRUSTAT);
IXGBE_READ_REG(hw, IXGBE_FDIRFSTAT);
IXGBE_READ_REG(hw, IXGBE_FDIRMATCH);
IXGBE_READ_REG(hw, IXGBE_FDIRMISS);
IXGBE_READ_REG(hw, IXGBE_FDIRLEN);
return 0;
}
/**
* ixgbe_fdir_enable_82599 - Initialize Flow Director control registers
* @hw: pointer to hardware structure
* @fdirctrl: value to write to flow director control register
**/
static void ixgbe_fdir_enable_82599(struct ixgbe_hw *hw, u32 fdirctrl)
{
int i;
/* Prime the keys for hashing */
IXGBE_WRITE_REG(hw, IXGBE_FDIRHKEY, IXGBE_ATR_BUCKET_HASH_KEY);
IXGBE_WRITE_REG(hw, IXGBE_FDIRSKEY, IXGBE_ATR_SIGNATURE_HASH_KEY);
/*
* Poll init-done after we write the register. Estimated times:
* 10G: PBALLOC = 11b, timing is 60us
* 1G: PBALLOC = 11b, timing is 600us
* 100M: PBALLOC = 11b, timing is 6ms
*
* Multiple these timings by 4 if under full Rx load
*
* So we'll poll for IXGBE_FDIR_INIT_DONE_POLL times, sleeping for
* 1 msec per poll time. If we're at line rate and drop to 100M, then
* this might not finish in our poll time, but we can live with that
* for now.
*/
IXGBE_WRITE_REG(hw, IXGBE_FDIRCTRL, fdirctrl);
IXGBE_WRITE_FLUSH(hw);
for (i = 0; i < IXGBE_FDIR_INIT_DONE_POLL; i++) {
if (IXGBE_READ_REG(hw, IXGBE_FDIRCTRL) &
IXGBE_FDIRCTRL_INIT_DONE)
break;
usleep_range(1000, 2000);
}
if (i >= IXGBE_FDIR_INIT_DONE_POLL)
hw_dbg(hw, "Flow Director poll time exceeded!\n");
}
/**
* ixgbe_init_fdir_signature_82599 - Initialize Flow Director signature filters
* @hw: pointer to hardware structure
* @fdirctrl: value to write to flow director control register, initially
* contains just the value of the Rx packet buffer allocation
**/
s32 ixgbe_init_fdir_signature_82599(struct ixgbe_hw *hw, u32 fdirctrl)
{
/*
* Continue setup of fdirctrl register bits:
* Move the flexible bytes to use the ethertype - shift 6 words
* Set the maximum length per hash bucket to 0xA filters
* Send interrupt when 64 filters are left
*/
fdirctrl |= (0x6 << IXGBE_FDIRCTRL_FLEX_SHIFT) |
(0xA << IXGBE_FDIRCTRL_MAX_LENGTH_SHIFT) |
(4 << IXGBE_FDIRCTRL_FULL_THRESH_SHIFT);
/* write hashes and fdirctrl register, poll for completion */
ixgbe_fdir_enable_82599(hw, fdirctrl);
return 0;
}
/**
* ixgbe_init_fdir_perfect_82599 - Initialize Flow Director perfect filters
* @hw: pointer to hardware structure
* @fdirctrl: value to write to flow director control register, initially
* contains just the value of the Rx packet buffer allocation
**/
s32 ixgbe_init_fdir_perfect_82599(struct ixgbe_hw *hw, u32 fdirctrl)
{
/*
* Continue setup of fdirctrl register bits:
* Turn perfect match filtering on
* Report hash in RSS field of Rx wb descriptor
* Initialize the drop queue
* Move the flexible bytes to use the ethertype - shift 6 words
* Set the maximum length per hash bucket to 0xA filters
* Send interrupt when 64 (0x4 * 16) filters are left
*/
fdirctrl |= IXGBE_FDIRCTRL_PERFECT_MATCH |
IXGBE_FDIRCTRL_REPORT_STATUS |
(IXGBE_FDIR_DROP_QUEUE << IXGBE_FDIRCTRL_DROP_Q_SHIFT) |
(0x6 << IXGBE_FDIRCTRL_FLEX_SHIFT) |
(0xA << IXGBE_FDIRCTRL_MAX_LENGTH_SHIFT) |
(4 << IXGBE_FDIRCTRL_FULL_THRESH_SHIFT);
/* write hashes and fdirctrl register, poll for completion */
ixgbe_fdir_enable_82599(hw, fdirctrl);
return 0;
}
/*
* These defines allow us to quickly generate all of the necessary instructions
* in the function below by simply calling out IXGBE_COMPUTE_SIG_HASH_ITERATION
* for values 0 through 15
*/
#define IXGBE_ATR_COMMON_HASH_KEY \
(IXGBE_ATR_BUCKET_HASH_KEY & IXGBE_ATR_SIGNATURE_HASH_KEY)
#define IXGBE_COMPUTE_SIG_HASH_ITERATION(_n) \
do { \
u32 n = (_n); \
if (IXGBE_ATR_COMMON_HASH_KEY & (0x01 << n)) \
common_hash ^= lo_hash_dword >> n; \
else if (IXGBE_ATR_BUCKET_HASH_KEY & (0x01 << n)) \
bucket_hash ^= lo_hash_dword >> n; \
else if (IXGBE_ATR_SIGNATURE_HASH_KEY & (0x01 << n)) \
sig_hash ^= lo_hash_dword << (16 - n); \
if (IXGBE_ATR_COMMON_HASH_KEY & (0x01 << (n + 16))) \
common_hash ^= hi_hash_dword >> n; \
else if (IXGBE_ATR_BUCKET_HASH_KEY & (0x01 << (n + 16))) \
bucket_hash ^= hi_hash_dword >> n; \
else if (IXGBE_ATR_SIGNATURE_HASH_KEY & (0x01 << (n + 16))) \
sig_hash ^= hi_hash_dword << (16 - n); \
} while (0);
/**
* ixgbe_atr_compute_sig_hash_82599 - Compute the signature hash
* @stream: input bitstream to compute the hash on
*
* This function is almost identical to the function above but contains
* several optomizations such as unwinding all of the loops, letting the
* compiler work out all of the conditional ifs since the keys are static
* defines, and computing two keys at once since the hashed dword stream
* will be the same for both keys.
**/
static u32 ixgbe_atr_compute_sig_hash_82599(union ixgbe_atr_hash_dword input,
union ixgbe_atr_hash_dword common)
{
u32 hi_hash_dword, lo_hash_dword, flow_vm_vlan;
u32 sig_hash = 0, bucket_hash = 0, common_hash = 0;
/* record the flow_vm_vlan bits as they are a key part to the hash */
flow_vm_vlan = ntohl(input.dword);
/* generate common hash dword */
hi_hash_dword = ntohl(common.dword);
/* low dword is word swapped version of common */
lo_hash_dword = (hi_hash_dword >> 16) | (hi_hash_dword << 16);
/* apply flow ID/VM pool/VLAN ID bits to hash words */
hi_hash_dword ^= flow_vm_vlan ^ (flow_vm_vlan >> 16);
/* Process bits 0 and 16 */
IXGBE_COMPUTE_SIG_HASH_ITERATION(0);
/*
* apply flow ID/VM pool/VLAN ID bits to lo hash dword, we had to
* delay this because bit 0 of the stream should not be processed
* so we do not add the vlan until after bit 0 was processed
*/
lo_hash_dword ^= flow_vm_vlan ^ (flow_vm_vlan << 16);
/* Process remaining 30 bit of the key */
IXGBE_COMPUTE_SIG_HASH_ITERATION(1);
IXGBE_COMPUTE_SIG_HASH_ITERATION(2);
IXGBE_COMPUTE_SIG_HASH_ITERATION(3);
IXGBE_COMPUTE_SIG_HASH_ITERATION(4);
IXGBE_COMPUTE_SIG_HASH_ITERATION(5);
IXGBE_COMPUTE_SIG_HASH_ITERATION(6);
IXGBE_COMPUTE_SIG_HASH_ITERATION(7);
IXGBE_COMPUTE_SIG_HASH_ITERATION(8);
IXGBE_COMPUTE_SIG_HASH_ITERATION(9);
IXGBE_COMPUTE_SIG_HASH_ITERATION(10);
IXGBE_COMPUTE_SIG_HASH_ITERATION(11);
IXGBE_COMPUTE_SIG_HASH_ITERATION(12);
IXGBE_COMPUTE_SIG_HASH_ITERATION(13);
IXGBE_COMPUTE_SIG_HASH_ITERATION(14);
IXGBE_COMPUTE_SIG_HASH_ITERATION(15);
/* combine common_hash result with signature and bucket hashes */
bucket_hash ^= common_hash;
bucket_hash &= IXGBE_ATR_HASH_MASK;
sig_hash ^= common_hash << 16;
sig_hash &= IXGBE_ATR_HASH_MASK << 16;
/* return completed signature hash */
return sig_hash ^ bucket_hash;
}
/**
* ixgbe_atr_add_signature_filter_82599 - Adds a signature hash filter
* @hw: pointer to hardware structure
* @input: unique input dword
* @common: compressed common input dword
* @queue: queue index to direct traffic to
**/
s32 ixgbe_fdir_add_signature_filter_82599(struct ixgbe_hw *hw,
union ixgbe_atr_hash_dword input,
union ixgbe_atr_hash_dword common,
u8 queue)
{
u64 fdirhashcmd;
u32 fdircmd;
/*
* Get the flow_type in order to program FDIRCMD properly
* lowest 2 bits are FDIRCMD.L4TYPE, third lowest bit is FDIRCMD.IPV6
*/
switch (input.formatted.flow_type) {
case IXGBE_ATR_FLOW_TYPE_TCPV4:
case IXGBE_ATR_FLOW_TYPE_UDPV4:
case IXGBE_ATR_FLOW_TYPE_SCTPV4:
case IXGBE_ATR_FLOW_TYPE_TCPV6:
case IXGBE_ATR_FLOW_TYPE_UDPV6:
case IXGBE_ATR_FLOW_TYPE_SCTPV6:
break;
default:
hw_dbg(hw, " Error on flow type input\n");
return IXGBE_ERR_CONFIG;
}
/* configure FDIRCMD register */
fdircmd = IXGBE_FDIRCMD_CMD_ADD_FLOW | IXGBE_FDIRCMD_FILTER_UPDATE |
IXGBE_FDIRCMD_LAST | IXGBE_FDIRCMD_QUEUE_EN;
fdircmd |= input.formatted.flow_type << IXGBE_FDIRCMD_FLOW_TYPE_SHIFT;
fdircmd |= (u32)queue << IXGBE_FDIRCMD_RX_QUEUE_SHIFT;
/*
* The lower 32-bits of fdirhashcmd is for FDIRHASH, the upper 32-bits
* is for FDIRCMD. Then do a 64-bit register write from FDIRHASH.
*/
fdirhashcmd = (u64)fdircmd << 32;
fdirhashcmd |= ixgbe_atr_compute_sig_hash_82599(input, common);
IXGBE_WRITE_REG64(hw, IXGBE_FDIRHASH, fdirhashcmd);
hw_dbg(hw, "Tx Queue=%x hash=%x\n", queue, (u32)fdirhashcmd);
return 0;
}
#define IXGBE_COMPUTE_BKT_HASH_ITERATION(_n) \
do { \
u32 n = (_n); \
if (IXGBE_ATR_BUCKET_HASH_KEY & (0x01 << n)) \
bucket_hash ^= lo_hash_dword >> n; \
if (IXGBE_ATR_BUCKET_HASH_KEY & (0x01 << (n + 16))) \
bucket_hash ^= hi_hash_dword >> n; \
} while (0);
/**
* ixgbe_atr_compute_perfect_hash_82599 - Compute the perfect filter hash
* @atr_input: input bitstream to compute the hash on
* @input_mask: mask for the input bitstream
*
* This function serves two main purposes. First it applys the input_mask
* to the atr_input resulting in a cleaned up atr_input data stream.
* Secondly it computes the hash and stores it in the bkt_hash field at
* the end of the input byte stream. This way it will be available for
* future use without needing to recompute the hash.
**/
void ixgbe_atr_compute_perfect_hash_82599(union ixgbe_atr_input *input,
union ixgbe_atr_input *input_mask)
{
u32 hi_hash_dword, lo_hash_dword, flow_vm_vlan;
u32 bucket_hash = 0;
/* Apply masks to input data */
input->dword_stream[0] &= input_mask->dword_stream[0];
input->dword_stream[1] &= input_mask->dword_stream[1];
input->dword_stream[2] &= input_mask->dword_stream[2];
input->dword_stream[3] &= input_mask->dword_stream[3];
input->dword_stream[4] &= input_mask->dword_stream[4];
input->dword_stream[5] &= input_mask->dword_stream[5];
input->dword_stream[6] &= input_mask->dword_stream[6];
input->dword_stream[7] &= input_mask->dword_stream[7];
input->dword_stream[8] &= input_mask->dword_stream[8];
input->dword_stream[9] &= input_mask->dword_stream[9];
input->dword_stream[10] &= input_mask->dword_stream[10];
/* record the flow_vm_vlan bits as they are a key part to the hash */
flow_vm_vlan = ntohl(input->dword_stream[0]);
/* generate common hash dword */
hi_hash_dword = ntohl(input->dword_stream[1] ^
input->dword_stream[2] ^
input->dword_stream[3] ^
input->dword_stream[4] ^
input->dword_stream[5] ^
input->dword_stream[6] ^
input->dword_stream[7] ^
input->dword_stream[8] ^
input->dword_stream[9] ^
input->dword_stream[10]);
/* low dword is word swapped version of common */
lo_hash_dword = (hi_hash_dword >> 16) | (hi_hash_dword << 16);
/* apply flow ID/VM pool/VLAN ID bits to hash words */
hi_hash_dword ^= flow_vm_vlan ^ (flow_vm_vlan >> 16);
/* Process bits 0 and 16 */
IXGBE_COMPUTE_BKT_HASH_ITERATION(0);
/*
* apply flow ID/VM pool/VLAN ID bits to lo hash dword, we had to
* delay this because bit 0 of the stream should not be processed
* so we do not add the vlan until after bit 0 was processed
*/
lo_hash_dword ^= flow_vm_vlan ^ (flow_vm_vlan << 16);
/* Process remaining 30 bit of the key */
IXGBE_COMPUTE_BKT_HASH_ITERATION(1);
IXGBE_COMPUTE_BKT_HASH_ITERATION(2);
IXGBE_COMPUTE_BKT_HASH_ITERATION(3);
IXGBE_COMPUTE_BKT_HASH_ITERATION(4);
IXGBE_COMPUTE_BKT_HASH_ITERATION(5);
IXGBE_COMPUTE_BKT_HASH_ITERATION(6);
IXGBE_COMPUTE_BKT_HASH_ITERATION(7);
IXGBE_COMPUTE_BKT_HASH_ITERATION(8);
IXGBE_COMPUTE_BKT_HASH_ITERATION(9);
IXGBE_COMPUTE_BKT_HASH_ITERATION(10);
IXGBE_COMPUTE_BKT_HASH_ITERATION(11);
IXGBE_COMPUTE_BKT_HASH_ITERATION(12);
IXGBE_COMPUTE_BKT_HASH_ITERATION(13);
IXGBE_COMPUTE_BKT_HASH_ITERATION(14);
IXGBE_COMPUTE_BKT_HASH_ITERATION(15);
/*
* Limit hash to 13 bits since max bucket count is 8K.
* Store result at the end of the input stream.
*/
input->formatted.bkt_hash = bucket_hash & 0x1FFF;
}
/**
* ixgbe_get_fdirtcpm_82599 - generate a tcp port from atr_input_masks
* @input_mask: mask to be bit swapped
*
* The source and destination port masks for flow director are bit swapped
* in that bit 15 effects bit 0, 14 effects 1, 13, 2 etc. In order to
* generate a correctly swapped value we need to bit swap the mask and that
* is what is accomplished by this function.
**/
static u32 ixgbe_get_fdirtcpm_82599(union ixgbe_atr_input *input_mask)
{
u32 mask = ntohs(input_mask->formatted.dst_port);
mask <<= IXGBE_FDIRTCPM_DPORTM_SHIFT;
mask |= ntohs(input_mask->formatted.src_port);
mask = ((mask & 0x55555555) << 1) | ((mask & 0xAAAAAAAA) >> 1);
mask = ((mask & 0x33333333) << 2) | ((mask & 0xCCCCCCCC) >> 2);
mask = ((mask & 0x0F0F0F0F) << 4) | ((mask & 0xF0F0F0F0) >> 4);
return ((mask & 0x00FF00FF) << 8) | ((mask & 0xFF00FF00) >> 8);
}
/*
* These two macros are meant to address the fact that we have registers
* that are either all or in part big-endian. As a result on big-endian
* systems we will end up byte swapping the value to little-endian before
* it is byte swapped again and written to the hardware in the original
* big-endian format.
*/
#define IXGBE_STORE_AS_BE32(_value) \
(((u32)(_value) >> 24) | (((u32)(_value) & 0x00FF0000) >> 8) | \
(((u32)(_value) & 0x0000FF00) << 8) | ((u32)(_value) << 24))
#define IXGBE_WRITE_REG_BE32(a, reg, value) \
IXGBE_WRITE_REG((a), (reg), IXGBE_STORE_AS_BE32(ntohl(value)))
#define IXGBE_STORE_AS_BE16(_value) \
ntohs(((u16)(_value) >> 8) | ((u16)(_value) << 8))
s32 ixgbe_fdir_set_input_mask_82599(struct ixgbe_hw *hw,
union ixgbe_atr_input *input_mask)
{
/* mask IPv6 since it is currently not supported */
u32 fdirm = IXGBE_FDIRM_DIPv6;
u32 fdirtcpm;
/*
* Program the relevant mask registers. If src/dst_port or src/dst_addr
* are zero, then assume a full mask for that field. Also assume that
* a VLAN of 0 is unspecified, so mask that out as well. L4type
* cannot be masked out in this implementation.
*
* This also assumes IPv4 only. IPv6 masking isn't supported at this
* point in time.
*/
/* verify bucket hash is cleared on hash generation */
if (input_mask->formatted.bkt_hash)
hw_dbg(hw, " bucket hash should always be 0 in mask\n");
/* Program FDIRM and verify partial masks */
switch (input_mask->formatted.vm_pool & 0x7F) {
case 0x0:
fdirm |= IXGBE_FDIRM_POOL;
case 0x7F:
break;
default:
hw_dbg(hw, " Error on vm pool mask\n");
return IXGBE_ERR_CONFIG;
}
switch (input_mask->formatted.flow_type & IXGBE_ATR_L4TYPE_MASK) {
case 0x0:
fdirm |= IXGBE_FDIRM_L4P;
if (input_mask->formatted.dst_port ||
input_mask->formatted.src_port) {
hw_dbg(hw, " Error on src/dst port mask\n");
return IXGBE_ERR_CONFIG;
}
case IXGBE_ATR_L4TYPE_MASK:
break;
default:
hw_dbg(hw, " Error on flow type mask\n");
return IXGBE_ERR_CONFIG;
}
switch (ntohs(input_mask->formatted.vlan_id) & 0xEFFF) {
case 0x0000:
/* mask VLAN ID, fall through to mask VLAN priority */
fdirm |= IXGBE_FDIRM_VLANID;
case 0x0FFF:
/* mask VLAN priority */
fdirm |= IXGBE_FDIRM_VLANP;
break;
case 0xE000:
/* mask VLAN ID only, fall through */
fdirm |= IXGBE_FDIRM_VLANID;
case 0xEFFF:
/* no VLAN fields masked */
break;
default:
hw_dbg(hw, " Error on VLAN mask\n");
return IXGBE_ERR_CONFIG;
}
switch (input_mask->formatted.flex_bytes & 0xFFFF) {
case 0x0000:
/* Mask Flex Bytes, fall through */
fdirm |= IXGBE_FDIRM_FLEX;
case 0xFFFF:
break;
default:
hw_dbg(hw, " Error on flexible byte mask\n");
return IXGBE_ERR_CONFIG;
}
/* Now mask VM pool and destination IPv6 - bits 5 and 2 */
IXGBE_WRITE_REG(hw, IXGBE_FDIRM, fdirm);
/* store the TCP/UDP port masks, bit reversed from port layout */
fdirtcpm = ixgbe_get_fdirtcpm_82599(input_mask);
/* write both the same so that UDP and TCP use the same mask */
IXGBE_WRITE_REG(hw, IXGBE_FDIRTCPM, ~fdirtcpm);
IXGBE_WRITE_REG(hw, IXGBE_FDIRUDPM, ~fdirtcpm);
/* store source and destination IP masks (big-enian) */
IXGBE_WRITE_REG_BE32(hw, IXGBE_FDIRSIP4M,
~input_mask->formatted.src_ip[0]);
IXGBE_WRITE_REG_BE32(hw, IXGBE_FDIRDIP4M,
~input_mask->formatted.dst_ip[0]);
return 0;
}
s32 ixgbe_fdir_write_perfect_filter_82599(struct ixgbe_hw *hw,
union ixgbe_atr_input *input,
u16 soft_id, u8 queue)
{
u32 fdirport, fdirvlan, fdirhash, fdircmd;
/* currently IPv6 is not supported, must be programmed with 0 */
IXGBE_WRITE_REG_BE32(hw, IXGBE_FDIRSIPv6(0),
input->formatted.src_ip[0]);
IXGBE_WRITE_REG_BE32(hw, IXGBE_FDIRSIPv6(1),
input->formatted.src_ip[1]);
IXGBE_WRITE_REG_BE32(hw, IXGBE_FDIRSIPv6(2),
input->formatted.src_ip[2]);
/* record the source address (big-endian) */
IXGBE_WRITE_REG_BE32(hw, IXGBE_FDIRIPSA, input->formatted.src_ip[0]);
/* record the first 32 bits of the destination address (big-endian) */
IXGBE_WRITE_REG_BE32(hw, IXGBE_FDIRIPDA, input->formatted.dst_ip[0]);
/* record source and destination port (little-endian)*/
fdirport = ntohs(input->formatted.dst_port);
fdirport <<= IXGBE_FDIRPORT_DESTINATION_SHIFT;
fdirport |= ntohs(input->formatted.src_port);
IXGBE_WRITE_REG(hw, IXGBE_FDIRPORT, fdirport);
/* record vlan (little-endian) and flex_bytes(big-endian) */
fdirvlan = IXGBE_STORE_AS_BE16(input->formatted.flex_bytes);
fdirvlan <<= IXGBE_FDIRVLAN_FLEX_SHIFT;
fdirvlan |= ntohs(input->formatted.vlan_id);
IXGBE_WRITE_REG(hw, IXGBE_FDIRVLAN, fdirvlan);
/* configure FDIRHASH register */
fdirhash = input->formatted.bkt_hash;
fdirhash |= soft_id << IXGBE_FDIRHASH_SIG_SW_INDEX_SHIFT;
IXGBE_WRITE_REG(hw, IXGBE_FDIRHASH, fdirhash);
/*
* flush all previous writes to make certain registers are
* programmed prior to issuing the command
*/
IXGBE_WRITE_FLUSH(hw);
/* configure FDIRCMD register */
fdircmd = IXGBE_FDIRCMD_CMD_ADD_FLOW | IXGBE_FDIRCMD_FILTER_UPDATE |
IXGBE_FDIRCMD_LAST | IXGBE_FDIRCMD_QUEUE_EN;
if (queue == IXGBE_FDIR_DROP_QUEUE)
fdircmd |= IXGBE_FDIRCMD_DROP;
fdircmd |= input->formatted.flow_type << IXGBE_FDIRCMD_FLOW_TYPE_SHIFT;
fdircmd |= (u32)queue << IXGBE_FDIRCMD_RX_QUEUE_SHIFT;
fdircmd |= (u32)input->formatted.vm_pool << IXGBE_FDIRCMD_VT_POOL_SHIFT;
IXGBE_WRITE_REG(hw, IXGBE_FDIRCMD, fdircmd);
return 0;
}
s32 ixgbe_fdir_erase_perfect_filter_82599(struct ixgbe_hw *hw,
union ixgbe_atr_input *input,
u16 soft_id)
{
u32 fdirhash;
u32 fdircmd = 0;
u32 retry_count;
s32 err = 0;
/* configure FDIRHASH register */
fdirhash = input->formatted.bkt_hash;
fdirhash |= soft_id << IXGBE_FDIRHASH_SIG_SW_INDEX_SHIFT;
IXGBE_WRITE_REG(hw, IXGBE_FDIRHASH, fdirhash);
/* flush hash to HW */
IXGBE_WRITE_FLUSH(hw);
/* Query if filter is present */
IXGBE_WRITE_REG(hw, IXGBE_FDIRCMD, IXGBE_FDIRCMD_CMD_QUERY_REM_FILT);
for (retry_count = 10; retry_count; retry_count--) {
/* allow 10us for query to process */
udelay(10);
/* verify query completed successfully */
fdircmd = IXGBE_READ_REG(hw, IXGBE_FDIRCMD);
if (!(fdircmd & IXGBE_FDIRCMD_CMD_MASK))
break;
}
if (!retry_count)
err = IXGBE_ERR_FDIR_REINIT_FAILED;
/* if filter exists in hardware then remove it */
if (fdircmd & IXGBE_FDIRCMD_FILTER_VALID) {
IXGBE_WRITE_REG(hw, IXGBE_FDIRHASH, fdirhash);
IXGBE_WRITE_FLUSH(hw);
IXGBE_WRITE_REG(hw, IXGBE_FDIRCMD,
IXGBE_FDIRCMD_CMD_REMOVE_FLOW);
}
return err;
}
/**
* ixgbe_read_analog_reg8_82599 - Reads 8 bit Omer analog register
* @hw: pointer to hardware structure
* @reg: analog register to read
* @val: read value
*
* Performs read operation to Omer analog register specified.
**/
static s32 ixgbe_read_analog_reg8_82599(struct ixgbe_hw *hw, u32 reg, u8 *val)
{
u32 core_ctl;
IXGBE_WRITE_REG(hw, IXGBE_CORECTL, IXGBE_CORECTL_WRITE_CMD |
(reg << 8));
IXGBE_WRITE_FLUSH(hw);
udelay(10);
core_ctl = IXGBE_READ_REG(hw, IXGBE_CORECTL);
*val = (u8)core_ctl;
return 0;
}
/**
* ixgbe_write_analog_reg8_82599 - Writes 8 bit Omer analog register
* @hw: pointer to hardware structure
* @reg: atlas register to write
* @val: value to write
*
* Performs write operation to Omer analog register specified.
**/
static s32 ixgbe_write_analog_reg8_82599(struct ixgbe_hw *hw, u32 reg, u8 val)
{
u32 core_ctl;
core_ctl = (reg << 8) | val;
IXGBE_WRITE_REG(hw, IXGBE_CORECTL, core_ctl);
IXGBE_WRITE_FLUSH(hw);
udelay(10);
return 0;
}
/**
* ixgbe_start_hw_82599 - Prepare hardware for Tx/Rx
* @hw: pointer to hardware structure
*
* Starts the hardware using the generic start_hw function
* and the generation start_hw function.
* Then performs revision-specific operations, if any.
**/
static s32 ixgbe_start_hw_82599(struct ixgbe_hw *hw)
{
s32 ret_val = 0;
ret_val = ixgbe_start_hw_generic(hw);
if (ret_val != 0)
goto out;
ret_val = ixgbe_start_hw_gen2(hw);
if (ret_val != 0)
goto out;
/* We need to run link autotry after the driver loads */
hw->mac.autotry_restart = true;
hw->mac.rx_pb_size = IXGBE_82599_RX_PB_SIZE;
if (ret_val == 0)
ret_val = ixgbe_verify_fw_version_82599(hw);
out:
return ret_val;
}
/**
* ixgbe_identify_phy_82599 - Get physical layer module
* @hw: pointer to hardware structure
*
* Determines the physical layer module found on the current adapter.
* If PHY already detected, maintains current PHY type in hw struct,
* otherwise executes the PHY detection routine.
**/
static s32 ixgbe_identify_phy_82599(struct ixgbe_hw *hw)
{
s32 status = IXGBE_ERR_PHY_ADDR_INVALID;
/* Detect PHY if not unknown - returns success if already detected. */
status = ixgbe_identify_phy_generic(hw);
if (status != 0) {
/* 82599 10GBASE-T requires an external PHY */
if (hw->mac.ops.get_media_type(hw) == ixgbe_media_type_copper)
goto out;
else
status = ixgbe_identify_sfp_module_generic(hw);
}
/* Set PHY type none if no PHY detected */
if (hw->phy.type == ixgbe_phy_unknown) {
hw->phy.type = ixgbe_phy_none;
status = 0;
}
/* Return error if SFP module has been detected but is not supported */
if (hw->phy.type == ixgbe_phy_sfp_unsupported)
status = IXGBE_ERR_SFP_NOT_SUPPORTED;
out:
return status;
}
/**
* ixgbe_get_supported_physical_layer_82599 - Returns physical layer type
* @hw: pointer to hardware structure
*
* Determines physical layer capabilities of the current configuration.
**/
static u32 ixgbe_get_supported_physical_layer_82599(struct ixgbe_hw *hw)
{
u32 physical_layer = IXGBE_PHYSICAL_LAYER_UNKNOWN;
u32 autoc = IXGBE_READ_REG(hw, IXGBE_AUTOC);
u32 autoc2 = IXGBE_READ_REG(hw, IXGBE_AUTOC2);
u32 pma_pmd_10g_serial = autoc2 & IXGBE_AUTOC2_10G_SERIAL_PMA_PMD_MASK;
u32 pma_pmd_10g_parallel = autoc & IXGBE_AUTOC_10G_PMA_PMD_MASK;
u32 pma_pmd_1g = autoc & IXGBE_AUTOC_1G_PMA_PMD_MASK;
u16 ext_ability = 0;
u8 comp_codes_10g = 0;
u8 comp_codes_1g = 0;
hw->phy.ops.identify(hw);
switch (hw->phy.type) {
case ixgbe_phy_tn:
case ixgbe_phy_cu_unknown:
hw->phy.ops.read_reg(hw, MDIO_PMA_EXTABLE, MDIO_MMD_PMAPMD,
&ext_ability);
if (ext_ability & MDIO_PMA_EXTABLE_10GBT)
physical_layer |= IXGBE_PHYSICAL_LAYER_10GBASE_T;
if (ext_ability & MDIO_PMA_EXTABLE_1000BT)
physical_layer |= IXGBE_PHYSICAL_LAYER_1000BASE_T;
if (ext_ability & MDIO_PMA_EXTABLE_100BTX)
physical_layer |= IXGBE_PHYSICAL_LAYER_100BASE_TX;
goto out;
default:
break;
}
switch (autoc & IXGBE_AUTOC_LMS_MASK) {
case IXGBE_AUTOC_LMS_1G_AN:
case IXGBE_AUTOC_LMS_1G_LINK_NO_AN:
if (pma_pmd_1g == IXGBE_AUTOC_1G_KX_BX) {
physical_layer = IXGBE_PHYSICAL_LAYER_1000BASE_KX |
IXGBE_PHYSICAL_LAYER_1000BASE_BX;
goto out;
} else
/* SFI mode so read SFP module */
goto sfp_check;
break;
case IXGBE_AUTOC_LMS_10G_LINK_NO_AN:
if (pma_pmd_10g_parallel == IXGBE_AUTOC_10G_CX4)
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_CX4;
else if (pma_pmd_10g_parallel == IXGBE_AUTOC_10G_KX4)
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_KX4;
else if (pma_pmd_10g_parallel == IXGBE_AUTOC_10G_XAUI)
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_XAUI;
goto out;
break;
case IXGBE_AUTOC_LMS_10G_SERIAL:
if (pma_pmd_10g_serial == IXGBE_AUTOC2_10G_KR) {
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_KR;
goto out;
} else if (pma_pmd_10g_serial == IXGBE_AUTOC2_10G_SFI)
goto sfp_check;
break;
case IXGBE_AUTOC_LMS_KX4_KX_KR:
case IXGBE_AUTOC_LMS_KX4_KX_KR_1G_AN:
if (autoc & IXGBE_AUTOC_KX_SUPP)
physical_layer |= IXGBE_PHYSICAL_LAYER_1000BASE_KX;
if (autoc & IXGBE_AUTOC_KX4_SUPP)
physical_layer |= IXGBE_PHYSICAL_LAYER_10GBASE_KX4;
if (autoc & IXGBE_AUTOC_KR_SUPP)
physical_layer |= IXGBE_PHYSICAL_LAYER_10GBASE_KR;
goto out;
break;
default:
goto out;
break;
}
sfp_check:
/* SFP check must be done last since DA modules are sometimes used to
* test KR mode - we need to id KR mode correctly before SFP module.
* Call identify_sfp because the pluggable module may have changed */
hw->phy.ops.identify_sfp(hw);
if (hw->phy.sfp_type == ixgbe_sfp_type_not_present)
goto out;
switch (hw->phy.type) {
case ixgbe_phy_sfp_passive_tyco:
case ixgbe_phy_sfp_passive_unknown:
physical_layer = IXGBE_PHYSICAL_LAYER_SFP_PLUS_CU;
break;
case ixgbe_phy_sfp_ftl_active:
case ixgbe_phy_sfp_active_unknown:
physical_layer = IXGBE_PHYSICAL_LAYER_SFP_ACTIVE_DA;
break;
case ixgbe_phy_sfp_avago:
case ixgbe_phy_sfp_ftl:
case ixgbe_phy_sfp_intel:
case ixgbe_phy_sfp_unknown:
hw->phy.ops.read_i2c_eeprom(hw,
IXGBE_SFF_1GBE_COMP_CODES, &comp_codes_1g);
hw->phy.ops.read_i2c_eeprom(hw,
IXGBE_SFF_10GBE_COMP_CODES, &comp_codes_10g);
if (comp_codes_10g & IXGBE_SFF_10GBASESR_CAPABLE)
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_SR;
else if (comp_codes_10g & IXGBE_SFF_10GBASELR_CAPABLE)
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_LR;
else if (comp_codes_1g & IXGBE_SFF_1GBASET_CAPABLE)
physical_layer = IXGBE_PHYSICAL_LAYER_1000BASE_T;
break;
default:
break;
}
out:
return physical_layer;
}
/**
* ixgbe_enable_rx_dma_82599 - Enable the Rx DMA unit on 82599
* @hw: pointer to hardware structure
* @regval: register value to write to RXCTRL
*
* Enables the Rx DMA unit for 82599
**/
static s32 ixgbe_enable_rx_dma_82599(struct ixgbe_hw *hw, u32 regval)
{
/*
* Workaround for 82599 silicon errata when enabling the Rx datapath.
* If traffic is incoming before we enable the Rx unit, it could hang
* the Rx DMA unit. Therefore, make sure the security engine is
* completely disabled prior to enabling the Rx unit.
*/
hw->mac.ops.disable_rx_buff(hw);
IXGBE_WRITE_REG(hw, IXGBE_RXCTRL, regval);
hw->mac.ops.enable_rx_buff(hw);
return 0;
}
/**
* ixgbe_verify_fw_version_82599 - verify fw version for 82599
* @hw: pointer to hardware structure
*
* Verifies that installed the firmware version is 0.6 or higher
* for SFI devices. All 82599 SFI devices should have version 0.6 or higher.
*
* Returns IXGBE_ERR_EEPROM_VERSION if the FW is not present or
* if the FW version is not supported.
**/
static s32 ixgbe_verify_fw_version_82599(struct ixgbe_hw *hw)
{
s32 status = IXGBE_ERR_EEPROM_VERSION;
u16 fw_offset, fw_ptp_cfg_offset;
u16 fw_version = 0;
/* firmware check is only necessary for SFI devices */
if (hw->phy.media_type != ixgbe_media_type_fiber) {
status = 0;
goto fw_version_out;
}
/* get the offset to the Firmware Module block */
hw->eeprom.ops.read(hw, IXGBE_FW_PTR, &fw_offset);
if ((fw_offset == 0) || (fw_offset == 0xFFFF))
goto fw_version_out;
/* get the offset to the Pass Through Patch Configuration block */
hw->eeprom.ops.read(hw, (fw_offset +
IXGBE_FW_PASSTHROUGH_PATCH_CONFIG_PTR),
&fw_ptp_cfg_offset);
if ((fw_ptp_cfg_offset == 0) || (fw_ptp_cfg_offset == 0xFFFF))
goto fw_version_out;
/* get the firmware version */
hw->eeprom.ops.read(hw, (fw_ptp_cfg_offset +
IXGBE_FW_PATCH_VERSION_4),
&fw_version);
if (fw_version > 0x5)
status = 0;
fw_version_out:
return status;
}
/**
* ixgbe_verify_lesm_fw_enabled_82599 - Checks LESM FW module state.
* @hw: pointer to hardware structure
*
* Returns true if the LESM FW module is present and enabled. Otherwise
* returns false. Smart Speed must be disabled if LESM FW module is enabled.
**/
static bool ixgbe_verify_lesm_fw_enabled_82599(struct ixgbe_hw *hw)
{
bool lesm_enabled = false;
u16 fw_offset, fw_lesm_param_offset, fw_lesm_state;
s32 status;
/* get the offset to the Firmware Module block */
status = hw->eeprom.ops.read(hw, IXGBE_FW_PTR, &fw_offset);
if ((status != 0) ||
(fw_offset == 0) || (fw_offset == 0xFFFF))
goto out;
/* get the offset to the LESM Parameters block */
status = hw->eeprom.ops.read(hw, (fw_offset +
IXGBE_FW_LESM_PARAMETERS_PTR),
&fw_lesm_param_offset);
if ((status != 0) ||
(fw_lesm_param_offset == 0) || (fw_lesm_param_offset == 0xFFFF))
goto out;
/* get the lesm state word */
status = hw->eeprom.ops.read(hw, (fw_lesm_param_offset +
IXGBE_FW_LESM_STATE_1),
&fw_lesm_state);
if ((status == 0) &&
(fw_lesm_state & IXGBE_FW_LESM_STATE_ENABLED))
lesm_enabled = true;
out:
return lesm_enabled;
}
/**
* ixgbe_read_eeprom_buffer_82599 - Read EEPROM word(s) using
* fastest available method
*
* @hw: pointer to hardware structure
* @offset: offset of word in EEPROM to read
* @words: number of words
* @data: word(s) read from the EEPROM
*
* Retrieves 16 bit word(s) read from EEPROM
**/
static s32 ixgbe_read_eeprom_buffer_82599(struct ixgbe_hw *hw, u16 offset,
u16 words, u16 *data)
{
struct ixgbe_eeprom_info *eeprom = &hw->eeprom;
s32 ret_val = IXGBE_ERR_CONFIG;
/*
* If EEPROM is detected and can be addressed using 14 bits,
* use EERD otherwise use bit bang
*/
if ((eeprom->type == ixgbe_eeprom_spi) &&
(offset + (words - 1) <= IXGBE_EERD_MAX_ADDR))
ret_val = ixgbe_read_eerd_buffer_generic(hw, offset, words,
data);
else
ret_val = ixgbe_read_eeprom_buffer_bit_bang_generic(hw, offset,
words,
data);
return ret_val;
}
/**
* ixgbe_read_eeprom_82599 - Read EEPROM word using
* fastest available method
*
* @hw: pointer to hardware structure
* @offset: offset of word in the EEPROM to read
* @data: word read from the EEPROM
*
* Reads a 16 bit word from the EEPROM
**/
static s32 ixgbe_read_eeprom_82599(struct ixgbe_hw *hw,
u16 offset, u16 *data)
{
struct ixgbe_eeprom_info *eeprom = &hw->eeprom;
s32 ret_val = IXGBE_ERR_CONFIG;
/*
* If EEPROM is detected and can be addressed using 14 bits,
* use EERD otherwise use bit bang
*/
if ((eeprom->type == ixgbe_eeprom_spi) &&
(offset <= IXGBE_EERD_MAX_ADDR))
ret_val = ixgbe_read_eerd_generic(hw, offset, data);
else
ret_val = ixgbe_read_eeprom_bit_bang_generic(hw, offset, data);
return ret_val;
}
static struct ixgbe_mac_operations mac_ops_82599 = {
.init_hw = &ixgbe_init_hw_generic,
.reset_hw = &ixgbe_reset_hw_82599,
.start_hw = &ixgbe_start_hw_82599,
.clear_hw_cntrs = &ixgbe_clear_hw_cntrs_generic,
.get_media_type = &ixgbe_get_media_type_82599,
.get_supported_physical_layer = &ixgbe_get_supported_physical_layer_82599,
.enable_rx_dma = &ixgbe_enable_rx_dma_82599,
.disable_rx_buff = &ixgbe_disable_rx_buff_generic,
.enable_rx_buff = &ixgbe_enable_rx_buff_generic,
.get_mac_addr = &ixgbe_get_mac_addr_generic,
.get_san_mac_addr = &ixgbe_get_san_mac_addr_generic,
.get_device_caps = &ixgbe_get_device_caps_generic,
.get_wwn_prefix = &ixgbe_get_wwn_prefix_generic,
.stop_adapter = &ixgbe_stop_adapter_generic,
.get_bus_info = &ixgbe_get_bus_info_generic,
.set_lan_id = &ixgbe_set_lan_id_multi_port_pcie,
.read_analog_reg8 = &ixgbe_read_analog_reg8_82599,
.write_analog_reg8 = &ixgbe_write_analog_reg8_82599,
.setup_link = &ixgbe_setup_mac_link_82599,
.set_rxpba = &ixgbe_set_rxpba_generic,
.check_link = &ixgbe_check_mac_link_generic,
.get_link_capabilities = &ixgbe_get_link_capabilities_82599,
.led_on = &ixgbe_led_on_generic,
.led_off = &ixgbe_led_off_generic,
.blink_led_start = &ixgbe_blink_led_start_generic,
.blink_led_stop = &ixgbe_blink_led_stop_generic,
.set_rar = &ixgbe_set_rar_generic,
.clear_rar = &ixgbe_clear_rar_generic,
.set_vmdq = &ixgbe_set_vmdq_generic,
.clear_vmdq = &ixgbe_clear_vmdq_generic,
.init_rx_addrs = &ixgbe_init_rx_addrs_generic,
.update_mc_addr_list = &ixgbe_update_mc_addr_list_generic,
.enable_mc = &ixgbe_enable_mc_generic,
.disable_mc = &ixgbe_disable_mc_generic,
.clear_vfta = &ixgbe_clear_vfta_generic,
.set_vfta = &ixgbe_set_vfta_generic,
.fc_enable = &ixgbe_fc_enable_generic,
.set_fw_drv_ver = &ixgbe_set_fw_drv_ver_generic,
.init_uta_tables = &ixgbe_init_uta_tables_generic,
.setup_sfp = &ixgbe_setup_sfp_modules_82599,
.set_mac_anti_spoofing = &ixgbe_set_mac_anti_spoofing,
.set_vlan_anti_spoofing = &ixgbe_set_vlan_anti_spoofing,
.acquire_swfw_sync = &ixgbe_acquire_swfw_sync,
.release_swfw_sync = &ixgbe_release_swfw_sync,
};
static struct ixgbe_eeprom_operations eeprom_ops_82599 = {
.init_params = &ixgbe_init_eeprom_params_generic,
.read = &ixgbe_read_eeprom_82599,
.read_buffer = &ixgbe_read_eeprom_buffer_82599,
.write = &ixgbe_write_eeprom_generic,
.write_buffer = &ixgbe_write_eeprom_buffer_bit_bang_generic,
.calc_checksum = &ixgbe_calc_eeprom_checksum_generic,
.validate_checksum = &ixgbe_validate_eeprom_checksum_generic,
.update_checksum = &ixgbe_update_eeprom_checksum_generic,
};
static struct ixgbe_phy_operations phy_ops_82599 = {
.identify = &ixgbe_identify_phy_82599,
.identify_sfp = &ixgbe_identify_sfp_module_generic,
.init = &ixgbe_init_phy_ops_82599,
.reset = &ixgbe_reset_phy_generic,
.read_reg = &ixgbe_read_phy_reg_generic,
.write_reg = &ixgbe_write_phy_reg_generic,
.setup_link = &ixgbe_setup_phy_link_generic,
.setup_link_speed = &ixgbe_setup_phy_link_speed_generic,
.read_i2c_byte = &ixgbe_read_i2c_byte_generic,
.write_i2c_byte = &ixgbe_write_i2c_byte_generic,
.read_i2c_eeprom = &ixgbe_read_i2c_eeprom_generic,
.write_i2c_eeprom = &ixgbe_write_i2c_eeprom_generic,
.check_overtemp = &ixgbe_tn_check_overtemp,
};
struct ixgbe_info ixgbe_82599_info = {
.mac = ixgbe_mac_82599EB,
.get_invariants = &ixgbe_get_invariants_82599,
.mac_ops = &mac_ops_82599,
.eeprom_ops = &eeprom_ops_82599,
.phy_ops = &phy_ops_82599,
.mbx_ops = &mbx_ops_generic,
};
| gpl-2.0 |
talnoah/Lemur_kernel-DNA | drivers/net/wireless/p54/main.c | 4809 | 21033 | /*
* mac80211 glue code for mac80211 Prism54 drivers
*
* Copyright (c) 2006, Michael Wu <flamingice@sourmilk.net>
* Copyright (c) 2007-2009, Christian Lamparter <chunkeey@web.de>
* Copyright 2008, Johannes Berg <johannes@sipsolutions.net>
*
* Based on:
* - the islsm (softmac prism54) driver, which is:
* Copyright 2004-2006 Jean-Baptiste Note <jbnote@gmail.com>, et al.
* - stlc45xx driver
* Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/firmware.h>
#include <linux/etherdevice.h>
#include <linux/module.h>
#include <net/mac80211.h>
#include "p54.h"
#include "lmac.h"
static bool modparam_nohwcrypt;
module_param_named(nohwcrypt, modparam_nohwcrypt, bool, S_IRUGO);
MODULE_PARM_DESC(nohwcrypt, "Disable hardware encryption.");
MODULE_AUTHOR("Michael Wu <flamingice@sourmilk.net>");
MODULE_DESCRIPTION("Softmac Prism54 common code");
MODULE_LICENSE("GPL");
MODULE_ALIAS("prism54common");
static int p54_sta_add_remove(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta)
{
struct p54_common *priv = hw->priv;
/*
* Notify the firmware that we don't want or we don't
* need to buffer frames for this station anymore.
*/
p54_sta_unlock(priv, sta->addr);
return 0;
}
static void p54_sta_notify(struct ieee80211_hw *dev, struct ieee80211_vif *vif,
enum sta_notify_cmd notify_cmd,
struct ieee80211_sta *sta)
{
struct p54_common *priv = dev->priv;
switch (notify_cmd) {
case STA_NOTIFY_AWAKE:
/* update the firmware's filter table */
p54_sta_unlock(priv, sta->addr);
break;
default:
break;
}
}
static int p54_set_tim(struct ieee80211_hw *dev, struct ieee80211_sta *sta,
bool set)
{
struct p54_common *priv = dev->priv;
return p54_update_beacon_tim(priv, sta->aid, set);
}
u8 *p54_find_ie(struct sk_buff *skb, u8 ie)
{
struct ieee80211_mgmt *mgmt = (void *)skb->data;
u8 *pos, *end;
if (skb->len <= sizeof(mgmt))
return NULL;
pos = (u8 *)mgmt->u.beacon.variable;
end = skb->data + skb->len;
while (pos < end) {
if (pos + 2 + pos[1] > end)
return NULL;
if (pos[0] == ie)
return pos;
pos += 2 + pos[1];
}
return NULL;
}
static int p54_beacon_format_ie_tim(struct sk_buff *skb)
{
/*
* the good excuse for this mess is ... the firmware.
* The dummy TIM MUST be at the end of the beacon frame,
* because it'll be overwritten!
*/
u8 *tim;
u8 dtim_len;
u8 dtim_period;
u8 *next;
tim = p54_find_ie(skb, WLAN_EID_TIM);
if (!tim)
return 0;
dtim_len = tim[1];
dtim_period = tim[3];
next = tim + 2 + dtim_len;
if (dtim_len < 3)
return -EINVAL;
memmove(tim, next, skb_tail_pointer(skb) - next);
tim = skb_tail_pointer(skb) - (dtim_len + 2);
/* add the dummy at the end */
tim[0] = WLAN_EID_TIM;
tim[1] = 3;
tim[2] = 0;
tim[3] = dtim_period;
tim[4] = 0;
if (dtim_len > 3)
skb_trim(skb, skb->len - (dtim_len - 3));
return 0;
}
static int p54_beacon_update(struct p54_common *priv,
struct ieee80211_vif *vif)
{
struct sk_buff *beacon;
int ret;
beacon = ieee80211_beacon_get(priv->hw, vif);
if (!beacon)
return -ENOMEM;
ret = p54_beacon_format_ie_tim(beacon);
if (ret)
return ret;
/*
* During operation, the firmware takes care of beaconing.
* The driver only needs to upload a new beacon template, once
* the template was changed by the stack or userspace.
*
* LMAC API 3.2.2 also specifies that the driver does not need
* to cancel the old beacon template by hand, instead the firmware
* will release the previous one through the feedback mechanism.
*/
p54_tx_80211(priv->hw, beacon);
priv->tsf_high32 = 0;
priv->tsf_low32 = 0;
return 0;
}
static int p54_start(struct ieee80211_hw *dev)
{
struct p54_common *priv = dev->priv;
int err;
mutex_lock(&priv->conf_mutex);
err = priv->open(dev);
if (err)
goto out;
P54_SET_QUEUE(priv->qos_params[0], 0x0002, 0x0003, 0x0007, 47);
P54_SET_QUEUE(priv->qos_params[1], 0x0002, 0x0007, 0x000f, 94);
P54_SET_QUEUE(priv->qos_params[2], 0x0003, 0x000f, 0x03ff, 0);
P54_SET_QUEUE(priv->qos_params[3], 0x0007, 0x000f, 0x03ff, 0);
err = p54_set_edcf(priv);
if (err)
goto out;
memset(priv->bssid, ~0, ETH_ALEN);
priv->mode = NL80211_IFTYPE_MONITOR;
err = p54_setup_mac(priv);
if (err) {
priv->mode = NL80211_IFTYPE_UNSPECIFIED;
goto out;
}
ieee80211_queue_delayed_work(dev, &priv->work, 0);
priv->softled_state = 0;
err = p54_set_leds(priv);
out:
mutex_unlock(&priv->conf_mutex);
return err;
}
static void p54_stop(struct ieee80211_hw *dev)
{
struct p54_common *priv = dev->priv;
int i;
priv->mode = NL80211_IFTYPE_UNSPECIFIED;
priv->softled_state = 0;
cancel_delayed_work_sync(&priv->work);
mutex_lock(&priv->conf_mutex);
p54_set_leds(priv);
priv->stop(dev);
skb_queue_purge(&priv->tx_pending);
skb_queue_purge(&priv->tx_queue);
for (i = 0; i < P54_QUEUE_NUM; i++) {
priv->tx_stats[i].count = 0;
priv->tx_stats[i].len = 0;
}
priv->beacon_req_id = cpu_to_le32(0);
priv->tsf_high32 = priv->tsf_low32 = 0;
mutex_unlock(&priv->conf_mutex);
}
static int p54_add_interface(struct ieee80211_hw *dev,
struct ieee80211_vif *vif)
{
struct p54_common *priv = dev->priv;
int err;
vif->driver_flags |= IEEE80211_VIF_BEACON_FILTER;
mutex_lock(&priv->conf_mutex);
if (priv->mode != NL80211_IFTYPE_MONITOR) {
mutex_unlock(&priv->conf_mutex);
return -EOPNOTSUPP;
}
priv->vif = vif;
switch (vif->type) {
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_MESH_POINT:
priv->mode = vif->type;
break;
default:
mutex_unlock(&priv->conf_mutex);
return -EOPNOTSUPP;
}
memcpy(priv->mac_addr, vif->addr, ETH_ALEN);
err = p54_setup_mac(priv);
mutex_unlock(&priv->conf_mutex);
return err;
}
static void p54_remove_interface(struct ieee80211_hw *dev,
struct ieee80211_vif *vif)
{
struct p54_common *priv = dev->priv;
mutex_lock(&priv->conf_mutex);
priv->vif = NULL;
/*
* LMAC API 3.2.2 states that any active beacon template must be
* canceled by the driver before attempting a mode transition.
*/
if (le32_to_cpu(priv->beacon_req_id) != 0) {
p54_tx_cancel(priv, priv->beacon_req_id);
wait_for_completion_interruptible_timeout(&priv->beacon_comp, HZ);
}
priv->mode = NL80211_IFTYPE_MONITOR;
memset(priv->mac_addr, 0, ETH_ALEN);
memset(priv->bssid, 0, ETH_ALEN);
p54_setup_mac(priv);
mutex_unlock(&priv->conf_mutex);
}
static int p54_wait_for_stats(struct ieee80211_hw *dev)
{
struct p54_common *priv = dev->priv;
int ret;
priv->update_stats = true;
ret = p54_fetch_statistics(priv);
if (ret)
return ret;
ret = wait_for_completion_interruptible_timeout(&priv->stat_comp, HZ);
if (ret == 0)
return -ETIMEDOUT;
return 0;
}
static void p54_reset_stats(struct p54_common *priv)
{
struct ieee80211_channel *chan = priv->curchan;
if (chan) {
struct survey_info *info = &priv->survey[chan->hw_value];
/* only reset channel statistics, don't touch .filled, etc. */
info->channel_time = 0;
info->channel_time_busy = 0;
info->channel_time_tx = 0;
}
priv->update_stats = true;
priv->survey_raw.active = 0;
priv->survey_raw.cca = 0;
priv->survey_raw.tx = 0;
}
static int p54_config(struct ieee80211_hw *dev, u32 changed)
{
int ret = 0;
struct p54_common *priv = dev->priv;
struct ieee80211_conf *conf = &dev->conf;
mutex_lock(&priv->conf_mutex);
if (changed & IEEE80211_CONF_CHANGE_POWER)
priv->output_power = conf->power_level << 2;
if (changed & IEEE80211_CONF_CHANGE_CHANNEL) {
struct ieee80211_channel *oldchan;
WARN_ON(p54_wait_for_stats(dev));
oldchan = priv->curchan;
priv->curchan = NULL;
ret = p54_scan(priv, P54_SCAN_EXIT, 0);
if (ret) {
priv->curchan = oldchan;
goto out;
}
/*
* TODO: Use the LM_SCAN_TRAP to determine the current
* operating channel.
*/
priv->curchan = priv->hw->conf.channel;
p54_reset_stats(priv);
WARN_ON(p54_fetch_statistics(priv));
}
if (changed & IEEE80211_CONF_CHANGE_PS) {
WARN_ON(p54_wait_for_stats(dev));
ret = p54_set_ps(priv);
if (ret)
goto out;
WARN_ON(p54_wait_for_stats(dev));
}
if (changed & IEEE80211_CONF_CHANGE_IDLE) {
WARN_ON(p54_wait_for_stats(dev));
ret = p54_setup_mac(priv);
if (ret)
goto out;
WARN_ON(p54_wait_for_stats(dev));
}
out:
mutex_unlock(&priv->conf_mutex);
return ret;
}
static u64 p54_prepare_multicast(struct ieee80211_hw *dev,
struct netdev_hw_addr_list *mc_list)
{
struct p54_common *priv = dev->priv;
struct netdev_hw_addr *ha;
int i;
BUILD_BUG_ON(ARRAY_SIZE(priv->mc_maclist) !=
ARRAY_SIZE(((struct p54_group_address_table *)NULL)->mac_list));
/*
* The first entry is reserved for the global broadcast MAC.
* Otherwise the firmware will drop it and ARP will no longer work.
*/
i = 1;
priv->mc_maclist_num = netdev_hw_addr_list_count(mc_list) + i;
netdev_hw_addr_list_for_each(ha, mc_list) {
memcpy(&priv->mc_maclist[i], ha->addr, ETH_ALEN);
i++;
if (i >= ARRAY_SIZE(priv->mc_maclist))
break;
}
return 1; /* update */
}
static void p54_configure_filter(struct ieee80211_hw *dev,
unsigned int changed_flags,
unsigned int *total_flags,
u64 multicast)
{
struct p54_common *priv = dev->priv;
*total_flags &= FIF_PROMISC_IN_BSS |
FIF_ALLMULTI |
FIF_OTHER_BSS;
priv->filter_flags = *total_flags;
if (changed_flags & (FIF_PROMISC_IN_BSS | FIF_OTHER_BSS))
p54_setup_mac(priv);
if (changed_flags & FIF_ALLMULTI || multicast)
p54_set_groupfilter(priv);
}
static int p54_conf_tx(struct ieee80211_hw *dev,
struct ieee80211_vif *vif, u16 queue,
const struct ieee80211_tx_queue_params *params)
{
struct p54_common *priv = dev->priv;
int ret;
mutex_lock(&priv->conf_mutex);
if (queue < dev->queues) {
P54_SET_QUEUE(priv->qos_params[queue], params->aifs,
params->cw_min, params->cw_max, params->txop);
ret = p54_set_edcf(priv);
} else
ret = -EINVAL;
mutex_unlock(&priv->conf_mutex);
return ret;
}
static void p54_work(struct work_struct *work)
{
struct p54_common *priv = container_of(work, struct p54_common,
work.work);
if (unlikely(priv->mode == NL80211_IFTYPE_UNSPECIFIED))
return ;
/*
* TODO: walk through tx_queue and do the following tasks
* 1. initiate bursts.
* 2. cancel stuck frames / reset the device if necessary.
*/
mutex_lock(&priv->conf_mutex);
WARN_ON_ONCE(p54_fetch_statistics(priv));
mutex_unlock(&priv->conf_mutex);
}
static int p54_get_stats(struct ieee80211_hw *dev,
struct ieee80211_low_level_stats *stats)
{
struct p54_common *priv = dev->priv;
memcpy(stats, &priv->stats, sizeof(*stats));
return 0;
}
static void p54_bss_info_changed(struct ieee80211_hw *dev,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *info,
u32 changed)
{
struct p54_common *priv = dev->priv;
mutex_lock(&priv->conf_mutex);
if (changed & BSS_CHANGED_BSSID) {
memcpy(priv->bssid, info->bssid, ETH_ALEN);
p54_setup_mac(priv);
}
if (changed & BSS_CHANGED_BEACON) {
p54_scan(priv, P54_SCAN_EXIT, 0);
p54_setup_mac(priv);
p54_beacon_update(priv, vif);
p54_set_edcf(priv);
}
if (changed & (BSS_CHANGED_ERP_SLOT | BSS_CHANGED_BEACON)) {
priv->use_short_slot = info->use_short_slot;
p54_set_edcf(priv);
}
if (changed & BSS_CHANGED_BASIC_RATES) {
if (dev->conf.channel->band == IEEE80211_BAND_5GHZ)
priv->basic_rate_mask = (info->basic_rates << 4);
else
priv->basic_rate_mask = info->basic_rates;
p54_setup_mac(priv);
if (priv->fw_var >= 0x500)
p54_scan(priv, P54_SCAN_EXIT, 0);
}
if (changed & BSS_CHANGED_ASSOC) {
if (info->assoc) {
priv->aid = info->aid;
priv->wakeup_timer = info->beacon_int *
info->dtim_period * 5;
p54_setup_mac(priv);
} else {
priv->wakeup_timer = 500;
priv->aid = 0;
}
}
mutex_unlock(&priv->conf_mutex);
}
static int p54_set_key(struct ieee80211_hw *dev, enum set_key_cmd cmd,
struct ieee80211_vif *vif, struct ieee80211_sta *sta,
struct ieee80211_key_conf *key)
{
struct p54_common *priv = dev->priv;
int slot, ret = 0;
u8 algo = 0;
u8 *addr = NULL;
if (modparam_nohwcrypt)
return -EOPNOTSUPP;
mutex_lock(&priv->conf_mutex);
if (cmd == SET_KEY) {
switch (key->cipher) {
case WLAN_CIPHER_SUITE_TKIP:
if (!(priv->privacy_caps & (BR_DESC_PRIV_CAP_MICHAEL |
BR_DESC_PRIV_CAP_TKIP))) {
ret = -EOPNOTSUPP;
goto out_unlock;
}
key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
algo = P54_CRYPTO_TKIPMICHAEL;
break;
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
if (!(priv->privacy_caps & BR_DESC_PRIV_CAP_WEP)) {
ret = -EOPNOTSUPP;
goto out_unlock;
}
key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
algo = P54_CRYPTO_WEP;
break;
case WLAN_CIPHER_SUITE_CCMP:
if (!(priv->privacy_caps & BR_DESC_PRIV_CAP_AESCCMP)) {
ret = -EOPNOTSUPP;
goto out_unlock;
}
key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
algo = P54_CRYPTO_AESCCMP;
break;
default:
ret = -EOPNOTSUPP;
goto out_unlock;
}
slot = bitmap_find_free_region(priv->used_rxkeys,
priv->rx_keycache_size, 0);
if (slot < 0) {
/*
* The device supports the chosen algorithm, but the
* firmware does not provide enough key slots to store
* all of them.
* But encryption offload for outgoing frames is always
* possible, so we just pretend that the upload was
* successful and do the decryption in software.
*/
/* mark the key as invalid. */
key->hw_key_idx = 0xff;
goto out_unlock;
}
} else {
slot = key->hw_key_idx;
if (slot == 0xff) {
/* This key was not uploaded into the rx key cache. */
goto out_unlock;
}
bitmap_release_region(priv->used_rxkeys, slot, 0);
algo = 0;
}
if (sta)
addr = sta->addr;
ret = p54_upload_key(priv, algo, slot, key->keyidx,
key->keylen, addr, key->key);
if (ret) {
bitmap_release_region(priv->used_rxkeys, slot, 0);
ret = -EOPNOTSUPP;
goto out_unlock;
}
key->hw_key_idx = slot;
out_unlock:
mutex_unlock(&priv->conf_mutex);
return ret;
}
static int p54_get_survey(struct ieee80211_hw *dev, int idx,
struct survey_info *survey)
{
struct p54_common *priv = dev->priv;
struct ieee80211_channel *chan;
int err, tries;
bool in_use = false;
if (idx >= priv->chan_num)
return -ENOENT;
#define MAX_TRIES 1
for (tries = 0; tries < MAX_TRIES; tries++) {
chan = priv->curchan;
if (chan && chan->hw_value == idx) {
mutex_lock(&priv->conf_mutex);
err = p54_wait_for_stats(dev);
mutex_unlock(&priv->conf_mutex);
if (err)
return err;
in_use = true;
}
memcpy(survey, &priv->survey[idx], sizeof(*survey));
if (in_use) {
/* test if the reported statistics are valid. */
if (survey->channel_time != 0) {
survey->filled |= SURVEY_INFO_IN_USE;
} else {
/*
* hw/fw has not accumulated enough sample sets.
* Wait for 100ms, this ought to be enough to
* to get at least one non-null set of channel
* usage statistics.
*/
msleep(100);
continue;
}
}
return 0;
}
return -ETIMEDOUT;
#undef MAX_TRIES
}
static unsigned int p54_flush_count(struct p54_common *priv)
{
unsigned int total = 0, i;
BUILD_BUG_ON(P54_QUEUE_NUM > ARRAY_SIZE(priv->tx_stats));
/*
* Because the firmware has the sole control over any frames
* in the P54_QUEUE_BEACON or P54_QUEUE_SCAN queues, they
* don't really count as pending or active.
*/
for (i = P54_QUEUE_MGMT; i < P54_QUEUE_NUM; i++)
total += priv->tx_stats[i].len;
return total;
}
static void p54_flush(struct ieee80211_hw *dev, bool drop)
{
struct p54_common *priv = dev->priv;
unsigned int total, i;
/*
* Currently, it wouldn't really matter if we wait for one second
* or 15 minutes. But once someone gets around and completes the
* TODOs [ancel stuck frames / reset device] in p54_work, it will
* suddenly make sense to wait that long.
*/
i = P54_STATISTICS_UPDATE * 2 / 20;
/*
* In this case no locking is required because as we speak the
* queues have already been stopped and no new frames can sneak
* up from behind.
*/
while ((total = p54_flush_count(priv) && i--)) {
/* waste time */
msleep(20);
}
WARN(total, "tx flush timeout, unresponsive firmware");
}
static void p54_set_coverage_class(struct ieee80211_hw *dev, u8 coverage_class)
{
struct p54_common *priv = dev->priv;
mutex_lock(&priv->conf_mutex);
/* support all coverage class values as in 802.11-2007 Table 7-27 */
priv->coverage_class = clamp_t(u8, coverage_class, 0, 31);
p54_set_edcf(priv);
mutex_unlock(&priv->conf_mutex);
}
static const struct ieee80211_ops p54_ops = {
.tx = p54_tx_80211,
.start = p54_start,
.stop = p54_stop,
.add_interface = p54_add_interface,
.remove_interface = p54_remove_interface,
.set_tim = p54_set_tim,
.sta_notify = p54_sta_notify,
.sta_add = p54_sta_add_remove,
.sta_remove = p54_sta_add_remove,
.set_key = p54_set_key,
.config = p54_config,
.flush = p54_flush,
.bss_info_changed = p54_bss_info_changed,
.prepare_multicast = p54_prepare_multicast,
.configure_filter = p54_configure_filter,
.conf_tx = p54_conf_tx,
.get_stats = p54_get_stats,
.get_survey = p54_get_survey,
.set_coverage_class = p54_set_coverage_class,
};
struct ieee80211_hw *p54_init_common(size_t priv_data_len)
{
struct ieee80211_hw *dev;
struct p54_common *priv;
dev = ieee80211_alloc_hw(priv_data_len, &p54_ops);
if (!dev)
return NULL;
priv = dev->priv;
priv->hw = dev;
priv->mode = NL80211_IFTYPE_UNSPECIFIED;
priv->basic_rate_mask = 0x15f;
spin_lock_init(&priv->tx_stats_lock);
skb_queue_head_init(&priv->tx_queue);
skb_queue_head_init(&priv->tx_pending);
dev->flags = IEEE80211_HW_RX_INCLUDES_FCS |
IEEE80211_HW_SIGNAL_DBM |
IEEE80211_HW_SUPPORTS_PS |
IEEE80211_HW_PS_NULLFUNC_STACK |
IEEE80211_HW_REPORTS_TX_ACK_STATUS;
dev->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC) |
BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_MESH_POINT);
dev->channel_change_time = 1000; /* TODO: find actual value */
priv->beacon_req_id = cpu_to_le32(0);
priv->tx_stats[P54_QUEUE_BEACON].limit = 1;
priv->tx_stats[P54_QUEUE_FWSCAN].limit = 1;
priv->tx_stats[P54_QUEUE_MGMT].limit = 3;
priv->tx_stats[P54_QUEUE_CAB].limit = 3;
priv->tx_stats[P54_QUEUE_DATA].limit = 5;
dev->queues = 1;
priv->noise = -94;
/*
* We support at most 8 tries no matter which rate they're at,
* we cannot support max_rates * max_rate_tries as we set it
* here, but setting it correctly to 4/2 or so would limit us
* artificially if the RC algorithm wants just two rates, so
* let's say 4/7, we'll redistribute it at TX time, see the
* comments there.
*/
dev->max_rates = 4;
dev->max_rate_tries = 7;
dev->extra_tx_headroom = sizeof(struct p54_hdr) + 4 +
sizeof(struct p54_tx_data);
/*
* For now, disable PS by default because it affects
* link stability significantly.
*/
dev->wiphy->flags &= ~WIPHY_FLAG_PS_ON_BY_DEFAULT;
mutex_init(&priv->conf_mutex);
mutex_init(&priv->eeprom_mutex);
init_completion(&priv->stat_comp);
init_completion(&priv->eeprom_comp);
init_completion(&priv->beacon_comp);
INIT_DELAYED_WORK(&priv->work, p54_work);
memset(&priv->mc_maclist[0], ~0, ETH_ALEN);
priv->curchan = NULL;
p54_reset_stats(priv);
return dev;
}
EXPORT_SYMBOL_GPL(p54_init_common);
int p54_register_common(struct ieee80211_hw *dev, struct device *pdev)
{
struct p54_common __maybe_unused *priv = dev->priv;
int err;
err = ieee80211_register_hw(dev);
if (err) {
dev_err(pdev, "Cannot register device (%d).\n", err);
return err;
}
#ifdef CONFIG_P54_LEDS
err = p54_init_leds(priv);
if (err)
return err;
#endif /* CONFIG_P54_LEDS */
dev_info(pdev, "is registered as '%s'\n", wiphy_name(dev->wiphy));
return 0;
}
EXPORT_SYMBOL_GPL(p54_register_common);
void p54_free_common(struct ieee80211_hw *dev)
{
struct p54_common *priv = dev->priv;
unsigned int i;
for (i = 0; i < IEEE80211_NUM_BANDS; i++)
kfree(priv->band_table[i]);
kfree(priv->iq_autocal);
kfree(priv->output_limit);
kfree(priv->curve_data);
kfree(priv->rssi_db);
kfree(priv->used_rxkeys);
kfree(priv->survey);
priv->iq_autocal = NULL;
priv->output_limit = NULL;
priv->curve_data = NULL;
priv->rssi_db = NULL;
priv->used_rxkeys = NULL;
priv->survey = NULL;
ieee80211_free_hw(dev);
}
EXPORT_SYMBOL_GPL(p54_free_common);
void p54_unregister_common(struct ieee80211_hw *dev)
{
struct p54_common *priv = dev->priv;
#ifdef CONFIG_P54_LEDS
p54_unregister_leds(priv);
#endif /* CONFIG_P54_LEDS */
ieee80211_unregister_hw(dev);
mutex_destroy(&priv->conf_mutex);
mutex_destroy(&priv->eeprom_mutex);
}
EXPORT_SYMBOL_GPL(p54_unregister_common);
| gpl-2.0 |
ea4862/boeffla_cm11 | drivers/parisc/led.c | 8393 | 20416 | /*
* Chassis LCD/LED driver for HP-PARISC workstations
*
* (c) Copyright 2000 Red Hat Software
* (c) Copyright 2000 Helge Deller <hdeller@redhat.com>
* (c) Copyright 2001-2009 Helge Deller <deller@gmx.de>
* (c) Copyright 2001 Randolph Chung <tausq@debian.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* TODO:
* - speed-up calculations with inlined assembler
* - interface to write to second row of LCD from /proc (if technically possible)
*
* Changes:
* - Audit copy_from_user in led_proc_write.
* Daniele Bellucci <bellucda@tiscali.it>
* - Switch from using a tasklet to a work queue, so the led_LCD_driver
* can sleep.
* David Pye <dmp@davidmpye.dyndns.org>
*/
#include <linux/module.h>
#include <linux/stddef.h> /* for offsetof() */
#include <linux/init.h>
#include <linux/types.h>
#include <linux/ioport.h>
#include <linux/utsname.h>
#include <linux/capability.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/inetdevice.h>
#include <linux/in.h>
#include <linux/interrupt.h>
#include <linux/kernel_stat.h>
#include <linux/reboot.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/ctype.h>
#include <linux/blkdev.h>
#include <linux/workqueue.h>
#include <linux/rcupdate.h>
#include <asm/io.h>
#include <asm/processor.h>
#include <asm/hardware.h>
#include <asm/param.h> /* HZ */
#include <asm/led.h>
#include <asm/pdc.h>
#include <asm/uaccess.h>
/* The control of the LEDs and LCDs on PARISC-machines have to be done
completely in software. The necessary calculations are done in a work queue
task which is scheduled regularly, and since the calculations may consume a
relatively large amount of CPU time, some of the calculations can be
turned off with the following variables (controlled via procfs) */
static int led_type __read_mostly = -1;
static unsigned char lastleds; /* LED state from most recent update */
static unsigned int led_heartbeat __read_mostly = 1;
static unsigned int led_diskio __read_mostly = 1;
static unsigned int led_lanrxtx __read_mostly = 1;
static char lcd_text[32] __read_mostly;
static char lcd_text_default[32] __read_mostly;
static int lcd_no_led_support __read_mostly = 0; /* KittyHawk doesn't support LED on its LCD */
static struct workqueue_struct *led_wq;
static void led_work_func(struct work_struct *);
static DECLARE_DELAYED_WORK(led_task, led_work_func);
#if 0
#define DPRINTK(x) printk x
#else
#define DPRINTK(x)
#endif
struct lcd_block {
unsigned char command; /* stores the command byte */
unsigned char on; /* value for turning LED on */
unsigned char off; /* value for turning LED off */
};
/* Structure returned by PDC_RETURN_CHASSIS_INFO */
/* NOTE: we use unsigned long:16 two times, since the following member
lcd_cmd_reg_addr needs to be 64bit aligned on 64bit PA2.0-machines */
struct pdc_chassis_lcd_info_ret_block {
unsigned long model:16; /* DISPLAY_MODEL_XXXX */
unsigned long lcd_width:16; /* width of the LCD in chars (DISPLAY_MODEL_LCD only) */
unsigned long lcd_cmd_reg_addr; /* ptr to LCD cmd-register & data ptr for LED */
unsigned long lcd_data_reg_addr; /* ptr to LCD data-register (LCD only) */
unsigned int min_cmd_delay; /* delay in uS after cmd-write (LCD only) */
unsigned char reset_cmd1; /* command #1 for writing LCD string (LCD only) */
unsigned char reset_cmd2; /* command #2 for writing LCD string (LCD only) */
unsigned char act_enable; /* 0 = no activity (LCD only) */
struct lcd_block heartbeat;
struct lcd_block disk_io;
struct lcd_block lan_rcv;
struct lcd_block lan_tx;
char _pad;
};
/* LCD_CMD and LCD_DATA for KittyHawk machines */
#define KITTYHAWK_LCD_CMD F_EXTEND(0xf0190000UL) /* 64bit-ready */
#define KITTYHAWK_LCD_DATA (KITTYHAWK_LCD_CMD+1)
/* lcd_info is pre-initialized to the values needed to program KittyHawk LCD's
* HP seems to have used Sharp/Hitachi HD44780 LCDs most of the time. */
static struct pdc_chassis_lcd_info_ret_block
lcd_info __attribute__((aligned(8))) __read_mostly =
{
.model = DISPLAY_MODEL_LCD,
.lcd_width = 16,
.lcd_cmd_reg_addr = KITTYHAWK_LCD_CMD,
.lcd_data_reg_addr = KITTYHAWK_LCD_DATA,
.min_cmd_delay = 80,
.reset_cmd1 = 0x80,
.reset_cmd2 = 0xc0,
};
/* direct access to some of the lcd_info variables */
#define LCD_CMD_REG lcd_info.lcd_cmd_reg_addr
#define LCD_DATA_REG lcd_info.lcd_data_reg_addr
#define LED_DATA_REG lcd_info.lcd_cmd_reg_addr /* LASI & ASP only */
#define LED_HASLCD 1
#define LED_NOLCD 0
/* The workqueue must be created at init-time */
static int start_task(void)
{
/* Display the default text now */
if (led_type == LED_HASLCD) lcd_print( lcd_text_default );
/* KittyHawk has no LED support on its LCD */
if (lcd_no_led_support) return 0;
/* Create the work queue and queue the LED task */
led_wq = create_singlethread_workqueue("led_wq");
queue_delayed_work(led_wq, &led_task, 0);
return 0;
}
device_initcall(start_task);
/* ptr to LCD/LED-specific function */
static void (*led_func_ptr) (unsigned char) __read_mostly;
#ifdef CONFIG_PROC_FS
static int led_proc_show(struct seq_file *m, void *v)
{
switch ((long)m->private)
{
case LED_NOLCD:
seq_printf(m, "Heartbeat: %d\n", led_heartbeat);
seq_printf(m, "Disk IO: %d\n", led_diskio);
seq_printf(m, "LAN Rx/Tx: %d\n", led_lanrxtx);
break;
case LED_HASLCD:
seq_printf(m, "%s\n", lcd_text);
break;
default:
return 0;
}
return 0;
}
static int led_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, led_proc_show, PDE(inode)->data);
}
static ssize_t led_proc_write(struct file *file, const char *buf,
size_t count, loff_t *pos)
{
void *data = PDE(file->f_path.dentry->d_inode)->data;
char *cur, lbuf[32];
int d;
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
if (count >= sizeof(lbuf))
count = sizeof(lbuf)-1;
if (copy_from_user(lbuf, buf, count))
return -EFAULT;
lbuf[count] = 0;
cur = lbuf;
switch ((long)data)
{
case LED_NOLCD:
d = *cur++ - '0';
if (d != 0 && d != 1) goto parse_error;
led_heartbeat = d;
if (*cur++ != ' ') goto parse_error;
d = *cur++ - '0';
if (d != 0 && d != 1) goto parse_error;
led_diskio = d;
if (*cur++ != ' ') goto parse_error;
d = *cur++ - '0';
if (d != 0 && d != 1) goto parse_error;
led_lanrxtx = d;
break;
case LED_HASLCD:
if (*cur && cur[strlen(cur)-1] == '\n')
cur[strlen(cur)-1] = 0;
if (*cur == 0)
cur = lcd_text_default;
lcd_print(cur);
break;
default:
return 0;
}
return count;
parse_error:
if ((long)data == LED_NOLCD)
printk(KERN_CRIT "Parse error: expect \"n n n\" (n == 0 or 1) for heartbeat,\ndisk io and lan tx/rx indicators\n");
return -EINVAL;
}
static const struct file_operations led_proc_fops = {
.owner = THIS_MODULE,
.open = led_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = led_proc_write,
};
static int __init led_create_procfs(void)
{
struct proc_dir_entry *proc_pdc_root = NULL;
struct proc_dir_entry *ent;
if (led_type == -1) return -1;
proc_pdc_root = proc_mkdir("pdc", 0);
if (!proc_pdc_root) return -1;
if (!lcd_no_led_support)
{
ent = proc_create_data("led", S_IRUGO|S_IWUSR, proc_pdc_root,
&led_proc_fops, (void *)LED_NOLCD); /* LED */
if (!ent) return -1;
}
if (led_type == LED_HASLCD)
{
ent = proc_create_data("lcd", S_IRUGO|S_IWUSR, proc_pdc_root,
&led_proc_fops, (void *)LED_HASLCD); /* LCD */
if (!ent) return -1;
}
return 0;
}
#endif
/*
**
** led_ASP_driver()
**
*/
#define LED_DATA 0x01 /* data to shift (0:on 1:off) */
#define LED_STROBE 0x02 /* strobe to clock data */
static void led_ASP_driver(unsigned char leds)
{
int i;
leds = ~leds;
for (i = 0; i < 8; i++) {
unsigned char value;
value = (leds & 0x80) >> 7;
gsc_writeb( value, LED_DATA_REG );
gsc_writeb( value | LED_STROBE, LED_DATA_REG );
leds <<= 1;
}
}
/*
**
** led_LASI_driver()
**
*/
static void led_LASI_driver(unsigned char leds)
{
leds = ~leds;
gsc_writeb( leds, LED_DATA_REG );
}
/*
**
** led_LCD_driver()
**
*/
static void led_LCD_driver(unsigned char leds)
{
static int i;
static unsigned char mask[4] = { LED_HEARTBEAT, LED_DISK_IO,
LED_LAN_RCV, LED_LAN_TX };
static struct lcd_block * blockp[4] = {
&lcd_info.heartbeat,
&lcd_info.disk_io,
&lcd_info.lan_rcv,
&lcd_info.lan_tx
};
/* Convert min_cmd_delay to milliseconds */
unsigned int msec_cmd_delay = 1 + (lcd_info.min_cmd_delay / 1000);
for (i=0; i<4; ++i)
{
if ((leds & mask[i]) != (lastleds & mask[i]))
{
gsc_writeb( blockp[i]->command, LCD_CMD_REG );
msleep(msec_cmd_delay);
gsc_writeb( leds & mask[i] ? blockp[i]->on :
blockp[i]->off, LCD_DATA_REG );
msleep(msec_cmd_delay);
}
}
}
/*
**
** led_get_net_activity()
**
** calculate if there was TX- or RX-throughput on the network interfaces
** (analog to dev_get_info() from net/core/dev.c)
**
*/
static __inline__ int led_get_net_activity(void)
{
#ifndef CONFIG_NET
return 0;
#else
static u64 rx_total_last, tx_total_last;
u64 rx_total, tx_total;
struct net_device *dev;
int retval;
rx_total = tx_total = 0;
/* we are running as a workqueue task, so we can use an RCU lookup */
rcu_read_lock();
for_each_netdev_rcu(&init_net, dev) {
const struct rtnl_link_stats64 *stats;
struct rtnl_link_stats64 temp;
struct in_device *in_dev = __in_dev_get_rcu(dev);
if (!in_dev || !in_dev->ifa_list)
continue;
if (ipv4_is_loopback(in_dev->ifa_list->ifa_local))
continue;
stats = dev_get_stats(dev, &temp);
rx_total += stats->rx_packets;
tx_total += stats->tx_packets;
}
rcu_read_unlock();
retval = 0;
if (rx_total != rx_total_last) {
rx_total_last = rx_total;
retval |= LED_LAN_RCV;
}
if (tx_total != tx_total_last) {
tx_total_last = tx_total;
retval |= LED_LAN_TX;
}
return retval;
#endif
}
/*
**
** led_get_diskio_activity()
**
** calculate if there was disk-io in the system
**
*/
static __inline__ int led_get_diskio_activity(void)
{
static unsigned long last_pgpgin, last_pgpgout;
unsigned long events[NR_VM_EVENT_ITEMS];
int changed;
all_vm_events(events);
/* Just use a very simple calculation here. Do not care about overflow,
since we only want to know if there was activity or not. */
changed = (events[PGPGIN] != last_pgpgin) ||
(events[PGPGOUT] != last_pgpgout);
last_pgpgin = events[PGPGIN];
last_pgpgout = events[PGPGOUT];
return (changed ? LED_DISK_IO : 0);
}
/*
** led_work_func()
**
** manages when and which chassis LCD/LED gets updated
TODO:
- display load average (older machines like 715/64 have 4 "free" LED's for that)
- optimizations
*/
#define HEARTBEAT_LEN (HZ*10/100)
#define HEARTBEAT_2ND_RANGE_START (HZ*28/100)
#define HEARTBEAT_2ND_RANGE_END (HEARTBEAT_2ND_RANGE_START + HEARTBEAT_LEN)
#define LED_UPDATE_INTERVAL (1 + (HZ*19/1000))
static void led_work_func (struct work_struct *unused)
{
static unsigned long last_jiffies;
static unsigned long count_HZ; /* counter in range 0..HZ */
unsigned char currentleds = 0; /* stores current value of the LEDs */
/* exit if not initialized */
if (!led_func_ptr)
return;
/* increment the heartbeat timekeeper */
count_HZ += jiffies - last_jiffies;
last_jiffies = jiffies;
if (count_HZ >= HZ)
count_HZ = 0;
if (likely(led_heartbeat))
{
/* flash heartbeat-LED like a real heart
* (2 x short then a long delay)
*/
if (count_HZ < HEARTBEAT_LEN ||
(count_HZ >= HEARTBEAT_2ND_RANGE_START &&
count_HZ < HEARTBEAT_2ND_RANGE_END))
currentleds |= LED_HEARTBEAT;
}
if (likely(led_lanrxtx)) currentleds |= led_get_net_activity();
if (likely(led_diskio)) currentleds |= led_get_diskio_activity();
/* blink LEDs if we got an Oops (HPMC) */
if (unlikely(oops_in_progress)) {
if (boot_cpu_data.cpu_type >= pcxl2) {
/* newer machines don't have loadavg. LEDs, so we
* let all LEDs blink twice per second instead */
currentleds = (count_HZ <= (HZ/2)) ? 0 : 0xff;
} else {
/* old machines: blink loadavg. LEDs twice per second */
if (count_HZ <= (HZ/2))
currentleds &= ~(LED4|LED5|LED6|LED7);
else
currentleds |= (LED4|LED5|LED6|LED7);
}
}
if (currentleds != lastleds)
{
led_func_ptr(currentleds); /* Update the LCD/LEDs */
lastleds = currentleds;
}
queue_delayed_work(led_wq, &led_task, LED_UPDATE_INTERVAL);
}
/*
** led_halt()
**
** called by the reboot notifier chain at shutdown and stops all
** LED/LCD activities.
**
*/
static int led_halt(struct notifier_block *, unsigned long, void *);
static struct notifier_block led_notifier = {
.notifier_call = led_halt,
};
static int notifier_disabled = 0;
static int led_halt(struct notifier_block *nb, unsigned long event, void *buf)
{
char *txt;
if (notifier_disabled)
return NOTIFY_OK;
notifier_disabled = 1;
switch (event) {
case SYS_RESTART: txt = "SYSTEM RESTART";
break;
case SYS_HALT: txt = "SYSTEM HALT";
break;
case SYS_POWER_OFF: txt = "SYSTEM POWER OFF";
break;
default: return NOTIFY_DONE;
}
/* Cancel the work item and delete the queue */
if (led_wq) {
cancel_delayed_work_sync(&led_task);
destroy_workqueue(led_wq);
led_wq = NULL;
}
if (lcd_info.model == DISPLAY_MODEL_LCD)
lcd_print(txt);
else
if (led_func_ptr)
led_func_ptr(0xff); /* turn all LEDs ON */
return NOTIFY_OK;
}
/*
** register_led_driver()
**
** registers an external LED or LCD for usage by this driver.
** currently only LCD-, LASI- and ASP-style LCD/LED's are supported.
**
*/
int __init register_led_driver(int model, unsigned long cmd_reg, unsigned long data_reg)
{
static int initialized;
if (initialized || !data_reg)
return 1;
lcd_info.model = model; /* store the values */
LCD_CMD_REG = (cmd_reg == LED_CMD_REG_NONE) ? 0 : cmd_reg;
switch (lcd_info.model) {
case DISPLAY_MODEL_LCD:
LCD_DATA_REG = data_reg;
printk(KERN_INFO "LCD display at %lx,%lx registered\n",
LCD_CMD_REG , LCD_DATA_REG);
led_func_ptr = led_LCD_driver;
led_type = LED_HASLCD;
break;
case DISPLAY_MODEL_LASI:
LED_DATA_REG = data_reg;
led_func_ptr = led_LASI_driver;
printk(KERN_INFO "LED display at %lx registered\n", LED_DATA_REG);
led_type = LED_NOLCD;
break;
case DISPLAY_MODEL_OLD_ASP:
LED_DATA_REG = data_reg;
led_func_ptr = led_ASP_driver;
printk(KERN_INFO "LED (ASP-style) display at %lx registered\n",
LED_DATA_REG);
led_type = LED_NOLCD;
break;
default:
printk(KERN_ERR "%s: Wrong LCD/LED model %d !\n",
__func__, lcd_info.model);
return 1;
}
/* mark the LCD/LED driver now as initialized and
* register to the reboot notifier chain */
initialized++;
register_reboot_notifier(&led_notifier);
/* Ensure the work is queued */
if (led_wq) {
queue_delayed_work(led_wq, &led_task, 0);
}
return 0;
}
/*
** register_led_regions()
**
** register_led_regions() registers the LCD/LED regions for /procfs.
** At bootup - where the initialisation of the LCD/LED normally happens -
** not all internal structures of request_region() are properly set up,
** so that we delay the led-registration until after busdevices_init()
** has been executed.
**
*/
void __init register_led_regions(void)
{
switch (lcd_info.model) {
case DISPLAY_MODEL_LCD:
request_mem_region((unsigned long)LCD_CMD_REG, 1, "lcd_cmd");
request_mem_region((unsigned long)LCD_DATA_REG, 1, "lcd_data");
break;
case DISPLAY_MODEL_LASI:
case DISPLAY_MODEL_OLD_ASP:
request_mem_region((unsigned long)LED_DATA_REG, 1, "led_data");
break;
}
}
/*
**
** lcd_print()
**
** Displays the given string on the LCD-Display of newer machines.
** lcd_print() disables/enables the timer-based led work queue to
** avoid a race condition while writing the CMD/DATA register pair.
**
*/
int lcd_print( const char *str )
{
int i;
if (!led_func_ptr || lcd_info.model != DISPLAY_MODEL_LCD)
return 0;
/* temporarily disable the led work task */
if (led_wq)
cancel_delayed_work_sync(&led_task);
/* copy display string to buffer for procfs */
strlcpy(lcd_text, str, sizeof(lcd_text));
/* Set LCD Cursor to 1st character */
gsc_writeb(lcd_info.reset_cmd1, LCD_CMD_REG);
udelay(lcd_info.min_cmd_delay);
/* Print the string */
for (i=0; i < lcd_info.lcd_width; i++) {
if (str && *str)
gsc_writeb(*str++, LCD_DATA_REG);
else
gsc_writeb(' ', LCD_DATA_REG);
udelay(lcd_info.min_cmd_delay);
}
/* re-queue the work */
if (led_wq) {
queue_delayed_work(led_wq, &led_task, 0);
}
return lcd_info.lcd_width;
}
/*
** led_init()
**
** led_init() is called very early in the bootup-process from setup.c
** and asks the PDC for an usable chassis LCD or LED.
** If the PDC doesn't return any info, then the LED
** is detected by lasi.c or asp.c and registered with the
** above functions lasi_led_init() or asp_led_init().
** KittyHawk machines have often a buggy PDC, so that
** we explicitly check for those machines here.
*/
int __init led_init(void)
{
struct pdc_chassis_info chassis_info;
int ret;
snprintf(lcd_text_default, sizeof(lcd_text_default),
"Linux %s", init_utsname()->release);
/* Work around the buggy PDC of KittyHawk-machines */
switch (CPU_HVERSION) {
case 0x580: /* KittyHawk DC2-100 (K100) */
case 0x581: /* KittyHawk DC3-120 (K210) */
case 0x582: /* KittyHawk DC3 100 (K400) */
case 0x583: /* KittyHawk DC3 120 (K410) */
case 0x58B: /* KittyHawk DC2 100 (K200) */
printk(KERN_INFO "%s: KittyHawk-Machine (hversion 0x%x) found, "
"LED detection skipped.\n", __FILE__, CPU_HVERSION);
lcd_no_led_support = 1;
goto found; /* use the preinitialized values of lcd_info */
}
/* initialize the struct, so that we can check for valid return values */
lcd_info.model = DISPLAY_MODEL_NONE;
chassis_info.actcnt = chassis_info.maxcnt = 0;
ret = pdc_chassis_info(&chassis_info, &lcd_info, sizeof(lcd_info));
if (ret == PDC_OK) {
DPRINTK((KERN_INFO "%s: chassis info: model=%d (%s), "
"lcd_width=%d, cmd_delay=%u,\n"
"%s: sizecnt=%d, actcnt=%ld, maxcnt=%ld\n",
__FILE__, lcd_info.model,
(lcd_info.model==DISPLAY_MODEL_LCD) ? "LCD" :
(lcd_info.model==DISPLAY_MODEL_LASI) ? "LED" : "unknown",
lcd_info.lcd_width, lcd_info.min_cmd_delay,
__FILE__, sizeof(lcd_info),
chassis_info.actcnt, chassis_info.maxcnt));
DPRINTK((KERN_INFO "%s: cmd=%p, data=%p, reset1=%x, reset2=%x, act_enable=%d\n",
__FILE__, lcd_info.lcd_cmd_reg_addr,
lcd_info.lcd_data_reg_addr, lcd_info.reset_cmd1,
lcd_info.reset_cmd2, lcd_info.act_enable ));
/* check the results. Some machines have a buggy PDC */
if (chassis_info.actcnt <= 0 || chassis_info.actcnt != chassis_info.maxcnt)
goto not_found;
switch (lcd_info.model) {
case DISPLAY_MODEL_LCD: /* LCD display */
if (chassis_info.actcnt <
offsetof(struct pdc_chassis_lcd_info_ret_block, _pad)-1)
goto not_found;
if (!lcd_info.act_enable) {
DPRINTK((KERN_INFO "PDC prohibited usage of the LCD.\n"));
goto not_found;
}
break;
case DISPLAY_MODEL_NONE: /* no LED or LCD available */
printk(KERN_INFO "PDC reported no LCD or LED.\n");
goto not_found;
case DISPLAY_MODEL_LASI: /* Lasi style 8 bit LED display */
if (chassis_info.actcnt != 8 && chassis_info.actcnt != 32)
goto not_found;
break;
default:
printk(KERN_WARNING "PDC reported unknown LCD/LED model %d\n",
lcd_info.model);
goto not_found;
} /* switch() */
found:
/* register the LCD/LED driver */
register_led_driver(lcd_info.model, LCD_CMD_REG, LCD_DATA_REG);
return 0;
} else { /* if() */
DPRINTK((KERN_INFO "pdc_chassis_info call failed with retval = %d\n", ret));
}
not_found:
lcd_info.model = DISPLAY_MODEL_NONE;
return 1;
}
static void __exit led_exit(void)
{
unregister_reboot_notifier(&led_notifier);
return;
}
#ifdef CONFIG_PROC_FS
module_init(led_create_procfs)
#endif
| gpl-2.0 |
mseskir/android_kernel_vestel_55g | drivers/uwb/whc-rc.c | 10441 | 13503 | /*
* Wireless Host Controller: Radio Control Interface (WHCI v0.95[2.3])
* Radio Control command/event transport to the UWB stack
*
* Copyright (C) 2005-2006 Intel Corporation
* Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*
* Initialize and hook up the Radio Control interface.
*
* For each device probed, creates an 'struct whcrc' which contains
* just the representation of the UWB Radio Controller, and the logic
* for reading notifications and passing them to the UWB Core.
*
* So we initialize all of those, register the UWB Radio Controller
* and setup the notification/event handle to pipe the notifications
* to the UWB management Daemon.
*
* Once uwb_rc_add() is called, the UWB stack takes control, resets
* the radio and readies the device to take commands the UWB
* API/user-space.
*
* Note this driver is just a transport driver; the commands are
* formed at the UWB stack and given to this driver who will deliver
* them to the hw and transfer the replies/notifications back to the
* UWB stack through the UWB daemon (UWBD).
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/sched.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/uwb.h>
#include <linux/uwb/whci.h>
#include <linux/uwb/umc.h>
#include "uwb-internal.h"
/**
* Descriptor for an instance of the UWB Radio Control Driver that
* attaches to the URC interface of the WHCI PCI card.
*
* Unless there is a lock specific to the 'data members', all access
* is protected by uwb_rc->mutex.
*/
struct whcrc {
struct umc_dev *umc_dev;
struct uwb_rc *uwb_rc; /* UWB host controller */
unsigned long area;
void __iomem *rc_base;
size_t rc_len;
spinlock_t irq_lock;
void *evt_buf, *cmd_buf;
dma_addr_t evt_dma_buf, cmd_dma_buf;
wait_queue_head_t cmd_wq;
struct work_struct event_work;
};
/**
* Execute an UWB RC command on WHCI/RC
*
* @rc: Instance of a Radio Controller that is a whcrc
* @cmd: Buffer containing the RCCB and payload to execute
* @cmd_size: Size of the command buffer.
*
* We copy the command into whcrc->cmd_buf (as it is pretty and
* aligned`and physically contiguous) and then press the right keys in
* the controller's URCCMD register to get it to read it. We might
* have to wait for the cmd_sem to be open to us.
*
* NOTE: rc's mutex has to be locked
*/
static int whcrc_cmd(struct uwb_rc *uwb_rc,
const struct uwb_rccb *cmd, size_t cmd_size)
{
int result = 0;
struct whcrc *whcrc = uwb_rc->priv;
struct device *dev = &whcrc->umc_dev->dev;
u32 urccmd;
if (cmd_size >= 4096)
return -EINVAL;
/*
* If the URC is halted, then the hardware has reset itself.
* Attempt to recover by restarting the device and then return
* an error as it's likely that the current command isn't
* valid for a newly started RC.
*/
if (le_readl(whcrc->rc_base + URCSTS) & URCSTS_HALTED) {
dev_err(dev, "requesting reset of halted radio controller\n");
uwb_rc_reset_all(uwb_rc);
return -EIO;
}
result = wait_event_timeout(whcrc->cmd_wq,
!(le_readl(whcrc->rc_base + URCCMD) & URCCMD_ACTIVE), HZ/2);
if (result == 0) {
dev_err(dev, "device is not ready to execute commands\n");
return -ETIMEDOUT;
}
memmove(whcrc->cmd_buf, cmd, cmd_size);
le_writeq(whcrc->cmd_dma_buf, whcrc->rc_base + URCCMDADDR);
spin_lock(&whcrc->irq_lock);
urccmd = le_readl(whcrc->rc_base + URCCMD);
urccmd &= ~(URCCMD_EARV | URCCMD_SIZE_MASK);
le_writel(urccmd | URCCMD_ACTIVE | URCCMD_IWR | cmd_size,
whcrc->rc_base + URCCMD);
spin_unlock(&whcrc->irq_lock);
return 0;
}
static int whcrc_reset(struct uwb_rc *rc)
{
struct whcrc *whcrc = rc->priv;
return umc_controller_reset(whcrc->umc_dev);
}
/**
* Reset event reception mechanism and tell hw we are ready to get more
*
* We have read all the events in the event buffer, so we are ready to
* reset it to the beginning.
*
* This is only called during initialization or after an event buffer
* has been retired. This means we can be sure that event processing
* is disabled and it's safe to update the URCEVTADDR register.
*
* There's no need to wait for the event processing to start as the
* URC will not clear URCCMD_ACTIVE until (internal) event buffer
* space is available.
*/
static
void whcrc_enable_events(struct whcrc *whcrc)
{
u32 urccmd;
le_writeq(whcrc->evt_dma_buf, whcrc->rc_base + URCEVTADDR);
spin_lock(&whcrc->irq_lock);
urccmd = le_readl(whcrc->rc_base + URCCMD) & ~URCCMD_ACTIVE;
le_writel(urccmd | URCCMD_EARV, whcrc->rc_base + URCCMD);
spin_unlock(&whcrc->irq_lock);
}
static void whcrc_event_work(struct work_struct *work)
{
struct whcrc *whcrc = container_of(work, struct whcrc, event_work);
size_t size;
u64 urcevtaddr;
urcevtaddr = le_readq(whcrc->rc_base + URCEVTADDR);
size = urcevtaddr & URCEVTADDR_OFFSET_MASK;
uwb_rc_neh_grok(whcrc->uwb_rc, whcrc->evt_buf, size);
whcrc_enable_events(whcrc);
}
/**
* Catch interrupts?
*
* We ack inmediately (and expect the hw to do the right thing and
* raise another IRQ if things have changed :)
*/
static
irqreturn_t whcrc_irq_cb(int irq, void *_whcrc)
{
struct whcrc *whcrc = _whcrc;
struct device *dev = &whcrc->umc_dev->dev;
u32 urcsts;
urcsts = le_readl(whcrc->rc_base + URCSTS);
if (!(urcsts & URCSTS_INT_MASK))
return IRQ_NONE;
le_writel(urcsts & URCSTS_INT_MASK, whcrc->rc_base + URCSTS);
if (urcsts & URCSTS_HSE) {
dev_err(dev, "host system error -- hardware halted\n");
/* FIXME: do something sensible here */
goto out;
}
if (urcsts & URCSTS_ER)
schedule_work(&whcrc->event_work);
if (urcsts & URCSTS_RCI)
wake_up_all(&whcrc->cmd_wq);
out:
return IRQ_HANDLED;
}
/**
* Initialize a UMC RC interface: map regions, get (shared) IRQ
*/
static
int whcrc_setup_rc_umc(struct whcrc *whcrc)
{
int result = 0;
struct device *dev = &whcrc->umc_dev->dev;
struct umc_dev *umc_dev = whcrc->umc_dev;
whcrc->area = umc_dev->resource.start;
whcrc->rc_len = resource_size(&umc_dev->resource);
result = -EBUSY;
if (request_mem_region(whcrc->area, whcrc->rc_len, KBUILD_MODNAME) == NULL) {
dev_err(dev, "can't request URC region (%zu bytes @ 0x%lx): %d\n",
whcrc->rc_len, whcrc->area, result);
goto error_request_region;
}
whcrc->rc_base = ioremap_nocache(whcrc->area, whcrc->rc_len);
if (whcrc->rc_base == NULL) {
dev_err(dev, "can't ioremap registers (%zu bytes @ 0x%lx): %d\n",
whcrc->rc_len, whcrc->area, result);
goto error_ioremap_nocache;
}
result = request_irq(umc_dev->irq, whcrc_irq_cb, IRQF_SHARED,
KBUILD_MODNAME, whcrc);
if (result < 0) {
dev_err(dev, "can't allocate IRQ %d: %d\n",
umc_dev->irq, result);
goto error_request_irq;
}
result = -ENOMEM;
whcrc->cmd_buf = dma_alloc_coherent(&umc_dev->dev, PAGE_SIZE,
&whcrc->cmd_dma_buf, GFP_KERNEL);
if (whcrc->cmd_buf == NULL) {
dev_err(dev, "Can't allocate cmd transfer buffer\n");
goto error_cmd_buffer;
}
whcrc->evt_buf = dma_alloc_coherent(&umc_dev->dev, PAGE_SIZE,
&whcrc->evt_dma_buf, GFP_KERNEL);
if (whcrc->evt_buf == NULL) {
dev_err(dev, "Can't allocate evt transfer buffer\n");
goto error_evt_buffer;
}
return 0;
error_evt_buffer:
dma_free_coherent(&umc_dev->dev, PAGE_SIZE, whcrc->cmd_buf,
whcrc->cmd_dma_buf);
error_cmd_buffer:
free_irq(umc_dev->irq, whcrc);
error_request_irq:
iounmap(whcrc->rc_base);
error_ioremap_nocache:
release_mem_region(whcrc->area, whcrc->rc_len);
error_request_region:
return result;
}
/**
* Release RC's UMC resources
*/
static
void whcrc_release_rc_umc(struct whcrc *whcrc)
{
struct umc_dev *umc_dev = whcrc->umc_dev;
dma_free_coherent(&umc_dev->dev, PAGE_SIZE, whcrc->evt_buf,
whcrc->evt_dma_buf);
dma_free_coherent(&umc_dev->dev, PAGE_SIZE, whcrc->cmd_buf,
whcrc->cmd_dma_buf);
free_irq(umc_dev->irq, whcrc);
iounmap(whcrc->rc_base);
release_mem_region(whcrc->area, whcrc->rc_len);
}
/**
* whcrc_start_rc - start a WHCI radio controller
* @whcrc: the radio controller to start
*
* Reset the UMC device, start the radio controller, enable events and
* finally enable interrupts.
*/
static int whcrc_start_rc(struct uwb_rc *rc)
{
struct whcrc *whcrc = rc->priv;
struct device *dev = &whcrc->umc_dev->dev;
/* Reset the thing */
le_writel(URCCMD_RESET, whcrc->rc_base + URCCMD);
if (whci_wait_for(dev, whcrc->rc_base + URCCMD, URCCMD_RESET, 0,
5000, "hardware reset") < 0)
return -EBUSY;
/* Set the event buffer, start the controller (enable IRQs later) */
le_writel(0, whcrc->rc_base + URCINTR);
le_writel(URCCMD_RS, whcrc->rc_base + URCCMD);
if (whci_wait_for(dev, whcrc->rc_base + URCSTS, URCSTS_HALTED, 0,
5000, "radio controller start") < 0)
return -ETIMEDOUT;
whcrc_enable_events(whcrc);
le_writel(URCINTR_EN_ALL, whcrc->rc_base + URCINTR);
return 0;
}
/**
* whcrc_stop_rc - stop a WHCI radio controller
* @whcrc: the radio controller to stop
*
* Disable interrupts and cancel any pending event processing work
* before clearing the Run/Stop bit.
*/
static
void whcrc_stop_rc(struct uwb_rc *rc)
{
struct whcrc *whcrc = rc->priv;
struct umc_dev *umc_dev = whcrc->umc_dev;
le_writel(0, whcrc->rc_base + URCINTR);
cancel_work_sync(&whcrc->event_work);
le_writel(0, whcrc->rc_base + URCCMD);
whci_wait_for(&umc_dev->dev, whcrc->rc_base + URCSTS,
URCSTS_HALTED, URCSTS_HALTED, 100, "radio controller stop");
}
static void whcrc_init(struct whcrc *whcrc)
{
spin_lock_init(&whcrc->irq_lock);
init_waitqueue_head(&whcrc->cmd_wq);
INIT_WORK(&whcrc->event_work, whcrc_event_work);
}
/**
* Initialize the radio controller.
*
* NOTE: we setup whcrc->uwb_rc before calling uwb_rc_add(); in the
* IRQ handler we use that to determine if the hw is ready to
* handle events. Looks like a race condition, but it really is
* not.
*/
static
int whcrc_probe(struct umc_dev *umc_dev)
{
int result;
struct uwb_rc *uwb_rc;
struct whcrc *whcrc;
struct device *dev = &umc_dev->dev;
result = -ENOMEM;
uwb_rc = uwb_rc_alloc();
if (uwb_rc == NULL) {
dev_err(dev, "unable to allocate RC instance\n");
goto error_rc_alloc;
}
whcrc = kzalloc(sizeof(*whcrc), GFP_KERNEL);
if (whcrc == NULL) {
dev_err(dev, "unable to allocate WHC-RC instance\n");
goto error_alloc;
}
whcrc_init(whcrc);
whcrc->umc_dev = umc_dev;
result = whcrc_setup_rc_umc(whcrc);
if (result < 0) {
dev_err(dev, "Can't setup RC UMC interface: %d\n", result);
goto error_setup_rc_umc;
}
whcrc->uwb_rc = uwb_rc;
uwb_rc->owner = THIS_MODULE;
uwb_rc->cmd = whcrc_cmd;
uwb_rc->reset = whcrc_reset;
uwb_rc->start = whcrc_start_rc;
uwb_rc->stop = whcrc_stop_rc;
result = uwb_rc_add(uwb_rc, dev, whcrc);
if (result < 0)
goto error_rc_add;
umc_set_drvdata(umc_dev, whcrc);
return 0;
error_rc_add:
whcrc_release_rc_umc(whcrc);
error_setup_rc_umc:
kfree(whcrc);
error_alloc:
uwb_rc_put(uwb_rc);
error_rc_alloc:
return result;
}
/**
* Clean up the radio control resources
*
* When we up the command semaphore, everybody possibly held trying to
* execute a command should be granted entry and then they'll see the
* host is quiescing and up it (so it will chain to the next waiter).
* This should not happen (in any case), as we can only remove when
* there are no handles open...
*/
static void whcrc_remove(struct umc_dev *umc_dev)
{
struct whcrc *whcrc = umc_get_drvdata(umc_dev);
struct uwb_rc *uwb_rc = whcrc->uwb_rc;
umc_set_drvdata(umc_dev, NULL);
uwb_rc_rm(uwb_rc);
whcrc_release_rc_umc(whcrc);
kfree(whcrc);
uwb_rc_put(uwb_rc);
}
static int whcrc_pre_reset(struct umc_dev *umc)
{
struct whcrc *whcrc = umc_get_drvdata(umc);
struct uwb_rc *uwb_rc = whcrc->uwb_rc;
uwb_rc_pre_reset(uwb_rc);
return 0;
}
static int whcrc_post_reset(struct umc_dev *umc)
{
struct whcrc *whcrc = umc_get_drvdata(umc);
struct uwb_rc *uwb_rc = whcrc->uwb_rc;
return uwb_rc_post_reset(uwb_rc);
}
/* PCI device ID's that we handle [so it gets loaded] */
static struct pci_device_id __used whcrc_id_table[] = {
{ PCI_DEVICE_CLASS(PCI_CLASS_WIRELESS_WHCI, ~0) },
{ /* empty last entry */ }
};
MODULE_DEVICE_TABLE(pci, whcrc_id_table);
static struct umc_driver whcrc_driver = {
.name = "whc-rc",
.cap_id = UMC_CAP_ID_WHCI_RC,
.probe = whcrc_probe,
.remove = whcrc_remove,
.pre_reset = whcrc_pre_reset,
.post_reset = whcrc_post_reset,
};
static int __init whcrc_driver_init(void)
{
return umc_driver_register(&whcrc_driver);
}
module_init(whcrc_driver_init);
static void __exit whcrc_driver_exit(void)
{
umc_driver_unregister(&whcrc_driver);
}
module_exit(whcrc_driver_exit);
MODULE_AUTHOR("Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.com>");
MODULE_DESCRIPTION("Wireless Host Controller Radio Control Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Fagyi/kernel_msm_hammerhead | arch/powerpc/sysdev/micropatch.c | 11209 | 11485 |
/* Microcode patches for the CPM as supplied by Motorola.
* This is the one for IIC/SPI. There is a newer one that
* also relocates SMC2, but this would require additional changes
* to uart.c, so I am holding off on that for a moment.
*/
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/param.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <asm/irq.h>
#include <asm/mpc8xx.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/8xx_immap.h>
#include <asm/cpm.h>
#include <asm/cpm1.h>
/*
* I2C/SPI relocation patch arrays.
*/
#ifdef CONFIG_I2C_SPI_UCODE_PATCH
static uint patch_2000[] __initdata = {
0x7FFFEFD9,
0x3FFD0000,
0x7FFB49F7,
0x7FF90000,
0x5FEFADF7,
0x5F89ADF7,
0x5FEFAFF7,
0x5F89AFF7,
0x3A9CFBC8,
0xE7C0EDF0,
0x77C1E1BB,
0xF4DC7F1D,
0xABAD932F,
0x4E08FDCF,
0x6E0FAFF8,
0x7CCF76CF,
0xFD1FF9CF,
0xABF88DC6,
0xAB5679F7,
0xB0937383,
0xDFCE79F7,
0xB091E6BB,
0xE5BBE74F,
0xB3FA6F0F,
0x6FFB76CE,
0xEE0DF9CF,
0x2BFBEFEF,
0xCFEEF9CF,
0x76CEAD24,
0x90B2DF9A,
0x7FDDD0BF,
0x4BF847FD,
0x7CCF76CE,
0xCFEF7E1F,
0x7F1D7DFD,
0xF0B6EF71,
0x7FC177C1,
0xFBC86079,
0xE722FBC8,
0x5FFFDFFF,
0x5FB2FFFB,
0xFBC8F3C8,
0x94A67F01,
0x7F1D5F39,
0xAFE85F5E,
0xFFDFDF96,
0xCB9FAF7D,
0x5FC1AFED,
0x8C1C5FC1,
0xAFDD5FC3,
0xDF9A7EFD,
0xB0B25FB2,
0xFFFEABAD,
0x5FB2FFFE,
0x5FCE600B,
0xE6BB600B,
0x5FCEDFC6,
0x27FBEFDF,
0x5FC8CFDE,
0x3A9CE7C0,
0xEDF0F3C8,
0x7F0154CD,
0x7F1D2D3D,
0x363A7570,
0x7E0AF1CE,
0x37EF2E68,
0x7FEE10EC,
0xADF8EFDE,
0xCFEAE52F,
0x7D0FE12B,
0xF1CE5F65,
0x7E0A4DF8,
0xCFEA5F72,
0x7D0BEFEE,
0xCFEA5F74,
0xE522EFDE,
0x5F74CFDA,
0x0B627385,
0xDF627E0A,
0x30D8145B,
0xBFFFF3C8,
0x5FFFDFFF,
0xA7F85F5E,
0xBFFE7F7D,
0x10D31450,
0x5F36BFFF,
0xAF785F5E,
0xBFFDA7F8,
0x5F36BFFE,
0x77FD30C0,
0x4E08FDCF,
0xE5FF6E0F,
0xAFF87E1F,
0x7E0FFD1F,
0xF1CF5F1B,
0xABF80D5E,
0x5F5EFFEF,
0x79F730A2,
0xAFDD5F34,
0x47F85F34,
0xAFED7FDD,
0x50B24978,
0x47FD7F1D,
0x7DFD70AD,
0xEF717EC1,
0x6BA47F01,
0x2D267EFD,
0x30DE5F5E,
0xFFFD5F5E,
0xFFEF5F5E,
0xFFDF0CA0,
0xAFED0A9E,
0xAFDD0C3A,
0x5F3AAFBD,
0x7FBDB082,
0x5F8247F8
};
static uint patch_2f00[] __initdata = {
0x3E303430,
0x34343737,
0xABF7BF9B,
0x994B4FBD,
0xBD599493,
0x349FFF37,
0xFB9B177D,
0xD9936956,
0xBBFDD697,
0xBDD2FD11,
0x31DB9BB3,
0x63139637,
0x93733693,
0x193137F7,
0x331737AF,
0x7BB9B999,
0xBB197957,
0x7FDFD3D5,
0x73B773F7,
0x37933B99,
0x1D115316,
0x99315315,
0x31694BF4,
0xFBDBD359,
0x31497353,
0x76956D69,
0x7B9D9693,
0x13131979,
0x79376935
};
#endif
/*
* I2C/SPI/SMC1 relocation patch arrays.
*/
#ifdef CONFIG_I2C_SPI_SMC1_UCODE_PATCH
static uint patch_2000[] __initdata = {
0x3fff0000,
0x3ffd0000,
0x3ffb0000,
0x3ff90000,
0x5f13eff8,
0x5eb5eff8,
0x5f88adf7,
0x5fefadf7,
0x3a9cfbc8,
0x77cae1bb,
0xf4de7fad,
0xabae9330,
0x4e08fdcf,
0x6e0faff8,
0x7ccf76cf,
0xfdaff9cf,
0xabf88dc8,
0xab5879f7,
0xb0925d8d,
0xdfd079f7,
0xb090e6bb,
0xe5bbe74f,
0x9e046f0f,
0x6ffb76ce,
0xee0cf9cf,
0x2bfbefef,
0xcfeef9cf,
0x76cead23,
0x90b3df99,
0x7fddd0c1,
0x4bf847fd,
0x7ccf76ce,
0xcfef77ca,
0x7eaf7fad,
0x7dfdf0b7,
0xef7a7fca,
0x77cafbc8,
0x6079e722,
0xfbc85fff,
0xdfff5fb3,
0xfffbfbc8,
0xf3c894a5,
0xe7c9edf9,
0x7f9a7fad,
0x5f36afe8,
0x5f5bffdf,
0xdf95cb9e,
0xaf7d5fc3,
0xafed8c1b,
0x5fc3afdd,
0x5fc5df99,
0x7efdb0b3,
0x5fb3fffe,
0xabae5fb3,
0xfffe5fd0,
0x600be6bb,
0x600b5fd0,
0xdfc827fb,
0xefdf5fca,
0xcfde3a9c,
0xe7c9edf9,
0xf3c87f9e,
0x54ca7fed,
0x2d3a3637,
0x756f7e9a,
0xf1ce37ef,
0x2e677fee,
0x10ebadf8,
0xefdecfea,
0xe52f7d9f,
0xe12bf1ce,
0x5f647e9a,
0x4df8cfea,
0x5f717d9b,
0xefeecfea,
0x5f73e522,
0xefde5f73,
0xcfda0b61,
0x5d8fdf61,
0xe7c9edf9,
0x7e9a30d5,
0x1458bfff,
0xf3c85fff,
0xdfffa7f8,
0x5f5bbffe,
0x7f7d10d0,
0x144d5f33,
0xbfffaf78,
0x5f5bbffd,
0xa7f85f33,
0xbffe77fd,
0x30bd4e08,
0xfdcfe5ff,
0x6e0faff8,
0x7eef7e9f,
0xfdeff1cf,
0x5f17abf8,
0x0d5b5f5b,
0xffef79f7,
0x309eafdd,
0x5f3147f8,
0x5f31afed,
0x7fdd50af,
0x497847fd,
0x7f9e7fed,
0x7dfd70a9,
0xef7e7ece,
0x6ba07f9e,
0x2d227efd,
0x30db5f5b,
0xfffd5f5b,
0xffef5f5b,
0xffdf0c9c,
0xafed0a9a,
0xafdd0c37,
0x5f37afbd,
0x7fbdb081,
0x5f8147f8,
0x3a11e710,
0xedf0ccdd,
0xf3186d0a,
0x7f0e5f06,
0x7fedbb38,
0x3afe7468,
0x7fedf4fc,
0x8ffbb951,
0xb85f77fd,
0xb0df5ddd,
0xdefe7fed,
0x90e1e74d,
0x6f0dcbf7,
0xe7decfed,
0xcb74cfed,
0xcfeddf6d,
0x91714f74,
0x5dd2deef,
0x9e04e7df,
0xefbb6ffb,
0xe7ef7f0e,
0x9e097fed,
0xebdbeffa,
0xeb54affb,
0x7fea90d7,
0x7e0cf0c3,
0xbffff318,
0x5fffdfff,
0xac59efea,
0x7fce1ee5,
0xe2ff5ee1,
0xaffbe2ff,
0x5ee3affb,
0xf9cc7d0f,
0xaef8770f,
0x7d0fb0c6,
0xeffbbfff,
0xcfef5ede,
0x7d0fbfff,
0x5ede4cf8,
0x7fddd0bf,
0x49f847fd,
0x7efdf0bb,
0x7fedfffd,
0x7dfdf0b7,
0xef7e7e1e,
0x5ede7f0e,
0x3a11e710,
0xedf0ccab,
0xfb18ad2e,
0x1ea9bbb8,
0x74283b7e,
0x73c2e4bb,
0x2ada4fb8,
0xdc21e4bb,
0xb2a1ffbf,
0x5e2c43f8,
0xfc87e1bb,
0xe74ffd91,
0x6f0f4fe8,
0xc7ba32e2,
0xf396efeb,
0x600b4f78,
0xe5bb760b,
0x53acaef8,
0x4ef88b0e,
0xcfef9e09,
0xabf8751f,
0xefef5bac,
0x741f4fe8,
0x751e760d,
0x7fdbf081,
0x741cafce,
0xefcc7fce,
0x751e70ac,
0x741ce7bb,
0x3372cfed,
0xafdbefeb,
0xe5bb760b,
0x53f2aef8,
0xafe8e7eb,
0x4bf8771e,
0x7e247fed,
0x4fcbe2cc,
0x7fbc30a9,
0x7b0f7a0f,
0x34d577fd,
0x308b5db7,
0xde553e5f,
0xaf78741f,
0x741f30f0,
0xcfef5e2c,
0x741f3eac,
0xafb8771e,
0x5e677fed,
0x0bd3e2cc,
0x741ccfec,
0xe5ca53cd,
0x6fcb4f74,
0x5dadde4b,
0x2ab63d38,
0x4bb3de30,
0x751f741c,
0x6c42effa,
0xefea7fce,
0x6ffc30be,
0xefec3fca,
0x30b3de2e,
0xadf85d9e,
0xaf7daefd,
0x5d9ede2e,
0x5d9eafdd,
0x761f10ac,
0x1da07efd,
0x30adfffe,
0x4908fb18,
0x5fffdfff,
0xafbb709b,
0x4ef85e67,
0xadf814ad,
0x7a0f70ad,
0xcfef50ad,
0x7a0fde30,
0x5da0afed,
0x3c12780f,
0xefef780f,
0xefef790f,
0xa7f85e0f,
0xffef790f,
0xefef790f,
0x14adde2e,
0x5d9eadfd,
0x5e2dfffb,
0xe79addfd,
0xeff96079,
0x607ae79a,
0xddfceff9,
0x60795dff,
0x607acfef,
0xefefefdf,
0xefbfef7f,
0xeeffedff,
0xebffe7ff,
0xafefafdf,
0xafbfaf7f,
0xaeffadff,
0xabffa7ff,
0x6fef6fdf,
0x6fbf6f7f,
0x6eff6dff,
0x6bff67ff,
0x2fef2fdf,
0x2fbf2f7f,
0x2eff2dff,
0x2bff27ff,
0x4e08fd1f,
0xe5ff6e0f,
0xaff87eef,
0x7e0ffdef,
0xf11f6079,
0xabf8f542,
0x7e0af11c,
0x37cfae3a,
0x7fec90be,
0xadf8efdc,
0xcfeae52f,
0x7d0fe12b,
0xf11c6079,
0x7e0a4df8,
0xcfea5dc4,
0x7d0befec,
0xcfea5dc6,
0xe522efdc,
0x5dc6cfda,
0x4e08fd1f,
0x6e0faff8,
0x7c1f761f,
0xfdeff91f,
0x6079abf8,
0x761cee24,
0xf91f2bfb,
0xefefcfec,
0xf91f6079,
0x761c27fb,
0xefdf5da7,
0xcfdc7fdd,
0xd09c4bf8,
0x47fd7c1f,
0x761ccfcf,
0x7eef7fed,
0x7dfdf093,
0xef7e7f1e,
0x771efb18,
0x6079e722,
0xe6bbe5bb,
0xae0ae5bb,
0x600bae85,
0xe2bbe2bb,
0xe2bbe2bb,
0xaf02e2bb,
0xe2bb2ff9,
0x6079e2bb
};
static uint patch_2f00[] __initdata = {
0x30303030,
0x3e3e3434,
0xabbf9b99,
0x4b4fbdbd,
0x59949334,
0x9fff37fb,
0x9b177dd9,
0x936956bb,
0xfbdd697b,
0xdd2fd113,
0x1db9f7bb,
0x36313963,
0x79373369,
0x3193137f,
0x7331737a,
0xf7bb9b99,
0x9bb19795,
0x77fdfd3d,
0x573b773f,
0x737933f7,
0xb991d115,
0x31699315,
0x31531694,
0xbf4fbdbd,
0x35931497,
0x35376956,
0xbd697b9d,
0x96931313,
0x19797937,
0x6935af78,
0xb9b3baa3,
0xb8788683,
0x368f78f7,
0x87778733,
0x3ffffb3b,
0x8e8f78b8,
0x1d118e13,
0xf3ff3f8b,
0x6bd8e173,
0xd1366856,
0x68d1687b,
0x3daf78b8,
0x3a3a3f87,
0x8f81378f,
0xf876f887,
0x77fd8778,
0x737de8d6,
0xbbf8bfff,
0xd8df87f7,
0xfd876f7b,
0x8bfff8bd,
0x8683387d,
0xb873d87b,
0x3b8fd7f8,
0xf7338883,
0xbb8ee1f8,
0xef837377,
0x3337b836,
0x817d11f8,
0x7378b878,
0xd3368b7d,
0xed731b7d,
0x833731f3,
0xf22f3f23
};
static uint patch_2e00[] __initdata = {
0x27eeeeee,
0xeeeeeeee,
0xeeeeeeee,
0xeeeeeeee,
0xee4bf4fb,
0xdbd259bb,
0x1979577f,
0xdfd2d573,
0xb773f737,
0x4b4fbdbd,
0x25b9b177,
0xd2d17376,
0x956bbfdd,
0x697bdd2f,
0xff9f79ff,
0xff9ff22f
};
#endif
/*
* USB SOF patch arrays.
*/
#ifdef CONFIG_USB_SOF_UCODE_PATCH
static uint patch_2000[] __initdata = {
0x7fff0000,
0x7ffd0000,
0x7ffb0000,
0x49f7ba5b,
0xba383ffb,
0xf9b8b46d,
0xe5ab4e07,
0xaf77bffe,
0x3f7bbf79,
0xba5bba38,
0xe7676076,
0x60750000
};
static uint patch_2f00[] __initdata = {
0x3030304c,
0xcab9e441,
0xa1aaf220
};
#endif
void __init cpm_load_patch(cpm8xx_t *cp)
{
volatile uint *dp; /* Dual-ported RAM. */
volatile cpm8xx_t *commproc;
#if defined(CONFIG_I2C_SPI_UCODE_PATCH) || \
defined(CONFIG_I2C_SPI_SMC1_UCODE_PATCH)
volatile iic_t *iip;
volatile struct spi_pram *spp;
#ifdef CONFIG_I2C_SPI_SMC1_UCODE_PATCH
volatile smc_uart_t *smp;
#endif
#endif
int i;
commproc = cp;
#ifdef CONFIG_USB_SOF_UCODE_PATCH
commproc->cp_rccr = 0;
dp = (uint *)(commproc->cp_dpmem);
for (i=0; i<(sizeof(patch_2000)/4); i++)
*dp++ = patch_2000[i];
dp = (uint *)&(commproc->cp_dpmem[0x0f00]);
for (i=0; i<(sizeof(patch_2f00)/4); i++)
*dp++ = patch_2f00[i];
commproc->cp_rccr = 0x0009;
printk("USB SOF microcode patch installed\n");
#endif /* CONFIG_USB_SOF_UCODE_PATCH */
#if defined(CONFIG_I2C_SPI_UCODE_PATCH) || \
defined(CONFIG_I2C_SPI_SMC1_UCODE_PATCH)
commproc->cp_rccr = 0;
dp = (uint *)(commproc->cp_dpmem);
for (i=0; i<(sizeof(patch_2000)/4); i++)
*dp++ = patch_2000[i];
dp = (uint *)&(commproc->cp_dpmem[0x0f00]);
for (i=0; i<(sizeof(patch_2f00)/4); i++)
*dp++ = patch_2f00[i];
iip = (iic_t *)&commproc->cp_dparam[PROFF_IIC];
# define RPBASE 0x0500
iip->iic_rpbase = RPBASE;
/* Put SPI above the IIC, also 32-byte aligned.
*/
i = (RPBASE + sizeof(iic_t) + 31) & ~31;
spp = (struct spi_pram *)&commproc->cp_dparam[PROFF_SPI];
spp->rpbase = i;
# if defined(CONFIG_I2C_SPI_UCODE_PATCH)
commproc->cp_cpmcr1 = 0x802a;
commproc->cp_cpmcr2 = 0x8028;
commproc->cp_cpmcr3 = 0x802e;
commproc->cp_cpmcr4 = 0x802c;
commproc->cp_rccr = 1;
printk("I2C/SPI microcode patch installed.\n");
# endif /* CONFIG_I2C_SPI_UCODE_PATCH */
# if defined(CONFIG_I2C_SPI_SMC1_UCODE_PATCH)
dp = (uint *)&(commproc->cp_dpmem[0x0e00]);
for (i=0; i<(sizeof(patch_2e00)/4); i++)
*dp++ = patch_2e00[i];
commproc->cp_cpmcr1 = 0x8080;
commproc->cp_cpmcr2 = 0x808a;
commproc->cp_cpmcr3 = 0x8028;
commproc->cp_cpmcr4 = 0x802a;
commproc->cp_rccr = 3;
smp = (smc_uart_t *)&commproc->cp_dparam[PROFF_SMC1];
smp->smc_rpbase = 0x1FC0;
printk("I2C/SPI/SMC1 microcode patch installed.\n");
# endif /* CONFIG_I2C_SPI_SMC1_UCODE_PATCH) */
#endif /* some variation of the I2C/SPI patch was selected */
}
/*
* Take this entire routine out, since no one calls it and its
* logic is suspect.
*/
#if 0
void
verify_patch(volatile immap_t *immr)
{
volatile uint *dp;
volatile cpm8xx_t *commproc;
int i;
commproc = (cpm8xx_t *)&immr->im_cpm;
printk("cp_rccr %x\n", commproc->cp_rccr);
commproc->cp_rccr = 0;
dp = (uint *)(commproc->cp_dpmem);
for (i=0; i<(sizeof(patch_2000)/4); i++)
if (*dp++ != patch_2000[i]) {
printk("patch_2000 bad at %d\n", i);
dp--;
printk("found 0x%X, wanted 0x%X\n", *dp, patch_2000[i]);
break;
}
dp = (uint *)&(commproc->cp_dpmem[0x0f00]);
for (i=0; i<(sizeof(patch_2f00)/4); i++)
if (*dp++ != patch_2f00[i]) {
printk("patch_2f00 bad at %d\n", i);
dp--;
printk("found 0x%X, wanted 0x%X\n", *dp, patch_2f00[i]);
break;
}
commproc->cp_rccr = 0x0009;
}
#endif
| gpl-2.0 |
TRKP/android_kernel_samsung_s5312 | arch/sh/mm/tlbflush_32.c | 13001 | 3288 | /*
* TLB flushing operations for SH with an MMU.
*
* Copyright (C) 1999 Niibe Yutaka
* Copyright (C) 2003 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/mm.h>
#include <asm/mmu_context.h>
#include <asm/tlbflush.h>
void local_flush_tlb_page(struct vm_area_struct *vma, unsigned long page)
{
unsigned int cpu = smp_processor_id();
if (vma->vm_mm && cpu_context(cpu, vma->vm_mm) != NO_CONTEXT) {
unsigned long flags;
unsigned long asid;
unsigned long saved_asid = MMU_NO_ASID;
asid = cpu_asid(cpu, vma->vm_mm);
page &= PAGE_MASK;
local_irq_save(flags);
if (vma->vm_mm != current->mm) {
saved_asid = get_asid();
set_asid(asid);
}
local_flush_tlb_one(asid, page);
if (saved_asid != MMU_NO_ASID)
set_asid(saved_asid);
local_irq_restore(flags);
}
}
void local_flush_tlb_range(struct vm_area_struct *vma, unsigned long start,
unsigned long end)
{
struct mm_struct *mm = vma->vm_mm;
unsigned int cpu = smp_processor_id();
if (cpu_context(cpu, mm) != NO_CONTEXT) {
unsigned long flags;
int size;
local_irq_save(flags);
size = (end - start + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
if (size > (MMU_NTLB_ENTRIES/4)) { /* Too many TLB to flush */
cpu_context(cpu, mm) = NO_CONTEXT;
if (mm == current->mm)
activate_context(mm, cpu);
} else {
unsigned long asid;
unsigned long saved_asid = MMU_NO_ASID;
asid = cpu_asid(cpu, mm);
start &= PAGE_MASK;
end += (PAGE_SIZE - 1);
end &= PAGE_MASK;
if (mm != current->mm) {
saved_asid = get_asid();
set_asid(asid);
}
while (start < end) {
local_flush_tlb_one(asid, start);
start += PAGE_SIZE;
}
if (saved_asid != MMU_NO_ASID)
set_asid(saved_asid);
}
local_irq_restore(flags);
}
}
void local_flush_tlb_kernel_range(unsigned long start, unsigned long end)
{
unsigned int cpu = smp_processor_id();
unsigned long flags;
int size;
local_irq_save(flags);
size = (end - start + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
if (size > (MMU_NTLB_ENTRIES/4)) { /* Too many TLB to flush */
local_flush_tlb_all();
} else {
unsigned long asid;
unsigned long saved_asid = get_asid();
asid = cpu_asid(cpu, &init_mm);
start &= PAGE_MASK;
end += (PAGE_SIZE - 1);
end &= PAGE_MASK;
set_asid(asid);
while (start < end) {
local_flush_tlb_one(asid, start);
start += PAGE_SIZE;
}
set_asid(saved_asid);
}
local_irq_restore(flags);
}
void local_flush_tlb_mm(struct mm_struct *mm)
{
unsigned int cpu = smp_processor_id();
/* Invalidate all TLB of this process. */
/* Instead of invalidating each TLB, we get new MMU context. */
if (cpu_context(cpu, mm) != NO_CONTEXT) {
unsigned long flags;
local_irq_save(flags);
cpu_context(cpu, mm) = NO_CONTEXT;
if (mm == current->mm)
activate_context(mm, cpu);
local_irq_restore(flags);
}
}
void __flush_tlb_global(void)
{
unsigned long flags;
local_irq_save(flags);
/*
* This is the most destructive of the TLB flushing options,
* and will tear down all of the UTLB/ITLB mappings, including
* wired entries.
*/
__raw_writel(__raw_readl(MMUCR) | MMUCR_TI, MMUCR);
local_irq_restore(flags);
}
| gpl-2.0 |
delaemon/linux | drivers/dma/ioat/init.c | 202 | 36224 | /*
* Intel I/OAT DMA Linux driver
* Copyright(c) 2004 - 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 that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* The full GNU General Public License is included in this distribution in
* the file called "COPYING".
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/interrupt.h>
#include <linux/dmaengine.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/workqueue.h>
#include <linux/prefetch.h>
#include <linux/dca.h>
#include "dma.h"
#include "registers.h"
#include "hw.h"
#include "../dmaengine.h"
MODULE_VERSION(IOAT_DMA_VERSION);
MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("Intel Corporation");
static struct pci_device_id ioat_pci_tbl[] = {
/* I/OAT v3 platforms */
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_TBG0) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_TBG1) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_TBG2) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_TBG3) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_TBG4) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_TBG5) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_TBG6) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_TBG7) },
/* I/OAT v3.2 platforms */
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_JSF0) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_JSF1) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_JSF2) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_JSF3) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_JSF4) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_JSF5) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_JSF6) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_JSF7) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_JSF8) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_JSF9) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_SNB0) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_SNB1) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_SNB2) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_SNB3) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_SNB4) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_SNB5) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_SNB6) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_SNB7) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_SNB8) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_SNB9) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_IVB0) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_IVB1) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_IVB2) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_IVB3) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_IVB4) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_IVB5) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_IVB6) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_IVB7) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_IVB8) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_IVB9) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_HSW0) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_HSW1) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_HSW2) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_HSW3) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_HSW4) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_HSW5) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_HSW6) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_HSW7) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_HSW8) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_HSW9) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BDX0) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BDX1) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BDX2) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BDX3) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BDX4) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BDX5) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BDX6) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BDX7) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BDX8) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BDX9) },
/* I/OAT v3.3 platforms */
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BWD0) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BWD1) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BWD2) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BWD3) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BDXDE0) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BDXDE1) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BDXDE2) },
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_IOAT_BDXDE3) },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, ioat_pci_tbl);
static int ioat_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id);
static void ioat_remove(struct pci_dev *pdev);
static void
ioat_init_channel(struct ioatdma_device *ioat_dma,
struct ioatdma_chan *ioat_chan, int idx);
static void ioat_intr_quirk(struct ioatdma_device *ioat_dma);
static int ioat_enumerate_channels(struct ioatdma_device *ioat_dma);
static int ioat3_dma_self_test(struct ioatdma_device *ioat_dma);
static int ioat_dca_enabled = 1;
module_param(ioat_dca_enabled, int, 0644);
MODULE_PARM_DESC(ioat_dca_enabled, "control support of dca service (default: 1)");
int ioat_pending_level = 4;
module_param(ioat_pending_level, int, 0644);
MODULE_PARM_DESC(ioat_pending_level,
"high-water mark for pushing ioat descriptors (default: 4)");
int ioat_ring_alloc_order = 8;
module_param(ioat_ring_alloc_order, int, 0644);
MODULE_PARM_DESC(ioat_ring_alloc_order,
"ioat+: allocate 2^n descriptors per channel (default: 8 max: 16)");
int ioat_ring_max_alloc_order = IOAT_MAX_ORDER;
module_param(ioat_ring_max_alloc_order, int, 0644);
MODULE_PARM_DESC(ioat_ring_max_alloc_order,
"ioat+: upper limit for ring size (default: 16)");
static char ioat_interrupt_style[32] = "msix";
module_param_string(ioat_interrupt_style, ioat_interrupt_style,
sizeof(ioat_interrupt_style), 0644);
MODULE_PARM_DESC(ioat_interrupt_style,
"set ioat interrupt style: msix (default), msi, intx");
struct kmem_cache *ioat_cache;
struct kmem_cache *ioat_sed_cache;
static bool is_jf_ioat(struct pci_dev *pdev)
{
switch (pdev->device) {
case PCI_DEVICE_ID_INTEL_IOAT_JSF0:
case PCI_DEVICE_ID_INTEL_IOAT_JSF1:
case PCI_DEVICE_ID_INTEL_IOAT_JSF2:
case PCI_DEVICE_ID_INTEL_IOAT_JSF3:
case PCI_DEVICE_ID_INTEL_IOAT_JSF4:
case PCI_DEVICE_ID_INTEL_IOAT_JSF5:
case PCI_DEVICE_ID_INTEL_IOAT_JSF6:
case PCI_DEVICE_ID_INTEL_IOAT_JSF7:
case PCI_DEVICE_ID_INTEL_IOAT_JSF8:
case PCI_DEVICE_ID_INTEL_IOAT_JSF9:
return true;
default:
return false;
}
}
static bool is_snb_ioat(struct pci_dev *pdev)
{
switch (pdev->device) {
case PCI_DEVICE_ID_INTEL_IOAT_SNB0:
case PCI_DEVICE_ID_INTEL_IOAT_SNB1:
case PCI_DEVICE_ID_INTEL_IOAT_SNB2:
case PCI_DEVICE_ID_INTEL_IOAT_SNB3:
case PCI_DEVICE_ID_INTEL_IOAT_SNB4:
case PCI_DEVICE_ID_INTEL_IOAT_SNB5:
case PCI_DEVICE_ID_INTEL_IOAT_SNB6:
case PCI_DEVICE_ID_INTEL_IOAT_SNB7:
case PCI_DEVICE_ID_INTEL_IOAT_SNB8:
case PCI_DEVICE_ID_INTEL_IOAT_SNB9:
return true;
default:
return false;
}
}
static bool is_ivb_ioat(struct pci_dev *pdev)
{
switch (pdev->device) {
case PCI_DEVICE_ID_INTEL_IOAT_IVB0:
case PCI_DEVICE_ID_INTEL_IOAT_IVB1:
case PCI_DEVICE_ID_INTEL_IOAT_IVB2:
case PCI_DEVICE_ID_INTEL_IOAT_IVB3:
case PCI_DEVICE_ID_INTEL_IOAT_IVB4:
case PCI_DEVICE_ID_INTEL_IOAT_IVB5:
case PCI_DEVICE_ID_INTEL_IOAT_IVB6:
case PCI_DEVICE_ID_INTEL_IOAT_IVB7:
case PCI_DEVICE_ID_INTEL_IOAT_IVB8:
case PCI_DEVICE_ID_INTEL_IOAT_IVB9:
return true;
default:
return false;
}
}
static bool is_hsw_ioat(struct pci_dev *pdev)
{
switch (pdev->device) {
case PCI_DEVICE_ID_INTEL_IOAT_HSW0:
case PCI_DEVICE_ID_INTEL_IOAT_HSW1:
case PCI_DEVICE_ID_INTEL_IOAT_HSW2:
case PCI_DEVICE_ID_INTEL_IOAT_HSW3:
case PCI_DEVICE_ID_INTEL_IOAT_HSW4:
case PCI_DEVICE_ID_INTEL_IOAT_HSW5:
case PCI_DEVICE_ID_INTEL_IOAT_HSW6:
case PCI_DEVICE_ID_INTEL_IOAT_HSW7:
case PCI_DEVICE_ID_INTEL_IOAT_HSW8:
case PCI_DEVICE_ID_INTEL_IOAT_HSW9:
return true;
default:
return false;
}
}
static bool is_bdx_ioat(struct pci_dev *pdev)
{
switch (pdev->device) {
case PCI_DEVICE_ID_INTEL_IOAT_BDX0:
case PCI_DEVICE_ID_INTEL_IOAT_BDX1:
case PCI_DEVICE_ID_INTEL_IOAT_BDX2:
case PCI_DEVICE_ID_INTEL_IOAT_BDX3:
case PCI_DEVICE_ID_INTEL_IOAT_BDX4:
case PCI_DEVICE_ID_INTEL_IOAT_BDX5:
case PCI_DEVICE_ID_INTEL_IOAT_BDX6:
case PCI_DEVICE_ID_INTEL_IOAT_BDX7:
case PCI_DEVICE_ID_INTEL_IOAT_BDX8:
case PCI_DEVICE_ID_INTEL_IOAT_BDX9:
return true;
default:
return false;
}
}
static bool is_xeon_cb32(struct pci_dev *pdev)
{
return is_jf_ioat(pdev) || is_snb_ioat(pdev) || is_ivb_ioat(pdev) ||
is_hsw_ioat(pdev) || is_bdx_ioat(pdev);
}
bool is_bwd_ioat(struct pci_dev *pdev)
{
switch (pdev->device) {
case PCI_DEVICE_ID_INTEL_IOAT_BWD0:
case PCI_DEVICE_ID_INTEL_IOAT_BWD1:
case PCI_DEVICE_ID_INTEL_IOAT_BWD2:
case PCI_DEVICE_ID_INTEL_IOAT_BWD3:
/* even though not Atom, BDX-DE has same DMA silicon */
case PCI_DEVICE_ID_INTEL_IOAT_BDXDE0:
case PCI_DEVICE_ID_INTEL_IOAT_BDXDE1:
case PCI_DEVICE_ID_INTEL_IOAT_BDXDE2:
case PCI_DEVICE_ID_INTEL_IOAT_BDXDE3:
return true;
default:
return false;
}
}
static bool is_bwd_noraid(struct pci_dev *pdev)
{
switch (pdev->device) {
case PCI_DEVICE_ID_INTEL_IOAT_BWD2:
case PCI_DEVICE_ID_INTEL_IOAT_BWD3:
case PCI_DEVICE_ID_INTEL_IOAT_BDXDE0:
case PCI_DEVICE_ID_INTEL_IOAT_BDXDE1:
case PCI_DEVICE_ID_INTEL_IOAT_BDXDE2:
case PCI_DEVICE_ID_INTEL_IOAT_BDXDE3:
return true;
default:
return false;
}
}
/*
* Perform a IOAT transaction to verify the HW works.
*/
#define IOAT_TEST_SIZE 2000
static void ioat_dma_test_callback(void *dma_async_param)
{
struct completion *cmp = dma_async_param;
complete(cmp);
}
/**
* ioat_dma_self_test - Perform a IOAT transaction to verify the HW works.
* @ioat_dma: dma device to be tested
*/
static int ioat_dma_self_test(struct ioatdma_device *ioat_dma)
{
int i;
u8 *src;
u8 *dest;
struct dma_device *dma = &ioat_dma->dma_dev;
struct device *dev = &ioat_dma->pdev->dev;
struct dma_chan *dma_chan;
struct dma_async_tx_descriptor *tx;
dma_addr_t dma_dest, dma_src;
dma_cookie_t cookie;
int err = 0;
struct completion cmp;
unsigned long tmo;
unsigned long flags;
src = kzalloc(sizeof(u8) * IOAT_TEST_SIZE, GFP_KERNEL);
if (!src)
return -ENOMEM;
dest = kzalloc(sizeof(u8) * IOAT_TEST_SIZE, GFP_KERNEL);
if (!dest) {
kfree(src);
return -ENOMEM;
}
/* Fill in src buffer */
for (i = 0; i < IOAT_TEST_SIZE; i++)
src[i] = (u8)i;
/* Start copy, using first DMA channel */
dma_chan = container_of(dma->channels.next, struct dma_chan,
device_node);
if (dma->device_alloc_chan_resources(dma_chan) < 1) {
dev_err(dev, "selftest cannot allocate chan resource\n");
err = -ENODEV;
goto out;
}
dma_src = dma_map_single(dev, src, IOAT_TEST_SIZE, DMA_TO_DEVICE);
if (dma_mapping_error(dev, dma_src)) {
dev_err(dev, "mapping src buffer failed\n");
goto free_resources;
}
dma_dest = dma_map_single(dev, dest, IOAT_TEST_SIZE, DMA_FROM_DEVICE);
if (dma_mapping_error(dev, dma_dest)) {
dev_err(dev, "mapping dest buffer failed\n");
goto unmap_src;
}
flags = DMA_PREP_INTERRUPT;
tx = ioat_dma->dma_dev.device_prep_dma_memcpy(dma_chan, dma_dest,
dma_src, IOAT_TEST_SIZE,
flags);
if (!tx) {
dev_err(dev, "Self-test prep failed, disabling\n");
err = -ENODEV;
goto unmap_dma;
}
async_tx_ack(tx);
init_completion(&cmp);
tx->callback = ioat_dma_test_callback;
tx->callback_param = &cmp;
cookie = tx->tx_submit(tx);
if (cookie < 0) {
dev_err(dev, "Self-test setup failed, disabling\n");
err = -ENODEV;
goto unmap_dma;
}
dma->device_issue_pending(dma_chan);
tmo = wait_for_completion_timeout(&cmp, msecs_to_jiffies(3000));
if (tmo == 0 ||
dma->device_tx_status(dma_chan, cookie, NULL)
!= DMA_COMPLETE) {
dev_err(dev, "Self-test copy timed out, disabling\n");
err = -ENODEV;
goto unmap_dma;
}
if (memcmp(src, dest, IOAT_TEST_SIZE)) {
dev_err(dev, "Self-test copy failed compare, disabling\n");
err = -ENODEV;
goto free_resources;
}
unmap_dma:
dma_unmap_single(dev, dma_dest, IOAT_TEST_SIZE, DMA_FROM_DEVICE);
unmap_src:
dma_unmap_single(dev, dma_src, IOAT_TEST_SIZE, DMA_TO_DEVICE);
free_resources:
dma->device_free_chan_resources(dma_chan);
out:
kfree(src);
kfree(dest);
return err;
}
/**
* ioat_dma_setup_interrupts - setup interrupt handler
* @ioat_dma: ioat dma device
*/
int ioat_dma_setup_interrupts(struct ioatdma_device *ioat_dma)
{
struct ioatdma_chan *ioat_chan;
struct pci_dev *pdev = ioat_dma->pdev;
struct device *dev = &pdev->dev;
struct msix_entry *msix;
int i, j, msixcnt;
int err = -EINVAL;
u8 intrctrl = 0;
if (!strcmp(ioat_interrupt_style, "msix"))
goto msix;
if (!strcmp(ioat_interrupt_style, "msi"))
goto msi;
if (!strcmp(ioat_interrupt_style, "intx"))
goto intx;
dev_err(dev, "invalid ioat_interrupt_style %s\n", ioat_interrupt_style);
goto err_no_irq;
msix:
/* The number of MSI-X vectors should equal the number of channels */
msixcnt = ioat_dma->dma_dev.chancnt;
for (i = 0; i < msixcnt; i++)
ioat_dma->msix_entries[i].entry = i;
err = pci_enable_msix_exact(pdev, ioat_dma->msix_entries, msixcnt);
if (err)
goto msi;
for (i = 0; i < msixcnt; i++) {
msix = &ioat_dma->msix_entries[i];
ioat_chan = ioat_chan_by_index(ioat_dma, i);
err = devm_request_irq(dev, msix->vector,
ioat_dma_do_interrupt_msix, 0,
"ioat-msix", ioat_chan);
if (err) {
for (j = 0; j < i; j++) {
msix = &ioat_dma->msix_entries[j];
ioat_chan = ioat_chan_by_index(ioat_dma, j);
devm_free_irq(dev, msix->vector, ioat_chan);
}
goto msi;
}
}
intrctrl |= IOAT_INTRCTRL_MSIX_VECTOR_CONTROL;
ioat_dma->irq_mode = IOAT_MSIX;
goto done;
msi:
err = pci_enable_msi(pdev);
if (err)
goto intx;
err = devm_request_irq(dev, pdev->irq, ioat_dma_do_interrupt, 0,
"ioat-msi", ioat_dma);
if (err) {
pci_disable_msi(pdev);
goto intx;
}
ioat_dma->irq_mode = IOAT_MSI;
goto done;
intx:
err = devm_request_irq(dev, pdev->irq, ioat_dma_do_interrupt,
IRQF_SHARED, "ioat-intx", ioat_dma);
if (err)
goto err_no_irq;
ioat_dma->irq_mode = IOAT_INTX;
done:
if (is_bwd_ioat(pdev))
ioat_intr_quirk(ioat_dma);
intrctrl |= IOAT_INTRCTRL_MASTER_INT_EN;
writeb(intrctrl, ioat_dma->reg_base + IOAT_INTRCTRL_OFFSET);
return 0;
err_no_irq:
/* Disable all interrupt generation */
writeb(0, ioat_dma->reg_base + IOAT_INTRCTRL_OFFSET);
ioat_dma->irq_mode = IOAT_NOIRQ;
dev_err(dev, "no usable interrupts\n");
return err;
}
static void ioat_disable_interrupts(struct ioatdma_device *ioat_dma)
{
/* Disable all interrupt generation */
writeb(0, ioat_dma->reg_base + IOAT_INTRCTRL_OFFSET);
}
static int ioat_probe(struct ioatdma_device *ioat_dma)
{
int err = -ENODEV;
struct dma_device *dma = &ioat_dma->dma_dev;
struct pci_dev *pdev = ioat_dma->pdev;
struct device *dev = &pdev->dev;
/* DMA coherent memory pool for DMA descriptor allocations */
ioat_dma->dma_pool = pci_pool_create("dma_desc_pool", pdev,
sizeof(struct ioat_dma_descriptor),
64, 0);
if (!ioat_dma->dma_pool) {
err = -ENOMEM;
goto err_dma_pool;
}
ioat_dma->completion_pool = pci_pool_create("completion_pool", pdev,
sizeof(u64),
SMP_CACHE_BYTES,
SMP_CACHE_BYTES);
if (!ioat_dma->completion_pool) {
err = -ENOMEM;
goto err_completion_pool;
}
ioat_enumerate_channels(ioat_dma);
dma_cap_set(DMA_MEMCPY, dma->cap_mask);
dma->dev = &pdev->dev;
if (!dma->chancnt) {
dev_err(dev, "channel enumeration error\n");
goto err_setup_interrupts;
}
err = ioat_dma_setup_interrupts(ioat_dma);
if (err)
goto err_setup_interrupts;
err = ioat3_dma_self_test(ioat_dma);
if (err)
goto err_self_test;
return 0;
err_self_test:
ioat_disable_interrupts(ioat_dma);
err_setup_interrupts:
pci_pool_destroy(ioat_dma->completion_pool);
err_completion_pool:
pci_pool_destroy(ioat_dma->dma_pool);
err_dma_pool:
return err;
}
static int ioat_register(struct ioatdma_device *ioat_dma)
{
int err = dma_async_device_register(&ioat_dma->dma_dev);
if (err) {
ioat_disable_interrupts(ioat_dma);
pci_pool_destroy(ioat_dma->completion_pool);
pci_pool_destroy(ioat_dma->dma_pool);
}
return err;
}
static void ioat_dma_remove(struct ioatdma_device *ioat_dma)
{
struct dma_device *dma = &ioat_dma->dma_dev;
ioat_disable_interrupts(ioat_dma);
ioat_kobject_del(ioat_dma);
dma_async_device_unregister(dma);
pci_pool_destroy(ioat_dma->dma_pool);
pci_pool_destroy(ioat_dma->completion_pool);
INIT_LIST_HEAD(&dma->channels);
}
/**
* ioat_enumerate_channels - find and initialize the device's channels
* @ioat_dma: the ioat dma device to be enumerated
*/
static int ioat_enumerate_channels(struct ioatdma_device *ioat_dma)
{
struct ioatdma_chan *ioat_chan;
struct device *dev = &ioat_dma->pdev->dev;
struct dma_device *dma = &ioat_dma->dma_dev;
u8 xfercap_log;
int i;
INIT_LIST_HEAD(&dma->channels);
dma->chancnt = readb(ioat_dma->reg_base + IOAT_CHANCNT_OFFSET);
dma->chancnt &= 0x1f; /* bits [4:0] valid */
if (dma->chancnt > ARRAY_SIZE(ioat_dma->idx)) {
dev_warn(dev, "(%d) exceeds max supported channels (%zu)\n",
dma->chancnt, ARRAY_SIZE(ioat_dma->idx));
dma->chancnt = ARRAY_SIZE(ioat_dma->idx);
}
xfercap_log = readb(ioat_dma->reg_base + IOAT_XFERCAP_OFFSET);
xfercap_log &= 0x1f; /* bits [4:0] valid */
if (xfercap_log == 0)
return 0;
dev_dbg(dev, "%s: xfercap = %d\n", __func__, 1 << xfercap_log);
for (i = 0; i < dma->chancnt; i++) {
ioat_chan = devm_kzalloc(dev, sizeof(*ioat_chan), GFP_KERNEL);
if (!ioat_chan)
break;
ioat_init_channel(ioat_dma, ioat_chan, i);
ioat_chan->xfercap_log = xfercap_log;
spin_lock_init(&ioat_chan->prep_lock);
if (ioat_reset_hw(ioat_chan)) {
i = 0;
break;
}
}
dma->chancnt = i;
return i;
}
/**
* ioat_free_chan_resources - release all the descriptors
* @chan: the channel to be cleaned
*/
static void ioat_free_chan_resources(struct dma_chan *c)
{
struct ioatdma_chan *ioat_chan = to_ioat_chan(c);
struct ioatdma_device *ioat_dma = ioat_chan->ioat_dma;
struct ioat_ring_ent *desc;
const int total_descs = 1 << ioat_chan->alloc_order;
int descs;
int i;
/* Before freeing channel resources first check
* if they have been previously allocated for this channel.
*/
if (!ioat_chan->ring)
return;
ioat_stop(ioat_chan);
ioat_reset_hw(ioat_chan);
spin_lock_bh(&ioat_chan->cleanup_lock);
spin_lock_bh(&ioat_chan->prep_lock);
descs = ioat_ring_space(ioat_chan);
dev_dbg(to_dev(ioat_chan), "freeing %d idle descriptors\n", descs);
for (i = 0; i < descs; i++) {
desc = ioat_get_ring_ent(ioat_chan, ioat_chan->head + i);
ioat_free_ring_ent(desc, c);
}
if (descs < total_descs)
dev_err(to_dev(ioat_chan), "Freeing %d in use descriptors!\n",
total_descs - descs);
for (i = 0; i < total_descs - descs; i++) {
desc = ioat_get_ring_ent(ioat_chan, ioat_chan->tail + i);
dump_desc_dbg(ioat_chan, desc);
ioat_free_ring_ent(desc, c);
}
kfree(ioat_chan->ring);
ioat_chan->ring = NULL;
ioat_chan->alloc_order = 0;
pci_pool_free(ioat_dma->completion_pool, ioat_chan->completion,
ioat_chan->completion_dma);
spin_unlock_bh(&ioat_chan->prep_lock);
spin_unlock_bh(&ioat_chan->cleanup_lock);
ioat_chan->last_completion = 0;
ioat_chan->completion_dma = 0;
ioat_chan->dmacount = 0;
}
/* ioat_alloc_chan_resources - allocate/initialize ioat descriptor ring
* @chan: channel to be initialized
*/
static int ioat_alloc_chan_resources(struct dma_chan *c)
{
struct ioatdma_chan *ioat_chan = to_ioat_chan(c);
struct ioat_ring_ent **ring;
u64 status;
int order;
int i = 0;
u32 chanerr;
/* have we already been set up? */
if (ioat_chan->ring)
return 1 << ioat_chan->alloc_order;
/* Setup register to interrupt and write completion status on error */
writew(IOAT_CHANCTRL_RUN, ioat_chan->reg_base + IOAT_CHANCTRL_OFFSET);
/* allocate a completion writeback area */
/* doing 2 32bit writes to mmio since 1 64b write doesn't work */
ioat_chan->completion =
pci_pool_alloc(ioat_chan->ioat_dma->completion_pool,
GFP_KERNEL, &ioat_chan->completion_dma);
if (!ioat_chan->completion)
return -ENOMEM;
memset(ioat_chan->completion, 0, sizeof(*ioat_chan->completion));
writel(((u64)ioat_chan->completion_dma) & 0x00000000FFFFFFFF,
ioat_chan->reg_base + IOAT_CHANCMP_OFFSET_LOW);
writel(((u64)ioat_chan->completion_dma) >> 32,
ioat_chan->reg_base + IOAT_CHANCMP_OFFSET_HIGH);
order = ioat_get_alloc_order();
ring = ioat_alloc_ring(c, order, GFP_KERNEL);
if (!ring)
return -ENOMEM;
spin_lock_bh(&ioat_chan->cleanup_lock);
spin_lock_bh(&ioat_chan->prep_lock);
ioat_chan->ring = ring;
ioat_chan->head = 0;
ioat_chan->issued = 0;
ioat_chan->tail = 0;
ioat_chan->alloc_order = order;
set_bit(IOAT_RUN, &ioat_chan->state);
spin_unlock_bh(&ioat_chan->prep_lock);
spin_unlock_bh(&ioat_chan->cleanup_lock);
ioat_start_null_desc(ioat_chan);
/* check that we got off the ground */
do {
udelay(1);
status = ioat_chansts(ioat_chan);
} while (i++ < 20 && !is_ioat_active(status) && !is_ioat_idle(status));
if (is_ioat_active(status) || is_ioat_idle(status))
return 1 << ioat_chan->alloc_order;
chanerr = readl(ioat_chan->reg_base + IOAT_CHANERR_OFFSET);
dev_WARN(to_dev(ioat_chan),
"failed to start channel chanerr: %#x\n", chanerr);
ioat_free_chan_resources(c);
return -EFAULT;
}
/* common channel initialization */
static void
ioat_init_channel(struct ioatdma_device *ioat_dma,
struct ioatdma_chan *ioat_chan, int idx)
{
struct dma_device *dma = &ioat_dma->dma_dev;
struct dma_chan *c = &ioat_chan->dma_chan;
unsigned long data = (unsigned long) c;
ioat_chan->ioat_dma = ioat_dma;
ioat_chan->reg_base = ioat_dma->reg_base + (0x80 * (idx + 1));
spin_lock_init(&ioat_chan->cleanup_lock);
ioat_chan->dma_chan.device = dma;
dma_cookie_init(&ioat_chan->dma_chan);
list_add_tail(&ioat_chan->dma_chan.device_node, &dma->channels);
ioat_dma->idx[idx] = ioat_chan;
init_timer(&ioat_chan->timer);
ioat_chan->timer.function = ioat_timer_event;
ioat_chan->timer.data = data;
tasklet_init(&ioat_chan->cleanup_task, ioat_cleanup_event, data);
}
#define IOAT_NUM_SRC_TEST 6 /* must be <= 8 */
static int ioat_xor_val_self_test(struct ioatdma_device *ioat_dma)
{
int i, src_idx;
struct page *dest;
struct page *xor_srcs[IOAT_NUM_SRC_TEST];
struct page *xor_val_srcs[IOAT_NUM_SRC_TEST + 1];
dma_addr_t dma_srcs[IOAT_NUM_SRC_TEST + 1];
dma_addr_t dest_dma;
struct dma_async_tx_descriptor *tx;
struct dma_chan *dma_chan;
dma_cookie_t cookie;
u8 cmp_byte = 0;
u32 cmp_word;
u32 xor_val_result;
int err = 0;
struct completion cmp;
unsigned long tmo;
struct device *dev = &ioat_dma->pdev->dev;
struct dma_device *dma = &ioat_dma->dma_dev;
u8 op = 0;
dev_dbg(dev, "%s\n", __func__);
if (!dma_has_cap(DMA_XOR, dma->cap_mask))
return 0;
for (src_idx = 0; src_idx < IOAT_NUM_SRC_TEST; src_idx++) {
xor_srcs[src_idx] = alloc_page(GFP_KERNEL);
if (!xor_srcs[src_idx]) {
while (src_idx--)
__free_page(xor_srcs[src_idx]);
return -ENOMEM;
}
}
dest = alloc_page(GFP_KERNEL);
if (!dest) {
while (src_idx--)
__free_page(xor_srcs[src_idx]);
return -ENOMEM;
}
/* Fill in src buffers */
for (src_idx = 0; src_idx < IOAT_NUM_SRC_TEST; src_idx++) {
u8 *ptr = page_address(xor_srcs[src_idx]);
for (i = 0; i < PAGE_SIZE; i++)
ptr[i] = (1 << src_idx);
}
for (src_idx = 0; src_idx < IOAT_NUM_SRC_TEST; src_idx++)
cmp_byte ^= (u8) (1 << src_idx);
cmp_word = (cmp_byte << 24) | (cmp_byte << 16) |
(cmp_byte << 8) | cmp_byte;
memset(page_address(dest), 0, PAGE_SIZE);
dma_chan = container_of(dma->channels.next, struct dma_chan,
device_node);
if (dma->device_alloc_chan_resources(dma_chan) < 1) {
err = -ENODEV;
goto out;
}
/* test xor */
op = IOAT_OP_XOR;
dest_dma = dma_map_page(dev, dest, 0, PAGE_SIZE, DMA_FROM_DEVICE);
if (dma_mapping_error(dev, dest_dma))
goto dma_unmap;
for (i = 0; i < IOAT_NUM_SRC_TEST; i++)
dma_srcs[i] = DMA_ERROR_CODE;
for (i = 0; i < IOAT_NUM_SRC_TEST; i++) {
dma_srcs[i] = dma_map_page(dev, xor_srcs[i], 0, PAGE_SIZE,
DMA_TO_DEVICE);
if (dma_mapping_error(dev, dma_srcs[i]))
goto dma_unmap;
}
tx = dma->device_prep_dma_xor(dma_chan, dest_dma, dma_srcs,
IOAT_NUM_SRC_TEST, PAGE_SIZE,
DMA_PREP_INTERRUPT);
if (!tx) {
dev_err(dev, "Self-test xor prep failed\n");
err = -ENODEV;
goto dma_unmap;
}
async_tx_ack(tx);
init_completion(&cmp);
tx->callback = ioat_dma_test_callback;
tx->callback_param = &cmp;
cookie = tx->tx_submit(tx);
if (cookie < 0) {
dev_err(dev, "Self-test xor setup failed\n");
err = -ENODEV;
goto dma_unmap;
}
dma->device_issue_pending(dma_chan);
tmo = wait_for_completion_timeout(&cmp, msecs_to_jiffies(3000));
if (tmo == 0 ||
dma->device_tx_status(dma_chan, cookie, NULL) != DMA_COMPLETE) {
dev_err(dev, "Self-test xor timed out\n");
err = -ENODEV;
goto dma_unmap;
}
for (i = 0; i < IOAT_NUM_SRC_TEST; i++)
dma_unmap_page(dev, dma_srcs[i], PAGE_SIZE, DMA_TO_DEVICE);
dma_sync_single_for_cpu(dev, dest_dma, PAGE_SIZE, DMA_FROM_DEVICE);
for (i = 0; i < (PAGE_SIZE / sizeof(u32)); i++) {
u32 *ptr = page_address(dest);
if (ptr[i] != cmp_word) {
dev_err(dev, "Self-test xor failed compare\n");
err = -ENODEV;
goto free_resources;
}
}
dma_sync_single_for_device(dev, dest_dma, PAGE_SIZE, DMA_FROM_DEVICE);
dma_unmap_page(dev, dest_dma, PAGE_SIZE, DMA_FROM_DEVICE);
/* skip validate if the capability is not present */
if (!dma_has_cap(DMA_XOR_VAL, dma_chan->device->cap_mask))
goto free_resources;
op = IOAT_OP_XOR_VAL;
/* validate the sources with the destintation page */
for (i = 0; i < IOAT_NUM_SRC_TEST; i++)
xor_val_srcs[i] = xor_srcs[i];
xor_val_srcs[i] = dest;
xor_val_result = 1;
for (i = 0; i < IOAT_NUM_SRC_TEST + 1; i++)
dma_srcs[i] = DMA_ERROR_CODE;
for (i = 0; i < IOAT_NUM_SRC_TEST + 1; i++) {
dma_srcs[i] = dma_map_page(dev, xor_val_srcs[i], 0, PAGE_SIZE,
DMA_TO_DEVICE);
if (dma_mapping_error(dev, dma_srcs[i]))
goto dma_unmap;
}
tx = dma->device_prep_dma_xor_val(dma_chan, dma_srcs,
IOAT_NUM_SRC_TEST + 1, PAGE_SIZE,
&xor_val_result, DMA_PREP_INTERRUPT);
if (!tx) {
dev_err(dev, "Self-test zero prep failed\n");
err = -ENODEV;
goto dma_unmap;
}
async_tx_ack(tx);
init_completion(&cmp);
tx->callback = ioat_dma_test_callback;
tx->callback_param = &cmp;
cookie = tx->tx_submit(tx);
if (cookie < 0) {
dev_err(dev, "Self-test zero setup failed\n");
err = -ENODEV;
goto dma_unmap;
}
dma->device_issue_pending(dma_chan);
tmo = wait_for_completion_timeout(&cmp, msecs_to_jiffies(3000));
if (tmo == 0 ||
dma->device_tx_status(dma_chan, cookie, NULL) != DMA_COMPLETE) {
dev_err(dev, "Self-test validate timed out\n");
err = -ENODEV;
goto dma_unmap;
}
for (i = 0; i < IOAT_NUM_SRC_TEST + 1; i++)
dma_unmap_page(dev, dma_srcs[i], PAGE_SIZE, DMA_TO_DEVICE);
if (xor_val_result != 0) {
dev_err(dev, "Self-test validate failed compare\n");
err = -ENODEV;
goto free_resources;
}
memset(page_address(dest), 0, PAGE_SIZE);
/* test for non-zero parity sum */
op = IOAT_OP_XOR_VAL;
xor_val_result = 0;
for (i = 0; i < IOAT_NUM_SRC_TEST + 1; i++)
dma_srcs[i] = DMA_ERROR_CODE;
for (i = 0; i < IOAT_NUM_SRC_TEST + 1; i++) {
dma_srcs[i] = dma_map_page(dev, xor_val_srcs[i], 0, PAGE_SIZE,
DMA_TO_DEVICE);
if (dma_mapping_error(dev, dma_srcs[i]))
goto dma_unmap;
}
tx = dma->device_prep_dma_xor_val(dma_chan, dma_srcs,
IOAT_NUM_SRC_TEST + 1, PAGE_SIZE,
&xor_val_result, DMA_PREP_INTERRUPT);
if (!tx) {
dev_err(dev, "Self-test 2nd zero prep failed\n");
err = -ENODEV;
goto dma_unmap;
}
async_tx_ack(tx);
init_completion(&cmp);
tx->callback = ioat_dma_test_callback;
tx->callback_param = &cmp;
cookie = tx->tx_submit(tx);
if (cookie < 0) {
dev_err(dev, "Self-test 2nd zero setup failed\n");
err = -ENODEV;
goto dma_unmap;
}
dma->device_issue_pending(dma_chan);
tmo = wait_for_completion_timeout(&cmp, msecs_to_jiffies(3000));
if (tmo == 0 ||
dma->device_tx_status(dma_chan, cookie, NULL) != DMA_COMPLETE) {
dev_err(dev, "Self-test 2nd validate timed out\n");
err = -ENODEV;
goto dma_unmap;
}
if (xor_val_result != SUM_CHECK_P_RESULT) {
dev_err(dev, "Self-test validate failed compare\n");
err = -ENODEV;
goto dma_unmap;
}
for (i = 0; i < IOAT_NUM_SRC_TEST + 1; i++)
dma_unmap_page(dev, dma_srcs[i], PAGE_SIZE, DMA_TO_DEVICE);
goto free_resources;
dma_unmap:
if (op == IOAT_OP_XOR) {
if (dest_dma != DMA_ERROR_CODE)
dma_unmap_page(dev, dest_dma, PAGE_SIZE,
DMA_FROM_DEVICE);
for (i = 0; i < IOAT_NUM_SRC_TEST; i++)
if (dma_srcs[i] != DMA_ERROR_CODE)
dma_unmap_page(dev, dma_srcs[i], PAGE_SIZE,
DMA_TO_DEVICE);
} else if (op == IOAT_OP_XOR_VAL) {
for (i = 0; i < IOAT_NUM_SRC_TEST + 1; i++)
if (dma_srcs[i] != DMA_ERROR_CODE)
dma_unmap_page(dev, dma_srcs[i], PAGE_SIZE,
DMA_TO_DEVICE);
}
free_resources:
dma->device_free_chan_resources(dma_chan);
out:
src_idx = IOAT_NUM_SRC_TEST;
while (src_idx--)
__free_page(xor_srcs[src_idx]);
__free_page(dest);
return err;
}
static int ioat3_dma_self_test(struct ioatdma_device *ioat_dma)
{
int rc;
rc = ioat_dma_self_test(ioat_dma);
if (rc)
return rc;
rc = ioat_xor_val_self_test(ioat_dma);
return rc;
}
static void ioat_intr_quirk(struct ioatdma_device *ioat_dma)
{
struct dma_device *dma;
struct dma_chan *c;
struct ioatdma_chan *ioat_chan;
u32 errmask;
dma = &ioat_dma->dma_dev;
/*
* if we have descriptor write back error status, we mask the
* error interrupts
*/
if (ioat_dma->cap & IOAT_CAP_DWBES) {
list_for_each_entry(c, &dma->channels, device_node) {
ioat_chan = to_ioat_chan(c);
errmask = readl(ioat_chan->reg_base +
IOAT_CHANERR_MASK_OFFSET);
errmask |= IOAT_CHANERR_XOR_P_OR_CRC_ERR |
IOAT_CHANERR_XOR_Q_ERR;
writel(errmask, ioat_chan->reg_base +
IOAT_CHANERR_MASK_OFFSET);
}
}
}
static int ioat3_dma_probe(struct ioatdma_device *ioat_dma, int dca)
{
struct pci_dev *pdev = ioat_dma->pdev;
int dca_en = system_has_dca_enabled(pdev);
struct dma_device *dma;
struct dma_chan *c;
struct ioatdma_chan *ioat_chan;
bool is_raid_device = false;
int err;
dma = &ioat_dma->dma_dev;
dma->device_prep_dma_memcpy = ioat_dma_prep_memcpy_lock;
dma->device_issue_pending = ioat_issue_pending;
dma->device_alloc_chan_resources = ioat_alloc_chan_resources;
dma->device_free_chan_resources = ioat_free_chan_resources;
dma_cap_set(DMA_INTERRUPT, dma->cap_mask);
dma->device_prep_dma_interrupt = ioat_prep_interrupt_lock;
ioat_dma->cap = readl(ioat_dma->reg_base + IOAT_DMA_CAP_OFFSET);
if (is_xeon_cb32(pdev) || is_bwd_noraid(pdev))
ioat_dma->cap &=
~(IOAT_CAP_XOR | IOAT_CAP_PQ | IOAT_CAP_RAID16SS);
/* dca is incompatible with raid operations */
if (dca_en && (ioat_dma->cap & (IOAT_CAP_XOR|IOAT_CAP_PQ)))
ioat_dma->cap &= ~(IOAT_CAP_XOR|IOAT_CAP_PQ);
if (ioat_dma->cap & IOAT_CAP_XOR) {
is_raid_device = true;
dma->max_xor = 8;
dma_cap_set(DMA_XOR, dma->cap_mask);
dma->device_prep_dma_xor = ioat_prep_xor;
dma_cap_set(DMA_XOR_VAL, dma->cap_mask);
dma->device_prep_dma_xor_val = ioat_prep_xor_val;
}
if (ioat_dma->cap & IOAT_CAP_PQ) {
is_raid_device = true;
dma->device_prep_dma_pq = ioat_prep_pq;
dma->device_prep_dma_pq_val = ioat_prep_pq_val;
dma_cap_set(DMA_PQ, dma->cap_mask);
dma_cap_set(DMA_PQ_VAL, dma->cap_mask);
if (ioat_dma->cap & IOAT_CAP_RAID16SS)
dma_set_maxpq(dma, 16, 0);
else
dma_set_maxpq(dma, 8, 0);
if (!(ioat_dma->cap & IOAT_CAP_XOR)) {
dma->device_prep_dma_xor = ioat_prep_pqxor;
dma->device_prep_dma_xor_val = ioat_prep_pqxor_val;
dma_cap_set(DMA_XOR, dma->cap_mask);
dma_cap_set(DMA_XOR_VAL, dma->cap_mask);
if (ioat_dma->cap & IOAT_CAP_RAID16SS)
dma->max_xor = 16;
else
dma->max_xor = 8;
}
}
dma->device_tx_status = ioat_tx_status;
/* starting with CB3.3 super extended descriptors are supported */
if (ioat_dma->cap & IOAT_CAP_RAID16SS) {
char pool_name[14];
int i;
for (i = 0; i < MAX_SED_POOLS; i++) {
snprintf(pool_name, 14, "ioat_hw%d_sed", i);
/* allocate SED DMA pool */
ioat_dma->sed_hw_pool[i] = dmam_pool_create(pool_name,
&pdev->dev,
SED_SIZE * (i + 1), 64, 0);
if (!ioat_dma->sed_hw_pool[i])
return -ENOMEM;
}
}
if (!(ioat_dma->cap & (IOAT_CAP_XOR | IOAT_CAP_PQ)))
dma_cap_set(DMA_PRIVATE, dma->cap_mask);
err = ioat_probe(ioat_dma);
if (err)
return err;
list_for_each_entry(c, &dma->channels, device_node) {
ioat_chan = to_ioat_chan(c);
writel(IOAT_DMA_DCA_ANY_CPU,
ioat_chan->reg_base + IOAT_DCACTRL_OFFSET);
}
err = ioat_register(ioat_dma);
if (err)
return err;
ioat_kobject_add(ioat_dma, &ioat_ktype);
if (dca)
ioat_dma->dca = ioat_dca_init(pdev, ioat_dma->reg_base);
return 0;
}
#define DRV_NAME "ioatdma"
static struct pci_driver ioat_pci_driver = {
.name = DRV_NAME,
.id_table = ioat_pci_tbl,
.probe = ioat_pci_probe,
.remove = ioat_remove,
};
static struct ioatdma_device *
alloc_ioatdma(struct pci_dev *pdev, void __iomem *iobase)
{
struct device *dev = &pdev->dev;
struct ioatdma_device *d = devm_kzalloc(dev, sizeof(*d), GFP_KERNEL);
if (!d)
return NULL;
d->pdev = pdev;
d->reg_base = iobase;
return d;
}
static int ioat_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
void __iomem * const *iomap;
struct device *dev = &pdev->dev;
struct ioatdma_device *device;
int err;
err = pcim_enable_device(pdev);
if (err)
return err;
err = pcim_iomap_regions(pdev, 1 << IOAT_MMIO_BAR, DRV_NAME);
if (err)
return err;
iomap = pcim_iomap_table(pdev);
if (!iomap)
return -ENOMEM;
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
if (err)
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (err)
return err;
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
if (err)
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
if (err)
return err;
device = alloc_ioatdma(pdev, iomap[IOAT_MMIO_BAR]);
if (!device)
return -ENOMEM;
pci_set_master(pdev);
pci_set_drvdata(pdev, device);
device->version = readb(device->reg_base + IOAT_VER_OFFSET);
if (device->version >= IOAT_VER_3_0)
err = ioat3_dma_probe(device, ioat_dca_enabled);
else
return -ENODEV;
if (err) {
dev_err(dev, "Intel(R) I/OAT DMA Engine init failed\n");
return -ENODEV;
}
return 0;
}
static void ioat_remove(struct pci_dev *pdev)
{
struct ioatdma_device *device = pci_get_drvdata(pdev);
if (!device)
return;
dev_err(&pdev->dev, "Removing dma and dca services\n");
if (device->dca) {
unregister_dca_provider(device->dca, &pdev->dev);
free_dca_provider(device->dca);
device->dca = NULL;
}
ioat_dma_remove(device);
}
static int __init ioat_init_module(void)
{
int err = -ENOMEM;
pr_info("%s: Intel(R) QuickData Technology Driver %s\n",
DRV_NAME, IOAT_DMA_VERSION);
ioat_cache = kmem_cache_create("ioat", sizeof(struct ioat_ring_ent),
0, SLAB_HWCACHE_ALIGN, NULL);
if (!ioat_cache)
return -ENOMEM;
ioat_sed_cache = KMEM_CACHE(ioat_sed_ent, 0);
if (!ioat_sed_cache)
goto err_ioat_cache;
err = pci_register_driver(&ioat_pci_driver);
if (err)
goto err_ioat3_cache;
return 0;
err_ioat3_cache:
kmem_cache_destroy(ioat_sed_cache);
err_ioat_cache:
kmem_cache_destroy(ioat_cache);
return err;
}
module_init(ioat_init_module);
static void __exit ioat_exit_module(void)
{
pci_unregister_driver(&ioat_pci_driver);
kmem_cache_destroy(ioat_cache);
}
module_exit(ioat_exit_module);
| gpl-2.0 |
zyw-200/decaf-platform | ui/vnc-jobs-sync.c | 202 | 2177 | /*
* QEMU VNC display driver
*
* Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
* Copyright (C) 2006 Fabrice Bellard
* Copyright (C) 2009 Red Hat, Inc
* Copyright (C) 2010 Corentin Chary <corentin.chary@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE 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 "vnc.h"
#include "vnc-jobs.h"
void vnc_jobs_clear(VncState *vs)
{
}
void vnc_jobs_join(VncState *vs)
{
}
VncJob *vnc_job_new(VncState *vs)
{
vs->job.vs = vs;
vs->job.rectangles = 0;
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vs->job.saved_offset = vs->output.offset;
vnc_write_u16(vs, 0);
return &vs->job;
}
void vnc_job_push(VncJob *job)
{
VncState *vs = job->vs;
vs->output.buffer[job->saved_offset] = (job->rectangles >> 8) & 0xFF;
vs->output.buffer[job->saved_offset + 1] = job->rectangles & 0xFF;
vnc_flush(job->vs);
}
int vnc_job_add_rect(VncJob *job, int x, int y, int w, int h)
{
int n;
n = vnc_send_framebuffer_update(job->vs, x, y, w, h);
if (n >= 0)
job->rectangles += n;
return n;
}
bool vnc_has_job(VncState *vs)
{
return false;
}
| gpl-2.0 |
kingklick/kk-note2-kernel | drivers/gpu/drm/drm_pci.c | 458 | 11881 | /* drm_pci.h -- PCI DMA memory management wrappers for DRM -*- linux-c -*- */
/**
* \file drm_pci.c
* \brief Functions and ioctls to manage PCI memory
*
* \warning These interfaces aren't stable yet.
*
* \todo Implement the remaining ioctl's for the PCI pools.
* \todo The wrappers here are so thin that they would be better off inlined..
*
* \author José Fonseca <jrfonseca@tungstengraphics.com>
* \author Leif Delgass <ldelgass@retinalburn.net>
*/
/*
* Copyright 2003 José Fonseca.
* Copyright 2003 Leif Delgass.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS 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/pci.h>
#include <linux/slab.h>
#include <linux/dma-mapping.h>
#include "drmP.h"
/**********************************************************************/
/** \name PCI memory */
/*@{*/
/**
* \brief Allocate a PCI consistent memory block, for DMA.
*/
drm_dma_handle_t *drm_pci_alloc(struct drm_device * dev, size_t size, size_t align)
{
drm_dma_handle_t *dmah;
#if 1
unsigned long addr;
size_t sz;
#endif
/* pci_alloc_consistent only guarantees alignment to the smallest
* PAGE_SIZE order which is greater than or equal to the requested size.
* Return NULL here for now to make sure nobody tries for larger alignment
*/
if (align > size)
return NULL;
dmah = kmalloc(sizeof(drm_dma_handle_t), GFP_KERNEL);
if (!dmah)
return NULL;
dmah->size = size;
dmah->vaddr = dma_alloc_coherent(&dev->pdev->dev, size, &dmah->busaddr, GFP_KERNEL | __GFP_COMP);
if (dmah->vaddr == NULL) {
kfree(dmah);
return NULL;
}
memset(dmah->vaddr, 0, size);
/* XXX - Is virt_to_page() legal for consistent mem? */
/* Reserve */
for (addr = (unsigned long)dmah->vaddr, sz = size;
sz > 0; addr += PAGE_SIZE, sz -= PAGE_SIZE) {
SetPageReserved(virt_to_page(addr));
}
return dmah;
}
EXPORT_SYMBOL(drm_pci_alloc);
/**
* \brief Free a PCI consistent memory block without freeing its descriptor.
*
* This function is for internal use in the Linux-specific DRM core code.
*/
void __drm_pci_free(struct drm_device * dev, drm_dma_handle_t * dmah)
{
#if 1
unsigned long addr;
size_t sz;
#endif
if (dmah->vaddr) {
/* XXX - Is virt_to_page() legal for consistent mem? */
/* Unreserve */
for (addr = (unsigned long)dmah->vaddr, sz = dmah->size;
sz > 0; addr += PAGE_SIZE, sz -= PAGE_SIZE) {
ClearPageReserved(virt_to_page(addr));
}
dma_free_coherent(&dev->pdev->dev, dmah->size, dmah->vaddr,
dmah->busaddr);
}
}
/**
* \brief Free a PCI consistent memory block
*/
void drm_pci_free(struct drm_device * dev, drm_dma_handle_t * dmah)
{
__drm_pci_free(dev, dmah);
kfree(dmah);
}
EXPORT_SYMBOL(drm_pci_free);
#ifdef CONFIG_PCI
static int drm_get_pci_domain(struct drm_device *dev)
{
#ifndef __alpha__
/* For historical reasons, drm_get_pci_domain() is busticated
* on most archs and has to remain so for userspace interface
* < 1.4, except on alpha which was right from the beginning
*/
if (dev->if_version < 0x10004)
return 0;
#endif /* __alpha__ */
return pci_domain_nr(dev->pdev->bus);
}
static int drm_pci_get_irq(struct drm_device *dev)
{
return dev->pdev->irq;
}
static const char *drm_pci_get_name(struct drm_device *dev)
{
struct pci_driver *pdriver = dev->driver->kdriver.pci;
return pdriver->name;
}
int drm_pci_set_busid(struct drm_device *dev, struct drm_master *master)
{
int len, ret;
struct pci_driver *pdriver = dev->driver->kdriver.pci;
master->unique_len = 40;
master->unique_size = master->unique_len;
master->unique = kmalloc(master->unique_size, GFP_KERNEL);
if (master->unique == NULL)
return -ENOMEM;
len = snprintf(master->unique, master->unique_len,
"pci:%04x:%02x:%02x.%d",
drm_get_pci_domain(dev),
dev->pdev->bus->number,
PCI_SLOT(dev->pdev->devfn),
PCI_FUNC(dev->pdev->devfn));
if (len >= master->unique_len) {
DRM_ERROR("buffer overflow");
ret = -EINVAL;
goto err;
} else
master->unique_len = len;
dev->devname =
kmalloc(strlen(pdriver->name) +
master->unique_len + 2, GFP_KERNEL);
if (dev->devname == NULL) {
ret = -ENOMEM;
goto err;
}
sprintf(dev->devname, "%s@%s", pdriver->name,
master->unique);
return 0;
err:
return ret;
}
int drm_pci_set_unique(struct drm_device *dev,
struct drm_master *master,
struct drm_unique *u)
{
int domain, bus, slot, func, ret;
const char *bus_name;
master->unique_len = u->unique_len;
master->unique_size = u->unique_len + 1;
master->unique = kmalloc(master->unique_size, GFP_KERNEL);
if (!master->unique) {
ret = -ENOMEM;
goto err;
}
if (copy_from_user(master->unique, u->unique, master->unique_len)) {
ret = -EFAULT;
goto err;
}
master->unique[master->unique_len] = '\0';
bus_name = dev->driver->bus->get_name(dev);
dev->devname = kmalloc(strlen(bus_name) +
strlen(master->unique) + 2, GFP_KERNEL);
if (!dev->devname) {
ret = -ENOMEM;
goto err;
}
sprintf(dev->devname, "%s@%s", bus_name,
master->unique);
/* Return error if the busid submitted doesn't match the device's actual
* busid.
*/
ret = sscanf(master->unique, "PCI:%d:%d:%d", &bus, &slot, &func);
if (ret != 3) {
ret = -EINVAL;
goto err;
}
domain = bus >> 8;
bus &= 0xff;
if ((domain != drm_get_pci_domain(dev)) ||
(bus != dev->pdev->bus->number) ||
(slot != PCI_SLOT(dev->pdev->devfn)) ||
(func != PCI_FUNC(dev->pdev->devfn))) {
ret = -EINVAL;
goto err;
}
return 0;
err:
return ret;
}
static int drm_pci_irq_by_busid(struct drm_device *dev, struct drm_irq_busid *p)
{
if ((p->busnum >> 8) != drm_get_pci_domain(dev) ||
(p->busnum & 0xff) != dev->pdev->bus->number ||
p->devnum != PCI_SLOT(dev->pdev->devfn) || p->funcnum != PCI_FUNC(dev->pdev->devfn))
return -EINVAL;
p->irq = dev->pdev->irq;
DRM_DEBUG("%d:%d:%d => IRQ %d\n", p->busnum, p->devnum, p->funcnum,
p->irq);
return 0;
}
int drm_pci_agp_init(struct drm_device *dev)
{
if (drm_core_has_AGP(dev)) {
if (drm_pci_device_is_agp(dev))
dev->agp = drm_agp_init(dev);
if (drm_core_check_feature(dev, DRIVER_REQUIRE_AGP)
&& (dev->agp == NULL)) {
DRM_ERROR("Cannot initialize the agpgart module.\n");
return -EINVAL;
}
if (drm_core_has_MTRR(dev)) {
if (dev->agp)
dev->agp->agp_mtrr =
mtrr_add(dev->agp->agp_info.aper_base,
dev->agp->agp_info.aper_size *
1024 * 1024, MTRR_TYPE_WRCOMB, 1);
}
}
return 0;
}
static struct drm_bus drm_pci_bus = {
.bus_type = DRIVER_BUS_PCI,
.get_irq = drm_pci_get_irq,
.get_name = drm_pci_get_name,
.set_busid = drm_pci_set_busid,
.set_unique = drm_pci_set_unique,
.irq_by_busid = drm_pci_irq_by_busid,
.agp_init = drm_pci_agp_init,
};
/**
* Register.
*
* \param pdev - PCI device structure
* \param ent entry from the PCI ID table with device type flags
* \return zero on success or a negative number on failure.
*
* Attempt to gets inter module "drm" information. If we are first
* then register the character device and inter module information.
* Try and register, if we fail to register, backout previous work.
*/
int drm_get_pci_dev(struct pci_dev *pdev, const struct pci_device_id *ent,
struct drm_driver *driver)
{
struct drm_device *dev;
int ret;
DRM_DEBUG("\n");
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
ret = pci_enable_device(pdev);
if (ret)
goto err_g1;
dev->pdev = pdev;
dev->dev = &pdev->dev;
dev->pci_device = pdev->device;
dev->pci_vendor = pdev->vendor;
#ifdef __alpha__
dev->hose = pdev->sysdata;
#endif
mutex_lock(&drm_global_mutex);
if ((ret = drm_fill_in_dev(dev, ent, driver))) {
printk(KERN_ERR "DRM: Fill_in_dev failed.\n");
goto err_g2;
}
if (drm_core_check_feature(dev, DRIVER_MODESET)) {
pci_set_drvdata(pdev, dev);
ret = drm_get_minor(dev, &dev->control, DRM_MINOR_CONTROL);
if (ret)
goto err_g2;
}
if ((ret = drm_get_minor(dev, &dev->primary, DRM_MINOR_LEGACY)))
goto err_g3;
if (dev->driver->load) {
ret = dev->driver->load(dev, ent->driver_data);
if (ret)
goto err_g4;
}
/* setup the grouping for the legacy output */
if (drm_core_check_feature(dev, DRIVER_MODESET)) {
ret = drm_mode_group_init_legacy_group(dev,
&dev->primary->mode_group);
if (ret)
goto err_g4;
}
list_add_tail(&dev->driver_item, &driver->device_list);
DRM_INFO("Initialized %s %d.%d.%d %s for %s on minor %d\n",
driver->name, driver->major, driver->minor, driver->patchlevel,
driver->date, pci_name(pdev), dev->primary->index);
mutex_unlock(&drm_global_mutex);
return 0;
err_g4:
drm_put_minor(&dev->primary);
err_g3:
if (drm_core_check_feature(dev, DRIVER_MODESET))
drm_put_minor(&dev->control);
err_g2:
pci_disable_device(pdev);
err_g1:
kfree(dev);
mutex_unlock(&drm_global_mutex);
return ret;
}
EXPORT_SYMBOL(drm_get_pci_dev);
/**
* PCI device initialization. Called direct from modules at load time.
*
* \return zero on success or a negative number on failure.
*
* Initializes a drm_device structures,registering the
* stubs and initializing the AGP device.
*
* Expands the \c DRIVER_PREINIT and \c DRIVER_POST_INIT macros before and
* after the initialization for driver customization.
*/
int drm_pci_init(struct drm_driver *driver, struct pci_driver *pdriver)
{
struct pci_dev *pdev = NULL;
const struct pci_device_id *pid;
int i;
DRM_DEBUG("\n");
INIT_LIST_HEAD(&driver->device_list);
driver->kdriver.pci = pdriver;
driver->bus = &drm_pci_bus;
if (driver->driver_features & DRIVER_MODESET)
return pci_register_driver(pdriver);
/* If not using KMS, fall back to stealth mode manual scanning. */
for (i = 0; pdriver->id_table[i].vendor != 0; i++) {
pid = &pdriver->id_table[i];
/* Loop around setting up a DRM device for each PCI device
* matching our ID and device class. If we had the internal
* function that pci_get_subsys and pci_get_class used, we'd
* be able to just pass pid in instead of doing a two-stage
* thing.
*/
pdev = NULL;
while ((pdev =
pci_get_subsys(pid->vendor, pid->device, pid->subvendor,
pid->subdevice, pdev)) != NULL) {
if ((pdev->class & pid->class_mask) != pid->class)
continue;
/* stealth mode requires a manual probe */
pci_dev_get(pdev);
drm_get_pci_dev(pdev, pid, driver);
}
}
return 0;
}
#else
int drm_pci_init(struct drm_driver *driver, struct pci_driver *pdriver)
{
return -1;
}
#endif
EXPORT_SYMBOL(drm_pci_init);
/*@}*/
void drm_pci_exit(struct drm_driver *driver, struct pci_driver *pdriver)
{
struct drm_device *dev, *tmp;
DRM_DEBUG("\n");
if (driver->driver_features & DRIVER_MODESET) {
pci_unregister_driver(pdriver);
} else {
list_for_each_entry_safe(dev, tmp, &driver->device_list, driver_item)
drm_put_dev(dev);
}
DRM_INFO("Module unloaded\n");
}
EXPORT_SYMBOL(drm_pci_exit);
| gpl-2.0 |
bgat/linux-udoo | backports/drivers/media/pci/bt8xx/bttv-gpio.c | 1482 | 4878 | /*
bttv-gpio.c -- gpio sub drivers
sysfs-based sub driver interface for bttv
mainly intended for gpio access
Copyright (C) 1996,97,98 Ralph Metzler (rjkm@thp.uni-koeln.de)
& Marcus Metzler (mocm@thp.uni-koeln.de)
(c) 1999-2003 Gerd Knorr <kraxel@bytesex.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <asm/io.h>
#include "bttvp.h"
/* ----------------------------------------------------------------------- */
/* internal: the bttv "bus" */
static int bttv_sub_bus_match(struct device *dev, struct device_driver *drv)
{
struct bttv_sub_driver *sub = to_bttv_sub_drv(drv);
int len = strlen(sub->wanted);
if (0 == strncmp(dev_name(dev), sub->wanted, len))
return 1;
return 0;
}
static int bttv_sub_probe(struct device *dev)
{
struct bttv_sub_device *sdev = to_bttv_sub_dev(dev);
struct bttv_sub_driver *sub = to_bttv_sub_drv(dev->driver);
return sub->probe ? sub->probe(sdev) : -ENODEV;
}
static int bttv_sub_remove(struct device *dev)
{
struct bttv_sub_device *sdev = to_bttv_sub_dev(dev);
struct bttv_sub_driver *sub = to_bttv_sub_drv(dev->driver);
if (sub->remove)
sub->remove(sdev);
return 0;
}
struct bus_type bttv_sub_bus_type = {
.name = "bttv-sub",
.match = &bttv_sub_bus_match,
.probe = bttv_sub_probe,
.remove = bttv_sub_remove,
};
static void release_sub_device(struct device *dev)
{
struct bttv_sub_device *sub = to_bttv_sub_dev(dev);
kfree(sub);
}
int bttv_sub_add_device(struct bttv_core *core, char *name)
{
struct bttv_sub_device *sub;
int err;
sub = kzalloc(sizeof(*sub),GFP_KERNEL);
if (NULL == sub)
return -ENOMEM;
sub->core = core;
sub->dev.parent = &core->pci->dev;
sub->dev.bus = &bttv_sub_bus_type;
sub->dev.release = release_sub_device;
dev_set_name(&sub->dev, "%s%d", name, core->nr);
err = device_register(&sub->dev);
if (0 != err) {
put_device(&sub->dev);
return err;
}
pr_info("%d: add subdevice \"%s\"\n", core->nr, dev_name(&sub->dev));
list_add_tail(&sub->list,&core->subs);
return 0;
}
int bttv_sub_del_devices(struct bttv_core *core)
{
struct bttv_sub_device *sub, *save;
list_for_each_entry_safe(sub, save, &core->subs, list) {
list_del(&sub->list);
device_unregister(&sub->dev);
}
return 0;
}
/* ----------------------------------------------------------------------- */
/* external: sub-driver register/unregister */
int bttv_sub_register(struct bttv_sub_driver *sub, char *wanted)
{
sub->drv.bus = &bttv_sub_bus_type;
snprintf(sub->wanted,sizeof(sub->wanted),"%s",wanted);
return driver_register(&sub->drv);
}
EXPORT_SYMBOL(bttv_sub_register);
int bttv_sub_unregister(struct bttv_sub_driver *sub)
{
driver_unregister(&sub->drv);
return 0;
}
EXPORT_SYMBOL(bttv_sub_unregister);
/* ----------------------------------------------------------------------- */
/* external: gpio access functions */
void bttv_gpio_inout(struct bttv_core *core, u32 mask, u32 outbits)
{
struct bttv *btv = container_of(core, struct bttv, c);
unsigned long flags;
u32 data;
spin_lock_irqsave(&btv->gpio_lock,flags);
data = btread(BT848_GPIO_OUT_EN);
data = data & ~mask;
data = data | (mask & outbits);
btwrite(data,BT848_GPIO_OUT_EN);
spin_unlock_irqrestore(&btv->gpio_lock,flags);
}
u32 bttv_gpio_read(struct bttv_core *core)
{
struct bttv *btv = container_of(core, struct bttv, c);
u32 value;
value = btread(BT848_GPIO_DATA);
return value;
}
void bttv_gpio_write(struct bttv_core *core, u32 value)
{
struct bttv *btv = container_of(core, struct bttv, c);
btwrite(value,BT848_GPIO_DATA);
}
void bttv_gpio_bits(struct bttv_core *core, u32 mask, u32 bits)
{
struct bttv *btv = container_of(core, struct bttv, c);
unsigned long flags;
u32 data;
spin_lock_irqsave(&btv->gpio_lock,flags);
data = btread(BT848_GPIO_DATA);
data = data & ~mask;
data = data | (mask & bits);
btwrite(data,BT848_GPIO_DATA);
spin_unlock_irqrestore(&btv->gpio_lock,flags);
}
| gpl-2.0 |
yu-validus/kernel_cyanogen_msm8916 | drivers/mfd/intel_msic.c | 1994 | 11659 | /*
* Driver for Intel MSIC
*
* Copyright (C) 2011, Intel Corporation
* Author: Mika Westerberg <mika.westerberg@linux.intel.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/err.h>
#include <linux/gpio.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/mfd/core.h>
#include <linux/mfd/intel_msic.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <asm/intel_scu_ipc.h>
#define MSIC_VENDOR(id) ((id >> 6) & 3)
#define MSIC_VERSION(id) (id & 0x3f)
#define MSIC_MAJOR(id) ('A' + ((id >> 3) & 7))
#define MSIC_MINOR(id) (id & 7)
/*
* MSIC interrupt tree is readable from SRAM at INTEL_MSIC_IRQ_PHYS_BASE.
* Since IRQ block starts from address 0x002 we need to substract that from
* the actual IRQ status register address.
*/
#define MSIC_IRQ_STATUS(x) (INTEL_MSIC_IRQ_PHYS_BASE + ((x) - 2))
#define MSIC_IRQ_STATUS_ACCDET MSIC_IRQ_STATUS(INTEL_MSIC_ACCDET)
/*
* The SCU hardware has limitation of 16 bytes per read/write buffer on
* Medfield.
*/
#define SCU_IPC_RWBUF_LIMIT 16
/**
* struct intel_msic - an MSIC MFD instance
* @pdev: pointer to the platform device
* @vendor: vendor ID
* @version: chip version
* @irq_base: base address of the mapped MSIC SRAM interrupt tree
*/
struct intel_msic {
struct platform_device *pdev;
unsigned vendor;
unsigned version;
void __iomem *irq_base;
};
static struct resource msic_touch_resources[] = {
{
.flags = IORESOURCE_IRQ,
},
};
static struct resource msic_adc_resources[] = {
{
.flags = IORESOURCE_IRQ,
},
};
static struct resource msic_battery_resources[] = {
{
.flags = IORESOURCE_IRQ,
},
};
static struct resource msic_gpio_resources[] = {
{
.flags = IORESOURCE_IRQ,
},
};
static struct resource msic_audio_resources[] = {
{
.name = "IRQ",
.flags = IORESOURCE_IRQ,
},
/*
* We will pass IRQ_BASE to the driver now but this can be removed
* when/if the driver starts to use intel_msic_irq_read().
*/
{
.name = "IRQ_BASE",
.flags = IORESOURCE_MEM,
.start = MSIC_IRQ_STATUS_ACCDET,
.end = MSIC_IRQ_STATUS_ACCDET,
},
};
static struct resource msic_hdmi_resources[] = {
{
.flags = IORESOURCE_IRQ,
},
};
static struct resource msic_thermal_resources[] = {
{
.flags = IORESOURCE_IRQ,
},
};
static struct resource msic_power_btn_resources[] = {
{
.flags = IORESOURCE_IRQ,
},
};
static struct resource msic_ocd_resources[] = {
{
.flags = IORESOURCE_IRQ,
},
};
/*
* Devices that are part of the MSIC and are available via firmware
* populated SFI DEVS table.
*/
static struct mfd_cell msic_devs[] = {
[INTEL_MSIC_BLOCK_TOUCH] = {
.name = "msic_touch",
.num_resources = ARRAY_SIZE(msic_touch_resources),
.resources = msic_touch_resources,
},
[INTEL_MSIC_BLOCK_ADC] = {
.name = "msic_adc",
.num_resources = ARRAY_SIZE(msic_adc_resources),
.resources = msic_adc_resources,
},
[INTEL_MSIC_BLOCK_BATTERY] = {
.name = "msic_battery",
.num_resources = ARRAY_SIZE(msic_battery_resources),
.resources = msic_battery_resources,
},
[INTEL_MSIC_BLOCK_GPIO] = {
.name = "msic_gpio",
.num_resources = ARRAY_SIZE(msic_gpio_resources),
.resources = msic_gpio_resources,
},
[INTEL_MSIC_BLOCK_AUDIO] = {
.name = "msic_audio",
.num_resources = ARRAY_SIZE(msic_audio_resources),
.resources = msic_audio_resources,
},
[INTEL_MSIC_BLOCK_HDMI] = {
.name = "msic_hdmi",
.num_resources = ARRAY_SIZE(msic_hdmi_resources),
.resources = msic_hdmi_resources,
},
[INTEL_MSIC_BLOCK_THERMAL] = {
.name = "msic_thermal",
.num_resources = ARRAY_SIZE(msic_thermal_resources),
.resources = msic_thermal_resources,
},
[INTEL_MSIC_BLOCK_POWER_BTN] = {
.name = "msic_power_btn",
.num_resources = ARRAY_SIZE(msic_power_btn_resources),
.resources = msic_power_btn_resources,
},
[INTEL_MSIC_BLOCK_OCD] = {
.name = "msic_ocd",
.num_resources = ARRAY_SIZE(msic_ocd_resources),
.resources = msic_ocd_resources,
},
};
/*
* Other MSIC related devices which are not directly available via SFI DEVS
* table. These can be pseudo devices, regulators etc. which are needed for
* different purposes.
*
* These devices appear only after the MSIC driver itself is initialized so
* we can guarantee that the SCU IPC interface is ready.
*/
static struct mfd_cell msic_other_devs[] = {
/* Audio codec in the MSIC */
{
.id = -1,
.name = "sn95031",
},
};
/**
* intel_msic_reg_read - read a single MSIC register
* @reg: register to read
* @val: register value is placed here
*
* Read a single register from MSIC. Returns %0 on success and negative
* errno in case of failure.
*
* Function may sleep.
*/
int intel_msic_reg_read(unsigned short reg, u8 *val)
{
return intel_scu_ipc_ioread8(reg, val);
}
EXPORT_SYMBOL_GPL(intel_msic_reg_read);
/**
* intel_msic_reg_write - write a single MSIC register
* @reg: register to write
* @val: value to write to that register
*
* Write a single MSIC register. Returns 0 on success and negative
* errno in case of failure.
*
* Function may sleep.
*/
int intel_msic_reg_write(unsigned short reg, u8 val)
{
return intel_scu_ipc_iowrite8(reg, val);
}
EXPORT_SYMBOL_GPL(intel_msic_reg_write);
/**
* intel_msic_reg_update - update a single MSIC register
* @reg: register to update
* @val: value to write to the register
* @mask: specifies which of the bits are updated (%0 = don't update,
* %1 = update)
*
* Perform an update to a register @reg. @mask is used to specify which
* bits are updated. Returns %0 in case of success and negative errno in
* case of failure.
*
* Function may sleep.
*/
int intel_msic_reg_update(unsigned short reg, u8 val, u8 mask)
{
return intel_scu_ipc_update_register(reg, val, mask);
}
EXPORT_SYMBOL_GPL(intel_msic_reg_update);
/**
* intel_msic_bulk_read - read an array of registers
* @reg: array of register addresses to read
* @buf: array where the read values are placed
* @count: number of registers to read
*
* Function reads @count registers from the MSIC using addresses passed in
* @reg. Read values are placed in @buf. Reads are performed atomically
* wrt. MSIC.
*
* Returns %0 in case of success and negative errno in case of failure.
*
* Function may sleep.
*/
int intel_msic_bulk_read(unsigned short *reg, u8 *buf, size_t count)
{
if (WARN_ON(count > SCU_IPC_RWBUF_LIMIT))
return -EINVAL;
return intel_scu_ipc_readv(reg, buf, count);
}
EXPORT_SYMBOL_GPL(intel_msic_bulk_read);
/**
* intel_msic_bulk_write - write an array of values to the MSIC registers
* @reg: array of registers to write
* @buf: values to write to each register
* @count: number of registers to write
*
* Function writes @count registers in @buf to MSIC. Writes are performed
* atomically wrt MSIC. Returns %0 in case of success and negative errno in
* case of failure.
*
* Function may sleep.
*/
int intel_msic_bulk_write(unsigned short *reg, u8 *buf, size_t count)
{
if (WARN_ON(count > SCU_IPC_RWBUF_LIMIT))
return -EINVAL;
return intel_scu_ipc_writev(reg, buf, count);
}
EXPORT_SYMBOL_GPL(intel_msic_bulk_write);
/**
* intel_msic_irq_read - read a register from an MSIC interrupt tree
* @msic: MSIC instance
* @reg: interrupt register (between %INTEL_MSIC_IRQLVL1 and
* %INTEL_MSIC_RESETIRQ2)
* @val: value of the register is placed here
*
* This function can be used by an MSIC subdevice interrupt handler to read
* a register value from the MSIC interrupt tree. In this way subdevice
* drivers don't have to map in the interrupt tree themselves but can just
* call this function instead.
*
* Function doesn't sleep and is callable from interrupt context.
*
* Returns %-EINVAL if @reg is outside of the allowed register region.
*/
int intel_msic_irq_read(struct intel_msic *msic, unsigned short reg, u8 *val)
{
if (WARN_ON(reg < INTEL_MSIC_IRQLVL1 || reg > INTEL_MSIC_RESETIRQ2))
return -EINVAL;
*val = readb(msic->irq_base + (reg - INTEL_MSIC_IRQLVL1));
return 0;
}
EXPORT_SYMBOL_GPL(intel_msic_irq_read);
static int intel_msic_init_devices(struct intel_msic *msic)
{
struct platform_device *pdev = msic->pdev;
struct intel_msic_platform_data *pdata = pdev->dev.platform_data;
int ret, i;
if (pdata->gpio) {
struct mfd_cell *cell = &msic_devs[INTEL_MSIC_BLOCK_GPIO];
cell->platform_data = pdata->gpio;
cell->pdata_size = sizeof(*pdata->gpio);
}
if (pdata->ocd) {
unsigned gpio = pdata->ocd->gpio;
ret = devm_gpio_request_one(&pdev->dev, gpio,
GPIOF_IN, "ocd_gpio");
if (ret) {
dev_err(&pdev->dev, "failed to register OCD GPIO\n");
return ret;
}
ret = gpio_to_irq(gpio);
if (ret < 0) {
dev_err(&pdev->dev, "no IRQ number for OCD GPIO\n");
return ret;
}
/* Update the IRQ number for the OCD */
pdata->irq[INTEL_MSIC_BLOCK_OCD] = ret;
}
for (i = 0; i < ARRAY_SIZE(msic_devs); i++) {
if (!pdata->irq[i])
continue;
ret = mfd_add_devices(&pdev->dev, -1, &msic_devs[i], 1, NULL,
pdata->irq[i], NULL);
if (ret)
goto fail;
}
ret = mfd_add_devices(&pdev->dev, 0, msic_other_devs,
ARRAY_SIZE(msic_other_devs), NULL, 0, NULL);
if (ret)
goto fail;
return 0;
fail:
mfd_remove_devices(&pdev->dev);
return ret;
}
static void intel_msic_remove_devices(struct intel_msic *msic)
{
struct platform_device *pdev = msic->pdev;
mfd_remove_devices(&pdev->dev);
}
static int intel_msic_probe(struct platform_device *pdev)
{
struct intel_msic_platform_data *pdata = pdev->dev.platform_data;
struct intel_msic *msic;
struct resource *res;
u8 id0, id1;
int ret;
if (!pdata) {
dev_err(&pdev->dev, "no platform data passed\n");
return -EINVAL;
}
/* First validate that we have an MSIC in place */
ret = intel_scu_ipc_ioread8(INTEL_MSIC_ID0, &id0);
if (ret) {
dev_err(&pdev->dev, "failed to identify the MSIC chip (ID0)\n");
return -ENXIO;
}
ret = intel_scu_ipc_ioread8(INTEL_MSIC_ID1, &id1);
if (ret) {
dev_err(&pdev->dev, "failed to identify the MSIC chip (ID1)\n");
return -ENXIO;
}
if (MSIC_VENDOR(id0) != MSIC_VENDOR(id1)) {
dev_err(&pdev->dev, "invalid vendor ID: %x, %x\n", id0, id1);
return -ENXIO;
}
msic = devm_kzalloc(&pdev->dev, sizeof(*msic), GFP_KERNEL);
if (!msic)
return -ENOMEM;
msic->vendor = MSIC_VENDOR(id0);
msic->version = MSIC_VERSION(id0);
msic->pdev = pdev;
/*
* Map in the MSIC interrupt tree area in SRAM. This is exposed to
* the clients via intel_msic_irq_read().
*/
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
msic->irq_base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(msic->irq_base))
return PTR_ERR(msic->irq_base);
platform_set_drvdata(pdev, msic);
ret = intel_msic_init_devices(msic);
if (ret) {
dev_err(&pdev->dev, "failed to initialize MSIC devices\n");
return ret;
}
dev_info(&pdev->dev, "Intel MSIC version %c%d (vendor %#x)\n",
MSIC_MAJOR(msic->version), MSIC_MINOR(msic->version),
msic->vendor);
return 0;
}
static int intel_msic_remove(struct platform_device *pdev)
{
struct intel_msic *msic = platform_get_drvdata(pdev);
intel_msic_remove_devices(msic);
platform_set_drvdata(pdev, NULL);
return 0;
}
static struct platform_driver intel_msic_driver = {
.probe = intel_msic_probe,
.remove = intel_msic_remove,
.driver = {
.name = "intel_msic",
.owner = THIS_MODULE,
},
};
module_platform_driver(intel_msic_driver);
MODULE_DESCRIPTION("Driver for Intel MSIC");
MODULE_AUTHOR("Mika Westerberg <mika.westerberg@linux.intel.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
zhaolin1230/kernel_sony_msm8x60 | drivers/usb/serial/metro-usb.c | 2762 | 11185 | /*
Some of this code is credited to Linux USB open source files that are
distributed with Linux.
Copyright: 2007 Metrologic Instruments. All rights reserved.
Copyright: 2011 Azimut Ltd. <http://azimutrzn.ru/>
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/tty.h>
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/moduleparam.h>
#include <linux/spinlock.h>
#include <linux/errno.h>
#include <linux/uaccess.h>
#include <linux/usb/serial.h>
/* Version Information */
#define DRIVER_VERSION "v1.2.0.0"
#define DRIVER_DESC "Metrologic Instruments Inc. - USB-POS driver"
/* Product information. */
#define FOCUS_VENDOR_ID 0x0C2E
#define FOCUS_PRODUCT_ID_BI 0x0720
#define FOCUS_PRODUCT_ID_UNI 0x0700
#define METROUSB_SET_REQUEST_TYPE 0x40
#define METROUSB_SET_MODEM_CTRL_REQUEST 10
#define METROUSB_SET_BREAK_REQUEST 0x40
#define METROUSB_MCR_NONE 0x08 /* Deactivate DTR and RTS. */
#define METROUSB_MCR_RTS 0x0a /* Activate RTS. */
#define METROUSB_MCR_DTR 0x09 /* Activate DTR. */
#define WDR_TIMEOUT 5000 /* default urb timeout. */
/* Private data structure. */
struct metrousb_private {
spinlock_t lock;
int throttled;
unsigned long control_state;
};
/* Device table list. */
static struct usb_device_id id_table[] = {
{ USB_DEVICE(FOCUS_VENDOR_ID, FOCUS_PRODUCT_ID_BI) },
{ USB_DEVICE(FOCUS_VENDOR_ID, FOCUS_PRODUCT_ID_UNI) },
{ }, /* Terminating entry. */
};
MODULE_DEVICE_TABLE(usb, id_table);
/* Input parameter constants. */
static bool debug;
static void metrousb_read_int_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct metrousb_private *metro_priv = usb_get_serial_port_data(port);
struct tty_struct *tty;
unsigned char *data = urb->transfer_buffer;
int throttled = 0;
int result = 0;
unsigned long flags = 0;
dev_dbg(&port->dev, "%s\n", __func__);
switch (urb->status) {
case 0:
/* Success status, read from the port. */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* urb has been terminated. */
dev_dbg(&port->dev,
"%s - urb shutting down, error code=%d\n",
__func__, result);
return;
default:
dev_dbg(&port->dev,
"%s - non-zero urb received, error code=%d\n",
__func__, result);
goto exit;
}
/* Set the data read from the usb port into the serial port buffer. */
tty = tty_port_tty_get(&port->port);
if (!tty) {
dev_dbg(&port->dev, "%s - bad tty pointer - exiting\n",
__func__);
return;
}
if (tty && urb->actual_length) {
/* Loop through the data copying each byte to the tty layer. */
tty_insert_flip_string(tty, data, urb->actual_length);
/* Force the data to the tty layer. */
tty_flip_buffer_push(tty);
}
tty_kref_put(tty);
/* Set any port variables. */
spin_lock_irqsave(&metro_priv->lock, flags);
throttled = metro_priv->throttled;
spin_unlock_irqrestore(&metro_priv->lock, flags);
/* Continue trying to read if set. */
if (!throttled) {
usb_fill_int_urb(port->interrupt_in_urb, port->serial->dev,
usb_rcvintpipe(port->serial->dev, port->interrupt_in_endpointAddress),
port->interrupt_in_urb->transfer_buffer,
port->interrupt_in_urb->transfer_buffer_length,
metrousb_read_int_callback, port, 1);
result = usb_submit_urb(port->interrupt_in_urb, GFP_ATOMIC);
if (result)
dev_dbg(&port->dev,
"%s - failed submitting interrupt in urb, error code=%d\n",
__func__, result);
}
return;
exit:
/* Try to resubmit the urb. */
result = usb_submit_urb(urb, GFP_ATOMIC);
if (result)
dev_dbg(&port->dev,
"%s - failed submitting interrupt in urb, error code=%d\n",
__func__, result);
}
static void metrousb_cleanup(struct usb_serial_port *port)
{
dev_dbg(&port->dev, "%s\n", __func__);
if (port->serial->dev) {
/* Shutdown any interrupt in urbs. */
if (port->interrupt_in_urb) {
usb_unlink_urb(port->interrupt_in_urb);
usb_kill_urb(port->interrupt_in_urb);
}
}
}
static int metrousb_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct usb_serial *serial = port->serial;
struct metrousb_private *metro_priv = usb_get_serial_port_data(port);
unsigned long flags = 0;
int result = 0;
dev_dbg(&port->dev, "%s\n", __func__);
/* Make sure the urb is initialized. */
if (!port->interrupt_in_urb) {
dev_dbg(&port->dev, "%s - interrupt urb not initialized\n",
__func__);
return -ENODEV;
}
/* Set the private data information for the port. */
spin_lock_irqsave(&metro_priv->lock, flags);
metro_priv->control_state = 0;
metro_priv->throttled = 0;
spin_unlock_irqrestore(&metro_priv->lock, flags);
/*
* Force low_latency on so that our tty_push actually forces the data
* through, otherwise it is scheduled, and with high data rates (like
* with OHCI) data can get lost.
*/
if (tty)
tty->low_latency = 1;
/* Clear the urb pipe. */
usb_clear_halt(serial->dev, port->interrupt_in_urb->pipe);
/* Start reading from the device */
usb_fill_int_urb(port->interrupt_in_urb, serial->dev,
usb_rcvintpipe(serial->dev, port->interrupt_in_endpointAddress),
port->interrupt_in_urb->transfer_buffer,
port->interrupt_in_urb->transfer_buffer_length,
metrousb_read_int_callback, port, 1);
result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL);
if (result) {
dev_dbg(&port->dev,
"%s - failed submitting interrupt in urb, error code=%d\n",
__func__, result);
goto exit;
}
dev_dbg(&port->dev, "%s - port open\n", __func__);
exit:
return result;
}
static int metrousb_set_modem_ctrl(struct usb_serial *serial, unsigned int control_state)
{
int retval = 0;
unsigned char mcr = METROUSB_MCR_NONE;
dev_dbg(&serial->dev->dev, "%s - control state = %d\n",
__func__, control_state);
/* Set the modem control value. */
if (control_state & TIOCM_DTR)
mcr |= METROUSB_MCR_DTR;
if (control_state & TIOCM_RTS)
mcr |= METROUSB_MCR_RTS;
/* Send the command to the usb port. */
retval = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
METROUSB_SET_REQUEST_TYPE, METROUSB_SET_MODEM_CTRL_REQUEST,
control_state, 0, NULL, 0, WDR_TIMEOUT);
if (retval < 0)
dev_dbg(&serial->dev->dev,
"%s - set modem ctrl=0x%x failed, error code=%d\n",
__func__, mcr, retval);
return retval;
}
static void metrousb_shutdown(struct usb_serial *serial)
{
int i = 0;
dev_dbg(&serial->dev->dev, "%s\n", __func__);
/* Stop reading and writing on all ports. */
for (i = 0; i < serial->num_ports; ++i) {
/* Close any open urbs. */
metrousb_cleanup(serial->port[i]);
/* Free memory. */
kfree(usb_get_serial_port_data(serial->port[i]));
usb_set_serial_port_data(serial->port[i], NULL);
dev_dbg(&serial->dev->dev, "%s - freed port number=%d\n",
__func__, serial->port[i]->number);
}
}
static int metrousb_startup(struct usb_serial *serial)
{
struct metrousb_private *metro_priv;
struct usb_serial_port *port;
int i = 0;
dev_dbg(&serial->dev->dev, "%s\n", __func__);
/* Loop through the serial ports setting up the private structures.
* Currently we only use one port. */
for (i = 0; i < serial->num_ports; ++i) {
port = serial->port[i];
/* Declare memory. */
metro_priv = kzalloc(sizeof(struct metrousb_private), GFP_KERNEL);
if (!metro_priv)
return -ENOMEM;
/* Initialize memory. */
spin_lock_init(&metro_priv->lock);
usb_set_serial_port_data(port, metro_priv);
dev_dbg(&serial->dev->dev, "%s - port number=%d\n ",
__func__, port->number);
}
return 0;
}
static void metrousb_throttle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct metrousb_private *metro_priv = usb_get_serial_port_data(port);
unsigned long flags = 0;
dev_dbg(tty->dev, "%s\n", __func__);
/* Set the private information for the port to stop reading data. */
spin_lock_irqsave(&metro_priv->lock, flags);
metro_priv->throttled = 1;
spin_unlock_irqrestore(&metro_priv->lock, flags);
}
static int metrousb_tiocmget(struct tty_struct *tty)
{
unsigned long control_state = 0;
struct usb_serial_port *port = tty->driver_data;
struct metrousb_private *metro_priv = usb_get_serial_port_data(port);
unsigned long flags = 0;
dev_dbg(tty->dev, "%s\n", __func__);
spin_lock_irqsave(&metro_priv->lock, flags);
control_state = metro_priv->control_state;
spin_unlock_irqrestore(&metro_priv->lock, flags);
return control_state;
}
static int metrousb_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct usb_serial_port *port = tty->driver_data;
struct usb_serial *serial = port->serial;
struct metrousb_private *metro_priv = usb_get_serial_port_data(port);
unsigned long flags = 0;
unsigned long control_state = 0;
dev_dbg(tty->dev, "%s - set=%d, clear=%d\n", __func__, set, clear);
spin_lock_irqsave(&metro_priv->lock, flags);
control_state = metro_priv->control_state;
/* Set the RTS and DTR values. */
if (set & TIOCM_RTS)
control_state |= TIOCM_RTS;
if (set & TIOCM_DTR)
control_state |= TIOCM_DTR;
if (clear & TIOCM_RTS)
control_state &= ~TIOCM_RTS;
if (clear & TIOCM_DTR)
control_state &= ~TIOCM_DTR;
metro_priv->control_state = control_state;
spin_unlock_irqrestore(&metro_priv->lock, flags);
return metrousb_set_modem_ctrl(serial, control_state);
}
static void metrousb_unthrottle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct metrousb_private *metro_priv = usb_get_serial_port_data(port);
unsigned long flags = 0;
int result = 0;
dev_dbg(tty->dev, "%s\n", __func__);
/* Set the private information for the port to resume reading data. */
spin_lock_irqsave(&metro_priv->lock, flags);
metro_priv->throttled = 0;
spin_unlock_irqrestore(&metro_priv->lock, flags);
/* Submit the urb to read from the port. */
port->interrupt_in_urb->dev = port->serial->dev;
result = usb_submit_urb(port->interrupt_in_urb, GFP_ATOMIC);
if (result)
dev_dbg(tty->dev,
"failed submitting interrupt in urb error code=%d\n",
result);
}
static struct usb_driver metrousb_driver = {
.name = "metro-usb",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = id_table
};
static struct usb_serial_driver metrousb_device = {
.driver = {
.owner = THIS_MODULE,
.name = "metro-usb",
},
.description = "Metrologic USB to serial converter.",
.id_table = id_table,
.num_ports = 1,
.open = metrousb_open,
.close = metrousb_cleanup,
.read_int_callback = metrousb_read_int_callback,
.attach = metrousb_startup,
.release = metrousb_shutdown,
.throttle = metrousb_throttle,
.unthrottle = metrousb_unthrottle,
.tiocmget = metrousb_tiocmget,
.tiocmset = metrousb_tiocmset,
};
static struct usb_serial_driver * const serial_drivers[] = {
&metrousb_device,
NULL,
};
module_usb_serial_driver(metrousb_driver, serial_drivers);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Philip Nicastro");
MODULE_AUTHOR("Aleksey Babahin <tamerlan311@gmail.com>");
MODULE_DESCRIPTION(DRIVER_DESC);
/* Module input parameters */
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Print debug info (bool 1=on, 0=off)");
| gpl-2.0 |
pio-masaki/android-kernel-at1s0 | drivers/net/wireless/orinoco/orinoco_tmd.c | 3530 | 6536 | /* orinoco_tmd.c
*
* Driver for Prism II devices which would usually be driven by orinoco_cs,
* but are connected to the PCI bus by a TMD7160.
*
* Copyright (C) 2003 Joerg Dorchain <joerg AT dorchain.net>
* based heavily upon orinoco_plx.c Copyright (C) 2001 Daniel Barlow
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License
* at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and
* limitations under the License.
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License version 2 (the "GPL"), in
* which case the provisions of the GPL are applicable instead of the
* above. If you wish to allow the use of your version of this file
* only under the terms of the GPL and not to allow others to use your
* version of this file under the MPL, indicate your decision by
* deleting the provisions above and replace them with the notice and
* other provisions required by the GPL. If you do not delete the
* provisions above, a recipient may use your version of this file
* under either the MPL or the GPL.
*
* The actual driving is done by main.c, this is just resource
* allocation stuff.
*
* This driver is modeled after the orinoco_plx driver. The main
* difference is that the TMD chip has only IO port ranges and doesn't
* provide access to the PCMCIA attribute space.
*
* Pheecom sells cards with the TMD chip as "ASIC version"
*/
#define DRIVER_NAME "orinoco_tmd"
#define PFX DRIVER_NAME ": "
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <pcmcia/cisreg.h>
#include "orinoco.h"
#include "orinoco_pci.h"
#define COR_VALUE (COR_LEVEL_REQ | COR_FUNC_ENA) /* Enable PC card with interrupt in level trigger */
#define COR_RESET (0x80) /* reset bit in the COR register */
#define TMD_RESET_TIME (500) /* milliseconds */
/*
* Do a soft reset of the card using the Configuration Option Register
*/
static int orinoco_tmd_cor_reset(struct orinoco_private *priv)
{
hermes_t *hw = &priv->hw;
struct orinoco_pci_card *card = priv->card;
unsigned long timeout;
u16 reg;
iowrite8(COR_VALUE | COR_RESET, card->bridge_io);
mdelay(1);
iowrite8(COR_VALUE, card->bridge_io);
mdelay(1);
/* Just in case, wait more until the card is no longer busy */
timeout = jiffies + (TMD_RESET_TIME * HZ / 1000);
reg = hermes_read_regn(hw, CMD);
while (time_before(jiffies, timeout) && (reg & HERMES_CMD_BUSY)) {
mdelay(1);
reg = hermes_read_regn(hw, CMD);
}
/* Still busy? */
if (reg & HERMES_CMD_BUSY) {
printk(KERN_ERR PFX "Busy timeout\n");
return -ETIMEDOUT;
}
return 0;
}
static int orinoco_tmd_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
int err;
struct orinoco_private *priv;
struct orinoco_pci_card *card;
void __iomem *hermes_io, *bridge_io;
err = pci_enable_device(pdev);
if (err) {
printk(KERN_ERR PFX "Cannot enable PCI device\n");
return err;
}
err = pci_request_regions(pdev, DRIVER_NAME);
if (err) {
printk(KERN_ERR PFX "Cannot obtain PCI resources\n");
goto fail_resources;
}
bridge_io = pci_iomap(pdev, 1, 0);
if (!bridge_io) {
printk(KERN_ERR PFX "Cannot map bridge registers\n");
err = -EIO;
goto fail_map_bridge;
}
hermes_io = pci_iomap(pdev, 2, 0);
if (!hermes_io) {
printk(KERN_ERR PFX "Cannot map chipset registers\n");
err = -EIO;
goto fail_map_hermes;
}
/* Allocate network device */
priv = alloc_orinocodev(sizeof(*card), &pdev->dev,
orinoco_tmd_cor_reset, NULL);
if (!priv) {
printk(KERN_ERR PFX "Cannot allocate network device\n");
err = -ENOMEM;
goto fail_alloc;
}
card = priv->card;
card->bridge_io = bridge_io;
hermes_struct_init(&priv->hw, hermes_io, HERMES_16BIT_REGSPACING);
err = request_irq(pdev->irq, orinoco_interrupt, IRQF_SHARED,
DRIVER_NAME, priv);
if (err) {
printk(KERN_ERR PFX "Cannot allocate IRQ %d\n", pdev->irq);
err = -EBUSY;
goto fail_irq;
}
err = orinoco_tmd_cor_reset(priv);
if (err) {
printk(KERN_ERR PFX "Initial reset failed\n");
goto fail;
}
err = orinoco_init(priv);
if (err) {
printk(KERN_ERR PFX "orinoco_init() failed\n");
goto fail;
}
err = orinoco_if_add(priv, 0, 0, NULL);
if (err) {
printk(KERN_ERR PFX "orinoco_if_add() failed\n");
goto fail;
}
pci_set_drvdata(pdev, priv);
return 0;
fail:
free_irq(pdev->irq, priv);
fail_irq:
pci_set_drvdata(pdev, NULL);
free_orinocodev(priv);
fail_alloc:
pci_iounmap(pdev, hermes_io);
fail_map_hermes:
pci_iounmap(pdev, bridge_io);
fail_map_bridge:
pci_release_regions(pdev);
fail_resources:
pci_disable_device(pdev);
return err;
}
static void __devexit orinoco_tmd_remove_one(struct pci_dev *pdev)
{
struct orinoco_private *priv = pci_get_drvdata(pdev);
struct orinoco_pci_card *card = priv->card;
orinoco_if_del(priv);
free_irq(pdev->irq, priv);
pci_set_drvdata(pdev, NULL);
free_orinocodev(priv);
pci_iounmap(pdev, priv->hw.iobase);
pci_iounmap(pdev, card->bridge_io);
pci_release_regions(pdev);
pci_disable_device(pdev);
}
static DEFINE_PCI_DEVICE_TABLE(orinoco_tmd_id_table) = {
{0x15e8, 0x0131, PCI_ANY_ID, PCI_ANY_ID,}, /* NDC and OEMs, e.g. pheecom */
{0,},
};
MODULE_DEVICE_TABLE(pci, orinoco_tmd_id_table);
static struct pci_driver orinoco_tmd_driver = {
.name = DRIVER_NAME,
.id_table = orinoco_tmd_id_table,
.probe = orinoco_tmd_init_one,
.remove = __devexit_p(orinoco_tmd_remove_one),
.suspend = orinoco_pci_suspend,
.resume = orinoco_pci_resume,
};
static char version[] __initdata = DRIVER_NAME " " DRIVER_VERSION
" (Joerg Dorchain <joerg@dorchain.net>)";
MODULE_AUTHOR("Joerg Dorchain <joerg@dorchain.net>");
MODULE_DESCRIPTION("Driver for wireless LAN cards using the TMD7160 PCI bridge");
MODULE_LICENSE("Dual MPL/GPL");
static int __init orinoco_tmd_init(void)
{
printk(KERN_DEBUG "%s\n", version);
return pci_register_driver(&orinoco_tmd_driver);
}
static void __exit orinoco_tmd_exit(void)
{
pci_unregister_driver(&orinoco_tmd_driver);
}
module_init(orinoco_tmd_init);
module_exit(orinoco_tmd_exit);
/*
* Local variables:
* c-indent-level: 8
* c-basic-offset: 8
* tab-width: 8
* End:
*/
| gpl-2.0 |
morogoku/MoRoKernel-I9300-4.4.4 | drivers/video/logo/logo.c | 4554 | 2446 |
/*
* Linux logo to be displayed on boot
*
* Copyright (C) 1996 Larry Ewing (lewing@isc.tamu.edu)
* Copyright (C) 1996,1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
* Copyright (C) 2001 Greg Banks <gnb@alphalink.com.au>
* Copyright (C) 2001 Jan-Benedict Glaw <jbglaw@lug-owl.de>
* Copyright (C) 2003 Geert Uytterhoeven <geert@linux-m68k.org>
*/
#include <linux/linux_logo.h>
#include <linux/stddef.h>
#include <linux/module.h>
#ifdef CONFIG_M68K
#include <asm/setup.h>
#endif
#ifdef CONFIG_MIPS
#include <asm/bootinfo.h>
#endif
static int nologo;
module_param(nologo, bool, 0);
MODULE_PARM_DESC(nologo, "Disables startup logo");
/* logo's are marked __initdata. Use __init_refok to tell
* modpost that it is intended that this function uses data
* marked __initdata.
*/
const struct linux_logo * __init_refok fb_find_logo(int depth)
{
const struct linux_logo *logo = NULL;
if (nologo)
return NULL;
if (depth >= 1) {
#ifdef CONFIG_LOGO_LINUX_MONO
/* Generic Linux logo */
logo = &logo_linux_mono;
#endif
#ifdef CONFIG_LOGO_SUPERH_MONO
/* SuperH Linux logo */
logo = &logo_superh_mono;
#endif
}
if (depth >= 4) {
#ifdef CONFIG_LOGO_LINUX_VGA16
/* Generic Linux logo */
logo = &logo_linux_vga16;
#endif
#ifdef CONFIG_LOGO_BLACKFIN_VGA16
/* Blackfin processor logo */
logo = &logo_blackfin_vga16;
#endif
#ifdef CONFIG_LOGO_SUPERH_VGA16
/* SuperH Linux logo */
logo = &logo_superh_vga16;
#endif
}
if (depth >= 8) {
#ifdef CONFIG_LOGO_LINUX_CLUT224
/* Generic Linux logo */
logo = &logo_linux_clut224;
#endif
#ifdef CONFIG_LOGO_BLACKFIN_CLUT224
/* Blackfin Linux logo */
logo = &logo_blackfin_clut224;
#endif
#ifdef CONFIG_LOGO_DEC_CLUT224
/* DEC Linux logo on MIPS/MIPS64 or ALPHA */
logo = &logo_dec_clut224;
#endif
#ifdef CONFIG_LOGO_MAC_CLUT224
/* Macintosh Linux logo on m68k */
if (MACH_IS_MAC)
logo = &logo_mac_clut224;
#endif
#ifdef CONFIG_LOGO_PARISC_CLUT224
/* PA-RISC Linux logo */
logo = &logo_parisc_clut224;
#endif
#ifdef CONFIG_LOGO_SGI_CLUT224
/* SGI Linux logo on MIPS/MIPS64 and VISWS */
logo = &logo_sgi_clut224;
#endif
#ifdef CONFIG_LOGO_SUN_CLUT224
/* Sun Linux logo */
logo = &logo_sun_clut224;
#endif
#ifdef CONFIG_LOGO_SUPERH_CLUT224
/* SuperH Linux logo */
logo = &logo_superh_clut224;
#endif
#ifdef CONFIG_LOGO_M32R_CLUT224
/* M32R Linux logo */
logo = &logo_m32r_clut224;
#endif
}
return logo;
}
EXPORT_SYMBOL_GPL(fb_find_logo);
| gpl-2.0 |
rachitrawat/Vengeance-Kernel-MSM7x27 | drivers/video/logo/logo.c | 4554 | 2446 |
/*
* Linux logo to be displayed on boot
*
* Copyright (C) 1996 Larry Ewing (lewing@isc.tamu.edu)
* Copyright (C) 1996,1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
* Copyright (C) 2001 Greg Banks <gnb@alphalink.com.au>
* Copyright (C) 2001 Jan-Benedict Glaw <jbglaw@lug-owl.de>
* Copyright (C) 2003 Geert Uytterhoeven <geert@linux-m68k.org>
*/
#include <linux/linux_logo.h>
#include <linux/stddef.h>
#include <linux/module.h>
#ifdef CONFIG_M68K
#include <asm/setup.h>
#endif
#ifdef CONFIG_MIPS
#include <asm/bootinfo.h>
#endif
static int nologo;
module_param(nologo, bool, 0);
MODULE_PARM_DESC(nologo, "Disables startup logo");
/* logo's are marked __initdata. Use __init_refok to tell
* modpost that it is intended that this function uses data
* marked __initdata.
*/
const struct linux_logo * __init_refok fb_find_logo(int depth)
{
const struct linux_logo *logo = NULL;
if (nologo)
return NULL;
if (depth >= 1) {
#ifdef CONFIG_LOGO_LINUX_MONO
/* Generic Linux logo */
logo = &logo_linux_mono;
#endif
#ifdef CONFIG_LOGO_SUPERH_MONO
/* SuperH Linux logo */
logo = &logo_superh_mono;
#endif
}
if (depth >= 4) {
#ifdef CONFIG_LOGO_LINUX_VGA16
/* Generic Linux logo */
logo = &logo_linux_vga16;
#endif
#ifdef CONFIG_LOGO_BLACKFIN_VGA16
/* Blackfin processor logo */
logo = &logo_blackfin_vga16;
#endif
#ifdef CONFIG_LOGO_SUPERH_VGA16
/* SuperH Linux logo */
logo = &logo_superh_vga16;
#endif
}
if (depth >= 8) {
#ifdef CONFIG_LOGO_LINUX_CLUT224
/* Generic Linux logo */
logo = &logo_linux_clut224;
#endif
#ifdef CONFIG_LOGO_BLACKFIN_CLUT224
/* Blackfin Linux logo */
logo = &logo_blackfin_clut224;
#endif
#ifdef CONFIG_LOGO_DEC_CLUT224
/* DEC Linux logo on MIPS/MIPS64 or ALPHA */
logo = &logo_dec_clut224;
#endif
#ifdef CONFIG_LOGO_MAC_CLUT224
/* Macintosh Linux logo on m68k */
if (MACH_IS_MAC)
logo = &logo_mac_clut224;
#endif
#ifdef CONFIG_LOGO_PARISC_CLUT224
/* PA-RISC Linux logo */
logo = &logo_parisc_clut224;
#endif
#ifdef CONFIG_LOGO_SGI_CLUT224
/* SGI Linux logo on MIPS/MIPS64 and VISWS */
logo = &logo_sgi_clut224;
#endif
#ifdef CONFIG_LOGO_SUN_CLUT224
/* Sun Linux logo */
logo = &logo_sun_clut224;
#endif
#ifdef CONFIG_LOGO_SUPERH_CLUT224
/* SuperH Linux logo */
logo = &logo_superh_clut224;
#endif
#ifdef CONFIG_LOGO_M32R_CLUT224
/* M32R Linux logo */
logo = &logo_m32r_clut224;
#endif
}
return logo;
}
EXPORT_SYMBOL_GPL(fb_find_logo);
| gpl-2.0 |
VegaDevTeam/android_kernel_pantech_ef52s | drivers/edac/i82860_edac.c | 4810 | 8841 | /*
* Intel 82860 Memory Controller kernel module
* (C) 2005 Red Hat (http://www.redhat.com)
* This file may be distributed under the terms of the
* GNU General Public License.
*
* Written by Ben Woodard <woodard@redhat.com>
* shamelessly copied from and based upon the edac_i82875 driver
* by Thayne Harbaugh of Linux Networx. (http://lnxi.com)
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/edac.h>
#include "edac_core.h"
#define I82860_REVISION " Ver: 2.0.2"
#define EDAC_MOD_STR "i82860_edac"
#define i82860_printk(level, fmt, arg...) \
edac_printk(level, "i82860", fmt, ##arg)
#define i82860_mc_printk(mci, level, fmt, arg...) \
edac_mc_chipset_printk(mci, level, "i82860", fmt, ##arg)
#ifndef PCI_DEVICE_ID_INTEL_82860_0
#define PCI_DEVICE_ID_INTEL_82860_0 0x2531
#endif /* PCI_DEVICE_ID_INTEL_82860_0 */
#define I82860_MCHCFG 0x50
#define I82860_GBA 0x60
#define I82860_GBA_MASK 0x7FF
#define I82860_GBA_SHIFT 24
#define I82860_ERRSTS 0xC8
#define I82860_EAP 0xE4
#define I82860_DERRCTL_STS 0xE2
enum i82860_chips {
I82860 = 0,
};
struct i82860_dev_info {
const char *ctl_name;
};
struct i82860_error_info {
u16 errsts;
u32 eap;
u16 derrsyn;
u16 errsts2;
};
static const struct i82860_dev_info i82860_devs[] = {
[I82860] = {
.ctl_name = "i82860"},
};
static struct pci_dev *mci_pdev; /* init dev: in case that AGP code
* has already registered driver
*/
static struct edac_pci_ctl_info *i82860_pci;
static void i82860_get_error_info(struct mem_ctl_info *mci,
struct i82860_error_info *info)
{
struct pci_dev *pdev;
pdev = to_pci_dev(mci->dev);
/*
* This is a mess because there is no atomic way to read all the
* registers at once and the registers can transition from CE being
* overwritten by UE.
*/
pci_read_config_word(pdev, I82860_ERRSTS, &info->errsts);
pci_read_config_dword(pdev, I82860_EAP, &info->eap);
pci_read_config_word(pdev, I82860_DERRCTL_STS, &info->derrsyn);
pci_read_config_word(pdev, I82860_ERRSTS, &info->errsts2);
pci_write_bits16(pdev, I82860_ERRSTS, 0x0003, 0x0003);
/*
* If the error is the same for both reads then the first set of reads
* is valid. If there is a change then there is a CE no info and the
* second set of reads is valid and should be UE info.
*/
if (!(info->errsts2 & 0x0003))
return;
if ((info->errsts ^ info->errsts2) & 0x0003) {
pci_read_config_dword(pdev, I82860_EAP, &info->eap);
pci_read_config_word(pdev, I82860_DERRCTL_STS, &info->derrsyn);
}
}
static int i82860_process_error_info(struct mem_ctl_info *mci,
struct i82860_error_info *info,
int handle_errors)
{
int row;
if (!(info->errsts2 & 0x0003))
return 0;
if (!handle_errors)
return 1;
if ((info->errsts ^ info->errsts2) & 0x0003) {
edac_mc_handle_ce_no_info(mci, "UE overwrote CE");
info->errsts = info->errsts2;
}
info->eap >>= PAGE_SHIFT;
row = edac_mc_find_csrow_by_page(mci, info->eap);
if (info->errsts & 0x0002)
edac_mc_handle_ue(mci, info->eap, 0, row, "i82860 UE");
else
edac_mc_handle_ce(mci, info->eap, 0, info->derrsyn, row, 0,
"i82860 UE");
return 1;
}
static void i82860_check(struct mem_ctl_info *mci)
{
struct i82860_error_info info;
debugf1("MC%d: %s()\n", mci->mc_idx, __func__);
i82860_get_error_info(mci, &info);
i82860_process_error_info(mci, &info, 1);
}
static void i82860_init_csrows(struct mem_ctl_info *mci, struct pci_dev *pdev)
{
unsigned long last_cumul_size;
u16 mchcfg_ddim; /* DRAM Data Integrity Mode 0=none, 2=edac */
u16 value;
u32 cumul_size;
struct csrow_info *csrow;
int index;
pci_read_config_word(pdev, I82860_MCHCFG, &mchcfg_ddim);
mchcfg_ddim = mchcfg_ddim & 0x180;
last_cumul_size = 0;
/* The group row boundary (GRA) reg values are boundary address
* for each DRAM row with a granularity of 16MB. GRA regs are
* cumulative; therefore GRA15 will contain the total memory contained
* in all eight rows.
*/
for (index = 0; index < mci->nr_csrows; index++) {
csrow = &mci->csrows[index];
pci_read_config_word(pdev, I82860_GBA + index * 2, &value);
cumul_size = (value & I82860_GBA_MASK) <<
(I82860_GBA_SHIFT - PAGE_SHIFT);
debugf3("%s(): (%d) cumul_size 0x%x\n", __func__, index,
cumul_size);
if (cumul_size == last_cumul_size)
continue; /* not populated */
csrow->first_page = last_cumul_size;
csrow->last_page = cumul_size - 1;
csrow->nr_pages = cumul_size - last_cumul_size;
last_cumul_size = cumul_size;
csrow->grain = 1 << 12; /* I82860_EAP has 4KiB reolution */
csrow->mtype = MEM_RMBS;
csrow->dtype = DEV_UNKNOWN;
csrow->edac_mode = mchcfg_ddim ? EDAC_SECDED : EDAC_NONE;
}
}
static int i82860_probe1(struct pci_dev *pdev, int dev_idx)
{
struct mem_ctl_info *mci;
struct i82860_error_info discard;
/* RDRAM has channels but these don't map onto the abstractions that
edac uses.
The device groups from the GRA registers seem to map reasonably
well onto the notion of a chip select row.
There are 16 GRA registers and since the name is associated with
the channel and the GRA registers map to physical devices so we are
going to make 1 channel for group.
*/
mci = edac_mc_alloc(0, 16, 1, 0);
if (!mci)
return -ENOMEM;
debugf3("%s(): init mci\n", __func__);
mci->dev = &pdev->dev;
mci->mtype_cap = MEM_FLAG_DDR;
mci->edac_ctl_cap = EDAC_FLAG_NONE | EDAC_FLAG_SECDED;
/* I"m not sure about this but I think that all RDRAM is SECDED */
mci->edac_cap = EDAC_FLAG_SECDED;
mci->mod_name = EDAC_MOD_STR;
mci->mod_ver = I82860_REVISION;
mci->ctl_name = i82860_devs[dev_idx].ctl_name;
mci->dev_name = pci_name(pdev);
mci->edac_check = i82860_check;
mci->ctl_page_to_phys = NULL;
i82860_init_csrows(mci, pdev);
i82860_get_error_info(mci, &discard); /* clear counters */
/* Here we assume that we will never see multiple instances of this
* type of memory controller. The ID is therefore hardcoded to 0.
*/
if (edac_mc_add_mc(mci)) {
debugf3("%s(): failed edac_mc_add_mc()\n", __func__);
goto fail;
}
/* allocating generic PCI control info */
i82860_pci = edac_pci_create_generic_ctl(&pdev->dev, EDAC_MOD_STR);
if (!i82860_pci) {
printk(KERN_WARNING
"%s(): Unable to create PCI control\n",
__func__);
printk(KERN_WARNING
"%s(): PCI error report via EDAC not setup\n",
__func__);
}
/* get this far and it's successful */
debugf3("%s(): success\n", __func__);
return 0;
fail:
edac_mc_free(mci);
return -ENODEV;
}
/* returns count (>= 0), or negative on error */
static int __devinit i82860_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
int rc;
debugf0("%s()\n", __func__);
i82860_printk(KERN_INFO, "i82860 init one\n");
if (pci_enable_device(pdev) < 0)
return -EIO;
rc = i82860_probe1(pdev, ent->driver_data);
if (rc == 0)
mci_pdev = pci_dev_get(pdev);
return rc;
}
static void __devexit i82860_remove_one(struct pci_dev *pdev)
{
struct mem_ctl_info *mci;
debugf0("%s()\n", __func__);
if (i82860_pci)
edac_pci_release_generic_ctl(i82860_pci);
if ((mci = edac_mc_del_mc(&pdev->dev)) == NULL)
return;
edac_mc_free(mci);
}
static DEFINE_PCI_DEVICE_TABLE(i82860_pci_tbl) = {
{
PCI_VEND_DEV(INTEL, 82860_0), PCI_ANY_ID, PCI_ANY_ID, 0, 0,
I82860},
{
0,
} /* 0 terminated list. */
};
MODULE_DEVICE_TABLE(pci, i82860_pci_tbl);
static struct pci_driver i82860_driver = {
.name = EDAC_MOD_STR,
.probe = i82860_init_one,
.remove = __devexit_p(i82860_remove_one),
.id_table = i82860_pci_tbl,
};
static int __init i82860_init(void)
{
int pci_rc;
debugf3("%s()\n", __func__);
/* Ensure that the OPSTATE is set correctly for POLL or NMI */
opstate_init();
if ((pci_rc = pci_register_driver(&i82860_driver)) < 0)
goto fail0;
if (!mci_pdev) {
mci_pdev = pci_get_device(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_82860_0, NULL);
if (mci_pdev == NULL) {
debugf0("860 pci_get_device fail\n");
pci_rc = -ENODEV;
goto fail1;
}
pci_rc = i82860_init_one(mci_pdev, i82860_pci_tbl);
if (pci_rc < 0) {
debugf0("860 init fail\n");
pci_rc = -ENODEV;
goto fail1;
}
}
return 0;
fail1:
pci_unregister_driver(&i82860_driver);
fail0:
if (mci_pdev != NULL)
pci_dev_put(mci_pdev);
return pci_rc;
}
static void __exit i82860_exit(void)
{
debugf3("%s()\n", __func__);
pci_unregister_driver(&i82860_driver);
if (mci_pdev != NULL)
pci_dev_put(mci_pdev);
}
module_init(i82860_init);
module_exit(i82860_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Red Hat Inc. (http://www.redhat.com) "
"Ben Woodard <woodard@redhat.com>");
MODULE_DESCRIPTION("ECC support for Intel 82860 memory hub controllers");
module_param(edac_op_state, int, 0444);
MODULE_PARM_DESC(edac_op_state, "EDAC Error Reporting state: 0=Poll,1=NMI");
| gpl-2.0 |
kurisuxx/android_kernel_samsung_klimtlte | drivers/media/video/tvp5150.c | 4810 | 33824 | /*
* tvp5150 - Texas Instruments TVP5150A/AM1 video decoder driver
*
* Copyright (c) 2005,2006 Mauro Carvalho Chehab (mchehab@infradead.org)
* This code is placed under the terms of the GNU General Public License v2
*/
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/videodev2.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <media/v4l2-device.h>
#include <media/tvp5150.h>
#include <media/v4l2-chip-ident.h>
#include <media/v4l2-ctrls.h>
#include "tvp5150_reg.h"
#define TVP5150_H_MAX 720
#define TVP5150_V_MAX_525_60 480
#define TVP5150_V_MAX_OTHERS 576
#define TVP5150_MAX_CROP_LEFT 511
#define TVP5150_MAX_CROP_TOP 127
#define TVP5150_CROP_SHIFT 2
MODULE_DESCRIPTION("Texas Instruments TVP5150A video decoder driver");
MODULE_AUTHOR("Mauro Carvalho Chehab");
MODULE_LICENSE("GPL");
static int debug;
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0-2)");
struct tvp5150 {
struct v4l2_subdev sd;
struct v4l2_ctrl_handler hdl;
struct v4l2_rect rect;
v4l2_std_id norm; /* Current set standard */
u32 input;
u32 output;
int enable;
};
static inline struct tvp5150 *to_tvp5150(struct v4l2_subdev *sd)
{
return container_of(sd, struct tvp5150, sd);
}
static inline struct v4l2_subdev *to_sd(struct v4l2_ctrl *ctrl)
{
return &container_of(ctrl->handler, struct tvp5150, hdl)->sd;
}
static int tvp5150_read(struct v4l2_subdev *sd, unsigned char addr)
{
struct i2c_client *c = v4l2_get_subdevdata(sd);
unsigned char buffer[1];
int rc;
buffer[0] = addr;
if (1 != (rc = i2c_master_send(c, buffer, 1)))
v4l2_dbg(0, debug, sd, "i2c i/o error: rc == %d (should be 1)\n", rc);
msleep(10);
if (1 != (rc = i2c_master_recv(c, buffer, 1)))
v4l2_dbg(0, debug, sd, "i2c i/o error: rc == %d (should be 1)\n", rc);
v4l2_dbg(2, debug, sd, "tvp5150: read 0x%02x = 0x%02x\n", addr, buffer[0]);
return (buffer[0]);
}
static inline void tvp5150_write(struct v4l2_subdev *sd, unsigned char addr,
unsigned char value)
{
struct i2c_client *c = v4l2_get_subdevdata(sd);
unsigned char buffer[2];
int rc;
buffer[0] = addr;
buffer[1] = value;
v4l2_dbg(2, debug, sd, "tvp5150: writing 0x%02x 0x%02x\n", buffer[0], buffer[1]);
if (2 != (rc = i2c_master_send(c, buffer, 2)))
v4l2_dbg(0, debug, sd, "i2c i/o error: rc == %d (should be 2)\n", rc);
}
static void dump_reg_range(struct v4l2_subdev *sd, char *s, u8 init,
const u8 end, int max_line)
{
int i = 0;
while (init != (u8)(end + 1)) {
if ((i % max_line) == 0) {
if (i > 0)
printk("\n");
printk("tvp5150: %s reg 0x%02x = ", s, init);
}
printk("%02x ", tvp5150_read(sd, init));
init++;
i++;
}
printk("\n");
}
static int tvp5150_log_status(struct v4l2_subdev *sd)
{
printk("tvp5150: Video input source selection #1 = 0x%02x\n",
tvp5150_read(sd, TVP5150_VD_IN_SRC_SEL_1));
printk("tvp5150: Analog channel controls = 0x%02x\n",
tvp5150_read(sd, TVP5150_ANAL_CHL_CTL));
printk("tvp5150: Operation mode controls = 0x%02x\n",
tvp5150_read(sd, TVP5150_OP_MODE_CTL));
printk("tvp5150: Miscellaneous controls = 0x%02x\n",
tvp5150_read(sd, TVP5150_MISC_CTL));
printk("tvp5150: Autoswitch mask= 0x%02x\n",
tvp5150_read(sd, TVP5150_AUTOSW_MSK));
printk("tvp5150: Color killer threshold control = 0x%02x\n",
tvp5150_read(sd, TVP5150_COLOR_KIL_THSH_CTL));
printk("tvp5150: Luminance processing controls #1 #2 and #3 = %02x %02x %02x\n",
tvp5150_read(sd, TVP5150_LUMA_PROC_CTL_1),
tvp5150_read(sd, TVP5150_LUMA_PROC_CTL_2),
tvp5150_read(sd, TVP5150_LUMA_PROC_CTL_3));
printk("tvp5150: Brightness control = 0x%02x\n",
tvp5150_read(sd, TVP5150_BRIGHT_CTL));
printk("tvp5150: Color saturation control = 0x%02x\n",
tvp5150_read(sd, TVP5150_SATURATION_CTL));
printk("tvp5150: Hue control = 0x%02x\n",
tvp5150_read(sd, TVP5150_HUE_CTL));
printk("tvp5150: Contrast control = 0x%02x\n",
tvp5150_read(sd, TVP5150_CONTRAST_CTL));
printk("tvp5150: Outputs and data rates select = 0x%02x\n",
tvp5150_read(sd, TVP5150_DATA_RATE_SEL));
printk("tvp5150: Configuration shared pins = 0x%02x\n",
tvp5150_read(sd, TVP5150_CONF_SHARED_PIN));
printk("tvp5150: Active video cropping start = 0x%02x%02x\n",
tvp5150_read(sd, TVP5150_ACT_VD_CROP_ST_MSB),
tvp5150_read(sd, TVP5150_ACT_VD_CROP_ST_LSB));
printk("tvp5150: Active video cropping stop = 0x%02x%02x\n",
tvp5150_read(sd, TVP5150_ACT_VD_CROP_STP_MSB),
tvp5150_read(sd, TVP5150_ACT_VD_CROP_STP_LSB));
printk("tvp5150: Genlock/RTC = 0x%02x\n",
tvp5150_read(sd, TVP5150_GENLOCK));
printk("tvp5150: Horizontal sync start = 0x%02x\n",
tvp5150_read(sd, TVP5150_HORIZ_SYNC_START));
printk("tvp5150: Vertical blanking start = 0x%02x\n",
tvp5150_read(sd, TVP5150_VERT_BLANKING_START));
printk("tvp5150: Vertical blanking stop = 0x%02x\n",
tvp5150_read(sd, TVP5150_VERT_BLANKING_STOP));
printk("tvp5150: Chrominance processing control #1 and #2 = %02x %02x\n",
tvp5150_read(sd, TVP5150_CHROMA_PROC_CTL_1),
tvp5150_read(sd, TVP5150_CHROMA_PROC_CTL_2));
printk("tvp5150: Interrupt reset register B = 0x%02x\n",
tvp5150_read(sd, TVP5150_INT_RESET_REG_B));
printk("tvp5150: Interrupt enable register B = 0x%02x\n",
tvp5150_read(sd, TVP5150_INT_ENABLE_REG_B));
printk("tvp5150: Interrupt configuration register B = 0x%02x\n",
tvp5150_read(sd, TVP5150_INTT_CONFIG_REG_B));
printk("tvp5150: Video standard = 0x%02x\n",
tvp5150_read(sd, TVP5150_VIDEO_STD));
printk("tvp5150: Chroma gain factor: Cb=0x%02x Cr=0x%02x\n",
tvp5150_read(sd, TVP5150_CB_GAIN_FACT),
tvp5150_read(sd, TVP5150_CR_GAIN_FACTOR));
printk("tvp5150: Macrovision on counter = 0x%02x\n",
tvp5150_read(sd, TVP5150_MACROVISION_ON_CTR));
printk("tvp5150: Macrovision off counter = 0x%02x\n",
tvp5150_read(sd, TVP5150_MACROVISION_OFF_CTR));
printk("tvp5150: ITU-R BT.656.%d timing(TVP5150AM1 only)\n",
(tvp5150_read(sd, TVP5150_REV_SELECT) & 1) ? 3 : 4);
printk("tvp5150: Device ID = %02x%02x\n",
tvp5150_read(sd, TVP5150_MSB_DEV_ID),
tvp5150_read(sd, TVP5150_LSB_DEV_ID));
printk("tvp5150: ROM version = (hex) %02x.%02x\n",
tvp5150_read(sd, TVP5150_ROM_MAJOR_VER),
tvp5150_read(sd, TVP5150_ROM_MINOR_VER));
printk("tvp5150: Vertical line count = 0x%02x%02x\n",
tvp5150_read(sd, TVP5150_VERT_LN_COUNT_MSB),
tvp5150_read(sd, TVP5150_VERT_LN_COUNT_LSB));
printk("tvp5150: Interrupt status register B = 0x%02x\n",
tvp5150_read(sd, TVP5150_INT_STATUS_REG_B));
printk("tvp5150: Interrupt active register B = 0x%02x\n",
tvp5150_read(sd, TVP5150_INT_ACTIVE_REG_B));
printk("tvp5150: Status regs #1 to #5 = %02x %02x %02x %02x %02x\n",
tvp5150_read(sd, TVP5150_STATUS_REG_1),
tvp5150_read(sd, TVP5150_STATUS_REG_2),
tvp5150_read(sd, TVP5150_STATUS_REG_3),
tvp5150_read(sd, TVP5150_STATUS_REG_4),
tvp5150_read(sd, TVP5150_STATUS_REG_5));
dump_reg_range(sd, "Teletext filter 1", TVP5150_TELETEXT_FIL1_INI,
TVP5150_TELETEXT_FIL1_END, 8);
dump_reg_range(sd, "Teletext filter 2", TVP5150_TELETEXT_FIL2_INI,
TVP5150_TELETEXT_FIL2_END, 8);
printk("tvp5150: Teletext filter enable = 0x%02x\n",
tvp5150_read(sd, TVP5150_TELETEXT_FIL_ENA));
printk("tvp5150: Interrupt status register A = 0x%02x\n",
tvp5150_read(sd, TVP5150_INT_STATUS_REG_A));
printk("tvp5150: Interrupt enable register A = 0x%02x\n",
tvp5150_read(sd, TVP5150_INT_ENABLE_REG_A));
printk("tvp5150: Interrupt configuration = 0x%02x\n",
tvp5150_read(sd, TVP5150_INT_CONF));
printk("tvp5150: VDP status register = 0x%02x\n",
tvp5150_read(sd, TVP5150_VDP_STATUS_REG));
printk("tvp5150: FIFO word count = 0x%02x\n",
tvp5150_read(sd, TVP5150_FIFO_WORD_COUNT));
printk("tvp5150: FIFO interrupt threshold = 0x%02x\n",
tvp5150_read(sd, TVP5150_FIFO_INT_THRESHOLD));
printk("tvp5150: FIFO reset = 0x%02x\n",
tvp5150_read(sd, TVP5150_FIFO_RESET));
printk("tvp5150: Line number interrupt = 0x%02x\n",
tvp5150_read(sd, TVP5150_LINE_NUMBER_INT));
printk("tvp5150: Pixel alignment register = 0x%02x%02x\n",
tvp5150_read(sd, TVP5150_PIX_ALIGN_REG_HIGH),
tvp5150_read(sd, TVP5150_PIX_ALIGN_REG_LOW));
printk("tvp5150: FIFO output control = 0x%02x\n",
tvp5150_read(sd, TVP5150_FIFO_OUT_CTRL));
printk("tvp5150: Full field enable = 0x%02x\n",
tvp5150_read(sd, TVP5150_FULL_FIELD_ENA));
printk("tvp5150: Full field mode register = 0x%02x\n",
tvp5150_read(sd, TVP5150_FULL_FIELD_MODE_REG));
dump_reg_range(sd, "CC data", TVP5150_CC_DATA_INI,
TVP5150_CC_DATA_END, 8);
dump_reg_range(sd, "WSS data", TVP5150_WSS_DATA_INI,
TVP5150_WSS_DATA_END, 8);
dump_reg_range(sd, "VPS data", TVP5150_VPS_DATA_INI,
TVP5150_VPS_DATA_END, 8);
dump_reg_range(sd, "VITC data", TVP5150_VITC_DATA_INI,
TVP5150_VITC_DATA_END, 10);
dump_reg_range(sd, "Line mode", TVP5150_LINE_MODE_INI,
TVP5150_LINE_MODE_END, 8);
return 0;
}
/****************************************************************************
Basic functions
****************************************************************************/
static inline void tvp5150_selmux(struct v4l2_subdev *sd)
{
int opmode = 0;
struct tvp5150 *decoder = to_tvp5150(sd);
int input = 0;
unsigned char val;
if ((decoder->output & TVP5150_BLACK_SCREEN) || !decoder->enable)
input = 8;
switch (decoder->input) {
case TVP5150_COMPOSITE1:
input |= 2;
/* fall through */
case TVP5150_COMPOSITE0:
break;
case TVP5150_SVIDEO:
default:
input |= 1;
break;
}
v4l2_dbg(1, debug, sd, "Selecting video route: route input=%i, output=%i "
"=> tvp5150 input=%i, opmode=%i\n",
decoder->input, decoder->output,
input, opmode);
tvp5150_write(sd, TVP5150_OP_MODE_CTL, opmode);
tvp5150_write(sd, TVP5150_VD_IN_SRC_SEL_1, input);
/* Svideo should enable YCrCb output and disable GPCL output
* For Composite and TV, it should be the reverse
*/
val = tvp5150_read(sd, TVP5150_MISC_CTL);
if (decoder->input == TVP5150_SVIDEO)
val = (val & ~0x40) | 0x10;
else
val = (val & ~0x10) | 0x40;
tvp5150_write(sd, TVP5150_MISC_CTL, val);
};
struct i2c_reg_value {
unsigned char reg;
unsigned char value;
};
/* Default values as sugested at TVP5150AM1 datasheet */
static const struct i2c_reg_value tvp5150_init_default[] = {
{ /* 0x00 */
TVP5150_VD_IN_SRC_SEL_1,0x00
},
{ /* 0x01 */
TVP5150_ANAL_CHL_CTL,0x15
},
{ /* 0x02 */
TVP5150_OP_MODE_CTL,0x00
},
{ /* 0x03 */
TVP5150_MISC_CTL,0x01
},
{ /* 0x06 */
TVP5150_COLOR_KIL_THSH_CTL,0x10
},
{ /* 0x07 */
TVP5150_LUMA_PROC_CTL_1,0x60
},
{ /* 0x08 */
TVP5150_LUMA_PROC_CTL_2,0x00
},
{ /* 0x09 */
TVP5150_BRIGHT_CTL,0x80
},
{ /* 0x0a */
TVP5150_SATURATION_CTL,0x80
},
{ /* 0x0b */
TVP5150_HUE_CTL,0x00
},
{ /* 0x0c */
TVP5150_CONTRAST_CTL,0x80
},
{ /* 0x0d */
TVP5150_DATA_RATE_SEL,0x47
},
{ /* 0x0e */
TVP5150_LUMA_PROC_CTL_3,0x00
},
{ /* 0x0f */
TVP5150_CONF_SHARED_PIN,0x08
},
{ /* 0x11 */
TVP5150_ACT_VD_CROP_ST_MSB,0x00
},
{ /* 0x12 */
TVP5150_ACT_VD_CROP_ST_LSB,0x00
},
{ /* 0x13 */
TVP5150_ACT_VD_CROP_STP_MSB,0x00
},
{ /* 0x14 */
TVP5150_ACT_VD_CROP_STP_LSB,0x00
},
{ /* 0x15 */
TVP5150_GENLOCK,0x01
},
{ /* 0x16 */
TVP5150_HORIZ_SYNC_START,0x80
},
{ /* 0x18 */
TVP5150_VERT_BLANKING_START,0x00
},
{ /* 0x19 */
TVP5150_VERT_BLANKING_STOP,0x00
},
{ /* 0x1a */
TVP5150_CHROMA_PROC_CTL_1,0x0c
},
{ /* 0x1b */
TVP5150_CHROMA_PROC_CTL_2,0x14
},
{ /* 0x1c */
TVP5150_INT_RESET_REG_B,0x00
},
{ /* 0x1d */
TVP5150_INT_ENABLE_REG_B,0x00
},
{ /* 0x1e */
TVP5150_INTT_CONFIG_REG_B,0x00
},
{ /* 0x28 */
TVP5150_VIDEO_STD,0x00
},
{ /* 0x2e */
TVP5150_MACROVISION_ON_CTR,0x0f
},
{ /* 0x2f */
TVP5150_MACROVISION_OFF_CTR,0x01
},
{ /* 0xbb */
TVP5150_TELETEXT_FIL_ENA,0x00
},
{ /* 0xc0 */
TVP5150_INT_STATUS_REG_A,0x00
},
{ /* 0xc1 */
TVP5150_INT_ENABLE_REG_A,0x00
},
{ /* 0xc2 */
TVP5150_INT_CONF,0x04
},
{ /* 0xc8 */
TVP5150_FIFO_INT_THRESHOLD,0x80
},
{ /* 0xc9 */
TVP5150_FIFO_RESET,0x00
},
{ /* 0xca */
TVP5150_LINE_NUMBER_INT,0x00
},
{ /* 0xcb */
TVP5150_PIX_ALIGN_REG_LOW,0x4e
},
{ /* 0xcc */
TVP5150_PIX_ALIGN_REG_HIGH,0x00
},
{ /* 0xcd */
TVP5150_FIFO_OUT_CTRL,0x01
},
{ /* 0xcf */
TVP5150_FULL_FIELD_ENA,0x00
},
{ /* 0xd0 */
TVP5150_LINE_MODE_INI,0x00
},
{ /* 0xfc */
TVP5150_FULL_FIELD_MODE_REG,0x7f
},
{ /* end of data */
0xff,0xff
}
};
/* Default values as sugested at TVP5150AM1 datasheet */
static const struct i2c_reg_value tvp5150_init_enable[] = {
{
TVP5150_CONF_SHARED_PIN, 2
},{ /* Automatic offset and AGC enabled */
TVP5150_ANAL_CHL_CTL, 0x15
},{ /* Activate YCrCb output 0x9 or 0xd ? */
TVP5150_MISC_CTL, 0x6f
},{ /* Activates video std autodetection for all standards */
TVP5150_AUTOSW_MSK, 0x0
},{ /* Default format: 0x47. For 4:2:2: 0x40 */
TVP5150_DATA_RATE_SEL, 0x47
},{
TVP5150_CHROMA_PROC_CTL_1, 0x0c
},{
TVP5150_CHROMA_PROC_CTL_2, 0x54
},{ /* Non documented, but initialized on WinTV USB2 */
0x27, 0x20
},{
0xff,0xff
}
};
struct tvp5150_vbi_type {
unsigned int vbi_type;
unsigned int ini_line;
unsigned int end_line;
unsigned int by_field :1;
};
struct i2c_vbi_ram_value {
u16 reg;
struct tvp5150_vbi_type type;
unsigned char values[16];
};
/* This struct have the values for each supported VBI Standard
* by
tvp5150_vbi_types should follow the same order as vbi_ram_default
* value 0 means rom position 0x10, value 1 means rom position 0x30
* and so on. There are 16 possible locations from 0 to 15.
*/
static struct i2c_vbi_ram_value vbi_ram_default[] =
{
/* FIXME: Current api doesn't handle all VBI types, those not
yet supported are placed under #if 0 */
#if 0
{0x010, /* Teletext, SECAM, WST System A */
{V4L2_SLICED_TELETEXT_SECAM,6,23,1},
{ 0xaa, 0xaa, 0xff, 0xff, 0xe7, 0x2e, 0x20, 0x26,
0xe6, 0xb4, 0x0e, 0x00, 0x00, 0x00, 0x10, 0x00 }
},
#endif
{0x030, /* Teletext, PAL, WST System B */
{V4L2_SLICED_TELETEXT_B,6,22,1},
{ 0xaa, 0xaa, 0xff, 0xff, 0x27, 0x2e, 0x20, 0x2b,
0xa6, 0x72, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00 }
},
#if 0
{0x050, /* Teletext, PAL, WST System C */
{V4L2_SLICED_TELETEXT_PAL_C,6,22,1},
{ 0xaa, 0xaa, 0xff, 0xff, 0xe7, 0x2e, 0x20, 0x22,
0xa6, 0x98, 0x0d, 0x00, 0x00, 0x00, 0x10, 0x00 }
},
{0x070, /* Teletext, NTSC, WST System B */
{V4L2_SLICED_TELETEXT_NTSC_B,10,21,1},
{ 0xaa, 0xaa, 0xff, 0xff, 0x27, 0x2e, 0x20, 0x23,
0x69, 0x93, 0x0d, 0x00, 0x00, 0x00, 0x10, 0x00 }
},
{0x090, /* Tetetext, NTSC NABTS System C */
{V4L2_SLICED_TELETEXT_NTSC_C,10,21,1},
{ 0xaa, 0xaa, 0xff, 0xff, 0xe7, 0x2e, 0x20, 0x22,
0x69, 0x93, 0x0d, 0x00, 0x00, 0x00, 0x15, 0x00 }
},
{0x0b0, /* Teletext, NTSC-J, NABTS System D */
{V4L2_SLICED_TELETEXT_NTSC_D,10,21,1},
{ 0xaa, 0xaa, 0xff, 0xff, 0xa7, 0x2e, 0x20, 0x23,
0x69, 0x93, 0x0d, 0x00, 0x00, 0x00, 0x10, 0x00 }
},
{0x0d0, /* Closed Caption, PAL/SECAM */
{V4L2_SLICED_CAPTION_625,22,22,1},
{ 0xaa, 0x2a, 0xff, 0x3f, 0x04, 0x51, 0x6e, 0x02,
0xa6, 0x7b, 0x09, 0x00, 0x00, 0x00, 0x27, 0x00 }
},
#endif
{0x0f0, /* Closed Caption, NTSC */
{V4L2_SLICED_CAPTION_525,21,21,1},
{ 0xaa, 0x2a, 0xff, 0x3f, 0x04, 0x51, 0x6e, 0x02,
0x69, 0x8c, 0x09, 0x00, 0x00, 0x00, 0x27, 0x00 }
},
{0x110, /* Wide Screen Signal, PAL/SECAM */
{V4L2_SLICED_WSS_625,23,23,1},
{ 0x5b, 0x55, 0xc5, 0xff, 0x00, 0x71, 0x6e, 0x42,
0xa6, 0xcd, 0x0f, 0x00, 0x00, 0x00, 0x3a, 0x00 }
},
#if 0
{0x130, /* Wide Screen Signal, NTSC C */
{V4L2_SLICED_WSS_525,20,20,1},
{ 0x38, 0x00, 0x3f, 0x00, 0x00, 0x71, 0x6e, 0x43,
0x69, 0x7c, 0x08, 0x00, 0x00, 0x00, 0x39, 0x00 }
},
{0x150, /* Vertical Interval Timecode (VITC), PAL/SECAM */
{V4l2_SLICED_VITC_625,6,22,0},
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x8f, 0x6d, 0x49,
0xa6, 0x85, 0x08, 0x00, 0x00, 0x00, 0x4c, 0x00 }
},
{0x170, /* Vertical Interval Timecode (VITC), NTSC */
{V4l2_SLICED_VITC_525,10,20,0},
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x8f, 0x6d, 0x49,
0x69, 0x94, 0x08, 0x00, 0x00, 0x00, 0x4c, 0x00 }
},
#endif
{0x190, /* Video Program System (VPS), PAL */
{V4L2_SLICED_VPS,16,16,0},
{ 0xaa, 0xaa, 0xff, 0xff, 0xba, 0xce, 0x2b, 0x0d,
0xa6, 0xda, 0x0b, 0x00, 0x00, 0x00, 0x60, 0x00 }
},
/* 0x1d0 User programmable */
/* End of struct */
{ (u16)-1 }
};
static int tvp5150_write_inittab(struct v4l2_subdev *sd,
const struct i2c_reg_value *regs)
{
while (regs->reg != 0xff) {
tvp5150_write(sd, regs->reg, regs->value);
regs++;
}
return 0;
}
static int tvp5150_vdp_init(struct v4l2_subdev *sd,
const struct i2c_vbi_ram_value *regs)
{
unsigned int i;
/* Disable Full Field */
tvp5150_write(sd, TVP5150_FULL_FIELD_ENA, 0);
/* Before programming, Line mode should be at 0xff */
for (i = TVP5150_LINE_MODE_INI; i <= TVP5150_LINE_MODE_END; i++)
tvp5150_write(sd, i, 0xff);
/* Load Ram Table */
while (regs->reg != (u16)-1) {
tvp5150_write(sd, TVP5150_CONF_RAM_ADDR_HIGH, regs->reg >> 8);
tvp5150_write(sd, TVP5150_CONF_RAM_ADDR_LOW, regs->reg);
for (i = 0; i < 16; i++)
tvp5150_write(sd, TVP5150_VDP_CONF_RAM_DATA, regs->values[i]);
regs++;
}
return 0;
}
/* Fills VBI capabilities based on i2c_vbi_ram_value struct */
static int tvp5150_g_sliced_vbi_cap(struct v4l2_subdev *sd,
struct v4l2_sliced_vbi_cap *cap)
{
const struct i2c_vbi_ram_value *regs = vbi_ram_default;
int line;
v4l2_dbg(1, debug, sd, "g_sliced_vbi_cap\n");
memset(cap, 0, sizeof *cap);
while (regs->reg != (u16)-1 ) {
for (line=regs->type.ini_line;line<=regs->type.end_line;line++) {
cap->service_lines[0][line] |= regs->type.vbi_type;
}
cap->service_set |= regs->type.vbi_type;
regs++;
}
return 0;
}
/* Set vbi processing
* type - one of tvp5150_vbi_types
* line - line to gather data
* fields: bit 0 field1, bit 1, field2
* flags (default=0xf0) is a bitmask, were set means:
* bit 7: enable filtering null bytes on CC
* bit 6: send data also to FIFO
* bit 5: don't allow data with errors on FIFO
* bit 4: enable ECC when possible
* pix_align = pix alignment:
* LSB = field1
* MSB = field2
*/
static int tvp5150_set_vbi(struct v4l2_subdev *sd,
const struct i2c_vbi_ram_value *regs,
unsigned int type,u8 flags, int line,
const int fields)
{
struct tvp5150 *decoder = to_tvp5150(sd);
v4l2_std_id std = decoder->norm;
u8 reg;
int pos=0;
if (std == V4L2_STD_ALL) {
v4l2_err(sd, "VBI can't be configured without knowing number of lines\n");
return 0;
} else if (std & V4L2_STD_625_50) {
/* Don't follow NTSC Line number convension */
line += 3;
}
if (line<6||line>27)
return 0;
while (regs->reg != (u16)-1 ) {
if ((type & regs->type.vbi_type) &&
(line>=regs->type.ini_line) &&
(line<=regs->type.end_line)) {
type=regs->type.vbi_type;
break;
}
regs++;
pos++;
}
if (regs->reg == (u16)-1)
return 0;
type=pos | (flags & 0xf0);
reg=((line-6)<<1)+TVP5150_LINE_MODE_INI;
if (fields&1) {
tvp5150_write(sd, reg, type);
}
if (fields&2) {
tvp5150_write(sd, reg+1, type);
}
return type;
}
static int tvp5150_get_vbi(struct v4l2_subdev *sd,
const struct i2c_vbi_ram_value *regs, int line)
{
struct tvp5150 *decoder = to_tvp5150(sd);
v4l2_std_id std = decoder->norm;
u8 reg;
int pos, type = 0;
if (std == V4L2_STD_ALL) {
v4l2_err(sd, "VBI can't be configured without knowing number of lines\n");
return 0;
} else if (std & V4L2_STD_625_50) {
/* Don't follow NTSC Line number convension */
line += 3;
}
if (line < 6 || line > 27)
return 0;
reg = ((line - 6) << 1) + TVP5150_LINE_MODE_INI;
pos = tvp5150_read(sd, reg) & 0x0f;
if (pos < 0x0f)
type = regs[pos].type.vbi_type;
pos = tvp5150_read(sd, reg + 1) & 0x0f;
if (pos < 0x0f)
type |= regs[pos].type.vbi_type;
return type;
}
static int tvp5150_set_std(struct v4l2_subdev *sd, v4l2_std_id std)
{
struct tvp5150 *decoder = to_tvp5150(sd);
int fmt = 0;
decoder->norm = std;
/* First tests should be against specific std */
if (std == V4L2_STD_ALL) {
fmt = VIDEO_STD_AUTO_SWITCH_BIT; /* Autodetect mode */
} else if (std & V4L2_STD_NTSC_443) {
fmt = VIDEO_STD_NTSC_4_43_BIT;
} else if (std & V4L2_STD_PAL_M) {
fmt = VIDEO_STD_PAL_M_BIT;
} else if (std & (V4L2_STD_PAL_N | V4L2_STD_PAL_Nc)) {
fmt = VIDEO_STD_PAL_COMBINATION_N_BIT;
} else {
/* Then, test against generic ones */
if (std & V4L2_STD_NTSC)
fmt = VIDEO_STD_NTSC_MJ_BIT;
else if (std & V4L2_STD_PAL)
fmt = VIDEO_STD_PAL_BDGHIN_BIT;
else if (std & V4L2_STD_SECAM)
fmt = VIDEO_STD_SECAM_BIT;
}
v4l2_dbg(1, debug, sd, "Set video std register to %d.\n", fmt);
tvp5150_write(sd, TVP5150_VIDEO_STD, fmt);
return 0;
}
static int tvp5150_s_std(struct v4l2_subdev *sd, v4l2_std_id std)
{
struct tvp5150 *decoder = to_tvp5150(sd);
if (decoder->norm == std)
return 0;
/* Change cropping height limits */
if (std & V4L2_STD_525_60)
decoder->rect.height = TVP5150_V_MAX_525_60;
else
decoder->rect.height = TVP5150_V_MAX_OTHERS;
return tvp5150_set_std(sd, std);
}
static int tvp5150_reset(struct v4l2_subdev *sd, u32 val)
{
struct tvp5150 *decoder = to_tvp5150(sd);
/* Initializes TVP5150 to its default values */
tvp5150_write_inittab(sd, tvp5150_init_default);
/* Initializes VDP registers */
tvp5150_vdp_init(sd, vbi_ram_default);
/* Selects decoder input */
tvp5150_selmux(sd);
/* Initializes TVP5150 to stream enabled values */
tvp5150_write_inittab(sd, tvp5150_init_enable);
/* Initialize image preferences */
v4l2_ctrl_handler_setup(&decoder->hdl);
tvp5150_set_std(sd, decoder->norm);
return 0;
};
static int tvp5150_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct v4l2_subdev *sd = to_sd(ctrl);
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
tvp5150_write(sd, TVP5150_BRIGHT_CTL, ctrl->val);
return 0;
case V4L2_CID_CONTRAST:
tvp5150_write(sd, TVP5150_CONTRAST_CTL, ctrl->val);
return 0;
case V4L2_CID_SATURATION:
tvp5150_write(sd, TVP5150_SATURATION_CTL, ctrl->val);
return 0;
case V4L2_CID_HUE:
tvp5150_write(sd, TVP5150_HUE_CTL, ctrl->val);
return 0;
}
return -EINVAL;
}
static v4l2_std_id tvp5150_read_std(struct v4l2_subdev *sd)
{
int val = tvp5150_read(sd, TVP5150_STATUS_REG_5);
switch (val & 0x0F) {
case 0x01:
return V4L2_STD_NTSC;
case 0x03:
return V4L2_STD_PAL;
case 0x05:
return V4L2_STD_PAL_M;
case 0x07:
return V4L2_STD_PAL_N | V4L2_STD_PAL_Nc;
case 0x09:
return V4L2_STD_NTSC_443;
case 0xb:
return V4L2_STD_SECAM;
default:
return V4L2_STD_UNKNOWN;
}
}
static int tvp5150_enum_mbus_fmt(struct v4l2_subdev *sd, unsigned index,
enum v4l2_mbus_pixelcode *code)
{
if (index)
return -EINVAL;
*code = V4L2_MBUS_FMT_YUYV8_2X8;
return 0;
}
static int tvp5150_mbus_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *f)
{
struct tvp5150 *decoder = to_tvp5150(sd);
v4l2_std_id std;
if (f == NULL)
return -EINVAL;
tvp5150_reset(sd, 0);
/* Calculate height and width based on current standard */
if (decoder->norm == V4L2_STD_ALL)
std = tvp5150_read_std(sd);
else
std = decoder->norm;
f->width = decoder->rect.width;
f->height = decoder->rect.height;
f->code = V4L2_MBUS_FMT_YUYV8_2X8;
f->field = V4L2_FIELD_SEQ_TB;
f->colorspace = V4L2_COLORSPACE_SMPTE170M;
v4l2_dbg(1, debug, sd, "width = %d, height = %d\n", f->width,
f->height);
return 0;
}
static int tvp5150_s_crop(struct v4l2_subdev *sd, struct v4l2_crop *a)
{
struct v4l2_rect rect = a->c;
struct tvp5150 *decoder = to_tvp5150(sd);
v4l2_std_id std;
int hmax;
v4l2_dbg(1, debug, sd, "%s left=%d, top=%d, width=%d, height=%d\n",
__func__, rect.left, rect.top, rect.width, rect.height);
if (a->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
/* tvp5150 has some special limits */
rect.left = clamp(rect.left, 0, TVP5150_MAX_CROP_LEFT);
rect.width = clamp(rect.width,
TVP5150_H_MAX - TVP5150_MAX_CROP_LEFT - rect.left,
TVP5150_H_MAX - rect.left);
rect.top = clamp(rect.top, 0, TVP5150_MAX_CROP_TOP);
/* Calculate height based on current standard */
if (decoder->norm == V4L2_STD_ALL)
std = tvp5150_read_std(sd);
else
std = decoder->norm;
if (std & V4L2_STD_525_60)
hmax = TVP5150_V_MAX_525_60;
else
hmax = TVP5150_V_MAX_OTHERS;
rect.height = clamp(rect.height,
hmax - TVP5150_MAX_CROP_TOP - rect.top,
hmax - rect.top);
tvp5150_write(sd, TVP5150_VERT_BLANKING_START, rect.top);
tvp5150_write(sd, TVP5150_VERT_BLANKING_STOP,
rect.top + rect.height - hmax);
tvp5150_write(sd, TVP5150_ACT_VD_CROP_ST_MSB,
rect.left >> TVP5150_CROP_SHIFT);
tvp5150_write(sd, TVP5150_ACT_VD_CROP_ST_LSB,
rect.left | (1 << TVP5150_CROP_SHIFT));
tvp5150_write(sd, TVP5150_ACT_VD_CROP_STP_MSB,
(rect.left + rect.width - TVP5150_MAX_CROP_LEFT) >>
TVP5150_CROP_SHIFT);
tvp5150_write(sd, TVP5150_ACT_VD_CROP_STP_LSB,
rect.left + rect.width - TVP5150_MAX_CROP_LEFT);
decoder->rect = rect;
return 0;
}
static int tvp5150_g_crop(struct v4l2_subdev *sd, struct v4l2_crop *a)
{
struct tvp5150 *decoder = container_of(sd, struct tvp5150, sd);
a->c = decoder->rect;
a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
return 0;
}
static int tvp5150_cropcap(struct v4l2_subdev *sd, struct v4l2_cropcap *a)
{
struct tvp5150 *decoder = container_of(sd, struct tvp5150, sd);
v4l2_std_id std;
if (a->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
a->bounds.left = 0;
a->bounds.top = 0;
a->bounds.width = TVP5150_H_MAX;
/* Calculate height based on current standard */
if (decoder->norm == V4L2_STD_ALL)
std = tvp5150_read_std(sd);
else
std = decoder->norm;
if (std & V4L2_STD_525_60)
a->bounds.height = TVP5150_V_MAX_525_60;
else
a->bounds.height = TVP5150_V_MAX_OTHERS;
a->defrect = a->bounds;
a->pixelaspect.numerator = 1;
a->pixelaspect.denominator = 1;
return 0;
}
/****************************************************************************
I2C Command
****************************************************************************/
static int tvp5150_s_routing(struct v4l2_subdev *sd,
u32 input, u32 output, u32 config)
{
struct tvp5150 *decoder = to_tvp5150(sd);
decoder->input = input;
decoder->output = output;
tvp5150_selmux(sd);
return 0;
}
static int tvp5150_s_raw_fmt(struct v4l2_subdev *sd, struct v4l2_vbi_format *fmt)
{
/* this is for capturing 36 raw vbi lines
if there's a way to cut off the beginning 2 vbi lines
with the tvp5150 then the vbi line count could be lowered
to 17 lines/field again, although I couldn't find a register
which could do that cropping */
if (fmt->sample_format == V4L2_PIX_FMT_GREY)
tvp5150_write(sd, TVP5150_LUMA_PROC_CTL_1, 0x70);
if (fmt->count[0] == 18 && fmt->count[1] == 18) {
tvp5150_write(sd, TVP5150_VERT_BLANKING_START, 0x00);
tvp5150_write(sd, TVP5150_VERT_BLANKING_STOP, 0x01);
}
return 0;
}
static int tvp5150_s_sliced_fmt(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_format *svbi)
{
int i;
if (svbi->service_set != 0) {
for (i = 0; i <= 23; i++) {
svbi->service_lines[1][i] = 0;
svbi->service_lines[0][i] =
tvp5150_set_vbi(sd, vbi_ram_default,
svbi->service_lines[0][i], 0xf0, i, 3);
}
/* Enables FIFO */
tvp5150_write(sd, TVP5150_FIFO_OUT_CTRL, 1);
} else {
/* Disables FIFO*/
tvp5150_write(sd, TVP5150_FIFO_OUT_CTRL, 0);
/* Disable Full Field */
tvp5150_write(sd, TVP5150_FULL_FIELD_ENA, 0);
/* Disable Line modes */
for (i = TVP5150_LINE_MODE_INI; i <= TVP5150_LINE_MODE_END; i++)
tvp5150_write(sd, i, 0xff);
}
return 0;
}
static int tvp5150_g_sliced_fmt(struct v4l2_subdev *sd, struct v4l2_sliced_vbi_format *svbi)
{
int i, mask = 0;
memset(svbi, 0, sizeof(*svbi));
for (i = 0; i <= 23; i++) {
svbi->service_lines[0][i] =
tvp5150_get_vbi(sd, vbi_ram_default, i);
mask |= svbi->service_lines[0][i];
}
svbi->service_set = mask;
return 0;
}
static int tvp5150_g_chip_ident(struct v4l2_subdev *sd,
struct v4l2_dbg_chip_ident *chip)
{
int rev;
struct i2c_client *client = v4l2_get_subdevdata(sd);
rev = tvp5150_read(sd, TVP5150_ROM_MAJOR_VER) << 8 |
tvp5150_read(sd, TVP5150_ROM_MINOR_VER);
return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_TVP5150,
rev);
}
#ifdef CONFIG_VIDEO_ADV_DEBUG
static int tvp5150_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 = tvp5150_read(sd, reg->reg & 0xff);
reg->size = 1;
return 0;
}
static int tvp5150_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;
tvp5150_write(sd, reg->reg & 0xff, reg->val & 0xff);
return 0;
}
#endif
static int tvp5150_g_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *vt)
{
int status = tvp5150_read(sd, 0x88);
vt->signal = ((status & 0x04) && (status & 0x02)) ? 0xffff : 0x0;
return 0;
}
/* ----------------------------------------------------------------------- */
static const struct v4l2_ctrl_ops tvp5150_ctrl_ops = {
.s_ctrl = tvp5150_s_ctrl,
};
static const struct v4l2_subdev_core_ops tvp5150_core_ops = {
.log_status = tvp5150_log_status,
.g_ext_ctrls = v4l2_subdev_g_ext_ctrls,
.try_ext_ctrls = v4l2_subdev_try_ext_ctrls,
.s_ext_ctrls = v4l2_subdev_s_ext_ctrls,
.g_ctrl = v4l2_subdev_g_ctrl,
.s_ctrl = v4l2_subdev_s_ctrl,
.queryctrl = v4l2_subdev_queryctrl,
.querymenu = v4l2_subdev_querymenu,
.s_std = tvp5150_s_std,
.reset = tvp5150_reset,
.g_chip_ident = tvp5150_g_chip_ident,
#ifdef CONFIG_VIDEO_ADV_DEBUG
.g_register = tvp5150_g_register,
.s_register = tvp5150_s_register,
#endif
};
static const struct v4l2_subdev_tuner_ops tvp5150_tuner_ops = {
.g_tuner = tvp5150_g_tuner,
};
static const struct v4l2_subdev_video_ops tvp5150_video_ops = {
.s_routing = tvp5150_s_routing,
.enum_mbus_fmt = tvp5150_enum_mbus_fmt,
.s_mbus_fmt = tvp5150_mbus_fmt,
.try_mbus_fmt = tvp5150_mbus_fmt,
.g_mbus_fmt = tvp5150_mbus_fmt,
.s_crop = tvp5150_s_crop,
.g_crop = tvp5150_g_crop,
.cropcap = tvp5150_cropcap,
};
static const struct v4l2_subdev_vbi_ops tvp5150_vbi_ops = {
.g_sliced_vbi_cap = tvp5150_g_sliced_vbi_cap,
.g_sliced_fmt = tvp5150_g_sliced_fmt,
.s_sliced_fmt = tvp5150_s_sliced_fmt,
.s_raw_fmt = tvp5150_s_raw_fmt,
};
static const struct v4l2_subdev_ops tvp5150_ops = {
.core = &tvp5150_core_ops,
.tuner = &tvp5150_tuner_ops,
.video = &tvp5150_video_ops,
.vbi = &tvp5150_vbi_ops,
};
/****************************************************************************
I2C Client & Driver
****************************************************************************/
static int tvp5150_probe(struct i2c_client *c,
const struct i2c_device_id *id)
{
struct tvp5150 *core;
struct v4l2_subdev *sd;
u8 msb_id, lsb_id, msb_rom, lsb_rom;
/* Check if the adapter supports the needed features */
if (!i2c_check_functionality(c->adapter,
I2C_FUNC_SMBUS_READ_BYTE | I2C_FUNC_SMBUS_WRITE_BYTE_DATA))
return -EIO;
core = kzalloc(sizeof(struct tvp5150), GFP_KERNEL);
if (!core) {
return -ENOMEM;
}
sd = &core->sd;
v4l2_i2c_subdev_init(sd, c, &tvp5150_ops);
v4l_info(c, "chip found @ 0x%02x (%s)\n",
c->addr << 1, c->adapter->name);
msb_id = tvp5150_read(sd, TVP5150_MSB_DEV_ID);
lsb_id = tvp5150_read(sd, TVP5150_LSB_DEV_ID);
msb_rom = tvp5150_read(sd, TVP5150_ROM_MAJOR_VER);
lsb_rom = tvp5150_read(sd, TVP5150_ROM_MINOR_VER);
if (msb_rom == 4 && lsb_rom == 0) { /* Is TVP5150AM1 */
v4l2_info(sd, "tvp%02x%02xam1 detected.\n", msb_id, lsb_id);
/* ITU-T BT.656.4 timing */
tvp5150_write(sd, TVP5150_REV_SELECT, 0);
} else {
if (msb_rom == 3 || lsb_rom == 0x21) { /* Is TVP5150A */
v4l2_info(sd, "tvp%02x%02xa detected.\n", msb_id, lsb_id);
} else {
v4l2_info(sd, "*** unknown tvp%02x%02x chip detected.\n",
msb_id, lsb_id);
v4l2_info(sd, "*** Rom ver is %d.%d\n", msb_rom, lsb_rom);
}
}
core->norm = V4L2_STD_ALL; /* Default is autodetect */
core->input = TVP5150_COMPOSITE1;
core->enable = 1;
v4l2_ctrl_handler_init(&core->hdl, 4);
v4l2_ctrl_new_std(&core->hdl, &tvp5150_ctrl_ops,
V4L2_CID_BRIGHTNESS, 0, 255, 1, 128);
v4l2_ctrl_new_std(&core->hdl, &tvp5150_ctrl_ops,
V4L2_CID_CONTRAST, 0, 255, 1, 128);
v4l2_ctrl_new_std(&core->hdl, &tvp5150_ctrl_ops,
V4L2_CID_SATURATION, 0, 255, 1, 128);
v4l2_ctrl_new_std(&core->hdl, &tvp5150_ctrl_ops,
V4L2_CID_HUE, -128, 127, 1, 0);
sd->ctrl_handler = &core->hdl;
if (core->hdl.error) {
int err = core->hdl.error;
v4l2_ctrl_handler_free(&core->hdl);
kfree(core);
return err;
}
v4l2_ctrl_handler_setup(&core->hdl);
/* Default is no cropping */
core->rect.top = 0;
if (tvp5150_read_std(sd) & V4L2_STD_525_60)
core->rect.height = TVP5150_V_MAX_525_60;
else
core->rect.height = TVP5150_V_MAX_OTHERS;
core->rect.left = 0;
core->rect.width = TVP5150_H_MAX;
if (debug > 1)
tvp5150_log_status(sd);
return 0;
}
static int tvp5150_remove(struct i2c_client *c)
{
struct v4l2_subdev *sd = i2c_get_clientdata(c);
struct tvp5150 *decoder = to_tvp5150(sd);
v4l2_dbg(1, debug, sd,
"tvp5150.c: removing tvp5150 adapter on address 0x%x\n",
c->addr << 1);
v4l2_device_unregister_subdev(sd);
v4l2_ctrl_handler_free(&decoder->hdl);
kfree(to_tvp5150(sd));
return 0;
}
/* ----------------------------------------------------------------------- */
static const struct i2c_device_id tvp5150_id[] = {
{ "tvp5150", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, tvp5150_id);
static struct i2c_driver tvp5150_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "tvp5150",
},
.probe = tvp5150_probe,
.remove = tvp5150_remove,
.id_table = tvp5150_id,
};
module_i2c_driver(tvp5150_driver);
| gpl-2.0 |
SiniTurk/android_kernel_samsung_kylevexx | net/tipc/name_distr.c | 4810 | 9220 | /*
* net/tipc/name_distr.c: TIPC name distribution code
*
* Copyright (c) 2000-2006, Ericsson AB
* Copyright (c) 2005, 2010-2011, Wind River Systems
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the names of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "core.h"
#include "link.h"
#include "name_distr.h"
#define ITEM_SIZE sizeof(struct distr_item)
/**
* struct distr_item - publication info distributed to other nodes
* @type: name sequence type
* @lower: name sequence lower bound
* @upper: name sequence upper bound
* @ref: publishing port reference
* @key: publication key
*
* ===> All fields are stored in network byte order. <===
*
* First 3 fields identify (name or) name sequence being published.
* Reference field uniquely identifies port that published name sequence.
* Key field uniquely identifies publication, in the event a port has
* multiple publications of the same name sequence.
*
* Note: There is no field that identifies the publishing node because it is
* the same for all items contained within a publication message.
*/
struct distr_item {
__be32 type;
__be32 lower;
__be32 upper;
__be32 ref;
__be32 key;
};
/**
* List of externally visible publications by this node --
* that is, all publications having scope > TIPC_NODE_SCOPE.
*/
static LIST_HEAD(publ_root);
static u32 publ_cnt;
/**
* publ_to_item - add publication info to a publication message
*/
static void publ_to_item(struct distr_item *i, struct publication *p)
{
i->type = htonl(p->type);
i->lower = htonl(p->lower);
i->upper = htonl(p->upper);
i->ref = htonl(p->ref);
i->key = htonl(p->key);
}
/**
* named_prepare_buf - allocate & initialize a publication message
*/
static struct sk_buff *named_prepare_buf(u32 type, u32 size, u32 dest)
{
struct sk_buff *buf = tipc_buf_acquire(INT_H_SIZE + size);
struct tipc_msg *msg;
if (buf != NULL) {
msg = buf_msg(buf);
tipc_msg_init(msg, NAME_DISTRIBUTOR, type, INT_H_SIZE, dest);
msg_set_size(msg, INT_H_SIZE + size);
}
return buf;
}
static void named_cluster_distribute(struct sk_buff *buf)
{
struct sk_buff *buf_copy;
struct tipc_node *n_ptr;
list_for_each_entry(n_ptr, &tipc_node_list, list) {
if (tipc_node_active_links(n_ptr)) {
buf_copy = skb_copy(buf, GFP_ATOMIC);
if (!buf_copy)
break;
msg_set_destnode(buf_msg(buf_copy), n_ptr->addr);
tipc_link_send(buf_copy, n_ptr->addr, n_ptr->addr);
}
}
kfree_skb(buf);
}
/**
* tipc_named_publish - tell other nodes about a new publication by this node
*/
void tipc_named_publish(struct publication *publ)
{
struct sk_buff *buf;
struct distr_item *item;
list_add_tail(&publ->local_list, &publ_root);
publ_cnt++;
buf = named_prepare_buf(PUBLICATION, ITEM_SIZE, 0);
if (!buf) {
warn("Publication distribution failure\n");
return;
}
item = (struct distr_item *)msg_data(buf_msg(buf));
publ_to_item(item, publ);
named_cluster_distribute(buf);
}
/**
* tipc_named_withdraw - tell other nodes about a withdrawn publication by this node
*/
void tipc_named_withdraw(struct publication *publ)
{
struct sk_buff *buf;
struct distr_item *item;
list_del(&publ->local_list);
publ_cnt--;
buf = named_prepare_buf(WITHDRAWAL, ITEM_SIZE, 0);
if (!buf) {
warn("Withdrawal distribution failure\n");
return;
}
item = (struct distr_item *)msg_data(buf_msg(buf));
publ_to_item(item, publ);
named_cluster_distribute(buf);
}
/**
* tipc_named_node_up - tell specified node about all publications by this node
*/
void tipc_named_node_up(unsigned long nodearg)
{
struct tipc_node *n_ptr;
struct tipc_link *l_ptr;
struct publication *publ;
struct distr_item *item = NULL;
struct sk_buff *buf = NULL;
struct list_head message_list;
u32 node = (u32)nodearg;
u32 left = 0;
u32 rest;
u32 max_item_buf = 0;
/* compute maximum amount of publication data to send per message */
read_lock_bh(&tipc_net_lock);
n_ptr = tipc_node_find(node);
if (n_ptr) {
tipc_node_lock(n_ptr);
l_ptr = n_ptr->active_links[0];
if (l_ptr)
max_item_buf = ((l_ptr->max_pkt - INT_H_SIZE) /
ITEM_SIZE) * ITEM_SIZE;
tipc_node_unlock(n_ptr);
}
read_unlock_bh(&tipc_net_lock);
if (!max_item_buf)
return;
/* create list of publication messages, then send them as a unit */
INIT_LIST_HEAD(&message_list);
read_lock_bh(&tipc_nametbl_lock);
rest = publ_cnt * ITEM_SIZE;
list_for_each_entry(publ, &publ_root, local_list) {
if (!buf) {
left = (rest <= max_item_buf) ? rest : max_item_buf;
rest -= left;
buf = named_prepare_buf(PUBLICATION, left, node);
if (!buf) {
warn("Bulk publication distribution failure\n");
goto exit;
}
item = (struct distr_item *)msg_data(buf_msg(buf));
}
publ_to_item(item, publ);
item++;
left -= ITEM_SIZE;
if (!left) {
list_add_tail((struct list_head *)buf, &message_list);
buf = NULL;
}
}
exit:
read_unlock_bh(&tipc_nametbl_lock);
tipc_link_send_names(&message_list, (u32)node);
}
/**
* named_purge_publ - remove publication associated with a failed node
*
* Invoked for each publication issued by a newly failed node.
* Removes publication structure from name table & deletes it.
*/
static void named_purge_publ(struct publication *publ)
{
struct publication *p;
write_lock_bh(&tipc_nametbl_lock);
p = tipc_nametbl_remove_publ(publ->type, publ->lower,
publ->node, publ->ref, publ->key);
if (p)
tipc_nodesub_unsubscribe(&p->subscr);
write_unlock_bh(&tipc_nametbl_lock);
if (p != publ) {
err("Unable to remove publication from failed node\n"
"(type=%u, lower=%u, node=0x%x, ref=%u, key=%u)\n",
publ->type, publ->lower, publ->node, publ->ref, publ->key);
}
kfree(p);
}
/**
* tipc_named_recv - process name table update message sent by another node
*/
void tipc_named_recv(struct sk_buff *buf)
{
struct publication *publ;
struct tipc_msg *msg = buf_msg(buf);
struct distr_item *item = (struct distr_item *)msg_data(msg);
u32 count = msg_data_sz(msg) / ITEM_SIZE;
write_lock_bh(&tipc_nametbl_lock);
while (count--) {
if (msg_type(msg) == PUBLICATION) {
publ = tipc_nametbl_insert_publ(ntohl(item->type),
ntohl(item->lower),
ntohl(item->upper),
TIPC_CLUSTER_SCOPE,
msg_orignode(msg),
ntohl(item->ref),
ntohl(item->key));
if (publ) {
tipc_nodesub_subscribe(&publ->subscr,
msg_orignode(msg),
publ,
(net_ev_handler)
named_purge_publ);
}
} else if (msg_type(msg) == WITHDRAWAL) {
publ = tipc_nametbl_remove_publ(ntohl(item->type),
ntohl(item->lower),
msg_orignode(msg),
ntohl(item->ref),
ntohl(item->key));
if (publ) {
tipc_nodesub_unsubscribe(&publ->subscr);
kfree(publ);
} else {
err("Unable to remove publication by node 0x%x\n"
"(type=%u, lower=%u, ref=%u, key=%u)\n",
msg_orignode(msg),
ntohl(item->type), ntohl(item->lower),
ntohl(item->ref), ntohl(item->key));
}
} else {
warn("Unrecognized name table message received\n");
}
item++;
}
write_unlock_bh(&tipc_nametbl_lock);
kfree_skb(buf);
}
/**
* tipc_named_reinit - re-initialize local publication list
*
* This routine is called whenever TIPC networking is enabled.
* All existing publications by this node that have "cluster" or "zone" scope
* are updated to reflect the node's new network address.
*/
void tipc_named_reinit(void)
{
struct publication *publ;
write_lock_bh(&tipc_nametbl_lock);
list_for_each_entry(publ, &publ_root, local_list)
publ->node = tipc_own_addr;
write_unlock_bh(&tipc_nametbl_lock);
}
| gpl-2.0 |
ochiman/e405-kernel | sound/synth/util_mem.c | 4810 | 4637 | /*
* Copyright (C) 2000 Takashi Iwai <tiwai@suse.de>
*
* Generic memory management routines for soundcard memory allocation
*
* 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/mutex.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/util_mem.h>
MODULE_AUTHOR("Takashi Iwai");
MODULE_DESCRIPTION("Generic memory management routines for soundcard memory allocation");
MODULE_LICENSE("GPL");
#define get_memblk(p) list_entry(p, struct snd_util_memblk, list)
/*
* create a new memory manager
*/
struct snd_util_memhdr *
snd_util_memhdr_new(int memsize)
{
struct snd_util_memhdr *hdr;
hdr = kzalloc(sizeof(*hdr), GFP_KERNEL);
if (hdr == NULL)
return NULL;
hdr->size = memsize;
mutex_init(&hdr->block_mutex);
INIT_LIST_HEAD(&hdr->block);
return hdr;
}
/*
* free a memory manager
*/
void snd_util_memhdr_free(struct snd_util_memhdr *hdr)
{
struct list_head *p;
if (!hdr)
return;
/* release all blocks */
while ((p = hdr->block.next) != &hdr->block) {
list_del(p);
kfree(get_memblk(p));
}
kfree(hdr);
}
/*
* allocate a memory block (without mutex)
*/
struct snd_util_memblk *
__snd_util_mem_alloc(struct snd_util_memhdr *hdr, int size)
{
struct snd_util_memblk *blk;
unsigned int units, prev_offset;
struct list_head *p;
if (snd_BUG_ON(!hdr || size <= 0))
return NULL;
/* word alignment */
units = size;
if (units & 1)
units++;
if (units > hdr->size)
return NULL;
/* look for empty block */
prev_offset = 0;
list_for_each(p, &hdr->block) {
blk = get_memblk(p);
if (blk->offset - prev_offset >= units)
goto __found;
prev_offset = blk->offset + blk->size;
}
if (hdr->size - prev_offset < units)
return NULL;
__found:
return __snd_util_memblk_new(hdr, units, p->prev);
}
/*
* create a new memory block with the given size
* the block is linked next to prev
*/
struct snd_util_memblk *
__snd_util_memblk_new(struct snd_util_memhdr *hdr, unsigned int units,
struct list_head *prev)
{
struct snd_util_memblk *blk;
blk = kmalloc(sizeof(struct snd_util_memblk) + hdr->block_extra_size,
GFP_KERNEL);
if (blk == NULL)
return NULL;
if (prev == &hdr->block)
blk->offset = 0;
else {
struct snd_util_memblk *p = get_memblk(prev);
blk->offset = p->offset + p->size;
}
blk->size = units;
list_add(&blk->list, prev);
hdr->nblocks++;
hdr->used += units;
return blk;
}
/*
* allocate a memory block (with mutex)
*/
struct snd_util_memblk *
snd_util_mem_alloc(struct snd_util_memhdr *hdr, int size)
{
struct snd_util_memblk *blk;
mutex_lock(&hdr->block_mutex);
blk = __snd_util_mem_alloc(hdr, size);
mutex_unlock(&hdr->block_mutex);
return blk;
}
/*
* remove the block from linked-list and free resource
* (without mutex)
*/
void
__snd_util_mem_free(struct snd_util_memhdr *hdr, struct snd_util_memblk *blk)
{
list_del(&blk->list);
hdr->nblocks--;
hdr->used -= blk->size;
kfree(blk);
}
/*
* free a memory block (with mutex)
*/
int snd_util_mem_free(struct snd_util_memhdr *hdr, struct snd_util_memblk *blk)
{
if (snd_BUG_ON(!hdr || !blk))
return -EINVAL;
mutex_lock(&hdr->block_mutex);
__snd_util_mem_free(hdr, blk);
mutex_unlock(&hdr->block_mutex);
return 0;
}
/*
* return available memory size
*/
int snd_util_mem_avail(struct snd_util_memhdr *hdr)
{
unsigned int size;
mutex_lock(&hdr->block_mutex);
size = hdr->size - hdr->used;
mutex_unlock(&hdr->block_mutex);
return size;
}
EXPORT_SYMBOL(snd_util_memhdr_new);
EXPORT_SYMBOL(snd_util_memhdr_free);
EXPORT_SYMBOL(snd_util_mem_alloc);
EXPORT_SYMBOL(snd_util_mem_free);
EXPORT_SYMBOL(snd_util_mem_avail);
EXPORT_SYMBOL(__snd_util_mem_alloc);
EXPORT_SYMBOL(__snd_util_mem_free);
EXPORT_SYMBOL(__snd_util_memblk_new);
/*
* INIT part
*/
static int __init alsa_util_mem_init(void)
{
return 0;
}
static void __exit alsa_util_mem_exit(void)
{
}
module_init(alsa_util_mem_init)
module_exit(alsa_util_mem_exit)
| gpl-2.0 |
ZdrowyGosciu/kernel_lge_g2_msm8974 | drivers/clocksource/sh_tmu.c | 4810 | 10943 | /*
* SuperH Timer Support - TMU
*
* Copyright (C) 2009 Magnus Damm
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <linux/irq.h>
#include <linux/err.h>
#include <linux/clocksource.h>
#include <linux/clockchips.h>
#include <linux/sh_timer.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/pm_domain.h>
struct sh_tmu_priv {
void __iomem *mapbase;
struct clk *clk;
struct irqaction irqaction;
struct platform_device *pdev;
unsigned long rate;
unsigned long periodic;
struct clock_event_device ced;
struct clocksource cs;
};
static DEFINE_SPINLOCK(sh_tmu_lock);
#define TSTR -1 /* shared register */
#define TCOR 0 /* channel register */
#define TCNT 1 /* channel register */
#define TCR 2 /* channel register */
static inline unsigned long sh_tmu_read(struct sh_tmu_priv *p, int reg_nr)
{
struct sh_timer_config *cfg = p->pdev->dev.platform_data;
void __iomem *base = p->mapbase;
unsigned long offs;
if (reg_nr == TSTR)
return ioread8(base - cfg->channel_offset);
offs = reg_nr << 2;
if (reg_nr == TCR)
return ioread16(base + offs);
else
return ioread32(base + offs);
}
static inline void sh_tmu_write(struct sh_tmu_priv *p, int reg_nr,
unsigned long value)
{
struct sh_timer_config *cfg = p->pdev->dev.platform_data;
void __iomem *base = p->mapbase;
unsigned long offs;
if (reg_nr == TSTR) {
iowrite8(value, base - cfg->channel_offset);
return;
}
offs = reg_nr << 2;
if (reg_nr == TCR)
iowrite16(value, base + offs);
else
iowrite32(value, base + offs);
}
static void sh_tmu_start_stop_ch(struct sh_tmu_priv *p, int start)
{
struct sh_timer_config *cfg = p->pdev->dev.platform_data;
unsigned long flags, value;
/* start stop register shared by multiple timer channels */
spin_lock_irqsave(&sh_tmu_lock, flags);
value = sh_tmu_read(p, TSTR);
if (start)
value |= 1 << cfg->timer_bit;
else
value &= ~(1 << cfg->timer_bit);
sh_tmu_write(p, TSTR, value);
spin_unlock_irqrestore(&sh_tmu_lock, flags);
}
static int sh_tmu_enable(struct sh_tmu_priv *p)
{
int ret;
/* enable clock */
ret = clk_enable(p->clk);
if (ret) {
dev_err(&p->pdev->dev, "cannot enable clock\n");
return ret;
}
/* make sure channel is disabled */
sh_tmu_start_stop_ch(p, 0);
/* maximum timeout */
sh_tmu_write(p, TCOR, 0xffffffff);
sh_tmu_write(p, TCNT, 0xffffffff);
/* configure channel to parent clock / 4, irq off */
p->rate = clk_get_rate(p->clk) / 4;
sh_tmu_write(p, TCR, 0x0000);
/* enable channel */
sh_tmu_start_stop_ch(p, 1);
return 0;
}
static void sh_tmu_disable(struct sh_tmu_priv *p)
{
/* disable channel */
sh_tmu_start_stop_ch(p, 0);
/* disable interrupts in TMU block */
sh_tmu_write(p, TCR, 0x0000);
/* stop clock */
clk_disable(p->clk);
}
static void sh_tmu_set_next(struct sh_tmu_priv *p, unsigned long delta,
int periodic)
{
/* stop timer */
sh_tmu_start_stop_ch(p, 0);
/* acknowledge interrupt */
sh_tmu_read(p, TCR);
/* enable interrupt */
sh_tmu_write(p, TCR, 0x0020);
/* reload delta value in case of periodic timer */
if (periodic)
sh_tmu_write(p, TCOR, delta);
else
sh_tmu_write(p, TCOR, 0xffffffff);
sh_tmu_write(p, TCNT, delta);
/* start timer */
sh_tmu_start_stop_ch(p, 1);
}
static irqreturn_t sh_tmu_interrupt(int irq, void *dev_id)
{
struct sh_tmu_priv *p = dev_id;
/* disable or acknowledge interrupt */
if (p->ced.mode == CLOCK_EVT_MODE_ONESHOT)
sh_tmu_write(p, TCR, 0x0000);
else
sh_tmu_write(p, TCR, 0x0020);
/* notify clockevent layer */
p->ced.event_handler(&p->ced);
return IRQ_HANDLED;
}
static struct sh_tmu_priv *cs_to_sh_tmu(struct clocksource *cs)
{
return container_of(cs, struct sh_tmu_priv, cs);
}
static cycle_t sh_tmu_clocksource_read(struct clocksource *cs)
{
struct sh_tmu_priv *p = cs_to_sh_tmu(cs);
return sh_tmu_read(p, TCNT) ^ 0xffffffff;
}
static int sh_tmu_clocksource_enable(struct clocksource *cs)
{
struct sh_tmu_priv *p = cs_to_sh_tmu(cs);
int ret;
ret = sh_tmu_enable(p);
if (!ret)
__clocksource_updatefreq_hz(cs, p->rate);
return ret;
}
static void sh_tmu_clocksource_disable(struct clocksource *cs)
{
sh_tmu_disable(cs_to_sh_tmu(cs));
}
static int sh_tmu_register_clocksource(struct sh_tmu_priv *p,
char *name, unsigned long rating)
{
struct clocksource *cs = &p->cs;
cs->name = name;
cs->rating = rating;
cs->read = sh_tmu_clocksource_read;
cs->enable = sh_tmu_clocksource_enable;
cs->disable = sh_tmu_clocksource_disable;
cs->mask = CLOCKSOURCE_MASK(32);
cs->flags = CLOCK_SOURCE_IS_CONTINUOUS;
dev_info(&p->pdev->dev, "used as clock source\n");
/* Register with dummy 1 Hz value, gets updated in ->enable() */
clocksource_register_hz(cs, 1);
return 0;
}
static struct sh_tmu_priv *ced_to_sh_tmu(struct clock_event_device *ced)
{
return container_of(ced, struct sh_tmu_priv, ced);
}
static void sh_tmu_clock_event_start(struct sh_tmu_priv *p, int periodic)
{
struct clock_event_device *ced = &p->ced;
sh_tmu_enable(p);
/* TODO: calculate good shift from rate and counter bit width */
ced->shift = 32;
ced->mult = div_sc(p->rate, NSEC_PER_SEC, ced->shift);
ced->max_delta_ns = clockevent_delta2ns(0xffffffff, ced);
ced->min_delta_ns = 5000;
if (periodic) {
p->periodic = (p->rate + HZ/2) / HZ;
sh_tmu_set_next(p, p->periodic, 1);
}
}
static void sh_tmu_clock_event_mode(enum clock_event_mode mode,
struct clock_event_device *ced)
{
struct sh_tmu_priv *p = ced_to_sh_tmu(ced);
int disabled = 0;
/* deal with old setting first */
switch (ced->mode) {
case CLOCK_EVT_MODE_PERIODIC:
case CLOCK_EVT_MODE_ONESHOT:
sh_tmu_disable(p);
disabled = 1;
break;
default:
break;
}
switch (mode) {
case CLOCK_EVT_MODE_PERIODIC:
dev_info(&p->pdev->dev, "used for periodic clock events\n");
sh_tmu_clock_event_start(p, 1);
break;
case CLOCK_EVT_MODE_ONESHOT:
dev_info(&p->pdev->dev, "used for oneshot clock events\n");
sh_tmu_clock_event_start(p, 0);
break;
case CLOCK_EVT_MODE_UNUSED:
if (!disabled)
sh_tmu_disable(p);
break;
case CLOCK_EVT_MODE_SHUTDOWN:
default:
break;
}
}
static int sh_tmu_clock_event_next(unsigned long delta,
struct clock_event_device *ced)
{
struct sh_tmu_priv *p = ced_to_sh_tmu(ced);
BUG_ON(ced->mode != CLOCK_EVT_MODE_ONESHOT);
/* program new delta value */
sh_tmu_set_next(p, delta, 0);
return 0;
}
static void sh_tmu_register_clockevent(struct sh_tmu_priv *p,
char *name, unsigned long rating)
{
struct clock_event_device *ced = &p->ced;
int ret;
memset(ced, 0, sizeof(*ced));
ced->name = name;
ced->features = CLOCK_EVT_FEAT_PERIODIC;
ced->features |= CLOCK_EVT_FEAT_ONESHOT;
ced->rating = rating;
ced->cpumask = cpumask_of(0);
ced->set_next_event = sh_tmu_clock_event_next;
ced->set_mode = sh_tmu_clock_event_mode;
dev_info(&p->pdev->dev, "used for clock events\n");
clockevents_register_device(ced);
ret = setup_irq(p->irqaction.irq, &p->irqaction);
if (ret) {
dev_err(&p->pdev->dev, "failed to request irq %d\n",
p->irqaction.irq);
return;
}
}
static int sh_tmu_register(struct sh_tmu_priv *p, char *name,
unsigned long clockevent_rating,
unsigned long clocksource_rating)
{
if (clockevent_rating)
sh_tmu_register_clockevent(p, name, clockevent_rating);
else if (clocksource_rating)
sh_tmu_register_clocksource(p, name, clocksource_rating);
return 0;
}
static int sh_tmu_setup(struct sh_tmu_priv *p, struct platform_device *pdev)
{
struct sh_timer_config *cfg = pdev->dev.platform_data;
struct resource *res;
int irq, ret;
ret = -ENXIO;
memset(p, 0, sizeof(*p));
p->pdev = pdev;
if (!cfg) {
dev_err(&p->pdev->dev, "missing platform data\n");
goto err0;
}
platform_set_drvdata(pdev, p);
res = platform_get_resource(p->pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&p->pdev->dev, "failed to get I/O memory\n");
goto err0;
}
irq = platform_get_irq(p->pdev, 0);
if (irq < 0) {
dev_err(&p->pdev->dev, "failed to get irq\n");
goto err0;
}
/* map memory, let mapbase point to our channel */
p->mapbase = ioremap_nocache(res->start, resource_size(res));
if (p->mapbase == NULL) {
dev_err(&p->pdev->dev, "failed to remap I/O memory\n");
goto err0;
}
/* setup data for setup_irq() (too early for request_irq()) */
p->irqaction.name = dev_name(&p->pdev->dev);
p->irqaction.handler = sh_tmu_interrupt;
p->irqaction.dev_id = p;
p->irqaction.irq = irq;
p->irqaction.flags = IRQF_DISABLED | IRQF_TIMER | \
IRQF_IRQPOLL | IRQF_NOBALANCING;
/* get hold of clock */
p->clk = clk_get(&p->pdev->dev, "tmu_fck");
if (IS_ERR(p->clk)) {
dev_err(&p->pdev->dev, "cannot get clock\n");
ret = PTR_ERR(p->clk);
goto err1;
}
return sh_tmu_register(p, (char *)dev_name(&p->pdev->dev),
cfg->clockevent_rating,
cfg->clocksource_rating);
err1:
iounmap(p->mapbase);
err0:
return ret;
}
static int __devinit sh_tmu_probe(struct platform_device *pdev)
{
struct sh_tmu_priv *p = platform_get_drvdata(pdev);
int ret;
if (!is_early_platform_device(pdev))
pm_genpd_dev_always_on(&pdev->dev, true);
if (p) {
dev_info(&pdev->dev, "kept as earlytimer\n");
return 0;
}
p = kmalloc(sizeof(*p), GFP_KERNEL);
if (p == NULL) {
dev_err(&pdev->dev, "failed to allocate driver data\n");
return -ENOMEM;
}
ret = sh_tmu_setup(p, pdev);
if (ret) {
kfree(p);
platform_set_drvdata(pdev, NULL);
}
return ret;
}
static int __devexit sh_tmu_remove(struct platform_device *pdev)
{
return -EBUSY; /* cannot unregister clockevent and clocksource */
}
static struct platform_driver sh_tmu_device_driver = {
.probe = sh_tmu_probe,
.remove = __devexit_p(sh_tmu_remove),
.driver = {
.name = "sh_tmu",
}
};
static int __init sh_tmu_init(void)
{
return platform_driver_register(&sh_tmu_device_driver);
}
static void __exit sh_tmu_exit(void)
{
platform_driver_unregister(&sh_tmu_device_driver);
}
early_platform_init("earlytimer", &sh_tmu_device_driver);
module_init(sh_tmu_init);
module_exit(sh_tmu_exit);
MODULE_AUTHOR("Magnus Damm");
MODULE_DESCRIPTION("SuperH TMU Timer Driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
Monadiac/cm_kernel_samsung_hlte | drivers/bcma/host_pci.c | 4810 | 7205 | /*
* Broadcom specific AMBA
* PCI Host
*
* Licensed under the GNU/GPL. See COPYING for details.
*/
#include "bcma_private.h"
#include <linux/slab.h>
#include <linux/bcma/bcma.h>
#include <linux/pci.h>
#include <linux/module.h>
static void bcma_host_pci_switch_core(struct bcma_device *core)
{
pci_write_config_dword(core->bus->host_pci, BCMA_PCI_BAR0_WIN,
core->addr);
pci_write_config_dword(core->bus->host_pci, BCMA_PCI_BAR0_WIN2,
core->wrap);
core->bus->mapped_core = core;
pr_debug("Switched to core: 0x%X\n", core->id.id);
}
/* Provides access to the requested core. Returns base offset that has to be
* used. It makes use of fixed windows when possible. */
static u16 bcma_host_pci_provide_access_to_core(struct bcma_device *core)
{
switch (core->id.id) {
case BCMA_CORE_CHIPCOMMON:
return 3 * BCMA_CORE_SIZE;
case BCMA_CORE_PCIE:
return 2 * BCMA_CORE_SIZE;
}
if (core->bus->mapped_core != core)
bcma_host_pci_switch_core(core);
return 0;
}
static u8 bcma_host_pci_read8(struct bcma_device *core, u16 offset)
{
offset += bcma_host_pci_provide_access_to_core(core);
return ioread8(core->bus->mmio + offset);
}
static u16 bcma_host_pci_read16(struct bcma_device *core, u16 offset)
{
offset += bcma_host_pci_provide_access_to_core(core);
return ioread16(core->bus->mmio + offset);
}
static u32 bcma_host_pci_read32(struct bcma_device *core, u16 offset)
{
offset += bcma_host_pci_provide_access_to_core(core);
return ioread32(core->bus->mmio + offset);
}
static void bcma_host_pci_write8(struct bcma_device *core, u16 offset,
u8 value)
{
offset += bcma_host_pci_provide_access_to_core(core);
iowrite8(value, core->bus->mmio + offset);
}
static void bcma_host_pci_write16(struct bcma_device *core, u16 offset,
u16 value)
{
offset += bcma_host_pci_provide_access_to_core(core);
iowrite16(value, core->bus->mmio + offset);
}
static void bcma_host_pci_write32(struct bcma_device *core, u16 offset,
u32 value)
{
offset += bcma_host_pci_provide_access_to_core(core);
iowrite32(value, core->bus->mmio + offset);
}
#ifdef CONFIG_BCMA_BLOCKIO
void bcma_host_pci_block_read(struct bcma_device *core, void *buffer,
size_t count, u16 offset, u8 reg_width)
{
void __iomem *addr = core->bus->mmio + offset;
if (core->bus->mapped_core != core)
bcma_host_pci_switch_core(core);
switch (reg_width) {
case sizeof(u8):
ioread8_rep(addr, buffer, count);
break;
case sizeof(u16):
WARN_ON(count & 1);
ioread16_rep(addr, buffer, count >> 1);
break;
case sizeof(u32):
WARN_ON(count & 3);
ioread32_rep(addr, buffer, count >> 2);
break;
default:
WARN_ON(1);
}
}
void bcma_host_pci_block_write(struct bcma_device *core, const void *buffer,
size_t count, u16 offset, u8 reg_width)
{
void __iomem *addr = core->bus->mmio + offset;
if (core->bus->mapped_core != core)
bcma_host_pci_switch_core(core);
switch (reg_width) {
case sizeof(u8):
iowrite8_rep(addr, buffer, count);
break;
case sizeof(u16):
WARN_ON(count & 1);
iowrite16_rep(addr, buffer, count >> 1);
break;
case sizeof(u32):
WARN_ON(count & 3);
iowrite32_rep(addr, buffer, count >> 2);
break;
default:
WARN_ON(1);
}
}
#endif
static u32 bcma_host_pci_aread32(struct bcma_device *core, u16 offset)
{
if (core->bus->mapped_core != core)
bcma_host_pci_switch_core(core);
return ioread32(core->bus->mmio + (1 * BCMA_CORE_SIZE) + offset);
}
static void bcma_host_pci_awrite32(struct bcma_device *core, u16 offset,
u32 value)
{
if (core->bus->mapped_core != core)
bcma_host_pci_switch_core(core);
iowrite32(value, core->bus->mmio + (1 * BCMA_CORE_SIZE) + offset);
}
const struct bcma_host_ops bcma_host_pci_ops = {
.read8 = bcma_host_pci_read8,
.read16 = bcma_host_pci_read16,
.read32 = bcma_host_pci_read32,
.write8 = bcma_host_pci_write8,
.write16 = bcma_host_pci_write16,
.write32 = bcma_host_pci_write32,
#ifdef CONFIG_BCMA_BLOCKIO
.block_read = bcma_host_pci_block_read,
.block_write = bcma_host_pci_block_write,
#endif
.aread32 = bcma_host_pci_aread32,
.awrite32 = bcma_host_pci_awrite32,
};
static int __devinit bcma_host_pci_probe(struct pci_dev *dev,
const struct pci_device_id *id)
{
struct bcma_bus *bus;
int err = -ENOMEM;
const char *name;
u32 val;
/* Alloc */
bus = kzalloc(sizeof(*bus), GFP_KERNEL);
if (!bus)
goto out;
/* Basic PCI configuration */
err = pci_enable_device(dev);
if (err)
goto err_kfree_bus;
name = dev_name(&dev->dev);
if (dev->driver && dev->driver->name)
name = dev->driver->name;
err = pci_request_regions(dev, name);
if (err)
goto err_pci_disable;
pci_set_master(dev);
/* Disable the RETRY_TIMEOUT register (0x41) to keep
* PCI Tx retries from interfering with C3 CPU state */
pci_read_config_dword(dev, 0x40, &val);
if ((val & 0x0000ff00) != 0)
pci_write_config_dword(dev, 0x40, val & 0xffff00ff);
/* SSB needed additional powering up, do we have any AMBA PCI cards? */
if (!pci_is_pcie(dev))
pr_err("PCI card detected, report problems.\n");
/* Map MMIO */
err = -ENOMEM;
bus->mmio = pci_iomap(dev, 0, ~0UL);
if (!bus->mmio)
goto err_pci_release_regions;
/* Host specific */
bus->host_pci = dev;
bus->hosttype = BCMA_HOSTTYPE_PCI;
bus->ops = &bcma_host_pci_ops;
/* Register */
err = bcma_bus_register(bus);
if (err)
goto err_pci_unmap_mmio;
pci_set_drvdata(dev, bus);
out:
return err;
err_pci_unmap_mmio:
pci_iounmap(dev, bus->mmio);
err_pci_release_regions:
pci_release_regions(dev);
err_pci_disable:
pci_disable_device(dev);
err_kfree_bus:
kfree(bus);
return err;
}
static void bcma_host_pci_remove(struct pci_dev *dev)
{
struct bcma_bus *bus = pci_get_drvdata(dev);
bcma_bus_unregister(bus);
pci_iounmap(dev, bus->mmio);
pci_release_regions(dev);
pci_disable_device(dev);
kfree(bus);
pci_set_drvdata(dev, NULL);
}
#ifdef CONFIG_PM
static int bcma_host_pci_suspend(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct bcma_bus *bus = pci_get_drvdata(pdev);
bus->mapped_core = NULL;
return bcma_bus_suspend(bus);
}
static int bcma_host_pci_resume(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct bcma_bus *bus = pci_get_drvdata(pdev);
return bcma_bus_resume(bus);
}
static SIMPLE_DEV_PM_OPS(bcma_pm_ops, bcma_host_pci_suspend,
bcma_host_pci_resume);
#define BCMA_PM_OPS (&bcma_pm_ops)
#else /* CONFIG_PM */
#define BCMA_PM_OPS NULL
#endif /* CONFIG_PM */
static DEFINE_PCI_DEVICE_TABLE(bcma_pci_bridge_tbl) = {
{ PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, 0x0576) },
{ PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, 0x4331) },
{ PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, 0x4353) },
{ PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, 0x4357) },
{ PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, 0x4727) },
{ 0, },
};
MODULE_DEVICE_TABLE(pci, bcma_pci_bridge_tbl);
static struct pci_driver bcma_pci_bridge_driver = {
.name = "bcma-pci-bridge",
.id_table = bcma_pci_bridge_tbl,
.probe = bcma_host_pci_probe,
.remove = bcma_host_pci_remove,
.driver.pm = BCMA_PM_OPS,
};
int __init bcma_host_pci_init(void)
{
return pci_register_driver(&bcma_pci_bridge_driver);
}
void __exit bcma_host_pci_exit(void)
{
pci_unregister_driver(&bcma_pci_bridge_driver);
}
| gpl-2.0 |
MinimalOS-AOSP/kernel_lge_hammerhead | drivers/media/video/gspca/stv06xx/stv06xx_pb0100.c | 5066 | 15359 | /*
* Copyright (c) 2001 Jean-Fredric Clere, Nikolas Zimmermann, Georg Acher
* Mark Cave-Ayland, Carlo E Prelz, Dick Streefland
* Copyright (c) 2002, 2003 Tuukka Toivonen
* Copyright (c) 2008 Erik Andrén
*
* 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
*
* P/N 861037: Sensor HDCS1000 ASIC STV0600
* P/N 861050-0010: Sensor HDCS1000 ASIC STV0600
* P/N 861050-0020: Sensor Photobit PB100 ASIC STV0600-1 - QuickCam Express
* P/N 861055: Sensor ST VV6410 ASIC STV0610 - LEGO cam
* P/N 861075-0040: Sensor HDCS1000 ASIC
* P/N 961179-0700: Sensor ST VV6410 ASIC STV0602 - Dexxa WebCam USB
* P/N 861040-0000: Sensor ST VV6410 ASIC STV0610 - QuickCam Web
*/
/*
* The spec file for the PB-0100 suggests the following for best quality
* images after the sensor has been reset :
*
* PB_ADCGAINL = R60 = 0x03 (3 dec) : sets low reference of ADC
to produce good black level
* PB_PREADCTRL = R32 = 0x1400 (5120 dec) : Enables global gain changes
through R53
* PB_ADCMINGAIN = R52 = 0x10 (16 dec) : Sets the minimum gain for
auto-exposure
* PB_ADCGLOBALGAIN = R53 = 0x10 (16 dec) : Sets the global gain
* PB_EXPGAIN = R14 = 0x11 (17 dec) : Sets the auto-exposure value
* PB_UPDATEINT = R23 = 0x02 (2 dec) : Sets the speed on
auto-exposure routine
* PB_CFILLIN = R5 = 0x0E (14 dec) : Sets the frame rate
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include "stv06xx_pb0100.h"
static const struct ctrl pb0100_ctrl[] = {
#define GAIN_IDX 0
{
{
.id = V4L2_CID_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Gain",
.minimum = 0,
.maximum = 255,
.step = 1,
.default_value = 128
},
.set = pb0100_set_gain,
.get = pb0100_get_gain
},
#define RED_BALANCE_IDX 1
{
{
.id = V4L2_CID_RED_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Red Balance",
.minimum = -255,
.maximum = 255,
.step = 1,
.default_value = 0
},
.set = pb0100_set_red_balance,
.get = pb0100_get_red_balance
},
#define BLUE_BALANCE_IDX 2
{
{
.id = V4L2_CID_BLUE_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Blue Balance",
.minimum = -255,
.maximum = 255,
.step = 1,
.default_value = 0
},
.set = pb0100_set_blue_balance,
.get = pb0100_get_blue_balance
},
#define EXPOSURE_IDX 3
{
{
.id = V4L2_CID_EXPOSURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Exposure",
.minimum = 0,
.maximum = 511,
.step = 1,
.default_value = 12
},
.set = pb0100_set_exposure,
.get = pb0100_get_exposure
},
#define AUTOGAIN_IDX 4
{
{
.id = V4L2_CID_AUTOGAIN,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Automatic Gain and Exposure",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 1
},
.set = pb0100_set_autogain,
.get = pb0100_get_autogain
},
#define AUTOGAIN_TARGET_IDX 5
{
{
.id = V4L2_CTRL_CLASS_USER + 0x1000,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Automatic Gain Target",
.minimum = 0,
.maximum = 255,
.step = 1,
.default_value = 128
},
.set = pb0100_set_autogain_target,
.get = pb0100_get_autogain_target
},
#define NATURAL_IDX 6
{
{
.id = V4L2_CTRL_CLASS_USER + 0x1001,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Natural Light Source",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 1
},
.set = pb0100_set_natural,
.get = pb0100_get_natural
}
};
static struct v4l2_pix_format pb0100_mode[] = {
/* low res / subsample modes disabled as they are only half res horizontal,
halving the vertical resolution does not seem to work */
{
320,
240,
V4L2_PIX_FMT_SGRBG8,
V4L2_FIELD_NONE,
.sizeimage = 320 * 240,
.bytesperline = 320,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = PB0100_CROP_TO_VGA
},
{
352,
288,
V4L2_PIX_FMT_SGRBG8,
V4L2_FIELD_NONE,
.sizeimage = 352 * 288,
.bytesperline = 352,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 0
}
};
static int pb0100_probe(struct sd *sd)
{
u16 sensor;
int i, err;
s32 *sensor_settings;
err = stv06xx_read_sensor(sd, PB_IDENT, &sensor);
if (err < 0)
return -ENODEV;
if ((sensor >> 8) == 0x64) {
sensor_settings = kmalloc(
ARRAY_SIZE(pb0100_ctrl) * sizeof(s32),
GFP_KERNEL);
if (!sensor_settings)
return -ENOMEM;
pr_info("Photobit pb0100 sensor detected\n");
sd->gspca_dev.cam.cam_mode = pb0100_mode;
sd->gspca_dev.cam.nmodes = ARRAY_SIZE(pb0100_mode);
sd->desc.ctrls = pb0100_ctrl;
sd->desc.nctrls = ARRAY_SIZE(pb0100_ctrl);
for (i = 0; i < sd->desc.nctrls; i++)
sensor_settings[i] = pb0100_ctrl[i].qctrl.default_value;
sd->sensor_priv = sensor_settings;
return 0;
}
return -ENODEV;
}
static int pb0100_start(struct sd *sd)
{
int err, packet_size, max_packet_size;
struct usb_host_interface *alt;
struct usb_interface *intf;
struct cam *cam = &sd->gspca_dev.cam;
s32 *sensor_settings = sd->sensor_priv;
u32 mode = cam->cam_mode[sd->gspca_dev.curr_mode].priv;
intf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface);
alt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt);
if (!alt)
return -ENODEV;
packet_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize);
/* If we don't have enough bandwidth use a lower framerate */
max_packet_size = sd->sensor->max_packet_size[sd->gspca_dev.curr_mode];
if (packet_size < max_packet_size)
stv06xx_write_sensor(sd, PB_ROWSPEED, BIT(4)|BIT(3)|BIT(1));
else
stv06xx_write_sensor(sd, PB_ROWSPEED, BIT(5)|BIT(3)|BIT(1));
/* Setup sensor window */
if (mode & PB0100_CROP_TO_VGA) {
stv06xx_write_sensor(sd, PB_RSTART, 30);
stv06xx_write_sensor(sd, PB_CSTART, 20);
stv06xx_write_sensor(sd, PB_RWSIZE, 240 - 1);
stv06xx_write_sensor(sd, PB_CWSIZE, 320 - 1);
} else {
stv06xx_write_sensor(sd, PB_RSTART, 8);
stv06xx_write_sensor(sd, PB_CSTART, 4);
stv06xx_write_sensor(sd, PB_RWSIZE, 288 - 1);
stv06xx_write_sensor(sd, PB_CWSIZE, 352 - 1);
}
if (mode & PB0100_SUBSAMPLE) {
stv06xx_write_bridge(sd, STV_Y_CTRL, 0x02); /* Wrong, FIXME */
stv06xx_write_bridge(sd, STV_X_CTRL, 0x06);
stv06xx_write_bridge(sd, STV_SCAN_RATE, 0x10);
} else {
stv06xx_write_bridge(sd, STV_Y_CTRL, 0x01);
stv06xx_write_bridge(sd, STV_X_CTRL, 0x0a);
/* larger -> slower */
stv06xx_write_bridge(sd, STV_SCAN_RATE, 0x20);
}
/* set_gain also sets red and blue balance */
pb0100_set_gain(&sd->gspca_dev, sensor_settings[GAIN_IDX]);
pb0100_set_exposure(&sd->gspca_dev, sensor_settings[EXPOSURE_IDX]);
pb0100_set_autogain_target(&sd->gspca_dev,
sensor_settings[AUTOGAIN_TARGET_IDX]);
pb0100_set_autogain(&sd->gspca_dev, sensor_settings[AUTOGAIN_IDX]);
err = stv06xx_write_sensor(sd, PB_CONTROL, BIT(5)|BIT(3)|BIT(1));
PDEBUG(D_STREAM, "Started stream, status: %d", err);
return (err < 0) ? err : 0;
}
static int pb0100_stop(struct sd *sd)
{
int err;
err = stv06xx_write_sensor(sd, PB_ABORTFRAME, 1);
if (err < 0)
goto out;
/* Set bit 1 to zero */
err = stv06xx_write_sensor(sd, PB_CONTROL, BIT(5)|BIT(3));
PDEBUG(D_STREAM, "Halting stream");
out:
return (err < 0) ? err : 0;
}
static void pb0100_disconnect(struct sd *sd)
{
sd->sensor = NULL;
kfree(sd->sensor_priv);
}
/* FIXME: Sort the init commands out and put them into tables,
this is only for getting the camera to work */
/* FIXME: No error handling for now,
add this once the init has been converted to proper tables */
static int pb0100_init(struct sd *sd)
{
stv06xx_write_bridge(sd, STV_REG00, 1);
stv06xx_write_bridge(sd, STV_SCAN_RATE, 0);
/* Reset sensor */
stv06xx_write_sensor(sd, PB_RESET, 1);
stv06xx_write_sensor(sd, PB_RESET, 0);
/* Disable chip */
stv06xx_write_sensor(sd, PB_CONTROL, BIT(5)|BIT(3));
/* Gain stuff...*/
stv06xx_write_sensor(sd, PB_PREADCTRL, BIT(12)|BIT(10)|BIT(6));
stv06xx_write_sensor(sd, PB_ADCGLOBALGAIN, 12);
/* Set up auto-exposure */
/* ADC VREF_HI new setting for a transition
from the Expose1 to the Expose2 setting */
stv06xx_write_sensor(sd, PB_R28, 12);
/* gain max for autoexposure */
stv06xx_write_sensor(sd, PB_ADCMAXGAIN, 180);
/* gain min for autoexposure */
stv06xx_write_sensor(sd, PB_ADCMINGAIN, 12);
/* Maximum frame integration time (programmed into R8)
allowed for auto-exposure routine */
stv06xx_write_sensor(sd, PB_R54, 3);
/* Minimum frame integration time (programmed into R8)
allowed for auto-exposure routine */
stv06xx_write_sensor(sd, PB_R55, 0);
stv06xx_write_sensor(sd, PB_UPDATEINT, 1);
/* R15 Expose0 (maximum that auto-exposure may use) */
stv06xx_write_sensor(sd, PB_R15, 800);
/* R17 Expose2 (minimum that auto-exposure may use) */
stv06xx_write_sensor(sd, PB_R17, 10);
stv06xx_write_sensor(sd, PB_EXPGAIN, 0);
/* 0x14 */
stv06xx_write_sensor(sd, PB_VOFFSET, 0);
/* 0x0D */
stv06xx_write_sensor(sd, PB_ADCGAINH, 11);
/* Set black level (important!) */
stv06xx_write_sensor(sd, PB_ADCGAINL, 0);
/* ??? */
stv06xx_write_bridge(sd, STV_REG00, 0x11);
stv06xx_write_bridge(sd, STV_REG03, 0x45);
stv06xx_write_bridge(sd, STV_REG04, 0x07);
/* Scan/timing for the sensor */
stv06xx_write_sensor(sd, PB_ROWSPEED, BIT(4)|BIT(3)|BIT(1));
stv06xx_write_sensor(sd, PB_CFILLIN, 14);
stv06xx_write_sensor(sd, PB_VBL, 0);
stv06xx_write_sensor(sd, PB_FINTTIME, 0);
stv06xx_write_sensor(sd, PB_RINTTIME, 123);
stv06xx_write_bridge(sd, STV_REG01, 0xc2);
stv06xx_write_bridge(sd, STV_REG02, 0xb0);
return 0;
}
static int pb0100_dump(struct sd *sd)
{
return 0;
}
static int pb0100_get_gain(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[GAIN_IDX];
return 0;
}
static int pb0100_set_gain(struct gspca_dev *gspca_dev, __s32 val)
{
int err;
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
if (sensor_settings[AUTOGAIN_IDX])
return -EBUSY;
sensor_settings[GAIN_IDX] = val;
err = stv06xx_write_sensor(sd, PB_G1GAIN, val);
if (!err)
err = stv06xx_write_sensor(sd, PB_G2GAIN, val);
PDEBUG(D_V4L2, "Set green gain to %d, status: %d", val, err);
if (!err)
err = pb0100_set_red_balance(gspca_dev,
sensor_settings[RED_BALANCE_IDX]);
if (!err)
err = pb0100_set_blue_balance(gspca_dev,
sensor_settings[BLUE_BALANCE_IDX]);
return err;
}
static int pb0100_get_red_balance(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[RED_BALANCE_IDX];
return 0;
}
static int pb0100_set_red_balance(struct gspca_dev *gspca_dev, __s32 val)
{
int err;
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
if (sensor_settings[AUTOGAIN_IDX])
return -EBUSY;
sensor_settings[RED_BALANCE_IDX] = val;
val += sensor_settings[GAIN_IDX];
if (val < 0)
val = 0;
else if (val > 255)
val = 255;
err = stv06xx_write_sensor(sd, PB_RGAIN, val);
PDEBUG(D_V4L2, "Set red gain to %d, status: %d", val, err);
return err;
}
static int pb0100_get_blue_balance(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[BLUE_BALANCE_IDX];
return 0;
}
static int pb0100_set_blue_balance(struct gspca_dev *gspca_dev, __s32 val)
{
int err;
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
if (sensor_settings[AUTOGAIN_IDX])
return -EBUSY;
sensor_settings[BLUE_BALANCE_IDX] = val;
val += sensor_settings[GAIN_IDX];
if (val < 0)
val = 0;
else if (val > 255)
val = 255;
err = stv06xx_write_sensor(sd, PB_BGAIN, val);
PDEBUG(D_V4L2, "Set blue gain to %d, status: %d", val, err);
return err;
}
static int pb0100_get_exposure(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[EXPOSURE_IDX];
return 0;
}
static int pb0100_set_exposure(struct gspca_dev *gspca_dev, __s32 val)
{
int err;
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
if (sensor_settings[AUTOGAIN_IDX])
return -EBUSY;
sensor_settings[EXPOSURE_IDX] = val;
err = stv06xx_write_sensor(sd, PB_RINTTIME, val);
PDEBUG(D_V4L2, "Set exposure to %d, status: %d", val, err);
return err;
}
static int pb0100_get_autogain(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[AUTOGAIN_IDX];
return 0;
}
static int pb0100_set_autogain(struct gspca_dev *gspca_dev, __s32 val)
{
int err;
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
sensor_settings[AUTOGAIN_IDX] = val;
if (sensor_settings[AUTOGAIN_IDX]) {
if (sensor_settings[NATURAL_IDX])
val = BIT(6)|BIT(4)|BIT(0);
else
val = BIT(4)|BIT(0);
} else
val = 0;
err = stv06xx_write_sensor(sd, PB_EXPGAIN, val);
PDEBUG(D_V4L2, "Set autogain to %d (natural: %d), status: %d",
sensor_settings[AUTOGAIN_IDX], sensor_settings[NATURAL_IDX],
err);
return err;
}
static int pb0100_get_autogain_target(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[AUTOGAIN_TARGET_IDX];
return 0;
}
static int pb0100_set_autogain_target(struct gspca_dev *gspca_dev, __s32 val)
{
int err, totalpixels, brightpixels, darkpixels;
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
sensor_settings[AUTOGAIN_TARGET_IDX] = val;
/* Number of pixels counted by the sensor when subsampling the pixels.
* Slightly larger than the real value to avoid oscillation */
totalpixels = gspca_dev->width * gspca_dev->height;
totalpixels = totalpixels/(8*8) + totalpixels/(64*64);
brightpixels = (totalpixels * val) >> 8;
darkpixels = totalpixels - brightpixels;
err = stv06xx_write_sensor(sd, PB_R21, brightpixels);
if (!err)
err = stv06xx_write_sensor(sd, PB_R22, darkpixels);
PDEBUG(D_V4L2, "Set autogain target to %d, status: %d", val, err);
return err;
}
static int pb0100_get_natural(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[NATURAL_IDX];
return 0;
}
static int pb0100_set_natural(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
sensor_settings[NATURAL_IDX] = val;
return pb0100_set_autogain(gspca_dev, sensor_settings[AUTOGAIN_IDX]);
}
| gpl-2.0 |
mlachwani/Android-4.4.2-Hammerhead-Kernel | drivers/power/max8925_power.c | 5066 | 13873 | /*
* Battery driver for Maxim MAX8925
*
* Copyright (c) 2009-2010 Marvell International Ltd.
* Haojian Zhuang <haojian.zhuang@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/module.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/mfd/max8925.h>
/* registers in GPM */
#define MAX8925_OUT5VEN 0x54
#define MAX8925_OUT3VEN 0x58
#define MAX8925_CHG_CNTL1 0x7c
/* bits definition */
#define MAX8925_CHG_STAT_VSYSLOW (1 << 0)
#define MAX8925_CHG_STAT_MODE_MASK (3 << 2)
#define MAX8925_CHG_STAT_EN_MASK (1 << 4)
#define MAX8925_CHG_MBDET (1 << 1)
#define MAX8925_CHG_AC_RANGE_MASK (3 << 6)
/* registers in ADC */
#define MAX8925_ADC_RES_CNFG1 0x06
#define MAX8925_ADC_AVG_CNFG1 0x07
#define MAX8925_ADC_ACQ_CNFG1 0x08
#define MAX8925_ADC_ACQ_CNFG2 0x09
/* 2 bytes registers in below. MSB is 1st, LSB is 2nd. */
#define MAX8925_ADC_AUX2 0x62
#define MAX8925_ADC_VCHG 0x64
#define MAX8925_ADC_VBBATT 0x66
#define MAX8925_ADC_VMBATT 0x68
#define MAX8925_ADC_ISNS 0x6a
#define MAX8925_ADC_THM 0x6c
#define MAX8925_ADC_TDIE 0x6e
#define MAX8925_CMD_AUX2 0xc8
#define MAX8925_CMD_VCHG 0xd0
#define MAX8925_CMD_VBBATT 0xd8
#define MAX8925_CMD_VMBATT 0xe0
#define MAX8925_CMD_ISNS 0xe8
#define MAX8925_CMD_THM 0xf0
#define MAX8925_CMD_TDIE 0xf8
enum {
MEASURE_AUX2,
MEASURE_VCHG,
MEASURE_VBBATT,
MEASURE_VMBATT,
MEASURE_ISNS,
MEASURE_THM,
MEASURE_TDIE,
MEASURE_MAX,
};
struct max8925_power_info {
struct max8925_chip *chip;
struct i2c_client *gpm;
struct i2c_client *adc;
struct power_supply ac;
struct power_supply usb;
struct power_supply battery;
int irq_base;
unsigned ac_online:1;
unsigned usb_online:1;
unsigned bat_online:1;
unsigned chg_mode:2;
unsigned batt_detect:1; /* detecing MB by ID pin */
unsigned topoff_threshold:2;
unsigned fast_charge:3;
unsigned no_temp_support:1;
unsigned no_insert_detect:1;
int (*set_charger) (int);
};
static int __set_charger(struct max8925_power_info *info, int enable)
{
struct max8925_chip *chip = info->chip;
if (enable) {
/* enable charger in platform */
if (info->set_charger)
info->set_charger(1);
/* enable charger */
max8925_set_bits(info->gpm, MAX8925_CHG_CNTL1, 1 << 7, 0);
} else {
/* disable charge */
max8925_set_bits(info->gpm, MAX8925_CHG_CNTL1, 1 << 7, 1 << 7);
if (info->set_charger)
info->set_charger(0);
}
dev_dbg(chip->dev, "%s\n", (enable) ? "Enable charger"
: "Disable charger");
return 0;
}
static irqreturn_t max8925_charger_handler(int irq, void *data)
{
struct max8925_power_info *info = (struct max8925_power_info *)data;
struct max8925_chip *chip = info->chip;
switch (irq - chip->irq_base) {
case MAX8925_IRQ_VCHG_DC_R:
info->ac_online = 1;
__set_charger(info, 1);
dev_dbg(chip->dev, "Adapter inserted\n");
break;
case MAX8925_IRQ_VCHG_DC_F:
info->ac_online = 0;
__set_charger(info, 0);
dev_dbg(chip->dev, "Adapter removed\n");
break;
case MAX8925_IRQ_VCHG_THM_OK_F:
/* Battery is not ready yet */
dev_dbg(chip->dev, "Battery temperature is out of range\n");
case MAX8925_IRQ_VCHG_DC_OVP:
dev_dbg(chip->dev, "Error detection\n");
__set_charger(info, 0);
break;
case MAX8925_IRQ_VCHG_THM_OK_R:
/* Battery is ready now */
dev_dbg(chip->dev, "Battery temperature is in range\n");
break;
case MAX8925_IRQ_VCHG_SYSLOW_R:
/* VSYS is low */
dev_info(chip->dev, "Sys power is too low\n");
break;
case MAX8925_IRQ_VCHG_SYSLOW_F:
dev_dbg(chip->dev, "Sys power is above low threshold\n");
break;
case MAX8925_IRQ_VCHG_DONE:
__set_charger(info, 0);
dev_dbg(chip->dev, "Charging is done\n");
break;
case MAX8925_IRQ_VCHG_TOPOFF:
dev_dbg(chip->dev, "Charging in top-off mode\n");
break;
case MAX8925_IRQ_VCHG_TMR_FAULT:
__set_charger(info, 0);
dev_dbg(chip->dev, "Safe timer is expired\n");
break;
case MAX8925_IRQ_VCHG_RST:
__set_charger(info, 0);
dev_dbg(chip->dev, "Charger is reset\n");
break;
}
return IRQ_HANDLED;
}
static int start_measure(struct max8925_power_info *info, int type)
{
unsigned char buf[2] = {0, 0};
int meas_cmd;
int meas_reg = 0, ret;
switch (type) {
case MEASURE_VCHG:
meas_cmd = MAX8925_CMD_VCHG;
meas_reg = MAX8925_ADC_VCHG;
break;
case MEASURE_VBBATT:
meas_cmd = MAX8925_CMD_VBBATT;
meas_reg = MAX8925_ADC_VBBATT;
break;
case MEASURE_VMBATT:
meas_cmd = MAX8925_CMD_VMBATT;
meas_reg = MAX8925_ADC_VMBATT;
break;
case MEASURE_ISNS:
meas_cmd = MAX8925_CMD_ISNS;
meas_reg = MAX8925_ADC_ISNS;
break;
default:
return -EINVAL;
}
max8925_reg_write(info->adc, meas_cmd, 0);
max8925_bulk_read(info->adc, meas_reg, 2, buf);
ret = ((buf[0]<<8) | buf[1]) >> 4;
return ret;
}
static int max8925_ac_get_prop(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct max8925_power_info *info = dev_get_drvdata(psy->dev->parent);
int ret = 0;
switch (psp) {
case POWER_SUPPLY_PROP_ONLINE:
val->intval = info->ac_online;
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
if (info->ac_online) {
ret = start_measure(info, MEASURE_VCHG);
if (ret >= 0) {
val->intval = ret * 2000; /* unit is uV */
goto out;
}
}
ret = -ENODATA;
break;
default:
ret = -ENODEV;
break;
}
out:
return ret;
}
static enum power_supply_property max8925_ac_props[] = {
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
};
static int max8925_usb_get_prop(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct max8925_power_info *info = dev_get_drvdata(psy->dev->parent);
int ret = 0;
switch (psp) {
case POWER_SUPPLY_PROP_ONLINE:
val->intval = info->usb_online;
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
if (info->usb_online) {
ret = start_measure(info, MEASURE_VCHG);
if (ret >= 0) {
val->intval = ret * 2000; /* unit is uV */
goto out;
}
}
ret = -ENODATA;
break;
default:
ret = -ENODEV;
break;
}
out:
return ret;
}
static enum power_supply_property max8925_usb_props[] = {
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
};
static int max8925_bat_get_prop(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct max8925_power_info *info = dev_get_drvdata(psy->dev->parent);
int ret = 0;
switch (psp) {
case POWER_SUPPLY_PROP_ONLINE:
val->intval = info->bat_online;
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
if (info->bat_online) {
ret = start_measure(info, MEASURE_VMBATT);
if (ret >= 0) {
val->intval = ret * 2000; /* unit is uV */
ret = 0;
break;
}
}
ret = -ENODATA;
break;
case POWER_SUPPLY_PROP_CURRENT_NOW:
if (info->bat_online) {
ret = start_measure(info, MEASURE_ISNS);
if (ret >= 0) {
/* assume r_sns is 0.02 */
ret = ((ret * 6250) - 3125) /* uA */;
val->intval = 0;
if (ret > 0)
val->intval = ret; /* unit is mA */
ret = 0;
break;
}
}
ret = -ENODATA;
break;
case POWER_SUPPLY_PROP_CHARGE_TYPE:
if (!info->bat_online) {
ret = -ENODATA;
break;
}
ret = max8925_reg_read(info->gpm, MAX8925_CHG_STATUS);
ret = (ret & MAX8925_CHG_STAT_MODE_MASK) >> 2;
switch (ret) {
case 1:
val->intval = POWER_SUPPLY_CHARGE_TYPE_FAST;
break;
case 0:
case 2:
val->intval = POWER_SUPPLY_CHARGE_TYPE_TRICKLE;
break;
case 3:
val->intval = POWER_SUPPLY_CHARGE_TYPE_NONE;
break;
}
ret = 0;
break;
case POWER_SUPPLY_PROP_STATUS:
if (!info->bat_online) {
ret = -ENODATA;
break;
}
ret = max8925_reg_read(info->gpm, MAX8925_CHG_STATUS);
if (info->usb_online || info->ac_online) {
val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING;
if (ret & MAX8925_CHG_STAT_EN_MASK)
val->intval = POWER_SUPPLY_STATUS_CHARGING;
} else
val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
ret = 0;
break;
default:
ret = -ENODEV;
break;
}
return ret;
}
static enum power_supply_property max8925_battery_props[] = {
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_CURRENT_NOW,
POWER_SUPPLY_PROP_CHARGE_TYPE,
POWER_SUPPLY_PROP_STATUS,
};
#define REQUEST_IRQ(_irq, _name) \
do { \
ret = request_threaded_irq(chip->irq_base + _irq, NULL, \
max8925_charger_handler, \
IRQF_ONESHOT, _name, info); \
if (ret) \
dev_err(chip->dev, "Failed to request IRQ #%d: %d\n", \
_irq, ret); \
} while (0)
static __devinit int max8925_init_charger(struct max8925_chip *chip,
struct max8925_power_info *info)
{
int ret;
REQUEST_IRQ(MAX8925_IRQ_VCHG_DC_OVP, "ac-ovp");
if (!info->no_insert_detect) {
REQUEST_IRQ(MAX8925_IRQ_VCHG_DC_F, "ac-remove");
REQUEST_IRQ(MAX8925_IRQ_VCHG_DC_R, "ac-insert");
}
if (!info->no_temp_support) {
REQUEST_IRQ(MAX8925_IRQ_VCHG_THM_OK_R, "batt-temp-in-range");
REQUEST_IRQ(MAX8925_IRQ_VCHG_THM_OK_F, "batt-temp-out-range");
}
REQUEST_IRQ(MAX8925_IRQ_VCHG_SYSLOW_F, "vsys-high");
REQUEST_IRQ(MAX8925_IRQ_VCHG_SYSLOW_R, "vsys-low");
REQUEST_IRQ(MAX8925_IRQ_VCHG_RST, "charger-reset");
REQUEST_IRQ(MAX8925_IRQ_VCHG_DONE, "charger-done");
REQUEST_IRQ(MAX8925_IRQ_VCHG_TOPOFF, "charger-topoff");
REQUEST_IRQ(MAX8925_IRQ_VCHG_TMR_FAULT, "charger-timer-expire");
info->usb_online = 0;
info->bat_online = 0;
/* check for power - can miss interrupt at boot time */
if (start_measure(info, MEASURE_VCHG) * 2000 > 500000)
info->ac_online = 1;
else
info->ac_online = 0;
ret = max8925_reg_read(info->gpm, MAX8925_CHG_STATUS);
if (ret >= 0) {
/*
* If battery detection is enabled, ID pin of battery is
* connected to MBDET pin of MAX8925. It could be used to
* detect battery presence.
* Otherwise, we have to assume that battery is always on.
*/
if (info->batt_detect)
info->bat_online = (ret & MAX8925_CHG_MBDET) ? 0 : 1;
else
info->bat_online = 1;
if (ret & MAX8925_CHG_AC_RANGE_MASK)
info->ac_online = 1;
else
info->ac_online = 0;
}
/* disable charge */
max8925_set_bits(info->gpm, MAX8925_CHG_CNTL1, 1 << 7, 1 << 7);
/* set charging current in charge topoff mode */
max8925_set_bits(info->gpm, MAX8925_CHG_CNTL1, 3 << 5,
info->topoff_threshold << 5);
/* set charing current in fast charge mode */
max8925_set_bits(info->gpm, MAX8925_CHG_CNTL1, 7, info->fast_charge);
return 0;
}
static __devexit int max8925_deinit_charger(struct max8925_power_info *info)
{
struct max8925_chip *chip = info->chip;
int irq;
irq = chip->irq_base + MAX8925_IRQ_VCHG_DC_OVP;
for (; irq <= chip->irq_base + MAX8925_IRQ_VCHG_TMR_FAULT; irq++)
free_irq(irq, info);
return 0;
}
static __devinit int max8925_power_probe(struct platform_device *pdev)
{
struct max8925_chip *chip = dev_get_drvdata(pdev->dev.parent);
struct max8925_power_pdata *pdata = NULL;
struct max8925_power_info *info;
int ret;
pdata = pdev->dev.platform_data;
if (!pdata) {
dev_err(&pdev->dev, "platform data isn't assigned to "
"power supply\n");
return -EINVAL;
}
info = kzalloc(sizeof(struct max8925_power_info), GFP_KERNEL);
if (!info)
return -ENOMEM;
info->chip = chip;
info->gpm = chip->i2c;
info->adc = chip->adc;
platform_set_drvdata(pdev, info);
info->ac.name = "max8925-ac";
info->ac.type = POWER_SUPPLY_TYPE_MAINS;
info->ac.properties = max8925_ac_props;
info->ac.num_properties = ARRAY_SIZE(max8925_ac_props);
info->ac.get_property = max8925_ac_get_prop;
info->ac.supplied_to = pdata->supplied_to;
info->ac.num_supplicants = pdata->num_supplicants;
ret = power_supply_register(&pdev->dev, &info->ac);
if (ret)
goto out;
info->ac.dev->parent = &pdev->dev;
info->usb.name = "max8925-usb";
info->usb.type = POWER_SUPPLY_TYPE_USB;
info->usb.properties = max8925_usb_props;
info->usb.num_properties = ARRAY_SIZE(max8925_usb_props);
info->usb.get_property = max8925_usb_get_prop;
info->usb.supplied_to = pdata->supplied_to;
info->usb.num_supplicants = pdata->num_supplicants;
ret = power_supply_register(&pdev->dev, &info->usb);
if (ret)
goto out_usb;
info->usb.dev->parent = &pdev->dev;
info->battery.name = "max8925-battery";
info->battery.type = POWER_SUPPLY_TYPE_BATTERY;
info->battery.properties = max8925_battery_props;
info->battery.num_properties = ARRAY_SIZE(max8925_battery_props);
info->battery.get_property = max8925_bat_get_prop;
ret = power_supply_register(&pdev->dev, &info->battery);
if (ret)
goto out_battery;
info->battery.dev->parent = &pdev->dev;
info->batt_detect = pdata->batt_detect;
info->topoff_threshold = pdata->topoff_threshold;
info->fast_charge = pdata->fast_charge;
info->set_charger = pdata->set_charger;
info->no_temp_support = pdata->no_temp_support;
info->no_insert_detect = pdata->no_insert_detect;
max8925_init_charger(chip, info);
return 0;
out_battery:
power_supply_unregister(&info->battery);
out_usb:
power_supply_unregister(&info->ac);
out:
kfree(info);
return ret;
}
static __devexit int max8925_power_remove(struct platform_device *pdev)
{
struct max8925_power_info *info = platform_get_drvdata(pdev);
if (info) {
power_supply_unregister(&info->ac);
power_supply_unregister(&info->usb);
power_supply_unregister(&info->battery);
max8925_deinit_charger(info);
kfree(info);
}
return 0;
}
static struct platform_driver max8925_power_driver = {
.probe = max8925_power_probe,
.remove = __devexit_p(max8925_power_remove),
.driver = {
.name = "max8925-power",
},
};
module_platform_driver(max8925_power_driver);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Power supply driver for MAX8925");
MODULE_ALIAS("platform:max8925-power");
| gpl-2.0 |
flashka07/android_kernel_samsung_ha3g | arch/unicore32/kernel/puv3-core.c | 7370 | 6535 | /*
* linux/arch/unicore32/kernel/puv3-core.c
*
* Code specific to PKUnity SoC and UniCore ISA
*
* Maintained by GUAN Xue-tao <gxt@mprc.pku.edu.cn>
* Copyright (C) 2001-2010 Guan Xuetao
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/device.h>
#include <linux/amba/bus.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/cnt32_to_63.h>
#include <linux/usb/musb.h>
#include <asm/irq.h>
#include <mach/hardware.h>
#include <mach/pm.h>
/*
* This is the PKUnity sched_clock implementation. This has
* a resolution of 271ns, and a maximum value of 32025597s (370 days).
*
* The return value is guaranteed to be monotonic in that range as
* long as there is always less than 582 seconds between successive
* calls to this function.
*
* ( * 1E9 / CLOCK_TICK_RATE ) -> about 2235/32
*/
unsigned long long sched_clock(void)
{
unsigned long long v = cnt32_to_63(readl(OST_OSCR));
/* original conservative method, but overflow frequently
* v *= NSEC_PER_SEC >> 12;
* do_div(v, CLOCK_TICK_RATE >> 12);
*/
v = ((v & 0x7fffffffffffffffULL) * 2235) >> 5;
return v;
}
static struct resource puv3_usb_resources[] = {
/* order is significant! */
{
.start = io_v2p(PKUNITY_USB_BASE),
.end = io_v2p(PKUNITY_USB_BASE) + 0x3ff,
.flags = IORESOURCE_MEM,
}, {
.start = IRQ_USB,
.flags = IORESOURCE_IRQ,
}, {
.start = IRQ_USB,
.flags = IORESOURCE_IRQ,
},
};
static struct musb_hdrc_config puv3_usb_config[] = {
{
.num_eps = 16,
.multipoint = 1,
#ifdef CONFIG_USB_INVENTRA_DMA
.dma = 1,
.dma_channels = 8,
#endif
},
};
static struct musb_hdrc_platform_data puv3_usb_plat = {
.mode = MUSB_HOST,
.min_power = 100,
.clock = 0,
.config = puv3_usb_config,
};
static struct resource puv3_mmc_resources[] = {
[0] = {
.start = io_v2p(PKUNITY_SDC_BASE),
.end = io_v2p(PKUNITY_SDC_BASE) + 0xfff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_SDC,
.end = IRQ_SDC,
.flags = IORESOURCE_IRQ,
},
};
static struct resource puv3_unigfx_resources[] = {
[0] = {
.start = io_v2p(PKUNITY_UNIGFX_BASE),
.end = io_v2p(PKUNITY_UNIGFX_BASE) + 0xfff,
.flags = IORESOURCE_MEM,
},
};
static struct resource puv3_rtc_resources[] = {
[0] = {
.start = io_v2p(PKUNITY_RTC_BASE),
.end = io_v2p(PKUNITY_RTC_BASE) + 0xff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_RTCAlarm,
.end = IRQ_RTCAlarm,
.flags = IORESOURCE_IRQ,
},
[2] = {
.start = IRQ_RTC,
.end = IRQ_RTC,
.flags = IORESOURCE_IRQ
}
};
static struct resource puv3_pwm_resources[] = {
[0] = {
.start = io_v2p(PKUNITY_OST_BASE) + 0x80,
.end = io_v2p(PKUNITY_OST_BASE) + 0xff,
.flags = IORESOURCE_MEM,
},
};
static struct resource puv3_uart0_resources[] = {
[0] = {
.start = io_v2p(PKUNITY_UART0_BASE),
.end = io_v2p(PKUNITY_UART0_BASE) + 0xff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_UART0,
.end = IRQ_UART0,
.flags = IORESOURCE_IRQ
}
};
static struct resource puv3_uart1_resources[] = {
[0] = {
.start = io_v2p(PKUNITY_UART1_BASE),
.end = io_v2p(PKUNITY_UART1_BASE) + 0xff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_UART1,
.end = IRQ_UART1,
.flags = IORESOURCE_IRQ
}
};
static struct resource puv3_umal_resources[] = {
[0] = {
.start = io_v2p(PKUNITY_UMAL_BASE),
.end = io_v2p(PKUNITY_UMAL_BASE) + 0x1fff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_UMAL,
.end = IRQ_UMAL,
.flags = IORESOURCE_IRQ
}
};
#ifdef CONFIG_PUV3_PM
#define SAVE(x) sleep_save[SLEEP_SAVE_##x] = x
#define RESTORE(x) x = sleep_save[SLEEP_SAVE_##x]
/*
* List of global PXA peripheral registers to preserve.
* More ones like CP and general purpose register values are preserved
* with the stack pointer in sleep.S.
*/
enum {
SLEEP_SAVE_PM_PLLDDRCFG,
SLEEP_SAVE_COUNT
};
static void puv3_cpu_pm_save(unsigned long *sleep_save)
{
/* SAVE(PM_PLLDDRCFG); */
}
static void puv3_cpu_pm_restore(unsigned long *sleep_save)
{
/* RESTORE(PM_PLLDDRCFG); */
}
static int puv3_cpu_pm_prepare(void)
{
/* set resume return address */
writel(virt_to_phys(puv3_cpu_resume), PM_DIVCFG);
return 0;
}
static void puv3_cpu_pm_enter(suspend_state_t state)
{
/* Clear reset status */
writel(RESETC_RSSR_HWR | RESETC_RSSR_WDR
| RESETC_RSSR_SMR | RESETC_RSSR_SWR, RESETC_RSSR);
switch (state) {
/* case PM_SUSPEND_ON:
puv3_cpu_idle();
break; */
case PM_SUSPEND_MEM:
puv3_cpu_pm_prepare();
puv3_cpu_suspend(PM_PMCR_SFB);
break;
}
}
static int puv3_cpu_pm_valid(suspend_state_t state)
{
return state == PM_SUSPEND_MEM;
}
static void puv3_cpu_pm_finish(void)
{
/* ensure not to come back here if it wasn't intended */
/* PSPR = 0; */
}
static struct puv3_cpu_pm_fns puv3_cpu_pm_fnss = {
.save_count = SLEEP_SAVE_COUNT,
.valid = puv3_cpu_pm_valid,
.save = puv3_cpu_pm_save,
.restore = puv3_cpu_pm_restore,
.enter = puv3_cpu_pm_enter,
.prepare = puv3_cpu_pm_prepare,
.finish = puv3_cpu_pm_finish,
};
static void __init puv3_init_pm(void)
{
puv3_cpu_pm_fns = &puv3_cpu_pm_fnss;
}
#else
static inline void puv3_init_pm(void) {}
#endif
void puv3_ps2_init(void)
{
struct clk *bclk32;
bclk32 = clk_get(NULL, "BUS32_CLK");
writel(clk_get_rate(bclk32) / 200000, PS2_CNT); /* should > 5us */
}
void __init puv3_core_init(void)
{
puv3_init_pm();
puv3_ps2_init();
platform_device_register_simple("PKUnity-v3-RTC", -1,
puv3_rtc_resources, ARRAY_SIZE(puv3_rtc_resources));
platform_device_register_simple("PKUnity-v3-UMAL", -1,
puv3_umal_resources, ARRAY_SIZE(puv3_umal_resources));
platform_device_register_simple("PKUnity-v3-MMC", -1,
puv3_mmc_resources, ARRAY_SIZE(puv3_mmc_resources));
platform_device_register_simple("PKUnity-v3-UNIGFX", -1,
puv3_unigfx_resources, ARRAY_SIZE(puv3_unigfx_resources));
platform_device_register_simple("PKUnity-v3-PWM", -1,
puv3_pwm_resources, ARRAY_SIZE(puv3_pwm_resources));
platform_device_register_simple("PKUnity-v3-UART", 0,
puv3_uart0_resources, ARRAY_SIZE(puv3_uart0_resources));
platform_device_register_simple("PKUnity-v3-UART", 1,
puv3_uart1_resources, ARRAY_SIZE(puv3_uart1_resources));
platform_device_register_simple("PKUnity-v3-AC97", -1, NULL, 0);
platform_device_register_resndata(&platform_bus, "musb_hdrc", -1,
puv3_usb_resources, ARRAY_SIZE(puv3_usb_resources),
&puv3_usb_plat, sizeof(puv3_usb_plat));
}
| gpl-2.0 |
baselsayeh/Kyleopen-4.4 | sound/core/oss/route.c | 13002 | 3140 | /*
* Route Plug-In
* Copyright (c) 2000 by Abramo Bagnara <abramo@alsa-project.org>
*
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/time.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include "pcm_plugin.h"
static void zero_areas(struct snd_pcm_plugin_channel *dvp, int ndsts,
snd_pcm_uframes_t frames, snd_pcm_format_t format)
{
int dst = 0;
for (; dst < ndsts; ++dst) {
if (dvp->wanted)
snd_pcm_area_silence(&dvp->area, 0, frames, format);
dvp->enabled = 0;
dvp++;
}
}
static inline void copy_area(const struct snd_pcm_plugin_channel *src_channel,
struct snd_pcm_plugin_channel *dst_channel,
snd_pcm_uframes_t frames, snd_pcm_format_t format)
{
dst_channel->enabled = 1;
snd_pcm_area_copy(&src_channel->area, 0, &dst_channel->area, 0, frames, format);
}
static snd_pcm_sframes_t route_transfer(struct snd_pcm_plugin *plugin,
const struct snd_pcm_plugin_channel *src_channels,
struct snd_pcm_plugin_channel *dst_channels,
snd_pcm_uframes_t frames)
{
int nsrcs, ndsts, dst;
struct snd_pcm_plugin_channel *dvp;
snd_pcm_format_t format;
if (snd_BUG_ON(!plugin || !src_channels || !dst_channels))
return -ENXIO;
if (frames == 0)
return 0;
nsrcs = plugin->src_format.channels;
ndsts = plugin->dst_format.channels;
format = plugin->dst_format.format;
dvp = dst_channels;
if (nsrcs <= 1) {
/* expand to all channels */
for (dst = 0; dst < ndsts; ++dst) {
copy_area(src_channels, dvp, frames, format);
dvp++;
}
return frames;
}
for (dst = 0; dst < ndsts && dst < nsrcs; ++dst) {
copy_area(src_channels, dvp, frames, format);
dvp++;
src_channels++;
}
if (dst < ndsts)
zero_areas(dvp, ndsts - dst, frames, format);
return frames;
}
int snd_pcm_plugin_build_route(struct snd_pcm_substream *plug,
struct snd_pcm_plugin_format *src_format,
struct snd_pcm_plugin_format *dst_format,
struct snd_pcm_plugin **r_plugin)
{
struct snd_pcm_plugin *plugin;
int err;
if (snd_BUG_ON(!r_plugin))
return -ENXIO;
*r_plugin = NULL;
if (snd_BUG_ON(src_format->rate != dst_format->rate))
return -ENXIO;
if (snd_BUG_ON(src_format->format != dst_format->format))
return -ENXIO;
err = snd_pcm_plugin_build(plug, "route conversion",
src_format, dst_format, 0, &plugin);
if (err < 0)
return err;
plugin->transfer = route_transfer;
*r_plugin = plugin;
return 0;
}
| gpl-2.0 |
Dopi/JetKernel | drivers/infiniband/core/mad_rmpp.c | 203 | 27350 | /*
* Copyright (c) 2005 Intel Inc. All rights reserved.
* Copyright (c) 2005-2006 Voltaire, 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 "mad_priv.h"
#include "mad_rmpp.h"
enum rmpp_state {
RMPP_STATE_ACTIVE,
RMPP_STATE_TIMEOUT,
RMPP_STATE_COMPLETE
};
struct mad_rmpp_recv {
struct ib_mad_agent_private *agent;
struct list_head list;
struct delayed_work timeout_work;
struct delayed_work cleanup_work;
struct completion comp;
enum rmpp_state state;
spinlock_t lock;
atomic_t refcount;
struct ib_ah *ah;
struct ib_mad_recv_wc *rmpp_wc;
struct ib_mad_recv_buf *cur_seg_buf;
int last_ack;
int seg_num;
int newwin;
int repwin;
__be64 tid;
u32 src_qp;
u16 slid;
u8 mgmt_class;
u8 class_version;
u8 method;
};
static inline void deref_rmpp_recv(struct mad_rmpp_recv *rmpp_recv)
{
if (atomic_dec_and_test(&rmpp_recv->refcount))
complete(&rmpp_recv->comp);
}
static void destroy_rmpp_recv(struct mad_rmpp_recv *rmpp_recv)
{
deref_rmpp_recv(rmpp_recv);
wait_for_completion(&rmpp_recv->comp);
ib_destroy_ah(rmpp_recv->ah);
kfree(rmpp_recv);
}
void ib_cancel_rmpp_recvs(struct ib_mad_agent_private *agent)
{
struct mad_rmpp_recv *rmpp_recv, *temp_rmpp_recv;
unsigned long flags;
spin_lock_irqsave(&agent->lock, flags);
list_for_each_entry(rmpp_recv, &agent->rmpp_list, list) {
cancel_delayed_work(&rmpp_recv->timeout_work);
cancel_delayed_work(&rmpp_recv->cleanup_work);
}
spin_unlock_irqrestore(&agent->lock, flags);
flush_workqueue(agent->qp_info->port_priv->wq);
list_for_each_entry_safe(rmpp_recv, temp_rmpp_recv,
&agent->rmpp_list, list) {
list_del(&rmpp_recv->list);
if (rmpp_recv->state != RMPP_STATE_COMPLETE)
ib_free_recv_mad(rmpp_recv->rmpp_wc);
destroy_rmpp_recv(rmpp_recv);
}
}
static void format_ack(struct ib_mad_send_buf *msg,
struct ib_rmpp_mad *data,
struct mad_rmpp_recv *rmpp_recv)
{
struct ib_rmpp_mad *ack = msg->mad;
unsigned long flags;
memcpy(ack, &data->mad_hdr, msg->hdr_len);
ack->mad_hdr.method ^= IB_MGMT_METHOD_RESP;
ack->rmpp_hdr.rmpp_type = IB_MGMT_RMPP_TYPE_ACK;
ib_set_rmpp_flags(&ack->rmpp_hdr, IB_MGMT_RMPP_FLAG_ACTIVE);
spin_lock_irqsave(&rmpp_recv->lock, flags);
rmpp_recv->last_ack = rmpp_recv->seg_num;
ack->rmpp_hdr.seg_num = cpu_to_be32(rmpp_recv->seg_num);
ack->rmpp_hdr.paylen_newwin = cpu_to_be32(rmpp_recv->newwin);
spin_unlock_irqrestore(&rmpp_recv->lock, flags);
}
static void ack_recv(struct mad_rmpp_recv *rmpp_recv,
struct ib_mad_recv_wc *recv_wc)
{
struct ib_mad_send_buf *msg;
int ret, hdr_len;
hdr_len = ib_get_mad_data_offset(recv_wc->recv_buf.mad->mad_hdr.mgmt_class);
msg = ib_create_send_mad(&rmpp_recv->agent->agent, recv_wc->wc->src_qp,
recv_wc->wc->pkey_index, 1, hdr_len,
0, GFP_KERNEL);
if (IS_ERR(msg))
return;
format_ack(msg, (struct ib_rmpp_mad *) recv_wc->recv_buf.mad, rmpp_recv);
msg->ah = rmpp_recv->ah;
ret = ib_post_send_mad(msg, NULL);
if (ret)
ib_free_send_mad(msg);
}
static struct ib_mad_send_buf *alloc_response_msg(struct ib_mad_agent *agent,
struct ib_mad_recv_wc *recv_wc)
{
struct ib_mad_send_buf *msg;
struct ib_ah *ah;
int hdr_len;
ah = ib_create_ah_from_wc(agent->qp->pd, recv_wc->wc,
recv_wc->recv_buf.grh, agent->port_num);
if (IS_ERR(ah))
return (void *) ah;
hdr_len = ib_get_mad_data_offset(recv_wc->recv_buf.mad->mad_hdr.mgmt_class);
msg = ib_create_send_mad(agent, recv_wc->wc->src_qp,
recv_wc->wc->pkey_index, 1,
hdr_len, 0, GFP_KERNEL);
if (IS_ERR(msg))
ib_destroy_ah(ah);
else {
msg->ah = ah;
msg->context[0] = ah;
}
return msg;
}
static void ack_ds_ack(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *recv_wc)
{
struct ib_mad_send_buf *msg;
struct ib_rmpp_mad *rmpp_mad;
int ret;
msg = alloc_response_msg(&agent->agent, recv_wc);
if (IS_ERR(msg))
return;
rmpp_mad = msg->mad;
memcpy(rmpp_mad, recv_wc->recv_buf.mad, msg->hdr_len);
rmpp_mad->mad_hdr.method ^= IB_MGMT_METHOD_RESP;
ib_set_rmpp_flags(&rmpp_mad->rmpp_hdr, IB_MGMT_RMPP_FLAG_ACTIVE);
rmpp_mad->rmpp_hdr.seg_num = 0;
rmpp_mad->rmpp_hdr.paylen_newwin = cpu_to_be32(1);
ret = ib_post_send_mad(msg, NULL);
if (ret) {
ib_destroy_ah(msg->ah);
ib_free_send_mad(msg);
}
}
void ib_rmpp_send_handler(struct ib_mad_send_wc *mad_send_wc)
{
if (mad_send_wc->send_buf->context[0] == mad_send_wc->send_buf->ah)
ib_destroy_ah(mad_send_wc->send_buf->ah);
ib_free_send_mad(mad_send_wc->send_buf);
}
static void nack_recv(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *recv_wc, u8 rmpp_status)
{
struct ib_mad_send_buf *msg;
struct ib_rmpp_mad *rmpp_mad;
int ret;
msg = alloc_response_msg(&agent->agent, recv_wc);
if (IS_ERR(msg))
return;
rmpp_mad = msg->mad;
memcpy(rmpp_mad, recv_wc->recv_buf.mad, msg->hdr_len);
rmpp_mad->mad_hdr.method ^= IB_MGMT_METHOD_RESP;
rmpp_mad->rmpp_hdr.rmpp_version = IB_MGMT_RMPP_VERSION;
rmpp_mad->rmpp_hdr.rmpp_type = IB_MGMT_RMPP_TYPE_ABORT;
ib_set_rmpp_flags(&rmpp_mad->rmpp_hdr, IB_MGMT_RMPP_FLAG_ACTIVE);
rmpp_mad->rmpp_hdr.rmpp_status = rmpp_status;
rmpp_mad->rmpp_hdr.seg_num = 0;
rmpp_mad->rmpp_hdr.paylen_newwin = 0;
ret = ib_post_send_mad(msg, NULL);
if (ret) {
ib_destroy_ah(msg->ah);
ib_free_send_mad(msg);
}
}
static void recv_timeout_handler(struct work_struct *work)
{
struct mad_rmpp_recv *rmpp_recv =
container_of(work, struct mad_rmpp_recv, timeout_work.work);
struct ib_mad_recv_wc *rmpp_wc;
unsigned long flags;
spin_lock_irqsave(&rmpp_recv->agent->lock, flags);
if (rmpp_recv->state != RMPP_STATE_ACTIVE) {
spin_unlock_irqrestore(&rmpp_recv->agent->lock, flags);
return;
}
rmpp_recv->state = RMPP_STATE_TIMEOUT;
list_del(&rmpp_recv->list);
spin_unlock_irqrestore(&rmpp_recv->agent->lock, flags);
rmpp_wc = rmpp_recv->rmpp_wc;
nack_recv(rmpp_recv->agent, rmpp_wc, IB_MGMT_RMPP_STATUS_T2L);
destroy_rmpp_recv(rmpp_recv);
ib_free_recv_mad(rmpp_wc);
}
static void recv_cleanup_handler(struct work_struct *work)
{
struct mad_rmpp_recv *rmpp_recv =
container_of(work, struct mad_rmpp_recv, cleanup_work.work);
unsigned long flags;
spin_lock_irqsave(&rmpp_recv->agent->lock, flags);
list_del(&rmpp_recv->list);
spin_unlock_irqrestore(&rmpp_recv->agent->lock, flags);
destroy_rmpp_recv(rmpp_recv);
}
static struct mad_rmpp_recv *
create_rmpp_recv(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct mad_rmpp_recv *rmpp_recv;
struct ib_mad_hdr *mad_hdr;
rmpp_recv = kmalloc(sizeof *rmpp_recv, GFP_KERNEL);
if (!rmpp_recv)
return NULL;
rmpp_recv->ah = ib_create_ah_from_wc(agent->agent.qp->pd,
mad_recv_wc->wc,
mad_recv_wc->recv_buf.grh,
agent->agent.port_num);
if (IS_ERR(rmpp_recv->ah))
goto error;
rmpp_recv->agent = agent;
init_completion(&rmpp_recv->comp);
INIT_DELAYED_WORK(&rmpp_recv->timeout_work, recv_timeout_handler);
INIT_DELAYED_WORK(&rmpp_recv->cleanup_work, recv_cleanup_handler);
spin_lock_init(&rmpp_recv->lock);
rmpp_recv->state = RMPP_STATE_ACTIVE;
atomic_set(&rmpp_recv->refcount, 1);
rmpp_recv->rmpp_wc = mad_recv_wc;
rmpp_recv->cur_seg_buf = &mad_recv_wc->recv_buf;
rmpp_recv->newwin = 1;
rmpp_recv->seg_num = 1;
rmpp_recv->last_ack = 0;
rmpp_recv->repwin = 1;
mad_hdr = &mad_recv_wc->recv_buf.mad->mad_hdr;
rmpp_recv->tid = mad_hdr->tid;
rmpp_recv->src_qp = mad_recv_wc->wc->src_qp;
rmpp_recv->slid = mad_recv_wc->wc->slid;
rmpp_recv->mgmt_class = mad_hdr->mgmt_class;
rmpp_recv->class_version = mad_hdr->class_version;
rmpp_recv->method = mad_hdr->method;
return rmpp_recv;
error: kfree(rmpp_recv);
return NULL;
}
static struct mad_rmpp_recv *
find_rmpp_recv(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct mad_rmpp_recv *rmpp_recv;
struct ib_mad_hdr *mad_hdr = &mad_recv_wc->recv_buf.mad->mad_hdr;
list_for_each_entry(rmpp_recv, &agent->rmpp_list, list) {
if (rmpp_recv->tid == mad_hdr->tid &&
rmpp_recv->src_qp == mad_recv_wc->wc->src_qp &&
rmpp_recv->slid == mad_recv_wc->wc->slid &&
rmpp_recv->mgmt_class == mad_hdr->mgmt_class &&
rmpp_recv->class_version == mad_hdr->class_version &&
rmpp_recv->method == mad_hdr->method)
return rmpp_recv;
}
return NULL;
}
static struct mad_rmpp_recv *
acquire_rmpp_recv(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct mad_rmpp_recv *rmpp_recv;
unsigned long flags;
spin_lock_irqsave(&agent->lock, flags);
rmpp_recv = find_rmpp_recv(agent, mad_recv_wc);
if (rmpp_recv)
atomic_inc(&rmpp_recv->refcount);
spin_unlock_irqrestore(&agent->lock, flags);
return rmpp_recv;
}
static struct mad_rmpp_recv *
insert_rmpp_recv(struct ib_mad_agent_private *agent,
struct mad_rmpp_recv *rmpp_recv)
{
struct mad_rmpp_recv *cur_rmpp_recv;
cur_rmpp_recv = find_rmpp_recv(agent, rmpp_recv->rmpp_wc);
if (!cur_rmpp_recv)
list_add_tail(&rmpp_recv->list, &agent->rmpp_list);
return cur_rmpp_recv;
}
static inline int get_last_flag(struct ib_mad_recv_buf *seg)
{
struct ib_rmpp_mad *rmpp_mad;
rmpp_mad = (struct ib_rmpp_mad *) seg->mad;
return ib_get_rmpp_flags(&rmpp_mad->rmpp_hdr) & IB_MGMT_RMPP_FLAG_LAST;
}
static inline int get_seg_num(struct ib_mad_recv_buf *seg)
{
struct ib_rmpp_mad *rmpp_mad;
rmpp_mad = (struct ib_rmpp_mad *) seg->mad;
return be32_to_cpu(rmpp_mad->rmpp_hdr.seg_num);
}
static inline struct ib_mad_recv_buf * get_next_seg(struct list_head *rmpp_list,
struct ib_mad_recv_buf *seg)
{
if (seg->list.next == rmpp_list)
return NULL;
return container_of(seg->list.next, struct ib_mad_recv_buf, list);
}
static inline int window_size(struct ib_mad_agent_private *agent)
{
return max(agent->qp_info->recv_queue.max_active >> 3, 1);
}
static struct ib_mad_recv_buf * find_seg_location(struct list_head *rmpp_list,
int seg_num)
{
struct ib_mad_recv_buf *seg_buf;
int cur_seg_num;
list_for_each_entry_reverse(seg_buf, rmpp_list, list) {
cur_seg_num = get_seg_num(seg_buf);
if (seg_num > cur_seg_num)
return seg_buf;
if (seg_num == cur_seg_num)
break;
}
return NULL;
}
static void update_seg_num(struct mad_rmpp_recv *rmpp_recv,
struct ib_mad_recv_buf *new_buf)
{
struct list_head *rmpp_list = &rmpp_recv->rmpp_wc->rmpp_list;
while (new_buf && (get_seg_num(new_buf) == rmpp_recv->seg_num + 1)) {
rmpp_recv->cur_seg_buf = new_buf;
rmpp_recv->seg_num++;
new_buf = get_next_seg(rmpp_list, new_buf);
}
}
static inline int get_mad_len(struct mad_rmpp_recv *rmpp_recv)
{
struct ib_rmpp_mad *rmpp_mad;
int hdr_size, data_size, pad;
rmpp_mad = (struct ib_rmpp_mad *)rmpp_recv->cur_seg_buf->mad;
hdr_size = ib_get_mad_data_offset(rmpp_mad->mad_hdr.mgmt_class);
data_size = sizeof(struct ib_rmpp_mad) - hdr_size;
pad = IB_MGMT_RMPP_DATA - be32_to_cpu(rmpp_mad->rmpp_hdr.paylen_newwin);
if (pad > IB_MGMT_RMPP_DATA || pad < 0)
pad = 0;
return hdr_size + rmpp_recv->seg_num * data_size - pad;
}
static struct ib_mad_recv_wc * complete_rmpp(struct mad_rmpp_recv *rmpp_recv)
{
struct ib_mad_recv_wc *rmpp_wc;
ack_recv(rmpp_recv, rmpp_recv->rmpp_wc);
if (rmpp_recv->seg_num > 1)
cancel_delayed_work(&rmpp_recv->timeout_work);
rmpp_wc = rmpp_recv->rmpp_wc;
rmpp_wc->mad_len = get_mad_len(rmpp_recv);
/* 10 seconds until we can find the packet lifetime */
queue_delayed_work(rmpp_recv->agent->qp_info->port_priv->wq,
&rmpp_recv->cleanup_work, msecs_to_jiffies(10000));
return rmpp_wc;
}
static struct ib_mad_recv_wc *
continue_rmpp(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct mad_rmpp_recv *rmpp_recv;
struct ib_mad_recv_buf *prev_buf;
struct ib_mad_recv_wc *done_wc;
int seg_num;
unsigned long flags;
rmpp_recv = acquire_rmpp_recv(agent, mad_recv_wc);
if (!rmpp_recv)
goto drop1;
seg_num = get_seg_num(&mad_recv_wc->recv_buf);
spin_lock_irqsave(&rmpp_recv->lock, flags);
if ((rmpp_recv->state == RMPP_STATE_TIMEOUT) ||
(seg_num > rmpp_recv->newwin))
goto drop3;
if ((seg_num <= rmpp_recv->last_ack) ||
(rmpp_recv->state == RMPP_STATE_COMPLETE)) {
spin_unlock_irqrestore(&rmpp_recv->lock, flags);
ack_recv(rmpp_recv, mad_recv_wc);
goto drop2;
}
prev_buf = find_seg_location(&rmpp_recv->rmpp_wc->rmpp_list, seg_num);
if (!prev_buf)
goto drop3;
done_wc = NULL;
list_add(&mad_recv_wc->recv_buf.list, &prev_buf->list);
if (rmpp_recv->cur_seg_buf == prev_buf) {
update_seg_num(rmpp_recv, &mad_recv_wc->recv_buf);
if (get_last_flag(rmpp_recv->cur_seg_buf)) {
rmpp_recv->state = RMPP_STATE_COMPLETE;
spin_unlock_irqrestore(&rmpp_recv->lock, flags);
done_wc = complete_rmpp(rmpp_recv);
goto out;
} else if (rmpp_recv->seg_num == rmpp_recv->newwin) {
rmpp_recv->newwin += window_size(agent);
spin_unlock_irqrestore(&rmpp_recv->lock, flags);
ack_recv(rmpp_recv, mad_recv_wc);
goto out;
}
}
spin_unlock_irqrestore(&rmpp_recv->lock, flags);
out:
deref_rmpp_recv(rmpp_recv);
return done_wc;
drop3: spin_unlock_irqrestore(&rmpp_recv->lock, flags);
drop2: deref_rmpp_recv(rmpp_recv);
drop1: ib_free_recv_mad(mad_recv_wc);
return NULL;
}
static struct ib_mad_recv_wc *
start_rmpp(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct mad_rmpp_recv *rmpp_recv;
unsigned long flags;
rmpp_recv = create_rmpp_recv(agent, mad_recv_wc);
if (!rmpp_recv) {
ib_free_recv_mad(mad_recv_wc);
return NULL;
}
spin_lock_irqsave(&agent->lock, flags);
if (insert_rmpp_recv(agent, rmpp_recv)) {
spin_unlock_irqrestore(&agent->lock, flags);
/* duplicate first MAD */
destroy_rmpp_recv(rmpp_recv);
return continue_rmpp(agent, mad_recv_wc);
}
atomic_inc(&rmpp_recv->refcount);
if (get_last_flag(&mad_recv_wc->recv_buf)) {
rmpp_recv->state = RMPP_STATE_COMPLETE;
spin_unlock_irqrestore(&agent->lock, flags);
complete_rmpp(rmpp_recv);
} else {
spin_unlock_irqrestore(&agent->lock, flags);
/* 40 seconds until we can find the packet lifetimes */
queue_delayed_work(agent->qp_info->port_priv->wq,
&rmpp_recv->timeout_work,
msecs_to_jiffies(40000));
rmpp_recv->newwin += window_size(agent);
ack_recv(rmpp_recv, mad_recv_wc);
mad_recv_wc = NULL;
}
deref_rmpp_recv(rmpp_recv);
return mad_recv_wc;
}
static int send_next_seg(struct ib_mad_send_wr_private *mad_send_wr)
{
struct ib_rmpp_mad *rmpp_mad;
int timeout;
u32 paylen = 0;
rmpp_mad = mad_send_wr->send_buf.mad;
ib_set_rmpp_flags(&rmpp_mad->rmpp_hdr, IB_MGMT_RMPP_FLAG_ACTIVE);
rmpp_mad->rmpp_hdr.seg_num = cpu_to_be32(++mad_send_wr->seg_num);
if (mad_send_wr->seg_num == 1) {
rmpp_mad->rmpp_hdr.rmpp_rtime_flags |= IB_MGMT_RMPP_FLAG_FIRST;
paylen = mad_send_wr->send_buf.seg_count * IB_MGMT_RMPP_DATA -
mad_send_wr->pad;
}
if (mad_send_wr->seg_num == mad_send_wr->send_buf.seg_count) {
rmpp_mad->rmpp_hdr.rmpp_rtime_flags |= IB_MGMT_RMPP_FLAG_LAST;
paylen = IB_MGMT_RMPP_DATA - mad_send_wr->pad;
}
rmpp_mad->rmpp_hdr.paylen_newwin = cpu_to_be32(paylen);
/* 2 seconds for an ACK until we can find the packet lifetime */
timeout = mad_send_wr->send_buf.timeout_ms;
if (!timeout || timeout > 2000)
mad_send_wr->timeout = msecs_to_jiffies(2000);
return ib_send_mad(mad_send_wr);
}
static void abort_send(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc, u8 rmpp_status)
{
struct ib_mad_send_wr_private *mad_send_wr;
struct ib_mad_send_wc wc;
unsigned long flags;
spin_lock_irqsave(&agent->lock, flags);
mad_send_wr = ib_find_send_mad(agent, mad_recv_wc);
if (!mad_send_wr)
goto out; /* Unmatched send */
if ((mad_send_wr->last_ack == mad_send_wr->send_buf.seg_count) ||
(!mad_send_wr->timeout) || (mad_send_wr->status != IB_WC_SUCCESS))
goto out; /* Send is already done */
ib_mark_mad_done(mad_send_wr);
spin_unlock_irqrestore(&agent->lock, flags);
wc.status = IB_WC_REM_ABORT_ERR;
wc.vendor_err = rmpp_status;
wc.send_buf = &mad_send_wr->send_buf;
ib_mad_complete_send_wr(mad_send_wr, &wc);
return;
out:
spin_unlock_irqrestore(&agent->lock, flags);
}
static inline void adjust_last_ack(struct ib_mad_send_wr_private *wr,
int seg_num)
{
struct list_head *list;
wr->last_ack = seg_num;
list = &wr->last_ack_seg->list;
list_for_each_entry(wr->last_ack_seg, list, list)
if (wr->last_ack_seg->num == seg_num)
break;
}
static void process_ds_ack(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc, int newwin)
{
struct mad_rmpp_recv *rmpp_recv;
rmpp_recv = find_rmpp_recv(agent, mad_recv_wc);
if (rmpp_recv && rmpp_recv->state == RMPP_STATE_COMPLETE)
rmpp_recv->repwin = newwin;
}
static void process_rmpp_ack(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct ib_mad_send_wr_private *mad_send_wr;
struct ib_rmpp_mad *rmpp_mad;
unsigned long flags;
int seg_num, newwin, ret;
rmpp_mad = (struct ib_rmpp_mad *)mad_recv_wc->recv_buf.mad;
if (rmpp_mad->rmpp_hdr.rmpp_status) {
abort_send(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BAD_STATUS);
nack_recv(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BAD_STATUS);
return;
}
seg_num = be32_to_cpu(rmpp_mad->rmpp_hdr.seg_num);
newwin = be32_to_cpu(rmpp_mad->rmpp_hdr.paylen_newwin);
if (newwin < seg_num) {
abort_send(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_W2S);
nack_recv(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_W2S);
return;
}
spin_lock_irqsave(&agent->lock, flags);
mad_send_wr = ib_find_send_mad(agent, mad_recv_wc);
if (!mad_send_wr) {
if (!seg_num)
process_ds_ack(agent, mad_recv_wc, newwin);
goto out; /* Unmatched or DS RMPP ACK */
}
if ((mad_send_wr->last_ack == mad_send_wr->send_buf.seg_count) &&
(mad_send_wr->timeout)) {
spin_unlock_irqrestore(&agent->lock, flags);
ack_ds_ack(agent, mad_recv_wc);
return; /* Repeated ACK for DS RMPP transaction */
}
if ((mad_send_wr->last_ack == mad_send_wr->send_buf.seg_count) ||
(!mad_send_wr->timeout) || (mad_send_wr->status != IB_WC_SUCCESS))
goto out; /* Send is already done */
if (seg_num > mad_send_wr->send_buf.seg_count ||
seg_num > mad_send_wr->newwin) {
spin_unlock_irqrestore(&agent->lock, flags);
abort_send(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_S2B);
nack_recv(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_S2B);
return;
}
if (newwin < mad_send_wr->newwin || seg_num < mad_send_wr->last_ack)
goto out; /* Old ACK */
if (seg_num > mad_send_wr->last_ack) {
adjust_last_ack(mad_send_wr, seg_num);
mad_send_wr->retries_left = mad_send_wr->max_retries;
}
mad_send_wr->newwin = newwin;
if (mad_send_wr->last_ack == mad_send_wr->send_buf.seg_count) {
/* If no response is expected, the ACK completes the send */
if (!mad_send_wr->send_buf.timeout_ms) {
struct ib_mad_send_wc wc;
ib_mark_mad_done(mad_send_wr);
spin_unlock_irqrestore(&agent->lock, flags);
wc.status = IB_WC_SUCCESS;
wc.vendor_err = 0;
wc.send_buf = &mad_send_wr->send_buf;
ib_mad_complete_send_wr(mad_send_wr, &wc);
return;
}
if (mad_send_wr->refcount == 1)
ib_reset_mad_timeout(mad_send_wr,
mad_send_wr->send_buf.timeout_ms);
spin_unlock_irqrestore(&agent->lock, flags);
ack_ds_ack(agent, mad_recv_wc);
return;
} else if (mad_send_wr->refcount == 1 &&
mad_send_wr->seg_num < mad_send_wr->newwin &&
mad_send_wr->seg_num < mad_send_wr->send_buf.seg_count) {
/* Send failure will just result in a timeout/retry */
ret = send_next_seg(mad_send_wr);
if (ret)
goto out;
mad_send_wr->refcount++;
list_move_tail(&mad_send_wr->agent_list,
&mad_send_wr->mad_agent_priv->send_list);
}
out:
spin_unlock_irqrestore(&agent->lock, flags);
}
static struct ib_mad_recv_wc *
process_rmpp_data(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct ib_rmpp_hdr *rmpp_hdr;
u8 rmpp_status;
rmpp_hdr = &((struct ib_rmpp_mad *)mad_recv_wc->recv_buf.mad)->rmpp_hdr;
if (rmpp_hdr->rmpp_status) {
rmpp_status = IB_MGMT_RMPP_STATUS_BAD_STATUS;
goto bad;
}
if (rmpp_hdr->seg_num == __constant_htonl(1)) {
if (!(ib_get_rmpp_flags(rmpp_hdr) & IB_MGMT_RMPP_FLAG_FIRST)) {
rmpp_status = IB_MGMT_RMPP_STATUS_BAD_SEG;
goto bad;
}
return start_rmpp(agent, mad_recv_wc);
} else {
if (ib_get_rmpp_flags(rmpp_hdr) & IB_MGMT_RMPP_FLAG_FIRST) {
rmpp_status = IB_MGMT_RMPP_STATUS_BAD_SEG;
goto bad;
}
return continue_rmpp(agent, mad_recv_wc);
}
bad:
nack_recv(agent, mad_recv_wc, rmpp_status);
ib_free_recv_mad(mad_recv_wc);
return NULL;
}
static void process_rmpp_stop(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct ib_rmpp_mad *rmpp_mad;
rmpp_mad = (struct ib_rmpp_mad *)mad_recv_wc->recv_buf.mad;
if (rmpp_mad->rmpp_hdr.rmpp_status != IB_MGMT_RMPP_STATUS_RESX) {
abort_send(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BAD_STATUS);
nack_recv(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BAD_STATUS);
} else
abort_send(agent, mad_recv_wc, rmpp_mad->rmpp_hdr.rmpp_status);
}
static void process_rmpp_abort(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct ib_rmpp_mad *rmpp_mad;
rmpp_mad = (struct ib_rmpp_mad *)mad_recv_wc->recv_buf.mad;
if (rmpp_mad->rmpp_hdr.rmpp_status < IB_MGMT_RMPP_STATUS_ABORT_MIN ||
rmpp_mad->rmpp_hdr.rmpp_status > IB_MGMT_RMPP_STATUS_ABORT_MAX) {
abort_send(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BAD_STATUS);
nack_recv(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BAD_STATUS);
} else
abort_send(agent, mad_recv_wc, rmpp_mad->rmpp_hdr.rmpp_status);
}
struct ib_mad_recv_wc *
ib_process_rmpp_recv_wc(struct ib_mad_agent_private *agent,
struct ib_mad_recv_wc *mad_recv_wc)
{
struct ib_rmpp_mad *rmpp_mad;
rmpp_mad = (struct ib_rmpp_mad *)mad_recv_wc->recv_buf.mad;
if (!(rmpp_mad->rmpp_hdr.rmpp_rtime_flags & IB_MGMT_RMPP_FLAG_ACTIVE))
return mad_recv_wc;
if (rmpp_mad->rmpp_hdr.rmpp_version != IB_MGMT_RMPP_VERSION) {
abort_send(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_UNV);
nack_recv(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_UNV);
goto out;
}
switch (rmpp_mad->rmpp_hdr.rmpp_type) {
case IB_MGMT_RMPP_TYPE_DATA:
return process_rmpp_data(agent, mad_recv_wc);
case IB_MGMT_RMPP_TYPE_ACK:
process_rmpp_ack(agent, mad_recv_wc);
break;
case IB_MGMT_RMPP_TYPE_STOP:
process_rmpp_stop(agent, mad_recv_wc);
break;
case IB_MGMT_RMPP_TYPE_ABORT:
process_rmpp_abort(agent, mad_recv_wc);
break;
default:
abort_send(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BADT);
nack_recv(agent, mad_recv_wc, IB_MGMT_RMPP_STATUS_BADT);
break;
}
out:
ib_free_recv_mad(mad_recv_wc);
return NULL;
}
static int init_newwin(struct ib_mad_send_wr_private *mad_send_wr)
{
struct ib_mad_agent_private *agent = mad_send_wr->mad_agent_priv;
struct ib_mad_hdr *mad_hdr = mad_send_wr->send_buf.mad;
struct mad_rmpp_recv *rmpp_recv;
struct ib_ah_attr ah_attr;
unsigned long flags;
int newwin = 1;
if (!(mad_hdr->method & IB_MGMT_METHOD_RESP))
goto out;
spin_lock_irqsave(&agent->lock, flags);
list_for_each_entry(rmpp_recv, &agent->rmpp_list, list) {
if (rmpp_recv->tid != mad_hdr->tid ||
rmpp_recv->mgmt_class != mad_hdr->mgmt_class ||
rmpp_recv->class_version != mad_hdr->class_version ||
(rmpp_recv->method & IB_MGMT_METHOD_RESP))
continue;
if (ib_query_ah(mad_send_wr->send_buf.ah, &ah_attr))
continue;
if (rmpp_recv->slid == ah_attr.dlid) {
newwin = rmpp_recv->repwin;
break;
}
}
spin_unlock_irqrestore(&agent->lock, flags);
out:
return newwin;
}
int ib_send_rmpp_mad(struct ib_mad_send_wr_private *mad_send_wr)
{
struct ib_rmpp_mad *rmpp_mad;
int ret;
rmpp_mad = mad_send_wr->send_buf.mad;
if (!(ib_get_rmpp_flags(&rmpp_mad->rmpp_hdr) &
IB_MGMT_RMPP_FLAG_ACTIVE))
return IB_RMPP_RESULT_UNHANDLED;
if (rmpp_mad->rmpp_hdr.rmpp_type != IB_MGMT_RMPP_TYPE_DATA) {
mad_send_wr->seg_num = 1;
return IB_RMPP_RESULT_INTERNAL;
}
mad_send_wr->newwin = init_newwin(mad_send_wr);
/* We need to wait for the final ACK even if there isn't a response */
mad_send_wr->refcount += (mad_send_wr->timeout == 0);
ret = send_next_seg(mad_send_wr);
if (!ret)
return IB_RMPP_RESULT_CONSUMED;
return ret;
}
int ib_process_rmpp_send_wc(struct ib_mad_send_wr_private *mad_send_wr,
struct ib_mad_send_wc *mad_send_wc)
{
struct ib_rmpp_mad *rmpp_mad;
int ret;
rmpp_mad = mad_send_wr->send_buf.mad;
if (!(ib_get_rmpp_flags(&rmpp_mad->rmpp_hdr) &
IB_MGMT_RMPP_FLAG_ACTIVE))
return IB_RMPP_RESULT_UNHANDLED; /* RMPP not active */
if (rmpp_mad->rmpp_hdr.rmpp_type != IB_MGMT_RMPP_TYPE_DATA)
return IB_RMPP_RESULT_INTERNAL; /* ACK, STOP, or ABORT */
if (mad_send_wc->status != IB_WC_SUCCESS ||
mad_send_wr->status != IB_WC_SUCCESS)
return IB_RMPP_RESULT_PROCESSED; /* Canceled or send error */
if (!mad_send_wr->timeout)
return IB_RMPP_RESULT_PROCESSED; /* Response received */
if (mad_send_wr->last_ack == mad_send_wr->send_buf.seg_count) {
mad_send_wr->timeout =
msecs_to_jiffies(mad_send_wr->send_buf.timeout_ms);
return IB_RMPP_RESULT_PROCESSED; /* Send done */
}
if (mad_send_wr->seg_num == mad_send_wr->newwin ||
mad_send_wr->seg_num == mad_send_wr->send_buf.seg_count)
return IB_RMPP_RESULT_PROCESSED; /* Wait for ACK */
ret = send_next_seg(mad_send_wr);
if (ret) {
mad_send_wc->status = IB_WC_GENERAL_ERR;
return IB_RMPP_RESULT_PROCESSED;
}
return IB_RMPP_RESULT_CONSUMED;
}
int ib_retry_rmpp(struct ib_mad_send_wr_private *mad_send_wr)
{
struct ib_rmpp_mad *rmpp_mad;
int ret;
rmpp_mad = mad_send_wr->send_buf.mad;
if (!(ib_get_rmpp_flags(&rmpp_mad->rmpp_hdr) &
IB_MGMT_RMPP_FLAG_ACTIVE))
return IB_RMPP_RESULT_UNHANDLED; /* RMPP not active */
if (mad_send_wr->last_ack == mad_send_wr->send_buf.seg_count)
return IB_RMPP_RESULT_PROCESSED;
mad_send_wr->seg_num = mad_send_wr->last_ack;
mad_send_wr->cur_seg = mad_send_wr->last_ack_seg;
ret = send_next_seg(mad_send_wr);
if (ret)
return IB_RMPP_RESULT_PROCESSED;
return IB_RMPP_RESULT_CONSUMED;
}
| gpl-2.0 |
luckpizza/n8000-kernel-aufs | drivers/net/wireless/ath/ath6kl/c210.c | 203 | 3981 | #include <linux/device.h>
#include <linux/regulator/consumer.h>
#include <linux/gpio.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include "core.h"
typedef int A_BOOL;
typedef unsigned char A_UCHAR;
typedef unsigned long A_ATH_TIMER;
typedef int8_t A_INT8;
typedef int16_t A_INT16;
typedef int32_t A_INT32;
typedef u_int8_t A_UINT8;
typedef u_int16_t A_UINT16;
typedef u_int32_t A_UINT32;
#define WMI_MAX_SSID_LEN 32
#define ATH_MAC_LEN 6 /* length of mac in bytes */
#define __ATTRIB_PACK
#define POSTPACK __ATTRIB_PACK
#define PREPACK
typedef PREPACK struct {
PREPACK union {
A_UINT8 ie[17];
A_INT32 wac_status;
} POSTPACK info;
} POSTPACK WMI_GET_WAC_INFO;
struct ar_wep_key {
A_UINT8 arKeyIndex;
A_UINT8 arKeyLen;
A_UINT8 arKey[64];
} ;
#define A_MDELAY(msecs) mdelay(msecs)
#define WMI_MAX_RATE_MASK 2
#define GET_INODE_FROM_FILEP(filp) \
(filp)->f_path.dentry->d_inode
typedef char A_CHAR;
#if 1 // by bbelief
#define ATH6KL_INIT_TIMEOUT (3 * HZ)
wait_queue_head_t init_wq;
static atomic_t init_done = ATOMIC_INIT(0);
#endif
int android_readwrite_file(const A_CHAR *filename, A_CHAR *rbuf, const A_CHAR *wbuf, size_t length)
{
int ret = 0;
struct file *filp = (struct file *)-ENOENT;
mm_segment_t oldfs;
oldfs = get_fs();
set_fs(KERNEL_DS);
do {
int mode = (wbuf) ? O_RDWR|O_CREAT : O_RDONLY;
filp = filp_open(filename, mode,
S_IRUSR | S_IWUSR | S_IRGRP |
S_IWGRP | S_IROTH | S_IWOTH);
if (IS_ERR(filp) || !filp->f_op) {
ret = -ENOENT;
break;
}
if (length == 0) {
/* Read the length of the file only */
struct inode *inode;
inode = GET_INODE_FROM_FILEP(filp);
if (!inode) {
printk(KERN_INFO "android_readwrite_file: Error 2\n");
ret = -ENOENT;
break;
}
ret = i_size_read(inode->i_mapping->host);
break;
}
if (wbuf) {
if ((ret=filp->f_op->write(filp, wbuf, length, &filp->f_pos)) < 0) {
printk(KERN_INFO "android_readwrite_file: Error 3\n");
break;
}
} else {
if ((ret=filp->f_op->read(filp, rbuf, length, &filp->f_pos)) < 0) {
printk(KERN_INFO "android_readwrite_file: Error 4\n");
break;
}
}
} while (0);
if (!IS_ERR(filp)) {
filp_close(filp, NULL);
}
set_fs(oldfs);
printk(KERN_INFO "android_readwrite_file: ret=%d\n", ret);
return ret;
}
extern void wlan_setup_power(int on, int detect);
static int ath6kl_pm_probe(struct platform_device *pdev)
{
wlan_setup_power(1, 1);
return 0;
}
static int ath6kl_pm_remove(struct platform_device *pdev)
{
wlan_setup_power(0, 1);
return 0;
}
static int ath6kl_pm_suspend(struct platform_device *pdev, pm_message_t state)
{
return 0;
}
static inline void *ar6k_priv(struct net_device *dev)
{
return (wdev_priv(dev->ieee80211_ptr));
}
static int ath6kl_pm_resume(struct platform_device *pdev)
{
return 0;
}
static struct platform_driver ath6kl_pm_device = {
.probe = ath6kl_pm_probe,
.remove = ath6kl_pm_remove,
.suspend = ath6kl_pm_suspend,
.resume = ath6kl_pm_resume,
.driver = {
.name = "wlan_ar6000_pm_dev",
},
};
void __init ath6kl_sdio_init_c210(void)
{
platform_driver_register(&ath6kl_pm_device);
A_MDELAY(50);
}
void __exit ath6kl_sdio_exit_c210(void)
{
platform_driver_unregister(&ath6kl_pm_device);
A_MDELAY(1000);
}
#if 1 // by bbelief
int ath6kl_wait_for_init_comp(void)
{
int left;
if (atomic_read(&init_done) == 1)
return 0;
init_waitqueue_head(&init_wq);
left = wait_event_interruptible_timeout(init_wq,
atomic_read(&init_done) == 1,
ATH6KL_INIT_TIMEOUT);
if (left == 0)
printk(KERN_ERR "timeout while waiting for init operation\n");
else if (left < 0)
printk(KERN_ERR "wait for init operation failed: %d\n", left);
return 0;
}
void ath6kl_notify_init_done(void)
{
atomic_set(&init_done, 1);
wake_up(&init_wq);
}
#endif
| gpl-2.0 |
cattleprod/for-sense | drivers/mtd/onenand/omap2.c | 203 | 21146 | /*
* linux/drivers/mtd/onenand/omap2.c
*
* OneNAND driver for OMAP2 / OMAP3
*
* Copyright © 2005-2006 Nokia Corporation
*
* Author: Jarkko Lavinen <jarkko.lavinen@nokia.com> and Juha Yrjölä
* IRQ and DMA support written by Timo Teras
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; see the file COPYING. If not, write to the Free Software
* Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include <linux/device.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/onenand.h>
#include <linux/mtd/partitions.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <asm/mach/flash.h>
#include <plat/gpmc.h>
#include <plat/onenand.h>
#include <mach/gpio.h>
#include <plat/dma.h>
#include <plat/board.h>
#define DRIVER_NAME "omap2-onenand"
#define ONENAND_IO_SIZE SZ_128K
#define ONENAND_BUFRAM_SIZE (1024 * 5)
struct omap2_onenand {
struct platform_device *pdev;
int gpmc_cs;
unsigned long phys_base;
int gpio_irq;
struct mtd_info mtd;
struct mtd_partition *parts;
struct onenand_chip onenand;
struct completion irq_done;
struct completion dma_done;
int dma_channel;
int freq;
int (*setup)(void __iomem *base, int freq);
};
static void omap2_onenand_dma_cb(int lch, u16 ch_status, void *data)
{
struct omap2_onenand *c = data;
complete(&c->dma_done);
}
static irqreturn_t omap2_onenand_interrupt(int irq, void *dev_id)
{
struct omap2_onenand *c = dev_id;
complete(&c->irq_done);
return IRQ_HANDLED;
}
static inline unsigned short read_reg(struct omap2_onenand *c, int reg)
{
return readw(c->onenand.base + reg);
}
static inline void write_reg(struct omap2_onenand *c, unsigned short value,
int reg)
{
writew(value, c->onenand.base + reg);
}
static void wait_err(char *msg, int state, unsigned int ctrl, unsigned int intr)
{
printk(KERN_ERR "onenand_wait: %s! state %d ctrl 0x%04x intr 0x%04x\n",
msg, state, ctrl, intr);
}
static void wait_warn(char *msg, int state, unsigned int ctrl,
unsigned int intr)
{
printk(KERN_WARNING "onenand_wait: %s! state %d ctrl 0x%04x "
"intr 0x%04x\n", msg, state, ctrl, intr);
}
static int omap2_onenand_wait(struct mtd_info *mtd, int state)
{
struct omap2_onenand *c = container_of(mtd, struct omap2_onenand, mtd);
unsigned int intr = 0;
unsigned int ctrl;
unsigned long timeout;
u32 syscfg;
if (state == FL_RESETING || state == FL_PREPARING_ERASE ||
state == FL_VERIFYING_ERASE) {
int i = 21;
unsigned int intr_flags = ONENAND_INT_MASTER;
switch (state) {
case FL_RESETING:
intr_flags |= ONENAND_INT_RESET;
break;
case FL_PREPARING_ERASE:
intr_flags |= ONENAND_INT_ERASE;
break;
case FL_VERIFYING_ERASE:
i = 101;
break;
}
while (--i) {
udelay(1);
intr = read_reg(c, ONENAND_REG_INTERRUPT);
if (intr & ONENAND_INT_MASTER)
break;
}
ctrl = read_reg(c, ONENAND_REG_CTRL_STATUS);
if (ctrl & ONENAND_CTRL_ERROR) {
wait_err("controller error", state, ctrl, intr);
return -EIO;
}
if ((intr & intr_flags) != intr_flags) {
wait_err("timeout", state, ctrl, intr);
return -EIO;
}
return 0;
}
if (state != FL_READING) {
int result;
/* Turn interrupts on */
syscfg = read_reg(c, ONENAND_REG_SYS_CFG1);
if (!(syscfg & ONENAND_SYS_CFG1_IOBE)) {
syscfg |= ONENAND_SYS_CFG1_IOBE;
write_reg(c, syscfg, ONENAND_REG_SYS_CFG1);
if (cpu_is_omap34xx())
/* Add a delay to let GPIO settle */
syscfg = read_reg(c, ONENAND_REG_SYS_CFG1);
}
INIT_COMPLETION(c->irq_done);
if (c->gpio_irq) {
result = gpio_get_value(c->gpio_irq);
if (result == -1) {
ctrl = read_reg(c, ONENAND_REG_CTRL_STATUS);
intr = read_reg(c, ONENAND_REG_INTERRUPT);
wait_err("gpio error", state, ctrl, intr);
return -EIO;
}
} else
result = 0;
if (result == 0) {
int retry_cnt = 0;
retry:
result = wait_for_completion_timeout(&c->irq_done,
msecs_to_jiffies(20));
if (result == 0) {
/* Timeout after 20ms */
ctrl = read_reg(c, ONENAND_REG_CTRL_STATUS);
if (ctrl & ONENAND_CTRL_ONGO) {
/*
* The operation seems to be still going
* so give it some more time.
*/
retry_cnt += 1;
if (retry_cnt < 3)
goto retry;
intr = read_reg(c,
ONENAND_REG_INTERRUPT);
wait_err("timeout", state, ctrl, intr);
return -EIO;
}
intr = read_reg(c, ONENAND_REG_INTERRUPT);
if ((intr & ONENAND_INT_MASTER) == 0)
wait_warn("timeout", state, ctrl, intr);
}
}
} else {
int retry_cnt = 0;
/* Turn interrupts off */
syscfg = read_reg(c, ONENAND_REG_SYS_CFG1);
syscfg &= ~ONENAND_SYS_CFG1_IOBE;
write_reg(c, syscfg, ONENAND_REG_SYS_CFG1);
timeout = jiffies + msecs_to_jiffies(20);
while (1) {
if (time_before(jiffies, timeout)) {
intr = read_reg(c, ONENAND_REG_INTERRUPT);
if (intr & ONENAND_INT_MASTER)
break;
} else {
/* Timeout after 20ms */
ctrl = read_reg(c, ONENAND_REG_CTRL_STATUS);
if (ctrl & ONENAND_CTRL_ONGO) {
/*
* The operation seems to be still going
* so give it some more time.
*/
retry_cnt += 1;
if (retry_cnt < 3) {
timeout = jiffies +
msecs_to_jiffies(20);
continue;
}
}
break;
}
}
}
intr = read_reg(c, ONENAND_REG_INTERRUPT);
ctrl = read_reg(c, ONENAND_REG_CTRL_STATUS);
if (intr & ONENAND_INT_READ) {
int ecc = read_reg(c, ONENAND_REG_ECC_STATUS);
if (ecc) {
unsigned int addr1, addr8;
addr1 = read_reg(c, ONENAND_REG_START_ADDRESS1);
addr8 = read_reg(c, ONENAND_REG_START_ADDRESS8);
if (ecc & ONENAND_ECC_2BIT_ALL) {
printk(KERN_ERR "onenand_wait: ECC error = "
"0x%04x, addr1 %#x, addr8 %#x\n",
ecc, addr1, addr8);
mtd->ecc_stats.failed++;
return -EBADMSG;
} else if (ecc & ONENAND_ECC_1BIT_ALL) {
printk(KERN_NOTICE "onenand_wait: correctable "
"ECC error = 0x%04x, addr1 %#x, "
"addr8 %#x\n", ecc, addr1, addr8);
mtd->ecc_stats.corrected++;
}
}
} else if (state == FL_READING) {
wait_err("timeout", state, ctrl, intr);
return -EIO;
}
if (ctrl & ONENAND_CTRL_ERROR) {
wait_err("controller error", state, ctrl, intr);
if (ctrl & ONENAND_CTRL_LOCK)
printk(KERN_ERR "onenand_wait: "
"Device is write protected!!!\n");
return -EIO;
}
if (ctrl & 0xFE9F)
wait_warn("unexpected controller status", state, ctrl, intr);
return 0;
}
static inline int omap2_onenand_bufferram_offset(struct mtd_info *mtd, int area)
{
struct onenand_chip *this = mtd->priv;
if (ONENAND_CURRENT_BUFFERRAM(this)) {
if (area == ONENAND_DATARAM)
return this->writesize;
if (area == ONENAND_SPARERAM)
return mtd->oobsize;
}
return 0;
}
#if defined(CONFIG_ARCH_OMAP3) || defined(MULTI_OMAP2)
static int omap3_onenand_read_bufferram(struct mtd_info *mtd, int area,
unsigned char *buffer, int offset,
size_t count)
{
struct omap2_onenand *c = container_of(mtd, struct omap2_onenand, mtd);
struct onenand_chip *this = mtd->priv;
dma_addr_t dma_src, dma_dst;
int bram_offset;
unsigned long timeout;
void *buf = (void *)buffer;
size_t xtra;
volatile unsigned *done;
bram_offset = omap2_onenand_bufferram_offset(mtd, area) + area + offset;
if (bram_offset & 3 || (size_t)buf & 3 || count < 384)
goto out_copy;
/* panic_write() may be in an interrupt context */
if (in_interrupt() || oops_in_progress)
goto out_copy;
if (buf >= high_memory) {
struct page *p1;
if (((size_t)buf & PAGE_MASK) !=
((size_t)(buf + count - 1) & PAGE_MASK))
goto out_copy;
p1 = vmalloc_to_page(buf);
if (!p1)
goto out_copy;
buf = page_address(p1) + ((size_t)buf & ~PAGE_MASK);
}
xtra = count & 3;
if (xtra) {
count -= xtra;
memcpy(buf + count, this->base + bram_offset + count, xtra);
}
dma_src = c->phys_base + bram_offset;
dma_dst = dma_map_single(&c->pdev->dev, buf, count, DMA_FROM_DEVICE);
if (dma_mapping_error(&c->pdev->dev, dma_dst)) {
dev_err(&c->pdev->dev,
"Couldn't DMA map a %d byte buffer\n",
count);
goto out_copy;
}
omap_set_dma_transfer_params(c->dma_channel, OMAP_DMA_DATA_TYPE_S32,
count >> 2, 1, 0, 0, 0);
omap_set_dma_src_params(c->dma_channel, 0, OMAP_DMA_AMODE_POST_INC,
dma_src, 0, 0);
omap_set_dma_dest_params(c->dma_channel, 0, OMAP_DMA_AMODE_POST_INC,
dma_dst, 0, 0);
INIT_COMPLETION(c->dma_done);
omap_start_dma(c->dma_channel);
timeout = jiffies + msecs_to_jiffies(20);
done = &c->dma_done.done;
while (time_before(jiffies, timeout))
if (*done)
break;
dma_unmap_single(&c->pdev->dev, dma_dst, count, DMA_FROM_DEVICE);
if (!*done) {
dev_err(&c->pdev->dev, "timeout waiting for DMA\n");
goto out_copy;
}
return 0;
out_copy:
memcpy(buf, this->base + bram_offset, count);
return 0;
}
static int omap3_onenand_write_bufferram(struct mtd_info *mtd, int area,
const unsigned char *buffer,
int offset, size_t count)
{
struct omap2_onenand *c = container_of(mtd, struct omap2_onenand, mtd);
struct onenand_chip *this = mtd->priv;
dma_addr_t dma_src, dma_dst;
int bram_offset;
unsigned long timeout;
void *buf = (void *)buffer;
volatile unsigned *done;
bram_offset = omap2_onenand_bufferram_offset(mtd, area) + area + offset;
if (bram_offset & 3 || (size_t)buf & 3 || count < 384)
goto out_copy;
/* panic_write() may be in an interrupt context */
if (in_interrupt() || oops_in_progress)
goto out_copy;
if (buf >= high_memory) {
struct page *p1;
if (((size_t)buf & PAGE_MASK) !=
((size_t)(buf + count - 1) & PAGE_MASK))
goto out_copy;
p1 = vmalloc_to_page(buf);
if (!p1)
goto out_copy;
buf = page_address(p1) + ((size_t)buf & ~PAGE_MASK);
}
dma_src = dma_map_single(&c->pdev->dev, buf, count, DMA_TO_DEVICE);
dma_dst = c->phys_base + bram_offset;
if (dma_mapping_error(&c->pdev->dev, dma_src)) {
dev_err(&c->pdev->dev,
"Couldn't DMA map a %d byte buffer\n",
count);
return -1;
}
omap_set_dma_transfer_params(c->dma_channel, OMAP_DMA_DATA_TYPE_S32,
count >> 2, 1, 0, 0, 0);
omap_set_dma_src_params(c->dma_channel, 0, OMAP_DMA_AMODE_POST_INC,
dma_src, 0, 0);
omap_set_dma_dest_params(c->dma_channel, 0, OMAP_DMA_AMODE_POST_INC,
dma_dst, 0, 0);
INIT_COMPLETION(c->dma_done);
omap_start_dma(c->dma_channel);
timeout = jiffies + msecs_to_jiffies(20);
done = &c->dma_done.done;
while (time_before(jiffies, timeout))
if (*done)
break;
dma_unmap_single(&c->pdev->dev, dma_src, count, DMA_TO_DEVICE);
if (!*done) {
dev_err(&c->pdev->dev, "timeout waiting for DMA\n");
goto out_copy;
}
return 0;
out_copy:
memcpy(this->base + bram_offset, buf, count);
return 0;
}
#else
int omap3_onenand_read_bufferram(struct mtd_info *mtd, int area,
unsigned char *buffer, int offset,
size_t count);
int omap3_onenand_write_bufferram(struct mtd_info *mtd, int area,
const unsigned char *buffer,
int offset, size_t count);
#endif
#if defined(CONFIG_ARCH_OMAP2) || defined(MULTI_OMAP2)
static int omap2_onenand_read_bufferram(struct mtd_info *mtd, int area,
unsigned char *buffer, int offset,
size_t count)
{
struct omap2_onenand *c = container_of(mtd, struct omap2_onenand, mtd);
struct onenand_chip *this = mtd->priv;
dma_addr_t dma_src, dma_dst;
int bram_offset;
bram_offset = omap2_onenand_bufferram_offset(mtd, area) + area + offset;
/* DMA is not used. Revisit PM requirements before enabling it. */
if (1 || (c->dma_channel < 0) ||
((void *) buffer >= (void *) high_memory) || (bram_offset & 3) ||
(((unsigned int) buffer) & 3) || (count < 1024) || (count & 3)) {
memcpy(buffer, (__force void *)(this->base + bram_offset),
count);
return 0;
}
dma_src = c->phys_base + bram_offset;
dma_dst = dma_map_single(&c->pdev->dev, buffer, count,
DMA_FROM_DEVICE);
if (dma_mapping_error(&c->pdev->dev, dma_dst)) {
dev_err(&c->pdev->dev,
"Couldn't DMA map a %d byte buffer\n",
count);
return -1;
}
omap_set_dma_transfer_params(c->dma_channel, OMAP_DMA_DATA_TYPE_S32,
count / 4, 1, 0, 0, 0);
omap_set_dma_src_params(c->dma_channel, 0, OMAP_DMA_AMODE_POST_INC,
dma_src, 0, 0);
omap_set_dma_dest_params(c->dma_channel, 0, OMAP_DMA_AMODE_POST_INC,
dma_dst, 0, 0);
INIT_COMPLETION(c->dma_done);
omap_start_dma(c->dma_channel);
wait_for_completion(&c->dma_done);
dma_unmap_single(&c->pdev->dev, dma_dst, count, DMA_FROM_DEVICE);
return 0;
}
static int omap2_onenand_write_bufferram(struct mtd_info *mtd, int area,
const unsigned char *buffer,
int offset, size_t count)
{
struct omap2_onenand *c = container_of(mtd, struct omap2_onenand, mtd);
struct onenand_chip *this = mtd->priv;
dma_addr_t dma_src, dma_dst;
int bram_offset;
bram_offset = omap2_onenand_bufferram_offset(mtd, area) + area + offset;
/* DMA is not used. Revisit PM requirements before enabling it. */
if (1 || (c->dma_channel < 0) ||
((void *) buffer >= (void *) high_memory) || (bram_offset & 3) ||
(((unsigned int) buffer) & 3) || (count < 1024) || (count & 3)) {
memcpy((__force void *)(this->base + bram_offset), buffer,
count);
return 0;
}
dma_src = dma_map_single(&c->pdev->dev, (void *) buffer, count,
DMA_TO_DEVICE);
dma_dst = c->phys_base + bram_offset;
if (dma_mapping_error(&c->pdev->dev, dma_src)) {
dev_err(&c->pdev->dev,
"Couldn't DMA map a %d byte buffer\n",
count);
return -1;
}
omap_set_dma_transfer_params(c->dma_channel, OMAP_DMA_DATA_TYPE_S16,
count / 2, 1, 0, 0, 0);
omap_set_dma_src_params(c->dma_channel, 0, OMAP_DMA_AMODE_POST_INC,
dma_src, 0, 0);
omap_set_dma_dest_params(c->dma_channel, 0, OMAP_DMA_AMODE_POST_INC,
dma_dst, 0, 0);
INIT_COMPLETION(c->dma_done);
omap_start_dma(c->dma_channel);
wait_for_completion(&c->dma_done);
dma_unmap_single(&c->pdev->dev, dma_src, count, DMA_TO_DEVICE);
return 0;
}
#else
int omap2_onenand_read_bufferram(struct mtd_info *mtd, int area,
unsigned char *buffer, int offset,
size_t count);
int omap2_onenand_write_bufferram(struct mtd_info *mtd, int area,
const unsigned char *buffer,
int offset, size_t count);
#endif
static struct platform_driver omap2_onenand_driver;
static int __adjust_timing(struct device *dev, void *data)
{
int ret = 0;
struct omap2_onenand *c;
c = dev_get_drvdata(dev);
BUG_ON(c->setup == NULL);
/* DMA is not in use so this is all that is needed */
/* Revisit for OMAP3! */
ret = c->setup(c->onenand.base, c->freq);
return ret;
}
int omap2_onenand_rephase(void)
{
return driver_for_each_device(&omap2_onenand_driver.driver, NULL,
NULL, __adjust_timing);
}
static void omap2_onenand_shutdown(struct platform_device *pdev)
{
struct omap2_onenand *c = dev_get_drvdata(&pdev->dev);
/* With certain content in the buffer RAM, the OMAP boot ROM code
* can recognize the flash chip incorrectly. Zero it out before
* soft reset.
*/
memset((__force void *)c->onenand.base, 0, ONENAND_BUFRAM_SIZE);
}
static int __devinit omap2_onenand_probe(struct platform_device *pdev)
{
struct omap_onenand_platform_data *pdata;
struct omap2_onenand *c;
int r;
pdata = pdev->dev.platform_data;
if (pdata == NULL) {
dev_err(&pdev->dev, "platform data missing\n");
return -ENODEV;
}
c = kzalloc(sizeof(struct omap2_onenand), GFP_KERNEL);
if (!c)
return -ENOMEM;
init_completion(&c->irq_done);
init_completion(&c->dma_done);
c->gpmc_cs = pdata->cs;
c->gpio_irq = pdata->gpio_irq;
c->dma_channel = pdata->dma_channel;
if (c->dma_channel < 0) {
/* if -1, don't use DMA */
c->gpio_irq = 0;
}
r = gpmc_cs_request(c->gpmc_cs, ONENAND_IO_SIZE, &c->phys_base);
if (r < 0) {
dev_err(&pdev->dev, "Cannot request GPMC CS\n");
goto err_kfree;
}
if (request_mem_region(c->phys_base, ONENAND_IO_SIZE,
pdev->dev.driver->name) == NULL) {
dev_err(&pdev->dev, "Cannot reserve memory region at 0x%08lx, "
"size: 0x%x\n", c->phys_base, ONENAND_IO_SIZE);
r = -EBUSY;
goto err_free_cs;
}
c->onenand.base = ioremap(c->phys_base, ONENAND_IO_SIZE);
if (c->onenand.base == NULL) {
r = -ENOMEM;
goto err_release_mem_region;
}
if (pdata->onenand_setup != NULL) {
r = pdata->onenand_setup(c->onenand.base, c->freq);
if (r < 0) {
dev_err(&pdev->dev, "Onenand platform setup failed: "
"%d\n", r);
goto err_iounmap;
}
c->setup = pdata->onenand_setup;
}
if (c->gpio_irq) {
if ((r = gpio_request(c->gpio_irq, "OneNAND irq")) < 0) {
dev_err(&pdev->dev, "Failed to request GPIO%d for "
"OneNAND\n", c->gpio_irq);
goto err_iounmap;
}
gpio_direction_input(c->gpio_irq);
if ((r = request_irq(gpio_to_irq(c->gpio_irq),
omap2_onenand_interrupt, IRQF_TRIGGER_RISING,
pdev->dev.driver->name, c)) < 0)
goto err_release_gpio;
}
if (c->dma_channel >= 0) {
r = omap_request_dma(0, pdev->dev.driver->name,
omap2_onenand_dma_cb, (void *) c,
&c->dma_channel);
if (r == 0) {
omap_set_dma_write_mode(c->dma_channel,
OMAP_DMA_WRITE_NON_POSTED);
omap_set_dma_src_data_pack(c->dma_channel, 1);
omap_set_dma_src_burst_mode(c->dma_channel,
OMAP_DMA_DATA_BURST_8);
omap_set_dma_dest_data_pack(c->dma_channel, 1);
omap_set_dma_dest_burst_mode(c->dma_channel,
OMAP_DMA_DATA_BURST_8);
} else {
dev_info(&pdev->dev,
"failed to allocate DMA for OneNAND, "
"using PIO instead\n");
c->dma_channel = -1;
}
}
dev_info(&pdev->dev, "initializing on CS%d, phys base 0x%08lx, virtual "
"base %p\n", c->gpmc_cs, c->phys_base,
c->onenand.base);
c->pdev = pdev;
c->mtd.name = dev_name(&pdev->dev);
c->mtd.priv = &c->onenand;
c->mtd.owner = THIS_MODULE;
c->mtd.dev.parent = &pdev->dev;
if (c->dma_channel >= 0) {
struct onenand_chip *this = &c->onenand;
this->wait = omap2_onenand_wait;
if (cpu_is_omap34xx()) {
this->read_bufferram = omap3_onenand_read_bufferram;
this->write_bufferram = omap3_onenand_write_bufferram;
} else {
this->read_bufferram = omap2_onenand_read_bufferram;
this->write_bufferram = omap2_onenand_write_bufferram;
}
}
if ((r = onenand_scan(&c->mtd, 1)) < 0)
goto err_release_dma;
switch ((c->onenand.version_id >> 4) & 0xf) {
case 0:
c->freq = 40;
break;
case 1:
c->freq = 54;
break;
case 2:
c->freq = 66;
break;
case 3:
c->freq = 83;
break;
}
#ifdef CONFIG_MTD_PARTITIONS
if (pdata->parts != NULL)
r = add_mtd_partitions(&c->mtd, pdata->parts,
pdata->nr_parts);
else
#endif
r = add_mtd_device(&c->mtd);
if (r < 0)
goto err_release_onenand;
platform_set_drvdata(pdev, c);
return 0;
err_release_onenand:
onenand_release(&c->mtd);
err_release_dma:
if (c->dma_channel != -1)
omap_free_dma(c->dma_channel);
if (c->gpio_irq)
free_irq(gpio_to_irq(c->gpio_irq), c);
err_release_gpio:
if (c->gpio_irq)
gpio_free(c->gpio_irq);
err_iounmap:
iounmap(c->onenand.base);
err_release_mem_region:
release_mem_region(c->phys_base, ONENAND_IO_SIZE);
err_free_cs:
gpmc_cs_free(c->gpmc_cs);
err_kfree:
kfree(c);
return r;
}
static int __devexit omap2_onenand_remove(struct platform_device *pdev)
{
struct omap2_onenand *c = dev_get_drvdata(&pdev->dev);
BUG_ON(c == NULL);
#ifdef CONFIG_MTD_PARTITIONS
if (c->parts)
del_mtd_partitions(&c->mtd);
else
del_mtd_device(&c->mtd);
#else
del_mtd_device(&c->mtd);
#endif
onenand_release(&c->mtd);
if (c->dma_channel != -1)
omap_free_dma(c->dma_channel);
omap2_onenand_shutdown(pdev);
platform_set_drvdata(pdev, NULL);
if (c->gpio_irq) {
free_irq(gpio_to_irq(c->gpio_irq), c);
gpio_free(c->gpio_irq);
}
iounmap(c->onenand.base);
release_mem_region(c->phys_base, ONENAND_IO_SIZE);
gpmc_cs_free(c->gpmc_cs);
kfree(c);
return 0;
}
static struct platform_driver omap2_onenand_driver = {
.probe = omap2_onenand_probe,
.remove = __devexit_p(omap2_onenand_remove),
.shutdown = omap2_onenand_shutdown,
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
},
};
static int __init omap2_onenand_init(void)
{
printk(KERN_INFO "OneNAND driver initializing\n");
return platform_driver_register(&omap2_onenand_driver);
}
static void __exit omap2_onenand_exit(void)
{
platform_driver_unregister(&omap2_onenand_driver);
}
module_init(omap2_onenand_init);
module_exit(omap2_onenand_exit);
MODULE_ALIAS("platform:" DRIVER_NAME);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jarkko Lavinen <jarkko.lavinen@nokia.com>");
MODULE_DESCRIPTION("Glue layer for OneNAND flash on OMAP2 / OMAP3");
| gpl-2.0 |
szezso/T.E.S.C.O-kernel_vivo | drivers/virtio/virtio_ring.c | 459 | 15637 | /* Virtio ring implementation.
*
* Copyright 2007 Rusty Russell IBM Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/virtio.h>
#include <linux/virtio_ring.h>
#include <linux/virtio_config.h>
#include <linux/device.h>
#include <linux/slab.h>
/* virtio guest is communicating with a virtual "device" that actually runs on
* a host processor. Memory barriers are used to control SMP effects. */
#ifdef CONFIG_SMP
/* Where possible, use SMP barriers which are more lightweight than mandatory
* barriers, because mandatory barriers control MMIO effects on accesses
* through relaxed memory I/O windows (which virtio does not use). */
#define virtio_mb() smp_mb()
#define virtio_rmb() smp_rmb()
#define virtio_wmb() smp_wmb()
#else
/* We must force memory ordering even if guest is UP since host could be
* running on another CPU, but SMP barriers are defined to barrier() in that
* configuration. So fall back to mandatory barriers instead. */
#define virtio_mb() mb()
#define virtio_rmb() rmb()
#define virtio_wmb() wmb()
#endif
#ifdef DEBUG
/* For development, we want to crash whenever the ring is screwed. */
#define BAD_RING(_vq, fmt, args...) \
do { \
dev_err(&(_vq)->vq.vdev->dev, \
"%s:"fmt, (_vq)->vq.name, ##args); \
BUG(); \
} while (0)
/* Caller is supposed to guarantee no reentry. */
#define START_USE(_vq) \
do { \
if ((_vq)->in_use) \
panic("%s:in_use = %i\n", \
(_vq)->vq.name, (_vq)->in_use); \
(_vq)->in_use = __LINE__; \
} while (0)
#define END_USE(_vq) \
do { BUG_ON(!(_vq)->in_use); (_vq)->in_use = 0; } while(0)
#else
#define BAD_RING(_vq, fmt, args...) \
do { \
dev_err(&_vq->vq.vdev->dev, \
"%s:"fmt, (_vq)->vq.name, ##args); \
(_vq)->broken = true; \
} while (0)
#define START_USE(vq)
#define END_USE(vq)
#endif
struct vring_virtqueue
{
struct virtqueue vq;
/* Actual memory layout for this queue */
struct vring vring;
/* Other side has made a mess, don't try any more. */
bool broken;
/* Host supports indirect buffers */
bool indirect;
/* Host publishes avail event idx */
bool event;
/* Number of free buffers */
unsigned int num_free;
/* Head of free buffer list. */
unsigned int free_head;
/* Number we've added since last sync. */
unsigned int num_added;
/* Last used index we've seen. */
u16 last_used_idx;
/* How to notify other side. FIXME: commonalize hcalls! */
void (*notify)(struct virtqueue *vq);
#ifdef DEBUG
/* They're supposed to lock for us. */
unsigned int in_use;
#endif
/* Tokens for callbacks. */
void *data[];
};
#define to_vvq(_vq) container_of(_vq, struct vring_virtqueue, vq)
/* Set up an indirect table of descriptors and add it to the queue. */
static int vring_add_indirect(struct vring_virtqueue *vq,
struct scatterlist sg[],
unsigned int out,
unsigned int in,
gfp_t gfp)
{
struct vring_desc *desc;
unsigned head;
int i;
/*
* We require lowmem mappings for the descriptors because
* otherwise virt_to_phys will give us bogus addresses in the
* virtqueue.
*/
gfp &= ~(__GFP_HIGHMEM | __GFP_HIGH);
desc = kmalloc((out + in) * sizeof(struct vring_desc), gfp);
if (!desc)
return -ENOMEM;
/* Transfer entries from the sg list into the indirect page */
for (i = 0; i < out; i++) {
desc[i].flags = VRING_DESC_F_NEXT;
desc[i].addr = sg_phys(sg);
desc[i].len = sg->length;
desc[i].next = i+1;
sg++;
}
for (; i < (out + in); i++) {
desc[i].flags = VRING_DESC_F_NEXT|VRING_DESC_F_WRITE;
desc[i].addr = sg_phys(sg);
desc[i].len = sg->length;
desc[i].next = i+1;
sg++;
}
/* Last one doesn't continue. */
desc[i-1].flags &= ~VRING_DESC_F_NEXT;
desc[i-1].next = 0;
/* We're about to use a buffer */
vq->num_free--;
/* Use a single buffer which doesn't continue */
head = vq->free_head;
vq->vring.desc[head].flags = VRING_DESC_F_INDIRECT;
vq->vring.desc[head].addr = virt_to_phys(desc);
vq->vring.desc[head].len = i * sizeof(struct vring_desc);
/* Update free pointer */
vq->free_head = vq->vring.desc[head].next;
return head;
}
int virtqueue_add_buf_gfp(struct virtqueue *_vq,
struct scatterlist sg[],
unsigned int out,
unsigned int in,
void *data,
gfp_t gfp)
{
struct vring_virtqueue *vq = to_vvq(_vq);
unsigned int i, avail, uninitialized_var(prev);
int head;
START_USE(vq);
BUG_ON(data == NULL);
/* If the host supports indirect descriptor tables, and we have multiple
* buffers, then go indirect. FIXME: tune this threshold */
if (vq->indirect && (out + in) > 1 && vq->num_free) {
head = vring_add_indirect(vq, sg, out, in, gfp);
if (likely(head >= 0))
goto add_head;
}
BUG_ON(out + in > vq->vring.num);
BUG_ON(out + in == 0);
if (vq->num_free < out + in) {
pr_debug("Can't add buf len %i - avail = %i\n",
out + in, vq->num_free);
/* FIXME: for historical reasons, we force a notify here if
* there are outgoing parts to the buffer. Presumably the
* host should service the ring ASAP. */
if (out)
vq->notify(&vq->vq);
END_USE(vq);
return -ENOSPC;
}
/* We're about to use some buffers from the free list. */
vq->num_free -= out + in;
head = vq->free_head;
for (i = vq->free_head; out; i = vq->vring.desc[i].next, out--) {
vq->vring.desc[i].flags = VRING_DESC_F_NEXT;
vq->vring.desc[i].addr = sg_phys(sg);
vq->vring.desc[i].len = sg->length;
prev = i;
sg++;
}
for (; in; i = vq->vring.desc[i].next, in--) {
vq->vring.desc[i].flags = VRING_DESC_F_NEXT|VRING_DESC_F_WRITE;
vq->vring.desc[i].addr = sg_phys(sg);
vq->vring.desc[i].len = sg->length;
prev = i;
sg++;
}
/* Last one doesn't continue. */
vq->vring.desc[prev].flags &= ~VRING_DESC_F_NEXT;
/* Update free pointer */
vq->free_head = i;
add_head:
/* Set token. */
vq->data[head] = data;
/* Put entry in available array (but don't update avail->idx until they
* do sync). FIXME: avoid modulus here? */
avail = (vq->vring.avail->idx + vq->num_added++) % vq->vring.num;
vq->vring.avail->ring[avail] = head;
pr_debug("Added buffer head %i to %p\n", head, vq);
END_USE(vq);
return vq->num_free;
}
EXPORT_SYMBOL_GPL(virtqueue_add_buf_gfp);
void virtqueue_kick(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
u16 new, old;
START_USE(vq);
/* Descriptors and available array need to be set before we expose the
* new available array entries. */
virtio_wmb();
old = vq->vring.avail->idx;
new = vq->vring.avail->idx = old + vq->num_added;
vq->num_added = 0;
/* Need to update avail index before checking if we should notify */
virtio_mb();
if (vq->event ?
vring_need_event(vring_avail_event(&vq->vring), new, old) :
!(vq->vring.used->flags & VRING_USED_F_NO_NOTIFY))
/* Prod other side to tell it about changes. */
vq->notify(&vq->vq);
END_USE(vq);
}
EXPORT_SYMBOL_GPL(virtqueue_kick);
static void detach_buf(struct vring_virtqueue *vq, unsigned int head)
{
unsigned int i;
/* Clear data ptr. */
vq->data[head] = NULL;
/* Put back on free list: find end */
i = head;
/* Free the indirect table */
if (vq->vring.desc[i].flags & VRING_DESC_F_INDIRECT)
kfree(phys_to_virt(vq->vring.desc[i].addr));
while (vq->vring.desc[i].flags & VRING_DESC_F_NEXT) {
i = vq->vring.desc[i].next;
vq->num_free++;
}
vq->vring.desc[i].next = vq->free_head;
vq->free_head = head;
/* Plus final descriptor */
vq->num_free++;
}
static inline bool more_used(const struct vring_virtqueue *vq)
{
return vq->last_used_idx != vq->vring.used->idx;
}
void *virtqueue_get_buf(struct virtqueue *_vq, unsigned int *len)
{
struct vring_virtqueue *vq = to_vvq(_vq);
void *ret;
unsigned int i;
START_USE(vq);
if (unlikely(vq->broken)) {
END_USE(vq);
return NULL;
}
if (!more_used(vq)) {
pr_debug("No more buffers in queue\n");
END_USE(vq);
return NULL;
}
/* Only get used array entries after they have been exposed by host. */
virtio_rmb();
i = vq->vring.used->ring[vq->last_used_idx%vq->vring.num].id;
*len = vq->vring.used->ring[vq->last_used_idx%vq->vring.num].len;
if (unlikely(i >= vq->vring.num)) {
BAD_RING(vq, "id %u out of range\n", i);
return NULL;
}
if (unlikely(!vq->data[i])) {
BAD_RING(vq, "id %u is not a head!\n", i);
return NULL;
}
/* detach_buf clears data, so grab it now. */
ret = vq->data[i];
detach_buf(vq, i);
vq->last_used_idx++;
/* If we expect an interrupt for the next entry, tell host
* by writing event index and flush out the write before
* the read in the next get_buf call. */
if (!(vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT)) {
vring_used_event(&vq->vring) = vq->last_used_idx;
virtio_mb();
}
END_USE(vq);
return ret;
}
EXPORT_SYMBOL_GPL(virtqueue_get_buf);
void virtqueue_disable_cb(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT;
}
EXPORT_SYMBOL_GPL(virtqueue_disable_cb);
/**
* virtqueue_enable_cb_prepare - restart callbacks after disable_cb
* @vq: the struct virtqueue we're talking about.
*
* This re-enables callbacks; it returns current queue state
* in an opaque unsigned value. This value should be later tested by
* virtqueue_poll, to detect a possible race between the driver checking for
* more work, and enabling callbacks.
*
* Caller must ensure we don't call this with other virtqueue
* operations at the same time (except where noted).
*/
unsigned virtqueue_enable_cb_prepare(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
u16 last_used_idx;
START_USE(vq);
/* We optimistically turn back on interrupts, then check if there was
* more to do. */
/* Depending on the VIRTIO_RING_F_EVENT_IDX feature, we need to
* either clear the flags bit or point the event index at the next
* entry. Always do both to keep code simple. */
vq->vring.avail->flags &= ~VRING_AVAIL_F_NO_INTERRUPT;
vring_used_event(&vq->vring) = last_used_idx = vq->last_used_idx;
END_USE(vq);
return last_used_idx;
}
EXPORT_SYMBOL_GPL(virtqueue_enable_cb_prepare);
/**
* virtqueue_poll - query pending used buffers
* @vq: the struct virtqueue we're talking about.
* @last_used_idx: virtqueue state (from call to virtqueue_enable_cb_prepare).
*
* Returns "true" if there are pending used buffers in the queue.
*
* This does not need to be serialized.
*/
bool virtqueue_poll(struct virtqueue *_vq, unsigned last_used_idx)
{
struct vring_virtqueue *vq = to_vvq(_vq);
virtio_mb();
return (u16)last_used_idx != vq->vring.used->idx;
}
EXPORT_SYMBOL_GPL(virtqueue_poll);
/**
* virtqueue_enable_cb - restart callbacks after disable_cb.
* @vq: the struct virtqueue we're talking about.
*
* This re-enables callbacks; it returns "false" if there are pending
* buffers in the queue, to detect a possible race between the driver
* checking for more work, and enabling callbacks.
*
* Caller must ensure we don't call this with other virtqueue
* operations at the same time (except where noted).
*/
bool virtqueue_enable_cb(struct virtqueue *_vq)
{
unsigned last_used_idx = virtqueue_enable_cb_prepare(_vq);
return !virtqueue_poll(_vq, last_used_idx);
}
EXPORT_SYMBOL_GPL(virtqueue_enable_cb);
bool virtqueue_enable_cb_delayed(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
u16 bufs;
START_USE(vq);
/* We optimistically turn back on interrupts, then check if there was
* more to do. */
/* Depending on the VIRTIO_RING_F_USED_EVENT_IDX feature, we need to
* either clear the flags bit or point the event index at the next
* entry. Always do both to keep code simple. */
vq->vring.avail->flags &= ~VRING_AVAIL_F_NO_INTERRUPT;
/* TODO: tune this threshold */
bufs = (u16)(vq->vring.avail->idx - vq->last_used_idx) * 3 / 4;
vring_used_event(&vq->vring) = vq->last_used_idx + bufs;
virtio_mb();
if (unlikely((u16)(vq->vring.used->idx - vq->last_used_idx) > bufs)) {
END_USE(vq);
return false;
}
END_USE(vq);
return true;
}
EXPORT_SYMBOL_GPL(virtqueue_enable_cb_delayed);
void *virtqueue_detach_unused_buf(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
unsigned int i;
void *buf;
START_USE(vq);
for (i = 0; i < vq->vring.num; i++) {
if (!vq->data[i])
continue;
/* detach_buf clears data, so grab it now. */
buf = vq->data[i];
detach_buf(vq, i);
vq->vring.avail->idx--;
END_USE(vq);
return buf;
}
/* That should have freed everything. */
BUG_ON(vq->num_free != vq->vring.num);
END_USE(vq);
return NULL;
}
EXPORT_SYMBOL_GPL(virtqueue_detach_unused_buf);
irqreturn_t vring_interrupt(int irq, void *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
if (!more_used(vq)) {
pr_debug("virtqueue interrupt with no work for %p\n", vq);
return IRQ_NONE;
}
if (unlikely(vq->broken))
return IRQ_HANDLED;
pr_debug("virtqueue callback for %p (%p)\n", vq, vq->vq.callback);
if (vq->vq.callback)
vq->vq.callback(&vq->vq);
return IRQ_HANDLED;
}
EXPORT_SYMBOL_GPL(vring_interrupt);
struct virtqueue *vring_new_virtqueue(unsigned int num,
unsigned int vring_align,
struct virtio_device *vdev,
void *pages,
void (*notify)(struct virtqueue *),
void (*callback)(struct virtqueue *),
const char *name)
{
struct vring_virtqueue *vq;
unsigned int i;
/* We assume num is a power of 2. */
if (num & (num - 1)) {
dev_warn(&vdev->dev, "Bad virtqueue length %u\n", num);
return NULL;
}
vq = kmalloc(sizeof(*vq) + sizeof(void *)*num, GFP_KERNEL);
if (!vq)
return NULL;
vring_init(&vq->vring, num, pages, vring_align);
vq->vq.callback = callback;
vq->vq.vdev = vdev;
vq->vq.name = name;
vq->notify = notify;
vq->broken = false;
vq->last_used_idx = 0;
vq->num_added = 0;
list_add_tail(&vq->vq.list, &vdev->vqs);
#ifdef DEBUG
vq->in_use = false;
#endif
vq->indirect = virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC);
vq->event = virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
/* No callback? Tell other side not to bother us. */
if (!callback)
vq->vring.avail->flags |= VRING_AVAIL_F_NO_INTERRUPT;
/* Put everything in free lists. */
vq->num_free = num;
vq->free_head = 0;
for (i = 0; i < num-1; i++) {
vq->vring.desc[i].next = i+1;
vq->data[i] = NULL;
}
vq->data[i] = NULL;
return &vq->vq;
}
EXPORT_SYMBOL_GPL(vring_new_virtqueue);
void vring_del_virtqueue(struct virtqueue *vq)
{
list_del(&vq->list);
kfree(to_vvq(vq));
}
EXPORT_SYMBOL_GPL(vring_del_virtqueue);
/* Manipulates transport-specific feature bits. */
void vring_transport_features(struct virtio_device *vdev)
{
unsigned int i;
for (i = VIRTIO_TRANSPORT_F_START; i < VIRTIO_TRANSPORT_F_END; i++) {
switch (i) {
case VIRTIO_RING_F_INDIRECT_DESC:
break;
case VIRTIO_RING_F_EVENT_IDX:
break;
default:
/* We don't understand this bit. */
clear_bit(i, vdev->features);
}
}
}
EXPORT_SYMBOL_GPL(vring_transport_features);
MODULE_LICENSE("GPL");
| gpl-2.0 |
b00tbu9/CM7.2_Phoenix_CyanogenMode | security/selinux/nlmsgtab.c | 459 | 6452 | /*
* Netlink message type permission tables, for user generated messages.
*
* Author: James Morris <jmorris@redhat.com>
*
* Copyright (C) 2004 Red Hat, Inc., James Morris <jmorris@redhat.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/types.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/if.h>
#include <linux/netfilter_ipv4/ip_queue.h>
#include <linux/inet_diag.h>
#include <linux/xfrm.h>
#include <linux/audit.h>
#include "flask.h"
#include "av_permissions.h"
struct nlmsg_perm {
u16 nlmsg_type;
u32 perm;
};
static struct nlmsg_perm nlmsg_route_perms[] =
{
{ RTM_NEWLINK, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_DELLINK, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_GETLINK, NETLINK_ROUTE_SOCKET__NLMSG_READ },
{ RTM_SETLINK, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_NEWADDR, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_DELADDR, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_GETADDR, NETLINK_ROUTE_SOCKET__NLMSG_READ },
{ RTM_NEWROUTE, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_DELROUTE, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_GETROUTE, NETLINK_ROUTE_SOCKET__NLMSG_READ },
{ RTM_NEWNEIGH, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_DELNEIGH, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_GETNEIGH, NETLINK_ROUTE_SOCKET__NLMSG_READ },
{ RTM_NEWRULE, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_DELRULE, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_GETRULE, NETLINK_ROUTE_SOCKET__NLMSG_READ },
{ RTM_NEWQDISC, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_DELQDISC, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_GETQDISC, NETLINK_ROUTE_SOCKET__NLMSG_READ },
{ RTM_NEWTCLASS, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_DELTCLASS, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_GETTCLASS, NETLINK_ROUTE_SOCKET__NLMSG_READ },
{ RTM_NEWTFILTER, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_DELTFILTER, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_GETTFILTER, NETLINK_ROUTE_SOCKET__NLMSG_READ },
{ RTM_NEWACTION, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_DELACTION, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_GETACTION, NETLINK_ROUTE_SOCKET__NLMSG_READ },
{ RTM_NEWPREFIX, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_GETMULTICAST, NETLINK_ROUTE_SOCKET__NLMSG_READ },
{ RTM_GETANYCAST, NETLINK_ROUTE_SOCKET__NLMSG_READ },
{ RTM_GETNEIGHTBL, NETLINK_ROUTE_SOCKET__NLMSG_READ },
{ RTM_SETNEIGHTBL, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_NEWADDRLABEL, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_DELADDRLABEL, NETLINK_ROUTE_SOCKET__NLMSG_WRITE },
{ RTM_GETADDRLABEL, NETLINK_ROUTE_SOCKET__NLMSG_READ },
};
static struct nlmsg_perm nlmsg_firewall_perms[] =
{
{ IPQM_MODE, NETLINK_FIREWALL_SOCKET__NLMSG_WRITE },
{ IPQM_VERDICT, NETLINK_FIREWALL_SOCKET__NLMSG_WRITE },
};
static struct nlmsg_perm nlmsg_tcpdiag_perms[] =
{
{ TCPDIAG_GETSOCK, NETLINK_TCPDIAG_SOCKET__NLMSG_READ },
{ DCCPDIAG_GETSOCK, NETLINK_TCPDIAG_SOCKET__NLMSG_READ },
};
static struct nlmsg_perm nlmsg_xfrm_perms[] =
{
{ XFRM_MSG_NEWSA, NETLINK_XFRM_SOCKET__NLMSG_WRITE },
{ XFRM_MSG_DELSA, NETLINK_XFRM_SOCKET__NLMSG_WRITE },
{ XFRM_MSG_GETSA, NETLINK_XFRM_SOCKET__NLMSG_READ },
{ XFRM_MSG_NEWPOLICY, NETLINK_XFRM_SOCKET__NLMSG_WRITE },
{ XFRM_MSG_DELPOLICY, NETLINK_XFRM_SOCKET__NLMSG_WRITE },
{ XFRM_MSG_GETPOLICY, NETLINK_XFRM_SOCKET__NLMSG_READ },
{ XFRM_MSG_ALLOCSPI, NETLINK_XFRM_SOCKET__NLMSG_WRITE },
{ XFRM_MSG_ACQUIRE, NETLINK_XFRM_SOCKET__NLMSG_WRITE },
{ XFRM_MSG_EXPIRE, NETLINK_XFRM_SOCKET__NLMSG_WRITE },
{ XFRM_MSG_UPDPOLICY, NETLINK_XFRM_SOCKET__NLMSG_WRITE },
{ XFRM_MSG_UPDSA, NETLINK_XFRM_SOCKET__NLMSG_WRITE },
{ XFRM_MSG_POLEXPIRE, NETLINK_XFRM_SOCKET__NLMSG_WRITE },
{ XFRM_MSG_FLUSHSA, NETLINK_XFRM_SOCKET__NLMSG_WRITE },
{ XFRM_MSG_FLUSHPOLICY, NETLINK_XFRM_SOCKET__NLMSG_WRITE },
{ XFRM_MSG_NEWAE, NETLINK_XFRM_SOCKET__NLMSG_WRITE },
{ XFRM_MSG_GETAE, NETLINK_XFRM_SOCKET__NLMSG_READ },
};
static struct nlmsg_perm nlmsg_audit_perms[] =
{
{ AUDIT_GET, NETLINK_AUDIT_SOCKET__NLMSG_READ },
{ AUDIT_SET, NETLINK_AUDIT_SOCKET__NLMSG_WRITE },
{ AUDIT_LIST, NETLINK_AUDIT_SOCKET__NLMSG_READPRIV },
{ AUDIT_ADD, NETLINK_AUDIT_SOCKET__NLMSG_WRITE },
{ AUDIT_DEL, NETLINK_AUDIT_SOCKET__NLMSG_WRITE },
{ AUDIT_LIST_RULES, NETLINK_AUDIT_SOCKET__NLMSG_READPRIV },
{ AUDIT_ADD_RULE, NETLINK_AUDIT_SOCKET__NLMSG_WRITE },
{ AUDIT_DEL_RULE, NETLINK_AUDIT_SOCKET__NLMSG_WRITE },
{ AUDIT_USER, NETLINK_AUDIT_SOCKET__NLMSG_RELAY },
{ AUDIT_SIGNAL_INFO, NETLINK_AUDIT_SOCKET__NLMSG_READ },
{ AUDIT_TRIM, NETLINK_AUDIT_SOCKET__NLMSG_WRITE },
{ AUDIT_MAKE_EQUIV, NETLINK_AUDIT_SOCKET__NLMSG_WRITE },
{ AUDIT_TTY_GET, NETLINK_AUDIT_SOCKET__NLMSG_READ },
{ AUDIT_TTY_SET, NETLINK_AUDIT_SOCKET__NLMSG_TTY_AUDIT },
};
static int nlmsg_perm(u16 nlmsg_type, u32 *perm, struct nlmsg_perm *tab, size_t tabsize)
{
int i, err = -EINVAL;
for (i = 0; i < tabsize/sizeof(struct nlmsg_perm); i++)
if (nlmsg_type == tab[i].nlmsg_type) {
*perm = tab[i].perm;
err = 0;
break;
}
return err;
}
int selinux_nlmsg_lookup(u16 sclass, u16 nlmsg_type, u32 *perm)
{
int err = 0;
switch (sclass) {
case SECCLASS_NETLINK_ROUTE_SOCKET:
err = nlmsg_perm(nlmsg_type, perm, nlmsg_route_perms,
sizeof(nlmsg_route_perms));
break;
case SECCLASS_NETLINK_FIREWALL_SOCKET:
case SECCLASS_NETLINK_IP6FW_SOCKET:
err = nlmsg_perm(nlmsg_type, perm, nlmsg_firewall_perms,
sizeof(nlmsg_firewall_perms));
break;
case SECCLASS_NETLINK_TCPDIAG_SOCKET:
err = nlmsg_perm(nlmsg_type, perm, nlmsg_tcpdiag_perms,
sizeof(nlmsg_tcpdiag_perms));
break;
case SECCLASS_NETLINK_XFRM_SOCKET:
err = nlmsg_perm(nlmsg_type, perm, nlmsg_xfrm_perms,
sizeof(nlmsg_xfrm_perms));
break;
case SECCLASS_NETLINK_AUDIT_SOCKET:
if ((nlmsg_type >= AUDIT_FIRST_USER_MSG &&
nlmsg_type <= AUDIT_LAST_USER_MSG) ||
(nlmsg_type >= AUDIT_FIRST_USER_MSG2 &&
nlmsg_type <= AUDIT_LAST_USER_MSG2)) {
*perm = NETLINK_AUDIT_SOCKET__NLMSG_RELAY;
} else {
err = nlmsg_perm(nlmsg_type, perm, nlmsg_audit_perms,
sizeof(nlmsg_audit_perms));
}
break;
/* No messaging from userspace, or class unknown/unhandled */
default:
err = -ENOENT;
break;
}
return err;
}
| gpl-2.0 |
darshan1205/yu_kernel | drivers/staging/android/ion/compat_ion.c | 971 | 4810 | /*
* drivers/gpu/ion/compat_ion.c
*
* Copyright (C) 2013 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/compat.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include "ion.h"
#include "compat_ion.h"
/* See drivers/staging/android/uapi/ion.h for the definition of these structs */
struct compat_ion_allocation_data {
compat_size_t len;
compat_size_t align;
compat_uint_t heap_id_mask;
compat_uint_t flags;
compat_int_t handle;
};
struct compat_ion_custom_data {
compat_uint_t cmd;
compat_ulong_t arg;
};
struct compat_ion_handle_data {
compat_int_t handle;
};
#define COMPAT_ION_IOC_ALLOC _IOWR(ION_IOC_MAGIC, 0, \
struct compat_ion_allocation_data)
#define COMPAT_ION_IOC_FREE _IOWR(ION_IOC_MAGIC, 1, \
struct compat_ion_handle_data)
#define COMPAT_ION_IOC_CUSTOM _IOWR(ION_IOC_MAGIC, 6, \
struct compat_ion_custom_data)
static int compat_get_ion_allocation_data(
struct compat_ion_allocation_data __user *data32,
struct ion_allocation_data __user *data)
{
compat_size_t s;
compat_uint_t u;
compat_int_t i;
int err;
err = get_user(s, &data32->len);
err |= put_user(s, &data->len);
err |= get_user(s, &data32->align);
err |= put_user(s, &data->align);
err |= get_user(u, &data32->heap_id_mask);
err |= put_user(u, &data->heap_id_mask);
err |= get_user(u, &data32->flags);
err |= put_user(u, &data->flags);
err |= get_user(i, &data32->handle);
err |= put_user(i, &data->handle);
return err;
}
static int compat_get_ion_handle_data(
struct compat_ion_handle_data __user *data32,
struct ion_handle_data __user *data)
{
compat_int_t i;
int err;
err = get_user(i, &data32->handle);
err |= put_user(i, &data->handle);
return err;
}
static int compat_put_ion_allocation_data(
struct compat_ion_allocation_data __user *data32,
struct ion_allocation_data __user *data)
{
compat_size_t s;
compat_uint_t u;
compat_int_t i;
int err;
err = get_user(s, &data->len);
err |= put_user(s, &data32->len);
err |= get_user(s, &data->align);
err |= put_user(s, &data32->align);
err |= get_user(u, &data->heap_id_mask);
err |= put_user(u, &data32->heap_id_mask);
err |= get_user(u, &data->flags);
err |= put_user(u, &data32->flags);
err |= get_user(i, &data->handle);
err |= put_user(i, &data32->handle);
return err;
}
static int compat_get_ion_custom_data(
struct compat_ion_custom_data __user *data32,
struct ion_custom_data __user *data)
{
compat_uint_t cmd;
compat_ulong_t arg;
int err;
err = get_user(cmd, &data32->cmd);
err |= put_user(cmd, &data->cmd);
err |= get_user(arg, &data32->arg);
err |= put_user(arg, &data->arg);
return err;
};
long compat_ion_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
long ret;
if (!filp->f_op || !filp->f_op->unlocked_ioctl)
return -ENOTTY;
switch (cmd) {
case COMPAT_ION_IOC_ALLOC:
{
struct compat_ion_allocation_data __user *data32;
struct ion_allocation_data __user *data;
int err;
data32 = compat_ptr(arg);
data = compat_alloc_user_space(sizeof(*data));
if (data == NULL)
return -EFAULT;
err = compat_get_ion_allocation_data(data32, data);
if (err)
return err;
ret = filp->f_op->unlocked_ioctl(filp, ION_IOC_ALLOC,
(unsigned long)data);
err = compat_put_ion_allocation_data(data32, data);
return ret ? ret : err;
}
case COMPAT_ION_IOC_FREE:
{
struct compat_ion_handle_data __user *data32;
struct ion_handle_data __user *data;
int err;
data32 = compat_ptr(arg);
data = compat_alloc_user_space(sizeof(*data));
if (data == NULL)
return -EFAULT;
err = compat_get_ion_handle_data(data32, data);
if (err)
return err;
return filp->f_op->unlocked_ioctl(filp, ION_IOC_FREE,
(unsigned long)data);
}
case COMPAT_ION_IOC_CUSTOM: {
struct compat_ion_custom_data __user *data32;
struct ion_custom_data __user *data;
int err;
data32 = compat_ptr(arg);
data = compat_alloc_user_space(sizeof(*data));
if (data == NULL)
return -EFAULT;
err = compat_get_ion_custom_data(data32, data);
if (err)
return err;
return filp->f_op->unlocked_ioctl(filp, ION_IOC_CUSTOM,
(unsigned long)data);
}
case ION_IOC_SHARE:
case ION_IOC_MAP:
case ION_IOC_IMPORT:
case ION_IOC_SYNC:
return filp->f_op->unlocked_ioctl(filp, cmd,
(unsigned long)compat_ptr(arg));
default:
return -ENOIOCTLCMD;
}
}
| gpl-2.0 |
dancefire/hd806-kernel-android | drivers/infiniband/hw/ipath/ipath_init_chip.c | 971 | 33465 | /*
* Copyright (c) 2006, 2007, 2008 QLogic Corporation. All rights reserved.
* Copyright (c) 2003, 2004, 2005, 2006 PathScale, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include "ipath_kernel.h"
#include "ipath_common.h"
/*
* min buffers we want to have per port, after driver
*/
#define IPATH_MIN_USER_PORT_BUFCNT 7
/*
* Number of ports we are configured to use (to allow for more pio
* buffers per port, etc.) Zero means use chip value.
*/
static ushort ipath_cfgports;
module_param_named(cfgports, ipath_cfgports, ushort, S_IRUGO);
MODULE_PARM_DESC(cfgports, "Set max number of ports to use");
/*
* Number of buffers reserved for driver (verbs and layered drivers.)
* Initialized based on number of PIO buffers if not set via module interface.
* The problem with this is that it's global, but we'll use different
* numbers for different chip types.
*/
static ushort ipath_kpiobufs;
static int ipath_set_kpiobufs(const char *val, struct kernel_param *kp);
module_param_call(kpiobufs, ipath_set_kpiobufs, param_get_ushort,
&ipath_kpiobufs, S_IWUSR | S_IRUGO);
MODULE_PARM_DESC(kpiobufs, "Set number of PIO buffers for driver");
/**
* create_port0_egr - allocate the eager TID buffers
* @dd: the infinipath device
*
* This code is now quite different for user and kernel, because
* the kernel uses skb's, for the accelerated network performance.
* This is the kernel (port0) version.
*
* Allocate the eager TID buffers and program them into infinipath.
* We use the network layer alloc_skb() allocator to allocate the
* memory, and either use the buffers as is for things like verbs
* packets, or pass the buffers up to the ipath layered driver and
* thence the network layer, replacing them as we do so (see
* ipath_rcv_layer()).
*/
static int create_port0_egr(struct ipath_devdata *dd)
{
unsigned e, egrcnt;
struct ipath_skbinfo *skbinfo;
int ret;
egrcnt = dd->ipath_p0_rcvegrcnt;
skbinfo = vmalloc(sizeof(*dd->ipath_port0_skbinfo) * egrcnt);
if (skbinfo == NULL) {
ipath_dev_err(dd, "allocation error for eager TID "
"skb array\n");
ret = -ENOMEM;
goto bail;
}
for (e = 0; e < egrcnt; e++) {
/*
* This is a bit tricky in that we allocate extra
* space for 2 bytes of the 14 byte ethernet header.
* These two bytes are passed in the ipath header so
* the rest of the data is word aligned. We allocate
* 4 bytes so that the data buffer stays word aligned.
* See ipath_kreceive() for more details.
*/
skbinfo[e].skb = ipath_alloc_skb(dd, GFP_KERNEL);
if (!skbinfo[e].skb) {
ipath_dev_err(dd, "SKB allocation error for "
"eager TID %u\n", e);
while (e != 0)
dev_kfree_skb(skbinfo[--e].skb);
vfree(skbinfo);
ret = -ENOMEM;
goto bail;
}
}
/*
* After loop above, so we can test non-NULL to see if ready
* to use at receive, etc.
*/
dd->ipath_port0_skbinfo = skbinfo;
for (e = 0; e < egrcnt; e++) {
dd->ipath_port0_skbinfo[e].phys =
ipath_map_single(dd->pcidev,
dd->ipath_port0_skbinfo[e].skb->data,
dd->ipath_ibmaxlen, PCI_DMA_FROMDEVICE);
dd->ipath_f_put_tid(dd, e + (u64 __iomem *)
((char __iomem *) dd->ipath_kregbase +
dd->ipath_rcvegrbase),
RCVHQ_RCV_TYPE_EAGER,
dd->ipath_port0_skbinfo[e].phys);
}
ret = 0;
bail:
return ret;
}
static int bringup_link(struct ipath_devdata *dd)
{
u64 val, ibc;
int ret = 0;
/* hold IBC in reset */
dd->ipath_control &= ~INFINIPATH_C_LINKENABLE;
ipath_write_kreg(dd, dd->ipath_kregs->kr_control,
dd->ipath_control);
/*
* set initial max size pkt IBC will send, including ICRC; it's the
* PIO buffer size in dwords, less 1; also see ipath_set_mtu()
*/
val = (dd->ipath_ibmaxlen >> 2) + 1;
ibc = val << dd->ibcc_mpl_shift;
/* flowcontrolwatermark is in units of KBytes */
ibc |= 0x5ULL << INFINIPATH_IBCC_FLOWCTRLWATERMARK_SHIFT;
/*
* How often flowctrl sent. More or less in usecs; balance against
* watermark value, so that in theory senders always get a flow
* control update in time to not let the IB link go idle.
*/
ibc |= 0x3ULL << INFINIPATH_IBCC_FLOWCTRLPERIOD_SHIFT;
/* max error tolerance */
ibc |= 0xfULL << INFINIPATH_IBCC_PHYERRTHRESHOLD_SHIFT;
/* use "real" buffer space for */
ibc |= 4ULL << INFINIPATH_IBCC_CREDITSCALE_SHIFT;
/* IB credit flow control. */
ibc |= 0xfULL << INFINIPATH_IBCC_OVERRUNTHRESHOLD_SHIFT;
/* initially come up waiting for TS1, without sending anything. */
dd->ipath_ibcctrl = ibc;
/*
* Want to start out with both LINKCMD and LINKINITCMD in NOP
* (0 and 0). Don't put linkinitcmd in ipath_ibcctrl, want that
* to stay a NOP. Flag that we are disabled, for the (unlikely)
* case that some recovery path is trying to bring the link up
* before we are ready.
*/
ibc |= INFINIPATH_IBCC_LINKINITCMD_DISABLE <<
INFINIPATH_IBCC_LINKINITCMD_SHIFT;
dd->ipath_flags |= IPATH_IB_LINK_DISABLED;
ipath_cdbg(VERBOSE, "Writing 0x%llx to ibcctrl\n",
(unsigned long long) ibc);
ipath_write_kreg(dd, dd->ipath_kregs->kr_ibcctrl, ibc);
// be sure chip saw it
val = ipath_read_kreg64(dd, dd->ipath_kregs->kr_scratch);
ret = dd->ipath_f_bringup_serdes(dd);
if (ret)
dev_info(&dd->pcidev->dev, "Could not initialize SerDes, "
"not usable\n");
else {
/* enable IBC */
dd->ipath_control |= INFINIPATH_C_LINKENABLE;
ipath_write_kreg(dd, dd->ipath_kregs->kr_control,
dd->ipath_control);
}
return ret;
}
static struct ipath_portdata *create_portdata0(struct ipath_devdata *dd)
{
struct ipath_portdata *pd = NULL;
pd = kzalloc(sizeof(*pd), GFP_KERNEL);
if (pd) {
pd->port_dd = dd;
pd->port_cnt = 1;
/* The port 0 pkey table is used by the layer interface. */
pd->port_pkeys[0] = IPATH_DEFAULT_P_KEY;
pd->port_seq_cnt = 1;
}
return pd;
}
static int init_chip_first(struct ipath_devdata *dd)
{
struct ipath_portdata *pd;
int ret = 0;
u64 val;
spin_lock_init(&dd->ipath_kernel_tid_lock);
spin_lock_init(&dd->ipath_user_tid_lock);
spin_lock_init(&dd->ipath_sendctrl_lock);
spin_lock_init(&dd->ipath_uctxt_lock);
spin_lock_init(&dd->ipath_sdma_lock);
spin_lock_init(&dd->ipath_gpio_lock);
spin_lock_init(&dd->ipath_eep_st_lock);
spin_lock_init(&dd->ipath_sdepb_lock);
mutex_init(&dd->ipath_eep_lock);
/*
* skip cfgports stuff because we are not allocating memory,
* and we don't want problems if the portcnt changed due to
* cfgports. We do still check and report a difference, if
* not same (should be impossible).
*/
dd->ipath_f_config_ports(dd, ipath_cfgports);
if (!ipath_cfgports)
dd->ipath_cfgports = dd->ipath_portcnt;
else if (ipath_cfgports <= dd->ipath_portcnt) {
dd->ipath_cfgports = ipath_cfgports;
ipath_dbg("Configured to use %u ports out of %u in chip\n",
dd->ipath_cfgports, ipath_read_kreg32(dd,
dd->ipath_kregs->kr_portcnt));
} else {
dd->ipath_cfgports = dd->ipath_portcnt;
ipath_dbg("Tried to configured to use %u ports; chip "
"only supports %u\n", ipath_cfgports,
ipath_read_kreg32(dd,
dd->ipath_kregs->kr_portcnt));
}
/*
* Allocate full portcnt array, rather than just cfgports, because
* cleanup iterates across all possible ports.
*/
dd->ipath_pd = kzalloc(sizeof(*dd->ipath_pd) * dd->ipath_portcnt,
GFP_KERNEL);
if (!dd->ipath_pd) {
ipath_dev_err(dd, "Unable to allocate portdata array, "
"failing\n");
ret = -ENOMEM;
goto done;
}
pd = create_portdata0(dd);
if (!pd) {
ipath_dev_err(dd, "Unable to allocate portdata for port "
"0, failing\n");
ret = -ENOMEM;
goto done;
}
dd->ipath_pd[0] = pd;
dd->ipath_rcvtidcnt =
ipath_read_kreg32(dd, dd->ipath_kregs->kr_rcvtidcnt);
dd->ipath_rcvtidbase =
ipath_read_kreg32(dd, dd->ipath_kregs->kr_rcvtidbase);
dd->ipath_rcvegrcnt =
ipath_read_kreg32(dd, dd->ipath_kregs->kr_rcvegrcnt);
dd->ipath_rcvegrbase =
ipath_read_kreg32(dd, dd->ipath_kregs->kr_rcvegrbase);
dd->ipath_palign =
ipath_read_kreg32(dd, dd->ipath_kregs->kr_pagealign);
dd->ipath_piobufbase =
ipath_read_kreg64(dd, dd->ipath_kregs->kr_sendpiobufbase);
val = ipath_read_kreg64(dd, dd->ipath_kregs->kr_sendpiosize);
dd->ipath_piosize2k = val & ~0U;
dd->ipath_piosize4k = val >> 32;
if (dd->ipath_piosize4k == 0 && ipath_mtu4096)
ipath_mtu4096 = 0; /* 4KB not supported by this chip */
dd->ipath_ibmtu = ipath_mtu4096 ? 4096 : 2048;
val = ipath_read_kreg64(dd, dd->ipath_kregs->kr_sendpiobufcnt);
dd->ipath_piobcnt2k = val & ~0U;
dd->ipath_piobcnt4k = val >> 32;
dd->ipath_pio2kbase =
(u32 __iomem *) (((char __iomem *) dd->ipath_kregbase) +
(dd->ipath_piobufbase & 0xffffffff));
if (dd->ipath_piobcnt4k) {
dd->ipath_pio4kbase = (u32 __iomem *)
(((char __iomem *) dd->ipath_kregbase) +
(dd->ipath_piobufbase >> 32));
/*
* 4K buffers take 2 pages; we use roundup just to be
* paranoid; we calculate it once here, rather than on
* ever buf allocate
*/
dd->ipath_4kalign = ALIGN(dd->ipath_piosize4k,
dd->ipath_palign);
ipath_dbg("%u 2k(%x) piobufs @ %p, %u 4k(%x) @ %p "
"(%x aligned)\n",
dd->ipath_piobcnt2k, dd->ipath_piosize2k,
dd->ipath_pio2kbase, dd->ipath_piobcnt4k,
dd->ipath_piosize4k, dd->ipath_pio4kbase,
dd->ipath_4kalign);
}
else ipath_dbg("%u 2k piobufs @ %p\n",
dd->ipath_piobcnt2k, dd->ipath_pio2kbase);
done:
return ret;
}
/**
* init_chip_reset - re-initialize after a reset, or enable
* @dd: the infinipath device
*
* sanity check at least some of the values after reset, and
* ensure no receive or transmit (explictly, in case reset
* failed
*/
static int init_chip_reset(struct ipath_devdata *dd)
{
u32 rtmp;
int i;
unsigned long flags;
/*
* ensure chip does no sends or receives, tail updates, or
* pioavail updates while we re-initialize
*/
dd->ipath_rcvctrl &= ~(1ULL << dd->ipath_r_tailupd_shift);
for (i = 0; i < dd->ipath_portcnt; i++) {
clear_bit(dd->ipath_r_portenable_shift + i,
&dd->ipath_rcvctrl);
clear_bit(dd->ipath_r_intravail_shift + i,
&dd->ipath_rcvctrl);
}
ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvctrl,
dd->ipath_rcvctrl);
spin_lock_irqsave(&dd->ipath_sendctrl_lock, flags);
dd->ipath_sendctrl = 0U; /* no sdma, etc */
ipath_write_kreg(dd, dd->ipath_kregs->kr_sendctrl, dd->ipath_sendctrl);
ipath_read_kreg64(dd, dd->ipath_kregs->kr_scratch);
spin_unlock_irqrestore(&dd->ipath_sendctrl_lock, flags);
ipath_write_kreg(dd, dd->ipath_kregs->kr_control, 0ULL);
rtmp = ipath_read_kreg32(dd, dd->ipath_kregs->kr_rcvtidcnt);
if (rtmp != dd->ipath_rcvtidcnt)
dev_info(&dd->pcidev->dev, "tidcnt was %u before "
"reset, now %u, using original\n",
dd->ipath_rcvtidcnt, rtmp);
rtmp = ipath_read_kreg32(dd, dd->ipath_kregs->kr_rcvtidbase);
if (rtmp != dd->ipath_rcvtidbase)
dev_info(&dd->pcidev->dev, "tidbase was %u before "
"reset, now %u, using original\n",
dd->ipath_rcvtidbase, rtmp);
rtmp = ipath_read_kreg32(dd, dd->ipath_kregs->kr_rcvegrcnt);
if (rtmp != dd->ipath_rcvegrcnt)
dev_info(&dd->pcidev->dev, "egrcnt was %u before "
"reset, now %u, using original\n",
dd->ipath_rcvegrcnt, rtmp);
rtmp = ipath_read_kreg32(dd, dd->ipath_kregs->kr_rcvegrbase);
if (rtmp != dd->ipath_rcvegrbase)
dev_info(&dd->pcidev->dev, "egrbase was %u before "
"reset, now %u, using original\n",
dd->ipath_rcvegrbase, rtmp);
return 0;
}
static int init_pioavailregs(struct ipath_devdata *dd)
{
int ret;
dd->ipath_pioavailregs_dma = dma_alloc_coherent(
&dd->pcidev->dev, PAGE_SIZE, &dd->ipath_pioavailregs_phys,
GFP_KERNEL);
if (!dd->ipath_pioavailregs_dma) {
ipath_dev_err(dd, "failed to allocate PIOavail reg area "
"in memory\n");
ret = -ENOMEM;
goto done;
}
/*
* we really want L2 cache aligned, but for current CPUs of
* interest, they are the same.
*/
dd->ipath_statusp = (u64 *)
((char *)dd->ipath_pioavailregs_dma +
((2 * L1_CACHE_BYTES +
dd->ipath_pioavregs * sizeof(u64)) & ~L1_CACHE_BYTES));
/* copy the current value now that it's really allocated */
*dd->ipath_statusp = dd->_ipath_status;
/*
* setup buffer to hold freeze msg, accessible to apps,
* following statusp
*/
dd->ipath_freezemsg = (char *)&dd->ipath_statusp[1];
/* and its length */
dd->ipath_freezelen = L1_CACHE_BYTES - sizeof(dd->ipath_statusp[0]);
ret = 0;
done:
return ret;
}
/**
* init_shadow_tids - allocate the shadow TID array
* @dd: the infinipath device
*
* allocate the shadow TID array, so we can ipath_munlock previous
* entries. It may make more sense to move the pageshadow to the
* port data structure, so we only allocate memory for ports actually
* in use, since we at 8k per port, now.
*/
static void init_shadow_tids(struct ipath_devdata *dd)
{
struct page **pages;
dma_addr_t *addrs;
pages = vmalloc(dd->ipath_cfgports * dd->ipath_rcvtidcnt *
sizeof(struct page *));
if (!pages) {
ipath_dev_err(dd, "failed to allocate shadow page * "
"array, no expected sends!\n");
dd->ipath_pageshadow = NULL;
return;
}
addrs = vmalloc(dd->ipath_cfgports * dd->ipath_rcvtidcnt *
sizeof(dma_addr_t));
if (!addrs) {
ipath_dev_err(dd, "failed to allocate shadow dma handle "
"array, no expected sends!\n");
vfree(pages);
dd->ipath_pageshadow = NULL;
return;
}
memset(pages, 0, dd->ipath_cfgports * dd->ipath_rcvtidcnt *
sizeof(struct page *));
dd->ipath_pageshadow = pages;
dd->ipath_physshadow = addrs;
}
static void enable_chip(struct ipath_devdata *dd, int reinit)
{
u32 val;
u64 rcvmask;
unsigned long flags;
int i;
if (!reinit)
init_waitqueue_head(&ipath_state_wait);
ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvctrl,
dd->ipath_rcvctrl);
spin_lock_irqsave(&dd->ipath_sendctrl_lock, flags);
/* Enable PIO send, and update of PIOavail regs to memory. */
dd->ipath_sendctrl = INFINIPATH_S_PIOENABLE |
INFINIPATH_S_PIOBUFAVAILUPD;
/*
* Set the PIO avail update threshold to host memory
* on chips that support it.
*/
if (dd->ipath_pioupd_thresh)
dd->ipath_sendctrl |= dd->ipath_pioupd_thresh
<< INFINIPATH_S_UPDTHRESH_SHIFT;
ipath_write_kreg(dd, dd->ipath_kregs->kr_sendctrl, dd->ipath_sendctrl);
ipath_read_kreg64(dd, dd->ipath_kregs->kr_scratch);
spin_unlock_irqrestore(&dd->ipath_sendctrl_lock, flags);
/*
* Enable kernel ports' receive and receive interrupt.
* Other ports done as user opens and inits them.
*/
rcvmask = 1ULL;
dd->ipath_rcvctrl |= (rcvmask << dd->ipath_r_portenable_shift) |
(rcvmask << dd->ipath_r_intravail_shift);
if (!(dd->ipath_flags & IPATH_NODMA_RTAIL))
dd->ipath_rcvctrl |= (1ULL << dd->ipath_r_tailupd_shift);
ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvctrl,
dd->ipath_rcvctrl);
/*
* now ready for use. this should be cleared whenever we
* detect a reset, or initiate one.
*/
dd->ipath_flags |= IPATH_INITTED;
/*
* Init our shadow copies of head from tail values,
* and write head values to match.
*/
val = ipath_read_ureg32(dd, ur_rcvegrindextail, 0);
ipath_write_ureg(dd, ur_rcvegrindexhead, val, 0);
/* Initialize so we interrupt on next packet received */
ipath_write_ureg(dd, ur_rcvhdrhead,
dd->ipath_rhdrhead_intr_off |
dd->ipath_pd[0]->port_head, 0);
/*
* by now pioavail updates to memory should have occurred, so
* copy them into our working/shadow registers; this is in
* case something went wrong with abort, but mostly to get the
* initial values of the generation bit correct.
*/
for (i = 0; i < dd->ipath_pioavregs; i++) {
__le64 pioavail;
/*
* Chip Errata bug 6641; even and odd qwords>3 are swapped.
*/
if (i > 3 && (dd->ipath_flags & IPATH_SWAP_PIOBUFS))
pioavail = dd->ipath_pioavailregs_dma[i ^ 1];
else
pioavail = dd->ipath_pioavailregs_dma[i];
/*
* don't need to worry about ipath_pioavailkernel here
* because we will call ipath_chg_pioavailkernel() later
* in initialization, to busy out buffers as needed
*/
dd->ipath_pioavailshadow[i] = le64_to_cpu(pioavail);
}
/* can get counters, stats, etc. */
dd->ipath_flags |= IPATH_PRESENT;
}
static int init_housekeeping(struct ipath_devdata *dd, int reinit)
{
char boardn[40];
int ret = 0;
/*
* have to clear shadow copies of registers at init that are
* not otherwise set here, or all kinds of bizarre things
* happen with driver on chip reset
*/
dd->ipath_rcvhdrsize = 0;
/*
* Don't clear ipath_flags as 8bit mode was set before
* entering this func. However, we do set the linkstate to
* unknown, so we can watch for a transition.
* PRESENT is set because we want register reads to work,
* and the kernel infrastructure saw it in config space;
* We clear it if we have failures.
*/
dd->ipath_flags |= IPATH_LINKUNK | IPATH_PRESENT;
dd->ipath_flags &= ~(IPATH_LINKACTIVE | IPATH_LINKARMED |
IPATH_LINKDOWN | IPATH_LINKINIT);
ipath_cdbg(VERBOSE, "Try to read spc chip revision\n");
dd->ipath_revision =
ipath_read_kreg64(dd, dd->ipath_kregs->kr_revision);
/*
* set up fundamental info we need to use the chip; we assume
* if the revision reg and these regs are OK, we don't need to
* special case the rest
*/
dd->ipath_sregbase =
ipath_read_kreg32(dd, dd->ipath_kregs->kr_sendregbase);
dd->ipath_cregbase =
ipath_read_kreg32(dd, dd->ipath_kregs->kr_counterregbase);
dd->ipath_uregbase =
ipath_read_kreg32(dd, dd->ipath_kregs->kr_userregbase);
ipath_cdbg(VERBOSE, "ipath_kregbase %p, sendbase %x usrbase %x, "
"cntrbase %x\n", dd->ipath_kregbase, dd->ipath_sregbase,
dd->ipath_uregbase, dd->ipath_cregbase);
if ((dd->ipath_revision & 0xffffffff) == 0xffffffff
|| (dd->ipath_sregbase & 0xffffffff) == 0xffffffff
|| (dd->ipath_cregbase & 0xffffffff) == 0xffffffff
|| (dd->ipath_uregbase & 0xffffffff) == 0xffffffff) {
ipath_dev_err(dd, "Register read failures from chip, "
"giving up initialization\n");
dd->ipath_flags &= ~IPATH_PRESENT;
ret = -ENODEV;
goto done;
}
/* clear diagctrl register, in case diags were running and crashed */
ipath_write_kreg (dd, dd->ipath_kregs->kr_hwdiagctrl, 0);
/* clear the initial reset flag, in case first driver load */
ipath_write_kreg(dd, dd->ipath_kregs->kr_errorclear,
INFINIPATH_E_RESET);
ipath_cdbg(VERBOSE, "Revision %llx (PCI %x)\n",
(unsigned long long) dd->ipath_revision,
dd->ipath_pcirev);
if (((dd->ipath_revision >> INFINIPATH_R_SOFTWARE_SHIFT) &
INFINIPATH_R_SOFTWARE_MASK) != IPATH_CHIP_SWVERSION) {
ipath_dev_err(dd, "Driver only handles version %d, "
"chip swversion is %d (%llx), failng\n",
IPATH_CHIP_SWVERSION,
(int)(dd->ipath_revision >>
INFINIPATH_R_SOFTWARE_SHIFT) &
INFINIPATH_R_SOFTWARE_MASK,
(unsigned long long) dd->ipath_revision);
ret = -ENOSYS;
goto done;
}
dd->ipath_majrev = (u8) ((dd->ipath_revision >>
INFINIPATH_R_CHIPREVMAJOR_SHIFT) &
INFINIPATH_R_CHIPREVMAJOR_MASK);
dd->ipath_minrev = (u8) ((dd->ipath_revision >>
INFINIPATH_R_CHIPREVMINOR_SHIFT) &
INFINIPATH_R_CHIPREVMINOR_MASK);
dd->ipath_boardrev = (u8) ((dd->ipath_revision >>
INFINIPATH_R_BOARDID_SHIFT) &
INFINIPATH_R_BOARDID_MASK);
ret = dd->ipath_f_get_boardname(dd, boardn, sizeof boardn);
snprintf(dd->ipath_boardversion, sizeof(dd->ipath_boardversion),
"ChipABI %u.%u, %s, InfiniPath%u %u.%u, PCI %u, "
"SW Compat %u\n",
IPATH_CHIP_VERS_MAJ, IPATH_CHIP_VERS_MIN, boardn,
(unsigned)(dd->ipath_revision >> INFINIPATH_R_ARCH_SHIFT) &
INFINIPATH_R_ARCH_MASK,
dd->ipath_majrev, dd->ipath_minrev, dd->ipath_pcirev,
(unsigned)(dd->ipath_revision >>
INFINIPATH_R_SOFTWARE_SHIFT) &
INFINIPATH_R_SOFTWARE_MASK);
ipath_dbg("%s", dd->ipath_boardversion);
if (ret)
goto done;
if (reinit)
ret = init_chip_reset(dd);
else
ret = init_chip_first(dd);
done:
return ret;
}
static void verify_interrupt(unsigned long opaque)
{
struct ipath_devdata *dd = (struct ipath_devdata *) opaque;
if (!dd)
return; /* being torn down */
/*
* If we don't have any interrupts, let the user know and
* don't bother checking again.
*/
if (dd->ipath_int_counter == 0) {
if (!dd->ipath_f_intr_fallback(dd))
dev_err(&dd->pcidev->dev, "No interrupts detected, "
"not usable.\n");
else /* re-arm the timer to see if fallback works */
mod_timer(&dd->ipath_intrchk_timer, jiffies + HZ/2);
} else
ipath_cdbg(VERBOSE, "%u interrupts at timer check\n",
dd->ipath_int_counter);
}
/**
* ipath_init_chip - do the actual initialization sequence on the chip
* @dd: the infinipath device
* @reinit: reinitializing, so don't allocate new memory
*
* Do the actual initialization sequence on the chip. This is done
* both from the init routine called from the PCI infrastructure, and
* when we reset the chip, or detect that it was reset internally,
* or it's administratively re-enabled.
*
* Memory allocation here and in called routines is only done in
* the first case (reinit == 0). We have to be careful, because even
* without memory allocation, we need to re-write all the chip registers
* TIDs, etc. after the reset or enable has completed.
*/
int ipath_init_chip(struct ipath_devdata *dd, int reinit)
{
int ret = 0;
u32 kpiobufs, defkbufs;
u32 piobufs, uports;
u64 val;
struct ipath_portdata *pd;
gfp_t gfp_flags = GFP_USER | __GFP_COMP;
ret = init_housekeeping(dd, reinit);
if (ret)
goto done;
/*
* we ignore most issues after reporting them, but have to specially
* handle hardware-disabled chips.
*/
if (ret == 2) {
/* unique error, known to ipath_init_one */
ret = -EPERM;
goto done;
}
/*
* We could bump this to allow for full rcvegrcnt + rcvtidcnt,
* but then it no longer nicely fits power of two, and since
* we now use routines that backend onto __get_free_pages, the
* rest would be wasted.
*/
dd->ipath_rcvhdrcnt = max(dd->ipath_p0_rcvegrcnt, dd->ipath_rcvegrcnt);
ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvhdrcnt,
dd->ipath_rcvhdrcnt);
/*
* Set up the shadow copies of the piobufavail registers,
* which we compare against the chip registers for now, and
* the in memory DMA'ed copies of the registers. This has to
* be done early, before we calculate lastport, etc.
*/
piobufs = dd->ipath_piobcnt2k + dd->ipath_piobcnt4k;
/*
* calc number of pioavail registers, and save it; we have 2
* bits per buffer.
*/
dd->ipath_pioavregs = ALIGN(piobufs, sizeof(u64) * BITS_PER_BYTE / 2)
/ (sizeof(u64) * BITS_PER_BYTE / 2);
uports = dd->ipath_cfgports ? dd->ipath_cfgports - 1 : 0;
if (piobufs > 144)
defkbufs = 32 + dd->ipath_pioreserved;
else
defkbufs = 16 + dd->ipath_pioreserved;
if (ipath_kpiobufs && (ipath_kpiobufs +
(uports * IPATH_MIN_USER_PORT_BUFCNT)) > piobufs) {
int i = (int) piobufs -
(int) (uports * IPATH_MIN_USER_PORT_BUFCNT);
if (i < 1)
i = 1;
dev_info(&dd->pcidev->dev, "Allocating %d PIO bufs of "
"%d for kernel leaves too few for %d user ports "
"(%d each); using %u\n", ipath_kpiobufs,
piobufs, uports, IPATH_MIN_USER_PORT_BUFCNT, i);
/*
* shouldn't change ipath_kpiobufs, because could be
* different for different devices...
*/
kpiobufs = i;
} else if (ipath_kpiobufs)
kpiobufs = ipath_kpiobufs;
else
kpiobufs = defkbufs;
dd->ipath_lastport_piobuf = piobufs - kpiobufs;
dd->ipath_pbufsport =
uports ? dd->ipath_lastport_piobuf / uports : 0;
/* if not an even divisor, some user ports get extra buffers */
dd->ipath_ports_extrabuf = dd->ipath_lastport_piobuf -
(dd->ipath_pbufsport * uports);
if (dd->ipath_ports_extrabuf)
ipath_dbg("%u pbufs/port leaves some unused, add 1 buffer to "
"ports <= %u\n", dd->ipath_pbufsport,
dd->ipath_ports_extrabuf);
dd->ipath_lastpioindex = 0;
dd->ipath_lastpioindexl = dd->ipath_piobcnt2k;
/* ipath_pioavailshadow initialized earlier */
ipath_cdbg(VERBOSE, "%d PIO bufs for kernel out of %d total %u "
"each for %u user ports\n", kpiobufs,
piobufs, dd->ipath_pbufsport, uports);
ret = dd->ipath_f_early_init(dd);
if (ret) {
ipath_dev_err(dd, "Early initialization failure\n");
goto done;
}
/*
* Early_init sets rcvhdrentsize and rcvhdrsize, so this must be
* done after early_init.
*/
dd->ipath_hdrqlast =
dd->ipath_rcvhdrentsize * (dd->ipath_rcvhdrcnt - 1);
ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvhdrentsize,
dd->ipath_rcvhdrentsize);
ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvhdrsize,
dd->ipath_rcvhdrsize);
if (!reinit) {
ret = init_pioavailregs(dd);
init_shadow_tids(dd);
if (ret)
goto done;
}
ipath_write_kreg(dd, dd->ipath_kregs->kr_sendpioavailaddr,
dd->ipath_pioavailregs_phys);
/*
* this is to detect s/w errors, which the h/w works around by
* ignoring the low 6 bits of address, if it wasn't aligned.
*/
val = ipath_read_kreg64(dd, dd->ipath_kregs->kr_sendpioavailaddr);
if (val != dd->ipath_pioavailregs_phys) {
ipath_dev_err(dd, "Catastrophic software error, "
"SendPIOAvailAddr written as %lx, "
"read back as %llx\n",
(unsigned long) dd->ipath_pioavailregs_phys,
(unsigned long long) val);
ret = -EINVAL;
goto done;
}
ipath_write_kreg(dd, dd->ipath_kregs->kr_rcvbthqp, IPATH_KD_QP);
/*
* make sure we are not in freeze, and PIO send enabled, so
* writes to pbc happen
*/
ipath_write_kreg(dd, dd->ipath_kregs->kr_hwerrmask, 0ULL);
ipath_write_kreg(dd, dd->ipath_kregs->kr_hwerrclear,
~0ULL&~INFINIPATH_HWE_MEMBISTFAILED);
ipath_write_kreg(dd, dd->ipath_kregs->kr_control, 0ULL);
/*
* before error clears, since we expect serdes pll errors during
* this, the first time after reset
*/
if (bringup_link(dd)) {
dev_info(&dd->pcidev->dev, "Failed to bringup IB link\n");
ret = -ENETDOWN;
goto done;
}
/*
* clear any "expected" hwerrs from reset and/or initialization
* clear any that aren't enabled (at least this once), and then
* set the enable mask
*/
dd->ipath_f_init_hwerrors(dd);
ipath_write_kreg(dd, dd->ipath_kregs->kr_hwerrclear,
~0ULL&~INFINIPATH_HWE_MEMBISTFAILED);
ipath_write_kreg(dd, dd->ipath_kregs->kr_hwerrmask,
dd->ipath_hwerrmask);
/* clear all */
ipath_write_kreg(dd, dd->ipath_kregs->kr_errorclear, -1LL);
/* enable errors that are masked, at least this first time. */
ipath_write_kreg(dd, dd->ipath_kregs->kr_errormask,
~dd->ipath_maskederrs);
dd->ipath_maskederrs = 0; /* don't re-enable ignored in timer */
dd->ipath_errormask =
ipath_read_kreg64(dd, dd->ipath_kregs->kr_errormask);
/* clear any interrupts up to this point (ints still not enabled) */
ipath_write_kreg(dd, dd->ipath_kregs->kr_intclear, -1LL);
dd->ipath_f_tidtemplate(dd);
/*
* Set up the port 0 (kernel) rcvhdr q and egr TIDs. If doing
* re-init, the simplest way to handle this is to free
* existing, and re-allocate.
* Need to re-create rest of port 0 portdata as well.
*/
pd = dd->ipath_pd[0];
if (reinit) {
struct ipath_portdata *npd;
/*
* Alloc and init new ipath_portdata for port0,
* Then free old pd. Could lead to fragmentation, but also
* makes later support for hot-swap easier.
*/
npd = create_portdata0(dd);
if (npd) {
ipath_free_pddata(dd, pd);
dd->ipath_pd[0] = npd;
pd = npd;
} else {
ipath_dev_err(dd, "Unable to allocate portdata"
" for port 0, failing\n");
ret = -ENOMEM;
goto done;
}
}
ret = ipath_create_rcvhdrq(dd, pd);
if (!ret)
ret = create_port0_egr(dd);
if (ret) {
ipath_dev_err(dd, "failed to allocate kernel port's "
"rcvhdrq and/or egr bufs\n");
goto done;
}
else
enable_chip(dd, reinit);
/* after enable_chip, so pioavailshadow setup */
ipath_chg_pioavailkernel(dd, 0, piobufs, 1);
/*
* Cancel any possible active sends from early driver load.
* Follows early_init because some chips have to initialize
* PIO buffers in early_init to avoid false parity errors.
* After enable and ipath_chg_pioavailkernel so we can safely
* enable pioavail updates and PIOENABLE; packets are now
* ready to go out.
*/
ipath_cancel_sends(dd, 1);
if (!reinit) {
/*
* Used when we close a port, for DMA already in flight
* at close.
*/
dd->ipath_dummy_hdrq = dma_alloc_coherent(
&dd->pcidev->dev, dd->ipath_pd[0]->port_rcvhdrq_size,
&dd->ipath_dummy_hdrq_phys,
gfp_flags);
if (!dd->ipath_dummy_hdrq) {
dev_info(&dd->pcidev->dev,
"Couldn't allocate 0x%lx bytes for dummy hdrq\n",
dd->ipath_pd[0]->port_rcvhdrq_size);
/* fallback to just 0'ing */
dd->ipath_dummy_hdrq_phys = 0UL;
}
}
/*
* cause retrigger of pending interrupts ignored during init,
* even if we had errors
*/
ipath_write_kreg(dd, dd->ipath_kregs->kr_intclear, 0ULL);
if (!dd->ipath_stats_timer_active) {
/*
* first init, or after an admin disable/enable
* set up stats retrieval timer, even if we had errors
* in last portion of setup
*/
init_timer(&dd->ipath_stats_timer);
dd->ipath_stats_timer.function = ipath_get_faststats;
dd->ipath_stats_timer.data = (unsigned long) dd;
/* every 5 seconds; */
dd->ipath_stats_timer.expires = jiffies + 5 * HZ;
/* takes ~16 seconds to overflow at full IB 4x bandwdith */
add_timer(&dd->ipath_stats_timer);
dd->ipath_stats_timer_active = 1;
}
/* Set up SendDMA if chip supports it */
if (dd->ipath_flags & IPATH_HAS_SEND_DMA)
ret = setup_sdma(dd);
/* Set up HoL state */
init_timer(&dd->ipath_hol_timer);
dd->ipath_hol_timer.function = ipath_hol_event;
dd->ipath_hol_timer.data = (unsigned long)dd;
dd->ipath_hol_state = IPATH_HOL_UP;
done:
if (!ret) {
*dd->ipath_statusp |= IPATH_STATUS_CHIP_PRESENT;
if (!dd->ipath_f_intrsetup(dd)) {
/* now we can enable all interrupts from the chip */
ipath_write_kreg(dd, dd->ipath_kregs->kr_intmask,
-1LL);
/* force re-interrupt of any pending interrupts. */
ipath_write_kreg(dd, dd->ipath_kregs->kr_intclear,
0ULL);
/* chip is usable; mark it as initialized */
*dd->ipath_statusp |= IPATH_STATUS_INITTED;
/*
* setup to verify we get an interrupt, and fallback
* to an alternate if necessary and possible
*/
if (!reinit) {
init_timer(&dd->ipath_intrchk_timer);
dd->ipath_intrchk_timer.function =
verify_interrupt;
dd->ipath_intrchk_timer.data =
(unsigned long) dd;
}
dd->ipath_intrchk_timer.expires = jiffies + HZ/2;
add_timer(&dd->ipath_intrchk_timer);
} else
ipath_dev_err(dd, "No interrupts enabled, couldn't "
"setup interrupt address\n");
if (dd->ipath_cfgports > ipath_stats.sps_nports)
/*
* sps_nports is a global, so, we set it to
* the highest number of ports of any of the
* chips we find; we never decrement it, at
* least for now. Since this might have changed
* over disable/enable or prior to reset, always
* do the check and potentially adjust.
*/
ipath_stats.sps_nports = dd->ipath_cfgports;
} else
ipath_dbg("Failed (%d) to initialize chip\n", ret);
/* if ret is non-zero, we probably should do some cleanup
here... */
return ret;
}
static int ipath_set_kpiobufs(const char *str, struct kernel_param *kp)
{
struct ipath_devdata *dd;
unsigned long flags;
unsigned short val;
int ret;
ret = ipath_parse_ushort(str, &val);
spin_lock_irqsave(&ipath_devs_lock, flags);
if (ret < 0)
goto bail;
if (val == 0) {
ret = -EINVAL;
goto bail;
}
list_for_each_entry(dd, &ipath_dev_list, ipath_list) {
if (dd->ipath_kregbase)
continue;
if (val > (dd->ipath_piobcnt2k + dd->ipath_piobcnt4k -
(dd->ipath_cfgports *
IPATH_MIN_USER_PORT_BUFCNT)))
{
ipath_dev_err(
dd,
"Allocating %d PIO bufs for kernel leaves "
"too few for %d user ports (%d each)\n",
val, dd->ipath_cfgports - 1,
IPATH_MIN_USER_PORT_BUFCNT);
ret = -EINVAL;
goto bail;
}
dd->ipath_lastport_piobuf =
dd->ipath_piobcnt2k + dd->ipath_piobcnt4k - val;
}
ipath_kpiobufs = val;
ret = 0;
bail:
spin_unlock_irqrestore(&ipath_devs_lock, flags);
return ret;
}
| gpl-2.0 |
kirananto/android_kernel_cyanogen_msm8916-1 | drivers/mfd/htc-i2cpld.c | 2251 | 18368 | /*
* htc-i2cpld.c
* Chip driver for an unknown CPLD chip found on omap850 HTC devices like
* the HTC Wizard and HTC Herald.
* The cpld is located on the i2c bus and acts as an input/output GPIO
* extender.
*
* Copyright (C) 2009 Cory Maccarrone <darkstar6262@gmail.com>
*
* Based on work done in the linwizard project
* Copyright (C) 2008-2009 Angelo Arrifano <miknix@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/irq.h>
#include <linux/spinlock.h>
#include <linux/htcpld.h>
#include <linux/gpio.h>
#include <linux/slab.h>
struct htcpld_chip {
spinlock_t lock;
/* chip info */
u8 reset;
u8 addr;
struct device *dev;
struct i2c_client *client;
/* Output details */
u8 cache_out;
struct gpio_chip chip_out;
/* Input details */
u8 cache_in;
struct gpio_chip chip_in;
u16 irqs_enabled;
uint irq_start;
int nirqs;
unsigned int flow_type;
/*
* Work structure to allow for setting values outside of any
* possible interrupt context
*/
struct work_struct set_val_work;
};
struct htcpld_data {
/* irq info */
u16 irqs_enabled;
uint irq_start;
int nirqs;
uint chained_irq;
unsigned int int_reset_gpio_hi;
unsigned int int_reset_gpio_lo;
/* htcpld info */
struct htcpld_chip *chip;
unsigned int nchips;
};
/* There does not appear to be a way to proactively mask interrupts
* on the htcpld chip itself. So, we simply ignore interrupts that
* aren't desired. */
static void htcpld_mask(struct irq_data *data)
{
struct htcpld_chip *chip = irq_data_get_irq_chip_data(data);
chip->irqs_enabled &= ~(1 << (data->irq - chip->irq_start));
pr_debug("HTCPLD mask %d %04x\n", data->irq, chip->irqs_enabled);
}
static void htcpld_unmask(struct irq_data *data)
{
struct htcpld_chip *chip = irq_data_get_irq_chip_data(data);
chip->irqs_enabled |= 1 << (data->irq - chip->irq_start);
pr_debug("HTCPLD unmask %d %04x\n", data->irq, chip->irqs_enabled);
}
static int htcpld_set_type(struct irq_data *data, unsigned int flags)
{
struct htcpld_chip *chip = irq_data_get_irq_chip_data(data);
if (flags & ~IRQ_TYPE_SENSE_MASK)
return -EINVAL;
/* We only allow edge triggering */
if (flags & (IRQ_TYPE_LEVEL_LOW|IRQ_TYPE_LEVEL_HIGH))
return -EINVAL;
chip->flow_type = flags;
return 0;
}
static struct irq_chip htcpld_muxed_chip = {
.name = "htcpld",
.irq_mask = htcpld_mask,
.irq_unmask = htcpld_unmask,
.irq_set_type = htcpld_set_type,
};
/* To properly dispatch IRQ events, we need to read from the
* chip. This is an I2C action that could possibly sleep
* (which is bad in interrupt context) -- so we use a threaded
* interrupt handler to get around that.
*/
static irqreturn_t htcpld_handler(int irq, void *dev)
{
struct htcpld_data *htcpld = dev;
unsigned int i;
unsigned long flags;
int irqpin;
if (!htcpld) {
pr_debug("htcpld is null in ISR\n");
return IRQ_HANDLED;
}
/*
* For each chip, do a read of the chip and trigger any interrupts
* desired. The interrupts will be triggered from LSB to MSB (i.e.
* bit 0 first, then bit 1, etc.)
*
* For chips that have no interrupt range specified, just skip 'em.
*/
for (i = 0; i < htcpld->nchips; i++) {
struct htcpld_chip *chip = &htcpld->chip[i];
struct i2c_client *client;
int val;
unsigned long uval, old_val;
if (!chip) {
pr_debug("chip %d is null in ISR\n", i);
continue;
}
if (chip->nirqs == 0)
continue;
client = chip->client;
if (!client) {
pr_debug("client %d is null in ISR\n", i);
continue;
}
/* Scan the chip */
val = i2c_smbus_read_byte_data(client, chip->cache_out);
if (val < 0) {
/* Throw a warning and skip this chip */
dev_warn(chip->dev, "Unable to read from chip: %d\n",
val);
continue;
}
uval = (unsigned long)val;
spin_lock_irqsave(&chip->lock, flags);
/* Save away the old value so we can compare it */
old_val = chip->cache_in;
/* Write the new value */
chip->cache_in = uval;
spin_unlock_irqrestore(&chip->lock, flags);
/*
* For each bit in the data (starting at bit 0), trigger
* associated interrupts.
*/
for (irqpin = 0; irqpin < chip->nirqs; irqpin++) {
unsigned oldb, newb, type = chip->flow_type;
irq = chip->irq_start + irqpin;
/* Run the IRQ handler, but only if the bit value
* changed, and the proper flags are set */
oldb = (old_val >> irqpin) & 1;
newb = (uval >> irqpin) & 1;
if ((!oldb && newb && (type & IRQ_TYPE_EDGE_RISING)) ||
(oldb && !newb && (type & IRQ_TYPE_EDGE_FALLING))) {
pr_debug("fire IRQ %d\n", irqpin);
generic_handle_irq(irq);
}
}
}
/*
* In order to continue receiving interrupts, the int_reset_gpio must
* be asserted.
*/
if (htcpld->int_reset_gpio_hi)
gpio_set_value(htcpld->int_reset_gpio_hi, 1);
if (htcpld->int_reset_gpio_lo)
gpio_set_value(htcpld->int_reset_gpio_lo, 0);
return IRQ_HANDLED;
}
/*
* The GPIO set routines can be called from interrupt context, especially if,
* for example they're attached to the led-gpio framework and a trigger is
* enabled. As such, we declared work above in the htcpld_chip structure,
* and that work is scheduled in the set routine. The kernel can then run
* the I2C functions, which will sleep, in process context.
*/
static void htcpld_chip_set(struct gpio_chip *chip, unsigned offset, int val)
{
struct i2c_client *client;
struct htcpld_chip *chip_data;
unsigned long flags;
chip_data = container_of(chip, struct htcpld_chip, chip_out);
if (!chip_data)
return;
client = chip_data->client;
if (client == NULL)
return;
spin_lock_irqsave(&chip_data->lock, flags);
if (val)
chip_data->cache_out |= (1 << offset);
else
chip_data->cache_out &= ~(1 << offset);
spin_unlock_irqrestore(&chip_data->lock, flags);
schedule_work(&(chip_data->set_val_work));
}
static void htcpld_chip_set_ni(struct work_struct *work)
{
struct htcpld_chip *chip_data;
struct i2c_client *client;
chip_data = container_of(work, struct htcpld_chip, set_val_work);
client = chip_data->client;
i2c_smbus_read_byte_data(client, chip_data->cache_out);
}
static int htcpld_chip_get(struct gpio_chip *chip, unsigned offset)
{
struct htcpld_chip *chip_data;
int val = 0;
int is_input = 0;
/* Try out first */
chip_data = container_of(chip, struct htcpld_chip, chip_out);
if (!chip_data) {
/* Try in */
is_input = 1;
chip_data = container_of(chip, struct htcpld_chip, chip_in);
if (!chip_data)
return -EINVAL;
}
/* Determine if this is an input or output GPIO */
if (!is_input)
/* Use the output cache */
val = (chip_data->cache_out >> offset) & 1;
else
/* Use the input cache */
val = (chip_data->cache_in >> offset) & 1;
if (val)
return 1;
else
return 0;
}
static int htcpld_direction_output(struct gpio_chip *chip,
unsigned offset, int value)
{
htcpld_chip_set(chip, offset, value);
return 0;
}
static int htcpld_direction_input(struct gpio_chip *chip,
unsigned offset)
{
/*
* No-op: this function can only be called on the input chip.
* We do however make sure the offset is within range.
*/
return (offset < chip->ngpio) ? 0 : -EINVAL;
}
static int htcpld_chip_to_irq(struct gpio_chip *chip, unsigned offset)
{
struct htcpld_chip *chip_data;
chip_data = container_of(chip, struct htcpld_chip, chip_in);
if (offset < chip_data->nirqs)
return chip_data->irq_start + offset;
else
return -EINVAL;
}
static void htcpld_chip_reset(struct i2c_client *client)
{
struct htcpld_chip *chip_data = i2c_get_clientdata(client);
if (!chip_data)
return;
i2c_smbus_read_byte_data(
client, (chip_data->cache_out = chip_data->reset));
}
static int htcpld_setup_chip_irq(
struct platform_device *pdev,
int chip_index)
{
struct htcpld_data *htcpld;
struct device *dev = &pdev->dev;
struct htcpld_core_platform_data *pdata;
struct htcpld_chip *chip;
struct htcpld_chip_platform_data *plat_chip_data;
unsigned int irq, irq_end;
int ret = 0;
/* Get the platform and driver data */
pdata = dev->platform_data;
htcpld = platform_get_drvdata(pdev);
chip = &htcpld->chip[chip_index];
plat_chip_data = &pdata->chip[chip_index];
/* Setup irq handlers */
irq_end = chip->irq_start + chip->nirqs;
for (irq = chip->irq_start; irq < irq_end; irq++) {
irq_set_chip_and_handler(irq, &htcpld_muxed_chip,
handle_simple_irq);
irq_set_chip_data(irq, chip);
#ifdef CONFIG_ARM
set_irq_flags(irq, IRQF_VALID | IRQF_PROBE);
#else
irq_set_probe(irq);
#endif
}
return ret;
}
static int htcpld_register_chip_i2c(
struct platform_device *pdev,
int chip_index)
{
struct htcpld_data *htcpld;
struct device *dev = &pdev->dev;
struct htcpld_core_platform_data *pdata;
struct htcpld_chip *chip;
struct htcpld_chip_platform_data *plat_chip_data;
struct i2c_adapter *adapter;
struct i2c_client *client;
struct i2c_board_info info;
/* Get the platform and driver data */
pdata = dev->platform_data;
htcpld = platform_get_drvdata(pdev);
chip = &htcpld->chip[chip_index];
plat_chip_data = &pdata->chip[chip_index];
adapter = i2c_get_adapter(pdata->i2c_adapter_id);
if (adapter == NULL) {
/* Eek, no such I2C adapter! Bail out. */
dev_warn(dev, "Chip at i2c address 0x%x: Invalid i2c adapter %d\n",
plat_chip_data->addr, pdata->i2c_adapter_id);
return -ENODEV;
}
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_READ_BYTE_DATA)) {
dev_warn(dev, "i2c adapter %d non-functional\n",
pdata->i2c_adapter_id);
return -EINVAL;
}
memset(&info, 0, sizeof(struct i2c_board_info));
info.addr = plat_chip_data->addr;
strlcpy(info.type, "htcpld-chip", I2C_NAME_SIZE);
info.platform_data = chip;
/* Add the I2C device. This calls the probe() function. */
client = i2c_new_device(adapter, &info);
if (!client) {
/* I2C device registration failed, contineu with the next */
dev_warn(dev, "Unable to add I2C device for 0x%x\n",
plat_chip_data->addr);
return -ENODEV;
}
i2c_set_clientdata(client, chip);
snprintf(client->name, I2C_NAME_SIZE, "Chip_0x%d", client->addr);
chip->client = client;
/* Reset the chip */
htcpld_chip_reset(client);
chip->cache_in = i2c_smbus_read_byte_data(client, chip->cache_out);
return 0;
}
static void htcpld_unregister_chip_i2c(
struct platform_device *pdev,
int chip_index)
{
struct htcpld_data *htcpld;
struct htcpld_chip *chip;
/* Get the platform and driver data */
htcpld = platform_get_drvdata(pdev);
chip = &htcpld->chip[chip_index];
if (chip->client)
i2c_unregister_device(chip->client);
}
static int htcpld_register_chip_gpio(
struct platform_device *pdev,
int chip_index)
{
struct htcpld_data *htcpld;
struct device *dev = &pdev->dev;
struct htcpld_core_platform_data *pdata;
struct htcpld_chip *chip;
struct htcpld_chip_platform_data *plat_chip_data;
struct gpio_chip *gpio_chip;
int ret = 0;
/* Get the platform and driver data */
pdata = dev->platform_data;
htcpld = platform_get_drvdata(pdev);
chip = &htcpld->chip[chip_index];
plat_chip_data = &pdata->chip[chip_index];
/* Setup the GPIO chips */
gpio_chip = &(chip->chip_out);
gpio_chip->label = "htcpld-out";
gpio_chip->dev = dev;
gpio_chip->owner = THIS_MODULE;
gpio_chip->get = htcpld_chip_get;
gpio_chip->set = htcpld_chip_set;
gpio_chip->direction_input = NULL;
gpio_chip->direction_output = htcpld_direction_output;
gpio_chip->base = plat_chip_data->gpio_out_base;
gpio_chip->ngpio = plat_chip_data->num_gpios;
gpio_chip = &(chip->chip_in);
gpio_chip->label = "htcpld-in";
gpio_chip->dev = dev;
gpio_chip->owner = THIS_MODULE;
gpio_chip->get = htcpld_chip_get;
gpio_chip->set = NULL;
gpio_chip->direction_input = htcpld_direction_input;
gpio_chip->direction_output = NULL;
gpio_chip->to_irq = htcpld_chip_to_irq;
gpio_chip->base = plat_chip_data->gpio_in_base;
gpio_chip->ngpio = plat_chip_data->num_gpios;
/* Add the GPIO chips */
ret = gpiochip_add(&(chip->chip_out));
if (ret) {
dev_warn(dev, "Unable to register output GPIOs for 0x%x: %d\n",
plat_chip_data->addr, ret);
return ret;
}
ret = gpiochip_add(&(chip->chip_in));
if (ret) {
int error;
dev_warn(dev, "Unable to register input GPIOs for 0x%x: %d\n",
plat_chip_data->addr, ret);
error = gpiochip_remove(&(chip->chip_out));
if (error)
dev_warn(dev, "Error while trying to unregister gpio chip: %d\n", error);
return ret;
}
return 0;
}
static int htcpld_setup_chips(struct platform_device *pdev)
{
struct htcpld_data *htcpld;
struct device *dev = &pdev->dev;
struct htcpld_core_platform_data *pdata;
int i;
/* Get the platform and driver data */
pdata = dev->platform_data;
htcpld = platform_get_drvdata(pdev);
/* Setup each chip's output GPIOs */
htcpld->nchips = pdata->num_chip;
htcpld->chip = kzalloc(sizeof(struct htcpld_chip) * htcpld->nchips,
GFP_KERNEL);
if (!htcpld->chip) {
dev_warn(dev, "Unable to allocate memory for chips\n");
return -ENOMEM;
}
/* Add the chips as best we can */
for (i = 0; i < htcpld->nchips; i++) {
int ret;
/* Setup the HTCPLD chips */
htcpld->chip[i].reset = pdata->chip[i].reset;
htcpld->chip[i].cache_out = pdata->chip[i].reset;
htcpld->chip[i].cache_in = 0;
htcpld->chip[i].dev = dev;
htcpld->chip[i].irq_start = pdata->chip[i].irq_base;
htcpld->chip[i].nirqs = pdata->chip[i].num_irqs;
INIT_WORK(&(htcpld->chip[i].set_val_work), &htcpld_chip_set_ni);
spin_lock_init(&(htcpld->chip[i].lock));
/* Setup the interrupts for the chip */
if (htcpld->chained_irq) {
ret = htcpld_setup_chip_irq(pdev, i);
if (ret)
continue;
}
/* Register the chip with I2C */
ret = htcpld_register_chip_i2c(pdev, i);
if (ret)
continue;
/* Register the chips with the GPIO subsystem */
ret = htcpld_register_chip_gpio(pdev, i);
if (ret) {
/* Unregister the chip from i2c and continue */
htcpld_unregister_chip_i2c(pdev, i);
continue;
}
dev_info(dev, "Registered chip at 0x%x\n", pdata->chip[i].addr);
}
return 0;
}
static int htcpld_core_probe(struct platform_device *pdev)
{
struct htcpld_data *htcpld;
struct device *dev = &pdev->dev;
struct htcpld_core_platform_data *pdata;
struct resource *res;
int ret = 0;
if (!dev)
return -ENODEV;
pdata = dev->platform_data;
if (!pdata) {
dev_warn(dev, "Platform data not found for htcpld core!\n");
return -ENXIO;
}
htcpld = kzalloc(sizeof(struct htcpld_data), GFP_KERNEL);
if (!htcpld)
return -ENOMEM;
/* Find chained irq */
ret = -EINVAL;
res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (res) {
int flags;
htcpld->chained_irq = res->start;
/* Setup the chained interrupt handler */
flags = IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING;
ret = request_threaded_irq(htcpld->chained_irq,
NULL, htcpld_handler,
flags, pdev->name, htcpld);
if (ret) {
dev_warn(dev, "Unable to setup chained irq handler: %d\n", ret);
goto fail;
} else
device_init_wakeup(dev, 0);
}
/* Set the driver data */
platform_set_drvdata(pdev, htcpld);
/* Setup the htcpld chips */
ret = htcpld_setup_chips(pdev);
if (ret)
goto fail;
/* Request the GPIO(s) for the int reset and set them up */
if (pdata->int_reset_gpio_hi) {
ret = gpio_request(pdata->int_reset_gpio_hi, "htcpld-core");
if (ret) {
/*
* If it failed, that sucks, but we can probably
* continue on without it.
*/
dev_warn(dev, "Unable to request int_reset_gpio_hi -- interrupts may not work\n");
htcpld->int_reset_gpio_hi = 0;
} else {
htcpld->int_reset_gpio_hi = pdata->int_reset_gpio_hi;
gpio_set_value(htcpld->int_reset_gpio_hi, 1);
}
}
if (pdata->int_reset_gpio_lo) {
ret = gpio_request(pdata->int_reset_gpio_lo, "htcpld-core");
if (ret) {
/*
* If it failed, that sucks, but we can probably
* continue on without it.
*/
dev_warn(dev, "Unable to request int_reset_gpio_lo -- interrupts may not work\n");
htcpld->int_reset_gpio_lo = 0;
} else {
htcpld->int_reset_gpio_lo = pdata->int_reset_gpio_lo;
gpio_set_value(htcpld->int_reset_gpio_lo, 0);
}
}
dev_info(dev, "Initialized successfully\n");
return 0;
fail:
kfree(htcpld);
return ret;
}
/* The I2C Driver -- used internally */
static const struct i2c_device_id htcpld_chip_id[] = {
{ "htcpld-chip", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, htcpld_chip_id);
static struct i2c_driver htcpld_chip_driver = {
.driver = {
.name = "htcpld-chip",
},
.id_table = htcpld_chip_id,
};
/* The Core Driver */
static struct platform_driver htcpld_core_driver = {
.driver = {
.name = "i2c-htcpld",
},
};
static int __init htcpld_core_init(void)
{
int ret;
/* Register the I2C Chip driver */
ret = i2c_add_driver(&htcpld_chip_driver);
if (ret)
return ret;
/* Probe for our chips */
return platform_driver_probe(&htcpld_core_driver, htcpld_core_probe);
}
static void __exit htcpld_core_exit(void)
{
i2c_del_driver(&htcpld_chip_driver);
platform_driver_unregister(&htcpld_core_driver);
}
module_init(htcpld_core_init);
module_exit(htcpld_core_exit);
MODULE_AUTHOR("Cory Maccarrone <darkstar6262@gmail.com>");
MODULE_DESCRIPTION("I2C HTC PLD Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
DSMKexec/kexec-kernel-g720n0 | drivers/video/sm501fb.c | 2763 | 54451 | /* linux/drivers/video/sm501fb.c
*
* Copyright (c) 2006 Simtec Electronics
* Vincent Sanders <vince@simtec.co.uk>
* Ben Dooks <ben@simtec.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Framebuffer driver for the Silicon Motion SM501
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/tty.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/vmalloc.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <linux/workqueue.h>
#include <linux/wait.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/console.h>
#include <linux/io.h>
#include <asm/uaccess.h>
#include <asm/div64.h>
#ifdef CONFIG_PM
#include <linux/pm.h>
#endif
#include <linux/sm501.h>
#include <linux/sm501-regs.h>
#include "edid.h"
static char *fb_mode = "640x480-16@60";
static unsigned long default_bpp = 16;
static struct fb_videomode sm501_default_mode = {
.refresh = 60,
.xres = 640,
.yres = 480,
.pixclock = 20833,
.left_margin = 142,
.right_margin = 13,
.upper_margin = 21,
.lower_margin = 1,
.hsync_len = 69,
.vsync_len = 3,
.sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
.vmode = FB_VMODE_NONINTERLACED
};
#define NR_PALETTE 256
enum sm501_controller {
HEAD_CRT = 0,
HEAD_PANEL = 1,
};
/* SM501 memory address.
*
* This structure is used to track memory usage within the SM501 framebuffer
* allocation. The sm_addr field is stored as an offset as it is often used
* against both the physical and mapped addresses.
*/
struct sm501_mem {
unsigned long size;
unsigned long sm_addr; /* offset from base of sm501 fb. */
void __iomem *k_addr;
};
/* private data that is shared between all frambuffers* */
struct sm501fb_info {
struct device *dev;
struct fb_info *fb[2]; /* fb info for both heads */
struct resource *fbmem_res; /* framebuffer resource */
struct resource *regs_res; /* registers resource */
struct resource *regs2d_res; /* 2d registers resource */
struct sm501_platdata_fb *pdata; /* our platform data */
unsigned long pm_crt_ctrl; /* pm: crt ctrl save */
int irq;
int swap_endian; /* set to swap rgb=>bgr */
void __iomem *regs; /* remapped registers */
void __iomem *regs2d; /* 2d remapped registers */
void __iomem *fbmem; /* remapped framebuffer */
size_t fbmem_len; /* length of remapped region */
u8 *edid_data;
};
/* per-framebuffer private data */
struct sm501fb_par {
u32 pseudo_palette[16];
enum sm501_controller head;
struct sm501_mem cursor;
struct sm501_mem screen;
struct fb_ops ops;
void *store_fb;
void *store_cursor;
void __iomem *cursor_regs;
struct sm501fb_info *info;
};
/* Helper functions */
static inline int h_total(struct fb_var_screeninfo *var)
{
return var->xres + var->left_margin +
var->right_margin + var->hsync_len;
}
static inline int v_total(struct fb_var_screeninfo *var)
{
return var->yres + var->upper_margin +
var->lower_margin + var->vsync_len;
}
/* sm501fb_sync_regs()
*
* This call is mainly for PCI bus systems where we need to
* ensure that any writes to the bus are completed before the
* next phase, or after completing a function.
*/
static inline void sm501fb_sync_regs(struct sm501fb_info *info)
{
smc501_readl(info->regs);
}
/* sm501_alloc_mem
*
* This is an attempt to lay out memory for the two framebuffers and
* everything else
*
* |fbmem_res->start fbmem_res->end|
* | |
* |fb[0].fix.smem_start | |fb[1].fix.smem_start | 2K |
* |-> fb[0].fix.smem_len <-| spare |-> fb[1].fix.smem_len <-|-> cursors <-|
*
* The "spare" space is for the 2d engine data
* the fixed is space for the cursors (2x1Kbyte)
*
* we need to allocate memory for the 2D acceleration engine
* command list and the data for the engine to deal with.
*
* - all allocations must be 128bit aligned
* - cursors are 64x64x2 bits (1Kbyte)
*
*/
#define SM501_MEMF_CURSOR (1)
#define SM501_MEMF_PANEL (2)
#define SM501_MEMF_CRT (4)
#define SM501_MEMF_ACCEL (8)
static int sm501_alloc_mem(struct sm501fb_info *inf, struct sm501_mem *mem,
unsigned int why, size_t size, u32 smem_len)
{
struct sm501fb_par *par;
struct fb_info *fbi;
unsigned int ptr;
unsigned int end;
switch (why) {
case SM501_MEMF_CURSOR:
ptr = inf->fbmem_len - size;
inf->fbmem_len = ptr; /* adjust available memory. */
break;
case SM501_MEMF_PANEL:
if (size > inf->fbmem_len)
return -ENOMEM;
ptr = inf->fbmem_len - size;
fbi = inf->fb[HEAD_CRT];
/* round down, some programs such as directfb do not draw
* 0,0 correctly unless the start is aligned to a page start.
*/
if (ptr > 0)
ptr &= ~(PAGE_SIZE - 1);
if (fbi && ptr < smem_len)
return -ENOMEM;
break;
case SM501_MEMF_CRT:
ptr = 0;
/* check to see if we have panel memory allocated
* which would put an limit on available memory. */
fbi = inf->fb[HEAD_PANEL];
if (fbi) {
par = fbi->par;
end = par->screen.k_addr ? par->screen.sm_addr : inf->fbmem_len;
} else
end = inf->fbmem_len;
if ((ptr + size) > end)
return -ENOMEM;
break;
case SM501_MEMF_ACCEL:
fbi = inf->fb[HEAD_CRT];
ptr = fbi ? smem_len : 0;
fbi = inf->fb[HEAD_PANEL];
if (fbi) {
par = fbi->par;
end = par->screen.sm_addr;
} else
end = inf->fbmem_len;
if ((ptr + size) > end)
return -ENOMEM;
break;
default:
return -EINVAL;
}
mem->size = size;
mem->sm_addr = ptr;
mem->k_addr = inf->fbmem + ptr;
dev_dbg(inf->dev, "%s: result %08lx, %p - %u, %zd\n",
__func__, mem->sm_addr, mem->k_addr, why, size);
return 0;
}
/* sm501fb_ps_to_hz
*
* Converts a period in picoseconds to Hz.
*
* Note, we try to keep this in Hz to minimise rounding with
* the limited PLL settings on the SM501.
*/
static unsigned long sm501fb_ps_to_hz(unsigned long psvalue)
{
unsigned long long numerator=1000000000000ULL;
/* 10^12 / picosecond period gives frequency in Hz */
do_div(numerator, psvalue);
return (unsigned long)numerator;
}
/* sm501fb_hz_to_ps is identical to the opposite transform */
#define sm501fb_hz_to_ps(x) sm501fb_ps_to_hz(x)
/* sm501fb_setup_gamma
*
* Programs a linear 1.0 gamma ramp in case the gamma
* correction is enabled without programming anything else.
*/
static void sm501fb_setup_gamma(struct sm501fb_info *fbi,
unsigned long palette)
{
unsigned long value = 0;
int offset;
/* set gamma values */
for (offset = 0; offset < 256 * 4; offset += 4) {
smc501_writel(value, fbi->regs + palette + offset);
value += 0x010101; /* Advance RGB by 1,1,1.*/
}
}
/* sm501fb_check_var
*
* check common variables for both panel and crt
*/
static int sm501fb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct sm501fb_par *par = info->par;
struct sm501fb_info *sm = par->info;
unsigned long tmp;
/* check we can fit these values into the registers */
if (var->hsync_len > 255 || var->vsync_len > 63)
return -EINVAL;
/* hdisplay end and hsync start */
if ((var->xres + var->right_margin) > 4096)
return -EINVAL;
/* vdisplay end and vsync start */
if ((var->yres + var->lower_margin) > 2048)
return -EINVAL;
/* hard limits of device */
if (h_total(var) > 4096 || v_total(var) > 2048)
return -EINVAL;
/* check our line length is going to be 128 bit aligned */
tmp = (var->xres * var->bits_per_pixel) / 8;
if ((tmp & 15) != 0)
return -EINVAL;
/* check the virtual size */
if (var->xres_virtual > 4096 || var->yres_virtual > 2048)
return -EINVAL;
/* can cope with 8,16 or 32bpp */
if (var->bits_per_pixel <= 8)
var->bits_per_pixel = 8;
else if (var->bits_per_pixel <= 16)
var->bits_per_pixel = 16;
else if (var->bits_per_pixel == 24)
var->bits_per_pixel = 32;
/* set r/g/b positions and validate bpp */
switch(var->bits_per_pixel) {
case 8:
var->red.length = var->bits_per_pixel;
var->red.offset = 0;
var->green.length = var->bits_per_pixel;
var->green.offset = 0;
var->blue.length = var->bits_per_pixel;
var->blue.offset = 0;
var->transp.length = 0;
var->transp.offset = 0;
break;
case 16:
if (sm->pdata->flags & SM501_FBPD_SWAP_FB_ENDIAN) {
var->blue.offset = 11;
var->green.offset = 5;
var->red.offset = 0;
} else {
var->red.offset = 11;
var->green.offset = 5;
var->blue.offset = 0;
}
var->transp.offset = 0;
var->red.length = 5;
var->green.length = 6;
var->blue.length = 5;
var->transp.length = 0;
break;
case 32:
if (sm->pdata->flags & SM501_FBPD_SWAP_FB_ENDIAN) {
var->transp.offset = 0;
var->red.offset = 8;
var->green.offset = 16;
var->blue.offset = 24;
} else {
var->transp.offset = 24;
var->red.offset = 16;
var->green.offset = 8;
var->blue.offset = 0;
}
var->red.length = 8;
var->green.length = 8;
var->blue.length = 8;
var->transp.length = 0;
break;
default:
return -EINVAL;
}
return 0;
}
/*
* sm501fb_check_var_crt():
*
* check the parameters for the CRT head, and either bring them
* back into range, or return -EINVAL.
*/
static int sm501fb_check_var_crt(struct fb_var_screeninfo *var,
struct fb_info *info)
{
return sm501fb_check_var(var, info);
}
/* sm501fb_check_var_pnl():
*
* check the parameters for the CRT head, and either bring them
* back into range, or return -EINVAL.
*/
static int sm501fb_check_var_pnl(struct fb_var_screeninfo *var,
struct fb_info *info)
{
return sm501fb_check_var(var, info);
}
/* sm501fb_set_par_common
*
* set common registers for framebuffers
*/
static int sm501fb_set_par_common(struct fb_info *info,
struct fb_var_screeninfo *var)
{
struct sm501fb_par *par = info->par;
struct sm501fb_info *fbi = par->info;
unsigned long pixclock; /* pixelclock in Hz */
unsigned long sm501pixclock; /* pixelclock the 501 can achieve in Hz */
unsigned int mem_type;
unsigned int clock_type;
unsigned int head_addr;
unsigned int smem_len;
dev_dbg(fbi->dev, "%s: %dx%d, bpp = %d, virtual %dx%d\n",
__func__, var->xres, var->yres, var->bits_per_pixel,
var->xres_virtual, var->yres_virtual);
switch (par->head) {
case HEAD_CRT:
mem_type = SM501_MEMF_CRT;
clock_type = SM501_CLOCK_V2XCLK;
head_addr = SM501_DC_CRT_FB_ADDR;
break;
case HEAD_PANEL:
mem_type = SM501_MEMF_PANEL;
clock_type = SM501_CLOCK_P2XCLK;
head_addr = SM501_DC_PANEL_FB_ADDR;
break;
default:
mem_type = 0; /* stop compiler warnings */
head_addr = 0;
clock_type = 0;
}
switch (var->bits_per_pixel) {
case 8:
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
break;
case 16:
info->fix.visual = FB_VISUAL_TRUECOLOR;
break;
case 32:
info->fix.visual = FB_VISUAL_TRUECOLOR;
break;
}
/* allocate fb memory within 501 */
info->fix.line_length = (var->xres_virtual * var->bits_per_pixel)/8;
smem_len = info->fix.line_length * var->yres_virtual;
dev_dbg(fbi->dev, "%s: line length = %u\n", __func__,
info->fix.line_length);
if (sm501_alloc_mem(fbi, &par->screen, mem_type, smem_len, smem_len)) {
dev_err(fbi->dev, "no memory available\n");
return -ENOMEM;
}
mutex_lock(&info->mm_lock);
info->fix.smem_start = fbi->fbmem_res->start + par->screen.sm_addr;
info->fix.smem_len = smem_len;
mutex_unlock(&info->mm_lock);
info->screen_base = fbi->fbmem + par->screen.sm_addr;
info->screen_size = info->fix.smem_len;
/* set start of framebuffer to the screen */
smc501_writel(par->screen.sm_addr | SM501_ADDR_FLIP,
fbi->regs + head_addr);
/* program CRT clock */
pixclock = sm501fb_ps_to_hz(var->pixclock);
sm501pixclock = sm501_set_clock(fbi->dev->parent, clock_type,
pixclock);
/* update fb layer with actual clock used */
var->pixclock = sm501fb_hz_to_ps(sm501pixclock);
dev_dbg(fbi->dev, "%s: pixclock(ps) = %u, pixclock(Hz) = %lu, "
"sm501pixclock = %lu, error = %ld%%\n",
__func__, var->pixclock, pixclock, sm501pixclock,
((pixclock - sm501pixclock)*100)/pixclock);
return 0;
}
/* sm501fb_set_par_geometry
*
* set the geometry registers for specified framebuffer.
*/
static void sm501fb_set_par_geometry(struct fb_info *info,
struct fb_var_screeninfo *var)
{
struct sm501fb_par *par = info->par;
struct sm501fb_info *fbi = par->info;
void __iomem *base = fbi->regs;
unsigned long reg;
if (par->head == HEAD_CRT)
base += SM501_DC_CRT_H_TOT;
else
base += SM501_DC_PANEL_H_TOT;
/* set framebuffer width and display width */
reg = info->fix.line_length;
reg |= ((var->xres * var->bits_per_pixel)/8) << 16;
smc501_writel(reg, fbi->regs + (par->head == HEAD_CRT ?
SM501_DC_CRT_FB_OFFSET : SM501_DC_PANEL_FB_OFFSET));
/* program horizontal total */
reg = (h_total(var) - 1) << 16;
reg |= (var->xres - 1);
smc501_writel(reg, base + SM501_OFF_DC_H_TOT);
/* program horizontal sync */
reg = var->hsync_len << 16;
reg |= var->xres + var->right_margin - 1;
smc501_writel(reg, base + SM501_OFF_DC_H_SYNC);
/* program vertical total */
reg = (v_total(var) - 1) << 16;
reg |= (var->yres - 1);
smc501_writel(reg, base + SM501_OFF_DC_V_TOT);
/* program vertical sync */
reg = var->vsync_len << 16;
reg |= var->yres + var->lower_margin - 1;
smc501_writel(reg, base + SM501_OFF_DC_V_SYNC);
}
/* sm501fb_pan_crt
*
* pan the CRT display output within an virtual framebuffer
*/
static int sm501fb_pan_crt(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct sm501fb_par *par = info->par;
struct sm501fb_info *fbi = par->info;
unsigned int bytes_pixel = info->var.bits_per_pixel / 8;
unsigned long reg;
unsigned long xoffs;
xoffs = var->xoffset * bytes_pixel;
reg = smc501_readl(fbi->regs + SM501_DC_CRT_CONTROL);
reg &= ~SM501_DC_CRT_CONTROL_PIXEL_MASK;
reg |= ((xoffs & 15) / bytes_pixel) << 4;
smc501_writel(reg, fbi->regs + SM501_DC_CRT_CONTROL);
reg = (par->screen.sm_addr + xoffs +
var->yoffset * info->fix.line_length);
smc501_writel(reg | SM501_ADDR_FLIP, fbi->regs + SM501_DC_CRT_FB_ADDR);
sm501fb_sync_regs(fbi);
return 0;
}
/* sm501fb_pan_pnl
*
* pan the panel display output within an virtual framebuffer
*/
static int sm501fb_pan_pnl(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct sm501fb_par *par = info->par;
struct sm501fb_info *fbi = par->info;
unsigned long reg;
reg = var->xoffset | (info->var.xres_virtual << 16);
smc501_writel(reg, fbi->regs + SM501_DC_PANEL_FB_WIDTH);
reg = var->yoffset | (info->var.yres_virtual << 16);
smc501_writel(reg, fbi->regs + SM501_DC_PANEL_FB_HEIGHT);
sm501fb_sync_regs(fbi);
return 0;
}
/* sm501fb_set_par_crt
*
* Set the CRT video mode from the fb_info structure
*/
static int sm501fb_set_par_crt(struct fb_info *info)
{
struct sm501fb_par *par = info->par;
struct sm501fb_info *fbi = par->info;
struct fb_var_screeninfo *var = &info->var;
unsigned long control; /* control register */
int ret;
/* activate new configuration */
dev_dbg(fbi->dev, "%s(%p)\n", __func__, info);
/* enable CRT DAC - note 0 is on!*/
sm501_misc_control(fbi->dev->parent, 0, SM501_MISC_DAC_POWER);
control = smc501_readl(fbi->regs + SM501_DC_CRT_CONTROL);
control &= (SM501_DC_CRT_CONTROL_PIXEL_MASK |
SM501_DC_CRT_CONTROL_GAMMA |
SM501_DC_CRT_CONTROL_BLANK |
SM501_DC_CRT_CONTROL_SEL |
SM501_DC_CRT_CONTROL_CP |
SM501_DC_CRT_CONTROL_TVP);
/* set the sync polarities before we check data source */
if ((var->sync & FB_SYNC_HOR_HIGH_ACT) == 0)
control |= SM501_DC_CRT_CONTROL_HSP;
if ((var->sync & FB_SYNC_VERT_HIGH_ACT) == 0)
control |= SM501_DC_CRT_CONTROL_VSP;
if ((control & SM501_DC_CRT_CONTROL_SEL) == 0) {
/* the head is displaying panel data... */
sm501_alloc_mem(fbi, &par->screen, SM501_MEMF_CRT, 0,
info->fix.smem_len);
goto out_update;
}
ret = sm501fb_set_par_common(info, var);
if (ret) {
dev_err(fbi->dev, "failed to set common parameters\n");
return ret;
}
sm501fb_pan_crt(var, info);
sm501fb_set_par_geometry(info, var);
control |= SM501_FIFO_3; /* fill if >3 free slots */
switch(var->bits_per_pixel) {
case 8:
control |= SM501_DC_CRT_CONTROL_8BPP;
break;
case 16:
control |= SM501_DC_CRT_CONTROL_16BPP;
sm501fb_setup_gamma(fbi, SM501_DC_CRT_PALETTE);
break;
case 32:
control |= SM501_DC_CRT_CONTROL_32BPP;
sm501fb_setup_gamma(fbi, SM501_DC_CRT_PALETTE);
break;
default:
BUG();
}
control |= SM501_DC_CRT_CONTROL_SEL; /* CRT displays CRT data */
control |= SM501_DC_CRT_CONTROL_TE; /* enable CRT timing */
control |= SM501_DC_CRT_CONTROL_ENABLE; /* enable CRT plane */
out_update:
dev_dbg(fbi->dev, "new control is %08lx\n", control);
smc501_writel(control, fbi->regs + SM501_DC_CRT_CONTROL);
sm501fb_sync_regs(fbi);
return 0;
}
static void sm501fb_panel_power(struct sm501fb_info *fbi, int to)
{
unsigned long control;
void __iomem *ctrl_reg = fbi->regs + SM501_DC_PANEL_CONTROL;
struct sm501_platdata_fbsub *pd = fbi->pdata->fb_pnl;
control = smc501_readl(ctrl_reg);
if (to && (control & SM501_DC_PANEL_CONTROL_VDD) == 0) {
/* enable panel power */
control |= SM501_DC_PANEL_CONTROL_VDD; /* FPVDDEN */
smc501_writel(control, ctrl_reg);
sm501fb_sync_regs(fbi);
mdelay(10);
control |= SM501_DC_PANEL_CONTROL_DATA; /* DATA */
smc501_writel(control, ctrl_reg);
sm501fb_sync_regs(fbi);
mdelay(10);
/* VBIASEN */
if (!(pd->flags & SM501FB_FLAG_PANEL_NO_VBIASEN)) {
if (pd->flags & SM501FB_FLAG_PANEL_INV_VBIASEN)
control &= ~SM501_DC_PANEL_CONTROL_BIAS;
else
control |= SM501_DC_PANEL_CONTROL_BIAS;
smc501_writel(control, ctrl_reg);
sm501fb_sync_regs(fbi);
mdelay(10);
}
if (!(pd->flags & SM501FB_FLAG_PANEL_NO_FPEN)) {
if (pd->flags & SM501FB_FLAG_PANEL_INV_FPEN)
control &= ~SM501_DC_PANEL_CONTROL_FPEN;
else
control |= SM501_DC_PANEL_CONTROL_FPEN;
smc501_writel(control, ctrl_reg);
sm501fb_sync_regs(fbi);
mdelay(10);
}
} else if (!to && (control & SM501_DC_PANEL_CONTROL_VDD) != 0) {
/* disable panel power */
if (!(pd->flags & SM501FB_FLAG_PANEL_NO_FPEN)) {
if (pd->flags & SM501FB_FLAG_PANEL_INV_FPEN)
control |= SM501_DC_PANEL_CONTROL_FPEN;
else
control &= ~SM501_DC_PANEL_CONTROL_FPEN;
smc501_writel(control, ctrl_reg);
sm501fb_sync_regs(fbi);
mdelay(10);
}
if (!(pd->flags & SM501FB_FLAG_PANEL_NO_VBIASEN)) {
if (pd->flags & SM501FB_FLAG_PANEL_INV_VBIASEN)
control |= SM501_DC_PANEL_CONTROL_BIAS;
else
control &= ~SM501_DC_PANEL_CONTROL_BIAS;
smc501_writel(control, ctrl_reg);
sm501fb_sync_regs(fbi);
mdelay(10);
}
control &= ~SM501_DC_PANEL_CONTROL_DATA;
smc501_writel(control, ctrl_reg);
sm501fb_sync_regs(fbi);
mdelay(10);
control &= ~SM501_DC_PANEL_CONTROL_VDD;
smc501_writel(control, ctrl_reg);
sm501fb_sync_regs(fbi);
mdelay(10);
}
sm501fb_sync_regs(fbi);
}
/* sm501fb_set_par_pnl
*
* Set the panel video mode from the fb_info structure
*/
static int sm501fb_set_par_pnl(struct fb_info *info)
{
struct sm501fb_par *par = info->par;
struct sm501fb_info *fbi = par->info;
struct fb_var_screeninfo *var = &info->var;
unsigned long control;
unsigned long reg;
int ret;
dev_dbg(fbi->dev, "%s(%p)\n", __func__, info);
/* activate this new configuration */
ret = sm501fb_set_par_common(info, var);
if (ret)
return ret;
sm501fb_pan_pnl(var, info);
sm501fb_set_par_geometry(info, var);
/* update control register */
control = smc501_readl(fbi->regs + SM501_DC_PANEL_CONTROL);
control &= (SM501_DC_PANEL_CONTROL_GAMMA |
SM501_DC_PANEL_CONTROL_VDD |
SM501_DC_PANEL_CONTROL_DATA |
SM501_DC_PANEL_CONTROL_BIAS |
SM501_DC_PANEL_CONTROL_FPEN |
SM501_DC_PANEL_CONTROL_CP |
SM501_DC_PANEL_CONTROL_CK |
SM501_DC_PANEL_CONTROL_HP |
SM501_DC_PANEL_CONTROL_VP |
SM501_DC_PANEL_CONTROL_HPD |
SM501_DC_PANEL_CONTROL_VPD);
control |= SM501_FIFO_3; /* fill if >3 free slots */
switch(var->bits_per_pixel) {
case 8:
control |= SM501_DC_PANEL_CONTROL_8BPP;
break;
case 16:
control |= SM501_DC_PANEL_CONTROL_16BPP;
sm501fb_setup_gamma(fbi, SM501_DC_PANEL_PALETTE);
break;
case 32:
control |= SM501_DC_PANEL_CONTROL_32BPP;
sm501fb_setup_gamma(fbi, SM501_DC_PANEL_PALETTE);
break;
default:
BUG();
}
smc501_writel(0x0, fbi->regs + SM501_DC_PANEL_PANNING_CONTROL);
/* panel plane top left and bottom right location */
smc501_writel(0x00, fbi->regs + SM501_DC_PANEL_TL_LOC);
reg = var->xres - 1;
reg |= (var->yres - 1) << 16;
smc501_writel(reg, fbi->regs + SM501_DC_PANEL_BR_LOC);
/* program panel control register */
control |= SM501_DC_PANEL_CONTROL_TE; /* enable PANEL timing */
control |= SM501_DC_PANEL_CONTROL_EN; /* enable PANEL gfx plane */
if ((var->sync & FB_SYNC_HOR_HIGH_ACT) == 0)
control |= SM501_DC_PANEL_CONTROL_HSP;
if ((var->sync & FB_SYNC_VERT_HIGH_ACT) == 0)
control |= SM501_DC_PANEL_CONTROL_VSP;
smc501_writel(control, fbi->regs + SM501_DC_PANEL_CONTROL);
sm501fb_sync_regs(fbi);
/* ensure the panel interface is not tristated at this point */
sm501_modify_reg(fbi->dev->parent, SM501_SYSTEM_CONTROL,
0, SM501_SYSCTRL_PANEL_TRISTATE);
/* power the panel up */
sm501fb_panel_power(fbi, 1);
return 0;
}
/* chan_to_field
*
* convert a colour value into a field position
*
* from pxafb.c
*/
static inline unsigned int chan_to_field(unsigned int chan,
struct fb_bitfield *bf)
{
chan &= 0xffff;
chan >>= 16 - bf->length;
return chan << bf->offset;
}
/* sm501fb_setcolreg
*
* set the colour mapping for modes that support palettised data
*/
static int sm501fb_setcolreg(unsigned regno,
unsigned red, unsigned green, unsigned blue,
unsigned transp, struct fb_info *info)
{
struct sm501fb_par *par = info->par;
struct sm501fb_info *fbi = par->info;
void __iomem *base = fbi->regs;
unsigned int val;
if (par->head == HEAD_CRT)
base += SM501_DC_CRT_PALETTE;
else
base += SM501_DC_PANEL_PALETTE;
switch (info->fix.visual) {
case FB_VISUAL_TRUECOLOR:
/* true-colour, use pseuo-palette */
if (regno < 16) {
u32 *pal = par->pseudo_palette;
val = chan_to_field(red, &info->var.red);
val |= chan_to_field(green, &info->var.green);
val |= chan_to_field(blue, &info->var.blue);
pal[regno] = val;
}
break;
case FB_VISUAL_PSEUDOCOLOR:
if (regno < 256) {
val = (red >> 8) << 16;
val |= (green >> 8) << 8;
val |= blue >> 8;
smc501_writel(val, base + (regno * 4));
}
break;
default:
return 1; /* unknown type */
}
return 0;
}
/* sm501fb_blank_pnl
*
* Blank or un-blank the panel interface
*/
static int sm501fb_blank_pnl(int blank_mode, struct fb_info *info)
{
struct sm501fb_par *par = info->par;
struct sm501fb_info *fbi = par->info;
dev_dbg(fbi->dev, "%s(mode=%d, %p)\n", __func__, blank_mode, info);
switch (blank_mode) {
case FB_BLANK_POWERDOWN:
sm501fb_panel_power(fbi, 0);
break;
case FB_BLANK_UNBLANK:
sm501fb_panel_power(fbi, 1);
break;
case FB_BLANK_NORMAL:
case FB_BLANK_VSYNC_SUSPEND:
case FB_BLANK_HSYNC_SUSPEND:
default:
return 1;
}
return 0;
}
/* sm501fb_blank_crt
*
* Blank or un-blank the crt interface
*/
static int sm501fb_blank_crt(int blank_mode, struct fb_info *info)
{
struct sm501fb_par *par = info->par;
struct sm501fb_info *fbi = par->info;
unsigned long ctrl;
dev_dbg(fbi->dev, "%s(mode=%d, %p)\n", __func__, blank_mode, info);
ctrl = smc501_readl(fbi->regs + SM501_DC_CRT_CONTROL);
switch (blank_mode) {
case FB_BLANK_POWERDOWN:
ctrl &= ~SM501_DC_CRT_CONTROL_ENABLE;
sm501_misc_control(fbi->dev->parent, SM501_MISC_DAC_POWER, 0);
case FB_BLANK_NORMAL:
ctrl |= SM501_DC_CRT_CONTROL_BLANK;
break;
case FB_BLANK_UNBLANK:
ctrl &= ~SM501_DC_CRT_CONTROL_BLANK;
ctrl |= SM501_DC_CRT_CONTROL_ENABLE;
sm501_misc_control(fbi->dev->parent, 0, SM501_MISC_DAC_POWER);
break;
case FB_BLANK_VSYNC_SUSPEND:
case FB_BLANK_HSYNC_SUSPEND:
default:
return 1;
}
smc501_writel(ctrl, fbi->regs + SM501_DC_CRT_CONTROL);
sm501fb_sync_regs(fbi);
return 0;
}
/* sm501fb_cursor
*
* set or change the hardware cursor parameters
*/
static int sm501fb_cursor(struct fb_info *info, struct fb_cursor *cursor)
{
struct sm501fb_par *par = info->par;
struct sm501fb_info *fbi = par->info;
void __iomem *base = fbi->regs;
unsigned long hwc_addr;
unsigned long fg, bg;
dev_dbg(fbi->dev, "%s(%p,%p)\n", __func__, info, cursor);
if (par->head == HEAD_CRT)
base += SM501_DC_CRT_HWC_BASE;
else
base += SM501_DC_PANEL_HWC_BASE;
/* check not being asked to exceed capabilities */
if (cursor->image.width > 64)
return -EINVAL;
if (cursor->image.height > 64)
return -EINVAL;
if (cursor->image.depth > 1)
return -EINVAL;
hwc_addr = smc501_readl(base + SM501_OFF_HWC_ADDR);
if (cursor->enable)
smc501_writel(hwc_addr | SM501_HWC_EN,
base + SM501_OFF_HWC_ADDR);
else
smc501_writel(hwc_addr & ~SM501_HWC_EN,
base + SM501_OFF_HWC_ADDR);
/* set data */
if (cursor->set & FB_CUR_SETPOS) {
unsigned int x = cursor->image.dx;
unsigned int y = cursor->image.dy;
if (x >= 2048 || y >= 2048 )
return -EINVAL;
dev_dbg(fbi->dev, "set position %d,%d\n", x, y);
//y += cursor->image.height;
smc501_writel(x | (y << 16), base + SM501_OFF_HWC_LOC);
}
if (cursor->set & FB_CUR_SETCMAP) {
unsigned int bg_col = cursor->image.bg_color;
unsigned int fg_col = cursor->image.fg_color;
dev_dbg(fbi->dev, "%s: update cmap (%08x,%08x)\n",
__func__, bg_col, fg_col);
bg = ((info->cmap.red[bg_col] & 0xF8) << 8) |
((info->cmap.green[bg_col] & 0xFC) << 3) |
((info->cmap.blue[bg_col] & 0xF8) >> 3);
fg = ((info->cmap.red[fg_col] & 0xF8) << 8) |
((info->cmap.green[fg_col] & 0xFC) << 3) |
((info->cmap.blue[fg_col] & 0xF8) >> 3);
dev_dbg(fbi->dev, "fgcol %08lx, bgcol %08lx\n", fg, bg);
smc501_writel(bg, base + SM501_OFF_HWC_COLOR_1_2);
smc501_writel(fg, base + SM501_OFF_HWC_COLOR_3);
}
if (cursor->set & FB_CUR_SETSIZE ||
cursor->set & (FB_CUR_SETIMAGE | FB_CUR_SETSHAPE)) {
/* SM501 cursor is a two bpp 64x64 bitmap this routine
* clears it to transparent then combines the cursor
* shape plane with the colour plane to set the
* cursor */
int x, y;
const unsigned char *pcol = cursor->image.data;
const unsigned char *pmsk = cursor->mask;
void __iomem *dst = par->cursor.k_addr;
unsigned char dcol = 0;
unsigned char dmsk = 0;
unsigned int op;
dev_dbg(fbi->dev, "%s: setting shape (%d,%d)\n",
__func__, cursor->image.width, cursor->image.height);
for (op = 0; op < (64*64*2)/8; op+=4)
smc501_writel(0x0, dst + op);
for (y = 0; y < cursor->image.height; y++) {
for (x = 0; x < cursor->image.width; x++) {
if ((x % 8) == 0) {
dcol = *pcol++;
dmsk = *pmsk++;
} else {
dcol >>= 1;
dmsk >>= 1;
}
if (dmsk & 1) {
op = (dcol & 1) ? 1 : 3;
op <<= ((x % 4) * 2);
op |= readb(dst + (x / 4));
writeb(op, dst + (x / 4));
}
}
dst += (64*2)/8;
}
}
sm501fb_sync_regs(fbi); /* ensure cursor data flushed */
return 0;
}
/* sm501fb_crtsrc_show
*
* device attribute code to show where the crt output is sourced from
*/
static ssize_t sm501fb_crtsrc_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct sm501fb_info *info = dev_get_drvdata(dev);
unsigned long ctrl;
ctrl = smc501_readl(info->regs + SM501_DC_CRT_CONTROL);
ctrl &= SM501_DC_CRT_CONTROL_SEL;
return snprintf(buf, PAGE_SIZE, "%s\n", ctrl ? "crt" : "panel");
}
/* sm501fb_crtsrc_show
*
* device attribute code to set where the crt output is sourced from
*/
static ssize_t sm501fb_crtsrc_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct sm501fb_info *info = dev_get_drvdata(dev);
enum sm501_controller head;
unsigned long ctrl;
if (len < 1)
return -EINVAL;
if (strnicmp(buf, "crt", 3) == 0)
head = HEAD_CRT;
else if (strnicmp(buf, "panel", 5) == 0)
head = HEAD_PANEL;
else
return -EINVAL;
dev_info(dev, "setting crt source to head %d\n", head);
ctrl = smc501_readl(info->regs + SM501_DC_CRT_CONTROL);
if (head == HEAD_CRT) {
ctrl |= SM501_DC_CRT_CONTROL_SEL;
ctrl |= SM501_DC_CRT_CONTROL_ENABLE;
ctrl |= SM501_DC_CRT_CONTROL_TE;
} else {
ctrl &= ~SM501_DC_CRT_CONTROL_SEL;
ctrl &= ~SM501_DC_CRT_CONTROL_ENABLE;
ctrl &= ~SM501_DC_CRT_CONTROL_TE;
}
smc501_writel(ctrl, info->regs + SM501_DC_CRT_CONTROL);
sm501fb_sync_regs(info);
return len;
}
/* Prepare the device_attr for registration with sysfs later */
static DEVICE_ATTR(crt_src, 0666, sm501fb_crtsrc_show, sm501fb_crtsrc_store);
/* sm501fb_show_regs
*
* show the primary sm501 registers
*/
static int sm501fb_show_regs(struct sm501fb_info *info, char *ptr,
unsigned int start, unsigned int len)
{
void __iomem *mem = info->regs;
char *buf = ptr;
unsigned int reg;
for (reg = start; reg < (len + start); reg += 4)
ptr += sprintf(ptr, "%08x = %08x\n", reg,
smc501_readl(mem + reg));
return ptr - buf;
}
/* sm501fb_debug_show_crt
*
* show the crt control and cursor registers
*/
static ssize_t sm501fb_debug_show_crt(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct sm501fb_info *info = dev_get_drvdata(dev);
char *ptr = buf;
ptr += sm501fb_show_regs(info, ptr, SM501_DC_CRT_CONTROL, 0x40);
ptr += sm501fb_show_regs(info, ptr, SM501_DC_CRT_HWC_BASE, 0x10);
return ptr - buf;
}
static DEVICE_ATTR(fbregs_crt, 0444, sm501fb_debug_show_crt, NULL);
/* sm501fb_debug_show_pnl
*
* show the panel control and cursor registers
*/
static ssize_t sm501fb_debug_show_pnl(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct sm501fb_info *info = dev_get_drvdata(dev);
char *ptr = buf;
ptr += sm501fb_show_regs(info, ptr, 0x0, 0x40);
ptr += sm501fb_show_regs(info, ptr, SM501_DC_PANEL_HWC_BASE, 0x10);
return ptr - buf;
}
static DEVICE_ATTR(fbregs_pnl, 0444, sm501fb_debug_show_pnl, NULL);
/* acceleration operations */
static int sm501fb_sync(struct fb_info *info)
{
int count = 1000000;
struct sm501fb_par *par = info->par;
struct sm501fb_info *fbi = par->info;
/* wait for the 2d engine to be ready */
while ((count > 0) &&
(smc501_readl(fbi->regs + SM501_SYSTEM_CONTROL) &
SM501_SYSCTRL_2D_ENGINE_STATUS) != 0)
count--;
if (count <= 0) {
dev_err(info->dev, "Timeout waiting for 2d engine sync\n");
return 1;
}
return 0;
}
static void sm501fb_copyarea(struct fb_info *info, const struct fb_copyarea *area)
{
struct sm501fb_par *par = info->par;
struct sm501fb_info *fbi = par->info;
int width = area->width;
int height = area->height;
int sx = area->sx;
int sy = area->sy;
int dx = area->dx;
int dy = area->dy;
unsigned long rtl = 0;
/* source clip */
if ((sx >= info->var.xres_virtual) ||
(sy >= info->var.yres_virtual))
/* source Area not within virtual screen, skipping */
return;
if ((sx + width) >= info->var.xres_virtual)
width = info->var.xres_virtual - sx - 1;
if ((sy + height) >= info->var.yres_virtual)
height = info->var.yres_virtual - sy - 1;
/* dest clip */
if ((dx >= info->var.xres_virtual) ||
(dy >= info->var.yres_virtual))
/* Destination Area not within virtual screen, skipping */
return;
if ((dx + width) >= info->var.xres_virtual)
width = info->var.xres_virtual - dx - 1;
if ((dy + height) >= info->var.yres_virtual)
height = info->var.yres_virtual - dy - 1;
if ((sx < dx) || (sy < dy)) {
rtl = 1 << 27;
sx += width - 1;
dx += width - 1;
sy += height - 1;
dy += height - 1;
}
if (sm501fb_sync(info))
return;
/* set the base addresses */
smc501_writel(par->screen.sm_addr, fbi->regs2d + SM501_2D_SOURCE_BASE);
smc501_writel(par->screen.sm_addr,
fbi->regs2d + SM501_2D_DESTINATION_BASE);
/* set the window width */
smc501_writel((info->var.xres << 16) | info->var.xres,
fbi->regs2d + SM501_2D_WINDOW_WIDTH);
/* set window stride */
smc501_writel((info->var.xres_virtual << 16) | info->var.xres_virtual,
fbi->regs2d + SM501_2D_PITCH);
/* set data format */
switch (info->var.bits_per_pixel) {
case 8:
smc501_writel(0, fbi->regs2d + SM501_2D_STRETCH);
break;
case 16:
smc501_writel(0x00100000, fbi->regs2d + SM501_2D_STRETCH);
break;
case 32:
smc501_writel(0x00200000, fbi->regs2d + SM501_2D_STRETCH);
break;
}
/* 2d compare mask */
smc501_writel(0xffffffff, fbi->regs2d + SM501_2D_COLOR_COMPARE_MASK);
/* 2d mask */
smc501_writel(0xffffffff, fbi->regs2d + SM501_2D_MASK);
/* source and destination x y */
smc501_writel((sx << 16) | sy, fbi->regs2d + SM501_2D_SOURCE);
smc501_writel((dx << 16) | dy, fbi->regs2d + SM501_2D_DESTINATION);
/* w/h */
smc501_writel((width << 16) | height, fbi->regs2d + SM501_2D_DIMENSION);
/* do area move */
smc501_writel(0x800000cc | rtl, fbi->regs2d + SM501_2D_CONTROL);
}
static void sm501fb_fillrect(struct fb_info *info, const struct fb_fillrect *rect)
{
struct sm501fb_par *par = info->par;
struct sm501fb_info *fbi = par->info;
int width = rect->width, height = rect->height;
if ((rect->dx >= info->var.xres_virtual) ||
(rect->dy >= info->var.yres_virtual))
/* Rectangle not within virtual screen, skipping */
return;
if ((rect->dx + width) >= info->var.xres_virtual)
width = info->var.xres_virtual - rect->dx - 1;
if ((rect->dy + height) >= info->var.yres_virtual)
height = info->var.yres_virtual - rect->dy - 1;
if (sm501fb_sync(info))
return;
/* set the base addresses */
smc501_writel(par->screen.sm_addr, fbi->regs2d + SM501_2D_SOURCE_BASE);
smc501_writel(par->screen.sm_addr,
fbi->regs2d + SM501_2D_DESTINATION_BASE);
/* set the window width */
smc501_writel((info->var.xres << 16) | info->var.xres,
fbi->regs2d + SM501_2D_WINDOW_WIDTH);
/* set window stride */
smc501_writel((info->var.xres_virtual << 16) | info->var.xres_virtual,
fbi->regs2d + SM501_2D_PITCH);
/* set data format */
switch (info->var.bits_per_pixel) {
case 8:
smc501_writel(0, fbi->regs2d + SM501_2D_STRETCH);
break;
case 16:
smc501_writel(0x00100000, fbi->regs2d + SM501_2D_STRETCH);
break;
case 32:
smc501_writel(0x00200000, fbi->regs2d + SM501_2D_STRETCH);
break;
}
/* 2d compare mask */
smc501_writel(0xffffffff, fbi->regs2d + SM501_2D_COLOR_COMPARE_MASK);
/* 2d mask */
smc501_writel(0xffffffff, fbi->regs2d + SM501_2D_MASK);
/* colour */
smc501_writel(rect->color, fbi->regs2d + SM501_2D_FOREGROUND);
/* x y */
smc501_writel((rect->dx << 16) | rect->dy,
fbi->regs2d + SM501_2D_DESTINATION);
/* w/h */
smc501_writel((width << 16) | height, fbi->regs2d + SM501_2D_DIMENSION);
/* do rectangle fill */
smc501_writel(0x800100cc, fbi->regs2d + SM501_2D_CONTROL);
}
static struct fb_ops sm501fb_ops_crt = {
.owner = THIS_MODULE,
.fb_check_var = sm501fb_check_var_crt,
.fb_set_par = sm501fb_set_par_crt,
.fb_blank = sm501fb_blank_crt,
.fb_setcolreg = sm501fb_setcolreg,
.fb_pan_display = sm501fb_pan_crt,
.fb_cursor = sm501fb_cursor,
.fb_fillrect = sm501fb_fillrect,
.fb_copyarea = sm501fb_copyarea,
.fb_imageblit = cfb_imageblit,
.fb_sync = sm501fb_sync,
};
static struct fb_ops sm501fb_ops_pnl = {
.owner = THIS_MODULE,
.fb_check_var = sm501fb_check_var_pnl,
.fb_set_par = sm501fb_set_par_pnl,
.fb_pan_display = sm501fb_pan_pnl,
.fb_blank = sm501fb_blank_pnl,
.fb_setcolreg = sm501fb_setcolreg,
.fb_cursor = sm501fb_cursor,
.fb_fillrect = sm501fb_fillrect,
.fb_copyarea = sm501fb_copyarea,
.fb_imageblit = cfb_imageblit,
.fb_sync = sm501fb_sync,
};
/* sm501_init_cursor
*
* initialise hw cursor parameters
*/
static int sm501_init_cursor(struct fb_info *fbi, unsigned int reg_base)
{
struct sm501fb_par *par;
struct sm501fb_info *info;
int ret;
if (fbi == NULL)
return 0;
par = fbi->par;
info = par->info;
par->cursor_regs = info->regs + reg_base;
ret = sm501_alloc_mem(info, &par->cursor, SM501_MEMF_CURSOR, 1024,
fbi->fix.smem_len);
if (ret < 0)
return ret;
/* initialise the colour registers */
smc501_writel(par->cursor.sm_addr,
par->cursor_regs + SM501_OFF_HWC_ADDR);
smc501_writel(0x00, par->cursor_regs + SM501_OFF_HWC_LOC);
smc501_writel(0x00, par->cursor_regs + SM501_OFF_HWC_COLOR_1_2);
smc501_writel(0x00, par->cursor_regs + SM501_OFF_HWC_COLOR_3);
sm501fb_sync_regs(info);
return 0;
}
/* sm501fb_info_start
*
* fills the par structure claiming resources and remapping etc.
*/
static int sm501fb_start(struct sm501fb_info *info,
struct platform_device *pdev)
{
struct resource *res;
struct device *dev = &pdev->dev;
int k;
int ret;
info->irq = ret = platform_get_irq(pdev, 0);
if (ret < 0) {
/* we currently do not use the IRQ */
dev_warn(dev, "no irq for device\n");
}
/* allocate, reserve and remap resources for display
* controller registers */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res == NULL) {
dev_err(dev, "no resource definition for registers\n");
ret = -ENOENT;
goto err_release;
}
info->regs_res = request_mem_region(res->start,
resource_size(res),
pdev->name);
if (info->regs_res == NULL) {
dev_err(dev, "cannot claim registers\n");
ret = -ENXIO;
goto err_release;
}
info->regs = ioremap(res->start, resource_size(res));
if (info->regs == NULL) {
dev_err(dev, "cannot remap registers\n");
ret = -ENXIO;
goto err_regs_res;
}
/* allocate, reserve and remap resources for 2d
* controller registers */
res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (res == NULL) {
dev_err(dev, "no resource definition for 2d registers\n");
ret = -ENOENT;
goto err_regs_map;
}
info->regs2d_res = request_mem_region(res->start,
resource_size(res),
pdev->name);
if (info->regs2d_res == NULL) {
dev_err(dev, "cannot claim registers\n");
ret = -ENXIO;
goto err_regs_map;
}
info->regs2d = ioremap(res->start, resource_size(res));
if (info->regs2d == NULL) {
dev_err(dev, "cannot remap registers\n");
ret = -ENXIO;
goto err_regs2d_res;
}
/* allocate, reserve resources for framebuffer */
res = platform_get_resource(pdev, IORESOURCE_MEM, 2);
if (res == NULL) {
dev_err(dev, "no memory resource defined\n");
ret = -ENXIO;
goto err_regs2d_map;
}
info->fbmem_res = request_mem_region(res->start,
resource_size(res),
pdev->name);
if (info->fbmem_res == NULL) {
dev_err(dev, "cannot claim framebuffer\n");
ret = -ENXIO;
goto err_regs2d_map;
}
info->fbmem = ioremap(res->start, resource_size(res));
if (info->fbmem == NULL) {
dev_err(dev, "cannot remap framebuffer\n");
goto err_mem_res;
}
info->fbmem_len = resource_size(res);
/* clear framebuffer memory - avoids garbage data on unused fb */
memset(info->fbmem, 0, info->fbmem_len);
/* clear palette ram - undefined at power on */
for (k = 0; k < (256 * 3); k++)
smc501_writel(0, info->regs + SM501_DC_PANEL_PALETTE + (k * 4));
/* enable display controller */
sm501_unit_power(dev->parent, SM501_GATE_DISPLAY, 1);
/* enable 2d controller */
sm501_unit_power(dev->parent, SM501_GATE_2D_ENGINE, 1);
/* setup cursors */
sm501_init_cursor(info->fb[HEAD_CRT], SM501_DC_CRT_HWC_ADDR);
sm501_init_cursor(info->fb[HEAD_PANEL], SM501_DC_PANEL_HWC_ADDR);
return 0; /* everything is setup */
err_mem_res:
release_mem_region(info->fbmem_res->start,
resource_size(info->fbmem_res));
err_regs2d_map:
iounmap(info->regs2d);
err_regs2d_res:
release_mem_region(info->regs2d_res->start,
resource_size(info->regs2d_res));
err_regs_map:
iounmap(info->regs);
err_regs_res:
release_mem_region(info->regs_res->start,
resource_size(info->regs_res));
err_release:
return ret;
}
static void sm501fb_stop(struct sm501fb_info *info)
{
/* disable display controller */
sm501_unit_power(info->dev->parent, SM501_GATE_DISPLAY, 0);
iounmap(info->fbmem);
release_mem_region(info->fbmem_res->start,
resource_size(info->fbmem_res));
iounmap(info->regs2d);
release_mem_region(info->regs2d_res->start,
resource_size(info->regs2d_res));
iounmap(info->regs);
release_mem_region(info->regs_res->start,
resource_size(info->regs_res));
}
static int sm501fb_init_fb(struct fb_info *fb, enum sm501_controller head,
const char *fbname)
{
struct sm501_platdata_fbsub *pd;
struct sm501fb_par *par = fb->par;
struct sm501fb_info *info = par->info;
unsigned long ctrl;
unsigned int enable;
int ret;
switch (head) {
case HEAD_CRT:
pd = info->pdata->fb_crt;
ctrl = smc501_readl(info->regs + SM501_DC_CRT_CONTROL);
enable = (ctrl & SM501_DC_CRT_CONTROL_ENABLE) ? 1 : 0;
/* ensure we set the correct source register */
if (info->pdata->fb_route != SM501_FB_CRT_PANEL) {
ctrl |= SM501_DC_CRT_CONTROL_SEL;
smc501_writel(ctrl, info->regs + SM501_DC_CRT_CONTROL);
}
break;
case HEAD_PANEL:
pd = info->pdata->fb_pnl;
ctrl = smc501_readl(info->regs + SM501_DC_PANEL_CONTROL);
enable = (ctrl & SM501_DC_PANEL_CONTROL_EN) ? 1 : 0;
break;
default:
pd = NULL; /* stop compiler warnings */
ctrl = 0;
enable = 0;
BUG();
}
dev_info(info->dev, "fb %s %sabled at start\n",
fbname, enable ? "en" : "dis");
/* check to see if our routing allows this */
if (head == HEAD_CRT && info->pdata->fb_route == SM501_FB_CRT_PANEL) {
ctrl &= ~SM501_DC_CRT_CONTROL_SEL;
smc501_writel(ctrl, info->regs + SM501_DC_CRT_CONTROL);
enable = 0;
}
strlcpy(fb->fix.id, fbname, sizeof(fb->fix.id));
memcpy(&par->ops,
(head == HEAD_CRT) ? &sm501fb_ops_crt : &sm501fb_ops_pnl,
sizeof(struct fb_ops));
/* update ops dependent on what we've been passed */
if ((pd->flags & SM501FB_FLAG_USE_HWCURSOR) == 0)
par->ops.fb_cursor = NULL;
fb->fbops = &par->ops;
fb->flags = FBINFO_FLAG_DEFAULT | FBINFO_READS_FAST |
FBINFO_HWACCEL_COPYAREA | FBINFO_HWACCEL_FILLRECT |
FBINFO_HWACCEL_XPAN | FBINFO_HWACCEL_YPAN;
#if defined(CONFIG_OF)
#ifdef __BIG_ENDIAN
if (of_get_property(info->dev->parent->of_node, "little-endian", NULL))
fb->flags |= FBINFO_FOREIGN_ENDIAN;
#else
if (of_get_property(info->dev->parent->of_node, "big-endian", NULL))
fb->flags |= FBINFO_FOREIGN_ENDIAN;
#endif
#endif
/* fixed data */
fb->fix.type = FB_TYPE_PACKED_PIXELS;
fb->fix.type_aux = 0;
fb->fix.xpanstep = 1;
fb->fix.ypanstep = 1;
fb->fix.ywrapstep = 0;
fb->fix.accel = FB_ACCEL_NONE;
/* screenmode */
fb->var.nonstd = 0;
fb->var.activate = FB_ACTIVATE_NOW;
fb->var.accel_flags = 0;
fb->var.vmode = FB_VMODE_NONINTERLACED;
fb->var.bits_per_pixel = 16;
if (info->edid_data) {
/* Now build modedb from EDID */
fb_edid_to_monspecs(info->edid_data, &fb->monspecs);
fb_videomode_to_modelist(fb->monspecs.modedb,
fb->monspecs.modedb_len,
&fb->modelist);
}
if (enable && (pd->flags & SM501FB_FLAG_USE_INIT_MODE) && 0) {
/* TODO read the mode from the current display */
} else {
if (pd->def_mode) {
dev_info(info->dev, "using supplied mode\n");
fb_videomode_to_var(&fb->var, pd->def_mode);
fb->var.bits_per_pixel = pd->def_bpp ? pd->def_bpp : 8;
fb->var.xres_virtual = fb->var.xres;
fb->var.yres_virtual = fb->var.yres;
} else {
if (info->edid_data) {
ret = fb_find_mode(&fb->var, fb, fb_mode,
fb->monspecs.modedb,
fb->monspecs.modedb_len,
&sm501_default_mode, default_bpp);
/* edid_data is no longer needed, free it */
kfree(info->edid_data);
} else {
ret = fb_find_mode(&fb->var, fb,
NULL, NULL, 0, NULL, 8);
}
switch (ret) {
case 1:
dev_info(info->dev, "using mode specified in "
"@mode\n");
break;
case 2:
dev_info(info->dev, "using mode specified in "
"@mode with ignored refresh rate\n");
break;
case 3:
dev_info(info->dev, "using mode default "
"mode\n");
break;
case 4:
dev_info(info->dev, "using mode from list\n");
break;
default:
dev_info(info->dev, "ret = %d\n", ret);
dev_info(info->dev, "failed to find mode\n");
return -EINVAL;
}
}
}
/* initialise and set the palette */
if (fb_alloc_cmap(&fb->cmap, NR_PALETTE, 0)) {
dev_err(info->dev, "failed to allocate cmap memory\n");
return -ENOMEM;
}
fb_set_cmap(&fb->cmap, fb);
ret = (fb->fbops->fb_check_var)(&fb->var, fb);
if (ret)
dev_err(info->dev, "check_var() failed on initial setup?\n");
return 0;
}
/* default platform data if none is supplied (ie, PCI device) */
static struct sm501_platdata_fbsub sm501fb_pdata_crt = {
.flags = (SM501FB_FLAG_USE_INIT_MODE |
SM501FB_FLAG_USE_HWCURSOR |
SM501FB_FLAG_USE_HWACCEL |
SM501FB_FLAG_DISABLE_AT_EXIT),
};
static struct sm501_platdata_fbsub sm501fb_pdata_pnl = {
.flags = (SM501FB_FLAG_USE_INIT_MODE |
SM501FB_FLAG_USE_HWCURSOR |
SM501FB_FLAG_USE_HWACCEL |
SM501FB_FLAG_DISABLE_AT_EXIT),
};
static struct sm501_platdata_fb sm501fb_def_pdata = {
.fb_route = SM501_FB_OWN,
.fb_crt = &sm501fb_pdata_crt,
.fb_pnl = &sm501fb_pdata_pnl,
};
static char driver_name_crt[] = "sm501fb-crt";
static char driver_name_pnl[] = "sm501fb-panel";
static int sm501fb_probe_one(struct sm501fb_info *info,
enum sm501_controller head)
{
unsigned char *name = (head == HEAD_CRT) ? "crt" : "panel";
struct sm501_platdata_fbsub *pd;
struct sm501fb_par *par;
struct fb_info *fbi;
pd = (head == HEAD_CRT) ? info->pdata->fb_crt : info->pdata->fb_pnl;
/* Do not initialise if we've not been given any platform data */
if (pd == NULL) {
dev_info(info->dev, "no data for fb %s (disabled)\n", name);
return 0;
}
fbi = framebuffer_alloc(sizeof(struct sm501fb_par), info->dev);
if (fbi == NULL) {
dev_err(info->dev, "cannot allocate %s framebuffer\n", name);
return -ENOMEM;
}
par = fbi->par;
par->info = info;
par->head = head;
fbi->pseudo_palette = &par->pseudo_palette;
info->fb[head] = fbi;
return 0;
}
/* Free up anything allocated by sm501fb_init_fb */
static void sm501_free_init_fb(struct sm501fb_info *info,
enum sm501_controller head)
{
struct fb_info *fbi = info->fb[head];
fb_dealloc_cmap(&fbi->cmap);
}
static int sm501fb_start_one(struct sm501fb_info *info,
enum sm501_controller head, const char *drvname)
{
struct fb_info *fbi = info->fb[head];
int ret;
if (!fbi)
return 0;
mutex_init(&info->fb[head]->mm_lock);
ret = sm501fb_init_fb(info->fb[head], head, drvname);
if (ret) {
dev_err(info->dev, "cannot initialise fb %s\n", drvname);
return ret;
}
ret = register_framebuffer(info->fb[head]);
if (ret) {
dev_err(info->dev, "failed to register fb %s\n", drvname);
sm501_free_init_fb(info, head);
return ret;
}
dev_info(info->dev, "fb%d: %s frame buffer\n", fbi->node, fbi->fix.id);
return 0;
}
static int sm501fb_probe(struct platform_device *pdev)
{
struct sm501fb_info *info;
struct device *dev = &pdev->dev;
int ret;
/* allocate our framebuffers */
info = kzalloc(sizeof(struct sm501fb_info), GFP_KERNEL);
if (!info) {
dev_err(dev, "failed to allocate state\n");
return -ENOMEM;
}
info->dev = dev = &pdev->dev;
platform_set_drvdata(pdev, info);
if (dev->parent->platform_data) {
struct sm501_platdata *pd = dev->parent->platform_data;
info->pdata = pd->fb;
}
if (info->pdata == NULL) {
int found = 0;
#if defined(CONFIG_OF)
struct device_node *np = pdev->dev.parent->of_node;
const u8 *prop;
const char *cp;
int len;
info->pdata = &sm501fb_def_pdata;
if (np) {
/* Get EDID */
cp = of_get_property(np, "mode", &len);
if (cp)
strcpy(fb_mode, cp);
prop = of_get_property(np, "edid", &len);
if (prop && len == EDID_LENGTH) {
info->edid_data = kmemdup(prop, EDID_LENGTH,
GFP_KERNEL);
if (info->edid_data)
found = 1;
}
}
#endif
if (!found) {
dev_info(dev, "using default configuration data\n");
info->pdata = &sm501fb_def_pdata;
}
}
/* probe for the presence of each panel */
ret = sm501fb_probe_one(info, HEAD_CRT);
if (ret < 0) {
dev_err(dev, "failed to probe CRT\n");
goto err_alloc;
}
ret = sm501fb_probe_one(info, HEAD_PANEL);
if (ret < 0) {
dev_err(dev, "failed to probe PANEL\n");
goto err_probed_crt;
}
if (info->fb[HEAD_PANEL] == NULL &&
info->fb[HEAD_CRT] == NULL) {
dev_err(dev, "no framebuffers found\n");
goto err_alloc;
}
/* get the resources for both of the framebuffers */
ret = sm501fb_start(info, pdev);
if (ret) {
dev_err(dev, "cannot initialise SM501\n");
goto err_probed_panel;
}
ret = sm501fb_start_one(info, HEAD_CRT, driver_name_crt);
if (ret) {
dev_err(dev, "failed to start CRT\n");
goto err_started;
}
ret = sm501fb_start_one(info, HEAD_PANEL, driver_name_pnl);
if (ret) {
dev_err(dev, "failed to start Panel\n");
goto err_started_crt;
}
/* create device files */
ret = device_create_file(dev, &dev_attr_crt_src);
if (ret)
goto err_started_panel;
ret = device_create_file(dev, &dev_attr_fbregs_pnl);
if (ret)
goto err_attached_crtsrc_file;
ret = device_create_file(dev, &dev_attr_fbregs_crt);
if (ret)
goto err_attached_pnlregs_file;
/* we registered, return ok */
return 0;
err_attached_pnlregs_file:
device_remove_file(dev, &dev_attr_fbregs_pnl);
err_attached_crtsrc_file:
device_remove_file(dev, &dev_attr_crt_src);
err_started_panel:
unregister_framebuffer(info->fb[HEAD_PANEL]);
sm501_free_init_fb(info, HEAD_PANEL);
err_started_crt:
unregister_framebuffer(info->fb[HEAD_CRT]);
sm501_free_init_fb(info, HEAD_CRT);
err_started:
sm501fb_stop(info);
err_probed_panel:
framebuffer_release(info->fb[HEAD_PANEL]);
err_probed_crt:
framebuffer_release(info->fb[HEAD_CRT]);
err_alloc:
kfree(info);
return ret;
}
/*
* Cleanup
*/
static int sm501fb_remove(struct platform_device *pdev)
{
struct sm501fb_info *info = platform_get_drvdata(pdev);
struct fb_info *fbinfo_crt = info->fb[0];
struct fb_info *fbinfo_pnl = info->fb[1];
device_remove_file(&pdev->dev, &dev_attr_fbregs_crt);
device_remove_file(&pdev->dev, &dev_attr_fbregs_pnl);
device_remove_file(&pdev->dev, &dev_attr_crt_src);
sm501_free_init_fb(info, HEAD_CRT);
sm501_free_init_fb(info, HEAD_PANEL);
unregister_framebuffer(fbinfo_crt);
unregister_framebuffer(fbinfo_pnl);
sm501fb_stop(info);
kfree(info);
framebuffer_release(fbinfo_pnl);
framebuffer_release(fbinfo_crt);
return 0;
}
#ifdef CONFIG_PM
static int sm501fb_suspend_fb(struct sm501fb_info *info,
enum sm501_controller head)
{
struct fb_info *fbi = info->fb[head];
struct sm501fb_par *par = fbi->par;
if (par->screen.size == 0)
return 0;
/* blank the relevant interface to ensure unit power minimised */
(par->ops.fb_blank)(FB_BLANK_POWERDOWN, fbi);
/* tell console/fb driver we are suspending */
console_lock();
fb_set_suspend(fbi, 1);
console_unlock();
/* backup copies in case chip is powered down over suspend */
par->store_fb = vmalloc(par->screen.size);
if (par->store_fb == NULL) {
dev_err(info->dev, "no memory to store screen\n");
return -ENOMEM;
}
par->store_cursor = vmalloc(par->cursor.size);
if (par->store_cursor == NULL) {
dev_err(info->dev, "no memory to store cursor\n");
goto err_nocursor;
}
dev_dbg(info->dev, "suspending screen to %p\n", par->store_fb);
dev_dbg(info->dev, "suspending cursor to %p\n", par->store_cursor);
memcpy_fromio(par->store_fb, par->screen.k_addr, par->screen.size);
memcpy_fromio(par->store_cursor, par->cursor.k_addr, par->cursor.size);
return 0;
err_nocursor:
vfree(par->store_fb);
par->store_fb = NULL;
return -ENOMEM;
}
static void sm501fb_resume_fb(struct sm501fb_info *info,
enum sm501_controller head)
{
struct fb_info *fbi = info->fb[head];
struct sm501fb_par *par = fbi->par;
if (par->screen.size == 0)
return;
/* re-activate the configuration */
(par->ops.fb_set_par)(fbi);
/* restore the data */
dev_dbg(info->dev, "restoring screen from %p\n", par->store_fb);
dev_dbg(info->dev, "restoring cursor from %p\n", par->store_cursor);
if (par->store_fb)
memcpy_toio(par->screen.k_addr, par->store_fb,
par->screen.size);
if (par->store_cursor)
memcpy_toio(par->cursor.k_addr, par->store_cursor,
par->cursor.size);
console_lock();
fb_set_suspend(fbi, 0);
console_unlock();
vfree(par->store_fb);
vfree(par->store_cursor);
}
/* suspend and resume support */
static int sm501fb_suspend(struct platform_device *pdev, pm_message_t state)
{
struct sm501fb_info *info = platform_get_drvdata(pdev);
/* store crt control to resume with */
info->pm_crt_ctrl = smc501_readl(info->regs + SM501_DC_CRT_CONTROL);
sm501fb_suspend_fb(info, HEAD_CRT);
sm501fb_suspend_fb(info, HEAD_PANEL);
/* turn off the clocks, in case the device is not powered down */
sm501_unit_power(info->dev->parent, SM501_GATE_DISPLAY, 0);
return 0;
}
#define SM501_CRT_CTRL_SAVE (SM501_DC_CRT_CONTROL_TVP | \
SM501_DC_CRT_CONTROL_SEL)
static int sm501fb_resume(struct platform_device *pdev)
{
struct sm501fb_info *info = platform_get_drvdata(pdev);
unsigned long crt_ctrl;
sm501_unit_power(info->dev->parent, SM501_GATE_DISPLAY, 1);
/* restore the items we want to be saved for crt control */
crt_ctrl = smc501_readl(info->regs + SM501_DC_CRT_CONTROL);
crt_ctrl &= ~SM501_CRT_CTRL_SAVE;
crt_ctrl |= info->pm_crt_ctrl & SM501_CRT_CTRL_SAVE;
smc501_writel(crt_ctrl, info->regs + SM501_DC_CRT_CONTROL);
sm501fb_resume_fb(info, HEAD_CRT);
sm501fb_resume_fb(info, HEAD_PANEL);
return 0;
}
#else
#define sm501fb_suspend NULL
#define sm501fb_resume NULL
#endif
static struct platform_driver sm501fb_driver = {
.probe = sm501fb_probe,
.remove = sm501fb_remove,
.suspend = sm501fb_suspend,
.resume = sm501fb_resume,
.driver = {
.name = "sm501-fb",
.owner = THIS_MODULE,
},
};
module_platform_driver(sm501fb_driver);
module_param_named(mode, fb_mode, charp, 0);
MODULE_PARM_DESC(mode,
"Specify resolution as \"<xres>x<yres>[-<bpp>][@<refresh>]\" ");
module_param_named(bpp, default_bpp, ulong, 0);
MODULE_PARM_DESC(bpp, "Specify bit-per-pixel if not specified mode");
MODULE_AUTHOR("Ben Dooks, Vincent Sanders");
MODULE_DESCRIPTION("SM501 Framebuffer driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
NovaFusion/android_kernel_samsung_codina | sound/core/misc.c | 2763 | 3821 | /*
* Misc and compatibility things
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/init.h>
#include <linux/time.h>
#include <linux/slab.h>
#include <linux/ioport.h>
#include <sound/core.h>
#ifdef CONFIG_SND_DEBUG
#ifdef CONFIG_SND_DEBUG_VERBOSE
#define DEFAULT_DEBUG_LEVEL 2
#else
#define DEFAULT_DEBUG_LEVEL 1
#endif
static int debug = DEFAULT_DEBUG_LEVEL;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Debug level (0 = disable)");
#endif /* CONFIG_SND_DEBUG */
void release_and_free_resource(struct resource *res)
{
if (res) {
release_resource(res);
kfree(res);
}
}
EXPORT_SYMBOL(release_and_free_resource);
#ifdef CONFIG_SND_VERBOSE_PRINTK
/* strip the leading path if the given path is absolute */
static const char *sanity_file_name(const char *path)
{
if (*path == '/')
return strrchr(path, '/') + 1;
else
return path;
}
#endif
#if defined(CONFIG_SND_DEBUG) || defined(CONFIG_SND_VERBOSE_PRINTK)
void __snd_printk(unsigned int level, const char *path, int line,
const char *format, ...)
{
va_list args;
#ifdef CONFIG_SND_VERBOSE_PRINTK
struct va_format vaf;
char verbose_fmt[] = KERN_DEFAULT "ALSA %s:%d %pV";
#endif
#ifdef CONFIG_SND_DEBUG
if (debug < level)
return;
#endif
va_start(args, format);
#ifdef CONFIG_SND_VERBOSE_PRINTK
vaf.fmt = format;
vaf.va = &args;
if (format[0] == '<' && format[2] == '>') {
memcpy(verbose_fmt, format, 3);
vaf.fmt = format + 3;
} else if (level)
memcpy(verbose_fmt, KERN_DEBUG, 3);
printk(verbose_fmt, sanity_file_name(path), line, &vaf);
#else
vprintk(format, args);
#endif
va_end(args);
}
EXPORT_SYMBOL_GPL(__snd_printk);
#endif
#ifdef CONFIG_PCI
#include <linux/pci.h>
/**
* snd_pci_quirk_lookup_id - look up a PCI SSID quirk list
* @vendor: PCI SSV id
* @device: PCI SSD id
* @list: quirk list, terminated by a null entry
*
* Look through the given quirk list and finds a matching entry
* with the same PCI SSID. When subdevice is 0, all subdevice
* values may match.
*
* Returns the matched entry pointer, or NULL if nothing matched.
*/
const struct snd_pci_quirk *
snd_pci_quirk_lookup_id(u16 vendor, u16 device,
const struct snd_pci_quirk *list)
{
const struct snd_pci_quirk *q;
for (q = list; q->subvendor; q++) {
if (q->subvendor != vendor)
continue;
if (!q->subdevice ||
(device & q->subdevice_mask) == q->subdevice)
return q;
}
return NULL;
}
EXPORT_SYMBOL(snd_pci_quirk_lookup_id);
/**
* snd_pci_quirk_lookup - look up a PCI SSID quirk list
* @pci: pci_dev handle
* @list: quirk list, terminated by a null entry
*
* Look through the given quirk list and finds a matching entry
* with the same PCI SSID. When subdevice is 0, all subdevice
* values may match.
*
* Returns the matched entry pointer, or NULL if nothing matched.
*/
const struct snd_pci_quirk *
snd_pci_quirk_lookup(struct pci_dev *pci, const struct snd_pci_quirk *list)
{
return snd_pci_quirk_lookup_id(pci->subsystem_vendor,
pci->subsystem_device,
list);
}
EXPORT_SYMBOL(snd_pci_quirk_lookup);
#endif
| gpl-2.0 |
ajopanoor/popcorn | drivers/hwmon/lm63.c | 3275 | 21125 | /*
* lm63.c - driver for the National Semiconductor LM63 temperature sensor
* with integrated fan control
* Copyright (C) 2004-2008 Jean Delvare <khali@linux-fr.org>
* Based on the lm90 driver.
*
* The LM63 is a sensor chip made by National Semiconductor. It measures
* two temperatures (its own and one external one) and the speed of one
* fan, those speed it can additionally control. Complete datasheet can be
* obtained from National's website at:
* http://www.national.com/pf/LM/LM63.html
*
* The LM63 is basically an LM86 with fan speed monitoring and control
* capabilities added. It misses some of the LM86 features though:
* - No low limit for local temperature.
* - No critical limit for local temperature.
* - Critical limit for remote temperature can be changed only once. We
* will consider that the critical limit is read-only.
*
* The datasheet isn't very clear about what the tachometer reading is.
* I had a explanation from National Semiconductor though. The two lower
* bits of the read value have to be masked out. The value is still 16 bit
* in width.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon-sysfs.h>
#include <linux/hwmon.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/sysfs.h>
/*
* Addresses to scan
* Address is fully defined internally and cannot be changed.
*/
static const unsigned short normal_i2c[] = { 0x18, 0x4c, 0x4e, I2C_CLIENT_END };
/*
* The LM63 registers
*/
#define LM63_REG_CONFIG1 0x03
#define LM63_REG_CONFIG2 0xBF
#define LM63_REG_CONFIG_FAN 0x4A
#define LM63_REG_TACH_COUNT_MSB 0x47
#define LM63_REG_TACH_COUNT_LSB 0x46
#define LM63_REG_TACH_LIMIT_MSB 0x49
#define LM63_REG_TACH_LIMIT_LSB 0x48
#define LM63_REG_PWM_VALUE 0x4C
#define LM63_REG_PWM_FREQ 0x4D
#define LM63_REG_LOCAL_TEMP 0x00
#define LM63_REG_LOCAL_HIGH 0x05
#define LM63_REG_REMOTE_TEMP_MSB 0x01
#define LM63_REG_REMOTE_TEMP_LSB 0x10
#define LM63_REG_REMOTE_OFFSET_MSB 0x11
#define LM63_REG_REMOTE_OFFSET_LSB 0x12
#define LM63_REG_REMOTE_HIGH_MSB 0x07
#define LM63_REG_REMOTE_HIGH_LSB 0x13
#define LM63_REG_REMOTE_LOW_MSB 0x08
#define LM63_REG_REMOTE_LOW_LSB 0x14
#define LM63_REG_REMOTE_TCRIT 0x19
#define LM63_REG_REMOTE_TCRIT_HYST 0x21
#define LM63_REG_ALERT_STATUS 0x02
#define LM63_REG_ALERT_MASK 0x16
#define LM63_REG_MAN_ID 0xFE
#define LM63_REG_CHIP_ID 0xFF
/*
* Conversions and various macros
* For tachometer counts, the LM63 uses 16-bit values.
* For local temperature and high limit, remote critical limit and hysteresis
* value, it uses signed 8-bit values with LSB = 1 degree Celsius.
* For remote temperature, low and high limits, it uses signed 11-bit values
* with LSB = 0.125 degree Celsius, left-justified in 16-bit registers.
* For LM64 the actual remote diode temperature is 16 degree Celsius higher
* than the register reading. Remote temperature setpoints have to be
* adapted accordingly.
*/
#define FAN_FROM_REG(reg) ((reg) == 0xFFFC || (reg) == 0 ? 0 : \
5400000 / (reg))
#define FAN_TO_REG(val) ((val) <= 82 ? 0xFFFC : \
(5400000 / (val)) & 0xFFFC)
#define TEMP8_FROM_REG(reg) ((reg) * 1000)
#define TEMP8_TO_REG(val) ((val) <= -128000 ? -128 : \
(val) >= 127000 ? 127 : \
(val) < 0 ? ((val) - 500) / 1000 : \
((val) + 500) / 1000)
#define TEMP11_FROM_REG(reg) ((reg) / 32 * 125)
#define TEMP11_TO_REG(val) ((val) <= -128000 ? 0x8000 : \
(val) >= 127875 ? 0x7FE0 : \
(val) < 0 ? ((val) - 62) / 125 * 32 : \
((val) + 62) / 125 * 32)
#define HYST_TO_REG(val) ((val) <= 0 ? 0 : \
(val) >= 127000 ? 127 : \
((val) + 500) / 1000)
/*
* Functions declaration
*/
static int lm63_probe(struct i2c_client *client,
const struct i2c_device_id *id);
static int lm63_remove(struct i2c_client *client);
static struct lm63_data *lm63_update_device(struct device *dev);
static int lm63_detect(struct i2c_client *client, struct i2c_board_info *info);
static void lm63_init_client(struct i2c_client *client);
enum chips { lm63, lm64 };
/*
* Driver data (common to all clients)
*/
static const struct i2c_device_id lm63_id[] = {
{ "lm63", lm63 },
{ "lm64", lm64 },
{ }
};
MODULE_DEVICE_TABLE(i2c, lm63_id);
static struct i2c_driver lm63_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "lm63",
},
.probe = lm63_probe,
.remove = lm63_remove,
.id_table = lm63_id,
.detect = lm63_detect,
.address_list = normal_i2c,
};
/*
* Client data (each client gets its own)
*/
struct lm63_data {
struct device *hwmon_dev;
struct mutex update_lock;
char valid; /* zero until following fields are valid */
unsigned long last_updated; /* in jiffies */
int kind;
int temp2_offset;
/* registers values */
u8 config, config_fan;
u16 fan[2]; /* 0: input
1: low limit */
u8 pwm1_freq;
u8 pwm1_value;
s8 temp8[3]; /* 0: local input
1: local high limit
2: remote critical limit */
s16 temp11[3]; /* 0: remote input
1: remote low limit
2: remote high limit */
u8 temp2_crit_hyst;
u8 alarms;
};
/*
* Sysfs callback functions and files
*/
static ssize_t show_fan(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct lm63_data *data = lm63_update_device(dev);
return sprintf(buf, "%d\n", FAN_FROM_REG(data->fan[attr->index]));
}
static ssize_t set_fan(struct device *dev, struct device_attribute *dummy,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm63_data *data = i2c_get_clientdata(client);
unsigned long val = simple_strtoul(buf, NULL, 10);
mutex_lock(&data->update_lock);
data->fan[1] = FAN_TO_REG(val);
i2c_smbus_write_byte_data(client, LM63_REG_TACH_LIMIT_LSB,
data->fan[1] & 0xFF);
i2c_smbus_write_byte_data(client, LM63_REG_TACH_LIMIT_MSB,
data->fan[1] >> 8);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm1(struct device *dev, struct device_attribute *dummy,
char *buf)
{
struct lm63_data *data = lm63_update_device(dev);
return sprintf(buf, "%d\n", data->pwm1_value >= 2 * data->pwm1_freq ?
255 : (data->pwm1_value * 255 + data->pwm1_freq) /
(2 * data->pwm1_freq));
}
static ssize_t set_pwm1(struct device *dev, struct device_attribute *dummy,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm63_data *data = i2c_get_clientdata(client);
unsigned long val;
if (!(data->config_fan & 0x20)) /* register is read-only */
return -EPERM;
val = simple_strtoul(buf, NULL, 10);
mutex_lock(&data->update_lock);
data->pwm1_value = val <= 0 ? 0 :
val >= 255 ? 2 * data->pwm1_freq :
(val * data->pwm1_freq * 2 + 127) / 255;
i2c_smbus_write_byte_data(client, LM63_REG_PWM_VALUE, data->pwm1_value);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm1_enable(struct device *dev, struct device_attribute *dummy,
char *buf)
{
struct lm63_data *data = lm63_update_device(dev);
return sprintf(buf, "%d\n", data->config_fan & 0x20 ? 1 : 2);
}
/*
* There are 8bit registers for both local(temp1) and remote(temp2) sensor.
* For remote sensor registers temp2_offset has to be considered,
* for local sensor it must not.
* So we need separate 8bit accessors for local and remote sensor.
*/
static ssize_t show_local_temp8(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct lm63_data *data = lm63_update_device(dev);
return sprintf(buf, "%d\n", TEMP8_FROM_REG(data->temp8[attr->index]));
}
static ssize_t show_remote_temp8(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct lm63_data *data = lm63_update_device(dev);
return sprintf(buf, "%d\n", TEMP8_FROM_REG(data->temp8[attr->index])
+ data->temp2_offset);
}
static ssize_t set_local_temp8(struct device *dev,
struct device_attribute *dummy,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm63_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
mutex_lock(&data->update_lock);
data->temp8[1] = TEMP8_TO_REG(val);
i2c_smbus_write_byte_data(client, LM63_REG_LOCAL_HIGH, data->temp8[1]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_temp11(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct lm63_data *data = lm63_update_device(dev);
return sprintf(buf, "%d\n", TEMP11_FROM_REG(data->temp11[attr->index])
+ data->temp2_offset);
}
static ssize_t set_temp11(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
static const u8 reg[4] = {
LM63_REG_REMOTE_LOW_MSB,
LM63_REG_REMOTE_LOW_LSB,
LM63_REG_REMOTE_HIGH_MSB,
LM63_REG_REMOTE_HIGH_LSB,
};
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct i2c_client *client = to_i2c_client(dev);
struct lm63_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
int nr = attr->index;
mutex_lock(&data->update_lock);
data->temp11[nr] = TEMP11_TO_REG(val - data->temp2_offset);
i2c_smbus_write_byte_data(client, reg[(nr - 1) * 2],
data->temp11[nr] >> 8);
i2c_smbus_write_byte_data(client, reg[(nr - 1) * 2 + 1],
data->temp11[nr] & 0xff);
mutex_unlock(&data->update_lock);
return count;
}
/* Hysteresis register holds a relative value, while we want to present
an absolute to user-space */
static ssize_t show_temp2_crit_hyst(struct device *dev, struct device_attribute *dummy,
char *buf)
{
struct lm63_data *data = lm63_update_device(dev);
return sprintf(buf, "%d\n", TEMP8_FROM_REG(data->temp8[2])
+ data->temp2_offset
- TEMP8_FROM_REG(data->temp2_crit_hyst));
}
/* And now the other way around, user-space provides an absolute
hysteresis value and we have to store a relative one */
static ssize_t set_temp2_crit_hyst(struct device *dev, struct device_attribute *dummy,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm63_data *data = i2c_get_clientdata(client);
long val = simple_strtol(buf, NULL, 10);
long hyst;
mutex_lock(&data->update_lock);
hyst = TEMP8_FROM_REG(data->temp8[2]) + data->temp2_offset - val;
i2c_smbus_write_byte_data(client, LM63_REG_REMOTE_TCRIT_HYST,
HYST_TO_REG(hyst));
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_alarms(struct device *dev, struct device_attribute *dummy,
char *buf)
{
struct lm63_data *data = lm63_update_device(dev);
return sprintf(buf, "%u\n", data->alarms);
}
static ssize_t show_alarm(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct lm63_data *data = lm63_update_device(dev);
int bitnr = attr->index;
return sprintf(buf, "%u\n", (data->alarms >> bitnr) & 1);
}
static SENSOR_DEVICE_ATTR(fan1_input, S_IRUGO, show_fan, NULL, 0);
static SENSOR_DEVICE_ATTR(fan1_min, S_IWUSR | S_IRUGO, show_fan,
set_fan, 1);
static DEVICE_ATTR(pwm1, S_IWUSR | S_IRUGO, show_pwm1, set_pwm1);
static DEVICE_ATTR(pwm1_enable, S_IRUGO, show_pwm1_enable, NULL);
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_local_temp8, NULL, 0);
static SENSOR_DEVICE_ATTR(temp1_max, S_IWUSR | S_IRUGO, show_local_temp8,
set_local_temp8, 1);
static SENSOR_DEVICE_ATTR(temp2_input, S_IRUGO, show_temp11, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_min, S_IWUSR | S_IRUGO, show_temp11,
set_temp11, 1);
static SENSOR_DEVICE_ATTR(temp2_max, S_IWUSR | S_IRUGO, show_temp11,
set_temp11, 2);
/*
* On LM63, temp2_crit can be set only once, which should be job
* of the bootloader.
*/
static SENSOR_DEVICE_ATTR(temp2_crit, S_IRUGO, show_remote_temp8,
NULL, 2);
static DEVICE_ATTR(temp2_crit_hyst, S_IWUSR | S_IRUGO, show_temp2_crit_hyst,
set_temp2_crit_hyst);
/* Individual alarm files */
static SENSOR_DEVICE_ATTR(fan1_min_alarm, S_IRUGO, show_alarm, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_crit_alarm, S_IRUGO, show_alarm, NULL, 1);
static SENSOR_DEVICE_ATTR(temp2_fault, S_IRUGO, show_alarm, NULL, 2);
static SENSOR_DEVICE_ATTR(temp2_min_alarm, S_IRUGO, show_alarm, NULL, 3);
static SENSOR_DEVICE_ATTR(temp2_max_alarm, S_IRUGO, show_alarm, NULL, 4);
static SENSOR_DEVICE_ATTR(temp1_max_alarm, S_IRUGO, show_alarm, NULL, 6);
/* Raw alarm file for compatibility */
static DEVICE_ATTR(alarms, S_IRUGO, show_alarms, NULL);
static struct attribute *lm63_attributes[] = {
&dev_attr_pwm1.attr,
&dev_attr_pwm1_enable.attr,
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp2_input.dev_attr.attr,
&sensor_dev_attr_temp2_min.dev_attr.attr,
&sensor_dev_attr_temp1_max.dev_attr.attr,
&sensor_dev_attr_temp2_max.dev_attr.attr,
&sensor_dev_attr_temp2_crit.dev_attr.attr,
&dev_attr_temp2_crit_hyst.attr,
&sensor_dev_attr_temp2_crit_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_fault.dev_attr.attr,
&sensor_dev_attr_temp2_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_max_alarm.dev_attr.attr,
&dev_attr_alarms.attr,
NULL
};
static const struct attribute_group lm63_group = {
.attrs = lm63_attributes,
};
static struct attribute *lm63_attributes_fan1[] = {
&sensor_dev_attr_fan1_input.dev_attr.attr,
&sensor_dev_attr_fan1_min.dev_attr.attr,
&sensor_dev_attr_fan1_min_alarm.dev_attr.attr,
NULL
};
static const struct attribute_group lm63_group_fan1 = {
.attrs = lm63_attributes_fan1,
};
/*
* Real code
*/
/* Return 0 if detection is successful, -ENODEV otherwise */
static int lm63_detect(struct i2c_client *new_client,
struct i2c_board_info *info)
{
struct i2c_adapter *adapter = new_client->adapter;
u8 man_id, chip_id, reg_config1, reg_config2;
u8 reg_alert_status, reg_alert_mask;
int address = new_client->addr;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
man_id = i2c_smbus_read_byte_data(new_client, LM63_REG_MAN_ID);
chip_id = i2c_smbus_read_byte_data(new_client, LM63_REG_CHIP_ID);
reg_config1 = i2c_smbus_read_byte_data(new_client,
LM63_REG_CONFIG1);
reg_config2 = i2c_smbus_read_byte_data(new_client,
LM63_REG_CONFIG2);
reg_alert_status = i2c_smbus_read_byte_data(new_client,
LM63_REG_ALERT_STATUS);
reg_alert_mask = i2c_smbus_read_byte_data(new_client,
LM63_REG_ALERT_MASK);
if (man_id != 0x01 /* National Semiconductor */
|| (reg_config1 & 0x18) != 0x00
|| (reg_config2 & 0xF8) != 0x00
|| (reg_alert_status & 0x20) != 0x00
|| (reg_alert_mask & 0xA4) != 0xA4) {
dev_dbg(&adapter->dev,
"Unsupported chip (man_id=0x%02X, chip_id=0x%02X)\n",
man_id, chip_id);
return -ENODEV;
}
if (chip_id == 0x41 && address == 0x4c)
strlcpy(info->type, "lm63", I2C_NAME_SIZE);
else if (chip_id == 0x51 && (address == 0x18 || address == 0x4e))
strlcpy(info->type, "lm64", I2C_NAME_SIZE);
else
return -ENODEV;
return 0;
}
static int lm63_probe(struct i2c_client *new_client,
const struct i2c_device_id *id)
{
struct lm63_data *data;
int err;
data = kzalloc(sizeof(struct lm63_data), GFP_KERNEL);
if (!data) {
err = -ENOMEM;
goto exit;
}
i2c_set_clientdata(new_client, data);
data->valid = 0;
mutex_init(&data->update_lock);
/* Set the device type */
data->kind = id->driver_data;
if (data->kind == lm64)
data->temp2_offset = 16000;
/* Initialize chip */
lm63_init_client(new_client);
/* Register sysfs hooks */
if ((err = sysfs_create_group(&new_client->dev.kobj,
&lm63_group)))
goto exit_free;
if (data->config & 0x04) { /* tachometer enabled */
if ((err = sysfs_create_group(&new_client->dev.kobj,
&lm63_group_fan1)))
goto exit_remove_files;
}
data->hwmon_dev = hwmon_device_register(&new_client->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto exit_remove_files;
}
return 0;
exit_remove_files:
sysfs_remove_group(&new_client->dev.kobj, &lm63_group);
sysfs_remove_group(&new_client->dev.kobj, &lm63_group_fan1);
exit_free:
kfree(data);
exit:
return err;
}
/* Idealy we shouldn't have to initialize anything, since the BIOS
should have taken care of everything */
static void lm63_init_client(struct i2c_client *client)
{
struct lm63_data *data = i2c_get_clientdata(client);
data->config = i2c_smbus_read_byte_data(client, LM63_REG_CONFIG1);
data->config_fan = i2c_smbus_read_byte_data(client,
LM63_REG_CONFIG_FAN);
/* Start converting if needed */
if (data->config & 0x40) { /* standby */
dev_dbg(&client->dev, "Switching to operational mode\n");
data->config &= 0xA7;
i2c_smbus_write_byte_data(client, LM63_REG_CONFIG1,
data->config);
}
/* We may need pwm1_freq before ever updating the client data */
data->pwm1_freq = i2c_smbus_read_byte_data(client, LM63_REG_PWM_FREQ);
if (data->pwm1_freq == 0)
data->pwm1_freq = 1;
/* Show some debug info about the LM63 configuration */
dev_dbg(&client->dev, "Alert/tach pin configured for %s\n",
(data->config & 0x04) ? "tachometer input" :
"alert output");
dev_dbg(&client->dev, "PWM clock %s kHz, output frequency %u Hz\n",
(data->config_fan & 0x08) ? "1.4" : "360",
((data->config_fan & 0x08) ? 700 : 180000) / data->pwm1_freq);
dev_dbg(&client->dev, "PWM output active %s, %s mode\n",
(data->config_fan & 0x10) ? "low" : "high",
(data->config_fan & 0x20) ? "manual" : "auto");
}
static int lm63_remove(struct i2c_client *client)
{
struct lm63_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&client->dev.kobj, &lm63_group);
sysfs_remove_group(&client->dev.kobj, &lm63_group_fan1);
kfree(data);
return 0;
}
static struct lm63_data *lm63_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm63_data *data = i2c_get_clientdata(client);
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ) || !data->valid) {
if (data->config & 0x04) { /* tachometer enabled */
/* order matters for fan1_input */
data->fan[0] = i2c_smbus_read_byte_data(client,
LM63_REG_TACH_COUNT_LSB) & 0xFC;
data->fan[0] |= i2c_smbus_read_byte_data(client,
LM63_REG_TACH_COUNT_MSB) << 8;
data->fan[1] = (i2c_smbus_read_byte_data(client,
LM63_REG_TACH_LIMIT_LSB) & 0xFC)
| (i2c_smbus_read_byte_data(client,
LM63_REG_TACH_LIMIT_MSB) << 8);
}
data->pwm1_freq = i2c_smbus_read_byte_data(client,
LM63_REG_PWM_FREQ);
if (data->pwm1_freq == 0)
data->pwm1_freq = 1;
data->pwm1_value = i2c_smbus_read_byte_data(client,
LM63_REG_PWM_VALUE);
data->temp8[0] = i2c_smbus_read_byte_data(client,
LM63_REG_LOCAL_TEMP);
data->temp8[1] = i2c_smbus_read_byte_data(client,
LM63_REG_LOCAL_HIGH);
/* order matters for temp2_input */
data->temp11[0] = i2c_smbus_read_byte_data(client,
LM63_REG_REMOTE_TEMP_MSB) << 8;
data->temp11[0] |= i2c_smbus_read_byte_data(client,
LM63_REG_REMOTE_TEMP_LSB);
data->temp11[1] = (i2c_smbus_read_byte_data(client,
LM63_REG_REMOTE_LOW_MSB) << 8)
| i2c_smbus_read_byte_data(client,
LM63_REG_REMOTE_LOW_LSB);
data->temp11[2] = (i2c_smbus_read_byte_data(client,
LM63_REG_REMOTE_HIGH_MSB) << 8)
| i2c_smbus_read_byte_data(client,
LM63_REG_REMOTE_HIGH_LSB);
data->temp8[2] = i2c_smbus_read_byte_data(client,
LM63_REG_REMOTE_TCRIT);
data->temp2_crit_hyst = i2c_smbus_read_byte_data(client,
LM63_REG_REMOTE_TCRIT_HYST);
data->alarms = i2c_smbus_read_byte_data(client,
LM63_REG_ALERT_STATUS) & 0x7F;
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
static int __init sensors_lm63_init(void)
{
return i2c_add_driver(&lm63_driver);
}
static void __exit sensors_lm63_exit(void)
{
i2c_del_driver(&lm63_driver);
}
MODULE_AUTHOR("Jean Delvare <khali@linux-fr.org>");
MODULE_DESCRIPTION("LM63 driver");
MODULE_LICENSE("GPL");
module_init(sensors_lm63_init);
module_exit(sensors_lm63_exit);
| gpl-2.0 |
CyanogenMod/android_kernel_samsung_lt03wifi | arch/mips/pci/pci-ip27.c | 4299 | 5742 | /*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 2003 Christoph Hellwig (hch@lst.de)
* Copyright (C) 1999, 2000, 04 Ralf Baechle (ralf@linux-mips.org)
* Copyright (C) 1999, 2000 Silicon Graphics, Inc.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/pci.h>
#include <linux/smp.h>
#include <asm/sn/arch.h>
#include <asm/pci/bridge.h>
#include <asm/paccess.h>
#include <asm/sn/intr.h>
#include <asm/sn/sn0/hub.h>
/*
* Max #PCI busses we can handle; ie, max #PCI bridges.
*/
#define MAX_PCI_BUSSES 40
/*
* Max #PCI devices (like scsi controllers) we handle on a bus.
*/
#define MAX_DEVICES_PER_PCIBUS 8
/*
* XXX: No kmalloc available when we do our crosstalk scan,
* we should try to move it later in the boot process.
*/
static struct bridge_controller bridges[MAX_PCI_BUSSES];
/*
* Translate from irq to software PCI bus number and PCI slot.
*/
struct bridge_controller *irq_to_bridge[MAX_PCI_BUSSES * MAX_DEVICES_PER_PCIBUS];
int irq_to_slot[MAX_PCI_BUSSES * MAX_DEVICES_PER_PCIBUS];
extern struct pci_ops bridge_pci_ops;
int __cpuinit bridge_probe(nasid_t nasid, int widget_id, int masterwid)
{
unsigned long offset = NODE_OFFSET(nasid);
struct bridge_controller *bc;
static int num_bridges = 0;
bridge_t *bridge;
int slot;
pci_set_flags(PCI_PROBE_ONLY);
printk("a bridge\n");
/* XXX: kludge alert.. */
if (!num_bridges)
ioport_resource.end = ~0UL;
bc = &bridges[num_bridges];
bc->pc.pci_ops = &bridge_pci_ops;
bc->pc.mem_resource = &bc->mem;
bc->pc.io_resource = &bc->io;
bc->pc.index = num_bridges;
bc->mem.name = "Bridge PCI MEM";
bc->pc.mem_offset = offset;
bc->mem.start = 0;
bc->mem.end = ~0UL;
bc->mem.flags = IORESOURCE_MEM;
bc->io.name = "Bridge IO MEM";
bc->pc.io_offset = offset;
bc->io.start = 0UL;
bc->io.end = ~0UL;
bc->io.flags = IORESOURCE_IO;
bc->irq_cpu = smp_processor_id();
bc->widget_id = widget_id;
bc->nasid = nasid;
bc->baddr = (u64)masterwid << 60 | PCI64_ATTR_BAR;
/*
* point to this bridge
*/
bridge = (bridge_t *) RAW_NODE_SWIN_BASE(nasid, widget_id);
/*
* Clear all pending interrupts.
*/
bridge->b_int_rst_stat = BRIDGE_IRR_ALL_CLR;
/*
* Until otherwise set up, assume all interrupts are from slot 0
*/
bridge->b_int_device = 0x0;
/*
* swap pio's to pci mem and io space (big windows)
*/
bridge->b_wid_control |= BRIDGE_CTRL_IO_SWAP |
BRIDGE_CTRL_MEM_SWAP;
#ifdef CONFIG_PAGE_SIZE_4KB
bridge->b_wid_control &= ~BRIDGE_CTRL_PAGE_SIZE;
#else /* 16kB or larger */
bridge->b_wid_control |= BRIDGE_CTRL_PAGE_SIZE;
#endif
/*
* Hmm... IRIX sets additional bits in the address which
* are documented as reserved in the bridge docs.
*/
bridge->b_wid_int_upper = 0x8000 | (masterwid << 16);
bridge->b_wid_int_lower = 0x01800090; /* PI_INT_PEND_MOD off*/
bridge->b_dir_map = (masterwid << 20); /* DMA */
bridge->b_int_enable = 0;
for (slot = 0; slot < 8; slot ++) {
bridge->b_device[slot].reg |= BRIDGE_DEV_SWAP_DIR;
bc->pci_int[slot] = -1;
}
bridge->b_wid_tflush; /* wait until Bridge PIO complete */
bc->base = bridge;
register_pci_controller(&bc->pc);
num_bridges++;
return 0;
}
/*
* All observed requests have pin == 1. We could have a global here, that
* gets incremented and returned every time - unfortunately, pci_map_irq
* may be called on the same device over and over, and need to return the
* same value. On O2000, pin can be 0 or 1, and PCI slots can be [0..7].
*
* A given PCI device, in general, should be able to intr any of the cpus
* on any one of the hubs connected to its xbow.
*/
int __devinit pcibios_map_irq(const struct pci_dev *dev, u8 slot, u8 pin)
{
return 0;
}
static inline struct pci_dev *bridge_root_dev(struct pci_dev *dev)
{
while (dev->bus->parent) {
/* Move up the chain of bridges. */
dev = dev->bus->self;
}
return dev;
}
/* Do platform specific device initialization at pci_enable_device() time */
int pcibios_plat_dev_init(struct pci_dev *dev)
{
struct bridge_controller *bc = BRIDGE_CONTROLLER(dev->bus);
struct pci_dev *rdev = bridge_root_dev(dev);
int slot = PCI_SLOT(rdev->devfn);
int irq;
irq = bc->pci_int[slot];
if (irq == -1) {
irq = request_bridge_irq(bc);
if (irq < 0)
return irq;
bc->pci_int[slot] = irq;
}
irq_to_bridge[irq] = bc;
irq_to_slot[irq] = slot;
dev->irq = irq;
return 0;
}
/*
* Device might live on a subordinate PCI bus. XXX Walk up the chain of buses
* to find the slot number in sense of the bridge device register.
* XXX This also means multiple devices might rely on conflicting bridge
* settings.
*/
static inline void pci_disable_swapping(struct pci_dev *dev)
{
struct bridge_controller *bc = BRIDGE_CONTROLLER(dev->bus);
bridge_t *bridge = bc->base;
int slot = PCI_SLOT(dev->devfn);
/* Turn off byte swapping */
bridge->b_device[slot].reg &= ~BRIDGE_DEV_SWAP_DIR;
bridge->b_widget.w_tflush; /* Flush */
}
static inline void pci_enable_swapping(struct pci_dev *dev)
{
struct bridge_controller *bc = BRIDGE_CONTROLLER(dev->bus);
bridge_t *bridge = bc->base;
int slot = PCI_SLOT(dev->devfn);
/* Turn on byte swapping */
bridge->b_device[slot].reg |= BRIDGE_DEV_SWAP_DIR;
bridge->b_widget.w_tflush; /* Flush */
}
static void __init pci_fixup_ioc3(struct pci_dev *d)
{
pci_disable_swapping(d);
}
int pcibus_to_node(struct pci_bus *bus)
{
struct bridge_controller *bc = BRIDGE_CONTROLLER(bus);
return bc->nasid;
}
EXPORT_SYMBOL(pcibus_to_node);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SGI, PCI_DEVICE_ID_SGI_IOC3,
pci_fixup_ioc3);
| gpl-2.0 |
ISTweak/android_kernel_htc_msm8960 | arch/sparc/kernel/visemul.c | 4555 | 20079 | /* visemul.c: Emulation of VIS instructions.
*
* Copyright (C) 2006 David S. Miller (davem@davemloft.net)
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/thread_info.h>
#include <linux/perf_event.h>
#include <asm/ptrace.h>
#include <asm/pstate.h>
#include <asm/fpumacro.h>
#include <asm/uaccess.h>
#include <asm/cacheflush.h>
/* OPF field of various VIS instructions. */
/* 000111011 - four 16-bit packs */
#define FPACK16_OPF 0x03b
/* 000111010 - two 32-bit packs */
#define FPACK32_OPF 0x03a
/* 000111101 - four 16-bit packs */
#define FPACKFIX_OPF 0x03d
/* 001001101 - four 16-bit expands */
#define FEXPAND_OPF 0x04d
/* 001001011 - two 32-bit merges */
#define FPMERGE_OPF 0x04b
/* 000110001 - 8-by-16-bit partitoned product */
#define FMUL8x16_OPF 0x031
/* 000110011 - 8-by-16-bit upper alpha partitioned product */
#define FMUL8x16AU_OPF 0x033
/* 000110101 - 8-by-16-bit lower alpha partitioned product */
#define FMUL8x16AL_OPF 0x035
/* 000110110 - upper 8-by-16-bit partitioned product */
#define FMUL8SUx16_OPF 0x036
/* 000110111 - lower 8-by-16-bit partitioned product */
#define FMUL8ULx16_OPF 0x037
/* 000111000 - upper 8-by-16-bit partitioned product */
#define FMULD8SUx16_OPF 0x038
/* 000111001 - lower unsigned 8-by-16-bit partitioned product */
#define FMULD8ULx16_OPF 0x039
/* 000101000 - four 16-bit compare; set rd if src1 > src2 */
#define FCMPGT16_OPF 0x028
/* 000101100 - two 32-bit compare; set rd if src1 > src2 */
#define FCMPGT32_OPF 0x02c
/* 000100000 - four 16-bit compare; set rd if src1 <= src2 */
#define FCMPLE16_OPF 0x020
/* 000100100 - two 32-bit compare; set rd if src1 <= src2 */
#define FCMPLE32_OPF 0x024
/* 000100010 - four 16-bit compare; set rd if src1 != src2 */
#define FCMPNE16_OPF 0x022
/* 000100110 - two 32-bit compare; set rd if src1 != src2 */
#define FCMPNE32_OPF 0x026
/* 000101010 - four 16-bit compare; set rd if src1 == src2 */
#define FCMPEQ16_OPF 0x02a
/* 000101110 - two 32-bit compare; set rd if src1 == src2 */
#define FCMPEQ32_OPF 0x02e
/* 000000000 - Eight 8-bit edge boundary processing */
#define EDGE8_OPF 0x000
/* 000000001 - Eight 8-bit edge boundary processing, no CC */
#define EDGE8N_OPF 0x001
/* 000000010 - Eight 8-bit edge boundary processing, little-endian */
#define EDGE8L_OPF 0x002
/* 000000011 - Eight 8-bit edge boundary processing, little-endian, no CC */
#define EDGE8LN_OPF 0x003
/* 000000100 - Four 16-bit edge boundary processing */
#define EDGE16_OPF 0x004
/* 000000101 - Four 16-bit edge boundary processing, no CC */
#define EDGE16N_OPF 0x005
/* 000000110 - Four 16-bit edge boundary processing, little-endian */
#define EDGE16L_OPF 0x006
/* 000000111 - Four 16-bit edge boundary processing, little-endian, no CC */
#define EDGE16LN_OPF 0x007
/* 000001000 - Two 32-bit edge boundary processing */
#define EDGE32_OPF 0x008
/* 000001001 - Two 32-bit edge boundary processing, no CC */
#define EDGE32N_OPF 0x009
/* 000001010 - Two 32-bit edge boundary processing, little-endian */
#define EDGE32L_OPF 0x00a
/* 000001011 - Two 32-bit edge boundary processing, little-endian, no CC */
#define EDGE32LN_OPF 0x00b
/* 000111110 - distance between 8 8-bit components */
#define PDIST_OPF 0x03e
/* 000010000 - convert 8-bit 3-D address to blocked byte address */
#define ARRAY8_OPF 0x010
/* 000010010 - convert 16-bit 3-D address to blocked byte address */
#define ARRAY16_OPF 0x012
/* 000010100 - convert 32-bit 3-D address to blocked byte address */
#define ARRAY32_OPF 0x014
/* 000011001 - Set the GSR.MASK field in preparation for a BSHUFFLE */
#define BMASK_OPF 0x019
/* 001001100 - Permute bytes as specified by GSR.MASK */
#define BSHUFFLE_OPF 0x04c
#define VIS_OPF_SHIFT 5
#define VIS_OPF_MASK (0x1ff << VIS_OPF_SHIFT)
#define RS1(INSN) (((INSN) >> 14) & 0x1f)
#define RS2(INSN) (((INSN) >> 0) & 0x1f)
#define RD(INSN) (((INSN) >> 25) & 0x1f)
static inline void maybe_flush_windows(unsigned int rs1, unsigned int rs2,
unsigned int rd, int from_kernel)
{
if (rs2 >= 16 || rs1 >= 16 || rd >= 16) {
if (from_kernel != 0)
__asm__ __volatile__("flushw");
else
flushw_user();
}
}
static unsigned long fetch_reg(unsigned int reg, struct pt_regs *regs)
{
unsigned long value;
if (reg < 16)
return (!reg ? 0 : regs->u_regs[reg]);
if (regs->tstate & TSTATE_PRIV) {
struct reg_window *win;
win = (struct reg_window *)(regs->u_regs[UREG_FP] + STACK_BIAS);
value = win->locals[reg - 16];
} else if (test_thread_flag(TIF_32BIT)) {
struct reg_window32 __user *win32;
win32 = (struct reg_window32 __user *)((unsigned long)((u32)regs->u_regs[UREG_FP]));
get_user(value, &win32->locals[reg - 16]);
} else {
struct reg_window __user *win;
win = (struct reg_window __user *)(regs->u_regs[UREG_FP] + STACK_BIAS);
get_user(value, &win->locals[reg - 16]);
}
return value;
}
static inline unsigned long __user *__fetch_reg_addr_user(unsigned int reg,
struct pt_regs *regs)
{
BUG_ON(reg < 16);
BUG_ON(regs->tstate & TSTATE_PRIV);
if (test_thread_flag(TIF_32BIT)) {
struct reg_window32 __user *win32;
win32 = (struct reg_window32 __user *)((unsigned long)((u32)regs->u_regs[UREG_FP]));
return (unsigned long __user *)&win32->locals[reg - 16];
} else {
struct reg_window __user *win;
win = (struct reg_window __user *)(regs->u_regs[UREG_FP] + STACK_BIAS);
return &win->locals[reg - 16];
}
}
static inline unsigned long *__fetch_reg_addr_kern(unsigned int reg,
struct pt_regs *regs)
{
BUG_ON(reg >= 16);
BUG_ON(regs->tstate & TSTATE_PRIV);
return ®s->u_regs[reg];
}
static void store_reg(struct pt_regs *regs, unsigned long val, unsigned long rd)
{
if (rd < 16) {
unsigned long *rd_kern = __fetch_reg_addr_kern(rd, regs);
*rd_kern = val;
} else {
unsigned long __user *rd_user = __fetch_reg_addr_user(rd, regs);
if (test_thread_flag(TIF_32BIT))
__put_user((u32)val, (u32 __user *)rd_user);
else
__put_user(val, rd_user);
}
}
static inline unsigned long fpd_regval(struct fpustate *f,
unsigned int insn_regnum)
{
insn_regnum = (((insn_regnum & 1) << 5) |
(insn_regnum & 0x1e));
return *(unsigned long *) &f->regs[insn_regnum];
}
static inline unsigned long *fpd_regaddr(struct fpustate *f,
unsigned int insn_regnum)
{
insn_regnum = (((insn_regnum & 1) << 5) |
(insn_regnum & 0x1e));
return (unsigned long *) &f->regs[insn_regnum];
}
static inline unsigned int fps_regval(struct fpustate *f,
unsigned int insn_regnum)
{
return f->regs[insn_regnum];
}
static inline unsigned int *fps_regaddr(struct fpustate *f,
unsigned int insn_regnum)
{
return &f->regs[insn_regnum];
}
struct edge_tab {
u16 left, right;
};
static struct edge_tab edge8_tab[8] = {
{ 0xff, 0x80 },
{ 0x7f, 0xc0 },
{ 0x3f, 0xe0 },
{ 0x1f, 0xf0 },
{ 0x0f, 0xf8 },
{ 0x07, 0xfc },
{ 0x03, 0xfe },
{ 0x01, 0xff },
};
static struct edge_tab edge8_tab_l[8] = {
{ 0xff, 0x01 },
{ 0xfe, 0x03 },
{ 0xfc, 0x07 },
{ 0xf8, 0x0f },
{ 0xf0, 0x1f },
{ 0xe0, 0x3f },
{ 0xc0, 0x7f },
{ 0x80, 0xff },
};
static struct edge_tab edge16_tab[4] = {
{ 0xf, 0x8 },
{ 0x7, 0xc },
{ 0x3, 0xe },
{ 0x1, 0xf },
};
static struct edge_tab edge16_tab_l[4] = {
{ 0xf, 0x1 },
{ 0xe, 0x3 },
{ 0xc, 0x7 },
{ 0x8, 0xf },
};
static struct edge_tab edge32_tab[2] = {
{ 0x3, 0x2 },
{ 0x1, 0x3 },
};
static struct edge_tab edge32_tab_l[2] = {
{ 0x3, 0x1 },
{ 0x2, 0x3 },
};
static void edge(struct pt_regs *regs, unsigned int insn, unsigned int opf)
{
unsigned long orig_rs1, rs1, orig_rs2, rs2, rd_val;
u16 left, right;
maybe_flush_windows(RS1(insn), RS2(insn), RD(insn), 0);
orig_rs1 = rs1 = fetch_reg(RS1(insn), regs);
orig_rs2 = rs2 = fetch_reg(RS2(insn), regs);
if (test_thread_flag(TIF_32BIT)) {
rs1 = rs1 & 0xffffffff;
rs2 = rs2 & 0xffffffff;
}
switch (opf) {
default:
case EDGE8_OPF:
case EDGE8N_OPF:
left = edge8_tab[rs1 & 0x7].left;
right = edge8_tab[rs2 & 0x7].right;
break;
case EDGE8L_OPF:
case EDGE8LN_OPF:
left = edge8_tab_l[rs1 & 0x7].left;
right = edge8_tab_l[rs2 & 0x7].right;
break;
case EDGE16_OPF:
case EDGE16N_OPF:
left = edge16_tab[(rs1 >> 1) & 0x3].left;
right = edge16_tab[(rs2 >> 1) & 0x3].right;
break;
case EDGE16L_OPF:
case EDGE16LN_OPF:
left = edge16_tab_l[(rs1 >> 1) & 0x3].left;
right = edge16_tab_l[(rs2 >> 1) & 0x3].right;
break;
case EDGE32_OPF:
case EDGE32N_OPF:
left = edge32_tab[(rs1 >> 2) & 0x1].left;
right = edge32_tab[(rs2 >> 2) & 0x1].right;
break;
case EDGE32L_OPF:
case EDGE32LN_OPF:
left = edge32_tab_l[(rs1 >> 2) & 0x1].left;
right = edge32_tab_l[(rs2 >> 2) & 0x1].right;
break;
}
if ((rs1 & ~0x7UL) == (rs2 & ~0x7UL))
rd_val = right & left;
else
rd_val = left;
store_reg(regs, rd_val, RD(insn));
switch (opf) {
case EDGE8_OPF:
case EDGE8L_OPF:
case EDGE16_OPF:
case EDGE16L_OPF:
case EDGE32_OPF:
case EDGE32L_OPF: {
unsigned long ccr, tstate;
__asm__ __volatile__("subcc %1, %2, %%g0\n\t"
"rd %%ccr, %0"
: "=r" (ccr)
: "r" (orig_rs1), "r" (orig_rs2)
: "cc");
tstate = regs->tstate & ~(TSTATE_XCC | TSTATE_ICC);
regs->tstate = tstate | (ccr << 32UL);
}
}
}
static void array(struct pt_regs *regs, unsigned int insn, unsigned int opf)
{
unsigned long rs1, rs2, rd_val;
unsigned int bits, bits_mask;
maybe_flush_windows(RS1(insn), RS2(insn), RD(insn), 0);
rs1 = fetch_reg(RS1(insn), regs);
rs2 = fetch_reg(RS2(insn), regs);
bits = (rs2 > 5 ? 5 : rs2);
bits_mask = (1UL << bits) - 1UL;
rd_val = ((((rs1 >> 11) & 0x3) << 0) |
(((rs1 >> 33) & 0x3) << 2) |
(((rs1 >> 55) & 0x1) << 4) |
(((rs1 >> 13) & 0xf) << 5) |
(((rs1 >> 35) & 0xf) << 9) |
(((rs1 >> 56) & 0xf) << 13) |
(((rs1 >> 17) & bits_mask) << 17) |
(((rs1 >> 39) & bits_mask) << (17 + bits)) |
(((rs1 >> 60) & 0xf) << (17 + (2*bits))));
switch (opf) {
case ARRAY16_OPF:
rd_val <<= 1;
break;
case ARRAY32_OPF:
rd_val <<= 2;
}
store_reg(regs, rd_val, RD(insn));
}
static void bmask(struct pt_regs *regs, unsigned int insn)
{
unsigned long rs1, rs2, rd_val, gsr;
maybe_flush_windows(RS1(insn), RS2(insn), RD(insn), 0);
rs1 = fetch_reg(RS1(insn), regs);
rs2 = fetch_reg(RS2(insn), regs);
rd_val = rs1 + rs2;
store_reg(regs, rd_val, RD(insn));
gsr = current_thread_info()->gsr[0] & 0xffffffff;
gsr |= rd_val << 32UL;
current_thread_info()->gsr[0] = gsr;
}
static void bshuffle(struct pt_regs *regs, unsigned int insn)
{
struct fpustate *f = FPUSTATE;
unsigned long rs1, rs2, rd_val;
unsigned long bmask, i;
bmask = current_thread_info()->gsr[0] >> 32UL;
rs1 = fpd_regval(f, RS1(insn));
rs2 = fpd_regval(f, RS2(insn));
rd_val = 0UL;
for (i = 0; i < 8; i++) {
unsigned long which = (bmask >> (i * 4)) & 0xf;
unsigned long byte;
if (which < 8)
byte = (rs1 >> (which * 8)) & 0xff;
else
byte = (rs2 >> ((which-8)*8)) & 0xff;
rd_val |= (byte << (i * 8));
}
*fpd_regaddr(f, RD(insn)) = rd_val;
}
static void pdist(struct pt_regs *regs, unsigned int insn)
{
struct fpustate *f = FPUSTATE;
unsigned long rs1, rs2, *rd, rd_val;
unsigned long i;
rs1 = fpd_regval(f, RS1(insn));
rs2 = fpd_regval(f, RS2(insn));
rd = fpd_regaddr(f, RD(insn));
rd_val = *rd;
for (i = 0; i < 8; i++) {
s16 s1, s2;
s1 = (rs1 >> (56 - (i * 8))) & 0xff;
s2 = (rs2 >> (56 - (i * 8))) & 0xff;
/* Absolute value of difference. */
s1 -= s2;
if (s1 < 0)
s1 = ~s1 + 1;
rd_val += s1;
}
*rd = rd_val;
}
static void pformat(struct pt_regs *regs, unsigned int insn, unsigned int opf)
{
struct fpustate *f = FPUSTATE;
unsigned long rs1, rs2, gsr, scale, rd_val;
gsr = current_thread_info()->gsr[0];
scale = (gsr >> 3) & (opf == FPACK16_OPF ? 0xf : 0x1f);
switch (opf) {
case FPACK16_OPF: {
unsigned long byte;
rs2 = fpd_regval(f, RS2(insn));
rd_val = 0;
for (byte = 0; byte < 4; byte++) {
unsigned int val;
s16 src = (rs2 >> (byte * 16UL)) & 0xffffUL;
int scaled = src << scale;
int from_fixed = scaled >> 7;
val = ((from_fixed < 0) ?
0 :
(from_fixed > 255) ?
255 : from_fixed);
rd_val |= (val << (8 * byte));
}
*fps_regaddr(f, RD(insn)) = rd_val;
break;
}
case FPACK32_OPF: {
unsigned long word;
rs1 = fpd_regval(f, RS1(insn));
rs2 = fpd_regval(f, RS2(insn));
rd_val = (rs1 << 8) & ~(0x000000ff000000ffUL);
for (word = 0; word < 2; word++) {
unsigned long val;
s32 src = (rs2 >> (word * 32UL));
s64 scaled = src << scale;
s64 from_fixed = scaled >> 23;
val = ((from_fixed < 0) ?
0 :
(from_fixed > 255) ?
255 : from_fixed);
rd_val |= (val << (32 * word));
}
*fpd_regaddr(f, RD(insn)) = rd_val;
break;
}
case FPACKFIX_OPF: {
unsigned long word;
rs2 = fpd_regval(f, RS2(insn));
rd_val = 0;
for (word = 0; word < 2; word++) {
long val;
s32 src = (rs2 >> (word * 32UL));
s64 scaled = src << scale;
s64 from_fixed = scaled >> 16;
val = ((from_fixed < -32768) ?
-32768 :
(from_fixed > 32767) ?
32767 : from_fixed);
rd_val |= ((val & 0xffff) << (word * 16));
}
*fps_regaddr(f, RD(insn)) = rd_val;
break;
}
case FEXPAND_OPF: {
unsigned long byte;
rs2 = fps_regval(f, RS2(insn));
rd_val = 0;
for (byte = 0; byte < 4; byte++) {
unsigned long val;
u8 src = (rs2 >> (byte * 8)) & 0xff;
val = src << 4;
rd_val |= (val << (byte * 16));
}
*fpd_regaddr(f, RD(insn)) = rd_val;
break;
}
case FPMERGE_OPF: {
rs1 = fps_regval(f, RS1(insn));
rs2 = fps_regval(f, RS2(insn));
rd_val = (((rs2 & 0x000000ff) << 0) |
((rs1 & 0x000000ff) << 8) |
((rs2 & 0x0000ff00) << 8) |
((rs1 & 0x0000ff00) << 16) |
((rs2 & 0x00ff0000) << 16) |
((rs1 & 0x00ff0000) << 24) |
((rs2 & 0xff000000) << 24) |
((rs1 & 0xff000000) << 32));
*fpd_regaddr(f, RD(insn)) = rd_val;
break;
}
}
}
static void pmul(struct pt_regs *regs, unsigned int insn, unsigned int opf)
{
struct fpustate *f = FPUSTATE;
unsigned long rs1, rs2, rd_val;
switch (opf) {
case FMUL8x16_OPF: {
unsigned long byte;
rs1 = fps_regval(f, RS1(insn));
rs2 = fpd_regval(f, RS2(insn));
rd_val = 0;
for (byte = 0; byte < 4; byte++) {
u16 src1 = (rs1 >> (byte * 8)) & 0x00ff;
s16 src2 = (rs2 >> (byte * 16)) & 0xffff;
u32 prod = src1 * src2;
u16 scaled = ((prod & 0x00ffff00) >> 8);
/* Round up. */
if (prod & 0x80)
scaled++;
rd_val |= ((scaled & 0xffffUL) << (byte * 16UL));
}
*fpd_regaddr(f, RD(insn)) = rd_val;
break;
}
case FMUL8x16AU_OPF:
case FMUL8x16AL_OPF: {
unsigned long byte;
s16 src2;
rs1 = fps_regval(f, RS1(insn));
rs2 = fps_regval(f, RS2(insn));
rd_val = 0;
src2 = rs2 >> (opf == FMUL8x16AU_OPF ? 16 : 0);
for (byte = 0; byte < 4; byte++) {
u16 src1 = (rs1 >> (byte * 8)) & 0x00ff;
u32 prod = src1 * src2;
u16 scaled = ((prod & 0x00ffff00) >> 8);
/* Round up. */
if (prod & 0x80)
scaled++;
rd_val |= ((scaled & 0xffffUL) << (byte * 16UL));
}
*fpd_regaddr(f, RD(insn)) = rd_val;
break;
}
case FMUL8SUx16_OPF:
case FMUL8ULx16_OPF: {
unsigned long byte, ushift;
rs1 = fpd_regval(f, RS1(insn));
rs2 = fpd_regval(f, RS2(insn));
rd_val = 0;
ushift = (opf == FMUL8SUx16_OPF) ? 8 : 0;
for (byte = 0; byte < 4; byte++) {
u16 src1;
s16 src2;
u32 prod;
u16 scaled;
src1 = ((rs1 >> ((16 * byte) + ushift)) & 0x00ff);
src2 = ((rs2 >> (16 * byte)) & 0xffff);
prod = src1 * src2;
scaled = ((prod & 0x00ffff00) >> 8);
/* Round up. */
if (prod & 0x80)
scaled++;
rd_val |= ((scaled & 0xffffUL) << (byte * 16UL));
}
*fpd_regaddr(f, RD(insn)) = rd_val;
break;
}
case FMULD8SUx16_OPF:
case FMULD8ULx16_OPF: {
unsigned long byte, ushift;
rs1 = fps_regval(f, RS1(insn));
rs2 = fps_regval(f, RS2(insn));
rd_val = 0;
ushift = (opf == FMULD8SUx16_OPF) ? 8 : 0;
for (byte = 0; byte < 2; byte++) {
u16 src1;
s16 src2;
u32 prod;
u16 scaled;
src1 = ((rs1 >> ((16 * byte) + ushift)) & 0x00ff);
src2 = ((rs2 >> (16 * byte)) & 0xffff);
prod = src1 * src2;
scaled = ((prod & 0x00ffff00) >> 8);
/* Round up. */
if (prod & 0x80)
scaled++;
rd_val |= ((scaled & 0xffffUL) <<
((byte * 32UL) + 7UL));
}
*fpd_regaddr(f, RD(insn)) = rd_val;
break;
}
}
}
static void pcmp(struct pt_regs *regs, unsigned int insn, unsigned int opf)
{
struct fpustate *f = FPUSTATE;
unsigned long rs1, rs2, rd_val, i;
rs1 = fpd_regval(f, RS1(insn));
rs2 = fpd_regval(f, RS2(insn));
rd_val = 0;
switch (opf) {
case FCMPGT16_OPF:
for (i = 0; i < 4; i++) {
s16 a = (rs1 >> (i * 16)) & 0xffff;
s16 b = (rs2 >> (i * 16)) & 0xffff;
if (a > b)
rd_val |= 8 >> i;
}
break;
case FCMPGT32_OPF:
for (i = 0; i < 2; i++) {
s32 a = (rs1 >> (i * 32)) & 0xffffffff;
s32 b = (rs2 >> (i * 32)) & 0xffffffff;
if (a > b)
rd_val |= 2 >> i;
}
break;
case FCMPLE16_OPF:
for (i = 0; i < 4; i++) {
s16 a = (rs1 >> (i * 16)) & 0xffff;
s16 b = (rs2 >> (i * 16)) & 0xffff;
if (a <= b)
rd_val |= 8 >> i;
}
break;
case FCMPLE32_OPF:
for (i = 0; i < 2; i++) {
s32 a = (rs1 >> (i * 32)) & 0xffffffff;
s32 b = (rs2 >> (i * 32)) & 0xffffffff;
if (a <= b)
rd_val |= 2 >> i;
}
break;
case FCMPNE16_OPF:
for (i = 0; i < 4; i++) {
s16 a = (rs1 >> (i * 16)) & 0xffff;
s16 b = (rs2 >> (i * 16)) & 0xffff;
if (a != b)
rd_val |= 8 >> i;
}
break;
case FCMPNE32_OPF:
for (i = 0; i < 2; i++) {
s32 a = (rs1 >> (i * 32)) & 0xffffffff;
s32 b = (rs2 >> (i * 32)) & 0xffffffff;
if (a != b)
rd_val |= 2 >> i;
}
break;
case FCMPEQ16_OPF:
for (i = 0; i < 4; i++) {
s16 a = (rs1 >> (i * 16)) & 0xffff;
s16 b = (rs2 >> (i * 16)) & 0xffff;
if (a == b)
rd_val |= 8 >> i;
}
break;
case FCMPEQ32_OPF:
for (i = 0; i < 2; i++) {
s32 a = (rs1 >> (i * 32)) & 0xffffffff;
s32 b = (rs2 >> (i * 32)) & 0xffffffff;
if (a == b)
rd_val |= 2 >> i;
}
break;
}
maybe_flush_windows(0, 0, RD(insn), 0);
store_reg(regs, rd_val, RD(insn));
}
/* Emulate the VIS instructions which are not implemented in
* hardware on Niagara.
*/
int vis_emul(struct pt_regs *regs, unsigned int insn)
{
unsigned long pc = regs->tpc;
unsigned int opf;
BUG_ON(regs->tstate & TSTATE_PRIV);
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, 0);
if (test_thread_flag(TIF_32BIT))
pc = (u32)pc;
if (get_user(insn, (u32 __user *) pc))
return -EFAULT;
save_and_clear_fpu();
opf = (insn & VIS_OPF_MASK) >> VIS_OPF_SHIFT;
switch (opf) {
default:
return -EINVAL;
/* Pixel Formatting Instructions. */
case FPACK16_OPF:
case FPACK32_OPF:
case FPACKFIX_OPF:
case FEXPAND_OPF:
case FPMERGE_OPF:
pformat(regs, insn, opf);
break;
/* Partitioned Multiply Instructions */
case FMUL8x16_OPF:
case FMUL8x16AU_OPF:
case FMUL8x16AL_OPF:
case FMUL8SUx16_OPF:
case FMUL8ULx16_OPF:
case FMULD8SUx16_OPF:
case FMULD8ULx16_OPF:
pmul(regs, insn, opf);
break;
/* Pixel Compare Instructions */
case FCMPGT16_OPF:
case FCMPGT32_OPF:
case FCMPLE16_OPF:
case FCMPLE32_OPF:
case FCMPNE16_OPF:
case FCMPNE32_OPF:
case FCMPEQ16_OPF:
case FCMPEQ32_OPF:
pcmp(regs, insn, opf);
break;
/* Edge Handling Instructions */
case EDGE8_OPF:
case EDGE8N_OPF:
case EDGE8L_OPF:
case EDGE8LN_OPF:
case EDGE16_OPF:
case EDGE16N_OPF:
case EDGE16L_OPF:
case EDGE16LN_OPF:
case EDGE32_OPF:
case EDGE32N_OPF:
case EDGE32L_OPF:
case EDGE32LN_OPF:
edge(regs, insn, opf);
break;
/* Pixel Component Distance */
case PDIST_OPF:
pdist(regs, insn);
break;
/* Three-Dimensional Array Addressing Instructions */
case ARRAY8_OPF:
case ARRAY16_OPF:
case ARRAY32_OPF:
array(regs, insn, opf);
break;
/* Byte Mask and Shuffle Instructions */
case BMASK_OPF:
bmask(regs, insn);
break;
case BSHUFFLE_OPF:
bshuffle(regs, insn);
break;
}
regs->tpc = regs->tnpc;
regs->tnpc += 4;
return 0;
}
| gpl-2.0 |
Caio99BR/android_kernel_sony_falconss | arch/sparc/kernel/visemul.c | 4555 | 20079 | /* visemul.c: Emulation of VIS instructions.
*
* Copyright (C) 2006 David S. Miller (davem@davemloft.net)
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/thread_info.h>
#include <linux/perf_event.h>
#include <asm/ptrace.h>
#include <asm/pstate.h>
#include <asm/fpumacro.h>
#include <asm/uaccess.h>
#include <asm/cacheflush.h>
/* OPF field of various VIS instructions. */
/* 000111011 - four 16-bit packs */
#define FPACK16_OPF 0x03b
/* 000111010 - two 32-bit packs */
#define FPACK32_OPF 0x03a
/* 000111101 - four 16-bit packs */
#define FPACKFIX_OPF 0x03d
/* 001001101 - four 16-bit expands */
#define FEXPAND_OPF 0x04d
/* 001001011 - two 32-bit merges */
#define FPMERGE_OPF 0x04b
/* 000110001 - 8-by-16-bit partitoned product */
#define FMUL8x16_OPF 0x031
/* 000110011 - 8-by-16-bit upper alpha partitioned product */
#define FMUL8x16AU_OPF 0x033
/* 000110101 - 8-by-16-bit lower alpha partitioned product */
#define FMUL8x16AL_OPF 0x035
/* 000110110 - upper 8-by-16-bit partitioned product */
#define FMUL8SUx16_OPF 0x036
/* 000110111 - lower 8-by-16-bit partitioned product */
#define FMUL8ULx16_OPF 0x037
/* 000111000 - upper 8-by-16-bit partitioned product */
#define FMULD8SUx16_OPF 0x038
/* 000111001 - lower unsigned 8-by-16-bit partitioned product */
#define FMULD8ULx16_OPF 0x039
/* 000101000 - four 16-bit compare; set rd if src1 > src2 */
#define FCMPGT16_OPF 0x028
/* 000101100 - two 32-bit compare; set rd if src1 > src2 */
#define FCMPGT32_OPF 0x02c
/* 000100000 - four 16-bit compare; set rd if src1 <= src2 */
#define FCMPLE16_OPF 0x020
/* 000100100 - two 32-bit compare; set rd if src1 <= src2 */
#define FCMPLE32_OPF 0x024
/* 000100010 - four 16-bit compare; set rd if src1 != src2 */
#define FCMPNE16_OPF 0x022
/* 000100110 - two 32-bit compare; set rd if src1 != src2 */
#define FCMPNE32_OPF 0x026
/* 000101010 - four 16-bit compare; set rd if src1 == src2 */
#define FCMPEQ16_OPF 0x02a
/* 000101110 - two 32-bit compare; set rd if src1 == src2 */
#define FCMPEQ32_OPF 0x02e
/* 000000000 - Eight 8-bit edge boundary processing */
#define EDGE8_OPF 0x000
/* 000000001 - Eight 8-bit edge boundary processing, no CC */
#define EDGE8N_OPF 0x001
/* 000000010 - Eight 8-bit edge boundary processing, little-endian */
#define EDGE8L_OPF 0x002
/* 000000011 - Eight 8-bit edge boundary processing, little-endian, no CC */
#define EDGE8LN_OPF 0x003
/* 000000100 - Four 16-bit edge boundary processing */
#define EDGE16_OPF 0x004
/* 000000101 - Four 16-bit edge boundary processing, no CC */
#define EDGE16N_OPF 0x005
/* 000000110 - Four 16-bit edge boundary processing, little-endian */
#define EDGE16L_OPF 0x006
/* 000000111 - Four 16-bit edge boundary processing, little-endian, no CC */
#define EDGE16LN_OPF 0x007
/* 000001000 - Two 32-bit edge boundary processing */
#define EDGE32_OPF 0x008
/* 000001001 - Two 32-bit edge boundary processing, no CC */
#define EDGE32N_OPF 0x009
/* 000001010 - Two 32-bit edge boundary processing, little-endian */
#define EDGE32L_OPF 0x00a
/* 000001011 - Two 32-bit edge boundary processing, little-endian, no CC */
#define EDGE32LN_OPF 0x00b
/* 000111110 - distance between 8 8-bit components */
#define PDIST_OPF 0x03e
/* 000010000 - convert 8-bit 3-D address to blocked byte address */
#define ARRAY8_OPF 0x010
/* 000010010 - convert 16-bit 3-D address to blocked byte address */
#define ARRAY16_OPF 0x012
/* 000010100 - convert 32-bit 3-D address to blocked byte address */
#define ARRAY32_OPF 0x014
/* 000011001 - Set the GSR.MASK field in preparation for a BSHUFFLE */
#define BMASK_OPF 0x019
/* 001001100 - Permute bytes as specified by GSR.MASK */
#define BSHUFFLE_OPF 0x04c
#define VIS_OPF_SHIFT 5
#define VIS_OPF_MASK (0x1ff << VIS_OPF_SHIFT)
#define RS1(INSN) (((INSN) >> 14) & 0x1f)
#define RS2(INSN) (((INSN) >> 0) & 0x1f)
#define RD(INSN) (((INSN) >> 25) & 0x1f)
static inline void maybe_flush_windows(unsigned int rs1, unsigned int rs2,
unsigned int rd, int from_kernel)
{
if (rs2 >= 16 || rs1 >= 16 || rd >= 16) {
if (from_kernel != 0)
__asm__ __volatile__("flushw");
else
flushw_user();
}
}
static unsigned long fetch_reg(unsigned int reg, struct pt_regs *regs)
{
unsigned long value;
if (reg < 16)
return (!reg ? 0 : regs->u_regs[reg]);
if (regs->tstate & TSTATE_PRIV) {
struct reg_window *win;
win = (struct reg_window *)(regs->u_regs[UREG_FP] + STACK_BIAS);
value = win->locals[reg - 16];
} else if (test_thread_flag(TIF_32BIT)) {
struct reg_window32 __user *win32;
win32 = (struct reg_window32 __user *)((unsigned long)((u32)regs->u_regs[UREG_FP]));
get_user(value, &win32->locals[reg - 16]);
} else {
struct reg_window __user *win;
win = (struct reg_window __user *)(regs->u_regs[UREG_FP] + STACK_BIAS);
get_user(value, &win->locals[reg - 16]);
}
return value;
}
static inline unsigned long __user *__fetch_reg_addr_user(unsigned int reg,
struct pt_regs *regs)
{
BUG_ON(reg < 16);
BUG_ON(regs->tstate & TSTATE_PRIV);
if (test_thread_flag(TIF_32BIT)) {
struct reg_window32 __user *win32;
win32 = (struct reg_window32 __user *)((unsigned long)((u32)regs->u_regs[UREG_FP]));
return (unsigned long __user *)&win32->locals[reg - 16];
} else {
struct reg_window __user *win;
win = (struct reg_window __user *)(regs->u_regs[UREG_FP] + STACK_BIAS);
return &win->locals[reg - 16];
}
}
static inline unsigned long *__fetch_reg_addr_kern(unsigned int reg,
struct pt_regs *regs)
{
BUG_ON(reg >= 16);
BUG_ON(regs->tstate & TSTATE_PRIV);
return ®s->u_regs[reg];
}
static void store_reg(struct pt_regs *regs, unsigned long val, unsigned long rd)
{
if (rd < 16) {
unsigned long *rd_kern = __fetch_reg_addr_kern(rd, regs);
*rd_kern = val;
} else {
unsigned long __user *rd_user = __fetch_reg_addr_user(rd, regs);
if (test_thread_flag(TIF_32BIT))
__put_user((u32)val, (u32 __user *)rd_user);
else
__put_user(val, rd_user);
}
}
static inline unsigned long fpd_regval(struct fpustate *f,
unsigned int insn_regnum)
{
insn_regnum = (((insn_regnum & 1) << 5) |
(insn_regnum & 0x1e));
return *(unsigned long *) &f->regs[insn_regnum];
}
static inline unsigned long *fpd_regaddr(struct fpustate *f,
unsigned int insn_regnum)
{
insn_regnum = (((insn_regnum & 1) << 5) |
(insn_regnum & 0x1e));
return (unsigned long *) &f->regs[insn_regnum];
}
static inline unsigned int fps_regval(struct fpustate *f,
unsigned int insn_regnum)
{
return f->regs[insn_regnum];
}
static inline unsigned int *fps_regaddr(struct fpustate *f,
unsigned int insn_regnum)
{
return &f->regs[insn_regnum];
}
struct edge_tab {
u16 left, right;
};
static struct edge_tab edge8_tab[8] = {
{ 0xff, 0x80 },
{ 0x7f, 0xc0 },
{ 0x3f, 0xe0 },
{ 0x1f, 0xf0 },
{ 0x0f, 0xf8 },
{ 0x07, 0xfc },
{ 0x03, 0xfe },
{ 0x01, 0xff },
};
static struct edge_tab edge8_tab_l[8] = {
{ 0xff, 0x01 },
{ 0xfe, 0x03 },
{ 0xfc, 0x07 },
{ 0xf8, 0x0f },
{ 0xf0, 0x1f },
{ 0xe0, 0x3f },
{ 0xc0, 0x7f },
{ 0x80, 0xff },
};
static struct edge_tab edge16_tab[4] = {
{ 0xf, 0x8 },
{ 0x7, 0xc },
{ 0x3, 0xe },
{ 0x1, 0xf },
};
static struct edge_tab edge16_tab_l[4] = {
{ 0xf, 0x1 },
{ 0xe, 0x3 },
{ 0xc, 0x7 },
{ 0x8, 0xf },
};
static struct edge_tab edge32_tab[2] = {
{ 0x3, 0x2 },
{ 0x1, 0x3 },
};
static struct edge_tab edge32_tab_l[2] = {
{ 0x3, 0x1 },
{ 0x2, 0x3 },
};
static void edge(struct pt_regs *regs, unsigned int insn, unsigned int opf)
{
unsigned long orig_rs1, rs1, orig_rs2, rs2, rd_val;
u16 left, right;
maybe_flush_windows(RS1(insn), RS2(insn), RD(insn), 0);
orig_rs1 = rs1 = fetch_reg(RS1(insn), regs);
orig_rs2 = rs2 = fetch_reg(RS2(insn), regs);
if (test_thread_flag(TIF_32BIT)) {
rs1 = rs1 & 0xffffffff;
rs2 = rs2 & 0xffffffff;
}
switch (opf) {
default:
case EDGE8_OPF:
case EDGE8N_OPF:
left = edge8_tab[rs1 & 0x7].left;
right = edge8_tab[rs2 & 0x7].right;
break;
case EDGE8L_OPF:
case EDGE8LN_OPF:
left = edge8_tab_l[rs1 & 0x7].left;
right = edge8_tab_l[rs2 & 0x7].right;
break;
case EDGE16_OPF:
case EDGE16N_OPF:
left = edge16_tab[(rs1 >> 1) & 0x3].left;
right = edge16_tab[(rs2 >> 1) & 0x3].right;
break;
case EDGE16L_OPF:
case EDGE16LN_OPF:
left = edge16_tab_l[(rs1 >> 1) & 0x3].left;
right = edge16_tab_l[(rs2 >> 1) & 0x3].right;
break;
case EDGE32_OPF:
case EDGE32N_OPF:
left = edge32_tab[(rs1 >> 2) & 0x1].left;
right = edge32_tab[(rs2 >> 2) & 0x1].right;
break;
case EDGE32L_OPF:
case EDGE32LN_OPF:
left = edge32_tab_l[(rs1 >> 2) & 0x1].left;
right = edge32_tab_l[(rs2 >> 2) & 0x1].right;
break;
}
if ((rs1 & ~0x7UL) == (rs2 & ~0x7UL))
rd_val = right & left;
else
rd_val = left;
store_reg(regs, rd_val, RD(insn));
switch (opf) {
case EDGE8_OPF:
case EDGE8L_OPF:
case EDGE16_OPF:
case EDGE16L_OPF:
case EDGE32_OPF:
case EDGE32L_OPF: {
unsigned long ccr, tstate;
__asm__ __volatile__("subcc %1, %2, %%g0\n\t"
"rd %%ccr, %0"
: "=r" (ccr)
: "r" (orig_rs1), "r" (orig_rs2)
: "cc");
tstate = regs->tstate & ~(TSTATE_XCC | TSTATE_ICC);
regs->tstate = tstate | (ccr << 32UL);
}
}
}
static void array(struct pt_regs *regs, unsigned int insn, unsigned int opf)
{
unsigned long rs1, rs2, rd_val;
unsigned int bits, bits_mask;
maybe_flush_windows(RS1(insn), RS2(insn), RD(insn), 0);
rs1 = fetch_reg(RS1(insn), regs);
rs2 = fetch_reg(RS2(insn), regs);
bits = (rs2 > 5 ? 5 : rs2);
bits_mask = (1UL << bits) - 1UL;
rd_val = ((((rs1 >> 11) & 0x3) << 0) |
(((rs1 >> 33) & 0x3) << 2) |
(((rs1 >> 55) & 0x1) << 4) |
(((rs1 >> 13) & 0xf) << 5) |
(((rs1 >> 35) & 0xf) << 9) |
(((rs1 >> 56) & 0xf) << 13) |
(((rs1 >> 17) & bits_mask) << 17) |
(((rs1 >> 39) & bits_mask) << (17 + bits)) |
(((rs1 >> 60) & 0xf) << (17 + (2*bits))));
switch (opf) {
case ARRAY16_OPF:
rd_val <<= 1;
break;
case ARRAY32_OPF:
rd_val <<= 2;
}
store_reg(regs, rd_val, RD(insn));
}
static void bmask(struct pt_regs *regs, unsigned int insn)
{
unsigned long rs1, rs2, rd_val, gsr;
maybe_flush_windows(RS1(insn), RS2(insn), RD(insn), 0);
rs1 = fetch_reg(RS1(insn), regs);
rs2 = fetch_reg(RS2(insn), regs);
rd_val = rs1 + rs2;
store_reg(regs, rd_val, RD(insn));
gsr = current_thread_info()->gsr[0] & 0xffffffff;
gsr |= rd_val << 32UL;
current_thread_info()->gsr[0] = gsr;
}
static void bshuffle(struct pt_regs *regs, unsigned int insn)
{
struct fpustate *f = FPUSTATE;
unsigned long rs1, rs2, rd_val;
unsigned long bmask, i;
bmask = current_thread_info()->gsr[0] >> 32UL;
rs1 = fpd_regval(f, RS1(insn));
rs2 = fpd_regval(f, RS2(insn));
rd_val = 0UL;
for (i = 0; i < 8; i++) {
unsigned long which = (bmask >> (i * 4)) & 0xf;
unsigned long byte;
if (which < 8)
byte = (rs1 >> (which * 8)) & 0xff;
else
byte = (rs2 >> ((which-8)*8)) & 0xff;
rd_val |= (byte << (i * 8));
}
*fpd_regaddr(f, RD(insn)) = rd_val;
}
static void pdist(struct pt_regs *regs, unsigned int insn)
{
struct fpustate *f = FPUSTATE;
unsigned long rs1, rs2, *rd, rd_val;
unsigned long i;
rs1 = fpd_regval(f, RS1(insn));
rs2 = fpd_regval(f, RS2(insn));
rd = fpd_regaddr(f, RD(insn));
rd_val = *rd;
for (i = 0; i < 8; i++) {
s16 s1, s2;
s1 = (rs1 >> (56 - (i * 8))) & 0xff;
s2 = (rs2 >> (56 - (i * 8))) & 0xff;
/* Absolute value of difference. */
s1 -= s2;
if (s1 < 0)
s1 = ~s1 + 1;
rd_val += s1;
}
*rd = rd_val;
}
static void pformat(struct pt_regs *regs, unsigned int insn, unsigned int opf)
{
struct fpustate *f = FPUSTATE;
unsigned long rs1, rs2, gsr, scale, rd_val;
gsr = current_thread_info()->gsr[0];
scale = (gsr >> 3) & (opf == FPACK16_OPF ? 0xf : 0x1f);
switch (opf) {
case FPACK16_OPF: {
unsigned long byte;
rs2 = fpd_regval(f, RS2(insn));
rd_val = 0;
for (byte = 0; byte < 4; byte++) {
unsigned int val;
s16 src = (rs2 >> (byte * 16UL)) & 0xffffUL;
int scaled = src << scale;
int from_fixed = scaled >> 7;
val = ((from_fixed < 0) ?
0 :
(from_fixed > 255) ?
255 : from_fixed);
rd_val |= (val << (8 * byte));
}
*fps_regaddr(f, RD(insn)) = rd_val;
break;
}
case FPACK32_OPF: {
unsigned long word;
rs1 = fpd_regval(f, RS1(insn));
rs2 = fpd_regval(f, RS2(insn));
rd_val = (rs1 << 8) & ~(0x000000ff000000ffUL);
for (word = 0; word < 2; word++) {
unsigned long val;
s32 src = (rs2 >> (word * 32UL));
s64 scaled = src << scale;
s64 from_fixed = scaled >> 23;
val = ((from_fixed < 0) ?
0 :
(from_fixed > 255) ?
255 : from_fixed);
rd_val |= (val << (32 * word));
}
*fpd_regaddr(f, RD(insn)) = rd_val;
break;
}
case FPACKFIX_OPF: {
unsigned long word;
rs2 = fpd_regval(f, RS2(insn));
rd_val = 0;
for (word = 0; word < 2; word++) {
long val;
s32 src = (rs2 >> (word * 32UL));
s64 scaled = src << scale;
s64 from_fixed = scaled >> 16;
val = ((from_fixed < -32768) ?
-32768 :
(from_fixed > 32767) ?
32767 : from_fixed);
rd_val |= ((val & 0xffff) << (word * 16));
}
*fps_regaddr(f, RD(insn)) = rd_val;
break;
}
case FEXPAND_OPF: {
unsigned long byte;
rs2 = fps_regval(f, RS2(insn));
rd_val = 0;
for (byte = 0; byte < 4; byte++) {
unsigned long val;
u8 src = (rs2 >> (byte * 8)) & 0xff;
val = src << 4;
rd_val |= (val << (byte * 16));
}
*fpd_regaddr(f, RD(insn)) = rd_val;
break;
}
case FPMERGE_OPF: {
rs1 = fps_regval(f, RS1(insn));
rs2 = fps_regval(f, RS2(insn));
rd_val = (((rs2 & 0x000000ff) << 0) |
((rs1 & 0x000000ff) << 8) |
((rs2 & 0x0000ff00) << 8) |
((rs1 & 0x0000ff00) << 16) |
((rs2 & 0x00ff0000) << 16) |
((rs1 & 0x00ff0000) << 24) |
((rs2 & 0xff000000) << 24) |
((rs1 & 0xff000000) << 32));
*fpd_regaddr(f, RD(insn)) = rd_val;
break;
}
}
}
static void pmul(struct pt_regs *regs, unsigned int insn, unsigned int opf)
{
struct fpustate *f = FPUSTATE;
unsigned long rs1, rs2, rd_val;
switch (opf) {
case FMUL8x16_OPF: {
unsigned long byte;
rs1 = fps_regval(f, RS1(insn));
rs2 = fpd_regval(f, RS2(insn));
rd_val = 0;
for (byte = 0; byte < 4; byte++) {
u16 src1 = (rs1 >> (byte * 8)) & 0x00ff;
s16 src2 = (rs2 >> (byte * 16)) & 0xffff;
u32 prod = src1 * src2;
u16 scaled = ((prod & 0x00ffff00) >> 8);
/* Round up. */
if (prod & 0x80)
scaled++;
rd_val |= ((scaled & 0xffffUL) << (byte * 16UL));
}
*fpd_regaddr(f, RD(insn)) = rd_val;
break;
}
case FMUL8x16AU_OPF:
case FMUL8x16AL_OPF: {
unsigned long byte;
s16 src2;
rs1 = fps_regval(f, RS1(insn));
rs2 = fps_regval(f, RS2(insn));
rd_val = 0;
src2 = rs2 >> (opf == FMUL8x16AU_OPF ? 16 : 0);
for (byte = 0; byte < 4; byte++) {
u16 src1 = (rs1 >> (byte * 8)) & 0x00ff;
u32 prod = src1 * src2;
u16 scaled = ((prod & 0x00ffff00) >> 8);
/* Round up. */
if (prod & 0x80)
scaled++;
rd_val |= ((scaled & 0xffffUL) << (byte * 16UL));
}
*fpd_regaddr(f, RD(insn)) = rd_val;
break;
}
case FMUL8SUx16_OPF:
case FMUL8ULx16_OPF: {
unsigned long byte, ushift;
rs1 = fpd_regval(f, RS1(insn));
rs2 = fpd_regval(f, RS2(insn));
rd_val = 0;
ushift = (opf == FMUL8SUx16_OPF) ? 8 : 0;
for (byte = 0; byte < 4; byte++) {
u16 src1;
s16 src2;
u32 prod;
u16 scaled;
src1 = ((rs1 >> ((16 * byte) + ushift)) & 0x00ff);
src2 = ((rs2 >> (16 * byte)) & 0xffff);
prod = src1 * src2;
scaled = ((prod & 0x00ffff00) >> 8);
/* Round up. */
if (prod & 0x80)
scaled++;
rd_val |= ((scaled & 0xffffUL) << (byte * 16UL));
}
*fpd_regaddr(f, RD(insn)) = rd_val;
break;
}
case FMULD8SUx16_OPF:
case FMULD8ULx16_OPF: {
unsigned long byte, ushift;
rs1 = fps_regval(f, RS1(insn));
rs2 = fps_regval(f, RS2(insn));
rd_val = 0;
ushift = (opf == FMULD8SUx16_OPF) ? 8 : 0;
for (byte = 0; byte < 2; byte++) {
u16 src1;
s16 src2;
u32 prod;
u16 scaled;
src1 = ((rs1 >> ((16 * byte) + ushift)) & 0x00ff);
src2 = ((rs2 >> (16 * byte)) & 0xffff);
prod = src1 * src2;
scaled = ((prod & 0x00ffff00) >> 8);
/* Round up. */
if (prod & 0x80)
scaled++;
rd_val |= ((scaled & 0xffffUL) <<
((byte * 32UL) + 7UL));
}
*fpd_regaddr(f, RD(insn)) = rd_val;
break;
}
}
}
static void pcmp(struct pt_regs *regs, unsigned int insn, unsigned int opf)
{
struct fpustate *f = FPUSTATE;
unsigned long rs1, rs2, rd_val, i;
rs1 = fpd_regval(f, RS1(insn));
rs2 = fpd_regval(f, RS2(insn));
rd_val = 0;
switch (opf) {
case FCMPGT16_OPF:
for (i = 0; i < 4; i++) {
s16 a = (rs1 >> (i * 16)) & 0xffff;
s16 b = (rs2 >> (i * 16)) & 0xffff;
if (a > b)
rd_val |= 8 >> i;
}
break;
case FCMPGT32_OPF:
for (i = 0; i < 2; i++) {
s32 a = (rs1 >> (i * 32)) & 0xffffffff;
s32 b = (rs2 >> (i * 32)) & 0xffffffff;
if (a > b)
rd_val |= 2 >> i;
}
break;
case FCMPLE16_OPF:
for (i = 0; i < 4; i++) {
s16 a = (rs1 >> (i * 16)) & 0xffff;
s16 b = (rs2 >> (i * 16)) & 0xffff;
if (a <= b)
rd_val |= 8 >> i;
}
break;
case FCMPLE32_OPF:
for (i = 0; i < 2; i++) {
s32 a = (rs1 >> (i * 32)) & 0xffffffff;
s32 b = (rs2 >> (i * 32)) & 0xffffffff;
if (a <= b)
rd_val |= 2 >> i;
}
break;
case FCMPNE16_OPF:
for (i = 0; i < 4; i++) {
s16 a = (rs1 >> (i * 16)) & 0xffff;
s16 b = (rs2 >> (i * 16)) & 0xffff;
if (a != b)
rd_val |= 8 >> i;
}
break;
case FCMPNE32_OPF:
for (i = 0; i < 2; i++) {
s32 a = (rs1 >> (i * 32)) & 0xffffffff;
s32 b = (rs2 >> (i * 32)) & 0xffffffff;
if (a != b)
rd_val |= 2 >> i;
}
break;
case FCMPEQ16_OPF:
for (i = 0; i < 4; i++) {
s16 a = (rs1 >> (i * 16)) & 0xffff;
s16 b = (rs2 >> (i * 16)) & 0xffff;
if (a == b)
rd_val |= 8 >> i;
}
break;
case FCMPEQ32_OPF:
for (i = 0; i < 2; i++) {
s32 a = (rs1 >> (i * 32)) & 0xffffffff;
s32 b = (rs2 >> (i * 32)) & 0xffffffff;
if (a == b)
rd_val |= 2 >> i;
}
break;
}
maybe_flush_windows(0, 0, RD(insn), 0);
store_reg(regs, rd_val, RD(insn));
}
/* Emulate the VIS instructions which are not implemented in
* hardware on Niagara.
*/
int vis_emul(struct pt_regs *regs, unsigned int insn)
{
unsigned long pc = regs->tpc;
unsigned int opf;
BUG_ON(regs->tstate & TSTATE_PRIV);
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, 0);
if (test_thread_flag(TIF_32BIT))
pc = (u32)pc;
if (get_user(insn, (u32 __user *) pc))
return -EFAULT;
save_and_clear_fpu();
opf = (insn & VIS_OPF_MASK) >> VIS_OPF_SHIFT;
switch (opf) {
default:
return -EINVAL;
/* Pixel Formatting Instructions. */
case FPACK16_OPF:
case FPACK32_OPF:
case FPACKFIX_OPF:
case FEXPAND_OPF:
case FPMERGE_OPF:
pformat(regs, insn, opf);
break;
/* Partitioned Multiply Instructions */
case FMUL8x16_OPF:
case FMUL8x16AU_OPF:
case FMUL8x16AL_OPF:
case FMUL8SUx16_OPF:
case FMUL8ULx16_OPF:
case FMULD8SUx16_OPF:
case FMULD8ULx16_OPF:
pmul(regs, insn, opf);
break;
/* Pixel Compare Instructions */
case FCMPGT16_OPF:
case FCMPGT32_OPF:
case FCMPLE16_OPF:
case FCMPLE32_OPF:
case FCMPNE16_OPF:
case FCMPNE32_OPF:
case FCMPEQ16_OPF:
case FCMPEQ32_OPF:
pcmp(regs, insn, opf);
break;
/* Edge Handling Instructions */
case EDGE8_OPF:
case EDGE8N_OPF:
case EDGE8L_OPF:
case EDGE8LN_OPF:
case EDGE16_OPF:
case EDGE16N_OPF:
case EDGE16L_OPF:
case EDGE16LN_OPF:
case EDGE32_OPF:
case EDGE32N_OPF:
case EDGE32L_OPF:
case EDGE32LN_OPF:
edge(regs, insn, opf);
break;
/* Pixel Component Distance */
case PDIST_OPF:
pdist(regs, insn);
break;
/* Three-Dimensional Array Addressing Instructions */
case ARRAY8_OPF:
case ARRAY16_OPF:
case ARRAY32_OPF:
array(regs, insn, opf);
break;
/* Byte Mask and Shuffle Instructions */
case BMASK_OPF:
bmask(regs, insn);
break;
case BSHUFFLE_OPF:
bshuffle(regs, insn);
break;
}
regs->tpc = regs->tnpc;
regs->tnpc += 4;
return 0;
}
| gpl-2.0 |
tepelmann/linux-perf | arch/sh/boards/mach-cayman/setup.c | 4555 | 5556 | /*
* arch/sh/mach-cayman/setup.c
*
* SH5 Cayman support
*
* Copyright (C) 2002 David J. Mckay & Benedict Gaster
* Copyright (C) 2003 - 2007 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <cpu/irq.h>
/*
* Platform Dependent Interrupt Priorities.
*/
/* Using defaults defined in irq.h */
#define RES NO_PRIORITY /* Disabled */
#define IR0 IRL0_PRIORITY /* IRLs */
#define IR1 IRL1_PRIORITY
#define IR2 IRL2_PRIORITY
#define IR3 IRL3_PRIORITY
#define PCA INTA_PRIORITY /* PCI Ints */
#define PCB INTB_PRIORITY
#define PCC INTC_PRIORITY
#define PCD INTD_PRIORITY
#define SER TOP_PRIORITY
#define ERR TOP_PRIORITY
#define PW0 TOP_PRIORITY
#define PW1 TOP_PRIORITY
#define PW2 TOP_PRIORITY
#define PW3 TOP_PRIORITY
#define DM0 NO_PRIORITY /* DMA Ints */
#define DM1 NO_PRIORITY
#define DM2 NO_PRIORITY
#define DM3 NO_PRIORITY
#define DAE NO_PRIORITY
#define TU0 TIMER_PRIORITY /* TMU Ints */
#define TU1 NO_PRIORITY
#define TU2 NO_PRIORITY
#define TI2 NO_PRIORITY
#define ATI NO_PRIORITY /* RTC Ints */
#define PRI NO_PRIORITY
#define CUI RTC_PRIORITY
#define ERI SCIF_PRIORITY /* SCIF Ints */
#define RXI SCIF_PRIORITY
#define BRI SCIF_PRIORITY
#define TXI SCIF_PRIORITY
#define ITI TOP_PRIORITY /* WDT Ints */
/* Setup for the SMSC FDC37C935 */
#define SMSC_SUPERIO_BASE 0x04000000
#define SMSC_CONFIG_PORT_ADDR 0x3f0
#define SMSC_INDEX_PORT_ADDR SMSC_CONFIG_PORT_ADDR
#define SMSC_DATA_PORT_ADDR 0x3f1
#define SMSC_ENTER_CONFIG_KEY 0x55
#define SMSC_EXIT_CONFIG_KEY 0xaa
#define SMCS_LOGICAL_DEV_INDEX 0x07
#define SMSC_DEVICE_ID_INDEX 0x20
#define SMSC_DEVICE_REV_INDEX 0x21
#define SMSC_ACTIVATE_INDEX 0x30
#define SMSC_PRIMARY_BASE_INDEX 0x60
#define SMSC_SECONDARY_BASE_INDEX 0x62
#define SMSC_PRIMARY_INT_INDEX 0x70
#define SMSC_SECONDARY_INT_INDEX 0x72
#define SMSC_IDE1_DEVICE 1
#define SMSC_KEYBOARD_DEVICE 7
#define SMSC_CONFIG_REGISTERS 8
#define SMSC_SUPERIO_READ_INDEXED(index) ({ \
outb((index), SMSC_INDEX_PORT_ADDR); \
inb(SMSC_DATA_PORT_ADDR); })
#define SMSC_SUPERIO_WRITE_INDEXED(val, index) ({ \
outb((index), SMSC_INDEX_PORT_ADDR); \
outb((val), SMSC_DATA_PORT_ADDR); })
#define IDE1_PRIMARY_BASE 0x01f0
#define IDE1_SECONDARY_BASE 0x03f6
unsigned long smsc_superio_virt;
int platform_int_priority[NR_INTC_IRQS] = {
IR0, IR1, IR2, IR3, PCA, PCB, PCC, PCD, /* IRQ 0- 7 */
RES, RES, RES, RES, SER, ERR, PW3, PW2, /* IRQ 8-15 */
PW1, PW0, DM0, DM1, DM2, DM3, DAE, RES, /* IRQ 16-23 */
RES, RES, RES, RES, RES, RES, RES, RES, /* IRQ 24-31 */
TU0, TU1, TU2, TI2, ATI, PRI, CUI, ERI, /* IRQ 32-39 */
RXI, BRI, TXI, RES, RES, RES, RES, RES, /* IRQ 40-47 */
RES, RES, RES, RES, RES, RES, RES, RES, /* IRQ 48-55 */
RES, RES, RES, RES, RES, RES, RES, ITI, /* IRQ 56-63 */
};
static int __init smsc_superio_setup(void)
{
unsigned char devid, devrev;
smsc_superio_virt = (unsigned long)ioremap_nocache(SMSC_SUPERIO_BASE, 1024);
if (!smsc_superio_virt) {
panic("Unable to remap SMSC SuperIO\n");
}
/* Initially the chip is in run state */
/* Put it into configuration state */
outb(SMSC_ENTER_CONFIG_KEY, SMSC_CONFIG_PORT_ADDR);
outb(SMSC_ENTER_CONFIG_KEY, SMSC_CONFIG_PORT_ADDR);
/* Read device ID info */
devid = SMSC_SUPERIO_READ_INDEXED(SMSC_DEVICE_ID_INDEX);
devrev = SMSC_SUPERIO_READ_INDEXED(SMSC_DEVICE_REV_INDEX);
printk("SMSC SuperIO devid %02x rev %02x\n", devid, devrev);
/* Select the keyboard device */
SMSC_SUPERIO_WRITE_INDEXED(SMSC_KEYBOARD_DEVICE, SMCS_LOGICAL_DEV_INDEX);
/* enable it */
SMSC_SUPERIO_WRITE_INDEXED(1, SMSC_ACTIVATE_INDEX);
/* Select the interrupts */
/* On a PC keyboard is IRQ1, mouse is IRQ12 */
SMSC_SUPERIO_WRITE_INDEXED(1, SMSC_PRIMARY_INT_INDEX);
SMSC_SUPERIO_WRITE_INDEXED(12, SMSC_SECONDARY_INT_INDEX);
#ifdef CONFIG_IDE
/*
* Only IDE1 exists on the Cayman
*/
/* Power it on */
SMSC_SUPERIO_WRITE_INDEXED(1 << SMSC_IDE1_DEVICE, 0x22);
SMSC_SUPERIO_WRITE_INDEXED(SMSC_IDE1_DEVICE, SMCS_LOGICAL_DEV_INDEX);
SMSC_SUPERIO_WRITE_INDEXED(1, SMSC_ACTIVATE_INDEX);
SMSC_SUPERIO_WRITE_INDEXED(IDE1_PRIMARY_BASE >> 8,
SMSC_PRIMARY_BASE_INDEX + 0);
SMSC_SUPERIO_WRITE_INDEXED(IDE1_PRIMARY_BASE & 0xff,
SMSC_PRIMARY_BASE_INDEX + 1);
SMSC_SUPERIO_WRITE_INDEXED(IDE1_SECONDARY_BASE >> 8,
SMSC_SECONDARY_BASE_INDEX + 0);
SMSC_SUPERIO_WRITE_INDEXED(IDE1_SECONDARY_BASE & 0xff,
SMSC_SECONDARY_BASE_INDEX + 1);
SMSC_SUPERIO_WRITE_INDEXED(14, SMSC_PRIMARY_INT_INDEX);
SMSC_SUPERIO_WRITE_INDEXED(SMSC_CONFIG_REGISTERS,
SMCS_LOGICAL_DEV_INDEX);
SMSC_SUPERIO_WRITE_INDEXED(0x00, 0xc2); /* GP42 = nIDE1_OE */
SMSC_SUPERIO_WRITE_INDEXED(0x01, 0xc5); /* GP45 = IDE1_IRQ */
SMSC_SUPERIO_WRITE_INDEXED(0x00, 0xc6); /* GP46 = nIOROP */
SMSC_SUPERIO_WRITE_INDEXED(0x00, 0xc7); /* GP47 = nIOWOP */
#endif
/* Exit the configuration state */
outb(SMSC_EXIT_CONFIG_KEY, SMSC_CONFIG_PORT_ADDR);
return 0;
}
device_initcall(smsc_superio_setup);
static void __iomem *cayman_ioport_map(unsigned long port, unsigned int len)
{
if (port < 0x400) {
extern unsigned long smsc_superio_virt;
return (void __iomem *)((port << 2) | smsc_superio_virt);
}
return (void __iomem *)port;
}
extern void init_cayman_irq(void);
static struct sh_machine_vector mv_cayman __initmv = {
.mv_name = "Hitachi Cayman",
.mv_ioport_map = cayman_ioport_map,
.mv_init_irq = init_cayman_irq,
};
| gpl-2.0 |
Cl3Kener/UBER-L | drivers/staging/media/as102/as102_usb_drv.c | 4811 | 12223 | /*
* Abilis Systems Single DVB-T Receiver
* Copyright (C) 2008 Pierrick Hascoet <pierrick.hascoet@abilis.com>
* Copyright (C) 2010 Devin Heitmueller <dheitmueller@kernellabs.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, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/usb.h>
#include "as102_drv.h"
#include "as102_usb_drv.h"
#include "as102_fw.h"
static void as102_usb_disconnect(struct usb_interface *interface);
static int as102_usb_probe(struct usb_interface *interface,
const struct usb_device_id *id);
static int as102_usb_start_stream(struct as102_dev_t *dev);
static void as102_usb_stop_stream(struct as102_dev_t *dev);
static int as102_open(struct inode *inode, struct file *file);
static int as102_release(struct inode *inode, struct file *file);
static struct usb_device_id as102_usb_id_table[] = {
{ USB_DEVICE(AS102_USB_DEVICE_VENDOR_ID, AS102_USB_DEVICE_PID_0001) },
{ USB_DEVICE(PCTV_74E_USB_VID, PCTV_74E_USB_PID) },
{ USB_DEVICE(ELGATO_EYETV_DTT_USB_VID, ELGATO_EYETV_DTT_USB_PID) },
{ USB_DEVICE(NBOX_DVBT_DONGLE_USB_VID, NBOX_DVBT_DONGLE_USB_PID) },
{ USB_DEVICE(SKY_IT_DIGITAL_KEY_USB_VID, SKY_IT_DIGITAL_KEY_USB_PID) },
{ } /* Terminating entry */
};
/* Note that this table must always have the same number of entries as the
as102_usb_id_table struct */
static const char * const as102_device_names[] = {
AS102_REFERENCE_DESIGN,
AS102_PCTV_74E,
AS102_ELGATO_EYETV_DTT_NAME,
AS102_NBOX_DVBT_DONGLE_NAME,
AS102_SKY_IT_DIGITAL_KEY_NAME,
NULL /* Terminating entry */
};
/* eLNA configuration: devices built on the reference design work best
with 0xA0, while custom designs seem to require 0xC0 */
static uint8_t const as102_elna_cfg[] = {
0xA0,
0xC0,
0xC0,
0xA0,
0xA0,
0x00 /* Terminating entry */
};
struct usb_driver as102_usb_driver = {
.name = DRIVER_FULL_NAME,
.probe = as102_usb_probe,
.disconnect = as102_usb_disconnect,
.id_table = as102_usb_id_table
};
static const struct file_operations as102_dev_fops = {
.owner = THIS_MODULE,
.open = as102_open,
.release = as102_release,
};
static struct usb_class_driver as102_usb_class_driver = {
.name = "aton2-%d",
.fops = &as102_dev_fops,
.minor_base = AS102_DEVICE_MAJOR,
};
static int as102_usb_xfer_cmd(struct as10x_bus_adapter_t *bus_adap,
unsigned char *send_buf, int send_buf_len,
unsigned char *recv_buf, int recv_buf_len)
{
int ret = 0;
ENTER();
if (send_buf != NULL) {
ret = usb_control_msg(bus_adap->usb_dev,
usb_sndctrlpipe(bus_adap->usb_dev, 0),
AS102_USB_DEVICE_TX_CTRL_CMD,
USB_DIR_OUT | USB_TYPE_VENDOR |
USB_RECIP_DEVICE,
bus_adap->cmd_xid, /* value */
0, /* index */
send_buf, send_buf_len,
USB_CTRL_SET_TIMEOUT /* 200 */);
if (ret < 0) {
dprintk(debug, "usb_control_msg(send) failed, err %i\n",
ret);
return ret;
}
if (ret != send_buf_len) {
dprintk(debug, "only wrote %d of %d bytes\n",
ret, send_buf_len);
return -1;
}
}
if (recv_buf != NULL) {
#ifdef TRACE
dprintk(debug, "want to read: %d bytes\n", recv_buf_len);
#endif
ret = usb_control_msg(bus_adap->usb_dev,
usb_rcvctrlpipe(bus_adap->usb_dev, 0),
AS102_USB_DEVICE_RX_CTRL_CMD,
USB_DIR_IN | USB_TYPE_VENDOR |
USB_RECIP_DEVICE,
bus_adap->cmd_xid, /* value */
0, /* index */
recv_buf, recv_buf_len,
USB_CTRL_GET_TIMEOUT /* 200 */);
if (ret < 0) {
dprintk(debug, "usb_control_msg(recv) failed, err %i\n",
ret);
return ret;
}
#ifdef TRACE
dprintk(debug, "read %d bytes\n", recv_buf_len);
#endif
}
LEAVE();
return ret;
}
static int as102_send_ep1(struct as10x_bus_adapter_t *bus_adap,
unsigned char *send_buf,
int send_buf_len,
int swap32)
{
int ret = 0, actual_len;
ret = usb_bulk_msg(bus_adap->usb_dev,
usb_sndbulkpipe(bus_adap->usb_dev, 1),
send_buf, send_buf_len, &actual_len, 200);
if (ret) {
dprintk(debug, "usb_bulk_msg(send) failed, err %i\n", ret);
return ret;
}
if (actual_len != send_buf_len) {
dprintk(debug, "only wrote %d of %d bytes\n",
actual_len, send_buf_len);
return -1;
}
return ret ? ret : actual_len;
}
static int as102_read_ep2(struct as10x_bus_adapter_t *bus_adap,
unsigned char *recv_buf, int recv_buf_len)
{
int ret = 0, actual_len;
if (recv_buf == NULL)
return -EINVAL;
ret = usb_bulk_msg(bus_adap->usb_dev,
usb_rcvbulkpipe(bus_adap->usb_dev, 2),
recv_buf, recv_buf_len, &actual_len, 200);
if (ret) {
dprintk(debug, "usb_bulk_msg(recv) failed, err %i\n", ret);
return ret;
}
if (actual_len != recv_buf_len) {
dprintk(debug, "only read %d of %d bytes\n",
actual_len, recv_buf_len);
return -1;
}
return ret ? ret : actual_len;
}
struct as102_priv_ops_t as102_priv_ops = {
.upload_fw_pkt = as102_send_ep1,
.xfer_cmd = as102_usb_xfer_cmd,
.as102_read_ep2 = as102_read_ep2,
.start_stream = as102_usb_start_stream,
.stop_stream = as102_usb_stop_stream,
};
static int as102_submit_urb_stream(struct as102_dev_t *dev, struct urb *urb)
{
int err;
usb_fill_bulk_urb(urb,
dev->bus_adap.usb_dev,
usb_rcvbulkpipe(dev->bus_adap.usb_dev, 0x2),
urb->transfer_buffer,
AS102_USB_BUF_SIZE,
as102_urb_stream_irq,
dev);
err = usb_submit_urb(urb, GFP_ATOMIC);
if (err)
dprintk(debug, "%s: usb_submit_urb failed\n", __func__);
return err;
}
void as102_urb_stream_irq(struct urb *urb)
{
struct as102_dev_t *as102_dev = urb->context;
if (urb->actual_length > 0) {
dvb_dmx_swfilter(&as102_dev->dvb_dmx,
urb->transfer_buffer,
urb->actual_length);
} else {
if (urb->actual_length == 0)
memset(urb->transfer_buffer, 0, AS102_USB_BUF_SIZE);
}
/* is not stopped, re-submit urb */
if (as102_dev->streaming)
as102_submit_urb_stream(as102_dev, urb);
}
static void as102_free_usb_stream_buffer(struct as102_dev_t *dev)
{
int i;
ENTER();
for (i = 0; i < MAX_STREAM_URB; i++)
usb_free_urb(dev->stream_urb[i]);
usb_free_coherent(dev->bus_adap.usb_dev,
MAX_STREAM_URB * AS102_USB_BUF_SIZE,
dev->stream,
dev->dma_addr);
LEAVE();
}
static int as102_alloc_usb_stream_buffer(struct as102_dev_t *dev)
{
int i, ret = 0;
ENTER();
dev->stream = usb_alloc_coherent(dev->bus_adap.usb_dev,
MAX_STREAM_URB * AS102_USB_BUF_SIZE,
GFP_KERNEL,
&dev->dma_addr);
if (!dev->stream) {
dprintk(debug, "%s: usb_buffer_alloc failed\n", __func__);
return -ENOMEM;
}
memset(dev->stream, 0, MAX_STREAM_URB * AS102_USB_BUF_SIZE);
/* init urb buffers */
for (i = 0; i < MAX_STREAM_URB; i++) {
struct urb *urb;
urb = usb_alloc_urb(0, GFP_ATOMIC);
if (urb == NULL) {
dprintk(debug, "%s: usb_alloc_urb failed\n", __func__);
as102_free_usb_stream_buffer(dev);
return -ENOMEM;
}
urb->transfer_buffer = dev->stream + (i * AS102_USB_BUF_SIZE);
urb->transfer_dma = dev->dma_addr + (i * AS102_USB_BUF_SIZE);
urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
urb->transfer_buffer_length = AS102_USB_BUF_SIZE;
dev->stream_urb[i] = urb;
}
LEAVE();
return ret;
}
static void as102_usb_stop_stream(struct as102_dev_t *dev)
{
int i;
for (i = 0; i < MAX_STREAM_URB; i++)
usb_kill_urb(dev->stream_urb[i]);
}
static int as102_usb_start_stream(struct as102_dev_t *dev)
{
int i, ret = 0;
for (i = 0; i < MAX_STREAM_URB; i++) {
ret = as102_submit_urb_stream(dev, dev->stream_urb[i]);
if (ret) {
as102_usb_stop_stream(dev);
return ret;
}
}
return 0;
}
static void as102_usb_release(struct kref *kref)
{
struct as102_dev_t *as102_dev;
ENTER();
as102_dev = container_of(kref, struct as102_dev_t, kref);
if (as102_dev != NULL) {
usb_put_dev(as102_dev->bus_adap.usb_dev);
kfree(as102_dev);
}
LEAVE();
}
static void as102_usb_disconnect(struct usb_interface *intf)
{
struct as102_dev_t *as102_dev;
ENTER();
/* extract as102_dev_t from usb_device private data */
as102_dev = usb_get_intfdata(intf);
/* unregister dvb layer */
as102_dvb_unregister(as102_dev);
/* free usb buffers */
as102_free_usb_stream_buffer(as102_dev);
usb_set_intfdata(intf, NULL);
/* usb unregister device */
usb_deregister_dev(intf, &as102_usb_class_driver);
/* decrement usage counter */
kref_put(&as102_dev->kref, as102_usb_release);
pr_info("%s: device has been disconnected\n", DRIVER_NAME);
LEAVE();
}
static int as102_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
int ret;
struct as102_dev_t *as102_dev;
int i;
ENTER();
/* This should never actually happen */
if ((sizeof(as102_usb_id_table) / sizeof(struct usb_device_id)) !=
(sizeof(as102_device_names) / sizeof(const char *))) {
pr_err("Device names table invalid size");
return -EINVAL;
}
as102_dev = kzalloc(sizeof(struct as102_dev_t), GFP_KERNEL);
if (as102_dev == NULL) {
err("%s: kzalloc failed", __func__);
return -ENOMEM;
}
/* Assign the user-friendly device name */
for (i = 0; i < (sizeof(as102_usb_id_table) /
sizeof(struct usb_device_id)); i++) {
if (id == &as102_usb_id_table[i]) {
as102_dev->name = as102_device_names[i];
as102_dev->elna_cfg = as102_elna_cfg[i];
}
}
if (as102_dev->name == NULL)
as102_dev->name = "Unknown AS102 device";
/* set private callback functions */
as102_dev->bus_adap.ops = &as102_priv_ops;
/* init cmd token for usb bus */
as102_dev->bus_adap.cmd = &as102_dev->bus_adap.token.usb.c;
as102_dev->bus_adap.rsp = &as102_dev->bus_adap.token.usb.r;
/* init kernel device reference */
kref_init(&as102_dev->kref);
/* store as102 device to usb_device private data */
usb_set_intfdata(intf, (void *) as102_dev);
/* store in as102 device the usb_device pointer */
as102_dev->bus_adap.usb_dev = usb_get_dev(interface_to_usbdev(intf));
/* we can register the device now, as it is ready */
ret = usb_register_dev(intf, &as102_usb_class_driver);
if (ret < 0) {
/* something prevented us from registering this driver */
err("%s: usb_register_dev() failed (errno = %d)",
__func__, ret);
goto failed;
}
pr_info("%s: device has been detected\n", DRIVER_NAME);
/* request buffer allocation for streaming */
ret = as102_alloc_usb_stream_buffer(as102_dev);
if (ret != 0)
goto failed;
/* register dvb layer */
ret = as102_dvb_register(as102_dev);
LEAVE();
return ret;
failed:
usb_set_intfdata(intf, NULL);
kfree(as102_dev);
return ret;
}
static int as102_open(struct inode *inode, struct file *file)
{
int ret = 0, minor = 0;
struct usb_interface *intf = NULL;
struct as102_dev_t *dev = NULL;
ENTER();
/* read minor from inode */
minor = iminor(inode);
/* fetch device from usb interface */
intf = usb_find_interface(&as102_usb_driver, minor);
if (intf == NULL) {
pr_err("%s: can't find device for minor %d\n",
__func__, minor);
ret = -ENODEV;
goto exit;
}
/* get our device */
dev = usb_get_intfdata(intf);
if (dev == NULL) {
ret = -EFAULT;
goto exit;
}
/* save our device object in the file's private structure */
file->private_data = dev;
/* increment our usage count for the device */
kref_get(&dev->kref);
exit:
LEAVE();
return ret;
}
static int as102_release(struct inode *inode, struct file *file)
{
int ret = 0;
struct as102_dev_t *dev = NULL;
ENTER();
dev = file->private_data;
if (dev != NULL) {
/* decrement the count on our device */
kref_put(&dev->kref, as102_usb_release);
}
LEAVE();
return ret;
}
MODULE_DEVICE_TABLE(usb, as102_usb_id_table);
| gpl-2.0 |
HardbitCoded/linux-3.4-rtws | tools/usb/testusb.c | 4811 | 13009 | /* $(CROSS_COMPILE)cc -Wall -Wextra -g -lpthread -o testusb testusb.c */
/*
* Copyright (c) 2002 by David Brownell
* Copyright (c) 2010 by Samsung Electronics
* Author: Michal Nazarewicz <mina86@mina86.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.
*/
/*
* This program issues ioctls to perform the tests implemented by the
* kernel driver. It can generate a variety of transfer patterns; you
* should make sure to test both regular streaming and mixes of
* transfer sizes (including short transfers).
*
* For more information on how this can be used and on USB testing
* refer to <URL:http://www.linux-usb.org/usbtest/>.
*/
#include <stdio.h>
#include <string.h>
#include <ftw.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/usbdevice_fs.h>
/*-------------------------------------------------------------------------*/
#define TEST_CASES 30
// FIXME make these public somewhere; usbdevfs.h?
struct usbtest_param {
// inputs
unsigned test_num; /* 0..(TEST_CASES-1) */
unsigned iterations;
unsigned length;
unsigned vary;
unsigned sglen;
// outputs
struct timeval duration;
};
#define USBTEST_REQUEST _IOWR('U', 100, struct usbtest_param)
/*-------------------------------------------------------------------------*/
/* #include <linux/usb_ch9.h> */
#define USB_DT_DEVICE 0x01
#define USB_DT_INTERFACE 0x04
#define USB_CLASS_PER_INTERFACE 0 /* for DeviceClass */
#define USB_CLASS_VENDOR_SPEC 0xff
struct usb_device_descriptor {
__u8 bLength;
__u8 bDescriptorType;
__u16 bcdUSB;
__u8 bDeviceClass;
__u8 bDeviceSubClass;
__u8 bDeviceProtocol;
__u8 bMaxPacketSize0;
__u16 idVendor;
__u16 idProduct;
__u16 bcdDevice;
__u8 iManufacturer;
__u8 iProduct;
__u8 iSerialNumber;
__u8 bNumConfigurations;
} __attribute__ ((packed));
struct usb_interface_descriptor {
__u8 bLength;
__u8 bDescriptorType;
__u8 bInterfaceNumber;
__u8 bAlternateSetting;
__u8 bNumEndpoints;
__u8 bInterfaceClass;
__u8 bInterfaceSubClass;
__u8 bInterfaceProtocol;
__u8 iInterface;
} __attribute__ ((packed));
enum usb_device_speed {
USB_SPEED_UNKNOWN = 0, /* enumerating */
USB_SPEED_LOW, USB_SPEED_FULL, /* usb 1.1 */
USB_SPEED_HIGH /* usb 2.0 */
};
/*-------------------------------------------------------------------------*/
static char *speed (enum usb_device_speed s)
{
switch (s) {
case USB_SPEED_UNKNOWN: return "unknown";
case USB_SPEED_LOW: return "low";
case USB_SPEED_FULL: return "full";
case USB_SPEED_HIGH: return "high";
default: return "??";
}
}
struct testdev {
struct testdev *next;
char *name;
pthread_t thread;
enum usb_device_speed speed;
unsigned ifnum : 8;
unsigned forever : 1;
int test;
struct usbtest_param param;
};
static struct testdev *testdevs;
static int testdev_ffs_ifnum(FILE *fd)
{
union {
char buf[255];
struct usb_interface_descriptor intf;
} u;
for (;;) {
if (fread(u.buf, 1, 1, fd) != 1)
return -1;
if (fread(u.buf + 1, (unsigned char)u.buf[0] - 1, 1, fd) != 1)
return -1;
if (u.intf.bLength == sizeof u.intf
&& u.intf.bDescriptorType == USB_DT_INTERFACE
&& u.intf.bNumEndpoints == 2
&& u.intf.bInterfaceClass == USB_CLASS_VENDOR_SPEC
&& u.intf.bInterfaceSubClass == 0
&& u.intf.bInterfaceProtocol == 0)
return (unsigned char)u.intf.bInterfaceNumber;
}
}
static int testdev_ifnum(FILE *fd)
{
struct usb_device_descriptor dev;
if (fread(&dev, sizeof dev, 1, fd) != 1)
return -1;
if (dev.bLength != sizeof dev || dev.bDescriptorType != USB_DT_DEVICE)
return -1;
/* FX2 with (tweaked) bulksrc firmware */
if (dev.idVendor == 0x0547 && dev.idProduct == 0x1002)
return 0;
/*----------------------------------------------------*/
/* devices that start up using the EZ-USB default device and
* which we can use after loading simple firmware. hotplug
* can fxload it, and then run this test driver.
*
* we return false positives in two cases:
* - the device has a "real" driver (maybe usb-serial) that
* renumerates. the device should vanish quickly.
* - the device doesn't have the test firmware installed.
*/
/* generic EZ-USB FX controller */
if (dev.idVendor == 0x0547 && dev.idProduct == 0x2235)
return 0;
/* generic EZ-USB FX2 controller */
if (dev.idVendor == 0x04b4 && dev.idProduct == 0x8613)
return 0;
/* CY3671 development board with EZ-USB FX */
if (dev.idVendor == 0x0547 && dev.idProduct == 0x0080)
return 0;
/* Keyspan 19Qi uses an21xx (original EZ-USB) */
if (dev.idVendor == 0x06cd && dev.idProduct == 0x010b)
return 0;
/*----------------------------------------------------*/
/* "gadget zero", Linux-USB test software */
if (dev.idVendor == 0x0525 && dev.idProduct == 0xa4a0)
return 0;
/* user mode subset of that */
if (dev.idVendor == 0x0525 && dev.idProduct == 0xa4a4)
return testdev_ffs_ifnum(fd);
/* return 0; */
/* iso version of usermode code */
if (dev.idVendor == 0x0525 && dev.idProduct == 0xa4a3)
return 0;
/* some GPL'd test firmware uses these IDs */
if (dev.idVendor == 0xfff0 && dev.idProduct == 0xfff0)
return 0;
/*----------------------------------------------------*/
/* iBOT2 high speed webcam */
if (dev.idVendor == 0x0b62 && dev.idProduct == 0x0059)
return 0;
/*----------------------------------------------------*/
/* the FunctionFS gadget can have the source/sink interface
* anywhere. We look for an interface descriptor that match
* what we expect. We ignore configuratiens thou. */
if (dev.idVendor == 0x0525 && dev.idProduct == 0xa4ac
&& (dev.bDeviceClass == USB_CLASS_PER_INTERFACE
|| dev.bDeviceClass == USB_CLASS_VENDOR_SPEC))
return testdev_ffs_ifnum(fd);
return -1;
}
static int find_testdev(const char *name, const struct stat *sb, int flag)
{
FILE *fd;
int ifnum;
struct testdev *entry;
(void)sb; /* unused */
if (flag != FTW_F)
return 0;
/* ignore /proc/bus/usb/{devices,drivers} */
if (strrchr(name, '/')[1] == 'd')
return 0;
fd = fopen(name, "rb");
if (!fd) {
perror(name);
return 0;
}
ifnum = testdev_ifnum(fd);
fclose(fd);
if (ifnum < 0)
return 0;
entry = calloc(1, sizeof *entry);
if (!entry)
goto nomem;
entry->name = strdup(name);
if (!entry->name) {
free(entry);
nomem:
perror("malloc");
return 0;
}
entry->ifnum = ifnum;
/* FIXME ask usbfs what speed; update USBDEVFS_CONNECTINFO so
* it tells about high speed etc */
fprintf(stderr, "%s speed\t%s\t%u\n",
speed(entry->speed), entry->name, entry->ifnum);
entry->next = testdevs;
testdevs = entry;
return 0;
}
static int
usbdev_ioctl (int fd, int ifno, unsigned request, void *param)
{
struct usbdevfs_ioctl wrapper;
wrapper.ifno = ifno;
wrapper.ioctl_code = request;
wrapper.data = param;
return ioctl (fd, USBDEVFS_IOCTL, &wrapper);
}
static void *handle_testdev (void *arg)
{
struct testdev *dev = arg;
int fd, i;
int status;
if ((fd = open (dev->name, O_RDWR)) < 0) {
perror ("can't open dev file r/w");
return 0;
}
restart:
for (i = 0; i < TEST_CASES; i++) {
if (dev->test != -1 && dev->test != i)
continue;
dev->param.test_num = i;
status = usbdev_ioctl (fd, dev->ifnum,
USBTEST_REQUEST, &dev->param);
if (status < 0 && errno == EOPNOTSUPP)
continue;
/* FIXME need a "syslog it" option for background testing */
/* NOTE: each thread emits complete lines; no fragments! */
if (status < 0) {
char buf [80];
int err = errno;
if (strerror_r (errno, buf, sizeof buf)) {
snprintf (buf, sizeof buf, "error %d", err);
errno = err;
}
printf ("%s test %d --> %d (%s)\n",
dev->name, i, errno, buf);
} else
printf ("%s test %d, %4d.%.06d secs\n", dev->name, i,
(int) dev->param.duration.tv_sec,
(int) dev->param.duration.tv_usec);
fflush (stdout);
}
if (dev->forever)
goto restart;
close (fd);
return arg;
}
static const char *usbfs_dir_find(void)
{
static char usbfs_path_0[] = "/dev/usb/devices";
static char usbfs_path_1[] = "/proc/bus/usb/devices";
static char *const usbfs_paths[] = {
usbfs_path_0, usbfs_path_1
};
static char *const *
end = usbfs_paths + sizeof usbfs_paths / sizeof *usbfs_paths;
char *const *it = usbfs_paths;
do {
int fd = open(*it, O_RDONLY);
close(fd);
if (fd >= 0) {
strrchr(*it, '/')[0] = '\0';
return *it;
}
} while (++it != end);
return NULL;
}
static int parse_num(unsigned *num, const char *str)
{
unsigned long val;
char *end;
errno = 0;
val = strtoul(str, &end, 0);
if (errno || *end || val > UINT_MAX)
return -1;
*num = val;
return 0;
}
int main (int argc, char **argv)
{
int c;
struct testdev *entry;
char *device;
const char *usbfs_dir = NULL;
int all = 0, forever = 0, not = 0;
int test = -1 /* all */;
struct usbtest_param param;
/* pick defaults that works with all speeds, without short packets.
*
* Best per-frame data rates:
* high speed, bulk 512 * 13 * 8 = 53248
* interrupt 1024 * 3 * 8 = 24576
* full speed, bulk/intr 64 * 19 = 1216
* interrupt 64 * 1 = 64
* low speed, interrupt 8 * 1 = 8
*/
param.iterations = 1000;
param.length = 512;
param.vary = 512;
param.sglen = 32;
/* for easy use when hotplugging */
device = getenv ("DEVICE");
while ((c = getopt (argc, argv, "D:aA:c:g:hns:t:v:")) != EOF)
switch (c) {
case 'D': /* device, if only one */
device = optarg;
continue;
case 'A': /* use all devices with specified usbfs dir */
usbfs_dir = optarg;
/* FALL THROUGH */
case 'a': /* use all devices */
device = NULL;
all = 1;
continue;
case 'c': /* count iterations */
if (parse_num(¶m.iterations, optarg))
goto usage;
continue;
case 'g': /* scatter/gather entries */
if (parse_num(¶m.sglen, optarg))
goto usage;
continue;
case 'l': /* loop forever */
forever = 1;
continue;
case 'n': /* no test running! */
not = 1;
continue;
case 's': /* size of packet */
if (parse_num(¶m.length, optarg))
goto usage;
continue;
case 't': /* run just one test */
test = atoi (optarg);
if (test < 0)
goto usage;
continue;
case 'v': /* vary packet size by ... */
if (parse_num(¶m.vary, optarg))
goto usage;
continue;
case '?':
case 'h':
default:
usage:
fprintf (stderr, "usage: %s [-n] [-D dev | -a | -A usbfs-dir]\n"
"\t[-c iterations] [-t testnum]\n"
"\t[-s packetsize] [-g sglen] [-v vary]\n",
argv [0]);
return 1;
}
if (optind != argc)
goto usage;
if (!all && !device) {
fprintf (stderr, "must specify '-a' or '-D dev', "
"or DEVICE=/proc/bus/usb/BBB/DDD in env\n");
goto usage;
}
/* Find usbfs mount point */
if (!usbfs_dir) {
usbfs_dir = usbfs_dir_find();
if (!usbfs_dir) {
fputs ("usbfs files are missing\n", stderr);
return -1;
}
}
/* collect and list the test devices */
if (ftw (usbfs_dir, find_testdev, 3) != 0) {
fputs ("ftw failed; is usbfs missing?\n", stderr);
return -1;
}
/* quit, run single test, or create test threads */
if (!testdevs && !device) {
fputs ("no test devices recognized\n", stderr);
return -1;
}
if (not)
return 0;
if (testdevs && testdevs->next == 0 && !device)
device = testdevs->name;
for (entry = testdevs; entry; entry = entry->next) {
int status;
entry->param = param;
entry->forever = forever;
entry->test = test;
if (device) {
if (strcmp (entry->name, device))
continue;
return handle_testdev (entry) != entry;
}
status = pthread_create (&entry->thread, 0, handle_testdev, entry);
if (status) {
perror ("pthread_create");
continue;
}
}
if (device) {
struct testdev dev;
/* kernel can recognize test devices we don't */
fprintf (stderr, "%s: %s may see only control tests\n",
argv [0], device);
memset (&dev, 0, sizeof dev);
dev.name = device;
dev.param = param;
dev.forever = forever;
dev.test = test;
return handle_testdev (&dev) != &dev;
}
/* wait for tests to complete */
for (entry = testdevs; entry; entry = entry->next) {
void *retval;
if (pthread_join (entry->thread, &retval))
perror ("pthread_join");
/* testing errors discarded! */
}
return 0;
}
| gpl-2.0 |
vuanhduy/odroidxu-3.4.y | drivers/staging/rtl8192e/rtllib_softmac.c | 4811 | 100688 | /* IEEE 802.11 SoftMAC layer
* Copyright (c) 2005 Andrea Merello <andreamrl@tiscali.it>
*
* Mostly extracted from the rtl8180-sa2400 driver for the
* in-kernel generic ieee802.11 stack.
*
* Few lines might be stolen from other part of the rtllib
* stack. Copyright who own it's copyright
*
* WPA code stolen from the ipw2200 driver.
* Copyright who own it's copyright.
*
* released under the GPL
*/
#include "rtllib.h"
#include <linux/random.h>
#include <linux/delay.h>
#include <linux/uaccess.h>
#include "dot11d.h"
short rtllib_is_54g(struct rtllib_network *net)
{
return (net->rates_ex_len > 0) || (net->rates_len > 4);
}
short rtllib_is_shortslot(const struct rtllib_network *net)
{
return net->capability & WLAN_CAPABILITY_SHORT_SLOT_TIME;
}
/* returns the total length needed for pleacing the RATE MFIE
* tag and the EXTENDED RATE MFIE tag if needed.
* It encludes two bytes per tag for the tag itself and its len
*/
static unsigned int rtllib_MFIE_rate_len(struct rtllib_device *ieee)
{
unsigned int rate_len = 0;
if (ieee->modulation & RTLLIB_CCK_MODULATION)
rate_len = RTLLIB_CCK_RATE_LEN + 2;
if (ieee->modulation & RTLLIB_OFDM_MODULATION)
rate_len += RTLLIB_OFDM_RATE_LEN + 2;
return rate_len;
}
/* pleace the MFIE rate, tag to the memory (double) poined.
* Then it updates the pointer so that
* it points after the new MFIE tag added.
*/
static void rtllib_MFIE_Brate(struct rtllib_device *ieee, u8 **tag_p)
{
u8 *tag = *tag_p;
if (ieee->modulation & RTLLIB_CCK_MODULATION) {
*tag++ = MFIE_TYPE_RATES;
*tag++ = 4;
*tag++ = RTLLIB_BASIC_RATE_MASK | RTLLIB_CCK_RATE_1MB;
*tag++ = RTLLIB_BASIC_RATE_MASK | RTLLIB_CCK_RATE_2MB;
*tag++ = RTLLIB_BASIC_RATE_MASK | RTLLIB_CCK_RATE_5MB;
*tag++ = RTLLIB_BASIC_RATE_MASK | RTLLIB_CCK_RATE_11MB;
}
/* We may add an option for custom rates that specific HW
* might support */
*tag_p = tag;
}
static void rtllib_MFIE_Grate(struct rtllib_device *ieee, u8 **tag_p)
{
u8 *tag = *tag_p;
if (ieee->modulation & RTLLIB_OFDM_MODULATION) {
*tag++ = MFIE_TYPE_RATES_EX;
*tag++ = 8;
*tag++ = RTLLIB_BASIC_RATE_MASK | RTLLIB_OFDM_RATE_6MB;
*tag++ = RTLLIB_BASIC_RATE_MASK | RTLLIB_OFDM_RATE_9MB;
*tag++ = RTLLIB_BASIC_RATE_MASK | RTLLIB_OFDM_RATE_12MB;
*tag++ = RTLLIB_BASIC_RATE_MASK | RTLLIB_OFDM_RATE_18MB;
*tag++ = RTLLIB_BASIC_RATE_MASK | RTLLIB_OFDM_RATE_24MB;
*tag++ = RTLLIB_BASIC_RATE_MASK | RTLLIB_OFDM_RATE_36MB;
*tag++ = RTLLIB_BASIC_RATE_MASK | RTLLIB_OFDM_RATE_48MB;
*tag++ = RTLLIB_BASIC_RATE_MASK | RTLLIB_OFDM_RATE_54MB;
}
/* We may add an option for custom rates that specific HW might
* support */
*tag_p = tag;
}
static void rtllib_WMM_Info(struct rtllib_device *ieee, u8 **tag_p)
{
u8 *tag = *tag_p;
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = 7;
*tag++ = 0x00;
*tag++ = 0x50;
*tag++ = 0xf2;
*tag++ = 0x02;
*tag++ = 0x00;
*tag++ = 0x01;
*tag++ = MAX_SP_Len;
*tag_p = tag;
}
void rtllib_TURBO_Info(struct rtllib_device *ieee, u8 **tag_p)
{
u8 *tag = *tag_p;
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = 7;
*tag++ = 0x00;
*tag++ = 0xe0;
*tag++ = 0x4c;
*tag++ = 0x01;
*tag++ = 0x02;
*tag++ = 0x11;
*tag++ = 0x00;
*tag_p = tag;
printk(KERN_ALERT "This is enable turbo mode IE process\n");
}
static void enqueue_mgmt(struct rtllib_device *ieee, struct sk_buff *skb)
{
int nh;
nh = (ieee->mgmt_queue_head + 1) % MGMT_QUEUE_NUM;
/*
* if the queue is full but we have newer frames then
* just overwrites the oldest.
*
* if (nh == ieee->mgmt_queue_tail)
* return -1;
*/
ieee->mgmt_queue_head = nh;
ieee->mgmt_queue_ring[nh] = skb;
}
static struct sk_buff *dequeue_mgmt(struct rtllib_device *ieee)
{
struct sk_buff *ret;
if (ieee->mgmt_queue_tail == ieee->mgmt_queue_head)
return NULL;
ret = ieee->mgmt_queue_ring[ieee->mgmt_queue_tail];
ieee->mgmt_queue_tail =
(ieee->mgmt_queue_tail+1) % MGMT_QUEUE_NUM;
return ret;
}
static void init_mgmt_queue(struct rtllib_device *ieee)
{
ieee->mgmt_queue_tail = ieee->mgmt_queue_head = 0;
}
u8
MgntQuery_TxRateExcludeCCKRates(struct rtllib_device *ieee)
{
u16 i;
u8 QueryRate = 0;
u8 BasicRate;
for (i = 0; i < ieee->current_network.rates_len; i++) {
BasicRate = ieee->current_network.rates[i]&0x7F;
if (!rtllib_is_cck_rate(BasicRate)) {
if (QueryRate == 0) {
QueryRate = BasicRate;
} else {
if (BasicRate < QueryRate)
QueryRate = BasicRate;
}
}
}
if (QueryRate == 0) {
QueryRate = 12;
printk(KERN_INFO "No BasicRate found!!\n");
}
return QueryRate;
}
u8 MgntQuery_MgntFrameTxRate(struct rtllib_device *ieee)
{
struct rt_hi_throughput *pHTInfo = ieee->pHTInfo;
u8 rate;
if (pHTInfo->IOTAction & HT_IOT_ACT_MGNT_USE_CCK_6M)
rate = 0x0c;
else
rate = ieee->basic_rate & 0x7f;
if (rate == 0) {
if (ieee->mode == IEEE_A ||
ieee->mode == IEEE_N_5G ||
(ieee->mode == IEEE_N_24G && !pHTInfo->bCurSuppCCK))
rate = 0x0c;
else
rate = 0x02;
}
return rate;
}
inline void softmac_mgmt_xmit(struct sk_buff *skb, struct rtllib_device *ieee)
{
unsigned long flags;
short single = ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE;
struct rtllib_hdr_3addr *header =
(struct rtllib_hdr_3addr *) skb->data;
struct cb_desc *tcb_desc = (struct cb_desc *)(skb->cb + 8);
spin_lock_irqsave(&ieee->lock, flags);
/* called with 2nd param 0, no mgmt lock required */
rtllib_sta_wakeup(ieee, 0);
if (header->frame_ctl == RTLLIB_STYPE_BEACON)
tcb_desc->queue_index = BEACON_QUEUE;
else
tcb_desc->queue_index = MGNT_QUEUE;
if (ieee->disable_mgnt_queue)
tcb_desc->queue_index = HIGH_QUEUE;
tcb_desc->data_rate = MgntQuery_MgntFrameTxRate(ieee);
tcb_desc->RATRIndex = 7;
tcb_desc->bTxDisableRateFallBack = 1;
tcb_desc->bTxUseDriverAssingedRate = 1;
if (single) {
if (ieee->queue_stop) {
enqueue_mgmt(ieee, skb);
} else {
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0]<<4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
/* avoid watchdog triggers */
ieee->softmac_data_hard_start_xmit(skb, ieee->dev,
ieee->basic_rate);
}
spin_unlock_irqrestore(&ieee->lock, flags);
} else {
spin_unlock_irqrestore(&ieee->lock, flags);
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags);
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
/* check wether the managed packet queued greater than 5 */
if (!ieee->check_nic_enough_desc(ieee->dev, tcb_desc->queue_index) ||
(skb_queue_len(&ieee->skb_waitQ[tcb_desc->queue_index]) != 0) ||
(ieee->queue_stop)) {
/* insert the skb packet to the management queue */
/* as for the completion function, it does not need
* to check it any more.
* */
printk(KERN_INFO "%s():insert to waitqueue, queue_index"
":%d!\n", __func__, tcb_desc->queue_index);
skb_queue_tail(&ieee->skb_waitQ[tcb_desc->queue_index],
skb);
} else {
ieee->softmac_hard_start_xmit(skb, ieee->dev);
}
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags);
}
}
inline void softmac_ps_mgmt_xmit(struct sk_buff *skb,
struct rtllib_device *ieee)
{
short single = ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE;
struct rtllib_hdr_3addr *header =
(struct rtllib_hdr_3addr *) skb->data;
u16 fc, type, stype;
struct cb_desc *tcb_desc = (struct cb_desc *)(skb->cb + 8);
fc = header->frame_ctl;
type = WLAN_FC_GET_TYPE(fc);
stype = WLAN_FC_GET_STYPE(fc);
if (stype != RTLLIB_STYPE_PSPOLL)
tcb_desc->queue_index = MGNT_QUEUE;
else
tcb_desc->queue_index = HIGH_QUEUE;
if (ieee->disable_mgnt_queue)
tcb_desc->queue_index = HIGH_QUEUE;
tcb_desc->data_rate = MgntQuery_MgntFrameTxRate(ieee);
tcb_desc->RATRIndex = 7;
tcb_desc->bTxDisableRateFallBack = 1;
tcb_desc->bTxUseDriverAssingedRate = 1;
if (single) {
if (type != RTLLIB_FTYPE_CTL) {
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
}
/* avoid watchdog triggers */
ieee->softmac_data_hard_start_xmit(skb, ieee->dev,
ieee->basic_rate);
} else {
if (type != RTLLIB_FTYPE_CTL) {
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
}
ieee->softmac_hard_start_xmit(skb, ieee->dev);
}
}
inline struct sk_buff *rtllib_probe_req(struct rtllib_device *ieee)
{
unsigned int len, rate_len;
u8 *tag;
struct sk_buff *skb;
struct rtllib_probe_request *req;
len = ieee->current_network.ssid_len;
rate_len = rtllib_MFIE_rate_len(ieee);
skb = dev_alloc_skb(sizeof(struct rtllib_probe_request) +
2 + len + rate_len + ieee->tx_headroom);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
req = (struct rtllib_probe_request *) skb_put(skb,
sizeof(struct rtllib_probe_request));
req->header.frame_ctl = cpu_to_le16(RTLLIB_STYPE_PROBE_REQ);
req->header.duration_id = 0;
memset(req->header.addr1, 0xff, ETH_ALEN);
memcpy(req->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memset(req->header.addr3, 0xff, ETH_ALEN);
tag = (u8 *) skb_put(skb, len + 2 + rate_len);
*tag++ = MFIE_TYPE_SSID;
*tag++ = len;
memcpy(tag, ieee->current_network.ssid, len);
tag += len;
rtllib_MFIE_Brate(ieee, &tag);
rtllib_MFIE_Grate(ieee, &tag);
return skb;
}
struct sk_buff *rtllib_get_beacon_(struct rtllib_device *ieee);
static void rtllib_send_beacon(struct rtllib_device *ieee)
{
struct sk_buff *skb;
if (!ieee->ieee_up)
return;
skb = rtllib_get_beacon_(ieee);
if (skb) {
softmac_mgmt_xmit(skb, ieee);
ieee->softmac_stats.tx_beacons++;
}
if (ieee->beacon_txing && ieee->ieee_up)
mod_timer(&ieee->beacon_timer, jiffies +
(MSECS(ieee->current_network.beacon_interval - 5)));
}
static void rtllib_send_beacon_cb(unsigned long _ieee)
{
struct rtllib_device *ieee =
(struct rtllib_device *) _ieee;
unsigned long flags;
spin_lock_irqsave(&ieee->beacon_lock, flags);
rtllib_send_beacon(ieee);
spin_unlock_irqrestore(&ieee->beacon_lock, flags);
}
/*
* Description:
* Enable network monitor mode, all rx packets will be received.
*/
void rtllib_EnableNetMonitorMode(struct net_device *dev,
bool bInitState)
{
struct rtllib_device *ieee = netdev_priv_rsl(dev);
printk(KERN_INFO "========>Enter Monitor Mode\n");
ieee->AllowAllDestAddrHandler(dev, true, !bInitState);
}
/*
* Description:
* Disable network network monitor mode, only packets destinated to
* us will be received.
*/
void rtllib_DisableNetMonitorMode(struct net_device *dev,
bool bInitState)
{
struct rtllib_device *ieee = netdev_priv_rsl(dev);
printk(KERN_INFO "========>Exit Monitor Mode\n");
ieee->AllowAllDestAddrHandler(dev, false, !bInitState);
}
/*
* Description:
* This enables the specialized promiscuous mode required by Intel.
* In this mode, Intel intends to hear traffics from/to other STAs in the
* same BSS. Therefore we don't have to disable checking BSSID and we only need
* to allow all dest. BUT: if we enable checking BSSID then we can't recv
* packets from other STA.
*/
void rtllib_EnableIntelPromiscuousMode(struct net_device *dev,
bool bInitState)
{
bool bFilterOutNonAssociatedBSSID = false;
struct rtllib_device *ieee = netdev_priv_rsl(dev);
printk(KERN_INFO "========>Enter Intel Promiscuous Mode\n");
ieee->AllowAllDestAddrHandler(dev, true, !bInitState);
ieee->SetHwRegHandler(dev, HW_VAR_CECHK_BSSID,
(u8 *)&bFilterOutNonAssociatedBSSID);
ieee->bNetPromiscuousMode = true;
}
EXPORT_SYMBOL(rtllib_EnableIntelPromiscuousMode);
/*
* Description:
* This disables the specialized promiscuous mode required by Intel.
* See MgntEnableIntelPromiscuousMode for detail.
*/
void rtllib_DisableIntelPromiscuousMode(struct net_device *dev,
bool bInitState)
{
bool bFilterOutNonAssociatedBSSID = true;
struct rtllib_device *ieee = netdev_priv_rsl(dev);
printk(KERN_INFO "========>Exit Intel Promiscuous Mode\n");
ieee->AllowAllDestAddrHandler(dev, false, !bInitState);
ieee->SetHwRegHandler(dev, HW_VAR_CECHK_BSSID,
(u8 *)&bFilterOutNonAssociatedBSSID);
ieee->bNetPromiscuousMode = false;
}
EXPORT_SYMBOL(rtllib_DisableIntelPromiscuousMode);
static void rtllib_send_probe(struct rtllib_device *ieee, u8 is_mesh)
{
struct sk_buff *skb;
skb = rtllib_probe_req(ieee);
if (skb) {
softmac_mgmt_xmit(skb, ieee);
ieee->softmac_stats.tx_probe_rq++;
}
}
void rtllib_send_probe_requests(struct rtllib_device *ieee, u8 is_mesh)
{
if (ieee->active_scan && (ieee->softmac_features &
IEEE_SOFTMAC_PROBERQ)) {
rtllib_send_probe(ieee, 0);
rtllib_send_probe(ieee, 0);
}
}
static void rtllib_softmac_hint11d_wq(void *data)
{
}
void rtllib_update_active_chan_map(struct rtllib_device *ieee)
{
memcpy(ieee->active_channel_map, GET_DOT11D_INFO(ieee)->channel_map,
MAX_CHANNEL_NUMBER+1);
}
/* this performs syncro scan blocking the caller until all channels
* in the allowed channel map has been checked.
*/
void rtllib_softmac_scan_syncro(struct rtllib_device *ieee, u8 is_mesh)
{
union iwreq_data wrqu;
short ch = 0;
rtllib_update_active_chan_map(ieee);
ieee->be_scan_inprogress = true;
down(&ieee->scan_sem);
while (1) {
do {
ch++;
if (ch > MAX_CHANNEL_NUMBER)
goto out; /* scan completed */
} while (!ieee->active_channel_map[ch]);
/* this fuction can be called in two situations
* 1- We have switched to ad-hoc mode and we are
* performing a complete syncro scan before conclude
* there are no interesting cell and to create a
* new one. In this case the link state is
* RTLLIB_NOLINK until we found an interesting cell.
* If so the ieee8021_new_net, called by the RX path
* will set the state to RTLLIB_LINKED, so we stop
* scanning
* 2- We are linked and the root uses run iwlist scan.
* So we switch to RTLLIB_LINKED_SCANNING to remember
* that we are still logically linked (not interested in
* new network events, despite for updating the net list,
* but we are temporarly 'unlinked' as the driver shall
* not filter RX frames and the channel is changing.
* So the only situation in witch are interested is to check
* if the state become LINKED because of the #1 situation
*/
if (ieee->state == RTLLIB_LINKED)
goto out;
if (ieee->sync_scan_hurryup) {
printk(KERN_INFO "============>sync_scan_hurryup out\n");
goto out;
}
ieee->set_chan(ieee->dev, ch);
if (ieee->active_channel_map[ch] == 1)
rtllib_send_probe_requests(ieee, 0);
/* this prevent excessive time wait when we
* need to wait for a syncro scan to end..
*/
msleep_interruptible_rsl(RTLLIB_SOFTMAC_SCAN_TIME);
}
out:
ieee->actscanning = false;
ieee->sync_scan_hurryup = 0;
if (ieee->state >= RTLLIB_LINKED) {
if (IS_DOT11D_ENABLE(ieee))
DOT11D_ScanComplete(ieee);
}
up(&ieee->scan_sem);
ieee->be_scan_inprogress = false;
memset(&wrqu, 0, sizeof(wrqu));
wireless_send_event(ieee->dev, SIOCGIWSCAN, &wrqu, NULL);
}
static void rtllib_softmac_scan_wq(void *data)
{
struct rtllib_device *ieee = container_of_dwork_rsl(data,
struct rtllib_device, softmac_scan_wq);
u8 last_channel = ieee->current_network.channel;
rtllib_update_active_chan_map(ieee);
if (!ieee->ieee_up)
return;
if (rtllib_act_scanning(ieee, true) == true)
return;
down(&ieee->scan_sem);
if (ieee->eRFPowerState == eRfOff) {
printk(KERN_INFO "======>%s():rf state is eRfOff, return\n",
__func__);
goto out1;
}
do {
ieee->current_network.channel =
(ieee->current_network.channel + 1) %
MAX_CHANNEL_NUMBER;
if (ieee->scan_watch_dog++ > MAX_CHANNEL_NUMBER) {
if (!ieee->active_channel_map[ieee->current_network.channel])
ieee->current_network.channel = 6;
goto out; /* no good chans */
}
} while (!ieee->active_channel_map[ieee->current_network.channel]);
if (ieee->scanning_continue == 0)
goto out;
ieee->set_chan(ieee->dev, ieee->current_network.channel);
if (ieee->active_channel_map[ieee->current_network.channel] == 1)
rtllib_send_probe_requests(ieee, 0);
queue_delayed_work_rsl(ieee->wq, &ieee->softmac_scan_wq,
MSECS(RTLLIB_SOFTMAC_SCAN_TIME));
up(&ieee->scan_sem);
return;
out:
if (IS_DOT11D_ENABLE(ieee))
DOT11D_ScanComplete(ieee);
ieee->current_network.channel = last_channel;
out1:
ieee->actscanning = false;
ieee->scan_watch_dog = 0;
ieee->scanning_continue = 0;
up(&ieee->scan_sem);
}
static void rtllib_beacons_start(struct rtllib_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->beacon_lock, flags);
ieee->beacon_txing = 1;
rtllib_send_beacon(ieee);
spin_unlock_irqrestore(&ieee->beacon_lock, flags);
}
static void rtllib_beacons_stop(struct rtllib_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->beacon_lock, flags);
ieee->beacon_txing = 0;
del_timer_sync(&ieee->beacon_timer);
spin_unlock_irqrestore(&ieee->beacon_lock, flags);
}
void rtllib_stop_send_beacons(struct rtllib_device *ieee)
{
if (ieee->stop_send_beacons)
ieee->stop_send_beacons(ieee->dev);
if (ieee->softmac_features & IEEE_SOFTMAC_BEACONS)
rtllib_beacons_stop(ieee);
}
EXPORT_SYMBOL(rtllib_stop_send_beacons);
void rtllib_start_send_beacons(struct rtllib_device *ieee)
{
if (ieee->start_send_beacons)
ieee->start_send_beacons(ieee->dev);
if (ieee->softmac_features & IEEE_SOFTMAC_BEACONS)
rtllib_beacons_start(ieee);
}
EXPORT_SYMBOL(rtllib_start_send_beacons);
static void rtllib_softmac_stop_scan(struct rtllib_device *ieee)
{
down(&ieee->scan_sem);
ieee->scan_watch_dog = 0;
if (ieee->scanning_continue == 1) {
ieee->scanning_continue = 0;
ieee->actscanning = 0;
cancel_delayed_work(&ieee->softmac_scan_wq);
}
up(&ieee->scan_sem);
}
void rtllib_stop_scan(struct rtllib_device *ieee)
{
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN) {
rtllib_softmac_stop_scan(ieee);
} else {
if (ieee->rtllib_stop_hw_scan)
ieee->rtllib_stop_hw_scan(ieee->dev);
}
}
EXPORT_SYMBOL(rtllib_stop_scan);
void rtllib_stop_scan_syncro(struct rtllib_device *ieee)
{
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN) {
ieee->sync_scan_hurryup = 1;
} else {
if (ieee->rtllib_stop_hw_scan)
ieee->rtllib_stop_hw_scan(ieee->dev);
}
}
EXPORT_SYMBOL(rtllib_stop_scan_syncro);
bool rtllib_act_scanning(struct rtllib_device *ieee, bool sync_scan)
{
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN) {
if (sync_scan)
return ieee->be_scan_inprogress;
else
return ieee->actscanning || ieee->be_scan_inprogress;
} else {
return test_bit(STATUS_SCANNING, &ieee->status);
}
}
EXPORT_SYMBOL(rtllib_act_scanning);
/* called with ieee->lock held */
static void rtllib_start_scan(struct rtllib_device *ieee)
{
RT_TRACE(COMP_DBG, "===>%s()\n", __func__);
if (ieee->rtllib_ips_leave_wq != NULL)
ieee->rtllib_ips_leave_wq(ieee->dev);
if (IS_DOT11D_ENABLE(ieee)) {
if (IS_COUNTRY_IE_VALID(ieee))
RESET_CIE_WATCHDOG(ieee);
}
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN) {
if (ieee->scanning_continue == 0) {
ieee->actscanning = true;
ieee->scanning_continue = 1;
queue_delayed_work_rsl(ieee->wq,
&ieee->softmac_scan_wq, 0);
}
} else {
if (ieee->rtllib_start_hw_scan)
ieee->rtllib_start_hw_scan(ieee->dev);
}
}
/* called with wx_sem held */
void rtllib_start_scan_syncro(struct rtllib_device *ieee, u8 is_mesh)
{
if (IS_DOT11D_ENABLE(ieee)) {
if (IS_COUNTRY_IE_VALID(ieee))
RESET_CIE_WATCHDOG(ieee);
}
ieee->sync_scan_hurryup = 0;
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN) {
rtllib_softmac_scan_syncro(ieee, is_mesh);
} else {
if (ieee->rtllib_start_hw_scan)
ieee->rtllib_start_hw_scan(ieee->dev);
}
}
EXPORT_SYMBOL(rtllib_start_scan_syncro);
inline struct sk_buff *rtllib_authentication_req(struct rtllib_network *beacon,
struct rtllib_device *ieee, int challengelen, u8 *daddr)
{
struct sk_buff *skb;
struct rtllib_authentication *auth;
int len = 0;
len = sizeof(struct rtllib_authentication) + challengelen +
ieee->tx_headroom + 4;
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
auth = (struct rtllib_authentication *)
skb_put(skb, sizeof(struct rtllib_authentication));
auth->header.frame_ctl = RTLLIB_STYPE_AUTH;
if (challengelen)
auth->header.frame_ctl |= RTLLIB_FCTL_WEP;
auth->header.duration_id = 0x013a;
memcpy(auth->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(auth->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(auth->header.addr3, beacon->bssid, ETH_ALEN);
if (ieee->auth_mode == 0)
auth->algorithm = WLAN_AUTH_OPEN;
else if (ieee->auth_mode == 1)
auth->algorithm = WLAN_AUTH_SHARED_KEY;
else if (ieee->auth_mode == 2)
auth->algorithm = WLAN_AUTH_OPEN;
auth->transaction = cpu_to_le16(ieee->associate_seq);
ieee->associate_seq++;
auth->status = cpu_to_le16(WLAN_STATUS_SUCCESS);
return skb;
}
static struct sk_buff *rtllib_probe_resp(struct rtllib_device *ieee, u8 *dest)
{
u8 *tag;
int beacon_size;
struct rtllib_probe_response *beacon_buf;
struct sk_buff *skb = NULL;
int encrypt;
int atim_len, erp_len;
struct lib80211_crypt_data *crypt;
char *ssid = ieee->current_network.ssid;
int ssid_len = ieee->current_network.ssid_len;
int rate_len = ieee->current_network.rates_len+2;
int rate_ex_len = ieee->current_network.rates_ex_len;
int wpa_ie_len = ieee->wpa_ie_len;
u8 erpinfo_content = 0;
u8 *tmp_ht_cap_buf = NULL;
u8 tmp_ht_cap_len = 0;
u8 *tmp_ht_info_buf = NULL;
u8 tmp_ht_info_len = 0;
struct rt_hi_throughput *pHTInfo = ieee->pHTInfo;
u8 *tmp_generic_ie_buf = NULL;
u8 tmp_generic_ie_len = 0;
if (rate_ex_len > 0)
rate_ex_len += 2;
if (ieee->current_network.capability & WLAN_CAPABILITY_IBSS)
atim_len = 4;
else
atim_len = 0;
if ((ieee->current_network.mode == IEEE_G) ||
(ieee->current_network.mode == IEEE_N_24G &&
ieee->pHTInfo->bCurSuppCCK)) {
erp_len = 3;
erpinfo_content = 0;
if (ieee->current_network.buseprotection)
erpinfo_content |= ERP_UseProtection;
} else
erp_len = 0;
crypt = ieee->crypt_info.crypt[ieee->crypt_info.tx_keyidx];
encrypt = ieee->host_encrypt && crypt && crypt->ops &&
((0 == strcmp(crypt->ops->name, "R-WEP") || wpa_ie_len));
if (ieee->pHTInfo->bCurrentHTSupport) {
tmp_ht_cap_buf = (u8 *) &(ieee->pHTInfo->SelfHTCap);
tmp_ht_cap_len = sizeof(ieee->pHTInfo->SelfHTCap);
tmp_ht_info_buf = (u8 *) &(ieee->pHTInfo->SelfHTInfo);
tmp_ht_info_len = sizeof(ieee->pHTInfo->SelfHTInfo);
HTConstructCapabilityElement(ieee, tmp_ht_cap_buf,
&tmp_ht_cap_len, encrypt, false);
HTConstructInfoElement(ieee, tmp_ht_info_buf, &tmp_ht_info_len,
encrypt);
if (pHTInfo->bRegRT2RTAggregation) {
tmp_generic_ie_buf = ieee->pHTInfo->szRT2RTAggBuffer;
tmp_generic_ie_len =
sizeof(ieee->pHTInfo->szRT2RTAggBuffer);
HTConstructRT2RTAggElement(ieee, tmp_generic_ie_buf,
&tmp_generic_ie_len);
}
}
beacon_size = sizeof(struct rtllib_probe_response)+2+
ssid_len + 3 + rate_len + rate_ex_len + atim_len + erp_len
+ wpa_ie_len + ieee->tx_headroom;
skb = dev_alloc_skb(beacon_size);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
beacon_buf = (struct rtllib_probe_response *) skb_put(skb,
(beacon_size - ieee->tx_headroom));
memcpy(beacon_buf->header.addr1, dest, ETH_ALEN);
memcpy(beacon_buf->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(beacon_buf->header.addr3, ieee->current_network.bssid, ETH_ALEN);
beacon_buf->header.duration_id = 0;
beacon_buf->beacon_interval =
cpu_to_le16(ieee->current_network.beacon_interval);
beacon_buf->capability =
cpu_to_le16(ieee->current_network.capability &
WLAN_CAPABILITY_IBSS);
beacon_buf->capability |=
cpu_to_le16(ieee->current_network.capability &
WLAN_CAPABILITY_SHORT_PREAMBLE);
if (ieee->short_slot && (ieee->current_network.capability &
WLAN_CAPABILITY_SHORT_SLOT_TIME))
cpu_to_le16((beacon_buf->capability |=
WLAN_CAPABILITY_SHORT_SLOT_TIME));
crypt = ieee->crypt_info.crypt[ieee->crypt_info.tx_keyidx];
if (encrypt)
beacon_buf->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
beacon_buf->header.frame_ctl = cpu_to_le16(RTLLIB_STYPE_PROBE_RESP);
beacon_buf->info_element[0].id = MFIE_TYPE_SSID;
beacon_buf->info_element[0].len = ssid_len;
tag = (u8 *) beacon_buf->info_element[0].data;
memcpy(tag, ssid, ssid_len);
tag += ssid_len;
*(tag++) = MFIE_TYPE_RATES;
*(tag++) = rate_len-2;
memcpy(tag, ieee->current_network.rates, rate_len-2);
tag += rate_len-2;
*(tag++) = MFIE_TYPE_DS_SET;
*(tag++) = 1;
*(tag++) = ieee->current_network.channel;
if (atim_len) {
u16 val16;
*(tag++) = MFIE_TYPE_IBSS_SET;
*(tag++) = 2;
val16 = cpu_to_le16(ieee->current_network.atim_window);
memcpy((u8 *)tag, (u8 *)&val16, 2);
tag += 2;
}
if (erp_len) {
*(tag++) = MFIE_TYPE_ERP;
*(tag++) = 1;
*(tag++) = erpinfo_content;
}
if (rate_ex_len) {
*(tag++) = MFIE_TYPE_RATES_EX;
*(tag++) = rate_ex_len-2;
memcpy(tag, ieee->current_network.rates_ex, rate_ex_len-2);
tag += rate_ex_len-2;
}
if (wpa_ie_len) {
if (ieee->iw_mode == IW_MODE_ADHOC)
memcpy(&ieee->wpa_ie[14], &ieee->wpa_ie[8], 4);
memcpy(tag, ieee->wpa_ie, ieee->wpa_ie_len);
tag += ieee->wpa_ie_len;
}
return skb;
}
static struct sk_buff *rtllib_assoc_resp(struct rtllib_device *ieee, u8 *dest)
{
struct sk_buff *skb;
u8 *tag;
struct lib80211_crypt_data *crypt;
struct rtllib_assoc_response_frame *assoc;
short encrypt;
unsigned int rate_len = rtllib_MFIE_rate_len(ieee);
int len = sizeof(struct rtllib_assoc_response_frame) + rate_len +
ieee->tx_headroom;
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
assoc = (struct rtllib_assoc_response_frame *)
skb_put(skb, sizeof(struct rtllib_assoc_response_frame));
assoc->header.frame_ctl = cpu_to_le16(RTLLIB_STYPE_ASSOC_RESP);
memcpy(assoc->header.addr1, dest, ETH_ALEN);
memcpy(assoc->header.addr3, ieee->dev->dev_addr, ETH_ALEN);
memcpy(assoc->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
assoc->capability = cpu_to_le16(ieee->iw_mode == IW_MODE_MASTER ?
WLAN_CAPABILITY_ESS : WLAN_CAPABILITY_IBSS);
if (ieee->short_slot)
assoc->capability |=
cpu_to_le16(WLAN_CAPABILITY_SHORT_SLOT_TIME);
if (ieee->host_encrypt)
crypt = ieee->crypt_info.crypt[ieee->crypt_info.tx_keyidx];
else
crypt = NULL;
encrypt = (crypt && crypt->ops);
if (encrypt)
assoc->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
assoc->status = 0;
assoc->aid = cpu_to_le16(ieee->assoc_id);
if (ieee->assoc_id == 0x2007)
ieee->assoc_id = 0;
else
ieee->assoc_id++;
tag = (u8 *) skb_put(skb, rate_len);
rtllib_MFIE_Brate(ieee, &tag);
rtllib_MFIE_Grate(ieee, &tag);
return skb;
}
static struct sk_buff *rtllib_auth_resp(struct rtllib_device *ieee, int status,
u8 *dest)
{
struct sk_buff *skb = NULL;
struct rtllib_authentication *auth;
int len = ieee->tx_headroom + sizeof(struct rtllib_authentication) + 1;
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
skb->len = sizeof(struct rtllib_authentication);
skb_reserve(skb, ieee->tx_headroom);
auth = (struct rtllib_authentication *)
skb_put(skb, sizeof(struct rtllib_authentication));
auth->status = cpu_to_le16(status);
auth->transaction = cpu_to_le16(2);
auth->algorithm = cpu_to_le16(WLAN_AUTH_OPEN);
memcpy(auth->header.addr3, ieee->dev->dev_addr, ETH_ALEN);
memcpy(auth->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(auth->header.addr1, dest, ETH_ALEN);
auth->header.frame_ctl = cpu_to_le16(RTLLIB_STYPE_AUTH);
return skb;
}
static struct sk_buff *rtllib_null_func(struct rtllib_device *ieee, short pwr)
{
struct sk_buff *skb;
struct rtllib_hdr_3addr *hdr;
skb = dev_alloc_skb(sizeof(struct rtllib_hdr_3addr)+ieee->tx_headroom);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
hdr = (struct rtllib_hdr_3addr *)skb_put(skb,
sizeof(struct rtllib_hdr_3addr));
memcpy(hdr->addr1, ieee->current_network.bssid, ETH_ALEN);
memcpy(hdr->addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(hdr->addr3, ieee->current_network.bssid, ETH_ALEN);
hdr->frame_ctl = cpu_to_le16(RTLLIB_FTYPE_DATA |
RTLLIB_STYPE_NULLFUNC | RTLLIB_FCTL_TODS |
(pwr ? RTLLIB_FCTL_PM : 0));
return skb;
}
static struct sk_buff *rtllib_pspoll_func(struct rtllib_device *ieee)
{
struct sk_buff *skb;
struct rtllib_pspoll_hdr *hdr;
skb = dev_alloc_skb(sizeof(struct rtllib_pspoll_hdr)+ieee->tx_headroom);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
hdr = (struct rtllib_pspoll_hdr *)skb_put(skb,
sizeof(struct rtllib_pspoll_hdr));
memcpy(hdr->bssid, ieee->current_network.bssid, ETH_ALEN);
memcpy(hdr->ta, ieee->dev->dev_addr, ETH_ALEN);
hdr->aid = cpu_to_le16(ieee->assoc_id | 0xc000);
hdr->frame_ctl = cpu_to_le16(RTLLIB_FTYPE_CTL | RTLLIB_STYPE_PSPOLL |
RTLLIB_FCTL_PM);
return skb;
}
static void rtllib_resp_to_assoc_rq(struct rtllib_device *ieee, u8 *dest)
{
struct sk_buff *buf = rtllib_assoc_resp(ieee, dest);
if (buf)
softmac_mgmt_xmit(buf, ieee);
}
static void rtllib_resp_to_auth(struct rtllib_device *ieee, int s, u8 *dest)
{
struct sk_buff *buf = rtllib_auth_resp(ieee, s, dest);
if (buf)
softmac_mgmt_xmit(buf, ieee);
}
static void rtllib_resp_to_probe(struct rtllib_device *ieee, u8 *dest)
{
struct sk_buff *buf = rtllib_probe_resp(ieee, dest);
if (buf)
softmac_mgmt_xmit(buf, ieee);
}
inline int SecIsInPMKIDList(struct rtllib_device *ieee, u8 *bssid)
{
int i = 0;
do {
if ((ieee->PMKIDList[i].bUsed) &&
(memcmp(ieee->PMKIDList[i].Bssid, bssid, ETH_ALEN) == 0))
break;
else
i++;
} while (i < NUM_PMKID_CACHE);
if (i == NUM_PMKID_CACHE)
i = -1;
return i;
}
inline struct sk_buff *rtllib_association_req(struct rtllib_network *beacon,
struct rtllib_device *ieee)
{
struct sk_buff *skb;
struct rtllib_assoc_request_frame *hdr;
u8 *tag, *ies;
int i;
u8 *ht_cap_buf = NULL;
u8 ht_cap_len = 0;
u8 *realtek_ie_buf = NULL;
u8 realtek_ie_len = 0;
int wpa_ie_len = ieee->wpa_ie_len;
int wps_ie_len = ieee->wps_ie_len;
unsigned int ckip_ie_len = 0;
unsigned int ccxrm_ie_len = 0;
unsigned int cxvernum_ie_len = 0;
struct lib80211_crypt_data *crypt;
int encrypt;
int PMKCacheIdx;
unsigned int rate_len = (beacon->rates_len ?
(beacon->rates_len + 2) : 0) +
(beacon->rates_ex_len ? (beacon->rates_ex_len) +
2 : 0);
unsigned int wmm_info_len = beacon->qos_data.supported ? 9 : 0;
unsigned int turbo_info_len = beacon->Turbo_Enable ? 9 : 0;
int len = 0;
crypt = ieee->crypt_info.crypt[ieee->crypt_info.tx_keyidx];
if (crypt != NULL)
encrypt = ieee->host_encrypt && crypt && crypt->ops &&
((0 == strcmp(crypt->ops->name, "R-WEP") ||
wpa_ie_len));
else
encrypt = 0;
if ((ieee->rtllib_ap_sec_type &&
(ieee->rtllib_ap_sec_type(ieee) & SEC_ALG_TKIP)) ||
(ieee->bForcedBgMode == true)) {
ieee->pHTInfo->bEnableHT = 0;
ieee->mode = WIRELESS_MODE_G;
}
if (ieee->pHTInfo->bCurrentHTSupport && ieee->pHTInfo->bEnableHT) {
ht_cap_buf = (u8 *)&(ieee->pHTInfo->SelfHTCap);
ht_cap_len = sizeof(ieee->pHTInfo->SelfHTCap);
HTConstructCapabilityElement(ieee, ht_cap_buf, &ht_cap_len,
encrypt, true);
if (ieee->pHTInfo->bCurrentRT2RTAggregation) {
realtek_ie_buf = ieee->pHTInfo->szRT2RTAggBuffer;
realtek_ie_len =
sizeof(ieee->pHTInfo->szRT2RTAggBuffer);
HTConstructRT2RTAggElement(ieee, realtek_ie_buf,
&realtek_ie_len);
}
}
if (beacon->bCkipSupported)
ckip_ie_len = 30+2;
if (beacon->bCcxRmEnable)
ccxrm_ie_len = 6+2;
if (beacon->BssCcxVerNumber >= 2)
cxvernum_ie_len = 5+2;
PMKCacheIdx = SecIsInPMKIDList(ieee, ieee->current_network.bssid);
if (PMKCacheIdx >= 0) {
wpa_ie_len += 18;
printk(KERN_INFO "[PMK cache]: WPA2 IE length: %x\n",
wpa_ie_len);
}
len = sizeof(struct rtllib_assoc_request_frame) + 2
+ beacon->ssid_len
+ rate_len
+ wpa_ie_len
+ wps_ie_len
+ wmm_info_len
+ turbo_info_len
+ ht_cap_len
+ realtek_ie_len
+ ckip_ie_len
+ ccxrm_ie_len
+ cxvernum_ie_len
+ ieee->tx_headroom;
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
hdr = (struct rtllib_assoc_request_frame *)
skb_put(skb, sizeof(struct rtllib_assoc_request_frame) + 2);
hdr->header.frame_ctl = RTLLIB_STYPE_ASSOC_REQ;
hdr->header.duration_id = 37;
memcpy(hdr->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(hdr->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(hdr->header.addr3, beacon->bssid, ETH_ALEN);
memcpy(ieee->ap_mac_addr, beacon->bssid, ETH_ALEN);
hdr->capability = cpu_to_le16(WLAN_CAPABILITY_ESS);
if (beacon->capability & WLAN_CAPABILITY_PRIVACY)
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
if (beacon->capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_PREAMBLE);
if (ieee->short_slot &&
(beacon->capability&WLAN_CAPABILITY_SHORT_SLOT_TIME))
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_SLOT_TIME);
hdr->listen_interval = beacon->listen_interval;
hdr->info_element[0].id = MFIE_TYPE_SSID;
hdr->info_element[0].len = beacon->ssid_len;
tag = skb_put(skb, beacon->ssid_len);
memcpy(tag, beacon->ssid, beacon->ssid_len);
tag = skb_put(skb, rate_len);
if (beacon->rates_len) {
*tag++ = MFIE_TYPE_RATES;
*tag++ = beacon->rates_len;
for (i = 0; i < beacon->rates_len; i++)
*tag++ = beacon->rates[i];
}
if (beacon->rates_ex_len) {
*tag++ = MFIE_TYPE_RATES_EX;
*tag++ = beacon->rates_ex_len;
for (i = 0; i < beacon->rates_ex_len; i++)
*tag++ = beacon->rates_ex[i];
}
if (beacon->bCkipSupported) {
static u8 AironetIeOui[] = {0x00, 0x01, 0x66};
u8 CcxAironetBuf[30];
struct octet_string osCcxAironetIE;
memset(CcxAironetBuf, 0, 30);
osCcxAironetIE.Octet = CcxAironetBuf;
osCcxAironetIE.Length = sizeof(CcxAironetBuf);
memcpy(osCcxAironetIE.Octet, AironetIeOui,
sizeof(AironetIeOui));
osCcxAironetIE.Octet[IE_CISCO_FLAG_POSITION] |=
(SUPPORT_CKIP_PK|SUPPORT_CKIP_MIC);
tag = skb_put(skb, ckip_ie_len);
*tag++ = MFIE_TYPE_AIRONET;
*tag++ = osCcxAironetIE.Length;
memcpy(tag, osCcxAironetIE.Octet, osCcxAironetIE.Length);
tag += osCcxAironetIE.Length;
}
if (beacon->bCcxRmEnable) {
static u8 CcxRmCapBuf[] = {0x00, 0x40, 0x96, 0x01, 0x01, 0x00};
struct octet_string osCcxRmCap;
osCcxRmCap.Octet = CcxRmCapBuf;
osCcxRmCap.Length = sizeof(CcxRmCapBuf);
tag = skb_put(skb, ccxrm_ie_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = osCcxRmCap.Length;
memcpy(tag, osCcxRmCap.Octet, osCcxRmCap.Length);
tag += osCcxRmCap.Length;
}
if (beacon->BssCcxVerNumber >= 2) {
u8 CcxVerNumBuf[] = {0x00, 0x40, 0x96, 0x03, 0x00};
struct octet_string osCcxVerNum;
CcxVerNumBuf[4] = beacon->BssCcxVerNumber;
osCcxVerNum.Octet = CcxVerNumBuf;
osCcxVerNum.Length = sizeof(CcxVerNumBuf);
tag = skb_put(skb, cxvernum_ie_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = osCcxVerNum.Length;
memcpy(tag, osCcxVerNum.Octet, osCcxVerNum.Length);
tag += osCcxVerNum.Length;
}
if (ieee->pHTInfo->bCurrentHTSupport && ieee->pHTInfo->bEnableHT) {
if (ieee->pHTInfo->ePeerHTSpecVer != HT_SPEC_VER_EWC) {
tag = skb_put(skb, ht_cap_len);
*tag++ = MFIE_TYPE_HT_CAP;
*tag++ = ht_cap_len - 2;
memcpy(tag, ht_cap_buf, ht_cap_len - 2);
tag += ht_cap_len - 2;
}
}
if (wpa_ie_len) {
tag = skb_put(skb, ieee->wpa_ie_len);
memcpy(tag, ieee->wpa_ie, ieee->wpa_ie_len);
if (PMKCacheIdx >= 0) {
tag = skb_put(skb, 18);
*tag = 1;
*(tag + 1) = 0;
memcpy((tag + 2), &ieee->PMKIDList[PMKCacheIdx].PMKID,
16);
}
}
if (wmm_info_len) {
tag = skb_put(skb, wmm_info_len);
rtllib_WMM_Info(ieee, &tag);
}
if (wps_ie_len && ieee->wps_ie) {
tag = skb_put(skb, wps_ie_len);
memcpy(tag, ieee->wps_ie, wps_ie_len);
}
tag = skb_put(skb, turbo_info_len);
if (turbo_info_len)
rtllib_TURBO_Info(ieee, &tag);
if (ieee->pHTInfo->bCurrentHTSupport && ieee->pHTInfo->bEnableHT) {
if (ieee->pHTInfo->ePeerHTSpecVer == HT_SPEC_VER_EWC) {
tag = skb_put(skb, ht_cap_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = ht_cap_len - 2;
memcpy(tag, ht_cap_buf, ht_cap_len - 2);
tag += ht_cap_len - 2;
}
if (ieee->pHTInfo->bCurrentRT2RTAggregation) {
tag = skb_put(skb, realtek_ie_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = realtek_ie_len - 2;
memcpy(tag, realtek_ie_buf, realtek_ie_len - 2);
}
}
kfree(ieee->assocreq_ies);
ieee->assocreq_ies = NULL;
ies = &(hdr->info_element[0].id);
ieee->assocreq_ies_len = (skb->data + skb->len) - ies;
ieee->assocreq_ies = kmalloc(ieee->assocreq_ies_len, GFP_ATOMIC);
if (ieee->assocreq_ies)
memcpy(ieee->assocreq_ies, ies, ieee->assocreq_ies_len);
else {
printk(KERN_INFO "%s()Warning: can't alloc memory for assocreq"
"_ies\n", __func__);
ieee->assocreq_ies_len = 0;
}
return skb;
}
void rtllib_associate_abort(struct rtllib_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->lock, flags);
ieee->associate_seq++;
/* don't scan, and avoid to have the RX path possibily
* try again to associate. Even do not react to AUTH or
* ASSOC response. Just wait for the retry wq to be scheduled.
* Here we will check if there are good nets to associate
* with, so we retry or just get back to NO_LINK and scanning
*/
if (ieee->state == RTLLIB_ASSOCIATING_AUTHENTICATING) {
RTLLIB_DEBUG_MGMT("Authentication failed\n");
ieee->softmac_stats.no_auth_rs++;
} else {
RTLLIB_DEBUG_MGMT("Association failed\n");
ieee->softmac_stats.no_ass_rs++;
}
ieee->state = RTLLIB_ASSOCIATING_RETRY;
queue_delayed_work_rsl(ieee->wq, &ieee->associate_retry_wq,
RTLLIB_SOFTMAC_ASSOC_RETRY_TIME);
spin_unlock_irqrestore(&ieee->lock, flags);
}
static void rtllib_associate_abort_cb(unsigned long dev)
{
rtllib_associate_abort((struct rtllib_device *) dev);
}
static void rtllib_associate_step1(struct rtllib_device *ieee, u8 * daddr)
{
struct rtllib_network *beacon = &ieee->current_network;
struct sk_buff *skb;
RTLLIB_DEBUG_MGMT("Stopping scan\n");
ieee->softmac_stats.tx_auth_rq++;
skb = rtllib_authentication_req(beacon, ieee, 0, daddr);
if (!skb)
rtllib_associate_abort(ieee);
else {
ieee->state = RTLLIB_ASSOCIATING_AUTHENTICATING ;
RTLLIB_DEBUG_MGMT("Sending authentication request\n");
softmac_mgmt_xmit(skb, ieee);
if (!timer_pending(&ieee->associate_timer)) {
ieee->associate_timer.expires = jiffies + (HZ / 2);
add_timer(&ieee->associate_timer);
}
}
}
static void rtllib_auth_challenge(struct rtllib_device *ieee, u8 *challenge, int chlen)
{
u8 *c;
struct sk_buff *skb;
struct rtllib_network *beacon = &ieee->current_network;
ieee->associate_seq++;
ieee->softmac_stats.tx_auth_rq++;
skb = rtllib_authentication_req(beacon, ieee, chlen + 2, beacon->bssid);
if (!skb)
rtllib_associate_abort(ieee);
else {
c = skb_put(skb, chlen+2);
*(c++) = MFIE_TYPE_CHALLENGE;
*(c++) = chlen;
memcpy(c, challenge, chlen);
RTLLIB_DEBUG_MGMT("Sending authentication challenge "
"response\n");
rtllib_encrypt_fragment(ieee, skb,
sizeof(struct rtllib_hdr_3addr));
softmac_mgmt_xmit(skb, ieee);
mod_timer(&ieee->associate_timer, jiffies + (HZ/2));
}
kfree(challenge);
}
static void rtllib_associate_step2(struct rtllib_device *ieee)
{
struct sk_buff *skb;
struct rtllib_network *beacon = &ieee->current_network;
del_timer_sync(&ieee->associate_timer);
RTLLIB_DEBUG_MGMT("Sending association request\n");
ieee->softmac_stats.tx_ass_rq++;
skb = rtllib_association_req(beacon, ieee);
if (!skb)
rtllib_associate_abort(ieee);
else {
softmac_mgmt_xmit(skb, ieee);
mod_timer(&ieee->associate_timer, jiffies + (HZ/2));
}
}
#define CANCELLED 2
static void rtllib_associate_complete_wq(void *data)
{
struct rtllib_device *ieee = (struct rtllib_device *)
container_of_work_rsl(data,
struct rtllib_device,
associate_complete_wq);
struct rt_pwr_save_ctrl *pPSC = (struct rt_pwr_save_ctrl *)
(&(ieee->PowerSaveControl));
printk(KERN_INFO "Associated successfully\n");
if (ieee->is_silent_reset == 0) {
printk(KERN_INFO "normal associate\n");
notify_wx_assoc_event(ieee);
}
netif_carrier_on(ieee->dev);
ieee->is_roaming = false;
if (rtllib_is_54g(&ieee->current_network) &&
(ieee->modulation & RTLLIB_OFDM_MODULATION)) {
ieee->rate = 108;
printk(KERN_INFO"Using G rates:%d\n", ieee->rate);
} else {
ieee->rate = 22;
ieee->SetWirelessMode(ieee->dev, IEEE_B);
printk(KERN_INFO"Using B rates:%d\n", ieee->rate);
}
if (ieee->pHTInfo->bCurrentHTSupport && ieee->pHTInfo->bEnableHT) {
printk(KERN_INFO "Successfully associated, ht enabled\n");
HTOnAssocRsp(ieee);
} else {
printk(KERN_INFO "Successfully associated, ht not "
"enabled(%d, %d)\n",
ieee->pHTInfo->bCurrentHTSupport,
ieee->pHTInfo->bEnableHT);
memset(ieee->dot11HTOperationalRateSet, 0, 16);
}
ieee->LinkDetectInfo.SlotNum = 2 * (1 +
ieee->current_network.beacon_interval /
500);
if (ieee->LinkDetectInfo.NumRecvBcnInPeriod == 0 ||
ieee->LinkDetectInfo.NumRecvDataInPeriod == 0) {
ieee->LinkDetectInfo.NumRecvBcnInPeriod = 1;
ieee->LinkDetectInfo.NumRecvDataInPeriod = 1;
}
pPSC->LpsIdleCount = 0;
ieee->link_change(ieee->dev);
if (ieee->is_silent_reset == 1) {
printk(KERN_INFO "silent reset associate\n");
ieee->is_silent_reset = 0;
}
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
}
static void rtllib_sta_send_associnfo(struct rtllib_device *ieee)
{
}
static void rtllib_associate_complete(struct rtllib_device *ieee)
{
del_timer_sync(&ieee->associate_timer);
ieee->state = RTLLIB_LINKED;
rtllib_sta_send_associnfo(ieee);
queue_work_rsl(ieee->wq, &ieee->associate_complete_wq);
}
static void rtllib_associate_procedure_wq(void *data)
{
struct rtllib_device *ieee = container_of_dwork_rsl(data,
struct rtllib_device,
associate_procedure_wq);
rtllib_stop_scan_syncro(ieee);
if (ieee->rtllib_ips_leave != NULL)
ieee->rtllib_ips_leave(ieee->dev);
down(&ieee->wx_sem);
if (ieee->data_hard_stop)
ieee->data_hard_stop(ieee->dev);
rtllib_stop_scan(ieee);
RT_TRACE(COMP_DBG, "===>%s(), chan:%d\n", __func__,
ieee->current_network.channel);
HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
if (ieee->eRFPowerState == eRfOff) {
RT_TRACE(COMP_DBG, "=============>%s():Rf state is eRfOff,"
" schedule ipsleave wq again,return\n", __func__);
if (ieee->rtllib_ips_leave_wq != NULL)
ieee->rtllib_ips_leave_wq(ieee->dev);
up(&ieee->wx_sem);
return;
}
ieee->associate_seq = 1;
rtllib_associate_step1(ieee, ieee->current_network.bssid);
up(&ieee->wx_sem);
}
inline void rtllib_softmac_new_net(struct rtllib_device *ieee,
struct rtllib_network *net)
{
u8 tmp_ssid[IW_ESSID_MAX_SIZE + 1];
int tmp_ssid_len = 0;
short apset, ssidset, ssidbroad, apmatch, ssidmatch;
/* we are interested in new new only if we are not associated
* and we are not associating / authenticating
*/
if (ieee->state != RTLLIB_NOLINK)
return;
if ((ieee->iw_mode == IW_MODE_INFRA) && !(net->capability &
WLAN_CAPABILITY_ESS))
return;
if ((ieee->iw_mode == IW_MODE_ADHOC) && !(net->capability &
WLAN_CAPABILITY_IBSS))
return;
if ((ieee->iw_mode == IW_MODE_ADHOC) &&
(net->channel > ieee->ibss_maxjoin_chal))
return;
if (ieee->iw_mode == IW_MODE_INFRA || ieee->iw_mode == IW_MODE_ADHOC) {
/* if the user specified the AP MAC, we need also the essid
* This could be obtained by beacons or, if the network does not
* broadcast it, it can be put manually.
*/
apset = ieee->wap_set;
ssidset = ieee->ssid_set;
ssidbroad = !(net->ssid_len == 0 || net->ssid[0] == '\0');
apmatch = (memcmp(ieee->current_network.bssid, net->bssid,
ETH_ALEN) == 0);
if (!ssidbroad) {
ssidmatch = (ieee->current_network.ssid_len ==
net->hidden_ssid_len) &&
(!strncmp(ieee->current_network.ssid,
net->hidden_ssid, net->hidden_ssid_len));
if (net->hidden_ssid_len > 0) {
strncpy(net->ssid, net->hidden_ssid,
net->hidden_ssid_len);
net->ssid_len = net->hidden_ssid_len;
ssidbroad = 1;
}
} else
ssidmatch =
(ieee->current_network.ssid_len == net->ssid_len) &&
(!strncmp(ieee->current_network.ssid, net->ssid,
net->ssid_len));
/* if the user set the AP check if match.
* if the network does not broadcast essid we check the
* user supplyed ANY essid
* if the network does broadcast and the user does not set
* essid it is OK
* if the network does broadcast and the user did set essid
* check if essid match
* if the ap is not set, check that the user set the bssid
* and the network does bradcast and that those two bssid match
*/
if ((apset && apmatch &&
((ssidset && ssidbroad && ssidmatch) ||
(ssidbroad && !ssidset) || (!ssidbroad && ssidset))) ||
(!apset && ssidset && ssidbroad && ssidmatch) ||
(ieee->is_roaming && ssidset && ssidbroad && ssidmatch)) {
/* if the essid is hidden replace it with the
* essid provided by the user.
*/
if (!ssidbroad) {
strncpy(tmp_ssid, ieee->current_network.ssid,
IW_ESSID_MAX_SIZE);
tmp_ssid_len = ieee->current_network.ssid_len;
}
memcpy(&ieee->current_network, net,
sizeof(struct rtllib_network));
if (!ssidbroad) {
strncpy(ieee->current_network.ssid, tmp_ssid,
IW_ESSID_MAX_SIZE);
ieee->current_network.ssid_len = tmp_ssid_len;
}
printk(KERN_INFO"Linking with %s,channel:%d, qos:%d, "
"myHT:%d, networkHT:%d, mode:%x cur_net.flags"
":0x%x\n", ieee->current_network.ssid,
ieee->current_network.channel,
ieee->current_network.qos_data.supported,
ieee->pHTInfo->bEnableHT,
ieee->current_network.bssht.bdSupportHT,
ieee->current_network.mode,
ieee->current_network.flags);
if ((rtllib_act_scanning(ieee, false)) &&
!(ieee->softmac_features & IEEE_SOFTMAC_SCAN))
rtllib_stop_scan_syncro(ieee);
ieee->hwscan_ch_bk = ieee->current_network.channel;
HTResetIOTSetting(ieee->pHTInfo);
ieee->wmm_acm = 0;
if (ieee->iw_mode == IW_MODE_INFRA) {
/* Join the network for the first time */
ieee->AsocRetryCount = 0;
if ((ieee->current_network.qos_data.supported == 1) &&
ieee->current_network.bssht.bdSupportHT)
HTResetSelfAndSavePeerSetting(ieee,
&(ieee->current_network));
else
ieee->pHTInfo->bCurrentHTSupport =
false;
ieee->state = RTLLIB_ASSOCIATING;
if (ieee->LedControlHandler != NULL)
ieee->LedControlHandler(ieee->dev,
LED_CTL_START_TO_LINK);
queue_delayed_work_rsl(ieee->wq,
&ieee->associate_procedure_wq, 0);
} else {
if (rtllib_is_54g(&ieee->current_network) &&
(ieee->modulation & RTLLIB_OFDM_MODULATION)) {
ieee->rate = 108;
ieee->SetWirelessMode(ieee->dev, IEEE_G);
printk(KERN_INFO"Using G rates\n");
} else {
ieee->rate = 22;
ieee->SetWirelessMode(ieee->dev, IEEE_B);
printk(KERN_INFO"Using B rates\n");
}
memset(ieee->dot11HTOperationalRateSet, 0, 16);
ieee->state = RTLLIB_LINKED;
}
}
}
}
void rtllib_softmac_check_all_nets(struct rtllib_device *ieee)
{
unsigned long flags;
struct rtllib_network *target;
spin_lock_irqsave(&ieee->lock, flags);
list_for_each_entry(target, &ieee->network_list, list) {
/* if the state become different that NOLINK means
* we had found what we are searching for
*/
if (ieee->state != RTLLIB_NOLINK)
break;
if (ieee->scan_age == 0 || time_after(target->last_scanned +
ieee->scan_age, jiffies))
rtllib_softmac_new_net(ieee, target);
}
spin_unlock_irqrestore(&ieee->lock, flags);
}
static inline u16 auth_parse(struct sk_buff *skb, u8** challenge, int *chlen)
{
struct rtllib_authentication *a;
u8 *t;
if (skb->len < (sizeof(struct rtllib_authentication) -
sizeof(struct rtllib_info_element))) {
RTLLIB_DEBUG_MGMT("invalid len in auth resp: %d\n", skb->len);
return 0xcafe;
}
*challenge = NULL;
a = (struct rtllib_authentication *) skb->data;
if (skb->len > (sizeof(struct rtllib_authentication) + 3)) {
t = skb->data + sizeof(struct rtllib_authentication);
if (*(t++) == MFIE_TYPE_CHALLENGE) {
*chlen = *(t++);
*challenge = kmalloc(*chlen, GFP_ATOMIC);
memcpy(*challenge, t, *chlen); /*TODO - check here*/
}
}
return cpu_to_le16(a->status);
}
static int auth_rq_parse(struct sk_buff *skb, u8 *dest)
{
struct rtllib_authentication *a;
if (skb->len < (sizeof(struct rtllib_authentication) -
sizeof(struct rtllib_info_element))) {
RTLLIB_DEBUG_MGMT("invalid len in auth request: %d\n",
skb->len);
return -1;
}
a = (struct rtllib_authentication *) skb->data;
memcpy(dest, a->header.addr2, ETH_ALEN);
if (le16_to_cpu(a->algorithm) != WLAN_AUTH_OPEN)
return WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG;
return WLAN_STATUS_SUCCESS;
}
static short probe_rq_parse(struct rtllib_device *ieee, struct sk_buff *skb,
u8 *src)
{
u8 *tag;
u8 *skbend;
u8 *ssid = NULL;
u8 ssidlen = 0;
struct rtllib_hdr_3addr *header =
(struct rtllib_hdr_3addr *) skb->data;
bool bssid_match;
if (skb->len < sizeof(struct rtllib_hdr_3addr))
return -1; /* corrupted */
bssid_match =
(memcmp(header->addr3, ieee->current_network.bssid, ETH_ALEN) != 0) &&
(memcmp(header->addr3, "\xff\xff\xff\xff\xff\xff", ETH_ALEN) != 0);
if (bssid_match)
return -1;
memcpy(src, header->addr2, ETH_ALEN);
skbend = (u8 *)skb->data + skb->len;
tag = skb->data + sizeof(struct rtllib_hdr_3addr);
while (tag + 1 < skbend) {
if (*tag == 0) {
ssid = tag + 2;
ssidlen = *(tag + 1);
break;
}
tag++; /* point to the len field */
tag = tag + *(tag); /* point to the last data byte of the tag */
tag++; /* point to the next tag */
}
if (ssidlen == 0)
return 1;
if (!ssid)
return 1; /* ssid not found in tagged param */
return !strncmp(ssid, ieee->current_network.ssid, ssidlen);
}
static int assoc_rq_parse(struct sk_buff *skb, u8 *dest)
{
struct rtllib_assoc_request_frame *a;
if (skb->len < (sizeof(struct rtllib_assoc_request_frame) -
sizeof(struct rtllib_info_element))) {
RTLLIB_DEBUG_MGMT("invalid len in auth request:%d\n", skb->len);
return -1;
}
a = (struct rtllib_assoc_request_frame *) skb->data;
memcpy(dest, a->header.addr2, ETH_ALEN);
return 0;
}
static inline u16 assoc_parse(struct rtllib_device *ieee, struct sk_buff *skb,
int *aid)
{
struct rtllib_assoc_response_frame *response_head;
u16 status_code;
if (skb->len < sizeof(struct rtllib_assoc_response_frame)) {
RTLLIB_DEBUG_MGMT("invalid len in auth resp: %d\n", skb->len);
return 0xcafe;
}
response_head = (struct rtllib_assoc_response_frame *) skb->data;
*aid = le16_to_cpu(response_head->aid) & 0x3fff;
status_code = le16_to_cpu(response_head->status);
if ((status_code == WLAN_STATUS_ASSOC_DENIED_RATES ||
status_code == WLAN_STATUS_CAPS_UNSUPPORTED) &&
((ieee->mode == IEEE_G) &&
(ieee->current_network.mode == IEEE_N_24G) &&
(ieee->AsocRetryCount++ < (RT_ASOC_RETRY_LIMIT-1)))) {
ieee->pHTInfo->IOTAction |= HT_IOT_ACT_PURE_N_MODE;
} else {
ieee->AsocRetryCount = 0;
}
return le16_to_cpu(response_head->status);
}
void rtllib_rx_probe_rq(struct rtllib_device *ieee, struct sk_buff *skb)
{
u8 dest[ETH_ALEN];
ieee->softmac_stats.rx_probe_rq++;
if (probe_rq_parse(ieee, skb, dest) > 0) {
ieee->softmac_stats.tx_probe_rs++;
rtllib_resp_to_probe(ieee, dest);
}
}
static inline void rtllib_rx_auth_rq(struct rtllib_device *ieee,
struct sk_buff *skb)
{
u8 dest[ETH_ALEN];
int status;
ieee->softmac_stats.rx_auth_rq++;
status = auth_rq_parse(skb, dest);
if (status != -1)
rtllib_resp_to_auth(ieee, status, dest);
}
static inline void rtllib_rx_assoc_rq(struct rtllib_device *ieee,
struct sk_buff *skb)
{
u8 dest[ETH_ALEN];
ieee->softmac_stats.rx_ass_rq++;
if (assoc_rq_parse(skb, dest) != -1)
rtllib_resp_to_assoc_rq(ieee, dest);
printk(KERN_INFO"New client associated: %pM\n", dest);
}
void rtllib_sta_ps_send_null_frame(struct rtllib_device *ieee, short pwr)
{
struct sk_buff *buf = rtllib_null_func(ieee, pwr);
if (buf)
softmac_ps_mgmt_xmit(buf, ieee);
}
EXPORT_SYMBOL(rtllib_sta_ps_send_null_frame);
void rtllib_sta_ps_send_pspoll_frame(struct rtllib_device *ieee)
{
struct sk_buff *buf = rtllib_pspoll_func(ieee);
if (buf)
softmac_ps_mgmt_xmit(buf, ieee);
}
static short rtllib_sta_ps_sleep(struct rtllib_device *ieee, u64 *time)
{
int timeout = ieee->ps_timeout;
u8 dtim;
struct rt_pwr_save_ctrl *pPSC = (struct rt_pwr_save_ctrl *)
(&(ieee->PowerSaveControl));
if (ieee->LPSDelayCnt) {
ieee->LPSDelayCnt--;
return 0;
}
dtim = ieee->current_network.dtim_data;
if (!(dtim & RTLLIB_DTIM_VALID))
return 0;
timeout = ieee->current_network.beacon_interval;
ieee->current_network.dtim_data = RTLLIB_DTIM_INVALID;
/* there's no need to nofity AP that I find you buffered
* with broadcast packet */
if (dtim & (RTLLIB_DTIM_UCAST & ieee->ps))
return 2;
if (!time_after(jiffies, ieee->dev->trans_start + MSECS(timeout)))
return 0;
if (!time_after(jiffies, ieee->last_rx_ps_time + MSECS(timeout)))
return 0;
if ((ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE) &&
(ieee->mgmt_queue_tail != ieee->mgmt_queue_head))
return 0;
if (time) {
if (ieee->bAwakePktSent == true) {
pPSC->LPSAwakeIntvl = 1;
} else {
u8 MaxPeriod = 1;
if (pPSC->LPSAwakeIntvl == 0)
pPSC->LPSAwakeIntvl = 1;
if (pPSC->RegMaxLPSAwakeIntvl == 0)
MaxPeriod = 1;
else if (pPSC->RegMaxLPSAwakeIntvl == 0xFF)
MaxPeriod = ieee->current_network.dtim_period;
else
MaxPeriod = pPSC->RegMaxLPSAwakeIntvl;
pPSC->LPSAwakeIntvl = (pPSC->LPSAwakeIntvl >=
MaxPeriod) ? MaxPeriod :
(pPSC->LPSAwakeIntvl + 1);
}
{
u8 LPSAwakeIntvl_tmp = 0;
u8 period = ieee->current_network.dtim_period;
u8 count = ieee->current_network.tim.tim_count;
if (count == 0) {
if (pPSC->LPSAwakeIntvl > period)
LPSAwakeIntvl_tmp = period +
(pPSC->LPSAwakeIntvl -
period) -
((pPSC->LPSAwakeIntvl-period) %
period);
else
LPSAwakeIntvl_tmp = pPSC->LPSAwakeIntvl;
} else {
if (pPSC->LPSAwakeIntvl >
ieee->current_network.tim.tim_count)
LPSAwakeIntvl_tmp = count +
(pPSC->LPSAwakeIntvl - count) -
((pPSC->LPSAwakeIntvl-count)%period);
else
LPSAwakeIntvl_tmp = pPSC->LPSAwakeIntvl;
}
*time = ieee->current_network.last_dtim_sta_time
+ MSECS(ieee->current_network.beacon_interval *
LPSAwakeIntvl_tmp);
}
}
return 1;
}
static inline void rtllib_sta_ps(struct rtllib_device *ieee)
{
u64 time;
short sleep;
unsigned long flags, flags2;
spin_lock_irqsave(&ieee->lock, flags);
if ((ieee->ps == RTLLIB_PS_DISABLED ||
ieee->iw_mode != IW_MODE_INFRA ||
ieee->state != RTLLIB_LINKED)) {
RT_TRACE(COMP_DBG, "=====>%s(): no need to ps,wake up!! "
"ieee->ps is %d, ieee->iw_mode is %d, ieee->state"
" is %d\n", __func__, ieee->ps, ieee->iw_mode,
ieee->state);
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
rtllib_sta_wakeup(ieee, 1);
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
sleep = rtllib_sta_ps_sleep(ieee, &time);
/* 2 wake, 1 sleep, 0 do nothing */
if (sleep == 0)
goto out;
if (sleep == 1) {
if (ieee->sta_sleep == LPS_IS_SLEEP) {
ieee->enter_sleep_state(ieee->dev, time);
} else if (ieee->sta_sleep == LPS_IS_WAKE) {
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
if (ieee->ps_is_queue_empty(ieee->dev)) {
ieee->sta_sleep = LPS_WAIT_NULL_DATA_SEND;
ieee->ack_tx_to_ieee = 1;
rtllib_sta_ps_send_null_frame(ieee, 1);
ieee->ps_time = time;
}
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
ieee->bAwakePktSent = false;
} else if (sleep == 2) {
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
rtllib_sta_wakeup(ieee, 1);
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
out:
spin_unlock_irqrestore(&ieee->lock, flags);
}
void rtllib_sta_wakeup(struct rtllib_device *ieee, short nl)
{
if (ieee->sta_sleep == LPS_IS_WAKE) {
if (nl) {
if (ieee->pHTInfo->IOTAction &
HT_IOT_ACT_NULL_DATA_POWER_SAVING) {
ieee->ack_tx_to_ieee = 1;
rtllib_sta_ps_send_null_frame(ieee, 0);
} else {
ieee->ack_tx_to_ieee = 1;
rtllib_sta_ps_send_pspoll_frame(ieee);
}
}
return;
}
if (ieee->sta_sleep == LPS_IS_SLEEP)
ieee->sta_wake_up(ieee->dev);
if (nl) {
if (ieee->pHTInfo->IOTAction &
HT_IOT_ACT_NULL_DATA_POWER_SAVING) {
ieee->ack_tx_to_ieee = 1;
rtllib_sta_ps_send_null_frame(ieee, 0);
} else {
ieee->ack_tx_to_ieee = 1;
ieee->polling = true;
rtllib_sta_ps_send_pspoll_frame(ieee);
}
} else {
ieee->sta_sleep = LPS_IS_WAKE;
ieee->polling = false;
}
}
void rtllib_ps_tx_ack(struct rtllib_device *ieee, short success)
{
unsigned long flags, flags2;
spin_lock_irqsave(&ieee->lock, flags);
if (ieee->sta_sleep == LPS_WAIT_NULL_DATA_SEND) {
/* Null frame with PS bit set */
if (success) {
ieee->sta_sleep = LPS_IS_SLEEP;
ieee->enter_sleep_state(ieee->dev, ieee->ps_time);
}
/* if the card report not success we can't be sure the AP
* has not RXed so we can't assume the AP believe us awake
*/
} else {/* 21112005 - tx again null without PS bit if lost */
if ((ieee->sta_sleep == LPS_IS_WAKE) && !success) {
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
if (ieee->pHTInfo->IOTAction &
HT_IOT_ACT_NULL_DATA_POWER_SAVING)
rtllib_sta_ps_send_null_frame(ieee, 0);
else
rtllib_sta_ps_send_pspoll_frame(ieee);
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
}
spin_unlock_irqrestore(&ieee->lock, flags);
}
EXPORT_SYMBOL(rtllib_ps_tx_ack);
static void rtllib_process_action(struct rtllib_device *ieee, struct sk_buff *skb)
{
struct rtllib_hdr_3addr *header = (struct rtllib_hdr_3addr *) skb->data;
u8 *act = rtllib_get_payload((struct rtllib_hdr *)header);
u8 category = 0;
if (act == NULL) {
RTLLIB_DEBUG(RTLLIB_DL_ERR, "error to get payload of "
"action frame\n");
return;
}
category = *act;
act++;
switch (category) {
case ACT_CAT_BA:
switch (*act) {
case ACT_ADDBAREQ:
rtllib_rx_ADDBAReq(ieee, skb);
break;
case ACT_ADDBARSP:
rtllib_rx_ADDBARsp(ieee, skb);
break;
case ACT_DELBA:
rtllib_rx_DELBA(ieee, skb);
break;
}
break;
default:
break;
}
return;
}
inline int rtllib_rx_assoc_resp(struct rtllib_device *ieee, struct sk_buff *skb,
struct rtllib_rx_stats *rx_stats)
{
u16 errcode;
int aid;
u8 *ies;
struct rtllib_assoc_response_frame *assoc_resp;
struct rtllib_hdr_3addr *header = (struct rtllib_hdr_3addr *) skb->data;
RTLLIB_DEBUG_MGMT("received [RE]ASSOCIATION RESPONSE (%d)\n",
WLAN_FC_GET_STYPE(header->frame_ctl));
if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
ieee->state == RTLLIB_ASSOCIATING_AUTHENTICATED &&
(ieee->iw_mode == IW_MODE_INFRA)) {
errcode = assoc_parse(ieee, skb, &aid);
if (0 == errcode) {
struct rtllib_network *network =
kzalloc(sizeof(struct rtllib_network),
GFP_ATOMIC);
if (!network)
return 1;
ieee->state = RTLLIB_LINKED;
ieee->assoc_id = aid;
ieee->softmac_stats.rx_ass_ok++;
/* station support qos */
/* Let the register setting default with Legacy station */
assoc_resp = (struct rtllib_assoc_response_frame *)skb->data;
if (ieee->current_network.qos_data.supported == 1) {
if (rtllib_parse_info_param(ieee, assoc_resp->info_element,
rx_stats->len - sizeof(*assoc_resp),
network, rx_stats)) {
kfree(network);
return 1;
} else {
memcpy(ieee->pHTInfo->PeerHTCapBuf,
network->bssht.bdHTCapBuf,
network->bssht.bdHTCapLen);
memcpy(ieee->pHTInfo->PeerHTInfoBuf,
network->bssht.bdHTInfoBuf,
network->bssht.bdHTInfoLen);
}
if (ieee->handle_assoc_response != NULL)
ieee->handle_assoc_response(ieee->dev,
(struct rtllib_assoc_response_frame *)header,
network);
}
kfree(network);
kfree(ieee->assocresp_ies);
ieee->assocresp_ies = NULL;
ies = &(assoc_resp->info_element[0].id);
ieee->assocresp_ies_len = (skb->data + skb->len) - ies;
ieee->assocresp_ies = kmalloc(ieee->assocresp_ies_len,
GFP_ATOMIC);
if (ieee->assocresp_ies)
memcpy(ieee->assocresp_ies, ies,
ieee->assocresp_ies_len);
else {
printk(KERN_INFO "%s()Warning: can't alloc "
"memory for assocresp_ies\n", __func__);
ieee->assocresp_ies_len = 0;
}
rtllib_associate_complete(ieee);
} else {
/* aid could not been allocated */
ieee->softmac_stats.rx_ass_err++;
printk(KERN_INFO "Association response status code 0x%x\n",
errcode);
RTLLIB_DEBUG_MGMT(
"Association response status code 0x%x\n",
errcode);
if (ieee->AsocRetryCount < RT_ASOC_RETRY_LIMIT)
queue_delayed_work_rsl(ieee->wq,
&ieee->associate_procedure_wq, 0);
else
rtllib_associate_abort(ieee);
}
}
return 0;
}
inline int rtllib_rx_auth(struct rtllib_device *ieee, struct sk_buff *skb,
struct rtllib_rx_stats *rx_stats)
{
u16 errcode;
u8 *challenge;
int chlen = 0;
bool bSupportNmode = true, bHalfSupportNmode = false;
if (ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) {
if (ieee->state == RTLLIB_ASSOCIATING_AUTHENTICATING &&
(ieee->iw_mode == IW_MODE_INFRA)) {
RTLLIB_DEBUG_MGMT("Received authentication response");
errcode = auth_parse(skb, &challenge, &chlen);
if (0 == errcode) {
if (ieee->open_wep || !challenge) {
ieee->state = RTLLIB_ASSOCIATING_AUTHENTICATED;
ieee->softmac_stats.rx_auth_rs_ok++;
if (!(ieee->pHTInfo->IOTAction &
HT_IOT_ACT_PURE_N_MODE)) {
if (!ieee->GetNmodeSupportBySecCfg(ieee->dev)) {
if (IsHTHalfNmodeAPs(ieee)) {
bSupportNmode = true;
bHalfSupportNmode = true;
} else {
bSupportNmode = false;
bHalfSupportNmode = false;
}
}
}
/* Dummy wirless mode setting to avoid
* encryption issue */
if (bSupportNmode) {
ieee->SetWirelessMode(ieee->dev,
ieee->current_network.mode);
} else {
/*TODO*/
ieee->SetWirelessMode(ieee->dev,
IEEE_G);
}
if (ieee->current_network.mode ==
IEEE_N_24G &&
bHalfSupportNmode == true) {
printk(KERN_INFO "======>enter "
"half N mode\n");
ieee->bHalfWirelessN24GMode =
true;
} else
ieee->bHalfWirelessN24GMode =
false;
rtllib_associate_step2(ieee);
} else {
rtllib_auth_challenge(ieee, challenge,
chlen);
}
} else {
ieee->softmac_stats.rx_auth_rs_err++;
RTLLIB_DEBUG_MGMT("Authentication respose"
" status code 0x%x", errcode);
printk(KERN_INFO "Authentication respose "
"status code 0x%x", errcode);
rtllib_associate_abort(ieee);
}
} else if (ieee->iw_mode == IW_MODE_MASTER) {
rtllib_rx_auth_rq(ieee, skb);
}
}
return 0;
}
inline int rtllib_rx_deauth(struct rtllib_device *ieee, struct sk_buff *skb)
{
struct rtllib_hdr_3addr *header = (struct rtllib_hdr_3addr *) skb->data;
if (memcmp(header->addr3, ieee->current_network.bssid, ETH_ALEN) != 0)
return 0;
/* FIXME for now repeat all the association procedure
* both for disassociation and deauthentication
*/
if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
ieee->state == RTLLIB_LINKED &&
(ieee->iw_mode == IW_MODE_INFRA)) {
printk(KERN_INFO "==========>received disassoc/deauth(%x) "
"frame, reason code:%x\n",
WLAN_FC_GET_STYPE(header->frame_ctl),
((struct rtllib_disassoc *)skb->data)->reason);
ieee->state = RTLLIB_ASSOCIATING;
ieee->softmac_stats.reassoc++;
ieee->is_roaming = true;
ieee->LinkDetectInfo.bBusyTraffic = false;
rtllib_disassociate(ieee);
RemovePeerTS(ieee, header->addr2);
if (ieee->LedControlHandler != NULL)
ieee->LedControlHandler(ieee->dev,
LED_CTL_START_TO_LINK);
if (!(ieee->rtllib_ap_sec_type(ieee) &
(SEC_ALG_CCMP|SEC_ALG_TKIP)))
queue_delayed_work_rsl(ieee->wq,
&ieee->associate_procedure_wq, 5);
}
return 0;
}
inline int rtllib_rx_frame_softmac(struct rtllib_device *ieee,
struct sk_buff *skb,
struct rtllib_rx_stats *rx_stats, u16 type,
u16 stype)
{
struct rtllib_hdr_3addr *header = (struct rtllib_hdr_3addr *) skb->data;
if (!ieee->proto_started)
return 0;
switch (WLAN_FC_GET_STYPE(header->frame_ctl)) {
case RTLLIB_STYPE_ASSOC_RESP:
case RTLLIB_STYPE_REASSOC_RESP:
if (rtllib_rx_assoc_resp(ieee, skb, rx_stats) == 1)
return 1;
break;
case RTLLIB_STYPE_ASSOC_REQ:
case RTLLIB_STYPE_REASSOC_REQ:
if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
ieee->iw_mode == IW_MODE_MASTER)
rtllib_rx_assoc_rq(ieee, skb);
break;
case RTLLIB_STYPE_AUTH:
rtllib_rx_auth(ieee, skb, rx_stats);
break;
case RTLLIB_STYPE_DISASSOC:
case RTLLIB_STYPE_DEAUTH:
rtllib_rx_deauth(ieee, skb);
break;
case RTLLIB_STYPE_MANAGE_ACT:
rtllib_process_action(ieee, skb);
break;
default:
return -1;
break;
}
return 0;
}
/* following are for a simplier TX queue management.
* Instead of using netif_[stop/wake]_queue the driver
* will uses these two function (plus a reset one), that
* will internally uses the kernel netif_* and takes
* care of the ieee802.11 fragmentation.
* So the driver receives a fragment per time and might
* call the stop function when it want without take care
* to have enought room to TX an entire packet.
* This might be useful if each fragment need it's own
* descriptor, thus just keep a total free memory > than
* the max fragmentation treshold is not enought.. If the
* ieee802.11 stack passed a TXB struct then you needed
* to keep N free descriptors where
* N = MAX_PACKET_SIZE / MIN_FRAG_TRESHOLD
* In this way you need just one and the 802.11 stack
* will take care of buffering fragments and pass them to
* to the driver later, when it wakes the queue.
*/
void rtllib_softmac_xmit(struct rtllib_txb *txb, struct rtllib_device *ieee)
{
unsigned int queue_index = txb->queue_index;
unsigned long flags;
int i;
struct cb_desc *tcb_desc = NULL;
unsigned long queue_len = 0;
spin_lock_irqsave(&ieee->lock, flags);
/* called with 2nd parm 0, no tx mgmt lock required */
rtllib_sta_wakeup(ieee, 0);
/* update the tx status */
tcb_desc = (struct cb_desc *)(txb->fragments[0]->cb +
MAX_DEV_ADDR_SIZE);
if (tcb_desc->bMulticast)
ieee->stats.multicast++;
/* if xmit available, just xmit it immediately, else just insert it to
* the wait queue */
for (i = 0; i < txb->nr_frags; i++) {
queue_len = skb_queue_len(&ieee->skb_waitQ[queue_index]);
if ((queue_len != 0) ||\
(!ieee->check_nic_enough_desc(ieee->dev, queue_index)) ||
(ieee->queue_stop)) {
/* insert the skb packet to the wait queue */
/* as for the completion function, it does not need
* to check it any more.
* */
if (queue_len < 200)
skb_queue_tail(&ieee->skb_waitQ[queue_index],
txb->fragments[i]);
else
kfree_skb(txb->fragments[i]);
} else {
ieee->softmac_data_hard_start_xmit(
txb->fragments[i],
ieee->dev, ieee->rate);
}
}
rtllib_txb_free(txb);
spin_unlock_irqrestore(&ieee->lock, flags);
}
/* called with ieee->lock acquired */
static void rtllib_resume_tx(struct rtllib_device *ieee)
{
int i;
for (i = ieee->tx_pending.frag; i < ieee->tx_pending.txb->nr_frags;
i++) {
if (ieee->queue_stop) {
ieee->tx_pending.frag = i;
return;
} else {
ieee->softmac_data_hard_start_xmit(
ieee->tx_pending.txb->fragments[i],
ieee->dev, ieee->rate);
ieee->stats.tx_packets++;
}
}
rtllib_txb_free(ieee->tx_pending.txb);
ieee->tx_pending.txb = NULL;
}
void rtllib_reset_queue(struct rtllib_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->lock, flags);
init_mgmt_queue(ieee);
if (ieee->tx_pending.txb) {
rtllib_txb_free(ieee->tx_pending.txb);
ieee->tx_pending.txb = NULL;
}
ieee->queue_stop = 0;
spin_unlock_irqrestore(&ieee->lock, flags);
}
EXPORT_SYMBOL(rtllib_reset_queue);
void rtllib_wake_queue(struct rtllib_device *ieee)
{
unsigned long flags;
struct sk_buff *skb;
struct rtllib_hdr_3addr *header;
spin_lock_irqsave(&ieee->lock, flags);
if (!ieee->queue_stop)
goto exit;
ieee->queue_stop = 0;
if (ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE) {
while (!ieee->queue_stop && (skb = dequeue_mgmt(ieee))) {
header = (struct rtllib_hdr_3addr *) skb->data;
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
ieee->softmac_data_hard_start_xmit(skb, ieee->dev,
ieee->basic_rate);
}
}
if (!ieee->queue_stop && ieee->tx_pending.txb)
rtllib_resume_tx(ieee);
if (!ieee->queue_stop && netif_queue_stopped(ieee->dev)) {
ieee->softmac_stats.swtxawake++;
netif_wake_queue(ieee->dev);
}
exit:
spin_unlock_irqrestore(&ieee->lock, flags);
}
void rtllib_stop_queue(struct rtllib_device *ieee)
{
if (!netif_queue_stopped(ieee->dev)) {
netif_stop_queue(ieee->dev);
ieee->softmac_stats.swtxstop++;
}
ieee->queue_stop = 1;
}
void rtllib_stop_all_queues(struct rtllib_device *ieee)
{
unsigned int i;
for (i = 0; i < ieee->dev->num_tx_queues; i++)
netdev_get_tx_queue(ieee->dev, i)->trans_start = jiffies;
netif_tx_stop_all_queues(ieee->dev);
}
void rtllib_wake_all_queues(struct rtllib_device *ieee)
{
netif_tx_wake_all_queues(ieee->dev);
}
inline void rtllib_randomize_cell(struct rtllib_device *ieee)
{
get_random_bytes(ieee->current_network.bssid, ETH_ALEN);
/* an IBSS cell address must have the two less significant
* bits of the first byte = 2
*/
ieee->current_network.bssid[0] &= ~0x01;
ieee->current_network.bssid[0] |= 0x02;
}
/* called in user context only */
void rtllib_start_master_bss(struct rtllib_device *ieee)
{
ieee->assoc_id = 1;
if (ieee->current_network.ssid_len == 0) {
strncpy(ieee->current_network.ssid,
RTLLIB_DEFAULT_TX_ESSID,
IW_ESSID_MAX_SIZE);
ieee->current_network.ssid_len =
strlen(RTLLIB_DEFAULT_TX_ESSID);
ieee->ssid_set = 1;
}
memcpy(ieee->current_network.bssid, ieee->dev->dev_addr, ETH_ALEN);
ieee->set_chan(ieee->dev, ieee->current_network.channel);
ieee->state = RTLLIB_LINKED;
ieee->link_change(ieee->dev);
notify_wx_assoc_event(ieee);
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
}
static void rtllib_start_monitor_mode(struct rtllib_device *ieee)
{
/* reset hardware status */
if (ieee->raw_tx) {
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
}
}
static void rtllib_start_ibss_wq(void *data)
{
struct rtllib_device *ieee = container_of_dwork_rsl(data,
struct rtllib_device, start_ibss_wq);
/* iwconfig mode ad-hoc will schedule this and return
* on the other hand this will block further iwconfig SET
* operations because of the wx_sem hold.
* Anyway some most set operations set a flag to speed-up
* (abort) this wq (when syncro scanning) before sleeping
* on the semaphore
*/
if (!ieee->proto_started) {
printk(KERN_INFO "==========oh driver down return\n");
return;
}
down(&ieee->wx_sem);
if (ieee->current_network.ssid_len == 0) {
strcpy(ieee->current_network.ssid, RTLLIB_DEFAULT_TX_ESSID);
ieee->current_network.ssid_len = strlen(RTLLIB_DEFAULT_TX_ESSID);
ieee->ssid_set = 1;
}
ieee->state = RTLLIB_NOLINK;
ieee->mode = IEEE_G;
/* check if we have this cell in our network list */
rtllib_softmac_check_all_nets(ieee);
/* if not then the state is not linked. Maybe the user swithced to
* ad-hoc mode just after being in monitor mode, or just after
* being very few time in managed mode (so the card have had no
* time to scan all the chans..) or we have just run up the iface
* after setting ad-hoc mode. So we have to give another try..
* Here, in ibss mode, should be safe to do this without extra care
* (in bss mode we had to make sure no-one tryed to associate when
* we had just checked the ieee->state and we was going to start the
* scan) beacause in ibss mode the rtllib_new_net function, when
* finds a good net, just set the ieee->state to RTLLIB_LINKED,
* so, at worst, we waste a bit of time to initiate an unneeded syncro
* scan, that will stop at the first round because it sees the state
* associated.
*/
if (ieee->state == RTLLIB_NOLINK)
rtllib_start_scan_syncro(ieee, 0);
/* the network definitively is not here.. create a new cell */
if (ieee->state == RTLLIB_NOLINK) {
printk(KERN_INFO "creating new IBSS cell\n");
ieee->current_network.channel = ieee->IbssStartChnl;
if (!ieee->wap_set)
rtllib_randomize_cell(ieee);
if (ieee->modulation & RTLLIB_CCK_MODULATION) {
ieee->current_network.rates_len = 4;
ieee->current_network.rates[0] =
RTLLIB_BASIC_RATE_MASK | RTLLIB_CCK_RATE_1MB;
ieee->current_network.rates[1] =
RTLLIB_BASIC_RATE_MASK | RTLLIB_CCK_RATE_2MB;
ieee->current_network.rates[2] =
RTLLIB_BASIC_RATE_MASK | RTLLIB_CCK_RATE_5MB;
ieee->current_network.rates[3] =
RTLLIB_BASIC_RATE_MASK | RTLLIB_CCK_RATE_11MB;
} else
ieee->current_network.rates_len = 0;
if (ieee->modulation & RTLLIB_OFDM_MODULATION) {
ieee->current_network.rates_ex_len = 8;
ieee->current_network.rates_ex[0] =
RTLLIB_OFDM_RATE_6MB;
ieee->current_network.rates_ex[1] =
RTLLIB_OFDM_RATE_9MB;
ieee->current_network.rates_ex[2] =
RTLLIB_OFDM_RATE_12MB;
ieee->current_network.rates_ex[3] =
RTLLIB_OFDM_RATE_18MB;
ieee->current_network.rates_ex[4] =
RTLLIB_OFDM_RATE_24MB;
ieee->current_network.rates_ex[5] =
RTLLIB_OFDM_RATE_36MB;
ieee->current_network.rates_ex[6] =
RTLLIB_OFDM_RATE_48MB;
ieee->current_network.rates_ex[7] =
RTLLIB_OFDM_RATE_54MB;
ieee->rate = 108;
} else {
ieee->current_network.rates_ex_len = 0;
ieee->rate = 22;
}
ieee->current_network.qos_data.supported = 0;
ieee->SetWirelessMode(ieee->dev, IEEE_G);
ieee->current_network.mode = ieee->mode;
ieee->current_network.atim_window = 0;
ieee->current_network.capability = WLAN_CAPABILITY_IBSS;
}
printk(KERN_INFO "%s(): ieee->mode = %d\n", __func__, ieee->mode);
if ((ieee->mode == IEEE_N_24G) || (ieee->mode == IEEE_N_5G))
HTUseDefaultSetting(ieee);
else
ieee->pHTInfo->bCurrentHTSupport = false;
ieee->SetHwRegHandler(ieee->dev, HW_VAR_MEDIA_STATUS,
(u8 *)(&ieee->state));
ieee->state = RTLLIB_LINKED;
ieee->link_change(ieee->dev);
HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
if (ieee->LedControlHandler != NULL)
ieee->LedControlHandler(ieee->dev, LED_CTL_LINK);
rtllib_start_send_beacons(ieee);
notify_wx_assoc_event(ieee);
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
up(&ieee->wx_sem);
}
inline void rtllib_start_ibss(struct rtllib_device *ieee)
{
queue_delayed_work_rsl(ieee->wq, &ieee->start_ibss_wq, MSECS(150));
}
/* this is called only in user context, with wx_sem held */
void rtllib_start_bss(struct rtllib_device *ieee)
{
unsigned long flags;
if (IS_DOT11D_ENABLE(ieee) && !IS_COUNTRY_IE_VALID(ieee)) {
if (!ieee->bGlobalDomain)
return;
}
/* check if we have already found the net we
* are interested in (if any).
* if not (we are disassociated and we are not
* in associating / authenticating phase) start the background scanning.
*/
rtllib_softmac_check_all_nets(ieee);
/* ensure no-one start an associating process (thus setting
* the ieee->state to rtllib_ASSOCIATING) while we
* have just cheked it and we are going to enable scan.
* The rtllib_new_net function is always called with
* lock held (from both rtllib_softmac_check_all_nets and
* the rx path), so we cannot be in the middle of such function
*/
spin_lock_irqsave(&ieee->lock, flags);
if (ieee->state == RTLLIB_NOLINK)
rtllib_start_scan(ieee);
spin_unlock_irqrestore(&ieee->lock, flags);
}
static void rtllib_link_change_wq(void *data)
{
struct rtllib_device *ieee = container_of_dwork_rsl(data,
struct rtllib_device, link_change_wq);
ieee->link_change(ieee->dev);
}
/* called only in userspace context */
void rtllib_disassociate(struct rtllib_device *ieee)
{
netif_carrier_off(ieee->dev);
if (ieee->softmac_features & IEEE_SOFTMAC_TX_QUEUE)
rtllib_reset_queue(ieee);
if (ieee->data_hard_stop)
ieee->data_hard_stop(ieee->dev);
if (IS_DOT11D_ENABLE(ieee))
Dot11d_Reset(ieee);
ieee->state = RTLLIB_NOLINK;
ieee->is_set_key = false;
ieee->wap_set = 0;
queue_delayed_work_rsl(ieee->wq, &ieee->link_change_wq, 0);
notify_wx_assoc_event(ieee);
}
static void rtllib_associate_retry_wq(void *data)
{
struct rtllib_device *ieee = container_of_dwork_rsl(data,
struct rtllib_device, associate_retry_wq);
unsigned long flags;
down(&ieee->wx_sem);
if (!ieee->proto_started)
goto exit;
if (ieee->state != RTLLIB_ASSOCIATING_RETRY)
goto exit;
/* until we do not set the state to RTLLIB_NOLINK
* there are no possibility to have someone else trying
* to start an association procdure (we get here with
* ieee->state = RTLLIB_ASSOCIATING).
* When we set the state to RTLLIB_NOLINK it is possible
* that the RX path run an attempt to associate, but
* both rtllib_softmac_check_all_nets and the
* RX path works with ieee->lock held so there are no
* problems. If we are still disassociated then start a scan.
* the lock here is necessary to ensure no one try to start
* an association procedure when we have just checked the
* state and we are going to start the scan.
*/
ieee->beinretry = true;
ieee->state = RTLLIB_NOLINK;
rtllib_softmac_check_all_nets(ieee);
spin_lock_irqsave(&ieee->lock, flags);
if (ieee->state == RTLLIB_NOLINK)
rtllib_start_scan(ieee);
spin_unlock_irqrestore(&ieee->lock, flags);
ieee->beinretry = false;
exit:
up(&ieee->wx_sem);
}
struct sk_buff *rtllib_get_beacon_(struct rtllib_device *ieee)
{
u8 broadcast_addr[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
struct sk_buff *skb;
struct rtllib_probe_response *b;
skb = rtllib_probe_resp(ieee, broadcast_addr);
if (!skb)
return NULL;
b = (struct rtllib_probe_response *) skb->data;
b->header.frame_ctl = cpu_to_le16(RTLLIB_STYPE_BEACON);
return skb;
}
struct sk_buff *rtllib_get_beacon(struct rtllib_device *ieee)
{
struct sk_buff *skb;
struct rtllib_probe_response *b;
skb = rtllib_get_beacon_(ieee);
if (!skb)
return NULL;
b = (struct rtllib_probe_response *) skb->data;
b->header.seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
return skb;
}
EXPORT_SYMBOL(rtllib_get_beacon);
void rtllib_softmac_stop_protocol(struct rtllib_device *ieee, u8 mesh_flag,
u8 shutdown)
{
rtllib_stop_scan_syncro(ieee);
down(&ieee->wx_sem);
rtllib_stop_protocol(ieee, shutdown);
up(&ieee->wx_sem);
}
EXPORT_SYMBOL(rtllib_softmac_stop_protocol);
void rtllib_stop_protocol(struct rtllib_device *ieee, u8 shutdown)
{
if (!ieee->proto_started)
return;
if (shutdown) {
ieee->proto_started = 0;
ieee->proto_stoppping = 1;
if (ieee->rtllib_ips_leave != NULL)
ieee->rtllib_ips_leave(ieee->dev);
}
rtllib_stop_send_beacons(ieee);
del_timer_sync(&ieee->associate_timer);
cancel_delayed_work(&ieee->associate_retry_wq);
cancel_delayed_work(&ieee->start_ibss_wq);
cancel_delayed_work(&ieee->link_change_wq);
rtllib_stop_scan(ieee);
if (ieee->state <= RTLLIB_ASSOCIATING_AUTHENTICATED)
ieee->state = RTLLIB_NOLINK;
if (ieee->state == RTLLIB_LINKED) {
if (ieee->iw_mode == IW_MODE_INFRA)
SendDisassociation(ieee, 1, deauth_lv_ss);
rtllib_disassociate(ieee);
}
if (shutdown) {
RemoveAllTS(ieee);
ieee->proto_stoppping = 0;
}
kfree(ieee->assocreq_ies);
ieee->assocreq_ies = NULL;
ieee->assocreq_ies_len = 0;
kfree(ieee->assocresp_ies);
ieee->assocresp_ies = NULL;
ieee->assocresp_ies_len = 0;
}
void rtllib_softmac_start_protocol(struct rtllib_device *ieee, u8 mesh_flag)
{
down(&ieee->wx_sem);
rtllib_start_protocol(ieee);
up(&ieee->wx_sem);
}
EXPORT_SYMBOL(rtllib_softmac_start_protocol);
void rtllib_start_protocol(struct rtllib_device *ieee)
{
short ch = 0;
int i = 0;
rtllib_update_active_chan_map(ieee);
if (ieee->proto_started)
return;
ieee->proto_started = 1;
if (ieee->current_network.channel == 0) {
do {
ch++;
if (ch > MAX_CHANNEL_NUMBER)
return; /* no channel found */
} while (!ieee->active_channel_map[ch]);
ieee->current_network.channel = ch;
}
if (ieee->current_network.beacon_interval == 0)
ieee->current_network.beacon_interval = 100;
for (i = 0; i < 17; i++) {
ieee->last_rxseq_num[i] = -1;
ieee->last_rxfrag_num[i] = -1;
ieee->last_packet_time[i] = 0;
}
if (ieee->UpdateBeaconInterruptHandler)
ieee->UpdateBeaconInterruptHandler(ieee->dev, false);
ieee->wmm_acm = 0;
/* if the user set the MAC of the ad-hoc cell and then
* switch to managed mode, shall we make sure that association
* attempts does not fail just because the user provide the essid
* and the nic is still checking for the AP MAC ??
*/
if (ieee->iw_mode == IW_MODE_INFRA) {
rtllib_start_bss(ieee);
} else if (ieee->iw_mode == IW_MODE_ADHOC) {
if (ieee->UpdateBeaconInterruptHandler)
ieee->UpdateBeaconInterruptHandler(ieee->dev, true);
rtllib_start_ibss(ieee);
} else if (ieee->iw_mode == IW_MODE_MASTER) {
rtllib_start_master_bss(ieee);
} else if (ieee->iw_mode == IW_MODE_MONITOR) {
rtllib_start_monitor_mode(ieee);
}
}
void rtllib_softmac_init(struct rtllib_device *ieee)
{
int i;
memset(&ieee->current_network, 0, sizeof(struct rtllib_network));
ieee->state = RTLLIB_NOLINK;
for (i = 0; i < 5; i++)
ieee->seq_ctrl[i] = 0;
ieee->pDot11dInfo = kzalloc(sizeof(struct rt_dot11d_info), GFP_ATOMIC);
if (!ieee->pDot11dInfo)
RTLLIB_DEBUG(RTLLIB_DL_ERR, "can't alloc memory for DOT11D\n");
ieee->LinkDetectInfo.SlotIndex = 0;
ieee->LinkDetectInfo.SlotNum = 2;
ieee->LinkDetectInfo.NumRecvBcnInPeriod = 0;
ieee->LinkDetectInfo.NumRecvDataInPeriod = 0;
ieee->LinkDetectInfo.NumTxOkInPeriod = 0;
ieee->LinkDetectInfo.NumRxOkInPeriod = 0;
ieee->LinkDetectInfo.NumRxUnicastOkInPeriod = 0;
ieee->bIsAggregateFrame = false;
ieee->assoc_id = 0;
ieee->queue_stop = 0;
ieee->scanning_continue = 0;
ieee->softmac_features = 0;
ieee->wap_set = 0;
ieee->ssid_set = 0;
ieee->proto_started = 0;
ieee->proto_stoppping = 0;
ieee->basic_rate = RTLLIB_DEFAULT_BASIC_RATE;
ieee->rate = 22;
ieee->ps = RTLLIB_PS_DISABLED;
ieee->sta_sleep = LPS_IS_WAKE;
ieee->Regdot11HTOperationalRateSet[0] = 0xff;
ieee->Regdot11HTOperationalRateSet[1] = 0xff;
ieee->Regdot11HTOperationalRateSet[4] = 0x01;
ieee->Regdot11TxHTOperationalRateSet[0] = 0xff;
ieee->Regdot11TxHTOperationalRateSet[1] = 0xff;
ieee->Regdot11TxHTOperationalRateSet[4] = 0x01;
ieee->FirstIe_InScan = false;
ieee->actscanning = false;
ieee->beinretry = false;
ieee->is_set_key = false;
init_mgmt_queue(ieee);
ieee->sta_edca_param[0] = 0x0000A403;
ieee->sta_edca_param[1] = 0x0000A427;
ieee->sta_edca_param[2] = 0x005E4342;
ieee->sta_edca_param[3] = 0x002F3262;
ieee->aggregation = true;
ieee->enable_rx_imm_BA = 1;
ieee->tx_pending.txb = NULL;
_setup_timer(&ieee->associate_timer,
rtllib_associate_abort_cb,
(unsigned long) ieee);
_setup_timer(&ieee->beacon_timer,
rtllib_send_beacon_cb,
(unsigned long) ieee);
ieee->wq = create_workqueue(DRV_NAME);
INIT_DELAYED_WORK_RSL(&ieee->link_change_wq,
(void *)rtllib_link_change_wq, ieee);
INIT_DELAYED_WORK_RSL(&ieee->start_ibss_wq,
(void *)rtllib_start_ibss_wq, ieee);
INIT_WORK_RSL(&ieee->associate_complete_wq,
(void *)rtllib_associate_complete_wq, ieee);
INIT_DELAYED_WORK_RSL(&ieee->associate_procedure_wq,
(void *)rtllib_associate_procedure_wq, ieee);
INIT_DELAYED_WORK_RSL(&ieee->softmac_scan_wq,
(void *)rtllib_softmac_scan_wq, ieee);
INIT_DELAYED_WORK_RSL(&ieee->softmac_hint11d_wq,
(void *)rtllib_softmac_hint11d_wq, ieee);
INIT_DELAYED_WORK_RSL(&ieee->associate_retry_wq,
(void *)rtllib_associate_retry_wq, ieee);
INIT_WORK_RSL(&ieee->wx_sync_scan_wq, (void *)rtllib_wx_sync_scan_wq,
ieee);
sema_init(&ieee->wx_sem, 1);
sema_init(&ieee->scan_sem, 1);
sema_init(&ieee->ips_sem, 1);
spin_lock_init(&ieee->mgmt_tx_lock);
spin_lock_init(&ieee->beacon_lock);
tasklet_init(&ieee->ps_task,
(void(*)(unsigned long)) rtllib_sta_ps,
(unsigned long)ieee);
}
void rtllib_softmac_free(struct rtllib_device *ieee)
{
down(&ieee->wx_sem);
kfree(ieee->pDot11dInfo);
ieee->pDot11dInfo = NULL;
del_timer_sync(&ieee->associate_timer);
cancel_delayed_work(&ieee->associate_retry_wq);
destroy_workqueue(ieee->wq);
up(&ieee->wx_sem);
}
/********************************************************
* Start of WPA code. *
* this is stolen from the ipw2200 driver *
********************************************************/
static int rtllib_wpa_enable(struct rtllib_device *ieee, int value)
{
/* This is called when wpa_supplicant loads and closes the driver
* interface. */
printk(KERN_INFO "%s WPA\n", value ? "enabling" : "disabling");
ieee->wpa_enabled = value;
memset(ieee->ap_mac_addr, 0, 6);
return 0;
}
static void rtllib_wpa_assoc_frame(struct rtllib_device *ieee, char *wpa_ie,
int wpa_ie_len)
{
/* make sure WPA is enabled */
rtllib_wpa_enable(ieee, 1);
rtllib_disassociate(ieee);
}
static int rtllib_wpa_mlme(struct rtllib_device *ieee, int command, int reason)
{
int ret = 0;
switch (command) {
case IEEE_MLME_STA_DEAUTH:
break;
case IEEE_MLME_STA_DISASSOC:
rtllib_disassociate(ieee);
break;
default:
printk(KERN_INFO "Unknown MLME request: %d\n", command);
ret = -EOPNOTSUPP;
}
return ret;
}
static int rtllib_wpa_set_wpa_ie(struct rtllib_device *ieee,
struct ieee_param *param, int plen)
{
u8 *buf;
if (param->u.wpa_ie.len > MAX_WPA_IE_LEN ||
(param->u.wpa_ie.len && param->u.wpa_ie.data == NULL))
return -EINVAL;
if (param->u.wpa_ie.len) {
buf = kmemdup(param->u.wpa_ie.data, param->u.wpa_ie.len,
GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
kfree(ieee->wpa_ie);
ieee->wpa_ie = buf;
ieee->wpa_ie_len = param->u.wpa_ie.len;
} else {
kfree(ieee->wpa_ie);
ieee->wpa_ie = NULL;
ieee->wpa_ie_len = 0;
}
rtllib_wpa_assoc_frame(ieee, ieee->wpa_ie, ieee->wpa_ie_len);
return 0;
}
#define AUTH_ALG_OPEN_SYSTEM 0x1
#define AUTH_ALG_SHARED_KEY 0x2
#define AUTH_ALG_LEAP 0x4
static int rtllib_wpa_set_auth_algs(struct rtllib_device *ieee, int value)
{
struct rtllib_security sec = {
.flags = SEC_AUTH_MODE,
};
int ret = 0;
if (value & AUTH_ALG_SHARED_KEY) {
sec.auth_mode = WLAN_AUTH_SHARED_KEY;
ieee->open_wep = 0;
ieee->auth_mode = 1;
} else if (value & AUTH_ALG_OPEN_SYSTEM) {
sec.auth_mode = WLAN_AUTH_OPEN;
ieee->open_wep = 1;
ieee->auth_mode = 0;
} else if (value & AUTH_ALG_LEAP) {
sec.auth_mode = WLAN_AUTH_LEAP >> 6;
ieee->open_wep = 1;
ieee->auth_mode = 2;
}
if (ieee->set_security)
ieee->set_security(ieee->dev, &sec);
return ret;
}
static int rtllib_wpa_set_param(struct rtllib_device *ieee, u8 name, u32 value)
{
int ret = 0;
unsigned long flags;
switch (name) {
case IEEE_PARAM_WPA_ENABLED:
ret = rtllib_wpa_enable(ieee, value);
break;
case IEEE_PARAM_TKIP_COUNTERMEASURES:
ieee->tkip_countermeasures = value;
break;
case IEEE_PARAM_DROP_UNENCRYPTED:
{
/* HACK:
*
* wpa_supplicant calls set_wpa_enabled when the driver
* is loaded and unloaded, regardless of if WPA is being
* used. No other calls are made which can be used to
* determine if encryption will be used or not prior to
* association being expected. If encryption is not being
* used, drop_unencrypted is set to false, else true -- we
* can use this to determine if the CAP_PRIVACY_ON bit should
* be set.
*/
struct rtllib_security sec = {
.flags = SEC_ENABLED,
.enabled = value,
};
ieee->drop_unencrypted = value;
/* We only change SEC_LEVEL for open mode. Others
* are set by ipw_wpa_set_encryption.
*/
if (!value) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_0;
} else {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_1;
}
if (ieee->set_security)
ieee->set_security(ieee->dev, &sec);
break;
}
case IEEE_PARAM_PRIVACY_INVOKED:
ieee->privacy_invoked = value;
break;
case IEEE_PARAM_AUTH_ALGS:
ret = rtllib_wpa_set_auth_algs(ieee, value);
break;
case IEEE_PARAM_IEEE_802_1X:
ieee->ieee802_1x = value;
break;
case IEEE_PARAM_WPAX_SELECT:
spin_lock_irqsave(&ieee->wpax_suitlist_lock, flags);
spin_unlock_irqrestore(&ieee->wpax_suitlist_lock, flags);
break;
default:
printk(KERN_INFO "Unknown WPA param: %d\n", name);
ret = -EOPNOTSUPP;
}
return ret;
}
/* implementation borrowed from hostap driver */
static int rtllib_wpa_set_encryption(struct rtllib_device *ieee,
struct ieee_param *param, int param_len,
u8 is_mesh)
{
int ret = 0;
struct lib80211_crypto_ops *ops;
struct lib80211_crypt_data **crypt;
struct rtllib_security sec = {
.flags = 0,
};
param->u.crypt.err = 0;
param->u.crypt.alg[IEEE_CRYPT_ALG_NAME_LEN - 1] = '\0';
if (param_len !=
(int) ((char *) param->u.crypt.key - (char *) param) +
param->u.crypt.key_len) {
printk(KERN_INFO "Len mismatch %d, %d\n", param_len,
param->u.crypt.key_len);
return -EINVAL;
}
if (param->sta_addr[0] == 0xff && param->sta_addr[1] == 0xff &&
param->sta_addr[2] == 0xff && param->sta_addr[3] == 0xff &&
param->sta_addr[4] == 0xff && param->sta_addr[5] == 0xff) {
if (param->u.crypt.idx >= NUM_WEP_KEYS)
return -EINVAL;
crypt = &ieee->crypt_info.crypt[param->u.crypt.idx];
} else {
return -EINVAL;
}
if (strcmp(param->u.crypt.alg, "none") == 0) {
if (crypt) {
sec.enabled = 0;
sec.level = SEC_LEVEL_0;
sec.flags |= SEC_ENABLED | SEC_LEVEL;
lib80211_crypt_delayed_deinit(&ieee->crypt_info, crypt);
}
goto done;
}
sec.enabled = 1;
sec.flags |= SEC_ENABLED;
/* IPW HW cannot build TKIP MIC, host decryption still needed. */
if (!(ieee->host_encrypt || ieee->host_decrypt) &&
strcmp(param->u.crypt.alg, "R-TKIP"))
goto skip_host_crypt;
ops = lib80211_get_crypto_ops(param->u.crypt.alg);
if (ops == NULL && strcmp(param->u.crypt.alg, "R-WEP") == 0) {
request_module("rtllib_crypt_wep");
ops = lib80211_get_crypto_ops(param->u.crypt.alg);
} else if (ops == NULL && strcmp(param->u.crypt.alg, "R-TKIP") == 0) {
request_module("rtllib_crypt_tkip");
ops = lib80211_get_crypto_ops(param->u.crypt.alg);
} else if (ops == NULL && strcmp(param->u.crypt.alg, "R-CCMP") == 0) {
request_module("rtllib_crypt_ccmp");
ops = lib80211_get_crypto_ops(param->u.crypt.alg);
}
if (ops == NULL) {
printk(KERN_INFO "unknown crypto alg '%s'\n",
param->u.crypt.alg);
param->u.crypt.err = IEEE_CRYPT_ERR_UNKNOWN_ALG;
ret = -EINVAL;
goto done;
}
if (*crypt == NULL || (*crypt)->ops != ops) {
struct lib80211_crypt_data *new_crypt;
lib80211_crypt_delayed_deinit(&ieee->crypt_info, crypt);
new_crypt = (struct lib80211_crypt_data *)
kmalloc(sizeof(*new_crypt), GFP_KERNEL);
if (new_crypt == NULL) {
ret = -ENOMEM;
goto done;
}
memset(new_crypt, 0, sizeof(struct lib80211_crypt_data));
new_crypt->ops = ops;
if (new_crypt->ops)
new_crypt->priv =
new_crypt->ops->init(param->u.crypt.idx);
if (new_crypt->priv == NULL) {
kfree(new_crypt);
param->u.crypt.err = IEEE_CRYPT_ERR_CRYPT_INIT_FAILED;
ret = -EINVAL;
goto done;
}
*crypt = new_crypt;
}
if (param->u.crypt.key_len > 0 && (*crypt)->ops->set_key &&
(*crypt)->ops->set_key(param->u.crypt.key,
param->u.crypt.key_len, param->u.crypt.seq,
(*crypt)->priv) < 0) {
printk(KERN_INFO "key setting failed\n");
param->u.crypt.err = IEEE_CRYPT_ERR_KEY_SET_FAILED;
ret = -EINVAL;
goto done;
}
skip_host_crypt:
if (param->u.crypt.set_tx) {
ieee->crypt_info.tx_keyidx = param->u.crypt.idx;
sec.active_key = param->u.crypt.idx;
sec.flags |= SEC_ACTIVE_KEY;
} else
sec.flags &= ~SEC_ACTIVE_KEY;
if (param->u.crypt.alg != NULL) {
memcpy(sec.keys[param->u.crypt.idx],
param->u.crypt.key,
param->u.crypt.key_len);
sec.key_sizes[param->u.crypt.idx] = param->u.crypt.key_len;
sec.flags |= (1 << param->u.crypt.idx);
if (strcmp(param->u.crypt.alg, "R-WEP") == 0) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_1;
} else if (strcmp(param->u.crypt.alg, "R-TKIP") == 0) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_2;
} else if (strcmp(param->u.crypt.alg, "R-CCMP") == 0) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_3;
}
}
done:
if (ieee->set_security)
ieee->set_security(ieee->dev, &sec);
/* Do not reset port if card is in Managed mode since resetting will
* generate new IEEE 802.11 authentication which may end up in looping
* with IEEE 802.1X. If your hardware requires a reset after WEP
* configuration (for example... Prism2), implement the reset_port in
* the callbacks structures used to initialize the 802.11 stack. */
if (ieee->reset_on_keychange &&
ieee->iw_mode != IW_MODE_INFRA &&
ieee->reset_port &&
ieee->reset_port(ieee->dev)) {
printk(KERN_INFO "reset_port failed\n");
param->u.crypt.err = IEEE_CRYPT_ERR_CARD_CONF_FAILED;
return -EINVAL;
}
return ret;
}
inline struct sk_buff *rtllib_disauth_skb(struct rtllib_network *beacon,
struct rtllib_device *ieee, u16 asRsn)
{
struct sk_buff *skb;
struct rtllib_disauth *disauth;
int len = sizeof(struct rtllib_disauth) + ieee->tx_headroom;
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
disauth = (struct rtllib_disauth *) skb_put(skb,
sizeof(struct rtllib_disauth));
disauth->header.frame_ctl = cpu_to_le16(RTLLIB_STYPE_DEAUTH);
disauth->header.duration_id = 0;
memcpy(disauth->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(disauth->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(disauth->header.addr3, beacon->bssid, ETH_ALEN);
disauth->reason = cpu_to_le16(asRsn);
return skb;
}
inline struct sk_buff *rtllib_disassociate_skb(struct rtllib_network *beacon,
struct rtllib_device *ieee, u16 asRsn)
{
struct sk_buff *skb;
struct rtllib_disassoc *disass;
int len = sizeof(struct rtllib_disassoc) + ieee->tx_headroom;
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
disass = (struct rtllib_disassoc *) skb_put(skb,
sizeof(struct rtllib_disassoc));
disass->header.frame_ctl = cpu_to_le16(RTLLIB_STYPE_DISASSOC);
disass->header.duration_id = 0;
memcpy(disass->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(disass->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(disass->header.addr3, beacon->bssid, ETH_ALEN);
disass->reason = cpu_to_le16(asRsn);
return skb;
}
void SendDisassociation(struct rtllib_device *ieee, bool deauth, u16 asRsn)
{
struct rtllib_network *beacon = &ieee->current_network;
struct sk_buff *skb;
if (deauth)
skb = rtllib_disauth_skb(beacon, ieee, asRsn);
else
skb = rtllib_disassociate_skb(beacon, ieee, asRsn);
if (skb)
softmac_mgmt_xmit(skb, ieee);
}
u8 rtllib_ap_sec_type(struct rtllib_device *ieee)
{
static u8 ccmp_ie[4] = {0x00, 0x50, 0xf2, 0x04};
static u8 ccmp_rsn_ie[4] = {0x00, 0x0f, 0xac, 0x04};
int wpa_ie_len = ieee->wpa_ie_len;
struct lib80211_crypt_data *crypt;
int encrypt;
crypt = ieee->crypt_info.crypt[ieee->crypt_info.tx_keyidx];
encrypt = (ieee->current_network.capability & WLAN_CAPABILITY_PRIVACY)
|| (ieee->host_encrypt && crypt && crypt->ops &&
(0 == strcmp(crypt->ops->name, "R-WEP")));
/* simply judge */
if (encrypt && (wpa_ie_len == 0)) {
return SEC_ALG_WEP;
} else if ((wpa_ie_len != 0)) {
if (((ieee->wpa_ie[0] == 0xdd) &&
(!memcmp(&(ieee->wpa_ie[14]), ccmp_ie, 4))) ||
((ieee->wpa_ie[0] == 0x30) &&
(!memcmp(&ieee->wpa_ie[10], ccmp_rsn_ie, 4))))
return SEC_ALG_CCMP;
else
return SEC_ALG_TKIP;
} else {
return SEC_ALG_NONE;
}
}
int rtllib_wpa_supplicant_ioctl(struct rtllib_device *ieee, struct iw_point *p,
u8 is_mesh)
{
struct ieee_param *param;
int ret = 0;
down(&ieee->wx_sem);
if (p->length < sizeof(struct ieee_param) || !p->pointer) {
ret = -EINVAL;
goto out;
}
param = kmalloc(p->length, GFP_KERNEL);
if (param == NULL) {
ret = -ENOMEM;
goto out;
}
if (copy_from_user(param, p->pointer, p->length)) {
kfree(param);
ret = -EFAULT;
goto out;
}
switch (param->cmd) {
case IEEE_CMD_SET_WPA_PARAM:
ret = rtllib_wpa_set_param(ieee, param->u.wpa_param.name,
param->u.wpa_param.value);
break;
case IEEE_CMD_SET_WPA_IE:
ret = rtllib_wpa_set_wpa_ie(ieee, param, p->length);
break;
case IEEE_CMD_SET_ENCRYPTION:
ret = rtllib_wpa_set_encryption(ieee, param, p->length, 0);
break;
case IEEE_CMD_MLME:
ret = rtllib_wpa_mlme(ieee, param->u.mlme.command,
param->u.mlme.reason_code);
break;
default:
printk(KERN_INFO "Unknown WPA supplicant request: %d\n",
param->cmd);
ret = -EOPNOTSUPP;
break;
}
if (ret == 0 && copy_to_user(p->pointer, param, p->length))
ret = -EFAULT;
kfree(param);
out:
up(&ieee->wx_sem);
return ret;
}
EXPORT_SYMBOL(rtllib_wpa_supplicant_ioctl);
void rtllib_MgntDisconnectIBSS(struct rtllib_device *rtllib)
{
u8 OpMode;
u8 i;
bool bFilterOutNonAssociatedBSSID = false;
rtllib->state = RTLLIB_NOLINK;
for (i = 0; i < 6; i++)
rtllib->current_network.bssid[i] = 0x55;
rtllib->OpMode = RT_OP_MODE_NO_LINK;
rtllib->SetHwRegHandler(rtllib->dev, HW_VAR_BSSID,
rtllib->current_network.bssid);
OpMode = RT_OP_MODE_NO_LINK;
rtllib->SetHwRegHandler(rtllib->dev, HW_VAR_MEDIA_STATUS, &OpMode);
rtllib_stop_send_beacons(rtllib);
bFilterOutNonAssociatedBSSID = false;
rtllib->SetHwRegHandler(rtllib->dev, HW_VAR_CECHK_BSSID,
(u8 *)(&bFilterOutNonAssociatedBSSID));
notify_wx_assoc_event(rtllib);
}
void rtllib_MlmeDisassociateRequest(struct rtllib_device *rtllib, u8 *asSta,
u8 asRsn)
{
u8 i;
u8 OpMode;
RemovePeerTS(rtllib, asSta);
if (memcpy(rtllib->current_network.bssid, asSta, 6) == NULL) {
rtllib->state = RTLLIB_NOLINK;
for (i = 0; i < 6; i++)
rtllib->current_network.bssid[i] = 0x22;
OpMode = RT_OP_MODE_NO_LINK;
rtllib->OpMode = RT_OP_MODE_NO_LINK;
rtllib->SetHwRegHandler(rtllib->dev, HW_VAR_MEDIA_STATUS,
(u8 *)(&OpMode));
rtllib_disassociate(rtllib);
rtllib->SetHwRegHandler(rtllib->dev, HW_VAR_BSSID,
rtllib->current_network.bssid);
}
}
void
rtllib_MgntDisconnectAP(
struct rtllib_device *rtllib,
u8 asRsn
)
{
bool bFilterOutNonAssociatedBSSID = false;
bFilterOutNonAssociatedBSSID = false;
rtllib->SetHwRegHandler(rtllib->dev, HW_VAR_CECHK_BSSID,
(u8 *)(&bFilterOutNonAssociatedBSSID));
rtllib_MlmeDisassociateRequest(rtllib, rtllib->current_network.bssid,
asRsn);
rtllib->state = RTLLIB_NOLINK;
}
bool rtllib_MgntDisconnect(struct rtllib_device *rtllib, u8 asRsn)
{
if (rtllib->ps != RTLLIB_PS_DISABLED)
rtllib->sta_wake_up(rtllib->dev);
if (rtllib->state == RTLLIB_LINKED) {
if (rtllib->iw_mode == IW_MODE_ADHOC)
rtllib_MgntDisconnectIBSS(rtllib);
if (rtllib->iw_mode == IW_MODE_INFRA)
rtllib_MgntDisconnectAP(rtllib, asRsn);
}
return true;
}
EXPORT_SYMBOL(rtllib_MgntDisconnect);
void notify_wx_assoc_event(struct rtllib_device *ieee)
{
union iwreq_data wrqu;
if (ieee->cannot_notify)
return;
wrqu.ap_addr.sa_family = ARPHRD_ETHER;
if (ieee->state == RTLLIB_LINKED)
memcpy(wrqu.ap_addr.sa_data, ieee->current_network.bssid,
ETH_ALEN);
else {
printk(KERN_INFO "%s(): Tell user space disconnected\n",
__func__);
memset(wrqu.ap_addr.sa_data, 0, ETH_ALEN);
}
wireless_send_event(ieee->dev, SIOCGIWAP, &wrqu, NULL);
}
EXPORT_SYMBOL(notify_wx_assoc_event);
| gpl-2.0 |
steppnasty/htc-kernel-msm7x30 | drivers/usb/serial/hp4x.c | 4811 | 1566 | /*
* HP4x Calculators Serial USB driver
*
* Copyright (C) 2005 Arthur Huillet (ahuillet@users.sf.net)
* Copyright (C) 2001-2005 Greg Kroah-Hartman (greg@kroah.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.
*
* See Documentation/usb/usb-serial.txt for more information on using this
* driver
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/tty.h>
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
/*
* Version Information
*/
#define DRIVER_VERSION "v1.00"
#define DRIVER_DESC "HP4x (48/49) Generic Serial driver"
#define HP_VENDOR_ID 0x03f0
#define HP49GP_PRODUCT_ID 0x0121
static const struct usb_device_id id_table[] = {
{ USB_DEVICE(HP_VENDOR_ID, HP49GP_PRODUCT_ID) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, id_table);
static struct usb_driver hp49gp_driver = {
.name = "hp4X",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = id_table,
};
static struct usb_serial_driver hp49gp_device = {
.driver = {
.owner = THIS_MODULE,
.name = "hp4X",
},
.id_table = id_table,
.num_ports = 1,
};
static struct usb_serial_driver * const serial_drivers[] = {
&hp49gp_device, NULL
};
module_usb_serial_driver(hp49gp_driver, serial_drivers);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_VERSION(DRIVER_VERSION);
MODULE_LICENSE("GPL");
| gpl-2.0 |
acuicultor/android_kernel_oneplus_msm8974 | drivers/media/video/et61x251/et61x251_tas5130d1b.c | 5067 | 4103 | /***************************************************************************
* Plug-in for TAS5130D1B image sensor connected to the ET61X[12]51 *
* PC Camera Controllers *
* *
* Copyright (C) 2006-2007 by Luca Risolia <luca.risolia@studio.unibo.it> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
***************************************************************************/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include "et61x251_sensor.h"
static int tas5130d1b_init(struct et61x251_device* cam)
{
int err = 0;
err += et61x251_write_reg(cam, 0x14, 0x01);
err += et61x251_write_reg(cam, 0x1b, 0x02);
err += et61x251_write_reg(cam, 0x02, 0x12);
err += et61x251_write_reg(cam, 0x0e, 0x60);
err += et61x251_write_reg(cam, 0x80, 0x61);
err += et61x251_write_reg(cam, 0xf0, 0x62);
err += et61x251_write_reg(cam, 0x03, 0x63);
err += et61x251_write_reg(cam, 0x14, 0x64);
err += et61x251_write_reg(cam, 0xf4, 0x65);
err += et61x251_write_reg(cam, 0x01, 0x66);
err += et61x251_write_reg(cam, 0x05, 0x67);
err += et61x251_write_reg(cam, 0x8f, 0x68);
err += et61x251_write_reg(cam, 0x0f, 0x8d);
err += et61x251_write_reg(cam, 0x08, 0x8e);
return err;
}
static int tas5130d1b_set_ctrl(struct et61x251_device* cam,
const struct v4l2_control* ctrl)
{
int err = 0;
switch (ctrl->id) {
case V4L2_CID_GAIN:
err += et61x251_i2c_raw_write(cam, 2, 0x20,
0xf6-ctrl->value, 0, 0, 0,
0, 0, 0, 0);
break;
case V4L2_CID_EXPOSURE:
err += et61x251_i2c_raw_write(cam, 2, 0x40,
0x47-ctrl->value, 0, 0, 0,
0, 0, 0, 0);
break;
default:
return -EINVAL;
}
return err ? -EIO : 0;
}
static const struct et61x251_sensor tas5130d1b = {
.name = "TAS5130D1B",
.interface = ET61X251_I2C_3WIRES,
.rsta = ET61X251_I2C_RSTA_STOP,
.active_pixel = {
.left = 106,
.top = 13,
},
.init = &tas5130d1b_init,
.qctrl = {
{
.id = V4L2_CID_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "global gain",
.minimum = 0x00,
.maximum = 0xf6,
.step = 0x02,
.default_value = 0x0d,
.flags = 0,
},
{
.id = V4L2_CID_EXPOSURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "exposure",
.minimum = 0x00,
.maximum = 0x47,
.step = 0x01,
.default_value = 0x23,
.flags = 0,
},
},
.set_ctrl = &tas5130d1b_set_ctrl,
.cropcap = {
.bounds = {
.left = 0,
.top = 0,
.width = 640,
.height = 480,
},
.defrect = {
.left = 0,
.top = 0,
.width = 640,
.height = 480,
},
},
.pix_format = {
.width = 640,
.height = 480,
.pixelformat = V4L2_PIX_FMT_SBGGR8,
.priv = 8,
},
};
int et61x251_probe_tas5130d1b(struct et61x251_device* cam)
{
const struct usb_device_id tas5130d1b_id_table[] = {
{ USB_DEVICE(0x102c, 0x6251), },
{ }
};
/* Sensor detection is based on USB pid/vid */
if (!et61x251_match_id(cam, tas5130d1b_id_table))
return -ENODEV;
et61x251_attach_sensor(cam, &tas5130d1b);
return 0;
}
| gpl-2.0 |
major91/Zeta_Chromium-L_old | arch/powerpc/sysdev/bestcomm/ata.c | 9419 | 4208 | /*
* Bestcomm ATA task driver
*
*
* Patterned after bestcomm/fec.c by Dale Farnsworth <dfarnsworth@mvista.com>
* 2003-2004 (c) MontaVista, Software, Inc.
*
* Copyright (C) 2006-2007 Sylvain Munaut <tnt@246tNt.com>
* Copyright (C) 2006 Freescale - John Rigby
*
* This file is licensed under the terms of the GNU General Public License
* version 2. This program is licensed "as is" without any warranty of any
* kind, whether express or implied.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <asm/io.h>
#include "bestcomm.h"
#include "bestcomm_priv.h"
#include "ata.h"
/* ======================================================================== */
/* Task image/var/inc */
/* ======================================================================== */
/* ata task image */
extern u32 bcom_ata_task[];
/* ata task vars that need to be set before enabling the task */
struct bcom_ata_var {
u32 enable; /* (u16*) address of task's control register */
u32 bd_base; /* (struct bcom_bd*) beginning of ring buffer */
u32 bd_last; /* (struct bcom_bd*) end of ring buffer */
u32 bd_start; /* (struct bcom_bd*) current bd */
u32 buffer_size; /* size of receive buffer */
};
/* ata task incs that need to be set before enabling the task */
struct bcom_ata_inc {
u16 pad0;
s16 incr_bytes;
u16 pad1;
s16 incr_dst;
u16 pad2;
s16 incr_src;
};
/* ======================================================================== */
/* Task support code */
/* ======================================================================== */
struct bcom_task *
bcom_ata_init(int queue_len, int maxbufsize)
{
struct bcom_task *tsk;
struct bcom_ata_var *var;
struct bcom_ata_inc *inc;
/* Prefetch breaks ATA DMA. Turn it off for ATA DMA */
bcom_disable_prefetch();
tsk = bcom_task_alloc(queue_len, sizeof(struct bcom_ata_bd), 0);
if (!tsk)
return NULL;
tsk->flags = BCOM_FLAGS_NONE;
bcom_ata_reset_bd(tsk);
var = (struct bcom_ata_var *) bcom_task_var(tsk->tasknum);
inc = (struct bcom_ata_inc *) bcom_task_inc(tsk->tasknum);
if (bcom_load_image(tsk->tasknum, bcom_ata_task)) {
bcom_task_free(tsk);
return NULL;
}
var->enable = bcom_eng->regs_base +
offsetof(struct mpc52xx_sdma, tcr[tsk->tasknum]);
var->bd_base = tsk->bd_pa;
var->bd_last = tsk->bd_pa + ((tsk->num_bd-1) * tsk->bd_size);
var->bd_start = tsk->bd_pa;
var->buffer_size = maxbufsize;
/* Configure some stuff */
bcom_set_task_pragma(tsk->tasknum, BCOM_ATA_PRAGMA);
bcom_set_task_auto_start(tsk->tasknum, tsk->tasknum);
out_8(&bcom_eng->regs->ipr[BCOM_INITIATOR_ATA_RX], BCOM_IPR_ATA_RX);
out_8(&bcom_eng->regs->ipr[BCOM_INITIATOR_ATA_TX], BCOM_IPR_ATA_TX);
out_be32(&bcom_eng->regs->IntPend, 1<<tsk->tasknum); /* Clear ints */
return tsk;
}
EXPORT_SYMBOL_GPL(bcom_ata_init);
void bcom_ata_rx_prepare(struct bcom_task *tsk)
{
struct bcom_ata_inc *inc;
inc = (struct bcom_ata_inc *) bcom_task_inc(tsk->tasknum);
inc->incr_bytes = -(s16)sizeof(u32);
inc->incr_src = 0;
inc->incr_dst = sizeof(u32);
bcom_set_initiator(tsk->tasknum, BCOM_INITIATOR_ATA_RX);
}
EXPORT_SYMBOL_GPL(bcom_ata_rx_prepare);
void bcom_ata_tx_prepare(struct bcom_task *tsk)
{
struct bcom_ata_inc *inc;
inc = (struct bcom_ata_inc *) bcom_task_inc(tsk->tasknum);
inc->incr_bytes = -(s16)sizeof(u32);
inc->incr_src = sizeof(u32);
inc->incr_dst = 0;
bcom_set_initiator(tsk->tasknum, BCOM_INITIATOR_ATA_TX);
}
EXPORT_SYMBOL_GPL(bcom_ata_tx_prepare);
void bcom_ata_reset_bd(struct bcom_task *tsk)
{
struct bcom_ata_var *var;
/* Reset all BD */
memset(tsk->bd, 0x00, tsk->num_bd * tsk->bd_size);
tsk->index = 0;
tsk->outdex = 0;
var = (struct bcom_ata_var *) bcom_task_var(tsk->tasknum);
var->bd_start = var->bd_base;
}
EXPORT_SYMBOL_GPL(bcom_ata_reset_bd);
void bcom_ata_release(struct bcom_task *tsk)
{
/* Nothing special for the ATA tasks */
bcom_task_free(tsk);
}
EXPORT_SYMBOL_GPL(bcom_ata_release);
MODULE_DESCRIPTION("BestComm ATA task driver");
MODULE_AUTHOR("John Rigby");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
dr87/G2-L-KERNEL | drivers/isdn/hardware/avm/b1pcmcia.c | 9675 | 5698 | /* $Id: b1pcmcia.c,v 1.1.2.2 2004/01/16 21:09:27 keil Exp $
*
* Module for AVM B1/M1/M2 PCMCIA-card.
*
* Copyright 1999 by Carsten Paeth <calle@calle.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/delay.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <asm/io.h>
#include <linux/capi.h>
#include <linux/b1pcmcia.h>
#include <linux/isdn/capicmd.h>
#include <linux/isdn/capiutil.h>
#include <linux/isdn/capilli.h>
#include "avmcard.h"
/* ------------------------------------------------------------- */
static char *revision = "$Revision: 1.1.2.2 $";
/* ------------------------------------------------------------- */
MODULE_DESCRIPTION("CAPI4Linux: Driver for AVM PCMCIA cards");
MODULE_AUTHOR("Carsten Paeth");
MODULE_LICENSE("GPL");
/* ------------------------------------------------------------- */
static void b1pcmcia_remove_ctr(struct capi_ctr *ctrl)
{
avmctrl_info *cinfo = (avmctrl_info *)(ctrl->driverdata);
avmcard *card = cinfo->card;
unsigned int port = card->port;
b1_reset(port);
b1_reset(port);
detach_capi_ctr(ctrl);
free_irq(card->irq, card);
b1_free_card(card);
}
/* ------------------------------------------------------------- */
static LIST_HEAD(cards);
static char *b1pcmcia_procinfo(struct capi_ctr *ctrl);
static int b1pcmcia_add_card(unsigned int port, unsigned irq,
enum avmcardtype cardtype)
{
avmctrl_info *cinfo;
avmcard *card;
char *cardname;
int retval;
card = b1_alloc_card(1);
if (!card) {
printk(KERN_WARNING "b1pcmcia: no memory.\n");
retval = -ENOMEM;
goto err;
}
cinfo = card->ctrlinfo;
switch (cardtype) {
case avm_m1: sprintf(card->name, "m1-%x", port); break;
case avm_m2: sprintf(card->name, "m2-%x", port); break;
default: sprintf(card->name, "b1pcmcia-%x", port); break;
}
card->port = port;
card->irq = irq;
card->cardtype = cardtype;
retval = request_irq(card->irq, b1_interrupt, IRQF_SHARED, card->name, card);
if (retval) {
printk(KERN_ERR "b1pcmcia: unable to get IRQ %d.\n",
card->irq);
retval = -EBUSY;
goto err_free;
}
b1_reset(card->port);
if ((retval = b1_detect(card->port, card->cardtype)) != 0) {
printk(KERN_NOTICE "b1pcmcia: NO card at 0x%x (%d)\n",
card->port, retval);
retval = -ENODEV;
goto err_free_irq;
}
b1_reset(card->port);
b1_getrevision(card);
cinfo->capi_ctrl.owner = THIS_MODULE;
cinfo->capi_ctrl.driver_name = "b1pcmcia";
cinfo->capi_ctrl.driverdata = cinfo;
cinfo->capi_ctrl.register_appl = b1_register_appl;
cinfo->capi_ctrl.release_appl = b1_release_appl;
cinfo->capi_ctrl.send_message = b1_send_message;
cinfo->capi_ctrl.load_firmware = b1_load_firmware;
cinfo->capi_ctrl.reset_ctr = b1_reset_ctr;
cinfo->capi_ctrl.procinfo = b1pcmcia_procinfo;
cinfo->capi_ctrl.proc_fops = &b1ctl_proc_fops;
strcpy(cinfo->capi_ctrl.name, card->name);
retval = attach_capi_ctr(&cinfo->capi_ctrl);
if (retval) {
printk(KERN_ERR "b1pcmcia: attach controller failed.\n");
goto err_free_irq;
}
switch (cardtype) {
case avm_m1: cardname = "M1"; break;
case avm_m2: cardname = "M2"; break;
default: cardname = "B1 PCMCIA"; break;
}
printk(KERN_INFO "b1pcmcia: AVM %s at i/o %#x, irq %d, revision %d\n",
cardname, card->port, card->irq, card->revision);
list_add(&card->list, &cards);
return cinfo->capi_ctrl.cnr;
err_free_irq:
free_irq(card->irq, card);
err_free:
b1_free_card(card);
err:
return retval;
}
/* ------------------------------------------------------------- */
static char *b1pcmcia_procinfo(struct capi_ctr *ctrl)
{
avmctrl_info *cinfo = (avmctrl_info *)(ctrl->driverdata);
if (!cinfo)
return "";
sprintf(cinfo->infobuf, "%s %s 0x%x %d r%d",
cinfo->cardname[0] ? cinfo->cardname : "-",
cinfo->version[VER_DRIVER] ? cinfo->version[VER_DRIVER] : "-",
cinfo->card ? cinfo->card->port : 0x0,
cinfo->card ? cinfo->card->irq : 0,
cinfo->card ? cinfo->card->revision : 0
);
return cinfo->infobuf;
}
/* ------------------------------------------------------------- */
int b1pcmcia_addcard_b1(unsigned int port, unsigned irq)
{
return b1pcmcia_add_card(port, irq, avm_b1pcmcia);
}
int b1pcmcia_addcard_m1(unsigned int port, unsigned irq)
{
return b1pcmcia_add_card(port, irq, avm_m1);
}
int b1pcmcia_addcard_m2(unsigned int port, unsigned irq)
{
return b1pcmcia_add_card(port, irq, avm_m2);
}
int b1pcmcia_delcard(unsigned int port, unsigned irq)
{
struct list_head *l;
avmcard *card;
list_for_each(l, &cards) {
card = list_entry(l, avmcard, list);
if (card->port == port && card->irq == irq) {
b1pcmcia_remove_ctr(&card->ctrlinfo[0].capi_ctrl);
return 0;
}
}
return -ESRCH;
}
EXPORT_SYMBOL(b1pcmcia_addcard_b1);
EXPORT_SYMBOL(b1pcmcia_addcard_m1);
EXPORT_SYMBOL(b1pcmcia_addcard_m2);
EXPORT_SYMBOL(b1pcmcia_delcard);
static struct capi_driver capi_driver_b1pcmcia = {
.name = "b1pcmcia",
.revision = "1.0",
};
static int __init b1pcmcia_init(void)
{
char *p;
char rev[32];
if ((p = strchr(revision, ':')) != NULL && p[1]) {
strlcpy(rev, p + 2, 32);
if ((p = strchr(rev, '$')) != NULL && p > rev)
*(p - 1) = 0;
} else
strcpy(rev, "1.0");
strlcpy(capi_driver_b1pcmcia.revision, rev, 32);
register_capi_driver(&capi_driver_b1pcmcia);
printk(KERN_INFO "b1pci: revision %s\n", rev);
return 0;
}
static void __exit b1pcmcia_exit(void)
{
unregister_capi_driver(&capi_driver_b1pcmcia);
}
module_init(b1pcmcia_init);
module_exit(b1pcmcia_exit);
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.